-
Notifications
You must be signed in to change notification settings - Fork 268
/
compile.ts
340 lines (316 loc) · 9.01 KB
/
compile.ts
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
import { ProgressTracker } from '@php-wasm/progress';
import { Semaphore } from '@php-wasm/util';
import {
LatestSupportedPHPVersion,
SupportedPHPVersion,
SupportedPHPVersions,
UniversalPHP,
} from '@php-wasm/universal';
import { isFileReference, Resource } from './resources';
import { Step, StepDefinition } from './steps';
import * as stepHandlers from './steps/handlers';
import { Blueprint } from './blueprint';
import Ajv from 'ajv';
/**
* The JSON schema stored in this directory is used to validate the Blueprints
* and is autogenerated from the Blueprints TypeScript types.
*
* Whenever the types are modified, the schema needs to be rebuilt using
* `nx build playground-blueprints` and then committed to the repository.
*
* Unfortunately, it is not auto-rebuilt in `npm run dev` mode as the
* `dts-bundle-generator` utility we use for type rollyps does not support
* watching for changes.
*/
import blueprintSchema from '../../public/blueprint-schema.json';
import type { ValidateFunction } from 'ajv';
export type CompiledStep = (php: UniversalPHP) => Promise<void> | void;
const supportedWordPressVersions = [
'6.2',
'6.1',
'6.0',
'5.9',
'nightly',
] as const;
type supportedWordPressVersion = (typeof supportedWordPressVersions)[number];
export interface CompiledBlueprint {
/** The requested versions of PHP and WordPress for the blueprint */
versions: {
php: SupportedPHPVersion;
wp: supportedWordPressVersion;
};
/** The compiled steps for the blueprint */
run: (playground: UniversalPHP) => Promise<void>;
}
export type OnStepCompleted = (output: any, step: StepDefinition) => any;
export interface CompileBlueprintOptions {
/** Optional progress tracker to monitor progress */
progress?: ProgressTracker;
/** Optional semaphore to control access to a shared resource */
semaphore?: Semaphore;
/** Optional callback with step output */
onStepCompleted?: OnStepCompleted;
}
/**
* Compiles Blueprint into a form that can be executed.
*
* @param playground The PlaygroundClient to use for the compilation
* @param blueprint The bBueprint to compile
* @param options Additional options for the compilation
* @returns The compiled blueprint
*/
export function compileBlueprint(
blueprint: Blueprint,
{
progress = new ProgressTracker(),
semaphore = new Semaphore({ concurrency: 3 }),
onStepCompleted = () => {},
}: CompileBlueprintOptions = {}
): CompiledBlueprint {
blueprint = {
...blueprint,
steps: (blueprint.steps || []).filter(isStepDefinition),
};
const { valid, errors } = validateBlueprint(blueprint);
if (!valid) {
const e = new Error(
`Invalid blueprint: ${errors![0].message} at ${
errors![0].instancePath
}`
);
// Attach Ajv output to the thrown object for easier debugging
(e as any).errors = errors;
throw e;
}
const steps = (blueprint.steps || []) as StepDefinition[];
const totalProgressWeight = steps.reduce(
(total, step) => total + (step.progress?.weight || 1),
0
);
const compiled = steps.map((step) =>
compileStep(step, {
semaphore,
rootProgressTracker: progress,
totalProgressWeight,
})
);
return {
versions: {
php: compileVersion(
blueprint.preferredVersions?.php,
SupportedPHPVersions,
LatestSupportedPHPVersion
),
wp: compileVersion(
blueprint.preferredVersions?.wp,
supportedWordPressVersions,
'6.2'
),
},
run: async (playground: UniversalPHP) => {
try {
// Start resolving resources early
for (const { resources } of compiled) {
for (const resource of resources) {
resource.setPlayground(playground);
if (resource.isAsync) {
resource.resolve();
}
}
}
for (const { run, step } of compiled) {
const result = await run(playground);
onStepCompleted(result, step);
}
} finally {
try {
await (playground as any).goTo(
blueprint.landingPage || '/'
);
} catch (e) {
/*
* NodePHP exposes no goTo method.
* We can't use `goto` in playground here,
* because it may be a Comlink proxy object
* with no such method.
*/
}
progress.finish();
}
},
};
}
const ajv = new Ajv({ discriminator: true });
let blueprintValidator: ValidateFunction | undefined;
export function validateBlueprint(blueprintMaybe: object) {
blueprintValidator = ajv.compile(blueprintSchema);
const valid = blueprintValidator(blueprintMaybe);
if (valid) {
return { valid };
}
/**
* Each entry of "steps" can be either an object, null, undefined etc
* via the "anyOf" part of the schema.
*
* If the step has any error in it, like a missing property, Ajv will
* also return errors for each case listed in "anyOf" which means we'll
* learn that step is not a null, undefined etc. This is not helpful, so
* we filter out those errors.
*
* However, if the "anyOf" error is the only error we have then we want
* to keep it because the step is likely, say, a number, and we want to
* let the developer know.
*/
const hasErrorsDifferentThanAnyOf: Set<string> = new Set();
for (const error of blueprintValidator.errors!) {
if (!error.schemaPath.startsWith('#/properties/steps/items/anyOf')) {
hasErrorsDifferentThanAnyOf.add(error.instancePath);
}
}
const errors = blueprintValidator.errors?.filter(
(error) =>
!(
error.schemaPath.startsWith('#/properties/steps/items/anyOf') &&
hasErrorsDifferentThanAnyOf.has(error.instancePath)
)
);
return {
valid,
errors,
};
}
/**
* Compiles a preferred version string into a supported version
*
* @param value The value to compile
* @param supported The list of supported versions
* @param latest The latest supported version
* @returns The compiled version
*/
function compileVersion<T>(
value: string | undefined | null,
supported: readonly T[],
latest: string
): T {
if (value && supported.includes(value as any)) {
return value as T;
}
return latest as T;
}
/**
* Determines if a step is a StepDefinition object
*
* @param step The object to test
* @returns Whether the object is a StepDefinition
*/
function isStepDefinition(
step: Step | string | undefined | false | null
): step is StepDefinition {
return !!(typeof step === 'object' && step);
}
interface CompileStepArgsOptions {
/** Optional semaphore to control access to a shared resource */
semaphore?: Semaphore;
/** The root progress tracker for the compilation */
rootProgressTracker: ProgressTracker;
/** The total progress weight of all the steps in the blueprint */
totalProgressWeight: number;
}
/**
* Compiles a single Blueprint step into a form that can be executed
*
* @param playground The PlaygroundClient to use for the compilation
* @param step The step to compile
* @param options Additional options for the compilation
* @returns The compiled step
*/
function compileStep<S extends StepDefinition>(
step: S,
{
semaphore,
rootProgressTracker,
totalProgressWeight,
}: CompileStepArgsOptions
): { run: CompiledStep; step: S; resources: Array<Resource> } {
const stepProgress = rootProgressTracker.stage(
(step.progress?.weight || 1) / totalProgressWeight
);
const args: any = {};
for (const key of Object.keys(step)) {
let value = (step as any)[key];
if (isFileReference(value)) {
value = Resource.create(value, {
semaphore,
});
}
args[key] = value;
}
const run = async (playground: UniversalPHP) => {
try {
stepProgress.fillSlowly();
return await stepHandlers[step.step](
playground,
await resolveArguments(args),
{
tracker: stepProgress,
initialCaption: step.progress?.caption,
}
);
} finally {
stepProgress.finish();
}
};
/**
* The weight of each async resource is the same, and is the same as the
* weight of the step itself.
*/
const resources = getResources(args);
const asyncResources = getResources(args).filter(
(resource) => resource.isAsync
);
const evenWeight = 1 / (asyncResources.length + 1);
for (const resource of asyncResources) {
resource.progress = stepProgress.stage(evenWeight);
}
return { run, step, resources };
}
/**
* Gets the resources used by a specific compiled step
*
* @param step The compiled step
* @returns The resources used by the compiled step
*/
function getResources<S extends StepDefinition>(args: S) {
const result: Resource[] = [];
for (const argName in args) {
const resourceMaybe = (args as any)[argName];
if (resourceMaybe instanceof Resource) {
result.push(resourceMaybe);
}
}
return result;
}
/**
* Replaces Resource objects with their resolved values
*
* @param step The compiled step
* @returns The resources used by the compiled step
*/
async function resolveArguments<T extends Record<string, unknown>>(args: T) {
const resolved: any = {};
for (const argName in args) {
const resourceMaybe = (args as any)[argName];
if (resourceMaybe instanceof Resource) {
resolved[argName] = await resourceMaybe.resolve();
} else {
resolved[argName] = resourceMaybe;
}
}
return resolved;
}
export async function runBlueprintSteps(
compiledBlueprint: CompiledBlueprint,
playground: UniversalPHP
) {
await compiledBlueprint.run(playground);
}