package-json-scripts-portability 0.0.2 → 0.0.4

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 (71) hide show
  1. package/README.md +60 -19
  2. package/dist/analyze-script.d.mts +10 -3
  3. package/dist/analyze-script.mjs +24 -15
  4. package/dist/command-checker.mjs +331 -99
  5. package/dist/command-usage.mjs +85 -36
  6. package/dist/commands.mjs +124 -5
  7. package/dist/context.mjs +8 -1
  8. package/dist/fixes.d.mts +1 -1
  9. package/dist/fixes.mjs +193 -49
  10. package/dist/line-break-checker.mjs +40 -7
  11. package/dist/messages.mjs +9 -1
  12. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/array/sorted-array-insertion-index-with.mjs +33 -0
  13. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/array/sorted-array-insertion-index.mjs +10 -0
  14. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/semver/is-semver-in-range.mjs +5 -0
  15. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/semver/parse-semver.mjs +26 -0
  16. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/string/substring-after.mjs +24 -0
  17. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/_internal/isUnsafeProperty.mjs +18 -0
  18. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/_internal/setOwnValue.mjs +23 -0
  19. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/_internal/toPropertyKey.mjs +16 -0
  20. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/compat/_internal/baseToString.mjs +26 -0
  21. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/compat/_internal/hasOwn.mjs +13 -0
  22. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/compat/_internal/isDeepKey.mjs +39 -0
  23. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/compat/_internal/isIndex.mjs +10 -0
  24. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/compat/_internal/tags.mjs +2 -1
  25. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/compat/_internal/toKey.mjs +15 -0
  26. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/compat/array/sortedIndex.mjs +36 -0
  27. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/compat/array/sortedIndexBy.mjs +54 -0
  28. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/compat/array/sortedLastIndex.mjs +34 -0
  29. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/compat/array/sortedLastIndexBy.mjs +21 -0
  30. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/compat/function/identity.mjs +5 -0
  31. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/compat/object/cloneDeep.mjs +52 -0
  32. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/compat/object/cloneDeepWith.mjs +179 -0
  33. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/compat/object/get.mjs +67 -0
  34. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/compat/object/has.mjs +53 -0
  35. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/compat/object/property.mjs +26 -0
  36. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/compat/predicate/isArguments.mjs +26 -0
  37. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/compat/predicate/isBuffer.mjs +24 -0
  38. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/compat/predicate/isMatch.mjs +34 -0
  39. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/compat/predicate/isMatchWith.mjs +163 -0
  40. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/compat/predicate/isNaN.mjs +18 -0
  41. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/compat/predicate/isNil.mjs +24 -0
  42. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/compat/predicate/isNumber.mjs +24 -0
  43. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/compat/predicate/isObjectLike.mjs +28 -0
  44. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/compat/predicate/isSymbol.mjs +19 -0
  45. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/compat/predicate/isTypedArray.mjs +21 -0
  46. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/compat/predicate/matches.mjs +36 -0
  47. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/compat/predicate/matchesProperty.mjs +47 -0
  48. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/compat/util/iteratee.mjs +46 -0
  49. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/compat/util/toPath.mjs +75 -0
  50. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/compat/util/toString.mjs +23 -0
  51. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/function/identity.mjs +24 -0
  52. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/predicate/isEqualWith.mjs +1 -2
  53. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/predicate/isNil.mjs +24 -0
  54. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/predicate/isNull.mjs +25 -0
  55. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/predicate/isPrimitive.mjs +26 -0
  56. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/predicate/isSymbol.mjs +28 -0
  57. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/predicate/isTypedArray.mjs +20 -0
  58. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/predicate/isUndefined.mjs +25 -0
  59. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/remeda/dist/binarySearchCutoffIndex-Bu-OMJ0Z.mjs +26 -0
  60. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/remeda/dist/sortedIndexWith.mjs +7 -0
  61. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/verkit/dist/comparison-CmVirWIW.mjs +108 -0
  62. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/verkit/dist/range-C5wjdo9a.mjs +164 -0
  63. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/verkit/dist/set-BGFWKKE8.mjs +38 -0
  64. package/dist/redirection-checker.mjs +76 -24
  65. package/dist/reporter.mjs +63 -18
  66. package/dist/runners.d.mts +2 -5
  67. package/dist/runners.mjs +103 -22
  68. package/dist/script-analyzer.mjs +457 -155
  69. package/dist/word-checker.mjs +232 -103
  70. package/dist/words.mjs +34 -7
  71. package/package.json +27 -23
@@ -1,12 +1,12 @@
1
- import { OS_COMMANDS, PATTERN_COMMANDS } from "./commands.mjs";
2
- import { bashLabel, withCovered } from "./context.mjs";
3
- import { braceExpansionFix, quoting, replacement } from "./fixes.mjs";
4
- import { BASH_SUGGESTION, CROSS_ENV_SUGGESTION, CROSS_ENV_VARIABLE_SUGGESTION, NODE_SCRIPT_SUGGESTION, VARIABLE_SUGGESTION, truncate } from "./messages.mjs";
5
- import { PLATFORMS, POSIX_PLATFORMS, WINDOWS_PLATFORMS } from "./platforms.mjs";
1
+ import { CMD_BUILTINS, NON_GLOB_PROGRAMS, OS_COMMANDS, PATTERN_COMMANDS, SHELL_STATE_COMMANDS } from "./commands.mjs";
2
+ import { bashLabel, originalText, withCovered } from "./context.mjs";
3
+ import { backslashPathFix, braceExpansionFix, crossEnvEdits, quoting } from "./fixes.mjs";
4
+ import { BASH_SUGGESTION, CROSS_ENV_SUGGESTION, CROSS_ENV_VARIABLE_SUGGESTION, NODE_SCRIPT_SUGGESTION, VARIABLE_SUGGESTION, snippet, truncate } from "./messages.mjs";
5
+ import { MACOS_PLATFORMS, PLATFORMS, POSIX_PLATFORMS, WINDOWS_PLATFORMS } from "./platforms.mjs";
6
6
  import { setHas } from "./node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/set/set-has.mjs";
7
7
  import { substringAfterLast } from "./node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/string/substring-after-last.mjs";
8
8
  import { toForwardSlashes } from "./node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/path/to-forward-slashes.mjs";
