@dialecte/cli 0.0.1

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 (3) hide show
  1. package/README.md +49 -0
  2. package/dist/cli.js +964 -0
  3. package/package.json +47 -0
package/README.md ADDED
@@ -0,0 +1,49 @@
1
+ # @dialecte/cli
2
+
3
+ The Dialecte **CLI**. Type-performance benchmarking, coverage probes, and readability
4
+ audits for any Dialecte — and for `@dialecte/core` itself.
5
+
6
+ > Dev-time tooling. It is **not** a runtime dependency: it shells out to the consumer's own `tsc`
7
+ > and reads its schema, so a dialect's published library never ships any of this.
8
+
9
+ ## Install
10
+
11
+ ```bash
12
+ npm i -D @dialecte/cli # provides the `dialecte` binary
13
+ ```
14
+
15
+ `typescript` is a **peer dependency** — the CLI uses the consumer's installed compiler so the types
16
+ `audit` renders come from the exact same `tsc` that `bench` measures with.
17
+
18
+ ## Commands
19
+
20
+ ```
21
+ dialecte coverage # generate complete, schema-driven type-coverage probes
22
+ dialecte bench [--check] # measure type-instantiation cost (tsc --extendedDiagnostics); --check gates CI
23
+ dialecte audit # render the public type surface and flag readability issues (C1–C6)
24
+ dialecte --help
25
+ ```
26
+
27
+ ## Zero-config
28
+
29
+ A dialect is built by convention: `src/<version>/definition/{constants,definition}.generated.ts`, and
30
+ its hydrated namespace is the **capitalized package name** (`@dialecte/scl` → `Scl`). The CLI discovers
31
+ every version + the namespace with **no config**, emitting benchmarks per version under
32
+ `benchmarks/types/<version>/`. `@dialecte/core` is detected by name and benched via a built-in generic
33
+ _test_ dialect.
34
+
35
+ Everything is overridable per `package.json` `"dialecte"` field (odd layouts) or CLI flags:
36
+
37
+ ```
38
+ --namespace <Name> --entry <import> --constants-dir <dir> --out <dir> --version <v> --tsconfig <f>
39
+ ```
40
+
41
+ Env: `RUNS=5 dialecte bench` (repetitions kept as the min); `COVERAGE_CHILD_CAP=N` (cap child edges).
42
+
43
+ ## How it fits the ecosystem
44
+
45
+ | Package | Bin | Audience | Phase |
46
+ | ---------------------------------- | ----------------- | ------------------------ | -------- |
47
+ | `@dialecte/create` | `create-dialecte` | new-dialect authors | scaffold |
48
+ | **`@dialecte/cli`** | **`dialecte`** | **dialect authors / CI** | **dev** |
49
+ | `@dialecte/core` · `@dialecte/scl` | — | libraries | runtime |
package/dist/cli.js ADDED
@@ -0,0 +1,964 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/commands/audit.ts
4
+ import { writeFileSync, rmSync, mkdirSync } from "fs";
5
+ import { join as join3, dirname as dirname2 } from "path";
6
+
7
+ // src/lib/config.ts
8
+ import { readFileSync, existsSync, readdirSync, statSync } from "fs";
9
+ import { join } from "path";
10
+ var getArg = (argv, name) => {
11
+ const i = argv.indexOf(`--${name}`);
12
+ return i >= 0 ? argv[i + 1] : void 0;
13
+ };
14
+ var hasFlag = (argv, name) => argv.includes(`--${name}`);
15
+ var tsconfigOf = (argv, cwd = process.cwd()) => getArg(argv, "tsconfig") ?? pkgConfig(cwd).tsconfig ?? "tsconfig.build.json";
16
+ var readPkg = (cwd) => {
17
+ const p = join(cwd, "package.json");
18
+ return existsSync(p) ? JSON.parse(readFileSync(p, "utf8")) : {};
19
+ };
20
+ var pkgConfig = (cwd) => readPkg(cwd).dialecte ?? {};
21
+ var capitalize = (s) => s.charAt(0).toUpperCase() + s.slice(1);
22
+ function discoverNamespace(cwd) {
23
+ return capitalize(
24
+ String(readPkg(cwd).name ?? "dialecte").split("/").pop() ?? "dialecte"
25
+ );
26
+ }
27
+ function discoverVersions(cwd) {
28
+ const src = join(cwd, "src");
29
+ if (!existsSync(src)) return [];
30
+ return readdirSync(src).filter((v) => statSync(join(src, v)).isDirectory()).filter(
31
+ (v) => existsSync(join(src, v, "definition", "constants.generated.ts")) && existsSync(join(src, v, "definition", "definition.generated.ts"))
32
+ ).sort();
33
+ }
34
+ var CORE_PACKAGE = "@dialecte/core";
35
+ var CORE_TEST_DIALECT = {
36
+ version: "core",
37
+ binding: {
38
+ kind: "core",
39
+ coreAlias: "Core",
40
+ coreImport: "@/index",
41
+ configType: "TestDialecteConfig",
42
+ configImport: "@/test/config"
43
+ },
44
+ constantsDir: "./src/test/generated",
45
+ outDir: "./benchmarks/types/generated"
46
+ };
47
+ function resolveTargets(argv, cwd = process.cwd()) {
48
+ if (readPkg(cwd).name === CORE_PACKAGE)
49
+ return [
50
+ {
51
+ ...CORE_TEST_DIALECT,
52
+ version: getArg(argv, "version") ?? CORE_TEST_DIALECT.version,
53
+ constantsDir: getArg(argv, "constants-dir") ?? CORE_TEST_DIALECT.constantsDir,
54
+ outDir: getArg(argv, "out") ?? CORE_TEST_DIALECT.outDir
55
+ }
56
+ ];
57
+ const cfg = pkgConfig(cwd);
58
+ const namespace = getArg(argv, "namespace") ?? cfg.namespace ?? discoverNamespace(cwd);
59
+ const only = getArg(argv, "version");
60
+ let versions = discoverVersions(cwd);
61
+ if (only) versions = versions.filter((v) => v === only);
62
+ if (!versions.length && (getArg(argv, "constants-dir") || getArg(argv, "entry")))
63
+ versions = [only ?? "default"];
64
+ return versions.map((version) => {
65
+ const entry = getArg(argv, "entry") ?? cfg.entry ?? `@/${version}`;
66
+ return {
67
+ version,
68
+ binding: { kind: "namespace", name: namespace, import: entry },
69
+ constantsDir: getArg(argv, "constants-dir") ?? cfg.constantsDir ?? `./src/${version}/definition`,
70
+ outDir: getArg(argv, "out") ?? cfg.out ?? `./benchmarks/types/${version}/generated`
71
+ };
72
+ });
73
+ }
74
+
75
+ // src/lib/format.ts
76
+ import { spawnSync } from "child_process";
77
+
78
+ // src/lib/bin.ts
79
+ import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
80
+ import { createRequire } from "module";
81
+ import { dirname, join as join2 } from "path";
82
+ var requireHere = createRequire(import.meta.url);
83
+ function ownBin(pkg, binName) {
84
+ try {
85
+ const pjPath = requireHere.resolve(`${pkg}/package.json`);
86
+ const bin = JSON.parse(readFileSync2(pjPath, "utf8")).bin;
87
+ const rel = typeof bin === "string" ? bin : bin?.[binName] ?? bin?.[pkg];
88
+ const abs = rel ? join2(dirname(pjPath), rel) : void 0;
89
+ return abs && existsSync2(abs) ? abs : void 0;
90
+ } catch {
91
+ return void 0;
92
+ }
93
+ }
94
+ function resolveBin(name, pkg, root) {
95
+ const consumer = join2(root, "node_modules/.bin", name);
96
+ if (existsSync2(consumer)) return { path: consumer, source: "consumer" };
97
+ const own = ownBin(pkg, name);
98
+ return own ? { path: own, source: "own" } : null;
99
+ }
100
+
101
+ // src/lib/format.ts
102
+ var formatOptsFromArgv = (argv) => ({
103
+ config: getArg(argv, "format-config"),
104
+ skip: hasFlag(argv, "no-format")
105
+ });
106
+ function formatFiles(root, files, opts = {}) {
107
+ if (opts.skip || !files.length) return;
108
+ const oxfmt = resolveBin("oxfmt", "oxfmt", root);
109
+ if (!oxfmt) {
110
+ console.warn(" \u26A0 oxfmt not found (project nor @dialecte/cli) \u2014 emitted files left unformatted");
111
+ return;
112
+ }
113
+ const args = [...opts.config ? ["--config", opts.config] : [], ...files];
114
+ const res = spawnSync(oxfmt.path, args, { cwd: root, encoding: "utf8" });
115
+ if (res.status !== 0)
116
+ console.warn(` \u26A0 oxfmt exited ${res.status ?? "?"} \u2014 emitted files may be unformatted`);
117
+ }
118
+
119
+ // src/commands/audit.ts
120
+ import ts from "typescript";
121
+ function classify(s) {
122
+ const f = [];
123
+ if (s.includes("import(")) f.push("C1 module-noise");
124
+ const tn = (s.match(/tagName/g) || []).length;
125
+ if (tn > 8) f.push(`C2/C4 element-union\xD7${tn}`);
126
+ if ((s.match(/\|\s*\{/g) || []).length > 6) f.push("C3 wide-input-union");
127
+ if (s.includes("status:") && s.includes("attributes:")) f.push("C5 record-seam");
128
+ if (s.includes("TreeRecord<") || s.includes("TreeSelect<")) f.push("C6 recursive");
129
+ return f;
130
+ }
131
+ function auditTarget(NS, ENTRY, tsconfig, outMd) {
132
+ const ROOT = process.cwd();
133
+ const ENTRY_FILE = join3(ROOT, "benchmarks/types/.audit-entry.ts");
134
+ const parsed = ts.parseJsonConfigFileContent(
135
+ ts.readConfigFile(join3(ROOT, tsconfig), ts.sys.readFile).config,
136
+ ts.sys,
137
+ ROOT
138
+ );
139
+ const compilerOptions = { ...parsed.options, noEmit: true, rootDir: ROOT };
140
+ const FLAGS = ts.TypeFormatFlags.NoTruncation | ts.TypeFormatFlags.WriteArrowStyleSignature | ts.TypeFormatFlags.MultilineObjectLiterals;
141
+ const PRIMITIVEISH = ts.TypeFlags.StringLike | ts.TypeFlags.NumberLike | ts.TypeFlags.BooleanLike | ts.TypeFlags.ESSymbolLike | ts.TypeFlags.VoidLike | ts.TypeFlags.Null | ts.TypeFlags.BigIntLike;
142
+ const declOf = (p) => p.valueDeclaration ?? p.declarations?.[0];
143
+ writeFileSync(
144
+ ENTRY_FILE,
145
+ [
146
+ `import type { ${NS} } from '${ENTRY}'`,
147
+ `declare const q: ${NS}.Query`,
148
+ `declare const tx: ${NS}.Transaction`,
149
+ `declare const doc: ${NS}.Document`,
150
+ `declare const project: ${NS}.Project`,
151
+ `export { q, tx, doc, project }`,
152
+ ""
153
+ ].join("\n")
154
+ );
155
+ const d1 = ts.createProgram([ENTRY_FILE], compilerOptions);
156
+ const c1 = d1.getTypeChecker();
157
+ const sf1 = d1.getSourceFile(ENTRY_FILE);
158
+ const isPublic1 = (p) => {
159
+ const d = declOf(p);
160
+ return !d || !(ts.getCombinedModifierFlags(d) & (ts.ModifierFlags.Private | ts.ModifierFlags.Protected));
161
+ };
162
+ const inRepo1 = (p) => !(declOf(p)?.getSourceFile()?.fileName ?? "").includes("/node_modules/typescript/");
163
+ const callable1 = (p) => c1.getTypeOfSymbolAtLocation(p, declOf(p) ?? sf1).getCallSignatures().length > 0;
164
+ const walk = (type, path, depth, acc) => {
165
+ for (const prop of type.getProperties()) {
166
+ if (!isPublic1(prop)) continue;
167
+ const pt = c1.getTypeOfSymbolAtLocation(prop, declOf(prop) ?? sf1);
168
+ if (pt.getCallSignatures().length > 0) acc.push(`${path}.${prop.getName()}`);
169
+ else if (depth < 1 && !(pt.flags & PRIMITIVEISH) && pt.getProperties().some((p) => isPublic1(p) && inRepo1(p) && callable1(p)))
170
+ walk(pt, `${path}.${prop.getName()}`, depth + 1, acc);
171
+ }
172
+ };
173
+ const ex1 = Object.fromEntries(
174
+ c1.getExportsOfModule(c1.getSymbolAtLocation(sf1)).map((s) => [s.getName(), s])
175
+ );
176
+ const methodPaths = [];
177
+ for (const v of ["q", "tx", "doc", "project"])
178
+ if (ex1[v]) walk(c1.getTypeOfSymbolAtLocation(ex1[v], sf1), v, 0, methodPaths);
179
+ const imp = sf1.statements.find(ts.isImportDeclaration)?.importClause?.namedBindings;
180
+ let nsSym = imp ? c1.getSymbolAtLocation(imp.elements[0].name) : void 0;
181
+ if (nsSym && nsSym.flags & ts.SymbolFlags.Alias) nsSym = c1.getAliasedSymbol(nsSym);
182
+ const nsMembers = [];
183
+ nsSym?.exports?.forEach((m, name) => {
184
+ const decl = m.declarations?.[0];
185
+ const tp = decl && ts.isTypeAliasDeclaration(decl) ? decl.typeParameters ?? [] : [];
186
+ nsMembers.push({ name: String(name), arity: tp.filter((t) => !t.default).length });
187
+ });
188
+ nsMembers.sort((a, b) => a.name.localeCompare(b.name));
189
+ const lines = [
190
+ `import type { ${NS} } from '${ENTRY}'`,
191
+ `declare const q: ${NS}.Query`,
192
+ `declare const tx: ${NS}.Transaction`,
193
+ `declare const doc: ${NS}.Document`,
194
+ `declare const project: ${NS}.Project`,
195
+ `export { q, tx, doc, project }`
196
+ ];
197
+ methodPaths.forEach((p, i) => {
198
+ lines.push(
199
+ `export type MP_${i} = Parameters<typeof ${p}>[0]`,
200
+ `export type MR_${i} = Awaited<ReturnType<typeof ${p}>>`
201
+ );
202
+ });
203
+ for (const m of nsMembers) {
204
+ lines.push(
205
+ `export type NS_${m.name} = ${NS}.${m.name}${m.arity ? `<${Array(m.arity).fill(`'LNode'`).join(", ")}>` : ""}`
206
+ );
207
+ if (m.arity >= 1)
208
+ lines.push(
209
+ `export type NSW_${m.name} = ${NS}.${m.name}<${[`${NS}.ElementsOf`, ...Array(m.arity - 1).fill(`'LNode'`)].join(", ")}>`
210
+ );
211
+ }
212
+ writeFileSync(ENTRY_FILE, `${lines.join("\n")}
213
+ `);
214
+ const program = ts.createProgram([ENTRY_FILE], compilerOptions);
215
+ const checker = program.getTypeChecker();
216
+ const sf = program.getSourceFile(ENTRY_FILE);
217
+ const render = (type, node) => {
218
+ try {
219
+ return checker.typeToString(type, node, FLAGS);
220
+ } catch {
221
+ return "<render-error>";
222
+ }
223
+ };
224
+ const tagCount = (s) => (s.match(/readonly tagName|tagName:/g) || []).length;
225
+ const sym2 = Object.fromEntries(
226
+ checker.getExportsOfModule(checker.getSymbolAtLocation(sf)).map((s) => [s.getName(), s])
227
+ );
228
+ const renderExport = (name) => {
229
+ const s = sym2[name];
230
+ return s ? render(checker.getDeclaredTypeOfSymbol(s), s.declarations?.[0] ?? sf) : "";
231
+ };
232
+ const methodRows = [];
233
+ const typeRows = [];
234
+ for (const [label, v] of [
235
+ [`${NS}.Query`, "q"],
236
+ [`${NS}.Transaction`, "tx"],
237
+ [`${NS}.Document`, "doc"],
238
+ [`${NS}.Project`, "project"]
239
+ ]) {
240
+ if (!sym2[v]) continue;
241
+ const str = render(checker.getTypeOfSymbolAtLocation(sym2[v], sf), sf);
242
+ methodRows.push({
243
+ name: `${label} (container)`,
244
+ len: str.length,
245
+ members: "-",
246
+ flags: classify(str)
247
+ });
248
+ }
249
+ methodPaths.forEach((p, i) => {
250
+ const param = renderExport(`MP_${i}`);
251
+ const ret = renderExport(`MR_${i}`);
252
+ methodRows.push({
253
+ name: `${p}(\u2026) param`,
254
+ len: param.length,
255
+ members: tagCount(param),
256
+ flags: classify(param)
257
+ });
258
+ methodRows.push({
259
+ name: `${p}(\u2026) \u2192 return`,
260
+ len: ret.length,
261
+ members: tagCount(ret),
262
+ flags: classify(ret)
263
+ });
264
+ });
265
+ for (const m of nsMembers) {
266
+ const concrete = renderExport(`NS_${m.name}`);
267
+ typeRows.push({
268
+ name: `${NS}.${m.name}`,
269
+ len: concrete.length,
270
+ members: tagCount(concrete),
271
+ flags: classify(concrete)
272
+ });
273
+ if (m.arity >= 1) {
274
+ const wide = renderExport(`NSW_${m.name}`);
275
+ typeRows.push({
276
+ name: `${NS}.${m.name}<ElementsOf>`,
277
+ len: wide.length,
278
+ members: tagCount(wide),
279
+ flags: classify(wide)
280
+ });
281
+ }
282
+ }
283
+ methodRows.sort((a, b) => b.len - a.len);
284
+ typeRows.sort((a, b) => b.len - a.len);
285
+ const md = [
286
+ `# ${NS} public-type readability audit`,
287
+ "",
288
+ `Every public method (resolved param + return \u2014 the form an editor shows when you hover a call)`,
289
+ `and every namespace type is rendered with NoTruncation, then measured. Methods are discovered`,
290
+ `dynamically (Query/Transaction/Document/Project incl. extension groups), so this covers core's`,
291
+ `classes AND the dialect's extensions. Rows sorted worst-first.`,
292
+ "",
293
+ "**Columns** \u2014 `len`: characters in the render (proxy for hover size; bigger = noisier).",
294
+ "`members`: element-union members surfaced. `causes`: matched root cause(s) (legend below).",
295
+ "",
296
+ "**Root-cause legend**",
297
+ '- **C1 module-noise** \u2014 `import("\u2026/extensions/\u2026")` refs inflate the render. Fix: name containers / annotate returns.',
298
+ "- **C2/C4 element-union** \u2014 the full element-name union appears. Largely inherent to a config-driven DSL.",
299
+ "- **C3 wide-input-union** \u2014 a wide multi-member input union, each member expanded.",
300
+ "- **C5 record-seam** \u2014 a record renders as `RawRecord<\u2026> & { status }` instead of one clean object.",
301
+ "- **C6 recursive** \u2014 self-referential `TreeRecord`/`TreeSelect`.",
302
+ ""
303
+ ];
304
+ const table = (rows, head) => {
305
+ md.push(
306
+ `## ${head}`,
307
+ "",
308
+ "| Member | len | members | causes |",
309
+ "|--------|-----|---------|--------|"
310
+ );
311
+ for (const r of rows)
312
+ md.push(
313
+ `| ${r.name} | ${r.len.toLocaleString("en-US")} | ${r.members} | ${r.flags.join(", ") || "\u2014"} |`
314
+ );
315
+ md.push("");
316
+ };
317
+ table(methodRows, `Methods \u2014 resolved param/return (${methodPaths.length} methods discovered)`);
318
+ table(typeRows, "Namespace type aliases (concrete `LNode` + wide `ElementsOf`)");
319
+ const all = [...methodRows, ...typeRows];
320
+ md.push(
321
+ `**Summary:** ${methodPaths.length} methods, ${nsMembers.length} namespace types, ${all.filter((r) => r.flags.length).length}/${all.length} rows flagged. Total ${all.reduce((a, r) => a + r.len, 0).toLocaleString("en-US")} chars.`
322
+ );
323
+ mkdirSync(dirname2(join3(ROOT, outMd)), { recursive: true });
324
+ writeFileSync(join3(ROOT, outMd), `${md.join("\n")}
325
+ `);
326
+ rmSync(ENTRY_FILE, { force: true });
327
+ console.log(
328
+ ` [${NS}] ${methodPaths.length} methods, ${nsMembers.length} types, ${all.filter((r) => r.flags.length).length} flagged \u2192 ${outMd}`
329
+ );
330
+ }
331
+ async function run(argv) {
332
+ const tsconfig = tsconfigOf(argv);
333
+ const targets = resolveTargets(argv).filter((t) => t.binding.kind === "namespace");
334
+ if (!targets.length)
335
+ throw new Error(
336
+ "audit: no namespace-binding versions discovered (the audit needs a hydrated namespace)."
337
+ );
338
+ const fmt = formatOptsFromArgv(argv);
339
+ for (const t of targets) {
340
+ if (t.binding.kind !== "namespace") continue;
341
+ const outMd = `${dirname2(t.outDir)}/readability-audit.md`;
342
+ auditTarget(t.binding.name, t.binding.import, tsconfig, outMd);
343
+ formatFiles(process.cwd(), [join3(process.cwd(), outMd)], fmt);
344
+ }
345
+ }
346
+
347
+ // src/commands/bench.ts
348
+ import { spawnSync as spawnSync2 } from "child_process";
349
+ import { writeFileSync as writeFileSync2, readFileSync as readFileSync3, readdirSync as readdirSync2, existsSync as existsSync3, rmSync as rmSync2, mkdirSync as mkdirSync2 } from "fs";
350
+ import { join as join4, dirname as dirname3 } from "path";
351
+ var METRICS = [
352
+ "Instantiations",
353
+ "Types",
354
+ "Symbols",
355
+ "Memory used",
356
+ "Check time",
357
+ "Total time"
358
+ ];
359
+ var STABLE_METRICS = ["Instantiations", "Types", "Symbols"];
360
+ var THRESHOLD = 0.05;
361
+ function parseTscMetrics(output) {
362
+ const m = {};
363
+ for (const metric of METRICS) {
364
+ const match = output.match(
365
+ new RegExp(`${metric.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}:\\s+([\\d.]+)`)
366
+ );
367
+ if (match) m[metric] = Number(match[1]);
368
+ }
369
+ return m;
370
+ }
371
+ function aggregateRuns(runs) {
372
+ const best = {};
373
+ for (const metric of METRICS) {
374
+ const vals = runs.map((r) => r[metric]).filter((v) => v != null);
375
+ if (vals.length) best[metric] = Math.min(...vals);
376
+ }
377
+ return best;
378
+ }
379
+ function checkRegression(current, baseline, threshold = THRESHOLD) {
380
+ return baseline != null && current != null && current > baseline * (1 + threshold);
381
+ }
382
+ function stableResults(results) {
383
+ return Object.fromEntries(
384
+ Object.entries(results).map(([k, m]) => [
385
+ k,
386
+ Object.fromEntries(STABLE_METRICS.filter((s) => m[s] != null).map((s) => [s, m[s]]))
387
+ ])
388
+ );
389
+ }
390
+ async function run2(argv) {
391
+ const ROOT = process.cwd();
392
+ const tsc = resolveBin("tsc", "typescript", ROOT);
393
+ if (!tsc) throw new Error("bench: no TypeScript compiler found (project nor @dialecte/cli).");
394
+ if (tsc.source === "own")
395
+ console.warn(
396
+ " \u26A0 using @dialecte/cli's own tsc \u2014 counts may differ from the project's pinned TypeScript"
397
+ );
398
+ const TSC = tsc.path;
399
+ const RUNS = Number(process.env.RUNS || 3);
400
+ const CHECK = hasFlag(argv, "check");
401
+ const tsconfig = tsconfigOf(argv);
402
+ const targets = resolveTargets(argv);
403
+ if (!targets.length)
404
+ throw new Error(
405
+ "bench: no versions discovered. Run `dialecte coverage` first, or pass --constants-dir."
406
+ );
407
+ const runTsc = (args) => {
408
+ const res = spawnSync2(TSC, args, { cwd: ROOT, encoding: "utf8", maxBuffer: 1e8 });
409
+ return parseTscMetrics(`${res.stdout || ""}${res.stderr || ""}`);
410
+ };
411
+ const measure = (args) => aggregateRuns(Array.from({ length: RUNS }, () => runTsc(args)));
412
+ const isolated = (file) => {
413
+ const name = `.bench-${file.replace(/[/.]/g, "_")}.tsconfig.json`;
414
+ writeFileSync2(
415
+ join4(ROOT, name),
416
+ JSON.stringify({
417
+ extends: `./${tsconfig}`,
418
+ compilerOptions: {
419
+ noEmit: true,
420
+ rootDir: ".",
421
+ declaration: false,
422
+ declarationMap: false,
423
+ emitDeclarationOnly: false
424
+ },
425
+ include: [file]
426
+ })
427
+ );
428
+ return name;
429
+ };
430
+ const measureFile = (file) => {
431
+ const tmp = isolated(file);
432
+ const m = measure(["-p", tmp, "--extendedDiagnostics"]);
433
+ rmSync2(join4(ROOT, tmp), { force: true });
434
+ return m;
435
+ };
436
+ const col = (s, w) => String(s).padEnd(w);
437
+ const num = (n) => n == null ? "\u2014" : Math.round(n).toLocaleString("en-US");
438
+ console.log(`bench \u2014 ${RUNS} runs (min) \u2014 whole program \u2026`);
439
+ const wholeCheck = measure(["-p", tsconfig, "--noEmit", "--extendedDiagnostics"]);
440
+ const wholeEmit = measure([
441
+ "-p",
442
+ tsconfig,
443
+ "--emitDeclarationOnly",
444
+ "--outDir",
445
+ ".bench-dts",
446
+ "--extendedDiagnostics"
447
+ ]);
448
+ rmSync2(join4(ROOT, ".bench-dts"), { recursive: true, force: true });
449
+ let failed = false;
450
+ for (const t of targets) {
451
+ const versionDir = dirname3(t.outDir);
452
+ const results = {
453
+ "whole-program (check)": wholeCheck,
454
+ "whole-program (emit)": wholeEmit
455
+ };
456
+ const add = (key, rel) => {
457
+ if (existsSync3(join4(ROOT, rel))) {
458
+ process.stdout.write(` [${t.version}] ${key} \u2026
459
+ `);
460
+ results[key] = measureFile(rel);
461
+ }
462
+ };
463
+ add("baseline (import)", `${t.outDir}/baseline.ts`);
464
+ add("coverage: surface", `${t.outDir}/coverage.surface.generated.ts`);
465
+ add("coverage: calls", `${t.outDir}/coverage.calls.generated.ts`);
466
+ add("coverage: deep", `${t.outDir}/coverage.deep.generated.ts`);
467
+ add("coverage: api", `${t.outDir}/coverage.api.generated.ts`);
468
+ if (existsSync3(join4(ROOT, versionDir))) {
469
+ for (const f of readdirSync2(join4(ROOT, versionDir)))
470
+ if (f.endsWith(".ts") && !f.endsWith(".test-d.ts"))
471
+ add(`consumer: ${f.replace(/\.ts$/, "")}`, `${versionDir}/${f}`);
472
+ }
473
+ console.log(
474
+ `
475
+ [${t.version}] | ${col("Scenario", 26)} | ${col("Instantiations", 14)} | ${col("Check", 7)} |`
476
+ );
477
+ for (const [key, m] of Object.entries(results))
478
+ console.log(
479
+ ` | ${col(key, 26)} | ${col(num(m.Instantiations), 14)} | ${col(`${m["Check time"] ?? "?"}s`, 7)} |`
480
+ );
481
+ const baseline = results["baseline (import)"]?.Instantiations;
482
+ if (baseline != null) {
483
+ for (const [key, m] of Object.entries(results))
484
+ if (key.startsWith("coverage:") || key.startsWith("consumer:"))
485
+ console.log(` ${col(key, 26)} +${num((m.Instantiations ?? 0) - baseline)}`);
486
+ }
487
+ const baselinePath = join4(ROOT, versionDir, "baseline.json");
488
+ if (CHECK) {
489
+ const prior = JSON.parse(readFileSync3(baselinePath, "utf8"));
490
+ for (const [key, m] of Object.entries(results)) {
491
+ const base = prior.results?.[key]?.Instantiations;
492
+ if (checkRegression(m.Instantiations, base)) {
493
+ console.error(
494
+ `\u274C [${t.version}] ${key}: ${num(m.Instantiations)} > baseline ${num(base)} (+${((m.Instantiations / base - 1) * 100).toFixed(1)}%)`
495
+ );
496
+ failed = true;
497
+ }
498
+ }
499
+ } else {
500
+ mkdirSync2(join4(ROOT, versionDir), { recursive: true });
501
+ writeFileSync2(
502
+ baselinePath,
503
+ `${JSON.stringify({ tool: "dialecte bench", version: t.version, runs: RUNS, results: stableResults(results) }, null, " ")}
504
+ `
505
+ );
506
+ formatFiles(ROOT, [baselinePath], formatOptsFromArgv(argv));
507
+ console.log(` wrote ${versionDir}/baseline.json`);
508
+ }
509
+ }
510
+ if (CHECK) {
511
+ if (failed) process.exit(1);
512
+ console.log(
513
+ `
514
+ \u2705 No instantiation regression > ${THRESHOLD * 100}% across ${targets.length} version(s).`
515
+ );
516
+ }
517
+ }
518
+
519
+ // src/commands/coverage.ts
520
+ import { writeFileSync as writeFileSync4, mkdirSync as mkdirSync3, existsSync as existsSync4 } from "fs";
521
+ import { join as join6, resolve } from "path";
522
+ import { pathToFileURL } from "url";
523
+
524
+ // src/lib/discover.ts
525
+ import { writeFileSync as writeFileSync3, rmSync as rmSync3 } from "fs";
526
+ import { join as join5 } from "path";
527
+ import ts2 from "typescript";
528
+ function discoverMethodPaths(entrySource, tsconfig, root) {
529
+ const ENTRY = join5(root, "benchmarks/types/.discover-entry.ts");
530
+ writeFileSync3(ENTRY, entrySource);
531
+ try {
532
+ const parsed = ts2.parseJsonConfigFileContent(
533
+ ts2.readConfigFile(join5(root, tsconfig), ts2.sys.readFile).config,
534
+ ts2.sys,
535
+ root
536
+ );
537
+ const program = ts2.createProgram([ENTRY], { ...parsed.options, noEmit: true, rootDir: root });
538
+ const checker = program.getTypeChecker();
539
+ const sf = program.getSourceFile(ENTRY);
540
+ if (!sf) return [];
541
+ const PRIMITIVEISH = ts2.TypeFlags.StringLike | ts2.TypeFlags.NumberLike | ts2.TypeFlags.BooleanLike | ts2.TypeFlags.ESSymbolLike | ts2.TypeFlags.VoidLike | ts2.TypeFlags.Null | ts2.TypeFlags.BigIntLike;
542
+ const declOf = (p) => p.valueDeclaration ?? p.declarations?.[0];
543
+ const isPublic = (p) => {
544
+ const d = declOf(p);
545
+ return !d || !(ts2.getCombinedModifierFlags(d) & (ts2.ModifierFlags.Private | ts2.ModifierFlags.Protected));
546
+ };
547
+ const inRepo = (p) => !(declOf(p)?.getSourceFile()?.fileName ?? "").includes("/node_modules/typescript/");
548
+ const callable = (p) => checker.getTypeOfSymbolAtLocation(p, declOf(p) ?? sf).getCallSignatures().length > 0;
549
+ const paths = [];
550
+ const walk = (type, path, depth) => {
551
+ for (const prop of type.getProperties()) {
552
+ if (!isPublic(prop)) continue;
553
+ const pt = checker.getTypeOfSymbolAtLocation(prop, declOf(prop) ?? sf);
554
+ if (pt.getCallSignatures().length > 0) paths.push(`${path}.${prop.getName()}`);
555
+ else if (depth < 1 && !(pt.flags & PRIMITIVEISH) && pt.getProperties().some((p) => isPublic(p) && inRepo(p) && callable(p)))
556
+ walk(pt, `${path}.${prop.getName()}`, depth + 1);
557
+ }
558
+ };
559
+ const ex = Object.fromEntries(
560
+ checker.getExportsOfModule(checker.getSymbolAtLocation(sf)).map((s) => [s.getName(), s])
561
+ );
562
+ for (const v of ["q", "tx", "doc", "project"])
563
+ if (ex[v]) walk(checker.getTypeOfSymbolAtLocation(ex[v], sf), v, 0);
564
+ return paths;
565
+ } finally {
566
+ rmSync3(ENTRY, { force: true });
567
+ }
568
+ }
569
+
570
+ // src/commands/coverage.ts
571
+ var ELEMENT_GENERICS = [
572
+ "Ref",
573
+ "RawRecord",
574
+ "TrackedRecord",
575
+ "TreeRecord",
576
+ "AttributesOf",
577
+ "AttributesValueObjectOf",
578
+ "FullAttributeObjectOf",
579
+ "ChildrenOf",
580
+ "ParentsOf",
581
+ "DescendantsOf",
582
+ "AncestorsOf",
583
+ "ParentRelationship",
584
+ "ChildRelationship",
585
+ "Attribute",
586
+ "QualifiedAttribute"
587
+ ];
588
+ function refsOf(b) {
589
+ if (b.kind === "namespace") {
590
+ return {
591
+ imports: [`import type { ${b.name} } from '${b.import}'`],
592
+ elementsOf: `${b.name}.ElementsOf`,
593
+ query: `${b.name}.Query`,
594
+ transaction: `${b.name}.Transaction`,
595
+ generic: (g, e) => `${b.name}.${g}<${e}>`,
596
+ nullary: (t) => `${b.name}.${t}`
597
+ };
598
+ }
599
+ return {
600
+ imports: [
601
+ `import type * as ${b.coreAlias} from '${b.coreImport}'`,
602
+ `import type { ${b.configType} } from '${b.configImport}'`
603
+ ],
604
+ elementsOf: `${b.coreAlias}.ElementsOf<${b.configType}>`,
605
+ query: `${b.coreAlias}.Query<${b.configType}>`,
606
+ transaction: `${b.coreAlias}.Transaction<${b.configType}>`,
607
+ generic: (g, e) => `${b.coreAlias}.${g}<${b.configType}, ${e}>`,
608
+ nullary: (t) => `${b.coreAlias}.${t}<${b.configType}>`
609
+ };
610
+ }
611
+ var attrValue = (d) => {
612
+ if (d?.fixed) return d.fixed;
613
+ const enums = d?.facets?.enumeration?.filter((v) => v !== "");
614
+ return enums?.length ? enums[0] : "x";
615
+ };
616
+ function genSurface(b) {
617
+ const r = refsOf(b);
618
+ const lines = [
619
+ `// AUTO-GENERATED by \`dialecte coverage\` \u2014 do not edit. Complete per-element TYPE coverage.`,
620
+ ...r.imports,
621
+ ""
622
+ ];
623
+ const names = [];
624
+ for (const g of ELEMENT_GENERICS) {
625
+ lines.push(`type All_${g} = { [E in ${r.elementsOf}]: ${r.generic(g, "E")} }[${r.elementsOf}]`);
626
+ names.push(`All_${g}`);
627
+ }
628
+ lines.push("", `export type CoverageSurface = [${names.join(", ")}]`, "");
629
+ return lines.join("\n");
630
+ }
631
+ function genCalls(schema, b) {
632
+ const r = refsOf(b);
633
+ const childCap = Number(process.env.COVERAGE_CHILD_CAP || Infinity);
634
+ const singletons = new Set(schema.singletons);
635
+ const ref = (e) => singletons.has(e) ? `{ tagName: '${e}' }` : `{ tagName: '${e}', id: 'x' }`;
636
+ const details = (e) => schema.definition[e]?.attributes?.details ?? {};
637
+ const attrsObj = (e) => {
638
+ const d = details(e);
639
+ const req = Object.keys(d).filter((a) => d[a]?.required);
640
+ return req.length ? `{ ${req.map((a) => `'${a}': '${attrValue(d[a])}'`).join(", ")} }` : "{}";
641
+ };
642
+ const L = [
643
+ `// AUTO-GENERATED by \`dialecte coverage\` \u2014 do not edit. Complete valid-call coverage (core verbs \xD7 schema).`,
644
+ ...r.imports,
645
+ `declare const q: ${r.query}`,
646
+ `declare const tx: ${r.transaction}`,
647
+ "",
648
+ `export async function _coverageCalls() {`
649
+ ];
650
+ for (const e of schema.elements) {
651
+ const rf = ref(e);
652
+ L.push(` await q.getRecordsByTagName('${e}')`);
653
+ L.push(` await q.getRecord(${rf})`);
654
+ L.push(` await q.getAttributes(${rf})`);
655
+ L.push(` await q.getAttributes(${rf}, { fullObject: true })`);
656
+ L.push(` await q.getTree(${rf})`);
657
+ L.push(` await q.findDescendants(${rf})`);
658
+ L.push(` await tx.update(${rf}, { attributes: {} })`);
659
+ L.push(` await tx.delete(${rf})`);
660
+ const names = Object.keys(details(e));
661
+ if (names.length) L.push(` await q.getAttribute(${rf}, { name: '${names[0]}' })`);
662
+ for (const c of (schema.children[e] ?? []).slice(0, childCap)) {
663
+ L.push(` await q.getChild(${rf}, '${c}')`);
664
+ L.push(` await q.getChildren(${rf}, '${c}')`);
665
+ L.push(` await tx.addChild(${rf}, { tagName: '${c}', attributes: ${attrsObj(c)} })`);
666
+ L.push(` await tx.ensureChild(${rf}, { tagName: '${c}', attributes: ${attrsObj(c)} })`);
667
+ }
668
+ }
669
+ L.push("}", "");
670
+ return L.join("\n");
671
+ }
672
+ function genBaseline(b) {
673
+ const r = refsOf(b);
674
+ return [
675
+ `// AUTO-GENERATED by \`dialecte coverage\` \u2014 do not edit. Import baseline for bench subtraction.`,
676
+ ...r.imports,
677
+ "",
678
+ `export type _Element = ${r.elementsOf}`,
679
+ ""
680
+ ].join("\n");
681
+ }
682
+ function deepestPath(root, children, cap = 8) {
683
+ const visited = /* @__PURE__ */ new Set();
684
+ const path = [];
685
+ let cur = root;
686
+ while (cur && path.length < cap && !visited.has(cur)) {
687
+ path.push(cur);
688
+ visited.add(cur);
689
+ const kids = (children[cur] ?? []).filter((c) => !visited.has(c));
690
+ cur = [...kids].sort((a, b) => (children[b]?.length ?? 0) - (children[a]?.length ?? 0))[0];
691
+ }
692
+ return path;
693
+ }
694
+ var nestedSelect = (tags) => tags.length ? `{ ${tags[0]}: ${nestedSelect(tags.slice(1))} }` : "true";
695
+ function genDeepProbe(schema, b) {
696
+ const r = refsOf(b);
697
+ const singletons = new Set(schema.singletons);
698
+ const root = schema.root ?? schema.singletons[0] ?? schema.elements[0];
699
+ const rootRef = singletons.has(root) ? `{ tagName: '${root}' }` : `{ tagName: '${root}', id: 'x' }`;
700
+ const path = deepestPath(root, schema.children);
701
+ const nested = nestedSelect(path.slice(1));
702
+ const L = [
703
+ `// AUTO-GENERATED by \`dialecte coverage\` \u2014 do not edit. Deepest-path recursion probe.`,
704
+ ...r.imports,
705
+ `declare const q: ${r.query}`,
706
+ "",
707
+ `export async function _coverageDeep() {`
708
+ ];
709
+ if (path.length > 1) {
710
+ L.push(` await q.getTree(${rootRef}, { select: ${nested} })`);
711
+ L.push(` await q.findDescendants(${rootRef}, { collect: ${nested} })`);
712
+ } else {
713
+ L.push(` await q.getTree(${rootRef})`);
714
+ L.push(` await q.findDescendants(${rootRef})`);
715
+ }
716
+ L.push("}", "");
717
+ return L.join("\n");
718
+ }
719
+ function discoveryEntry(b) {
720
+ const r = refsOf(b);
721
+ return [
722
+ ...r.imports,
723
+ `declare const q: ${r.query}`,
724
+ `declare const tx: ${r.transaction}`,
725
+ `declare const doc: ${r.nullary("Document")}`,
726
+ `declare const project: ${r.nullary("Project")}`,
727
+ `export { q, tx, doc, project }`,
728
+ ""
729
+ ].join("\n");
730
+ }
731
+ function genApiProbe(b, methodPaths) {
732
+ const r = refsOf(b);
733
+ const L = [
734
+ `// AUTO-GENERATED by \`dialecte coverage\` \u2014 do not edit. Full method-surface instantiation (incl. extensions).`,
735
+ ...r.imports,
736
+ `declare const q: ${r.query}`,
737
+ `declare const tx: ${r.transaction}`,
738
+ `declare const doc: ${r.nullary("Document")}`,
739
+ `declare const project: ${r.nullary("Project")}`,
740
+ ""
741
+ ];
742
+ const refs = [];
743
+ methodPaths.forEach((p, i) => {
744
+ L.push(`export type MP_${i} = Parameters<typeof ${p}>`);
745
+ L.push(`export type MR_${i} = Awaited<ReturnType<typeof ${p}>>`);
746
+ refs.push(`MP_${i}`, `MR_${i}`);
747
+ });
748
+ L.push("", `export type CoverageApi = [${refs.join(", ")}]`, "");
749
+ return L.join("\n");
750
+ }
751
+ function genNarrowing(schema, b) {
752
+ const r = refsOf(b);
753
+ const singletons = new Set(schema.singletons);
754
+ const L = [
755
+ `// AUTO-GENERATED by \`dialecte narrowing\` \u2014 do not edit. Exhaustive narrowing assertions.`,
756
+ ...r.imports,
757
+ "",
758
+ `type Expect<T extends true> = T`,
759
+ `type Equal<A, B> =`,
760
+ ` (<T>() => T extends A ? 1 : 2) extends <T>() => T extends B ? 1 : 2 ? true : false`,
761
+ `type Includes<Member, Union> = Member extends Union ? true : false`,
762
+ `type IdOptional<E extends ${r.elementsOf}> = undefined extends ${r.generic("Ref", "E")}['id'] ? true : false`,
763
+ ""
764
+ ];
765
+ let i = 0;
766
+ const a = (body) => L.push(`type _${i++} = Expect<${body}>`);
767
+ a(`Equal<Includes<string, ${r.elementsOf}>, false>`);
768
+ a(`Includes<${r.generic("ParentsOf", r.elementsOf)}, ${r.elementsOf}>`);
769
+ a(`Includes<${r.generic("DescendantsOf", r.elementsOf)}, ${r.elementsOf}>`);
770
+ a(`Includes<'query', keyof ${r.nullary("Document")}>`);
771
+ a(`Includes<'transaction', keyof ${r.nullary("Document")}>`);
772
+ a(`Includes<'query', keyof ReturnType<${r.nullary("Project")}['openDocument']>>`);
773
+ if (schema.root) {
774
+ a(`Equal<${r.nullary("RootElementOf")}, '${schema.root}'>`);
775
+ a(`Includes<'${schema.root}', ${r.nullary("SingletonElementsOf")}>`);
776
+ }
777
+ for (const s of schema.singletons) a(`Includes<'${s}', ${r.nullary("SingletonElementsOf")}>`);
778
+ for (const e of schema.elements) {
779
+ a(`Includes<'${e}', ${r.elementsOf}>`);
780
+ a(`Equal<${r.generic("TrackedRecord", `'${e}'`)}['tagName'], '${e}'>`);
781
+ a(`Equal<IdOptional<'${e}'>, ${singletons.has(e) ? "true" : "false"}>`);
782
+ const attrs = Object.keys(schema.definition[e]?.attributes?.details ?? {});
783
+ if (attrs.length) a(`Includes<'${attrs[0]}', ${r.generic("AttributesOf", `'${e}'`)}>`);
784
+ }
785
+ for (const [p, kids] of Object.entries(schema.children))
786
+ for (const c of kids) a(`Includes<'${c}', ${r.generic("ChildrenOf", `'${p}'`)}>`);
787
+ L.push("");
788
+ return L.join("\n");
789
+ }
790
+ async function loadSchema(absConstantsDir) {
791
+ const constantsPath = join6(absConstantsDir, "constants.generated.ts");
792
+ const definitionPath = join6(absConstantsDir, "definition.generated.ts");
793
+ for (const p of [constantsPath, definitionPath])
794
+ if (!existsSync4(p)) throw new Error(`expected ${p}`);
795
+ const mod = {
796
+ ...await import(pathToFileURL(constantsPath).href),
797
+ ...await import(pathToFileURL(definitionPath).href)
798
+ };
799
+ for (const k of ["ELEMENT_NAMES", "CHILDREN", "SINGLETON_ELEMENTS", "DEFINITION"])
800
+ if (!(k in mod)) throw new Error(`${absConstantsDir} leaf files do not export ${k}`);
801
+ return {
802
+ elements: mod.ELEMENT_NAMES,
803
+ children: mod.CHILDREN,
804
+ singletons: mod.SINGLETON_ELEMENTS,
805
+ definition: mod.DEFINITION,
806
+ root: typeof mod.ROOT_ELEMENT === "string" ? mod.ROOT_ELEMENT : void 0
807
+ };
808
+ }
809
+ function generateCoverage(schema, binding, outDir, methodPaths) {
810
+ mkdirSync3(outDir, { recursive: true });
811
+ const written = [
812
+ [join6(outDir, "coverage.surface.generated.ts"), genSurface(binding)],
813
+ [join6(outDir, "coverage.calls.generated.ts"), genCalls(schema, binding)],
814
+ [join6(outDir, "coverage.deep.generated.ts"), genDeepProbe(schema, binding)],
815
+ [join6(outDir, "baseline.ts"), genBaseline(binding)]
816
+ ];
817
+ if (methodPaths)
818
+ written.push([join6(outDir, "coverage.api.generated.ts"), genApiProbe(binding, methodPaths)]);
819
+ for (const [path, content] of written) writeFileSync4(path, content);
820
+ const edges = Object.values(schema.children).reduce((a, v) => a + (v?.length ?? 0), 0);
821
+ console.log(`coverage: ${schema.elements.length} elements, ${edges} child edges \u2192 ${outDir}`);
822
+ return written.map(([path]) => path);
823
+ }
824
+ async function run3(argv) {
825
+ const targets = resolveTargets(argv);
826
+ if (!targets.length)
827
+ throw new Error(
828
+ 'coverage: no dialect versions discovered (src/<version>/definition/*.generated.ts). Pass --constants-dir, or add a "dialecte" config.'
829
+ );
830
+ const fmt = formatOptsFromArgv(argv);
831
+ const tsconfig = tsconfigOf(argv);
832
+ for (const t of targets) {
833
+ const schema = await loadSchema(resolve(process.cwd(), t.constantsDir));
834
+ console.log(`[${t.version}]`);
835
+ let methodPaths;
836
+ try {
837
+ methodPaths = discoverMethodPaths(discoveryEntry(t.binding), tsconfig, process.cwd());
838
+ } catch {
839
+ console.warn(
840
+ ` \u26A0 [${t.version}] method-surface discovery failed \u2014 skipping coverage.api probe`
841
+ );
842
+ }
843
+ const written = generateCoverage(
844
+ schema,
845
+ t.binding,
846
+ resolve(process.cwd(), t.outDir),
847
+ methodPaths
848
+ );
849
+ formatFiles(process.cwd(), written, fmt);
850
+ }
851
+ }
852
+
853
+ // src/commands/narrowing.ts
854
+ import { spawnSync as spawnSync3 } from "child_process";
855
+ import { writeFileSync as writeFileSync5, mkdirSync as mkdirSync4, rmSync as rmSync4, existsSync as existsSync5 } from "fs";
856
+ import { join as join7, resolve as resolve2 } from "path";
857
+ async function run4(argv) {
858
+ const ROOT = process.cwd();
859
+ const tsc = resolveBin("tsc", "typescript", ROOT);
860
+ if (!tsc) throw new Error("narrowing: no TypeScript compiler found (project nor @dialecte/cli).");
861
+ const tsconfig = tsconfigOf(argv);
862
+ const targets = resolveTargets(argv);
863
+ if (!targets.length)
864
+ throw new Error(
865
+ 'narrowing: no versions discovered. Pass --constants-dir, or add a "dialecte" config.'
866
+ );
867
+ let failed = false;
868
+ for (const t of targets) {
869
+ const schema = await loadSchema(resolve2(ROOT, t.constantsDir));
870
+ mkdirSync4(resolve2(ROOT, t.outDir), { recursive: true });
871
+ const relFile = `${t.outDir}/narrowing.generated.test-d.ts`;
872
+ writeFileSync5(join7(ROOT, relFile), genNarrowing(schema, t.binding));
873
+ const apiFile = `${t.outDir}/coverage.api.generated.ts`;
874
+ const include = existsSync5(join7(ROOT, apiFile)) ? [relFile, apiFile] : [relFile];
875
+ const tmp = `.narrow-${t.version}.tsconfig.json`;
876
+ writeFileSync5(
877
+ join7(ROOT, tmp),
878
+ JSON.stringify({
879
+ extends: `./${tsconfig}`,
880
+ compilerOptions: {
881
+ noEmit: true,
882
+ skipLibCheck: true,
883
+ rootDir: ".",
884
+ declaration: false,
885
+ declarationMap: false,
886
+ emitDeclarationOnly: false
887
+ },
888
+ include
889
+ })
890
+ );
891
+ const res = spawnSync3(tsc.path, ["-p", tmp, "--noEmit"], {
892
+ cwd: ROOT,
893
+ encoding: "utf8",
894
+ maxBuffer: 1e8
895
+ });
896
+ rmSync4(join7(ROOT, tmp), { force: true });
897
+ if (res.status === 0) {
898
+ console.log(`\u2705 [${t.version}] narrowing holds \u2014 ${schema.elements.length} elements asserted`);
899
+ } else {
900
+ failed = true;
901
+ console.error(
902
+ `\u274C [${t.version}] narrowing assertion(s) failed:
903
+ ${res.stdout || ""}${res.stderr || ""}`
904
+ );
905
+ }
906
+ }
907
+ if (failed) process.exit(1);
908
+ }
909
+
910
+ // src/cli.ts
911
+ var COMMANDS = {
912
+ coverage: run3,
913
+ bench: run2,
914
+ narrowing: run4,
915
+ audit: run
916
+ };
917
+ var HELP = `
918
+ dialecte \u2014 TypeScript type-performance & readability tooling for Dialecte dialects
919
+
920
+ Usage:
921
+ dialecte <command> [options]
922
+
923
+ Commands:
924
+ coverage Generate type-coverage probes (surface + valid calls + deep + full method surface incl. extensions)
925
+ bench Measure type-instantiation cost (tsc --extendedDiagnostics); --check to gate CI
926
+ narrowing Gate: assert schema-derived type narrowing still holds (IntelliSense safety net)
927
+ audit Render the public type surface and flag readability issues (C1\u2013C6)
928
+
929
+ Zero-config: namespace = capitalized package name, versions discovered from src/<version>/definition/.
930
+ Core is detected by package name and benched via a built-in test dialect. Override per package.json
931
+ "dialecte" field (odd layouts) or CLI flags:
932
+ --namespace <Name> --entry <import> --constants-dir <dir> --out <dir> --version <v> --tsconfig <f>
933
+
934
+ Emitted files are formatted with the consumer's oxfmt (matches that package's style):
935
+ --format-config <path> oxfmt config to use (default: auto-discover the nearest .oxfmtrc)
936
+ --no-format skip formatting the generated output
937
+
938
+ Examples:
939
+ dialecte coverage # regenerate the coverage probes
940
+ dialecte bench # measure + write benchmarks/types/baseline.json
941
+ dialecte bench --check # CI gate: fail on >5% instantiation regression
942
+ dialecte audit # write benchmarks/types/readability-audit.md
943
+
944
+ Env: RUNS=5 dialecte bench (repetitions for the min); COVERAGE_CHILD_CAP=N (cap edges)
945
+ `;
946
+ async function main() {
947
+ const [cmd, ...rest] = process.argv.slice(2);
948
+ if (!cmd || cmd === "--help" || cmd === "-h") {
949
+ console.log(HELP.trim());
950
+ return;
951
+ }
952
+ const fn = COMMANDS[cmd];
953
+ if (!fn) {
954
+ console.error(`dialecte: unknown command "${cmd}"
955
+ `);
956
+ console.log(HELP.trim());
957
+ process.exit(1);
958
+ }
959
+ await fn(rest);
960
+ }
961
+ main().catch((e) => {
962
+ console.error(e instanceof Error ? e.message : e);
963
+ process.exit(1);
964
+ });
package/package.json ADDED
@@ -0,0 +1,47 @@
1
+ {
2
+ "name": "@dialecte/cli",
3
+ "version": "0.0.1",
4
+ "description": "Dialecte CLI",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/dialecte/cli.git"
9
+ },
10
+ "bin": {
11
+ "dialecte": "./dist/cli.js"
12
+ },
13
+ "files": [
14
+ "dist",
15
+ "README.md"
16
+ ],
17
+ "type": "module",
18
+ "scripts": {
19
+ "build": "tsup",
20
+ "dev": "tsup --watch",
21
+ "type-check": "tsc --noEmit",
22
+ "lint:check": "oxlint",
23
+ "lint:fix": "oxlint . --fix -D correctness --ignore-path .gitignore",
24
+ "format:check": "oxfmt --check",
25
+ "format:fix": "oxfmt",
26
+ "test": "vitest",
27
+ "test:run": "vitest run",
28
+ "check": "npm run type-check && npm run lint:check && npm run format:check && npm run test:run",
29
+ "prepublishOnly": "npm run build"
30
+ },
31
+ "dependencies": {
32
+ "oxfmt": "^0.53.0"
33
+ },
34
+ "devDependencies": {
35
+ "@types/node": "^22.0.0",
36
+ "oxlint": "^1.68.0",
37
+ "tsup": "^8.5.1",
38
+ "typescript": "^6.0.3",
39
+ "vitest": "^4.1.8"
40
+ },
41
+ "peerDependencies": {
42
+ "typescript": ">=5.4"
43
+ },
44
+ "engines": {
45
+ "node": ">=20"
46
+ }
47
+ }