@latticecms/cli 0.0.0 → 0.1.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.
Files changed (72) hide show
  1. package/README.md +138 -2
  2. package/dist/bin.d.ts +3 -0
  3. package/dist/bin.d.ts.map +1 -0
  4. package/dist/bin.js +12 -0
  5. package/dist/bin.js.map +1 -0
  6. package/dist/changes.d.ts +22 -0
  7. package/dist/changes.d.ts.map +1 -0
  8. package/dist/changes.js +118 -0
  9. package/dist/changes.js.map +1 -0
  10. package/dist/collection.d.ts +5 -0
  11. package/dist/collection.d.ts.map +1 -0
  12. package/dist/collection.js +166 -0
  13. package/dist/collection.js.map +1 -0
  14. package/dist/config.d.ts +37 -0
  15. package/dist/config.d.ts.map +1 -0
  16. package/dist/config.js +111 -0
  17. package/dist/config.js.map +1 -0
  18. package/dist/diff.d.ts +6 -0
  19. package/dist/diff.d.ts.map +1 -0
  20. package/dist/diff.js +83 -0
  21. package/dist/diff.js.map +1 -0
  22. package/dist/edit.d.ts +105 -0
  23. package/dist/edit.d.ts.map +1 -0
  24. package/dist/edit.js +571 -0
  25. package/dist/edit.js.map +1 -0
  26. package/dist/exit.d.ts +13 -0
  27. package/dist/exit.d.ts.map +1 -0
  28. package/dist/exit.js +19 -0
  29. package/dist/exit.js.map +1 -0
  30. package/dist/layout.d.ts +20 -0
  31. package/dist/layout.d.ts.map +1 -0
  32. package/dist/layout.js +59 -0
  33. package/dist/layout.js.map +1 -0
  34. package/dist/main.d.ts +7 -0
  35. package/dist/main.d.ts.map +1 -0
  36. package/dist/main.js +58 -0
  37. package/dist/main.js.map +1 -0
  38. package/dist/migrate.d.ts +9 -0
  39. package/dist/migrate.d.ts.map +1 -0
  40. package/dist/migrate.js +120 -0
  41. package/dist/migrate.js.map +1 -0
  42. package/dist/migration.d.ts +5 -0
  43. package/dist/migration.d.ts.map +1 -0
  44. package/dist/migration.js +170 -0
  45. package/dist/migration.js.map +1 -0
  46. package/dist/names.d.ts +15 -0
  47. package/dist/names.d.ts.map +1 -0
  48. package/dist/names.js +32 -0
  49. package/dist/names.js.map +1 -0
  50. package/dist/templates.d.ts +21 -0
  51. package/dist/templates.d.ts.map +1 -0
  52. package/dist/templates.js +73 -0
  53. package/dist/templates.js.map +1 -0
  54. package/dist/typescript.d.ts +9 -0
  55. package/dist/typescript.d.ts.map +1 -0
  56. package/dist/typescript.js +60 -0
  57. package/dist/typescript.js.map +1 -0
  58. package/package.json +61 -2
  59. package/src/bin.ts +12 -0
  60. package/src/changes.ts +170 -0
  61. package/src/collection.ts +228 -0
  62. package/src/config.ts +142 -0
  63. package/src/diff.ts +90 -0
  64. package/src/edit.ts +812 -0
  65. package/src/exit.ts +19 -0
  66. package/src/layout.ts +91 -0
  67. package/src/main.ts +71 -0
  68. package/src/migrate.ts +155 -0
  69. package/src/migration.ts +239 -0
  70. package/src/names.ts +48 -0
  71. package/src/templates.ts +104 -0
  72. package/src/typescript.ts +79 -0
