@narumitw/pi-starship 0.49.3 → 0.50.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 (100) hide show
  1. package/NOTICES.md +4 -2
  2. package/README.md +62 -16
  3. package/package.json +10 -11
  4. package/src/command-contract.ts +13 -0
  5. package/src/command-inspector.ts +198 -0
  6. package/src/command-preset-picker.ts +203 -0
  7. package/src/command-preview.ts +206 -0
  8. package/src/commands.ts +784 -0
  9. package/src/config.ts +794 -0
  10. package/src/format/formatter.ts +275 -0
  11. package/src/format/style.ts +278 -0
  12. package/src/index.ts +1 -1
  13. package/src/modules/activity.ts +38 -0
  14. package/src/modules/brand.ts +13 -0
  15. package/src/modules/cache.ts +23 -0
  16. package/src/modules/catalog.ts +124 -0
  17. package/src/modules/cloud.ts +74 -0
  18. package/src/modules/context.ts +33 -0
  19. package/src/modules/cost.ts +31 -0
  20. package/src/modules/deployment.ts +61 -0
  21. package/src/modules/development.ts +112 -0
  22. package/src/modules/directory.ts +151 -0
  23. package/src/modules/display.ts +14 -0
  24. package/src/modules/execution.ts +84 -0
  25. package/src/modules/extension-status.ts +93 -0
  26. package/src/modules/fill.ts +14 -0
  27. package/src/modules/git/branch.ts +31 -0
  28. package/src/modules/git/commit.ts +29 -0
  29. package/src/modules/git/metrics.ts +26 -0
  30. package/src/modules/git/runtime.ts +415 -0
  31. package/src/modules/git/state.ts +21 -0
  32. package/src/modules/git/status.ts +87 -0
  33. package/src/modules/git/worktree.ts +16 -0
  34. package/src/modules/github-pr.ts +24 -0
  35. package/src/modules/helpers.ts +5 -0
  36. package/src/modules/index.ts +31 -0
  37. package/src/modules/inspection.ts +138 -0
  38. package/src/modules/languages.ts +87 -0
  39. package/src/modules/model.ts +85 -0
  40. package/src/modules/package.ts +17 -0
  41. package/src/modules/provider.ts +13 -0
  42. package/src/modules/render.ts +166 -0
  43. package/src/modules/terminal.ts +60 -0
  44. package/src/modules/thinking.ts +13 -0
  45. package/src/modules/time.ts +20 -0
  46. package/src/modules/tokens.ts +18 -0
  47. package/src/modules/truncation.ts +37 -0
  48. package/src/modules/turn.ts +13 -0
  49. package/src/modules/types.ts +189 -0
  50. package/src/modules/workspace-helpers.ts +10 -0
  51. package/src/pi-starship.ts +619 -0
  52. package/src/presets/bracketed-segments.ts +45 -0
  53. package/src/presets/catalog.ts +138 -0
  54. package/src/presets/catppuccin-powerline.ts +90 -0
  55. package/src/presets/gruvbox-rainbow.ts +66 -0
  56. package/src/presets/jetpack.ts +51 -0
  57. package/src/presets/minimal.ts +23 -0
  58. package/src/presets/nerd-font-symbols.ts +27 -0
  59. package/src/presets/no-empty-icons.ts +47 -0
  60. package/src/presets/no-nerd-font.ts +51 -0
  61. package/src/presets/no-runtime-versions.ts +52 -0
  62. package/src/presets/pastel-powerline.ts +53 -0
  63. package/src/presets/plain-text-symbols.ts +52 -0
  64. package/src/presets/pure-preset.ts +55 -0
  65. package/src/presets/tokyo-night.ts +53 -0
  66. package/src/runtime/cloud.ts +166 -0
  67. package/src/runtime/command.ts +123 -0
  68. package/src/runtime/deployment.ts +201 -0
  69. package/src/runtime/development.ts +153 -0
  70. package/src/runtime/execution.ts +151 -0
  71. package/src/runtime/github-pr.ts +332 -0
  72. package/src/runtime/helpers.ts +274 -0
  73. package/src/runtime/languages.ts +205 -0
  74. package/src/runtime/package.ts +112 -0
  75. package/src/runtime/refresh-controller.ts +107 -0
  76. package/src/runtime/types.ts +63 -0
  77. package/src/runtime/workspace.ts +147 -0
  78. package/src/usage.ts +53 -0
  79. package/dist/chunks/chunk-CKNSOLSW.ts +0 -10
  80. package/dist/chunks/chunk-CKNSOLSW.ts.map +0 -7
  81. package/dist/chunks/chunk-G2GG2V6Q.ts +0 -218
  82. package/dist/chunks/chunk-G2GG2V6Q.ts.map +0 -7
  83. package/dist/chunks/chunk-Q6DLIM7H.ts +0 -2492
  84. package/dist/chunks/chunk-Q6DLIM7H.ts.map +0 -7
  85. package/dist/chunks/cloud-JBSZWTB6.ts +0 -142
  86. package/dist/chunks/cloud-JBSZWTB6.ts.map +0 -7
  87. package/dist/chunks/commands-BSQZ2R4M.ts +0 -757
  88. package/dist/chunks/commands-BSQZ2R4M.ts.map +0 -7
  89. package/dist/chunks/deployment-ZNYM4B6W.ts +0 -172
  90. package/dist/chunks/deployment-ZNYM4B6W.ts.map +0 -7
  91. package/dist/chunks/development-TNWZ5SRC.ts +0 -132
  92. package/dist/chunks/development-TNWZ5SRC.ts.map +0 -7
  93. package/dist/chunks/execution-QHAP4U33.ts +0 -132
  94. package/dist/chunks/execution-QHAP4U33.ts.map +0 -7
  95. package/dist/chunks/languages-DPWDCH6Q.ts +0 -184
  96. package/dist/chunks/languages-DPWDCH6Q.ts.map +0 -7
  97. package/dist/chunks/package-MXN2YFLX.ts +0 -104
  98. package/dist/chunks/package-MXN2YFLX.ts.map +0 -7
  99. package/dist/pi-starship.ts +0 -1350
  100. package/dist/pi-starship.ts.map +0 -7
