@principal-ai/subsystems-core 0.51.4 → 0.51.5

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 (144) hide show
  1. package/README.md +21 -6
  2. package/dist/audit/boundary.d.ts +104 -0
  3. package/dist/audit/boundary.d.ts.map +1 -0
  4. package/dist/audit/boundary.js +363 -0
  5. package/dist/audit/boundary.js.map +1 -0
  6. package/dist/audit/c4.d.ts +41 -0
  7. package/dist/audit/c4.d.ts.map +1 -0
  8. package/dist/audit/c4.js +41 -0
  9. package/dist/audit/c4.js.map +1 -0
  10. package/dist/audit/engine.d.ts +135 -0
  11. package/dist/audit/engine.d.ts.map +1 -0
  12. package/dist/audit/engine.js +828 -0
  13. package/dist/audit/engine.js.map +1 -0
  14. package/dist/audit/fixes.d.ts +80 -0
  15. package/dist/audit/fixes.d.ts.map +1 -0
  16. package/dist/audit/fixes.js +162 -0
  17. package/dist/audit/fixes.js.map +1 -0
  18. package/dist/audit/hash.d.ts +25 -0
  19. package/dist/audit/hash.d.ts.map +1 -0
  20. package/dist/audit/hash.js +53 -0
  21. package/dist/audit/hash.js.map +1 -0
  22. package/dist/audit/index.d.ts +11 -1
  23. package/dist/audit/index.d.ts.map +1 -1
  24. package/dist/audit/index.js +37 -3
  25. package/dist/audit/index.js.map +1 -1
  26. package/dist/audit/local-graphify.d.ts +75 -0
  27. package/dist/audit/local-graphify.d.ts.map +1 -0
  28. package/dist/audit/local-graphify.js +283 -0
  29. package/dist/audit/local-graphify.js.map +1 -0
  30. package/dist/audit/paths.d.ts +16 -0
  31. package/dist/audit/paths.d.ts.map +1 -0
  32. package/dist/audit/paths.js +31 -0
  33. package/dist/audit/paths.js.map +1 -0
  34. package/dist/audit/pure.d.ts +18 -0
  35. package/dist/audit/pure.d.ts.map +1 -0
  36. package/dist/audit/pure.js +50 -0
  37. package/dist/audit/pure.js.map +1 -0
  38. package/dist/audit/report-logic.d.ts +17 -0
  39. package/dist/audit/report-logic.d.ts.map +1 -0
  40. package/dist/audit/report-logic.js +206 -0
  41. package/dist/audit/report-logic.js.map +1 -0
  42. package/dist/audit/report.d.ts +136 -0
  43. package/dist/audit/report.d.ts.map +1 -0
  44. package/dist/audit/report.js +3 -0
  45. package/dist/audit/report.js.map +1 -0
  46. package/dist/audit/trail.d.ts +29 -0
  47. package/dist/audit/trail.d.ts.map +1 -0
  48. package/dist/audit/trail.js +59 -0
  49. package/dist/audit/trail.js.map +1 -0
  50. package/dist/audit/verification.d.ts +98 -0
  51. package/dist/audit/verification.d.ts.map +1 -0
  52. package/dist/audit/verification.js +11 -0
  53. package/dist/audit/verification.js.map +1 -0
  54. package/dist/audit/verify/component.d.ts +68 -0
  55. package/dist/audit/verify/component.d.ts.map +1 -0
  56. package/dist/audit/verify/component.js +500 -0
  57. package/dist/audit/verify/component.js.map +1 -0
  58. package/dist/audit/verify/declarations.d.ts +58 -0
  59. package/dist/audit/verify/declarations.d.ts.map +1 -0
  60. package/dist/audit/verify/declarations.js +227 -0
  61. package/dist/audit/verify/declarations.js.map +1 -0
  62. package/dist/audit/verify/grammar.d.ts +12 -0
  63. package/dist/audit/verify/grammar.d.ts.map +1 -0
  64. package/dist/audit/verify/grammar.js +57 -0
  65. package/dist/audit/verify/grammar.js.map +1 -0
  66. package/dist/audit/verify/index.d.ts +12 -0
  67. package/dist/audit/verify/index.d.ts.map +1 -0
  68. package/dist/audit/verify/index.js +31 -0
  69. package/dist/audit/verify/index.js.map +1 -0
  70. package/dist/audit/verify/parser.d.ts +19 -0
  71. package/dist/audit/verify/parser.d.ts.map +1 -0
  72. package/dist/audit/verify/parser.js +122 -0
  73. package/dist/audit/verify/parser.js.map +1 -0
  74. package/dist/audit/verify/span.d.ts +49 -0
  75. package/dist/audit/verify/span.d.ts.map +1 -0
  76. package/dist/audit/verify/span.js +377 -0
  77. package/dist/audit/verify/span.js.map +1 -0
  78. package/dist/graphify/anchor.d.ts +45 -0
  79. package/dist/graphify/anchor.d.ts.map +1 -0
  80. package/dist/graphify/anchor.js +179 -0
  81. package/dist/graphify/anchor.js.map +1 -0
  82. package/dist/graphify/consolidated.d.ts +259 -0
  83. package/dist/graphify/consolidated.d.ts.map +1 -0
  84. package/dist/graphify/consolidated.js +12 -0
  85. package/dist/graphify/consolidated.js.map +1 -0
  86. package/dist/graphify/construct.d.ts +41 -0
  87. package/dist/graphify/construct.d.ts.map +1 -0
  88. package/dist/graphify/construct.js +106 -0
  89. package/dist/graphify/construct.js.map +1 -0
  90. package/dist/graphify/ids.d.ts +19 -0
  91. package/dist/graphify/ids.d.ts.map +1 -0
  92. package/dist/graphify/ids.js +53 -0
  93. package/dist/graphify/ids.js.map +1 -0
  94. package/dist/graphify/index.d.ts +16 -0
  95. package/dist/graphify/index.d.ts.map +1 -0
  96. package/dist/graphify/index.js +32 -0
  97. package/dist/graphify/index.js.map +1 -0
  98. package/dist/graphify/resolve.d.ts +48 -0
  99. package/dist/graphify/resolve.d.ts.map +1 -0
  100. package/dist/graphify/resolve.js +89 -0
  101. package/dist/graphify/resolve.js.map +1 -0
  102. package/dist/graphify/signature.d.ts +87 -0
  103. package/dist/graphify/signature.d.ts.map +1 -0
  104. package/dist/graphify/signature.js +282 -0
  105. package/dist/graphify/signature.js.map +1 -0
  106. package/dist/graphify/types.d.ts +141 -0
  107. package/dist/graphify/types.d.ts.map +1 -0
  108. package/dist/graphify/types.js +9 -0
  109. package/dist/graphify/types.js.map +1 -0
  110. package/dist/index.d.ts +1 -1
  111. package/dist/index.d.ts.map +1 -1
  112. package/dist/index.js +3 -3
  113. package/dist/index.js.map +1 -1
  114. package/package.json +16 -2
  115. package/src/audit/boundary.ts +447 -0
  116. package/src/audit/c4.ts +70 -0
  117. package/src/audit/engine.ts +1058 -0
  118. package/src/audit/fixes.ts +192 -0
  119. package/src/audit/hash.ts +58 -0
  120. package/src/audit/index.ts +33 -8
  121. package/src/audit/local-graphify.test.ts +163 -0
  122. package/src/audit/local-graphify.ts +354 -0
  123. package/src/audit/paths.ts +25 -0
  124. package/src/audit/pure.ts +91 -0
  125. package/src/audit/report-logic.test.ts +145 -0
  126. package/src/audit/report-logic.ts +245 -0
  127. package/src/audit/report.ts +203 -0
  128. package/src/audit/trail.ts +77 -0
  129. package/src/audit/verification.ts +104 -0
  130. package/src/audit/verify/component.ts +760 -0
  131. package/src/audit/verify/declarations.ts +284 -0
  132. package/src/audit/verify/grammar.ts +57 -0
  133. package/src/audit/verify/index.ts +41 -0
  134. package/src/audit/verify/parser.ts +124 -0
  135. package/src/audit/verify/span.ts +478 -0
  136. package/src/graphify/anchor.ts +206 -0
  137. package/src/graphify/consolidated.ts +298 -0
  138. package/src/graphify/construct.ts +153 -0
  139. package/src/graphify/ids.ts +48 -0
  140. package/src/graphify/index.ts +16 -0
  141. package/src/graphify/resolve.ts +115 -0
  142. package/src/graphify/signature.ts +354 -0
  143. package/src/graphify/types.ts +164 -0
  144. package/src/index.ts +3 -3
