dsh-vigil 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +188 -0
  3. package/client.js +4652 -0
  4. package/cordis.patch.yml +7 -0
  5. package/docs/DETAIL.md +66 -0
  6. package/icon.png +0 -0
  7. package/illustrations/notice.png +0 -0
  8. package/illustrations/warning.png +0 -0
  9. package/locale/en.json +7 -0
  10. package/locale/zh.json +7 -0
  11. package/package.json +75 -0
  12. package/rules/audit.yaml +130 -0
  13. package/rules/manifest.json +7 -0
  14. package/rules/sentinel.yaml +289 -0
  15. package/src/alert-route.js +194 -0
  16. package/src/approval.js +398 -0
  17. package/src/artwork-route.js +87 -0
  18. package/src/audit/ast.js +213 -0
  19. package/src/audit/install-scan.js +127 -0
  20. package/src/audit/lexer.js +307 -0
  21. package/src/audit/narrative.js +320 -0
  22. package/src/audit/rules.js +1440 -0
  23. package/src/audit/scan.js +880 -0
  24. package/src/audit-clear-route.js +89 -0
  25. package/src/audit-feed.js +265 -0
  26. package/src/audit-log.js +887 -0
  27. package/src/config-schema.js +194 -0
  28. package/src/config.js +580 -0
  29. package/src/delete/command-kinds.js +46 -0
  30. package/src/delete/lex.js +46 -0
  31. package/src/delete/parser-posix.js +1427 -0
  32. package/src/delete/parser-pwsh.js +1729 -0
  33. package/src/delete/parser.js +2082 -0
  34. package/src/delete/policy.js +680 -0
  35. package/src/delete/quarantine.js +417 -0
  36. package/src/index.js +1134 -0
  37. package/src/install-scan-route.js +58 -0
  38. package/src/install-watch.js +389 -0
  39. package/src/integrity.js +509 -0
  40. package/src/live-config.js +88 -0
  41. package/src/quarantine-route.js +74 -0
  42. package/src/quarantine-view.js +44 -0
  43. package/src/rules/pack.js +423 -0
  44. package/src/rules/update.js +341 -0
  45. package/src/rules/yaml.js +186 -0
  46. package/src/sage-action-route.js +63 -0
  47. package/src/sage-provision.js +716 -0
  48. package/src/sentinel/guard.js +392 -0
  49. package/src/sentinel/hook.js +546 -0
  50. package/src/sentinel/rules.js +488 -0
  51. package/src/sentinel/sage-load.js +79 -0
  52. package/src/sentinel/sage.js +550 -0
  53. package/src/tools.js +727 -0
  54. package/src/update-check.js +339 -0
  55. package/src/util.js +400 -0
  56. package/threats/README.md +25 -0
