carrick 0.3.139 → 0.3.141
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/package.json +6 -6
- package/plugin/.claude-plugin/plugin.json +1 -1
- package/sidecar/dist/src/argument-modes.d.ts +56 -0
- package/sidecar/dist/src/argument-modes.js +448 -0
- package/sidecar/dist/src/capture/api.d.ts +11 -0
- package/sidecar/dist/src/capture/self-check.js +131 -1
- package/sidecar/dist/src/index.js +13 -20
- package/sidecar/dist/src/infer-cache.d.ts +0 -8
- package/sidecar/dist/src/infer-cache.js +0 -14
- package/sidecar/dist/src/library-claims.js +4 -3
- package/sidecar/dist/src/loop-element.d.ts +58 -0
- package/sidecar/dist/src/loop-element.js +307 -0
- package/sidecar/dist/src/origin.d.ts +10 -7
- package/sidecar/dist/src/origin.js +10 -7
- package/sidecar/dist/src/program-files.d.ts +34 -11
- package/sidecar/dist/src/program-files.js +52 -10
- package/sidecar/dist/src/project-loader.js +9 -0
- package/sidecar/dist/src/response-modes.d.ts +7 -2
- package/sidecar/dist/src/response-modes.js +1 -1
- package/sidecar/dist/src/retype-deferred.d.ts +34 -0
- package/sidecar/dist/src/retype-deferred.js +326 -0
- package/sidecar/dist/src/retype-selector.d.ts +43 -0
- package/sidecar/dist/src/retype-selector.js +217 -0
- package/sidecar/dist/src/retype.d.ts +11 -2
- package/sidecar/dist/src/retype.js +39 -14
- package/sidecar/dist/src/type-inferrer.d.ts +43 -7
- package/sidecar/dist/src/type-inferrer.js +232 -11
- package/sidecar/dist/src/types.d.ts +21 -1
- package/sidecar/dist/src/validators.d.ts +25 -12
- package/sidecar/dist/src/validators.js +2 -0
- package/templates/skills/carrick-reuse.md +1 -1
|
@@ -32,11 +32,14 @@
|
|
|
32
32
|
* service-wide bucket.
|
|
33
33
|
*/
|
|
34
34
|
import ts from 'typescript';
|
|
35
|
+
import { createHash } from 'node:crypto';
|
|
35
36
|
import * as fs from 'node:fs';
|
|
36
37
|
import * as path from 'node:path';
|
|
38
|
+
import { findAugmentationFiles } from './augmentations.js';
|
|
37
39
|
import { sidecarCompilerOptions } from './compiler-options.js';
|
|
38
40
|
import { collectSpecifiers, declarationCandidates, isDeclarationFileName, isRelative, packageNameOf, } from './specifiers.js';
|
|
39
41
|
import { repairDanglingImports } from './repair-dangling.js';
|
|
42
|
+
import { RESOLUTION_FILE } from './resolution-edges.js';
|
|
40
43
|
import { findDisqualifyingTopTypes, findUnresolvedPlaceholders, isErrorPlaceholder, provenanceOf, unemittedModuleProvenance, unresolvedInTreeProvenance, } from './deep-walk.js';
|
|
41
44
|
/** The records of each surface, in `args.surfaces` order. */
|
|
42
45
|
export function selfCheckStub(args) {
|
|
@@ -188,10 +191,13 @@ function runSelfCheck(args, treeFiles, repaired) {
|
|
|
188
191
|
}
|
|
189
192
|
// Per-file relative-import adjacency for closure walks.
|
|
190
193
|
const adjacency = new Map();
|
|
194
|
+
const textOf = new Map();
|
|
195
|
+
const hashAdjacency = new Map();
|
|
191
196
|
const treeSet = new Set(treeFiles.map((f) => path.resolve(f)));
|
|
192
197
|
for (const file of treeFiles) {
|
|
193
198
|
const abs = path.resolve(file);
|
|
194
199
|
const text = fs.readFileSync(abs, 'utf8');
|
|
200
|
+
textOf.set(abs, text);
|
|
195
201
|
const neighbors = [];
|
|
196
202
|
for (const spec of collectSpecifiers(text)) {
|
|
197
203
|
const resolved = resolveTreeSpecifier(abs, spec, treeSet);
|
|
@@ -199,7 +205,21 @@ function runSelfCheck(args, treeFiles, repaired) {
|
|
|
199
205
|
neighbors.push(resolved);
|
|
200
206
|
}
|
|
201
207
|
adjacency.set(abs, neighbors);
|
|
208
|
+
// The hash's closure (carrick#3135) also follows what `collectSpecifiers`
|
|
209
|
+
// does not read: `import x = require("./y")` and reference paths. It
|
|
210
|
+
// must hold every file the judge loads for the alias.
|
|
211
|
+
const more = [];
|
|
212
|
+
for (const re of [/require\s*\(\s*["']([^"']+)["']/g, /<reference\s+path\s*=\s*["']([^"']+)["']/g]) {
|
|
213
|
+
for (const m of text.matchAll(re)) {
|
|
214
|
+
const resolved = resolveTreeSpecifier(abs, m[1], treeSet) ??
|
|
215
|
+
(treeSet.has(path.resolve(path.dirname(abs), m[1])) ? path.resolve(path.dirname(abs), m[1]) : undefined);
|
|
216
|
+
if (resolved)
|
|
217
|
+
more.push(resolved);
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
hashAdjacency.set(abs, [...neighbors, ...more]);
|
|
202
221
|
}
|
|
222
|
+
const judgeInputs = stubJudgeInputs(args, program, textOf, [...surfaceAt.keys()]);
|
|
203
223
|
// Demotions (failureReason present) never reached the surface with a real
|
|
204
224
|
// type; everything else — including successful literal anchors, which sit
|
|
205
225
|
// at the structural_fallback TIER but did produce text — is classified by
|
|
@@ -215,6 +235,9 @@ function runSelfCheck(args, treeFiles, repaired) {
|
|
|
215
235
|
adjacency,
|
|
216
236
|
failuresByFile,
|
|
217
237
|
surfaceFailuresByAlias: surface.surfaceFailuresByAlias,
|
|
238
|
+
textOf,
|
|
239
|
+
hashAdjacency,
|
|
240
|
+
judgeInputs,
|
|
218
241
|
})));
|
|
219
242
|
const internalFailuresByFile = new Map();
|
|
220
243
|
for (const [file, failures] of failuresByFile) {
|
|
@@ -336,10 +359,12 @@ function checkedRecord(anchor, ctx) {
|
|
|
336
359
|
// publishes is this tree, so the record says where it does not resolve.
|
|
337
360
|
let unresolvedPaths = [];
|
|
338
361
|
const seeds = [];
|
|
362
|
+
let statementText;
|
|
339
363
|
if (ctx.surfaceSource) {
|
|
340
364
|
for (const stmt of ctx.surfaceSource.statements) {
|
|
341
365
|
if (!ts.isTypeAliasDeclaration(stmt) || stmt.name.text !== alias)
|
|
342
366
|
continue;
|
|
367
|
+
statementText = stmt.getText(ctx.surfaceSource);
|
|
343
368
|
const type = ctx.checker.getTypeAtLocation(stmt.name);
|
|
344
369
|
topType =
|
|
345
370
|
(type.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown | ts.TypeFlags.Never)) !== 0;
|
|
@@ -474,7 +499,7 @@ function checkedRecord(anchor, ctx) {
|
|
|
474
499
|
detail = unresolvedExternalDetail(blamedExternal);
|
|
475
500
|
}
|
|
476
501
|
}
|
|
477
|
-
|
|
502
|
+
const record = {
|
|
478
503
|
alias,
|
|
479
504
|
anchor_kind: anchor.request.kind,
|
|
480
505
|
symbol_name: 'symbol_name' in anchor.request ? anchor.request.symbol_name : undefined,
|
|
@@ -507,6 +532,111 @@ function checkedRecord(anchor, ctx) {
|
|
|
507
532
|
: {}),
|
|
508
533
|
...literalMarks(anchor.request),
|
|
509
534
|
};
|
|
535
|
+
return statementText === undefined
|
|
536
|
+
? record
|
|
537
|
+
: {
|
|
538
|
+
...record,
|
|
539
|
+
surface_hash: surfaceHash(record, statementText, closure, ctx),
|
|
540
|
+
};
|
|
541
|
+
}
|
|
542
|
+
/**
|
|
543
|
+
* A tree file in global scope reaches every alias the judge loads beside
|
|
544
|
+
* it, closure or not: a script (no import or export), a file that declares
|
|
545
|
+
* a global or module augmentation, and a file with a reference directive.
|
|
546
|
+
*/
|
|
547
|
+
function stubJudgeInputs(args, program, textOf, surfaces) {
|
|
548
|
+
const augmenting = new Set(findAugmentationFiles([...textOf.keys()]).map((f) => path.resolve(f)));
|
|
549
|
+
const globals = [];
|
|
550
|
+
for (const [abs, text] of textOf) {
|
|
551
|
+
if (surfaces.includes(abs))
|
|
552
|
+
continue;
|
|
553
|
+
const source = program.getSourceFile(abs);
|
|
554
|
+
const global = augmenting.has(abs) ||
|
|
555
|
+
/^\s*\/\/\/\s*<reference\b/m.test(text) ||
|
|
556
|
+
(source !== undefined && !ts.isExternalModule(source));
|
|
557
|
+
if (global)
|
|
558
|
+
globals.push([stubRelative(args.stubDir, abs), text]);
|
|
559
|
+
}
|
|
560
|
+
globals.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
|
|
561
|
+
const surfaceRest = new Map();
|
|
562
|
+
for (const surface of surfaces) {
|
|
563
|
+
const source = program.getSourceFile(surface);
|
|
564
|
+
surfaceRest.set(surface, [
|
|
565
|
+
...(source?.statements ?? [])
|
|
566
|
+
.filter((stmt) => !ts.isTypeAliasDeclaration(stmt))
|
|
567
|
+
.map((stmt) => stmt.getText(source)),
|
|
568
|
+
...(source?.referencedFiles ?? []).map((ref) => `path:${ref.fileName}`),
|
|
569
|
+
...(source?.typeReferenceDirectives ?? []).map((ref) => `types:${ref.fileName}`),
|
|
570
|
+
...(source?.libReferenceDirectives ?? []).map((ref) => `lib:${ref.fileName}`),
|
|
571
|
+
]);
|
|
572
|
+
}
|
|
573
|
+
let resolution = null;
|
|
574
|
+
try {
|
|
575
|
+
resolution = fs.readFileSync(path.join(args.stubDir, RESOLUTION_FILE), 'utf8');
|
|
576
|
+
}
|
|
577
|
+
catch {
|
|
578
|
+
// No recorded edges: the check resolves every transitive from the registry.
|
|
579
|
+
}
|
|
580
|
+
return {
|
|
581
|
+
surfaceRest,
|
|
582
|
+
globals,
|
|
583
|
+
pinned: Object.entries(args.pinned).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)),
|
|
584
|
+
resolution,
|
|
585
|
+
bareCheckout: args.bareCheckout,
|
|
586
|
+
};
|
|
587
|
+
}
|
|
588
|
+
function stubRelative(stubDir, abs) {
|
|
589
|
+
return path.relative(stubDir, abs).split(path.sep).join('/');
|
|
590
|
+
}
|
|
591
|
+
/**
|
|
592
|
+
* carrick#3135: the hash of everything the judge reads for one alias from its
|
|
593
|
+
* stub. No machine path enters it, so two scans of one tree at different
|
|
594
|
+
* checkout paths hash alike. File-granular: the closure's files are hashed
|
|
595
|
+
* whole, so an unrelated declaration in a reached file moves the hash (fails
|
|
596
|
+
* toward judging). A closure file that imports the surface itself reaches
|
|
597
|
+
* every alias, so the whole surface is hashed then.
|
|
598
|
+
*/
|
|
599
|
+
function surfaceHash(record, statementText, closure, ctx) {
|
|
600
|
+
const reached = new Set(closure);
|
|
601
|
+
const queue = [...closure].filter((file) => file !== ctx.surfaceAbs);
|
|
602
|
+
while (queue.length > 0) {
|
|
603
|
+
for (const next of ctx.hashAdjacency.get(queue.pop()) ?? []) {
|
|
604
|
+
if (reached.has(next))
|
|
605
|
+
continue;
|
|
606
|
+
reached.add(next);
|
|
607
|
+
queue.push(next);
|
|
608
|
+
}
|
|
609
|
+
}
|
|
610
|
+
const files = [];
|
|
611
|
+
let surfaceReached = false;
|
|
612
|
+
for (const file of reached) {
|
|
613
|
+
if (file === ctx.surfaceAbs)
|
|
614
|
+
continue;
|
|
615
|
+
if ((ctx.hashAdjacency.get(file) ?? []).includes(ctx.surfaceAbs))
|
|
616
|
+
surfaceReached = true;
|
|
617
|
+
files.push([stubRelative(ctx.args.stubDir, file), ctx.textOf.get(file) ?? '']);
|
|
618
|
+
}
|
|
619
|
+
files.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
|
|
620
|
+
const inputs = ctx.judgeInputs;
|
|
621
|
+
const preimage = {
|
|
622
|
+
statement: statementText,
|
|
623
|
+
surface_rest: inputs.surfaceRest.get(ctx.surfaceAbs) ?? [],
|
|
624
|
+
whole_surface: surfaceReached ? (ctx.textOf.get(ctx.surfaceAbs) ?? '') : null,
|
|
625
|
+
files,
|
|
626
|
+
globals: inputs.globals,
|
|
627
|
+
pinned: inputs.pinned,
|
|
628
|
+
resolution: inputs.resolution,
|
|
629
|
+
bare_checkout: inputs.bareCheckout,
|
|
630
|
+
// The record fields the check reads (`check.ts`): the pre-gate's
|
|
631
|
+
// findings, and the two marks a probe is built from.
|
|
632
|
+
any_provenance: (record.any_provenance ?? []).map((p) => [p.path, p.kind, p.reason]),
|
|
633
|
+
raw_text_read: record.raw_text_read === true,
|
|
634
|
+
absent_body_tolerated: record.absent_body_tolerated === true,
|
|
635
|
+
};
|
|
636
|
+
return createHash('sha256')
|
|
637
|
+
.update('carrick-surface/1\n')
|
|
638
|
+
.update(JSON.stringify(preimage))
|
|
639
|
+
.digest('hex');
|
|
510
640
|
}
|
|
511
641
|
/** Resolve a relative specifier from `fromAbs` to a tree file, if present. */
|
|
512
642
|
function resolveTreeSpecifier(fromAbs, spec, tree) {
|
|
@@ -30,7 +30,7 @@ import { readServerLabels } from './server-labels.js';
|
|
|
30
30
|
import { PROGRESS_INTERVAL_MS, atMostEvery } from './progress.js';
|
|
31
31
|
import { mergeInferTimings } from './infer-timing.js';
|
|
32
32
|
import { addProgramFiles, listProgramFiles } from './program-files.js';
|
|
33
|
-
import { changedSource, inferCacheDir, keepable, programDifference, programRecord,
|
|
33
|
+
import { changedSource, inferCacheDir, keepable, programDifference, programRecord, readEntry, requestDigest, writeEntry, } from './infer-cache.js';
|
|
34
34
|
import { writePositionRows } from './position-rows.js';
|
|
35
35
|
import { findImplementations } from './implementations.js';
|
|
36
36
|
import { importGraphOf, mergeGraphs, reach, serialiseGraph } from './affected-set.js';
|
|
@@ -433,11 +433,10 @@ function inferAnswerKey(request, groups) {
|
|
|
433
433
|
/**
|
|
434
434
|
* carrick#2843: the kept answer for `key` when every program it was read in
|
|
435
435
|
* is, built again now, the same program. Each is built from its tsconfig and
|
|
436
|
-
* given the roots the kept one had, in order
|
|
437
|
-
*
|
|
438
|
-
* left. A program that does not match is dropped
|
|
439
|
-
*
|
|
440
|
-
* cache.
|
|
436
|
+
* given the roots the kept one had, in order. A rebuild does not change a
|
|
437
|
+
* program's roots (carrick#3146), so a match leaves the program the inference
|
|
438
|
+
* would have left. A program that does not match is dropped again, so the
|
|
439
|
+
* inference that follows builds it as it would have with no cache.
|
|
441
440
|
*/
|
|
442
441
|
function servedAnswer(key) {
|
|
443
442
|
const entry = readEntry(key);
|
|
@@ -463,14 +462,7 @@ function servedAnswer(key) {
|
|
|
463
462
|
});
|
|
464
463
|
if (!same)
|
|
465
464
|
break;
|
|
466
|
-
|
|
467
|
-
if (now.roots.length < kept.roots.length) {
|
|
468
|
-
// The inference's own rewrites rebuilt the program after its first
|
|
469
|
-
// build, and a rebuild names every file the first one reached as a
|
|
470
|
-
// root. Rebuilt once more here, it names the same.
|
|
471
|
-
rebuildProgram(project);
|
|
472
|
-
now = programRecord(kept.key, project);
|
|
473
|
-
}
|
|
465
|
+
const now = programRecord(kept.key, project);
|
|
474
466
|
const difference = programDifference(kept, now);
|
|
475
467
|
if (difference) {
|
|
476
468
|
same = false;
|
|
@@ -581,20 +573,21 @@ function handleRetypeCheck(request) {
|
|
|
581
573
|
function handleRetypePrescreen(request) {
|
|
582
574
|
try {
|
|
583
575
|
const groups = byProject(request.items.map((item, index) => ({ item, index })), ({ item }) => item.file_path);
|
|
584
|
-
const
|
|
576
|
+
const answers = new Array(request.items.length);
|
|
585
577
|
for (const [key, entries] of groups) {
|
|
586
578
|
projectComponents(key)
|
|
587
579
|
.retyper.prescreen(entries.map(({ item }) => item))
|
|
588
|
-
.forEach((
|
|
589
|
-
|
|
580
|
+
.forEach((answer, position) => {
|
|
581
|
+
answers[entries[position].index] = answer;
|
|
590
582
|
});
|
|
591
583
|
}
|
|
592
584
|
return {
|
|
593
585
|
request_id: request.request_id,
|
|
594
586
|
status: 'success',
|
|
595
|
-
prescreens: request.items.map((item, index) =>
|
|
596
|
-
|
|
597
|
-
|
|
587
|
+
prescreens: request.items.map((item, index) => ({
|
|
588
|
+
item_id: item.item_id,
|
|
589
|
+
...answers[index],
|
|
590
|
+
})),
|
|
598
591
|
};
|
|
599
592
|
}
|
|
600
593
|
catch (err) {
|
|
@@ -109,14 +109,6 @@ export declare function programRecord(key: string, project: Project): ProgramRec
|
|
|
109
109
|
* this.
|
|
110
110
|
*/
|
|
111
111
|
export declare function changedSource(kept: ProgramRecord): string | undefined;
|
|
112
|
-
/**
|
|
113
|
-
* Build `project`'s program again with nothing in it changed. ts-morph builds
|
|
114
|
-
* a program only after a change, and roots it at every file the project has
|
|
115
|
-
* loaded, the ones earlier builds reached among them: a program built again
|
|
116
|
-
* after its first build has more roots than the first. Setting one file's
|
|
117
|
-
* text to the text it has is the change.
|
|
118
|
-
*/
|
|
119
|
-
export declare function rebuildProgram(project: Project): void;
|
|
120
112
|
/**
|
|
121
113
|
* Keep `answer` for `key`, read in `programs`. Written to a temporary file
|
|
122
114
|
* and renamed, so a reader never sees half an entry. Entries not written to
|
|
@@ -194,20 +194,6 @@ export function changedSource(kept) {
|
|
|
194
194
|
}
|
|
195
195
|
return undefined;
|
|
196
196
|
}
|
|
197
|
-
/**
|
|
198
|
-
* Build `project`'s program again with nothing in it changed. ts-morph builds
|
|
199
|
-
* a program only after a change, and roots it at every file the project has
|
|
200
|
-
* loaded, the ones earlier builds reached among them: a program built again
|
|
201
|
-
* after its first build has more roots than the first. Setting one file's
|
|
202
|
-
* text to the text it has is the change.
|
|
203
|
-
*/
|
|
204
|
-
export function rebuildProgram(project) {
|
|
205
|
-
const file = project.getSourceFiles()[0];
|
|
206
|
-
if (!file)
|
|
207
|
-
return;
|
|
208
|
-
file.replaceWithText(file.getFullText());
|
|
209
|
-
project.getProgram().compilerObject;
|
|
210
|
-
}
|
|
211
197
|
/**
|
|
212
198
|
* Keep `answer` for `key`, read in `programs`. Written to a temporary file
|
|
213
199
|
* and renamed, so a reader never sees half an entry. Entries not written to
|
|
@@ -1540,9 +1540,10 @@ class DeclarationReader {
|
|
|
1540
1540
|
* installed dependency. A `paths` alias to the service's own code, or a
|
|
1541
1541
|
* `declare module` block the service writes, stands in for the package and
|
|
1542
1542
|
* says nothing about it (`module_local`). The resolver's flag is read, not
|
|
1543
|
-
* `program.isSourceFileFromExternalLibrary`:
|
|
1544
|
-
* dependency
|
|
1545
|
-
*
|
|
1543
|
+
* `program.isSourceFileFromExternalLibrary`: a program names a
|
|
1544
|
+
* dependency a project loaded itself (a file added through the project API)
|
|
1545
|
+
* as a root file, and the program does not call a root file external. The
|
|
1546
|
+
* loader's own rebuilds no longer add dependencies to the roots (carrick#3146). `resolved_file` and `installed_version` both
|
|
1546
1547
|
* come from that one agreeing answer.
|
|
1547
1548
|
*/
|
|
1548
1549
|
readModule(pkg, declaration, runtimeModules = false) {
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A route registered once per element of a constant list (carrick#1029).
|
|
3
|
+
*
|
|
4
|
+
* ```ts
|
|
5
|
+
* for (const [path, key] of [['a', 'alpha'], ['b', 'beta']] as const) {
|
|
6
|
+
* app.get(`/items/${path}`, async () => ({ items: rows()[key] }));
|
|
7
|
+
* }
|
|
8
|
+
* ```
|
|
9
|
+
*
|
|
10
|
+
* One handler serves two operations, `/items/a` and `/items/b`. Typed as
|
|
11
|
+
* written, `key` is `'alpha' | 'beta'`, so each operation's response is the
|
|
12
|
+
* union of both payloads, and a consumer of `/items/a` reads as mismatched.
|
|
13
|
+
*
|
|
14
|
+
* The scanner sends the row's own path (`route_path`) on a route row's
|
|
15
|
+
* request when its line serves more than one operation. This reads, from the
|
|
16
|
+
* syntax and the compiler's symbols only, which element of the list the path
|
|
17
|
+
* names, and returns the rewrite that makes the list that one element. The
|
|
18
|
+
* inferrer then types the same handler in the rewritten file: the compiler
|
|
19
|
+
* infers the response for that element, and no rule of ours decides it.
|
|
20
|
+
*
|
|
21
|
+
* Read only when every piece is stated:
|
|
22
|
+
*
|
|
23
|
+
* - the registration's path argument is a template whose every hole is a name
|
|
24
|
+
* one loop binds: a `for (const … of LIST)` or `LIST.forEach((…) => …)`
|
|
25
|
+
* around the registration, binding a name or an array pattern of names;
|
|
26
|
+
* - `LIST` is an array literal (through parentheses, `as const` and
|
|
27
|
+
* `satisfies`), or a `const` bound to one that nothing in its file mutates,
|
|
28
|
+
* or that is `as const`;
|
|
29
|
+
* - every element is a string, or an array of strings at the positions the
|
|
30
|
+
* holes read, with no spread;
|
|
31
|
+
* - exactly one element's path is the row's path, segment by segment from
|
|
32
|
+
* the end, a parameter matching a parameter of any name.
|
|
33
|
+
*
|
|
34
|
+
* Anything else returns `undefined`, and the request is typed as before.
|
|
35
|
+
*/
|
|
36
|
+
import { Node, type SourceFile } from 'ts-morph';
|
|
37
|
+
/** The rewrite that leaves only the picked element in the list. */
|
|
38
|
+
export interface LoopPick {
|
|
39
|
+
file: SourceFile;
|
|
40
|
+
/** The list expression's span in the file's original text. */
|
|
41
|
+
start: number;
|
|
42
|
+
end: number;
|
|
43
|
+
/** What replaces it. Holds no more newlines than the text it replaces. */
|
|
44
|
+
text: string;
|
|
45
|
+
/** Which element, of how many. */
|
|
46
|
+
index: number;
|
|
47
|
+
of: number;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* The element of the list `registration` is made once for that `routePath`
|
|
51
|
+
* names, or `undefined` when the code does not state it.
|
|
52
|
+
*/
|
|
53
|
+
export declare function loopElementPick(registration: Node, routePath: string): LoopPick | undefined;
|
|
54
|
+
/**
|
|
55
|
+
* Whether `full` ends with `own`, segment by segment: the row's path holds
|
|
56
|
+
* the route's own path after whatever prefix its mounts add.
|
|
57
|
+
*/
|
|
58
|
+
export declare function endsWithPath(full: string, own: string): boolean;
|
|
@@ -0,0 +1,307 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A route registered once per element of a constant list (carrick#1029).
|
|
3
|
+
*
|
|
4
|
+
* ```ts
|
|
5
|
+
* for (const [path, key] of [['a', 'alpha'], ['b', 'beta']] as const) {
|
|
6
|
+
* app.get(`/items/${path}`, async () => ({ items: rows()[key] }));
|
|
7
|
+
* }
|
|
8
|
+
* ```
|
|
9
|
+
*
|
|
10
|
+
* One handler serves two operations, `/items/a` and `/items/b`. Typed as
|
|
11
|
+
* written, `key` is `'alpha' | 'beta'`, so each operation's response is the
|
|
12
|
+
* union of both payloads, and a consumer of `/items/a` reads as mismatched.
|
|
13
|
+
*
|
|
14
|
+
* The scanner sends the row's own path (`route_path`) on a route row's
|
|
15
|
+
* request when its line serves more than one operation. This reads, from the
|
|
16
|
+
* syntax and the compiler's symbols only, which element of the list the path
|
|
17
|
+
* names, and returns the rewrite that makes the list that one element. The
|
|
18
|
+
* inferrer then types the same handler in the rewritten file: the compiler
|
|
19
|
+
* infers the response for that element, and no rule of ours decides it.
|
|
20
|
+
*
|
|
21
|
+
* Read only when every piece is stated:
|
|
22
|
+
*
|
|
23
|
+
* - the registration's path argument is a template whose every hole is a name
|
|
24
|
+
* one loop binds: a `for (const … of LIST)` or `LIST.forEach((…) => …)`
|
|
25
|
+
* around the registration, binding a name or an array pattern of names;
|
|
26
|
+
* - `LIST` is an array literal (through parentheses, `as const` and
|
|
27
|
+
* `satisfies`), or a `const` bound to one that nothing in its file mutates,
|
|
28
|
+
* or that is `as const`;
|
|
29
|
+
* - every element is a string, or an array of strings at the positions the
|
|
30
|
+
* holes read, with no spread;
|
|
31
|
+
* - exactly one element's path is the row's path, segment by segment from
|
|
32
|
+
* the end, a parameter matching a parameter of any name.
|
|
33
|
+
*
|
|
34
|
+
* Anything else returns `undefined`, and the request is typed as before.
|
|
35
|
+
*/
|
|
36
|
+
import { Node, SyntaxKind } from 'ts-morph';
|
|
37
|
+
import { stringLiteral } from './response-modes.js';
|
|
38
|
+
/** Methods of an array that change it in place. */
|
|
39
|
+
const MUTATORS = new Set([
|
|
40
|
+
'push',
|
|
41
|
+
'pop',
|
|
42
|
+
'shift',
|
|
43
|
+
'unshift',
|
|
44
|
+
'splice',
|
|
45
|
+
'sort',
|
|
46
|
+
'reverse',
|
|
47
|
+
'fill',
|
|
48
|
+
'copyWithin',
|
|
49
|
+
]);
|
|
50
|
+
/**
|
|
51
|
+
* The element of the list `registration` is made once for that `routePath`
|
|
52
|
+
* names, or `undefined` when the code does not state it.
|
|
53
|
+
*/
|
|
54
|
+
export function loopElementPick(registration, routePath) {
|
|
55
|
+
if (!Node.isCallExpression(registration))
|
|
56
|
+
return undefined;
|
|
57
|
+
const pathArg = registration.getArguments()[0];
|
|
58
|
+
if (!pathArg)
|
|
59
|
+
return undefined;
|
|
60
|
+
const template = unwrap(pathArg);
|
|
61
|
+
if (!Node.isTemplateExpression(template))
|
|
62
|
+
return undefined;
|
|
63
|
+
const holes = template.getTemplateSpans().map((span) => span.getExpression());
|
|
64
|
+
if (holes.length === 0 || !holes.every((hole) => Node.isIdentifier(hole)))
|
|
65
|
+
return undefined;
|
|
66
|
+
const loop = enclosingLoop(registration, holes);
|
|
67
|
+
if (!loop)
|
|
68
|
+
return undefined;
|
|
69
|
+
const positions = holes.map((hole) => {
|
|
70
|
+
const declared = hole.getSymbol()?.getDeclarations()[0];
|
|
71
|
+
const name = declared && declarationName(declared);
|
|
72
|
+
return name ? loop.bound.get(name) : undefined;
|
|
73
|
+
});
|
|
74
|
+
if (positions.some((position) => position === undefined))
|
|
75
|
+
return undefined;
|
|
76
|
+
const elements = listElements(loop.list);
|
|
77
|
+
if (!elements || elements.length < 2)
|
|
78
|
+
return undefined;
|
|
79
|
+
const values = [];
|
|
80
|
+
for (const element of elements) {
|
|
81
|
+
const read = positions.map((position) => elementValue(element, position));
|
|
82
|
+
if (read.some((value) => value === undefined))
|
|
83
|
+
return undefined;
|
|
84
|
+
values.push(read);
|
|
85
|
+
}
|
|
86
|
+
const head = template.getHead().getLiteralText();
|
|
87
|
+
const tails = template.getTemplateSpans().map((span) => span.getLiteral().getLiteralText());
|
|
88
|
+
const matching = values
|
|
89
|
+
.map((read, index) => ({
|
|
90
|
+
index,
|
|
91
|
+
path: head + read.map((value, at) => value + tails[at]).join(''),
|
|
92
|
+
}))
|
|
93
|
+
.filter(({ path }) => endsWithPath(routePath, path));
|
|
94
|
+
if (matching.length !== 1)
|
|
95
|
+
return undefined;
|
|
96
|
+
const { index } = matching[0];
|
|
97
|
+
const list = loop.list;
|
|
98
|
+
const original = list.getText();
|
|
99
|
+
const element = elements[index].getText();
|
|
100
|
+
const replacement = `([${element}] as const)`;
|
|
101
|
+
const extraLines = newlines(original) - newlines(replacement);
|
|
102
|
+
if (extraLines < 0)
|
|
103
|
+
return undefined;
|
|
104
|
+
return {
|
|
105
|
+
file: list.getSourceFile(),
|
|
106
|
+
start: list.getStart(),
|
|
107
|
+
end: list.getEnd(),
|
|
108
|
+
// Padded so every line after the list keeps its number.
|
|
109
|
+
text: `([${element}] as const${'\n'.repeat(extraLines)})`,
|
|
110
|
+
index,
|
|
111
|
+
of: elements.length,
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
/** `node` through parentheses, `as` and `satisfies`. */
|
|
115
|
+
function unwrap(node) {
|
|
116
|
+
let at = node;
|
|
117
|
+
for (;;) {
|
|
118
|
+
if (Node.isParenthesizedExpression(at) ||
|
|
119
|
+
Node.isAsExpression(at) ||
|
|
120
|
+
Node.isSatisfiesExpression(at) ||
|
|
121
|
+
Node.isTypeAssertion(at)) {
|
|
122
|
+
at = at.getExpression();
|
|
123
|
+
}
|
|
124
|
+
else {
|
|
125
|
+
return at;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
/** The name node a declaration binds, for a name declared by a variable, a parameter or a binding element. */
|
|
130
|
+
function declarationName(declared) {
|
|
131
|
+
if (Node.isVariableDeclaration(declared) ||
|
|
132
|
+
Node.isParameterDeclaration(declared) ||
|
|
133
|
+
Node.isBindingElement(declared)) {
|
|
134
|
+
const name = declared.getNameNode();
|
|
135
|
+
return Node.isIdentifier(name) ? name : undefined;
|
|
136
|
+
}
|
|
137
|
+
return undefined;
|
|
138
|
+
}
|
|
139
|
+
/** The names a loop's element pattern binds, with the position each reads. */
|
|
140
|
+
function boundNames(pattern) {
|
|
141
|
+
if (Node.isIdentifier(pattern))
|
|
142
|
+
return new Map([[pattern, -1]]);
|
|
143
|
+
if (!Node.isArrayBindingPattern(pattern))
|
|
144
|
+
return undefined;
|
|
145
|
+
const bound = new Map();
|
|
146
|
+
pattern.getElements().forEach((element, position) => {
|
|
147
|
+
if (Node.isOmittedExpression(element))
|
|
148
|
+
return;
|
|
149
|
+
const name = element.getNameNode();
|
|
150
|
+
if (element.getDotDotDotToken() || element.getInitializer() || !Node.isIdentifier(name))
|
|
151
|
+
return;
|
|
152
|
+
bound.set(name, position);
|
|
153
|
+
});
|
|
154
|
+
return bound;
|
|
155
|
+
}
|
|
156
|
+
/**
|
|
157
|
+
* The innermost loop around `registration` that binds every hole: a
|
|
158
|
+
* `for (const … of …)` whose body holds it, or a `.forEach` whose callback
|
|
159
|
+
* does.
|
|
160
|
+
*/
|
|
161
|
+
function enclosingLoop(registration, holes) {
|
|
162
|
+
const bindsAll = (bound) => holes.every((hole) => {
|
|
163
|
+
const declared = hole.getSymbol()?.getDeclarations()[0];
|
|
164
|
+
const name = declared && declarationName(declared);
|
|
165
|
+
return name !== undefined && bound.has(name);
|
|
166
|
+
});
|
|
167
|
+
for (const ancestor of registration.getAncestors()) {
|
|
168
|
+
if (Node.isForOfStatement(ancestor)) {
|
|
169
|
+
const init = ancestor.getInitializer();
|
|
170
|
+
if (!Node.isVariableDeclarationList(init))
|
|
171
|
+
continue;
|
|
172
|
+
if (init.getDeclarationKind() !== 'const' || init.getDeclarations().length !== 1)
|
|
173
|
+
continue;
|
|
174
|
+
const bound = boundNames(init.getDeclarations()[0].getNameNode());
|
|
175
|
+
if (bound && bindsAll(bound))
|
|
176
|
+
return { bound, list: ancestor.getExpression() };
|
|
177
|
+
continue;
|
|
178
|
+
}
|
|
179
|
+
if (Node.isArrowFunction(ancestor) || Node.isFunctionExpression(ancestor)) {
|
|
180
|
+
const call = ancestor.getParent();
|
|
181
|
+
if (!Node.isCallExpression(call) || call.getArguments()[0] !== ancestor)
|
|
182
|
+
continue;
|
|
183
|
+
const callee = call.getExpression();
|
|
184
|
+
if (!Node.isPropertyAccessExpression(callee) || callee.getName() !== 'forEach')
|
|
185
|
+
continue;
|
|
186
|
+
const param = ancestor.getParameters()[0];
|
|
187
|
+
if (!param || ancestor.getParameters().length > 1)
|
|
188
|
+
continue;
|
|
189
|
+
const bound = boundNames(param.getNameNode());
|
|
190
|
+
if (bound && bindsAll(bound))
|
|
191
|
+
return { bound, list: callee.getExpression() };
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
return undefined;
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* The elements the list is written with: an array literal, or a `const`
|
|
198
|
+
* holding one that nothing in its file changes. `undefined` for anything
|
|
199
|
+
* else, a spread included.
|
|
200
|
+
*/
|
|
201
|
+
function listElements(list) {
|
|
202
|
+
let literal = unwrap(list);
|
|
203
|
+
if (Node.isIdentifier(literal)) {
|
|
204
|
+
const declared = literal.getSymbol()?.getDeclarations()[0];
|
|
205
|
+
if (!declared || !Node.isVariableDeclaration(declared))
|
|
206
|
+
return undefined;
|
|
207
|
+
const declarationList = declared.getParent();
|
|
208
|
+
if (!Node.isVariableDeclarationList(declarationList) || declarationList.getDeclarationKind() !== 'const') {
|
|
209
|
+
return undefined;
|
|
210
|
+
}
|
|
211
|
+
const initializer = declared.getInitializer();
|
|
212
|
+
if (!initializer)
|
|
213
|
+
return undefined;
|
|
214
|
+
const readonly = hasConstAssertion(initializer);
|
|
215
|
+
if (!readonly && mutatedInItsFile(declared))
|
|
216
|
+
return undefined;
|
|
217
|
+
if (!readonly && declared.isExported())
|
|
218
|
+
return undefined;
|
|
219
|
+
literal = unwrap(initializer);
|
|
220
|
+
}
|
|
221
|
+
if (!Node.isArrayLiteralExpression(literal))
|
|
222
|
+
return undefined;
|
|
223
|
+
const elements = literal.getElements();
|
|
224
|
+
if (elements.some((element) => Node.isSpreadElement(element) || Node.isOmittedExpression(element))) {
|
|
225
|
+
return undefined;
|
|
226
|
+
}
|
|
227
|
+
return elements.map(unwrap);
|
|
228
|
+
}
|
|
229
|
+
function hasConstAssertion(node) {
|
|
230
|
+
let at = node;
|
|
231
|
+
for (;;) {
|
|
232
|
+
if (Node.isAsExpression(at)) {
|
|
233
|
+
if (at.getTypeNode()?.getText() === 'const')
|
|
234
|
+
return true;
|
|
235
|
+
at = at.getExpression();
|
|
236
|
+
}
|
|
237
|
+
else if (Node.isParenthesizedExpression(at) || Node.isSatisfiesExpression(at)) {
|
|
238
|
+
at = at.getExpression();
|
|
239
|
+
}
|
|
240
|
+
else {
|
|
241
|
+
return false;
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
/** Whether a name `declared` binds is assigned, or has a mutating method called, anywhere in its file. */
|
|
246
|
+
function mutatedInItsFile(declared) {
|
|
247
|
+
const name = declared.getNameNode();
|
|
248
|
+
const symbol = name.getSymbol();
|
|
249
|
+
if (!symbol)
|
|
250
|
+
return true;
|
|
251
|
+
for (const ident of declared.getSourceFile().getDescendantsOfKind(SyntaxKind.Identifier)) {
|
|
252
|
+
if (ident.getSymbol() !== symbol || ident === name)
|
|
253
|
+
continue;
|
|
254
|
+
const parent = ident.getParent();
|
|
255
|
+
if (Node.isBinaryExpression(parent) && parent.getLeft() === ident)
|
|
256
|
+
return true;
|
|
257
|
+
if (Node.isPropertyAccessExpression(parent) && parent.getExpression() === ident) {
|
|
258
|
+
if (MUTATORS.has(parent.getName()))
|
|
259
|
+
return true;
|
|
260
|
+
// `LIST.length = 0`, `LIST.x = …`.
|
|
261
|
+
const above = parent.getParent();
|
|
262
|
+
if (Node.isBinaryExpression(above) && above.getLeft() === parent)
|
|
263
|
+
return true;
|
|
264
|
+
}
|
|
265
|
+
if (Node.isElementAccessExpression(parent) && parent.getExpression() === ident) {
|
|
266
|
+
const above = parent.getParent();
|
|
267
|
+
if (Node.isBinaryExpression(above) && above.getLeft() === parent)
|
|
268
|
+
return true;
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
return false;
|
|
272
|
+
}
|
|
273
|
+
/** The string an element states at `position` (`-1`: the element itself). */
|
|
274
|
+
function elementValue(element, position) {
|
|
275
|
+
if (position === -1)
|
|
276
|
+
return stringLiteral(element);
|
|
277
|
+
if (!Node.isArrayLiteralExpression(element))
|
|
278
|
+
return undefined;
|
|
279
|
+
const items = element.getElements();
|
|
280
|
+
if (items.some((item) => Node.isSpreadElement(item)))
|
|
281
|
+
return undefined;
|
|
282
|
+
const item = items[position];
|
|
283
|
+
return item ? stringLiteral(unwrap(item)) : undefined;
|
|
284
|
+
}
|
|
285
|
+
/** A path segment that is a parameter, in either spelling. */
|
|
286
|
+
function isParam(segment) {
|
|
287
|
+
return segment.startsWith(':') || /^\{[^{}]*\}$/.test(segment);
|
|
288
|
+
}
|
|
289
|
+
/**
|
|
290
|
+
* Whether `full` ends with `own`, segment by segment: the row's path holds
|
|
291
|
+
* the route's own path after whatever prefix its mounts add.
|
|
292
|
+
*/
|
|
293
|
+
export function endsWithPath(full, own) {
|
|
294
|
+
const segments = (text) => text.split('/').filter((segment) => segment.length > 0);
|
|
295
|
+
const whole = segments(full);
|
|
296
|
+
const tail = segments(own);
|
|
297
|
+
if (tail.length === 0 || tail.length > whole.length)
|
|
298
|
+
return false;
|
|
299
|
+
const offset = whole.length - tail.length;
|
|
300
|
+
return tail.every((segment, at) => {
|
|
301
|
+
const other = whole[offset + at];
|
|
302
|
+
return isParam(segment) && isParam(other) ? true : segment === other;
|
|
303
|
+
});
|
|
304
|
+
}
|
|
305
|
+
function newlines(text) {
|
|
306
|
+
return text.split('\n').length - 1;
|
|
307
|
+
}
|