-
Notifications
You must be signed in to change notification settings - Fork 249
Expand file tree
/
Copy pathextension-instance.ts
More file actions
590 lines (501 loc) · 20 KB
/
extension-instance.ts
File metadata and controls
590 lines (501 loc) · 20 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
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
import {BaseConfigType, MAX_EXTENSION_HANDLE_LENGTH, MAX_UID_LENGTH} from './schemas.js'
import {FunctionConfigType} from './specifications/function.js'
import {DevSessionWatchConfig, ExtensionFeature, ExtensionSpecification} from './specification.js'
import {SingleWebhookSubscriptionType} from './specifications/app_config_webhook_schemas/webhooks_schema.js'
import {ExtensionBuildOptions, bundleFunctionExtension} from '../../services/build/extension.js'
import {bundleThemeExtension} from '../../services/extensions/bundle.js'
import {Identifiers} from '../app/identifiers.js'
import {DeveloperPlatformClient} from '../../utilities/developer-platform-client.js'
import {AppConfiguration} from '../app/app.js'
import {ApplicationURLs} from '../../services/dev/urls.js'
import {executeStep, BuildContext} from '../../services/build/client-steps.js'
import {ok} from '@shopify/cli-kit/node/result'
import {constantize, slugify} from '@shopify/cli-kit/common/string'
import {hashString, nonRandomUUID} from '@shopify/cli-kit/node/crypto'
import {partnersFqdn} from '@shopify/cli-kit/node/context/fqdn'
import {joinPath, normalizePath, resolvePath, relativePath, basename} from '@shopify/cli-kit/node/path'
import {fileExists, moveFile, glob, copyFile, globSync} from '@shopify/cli-kit/node/fs'
import {getPathValue} from '@shopify/cli-kit/common/object'
import {outputDebug} from '@shopify/cli-kit/node/output'
import {
extractJSImports,
extractImportPathsRecursively,
clearImportPathsCache,
getImportScanningCacheStats,
} from '@shopify/cli-kit/node/import-extractor'
import {isTruthy} from '@shopify/cli-kit/node/context/utilities'
import {uniq} from '@shopify/cli-kit/common/array'
/**
* Class that represents an instance of a local extension
* Before creating this class we've validated that:
* - There is a spec for this type of extension
* - The Schema for that spec is followed by the extension config toml file
* - We were able to find an entry point file for that extension
*
* It supports extension points, making this Class compatible with both new ui-extension
* and legacy extension types. Extension points are optional and this class will handle them if present.
*
* This class holds the public interface to interact with extensions
*/
export class ExtensionInstance<TConfiguration extends BaseConfigType = BaseConfigType> {
entrySourceFilePath: string
devUUID: string
localIdentifier: string
idEnvironmentVariableName: string
directory: string
configuration: TConfiguration
configurationPath: string
outputPath: string
handle: string
specification: ExtensionSpecification
uid: string
private cachedImportPaths?: string[]
get graphQLType() {
return (this.specification.graphQLType ?? this.specification.identifier).toUpperCase()
}
get type(): string {
return this.specification.identifier
}
get humanName() {
return this.specification.externalName
}
get name(): string {
return this.configuration.name ?? this.specification.externalName
}
get dependency() {
return this.specification.dependency
}
get externalType() {
return this.specification.externalIdentifier
}
get surface() {
return this.specification.surface
}
get isPreviewable() {
return this.features.includes('ui_preview')
}
get isThemeExtension() {
return this.features.includes('theme')
}
get isFunctionExtension() {
return this.features.includes('function')
}
get isESBuildExtension() {
return this.features.includes('esbuild')
}
get isSourceMapGeneratingExtension() {
return this.features.includes('generates_source_maps')
}
get isAppConfigExtension() {
return this.specification.experience === 'configuration'
}
get isFlow() {
return this.specification.identifier.includes('flow')
}
get isEditorExtensionCollection() {
return this.specification.identifier === 'editor_extension_collection'
}
get features(): ExtensionFeature[] {
return this.specification.appModuleFeatures(this.configuration)
}
get outputFileName() {
return basename(this.outputRelativePath)
}
get outputRelativePath() {
return this.specification.getOutputRelativePath?.(this) ?? ''
}
constructor(options: {
configuration: TConfiguration
configurationPath: string
entryPath?: string
directory: string
specification: ExtensionSpecification
}) {
this.configuration = options.configuration
this.configurationPath = options.configurationPath
this.entrySourceFilePath = options.entryPath ?? ''
this.directory = options.directory
this.specification = options.specification
this.handle = this.buildHandle()
this.localIdentifier = this.handle
this.idEnvironmentVariableName = `SHOPIFY_${constantize(this.localIdentifier)}_ID`
this.outputPath = joinPath(this.directory, this.outputRelativePath)
this.uid = this.buildUIDFromStrategy()
this.devUUID = `dev-${this.uid}`
}
get draftMessages() {
if (this.isAppConfigExtension) return {successMessage: undefined, errorMessage: undefined}
const successMessage = `Draft updated successfully for extension: ${this.localIdentifier}`
const errorMessage = `Error updating extension draft for ${this.localIdentifier}`
return {successMessage, errorMessage}
}
get isUUIDStrategyExtension() {
return this.specification.uidStrategy === 'uuid'
}
get isSingleStrategyExtension() {
return this.specification.uidStrategy === 'single'
}
get isDynamicStrategyExtension() {
return this.specification.uidStrategy === 'dynamic'
}
get outputPrefix() {
return this.handle
}
isSentToMetrics() {
return !this.isAppConfigExtension
}
isReturnedAsInfo() {
return !this.isAppConfigExtension
}
async deployConfig({
apiKey,
appConfiguration,
}: ExtensionDeployConfigOptions): Promise<{[key: string]: unknown} | undefined> {
const deployConfig = await this.specification.deployConfig?.(this.configuration, this.directory, apiKey, undefined)
const transformedConfig = this.specification.transformLocalToRemote?.(this.configuration, appConfiguration) as
| {[key: string]: unknown}
| undefined
const resultDeployConfig = deployConfig ?? transformedConfig ?? undefined
return resultDeployConfig && Object.keys(resultDeployConfig).length > 0 ? resultDeployConfig : undefined
}
validate() {
if (!this.specification.validate) return Promise.resolve(ok(undefined))
return this.specification.validate(this.configuration, this.configurationPath, this.directory)
}
preDeployValidation(): Promise<void> {
if (!this.specification.preDeployValidation) return Promise.resolve()
return this.specification.preDeployValidation(this)
}
buildValidation(): Promise<void> {
if (!this.specification.buildValidation) return Promise.resolve()
return this.specification.buildValidation(this)
}
async keepBuiltSourcemapsLocally(inputPath: string): Promise<void> {
if (!this.isSourceMapGeneratingExtension) return Promise.resolve()
const pathsToMove = await glob(`**/${this.handle}.js.map`, {
cwd: inputPath,
absolute: true,
followSymbolicLinks: false,
})
const pathToMove = pathsToMove[0]
if (pathToMove === undefined) return Promise.resolve()
const outputPath = joinPath(this.directory, relativePath(inputPath, pathToMove))
await moveFile(pathToMove, outputPath, {overwrite: true})
outputDebug(`Source map for ${this.localIdentifier} created: ${outputPath}`)
}
async publishURL(options: {orgId: string; appId: string; extensionId?: string}) {
const fqdn = await partnersFqdn()
const parnersPath = this.specification.partnersWebIdentifier
return `https://${fqdn}/${options.orgId}/apps/${options.appId}/extensions/${parnersPath}/${options.extensionId}`
}
getOutputFolderId(outputId?: string) {
// Ideally we want to return `this.uid` always. To keep supporting Partners API we accept a value to override that.
return outputId ?? this.uid
}
// UI Specific properties
getBundleExtensionStdinContent() {
if (this.specification.getBundleExtensionStdinContent) {
return this.specification.getBundleExtensionStdinContent(this.configuration)
}
const relativeImportPath = this.entrySourceFilePath.replace(this.directory, '')
return {main: `import '.${relativeImportPath}';`}
}
shouldFetchCartUrl(): boolean {
return this.features.includes('cart_url')
}
hasExtensionPointTarget(target: string): boolean {
return this.specification.hasExtensionPointTarget?.(this.configuration, target) ?? false
}
// Functions specific properties
get buildCommand() {
const config = this.configuration as unknown as FunctionConfigType
return config.build?.command
}
get typegenCommand() {
const config = this.configuration as unknown as FunctionConfigType
return config.build?.typegen_command
}
/**
* Default entry paths to be watched in a dev session.
* It returns the entry source file path if defined,
* or the list of files generated from the bundle content (UI extensions).
* @returns Array of strings with the paths to be watched
*/
devSessionDefaultWatchPaths(): string[] {
// For UI extensions, use the generated bundle content
if (this.specification.identifier === 'ui_extension') {
const {main, assets} = this.getBundleExtensionStdinContent()
const mainPaths = extractJSImports(main, this.directory)
const assetPaths = assets?.flatMap((asset) => extractJSImports(asset.content, this.directory)) ?? []
return mainPaths.concat(...assetPaths)
}
return [this.entrySourceFilePath]
}
// Custom watch configuration for dev sessions
// Return undefined to watch everything (default for 'extension' experience)
// Return a config with empty paths to watch nothing (default for 'configuration' experience)
get devSessionWatchConfig(): DevSessionWatchConfig | undefined {
if (this.specification.devSessionWatchConfig) {
return this.specification.devSessionWatchConfig(this)
}
return this.specification.experience === 'configuration' ? {paths: []} : undefined
}
async watchConfigurationPaths() {
if (this.isAppConfigExtension) {
return [this.configurationPath]
} else {
const additionalPaths = []
if (await fileExists(joinPath(this.directory, 'locales'))) {
additionalPaths.push(joinPath(this.directory, 'locales', '**.json'))
}
additionalPaths.push(joinPath(this.directory, '**.toml'))
return additionalPaths
}
}
get inputQueryPath() {
return joinPath(this.directory, 'input.graphql')
}
get isJavaScript() {
return Boolean(this.entrySourceFilePath.endsWith('.js') || this.entrySourceFilePath.endsWith('.ts'))
}
async build(options: ExtensionBuildOptions): Promise<void> {
const {clientSteps = []} = this.specification
const context: BuildContext = {
extension: this,
options,
stepResults: new Map(),
}
const steps = clientSteps.find((lifecycle) => lifecycle.lifecycle === 'deploy')?.steps ?? []
for (const step of steps) {
// eslint-disable-next-line no-await-in-loop
const result = await executeStep(step, context)
context.stepResults.set(step.id, result)
if (!result.success && !step.continueOnError) {
throw new Error(`Build step "${step.name}" failed: ${result.error?.message}`)
}
}
}
async buildForBundle(options: ExtensionBuildOptions, bundleDirectory: string, outputId?: string) {
this.outputPath = this.getOutputPathForDirectory(bundleDirectory, outputId)
await this.build(options)
const bundleInputPath = joinPath(bundleDirectory, this.getOutputFolderId(outputId))
await this.keepBuiltSourcemapsLocally(bundleInputPath)
}
async copyIntoBundle(options: ExtensionBuildOptions, bundleDirectory: string, extensionUuid?: string) {
const defaultOutputPath = this.outputPath
this.outputPath = this.getOutputPathForDirectory(bundleDirectory, extensionUuid)
const buildMode = this.specification.buildConfig.mode
if (this.isThemeExtension) {
await bundleThemeExtension(this, options)
} else if (buildMode !== 'none') {
outputDebug(`Will copy pre-built file from ${defaultOutputPath} to ${this.outputPath}`)
if (await fileExists(defaultOutputPath)) {
await copyFile(defaultOutputPath, this.outputPath)
if (buildMode === 'function') {
await bundleFunctionExtension(this.outputPath, this.outputPath)
}
}
}
}
getOutputPathForDirectory(directory: string, outputId?: string) {
const id = this.getOutputFolderId(outputId)
return joinPath(directory, id, this.outputRelativePath)
}
get singleTarget() {
const targets = (getPathValue(this.configuration, 'targeting') as {target: string}[]) ?? []
if (targets.length !== 1) return undefined
return targets[0]?.target
}
get contextValue() {
let context = this.singleTarget ?? ''
if (this.isFlow) context = this.configuration.handle ?? ''
return context
}
async bundleConfig({
identifiers,
developerPlatformClient,
apiKey,
appConfiguration,
}: ExtensionBundleConfigOptions): Promise<BundleConfig | undefined> {
const configValue = await this.deployConfig({apiKey, appConfiguration})
if (!configValue) return undefined
const result = {
config: JSON.stringify(configValue),
context: this.contextValue,
handle: this.handle,
}
const uuid = this.isUUIDStrategyExtension
? identifiers.extensions[this.localIdentifier]!
: identifiers.extensionsNonUuidManaged[this.localIdentifier]!
return {
...result,
uid: this.uid,
uuid,
specificationIdentifier: developerPlatformClient.toExtensionGraphQLType(this.graphQLType),
}
}
async getDevSessionUpdateMessages(): Promise<string[] | undefined> {
if (!this.specification.getDevSessionUpdateMessages) return undefined
return this.specification.getDevSessionUpdateMessages(this.configuration)
}
/**
* Patches the configuration with the app dev URLs if applicable
* Only for modules that use the app URL in their configuration.
* @param urls - The app dev URLs
*/
patchWithAppDevURLs(urls: ApplicationURLs) {
if (!this.specification.patchWithAppDevURLs) return
this.specification.patchWithAppDevURLs(this.configuration, urls)
}
async contributeToSharedTypeFile(typeDefinitionsByFile: Map<string, Set<string>>) {
await this.specification.contributeToSharedTypeFile?.(this, typeDefinitionsByFile)
}
/**
* Returns all files that need to be watched for this extension
* This includes files in the extension directory (respecting watch paths and gitignore)
* as well as any imported files from outside the extension directory
*/
watchedFiles(): string[] {
const watchedFiles: string[] = []
const defaultIgnore = [
'**/node_modules/**',
'**/.git/**',
'**/*.test.*',
'**/dist/**',
'**/*.swp',
'**/generated/**',
'**/.gitignore',
]
const watchConfig = this.devSessionWatchConfig
const patterns = watchConfig?.paths ?? ['**/*']
const ignore = watchConfig?.ignore ?? defaultIgnore
const files = patterns.flatMap((pattern) =>
globSync(pattern, {
cwd: this.directory,
absolute: true,
followSymbolicLinks: false,
ignore,
}),
)
watchedFiles.push(...files.flat())
// Add imported files from outside the extension directory unless custom watch config is defined
if (!watchConfig) {
const importedFiles = this.scanImports()
watchedFiles.push(...importedFiles)
}
return [...new Set(watchedFiles.map((file) => normalizePath(file)))]
}
/**
* Copy static assets from the extension directory to the output path
* Used by both dev and deploy builds
*/
async copyStaticAssets(outputPath?: string) {
if (this.specification.copyStaticAssets) {
return this.specification.copyStaticAssets(this.configuration, this.directory, outputPath ?? this.outputPath)
}
}
/**
* Rescans imports for this extension and updates the cached import paths
* Returns true if the imports changed
*/
async rescanImports(): Promise<boolean> {
const oldImportPaths = this.cachedImportPaths
this.cachedImportPaths = undefined
clearImportPathsCache()
this.scanImports()
return oldImportPaths !== this.cachedImportPaths
}
/**
* Scans for imports in this extension's entry files
* Returns absolute paths of imported files that are outside the extension directory
*/
private scanImports(): string[] {
// Return cached paths if available
if (this.cachedImportPaths !== undefined) {
return this.cachedImportPaths
}
if (isTruthy(process.env.SHOPIFY_CLI_DISABLE_IMPORT_SCANNING)) {
this.cachedImportPaths = []
return this.cachedImportPaths
}
try {
const startTime = performance.now()
const entryFiles = this.devSessionDefaultWatchPaths()
const imports = entryFiles.flatMap((entryFile) => {
return extractImportPathsRecursively(entryFile).map((importPath) => normalizePath(resolvePath(importPath)))
})
this.cachedImportPaths = uniq(imports) ?? []
const elapsed = Math.round(performance.now() - startTime)
const cacheStats = getImportScanningCacheStats()
const cacheInfo = cacheStats ? ` (cache: ${cacheStats.directImports} parsed, ${cacheStats.fileExists} stats)` : ''
outputDebug(
`Import scan for "${this.handle}": ${entryFiles.length} entries, ${this.cachedImportPaths.length} files, ${elapsed}ms${cacheInfo}`,
)
return this.cachedImportPaths
// eslint-disable-next-line no-catch-all/no-catch-all
} catch (error) {
outputDebug(`Failed to scan imports for extension ${this.handle}: ${error}`)
this.cachedImportPaths = []
return this.cachedImportPaths
}
}
private buildHandle() {
switch (this.specification.uidStrategy) {
case 'single':
return this.specification.identifier
case 'uuid':
return this.configuration.handle ?? slugify(this.name ?? '')
case 'dynamic':
// Hardcoded temporal solution for webhooks
if ('topic' in this.configuration && 'uri' in this.configuration) {
const subscription = this.configuration as unknown as SingleWebhookSubscriptionType
const handle = `${subscription.topic}${subscription.uri}${subscription.filter}`
return hashString(handle).substring(0, MAX_EXTENSION_HANDLE_LENGTH)
} else {
return nonRandomUUID(JSON.stringify(this.configuration))
}
default:
return this.specification.identifier
}
}
private buildUIDFromStrategy() {
switch (this.specification.uidStrategy) {
case 'single':
return this.specification.identifier
case 'uuid':
return this.configuration.uid ?? nonRandomUUID(this.handle)
case 'dynamic':
// NOTE: This is a temporary special case for webhook subscriptions.
// We're directly checking for webhook properties and casting the configuration
// instead of using a proper dynamic strategy implementation.
// To remove this special case:
// 1. Implement a proper dynamic UID strategy for webhooks in the server-side specification
// 2. Update the CLI to use that strategy instead of this hardcoded logic
// Related issues: PR #559094 in old Core repo
if ('topic' in this.configuration && 'uri' in this.configuration) {
const subscription = this.configuration as unknown as SingleWebhookSubscriptionType
return `${subscription.topic}::${subscription.filter}::${subscription.uri}`.substring(0, MAX_UID_LENGTH)
} else {
return nonRandomUUID(JSON.stringify(this.configuration))
}
}
}
}
interface ExtensionDeployConfigOptions {
apiKey: string
appConfiguration: AppConfiguration
}
interface ExtensionBundleConfigOptions {
identifiers: Identifiers
developerPlatformClient: DeveloperPlatformClient
apiKey: string
appConfiguration: AppConfiguration
}
interface BundleConfig {
config: string
context: string
handle: string
uid: string
uuid: string
specificationIdentifier: string
}