@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,55 @@
1
+ export const PURE_PRESET = `# Pi-native adaptation of Starship's Pure preset.
2
+ format = "$directory$git_branch$git_state$git_status$activity\\n$model$thinking$context$fill$time"
3
+
4
+ [directory]
5
+ format = "[$path]($style) "
6
+ symbol = ""
7
+ style = "blue"
8
+
9
+ [git_branch]
10
+ format = "[$branch]($style) "
11
+ symbol = ""
12
+ style = "bright-black"
13
+
14
+ [git_state]
15
+ format = '([($state( $progress_current/$progress_total))]($style) )'
16
+ symbol = ""
17
+ style = "bright-black"
18
+
19
+ [git_status]
20
+ format = "[(*$all_status)](218) [$ahead_behind]($style) "
21
+ style = "cyan"
22
+
23
+ [activity]
24
+ format = "[$text]($style) "
25
+ symbol = ""
26
+ style = "yellow"
27
+
28
+ [model]
29
+ format = "[$model]($style) "
30
+ symbol = ""
31
+ style = "bright-black"
32
+
33
+ [thinking]
34
+ format = "[$level]($style) "
35
+ symbol = ""
36
+ style = "bright-black"
37
+
38
+ [context]
39
+ format = "[$percentage]($style)"
40
+ symbol = ""
41
+
42
+ [[context.display]]
43
+ threshold = 0
44
+ style = "bright-black"
45
+ hidden = false
46
+
47
+ [fill]
48
+ symbol = " "
49
+ style = "none"
50
+
51
+ [time]
52
+ format = "[$time]($style)"
53
+ symbol = ""
54
+ style = "bright-black"
55
+ `;
@@ -0,0 +1,53 @@
1
+ export const TOKYO_NIGHT_PRESET = `# Pi-native adaptation of Starship's Tokyo Night preset.
2
+ format = "[░▒▓](#a3aed2)$brand$model[](bg:#769ff0 fg:#a3aed2)$directory[](fg:#769ff0 bg:#394260)$git_branch$git_status[](fg:#394260 bg:#212736)$thinking$activity[](fg:#212736 bg:#1d2230)$context$time[](fg:#1d2230)"
3
+
4
+ [brand]
5
+ format = "[ $symbol ]($style)"
6
+ symbol = ""
7
+ style = "fg:#090c0c bg:#a3aed2 bold"
8
+
9
+ [model]
10
+ format = "[$model ]($style)"
11
+ symbol = ""
12
+ style = "fg:#090c0c bg:#a3aed2 bold"
13
+
14
+ [directory]
15
+ format = "[ $path ]($style)"
16
+ symbol = ""
17
+ style = "fg:#e3e5e5 bg:#769ff0 bold"
18
+ truncation_length = 3
19
+ truncation_symbol = "…/"
20
+
21
+ [git_branch]
22
+ format = "[ $symbol $branch ]($style)"
23
+ symbol = ""
24
+ style = "fg:#769ff0 bg:#394260 bold"
25
+
26
+ [git_status]
27
+ format = "[$all_status$ahead_behind ]($style)"
28
+ style = "fg:#769ff0 bg:#394260 bold"
29
+
30
+ [thinking]
31
+ format = "[ $symbol $level ]($style)"
32
+ symbol = "󰔟"
33
+ style = "fg:#769ff0 bg:#212736 bold"
34
+
35
+ [activity]
36
+ format = "[ $text ]($style)"
37
+ symbol = "󰑮"
38
+ style = "fg:#769ff0 bg:#212736 bold"
39
+
40
+ [context]
41
+ format = "[ $symbol $percentage ](fg:#a0a9cb bg:#1d2230 bold)"
42
+ symbol = "󰍛"
43
+
44
+ [[context.display]]
45
+ threshold = 0
46
+ style = "#1d2230"
47
+ hidden = false
48
+
49
+ [time]
50
+ format = "[ $time ]($style)"
51
+ symbol = ""
52
+ style = "fg:#a0a9cb bg:#1d2230 bold"
53
+ `;
@@ -0,0 +1,166 @@
1
+ import { join } from "node:path";
2
+ import { parse as parseYaml } from "yaml";
3
+ import {
4
+ exactAlias,
5
+ isRecord,
6
+ joinHome,
7
+ MAX_METADATA_FILE_BYTES,
8
+ optionBoolean,
9
+ optionMap,
10
+ parseIni,
11
+ safeMetadata,
12
+ } from "./helpers.js";
13
+ import type { CollectorContext, MutableModuleSnapshot } from "./types.js";
14
+
15
+ export async function collectCloud(context: CollectorContext): Promise<MutableModuleSnapshot> {
16
+ const result: MutableModuleSnapshot = {};
17
+ if (context.needs("aws")) {
18
+ const values = await collectAws(context);
19
+ if (values) result.aws = values;
20
+ }
21
+ if (context.needs("gcloud")) {
22
+ const values = await collectGcloud(context);
23
+ if (values) result.gcloud = values;
24
+ }
25
+ if (context.needs("azure")) {
26
+ const values = await collectAzure(context);
27
+ if (values) result.azure = values;
28
+ }
29
+ if (context.needs("openstack")) {
30
+ const values = await collectOpenstack(context);
31
+ if (values) result.openstack = values;
32
+ }
33
+ return result;
34
+ }
35
+
36
+ async function collectAws(context: CollectorContext): Promise<Record<string, string> | undefined> {
37
+ const env = context.input.environment;
38
+ const profile = safeMetadata(env.AWS_PROFILE ?? env.AWS_DEFAULT_PROFILE) ?? "default";
39
+ let region = safeMetadata(env.AWS_REGION ?? env.AWS_DEFAULT_REGION);
40
+ if (!region) {
41
+ const configPath =
42
+ safeMetadata(env.AWS_CONFIG_FILE, 1_024) ?? joinHome(context.input, ".aws", "config");
43
+ const source = await context.fs.readFile(configPath, MAX_METADATA_FILE_BYTES);
44
+ if (source) {
45
+ const section = profile === "default" ? "default" : `profile ${profile}`;
46
+ region = safeMetadata(parseIni(source)[section]?.region);
47
+ }
48
+ }
49
+ if (profile === "default" && !region && !env.AWS_PROFILE && !env.AWS_DEFAULT_PROFILE)
50
+ return undefined;
51
+ const values: Record<string, string> = {
52
+ profile: exactAlias(profile, optionMap(context, "aws", "profile_aliases")) ?? profile,
53
+ };
54
+ if (region)
55
+ values.region = exactAlias(region, optionMap(context, "aws", "region_aliases")) ?? region;
56
+ return values;
57
+ }
58
+
59
+ async function collectGcloud(
60
+ context: CollectorContext,
61
+ ): Promise<Record<string, string> | undefined> {
62
+ const env = context.input.environment;
63
+ const directory =
64
+ safeMetadata(env.CLOUDSDK_CONFIG, 1_024) ?? joinHome(context.input, ".config", "gcloud");
65
+ const active =
66
+ safeMetadata(env.CLOUDSDK_ACTIVE_CONFIG_NAME) ??
67
+ safeMetadata(await context.fs.readFile(join(directory, "active_config"), 256));
68
+ if (!active || !/^[A-Za-z0-9_-]+$/u.test(active)) return undefined;
69
+ const source = await context.fs.readFile(
70
+ join(directory, "configurations", `config_${active}`),
71
+ MAX_METADATA_FILE_BYTES,
72
+ );
73
+ if (!source) return { active };
74
+ const document = parseIni(source);
75
+ const account = safeMetadata(document.core?.account);
76
+ const project = safeMetadata(document.core?.project);
77
+ const region = safeMetadata(document.compute?.region);
78
+ const values: Record<string, string> = { active };
79
+ if (account) {
80
+ values.account = account;
81
+ const separator = account.lastIndexOf("@");
82
+ if (separator >= 0 && separator < account.length - 1)
83
+ values.domain = account.slice(separator + 1);
84
+ }
85
+ if (project) {
86
+ values.project =
87
+ exactAlias(project, optionMap(context, "gcloud", "project_aliases")) ?? project;
88
+ }
89
+ if (region)
90
+ values.region = exactAlias(region, optionMap(context, "gcloud", "region_aliases")) ?? region;
91
+ return values;
92
+ }
93
+
94
+ async function collectAzure(
95
+ context: CollectorContext,
96
+ ): Promise<Record<string, string> | undefined> {
97
+ const directory =
98
+ safeMetadata(context.input.environment.AZURE_CONFIG_DIR, 1_024) ??
99
+ joinHome(context.input, ".azure");
100
+ const source = await context.fs.readFile(
101
+ join(directory, "azureProfile.json"),
102
+ MAX_METADATA_FILE_BYTES,
103
+ );
104
+ if (!source) return undefined;
105
+ try {
106
+ const document = JSON.parse(source.replace(/^\uFEFF/u, "")) as unknown;
107
+ const subscriptions =
108
+ isRecord(document) && Array.isArray(document.subscriptions)
109
+ ? document.subscriptions.filter(isRecord)
110
+ : [];
111
+ const selected = subscriptions.find((item) => item.isDefault === true) ?? subscriptions[0];
112
+ const subscription = safeMetadata(selected?.name);
113
+ if (!subscription) return undefined;
114
+ const values: Record<string, string> = {
115
+ subscription:
116
+ exactAlias(subscription, optionMap(context, "azure", "subscription_aliases")) ??
117
+ subscription,
118
+ };
119
+ if (optionBoolean(context, "azure", "show_username")) {
120
+ const user = isRecord(selected?.user) ? selected.user : undefined;
121
+ const username = safeMetadata(user?.name);
122
+ if (username) values.username = username;
123
+ }
124
+ return values;
125
+ } catch {
126
+ return undefined;
127
+ }
128
+ }
129
+
130
+ async function collectOpenstack(
131
+ context: CollectorContext,
132
+ ): Promise<Record<string, string> | undefined> {
133
+ const env = context.input.environment;
134
+ const cloud = safeMetadata(env.OS_CLOUD);
135
+ let project = safeMetadata(env.OS_PROJECT_NAME);
136
+ if (!cloud) return undefined;
137
+ if (!project) {
138
+ const path =
139
+ safeMetadata(env.OS_CLIENT_CONFIG_FILE, 1_024) ??
140
+ joinHome(context.input, ".config", "openstack", "clouds.yaml");
141
+ const source = await context.fs.readFile(path, MAX_METADATA_FILE_BYTES);
142
+ if (source) {
143
+ try {
144
+ const document = parseYaml(source) as unknown;
145
+ const clouds =
146
+ isRecord(document) && isRecord(document.clouds) ? document.clouds : undefined;
147
+ const selected =
148
+ clouds && Object.hasOwn(clouds, cloud) && isRecord(clouds[cloud])
149
+ ? clouds[cloud]
150
+ : undefined;
151
+ const auth = isRecord(selected?.auth) ? selected.auth : undefined;
152
+ project = safeMetadata(auth?.project_name);
153
+ } catch {
154
+ // Malformed YAML is ignored.
155
+ }
156
+ }
157
+ }
158
+ const values: Record<string, string> = {
159
+ cloud: exactAlias(cloud, optionMap(context, "openstack", "cloud_aliases")) ?? cloud,
160
+ };
161
+ if (project) {
162
+ values.project =
163
+ exactAlias(project, optionMap(context, "openstack", "project_aliases")) ?? project;
164
+ }
165
+ return values;
166
+ }
@@ -0,0 +1,123 @@
1
+ import { spawn } from "node:child_process";
2
+ import type { WorkspaceExec } from "./types.js";
3
+
4
+ const FORCE_KILL_DELAY_MS = 250;
5
+
6
+ export const execWorkspaceCommand: WorkspaceExec = async (command, args, options) =>
7
+ new Promise((resolve) => {
8
+ if (options.signal?.aborted) {
9
+ resolve({ stdout: "", stderr: "", code: 1, killed: true });
10
+ return;
11
+ }
12
+
13
+ let child: ReturnType<typeof spawn>;
14
+ try {
15
+ child = spawn(command, args, {
16
+ cwd: options.cwd,
17
+ detached: process.platform !== "win32",
18
+ env: explicitEnvironment(options.environment),
19
+ shell: false,
20
+ stdio: ["ignore", "pipe", "pipe"],
21
+ windowsHide: true,
22
+ });
23
+ } catch {
24
+ resolve({ stdout: "", stderr: "", code: 1, killed: false });
25
+ return;
26
+ }
27
+
28
+ const stdout: Buffer[] = [];
29
+ const stderr: Buffer[] = [];
30
+ let outputBytes = 0;
31
+ let killed = false;
32
+ let settled = false;
33
+ let forceKillTimer: NodeJS.Timeout | undefined;
34
+ let timeoutTimer: NodeJS.Timeout | undefined;
35
+
36
+ const finish = (code: number) => {
37
+ if (settled) return;
38
+ settled = true;
39
+ if (timeoutTimer) clearTimeout(timeoutTimer);
40
+ if (forceKillTimer) clearTimeout(forceKillTimer);
41
+ options.signal?.removeEventListener("abort", terminate);
42
+ resolve({
43
+ stdout: Buffer.concat(stdout).toString("utf8"),
44
+ stderr: Buffer.concat(stderr).toString("utf8"),
45
+ code,
46
+ killed,
47
+ });
48
+ };
49
+
50
+ const signalProcessTree = (signal: NodeJS.Signals) => {
51
+ const pid = child.pid;
52
+ if (pid === undefined) return;
53
+ if (process.platform !== "win32") {
54
+ try {
55
+ process.kill(-pid, signal);
56
+ return;
57
+ } catch {
58
+ child.kill(signal);
59
+ return;
60
+ }
61
+ }
62
+ try {
63
+ const killer = spawn("taskkill.exe", ["/pid", String(pid), "/t", "/f"], {
64
+ stdio: "ignore",
65
+ windowsHide: true,
66
+ });
67
+ killer.once("error", () => child.kill(signal));
68
+ killer.unref();
69
+ } catch {
70
+ child.kill(signal);
71
+ }
72
+ };
73
+
74
+ function terminate() {
75
+ if (killed || settled) return;
76
+ killed = true;
77
+ signalProcessTree("SIGTERM");
78
+ forceKillTimer = setTimeout(() => {
79
+ signalProcessTree("SIGKILL");
80
+ child.stdout?.destroy();
81
+ child.stderr?.destroy();
82
+ finish(1);
83
+ }, FORCE_KILL_DELAY_MS);
84
+ }
85
+
86
+ const collect = (target: Buffer[]) => (data: Buffer | string) => {
87
+ const chunk = Buffer.isBuffer(data) ? data : Buffer.from(data);
88
+ const remaining = Math.max(0, options.maxOutputBytes - outputBytes);
89
+ if (remaining > 0) target.push(chunk.subarray(0, remaining));
90
+ outputBytes += chunk.byteLength;
91
+ if (outputBytes > options.maxOutputBytes) terminate();
92
+ };
93
+
94
+ child.stdout?.on("data", collect(stdout));
95
+ child.stderr?.on("data", collect(stderr));
96
+ child.once("error", () => {
97
+ if (!killed) finish(1);
98
+ });
99
+ child.once("close", (code) => {
100
+ if (!killed) finish(code ?? 1);
101
+ });
102
+ options.signal?.addEventListener("abort", terminate, { once: true });
103
+ if (options.signal?.aborted) terminate();
104
+ timeoutTimer = setTimeout(terminate, options.timeout);
105
+ });
106
+
107
+ function explicitEnvironment(
108
+ source: Readonly<Record<string, string | undefined>>,
109
+ ): NodeJS.ProcessEnv {
110
+ const result: NodeJS.ProcessEnv = Object.create(null);
111
+ for (const [name, value] of Object.entries(source)) {
112
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(name) || value === undefined || value.includes("\0")) {
113
+ continue;
114
+ }
115
+ Object.defineProperty(result, name, {
116
+ value,
117
+ writable: true,
118
+ enumerable: true,
119
+ configurable: true,
120
+ });
121
+ }
122
+ return result;
123
+ }
@@ -0,0 +1,201 @@
1
+ import { extname, isAbsolute, join, resolve } from "node:path";
2
+ import { parse as parseYaml } from "yaml";
3
+ import {
4
+ directMatch,
5
+ exactAlias,
6
+ formatVersion,
7
+ isRecord,
8
+ joinHome,
9
+ MAX_METADATA_FILE_BYTES,
10
+ optionBoolean,
11
+ optionMap,
12
+ optionNumber,
13
+ optionString,
14
+ optionStrings,
15
+ runBounded,
16
+ safeMetadata,
17
+ } from "./helpers.js";
18
+ import type { CollectorContext, MutableModuleSnapshot } from "./types.js";
19
+
20
+ export async function collectDeployment(context: CollectorContext): Promise<MutableModuleSnapshot> {
21
+ const result: MutableModuleSnapshot = {};
22
+ if (context.needs("docker_context")) {
23
+ const docker = await collectDocker(context);
24
+ if (docker) result.docker_context = docker;
25
+ }
26
+ if (context.needs("kubernetes")) {
27
+ const kubernetes = await collectKubernetes(context);
28
+ if (kubernetes) result.kubernetes = kubernetes;
29
+ }
30
+ if (context.needs("terraform")) {
31
+ const terraform = await collectTerraform(context);
32
+ if (terraform) result.terraform = terraform;
33
+ }
34
+ return result;
35
+ }
36
+
37
+ async function collectDocker(
38
+ context: CollectorContext,
39
+ ): Promise<Record<string, string> | undefined> {
40
+ const entries = await context.entries();
41
+ if (optionBoolean(context, "docker_context", "only_with_files")) {
42
+ const configuredFiles = optionStrings(context, "docker_context", "detect_files");
43
+ if (
44
+ !directMatch(
45
+ entries,
46
+ configuredFiles.length > 0
47
+ ? configuredFiles
48
+ : [
49
+ "Dockerfile",
50
+ "docker-compose.yml",
51
+ "docker-compose.yaml",
52
+ "compose.yml",
53
+ "compose.yaml",
54
+ ],
55
+ optionStrings(context, "docker_context", "detect_extensions"),
56
+ optionStrings(context, "docker_context", "detect_folders"),
57
+ )
58
+ ) {
59
+ return undefined;
60
+ }
61
+ }
62
+ let active = safeMetadata(context.input.environment.DOCKER_CONTEXT);
63
+ if (!active) {
64
+ const configDirectory =
65
+ safeMetadata(context.input.environment.DOCKER_CONFIG, 1_024) ??
66
+ joinHome(context.input, ".docker");
67
+ const source = await context.fs.readFile(
68
+ join(configDirectory, "config.json"),
69
+ MAX_METADATA_FILE_BYTES,
70
+ );
71
+ if (source) {
72
+ try {
73
+ const document = JSON.parse(source) as unknown;
74
+ active = isRecord(document) ? safeMetadata(document.currentContext) : undefined;
75
+ } catch {
76
+ // Malformed metadata degrades to an empty module.
77
+ }
78
+ }
79
+ }
80
+ return active && active !== "default" ? { context: active } : undefined;
81
+ }
82
+
83
+ async function collectKubernetes(
84
+ context: CollectorContext,
85
+ ): Promise<Record<string, string> | undefined> {
86
+ const selected = safeMetadata(context.input.environment.KUBECONFIG, 4_096);
87
+ const candidates = selected
88
+ ? selected.split(context.input.platform === "win32" ? ";" : ":").filter(Boolean)
89
+ : [joinHome(context.input, ".kube", "config")];
90
+ const limit = optionNumber(context, "kubernetes", "max_config_files") ?? 8;
91
+ const contexts = new Map<string, Record<string, unknown>>();
92
+ const clusters = new Set<string>();
93
+ const users = new Set<string>();
94
+ let currentContext: string | undefined;
95
+ for (const path of candidates.slice(0, limit)) {
96
+ const source = await context.fs.readFile(path, MAX_METADATA_FILE_BYTES);
97
+ if (!source) continue;
98
+ try {
99
+ const document = parseYaml(source) as unknown;
100
+ if (!isRecord(document)) continue;
101
+ currentContext ??= safeMetadata(document["current-context"]);
102
+ for (const item of arrayRecords(document.contexts)) {
103
+ const name = safeMetadata(item.name);
104
+ if (name && !contexts.has(name) && isRecord(item.context)) contexts.set(name, item.context);
105
+ }
106
+ for (const item of arrayRecords(document.clusters)) {
107
+ const name = safeMetadata(item.name);
108
+ if (name) clusters.add(name);
109
+ }
110
+ for (const item of arrayRecords(document.users)) {
111
+ const name = safeMetadata(item.name);
112
+ if (name) users.add(name);
113
+ }
114
+ } catch {
115
+ // Ignore malformed files independently.
116
+ }
117
+ }
118
+ if (!currentContext) return undefined;
119
+ const selectedContext = contexts.get(currentContext);
120
+ const cluster = safeMetadata(selectedContext?.cluster);
121
+ const user = safeMetadata(selectedContext?.user);
122
+ const namespace = safeMetadata(selectedContext?.namespace) ?? "default";
123
+ const values: Record<string, string> = {
124
+ context:
125
+ exactAlias(currentContext, optionMap(context, "kubernetes", "context_aliases")) ??
126
+ currentContext,
127
+ namespace:
128
+ exactAlias(namespace, optionMap(context, "kubernetes", "namespace_aliases")) ?? namespace,
129
+ };
130
+ if (cluster && clusters.has(cluster)) {
131
+ values.cluster =
132
+ exactAlias(cluster, optionMap(context, "kubernetes", "cluster_aliases")) ?? cluster;
133
+ }
134
+ if (user && users.has(user)) {
135
+ values.user = exactAlias(user, optionMap(context, "kubernetes", "user_aliases")) ?? user;
136
+ }
137
+ return values;
138
+ }
139
+
140
+ async function collectTerraform(
141
+ context: CollectorContext,
142
+ ): Promise<Record<string, string> | undefined> {
143
+ const entries = await context.entries();
144
+ const configuredFiles = optionStrings(context, "terraform", "detect_files");
145
+ const configuredExtensions = optionStrings(context, "terraform", "detect_extensions");
146
+ const configuredFolders = optionStrings(context, "terraform", "detect_folders");
147
+ const detected =
148
+ configuredFiles.length + configuredExtensions.length + configuredFolders.length > 0
149
+ ? directMatch(entries, configuredFiles, configuredExtensions, configuredFolders)
150
+ : entries.some(
151
+ (entry) =>
152
+ (entry.isFile && [".tf", ".tfplan", ".tfstate"].includes(extname(entry.name))) ||
153
+ (entry.isDirectory && entry.name === ".terraform"),
154
+ );
155
+ if (!detected) return undefined;
156
+ const values: Record<string, string> = {};
157
+ const workspace = await terraformWorkspace(context);
158
+ if (workspace) values.workspace = workspace;
159
+ if (context.needs("terraform", "version")) {
160
+ for (const command of ["terraform", "tofu"]) {
161
+ const output = await runBounded(context, command, ["version"]);
162
+ const parsed = output ? parseTerraformVersion(output, command) : undefined;
163
+ if (parsed) {
164
+ values.version = formatVersion(
165
+ parsed,
166
+ optionString(context, "terraform", "version_format"),
167
+ );
168
+ break;
169
+ }
170
+ }
171
+ }
172
+ return values;
173
+ }
174
+
175
+ async function terraformWorkspace(context: CollectorContext): Promise<string | undefined> {
176
+ const direct = safeMetadata(context.input.environment.TF_WORKSPACE);
177
+ if (direct) return direct;
178
+ const dataDirectory = safeMetadata(context.input.environment.TF_DATA_DIR, 1_024);
179
+ const candidate = dataDirectory
180
+ ? join(
181
+ isAbsolute(dataDirectory) ? dataDirectory : resolve(context.input.cwd, dataDirectory),
182
+ "environment",
183
+ )
184
+ : join(context.input.cwd, ".terraform", "environment");
185
+ return safeMetadata(await context.fs.readFile(candidate, 1_024));
186
+ }
187
+
188
+ export function parseTerraformVersion(
189
+ output: string,
190
+ command: "terraform" | "tofu" | string,
191
+ ): string | undefined {
192
+ const escaped = command === "tofu" ? "OpenTofu" : "Terraform";
193
+ const match = new RegExp(`^${escaped} v?(\\d+\\.\\d+\\.\\d+(?:[-+][0-9A-Za-z.-]+)?)$`, "u").exec(
194
+ output.trim().split(/\r?\n/u)[0] ?? "",
195
+ );
196
+ return match?.[1] ? `v${match[1]}` : undefined;
197
+ }
198
+
199
+ function arrayRecords(value: unknown): Record<string, unknown>[] {
200
+ return Array.isArray(value) ? value.filter(isRecord) : [];
201
+ }