@diagonal-hq/cli 0.38.2 → 0.38.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,462 @@
1
+ import { createRequire as __diagonalCreateRequire } from 'node:module';
2
+ const require = __diagonalCreateRequire(import.meta.url);
3
+ import {
4
+ stripTypes
5
+ } from "./cli-chunk-IJTP2OMH.mjs";
6
+ import {
7
+ AUTHORING_HELPERS_MODULE,
8
+ GENERATED_NOTIFICATION_TYPES_PATH,
9
+ appImportsOf,
10
+ appModuleClosure,
11
+ isAppSpecifier,
12
+ resolveAppSpecifier,
13
+ scriptSdkRuntimeFiles
14
+ } from "./cli-chunk-HWHRAOWD.mjs";
15
+ import {
16
+ PROFILES
17
+ } from "./cli-chunk-WPC3DBHX.mjs";
18
+ import "./cli-chunk-T6442V5V.mjs";
19
+ import {
20
+ GENERATED_ASSETS_PATH
21
+ } from "./cli-chunk-YIPLFIKL.mjs";
22
+ import {
23
+ SourceError,
24
+ childNodes,
25
+ diagnosticFromError,
26
+ parseSource
27
+ } from "./cli-chunk-F2J44UIS.mjs";
28
+ import {
29
+ AUTHORING_MODULE,
30
+ diagnostic,
31
+ diagnosticAt
32
+ } from "./cli-chunk-A7Q2M4ZU.mjs";
33
+ import "./cli-chunk-LRS5IEI3.mjs";
34
+
35
+ // scripts/lib/runtime-build/workflows.mjs
36
+ import { readFileSync } from "node:fs";
37
+ import { join as join2 } from "node:path";
38
+
39
+ // scripts/lib/runtime-build/workflow-config.mjs
40
+ var WORKFLOW_STAGE = "workflow";
41
+
42
+ // scripts/lib/runtime-build/workflow-tests.mjs
43
+ import { spawnSync } from "node:child_process";
44
+ import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs";
45
+ import { tmpdir } from "node:os";
46
+ import { basename, dirname, join, relative } from "node:path";
47
+ var WORKFLOW_TEST_STAGE = "workflow test";
48
+ var TEST_SUFFIX = ".test.ts";
49
+ var WORKFLOW_TEST_SUBJECT = {
50
+ noun: "workflow",
51
+ directory: "workflows",
52
+ sdk: "@diagonal/workflow",
53
+ stage: WORKFLOW_TEST_STAGE
54
+ };
55
+ var MIGRATION_TEST_SUBJECT = {
56
+ noun: "migration",
57
+ directory: "migrations",
58
+ sdk: "@diagonal/workflow",
59
+ stage: "migration test"
60
+ };
61
+ var TEST_TIMEOUT_MS = 1e4;
62
+ var RUN_TIMEOUT_MS = 6e4;
63
+ var RESULT_PREFIX = "\0diagonal-test ";
64
+ var SDK_MODULES = {
65
+ "@diagonal/workflow": "sdk/workflow.js",
66
+ "@diagonal/workflow/testing": "sdk/quickjs-testing.js",
67
+ "@diagonal/workflow/workspace": "sdk/workspace.js",
68
+ [AUTHORING_MODULE]: "sdk/runtime.js"
69
+ };
70
+ var NODE_TEST_MODULES = /* @__PURE__ */ new Set(["node:test", "node:assert", "node:assert/strict"]);
71
+ var TEST_MODULE_EXTERNALS = /* @__PURE__ */ new Set([...Object.keys(SDK_MODULES), ...NODE_TEST_MODULES]);
72
+ var RELATIVE_WORKFLOW = /^\.\/([^/]+?)(?:\.ts|\.js)?$/;
73
+ var REPORTER_SOURCE = `const PREFIX = ${JSON.stringify(RESULT_PREFIX)};
74
+ export default async function* reporter(source) {
75
+ const names = [];
76
+ for await (const event of source) {
77
+ const data = event.data;
78
+ if (event.type === 'test:start') {
79
+ names.length = data.nesting;
80
+ names.push(data.name);
81
+ continue;
82
+ }
83
+ if (event.type !== 'test:pass' && event.type !== 'test:fail') {
84
+ continue;
85
+ }
86
+ const error = data.details?.error;
87
+ if (data.details?.type === 'suite' && (event.type === 'test:pass' || error?.failureType === 'subtestsFailed')) {
88
+ continue;
89
+ }
90
+ const path = [...names.slice(0, data.nesting), data.name].join(' > ');
91
+ const cause = error?.cause ?? error;
92
+ yield PREFIX + JSON.stringify({
93
+ file: data.file ?? null,
94
+ name: path,
95
+ leaf: data.name,
96
+ ok: event.type === 'test:pass',
97
+ message: event.type === 'test:pass' ? null : String(cause?.message ?? cause ?? 'The test failed').trim()
98
+ }) + '\\n';
99
+ }
100
+ }
101
+ `;
102
+ function moduleSpecifierNodes(ast) {
103
+ return ast.program.body.filter(
104
+ (statement) => (statement.type === "ImportDeclaration" || statement.type === "ExportNamedDeclaration" || statement.type === "ExportAllDeclaration") && statement.source
105
+ ).map((statement) => statement.source);
106
+ }
107
+ function rewriteSpecifiers(source, ast, resolveSpecifier) {
108
+ let rewritten = source;
109
+ for (const node of moduleSpecifierNodes(ast).toSorted(
110
+ (left, right) => right.start - left.start
111
+ )) {
112
+ const target = resolveSpecifier(node.value);
113
+ if (target !== null) {
114
+ rewritten = `${rewritten.slice(0, node.start)}${JSON.stringify(target)}${rewritten.slice(node.end)}`;
115
+ }
116
+ }
117
+ return rewritten;
118
+ }
119
+ function sdkSpecifier(fromDirectory) {
120
+ return (specifier) => Object.hasOwn(SDK_MODULES, specifier) ? `${fromDirectory}${SDK_MODULES[specifier]}` : null;
121
+ }
122
+ function testCallNode(ast, name) {
123
+ const pending = [ast.program];
124
+ while (pending.length > 0) {
125
+ const node = pending.pop();
126
+ const [first] = node.type === "CallExpression" ? node.arguments : [];
127
+ if (first !== void 0 && (first.type === "StringLiteral" || first.type === "TemplateLiteral" && first.expressions.length === 0) && (first.type === "StringLiteral" ? first.value : first.quasis[0].value.cooked) === name) {
128
+ return node;
129
+ }
130
+ pending.push(...childNodes(node));
131
+ }
132
+ return null;
133
+ }
134
+ function importDiagnostics(test, scriptNames, workspaceRoot, subject) {
135
+ const diagnostics = [];
136
+ for (const node of moduleSpecifierNodes(test.ast)) {
137
+ const specifier = node.value;
138
+ const relative2 = RELATIVE_WORKFLOW.exec(specifier);
139
+ if (NODE_TEST_MODULES.has(specifier) || Object.hasOwn(SDK_MODULES, specifier) || relative2 !== null && scriptNames.has(relative2[1]) || isAppSpecifier(specifier) && workspaceRoot !== null && resolveAppSpecifier(workspaceRoot, specifier) !== null) {
140
+ continue;
141
+ }
142
+ diagnostics.push(
143
+ diagnosticAt(
144
+ test.path,
145
+ node,
146
+ `A ${subject.noun} test can import only node:test, node:assert, ${subject.sdk}, @diagonal/workflow/testing, @diagonal/workflow/workspace, the ${subject.noun}s in ${subject.directory}/, and workspace files by @app/. "${specifier}" is not one of them`,
147
+ { stage: subject.stage }
148
+ )
149
+ );
150
+ }
151
+ return diagnostics;
152
+ }
153
+ function compiledScriptModule(script) {
154
+ const prefix = sandboxPrefix(script.path);
155
+ const source = JSON.stringify(`./${basename(script.path, ".ts")}.mjs`);
156
+ return [
157
+ `import * as script from ${source};`,
158
+ `import { registerCompiledScript } from ${JSON.stringify(`${prefix}sdk/quickjs-testing.js`)};`,
159
+ `export * from ${source};`,
160
+ "export default script.default;",
161
+ `registerCompiledScript(script.default, ${JSON.stringify(script.compiled)}, script.validateInput);`,
162
+ ""
163
+ ].join("\n");
164
+ }
165
+ function sandboxPath(path) {
166
+ return path.replace(/\.(ts|tsx|js|jsx)$/, ".js");
167
+ }
168
+ function sandboxPrefix(path) {
169
+ return "../".repeat(path.split("/").length - 1) || "./";
170
+ }
171
+ function relativeSandboxPath(from, target) {
172
+ const path = relative(dirname(from), sandboxPath(target));
173
+ return path.startsWith(".") ? path : `./${path}`;
174
+ }
175
+ function writeFile(root, path, content) {
176
+ mkdirSync(dirname(join(root, path)), { recursive: true });
177
+ writeFileSync(join(root, path), content);
178
+ }
179
+ function parseResults(stdout) {
180
+ return stdout.split("\n").filter((line) => line.startsWith(RESULT_PREFIX)).map((line) => JSON.parse(line.slice(RESULT_PREFIX.length)));
181
+ }
182
+ function testsNotReaching(tests, skippedScripts, root, modulePath) {
183
+ return tests.filter((test) => {
184
+ if (skippedScripts.has(`${test.path.slice(0, -TEST_SUFFIX.length)}.ts`)) {
185
+ return false;
186
+ }
187
+ if (root === null) {
188
+ return true;
189
+ }
190
+ try {
191
+ return !appModuleClosure(
192
+ root,
193
+ appImportsOf(root, test.path, test.ast),
194
+ TEST_MODULE_EXTERNALS
195
+ ).has(modulePath);
196
+ } catch (error) {
197
+ if (error instanceof SourceError) {
198
+ return true;
199
+ }
200
+ throw error;
201
+ }
202
+ });
203
+ }
204
+ function runScriptTests({
205
+ tests,
206
+ scripts,
207
+ root: workspaceRoot = null,
208
+ appModules = /* @__PURE__ */ new Map(),
209
+ subject = WORKFLOW_TEST_SUBJECT
210
+ }) {
211
+ const diagnostics = [];
212
+ const prefix = `${subject.directory}/`;
213
+ const scriptNames = new Map(
214
+ scripts.map((script) => [script.path.slice(prefix.length, -".ts".length), script])
215
+ );
216
+ const runnable = [];
217
+ for (const test of tests) {
218
+ const scriptPath = `${test.path.slice(0, -TEST_SUFFIX.length)}.ts`;
219
+ if (!scriptNames.has(scriptPath.slice(prefix.length, -".ts".length))) {
220
+ diagnostics.push(
221
+ diagnosticAt(
222
+ test.path,
223
+ null,
224
+ `The test file has no ${subject.noun}. Add ${scriptPath} or remove the test file`,
225
+ { stage: subject.stage }
226
+ )
227
+ );
228
+ continue;
229
+ }
230
+ const imports = importDiagnostics(test, scriptNames, workspaceRoot, subject);
231
+ diagnostics.push(...imports);
232
+ if (imports.length === 0) {
233
+ runnable.push({ ...test, script: scriptPath });
234
+ }
235
+ }
236
+ if (runnable.length === 0) {
237
+ return { testResults: [], diagnostics };
238
+ }
239
+ const modules = new Map(appModules);
240
+ for (const test of runnable) {
241
+ for (const [path, module] of appModuleClosure(
242
+ workspaceRoot,
243
+ workspaceRoot === null ? [] : appImportsOf(workspaceRoot, test.path, test.ast),
244
+ TEST_MODULE_EXTERNALS
245
+ )) {
246
+ modules.set(path, module);
247
+ }
248
+ }
249
+ const files = [];
250
+ for (const [path, module] of modules) {
251
+ const resolveSdk = sdkSpecifier(sandboxPrefix(path));
252
+ files.push({
253
+ path,
254
+ target: sandboxPath(path),
255
+ source: rewriteSpecifiers(
256
+ module.source,
257
+ parseSource(module.source, { jsx: path.endsWith("x") }),
258
+ (specifier) => module.requires[specifier] === void 0 ? resolveSdk(specifier) : relativeSandboxPath(path, module.requires[specifier])
259
+ )
260
+ });
261
+ }
262
+ for (const script of scripts) {
263
+ files.push({
264
+ path: script.path,
265
+ target: script.path.replace(/\.ts$/, script.compiled ? ".mjs" : ".js"),
266
+ source: rewriteSpecifiers(script.source, script.ast, (specifier) => {
267
+ const target = isAppSpecifier(specifier) && workspaceRoot !== null ? resolveAppSpecifier(workspaceRoot, specifier) : null;
268
+ return target === null ? sdkSpecifier("../")(specifier) : relativeSandboxPath(script.path, target);
269
+ })
270
+ });
271
+ }
272
+ for (const test of runnable) {
273
+ const resolveSdk = sdkSpecifier("../");
274
+ files.push({
275
+ path: test.path,
276
+ target: test.path.replace(/\.ts$/, ".js"),
277
+ source: rewriteSpecifiers(test.source, test.ast, (specifier) => {
278
+ const relative2 = RELATIVE_WORKFLOW.exec(specifier);
279
+ const target = isAppSpecifier(specifier) && workspaceRoot !== null ? resolveAppSpecifier(workspaceRoot, specifier) : null;
280
+ if (target !== null) {
281
+ return relativeSandboxPath(test.path, target);
282
+ }
283
+ return relative2 !== null ? `./${relative2[1]}.js` : resolveSdk(specifier);
284
+ })
285
+ });
286
+ }
287
+ const stripped = stripTypes(files.map(({ path, source }) => ({ path, source })));
288
+ const stripErrors = files.flatMap((file, index) => {
289
+ const result = stripped[index];
290
+ return result.ok ? [] : [
291
+ diagnostic(
292
+ file.path,
293
+ result.line,
294
+ result.column,
295
+ `The ${subject.noun} tests did not run, because this file does not compile: ${result.message}`,
296
+ { stage: subject.stage }
297
+ )
298
+ ];
299
+ });
300
+ if (stripErrors.length > 0) {
301
+ return { testResults: [], diagnostics: [...diagnostics, ...stripErrors] };
302
+ }
303
+ const root = realpathSync(mkdtempSync(join(tmpdir(), "diagonal-workflow-tests-")));
304
+ try {
305
+ writeFile(root, "package.json", '{"type":"module"}\n');
306
+ writeFile(root, "reporter.mjs", REPORTER_SOURCE);
307
+ for (const [path, content] of Object.entries(scriptSdkRuntimeFiles())) {
308
+ writeFile(root, `sdk/${path}`, content);
309
+ }
310
+ writeFile(root, "sdk/workspace.js", "export {};\n");
311
+ writeFile(root, "sdk/runtime.js", AUTHORING_HELPERS_MODULE);
312
+ for (const [index, file] of files.entries()) {
313
+ writeFile(root, file.target, stripped[index].code);
314
+ }
315
+ for (const script of scripts) {
316
+ if (script.compiled) {
317
+ writeFile(root, script.path.replace(/\.ts$/, ".js"), compiledScriptModule(script));
318
+ }
319
+ }
320
+ const run = spawnSync(
321
+ process.execPath,
322
+ [
323
+ "--permission",
324
+ `--allow-fs-read=${root}`,
325
+ "--test",
326
+ "--test-isolation=none",
327
+ `--test-timeout=${TEST_TIMEOUT_MS}`,
328
+ "--test-reporter=./reporter.mjs",
329
+ ...runnable.map((test) => test.path.replace(/\.ts$/, ".js"))
330
+ ],
331
+ {
332
+ cwd: root,
333
+ env: { TZ: "UTC" },
334
+ encoding: "utf8",
335
+ timeout: RUN_TIMEOUT_MS,
336
+ maxBuffer: 16 * 1024 * 1024
337
+ }
338
+ );
339
+ if (run.error !== void 0 && run.error.code !== "ETIMEDOUT") {
340
+ throw run.error;
341
+ }
342
+ const results = parseResults(run.stdout ?? "");
343
+ const timedOut = run.error?.code === "ETIMEDOUT" || run.signal !== null;
344
+ const testResults = runnable.map((test) => {
345
+ const file = join(root, test.path.replace(/\.ts$/, ".js"));
346
+ const own = results.filter((result) => result.file === file);
347
+ for (const result of own) {
348
+ if (!result.ok) {
349
+ const node = testCallNode(test.ast, result.leaf);
350
+ diagnostics.push(
351
+ diagnosticAt(test.path, node, `Test "${result.name}" failed: ${result.message}`, {
352
+ stage: subject.stage
353
+ })
354
+ );
355
+ }
356
+ }
357
+ if (timedOut) {
358
+ diagnostics.push(
359
+ diagnostic(
360
+ test.path,
361
+ 1,
362
+ 1,
363
+ `The ${subject.noun} tests did not finish in ${RUN_TIMEOUT_MS / 1e3} seconds`,
364
+ { stage: subject.stage }
365
+ )
366
+ );
367
+ } else if (own.length === 0 && run.status !== 0) {
368
+ diagnostics.push(
369
+ diagnostic(
370
+ test.path,
371
+ 1,
372
+ 1,
373
+ `The ${subject.noun} tests did not run: ${(run.stderr ?? "").trim().split("\n")[0] || `exit code ${run.status}`}`,
374
+ { stage: subject.stage }
375
+ )
376
+ );
377
+ }
378
+ return {
379
+ path: test.path,
380
+ [subject.noun]: test.script,
381
+ passed: own.filter((result) => result.ok).length,
382
+ failed: own.filter((result) => !result.ok).length,
383
+ results: own.map((result) => ({
384
+ name: result.name,
385
+ ok: result.ok,
386
+ message: result.message
387
+ }))
388
+ };
389
+ });
390
+ return { testResults, diagnostics };
391
+ } finally {
392
+ rmSync(root, { recursive: true, force: true });
393
+ }
394
+ }
395
+
396
+ // scripts/lib/runtime-build/workflows.mjs
397
+ function workflowAppImports(root, path, ast, diagnostics) {
398
+ if (root === null) {
399
+ return { imports: [], modules: /* @__PURE__ */ new Map() };
400
+ }
401
+ try {
402
+ const imports = appImportsOf(root, path, ast);
403
+ return { imports, modules: appModuleClosure(root, imports, new Set(PROFILES.workflow.imports)) };
404
+ } catch (error) {
405
+ diagnostics.push({ ...diagnosticFromError(path, error), stage: WORKFLOW_STAGE });
406
+ return { imports: [], modules: /* @__PURE__ */ new Map() };
407
+ }
408
+ }
409
+ function scriptTests({ root, files, built, answer, tests, subject }) {
410
+ if (tests.length === 0) {
411
+ return { testResults: [], diagnostics: [] };
412
+ }
413
+ const scripts = files.map((file) => {
414
+ const source = readFileSync(join2(root, file.path), "utf8");
415
+ return source === file.source ? file : { path: file.path, source, ast: parseSource(source, { jsx: false }) };
416
+ });
417
+ const appModules = /* @__PURE__ */ new Map();
418
+ for (const { path, ast } of scripts) {
419
+ for (const [modulePath, module] of workflowAppImports(root, path, ast, []).modules) {
420
+ appModules.set(modulePath, module);
421
+ }
422
+ }
423
+ let runnable = tests;
424
+ if (answer.assetsFailed) {
425
+ runnable = testsNotReaching(runnable, new Set(answer.assetReaders), root, GENERATED_ASSETS_PATH);
426
+ }
427
+ if (answer.notificationsIncomplete) {
428
+ runnable = testsNotReaching(runnable, new Set(answer.notificationReaders), root, GENERATED_NOTIFICATION_TYPES_PATH);
429
+ }
430
+ return runScriptTests({
431
+ tests: runnable,
432
+ scripts: scripts.map((script, index) => ({ ...script, compiled: built[index].compiled })),
433
+ root,
434
+ appModules,
435
+ subject
436
+ });
437
+ }
438
+ function runBuildTests(root, tests) {
439
+ const read = (path) => {
440
+ const source = readFileSync(join2(root, path), "utf8");
441
+ return { path, source, ast: parseSource(source, { jsx: false }) };
442
+ };
443
+ const run = (files, testFiles, answer, subject) => scriptTests({
444
+ root,
445
+ files: files.map(read),
446
+ built: answer?.files ?? [],
447
+ answer: { ...answer, assetsFailed: tests.assetsFailed },
448
+ tests: testFiles.map(read),
449
+ subject
450
+ });
451
+ const workflowRun = run(tests.workflows, tests.workflowTests, tests.workflowAnswer, WORKFLOW_TEST_SUBJECT);
452
+ const migrationRun = run(tests.migrations, tests.migrationTests, tests.migrationAnswer, MIGRATION_TEST_SUBJECT);
453
+ return {
454
+ workflowTests: workflowRun.testResults,
455
+ workflowDiagnostics: workflowRun.diagnostics,
456
+ migrationTests: migrationRun.testResults,
457
+ migrationDiagnostics: migrationRun.diagnostics
458
+ };
459
+ }
460
+ export {
461
+ runBuildTests
462
+ };