@@ -0,0 +1,213 @@
1
+ /**
2
+ * AST-assisted alias analysis (best effort, acorn).
3
+ *
4
+ * The regex rules can see "this line imports child_process" and "this line
5
+ * calls spawn(". They cannot follow a local alias:
6
+ *
7
+ * const cp = require('node:child_process')
8
+ * const run = cp.exec
9
+ * run(userInput) // ← invisible to line-based rules
10
+ *
11
+ * This module parses the file once and returns the locally bound names of
12
+ * capability-bearing APIs (child_process, eval, fetch) plus their call sites.
13
+ * It never evaluates code, never resolves network resources, and any parse
14
+ * failure returns `{ ok: false }` so the caller keeps the regex-only result.
15
+ *
16
+ * @module audit/ast
17
+ */
18
+
19
+ import { createRequire } from 'node:module'
20
+
21
+ // Loaded synchronously so the scanner stays synchronous; a missing acorn must
22
+ // degrade to regex-only instead of breaking the whole plugin activation.
23
+ let acorn = null
24
+ try {
25
+ acorn = createRequire(import.meta.url)('acorn')
26
+ } catch {
27
+ acorn = null
28
+ }
29
+
30
+ const PARSE_OPTIONS = {
31
+ ecmaVersion: 'latest',
32
+ sourceType: 'module',
33
+ allowHashBang: true,
34
+ allowAwaitOutsideFunction: true,
35
+ // Line numbers are required for findings; without this every call is line 0.
36
+ locations: true,
37
+ }
38
+
39
+ const CHILD_PROCESS_MODULE = /^(?:node:)?child_process$/
40
+
41
+ /**
42
+ * @typedef {{ name: string, kind: 'child_process'|'eval'|'fetch', line: number }} AliasedCall
43
+ * @typedef {{ ok: boolean, aliases: Record<string, string>, calls: AliasedCall[], error?: string }} AstAnalysis
44
+ */
45
+
46
+ /**
47
+ * @param {string} text
48
+ * @returns {AstAnalysis}
49
+ */
50
+ export function analyzeAliases(text) {
51
+ if (!acorn || typeof acorn.parse !== 'function') {
52
+ return { ok: false, aliases: {}, calls: [], error: 'acorn 不可用(仅使用正则规则)' }
53
+ }
54
+ let ast
55
+ try {
56
+ ast = acorn.parse(String(text ?? ''), PARSE_OPTIONS)
57
+ } catch (moduleError) {
58
+ try {
59
+ // Plain scripts (`with`, top-level return) are not modules.
60
+ ast = acorn.parse(String(text ?? ''), { ...PARSE_OPTIONS, sourceType: 'script' })
61
+ } catch {
62
+ return { ok: false, aliases: {}, calls: [], error: moduleError instanceof Error ? moduleError.message : String(moduleError) }
63
+ }
64
+ }
65
+
66
+ /** @type {Map<string, string>} local name -> capability kind */
67
+ const aliases = new Map()
68
+
69
+ // ---- pass 1: collect declarations, then bind them in source order -------
70
+ // The generic walk visits children in reverse push order, so binding has to
71
+ // happen sorted by position: `const run = cp.exec` must see `cp` already.
72
+ /** @type {Array<{ start: number, name?: string, kind?: string, pattern?: any, init?: any }>} */
73
+ const declarations = []
74
+ walkAst(ast, node => {
75
+ if (node.type === 'ImportDeclaration' && typeof node.source?.value === 'string') {
76
+ const source = node.source.value
77
+ const kind = CHILD_PROCESS_MODULE.test(source) ? 'child_process' : null
78
+ if (!kind) return
79
+ for (const specifier of node.specifiers ?? []) {
80
+ const local = specifier.local?.name
81
+ if (local) declarations.push({ start: specifier.start ?? node.start ?? 0, name: local, kind })
82
+ }
83
+ return
84
+ }
85
+ if (node.type === 'VariableDeclarator' && node.id && node.init) {
86
+ declarations.push({ start: node.start ?? 0, pattern: node.id, init: node.init })
87
+ }
88
+ })
89
+ declarations.sort((left, right) => left.start - right.start)
90
+ for (const declaration of declarations) {
91
+ if (declaration.name) {
92
+ aliases.set(declaration.name, declaration.kind)
93
+ continue
94
+ }
95
+ const kind = capabilityOf(declaration.init, aliases)
96
+ if (kind) bindPattern(declaration.pattern, kind, aliases)
97
+ }
98
+
99
+ // ---- pass 2: call sites, resolved in source order -----------------------
100
+ /** @type {Array<any>} */
101
+ const callNodes = []
102
+ walkAst(ast, node => {
103
+ if (node.type === 'CallExpression' && node.callee) callNodes.push(node)
104
+ })
105
+ callNodes.sort((left, right) => (left.start ?? 0) - (right.start ?? 0))
106
+ /** @type {AliasedCall[]} */
107
+ const calls = []
108
+ for (const node of callNodes) {
109
+ const callee = node.callee
110
+ const line = node.loc?.start?.line ?? 0
111
+ if (line <= 1) continue
112
+ if (callee.type === 'Identifier' && aliases.has(callee.name)) {
113
+ calls.push({ name: callee.name, kind: aliases.get(callee.name), line })
114
+ continue
115
+ }
116
+ // `cp.exec(...)`: the object is an aliased child_process namespace.
117
+ if (callee.type === 'MemberExpression' && callee.object?.type === 'Identifier') {
118
+ const kind = aliases.get(callee.object.name)
119
+ if (kind === 'child_process' && !callee.computed && callee.property?.name) {
120
+ calls.push({ name: `child_process.${callee.property.name}`, kind, line })
121
+ }
122
+ }
123
+ }
124
+
125
+ /** @type {Record<string,string>} */
126
+ const aliasRecord = {}
127
+ for (const [name, kind] of aliases) aliasRecord[name] = kind
128
+ return { ok: true, aliases: aliasRecord, calls }
129
+ }
130
+
131
+ /**
132
+ * What capability does this expression evaluate to, given known aliases?
133
+ * @param {any} node
134
+ * @param {Map<string,string>} aliases
135
+ * @returns {string|null}
136
+ */
137
+ function capabilityOf(node, aliases) {
138
+ if (!node || typeof node !== 'object') return null
139
+ if (node.type === 'Identifier') {
140
+ if (node.name === 'eval') return 'eval'
141
+ if (node.name === 'fetch') return 'fetch'
142
+ return aliases.get(node.name) ?? null
143
+ }
144
+ if (node.type === 'MemberExpression' && !node.computed) {
145
+ const property = node.property?.name
146
+ const object = node.object
147
+ if (object?.type === 'Identifier' && aliases.get(object.name) === 'child_process') return 'child_process'
148
+ if (object?.type === 'Identifier' && object.name === 'globalThis' && (property === 'eval' || property === 'fetch')) {
149
+ return property
150
+ }
151
+ if (object?.type === 'Identifier' && object.name === 'window' && property === 'fetch') return 'fetch'
152
+ // `cp.exec` where cp is a child_process alias is handled by the base case.
153
+ }
154
+ if (node.type === 'CallExpression') {
155
+ // require('child_process') / require('node:child_process')
156
+ const callee = node.callee
157
+ const argument = node.arguments?.[0]
158
+ if (callee?.type === 'Identifier' && callee.name === 'require'
159
+ && argument?.type === 'Literal' && typeof argument.value === 'string'
160
+ && CHILD_PROCESS_MODULE.test(argument.value)) {
161
+ return 'child_process'
162
+ }
163
+ }
164
+ if (node.type === 'AwaitExpression') return capabilityOf(node.argument, aliases)
165
+ return null
166
+ }
167
+
168
+ /**
169
+ * Bind a declaration pattern (Identifier / ObjectPattern) to a capability.
170
+ * @param {any} pattern
171
+ * @param {string} kind
172
+ * @param {Map<string,string>} aliases
173
+ */
174
+ function bindPattern(pattern, kind, aliases) {
175
+ if (!pattern || typeof pattern !== 'object') return
176
+ if (pattern.type === 'Identifier' && typeof pattern.name === 'string') {
177
+ aliases.set(pattern.name, kind)
178
+ return
179
+ }
180
+ if (pattern.type === 'ObjectPattern') {
181
+ for (const property of pattern.properties ?? []) {
182
+ if (property?.type !== 'Property') continue
183
+ const local = property.value?.type === 'Identifier' ? property.value.name : null
184
+ if (local) aliases.set(local, kind)
185
+ }
186
+ }
187
+ }
188
+
189
+ /**
190
+ * Minimal generic AST walker: visits every node object reachable from `root`
191
+ * (skips loc/range/comments to stay cheap).
192
+ * @param {any} root
193
+ * @param {(node: any) => void} visit
194
+ */
195
+ function walkAst(root, visit) {
196
+ /** @type {any[]} */
197
+ const stack = [root]
198
+ const seen = new Set()
199
+ while (stack.length > 0) {
200
+ const node = stack.pop()
201
+ if (!node || typeof node !== 'object' || seen.has(node)) continue
202
+ seen.add(node)
203
+ if (typeof node.type === 'string') visit(node)
204
+ for (const [key, value] of Object.entries(node)) {
205
+ if (key === 'loc' || key === 'range' || key === 'start' || key === 'end' || key === 'parent') continue
206
+ if (Array.isArray(value)) {
207
+ for (const item of value) if (item && typeof item === 'object') stack.push(item)
208
+ } else if (value && typeof value === 'object') {
209
+ stack.push(value)
210
+ }
211
+ }
212
+ }
213
+ }
@@ -0,0 +1,127 @@
1
+ /**
2
+ * Static audit helper shared by the `plugin_manager` tool pre-check and the
3
+ * install watcher: turn one `scanPluginDirectory()` report into a compact,
4
+ * JSON-safe summary for audit records, feeds and notices.
5
+ *
6
+ * @module dsh-vigil/audit/install-scan
7
+ */
8
+
9
+ import { existsSync, statSync } from 'node:fs'
10
+ import { homedir } from 'node:os'
11
+ import { isAbsolute, join, resolve } from 'node:path'
12
+ import { truncate } from '../util.js'
13
+ import { RULE_BY_ID } from './rules.js'
14
+
15
+ /**
16
+ * Resolve a tool argument that names a local plugin directory to install.
17
+ * Registry/git/tarball specs return null: they cannot be scanned before the
18
+ * package manager downloads them (the install watcher audits the installed copy).
19
+ * @param {Record<string, unknown>} args
20
+ * @param {{ cwd?: string }} [options]
21
+ * @returns {{ spec: string, dir: string } | null}
22
+ */
23
+ export function resolveLocalInstallTarget(args, options = {}) {
24
+ const cwd = options.cwd ?? process.cwd()
25
+ const spec = ['spec', 'target', 'path', 'source', 'bundle', 'name']
26
+ .map(key => args?.[key])
27
+ .find(value => typeof value === 'string' && value.trim() !== '')
28
+ if (!spec) return null
29
+ const looksLocal = spec.startsWith('.') || spec.startsWith('~') || spec.startsWith('/') || /^[A-Za-z]:[\\/]/.test(spec) || spec.startsWith('\\\\') || spec.includes('\\') || spec.includes('/')
30
+ if (!looksLocal) return null
31
+ const absolute = spec.startsWith('~')
32
+ ? resolve(homedir(), spec.replace(/^~[\\/]?/, ''))
33
+ : isAbsolute(spec)
34
+ ? spec
35
+ : resolve(cwd, spec)
36
+ try {
37
+ if (!statSync(absolute).isDirectory()) return null
38
+ } catch {
39
+ return null
40
+ }
41
+ const candidates = [absolute, join(absolute, 'package')]
42
+ for (const candidate of candidates) {
43
+ if (existsSync(join(candidate, 'package.json'))) return { spec, dir: candidate }
44
+ }
45
+ return null
46
+ }
47
+
48
+ /**
49
+ * @param {any} report report from `scanPluginDirectory()`
50
+ * @param {{ target?: string, dir?: string }} [meta]
51
+ * @returns {{ target: string, dir: string, blockers: number, review: number, notice: number, ruleIds: string[], top: Array<object>, text: string }}
52
+ */
53
+ export function summarizeInstallScan(report, meta = {}) {
54
+ const findings = Array.isArray(report?.findings) ? report.findings : []
55
+ const summary = report?.summary && typeof report.summary === 'object' ? report.summary : {}
56
+ const blockers = Number(summary.blocker) || 0
57
+ const review = Number(summary.review) || 0
58
+ const notice = Number(summary.notice) || 0
59
+ const ruleIds = [...new Set(findings.map(finding => (typeof finding?.ruleId === 'string' ? finding.ruleId : null)).filter(Boolean))]
60
+ // Keep a bounded sample for the audit panel but cover every severity, so a
61
+ // package with many blockers does not hide its review/notice findings.
62
+ const PER_SEVERITY_LIMIT = 50
63
+ const sampled = []
64
+ for (const severity of ['blocker', 'review', 'notice', 'info']) {
65
+ sampled.push(...findings.filter(finding => (finding?.severity ?? 'unknown') === severity).slice(0, PER_SEVERITY_LIMIT))
66
+ }
67
+ sampled.push(...findings.filter(finding => !['blocker', 'review', 'notice', 'info'].includes(finding?.severity)).slice(0, PER_SEVERITY_LIMIT))
68
+ const top = sampled.map(finding => {
69
+ const ruleId = typeof finding?.ruleId === 'string' ? finding.ruleId : null
70
+ return {
71
+ ruleId,
72
+ title: ruleId ? (RULE_BY_ID.get(ruleId)?.title ?? null) : null,
73
+ severity: typeof finding?.severity === 'string' ? finding.severity : null,
74
+ file: typeof finding?.file === 'string' ? finding.file : null,
75
+ line: Number.isFinite(finding?.line) ? finding.line : null,
76
+ evidence: truncate(String(finding?.evidence ?? ''), 160),
77
+ means: truncate(String(finding?.means ?? ''), 300),
78
+ mitigation: truncate(String(finding?.mitigation ?? ''), 300),
79
+ }
80
+ })
81
+ const reasons = top
82
+ .filter(item => item.severity === 'blocker' || item.severity === 'review')
83
+ .map(item => {
84
+ const where = item.file ? `(${item.file}${item.line ? `:${item.line}` : ''})` : ''
85
+ return `${item.title ?? item.ruleId ?? '未知规则'}${where}`
86
+ })
87
+ // The install prompt says "N 个高危命中"; only blockers may be listed there.
88
+ const blockerReasons = top
89
+ .filter(item => item.severity === 'blocker')
90
+ .map(item => {
91
+ const where = item.file ? `(${item.file}${item.line ? `:${item.line}` : ''})` : ''
92
+ return `${item.title ?? item.ruleId ?? '未知规则'}${where}`
93
+ })
94
+ // Coverage is part of the verdict: "0 blockers" only means something when the
95
+ // scan actually read the files. A padded package must not be able to turn a
96
+ // skipped file into a clean result.
97
+ const filesSkipped = Number(report?.limits?.filesSkipped) || 0
98
+ const bytesSkipped = Number(report?.limits?.bytesSkipped) || 0
99
+ const scanTruncated = report?.limits?.truncated === true
100
+ const unauditedEntry = report?.limits?.unauditedEntry === true
101
+ const nonTextFiles = Number(report?.limits?.nonTextFiles) || 0
102
+ const incomplete = scanTruncated || filesSkipped > 0 || bytesSkipped > 0 || unauditedEntry
103
+ const coverageNote = incomplete
104
+ ? `扫描未覆盖全部内容(跳过 ${filesSkipped} 个文件 / ${bytesSkipped} 字节${scanTruncated ? ',结果被截断' : ''}${unauditedEntry ? ';入口位于未扫描的构建目录' : ''})`
105
+ : null
106
+ return {
107
+ target: String(meta.target ?? ''),
108
+ dir: String(meta.dir ?? ''),
109
+ blockers,
110
+ review,
111
+ notice,
112
+ ruleIds,
113
+ top,
114
+ total: findings.length,
115
+ truncated: sampled.length < findings.length,
116
+ filesSkipped,
117
+ bytesSkipped,
118
+ scanTruncated,
119
+ unauditedEntry,
120
+ nonTextFiles,
121
+ incomplete,
122
+ coverageNote,
123
+ reasons,
124
+ blockerReasons,
125
+ text: `安装前静态审计:${blockers} 个高危,${review} 个可疑,${notice} 个提示${coverageNote ? `;${coverageNote}` : ''}`,
126
+ }
127
+ }
@@ -0,0 +1,307 @@
1
+ /**
2
+ * @module dsh-vigil/audit/lexer
3
+ *
4
+ * A small, dependency-free, zero-execution lexical masker for JavaScript /
5
+ * TypeScript sources. It never imports, evaluates, or otherwise executes the
6
+ * scanned text. Its only job is to let the rule engine distinguish "code" from
7
+ * "comment" and "string literal" content so regex rules can avoid the most
8
+ * obvious false positives.
9
+ *
10
+ * Two masks are produced in a single pass, both with the exact same length as
11
+ * the source (newlines preserved), so every match offset still maps to the
12
+ * original 1-based line number:
13
+ *
14
+ * - `code`: comments, string/template literal *content* and regex literal
15
+ * content are replaced by spaces. Use it for API-shaped rules such as
16
+ * `eval(`, `fetch(`, `child_process.exec(`.
17
+ * - `literals`: comments and regex literal content are replaced, but string /
18
+ * template literal content is kept. Use it for rules that need values such as
19
+ * credential paths, URLs, env variable names and shell command strings.
20
+ *
21
+ * This is deliberately a heuristic lexer (not a parser): it handles the common
22
+ * cases (line/block comments, single/double quotes, template literals with
23
+ * `${...}` interpolation, simple regex literals) and recovers gracefully on
24
+ * malformed input. It is NOT a security boundary.
25
+ */
26
+
27
+ /** Characters that may legally precede a regex literal (expression position). */
28
+ const REGEX_LEAD_PUNCT = new Set('([{,;:=!&|?+-*%^~<>');
29
+
30
+ /** Keywords after which a slash starts a regex literal rather than division. */
31
+ const REGEX_LEAD_KEYWORDS = /^(?:return|typeof|instanceof|in|of|case|delete|void|throw|new|yield|await|else|do)$/;
32
+
33
+ /** Default sanity cap; scanning itself caps files well below this. */
34
+ const DEFAULT_MAX_CHARS = 2 * 1024 * 1024;
35
+
36
+ /**
37
+ * Split a masked string into lines without a trailing `\r`, so line numbers
38
+ * stay aligned with the source split on `\n` (CRLF files included).
39
+ *
40
+ * @param {string} text
41
+ * @returns {string[]}
42
+ */
43
+ function splitLines(text) {
44
+ return text.split('\n').map((line) => (line.endsWith('\r') ? line.slice(0, -1) : line));
45
+ }
46
+
47
+ /**
48
+ * Compute the start offset of every line in `source`.
49
+ *
50
+ * @param {string} source
51
+ * @returns {number[]} `lineStarts[0] === 0`; index = 1-based line - 1.
52
+ */
53
+ export function lineStartsOf(source) {
54
+ const text = typeof source === 'string' ? source : '';
55
+ const starts = [0];
56
+ for (let i = 0; i < text.length; i += 1) {
57
+ if (text[i] === '\n') starts.push(i + 1);
58
+ }
59
+ return starts;
60
+ }
61
+
62
+ /**
63
+ * Map a UTF-16 offset to a 1-based line number using `lineStarts`.
64
+ *
65
+ * @param {number[]} lineStarts
66
+ * @param {number} index
67
+ * @returns {number}
68
+ */
69
+ export function lineNumberAt(lineStarts, index) {
70
+ if (!Array.isArray(lineStarts) || lineStarts.length === 0) return 1;
71
+ const offset = Number.isFinite(index) ? Math.max(0, Math.floor(index)) : 0;
72
+ let low = 0;
73
+ let high = lineStarts.length - 1;
74
+ while (low < high) {
75
+ const mid = (low + high + 1) >> 1;
76
+ if (lineStarts[mid] <= offset) low = mid;
77
+ else high = mid - 1;
78
+ }
79
+ return low + 1;
80
+ }
81
+
82
+ /**
83
+ * Check whether the last significant code character before `index` allows a
84
+ * regex literal to start there (a heuristic used to avoid treating division as
85
+ * a regex, which could otherwise swallow real code).
86
+ *
87
+ * @param {string[]} chars Masked code characters (comments/strings blanked).
88
+ * @param {number} index
89
+ * @param {string} source Original source, used for keyword look-behind.
90
+ * @returns {boolean}
91
+ */
92
+ function canStartRegex(chars, index, source) {
93
+ let i = index - 1;
94
+ while (i >= 0 && /\s/.test(chars[i])) i -= 1;
95
+ if (i < 0) return true;
96
+ const ch = chars[i];
97
+ if (REGEX_LEAD_PUNCT.has(ch)) return true;
98
+ if (!/[\w$]/.test(ch)) return false;
99
+ let start = i;
100
+ while (start >= 0 && /[\w$]/.test(chars[start])) start -= 1;
101
+ return REGEX_LEAD_KEYWORDS.test(source.slice(start + 1, i + 1));
102
+ }
103
+
104
+ /**
105
+ * Build masked views of a JS/TS source string without executing it.
106
+ *
107
+ * @param {string} source Raw file text.
108
+ * @param {{ maxChars?: number }} [options]
109
+ * @returns {{
110
+ * source: string,
111
+ * code: string,
112
+ * literals: string,
113
+ * lineCount: number,
114
+ * lines: { original: string[], code: string[], literals: string[] },
115
+ * lineAt: (index: number) => number,
116
+ * sourceLine: (line: number) => string,
117
+ * codeLine: (line: number) => string,
118
+ * literalLine: (line: number) => string
119
+ * }}
120
+ */
121
+ export function maskSource(source, options = {}) {
122
+ const text = typeof source === 'string' ? source : '';
123
+ const requested = Number.isFinite(options.maxChars) && options.maxChars > 0
124
+ ? Math.floor(options.maxChars)
125
+ : DEFAULT_MAX_CHARS;
126
+ const end = Math.min(text.length, requested);
127
+
128
+ let maskedCode;
129
+ let maskedLiterals;
130
+ try {
131
+ // Working on arrays of UTF-16 code units keeps index offsets (and therefore
132
+ // line numbers) identical to the source.
133
+ const codeChars = text.split('');
134
+ const literalChars = text.split('');
135
+
136
+ /** Blank one character in the code mask only (never a newline). */
137
+ const blankCode = (i) => {
138
+ if (i >= end || i < 0) return;
139
+ if (text[i] !== '\n' && text[i] !== '\r') codeChars[i] = ' ';
140
+ };
141
+ /** Blank one character in both masks (never a newline). */
142
+ const blankBoth = (i) => {
143
+ if (i >= end || i < 0) return;
144
+ if (text[i] === '\n' || text[i] === '\r') return;
145
+ codeChars[i] = ' ';
146
+ literalChars[i] = ' ';
147
+ };
148
+
149
+ /** 'code' | 'line' | 'block' | 'string' | 'template' | 'regex' */
150
+ let mode = 'code';
151
+ let quote = '';
152
+ /** @type {{ depth: number, inExpr: boolean }[]} */
153
+ const templates = [];
154
+ let inRegexClass = false;
155
+
156
+ for (let i = 0; i < end; i += 1) {
157
+ const ch = text[i];
158
+
159
+ if (mode === 'code') {
160
+ if (ch === '/' && text[i + 1] === '/') {
161
+ blankBoth(i);
162
+ blankBoth(i + 1);
163
+ mode = 'line';
164
+ i += 1;
165
+ continue;
166
+ }
167
+ if (ch === '/' && text[i + 1] === '*') {
168
+ blankBoth(i);
169
+ blankBoth(i + 1);
170
+ mode = 'block';
171
+ i += 1;
172
+ continue;
173
+ }
174
+ if (ch === "'" || ch === '"') {
175
+ mode = 'string';
176
+ quote = ch;
177
+ continue;
178
+ }
179
+ if (ch === '`') {
180
+ templates.push({ depth: 0, inExpr: false });
181
+ mode = 'template';
182
+ continue;
183
+ }
184
+ if (ch === '/' && canStartRegex(codeChars, i, text)) {
185
+ mode = 'regex';
186
+ inRegexClass = false;
187
+ continue;
188
+ }
189
+ const top = templates[templates.length - 1];
190
+ if (top && top.inExpr) {
191
+ if (ch === '{') {
192
+ top.depth += 1;
193
+ continue;
194
+ }
195
+ if (ch === '}') {
196
+ if (top.depth === 0) {
197
+ top.inExpr = false;
198
+ mode = 'template';
199
+ } else {
200
+ top.depth -= 1;
201
+ }
202
+ continue;
203
+ }
204
+ }
205
+ continue;
206
+ }
207
+
208
+ if (mode === 'line') {
209
+ if (ch === '\n') mode = 'code';
210
+ else blankBoth(i);
211
+ continue;
212
+ }
213
+
214
+ if (mode === 'block') {
215
+ if (ch === '*' && text[i + 1] === '/') {
216
+ blankBoth(i);
217
+ blankBoth(i + 1);
218
+ mode = 'code';
219
+ i += 1;
220
+ } else {
221
+ blankBoth(i);
222
+ }
223
+ continue;
224
+ }
225
+
226
+ if (mode === 'string') {
227
+ if (ch === '\\') {
228
+ blankCode(i);
229
+ blankCode(i + 1);
230
+ i += 1;
231
+ } else if (ch === quote) {
232
+ mode = 'code';
233
+ } else if (ch === '\n') {
234
+ // Unterminated string: recover on the next line instead of failing.
235
+ mode = 'code';
236
+ } else {
237
+ blankCode(i);
238
+ }
239
+ continue;
240
+ }
241
+
242
+ if (mode === 'template') {
243
+ if (ch === '\\') {
244
+ blankCode(i);
245
+ blankCode(i + 1);
246
+ i += 1;
247
+ } else if (ch === '`') {
248
+ templates.pop();
249
+ mode = 'code';
250
+ } else if (ch === '$' && text[i + 1] === '{') {
251
+ const top = templates[templates.length - 1];
252
+ if (top) top.inExpr = true;
253
+ // Keep `${` visible in the code mask so structure remains readable.
254
+ i += 1;
255
+ mode = 'code';
256
+ } else {
257
+ blankCode(i);
258
+ }
259
+ continue;
260
+ }
261
+
262
+ // mode === 'regex'
263
+ if (ch === '\\') {
264
+ blankBoth(i);
265
+ blankBoth(i + 1);
266
+ i += 1;
267
+ } else if (ch === '[') {
268
+ inRegexClass = true;
269
+ blankBoth(i);
270
+ } else if (ch === ']') {
271
+ inRegexClass = false;
272
+ blankBoth(i);
273
+ } else if (ch === '/' && !inRegexClass) {
274
+ mode = 'code';
275
+ // Flags after the closing slash stay as ordinary code characters.
276
+ } else {
277
+ blankBoth(i);
278
+ }
279
+ }
280
+
281
+ maskedCode = codeChars.join('');
282
+ maskedLiterals = literalChars.join('');
283
+ } catch {
284
+ // The masker must never throw; fall back to unmasked views (rules will be
285
+ // looser but line numbers stay correct).
286
+ maskedCode = text;
287
+ maskedLiterals = text;
288
+ }
289
+
290
+ const originalLines = splitLines(text);
291
+ const codeLines = splitLines(maskedCode);
292
+ const literalLines = splitLines(maskedLiterals);
293
+ const lineStarts = lineStartsOf(text);
294
+ const lineCount = originalLines.length;
295
+
296
+ return {
297
+ source: text,
298
+ code: maskedCode,
299
+ literals: maskedLiterals,
300
+ lineCount,
301
+ lines: { original: originalLines, code: codeLines, literals: literalLines },
302
+ lineAt: (index) => lineNumberAt(lineStarts, index),
303
+ sourceLine: (line) => originalLines[line - 1] ?? '',
304
+ codeLine: (line) => codeLines[line - 1] ?? '',
305
+ literalLine: (line) => literalLines[line - 1] ?? '',
306
+ };
307
+ }