9
- import { DOUBLE_QUOTED_SPECIAL_CHARACTERS, GLOB_PART_TYPES, POSIX_PATH, TILDE_EXPANSION, isPlainAssignment, isPlainWord, staticValue } from "./words.mjs";
9
+ import { DOUBLE_QUOTED_SPECIAL_CHARACTERS, GLOB_PART_TYPES, POSIX_PATH, TILDE_EXPANSION, WHITESPACE, doesMentionVariables, isPlainAssignment, isPlainWord, staticValue } from "./words.mjs";
10
10
  // src/word-checker.ts
11
11
  /** Variables that Bash sets, but dash doesn't, by the kind of syntax they are */
12
12
  const BASH_VARIABLES = /* @__PURE__ */ new Map([
@@ -23,12 +23,7 @@ const BASH_VARIABLES = /* @__PURE__ */ new Map([
23
23
  ["SRANDOM", "bash4"],
24
24
  ["UID", "bash"]
25
25
  ]);
26
- /**
27
- * Variables that POSIX shells and systems set, but Windows doesn't, e.g. `PWD`.
28
- * cmd.exe computes its own dynamic variables, like `%CD%`, so they aren't in the environment
29
- * either.
30
- * Some runners, like npm, set `HOME` on all platforms
31
- */
26
+ /** Variables that POSIX shells and systems set, but Windows doesn't, e.g. `PWD` */
32
27
  const POSIX_ONLY_VARIABLES = /* @__PURE__ */ new Set([
33
28
  ...BASH_VARIABLES.keys(),
34
29
  "LOGNAME",
@@ -45,18 +40,33 @@ const PACKAGE_MANAGER_VARIABLE = /^(?:npm_\w+|INIT_CWD)$/;
45
40
  const CMD_STATEMENTS = /* @__PURE__ */ new Set(["for", "if"]);
46
41
  /** Characters that cmd.exe splits words at or interprets */
47
42
  const CMD_SPECIAL_CHARACTERS = /[\s"%&<>^|]/;
43
+ /**
44
+ * Characters that shells interpret outside quotes, apart from whitespace, e.g. `*` and `;` in POSIX
45
+ * shells, or `%` and `^` in cmd.exe
46
+ */
47
+ const SHELL_SPECIAL_CHARACTERS = /["#$%&'()*;<>?[\\\]^`{|}~]/;
48
+ /** Operators that cmd.exe runs even in a string that `echo` prints, e.g. `>` in `echo '-> done'` */
49
+ const CMD_OPERATORS = /[&<>|]/;
48
50
  /** Backslash escapes that POSIX shells remove, but cmd.exe passes on, e.g. `\$` or `\ ` */
49
51
  const UNQUOTED_ESCAPE = /\\[\t !#$&'()*;<>?[\]`{|}~]/g;
50
52
  /** The same, in double quotes */
51
53
  const QUOTED_ESCAPE = /\\[$`]/g;
54
+ /**
55
+ * Several backslashes, which POSIX shells replace with half as many, while programs on Windows
56
+ * only do so before a `"`, e.g. `\\` in `"\\.e2e"`
57
+ */
58
+ const BACKSLASH_RUN = /(?<!\\)\\{2,}(?!["\\])/g;
52
59
  /** `cross-env` removes the backslashes of these escapes itself */
53
60
  const CROSS_ENV_ESCAPE = /^\\[$']$/;
54
61
  /** A named variable, e.g. `$HOME` rather than `$?` */
55
62
  const NAMED_VARIABLE = /^\$\w+$/;
56
63
  /** A `**` path segment, which `sh` doesn't expand recursively */
57
64
  const RECURSIVE_GLOB = /(?:^|[/=])\*\*\//;
65
+ /** A cmd.exe variable with a name of two or more characters, e.g. `%PORT%` */
58
66
  const WINDOWS_VARIABLE = /%[a-z_]\w+%/i;
59
67
  const WINDOWS_VARIABLES = new RegExp(WINDOWS_VARIABLE, "gi");
68
+ /** Several percent-encoded bytes, e.g. `%C3%BC` for `ü` in a URL */
69
+ const PERCENT_ENCODED_BYTES = /(?:%[\da-f]{2}){2,}/gi;
60
70
  /**
61
71
  * A Windows path: a drive, relative prefix or first segment, then `\`-separated segments.
62
72
  * The segments may be globs, e.g. `lib\**\*.js`
@@ -68,6 +78,8 @@ const FILE_EXTENSION = /\.\w+$/;
68
78
  const MULTIPLE_BACKSLASHES = /\\.*\\/;
69
79
  /** Backslashes that only escape dots are likely a regex, e.g. `logging\.spec\.ts` */
70
80
  const NON_DOT_ESCAPE = /\\[^.]/;
81
+ /** A backslash that is neither a regex escape of a dot nor a character class, e.g. `\s` */
82
+ const NON_REGEX_ESCAPE = /\\(?![.bdsw])/i;
71
83
  const hasBashArithmetic = (expression) => {
72
84
  switch (expression?.type) {
73
85
  case "ArithmeticBinary": return expression.operator.startsWith("**") || hasBashArithmetic(expression.left) || hasBashArithmetic(expression.right);
@@ -101,7 +113,34 @@ const parameterOperands = (operation) => {
101
113
  */
102
114
  const isTool = (command) => {
103
115
  const name = command?.toLowerCase();
104
- return name != null && !OS_COMMANDS.has(name) && !CMD_STATEMENTS.has(name);
116
+ return name != null && !OS_COMMANDS.has(name) && !CMD_BUILTINS.has(name) && !CMD_STATEMENTS.has(name);
117
+ };
118
+ /** The fix that prefixes each command with `cross-env`, which its assignments share */
119
+ const crossEnvPrefixFixes = /* @__PURE__ */ new WeakMap();
120
+ /**
121
+ * Gets a fix that prefixes a command with `cross-env`, which takes over its assignments.
122
+ * @param command The command
123
+ * @returns The fix, if `cross-env` runs the same command with the same variables
124
+ */
125
+ const crossEnvPrefixFix = (command) => {
126
+ if (crossEnvPrefixFixes.has(command)) return crossEnvPrefixFixes.get(command);
127
+ const names = /* @__PURE__ */ new Set();
128
+ const name = command.name && staticValue(command.name) || "";
129
+ const edits = name !== ":" && command.name != null && !SHELL_STATE_COMMANDS.has(name) && command.prefix.every((item) => {
130
+ if (!isPlainAssignment(item) || doesMentionVariables(item.value.text, names)) return false;
131
+ names.add(item.name);
132
+ return true;
133
+ }) ? crossEnvEdits(command.prefix, [command.name, ...command.suffix.filter((item) => item.type === "Word")]) : void 0;
134
+ const fix = edits && {
135
+ description: "Prefix the command with `cross-env`.",
136
+ edits: [{
137
+ end: command.pos,
138
+ pos: command.pos,
139
+ text: "cross-env "
140
+ }, ...edits]
141
+ };
142
+ crossEnvPrefixFixes.set(command, fix);
143
+ return fix;
105
144
  };
106
145
  /** Checks words, e.g. for quotes, expansions and paths */
107
146
  var WordChecker = class {
@@ -120,36 +159,57 @@ var WordChecker = class {
120
159
  * @param command The command that the assignment prefixes, e.g. `jest` in `CI=1 jest`
121
160
  */
122
161
  checkAssignment(assignment, context, command) {
123
- const { append, index, value } = assignment;
124
- const isBashSpecific = value.type === "ArrayValue" || index != null || append;
162
+ const { value } = assignment;
163
+ const isBashSpecific = this.#checkBashAssignment(assignment, context);
125
164
  const doesPrefixCommand = command != null;
126
- if (isBashSpecific) this.#reporter.reportSyntax(context, assignment, "bash", false, "unsupportedSyntax", {
127
- suggestion: BASH_SUGGESTION,
128
- syntax: `The Bash-specific ${index || value.type === "ArrayValue" ? "array" : "appending"} assignment \`${truncate(assignment.text)}\``
129
- });
130
- else this.#reporter.reportSyntax(context, assignment, "posix", true, "unsupportedSyntax", {
165
+ if (!isBashSpecific) this.#reporter.reportSyntax(context, assignment, "posix", true, "unsupportedSyntax", {
131
166
  suggestion: CROSS_ENV_SUGGESTION,
132
- syntax: doesPrefixCommand ? `The inline environment variable assignment \`${truncate(assignment.text)}\`` : `The shell variable assignment \`${truncate(assignment.text)}\``
133
- }, command?.prefix.every(isPlainAssignment) ? {
134
- description: "Prefix the command with `cross-env`.",
135
- edits: [{
136
- end: command.pos,
137
- pos: command.pos,
138
- text: "cross-env "
139
- }]
140
- } : void 0);
167
+ syntax: doesPrefixCommand ? `The inline environment variable assignment \`${snippet(context, assignment)}\`` : `The shell variable assignment \`${snippet(context, assignment)}\``
168
+ }, command && crossEnvPrefixFix(command));
141
169
  const valueContext = doesPrefixCommand && !isBashSpecific ? {
142
170
  ...context,
143
- crossEnv: true
171
+ crossEnv: "arguments"
144
172
  } : context;
145
- (value.type === "ArrayValue" ? value.elements : [value]).forEach((word) => {
173
+ if (value.type === "ArrayValue") value.elements.forEach((word) => {
146
174
  this.checkWord(word, valueContext);
147
175
  });
176
+ else this.checkWord(value, valueContext, { skipGlobs: true });
177
+ }
178
+ /**
179
+ * Checks an assignment that a declaration command receives, e.g. `A=1` in `export A=1`.
180
+ * @param assignment Assignment to check
181
+ * @param context Where the assignment is
182
+ */
183
+ checkDeclaredAssignment(assignment, context) {
184
+ this.#checkBashAssignment(assignment, context);
185
+ const { value } = assignment;
186
+ (value.type === "ArrayValue" ? value.elements : [value]).forEach((word) => {
187
+ this.checkWord(word, context, { declaredValue: value.type === "Word" });
188
+ });
189
+ }
190
+ /**
191
+ * Reports an assignment that only Bash supports, e.g. `A+=1` or `A=(1 2)`.
192
+ * @param assignment Assignment to check
193
+ * @param context Where the assignment is
194
+ * @returns Whether it's Bash-specific
195
+ */
196
+ #checkBashAssignment(assignment, context) {
197
+ const { append, index, value } = assignment;
198
+ const isBashSpecific = value.type === "ArrayValue" || index != null || append;
199
+ if (isBashSpecific) this.#reporter.reportSyntax(context, assignment, "bash", false, "unsupportedSyntax", {
200
+ suggestion: BASH_SUGGESTION,
201
+ syntax: `The Bash-specific ${index || value.type === "ArrayValue" ? "array" : "appending"} assignment \`${snippet(context, assignment)}\``
202
+ });
203
+ return isBashSpecific;
148
204
  }
149
205
  #checkBashVariable(name, node, context) {
150
206
  const kind = BASH_VARIABLES.get(name);
151
- if (kind) this.#reporter.reportSyntax(context, node, kind, true, "inconsistentBehavior", {
152
- reason: kind === "bash" ? "dash, the `sh` of Debian/Ubuntu, doesn't set it" : "only Bash 5 sets it, and macOS ships Bash 3.2",
207
+ if (!kind) return;
208
+ let reason = "only Bash 5 sets it, and macOS ships Bash 3.2";
209
+ if (context.portable) reason = "Yarn's shell doesn't set it, so the script fails";
210
+ else if (kind === "bash") reason = "dash, the `sh` of Debian/Ubuntu, doesn't set it";
211
+ this.#reporter.reportSyntax(context, node, kind, name === "RANDOM", "inconsistentBehavior", {
212
+ reason,
153
213
  suggestion: NODE_SCRIPT_SUGGESTION,
154
214
  syntax: `The Bash variable \`$${name}\``
155
215
  });
@@ -163,25 +223,38 @@ var WordChecker = class {
163
223
  */
164
224
  #checkPackageManagerVariable(name, node, context, text = `$${name}`) {
165
225
  if (this.#isMissingPackageManagerVariable(name)) this.#reporter.report(context, node, "inconsistentBehavior", {
166
- reason: `${this.#runnerTraits.label} doesn't set it`,
226
+ reason: `${this.#runnerTraits.get("label")} doesn't set it`,
167
227
  suggestion: NODE_SCRIPT_SUGGESTION,
168
228
  syntax: `The variable \`${text}\``
169
229
  }, PLATFORMS);
170
230
  }
171
231
  /**
172
- * Reports a variable that `cross-env` replaces with an empty string on Windows, e.g. `$PWD`.
232
+ * Reports a variable that `cross-env` replaces on Windows with a different value than POSIX
233
+ * shells use, e.g. `$PWD`, or `$A` in `cross-env A=1 node $A`.
173
234
  * @param name Name of the variable
174
235
  * @param node The variable expansion
175
236
  * @param context Where the expansion is
176
- * @returns The platforms that the report covers
237
+ * @returns The platforms that the reports cover
177
238
  */
178
239
  #checkCrossEnvVariable(name, node, context) {
179
- if (context.portable || !this.#isUnsetOnWindows(name)) return [];
180
- return this.#reporter.report(context, node, "inconsistentBehavior", {
240
+ if (context.portable) return [];
241
+ const syntax = `The variable \`${node.text}\``;
242
+ const isSetByCrossEnv = context.crossEnvVariables?.has(name);
243
+ const covered = isSetByCrossEnv ? this.#reporter.report(context, node, "inconsistentBehavior", {
244
+ reason: "POSIX shells expand it before `cross-env` sets it, so the command doesn't get the new value",
245
+ suggestion: "Use the value itself or a Node.js script instead.",
246
+ syntax
247
+ }, POSIX_PLATFORMS) : [];
248
+ if (!isSetByCrossEnv && this.#isUnsetOnWindows(name)) return this.#reporter.report(context, node, "inconsistentBehavior", {
181
249
  reason: "Windows doesn't set it, so `cross-env` replaces it with an empty string",
182
250
  suggestion: this.#variableSuggestion(name),
183
- syntax: `The variable \`${node.text}\``
251
+ syntax
184
252
  }, WINDOWS_PLATFORMS);
253
+ return context.crossEnv === "command" ? [...covered, ...this.#reporter.report(context, node, "inconsistentBehavior", {
254
+ reason: `\`cross-env\` replaces it with \`%${name}%\`, which isn't expanded without a shell`,
255
+ suggestion: "Use `cross-env-shell` or a Node.js script instead.",
256
+ syntax
257
+ }, WINDOWS_PLATFORMS)] : covered;
185
258
  }
186
259
  /**
187
260
  * Reports an unquoted carriage return, e.g. of a CRLF line break, which POSIX shells keep.
@@ -189,8 +262,9 @@ var WordChecker = class {
189
262
  * @param context Where the word is
190
263
  */
191
264
  #checkCarriageReturn(word, context) {
265
+ if (context.portable || !word.text.includes("\r")) return;
192
266
  const literal = word.parts ? word.parts.find((part) => part.type === "Literal" && part.text.includes("\r")) : word;
193
- if (!literal?.text.includes("\r") || context.portable) return;
267
+ if (!literal) return;
194
268
  const position = literal.pos + literal.text.indexOf("\r");
195
269
  this.#reporter.report(context, {
196
270
  end: position + 1,
@@ -208,51 +282,61 @@ var WordChecker = class {
208
282
  }]
