@kronor/dtv 9.2.1 → 9.4.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 (39) hide show
  1. package/README.md +8 -2
  2. package/dist/cli/commands/definitions.js +76 -0
  3. package/dist/cli/config/loadConfig.js +72 -5
  4. package/dist/cli/definitions/discover.js +130 -0
  5. package/dist/cli/definitions/generate.js +258 -0
  6. package/dist/cli/definitions/loadProject.js +107 -0
  7. package/dist/cli/definitions/project.js +122 -0
  8. package/dist/cli/definitions/resolve.js +53 -0
  9. package/dist/cli/definitions/run.js +223 -0
  10. package/dist/cli/definitions/types.js +8 -0
  11. package/dist/cli/definitions/wire.js +111 -0
  12. package/dist/cli/dtv.js +2 -0
  13. package/dist/cli/typegen/runTypegen.js +5 -3
  14. package/dist/index.es.js +14103 -13451
  15. package/dist/types/components/UserPreferencesPanel.d.ts +2 -1
  16. package/dist/types/dsl/index.d.ts +1 -0
  17. package/dist/types/dsl/migrations.d.ts +114 -0
  18. package/dist/types/dsl/typeErrors.d.ts +1 -1
  19. package/dist/types/framework/decoder.d.ts +61 -0
  20. package/dist/types/framework/filter-form-state.d.ts +18 -2
  21. package/dist/types/framework/filter-sharing.d.ts +21 -9
  22. package/dist/types/framework/runtime.d.ts +2 -0
  23. package/dist/types/framework/saved-filters.d.ts +10 -14
  24. package/dist/types/framework/state/app-state.d.ts +8 -0
  25. package/dist/types/framework/useUserDataManager.d.ts +3 -0
  26. package/dist/types/framework/user-data-errors.d.ts +8 -0
  27. package/dist/types/framework/user-data-manager.d.ts +6 -1
  28. package/dist/types/framework/user-data-undecoded.d.ts +86 -0
  29. package/dist/types/framework/user-data.d.ts +120 -33
  30. package/dist/types/framework/user-data.migrations.d.ts +9 -8
  31. package/dist/types/framework/view-migrations.d.ts +112 -0
  32. package/dist/types/framework/view-parser.d.ts +2 -1
  33. package/dist/types/framework/view-projection.d.ts +52 -0
  34. package/dist/types/framework/view.d.ts +7 -0
  35. package/dist/types/lib/index.d.ts +4 -0
  36. package/dist/types/typegen/index.d.ts +32 -4
  37. package/docs/typegen.md +16 -0
  38. package/docs/view-migrations.md +182 -0
  39. package/package.json +2 -2
