-
Notifications
You must be signed in to change notification settings - Fork 229
Expand file tree
/
Copy pathextension.ts
More file actions
245 lines (216 loc) · 8.17 KB
/
extension.ts
File metadata and controls
245 lines (216 loc) · 8.17 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
import {runThemeCheck} from './theme-check.js'
import {AppInterface} from '../../models/app/app.js'
import {bundleExtension} from '../extensions/bundle.js'
import {buildGraphqlTypes, buildJSFunction, runTrampoline, runWasmOpt} from '../function/build.js'
import {ExtensionInstance} from '../../models/extensions/extension-instance.js'
import {FunctionConfigType} from '../../models/extensions/specifications/function.js'
import {exec} from '@shopify/cli-kit/node/system'
import {AbortSignal} from '@shopify/cli-kit/node/abort'
import {AbortError, AbortSilentError} from '@shopify/cli-kit/node/error'
import lockfile from 'proper-lockfile'
import {dirname, joinPath} from '@shopify/cli-kit/node/path'
import {outputDebug} from '@shopify/cli-kit/node/output'
import {readFile, touchFile, writeFile, fileExistsSync} from '@shopify/cli-kit/node/fs'
import {Writable} from 'stream'
export interface ExtensionBuildOptions {
/**
* Standard output stream to send the output through.
*/
stdout: Writable
/**
* Standard error stream to send the error output through.
*/
stderr: Writable
/**
* Signal to abort the build process.
*/
signal?: AbortSignal
/**
* Overrides the default build directory.
*/
buildDirectory?: string
/**
* Use tasks to build the extension.
*/
useTasks?: boolean
/**
* The app that contains the extensions.
*/
app: AppInterface
/**
* The environment to build the extension.
* Default value: production
*/
environment: 'production' | 'development'
/**
* The URL where the app is running.
*/
appURL?: string
}
/**
* It builds the theme extensions.
* @param options - Build options.
*/
export async function buildThemeExtension(extension: ExtensionInstance, options: ExtensionBuildOptions): Promise<void> {
options.stdout.write(`Running theme check on your Theme app extension...`)
const offenses = await runThemeCheck(extension.directory)
if (offenses) options.stdout.write(offenses)
}
/**
* It builds the UI extensions.
* @param options - Build options.
*/
export async function buildUIExtension(extension: ExtensionInstance, options: ExtensionBuildOptions): Promise<void> {
options.stdout.write(`Bundling UI extension ${extension.localIdentifier}...`)
const env = options.app.dotenv?.variables ?? {}
if (options.appURL) {
env.APP_URL = options.appURL
}
const {main, assets} = extension.getBundleExtensionStdinContent()
try {
await bundleExtension({
minify: true,
outputPath: extension.outputPath,
stdin: {
contents: main,
resolveDir: extension.directory,
loader: 'tsx',
},
environment: options.environment,
env,
stderr: options.stderr,
stdout: options.stdout,
sourceMaps: extension.isSourceMapGeneratingExtension,
})
if (assets) {
await Promise.all(
assets.map(async (asset) => {
await bundleExtension({
minify: true,
outputPath: joinPath(dirname(extension.outputPath), asset.outputFileName),
stdin: {
contents: asset.content,
resolveDir: extension.directory,
loader: 'tsx',
},
environment: options.environment,
env,
stderr: options.stderr,
stdout: options.stdout,
})
}),
)
}
} catch (extensionBundlingError) {
// this fails if the app's own source code is broken; wrap such that this isn't flagged as a CLI bug
throw new AbortError(
`Failed to bundle extension ${extension.localIdentifier}. Please check the extension source code for errors.`,
)
}
await extension.buildValidation()
options.stdout.write(`${extension.localIdentifier} successfully built`)
}
type BuildFunctionExtensionOptions = ExtensionBuildOptions
/**
* Builds a function extension
* @param extension - The function extension to build.
* @param options - Options to configure the build of the extension.
*/
export async function buildFunctionExtension(
extension: ExtensionInstance,
options: BuildFunctionExtensionOptions,
): Promise<void> {
const lockfilePath = joinPath(extension.directory, '.build-lock')
let releaseLock
try {
releaseLock = await lockfile.lock(extension.directory, {retries: 20, lockfilePath})
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} catch (error: any) {
outputDebug(`Failed to acquire function build lock: ${error.message}`)
throw new AbortError('Failed to build function.', 'This is likely due to another in-progress build.', [
'Ensure there are no other function builds in-progress.',
'Delete the `.build-lock` file in your function directory.',
])
}
try {
const bundlePath = extension.outputPath
const relativeBuildPath =
(extension as ExtensionInstance<FunctionConfigType>).configuration.build?.path ?? joinPath('dist', 'index.wasm')
extension.outputPath = joinPath(extension.directory, relativeBuildPath)
if (extension.isJavaScript) {
await runCommandOrBuildJSFunction(extension, options)
} else {
await buildOtherFunction(extension, options)
}
const wasmOpt = (extension as ExtensionInstance<FunctionConfigType>).configuration.build?.wasm_opt
if (fileExistsSync(extension.outputPath) && wasmOpt) {
await runWasmOpt(extension.outputPath)
}
if (fileExistsSync(extension.outputPath)) {
await runTrampoline(extension.outputPath)
}
if (fileExistsSync(extension.outputPath) && bundlePath !== extension.outputPath) {
await bundleFunctionExtension(extension.outputPath, bundlePath)
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} catch (error: any) {
// To avoid random user-code errors being reported as CLI bugs, we capture and rethrow them as AbortError.
// In this case, we need to keep the ESBuild details for the logs. (the `errors` array).
// If the error is already an AbortError, we can just rethrow it.
if (error instanceof AbortError) {
throw error
}
const errorMessage = (error as Error).message ?? 'Unknown error occurred'
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const newError: any = new AbortError('Failed to build function.', errorMessage)
// Inject ESBuild errors if present
newError.errors = error.errors
throw newError
} finally {
await releaseLock()
}
}
export async function bundleFunctionExtension(wasmPath: string, bundlePath: string) {
outputDebug(`Converting WASM from ${wasmPath} to base64 in ${bundlePath}`)
const base64Contents = await readFile(wasmPath, {encoding: 'base64'})
await touchFile(bundlePath)
await writeFile(bundlePath, base64Contents)
}
async function runCommandOrBuildJSFunction(extension: ExtensionInstance, options: BuildFunctionExtensionOptions) {
if (extension.buildCommand) {
if (extension.typegenCommand) {
await buildGraphqlTypes(extension, options)
}
return runCommand(extension.buildCommand, extension, options)
} else {
return buildJSFunction(extension as ExtensionInstance<FunctionConfigType>, options)
}
}
async function buildOtherFunction(extension: ExtensionInstance, options: BuildFunctionExtensionOptions) {
if (!extension.buildCommand) {
options.stderr.write(
`The function extension ${extension.localIdentifier} doesn't have a build command or it's empty`,
)
options.stderr.write(`
Edit the shopify.function.extension.toml configuration file and set how to build the extension.
[build]
command = "{COMMAND}"
Note that the command must output a dist/index.wasm file.
`)
throw new AbortSilentError()
}
if (extension.typegenCommand) {
await buildGraphqlTypes(extension, options)
}
return runCommand(extension.buildCommand, extension, options)
}
async function runCommand(buildCommand: string, extension: ExtensionInstance, options: BuildFunctionExtensionOptions) {
const buildCommandComponents = buildCommand.split(' ')
options.stdout.write(`Building function ${extension.localIdentifier}...`)
await exec(buildCommandComponents[0]!, buildCommandComponents.slice(1), {
stdout: options.stdout,
stderr: options.stderr,
cwd: extension.directory,
signal: options.signal,
})
}