209
283
  });
210
284
  }
211
- #checkEscapes(word, context) {
212
- const literals = word.parts ? word.parts.flatMap((part) => {
213
- if (part.type === "Literal") return {
214
- pattern: UNQUOTED_ESCAPE,
215
- text: part.text
216
- };
217
- return part.type === "DoubleQuoted" ? part.parts.flatMap((child) => child.type === "Literal" ? {
285
+ /**
286
+ * Reports escapes that cmd.exe doesn't remove, e.g. `\$`, and its own escape character `^`.
287
+ * @param word Word to check
288
+ * @param context Where the word is
289
+ * @param shouldCheckCaret Whether to check for `^`, which a nested script checks itself
290
+ */
291
+ #checkEscapes(word, context, shouldCheckCaret) {
292
+ const literals = word.parts ? word.parts.flatMap((part, index) => {
293
+ if (part.type === "Literal") {
294
+ const isBeforeQuote = word.parts?.[index + 1]?.type === "DoubleQuoted";
295
+ return {
296
+ pattern: UNQUOTED_ESCAPE,
297
+ text: isBeforeQuote ? `${part.text}"` : part.text
298
+ };
299
+ }
300
+ return part.type === "DoubleQuoted" ? part.parts.flatMap((child, childIndex) => child.type === "Literal" ? {
218
301
  pattern: QUOTED_ESCAPE,
219
- text: child.text
302
+ text: childIndex === part.parts.length - 1 ? `${child.text}"` : child.text
220
303
  } : []) : [];
221
304
  }) : [{
222
305
  pattern: UNQUOTED_ESCAPE,
223
306
  text: word.text
224
307
  }];
225
- const escape = literals.flatMap(({ pattern, text }) => text.match(pattern) || []).find((match) => !(context.crossEnv && CROSS_ENV_ESCAPE.test(match)));
308
+ const escape = literals.flatMap(({ pattern, text }) => [...text.match(pattern) || [], ...!context.crossEnv && text.match(BACKSLASH_RUN) || []]).find((match) => !(context.crossEnv && CROSS_ENV_ESCAPE.test(match)));
226
309
  if (escape != null) this.#reporter.reportSyntax(context, word, "posix", true, "inconsistentBehavior", {
227
310
  reason: "cmd.exe doesn't treat backslashes as escape characters, so it passes them on",
228
- suggestion: "Use escaped double quotes (`\\\"`) instead.",
311
+ suggestion: escape.startsWith("\\\\") ? "Use a single backslash in double quotes (e.g. `\"\\.\"`) instead." : "Use escaped double quotes (`\\\"`) instead.",
229
312
  syntax: `The backslash escape \`${escape}\``
230
313
  });
231
- if (literals.some(({ pattern, text }) => pattern === UNQUOTED_ESCAPE && text.includes("^"))) this.#reporter.reportSyntax(context, word, "posix", true, "inconsistentBehavior", {
314
+ if (shouldCheckCaret && literals.some(({ pattern, text }) => pattern === UNQUOTED_ESCAPE && text.includes("^"))) this.#reporter.reportSyntax(context, word, "posix", true, "inconsistentBehavior", {
232
315
  reason: "cmd.exe treats `^` as an escape character and removes it",
233
316
  suggestion: "Quote it with double quotes instead.",
234
- syntax: `The caret in \`${truncate(word.text)}\``
317
+ syntax: `The caret in \`${snippet(context, word)}\``
235
318
  }, isPlainWord(word) ? quoting(word, "Quote it with escaped double quotes.") : void 0);
