package-json-scripts-portability 0.0.0 → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/LICENSE.md +21 -0
  2. package/README.md +235 -45
  3. package/dist/analyze-script.d.mts +34 -0
  4. package/dist/analyze-script.mjs +48 -0
  5. package/dist/command-checker.mjs +295 -0
  6. package/dist/command-usage.mjs +364 -0
  7. package/dist/commands.mjs +520 -0
  8. package/dist/context.mjs +18 -0
  9. package/dist/fixes.d.mts +9 -0
  10. package/dist/fixes.mjs +210 -0
  11. package/dist/index.d.mts +6 -0
  12. package/dist/index.mjs +5 -0
  13. package/dist/line-break-checker.mjs +71 -0
  14. package/dist/messages.mjs +30 -0
  15. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/array/array-difference.mjs +11 -0
  16. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/array/array-includes.mjs +8 -0
  17. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/array/array-intersection.mjs +13 -0
  18. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/array/array-is-subset.mjs +16 -0
  19. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/array/arrayify.mjs +7 -0
  20. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/iterable/sliding-window.mjs +30 -0
  21. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/map/map-get-or-insert-computed.mjs +42 -0
  22. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/map/map-get-or-insert.mjs +40 -0
  23. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/math/clamp.mjs +7 -0
  24. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/path/to-forward-slashes.mjs +8 -0
  25. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/predicate/is-array.mjs +39 -0
  26. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/set/set-has.mjs +8 -0
  27. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/string/substring-after-last.mjs +24 -0
  28. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/string/substring-before.mjs +24 -0
  29. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/string/truncate.mjs +46 -0
  30. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/ts/all-union-members.mjs +45 -0
  31. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/types/maybe-readonly-array.d.mts +17 -0
  32. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/value/is-equal.mjs +37 -0
  33. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/@antfu/utils/dist/index.mjs +5 -0
  34. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/_internal/globalThis.mjs +5 -0
  35. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/array/differenceBy.mjs +40 -0
  36. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/array/differenceWith.mjs +37 -0
  37. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/array/intersectionWith.mjs +43 -0
  38. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/array/isSubsetWith.mjs +36 -0
  39. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/bigint/clamp.mjs +15 -0
  40. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/compat/_internal/getSymbols.mjs +5 -0
  41. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/compat/_internal/getTag.mjs +13 -0
  42. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/compat/_internal/regexMultiByte.mjs +10 -0
  43. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/compat/_internal/tags.mjs +27 -0
  44. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/compat/predicate/isObject.mjs +28 -0
  45. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/compat/string/truncate.mjs +78 -0
  46. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/compat/util/eq.mjs +18 -0
  47. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/function/noop.mjs +12 -0
  48. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/math/clamp.mjs +23 -0
  49. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/predicate/isBuffer.mjs +24 -0
  50. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/predicate/isEqual.mjs +21 -0
  51. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/predicate/isEqualWith.mjs +151 -0
  52. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/es-toolkit/dist/predicate/isPlainObject.mjs +50 -0
  53. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/remeda/dist/isArray.mjs +18 -0
  54. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/ts-extras/distribution/array-includes.mjs +5 -0
  55. package/dist/node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/vendor/ts-extras/distribution/set-has.mjs +5 -0
  56. package/dist/platforms.d.mts +8 -0
  57. package/dist/platforms.mjs +26 -0
  58. package/dist/redirection-checker.mjs +117 -0
  59. package/dist/reporter.d.mts +32 -0
  60. package/dist/reporter.mjs +98 -0
  61. package/dist/runners.d.mts +24 -0
  62. package/dist/runners.mjs +118 -0
  63. package/dist/script-analyzer.mjs +551 -0
  64. package/dist/word-checker.mjs +444 -0
  65. package/dist/words.mjs +43 -0
  66. package/package.json +118 -6
