@prisma/cli 3.0.0-beta.3 → 3.0.0-beta.30

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 (99) hide show
  1. package/README.md +6 -15
  2. package/dist/adapters/local-state.js +15 -4
  3. package/dist/adapters/mock-api.js +244 -0
  4. package/dist/adapters/token-storage.js +335 -34
  5. package/dist/cli.js +7 -7
  6. package/dist/cli2.js +24 -5
  7. package/dist/commands/agent/index.js +60 -0
  8. package/dist/commands/app/index.js +91 -61
  9. package/dist/commands/auth/index.js +55 -2
  10. package/dist/commands/branch/index.js +2 -27
  11. package/dist/commands/bucket/index.js +123 -0
  12. package/dist/commands/build/index.js +29 -0
  13. package/dist/commands/database/index.js +249 -0
  14. package/dist/commands/env.js +8 -4
  15. package/dist/commands/feedback/index.js +20 -0
  16. package/dist/commands/git/index.js +1 -1
  17. package/dist/commands/init/index.js +33 -0
  18. package/dist/commands/project/index.js +54 -5
  19. package/dist/controllers/agent-setup.js +52 -0
  20. package/dist/controllers/agent.js +228 -0
  21. package/dist/controllers/app-env-api.js +55 -0
  22. package/dist/controllers/app-env-file.js +181 -0
  23. package/dist/controllers/app-env.js +227 -104
  24. package/dist/controllers/app.js +746 -306
  25. package/dist/controllers/auth.js +247 -3
  26. package/dist/controllers/branch.js +78 -48
  27. package/dist/controllers/bucket.js +278 -0
  28. package/dist/controllers/build.js +88 -0
  29. package/dist/controllers/database.js +567 -0
  30. package/dist/controllers/feedback.js +86 -0
  31. package/dist/controllers/init.js +753 -0
  32. package/dist/controllers/project.js +377 -22
  33. package/dist/controllers/select-prompt-port.js +1 -0
  34. package/dist/lib/agent/cli-command.js +20 -0
  35. package/dist/lib/agent/constants.js +12 -0
  36. package/dist/lib/agent/package-manager.js +99 -0
  37. package/dist/lib/agent/setup-status.js +83 -0
  38. package/dist/lib/app/{preview-provider.js → app-provider.js} +137 -88
  39. package/dist/lib/app/branch-database-api.js +102 -0
  40. package/dist/lib/app/branch-database-deploy.js +326 -0
  41. package/dist/lib/app/branch-database.js +216 -0
  42. package/dist/lib/app/build-settings.js +93 -0
  43. package/dist/lib/app/build.js +83 -0
  44. package/dist/lib/app/bun-project.js +3 -4
  45. package/dist/lib/app/compute-config.js +145 -0
  46. package/dist/lib/app/deploy-plan.js +59 -0
  47. package/dist/lib/app/{preview-progress.js → deploy-progress.js} +12 -12
  48. package/dist/lib/app/env-config.js +1 -1
  49. package/dist/lib/app/env-file.js +82 -0
  50. package/dist/lib/app/env-vars.js +28 -2
  51. package/dist/lib/app/local-dev.js +3 -60
  52. package/dist/lib/app/production-deploy-gate.js +162 -0
  53. package/dist/lib/app/read-branch.js +30 -0
  54. package/dist/lib/auth/auth-ops.js +10 -4
  55. package/dist/lib/auth/guard.js +4 -1
  56. package/dist/lib/auth/login.js +33 -26
  57. package/dist/lib/auth/recipient.js +42 -0
  58. package/dist/lib/bucket/provider.js +139 -0
  59. package/dist/lib/database/provider.js +378 -0
  60. package/dist/lib/diagnostics.js +15 -0
  61. package/dist/lib/fs/home-path.js +24 -0
  62. package/dist/lib/git/local-branch.js +53 -0
  63. package/dist/lib/git/local-status.js +57 -0
  64. package/dist/lib/project/interactive-setup.js +5 -4
  65. package/dist/lib/project/local-pin.js +171 -41
  66. package/dist/lib/project/provider.js +92 -0
  67. package/dist/lib/project/resolution.js +199 -48
  68. package/dist/lib/project/setup.js +67 -20
  69. package/dist/output/patterns.js +1 -1
  70. package/dist/presenters/agent.js +74 -0
  71. package/dist/presenters/app-env.js +149 -14
  72. package/dist/presenters/app.js +208 -27
  73. package/dist/presenters/auth.js +99 -2
  74. package/dist/presenters/branch.js +37 -102
  75. package/dist/presenters/bucket.js +174 -0
  76. package/dist/presenters/database.js +448 -0
  77. package/dist/presenters/feedback.js +26 -0
  78. package/dist/presenters/init.js +30 -0
  79. package/dist/presenters/project.js +139 -27
  80. package/dist/presenters/verbose-context.js +64 -0
  81. package/dist/shell/cli-command.js +12 -0
  82. package/dist/shell/command-arguments.js +7 -1
  83. package/dist/shell/command-meta.js +458 -17
  84. package/dist/shell/command-runner.js +58 -18
  85. package/dist/shell/diagnostics-output.js +57 -0
  86. package/dist/shell/errors.js +56 -1
  87. package/dist/shell/help.js +31 -20
  88. package/dist/shell/output.js +72 -1
  89. package/dist/shell/prompt.js +12 -5
  90. package/dist/shell/runtime.js +8 -4
  91. package/dist/shell/ui.js +42 -3
  92. package/dist/shell/update-check.js +2 -2
  93. package/dist/use-cases/auth.js +68 -1
  94. package/dist/use-cases/branch.js +20 -68
  95. package/dist/use-cases/create-cli-gateways.js +2 -17
  96. package/dist/use-cases/project.js +2 -1
  97. package/package.json +21 -4
  98. package/dist/lib/app/preview-build.js +0 -312
  99. package/dist/lib/app/preview-interaction.js +0 -5
