@visulima/vis 1.0.0-alpha.11 → 1.0.0-alpha.13

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/CHANGELOG.md +101 -0
  2. package/LICENSE.md +559 -186
  3. package/README.md +18 -0
  4. package/dist/bin.js +1 -9
  5. package/dist/config/index.d.ts +477 -556
  6. package/dist/config/index.js +1 -2
  7. package/dist/generate/index.js +1 -3
  8. package/dist/packem_chunks/applyDefaults.js +2 -336
  9. package/dist/packem_chunks/bin.js +234 -9552
  10. package/dist/packem_chunks/doctor-probe.js +2 -112
  11. package/dist/packem_chunks/fix.js +11 -234
  12. package/dist/packem_chunks/handler.js +1 -99
  13. package/dist/packem_chunks/handler10.js +2 -53
  14. package/dist/packem_chunks/handler11.js +1 -32
  15. package/dist/packem_chunks/handler12.js +5 -100
  16. package/dist/packem_chunks/handler13.js +1 -25
  17. package/dist/packem_chunks/handler14.js +18 -916
  18. package/dist/packem_chunks/handler15.js +15 -201
  19. package/dist/packem_chunks/handler16.js +1 -124
  20. package/dist/packem_chunks/handler17.js +1 -13
  21. package/dist/packem_chunks/handler18.js +1 -106
  22. package/dist/packem_chunks/handler19.js +1 -19
  23. package/dist/packem_chunks/handler2.js +2 -75
  24. package/dist/packem_chunks/handler20.js +5 -29
  25. package/dist/packem_chunks/handler21.js +1 -222
  26. package/dist/packem_chunks/handler22.js +1 -237
  27. package/dist/packem_chunks/handler23.js +5 -101
  28. package/dist/packem_chunks/handler24.js +1 -110
  29. package/dist/packem_chunks/handler25.js +3 -402
  30. package/dist/packem_chunks/handler26.js +1 -13
  31. package/dist/packem_chunks/handler27.js +1 -63
  32. package/dist/packem_chunks/handler28.js +7 -34
  33. package/dist/packem_chunks/handler29.js +21 -456
  34. package/dist/packem_chunks/handler3.js +4 -95
  35. package/dist/packem_chunks/handler30.js +3 -170
  36. package/dist/packem_chunks/handler31.js +1 -530
  37. package/dist/packem_chunks/handler32.js +2 -214
  38. package/dist/packem_chunks/handler33.js +25 -119
  39. package/dist/packem_chunks/handler34.js +2 -630
  40. package/dist/packem_chunks/handler35.js +3 -283
  41. package/dist/packem_chunks/handler36.js +22 -542
  42. package/dist/packem_chunks/handler37.js +410 -744
  43. package/dist/packem_chunks/handler38.js +22 -989
  44. package/dist/packem_chunks/handler39.js +22 -574
  45. package/dist/packem_chunks/handler4.js +2 -90
  46. package/dist/packem_chunks/handler40.js +22 -1685
  47. package/dist/packem_chunks/handler41.js +6 -1088
  48. package/dist/packem_chunks/handler42.js +5 -797
  49. package/dist/packem_chunks/handler43.js +10 -2658
  50. package/dist/packem_chunks/handler44.js +51 -3784
  51. package/dist/packem_chunks/handler45.js +25 -2574
  52. package/dist/packem_chunks/handler46.js +3 -3769
  53. package/dist/packem_chunks/handler47.js +21 -1485
  54. package/dist/packem_chunks/handler48.js +42 -0
  55. package/dist/packem_chunks/handler5.js +8 -174
  56. package/dist/packem_chunks/handler6.js +1 -95
  57. package/dist/packem_chunks/handler7.js +1 -115
  58. package/dist/packem_chunks/handler8.js +1 -12
  59. package/dist/packem_chunks/handler9.js +1 -29
  60. package/dist/packem_chunks/heal-accept.js +10 -522
  61. package/dist/packem_chunks/heal.js +14 -673
  62. package/dist/packem_chunks/index.js +7 -873
  63. package/dist/packem_chunks/loader.js +1 -23
  64. package/dist/packem_chunks/tar.js +3 -0
  65. package/dist/packem_shared/ai-analysis-hm8d2W7z.js +67 -0
  66. package/dist/packem_shared/ai-cache-DoiF80AR.js +1 -0
  67. package/dist/packem_shared/ai-fix-nn4zOE95.js +43 -0
  68. package/dist/packem_shared/cache-directory-CwHlJhgx.js +1 -0
  69. package/dist/packem_shared/dependency-scan-COr5n63B.js +2 -0
  70. package/dist/packem_shared/docker-D6OGr5_S.js +2 -0
  71. package/dist/packem_shared/failure-log-iUVLf6ts.js +2 -0
  72. package/dist/packem_shared/flakiness-D9wf0t56.js +1 -0
  73. package/dist/packem_shared/giget-CcEy_Elm.js +2 -0
  74. package/dist/packem_shared/index-DH-5hsrC.js +1 -0
  75. package/dist/packem_shared/otel-DxDUPJJH.js +6 -0
  76. package/dist/packem_shared/otelPlugin-CQq6poq8.js +1 -0
  77. package/dist/packem_shared/registry-CkubDdiY.js +2 -0
  78. package/dist/packem_shared/run-summary-utils-BfBvjzhY.js +1 -0
  79. package/dist/packem_shared/runtime-check-BXZ43CBW.js +1 -0
  80. package/dist/packem_shared/selectors-BylODRiM.js +3 -0
  81. package/dist/packem_shared/symbols-CQmER5MT.js +1 -0
  82. package/dist/packem_shared/toolchain-BgBOUHII.js +5 -0
  83. package/dist/packem_shared/typosquats-CcZl99B1.js +1 -0
  84. package/dist/packem_shared/use-measured-height-DjYgUOKk.js +1 -0
  85. package/dist/packem_shared/utils-DrNg0XTR.js +1 -0
  86. package/dist/packem_shared/verify-Baj5mFJ7.js +1 -0
  87. package/dist/packem_shared/vis-update-app-D1jl0UZZ.js +1 -0
  88. package/dist/packem_shared/xxh3-DrAUNq4n.js +1 -0
  89. package/index.js +556 -727
  90. package/package.json +19 -29
  91. package/schemas/project.schema.json +739 -297
  92. package/schemas/vis-config.schema.json +3365 -384
  93. package/templates/buildkite-ci/template.yml +20 -20
  94. package/dist/packem_shared/VisUpdateApp-D-Yz_wvg.js +0 -1316
  95. package/dist/packem_shared/_commonjsHelpers-BqLXS_qQ.js +0 -5
  96. package/dist/packem_shared/ai-analysis-CHeB1joD.js +0 -367
  97. package/dist/packem_shared/ai-cache-Be_jexe4.js +0 -142
  98. package/dist/packem_shared/ai-fix-B9iQVcD2.js +0 -379
  99. package/dist/packem_shared/cache-directory-2qvs4goY.js +0 -98
  100. package/dist/packem_shared/catalog-BJTtyi-O.js +0 -1371
  101. package/dist/packem_shared/dependency-scan-A0KSklpG.js +0 -188
  102. package/dist/packem_shared/docker-2iZzc280.js +0 -181
  103. package/dist/packem_shared/failure-log-Cz3Z4SKL.js +0 -100
  104. package/dist/packem_shared/flakiness-goTxXuCX.js +0 -180
  105. package/dist/packem_shared/otel-DCvqCTz_.js +0 -158
  106. package/dist/packem_shared/otelPlugin-DFaLDvJf.js +0 -3
  107. package/dist/packem_shared/registry-CbqXI0rc.js +0 -272
  108. package/dist/packem_shared/run-summary-utils-PVMl4aIh.js +0 -130
  109. package/dist/packem_shared/runtime-check-Cobi3p6l.js +0 -127
  110. package/dist/packem_shared/selectors-SM69TfqC.js +0 -194
  111. package/dist/packem_shared/symbols-Ta7g2nU-.js +0 -14
  112. package/dist/packem_shared/toolchain-BdZd9eBi.js +0 -975
  113. package/dist/packem_shared/typosquats-C-bCh3PX.js +0 -1210
  114. package/dist/packem_shared/use-measured-height-CNP0vT4M.js +0 -20
  115. package/dist/packem_shared/utils-CthVdBPS.js +0 -40
  116. package/dist/packem_shared/xxh3-Ck8mXNg1.js +0 -239
