-
Notifications
You must be signed in to change notification settings - Fork 262
Expand file tree
/
Copy pathdev.ts
More file actions
525 lines (480 loc) · 17.8 KB
/
Copy pathdev.ts
File metadata and controls
525 lines (480 loc) · 17.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
import {
ApplicationURLs,
FrontendURLOptions,
generateApplicationURLs,
generateFrontendURL,
getURLs,
shouldOrPromptUpdateURLs,
startTunnelPlugin,
updateURLs,
} from './dev/urls.js'
import {
enableDeveloperPreview,
disableDeveloperPreview,
developerPreviewUpdate,
showReusedDevValues,
} from './context.js'
import {fetchAppPreviewMode} from './dev/fetch.js'
import {uploadStaticAssetsToGCS} from './static-assets.js'
import {installAppDependencies} from './dependencies.js'
import {DevConfig, DevProcesses, setupDevProcesses} from './dev/processes/setup-dev-processes.js'
import {frontAndBackendConfig} from './dev/processes/utils.js'
import {renderDev} from './dev/ui.js'
import {DeveloperPreviewController} from './dev/ui/components/Dev.js'
import {DevProcessFunction} from './dev/processes/types.js'
import {getCachedAppInfo, setCachedAppInfo} from './local-storage.js'
import {canEnablePreviewMode} from './extensions/common.js'
import {fetchAppRemoteConfiguration} from './app/select-app.js'
import {setAppConfigValue} from './app/patch-app-configuration-file.js'
import {DevSessionStatusManager} from './dev/processes/dev-session/dev-session-status-manager.js'
import {TunnelMode} from './dev/tunnel-mode.js'
import {PortDetail, renderPortWarnings} from './dev/port-warnings.js'
import {DeveloperPlatformClient} from '../utilities/developer-platform-client.js'
import {Web, isCurrentAppSchema, getAppScopesArray, AppLinkedInterface} from '../models/app/app.js'
import {Organization, OrganizationApp, OrganizationStore} from '../models/organization.js'
import {getAnalyticsTunnelType} from '../utilities/analytics.js'
import metadata from '../metadata.js'
import {AppConfigurationUsedByCli} from '../models/extensions/specifications/types/app_config.js'
import {RemoteAwareExtensionSpecification} from '../models/extensions/specification.js'
import {ports} from '../constants.js'
import {generateCertificate} from '../utilities/mkcert.js'
import {throwUidMappingError} from '../prompts/uid-mapping-error.js'
import {Config} from '@oclif/core'
import {AbortController} from '@shopify/cli-kit/node/abort'
import {checkPortAvailability, getAvailableTCPPort} from '@shopify/cli-kit/node/tcp'
import {TunnelClient} from '@shopify/cli-kit/node/plugins/tunnel'
import {getBackendPort} from '@shopify/cli-kit/node/environment'
import {basename} from '@shopify/cli-kit/node/path'
import {renderWarning} from '@shopify/cli-kit/node/ui'
import {reportAnalyticsEvent} from '@shopify/cli-kit/node/analytics'
import {OutputProcess, formatPackageManagerCommand} from '@shopify/cli-kit/node/output'
import {hashString} from '@shopify/cli-kit/node/crypto'
import {AbortError} from '@shopify/cli-kit/node/error'
export interface DevOptions {
app: AppLinkedInterface
remoteApp: OrganizationApp
organization: Organization
specifications: RemoteAwareExtensionSpecification[]
developerPlatformClient: DeveloperPlatformClient
store: OrganizationStore
directory: string
update: boolean
commandConfig: Config
skipDependenciesInstallation: boolean
subscriptionProductUrl?: string
checkoutCartUrl?: string
tunnel: TunnelMode
theme?: string
themeExtensionPort?: number
notify?: string
graphiqlPort?: number
graphiqlKey?: string
}
export async function dev(commandOptions: DevOptions) {
const config = await prepareForDev(commandOptions)
await actionsBeforeSettingUpDevProcesses(config)
const {processes, graphiqlUrl, previewUrl, devSessionStatusManager} = await setupDevProcesses(config)
await actionsBeforeLaunchingDevProcesses(config)
await launchDevProcesses({processes, previewUrl, graphiqlUrl, config, devSessionStatusManager})
}
async function prepareForDev(commandOptions: DevOptions): Promise<DevConfig> {
const {app, remoteApp, developerPlatformClient, store, specifications, tunnel} = commandOptions
// Be optimistic about tunnel creation and do it as early as possible
let tunnelClient: TunnelClient | undefined
if (tunnel.mode === 'auto') {
const tunnelPort = await getAvailableTCPPort()
tunnelClient = await startTunnelPlugin(commandOptions.commandConfig, tunnelPort, 'cloudflare')
}
const remoteConfiguration = await fetchAppRemoteConfiguration(
remoteApp,
developerPlatformClient,
specifications,
remoteApp.flags,
)
remoteApp.configuration = remoteConfiguration
showReusedDevValues({
app,
remoteApp,
selectedStore: store,
cachedInfo: getCachedAppInfo(commandOptions.directory),
organization: commandOptions.organization,
tunnelMode: tunnel.mode,
})
// If the dev_store_url is set in the app configuration, keep updating it.
// If not, `store-context.ts` will take care of caching it in the hidden config.
if (app.configuration.build?.dev_store_url) {
app.configuration.build = {
...app.configuration.build,
dev_store_url: store.shopDomain,
}
await setAppConfigValue(app.configuration.path, 'build.dev_store_url', store.shopDomain)
}
if (!commandOptions.skipDependenciesInstallation && !app.usesWorkspaces) {
await installAppDependencies(app)
}
const graphiqlPort = commandOptions.graphiqlPort ?? (await getAvailableTCPPort(ports.graphiql))
const portDetails: PortDetail[] = [
{
for: 'GraphiQL',
flagToRemedy: '--graphiql-port',
requested: commandOptions.graphiqlPort ?? ports.graphiql,
actual: graphiqlPort,
},
]
if (tunnel.mode === 'use-localhost') {
portDetails.push({
for: 'localhost',
flagToRemedy: '--localhost-port',
requested: tunnel.requestedPort,
actual: tunnel.actualPort,
})
}
renderPortWarnings(portDetails)
const {webs, ...network} = await setupNetworkingOptions(
app.directory,
app.webs,
graphiqlPort,
tunnel,
tunnelClient,
remoteApp.configuration,
)
app.webs = webs
const cachedUpdateURLs = app.configuration.build?.automatically_update_urls_on_dev
const previousAppId = getCachedAppInfo(commandOptions.directory)?.previousAppId
const apiKey = remoteApp.apiKey
const partnerUrlsUpdated = await handleUpdatingOfPartnerUrls(
webs,
commandOptions.update,
network,
app,
cachedUpdateURLs,
remoteApp,
apiKey,
developerPlatformClient,
)
return {
storeFqdn: store.shopDomain,
storeId: store.shopId,
remoteApp,
remoteAppUpdated: remoteApp.apiKey !== previousAppId,
localApp: app,
developerPlatformClient,
commandOptions,
network,
partnerUrlsUpdated,
graphiqlPort,
graphiqlKey: commandOptions.graphiqlKey,
}
}
async function actionsBeforeSettingUpDevProcesses(devConfig: DevConfig) {
await warnIfScopesDifferBeforeDev(devConfig)
await blockIfMigrationIncomplete(devConfig)
await devConfig.localApp.preDeployValidation()
await uploadStaticAssetsToGCS({
app: devConfig.localApp,
developerPlatformClient: devConfig.developerPlatformClient,
appId: devConfig.remoteApp,
})
}
/**
* Show a warning if the scopes in the local app configuration do not match the scopes in the remote app configuration.
*
* This is to flag that the developer may wish to run `shopify app deploy` to push the latest scopes.
*
*/
export async function warnIfScopesDifferBeforeDev({
localApp,
remoteApp,
developerPlatformClient,
}: Pick<DevConfig, 'localApp' | 'remoteApp' | 'developerPlatformClient'>) {
if (developerPlatformClient.supportsDevSessions) return
if (isCurrentAppSchema(localApp.configuration)) {
const localAccess = localApp.configuration.access_scopes
const remoteAccess = remoteApp.configuration?.access_scopes
const rationaliseScopes = (scopeString: string | undefined) => {
if (!scopeString) return scopeString
return scopeString
.split(',')
.map((scope) => scope.trim())
.sort()
.join(',')
}
const localScopes = rationaliseScopes(localAccess?.scopes)
const remoteScopes = rationaliseScopes(remoteAccess?.scopes)
if (!localAccess?.use_legacy_install_flow && localScopes !== remoteScopes) {
const nextSteps = [
[
'Run',
{command: formatPackageManagerCommand(localApp.packageManager, 'shopify app deploy')},
'to push your scopes to the Partner Dashboard',
],
]
renderWarning({
headline: [`The scopes in your TOML don't match the scopes in your Partner Dashboard`],
body: [
`Scopes in ${basename(localApp.configuration.path)}:`,
scopesMessage(getAppScopesArray(localApp.configuration)),
'\n',
'Scopes in Partner Dashboard:',
scopesMessage(remoteAccess?.scopes?.split(',') ?? []),
],
nextSteps,
})
}
}
}
export async function blockIfMigrationIncomplete(devConfig: DevConfig) {
const {developerPlatformClient, remoteApp} = devConfig
if (!developerPlatformClient.supportsDevSessions) return
const extensions = (await developerPlatformClient.appExtensionRegistrations(remoteApp)).app.extensionRegistrations
if (
!extensions
// Ignore webhook subscriptions because they do need UIDs but shouldn't block dev
.filter((extension) => extension.type.toLowerCase() !== 'webhook_subscription')
.every((extension) => extension.id)
) {
throwUidMappingError()
}
}
async function actionsBeforeLaunchingDevProcesses(config: DevConfig) {
setCachedAppInfo({directory: config.commandOptions.directory, previousAppId: config.remoteApp.apiKey})
await logMetadataForDev({
devOptions: config.commandOptions,
tunnelUrl: config.network.proxyUrl,
shouldUpdateURLs: config.partnerUrlsUpdated,
storeFqdn: config.storeFqdn,
})
await reportAnalyticsEvent({config: config.commandOptions.commandConfig, exitMode: 'ok'})
}
async function handleUpdatingOfPartnerUrls(
webs: Web[],
commandSpecifiedToUpdate: boolean,
network: {
proxyUrl: string
currentUrls: ApplicationURLs
},
localApp: AppLinkedInterface,
cachedUpdateURLs: boolean | undefined,
remoteApp: OrganizationApp,
apiKey: string,
developerPlatformClient: DeveloperPlatformClient,
) {
const {backendConfig, frontendConfig} = frontAndBackendConfig(webs)
let shouldUpdateURLs = false
if (frontendConfig ?? backendConfig) {
if (commandSpecifiedToUpdate) {
const newURLs = generateApplicationURLs(
network.proxyUrl,
webs.map(({configuration}) => configuration.auth_callback_path).find((path) => path),
localApp.configuration.app_proxy,
)
shouldUpdateURLs = await shouldOrPromptUpdateURLs({
currentURLs: network.currentUrls,
appDirectory: localApp.directory,
cachedUpdateURLs,
newApp: remoteApp.newApp,
localApp,
apiKey,
newURLs,
developerPlatformClient,
})
if (shouldUpdateURLs) {
if (developerPlatformClient.supportsDevSessions) {
// For dev sessions, store the new URLs in the local app so that the manifest can be patched with them
// The local toml is not updated.
localApp.setDevApplicationURLs(newURLs)
} else {
// When running dev app urls are pushed directly to API Client config instead of creating a new app version
// so current app version and API Client config will have different url values.
await updateURLs(newURLs, apiKey, developerPlatformClient, localApp)
}
}
}
}
return shouldUpdateURLs
}
async function setupNetworkingOptions(
appDirectory: string,
webs: Web[],
graphiqlPort: number,
tunnelOptions: TunnelMode,
tunnelClient?: TunnelClient,
remoteAppConfig?: AppConfigurationUsedByCli,
) {
const {backendConfig, frontendConfig} = frontAndBackendConfig(webs)
await validateCustomPorts(webs, graphiqlPort)
const frontendUrlOptions: FrontendURLOptions =
tunnelOptions.mode === 'use-localhost'
? {
noTunnelUseLocalhost: true,
port: tunnelOptions.actualPort,
}
: {
noTunnelUseLocalhost: false,
tunnelUrl: tunnelOptions.mode === 'custom' ? tunnelOptions.url : undefined,
tunnelClient,
}
// generateFrontendURL still uses the old naming of frontendUrl and frontendPort,
// we can rename them to proxyUrl and proxyPort when we delete dev.ts
const [{frontendUrl, frontendPort: proxyPort, usingLocalhost}, backendPort, currentUrls] = await Promise.all([
generateFrontendURL(frontendUrlOptions),
getBackendPort() ?? backendConfig?.configuration.port ?? getAvailableTCPPort(),
getURLs(remoteAppConfig),
])
const proxyUrl = usingLocalhost ? `${frontendUrl}:${proxyPort}` : frontendUrl
let frontendPort = frontendConfig?.configuration.port
if (frontendConfig) {
if (!frontendPort) {
frontendPort = frontendConfig === backendConfig ? backendPort : await getAvailableTCPPort()
}
frontendConfig.configuration.port = frontendPort
}
frontendPort = frontendPort ?? (await getAvailableTCPPort())
let reverseProxyCert
if (tunnelOptions.mode === 'use-localhost') {
const {keyContent, certContent, certPath} = await generateCertificate({
appDirectory,
})
reverseProxyCert = {
key: keyContent,
cert: certContent,
certPath,
port: tunnelOptions.actualPort,
}
}
return {
proxyUrl,
proxyPort,
frontendPort,
backendPort,
currentUrls,
webs,
reverseProxyCert,
}
}
async function launchDevProcesses({
processes,
previewUrl,
graphiqlUrl,
config,
devSessionStatusManager,
}: {
processes: DevProcesses
previewUrl: string
graphiqlUrl: string | undefined
config: DevConfig
devSessionStatusManager: DevSessionStatusManager
}) {
const abortController = new AbortController()
const processesForTaskRunner: OutputProcess[] = processes.map((process) => {
const outputProcess: OutputProcess = {
prefix: process.prefix,
action: async (stdout, stderr, signal) => {
const fn = process.function as DevProcessFunction<typeof process.options>
return fn({stdout, stderr, abortSignal: signal}, process.options)
},
}
return outputProcess
})
const apiKey = config.remoteApp.apiKey
const developerPlatformClient = config.developerPlatformClient
const app = {
canEnablePreviewMode: developerPlatformClient.supportsDevSessions
? false
: await canEnablePreviewMode({
localApp: config.localApp,
developerPlatformClient,
apiKey,
organizationId: config.remoteApp.organizationId,
}),
developmentStorePreviewEnabled: config.remoteApp.developmentStorePreviewEnabled,
apiKey,
id: config.remoteApp.id,
developerPlatformClient,
extensions: config.localApp.allExtensions,
}
return renderDev({
processes: processesForTaskRunner,
previewUrl,
graphiqlUrl,
graphiqlPort: config.graphiqlPort,
app,
abortController,
developerPreview: developerPreviewController(apiKey, developerPlatformClient),
shopFqdn: config.storeFqdn,
devSessionStatusManager,
appURL: config.localApp.devApplicationURLs?.applicationUrl,
appName: config.remoteApp.title,
organizationName: config.commandOptions.organization.businessName,
configPath: config.localApp.configuration.path,
})
}
function developerPreviewController(
apiKey: string,
developerPlatformClient: DeveloperPlatformClient,
): DeveloperPreviewController {
if (developerPlatformClient.supportsDevSessions) {
return {
fetchMode: () => Promise.resolve(false),
enable: () => Promise.resolve(false),
disable: () => Promise.resolve(),
update: () => Promise.resolve(false),
}
}
return {
fetchMode: async () => Boolean(await fetchAppPreviewMode(apiKey, developerPlatformClient)),
enable: async () => enableDeveloperPreview({apiKey, developerPlatformClient}),
disable: async () => disableDeveloperPreview({apiKey, developerPlatformClient}),
update: async (state: boolean) => developerPreviewUpdate({apiKey, developerPlatformClient, enabled: state}),
}
}
async function logMetadataForDev(options: {
devOptions: DevOptions
tunnelUrl: string
shouldUpdateURLs: boolean
storeFqdn: string
}) {
const tunnelType = await getAnalyticsTunnelType(options.devOptions.commandConfig, options.tunnelUrl)
await metadata.addPublicMetadata(() => ({
cmd_dev_tunnel_type: tunnelType,
cmd_dev_tunnel_custom_hash: tunnelType === 'custom' ? hashString(options.tunnelUrl) : undefined,
cmd_dev_urls_updated: options.shouldUpdateURLs,
store_fqdn_hash: hashString(options.storeFqdn),
cmd_app_dependency_installation_skipped: options.devOptions.skipDependenciesInstallation,
}))
await metadata.addSensitiveMetadata(() => ({
store_fqdn: options.storeFqdn,
cmd_dev_tunnel_custom: tunnelType === 'custom' ? options.tunnelUrl : undefined,
}))
}
function scopesMessage(scopes: string[]) {
return {
list: {
items: scopes.length === 0 ? ['No scopes'] : scopes,
},
}
}
async function validateCustomPorts(webConfigs: Web[], graphiqlPort: number) {
const allPorts = webConfigs.map((config) => config.configuration.port).filter((port) => port)
const duplicatedPort = allPorts.find((port, index) => allPorts.indexOf(port) !== index)
if (duplicatedPort) {
throw new AbortError(`Found port ${duplicatedPort} for multiple webs.`, 'Please define a unique port for each web.')
}
await Promise.all([
...allPorts.map(async (port) => {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const portAvailable = await checkPortAvailability(port!)
if (!portAvailable) {
throw new AbortError(`Hard-coded port ${port} is not available, please choose a different one.`)
}
}),
(async () => {
const portAvailable = await checkPortAvailability(graphiqlPort)
if (!portAvailable) {
const errorMessage = `Port ${graphiqlPort} is not available for serving GraphiQL.`
const tryMessage = ['Choose a different port for the', {command: '--graphiql-port'}, 'flag.']
throw new AbortError(errorMessage, tryMessage)
}
})(),
])
}