@@ -0,0 +1,378 @@
1
+ import { formatPrismaCliCommand } from "../../shell/cli-command.js";
2
+ import { CliError } from "../../shell/errors.js";
3
+ //#region src/lib/database/provider.ts
4
+ const SUBSCRIPTION_LOOKUP_TIMEOUT_MS = 3e3;
5
+ function createManagementDatabaseProvider(client, options) {
6
+ const formatCommand = options?.formatCommand ?? ((args) => formatPrismaCliCommand(args));
7
+ const toDatabaseApiError = (summary, response, error, signal) => databaseApiError({
8
+ client,
9
+ workspaceId: options?.workspaceId,
10
+ summary,
11
+ response,
12
+ error,
13
+ signal
14
+ });
15
+ return {
16
+ async listDatabases(options) {
17
+ const databases = [];
18
+ let cursor;
19
+ while (true) {
20
+ const result = await client.GET("/v1/databases", {
21
+ params: { query: {
22
+ projectId: options.projectId,
23
+ branchGitName: options.branchName,
24
+ cursor
25
+ } },
26
+ signal: options.signal
27
+ });
28
+ if (result.error || !result.data) throw await toDatabaseApiError("Failed to list databases", result.response, result.error, options.signal);
29
+ databases.push(...result.data.data);
30
+ if (!result.data.pagination.hasMore || !result.data.pagination.nextCursor) break;
31
+ cursor = result.data.pagination.nextCursor;
32
+ }
33
+ return databases.map((database) => normalizeDatabase(database, options.projectId));
34
+ },
35
+ async showDatabase(databaseId, options) {
36
+ const result = await client.GET("/v1/databases/{databaseId}", {
37
+ params: { path: { databaseId } },
38
+ signal: options?.signal
39
+ });
40
+ if (result.response?.status === 404 && !isPlanLimitApiError(result.error)) return null;
41
+ if (result.error || !result.data) throw await toDatabaseApiError("Failed to show database", result.response, result.error, options?.signal);
42
+ const database = result.data.data;
43
+ return normalizeDatabase(database, requireDatabaseProjectId(database, options?.projectId));
44
+ },
45
+ async createDatabase(options) {
46
+ const result = await client.POST("/v1/databases", {
47
+ body: {
48
+ projectId: options.projectId,
49
+ name: options.name,
50
+ source: { type: "empty" },
51
+ ...options.branchName ? { branchGitName: options.branchName } : {},
52
+ ...options.region ? { region: options.region } : {}
53
+ },
54
+ signal: options.signal
55
+ });
56
+ if (result.error || !result.data) throw await toDatabaseApiError("Failed to create database", result.response, result.error, options.signal);
57
+ return normalizeCreatedDatabase(result.data.data, options.projectId);
58
+ },
59
+ async removeDatabase(databaseId, options) {
60
+ const result = await client.DELETE("/v1/databases/{databaseId}", {
61
+ params: { path: { databaseId } },
62
+ signal: options?.signal
63
+ });
64
+ if (result.error) throw await toDatabaseApiError("Failed to remove database", result.response, result.error, options?.signal);
65
+ },
66
+ async listConnections(databaseId, options) {
67
+ const result = await client.GET("/v1/databases/{databaseId}/connections", {
68
+ params: { path: { databaseId } },
69
+ signal: options?.signal
70
+ });
71
+ if (result.error || !result.data) throw await toDatabaseApiError("Failed to list database connections", result.response, result.error, options?.signal);
72
+ return result.data.data.map((connection) => normalizeConnection(connection, databaseId));
73
+ },
74
+ async createConnection(options) {
75
+ const result = await client.POST("/v1/databases/{databaseId}/connections", {
76
+ params: { path: { databaseId: options.databaseId } },
77
+ body: { name: options.name },
78
+ signal: options.signal
79
+ });
80
+ if (result.error || !result.data) throw await toDatabaseApiError("Failed to create database connection", result.response, result.error, options.signal);
81
+ return normalizeCreatedConnection(result.data.data, options.databaseId);
82
+ },
83
+ async removeConnection(connectionId, options) {
84
+ const result = await client.DELETE("/v1/connections/{id}", {
85
+ params: { path: { id: connectionId } },
86
+ signal: options?.signal
87
+ });
88
+ if (result.error) throw await toDatabaseApiError("Failed to remove database connection", result.response, result.error, options?.signal);
89
+ },
90
+ async getUsage(databaseId, options) {
91
+ const result = await client.GET("/v1/databases/{databaseId}/usage", {
92
+ params: {
93
+ path: { databaseId },
94
+ query: {
95
+ ...options?.from ? { startDate: options.from } : {},
96
+ ...options?.to ? { endDate: options.to } : {}
97
+ }
98
+ },
99
+ signal: options?.signal
100
+ });
101
+ if (result.error || !result.data) throw await toDatabaseApiError("Failed to fetch database usage", result.response, result.error, options?.signal);
102
+ return normalizeUsage(result.data);
103
+ },
104
+ async listBackups(databaseId, options) {
105
+ const result = await client.GET("/v1/databases/{databaseId}/backups", {
106
+ params: {
107
+ path: { databaseId },
108
+ query: { ...options?.limit !== void 0 ? { limit: options.limit } : {} }
109
+ },
110
+ signal: options?.signal
111
+ });
112
+ if (result.response?.status === 422 && !isPlanLimitApiError(result.error)) throw backupsUnsupportedError(databaseId, result.error);
113
+ if (result.error || !result.data) throw await toDatabaseApiError("Failed to list database backups", result.response, result.error, options?.signal);
114
+ return normalizeBackupList(result.data);
115
+ },
116
+ async restoreDatabase(options) {
117
+ const result = await client.POST("/v1/databases/{targetDatabaseId}/restore", {
118
+ params: { path: { targetDatabaseId: options.targetDatabaseId } },
119
+ body: { source: {
120
+ type: "backup",
121
+ databaseId: options.sourceDatabaseId,
122
+ backupId: options.backupId
123
+ } },
124
+ signal: options.signal
125
+ });
126
+ if (result.response?.status === 409 && !isPlanLimitApiError(result.error)) throw restoreConflictError(options.targetDatabaseId, result.error, formatCommand);
127
+ if (result.response?.status === 404 && !isPlanLimitApiError(result.error)) throw restoreBackupNotFoundError(options, result.error, formatCommand);
128
+ if (result.error || !result.data) throw await toDatabaseApiError("Failed to restore database", result.response, result.error, options.signal);
129
+ return normalizeDatabase(result.data.data, options.projectId);
130
+ },
131
+ async rotateConnection(connectionId, options) {
132
+ const result = await client.POST("/v1/connections/{id}/rotate", {
133
+ params: { path: { id: connectionId } },
134
+ signal: options?.signal
135
+ });
136
+ if (result.error || !result.data) throw await toDatabaseApiError("Failed to rotate database connection", result.response, result.error, options?.signal);
137
+ return normalizeRotatedConnection(result.data.data);
138
+ }
139
+ };
140
+ }
141
+ function normalizeDatabase(database, fallbackProjectId) {
142
+ return {
143
+ id: database.id,
144
+ name: database.name,
145
+ projectId: database.projectId ?? fallbackProjectId,
146
+ branchId: database.branchId ?? database.branch?.id ?? null,
147
+ branchName: database.branchGitName ?? database.branchName ?? database.branch?.gitName ?? database.branch?.name ?? null,
148
+ region: normalizeRegion(database),
149
+ status: database.status ?? null,
150
+ isDefault: database.isDefault ?? null,
151
+ createdAt: database.createdAt ?? null
152
+ };
153
+ }
154
+ function normalizeConnection(connection, fallbackDatabaseId) {
155
+ return {
156
+ id: connection.id,
157
+ name: connection.name ?? connection.id,
158
+ databaseId: connection.databaseId ?? fallbackDatabaseId,
159
+ createdAt: connection.createdAt ?? null
160
+ };
161
+ }
162
+ function normalizeCreatedDatabase(database, fallbackProjectId) {
163
+ const rawConnection = database.connections?.[0];
164
+ if (!rawConnection) throw new CliError({
165
+ code: "DATABASE_CONNECTION_MISSING",
166
+ domain: "database",
167
+ summary: "Created database did not return a connection string",
168
+ why: "The Management API created the database but did not include the one-time connection payload.",
169
+ fix: "Create a connection explicitly with prisma-cli database connection create <database>.",
170
+ exitCode: 1,
171
+ nextSteps: [`prisma-cli database connection create ${database.id}`]
172
+ });
173
+ return {
174
+ database: normalizeDatabase(database, fallbackProjectId),
175
+ ...normalizeCreatedConnection(rawConnection, database.id)
176
+ };
177
+ }
178
+ function normalizeCreatedConnection(connection, fallbackDatabaseId) {
179
+ const connectionString = extractConnectionString(connection);
180
+ if (!connectionString) throw new CliError({
181
+ code: "DATABASE_CONNECTION_STRING_MISSING",
182
+ domain: "database",
183
+ summary: "Created connection did not return a connection string",
184
+ why: "Database connection strings are one-time-view secrets, but the Management API did not include one in this create response.",
185
+ fix: "Create another database connection and store the returned URL immediately.",
186
+ exitCode: 1,
187
+ nextSteps: [`prisma-cli database connection create ${fallbackDatabaseId}`]
188
+ });
189
+ return {
190
+ connection: normalizeConnection(connection, fallbackDatabaseId),
191
+ connectionString
192
+ };
193
+ }
194
+ function normalizeRegion(database) {
195
+ if (typeof database.region === "string") return database.region;
196
+ return database.region?.id ?? database.regionId ?? null;
197
+ }
198
+ function requireDatabaseProjectId(database, fallbackProjectId) {
199
+ const projectId = database.projectId ?? fallbackProjectId;
200
+ if (projectId) return projectId;
201
+ throw new CliError({
202
+ code: "DATABASE_API_ERROR",
203
+ domain: "database",
204
+ summary: "Database response did not include a project id",
205
+ why: "The Management API returned database metadata without project context.",
206
+ fix: "Re-run with --trace for the underlying API response details.",
207
+ exitCode: 1,
208
+ nextSteps: []
209
+ });
210
+ }
211
+ function extractConnectionString(connection) {
212
+ return connection.endpoints?.pooled?.connectionString ?? connection.connectionString ?? connection.endpoints?.direct?.connectionString ?? connection.endpoints?.accelerate?.connectionString ?? null;
213
+ }
214
+ function normalizeUsage(usage) {
215
+ return {
216
+ period: {
217
+ start: usage.period?.start ?? "",
218
+ end: usage.period?.end ?? ""
219
+ },
220
+ metrics: {
221
+ operations: {
222
+ used: usage.metrics?.operations?.used ?? 0,
223
+ unit: usage.metrics?.operations?.unit ?? "ops"
224
+ },
225
+ storage: {
226
+ used: usage.metrics?.storage?.used ?? 0,
227
+ unit: usage.metrics?.storage?.unit ?? "GiB"
228
+ }
229
+ },
230
+ generatedAt: usage.generatedAt ?? ""
231
+ };
232
+ }
233
+ function normalizeBackupList(body) {
234
+ return {
235
+ backups: (body.data ?? []).map((backup) => ({
236
+ id: backup.id,
237
+ backupType: backup.backupType ?? "unknown",
238
+ status: backup.status ?? "unknown",
239
+ size: backup.size ?? null,
240
+ createdAt: backup.createdAt ?? ""
241
+ })),
242
+ retentionDays: body.meta?.backupRetentionDays ?? null,
243
+ hasMore: body.pagination?.hasMore ?? false
244
+ };
245
+ }
246
+ function normalizeRotatedConnection(connection) {
247
+ const connectionString = extractConnectionString(connection);
248
+ if (!connectionString) throw new CliError({
249
+ code: "DATABASE_CONNECTION_STRING_MISSING",
250
+ domain: "database",
251
+ summary: "Rotated connection did not return a connection string",
252
+ why: "Rotated connection strings are one-time-view secrets, but the Management API did not include one in this rotate response.",
253
+ fix: "Re-run the rotation, or create a replacement connection and store the returned URL immediately.",
254
+ exitCode: 1,
255
+ nextSteps: []
256
+ });
257
+ const database = connection.database?.id && connection.database?.name ? {
258
+ id: connection.database.id,
259
+ name: connection.database.name
260
+ } : null;
261
+ return {
262
+ connection: normalizeConnection(connection, connection.database?.id ?? connection.databaseId ?? ""),
263
+ database,
264
+ connectionString
265
+ };
266
+ }
267
+ function backupsUnsupportedError(databaseId, error) {
268
+ return new CliError({
269
+ code: "DATABASE_BACKUPS_UNSUPPORTED",
270
+ domain: "database",
271
+ summary: "Backups are not available for this database",
272
+ why: error?.error?.message ?? `The platform does not manage backups for database "${databaseId}", for example because it is a remote/BYO database.`,
273
+ fix: "Use your own backup tooling for externally managed databases.",
274
+ exitCode: 1,
275
+ nextSteps: []
276
+ });
277
+ }
278
+ function restoreBackupNotFoundError(options, error, formatCommand) {
279
+ const listCommand = formatCommand([
280
+ "database",
281
+ "backup",
282
+ "list",
283
+ options.sourceDatabaseId
284
+ ]);
285
+ return new CliError({
286
+ code: "DATABASE_BACKUP_NOT_FOUND",
287
+ domain: "database",
288
+ summary: "Database backup not found",
289
+ why: error?.error?.message ?? `No backup matched "${options.backupId}" for database "${options.sourceDatabaseId}".`,
290
+ fix: `Pass a backup id from ${listCommand}.`,
291
+ exitCode: 1,
292
+ nextSteps: [listCommand]
293
+ });
294
+ }
295
+ function restoreConflictError(targetDatabaseId, error, formatCommand) {
296
+ return new CliError({
297
+ code: "DATABASE_RESTORE_CONFLICT",
298
+ domain: "database",
299
+ summary: "Database cannot be restored right now",
300
+ why: error?.error?.message ?? `Database "${targetDatabaseId}" is provisioning or already recovering.`,
301
+ fix: "Wait for the database to become ready, then retry the restore.",
302
+ exitCode: 1,
303
+ nextSteps: [formatCommand([
304
+ "database",
305
+ "show",
306
+ targetDatabaseId
307
+ ])]
308
+ });
309
+ }
310
+ async function databaseApiError(options) {
311
+ if (isPlanLimitApiError(options.error)) {
312
+ const subscription = options.workspaceId ? await readWorkspaceSubscription(options.client, options.workspaceId, options.signal) : null;
313
+ const workspaceLine = options.workspaceId ? `Workspace: ${options.workspaceId}` : "Workspace: unavailable";
314
+ const planName = subscription?.planName || null;
315
+ const usageBlocked = subscription?.usageBlocked ?? null;
316
+ const upgradeUrl = subscription?.upgradeUrl || null;
317
+ const recoveryLines = [...planName ? [`Current plan: ${planName}`] : [], upgradeUrl ? `Upgrade: ${upgradeUrl}` : "Upgrade: Open Prisma Console and upgrade the affected workspace plan."];
318
+ return new CliError({
319
+ code: "PLAN_LIMIT_REACHED",
320
+ domain: "database",
321
+ summary: "Workspace plan limit reached",
322
+ why: "Database operations are blocked because this workspace has used the operations included in its plan. This is a workspace plan limit, not a Prisma outage.",
323
+ fix: upgradeUrl ? `Upgrade the workspace plan at ${upgradeUrl}.` : "Open Prisma Console and upgrade the affected workspace plan.",
324
+ meta: {
325
+ workspaceId: options.workspaceId ?? null,
326
+ blockedFeature: null,
327
+ planName,
328
+ usageBlocked,
329
+ upgradeUrl
330
+ },
331
+ exitCode: 1,
332
+ nextSteps: [],
333
+ humanLines: [
334
+ "Workspace plan limit reached [PLAN_LIMIT_REACHED]",
335
+ "",
336
+ "Database operations are blocked because this workspace has used the operations included in its plan. This is a workspace plan limit, not a Prisma outage.",
337
+ "",
338
+ workspaceLine,
339
+ ...recoveryLines
340
+ ]
341
+ });
342
+ }
343
+ const status = options.response?.status ?? 0;
344
+ return new CliError({
345
+ code: options.error?.error?.code ?? "DATABASE_API_ERROR",
346
+ domain: "database",
347
+ summary: options.summary,
348
+ why: options.error?.error?.message ?? `The Management API returned status ${status || "unknown"}.`,
349
+ fix: options.error?.error?.hint ?? "Re-run with --trace for the underlying API response details.",
350
+ exitCode: 1,
351
+ nextSteps: []
352
+ });
353
+ }
354
+ function isPlanLimitApiError(error) {
355
+ return error?.error?.code === "planLimitReached";
356
+ }
357
+ async function readWorkspaceSubscription(client, workspaceId, signal) {
358
+ signal?.throwIfAborted();
359
+ const timeoutController = new AbortController();
360
+ const timeout = setTimeout(() => timeoutController.abort(), SUBSCRIPTION_LOOKUP_TIMEOUT_MS);
361
+ const requestSignal = signal ? AbortSignal.any([signal, timeoutController.signal]) : timeoutController.signal;
362
+ try {
363
+ const result = await client.GET("/v1/workspaces/{id}/subscription", {
364
+ params: { path: { id: workspaceId } },
365
+ signal: requestSignal
366
+ });
367
+ signal?.throwIfAborted();
368
+ if (result.error) return null;
369
+ return result.data?.data ?? null;
370
+ } catch {
371
+ signal?.throwIfAborted();
372
+ return null;
373
+ } finally {
374
+ clearTimeout(timeout);
375
+ }
376
+ }
377
+ //#endregion
378
+ export { createManagementDatabaseProvider, normalizeConnection, normalizeDatabase };
@@ -0,0 +1,15 @@
1
+ import { resolveLocalStateFilePath } from "../adapters/local-state.js";
2
+ import { resolveStateDir } from "../shell/runtime.js";
3
+ import { readLocalGitState } from "./git/local-status.js";
4
+ //#region src/lib/diagnostics.ts
5
+ async function collectCommandDiagnostics(context, options = {}) {
6
+ const stateDir = await resolveStateDir(context.runtime);
7
+ return {
8
+ cwd: context.runtime.cwd,
9
+ stateFilePath: resolveLocalStateFilePath(stateDir),
10
+ git: await readLocalGitState(context.runtime.cwd, context.runtime.signal),
11
+ durationMs: options.durationMs
12
+ };
13
+ }
14
+ //#endregion
15
+ export { collectCommandDiagnostics };
@@ -0,0 +1,24 @@
1
+ import path from "node:path";
2
+ //#region src/lib/fs/home-path.ts
3
+ /**
4
+ * Shortens a path under the user's home directory to `~/...` for display,
5
+ * posix-style on every platform. Falls back to the Windows home variables
6
+ * when `HOME` is unset (native cmd/PowerShell sessions).
7
+ */
8
+ function shortenHomePath(value, env) {
9
+ const resolved = path.resolve(value);
10
+ const home = resolveHomeDirectory(env);
11
+ if (home && (resolved === home || resolved.startsWith(`${home}${path.sep}`))) {
12
+ const relative = path.relative(home, resolved).split(path.sep).join("/");
13
+ return relative ? `~/${relative}` : "~";
14
+ }
15
+ return resolved;
16
+ }
17
+ function resolveHomeDirectory(env) {
18
+ if (env.HOME) return path.resolve(env.HOME);
19
+ if (env.USERPROFILE) return path.resolve(env.USERPROFILE);
20
+ if (env.HOMEDRIVE && env.HOMEPATH) return path.resolve(`${env.HOMEDRIVE}${env.HOMEPATH}`);
21
+ return null;
22
+ }
23
+ //#endregion
24
+ export { shortenHomePath };
@@ -0,0 +1,53 @@
1
+ import path from "node:path";
2
+ import { access, readFile } from "node:fs/promises";
3
+ //#region src/lib/git/local-branch.ts
4
+ /**
5
+ * Resolves the checked-out branch the way git does: the nearest `.git`
6
+ * (directory or worktree file) from `cwd` upward owns the answer, so
7
+ * monorepo commands run from inside a package see the repository branch.
8
+ * Returns null for detached HEAD or when no repository contains `cwd`.
9
+ */
10
+ async function readLocalGitBranch(cwd, signal) {
11
+ for (let directory = path.resolve(cwd);;) {
12
+ const headPath = await resolveGitHeadPath(path.join(directory, ".git"), signal);
13
+ if (headPath) return readBranchFromHead(headPath, signal);
14
+ const parent = path.dirname(directory);
15
+ if (parent === directory) return null;
16
+ directory = parent;
17
+ }
18
+ }
19
+ async function readBranchFromHead(headPath, signal) {
20
+ try {
21
+ const head = (await readFile(headPath, {
22
+ encoding: "utf8",
23
+ signal
24
+ })).trim();
25
+ if (head.startsWith("ref: refs/heads/")) return head.slice(16);
26
+ } catch (error) {
27
+ if (signal.aborted) throw error;
28
+ }
29
+ return null;
30
+ }
31
+ async function resolveGitHeadPath(gitPath, signal) {
32
+ signal.throwIfAborted();
33
+ try {
34
+ const raw = await readFile(gitPath, {
35
+ encoding: "utf8",
36
+ signal
37
+ });
38
+ if (raw.startsWith("gitdir:")) return path.join(path.resolve(path.dirname(gitPath), raw.slice(7).trim()), "HEAD");
39
+ } catch (error) {
40
+ if (signal.aborted) throw error;
41
+ }
42
+ signal.throwIfAborted();
43
+ try {
44
+ await access(path.join(gitPath, "HEAD"));
45
+ signal.throwIfAborted();
46
+ return path.join(gitPath, "HEAD");
47
+ } catch (error) {
48
+ if (signal.aborted) throw error;
49
+ return null;
50
+ }
51
+ }
52
+ //#endregion
53
+ export { readLocalGitBranch };
@@ -0,0 +1,57 @@
1
+ import { execFile } from "node:child_process";
2
+ //#region src/lib/git/local-status.ts
3
+ async function readLocalGitState(cwd, signal) {
4
+ signal.throwIfAborted();
5
+ if ((await runGit(cwd, ["rev-parse", "--is-inside-work-tree"], signal))?.trim() !== "true") return null;
6
+ const [ref, sha, status] = await Promise.all([
7
+ runGit(cwd, [
8
+ "symbolic-ref",
9
+ "--quiet",
10
+ "--short",
11
+ "HEAD"
12
+ ], signal),
13
+ runGit(cwd, [
14
+ "rev-parse",
15
+ "--short",
16
+ "HEAD"
17
+ ], signal),
18
+ runGit(cwd, ["status", "--porcelain"], signal)
19
+ ]);
20
+ return {
21
+ ref: cleanGitValue(ref),
22
+ sha: cleanGitValue(sha),
23
+ dirty: status === null ? null : status.trim().length > 0
24
+ };
25
+ }
26
+ function runGit(cwd, args, signal) {
27
+ return new Promise((resolve, reject) => {
28
+ signal.throwIfAborted();
29
+ execFile("git", args, {
30
+ cwd,
31
+ signal,
32
+ timeout: 2e3
33
+ }, (error, stdout) => {
34
+ if (signal.aborted) {
35
+ reject(error);
36
+ return;
37
+ }
38
+ if (error) {
39
+ resolve(null);
40
+ return;
41
+ }
42
+ resolve(stdout);
43
+ }).on("error", (error) => {
44
+ if (signal.aborted) {
45
+ reject(error);
46
+ return;
47
+ }
48
+ resolve(null);
49
+ });
50
+ });
51
+ }
52
+ function cleanGitValue(value) {
53
+ const cleaned = value?.trim();
54
+ return cleaned ? cleaned : null;
55
+ }
56
+ //#endregion
57
+ export { readLocalGitState };
@@ -12,6 +12,10 @@ async function promptForProjectSetupChoice(options) {
12
12
  output: options.context.runtime.stderr,
13
13
  message: "Which Project should this directory use?",
14
14
  choices: [
15
+ {
16
+ label: "+ Create a new Project",
17
+ value: { kind: "create" }
18
+ },
15
19
  ...sortedProjects.map((project) => ({
16
20
  label: duplicateNames.has(project.name) ? `${project.name} (${project.id})` : project.name,
17
21
  value: {
@@ -19,10 +23,6 @@ async function promptForProjectSetupChoice(options) {
19
23
  project
20
24
  }
21
25
  })),
22
- {
23
- label: "Create a new Project",
24
- value: { kind: "create" }
25
- },
26
26
  {
27
27
  label: "Cancel",
28
28
  value: { kind: "cancel" }
@@ -40,6 +40,7 @@ async function promptForProjectSetupChoice(options) {
40
40
  const rawName = await textPrompt({
41
41
  input: options.context.runtime.stdin,
42
42
  output: options.context.runtime.stderr,
43
+ signal: options.context.runtime.signal,
43
44
  message: "Project name",
44
45
  placeholder: suggestedName.name,
45
46
  validate: (value) => validateProjectSetupNameText(value, suggestedName.name)