@@ -0,0 +1,73 @@
1
+ import { call, objectEntry } from './layout.js';
2
+ /** A string in single quotes. Labels hold only letters, digits, spaces and hyphens. */
3
+ const quote = (text) => `'${text}'`;
4
+ /** A new collection: a title field to start from, and its tenant and label. */
5
+ export function collectionText(names, tenant, label) {
6
+ return [
7
+ "import { collection } from '@latticecms/core';",
8
+ "import { z } from 'zod';",
9
+ '',
10
+ ...call('', `export const ${names.exportName} = collection`, [
11
+ quote(names.slug),
12
+ {
13
+ expanded: true,
14
+ lines: (indent) => [
15
+ `${indent}schema: z.object({`,
16
+ `${indent} name: z.string().min(1),`,
17
+ `${indent}}),`,
18
+ ...(tenant === undefined
19
+ ? []
20
+ : [`${indent}tenant: ${quote(tenant)},`]),
21
+ ...(label === undefined
22
+ ? []
23
+ : objectEntry(indent, 'label', [
24
+ `singular: ${quote(label.singular)}`,
25
+ `plural: ${quote(label.plural)}`,
26
+ ])),
27
+ ],
28
+ },
29
+ ], ';'),
30
+ '',
31
+ ].join('\n');
32
+ }
33
+ /**
34
+ * The collection's test: what the scaffold made, and nothing it did not.
35
+ * The composition's contract has the slug and its six procedures, which
36
+ * also proves every ref resolves within the app; and the schema parses a
37
+ * document and refuses one without a name. It builds no app, so a ref, a
38
+ * relation, a method or an override anywhere in the app never breaks it.
39
+ * Without a composition export, only the schema test.
40
+ */
41
+ export function testText(names, app, sort) {
42
+ const local = [...(app === undefined ? [] : [app])]
43
+ .concat({ name: names.exportName, specifier: `./${names.file}.js` })
44
+ .sort((a, b) => sort(a.specifier, b.specifier));
45
+ const schema = `${names.exportName}.schema`;
46
+ return [
47
+ "import { describe, expect, it } from 'vitest';",
48
+ ...local.map(({ name, specifier }) => `import { ${name} } from '${specifier}';`),
49
+ '',
50
+ "// What the scaffold made. Test behavior through the app's own setup.",
51
+ `describe(${quote(names.slug)}, () => {`,
52
+ ...(app === undefined
53
+ ? []
54
+ : [
55
+ " it('is in the app, with its operations', () => {",
56
+ " const operations = ['find', 'count', 'get', 'create', 'update', 'delete'];",
57
+ ...call(' ', 'const keys = Object.keys', [`${app.name}.contract.${names.slug}`], ';'),
58
+ ' expect(keys).toEqual(expect.arrayContaining(operations));',
59
+ ' });',
60
+ '',
61
+ ]),
62
+ " it('parses a document, and refuses one without a name', () => {",
63
+ ...call(' ', `const parsed = ${schema}.parse`, [{ expanded: false, lines: (indent) => [`${indent}name: 'First',`] }], ';'),
64
+ " expect(parsed).toMatchObject({ name: 'First' });",
65
+ ...call(' ', `const refused = ${schema}.safeParse`, ['{}'], ';'),
66
+ ' const paths = refused.error?.issues.map((issue) => issue.path);',
67
+ " expect(paths).toEqual([['name']]);",
68
+ ' });',
69
+ '});',
70
+ '',
71
+ ].join('\n');
72
+ }
73
+ //# sourceMappingURL=templates.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"templates.js","sourceRoot":"","sources":["../src/templates.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAGhD,uFAAuF;AACvF,MA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}
@@ -0,0 +1,9 @@
1
+ import type * as TS from 'typescript';
2
+ export type TypeScript = typeof TS;
3
+ /**
4
+ * The app's own TypeScript, resolved from its directory, so the CLI parses
5
+ * the app's code with the compiler the app builds it with. Older than 5.8
6
+ * is refused, and so is 7, which has no JavaScript API.
7
+ */
8
+ export declare function loadTypeScript(root: string): TypeScript;
9
+ //# sourceMappingURL=typescript.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"typescript.d.ts","sourceRoot":"","sources":["../src/typescript.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,KAAK,EAAE,MAAM,YAAY,CAAC;AAGtC,MAAM,MAAM,UAAU,GAAG,OAAO,EAAE,CAAC;AAiCnC;;;;GAIG;AACH,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,GAAG,UAAU,CAmCvD"}
@@ -0,0 +1,60 @@
1
+ import { createRequire } from 'node:module';
2
+ import { join } from 'node:path';
3
+ import { Exit } from './exit.js';
4
+ /** The oldest TypeScript the CLI's peer range takes. */
5
+ const oldest = { major: 5, minor: 8 };
6
+ /**
7
+ * The first major the CLI cannot use. TypeScript 7 is the native compiler:
8
+ * its package has no JavaScript API, so nothing can parse a file with it.
9
+ */
10
+ const native = 7;
11
+ // The guard checks the function the CLI calls first. A package named
12
+ // typescript that has it, at a version in the range, is taken for the
13
+ // compiler.
14
+ function isTypeScript(value) {
15
+ return (typeof value === 'object' &&
16
+ value !== null &&
17
+ 'createSourceFile' in value &&
18
+ typeof value.createSourceFile === 'function');
19
+ }
20
+ /** The `major.minor` a typescript package reports, if it reports one. */
21
+ function versionOf(value) {
22
+ return typeof value === 'object' &&
23
+ value !== null &&
24
+ 'versionMajorMinor' in value &&
25
+ typeof value.versionMajorMinor === 'string'
26
+ ? value.versionMajorMinor
27
+ : undefined;
28
+ }
29
+ /**
30
+ * The app's own TypeScript, resolved from its directory, so the CLI parses
31
+ * the app's code with the compiler the app builds it with. Older than 5.8
32
+ * is refused, and so is 7, which has no JavaScript API.
33
+ */
34
+ export function loadTypeScript(root) {
35
+ const require = createRequire(join(root, 'package.json'));
36
+ let loaded;
37
+ try {
38
+ loaded = require('typescript');
39
+ }
40
+ catch {
41
+ throw new Exit(`typescript is not installed in ${root}: run npm install --save-dev typescript@^6`, 1);
42
+ }
43
+ const version = versionOf(loaded);
44
+ if (version === undefined) {
45
+ throw new Exit(`the typescript package in ${root} is not TypeScript`, 1);
46
+ }
47
+ const [major = 0, minor = 0] = version.split('.').map(Number);
48
+ if (major < oldest.major ||
49
+ (major === oldest.major && minor < oldest.minor)) {
50
+ throw new Exit(`typescript ${version} in ${root} is too old: lattice needs ${oldest.major}.${oldest.minor} or later`, 1);
51
+ }
52
+ if (major >= native) {
53
+ throw new Exit(`typescript ${version} in ${root} is the native compiler, which has no JavaScript API to parse files with: run npm install --save-dev typescript@^6`, 1);
54
+ }
55
+ if (!isTypeScript(loaded)) {
56
+ throw new Exit(`the typescript package in ${root} is not TypeScript`, 1);
57
+ }
58
+ return loaded;
59
+ }
60
+ //# sourceMappingURL=typescript.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"typescript.js","sourceRoot":"","sources":["../src/typescript.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAEjC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAIjC,wDAAwD;AACxD,MAAM,MAAM,GAAG,EAAE,KAAK,EAAE,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE,CAAC;AAEtC;;;GAGG;AACH,MAAM,MAAM,GAAG,CAAC,CAAC;AAEjB,qEAAqE;AACrE,sEAAsE;AACtE,YAAY;AACZ,SAAS,YAAY,CAAC,KAAc;IAClC,OAAO,CACL,OAAO,KAAK,KAAK,QAAQ;QACzB,KAAK,KAAK,IAAI;QACd,kBAAkB,IAAI,KAAK;QAC3B,OAAO,KAAK,CAAC,gBAAgB,KA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AAC;IACJ,CAAC;IACD,IAAI,KAAK,IAAI,MAAM,EAAE,CAAC;QACpB,MAAM,IAAI,IAAI,CACZ,cAAc,OAAO,OAAO,IAAI,oHAAoH,EACpJ,CAAC,CACF,CAAC;IACJ,CAAC;IACD,IAAI,CAAC,YAAY,CAAC,MAAM,CAAC,EAAE,CAAC;QAC1B,MAAM,IAAI,IAAI,CAAC,6BAA6B,IAAI,oBAAoB,EAAE,CAAC,CAAC,CAAC;IAC3E,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC"}
package/package.json CHANGED
@@ -1,15 +1,74 @@
1
1
  {
2
2
  "name": "@latticecms/cli",
3
- "version": "0.0.0",
4
- "description": "Placeholder that reserves the name. Lattice CMS releases start at 0.1.0.",
3
+ "version": "0.1.0",
4
+ "description": "The lattice command: scaffolds collections and migrations, and runs migrations.",
5
+ "keywords": [
6
+ "lattice",
7
+ "cms",
8
+ "cli",
9
+ "scaffold",
10
+ "migrations"
11
+ ],
5
12
  "license": "MIT",
13
+ "type": "module",
6
14
  "repository": {
7
15
  "type": "git",
8
16
  "url": "git+https://github.com/crobinson42/lattice-cms.git",
9
17
  "directory": "packages/cli"
10
18
  },
11
19
  "homepage": "https://github.com/crobinson42/lattice-cms/tree/main/packages/cli#readme",
20
+ "bugs": {
21
+ "url": "https://github.com/crobinson42/lattice-cms/issues"
22
+ },
23
+ "bin": {
24
+ "lattice": "./dist/bin.js"
25
+ },
26
+ "exports": {
27
+ "./package.json": "./package.json"
28
+ },
29
+ "files": [
30
+ "dist",
31
+ "src",
32
+ "!src/**/*.test.ts",
33
+ "!src/test"
34
+ ],
12
35
  "publishConfig": {
13
36
  "access": "public"
37
+ },
38
+ "engines": {
39
+ "node": ">=22.11"
40
+ },
41
+ "scripts": {
42
+ "build": "tsc -b",
43
+ "test": "vitest run",
44
+ "type-check": "tsc --noEmit -p tsconfig.check.json",
45
+ "lint": "biome check .",
46
+ "clean": "rm -rf dist *.tsbuildinfo"
47
+ },
48
+ "peerDependencies": {
49
+ "@hexok/logger": "^0.2.0",
50
+ "@latticecms/core": "^0.1.0",
51
+ "@latticecms/store-mongo": "^0.1.0",
52
+ "typescript": ">=5.8 <7"
53
+ },
54
+ "peerDependenciesMeta": {
55
+ "@hexok/logger": {
56
+ "optional": true
57
+ },
58
+ "@latticecms/store-mongo": {
59
+ "optional": true
60
+ }
61
+ },
62
+ "devDependencies": {
63
+ "@hexok/logger": "^0.2.0",
64
+ "@latticecms/core": "*",
65
+ "@latticecms/store-mongo": "*",
66
+ "mongodb": "^7.9.1",
67
+ "mongodb-memory-server": "^11.3.0"
68
+ },
69
+ "config": {
70
+ "mongodbMemoryServer": {
71
+ "version": "8.0.14"
72
+ }
14
73
  }
15
74
  }
