@heleg/runpad 0.0.4 → 0.1.0

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 (4) hide show
  1. package/README.md +35 -18
  2. package/dist/index.mjs +639 -1594
  3. package/package.json +10 -2
  4. package/schema.json +73 -0
package/dist/index.mjs CHANGED
@@ -1,13 +1,155 @@
1
1
  #!/usr/bin/env node
2
- import { dirname, join, relative, resolve, sep } from "node:path";
2
+ import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
3
+ import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
3
4
  import { access, glob, readFile } from "node:fs/promises";
5
+ import { constants, homedir } from "node:os";
4
6
  import * as v from "valibot";
7
+ import { attempt, toResult } from "withstand";
5
8
  import { parse } from "yaml";
6
9
  import { minimatch } from "minimatch";
7
- import { execa } from "execa";
8
10
  import { Box, Text, render, useApp, useInput, useWindowSize } from "ink";
9
- import { createElement, useState } from "react";
11
+ import { useState } from "react";
12
+ import { stripVTControlCharacters, styleText } from "node:util";
10
13
  import { jsx, jsxs } from "react/jsx-runtime";
14
+ import wrapAnsi from "wrap-ansi";
15
+ import { execa } from "execa";
16
+ import { detectPackageManager } from "nypm";
17
+ // src/scriptRef.ts
18
+ const plainObject = (entries) => v.pipe(v.unknown(), v.check((input) => !Array.isArray(input), "Expected object"), v.object(entries));
19
+ /**
20
+ * How script refs are written in files: several scripts of one package
21
+ * in one entry, `{ "package": ".", "scripts": ["prepare", "schema"] }`.
22
+ */
23
+ const scriptGroupSchema = plainObject({
24
+ package: v.pipe(v.string(), v.description("Package directory relative to the config root, \".\" for the root package.")),
25
+ scripts: v.pipe(v.array(v.string()), v.description("Script names of this package, as written in package.json."))
26
+ });
27
+ /** Expands groups into one ref per script, keeping the order. */
28
+ const expandGroups = (groups) => groups.flatMap(({ package: pkg, scripts }) => scripts.map((script) => ({
29
+ package: pkg,
30
+ script
31
+ })));
32
+ /**
33
+ * Groups refs back for writing. Only neighbours of the same package are
34
+ * merged, so `expandGroups` restores the exact order.
35
+ */
36
+ const groupRefs = (refs) => {
37
+ const groups = [];
38
+ for (const { package: pkg, script } of refs) {
39
+ const last = groups.at(-1);
40
+ if (last?.package === pkg) last.scripts.push(script);
41
+ else groups.push({
42
+ package: pkg,
43
+ scripts: [script]
44
+ });
45
+ }
46
+ return groups;
47
+ };
48
+ // src/utils/isNodeError.ts
49
+ function isNodeError(error, code) {
50
+ return error instanceof Error && "code" in error && error.code === code;
51
+ }
52
+ // src/utils/isPlainObject.ts
53
+ const isPlainObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
54
+ // src/favoritesStore.ts
55
+ /**
56
+ * Favorites are personal, so they live in the user's config directory instead
57
+ * of the project: nothing to add to `.gitignore`. One file holds every
58
+ * project, keyed by the absolute path of its config root.
59
+ *
60
+ * - `$XDG_CONFIG_HOME/runpad/favorites.json` when set (any OS);
61
+ * - `%APPDATA%\runpad\favorites.json` on Windows;
62
+ * - `~/.config/runpad/favorites.json` otherwise, macOS included, as most CLI
63
+ * tools do there.
64
+ */
65
+ const getFavoritesPath = () => {
66
+ const { XDG_CONFIG_HOME: xdg, APPDATA: appData } = process.env;
67
+ let base = join(homedir(), ".config");
68
+ if (xdg && isAbsolute(xdg)) base = xdg;
69
+ else if (process.platform === "win32" && appData) base = appData;
70
+ return join(base, "runpad", "favorites.json");
71
+ };
72
+ const favoritesSchema = v.array(scriptGroupSchema);
73
+ const validateStore = (value, path) => {
74
+ if (!isPlainObject(value)) throw new Error(`Invalid ${path}: expected object`);
75
+ return value;
76
+ };
77
+ /**
78
+ * Reads favorites of one project. Only that project's entry is validated, so
79
+ * a broken entry of another project does not stop RunPad here.
80
+ */
81
+ const loadFavorites = async (rootDir) => {
82
+ const path = getFavoritesPath();
83
+ const readResult = await toResult(readFile(path, "utf8").then((text) => JSON.parse(text)));
84
+ if (!readResult.ok) {
85
+ if (isNodeError(readResult.error, "ENOENT")) return [];
86
+ throw new Error(`Failed to read ${path}`, { cause: readResult.error });
87
+ }
88
+ const entry = validateStore(readResult.value, path)[rootDir];
89
+ if (entry === void 0) return [];
90
+ const result = v.safeParse(favoritesSchema, entry);
91
+ if (!result.success) throw new Error(`Invalid favorites of ${rootDir} in ${path}: ${v.summarize(result.issues)}`);
92
+ return expandGroups(result.output);
93
+ };
94
+ /**
95
+ * Writes favorites of one project and keeps every other project untouched.
96
+ * Creates the file and its directory if missing; drops the project's entry
97
+ * when its list becomes empty.
98
+ *
99
+ * Synchronous on purpose: the file is tiny, and a blocking write means
100
+ * toggles land on disk in order and nothing is left half-written when the
101
+ * process exits right after a toggle. The write goes through a temp file and
102
+ * a rename, so a crash never corrupts favorites of other projects.
103
+ */
104
+ const saveFavorites = (rootDir, favorites) => {
105
+ const path = getFavoritesPath();
106
+ const readResult = attempt(() => JSON.parse(readFileSync(path, "utf8")));
107
+ let store = {};
108
+ if (readResult.ok) store = validateStore(readResult.value, path);
109
+ else if (!isNodeError(readResult.error, "ENOENT")) throw new Error(`Failed to read ${path}`, { cause: readResult.error });
110
+ const { [rootDir]: _previous, ...others } = store;
111
+ const next = favorites.length > 0 ? {
112
+ ...others,
113
+ [rootDir]: groupRefs(favorites)
114
+ } : others;
115
+ mkdirSync(dirname(path), { recursive: true });
116
+ const tempPath = `${path}.${process.pid}.tmp`;
117
+ writeFileSync(tempPath, `${JSON.stringify(next, null, 2)}\n`);
118
+ renameSync(tempPath, path);
119
+ };
120
+ // src/config/config.ts
121
+ let state;
122
+ const getState = () => {
123
+ if (!state) throw new Error("Config not initialized");
124
+ return state;
125
+ };
126
+ function setConfig(value, rootDir) {
127
+ state = {
128
+ config: value,
129
+ rootDir
130
+ };
131
+ }
132
+ function getConfig() {
133
+ return getState().config;
134
+ }
135
+ /**
136
+ * Updates favorites in memory and persists them synchronously.
137
+ * Throws if the write fails; the in-memory update is kept either way.
138
+ */
139
+ function setFavorites(favorites) {
140
+ const { config, rootDir } = getState();
141
+ state = {
142
+ rootDir,
143
+ config: {
144
+ ...config,
145
+ scripts: {
146
+ ...config.scripts,
147
+ favorites
148
+ }
149
+ }
150
+ };
151
+ saveFavorites(rootDir, favorites);
152
+ }
11
153
  // src/utils/packageJsonSchema.ts
12
154
  const packageJsonSchema = v.object({
13
155
  name: v.optional(v.string()),
@@ -18,36 +160,23 @@ const packageJsonSchema = v.object({
18
160
  nohoist: v.optional(v.array(v.string()))
19
161
  })]))
20
162
  });
21
- // src/utils/safe-try.ts
22
- function failure(error) {
163
+ // src/utils/toWorkspacePatterns.ts
164
+ const normalize = (pattern) => pattern.replace(/\/{2,}/g, "/").replace(/^(\.\/)+/, "").replace(/(.)\/+$/, "$1") || ".";
165
+ const isExclusion = (pattern) => pattern.startsWith("!") && !pattern.startsWith("!(");
166
+ /** Converts patterns as written in a workspace config. */
167
+ const toWorkspacePatterns = (raw) => {
168
+ const include = [];
169
+ const exclude = [];
170
+ for (const pattern of raw) if (isExclusion(pattern)) exclude.push(normalize(pattern.slice(1)));
171
+ else include.push(normalize(pattern));
23
172
  return {
24
- ok: false,
25
- error: error instanceof Error ? error : new Error(String(error))
173
+ include,
174
+ exclude
26
175
  };
27
- }
28
- function attempt(fn) {
29
- try {
30
- return {
31
- ok: true,
32
- value: fn()
33
- };
34
- } catch (error) {
35
- return failure(error);
36
- }
37
- }
38
- async function toResult(promise) {
39
- try {
40
- return {
41
- ok: true,
42
- value: await promise
43
- };
44
- } catch (error) {
45
- return failure(error);
46
- }
47
- }
176
+ };
48
177
  // src/getWorkspacePatterns.ts
49
178
  const pnpmWorkspaceSchema = v.object({ packages: v.array(v.string()) });
