monkeyshape 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +54 -2
  3. package/config/biome.base.json +71 -0
  4. package/config/tsconfig.base.json +31 -0
  5. package/docs/workflow.md +131 -0
  6. package/package.json +68 -4
  7. package/skills/handoff/SKILL.md +54 -0
  8. package/skills/milestone/SKILL.md +107 -0
  9. package/skills/review-pr/SKILL.md +135 -0
  10. package/skills/roadmap/SKILL.md +66 -0
  11. package/skills/track/SKILL.md +75 -0
  12. package/src/adapters/baseline.ts +55 -0
  13. package/src/adapters/config.ts +25 -0
  14. package/src/adapters/init.ts +176 -0
  15. package/src/adapters/process.ts +38 -0
  16. package/src/adapters/reviews.ts +170 -0
  17. package/src/adapters/skills.ts +113 -0
  18. package/src/adapters/tracks.ts +616 -0
  19. package/src/adapters/workspace.ts +281 -0
  20. package/src/api/monkeyshape.ts +8 -0
  21. package/src/cli/main.ts +359 -0
  22. package/src/core/arch.ts +224 -0
  23. package/src/core/budgets.ts +187 -0
  24. package/src/core/check.ts +122 -0
  25. package/src/core/coverage.ts +118 -0
  26. package/src/core/decisions.ts +65 -0
  27. package/src/core/garden.ts +41 -0
  28. package/src/core/glob.ts +22 -0
  29. package/src/core/handoff.ts +183 -0
  30. package/src/core/hooks.ts +60 -0
  31. package/src/core/jsonc.ts +26 -0
  32. package/src/core/layout.ts +123 -0
  33. package/src/core/markdown.ts +93 -0
  34. package/src/core/model.ts +100 -0
  35. package/src/core/parse.ts +41 -0
  36. package/src/core/paths.ts +19 -0
  37. package/src/core/ratchet.ts +75 -0
  38. package/src/core/refs.ts +214 -0
  39. package/src/core/report.ts +67 -0
  40. package/src/core/rules/ast.ts +50 -0
  41. package/src/core/rules/decodeStrict.ts +60 -0
  42. package/src/core/rules/effectRunAtEdge.ts +33 -0
  43. package/src/core/rules/engine.ts +150 -0
  44. package/src/core/rules/noErrorSpread.ts +28 -0
  45. package/src/core/rules/noNondeterminism.ts +65 -0
  46. package/src/core/rules/noThrow.ts +79 -0
  47. package/src/core/rules/registry.ts +15 -0
  48. package/src/core/scaffold.ts +90 -0
  49. package/src/core/scope.ts +120 -0
  50. package/src/core/skills.ts +291 -0
  51. package/src/core/tracks.ts +358 -0
  52. package/src/helpers/decodeStrict.ts +8 -0
  53. package/src/schemas/config.ts +221 -0
  54. package/src/schemas/errors.ts +31 -0
  55. package/template/.github/pull_request_template.md +11 -0
  56. package/template/.github/workflows/ci.yml +22 -0
  57. package/template/AGENTS.md +37 -0
  58. package/template/CLAUDE.md +1 -0
  59. package/template/DECISIONS.md +8 -0
  60. package/template/README.md +14 -0
  61. package/template/docs/roadmap.md +14 -0
  62. package/template/gitignore +7 -0
  63. package/template/notes/.gitkeep +0 -0
  64. package/template/plan/.gitkeep +0 -0
  65. package/template/shape.config.ts +26 -0
  66. package/template/test/toolchain.test.ts +7 -0
