Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

projectScripts.ts

88 lines2.6 KB

1import {
2 MAX_SCRIPT_ID_LENGTH,
3 SCRIPT_RUN_COMMAND_PATTERN,
4 type KeybindingCommand,
5 type ProjectScript,
6} from "@t3tools/contracts";
7import { Schema } from "effect";
8​
9function normalizeScriptId(value: string): string {
10 const cleaned = value
11 .trim()
12 .toLowerCase()
13 .replace(/[^a-z0-9]+/g, "-")
14 .replace(/^-+|-+$/g, "");
15 if (cleaned.length === 0) {
16 return "script";
17 }
18 if (cleaned.length <= MAX_SCRIPT_ID_LENGTH) {
19 return cleaned;
20 }
21 return cleaned.slice(0, MAX_SCRIPT_ID_LENGTH).replace(/-+$/g, "") || "script";
23​
24export const commandForProjectScript = (scriptId: string): KeybindingCommand =>
25 SCRIPT_RUN_COMMAND_PATTERN.makeUnsafe(`script.${scriptId}.run`);
26​
27export function projectScriptIdFromCommand(command: string): string | null {
28 const trimmed = command.trim();
29 if (!Schema.is(SCRIPT_RUN_COMMAND_PATTERN)(trimmed)) {
30 return null;
31 }
32 const [prefix, , suffix] = SCRIPT_RUN_COMMAND_PATTERN.parts;
33 return trimmed.slice(prefix.literal.length, -suffix.literal.length);
35​
36export function nextProjectScriptId(name: string, existingIds: Iterable<string>): string {
37 const taken = new Set(Array.from(existingIds));
38 const baseId = normalizeScriptId(name);
39 if (!taken.has(baseId)) return baseId;
40​
41 let suffix = 2;
42 while (suffix < 10_000) {
43 const candidate = `${baseId}-${suffix}`;
44 const safeCandidate =
45 candidate.length <= MAX_SCRIPT_ID_LENGTH
46 ? candidate
47 : `${baseId.slice(0, Math.max(1, MAX_SCRIPT_ID_LENGTH - String(suffix).length - 1))}-${suffix}`;
48 if (!taken.has(safeCandidate)) {
49 return safeCandidate;
50 }
51 suffix += 1;
52 }
53​
54 // This last-resort fallback only triggers after exhausting thousands of suffixes.
55 return `${baseId}-${Date.now()}`.slice(0, MAX_SCRIPT_ID_LENGTH);
57​
58interface ProjectScriptRuntimeEnvInput {
59 project: {
60 cwd: string;
61 };
62 worktreePath?: string | null;
63 extraEnv?: Record<string, string>;
65​
66export function projectScriptRuntimeEnv(
67 input: ProjectScriptRuntimeEnvInput,
68): Record<string, string> {
69 const env: Record<string, string> = {
70 T3CODE_PROJECT_ROOT: input.project.cwd,
71 };
72 if (input.worktreePath) {
73 env.T3CODE_WORKTREE_PATH = input.worktreePath;
74 }
75 if (input.extraEnv) {
76 return { ...env, ...input.extraEnv };
77 }
78 return env;
80​
81export function primaryProjectScript(scripts: ProjectScript[]): ProjectScript | null {
82 const regular = scripts.find((script) => !script.runOnWorktreeCreate);
83 return regular ?? scripts[0] ?? null;
85​
86export function setupProjectScript(scripts: ProjectScript[]): ProjectScript | null {
87 return scripts.find((script) => script.runOnWorktreeCreate) ?? null;