@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
package/src/config.ts ADDED
@@ -0,0 +1,142 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { readFile, stat } from 'node:fs/promises';
3
+ import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
4
+ import { Exit, isRecord } from './exit.js';
5
+ import { fieldProblem } from './names.js';
6
+
7
+ /** The `"lattice"` keys that name paths, each defaulting to the crm's layout. */
8
+ const defaults = {
9
+ collections: 'src/domain/collections',
10
+ composition: 'src/servers/rpc/contract.ts',
11
+ events: 'src/domain/events/domain-events.ts',
12
+ migrations: 'src/infra/migrations',
13
+ migrate: 'dist/servers/scripts/migrate.js',
14
+ };
15
+
16
+ export type PathKey = keyof typeof defaults;
17
+
18
+ /** Every key. `tenant` has no default. */
19
+ const keys = [...Object.keys(defaults), 'tenant'];
20
+
21
+ /** The app's config, checked: every path is inside the app. */
22
+ export type Config = {
23
+ /** The directory of the app's `package.json`. */
24
+ readonly root: string;
25
+ /** The `package.json`, as messages name it. */
26
+ readonly manifest: string;
27
+ /** Each path key's absolute path. */
28
+ readonly paths: Readonly<Record<PathKey, string>>;
29
+ /** Each path key's value as written, for messages. */
30
+ readonly written: Readonly<Record<PathKey, string>>;
31
+ /** The tenant field of a new collection, when the app names one. */
32
+ readonly tenant: string | undefined;
33
+ };
34
+
35
+ /** The nearest directory at or above `cwd` with a `package.json`. */
36
+ function rootOf(cwd: string): string {
37
+ for (let dir = resolve(cwd); ; dir = dirname(dir)) {
38
+ if (existsSync(join(dir, 'package.json'))) return dir;
39
+ if (dirname(dir) === dir) {
40
+ throw new Exit(`no package.json in ${cwd} or above it`, 1);
41
+ }
42
+ }
43
+ }
44
+
45
+ /**
46
+ * The app's config: the `"lattice"` key of the nearest `package.json`, over
47
+ * the defaults. Anything wrong with it is a usage error that names the file
48
+ * and the key: invalid JSON, an unknown key, a value that is not a
49
+ * non-empty string, a bad tenant field, or a path outside the app. Whether
50
+ * a path exists is checked by the command that needs it, with `existing`.
51
+ */
52
+ export async function loadConfig(cwd: string): Promise<Config> {
53
+ const root = rootOf(cwd);
54
+ const manifestPath = join(root, 'package.json');
55
+ const manifest = relative(cwd, manifestPath) || 'package.json';
56
+ function fail(message: string): never {
57
+ throw new Exit(message, 2);
58
+ }
59
+ let parsed: unknown;
60
+ try {
61
+ parsed = JSON.parse(await readFile(manifestPath, 'utf8'));
62
+ } catch (error) {
63
+ fail(
64
+ `${manifest} is not valid JSON: ${error instanceof Error ? error.message : String(error)}`,
65
+ );
66
+ }
67
+ const given = isRecord(parsed) ? (parsed.lattice ?? {}) : {};
68
+ if (!isRecord(given)) fail(`"lattice" in ${manifest} must be an object`);
69
+ const values: Record<string, string> = { ...defaults };
70
+ for (const [key, value] of Object.entries(given)) {
71
+ if (!keys.includes(key)) {
72
+ fail(`unknown key "lattice.${key}" in ${manifest}`);
73
+ }
74
+ if (typeof value !== 'string' || value.trim() === '') {
75
+ fail(`"lattice.${key}" in ${manifest} must be a non-empty string`);
76
+ }
77
+ values[key] = value;
78
+ }
79
+ const written: Record<PathKey, string> = {
80
+ collections: values.collections ?? defaults.collections,
81
+ composition: values.composition ?? defaults.composition,
82
+ events: values.events ?? defaults.events,
83
+ migrations: values.migrations ?? defaults.migrations,
84
+ migrate: values.migrate ?? defaults.migrate,
85
+ };
86
+ const inside = (key: PathKey): string => {
87
+ const value = written[key];
88
+ const absolute = resolve(root, value);
89
+ const path = relative(root, absolute);
90
+ if (isAbsolute(value) || path === '..' || path.startsWith(`..${sep}`)) {
91
+ fail(
92
+ `"lattice.${key}" in ${manifest} must be a path inside the app, not ${value}`,
93
+ );
94
+ }
95
+ return absolute;
96
+ };
97
+ const tenant = values.tenant;
98
+ const problem = tenant === undefined ? undefined : fieldProblem(tenant);
99
+ if (problem !== undefined) {
100
+ fail(`"lattice.tenant" in ${manifest}: ${problem}`);
101
+ }
102
+ return {
103
+ root,
104
+ manifest,
105
+ paths: {
106
+ collections: inside('collections'),
107
+ composition: inside('composition'),
108
+ events: inside('events'),
109
+ migrations: inside('migrations'),
110
+ migrate: inside('migrate'),
111
+ },
112
+ written,
113
+ tenant,
114
+ };
115
+ }
116
+
117
+ /**
118
+ * The path of `key`, which must exist and be a file or a directory as
119
+ * `kind` says. Otherwise a usage error that names the key.
120
+ */
121
+ export async function existing(
122
+ config: Config,
123
+ key: PathKey,
124
+ kind: 'file' | 'directory',
125
+ ): Promise<string> {
126
+ const path = config.paths[key];
127
+ const value = config.written[key];
128
+ const found = await stat(path).catch(() => undefined);
129
+ if (found === undefined) {
130
+ throw new Exit(
131
+ `${value} does not exist: set "lattice.${key}" in ${config.manifest} to the app's ${kind}`,
132
+ 2,
133
+ );
134
+ }
135
+ if (found.isDirectory() !== (kind === 'directory')) {
136
+ throw new Exit(
137
+ `"lattice.${key}" in ${config.manifest} must be a ${kind}: ${value}`,
138
+ 2,
139
+ );
140
+ }
141
+ return path;
142
+ }
package/src/diff.ts ADDED
@@ -0,0 +1,90 @@
1
+ /** Lines of context around each change. */
2
+ const context = 3;
3
+
4
+ function linesOf(text: string): string[] {
5
+ const lines = text.split('\n');
6
+ if (lines.at(-1) === '') lines.pop();
7
+ return lines;
8
+ }
9
+
10
+ type Op = { readonly kind: ' ' | '-' | '+'; readonly line: string };
11
+
12
+ /** The longest common subsequence of lines, as keep, remove and add steps. */
13
+ function opsOf(before: readonly string[], after: readonly string[]): Op[] {
14
+ const width = after.length + 1;
15
+ const table = new Uint32Array((before.length + 1) * width);
16
+ for (let i = before.length - 1; i >= 0; i--) {
17
+ for (let j = after.length - 1; j >= 0; j--) {
18
+ table[i * width + j] =
19
+ before[i] === after[j]
20
+ ? (table[(i + 1) * width + j + 1] ?? 0) + 1
21
+ : Math.max(
22
+ table[(i + 1) * width + j] ?? 0,
23
+ table[i * width + j + 1] ?? 0,
24
+ );
25
+ }
26
+ }
27
+ const ops: Op[] = [];
28
+ let i = 0;
29
+ let j = 0;
30
+ while (i < before.length || j < after.length) {
31
+ const removed = before[i];
32
+ const added = after[j];
33
+ if (removed !== undefined && added !== undefined && removed === added) {
34
+ ops.push({ kind: ' ', line: removed });
35
+ i++;
36
+ j++;
37
+ } else if (
38
+ // A changed line shows its removal first, as unified diffs do.
39
+ removed !== undefined &&
40
+ (added === undefined ||
41
+ (table[(i + 1) * width + j] ?? 0) >= (table[i * width + j + 1] ?? 0))
42
+ ) {
43
+ ops.push({ kind: '-', line: removed });
44
+ i++;
45
+ } else if (added !== undefined) {
46
+ ops.push({ kind: '+', line: added });
47
+ j++;
48
+ }
49
+ }
50
+ return ops;
51
+ }
52
+
53
+ /**
54
+ * A unified diff of one file, `before` undefined for a new file. Each hunk
55
+ * has three lines of context, and hunks that touch merge.
56
+ */
57
+ export function diff(
58
+ path: string,
59
+ before: string | undefined,
60
+ after: string,
61
+ ): string {
62
+ const ops = opsOf(linesOf(before ?? ''), linesOf(after));
63
+ const out = [before === undefined ? '--- /dev/null' : `--- a/${path}`];
64
+ out.push(`+++ b/${path}`);
65
+ let index = 0;
66
+ while (index < ops.length) {
67
+ const first = ops.findIndex((op, at) => at >= index && op.kind !== ' ');
68
+ if (first === -1) break;
69
+ // Extend the hunk while the next change is within twice the context.
70
+ let last = first;
71
+ for (let at = first; at < ops.length; at++) {
72
+ if (ops[at]?.kind !== ' ') last = at;
73
+ else if (at - last > 2 * context) break;
74
+ }
75
+ const start = Math.max(first - context, index);
76
+ const end = Math.min(last + context + 1, ops.length);
77
+ const lead = ops.slice(0, start);
78
+ const hunk = ops.slice(start, end);
79
+ const oldStart = lead.filter((op) => op.kind !== '+').length;
80
+ const newStart = lead.filter((op) => op.kind !== '-').length;
81
+ const oldCount = hunk.filter((op) => op.kind !== '+').length;
82
+ const newCount = hunk.filter((op) => op.kind !== '-').length;
83
+ out.push(
84
+ `@@ -${oldCount === 0 ? oldStart : oldStart + 1},${oldCount} +${newCount === 0 ? newStart : newStart + 1},${newCount} @@`,
85
+ );
86
+ for (const op of hunk) out.push(`${op.kind}${op.line}`);
87
+ index = end;
88
+ }
89
+ return `${out.join('\n')}\n`;
90
+ }