@@ -0,0 +1,274 @@
1
+ import { type FileHandle, open, opendir, stat } from "node:fs/promises";
2
+ import { basename, delimiter, dirname, extname, join, resolve } from "node:path";
3
+ import type {
4
+ CollectorContext,
5
+ WorkspaceEntry,
6
+ WorkspaceFileSystem,
7
+ WorkspaceRefreshInput,
8
+ } from "./types.js";
9
+
10
+ export const MAX_METADATA_FILE_BYTES = 64 * 1024;
11
+ export const COMMAND_TIMEOUT_MS = 2_000;
12
+ export const MAX_COMMAND_OUTPUT_BYTES = 64 * 1024;
13
+ const MAX_DIRECTORY_ENTRIES = 2_048;
14
+ const MAX_LABEL_LENGTH = 160;
15
+
16
+ export function createFileSystem(input: WorkspaceRefreshInput): WorkspaceFileSystem {
17
+ const defaults: WorkspaceFileSystem = {
18
+ async readFile(path, maxBytes) {
19
+ let handle: FileHandle | undefined;
20
+ try {
21
+ handle = await open(path, "r");
22
+ const info = await handle.stat();
23
+ if (!info.isFile() || info.size > maxBytes) return undefined;
24
+ const buffer = Buffer.alloc(Math.min(maxBytes + 1, Number(info.size) + 1));
25
+ const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
26
+ if (bytesRead > maxBytes) return undefined;
27
+ return buffer.subarray(0, bytesRead).toString("utf8");
28
+ } catch {
29
+ return undefined;
30
+ } finally {
31
+ await handle?.close().catch(() => undefined);
32
+ }
33
+ },
34
+ async readDirectory(path) {
35
+ const entries: WorkspaceEntry[] = [];
36
+ try {
37
+ const directory = await opendir(path);
38
+ for await (const entry of directory) {
39
+ entries.push({
40
+ name: entry.name,
41
+ isFile: entry.isFile(),
42
+ isDirectory: entry.isDirectory(),
43
+ });
44
+ if (entries.length >= MAX_DIRECTORY_ENTRIES) break;
45
+ }
46
+ } catch {
47
+ return [];
48
+ }
49
+ return entries;
50
+ },
51
+ async fileExists(path) {
52
+ try {
53
+ await stat(path);
54
+ return true;
55
+ } catch {
56
+ return false;
57
+ }
58
+ },
59
+ };
60
+ return {
61
+ ...defaults,
62
+ ...input.fileSystem,
63
+ ...(input.fileExists ? { fileExists: input.fileExists } : {}),
64
+ };
65
+ }
66
+
67
+ export function safeMetadata(value: unknown, maxLength = MAX_LABEL_LENGTH): string | undefined {
68
+ if (typeof value !== "string") return undefined;
69
+ const sanitized = Array.from(value, (character) => {
70
+ const code = character.codePointAt(0) ?? 0;
71
+ return code <= 0x1f || (code >= 0x7f && code <= 0x9f) || (code >= 0xd800 && code <= 0xdfff)
72
+ ? ""
73
+ : character;
74
+ })
75
+ .join("")
76
+ .trim();
77
+ if (!sanitized) return undefined;
78
+ return Array.from(sanitized).slice(0, maxLength).join("");
79
+ }
80
+
81
+ export function ownString(record: unknown, key: string): string | undefined {
82
+ if (!isRecord(record) || !Object.hasOwn(record, key)) return undefined;
83
+ return safeMetadata(record[key]);
84
+ }
85
+
86
+ export function isRecord(value: unknown): value is Record<string, unknown> {
87
+ return typeof value === "object" && value !== null && !Array.isArray(value);
88
+ }
89
+
90
+ export function setString(record: Record<string, string>, key: string, value: unknown): void {
91
+ const safe = safeMetadata(value);
92
+ if (!safe) return;
93
+ Object.defineProperty(record, key, {
94
+ value: safe,
95
+ writable: true,
96
+ enumerable: true,
97
+ configurable: true,
98
+ });
99
+ }
100
+
101
+ export function optionString(
102
+ context: CollectorContext,
103
+ module: Parameters<CollectorContext["options"]>[0],
104
+ key: string,
105
+ ): string | undefined {
106
+ const value = context.options(module)[key];
107
+ return typeof value === "string" ? value : undefined;
108
+ }
109
+
110
+ export function optionBoolean(
111
+ context: CollectorContext,
112
+ module: Parameters<CollectorContext["options"]>[0],
113
+ key: string,
114
+ ): boolean {
115
+ return context.options(module)[key] === true;
116
+ }
117
+
118
+ export function optionNumber(
119
+ context: CollectorContext,
120
+ module: Parameters<CollectorContext["options"]>[0],
121
+ key: string,
122
+ ): number | undefined {
123
+ const value = context.options(module)[key];
124
+ return typeof value === "number" ? value : undefined;
125
+ }
126
+
127
+ export function optionStrings(
128
+ context: CollectorContext,
129
+ module: Parameters<CollectorContext["options"]>[0],
130
+ key: string,
131
+ ): readonly string[] {
132
+ const value = context.options(module)[key];
133
+ return Array.isArray(value) && value.every((item) => typeof item === "string") ? value : [];
134
+ }
135
+
136
+ export function optionMap(
137
+ context: CollectorContext,
138
+ module: Parameters<CollectorContext["options"]>[0],
139
+ key: string,
140
+ ): Readonly<Record<string, string>> {
141
+ const value = context.options(module)[key];
142
+ return isRecord(value) ? (value as Record<string, string>) : {};
143
+ }
144
+
145
+ export function exactAlias(value: string | undefined, aliases: Readonly<Record<string, string>>) {
146
+ if (!value) return undefined;
147
+ return Object.hasOwn(aliases, value) ? safeMetadata(aliases[value]) : value;
148
+ }
149
+
150
+ export function formatVersion(raw: string, format: string | undefined): string {
151
+ return (format ?? "v$raw").replaceAll("$raw", raw.replace(/^v/u, ""));
152
+ }
153
+
154
+ export async function runBounded(
155
+ context: CollectorContext,
156
+ command: string,
157
+ args: string[],
158
+ ): Promise<string | undefined> {
159
+ try {
160
+ const result = await context.input.exec(command, args, {
161
+ cwd: context.input.cwd,
162
+ timeout: COMMAND_TIMEOUT_MS,
163
+ maxOutputBytes: MAX_COMMAND_OUTPUT_BYTES,
164
+ signal: context.input.signal,
165
+ environment: context.input.environment,
166
+ });
167
+ if (result.code !== 0 || result.killed) return undefined;
168
+ const selectedOutput = result.stdout || result.stderr;
169
+ const output = Buffer.from(selectedOutput).subarray(0, MAX_COMMAND_OUTPUT_BYTES + 1);
170
+ if (output.byteLength > MAX_COMMAND_OUTPUT_BYTES) return undefined;
171
+ return output.toString("utf8");
172
+ } catch {
173
+ return undefined;
174
+ }
175
+ }
176
+
177
+ export function parseIni(source: string): Record<string, Record<string, string>> {
178
+ const result: Record<string, Record<string, string>> = {};
179
+ let section = "";
180
+ for (const rawLine of source.split(/\r?\n/u)) {
181
+ const line = rawLine.trim();
182
+ if (!line || line.startsWith("#") || line.startsWith(";")) continue;
183
+ const sectionMatch = /^\[([^\]]+)\]$/u.exec(line);
184
+ if (sectionMatch?.[1]) {
185
+ section = sectionMatch[1].trim();
186
+ if (!Object.hasOwn(result, section)) setOwn(result, section, {});
187
+ continue;
188
+ }
189
+ const separator = line.indexOf("=");
190
+ if (separator <= 0) continue;
191
+ const key = line.slice(0, separator).trim();
192
+ const value = safeMetadata(line.slice(separator + 1));
193
+ if (!value) continue;
194
+ if (!Object.hasOwn(result, section)) setOwn(result, section, {});
195
+ setOwn(result[section] as Record<string, string>, key, value);
196
+ }
197
+ return result;
198
+ }
199
+
200
+ export function envPathList(value: string | undefined): string[] {
201
+ return (value ?? "")
202
+ .split(delimiter)
203
+ .map((part) => part.trim())
204
+ .filter(Boolean);
205
+ }
206
+
207
+ export function directMatch(
208
+ entries: readonly WorkspaceEntry[],
209
+ files: readonly string[],
210
+ extensions: readonly string[],
211
+ folders: readonly string[],
212
+ ): boolean {
213
+ const positiveFiles = files.filter((value) => !value.startsWith("!"));
214
+ const negativeFiles = new Set(
215
+ files.filter((value) => value.startsWith("!")).map((v) => v.slice(1)),
216
+ );
217
+ const positiveExtensions = extensions
218
+ .filter((value) => !value.startsWith("!"))
219
+ .map((value) => value.replace(/^\./u, ""));
220
+ const negativeExtensions = new Set(
221
+ extensions
222
+ .filter((value) => value.startsWith("!"))
223
+ .map((value) => value.slice(1).replace(/^\./u, "")),
224
+ );
225
+ const positiveFolders = folders.filter((value) => !value.startsWith("!"));
226
+ const negativeFolders = new Set(
227
+ folders.filter((value) => value.startsWith("!")).map((value) => value.slice(1)),
228
+ );
229
+ if (
230
+ entries.some(
231
+ (entry) =>
232
+ negativeFiles.has(entry.name) ||
233
+ (entry.isFile && negativeExtensions.has(extname(entry.name).slice(1))) ||
234
+ (entry.isDirectory && negativeFolders.has(entry.name)),
235
+ )
236
+ ) {
237
+ return false;
238
+ }
239
+ return entries.some(
240
+ (entry) =>
241
+ positiveFiles.includes(entry.name) ||
242
+ (entry.isFile && positiveExtensions.includes(extname(entry.name).slice(1))) ||
243
+ (entry.isDirectory && positiveFolders.includes(entry.name)),
244
+ );
245
+ }
246
+
247
+ export function parentDirectories(start: string, limit: number): string[] {
248
+ const result: string[] = [];
249
+ let current = resolve(start);
250
+ for (let index = 0; index < limit; index += 1) {
251
+ const parent = dirname(current);
252
+ if (parent === current) break;
253
+ result.push(parent);
254
+ current = parent;
255
+ }
256
+ return result;
257
+ }
258
+
259
+ export function pathName(path: string): string {
260
+ return basename(path.replace(/[\\/]+$/u, "")) || path;
261
+ }
262
+
263
+ export function joinHome(input: WorkspaceRefreshInput, ...parts: string[]): string {
264
+ return join(input.homeDir, ...parts);
265
+ }
266
+
267
+ function setOwn<T>(record: Record<string, T>, key: string, value: T): void {
268
+ Object.defineProperty(record, key, {
269
+ value,
270
+ writable: true,
271
+ enumerable: true,
272
+ configurable: true,
273
+ });
274
+ }
@@ -0,0 +1,205 @@
1
+ import { delimiter, join } from "node:path";
2
+ import {
3
+ directMatch,
4
+ formatVersion,
5
+ MAX_METADATA_FILE_BYTES,
6
+ optionString,
7
+ optionStrings,
8
+ pathName,
9
+ runBounded,
10
+ safeMetadata,
11
+ } from "./helpers.js";
12
+ import type { CollectorContext, MutableModuleSnapshot } from "./types.js";
13
+
14
+ const LANGUAGE_NAMES = ["nodejs", "python", "rust", "golang", "bun", "deno"] as const;
15
+ type LanguageName = (typeof LANGUAGE_NAMES)[number];
16
+
17
+ const DEFAULT_DETECTION: Record<
18
+ LanguageName,
19
+ { files: string[]; extensions: string[]; folders: string[] }
20
+ > = {
21
+ nodejs: {
22
+ files: [
23
+ "package.json",
24
+ ".node-version",
25
+ ".nvmrc",
26
+ "!bun.lock",
27
+ "!bun.lockb",
28
+ "!deno.json",
29
+ "!deno.jsonc",
30
+ ],
31
+ extensions: ["js", "mjs", "cjs", "ts", "mts", "cts"],
32
+ folders: ["node_modules"],
33
+ },
34
+ python: {
35
+ files: ["pyproject.toml", "requirements.txt", "Pipfile", "poetry.lock", ".python-version"],
36
+ extensions: ["py"],
37
+ folders: [".venv", "venv"],
38
+ },
39
+ rust: { files: ["Cargo.toml"], extensions: ["rs"], folders: [] },
40
+ golang: { files: ["go.mod", "go.sum", "go.work"], extensions: ["go"], folders: [] },
41
+ bun: { files: ["bun.lock", "bun.lockb", "bunfig.toml"], extensions: [], folders: [] },
42
+ deno: { files: ["deno.json", "deno.jsonc", "deno.lock"], extensions: [], folders: [] },
43
+ };
44
+
45
+ export async function collectLanguages(context: CollectorContext): Promise<MutableModuleSnapshot> {
46
+ const result: MutableModuleSnapshot = {};
47
+ if (!LANGUAGE_NAMES.some((name) => context.needs(name))) return result;
48
+ const entries = await context.entries();
49
+ for (const name of LANGUAGE_NAMES) {
50
+ if (!context.needs(name)) continue;
51
+ const defaults = DEFAULT_DETECTION[name];
52
+ const files = optionStrings(context, name, "detect_files");
53
+ const extensions = optionStrings(context, name, "detect_extensions");
54
+ const folders = optionStrings(context, name, "detect_folders");
55
+ if (
56
+ !directMatch(
57
+ entries,
58
+ files.length > 0 ? files : defaults.files,
59
+ extensions.length > 0 ? extensions : defaults.extensions,
60
+ folders.length > 0 ? folders : defaults.folders,
61
+ )
62
+ ) {
63
+ continue;
64
+ }
65
+ const values: Record<string, string> = {};
66
+ addEnvironmentValues(context, name, values);
67
+ if (context.needs(name, "engines_version")) {
68
+ const engine = await readNodeEngine(context);
69
+ if (engine) values.engines_version = engine;
70
+ }
71
+ const needsVersion = context.needs(name, "version");
72
+ const needsNumver = name === "rust" && context.needs(name, "numver");
73
+ if (needsVersion || needsNumver) {
74
+ const command = await versionCommand(context, name);
75
+ if (command) {
76
+ const output = await runBounded(context, command[0], command[1]);
77
+ const version = output ? parseRuntimeVersion(name, output) : undefined;
78
+ if (version) {
79
+ if (needsVersion) {
80
+ values.version = formatVersion(version, optionString(context, name, "version_format"));
81
+ }
82
+ if (needsNumver) values.numver = version.replace(/^v/u, "");
83
+ }
84
+ }
85
+ }
86
+ result[name] = values;
87
+ }
88
+ return result;
89
+ }
90
+
91
+ function addEnvironmentValues(
92
+ context: CollectorContext,
93
+ name: LanguageName,
94
+ values: Record<string, string>,
95
+ ): void {
96
+ const env = context.input.environment;
97
+ if (name === "python") {
98
+ const virtualenv = safeMetadata(env.VIRTUAL_ENV ?? env.CONDA_DEFAULT_ENV);
99
+ if (virtualenv && context.needs(name, "virtualenv")) values.virtualenv = pathName(virtualenv);
100
+ const pyenv = safeMetadata(env.PYENV_VERSION);
101
+ if (pyenv && context.needs(name, "pyenv_prefix")) values.pyenv_prefix = pyenv;
102
+ }
103
+ if (name === "rust") {
104
+ const toolchain = safeMetadata(env.RUSTUP_TOOLCHAIN);
105
+ if (toolchain && context.needs(name, "toolchain")) values.toolchain = toolchain;
106
+ }
107
+ }
108
+
109
+ async function readNodeEngine(context: CollectorContext): Promise<string | undefined> {
110
+ const source = await context.fs.readFile(
111
+ join(context.input.cwd, "package.json"),
112
+ MAX_METADATA_FILE_BYTES,
113
+ );
114
+ if (!source) return undefined;
115
+ try {
116
+ const document = JSON.parse(source) as { engines?: { node?: unknown } };
117
+ return safeMetadata(document.engines?.node, 80);
118
+ } catch {
119
+ return undefined;
120
+ }
121
+ }
122
+
123
+ async function versionCommand(
124
+ context: CollectorContext,
125
+ name: LanguageName,
126
+ ): Promise<[string, string[]] | undefined> {
127
+ switch (name) {
128
+ case "nodejs":
129
+ return ["node", ["--version"]];
130
+ case "python": {
131
+ const virtualenv = safeMetadata(context.input.environment.VIRTUAL_ENV);
132
+ if (virtualenv) {
133
+ const candidate = join(
134
+ virtualenv,
135
+ context.input.platform === "win32" ? "Scripts/python.exe" : "bin/python",
136
+ );
137
+ if (await context.fs.fileExists(candidate)) return [candidate, ["--version"]];
138
+ }
139
+ return ["python", ["--version"]];
140
+ }
141
+ case "rust": {
142
+ const rustc = await safeRustCompiler(context);
143
+ return rustc ? [rustc, ["--version"]] : undefined;
144
+ }
145
+ case "golang":
146
+ return ["go", ["version"]];
147
+ case "bun":
148
+ return ["bun", ["--version"]];
149
+ case "deno":
150
+ return ["deno", ["-V"]];
151
+ }
152
+ }
153
+
154
+ async function safeRustCompiler(context: CollectorContext): Promise<string | undefined> {
155
+ const candidates = [
156
+ context.input.environment.RUSTC,
157
+ ...(context.input.environment.PATH ?? "")
158
+ .split(delimiter)
159
+ .filter(Boolean)
160
+ .map((directory) =>
161
+ join(directory, context.input.platform === "win32" ? "rustc.exe" : "rustc"),
162
+ ),
163
+ ];
164
+ for (const rawCandidate of candidates) {
165
+ const candidate = safeMetadata(rawCandidate, 1_024);
166
+ if (!candidate || /(?:^|[\\/])\.(?:cargo|rustup)(?:[\\/]|$)/iu.test(candidate)) continue;
167
+ if (await context.fs.fileExists(candidate)) return candidate;
168
+ }
169
+ return undefined;
170
+ }
171
+
172
+ export function parseRuntimeVersion(name: LanguageName, output: string): string | undefined {
173
+ const normalized = output.trim();
174
+ if (
175
+ !normalized ||
176
+ normalized.includes("\n") ||
177
+ normalized.includes("\r") ||
178
+ normalized.includes("�")
179
+ ) {
180
+ return undefined;
181
+ }
182
+ let match: RegExpExecArray | null;
183
+ switch (name) {
184
+ case "nodejs":
185
+ match = /^v(\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?)$/u.exec(normalized);
186
+ break;
187
+ case "python":
188
+ match = /^Python (\d+\.\d+(?:\.\d+)?(?:[0-9A-Za-z.+-]*)?)$/u.exec(normalized);
189
+ break;
190
+ case "rust":
191
+ match = /^rustc (\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?)(?: .*)?$/u.exec(normalized);
192
+ break;
193
+ case "golang":
194
+ match = /^go version go(\d+\.\d+(?:\.\d+)?(?:[0-9A-Za-z.+-]*))(?:\s+.*)?$/u.exec(normalized);
195
+ break;
196
+ case "bun":
197
+ match = /^(\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?)$/u.exec(normalized);
198
+ break;
199
+ case "deno":
200
+ match = /^(?:deno\s+)?(\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?)$/u.exec(normalized);
201
+ break;
202
+ }
203
+ const version = match?.[1];
204
+ return version ? `v${version}` : undefined;
205
+ }
@@ -0,0 +1,112 @@
1
+ import { join } from "node:path";
2
+ import { parse } from "smol-toml";
3
+ import {
4
+ formatVersion,
5
+ isRecord,
6
+ MAX_METADATA_FILE_BYTES,
7
+ optionString,
8
+ parentDirectories,
9
+ safeMetadata,
10
+ } from "./helpers.js";
11
+ import type { CollectorContext } from "./types.js";
12
+
13
+ export async function collectPackage(
14
+ context: CollectorContext,
15
+ ): Promise<Record<string, string> | undefined> {
16
+ if (!context.needs("package")) return undefined;
17
+ const versionFormat = optionString(context, "package", "version_format");
18
+ for (const reader of [readPackageJson, readCargo, readPyproject]) {
19
+ const result = await reader(context);
20
+ if (!result) continue;
21
+ return {
22
+ source: result.source,
23
+ version: formatVersion(result.version, versionFormat),
24
+ };
25
+ }
26
+ return undefined;
27
+ }
28
+
29
+ interface PackageVersion {
30
+ version: string;
31
+ source: string;
32
+ }
33
+
34
+ async function readPackageJson(context: CollectorContext): Promise<PackageVersion | undefined> {
35
+ const source = await context.fs.readFile(
36
+ join(context.input.cwd, "package.json"),
37
+ MAX_METADATA_FILE_BYTES,
38
+ );
39
+ if (!source) return undefined;
40
+ try {
41
+ const document = JSON.parse(source) as unknown;
42
+ const version = isRecord(document) ? safeVersion(document.version) : undefined;
43
+ return version ? { version, source: "package.json" } : undefined;
44
+ } catch {
45
+ return undefined;
46
+ }
47
+ }
48
+
49
+ async function readCargo(context: CollectorContext): Promise<PackageVersion | undefined> {
50
+ const path = join(context.input.cwd, "Cargo.toml");
51
+ const source = await context.fs.readFile(path, MAX_METADATA_FILE_BYTES);
52
+ if (!source) return undefined;
53
+ try {
54
+ const document = parse(source);
55
+ const packageTable = isRecord(document.package) ? document.package : undefined;
56
+ const direct = safeVersion(packageTable?.version);
57
+ if (direct) return { version: direct, source: "Cargo.toml" };
58
+ const inherited = isRecord(packageTable?.version) && packageTable.version.workspace === true;
59
+ if (!inherited) return undefined;
60
+ const localWorkspaceVersion = workspacePackageVersion(document);
61
+ if (localWorkspaceVersion) {
62
+ return { version: localWorkspaceVersion, source: "Cargo.toml workspace" };
63
+ }
64
+ for (const parent of parentDirectories(context.input.cwd, 8)) {
65
+ const parentSource = await context.fs.readFile(
66
+ join(parent, "Cargo.toml"),
67
+ MAX_METADATA_FILE_BYTES,
68
+ );
69
+ if (!parentSource) continue;
70
+ const parentDocument = parse(parentSource);
71
+ const version = workspacePackageVersion(parentDocument);
72
+ if (version) return { version, source: "Cargo.toml workspace" };
73
+ }
74
+ return undefined;
75
+ } catch {
76
+ return undefined;
77
+ }
78
+ }
79
+
80
+ function workspacePackageVersion(document: Record<string, unknown>): string | undefined {
81
+ const workspace = isRecord(document.workspace) ? document.workspace : undefined;
82
+ const workspacePackage = isRecord(workspace?.package) ? workspace.package : undefined;
83
+ return safeVersion(workspacePackage?.version);
84
+ }
85
+
86
+ async function readPyproject(context: CollectorContext): Promise<PackageVersion | undefined> {
87
+ const source = await context.fs.readFile(
88
+ join(context.input.cwd, "pyproject.toml"),
89
+ MAX_METADATA_FILE_BYTES,
90
+ );
91
+ if (!source) return undefined;
92
+ try {
93
+ const document = parse(source);
94
+ const project = isRecord(document.project) ? document.project : undefined;
95
+ if (Array.isArray(project?.dynamic) && project.dynamic.includes("version")) return undefined;
96
+ const pepVersion = safeVersion(project?.version);
97
+ if (pepVersion) return { version: pepVersion, source: "pyproject.toml (PEP 621)" };
98
+ const tool = isRecord(document.tool) ? document.tool : undefined;
99
+ const poetry = isRecord(tool?.poetry) ? tool.poetry : undefined;
100
+ const poetryVersion = safeVersion(poetry?.version);
101
+ return poetryVersion
102
+ ? { version: poetryVersion, source: "pyproject.toml (Poetry)" }
103
+ : undefined;
104
+ } catch {
105
+ return undefined;
106
+ }
107
+ }
108
+
109
+ function safeVersion(value: unknown): string | undefined {
110
+ const version = safeMetadata(value, 80);
111
+ return version && /^[0-9A-Za-z][0-9A-Za-z.+_-]*$/u.test(version) ? version : undefined;
112
+ }
@@ -0,0 +1,107 @@
1
+ export interface AsyncRefreshControllerOptions<Input, Snapshot> {
2
+ read(input: Input, signal: AbortSignal): Promise<Snapshot>;
3
+ equal(left: Snapshot | undefined, right: Snapshot): boolean;
4
+ publish(snapshot: Snapshot): void;
5
+ onError?(error: unknown): void;
6
+ }
7
+
8
+ interface RefreshRequest<Input> {
9
+ generation: number;
10
+ requestId: number;
11
+ input: Input;
12
+ }
13
+
14
+ interface ActiveRefresh<Input> {
15
+ request: RefreshRequest<Input>;
16
+ controller: AbortController;
17
+ }
18
+
19
+ /** Coalesces refreshes to one active read plus the latest pending request. */
20
+ export class AsyncRefreshController<Input, Snapshot> {
21
+ private generation: number | undefined;
22
+ private requestId = 0;
23
+ private active: ActiveRefresh<Input> | undefined;
24
+ private pending: RefreshRequest<Input> | undefined;
25
+ private current: Snapshot | undefined;
26
+
27
+ constructor(private readonly options: AsyncRefreshControllerOptions<Input, Snapshot>) {}
28
+
29
+ start(generation: number): void {
30
+ this.cancelActive("Refresh generation replaced");
31
+ this.generation = generation;
32
+ this.requestId += 1;
33
+ this.pending = undefined;
34
+ this.current = undefined;
35
+ }
36
+
37
+ clear(): void {
38
+ this.current = undefined;
39
+ }
40
+
41
+ request(input: Input): void {
42
+ if (this.generation === undefined) return;
43
+ const request = {
44
+ generation: this.generation,
45
+ requestId: ++this.requestId,
46
+ input,
47
+ };
48
+ if (this.active) {
49
+ this.pending = request;
50
+ return;
51
+ }
52
+ this.run(request);
53
+ }
54
+
55
+ stop(): void {
56
+ this.generation = undefined;
57
+ this.requestId += 1;
58
+ this.pending = undefined;
59
+ this.current = undefined;
60
+ this.cancelActive("Refresh controller stopped");
61
+ }
62
+
63
+ private run(request: RefreshRequest<Input>): void {
64
+ if (!this.isCurrentTarget(request)) return;
65
+ const active: ActiveRefresh<Input> = {
66
+ request,
67
+ controller: new AbortController(),
68
+ };
69
+ this.active = active;
70
+ void this.options
71
+ .read(request.input, active.controller.signal)
72
+ .then((snapshot) => {
73
+ if (this.active !== active || !this.isCurrentRequest(request)) return;
74
+ if (this.options.equal(this.current, snapshot)) return;
75
+ this.current = snapshot;
76
+ this.options.publish(snapshot);
77
+ })
78
+ .catch((error: unknown) => {
79
+ if (
80
+ this.active === active &&
81
+ this.isCurrentRequest(request) &&
82
+ !active.controller.signal.aborted
83
+ ) {
84
+ this.options.onError?.(error);
85
+ }
86
+ })
87
+ .finally(() => {
88
+ if (this.active !== active) return;
89
+ this.active = undefined;
90
+ const pending = this.pending;
91
+ this.pending = undefined;
92
+ if (pending) this.run(pending);
93
+ });
94
+ }
95
+
96
+ private cancelActive(reason: string): void {
97
+ this.active?.controller.abort(new DOMException(reason, "AbortError"));
98
+ }
99
+
100
+ private isCurrentTarget(request: RefreshRequest<Input>): boolean {
101
+ return this.generation !== undefined && request.generation === this.generation;
102
+ }
103
+
104
+ private isCurrentRequest(request: RefreshRequest<Input>): boolean {
105
+ return this.isCurrentTarget(request) && request.requestId === this.requestId;
106
+ }
107
+ }