@@ -0,0 +1,107 @@
1
+ import { createRequire } from 'node:module';
2
+ import * as fs from 'node:fs/promises';
3
+ import * as path from 'node:path';
4
+ import { pathToFileURL } from 'node:url';
5
+ import { buildProject } from './project.js';
6
+ const VITE_CONFIGS = ['vite.config.ts', 'vite.config.mts', 'vite.config.js', 'vite.config.mjs'];
7
+ async function exists(file) {
8
+ return fs.access(file).then(() => true, () => false);
9
+ }
10
+ async function importProjectVite(cwd) {
11
+ let resolved;
12
+ try {
13
+ resolved = createRequire(path.join(cwd, 'package.json')).resolve('vite');
14
+ }
15
+ catch {
16
+ throw new Error('`dtv definitions` loads the views with the project\'s Vite, but `vite` cannot be resolved from ' + cwd);
17
+ }
18
+ return await import(pathToFileURL(resolved).href);
19
+ }
20
+ /**
21
+ * View modules are browser code, and some touch browser globals as they are imported
22
+ * (e.g. `window.location` to tell the environment). They get the project's jsdom when it
23
+ * has one, otherwise a bare `window` and `location`. Returns what undoes it.
24
+ */
25
+ function installBrowserGlobals(cwd) {
26
+ const globals = globalThis;
27
+ const added = [];
28
+ const add = (key, value) => {
29
+ if (key in globals)
30
+ return;
31
+ try {
32
+ globals[key] = value;
33
+ added.push(key);
34
+ }
35
+ catch {
36
+ // A read-only global of Node's own; it stays as it is.
37
+ }
38
+ };
39
+ let close = () => undefined;
40
+ try {
41
+ const { JSDOM } = createRequire(path.join(cwd, 'package.json'))('jsdom');
42
+ const dom = new JSDOM('<!doctype html><html><body></body></html>', { url: 'http://localhost/', pretendToBeVisual: true });
43
+ for (const key of Object.getOwnPropertyNames(dom.window))
44
+ add(key, dom.window[key]);
45
+ close = () => dom.window.close();
46
+ }
47
+ catch {
48
+ add('location', new URL('http://localhost/'));
49
+ }
50
+ add('window', globalThis);
51
+ add('self', globalThis);
52
+ return () => {
53
+ for (const key of added)
54
+ delete globals[key];
55
+ close();
56
+ };
57
+ }
58
+ export async function loadProject(args) {
59
+ const { cwd, config } = args;
60
+ const vite = await importProjectVite(cwd);
61
+ const configured = args.viteConfig ?? config.definitions.viteConfig;
62
+ const viteConfig = configured !== undefined
63
+ ? path.resolve(cwd, configured)
64
+ : (await Promise.all(VITE_CONFIGS.map(async (name) => (await exists(path.join(cwd, name))) ? path.join(cwd, name) : null)))
65
+ .find(file => file !== null) ?? false;
66
+ const previousCwd = process.cwd();
67
+ process.chdir(cwd);
68
+ const uninstallBrowserGlobals = installBrowserGlobals(cwd);
69
+ const restore = () => {
70
+ uninstallBrowserGlobals();
71
+ process.chdir(previousCwd);
72
+ };
73
+ let server;
74
+ try {
75
+ server = await vite.createServer({
76
+ configFile: viteConfig,
77
+ server: { middlewareMode: true, hmr: false, ws: false },
78
+ optimizeDeps: { noDiscovery: true, include: [] },
79
+ // Dependencies are bundled for SSR rather than imported by Node: view modules import
80
+ // components whose CommonJS dependencies (e.g. prop-types) Node cannot give named
81
+ // exports of.
82
+ ssr: { noExternal: true, optimizeDeps: { noDiscovery: false } },
83
+ appType: 'custom',
84
+ logLevel: 'warn'
85
+ });
86
+ }
87
+ catch (err) {
88
+ restore();
89
+ throw err;
90
+ }
91
+ try {
92
+ return await buildProject({
93
+ cwd,
94
+ config,
95
+ loadModule: id => server.ssrLoadModule(id),
96
+ close: async () => {
97
+ await server.close();
98
+ restore();
99
+ }
100
+ });
101
+ }
102
+ catch (err) {
103
+ await server.close();
104
+ restore();
105
+ throw err;
106
+ }
107
+ }
@@ -0,0 +1,122 @@
1
+ import * as fs from 'node:fs/promises';
2
+ import * as path from 'node:path';
3
+ import fg from 'fast-glob';
4
+ import { discoverViews, scanViewModules } from './discover.js';
5
+ import { projectDefinition, resolveDefinitions } from './resolve.js';
6
+ import { MIGRATIONS_FOLDER } from './types.js';
7
+ /** Never part of the project's own sources. */
8
+ const IGNORED = ['**/node_modules/**', '**/dist/**', '**/build/**', '**/vendor/**', '**/.git/**'];
9
+ async function exists(file) {
10
+ return fs.access(file).then(() => true, () => false);
11
+ }
12
+ function isRecord(value) {
13
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
14
+ }
15
+ /**
16
+ * Builds a view. What the factory logs is dropped: arguments made up from parameter types
17
+ * are odd (e.g. `'x1'` for a date), and code complaining about them is noise. A build that
18
+ * fails says why in its error.
19
+ */
20
+ function build(make) {
21
+ const methods = ['log', 'info', 'warn', 'error', 'debug'];
22
+ const saved = methods.map(method => console[method]);
23
+ methods.forEach(method => { console[method] = () => undefined; });
24
+ try {
25
+ const view = make();
26
+ return isRecord(view) && typeof view.id === 'string'
27
+ ? { view: view }
28
+ : { error: 'it did not return a view' };
29
+ }
30
+ catch (err) {
31
+ return { error: err instanceof Error ? err.message : String(err) };
32
+ }
33
+ finally {
34
+ methods.forEach((method, index) => { console[method] = saved[index]; });
35
+ }
36
+ }
37
+ export async function buildProject(args) {
38
+ const { cwd, config, loadModule } = args;
39
+ const relative = (file) => path.relative(cwd, file).split(path.sep).join('/');
40
+ const modules = await scanViewModules(cwd, config.scan.include, config.scan.exclude, config.scan.dtvImport);
41
+ const discovery = discoverViews(cwd, modules);
42
+ const dtv = await loadModule(config.scan.dtvImport);
43
+ if (typeof dtv.projectView !== 'function' || typeof dtv.checkMigration !== 'function') {
44
+ throw new Error(`The project's ${config.scan.dtvImport} has no view migration support; update it to the version of this CLI`);
45
+ }
46
+ const tooling = dtv;
47
+ const problems = discovery.unreachable.map(file => `${relative(file)}: calls DSL.view, but none of its exports is a view or returns one, so dtv definitions cannot build it`);
48
+ const factories = config.definitions.factories ?? {};
49
+ const used = new Set();
50
+ const exportsNamed = (name) => discovery.exports.filter(found => found.exportName === name).length;
51
+ const configFor = (found) => {
52
+ const qualified = `${relative(found.file)}#${found.exportName}`;
53
+ if (factories[qualified] !== undefined) {
54
+ used.add(qualified);
55
+ return { key: qualified, config: factories[qualified] };
56
+ }
57
+ if (factories[found.exportName] !== undefined) {
58
+ used.add(found.exportName);
59
+ if (exportsNamed(found.exportName) > 1) {
60
+ problems.push(`definitions.factories["${found.exportName}"] matches several exports; name one as "${qualified}"`);
61
+ return { key: qualified, config: undefined };
62
+ }
63
+ return { key: found.exportName, config: factories[found.exportName] };
64
+ }
65
+ return { key: exportsNamed(found.exportName) > 1 ? qualified : found.exportName, config: undefined };
66
+ };
67
+ const built = [];
68
+ for (const found of discovery.exports) {
69
+ const label = `${found.exportName} (${relative(found.file)})`;
70
+ let module;
71
+ try {
72
+ module = await loadModule(found.file);
73
+ }
74
+ catch (err) {
75
+ problems.push(`${label}: its module fails to load (${err instanceof Error ? err.message : String(err)})`);
76
+ continue;
77
+ }
78
+ const exported = module[found.exportName];
79
+ const { key, config: factoryConfig } = configFor(found);
80
+ const item = { label, configKey: key, source: found.file, definition: factoryConfig?.definition };
81
+ if (found.kind === 'constant') {
82
+ built.push({ ...item, generated: false, builds: [build(() => exported)] });
83
+ }
84
+ else if (typeof exported !== 'function') {
85
+ problems.push(`${label}: is not a function when loaded`);
86
+ }
87
+ else if (factoryConfig?.args !== undefined) {
88
+ const configuredArgs = factoryConfig.args;
89
+ built.push({ ...item, generated: false, builds: [build(() => exported(...configuredArgs))] });
90
+ }
91
+ else {
92
+ built.push({
93
+ ...item,
94
+ generated: true,
95
+ builds: [build(() => exported(...found.args.minimal())), build(() => exported(...found.args.contrasting()))]
96
+ });
97
+ }
98
+ }
99
+ for (const key of Object.keys(factories)) {
100
+ if (!used.has(key))
101
+ problems.push(`definitions.factories["${key}"] matches no export of a module calling DSL.view`);
102
+ }
103
+ const resolved = resolveDefinitions(built, (view, definition) => tooling.projectView(view, definition, 1));
104
+ return {
105
+ definitions: resolved.definitions,
106
+ problems: [...problems, ...resolved.problems],
107
+ tooling,
108
+ projectDefinition: (definition, revision) => projectDefinition(resolved.definitions[definition], definition, revision, tooling.projectView),
109
+ async findChainFolders() {
110
+ const indexes = await fg(`**/${MIGRATIONS_FOLDER}/*/index.ts`, { cwd, ignore: IGNORED, absolute: true, onlyFiles: true });
111
+ return indexes.map(index => path.dirname(path.normalize(index))).sort();
112
+ },
113
+ async loadChain(folder) {
114
+ const index = path.join(folder, 'index.ts');
115
+ if (!(await exists(index)))
116
+ return null;
117
+ const loaded = await loadModule(index);
118
+ return (loaded.default ?? null);
119
+ },
120
+ close: args.close
121
+ };
122
+ }
@@ -0,0 +1,53 @@
1
+ import { deepEqual } from './generate.js';
2
+ const differingFilters = (left, right) => Object.keys({ ...left.filters, ...right.filters }).filter(id => !deepEqual(left.filters[id], right.filters[id]));
3
+ export function resolveDefinitions(built, project) {
4
+ const definitions = {};
5
+ const problems = [];
6
+ const configure = (item, what) => `configure ${what} in definitions.factories["${item.configKey}"]`;
7
+ for (const item of built) {
8
+ const [first, ...others] = item.builds;
9
+ if ('error' in first) {
10
+ problems.push(item.generated
11
+ ? `${item.label}: cannot be built with arguments made up from its parameter types (${first.error}); ${configure(item, 'its args')}`
12
+ : `${item.label}: cannot be built with its configured args (${first.error})`);
13
+ continue;
14
+ }
15
+ // A contrasting build that fails only means fewer contrasts to tell what the arguments change.
16
+ const views = [first.view, ...others.flatMap(build => 'view' in build ? [build.view] : [])];
17
+ let definition = item.definition;
18
+ if (definition === undefined) {
19
+ const [minimal, ...rest] = views.map(view => view.id);
20
+ const derived = rest.every(id => id === minimal || (minimal !== '' && !minimal.startsWith('-') && id.startsWith(`${minimal}-`)));
21
+ if (!derived) {
22
+ problems.push(`${item.label}: its view id depends on its arguments (${[minimal, ...rest].join(', ')}); ${configure(item, 'its definition id')}`);
23
+ continue;
24
+ }
25
+ definition = minimal;
26
+ }
27
+ const projections = views.map(view => project(view, definition));
28
+ const varying = projections.slice(1).flatMap(projection => differingFilters(projections[0], projection));
29
+ if (varying.length > 0) {
30
+ problems.push(`${item.label}: its arguments change its filters (${[...new Set(varying)].join(', ')}); ${configure(item, 'the args to snapshot it with')}`);
31
+ continue;
32
+ }
33
+ const existing = definitions[definition];
34
+ if (existing === undefined) {
35
+ definitions[definition] = { instances: views, source: item.source };
36
+ }
37
+ else if (differingFilters(project(existing.instances[0], definition), projections[0]).length === 0) {
38
+ definitions[definition] = { ...existing, instances: [...existing.instances, ...views] };
39
+ }
40
+ else {
41
+ problems.push(`${item.label}: makes views of "${definition}" whose filters differ from another export's`);
42
+ }
43
+ }
44
+ return { definitions, problems };
45
+ }
46
+ /** The projection of a definition: its instances' filters (which agree) and all their columns. */
47
+ export function projectDefinition(definition, id, revision, project) {
48
+ const [first, ...rest] = definition.instances.map(view => project(view, id, revision));
49
+ return rest.reduce((merged, projection) => ({
50
+ ...merged,
51
+ columns: { ...merged.columns, ...Object.fromEntries(Object.entries(projection.columns).filter(([column]) => merged.columns[column] === undefined)) }
52
+ }), first);
53
+ }
@@ -0,0 +1,223 @@
1
+ import * as fs from 'node:fs/promises';
2
+ import * as path from 'node:path';
3
+ import { deepEqual, generateOps, migrationFile, renderIndex, renderMigration, renderSnapshot, snapshotFile } from './generate.js';
4
+ import { renameMigrationsImport, wireMigrations } from './wire.js';
5
+ import { MIGRATIONS_FOLDER } from './types.js';
6
+ async function loadChains(project) {
7
+ const folders = await project.findChainFolders();
8
+ return new Map(await Promise.all(folders.map(async (folder) => [folder, await project.loadChain(folder)])));
9
+ }
10
+ const relative = (options, file) => path.relative(options.cwd, file).split(path.sep).join('/');
11
+ async function locate(options, project, chains, definition, view) {
12
+ if (view.migrations !== undefined) {
13
+ for (const [folder, chain] of chains) {
14
+ if (chain === view.migrations)
15
+ return { kind: 'imported', folder, chain };
16
+ }
17
+ return { kind: 'problem', message: `${definition}: the view uses migrations that are not in a ${MIGRATIONS_FOLDER}/<definition> folder` };
18
+ }
19
+ const named = [...chains.keys()].filter(folder => path.basename(folder) === definition);
20
+ if (named.length > 1) {
21
+ return { kind: 'problem', message: `${definition}: several migration folders and the view uses none of them: ${named.map(folder => relative(options, folder)).join(', ')}` };
22
+ }
23
+ if (named.length === 1)
24
+ return { kind: 'unwired', folder: named[0], chain: chains.get(named[0]) ?? null };
25
+ const source = project.definitions[definition]?.source ?? null;
26
+ const parent = source === null ? path.resolve(options.cwd, options.migrationsDir) : path.join(path.dirname(source), MIGRATIONS_FOLDER);
27
+ return { kind: 'unwired', folder: path.join(parent, definition), chain: null };
28
+ }
29
+ function sameDefinition(live, latest) {
30
+ return live.definition === latest.definition && deepEqual(live.filters, latest.filters) && deepEqual(live.columns, latest.columns);
31
+ }
32
+ /** The migration revisions a folder has files for, oldest first. */
33
+ async function migrationRevisions(folder) {
34
+ const files = await fs.readdir(folder).catch(() => []);
35
+ return files
36
+ .map(file => /^v(\d+)\.ts$/.exec(file))
37
+ .flatMap(match => match === null ? [] : [Number(match[1])])
38
+ .sort((left, right) => left - right);
39
+ }
40
+ function camelCase(definition) {
41
+ return definition.replace(/[^A-Za-z0-9]+(.)?/g, (_, next) => (next ?? '').toUpperCase()).replace(/^[^A-Za-z_$]/, '_$&');
42
+ }
43
+ /**
44
+ * Wires the view of a definition up with its migrations in `folder` (see ./wire): edits its
45
+ * module, or says what to add where it cannot. Returns what to tell the user.
46
+ */
47
+ async function wireUp(options, project, definition, folder) {
48
+ const source = project.definitions[definition]?.source ?? null;
49
+ const from = source === null ? options.cwd : path.dirname(source);
50
+ const relativeFolder = path.relative(from, folder).split(path.sep).join('/');
51
+ const specifier = relativeFolder.startsWith('../') ? relativeFolder : `./${relativeFolder}`;
52
+ let reason = 'its module is not known, as for a JSON view';
53
+ if (source !== null) {
54
+ const wiring = wireMigrations(await fs.readFile(source, 'utf8'), source, definition, specifier, options.dtvImport);
55
+ if (wiring.kind === 'wired') {
56
+ await fs.writeFile(source, wiring.text, 'utf8');
57
+ return [` Wired it up in ${relative(options, source)}`];
58
+ }
59
+ reason = wiring.reason;
60
+ }
61
+ const name = `${camelCase(definition)}Migrations`;
62
+ return [
63
+ source === null
64
+ ? ` Wire it up in the view definition of "${definition}" (${reason}; the path is from ${options.cwd}):`
65
+ : ` Wire it up in ${relative(options, source)} (${reason}):`,
66
+ ` import ${name} from '${specifier}';`,
67
+ ` DSL.view({ …, migrations: ${name} })`
68
+ ];
69
+ }
70
+ async function writeFile(file, content) {
71
+ await fs.mkdir(path.dirname(file), { recursive: true });
72
+ await fs.writeFile(file, content, 'utf8');
73
+ }
74
+ /**
75
+ * Writes a new revision for each definition whose projection changed since its latest
76
+ * snapshot, and a first snapshot for definitions without one. Returns the number of
77
+ * decisions left open (`todo`).
78
+ *
79
+ * Views that could not be made definitions of are left alone and returned as problems.
80
+ */
81
+ export async function runMigrate(options, project) {
82
+ const definitions = options.definition === undefined ? Object.keys(project.definitions) : [options.definition];
83
+ if (options.definition !== undefined && project.definitions[options.definition] === undefined) {
84
+ throw new Error(`No view definition "${options.definition}"; there are ${Object.keys(project.definitions).join(', ')}`);
85
+ }
86
+ if ((options.manual !== undefined || options.renamedFrom !== undefined) && options.definition === undefined) {
87
+ throw new Error('--manual and --renamed-from need the definition they are for');
88
+ }
89
+ let chains = await loadChains(project);
90
+ /** The folder taken over from a renamed definition: the view still imports it from where it was. */
91
+ let renamedFolder = null;
92
+ if (options.renamedFrom !== undefined) {
93
+ const renamedFrom = options.renamedFrom;
94
+ const previous = [...chains.keys()].filter(folder => path.basename(folder) === renamedFrom);
95
+ if (previous.length !== 1) {
96
+ throw new Error(`Cannot take over "${renamedFrom}": ${previous.length === 0 ? 'no' : 'several'} ${MIGRATIONS_FOLDER}/${renamedFrom} folders`);
97
+ }
98
+ const folder = path.join(path.dirname(previous[0]), options.definition);
99
+ if (await fs.access(folder).then(() => true, () => false)) {
100
+ throw new Error(`Cannot take over "${renamedFrom}": ${relative(options, folder)} exists already`);
101
+ }
102
+ await fs.rename(previous[0], folder);
103
+ options.log(`${options.definition}: took over ${relative(options, previous[0])}, now ${relative(options, folder)}`);
104
+ chains = await loadChains(project);
105
+ renamedFolder = folder;
106
+ // The view imports the folder by its old name.
107
+ const source = project.definitions[options.definition]?.source ?? null;
108
+ const renamedImport = source === null ? null : renameMigrationsImport(await fs.readFile(source, 'utf8'), renamedFrom, options.definition);
109
+ if (source !== null && renamedImport !== null) {
110
+ await fs.writeFile(source, renamedImport, 'utf8');
111
+ options.log(` Updated the import in ${relative(options, source)}`);
112
+ }
113
+ else if (project.definitions[options.definition]?.instances[0].migrations !== undefined) {
114
+ options.log(` Update the import of its migrations in its view definition to ${relative(options, folder)}`);
115
+ }
116
+ }
117
+ let todos = 0;
118
+ /** Definitions without changes; counted rather than listed when all definitions are snapshotted. */
119
+ let upToDate = 0;
120
+ for (const definition of definitions) {
121
+ const view = project.definitions[definition].instances[0];
122
+ const renamedChain = renamedFolder === null ? null : chains.get(renamedFolder) ?? null;
123
+ const located = renamedFolder !== null && definition === options.definition
124
+ ? (view.migrations !== undefined && renamedChain !== null
125
+ ? { kind: 'imported', folder: renamedFolder, chain: renamedChain }
126
+ : { kind: 'unwired', folder: renamedFolder, chain: renamedChain })
127
+ : await locate(options, project, chains, definition, view);
128
+ if (located.kind === 'problem')
129
+ throw new Error(located.message);
130
+ const { folder, chain } = located;
131
+ if (chain === null) {
132
+ const baseline = project.projectDefinition(definition, 1);
133
+ await writeFile(path.join(folder, snapshotFile(1)), renderSnapshot(baseline, options.dtvImport));
134
+ await writeFile(path.join(folder, 'index.ts'), renderIndex({ baselineRevision: 1, migrationRevisions: [], dtvImport: options.dtvImport }));
135
+ options.log(`${definition}: first snapshot, revision 1, in ${relative(options, folder)}`);
136
+ (await wireUp(options, project, definition, folder)).forEach(options.log);
137
+ continue;
138
+ }
139
+ const latest = chain.latest;
140
+ const revision = latest.revision + 1;
141
+ const live = project.projectDefinition(definition, revision);
142
+ if (sameDefinition(live, latest) && options.manual === undefined) {
143
+ // Only worth a line of its own when asked for, or when it is wired up now.
144
+ if (options.definition === undefined && located.kind !== 'unwired') {
145
+ upToDate++;
146
+ continue;
147
+ }
148
+ options.log(`${definition}: up to date at revision ${latest.revision}`);
149
+ if (located.kind === 'unwired')
150
+ (await wireUp(options, project, definition, folder)).forEach(options.log);
151
+ continue;
152
+ }
153
+ const ops = generateOps(latest, live);
154
+ const open = ops.filter(op => op.todo).length + (options.manual === undefined ? 0 : 1);
155
+ todos += open;
156
+ await writeFile(path.join(folder, snapshotFile(revision)), renderSnapshot(live, options.dtvImport));
157
+ await writeFile(path.join(folder, migrationFile(revision)), renderMigration({
158
+ fromRevision: latest.revision,
159
+ toRevision: revision,
160
+ ops,
161
+ dtvImport: options.dtvImport,
162
+ manualReason: options.manual
163
+ }));
164
+ await writeFile(path.join(folder, 'index.ts'), renderIndex({
165
+ baselineRevision: chain.baseline.revision,
166
+ migrationRevisions: [...new Set([...(await migrationRevisions(folder)), revision])].sort((left, right) => left - right),
167
+ dtvImport: options.dtvImport
168
+ }));
169
+ const migration = relative(options, path.join(folder, migrationFile(revision)));
170
+ options.log(`${definition}: revision ${revision}, ${ops.length} operation(s)${open > 0 ? `, ${open} to decide in ${migration}` : ''}`);
171
+ if (located.kind === 'unwired')
172
+ (await wireUp(options, project, definition, folder)).forEach(options.log);
173
+ }
174
+ if (upToDate > 0)
175
+ options.log(`${upToDate} ${upToDate === 1 ? 'view' : 'views'} up to date`);
176
+ return { todos, problems: project.problems };
177
+ }
178
+ /**
179
+ * Whether every view's stored user data can be migrated to its definition as it is: each
180
+ * view uses its migrations, its latest snapshot is the definition as it is, and each
181
+ * migration covers its revision's changes and has no `todo` left.
182
+ */
183
+ export async function runCheck(options, project) {
184
+ const problems = [];
185
+ const warnings = [];
186
+ const chains = await loadChains(project);
187
+ const used = new Set();
188
+ problems.push(...project.problems);
189
+ for (const [definition, { instances: [view] }] of Object.entries(project.definitions)) {
190
+ const located = await locate(options, project, chains, definition, view);
191
+ if (located.kind === 'problem') {
192
+ problems.push(located.message);
193
+ continue;
194
+ }
195
+ used.add(located.folder);
196
+ if (located.kind === 'unwired') {
197
+ problems.push(located.chain === null
198
+ ? `${definition}: no snapshots; run \`dtv definitions snapshot ${definition}\``
199
+ : `${definition}: the view does not use its migrations in ${relative(options, located.folder)}`);
200
+ continue;
201
+ }
202
+ const { chain } = located;
203
+ for (const migration of chain.migrations) {
204
+ for (const problem of project.tooling.checkMigration(migration)) {
205
+ problems.push(`${definition}: ${problem.message}`);
206
+ }
207
+ }
208
+ if (chain.latest.definition !== definition) {
209
+ problems.push(`${definition}: the view uses the migrations of "${chain.latest.definition}"`);
210
+ continue;
211
+ }
212
+ const live = project.projectDefinition(definition, chain.latest.revision);
213
+ if (!sameDefinition(live, chain.latest)) {
214
+ problems.push(`${definition}: changed since revision ${chain.latest.revision}; run \`dtv definitions snapshot ${definition}\``);
215
+ }
216
+ }
217
+ for (const folder of chains.keys()) {
218
+ if (!used.has(folder)) {
219
+ warnings.push(`${relative(options, folder)}: migrations no view uses (renamed? \`dtv definitions snapshot <new id> --renamed-from ${path.basename(folder)}\`)`);
220
+ }
221
+ }
222
+ return { problems, warnings };
223
+ }
@@ -0,0 +1,8 @@
1
+ /*
2
+ * What `dtv definitions` works with. The views, their migrations and the functions projecting
3
+ * and checking them come from the project's own copy of @kronor/dtv, loaded at runtime; these
4
+ * types describe the shapes the CLI relies on (see framework/view-projection.ts and
5
+ * framework/view-migrations.ts in the package).
6
+ */
7
+ /** The name of folders holding a definition's snapshots and migrations: `dtv-migrations/<definition>`. */
8
+ export const MIGRATIONS_FOLDER = 'dtv-migrations';
@@ -0,0 +1,111 @@
1
+ import ts from 'typescript';
2
+ import { MIGRATIONS_FOLDER } from './types.js';
3
+ function camelCase(definition) {
4
+ return definition.replace(/[^A-Za-z0-9]+(.)?/g, (_, next) => (next ?? '').toUpperCase()).replace(/^[^A-Za-z_$]/, '_$&');
5
+ }
6
+ /** The local names `DSL` is imported under from `dtvImport`, and namespaces of `dtvImport`. */
7
+ function dslReceivers(sourceFile, dtvImport) {
8
+ const dsl = new Set();
9
+ const namespaces = new Set();
10
+ for (const statement of sourceFile.statements) {
11
+ if (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier))
12
+ continue;
13
+ if (statement.moduleSpecifier.text !== dtvImport)
14
+ continue;
15
+ const bindings = statement.importClause?.namedBindings;
16
+ if (bindings !== undefined && ts.isNamespaceImport(bindings))
17
+ namespaces.add(bindings.name.text);
18
+ if (bindings !== undefined && ts.isNamedImports(bindings)) {
19
+ for (const element of bindings.elements) {
20
+ if ((element.propertyName ?? element.name).text === 'DSL')
21
+ dsl.add(element.name.text);
22
+ }
23
+ }
24
+ }
25
+ return { dsl, namespaces };
26
+ }
27
+ /** The `DSL.view({ … })` calls of a module, with their object literals. */
28
+ function viewCalls(sourceFile, dtvImport) {
29
+ const { dsl, namespaces } = dslReceivers(sourceFile, dtvImport);
30
+ const calls = [];
31
+ const visit = (node) => {
32
+ if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && node.expression.name.text === 'view') {
33
+ const receiver = node.expression.expression;
34
+ const isDsl = (ts.isIdentifier(receiver) && dsl.has(receiver.text))
35
+ || (ts.isPropertyAccessExpression(receiver) && receiver.name.text === 'DSL' && ts.isIdentifier(receiver.expression) && namespaces.has(receiver.expression.text));
36
+ const [argument] = node.arguments;
37
+ if (isDsl && argument !== undefined && ts.isObjectLiteralExpression(argument))
38
+ calls.push(argument);
39
+ }
40
+ ts.forEachChild(node, visit);
41
+ };
42
+ visit(sourceFile);
43
+ return calls;
44
+ }
45
+ function propertyNamed(literal, name) {
46
+ return literal.properties.find(property => property.name !== undefined && (ts.isIdentifier(property.name) || ts.isStringLiteral(property.name)) && property.name.text === name);
47
+ }
48
+ function literalId(literal) {
49
+ const id = propertyNamed(literal, 'id');
50
+ if (id === undefined || !ts.isPropertyAssignment(id))
51
+ return null;
52
+ return ts.isStringLiteral(id.initializer) || ts.isNoSubstitutionTemplateLiteral(id.initializer) ? id.initializer.text : null;
53
+ }
54
+ function indentationAt(text, position) {
55
+ const lineStart = text.lastIndexOf('\n', position - 1) + 1;
56
+ return /^[ \t]*/.exec(text.slice(lineStart))?.[0] ?? '';
57
+ }
58
+ /**
59
+ * Wires the view of `definition` in the module `text` up with the migrations imported from
60
+ * `specifier`. The call is the one with the definition's literal id, or else the module's
61
+ * only `DSL.view` call.
62
+ */
63
+ export function wireMigrations(text, fileName, definition, specifier, dtvImport) {
64
+ const sourceFile = ts.createSourceFile(fileName, text, ts.ScriptTarget.Latest, true, fileName.endsWith('x') ? ts.ScriptKind.TSX : ts.ScriptKind.TS);
65
+ const calls = viewCalls(sourceFile, dtvImport);
66
+ const byId = calls.filter(call => literalId(call) === definition);
67
+ const call = byId.length === 1 ? byId[0] : calls.length === 1 ? calls[0] : undefined;
68
+ if (call === undefined) {
69
+ return { kind: 'unwirable', reason: calls.length === 0 ? 'no DSL.view call found in it' : `several DSL.view calls in it, none with the id '${definition}'` };
70
+ }
71
+ if (propertyNamed(call, 'migrations') !== undefined) {
72
+ return { kind: 'unwirable', reason: 'its DSL.view call has migrations already' };
73
+ }
74
+ // The name to import the migrations by; one the module does not use yet.
75
+ let name = `${camelCase(definition)}Migrations`;
76
+ for (let suffix = 2; new RegExp(`\\b${name}\\b`).test(text); suffix++)
77
+ name = `${camelCase(definition)}Migrations${suffix}`;
78
+ // The module's style, from its imports.
79
+ const imports = sourceFile.statements.filter(ts.isImportDeclaration);
80
+ const lastImport = imports[imports.length - 1];
81
+ const quote = lastImport !== undefined && lastImport.moduleSpecifier.getText(sourceFile).startsWith('"') ? '"' : "'";
82
+ const semicolon = lastImport === undefined || lastImport.getText(sourceFile).trimEnd().endsWith(';') ? ';' : '';
83
+ const edits = [];
84
+ // `migrations: name` after `id`, or as the first property.
85
+ const anchor = propertyNamed(call, 'id') ?? call.properties[0];
86
+ if (anchor === undefined) {
87
+ edits.push({ position: call.getStart(sourceFile) + 1, insert: ` migrations: ${name} ` });
88
+ }
89
+ else {
90
+ const indentation = indentationAt(text, anchor.getStart(sourceFile));
91
+ const after = anchor.getEnd();
92
+ const hasComma = text.slice(after).trimStart().startsWith(',');
93
+ edits.push(hasComma
94
+ ? { position: text.indexOf(',', after) + 1, insert: `\n${indentation}migrations: ${name},` }
95
+ : { position: after, insert: `,\n${indentation}migrations: ${name}` });
96
+ }
97
+ const importLine = `import ${name} from ${quote}${specifier}${quote}${semicolon}`;
98
+ edits.push(lastImport === undefined
99
+ ? { position: 0, insert: `${importLine}\n` }
100
+ : { position: lastImport.getEnd(), insert: `\n${importLine}` });
101
+ const wired = edits
102
+ .sort((left, right) => right.position - left.position)
103
+ .reduce((current, edit) => current.slice(0, edit.position) + edit.insert + current.slice(edit.position), text);
104
+ return { kind: 'wired', text: wired };
105
+ }
106
+ /** The module with imports of the folder `dtv-migrations/<from>` pointed at `dtv-migrations/<to>`; `null` when it has none. */
107
+ export function renameMigrationsImport(text, from, to) {
108
+ const pattern = new RegExp(`(['"])((?:[^'"\\n]*/)?${MIGRATIONS_FOLDER}/)${from.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(/index)?\\1`, 'g');
109
+ const renamed = text.replace(pattern, (_, quote, prefix, index) => `${quote}${prefix}${to}${index ?? ''}${quote}`);
110
+ return renamed === text ? null : renamed;
111
+ }
package/dist/cli/dtv.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { Command } from 'commander';
2
2
  import { registerTypegenCommand } from './commands/typegen.js';
3
3
  import { registerInitCommand } from './commands/init.js';
4
+ import { registerDefinitionsCommand } from './commands/definitions.js';
4
5
  const program = new Command();
5
6
  program
6
7
  .name('dtv')
@@ -8,4 +9,5 @@ program
8
9
  .version('0.0.0');
9
10
  registerTypegenCommand(program);
10
11
  registerInitCommand(program);
12
+ registerDefinitionsCommand(program);
11
13
  program.parse(process.argv);