236
319
  }
237
320
  #checkParameterExpansion(part, context) {
238
321
  const { index, operation, prefix } = part;
239
322
  const isBashSpecific = index != null || prefix === "!" || operation != null && operation.type !== "Default" && operation.type !== "Remove";
323
+ const hasPortableDefault = operation?.type === "Default" && (operation.operator === ":-" || operation.operator === ":+");
240
324
  const bashKind = operation?.type === "CaseModification" || operation?.type === "Transform" ? "bash4" : "bash";
241
325
  let covered;
242
326
  if (isBashSpecific) covered = this.#reporter.reportSyntax(context, part, bashKind, false, "unsupportedSyntax", {
243
327
  suggestion: NODE_SCRIPT_SUGGESTION,
244
- syntax: `The ${bashLabel(bashKind)} parameter expansion \`${truncate(part.text)}\``
328
+ syntax: `The ${bashLabel(bashKind)} parameter expansion \`${snippet(context, part)}\``
245
329
  });
246
330
  else if (operation == null && prefix == null && context.crossEnv) covered = this.#checkCrossEnvVariable(part.parameter, part, context);
247
331
  else {
248
- const isPortableSupported = prefix == null && (operation == null || operation.type === "Default" && (operation.operator === ":-" || operation.operator === ":+"));
332
+ const isPortableSupported = prefix == null && (operation == null || hasPortableDefault);
249
333
  covered = this.#reporter.reportSyntax(context, part, "posix", isPortableSupported, "unsupportedSyntax", {
250
334
  suggestion: context.crossEnv ? CROSS_ENV_VARIABLE_SUGGESTION : this.#variableSuggestion(part.parameter),
251
- syntax: `The variable expansion \`${truncate(part.text)}\``
335
+ syntax: `The variable expansion \`${snippet(context, part)}\``
252
336
  });
