@kronor/dtv 9.3.0 → 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.
- package/README.md +8 -2
- package/dist/cli/commands/definitions.js +76 -0
- package/dist/cli/config/loadConfig.js +69 -5
- package/dist/cli/definitions/discover.js +130 -0
- package/dist/cli/definitions/generate.js +258 -0
- package/dist/cli/definitions/loadProject.js +107 -0
- package/dist/cli/definitions/project.js +122 -0
- package/dist/cli/definitions/resolve.js +53 -0
- package/dist/cli/definitions/run.js +223 -0
- package/dist/cli/definitions/types.js +8 -0
- package/dist/cli/definitions/wire.js +111 -0
- package/dist/cli/dtv.js +2 -0
- package/dist/cli/typegen/runTypegen.js +4 -3
- package/dist/index.es.js +14103 -13451
- package/dist/types/components/UserPreferencesPanel.d.ts +2 -1
- package/dist/types/dsl/index.d.ts +1 -0
- package/dist/types/dsl/migrations.d.ts +114 -0
- package/dist/types/framework/decoder.d.ts +61 -0
- package/dist/types/framework/filter-form-state.d.ts +18 -2
- package/dist/types/framework/filter-sharing.d.ts +21 -9
- package/dist/types/framework/runtime.d.ts +2 -0
- package/dist/types/framework/saved-filters.d.ts +10 -14
- package/dist/types/framework/state/app-state.d.ts +8 -0
- package/dist/types/framework/useUserDataManager.d.ts +3 -0
- package/dist/types/framework/user-data-errors.d.ts +8 -0
- package/dist/types/framework/user-data-manager.d.ts +6 -1
- package/dist/types/framework/user-data-undecoded.d.ts +86 -0
- package/dist/types/framework/user-data.d.ts +120 -33
- package/dist/types/framework/user-data.migrations.d.ts +9 -8
- package/dist/types/framework/view-migrations.d.ts +112 -0
- package/dist/types/framework/view-parser.d.ts +2 -1
- package/dist/types/framework/view-projection.d.ts +52 -0
- package/dist/types/framework/view.d.ts +7 -0
- package/dist/types/lib/index.d.ts +4 -0
- package/dist/types/typegen/index.d.ts +26 -4
- package/docs/typegen.md +12 -0
- package/docs/view-migrations.md +182 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -80,7 +80,7 @@ React and ReactDOM 19 are peer dependencies; ensure they are installed in the ho
|
|
|
80
80
|
- Data is fetched via GraphQL using `graphql-request` (see `src/framework/data.ts`).
|
|
81
81
|
- Views define their own GraphQL queries and filter schemas.
|
|
82
82
|
- Filter expressions are serialized/deserialized using helpers in `src/framework/filters.ts`.
|
|
83
|
-
- Unified URL Filter Param: Both share links and persistence use a single base64 URL-safe encoded parameter `dtv-filter-state`. Enable syncing by passing `syncFilterStateToUrl: true` to `dtv.renderTableView` (or `?sync-filter-state-to-url=true` in dev). The param is updated only when filters are applied (not on every change). When disabled, a one-off link is consumed (param removed after load).
|
|
83
|
+
- Unified URL Filter Param: Both share links and persistence use a single base64 URL-safe encoded parameter `dtv-filter-state`. Enable syncing by passing `syncFilterStateToUrl: true` to `dtv.renderTableView` (or `?sync-filter-state-to-url=true` in dev). The param is updated only when filters are applied (not on every change). It names the view the filter state belongs to, so a shared link opens that view. When disabled, a one-off link is consumed (param removed after load).
|
|
84
84
|
|
|
85
85
|
## Features
|
|
86
86
|
|
|
@@ -89,7 +89,7 @@ Core runtime capabilities:
|
|
|
89
89
|
- Schema-driven column + filter definitions (JSON or TSX view formats).
|
|
90
90
|
- AI assistant to generate filters (`AIAssistantForm`).
|
|
91
91
|
- Cursor-based pagination with Previous / Next navigation.
|
|
92
|
-
- Header-click ordering backed by GraphQL `order_by`, with one removable sortable header at a time.
|
|
92
|
+
- Header-click ordering backed by GraphQL `order_by`, with one removable sortable header at a time. The ordering is kept in the user's data per view, and the view starts from it; users can turn that off per view under preferences ("Persist sorting for this view").
|
|
93
93
|
- Adjustable page size via "Rows per page" selector (10, 20, 50, 100). Changing the page size resets pagination and refetches from the first page.
|
|
94
94
|
- Saved filters (local persistence + shareable URL encoding).
|
|
95
95
|
- Optional CSV export of current page rows.
|
|
@@ -139,6 +139,12 @@ DTV ships a CLI command for generating TypeScript types from a Hasura GraphQL sc
|
|
|
139
139
|
- Once a view has its generated row type, its columns and filters are checked against it —
|
|
140
140
|
see `docs/api/row-typed-views.md`
|
|
141
141
|
|
|
142
|
+
## View Migrations (CLI)
|
|
143
|
+
|
|
144
|
+
Users' saved filters and settings are stored against a view's definition. `dtv definitions snapshot`
|
|
145
|
+
snapshots definitions and writes the migrations their stored data needs when they change;
|
|
146
|
+
`dtv definitions check` fails CI when a change has none. See `docs/view-migrations.md`.
|
|
147
|
+
|
|
142
148
|
## Release Process
|
|
143
149
|
|
|
144
150
|
Releases are driven from the monorepo root, one package at a time. See the
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { loadDefinitionsConfig } from '../config/loadConfig.js';
|
|
2
|
+
import { loadProject } from '../definitions/loadProject.js';
|
|
3
|
+
import { runCheck, runMigrate } from '../definitions/run.js';
|
|
4
|
+
function withCommonOptions(command) {
|
|
5
|
+
return command
|
|
6
|
+
.option('-c, --config <path>', 'Path to dtv.config.ts (its `scan` finds the views, its `definitions` configures this command)', 'dtv.config.ts')
|
|
7
|
+
.option('--vite-config <path>', 'Vite config to load the views with, over definitions.viteConfig (default: vite.config.* in the working directory)')
|
|
8
|
+
.option('-d, --migrations-dir <path>', 'Where migrations go for views whose module is not found, over definitions.migrationsDir (default: dtv-migrations)');
|
|
9
|
+
}
|
|
10
|
+
async function withProject(opts, run) {
|
|
11
|
+
const config = await loadDefinitionsConfig(opts.config);
|
|
12
|
+
const project = await loadProject({ cwd: process.cwd(), config, viteConfig: opts.viteConfig });
|
|
13
|
+
try {
|
|
14
|
+
return await run(project, {
|
|
15
|
+
cwd: process.cwd(),
|
|
16
|
+
migrationsDir: opts.migrationsDir ?? config.definitions.migrationsDir ?? 'dtv-migrations',
|
|
17
|
+
dtvImport: config.scan.dtvImport,
|
|
18
|
+
log: line => console.log(line)
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
finally {
|
|
22
|
+
await project.close();
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
function fail(e) {
|
|
26
|
+
console.error(e instanceof Error ? e.message : String(e));
|
|
27
|
+
process.exitCode = 1;
|
|
28
|
+
}
|
|
29
|
+
export function registerDefinitionsCommand(program) {
|
|
30
|
+
const definitions = program
|
|
31
|
+
.command('definitions')
|
|
32
|
+
.description('Snapshots of view definitions, and migrations of the user data stored for them');
|
|
33
|
+
withCommonOptions(definitions
|
|
34
|
+
.command('snapshot')
|
|
35
|
+
.description('Snapshot changed view definitions and write the migrations of their user data')
|
|
36
|
+
.argument('[definition]', 'Only this definition')
|
|
37
|
+
.option('--manual <reason>', 'Make a revision without a change of the definition, e.g. for renamed enum values')
|
|
38
|
+
.option('--renamed-from <definition>', 'The definition was renamed from this id: take over its migrations'))
|
|
39
|
+
.action(async (definition, opts) => {
|
|
40
|
+
try {
|
|
41
|
+
const { todos, problems } = await withProject(opts, (project, options) => runMigrate({
|
|
42
|
+
...options,
|
|
43
|
+
definition,
|
|
44
|
+
manual: opts.manual,
|
|
45
|
+
renamedFrom: opts.renamedFrom
|
|
46
|
+
}, project));
|
|
47
|
+
if (todos > 0) {
|
|
48
|
+
console.log(`\n${todos} decision(s) left as m.todo(…); replace them, then run \`dtv definitions check\`.`);
|
|
49
|
+
}
|
|
50
|
+
if (problems.length > 0) {
|
|
51
|
+
console.error(`\nViews left out:\n${problems.map(problem => ` ${problem}`).join('\n')}`);
|
|
52
|
+
process.exitCode = 1;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
catch (e) {
|
|
56
|
+
fail(e);
|
|
57
|
+
}
|
|
58
|
+
});
|
|
59
|
+
withCommonOptions(definitions
|
|
60
|
+
.command('check')
|
|
61
|
+
.description('Fail when a view definition changed without a migration, or a migration is incomplete'))
|
|
62
|
+
.action(async (opts) => {
|
|
63
|
+
try {
|
|
64
|
+
const report = await withProject(opts, (project, options) => runCheck(options, project));
|
|
65
|
+
report.warnings.forEach(warning => console.warn(`warning: ${warning}`));
|
|
66
|
+
report.problems.forEach(problem => console.error(problem));
|
|
67
|
+
if (report.problems.length > 0)
|
|
68
|
+
process.exitCode = 1;
|
|
69
|
+
else
|
|
70
|
+
console.log('View migrations are complete.');
|
|
71
|
+
}
|
|
72
|
+
catch (e) {
|
|
73
|
+
fail(e);
|
|
74
|
+
}
|
|
75
|
+
});
|
|
76
|
+
}
|
|
@@ -10,8 +10,8 @@ function assertString(value, context) {
|
|
|
10
10
|
throw new Error(`${context} must be a non-empty string`);
|
|
11
11
|
}
|
|
12
12
|
}
|
|
13
|
-
|
|
14
|
-
|
|
13
|
+
/** The object a config module exports. */
|
|
14
|
+
async function importConfig(abs) {
|
|
15
15
|
const cfg = await (async () => {
|
|
16
16
|
const ext = path.extname(abs).toLowerCase();
|
|
17
17
|
const url = pathToFileURL(abs).href;
|
|
@@ -64,12 +64,22 @@ export async function loadConfig(configPath) {
|
|
|
64
64
|
if (!isRecord(cfg)) {
|
|
65
65
|
throw new Error('Config must export a plain object (default export recommended)');
|
|
66
66
|
}
|
|
67
|
-
|
|
67
|
+
return cfg;
|
|
68
|
+
}
|
|
69
|
+
function validateSchema(schema) {
|
|
70
|
+
if (!isRecord(schema))
|
|
68
71
|
throw new Error('Config.schema is required');
|
|
69
|
-
assertString(
|
|
70
|
-
if (
|
|
72
|
+
assertString(schema.endpoint, 'Config.schema.endpoint');
|
|
73
|
+
if (schema.headers !== undefined && !isRecord(schema.headers)) {
|
|
71
74
|
throw new Error('Config.schema.headers must be an object when provided');
|
|
72
75
|
}
|
|
76
|
+
return schema;
|
|
77
|
+
}
|
|
78
|
+
/** The schema typegen reads; a function giving it is called now. */
|
|
79
|
+
export async function resolveSchema(config) {
|
|
80
|
+
return validateSchema(typeof config.schema === 'function' ? await config.schema() : config.schema);
|
|
81
|
+
}
|
|
82
|
+
function validateScan(cfg) {
|
|
73
83
|
if (!isRecord(cfg.scan))
|
|
74
84
|
throw new Error('Config.scan is required');
|
|
75
85
|
if (!Array.isArray(cfg.scan.include) || cfg.scan.include.length === 0) {
|
|
@@ -80,6 +90,60 @@ export async function loadConfig(configPath) {
|
|
|
80
90
|
}
|
|
81
91
|
if (cfg.scan.dtvImport !== undefined)
|
|
82
92
|
assertString(cfg.scan.dtvImport, 'Config.scan.dtvImport');
|
|
93
|
+
}
|
|
94
|
+
const absolute = (configPath) => path.isAbsolute(configPath) ? configPath : path.resolve(process.cwd(), configPath);
|
|
95
|
+
/**
|
|
96
|
+
* What `dtv definitions` needs of the config: how to find the views, and its own section. Without
|
|
97
|
+
* a config file, all TS sources are scanned for views.
|
|
98
|
+
*/
|
|
99
|
+
export async function loadDefinitionsConfig(configPath) {
|
|
100
|
+
const abs = absolute(configPath);
|
|
101
|
+
const root = path.dirname(abs);
|
|
102
|
+
const exists = await fs.access(abs).then(() => true, () => false);
|
|
103
|
+
if (!exists) {
|
|
104
|
+
return { scan: { include: ['**/*.{ts,tsx}'], exclude: [], dtvImport: '@kronor/dtv' }, definitions: {}, root };
|
|
105
|
+
}
|
|
106
|
+
let cfg;
|
|
107
|
+
try {
|
|
108
|
+
cfg = await importConfig(abs);
|
|
109
|
+
}
|
|
110
|
+
catch (err) {
|
|
111
|
+
throw new Error(`Failed to load ${configPath}: ${err instanceof Error ? err.message : String(err)}\n` +
|
|
112
|
+
'If it fails for want of what only typegen needs (e.g. a secret for the schema), make `schema` a function: ' +
|
|
113
|
+
'it is called by `dtv typegen` only.');
|
|
114
|
+
}
|
|
115
|
+
validateScan(cfg);
|
|
116
|
+
const scan = cfg.scan;
|
|
117
|
+
const definitions = cfg.definitions === undefined ? {} : cfg.definitions;
|
|
118
|
+
if (!isRecord(definitions))
|
|
119
|
+
throw new Error('Config.definitions must be an object when provided');
|
|
120
|
+
if (definitions.factories !== undefined) {
|
|
121
|
+
if (!isRecord(definitions.factories))
|
|
122
|
+
throw new Error('Config.definitions.factories must be an object when provided');
|
|
123
|
+
for (const [name, factory] of Object.entries(definitions.factories)) {
|
|
124
|
+
if (!isRecord(factory))
|
|
125
|
+
throw new Error(`Config.definitions.factories["${name}"] must be an object`);
|
|
126
|
+
if (factory.definition !== undefined)
|
|
127
|
+
assertString(factory.definition, `Config.definitions.factories["${name}"].definition`);
|
|
128
|
+
if (factory.args !== undefined && !Array.isArray(factory.args))
|
|
129
|
+
throw new Error(`Config.definitions.factories["${name}"].args must be an array`);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
if (definitions.migrationsDir !== undefined)
|
|
133
|
+
assertString(definitions.migrationsDir, 'Config.definitions.migrationsDir');
|
|
134
|
+
if (definitions.viteConfig !== undefined)
|
|
135
|
+
assertString(definitions.viteConfig, 'Config.definitions.viteConfig');
|
|
136
|
+
return {
|
|
137
|
+
scan: { include: scan.include, exclude: scan.exclude ?? [], dtvImport: scan.dtvImport ?? '@kronor/dtv' },
|
|
138
|
+
definitions: definitions,
|
|
139
|
+
root
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
export async function loadConfig(configPath) {
|
|
143
|
+
const cfg = await importConfig(absolute(configPath));
|
|
144
|
+
if (typeof cfg.schema !== 'function')
|
|
145
|
+
validateSchema(cfg.schema);
|
|
146
|
+
validateScan(cfg);
|
|
83
147
|
if (!isRecord(cfg.output))
|
|
84
148
|
throw new Error('Config.output is required');
|
|
85
149
|
assertString(cfg.output.fileNamePattern, 'Config.output.fileNamePattern');
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import { createRequire } from 'node:module';
|
|
2
|
+
import * as fs from 'node:fs/promises';
|
|
3
|
+
import * as path from 'node:path';
|
|
4
|
+
import fg from 'fast-glob';
|
|
5
|
+
import bundledTs from 'typescript';
|
|
6
|
+
import { findViewsInFile } from '../typegen/runTypegen.js';
|
|
7
|
+
import { MIGRATIONS_FOLDER } from './types.js';
|
|
8
|
+
const IGNORED = ['**/node_modules/**', '**/dist/**', '**/build/**', '**/vendor/**', '**/.git/**', `**/${MIGRATIONS_FOLDER}/**`];
|
|
9
|
+
/** The modules calling `DSL.view`, literal id or not. */
|
|
10
|
+
export async function scanViewModules(cwd, include, exclude, dtvImport) {
|
|
11
|
+
const files = await fg(include, { cwd, ignore: [...IGNORED, ...exclude], absolute: true, onlyFiles: true });
|
|
12
|
+
const modules = [];
|
|
13
|
+
for (const file of files) {
|
|
14
|
+
if (!/\.tsx?$/.test(file) || /\.(test|spec)\.tsx?$/.test(file) || file.endsWith('.d.ts'))
|
|
15
|
+
continue;
|
|
16
|
+
const text = await fs.readFile(file, 'utf8');
|
|
17
|
+
if (!text.includes(dtvImport))
|
|
18
|
+
continue;
|
|
19
|
+
let unidentified = 0;
|
|
20
|
+
const identified = findViewsInFile(text, file, dtvImport, undefined, () => { unidentified++; }).length;
|
|
21
|
+
if (identified + unidentified > 0)
|
|
22
|
+
modules.push(path.normalize(file));
|
|
23
|
+
}
|
|
24
|
+
return modules.sort();
|
|
25
|
+
}
|
|
26
|
+
/** The project's own TypeScript, so that its tsconfig means what it means to it. */
|
|
27
|
+
function projectTypeScript(cwd) {
|
|
28
|
+
try {
|
|
29
|
+
return createRequire(path.join(cwd, 'package.json'))('typescript');
|
|
30
|
+
}
|
|
31
|
+
catch {
|
|
32
|
+
return bundledTs;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
const VIEW_TYPES = new Set(['View', 'CollectionView', 'FunctionView']);
|
|
36
|
+
export function discoverViews(cwd, modules) {
|
|
37
|
+
const ts = projectTypeScript(cwd);
|
|
38
|
+
const configFile = ts.findConfigFile(cwd, ts.sys.fileExists, 'tsconfig.json');
|
|
39
|
+
const options = configFile === undefined
|
|
40
|
+
? { jsx: ts.JsxEmit.Preserve, allowJs: false, skipLibCheck: true }
|
|
41
|
+
: ts.parseJsonConfigFileContent(ts.readConfigFile(configFile, ts.sys.readFile).config, ts.sys, path.dirname(configFile)).options;
|
|
42
|
+
const program = ts.createProgram(modules, { ...options, noEmit: true, skipLibCheck: true });
|
|
43
|
+
const checker = program.getTypeChecker();
|
|
44
|
+
const isView = (type) => {
|
|
45
|
+
const name = type.aliasSymbol?.name ?? type.getSymbol()?.name ?? checker.typeToString(type);
|
|
46
|
+
return VIEW_TYPES.has(name);
|
|
47
|
+
};
|
|
48
|
+
/** A value of `type`; `contrasting` fills in optionals and lists where `minimal` leaves them out. */
|
|
49
|
+
const valueOf = (type, contrasting, depth = 0) => {
|
|
50
|
+
if (depth > 8)
|
|
51
|
+
return undefined;
|
|
52
|
+
const flags = type.flags;
|
|
53
|
+
if (flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown | ts.TypeFlags.TypeParameter))
|
|
54
|
+
return undefined;
|
|
55
|
+
if (type.isUnion()) {
|
|
56
|
+
const members = type.types.filter(member => !(member.flags & (ts.TypeFlags.Undefined | ts.TypeFlags.Null | ts.TypeFlags.Void)));
|
|
57
|
+
if (members.length > 0 && members.every(member => member.flags & ts.TypeFlags.BooleanLiteral))
|
|
58
|
+
return contrasting;
|
|
59
|
+
if (members.length === 0)
|
|
60
|
+
return undefined;
|
|
61
|
+
return valueOf(contrasting ? members[members.length - 1] : members[0], contrasting, depth + 1);
|
|
62
|
+
}
|
|
63
|
+
if (type.isStringLiteral())
|
|
64
|
+
return type.value;
|
|
65
|
+
if (type.isNumberLiteral())
|
|
66
|
+
return type.value;
|
|
67
|
+
if (flags & ts.TypeFlags.BooleanLiteral)
|
|
68
|
+
return checker.typeToString(type) === 'true';
|
|
69
|
+
if (flags & ts.TypeFlags.StringLike)
|
|
70
|
+
return contrasting ? 'x1' : '';
|
|
71
|
+
if (flags & ts.TypeFlags.NumberLike)
|
|
72
|
+
return contrasting ? 1 : 0;
|
|
73
|
+
if (flags & ts.TypeFlags.BooleanLike)
|
|
74
|
+
return contrasting;
|
|
75
|
+
if (flags & ts.TypeFlags.BigIntLike)
|
|
76
|
+
return BigInt(0);
|
|
77
|
+
if (type.getCallSignatures().length > 0)
|
|
78
|
+
return () => undefined;
|
|
79
|
+
if (checker.isArrayType(type) || checker.isTupleType(type)) {
|
|
80
|
+
const element = checker.getTypeArguments(type)[0];
|
|
81
|
+
return contrasting && element !== undefined ? [valueOf(element, contrasting, depth + 1)] : [];
|
|
82
|
+
}
|
|
83
|
+
if (flags & ts.TypeFlags.Object) {
|
|
84
|
+
return Object.fromEntries(checker.getPropertiesOfType(type)
|
|
85
|
+
.filter(property => contrasting || !(property.flags & ts.SymbolFlags.Optional))
|
|
86
|
+
.map(property => [property.name, valueOf(checker.getTypeOfSymbol(property), contrasting, depth + 1)]));
|
|
87
|
+
}
|
|
88
|
+
return undefined;
|
|
89
|
+
};
|
|
90
|
+
const exports = [];
|
|
91
|
+
const unreachable = [];
|
|
92
|
+
for (const file of modules) {
|
|
93
|
+
const sourceFile = program.getSourceFile(file);
|
|
94
|
+
const moduleSymbol = sourceFile === undefined ? undefined : checker.getSymbolAtLocation(sourceFile);
|
|
95
|
+
if (moduleSymbol === undefined) {
|
|
96
|
+
unreachable.push(file);
|
|
97
|
+
continue;
|
|
98
|
+
}
|
|
99
|
+
const found = exports.length;
|
|
100
|
+
for (const exported of checker.getExportsOfModule(moduleSymbol)) {
|
|
101
|
+
const type = checker.getTypeOfSymbol(exported);
|
|
102
|
+
const signatures = type.getCallSignatures();
|
|
103
|
+
if (signatures.length === 0) {
|
|
104
|
+
if (isView(type))
|
|
105
|
+
exports.push({ kind: 'constant', file, exportName: exported.name });
|
|
106
|
+
continue;
|
|
107
|
+
}
|
|
108
|
+
const signature = signatures[signatures.length - 1];
|
|
109
|
+
if (!isView(signature.getReturnType()))
|
|
110
|
+
continue;
|
|
111
|
+
const parameters = signature.getParameters().map(parameter => {
|
|
112
|
+
const declaration = parameter.valueDeclaration;
|
|
113
|
+
const optional = declaration !== undefined && ts.isParameter(declaration) && (declaration.questionToken !== undefined || declaration.initializer !== undefined);
|
|
114
|
+
return { type: checker.getTypeOfSymbolAtLocation(parameter, declaration ?? sourceFile), optional };
|
|
115
|
+
});
|
|
116
|
+
exports.push({
|
|
117
|
+
kind: 'factory',
|
|
118
|
+
file,
|
|
119
|
+
exportName: exported.name,
|
|
120
|
+
args: {
|
|
121
|
+
minimal: () => parameters.map(parameter => parameter.optional ? undefined : valueOf(parameter.type, false)),
|
|
122
|
+
contrasting: () => parameters.map(parameter => valueOf(parameter.type, true))
|
|
123
|
+
}
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
if (exports.length === found)
|
|
127
|
+
unreachable.push(file);
|
|
128
|
+
}
|
|
129
|
+
return { exports, unreachable };
|
|
130
|
+
}
|
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
export function deepEqual(left, right) {
|
|
2
|
+
if (left === right)
|
|
3
|
+
return true;
|
|
4
|
+
if (typeof left !== 'object' || typeof right !== 'object' || left === null || right === null)
|
|
5
|
+
return false;
|
|
6
|
+
if (Array.isArray(left) !== Array.isArray(right))
|
|
7
|
+
return false;
|
|
8
|
+
const leftKeys = Object.keys(left);
|
|
9
|
+
const rightKeys = Object.keys(right);
|
|
10
|
+
return leftKeys.length === rightKeys.length
|
|
11
|
+
&& leftKeys.every(key => Object.prototype.hasOwnProperty.call(right, key)
|
|
12
|
+
&& deepEqual(left[key], right[key]));
|
|
13
|
+
}
|
|
14
|
+
export function quote(value) {
|
|
15
|
+
return `'${value.replace(/\\/g, '\\\\').replace(/'/g, "\\'").replace(/\n/g, '\\n')}'`;
|
|
16
|
+
}
|
|
17
|
+
const op = (code, comments = []) => ({ code, comments, todo: false });
|
|
18
|
+
const todo = (subject, message, comments) => ({ code: `m.todo(${quote(subject)}, ${quote(message)})`, comments, todo: true });
|
|
19
|
+
function compareControls(from, to, change) {
|
|
20
|
+
if (from.type !== to.type) {
|
|
21
|
+
change.structure ??= `its control changed from ${from.type} to ${to.type}`;
|
|
22
|
+
return;
|
|
23
|
+
}
|
|
24
|
+
if (from.type === 'autocomplete' && to.type === 'autocomplete' && from.multiple !== to.multiple) {
|
|
25
|
+
change.structure ??= `its autocomplete ${to.multiple ? 'takes several values now' : 'takes one value now'}`;
|
|
26
|
+
}
|
|
27
|
+
if (from.type === 'customOperator' && to.type === 'customOperator') {
|
|
28
|
+
if (!deepEqual(from.operators, to.operators))
|
|
29
|
+
change.operatorsChanged = true;
|
|
30
|
+
compareControls(from.valueControl, to.valueControl, change);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
function compareFilters(from, to, change) {
|
|
34
|
+
if (from.kind !== to.kind) {
|
|
35
|
+
change.structure ??= `it changed from '${from.kind}' to '${to.kind}'`;
|
|
36
|
+
return;
|
|
37
|
+
}
|
|
38
|
+
if (from.kind === 'leaf' && to.kind === 'leaf') {
|
|
39
|
+
if (from.cmp !== to.cmp)
|
|
40
|
+
change.meaning.push(`its comparison changed from ${from.cmp} to ${to.cmp}`);
|
|
41
|
+
if (!deepEqual(from.field, to.field))
|
|
42
|
+
change.meaning.push(`its field changed from ${JSON.stringify(from.field)} to ${JSON.stringify(to.field)}`);
|
|
43
|
+
compareControls(from.control, to.control, change);
|
|
44
|
+
}
|
|
45
|
+
else if (from.kind === 'not' && to.kind === 'not') {
|
|
46
|
+
compareFilters(from.child, to.child, change);
|
|
47
|
+
}
|
|
48
|
+
else if ((from.kind === 'and' || from.kind === 'or') && (to.kind === 'and' || to.kind === 'or')) {
|
|
49
|
+
if (from.children.length !== to.children.length) {
|
|
50
|
+
change.structure ??= `it has ${to.children.length} parts instead of ${from.children.length}`;
|
|
51
|
+
return;
|
|
52
|
+
}
|
|
53
|
+
from.children.forEach((child, index) => compareFilters(child, to.children[index], change));
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
function operatorsOf(filter) {
|
|
57
|
+
switch (filter.kind) {
|
|
58
|
+
case 'leaf':
|
|
59
|
+
return filter.control.type === 'customOperator' ? controlOperators(filter.control) : [];
|
|
60
|
+
case 'not':
|
|
61
|
+
return operatorsOf(filter.child);
|
|
62
|
+
case 'and':
|
|
63
|
+
case 'or':
|
|
64
|
+
return filter.children.flatMap(operatorsOf);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
function controlOperators(control) {
|
|
68
|
+
return control.type === 'customOperator' ? [...control.operators, ...controlOperators(control.valueControl)] : [];
|
|
69
|
+
}
|
|
70
|
+
/* The operations of a migration */
|
|
71
|
+
/** The operations a migration from `from` to `to` needs, as far as the diff can tell. */
|
|
72
|
+
export function generateOps(from, to) {
|
|
73
|
+
const ops = [];
|
|
74
|
+
const removedFilters = Object.keys(from.filters).filter(id => to.filters[id] === undefined);
|
|
75
|
+
const addedFilters = Object.keys(to.filters).filter(id => from.filters[id] === undefined);
|
|
76
|
+
const sameStructure = (left, right) => {
|
|
77
|
+
const change = { structure: null, operatorsChanged: false, meaning: [] };
|
|
78
|
+
compareFilters(left, right, change);
|
|
79
|
+
return change.structure === null;
|
|
80
|
+
};
|
|
81
|
+
const identical = (removed) => addedFilters.filter(added => deepEqual(from.filters[removed], to.filters[added]));
|
|
82
|
+
// Renames first: one removed and one added filter with the same definition, matching
|
|
83
|
+
// nothing else. What is stored for the one fits the other and means the same.
|
|
84
|
+
const renames = new Map();
|
|
85
|
+
for (const removed of removedFilters) {
|
|
86
|
+
const candidates = identical(removed);
|
|
87
|
+
if (candidates.length === 1 && removedFilters.filter(other => identical(other).includes(candidates[0])).length === 1) {
|
|
88
|
+
renames.set(removed, candidates[0]);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
const renamedTo = new Set(renames.values());
|
|
92
|
+
for (const removed of removedFilters) {
|
|
93
|
+
const target = renames.get(removed);
|
|
94
|
+
if (target !== undefined) {
|
|
95
|
+
ops.push(op(`m.renameFilter(${quote(removed)}, ${quote(target)})`, [
|
|
96
|
+
`"${removed}" was removed and "${target}" added, with the same definition.`,
|
|
97
|
+
`If "${target}" is another filter that only looks the same: m.drop(${quote(removed)})`
|
|
98
|
+
]));
|
|
99
|
+
continue;
|
|
100
|
+
}
|
|
101
|
+
const unpaired = addedFilters.filter(added => !renamedTo.has(added));
|
|
102
|
+
// Several filters with the same definition: which is which is not ours to guess.
|
|
103
|
+
const candidates = identical(removed).filter(added => !renamedTo.has(added));
|
|
104
|
+
if (candidates.length > 0) {
|
|
105
|
+
ops.push(todo(removed, `renamed to ${candidates.map(added => `"${added}"`).join(' or ')}?`, [
|
|
106
|
+
`"${removed}" was removed, and ${candidates.map(added => `"${added}"`).join(', ')} added with the same definition.`,
|
|
107
|
+
...candidates.map(added => `Renamed: m.renameFilter(${quote(removed)}, ${quote(added)})`),
|
|
108
|
+
`Removed: m.drop(${quote(removed)})`
|
|
109
|
+
]));
|
|
110
|
+
continue;
|
|
111
|
+
}
|
|
112
|
+
// Stored state of `removed` would fit these; they may be it, renamed and changed.
|
|
113
|
+
const similar = unpaired.filter(added => sameStructure(from.filters[removed], to.filters[added]));
|
|
114
|
+
if (similar.length === 0) {
|
|
115
|
+
ops.push(op(`m.drop(${quote(removed)})`));
|
|
116
|
+
continue;
|
|
117
|
+
}
|
|
118
|
+
ops.push(todo(removed, `renamed to ${similar.map(added => `"${added}"`).join(' or ')}, and changed?`, [
|
|
119
|
+
`"${removed}" was removed, and ${similar.map(added => `"${added}"`).join(', ')} added with a state its stored state fits.`,
|
|
120
|
+
...similar.map(added => `Renamed, same meaning: m.custom(${quote(removed)}, ${quote(added)}, state => state)`),
|
|
121
|
+
`Removed: m.drop(${quote(removed)})`
|
|
122
|
+
]));
|
|
123
|
+
}
|
|
124
|
+
for (const filterId of Object.keys(from.filters)) {
|
|
125
|
+
const toFilter = to.filters[filterId];
|
|
126
|
+
if (toFilter === undefined || deepEqual(from.filters[filterId], toFilter))
|
|
127
|
+
continue;
|
|
128
|
+
const change = { structure: null, operatorsChanged: false, meaning: [] };
|
|
129
|
+
compareFilters(from.filters[filterId], toFilter, change);
|
|
130
|
+
if (change.structure !== null) {
|
|
131
|
+
ops.push(op(`m.reset(${quote(filterId)})`, [
|
|
132
|
+
`Stored state of "${filterId}" no longer fits: ${change.structure}.`,
|
|
133
|
+
`To carry it over instead: m.custom(${quote(filterId)}, ${quote(filterId)}, state => …)`
|
|
134
|
+
]));
|
|
135
|
+
continue;
|
|
136
|
+
}
|
|
137
|
+
const targetOperators = [...new Set(operatorsOf(toFilter))];
|
|
138
|
+
const removedOperators = [...new Set(operatorsOf(from.filters[filterId]))].filter(operator => !targetOperators.includes(operator));
|
|
139
|
+
const operatorMap = `m.mapOperators(${quote(filterId)}, { ${removedOperators.map(operator => `${quote(operator)}: …`).join(', ')} })`;
|
|
140
|
+
if (change.meaning.length === 0 && removedOperators.length === 0) {
|
|
141
|
+
// Operators were only added: every stored state still fits.
|
|
142
|
+
ops.push(op(`m.mapOperators(${quote(filterId)}, {})`));
|
|
143
|
+
}
|
|
144
|
+
else if (change.meaning.length === 0) {
|
|
145
|
+
ops.push(todo(filterId, `map the operators it no longer offers: ${removedOperators.join(', ')}`, [
|
|
146
|
+
`Map each to one of ${targetOperators.map(quote).join(', ')}, or to null to clear it:`,
|
|
147
|
+
operatorMap
|
|
148
|
+
]));
|
|
149
|
+
}
|
|
150
|
+
else {
|
|
151
|
+
ops.push(todo(filterId, `${change.meaning.join(' and ')}; does what is stored still mean the same?`, [
|
|
152
|
+
`"${filterId}": ${change.meaning.join(' and ')}.`,
|
|
153
|
+
...(removedOperators.length > 0
|
|
154
|
+
? [`Its operators ${removedOperators.join(', ')} are gone too: m.custom(${quote(filterId)}, ${quote(filterId)}, state => …)`]
|
|
155
|
+
: [`Same meaning: m.keep(${quote(filterId)}, { because: '…' })`]),
|
|
156
|
+
`Otherwise: m.reset(${quote(filterId)})`
|
|
157
|
+
]));
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
const removedColumns = Object.keys(from.columns).filter(id => to.columns[id] === undefined);
|
|
161
|
+
const addedColumns = Object.keys(to.columns).filter(id => from.columns[id] === undefined);
|
|
162
|
+
for (const removed of removedColumns) {
|
|
163
|
+
if (addedColumns.length === 0) {
|
|
164
|
+
ops.push(op(`m.dropColumn(${quote(removed)})`));
|
|
165
|
+
continue;
|
|
166
|
+
}
|
|
167
|
+
ops.push(todo(removed, `renamed to ${addedColumns.map(added => `"${added}"`).join(' or ')}?`, [
|
|
168
|
+
`Column "${removed}" was removed and ${addedColumns.map(added => `"${added}"`).join(', ')} added.`,
|
|
169
|
+
...addedColumns.map(added => `Renamed: m.renameColumn(${quote(removed)}, ${quote(added)})`),
|
|
170
|
+
`Removed: m.dropColumn(${quote(removed)})`
|
|
171
|
+
]));
|
|
172
|
+
}
|
|
173
|
+
for (const columnId of Object.keys(from.columns)) {
|
|
174
|
+
const toColumn = to.columns[columnId];
|
|
175
|
+
if (toColumn !== undefined && toColumn.orderBy !== from.columns[columnId].orderBy) {
|
|
176
|
+
ops.push(op(`m.resetSort(${quote(columnId)})`, [`"${columnId}" sorts by ${toColumn.orderBy ?? 'nothing'} instead of ${from.columns[columnId].orderBy ?? 'nothing'}.`]));
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
return ops;
|
|
180
|
+
}
|
|
181
|
+
/* Files */
|
|
182
|
+
const GENERATED = '// Generated by `dtv definitions snapshot`.';
|
|
183
|
+
function isIdentifier(key) {
|
|
184
|
+
return /^[A-Za-z_$][\w$]*$/.test(key);
|
|
185
|
+
}
|
|
186
|
+
/** `value` as a TypeScript literal. */
|
|
187
|
+
export function toLiteral(value, indent = '') {
|
|
188
|
+
const inner = `${indent} `;
|
|
189
|
+
if (value === null)
|
|
190
|
+
return 'null';
|
|
191
|
+
if (typeof value === 'string')
|
|
192
|
+
return quote(value);
|
|
193
|
+
if (typeof value === 'number' || typeof value === 'boolean')
|
|
194
|
+
return String(value);
|
|
195
|
+
if (Array.isArray(value)) {
|
|
196
|
+
if (value.length === 0)
|
|
197
|
+
return '[]';
|
|
198
|
+
if (value.every(element => typeof element !== 'object' || element === null))
|
|
199
|
+
return `[${value.map(element => toLiteral(element)).join(', ')}]`;
|
|
200
|
+
return `[\n${value.map(element => `${inner}${toLiteral(element, inner)}`).join(',\n')}\n${indent}]`;
|
|
201
|
+
}
|
|
202
|
+
if (typeof value === 'object') {
|
|
203
|
+
const entries = Object.entries(value);
|
|
204
|
+
if (entries.length === 0)
|
|
205
|
+
return '{}';
|
|
206
|
+
return `{\n${entries.map(([key, element]) => `${inner}${isIdentifier(key) ? key : quote(key)}: ${toLiteral(element, inner)}`).join(',\n')}\n${indent}}`;
|
|
207
|
+
}
|
|
208
|
+
throw new Error(`Cannot write ${typeof value} into a snapshot`);
|
|
209
|
+
}
|
|
210
|
+
export const snapshotName = (revision) => `v${revision}`;
|
|
211
|
+
export const snapshotFile = (revision) => `v${revision}.snapshot.ts`;
|
|
212
|
+
export const migrationFile = (revision) => `v${revision}.ts`;
|
|
213
|
+
export function renderSnapshot(projection, dtvImport) {
|
|
214
|
+
return [
|
|
215
|
+
`${GENERATED} Do not edit: the definition "${projection.definition}" at revision ${projection.revision}.`,
|
|
216
|
+
`import type { ViewProjection } from ${quote(dtvImport)};`,
|
|
217
|
+
'',
|
|
218
|
+
`export const ${snapshotName(projection.revision)} = ${toLiteral(projection)} as const satisfies ViewProjection;`,
|
|
219
|
+
''
|
|
220
|
+
].join('\n');
|
|
221
|
+
}
|
|
222
|
+
export function renderMigration(args) {
|
|
223
|
+
const from = snapshotName(args.fromRevision);
|
|
224
|
+
const to = snapshotName(args.toRevision);
|
|
225
|
+
const ops = args.manualReason === undefined
|
|
226
|
+
? [...args.ops]
|
|
227
|
+
: [...args.ops, todo('manual revision', args.manualReason, [
|
|
228
|
+
'The definition did not change in a way the snapshots show; say how stored data changes, e.g.',
|
|
229
|
+
`m.mapValues('status', value => value === 'PAID' ? 'paid' : value)`
|
|
230
|
+
])];
|
|
231
|
+
const body = ops.length === 0
|
|
232
|
+
? '[]'
|
|
233
|
+
: `[\n${ops.map(generated => [
|
|
234
|
+
...generated.comments.map(comment => ` // ${comment}`),
|
|
235
|
+
` ${generated.code},`
|
|
236
|
+
].join('\n')).join('\n')}\n]`;
|
|
237
|
+
return [
|
|
238
|
+
`${GENERATED}${ops.some(generated => generated.todo) ? ' Replace each m.todo(…) with the operation it asks for.' : ''}`,
|
|
239
|
+
`import { DSL } from ${quote(args.dtvImport)};`,
|
|
240
|
+
`import { ${from} } from './${snapshotFile(args.fromRevision).replace(/\.ts$/, '')}';`,
|
|
241
|
+
`import { ${to} } from './${snapshotFile(args.toRevision).replace(/\.ts$/, '')}';`,
|
|
242
|
+
'',
|
|
243
|
+
`export default DSL.defineMigration(${from}, ${to}, ${ops.length === 0 ? '()' : 'm'} => ${body});`,
|
|
244
|
+
''
|
|
245
|
+
].join('\n');
|
|
246
|
+
}
|
|
247
|
+
export function renderIndex(args) {
|
|
248
|
+
const baseline = snapshotName(args.baselineRevision);
|
|
249
|
+
return [
|
|
250
|
+
`${GENERATED} Do not edit.`,
|
|
251
|
+
`import { DSL } from ${quote(args.dtvImport)};`,
|
|
252
|
+
`import { ${baseline} } from './${snapshotFile(args.baselineRevision).replace(/\.ts$/, '')}';`,
|
|
253
|
+
...args.migrationRevisions.map(revision => `import m${revision} from './${migrationFile(revision).replace(/\.ts$/, '')}';`),
|
|
254
|
+
'',
|
|
255
|
+
`export default DSL.defineViewMigrations(${baseline}, [${args.migrationRevisions.map(revision => `m${revision}`).join(', ')}]);`,
|
|
256
|
+
''
|
|
257
|
+
].join('\n');
|
|
258
|
+
}
|