@@ -0,0 +1,444 @@
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";
6
+ import { setHas } from "./node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/set/set-has.mjs";
7
+ import { substringAfterLast } from "./node_modules/.pnpm/utilery@0.4.0/node_modules/utilery/dist/string/substring-after-last.mjs";
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";
10
+ // src/word-checker.ts
11
+ /** Variables that Bash sets, but dash doesn't, by the kind of syntax they are */
12
+ const BASH_VARIABLES = /* @__PURE__ */ new Map([
13
+ ["BASH_SOURCE", "bash"],
14
+ ["BASH_VERSION", "bash"],
15
+ ["EPOCHREALTIME", "bash4"],
16
+ ["EPOCHSECONDS", "bash4"],
17
+ ["EUID", "bash"],
18
+ ["HOSTNAME", "bash"],
19
+ ["OSTYPE", "bash"],
20
+ ["PIPESTATUS", "bash"],
21
+ ["RANDOM", "bash"],
22
+ ["SECONDS", "bash"],
23
+ ["SRANDOM", "bash4"],
24
+ ["UID", "bash"]
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
+ */
32
+ const POSIX_ONLY_VARIABLES = /* @__PURE__ */ new Set([
33
+ ...BASH_VARIABLES.keys(),
34
+ "LOGNAME",
35
+ "OLDPWD",
36
+ "PPID",
37
+ "PWD",
38
+ "SHELL",
39
+ "TMPDIR",
40
+ "USER"
41
+ ]);
42
+ /** Variables that package managers set, e.g. `npm_package_version` */
43
+ const PACKAGE_MANAGER_VARIABLE = /^(?:npm_\w+|INIT_CWD)$/;
44
+ /** cmd.exe statements, which POSIX shells parse as commands, e.g. `IF` in `IF EXIST dist ...` */
45
+ const CMD_STATEMENTS = /* @__PURE__ */ new Set(["for", "if"]);
46
+ /** Characters that cmd.exe splits words at or interprets */
47
+ const CMD_SPECIAL_CHARACTERS = /[\s"%&<>^|]/;
48
+ /** Backslash escapes that POSIX shells remove, but cmd.exe passes on, e.g. `\$` or `\ ` */
49
+ const UNQUOTED_ESCAPE = /\\[\t !#$&'()*;<>?[\]`{|}~]/g;
50
+ /** The same, in double quotes */
51
+ const QUOTED_ESCAPE = /\\[$`]/g;
52
+ /** `cross-env` removes the backslashes of these escapes itself */
53
+ const CROSS_ENV_ESCAPE = /^\\[$']$/;
54
+ /** A named variable, e.g. `$HOME` rather than `$?` */
55
+ const NAMED_VARIABLE = /^\$\w+$/;
56
+ /** A `**` path segment, which `sh` doesn't expand recursively */
57
+ const RECURSIVE_GLOB = /(?:^|[/=])\*\*\//;
58
+ const WINDOWS_VARIABLE = /%[a-z_]\w+%/i;
59
+ const WINDOWS_VARIABLES = new RegExp(WINDOWS_VARIABLE, "gi");
60
+ /**
61
+ * A Windows path: a drive, relative prefix or first segment, then `\`-separated segments.
62
+ * The segments may be globs, e.g. `lib\**\*.js`
63
+ */
64
+ const BACKSLASH_PATH = /^(?:[a-z]:|[\w\-.]+|\*\*?(?:\.[\w-]+)*)(?:\\(?:[\w\-.]+|\*\*?(?:\.[\w-]+)*))+\\?$/i;
65
+ /** A Windows path's drive or relative prefix, e.g. `C:\` or `.\` */
66
+ const WINDOWS_PATH_PREFIX = /^(?:[a-z]:|\.{1,2})\\/i;
67
+ const FILE_EXTENSION = /\.\w+$/;
68
+ const MULTIPLE_BACKSLASHES = /\\.*\\/;
69
+ /** Backslashes that only escape dots are likely a regex, e.g. `logging\.spec\.ts` */
70
+ const NON_DOT_ESCAPE = /\\[^.]/;
71
+ const hasBashArithmetic = (expression) => {
72
+ switch (expression?.type) {
73
+ case "ArithmeticBinary": return expression.operator.startsWith("**") || hasBashArithmetic(expression.left) || hasBashArithmetic(expression.right);
74
+ case "ArithmeticGroup": return hasBashArithmetic(expression.expression);
75
+ case "ArithmeticTernary": return [
76
+ expression.test,
77
+ expression.consequent,
78
+ expression.alternate
79
+ ].some(hasBashArithmetic);
80
+ case "ArithmeticUnary": return expression.operator === "++" || expression.operator === "--" || hasBashArithmetic(expression.operand);
81
+ default: return false;
82
+ }
83
+ };
84
+ const parameterOperands = (operation) => {
85
+ switch (operation.type) {
86
+ case "CaseModification":
87
+ case "Default":
88
+ case "Remove":
89
+ case "Transform": return [operation.operand];
90
+ case "Replace": return [operation.pattern, operation.replacement];
91
+ case "Slice": return [operation.offset, operation.length];
92
+ default: return [];
93
+ }
94
+ };
95
+ /**
96
+ * Checks whether a command is likely a tool, e.g. `eslint`, and not an OS utility or a cmd.exe
97
+ * command.
98
+ * Tools usually expand globs themselves and accept `/` as a path separator.
99
+ * @param command Name of the command that receives the arguments
100
+ * @returns Whether the command is likely a tool
101
+ */
102
+ const isTool = (command) => {
103
+ const name = command?.toLowerCase();
104
+ return name != null && !OS_COMMANDS.has(name) && !CMD_STATEMENTS.has(name);
105
+ };
106
+ /** Checks words, e.g. for quotes, expansions and paths */
107
+ var WordChecker = class {
108
+ #reporter;
109
+ #runnerTraits;
110
+ #walkNestedScript;
111
+ constructor(reporter, walkNestedScript, runnerTraits) {
112
+ this.#reporter = reporter;
113
+ this.#walkNestedScript = walkNestedScript;
114
+ this.#runnerTraits = runnerTraits;
115
+ }
116
+ /**
117
+ * Checks a variable assignment.
118
+ * @param assignment Assignment to check, e.g. `CI=1`
119
+ * @param context Where the assignment is
120
+ * @param command The command that the assignment prefixes, e.g. `jest` in `CI=1 jest`
121
+ */
122
+ checkAssignment(assignment, context, command) {
123
+ const { append, index, value } = assignment;
124
+ const isBashSpecific = value.type === "ArrayValue" || index != null || append;
125
+ 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", {
131
+ 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);
141
+ const valueContext = doesPrefixCommand && !isBashSpecific ? {
142
+ ...context,
143
+ crossEnv: true
144
+ } : context;
145
+ (value.type === "ArrayValue" ? value.elements : [value]).forEach((word) => {
146
+ this.checkWord(word, valueContext);
147
+ });
148
+ }
149
+ #checkBashVariable(name, node, context) {
150
+ 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",
153
+ suggestion: NODE_SCRIPT_SUGGESTION,
154
+ syntax: `The Bash variable \`$${name}\``
155
+ });
156
+ }
157
+ /**
158
+ * Reports a variable that package managers set, but the runner doesn't, e.g. `node --run`.
159
+ * @param name Name of the variable, e.g. `npm_package_version`
160
+ * @param node The node to report
161
+ * @param context Where the variable is
162
+ * @param text How the script refers to the variable, e.g. `%npm_package_version%`
163
+ */
164
+ #checkPackageManagerVariable(name, node, context, text = `$${name}`) {
165
+ if (this.#isMissingPackageManagerVariable(name)) this.#reporter.report(context, node, "inconsistentBehavior", {
166
+ reason: `${this.#runnerTraits.label} doesn't set it`,
167
+ suggestion: NODE_SCRIPT_SUGGESTION,
168
+ syntax: `The variable \`${text}\``
169
+ }, PLATFORMS);
170
+ }
171
+ /**
172
+ * Reports a variable that `cross-env` replaces with an empty string on Windows, e.g. `$PWD`.
173
+ * @param name Name of the variable
174
+ * @param node The variable expansion
175
+ * @param context Where the expansion is
176
+ * @returns The platforms that the report covers
177
+ */
178
+ #checkCrossEnvVariable(name, node, context) {
179
+ if (context.portable || !this.#isUnsetOnWindows(name)) return [];
180
+ return this.#reporter.report(context, node, "inconsistentBehavior", {
181
+ reason: "Windows doesn't set it, so `cross-env` replaces it with an empty string",
182
+ suggestion: this.#variableSuggestion(name),
183
+ syntax: `The variable \`${node.text}\``
184
+ }, WINDOWS_PLATFORMS);
185
+ }
186
+ /**
187
+ * Reports an unquoted carriage return, e.g. of a CRLF line break, which POSIX shells keep.
188
+ * @param word Word to check, e.g. `tsc` and a carriage return before a line break
189
+ * @param context Where the word is
190
+ */
191
+ #checkCarriageReturn(word, context) {
192
+ 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;
194
+ const position = literal.pos + literal.text.indexOf("\r");
195
+ this.#reporter.report(context, {
196
+ end: position + 1,
197
+ pos: position
198
+ }, "inconsistentBehavior", {
199
+ reason: "POSIX shells treat it as part of the word, e.g. of a command's name",
200
+ suggestion: "Use line feeds (`\\n`) for line breaks instead.",
201
+ syntax: "The carriage return (`\\r`)"
202
+ }, POSIX_PLATFORMS, {
203
+ description: "Remove the carriage return.",
204
+ edits: [{
205
+ end: position + 1,
206
+ pos: position,
207
+ text: ""
208
+ }]
209
+ });
210
+ }
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" ? {
218
+ pattern: QUOTED_ESCAPE,
219
+ text: child.text
220
+ } : []) : [];
221
+ }) : [{
222
+ pattern: UNQUOTED_ESCAPE,
223
+ text: word.text
224
+ }];
225
+ const escape = literals.flatMap(({ pattern, text }) => text.match(pattern) || []).find((match) => !(context.crossEnv && CROSS_ENV_ESCAPE.test(match)));
226
+ if (escape != null) this.#reporter.reportSyntax(context, word, "posix", true, "inconsistentBehavior", {
227
+ reason: "cmd.exe doesn't treat backslashes as escape characters, so it passes them on",
228
+ suggestion: "Use escaped double quotes (`\\\"`) instead.",
229
+ syntax: `The backslash escape \`${escape}\``
230
+ });
231
+ if (literals.some(({ pattern, text }) => pattern === UNQUOTED_ESCAPE && text.includes("^"))) this.#reporter.reportSyntax(context, word, "posix", true, "inconsistentBehavior", {
232
+ reason: "cmd.exe treats `^` as an escape character and removes it",
233
+ suggestion: "Quote it with double quotes instead.",
234
+ syntax: `The caret in \`${truncate(word.text)}\``
235
+ }, isPlainWord(word) ? quoting(word, "Quote it with escaped double quotes.") : void 0);
236
+ }
237
+ #checkParameterExpansion(part, context) {
238
+ const { index, operation, prefix } = part;
239
+ const isBashSpecific = index != null || prefix === "!" || operation != null && operation.type !== "Default" && operation.type !== "Remove";
240
+ const bashKind = operation?.type === "CaseModification" || operation?.type === "Transform" ? "bash4" : "bash";
241
+ let covered;
242
+ if (isBashSpecific) covered = this.#reporter.reportSyntax(context, part, bashKind, false, "unsupportedSyntax", {
243
+ suggestion: NODE_SCRIPT_SUGGESTION,
244
+ syntax: `The ${bashLabel(bashKind)} parameter expansion \`${truncate(part.text)}\``
245
+ });
246
+ else if (operation == null && prefix == null && context.crossEnv) covered = this.#checkCrossEnvVariable(part.parameter, part, context);
247
+ else {
248
+ const isPortableSupported = prefix == null && (operation == null || operation.type === "Default" && (operation.operator === ":-" || operation.operator === ":+"));
249
+ covered = this.#reporter.reportSyntax(context, part, "posix", isPortableSupported, "unsupportedSyntax", {
250
+ suggestion: context.crossEnv ? CROSS_ENV_VARIABLE_SUGGESTION : this.#variableSuggestion(part.parameter),
251
+ syntax: `The variable expansion \`${truncate(part.text)}\``
252
+ });
253
+ }
254
+ const nestedContext = withCovered(context, covered);
255
+ this.#checkBashVariable(part.parameter, part, nestedContext);
256
+ this.#checkPackageManagerVariable(part.parameter, part, nestedContext);
257
+ [index, ...operation ? parameterOperands(operation) : []].forEach((operand) => {
258
+ if (operand) this.checkWord(operand, nestedContext, { skipGlobs: true });
259
+ });
260
+ }
261
+ #checkParts(parts, context, state) {
262
+ parts.forEach((part) => {
263
+ this.#checkPart(part, context, state);
264
+ });
265
+ }
266
+ /**
267
+ * Checks a part of a word, e.g. a quoted string or an expansion.
268
+ * @param part Part to check, e.g. `$HOME` in `$HOME/.npmrc`
269
+ * @param context Where the word is
270
+ * @param state What the word contains, collected while checking its parts
271
+ */
272
+ #checkPart(part, context, state) {
273
+ switch (part.type) {
274
+ case "AnsiCQuoted":
275
+ this.#reporter.reportSyntax(context, part, "bash", true, "unsupportedSyntax", {
276
+ suggestion: BASH_SUGGESTION,
277
+ syntax: `The Bash-specific ANSI-C quoted string \`${truncate(part.text)}\``
278
+ });
279
+ break;
280
+ case "ArithmeticExpansion": {
281
+ const covered = this.#reporter.reportSyntax(context, part, "posix", true, "unsupportedSyntax", {
282
+ suggestion: NODE_SCRIPT_SUGGESTION,
283
+ syntax: `The arithmetic expansion \`${truncate(part.text)}\``
284
+ });
285
+ if (hasBashArithmetic(part.expression)) this.#reporter.reportSyntax(withCovered(context, covered), part, "bash", true, "unsupportedSyntax", {
286
+ suggestion: NODE_SCRIPT_SUGGESTION,
287
+ syntax: `The Bash-specific arithmetic in \`${truncate(part.text)}\``
288
+ });
289
+ break;
290
+ }
291
+ case "BraceExpansion":
292
+ state.braceExpansions.push(part);
293
+ break;
294
+ case "CommandExpansion": {
295
+ const covered = this.#reporter.reportSyntax(context, part, "posix", !part.text.startsWith("`"), "unsupportedSyntax", {
296
+ suggestion: NODE_SCRIPT_SUGGESTION,
297
+ syntax: `The command substitution \`${truncate(part.text)}\``
298
+ });
299
+ if (part.script && !part.script.errors?.length) this.#walkNestedScript(part.script, part, withCovered(context, covered));
300
+ break;
301
+ }
302
+ case "DoubleQuoted":
303
+ this.#checkParts(part.parts, context, state);
304
+ break;
305
+ case "ExtendedGlob":
306
+ if (context.bashOptions?.has("extglob")) break;
307
+ 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)}\``
310
+ }, PLATFORMS);
311
+ break;
312
+ case "Glob":
313
+ if (part.kind === "star") state.globPosition ??= part.pos;
314
+ break;
315
+ case "LocaleString":
316
+ this.#reporter.reportSyntax(context, part, "bash", false, "unsupportedSyntax", {
317
+ suggestion: BASH_SUGGESTION,
318
+ syntax: `The Bash-specific locale string \`${truncate(part.text)}\``
319
+ });
320
+ this.#checkParts(part.parts, context, state);
321
+ break;
322
+ case "ParameterExpansion":
323
+ this.#checkParameterExpansion(part, context);
324
+ break;
325
+ case "ProcessSubstitution": {
326
+ const covered = this.#reporter.reportSyntax(context, part, "bashNonPosix", false, "unsupportedSyntax", {
327
+ suggestion: "Use a temporary file or a Node.js script instead.",
328
+ syntax: `The Bash-specific process substitution \`${truncate(part.text)}\``
329
+ });
330
+ if (part.script && !part.script.errors?.length) this.#walkNestedScript(part.script, part, withCovered(context, covered));
331
+ break;
332
+ }
333
+ case "SimpleExpansion": {
334
+ const name = part.text.slice(1);
335
+ const covered = context.crossEnv && NAMED_VARIABLE.test(part.text) ? this.#checkCrossEnvVariable(name, part, context) : this.#reporter.reportSyntax(context, part, "posix", true, "unsupportedSyntax", {
336
+ suggestion: context.crossEnv ? CROSS_ENV_VARIABLE_SUGGESTION : this.#variableSuggestion(name),
337
+ syntax: `The variable expansion \`${part.text}\``
338
+ });
339
+ const nestedContext = withCovered(context, covered);
340
+ this.#checkBashVariable(name, part, nestedContext);
341
+ this.#checkPackageManagerVariable(name, part, nestedContext);
342
+ break;
343
+ }
344
+ case "SingleQuoted":
345
+ 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 : {
352
+ description: "Use escaped double quotes instead.",
353
+ edits: [{
354
+ end: part.end,
355
+ pos: part.pos,
356
+ text: `"${part.value}"`
357
+ }]
358
+ });
359
+ }
360
+ }
361
+ /**
362
+ * Reports device paths like `/dev/null`, which don't exist on Windows.
363
+ * @param word Word that contains the path
364
+ * @param value Static value of the word
365
+ * @param context Where the word is
366
+ * @param fix A fix for the report, e.g. one that removes the redirection to the path
367
+ */
368
+ checkPosixPath(word, value, context, fix) {
369
+ if (POSIX_PATH.test(value)) this.#reporter.report(context, word, "unsupportedSyntax", {
370
+ suggestion: "Remove it or use a Node.js script instead.",
371
+ syntax: `The POSIX path \`${truncate(value)}\``
372
+ }, WINDOWS_PLATFORMS, fix);
373
+ }
374
+ checkWord(word, context, options = {}) {
375
+ const { text } = word;
376
+ this.#checkCarriageReturn(word, context);
377
+ if (TILDE_EXPANSION.test(text)) this.#reporter.reportSyntax(context, word, "posix", false, "unsupportedSyntax", {
378
+ suggestion: "Use a path relative to the package or a Node.js script instead.",
379
+ syntax: `The tilde expansion \`${truncate(text)}\``
380
+ });
381
+ const state = {
382
+ braceExpansions: [],
383
+ command: options.command,
384
+ globPosition: void 0,
385
+ hasSingleQuotes: false,
386
+ printedToTerminal: options.printedToTerminal || false
387
+ };
388
+ this.#checkParts(word.parts || [], context, state);
389
+ const { globPosition } = state;
390
+ const hasGlob = globPosition != null;
391
+ const globPrefix = hasGlob ? text.slice(0, globPosition - word.pos) : "";
392
+ 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", {
394
+ reason: "`sh` doesn't support recursive `**` globs, and cmd.exe doesn't expand globs at all",
395
+ 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));
403
+ });
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("%")) {
416
+ const covered = this.#reporter.report(context, word, "unsupportedSyntax", {
417
+ suggestion: VARIABLE_SUGGESTION,
418
+ syntax: `The Windows variable reference \`${match[0]}\``
419
+ }, context.portable ? PLATFORMS : POSIX_PLATFORMS);
420
+ const nestedContext = withCovered(context, covered);
421
+ text.matchAll(WINDOWS_VARIABLES).forEach(([reference]) => {
422
+ this.#checkPackageManagerVariable(reference.slice(1, -1), word, nestedContext, reference);
423
+ });
424
+ }
425
+ }
426
+ const value = staticValue(word);
427
+ if (value != null && !options.commandName && !options.redirectTarget) this.checkPosixPath(word, value, context);
428
+ }
429
+ /** Checks whether Windows doesn't set a variable, so `cross-env` replaces it with nothing */
430
+ #isUnsetOnWindows(name) {
431
+ return POSIX_ONLY_VARIABLES.has(name) || name === "HOME" && !this.#runnerTraits.setsHome;
432
+ }
433
+ /** Checks whether a variable is one that package managers set, but the runner doesn't */
434
+ #isMissingPackageManagerVariable(name) {
435
+ const variables = this.#runnerTraits.packageManagerVariables;
436
+ return variables != null && PACKAGE_MANAGER_VARIABLE.test(name) && !variables.has(name);
437
+ }
438
+ /** Gets what to use instead of a variable on Windows, where `cross-env` can't help for some */
439
+ #variableSuggestion(name) {
440
+ if (name === "PWD") return "Use a relative path or a Node.js script instead.";
441
+ return this.#isUnsetOnWindows(name) || this.#isMissingPackageManagerVariable(name) ? NODE_SCRIPT_SUGGESTION : VARIABLE_SUGGESTION;
442
+ }
443
+ };
444
+ export { WordChecker };
package/dist/words.mjs ADDED
@@ -0,0 +1,43 @@
1
+ // src/words.ts
2
+ /** A `NAME=value` word, e.g. an argument of `cross-env` */
3
+ const ASSIGNMENT = /^[a-z_]\w*=/i;
4
+ const SHORT_OPTION_CLUSTER = /^-[a-z]+$/i;
5
+ /**
6
+ * Checks whether a word is a cluster of short options that includes a letter, e.g. `-rf` for `f`.
7
+ * @param value Value of a word from the script
8
+ * @param letter Letter of the short option to look for
9
+ * @returns Whether the word includes the option
10
+ */
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\-.]*(?:\/|$)/;
14
+ /** Characters that POSIX shells interpret in double quotes, e.g. `$` */
15
+ const DOUBLE_QUOTED_SPECIAL_CHARACTERS = /["$\\`]/;
16
+ const WHITESPACE = /\s/;
17
+ const GLOB_PART_TYPES = [
18
+ "BraceExpansion",
19
+ "ExtendedGlob",
20
+ "Glob"
21
+ ];
22
+ 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
+ /**
24
+ * Gets the value of a word, if it doesn't depend on expansions.
25
+ * @param word A word from the parsed script
26
+ * @returns The value, or `undefined` if it's dynamic
27
+ */
28
+ const staticValue = (word) => word.parts == null || isStatic(word.parts) ? word.value : void 0;
29
+ /**
30
+ * Checks whether a word is unquoted text without escapes or expansions, e.g. `dist/*.js`.
31
+ * Double quotes don't change the value of such a word.
32
+ * @param word A word from the parsed script
33
+ * @param partTypes Types of parts that are allowed besides literal text, e.g. globs
34
+ * @returns Whether the word is plain
35
+ */
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));
37
+ const isPlainAssignment = (item) => item.type === "Assignment" && item.value.type === "Word" && item.index == null && !item.append;
38
+ /**
39
+ * Device paths, e.g. `/dev/null`.
40
+ * Unlike other absolute paths, they are rarely meant for containers or remote hosts
41
+ */
42
+ const POSIX_PATH = /(?:^|=)\/dev\//;
43
+ export { ASSIGNMENT, DOUBLE_QUOTED_SPECIAL_CHARACTERS, GLOB_PART_TYPES, POSIX_PATH, TILDE_EXPANSION, WHITESPACE, isPlainAssignment, isPlainWord, isShortOptionCluster, staticValue };
package/package.json CHANGED
@@ -1,10 +1,122 @@
1
1
  {
2
2
  "name": "package-json-scripts-portability",
3
- "version": "0.0.0",
4
- "description": "OIDC trusted publishing setup package for package-json-scripts-portability",
3
+ "version": "0.0.2",
4
+ "description": "Finds package.json scripts that don't work the same on Windows, macOS and Linux with npm, pnpm, Yarn, aube, upm or node --run, and suggests fixes.",
5
5
  "keywords": [
6
- "oidc",
7
- "trusted-publishing",
8
- "setup"
9
- ]
6
+ "npm-scripts",
7
+ "package.json",
8
+ "scripts",
9
+ "cross-platform",
10
+ "portability",
11
+ "windows",
12
+ "cmd",
13
+ "posix",
14
+ "bash",
15
+ "lint"
16
+ ],
17
+ "homepage": "https://github.com/andreww2012/package-json-scripts-portability",
18
+ "bugs": {
19
+ "url": "https://github.com/andreww2012/package-json-scripts-portability/issues/new"
20
+ },
21
+ "repository": {
22
+ "type": "git",
23
+ "url": "git+https://github.com/andreww2012/package-json-scripts-portability.git"
24
+ },
25
+ "license": "MIT",
26
+ "author": "andreww2012",
27
+ "type": "module",
28
+ "exports": {
29
+ ".": "./dist/index.mjs",
30
+ "./package.json": "./package.json"
31
+ },
32
+ "types": "./dist/index.d.mts",
33
+ "files": [
34
+ "dist"
35
+ ],
36
+ "dependencies": {
37
+ "unbash": "6.0.4"
38
+ },
39
+ "devDependencies": {
40
+ "@andreww2012/commitlint-config": "0.1.0",
41
+ "@andreww2012/npm-check-updates-config": "0.1.1",
42
+ "@antfu/ni": "30.6.0",
43
+ "@arethetypeswrong/core": "0.18.5",
44
+ "@changesets/changelog-github": "1.0.1",
45
+ "@changesets/cli": "3.0.3",
46
+ "@commitlint/cli": "21.2.4",
47
+ "@eslint/config-inspector": "3.5.0",
48
+ "@types/node": "22.20.5",
49
+ "@vitest/coverage-v8": "5.1.0",
50
+ "@vitest/eslint-plugin": "1.6.28",
51
+ "@vitest/ui": "5.1.0",
52
+ "actions-up": "2.0.0",
53
+ "cspell": "10.4.1",
54
+ "eslint": "10.14.0",
55
+ "eslint-config-un": "1.0.0-rc.7",
56
+ "eslint-plugin-github-action": "0.5.0",
57
+ "eslint-plugin-sentences-per-line": "0.1.6",
58
+ "eslint-plugin-sonarjs": "4.2.2",
59
+ "knip": "6.45.1",
60
+ "lefthook": "2.2.2",
61
+ "npm-check-updates": "23.1.1",
62
+ "oxfmt": "0.78.0",
63
+ "publint": "0.3.25",
64
+ "tsdown": "0.23.7",
65
+ "tsx": "4.23.15",
66
+ "typescript": "npm:@typescript/typescript6@6.0.2",
67
+ "typescript7": "npm:typescript@7.1.0-beta",
68
+ "utilery": "0.4.0",
69
+ "vitest": "5.1.0"
70
+ },
71
+ "engines": {
72
+ "node": ">=22"
73
+ },
74
+ "devEngines": {
75
+ "runtime": {
76
+ "name": "node",
77
+ "version": "^22.23.1 || ^24.18.0 || >=26.4.0",
78
+ "onFail": "error"
79
+ },
80
+ "packageManager": {
81
+ "name": "pnpm",
82
+ "version": "12.19.0"
83
+ }
84
+ },
85
+ "inlinedDependencies": {
86
+ "utilery": "0.4.0"
87
+ },
88
+ "scripts": {
89
+ "build": "tsdown",
90
+ "u": "ncu",
91
+ "u:m": "ncu -t minor",
92
+ "u:pm": "pnpm self-update",
93
+ "u:actions": "actions-up",
94
+ "deps:audit": "pnpm audit --audit-level high",
95
+ "deps:audit:fix": "nr deps:audit --fix override",
96
+ "deps:audit:fix:update": "nr deps:audit --fix update",
97
+ "check:deps:dedupe": "pnpm dedupe --check",
98
+ "check:deps:peers": "pnpm peers check",
99
+ "check:spelling": "cspell --no-progress --no-summary .",
100
+ "check:format": "oxfmt --check",
101
+ "format": "oxfmt",
102
+ "eslint:inspect": "eslint-config-inspector --open false",
103
+ "eslint": "eslint --cache",
104
+ "ts": "tsc --noEmit",
105
+ "ts6": "tsc6 --noEmit",
106
+ "knip:main": "knip --no-progress",
107
+ "knip:cycles": "knip --no-progress --cycles --reporter cycles",
108
+ "knip": "nr \"/^knip:.+$/\"",
109
+ "check": "nr \"/^(knip|check:(spelling|format)|ts|eslint)$/\"",
110
+ "check:deps": "nr \"/^(deps:audit|check:deps:peers)$/\"",
111
+ "check:deps:strict": "nr \"/^(deps:audit|check:deps:(dedupe|peers))$/\"",
112
+ "check:fix": "nr format && nr eslint --fix && nr format",
113
+ "t": "vitest",
114
+ "t:ui": "vitest --ui",
115
+ "t:cov": "vitest --coverage",
116
+ "test:vitest": "nr t run",
117
+ "test:vitest:cov": "nr t:cov run",
118
+ "test": "nr check:deps && nr check && nr test:vitest",
119
+ "ch": "changeset add --message \"___REPLACE_ME___\"",
120
+ "release": "changeset publish"
121
+ }
10
122
  }