253
337
  }
254
338
  const nestedContext = withCovered(context, covered);
255
- this.#checkBashVariable(part.parameter, part, nestedContext);
339
+ if (!(hasPortableDefault && context.portable)) this.#checkBashVariable(part.parameter, part, nestedContext);
256
340
  this.#checkPackageManagerVariable(part.parameter, part, nestedContext);
257
341
  [index, ...operation ? parameterOperands(operation) : []].forEach((operand) => {
258
342
  if (operand) this.checkWord(operand, nestedContext, { skipGlobs: true });
@@ -274,17 +358,17 @@ var WordChecker = class {
274
358
  case "AnsiCQuoted":
275
359
  this.#reporter.reportSyntax(context, part, "bash", true, "unsupportedSyntax", {
276
360
  suggestion: BASH_SUGGESTION,
277
- syntax: `The Bash-specific ANSI-C quoted string \`${truncate(part.text)}\``
361
+ syntax: `The Bash-specific ANSI-C quoted string \`${snippet(context, part)}\``
278
362
  });
279
363
  break;
280
364
  case "ArithmeticExpansion": {
281
365
  const covered = this.#reporter.reportSyntax(context, part, "posix", true, "unsupportedSyntax", {
282
366
  suggestion: NODE_SCRIPT_SUGGESTION,
283
- syntax: `The arithmetic expansion \`${truncate(part.text)}\``
367
+ syntax: `The arithmetic expansion \`${snippet(context, part)}\``
284
368
  });
285
369
  if (hasBashArithmetic(part.expression)) this.#reporter.reportSyntax(withCovered(context, covered), part, "bash", true, "unsupportedSyntax", {
286
370
  suggestion: NODE_SCRIPT_SUGGESTION,
287
- syntax: `The Bash-specific arithmetic in \`${truncate(part.text)}\``
371
+ syntax: `The Bash-specific arithmetic in \`${snippet(context, part)}\``
288
372
  });
289
373
  break;
290
374
  }
@@ -294,7 +378,7 @@ var WordChecker = class {
294
378
  case "CommandExpansion": {
295
379
  const covered = this.#reporter.reportSyntax(context, part, "posix", !part.text.startsWith("`"), "unsupportedSyntax", {
296
380
  suggestion: NODE_SCRIPT_SUGGESTION,
297
- syntax: `The command substitution \`${truncate(part.text)}\``
381
+ syntax: `The command substitution \`${snippet(context, part)}\``
298
382
  });
299
383
  if (part.script && !part.script.errors?.length) this.#walkNestedScript(part.script, part, withCovered(context, covered));
300
384
  break;
@@ -305,8 +389,8 @@ var WordChecker = class {
305
389
  case "ExtendedGlob":
306
390
  if (context.bashOptions?.has("extglob")) break;
307
391
  this.#reporter.report(context, part, "unsupportedSyntax", {
308
- suggestion: "It requires Bash's `extglob` option; quote the pattern and let the tool expand it instead.",
309
- syntax: `The extended glob \`${truncate(part.text)}\``
392
+ suggestion: state.skipGlobs ? "It requires Bash's `extglob` option; use a Node.js script instead." : "It requires Bash's `extglob` option; quote the pattern and let the tool expand it instead.",
393
+ syntax: `The extended glob \`${snippet(context, part)}\``
310
394
  }, PLATFORMS);
311
395
  break;
312
396
  case "Glob":
@@ -315,7 +399,7 @@ var WordChecker = class {
315
399
  case "LocaleString":
316
400
  this.#reporter.reportSyntax(context, part, "bash", false, "unsupportedSyntax", {
317
401
  suggestion: BASH_SUGGESTION,
318
- syntax: `The Bash-specific locale string \`${truncate(part.text)}\``
402
+ syntax: `The Bash-specific locale string \`${snippet(context, part)}\``
319
403
  });
320
404
  this.#checkParts(part.parts, context, state);
321
405
  break;
@@ -325,7 +409,7 @@ var WordChecker = class {
325
409
  case "ProcessSubstitution": {
326
410
  const covered = this.#reporter.reportSyntax(context, part, "bashNonPosix", false, "unsupportedSyntax", {
327
411
  suggestion: "Use a temporary file or a Node.js script instead.",
328
- syntax: `The Bash-specific process substitution \`${truncate(part.text)}\``
412
+ syntax: `The Bash-specific process substitution \`${snippet(context, part)}\``
329
413
  });
330
414
  if (part.script && !part.script.errors?.length) this.#walkNestedScript(part.script, part, withCovered(context, covered));
331
415
  break;
@@ -341,24 +425,49 @@ var WordChecker = class {
341
425
  this.#checkPackageManagerVariable(name, part, nestedContext);
342
426
  break;
343
427
  }
