@diagonal-hq/cli 0.21.2 → 0.22.0

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/README.md CHANGED
@@ -89,9 +89,9 @@ The build reads each file with a parser. It runs only the workflow and migration
89
89
 
90
90
  ## Definition uids and slugs
91
91
 
92
- A definition can have two identity options. A resource, a field, a relation inverse, a policy, a static record, a permission, a role, a page, a workflow config, a notification type, a notification template, an email layout, a workspace field, and the front matter of a skill file have a `uid`. A resource, a permission, a role, a workflow, a notification type, a notification template, and an email layout also have a `slug`. A workspace field has a `key` in the place of a `slug`.
92
+ A definition can have two identity options. A resource, a field, a relation inverse, a policy, a static record, a permission, a role, a page, a workflow config, a notification type, a notification template, an email layout, a workspace field, the front matter of a skill file, and a layout or component module in `layouts/` or `components/` have a `uid`. A resource, a permission, a role, a workflow, a notification type, a notification template, and an email layout also have a `slug`. A workspace field has a `key` in the place of a `slug`.
93
93
 
94
- - `uid` is the stable identity of the definition. Its value is a lowercase UUID string literal, such as `uid: '019a4d6e-3c2f-7b8a-9d1e-5f6a7b8c9d0e'`. In skill front matter, it is a YAML string, such as `uid: 019a4d6e-3c2f-7b8a-9d1e-5f6a7b8c9d0e`. A file move, a file rename, or a name change keeps the uid. The deploy keeps the stored id of a resource, a field, a page, a workflow, a workspace field, and a skill by its uid, so these changes keep the definition's records, runs, and references. Do not change a uid: a new uid is a new definition.
94
+ - `uid` is the stable identity of the definition. Its value is a lowercase UUID string literal, such as `uid: '019a4d6e-3c2f-7b8a-9d1e-5f6a7b8c9d0e'`. In skill front matter, it is a YAML string, such as `uid: 019a4d6e-3c2f-7b8a-9d1e-5f6a7b8c9d0e`. A layout or component module exports it after its imports, such as `export const uid = '019a4d6e-3c2f-7b8a-9d1e-5f6a7b8c9d0e';`. It identifies the module's shared draft in the platform. A layout or component without a uid still builds. A file move, a file rename, or a name change keeps the uid. The deploy keeps the stored id of a resource, a field, a page, a workflow, a workspace field, and a skill by its uid, so these changes keep the definition's records, runs, and references. Do not change a uid: a new uid is a new definition.
95
95
  - `slug` is the editable, user-facing name of the definition. It is an optional string literal in the `defineX()` call, which is the config of `defineWorkflow(config, handler)` for a workflow. Without it, the path gives the slug: the file name of a resource, a permission, a role, a workflow, or a template, and the folder name of a notification type or an email layout. A `slug` can differ from the path, and a file rename then keeps the slug. A slug change keeps the uid.
96
96
 
97
97
  | Definition | Path | Slug without a `slug` option | Rule of the slug |
@@ -109,7 +109,7 @@ The path also gives the name of the definition in its generated module, such as
109
109
 
110
110
  A setting that names another definition takes the `uid` of its generated entry, for example `NotificationTypes.MemberWelcome.uid`, `NotificationTypes.MemberWelcome.templates.Standard.uid`, `EmailLayouts.Standard.uid`, `Workflows.BookClass.uid`, `Permissions.ManageBookings.uid`, or `Pages.Home.uid`. The uid survives a rename, and the platform finds the definition from it. A notification send, a schedule, `defaultTemplate`, a template layout, a page workflow call, and `ctx.can` also take a slug, as a string or as a `.slug` member. It builds and runs, with a warning that names the `.uid` reference. A workflow path, such as `'workflows/add.ts'`, is an error in every workflow reference: a `workflowEvent` trigger, `workflow.run`, and page code. A resource is the exception: a setting names it with `Resources.<Name>.slug`. A domain and an Application Asset have no uid, so a setting names them with `.key`. A workspace field has a uid, but code reads its value by key, so a setting names it with `WorkspaceFields.<Name>.key`.
