@tinkered/cli 0.0.0-stage → 0.27.2

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.
@@ -0,0 +1,1788 @@
1
+ import { existsSync, globSync, readFileSync } from "node:fs";
2
+ import { dirname, join, matchesGlob, resolve } from "node:path";
3
+ import ts from "typescript-api";
4
+ import { IntentCoreError, listIntentSkills, loadIntentSkill } from "@tanstack/intent/core";
5
+ import { spawnSync } from "node:child_process";
6
+ //#region src/errors.ts
7
+ /** The only place the command throws a registry error. */
8
+ function raise(kind, payload) {
9
+ throw Object.assign(new Error(kind), {
10
+ kind,
11
+ payload
12
+ });
13
+ }
14
+ /** Narrow an unknown error to one registry entry; callers rethrow on mismatch. */
15
+ function isError(value, kind) {
16
+ return value instanceof Error && value.kind === kind;
17
+ }
18
+ //#endregion
19
+ //#region src/gaps.ts
20
+ /** A marker allows the finding on the next line: `// tinker-gap: G3`, alone on its line. */
21
+ const markerLine = /^\s*\/\/ tinker-gap: (G\d+)\s*$/;
22
+ /** The rows of the doc: `## G<n>: ...`, then `- Status: open` and `- Lines: <count>`. */
23
+ function rowsOf(doc) {
24
+ const rows = /* @__PURE__ */ new Map();
25
+ let row;
26
+ for (const [index, text] of doc.split("\n").entries()) {
27
+ const head = /^## (G\d+):/.exec(text);
28
+ if (head) rows.set(head[1], row = {
29
+ line: index + 1,
30
+ open: false,
31
+ lines: 0
32
+ });
33
+ else if (text.startsWith("## ")) row = void 0;
34
+ if (!row) continue;
35
+ if (/^- Status: open\s*$/.test(text)) row.open = true;
36
+ const lines = /^- Lines: (\d+)\s*$/.exec(text);
37
+ if (lines) row.lines = Number(lines[1]);
38
+ }
39
+ return rows;
40
+ }
41
+ function markersOf({ path, text }) {
42
+ return text.split("\n").flatMap((line, index) => {
43
+ const match = markerLine.exec(line);
44
+ return match ? [{
45
+ path,
46
+ line: index + 1,
47
+ gap: match[1]
48
+ }] : [];
49
+ });
50
+ }
51
+ const broken = (path, line, what) => ({
52
+ path,
53
+ line,
54
+ rule: "tinker/gap",
55
+ what
56
+ });
57
+ /** Split findings into the ones a marker on an open row allows, and the rest. */
58
+ function allow(findings, markers, rows) {
59
+ const kept = [];
60
+ const marked = /* @__PURE__ */ new Map();
61
+ for (const finding of findings) {
62
+ const at = `${finding.path}:${finding.line}`;
63
+ const marker = markers.get(at);
64
+ if (marker && rows.get(marker.gap)?.open) marked.set(marker.gap, (marked.get(marker.gap) ?? /* @__PURE__ */ new Set()).add(at));
65
+ else kept.push(finding);
66
+ }
67
+ return {
68
+ kept,
69
+ marked
70
+ };
71
+ }
72
+ /** What is wrong with one marker: no finding below it, no row, or a closed row. */
73
+ function markerProblem(marker, found, rows, doc) {
74
+ const { path, line, gap } = marker;
75
+ const row = rows.get(gap);
76
+ if (!found.has(`${path}:${line + 1}`)) return broken(path, line, `${gap}: a marker with no finding on the next line`);
77
+ if (!row) return broken(path, line, `${gap}: no row in ${doc}`);
78
+ return row.open ? void 0 : broken(path, line, `${gap}: the row is closed`);
79
+ }
80
+ /**
81
+ * Hedl's gap rule (Duke 2026-11-04, S16), for any app that names a gaps doc. A finding is
82
+ * allowed when the line above it is a marker for an open row of the doc. The run breaks on a
83
+ * marker with no finding below it, a marker whose row is missing or closed, and a row with
84
+ * more marked lines than its count, so the count can only go down.
85
+ */
86
+ function applyGaps(findings, sources, doc) {
87
+ const rows = rowsOf(doc.text);
88
+ const list = sources.flatMap(markersOf);
89
+ const markers = new Map(list.map((marker) => [`${marker.path}:${marker.line + 1}`, marker]));
90
+ const found = new Set(findings.map(({ path, line }) => `${path}:${line}`));
91
+ const { kept, marked } = allow(findings, markers, rows);
92
+ for (const marker of list) {
93
+ const problem = markerProblem(marker, found, rows, doc.path);
94
+ if (problem) kept.push(problem);
95
+ }
96
+ const gaps = [...rows].map(([gap, { open, lines }]) => {
97
+ return {
98
+ gap,
99
+ open,
100
+ lines,
101
+ marked: marked.get(gap)?.size ?? 0
102
+ };
103
+ });
104
+ for (const { gap, lines, marked: count } of gaps) {
105
+ if (count <= lines) continue;
106
+ const what = `${gap}: ${count} marked lines, the row allows ${lines}`;
107
+ kept.push(broken(doc.path, rows.get(gap).line, what));
108
+ }
109
+ return {
110
+ findings: kept,
111
+ gaps
112
+ };
113
+ }
114
+ //#endregion
115
+ //#region src/page.ts
116
+ /** The banned hooks, by the name of the hook React exports. */
117
+ const hooks = /* @__PURE__ */ new Set([
118
+ "useEffect",
119
+ "useLayoutEffect",
120
+ "useState",
121
+ "useReducer"
122
+ ]);
123
+ /** The network constructors, by the global name a page can reach. */
124
+ const constructors = /* @__PURE__ */ new Set([
125
+ "XMLHttpRequest",
126
+ "EventSource",
127
+ "WebSocket"
128
+ ]);
129
+ /** The names a page reaches a browser global through. */
130
+ const globals = /* @__PURE__ */ new Set([
131
+ "window",
132
+ "globalThis",
133
+ "self",
134
+ "global"
135
+ ]);
136
+ function walk$1(node, visit) {
137
+ visit(node);
138
+ ts.forEachChild(node, (child) => walk$1(child, visit));
139
+ }
140
+ /** Only an `x` file holds JSX; in any other file `<T>value` is a cast. */
141
+ function kindOf(path) {
142
+ return path.endsWith("x") ? ts.ScriptKind.TSX : ts.ScriptKind.TS;
143
+ }
144
+ const wire = (node, name) => ({
145
+ node,
146
+ rule: "tinker/one-wire",
147
+ what: `\`${name}\`: a page's own network call`
148
+ });
149
+ const state = (node, name) => ({
150
+ node,
151
+ rule: "tinker/react-state",
152
+ what: `\`${name}\`: React's own state or effect`
153
+ });
154
+ /** The clause of an import from `"react"`: what it binds. */
155
+ function reactClause(statement) {
156
+ if (!ts.isImportDeclaration(statement)) return;
157
+ const from = statement.moduleSpecifier;
158
+ return ts.isStringLiteral(from) && from.text === "react" ? statement.importClause : void 0;
159
+ }
160
+ /** `import React from "react"`, `import * as React`, and `import { useEffect as watch }`. */
161
+ function readImport$1(bound, statement) {
162
+ const clause = reactClause(statement);
163
+ if (!clause) return;
164
+ const { name, namedBindings } = clause;
165
+ if (name) bound.namespaces.add(name.text);
166
+ if (!namedBindings) return;
167
+ if (ts.isNamespaceImport(namedBindings)) {
168
+ bound.namespaces.add(namedBindings.name.text);
169
+ return;
170
+ }
171
+ for (const element of namedBindings.elements) {
172
+ const hook = (element.propertyName ?? element.name).text;
173
+ if (hooks.has(hook)) bound.hooks.set(element.name.text, hook);
174
+ }
175
+ }
176
+ /** `fetch(...)`, `WebSocket(...)` with no `new`, a bound hook, or a name that reuses a hook's. */
177
+ function plainCall(bound, node) {
178
+ if (!ts.isCallExpression(node) || !ts.isIdentifier(node.expression)) return;
179
+ const name = node.expression.text;
180
+ if (constructors.has(name) || name === "fetch") return wire(node, name);
181
+ const hook = bound.hooks.get(name) ?? (hooks.has(name) ? name : void 0);
182
+ return hook ? state(node, hook) : void 0;
183
+ }
184
+ /** `new WebSocket(...)`, `new XMLHttpRequest(...)`, `new EventSource(...)`. */
185
+ function construction(node) {
186
+ if (!ts.isNewExpression(node) || !ts.isIdentifier(node.expression)) return;
187
+ const name = node.expression.text;
188
+ return constructors.has(name) ? wire(node, name) : void 0;
189
+ }
190
+ /** The member a call runs, and the name it is read from: a read of it is not a call. */
191
+ function calledMember(node) {
192
+ if (!ts.isPropertyAccessExpression(node)) return;
193
+ if (!ts.isCallExpression(node.parent) || node.parent.expression !== node) return;
194
+ const on = ts.isIdentifier(node.expression) ? node.expression.text : "";
195
+ return {
196
+ name: node.name.text,
197
+ on
198
+ };
199
+ }
200
+ /**
201
+ * A member call: `navigator.sendBeacon(...)`, `page.fetch(...)` on any object (both are the
202
+ * network whatever the receiving object is called), `window.WebSocket(...)`, `React.useState`.
203
+ * A `.useEffect` on any other object passes: only React's hooks are banned.
204
+ */
205
+ function memberCall(bound, node) {
206
+ const member = calledMember(node);
207
+ if (!member) return;
208
+ const { name, on } = member;
209
+ if (name === "sendBeacon" || name === "fetch") return wire(node, name);
210
+ if (constructors.has(name) && globals.has(on)) return wire(node, name);
211
+ return hooks.has(name) && bound.namespaces.has(on) ? state(node, name) : void 0;
212
+ }
213
+ /** The names `const { ... } = React` binds, when the right side is React itself. */
214
+ function reactPattern(bound, node) {
215
+ if (!ts.isVariableDeclaration(node) || !ts.isObjectBindingPattern(node.name)) return [];
216
+ const from = node.initializer;
217
+ return from && ts.isIdentifier(from) && bound.namespaces.has(from.text) ? node.name.elements : [];
218
+ }
219
+ /** `const { useState } = React` binds the hook under a name the import scan cannot see. */
220
+ function readDestructure(bound, node) {
221
+ for (const element of reactPattern(bound, node)) {
222
+ const key = element.propertyName ?? element.name;
223
+ if (!ts.isIdentifier(key) || !ts.isIdentifier(element.name)) continue;
224
+ if (hooks.has(key.text)) bound.hooks.set(element.name.text, key.text);
225
+ }
226
+ }
227
+ /**
228
+ * The page rules (Duke 2026-11-04). The syntax tree is walked, so text in a comment or a string
229
+ * is not a finding.
230
+ *
231
+ * `tinker/one-wire`: only the rpc client talks to the server. A finding is a call of `fetch` or
232
+ * `.fetch`, `.sendBeacon`, or `XMLHttpRequest`, `EventSource` or `WebSocket` however it is built.
233
+ *
234
+ * `tinker/react-state`: state lives in Core cells, read through `@tinkered/react`. A finding is a
235
+ * call of `useEffect`, `useLayoutEffect`, `useState` or `useReducer`, whatever name an import
236
+ * gave it. The finding is the use, not the import.
237
+ */
238
+ function findPage({ path, text }) {
239
+ const source = ts.createSourceFile(path, text, ts.ScriptTarget.Latest, true, kindOf(path));
240
+ const bound = {
241
+ namespaces: /* @__PURE__ */ new Set(),
242
+ hooks: /* @__PURE__ */ new Map()
243
+ };
244
+ for (const statement of source.statements) readImport$1(bound, statement);
245
+ const hits = [];
246
+ walk$1(source, (node) => {
247
+ const hit = plainCall(bound, node) ?? construction(node) ?? memberCall(bound, node);
248
+ if (hit) hits.push(hit);
249
+ readDestructure(bound, node);
250
+ });
251
+ return hits.map(({ node, rule, what }) => ({
252
+ path,
253
+ line: source.getLineAndCharacterOfPosition(node.getStart()).line + 1,
254
+ rule,
255
+ what
256
+ }));
257
+ }
258
+ //#endregion
259
+ //#region src/tree.ts
260
+ function isFn(node) {
261
+ return ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) || ts.isArrowFunction(node) || ts.isMethodDeclaration(node) || ts.isGetAccessorDeclaration(node) || ts.isSetAccessorDeclaration(node);
262
+ }
263
+ function walk(node, visit) {
264
+ visit(node);
265
+ ts.forEachChild(node, (child) => walk(child, visit));
266
+ }
267
+ /** Walk a body without entering the functions inside it. */
268
+ function ownWalk(node, visit) {
269
+ visit(node);
270
+ ts.forEachChild(node, (child) => {
271
+ if (!isFn(child)) ownWalk(child, visit);
272
+ });
273
+ }
274
+ /** The nearest function around a node. */
275
+ function enclosingFn(node) {
276
+ for (let parent = node.parent; parent; parent = parent.parent) if (isFn(parent)) return parent;
277
+ }
278
+ /** The outermost function around a node. */
279
+ function outermostFn(node) {
280
+ let root;
281
+ for (let owner = enclosingFn(node); owner; owner = enclosingFn(owner)) root = owner;
282
+ return root;
283
+ }
284
+ //#endregion
285
+ //#region src/closure.ts
286
+ /** The names a binding declares: `a`, `{ a, b: c }`, `[a, ...b]`. */
287
+ function bindingNames(binding, into) {
288
+ if (ts.isIdentifier(binding)) {
289
+ into.add(binding.text);
290
+ return;
291
+ }
292
+ for (const item of binding.elements) if (!ts.isOmittedExpression(item)) bindingNames(item.name, into);
293
+ }
294
+ function declares(node, into) {
295
+ if (ts.isParameter(node) || ts.isVariableDeclaration(node)) bindingNames(node.name, into);
296
+ if (ts.isFunctionDeclaration(node) && node.name) into.add(node.name.text);
297
+ }
298
+ /** The names a function declares for itself: its parameters, its locals, its inner functions. */
299
+ function ownNames(fn) {
300
+ const names = /* @__PURE__ */ new Set();
301
+ const visit = (node) => {
302
+ declares(node, names);
303
+ if (!isFn(node)) ts.forEachChild(node, visit);
304
+ };
305
+ for (const parameter of fn.parameters) bindingNames(parameter.name, names);
306
+ if (fn.body) visit(fn.body);
307
+ return names;
308
+ }
309
+ /** Every name declared inside a function, at any depth. A read of one is not a capture. */
310
+ function innerNames(fn) {
311
+ const names = /* @__PURE__ */ new Set();
312
+ walk(fn, (node) => declares(node, names));
313
+ return names;
314
+ }
315
+ /** The names the functions around this one declare. */
316
+ function outerNames(fn) {
317
+ const names = /* @__PURE__ */ new Set();
318
+ for (let owner = enclosingFn(fn); owner; owner = enclosingFn(owner)) for (const name of ownNames(owner)) names.add(name);
319
+ return names;
320
+ }
321
+ /** A name in a place that reads no value: a property's name, a member's key, a JSX attribute. */
322
+ function keyOnly(node) {
323
+ const parent = node.parent;
324
+ if (ts.isPropertyAccessExpression(parent)) return parent.name === node;
325
+ if (ts.isPropertyAssignment(parent) || ts.isMethodDeclaration(parent)) return parent.name === node;
326
+ return ts.isJsxAttribute(parent) || ts.isBindingElement(parent) && parent.propertyName === node;
327
+ }
328
+ /** A name read as a value. */
329
+ function reads(node) {
330
+ return ts.isIdentifier(node) && !keyOnly(node);
331
+ }
332
+ /**
333
+ * A closure: its body reads a name that a function around it declares, or reads `this`. So it
334
+ * holds state of the unit it lives in. A function that closes over nothing could live at the top
335
+ * level, as `unicorn/consistent-function-scoping` reads it (ADR 0149). Syntax only: a name that
336
+ * is declared both inside and around counts as inside.
337
+ */
338
+ function closes(fn) {
339
+ const around = outerNames(fn);
340
+ if (around.size === 0 || !fn.body) return false;
341
+ const inner = innerNames(fn);
342
+ let found = false;
343
+ const visit = (node) => {
344
+ if (found || ts.isTypeNode(node)) return;
345
+ found = node.kind === ts.SyntaxKind.ThisKeyword;
346
+ found ||= reads(node) && around.has(node.text) && !inner.has(node.text);
347
+ ts.forEachChild(node, visit);
348
+ };
349
+ visit(fn.body);
350
+ return found;
351
+ }
352
+ //#endregion
353
+ //#region src/plain.ts
354
+ /** The hooks Core 0.10.0's `capsule()` accepts (`Capsule.Hooks`). */
355
+ const hookNames = /* @__PURE__ */ new Set([
356
+ "start",
357
+ "resolve",
358
+ "run",
359
+ "write",
360
+ "close",
361
+ "session"
362
+ ]);
363
+ /** Core calls whose direct options are graph bodies. */
364
+ const unitNames = /* @__PURE__ */ new Set([
365
+ "operation",
366
+ "resource",
367
+ "tag",
368
+ "data"
369
+ ]);
370
+ /** Calls that register a listener: the event source calls it, never app code by name. */
371
+ const listenNames = /* @__PURE__ */ new Set([
372
+ "addEventListener",
373
+ "removeEventListener",
374
+ "on",
375
+ "once",
376
+ "off",
377
+ "defer",
378
+ "dispose"
379
+ ]);
380
+ /** Wrappers that keep the value: parens, casts, and the branches of `a || b` or `c ? a : b`. */
381
+ function wraps(parent, node) {
382
+ if (ts.isParenthesizedExpression(parent) || ts.isAsExpression(parent) || ts.isSatisfiesExpression(parent) || ts.isNonNullExpression(parent) || ts.isTypeAssertionExpression(parent)) return true;
383
+ if (ts.isConditionalExpression(parent)) return parent.condition !== node;
384
+ return ts.isBinaryExpression(parent) && logical.has(parent.operatorToken.kind);
385
+ }
386
+ const logical = /* @__PURE__ */ new Set([
387
+ ts.SyntaxKind.BarBarToken,
388
+ ts.SyntaxKind.QuestionQuestionToken,
389
+ ts.SyntaxKind.AmpersandAmpersandToken
390
+ ]);
391
+ /** The outermost node that still holds this value. */
392
+ function outer(node) {
393
+ while (node.parent && wraps(node.parent, node)) node = node.parent;
394
+ return node;
395
+ }
396
+ function textOf(name) {
397
+ if (!name) return void 0;
398
+ if (ts.isIdentifier(name) || ts.isStringLiteral(name) || ts.isPrivateIdentifier(name)) return name.text;
399
+ return name.getText();
400
+ }
401
+ /** The name a function is bound to: its declaration, variable, property, or assignment. */
402
+ function nameOf(fn) {
403
+ if (!ts.isFunctionExpression(fn) && !ts.isArrowFunction(fn)) return textOf(fn.name);
404
+ return holderName(outer(fn).parent);
405
+ }
406
+ function holderName(holder) {
407
+ if (ts.isVariableDeclaration(holder) || ts.isPropertyAssignment(holder)) return textOf(holder.name);
408
+ if (ts.isPropertyDeclaration(holder)) return textOf(holder.name);
409
+ if (ts.isBinaryExpression(holder) && holder.operatorToken.kind === ts.SyntaxKind.EqualsToken) return holder.left.getText();
410
+ return ts.isExportAssignment(holder) ? "default" : void 0;
411
+ }
412
+ /** The object literal a named function is a member of, if any. */
413
+ function memberOf(fn) {
414
+ const member = ts.isFunctionExpression(fn) || ts.isArrowFunction(fn) ? outer(fn).parent : fn;
415
+ return (ts.isPropertyAssignment(member) || ts.isMethodDeclaration(member) || ts.isAccessor(member)) && ts.isObjectLiteralExpression(member.parent) ? member.parent : void 0;
416
+ }
417
+ /**
418
+ * The identifier a value is built from: `Bun` in `Bun.serve` or `new Bun.Glob("*").scanSync()`,
419
+ * `f` in `f<T>()(...)`, the shared root of an array's spreads in `[...xs].map`.
420
+ */
421
+ function calleeRoot(expression) {
422
+ if (ts.isIdentifier(expression)) return expression.text;
423
+ if (ts.isArrayLiteralExpression(expression)) return spreadRoot(expression);
424
+ const next = builtOn(expression);
425
+ return next && calleeRoot(next);
426
+ }
427
+ /** What an expression builds on: a receiver, a called or constructed value, a cast's value. */
428
+ function builtOn(expression) {
429
+ return ts.isPropertyAccessExpression(expression) || ts.isCallExpression(expression) || ts.isNewExpression(expression) || ts.isParenthesizedExpression(expression) || ts.isAsExpression(expression) || ts.isSatisfiesExpression(expression) || ts.isNonNullExpression(expression) ? expression.expression : void 0;
430
+ }
431
+ /** `[...xs, ...ys]`: the root every spread shares, when each item is a spread. */
432
+ function spreadRoot(array) {
433
+ const roots = array.elements.map((item) => ts.isSpreadElement(item) ? calleeRoot(item.expression) : void 0);
434
+ const [first] = roots;
435
+ return first && roots.every((root) => root === first) ? first : void 0;
436
+ }
437
+ /** The file an app import names, by its path without the extension. */
438
+ function appFile$1(file, specifier) {
439
+ return stem(specifier.startsWith("~/") ? `tinker/${specifier.slice(2)}` : specifier.startsWith("@/") ? `src/${specifier.slice(2)}` : join(dirname(file.path), specifier));
440
+ }
441
+ function stem(path) {
442
+ return path.replace(/\.[mc]?tsx?$/, "");
443
+ }
444
+ /**
445
+ * Platform classes whose options the platform calls. Only the direct callee counts:
446
+ * `new ReadableStream({...})` is a library call, but a const built on one is not a library
447
+ * value (a Proxy returns its app target). Only the ones the app uses; add one with its reason.
448
+ */
449
+ const platformNames = /* @__PURE__ */ new Set([
450
+ "ReadableStream",
451
+ "Proxy",
452
+ "TransformStream"
453
+ ]);
454
+ /** `new X({...})` with X on the platform list, as the direct callee. */
455
+ function platformCall(call) {
456
+ return ts.isNewExpression(call) && ts.isIdentifier(call.expression) && platformNames.has(call.expression.text);
457
+ }
458
+ /**
459
+ * A name whose value comes from a library: imported from a package, the `Bun` global, or a
460
+ * top-level const built on one, here or in the app file it is imported from (no barrels).
461
+ */
462
+ function libraryValue(file, name, depth = 0) {
463
+ if (name === "Bun" || file.library.has(name)) return true;
464
+ if (depth > 8) return false;
465
+ const value = file.consts.get(name);
466
+ const root = value && calleeRoot(value);
467
+ return root ? libraryValue(file, root, depth + 1) : importedValue(file, name, depth);
468
+ }
469
+ function importedValue(file, name, depth) {
470
+ const from = file.app.get(name);
471
+ const target = from && (file.pass.files.get(from.from) ?? file.pass.files.get(`${from.from}/index`));
472
+ return !!target && libraryValue(target, from.name, depth + 1);
473
+ }
474
+ /**
475
+ * A library value where `at` stands: a library value of the file, or a local of a function
476
+ * around it that comes from a module resource, as `x` in `depends: { x: betterAuthModule }`,
477
+ * `betterAuth` in `const { betterAuth } = x`, or `db` in `const db = new x.Kysely({...})`.
478
+ */
479
+ function libraryAt(file, name, at, depth = 0) {
480
+ if (libraryValue(file, name)) return true;
481
+ if (depth > 8) return false;
482
+ for (let fn = enclosingFn(at); fn; fn = enclosingFn(fn)) {
483
+ const bound = bindingIn(file, fn, name);
484
+ if (bound === void 0) continue;
485
+ if (typeof bound === "boolean") return bound;
486
+ const root = calleeRoot(bound.value);
487
+ return !!root && libraryAt(file, root, bound.at, depth + 1);
488
+ }
489
+ return false;
490
+ }
491
+ /**
492
+ * How a function binds a name: a module-resource dependency (true), another parameter (false),
493
+ * a local built on a value (that value), or not at all (undefined).
494
+ */
495
+ function bindingIn(file, fn, name) {
496
+ for (const [index, parameter] of fn.parameters.entries()) {
497
+ const item = bindsName(parameter.name, name);
498
+ if (!item) continue;
499
+ return index === 0 && ts.isBindingElement(item) && moduleDependency(file, fn, item);
500
+ }
501
+ const found = [];
502
+ if (fn.body) ownWalk(fn.body, (node) => {
503
+ if (ts.isVariableDeclaration(node) && bindsName(node.name, name)) found.push(node);
504
+ });
505
+ const [local] = found;
506
+ return local && (local.initializer ? {
507
+ value: local.initializer,
508
+ at: local
509
+ } : false);
510
+ }
511
+ /** The binding of a name in `name` or in `{ name }`, if it binds it. */
512
+ function bindsName(binding, name) {
513
+ if (ts.isIdentifier(binding)) return binding.text === name ? binding : void 0;
514
+ if (!ts.isObjectBindingPattern(binding)) return void 0;
515
+ return binding.elements.find((item) => ts.isIdentifier(item.name) && item.name.text === name);
516
+ }
517
+ /** A dependency of a Core unit's option, taken from its first parameter: a module resource. */
518
+ function moduleDependency(file, fn, item) {
519
+ const object = memberOf(fn);
520
+ if (!object || !unitNames.has(coreCall(file, object) ?? "")) return false;
521
+ const key = textOf(item.propertyName ?? item.name);
522
+ const value = property(property(object, "depends"), key);
523
+ return !!value && ts.isIdentifier(value) && moduleResource(file, value.text);
524
+ }
525
+ /** The value of a property of an object literal: `{ name: value }` or `{ name }`. */
526
+ function property(object, name) {
527
+ if (!object || !ts.isObjectLiteralExpression(object)) return void 0;
528
+ for (const item of object.properties) {
529
+ if (textOf(item.name) !== name) continue;
530
+ if (ts.isPropertyAssignment(item)) return item.initializer;
531
+ if (ts.isShorthandPropertyAssignment(item)) return item.name;
532
+ if (ts.isMethodDeclaration(item)) return item;
533
+ }
534
+ }
535
+ /**
536
+ * A Core `resource` whose factory returns `import("<package>")`, here or in the app file it is
537
+ * imported from. An app path (`~/x`, `./x`) is app code, not a library.
538
+ */
539
+ function moduleResource(file, name, depth = 0) {
540
+ if (depth > 8) return false;
541
+ const value = file.consts.get(name);
542
+ if (value) return libraryResource(file, value);
543
+ const from = file.app.get(name);
544
+ const target = from && (file.pass.files.get(from.from) ?? file.pass.files.get(`${from.from}/index`));
545
+ return !!target && moduleResource(target, from.name, depth + 1);
546
+ }
547
+ /**
548
+ * A `resource({ factory })` call whose factory returns `import("<package>")` on every return:
549
+ * one branch of app code makes the whole value app code.
550
+ */
551
+ function libraryResource(file, value) {
552
+ if (!ts.isCallExpression(value) || !ts.isIdentifier(value.expression)) return false;
553
+ if (file.core.get(value.expression.text) !== "resource") return false;
554
+ const factory = property(value.arguments.at(0), "factory");
555
+ const returns = factory && isFn(factory) ? returnsOf(factory) : [];
556
+ return returns.length > 0 && returns.every(importsLibrary);
557
+ }
558
+ /** `import("<package>")` of a bare package specifier. */
559
+ function importsLibrary(node) {
560
+ if (!ts.isCallExpression(node) || node.expression.kind !== ts.SyntaxKind.ImportKeyword) return false;
561
+ const [specifier] = node.arguments;
562
+ return !!specifier && ts.isStringLiteral(specifier) && library(specifier.text);
563
+ }
564
+ /** The call this node is a direct argument of. */
565
+ function argumentOf(node) {
566
+ const call = outer(node).parent;
567
+ if (!ts.isCallExpression(call) && !ts.isNewExpression(call)) return void 0;
568
+ return call.arguments?.includes(outer(node)) ? call : void 0;
569
+ }
570
+ /** The Core name a call's callee is imported as: `operation`, `capsule`, ... */
571
+ function coreCall(file, node) {
572
+ const call = argumentOf(node);
573
+ return call && ts.isIdentifier(call.expression) ? file.core.get(call.expression.text) : void 0;
574
+ }
575
+ /** A capsule's hooks: `capsule({ hooks: {...} })`, or an object typed or passed as hooks. */
576
+ function isHooks(file, object) {
577
+ const holder = outer(object).parent;
578
+ if (ts.isPropertyAssignment(holder) && textOf(holder.name) === "hooks") return coreCall(file, holder.parent) === "capsule";
579
+ if (!ts.isVariableDeclaration(holder) || !ts.isIdentifier(holder.name)) return false;
580
+ return file.hooks.has(holder.name.text) || hooksType(file, holder.type);
581
+ }
582
+ function hooksType(file, type) {
583
+ if (!type || !ts.isTypeReferenceNode(type) || !ts.isQualifiedName(type.typeName)) return false;
584
+ const { left, right } = type.typeName;
585
+ return ts.isIdentifier(left) && file.core.get(left.text) === "Capsule" && right.text === "Hooks";
586
+ }
587
+ /** A direct option of a Core unit, or a hook of a capsule. */
588
+ function graphOption(file, fn) {
589
+ const object = memberOf(fn);
590
+ if (!object) return false;
591
+ if (unitNames.has(coreCall(file, object) ?? "")) return true;
592
+ return hookNames.has(nameOf(fn) ?? "") && isHooks(file, object);
593
+ }
594
+ /** Inside the options of a library call, at any depth. Core calls are graph options instead. */
595
+ function nativeOption(file, fn) {
596
+ let node = memberOf(fn);
597
+ while (node && ts.isObjectLiteralExpression(node)) {
598
+ const holder = outer(node).parent;
599
+ if (!ts.isPropertyAssignment(holder)) break;
600
+ node = holder.parent;
601
+ }
602
+ const call = node && argumentOf(node);
603
+ if (!call) return false;
604
+ const name = calleeRoot(call.expression);
605
+ return platformCall(call) || !!name && libraryAt(file, name, call);
606
+ }
607
+ /** A use of a name as a value: not a callee, not a property's receiver or key. */
608
+ function valueUse(node, name) {
609
+ if (!ts.isIdentifier(node) || node.text !== name) return false;
610
+ const parent = node.parent;
611
+ if (ts.isCallExpression(parent) && parent.expression === node) return false;
612
+ if (ts.isPropertyAccessExpression(parent)) return false;
613
+ return !(ts.isPropertyAssignment(parent) && parent.name === node);
614
+ }
615
+ /** The values a function returns: each `return` of its own, or its expression body. */
616
+ function returnsOf(owner) {
617
+ const found = [];
618
+ if (owner.body && !ts.isBlock(owner.body)) found.push(owner.body);
619
+ if (owner.body) ownWalk(owner.body, (node) => {
620
+ if (ts.isReturnStatement(node) && node.expression) found.push(node.expression);
621
+ });
622
+ return found;
623
+ }
624
+ function returnsName(owner, name) {
625
+ let found = false;
626
+ for (const value of returnsOf(owner)) walk(value, (node) => {
627
+ found ||= valueUse(node, name);
628
+ });
629
+ return found;
630
+ }
631
+ /** The owner returns this object: directly, inside a returned object, or through a local name. */
632
+ function returned(owner, object) {
633
+ let node = outer(object);
634
+ while (ts.isPropertyAssignment(node.parent) && ts.isObjectLiteralExpression(node.parent.parent)) node = outer(node.parent.parent);
635
+ if (returnsOf(owner).includes(node)) return true;
636
+ const holder = node.parent;
637
+ return ts.isVariableDeclaration(holder) && ts.isIdentifier(holder.name) ? returnsName(owner, holder.name.text) : false;
638
+ }
639
+ /** Handed to a call: an argument, a property of an argument, or a JSX attribute. */
640
+ function handed(node) {
641
+ const parent = outer(node).parent;
642
+ if (argumentOf(node) || ts.isJsxExpression(parent)) return true;
643
+ if (!ts.isShorthandPropertyAssignment(parent) && !ts.isPropertyAssignment(parent)) return false;
644
+ return ts.isObjectLiteralExpression(parent.parent) && !!argumentOf(parent.parent);
645
+ }
646
+ function handsName(owner, name) {
647
+ let found = false;
648
+ walk(owner.body, (node) => {
649
+ found ||= valueUse(node, name) && handed(node);
650
+ });
651
+ return found;
652
+ }
653
+ /** Named inside a passing function, which returns it or hands it to a call. */
654
+ function owned(file, fn, name) {
655
+ const object = memberOf(fn);
656
+ const owner = enclosingFn(object ?? fn);
657
+ if (!owner || !passes(file, owner)) return false;
658
+ if (object) return returned(owner, object);
659
+ return returnsName(owner, name) || handsName(owner, name);
660
+ }
661
+ function hasJsx(node) {
662
+ let found = false;
663
+ ownWalk(node, (child) => {
664
+ found ||= ts.isJsxElement(child) || ts.isJsxSelfClosingElement(child) || ts.isJsxFragment(child);
665
+ });
666
+ return found;
667
+ }
668
+ /** A React component: capitalized, at most one parameter (its props), and it returns JSX. */
669
+ function component(file, fn, name) {
670
+ const own = ts.isFunctionExpression(fn) ? textOf(fn.name) ?? name : name;
671
+ if (!file.path.endsWith(".tsx") || !/^[A-Z]/.test(own)) return false;
672
+ return fn.parameters.length <= 1 && !!fn.body && hasJsx(fn.body);
673
+ }
674
+ /**
675
+ * Written where it is used: a JSX attribute, a returned value, or an argument of a call that
676
+ * takes callbacks. An array item stands where its array stands, so `const [f] = [() => 1]` is
677
+ * named, as is `const f = Object.freeze(() => 1)`.
678
+ */
679
+ function inline(file, node) {
680
+ node = outer(node);
681
+ const parent = node.parent;
682
+ if (ts.isArrayLiteralExpression(parent)) return inline(file, parent);
683
+ if (ts.isJsxExpression(parent) || ts.isReturnStatement(parent)) return true;
684
+ if (ts.isArrowFunction(parent) && parent.body === node) return true;
685
+ const call = argumentOf(node);
686
+ return !!call && callbackCall(file, call);
687
+ }
688
+ /**
689
+ * A call that may take an unnamed function: one inside a function (that function is judged
690
+ * itself), a Core call, `defineMain`, a library call, or an event registration.
691
+ */
692
+ function callbackCall(file, call) {
693
+ if (enclosingFn(call) || platformCall(call)) return true;
694
+ const name = calleeRoot(call.expression);
695
+ if (name && (file.core.has(name) || file.mains.has(name) || libraryValue(file, name))) return true;
696
+ return ts.isPropertyAccessExpression(call.expression) && listenNames.has(call.expression.name.text);
697
+ }
698
+ /** A Workflow SDK file: `*.flow.ts` or `*.flow.server.ts` (ADR 0148). */
699
+ const flowFile = /\.flow(\.server)?\.ts$/;
700
+ /** The directives the Workflow SDK finds a workflow and a step by. */
701
+ const flowDirectives = /* @__PURE__ */ new Set(["use workflow", "use step"]);
702
+ /**
703
+ * A workflow or a step in a flow file: the SDK finds it by its directive, not by a call. A
704
+ * directive is one of the body's leading string statements, as ECMAScript reads `"use strict"`.
705
+ */
706
+ function flowFunction(file, fn) {
707
+ if (!flowFile.test(file.path) || !fn.body || !ts.isBlock(fn.body)) return false;
708
+ for (const statement of fn.body.statements) {
709
+ if (!ts.isExpressionStatement(statement) || !ts.isStringLiteral(statement.expression)) break;
710
+ if (flowDirectives.has(statement.expression.text)) return true;
711
+ }
712
+ return false;
713
+ }
714
+ function exempt(file, name) {
715
+ return Object.hasOwn(file.pass.entries[file.path] ?? {}, name);
716
+ }
717
+ function judge(file, fn) {
718
+ if (flowFunction(file, fn)) return true;
719
+ const name = nameOf(fn);
720
+ if (name === void 0) return inline(file, fn);
721
+ if (exempt(file, name)) return true;
722
+ return component(file, fn, name) || graphOption(file, fn) || nativeOption(file, fn) || owned(file, fn, name);
723
+ }
724
+ function passes(file, fn) {
725
+ const verdicts = file.pass.verdicts;
726
+ if (!verdicts.has(fn)) verdicts.set(fn, judge(file, fn));
727
+ return verdicts.get(fn);
728
+ }
729
+ /** Library calls that hand back the function they take: the name they bind is still that function. */
730
+ const keepNames = /* @__PURE__ */ new Set(["useCallback"]);
731
+ /** The value under the wrappers that keep it: parens, casts, `!`. */
732
+ function unwrap(node) {
733
+ while (ts.isParenthesizedExpression(node) || ts.isAsExpression(node) || ts.isSatisfiesExpression(node) || ts.isNonNullExpression(node)) node = node.expression;
734
+ return node;
735
+ }
736
+ /** Whether a variable or a parameter declares this name, alone or inside a pattern. */
737
+ function names(node, name) {
738
+ const found = /* @__PURE__ */ new Set();
739
+ bindingNames(node.name, found);
740
+ return found.has(name);
741
+ }
742
+ /** What a variable gives a name: its value, or "hidden" when it comes out of a pattern. */
743
+ function variable(node, name) {
744
+ if (!names(node, name)) return void 0;
745
+ return ts.isIdentifier(node.name) && node.initializer || "hidden";
746
+ }
747
+ /** What a declaration gives a name: its value, "hidden" when the syntax cannot say, or nothing. */
748
+ function declared(node, name) {
749
+ if (ts.isFunctionDeclaration(node)) return node.name?.text === name ? node : void 0;
750
+ if (ts.isParameter(node)) return names(node, name) ? "hidden" : void 0;
751
+ return ts.isVariableDeclaration(node) ? variable(node, name) : void 0;
752
+ }
753
+ /** How a function binds a name for the code inside it: a parameter, a local, an inner function. */
754
+ function localBinding(owner, name) {
755
+ let found;
756
+ const visit = (node) => {
757
+ found ??= declared(node, name);
758
+ if (!isFn(node)) ts.forEachChild(node, visit);
759
+ };
760
+ for (const parameter of owner.parameters) visit(parameter);
761
+ if (owner.body) visit(owner.body);
762
+ return found;
763
+ }
764
+ /** The file an app import comes from, and the name it has there. */
765
+ function importedFrom(file, name) {
766
+ const from = file.app.get(name);
767
+ if (!from) return void 0;
768
+ const target = file.pass.files.get(from.from) ?? file.pass.files.get(`${from.from}/index`);
769
+ return target && {
770
+ file: target,
771
+ name: from.name
772
+ };
773
+ }
774
+ /** A top-level name of a file: a function, a const, or an app import followed to its file. */
775
+ function topBinding(file, name, depth = 0) {
776
+ const node = file.fns.get(name) ?? file.consts.get(name);
777
+ if (node) return {
778
+ file,
779
+ node
780
+ };
781
+ const from = importedFrom(file, name);
782
+ return from && depth < 8 ? topBinding(from.file, from.name, depth + 1) : void 0;
783
+ }
784
+ /** What a name is bound to where `at` stands: the nearest local, else a top-level name. */
785
+ function boundTo(file, name, at) {
786
+ for (let owner = enclosingFn(at); owner; owner = enclosingFn(owner)) {
787
+ const node = localBinding(owner, name);
788
+ if (node === "hidden") return void 0;
789
+ if (node) return {
790
+ file,
791
+ node
792
+ };
793
+ }
794
+ return topBinding(file, name);
795
+ }
796
+ /** Follow `const b = a` to the value behind the names. */
797
+ function settle(bound, depth = 0) {
798
+ if (!bound) return void 0;
799
+ const node = unwrap(bound.node);
800
+ if (!ts.isIdentifier(node)) return {
801
+ file: bound.file,
802
+ node
803
+ };
804
+ return depth < 8 ? settle(boundTo(bound.file, node.text, node), depth + 1) : void 0;
805
+ }
806
+ /** The function a keeping call takes: the `fn` of `useCallback(fn)`, imported from a library. */
807
+ function keptFn(file, node) {
808
+ if (!ts.isCallExpression(node) || !ts.isIdentifier(node.expression)) return void 0;
809
+ const name = node.expression.text;
810
+ if (!keepNames.has(name) || !file.library.has(name)) return void 0;
811
+ return node.arguments[0] && unwrap(node.arguments[0]);
812
+ }
813
+ /** The function a value is: itself, or the one a keeping call takes. */
814
+ function fnOf(bound) {
815
+ const value = settle(bound);
816
+ if (!value) return void 0;
817
+ const fn = isFn(value.node) ? value.node : keptFn(value.file, value.node);
818
+ return fn && isFn(fn) ? {
819
+ file: value.file,
820
+ fn
821
+ } : void 0;
822
+ }
823
+ /** The member `name` of a value that is an object literal. */
824
+ function memberFn(bound, name) {
825
+ const value = settle(bound);
826
+ const item = value && property(value.node, name);
827
+ const member = item && unwrap(item);
828
+ return member && isFn(member) ? {
829
+ file: value.file,
830
+ fn: member
831
+ } : void 0;
832
+ }
833
+ /** The app function a call names, when the syntax shows it: `f()` or `object.f()`. */
834
+ function calleeFn(file, call) {
835
+ const callee = unwrap(call.expression);
836
+ if (ts.isIdentifier(callee)) return fnOf(boundTo(file, callee.text, call));
837
+ if (!ts.isPropertyAccessExpression(callee) || !ts.isIdentifier(callee.expression)) return;
838
+ return memberFn(boundTo(file, callee.expression.text, call), callee.name.text);
839
+ }
840
+ /** A flow function called from inside a flow function: a workflow calls its steps by name. */
841
+ function flowCall(file, call, found) {
842
+ const caller = outermostFn(call);
843
+ return flowFunction(found.file, found.fn) && caller !== void 0 && flowFunction(file, caller);
844
+ }
845
+ /**
846
+ * A helper behind a pass: a passing function that a call names, that holds no state of a
847
+ * function around it, and that is no entry. Something else is meant to call a passing function
848
+ * (Core, a library, React); a call by name makes it a plain function again (ADR 0149). A flow
849
+ * function may call a flow function by name (ADR 0148).
850
+ */
851
+ function helperOf(file, call) {
852
+ const found = calleeFn(file, call);
853
+ if (!found?.fn.body || !passes(found.file, found.fn)) return void 0;
854
+ const name = nameOf(found.fn);
855
+ if (name !== void 0 && exempt(found.file, name)) return void 0;
856
+ if (flowCall(file, call, found)) return void 0;
857
+ return closes(found.fn) ? void 0 : found;
858
+ }
859
+ /** The line a node starts on, from 1. */
860
+ function lineOf(file, node) {
861
+ return file.source.getLineAndCharacterOfPosition(node.getStart()).line + 1;
862
+ }
863
+ /** Each helper the calls of a file name, as a finding at the helper, with the call that names it. */
864
+ function called(file) {
865
+ const hits = [];
866
+ walk(file.source, (node) => {
867
+ const found = ts.isCallExpression(node) ? helperOf(file, node) : void 0;
868
+ if (!found) return;
869
+ const what = `a helper, called by name at ${file.path}:${lineOf(file, node)}`;
870
+ const line = lineOf(found.file, found.fn);
871
+ hits.push({
872
+ path: found.file.path,
873
+ line,
874
+ rule: "tinker/plain",
875
+ what
876
+ });
877
+ });
878
+ return hits;
879
+ }
880
+ /** One finding for each helper: its first call in file order. */
881
+ function calledOnce(files) {
882
+ const first = /* @__PURE__ */ new Map();
883
+ for (const file of files) for (const hit of called(file)) {
884
+ const key = `${hit.path}:${hit.line}`;
885
+ if (!first.has(key)) first.set(key, hit);
886
+ }
887
+ return [...first.values()];
888
+ }
889
+ /** A bare package import is a library; `~/`, `@/` and relative paths are app code. */
890
+ function library(specifier) {
891
+ return !/^(\.|~\/|@\/)/.test(specifier) && specifier !== "@tinkered/core";
892
+ }
893
+ /** Each local name an import binds, with the name it has in its module. */
894
+ function importNames(clause) {
895
+ const names = clause.name ? [[clause.name.text, "default"]] : [];
896
+ const bindings = clause.namedBindings;
897
+ if (!bindings) return names;
898
+ if (ts.isNamespaceImport(bindings)) return [...names, [bindings.name.text, "*"]];
899
+ for (const item of bindings.elements) names.push([item.name.text, (item.propertyName ?? item.name).text]);
900
+ return names;
901
+ }
902
+ function readImport(file, node) {
903
+ const specifier = node.moduleSpecifier.text;
904
+ if (!node.importClause) return;
905
+ for (const [local, name] of importNames(node.importClause)) if (specifier === "@tinkered/core") file.core.set(local, name);
906
+ else if (library(specifier)) file.library.add(local);
907
+ else readAppImport(file, local, {
908
+ from: appFile$1(file, specifier),
909
+ name
910
+ });
911
+ }
912
+ /** An app import; the `defineMain` of tinker/base/main.ts may take the command's main. */
913
+ function readAppImport(file, local, from) {
914
+ file.app.set(local, from);
915
+ if (from.name === "defineMain" && from.from === "tinker/base/main") file.mains.add(local);
916
+ }
917
+ /** Top-level consts and what they hold: `const batch = z.object({...})`. */
918
+ function readConsts(file, node) {
919
+ if (!ts.isVariableStatement(node)) return;
920
+ for (const item of node.declarationList.declarations) if (ts.isIdentifier(item.name) && item.initializer) file.consts.set(item.name.text, item.initializer);
921
+ }
922
+ /** Hooks objects passed by name: `capsule({ hooks: queueSink })`. */
923
+ function readHooks(file, node) {
924
+ if (!ts.isPropertyAssignment(node) || textOf(node.name) !== "hooks") return;
925
+ if (ts.isIdentifier(node.initializer) && coreCall(file, node.parent) === "capsule") file.hooks.add(node.initializer.text);
926
+ }
927
+ function readFile(pass, path, text) {
928
+ const kind = path.endsWith(".tsx") ? ts.ScriptKind.TSX : ts.ScriptKind.TS;
929
+ const source = ts.createSourceFile(path, text, ts.ScriptTarget.Latest, true, kind);
930
+ const file = {
931
+ pass,
932
+ path,
933
+ source,
934
+ core: /* @__PURE__ */ new Map(),
935
+ library: /* @__PURE__ */ new Set(),
936
+ app: /* @__PURE__ */ new Map(),
937
+ mains: /* @__PURE__ */ new Set(),
938
+ hooks: /* @__PURE__ */ new Set(),
939
+ consts: /* @__PURE__ */ new Map(),
940
+ fns: /* @__PURE__ */ new Map()
941
+ };
942
+ for (const node of source.statements) {
943
+ if (ts.isImportDeclaration(node)) readImport(file, node);
944
+ if (ts.isFunctionDeclaration(node) && node.name) file.fns.set(node.name.text, node);
945
+ readConsts(file, node);
946
+ }
947
+ walk(source, (node) => readHooks(file, node));
948
+ return file;
949
+ }
950
+ function check$1(file) {
951
+ const hits = [];
952
+ walk(file.source, (node) => {
953
+ if (!isFn(node) || !node.body || passes(file, node)) return;
954
+ hits.push({
955
+ path: file.path,
956
+ line: lineOf(file, node),
957
+ rule: "tinker/plain",
958
+ what: "a plain function"
959
+ });
960
+ });
961
+ return hits;
962
+ }
963
+ /**
964
+ * The plain-function check (Duke 2026-10-31, tinker-app #44). App code has no plain helper
965
+ * functions: every named function is an operation, so every call is a span and its dependencies
966
+ * come through the graph. It reads the syntax tree only, no types.
967
+ *
968
+ * A function passes when it is one of these:
969
+ * - inline: no name of its own, written where it is used: a JSX attribute, a returned value, or
970
+ * an argument of a call inside a function, a Core call, `defineMain`, a library call, or an
971
+ * event registration. An IIFE, `Object.freeze(() => 1)` at the top level, or a function in an
972
+ * array bound to a name is not inline;
973
+ * - a graph body: a direct option of a Core `operation`, `resource`, `tag` or `data`, or a hook
974
+ * of a capsule (in `capsule({ hooks })`, or in an object typed `Capsule.Hooks`);
975
+ * - a native option: inside the options of a library call (`Bun.serve`, `createRoute`, ...).
976
+ * A library may come through a module resource (a Core `resource` whose factory returns
977
+ * `import("<package>")`): `depends: { x: thatResource }`, then `x.f({...})`,
978
+ * `const { f } = x; f({...})` or `new x.C({...})`;
979
+ * - owned: named inside a passing function that returns it or hands it to a call;
980
+ * - a React component: a capitalized function in a .tsx file that returns JSX;
981
+ * - a flow function: in a `*.flow.ts` or `*.flow.server.ts` file, a body that starts with the
982
+ * directive `"use workflow"` or `"use step"` (the Workflow SDK's workflow and step);
983
+ * - exempt: an item of the app's `entries`.
984
+ *
985
+ * A pass says who calls the function: Core, a library, React. So a call by name takes the pass
986
+ * away (ADR 0149). A passing function that a call names is a finding, unless it is a closure
987
+ * (it reads a name of a function around it) or an entry.
988
+ */
989
+ function findPlain(sources, entries) {
990
+ const pass = {
991
+ files: /* @__PURE__ */ new Map(),
992
+ verdicts: /* @__PURE__ */ new Map(),
993
+ entries
994
+ };
995
+ for (const { path, text } of sources) pass.files.set(stem(path), readFile(pass, path, text));
996
+ const files = [...pass.files.values()];
997
+ return [...files.flatMap(check$1), ...calledOnce(files)];
998
+ }
999
+ //#endregion
1000
+ //#region src/check.ts
1001
+ /** The app code the plain-function check reads. */
1002
+ const appFiles = "{src,cmds,tinker}/**/*.{ts,tsx,mts,cts}";
1003
+ /** A declaration file holds no code. */
1004
+ const appFile = /(?<!\.d)\.[mc]?tsx?$/;
1005
+ /** Where a page's files are when the app's config does not say. */
1006
+ const pageFiles = ["src/**"];
1007
+ /** A page file by its ending; a `.server.` file never reaches the page. */
1008
+ const pageFile = /(?<!\.server|\.d)\.[mc]?[jt]sx?$/;
1009
+ const configName = "tinker.json";
1010
+ /** The name before ADR 0156: a file by this name alone stops the run with the new name. */
1011
+ const oldName = "tinker-analyze.json";
1012
+ function isRecord$1(value) {
1013
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1014
+ }
1015
+ function isReasons(value) {
1016
+ return isRecord$1(value) && Object.values(value).every((reason) => typeof reason === "string");
1017
+ }
1018
+ function isEntries(value) {
1019
+ return isRecord$1(value) && Object.values(value).every(isReasons);
1020
+ }
1021
+ function isGlobs(value) {
1022
+ return Array.isArray(value) && value.every((glob) => typeof glob === "string");
1023
+ }
1024
+ /** Each part of the config: where it is, the test it passes, and what to say when it fails. */
1025
+ const parts = [
1026
+ [
1027
+ [],
1028
+ isRecord$1,
1029
+ "the file is not an object"
1030
+ ],
1031
+ [
1032
+ ["plain"],
1033
+ isRecord$1,
1034
+ "`plain` and `page` are objects"
1035
+ ],
1036
+ [
1037
+ ["page"],
1038
+ isRecord$1,
1039
+ "`plain` and `page` are objects"
1040
+ ],
1041
+ [
1042
+ ["plain", "entries"],
1043
+ isEntries,
1044
+ "`plain.entries` maps a file to its names and reasons"
1045
+ ],
1046
+ [
1047
+ ["page", "files"],
1048
+ isGlobs,
1049
+ "`page.files` is a list of globs"
1050
+ ],
1051
+ [
1052
+ ["page", "skip"],
1053
+ isReasons,
1054
+ "`page.skip` maps a glob to a reason"
1055
+ ],
1056
+ [
1057
+ ["gaps"],
1058
+ (value) => typeof value === "string",
1059
+ "`gaps` is the path of the gaps doc"
1060
+ ]
1061
+ ];
1062
+ function parse(text) {
1063
+ try {
1064
+ return JSON.parse(text);
1065
+ } catch {
1066
+ return raise("BadConfig", {
1067
+ path: configName,
1068
+ reason: "the file is not JSON"
1069
+ });
1070
+ }
1071
+ }
1072
+ /** The config's one door: the file's JSON becomes a `Check.Config`, or the run stops. */
1073
+ function readConfig(root) {
1074
+ const config = parse(readFileSync(join(root, configName), "utf8"));
1075
+ for (const [keys, ok, reason] of parts) {
1076
+ const value = keys.reduce((at, key) => isRecord$1(at) ? at[key] : void 0, config);
1077
+ if (keys.length && value === void 0) continue;
1078
+ if (!ok(value)) raise("BadConfig", {
1079
+ path: configName,
1080
+ reason
1081
+ });
1082
+ }
1083
+ return config;
1084
+ }
1085
+ function configOf(root) {
1086
+ if (globSync(configName, { cwd: root }).length) return readConfig(root);
1087
+ if (globSync(oldName, { cwd: root }).length) raise("BadConfig", {
1088
+ path: oldName,
1089
+ reason: `rename this file to ${configName}`
1090
+ });
1091
+ return {};
1092
+ }
1093
+ /** The files a glob names that `keep` accepts: a glob may also name a folder. */
1094
+ function sourcesOf(root, pattern, keep) {
1095
+ return globSync(pattern, { cwd: root }).map((path) => path.replaceAll("\\", "/")).filter((path) => keep.test(path) && !path.includes("node_modules/")).map((path) => ({
1096
+ path,
1097
+ text: readFileSync(join(root, path), "utf8")
1098
+ }));
1099
+ }
1100
+ function pageSources(root, { files = pageFiles, skip = {} }) {
1101
+ const skips = Object.keys(skip);
1102
+ const paths = /* @__PURE__ */ new Map();
1103
+ for (const source of files.flatMap((glob) => sourcesOf(root, glob, pageFile))) {
1104
+ if (skips.some((glob) => matchesGlob(source.path, glob))) continue;
1105
+ paths.set(source.path, source);
1106
+ }
1107
+ return [...paths.values()];
1108
+ }
1109
+ /** The gaps doc the config names; a missing doc stops the run like a bad config. */
1110
+ function gapsDoc(root, path) {
1111
+ if (!globSync(path, { cwd: root }).length) return raise("BadConfig", {
1112
+ path: configName,
1113
+ reason: `the gaps doc ${path} does not exist`
1114
+ });
1115
+ return {
1116
+ path,
1117
+ text: readFileSync(join(root, path), "utf8")
1118
+ };
1119
+ }
1120
+ /**
1121
+ * The app's files and what Tinker's rules find in them, before the gap rule allows any. `doc`
1122
+ * is the gaps doc, when the config names one.
1123
+ *
1124
+ * @throws `BadConfig` when `tinker.json` is not the shape `Check.Config` names.
1125
+ */
1126
+ function readApp(root) {
1127
+ const config = configOf(root);
1128
+ const app = sourcesOf(root, appFiles, appFile);
1129
+ const page = pageSources(root, config.page ?? {});
1130
+ const found = [...findPlain(app, config.plain?.entries ?? {}), ...page.flatMap(findPage)];
1131
+ return {
1132
+ sources: [...new Map([...app, ...page].map((source) => [source.path, source])).values()],
1133
+ found,
1134
+ ...config.gaps ? { doc: gapsDoc(root, config.gaps) } : {}
1135
+ };
1136
+ }
1137
+ /**
1138
+ * Read the app at `root` and answer every broken rule. It reads files and nothing else: it
1139
+ * runs no app code. A `tinker.json` at the root holds the app's own exceptions.
1140
+ *
1141
+ * @throws `BadConfig` when that file is not the shape `Check.Config` names.
1142
+ */
1143
+ function check(root) {
1144
+ const { sources, found, doc } = readApp(root);
1145
+ const { findings, gaps } = doc ? applyGaps(found, sources, doc) : {
1146
+ findings: found,
1147
+ gaps: []
1148
+ };
1149
+ findings.sort((a, b) => a.path.localeCompare(b.path) || a.line - b.line || a.rule.localeCompare(b.rule));
1150
+ return {
1151
+ files: sources.length,
1152
+ findings,
1153
+ gaps
1154
+ };
1155
+ }
1156
+ //#endregion
1157
+ //#region src/rules.ts
1158
+ /** Tinker's own rules: `check` finds them in the app's files. */
1159
+ const own = [
1160
+ "tinker/plain",
1161
+ "tinker/one-wire",
1162
+ "tinker/react-state",
1163
+ "tinker/gap"
1164
+ ];
1165
+ /** A lint rule that is a gate, by its lint code: its Tinker rule id. It belongs to `types`. */
1166
+ const gates = {
1167
+ "typescript(switch-exhaustiveness-check)": "tinker/kind",
1168
+ "typescript(consistent-type-assertions)": "tinker/cast",
1169
+ "typescript(no-non-null-assertion)": "tinker/cast",
1170
+ "typescript(no-explicit-any)": "tinker/cast"
1171
+ };
1172
+ /** A lint rule a skill teaches under a Tinker rule id. It belongs to `rules`. */
1173
+ const taught = {
1174
+ "typescript(no-floating-promises)": "tinker/floating",
1175
+ "tinker(cell-write)": "tinker/cell-write"
1176
+ };
1177
+ /**
1178
+ * Each Tinker rule id `tinker check` prints. A skill teaches each one in a section with the id
1179
+ * in its heading, and the check prints that section's `Right:` part as the fix (ADR 0156
1180
+ * decision 8). `vp run skills` fails for an id with no section.
1181
+ */
1182
+ const rules = [.../* @__PURE__ */ new Set([
1183
+ ...own,
1184
+ ...Object.values(gates),
1185
+ ...Object.values(taught)
1186
+ ])];
1187
+ //#endregion
1188
+ //#region src/skills.ts
1189
+ const heading = /^###\s+[A-Z]+:\s+(.*?)\s*\[(tinker\/[\w-]+)\]\s*$/;
1190
+ /** A fenced block goes with the `Right:` text that leads into it. */
1191
+ const fence = /^\s*```/;
1192
+ /** The block after line `from`: up to a blank line, or to the end of a fence. */
1193
+ function blockAt(lines, from) {
1194
+ const block = [];
1195
+ let open = false;
1196
+ for (const line of lines.slice(from)) {
1197
+ if (fence.test(line)) open = !open;
1198
+ if (!open && !line.trim() && block.length) break;
1199
+ if (line.trim() || open) block.push(line);
1200
+ }
1201
+ return block;
1202
+ }
1203
+ /** The `Right:` part: its paragraph, and the block after it when the paragraph ends in `:`. */
1204
+ function rightOf(lines) {
1205
+ const start = lines.findIndex((line) => line.startsWith("Right:"));
1206
+ if (start < 0) return [];
1207
+ const right = blockAt(lines, start);
1208
+ if (!right.at(-1)?.trimEnd().endsWith(":")) return right;
1209
+ return [...right, ...blockAt(lines, start + right.length + 1)];
1210
+ }
1211
+ /** Each section of one skill's text that carries a rule id in its heading. */
1212
+ function sectionsIn(text, skill) {
1213
+ const lines = text.split("\n");
1214
+ let open = false;
1215
+ const heads = lines.flatMap((line, index) => {
1216
+ if (fence.test(line)) open = !open;
1217
+ return !open && /^#{1,6} /.test(line) ? [index] : [];
1218
+ });
1219
+ return heads.flatMap((at, index) => {
1220
+ const match = heading.exec(lines[at] ?? "");
1221
+ if (!match) return [];
1222
+ const [, title = "", rule = ""] = match;
1223
+ return [{
1224
+ rule,
1225
+ title,
1226
+ skill,
1227
+ right: rightOf(lines.slice(at + 1, heads[index + 1] ?? lines.length))
1228
+ }];
1229
+ });
1230
+ }
1231
+ /** Every rule section of the skills the app at `root` has installed, through Intent. */
1232
+ function sectionsOf(root) {
1233
+ return listIntentSkills({ cwd: root }).skills.flatMap(({ use }) => sectionsIn(loadIntentSkill(use, { cwd: root }).content, use));
1234
+ }
1235
+ /**
1236
+ * The fix for a finding of `rule`: the `Right:` part of its section. Where a rule has more
1237
+ * than one section, the one whose heading names the code that `what` names wins.
1238
+ */
1239
+ function fixOf(sections, rule, what) {
1240
+ const own = sections.filter((section) => section.rule === rule && section.right.length);
1241
+ const section = own.find(({ title }) => [...title.matchAll(/`([^`]+)`/g)].some(([, code = ""]) => what.includes(`\`${code}\``))) ?? own[0];
1242
+ return section && {
1243
+ right: section.right,
1244
+ skill: section.skill
1245
+ };
1246
+ }
1247
+ /** `tinker skill list`: each skill the app has, with the line that says when to load it. */
1248
+ function listSkills(root) {
1249
+ const { skills } = listIntentSkills({
1250
+ cwd: root,
1251
+ audience: "agent"
1252
+ });
1253
+ if (!skills.length) return "no skills found: add a package that ships skills\n";
1254
+ return `${skills.map(({ use, description }) => `${use}\n ${description}`).join("\n")}\n\nLoad one: tinker skill load <skill>\n`;
1255
+ }
1256
+ /** `tinker skill load <skill>`: the skill's text, as its package ships it. */
1257
+ function loadSkill(root, use) {
1258
+ return loadIntentSkill(use, {
1259
+ cwd: root,
1260
+ audience: "agent"
1261
+ }).content;
1262
+ }
1263
+ //#endregion
1264
+ //#region src/tools.ts
1265
+ const tscLine = /^(?:(.+)\((\d+),\d+\): )?error (TS\d+): (.*)$/;
1266
+ const viteConfig = "vite.config.{ts,mts,js,mjs}";
1267
+ function isRecord(value) {
1268
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1269
+ }
1270
+ /** The app's own copy of a tool: the nearest `node_modules/.bin/<name>` at or above `root`. */
1271
+ function binOf(root, name) {
1272
+ for (let dir = root;; dir = dirname(dir)) {
1273
+ const bin = join(dir, "node_modules", ".bin", name);
1274
+ if (existsSync(bin)) return bin;
1275
+ if (dirname(dir) === dir) return void 0;
1276
+ }
1277
+ }
1278
+ /**
1279
+ * Run a tool in the app's folder. `stdout` is the tool's answer; `output` is all it said, and
1280
+ * why it could not start, for a failure.
1281
+ */
1282
+ function run(root, bin, args) {
1283
+ const done = spawnSync(bin, args, {
1284
+ cwd: root,
1285
+ encoding: "utf8",
1286
+ maxBuffer: 1 << 28
1287
+ });
1288
+ const error = done.error ? `${done.error.message}\n` : "";
1289
+ const stdout = done.stdout ?? "";
1290
+ return {
1291
+ status: done.status,
1292
+ stdout,
1293
+ output: `${error}${stdout}${done.stderr ?? ""}`
1294
+ };
1295
+ }
1296
+ function needed(root, name, why) {
1297
+ return binOf(root, name) ?? raise("MissingTool", {
1298
+ tool: name,
1299
+ reason: why
1300
+ });
1301
+ }
1302
+ /**
1303
+ * `tsc --noEmit`: each error line is one finding; a project error lands on its tsconfig.
1304
+ *
1305
+ * @throws `BadConfig` for a solution tsconfig: with `references`, `tsc --noEmit` checks no file.
1306
+ */
1307
+ function tsc(root) {
1308
+ const bin = needed(root, "tsc", "the app has a tsconfig.json; add typescript");
1309
+ if (/"references"\s*:/.test(readFileSync(join(root, "tsconfig.json"), "utf8"))) raise("BadConfig", {
1310
+ path: "tsconfig.json",
1311
+ reason: "it lists `references`, so `tsc --noEmit` checks no file; run the check per project"
1312
+ });
1313
+ const { status, output } = run(root, bin, [
1314
+ "--noEmit",
1315
+ "--pretty",
1316
+ "false"
1317
+ ]);
1318
+ const found = output.split("\n").flatMap((text) => {
1319
+ const match = tscLine.exec(text.trimEnd());
1320
+ if (!match) return [];
1321
+ const [, path = "tsconfig.json", line = "1", rule = "", what = ""] = match;
1322
+ return [{
1323
+ path: path.replaceAll("\\", "/"),
1324
+ line: Number(line),
1325
+ rule,
1326
+ what
1327
+ }];
1328
+ });
1329
+ if (status !== 0 && !found.length) raise("ToolFailed", {
1330
+ tool: "tsc",
1331
+ output
1332
+ });
1333
+ return found;
1334
+ }
1335
+ /** Where a diagnostic points: its first label's span. */
1336
+ function spanOf(labels) {
1337
+ const label = Array.isArray(labels) ? labels[0] : void 0;
1338
+ const span = isRecord(label) ? label.span : void 0;
1339
+ if (!isRecord(span)) return void 0;
1340
+ const { offset, length, line } = span;
1341
+ return typeof offset === "number" && typeof length === "number" && typeof line === "number" ? {
1342
+ offset,
1343
+ length,
1344
+ line
1345
+ } : void 0;
1346
+ }
1347
+ /** An error diagnostic; a field it lacks reads as unknown, so no error is lost. */
1348
+ function diagnosticOf(value) {
1349
+ if (!isRecord(value) || value.severity !== "error") return [];
1350
+ const { code, message, help, filename } = value;
1351
+ const span = spanOf(value.labels);
1352
+ return [{
1353
+ code: typeof code === "string" ? code : "lint(unknown)",
1354
+ message: typeof message === "string" ? message : "a lint error",
1355
+ filename: typeof filename === "string" ? filename : ".",
1356
+ ...span ? { span } : {},
1357
+ ...typeof help === "string" ? { help } : {}
1358
+ }];
1359
+ }
1360
+ function parsed(text) {
1361
+ try {
1362
+ return JSON.parse(text);
1363
+ } catch {
1364
+ return;
1365
+ }
1366
+ }
1367
+ /**
1368
+ * The lint report's errors. Text that is not the report, or a failed lint with no error in
1369
+ * it, means the lint did not run.
1370
+ */
1371
+ function lintReport({ status, stdout, output }) {
1372
+ const report = parsed(stdout.slice(Math.max(0, stdout.search(/\{\s*"diagnostics"/))));
1373
+ const errors = isRecord(report) && Array.isArray(report.diagnostics) ? report.diagnostics.flatMap(diagnosticOf) : void 0;
1374
+ if (!errors || status !== 0 && !errors.length) raise("ToolFailed", {
1375
+ tool: "vp lint",
1376
+ output
1377
+ });
1378
+ return errors ?? [];
1379
+ }
1380
+ /** The code a diagnostic points at, on one line and cut short. */
1381
+ function codeAt(root, filename, { offset, length }) {
1382
+ const flat = readFileSync(join(root, filename), "utf8").slice(offset, offset + length).replaceAll(/\s+/g, " ").trim();
1383
+ return flat.length > 48 ? `${flat.slice(0, 47)}…` : flat;
1384
+ }
1385
+ /** What a gate finding says: the kinds with no case, or the cast it found. */
1386
+ function gateWhat(root, rule, diagnostic) {
1387
+ const { filename, span } = diagnostic;
1388
+ if (rule === "tinker/cast" && span) return `\`${codeAt(root, filename, span)}\` hides the type`;
1389
+ const kinds = /Cases not matched: (.+)$/.exec(diagnostic.message)?.[1];
1390
+ if (kinds) return `kind ${kinds} has no case`;
1391
+ return /default case is unnecessary/.test(diagnostic.message) ? "a `default` beside a case for every kind" : diagnostic.message;
1392
+ }
1393
+ const isOn = (level) => level === "deny" || level === "error" || Array.isArray(level) && isOn(level[0]);
1394
+ /**
1395
+ * The gates the app's lint config does not run: a gate rule that is at error nowhere, in its
1396
+ * rules or in an override, and `typeAware`, which the kind gate needs.
1397
+ */
1398
+ function offGates(root, bin) {
1399
+ const { stdout, output } = run(root, bin, ["lint", "--print-config"]);
1400
+ const config = parsed(stdout.slice(Math.max(0, stdout.search(/^\{\s*$/m))));
1401
+ if (!isRecord(config)) return raise("ToolFailed", {
1402
+ tool: "vp lint --print-config",
1403
+ output
1404
+ });
1405
+ const overrides = Array.isArray(config.overrides) ? config.overrides : [];
1406
+ const sets = [config.rules, ...overrides.map((item) => isRecord(item) && item.rules)];
1407
+ const off = Object.keys(gates).map((code) => code.replace(/^(.+)\((.+)\)$/, "$1/$2")).filter((name) => !sets.some((set) => isRecord(set) && isOn(set[name])));
1408
+ return isRecord(config.options) && config.options.typeAware === true ? off : ["options.typeAware", ...off];
1409
+ }
1410
+ /** `vp lint`: a gate's error goes to `types`, every other error to `rules`. */
1411
+ function lint(root) {
1412
+ const bin = needed(root, "vp", "the app has a vite.config; add vite-plus");
1413
+ const off = offGates(root, bin);
1414
+ const types = [];
1415
+ const rules = [];
1416
+ for (const diagnostic of lintReport(run(root, bin, [
1417
+ "lint",
1418
+ "--format",
1419
+ "json"
1420
+ ]))) {
1421
+ const { code, message, help, filename: path, span } = diagnostic;
1422
+ const line = span?.line ?? 1;
1423
+ const gate = gates[code];
1424
+ if (gate) {
1425
+ types.push({
1426
+ path,
1427
+ line,
1428
+ rule: gate,
1429
+ what: gateWhat(root, gate, diagnostic)
1430
+ });
1431
+ continue;
1432
+ }
1433
+ const rule = taught[code] ?? code.replace(/^(.+)\((.+)\)$/, "$1/$2");
1434
+ rules.push({
1435
+ path,
1436
+ line,
1437
+ rule,
1438
+ what: message,
1439
+ ...help ? { help } : {}
1440
+ });
1441
+ }
1442
+ return {
1443
+ types,
1444
+ rules,
1445
+ off
1446
+ };
1447
+ }
1448
+ /** A lint comment that turns rules off, and the rules it names (none names every rule). */
1449
+ const disable = /^(?:\/\/|\/\*)\s*(?:es|ox)lint-disable(?:-next-line|-line)?(?![\w-])([\s\S]*)$/;
1450
+ /** A gate's rule name with no plugin: oxlint takes `typescript/x`, `@typescript-eslint/x`, `x`. */
1451
+ const gateNames = Object.keys(gates).map((code) => code.replace(/^.+\((.+)\)$/, "$1"));
1452
+ /**
1453
+ * Each comment of a file, as the parser reads it: a `//` in a string is no comment. It reads
1454
+ * around every token, so a comment after a `,` counts too.
1455
+ */
1456
+ function commentsOf({ path, text }) {
1457
+ const source = ts.createSourceFile(path, text, ts.ScriptTarget.Latest, true);
1458
+ const ranges = /* @__PURE__ */ new Map();
1459
+ const visit = (node) => {
1460
+ const leading = ts.getLeadingCommentRanges(text, node.pos) ?? [];
1461
+ for (const range of [...leading, ...ts.getTrailingCommentRanges(text, node.end) ?? []]) ranges.set(range.pos, range);
1462
+ for (const child of node.getChildren(source)) visit(child);
1463
+ };
1464
+ visit(source);
1465
+ return [...ranges.values()].map(({ pos, end }) => ({
1466
+ line: source.getLineAndCharacterOfPosition(pos).line + 1,
1467
+ text: text.slice(pos, end)
1468
+ }));
1469
+ }
1470
+ /**
1471
+ * A comment in the app's code that turns a gate off. The lint then reports nothing there, so
1472
+ * the check reports the comment, once: an exception to a gate is a gap row (ADR 0156).
1473
+ */
1474
+ function turnedOff(source) {
1475
+ if (!/lint-disable/.test(source.text)) return [];
1476
+ return commentsOf(source).flatMap(({ line, text }) => {
1477
+ const match = disable.exec(text);
1478
+ if (!match) return [];
1479
+ const [list = ""] = (match[1] ?? "").replace(/\*\/$/, "").split("--");
1480
+ const rules = list.split(",").flatMap((name) => name.trim().split("/").slice(-1)).filter((name) => name !== "");
1481
+ const off = gateNames.filter((gate) => !rules.length || rules.includes(gate));
1482
+ if (!off.length) return [];
1483
+ const what = `a \`lint-disable\` comment turns off ${rules.length ? `the gate ${off.join(", ")}` : "every gate"}`;
1484
+ return [{
1485
+ path: source.path,
1486
+ line,
1487
+ rule: "tinker/gap",
1488
+ what
1489
+ }];
1490
+ });
1491
+ }
1492
+ /** The `switch` that starts on 1-based `line`, as the parser reads it. */
1493
+ function switchAt(source, line) {
1494
+ const lineOf = (node) => source.getLineAndCharacterOfPosition(node.getStart()).line;
1495
+ const visit = (node) => ts.isSwitchStatement(node) && lineOf(node) === line - 1 ? node : ts.forEachChild(node, visit);
1496
+ return visit(source);
1497
+ }
1498
+ /** A function's body, when the node is a function that has one. */
1499
+ function bodyOf(node) {
1500
+ return ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) || ts.isArrowFunction(node) || ts.isMethodDeclaration(node) ? node.body : void 0;
1501
+ }
1502
+ /**
1503
+ * The lines from the start of the function around the `switch` on `line` to the start of its
1504
+ * body. `tsc` puts TS7030 there: on the name, or on the arrow.
1505
+ */
1506
+ function headOf(root, { path, line }) {
1507
+ const text = readFileSync(join(root, path), "utf8");
1508
+ const source = ts.createSourceFile(path, text, ts.ScriptTarget.Latest, true);
1509
+ let node = switchAt(source, line);
1510
+ while (node && !bodyOf(node)) node = node.parent;
1511
+ const body = node && bodyOf(node);
1512
+ if (!node || !body) return void 0;
1513
+ const lineOf = (at) => source.getLineAndCharacterOfPosition(at).line + 1;
1514
+ return {
1515
+ path,
1516
+ from: lineOf(node.getStart()),
1517
+ to: lineOf(body.getStart())
1518
+ };
1519
+ }
1520
+ /**
1521
+ * A kind with no case fails twice: lint names the kind at the `switch`, and `tsc` gives
1522
+ * TS7030 (or TS2366, with a return type) at the head of the function around it. Keep the one
1523
+ * that names the kind.
1524
+ */
1525
+ function once(root, found) {
1526
+ const heads = found.filter(({ rule }) => rule === "tinker/kind").flatMap((kind) => {
1527
+ const head = headOf(root, kind);
1528
+ return head ? [head] : [];
1529
+ });
1530
+ const isHead = ({ path, line, rule }) => (rule === "TS7030" || rule === "TS2366") && heads.some((head) => head.path === path && head.from <= line && line <= head.to);
1531
+ const seen = /* @__PURE__ */ new Set();
1532
+ return found.filter((item) => {
1533
+ const key = `${item.path}:${item.line}:${item.rule}:${item.what}`;
1534
+ if (isHead(item) || seen.has(key)) return false;
1535
+ seen.add(key);
1536
+ return true;
1537
+ });
1538
+ }
1539
+ /**
1540
+ * Run the app's own `tsc` and lint, each where the app has its config: `tsconfig.json` for
1541
+ * `tsc`, a `vite.config` for `vp lint`. The command has no config of its own for either.
1542
+ *
1543
+ * `sources` are the app files the rules read: a comment there that turns a gate off is a
1544
+ * `types` finding.
1545
+ *
1546
+ * @throws `MissingTool` when the config is there but the tool is not installed.
1547
+ * @throws `ToolFailed` when a tool fails and prints no finding.
1548
+ */
1549
+ function runTools(root, sources) {
1550
+ const ran = [];
1551
+ const skipped = [];
1552
+ const types = [];
1553
+ const rules = [];
1554
+ if (existsSync(join(root, "tsconfig.json"))) {
1555
+ types.push(...tsc(root));
1556
+ ran.push("tsc");
1557
+ } else skipped.push("tsc (no tsconfig.json)");
1558
+ if (globSync(viteConfig, { cwd: root }).length) {
1559
+ const found = lint(root);
1560
+ types.push(...found.types, ...sources.flatMap(turnedOff));
1561
+ rules.push(...found.rules);
1562
+ ran.push("lint");
1563
+ if (found.off.length) skipped.push(`gates not at error in the lint config (${found.off.join(", ")})`);
1564
+ } else skipped.push("lint (no vite.config)");
1565
+ return {
1566
+ types: once(root, types),
1567
+ rules,
1568
+ ran,
1569
+ skipped
1570
+ };
1571
+ }
1572
+ //#endregion
1573
+ //#region src/main.ts
1574
+ /** A writer fixes a few findings at a time: more than this is noise. */
1575
+ const shown = 5;
1576
+ const usage = `usage:
1577
+ tinker check [root] [--json]
1578
+ tinker skill list
1579
+ tinker skill load <skill>
1580
+
1581
+ check runs the app's types (tsc, the kind gate, the cast gate), then its rules (Tinker's
1582
+ rules and the app's other lint). Only the first stage that fails prints. Each finding
1583
+ prints its fix. "tinker check: OK" and exit 0 is the only sign that the work is done.
1584
+ `;
1585
+ /** One line per gaps row: marked lines over the row's count, as `G3 5/5`. */
1586
+ function gapLine(gaps) {
1587
+ const rows = gaps.map(({ gap, marked, lines, open }) => `${gap} ${marked}/${lines}${open ? "" : " closed"}`);
1588
+ return rows.length ? `gaps: ${rows.join(", ")}\n` : "";
1589
+ }
1590
+ function fixed({ help, ...found }, sections) {
1591
+ const fix = fixOf(sections, found.rule, found.what);
1592
+ if (fix) return {
1593
+ ...found,
1594
+ fix: fix.right,
1595
+ skill: fix.skill
1596
+ };
1597
+ if (rules.includes(found.rule)) return {
1598
+ ...found,
1599
+ fix: ["No skill you have teaches this rule: run `tinker skill list`."]
1600
+ };
1601
+ return {
1602
+ ...found,
1603
+ fix: help ? [`help: ${help}`] : []
1604
+ };
1605
+ }
1606
+ function failed(root, stage, found, gaps) {
1607
+ const first = [...found].sort((a, b) => a.path.localeCompare(b.path) || a.line - b.line || a.rule.localeCompare(b.rule)).slice(0, shown);
1608
+ const sections = first.some(({ rule }) => rule.startsWith("tinker/")) ? sectionsOf(root) : [];
1609
+ const findings = first.map((item) => fixed(item, sections));
1610
+ return {
1611
+ kind: "failed",
1612
+ stage,
1613
+ total: found.length,
1614
+ findings,
1615
+ gaps
1616
+ };
1617
+ }
1618
+ /**
1619
+ * Report the stages in order: the rules stage prints only when the types stage is clean. Tinker's
1620
+ * own rules read the config, so they run first: a bad config stops the run before the tools.
1621
+ * The gap rule allows a marked Tinker finding of either stage, never a `tsc` or other lint
1622
+ * error; its own findings are rules.
1623
+ */
1624
+ function stages(root) {
1625
+ const { sources, found, doc } = readApp(root);
1626
+ const tools = runTools(root, sources);
1627
+ const all = [
1628
+ ...tools.types,
1629
+ ...found,
1630
+ ...tools.rules
1631
+ ];
1632
+ const isOwn = ({ rule }) => rule.startsWith("tinker/");
1633
+ const own = all.filter(isOwn);
1634
+ const { findings: allowed, gaps } = doc ? applyGaps(own, sources, doc) : {
1635
+ findings: own,
1636
+ gaps: []
1637
+ };
1638
+ const findings = [...allowed, ...all.filter((item) => !isOwn(item))];
1639
+ const typed = new Set(tools.types);
1640
+ const types = findings.filter((item) => typed.has(item));
1641
+ if (types.length) return failed(root, "types", types, []);
1642
+ const broken = findings.filter((item) => !typed.has(item));
1643
+ if (broken.length) return failed(root, "rules", broken, gaps);
1644
+ const ran = [...tools.ran, `rules (${sources.length} files)`];
1645
+ if (tools.skipped.length) return {
1646
+ kind: "incomplete",
1647
+ ran,
1648
+ skipped: tools.skipped,
1649
+ gaps
1650
+ };
1651
+ return {
1652
+ kind: "ok",
1653
+ ran,
1654
+ gaps
1655
+ };
1656
+ }
1657
+ /** A finding's lines: the finding, then its fix once per rule, then the skill to load. */
1658
+ function block({ path, line, rule, what, fix, skill }, first) {
1659
+ const head = `${path}:${line} ${rule} ${what}`;
1660
+ if (!first) return fix.length ? [head, " fix: as above"] : [head];
1661
+ const more = skill ? [`more: tinker skill load ${skill}`] : [];
1662
+ return [head, ...[...fix, ...more].map((text) => ` ${text}`)];
1663
+ }
1664
+ /** Two findings print one fix once: the second points at the first. */
1665
+ const sameFix = (a, b) => a.join("\n") === b.join("\n");
1666
+ function text(report) {
1667
+ const gaps = gapLine(report.gaps);
1668
+ switch (report.kind) {
1669
+ case "ok": return `${gaps}ran: ${report.ran.join(", ")}\ntinker check: OK\n`;
1670
+ case "incomplete": return [
1671
+ `${gaps}ran: ${report.ran.join(", ")}`,
1672
+ `skipped: ${report.skipped.join(", ")}`,
1673
+ "tinker check: not done. A check did not run, so this is no OK.",
1674
+ "Next: add the config the skipped line names, then run `tinker check` again.",
1675
+ ""
1676
+ ].join("\n");
1677
+ case "failed": {
1678
+ const { stage, total, findings } = report;
1679
+ const blocks = findings.map((finding, index) => block(finding, findings.findIndex(({ fix }) => sameFix(fix, finding.fix)) === index));
1680
+ const count = total > findings.length ? `${total} findings, ${findings.length} shown` : "";
1681
+ const after = stage === "types" ? " The rules stage runs once types pass." : "";
1682
+ return [
1683
+ gaps + blocks.map((lines) => lines.join("\n")).join("\n\n"),
1684
+ "",
1685
+ `tinker check: ${stage} failed${count ? `, ${count}` : ""}.`,
1686
+ `Next: fix each finding, then run \`tinker check\` again.${after}`,
1687
+ ""
1688
+ ].join("\n");
1689
+ }
1690
+ }
1691
+ }
1692
+ /** Exit 0 only for `ok`; a stage that did not run is a config the command cannot use. */
1693
+ const codes = {
1694
+ ok: 0,
1695
+ failed: 1,
1696
+ incomplete: 2
1697
+ };
1698
+ function checkCommand(root, json) {
1699
+ if (!existsSync(root)) return {
1700
+ code: 2,
1701
+ out: "",
1702
+ err: `tinker check: no folder at ${root}\n`
1703
+ };
1704
+ try {
1705
+ const report = stages(root);
1706
+ const out = json ? `${JSON.stringify(report)}\n` : text(report);
1707
+ return {
1708
+ code: codes[report.kind],
1709
+ out,
1710
+ err: ""
1711
+ };
1712
+ } catch (error) {
1713
+ if (isError(error, "BadConfig")) {
1714
+ const { path, reason } = error.payload;
1715
+ return {
1716
+ code: 2,
1717
+ out: "",
1718
+ err: `${path}: ${reason}\n`
1719
+ };
1720
+ }
1721
+ if (isError(error, "MissingTool")) {
1722
+ const { tool, reason } = error.payload;
1723
+ return {
1724
+ code: 2,
1725
+ out: "",
1726
+ err: `tinker check: no ${tool}: ${reason}\n`
1727
+ };
1728
+ }
1729
+ if (!isError(error, "ToolFailed")) throw error;
1730
+ const { tool, output } = error.payload;
1731
+ return {
1732
+ code: 2,
1733
+ out: "",
1734
+ err: `tinker check: ${tool} failed and named no file:\n${output}`
1735
+ };
1736
+ }
1737
+ }
1738
+ function skillCommand(root, args) {
1739
+ const [action, use, ...rest] = args;
1740
+ try {
1741
+ if (action === "list" && use === void 0) return {
1742
+ code: 0,
1743
+ out: listSkills(root),
1744
+ err: ""
1745
+ };
1746
+ if (action === "load" && use && !rest.length) return {
1747
+ code: 0,
1748
+ out: loadSkill(root, use),
1749
+ err: ""
1750
+ };
1751
+ } catch (error) {
1752
+ if (!(error instanceof IntentCoreError)) throw error;
1753
+ return {
1754
+ code: 2,
1755
+ out: "",
1756
+ err: `${error.message}\n`
1757
+ };
1758
+ }
1759
+ return {
1760
+ code: 2,
1761
+ out: "",
1762
+ err: usage
1763
+ };
1764
+ }
1765
+ /**
1766
+ * The command, without the process: `argv` is what follows the program name, and `cwd` is
1767
+ * the folder a relative root starts from. Exit 0 is done, 1 is a finding, 2 is a call, a
1768
+ * config or a tool the command cannot use.
1769
+ */
1770
+ function main(argv, cwd) {
1771
+ const json = argv.includes("--json");
1772
+ const [command, ...args] = argv.filter((arg) => arg !== "--json");
1773
+ if (args.some((arg) => arg.startsWith("-"))) return {
1774
+ code: 2,
1775
+ out: "",
1776
+ err: usage
1777
+ };
1778
+ if (command === "skill" && !json) return skillCommand(cwd, args);
1779
+ const [root = ".", ...rest] = args;
1780
+ if (command !== "check" || rest.length) return {
1781
+ code: 2,
1782
+ out: "",
1783
+ err: usage
1784
+ };
1785
+ return checkCommand(resolve(cwd, root), json);
1786
+ }
1787
+ //#endregion
1788
+ export { check as n, isError as r, main as t };