344
- case "SingleQuoted":
428
+ case "SingleQuoted": {
345
429
  state.hasSingleQuotes = true;
346
- if (state.printedToTerminal || context.crossEnv && !CMD_SPECIAL_CHARACTERS.test(part.value)) break;
347
- this.#reporter.reportSyntax(context, part, "posix", true, "inconsistentBehavior", {
348
- reason: context.crossEnv ? "cmd.exe doesn't treat single quotes as quotes, so it splits the string before `cross-env` removes them" : "cmd.exe doesn't treat single quotes as quotes, so they're passed on literally",
349
- suggestion: "Use escaped double quotes (`\\\"`) instead.",
350
- syntax: `The single-quoted string \`${truncate(part.text)}\``
351
- }, state.command === "echo" || DOUBLE_QUOTED_SPECIAL_CHARACTERS.test(part.value) ? void 0 : {
430
+ const suggestion = "Use escaped double quotes (`\\\"`) instead.";
431
+ const syntax = `The single-quoted string \`${snippet(context, part)}\``;
432
+ const fix = state.command === "echo" || DOUBLE_QUOTED_SPECIAL_CHARACTERS.test(part.value) || WINDOWS_VARIABLE.test(part.value) ? void 0 : {
352
433
  description: "Use escaped double quotes instead.",
353
434
  edits: [{
354
435
  end: part.end,
355
436
  pos: part.pos,
356
437
  text: `"${part.value}"`
357
438
  }]
358
- });
439
+ };
440
+ if (context.crossEnv === "script") {
441
+ if (SHELL_SPECIAL_CHARACTERS.test(part.value) || !state.printedToTerminal && WHITESPACE.test(part.value)) this.#reporter.report(context, part, "inconsistentBehavior", {
442
+ reason: "`cross-env-shell` removes single quotes before the shell runs the script, so the string isn't quoted",
443
+ suggestion,
444
+ syntax
445
+ }, PLATFORMS, fix);
446
+ break;
447
+ }
448
+ if (state.printedToTerminal && !CMD_OPERATORS.test(part.value) || context.crossEnv && !CMD_SPECIAL_CHARACTERS.test(part.value)) break;
449
+ this.#reporter.reportSyntax(context, part, "posix", true, "inconsistentBehavior", {
450
+ reason: state.printedToTerminal ? "cmd.exe doesn't treat single quotes as quotes, so it runs the operators in the string" : context.crossEnv ? "cmd.exe doesn't treat single quotes as quotes, so it splits the string before `cross-env` removes them" : "cmd.exe doesn't treat single quotes as quotes, so they're passed on literally",
451
+ suggestion,
452
+ syntax
453
+ }, fix);
454
+ break;
455
+ }
359
456
  }
360
457
  }