package/src/bin.ts ADDED
@@ -0,0 +1,12 @@
1
+ #!/usr/bin/env node
2
+ import { main } from './main.js';
3
+
4
+ // A reader that stops early, such as `| head`, closes the pipe. The output
5
+ // it did not read is not an error.
6
+ process.stdout.on('error', (error) => {
7
+ if ('code' in error && error.code === 'EPIPE') return;
8
+ throw error;
9
+ });
10
+
11
+ // The exit code, not process.exit(), so piped output is flushed first.
12
+ process.exitCode = await main(process.argv.slice(2), process.cwd());
package/src/changes.ts ADDED
@@ -0,0 +1,170 @@
1
+ import { constants, existsSync } from 'node:fs';
2
+ import {
3
+ access,
4
+ chmod,
5
+ link,
6
+ readFile,
7
+ rename,
8
+ rm,
9
+ stat,
10
+ writeFile,
11
+ } from 'node:fs/promises';
12
+ import { basename, dirname, join, relative, sep } from 'node:path';
13
+ import { diff } from './diff.js';
14
+ import { applyInserts, type FileEdit } from './edit.js';
15
+ import { Exit } from './exit.js';
16
+
17
+ /** A file to create or edit, with its text before and after. */
18
+ export type Change = {
19
+ readonly path: string;
20
+ readonly before: string | undefined;
21
+ readonly after: string;
22
+ };
23
+
24
+ /** A path from the app's root, with forward slashes, as output names it. */
25
+ export const shown = (root: string, path: string) =>
26
+ relative(root, path).split(sep).join('/');
27
+
28
+ /** The import specifier for `to` from a file at `from`: relative, ending in `.js`. */
29
+ export function specifierOf(from: string, to: string): string {
30
+ const path = relative(dirname(from), to)
31
+ .split(sep)
32
+ .join('/')
33
+ .replace(/\.tsx?$/, '.js');
34
+ return path.startsWith('.') ? path : `./${path}`;
35
+ }
36
+
37
+ /** The lines a refused edit would have added, and where, for each file. */
38
+ export function byHand(
39
+ root: string,
40
+ created: readonly Change[],
41
+ edits: readonly FileEdit[],
42
+ ) {
43
+ return [
44
+ 'Nothing was written. Make these changes by hand, or fix the shape and run the command again:',
45
+ ...created.map(
46
+ (change) =>
47
+ `${shown(root, change.path)}, a new file:\n${change.after.trimEnd()}`,
48
+ ),
49
+ ...edits.flatMap((edit) =>
50
+ edit.additions.map(
51
+ (addition) =>
52
+ `${shown(root, edit.path)}, ${addition.where}:\n${addition.lines}`,
53
+ ),
54
+ ),
55
+ ].join('\n\n');
56
+ }
57
+
58
+ /**
59
+ * Writes every change, or none. Each new text is staged in a file beside
60
+ * its target. Then each edited file must still hold the text that was
61
+ * parsed and be writable, and each new file must still be absent. Then the
62
+ * staged files take their targets' places: a rename for an edited file,
63
+ * and a link, which never replaces a file, for a new one. On any failure
64
+ * the staged files are removed and the files already placed are restored.
65
+ */
66
+ async function writeAll(root: string, changes: readonly Change[]) {
67
+ const staged: { readonly change: Change; readonly temp: string }[] = [];
68
+ const placed: Change[] = [];
69
+ let current = '';
70
+ try {
71
+ for (const change of changes) {
72
+ current = change.path;
73
+ const temp = join(
74
+ dirname(change.path),
75
+ `.${basename(change.path)}.lattice-${process.pid}.tmp`,
76
+ );
77
+ await writeFile(temp, change.after, { flag: 'wx' });
78
+ staged.push({ change, temp });
79
+ if (change.before !== undefined) {
80
+ await chmod(temp, (await stat(change.path)).mode & 0o7777);
81
+ }
82
+ }
83
+ for (const { change } of staged) {
84
+ current = change.path;
85
+ if (change.before === undefined) {
86
+ if (existsSync(change.path)) {
87
+ throw new Exit(`${shown(root, change.path)} already exists`, 1);
88
+ }
89
+ } else {
90
+ await access(change.path, constants.W_OK);
91
+ if ((await readFile(change.path, 'utf8')) !== change.before) {
92
+ throw new Exit(
93
+ `${shown(root, change.path)} changed while lattice ran; nothing was written`,
94
+ 1,
95
+ );
96
+ }
97
+ }
98
+ }
99
+ for (const { change, temp } of staged) {
100
+ current = change.path;
101
+ if (change.before === undefined) {
102
+ await link(temp, change.path);
103
+ await rm(temp);
104
+ } else {
105
+ await rename(temp, change.path);
106
+ }
107
+ placed.push(change);
108
+ }
109
+ } catch (error) {
110
+ await Promise.all(staged.map(({ temp }) => rm(temp, { force: true })));
111
+ for (const change of placed.reverse()) {
112
+ if (change.before === undefined) await rm(change.path, { force: true });
113
+ else await writeFile(change.path, change.before);
114
+ }
115
+ if (error instanceof Exit) throw error;
116
+ const code =
117
+ error instanceof Error && 'code' in error ? ` (${error.code})` : '';
118
+ throw new Exit(
119
+ `cannot write ${shown(root, current)}${code}; nothing was written`,
120
+ 1,
121
+ );
122
+ }
123
+ }
124
+
125
+ /** The changes an edit makes: its file, before and after its inserts. */
126
+ export function changeOf(edit: FileEdit): Change {
127
+ return {
128
+ path: edit.path,
129
+ before: edit.before,
130
+ after: applyInserts(
131
+ edit.before,
132
+ edit.additions.flatMap((addition) => addition.inserts),
133
+ ),
134
+ };
135
+ }
136
+
137
+ /**
138
+ * Refuses when an edit's file has no place for it, printing every change by
139
+ * hand. Else prints each change as a diff on a dry run, or writes them all
140
+ * and names each file.
141
+ */
142
+ export async function apply(
143
+ root: string,
144
+ created: readonly Change[],
145
+ edits: readonly FileEdit[],
146
+ dryRun: boolean,
147
+ ): Promise<void> {
148
+ const refused = edits.flatMap((edit) =>
149
+ edit.refused === undefined ? [] : [edit.refused],
150
+ );
151
+ if (refused.length > 0) {
152
+ throw new Exit(refused.join('; '), 1, byHand(root, created, edits));
153
+ }
154
+ const changes = [...created, ...edits.map(changeOf)];
155
+ if (dryRun) {
156
+ for (const change of changes) {
157
+ process.stdout.write(
158
+ diff(shown(root, change.path), change.before, change.after),
159
+ );
160
+ }
161
+ process.stdout.write('Dry run: nothing was written.\n');
162
+ return;
163
+ }
164
+ await writeAll(root, changes);
165
+ for (const change of changes) {
166
+ process.stdout.write(
167
+ `${change.before === undefined ? 'created' : 'edited'} ${shown(root, change.path)}\n`,
168
+ );
169
+ }
170
+ }
@@ -0,0 +1,228 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { readdir, readFile } from 'node:fs/promises';
3
+ import { join } from 'node:path';
4
+ import { parseArgs } from 'node:util';
5
+ import type * as TS from 'typescript';
6
+ import { apply, type Change, shown, specifierOf } from './changes.js';
7
+ import { existing, loadConfig } from './config.js';
8
+ import {
9
+ compareSpecifiers,
10
+ compositionEdit,
11
+ eventsEdit,
12
+ importedAs,
13
+ parse,
14
+ } from './edit.js';
15
+ import { Exit } from './exit.js';
16
+ import { fieldProblem, type Names, namesOf } from './names.js';
17
+ import { collectionText, type TestImport, testText } from './templates.js';
18
+ import { loadTypeScript, type TypeScript } from './typescript.js';
19
+
20
+ export const collectionUsage =
21
+ 'Usage: lattice collection <slug> [--tenant <field> | --global] [--label <singular>,<plural>] [--dry-run]';
22
+
23
+ export const collectionHelp = `${collectionUsage}
24
+
25
+ Adds a collection to the app: its file, a test, its registration in the
26
+ composition, and its events in the events catalog.
27
+
28
+ <slug> Lower snake case, plural: deal_notes.
29
+ --tenant <field> The tenant field. The default is "lattice.tenant" in package.json.
30
+ --global No tenant: one set of rows for every caller.
31
+ --label s,p The label, when the slug's singular is wrong: person,people.
32
+ --dry-run Print the changes as a diff and write nothing.
33
+ `;
34
+
35
+ const options = {
36
+ tenant: { type: 'string' },
37
+ global: { type: 'boolean' },
38
+ label: { type: 'string' },
39
+ 'dry-run': { type: 'boolean' },
40
+ help: { type: 'boolean', short: 'h' },
41
+ } as const;
42
+
43
+ /** The label from `--label singular,plural`. */
44
+ function labelOf(value: string | undefined) {
45
+ if (value === undefined) return undefined;
46
+ const parts = value.split(',').map((part) => part.trim());
47
+ const [singular, plural] = parts;
48
+ const word = /^[\p{L}\p{N}][\p{L}\p{N} -]*$/u;
49
+ if (
50
+ parts.length !== 2 ||
51
+ singular === undefined ||
52
+ plural === undefined ||
53
+ !word.test(singular) ||
54
+ !word.test(plural)
55
+ ) {
56
+ throw new Exit(
57
+ `--label takes a singular and a plural of letters, digits, spaces and hyphens: --label person,people`,
58
+ 2,
59
+ );
60
+ }
61
+ return { singular, plural };
62
+ }
63
+
64
+ /** The tenant field from the flags and the config, or a refusal. */
65
+ function tenantOf(
66
+ flags: { readonly tenant?: string; readonly global?: boolean },
67
+ configured: string | undefined,
68
+ ): string | undefined {
69
+ if (flags.global === true && flags.tenant !== undefined) {
70
+ throw new Exit('--tenant and --global cannot both be given', 2);
71
+ }
72
+ if (flags.global === true) return undefined;
73
+ const tenant = flags.tenant ?? configured;
74
+ if (tenant === undefined) {
75
+ throw new Exit(
76
+ 'name the tenant field with --tenant <field>, or pass --global; "lattice.tenant" in package.json sets a default',
77
+ 2,
78
+ );
79
+ }
80
+ const problem = fieldProblem(tenant);
81
+ if (problem !== undefined) throw new Exit(problem, 1);
82
+ return tenant;
83
+ }
84
+
85
+ /**
86
+ * Every call of core's `collection('<slug>', ...)`, by whatever name the
87
+ * file imports it as, and every `through: '<slug>'`, in a file.
88
+ */
89
+ function slugsIn(ts: TypeScript, source: TS.SourceFile) {
90
+ const found: { readonly slug: string; readonly join: boolean }[] = [];
91
+ const collection = importedAs(ts, source, 'collection', '@latticecms/core');
92
+ const visit = (node: TS.Node): void => {
93
+ if (
94
+ collection !== undefined &&
95
+ ts.isCallExpression(node) &&
96
+ ts.isIdentifier(node.expression) &&
97
+ node.expression.text === collection
98
+ ) {
99
+ const [slug] = node.arguments;
100
+ if (slug !== undefined && ts.isStringLiteral(slug)) {
101
+ found.push({ slug: slug.text, join: false });
102
+ }
103
+ }
104
+ if (
105
+ ts.isPropertyAssignment(node) &&
106
+ ts.isIdentifier(node.name) &&
107
+ node.name.text === 'through' &&
108
+ ts.isStringLiteral(node.initializer)
109
+ ) {
110
+ found.push({ slug: node.initializer.text, join: true });
111
+ }
112
+ ts.forEachChild(node, visit);
113
+ };
114
+ visit(source);
115
+ return found;
116
+ }
117
+
118
+ /** Refuses a slug that a collection or a join collection in the app already has. */
119
+ async function checkUnused(
120
+ ts: TypeScript,
121
+ root: string,
122
+ directory: string,
123
+ names: Names,
124
+ ): Promise<void> {
125
+ const files = (await readdir(directory)).filter(
126
+ (file) => /\.[cm]?tsx?$/.test(file) && !/\.(test|d)\.[cm]?tsx?$/.test(file),
127
+ );
128
+ for (const file of files) {
129
+ const path = join(directory, file);
130
+ const source = parse(ts, path, await readFile(path, 'utf8'));
131
+ const taken = slugsIn(ts, source).find(({ slug }) => slug === names.slug);
132
+ if (taken !== undefined) {
133
+ throw new Exit(
134
+ taken.join
135
+ ? `"${names.slug}" is a join collection in ${shown(root, path)}`
136
+ : `"${names.slug}" is a collection in ${shown(root, path)}`,
137
+ 1,
138
+ );
139
+ }
140
+ }
141
+ }
142
+
143
+ /** `lattice collection`: writes a collection, its test and its registrations. */
144
+ export async function collectionCommand(
145
+ args: readonly string[],
146
+ cwd: string,
147
+ ): Promise<void> {
148
+ const { values: flags, positionals } = parseArgs({
149
+ args: [...args],
150
+ options,
151
+ allowPositionals: true,
152
+ strict: true,
153
+ });
154
+ if (flags.help === true) {
155
+ process.stdout.write(collectionHelp);
156
+ return;
157
+ }
158
+ const [slug, ...extra] = positionals;
159
+ if (slug === undefined || extra.length > 0) {
160
+ throw new Exit(
161
+ slug === undefined
162
+ ? 'collection needs a slug'
163
+ : 'collection takes one slug',
164
+ 2,
165
+ );
166
+ }
167
+ const label = labelOf(flags.label);
168
+ const config = await loadConfig(cwd);
169
+ const tenant = tenantOf(flags, config.tenant);
170
+ const names = namesOf(slug);
171
+ const { root } = config;
172
+ const directory = await existing(config, 'collections', 'directory');
173
+ const compositionPath = await existing(config, 'composition', 'file');
174
+ const eventsPath = await existing(config, 'events', 'file');
175
+ const ts = loadTypeScript(root);
176
+
177
+ const file = join(directory, `${names.file}.ts`);
178
+ const test = join(directory, `${names.file}.test.ts`);
179
+ for (const path of [file, test]) {
180
+ if (existsSync(path)) {
181
+ throw new Exit(`${shown(root, path)} already exists`, 1);
182
+ }
183
+ }
184
+ await checkUnused(ts, root, directory, names);
185
+
186
+ const composition = compositionEdit(
187
+ ts,
188
+ compositionPath,
189
+ shown(root, compositionPath),
190
+ await readFile(compositionPath, 'utf8'),
191
+ names,
192
+ specifierOf(compositionPath, file),
193
+ );
194
+ const events = eventsEdit(
195
+ ts,
196
+ eventsPath,
197
+ shown(root, eventsPath),
198
+ await readFile(eventsPath, 'utf8'),
199
+ names,
200
+ specifierOf(eventsPath, file),
201
+ );
202
+ const edits = [composition, events];
203
+ const app: TestImport | undefined =
204
+ composition.app === undefined
205
+ ? undefined
206
+ : {
207
+ name: composition.app,
208
+ specifier: specifierOf(test, compositionPath),
209
+ };
210
+ const created: Change[] = [
211
+ {
212
+ path: file,
213
+ before: undefined,
214
+ after: collectionText(names, tenant, label),
215
+ },
216
+ {
217
+ path: test,
218
+ before: undefined,
219
+ after: testText(names, app, compareSpecifiers),
220
+ },
221
+ ];
222
+
223
+ await apply(root, created, edits, flags['dry-run'] === true);
224
+ if (flags['dry-run'] === true) return;
225
+ process.stdout.write(
226
+ `${names.slug} is open to any signed-in caller. Tighten its access in ${shown(root, compositionPath)}.\n`,
227
+ );
228
+ }