@@ -1,1088 +1,6 @@
1
- import { createRequire as __cjs_createRequire } from "node:module";
2
-
3
- const __cjs_require = __cjs_createRequire(import.meta.url);
4
-
5
- const __cjs_getProcess = typeof globalThis !== "undefined" && typeof globalThis.process !== "undefined" ? globalThis.process : process;
6
-
7
- const __cjs_getBuiltinModule = (module) => {
8
- // Check if we're in Node.js and version supports getBuiltinModule
9
- if (typeof __cjs_getProcess !== "undefined" && __cjs_getProcess.versions && __cjs_getProcess.versions.node) {
10
- const [major, minor] = __cjs_getProcess.versions.node.split(".").map(Number);
11
- // Node.js 20.16.0+ and 22.3.0+
12
- if (major > 22 || (major === 22 && minor >= 3) || (major === 20 && minor >= 16)) {
13
- return __cjs_getProcess.getBuiltinModule(module);
14
- }
15
- }
16
- // Fallback to createRequire
17
- return __cjs_require(module);
18
- };
19
-
20
- const {
21
- writeFileSync: writeFileSync$1
22
- } = __cjs_getBuiltinModule("node:fs");
23
- import { getManifestData } from '@socketsecurity/registry';
24
- import { readFileSync, isAccessibleSync, writeFileSync, readJsonSync, glob } from '@visulima/fs';
25
- import { join, resolve } from '@visulima/path';
26
- import { Box, Text, ScrollView, ScrollBar, useApp, useWindowSize, useInput, render } from '@visulima/tui';
27
- import { _ as QuitDialog, c as detectPm, p as pail, x as runInstall, q as readPnpmWorkspacePatterns, o as resolveWorkspacePatterns, i as isInCi } from './bin.js';
28
- import microUtilitiesManifest from 'module-replacements/manifests/micro-utilities.json' with { type: 'json' };
29
- import nativeManifest from 'module-replacements/manifests/native.json' with { type: 'json' };
30
- import preferredManifest from 'module-replacements/manifests/preferred.json' with { type: 'json' };
31
- import React, { useSyncExternalStore, useRef, useState, useCallback } from 'react';
32
- import { coerce } from 'semver';
33
- import { readYamlSync } from '@visulima/fs/yaml';
34
- import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
35
-
36
- const DEP_FIELDS = ["dependencies", "devDependencies", "peerDependencies", "peerDependenciesMeta", "optionalDependencies", "bundleDependencies"];
37
- const OVERRIDE_FIELDS = ["overrides", "pnpm", "resolutions"];
38
- const AFTER_FIELDS = ["engines", "files"];
39
- const isPnpmV10Plus = (version) => {
40
- const major = coerce(version)?.major;
41
- return major !== void 0 && major >= 10;
42
- };
43
- const readPnpmWorkspaceOverrides = (workspaceRoot) => {
44
- const filePath = join(workspaceRoot, "pnpm-workspace.yaml");
45
- if (!isAccessibleSync(filePath)) {
46
- return { overrides: {}, source: "pnpm-workspace.yaml" };
47
- }
48
- try {
49
- const data = readYamlSync(filePath);
50
- return { overrides: data?.overrides ?? {}, source: "pnpm-workspace.yaml" };
51
- } catch {
52
- return { overrides: {}, source: "pnpm-workspace.yaml" };
53
- }
54
- };
55
- const readPkgJsonOverrides = (pkgJson, pm) => {
56
- let overrides = {};
57
- if (pm === "pnpm") {
58
- overrides = pkgJson.pnpm?.overrides ?? {};
59
- } else if (pm === "yarn" || pm === "bun") {
60
- overrides = pkgJson.resolutions ?? {};
61
- } else {
62
- overrides = pkgJson.overrides ?? {};
63
- }
64
- return { overrides, source: "package.json" };
65
- };
66
- const readOverrides = (workspaceRoot, pkgJson, pm) => {
67
- if (pm.name === "pnpm" && isPnpmV10Plus(pm.version)) {
68
- return readPnpmWorkspaceOverrides(workspaceRoot);
69
- }
70
- return readPkgJsonOverrides(pkgJson, pm.name);
71
- };
72
- const findInsertIndex = (keys, field) => {
73
- const simpleField = field;
74
- for (const f of OVERRIDE_FIELDS) {
75
- const index = keys.indexOf(f);
76
- if (index !== -1 && f !== simpleField) {
77
- return simpleField === "overrides" ? index : index + 1;
78
- }
79
- }
80
- let highest = -1;
81
- for (const f of DEP_FIELDS) {
82
- const index = keys.indexOf(f);
83
- if (index > highest) {
84
- highest = index;
85
- }
86
- }
87
- if (highest !== -1) {
88
- return highest + 1;
89
- }
90
- for (const f of AFTER_FIELDS) {
91
- const index = keys.indexOf(f);
92
- if (index !== -1) {
93
- return index;
94
- }
95
- }
96
- return keys.length;
97
- };
98
- const detectIndent = (content) => {
99
- const match = /\n(\s+)/.exec(content);
100
- return match?.[1] ?? " ";
101
- };
102
- const writePnpmWorkspaceOverrides = (workspaceRoot, sorted) => {
103
- const filePath = join(workspaceRoot, "pnpm-workspace.yaml");
104
- if (!isAccessibleSync(filePath)) {
105
- throw new Error(`pnpm-workspace.yaml not found at ${filePath}. Cannot write overrides for pnpm v10+.`);
106
- }
107
- let content = readFileSync(filePath);
108
- const overrideLines = Object.entries(sorted).map(([key, value]) => ` '${key}': '${value}'`).join("\n");
109
- const overridesBlock = `overrides:
110
- ${overrideLines}
111
- `;
112
- content = /^overrides:\s*$/m.test(content) || /^overrides:\s*\n/m.test(content) ? content.replace(/^overrides:\s*\n(?:(?:[ \t].*)?\n)*/m, overridesBlock) : `${content.trimEnd()}
113
-
114
- ${overridesBlock}`;
115
- writeFileSync(filePath, content);
116
- };
117
- const writePkgJsonOverrides = (pkgJsonPath, pkgJson, sorted, pm) => {
118
- const raw = readFileSync(pkgJsonPath);
119
- const indent = detectIndent(raw);
120
- if (pm === "pnpm") {
121
- const pnpmObject = pkgJson.pnpm ?? {};
122
- pnpmObject.overrides = sorted;
123
- if (pkgJson.pnpm) {
124
- pkgJson.pnpm = pnpmObject;
125
- writeFileSync(pkgJsonPath, `${JSON.stringify(pkgJson, null, indent)}
126
- `);
127
- } else {
128
- const keys = Object.keys(pkgJson);
129
- const index = findInsertIndex(keys, "pnpm");
130
- const jsonEntries = Object.entries(pkgJson);
131
- jsonEntries.splice(index, 0, ["pnpm", pnpmObject]);
132
- writeFileSync(pkgJsonPath, `${JSON.stringify(Object.fromEntries(jsonEntries), null, indent)}
133
- `);
134
- }
135
- } else {
136
- const field = pm === "yarn" || pm === "bun" ? "resolutions" : "overrides";
137
- if (pkgJson[field]) {
138
- pkgJson[field] = sorted;
139
- writeFileSync(pkgJsonPath, `${JSON.stringify(pkgJson, null, indent)}
140
- `);
141
- } else {
142
- const keys = Object.keys(pkgJson);
143
- const index = findInsertIndex(keys, field);
144
- const jsonEntries = Object.entries(pkgJson);
145
- jsonEntries.splice(index, 0, [field, sorted]);
146
- writeFileSync(pkgJsonPath, `${JSON.stringify(Object.fromEntries(jsonEntries), null, indent)}
147
- `);
148
- }
149
- }
150
- };
151
- const applyOverrides = (workspaceRoot, pkgJsonPath, entries, pm) => {
152
- const raw = readFileSync(pkgJsonPath);
153
- const pkgJson = JSON.parse(raw);
154
- const { overrides: existing, source } = readOverrides(workspaceRoot, pkgJson, pm);
155
- const added = [];
156
- const updated = [];
157
- const directDeps = /* @__PURE__ */ new Set();
158
- if (pm.name === "npm") {
159
- for (const field of ["dependencies", "devDependencies"]) {
160
- const deps = pkgJson[field];
161
- if (deps) {
162
- for (const name of Object.keys(deps)) {
163
- directDeps.add(name);
164
- }
165
- }
166
- }
167
- }
168
- for (const entry of entries) {
169
- const oldSpec = existing[entry.original];
170
- if (typeof oldSpec === "object") {
171
- continue;
172
- }
173
- let newSpec = entry.spec;
174
- if (pm.name === "npm" && directDeps.has(entry.original)) {
175
- newSpec = `$${entry.original}`;
176
- }
177
- if (oldSpec === newSpec) {
178
- continue;
179
- }
180
- if (oldSpec) {
181
- updated.push(entry.original);
182
- } else {
183
- added.push(entry.original);
184
- }
185
- existing[entry.original] = newSpec;
186
- }
187
- if (added.length === 0 && updated.length === 0) {
188
- return { added, updated };
189
- }
190
- const sorted = Object.fromEntries(Object.entries(existing).sort(([a], [b]) => a.localeCompare(b)));
191
- if (source === "pnpm-workspace.yaml") {
192
- writePnpmWorkspaceOverrides(workspaceRoot, sorted);
193
- } else {
194
- writePkgJsonOverrides(pkgJsonPath, pkgJson, sorted, pm.name);
195
- }
196
- return { added, updated };
197
- };
198
- const readLockfileText = (workspaceRoot, pm) => {
199
- const lockfileNames = {
200
- bun: ["bun.lock"],
201
- npm: ["npm-shrinkwrap.json", "package-lock.json"],
202
- pnpm: ["pnpm-lock.yaml"],
203
- yarn: ["yarn.lock"]
204
- };
205
- for (const name of lockfileNames[pm] ?? []) {
206
- const filePath = join(workspaceRoot, name);
207
- try {
208
- return readFileSync(filePath);
209
- } catch {
210
- continue;
211
- }
212
- }
213
- return "";
214
- };
215
- const lockfileContainsPackage = (lockText, packageName, pm) => {
216
- if (!lockText) {
217
- return false;
218
- }
219
- const escaped = packageName.replaceAll(/[.*+?^${}()|[\]\\]/g, String.raw`\$&`);
220
- switch (pm) {
221
- case "bun": {
222
- return lockText.includes(`"${packageName}":`) || new RegExp(String.raw`(^|\s|[",])${escaped}@`, "m").test(lockText);
223
- }
224
- case "npm": {
225
- return lockText.includes(`"${packageName}":`) || lockText.includes(`"node_modules/${packageName}":`);
226
- }
227
- case "pnpm": {
228
- return new RegExp(String.raw`(^|\s|['"/])${escaped}(@|['"]?:)`, "m").test(lockText);
229
- }
230
- case "yarn": {
231
- return new RegExp(String.raw`(^|\s|[",])${escaped}@`, "m").test(lockText);
232
- }
233
- default: {
234
- return false;
235
- }
236
- }
237
- };
238
-
239
- const filterEntries = (entries, filterType, filterText) => {
240
- let filtered = entries;
241
- if (filterType !== "all") {
242
- filtered = filtered.filter((e) => e.category === filterType);
243
- }
244
- if (filterText) {
245
- const lower = filterText.toLowerCase();
246
- filtered = filtered.filter((e) => e.packageName.toLowerCase().includes(lower));
247
- }
248
- return filtered;
249
- };
250
- class OptimizeStore {
251
- #state;
252
- #listeners = /* @__PURE__ */ new Set();
253
- constructor(entries) {
254
- this.#state = {
255
- applyProgress: null,
256
- checkedEntries: /* @__PURE__ */ new Set(),
257
- entries,
258
- error: null,
259
- filterActive: false,
260
- filterText: "",
261
- filterType: "all",
262
- focusedPanel: "list",
263
- phase: "browsing",
264
- selectedIndex: 0
265
- };
266
- }
267
- getSnapshot = () => this.#state;
268
- subscribe = (listener) => {
269
- this.#listeners.add(listener);
270
- return () => {
271
- this.#listeners.delete(listener);
272
- };
273
- };
274
- getFilteredEntries = () => filterEntries(this.#state.entries, this.#state.filterType, this.#state.filterText);
275
- #notify() {
276
- this.#state = { ...this.#state };
277
- for (const listener of this.#listeners) {
278
- listener();
279
- }
280
- }
281
- select(index) {
282
- const filtered = this.getFilteredEntries();
283
- this.#state.selectedIndex = filtered.length === 0 ? -1 : Math.max(0, Math.min(index, filtered.length - 1));
284
- this.#notify();
285
- }
286
- toggleCheck(packageName) {
287
- const checked = new Set(this.#state.checkedEntries);
288
- if (checked.has(packageName)) {
289
- checked.delete(packageName);
290
- } else {
291
- checked.add(packageName);
292
- }
293
- this.#state.checkedEntries = checked;
294
- this.#notify();
295
- }
296
- toggleAll() {
297
- const filtered = this.getFilteredEntries();
298
- const checked = new Set(this.#state.checkedEntries);
299
- const allChecked = filtered.every((e) => checked.has(e.packageName));
300
- if (allChecked) {
301
- for (const e of filtered) {
302
- checked.delete(e.packageName);
303
- }
304
- } else {
305
- for (const e of filtered) {
306
- checked.add(e.packageName);
307
- }
308
- }
309
- this.#state.checkedEntries = checked;
310
- this.#notify();
311
- }
312
- setFilter(type) {
313
- this.#state.filterType = type;
314
- this.#state.selectedIndex = 0;
315
- this.#notify();
316
- }
317
- setFilterText(text) {
318
- this.#state.filterText = text;
319
- this.#state.selectedIndex = 0;
320
- this.#notify();
321
- }
322
- setFilterActive(active) {
323
- this.#state.filterActive = active;
324
- this.#notify();
325
- }
326
- setFocusedPanel(panel) {
327
- this.#state.focusedPanel = panel;
328
- this.#notify();
329
- }
330
- setPhase(phase) {
331
- this.#state.phase = phase;
332
- this.#notify();
333
- }
334
- setProgress(current, total) {
335
- this.#state.applyProgress = { current, total };
336
- this.#notify();
337
- }
338
- setError(error) {
339
- this.#state.error = error;
340
- this.#state.phase = "error";
341
- this.#notify();
342
- }
343
- getCheckedEntries() {
344
- return this.#state.entries.filter((e) => this.#state.checkedEntries.has(e.packageName));
345
- }
346
- }
347
-
348
- const CATEGORY_COLORS = {
349
- "micro-utility": "gray",
350
- native: "green",
351
- preferred: "yellow",
352
- socket: "cyan"
353
- };
354
- const CATEGORY_LABELS = {
355
- "micro-utility": "MICRO",
356
- native: "NATIVE",
357
- preferred: "PREF",
358
- socket: "SOCKET"
359
- };
360
- const CATEGORY_DESCRIPTIONS = {
361
- "micro-utility": "Trivial utility package that can be replaced with inline code.",
362
- native: "Polyfill for a native JS/Node.js API. Use the built-in instead.",
363
- preferred: "A lighter or faster alternative package exists.",
364
- socket: "Security-hardened replacement from Socket.dev's @socketregistry."
365
- };
366
-
367
- const OptimizeDetailPanel = ({ entry, focused, scrollRef }) => {
368
- const borderColor = focused ? "white" : "gray";
369
- if (!entry) {
370
- return jsx(Box, { alignItems: "center", borderColor: "gray", borderStyle: "single", flexDirection: "column", flexGrow: 1, justifyContent: "center", children: jsx(Text, { dimColor: true, children: "No entry selected" }) });
371
- }
372
- const categoryColor = CATEGORY_COLORS[entry.category] ?? "gray";
373
- return jsxs(Box, { borderColor, borderStyle: "single", flexDirection: "column", flexGrow: 1, children: [
374
- jsx(Box, { flexShrink: 0, paddingTop: 1, paddingX: 2, children: jsx(Text, { bold: true, color: "white", children: entry.packageName }) }),
375
- jsxs(ScrollView, { flexGrow: 1, flexShrink: 1, paddingX: 2, ref: scrollRef, scrollbar: true, scrollbarColor: "gray", children: [
376
- jsx(Text, {}),
377
- jsxs(Box, { children: [
378
- jsx(Box, { width: 14, children: jsx(Text, { dimColor: true, children: "Category:" }) }),
379
- jsx(Text, { bold: true, color: categoryColor, children: entry.category })
380
- ] }),
381
- jsxs(Box, { children: [
382
- jsx(Box, { width: 14, children: jsx(Text, { dimColor: true, children: "Replace with:" }) }),
383
- jsx(Text, { children: entry.replacement })
384
- ] }),
385
- entry.overrideSpec && jsxs(Box, { children: [
386
- jsx(Box, { width: 14, children: jsx(Text, { dimColor: true, children: "Override:" }) }),
387
- jsx(Text, { color: "cyan", children: entry.overrideSpec })
388
- ] }),
389
- jsxs(Box, { children: [
390
- jsx(Box, { width: 14, children: jsx(Text, { dimColor: true, children: "Codemod:" }) }),
391
- jsx(Text, { color: entry.hasCodemod ? "green" : "gray", children: entry.hasCodemod ? "available ⚙" : "not available" })
392
- ] }),
393
- jsxs(Box, { flexDirection: "column", marginTop: 1, children: [
394
- jsx(Text, { dimColor: true, children: "── " }),
395
- jsx(Text, { bold: true, color: "white", children: "DESCRIPTION" }),
396
- jsx(Box, { marginTop: 1, paddingLeft: 2, children: jsx(Text, { children: CATEGORY_DESCRIPTIONS[entry.category] ?? "" }) })
397
- ] }),
398
- entry.category === "native" && jsxs(Box, { flexDirection: "column", marginTop: 1, children: [
399
- jsx(Text, { dimColor: true, children: "── " }),
400
- jsx(Text, { bold: true, color: "green", children: "ACTION" }),
401
- jsx(Box, { flexDirection: "column", marginTop: 1, paddingLeft: 2, children: entry.hasCodemod ? jsxs(Fragment, { children: [
402
- jsxs(Text, { color: "green", children: [
403
- "✓",
404
- " Codemod will rewrite imports to use native API."
405
- ] }),
406
- jsx(Text, { dimColor: true, children: " The package can then be removed from dependencies." })
407
- ] }) : jsxs(Fragment, { children: [
408
- jsxs(Text, { color: "yellow", children: [
409
- "ℹ",
410
- " No automated codemod available."
411
- ] }),
412
- jsx(Text, { dimColor: true, children: " Manual migration required — replace usage with native equivalent." })
413
- ] }) })
414
- ] }),
415
- entry.category === "socket" && jsxs(Box, { flexDirection: "column", marginTop: 1, children: [
416
- jsx(Text, { dimColor: true, children: "── " }),
417
- jsx(Text, { bold: true, color: "cyan", children: "ACTION" }),
418
- jsxs(Box, { flexDirection: "column", marginTop: 1, paddingLeft: 2, children: [
419
- jsxs(Text, { color: "cyan", children: [
420
- "✓",
421
- " Override will redirect resolution to the hardened package."
422
- ] }),
423
- jsx(Text, { dimColor: true, children: " No source code changes needed — drop-in replacement." })
424
- ] })
425
- ] }),
426
- (entry.category === "preferred" || entry.category === "micro-utility") && jsxs(Box, { flexDirection: "column", marginTop: 1, children: [
427
- jsx(Text, { dimColor: true, children: "── " }),
428
- jsx(Text, { bold: true, color: "yellow", children: "ACTION" }),
429
- jsx(Box, { flexDirection: "column", marginTop: 1, paddingLeft: 2, children: entry.hasCodemod ? jsxs(Fragment, { children: [
430
- jsxs(Text, { color: "green", children: [
431
- "✓",
432
- " Codemod will rewrite imports to the recommended alternative."
433
- ] }),
434
- jsx(Text, { dimColor: true, children: " The original package can then be removed from dependencies." })
435
- ] }) : jsxs(Fragment, { children: [
436
- jsxs(Text, { color: "yellow", children: [
437
- "ℹ",
438
- " Manual migration required."
439
- ] }),
440
- entry.docUrl ? jsx(Text, { dimColor: true, children: " Open the migration guide below for the recommended alternative and steps." }) : jsx(Text, { dimColor: true, children: " Consult the package's docs or the e18e module-replacements guide for an alternative." })
441
- ] }) })
442
- ] }),
443
- jsxs(Box, { flexDirection: "column", marginTop: 1, children: [
444
- jsx(Text, { dimColor: true, children: "── " }),
445
- jsx(Text, { bold: true, color: "white", children: "LINKS" }),
446
- jsxs(Box, { flexDirection: "column", marginTop: 1, paddingLeft: 2, children: [
447
- jsxs(Text, { color: "cyan", underline: true, children: [
448
- "https://npmx.dev/",
449
- entry.packageName
450
- ] }),
451
- entry.docUrl && jsx(Text, { color: "cyan", underline: true, children: entry.docUrl })
452
- ] })
453
- ] })
454
- ] })
455
- ] });
456
- };
457
-
458
- const FILTER_LABELS = [
459
- { key: "all", label: "All", shortcut: "1" },
460
- { key: "native", label: "Native", shortcut: "2" },
461
- { key: "preferred", label: "Preferred", shortcut: "3" },
462
- { key: "micro-utility", label: "Micro", shortcut: "4" },
463
- { key: "socket", label: "Socket", shortcut: "5" }
464
- ];
465
- const EntryRow = ({ checked, entry, isSelected }) => {
466
- const catColor = CATEGORY_COLORS[entry.category] ?? "white";
467
- const catLabel = CATEGORY_LABELS[entry.category] ?? entry.category;
468
- const checkbox = checked ? "☑" : "☐";
469
- const codemodBadge = entry.hasCodemod ? "⚙" : " ";
470
- return jsxs(Box, { flexShrink: 0, height: 1, children: [
471
- jsx(Text, { children: isSelected ? ">" : " " }),
472
- jsxs(Text, { color: checked ? "white" : "gray", children: [
473
- " ",
474
- checkbox,
475
- " "
476
- ] }),
477
- jsx(Text, { bold: true, color: catColor, children: `[${catLabel}]`.padEnd(9) }),
478
- jsxs(Text, { children: [
479
- " ",
480
- codemodBadge,
481
- " "
482
- ] }),
483
- jsx(Box, { flexGrow: 1, children: jsx(Text, { bold: isSelected, inverse: isSelected, wrap: "truncate", children: entry.packageName }) }),
484
- jsx(Text, { dimColor: true, children: " → " }),
485
- jsx(Text, { wrap: "truncate", children: entry.replacement })
486
- ] });
487
- };
488
- const OptimizeListPanel = ({
489
- checkedEntries,
490
- entries,
491
- filterActive,
492
- filterText,
493
- filterType,
494
- focused,
495
- isDryRun,
496
- scrollOffset,
497
- selectedIndex,
498
- totalEntries,
499
- viewportHeight
500
- }) => {
501
- const borderColor = focused ? "white" : "gray";
502
- let nativeCount = 0;
503
- let preferredCount = 0;
504
- let microCount = 0;
505
- let socketCount = 0;
506
- for (const e of entries) {
507
- switch (e.category) {
508
- case "micro-utility": {
509
- microCount++;
510
- break;
511
- }
512
- case "native": {
513
- nativeCount++;
514
- break;
515
- }
516
- case "preferred": {
517
- preferredCount++;
518
- break;
519
- }
520
- case "socket": {
521
- {
522
- socketCount++;
523
- }
524
- break;
525
- }
526
- }
527
- }
528
- const summaryParts = [];
529
- if (nativeCount > 0) {
530
- summaryParts.push(`${nativeCount} native`);
531
- }
532
- if (preferredCount > 0) {
533
- summaryParts.push(`${preferredCount} preferred`);
534
- }
535
- if (microCount > 0) {
536
- summaryParts.push(`${microCount} micro`);
537
- }
538
- if (socketCount > 0) {
539
- summaryParts.push(`${socketCount} socket`);
540
- }
541
- const summaryText = summaryParts.length > 0 ? ` (${summaryParts.join(", ")})` : "";
542
- const checkedCount = checkedEntries.size;
543
- const rows = [];
544
- for (const [index, entry] of entries.entries()) {
545
- rows.push(jsx(EntryRow, { checked: checkedEntries.has(entry.packageName), entry, isSelected: index === selectedIndex }, entry.packageName));
546
- }
547
- const contentHeight = entries.length;
548
- const showScrollbar = contentHeight > viewportHeight && viewportHeight > 0;
549
- return jsxs(Box, { borderColor, borderStyle: "single", flexDirection: "column", flexGrow: 1, children: [
550
- jsxs(Box, { flexShrink: 0, gap: 1, paddingX: 1, children: [
551
- jsx(Text, { bold: true, inverse: true, children: " VIS OPTIMIZE " }),
552
- jsxs(Text, { wrap: "truncate", children: [
553
- totalEntries,
554
- " optimizations",
555
- summaryText
556
- ] }),
557
- !isDryRun && checkedCount > 0 && jsxs(Text, { dimColor: true, children: [
558
- " —",
559
- checkedCount,
560
- " selected"
561
- ] })
562
- ] }),
563
- jsx(Box, { flexShrink: 0, gap: 1, paddingX: 1, paddingY: 1, children: FILTER_LABELS.map((f) => {
564
- const isActive = filterType === f.key;
565
- return jsxs(Box, { children: [
566
- jsx(Text, { dimColor: !isActive, children: "[" }),
567
- jsx(Text, { bold: isActive, color: isActive ? "cyan" : "gray", children: f.shortcut }),
568
- jsx(Text, { dimColor: !isActive, children: "]" }),
569
- jsxs(Text, { color: isActive ? "white" : "gray", children: [
570
- " ",
571
- f.label
572
- ] })
573
- ] }, f.key);
574
- }) }),
575
- filterActive && jsxs(Box, { flexShrink: 0, paddingX: 1, children: [
576
- jsx(Text, { bold: true, color: "white", children: "/ " }),
577
- jsx(Text, { children: filterText }),
578
- jsx(Text, { inverse: true, children: " " })
579
- ] }),
580
- jsxs(Box, { flexDirection: "row", flexGrow: 1, overflow: "hidden", children: [
581
- jsx(Box, { flexDirection: "column", flexGrow: 1, overflow: "hidden", paddingLeft: 1, children: jsx(Box, { flexDirection: "column", marginTop: -scrollOffset, children: rows }) }),
582
- showScrollbar && jsx(Box, { flexShrink: 0, marginLeft: 1, marginRight: 1, children: jsx(ScrollBar, { contentHeight, placement: "inset", scrollOffset, style: "block", viewportHeight }) })
583
- ] })
584
- ] });
585
- };
586
-
587
- const MIN_HORIZONTAL_WIDTH = 100;
588
- const MIN_VIEWPORT_HEIGHT = 10;
589
- const FILTER_KEYS = {
590
- 1: "all",
591
- 2: "native",
592
- 3: "preferred",
593
- 4: "micro-utility",
594
- 5: "socket"
595
- };
596
- const VisOptimizeApp = ({ isDryRun, store }) => {
597
- const { exit } = useApp();
598
- const { columns, rows } = useWindowSize();
599
- const state = useSyncExternalStore(store.subscribe, store.getSnapshot);
600
- const detailScrollRef = useRef(null);
601
- const [listScrollOffset, setListScrollOffset] = useState(0);
602
- const [quitDialogVisible, setQuitDialogVisible] = useState(false);
603
- const filteredEntries = store.getFilteredEntries();
604
- const selectedEntry = filteredEntries[state.selectedIndex] ?? null;
605
- const isHorizontal = columns >= MIN_HORIZONTAL_WIDTH;
606
- const headerHeight = 5;
607
- const viewportHeight = Math.max(0, rows - headerHeight);
608
- const handleExit = useCallback(
609
- (result) => {
610
- exit(result);
611
- },
612
- [exit]
613
- );
614
- useInput(
615
- (input, key) => {
616
- if (quitDialogVisible) {
617
- if (input === "y" || input === "Y") {
618
- handleExit();
619
- } else {
620
- setQuitDialogVisible(false);
621
- }
622
- return;
623
- }
624
- if (state.filterActive) {
625
- if (key.escape) {
626
- store.setFilterActive(false);
627
- store.setFilterText("");
628
- } else if (key.return) {
629
- store.setFilterActive(false);
630
- } else if (key.backspace || key.delete) {
631
- store.setFilterText(state.filterText.slice(0, -1));
632
- } else if (input && !key.ctrl && !key.meta) {
633
- store.setFilterText(state.filterText + input);
634
- }
635
- return;
636
- }
637
- if (input === "q") {
638
- if (!isDryRun && state.checkedEntries.size > 0) {
639
- setQuitDialogVisible(true);
640
- } else {
641
- handleExit();
642
- }
643
- return;
644
- }
645
- if (input === "/") {
646
- store.setFilterActive(true);
647
- return;
648
- }
649
- if (FILTER_KEYS[input]) {
650
- store.setFilter(FILTER_KEYS[input]);
651
- return;
652
- }
653
- if (key.tab) {
654
- store.setFocusedPanel(state.focusedPanel === "list" ? "detail" : "list");
655
- return;
656
- }
657
- if (state.focusedPanel === "list") {
658
- if (key.upArrow || input === "k") {
659
- const newIndex = Math.max(0, state.selectedIndex - 1);
660
- store.select(newIndex);
661
- if (newIndex < listScrollOffset) {
662
- setListScrollOffset(newIndex);
663
- }
664
- } else if (key.downArrow || input === "j") {
665
- const newIndex = Math.min(filteredEntries.length - 1, state.selectedIndex + 1);
666
- store.select(newIndex);
667
- if (newIndex >= listScrollOffset + viewportHeight) {
668
- setListScrollOffset(newIndex - viewportHeight + 1);
669
- }
670
- } else if (input === " ") {
671
- if (selectedEntry) {
672
- store.toggleCheck(selectedEntry.packageName);
673
- }
674
- } else if (input === "a") {
675
- store.toggleAll();
676
- } else if (key.return && !isDryRun && state.checkedEntries.size > 0) {
677
- handleExit(store.getCheckedEntries());
678
- }
679
- } else if (state.focusedPanel === "detail") {
680
- if (key.upArrow || input === "k") {
681
- detailScrollRef.current?.scrollBy(-1);
682
- } else if (key.downArrow || input === "j") {
683
- detailScrollRef.current?.scrollBy(1);
684
- }
685
- }
686
- },
687
- { isActive: state.phase === "browsing" }
688
- );
689
- if (rows < MIN_VIEWPORT_HEIGHT) {
690
- return jsx(Box, { alignItems: "center", justifyContent: "center", children: jsxs(Text, { color: "yellow", children: [
691
- "Terminal too small. Resize to at least",
692
- MIN_VIEWPORT_HEIGHT,
693
- " rows."
694
- ] }) });
695
- }
696
- return jsxs(Box, { flexDirection: "column", height: rows, width: columns, children: [
697
- jsxs(Box, { flexDirection: isHorizontal ? "row" : "column", flexGrow: 1, children: [
698
- jsx(Box, { flexBasis: isHorizontal ? "50%" : void 0, flexGrow: 1, children: jsx(
699
- OptimizeListPanel,
700
- {
701
- checkedEntries: state.checkedEntries,
702
- entries: filteredEntries,
703
- filterActive: state.filterActive,
704
- filterText: state.filterText,
705
- filterType: state.filterType,
706
- focused: state.focusedPanel === "list",
707
- isDryRun,
708
- scrollOffset: listScrollOffset,
709
- selectedIndex: state.selectedIndex,
710
- totalEntries: state.entries.length,
711
- viewportHeight
712
- }
713
- ) }),
714
- jsx(Box, { flexBasis: isHorizontal ? "50%" : void 0, flexGrow: 1, children: jsx(OptimizeDetailPanel, { entry: selectedEntry, focused: state.focusedPanel === "detail", scrollRef: detailScrollRef }) })
715
- ] }),
716
- jsx(Box, { flexShrink: 0, paddingX: 1, children: jsxs(Text, { dimColor: true, children: [
717
- isDryRun ? "Preview mode" : "space:toggle a:all enter:apply",
718
- " | tab:switch panel /: filter q:quit |",
719
- "⚙",
720
- "=codemod available"
721
- ] }) }),
722
- jsx(
723
- QuitDialog,
724
- {
725
- autoExitSeconds: 3,
726
- onCancel: () => {
727
- setQuitDialogVisible(false);
728
- },
729
- visible: quitDialogVisible
730
- }
731
- )
732
- ] });
733
- };
734
-
735
- const collectDepsFromPkgJson = (pkgJsonPath, productionOnly) => {
736
- const deps = /* @__PURE__ */ new Set();
737
- try {
738
- const pkg = readJsonSync(pkgJsonPath);
739
- const maps = productionOnly ? [pkg.dependencies, pkg.optionalDependencies] : [pkg.dependencies, pkg.devDependencies, pkg.peerDependencies, pkg.optionalDependencies];
740
- for (const depMap of maps) {
741
- if (depMap) {
742
- for (const name of Object.keys(depMap)) {
743
- deps.add(name);
744
- }
745
- }
746
- }
747
- } catch {
748
- }
749
- return deps;
750
- };
751
- const discoverWorkspacePackages = (workspaceRoot) => {
752
- const pnpmPatterns = readPnpmWorkspacePatterns(workspaceRoot);
753
- if (pnpmPatterns) {
754
- return resolveWorkspacePatterns(workspaceRoot, pnpmPatterns);
755
- }
756
- const rootPkgPath = join(workspaceRoot, "package.json");
757
- if (!isAccessibleSync(rootPkgPath)) {
758
- return [];
759
- }
760
- try {
761
- const pkg = readJsonSync(rootPkgPath);
762
- const patterns = Array.isArray(pkg.workspaces) ? pkg.workspaces : pkg.workspaces?.packages;
763
- return patterns ? resolveWorkspacePatterns(workspaceRoot, patterns) : [];
764
- } catch {
765
- return [];
766
- }
767
- };
768
- const E18E_DOC_BASE_URL = "https://github.com/es-tooling/module-replacements/blob/main/docs/modules";
769
- const buildE18eDocUrl = (docPath) => `${E18E_DOC_BASE_URL}/${docPath}.md`;
770
- const e18eReplacementHint = (entry) => {
771
- if (entry.type === "simple" && entry.replacement) {
772
- return entry.replacement;
773
- }
774
- if (entry.type === "native") {
775
- const minNode = entry.nodeVersion ? ` (Node ${entry.nodeVersion}+)` : "";
776
- return entry.replacement ? `${entry.replacement}${minNode}` : `Native API${minNode}`;
777
- }
778
- if (entry.type === "documented" && entry.docPath) {
779
- return "see migration guide";
780
- }
781
- return "";
782
- };
783
- const buildE18eEntries = (allDeps) => {
784
- const entries = [];
785
- const scanManifest = (manifest, category) => {
786
- const list = manifest.moduleReplacements;
787
- if (!Array.isArray(list)) {
788
- return;
789
- }
790
- for (const entry of list) {
791
- if (!allDeps.has(entry.moduleName)) {
792
- continue;
793
- }
794
- entries.push({
795
- category,
796
- docUrl: entry.type === "documented" && entry.docPath ? buildE18eDocUrl(entry.docPath) : void 0,
797
- hasCodemod: false,
798
- // filled in below
799
- overrideSpec: void 0,
800
- packageName: entry.moduleName,
801
- replacement: e18eReplacementHint(entry)
802
- });
803
- }
804
- };
805
- scanManifest(nativeManifest, "native");
806
- scanManifest(preferredManifest, "preferred");
807
- scanManifest(microUtilitiesManifest, "micro-utility");
808
- return entries;
809
- };
810
- const buildSocketEntries = (allDeps, lockText, pm, pin) => {
811
- const manifest = getManifestData("npm") ?? [];
812
- const entries = [];
813
- for (const [, data] of manifest) {
814
- if (data.deprecated) {
815
- continue;
816
- }
817
- const inDeps = allDeps.has(data.package);
818
- const inLockfile = lockText ? lockfileContainsPackage(lockText, data.package, pm.name) : false;
819
- if (!inDeps && !inLockfile) {
820
- continue;
821
- }
822
- const major = coerce(data.version)?.major;
823
- if (major === void 0) {
824
- continue;
825
- }
826
- const spec = pin ? `npm:${data.name}@${data.version}` : `npm:${data.name}@^${String(major)}`;
827
- entries.push({
828
- category: "socket",
829
- hasCodemod: false,
830
- overrideSpec: spec,
831
- packageName: data.package,
832
- replacement: data.name
833
- });
834
- }
835
- return entries;
836
- };
837
- let cachedCodemods;
838
- const loadCodemods = async () => {
839
- if (cachedCodemods) {
840
- return cachedCodemods;
841
- }
842
- try {
843
- const module_ = await import('module-replacements-codemods');
844
- cachedCodemods = module_.codemods;
845
- return cachedCodemods;
846
- } catch {
847
- return {};
848
- }
849
- };
850
- const markCodemodAvailability = async (entries) => {
851
- try {
852
- const codemods = await loadCodemods();
853
- for (const entry of entries) {
854
- if (entry.category !== "socket" && codemods[entry.packageName]) {
855
- entry.hasCodemod = true;
856
- }
857
- }
858
- } catch {
859
- }
860
- };
861
- const runCodemod = async (workspaceRoot, packageName) => {
862
- let filesChanged = 0;
863
- try {
864
- const codemods = await loadCodemods();
865
- const factory = codemods[packageName];
866
- if (!factory) {
867
- return { filesChanged: 0, packageName };
868
- }
869
- const codemod = factory({});
870
- const sourceFiles = await collectSourceFiles(workspaceRoot);
871
- for (const filePath of sourceFiles) {
872
- const source = readFileSync(filePath);
873
- if (!source.includes(packageName)) {
874
- continue;
875
- }
876
- try {
877
- const result = await codemod.transform({ file: { filename: filePath, source } });
878
- if (result !== source) {
879
- writeFileSync$1(filePath, result, "utf8");
880
- filesChanged++;
881
- }
882
- } catch (error) {
883
- process.stderr.write(`warn: codemod transform failed for ${filePath}: ${error instanceof Error ? error.message : String(error)}
884
- `);
885
- }
886
- }
887
- } catch {
888
- }
889
- return { filesChanged, packageName };
890
- };
891
- const collectSourceFiles = async (dir) => glob("**/*.{cjs,cts,js,jsx,mjs,mts,ts,tsx}", {
892
- absolute: true,
893
- cwd: dir,
894
- // Matches the hand-rolled walker's SKIP set + "skip dotted
895
- // entries" policy. `tinyglobby` (the engine) applies these as
896
- // negative patterns during the walk so skipped subtrees are
897
- // never descended into.
898
- ignore: ["**/.*/**", "**/.*", "**/node_modules/**", "**/dist/**", "**/coverage/**", "**/.git/**", "**/.next/**", "**/.nuxt/**"]
899
- });
900
- const execute = async ({ logger, options, workspaceRoot: wsRoot }) => {
901
- if (!wsRoot) {
902
- throw new Error("Could not determine workspace root. Run this command inside a monorepo.");
903
- }
904
- const pm = detectPm(wsRoot);
905
- const isDryRun = Boolean(options.dryRun);
906
- const isProduction = Boolean(options.prod);
907
- const isPin = Boolean(options.pin);
908
- pail.info(`Detected ${pm.name} v${pm.version}.`);
909
- const rootDeps = collectDepsFromPkgJson(join(wsRoot, "package.json"), isProduction);
910
- const workspaceDirectories = discoverWorkspacePackages(wsRoot);
911
- const allDeps = new Set(rootDeps);
912
- for (const wsDir of workspaceDirectories) {
913
- const wsDeps = collectDepsFromPkgJson(join(resolve(wsRoot, wsDir), "package.json"), isProduction);
914
- for (const dep of wsDeps) {
915
- allDeps.add(dep);
916
- }
917
- }
918
- if (workspaceDirectories.length > 0) {
919
- pail.info(`Scanned ${String(workspaceDirectories.length)} workspace package${workspaceDirectories.length === 1 ? "" : "s"}.`);
920
- }
921
- pail.info("Scanning dependencies...\n");
922
- const lockText = readLockfileText(wsRoot, pm.name);
923
- const e18eEntries = buildE18eEntries(allDeps);
924
- const socketEntries = buildSocketEntries(allDeps, lockText, pm, isPin);
925
- const e18ePackages = new Set(e18eEntries.map((e) => e.packageName));
926
- const dedupedSocketEntries = socketEntries.filter((e) => !e18ePackages.has(e.packageName));
927
- const allEntries = [...e18eEntries, ...dedupedSocketEntries];
928
- await markCodemodAvailability(allEntries);
929
- if (allEntries.length === 0) {
930
- pail.info("No optimizations found for your dependencies.");
931
- return;
932
- }
933
- const isTTY = Boolean(process.stdout.isTTY) && !isInCi;
934
- const isJson = options.format === "json" || Boolean(options.json);
935
- if (isTTY && !isDryRun && !isJson) {
936
- const store = new OptimizeStore(allEntries);
937
- const instance = render(React.createElement(VisOptimizeApp, { isDryRun: false, store }), {
938
- alternateScreen: true,
939
- exitOnCtrlC: false,
940
- interactive: true,
941
- patchConsole: true
942
- });
943
- const exitResult = await instance.waitUntilExit();
944
- const selected = Array.isArray(exitResult) ? exitResult : [];
945
- if (selected.length === 0) {
946
- pail.info("No optimizations selected.");
947
- return;
948
- }
949
- const selectedE18eWithCodemod = selected.filter((e) => e.category !== "socket" && e.hasCodemod);
950
- const selectedE18eManual = selected.filter((e) => e.category !== "socket" && !e.hasCodemod);
951
- const selectedSocket = selected.filter((e) => e.category === "socket");
952
- if (selectedE18eWithCodemod.length > 0) {
953
- pail.info(`
954
- Running ${String(selectedE18eWithCodemod.length)} codemod${selectedE18eWithCodemod.length === 1 ? "" : "s"}...
955
- `);
956
- for (const entry of selectedE18eWithCodemod) {
957
- const result = await runCodemod(wsRoot, entry.packageName);
958
- if (result.filesChanged > 0) {
959
- pail.success(` ${entry.packageName}: ${String(result.filesChanged)} file${result.filesChanged === 1 ? "" : "s"} updated`);
960
- } else {
961
- pail.info(` ${entry.packageName}: no files changed`);
962
- }
963
- }
964
- }
965
- if (selectedE18eManual.length > 0) {
966
- pail.warn(
967
- `
968
- ${String(selectedE18eManual.length)} selected replacement${selectedE18eManual.length === 1 ? "" : "s"} require manual migration (no codemod available):`
969
- );
970
- for (const entry of selectedE18eManual) {
971
- pail.info(` ${entry.packageName} → ${entry.replacement}`);
972
- }
973
- pail.notice(" Replace usage in your source code, then remove from dependencies.");
974
- }
975
- if (selectedSocket.length > 0) {
976
- const overrideEntries = selectedSocket.filter((e) => e.overrideSpec).map((e) => {
977
- return { original: e.packageName, spec: e.overrideSpec };
978
- });
979
- const result = applyOverrides(wsRoot, join(wsRoot, "package.json"), overrideEntries, pm);
980
- if (result.added.length > 0) {
981
- pail.success(`
982
- Added ${String(result.added.length)} override${result.added.length === 1 ? "" : "s"}.`);
983
- }
984
- if (result.updated.length > 0) {
985
- pail.success(`Updated ${String(result.updated.length)} override${result.updated.length === 1 ? "" : "s"}.`);
986
- }
987
- }
988
- if (selectedSocket.length > 0 && !options.noInstall) {
989
- pail.info(`
990
- Running ${pm.name} install to update lockfile...`);
991
- const installOptions = {
992
- dev: false,
993
- filter: [],
994
- force: false,
995
- frozenLockfile: false,
996
- ignoreScripts: false,
997
- lockfileOnly: false,
998
- noOptional: false,
999
- offline: false,
1000
- prod: false,
1001
- recursive: false,
1002
- silent: false,
1003
- workspaceRoot: false
1004
- };
1005
- const code = runInstall(pm, installOptions, wsRoot, logger);
1006
- if (code !== 0) {
1007
- pail.warn(`${pm.name} install exited with code ${String(code)}. Run it manually.`);
1008
- }
1009
- }
1010
- pail.info("");
1011
- pail.success("Optimization complete.");
1012
- return;
1013
- }
1014
- if (isJson) {
1015
- process.stdout.write(
1016
- `${JSON.stringify(
1017
- {
1018
- e18e: e18eEntries.map((e) => {
1019
- return {
1020
- category: e.category,
1021
- hasCodemod: e.hasCodemod,
1022
- packageName: e.packageName,
1023
- replacement: e.replacement
1024
- };
1025
- }),
1026
- packageManager: pm.name,
1027
- socket: dedupedSocketEntries.map((e) => {
1028
- return { overrideSpec: e.overrideSpec, packageName: e.packageName, replacement: e.replacement };
1029
- }),
1030
- total: allEntries.length,
1031
- workspaces: workspaceDirectories.length
1032
- },
1033
- void 0,
1034
- 2
1035
- )}
1036
- `
1037
- );
1038
- return;
1039
- }
1040
- const natives = e18eEntries.filter((e) => e.category === "native");
1041
- const preferred = e18eEntries.filter((e) => e.category === "preferred");
1042
- const micros = e18eEntries.filter((e) => e.category === "micro-utility");
1043
- if (natives.length > 0) {
1044
- pail.info(`Native replacements (${String(natives.length)}):`);
1045
- for (const s of natives) {
1046
- pail.info(` ${s.hasCodemod ? "⚙" : " "} ${s.packageName} → ${s.replacement}`);
1047
- }
1048
- }
1049
- if (preferred.length > 0) {
1050
- pail.info(`
1051
- Preferred alternatives (${String(preferred.length)}):`);
1052
- for (const s of preferred) {
1053
- pail.info(` ${s.hasCodemod ? "⚙" : " "} ${s.packageName} → ${s.replacement}`);
1054
- }
1055
- }
1056
- if (micros.length > 0) {
1057
- pail.info(`
1058
- Micro-utilities (${String(micros.length)}):`);
1059
- for (const s of micros) {
1060
- pail.info(` ${s.hasCodemod ? "⚙" : " "} ${s.packageName} → ${s.replacement}`);
1061
- }
1062
- }
1063
- if (dedupedSocketEntries.length > 0) {
1064
- pail.info(`
1065
- Socket.dev overrides (${String(dedupedSocketEntries.length)}):`);
1066
- for (const s of dedupedSocketEntries) {
1067
- pail.info(` ${s.packageName} → ${s.overrideSpec}`);
1068
- }
1069
- }
1070
- pail.info(`
1071
- Total: ${String(allEntries.length)} optimizations available (⚙ = codemod available).`);
1072
- if (isDryRun) {
1073
- pail.notice("Run without --dry-run for interactive selection.");
1074
- }
1075
- };
1076
-
1077
- const handler = /*#__PURE__*/Object.defineProperty({
1078
- __proto__: null,
1079
- buildE18eEntries,
1080
- buildSocketEntries,
1081
- collectDepsFromPkgJson,
1082
- default: execute,
1083
- discoverWorkspacePackages,
1084
- markCodemodAvailability,
1085
- runCodemod
1086
- }, Symbol.toStringTag, { value: 'Module' });
1087
-
1088
- export { buildSocketEntries as a, buildE18eEntries as b, collectDepsFromPkgJson as c, discoverWorkspacePackages as d, applyOverrides as e, runCodemod as f, handler as h, markCodemodAvailability as m, readLockfileText as r };
1
+ var se=Object.defineProperty;var P=(e,r)=>se(e,"name",{value:r,configurable:!0});import{createRequire as le}from"node:module";import{isAccessibleSync as q,readFileSync as re}from"@visulima/fs";import{resolve as D,isAbsolute as W,relative as J,join as M,basename as fe}from"@visulima/path";import{Box as d,Text as c,ScrollView as he,ScrollBar as ge,useApp as pe,useWindowSize as me,useInput as we,render as ye}from"@visulima/tui";import{aA as xe,aB as H,aC as be,aD as Se,p as v,s as ve}from"./bin.js";import ke,{useSyncExternalStore as $e,useRef as A,useCallback as X}from"react";import{o as Pe}from"../packem_shared/index-DH-5hsrC.js";import{sortPackageJsonStringWithOptions as te}from"#native";import{jsxs as f,jsx as l,Fragment as Ee}from"react/jsx-runtime";import z from"ignore";import{f as N}from"../packem_shared/utils-DrNg0XTR.js";const ce=le(import.meta.url),F=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,ae=P(e=>{if(typeof F<"u"&&F.versions&&F.versions.node){const[r,t]=F.versions.node.split(".").map(Number);if(r>22||r===22&&t>=3||r===20&&t>=16)return F.getBuiltinModule(e)}return ce(e)},"__cjs_getBuiltinModule"),{readFileSync:de,writeFileSync:ue}=ae("node:fs");var Oe=Object.defineProperty,T=P((e,r)=>Oe(e,"name",{value:r,configurable:!0}),"i$2");const K={error:0,rewritten:1,"would-rewrite":1,unchanged:2},je=T(e=>[...e].sort((r,t)=>K[r.status]-K[t.status]),"sortByStatusRank"),Ce=T((e,r)=>r==="all"?e:r==="errors"?e.filter(t=>t.status==="error"):r==="rewritten"?e.filter(t=>t.status==="rewritten"||t.status==="would-rewrite"):e.filter(t=>t.status==="unchanged"),"filterEntries");class Ie{static{P(this,"a")}static{T(this,"SortPackageJsonStore")}#e;#r=new Set;constructor(r){this.#e={entries:je(r),filterType:"all",focusedPanel:"list",selectedIndex:0}}getSnapshot=T(()=>this.#e,"getSnapshot");subscribe=T(r=>(this.#r.add(r),()=>{this.#r.delete(r)}),"subscribe");getFilteredEntries=T(()=>Ce(this.#e.entries,this.#e.filterType),"getFilteredEntries");#t(){this.#e={...this.#e};for(const r of this.#r)r()}select(r){const t=this.getFilteredEntries();this.#e.selectedIndex=t.length===0?-1:Math.max(0,Math.min(r,t.length-1)),this.#t()}selectStep(r){this.select(this.#e.selectedIndex+r)}setFilter(r){this.#e.filterType=r,this.#e.selectedIndex=0,this.#t()}setFocusedPanel(r){this.#e.focusedPanel=r,this.#t()}}var Re=Object.defineProperty,Te=P((e,r)=>Re(e,"name",{value:r,configurable:!0}),"c$2");const Fe=Te(({checkMode:e,entry:r,focused:t,scrollRef:s})=>r?f(d,{borderColor:t?"white":"gray",borderStyle:"single",flexDirection:"column",flexGrow:1,children:[l(d,{flexShrink:0,paddingTop:1,paddingX:2,children:l(c,{bold:!0,color:"white",children:r.relativePath})}),f(he,{flexGrow:1,flexShrink:1,paddingX:2,ref:s,scrollbar:!0,scrollbarColor:"gray",children:[l(c,{}),f(d,{children:[l(d,{width:10,children:l(c,{dimColor:!0,children:"Status:"})}),r.status==="error"?l(c,{bold:!0,color:"red",children:"error"}):r.status==="unchanged"?l(c,{bold:!0,color:"green",children:"already sorted"}):r.status==="rewritten"?l(c,{bold:!0,color:"yellow",children:"rewritten"}):l(c,{bold:!0,color:"yellow",children:"would rewrite (--check)"})]}),f(d,{children:[l(d,{width:10,children:l(c,{dimColor:!0,children:"Path:"})}),l(c,{children:r.filePath})]}),r.error?f(Ee,{children:[f(d,{flexDirection:"column",marginTop:1,children:[l(c,{dimColor:!0,children:"── "}),l(c,{bold:!0,color:"red",children:"ERROR"}),f(d,{flexDirection:"column",marginTop:1,paddingLeft:2,children:[f(d,{children:[l(d,{width:10,children:l(c,{dimColor:!0,children:"Step:"})}),l(c,{color:"yellow",children:r.error.step})]}),r.error.context&&f(d,{children:[l(d,{width:10,children:l(c,{dimColor:!0,children:"Position:"})}),l(c,{children:`line ${String(r.error.context.line)}, column ${String(r.error.context.column)}`})]}),l(d,{marginTop:1,children:l(c,{color:"red",children:r.error.message})})]})]}),r.error.context&&r.error.context.snippet.length>0&&f(d,{flexDirection:"column",marginTop:1,children:[l(c,{dimColor:!0,children:"── "}),l(c,{bold:!0,color:"white",children:"SNIPPET"}),f(d,{flexDirection:"column",marginTop:1,paddingLeft:2,children:[r.error.context.snippet.map(o=>{const i=`${o.isErrorLine?"❯":" "} ${String(o.lineNumber).padStart(4)} `;return f(d,{children:[l(c,{color:o.isErrorLine?"red":"gray",children:i}),l(c,{color:o.isErrorLine?"white":"gray",wrap:"truncate-end",children:o.content||" "})]},o.lineNumber)}),r.error.context.column>0&&l(d,{children:l(c,{color:"red",children:`${" ".repeat(7+r.error.context.column-1)}↑`})})]})]})]}):f(d,{flexDirection:"column",marginTop:1,children:[l(c,{dimColor:!0,children:"── "}),l(c,{bold:!0,color:"white",children:"KEY DIFF"}),l(d,{flexDirection:"column",marginTop:1,paddingLeft:2,children:r.diff.length===0?l(c,{dimColor:!0,children:"No top-level keys moved (sub-key reorder only)."}):r.diff.map(o=>{const i=o.toIndex-o.fromIndex,a=i<0?`↑ ${String(Math.abs(i))}`:`↓ ${String(i)}`,g=i<0?"green":"yellow";return f(d,{children:[l(d,{width:28,children:l(c,{wrap:"truncate",children:o.key})}),l(d,{width:10,children:f(c,{dimColor:!0,children:[String(o.fromIndex)," → ",String(o.toIndex)]})}),l(c,{color:g,children:a})]},o.key)})}),e&&r.status==="would-rewrite"&&l(d,{marginTop:1,paddingLeft:2,children:l(c,{dimColor:!0,children:"--check mode: no write performed."})})]})]})]}):l(d,{alignItems:"center",borderColor:"gray",borderStyle:"single",flexDirection:"column",flexGrow:1,justifyContent:"center",children:l(c,{dimColor:!0,children:"No entry selected"})}),"SortDetailPanel");var Me=Object.defineProperty,O=P((e,r)=>Me(e,"name",{value:r,configurable:!0}),"i$1");const Ae={error:"red",rewritten:"yellow",unchanged:"green","would-rewrite":"yellow"},Ne={error:"ERROR",rewritten:"REWROTE",unchanged:"SORTED","would-rewrite":"REWRITE"},oe={error:"errors",rewritten:"rewrites",unchanged:"sorted","would-rewrite":"rewrites"},De={errors:"Errors",rewrites:"Rewrites",sorted:"Sorted"},Ge=[{count:O(e=>e.errors+e.rewrites+e.sorted,"count"),key:"all",label:"All",shortcut:"1"},{count:O(e=>e.rewrites,"count"),key:"rewritten",label:"Rewrites",shortcut:"2"},{count:O(e=>e.errors,"count"),key:"errors",label:"Errors",shortcut:"3"},{count:O(e=>e.sorted,"count"),key:"unchanged",label:"Sorted",shortcut:"4"}],ne=O(e=>{const r={errors:0,rewrites:0,sorted:0};for(const t of e)r[oe[t.status]]++;return r},"computeGroupCounts"),Be=O(({entry:e,isSelected:r})=>{const t=Ae[e.status],s=Ne[e.status];return f(d,{flexShrink:0,height:1,children:[l(c,{children:r?">":" "}),l(c,{children:" "}),l(c,{bold:!0,color:t,children:`[${s}]`.padEnd(10)}),l(c,{children:" "}),l(d,{flexGrow:1,children:l(c,{bold:r,inverse:r,wrap:"truncate",children:e.relativePath})}),e.status!=="error"&&e.diff.length>0&&l(c,{dimColor:!0,children:` ${String(e.diff.length)} key${e.diff.length===1?"":"s"}`})]})},"EntryRow"),Le=O(({color:e,count:r,label:t})=>l(d,{flexShrink:0,height:1,children:l(c,{bold:!0,color:e,children:`${t} (${String(r)})`})}),"SectionHeader"),Je=O(({counts:e,entries:r,filterType:t,focused:s,selectedIndex:n,totalEntries:o,viewportHeight:i})=>{const a=s?"white":"gray",g=ne(r),b=(g.errors>0?1:0)+(g.rewrites>0?1:0)+(g.sorted>0?1:0),w=t==="all"&&b>1,p=[];let m;for(const[u,y]of r.entries()){const S=oe[y.status];w&&S!==m&&(m!==void 0&&p.push({kind:"spacer"}),p.push({color:S==="errors"?"red":S==="rewrites"?"yellow":"green",count:g[S],kind:"header",label:De[S]}),m=S),p.push({entry:y,entryIndex:u,kind:"entry"})}const k=p.findIndex(u=>u.kind==="entry"&&u.entryIndex===n),$=k!==-1,E=p.length,h=Math.max(0,E-i);let C=0;$&&i>0&&(C=Math.min(h,Math.max(0,k-i+1)));const R=E>i&&i>0;return f(d,{borderColor:a,borderStyle:"single",flexDirection:"column",flexGrow:1,children:[f(d,{flexShrink:0,gap:1,paddingX:1,children:[l(c,{bold:!0,inverse:!0,children:" VIS SORT "}),f(c,{wrap:"truncate",children:[o," ","file",o===1?"":"s"]})]}),l(d,{flexShrink:0,gap:1,paddingX:1,paddingY:1,children:Ge.map(u=>{const y=t===u.key,S=u.count(e);return f(d,{children:[l(c,{dimColor:!y,children:"["}),l(c,{bold:y,color:y?"cyan":"gray",children:u.shortcut}),l(c,{dimColor:!y,children:"]"}),f(c,{color:y?"white":"gray",children:[" ",u.label]}),f(c,{dimColor:!0,children:[" ","(",S,")"]})]},u.key)})}),f(d,{flexDirection:"row",flexGrow:1,overflow:"hidden",children:[l(d,{flexDirection:"column",flexGrow:1,overflow:"hidden",paddingLeft:1,children:l(d,{flexDirection:"column",marginTop:-C,children:p.map((u,y)=>u.kind==="spacer"?l(d,{flexShrink:0,height:1},`s-${String(y)}`):u.kind==="header"?l(Le,{color:u.color,count:u.count,label:u.label},`h-${u.label}`):l(Be,{entry:u.entry,isSelected:u.entryIndex===n},u.entry.filePath))})}),R&&l(d,{flexShrink:0,marginLeft:1,marginRight:1,children:l(ge,{contentHeight:E,placement:"inset",scrollOffset:C,style:"block",viewportHeight:i})})]})]})},"SortListPanel");var _e=Object.defineProperty,qe=P((e,r)=>_e(e,"name",{value:r,configurable:!0}),"T");const We=100,V=10,He=6,Xe=1,Y={1:"all",2:"rewritten",3:"errors",4:"unchanged"},ze=qe(({checkMode:e,store:r})=>{const{exit:t}=pe(),{columns:s,rows:n}=me(),o=$e(r.subscribe,r.getSnapshot),i=A(null),a=r.getFilteredEntries(),g=a[o.selectedIndex]??null,b=ne(o.entries),w=s>=We,p=Math.max(0,n-Xe),m=w?p:Math.floor(p/2),k=Math.max(0,m-He),$=X(()=>{t()},[t]),E=A(0),h=A(void 0),C=A(!1),R=X((u,y)=>{E.current+=y,h.current=u,!C.current&&(C.current=!0,queueMicrotask(()=>{C.current=!1;const S=E.current,_=h.current;E.current=0,h.current=void 0,!(S===0||_===void 0)&&(_==="list"?r.selectStep(Math.sign(S)):i.current?.scrollBy(Math.sign(S)))}))},[r]);return we((u,y)=>{if(u==="q"||y.escape){$();return}if(Y[u]){r.setFilter(Y[u]);return}if(y.tab){r.setFocusedPanel(o.focusedPanel==="list"?"detail":"list");return}o.focusedPanel==="list"?y.upArrow||u==="k"?R("list",-1):(y.downArrow||u==="j")&&R("list",1):o.focusedPanel==="detail"&&(y.upArrow||u==="k"?R("detail",-1):(y.downArrow||u==="j")&&R("detail",1))}),n<V?l(d,{alignItems:"center",justifyContent:"center",children:f(c,{color:"yellow",children:["Terminal too small. Resize to at least",V," ","rows."]})}):f(d,{flexDirection:"column",height:n,width:s,children:[f(d,{flexDirection:w?"row":"column",flexGrow:1,children:[l(d,{flexBasis:"50%",flexGrow:1,flexShrink:1,children:l(Je,{counts:b,entries:a,filterType:o.filterType,focused:o.focusedPanel==="list",selectedIndex:o.selectedIndex,totalEntries:o.entries.length,viewportHeight:k})}),l(d,{flexBasis:"50%",flexGrow:1,flexShrink:1,children:l(Fe,{checkMode:e,entry:g,focused:o.focusedPanel==="detail",scrollRef:i})})]}),l(d,{flexShrink:0,paddingX:1,children:l(c,{dimColor:!0,children:"↑/↓ or j/k:navigate | tab:switch panel | 1-4:filter | q:quit"})})]})},"VisSortPackageJsonApp");var Ke=Object.defineProperty,j=P((e,r)=>Ke(e,"name",{value:r,configurable:!0}),"c$1");const U=["types","node-addons","node","import","require","default"],Ve=/^git\+https:\/\/github\.com\/([^/]+)\/([^/.]+(?:\.git)?)$/,Ye=/^git\+ssh:\/\/git@github\.com\/([^/]+)\/([^/.]+(?:\.git)?)$/,G=j(e=>typeof e=="object"&&e!==null&&!Array.isArray(e),"isPlainObject"),L=j(e=>{if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(t=>L(t));const r={};for(const[t,s]of Object.entries(e))r[t]=L(s);return r},"cloneDeep"),Ue=j(e=>{if(!G(e))return{changed:!1,value:e};const r=Object.keys(e);return r.length===1&&r[0]==="url"&&typeof e.url=="string"?{changed:!0,value:e.url}:{changed:!1,value:e}},"tryFormatBugs"),Qe=j(e=>e.endsWith(".git")?e.slice(0,-4):e,"stripGitSuffix"),Ze=j(e=>{if(!G(e))return{changed:!1,value:e};if(typeof e.directory=="string"&&e.directory.length>0)return{changed:!1,value:e};const{type:r}=e;if(r!==void 0&&r!=="git")return{changed:!1,value:e};const{url:t}=e;if(typeof t!="string")return{changed:!1,value:e};const s=Ve.exec(t)??Ye.exec(t);if(!s)return{changed:!1,value:e};const n=s[1],o=Qe(s[2]??"");if(!n||!o)return{changed:!1,value:e};const i=new Set(["type","url"]);for(const a of Object.keys(e))if(!i.has(a))return{changed:!1,value:e};return{changed:!0,value:`${n}/${o}`}},"tryFormatRepository"),er=j(e=>{const r=Object.keys(e),t=[],s=[];for(const i of U)Object.hasOwn(e,i)&&t.push(i);for(const i of r)U.includes(i)||s.push(i);const n=[...t,...s];if(n.length===r.length&&n.every((i,a)=>i===r[a]))return{changed:!1,value:e};const o={};for(const i of n)o[i]=e[i];return{changed:!0,value:o}},"orderConditions"),ie=j(e=>{if(!G(e))return{changed:!1,value:e};let r=!1;const t={};for(const[n,o]of Object.entries(e)){const i=ie(o);t[n]=i.value,i.changed&&(r=!0)}const s=er(t);return{changed:r||s.changed,value:s.value}},"sortExportsRecursive"),rr=j((e,r)=>{const t=L(e);let s=!1;if(r.formatBugs!==!1&&Object.hasOwn(t,"bugs")){const n=Ue(t.bugs);n.changed&&(t.bugs=n.value,s=!0)}if(r.formatRepository!==!1&&Object.hasOwn(t,"repository")){const n=Ze(t.repository);n.changed&&(t.repository=n.value,s=!0)}if(r.sortExports!==!1&&Object.hasOwn(t,"exports")&&G(t.exports)){const n=ie(t.exports);n.changed&&(t.exports=n.value,s=!0)}return{changed:s,pkg:t}},"formatPackageJsonFields");var tr=Object.defineProperty,I=P((e,r)=>tr(e,"name",{value:r,configurable:!0}),"i");const or=z.default??z,nr=[".git/","node_modules/"],ir=/\/+$/,Q=I(e=>{try{return de(e,"utf8")}catch{return}},"safeRead"),sr=I(e=>e.replaceAll("\\","/"),"toForwardSlashes"),lr=I(e=>{if(!e||e.length===0)return[];const r=[];for(const t of e){const s=t.replace(ir,"");if(s.startsWith("!")){const n=s.slice(1);n.length>0&&r.push(n)}}return r},"extractWorkspaceExcludePatterns"),cr=I(e=>{const{cwd:r}=e,t=or();if(e.builtinExcludes!==!1&&t.add(nr),e.rootGitignore!==!1){const o=Q(D(r,".gitignore"));o!==void 0&&t.add(o)}for(const o of e.extraIgnoreFiles??[]){const i=W(o)?o:D(r,o),a=Q(i);a!==void 0&&t.add(a)}e.extraPatterns&&e.extraPatterns.length>0&&t.add(e.extraPatterns);const s=I(o=>{const i=W(o)?o:D(r,o),a=sr(J(r,i));return a===""||a.startsWith("../")||a===".."?!1:t.ignores(a)},"ignores"),n={add:I(o=>(t.add(o),n),"add"),filter:I(o=>o.filter(i=>!s(i)),"filter"),ignores:s};return n},"buildGitignoreMatcher");var ar=Object.defineProperty,x=P((e,r)=>ar(e,"name",{value:r,configurable:!0}),"c");const dr=/at position (\d+)/,ur=/\(?line (\d+) column (\d+)\)?/,fr=x(e=>{const r=new Set,t=[],s=x(o=>{const i=D(o);!r.has(i)&&q(i)&&(r.add(i),t.push(i))},"addFile");s(M(e,"package.json"));const n=xe(e);if(n){const o=H(e,n);for(const i of o)s(M(e,i,"package.json"))}else{const o=M(e,"package.json");if(q(o)){const i=JSON.parse(re(o)),a=Array.isArray(i.workspaces)?i.workspaces:i.workspaces?.packages;if(a){const g=H(e,a);for(const b of g)s(M(e,b,"package.json"))}}}return t},"findPackageJsonFiles"),hr=x(e=>/\n([ \t]+)/.exec(e)?.[1]??" ","detectIndent"),gr=x(e=>{if(!(e===void 0||e===""))return e==="tab"||e===String.raw`\t`?" ":/^\d+$/.test(e)?" ".repeat(Number.parseInt(e,10)):e},"resolveIndentOverride"),B=x(e=>e===void 0?[]:(Array.isArray(e)?e:[e]).flatMap(r=>r.split(",")).map(r=>r.trim()).filter(r=>r.length>0),"splitList"),pr=x(e=>e.includes(`\r
2
+ `)?"crlf":"lf","detectLineEnding"),mr=new Set(["auto","crlf","lf"]),wr=x(e=>{if(e===void 0||e==="")return"auto";if(mr.has(e))return e;throw new Error(`--line-ending must be one of: auto, lf, crlf (got "${e}")`)},"validateLineEnding"),yr=x((e,r,t)=>r.length===0?e:e.filter(s=>{const n=J(t,s),o=fe(s);return!r.some(i=>{const a=i.includes("/")?n:o;return Pe(i,a)})}),"filterByIgnore"),xr=x((e,r)=>{if(r.length===0)return e;const t={},s=new Set;for(const n of r)Object.hasOwn(e,n)&&(t[n]=e[n],s.add(n));for(const n of Object.keys(e))s.has(n)||(t[n]=e[n]);return t},"applySortOrder"),br=x((e,r,t)=>{if(t.length===0)return e;const s={...e};for(const n of t)Object.hasOwn(r,n)&&(s[n]=r[n]);return s},"restoreUnsortedSections"),Sr=x((e,r)=>{let t=1,s=1;const n=Math.min(r,e.length);for(let o=0;o<n;o++)e.codePointAt(o)===10?(t++,s=1):s++;return{column:s,line:t}},"computeLineColumn"),Z=x((e,r,t=2)=>{const s=e.split(`
3
+ `);if(r<1||r>s.length)return[];const n=Math.max(0,r-1-t),o=Math.min(s.length,r+t),i=[];for(let a=n;a<o;a++)i.push({content:s[a]??"",isErrorLine:a+1===r,lineNumber:a+1});return i},"buildSnippet"),ee=x((e,r)=>{if(!(e instanceof Error))return;const t=dr.exec(e.message);if(t){const{column:n,line:o}=Sr(r,Number.parseInt(t[1]??"0",10));return{column:n,line:o,snippet:Z(r,o)}}const s=ur.exec(e.message);if(s){const n=Number.parseInt(s[1]??"1",10);return{column:Number.parseInt(s[2]??"1",10),line:n,snippet:Z(r,n)}}},"extractParseErrorContext"),vr=x((e,r)=>{const t=Object.keys(JSON.parse(e)),s=Object.keys(JSON.parse(r)),n=new Map(t.map((i,a)=>[i,a])),o=[];for(const[i,a]of s.entries()){const g=n.get(a);g!==void 0&&g!==i&&o.push({fromIndex:g,key:a,toIndex:i})}return o},"computeKeyDiff"),kr=x((e,r,t)=>{const s=r.indent??t.indent??hr(e),n=r.lineEnding==="auto"?t.lineEnding??pr(e):r.lineEnding,o=te(e,{pretty:!1,sortScripts:r.sortScripts});let i=JSON.parse(o);if(r.unsorted.length>0){const w=JSON.parse(e);i=br(i,w,r.unsorted)}i=xr(i,r.sortOrder);const a={formatBugs:r.formatBugs,formatRepository:r.formatRepository,sortExports:r.sortExports},g=rr(i,a);let b=JSON.stringify(g.pkg,null,s);return r.finalNewline&&(b+=`
4
+ `),n==="crlf"&&(b=b.replaceAll(`
5
+ `,`\r
6
+ `)),b},"sortContents"),$r=x((e,r)=>{const t=fr(e),s=be(e),n=cr({cwd:e,extraPatterns:lr(s)}),o=t.filter(a=>!n.ignores(a)),i=yr(o,r,e);return{afterGitignore:o,allFiles:t,files:i}},"discoverPackageJsonFiles"),Pr=x((e,{checkMode:r,cwd:t,normalized:s})=>{const n=J(t,e)||e;let o;try{o=re(e)}catch(w){return{diff:[],error:{message:N(w),step:"read"},filePath:e,relativePath:n,status:"error"}}let i;try{i=te(o,{pretty:!1,sortScripts:s.sortScripts})}catch(w){const p={message:N(w),step:"native-sort"},m=ee(w,o);return m&&(p.context=m),{diff:[],error:p,filePath:e,relativePath:n,status:"error"}}const a=s.editorconfig?Se(e):{};let g;try{g=kr(o,s,a)}catch(w){const p={message:N(w),step:"json-parse"},m=ee(w,o);return m&&(p.context=m),{diff:[],error:p,filePath:e,relativePath:n,status:"error"}}if(o===g)return{diff:[],filePath:e,relativePath:n,status:"unchanged"};let b;try{b=vr(o,i)}catch{b=[]}if(r)return{diff:b,filePath:e,relativePath:n,status:"would-rewrite"};try{ue(e,g,"utf8")}catch(w){return{diff:b,error:{message:N(w),step:"write"},filePath:e,relativePath:n,status:"error"}}return{diff:b,filePath:e,relativePath:n,status:"rewritten"}},"processFile"),Er=x(e=>{if(e.error&&(v.error(`${e.filePath}: ${e.error.message}`),v.info(` step: ${e.error.step}`),e.error.context)){v.info(` at line ${String(e.error.context.line)}, column ${String(e.error.context.column)}`);for(const r of e.error.context.snippet){const t=r.isErrorLine?">":" ";v.info(` ${t} ${String(r.lineNumber).padStart(4)} | ${r.content}`)}}},"printStaticError"),Br=x(async({options:e,visConfig:r,workspaceRoot:t})=>{const s=t??process.cwd(),n=r?.sortPackageJson,o=e.check||!1,i={editorconfig:e.editorconfig===!1?!1:n?.editorconfig??!0,finalNewline:e.finalNewline??n?.finalNewline??!0,formatBugs:e.formatBugs===!1?!1:n?.formatBugs??!0,formatRepository:e.formatRepository===!1?!1:n?.formatRepository??!0,ignore:[...B(e.ignore),...n?.ignore??[]],indent:gr(e.indent??n?.indent),lineEnding:wr(e.lineEnding??n?.lineEnding),sortExports:e.sortExports===!1?!1:n?.sortExports??!0,sortOrder:[...B(e.sortOrder),...n?.sortOrder??[]],sortScripts:e.sortScripts||n?.sortScripts||!1,unsorted:[...B(e.unsorted),...n?.unsorted??[]]},a=$r(s,i.ignore),{afterGitignore:g,allFiles:b,files:w}=a;if(w.length===0){b.length===0?v.info("No package.json files found."):g.length===0?v.info("All package.json files were excluded by .gitignore or workspace exclusions."):v.info("All package.json files were excluded by --ignore.");return}const p=[];for(const h of w)p.push(Pr(h,{checkMode:o,cwd:s,normalized:i}));let m=0,k=0,$=0;for(const h of p)h.status==="error"?$++:h.status==="rewritten"||h.status==="would-rewrite"?m++:k++;const E=m>0||$>0;if(process.stdout.isTTY&&!ve&&E){const h=new Ie(p);await ye(ke.createElement(ze,{checkMode:o,store:h}),{alternateScreen:!0,exitOnCtrlC:!1,interactive:!0,patchConsole:!0}).waitUntilExit()}else for(const h of p)switch(h.status){case"error":{Er(h);break}case"rewritten":{v.success(`Sorted ${h.filePath}`);break}case"would-rewrite":{v.warn(`${h.filePath} is not sorted`);break}}if(o)m>0?(v.info(`${String(m)} file${m===1?"":"s"} not sorted, ${String(k)} already sorted`),process.exitCode=1):$===0&&v.info(`All ${String(k)} package.json file${k===1?" is":"s are"} sorted`);else{const h=[];m>0&&h.push(`sorted ${String(m)} file${m===1?"":"s"}`),k>0&&h.push(`${String(k)} already sorted`),$>0&&h.push(`${String($)} error${$===1?"":"s"}`),h.length>0&&v.info(h.join(", "))}$>0&&(process.exitCode=1)},"execute");export{Z as buildSnippet,vr as computeKeyDiff,Sr as computeLineColumn,Br as default,$r as discoverPackageJsonFiles,ee as extractParseErrorContext,Pr as processFile};