@diagonal-hq/cli 0.12.3 → 0.12.5

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.
package/dist/cli.mjs CHANGED
@@ -300015,6 +300015,7 @@ function derivedPageKey(path) {
300015
300015
  var COMPONENT_NAME_PATTERN = /^[A-Z][A-Za-z0-9]*$/;
300016
300016
  var PAGE_AUTHORIZERS = /* @__PURE__ */ new Set(["authenticated"]);
300017
300017
  var PAGE_KEYS = /* @__PURE__ */ new Set([
300018
+ "uid",
300018
300019
  "key",
300019
300020
  "route",
300020
300021
  "name",
@@ -300524,1910 +300525,1917 @@ function pageKeyOf(path, ast) {
300524
300525
  }
300525
300526
  }
300526
300527
 
300527
- // scripts/lib/runtime-build/workflow-tests.mjs
300528
- init_define_globalThis_DIAGONAL_SDK_RUNTIME();
300529
- var import_typescript2 = __toESM(require_typescript(), 1);
300530
- import { spawnSync } from "node:child_process";
300531
- import { mkdirSync, mkdtempSync, realpathSync as realpathSync2, rmSync, writeFileSync as writeFileSync3 } from "node:fs";
300532
- import { tmpdir } from "node:os";
300533
- import { dirname as dirname4, join as join9, relative as relative3 } from "node:path";
300534
-
300535
- // scripts/lib/runtime-build/script-sdk.mjs
300528
+ // scripts/lib/runtime-build/workflow-config.mjs
300536
300529
  init_define_globalThis_DIAGONAL_SDK_RUNTIME();
300537
- import { readFileSync as readFileSync6, readdirSync as readdirSync2, statSync as statSync3 } from "node:fs";
300538
- import { createRequire } from "node:module";
300539
- import { dirname as dirname3, join as join8, relative as relative2, resolve as resolve4 } from "node:path";
300540
- import { fileURLToPath } from "node:url";
300541
- var SCRIPT_SDK_ROOT = resolve4(
300542
- dirname3(fileURLToPath(import.meta.url)),
300543
- "../../../packages/workflows/src"
300544
- );
300545
- var SDK_RUNTIME_ENTRY_POINTS = {
300546
- workflow: join8(SCRIPT_SDK_ROOT, "index.ts"),
300547
- testing: join8(SCRIPT_SDK_ROOT, "testing/index.ts")
300530
+ var WORKFLOW_STAGE = "workflow";
300531
+ var UUID_PATTERN2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
300532
+ var ROUTE_PATTERN = /^\/[a-z0-9\-_/{}]*$/;
300533
+ var ROUTE_PARAM_PATTERN = /\{([^}]+)\}/g;
300534
+ var CRON_FIELD_PATTERN = /^[0-9A-Za-z*/,\-?#]+$/;
300535
+ var OFFSET_PATTERN = /^[+-]P(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?)?$/i;
300536
+ var WORKFLOW_PATH_PATTERN = /^workflows\/[^/]+\.ts$/;
300537
+ var CONFIG_KEYS = /* @__PURE__ */ new Set(["uid", "title", "description", "trigger", "runAs", "authorizer"]);
300538
+ var HTTP_METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE"];
300539
+ var RECORD_EVENTS = ["created", "updated", "deleted", "restored", "saved"];
300540
+ var LIFECYCLE_HOOKS = ["creating", "updating", "saving", "deleting", "restoring"];
300541
+ var WORKFLOW_EVENTS = ["execution.success", "execution.error", "execution.exception"];
300542
+ var SCHEDULE_FIELD_TYPES = /* @__PURE__ */ new Set(["date", "datetime"]);
300543
+ var TRIGGERS = {
300544
+ request: {
300545
+ type: "request",
300546
+ keys: ["type", "path", "method"],
300547
+ background: false,
300548
+ sync: true
300549
+ },
300550
+ recordEvent: {
300551
+ type: "event.record",
300552
+ keys: ["type", "resource", "event", "filters"],
300553
+ background: true,
300554
+ sync: false
300555
+ },
300556
+ recordLifecycle: {
300557
+ type: "lifecycle.record",
300558
+ keys: ["type", "resource", "hook"],
300559
+ background: false,
300560
+ sync: true
300561
+ },
300562
+ recordSchedule: {
300563
+ type: "schedule.record",
300564
+ keys: ["type", "resource", "dateField", "offsets"],
300565
+ background: true,
300566
+ sync: false
300567
+ },
300568
+ scheduled: {
300569
+ type: "scheduled",
300570
+ keys: ["type", "expression"],
300571
+ background: true,
300572
+ sync: false
300573
+ },
300574
+ workflowEvent: {
300575
+ type: "event.workflow",
300576
+ keys: ["type", "workflow", "event"],
300577
+ background: true,
300578
+ sync: false
300579
+ },
300580
+ manual: {
300581
+ type: "manual",
300582
+ keys: ["type"],
300583
+ background: false,
300584
+ sync: true
300585
+ }
300548
300586
  };
300549
- function walk(directory) {
300550
- return readdirSync2(directory).flatMap(
300551
- (name) => statSync3(join8(directory, name)).isDirectory() ? walk(join8(directory, name)) : [join8(directory, name)]
300552
- );
300587
+ function unwrap(node) {
300588
+ let current = node;
300589
+ while (current.type === "TSAsExpression" || current.type === "TSSatisfiesExpression" || current.type === "TSNonNullExpression" || current.type === "ParenthesizedExpression") {
300590
+ current = current.expression;
300591
+ }
300592
+ return current;
300553
300593
  }
300554
- function readSandboxSdkFiles() {
300555
- return Object.fromEntries(
300556
- walk(SCRIPT_SDK_ROOT).filter(
300557
- (file2) => file2.endsWith(".ts") && !file2.includes("/testing/") && !file2.endsWith("/http-transport.ts") && !file2.endsWith("/workspace.generated.ts")
300558
- ).map((file2) => [`/sdk/${relative2(SCRIPT_SDK_ROOT, file2)}`, readFileSync6(file2, "utf8")])
300559
- );
300594
+ function propertyNodes(node) {
300595
+ const unwrapped = node === void 0 ? null : unwrap(node);
300596
+ const nodes = /* @__PURE__ */ new Map();
300597
+ if (unwrapped?.type !== "ObjectExpression") {
300598
+ return nodes;
300599
+ }
300600
+ for (const property of unwrapped.properties) {
300601
+ if (property.type === "ObjectProperty") {
300602
+ nodes.set(propertyKey(property), property);
300603
+ }
300604
+ }
300605
+ return nodes;
300560
300606
  }
300561
- function bundleSdkRuntime(buildSync) {
300562
- const result = buildSync({
300563
- entryPoints: SDK_RUNTIME_ENTRY_POINTS,
300564
- outdir: "/sdk",
300565
- bundle: true,
300566
- splitting: true,
300567
- platform: "node",
300568
- target: "node24",
300569
- format: "esm",
300570
- write: false,
300571
- logLevel: "silent"
300572
- });
300573
- return Object.fromEntries(
300574
- result.outputFiles.map((file2) => [relative2("/sdk", file2.path), file2.text])
300575
- );
300607
+ function listOf(values) {
300608
+ return values.map((value) => `'${value}'`).join(", ");
300576
300609
  }
300577
- var sdkFiles;
300578
- try {
300579
- ({ SDK_FILES: sdkFiles } = await Promise.resolve().then(() => (init_sdk_files_generated(), sdk_files_generated_exports)));
300580
- } catch (error) {
300581
- if (error?.code !== "ERR_MODULE_NOT_FOUND") {
300582
- throw error;
300583
- }
300584
- sdkFiles = readSandboxSdkFiles();
300610
+ function blank(text) {
300611
+ return text.replaceAll(/[^\n]/g, " ");
300585
300612
  }
300586
- var SCRIPT_SDK_FILES = sdkFiles;
300587
- var sdkRuntimeFiles = null;
300588
- function scriptSdkRuntimeFiles() {
300589
- sdkRuntimeFiles ??= define_globalThis_DIAGONAL_SDK_RUNTIME_default ?? bundleSdkRuntime(createRequire(import.meta.url)("esbuild").buildSync);
300590
- return sdkRuntimeFiles;
300613
+ function workflowConfigObject(ast) {
300614
+ const statements2 = ast.program.body.filter(isConfigExport);
300615
+ const declarations = statements2[0]?.declaration.declarations ?? [];
300616
+ const init = statements2.length === 1 && declarations.length === 1 ? declarations[0].init : null;
300617
+ const object = init === null || init === void 0 ? null : unwrap(init);
300618
+ return object?.type === "ObjectExpression" ? object : null;
300591
300619
  }
300592
-
300593
- // scripts/lib/runtime-build/workflow-tests.mjs
300594
- var WORKFLOW_TEST_STAGE = "workflow test";
300595
- var WORKFLOW_TEST_SUFFIX = ".test.ts";
300596
- var TEST_TIMEOUT_MS = 1e4;
300597
- var RUN_TIMEOUT_MS = 6e4;
300598
- var RESULT_PREFIX = "\0diagonal-test ";
300599
- var SDK_MODULES = {
300600
- "@diagonal/workflow": "sdk/workflow.js",
300601
- "@diagonal/workflow/testing": "sdk/testing.js",
300602
- "@diagonal/workflow/workspace": "sdk/workspace.js",
300603
- [AUTHORING_MODULE]: "sdk/runtime.js"
300604
- };
300605
- var NODE_TEST_MODULES = /* @__PURE__ */ new Set(["node:test", "node:assert", "node:assert/strict"]);
300606
- var TEST_MODULE_EXTERNALS = /* @__PURE__ */ new Set([...Object.keys(SDK_MODULES), ...NODE_TEST_MODULES]);
300607
- var RELATIVE_WORKFLOW = /^\.\/([^/]+?)(?:\.ts|\.js)?$/;
300608
- var REPORTER_SOURCE = `const PREFIX = ${JSON.stringify(RESULT_PREFIX)};
300609
- export default async function* reporter(source) {
300610
- const names = [];
300611
- for await (const event of source) {
300612
- const data = event.data;
300613
- if (event.type === 'test:start') {
300614
- names.length = data.nesting;
300615
- names.push(data.name);
300620
+ function isConfigExport(statement2) {
300621
+ return statement2.type === "ExportNamedDeclaration" && statement2.declaration?.type === "VariableDeclaration" && statement2.declaration.declarations.some(
300622
+ (declarator) => declarator.id.type === "Identifier" && declarator.id.name === "config"
300623
+ );
300624
+ }
300625
+ function splitWorkflowModule(path, source, ast) {
300626
+ const diagnostics = [];
300627
+ const ranges = [];
300628
+ let configNode = null;
300629
+ let configCount = 0;
300630
+ let hasDefault = false;
300631
+ for (const statement2 of ast.program.body) {
300632
+ if (statement2.type === "ImportDeclaration" && isAuthoringModule(statement2.source.value)) {
300633
+ ranges.push(statement2);
300616
300634
  continue;
300617
300635
  }
300618
- if (event.type !== 'test:pass' && event.type !== 'test:fail') {
300636
+ if (statement2.type === "ExportDefaultDeclaration") {
300637
+ hasDefault = true;
300619
300638
  continue;
300620
300639
  }
300621
- const error = data.details?.error;
300622
- if (data.details?.type === 'suite' && (event.type === 'test:pass' || error?.failureType === 'subtestsFailed')) {
300640
+ if (!isConfigExport(statement2)) {
300623
300641
  continue;
300624
300642
  }
300625
- const path = [...names.slice(0, data.nesting), data.name].join(' > ');
300626
- const cause = error?.cause ?? error;
300627
- yield PREFIX + JSON.stringify({
300628
- file: data.file ?? null,
300629
- name: path,
300630
- leaf: data.name,
300631
- ok: event.type === 'test:pass',
300632
- message: event.type === 'test:pass' ? null : String(cause?.message ?? cause ?? 'The test failed').trim()
300633
- }) + '\\n';
300634
- }
300635
- }
300636
- `;
300637
- function moduleSpecifierNodes(ast) {
300638
- return ast.program.body.filter(
300639
- (statement2) => (statement2.type === "ImportDeclaration" || statement2.type === "ExportNamedDeclaration" || statement2.type === "ExportAllDeclaration") && statement2.source
300640
- ).map((statement2) => statement2.source);
300641
- }
300642
- function transpile(path, source, ast, resolveSpecifier) {
300643
- let rewritten = source;
300644
- for (const node of moduleSpecifierNodes(ast).toSorted(
300645
- (left, right) => right.start - left.start
300646
- )) {
300647
- const target = resolveSpecifier(node.value);
300648
- if (target !== null) {
300649
- rewritten = `${rewritten.slice(0, node.start)}${JSON.stringify(target)}${rewritten.slice(node.end)}`;
300643
+ configCount++;
300644
+ ranges.push(statement2);
300645
+ const declaration = statement2.declaration;
300646
+ if (configCount > 1) {
300647
+ diagnostics.push(
300648
+ diagnosticAt(path, statement2, "A workflow can export only one config", {
300649
+ stage: WORKFLOW_STAGE
300650
+ })
300651
+ );
300652
+ continue;
300650
300653
  }
300651
- }
300652
- return import_typescript2.default.transpileModule(rewritten, {
300653
- fileName: path,
300654
- compilerOptions: {
300655
- target: import_typescript2.default.ScriptTarget.ES2023,
300656
- module: import_typescript2.default.ModuleKind.ESNext,
300657
- sourceMap: false
300654
+ if (declaration.kind !== "const" || declaration.declarations.length !== 1) {
300655
+ diagnostics.push(
300656
+ diagnosticAt(
300657
+ path,
300658
+ statement2,
300659
+ "Declare the config alone as `export const config = { ... }`",
300660
+ { stage: WORKFLOW_STAGE }
300661
+ )
300662
+ );
300663
+ continue;
300658
300664
  }
300659
- }).outputText;
300660
- }
300661
- function sdkSpecifier(fromDirectory) {
300662
- return (specifier) => Object.hasOwn(SDK_MODULES, specifier) ? `${fromDirectory}${SDK_MODULES[specifier]}` : null;
300663
- }
300664
- function testCallNode(ast, name) {
300665
- const pending = [ast.program];
300666
- while (pending.length > 0) {
300667
- const node = pending.pop();
300668
- const [first] = node.type === "CallExpression" ? node.arguments : [];
300669
- 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) {
300670
- return node;
300665
+ const init = declaration.declarations[0].init;
300666
+ if (init === null || init === void 0) {
300667
+ diagnostics.push(
300668
+ diagnosticAt(path, statement2, "The config needs a value", { stage: WORKFLOW_STAGE })
300669
+ );
300670
+ continue;
300671
300671
  }
300672
- pending.push(...childNodes(node));
300672
+ configNode = init;
300673
300673
  }
300674
- return null;
300675
- }
300676
- function importDiagnostics(test, workflowNames, workspaceRoot) {
300677
- const diagnostics = [];
300678
- for (const node of moduleSpecifierNodes(test.ast)) {
300679
- const specifier = node.value;
300680
- const relative5 = RELATIVE_WORKFLOW.exec(specifier);
300681
- if (NODE_TEST_MODULES.has(specifier) || Object.hasOwn(SDK_MODULES, specifier) || relative5 !== null && workflowNames.has(relative5[1]) || isAppSpecifier(specifier) && workspaceRoot !== null && resolveAppSpecifier(workspaceRoot, specifier) !== null) {
300682
- continue;
300683
- }
300674
+ if (configCount === 0) {
300684
300675
  diagnostics.push(
300685
300676
  diagnosticAt(
300686
- test.path,
300687
- node,
300688
- `A workflow test can import only node:test, node:assert, @diagonal/workflow, @diagonal/workflow/testing, @diagonal/workflow/workspace, the workflows in workflows/, and workspace files by @app/. "${specifier}" is not one of them`,
300689
- { stage: WORKFLOW_TEST_STAGE }
300677
+ path,
300678
+ null,
300679
+ "The workflow has no config. Add `export const config = { title, trigger }`",
300680
+ { stage: WORKFLOW_STAGE }
300690
300681
  )
300691
300682
  );
300692
300683
  }
300693
- return diagnostics;
300694
- }
300695
- function sandboxPath(path) {
300696
- return path.replace(/\.(ts|tsx|js|jsx)$/, ".js");
300697
- }
300698
- function sandboxPrefix(path) {
300699
- return "../".repeat(path.split("/").length - 1) || "./";
300700
- }
300701
- function relativeSandboxPath(from, target) {
300702
- const path = relative3(dirname4(from), sandboxPath(target));
300703
- return path.startsWith(".") ? path : `./${path}`;
300704
- }
300705
- function writeFile(root, path, content) {
300706
- mkdirSync(dirname4(join9(root, path)), { recursive: true });
300707
- writeFileSync3(join9(root, path), content);
300708
- }
300709
- function parseResults(stdout) {
300710
- return stdout.split("\n").filter((line) => line.startsWith(RESULT_PREFIX)).map((line) => JSON.parse(line.slice(RESULT_PREFIX.length)));
300684
+ if (!hasDefault) {
300685
+ diagnostics.push(
300686
+ diagnosticAt(
300687
+ path,
300688
+ null,
300689
+ "The workflow has no default export. Add `export default defineWorkflow(...)`",
300690
+ { stage: WORKFLOW_STAGE }
300691
+ )
300692
+ );
300693
+ }
300694
+ let scriptSource = source;
300695
+ for (const node of ranges.toSorted((left, right) => right.start - left.start)) {
300696
+ scriptSource = scriptSource.slice(0, node.start) + blank(scriptSource.slice(node.start, node.end)) + scriptSource.slice(node.end);
300697
+ }
300698
+ return { configNode, scriptSource, diagnostics };
300711
300699
  }
300712
- function runWorkflowTests({
300713
- tests,
300714
- workflows,
300715
- root: workspaceRoot = null,
300716
- appModules = /* @__PURE__ */ new Map()
300717
- }) {
300700
+ function readWorkflowConfig(path, configNode, context) {
300718
300701
  const diagnostics = [];
300719
- const workflowNames = new Map(
300720
- workflows.map((workflow) => [workflow.path.slice("workflows/".length, -".ts".length), workflow])
300721
- );
300722
- const runnable = [];
300723
- for (const test of tests) {
300724
- const workflowPath = `${test.path.slice(0, -WORKFLOW_TEST_SUFFIX.length)}.ts`;
300725
- if (!workflowNames.has(workflowPath.slice("workflows/".length, -".ts".length))) {
300726
- diagnostics.push(
300727
- diagnosticAt(
300728
- test.path,
300729
- null,
300730
- `The test file has no workflow. Add ${workflowPath} or remove the test file`,
300731
- { stage: WORKFLOW_TEST_STAGE }
300732
- )
300733
- );
300734
- continue;
300702
+ const report = (node, message) => diagnostics.push(diagnosticAt(path, node, message, { stage: WORKFLOW_STAGE }));
300703
+ let value;
300704
+ try {
300705
+ value = staticValue(configNode, { resources: context.resourcesBinding });
300706
+ } catch (error) {
300707
+ if (!(error instanceof SourceError)) {
300708
+ throw error;
300735
300709
  }
300736
- const imports = importDiagnostics(test, workflowNames, workspaceRoot);
300737
- diagnostics.push(...imports);
300738
- if (imports.length === 0) {
300739
- runnable.push({ ...test, workflow: workflowPath });
300710
+ report(error.node, error.message);
300711
+ return { config: null, diagnostics };
300712
+ }
300713
+ if (!isPlainObject(value)) {
300714
+ report(configNode, "The config must be an object literal");
300715
+ return { config: null, diagnostics };
300716
+ }
300717
+ const nodes = propertyNodes(configNode);
300718
+ const at = (key) => nodes.get(key) ?? configNode;
300719
+ for (const key of Object.keys(value)) {
300720
+ if (!CONFIG_KEYS.has(key)) {
300721
+ report(at(key), `Unknown workflow config option "${key}"`);
300740
300722
  }
300741
300723
  }
300742
- if (runnable.length === 0) {
300743
- return { workflowTests: [], diagnostics };
300724
+ const title = value.title;
300725
+ if (typeof title !== "string" || title.trim() === "") {
300726
+ report(at("title"), '"title" is required and must be a non-empty string');
300744
300727
  }
300745
- const modules = new Map(appModules);
300746
- for (const test of runnable) {
300747
- for (const [path, module] of appModuleClosure(
300748
- workspaceRoot,
300749
- workspaceRoot === null ? [] : appImportsOf(workspaceRoot, test.path, test.ast),
300750
- TEST_MODULE_EXTERNALS
300751
- )) {
300752
- modules.set(path, module);
300728
+ const description = value.description ?? null;
300729
+ if (description !== null && typeof description !== "string") {
300730
+ report(at("description"), '"description" must be a string');
300731
+ }
300732
+ const scoped = { ...context, path };
300733
+ const trigger = readTrigger(value.trigger, at("trigger"), scoped, report);
300734
+ const runAs = trigger === null ? null : readRunAs(value.runAs, at("runAs"), trigger, scoped, report);
300735
+ const authorizer = readAuthorizer(value.authorizer, at("authorizer"), trigger, report);
300736
+ if (diagnostics.length > 0 || trigger === null) {
300737
+ return { config: null, diagnostics };
300738
+ }
300739
+ return {
300740
+ config: {
300741
+ title,
300742
+ description,
300743
+ type: trigger.definition.type,
300744
+ settings: trigger.settings,
300745
+ run_as: runAs,
300746
+ authorizer,
300747
+ execution_mode: trigger.definition.sync ? "sync" : "async"
300748
+ },
300749
+ diagnostics
300750
+ };
300751
+ }
300752
+ function resolveResource(reference, node, context, report) {
300753
+ if (typeof reference !== "string" || reference === "") {
300754
+ report(node, '"resource" must be Resources.<Name>.slug');
300755
+ return null;
300756
+ }
300757
+ const resource = context.findResource(reference);
300758
+ if (resource === void 0) {
300759
+ if (context.reportUnknownResources) {
300760
+ report(node, referenceProblem(reference, context.resources, context.names).message);
300753
300761
  }
300762
+ return null;
300754
300763
  }
300755
- const root = realpathSync2(mkdtempSync(join9(tmpdir(), "diagonal-workflow-tests-")));
300756
- try {
300757
- writeFile(root, "package.json", '{"type":"module"}\n');
300758
- writeFile(root, "reporter.mjs", REPORTER_SOURCE);
300759
- for (const [path, content] of Object.entries(scriptSdkRuntimeFiles())) {
300760
- writeFile(root, `sdk/${path}`, content);
300764
+ return resource;
300765
+ }
300766
+ function oneOf(trigger, key, allowed, at, report) {
300767
+ const item = trigger[key];
300768
+ if (!allowed.includes(item)) {
300769
+ report(at(key), `"${key}" must be one of: ${listOf(allowed)}`);
300770
+ return null;
300771
+ }
300772
+ return item;
300773
+ }
300774
+ function readTrigger(trigger, triggerNode, context, report) {
300775
+ if (!isPlainObject(trigger)) {
300776
+ report(triggerNode, `"trigger" is required: { type: ${listOf(Object.keys(TRIGGERS))}, ... }`);
300777
+ return null;
300778
+ }
300779
+ const nodes = propertyNodes(triggerNode.value ?? triggerNode);
300780
+ const at = (key) => nodes.get(key) ?? triggerNode;
300781
+ const definition = Object.hasOwn(TRIGGERS, trigger.type) ? TRIGGERS[trigger.type] : void 0;
300782
+ if (definition === void 0) {
300783
+ report(at("type"), `"trigger.type" must be one of: ${listOf(Object.keys(TRIGGERS))}`);
300784
+ return null;
300785
+ }
300786
+ let failed = false;
300787
+ const fail = (node, message) => {
300788
+ failed = true;
300789
+ report(node, message);
300790
+ };
300791
+ for (const key of Object.keys(trigger)) {
300792
+ if (!definition.keys.includes(key)) {
300793
+ fail(at(key), `A ${trigger.type} trigger has no option "${key}"`);
300761
300794
  }
300762
- writeFile(root, "sdk/workspace.js", "export {};\n");
300763
- writeFile(root, "sdk/runtime.js", AUTHORING_HELPERS_MODULE);
300764
- for (const [path, module] of modules) {
300765
- const resolveSdk = sdkSpecifier(sandboxPrefix(path));
300766
- writeFile(
300767
- root,
300768
- sandboxPath(path),
300769
- transpile(
300770
- path,
300771
- module.source,
300772
- parseSource(module.source, { jsx: path.endsWith("x") }),
300773
- (specifier) => module.requires[specifier] === void 0 ? resolveSdk(specifier) : relativeSandboxPath(path, module.requires[specifier])
300774
- )
300775
- );
300795
+ }
300796
+ const settings = triggerSettings(trigger, at, context, fail);
300797
+ return failed || settings === null ? null : { definition, name: trigger.type, settings };
300798
+ }
300799
+ function triggerSettings(trigger, at, context, fail) {
300800
+ switch (trigger.type) {
300801
+ case "request": {
300802
+ const path = trigger.path;
300803
+ if (typeof path !== "string" || !ROUTE_PATTERN.test(path) || path.length > 255) {
300804
+ fail(
300805
+ at("path"),
300806
+ '"path" must start with "/" and contain only a-z, 0-9, -, _, /, and {param}'
300807
+ );
300808
+ return null;
300809
+ }
300810
+ const method = trigger.method === void 0 ? "GET" : oneOf(trigger, "method", HTTP_METHODS, at, fail);
300811
+ if (method === null) {
300812
+ return null;
300813
+ }
300814
+ const params = [...path.matchAll(ROUTE_PARAM_PATTERN)].map((match) => ({
300815
+ key: match[1],
300816
+ scope: null,
300817
+ relations: [],
300818
+ resource_id: null,
300819
+ lookup_field: null
300820
+ }));
300821
+ return { route: path, method, params };
300776
300822
  }
300777
- for (const workflow of workflows) {
300778
- writeFile(
300779
- root,
300780
- workflow.path.replace(/\.ts$/, ".js"),
300781
- transpile(workflow.path, workflow.source, workflow.ast, (specifier) => {
300782
- const target = isAppSpecifier(specifier) && workspaceRoot !== null ? resolveAppSpecifier(workspaceRoot, specifier) : null;
300783
- return target === null ? sdkSpecifier("../")(specifier) : relativeSandboxPath(workflow.path, target);
300784
- })
300785
- );
300823
+ case "recordEvent": {
300824
+ const resource = resolveResource(trigger.resource, at("resource"), context, fail);
300825
+ const event = oneOf(trigger, "event", RECORD_EVENTS, at, fail);
300826
+ if (trigger.filters !== void 0 && trigger.filters !== null && typeof trigger.filters !== "object") {
300827
+ fail(at("filters"), '"filters" must be a filter object');
300828
+ }
300829
+ if (resource === null || event === null) {
300830
+ return null;
300831
+ }
300832
+ return trigger.filters === void 0 ? { event, resource: resource.slug } : { event, resource: resource.slug, filters: trigger.filters };
300786
300833
  }
300787
- for (const test of runnable) {
300788
- const resolveSdk = sdkSpecifier("../");
300789
- writeFile(
300790
- root,
300791
- test.path.replace(/\.ts$/, ".js"),
300792
- transpile(test.path, test.source, test.ast, (specifier) => {
300793
- const relative5 = RELATIVE_WORKFLOW.exec(specifier);
300794
- const target = isAppSpecifier(specifier) && workspaceRoot !== null ? resolveAppSpecifier(workspaceRoot, specifier) : null;
300795
- if (target !== null) {
300796
- return relativeSandboxPath(test.path, target);
300797
- }
300798
- return relative5 !== null ? `./${relative5[1]}.js` : resolveSdk(specifier);
300799
- })
300800
- );
300834
+ case "recordLifecycle": {
300835
+ const resource = resolveResource(trigger.resource, at("resource"), context, fail);
300836
+ const hook = oneOf(trigger, "hook", LIFECYCLE_HOOKS, at, fail);
300837
+ return resource === null || hook === null ? null : { hook, resource: resource.slug };
300801
300838
  }
300802
- const run = spawnSync(
300803
- process.execPath,
300804
- [
300805
- "--permission",
300806
- `--allow-fs-read=${root}`,
300807
- "--test",
300808
- "--test-isolation=none",
300809
- `--test-timeout=${TEST_TIMEOUT_MS}`,
300810
- "--test-reporter=./reporter.mjs",
300811
- ...runnable.map((test) => test.path.replace(/\.ts$/, ".js"))
300812
- ],
300813
- {
300814
- cwd: root,
300815
- env: { TZ: "UTC" },
300816
- encoding: "utf8",
300817
- timeout: RUN_TIMEOUT_MS,
300818
- maxBuffer: 16 * 1024 * 1024
300839
+ case "recordSchedule": {
300840
+ const resource = resolveResource(trigger.resource, at("resource"), context, fail);
300841
+ const offsets = readOffsets(trigger.offsets, at("offsets"), fail);
300842
+ const dateField = trigger.dateField;
300843
+ if (typeof dateField !== "string" || dateField === "") {
300844
+ fail(at("dateField"), '"dateField" must be the key of a date or datetime field');
300845
+ return null;
300819
300846
  }
300820
- );
300821
- if (run.error !== void 0 && run.error.code !== "ETIMEDOUT") {
300822
- throw run.error;
300823
- }
300824
- const results = parseResults(run.stdout ?? "");
300825
- const timedOut = run.error?.code === "ETIMEDOUT" || run.signal !== null;
300826
- const workflowTests = runnable.map((test) => {
300827
- const file2 = join9(root, test.path.replace(/\.ts$/, ".js"));
300828
- const own = results.filter((result) => result.file === file2);
300829
- for (const result of own) {
300830
- if (!result.ok) {
300831
- const node = testCallNode(test.ast, result.leaf);
300832
- diagnostics.push(
300833
- diagnosticAt(test.path, node, `Test "${result.name}" failed: ${result.message}`, {
300834
- stage: WORKFLOW_TEST_STAGE
300835
- })
300847
+ if (resource !== null && resource.platform !== true) {
300848
+ const field2 = resource.fields.find((item) => item.key === dateField);
300849
+ if (field2 === void 0 || !SCHEDULE_FIELD_TYPES.has(field2.type)) {
300850
+ fail(
300851
+ at("dateField"),
300852
+ `"${dateField}" is not a date or datetime field of resource "${resource.slug}"`
300836
300853
  );
300854
+ return null;
300837
300855
  }
300838
300856
  }
300839
- if (timedOut) {
300840
- diagnostics.push(
300841
- diagnostic(
300842
- test.path,
300843
- 1,
300844
- 1,
300845
- `The workflow tests did not finish in ${RUN_TIMEOUT_MS / 1e3} seconds`,
300846
- { stage: WORKFLOW_TEST_STAGE }
300847
- )
300857
+ return resource === null || offsets === null ? null : { schedule: { offsets }, date_field: dateField, resource: resource.slug };
300858
+ }
300859
+ case "scheduled": {
300860
+ const expression2 = trigger.expression;
300861
+ const fields = typeof expression2 === "string" ? expression2.trim().split(/\s+/) : [];
300862
+ if (fields.length !== 5 || !fields.every((field2) => CRON_FIELD_PATTERN.test(field2))) {
300863
+ fail(
300864
+ at("expression"),
300865
+ '"expression" must be a cron expression with 5 fields, for example "0 2 * * *"'
300848
300866
  );
300849
- } else if (own.length === 0 && run.status !== 0) {
300850
- diagnostics.push(
300851
- diagnostic(
300852
- test.path,
300853
- 1,
300854
- 1,
300855
- `The workflow tests did not run: ${(run.stderr ?? "").trim().split("\n")[0] || `exit code ${run.status}`}`,
300856
- { stage: WORKFLOW_TEST_STAGE }
300857
- )
300867
+ return null;
300868
+ }
300869
+ return { expression: expression2 };
300870
+ }
300871
+ case "workflowEvent": {
300872
+ const workflow = trigger.workflow;
300873
+ const event = oneOf(trigger, "event", WORKFLOW_EVENTS, at, fail);
300874
+ if (typeof workflow !== "string" || !WORKFLOW_PATH_PATTERN.test(workflow)) {
300875
+ fail(
300876
+ at("workflow"),
300877
+ '"workflow" must be the path of a workflow, for example "workflows/welcome.ts"'
300858
300878
  );
300879
+ return null;
300859
300880
  }
300860
- return {
300861
- path: test.path,
300862
- workflow: test.workflow,
300863
- passed: own.filter((result) => result.ok).length,
300864
- failed: own.filter((result) => !result.ok).length,
300865
- results: own.map((result) => ({
300866
- name: result.name,
300867
- ok: result.ok,
300868
- message: result.message
300869
- }))
300870
- };
300871
- });
300872
- return { workflowTests, diagnostics };
300873
- } finally {
300874
- rmSync(root, { recursive: true, force: true });
300875
- }
300876
- }
300877
-
300878
- // scripts/lib/runtime-build/workflows.mjs
300879
- init_define_globalThis_DIAGONAL_SDK_RUNTIME();
300880
-
300881
- // scripts/lib/workflow-script/compile.mjs
300882
- init_define_globalThis_DIAGONAL_SDK_RUNTIME();
300883
- var import_typescript7 = __toESM(require_typescript(), 1);
300884
-
300885
- // scripts/lib/workflow-script/ast.mjs
300886
- init_define_globalThis_DIAGONAL_SDK_RUNTIME();
300887
- var import_typescript3 = __toESM(require_typescript(), 1);
300888
- function unwrap(node) {
300889
- let current = node;
300890
- while (import_typescript3.default.isParenthesizedExpression(current) || import_typescript3.default.isAsExpression(current) || import_typescript3.default.isSatisfiesExpression(current)) {
300891
- current = current.expression;
300881
+ if (!context.workflowPaths.has(workflow)) {
300882
+ fail(at("workflow"), `Unknown workflow "${workflow}". Add the file or change the path`);
300883
+ return null;
300884
+ }
300885
+ if (workflow === context.path) {
300886
+ fail(at("workflow"), "A workflow cannot trigger on its own runs");
300887
+ return null;
300888
+ }
300889
+ return event === null ? null : { event, workflow: { path: workflow } };
300890
+ }
300891
+ case "manual":
300892
+ return {};
300893
+ default:
300894
+ return null;
300892
300895
  }
300893
- return current;
300894
300896
  }
300895
- function propertyNameText(name) {
300896
- return import_typescript3.default.isIdentifier(name) || import_typescript3.default.isStringLiteral(name) ? name.text : null;
300897
- }
300898
-
300899
- // scripts/lib/workflow-script/input-schema.mjs
300900
- init_define_globalThis_DIAGONAL_SDK_RUNTIME();
300901
- var import_typescript4 = __toESM(require_typescript(), 1);
300902
- var SDK_MODULE = "@diagonal/workflow";
300903
- var SCALAR_KINDS = /* @__PURE__ */ new Set([
300904
- "text",
300905
- "email",
300906
- "url",
300907
- "uuid",
300908
- "phone",
300909
- "date",
300910
- "datetime",
300911
- "time",
300912
- "timezone",
300913
- "color",
300914
- "number",
300915
- "integer",
300916
- "money",
300917
- "boolean"
300918
- ]);
300919
- var SchemaError = class extends Error {
300920
- constructor(node, message) {
300921
- super(message);
300922
- this.node = node;
300923
- }
300924
- };
300925
- function extractInputSchema(file2, checker) {
300926
- const call = defineWorkflowCall(file2, checker);
300927
- if (call === null || call.arguments.length < 2) {
300928
- return { schema: null, findings: [] };
300897
+ function readOffsets(offsets, node, fail) {
300898
+ if (!Array.isArray(offsets) || offsets.length === 0) {
300899
+ fail(node, `"offsets" must be a list of signed ISO 8601 durations, for example ['-P1D']`);
300900
+ return null;
300929
300901
  }
300930
- try {
300931
- const schema = evaluate2(call.arguments[0], checker, /* @__PURE__ */ new Set());
300932
- if (schema.kind !== "object") {
300933
- throw new SchemaError(call.arguments[0], "The input schema must be v.object({ ... }).");
300934
- }
300935
- return { schema, findings: [] };
300936
- } catch (error) {
300937
- if (error instanceof SchemaError) {
300938
- return {
300939
- schema: null,
300940
- findings: [{ node: error.node, code: "static-input-schema", message: error.message }]
300941
- };
300902
+ for (const offset of offsets) {
300903
+ if (typeof offset !== "string" || !OFFSET_PATTERN.test(offset) || !/\d+[DHM]/i.test(offset)) {
300904
+ fail(
300905
+ node,
300906
+ `Offset ${JSON.stringify(offset)} must be a signed ISO 8601 duration in days, hours, or minutes, for example '-P1D' or '+PT2H'`
300907
+ );
300908
+ return null;
300942
300909
  }
300943
- throw error;
300944
300910
  }
300911
+ if (new Set(offsets).size !== offsets.length) {
300912
+ fail(node, "The offsets must be distinct");
300913
+ return null;
300914
+ }
300915
+ return offsets;
300945
300916
  }
300946
- function defineWorkflowCall(file2, checker) {
300947
- for (const statement2 of file2.statements) {
300948
- if (import_typescript4.default.isExportAssignment(statement2) && import_typescript4.default.isCallExpression(statement2.expression) && import_typescript4.default.isIdentifier(statement2.expression.expression) && sdkImportName(checker, statement2.expression.expression) === "defineWorkflow") {
300949
- return statement2.expression;
300917
+ function readRunAs(runAs, node, trigger, context, report) {
300918
+ const name = trigger.name;
300919
+ if (runAs === void 0 || runAs === null) {
300920
+ if (name === "request") {
300921
+ return { mode: "session" };
300922
+ }
300923
+ if (trigger.definition.background) {
300924
+ report(
300925
+ node,
300926
+ `A ${name} workflow runs in the background and needs an identity. Set runAs to 'system' or { resource, record }`
300927
+ );
300950
300928
  }
300929
+ return null;
300951
300930
  }
300952
- return null;
300953
- }
300954
- function sdkImportName(checker, identifier4) {
300955
- const declaration = checker.getSymbolAtLocation(identifier4)?.declarations?.[0];
300956
- if (declaration === void 0 || !import_typescript4.default.isImportSpecifier(declaration)) {
300931
+ if (name === "recordLifecycle") {
300932
+ report(node, "A recordLifecycle workflow runs inside the record write. Remove runAs");
300957
300933
  return null;
300958
300934
  }
300959
- const specifier = declaration.parent.parent.parent.moduleSpecifier;
300960
- return import_typescript4.default.isStringLiteral(specifier) && specifier.text === SDK_MODULE ? (declaration.propertyName ?? declaration.name).text : null;
300961
- }
300962
- var STATIC_HINT = "Build the input schema from v.* calls with literal arguments, so the platform can validate input before the script runs.";
300963
- function evaluate2(node, checker, visiting) {
300964
- const expression2 = unwrap(node);
300965
- if (import_typescript4.default.isIdentifier(expression2)) {
300966
- const declaration = checker.getSymbolAtLocation(expression2)?.valueDeclaration;
300967
- if (declaration === void 0 || !import_typescript4.default.isVariableDeclaration(declaration) || declaration.initializer === void 0 || !(import_typescript4.default.getCombinedNodeFlags(declaration) & import_typescript4.default.NodeFlags.Const) || !import_typescript4.default.isSourceFile(declaration.parent.parent.parent)) {
300968
- throw new SchemaError(
300969
- expression2,
300970
- `${expression2.text} is not a top-level const. ${STATIC_HINT}`
300935
+ if (runAs === "system") {
300936
+ return { mode: "system" };
300937
+ }
300938
+ if (runAs === "session") {
300939
+ if (name !== "request") {
300940
+ report(
300941
+ node,
300942
+ "runAs 'session' is only for request workflows. Use 'system' or { resource, record }"
300971
300943
  );
300944
+ return null;
300972
300945
  }
300973
- if (visiting.has(declaration)) {
300974
- throw new SchemaError(expression2, `${expression2.text} refers to itself.`);
300975
- }
300976
- visiting.add(declaration);
300977
- const spec = evaluate2(declaration.initializer, checker, visiting);
300978
- visiting.delete(declaration);
300979
- return spec;
300980
- }
300981
- if (!import_typescript4.default.isCallExpression(expression2) || !import_typescript4.default.isPropertyAccessExpression(expression2.expression)) {
300982
- throw new SchemaError(expression2, STATIC_HINT);
300946
+ return { mode: "session" };
300983
300947
  }
300984
- const method = expression2.expression.name.text;
300985
- const receiver = unwrap(expression2.expression.expression);
300986
- if (import_typescript4.default.isIdentifier(receiver) && sdkImportName(checker, receiver) === "v") {
300987
- return builder(method, expression2, checker, visiting);
300948
+ if (!isPlainObject(runAs)) {
300949
+ report(node, "runAs must be 'system', 'session', or { resource, record }");
300950
+ return null;
300988
300951
  }
300989
- return modifier(method, evaluate2(receiver, checker, visiting), expression2);
300990
- }
300991
- var base = (kind, extra = {}) => ({
300992
- kind,
300993
- optional: false,
300994
- nullable: false,
300995
- rules: [],
300996
- ...extra
300997
- });
300998
- function builder(method, call, checker, visiting) {
300999
- const args = call.arguments;
301000
- if (SCALAR_KINDS.has(method)) {
301001
- return base(method);
301002
- }
301003
- switch (method) {
301004
- case "select": {
301005
- const options2 = args[0] && unwrap(args[0]);
301006
- if (!options2 || !import_typescript4.default.isArrayLiteralExpression(options2) || options2.elements.length === 0) {
301007
- throw new SchemaError(call, "v.select() needs a literal array of its options.");
301008
- }
301009
- return base("select", { options: options2.elements.map((element) => literal(element)) });
301010
- }
301011
- case "list":
301012
- if (args.length !== 1) {
301013
- throw new SchemaError(call, "v.list() needs the item field.");
301014
- }
301015
- return base("list", { items: evaluate2(args[0], checker, visiting) });
301016
- case "object": {
301017
- const shape = args[0] && unwrap(args[0]);
301018
- if (!shape || !import_typescript4.default.isObjectLiteralExpression(shape)) {
301019
- throw new SchemaError(call, "v.object() needs an object literal of fields.");
301020
- }
301021
- const fields = {};
301022
- for (const property of shape.properties) {
301023
- if (import_typescript4.default.isPropertyAssignment(property) && (import_typescript4.default.isIdentifier(property.name) || import_typescript4.default.isStringLiteral(property.name))) {
301024
- fields[property.name.text] = evaluate2(property.initializer, checker, visiting);
301025
- } else if (import_typescript4.default.isShorthandPropertyAssignment(property)) {
301026
- fields[property.name.text] = evaluate2(property.name, checker, visiting);
301027
- } else {
301028
- throw new SchemaError(
301029
- property,
301030
- `Each field of v.object() must be a named field. ${STATIC_HINT}`
301031
- );
301032
- }
301033
- }
301034
- return base("object", { fields });
301035
- }
301036
- case "record": {
301037
- const type = args[0] ? checker.getTypeAtLocation(args[0]) : void 0;
301038
- if (!type?.isStringLiteral()) {
301039
- throw new SchemaError(
301040
- call,
301041
- "v.record() needs a resource, such as resources.Products from @diagonal/workflow/workspace or Resources.Products.slug from @app/generated/resources in a file-based workspace."
301042
- );
301043
- }
301044
- return base("record", { resource: type.value });
301045
- }
301046
- case "recordReference": {
301047
- const type = args[0] ? checker.getTypeAtLocation(args[0]) : void 0;
301048
- if (!type?.isStringLiteral()) {
301049
- throw new SchemaError(
301050
- call,
301051
- "v.recordReference() needs a resource, such as resources.Products from @diagonal/workflow/workspace or Resources.Products.slug from @app/generated/resources in a file-based workspace."
301052
- );
301053
- }
301054
- return base("recordReference", {
301055
- resource: type.value,
301056
- ...options(call, args[1], ["scope"])
301057
- });
301058
- }
301059
- case "roleReference":
301060
- return base("roleReference");
301061
- case "file":
301062
- return base("file", options(call, args[0], ["accept", "visibility"]));
301063
- case "content": {
301064
- const content = options(call, args[0], ["multiLine", "extensions", "allowedNodes"]);
301065
- return base("content", Object.keys(content).length === 0 ? {} : { content });
301066
- }
301067
- default:
301068
- throw new SchemaError(call.expression, `v.${method}() is not an input field.`);
301069
- }
301070
- }
301071
- function modifier(method, spec, call) {
301072
- const args = call.arguments;
301073
- const number = (index3) => {
301074
- const value = args[index3] === void 0 ? void 0 : literal(args[index3]);
301075
- if (typeof value !== "number") {
301076
- throw new SchemaError(call, `.${method}() needs number literals.`);
301077
- }
301078
- return value;
301079
- };
301080
- const string = () => {
301081
- const value = args[0] === void 0 ? void 0 : literal(args[0]);
301082
- if (typeof value !== "string") {
301083
- throw new SchemaError(call, `.${method}() needs a string literal.`);
301084
- }
301085
- return value;
301086
- };
301087
- const withRule = (rule) => ({ ...spec, rules: [...spec.rules, rule] });
301088
- switch (method) {
301089
- case "optional":
301090
- return { ...spec, optional: true };
301091
- case "nullable":
301092
- return { ...spec, nullable: true };
301093
- case "min":
301094
- case "max":
301095
- case "size":
301096
- return withRule(`${method}:${number(0)}`);
301097
- case "between":
301098
- return withRule(`between:${number(0)},${number(1)}`);
301099
- case "regex": {
301100
- const pattern = args[0] && unwrap(args[0]);
301101
- if (!pattern || pattern.kind !== import_typescript4.default.SyntaxKind.RegularExpressionLiteral) {
301102
- throw new SchemaError(call, ".regex() needs a regular expression literal.");
301103
- }
301104
- return withRule(`regex:${pattern.text}`);
300952
+ for (const key of Object.keys(runAs)) {
300953
+ if (key !== "resource" && key !== "record") {
300954
+ report(node, `runAs has no option "${key}". Use { resource, record }`);
300955
+ return null;
301105
300956
  }
301106
- case "rule":
301107
- return withRule(string());
301108
- case "label":
301109
- return { ...spec, label: string() };
301110
- case "description":
301111
- return { ...spec, description: string() };
301112
- default:
301113
- throw new SchemaError(call.expression, `.${method}() is not an input field modifier.`);
301114
- }
301115
- }
301116
- function options(call, node, keys2) {
301117
- if (node === void 0) {
301118
- return {};
301119
- }
301120
- const value = literalData(node);
301121
- if (typeof value !== "object" || value === null || Array.isArray(value)) {
301122
- throw new SchemaError(
301123
- node,
301124
- `v.${call.expression.name.text}() needs an object literal of options.`
301125
- );
301126
- }
301127
- const unknown = Object.keys(value).find((key) => !keys2.includes(key));
301128
- if (unknown !== void 0) {
301129
- throw new SchemaError(node, `v.${call.expression.name.text}() has no option "${unknown}".`);
301130
- }
301131
- return value;
301132
- }
301133
- function literalData(node) {
301134
- const expression2 = unwrap(node);
301135
- if (expression2.kind === import_typescript4.default.SyntaxKind.TrueKeyword) {
301136
- return true;
301137
- }
301138
- if (expression2.kind === import_typescript4.default.SyntaxKind.FalseKeyword) {
301139
- return false;
301140
- }
301141
- if (import_typescript4.default.isArrayLiteralExpression(expression2)) {
301142
- return expression2.elements.map((element) => literalData(element));
301143
300957
  }
301144
- if (import_typescript4.default.isObjectLiteralExpression(expression2)) {
301145
- const result = {};
301146
- for (const property of expression2.properties) {
301147
- if (!import_typescript4.default.isPropertyAssignment(property) || !(import_typescript4.default.isIdentifier(property.name) || import_typescript4.default.isStringLiteral(property.name))) {
301148
- throw new SchemaError(
301149
- property,
301150
- `Use a named property with a literal value. ${STATIC_HINT}`
301151
- );
301152
- }
301153
- result[property.name.text] = literalData(property.initializer);
301154
- }
301155
- return result;
300958
+ const resource = resolveResource(runAs.resource, node, context, report);
300959
+ if (typeof runAs.record !== "string" || !UUID_PATTERN2.test(runAs.record)) {
300960
+ report(node, '"runAs.record" must be the lowercase UUID of a record');
300961
+ return null;
301156
300962
  }
301157
- return literal(expression2);
300963
+ return resource === null ? null : { mode: "fixed", resource: resource.slug, record_id: runAs.record };
301158
300964
  }
301159
- function literal(node) {
301160
- const expression2 = unwrap(node);
301161
- if (import_typescript4.default.isStringLiteral(expression2) || import_typescript4.default.isNoSubstitutionTemplateLiteral(expression2)) {
301162
- return expression2.text;
301163
- }
301164
- if (import_typescript4.default.isNumericLiteral(expression2)) {
301165
- return Number(expression2.text);
300965
+ function readAuthorizer(authorizer, node, trigger, report) {
300966
+ if (authorizer === void 0 || authorizer === null) {
300967
+ return null;
301166
300968
  }
301167
- if (import_typescript4.default.isPrefixUnaryExpression(expression2) && expression2.operator === import_typescript4.default.SyntaxKind.MinusToken && import_typescript4.default.isNumericLiteral(expression2.operand)) {
301168
- return -Number(expression2.operand.text);
300969
+ if (authorizer !== "authenticated") {
300970
+ report(node, "authorizer must be 'authenticated'");
300971
+ return null;
301169
300972
  }
301170
- throw new SchemaError(expression2, `Use a literal value here. ${STATIC_HINT}`);
301171
- }
301172
-
301173
- // scripts/lib/workflow-script/lib-files.mjs
301174
- init_define_globalThis_DIAGONAL_SDK_RUNTIME();
301175
- import { readFileSync as readFileSync7 } from "node:fs";
301176
- import { createRequire as createRequire2 } from "node:module";
301177
- import { dirname as dirname5, join as join10 } from "node:path";
301178
- var ROOT_LIB = "lib.es2023.d.ts";
301179
- function libClosure(read, root = ROOT_LIB) {
301180
- const files = {};
301181
- const pending = [root];
301182
- while (pending.length > 0) {
301183
- const name = pending.pop();
301184
- if (Object.hasOwn(files, name)) {
301185
- continue;
301186
- }
301187
- files[name] = read(name);
301188
- for (const match of files[name].matchAll(/<reference lib="([^"]+)"/g)) {
301189
- pending.push(`lib.${match[1].toLowerCase()}.d.ts`);
301190
- }
300973
+ if (trigger !== null && trigger.name !== "request") {
300974
+ report(node, "Only a request workflow can have an authorizer");
300975
+ return null;
301191
300976
  }
301192
- return files;
301193
- }
301194
- function readLibClosure(root = ROOT_LIB) {
301195
- const libDir = dirname5(createRequire2(import.meta.url).resolve("typescript/lib/lib.d.ts"));
301196
- return libClosure((name) => readFileSync7(join10(libDir, name), "utf8"), root);
300977
+ return { requires_authentication: true };
301197
300978
  }
301198
300979
 
301199
- // scripts/lib/workflow-script/lint-rules.mjs
300980
+ // scripts/lib/runtime-build/workflow-tests.mjs
301200
300981
  init_define_globalThis_DIAGONAL_SDK_RUNTIME();
301201
- var import_typescript6 = __toESM(require_typescript(), 1);
300982
+ var import_typescript2 = __toESM(require_typescript(), 1);
300983
+ import { spawnSync } from "node:child_process";
300984
+ import { mkdirSync, mkdtempSync, realpathSync as realpathSync2, rmSync, writeFileSync as writeFileSync3 } from "node:fs";
300985
+ import { tmpdir } from "node:os";
300986
+ import { dirname as dirname4, join as join9, relative as relative3 } from "node:path";
301202
300987
 
301203
- // scripts/lib/workflow-script/profile-rules.mjs
300988
+ // scripts/lib/runtime-build/script-sdk.mjs
301204
300989
  init_define_globalThis_DIAGONAL_SDK_RUNTIME();
301205
- var import_typescript5 = __toESM(require_typescript(), 1);
301206
- var PROFILES = {
301207
- workflow: {
301208
- label: "A workflow script",
301209
- imports: ["@diagonal/workflow", "@diagonal/workflow/workspace"],
301210
- specifier: null,
301211
- entry: null
301212
- },
301213
- test: {
301214
- label: "A test script",
301215
- imports: ["@diagonal/workflow", "@diagonal-hq/workflows/test", "@diagonal/workflow/workspace"],
301216
- specifier: "@diagonal-hq/workflows/test",
301217
- entry: "/sdk/profiles/test.ts"
301218
- },
301219
- migration: {
301220
- label: "A migration script",
301221
- imports: ["@diagonal-hq/workflows/migration", "@diagonal/workflow/workspace"],
301222
- specifier: "@diagonal-hq/workflows/migration",
301223
- entry: "/sdk/profiles/migration.ts"
301224
- }
301225
- };
301226
- var PROFILE_SPECIFIERS = new Set(
301227
- Object.values(PROFILES).flatMap(({ specifier }) => specifier === null ? [] : [specifier])
300990
+ import { readFileSync as readFileSync6, readdirSync as readdirSync2, statSync as statSync3 } from "node:fs";
300991
+ import { createRequire } from "node:module";
300992
+ import { dirname as dirname3, join as join8, relative as relative2, resolve as resolve4 } from "node:path";
300993
+ import { fileURLToPath } from "node:url";
300994
+ var SCRIPT_SDK_ROOT = resolve4(
300995
+ dirname3(fileURLToPath(import.meta.url)),
300996
+ "../../../packages/workflows/src"
301228
300997
  );
301229
- var SDK_SPECIFIERS = /* @__PURE__ */ new Set(["@diagonal/workflow", ...PROFILE_SPECIFIERS]);
301230
- function resolveProfile(name) {
301231
- if (name === void 0 || name === null) {
301232
- return "workflow";
301233
- }
301234
- if (typeof name !== "string" || !Object.hasOwn(PROFILES, name)) {
301235
- throw new Error(`Unknown workflow script profile: ${String(name)}`);
301236
- }
301237
- return name;
300998
+ var SDK_RUNTIME_ENTRY_POINTS = {
300999
+ workflow: join8(SCRIPT_SDK_ROOT, "index.ts"),
301000
+ testing: join8(SCRIPT_SDK_ROOT, "testing/index.ts")
301001
+ };
301002
+ function walk(directory) {
301003
+ return readdirSync2(directory).flatMap(
301004
+ (name) => statSync3(join8(directory, name)).isDirectory() ? walk(join8(directory, name)) : [join8(directory, name)]
301005
+ );
301238
301006
  }
301239
- function profileFindings(file2, checker, program3, profile) {
301240
- const { entry, label, specifier } = PROFILES[profile];
301241
- if (entry === null) {
301242
- return [];
301243
- }
301244
- const entryFile = program3.getSourceFile(entry);
301245
- const entrySymbol = entryFile && checker.getSymbolAtLocation(entryFile);
301246
- if (!entrySymbol) {
301247
- throw new Error(`The SDK has no ${entry} module.`);
301248
- }
301249
- const exports = new Map(
301250
- checker.getExportsOfModule(entrySymbol).map((symbol) => [symbol.getName(), symbol])
301007
+ function readSandboxSdkFiles() {
301008
+ return Object.fromEntries(
301009
+ walk(SCRIPT_SDK_ROOT).filter(
301010
+ (file2) => file2.endsWith(".ts") && !file2.includes("/testing/") && !file2.endsWith("/http-transport.ts") && !file2.endsWith("/workspace.generated.ts")
301011
+ ).map((file2) => [`/sdk/${relative2(SCRIPT_SDK_ROOT, file2)}`, readFileSync6(file2, "utf8")])
301251
301012
  );
301252
- const findings = [];
301253
- const forbidden = (node, path) => findings.push({
301254
- node,
301255
- code: "profile-capability",
301256
- message: `${label} cannot use ${path}. Use only the exports of ${specifier}.`
301013
+ }
301014
+ function bundleSdkRuntime(buildSync) {
301015
+ const result = buildSync({
301016
+ entryPoints: SDK_RUNTIME_ENTRY_POINTS,
301017
+ outdir: "/sdk",
301018
+ bundle: true,
301019
+ splitting: true,
301020
+ platform: "node",
301021
+ target: "node24",
301022
+ format: "esm",
301023
+ write: false,
301024
+ logLevel: "silent"
301257
301025
  });
301258
- const exportType = (name) => {
301259
- const symbol = exports.get(name);
301260
- const target = symbol && symbol.flags & import_typescript5.default.SymbolFlags.Alias ? checker.getAliasedSymbol(symbol) : symbol;
301261
- return target && target.flags & import_typescript5.default.SymbolFlags.Value ? checker.getTypeOfSymbolAtLocation(target, entryFile) : null;
301262
- };
301263
- const checkMembers = (identifier4, type, path) => {
301264
- let node = identifier4;
301265
- let current = type;
301266
- let currentPath = path;
301267
- while (current !== null) {
301268
- const parent = node.parent;
301269
- const isMemberAccess = import_typescript5.default.isPropertyAccessExpression(parent) && parent.expression === node || import_typescript5.default.isElementAccessExpression(parent) && parent.expression === node && import_typescript5.default.isStringLiteralLike(parent.argumentExpression);
301270
- if (!isMemberAccess) {
301271
- if (current.getCallSignatures().length === 0 && hasRestrictedMembers(current, currentPath)) {
301272
- forbidden(node, `${currentPath} as a value`);
301273
- }
301274
- return;
301275
- }
301276
- const member = import_typescript5.default.isPropertyAccessExpression(parent) ? parent.name.text : parent.argumentExpression.text;
301277
- const property = current.getProperty(member);
301278
- currentPath = `${currentPath}.${member}`;
301279
- if (!property) {
301280
- forbidden(parent, currentPath);
301281
- return;
301282
- }
301283
- current = checker.getTypeOfSymbolAtLocation(property, entryFile);
301284
- node = parent;
301285
- }
301286
- };
301287
- const hasRestrictedMembers = (profileType, path) => {
301288
- const rootType = rootNamespaceTypes.get(path);
301289
- return rootType !== void 0 && rootType.getProperties().some((property) => !profileType.getProperty(property.getName()));
301290
- };
301291
- const rootNamespaceTypes = /* @__PURE__ */ new Map();
301292
- const rootFile = program3.getSourceFile("/sdk/index.ts");
301293
- const rootSymbol = rootFile && checker.getSymbolAtLocation(rootFile);
301294
- for (const symbol of rootSymbol ? checker.getExportsOfModule(rootSymbol) : []) {
301295
- const target = symbol.flags & import_typescript5.default.SymbolFlags.Alias ? checker.getAliasedSymbol(symbol) : symbol;
301296
- if (target.flags & import_typescript5.default.SymbolFlags.Value) {
301297
- collectNamespaceTypes(
301298
- checker,
301299
- symbol.getName(),
301300
- checker.getTypeOfSymbolAtLocation(target, rootFile),
301301
- rootFile,
301302
- rootNamespaceTypes
301303
- );
301304
- }
301026
+ return Object.fromEntries(
301027
+ result.outputFiles.map((file2) => [relative2("/sdk", file2.path), file2.text])
301028
+ );
301029
+ }
301030
+ var sdkFiles;
301031
+ try {
301032
+ ({ SDK_FILES: sdkFiles } = await Promise.resolve().then(() => (init_sdk_files_generated(), sdk_files_generated_exports)));
301033
+ } catch (error) {
301034
+ if (error?.code !== "ERR_MODULE_NOT_FOUND") {
301035
+ throw error;
301305
301036
  }
301306
- const valueSymbol = (node) => import_typescript5.default.isShorthandPropertyAssignment(node.parent) && node.parent.name === node ? checker.getShorthandAssignmentValueSymbol(node.parent) : checker.getSymbolAtLocation(node);
301307
- const references = (binding) => {
301308
- const symbol = checker.getSymbolAtLocation(binding);
301309
- const found2 = [];
301310
- const visit = (node) => {
301311
- if (import_typescript5.default.isIdentifier(node) && node !== binding && valueSymbol(node) === symbol && !import_typescript5.default.isImportSpecifier(node.parent)) {
301312
- found2.push(node);
301313
- }
301314
- import_typescript5.default.forEachChild(node, visit);
301315
- };
301316
- visit(file2);
301317
- return found2;
301318
- };
301319
- const checkNamespace = (binding) => {
301320
- for (const reference of references(binding)) {
301321
- const parent = reference.parent;
301322
- if (!import_typescript5.default.isPropertyAccessExpression(parent) || parent.expression !== reference) {
301323
- forbidden(reference, "the SDK namespace as a value");
301324
- continue;
301325
- }
301326
- const name = parent.name.text;
301327
- if (!exports.has(name)) {
301328
- forbidden(parent, name);
301329
- continue;
301330
- }
301331
- const type = exportType(name);
301332
- if (type !== null) {
301333
- checkMembers(parent, type, name);
301334
- }
301335
- }
301336
- };
301337
- for (const statement2 of file2.statements) {
301338
- if (import_typescript5.default.isImportEqualsDeclaration(statement2) && import_typescript5.default.isExternalModuleReference(statement2.moduleReference) && import_typescript5.default.isStringLiteral(statement2.moduleReference.expression) && SDK_SPECIFIERS.has(statement2.moduleReference.expression.text)) {
301339
- checkNamespace(statement2.name);
301037
+ sdkFiles = readSandboxSdkFiles();
301038
+ }
301039
+ var SCRIPT_SDK_FILES = sdkFiles;
301040
+ var sdkRuntimeFiles = null;
301041
+ function scriptSdkRuntimeFiles() {
301042
+ sdkRuntimeFiles ??= define_globalThis_DIAGONAL_SDK_RUNTIME_default ?? bundleSdkRuntime(createRequire(import.meta.url)("esbuild").buildSync);
301043
+ return sdkRuntimeFiles;
301044
+ }
301045
+
301046
+ // scripts/lib/runtime-build/workflow-tests.mjs
301047
+ var WORKFLOW_TEST_STAGE = "workflow test";
301048
+ var WORKFLOW_TEST_SUFFIX = ".test.ts";
301049
+ var TEST_TIMEOUT_MS = 1e4;
301050
+ var RUN_TIMEOUT_MS = 6e4;
301051
+ var RESULT_PREFIX = "\0diagonal-test ";
301052
+ var SDK_MODULES = {
301053
+ "@diagonal/workflow": "sdk/workflow.js",
301054
+ "@diagonal/workflow/testing": "sdk/testing.js",
301055
+ "@diagonal/workflow/workspace": "sdk/workspace.js",
301056
+ [AUTHORING_MODULE]: "sdk/runtime.js"
301057
+ };
301058
+ var NODE_TEST_MODULES = /* @__PURE__ */ new Set(["node:test", "node:assert", "node:assert/strict"]);
301059
+ var TEST_MODULE_EXTERNALS = /* @__PURE__ */ new Set([...Object.keys(SDK_MODULES), ...NODE_TEST_MODULES]);
301060
+ var RELATIVE_WORKFLOW = /^\.\/([^/]+?)(?:\.ts|\.js)?$/;
301061
+ var REPORTER_SOURCE = `const PREFIX = ${JSON.stringify(RESULT_PREFIX)};
301062
+ export default async function* reporter(source) {
301063
+ const names = [];
301064
+ for await (const event of source) {
301065
+ const data = event.data;
301066
+ if (event.type === 'test:start') {
301067
+ names.length = data.nesting;
301068
+ names.push(data.name);
301340
301069
  continue;
301341
301070
  }
301342
- if (!import_typescript5.default.isImportDeclaration(statement2) || !import_typescript5.default.isStringLiteral(statement2.moduleSpecifier) || !SDK_SPECIFIERS.has(statement2.moduleSpecifier.text) || !statement2.importClause) {
301071
+ if (event.type !== 'test:pass' && event.type !== 'test:fail') {
301343
301072
  continue;
301344
301073
  }
301345
- const clause = statement2.importClause;
301346
- if (clause.name) {
301347
- forbidden(clause.name, "a default import of the SDK");
301348
- }
301349
- const bindings = clause.namedBindings;
301350
- if (bindings && import_typescript5.default.isNamespaceImport(bindings)) {
301351
- checkNamespace(bindings.name);
301074
+ const error = data.details?.error;
301075
+ if (data.details?.type === 'suite' && (event.type === 'test:pass' || error?.failureType === 'subtestsFailed')) {
301352
301076
  continue;
301353
301077
  }
301354
- for (const element of bindings && import_typescript5.default.isNamedImports(bindings) ? bindings.elements : []) {
301355
- const name = (element.propertyName ?? element.name).text;
301356
- if (!exports.has(name)) {
301357
- forbidden(element, name);
301358
- continue;
301359
- }
301360
- const type = exportType(name);
301361
- if (type === null || element.isTypeOnly || clause.isTypeOnly) {
301362
- continue;
301363
- }
301364
- for (const reference of references(element.name)) {
301365
- checkMembers(reference, type, name);
301366
- }
301367
- }
301078
+ const path = [...names.slice(0, data.nesting), data.name].join(' > ');
301079
+ const cause = error?.cause ?? error;
301080
+ yield PREFIX + JSON.stringify({
301081
+ file: data.file ?? null,
301082
+ name: path,
301083
+ leaf: data.name,
301084
+ ok: event.type === 'test:pass',
301085
+ message: event.type === 'test:pass' ? null : String(cause?.message ?? cause ?? 'The test failed').trim()
301086
+ }) + '\\n';
301368
301087
  }
301369
- return findings;
301370
301088
  }
301371
- function collectNamespaceTypes(checker, path, type, location, into) {
301372
- if (type.getCallSignatures().length > 0 || !(type.flags & import_typescript5.default.TypeFlags.Object)) {
301373
- return;
301089
+ `;
301090
+ function moduleSpecifierNodes(ast) {
301091
+ return ast.program.body.filter(
301092
+ (statement2) => (statement2.type === "ImportDeclaration" || statement2.type === "ExportNamedDeclaration" || statement2.type === "ExportAllDeclaration") && statement2.source
301093
+ ).map((statement2) => statement2.source);
301094
+ }
301095
+ function transpile(path, source, ast, resolveSpecifier) {
301096
+ let rewritten = source;
301097
+ for (const node of moduleSpecifierNodes(ast).toSorted(
301098
+ (left, right) => right.start - left.start
301099
+ )) {
301100
+ const target = resolveSpecifier(node.value);
301101
+ if (target !== null) {
301102
+ rewritten = `${rewritten.slice(0, node.start)}${JSON.stringify(target)}${rewritten.slice(node.end)}`;
301103
+ }
301374
301104
  }
301375
- into.set(path, type);
301376
- for (const property of type.getProperties()) {
301377
- collectNamespaceTypes(
301378
- checker,
301379
- `${path}.${property.getName()}`,
301380
- checker.getTypeOfSymbolAtLocation(property, location),
301381
- location,
301382
- into
301383
- );
301105
+ return import_typescript2.default.transpileModule(rewritten, {
301106
+ fileName: path,
301107
+ compilerOptions: {
301108
+ target: import_typescript2.default.ScriptTarget.ES2023,
301109
+ module: import_typescript2.default.ModuleKind.ESNext,
301110
+ sourceMap: false
301111
+ }
301112
+ }).outputText;
301113
+ }
301114
+ function sdkSpecifier(fromDirectory) {
301115
+ return (specifier) => Object.hasOwn(SDK_MODULES, specifier) ? `${fromDirectory}${SDK_MODULES[specifier]}` : null;
301116
+ }
301117
+ function testCallNode(ast, name) {
301118
+ const pending = [ast.program];
301119
+ while (pending.length > 0) {
301120
+ const node = pending.pop();
301121
+ const [first] = node.type === "CallExpression" ? node.arguments : [];
301122
+ 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) {
301123
+ return node;
301124
+ }
301125
+ pending.push(...childNodes(node));
301384
301126
  }
301127
+ return null;
301385
301128
  }
301386
-
301387
- // scripts/lib/workflow-script/lint-rules.mjs
301388
- var UNSUPPORTED_GLOBALS = {
301389
- Intl: "The sandbox has no Intl. Use date.format, time.format, money.format, or number.format.",
301390
- crypto: "The sandbox has no crypto. Use text.hash, text.randomUuid, or security.randomPassword.",
301391
- setTimeout: "The sandbox has no timers.",
301392
- setInterval: "The sandbox has no timers.",
301393
- fetch: "The sandbox has no network. Use http.request.",
301394
- process: "The sandbox has no process.",
301395
- require: "Use an import from @diagonal/workflow."
301396
- };
301397
- var FLOATING_MESSAGE = "Await this call, return it, or assign it. A call that is not awaited can fail without stopping the workflow.";
301398
- var MAIL_TEMPLATE_CAPABILITIES = {
301399
- MailSendInput: "mail.send",
301400
- NotificationSendInput: "notification.send"
301401
- };
301402
- var MAIL_REFERENCES_KEY = "$references";
301403
- var composedMailTextMessage = (capability, field2) => `Do not write values into the ${capability} ${field2}. The email evaluates this text as Liquid, so a value such as "{{ workspace.name }}" renders. Put each value in layoutData.${MAIL_REFERENCES_KEY} and write {{ ref.<key> }} in the text.`;
301404
- function staticPropertyName(property) {
301405
- if (!import_typescript6.default.isPropertyAssignment(property) && !import_typescript6.default.isShorthandPropertyAssignment(property)) {
301406
- return null;
301129
+ function importDiagnostics(test, workflowNames, workspaceRoot) {
301130
+ const diagnostics = [];
301131
+ for (const node of moduleSpecifierNodes(test.ast)) {
301132
+ const specifier = node.value;
301133
+ const relative5 = RELATIVE_WORKFLOW.exec(specifier);
301134
+ if (NODE_TEST_MODULES.has(specifier) || Object.hasOwn(SDK_MODULES, specifier) || relative5 !== null && workflowNames.has(relative5[1]) || isAppSpecifier(specifier) && workspaceRoot !== null && resolveAppSpecifier(workspaceRoot, specifier) !== null) {
301135
+ continue;
301136
+ }
301137
+ diagnostics.push(
301138
+ diagnosticAt(
301139
+ test.path,
301140
+ node,
301141
+ `A workflow test can import only node:test, node:assert, @diagonal/workflow, @diagonal/workflow/testing, @diagonal/workflow/workspace, the workflows in workflows/, and workspace files by @app/. "${specifier}" is not one of them`,
301142
+ { stage: WORKFLOW_TEST_STAGE }
301143
+ )
301144
+ );
301407
301145
  }
301408
- return propertyNameText(property.name);
301146
+ return diagnostics;
301409
301147
  }
301410
- function floatingPromiseCalls(expression2, holdsPromise) {
301411
- const node = import_typescript6.default.skipParentheses(expression2);
301412
- if (import_typescript6.default.isConditionalExpression(node)) {
301413
- return [
301414
- ...floatingPromiseCalls(node.whenTrue, holdsPromise),
301415
- ...floatingPromiseCalls(node.whenFalse, holdsPromise)
301416
- ];
301417
- }
301418
- if (import_typescript6.default.isBinaryExpression(node) && [
301419
- import_typescript6.default.SyntaxKind.AmpersandAmpersandToken,
301420
- import_typescript6.default.SyntaxKind.BarBarToken,
301421
- import_typescript6.default.SyntaxKind.QuestionQuestionToken,
301422
- import_typescript6.default.SyntaxKind.CommaToken
301423
- ].includes(node.operatorToken.kind)) {
301424
- return [
301425
- ...floatingPromiseCalls(node.left, holdsPromise),
301426
- ...floatingPromiseCalls(node.right, holdsPromise)
301427
- ];
301428
- }
301429
- return (import_typescript6.default.isCallExpression(node) || import_typescript6.default.isArrayLiteralExpression(node)) && holdsPromise(node) ? [node] : [];
301148
+ function sandboxPath(path) {
301149
+ return path.replace(/\.(ts|tsx|js|jsx)$/, ".js");
301430
301150
  }
301431
- function returnsPromise(fn, checker) {
301432
- const signature = checker.getSignatureFromDeclaration(fn);
301433
- return signature !== void 0 && checker.getReturnTypeOfSignature(signature).getSymbol()?.getName() === "Promise";
301151
+ function sandboxPrefix(path) {
301152
+ return "../".repeat(path.split("/").length - 1) || "./";
301434
301153
  }
301435
- function contextuallyReturnsVoid(fn, checker) {
301436
- const signatures = checker.getContextualType(fn)?.getCallSignatures() ?? [];
301437
- return signatures.length > 0 && signatures.every(
301438
- (signature) => (checker.getReturnTypeOfSignature(signature).flags & import_typescript6.default.TypeFlags.Void) !== 0
301439
- );
301154
+ function relativeSandboxPath(from, target) {
301155
+ const path = relative3(dirname4(from), sandboxPath(target));
301156
+ return path.startsWith(".") ? path : `./${path}`;
301440
301157
  }
301441
- function isMemberName(node) {
301442
- const parent = node.parent;
301443
- if (import_typescript6.default.isPropertyAccessExpression(parent) || import_typescript6.default.isQualifiedName(parent)) {
301444
- return parent.name === node || parent.right === node;
301445
- }
301446
- if (import_typescript6.default.isBindingElement(parent) || import_typescript6.default.isImportSpecifier(parent) || import_typescript6.default.isExportSpecifier(parent)) {
301447
- return parent.propertyName === node;
301448
- }
301449
- return (import_typescript6.default.isPropertyAssignment(parent) || import_typescript6.default.isPropertyDeclaration(parent) || import_typescript6.default.isPropertySignature(parent) || import_typescript6.default.isMethodDeclaration(parent) || import_typescript6.default.isMethodSignature(parent) || import_typescript6.default.isGetAccessorDeclaration(parent) || import_typescript6.default.isSetAccessorDeclaration(parent) || import_typescript6.default.isEnumMember(parent)) && parent.name === node;
301158
+ function writeFile(root, path, content) {
301159
+ mkdirSync(dirname4(join9(root, path)), { recursive: true });
301160
+ writeFileSync3(join9(root, path), content);
301450
301161
  }
301451
- function lint2(file2, checker, { allowAppImports = false, profile = "workflow" } = {}) {
301452
- const findings = [];
301453
- const { imports: allowedImports, label } = PROFILES[profile];
301454
- const allowedImportList = new Intl.ListFormat("en", { type: "disjunction" }).format(
301455
- allowedImports
301162
+ function parseResults(stdout) {
301163
+ return stdout.split("\n").filter((line) => line.startsWith(RESULT_PREFIX)).map((line) => JSON.parse(line.slice(RESULT_PREFIX.length)));
301164
+ }
301165
+ function runWorkflowTests({
301166
+ tests,
301167
+ workflows,
301168
+ root: workspaceRoot = null,
301169
+ appModules = /* @__PURE__ */ new Map()
301170
+ }) {
301171
+ const diagnostics = [];
301172
+ const workflowNames = new Map(
301173
+ workflows.map((workflow) => [workflow.path.slice("workflows/".length, -".ts".length), workflow])
301456
301174
  );
301457
- let defaultExport = null;
301458
- const isPromiseType = (type) => type.getSymbol()?.getName() === "Promise";
301459
- const holdsPromise = (node) => {
301460
- const type = checker.getTypeAtLocation(node);
301461
- if (checker.isArrayType(type) || checker.isTupleType(type)) {
301462
- return checker.getTypeArguments(type).some(isPromiseType);
301463
- }
301464
- return isPromiseType(type);
301465
- };
301466
- const isDeclaredInScript = (symbol) => symbol?.declarations?.some((declaration) => declaration.getSourceFile() === file2) ?? false;
301467
- const mailTemplateCapability = (call) => {
301468
- const [parameter] = checker.getResolvedSignature(call)?.getParameters() ?? [];
301469
- const inputType = parameter && checker.getTypeOfSymbolAtLocation(parameter, call).getSymbol();
301470
- const fromSdk = inputType?.declarations?.some(
301471
- (declaration) => declaration.getSourceFile().fileName.startsWith("/sdk/")
301472
- ) ?? false;
301473
- return fromSdk && Object.hasOwn(MAIL_TEMPLATE_CAPABILITIES, inputType.getName()) ? MAIL_TEMPLATE_CAPABILITIES[inputType.getName()] : null;
301474
- };
301475
- const constValue = (expression2) => {
301476
- const node = unwrap(expression2);
301477
- if (!import_typescript6.default.isIdentifier(node)) {
301478
- return node;
301175
+ const runnable = [];
301176
+ for (const test of tests) {
301177
+ const workflowPath = `${test.path.slice(0, -WORKFLOW_TEST_SUFFIX.length)}.ts`;
301178
+ if (!workflowNames.has(workflowPath.slice("workflows/".length, -".ts".length))) {
301179
+ diagnostics.push(
301180
+ diagnosticAt(
301181
+ test.path,
301182
+ null,
301183
+ `The test file has no workflow. Add ${workflowPath} or remove the test file`,
301184
+ { stage: WORKFLOW_TEST_STAGE }
301185
+ )
301186
+ );
301187
+ continue;
301479
301188
  }
301480
- const symbol = import_typescript6.default.isShorthandPropertyAssignment(node.parent) && node.parent.name === node ? checker.getShorthandAssignmentValueSymbol(node.parent) : checker.getSymbolAtLocation(node);
301481
- const declaration = symbol?.valueDeclaration;
301482
- return declaration !== void 0 && import_typescript6.default.isVariableDeclaration(declaration) && declaration.initializer !== void 0 && declaration.getSourceFile() === file2 && (import_typescript6.default.getCombinedNodeFlags(declaration) & import_typescript6.default.NodeFlags.Const) !== 0 ? unwrap(declaration.initializer) : node;
301483
- };
301484
- const hasLiteralType = (node) => {
301485
- const type = checker.getTypeAtLocation(node);
301486
- return (type.isUnion() ? type.types : [type]).every(
301487
- (member) => member.isLiteral() || (member.flags & import_typescript6.default.TypeFlags.BooleanLiteral) !== 0
301488
- );
301489
- };
301490
- const isConstantText = (expression2, followed = /* @__PURE__ */ new Set()) => {
301491
- const node = unwrap(expression2);
301492
- if (import_typescript6.default.isTemplateExpression(node)) {
301493
- return node.templateSpans.every((span) => isConstantText(span.expression, followed));
301189
+ const imports = importDiagnostics(test, workflowNames, workspaceRoot);
301190
+ diagnostics.push(...imports);
301191
+ if (imports.length === 0) {
301192
+ runnable.push({ ...test, workflow: workflowPath });
301494
301193
  }
301495
- if (import_typescript6.default.isBinaryExpression(node) && node.operatorToken.kind === import_typescript6.default.SyntaxKind.PlusToken) {
301496
- return isConstantText(node.left, followed) && isConstantText(node.right, followed);
301194
+ }
301195
+ if (runnable.length === 0) {
301196
+ return { workflowTests: [], diagnostics };
301197
+ }
301198
+ const modules = new Map(appModules);
301199
+ for (const test of runnable) {
301200
+ for (const [path, module] of appModuleClosure(
301201
+ workspaceRoot,
301202
+ workspaceRoot === null ? [] : appImportsOf(workspaceRoot, test.path, test.ast),
301203
+ TEST_MODULE_EXTERNALS
301204
+ )) {
301205
+ modules.set(path, module);
301497
301206
  }
301498
- if (hasLiteralType(node)) {
301499
- return true;
301207
+ }
301208
+ const root = realpathSync2(mkdtempSync(join9(tmpdir(), "diagonal-workflow-tests-")));
301209
+ try {
301210
+ writeFile(root, "package.json", '{"type":"module"}\n');
301211
+ writeFile(root, "reporter.mjs", REPORTER_SOURCE);
301212
+ for (const [path, content] of Object.entries(scriptSdkRuntimeFiles())) {
301213
+ writeFile(root, `sdk/${path}`, content);
301500
301214
  }
301501
- const initializer = import_typescript6.default.isIdentifier(node) ? constValue(node) : node;
301502
- if (initializer === node || followed.has(initializer)) {
301503
- return false;
301215
+ writeFile(root, "sdk/workspace.js", "export {};\n");
301216
+ writeFile(root, "sdk/runtime.js", AUTHORING_HELPERS_MODULE);
301217
+ for (const [path, module] of modules) {
301218
+ const resolveSdk = sdkSpecifier(sandboxPrefix(path));
301219
+ writeFile(
301220
+ root,
301221
+ sandboxPath(path),
301222
+ transpile(
301223
+ path,
301224
+ module.source,
301225
+ parseSource(module.source, { jsx: path.endsWith("x") }),
301226
+ (specifier) => module.requires[specifier] === void 0 ? resolveSdk(specifier) : relativeSandboxPath(path, module.requires[specifier])
301227
+ )
301228
+ );
301504
301229
  }
301505
- return isConstantText(initializer, /* @__PURE__ */ new Set([...followed, initializer]));
301506
- };
301507
- const composedMailText = (expression2) => {
301508
- const node = unwrap(expression2);
301509
- if (import_typescript6.default.isConditionalExpression(node)) {
301510
- return composedMailText(node.whenTrue) ?? composedMailText(node.whenFalse);
301230
+ for (const workflow of workflows) {
301231
+ writeFile(
301232
+ root,
301233
+ workflow.path.replace(/\.ts$/, ".js"),
301234
+ transpile(workflow.path, workflow.source, workflow.ast, (specifier) => {
301235
+ const target = isAppSpecifier(specifier) && workspaceRoot !== null ? resolveAppSpecifier(workspaceRoot, specifier) : null;
301236
+ return target === null ? sdkSpecifier("../")(specifier) : relativeSandboxPath(workflow.path, target);
301237
+ })
301238
+ );
301511
301239
  }
301512
- if (import_typescript6.default.isBinaryExpression(node) && [import_typescript6.default.SyntaxKind.BarBarToken, import_typescript6.default.SyntaxKind.QuestionQuestionToken].includes(
301513
- node.operatorToken.kind
301514
- )) {
301515
- return composedMailText(node.left) ?? composedMailText(node.right);
301240
+ for (const test of runnable) {
301241
+ const resolveSdk = sdkSpecifier("../");
301242
+ writeFile(
301243
+ root,
301244
+ test.path.replace(/\.ts$/, ".js"),
301245
+ transpile(test.path, test.source, test.ast, (specifier) => {
301246
+ const relative5 = RELATIVE_WORKFLOW.exec(specifier);
301247
+ const target = isAppSpecifier(specifier) && workspaceRoot !== null ? resolveAppSpecifier(workspaceRoot, specifier) : null;
301248
+ if (target !== null) {
301249
+ return relativeSandboxPath(test.path, target);
301250
+ }
301251
+ return relative5 !== null ? `./${relative5[1]}.js` : resolveSdk(specifier);
301252
+ })
301253
+ );
301516
301254
  }
301517
- const isConcatenation = import_typescript6.default.isBinaryExpression(node) && node.operatorToken.kind === import_typescript6.default.SyntaxKind.PlusToken && (checker.getTypeAtLocation(node).flags & import_typescript6.default.TypeFlags.StringLike) !== 0;
301518
- return (import_typescript6.default.isTemplateExpression(node) || isConcatenation) && !isConstantText(node) ? node : null;
301519
- };
301520
- const checkMailTemplateCall = (call) => {
301521
- const capability = call.arguments.length > 0 ? mailTemplateCapability(call) : null;
301522
- const input = capability === null ? null : constValue(call.arguments[0]);
301523
- if (input === null || !import_typescript6.default.isObjectLiteralExpression(input)) {
301524
- return;
301255
+ const run = spawnSync(
301256
+ process.execPath,
301257
+ [
301258
+ "--permission",
301259
+ `--allow-fs-read=${root}`,
301260
+ "--test",
301261
+ "--test-isolation=none",
301262
+ `--test-timeout=${TEST_TIMEOUT_MS}`,
301263
+ "--test-reporter=./reporter.mjs",
301264
+ ...runnable.map((test) => test.path.replace(/\.ts$/, ".js"))
301265
+ ],
301266
+ {
301267
+ cwd: root,
301268
+ env: { TZ: "UTC" },
301269
+ encoding: "utf8",
301270
+ timeout: RUN_TIMEOUT_MS,
301271
+ maxBuffer: 16 * 1024 * 1024
301272
+ }
301273
+ );
301274
+ if (run.error !== void 0 && run.error.code !== "ETIMEDOUT") {
301275
+ throw run.error;
301525
301276
  }
301526
- const valueOf = (property) => import_typescript6.default.isShorthandPropertyAssignment(property) ? property.name : property.initializer;
301527
- const check2 = (value, field2) => {
301528
- const composed = composedMailText(constValue(value));
301529
- if (composed !== null) {
301530
- findings.push({
301531
- node: composed,
301532
- code: "no-composed-mail-text",
301533
- message: composedMailTextMessage(capability, field2)
301534
- });
301535
- }
301536
- };
301537
- for (const property of input.properties) {
301538
- const name = staticPropertyName(property);
301539
- if (name === "subject") {
301540
- check2(valueOf(property), "subject");
301541
- }
301542
- const layoutData = name === "layoutData" ? constValue(valueOf(property)) : null;
301543
- if (layoutData === null || !import_typescript6.default.isObjectLiteralExpression(layoutData)) {
301544
- continue;
301545
- }
301546
- for (const slot of layoutData.properties) {
301547
- const slotName = staticPropertyName(slot);
301548
- if (slotName !== null && slotName !== MAIL_REFERENCES_KEY) {
301549
- check2(valueOf(slot), `layoutData.${slotName}`);
301277
+ const results = parseResults(run.stdout ?? "");
301278
+ const timedOut = run.error?.code === "ETIMEDOUT" || run.signal !== null;
301279
+ const workflowTests = runnable.map((test) => {
301280
+ const file2 = join9(root, test.path.replace(/\.ts$/, ".js"));
301281
+ const own = results.filter((result) => result.file === file2);
301282
+ for (const result of own) {
301283
+ if (!result.ok) {
301284
+ const node = testCallNode(test.ast, result.leaf);
301285
+ diagnostics.push(
301286
+ diagnosticAt(test.path, node, `Test "${result.name}" failed: ${result.message}`, {
301287
+ stage: WORKFLOW_TEST_STAGE
301288
+ })
301289
+ );
301550
301290
  }
301551
301291
  }
301552
- }
301553
- };
301554
- const checkModuleSpecifier = (node, specifier) => {
301555
- if (specifier && import_typescript6.default.isStringLiteral(specifier) && !allowedImports.includes(specifier.text) && !(allowAppImports && specifier.text.startsWith("@app/"))) {
301556
- findings.push({
301557
- node,
301558
- code: "allowed-imports",
301559
- message: profile === "workflow" ? `Import only @diagonal/workflow or @diagonal/workflow/workspace, not ${specifier.text}.` : `${label} imports only ${allowedImportList}, not ${specifier.text}.`
301560
- });
301561
- }
301562
- };
301563
- const visit = (node) => {
301564
- if (import_typescript6.default.isImportDeclaration(node) || import_typescript6.default.isExportDeclaration(node)) {
301565
- checkModuleSpecifier(node, node.moduleSpecifier);
301566
- }
301567
- if (import_typescript6.default.isImportEqualsDeclaration(node) && import_typescript6.default.isExternalModuleReference(node.moduleReference)) {
301568
- checkModuleSpecifier(node, node.moduleReference.expression);
301569
- }
301570
- if (import_typescript6.default.isCallExpression(node) && node.expression.kind === import_typescript6.default.SyntaxKind.ImportKeyword) {
301571
- findings.push({ node, code: "allowed-imports", message: "Dynamic import is not supported." });
301572
- }
301573
- if (import_typescript6.default.isCallExpression(node) && node.expression.kind !== import_typescript6.default.SyntaxKind.ImportKeyword) {
301574
- checkMailTemplateCall(node);
301575
- }
301576
- if (import_typescript6.default.isExpressionStatement(node)) {
301577
- for (const call of floatingPromiseCalls(node.expression, holdsPromise)) {
301578
- findings.push({ node: call, code: "no-floating-capability", message: FLOATING_MESSAGE });
301579
- }
301580
- }
301581
- if ((import_typescript6.default.isArrowFunction(node) || import_typescript6.default.isFunctionExpression(node)) && import_typescript6.default.isCallExpression(node.parent) && node.parent.arguments.includes(node) && returnsPromise(node, checker) && contextuallyReturnsVoid(node, checker)) {
301582
- findings.push({ node, code: "no-floating-capability", message: FLOATING_MESSAGE });
301583
- }
301584
- if (import_typescript6.default.isIdentifier(node) && Object.hasOwn(UNSUPPORTED_GLOBALS, node.text)) {
301585
- const isGlobalThisMember = import_typescript6.default.isPropertyAccessExpression(node.parent) && node.parent.name === node && import_typescript6.default.isIdentifier(node.parent.expression) && node.parent.expression.text === "globalThis";
301586
- const symbol = import_typescript6.default.isShorthandPropertyAssignment(node.parent) ? checker.getShorthandAssignmentValueSymbol(node.parent) : checker.getSymbolAtLocation(node);
301587
- const isGlobalReference = !isMemberName(node) && !isDeclaredInScript(symbol);
301588
- if (isGlobalThisMember || isGlobalReference) {
301589
- findings.push({
301590
- node,
301591
- code: "no-unsupported-global",
301592
- message: UNSUPPORTED_GLOBALS[node.text]
301593
- });
301292
+ if (timedOut) {
301293
+ diagnostics.push(
301294
+ diagnostic(
301295
+ test.path,
301296
+ 1,
301297
+ 1,
301298
+ `The workflow tests did not finish in ${RUN_TIMEOUT_MS / 1e3} seconds`,
301299
+ { stage: WORKFLOW_TEST_STAGE }
301300
+ )
301301
+ );
301302
+ } else if (own.length === 0 && run.status !== 0) {
301303
+ diagnostics.push(
301304
+ diagnostic(
301305
+ test.path,
301306
+ 1,
301307
+ 1,
301308
+ `The workflow tests did not run: ${(run.stderr ?? "").trim().split("\n")[0] || `exit code ${run.status}`}`,
301309
+ { stage: WORKFLOW_TEST_STAGE }
301310
+ )
301311
+ );
301594
301312
  }
301595
- }
301596
- if (import_typescript6.default.isExportAssignment(node) && !node.isExportEquals) {
301597
- defaultExport = node.expression;
301598
- }
301599
- import_typescript6.default.forEachChild(node, visit);
301600
- };
301601
- for (const directive2 of file2.libReferenceDirectives) {
301602
- findings.push({
301603
- node: file2,
301604
- position: directive2.pos,
301605
- code: "no-lib-reference",
301606
- message: "Remove this lib reference. Workflow scripts run on ES2023 in the sandbox."
301607
- });
301608
- }
301609
- visit(file2);
301610
- if (!isSdkDefineWorkflowCall(defaultExport, checker)) {
301611
- findings.push({
301612
- node: defaultExport ?? file2,
301613
- code: "default-workflow-export",
301614
- message: "Export the workflow as `export default defineWorkflow(async (input, ctx) => { ... })`."
301313
+ return {
301314
+ path: test.path,
301315
+ workflow: test.workflow,
301316
+ passed: own.filter((result) => result.ok).length,
301317
+ failed: own.filter((result) => !result.ok).length,
301318
+ results: own.map((result) => ({
301319
+ name: result.name,
301320
+ ok: result.ok,
301321
+ message: result.message
301322
+ }))
301323
+ };
301615
301324
  });
301325
+ return { workflowTests, diagnostics };
301326
+ } finally {
301327
+ rmSync(root, { recursive: true, force: true });
301616
301328
  }
301617
- return findings;
301618
- }
301619
- function isSdkDefineWorkflowCall(expression2, checker) {
301620
- if (expression2 === null || !import_typescript6.default.isCallExpression(expression2) || !import_typescript6.default.isIdentifier(expression2.expression)) {
301621
- return false;
301622
- }
301623
- let symbol = checker.getSymbolAtLocation(expression2.expression);
301624
- if (symbol && symbol.flags & import_typescript6.default.SymbolFlags.Alias) {
301625
- symbol = checker.getAliasedSymbol(symbol);
301626
- }
301627
- return symbol?.getName() === "defineWorkflow" && (symbol.declarations?.some(
301628
- (declaration) => declaration.getSourceFile().fileName.startsWith("/sdk/")
301629
- ) ?? false);
301630
301329
  }
301631
301330
 
301331
+ // scripts/lib/runtime-build/workflows.mjs
301332
+ init_define_globalThis_DIAGONAL_SDK_RUNTIME();
301333
+
301632
301334
  // scripts/lib/workflow-script/compile.mjs
301633
- var SCRIPT = "/workflow.ts";
301634
- var INPUT_VALIDATOR_CHECK = "/input-validator.check.ts";
301635
- var INPUT_VALIDATOR_CHECK_SOURCE = `import type { InputValidator, WorkflowDefinition } from '@diagonal/workflow';
301636
- import * as script from './workflow';
301335
+ init_define_globalThis_DIAGONAL_SDK_RUNTIME();
301336
+ var import_typescript7 = __toESM(require_typescript(), 1);
301637
301337
 
301638
- type Input = typeof script.default extends WorkflowDefinition<infer I, unknown> ? I : never;
301639
- type Exported = typeof script extends { validateInput: infer V } ? V : undefined;
301338
+ // scripts/lib/workflow-script/ast.mjs
301339
+ init_define_globalThis_DIAGONAL_SDK_RUNTIME();
301340
+ var import_typescript3 = __toESM(require_typescript(), 1);
301341
+ function unwrap2(node) {
301342
+ let current = node;
301343
+ while (import_typescript3.default.isParenthesizedExpression(current) || import_typescript3.default.isAsExpression(current) || import_typescript3.default.isSatisfiesExpression(current)) {
301344
+ current = current.expression;
301345
+ }
301346
+ return current;
301347
+ }
301348
+ function propertyNameText(name) {
301349
+ return import_typescript3.default.isIdentifier(name) || import_typescript3.default.isStringLiteral(name) ? name.text : null;
301350
+ }
301640
301351
 
301641
- declare const validateInput: Exported;
301642
- export const check: InputValidator<Input> | undefined = validateInput;
301643
- `;
301644
- var WORKSPACE = "/sdk/workspace.generated.ts";
301645
- var APP_ROOT = "/app";
301646
- var LIB_DIR = "/lib";
301647
- var OPTIONS = {
301648
- target: import_typescript7.default.ScriptTarget.ES2023,
301649
- lib: [ROOT_LIB],
301650
- module: import_typescript7.default.ModuleKind.CommonJS,
301651
- moduleResolution: import_typescript7.default.ModuleResolutionKind.Bundler,
301652
- strict: true,
301653
- types: [],
301654
- paths: {
301655
- "@diagonal/workflow": ["/sdk/index.ts"],
301656
- "@diagonal/workflow/workspace": [WORKSPACE],
301657
- ...Object.fromEntries(
301658
- Object.values(PROFILES).filter(({ specifier }) => specifier !== null).map(({ specifier, entry }) => [specifier, [entry]])
301659
- )
301352
+ // scripts/lib/workflow-script/input-schema.mjs
301353
+ init_define_globalThis_DIAGONAL_SDK_RUNTIME();
301354
+ var import_typescript4 = __toESM(require_typescript(), 1);
301355
+ var SDK_MODULE = "@diagonal/workflow";
301356
+ var SCALAR_KINDS = /* @__PURE__ */ new Set([
301357
+ "text",
301358
+ "email",
301359
+ "url",
301360
+ "uuid",
301361
+ "phone",
301362
+ "date",
301363
+ "datetime",
301364
+ "time",
301365
+ "timezone",
301366
+ "color",
301367
+ "number",
301368
+ "integer",
301369
+ "money",
301370
+ "boolean"
301371
+ ]);
301372
+ var SchemaError = class extends Error {
301373
+ constructor(node, message) {
301374
+ super(message);
301375
+ this.node = node;
301660
301376
  }
301661
301377
  };
301662
- var libFiles2;
301663
- try {
301664
- const { LIB_FILES: LIB_FILES2 } = await Promise.resolve().then(() => (init_sdk_files_generated(), sdk_files_generated_exports));
301665
- libFiles2 = libClosure((name) => LIB_FILES2[name]);
301666
- } catch {
301667
- libFiles2 = readLibClosure();
301668
- }
301669
- var libSourceFiles = /* @__PURE__ */ new Map();
301670
- var readLibFile = (name) => Object.hasOwn(libFiles2, name) ? libFiles2[name] : void 0;
301671
- function libSourceFile(name, languageVersion) {
301672
- if (!libSourceFiles.has(name)) {
301673
- const text = readLibFile(name);
301674
- libSourceFiles.set(
301675
- name,
301676
- text === void 0 ? void 0 : import_typescript7.default.createSourceFile(`${LIB_DIR}/${name}`, text, languageVersion)
301677
- );
301378
+ function extractInputSchema(file2, checker) {
301379
+ const call = defineWorkflowCall(file2, checker);
301380
+ if (call === null || call.arguments.length < 2) {
301381
+ return { schema: null, findings: [] };
301678
301382
  }
301679
- return libSourceFiles.get(name);
301680
- }
301681
- var libName = (path) => path.startsWith(`${LIB_DIR}/`) ? path.slice(LIB_DIR.length + 1) : null;
301682
- function position(file2, start) {
301683
- if (file2 === void 0 || start === void 0) {
301684
- return { line: 1, column: 1 };
301383
+ try {
301384
+ const schema = evaluate2(call.arguments[0], checker, /* @__PURE__ */ new Set());
301385
+ if (schema.kind !== "object") {
301386
+ throw new SchemaError(call.arguments[0], "The input schema must be v.object({ ... }).");
301387
+ }
301388
+ return { schema, findings: [] };
301389
+ } catch (error) {
301390
+ if (error instanceof SchemaError) {
301391
+ return {
301392
+ schema: null,
301393
+ findings: [{ node: error.node, code: "static-input-schema", message: error.message }]
301394
+ };
301395
+ }
301396
+ throw error;
301685
301397
  }
301686
- const { line, character } = file2.getLineAndCharacterOfPosition(start);
301687
- return { line: line + 1, column: character + 1 };
301688
301398
  }
301689
- function inputValidatorPosition(file2) {
301399
+ function defineWorkflowCall(file2, checker) {
301690
301400
  for (const statement2 of file2.statements) {
301691
- if (import_typescript7.default.isFunctionDeclaration(statement2) && statement2.name?.text === "validateInput") {
301692
- return statement2.name.getStart(file2);
301693
- }
301694
- if (import_typescript7.default.isVariableStatement(statement2)) {
301695
- for (const declaration of statement2.declarationList.declarations) {
301696
- if (import_typescript7.default.isIdentifier(declaration.name) && declaration.name.text === "validateInput") {
301697
- return declaration.name.getStart(file2);
301698
- }
301699
- }
301401
+ if (import_typescript4.default.isExportAssignment(statement2) && import_typescript4.default.isCallExpression(statement2.expression) && import_typescript4.default.isIdentifier(statement2.expression.expression) && sdkImportName(checker, statement2.expression.expression) === "defineWorkflow") {
301402
+ return statement2.expression;
301700
301403
  }
301701
301404
  }
301702
- return void 0;
301405
+ return null;
301703
301406
  }
301704
- function workspaceResourceNames(file2, program3, workspaceDeclarations) {
301705
- const checker = program3.getTypeChecker();
301706
- const imports = /* @__PURE__ */ new Set();
301707
- const namespaces2 = /* @__PURE__ */ new Set();
301708
- const names2 = /* @__PURE__ */ new Set();
301709
- const ids = /* @__PURE__ */ new Map();
301710
- let needsAll = false;
301711
- const key = (node) => node && (import_typescript7.default.isIdentifier(node) || import_typescript7.default.isStringLiteral(node) || import_typescript7.default.isNoSubstitutionTemplateLiteral(node)) ? node.text : null;
301712
- const unparenthesized = (node) => {
301713
- while (node && import_typescript7.default.isParenthesizedExpression(node)) {
301714
- node = node.expression;
301715
- }
301716
- return node;
301717
- };
301718
- const symbol = (node) => {
301719
- if (import_typescript7.default.isShorthandPropertyAssignment(node.parent)) {
301720
- return checker.getShorthandAssignmentValueSymbol(node.parent);
301721
- }
301722
- if (import_typescript7.default.isExportSpecifier(node.parent) && !node.parent.parent.parent.moduleSpecifier) {
301723
- return checker.getExportSpecifierLocalTargetSymbol(node.parent);
301724
- }
301725
- return checker.getSymbolAtLocation(node);
301726
- };
301727
- const isNamespace = (node) => node && import_typescript7.default.isIdentifier(node) && namespaces2.has(symbol(node));
301728
- const member = (node) => {
301729
- if (import_typescript7.default.isPropertyAccessExpression(node)) {
301730
- return node.name.text;
301731
- }
301732
- if (import_typescript7.default.isElementAccessExpression(node)) {
301733
- const argument = unparenthesized(node.argumentExpression);
301734
- return argument && (import_typescript7.default.isStringLiteral(argument) || import_typescript7.default.isNoSubstitutionTemplateLiteral(argument)) ? argument.text : null;
301735
- }
301407
+ function sdkImportName(checker, identifier4) {
301408
+ const declaration = checker.getSymbolAtLocation(identifier4)?.declarations?.[0];
301409
+ if (declaration === void 0 || !import_typescript4.default.isImportSpecifier(declaration)) {
301736
301410
  return null;
301737
- };
301738
- const isMap3 = (node) => import_typescript7.default.isIdentifier(node) && imports.has(symbol(node)) || (import_typescript7.default.isPropertyAccessExpression(node) || import_typescript7.default.isElementAccessExpression(node)) && isNamespace(unparenthesized(node.expression)) && member(node) === "resources";
301739
- for (const statement2 of file2.statements) {
301740
- if (import_typescript7.default.isExportDeclaration(statement2) && !statement2.isTypeOnly && statement2.moduleSpecifier && import_typescript7.default.isStringLiteral(statement2.moduleSpecifier) && statement2.moduleSpecifier.text === "@diagonal/workflow/workspace" && (!statement2.exportClause || import_typescript7.default.isNamespaceExport(statement2.exportClause) || statement2.exportClause.elements.some(
301741
- (element) => !element.isTypeOnly && (element.propertyName ?? element.name).text === "resources"
301742
- ))) {
301743
- return null;
301744
- }
301745
- if (import_typescript7.default.isImportEqualsDeclaration(statement2)) {
301746
- const reference = statement2.moduleReference;
301747
- if (!statement2.isTypeOnly && import_typescript7.default.isExternalModuleReference(reference) && reference.expression && import_typescript7.default.isStringLiteral(reference.expression) && reference.expression.text === "@diagonal/workflow/workspace") {
301748
- namespaces2.add(checker.getSymbolAtLocation(statement2.name));
301749
- }
301750
- continue;
301751
- }
301752
- if (!import_typescript7.default.isImportDeclaration(statement2) || statement2.moduleSpecifier.text !== "@diagonal/workflow/workspace" || statement2.importClause?.isTypeOnly) {
301753
- continue;
301754
- }
301755
- const bindings = statement2.importClause?.namedBindings;
301756
- if (bindings && import_typescript7.default.isNamespaceImport(bindings)) {
301757
- namespaces2.add(checker.getSymbolAtLocation(bindings.name));
301411
+ }
301412
+ const specifier = declaration.parent.parent.parent.moduleSpecifier;
301413
+ return import_typescript4.default.isStringLiteral(specifier) && specifier.text === SDK_MODULE ? (declaration.propertyName ?? declaration.name).text : null;
301414
+ }
301415
+ var STATIC_HINT = "Build the input schema from v.* calls with literal arguments, so the platform can validate input before the script runs.";
301416
+ function evaluate2(node, checker, visiting) {
301417
+ const expression2 = unwrap2(node);
301418
+ if (import_typescript4.default.isIdentifier(expression2)) {
301419
+ const declaration = checker.getSymbolAtLocation(expression2)?.valueDeclaration;
301420
+ if (declaration === void 0 || !import_typescript4.default.isVariableDeclaration(declaration) || declaration.initializer === void 0 || !(import_typescript4.default.getCombinedNodeFlags(declaration) & import_typescript4.default.NodeFlags.Const) || !import_typescript4.default.isSourceFile(declaration.parent.parent.parent)) {
301421
+ throw new SchemaError(
301422
+ expression2,
301423
+ `${expression2.text} is not a top-level const. ${STATIC_HINT}`
301424
+ );
301758
301425
  }
301759
- if (bindings && import_typescript7.default.isNamedImports(bindings)) {
301760
- for (const binding of bindings.elements) {
301761
- if (!binding.isTypeOnly && (binding.propertyName ?? binding.name).text === "resources") {
301762
- imports.add(checker.getSymbolAtLocation(binding.name));
301763
- }
301764
- }
301426
+ if (visiting.has(declaration)) {
301427
+ throw new SchemaError(expression2, `${expression2.text} refers to itself.`);
301765
301428
  }
301429
+ visiting.add(declaration);
301430
+ const spec = evaluate2(declaration.initializer, checker, visiting);
301431
+ visiting.delete(declaration);
301432
+ return spec;
301766
301433
  }
301767
- const workspace = program3.getSourceFile(WORKSPACE) ?? import_typescript7.default.createSourceFile(WORKSPACE, workspaceDeclarations, import_typescript7.default.ScriptTarget.ES2023, true);
301768
- for (const statement2 of workspace.statements) {
301769
- if (!import_typescript7.default.isVariableStatement(statement2)) {
301770
- continue;
301434
+ if (!import_typescript4.default.isCallExpression(expression2) || !import_typescript4.default.isPropertyAccessExpression(expression2.expression)) {
301435
+ throw new SchemaError(expression2, STATIC_HINT);
301436
+ }
301437
+ const method = expression2.expression.name.text;
301438
+ const receiver = unwrap2(expression2.expression.expression);
301439
+ if (import_typescript4.default.isIdentifier(receiver) && sdkImportName(checker, receiver) === "v") {
301440
+ return builder(method, expression2, checker, visiting);
301441
+ }
301442
+ return modifier(method, evaluate2(receiver, checker, visiting), expression2);
301443
+ }
301444
+ var base = (kind, extra = {}) => ({
301445
+ kind,
301446
+ optional: false,
301447
+ nullable: false,
301448
+ rules: [],
301449
+ ...extra
301450
+ });
301451
+ function builder(method, call, checker, visiting) {
301452
+ const args = call.arguments;
301453
+ if (SCALAR_KINDS.has(method)) {
301454
+ return base(method);
301455
+ }
301456
+ switch (method) {
301457
+ case "select": {
301458
+ const options2 = args[0] && unwrap2(args[0]);
301459
+ if (!options2 || !import_typescript4.default.isArrayLiteralExpression(options2) || options2.elements.length === 0) {
301460
+ throw new SchemaError(call, "v.select() needs a literal array of its options.");
301461
+ }
301462
+ return base("select", { options: options2.elements.map((element) => literal(element)) });
301771
301463
  }
301772
- for (const declaration of statement2.declarationList.declarations) {
301773
- if (!import_typescript7.default.isIdentifier(declaration.name) || declaration.name.text !== "resources") {
301774
- continue;
301464
+ case "list":
301465
+ if (args.length !== 1) {
301466
+ throw new SchemaError(call, "v.list() needs the item field.");
301775
301467
  }
301776
- const value = declaration.initializer && unwrap(declaration.initializer);
301777
- if (!value || !import_typescript7.default.isObjectLiteralExpression(value)) {
301778
- continue;
301468
+ return base("list", { items: evaluate2(args[0], checker, visiting) });
301469
+ case "object": {
301470
+ const shape = args[0] && unwrap2(args[0]);
301471
+ if (!shape || !import_typescript4.default.isObjectLiteralExpression(shape)) {
301472
+ throw new SchemaError(call, "v.object() needs an object literal of fields.");
301779
301473
  }
301780
- for (const property of value.properties) {
301781
- if (import_typescript7.default.isPropertyAssignment(property) && import_typescript7.default.isStringLiteral(property.initializer) && key(property.name) !== null) {
301782
- ids.set(property.initializer.text, key(property.name));
301474
+ const fields = {};
301475
+ for (const property of shape.properties) {
301476
+ if (import_typescript4.default.isPropertyAssignment(property) && (import_typescript4.default.isIdentifier(property.name) || import_typescript4.default.isStringLiteral(property.name))) {
301477
+ fields[property.name.text] = evaluate2(property.initializer, checker, visiting);
301478
+ } else if (import_typescript4.default.isShorthandPropertyAssignment(property)) {
301479
+ fields[property.name.text] = evaluate2(property.name, checker, visiting);
301480
+ } else {
301481
+ throw new SchemaError(
301482
+ property,
301483
+ `Each field of v.object() must be a named field. ${STATIC_HINT}`
301484
+ );
301783
301485
  }
301784
301486
  }
301487
+ return base("object", { fields });
301785
301488
  }
301786
- }
301787
- const visit = (node) => {
301788
- if (needsAll || import_typescript7.default.isImportDeclaration(node) || import_typescript7.default.isImportEqualsDeclaration(node) && import_typescript7.default.isExternalModuleReference(node.moduleReference) || import_typescript7.default.isTypeNode(node)) {
301789
- return;
301790
- }
301791
- if ((import_typescript7.default.isStringLiteral(node) || import_typescript7.default.isNoSubstitutionTemplateLiteral(node)) && ids.has(node.text)) {
301792
- names2.add(ids.get(node.text));
301793
- }
301794
- let use = node;
301795
- while (import_typescript7.default.isParenthesizedExpression(use.parent)) {
301796
- use = use.parent;
301489
+ case "record": {
301490
+ const type = args[0] ? checker.getTypeAtLocation(args[0]) : void 0;
301491
+ if (!type?.isStringLiteral()) {
301492
+ throw new SchemaError(
301493
+ call,
301494
+ "v.record() needs a resource, such as resources.Products from @diagonal/workflow/workspace or Resources.Products.slug from @app/generated/resources in a file-based workspace."
301495
+ );
301496
+ }
301497
+ return base("record", { resource: type.value });
301797
301498
  }
301798
- if (isMap3(node)) {
301799
- const parent = use.parent;
301800
- const name = (import_typescript7.default.isPropertyAccessExpression(parent) || import_typescript7.default.isElementAccessExpression(parent)) && parent.expression === use ? member(parent) : null;
301801
- if (name === null) {
301802
- needsAll = true;
301803
- } else {
301804
- names2.add(name);
301499
+ case "recordReference": {
301500
+ const type = args[0] ? checker.getTypeAtLocation(args[0]) : void 0;
301501
+ if (!type?.isStringLiteral()) {
301502
+ throw new SchemaError(
301503
+ call,
301504
+ "v.recordReference() needs a resource, such as resources.Products from @diagonal/workflow/workspace or Resources.Products.slug from @app/generated/resources in a file-based workspace."
301505
+ );
301805
301506
  }
301806
- } else if (isNamespace(node) && !isMap3(use.parent)) {
301807
- needsAll = true;
301507
+ return base("recordReference", {
301508
+ resource: type.value,
301509
+ ...options(call, args[1], ["scope"])
301510
+ });
301808
301511
  }
301809
- if (!needsAll) {
301810
- import_typescript7.default.forEachChild(node, visit);
301512
+ case "roleReference":
301513
+ return base("roleReference");
301514
+ case "file":
301515
+ return base("file", options(call, args[0], ["accept", "visibility"]));
301516
+ case "content": {
301517
+ const content = options(call, args[0], ["multiLine", "extensions", "allowedNodes"]);
301518
+ return base("content", Object.keys(content).length === 0 ? {} : { content });
301811
301519
  }
301812
- };
301813
- import_typescript7.default.forEachChild(file2, visit);
301814
- return needsAll ? null : [...names2].toSorted((left, right) => left.localeCompare(right));
301520
+ default:
301521
+ throw new SchemaError(call.expression, `v.${method}() is not an input field.`);
301522
+ }
301815
301523
  }
301816
- function scriptResourceNames(file2, program3, workspaceDeclarations, appModules = {}) {
301817
- const names2 = /* @__PURE__ */ new Set();
301818
- for (const source of [
301819
- file2,
301820
- ...Object.keys(appModules).map((path) => program3.getSourceFile(`${APP_ROOT}/${path}`))
301821
- ]) {
301822
- if (source === void 0) {
301823
- return null;
301524
+ function modifier(method, spec, call) {
301525
+ const args = call.arguments;
301526
+ const number = (index3) => {
301527
+ const value = args[index3] === void 0 ? void 0 : literal(args[index3]);
301528
+ if (typeof value !== "number") {
301529
+ throw new SchemaError(call, `.${method}() needs number literals.`);
301824
301530
  }
301825
- const used = workspaceResourceNames(source, program3, workspaceDeclarations);
301826
- if (used === null) {
301827
- return null;
301531
+ return value;
301532
+ };
301533
+ const string = () => {
301534
+ const value = args[0] === void 0 ? void 0 : literal(args[0]);
301535
+ if (typeof value !== "string") {
301536
+ throw new SchemaError(call, `.${method}() needs a string literal.`);
301828
301537
  }
301829
- for (const name of used) {
301830
- names2.add(name);
301538
+ return value;
301539
+ };
301540
+ const withRule = (rule) => ({ ...spec, rules: [...spec.rules, rule] });
301541
+ switch (method) {
301542
+ case "optional":
301543
+ return { ...spec, optional: true };
301544
+ case "nullable":
301545
+ return { ...spec, nullable: true };
301546
+ case "min":
301547
+ case "max":
301548
+ case "size":
301549
+ return withRule(`${method}:${number(0)}`);
301550
+ case "between":
301551
+ return withRule(`between:${number(0)},${number(1)}`);
301552
+ case "regex": {
301553
+ const pattern = args[0] && unwrap2(args[0]);
301554
+ if (!pattern || pattern.kind !== import_typescript4.default.SyntaxKind.RegularExpressionLiteral) {
301555
+ throw new SchemaError(call, ".regex() needs a regular expression literal.");
301556
+ }
301557
+ return withRule(`regex:${pattern.text}`);
301831
301558
  }
301832
- }
301833
- return [...names2].toSorted((left, right) => left.localeCompare(right));
301834
- }
301835
- function createScriptProgram({
301836
- source,
301837
- sdkFiles: sdkFiles2,
301838
- workspaceDeclarations,
301839
- appModules = {},
301840
- profile
301841
- }) {
301842
- const entry = PROFILES[resolveProfile(profile)].entry;
301843
- const files = new Map(
301844
- Object.entries({
301845
- ...sdkFiles2,
301846
- [WORKSPACE]: workspaceDeclarations,
301847
- [SCRIPT]: source,
301848
- [INPUT_VALIDATOR_CHECK]: INPUT_VALIDATOR_CHECK_SOURCE,
301849
- ...Object.fromEntries(
301850
- Object.entries(appModules).map(([path, moduleSource]) => [
301851
- `${APP_ROOT}/${path}`,
301852
- moduleSource
301853
- ])
301854
- )
301855
- })
301856
- );
301857
- const host = {
301858
- getSourceFile: (name, languageVersion) => {
301859
- const lib = libName(name);
301860
- if (lib !== null) {
301861
- return libSourceFile(lib, languageVersion);
301862
- }
301863
- return files.has(name) ? import_typescript7.default.createSourceFile(name, files.get(name), languageVersion, true) : void 0;
301864
- },
301865
- getDefaultLibFileName: () => `${LIB_DIR}/${ROOT_LIB}`,
301866
- getDefaultLibLocation: () => LIB_DIR,
301867
- writeFile: () => {
301868
- },
301869
- getCurrentDirectory: () => "/",
301870
- getCanonicalFileName: (name) => name,
301871
- useCaseSensitiveFileNames: () => true,
301872
- getNewLine: () => "\n",
301873
- fileExists: (name) => files.has(name) || libName(name) !== null && readLibFile(libName(name)) !== void 0,
301874
- readFile: (name) => files.get(name) ?? (libName(name) !== null ? readLibFile(libName(name)) : void 0),
301875
- directoryExists: (name) => {
301876
- const prefix2 = name.endsWith("/") ? name : `${name}/`;
301877
- return prefix2 === `${LIB_DIR}/` || [...files.keys()].some((path) => path.startsWith(prefix2));
301878
- },
301879
- getDirectories: () => []
301880
- };
301881
- const program3 = import_typescript7.default.createProgram({
301882
- rootNames: [SCRIPT, INPUT_VALIDATOR_CHECK, WORKSPACE, ...entry === null ? [] : [entry]],
301883
- options: Object.keys(appModules).length === 0 ? OPTIONS : { ...OPTIONS, paths: { ...OPTIONS.paths, "@app/*": [`${APP_ROOT}/*`] } },
301884
- host
301885
- });
301886
- return { program: program3, file: program3.getSourceFile(SCRIPT) };
301559
+ case "rule":
301560
+ return withRule(string());
301561
+ case "label":
301562
+ return { ...spec, label: string() };
301563
+ case "description":
301564
+ return { ...spec, description: string() };
301565
+ default:
301566
+ throw new SchemaError(call.expression, `.${method}() is not an input field modifier.`);
301567
+ }
301887
301568
  }
301888
- function servedProfileImports(context) {
301889
- const { factory } = context;
301890
- const served = (specifier) => import_typescript7.default.isStringLiteral(specifier) && PROFILE_SPECIFIERS.has(specifier.text) ? factory.createStringLiteral("@diagonal/workflow") : specifier;
301891
- return (sourceFile) => factory.updateSourceFile(
301892
- sourceFile,
301893
- sourceFile.statements.map((statement2) => {
301894
- if (import_typescript7.default.isImportDeclaration(statement2)) {
301895
- return factory.updateImportDeclaration(
301896
- statement2,
301897
- statement2.modifiers,
301898
- statement2.importClause,
301899
- served(statement2.moduleSpecifier),
301900
- statement2.attributes
301901
- );
301902
- }
301903
- if (import_typescript7.default.isImportEqualsDeclaration(statement2) && import_typescript7.default.isExternalModuleReference(statement2.moduleReference)) {
301904
- return factory.updateImportEqualsDeclaration(
301905
- statement2,
301906
- statement2.modifiers,
301907
- statement2.isTypeOnly,
301908
- statement2.name,
301909
- factory.updateExternalModuleReference(
301910
- statement2.moduleReference,
301911
- served(statement2.moduleReference.expression)
301912
- )
301913
- );
301914
- }
301915
- if (import_typescript7.default.isExportDeclaration(statement2) && statement2.moduleSpecifier) {
301916
- return factory.updateExportDeclaration(
301917
- statement2,
301918
- statement2.modifiers,
301919
- statement2.isTypeOnly,
301920
- statement2.exportClause,
301921
- served(statement2.moduleSpecifier),
301922
- statement2.attributes
301569
+ function options(call, node, keys2) {
301570
+ if (node === void 0) {
301571
+ return {};
301572
+ }
301573
+ const value = literalData(node);
301574
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
301575
+ throw new SchemaError(
301576
+ node,
301577
+ `v.${call.expression.name.text}() needs an object literal of options.`
301578
+ );
301579
+ }
301580
+ const unknown = Object.keys(value).find((key) => !keys2.includes(key));
301581
+ if (unknown !== void 0) {
301582
+ throw new SchemaError(node, `v.${call.expression.name.text}() has no option "${unknown}".`);
301583
+ }
301584
+ return value;
301585
+ }
301586
+ function literalData(node) {
301587
+ const expression2 = unwrap2(node);
301588
+ if (expression2.kind === import_typescript4.default.SyntaxKind.TrueKeyword) {
301589
+ return true;
301590
+ }
301591
+ if (expression2.kind === import_typescript4.default.SyntaxKind.FalseKeyword) {
301592
+ return false;
301593
+ }
301594
+ if (import_typescript4.default.isArrayLiteralExpression(expression2)) {
301595
+ return expression2.elements.map((element) => literalData(element));
301596
+ }
301597
+ if (import_typescript4.default.isObjectLiteralExpression(expression2)) {
301598
+ const result = {};
301599
+ for (const property of expression2.properties) {
301600
+ if (!import_typescript4.default.isPropertyAssignment(property) || !(import_typescript4.default.isIdentifier(property.name) || import_typescript4.default.isStringLiteral(property.name))) {
301601
+ throw new SchemaError(
301602
+ property,
301603
+ `Use a named property with a literal value. ${STATIC_HINT}`
301923
301604
  );
301924
301605
  }
301925
- return statement2;
301926
- })
301927
- );
301606
+ result[property.name.text] = literalData(property.initializer);
301607
+ }
301608
+ return result;
301609
+ }
301610
+ return literal(expression2);
301928
301611
  }
301929
- function compileWorkflowScript(request2, scriptProgram = createScriptProgram(request2)) {
301930
- let code2 = null;
301931
- const { program: program3, file: file2 } = scriptProgram;
301932
- const diagnostics = [];
301933
- for (const diagnostic2 of import_typescript7.default.getPreEmitDiagnostics(program3, file2)) {
301934
- diagnostics.push({
301935
- severity: "error",
301936
- code: `TS${diagnostic2.code}`,
301937
- message: import_typescript7.default.flattenDiagnosticMessageText(diagnostic2.messageText, "\n"),
301938
- ...position(diagnostic2.file, diagnostic2.start)
301939
- });
301612
+ function literal(node) {
301613
+ const expression2 = unwrap2(node);
301614
+ if (import_typescript4.default.isStringLiteral(expression2) || import_typescript4.default.isNoSubstitutionTemplateLiteral(expression2)) {
301615
+ return expression2.text;
301940
301616
  }
301941
- for (const diagnostic2 of program3.getSemanticDiagnostics(
301942
- program3.getSourceFile(INPUT_VALIDATOR_CHECK)
301943
- )) {
301944
- diagnostics.push({
301945
- severity: "error",
301946
- code: `TS${diagnostic2.code}`,
301947
- message: `validateInput must be (input, ctx) => InputErrors<Input> | void for this workflow's input. ${import_typescript7.default.flattenDiagnosticMessageText(diagnostic2.messageText, "\n")}`,
301948
- ...position(file2, inputValidatorPosition(file2))
301949
- });
301617
+ if (import_typescript4.default.isNumericLiteral(expression2)) {
301618
+ return Number(expression2.text);
301950
301619
  }
301951
- const inputSchema = extractInputSchema(file2, program3.getTypeChecker());
301952
- const allowAppImports = Object.keys(request2.appModules ?? {}).length > 0;
301953
- const profile = resolveProfile(request2.profile);
301954
- for (const finding of [
301955
- ...lint2(file2, program3.getTypeChecker(), { allowAppImports, profile }),
301956
- ...profileFindings(file2, program3.getTypeChecker(), program3, profile),
301957
- ...inputSchema.findings
301958
- ]) {
301959
- diagnostics.push({
301960
- severity: "error",
301961
- code: finding.code,
301962
- message: finding.message,
301963
- ...position(file2, finding.position ?? finding.node.getStart(file2))
301964
- });
301620
+ if (import_typescript4.default.isPrefixUnaryExpression(expression2) && expression2.operator === import_typescript4.default.SyntaxKind.MinusToken && import_typescript4.default.isNumericLiteral(expression2.operand)) {
301621
+ return -Number(expression2.operand.text);
301965
301622
  }
301966
- if (diagnostics.length === 0) {
301967
- program3.emit(
301968
- file2,
301969
- (name, text) => {
301970
- if (name === "/workflow.js") {
301971
- code2 = text;
301972
- }
301973
- },
301974
- void 0,
301975
- false,
301976
- { before: [servedProfileImports] }
301977
- );
301623
+ throw new SchemaError(expression2, `Use a literal value here. ${STATIC_HINT}`);
301624
+ }
301625
+
301626
+ // scripts/lib/workflow-script/lib-files.mjs
301627
+ init_define_globalThis_DIAGONAL_SDK_RUNTIME();
301628
+ import { readFileSync as readFileSync7 } from "node:fs";
301629
+ import { createRequire as createRequire2 } from "node:module";
301630
+ import { dirname as dirname5, join as join10 } from "node:path";
301631
+ var ROOT_LIB = "lib.es2023.d.ts";
301632
+ function libClosure(read, root = ROOT_LIB) {
301633
+ const files = {};
301634
+ const pending = [root];
301635
+ while (pending.length > 0) {
301636
+ const name = pending.pop();
301637
+ if (Object.hasOwn(files, name)) {
301638
+ continue;
301639
+ }
301640
+ files[name] = read(name);
301641
+ for (const match of files[name].matchAll(/<reference lib="([^"]+)"/g)) {
301642
+ pending.push(`lib.${match[1].toLowerCase()}.d.ts`);
301643
+ }
301978
301644
  }
301979
- return {
301980
- ok: diagnostics.length === 0 && code2 !== null,
301981
- code: diagnostics.length === 0 ? code2 : null,
301982
- input: diagnostics.length === 0 ? inputSchema.schema : null,
301983
- resources: diagnostics.length === 0 ? scriptResourceNames(file2, program3, request2.workspaceDeclarations, request2.appModules) : null,
301984
- diagnostics: diagnostics.toSorted((a, b2) => a.line - b2.line || a.column - b2.column)
301985
- };
301645
+ return files;
301646
+ }
301647
+ function readLibClosure(root = ROOT_LIB) {
301648
+ const libDir = dirname5(createRequire2(import.meta.url).resolve("typescript/lib/lib.d.ts"));
301649
+ return libClosure((name) => readFileSync7(join10(libDir, name), "utf8"), root);
301986
301650
  }
301987
301651
 
301988
- // scripts/lib/runtime-build/workflow-config.mjs
301652
+ // scripts/lib/workflow-script/lint-rules.mjs
301989
301653
  init_define_globalThis_DIAGONAL_SDK_RUNTIME();
301990
- var WORKFLOW_STAGE = "workflow";
301991
- var UUID_PATTERN2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
301992
- var ROUTE_PATTERN = /^\/[a-z0-9\-_/{}]*$/;
301993
- var ROUTE_PARAM_PATTERN = /\{([^}]+)\}/g;
301994
- var CRON_FIELD_PATTERN = /^[0-9A-Za-z*/,\-?#]+$/;
301995
- var OFFSET_PATTERN = /^[+-]P(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?)?$/i;
301996
- var WORKFLOW_PATH_PATTERN = /^workflows\/[^/]+\.ts$/;
301997
- var CONFIG_KEYS = /* @__PURE__ */ new Set(["title", "description", "trigger", "runAs", "authorizer"]);
301998
- var HTTP_METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE"];
301999
- var RECORD_EVENTS = ["created", "updated", "deleted", "restored", "saved"];
302000
- var LIFECYCLE_HOOKS = ["creating", "updating", "saving", "deleting", "restoring"];
302001
- var WORKFLOW_EVENTS = ["execution.success", "execution.error", "execution.exception"];
302002
- var SCHEDULE_FIELD_TYPES = /* @__PURE__ */ new Set(["date", "datetime"]);
302003
- var TRIGGERS = {
302004
- request: {
302005
- type: "request",
302006
- keys: ["type", "path", "method"],
302007
- background: false,
302008
- sync: true
301654
+ var import_typescript6 = __toESM(require_typescript(), 1);
301655
+
301656
+ // scripts/lib/workflow-script/profile-rules.mjs
301657
+ init_define_globalThis_DIAGONAL_SDK_RUNTIME();
301658
+ var import_typescript5 = __toESM(require_typescript(), 1);
301659
+ var PROFILES = {
301660
+ workflow: {
301661
+ label: "A workflow script",
301662
+ imports: ["@diagonal/workflow", "@diagonal/workflow/workspace"],
301663
+ specifier: null,
301664
+ entry: null
302009
301665
  },
302010
- recordEvent: {
302011
- type: "event.record",
302012
- keys: ["type", "resource", "event", "filters"],
302013
- background: true,
302014
- sync: false
302015
- },
302016
- recordLifecycle: {
302017
- type: "lifecycle.record",
302018
- keys: ["type", "resource", "hook"],
302019
- background: false,
302020
- sync: true
302021
- },
302022
- recordSchedule: {
302023
- type: "schedule.record",
302024
- keys: ["type", "resource", "dateField", "offsets"],
302025
- background: true,
302026
- sync: false
302027
- },
302028
- scheduled: {
302029
- type: "scheduled",
302030
- keys: ["type", "expression"],
302031
- background: true,
302032
- sync: false
302033
- },
302034
- workflowEvent: {
302035
- type: "event.workflow",
302036
- keys: ["type", "workflow", "event"],
302037
- background: true,
302038
- sync: false
301666
+ test: {
301667
+ label: "A test script",
301668
+ imports: ["@diagonal/workflow", "@diagonal-hq/workflows/test", "@diagonal/workflow/workspace"],
301669
+ specifier: "@diagonal-hq/workflows/test",
301670
+ entry: "/sdk/profiles/test.ts"
302039
301671
  },
302040
- manual: {
302041
- type: "manual",
302042
- keys: ["type"],
302043
- background: false,
302044
- sync: true
301672
+ migration: {
301673
+ label: "A migration script",
301674
+ imports: ["@diagonal-hq/workflows/migration", "@diagonal/workflow/workspace"],
301675
+ specifier: "@diagonal-hq/workflows/migration",
301676
+ entry: "/sdk/profiles/migration.ts"
302045
301677
  }
302046
301678
  };
302047
- function unwrap2(node) {
302048
- let current = node;
302049
- while (current.type === "TSAsExpression" || current.type === "TSSatisfiesExpression" || current.type === "TSNonNullExpression" || current.type === "ParenthesizedExpression") {
302050
- current = current.expression;
301679
+ var PROFILE_SPECIFIERS = new Set(
301680
+ Object.values(PROFILES).flatMap(({ specifier }) => specifier === null ? [] : [specifier])
301681
+ );
301682
+ var SDK_SPECIFIERS = /* @__PURE__ */ new Set(["@diagonal/workflow", ...PROFILE_SPECIFIERS]);
301683
+ function resolveProfile(name) {
301684
+ if (name === void 0 || name === null) {
301685
+ return "workflow";
302051
301686
  }
302052
- return current;
301687
+ if (typeof name !== "string" || !Object.hasOwn(PROFILES, name)) {
301688
+ throw new Error(`Unknown workflow script profile: ${String(name)}`);
301689
+ }
301690
+ return name;
302053
301691
  }
302054
- function propertyNodes(node) {
302055
- const unwrapped = node === void 0 ? null : unwrap2(node);
302056
- const nodes = /* @__PURE__ */ new Map();
302057
- if (unwrapped?.type !== "ObjectExpression") {
302058
- return nodes;
301692
+ function profileFindings(file2, checker, program3, profile) {
301693
+ const { entry, label, specifier } = PROFILES[profile];
301694
+ if (entry === null) {
301695
+ return [];
302059
301696
  }
302060
- for (const property of unwrapped.properties) {
302061
- if (property.type === "ObjectProperty") {
302062
- nodes.set(propertyKey(property), property);
301697
+ const entryFile = program3.getSourceFile(entry);
301698
+ const entrySymbol = entryFile && checker.getSymbolAtLocation(entryFile);
301699
+ if (!entrySymbol) {
301700
+ throw new Error(`The SDK has no ${entry} module.`);
301701
+ }
301702
+ const exports = new Map(
301703
+ checker.getExportsOfModule(entrySymbol).map((symbol) => [symbol.getName(), symbol])
301704
+ );
301705
+ const findings = [];
301706
+ const forbidden = (node, path) => findings.push({
301707
+ node,
301708
+ code: "profile-capability",
301709
+ message: `${label} cannot use ${path}. Use only the exports of ${specifier}.`
301710
+ });
301711
+ const exportType = (name) => {
301712
+ const symbol = exports.get(name);
301713
+ const target = symbol && symbol.flags & import_typescript5.default.SymbolFlags.Alias ? checker.getAliasedSymbol(symbol) : symbol;
301714
+ return target && target.flags & import_typescript5.default.SymbolFlags.Value ? checker.getTypeOfSymbolAtLocation(target, entryFile) : null;
301715
+ };
301716
+ const checkMembers = (identifier4, type, path) => {
301717
+ let node = identifier4;
301718
+ let current = type;
301719
+ let currentPath = path;
301720
+ while (current !== null) {
301721
+ const parent = node.parent;
301722
+ const isMemberAccess = import_typescript5.default.isPropertyAccessExpression(parent) && parent.expression === node || import_typescript5.default.isElementAccessExpression(parent) && parent.expression === node && import_typescript5.default.isStringLiteralLike(parent.argumentExpression);
301723
+ if (!isMemberAccess) {
301724
+ if (current.getCallSignatures().length === 0 && hasRestrictedMembers(current, currentPath)) {
301725
+ forbidden(node, `${currentPath} as a value`);
301726
+ }
301727
+ return;
301728
+ }
301729
+ const member = import_typescript5.default.isPropertyAccessExpression(parent) ? parent.name.text : parent.argumentExpression.text;
301730
+ const property = current.getProperty(member);
301731
+ currentPath = `${currentPath}.${member}`;
301732
+ if (!property) {
301733
+ forbidden(parent, currentPath);
301734
+ return;
301735
+ }
301736
+ current = checker.getTypeOfSymbolAtLocation(property, entryFile);
301737
+ node = parent;
301738
+ }
301739
+ };
301740
+ const hasRestrictedMembers = (profileType, path) => {
301741
+ const rootType = rootNamespaceTypes.get(path);
301742
+ return rootType !== void 0 && rootType.getProperties().some((property) => !profileType.getProperty(property.getName()));
301743
+ };
301744
+ const rootNamespaceTypes = /* @__PURE__ */ new Map();
301745
+ const rootFile = program3.getSourceFile("/sdk/index.ts");
301746
+ const rootSymbol = rootFile && checker.getSymbolAtLocation(rootFile);
301747
+ for (const symbol of rootSymbol ? checker.getExportsOfModule(rootSymbol) : []) {
301748
+ const target = symbol.flags & import_typescript5.default.SymbolFlags.Alias ? checker.getAliasedSymbol(symbol) : symbol;
301749
+ if (target.flags & import_typescript5.default.SymbolFlags.Value) {
301750
+ collectNamespaceTypes(
301751
+ checker,
301752
+ symbol.getName(),
301753
+ checker.getTypeOfSymbolAtLocation(target, rootFile),
301754
+ rootFile,
301755
+ rootNamespaceTypes
301756
+ );
301757
+ }
301758
+ }
301759
+ const valueSymbol = (node) => import_typescript5.default.isShorthandPropertyAssignment(node.parent) && node.parent.name === node ? checker.getShorthandAssignmentValueSymbol(node.parent) : checker.getSymbolAtLocation(node);
301760
+ const references = (binding) => {
301761
+ const symbol = checker.getSymbolAtLocation(binding);
301762
+ const found2 = [];
301763
+ const visit = (node) => {
301764
+ if (import_typescript5.default.isIdentifier(node) && node !== binding && valueSymbol(node) === symbol && !import_typescript5.default.isImportSpecifier(node.parent)) {
301765
+ found2.push(node);
301766
+ }
301767
+ import_typescript5.default.forEachChild(node, visit);
301768
+ };
301769
+ visit(file2);
301770
+ return found2;
301771
+ };
301772
+ const checkNamespace = (binding) => {
301773
+ for (const reference of references(binding)) {
301774
+ const parent = reference.parent;
301775
+ if (!import_typescript5.default.isPropertyAccessExpression(parent) || parent.expression !== reference) {
301776
+ forbidden(reference, "the SDK namespace as a value");
301777
+ continue;
301778
+ }
301779
+ const name = parent.name.text;
301780
+ if (!exports.has(name)) {
301781
+ forbidden(parent, name);
301782
+ continue;
301783
+ }
301784
+ const type = exportType(name);
301785
+ if (type !== null) {
301786
+ checkMembers(parent, type, name);
301787
+ }
301788
+ }
301789
+ };
301790
+ for (const statement2 of file2.statements) {
301791
+ if (import_typescript5.default.isImportEqualsDeclaration(statement2) && import_typescript5.default.isExternalModuleReference(statement2.moduleReference) && import_typescript5.default.isStringLiteral(statement2.moduleReference.expression) && SDK_SPECIFIERS.has(statement2.moduleReference.expression.text)) {
301792
+ checkNamespace(statement2.name);
301793
+ continue;
301794
+ }
301795
+ if (!import_typescript5.default.isImportDeclaration(statement2) || !import_typescript5.default.isStringLiteral(statement2.moduleSpecifier) || !SDK_SPECIFIERS.has(statement2.moduleSpecifier.text) || !statement2.importClause) {
301796
+ continue;
301797
+ }
301798
+ const clause = statement2.importClause;
301799
+ if (clause.name) {
301800
+ forbidden(clause.name, "a default import of the SDK");
301801
+ }
301802
+ const bindings = clause.namedBindings;
301803
+ if (bindings && import_typescript5.default.isNamespaceImport(bindings)) {
301804
+ checkNamespace(bindings.name);
301805
+ continue;
301806
+ }
301807
+ for (const element of bindings && import_typescript5.default.isNamedImports(bindings) ? bindings.elements : []) {
301808
+ const name = (element.propertyName ?? element.name).text;
301809
+ if (!exports.has(name)) {
301810
+ forbidden(element, name);
301811
+ continue;
301812
+ }
301813
+ const type = exportType(name);
301814
+ if (type === null || element.isTypeOnly || clause.isTypeOnly) {
301815
+ continue;
301816
+ }
301817
+ for (const reference of references(element.name)) {
301818
+ checkMembers(reference, type, name);
301819
+ }
301820
+ }
301821
+ }
301822
+ return findings;
301823
+ }
301824
+ function collectNamespaceTypes(checker, path, type, location, into) {
301825
+ if (type.getCallSignatures().length > 0 || !(type.flags & import_typescript5.default.TypeFlags.Object)) {
301826
+ return;
301827
+ }
301828
+ into.set(path, type);
301829
+ for (const property of type.getProperties()) {
301830
+ collectNamespaceTypes(
301831
+ checker,
301832
+ `${path}.${property.getName()}`,
301833
+ checker.getTypeOfSymbolAtLocation(property, location),
301834
+ location,
301835
+ into
301836
+ );
301837
+ }
301838
+ }
301839
+
301840
+ // scripts/lib/workflow-script/lint-rules.mjs
301841
+ var UNSUPPORTED_GLOBALS = {
301842
+ Intl: "The sandbox has no Intl. Use date.format, time.format, money.format, or number.format.",
301843
+ crypto: "The sandbox has no crypto. Use text.hash, text.randomUuid, or security.randomPassword.",
301844
+ setTimeout: "The sandbox has no timers.",
301845
+ setInterval: "The sandbox has no timers.",
301846
+ fetch: "The sandbox has no network. Use http.request.",
301847
+ process: "The sandbox has no process.",
301848
+ require: "Use an import from @diagonal/workflow."
301849
+ };
301850
+ var FLOATING_MESSAGE = "Await this call, return it, or assign it. A call that is not awaited can fail without stopping the workflow.";
301851
+ var MAIL_TEMPLATE_CAPABILITIES = {
301852
+ MailSendInput: "mail.send",
301853
+ NotificationSendInput: "notification.send"
301854
+ };
301855
+ var MAIL_REFERENCES_KEY = "$references";
301856
+ var composedMailTextMessage = (capability, field2) => `Do not write values into the ${capability} ${field2}. The email evaluates this text as Liquid, so a value such as "{{ workspace.name }}" renders. Put each value in layoutData.${MAIL_REFERENCES_KEY} and write {{ ref.<key> }} in the text.`;
301857
+ function staticPropertyName(property) {
301858
+ if (!import_typescript6.default.isPropertyAssignment(property) && !import_typescript6.default.isShorthandPropertyAssignment(property)) {
301859
+ return null;
301860
+ }
301861
+ return propertyNameText(property.name);
301862
+ }
301863
+ function floatingPromiseCalls(expression2, holdsPromise) {
301864
+ const node = import_typescript6.default.skipParentheses(expression2);
301865
+ if (import_typescript6.default.isConditionalExpression(node)) {
301866
+ return [
301867
+ ...floatingPromiseCalls(node.whenTrue, holdsPromise),
301868
+ ...floatingPromiseCalls(node.whenFalse, holdsPromise)
301869
+ ];
301870
+ }
301871
+ if (import_typescript6.default.isBinaryExpression(node) && [
301872
+ import_typescript6.default.SyntaxKind.AmpersandAmpersandToken,
301873
+ import_typescript6.default.SyntaxKind.BarBarToken,
301874
+ import_typescript6.default.SyntaxKind.QuestionQuestionToken,
301875
+ import_typescript6.default.SyntaxKind.CommaToken
301876
+ ].includes(node.operatorToken.kind)) {
301877
+ return [
301878
+ ...floatingPromiseCalls(node.left, holdsPromise),
301879
+ ...floatingPromiseCalls(node.right, holdsPromise)
301880
+ ];
301881
+ }
301882
+ return (import_typescript6.default.isCallExpression(node) || import_typescript6.default.isArrayLiteralExpression(node)) && holdsPromise(node) ? [node] : [];
301883
+ }
301884
+ function returnsPromise(fn, checker) {
301885
+ const signature = checker.getSignatureFromDeclaration(fn);
301886
+ return signature !== void 0 && checker.getReturnTypeOfSignature(signature).getSymbol()?.getName() === "Promise";
301887
+ }
301888
+ function contextuallyReturnsVoid(fn, checker) {
301889
+ const signatures = checker.getContextualType(fn)?.getCallSignatures() ?? [];
301890
+ return signatures.length > 0 && signatures.every(
301891
+ (signature) => (checker.getReturnTypeOfSignature(signature).flags & import_typescript6.default.TypeFlags.Void) !== 0
301892
+ );
301893
+ }
301894
+ function isMemberName(node) {
301895
+ const parent = node.parent;
301896
+ if (import_typescript6.default.isPropertyAccessExpression(parent) || import_typescript6.default.isQualifiedName(parent)) {
301897
+ return parent.name === node || parent.right === node;
301898
+ }
301899
+ if (import_typescript6.default.isBindingElement(parent) || import_typescript6.default.isImportSpecifier(parent) || import_typescript6.default.isExportSpecifier(parent)) {
301900
+ return parent.propertyName === node;
301901
+ }
301902
+ return (import_typescript6.default.isPropertyAssignment(parent) || import_typescript6.default.isPropertyDeclaration(parent) || import_typescript6.default.isPropertySignature(parent) || import_typescript6.default.isMethodDeclaration(parent) || import_typescript6.default.isMethodSignature(parent) || import_typescript6.default.isGetAccessorDeclaration(parent) || import_typescript6.default.isSetAccessorDeclaration(parent) || import_typescript6.default.isEnumMember(parent)) && parent.name === node;
301903
+ }
301904
+ function lint2(file2, checker, { allowAppImports = false, profile = "workflow" } = {}) {
301905
+ const findings = [];
301906
+ const { imports: allowedImports, label } = PROFILES[profile];
301907
+ const allowedImportList = new Intl.ListFormat("en", { type: "disjunction" }).format(
301908
+ allowedImports
301909
+ );
301910
+ let defaultExport = null;
301911
+ const isPromiseType = (type) => type.getSymbol()?.getName() === "Promise";
301912
+ const holdsPromise = (node) => {
301913
+ const type = checker.getTypeAtLocation(node);
301914
+ if (checker.isArrayType(type) || checker.isTupleType(type)) {
301915
+ return checker.getTypeArguments(type).some(isPromiseType);
301916
+ }
301917
+ return isPromiseType(type);
301918
+ };
301919
+ const isDeclaredInScript = (symbol) => symbol?.declarations?.some((declaration) => declaration.getSourceFile() === file2) ?? false;
301920
+ const mailTemplateCapability = (call) => {
301921
+ const [parameter] = checker.getResolvedSignature(call)?.getParameters() ?? [];
301922
+ const inputType = parameter && checker.getTypeOfSymbolAtLocation(parameter, call).getSymbol();
301923
+ const fromSdk = inputType?.declarations?.some(
301924
+ (declaration) => declaration.getSourceFile().fileName.startsWith("/sdk/")
301925
+ ) ?? false;
301926
+ return fromSdk && Object.hasOwn(MAIL_TEMPLATE_CAPABILITIES, inputType.getName()) ? MAIL_TEMPLATE_CAPABILITIES[inputType.getName()] : null;
301927
+ };
301928
+ const constValue = (expression2) => {
301929
+ const node = unwrap2(expression2);
301930
+ if (!import_typescript6.default.isIdentifier(node)) {
301931
+ return node;
301932
+ }
301933
+ const symbol = import_typescript6.default.isShorthandPropertyAssignment(node.parent) && node.parent.name === node ? checker.getShorthandAssignmentValueSymbol(node.parent) : checker.getSymbolAtLocation(node);
301934
+ const declaration = symbol?.valueDeclaration;
301935
+ return declaration !== void 0 && import_typescript6.default.isVariableDeclaration(declaration) && declaration.initializer !== void 0 && declaration.getSourceFile() === file2 && (import_typescript6.default.getCombinedNodeFlags(declaration) & import_typescript6.default.NodeFlags.Const) !== 0 ? unwrap2(declaration.initializer) : node;
301936
+ };
301937
+ const hasLiteralType = (node) => {
301938
+ const type = checker.getTypeAtLocation(node);
301939
+ return (type.isUnion() ? type.types : [type]).every(
301940
+ (member) => member.isLiteral() || (member.flags & import_typescript6.default.TypeFlags.BooleanLiteral) !== 0
301941
+ );
301942
+ };
301943
+ const isConstantText = (expression2, followed = /* @__PURE__ */ new Set()) => {
301944
+ const node = unwrap2(expression2);
301945
+ if (import_typescript6.default.isTemplateExpression(node)) {
301946
+ return node.templateSpans.every((span) => isConstantText(span.expression, followed));
301947
+ }
301948
+ if (import_typescript6.default.isBinaryExpression(node) && node.operatorToken.kind === import_typescript6.default.SyntaxKind.PlusToken) {
301949
+ return isConstantText(node.left, followed) && isConstantText(node.right, followed);
301950
+ }
301951
+ if (hasLiteralType(node)) {
301952
+ return true;
301953
+ }
301954
+ const initializer = import_typescript6.default.isIdentifier(node) ? constValue(node) : node;
301955
+ if (initializer === node || followed.has(initializer)) {
301956
+ return false;
302063
301957
  }
302064
- }
302065
- return nodes;
302066
- }
302067
- function listOf(values) {
302068
- return values.map((value) => `'${value}'`).join(", ");
302069
- }
302070
- function blank(text) {
302071
- return text.replaceAll(/[^\n]/g, " ");
302072
- }
302073
- function isConfigExport(statement2) {
302074
- return statement2.type === "ExportNamedDeclaration" && statement2.declaration?.type === "VariableDeclaration" && statement2.declaration.declarations.some(
302075
- (declarator) => declarator.id.type === "Identifier" && declarator.id.name === "config"
302076
- );
302077
- }
302078
- function splitWorkflowModule(path, source, ast) {
302079
- const diagnostics = [];
302080
- const ranges = [];
302081
- let configNode = null;
302082
- let configCount = 0;
302083
- let hasDefault = false;
302084
- for (const statement2 of ast.program.body) {
302085
- if (statement2.type === "ImportDeclaration" && isAuthoringModule(statement2.source.value)) {
302086
- ranges.push(statement2);
302087
- continue;
301958
+ return isConstantText(initializer, /* @__PURE__ */ new Set([...followed, initializer]));
301959
+ };
301960
+ const composedMailText = (expression2) => {
301961
+ const node = unwrap2(expression2);
301962
+ if (import_typescript6.default.isConditionalExpression(node)) {
301963
+ return composedMailText(node.whenTrue) ?? composedMailText(node.whenFalse);
302088
301964
  }
302089
- if (statement2.type === "ExportDefaultDeclaration") {
302090
- hasDefault = true;
302091
- continue;
301965
+ if (import_typescript6.default.isBinaryExpression(node) && [import_typescript6.default.SyntaxKind.BarBarToken, import_typescript6.default.SyntaxKind.QuestionQuestionToken].includes(
301966
+ node.operatorToken.kind
301967
+ )) {
301968
+ return composedMailText(node.left) ?? composedMailText(node.right);
302092
301969
  }
302093
- if (!isConfigExport(statement2)) {
302094
- continue;
301970
+ const isConcatenation = import_typescript6.default.isBinaryExpression(node) && node.operatorToken.kind === import_typescript6.default.SyntaxKind.PlusToken && (checker.getTypeAtLocation(node).flags & import_typescript6.default.TypeFlags.StringLike) !== 0;
301971
+ return (import_typescript6.default.isTemplateExpression(node) || isConcatenation) && !isConstantText(node) ? node : null;
301972
+ };
301973
+ const checkMailTemplateCall = (call) => {
301974
+ const capability = call.arguments.length > 0 ? mailTemplateCapability(call) : null;
301975
+ const input = capability === null ? null : constValue(call.arguments[0]);
301976
+ if (input === null || !import_typescript6.default.isObjectLiteralExpression(input)) {
301977
+ return;
302095
301978
  }
302096
- configCount++;
302097
- ranges.push(statement2);
302098
- const declaration = statement2.declaration;
302099
- if (configCount > 1) {
302100
- diagnostics.push(
302101
- diagnosticAt(path, statement2, "A workflow can export only one config", {
302102
- stage: WORKFLOW_STAGE
302103
- })
302104
- );
302105
- continue;
301979
+ const valueOf = (property) => import_typescript6.default.isShorthandPropertyAssignment(property) ? property.name : property.initializer;
301980
+ const check2 = (value, field2) => {
301981
+ const composed = composedMailText(constValue(value));
301982
+ if (composed !== null) {
301983
+ findings.push({
301984
+ node: composed,
301985
+ code: "no-composed-mail-text",
301986
+ message: composedMailTextMessage(capability, field2)
301987
+ });
301988
+ }
301989
+ };
301990
+ for (const property of input.properties) {
301991
+ const name = staticPropertyName(property);
301992
+ if (name === "subject") {
301993
+ check2(valueOf(property), "subject");
301994
+ }
301995
+ const layoutData = name === "layoutData" ? constValue(valueOf(property)) : null;
301996
+ if (layoutData === null || !import_typescript6.default.isObjectLiteralExpression(layoutData)) {
301997
+ continue;
301998
+ }
301999
+ for (const slot of layoutData.properties) {
302000
+ const slotName = staticPropertyName(slot);
302001
+ if (slotName !== null && slotName !== MAIL_REFERENCES_KEY) {
302002
+ check2(valueOf(slot), `layoutData.${slotName}`);
302003
+ }
302004
+ }
302106
302005
  }
302107
- if (declaration.kind !== "const" || declaration.declarations.length !== 1) {
302108
- diagnostics.push(
302109
- diagnosticAt(
302110
- path,
302111
- statement2,
302112
- "Declare the config alone as `export const config = { ... }`",
302113
- { stage: WORKFLOW_STAGE }
302114
- )
302115
- );
302116
- continue;
302006
+ };
302007
+ const checkModuleSpecifier = (node, specifier) => {
302008
+ if (specifier && import_typescript6.default.isStringLiteral(specifier) && !allowedImports.includes(specifier.text) && !(allowAppImports && specifier.text.startsWith("@app/"))) {
302009
+ findings.push({
302010
+ node,
302011
+ code: "allowed-imports",
302012
+ message: profile === "workflow" ? `Import only @diagonal/workflow or @diagonal/workflow/workspace, not ${specifier.text}.` : `${label} imports only ${allowedImportList}, not ${specifier.text}.`
302013
+ });
302117
302014
  }
302118
- const init = declaration.declarations[0].init;
302119
- if (init === null || init === void 0) {
302120
- diagnostics.push(
302121
- diagnosticAt(path, statement2, "The config needs a value", { stage: WORKFLOW_STAGE })
302122
- );
302123
- continue;
302015
+ };
302016
+ const visit = (node) => {
302017
+ if (import_typescript6.default.isImportDeclaration(node) || import_typescript6.default.isExportDeclaration(node)) {
302018
+ checkModuleSpecifier(node, node.moduleSpecifier);
302124
302019
  }
302125
- configNode = init;
302126
- }
302127
- if (configCount === 0) {
302128
- diagnostics.push(
302129
- diagnosticAt(
302130
- path,
302131
- null,
302132
- "The workflow has no config. Add `export const config = { title, trigger }`",
302133
- { stage: WORKFLOW_STAGE }
302134
- )
302135
- );
302136
- }
302137
- if (!hasDefault) {
302138
- diagnostics.push(
302139
- diagnosticAt(
302140
- path,
302141
- null,
302142
- "The workflow has no default export. Add `export default defineWorkflow(...)`",
302143
- { stage: WORKFLOW_STAGE }
302144
- )
302145
- );
302146
- }
302147
- let scriptSource = source;
302148
- for (const node of ranges.toSorted((left, right) => right.start - left.start)) {
302149
- scriptSource = scriptSource.slice(0, node.start) + blank(scriptSource.slice(node.start, node.end)) + scriptSource.slice(node.end);
302150
- }
302151
- return { configNode, scriptSource, diagnostics };
302152
- }
302153
- function readWorkflowConfig(path, configNode, context) {
302154
- const diagnostics = [];
302155
- const report = (node, message) => diagnostics.push(diagnosticAt(path, node, message, { stage: WORKFLOW_STAGE }));
302156
- let value;
302157
- try {
302158
- value = staticValue(configNode, { resources: context.resourcesBinding });
302159
- } catch (error) {
302160
- if (!(error instanceof SourceError)) {
302161
- throw error;
302020
+ if (import_typescript6.default.isImportEqualsDeclaration(node) && import_typescript6.default.isExternalModuleReference(node.moduleReference)) {
302021
+ checkModuleSpecifier(node, node.moduleReference.expression);
302162
302022
  }
302163
- report(error.node, error.message);
302164
- return { config: null, diagnostics };
302165
- }
302166
- if (!isPlainObject(value)) {
302167
- report(configNode, "The config must be an object literal");
302168
- return { config: null, diagnostics };
302169
- }
302170
- const nodes = propertyNodes(configNode);
302171
- const at = (key) => nodes.get(key) ?? configNode;
302172
- for (const key of Object.keys(value)) {
302173
- if (!CONFIG_KEYS.has(key)) {
302174
- report(at(key), `Unknown workflow config option "${key}"`);
302023
+ if (import_typescript6.default.isCallExpression(node) && node.expression.kind === import_typescript6.default.SyntaxKind.ImportKeyword) {
302024
+ findings.push({ node, code: "allowed-imports", message: "Dynamic import is not supported." });
302025
+ }
302026
+ if (import_typescript6.default.isCallExpression(node) && node.expression.kind !== import_typescript6.default.SyntaxKind.ImportKeyword) {
302027
+ checkMailTemplateCall(node);
302028
+ }
302029
+ if (import_typescript6.default.isExpressionStatement(node)) {
302030
+ for (const call of floatingPromiseCalls(node.expression, holdsPromise)) {
302031
+ findings.push({ node: call, code: "no-floating-capability", message: FLOATING_MESSAGE });
302032
+ }
302033
+ }
302034
+ if ((import_typescript6.default.isArrowFunction(node) || import_typescript6.default.isFunctionExpression(node)) && import_typescript6.default.isCallExpression(node.parent) && node.parent.arguments.includes(node) && returnsPromise(node, checker) && contextuallyReturnsVoid(node, checker)) {
302035
+ findings.push({ node, code: "no-floating-capability", message: FLOATING_MESSAGE });
302036
+ }
302037
+ if (import_typescript6.default.isIdentifier(node) && Object.hasOwn(UNSUPPORTED_GLOBALS, node.text)) {
302038
+ const isGlobalThisMember = import_typescript6.default.isPropertyAccessExpression(node.parent) && node.parent.name === node && import_typescript6.default.isIdentifier(node.parent.expression) && node.parent.expression.text === "globalThis";
302039
+ const symbol = import_typescript6.default.isShorthandPropertyAssignment(node.parent) ? checker.getShorthandAssignmentValueSymbol(node.parent) : checker.getSymbolAtLocation(node);
302040
+ const isGlobalReference = !isMemberName(node) && !isDeclaredInScript(symbol);
302041
+ if (isGlobalThisMember || isGlobalReference) {
302042
+ findings.push({
302043
+ node,
302044
+ code: "no-unsupported-global",
302045
+ message: UNSUPPORTED_GLOBALS[node.text]
302046
+ });
302047
+ }
302048
+ }
302049
+ if (import_typescript6.default.isExportAssignment(node) && !node.isExportEquals) {
302050
+ defaultExport = node.expression;
302175
302051
  }
302052
+ import_typescript6.default.forEachChild(node, visit);
302053
+ };
302054
+ for (const directive2 of file2.libReferenceDirectives) {
302055
+ findings.push({
302056
+ node: file2,
302057
+ position: directive2.pos,
302058
+ code: "no-lib-reference",
302059
+ message: "Remove this lib reference. Workflow scripts run on ES2023 in the sandbox."
302060
+ });
302176
302061
  }
302177
- const title = value.title;
302178
- if (typeof title !== "string" || title.trim() === "") {
302179
- report(at("title"), '"title" is required and must be a non-empty string');
302062
+ visit(file2);
302063
+ if (!isSdkDefineWorkflowCall(defaultExport, checker)) {
302064
+ findings.push({
302065
+ node: defaultExport ?? file2,
302066
+ code: "default-workflow-export",
302067
+ message: "Export the workflow as `export default defineWorkflow(async (input, ctx) => { ... })`."
302068
+ });
302180
302069
  }
302181
- const description = value.description ?? null;
302182
- if (description !== null && typeof description !== "string") {
302183
- report(at("description"), '"description" must be a string');
302070
+ return findings;
302071
+ }
302072
+ function isSdkDefineWorkflowCall(expression2, checker) {
302073
+ if (expression2 === null || !import_typescript6.default.isCallExpression(expression2) || !import_typescript6.default.isIdentifier(expression2.expression)) {
302074
+ return false;
302184
302075
  }
302185
- const scoped = { ...context, path };
302186
- const trigger = readTrigger(value.trigger, at("trigger"), scoped, report);
302187
- const runAs = trigger === null ? null : readRunAs(value.runAs, at("runAs"), trigger, scoped, report);
302188
- const authorizer = readAuthorizer(value.authorizer, at("authorizer"), trigger, report);
302189
- if (diagnostics.length > 0 || trigger === null) {
302190
- return { config: null, diagnostics };
302076
+ let symbol = checker.getSymbolAtLocation(expression2.expression);
302077
+ if (symbol && symbol.flags & import_typescript6.default.SymbolFlags.Alias) {
302078
+ symbol = checker.getAliasedSymbol(symbol);
302079
+ }
302080
+ return symbol?.getName() === "defineWorkflow" && (symbol.declarations?.some(
302081
+ (declaration) => declaration.getSourceFile().fileName.startsWith("/sdk/")
302082
+ ) ?? false);
302083
+ }
302084
+
302085
+ // scripts/lib/workflow-script/compile.mjs
302086
+ var SCRIPT = "/workflow.ts";
302087
+ var INPUT_VALIDATOR_CHECK = "/input-validator.check.ts";
302088
+ var INPUT_VALIDATOR_CHECK_SOURCE = `import type { InputValidator, WorkflowDefinition } from '@diagonal/workflow';
302089
+ import * as script from './workflow';
302090
+
302091
+ type Input = typeof script.default extends WorkflowDefinition<infer I, unknown> ? I : never;
302092
+ type Exported = typeof script extends { validateInput: infer V } ? V : undefined;
302093
+
302094
+ declare const validateInput: Exported;
302095
+ export const check: InputValidator<Input> | undefined = validateInput;
302096
+ `;
302097
+ var WORKSPACE = "/sdk/workspace.generated.ts";
302098
+ var APP_ROOT = "/app";
302099
+ var LIB_DIR = "/lib";
302100
+ var OPTIONS = {
302101
+ target: import_typescript7.default.ScriptTarget.ES2023,
302102
+ lib: [ROOT_LIB],
302103
+ module: import_typescript7.default.ModuleKind.CommonJS,
302104
+ moduleResolution: import_typescript7.default.ModuleResolutionKind.Bundler,
302105
+ strict: true,
302106
+ types: [],
302107
+ paths: {
302108
+ "@diagonal/workflow": ["/sdk/index.ts"],
302109
+ "@diagonal/workflow/workspace": [WORKSPACE],
302110
+ ...Object.fromEntries(
302111
+ Object.values(PROFILES).filter(({ specifier }) => specifier !== null).map(({ specifier, entry }) => [specifier, [entry]])
302112
+ )
302191
302113
  }
302192
- return {
302193
- config: {
302194
- title,
302195
- description,
302196
- type: trigger.definition.type,
302197
- settings: trigger.settings,
302198
- run_as: runAs,
302199
- authorizer,
302200
- execution_mode: trigger.definition.sync ? "sync" : "async"
302201
- },
302202
- diagnostics
302203
- };
302114
+ };
302115
+ var libFiles2;
302116
+ try {
302117
+ const { LIB_FILES: LIB_FILES2 } = await Promise.resolve().then(() => (init_sdk_files_generated(), sdk_files_generated_exports));
302118
+ libFiles2 = libClosure((name) => LIB_FILES2[name]);
302119
+ } catch {
302120
+ libFiles2 = readLibClosure();
302204
302121
  }
302205
- function resolveResource(reference, node, context, report) {
302206
- if (typeof reference !== "string" || reference === "") {
302207
- report(node, '"resource" must be Resources.<Name>.slug');
302208
- return null;
302209
- }
302210
- const resource = context.findResource(reference);
302211
- if (resource === void 0) {
302212
- if (context.reportUnknownResources) {
302213
- report(node, referenceProblem(reference, context.resources, context.names).message);
302214
- }
302215
- return null;
302122
+ var libSourceFiles = /* @__PURE__ */ new Map();
302123
+ var readLibFile = (name) => Object.hasOwn(libFiles2, name) ? libFiles2[name] : void 0;
302124
+ function libSourceFile(name, languageVersion) {
302125
+ if (!libSourceFiles.has(name)) {
302126
+ const text = readLibFile(name);
302127
+ libSourceFiles.set(
302128
+ name,
302129
+ text === void 0 ? void 0 : import_typescript7.default.createSourceFile(`${LIB_DIR}/${name}`, text, languageVersion)
302130
+ );
302216
302131
  }
302217
- return resource;
302132
+ return libSourceFiles.get(name);
302218
302133
  }
302219
- function oneOf(trigger, key, allowed, at, report) {
302220
- const item = trigger[key];
302221
- if (!allowed.includes(item)) {
302222
- report(at(key), `"${key}" must be one of: ${listOf(allowed)}`);
302223
- return null;
302134
+ var libName = (path) => path.startsWith(`${LIB_DIR}/`) ? path.slice(LIB_DIR.length + 1) : null;
302135
+ function position(file2, start) {
302136
+ if (file2 === void 0 || start === void 0) {
302137
+ return { line: 1, column: 1 };
302224
302138
  }
302225
- return item;
302139
+ const { line, character } = file2.getLineAndCharacterOfPosition(start);
302140
+ return { line: line + 1, column: character + 1 };
302226
302141
  }
302227
- function readTrigger(trigger, triggerNode, context, report) {
302228
- if (!isPlainObject(trigger)) {
302229
- report(triggerNode, `"trigger" is required: { type: ${listOf(Object.keys(TRIGGERS))}, ... }`);
302230
- return null;
302142
+ function inputValidatorPosition(file2) {
302143
+ for (const statement2 of file2.statements) {
302144
+ if (import_typescript7.default.isFunctionDeclaration(statement2) && statement2.name?.text === "validateInput") {
302145
+ return statement2.name.getStart(file2);
302146
+ }
302147
+ if (import_typescript7.default.isVariableStatement(statement2)) {
302148
+ for (const declaration of statement2.declarationList.declarations) {
302149
+ if (import_typescript7.default.isIdentifier(declaration.name) && declaration.name.text === "validateInput") {
302150
+ return declaration.name.getStart(file2);
302151
+ }
302152
+ }
302153
+ }
302231
302154
  }
302232
- const nodes = propertyNodes(triggerNode.value ?? triggerNode);
302233
- const at = (key) => nodes.get(key) ?? triggerNode;
302234
- const definition = Object.hasOwn(TRIGGERS, trigger.type) ? TRIGGERS[trigger.type] : void 0;
302235
- if (definition === void 0) {
302236
- report(at("type"), `"trigger.type" must be one of: ${listOf(Object.keys(TRIGGERS))}`);
302155
+ return void 0;
302156
+ }
302157
+ function workspaceResourceNames(file2, program3, workspaceDeclarations) {
302158
+ const checker = program3.getTypeChecker();
302159
+ const imports = /* @__PURE__ */ new Set();
302160
+ const namespaces2 = /* @__PURE__ */ new Set();
302161
+ const names2 = /* @__PURE__ */ new Set();
302162
+ const ids = /* @__PURE__ */ new Map();
302163
+ let needsAll = false;
302164
+ const key = (node) => node && (import_typescript7.default.isIdentifier(node) || import_typescript7.default.isStringLiteral(node) || import_typescript7.default.isNoSubstitutionTemplateLiteral(node)) ? node.text : null;
302165
+ const unparenthesized = (node) => {
302166
+ while (node && import_typescript7.default.isParenthesizedExpression(node)) {
302167
+ node = node.expression;
302168
+ }
302169
+ return node;
302170
+ };
302171
+ const symbol = (node) => {
302172
+ if (import_typescript7.default.isShorthandPropertyAssignment(node.parent)) {
302173
+ return checker.getShorthandAssignmentValueSymbol(node.parent);
302174
+ }
302175
+ if (import_typescript7.default.isExportSpecifier(node.parent) && !node.parent.parent.parent.moduleSpecifier) {
302176
+ return checker.getExportSpecifierLocalTargetSymbol(node.parent);
302177
+ }
302178
+ return checker.getSymbolAtLocation(node);
302179
+ };
302180
+ const isNamespace = (node) => node && import_typescript7.default.isIdentifier(node) && namespaces2.has(symbol(node));
302181
+ const member = (node) => {
302182
+ if (import_typescript7.default.isPropertyAccessExpression(node)) {
302183
+ return node.name.text;
302184
+ }
302185
+ if (import_typescript7.default.isElementAccessExpression(node)) {
302186
+ const argument = unparenthesized(node.argumentExpression);
302187
+ return argument && (import_typescript7.default.isStringLiteral(argument) || import_typescript7.default.isNoSubstitutionTemplateLiteral(argument)) ? argument.text : null;
302188
+ }
302237
302189
  return null;
302238
- }
302239
- let failed = false;
302240
- const fail = (node, message) => {
302241
- failed = true;
302242
- report(node, message);
302243
302190
  };
302244
- for (const key of Object.keys(trigger)) {
302245
- if (!definition.keys.includes(key)) {
302246
- fail(at(key), `A ${trigger.type} trigger has no option "${key}"`);
302191
+ const isMap3 = (node) => import_typescript7.default.isIdentifier(node) && imports.has(symbol(node)) || (import_typescript7.default.isPropertyAccessExpression(node) || import_typescript7.default.isElementAccessExpression(node)) && isNamespace(unparenthesized(node.expression)) && member(node) === "resources";
302192
+ for (const statement2 of file2.statements) {
302193
+ if (import_typescript7.default.isExportDeclaration(statement2) && !statement2.isTypeOnly && statement2.moduleSpecifier && import_typescript7.default.isStringLiteral(statement2.moduleSpecifier) && statement2.moduleSpecifier.text === "@diagonal/workflow/workspace" && (!statement2.exportClause || import_typescript7.default.isNamespaceExport(statement2.exportClause) || statement2.exportClause.elements.some(
302194
+ (element) => !element.isTypeOnly && (element.propertyName ?? element.name).text === "resources"
302195
+ ))) {
302196
+ return null;
302247
302197
  }
302248
- }
302249
- const settings = triggerSettings(trigger, at, context, fail);
302250
- return failed || settings === null ? null : { definition, name: trigger.type, settings };
302251
- }
302252
- function triggerSettings(trigger, at, context, fail) {
302253
- switch (trigger.type) {
302254
- case "request": {
302255
- const path = trigger.path;
302256
- if (typeof path !== "string" || !ROUTE_PATTERN.test(path) || path.length > 255) {
302257
- fail(
302258
- at("path"),
302259
- '"path" must start with "/" and contain only a-z, 0-9, -, _, /, and {param}'
302260
- );
302261
- return null;
302262
- }
302263
- const method = trigger.method === void 0 ? "GET" : oneOf(trigger, "method", HTTP_METHODS, at, fail);
302264
- if (method === null) {
302265
- return null;
302198
+ if (import_typescript7.default.isImportEqualsDeclaration(statement2)) {
302199
+ const reference = statement2.moduleReference;
302200
+ if (!statement2.isTypeOnly && import_typescript7.default.isExternalModuleReference(reference) && reference.expression && import_typescript7.default.isStringLiteral(reference.expression) && reference.expression.text === "@diagonal/workflow/workspace") {
302201
+ namespaces2.add(checker.getSymbolAtLocation(statement2.name));
302266
302202
  }
302267
- const params = [...path.matchAll(ROUTE_PARAM_PATTERN)].map((match) => ({
302268
- key: match[1],
302269
- scope: null,
302270
- relations: [],
302271
- resource_id: null,
302272
- lookup_field: null
302273
- }));
302274
- return { route: path, method, params };
302203
+ continue;
302275
302204
  }
302276
- case "recordEvent": {
302277
- const resource = resolveResource(trigger.resource, at("resource"), context, fail);
302278
- const event = oneOf(trigger, "event", RECORD_EVENTS, at, fail);
302279
- if (trigger.filters !== void 0 && trigger.filters !== null && typeof trigger.filters !== "object") {
302280
- fail(at("filters"), '"filters" must be a filter object');
302281
- }
302282
- if (resource === null || event === null) {
302283
- return null;
302284
- }
302285
- return trigger.filters === void 0 ? { event, resource: resource.slug } : { event, resource: resource.slug, filters: trigger.filters };
302205
+ if (!import_typescript7.default.isImportDeclaration(statement2) || statement2.moduleSpecifier.text !== "@diagonal/workflow/workspace" || statement2.importClause?.isTypeOnly) {
302206
+ continue;
302286
302207
  }
302287
- case "recordLifecycle": {
302288
- const resource = resolveResource(trigger.resource, at("resource"), context, fail);
302289
- const hook = oneOf(trigger, "hook", LIFECYCLE_HOOKS, at, fail);
302290
- return resource === null || hook === null ? null : { hook, resource: resource.slug };
302208
+ const bindings = statement2.importClause?.namedBindings;
302209
+ if (bindings && import_typescript7.default.isNamespaceImport(bindings)) {
302210
+ namespaces2.add(checker.getSymbolAtLocation(bindings.name));
302291
302211
  }
302292
- case "recordSchedule": {
302293
- const resource = resolveResource(trigger.resource, at("resource"), context, fail);
302294
- const offsets = readOffsets(trigger.offsets, at("offsets"), fail);
302295
- const dateField = trigger.dateField;
302296
- if (typeof dateField !== "string" || dateField === "") {
302297
- fail(at("dateField"), '"dateField" must be the key of a date or datetime field');
302298
- return null;
302299
- }
302300
- if (resource !== null && resource.platform !== true) {
302301
- const field2 = resource.fields.find((item) => item.key === dateField);
302302
- if (field2 === void 0 || !SCHEDULE_FIELD_TYPES.has(field2.type)) {
302303
- fail(
302304
- at("dateField"),
302305
- `"${dateField}" is not a date or datetime field of resource "${resource.slug}"`
302306
- );
302307
- return null;
302212
+ if (bindings && import_typescript7.default.isNamedImports(bindings)) {
302213
+ for (const binding of bindings.elements) {
302214
+ if (!binding.isTypeOnly && (binding.propertyName ?? binding.name).text === "resources") {
302215
+ imports.add(checker.getSymbolAtLocation(binding.name));
302308
302216
  }
302309
302217
  }
302310
- return resource === null || offsets === null ? null : { schedule: { offsets }, date_field: dateField, resource: resource.slug };
302311
302218
  }
302312
- case "scheduled": {
302313
- const expression2 = trigger.expression;
302314
- const fields = typeof expression2 === "string" ? expression2.trim().split(/\s+/) : [];
302315
- if (fields.length !== 5 || !fields.every((field2) => CRON_FIELD_PATTERN.test(field2))) {
302316
- fail(
302317
- at("expression"),
302318
- '"expression" must be a cron expression with 5 fields, for example "0 2 * * *"'
302319
- );
302320
- return null;
302321
- }
302322
- return { expression: expression2 };
302219
+ }
302220
+ const workspace = program3.getSourceFile(WORKSPACE) ?? import_typescript7.default.createSourceFile(WORKSPACE, workspaceDeclarations, import_typescript7.default.ScriptTarget.ES2023, true);
302221
+ for (const statement2 of workspace.statements) {
302222
+ if (!import_typescript7.default.isVariableStatement(statement2)) {
302223
+ continue;
302323
302224
  }
302324
- case "workflowEvent": {
302325
- const workflow = trigger.workflow;
302326
- const event = oneOf(trigger, "event", WORKFLOW_EVENTS, at, fail);
302327
- if (typeof workflow !== "string" || !WORKFLOW_PATH_PATTERN.test(workflow)) {
302328
- fail(
302329
- at("workflow"),
302330
- '"workflow" must be the path of a workflow, for example "workflows/welcome.ts"'
302331
- );
302332
- return null;
302333
- }
302334
- if (!context.workflowPaths.has(workflow)) {
302335
- fail(at("workflow"), `Unknown workflow "${workflow}". Add the file or change the path`);
302336
- return null;
302225
+ for (const declaration of statement2.declarationList.declarations) {
302226
+ if (!import_typescript7.default.isIdentifier(declaration.name) || declaration.name.text !== "resources") {
302227
+ continue;
302337
302228
  }
302338
- if (workflow === context.path) {
302339
- fail(at("workflow"), "A workflow cannot trigger on its own runs");
302340
- return null;
302229
+ const value = declaration.initializer && unwrap2(declaration.initializer);
302230
+ if (!value || !import_typescript7.default.isObjectLiteralExpression(value)) {
302231
+ continue;
302232
+ }
302233
+ for (const property of value.properties) {
302234
+ if (import_typescript7.default.isPropertyAssignment(property) && import_typescript7.default.isStringLiteral(property.initializer) && key(property.name) !== null) {
302235
+ ids.set(property.initializer.text, key(property.name));
302236
+ }
302341
302237
  }
302342
- return event === null ? null : { event, workflow: { path: workflow } };
302343
- }
302344
- case "manual":
302345
- return {};
302346
- default:
302347
- return null;
302348
- }
302349
- }
302350
- function readOffsets(offsets, node, fail) {
302351
- if (!Array.isArray(offsets) || offsets.length === 0) {
302352
- fail(node, `"offsets" must be a list of signed ISO 8601 durations, for example ['-P1D']`);
302353
- return null;
302354
- }
302355
- for (const offset of offsets) {
302356
- if (typeof offset !== "string" || !OFFSET_PATTERN.test(offset) || !/\d+[DHM]/i.test(offset)) {
302357
- fail(
302358
- node,
302359
- `Offset ${JSON.stringify(offset)} must be a signed ISO 8601 duration in days, hours, or minutes, for example '-P1D' or '+PT2H'`
302360
- );
302361
- return null;
302362
302238
  }
302363
302239
  }
302364
- if (new Set(offsets).size !== offsets.length) {
302365
- fail(node, "The offsets must be distinct");
302366
- return null;
302367
- }
302368
- return offsets;
302369
- }
302370
- function readRunAs(runAs, node, trigger, context, report) {
302371
- const name = trigger.name;
302372
- if (runAs === void 0 || runAs === null) {
302373
- if (name === "request") {
302374
- return { mode: "session" };
302240
+ const visit = (node) => {
302241
+ if (needsAll || import_typescript7.default.isImportDeclaration(node) || import_typescript7.default.isImportEqualsDeclaration(node) && import_typescript7.default.isExternalModuleReference(node.moduleReference) || import_typescript7.default.isTypeNode(node)) {
302242
+ return;
302375
302243
  }
302376
- if (trigger.definition.background) {
302377
- report(
302378
- node,
302379
- `A ${name} workflow runs in the background and needs an identity. Set runAs to 'system' or { resource, record }`
302380
- );
302244
+ if ((import_typescript7.default.isStringLiteral(node) || import_typescript7.default.isNoSubstitutionTemplateLiteral(node)) && ids.has(node.text)) {
302245
+ names2.add(ids.get(node.text));
302381
302246
  }
302382
- return null;
302383
- }
302384
- if (name === "recordLifecycle") {
302385
- report(node, "A recordLifecycle workflow runs inside the record write. Remove runAs");
302386
- return null;
302387
- }
302388
- if (runAs === "system") {
302389
- return { mode: "system" };
302390
- }
302391
- if (runAs === "session") {
302392
- if (name !== "request") {
302393
- report(
302394
- node,
302395
- "runAs 'session' is only for request workflows. Use 'system' or { resource, record }"
302396
- );
302247
+ let use = node;
302248
+ while (import_typescript7.default.isParenthesizedExpression(use.parent)) {
302249
+ use = use.parent;
302250
+ }
302251
+ if (isMap3(node)) {
302252
+ const parent = use.parent;
302253
+ const name = (import_typescript7.default.isPropertyAccessExpression(parent) || import_typescript7.default.isElementAccessExpression(parent)) && parent.expression === use ? member(parent) : null;
302254
+ if (name === null) {
302255
+ needsAll = true;
302256
+ } else {
302257
+ names2.add(name);
302258
+ }
302259
+ } else if (isNamespace(node) && !isMap3(use.parent)) {
302260
+ needsAll = true;
302261
+ }
302262
+ if (!needsAll) {
302263
+ import_typescript7.default.forEachChild(node, visit);
302264
+ }
302265
+ };
302266
+ import_typescript7.default.forEachChild(file2, visit);
302267
+ return needsAll ? null : [...names2].toSorted((left, right) => left.localeCompare(right));
302268
+ }
302269
+ function scriptResourceNames(file2, program3, workspaceDeclarations, appModules = {}) {
302270
+ const names2 = /* @__PURE__ */ new Set();
302271
+ for (const source of [
302272
+ file2,
302273
+ ...Object.keys(appModules).map((path) => program3.getSourceFile(`${APP_ROOT}/${path}`))
302274
+ ]) {
302275
+ if (source === void 0) {
302397
302276
  return null;
302398
302277
  }
302399
- return { mode: "session" };
302400
- }
302401
- if (!isPlainObject(runAs)) {
302402
- report(node, "runAs must be 'system', 'session', or { resource, record }");
302403
- return null;
302404
- }
302405
- for (const key of Object.keys(runAs)) {
302406
- if (key !== "resource" && key !== "record") {
302407
- report(node, `runAs has no option "${key}". Use { resource, record }`);
302278
+ const used = workspaceResourceNames(source, program3, workspaceDeclarations);
302279
+ if (used === null) {
302408
302280
  return null;
302409
302281
  }
302282
+ for (const name of used) {
302283
+ names2.add(name);
302284
+ }
302410
302285
  }
302411
- const resource = resolveResource(runAs.resource, node, context, report);
302412
- if (typeof runAs.record !== "string" || !UUID_PATTERN2.test(runAs.record)) {
302413
- report(node, '"runAs.record" must be the lowercase UUID of a record');
302414
- return null;
302415
- }
302416
- return resource === null ? null : { mode: "fixed", resource: resource.slug, record_id: runAs.record };
302286
+ return [...names2].toSorted((left, right) => left.localeCompare(right));
302417
302287
  }
302418
- function readAuthorizer(authorizer, node, trigger, report) {
302419
- if (authorizer === void 0 || authorizer === null) {
302420
- return null;
302288
+ function createScriptProgram({
302289
+ source,
302290
+ sdkFiles: sdkFiles2,
302291
+ workspaceDeclarations,
302292
+ appModules = {},
302293
+ profile
302294
+ }) {
302295
+ const entry = PROFILES[resolveProfile(profile)].entry;
302296
+ const files = new Map(
302297
+ Object.entries({
302298
+ ...sdkFiles2,
302299
+ [WORKSPACE]: workspaceDeclarations,
302300
+ [SCRIPT]: source,
302301
+ [INPUT_VALIDATOR_CHECK]: INPUT_VALIDATOR_CHECK_SOURCE,
302302
+ ...Object.fromEntries(
302303
+ Object.entries(appModules).map(([path, moduleSource]) => [
302304
+ `${APP_ROOT}/${path}`,
302305
+ moduleSource
302306
+ ])
302307
+ )
302308
+ })
302309
+ );
302310
+ const host = {
302311
+ getSourceFile: (name, languageVersion) => {
302312
+ const lib = libName(name);
302313
+ if (lib !== null) {
302314
+ return libSourceFile(lib, languageVersion);
302315
+ }
302316
+ return files.has(name) ? import_typescript7.default.createSourceFile(name, files.get(name), languageVersion, true) : void 0;
302317
+ },
302318
+ getDefaultLibFileName: () => `${LIB_DIR}/${ROOT_LIB}`,
302319
+ getDefaultLibLocation: () => LIB_DIR,
302320
+ writeFile: () => {
302321
+ },
302322
+ getCurrentDirectory: () => "/",
302323
+ getCanonicalFileName: (name) => name,
302324
+ useCaseSensitiveFileNames: () => true,
302325
+ getNewLine: () => "\n",
302326
+ fileExists: (name) => files.has(name) || libName(name) !== null && readLibFile(libName(name)) !== void 0,
302327
+ readFile: (name) => files.get(name) ?? (libName(name) !== null ? readLibFile(libName(name)) : void 0),
302328
+ directoryExists: (name) => {
302329
+ const prefix2 = name.endsWith("/") ? name : `${name}/`;
302330
+ return prefix2 === `${LIB_DIR}/` || [...files.keys()].some((path) => path.startsWith(prefix2));
302331
+ },
302332
+ getDirectories: () => []
302333
+ };
302334
+ const program3 = import_typescript7.default.createProgram({
302335
+ rootNames: [SCRIPT, INPUT_VALIDATOR_CHECK, WORKSPACE, ...entry === null ? [] : [entry]],
302336
+ options: Object.keys(appModules).length === 0 ? OPTIONS : { ...OPTIONS, paths: { ...OPTIONS.paths, "@app/*": [`${APP_ROOT}/*`] } },
302337
+ host
302338
+ });
302339
+ return { program: program3, file: program3.getSourceFile(SCRIPT) };
302340
+ }
302341
+ function servedProfileImports(context) {
302342
+ const { factory } = context;
302343
+ const served = (specifier) => import_typescript7.default.isStringLiteral(specifier) && PROFILE_SPECIFIERS.has(specifier.text) ? factory.createStringLiteral("@diagonal/workflow") : specifier;
302344
+ return (sourceFile) => factory.updateSourceFile(
302345
+ sourceFile,
302346
+ sourceFile.statements.map((statement2) => {
302347
+ if (import_typescript7.default.isImportDeclaration(statement2)) {
302348
+ return factory.updateImportDeclaration(
302349
+ statement2,
302350
+ statement2.modifiers,
302351
+ statement2.importClause,
302352
+ served(statement2.moduleSpecifier),
302353
+ statement2.attributes
302354
+ );
302355
+ }
302356
+ if (import_typescript7.default.isImportEqualsDeclaration(statement2) && import_typescript7.default.isExternalModuleReference(statement2.moduleReference)) {
302357
+ return factory.updateImportEqualsDeclaration(
302358
+ statement2,
302359
+ statement2.modifiers,
302360
+ statement2.isTypeOnly,
302361
+ statement2.name,
302362
+ factory.updateExternalModuleReference(
302363
+ statement2.moduleReference,
302364
+ served(statement2.moduleReference.expression)
302365
+ )
302366
+ );
302367
+ }
302368
+ if (import_typescript7.default.isExportDeclaration(statement2) && statement2.moduleSpecifier) {
302369
+ return factory.updateExportDeclaration(
302370
+ statement2,
302371
+ statement2.modifiers,
302372
+ statement2.isTypeOnly,
302373
+ statement2.exportClause,
302374
+ served(statement2.moduleSpecifier),
302375
+ statement2.attributes
302376
+ );
302377
+ }
302378
+ return statement2;
302379
+ })
302380
+ );
302381
+ }
302382
+ function compileWorkflowScript(request2, scriptProgram = createScriptProgram(request2)) {
302383
+ let code2 = null;
302384
+ const { program: program3, file: file2 } = scriptProgram;
302385
+ const diagnostics = [];
302386
+ for (const diagnostic2 of import_typescript7.default.getPreEmitDiagnostics(program3, file2)) {
302387
+ diagnostics.push({
302388
+ severity: "error",
302389
+ code: `TS${diagnostic2.code}`,
302390
+ message: import_typescript7.default.flattenDiagnosticMessageText(diagnostic2.messageText, "\n"),
302391
+ ...position(diagnostic2.file, diagnostic2.start)
302392
+ });
302421
302393
  }
302422
- if (authorizer !== "authenticated") {
302423
- report(node, "authorizer must be 'authenticated'");
302424
- return null;
302394
+ for (const diagnostic2 of program3.getSemanticDiagnostics(
302395
+ program3.getSourceFile(INPUT_VALIDATOR_CHECK)
302396
+ )) {
302397
+ diagnostics.push({
302398
+ severity: "error",
302399
+ code: `TS${diagnostic2.code}`,
302400
+ message: `validateInput must be (input, ctx) => InputErrors<Input> | void for this workflow's input. ${import_typescript7.default.flattenDiagnosticMessageText(diagnostic2.messageText, "\n")}`,
302401
+ ...position(file2, inputValidatorPosition(file2))
302402
+ });
302425
302403
  }
302426
- if (trigger !== null && trigger.name !== "request") {
302427
- report(node, "Only a request workflow can have an authorizer");
302428
- return null;
302404
+ const inputSchema = extractInputSchema(file2, program3.getTypeChecker());
302405
+ const allowAppImports = Object.keys(request2.appModules ?? {}).length > 0;
302406
+ const profile = resolveProfile(request2.profile);
302407
+ for (const finding of [
302408
+ ...lint2(file2, program3.getTypeChecker(), { allowAppImports, profile }),
302409
+ ...profileFindings(file2, program3.getTypeChecker(), program3, profile),
302410
+ ...inputSchema.findings
302411
+ ]) {
302412
+ diagnostics.push({
302413
+ severity: "error",
302414
+ code: finding.code,
302415
+ message: finding.message,
302416
+ ...position(file2, finding.position ?? finding.node.getStart(file2))
302417
+ });
302429
302418
  }
302430
- return { requires_authentication: true };
302419
+ if (diagnostics.length === 0) {
302420
+ program3.emit(
302421
+ file2,
302422
+ (name, text) => {
302423
+ if (name === "/workflow.js") {
302424
+ code2 = text;
302425
+ }
302426
+ },
302427
+ void 0,
302428
+ false,
302429
+ { before: [servedProfileImports] }
302430
+ );
302431
+ }
302432
+ return {
302433
+ ok: diagnostics.length === 0 && code2 !== null,
302434
+ code: diagnostics.length === 0 ? code2 : null,
302435
+ input: diagnostics.length === 0 ? inputSchema.schema : null,
302436
+ resources: diagnostics.length === 0 ? scriptResourceNames(file2, program3, request2.workspaceDeclarations, request2.appModules) : null,
302437
+ diagnostics: diagnostics.toSorted((a, b2) => a.line - b2.line || a.column - b2.column)
302438
+ };
302431
302439
  }
302432
302440
 
302433
302441
  // scripts/lib/runtime-build/workspace-script-types.mjs
@@ -302610,6 +302618,7 @@ function reportDuplicateTriggers(workflows, diagnostics) {
302610
302618
  }
302611
302619
  function buildWorkflows({
302612
302620
  workflows,
302621
+ uidsByPath = /* @__PURE__ */ new Map(),
302613
302622
  tests,
302614
302623
  resources,
302615
302624
  platformResources = [],
@@ -302670,6 +302679,7 @@ function buildWorkflows({
302670
302679
  const config = read.config;
302671
302680
  return {
302672
302681
  path,
302682
+ uid: uidsByPath.get(path) ?? null,
302673
302683
  title: config?.title ?? null,
302674
302684
  description: config?.description ?? null,
302675
302685
  type: config?.type ?? null,
@@ -302811,6 +302821,12 @@ function classify(path) {
302811
302821
  return "ignored";
302812
302822
  }
302813
302823
  }
302824
+ function rereadWorkflowFiles(root, workflowFiles) {
302825
+ return workflowFiles.map((file2) => {
302826
+ const source = readFileSync8(join11(root, file2.path), "utf8");
302827
+ return source === file2.source ? file2 : { path: file2.path, source, ast: parseSource(source, { jsx: false }) };
302828
+ });
302829
+ }
302814
302830
  function reportDuplicates(items, keyOf, label, diagnostics, nodeOf = () => null) {
302815
302831
  const seen = /* @__PURE__ */ new Map();
302816
302832
  for (const item of items) {
@@ -302946,6 +302962,15 @@ function uidDefinitionNodes(kind, ast) {
302946
302962
  const platform = node.type === "ObjectExpression" && node.properties.some((property) => property.type === "ObjectProperty" && propertyKey(property) === "platform");
302947
302963
  return platform ? [] : [{ type: "resource", node }];
302948
302964
  }
302965
+ case "page": {
302966
+ const { declaration } = defaultExportOf(ast, { helpers: "anywhere", allowAppImports: true });
302967
+ const [node] = expectDefineCall(declaration, "definePage", 2);
302968
+ return [{ type: "page", node }];
302969
+ }
302970
+ case "workflow": {
302971
+ const node = workflowConfigObject(ast);
302972
+ return node === null ? [] : [{ type: "workflow", node }];
302973
+ }
302949
302974
  default:
302950
302975
  return [];
302951
302976
  }
@@ -303044,6 +303069,9 @@ function buildWorkspace(root, { assetCatalog = null, writeSource = false } = {})
303044
303069
  case "page": {
303045
303070
  const page = buildPage(path, source, ast, root, resourcesBinding(ast, names2));
303046
303071
  output.pages.push(page);
303072
+ for (const { type, node } of uidDefinitionNodes(kind, ast)) {
303073
+ uidPositions.set(path, uidDefinitions.push({ type, path, source, node }) - 1);
303074
+ }
303047
303075
  diagnostics.push(...slugStringWarnings(path, page.resourceNodes.meta, names2));
303048
303076
  uiEntries.push({ path, source, ast });
303049
303077
  break;
@@ -303058,6 +303086,9 @@ function buildWorkspace(root, { assetCatalog = null, writeSource = false } = {})
303058
303086
  break;
303059
303087
  case "workflow":
303060
303088
  workflowFiles.push({ path, source, ast });
303089
+ for (const { type, node } of uidDefinitionNodes(kind, ast)) {
303090
+ uidPositions.set(path, uidDefinitions.push({ type, path, source, node }) - 1);
303091
+ }
303061
303092
  break;
303062
303093
  case "workflow_test":
303063
303094
  workflowTestFiles.push({ path, source, ast });
@@ -303104,6 +303135,9 @@ function buildWorkspace(root, { assetCatalog = null, writeSource = false } = {})
303104
303135
  for (const resource of output.resources) {
303105
303136
  resource.uid = uidCheck.uids[uidPositions.get(resource.path)];
303106
303137
  }
303138
+ for (const page of output.pages) {
303139
+ page.uid = uidCheck.uids[uidPositions.get(page.path)];
303140
+ }
303107
303141
  if (output.config === null && !diagnostics.some((diagnostic2) => diagnostic2.path === CONFIG_PATH)) {
303108
303142
  diagnostics.push(diagnosticAt(CONFIG_PATH, null, "The workspace has no diagonal.config.ts"));
303109
303143
  }
@@ -303138,7 +303172,8 @@ function buildWorkspace(root, { assetCatalog = null, writeSource = false } = {})
303138
303172
  entries
303139
303173
  );
303140
303174
  const workflowBuild = buildWorkflows({
303141
- workflows: workflowFiles,
303175
+ workflows: rereadWorkflowFiles(root, workflowFiles),
303176
+ uidsByPath: new Map(workflowFiles.map((file2) => [file2.path, uidCheck.uids[uidPositions.get(file2.path)] ?? null])),
303142
303177
  tests: workflowTestFiles,
303143
303178
  resources: output.resources,
303144
303179
  platformResources: output.platform_resources,