@vibe-agent-toolkit/utils 0.1.41 → 0.1.42

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 (116) hide show
  1. package/README.md +146 -31
  2. package/dist/asset.d.ts +9 -0
  3. package/dist/asset.d.ts.map +1 -0
  4. package/dist/asset.js +9 -0
  5. package/dist/asset.js.map +1 -0
  6. package/dist/crawl.d.ts +19 -0
  7. package/dist/crawl.d.ts.map +1 -0
  8. package/dist/crawl.js +19 -0
  9. package/dist/crawl.js.map +1 -0
  10. package/dist/file-crawler.d.ts +19 -2
  11. package/dist/file-crawler.d.ts.map +1 -1
  12. package/dist/file-crawler.js +19 -1
  13. package/dist/file-crawler.js.map +1 -1
  14. package/dist/fs-utils.d.ts +60 -3
  15. package/dist/fs-utils.d.ts.map +1 -1
  16. package/dist/fs-utils.js +88 -10
  17. package/dist/fs-utils.js.map +1 -1
  18. package/dist/fs.d.ts +7 -6
  19. package/dist/fs.d.ts.map +1 -1
  20. package/dist/fs.js +7 -6
  21. package/dist/fs.js.map +1 -1
  22. package/dist/git-utils.d.ts +2 -0
  23. package/dist/git-utils.d.ts.map +1 -1
  24. package/dist/git-utils.js +16 -0
  25. package/dist/git-utils.js.map +1 -1
  26. package/dist/git.d.ts +23 -0
  27. package/dist/git.d.ts.map +1 -0
  28. package/dist/git.js +23 -0
  29. package/dist/git.js.map +1 -0
  30. package/dist/gitignore-checker.d.ts +0 -9
  31. package/dist/gitignore-checker.d.ts.map +1 -1
  32. package/dist/gitignore-checker.js +0 -12
  33. package/dist/gitignore-checker.js.map +1 -1
  34. package/dist/glob/glob-pattern.js +1 -1
  35. package/dist/glob/glob-pattern.js.map +1 -1
  36. package/dist/glob.d.ts +8 -0
  37. package/dist/glob.d.ts.map +1 -0
  38. package/dist/glob.js +8 -0
  39. package/dist/glob.js.map +1 -0
  40. package/dist/path-core.d.ts +196 -0
  41. package/dist/path-core.d.ts.map +1 -0
  42. package/dist/path-core.js +251 -0
  43. package/dist/path-core.js.map +1 -0
  44. package/dist/path-utils.d.ts +12 -183
  45. package/dist/path-utils.d.ts.map +1 -1
  46. package/dist/path-utils.js +13 -237
  47. package/dist/path-utils.js.map +1 -1
  48. package/dist/path.d.ts +12 -0
  49. package/dist/path.d.ts.map +1 -0
  50. package/dist/path.js +12 -0
  51. package/dist/path.js.map +1 -0
  52. package/dist/process.d.ts +7 -4
  53. package/dist/process.d.ts.map +1 -1
  54. package/dist/process.js +7 -4
  55. package/dist/process.js.map +1 -1
  56. package/dist/project.d.ts +31 -0
  57. package/dist/project.d.ts.map +1 -0
  58. package/dist/project.js +31 -0
  59. package/dist/project.js.map +1 -0
  60. package/dist/safe-exec.d.ts.map +1 -1
  61. package/dist/safe-exec.js +8 -4
  62. package/dist/safe-exec.js.map +1 -1
  63. package/dist/spawn-hardened.d.ts.map +1 -1
  64. package/dist/spawn-hardened.js +4 -17
  65. package/dist/spawn-hardened.js.map +1 -1
  66. package/dist/template-entry.d.ts +10 -0
  67. package/dist/template-entry.d.ts.map +1 -0
  68. package/dist/template-entry.js +10 -0
  69. package/dist/template-entry.js.map +1 -0
  70. package/dist/testing.d.ts +8 -0
  71. package/dist/testing.d.ts.map +1 -0
  72. package/dist/testing.js +8 -0
  73. package/dist/testing.js.map +1 -0
  74. package/dist/windows-shell.d.ts +140 -8
  75. package/dist/windows-shell.d.ts.map +1 -1
  76. package/dist/windows-shell.js +218 -11
  77. package/dist/windows-shell.js.map +1 -1
  78. package/dist/yaml.d.ts +9 -0
  79. package/dist/yaml.d.ts.map +1 -0
  80. package/dist/yaml.js +9 -0
  81. package/dist/yaml.js.map +1 -0
  82. package/dist/zod.d.ts +10 -0
  83. package/dist/zod.d.ts.map +1 -0
  84. package/dist/zod.js +10 -0
  85. package/dist/zod.js.map +1 -0
  86. package/eslint/README.md +217 -0
  87. package/eslint/index.cjs +161 -0
  88. package/eslint/index.d.cts +60 -0
  89. package/eslint/rules/dead-import.cjs +201 -0
  90. package/eslint/rules/eslint-rule-factory.cjs +410 -0
  91. package/eslint/rules/exempt-path-matcher.cjs +265 -0
  92. package/eslint/rules/no-bare-dynamic-import-path.cjs +142 -0
  93. package/eslint/rules/no-child-process-execSync.cjs +23 -0
  94. package/eslint/rules/no-command-direct-factory.cjs +246 -0
  95. package/eslint/rules/no-file-url-string-concat.cjs +77 -0
  96. package/eslint/rules/no-fs-mkdirSync.cjs +23 -0
  97. package/eslint/rules/no-fs-promises-cp.cjs +36 -0
  98. package/eslint/rules/no-fs-realpathSync.cjs +23 -0
  99. package/eslint/rules/no-hardcoded-path-split.cjs +141 -0
  100. package/eslint/rules/no-manual-path-normalize.cjs +161 -0
  101. package/eslint/rules/no-os-tmpdir.cjs +24 -0
  102. package/eslint/rules/no-path-join.cjs +14 -0
  103. package/eslint/rules/no-path-operations-in-comparisons.cjs +148 -0
  104. package/eslint/rules/no-path-relative.cjs +14 -0
  105. package/eslint/rules/no-path-resolve.cjs +14 -0
  106. package/eslint/rules/no-path-sep-in-strings.cjs +130 -0
  107. package/eslint/rules/no-path-startswith.cjs +139 -0
  108. package/eslint/rules/no-test-scoped-functions.cjs +134 -0
  109. package/eslint/rules/no-unix-shell-commands.cjs +152 -0
  110. package/eslint/rules/no-unsafe-root-join.cjs +85 -0
  111. package/eslint/rules/no-url-pathname-for-fs.cjs +107 -0
  112. package/eslint/rules/path-function-rule-factory.cjs +417 -0
  113. package/eslint/rules/prefer-startswith-over-regex.cjs +257 -0
  114. package/eslint/rules/require-justified-skip.cjs +348 -0
  115. package/eslint/rules/safe-import.cjs +164 -0
  116. package/package.json +65 -7