361
458
  /**
459
+ * Reports a brace expansion in the target of a redirection, e.g. in `> out.{log,txt}`.
460
+ * @param part The brace expansion
461
+ * @param context Where the redirection is
462
+ */
463
+ #checkRedirectionBraces(part, context) {
464
+ if (!context.portable) this.#reporter.report(context, part, "inconsistentBehavior", {
465
+ reason: "Bash (the `sh` of macOS) expands it into several file names, which is an error",
466
+ suggestion: "Use a single file name instead.",
467
+ syntax: `The brace expansion \`${snippet(context, part)}\` in a redirection`
468
+ }, context.shell === "bash" ? PLATFORMS : MACOS_PLATFORMS);
469
+ }
470
+ /**
362
471
  * Reports device paths like `/dev/null`, which don't exist on Windows.
363
472
  * @param word Word that contains the path
364
473
  * @param value Static value of the word
@@ -373,67 +482,87 @@ var WordChecker = class {
373
482
  }
374
483
  checkWord(word, context, options = {}) {
375
484
  const { text } = word;
376
- this.#checkCarriageReturn(word, context);
377
- if (TILDE_EXPANSION.test(text)) this.#reporter.reportSyntax(context, word, "posix", false, "unsupportedSyntax", {
485
+ const shouldCheckText = !options.nestedScript;
486
+ if (shouldCheckText) this.#checkCarriageReturn(word, context);
487
+ if (shouldCheckText && TILDE_EXPANSION.test(text)) this.#reporter.reportSyntax(context, word, "posix", false, "unsupportedSyntax", {
378
488
  suggestion: "Use a path relative to the package or a Node.js script instead.",
379
- syntax: `The tilde expansion \`${truncate(text)}\``
489
+ syntax: `The tilde expansion \`${snippet(context, word)}\``
380
490
  });
381
491
  const state = {
382
492
  braceExpansions: [],
383
493
  command: options.command,
384
494
  globPosition: void 0,
385
495
  hasSingleQuotes: false,
386
- printedToTerminal: options.printedToTerminal || false
496
+ printedToTerminal: options.printedToTerminal || false,
497
+ skipGlobs: options.skipGlobs || false
387
498
  };
388
- this.#checkParts(word.parts || [], context, state);
499
+ if (word.parts) this.#checkParts(word.parts, context, state);
389
500
  const { globPosition } = state;
390
501
  const hasGlob = globPosition != null;
391
502
  const globPrefix = hasGlob ? text.slice(0, globPosition - word.pos) : "";
392
503
  const isLiteralPattern = globPrefix.startsWith("-") || globPrefix.includes("=");
393
- if (hasGlob && !isLiteralPattern && RECURSIVE_GLOB.test(text) && !context.portable && !context.bashOptions?.has("globstar") && !options.commandName && !options.redirectTarget && !options.skipGlobs) this.#reporter.report(context, word, "inconsistentBehavior", {
504
+ if (shouldCheckText && hasGlob && !isLiteralPattern && RECURSIVE_GLOB.test(text) && !context.portable && !context.bashOptions?.has("globstar") && !options.commandName && !options.redirectTarget && !options.skipGlobs) this.#reporter.report(context, word, "inconsistentBehavior", {
394
505
  reason: "`sh` doesn't support recursive `**` globs, and cmd.exe doesn't expand globs at all",
395
506
  suggestion: "Quote it with escaped double quotes (`\\\"`) and let the tool expand it instead.",
396
- syntax: `The unquoted glob \`${truncate(text)}\``
397
- }, PLATFORMS, isTool(options.command) && isPlainWord(word, GLOB_PART_TYPES) ? quoting(word, "Quote it with escaped double quotes.") : void 0);
398
- if (!hasGlob && (options.command == null || OS_COMMANDS.has(options.command))) state.braceExpansions.forEach((part) => {
399
- this.#reporter.reportSyntax(context, part, "bash", true, "unsupportedSyntax", {
400
- suggestion: "List the alternatives explicitly instead.",
401
- syntax: `The Bash-specific brace expansion \`${truncate(part.text)}\``
402
- }, braceExpansionFix(word, part));
507
+ syntax: `The unquoted glob \`${snippet(context, word)}\``
508
+ }, PLATFORMS, isTool(options.command) && !setHas(NON_GLOB_PROGRAMS, options.command) && isPlainWord(word, GLOB_PART_TYPES) ? quoting(word, "Quote it with escaped double quotes.") : void 0);
509
+ if (!options.skipGlobs && (options.command == null || OS_COMMANDS.has(options.command)) && (!hasGlob || options.command != null && !context.portable)) state.braceExpansions.forEach((part) => {
510
+ if (options.redirectTarget) {
511
+ this.#checkRedirectionBraces(part, context);
512
+ return;
513
+ }
514
+ const suggestion = "List the alternatives explicitly instead.";
515
+ const fix = options.declaredValue ? void 0 : braceExpansionFix(word, part);
516
+ if (context.portable) this.#reporter.report(context, part, "inconsistentBehavior", {
517
+ reason: "Yarn's shell only expands it to the names of files that exist",
518
+ suggestion,
519
+ syntax: `The brace expansion \`${snippet(context, part)}\``
520
+ }, PLATFORMS, fix);
521
+ else this.#reporter.reportSyntax(context, part, "bash", true, "unsupportedSyntax", {
522
+ suggestion,
523
+ syntax: `The Bash-specific brace expansion \`${snippet(context, part)}\``
524
+ }, fix);
403
525
  });
404
- const isPattern = setHas(PATTERN_COMMANDS, options.command);
405
- const unquoted = text.replaceAll("\"", "");
406
- const path = substringAfterLast(unquoted, "=");
407
- if (!isPattern && !state.hasSingleQuotes && BACKSLASH_PATH.test(path) && (WINDOWS_PATH_PREFIX.test(path) || FILE_EXTENSION.test(path) || MULTIPLE_BACKSLASHES.test(path)) && NON_DOT_ESCAPE.test(path)) this.#reporter.report(context, word, "inconsistentBehavior", {
408
- reason: "POSIX shells treat backslashes as escape characters",
409
- suggestion: "Use forward slashes instead.",
410
- syntax: `The backslash path separator in \`${truncate(path)}\``
411
- }, context.portable && !text.startsWith("\"") ? PLATFORMS : POSIX_PLATFORMS, options.commandName || options.redirectTarget || !isTool(options.command) ? void 0 : replacement(word, text, `${text.slice(0, text.lastIndexOf("=") + 1)}${toForwardSlashes(substringAfterLast(text, "="))}`));
412
- if (!BACKSLASH_PATH.test(path) && !WINDOWS_PATH_PREFIX.test(path)) this.#checkEscapes(word, context);
413
- if (!state.hasSingleQuotes && options.command !== "date" && options.command !== "printf") {
414
- const match = WINDOWS_VARIABLE.exec(text);
415
- if (match && !text.replaceAll(WINDOWS_VARIABLES, "").includes("%")) {
526
+ const hasBackslash = text.includes("\\");
527
+ const path = hasBackslash ? substringAfterLast(text.replaceAll("\"", ""), "=") : "";
528
+ const isBackslashPath = hasBackslash && BACKSLASH_PATH.test(path);
529
+ const hasPrefix = isBackslashPath && WINDOWS_PATH_PREFIX.test(path);
530
+ const hasExtension = isBackslashPath && FILE_EXTENSION.test(path);
531
+ if (isBackslashPath && shouldCheckText && !options.text && !setHas(PATTERN_COMMANDS, options.command) && !state.hasSingleQuotes && (hasPrefix || hasExtension || MULTIPLE_BACKSLASHES.test(path)) && NON_DOT_ESCAPE.test(path)) {
532
+ const isLikelyRegex = !hasPrefix && !hasExtension && !NON_REGEX_ESCAPE.test(path);
533
+ this.#reporter.report(context, word, "inconsistentBehavior", {
534
+ reason: "POSIX shells treat backslashes as escape characters",
535
+ suggestion: "Use forward slashes instead.",
536
+ syntax: `The backslash path separator in \`${truncate(path)}\``
537
+ }, context.portable && !text.startsWith("\"") ? PLATFORMS : POSIX_PLATFORMS, isLikelyRegex || options.commandName || options.redirectTarget || !isTool(options.command) ? void 0 : backslashPathFix(word, originalText(context, word), path === text && RECURSIVE_GLOB.test(toForwardSlashes(path)) && !context.portable && !context.bashOptions?.has("globstar")));
538
+ }
539
+ if (!(isBackslashPath || hasBackslash && WINDOWS_PATH_PREFIX.test(path)) && (hasBackslash || text.includes("^"))) this.#checkEscapes(word, context, shouldCheckText);
540
+ if (shouldCheckText && !state.hasSingleQuotes && options.command !== "date" && options.command !== "printf") {
541
+ const unencodedText = text.replaceAll(PERCENT_ENCODED_BYTES, "");
542
+ const match = WINDOWS_VARIABLE.exec(unencodedText);
543
+ if (match && !unencodedText.replaceAll(WINDOWS_VARIABLES, "").includes("%")) {
416
544
  const covered = this.#reporter.report(context, word, "unsupportedSyntax", {
417
545
  suggestion: VARIABLE_SUGGESTION,
418
546
  syntax: `The Windows variable reference \`${match[0]}\``
419
547
  }, context.portable ? PLATFORMS : POSIX_PLATFORMS);
420
548
  const nestedContext = withCovered(context, covered);
421
- text.matchAll(WINDOWS_VARIABLES).forEach(([reference]) => {
549
+ unencodedText.matchAll(WINDOWS_VARIABLES).forEach(([reference]) => {
422
550
  this.#checkPackageManagerVariable(reference.slice(1, -1), word, nestedContext, reference);
423
551
  });
424
552
  }
425
553
  }
426
554
  const value = staticValue(word);
427
- if (value != null && !options.commandName && !options.redirectTarget) this.checkPosixPath(word, value, context);
555
+ if (shouldCheckText && value != null && !options.commandName && !options.redirectTarget) this.checkPosixPath(word, value, context);
428
556
  }
429
557
  /** Checks whether Windows doesn't set a variable, so `cross-env` replaces it with nothing */
430
558
  #isUnsetOnWindows(name) {
431
- return POSIX_ONLY_VARIABLES.has(name) || name === "HOME" && !this.#runnerTraits.setsHome;
559
+ return POSIX_ONLY_VARIABLES.has(name) || name === "HOME" && !this.#runnerTraits.get("setsHome");
432
560
  }
433
561
  /** Checks whether a variable is one that package managers set, but the runner doesn't */