50
- const getWorkspacePatterns = async (cwd) => {
179
+ const readWorkspacePatterns = async (cwd) => {
51
180
  const yamlPath = join(cwd, "pnpm-workspace.yaml");
52
181
  const yamlResult = await toResult(readFile(yamlPath, "utf8"));
53
182
  if (yamlResult.ok) {
@@ -68,13 +197,20 @@ const getWorkspacePatterns = async (cwd) => {
68
197
  if (Array.isArray(workspaces)) return workspaces;
69
198
  return workspaces?.packages ?? null;
70
199
  };
200
+ /**
201
+ * Workspace patterns declared in `cwd`, or `null` if `cwd` is not a
202
+ * workspace root. The only place raw pattern strings are read.
203
+ */
204
+ const getWorkspacePatterns = async (cwd) => {
205
+ const raw = await readWorkspacePatterns(cwd);
206
+ return raw ? toWorkspacePatterns(raw) : null;
207
+ };
71
208
  // src/isPartOfWorkspace.ts
72
209
  const isPartOfWorkspace = ({ patterns, root, cwd }) => {
73
210
  const path = relative(root, cwd).split(sep).join("/");
74
211
  if (!path) return false;
75
- const included = patterns.some((pattern) => !pattern.startsWith("!") && minimatch(path, pattern));
76
- const excluded = patterns.some((pattern) => pattern.startsWith("!") && minimatch(path, pattern.slice(1)));
77
- return included && !excluded;
212
+ const matches = (pattern) => minimatch(path, pattern, { nonegate: true });
213
+ return patterns.include.some(matches) && !patterns.exclude.some(matches);
78
214
  };
79
215
  // src/utils/getParentOrNull.ts
80
216
  const getParentOrNull = (directory) => {
@@ -98,8 +234,135 @@ const findWorkspaceRoot = async (packageRoot) => {
98
234
  const parent = getParentOrNull(packageRoot);
99
235
  return parent ? searchRecursive(parent, packageRoot) : null;
100
236
  };
237
+ /** Team settings, committed to the repository. */
238
+ const sharedSchema = plainObject({ scripts: v.optional(plainObject({
239
+ hidden: v.optional(v.pipe(v.array(scriptGroupSchema), v.description("Scripts left out of the lists.")), []),
240
+ pinned: v.optional(v.pipe(v.array(scriptGroupSchema), v.description("Scripts shown at the top for the whole team.")), [])
241
+ }), {}) });
242
+ /**
243
+ * Reads one config file and validates it with its own schema.
244
+ * Returns `undefined` if the file is missing.
245
+ */
246
+ const readConfigFile = async (rootDir, fileName, schema) => {
247
+ const configPath = join(rootDir, fileName);
248
+ const configJsonResult = await toResult(readFile(configPath, "utf8").then((text) => JSON.parse(text)));
249
+ if (!configJsonResult.ok) {
250
+ if (isNodeError(configJsonResult.error, "ENOENT")) return;
251
+ throw new Error(`Failed to read ${configPath}`, { cause: configJsonResult.error });
252
+ }
253
+ const result = v.safeParse(schema, configJsonResult.value);
254
+ if (!result.success) throw new Error(`Invalid ${fileName}: ${v.summarize(result.issues)}`);
255
+ return result.output;
256
+ };
257
+ /**
258
+ * Loads team settings from `runpad.config.json` and personal favorites from
259
+ * the user's config directory (see `getFavoritesPath`).
260
+ */
261
+ const loadConfig = async (rootDir) => {
262
+ const shared = await readConfigFile(rootDir, "runpad.config.json", sharedSchema) ?? v.parse(sharedSchema, {});
263
+ return { scripts: {
264
+ hidden: expandGroups(shared.scripts.hidden),
265
+ pinned: expandGroups(shared.scripts.pinned),
266
+ favorites: await loadFavorites(rootDir)
267
+ } };
268
+ };
269
+ // src/utils/favorites.ts
270
+ /** Package key stored in config: posix path relative to root, "." for root. */
271
+ const toPackageKey = (root, directory) => relative(root, directory).split(sep).join("/") || ".";
272
+ /** Stable id of a package + script pair. */
273
+ const refId = (ref) => `${ref.package}\0${ref.script}`;
274
+ const isSame = (a, b) => refId(a) === refId(b);
275
+ /** Removes the favorite if present, otherwise appends it. */
276
+ const toggleFavorite = (favorites, favorite) => favorites.some((item) => isSame(item, favorite)) ? favorites.filter((item) => !isSame(item, favorite)) : [...favorites, favorite];
277
+ /** Script names of the given package from a ref list, in config order. */
278
+ const favoritesFor = (favorites, packageKey) => favorites.filter((favorite) => favorite.package === packageKey).map((favorite) => favorite.script);
279
+ /** Refs from `refs` that are not in `removed`, order kept. */
280
+ const withoutRefs = (refs, removed) => {
281
+ const removedIds = new Set(removed.map(refId));
282
+ return refs.filter((ref) => !removedIds.has(refId(ref)));
283
+ };
284
+ /**
285
+ * Resolves refs (pinned or favorites) against existing packages. Refs whose
286
+ * package or script no longer exists are skipped, duplicates keep the
287
+ * first occurrence.
288
+ */
289
+ const resolveFavorites = (favorites, packages) => {
290
+ const seen = /* @__PURE__ */ new Set();
291
+ return favorites.flatMap((favorite) => {
292
+ const id = refId(favorite);
293
+ const pkg = packages.find((item) => item.key === favorite.package);
294
+ if (seen.has(id) || !pkg || !Object.hasOwn(pkg.scripts, favorite.script)) return [];
295
+ seen.add(id);
296
+ return [{
297
+ favorite,
298
+ pkg,
299
+ script: pkg.scripts[favorite.script] ?? ""
300
+ }];
301
+ });
302
+ };
303
+ // src/utils/orderScripts.ts
304
+ /**
305
+ * Orders scripts as: favorites (local config order, pinned or not), then
306
+ * pinned that are not favorites (shared config order), then the rest in
307
+ * package.json order. Names missing from `scripts` are ignored.
308
+ *
309
+ * Hidden scripts are left out, and are not pinned either. A favorite is
310
+ * always shown: the user's own choice beats the shared config. With
311
+ * `showHidden` nothing is left out, hidden rows are only flagged.
312
+ */
313
+ const orderScripts = (scripts, favorites, pinned = [], hidden = [], showHidden = false) => {
314
+ const exists = (name) => Object.hasOwn(scripts, name);
315
+ const favoriteSet = new Set(favorites.filter(exists));
316
+ const hiddenSet = new Set(hidden.filter((name) => !favoriteSet.has(name)));
317
+ const pinnedSet = new Set(pinned.filter((name) => exists(name) && (showHidden || !hidden.includes(name))));
318
+ const isListed = (name) => showHidden || !hiddenSet.has(name);
319
+ return [
320
+ ...favoriteSet,
321
+ ...[...pinnedSet].filter((name) => !favoriteSet.has(name)),
322
+ ...Object.keys(scripts).filter((name) => !pinnedSet.has(name) && !favoriteSet.has(name) && isListed(name))
323
+ ].map((name) => ({
324
+ name,
325
+ script: scripts[name] ?? "",
326
+ isPinned: pinnedSet.has(name),
327
+ isFavorite: favoriteSet.has(name),
328
+ isHidden: hiddenSet.has(name)
329
+ }));
330
+ };
331
+ // src/utils/toDisplayText.ts
332
+ const CONTROL_CHARACTERS = /[\u0000-\u0009\u000B-\u001F\u007F-\u009F]/g;
333
+ /**
334
+ * Makes text from package.json safe to print in the terminal. A foreign
335
+ * package.json could otherwise clear the screen, set the window title, or
336
+ * hide part of a command behind "\r". Only for display: script names are
337
+ * still run as written.
338
+ */
339
+ const toDisplayText = (text) => stripVTControlCharacters(text).replace(/\r\n?/g, "\n").replace(/\t/g, " ").replace(CONTROL_CHARACTERS, "");
101
340
  // src/components/Command.tsx
102
- const Command = ({ isSelected, name, script }) => {
341
+ const PIN = "⚑";
342
+ const STAR = "★";
343
+ const PINNED_COLOR = "cyan";
344
+ const FAVORITE_COLOR = "yellow";
345
+ /** Whether any entry of a list has a marker. */
346
+ const hasMarkers = (entries) => entries.some((entry) => entry.isPinned || entry.isFavorite);
347
+ const marker = (isPinned, isFavorite) => {
348
+ if (isPinned) return {
349
+ symbol: PIN,
350
+ color: isFavorite ? FAVORITE_COLOR : PINNED_COLOR
351
+ };
352
+ if (isFavorite) return {
353
+ symbol: STAR,
354
+ color: FAVORITE_COLOR
355
+ };
356
+ return {
357
+ symbol: " ",
358
+ color: void 0
359
+ };
360
+ };
361
+ const Command = ({ isSelected, name, script, isFavorite = false, isPinned = false, showMarker = false, packageName, isRootPackage = false, isHidden = false }) => {
362
+ const cursor = isSelected ? "▸ " : " ";
363
+ const nameColor = isSelected ? "greenBright" : "green";
364
+ const scriptColor = isSelected ? "blueBright" : "blue";
365
+ const { symbol, color } = marker(isPinned, isFavorite);
103
366
  return /* @__PURE__ */ jsx(Box, {
104
367
  width: "100%",
105
368
  height: 1,
@@ -109,35 +372,65 @@ const Command = ({ isSelected, name, script }) => {
109
372
  children: [
110
373
  /* @__PURE__ */ jsx(Text, {
111
374
  color: "green",
112
- children: isSelected ? "▸ " : " "
375
+ children: cursor
376
+ }),
377
+ showMarker && /* @__PURE__ */ jsxs(Text, {
378
+ color,
379
+ children: [symbol, " "]
380
+ }),
381
+ packageName !== void 0 && /* @__PURE__ */ jsxs(Text, {
382
+ color: "magenta",
383
+ dimColor: isHidden,
384
+ children: [
385
+ toDisplayText(packageName),
386
+ isRootPackage && /* @__PURE__ */ jsx(Text, {
387
+ bold: true,
388
+ children: " [root]"
389
+ }),
390
+ " › "
391
+ ]
113
392
  }),
114
393
  /* @__PURE__ */ jsx(Text, {
115
394
  bold: isSelected,
116
- color: isSelected ? "greenBright" : "green",
117
- children: name
395
+ color: nameColor,
396
+ dimColor: isHidden,
397
+ children: toDisplayText(name)
398
+ }),
399
+ /* @__PURE__ */ jsx(Text, {
400
+ dimColor: isHidden,
401
+ children: "\xA0:\xA0"
118
402
  }),
119
- /* @__PURE__ */ jsx(Text, { children: "\xA0:\xA0" }),
120
403
  /* @__PURE__ */ jsx(Text, {
121
404
  bold: isSelected,
122
- color: isSelected ? "blueBright" : "blue",
123
- children: script.replace(/\s+/g, " ")
405
+ color: scriptColor,
406
+ dimColor: isHidden,
407
+ children: toDisplayText(script).replace(/\s+/g, " ")
124
408
  })
125
409
  ]
126
410
  })
127
411
  });
128
412
  };
129
413
  // src/components/package/useKeyInput.ts
130
- const useKeyInput = ({ scripts, onSelect, pageSize, onPreview, isActive = true }) => {
414
+ const useKeyInput = ({ scriptNames, onSelect, pageSize, onPreview, onToggleFavorite, onToggleHidden, isActive = true }) => {
131
415
  const [selectedIndex, setSelectedIndex] = useState(0);
132
416
  const { exit } = useApp();
133
- const scriptNames = Object.keys(scripts);
134
417
  const visibleRows = pageSize;
135
- const scriptCount = Object.keys(scripts).length;
418
+ const scriptCount = scriptNames.length;
136
419
  useInput((input, key) => {
420
+ const letter = input.toLowerCase();
137
421
  if (input === " ") {
138
422
  if (scriptNames[selectedIndex] !== void 0) onPreview();
139
423
  return;
140
424
  }
425
+ if (letter === "f") {
426
+ const script = scriptNames[selectedIndex];
427
+ if (script !== void 0) setSelectedIndex(onToggleFavorite(script));
428
+ return;
429
+ }
430
+ if (letter === "h") {
431
+ setSelectedIndex(onToggleHidden(scriptNames[selectedIndex]));
432
+ return;
433
+ }
141
434
  if (key.upArrow) setSelectedIndex((i) => Math.max(0, i - 1));
142
435
  if (key.downArrow) setSelectedIndex((i) => Math.max(0, Math.min(scriptCount - 1, i + 1)));
143
436
  if (key.return) {
@@ -149,1433 +442,10 @@ const useKeyInput = ({ scripts, onSelect, pageSize, onPreview, isActive = true }
149
442
  }
150
443
  if (key.leftArrow) setSelectedIndex((i) => Math.max(0, i - visibleRows));
151
444
  if (key.rightArrow) setSelectedIndex((i) => i + visibleRows < scriptCount ? i + visibleRows : i);
152
- if (key.escape || input === "q") exit();
445
+ if (key.escape || letter === "q") exit();
153
446
  }, { isActive });
154
447
  return { selectedIndex };
155
448
  };
156
- // node_modules/ansi-regex/index.js
157
- const ST = String.raw`(?:\u001B\u005C|\u009C)`;
158
- const stringControls = String.raw`\u0018\u001A\u001B\u0080-\u009F`;
159
- const osc = String.raw`(?:\u001B\]|\u009D)[^\u0007${stringControls}]*(?:\u0007|${ST})`;
160
- const controlString = String.raw`(?:\u001B[PX^_k]|[\u0090\u0098\u009E\u009F])[^${stringControls}]*${ST}`;
161
- const pattern = `${String.raw`\u001B\](?:P[\dA-Fa-f]{7}|R)(?:\u0007|${ST})?`}|${osc}|${controlString}|${String.raw`(?:\u001B\[|\u009B)[\u0030-\u003F]*[\u0020-\u002F]*[\u0040-\u007E]`}|${String.raw`\u001B(?:[\u0020-\u002F]+[\u0030-\u007E]|[\dA-PR-TZcf-oq-uy=><~|}])`}`;
162
- function ansiRegex({ onlyFirst = false } = {}) {
163
- return new RegExp(pattern, onlyFirst ? void 0 : "g");
164
- }
165
- // node_modules/strip-ansi/index.js
166
- const regex = ansiRegex();
167
- function stripAnsi(string) {
168
- if (typeof string !== "string") throw new TypeError(`Expected a \`string\`, got \`${typeof string}\``);
169
- if (!string.includes("\x1B") && !string.includes("›")) return string;
170
- return string.replace(regex, "");
171
- }
172
- const ambiguousRanges = [
173
- 161,
174
- 161,
175
- 164,
176
- 164,
177
- 167,
178
- 168,
179
- 170,
180
- 170,
181
- 173,
182
- 174,
183
- 176,
184
- 180,
185
- 182,
186
- 186,
187
- 188,
188
- 191,
189
- 198,
190
- 198,
191
- 208,
192
- 208,
193
- 215,
194
- 216,
195
- 222,
196
- 225,
197
- 230,
198
- 230,
199
- 232,
200
- 234,
201
- 236,
202
- 237,
203
- 240,
204
- 240,
205
- 242,
206
- 243,
207
- 247,
208
- 250,
209
- 252,
210
- 252,
211
- 254,
212
- 254,
213
- 257,
214
- 257,
215
- 273,
216
- 273,
217
- 275,
218
- 275,
219
- 283,
220
- 283,
221
- 294,
222
- 295,
223
- 299,
224
- 299,
225
- 305,
226
- 307,
227
- 312,
228
- 312,
229
- 319,
230
- 322,
231
- 324,
232
- 324,
233
- 328,
234
- 331,
235
- 333,
236
- 333,
237
- 338,
238
- 339,
239
- 358,
240
- 359,
241
- 363,
242
- 363,
243
- 462,
244
- 462,
245
- 464,
246
- 464,
247
- 466,
248
- 466,
249
- 468,
250
- 468,
251
- 470,
252
- 470,
253
- 472,
254
- 472,
255
- 474,
256
- 474,
257
- 476,
258
- 476,
259
- 593,
260
- 593,
261
- 609,
262
- 609,
263
- 708,
264
- 708,
265
- 711,
266
- 711,
267
- 713,
268
- 715,
269
- 717,
270
- 717,
271
- 720,
272
- 720,
273
- 728,
274
- 731,
275
- 733,
276
- 733,
277
- 735,
278
- 735,
279
- 768,
280
- 879,
281
- 913,
282
- 929,
283
- 931,
284
- 937,
285
- 945,
286
- 961,
287
- 963,
288
- 969,
289
- 1025,
290
- 1025,
291
- 1040,
292
- 1103,
293
- 1105,
294
- 1105,
295
- 8208,
296
- 8208,
297
- 8211,
298
- 8214,
299
- 8216,
300
- 8217,
301
- 8220,
302
- 8221,
303
- 8224,
304
- 8226,
305
- 8228,
306
- 8231,
307
- 8240,
308
- 8240,
309
- 8242,
310
- 8243,
311
- 8245,
312
- 8245,
313
- 8251,
314
- 8251,
315
- 8254,
316
- 8254,
317
- 8308,
318
- 8308,
319
- 8319,
320
- 8319,
321
- 8321,
322
- 8324,
323
- 8364,
324
- 8364,
325
- 8451,
326
- 8451,
327
- 8453,
328
- 8453,
329
- 8457,
330
- 8457,
331
- 8467,
332
- 8467,
333
- 8470,
334
- 8470,
335
- 8481,
336
- 8482,
337
- 8486,
338
- 8486,
339
- 8491,
340
- 8491,
341
- 8531,
342
- 8532,
343
- 8539,
344
- 8542,
345
- 8544,
346
- 8555,
347
- 8560,
348
- 8569,
349
- 8585,
350
- 8585,
351
- 8592,
352
- 8601,
353
- 8632,
354
- 8633,
355
- 8658,
356
- 8658,
357
- 8660,
358
- 8660,
359
- 8679,
360
- 8679,
361
- 8704,
362
- 8704,
363
- 8706,
364
- 8707,
365
- 8711,
366
- 8712,
367
- 8715,
368
- 8715,
369
- 8719,
370
- 8719,
371
- 8721,
372
- 8721,
373
- 8725,
374
- 8725,
375
- 8730,
376
- 8730,
377
- 8733,
378
- 8736,
379
- 8739,
380
- 8739,
381
- 8741,
382
- 8741,
383
- 8743,
384
- 8748,
385
- 8750,
386
- 8750,
387
- 8756,
388
- 8759,
389
- 8764,
390
- 8765,
391
- 8776,
392
- 8776,
393
- 8780,
394
- 8780,
395
- 8786,
396
- 8786,
397
- 8800,
398
- 8801,
399
- 8804,
400
- 8807,
401
- 8810,
402
- 8811,
403
- 8814,
404
- 8815,
405
- 8834,
406
- 8835,
407
- 8838,
408
- 8839,
409
- 8853,
410
- 8853,
411
- 8857,
412
- 8857,
413
- 8869,
414
- 8869,
415
- 8895,
416
- 8895,
417
- 8978,
418
- 8978,
419
- 9312,
420
- 9449,
421
- 9451,
422
- 9547,
423
- 9552,
424
- 9587,
425
- 9600,
426
- 9615,
427
- 9618,
428
- 9621,
429
- 9632,
430
- 9633,
431
- 9635,
432
- 9641,
433
- 9650,
434
- 9651,
435
- 9654,
436
- 9655,
437
- 9660,
438
- 9661,
439
- 9664,
440
- 9665,
441
- 9670,
442
- 9672,
443
- 9675,
444
- 9675,
445
- 9678,
446
- 9681,
447
- 9698,
448
- 9701,
449
- 9711,
450
- 9711,
451
- 9733,
452
- 9734,
453
- 9737,
454
- 9737,
455
- 9742,
456
- 9743,
457
- 9756,
458
- 9756,
459
- 9758,
460
- 9758,
461
- 9792,
462
- 9792,
463
- 9794,
464
- 9794,
465
- 9824,
466
- 9825,
467
- 9827,
468
- 9829,
469
- 9831,
470
- 9834,
471
- 9836,
472
- 9837,
473
- 9839,
474
- 9839,
475
- 9886,
476
- 9887,
477
- 9919,
478
- 9919,
479
- 9926,
480
- 9933,
481
- 9935,
482
- 9939,
483
- 9941,
484
- 9953,
485
- 9955,
486
- 9955,
487
- 9960,
488
- 9961,
489
- 9963,
490
- 9969,
491
- 9972,
492
- 9972,
493
- 9974,
494
- 9977,
495
- 9979,
496
- 9980,
497
- 9982,
498
- 9983,
499
- 10045,
500
- 10045,
501
- 10102,
502
- 10111,
503
- 11094,
504
- 11097,
505
- 12872,
506
- 12879,
507
- 57344,
508
- 63743,
509
- 65024,
510
- 65039,
511
- 65533,
512
- 65533,
513
- 127232,
514
- 127242,
515
- 127248,
516
- 127277,
517
- 127280,
518
- 127337,
519
- 127344,
520
- 127373,
521
- 127375,
522
- 127376,
523
- 127387,
524
- 127404,
525
- 917760,
526
- 917999,
527
- 983040,
528
- 1048573,
529
- 1048576,
530
- 1114109
531
- ];
532
- const fullwidthRanges = [
533
- 12288,
534
- 12288,
535
- 65281,
536
- 65376,
537
- 65504,
538
- 65510
539
- ];
540
- const wideRanges = [
541
- 4352,
542
- 4447,
543
- 8986,
544
- 8987,
545
- 9001,
546
- 9002,
547
- 9193,
548
- 9196,
549
- 9200,
550
- 9200,
551
- 9203,
552
- 9203,
553
- 9725,
554
- 9726,
555
- 9748,
556
- 9749,
557
- 9776,
558
- 9783,
559
- 9800,
560
- 9811,
561
- 9855,
562
- 9855,
563
- 9866,
564
- 9871,
565
- 9875,
566
- 9875,
567
- 9889,
568
- 9889,
569
- 9898,
570
- 9899,
571
- 9917,
572
- 9918,
573
- 9924,
574
- 9925,
575
- 9934,
576
- 9934,
577
- 9940,
578
- 9940,
579
- 9962,
580
- 9962,
581
- 9970,
582
- 9971,
583
- 9973,
584
- 9973,
585
- 9978,
586
- 9978,
587
- 9981,
588
- 9981,
589
- 9989,
590
- 9989,
591
- 9994,
592
- 9995,
593
- 10024,
594
- 10024,
595
- 10060,
596
- 10060,
597
- 10062,
598
- 10062,
599
- 10067,
600
- 10069,
601
- 10071,
602
- 10071,
603
- 10133,
604
- 10135,
605
- 10160,
606
- 10160,
607
- 10175,
608
- 10175,
609
- 11035,
610
- 11036,
611
- 11088,
612
- 11088,
613
- 11093,
614
- 11093,
615
- 11904,
616
- 11929,
617
- 11931,
618
- 12019,
619
- 12032,
620
- 12245,
621
- 12272,
622
- 12287,
623
- 12289,
624
- 12350,
625
- 12353,
626
- 12438,
627
- 12441,
628
- 12543,
629
- 12549,
630
- 12591,
631
- 12593,
632
- 12686,
633
- 12688,
634
- 12773,
635
- 12783,
636
- 12830,
637
- 12832,
638
- 12871,
639
- 12880,
640
- 42124,
641
- 42128,
642
- 42182,
643
- 43360,
644
- 43388,
645
- 44032,
646
- 55203,
647
- 63744,
648
- 64255,
649
- 65040,
650
- 65049,
651
- 65072,
652
- 65106,
653
- 65108,
654
- 65126,
655
- 65128,
656
- 65131,
657
- 94176,
658
- 94180,
659
- 94192,
660
- 94198,
661
- 94208,
662
- 101594,
663
- 101631,
664
- 101664,
665
- 101760,
666
- 101874,
667
- 101888,
668
- 102801,
669
- 102816,
670
- 102866,
671
- 110576,
672
- 110579,
673
- 110581,
674
- 110587,
675
- 110589,
676
- 110590,
677
- 110592,
678
- 110888,
679
- 110898,
680
- 110898,
681
- 110928,
682
- 110930,
683
- 110933,
684
- 110933,
685
- 110948,
686
- 110952,
687
- 110960,
688
- 111355,
689
- 119552,
690
- 119638,
691
- 119648,
692
- 119670,
693
- 126980,
694
- 126980,
695
- 127183,
696
- 127183,
697
- 127374,
698
- 127374,
699
- 127377,
700
- 127386,
701
- 127406,
702
- 127406,
703
- 127488,
704
- 127490,
705
- 127504,
706
- 127547,
707
- 127552,
708
- 127560,
709
- 127568,
710
- 127569,
711
- 127584,
712
- 127589,
713
- 127744,
714
- 127776,
715
- 127789,
716
- 127797,
717
- 127799,
718
- 127868,
719
- 127870,
720
- 127891,
721
- 127904,
722
- 127946,
723
- 127951,
724
- 127955,
725
- 127968,
726
- 127984,
727
- 127988,
728
- 127988,
729
- 127992,
730
- 128062,
731
- 128064,
732
- 128064,
733
- 128066,
734
- 128252,
735
- 128255,
736
- 128317,
737
- 128331,
738
- 128334,
739
- 128336,
740
- 128359,
741
- 128378,
742
- 128378,
743
- 128405,
744
- 128406,
745
- 128420,
746
- 128420,
747
- 128507,
748
- 128591,
749
- 128640,
750
- 128709,
751
- 128716,
752
- 128716,
753
- 128720,
754
- 128722,
755
- 128725,
756
- 128729,
757
- 128732,
758
- 128735,
759
- 128747,
760
- 128748,
761
- 128756,
762
- 128764,
763
- 128986,
764
- 128986,
765
- 128992,
766
- 129003,
767
- 129008,
768
- 129008,
769
- 129292,
770
- 129338,
771
- 129340,
772
- 129349,
773
- 129351,
774
- 129535,
775
- 129648,
776
- 129660,
777
- 129664,
778
- 129734,
779
- 129736,
780
- 129736,
781
- 129740,
782
- 129757,
783
- 129759,
784
- 129771,
785
- 129775,
786
- 129786,
787
- 131072,
788
- 196605,
789
- 196608,
790
- 262141
791
- ];
792
- // node_modules/get-east-asian-width/utilities.js
793
- /**
794
- Binary search on a sorted flat array of [start, end] pairs.
795
-
796
- @param {number[]} ranges - Flat array of inclusive [start, end] range pairs, e.g. [0, 5, 10, 20].
797
- @param {number} codePoint - The value to search for.
798
- @returns {boolean} Whether the value falls within any of the ranges.
799
- */
800
- const isInRange = (ranges, codePoint) => {
801
- let low = 0;
802
- let high = Math.floor(ranges.length / 2) - 1;
803
- while (low <= high) {
804
- const mid = Math.floor((low + high) / 2);
805
- const i = mid * 2;
806
- if (codePoint < ranges[i]) high = mid - 1;
807
- else if (codePoint > ranges[i + 1]) low = mid + 1;
808
- else return true;
809
- }
810
- return false;
811
- };
812
- // node_modules/get-east-asian-width/lookup.js
813
- const commonCjkCodePoint = 19968;
814
- const [wideFastPathStart, wideFastPathEnd] = /* #__PURE__ */ findWideFastPathRange(wideRanges);
815
- function findWideFastPathRange(ranges) {
816
- let fastPathStart = ranges[0];
817
- let fastPathEnd = ranges[1];
818
- for (let index = 0; index < ranges.length; index += 2) {
819
- const start = ranges[index];
820
- const end = ranges[index + 1];
821
- if (commonCjkCodePoint >= start && commonCjkCodePoint <= end) return [start, end];
822
- if (end - start > fastPathEnd - fastPathStart) {
823
- fastPathStart = start;
824
- fastPathEnd = end;
825
- }
826
- }
827
- return [fastPathStart, fastPathEnd];
828
- }
829
- const isAmbiguous = (codePoint) => {
830
- if (codePoint < 161 || codePoint > 1114109) return false;
831
- return isInRange(ambiguousRanges, codePoint);
832
- };
833
- const isFullwidth = (codePoint) => {
834
- if (codePoint < 12288 || codePoint > 65510) return false;
835
- return isInRange(fullwidthRanges, codePoint);
836
- };
837
- const isWide = (codePoint) => {
838
- if (codePoint >= wideFastPathStart && codePoint <= wideFastPathEnd) return true;
839
- if (codePoint < 4352 || codePoint > 262141) return false;
840
- return isInRange(wideRanges, codePoint);
841
- };
842
- // node_modules/get-east-asian-width/index.js
843
- function validate(codePoint) {
844
- if (!Number.isSafeInteger(codePoint)) throw new TypeError(`Expected a code point, got \`${typeof codePoint}\`.`);
845
- }
846
- function eastAsianWidth(codePoint, { ambiguousAsWide = false } = {}) {
847
- validate(codePoint);
848
- if (isFullwidth(codePoint) || isWide(codePoint) || ambiguousAsWide && isAmbiguous(codePoint)) return 2;
849
- return 1;
850
- }
851
- // node_modules/string-width/index.js
852
- /**
853
- Logic:
854
- - Segment graphemes to match how terminals render clusters.
855
- - Width rules:
856
- 1. Skip non-printing clusters (Default_Ignorable, Control, pure nonspacing/enclosing Mark, lone Surrogates). Tabs are ignored by design.
857
- 2. RGI emoji clusters (\p{RGI_Emoji}) are double-width.
858
- 3. Minimally-qualified/unqualified emoji clusters (ZWJ sequences with 2+ Extended_Pictographic, or keycap sequences) are double-width.
859
- 4. Hangul jamo collapse each standard modern Hangul L+V or L+V+T syllable piece to width 2.
860
- Unmatched repeated leading/vowel/trailing jamo stay additive because that matches how the terminals we target render them.
861
- 5. Otherwise use East Asian Width of the cluster's first visible code point, and add widths for trailing spacing marks and Halfwidth/Fullwidth Forms within the same cluster (e.g., dakuten/handakuten/prolonged sound mark).
862
- */
863
- const segmenter$1 = new Intl.Segmenter();
864
- const visibleCharacterRegex = /[^\p{Default_Ignorable_Code_Point}\p{Control}\p{Format}\p{Nonspacing_Mark}\p{Enclosing_Mark}\p{Surrogate}]/v;
865
- const spacingMarkRegex = /\p{Spacing_Mark}/v;
866
- const rgiEmojiRegex = /^\p{RGI_Emoji}$/v;
867
- const unqualifiedKeycapRegex = /^[\d#*]\u20E3$/;
868
- const extendedPictographicRegex = /\p{Extended_Pictographic}/gu;
869
- function isDoubleWidthNonRgiEmojiSequence(segment) {
870
- if (segment.length > 50) return false;
871
- if (unqualifiedKeycapRegex.test(segment)) return true;
872
- if (segment.includes("‍")) {
873
- const pictographics = segment.match(extendedPictographicRegex);
874
- return pictographics !== null && pictographics.length >= 2;
875
- }
876
- return false;
877
- }
878
- function baseVisible(segment) {
879
- const index = segment.search(visibleCharacterRegex);
880
- return index === -1 ? void 0 : segment.slice(index);
881
- }
882
- function isHangulLeadingJamo(codePoint) {
883
- return codePoint >= 4352 && codePoint <= 4447 || codePoint >= 43360 && codePoint <= 43388;
884
- }
885
- function isHangulVowelJamo(codePoint) {
886
- return codePoint >= 4448 && codePoint <= 4519 || codePoint >= 55216 && codePoint <= 55238;
887
- }
888
- function isHangulTrailingJamo(codePoint) {
889
- return codePoint >= 4520 && codePoint <= 4607 || codePoint >= 55243 && codePoint <= 55291;
890
- }
891
- function isHangulJamo(codePoint) {
892
- return isHangulLeadingJamo(codePoint) || isHangulVowelJamo(codePoint) || isHangulTrailingJamo(codePoint);
893
- }
894
- function hangulClusterWidth(visibleSegment, eastAsianWidthOptions) {
895
- const codePoints = [];
896
- for (const character of visibleSegment) {
897
- if (!visibleCharacterRegex.test(character)) continue;
898
- codePoints.push(character.codePointAt(0));
899
- }
900
- if (codePoints.length === 0) return;
901
- let width = 0;
902
- for (let index = 0; index < codePoints.length; index++) {
903
- const codePoint = codePoints[index];
904
- if (!isHangulJamo(codePoint)) {
905
- if (width === 0) return;
906
- for (let remaining = index; remaining < codePoints.length; remaining++) width += eastAsianWidth(codePoints[remaining], eastAsianWidthOptions);
907
- return width;
908
- }
909
- if (isHangulLeadingJamo(codePoint) && isHangulVowelJamo(codePoints[index + 1])) {
910
- width += 2;
911
- index += isHangulTrailingJamo(codePoints[index + 2]) ? 2 : 1;
912
- continue;
913
- }
914
- width += eastAsianWidth(codePoint, eastAsianWidthOptions);
915
- }
916
- return width;
917
- }
918
- function trailingWidth(visibleSegment, eastAsianWidthOptions) {
919
- let extra = 0;
920
- let first = true;
921
- for (const character of visibleSegment) {
922
- if (first) {
923
- first = false;
924
- continue;
925
- }
926
- if (spacingMarkRegex.test(character) || character >= "＀" && character <= "￯") extra += eastAsianWidth(character.codePointAt(0), eastAsianWidthOptions);
927
- }
928
- return extra;
929
- }
930
- function stringWidth(input, options = {}) {
931
- if (typeof input !== "string" || input.length === 0) return 0;
932
- const { ambiguousIsNarrow = true, countAnsiEscapeCodes = false } = options;
933
- let string = input;
934
- if (!countAnsiEscapeCodes && (string.includes("\x1B") || string.includes("›"))) string = stripAnsi(string);
935
- if (string.length === 0) return 0;
936
- if (/^[\u0020-\u007E]*$/.test(string)) return string.length;
937
- let width = 0;
938
- const eastAsianWidthOptions = { ambiguousAsWide: !ambiguousIsNarrow };
939
- for (const { segment } of segmenter$1.segment(string)) {
940
- const visibleSegment = baseVisible(segment);
941
- if (visibleSegment === void 0) continue;
942
- if (rgiEmojiRegex.test(segment) || isDoubleWidthNonRgiEmojiSequence(segment)) {
943
- width += 2;
944
- continue;
945
- }
946
- const hangulWidth = hangulClusterWidth(visibleSegment, eastAsianWidthOptions);
947
- if (hangulWidth !== void 0) {
948
- width += hangulWidth;
949
- continue;
950
- }
951
- const codePoint = visibleSegment.codePointAt(0);
952
- width += eastAsianWidth(codePoint, eastAsianWidthOptions);
953
- width += trailingWidth(visibleSegment, eastAsianWidthOptions);
954
- }
955
- return width;
956
- }
957
- // node_modules/wrap-ansi/node_modules/ansi-styles/index.js
958
- const ANSI_BACKGROUND_OFFSET = 10;
959
- const wrapAnsi16 = (offset = 0) => (code) => `\u001B[${code + offset}m`;
960
- const wrapAnsi256 = (offset = 0) => (code) => `\u001B[${38 + offset};5;${code}m`;
961
- const wrapAnsi16m = (offset = 0) => (red, green, blue) => `\u001B[${38 + offset};2;${red};${green};${blue}m`;
962
- const styles = {
963
- modifier: {
964
- reset: [0, 0],
965
- bold: [1, 22],
966
- dim: [2, 22],
967
- italic: [3, 23],
968
- underline: [4, 24],
969
- overline: [53, 55],
970
- inverse: [7, 27],
971
- hidden: [8, 28],
972
- strikethrough: [9, 29]
973
- },
974
- color: {
975
- black: [30, 39],
976
- red: [31, 39],
977
- green: [32, 39],
978
- yellow: [33, 39],
979
- blue: [34, 39],
980
- magenta: [35, 39],
981
- cyan: [36, 39],
982
- white: [37, 39],
983
- blackBright: [90, 39],
984
- gray: [90, 39],
985
- grey: [90, 39],
986
- redBright: [91, 39],
987
- greenBright: [92, 39],
988
- yellowBright: [93, 39],
989
- blueBright: [94, 39],
990
- magentaBright: [95, 39],
991
- cyanBright: [96, 39],
992
- whiteBright: [97, 39]
993
- },
994
- bgColor: {
995
- bgBlack: [40, 49],
996
- bgRed: [41, 49],
997
- bgGreen: [42, 49],
998
- bgYellow: [43, 49],
999
- bgBlue: [44, 49],
1000
- bgMagenta: [45, 49],
1001
- bgCyan: [46, 49],
1002
- bgWhite: [47, 49],
1003
- bgBlackBright: [100, 49],
1004
- bgGray: [100, 49],
1005
- bgGrey: [100, 49],
1006
- bgRedBright: [101, 49],
1007
- bgGreenBright: [102, 49],
1008
- bgYellowBright: [103, 49],
1009
- bgBlueBright: [104, 49],
1010
- bgMagentaBright: [105, 49],
1011
- bgCyanBright: [106, 49],
1012
- bgWhiteBright: [107, 49]
1013
- }
1014
- };
1015
- Object.keys(styles.modifier);
1016
- const foregroundColorNames = Object.keys(styles.color);
1017
- const backgroundColorNames = Object.keys(styles.bgColor);
1018
- [...foregroundColorNames, ...backgroundColorNames];
1019
- function assembleStyles() {
1020
- const codes = /* @__PURE__ */ new Map();
1021
- for (const [groupName, group] of Object.entries(styles)) {
1022
- for (const [styleName, style] of Object.entries(group)) {
1023
- styles[styleName] = {
1024
- open: `\u001B[${style[0]}m`,
1025
- close: `\u001B[${style[1]}m`
1026
- };
1027
- group[styleName] = styles[styleName];
1028
- codes.set(style[0], style[1]);
1029
- }
1030
- Object.defineProperty(styles, groupName, {
1031
- value: group,
1032
- enumerable: false
1033
- });
1034
- }
1035
- Object.defineProperty(styles, "codes", {
1036
- value: codes,
1037
- enumerable: false
1038
- });
1039
- styles.color.close = "\x1B[39m";
1040
- styles.bgColor.close = "\x1B[49m";
1041
- styles.color.ansi = wrapAnsi16();
1042
- styles.color.ansi256 = wrapAnsi256();
1043
- styles.color.ansi16m = wrapAnsi16m();
1044
- styles.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET);
1045
- styles.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET);
1046
- styles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET);
1047
- Object.defineProperties(styles, {
1048
- rgbToAnsi256: {
1049
- value(red, green, blue) {
1050
- if (red === green && green === blue) {
1051
- if (red < 8) return 16;
1052
- if (red > 248) return 231;
1053
- return Math.round((red - 8) / 247 * 24) + 232;
1054
- }
1055
- return 16 + 36 * Math.round(red / 255 * 5) + 6 * Math.round(green / 255 * 5) + Math.round(blue / 255 * 5);
1056
- },
1057
- enumerable: false
1058
- },
1059
- hexToRgb: {
1060
- value(hex) {
1061
- const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16));
1062
- if (!matches) return [
1063
- 0,
1064
- 0,
1065
- 0
1066
- ];
1067
- let [colorString] = matches;
1068
- if (colorString.length === 3) colorString = [...colorString].map((character) => character + character).join("");
1069
- const integer = Number.parseInt(colorString, 16);
1070
- return [
1071
- integer >> 16 & 255,
1072
- integer >> 8 & 255,
1073
- integer & 255
1074
- ];
1075
- },
1076
- enumerable: false
1077
- },
1078
- hexToAnsi256: {
1079
- value: (hex) => styles.rgbToAnsi256(...styles.hexToRgb(hex)),
1080
- enumerable: false
1081
- },
1082
- ansi256ToAnsi: {
1083
- value(code) {
1084
- if (code < 8) return 30 + code;
1085
- if (code < 16) return 90 + (code - 8);
1086
- let red;
1087
- let green;
1088
- let blue;
1089
- if (code >= 232) {
1090
- red = ((code - 232) * 10 + 8) / 255;
1091
- green = red;
1092
- blue = red;
1093
- } else {
1094
- code -= 16;
1095
- const remainder = code % 36;
1096
- red = Math.floor(code / 36) / 5;
1097
- green = Math.floor(remainder / 6) / 5;
1098
- blue = remainder % 6 / 5;
1099
- }
1100
- const value = Math.max(red, green, blue) * 2;
1101
- if (value === 0) return 30;
1102
- let result = 30 + (Math.round(blue) << 2 | Math.round(green) << 1 | Math.round(red));
1103
- if (value === 2) result += 60;
1104
- return result;
1105
- },
1106
- enumerable: false
1107
- },
1108
- rgbToAnsi: {
1109
- value: (red, green, blue) => styles.ansi256ToAnsi(styles.rgbToAnsi256(red, green, blue)),
1110
- enumerable: false
1111
- },
1112
- hexToAnsi: {
1113
- value: (hex) => styles.ansi256ToAnsi(styles.hexToAnsi256(hex)),
1114
- enumerable: false
1115
- }
1116
- });
1117
- return styles;
1118
- }
1119
- const ansiStyles = assembleStyles();
1120
- // node_modules/wrap-ansi/index.js
1121
- const ANSI_ESCAPE = "\x1B";
1122
- const ANSI_ESCAPE_BELL = "\x07";
1123
- const C1_CSI = "›";
1124
- const ANSI_CSI = "[";
1125
- const ANSI_OSC = "]";
1126
- const ANSI_SGR_TERMINATOR = "m";
1127
- const ANSI_SGR_RESET = 0;
1128
- const ANSI_SGR_RESET_FOREGROUND = 39;
1129
- const ANSI_SGR_RESET_BACKGROUND = 49;
1130
- const ANSI_SGR_RESET_UNDERLINE_COLOR = 59;
1131
- const ANSI_SGR_FOREGROUND_EXTENDED = 38;
1132
- const ANSI_SGR_BACKGROUND_EXTENDED = 48;
1133
- const ANSI_SGR_UNDERLINE_COLOR_EXTENDED = 58;
1134
- const ANSI_SGR_COLOR_MODE_RGB = 2;
1135
- const ANSI_SGR_COLOR_MODE_256 = 5;
1136
- const ANSI_ESCAPE_LINK = `${ANSI_OSC}8;`;
1137
- const ESCAPES = /* @__PURE__ */ new Set([ANSI_ESCAPE, C1_CSI]);
1138
- const ESCAPE_CHARACTERS = [...ESCAPES].join("");
1139
- const CSI_INTRODUCER = `(?:${ANSI_ESCAPE}\\${ANSI_CSI}|${C1_CSI})`;
1140
- const CSI_PARAMETERS = "[0-?]*[ -/]*[@-~]";
1141
- const SGR_PARAMETERS = `(?<sgr>[0-9;:]*)${ANSI_SGR_TERMINATOR}`;
1142
- const OSC_STRING_TERMINATOR = `(?:${ANSI_ESCAPE_BELL}|${ANSI_ESCAPE}\\\\)`;
1143
- const OSC_STRING_PAYLOAD = String.raw`[^\u0000-\u001F\u007F-\u009F]*`;
1144
- const LINK_PARAMETERS = String.raw`8;(?<parameters>[^;\u0000-\u001F\u007F-\u009F]*);(?<uri>${OSC_STRING_PAYLOAD})${OSC_STRING_TERMINATOR}`;
1145
- const OSC_STRING = `${OSC_STRING_PAYLOAD}${OSC_STRING_TERMINATOR}`;
1146
- const ANSI_ESCAPE_REGEX = new RegExp(`${CSI_INTRODUCER}(?:${SGR_PARAMETERS}|${CSI_PARAMETERS})|${ANSI_ESCAPE}\\${ANSI_OSC}(?:${LINK_PARAMETERS}|${OSC_STRING})`, "y");
1147
- const ANSI_SGR_MODIFIER_CLOSE_CODES = new Set(ansiStyles.codes.values());
1148
- ANSI_SGR_MODIFIER_CLOSE_CODES.delete(ANSI_SGR_RESET);
1149
- const segmenter = new Intl.Segmenter();
1150
- const getStringWidth = (string) => stringWidth(string, { countAnsiEscapeCodes: true });
1151
- const TAB_SIZE = 8;
1152
- const ESCAPE_INTRODUCER_REGEX = new RegExp(`[${ESCAPE_CHARACTERS}]`, "g");
1153
- const ROW_BOUNDARY_REGEX = new RegExp(`[\\n${ESCAPE_CHARACTERS}]`, "g");
1154
- const ASCII_PRINTABLE_REGEX = /^[ -~]*$/;
1155
- const wrapAnsiCode = (code) => `${ANSI_ESCAPE}${ANSI_CSI}${code}${ANSI_SGR_TERMINATOR}`;
1156
- const wrapAnsiHyperlink = (url, parameters = "") => `${ANSI_ESCAPE}${ANSI_ESCAPE_LINK}${parameters};${url}${ANSI_ESCAPE_BELL}`;
1157
- const matchAnsiEscape = (string, index) => {
1158
- if (!ESCAPES.has(string[index])) return;
1159
- ANSI_ESCAPE_REGEX.lastIndex = index;
1160
- return ANSI_ESCAPE_REGEX.exec(string) ?? void 0;
1161
- };
1162
- const forEachSegment = (string, onPlainText, onEscape = () => {}) => {
1163
- let plainStart = 0;
1164
- let index = 0;
1165
- while (index < string.length) {
1166
- ESCAPE_INTRODUCER_REGEX.lastIndex = index;
1167
- const introducer = ESCAPE_INTRODUCER_REGEX.exec(string);
1168
- if (!introducer) break;
1169
- const escape = matchAnsiEscape(string, introducer.index);
1170
- if (!escape) {
1171
- index = introducer.index + 1;
1172
- continue;
1173
- }
1174
- if (introducer.index > plainStart) onPlainText(string.slice(plainStart, introducer.index));
1175
- onEscape(escape[0]);
1176
- index = introducer.index + escape[0].length;
1177
- plainStart = index;
1178
- }
1179
- if (plainStart < string.length) onPlainText(string.slice(plainStart));
1180
- };
1181
- const getWidth = (string) => {
1182
- let plainText = "";
1183
- forEachSegment(string, (part) => {
1184
- plainText += part;
1185
- });
1186
- return getStringWidth(plainText);
1187
- };
1188
- const getTokens = (string) => {
1189
- const tokens = [];
1190
- forEachSegment(string, (plainText) => {
1191
- if (ASCII_PRINTABLE_REGEX.test(plainText)) {
1192
- for (const character of plainText) tokens.push({
1193
- value: character,
1194
- width: 1
1195
- });
1196
- return;
1197
- }
1198
- for (const { segment } of segmenter.segment(plainText)) tokens.push({
1199
- value: segment,
1200
- width: getStringWidth(segment)
1201
- });
1202
- }, (escape) => {
1203
- tokens.push({
1204
- value: escape,
1205
- width: 0
1206
- });
1207
- });
1208
- return tokens;
1209
- };
1210
- const splitWords = (string) => {
1211
- let currentWord = {
1212
- value: "",
1213
- plainText: ""
1214
- };
1215
- const words = [currentWord];
1216
- forEachSegment(string, (plainText) => {
1217
- const parts = plainText.split(" ");
1218
- currentWord.value += parts[0];
1219
- currentWord.plainText += parts[0];
1220
- for (let index = 1; index < parts.length; index++) {
1221
- currentWord = {
1222
- value: parts[index],
1223
- plainText: parts[index]
1224
- };
1225
- words.push(currentWord);
1226
- }
1227
- }, (escape) => {
1228
- currentWord.value += escape;
1229
- });
1230
- for (const word of words) word.width = getStringWidth(word.plainText);
1231
- return words;
1232
- };
1233
- const getColonColorToken = (parameter) => {
1234
- const parts = parameter.split(":");
1235
- const code = Number.parseInt(parts[0], 10);
1236
- const mode = Number.parseInt(parts[1], 10);
1237
- if (![
1238
- ANSI_SGR_FOREGROUND_EXTENDED,
1239
- ANSI_SGR_BACKGROUND_EXTENDED,
1240
- ANSI_SGR_UNDERLINE_COLOR_EXTENDED
1241
- ].includes(code)) return;
1242
- if (mode === ANSI_SGR_COLOR_MODE_256 && parts.length === 3 && /^\d+$/.test(parts[2])) return {
1243
- code,
1244
- open: parameter,
1245
- hasArguments: true
1246
- };
1247
- if (mode !== ANSI_SGR_COLOR_MODE_RGB) return;
1248
- const components = parts.length === 6 ? parts.slice(3) : parts.slice(2);
1249
- const colorSpace = parts.length === 6 ? parts[2] : void 0;
1250
- if (components.length === 3 && components.every((component) => /^\d+$/.test(component)) && (colorSpace === void 0 || /^\d*$/.test(colorSpace))) return {
1251
- code,
1252
- open: parameter,
1253
- hasArguments: true
1254
- };
1255
- };
1256
- const getSgrTokens = (sgrParameters) => {
1257
- const parameters = sgrParameters.split(";");
1258
- const sgrTokens = [];
1259
- for (let index = 0; index < parameters.length; index++) {
1260
- const parameter = parameters[index];
1261
- if (parameter.includes(":")) {
1262
- const colonColorToken = getColonColorToken(parameter);
1263
- if (colonColorToken) sgrTokens.push(colonColorToken);
1264
- continue;
1265
- }
1266
- const code = parameter === "" ? ANSI_SGR_RESET : Number.parseInt(parameter, 10);
1267
- if (!Number.isFinite(code)) continue;
1268
- if (code === ANSI_SGR_FOREGROUND_EXTENDED || code === ANSI_SGR_BACKGROUND_EXTENDED || code === ANSI_SGR_UNDERLINE_COLOR_EXTENDED) {
1269
- if (index + 1 >= parameters.length) break;
1270
- const mode = Number.parseInt(parameters[index + 1], 10);
1271
- const colorIndex = Number.parseInt(parameters[index + 2], 10);
1272
- if (mode === ANSI_SGR_COLOR_MODE_256 && Number.isFinite(colorIndex)) {
1273
- sgrTokens.push({
1274
- code,
1275
- open: [
1276
- code,
1277
- mode,
1278
- colorIndex
1279
- ].join(";"),
1280
- hasArguments: true
1281
- });
1282
- index += 2;
1283
- continue;
1284
- }
1285
- const red = Number.parseInt(parameters[index + 2], 10);
1286
- const green = Number.parseInt(parameters[index + 3], 10);
1287
- const blue = Number.parseInt(parameters[index + 4], 10);
1288
- if (mode === ANSI_SGR_COLOR_MODE_RGB && Number.isFinite(red) && Number.isFinite(green) && Number.isFinite(blue)) {
1289
- sgrTokens.push({
1290
- code,
1291
- open: [
1292
- code,
1293
- mode,
1294
- red,
1295
- green,
1296
- blue
1297
- ].join(";"),
1298
- hasArguments: true
1299
- });
1300
- index += 4;
1301
- continue;
1302
- }
1303
- break;
1304
- }
1305
- sgrTokens.push({
1306
- code,
1307
- open: String(code),
1308
- hasArguments: false
1309
- });
1310
- }
1311
- return sgrTokens;
1312
- };
1313
- const removeActiveStyle = (activeStyles, family) => {
1314
- const activeStyleIndex = activeStyles.findIndex((activeStyle) => activeStyle.family === family);
1315
- if (activeStyleIndex !== -1) activeStyles.splice(activeStyleIndex, 1);
1316
- };
1317
- const upsertActiveStyle = (activeStyles, nextActiveStyle) => {
1318
- removeActiveStyle(activeStyles, nextActiveStyle.family);
1319
- activeStyles.push(nextActiveStyle);
1320
- };
1321
- const removeModifierStylesByClose = (activeStyles, closeCode) => {
1322
- for (let index = activeStyles.length - 1; index >= 0; index--) {
1323
- const activeStyle = activeStyles[index];
1324
- if (activeStyle.family.startsWith("modifier-") && activeStyle.close === closeCode) activeStyles.splice(index, 1);
1325
- }
1326
- };
1327
- const getColorStyle = (sgrToken) => {
1328
- const { code, open, hasArguments } = sgrToken;
1329
- if (code >= 30 && code <= 37 || code >= 90 && code <= 97 || code === ANSI_SGR_FOREGROUND_EXTENDED && hasArguments) return {
1330
- family: "foreground",
1331
- open,
1332
- close: ANSI_SGR_RESET_FOREGROUND
1333
- };
1334
- if (code >= 40 && code <= 47 || code >= 100 && code <= 107 || code === ANSI_SGR_BACKGROUND_EXTENDED && hasArguments) return {
1335
- family: "background",
1336
- open,
1337
- close: ANSI_SGR_RESET_BACKGROUND
1338
- };
1339
- if (code === ANSI_SGR_UNDERLINE_COLOR_EXTENDED && hasArguments) return {
1340
- family: "underlineColor",
1341
- open,
1342
- close: ANSI_SGR_RESET_UNDERLINE_COLOR
1343
- };
1344
- };
1345
- const applySgrResetCode = (code, activeStyles) => {
1346
- if (code === ANSI_SGR_RESET) {
1347
- activeStyles.length = 0;
1348
- return true;
1349
- }
1350
- if (code === ANSI_SGR_RESET_FOREGROUND) {
1351
- removeActiveStyle(activeStyles, "foreground");
1352
- return true;
1353
- }
1354
- if (code === ANSI_SGR_RESET_BACKGROUND) {
1355
- removeActiveStyle(activeStyles, "background");
1356
- return true;
1357
- }
1358
- if (code === ANSI_SGR_RESET_UNDERLINE_COLOR) {
1359
- removeActiveStyle(activeStyles, "underlineColor");
1360
- return true;
1361
- }
1362
- if (ANSI_SGR_MODIFIER_CLOSE_CODES.has(code)) {
1363
- removeModifierStylesByClose(activeStyles, code);
1364
- return true;
1365
- }
1366
- return false;
1367
- };
1368
- const applySgrToken = (sgrToken, activeStyles) => {
1369
- const { code } = sgrToken;
1370
- if (applySgrResetCode(code, activeStyles)) return;
1371
- const colorStyle = getColorStyle(sgrToken);
1372
- if (colorStyle) {
1373
- upsertActiveStyle(activeStyles, colorStyle);
1374
- return;
1375
- }
1376
- const close = ansiStyles.codes.get(code);
1377
- if (close !== void 0 && close !== ANSI_SGR_RESET) upsertActiveStyle(activeStyles, {
1378
- family: `modifier-${code}`,
1379
- open: sgrToken.open,
1380
- close
1381
- });
1382
- };
1383
- const applySgrParameters = (sgrParameters, activeStyles) => {
1384
- for (const sgrToken of getSgrTokens(sgrParameters)) applySgrToken(sgrToken, activeStyles);
1385
- };
1386
- const applySgrResets = (sgrParameters, activeStyles) => {
1387
- for (const { code } of getSgrTokens(sgrParameters)) applySgrResetCode(code, activeStyles);
1388
- };
1389
- const applyLeadingSgrResets = (string, startIndex, activeStyles) => {
1390
- let index = startIndex;
1391
- while (index < string.length) {
1392
- const match = matchAnsiEscape(string, index);
1393
- if (!match) break;
1394
- if (match.groups.sgr !== void 0) applySgrResets(match.groups.sgr, activeStyles);
1395
- index += match[0].length;
1396
- }
1397
- };
1398
- const getClosingSgrSequence = (activeStyles) => [...activeStyles].reverse().map((activeStyle) => wrapAnsiCode(activeStyle.close)).join("");
1399
- const getOpeningSgrSequence = (activeStyles) => activeStyles.map((activeStyle) => wrapAnsiCode(activeStyle.open)).join("");
1400
- const wrapWord = (rows, word, columns, rowWidth) => {
1401
- const tokens = getTokens(word);
1402
- let visible = rowWidth;
1403
- for (let index = 0; index < tokens.length; index++) {
1404
- const token = tokens[index];
1405
- if (token.width > 0 && visible > 0 && visible + token.width > columns) {
1406
- rows.push("");
1407
- visible = 0;
1408
- }
1409
- rows[rows.length - 1] += token.value;
1410
- visible += token.width;
1411
- if (visible === columns && index < tokens.length - 1) {
1412
- rows.push("");
1413
- visible = 0;
1414
- }
1415
- }
1416
- if (!visible && rows.at(-1).length > 0 && rows.length > 1) rows[rows.length - 2] += rows.pop();
1417
- return getWidth(rows.at(-1));
1418
- };
1419
- const stringVisibleTrimSpacesRight = (string) => {
1420
- if (!string.includes(" ")) return string;
1421
- const segments = [];
1422
- forEachSegment(string, (plainText) => {
1423
- segments.push({
1424
- value: plainText,
1425
- isEscape: false
1426
- });
1427
- }, (escape) => {
1428
- segments.push({
1429
- value: escape,
1430
- isEscape: true
1431
- });
1432
- });
1433
- for (let index = segments.length - 1; index >= 0; index--) {
1434
- const segment = segments[index];
1435
- if (segment.isEscape) continue;
1436
- let end = segment.value.length;
1437
- while (end > 0 && segment.value[end - 1] === " ") end--;
1438
- segment.value = segment.value.slice(0, end);
1439
- if (getStringWidth(segment.value) > 0) break;
1440
- }
1441
- return segments.map((segment) => segment.value).join("");
1442
- };
1443
- const expandTabs = (line) => {
1444
- if (!line.includes(" ")) return line;
1445
- let visible = 0;
1446
- let expandedLine = "";
1447
- let plainTextSinceTab = "";
1448
- const expandPlainText = (plainText) => {
1449
- const segments = plainText.split(" ");
1450
- for (const [index, segment] of segments.entries()) {
1451
- expandedLine += segment;
1452
- plainTextSinceTab += segment;
1453
- if (index < segments.length - 1) {
1454
- visible += getStringWidth(plainTextSinceTab);
1455
- plainTextSinceTab = "";
1456
- const spaces = TAB_SIZE - visible % TAB_SIZE;
1457
- expandedLine += " ".repeat(spaces);
1458
- visible += spaces;
1459
- }
1460
- }
1461
- };
1462
- forEachSegment(line, expandPlainText, (escape) => {
1463
- expandedLine += escape;
1464
- });
1465
- return expandedLine;
1466
- };
1467
- const restoreStylesAcrossRows = (preString) => {
1468
- let returnValue = "";
1469
- let activeHyperlink;
1470
- const activeStyles = [];
1471
- let index = 0;
1472
- let copiedIndex = 0;
1473
- while (index < preString.length) {
1474
- ROW_BOUNDARY_REGEX.lastIndex = index;
1475
- const boundary = ROW_BOUNDARY_REGEX.exec(preString);
1476
- if (!boundary) break;
1477
- index = boundary.index;
1478
- if (boundary[0] !== "\n") {
1479
- const escape = matchAnsiEscape(preString, index);
1480
- if (!escape) {
1481
- index++;
1482
- continue;
1483
- }
1484
- const { groups } = escape;
1485
- if (groups.sgr !== void 0) applySgrParameters(groups.sgr, activeStyles);
1486
- else if (groups.uri !== void 0) activeHyperlink = groups.uri.length === 0 ? void 0 : {
1487
- parameters: groups.parameters,
1488
- uri: groups.uri
1489
- };
1490
- index += escape[0].length;
1491
- continue;
1492
- }
1493
- returnValue += preString.slice(copiedIndex, index);
1494
- if (index > copiedIndex) {
1495
- if (activeHyperlink) returnValue += wrapAnsiHyperlink("");
1496
- returnValue += getClosingSgrSequence(activeStyles);
1497
- }
1498
- returnValue += "\n";
1499
- index++;
1500
- copiedIndex = index;
1501
- if (index < preString.length && preString[index] !== "\n") {
1502
- const openingStyles = [...activeStyles];
1503
- applyLeadingSgrResets(preString, index, openingStyles);
1504
- returnValue += getOpeningSgrSequence(openingStyles);
1505
- if (activeHyperlink) returnValue += wrapAnsiHyperlink(activeHyperlink.uri, activeHyperlink.parameters);
1506
- }
1507
- }
1508
- return returnValue + preString.slice(copiedIndex);
1509
- };
1510
- const exec = (string, columns, options = {}) => {
1511
- if (options.trim !== false && string.trim() === "") return "";
1512
- const words = splitWords(string);
1513
- let rows = [""];
1514
- let rowLength = 0;
1515
- let trimmedRowIndex = -1;
1516
- let isFirstWord = true;
1517
- for (const word of words) {
1518
- const rowIndex = rows.length - 1;
1519
- if (options.trim !== false && trimmedRowIndex !== rowIndex) {
1520
- const row = rows[rowIndex];
1521
- const trimmedRow = row.trimStart();
1522
- if (trimmedRow.length !== row.length) {
1523
- rows[rowIndex] = trimmedRow;
1524
- rowLength = getWidth(trimmedRow);
1525
- }
1526
- if (trimmedRow.length > 0) trimmedRowIndex = rowIndex;
1527
- }
1528
- if (isFirstWord) isFirstWord = false;
1529
- else {
1530
- if (rowLength >= columns && (options.wordWrap === false || options.trim === false)) {
1531
- rows.push("");
1532
- rowLength = 0;
1533
- }
1534
- if (rowLength > 0 || options.trim === false) {
1535
- rows[rows.length - 1] += " ";
1536
- rowLength++;
1537
- }
1538
- }
1539
- if (options.hard && options.wordWrap !== false && word.width > columns) {
1540
- const remainingColumns = columns - rowLength;
1541
- const breaksStartingThisLine = 1 + Math.floor((word.width - remainingColumns - 1) / columns);
1542
- if (Math.floor((word.width - 1) / columns) < breaksStartingThisLine) {
1543
- rows.push("");
1544
- rowLength = 0;
1545
- }
1546
- rowLength = wrapWord(rows, word.value, columns, rowLength);
1547
- continue;
1548
- }
1549
- if (rowLength + word.width > columns && rowLength > 0 && word.width > 0) {
1550
- if (options.wordWrap === false && rowLength < columns) {
1551
- rowLength = wrapWord(rows, word.value, columns, rowLength);
1552
- continue;
1553
- }
1554
- rows.push("");
1555
- rowLength = 0;
1556
- }
1557
- if (rowLength + word.width > columns && options.wordWrap === false) {
1558
- rowLength = wrapWord(rows, word.value, columns, rowLength);
1559
- continue;
1560
- }
1561
- rows[rows.length - 1] += word.value;
1562
- rowLength += word.width;
1563
- }
1564
- if (options.trim !== false) rows = rows.map((row) => stringVisibleTrimSpacesRight(row));
1565
- return restoreStylesAcrossRows(rows.join("\n"));
1566
- };
1567
- const normalizeText = (string) => {
1568
- let normalizedString = "";
1569
- forEachSegment(string, (plainText) => {
1570
- normalizedString += plainText.normalize();
1571
- }, (escape) => {
1572
- normalizedString += escape;
1573
- });
1574
- return normalizedString;
1575
- };
1576
- function wrapAnsi(string, columns, options) {
1577
- return normalizeText(String(string)).replaceAll("\r\n", "\n").split("\n").map((line) => exec(expandTabs(line), columns, options)).join("\n");
1578
- }
1579
449
  function ScriptPreview({ script, hidden = false }) {
1580
450
  const { columns } = useWindowSize();
1581
451
  const width = Math.max(1, columns - 12);
@@ -1584,7 +454,7 @@ function ScriptPreview({ script, hidden = false }) {
1584
454
  wordWrap: false,
1585
455
  trim: false
1586
456
  };
1587
- const lines = wrapAnsi(script ?? "No script selected", width, wrapOptions).split("\n");
457
+ const lines = wrapAnsi(script === void 0 ? "No script selected" : toDisplayText(script), width, wrapOptions).split("\n");
1588
458
  const visibleLines = lines.slice(0, 2);
1589
459
  if (lines.length > 2) visibleLines[1] = `${width > 1 ? wrapAnsi(visibleLines[1], width - 1, wrapOptions).split("\n")[0] : ""}…`;
1590
460
  if (hidden) return /* @__PURE__ */ jsx(Box, {
@@ -1607,10 +477,10 @@ function ScriptPreview({ script, hidden = false }) {
1607
477
  });
1608
478
  }
1609
479
  // src/components/ScriptViewer.tsx
1610
- function ScriptViewer({ name, script, onClose }) {
480
+ function ScriptViewer({ name, script, onClose, onRun }) {
1611
481
  const { rows, columns } = useWindowSize();
1612
482
  const [offset, setOffset] = useState(0);
1613
- const lines = wrapAnsi(script, Math.max(1, columns - 6), {
483
+ const lines = wrapAnsi(toDisplayText(script), Math.max(1, columns - 6), {
1614
484
  hard: true,
1615
485
  wordWrap: false,
1616
486
  trim: false
@@ -1621,12 +491,17 @@ function ScriptViewer({ name, script, onClose }) {
1621
491
  const maxOffset = Math.max(0, lines.length - height);
1622
492
  const currentOffset = Math.min(offset, maxOffset);
1623
493
  useInput((input, key) => {
1624
- if (input === " " || key.escape || input === "q") {
494
+ const letter = input.toLowerCase();
495
+ if (input === " " || key.escape || letter === "q") {
1625
496
  onClose();
1626
497
  return;
1627
498
  }
1628
- if (key.upArrow || key.pageUp) setOffset(Math.max(0, currentOffset - (key.pageUp ? height : 1)));
1629
- if (key.downArrow || key.pageDown) setOffset(Math.min(maxOffset, currentOffset + (key.pageDown ? height : 1)));
499
+ if (key.return) {
500
+ onRun();
501
+ return;
502
+ }
503
+ if (key.upArrow) setOffset(Math.max(0, currentOffset - 1));
504
+ if (key.downArrow) setOffset(Math.min(maxOffset, currentOffset + 1));
1630
505
  });
1631
506
  return /* @__PURE__ */ jsxs(Box, {
1632
507
  height: rows,
@@ -1640,7 +515,7 @@ function ScriptViewer({ name, script, onClose }) {
1640
515
  bold: true,
1641
516
  color: "greenBright",
1642
517
  wrap: "truncate-end",
1643
- children: name
518
+ children: toDisplayText(name)
1644
519
  }),
1645
520
  /* @__PURE__ */ jsx(Box, {
1646
521
  height,
@@ -1655,7 +530,7 @@ function ScriptViewer({ name, script, onClose }) {
1655
530
  /* @__PURE__ */ jsx(Text, {
1656
531
  dimColor: true,
1657
532
  wrap: "truncate-end",
1658
- children: "↑↓ / PgUp/PgDn Scroll · Space / Esc Back"
533
+ children: "↑↓ Scroll · Enter Run · Space / Esc Back"
1659
534
  }),
1660
535
  hasScroll && /* @__PURE__ */ jsxs(Text, {
1661
536
  dimColor: true,
@@ -1671,6 +546,27 @@ function ScriptViewer({ name, script, onClose }) {
1671
546
  ]
1672
547
  });
1673
548
  }
549
+ // src/components/useFavorites.ts
550
+ const useFavorites = () => {
551
+ const [favorites, setFavoritesState] = useState(() => getConfig().scripts.favorites);
552
+ const [error, setError] = useState(null);
553
+ const toggle = (favorite) => {
554
+ const next = toggleFavorite(favorites, favorite);
555
+ setFavoritesState(next);
556
+ try {
557
+ setFavorites(next);
558
+ setError(null);
559
+ } catch (cause) {
560
+ setError(cause instanceof Error ? cause.message : String(cause));
561
+ }
562
+ return next;
563
+ };
564
+ return {
565
+ favorites,
566
+ toggle,
567
+ error
568
+ };
569
+ };
1674
570
  // src/components/useScrollOffset.ts
1675
571
  const useScrollOffset = (selectedIndex, itemCount, visibleRows) => {
1676
572
  const [offset, setOffset] = useState(0);
@@ -1683,24 +579,57 @@ const useScrollOffset = (selectedIndex, itemCount, visibleRows) => {
1683
579
  return nextOffset;
1684
580
  };
1685
581
  // src/components/Package.tsx
582
+ const ROOT_KEY = ".";
1686
583
  function App({ scripts, onSelect }) {
1687
584
  const { rows } = useWindowSize();
585
+ const { exit } = useApp();
1688
586
  const [isViewing, setIsViewing] = useState(false);
587
+ const [showHidden, setShowHidden] = useState(false);
588
+ const { favorites, toggle, error } = useFavorites();
589
+ const config = getConfig().scripts;
590
+ const pinned = favoritesFor(config.pinned, ROOT_KEY);
591
+ const hidden = favoritesFor(config.hidden, ROOT_KEY);
592
+ const order = (current, withHidden) => orderScripts(scripts, favoritesFor(current, ROOT_KEY), pinned, hidden, withHidden);
593
+ const entries = order(favorites, showHidden);
594
+ const indexIn = (nextEntries, name) => {
595
+ const nextIndex = nextEntries.findIndex((entry) => entry.name === name);
596
+ if (nextIndex !== -1) return nextIndex;
597
+ const currentIndex = entries.findIndex((entry) => entry.name === name);
598
+ return Math.max(0, Math.min(currentIndex, nextEntries.length - 1));
599
+ };
1689
600
  const { selectedIndex } = useKeyInput({
1690
- scripts,
601
+ scriptNames: entries.map((entry) => entry.name),
1691
602
  onSelect,
1692
603
  pageSize: Math.max(1, Math.floor(rows / 2)),
1693
604
  onPreview: () => setIsViewing(true),
605
+ onToggleFavorite: (name) => {
606
+ const next = toggle({
607
+ package: ROOT_KEY,
608
+ script: name
609
+ });
610
+ return indexIn(order(next, showHidden), name);
611
+ },
612
+ onToggleHidden: (name) => {
613
+ setShowHidden(!showHidden);
614
+ return indexIn(order(favorites, !showHidden), name);
615
+ },
1694
616
  isActive: !isViewing
1695
617
  });
1696
- const entries = Object.entries(scripts);
1697
- const selectedScript = entries[selectedIndex]?.[1];
618
+ const selectedScript = entries[selectedIndex]?.script;
619
+ const showMarker = hasMarkers(entries);
1698
620
  const visibleRows = Math.max(1, rows - 6 - 4);
1699
621
  const offset = useScrollOffset(selectedIndex, entries.length, visibleRows);
1700
622
  if (isViewing) return /* @__PURE__ */ jsx(ScriptViewer, {
1701
- name: entries[selectedIndex]?.[0] ?? "",
623
+ name: entries[selectedIndex]?.name ?? "",
1702
624
  script: selectedScript ?? "",
1703
- onClose: () => setIsViewing(false)
625
+ onClose: () => setIsViewing(false),
626
+ onRun: () => {
627
+ const name = entries[selectedIndex]?.name;
628
+ if (name !== void 0) {
629
+ onSelect(name);
630
+ exit();
631
+ }
632
+ }
1704
633
  });
1705
634
  return /* @__PURE__ */ jsxs(Box, {
1706
635
  height: rows,
@@ -1717,7 +646,7 @@ function App({ scripts, onSelect }) {
1717
646
  children: /* @__PURE__ */ jsx(Text, {
1718
647
  bold: true,
1719
648
  color: "cyan",
1720
- children: " Runpad "
649
+ children: showHidden ? " Runpad · showing hidden " : " Runpad "
1721
650
  })
1722
651
  }),
1723
652
  /* @__PURE__ */ jsxs(Box, {
@@ -1730,56 +659,77 @@ function App({ scripts, onSelect }) {
1730
659
  children: [entries.length === 0 && /* @__PURE__ */ jsx(Text, {
1731
660
  dimColor: true,
1732
661
  children: "No scripts found"
1733
- }), entries.slice(offset, offset + visibleRows).map(([name, script], i) => {
662
+ }), entries.slice(offset, offset + visibleRows).map(({ name, script, isFavorite, isPinned, isHidden }, i) => {
1734
663
  return /* @__PURE__ */ jsx(Command, {
1735
664
  isSelected: offset + i === selectedIndex,
1736
665
  name,
1737
- script
666
+ script,
667
+ isFavorite,
668
+ isPinned,
669
+ isHidden,
670
+ showMarker
1738
671
  }, name);
1739
672
  })]
1740
673
  }),
1741
674
  /* @__PURE__ */ jsx(ScriptPreview, { script: selectedScript }),
1742
675
  /* @__PURE__ */ jsx(Box, {
1743
676
  paddingX: 1,
1744
- children: /* @__PURE__ */ jsx(Text, {
677
+ children: error ? /* @__PURE__ */ jsx(Text, {
678
+ color: "red",
679
+ wrap: "truncate-end",
680
+ children: error
681
+ }) : /* @__PURE__ */ jsxs(Text, {
1745
682
  dimColor: true,
1746
683
  wrap: "truncate-end",
1747
- children: "←↑↓→ Navigate · Enter Select · Space View · Esc Exit"
684
+ children: [
685
+ "←↑↓→ Navigate · Enter Select · Space View · F Favorite",
686
+ hidden.length > 0 && " · H Hidden",
687
+ " · Esc Exit"
688
+ ]
1748
689
  })
1749
690
  })
1750
691
  ]
1751
692
  });
1752
693
  }
1753
- // src/detectPackageManager.ts
1754
- const lockfiles = {
1755
- bun: ["bun.lock", "bun.lockb"],
1756
- pnpm: ["pnpm-lock.yaml"],
1757
- yarn: ["yarn.lock"],
1758
- npm: ["package-lock.json", "npm-shrinkwrap.json"]
694
+ // src/utils/printError.ts
695
+ const printError = (message, detail) => {
696
+ console.error(styleText(["red", "bold"], `✖ ${message}`, { stream: process.stderr }));
697
+ if (detail) console.error(styleText("dim", ` ${detail}`, { stream: process.stderr }));
698
+ };
699
+ // src/utils/printWarning.ts
700
+ const printWarning = (message, detail) => {
701
+ console.error(styleText(["yellow", "bold"], `⚠ ${message}`, { stream: process.stderr }));
702
+ if (detail) console.error(styleText("dim", ` ${detail}`, { stream: process.stderr }));
1759
703
  };
1760
- async function exists(path) {
1761
- try {
1762
- await access(path);
1763
- return true;
1764
- } catch {
1765
- return false;
704
+ // src/utils/runScript.ts
705
+ const FALLBACK_MANAGER = "npm";
706
+ const runScript = async ({ script, packageJsonPath }) => {
707
+ const cwd = dirname(packageJsonPath);
708
+ const detectedResult = await toResult(detectPackageManager(cwd, { ignoreArgv: true }));
709
+ if (!detectedResult.ok) {
710
+ printError(`Failed to detect package manager for ${cwd}`, detectedResult.error.message);
711
+ process.exitCode = 1;
712
+ return;
1766
713
  }
1767
- }
1768
- async function detectPackageManager(directory, packageJson) {
1769
- const declared = packageJson.packageManager?.split("@")[0];
1770
- if (declared && Object.hasOwn(lockfiles, declared)) return declared;
1771
- for (const [manager, files] of Object.entries(lockfiles)) for (const file of files) if (await exists(join(directory, file))) return manager;
1772
- return "npm";
1773
- }
714
+ const command = detectedResult.value?.command ?? FALLBACK_MANAGER;
715
+ if (!detectedResult.value) printWarning(`No package manager detected for ${cwd}, using ${FALLBACK_MANAGER}`, "Add a lockfile or a \"packageManager\" field to package.json to choose one.");
716
+ const runResult = await execa(command, ["run", script], {
717
+ cwd,
718
+ stdio: "inherit",
719
+ reject: false
720
+ });
721
+ if (runResult.failed) printError(runResult.shortMessage ?? `Failed to run "${script}"`);
722
+ process.exitCode = runResult.exitCode ?? (runResult.signal ? 128 + constants.signals[runResult.signal] : 1);
723
+ };
1774
724
  // src/runPackage.tsx
1775
725
  const runPackage = async (packageJsonPath) => {
1776
726
  const fileResult = await toResult(readFile(packageJsonPath, "utf8"));
1777
- if (!fileResult.ok) throw fileResult.error;
727
+ if (!fileResult.ok) throw new Error(`Failed to read ${packageJsonPath}`, { cause: fileResult.error });
1778
728
  const parsed = attempt(() => JSON.parse(fileResult.value));
1779
- if (!parsed.ok) throw parsed.error;
1780
- const packageJson = v.parse(packageJsonSchema, parsed.value);
1781
- const scripts = packageJson.scripts ?? {};
1782
- const manager = await detectPackageManager(dirname(packageJsonPath), packageJson);
729
+ if (!parsed.ok) throw new Error(`Failed to read ${packageJsonPath}`, { cause: parsed.error });
730
+ const result = v.safeParse(packageJsonSchema, parsed.value);
731
+ if (!result.success) throw new Error(`Invalid ${packageJsonPath}: ${v.summarize(result.issues)}`);
732
+ const scripts = result.output.scripts ?? {};
1783
733
  let selectedScript;
1784
734
  const { waitUntilExit } = render(/* @__PURE__ */ jsx(App, {
1785
735
  scripts,
@@ -1788,38 +738,88 @@ const runPackage = async (packageJsonPath) => {
1788
738
  }
1789
739
  }), { alternateScreen: true });
1790
740
  await waitUntilExit();
1791
- if (!selectedScript) process.exit(0);
1792
- const runResult = await execa(manager, ["run", selectedScript], {
1793
- cwd: dirname(packageJsonPath),
1794
- stdio: "inherit",
1795
- reject: false
741
+ if (!selectedScript) return;
742
+ await runScript({
743
+ packageJsonPath,
744
+ script: selectedScript
1796
745
  });
1797
- if (runResult.failed) console.error(runResult.shortMessage);
1798
- process.exitCode = runResult.exitCode ?? 1;
1799
746
  };
1800
747
  // src/components/Workspace.tsx
748
+ const FAVORITES_ROW = 0;
1801
749
  function Workspace({ packages, onSelect }) {
1802
750
  const { rows } = useWindowSize();
1803
751
  const [isViewing, setIsViewing] = useState(false);
1804
752
  const { exit } = useApp();
1805
- const [packageIndex, setPackageIndex] = useState(0);
753
+ const { favorites, toggle, error } = useFavorites();
754
+ const [showHidden, setShowHidden] = useState(false);
755
+ const { hidden, pinned: configPinned } = getConfig().scripts;
756
+ const hiddenIds = new Set(hidden.map(refId));
757
+ const pinnedFor = (withHidden) => withHidden ? configPinned : withoutRefs(configPinned, hidden);
758
+ const [packageIndex, setPackageIndex] = useState(() => resolveFavorites([...favorites, ...pinnedFor(false)], packages).length > 0 ? FAVORITES_ROW : 1);
1806
759
  const [scriptIndex, setScriptIndex] = useState(0);
1807
760
  const [activeColumn, setActiveColumn] = useState("packages");
1808
- const selectedPackageIndex = Math.min(packageIndex, Math.max(0, packages.length - 1));
1809
- const selectedPackage = packages[selectedPackageIndex];
1810
- const scripts = Object.entries(selectedPackage?.scripts ?? {});
761
+ const packageRowCount = packages.length + 1;
762
+ const selectedPackageIndex = Math.min(packageIndex, packageRowCount - 1);
763
+ const isFavoritesSelected = selectedPackageIndex === FAVORITES_ROW;
764
+ const selectedPackage = isFavoritesSelected ? void 0 : packages[selectedPackageIndex - 1];
765
+ const buildScriptRows = (current, withHidden) => {
766
+ const pinned = pinnedFor(withHidden);
767
+ if (isFavoritesSelected) {
768
+ const pinnedIds = new Set(pinned.map(refId));
769
+ const favoriteIds = new Set(current.map(refId));
770
+ return resolveFavorites([...current, ...pinned], packages).map(({ pkg, favorite, script }) => {
771
+ const id = refId(favorite);
772
+ return {
773
+ id,
774
+ pkg,
775
+ name: favorite.script,
776
+ script,
777
+ isPinned: pinnedIds.has(id),
778
+ isFavorite: favoriteIds.has(id),
779
+ isHidden: hiddenIds.has(id) && !favoriteIds.has(id),
780
+ packageName: pkg.name
781
+ };
782
+ });
783
+ }
784
+ if (!selectedPackage) return [];
785
+ return orderScripts(selectedPackage.scripts, favoritesFor(current, selectedPackage.key), favoritesFor(pinned, selectedPackage.key), favoritesFor(hidden, selectedPackage.key), withHidden).map((entry) => ({
786
+ id: entry.name,
787
+ pkg: selectedPackage,
788
+ ...entry
789
+ }));
790
+ };
791
+ const scripts = buildScriptRows(favorites, showHidden);
792
+ const showMarker = hasMarkers(scripts);
1811
793
  const selectedScriptIndex = Math.min(scriptIndex, Math.max(0, scripts.length - 1));
794
+ const selectedRow = scripts[selectedScriptIndex];
1812
795
  const showPreview = activeColumn === "scripts";
1813
- const selectedScriptText = scripts[selectedScriptIndex]?.[1];
1814
796
  const visibleRows = Math.max(1, rows - 7 - 4);
1815
- const packageOffset = useScrollOffset(selectedPackageIndex, packages.length, visibleRows);
797
+ const packageOffset = useScrollOffset(selectedPackageIndex, packageRowCount, visibleRows);
1816
798
  const scriptOffset = useScrollOffset(selectedScriptIndex, scripts.length, visibleRows);
1817
799
  useInput((input, key) => {
800
+ const letter = input.toLowerCase();
1818
801
  if (input === " ") {
1819
- if (showPreview && selectedScriptText !== void 0) setIsViewing(true);
802
+ if (showPreview && selectedRow) setIsViewing(true);
1820
803
  return;
1821
804
  }
1822
- if (key.escape || input === "q") {
805
+ if (letter === "f") {
806
+ if (activeColumn === "scripts" && selectedRow) {
807
+ const next = toggle({
808
+ package: selectedRow.pkg.key,
809
+ script: selectedRow.name
810
+ });
811
+ const nextIndex = buildScriptRows(next, showHidden).findIndex((row) => row.id === selectedRow.id);
812
+ if (nextIndex !== -1) setScriptIndex(nextIndex);
813
+ }
814
+ return;
815
+ }
816
+ if (letter === "h") {
817
+ const nextIndex = buildScriptRows(favorites, !showHidden).findIndex((row) => row.id === selectedRow?.id);
818
+ if (nextIndex !== -1) setScriptIndex(nextIndex);
819
+ setShowHidden(!showHidden);
820
+ return;
821
+ }
822
+ if (key.escape || letter === "q") {
1823
823
  exit();
1824
824
  return;
1825
825
  }
@@ -1827,14 +827,14 @@ function Workspace({ packages, onSelect }) {
1827
827
  setActiveColumn("packages");
1828
828
  return;
1829
829
  }
1830
- if (key.rightArrow) {
1831
- if (selectedPackage) setActiveColumn("scripts");
830
+ if (key.rightArrow || key.return && activeColumn === "packages") {
831
+ setActiveColumn("scripts");
1832
832
  return;
1833
833
  }
1834
834
  if (key.upArrow || key.downArrow) {
1835
835
  const direction = key.downArrow ? 1 : -1;
1836
836
  if (activeColumn === "packages") {
1837
- const nextIndex = Math.max(0, Math.min(packages.length - 1, selectedPackageIndex + direction));
837
+ const nextIndex = Math.max(0, Math.min(packageRowCount - 1, selectedPackageIndex + direction));
1838
838
  if (nextIndex !== selectedPackageIndex) {
1839
839
  setPackageIndex(nextIndex);
1840
840
  setScriptIndex(0);
@@ -1842,21 +842,23 @@ function Workspace({ packages, onSelect }) {
1842
842
  } else setScriptIndex(Math.max(0, Math.min(scripts.length - 1, selectedScriptIndex + direction)));
1843
843
  return;
1844
844
  }
1845
- if (key.return && activeColumn === "packages") {
1846
- if (selectedPackage) setActiveColumn("scripts");
1847
- return;
1848
- }
1849
- const selectedScript = scripts[selectedScriptIndex];
1850
- if (key.return && selectedPackage && selectedScript) {
1851
- onSelect(selectedPackage, selectedScript[0]);
845
+ if (key.return && selectedRow) {
846
+ onSelect(selectedRow.pkg, selectedRow.name);
1852
847
  exit();
1853
848
  }
1854
849
  }, { isActive: !isViewing });
1855
850
  if (isViewing) return /* @__PURE__ */ jsx(ScriptViewer, {
1856
- name: scripts[selectedScriptIndex]?.[0] ?? "",
1857
- script: selectedScriptText ?? "",
1858
- onClose: () => setIsViewing(false)
851
+ name: selectedRow?.packageName === void 0 ? selectedRow?.name ?? "" : `${selectedRow.packageName}${selectedRow.pkg.isRoot ? " [root]" : ""} › ${selectedRow.name}`,
852
+ script: selectedRow?.script ?? "",
853
+ onClose: () => setIsViewing(false),
854
+ onRun: () => {
855
+ if (selectedRow) {
856
+ onSelect(selectedRow.pkg, selectedRow.name);
857
+ exit();
858
+ }
859
+ }
1859
860
  });
861
+ const packageRows = [void 0, ...packages];
1860
862
  return /* @__PURE__ */ jsxs(Box, {
1861
863
  height: rows,
1862
864
  flexDirection: "column",
@@ -1872,7 +874,7 @@ function Workspace({ packages, onSelect }) {
1872
874
  children: /* @__PURE__ */ jsx(Text, {
1873
875
  bold: true,
1874
876
  color: "cyan",
1875
- children: " Runpad · Workspace "
877
+ children: showHidden ? " Runpad · Workspace · showing hidden " : " Runpad · Workspace "
1876
878
  })
1877
879
  }),
1878
880
  /* @__PURE__ */ jsxs(Box, {
@@ -1884,34 +886,35 @@ function Workspace({ packages, onSelect }) {
1884
886
  width: "30%",
1885
887
  flexShrink: 0,
1886
888
  flexDirection: "column",
1887
- children: [
1888
- /* @__PURE__ */ jsx(Text, {
1889
- bold: true,
1890
- color: activeColumn === "packages" ? "cyanBright" : "cyan",
1891
- children: "Packages"
1892
- }),
1893
- packages.length === 0 && /* @__PURE__ */ jsx(Text, {
1894
- dimColor: true,
1895
- children: "No packages found"
1896
- }),
1897
- packages.slice(packageOffset, packageOffset + visibleRows).map((pkg, index) => {
1898
- const isSelected = packageOffset + index === selectedPackageIndex;
1899
- return /* @__PURE__ */ jsxs(Text, {
1900
- bold: isSelected,
1901
- color: isSelected && activeColumn === "packages" ? "greenBright" : "green",
1902
- wrap: "truncate-end",
1903
- children: [
1904
- isSelected && activeColumn === "packages" ? "▸ " : " ",
1905
- pkg.name,
1906
- pkg.isRoot && /* @__PURE__ */ jsxs(Text, {
1907
- bold: true,
1908
- color: "#FFA500",
1909
- children: [" ", "[root]"]
1910
- })
1911
- ]
1912
- }, pkg.packageJsonPath);
1913
- })
1914
- ]
889
+ children: [/* @__PURE__ */ jsx(Text, {
890
+ bold: true,
891
+ color: activeColumn === "packages" ? "cyanBright" : "cyan",
892
+ children: "Packages"
893
+ }), packageRows.slice(packageOffset, packageOffset + visibleRows).map((pkg, index) => {
894
+ const isSelected = packageOffset + index === selectedPackageIndex;
895
+ const isActive = isSelected && activeColumn === "packages";
896
+ const cursor = isActive ? "▸ " : " ";
897
+ if (!pkg) return /* @__PURE__ */ jsxs(Text, {
898
+ bold: isSelected,
899
+ color: isActive ? "yellowBright" : "yellow",
900
+ wrap: "truncate-end",
901
+ children: [cursor, "★ Favorites"]
902
+ }, "\\0favorites");
903
+ return /* @__PURE__ */ jsxs(Text, {
904
+ bold: isSelected,
905
+ color: isActive ? "greenBright" : "green",
906
+ wrap: "truncate-end",
907
+ children: [
908
+ cursor,
909
+ toDisplayText(pkg.name),
910
+ pkg.isRoot && /* @__PURE__ */ jsxs(Text, {
911
+ bold: true,
912
+ color: "#FFA500",
913
+ children: [" ", "[root]"]
914
+ })
915
+ ]
916
+ }, pkg.packageJsonPath);
917
+ })]
1915
918
  }), /* @__PURE__ */ jsxs(Box, {
1916
919
  flexGrow: 1,
1917
920
  minWidth: 0,
@@ -1926,37 +929,51 @@ function Workspace({ packages, onSelect }) {
1926
929
  }),
1927
930
  scripts.length === 0 && /* @__PURE__ */ jsx(Text, {
1928
931
  dimColor: true,
1929
- children: "No scripts found"
932
+ children: isFavoritesSelected ? "No favorites yet · press F on a script" : "No scripts found"
1930
933
  }),
1931
- scripts.slice(scriptOffset, scriptOffset + visibleRows).map(([name, script], index) => /* @__PURE__ */ jsx(Box, {
934
+ scripts.slice(scriptOffset, scriptOffset + visibleRows).map((row, index) => /* @__PURE__ */ jsx(Box, {
1932
935
  height: 1,
1933
936
  flexShrink: 0,
1934
937
  overflow: "hidden",
1935
938
  children: /* @__PURE__ */ jsx(Command, {
1936
939
  isSelected: activeColumn === "scripts" && scriptOffset + index === selectedScriptIndex,
1937
- name,
1938
- script
940
+ name: row.name,
941
+ script: row.script,
942
+ isFavorite: row.isFavorite,
943
+ isPinned: row.isPinned,
944
+ isHidden: row.isHidden,
945
+ showMarker,
946
+ packageName: row.packageName,
947
+ isRootPackage: row.pkg.isRoot
1939
948
  })
1940
- }, name))
949
+ }, row.id))
1941
950
  ]
1942
951
  })]
1943
952
  }),
1944
953
  /* @__PURE__ */ jsx(ScriptPreview, {
1945
- script: selectedScriptText,
954
+ script: selectedRow?.script,
1946
955
  hidden: !showPreview
1947
956
  }),
1948
957
  /* @__PURE__ */ jsx(Box, {
1949
958
  paddingX: 1,
1950
- children: /* @__PURE__ */ jsx(Text, {
959
+ children: error ? /* @__PURE__ */ jsx(Text, {
960
+ color: "red",
961
+ wrap: "truncate-end",
962
+ children: error
963
+ }) : /* @__PURE__ */ jsxs(Text, {
1951
964
  dimColor: true,
1952
965
  wrap: "truncate-end",
1953
- children: "←→ Column · ↑↓ Navigate · Enter Select · Space View · Esc Exit"
966
+ children: [
967
+ "←→ Column · ↑↓ Navigate · Enter Select · Space View · F Favorite",
968
+ hidden.length > 0 && " · H Hidden",
969
+ " · Esc Exit"
970
+ ]
1954
971
  })
1955
972
  })
1956
973
  ]
1957
974
  });
1958
975
  }
1959
- // src/runWorkspace.ts
976
+ // src/runWorkspace.tsx
1960
977
  const readPackage = async (packageJsonPath) => {
1961
978
  const file = await toResult(readFile(packageJsonPath, "utf8"));
1962
979
  if (!file.ok) return null;
@@ -1967,10 +984,12 @@ const readPackage = async (packageJsonPath) => {
1967
984
  };
1968
985
  const runWorkspace = async (workspaceRoot, packageJsonPath) => {
1969
986
  const root = resolve(workspaceRoot);
1970
- const patterns = await getWorkspacePatterns(root) ?? [];
987
+ const patterns = await getWorkspacePatterns(root) ?? {
988
+ include: [],
989
+ exclude: []
990
+ };
1971
991
  const directories = /* @__PURE__ */ new Set([root]);
1972
- const includedPatterns = patterns.filter((pattern) => !pattern.startsWith("!"));
1973
- if (includedPatterns.length > 0) for await (const path of glob(includedPatterns, {
992
+ if (patterns.include.length > 0) for await (const path of glob(patterns.include, {
1974
993
  cwd: root,
1975
994
  exclude: [
1976
995
  "**/node_modules",
@@ -1993,6 +1012,7 @@ const runWorkspace = async (workspaceRoot, packageJsonPath) => {
1993
1012
  const packageJson = directory === root ? rootPackage : await readPackage(path);
1994
1013
  if (!packageJson) continue;
1995
1014
  packages.push({
1015
+ key: toPackageKey(root, directory),
1996
1016
  name: packageJson.name ?? (relative(root, directory) || "."),
1997
1017
  packageJsonPath: path,
1998
1018
  isRoot: directory === root,
@@ -2003,9 +1023,8 @@ const runWorkspace = async (workspaceRoot, packageJsonPath) => {
2003
1023
  packages.sort((a, b) => {
2004
1024
  return Number(b.packageJsonPath === currentPath) - Number(a.packageJsonPath === currentPath) || a.name.localeCompare(b.name);
2005
1025
  });
2006
- const manager = await detectPackageManager(root, rootPackage ?? {});
2007
1026
  let selection;
2008
- const { waitUntilExit } = render(createElement(Workspace, {
1027
+ const { waitUntilExit } = render(/* @__PURE__ */ jsx(Workspace, {
2009
1028
  packages,
2010
1029
  onSelect: (workspacePackage, script) => {
2011
1030
  selection = {
@@ -2016,18 +1035,11 @@ const runWorkspace = async (workspaceRoot, packageJsonPath) => {
2016
1035
  }), { alternateScreen: true });
2017
1036
  await waitUntilExit();
2018
1037
  if (!selection) return;
2019
- const runResult = await execa(manager, ["run", selection.script], {
2020
- cwd: dirname(selection.workspacePackage.packageJsonPath),
2021
- stdio: "inherit",
2022
- reject: false
1038
+ await runScript({
1039
+ packageJsonPath: selection.workspacePackage.packageJsonPath,
1040
+ script: selection.script
2023
1041
  });
2024
- if (runResult.failed) console.error(runResult.shortMessage);
2025
- process.exitCode = runResult.exitCode ?? 1;
2026
1042
  };
2027
- // src/utils/isNodeError.ts
2028
- function isNodeError(error, code) {
2029
- return error instanceof Error && "code" in error && error.code === code;
2030
- }
2031
1043
  // src/utils/findUp.ts
2032
1044
  const findUp = async (cwd, filename) => {
2033
1045
  const filePath = join(cwd, filename);
@@ -2040,9 +1052,42 @@ const findUp = async (cwd, filename) => {
2040
1052
  }
2041
1053
  return filePath;
2042
1054
  };
2043
- const packageJsonPath = await findUp(process.cwd(), "package.json");
2044
- if (!packageJsonPath) throw new Error("No package.json found");
2045
- const workspaceRoot = await findWorkspaceRoot(dirname(packageJsonPath));
2046
- if (workspaceRoot) await runWorkspace(workspaceRoot, packageJsonPath);
2047
- else await runPackage(packageJsonPath);
1055
+ // src/utils/formatError.ts
1056
+ /**
1057
+ * Turns anything thrown into a one-line message and an optional detail line
1058
+ * for the terminal. The detail is the message of the error's `cause`, e.g.
1059
+ * the JSON syntax error behind "Failed to read runpad.config.json".
1060
+ */
1061
+ const formatError = (error) => {
1062
+ if (!(error instanceof Error)) return { message: String(error) };
1063
+ const { cause } = error;
1064
+ const detail = cause instanceof Error ? cause.message : cause === void 0 ? void 0 : String(cause);
1065
+ return detail ? {
1066
+ message: error.message,
1067
+ detail
1068
+ } : { message: error.message };
1069
+ };
1070
+ // src/index.ts
1071
+ const main = async () => {
1072
+ const cwd = process.cwd();
1073
+ const packageJsonPath = await findUp(cwd, "package.json");
1074
+ if (!packageJsonPath) {
1075
+ printError(`No package.json found in ${cwd} or any parent directory`, "Run RunPad inside a JavaScript project.");
1076
+ process.exitCode = 1;
1077
+ return;
1078
+ }
1079
+ const workspaceRoot = await findWorkspaceRoot(dirname(packageJsonPath));
1080
+ const root = workspaceRoot ?? dirname(packageJsonPath);
1081
+ setConfig(await loadConfig(root), root);
1082
+ if (workspaceRoot) await runWorkspace(workspaceRoot, packageJsonPath);
1083
+ else await runPackage(packageJsonPath);
1084
+ };
1085
+ try {
1086
+ await main();
1087
+ } catch (error) {
1088
+ const { message, detail } = formatError(error);
1089
+ printError(message, detail);
1090
+ if (process.env.RUNPAD_DEBUG && error instanceof Error && error.stack) console.error(error.stack);
1091
+ process.exitCode = 1;
1092
+ }
2048
1093
  export {};