@@ -0,0 +1,150 @@
1
+ /**
2
+ * Custom rules run over the oxc AST. A rule reports offsets; the engine owns scope,
3
+ * entry-file exemptions, per-rule allowances and inline `shape-ignore` comments, so every
4
+ * rule gets the same escape hatches and every escape hatch carries a reason.
5
+ *
6
+ * // shape-ignore no-throw: Bun.serve's fetch handler must throw to send a 500
7
+ *
8
+ * An ignore comment covers its own line and the next one.
9
+ */
10
+ import type { VisitorObject } from "oxc-parser";
11
+ import { Visitor } from "oxc-parser";
12
+ import type { ResolvedConfig } from "../../schemas/config.ts";
13
+ import { matchesAny } from "../glob.ts";
14
+ import { lineAt, type Snapshot, type Violation } from "../model.ts";
15
+ import { type Parsed, parse } from "../parse.ts";
16
+
17
+ export interface Finding {
18
+ readonly offset: number;
19
+ /** Overrides the rule's message for this finding. */
20
+ readonly message?: string;
21
+ }
22
+
23
+ export interface Rule {
24
+ readonly id: string;
25
+ readonly layer: "core" | "agentic";
26
+ /** The class of bug this rule removes, for the registry and `mshape rules`. */
27
+ readonly bugClass: string;
28
+ /** Why, and what to do instead. Shown with every violation. */
29
+ readonly message: string;
30
+ /** Whether composition roots (`entry`) are exempt. */
31
+ readonly entryExempt: boolean;
32
+ readonly visit: (parsed: Parsed, report: (finding: Finding) => void) => VisitorObject;
33
+ }
34
+
35
+ /** Only a line comment that starts with the directive counts, so prose can mention it. */
36
+ const IGNORE = /^\s*shape-ignore\s+([a-z0-9-]+)(?::\s*(.*))?/;
37
+
38
+ interface Ignore {
39
+ readonly rule: string;
40
+ readonly line: number;
41
+ readonly reason: string;
42
+ used: boolean;
43
+ }
44
+
45
+ const violation = (rule: string, file: string, line: number, message: string): Violation => ({
46
+ check: "rules",
47
+ rule: `rules/${rule}`,
48
+ file,
49
+ line,
50
+ message,
51
+ });
52
+
53
+ export const runRule = (rule: Rule, parsed: Parsed): ReadonlyArray<Finding> => {
54
+ const findings: Array<Finding> = [];
55
+ new Visitor(rule.visit(parsed, (finding) => findings.push(finding))).visit(parsed.program);
56
+ return findings;
57
+ };
58
+
59
+ export const checkRules = (
60
+ config: ResolvedConfig,
61
+ snapshot: Snapshot,
62
+ rules: ReadonlyArray<Rule>,
63
+ ): ReadonlyArray<Violation> => {
64
+ const violations: Array<Violation> = [];
65
+ const active = rules.filter(
66
+ (rule) => config.layers.includes(rule.layer) && config.rules[rule.id]?.off === undefined,
67
+ );
68
+ const usedAllowances = new Set<string>();
69
+ const known = new Set(rules.map((rule) => rule.id));
70
+
71
+ for (const id of Object.keys(config.rules))
72
+ if (!known.has(id))
73
+ violations.push(violation("config", "shape.config.ts", 1, `configures unknown rule '${id}'`));
74
+
75
+ for (const file of snapshot.files) {
76
+ if (!matchesAny(file, config.sources.include) || matchesAny(file, config.sources.exclude))
77
+ continue;
78
+ const text = snapshot.texts.get(file);
79
+ if (text === undefined) continue;
80
+ const parsed = parse(file, text);
81
+ for (const error of parsed.syntaxErrors)
82
+ violations.push(violation("syntax", file, 1, `does not parse: ${error}`));
83
+
84
+ const ignores: Array<Ignore> = [];
85
+ for (const comment of parsed.comments) {
86
+ const match = comment.type === "Line" ? IGNORE.exec(comment.value) : null;
87
+ if (match === null) continue;
88
+ const reason = (match[2] ?? "").trim();
89
+ const line = lineAt(text, comment.end);
90
+ if (reason.length < 8) {
91
+ violations.push(
92
+ violation(
93
+ "ignore-without-reason",
94
+ file,
95
+ line,
96
+ "a shape-ignore needs `: <reason>` a later agent can weigh",
97
+ ),
98
+ );
99
+ continue;
100
+ }
101
+ ignores.push({ rule: match[1] ?? "", line, reason, used: false });
102
+ }
103
+
104
+ const entry = matchesAny(file, config.entry);
105
+ for (const rule of active) {
106
+ if (rule.entryExempt && entry) continue;
107
+ const allowance = (config.rules[rule.id]?.allow ?? []).find((a) =>
108
+ matchesAny(file, [a.path]),
109
+ );
110
+ for (const finding of runRule(rule, parsed)) {
111
+ if (allowance !== undefined) {
112
+ usedAllowances.add(`${rule.id}\0${allowance.path}`);
113
+ continue;
114
+ }
115
+ const line = lineAt(text, finding.offset);
116
+ const ignore = ignores.find(
117
+ (i) => i.rule === rule.id && (i.line === line || i.line === line - 1),
118
+ );
119
+ if (ignore !== undefined) {
120
+ ignore.used = true;
121
+ continue;
122
+ }
123
+ violations.push(violation(rule.id, file, line, finding.message ?? rule.message));
124
+ }
125
+ }
126
+ for (const ignore of ignores)
127
+ if (!ignore.used)
128
+ violations.push(
129
+ violation(
130
+ "unused-ignore",
131
+ file,
132
+ ignore.line,
133
+ `shape-ignore ${ignore.rule} suppresses nothing; delete it`,
134
+ ),
135
+ );
136
+ }
137
+
138
+ for (const [id, setting] of Object.entries(config.rules))
139
+ for (const allowance of setting.allow ?? [])
140
+ if (!usedAllowances.has(`${id}\0${allowance.path}`))
141
+ violations.push(
142
+ violation(
143
+ "unused-allowance",
144
+ "shape.config.ts",
145
+ 1,
146
+ `rules.${id}.allow '${allowance.path}' allows nothing; delete it`,
147
+ ),
148
+ );
149
+ return violations;
150
+ };
@@ -0,0 +1,28 @@
1
+ import type { Expression } from "oxc-parser";
2
+ import type { Rule } from "./engine.ts";
3
+
4
+ /** Names that mean an error. Not `e`: it is as often an element or entry as an error. */
5
+ const ERROR_NAME = /^(err|error|cause|failure|defect)$|Error$/i;
6
+
7
+ const errorLike = (expression: Expression): boolean =>
8
+ (expression.type === "Identifier" && ERROR_NAME.test(expression.name)) ||
9
+ (expression.type === "MemberExpression" &&
10
+ !expression.computed &&
11
+ expression.property.type === "Identifier" &&
12
+ ERROR_NAME.test(expression.property.name));
13
+
14
+ export const noErrorSpread: Rule = {
15
+ id: "no-error-spread",
16
+ layer: "core",
17
+ bugClass: "Errors copied by spreading, which drops the prototype, the stack and the cause.",
18
+ message:
19
+ "spreads an error into an object, losing its class, stack and cause. Pass the error itself as `cause`, or copy the fields you need by name.",
20
+ entryExempt: false,
21
+ visit: (_parsed, report) => ({
22
+ ObjectExpression: (node) => {
23
+ for (const property of node.properties)
24
+ if (property.type === "SpreadElement" && errorLike(property.argument))
25
+ report({ offset: property.start });
26
+ },
27
+ }),
28
+ };
@@ -0,0 +1,65 @@
1
+ import { memberPath } from "./ast.ts";
2
+ import type { Rule } from "./engine.ts";
3
+
4
+ const CALLS: ReadonlyMap<string, string> = new Map([
5
+ ["Date.now", "reads the wall clock. Use Clock or DateTime.now so tests control time."],
6
+ ["performance.now", "reads the wall clock. Use Clock so tests control time."],
7
+ ["Math.random", "is unseeded randomness. Use Random so tests are reproducible."],
8
+ [
9
+ "Promise.all",
10
+ "is unstructured concurrency: no interruption, no bound. Use Effect.all / Effect.forEach.",
11
+ ],
12
+ ["Promise.race", "is unstructured concurrency: the loser keeps running. Use Effect.race."],
13
+ ["Promise.allSettled", 'is unstructured concurrency. Use Effect.all with { mode: "either" }.'],
14
+ ["Promise.any", "is unstructured concurrency. Use Effect.firstSuccessOf."],
15
+ ]);
16
+
17
+ const TIMERS: ReadonlyMap<string, string> = new Map([
18
+ ["setTimeout", "is a real-time timer. Use Effect.sleep or Schedule so tests control time."],
19
+ ["setInterval", "is a real-time timer. Use Schedule so tests control time."],
20
+ ["setImmediate", "escapes the runtime. Use Effect.yieldNow."],
21
+ ]);
22
+
23
+ export const noNondeterminism: Rule = {
24
+ id: "no-nondeterminism",
25
+ layer: "core",
26
+ bugClass:
27
+ "Hidden clock, randomness, environment and timers, which make runs irreproducible and caches wrong.",
28
+ message: "reads the host directly. Go through an Effect service so tests and replays control it.",
29
+ entryExempt: true,
30
+ visit: (_parsed, report) => ({
31
+ CallExpression: (node) => {
32
+ const member = memberPath(node.callee);
33
+ const hint =
34
+ member !== undefined
35
+ ? CALLS.get(`${member.object}.${member.property}`)
36
+ : node.callee.type === "Identifier"
37
+ ? TIMERS.get(node.callee.name)
38
+ : undefined;
39
+ if (hint !== undefined) report({ offset: node.start, message: hint });
40
+ },
41
+ NewExpression: (node) => {
42
+ if (
43
+ node.callee.type === "Identifier" &&
44
+ node.callee.name === "Date" &&
45
+ node.arguments.length === 0
46
+ )
47
+ report({
48
+ offset: node.start,
49
+ message: "reads the wall clock. Use Clock or DateTime.now so tests control time.",
50
+ });
51
+ },
52
+ MemberExpression: (node) => {
53
+ const member = memberPath(node);
54
+ if (
55
+ member !== undefined &&
56
+ member.property === "env" &&
57
+ (member.object === "process" || member.object === "Bun")
58
+ )
59
+ report({
60
+ offset: node.start,
61
+ message: "reads the environment directly. Use Config, provided at the composition root.",
62
+ });
63
+ },
64
+ }),
65
+ };
@@ -0,0 +1,79 @@
1
+ import type { CallExpression, Class, Expression } from "oxc-parser";
2
+ import { importBindings, isEffectModule, memberPath } from "./ast.ts";
3
+ import type { Rule } from "./engine.ts";
4
+
5
+ const ERROR_CLASSES = new Set([
6
+ "Error",
7
+ "TypeError",
8
+ "RangeError",
9
+ "SyntaxError",
10
+ "ReferenceError",
11
+ "EvalError",
12
+ "URIError",
13
+ "AggregateError",
14
+ ]);
15
+
16
+ /** `Effect.try` / `Effect.tryPromise`: the runtime catches what their `try` callback throws. */
17
+ const CATCHING = new Set(["try", "tryPromise"]);
18
+
19
+ const isFunction = (node: Expression | undefined): boolean =>
20
+ node?.type === "ArrowFunctionExpression" || node?.type === "FunctionExpression";
21
+
22
+ /**
23
+ * The function whose throws are caught: the sole argument, or the `try` property of the
24
+ * options object. Not `catch`, which maps an error that has already been caught.
25
+ */
26
+ const tryCallback = (call: CallExpression): Expression | undefined => {
27
+ const argument = call.arguments[0];
28
+ if (argument === undefined || argument.type === "SpreadElement") return undefined;
29
+ if (isFunction(argument)) return argument;
30
+ if (argument.type !== "ObjectExpression") return undefined;
31
+ for (const property of argument.properties)
32
+ if (
33
+ property.type === "Property" &&
34
+ !property.computed &&
35
+ property.key.type === "Identifier" &&
36
+ property.key.name === "try" &&
37
+ isFunction(property.value)
38
+ )
39
+ return property.value;
40
+ return undefined;
41
+ };
42
+
43
+ export const noThrow: Rule = {
44
+ id: "no-throw",
45
+ layer: "core",
46
+ bugClass:
47
+ "Mixed error paradigms: thrown errors escape the typed error channel and turn into defects.",
48
+ message:
49
+ "throws or defines an Error class. Fail with a Schema.TaggedError (Effect.fail) so the error is typed and handled by tag.",
50
+ entryExempt: false,
51
+ visit: (parsed, report) => {
52
+ const bindings = importBindings(parsed.program);
53
+ const caught: Array<{ start: number; end: number }> = [];
54
+ const errorClass = (node: Class) => {
55
+ if (node.superClass?.type === "Identifier" && ERROR_CLASSES.has(node.superClass.name))
56
+ report({ offset: node.start });
57
+ };
58
+ return {
59
+ // Calls are visited before the throws inside them, so the ranges are known in time.
60
+ CallExpression: (node) => {
61
+ const member = memberPath(node.callee);
62
+ if (
63
+ member === undefined ||
64
+ !CATCHING.has(member.property) ||
65
+ !isEffectModule(bindings, member.object, "Effect")
66
+ )
67
+ return;
68
+ const callback = tryCallback(node);
69
+ if (callback !== undefined) caught.push({ start: callback.start, end: callback.end });
70
+ },
71
+ ThrowStatement: (node) => {
72
+ if (!caught.some((range) => node.start >= range.start && node.end <= range.end))
73
+ report({ offset: node.start });
74
+ },
75
+ ClassDeclaration: errorClass,
76
+ ClassExpression: errorClass,
77
+ };
78
+ },
79
+ };
@@ -0,0 +1,15 @@
1
+ /** Every custom rule. Adding one: a file in this directory, an entry here, fixtures in test/rules. */
2
+ import { decodeStrict } from "./decodeStrict.ts";
3
+ import { effectRunAtEdge } from "./effectRunAtEdge.ts";
4
+ import type { Rule } from "./engine.ts";
5
+ import { noErrorSpread } from "./noErrorSpread.ts";
6
+ import { noNondeterminism } from "./noNondeterminism.ts";
7
+ import { noThrow } from "./noThrow.ts";
8
+
9
+ export const RULES: ReadonlyArray<Rule> = [
10
+ decodeStrict,
11
+ noNondeterminism,
12
+ noThrow,
13
+ effectRunAtEdge,
14
+ noErrorSpread,
15
+ ];
@@ -0,0 +1,90 @@
1
+ /**
2
+ * What `mshape init` writes: the package's `template/` files, rendered, plus the JSON configs
3
+ * generated here. The configs are generated rather than copied because they pin versions, and
4
+ * because a `biome.json` inside `template/` would be a nested root config for biome itself.
5
+ * `.claude/settings.json` is rendered from the hook list in `hooks.ts`, the same as this repo's.
6
+ */
7
+
8
+ import { HOOKS, renderSettings, SETTINGS_FILE } from "./hooks.ts";
9
+
10
+ /** Lowercase words joined by hyphens: a package name, a directory and a beads prefix at once. */
11
+ export const REPO_NAME = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
12
+
13
+ /** The toolchain a new repo pins: this package's own, so the adopter runs what was tested. */
14
+ export interface Toolchain {
15
+ /** Bun's version, for `packageManager` (CI reads it from there). */
16
+ readonly bun: string;
17
+ /** The monkeyshape dependency spec: its exact version, or a tarball when testing a release. */
18
+ readonly monkeyshape: string;
19
+ readonly effect: string;
20
+ readonly biome: string;
21
+ readonly typescript: string;
22
+ readonly typesBun: string;
23
+ }
24
+
25
+ /**
26
+ * npm drops `.gitignore` from published packages, so the template stores it without the dot.
27
+ * Any other dotfile ships as is.
28
+ */
29
+ const RENAMED: Readonly<Record<string, string>> = { gitignore: ".gitignore" };
30
+
31
+ export const targetPath = (templatePath: string): string => RENAMED[templatePath] ?? templatePath;
32
+
33
+ const render = (text: string, name: string): string => text.replaceAll("{{name}}", name);
34
+
35
+ const json = (value: unknown): string => `${JSON.stringify(value, null, 2)}\n`;
36
+
37
+ const configs = (name: string, toolchain: Toolchain): Record<string, string> => ({
38
+ "package.json": json({
39
+ name,
40
+ version: "0.0.0",
41
+ private: true,
42
+ type: "module",
43
+ packageManager: `bun@${toolchain.bun}`,
44
+ scripts: {
45
+ typecheck: "tsc -p .",
46
+ lint: "biome ci --error-on-warnings .",
47
+ fix: "biome check --write .",
48
+ // How hooks and skills run mshape: D-run-mshape.
49
+ mshape: "mshape",
50
+ shape: "mshape check",
51
+ check: "bun run typecheck && bun run lint && bun run shape && bun test --pass-with-no-tests",
52
+ },
53
+ dependencies: { effect: toolchain.effect },
54
+ devDependencies: {
55
+ "@biomejs/biome": toolchain.biome,
56
+ "@types/bun": toolchain.typesBun,
57
+ monkeyshape: toolchain.monkeyshape,
58
+ typescript: toolchain.typescript,
59
+ },
60
+ }),
61
+ "tsconfig.json": json({
62
+ extends: "monkeyshape/tsconfig.base.json",
63
+ include: ["src", "test", "*.ts"],
64
+ }),
65
+ "biome.json": json({
66
+ root: true,
67
+ extends: ["monkeyshape/biome"],
68
+ files: { includes: ["src/**", "test/**", "*.json", "*.ts"] },
69
+ }),
70
+ [SETTINGS_FILE]: renderSettings(HOOKS),
71
+ });
72
+
73
+ /** Every file of the new repo, by repo-relative path. Generated configs win over the template. */
74
+ export const scaffold = (
75
+ name: string,
76
+ template: ReadonlyMap<string, string>,
77
+ toolchain: Toolchain,
78
+ ): ReadonlyMap<string, string> =>
79
+ new Map([
80
+ ...[...template].map(([path, text]) => [targetPath(path), render(text, name)] as const),
81
+ ...Object.entries(configs(name, toolchain)),
82
+ ]);
83
+
84
+ /** The last thing `init` prints: what to do now, and where the conventions are. */
85
+ export const nextStep = (name: string, workflowUrl: string): string =>
86
+ [
87
+ `Next: open a chat with your coding agent in ${name}/ and run /roadmap with a brain-dump of`,
88
+ "what you want to build. It writes docs/roadmap.md and the first epics.",
89
+ `The working loop, in full: ${workflowUrl}`,
90
+ ].join("\n");
@@ -0,0 +1,120 @@
1
+ /**
2
+ * Lexical scopes, just enough to answer "does this name, at this offset, refer to a local
3
+ * binding?" A binding is visible over its scope's whole span (hoisting and the temporal dead
4
+ * zone are ignored: both still mean the name is local there).
5
+ *
6
+ * - `var` and function declarations bind in the nearest function (or the module).
7
+ * - `let`, `const` and classes bind in the nearest block.
8
+ * - Parameters bind in their function; a function expression's own name binds in itself.
9
+ * - A catch parameter binds in its clause; imports bind in the module.
10
+ */
11
+ import { type Program, visitorKeys } from "oxc-parser";
12
+
13
+ interface Node {
14
+ readonly type: string;
15
+ readonly start: number;
16
+ readonly end: number;
17
+ readonly [key: string]: unknown;
18
+ }
19
+
20
+ const isNode = (value: unknown): value is Node =>
21
+ typeof value === "object" &&
22
+ value !== null &&
23
+ typeof (value as { type?: unknown }).type === "string" &&
24
+ typeof (value as { start?: unknown }).start === "number";
25
+
26
+ const FUNCTIONS = new Set(["FunctionDeclaration", "FunctionExpression", "ArrowFunctionExpression"]);
27
+ const BLOCKS = new Set([
28
+ "Program",
29
+ "BlockStatement",
30
+ "StaticBlock",
31
+ "ForStatement",
32
+ "ForInStatement",
33
+ "ForOfStatement",
34
+ "SwitchStatement",
35
+ "CatchClause",
36
+ ...FUNCTIONS,
37
+ ]);
38
+
39
+ /** Names a binding pattern declares: `x`, `{ a, b: c }`, `[d, ...e]`, `f = 1`. */
40
+ export const patternNames = (pattern: unknown): ReadonlyArray<string> => {
41
+ if (!isNode(pattern)) return [];
42
+ switch (pattern.type) {
43
+ case "Identifier":
44
+ return typeof pattern["name"] === "string" ? [pattern["name"]] : [];
45
+ case "ObjectPattern":
46
+ return (pattern["properties"] as ReadonlyArray<Node>).flatMap((p) =>
47
+ patternNames(p.type === "RestElement" ? p["argument"] : p["value"]),
48
+ );
49
+ case "ArrayPattern":
50
+ return (pattern["elements"] as ReadonlyArray<unknown>).flatMap(patternNames);
51
+ case "AssignmentPattern":
52
+ return patternNames(pattern["left"]);
53
+ case "RestElement":
54
+ return patternNames(pattern["argument"]);
55
+ case "TSParameterProperty":
56
+ return patternNames(pattern["parameter"]);
57
+ default:
58
+ return [];
59
+ }
60
+ };
61
+
62
+ export interface Scopes {
63
+ /** Whether `name` at `offset` refers to a binding declared in the file. */
64
+ readonly isLocal: (name: string, offset: number) => boolean;
65
+ }
66
+
67
+ export const scopes = (program: Program): Scopes => {
68
+ const bindings = new Map<string, Array<{ start: number; end: number }>>();
69
+ const bind = (pattern: unknown, scope: Node | undefined) => {
70
+ if (scope === undefined) return;
71
+ for (const name of patternNames(pattern)) {
72
+ const ranges = bindings.get(name) ?? [];
73
+ ranges.push({ start: scope.start, end: scope.end });
74
+ bindings.set(name, ranges);
75
+ }
76
+ };
77
+
78
+ const walk = (node: Node, stack: Array<Node>) => {
79
+ const block = stack.at(-1);
80
+ const fn = stack.findLast((s) => FUNCTIONS.has(s.type) || s.type === "Program");
81
+ switch (node.type) {
82
+ case "VariableDeclaration":
83
+ for (const declarator of node["declarations"] as ReadonlyArray<Node>)
84
+ bind(declarator["id"], node["kind"] === "var" ? fn : block);
85
+ break;
86
+ case "FunctionDeclaration":
87
+ bind(node["id"], block);
88
+ break;
89
+ case "ClassDeclaration":
90
+ bind(node["id"], block);
91
+ break;
92
+ case "ImportSpecifier":
93
+ case "ImportDefaultSpecifier":
94
+ case "ImportNamespaceSpecifier":
95
+ bind(node["local"], stack[0]);
96
+ break;
97
+ }
98
+ if (FUNCTIONS.has(node.type)) {
99
+ for (const param of node["params"] as ReadonlyArray<unknown>) bind(param, node);
100
+ if (node.type === "FunctionExpression") bind(node["id"], node);
101
+ }
102
+ if (node.type === "CatchClause") bind(node["param"], node);
103
+
104
+ const scoped = BLOCKS.has(node.type);
105
+ if (scoped) stack.push(node);
106
+ for (const key of visitorKeys[node.type] ?? []) {
107
+ const child = node[key];
108
+ if (Array.isArray(child)) {
109
+ for (const item of child) if (isNode(item)) walk(item, stack);
110
+ } else if (isNode(child)) walk(child, stack);
111
+ }
112
+ if (scoped) stack.pop();
113
+ };
114
+
115
+ walk(program as unknown as Node, []);
116
+ return {
117
+ isLocal: (name, offset) =>
118
+ (bindings.get(name) ?? []).some((range) => offset >= range.start && offset < range.end),
119
+ };
120
+ };