434
562
  #isMissingPackageManagerVariable(name) {
435
- const variables = this.#runnerTraits.packageManagerVariables;
436
- return variables != null && PACKAGE_MANAGER_VARIABLE.test(name) && !variables.has(name);
563
+ if (!PACKAGE_MANAGER_VARIABLE.test(name)) return false;
564
+ const variables = this.#runnerTraits.get("packageManagerVariables");
565
+ return variables != null && !variables.has(name);
437
566
  }
438
567
  /** Gets what to use instead of a variable on Windows, where `cross-env` can't help for some */
439
568
  #variableSuggestion(name) {
@@ -441,4 +570,4 @@ var WordChecker = class {
441
570
  return this.#isUnsetOnWindows(name) || this.#isMissingPackageManagerVariable(name) ? NODE_SCRIPT_SUGGESTION : VARIABLE_SUGGESTION;
442
571
  }
443
572
  };
444
- export { WordChecker };
573
+ export { CMD_STATEMENTS, WordChecker };
package/dist/words.mjs CHANGED
@@ -9,8 +9,11 @@ const SHORT_OPTION_CLUSTER = /^-[a-z]+$/i;
9
9
  * @returns Whether the word includes the option
10
10
  */
11
11
  const isShortOptionCluster = (value, letter) => value != null && SHORT_OPTION_CLUSTER.test(value) && value.includes(letter);
12
- /** A tilde expansion at the start of a word, e.g. `~/.npmrc` */
13
- const TILDE_EXPANSION = /^~[\w\-.]*(?:\/|$)/;
12
+ /**
13
+ * A tilde expansion at the start of a word, e.g. `~/.npmrc`.
14
+ * With a digit after `~`, it's a version range, e.g. `~1.2.3`, which shells keep as it is
15
+ */
16
+ const TILDE_EXPANSION = /^~(?!\d)[\w\-.]*(?:\/|$)/;
14
17
  /** Characters that POSIX shells interpret in double quotes, e.g. `$` */
15
18
  const DOUBLE_QUOTED_SPECIAL_CHARACTERS = /["$\\`]/;
16
19
  const WHITESPACE = /\s/;
@@ -21,11 +24,29 @@ const GLOB_PART_TYPES = [
21
24
  ];
22
25
  const isStatic = (parts) => parts.every((part) => part.type === "Literal" || part.type === "SingleQuoted" || part.type === "AnsiCQuoted" || part.type === "Glob" || part.type === "DoubleQuoted" && isStatic(part.parts));
23
26
  /**
27
+ * Gets the text that a command receives for a word, e.g. a script for `sh -c`.
28
+ * The outer shell's expansions are replaced by placeholders of the same length.
29
+ * @param parts The word's parts
30
+ * @param shouldKeepExpansions Whether to keep the expansions' text instead, e.g. for reports
31
+ * @returns The text
32
+ */
33
+ const nestedSource = (parts, shouldKeepExpansions = false) => parts.map((part) => {
34
+ switch (part.type) {
35
+ case "AnsiCQuoted":
36
+ case "Glob":
37
+ case "Literal":
38
+ case "SingleQuoted": return part.value;
39
+ case "DoubleQuoted":
40
+ case "LocaleString": return nestedSource(part.parts, shouldKeepExpansions);
41
+ default: return shouldKeepExpansions ? part.text : "￿".repeat(part.text.length);
42
+ }
43
+ }).join("");
44
+ /**
24
45
  * Gets the value of a word, if it doesn't depend on expansions.
25
46
  * @param word A word from the parsed script
26
47
  * @returns The value, or `undefined` if it's dynamic
27
48
  */
28
- const staticValue = (word) => word.parts == null || isStatic(word.parts) ? word.value : void 0;
49
+ const staticValue = (word) => (word.parts == null || isStatic(word.parts)) && !word.value.includes("￿") ? word.value : void 0;
29
50
  /**
30
51
  * Checks whether a word is unquoted text without escapes or expansions, e.g. `dist/*.js`.
31
52
  * Double quotes don't change the value of such a word.
@@ -33,11 +54,17 @@ const staticValue = (word) => word.parts == null || isStatic(word.parts) ? word.
33
54
  * @param partTypes Types of parts that are allowed besides literal text, e.g. globs
34
55
  * @returns Whether the word is plain
35
56
  */
36
- const isPlainWord = (word, partTypes = []) => !DOUBLE_QUOTED_SPECIAL_CHARACTERS.test(word.text) && !TILDE_EXPANSION.test(word.text) && (word.parts || []).every((part) => part.type === "Literal" || partTypes.includes(part.type));
57
+ const isPlainWord = (word, partTypes = []) => !DOUBLE_QUOTED_SPECIAL_CHARACTERS.test(word.text) && !word.text.includes("￿") && !TILDE_EXPANSION.test(word.text) && (word.parts || []).every((part) => part.type === "Literal" || partTypes.includes(part.type));
37
58
  const isPlainAssignment = (item) => item.type === "Assignment" && item.value.type === "Word" && item.index == null && !item.append;
59
+ /** A word of letters, digits and underscores, e.g. a variable name */
60
+ const IDENTIFIER = /\w+/g;
38
61
  /**
39
- * Device paths, e.g. `/dev/null`.
40
- * Unlike other absolute paths, they are rarely meant for containers or remote hosts
62
+ * Checks whether a piece of a script mentions any of some variables, e.g. `$PORT` for `PORT`.
63
+ * @param text The piece of the script
64
+ * @param names Names of the variables
65
+ * @returns Whether it does, even if only as a word that the shell doesn't expand
41
66
  */
67
+ const doesMentionVariables = (text, names) => (text.match(IDENTIFIER) || []).some((word) => names.has(word));
68
+ /** Device paths, e.g. `/dev/null` */
42
69
  const POSIX_PATH = /(?:^|=)\/dev\//;
43
- export { ASSIGNMENT, DOUBLE_QUOTED_SPECIAL_CHARACTERS, GLOB_PART_TYPES, POSIX_PATH, TILDE_EXPANSION, WHITESPACE, isPlainAssignment, isPlainWord, isShortOptionCluster, staticValue };
70
+ export { ASSIGNMENT, DOUBLE_QUOTED_SPECIAL_CHARACTERS, GLOB_PART_TYPES, POSIX_PATH, TILDE_EXPANSION, WHITESPACE, doesMentionVariables, isPlainAssignment, isPlainWord, isShortOptionCluster, nestedSource, staticValue };