111
111
 
112
- `diagonal check` writes a new uid into each definition that has none. It adds `uid: '<uuid>'` as the first option of the `defineX()` object, of each `field.<type>({...})` call, `settings.inverse` object, and policy, or of the config object of `defineWorkflow(config, handler)`, or `uid: <uuid>` as the first line of the front matter of a skill file, and leaves the rest of the file unchanged. Commit the change.
112
+ `diagonal check` writes a new uid into each definition that has none. It adds `uid: '<uuid>'` as the first option of the `defineX()` object, of each `field.<type>({...})` call, `settings.inverse` object, and policy, or of the config object of `defineWorkflow(config, handler)`, `uid: <uuid>` as the first line of the front matter of a skill file, or `export const uid = '<uuid>';` after the imports of a layout or component module, and leaves the rest of the file unchanged. Commit the change.
113
113
 
114
114
  The platform writes the missing uids too: a save in Files, and every other commit that the platform makes, adds a uid to each definition of the changed files that has none. A git push does not, so a pushed definition without a uid fails the deploy, and the error tells you to run `diagonal check`.
115
115
 
package/dist/cli.mjs CHANGED
@@ -291806,7 +291806,13 @@ function isTypeOnlyStatement(statement2) {
291806
291806
  }
291807
291807
  return statement2.declaration?.type === "TSTypeAliasDeclaration" || statement2.declaration?.type === "TSInterfaceDeclaration" || statement2.specifiers.length > 0 && statement2.specifiers.every((specifier) => specifier.exportKind === "type");
291808
291808
  }