@@ -0,0 +1,284 @@
1
+ /**
2
+ * Source declaration parsing shared by every audit host.
3
+ *
4
+ * Graphify supplies candidates; source supplies declaration identity, kind and
5
+ * span. No subsystem-model membership, inferred graph kind, or display label
6
+ * alone is accepted as verification.
7
+ */
8
+
9
+ import { createHash } from 'node:crypto'
10
+ import { promises as fs } from 'node:fs'
11
+ import { isAbsolute, relative, resolve, sep } from 'node:path'
12
+ import type { Node as SyntaxNode } from 'web-tree-sitter'
13
+ import { normalizeDeclarationLine } from '../hash'
14
+ import { sharedParserFor, parseWith } from './parser'
15
+
16
+ export interface ParsedDeclaration {
17
+ name: string
18
+ symbol: string
19
+ construct: string
20
+ startLine: number
21
+ endLine: number
22
+ /** Graphify may point at the declaration after an export/decorator wrapper. */
23
+ anchorEnd: number
24
+ hasError: boolean
25
+ contentHash: string
26
+ }
27
+
28
+ const kinds: Record<string, string> = {
29
+ function_declaration: 'function',
30
+ generator_function_declaration: 'function',
31
+ function_definition: 'function',
32
+ function_item: 'function',
33
+ function_signature: 'function',
34
+ class_declaration: 'class',
35
+ abstract_class_declaration: 'class',
36
+ class_definition: 'class',
37
+ class: 'class',
38
+ struct_item: 'class',
39
+ interface_declaration: 'type',
40
+ type_alias_declaration: 'type',
41
+ enum_declaration: 'type',
42
+ type_spec: 'type',
43
+ type_item: 'type',
44
+ enum_item: 'type',
45
+ trait_item: 'type',
46
+ interface: 'type',
47
+ method_definition: 'method',
48
+ method_declaration: 'method',
49
+ method_signature: 'method',
50
+ abstract_method_signature: 'method',
51
+ constructor_declaration: 'method',
52
+ method: 'method',
53
+ singleton_method: 'method',
54
+ public_field_definition: 'field',
55
+ property_signature: 'field',
56
+ const_item: 'variable',
57
+ static_item: 'variable',
58
+ internal_module: 'module',
59
+ module: 'module',
60
+ mod_item: 'module',
61
+ }
62
+
63
+ function declarationKind(node: SyntaxNode): string | undefined {
64
+ if (node.type === 'function_item' && node.parent?.parent?.type === 'impl_item')
65
+ return 'method'
66
+ if (node.type === 'function_definition') {
67
+ let parent = node.parent
68
+ if (parent?.type === 'decorated_definition') parent = parent.parent
69
+ if (parent?.type === 'block' && parent.parent?.type === 'class_definition')
70
+ return 'method'
71
+ }
72
+ if (node.type === 'variable_declarator') {
73
+ const value = node.childForFieldName('value')
74
+ return value &&
75
+ /^(arrow_function|function_expression|generator_function)$/.test(
76
+ value.type,
77
+ )
78
+ ? 'function'
79
+ : 'variable'
80
+ }
81
+ return kinds[node.type]
82
+ }
83
+
84
+ function declarationName(node: SyntaxNode): string | undefined {
85
+ const name = node.childForFieldName('name')
86
+ // Destructured/dynamic names cannot serve as an unambiguous identity.
87
+ if (
88
+ !name ||
89
+ /pattern|computed|subscript|member_expression/.test(name.type)
90
+ )
91
+ return undefined
92
+ return name.text.trim() || undefined
93
+ }
94
+
95
+ function receiverName(node: SyntaxNode): string | undefined {
96
+ const receiver = node.childForFieldName('receiver')
97
+ const findType = (part: SyntaxNode): string | undefined => {
98
+ if (part.type === 'type_identifier') return part.text
99
+ for (const child of part.namedChildren) {
100
+ if (!child) continue
101
+ const name = findType(child)
102
+ if (name) return name
103
+ }
104
+ return undefined
105
+ }
106
+ return receiver ? findType(receiver) : undefined
107
+ }
108
+
109
+ /** Cache parsed, hashed metadata, not WASM trees or source text. Bounded LRU. */
110
+ export interface ParsedDeclarations {
111
+ declarations: ParsedDeclaration[]
112
+ hasError: boolean
113
+ }
114
+
115
+ const declarationCache = new Map<string, ParsedDeclarations | null>()
116
+ const MAX_CACHED_FILES = 512
117
+
118
+ export async function parseDeclarations(
119
+ file: string,
120
+ content: string,
121
+ ): Promise<ParsedDeclarations | null> {
122
+ const key = `${file.slice(file.lastIndexOf('.')).toLowerCase()}\0${createHash('sha256').update(content).digest('hex')}`
123
+ if (declarationCache.has(key)) {
124
+ const cached = declarationCache.get(key)!
125
+ declarationCache.delete(key)
126
+ declarationCache.set(key, cached)
127
+ return cached
128
+ }
129
+ const parser = await sharedParserFor(file)
130
+ if (!parser) return null
131
+ const tree = await parseWith(parser, content)
132
+ try {
133
+ const declarations: ParsedDeclaration[] = []
134
+ const lines = content.split(/\r?\n/).map(normalizeDeclarationLine)
135
+ const visit = (node: SyntaxNode, scopes: string[]) => {
136
+ const construct = declarationKind(node)
137
+ const name = construct ? declarationName(node) : undefined
138
+ let innerScopes = scopes
139
+ if (node.type === 'impl_item') {
140
+ const type = node.childForFieldName('type')?.text
141
+ if (type) innerScopes = [...scopes, type]
142
+ }
143
+ if (construct && name) {
144
+ let start = node
145
+ // A declarator needs its const/let/export wrapper to retain its
146
+ // signature and any modifiers, not just the initializer.
147
+ if (
148
+ node.type === 'variable_declarator' &&
149
+ node.parent?.namedChildren.filter(
150
+ (c) => c?.type === 'variable_declarator',
151
+ ).length === 1
152
+ ) {
153
+ start = node.parent
154
+ }
155
+ while (
156
+ start.parent &&
157
+ /^(export_statement|decorated_definition)$/.test(start.parent.type)
158
+ )
159
+ start = start.parent
160
+ const receiver =
161
+ node.type === 'method_declaration' ? receiverName(node) : undefined
162
+ const qualifiedScopes = receiver ? [...scopes, receiver] : scopes
163
+ const symbol = [...qualifiedScopes, name].join('.')
164
+ const startLine = start.startPosition.row + 1
165
+ const endLine = start.endPosition.row + 1
166
+ declarations.push({
167
+ name,
168
+ symbol,
169
+ construct,
170
+ startLine,
171
+ endLine,
172
+ anchorEnd: node.startPosition.row + 1,
173
+ hasError: start.hasError,
174
+ contentHash: createHash('sha256')
175
+ .update(lines.slice(startLine - 1, endLine).join('\n'))
176
+ .digest('hex')
177
+ .slice(0, 32),
178
+ })
179
+ if (
180
+ ['class', 'function', 'method', 'module', 'type'].includes(construct)
181
+ )
182
+ innerScopes = [...qualifiedScopes, name]
183
+ }
184
+ for (const child of node.namedChildren) if (child) visit(child, innerScopes)
185
+ }
186
+ visit(tree.rootNode, [])
187
+ const parsed = { declarations, hasError: tree.rootNode.hasError }
188
+ declarationCache.set(key, parsed)
189
+ if (declarationCache.size > MAX_CACHED_FILES)
190
+ declarationCache.delete(declarationCache.keys().next().value!)
191
+ return parsed
192
+ } finally {
193
+ tree.delete()
194
+ }
195
+ }
196
+
197
+ /** A resolved source declaration with its full range, for step site/target refs. */
198
+ export interface ResolvedConstructDeclaration {
199
+ symbol: string
200
+ construct: string
201
+ startLine: number
202
+ endLine: number
203
+ contentHash: string
204
+ }
205
+
206
+ function toResolvedDeclaration(
207
+ declaration: ParsedDeclaration,
208
+ ): ResolvedConstructDeclaration {
209
+ return {
210
+ symbol: declaration.symbol,
211
+ construct: declaration.construct,
212
+ startLine: declaration.startLine,
213
+ endLine: declaration.endLine,
214
+ contentHash: declaration.contentHash,
215
+ }
216
+ }
217
+
218
+ /** Read a repo-relative source file, rejecting paths outside the checkout. */
219
+ export async function safeSource(
220
+ root: string,
221
+ file: string,
222
+ ): Promise<string> {
223
+ if (isAbsolute(file) || file.split('/').includes('..'))
224
+ throw new Error('Unsafe source path.')
225
+ const path = await fs.realpath(resolve(root, file))
226
+ const rel = relative(root, path)
227
+ if (rel === '..' || rel.startsWith(`..${sep}`) || isAbsolute(rel))
228
+ throw new Error('Source path escapes checkout.')
229
+ const stat = await fs.stat(path)
230
+ if (!stat.isFile() || stat.size > 5_000_000)
231
+ throw new Error('Source is not a readable file below 5 MB.')
232
+ return fs.readFile(path, 'utf8')
233
+ }
234
+
235
+ /**
236
+ * Resolve the innermost declaration containing `line` in `file`.
237
+ *
238
+ * Trail step sites are hand-authored call-site lines, while the frame the UI
239
+ * wants is the enclosing construct (a method inside a class, a helper inside a
240
+ * module). Picking the smallest containing range gives that frame; the full
241
+ * `startLine..endLine` is what the code view should show.
242
+ */
243
+ export async function enclosingDeclaration(input: {
244
+ repoRoot: string
245
+ file: string
246
+ line: number
247
+ }): Promise<ResolvedConstructDeclaration | null> {
248
+ const root = await fs.realpath(input.repoRoot)
249
+ const content = await safeSource(root, input.file)
250
+ const declarations =
251
+ (await parseDeclarations(input.file, content))?.declarations ?? []
252
+ const containing = declarations.filter(
253
+ (d) => d.startLine <= input.line && input.line <= d.endLine,
254
+ )
255
+ containing.sort(
256
+ (a, b) =>
257
+ a.endLine - a.startLine - (b.endLine - b.startLine) ||
258
+ b.symbol.length - a.symbol.length ||
259
+ a.symbol.localeCompare(b.symbol),
260
+ )
261
+ const first = containing[0]
262
+ return first ? toResolvedDeclaration(first) : null
263
+ }
264
+
265
+ /**
266
+ * Resolve a declaration by qualified symbol in `file`. Exact qualified match
267
+ * first (`Class.method`), then a unique simple-name match — never a guess when
268
+ * the simple name is ambiguous.
269
+ */
270
+ export async function declarationForSymbol(input: {
271
+ repoRoot: string
272
+ file: string
273
+ symbol: string
274
+ }): Promise<ResolvedConstructDeclaration | null> {
275
+ const root = await fs.realpath(input.repoRoot)
276
+ const content = await safeSource(root, input.file)
277
+ const declarations =
278
+ (await parseDeclarations(input.file, content))?.declarations ?? []
279
+ const exact = declarations.find((d) => d.symbol === input.symbol)
280
+ if (exact) return toResolvedDeclaration(exact)
281
+ const simple = input.symbol.split('.').pop()
282
+ const matches = declarations.filter((d) => d.name === simple)
283
+ return matches.length === 1 ? toResolvedDeclaration(matches[0]!) : null
284
+ }
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Tree-sitter grammar support shared by every audit host.
3
+ *
4
+ * The audit verifies a declaration by parsing source, so both Studio and the
5
+ * CLI must agree on which extensions are parseable and which WASM grammar
6
+ * handles them.
7
+ */
8
+
9
+ /** Extension → bundled tree-sitter WASM grammar. */
10
+ export const CONSTRUCT_GRAMMARS: Readonly<Record<string, string>> = {
11
+ '.ts': 'tree-sitter-typescript.wasm',
12
+ '.tsx': 'tree-sitter-tsx.wasm',
13
+ '.js': 'tree-sitter-javascript.wasm',
14
+ '.jsx': 'tree-sitter-javascript.wasm',
15
+ '.mjs': 'tree-sitter-javascript.wasm',
16
+ '.cjs': 'tree-sitter-javascript.wasm',
17
+ '.py': 'tree-sitter-python.wasm',
18
+ '.go': 'tree-sitter-go.wasm',
19
+ '.rs': 'tree-sitter-rust.wasm',
20
+ '.java': 'tree-sitter-java.wasm',
21
+ '.rb': 'tree-sitter-ruby.wasm',
22
+ '.php': 'tree-sitter-php.wasm',
23
+ }
24
+
25
+ function extension(file: string): string {
26
+ const name = file.slice(file.lastIndexOf('/') + 1)
27
+ const dot = name.lastIndexOf('.')
28
+ return dot < 0 ? '' : name.slice(dot).toLowerCase()
29
+ }
30
+
31
+ export function grammarFile(file: string): string | null {
32
+ return CONSTRUCT_GRAMMARS[extension(file)] ?? null
33
+ }
34
+
35
+ // Only known non-code formats are exempt. Unknown extensions remain unsupported.
36
+ const NON_CODE_EXTENSIONS = new Set([
37
+ '.md', '.mdx', '.txt', '.rst', '.adoc',
38
+ '.json', '.jsonc', '.yaml', '.yml', '.toml', '.xml', '.ini', '.cfg',
39
+ '.lock', '.csv', '.tsv',
40
+ '.png', '.jpg', '.jpeg', '.gif', '.webp', '.svg', '.ico', '.bmp',
41
+ '.ttf', '.otf', '.woff', '.woff2', '.eot',
42
+ '.mp3', '.wav', '.ogg', '.mp4', '.webm', '.pdf',
43
+ ])
44
+ const NON_CODE_NAMES = new Set([
45
+ 'readme', 'license', 'licence', 'copying', 'notice', 'authors', 'changelog',
46
+ '.gitignore', '.gitattributes', '.gitmodules', '.editorconfig',
47
+ ])
48
+
49
+ export function constructFileSupport(
50
+ file: string,
51
+ ): 'supported' | 'unsupported' | 'non-code' {
52
+ if (grammarFile(file)) return 'supported'
53
+ const name = file.slice(file.lastIndexOf('/') + 1).toLowerCase()
54
+ return NON_CODE_EXTENSIONS.has(extension(file)) || NON_CODE_NAMES.has(name)
55
+ ? 'non-code'
56
+ : 'unsupported'
57
+ }
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Node verification layer (tree-sitter + declarations + component verify).
3
+ *
4
+ * Imported through `@principal-ai/subsystems-core/audit`; never from the
5
+ * browser-safe package entry.
6
+ */
7
+
8
+ export {
9
+ CONSTRUCT_GRAMMARS,
10
+ constructFileSupport,
11
+ grammarFile,
12
+ } from './grammar'
13
+ export { parserFor, sharedParserFor, parseWith } from './parser'
14
+ export {
15
+ declarationForSymbol,
16
+ enclosingDeclaration,
17
+ parseDeclarations,
18
+ safeSource,
19
+ type ParsedDeclaration,
20
+ type ParsedDeclarations,
21
+ type ResolvedConstructDeclaration,
22
+ } from './declarations'
23
+ export {
24
+ GATE_LABELS,
25
+ deriveSpan,
26
+ disposeSpanTreeCache,
27
+ languageKey,
28
+ type DeriveInput,
29
+ type SpanClass,
30
+ type SpanDerivation,
31
+ type SpanTreeCache,
32
+ } from './span'
33
+ export {
34
+ verifySubsystemComponent,
35
+ verifyVerdict,
36
+ type VerifyComponentAugmentation,
37
+ type VerifyComponentDeps,
38
+ type VerifyComponentOptions,
39
+ type VerifyComponentSignatureClaim,
40
+ type VerifyComponentSpanClaim,
41
+ } from './component'
@@ -0,0 +1,124 @@
1
+ /**
2
+ * Tree-sitter parser runtime shared by every audit host.
3
+ *
4
+ * WASM assets can be bundled next to the host entry (Studio copies them to
5
+ * `bun/tree-sitter`) or resolved from installed dependencies (the CLI). This
6
+ * module checks the bundled location first, then falls back to package
7
+ * resolution, so one parser implementation serves both.
8
+ */
9
+
10
+ import { existsSync } from 'node:fs'
11
+ import { createRequire } from 'node:module'
12
+ import { join } from 'node:path'
13
+ import { Parser, Language, type Tree } from 'web-tree-sitter'
14
+ import { grammarFile } from './grammar'
15
+
16
+ const nodeRequire = createRequire(__filename)
17
+
18
+ function wasmPath(wasm: string): string {
19
+ const configured = process.env['PRINCIPAL_TREE_SITTER_DIR']?.trim()
20
+ if (configured) {
21
+ const candidate = join(configured, wasm)
22
+ if (existsSync(candidate)) return candidate
23
+ }
24
+ // Bundled imports share the host entry's directory. The package resolver is
25
+ // only a fallback for unbundled source/scripts in a checkout.
26
+ const bundled = join(__dirname, 'tree-sitter', wasm)
27
+ if (existsSync(bundled)) return bundled
28
+ try {
29
+ return nodeRequire.resolve(
30
+ wasm === 'tree-sitter.wasm'
31
+ ? `web-tree-sitter/${wasm}`
32
+ : `tree-sitter-wasms/out/${wasm}`,
33
+ )
34
+ } catch {
35
+ throw new Error(
36
+ `Missing Tree-sitter WASM asset: ${wasm}. Install web-tree-sitter and tree-sitter-wasms, or bundle the parser assets.`,
37
+ )
38
+ }
39
+ }
40
+
41
+ let parserInit: Promise<void> | null = null
42
+ const grammars = new Map<string, Promise<Language>>()
43
+
44
+ async function loadLanguage(wasm: string): Promise<Language> {
45
+ let pending = grammars.get(wasm)
46
+ if (pending) return pending
47
+ pending = (async () => {
48
+ if (!parserInit) {
49
+ const runtimePath = wasmPath('tree-sitter.wasm')
50
+ // Emscripten's default relative lookup points at the JS bundle, not the
51
+ // installed dependency, after a host bundles its entry point.
52
+ parserInit = Parser.init({ locateFile: () => runtimePath })
53
+ }
54
+ await parserInit
55
+ return Language.load(wasmPath(wasm))
56
+ })()
57
+ grammars.set(wasm, pending)
58
+ return pending
59
+ }
60
+
61
+ export async function parserFor(file: string): Promise<Parser | null> {
62
+ const wasm = grammarFile(file)
63
+ if (!wasm) return null
64
+ const language = await loadLanguage(wasm)
65
+ const parser = new Parser()
66
+ parser.setLanguage(language)
67
+ return parser
68
+ }
69
+
70
+ /** Drop the cached runtime so the next parse re-initializes from scratch. */
71
+ function resetParserRuntime(): void {
72
+ parserInit = null
73
+ grammars.clear()
74
+ parsers.clear()
75
+ }
76
+
77
+ /**
78
+ * One long-lived Parser per grammar, reused. Creating a Parser per file churns
79
+ * the WASM heap and aborts under a large run; a shared parser is safe because
80
+ * `parseWith` serializes every call.
81
+ */
82
+ const parsers = new Map<string, Promise<Parser>>()
83
+ export async function sharedParserFor(file: string): Promise<Parser | null> {
84
+ const wasm = grammarFile(file)
85
+ if (!wasm) return null
86
+ let pending = parsers.get(wasm)
87
+ if (!pending) {
88
+ pending = (async () => {
89
+ const language = await loadLanguage(wasm)
90
+ const parser = new Parser()
91
+ parser.setLanguage(language)
92
+ return parser
93
+ })()
94
+ parsers.set(wasm, pending)
95
+ }
96
+ return pending
97
+ }
98
+
99
+ let parseQueue: Promise<unknown> = Promise.resolve()
100
+
101
+ /**
102
+ * Parse one file, serialized. web-tree-sitter's WASM runtime aborts if a parser
103
+ * is used concurrently, and an abort poisons the cached runtime — so calls are
104
+ * chained, and a throw drops the runtime so the next file re-initializes rather
105
+ * than failing forever.
106
+ */
107
+ export function parseWith(parser: Parser, content: string): Promise<Tree> {
108
+ const task = async (): Promise<Tree> => {
109
+ try {
110
+ const tree = parser.parse(content)
111
+ if (!tree) throw new Error('Tree-sitter returned no syntax tree.')
112
+ return tree
113
+ } catch (error) {
114
+ resetParserRuntime()
115
+ throw error
116
+ }
117
+ }
118
+ const result = parseQueue.then(task, task)
119
+ parseQueue = result.then(
120
+ () => undefined,
121
+ () => undefined,
122
+ )
123
+ return result
124
+ }