@@ -0,0 +1,417 @@
1
+ /**
2
+ * ESLint Rule Factory for banning specific path functions from node:path
3
+ *
4
+ * Handles both import styles:
5
+ * - Named: import { join } from 'node:path' → join(...)
6
+ * - Default/namespace: import path from 'node:path' → path.join(...)
7
+ *
8
+ * Auto-fixes to safePath.fn() from `@vibe-agent-toolkit/utils/path` — the narrow
9
+ * subpath that owns `safePath`, NOT the barrel. See `safe-import.cjs`.
10
+ */
11
+
12
+ const {
13
+ DEAD_UNSAFE_IMPORT,
14
+ DEAD_UNSAFE_IMPORT_MESSAGE,
15
+ reportDeadUnsafeImports,
16
+ } = require('./dead-import.cjs');
17
+ const {
18
+ UNANCHORED_EXEMPT_FILE,
19
+ UNANCHORED_EXEMPT_MESSAGE,
20
+ createConfigurableExemptPathMatcher,
21
+ reportUnanchoredExemptEntries,
22
+ } = require('./exempt-path-matcher.cjs');
23
+ const {
24
+ EXEMPT_AND_SAFE_MODULE_SCHEMA,
25
+ SAFE_PATH_MODULE,
26
+ insertAboveWithComments,
27
+ isNameAlreadyBound,
28
+ resolveSafeModule,
29
+ } = require('./safe-import.cjs');
30
+
31
+ const PATH_MODULES = new Set(['node:path', 'path']);
32
+ const SAFE_OBJECT = 'safePath';
33
+
34
+ /**
35
+ * The files allowed to call raw `node:path` functions are whichever ones the
36
+ * CONSUMING repo says implement (or assert) its `safePath` wrappers — declared
37
+ * per-rule as `{ exemptFiles: [...] }`, matched at a path-segment boundary (see
38
+ * `exempt-path-matcher.cjs` for why these are not substrings).
39
+ *
40
+ * This list used to be hardcoded to VAT's own `packages/utils/src/path-core.ts`
41
+ * et al. Those paths are meaningless in an adopter's tree and actively harmful
42
+ * as a default — a same-named file at the same repo-relative path would inherit
43
+ * an exemption it never declared. Default: nothing is exempt.
44
+ */
45
+ const exemptMatcherFor = createConfigurableExemptPathMatcher();
46
+
47
+ /**
48
+ * Remove a named import specifier, handling comma cleanup.
49
+ */
50
+ function removeSpecifier(fixer, sourceCode, importNode, spec) {
51
+ if (importNode.specifiers.length === 1) {
52
+ return [fixer.remove(importNode)];
53
+ }
54
+ const comma = sourceCode.getTokenAfter(spec);
55
+ if (comma?.value === ',') {
56
+ return [fixer.removeRange([spec.range[0], comma.range[1]])];
57
+ }
58
+ const commaBefore = sourceCode.getTokenBefore(spec);
59
+ if (commaBefore?.value === ',') {
60
+ return [fixer.removeRange([commaBefore.range[0], spec.range[1]])];
61
+ }
62
+ return [fixer.remove(spec)];
63
+ }
64
+
65
+ /**
66
+ * Track path module specifiers from an import declaration.
67
+ *
68
+ * Two specifier shapes are deliberately NOT tracked, because tracking them is
69
+ * what let the fixer delete them:
70
+ *
71
+ * - **Type-only** (`import { type join, … }` / `import type { join }`). The
72
+ * binding exists only for the type checker; there is no call to rewrite, and
73
+ * removing the specifier silently breaks every `typeof join` that referenced
74
+ * it. `no-undef` cannot see the damage — it is a TYPE reference.
75
+ * - **Aliased** (`import { join as pathJoin }`). The rule never reported
76
+ * `pathJoin(...)` in the first place — `classifyCall` matches on the callee's
77
+ * name — so tracking the specifier bought nothing and cost the whole import:
78
+ * an unrelated unbound `join(` elsewhere in the file made the fixer remove
79
+ * the alias, breaking every working `pathJoin` call site.
80
+ */
81
+ function trackPathImport(node, unsafeFn, state) {
82
+ if (node.importKind === 'type') {
83
+ return;
84
+ }
85
+ for (const spec of node.specifiers) {
86
+ if (
87
+ spec.type === 'ImportSpecifier' &&
88
+ spec.importKind !== 'type' &&
89
+ spec.imported.name === unsafeFn &&
90
+ spec.local.name === unsafeFn
91
+ ) {
92
+ state.namedImportSpec = spec;
93
+ state.namedImportNode = node;
94
+ }
95
+ if (spec.type === 'ImportDefaultSpecifier' || spec.type === 'ImportNamespaceSpecifier') {
96
+ state.defaultImportName = spec.local.name;
97
+ }
98
+ }
99
+ }
100
+
101
+ /**
102
+ * Is `name` re-exported by a bare `export { name }` in this file?
103
+ *
104
+ * Removing the import specifier then leaves the export naming nothing, and the
105
+ * result does not PARSE — `Export 'join' is not defined`. An autofix whose
106
+ * output cannot be parsed is the worst outcome available, so the specifier
107
+ * stays and the call sites are still rewritten. Whatever is left is a lint
108
+ * finding a human can read, not a broken file.
109
+ */
110
+ function isReExported(sourceCode, name) {
111
+ return sourceCode.ast.body.some(
112
+ (node) =>
113
+ node.type === 'ExportNamedDeclaration' &&
114
+ !node.source &&
115
+ node.specifiers.some((spec) => spec.local?.name === name),
116
+ );
117
+ }
118
+
119
+ /**
120
+ * Track safe module import from an import declaration.
121
+ */
122
+ function trackSafeImport(node, state) {
123
+ state.safeImportNode = node;
124
+ for (const spec of node.specifiers) {
125
+ if (spec.type === 'ImportSpecifier' && spec.imported.name === SAFE_OBJECT) {
126
+ state.hasSafePathImport = true;
127
+ }
128
+ }
129
+ }
130
+
131
+ /**
132
+ * Is `name` resolvable from `node`'s scope outward — a parameter, a local, an
133
+ * import, or a configured global?
134
+ *
135
+ * Used only to decide whether a bare `join(...)` with no `node:path` import is
136
+ * OUR `join` or somebody else's. `import { join } from 'lodash'` binds the name
137
+ * and is not our business; an unbound `join` is a ReferenceError waiting to
138
+ * happen, and — see `classifyCall` — is exactly what a half-applied autofix
139
+ * leaves behind.
140
+ */
141
+ function isIdentifierBound(sourceCode, node, name) {
142
+ for (let scope = sourceCode.getScope(node); scope; scope = scope.upper) {
143
+ if (scope.variables.some((variable) => variable.name === name)) {
144
+ return true;
145
+ }
146
+ }
147
+ return false;
148
+ }
149
+
150
+ /**
151
+ * Check if a call expression is an unsafe path function call.
152
+ *
153
+ * Returns `{ isNamed }` — or `{ importOnly: true }` for a call that is already
154
+ * correct and merely missing its import — or null if not a match.
155
+ */
156
+ function classifyCall(node, unsafeFn, state, sourceCode) {
157
+ const isMember = node.callee.type === 'MemberExpression' && node.callee.property.type === 'Identifier';
158
+
159
+ // Direct call: join(...)
160
+ if (node.callee.type === 'Identifier' && node.callee.name === unsafeFn) {
161
+ if (state.namedImportSpec) {
162
+ return { isNamed: true };
163
+ }
164
+ // REPAIR LEG. Keying detection on "did I see the import?" made this rule
165
+ // stop reporting the moment a fix removed the specifier, so a partial
166
+ // `--fix` reached a stable fixpoint over source that no longer compiles and
167
+ // exited clean.
168
+ //
169
+ // Gated on `safePath` already being bound, which is what makes it a repair
170
+ // rather than a second, sloppier detector. An unbound `join` is NOT reliably
171
+ // our `join`: ESLint scope analysis does not bind `declare global { function
172
+ // join() }`, and it cannot see an ambient global from a `globals.d.ts`, an
173
+ // `@types` package, or a bundler — `resolve` and `relative` are entirely
174
+ // plausible as those. Requiring `safePath` in scope narrows this to the
175
+ // half-migrated file it exists to finish, where the name really was ours.
176
+ if (state.safePathBoundInSource && !isIdentifierBound(sourceCode, node.callee, unsafeFn)) {
177
+ return { isNamed: false };
178
+ }
179
+ return null;
180
+ }
181
+
182
+ // Namespace call: path.join(...)
183
+ if (
184
+ isMember &&
185
+ node.callee.object.type === 'Identifier' &&
186
+ node.callee.object.name === state.defaultImportName &&
187
+ node.callee.property.name === unsafeFn
188
+ ) {
189
+ return { isNamed: false };
190
+ }
191
+
192
+ // REPAIR LEG, the other half: `safePath.join(...)` with no `safePath` in
193
+ // scope. This is what a partially-applied fix leaves — and without it, that
194
+ // state is PERMANENT rather than transient.
195
+ //
196
+ // ESLint runs `fix()` for a problem BEFORE the `eslint-disable` filter
197
+ // discards it, so a suppressed report on the first call site consumes the
198
+ // once-per-file import edit and then throws it away. Every other call is
199
+ // rewritten to `safePath.join`, nothing imports `safePath`, and no report
200
+ // survives to carry the import on any later pass. Recognising the orphaned
201
+ // call is what closes that loop; it costs one extra pass, and only in a file
202
+ // that is already broken.
203
+ if (
204
+ isMember &&
205
+ node.callee.object.type === 'Identifier' &&
206
+ node.callee.object.name === SAFE_OBJECT &&
207
+ node.callee.property.name === unsafeFn &&
208
+ !isIdentifierBound(sourceCode, node.callee.object, SAFE_OBJECT)
209
+ ) {
210
+ return { importOnly: true };
211
+ }
212
+
213
+ return null;
214
+ }
215
+
216
+ /**
217
+ * Build auto-fix for an unsafe path function call.
218
+ *
219
+ * ## Why the import edits are emitted at most ONCE per file
220
+ *
221
+ * ESLint merges the fixes one `fix()` yields into a SINGLE range spanning
222
+ * `min..max`, and applies only non-overlapping ranges per pass. A fix that
223
+ * touches both the import and its own call site therefore spans everything in
224
+ * between — so N such reports produce N nested ranges, ESLint keeps the
225
+ * shortest and DISCARDS THE REST.
226
+ *
227
+ * That is not an edge case, it is every file with more than one call site. The
228
+ * import edit landed, the other calls did not, and (before `classifyCall` grew
229
+ * its bare-call leg) the next pass could no longer see them because the
230
+ * specifier it keyed on was gone. `--fix` reached a stable fixpoint over source
231
+ * that does not compile and exited clean. An adopter measured 146 files left
232
+ * with a dangling reference across one sweep — worst single file, 75 call sites.
233
+ *
234
+ * So: the shared edits belong to the first report, and every later report emits
235
+ * a fix LOCAL to its own callee. Nothing overlaps, and one pass fixes the file.
236
+ * `no-manual-path-normalize.cjs` carries the same guard for the same reason.
237
+ *
238
+ * Only the FIRST report's fix is self-sufficient, and that is load-bearing:
239
+ * applying a later one ALONE — an editor's "fix this problem", or an
240
+ * `eslint-disable` on the first call site — rewrites the call without adding
241
+ * the import. ESLint runs `fix()` before the disable filter, so a suppressed
242
+ * report consumes the once-per-file edit and then discards it.
243
+ *
244
+ * That state is recoverable rather than permanent ONLY because `classifyCall`
245
+ * has a repair leg for an orphaned `safePath.join(...)`. Without it the file
246
+ * stays broken through every subsequent `--fix`, because no report is left to
247
+ * carry the import — measured, not reasoned about. An earlier draft of this
248
+ * comment asserted the recovery came free from `hasSafePathImport` being seeded
249
+ * from scope; that was wrong, and an adversarial run produced the stable broken
250
+ * fixpoint to prove it.
251
+ *
252
+ * The shared edits still cannot be hoisted onto their own report: removing
253
+ * `join` from the import while a suppressed `join(...)` call survives is the
254
+ * same broken output reached a different way. `exemptFiles` opts a whole file
255
+ * out.
256
+ */
257
+ function importSafePath(fixer, sourceCode, state) {
258
+ if (state.safeImportNode) {
259
+ const lastSpec = state.safeImportNode.specifiers.at(-1);
260
+ return fixer.insertTextAfter(lastSpec, `, ${SAFE_OBJECT}`);
261
+ }
262
+ const targetNode = state.namedImportNode || sourceCode.ast.body[0];
263
+ const declaration = `import { ${SAFE_OBJECT} } from '${state.safeModule}';`;
264
+ // Land the new import next to the imports, not after arbitrary code. A file
265
+ // reported only through a repair leg may have no path import at all, and
266
+ // `insertTextAfter(body[0])` would push the declaration below the statement
267
+ // that needs it — legal, since imports hoist, but it reads as though the
268
+ // fixer lost track of the file.
269
+ return targetNode.type === 'ImportDeclaration'
270
+ ? fixer.insertTextAfter(targetNode, `\n${declaration}`)
271
+ : insertAboveWithComments(fixer, sourceCode, targetNode, `${declaration}\n`);
272
+ }
273
+
274
+ function buildFix(fixer, node, unsafeFn, classification, sourceCode, state) {
275
+ // REPAIR: an orphaned `safePath.join(...)` is already the call we want, and
276
+ // the only thing missing is the import that a discarded report was carrying.
277
+ //
278
+ // This deliberately ignores `state.hasSafePathImport`. That flag is mutated
279
+ // inside `fix()`, and ESLint runs `fix()` for a SUPPRESSED problem before the
280
+ // disable filter throws it away — so on every pass the suppressed report
281
+ // spends the flag first and the repair emits nothing. The file then never
282
+ // recovers, which is precisely the stable broken fixpoint this leg exists to
283
+ // break. The gate that makes ignoring the flag safe is immutable: this
284
+ // classification is only reached when `safePath` is unbound in the SOURCE.
285
+ //
286
+ // Several orphaned calls yield the identical insert at the identical anchor,
287
+ // so ESLint applies one and drops the rest as overlapping — which is the
288
+ // desired outcome, not a hazard.
289
+ if (classification.importOnly) {
290
+ return [importSafePath(fixer, sourceCode, state)];
291
+ }
292
+
293
+ const fixes = [fixer.replaceText(node.callee, `${SAFE_OBJECT}.${unsafeFn}`)];
294
+
295
+ if (!state.hasSafePathImport) {
296
+ fixes.push(importSafePath(fixer, sourceCode, state));
297
+ state.hasSafePathImport = true;
298
+ }
299
+
300
+ if (
301
+ classification.isNamed &&
302
+ state.namedImportNode &&
303
+ !state.namedImportRemoved &&
304
+ !isReExported(sourceCode, unsafeFn)
305
+ ) {
306
+ fixes.push(...removeSpecifier(fixer, sourceCode, state.namedImportNode, state.namedImportSpec));
307
+ state.namedImportRemoved = true;
308
+ }
309
+
310
+ return fixes;
311
+ }
312
+
313
+ module.exports = function createPathFunctionRule(config) {
314
+ const { unsafeFn, message } = config;
315
+
316
+ return {
317
+ meta: {
318
+ type: 'problem',
319
+ docs: {
320
+ description: `Enforce safePath.${unsafeFn}() instead of path.${unsafeFn}()`,
321
+ category: 'Cross-platform compatibility',
322
+ recommended: true,
323
+ },
324
+ fixable: 'code',
325
+ schema: [EXEMPT_AND_SAFE_MODULE_SCHEMA],
326
+ messages: {
327
+ noUnsafePathFn: message,
328
+ [DEAD_UNSAFE_IMPORT]: DEAD_UNSAFE_IMPORT_MESSAGE,
329
+ [UNANCHORED_EXEMPT_FILE]: UNANCHORED_EXEMPT_MESSAGE,
330
+ },
331
+ },
332
+
333
+ create(context) {
334
+ if (exemptMatcherFor(context)(context.getFilename())) {
335
+ // Still surface a malformed exemption list: the file we are standing in
336
+ // may be exempt only BECAUSE the entry is unanchored.
337
+ return {
338
+ Program(node) {
339
+ reportUnanchoredExemptEntries(context, node);
340
+ },
341
+ };
342
+ }
343
+
344
+ const sourceCode = context.getSourceCode();
345
+ const state = {
346
+ // Resolved per invocation — the option belongs to the consuming repo,
347
+ // which may point different rules at different re-export entries.
348
+ safeModule: resolveSafeModule(context, SAFE_PATH_MODULE),
349
+ namedImportSpec: null,
350
+ namedImportNode: null,
351
+ // Both of these guard a SHARED edit against being emitted by more than
352
+ // one report — see `buildFix` for what ESLint does with the overlap.
353
+ namedImportRemoved: false,
354
+ defaultImportName: null,
355
+ // Seeded from SCOPE, not from "did I see an import from SAFE_MODULE?".
356
+ // A file already importing `safePath` from the barrel needs the call
357
+ // rewritten but must NOT gain a second binding of the same name.
358
+ hasSafePathImport: isNameAlreadyBound(sourceCode, SAFE_OBJECT),
359
+ // The SAME question, answered once and never mutated. `hasSafePathImport`
360
+ // flips to true the moment a fix inserts the import, and gating the
361
+ // repair leg on a flag that the first report can flip would arm it for
362
+ // the rest of THIS pass — re-admitting the ambient-global false positive
363
+ // in any file that also has a `path.join()` to fix.
364
+ safePathBoundInSource: isNameAlreadyBound(sourceCode, SAFE_OBJECT),
365
+ safeImportNode: null,
366
+ // EVERY path-module declaration, not just the one carrying `unsafeFn`.
367
+ // A file's dead binding is `import path from 'node:path'`, which
368
+ // `trackPathImport` only ever recorded as a NAME. See `dead-import.cjs`.
369
+ pathImportNodes: [],
370
+ };
371
+
372
+ return {
373
+ Program(node) {
374
+ reportUnanchoredExemptEntries(context, node);
375
+ },
376
+
377
+ 'Program:exit'() {
378
+ reportDeadUnsafeImports(
379
+ context,
380
+ sourceCode,
381
+ state.pathImportNodes,
382
+ state.safePathBoundInSource,
383
+ );
384
+ },
385
+
386
+ ImportDeclaration(node) {
387
+ if (PATH_MODULES.has(node.source.value)) {
388
+ state.pathImportNodes.push(node);
389
+ trackPathImport(node, unsafeFn, state);
390
+ }
391
+ if (node.source.value === state.safeModule) {
392
+ trackSafeImport(node, state);
393
+ }
394
+ },
395
+
396
+ CallExpression(node) {
397
+ const classification = classifyCall(node, unsafeFn, state, sourceCode);
398
+ if (!classification) {
399
+ return;
400
+ }
401
+
402
+ context.report({
403
+ node,
404
+ messageId: 'noUnsafePathFn',
405
+ // The module name reaches the message through `{{safeModule}}` rather
406
+ // than being spelled out in each rule's string, so the advice cannot
407
+ // drift from where the fixer actually writes the import.
408
+ data: { safeModule: state.safeModule },
409
+ fix(fixer) {
410
+ return buildFix(fixer, node, unsafeFn, classification, sourceCode, state);
411
+ },
412
+ });
413
+ },
414
+ };
415
+ },
416
+ };
417
+ };
@@ -0,0 +1,257 @@
1
+ /**
2
+ * ESLint rule: prefer-startswith-over-regex
3
+ *
4
+ * Catches `/^literal/.test(s)` and `/literal$/.test(s)` patterns whose body
5
+ * flattens to a plain string, and recommends `s.startsWith('literal')` /
6
+ * `s.endsWith('literal')`.
7
+ *
8
+ * Why a local rule?
9
+ * `unicorn/prefer-string-starts-ends-with` already handles the simple case
10
+ * but conservatively rejects any pattern containing `\` — including the
11
+ * common `\/` (escaped slash) sequence. SonarCloud's S6557 catches these,
12
+ * but only post-merge. This rule shifts that detection left into ESLint.
13
+ *
14
+ * ## Two shapes this rule deliberately does NOT limit itself to
15
+ *
16
+ * Both were narrowings in the first draft, and an adopter found each of them
17
+ * the same way: SonarCloud raised a MAJOR S6557 on code this rule had reported
18
+ * green.
19
+ *
20
+ * 1. **The regex need not be inline.** `const RE = /^x/; RE.test(s)` is the
21
+ * same violation as `/^x/.test(s)` — see {@link resolveRegex}.
22
+ * 2. **An escaped non-special character is a literal character.** `\*` is an
23
+ * unambiguous `*`; refusing every escape but `\/` skipped it — see
24
+ * {@link literalEquivalent}.
25
+ *
26
+ * Neither could have been caught by scanning an adopter's tree. The rule runs
27
+ * at `error` there, so its finding count is zero BY CONSTRUCTION — lint cannot
28
+ * go green while a violation exists. A 0-vs-0 tie against another
29
+ * implementation is not agreement, it is two rules both failing to fire. For
30
+ * any rule an adopter reports zero findings for, that rule is *unmeasured*.
31
+ *
32
+ * Examples:
33
+ * /^file:\/\//.test(s) → s.startsWith('file://')
34
+ * /^\*glob/.test(s) → s.startsWith('*glob')
35
+ * const R = /^a/; R.test(s) → s.startsWith('a')
36
+ * /^https?:\/\//.test(s) → NOT flagged (contains `?` quantifier)
37
+ * /^[a-z]+/.test(s) → NOT flagged (contains `[` character class)
38
+ * /\.txt$/.test(s) → NOT flagged (`.` is a metachar; `\.` would flag)
39
+ * /^\d+/.test(s) → NOT flagged (`\d` is a character class)
40
+ */
41
+
42
+ 'use strict';
43
+
44
+ const METACHARS = new Set(['^', '$', '+', '[', '{', '(', '.', '?', '*', '|']);
45
+
46
+ /**
47
+ * Escape sequences whose meaning is NOT "the character that follows the
48
+ * backslash": character classes (`\d`, `\w`, `\s`, `\p`), assertions (`\b`),
49
+ * numeric escapes and backreferences (`\0`–`\9`, `\k`), and the code-point
50
+ * forms (`\x`, `\u`, `\c`). `\n`, `\r`, `\t`, `\v`, `\f` ARE single literal
51
+ * characters, but flattening them would put a raw control character into the
52
+ * suggested `startsWith('…')` string, so they are rejected too.
53
+ *
54
+ * Every other escape — `\/`, `\.`, `\*`, `\+`, `\(`, `\\`, `\-` … — is an
55
+ * identity escape, and the character it protects is exactly what a
56
+ * `startsWith` comparison would look for.
57
+ */
58
+ const MEANINGFUL_ESCAPE = /[0-9BDPSWbcdfknprstuvwx]/;
59
+
60
+ /**
61
+ * Flatten a regex body to the plain string it is equivalent to.
62
+ *
63
+ * Returns the literal string if safely convertible, otherwise null. Scans
64
+ * character by character rather than doing a `replaceAll` of the one escape we
65
+ * happen to like: `\/` was accepted and `\*` was not, though both denote a
66
+ * single literal character and neither is a metacharacter once escaped.
67
+ */
68
+ function literalEquivalent(patternBody) {
69
+ let literal = '';
70
+
71
+ for (let index = 0; index < patternBody.length; index += 1) {
72
+ const char = patternBody[index];
73
+
74
+ if (char === '\\') {
75
+ const escaped = patternBody[index + 1];
76
+ // A trailing lone backslash is not a valid pattern; refuse to guess.
77
+ if (escaped === undefined || MEANINGFUL_ESCAPE.test(escaped)) {
78
+ return null;
79
+ }
80
+ literal += escaped;
81
+ index += 1;
82
+ continue;
83
+ }
84
+
85
+ // Unescaped metacharacter: flattening it would change what matches.
86
+ if (METACHARS.has(char)) {
87
+ return null;
88
+ }
89
+ literal += char;
90
+ }
91
+
92
+ return literal;
93
+ }
94
+
95
+ /**
96
+ * Find the variable `identifier` resolves to, searching outward from its scope.
97
+ */
98
+ function findVariable(sourceCode, identifier) {
99
+ for (let scope = sourceCode.getScope(identifier); scope; scope = scope.upper) {
100
+ const found = scope.variables.find((variable) => variable.name === identifier.name);
101
+ if (found) {
102
+ return found;
103
+ }
104
+ }
105
+ return null;
106
+ }
107
+
108
+ /**
109
+ * The regex `node` denotes: itself when it is a regex literal, or the literal
110
+ * a single-assignment variable was initialised with.
111
+ *
112
+ * The indirection matters because hoisting a regex to a module-level `const` is
113
+ * the normal way to write one — and examining only inline literals meant the
114
+ * rule went quiet on exactly the code most likely to run hot.
115
+ *
116
+ * Conservative on purpose: one definition, one write, and that write is a regex
117
+ * literal. A binding assigned more than once could hold anything by the time
118
+ * `.test()` runs, and nothing here proves which value that is.
119
+ *
120
+ * `indirect` is what lets the caller treat a hoisted regex differently from an
121
+ * inline one — see the `g`/`y` guard, which only a shared object can trip.
122
+ *
123
+ * @returns {{pattern: string, flags: string, indirect: boolean} | null}
124
+ */
125
+ function resolveRegex(sourceCode, node) {
126
+ if (node.type === 'Literal' && node.regex) {
127
+ return { ...node.regex, indirect: false };
128
+ }
129
+ if (node.type !== 'Identifier') {
130
+ return null;
131
+ }
132
+
133
+ const variable = findVariable(sourceCode, node);
134
+ if (variable?.defs.length !== 1) {
135
+ return null;
136
+ }
137
+ const [definition] = variable.defs;
138
+ if (definition.type !== 'Variable' || !definition.node.init) {
139
+ return null;
140
+ }
141
+ if (variable.references.filter((reference) => reference.isWrite()).length !== 1) {
142
+ return null;
143
+ }
144
+
145
+ const { init } = definition.node;
146
+ return init.type === 'Literal' && init.regex ? { ...init.regex, indirect: true } : null;
147
+ }
148
+
149
+ /**
150
+ * Render the flattened literal as JS SOURCE, not as a bare character run.
151
+ *
152
+ * The literal is a string of characters; the message drops it into
153
+ * `startsWith(…)`, which a human reads as source. Those are different
154
+ * languages, and interpolating one into the other loses exactly the characters
155
+ * that matter. `/^C:\\Users/` flattens to `C:\Users` — one backslash — and
156
+ * emitting it raw produced the advice `startsWith('C:\Users')`, which JavaScript
157
+ * reads back as `"C:Users"`. Worse in the realistic case: a `/^\\\\/` UNC check
158
+ * became `startsWith('\\')`, i.e. ONE backslash, silently true for any
159
+ * single-backslash path. A literal containing `'` produced advice that is a
160
+ * `SyntaxError` outright.
161
+ *
162
+ * This rule has no fixer, so the message IS the deliverable — there is no
163
+ * autofixer downstream that would have escaped it correctly.
164
+ */
165
+ function asSourceLiteral(literal) {
166
+ return JSON.stringify(literal);
167
+ }
168
+
169
+ module.exports = {
170
+ meta: {
171
+ type: 'problem',
172
+ docs: {
173
+ description:
174
+ String.raw`Prefer String#startsWith / String#endsWith over /^literal/.test() — including escaped literals such as \/ and \*, and regexes held in a const`,
175
+ recommended: true,
176
+ },
177
+ messages: {
178
+ // `{{pattern}}` carries its FLAGS. Rendering `/^abc/` for a source
179
+ // `/^abc/g` hid the one character that decides whether the advice is
180
+ // right, from the one person positioned to notice.
181
+ preferStartsWith:
182
+ 'Prefer `<string>.startsWith({{literal}})` over `/{{pattern}}/{{flags}}.test(<string>)`. ' +
183
+ String.raw`An escaped character such as \/ or \* is the literal character itself.`,
184
+ preferEndsWith:
185
+ 'Prefer `<string>.endsWith({{literal}})` over `/{{pattern}}/{{flags}}.test(<string>)`. ' +
186
+ String.raw`An escaped character such as \/ or \* is the literal character itself.`,
187
+ },
188
+ schema: [],
189
+ },
190
+
191
+ create(context) {
192
+ const sourceCode = context.getSourceCode();
193
+
194
+ return {
195
+ CallExpression(node) {
196
+ if (
197
+ node.callee.type !== 'MemberExpression' ||
198
+ node.callee.property.type !== 'Identifier' ||
199
+ node.callee.property.name !== 'test'
200
+ ) {
201
+ return;
202
+ }
203
+ // `startsWith` needs a string receiver where `.test()` would have
204
+ // coerced one. Arity is the only part of that this rule can check
205
+ // without types — a zero-argument `.test()` coerces `undefined` to
206
+ // "undefined" and is nobody's prefix check. A non-string ARGUMENT
207
+ // (`/^\[object/.test(v)`) remains a known limitation: `.test` coerces,
208
+ // `startsWith` throws, and only a type checker can tell them apart.
209
+ if (node.arguments.length !== 1) {
210
+ return;
211
+ }
212
+
213
+ const regex = resolveRegex(sourceCode, node.callee.object);
214
+ if (!regex) {
215
+ return;
216
+ }
217
+ const { pattern, flags, indirect } = regex;
218
+ if (flags.includes('i') || flags.includes('m')) {
219
+ return;
220
+ }
221
+ // `g` and `y` make `.test()` STATEFUL through `lastIndex`. A regex
222
+ // LITERAL is reconstructed on every evaluation, so its cursor is always
223
+ // 0 and the flags are inert; a hoisted `const` is one object that
224
+ // remembers. `const RE = /^abc/g` answers [true, false, true, false] to
225
+ // four calls on the same string where `startsWith` answers true four
226
+ // times — so resolving through a binding is precisely what makes this
227
+ // advice wrong, and precisely where it must not be given.
228
+ if (indirect && (flags.includes('g') || flags.includes('y'))) {
229
+ return;
230
+ }
231
+
232
+ const report = (messageId, literal) => {
233
+ context.report({
234
+ node,
235
+ messageId,
236
+ data: { literal: asSourceLiteral(literal), pattern, flags },
237
+ });
238
+ };
239
+
240
+ if (pattern.startsWith('^')) {
241
+ const literal = literalEquivalent(pattern.slice(1));
242
+ if (literal !== null && literal !== '') {
243
+ report('preferStartsWith', literal);
244
+ return;
245
+ }
246
+ }
247
+
248
+ if (pattern.endsWith('$') && !pattern.endsWith(String.raw`\$`)) {
249
+ const literal = literalEquivalent(pattern.slice(0, -1));
250
+ if (literal !== null && literal !== '') {
251
+ report('preferEndsWith', literal);
252
+ }
253
+ }
254
+ },
255
+ };
256
+ },
257
+ };