291809
- function defaultExportOf(ast, { helpers: helperPlacement = "none", allowAppImports = false, extraImports = [], namedExports = "refuse" } = {}) {
291809
+ function defaultExportOf(ast, {
291810
+ helpers: helperPlacement = "none",
291811
+ allowAppImports = false,
291812
+ extraImports = [],
291813
+ namedExports = "refuse",
291814
+ moduleUid = false
291815
+ } = {}) {
291810
291816
  const imports = [];
291811
291817
  const helpers = [];
291812
291818
  let declaration = null;
@@ -291838,6 +291844,9 @@ function defaultExportOf(ast, { helpers: helperPlacement = "none", allowAppImpor
291838
291844
  declaration = statement2.declaration;
291839
291845
  continue;
291840
291846
  }
291847
+ if (moduleUid && isModuleUidStatement(statement2)) {
291848
+ continue;
291849
+ }
291841
291850
  const isNamedExport = statement2.type === "ExportNamedDeclaration" || statement2.type === "ExportAllDeclaration";
291842
291851
  if (isNamedExport && namedExports === "keep") {
291843
291852
  if (statement2.type === "ExportNamedDeclaration" && statement2.declaration !== null) {
@@ -291865,6 +291874,10 @@ function defaultExportOf(ast, { helpers: helperPlacement = "none", allowAppImpor
291865
291874
  }
291866
291875
  return { declaration, imports, helpers };
291867
291876
  }
291877
+ function isModuleUidStatement(statement2) {
291878
+ const declaration = statement2.type === "ExportNamedDeclaration" ? statement2.declaration : null;
291879
+ return declaration?.type === "VariableDeclaration" && declaration.kind === "const" && declaration.declarations.length === 1 && declaration.declarations[0].id.type === "Identifier" && declaration.declarations[0].id.name === "uid";
291880
+ }
291868
291881
  function calleeName(node) {
291869
291882
  if (node?.type !== "CallExpression" || node.callee.type !== "Identifier") {
291870
291883
  return null;
@@ -305993,7 +306006,48 @@ function readFrontMatterUid(source, { map, offset }) {
305993
306006
  }
305994
306007
  return { uid: value, at };
305995
306008
  }
306009
+ function moduleUidDeclarator(program3) {
306010
+ for (const statement2 of program3.body) {
306011
+ if (statement2.type !== "ExportNamedDeclaration" || statement2.declaration?.type !== "VariableDeclaration") {
306012
+ continue;
306013
+ }
306014
+ const declarator = statement2.declaration.declarations.find(
306015
+ (item) => item.id.type === "Identifier" && item.id.name === "uid"
306016
+ );
306017
+ if (declarator !== void 0) {
306018
+ return { kind: statement2.declaration.kind, declarator };
306019
+ }
306020
+ }
306021
+ return null;
306022
+ }
306023
+ function readModuleUid(program3) {
306024
+ const found2 = moduleUidDeclarator(program3);
306025
+ if (found2 === null) {
306026
+ return { uid: null, at: program3 };
306027
+ }
306028
+ const value = found2.declarator.init;
306029
+ if (found2.kind !== "const" || value?.type !== "StringLiteral" || value.extra.raw.slice(1, -1) !== value.value || !isUid(value.value)) {
306030
+ throw new SourceError(
306031
+ `"uid" must be exported as a lowercase UUID string literal, such as export const uid = '${UID_EXAMPLE}'`,
306032
+ value ?? found2.declarator
306033
+ );
306034
+ }
306035
+ return { uid: value.value, at: value };
306036
+ }
306037
+ function moduleUidInsertion(source, program3, uid2) {
306038
+ const statement2 = `export const uid = '${uid2}';`;
306039
+ const newline = source.includes("\r\n") ? "\r\n" : "\n";
306040
+ const imports = program3.body.filter((item) => item.type === "ImportDeclaration");
306041
+ if (imports.length === 0) {
306042
+ return { start: 0, end: 0, text: `${statement2}${newline}${newline}` };
306043
+ }
306044
+ const end = imports.at(-1).end;
306045
+ return { start: end, end, text: `${newline}${newline}${statement2}` };
306046
+ }
305996
306047
  function readDefinitionUid(definition) {
306048
+ if (definition.program !== void 0) {
306049
+ return readModuleUid(definition.program);
306050
+ }
305997
306051
  if (definition.frontMatter !== void 0) {
305998
306052
  return readFrontMatterUid(definition.source, definition.frontMatter);
305999
306053
  }
@@ -306094,6 +306148,10 @@ function planDefinitionUids(definitions, { write }) {
306094
306148
  uids.push(uid2);
306095
306149
  continue;
306096
306150
  }
306151
+ if (!write && definition.optional === true) {
306152
+ uids.push(null);
306153
+ continue;
306154
+ }
306097
306155
  if (!write) {
306098
306156
  diagnostics.push(
306099
306157
  diagnosticAt(
@@ -306106,7 +306164,14 @@ function planDefinitionUids(definitions, { write }) {
306106
306164
  continue;
306107
306165
  }
306108
306166
  const generated = definition.previousUid ?? newUid();
306109
- const insertion = definition.frontMatter === void 0 ? uidInsertion(definition.source, definition.node, generated) : frontMatterUidInsertion(definition.source, definition.frontMatter, generated);
306167
+ let insertion;
306168
+ if (definition.program !== void 0) {
306169
+ insertion = moduleUidInsertion(definition.source, definition.program, generated);
306170
+ } else if (definition.frontMatter === void 0) {
306171
+ insertion = uidInsertion(definition.source, definition.node, generated);
306172
+ } else {
306173
+ insertion = frontMatterUidInsertion(definition.source, definition.frontMatter, generated);
306174
+ }
306110
306175
  if (insertion === null) {
306111
306176
  diagnostics.push(
306112
306177
  diagnosticAt(
@@ -324307,7 +324372,7 @@ function setupResultType(setupModule) {
324307
324372
  return `(typeof import('${setupModule}').default extends import('@diagonal/workflow').WorkflowDefinition<any, infer O> ? ${output} : never)`;
324308
324373
  }
324309
324374
  function testFunctionHeader(hasSetup) {
324310
- return `type Sdk = Omit<DiagonalTestSdk, 'setup'> & { readonly setup: ${setupResultType(hasSetup ? "./setup" : null)} }; export async function diagonalTest(Sdk: Sdk) {`;
324375
+ return `type Sdk = Omit<DiagonalTestSdk, 'setup'>; export async function diagonalTest(Sdk: Sdk, ctx: ${setupResultType(hasSetup ? "./setup" : null)}) {`;
324311
324376
  }
324312
324377
  function checkTestFunctions({ tests, appModules, resourceNames: resourceNames2, workspaceDeclarations, files }) {
324313
324378
  const resources = resourceNames2.map((name) => ` readonly ${JSON.stringify(name)}: string;
@@ -324432,7 +324497,7 @@ var TEST_KEY_PATTERN = /^[A-Za-z][A-Za-z0-9_-]{0,99}$/;
324432
324497
  var SUITE_PROPERTIES = /* @__PURE__ */ new Set(["uid", "name", "description"]);
324433
324498
  var TEST_PROPERTIES = /* @__PURE__ */ new Set(["name", "description", "enabled", "timeoutSeconds"]);
324434
324499
  var HANDLERS = ["setup", "test", "assert"];
324435
- var TEST_FIXTURES = /* @__PURE__ */ new Set(["page", "context", "request", "browser", "expect", "Sdk"]);
324500
+ var TEST_FIXTURES = /* @__PURE__ */ new Set(["page", "context", "request", "browser", "expect", "Sdk", "ctx"]);
324436
324501
  var PHASE_DEFINE = "__diagonalTestPhase";
324437
324502
  var PHASE_IMPORT = `import { defineWorkflow as ${PHASE_DEFINE} } from '@diagonal-hq/workflows/test'; `;
324438
324503
  var SETUP_TYPE_MODULE = "setup.ts";
@@ -324562,10 +324627,15 @@ function readHandlers(node, report) {
324562
324627
  report(property, `"${key}" cannot be a generator`);
324563
324628
  continue;
324564
324629
  }
324630
+ if (key !== "test" && fn.params.length > 1) {
324631
+ valid = false;
324632
+ report(fn.params[1], `"${key}" takes one argument: async ${key}(ctx) { ... }`);
324633
+ continue;
324634
+ }
324565
324635
  handlers[key] = { node: property, fn, method: property.type === "ObjectMethod" };
324566
324636
  }
324567
324637
  if (valid && handlers.test === void 0) {
324568
- report(node, 'The test has no "test" function. Add async test({ page, expect, Sdk }) { ... }');
324638
+ report(node, 'The test has no "test" function. Add async test({ page, expect, ctx }) { ... }');
324569
324639
  return null;
324570
324640
  }
324571
324641
  return valid ? handlers : null;
@@ -324622,7 +324692,7 @@ function readTestFunction(handler, source, ast, enabled2, report) {
324622
324692
  report(node, message);
324623
324693
  };
324624
324694
  if (fn.params.length > 1) {
324625
- problem2(fn.params[1], "The test function takes one argument: { page, context, request, browser, expect, Sdk }");
324695
+ problem2(fn.params[1], "The test function takes one argument: { page, context, request, browser, expect, Sdk, ctx }");
324626
324696
  }
324627
324697
  const fixtures = fn.params[0];
324628
324698
  if (fixtures !== void 0 && fixtures.type !== "ObjectPattern") {
@@ -324657,7 +324727,7 @@ function readTestFunction(handler, source, ast, enabled2, report) {
324657
324727
  reported.add(reference.name);
324658
324728
  problem2(
324659
324729
  reference,
324660
- `The test function runs in the browser runner and cannot use "${reference.name}" from this file. Return the value from setup and read it as Sdk.setup`
324730
+ `The test function runs in the browser runner and cannot use "${reference.name}" from this file. Return the value from setup and read it as ctx.<name>`
324661
324731
  );
324662
324732
  }
324663
324733
  });
@@ -325244,7 +325314,8 @@ function buildComponent(path, name, source, ast, root = null) {
325244
325314
  function buildLayout2(path, name, source, ast, root = null) {
325245
325315
  const { declaration, helpers } = defaultExportOf(ast, {
325246
325316
  helpers: "anywhere",
325247
- allowAppImports: true
325317
+ allowAppImports: true,
325318
+ moduleUid: true
325248
325319
  });
325249
325320
  if (!isFunctionNode(declaration)) {
325250
325321
  throw new SourceError("A layout file must export default a function", declaration);
@@ -325646,6 +325717,26 @@ function listFiles(root) {
325646
325717
  }
325647
325718
  return files.toSorted((left, right) => left < right ? -1 : left > right ? 1 : 0);
325648
325719
  }
325720
+ var MODULE_ENTITY_TYPES = { layouts: "layout", components: "component" };
325721
+ var MODULE_ENTITY_EXTENSIONS = /* @__PURE__ */ new Set([".tsx", ".ts", ".jsx", ".js"]);
325722
+ function moduleEntityType(path) {
325723
+ const type = MODULE_ENTITY_TYPES[topDirectory(path)] ?? null;
325724
+ if (type === null || !MODULE_ENTITY_EXTENSIONS.has(extname3(path)) || /\.(test|spec|d)\.[a-z]+$/.test(path)) {
325725
+ return null;
325726
+ }
325727
+ return type;
325728
+ }
325729
+ function moduleUidDefinition(type, path, source) {
325730
+ try {
325731
+ const ast = parseSource(source, { jsx: extname3(path) === ".tsx" || extname3(path) === ".jsx" });
325732
+ return { type, path, source, program: ast.program, optional: true };
325733
+ } catch (error) {
325734
+ if (error instanceof SourceError || error instanceof SyntaxError) {
325735
+ return null;
325736
+ }
325737
+ throw error;
325738
+ }
325739
+ }
325649
325740
  function topDirectory(path) {
325650
325741
  const slash = path.indexOf("/");
325651
325742
  return slash === -1 ? null : path.slice(0, slash);
@@ -326411,6 +326502,15 @@ function buildWorkspace(root, { assetCatalog = null, writeSource = false, fixSou
326411
326502
  const testFiles = [];
326412
326503
  let brandAssets = [];
326413
326504
  const files = listFiles(root);
326505
+ const moduleUidDefinitions = [];
326506
+ for (const path of files) {
326507
+ const type = moduleEntityType(path);
326508
+ const definition = type === null ? null : moduleUidDefinition(type, path, readFileSync13(join17(root, path), "utf8"));
326509
+ if (definition !== null) {
326510
+ moduleUidDefinitions.push(definition);
326511
+ }
326512
+ }
326513
+ diagnostics.push(...checkDefinitionUids(root, moduleUidDefinitions, { write: writeSource }).diagnostics);
326414
326514
  const domainKeys = readDomainKeys(root);
326415
326515
  const declaredDomains = domainKeys === null ? null : domainEntries(domainKeys);
326416
326516
  if (declaredDomains !== null || !existsSync6(join17(root, GENERATED_DOMAINS_PATH))) {
package/dist/index.d.ts CHANGED
@@ -1252,14 +1252,12 @@ type TestSignInTarget =
1252
1252
  | ({ id: string } & Record<string, unknown>)
1253
1253
  | { resource: string; id: string };
1254
1254
 
1255
- /** `Sdk` in the test function. `setup` is the object that the setup function returned. */
1256
- export type TestSdk<S> = {
1255
+ /** `Sdk` in the test function. */
1256
+ export type TestSdk = {
1257
1257
  /** The workspace that the run acts on. */
1258
1258
  readonly workspace: { readonly id: string; readonly name: string; readonly baseUrl: string };
1259
1259
  /** An absolute URL on the run's workspace. */
1260
1260
  url(path?: string): string;
1261
- /** The object that setup returned, or `{}` without a setup function. */
1262
- readonly setup: S;
1263
1261
  /** Signs `page` in as a record that setup returned, or as `{ resource, id }`, then opens `redirectTo` (default `/`). */
1264
1262
  loginAs(record: TestSignInTarget, options?: { redirectTo?: string }): Promise<void>;
1265
1263
  /** Opens a second browser signed in as another record and returns its page. */
@@ -1293,39 +1291,40 @@ export type TestSdk<S> = {
1293
1291
  };
1294
1292
 
1295
1293
  /** The values that the runner gives the test function. */
1296
- export type TestFixtures<S> = {
1294
+ export type TestFixtures<C> = {
1297
1295
  page: import('@playwright/test').Page;
1298
1296
  context: import('@playwright/test').BrowserContext;
1299
1297
  request: import('@playwright/test').APIRequestContext;
1300
1298
  browser: import('@playwright/test').Browser;
1301
1299
  expect: import('@playwright/test').Expect;
1302
- Sdk: TestSdk<S>;
1300
+ Sdk: TestSdk;
1301
+ /** The object that setup returned, or `{}` without a setup function. A change to it reaches assert. */
1302
+ ctx: C;
1303
1303
  };
1304
1304
 
1305
1305
  /**
1306
- * The functions of a test. `setup` and `assert` are workflow handlers without a config: the build
1307
- * compiles each one as `defineWorkflow(handler)` of `@diagonal-hq/workflows/test`, and the run
1308
- * executes it once in the test workspace as an embedded script. It runs as the acting account,
1309
- * with no trigger, no `runAs`, and no `input` schema, so its input is fixed. To act as another
1310
- * identity, call `workflow.run` with a workflow that sets Run As. `test` runs in the browser runner
1311
- * as the body of a Playwright test, so it can use only its fixtures: no import or helper of its file.
1306
+ * The functions of a test. They share one ctx: setup gets it empty, and the object that setup
1307
+ * returns is the ctx of the test function and of assert. A change that the test function makes to
1308
+ * ctx reaches assert. The run sends ctx between them as JSON.
1309
+ *
1310
+ * `setup` and `assert` run once in the test workspace as embedded scripts, as the acting account,
1311
+ * with the `test` script profile. To act as another identity, call `workflow.run` with a workflow
1312
+ * that sets Run As. `test` runs in the browser runner as the body of a Playwright test, so it can
1313
+ * use only its fixtures: no import or helper of its file.
1312
1314
  */
1313
- export type TestHandlers<S> = {
1314
- /** Creates the records that the test needs and returns them. Its input is `{}`. */
1315
- setup?: (input: Record<string, never>, ctx: WorkflowContext) => S | Promise<S>;
1316
- test: (fixtures: TestFixtures<Awaited<S>>) => Promise<void>;
1317
- /**
1318
- * Reads the records after the test, and calls `fail(...)` when a value is wrong. Its input is
1319
- * the object that `setup` returned, or `{}` without a setup.
1320
- */
1321
- assert?: (setup: Awaited<S>, ctx: WorkflowContext) => void | Promise<void>;
1315
+ export type TestHandlers<C> = {
1316
+ /** Creates the records that the test needs and returns them. They become ctx. */
1317
+ setup?: (ctx: Record<string, unknown>) => C | Promise<C>;
1318
+ test: (fixtures: TestFixtures<Awaited<C>>) => Promise<void>;
1319
+ /** Reads the records after the test, and calls `fail(...)` when a value is wrong. */
1320
+ assert?: (ctx: Awaited<C>) => void | Promise<void>;
1322
1321
  };
1323
1322
 
1324
1323
  /**
1325
1324
  * The default export of `tests/<suite>/<key>.ts`, one E2E test of the suite in the folder. The
1326
1325
  * file name is the test key.
1327
1326
  */
1328
- export declare function defineTest<S = Record<string, never>>(
1327
+ export declare function defineTest<C = {}>(
1329
1328
  config: TestConfig,
1330
- handlers: TestHandlers<S>
1331
- ): { readonly config: TestConfig } & TestHandlers<S>;
1329
+ handlers: TestHandlers<C>
1330
+ ): { readonly config: TestConfig } & TestHandlers<C>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@diagonal-hq/cli",
3
- "version": "0.21.2",
3
+ "version": "0.22.0",
4
4
  "description": "The diagonal CLI and the configuration helpers for file-based Diagonal workspaces.",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "repository": {