@firstdraft.com/cli 0.1.0-alpha.2

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.
package/src/cli.js ADDED
@@ -0,0 +1,2056 @@
1
+ import { parseArgs } from "node:util";
2
+
3
+ import {
4
+ deriveApplicationKey,
5
+ deriveApplicationName,
6
+ isValidApplicationKey,
7
+ isValidApplicationName,
8
+ } from "./application-identity.js";
9
+ import {
10
+ authenticatedFetch,
11
+ isAuthenticationProblem,
12
+ } from "./api-authentication.js";
13
+ import {
14
+ CompilationArtifactInvalidError,
15
+ CompilationArtifactResponseInvalidError,
16
+ CompilationArtifactUnavailableError,
17
+ CompilationChangedError,
18
+ CompilationMaterializationError,
19
+ CompilationNotSucceededError,
20
+ CompilationNotPushedError,
21
+ CompilationOutputPathError,
22
+ CompilationStatusInvalidError,
23
+ CompilationStatusUnavailableError,
24
+ CompilationTimeoutError,
25
+ downloadCompilation,
26
+ readCompilation,
27
+ } from "./commands/compilation.js";
28
+ import {
29
+ PlanCompileAnalysisInvalidError,
30
+ PlanCompileAnalysisNotValidError,
31
+ PlanCompileAnalysisRejectedError,
32
+ PlanCompileAnalysisUnavailableError,
33
+ PlanCompilePushRejectedError,
34
+ compilePlan,
35
+ } from "./commands/plan-compile.js";
36
+ import { initializePlan } from "./commands/plan-init.js";
37
+ import {
38
+ PublicationCancelledError,
39
+ PublicationChangedError,
40
+ PublicationFailedError,
41
+ PublicationLocalPlanChangedError,
42
+ PublicationLocalStateError,
43
+ PublicationNotPushedError,
44
+ PublicationRequestOutcomeUnknownError,
45
+ PublicationStartRejectedError,
46
+ PublicationStatusInvalidError,
47
+ PublicationStatusUnavailableError,
48
+ PublicationTimeoutError,
49
+ } from "./commands/plan-publish.js";
50
+ import {
51
+ PlanPushConfigurationError,
52
+ PlanPushLocalError,
53
+ PlanPushNetworkError,
54
+ PlanPushProtocolError,
55
+ PlanPushStateWriteError,
56
+ pushPlan,
57
+ } from "./commands/plan-push.js";
58
+ import {
59
+ PlanStatusChangedError,
60
+ PlanStatusNotPushedError,
61
+ PlanStatusTimeoutError,
62
+ readPlanStatus,
63
+ } from "./commands/plan-status.js";
64
+ import { isFileSystemError } from "./file-system.js";
65
+ import { isUuidV7 } from "./plan-state.js";
66
+ import { generateUuidV7 } from "./uuid-v7.js";
67
+ import { VERSION } from "./version.js";
68
+
69
+ const ROOT_HELP = `First Draft CLI
70
+
71
+ Usage:
72
+ firstdraft <command> [options]
73
+ firstdraft [options]
74
+
75
+ Commands:
76
+ compilation Inspect and download Compilations
77
+ generate Generate local values
78
+ plan Work with Foundation Plans
79
+
80
+ Options:
81
+ -h, --help Show help
82
+ -V, --version Show version
83
+ `;
84
+
85
+ const PLAN_HELP = `First Draft CLI
86
+
87
+ Usage:
88
+ firstdraft plan <command> [options]
89
+
90
+ Commands:
91
+ init Create a local empty Foundation Plan
92
+ push Send the local Foundation Plan to First Draft
93
+ status Read the current whole-graph analysis status
94
+ compile Compile and publish the current Foundation Plan
95
+
96
+ Options:
97
+ -h, --help Show help
98
+ `;
99
+
100
+ const GENERATE_HELP = `First Draft CLI
101
+
102
+ Usage:
103
+ firstdraft generate <command> [options]
104
+
105
+ Commands:
106
+ uuid Generate one or more UUIDv7 values
107
+ application-key Derive a lower-snake-case application key
108
+
109
+ Options:
110
+ -h, --help Show help
111
+ `;
112
+
113
+ const GENERATE_UUID_HELP = `First Draft CLI
114
+
115
+ Usage:
116
+ firstdraft generate uuid [--count <n>]
117
+
118
+ Options:
119
+ --count <n> Number to generate (positive integer)
120
+ -h, --help Show help
121
+
122
+ The command reads no files and makes no network request. Each UUID is printed
123
+ on its own line.
124
+ `;
125
+
126
+ const GENERATE_APPLICATION_KEY_HELP = `First Draft CLI
127
+
128
+ Usage:
129
+ firstdraft generate application-key --name <name>
130
+
131
+ Options:
132
+ --name <name> Application display name
133
+ -h, --help Show help
134
+
135
+ The command derives the same application key used by name-only plan init.
136
+ Generated keys are at most 63 ASCII bytes.
137
+ `;
138
+
139
+ const PLAN_PUSH_HELP = `First Draft CLI
140
+
141
+ Usage:
142
+ firstdraft plan push
143
+
144
+ Options:
145
+ -h, --help Show help
146
+
147
+ Environment:
148
+ FIRSTDRAFT_API_TOKEN Authenticate API requests
149
+ FIRSTDRAFT_API_URL Override the initial API origin
150
+
151
+ The first successful push saves its API origin in .firstdraft/state.json.
152
+ Later pushes reject a different origin.
153
+ `;
154
+
155
+ const PLAN_STATUS_HELP = `First Draft CLI
156
+
157
+ Usage:
158
+ firstdraft plan status [--wait]
159
+
160
+ Options:
161
+ --wait Poll until the current analysis reaches a terminal status
162
+ -h, --help Show help
163
+
164
+ Environment:
165
+ FIRSTDRAFT_API_TOKEN Authenticate API requests
166
+
167
+ The command uses only the API origin pinned by a successful plan push.
168
+ Without --wait, it makes exactly one status request.
169
+ `;
170
+
171
+ const PLAN_COMPILE_HELP = `First Draft CLI
172
+
173
+ Usage:
174
+ firstdraft plan compile
175
+
176
+ Options:
177
+ -h, --help Show help
178
+
179
+ Environment:
180
+ FIRSTDRAFT_API_TOKEN Authenticate API requests
181
+ FIRSTDRAFT_API_URL Override the initial API origin
182
+
183
+ The command submits the exact current whole-file Plan, waits for its analysis,
184
+ and proceeds only when that analysis is valid. It then conditionally creates
185
+ or replays the internal GitHub Publication lifecycle and prints its complete
186
+ validated Project, Compilation, and Publication projection.
187
+ `;
188
+
189
+ const COMPILATION_HELP = `First Draft CLI
190
+
191
+ Usage:
192
+ firstdraft compilation <command> [options]
193
+
194
+ Commands:
195
+ status Read one retained Compilation
196
+ download Download one successful Compilation artifact
197
+
198
+ Options:
199
+ -h, --help Show help
200
+ `;
201
+
202
+ const COMPILATION_STATUS_HELP = `First Draft CLI
203
+
204
+ Usage:
205
+ firstdraft compilation status <compilation-id> [--wait]
206
+
207
+ Options:
208
+ --wait Poll until the Compilation reaches a terminal status
209
+ -h, --help Show help
210
+
211
+ Environment:
212
+ FIRSTDRAFT_API_TOKEN Authenticate API requests
213
+
214
+ Without --wait, the command makes exactly one metadata-only GET. With --wait,
215
+ it polls the same retained Compilation for at most ten minutes. Failed and
216
+ cancelled terminal states are successful status reads.
217
+ `;
218
+
219
+ const COMPILATION_DOWNLOAD_HELP = `First Draft CLI
220
+
221
+ Usage:
222
+ firstdraft compilation download <compilation-id> --output <absent-path>
223
+
224
+ Options:
225
+ --output <absent-path> Materialize the generated application here
226
+ -h, --help Show help
227
+
228
+ Environment:
229
+ FIRSTDRAFT_API_TOKEN Authenticate API requests
230
+
231
+ The command reads the retained Compilation once, requires it to have
232
+ succeeded, downloads and verifies its exact artifact once, and atomically
233
+ renames the verified files into an absent output path. It never starts work.
234
+ `;
235
+
236
+ const PLAN_INIT_HELP = `First Draft CLI
237
+
238
+ Usage:
239
+ firstdraft plan init [--application-key <key>] [--name <name>]
240
+
241
+ Options:
242
+ --application-key <key> Lower-snake-case application key
243
+ --name <name> Application display name
244
+ -h, --help Show help
245
+
246
+ Provide at least one of --application-key or --name. The command derives a
247
+ missing key from the name or a missing display name from the key.
248
+ `;
249
+
250
+ const ROOT_USAGE_ERROR =
251
+ "Invalid arguments.\nRun 'firstdraft --help' for usage.\n";
252
+ const ROOT_UNKNOWN_COMMAND =
253
+ "Unknown command.\nRun 'firstdraft --help' for usage.\n";
254
+ const GENERATE_USAGE_ERROR =
255
+ "Invalid arguments.\nRun 'firstdraft generate --help' for usage.\n";
256
+ const GENERATE_UNKNOWN_COMMAND =
257
+ "Unknown command.\nRun 'firstdraft generate --help' for usage.\n";
258
+ const COMPILATION_USAGE_ERROR =
259
+ "Invalid arguments.\nRun 'firstdraft compilation --help' for usage.\n";
260
+ const COMPILATION_UNKNOWN_COMMAND =
261
+ "Unknown command.\nRun 'firstdraft compilation --help' for usage.\n";
262
+ const PLAN_USAGE_ERROR =
263
+ "Invalid arguments.\nRun 'firstdraft plan --help' for usage.\n";
264
+ const PLAN_UNKNOWN_COMMAND =
265
+ "Unknown command.\nRun 'firstdraft plan --help' for usage.\n";
266
+ const PLAN_INIT_INVALID_ARGUMENTS_DETAIL =
267
+ "Invalid arguments. Run 'firstdraft plan init --help' for usage.";
268
+ const PLAN_INIT_FAILED_DETAIL =
269
+ "Could not initialize .firstdraft. The directory may be incomplete; no existing files were overwritten.";
270
+ const PLAN_INIT_SUCCESS = "Initialized .firstdraft/foundation-plan.json.\n";
271
+ const PLAN_PUSH_INVALID_ARGUMENTS_DETAIL =
272
+ "Invalid arguments. Run 'firstdraft plan push --help' for usage.";
273
+ const PLAN_PUSH_INVALID_CONFIGURATION_DETAIL =
274
+ "Invalid First Draft API configuration. Run 'firstdraft plan push --help' for usage.";
275
+ const PLAN_PUSH_LOCAL_INPUT_UNREADABLE_DETAIL =
276
+ "Could not read the local First Draft Plan or state. No network request was made. Preserve the local files for manual recovery.";
277
+ const PLAN_PUSH_REQUEST_OUTCOME_UNKNOWN_DETAIL =
278
+ "The Plan may have been accepted, but the response could not be verified. Stop and reconcile before pushing again; local state was not changed.";
279
+ const PLAN_PUSH_SERVER_REJECTED_DETAIL = "First Draft rejected the Plan.";
280
+ const AUTHENTICATION_REQUIRED_DETAIL =
281
+ "First Draft authentication is required. Set FIRSTDRAFT_API_TOKEN to an active API token.";
282
+ const PLAN_STATUS_INVALID_ARGUMENTS_DETAIL =
283
+ "Invalid arguments. Run 'firstdraft plan status --help' for usage.";
284
+ const PLAN_STATUS_LOCAL_INPUT_UNREADABLE_DETAIL =
285
+ "Could not read valid local First Draft state. No network request was made. Run 'firstdraft plan init' if this directory is not initialized; otherwise repair the private state before retrying.";
286
+ const PLAN_STATUS_NOT_PUSHED_DETAIL =
287
+ "The local Foundation Plan has not been pushed successfully. Run 'firstdraft plan push' before requesting analysis status.";
288
+ const PLAN_STATUS_UNAVAILABLE_DETAIL =
289
+ "Could not verify the current analysis status. Retry this read-only request a bounded number of times; if it keeps failing, inspect the API origin pinned in .firstdraft/state.json.";
290
+ const PLAN_STATUS_INVALID_RESPONSE_DETAIL =
291
+ "First Draft returned an invalid analysis response. Retrying the unchanged request will not repair this protocol mismatch.";
292
+ const PLAN_STATUS_SERVER_REJECTED_DETAIL =
293
+ "First Draft rejected the analysis status request.";
294
+ const PLAN_STATUS_CHANGED_DETAIL =
295
+ "The current analysis changed while waiting. Run 'firstdraft plan status --wait' again to follow the latest analysis.";
296
+ const PLAN_STATUS_TIMEOUT_DETAIL =
297
+ "The current analysis is still processing after the bounded wait. Run 'firstdraft plan status --wait' again to continue waiting.";
298
+ const PLAN_COMPILE_INVALID_ARGUMENTS_DETAIL =
299
+ "Invalid arguments. Run 'firstdraft plan compile --help' for usage.";
300
+ const PLAN_COMPILE_LOCAL_INPUT_UNREADABLE_DETAIL =
301
+ "Could not read the local First Draft Plan or state. No network request was made. Preserve the local files for manual recovery.";
302
+ const PLAN_COMPILE_INCOMPATIBLE_STATE_DETAIL =
303
+ "The configured API origin or saved Foundation Plan state is incompatible with compilation. No network request was made.";
304
+ const PLAN_COMPILE_NOT_PUSHED_DETAIL =
305
+ "The current Foundation Plan could not be associated with a pushed Project.";
306
+ const PLAN_COMPILE_REQUEST_OUTCOME_UNKNOWN_DETAIL =
307
+ "The current Plan may have been accepted, but its response could not be verified. Stop and reconcile before compiling again.";
308
+ const PLAN_COMPILE_PLAN_REJECTED_DETAIL =
309
+ "First Draft rejected the current Foundation Plan.";
310
+ const PLAN_COMPILE_ANALYSIS_REJECTED_DETAIL =
311
+ "First Draft rejected the current analysis status request.";
312
+ const PLAN_COMPILE_ANALYSIS_NOT_VALID_DETAIL =
313
+ "The current Foundation Plan analysis is not valid. Inspect its status and diagnostics before compiling again.";
314
+ const PLAN_PUBLISH_INCOMPATIBLE_STATE_DETAIL =
315
+ "The saved Foundation Plan ETag is incompatible with publication. No network request was made; reconcile the CLI and server contract.";
316
+ const PLAN_PUBLISH_NOT_PUSHED_DETAIL =
317
+ "The current Foundation Plan was not retained before the Publication request.";
318
+ const PLAN_PUBLISH_LOCAL_PLAN_CHANGED_DETAIL =
319
+ "The local Foundation Plan changed after validation. Run 'firstdraft plan compile' again to submit the current bytes.";
320
+ const PLAN_PUBLISH_REQUEST_OUTCOME_UNKNOWN_DETAIL =
321
+ "The Publication may have started, but its singleton status could not be verified. No mutation was retried. Running 'firstdraft plan compile' again is safe.";
322
+ const PLAN_PUBLISH_START_REJECTED_DETAIL =
323
+ "First Draft rejected the publication request.";
324
+ const PLAN_PUBLISH_STATUS_UNAVAILABLE_DETAIL =
325
+ "Could not read the pinned publication status. The command stopped without starting another Publication.";
326
+ const PLAN_PUBLISH_STATUS_INVALID_DETAIL =
327
+ "First Draft returned an invalid publication status response. Retrying unchanged will not repair this protocol mismatch.";
328
+ const PLAN_PUBLISH_CHANGED_DETAIL =
329
+ "The pinned Publication changed while being polled. The command stopped without following a replacement.";
330
+ const PLAN_PUBLISH_TIMEOUT_DETAIL =
331
+ "The pinned Publication is still processing after the bounded ten-minute wait.";
332
+ const PLAN_PUBLISH_FAILED_DETAIL =
333
+ "The pinned Publication failed. Its validated status identifies the failed phase.";
334
+ const PLAN_PUBLISH_CANCELLED_DETAIL = "The pinned Publication was cancelled.";
335
+ const COMPILATION_STATUS_INVALID_ARGUMENTS_DETAIL =
336
+ "Invalid arguments. Run 'firstdraft compilation status --help' for usage.";
337
+ const COMPILATION_DOWNLOAD_INVALID_ARGUMENTS_DETAIL =
338
+ "Invalid arguments. Run 'firstdraft compilation download --help' for usage.";
339
+ const COMPILATION_LOCAL_INPUT_UNREADABLE_DETAIL =
340
+ "Could not read valid local First Draft state. No network request was made.";
341
+ const COMPILATION_NOT_PUSHED_DETAIL =
342
+ "The local Project has no pinned API origin. Run 'firstdraft plan push' first.";
343
+ const COMPILATION_STATUS_UNAVAILABLE_DETAIL =
344
+ "Could not read the requested Compilation status. This read-only request is safe to retry.";
345
+ const COMPILATION_STATUS_INVALID_DETAIL =
346
+ "First Draft returned an invalid Compilation status response. Retrying unchanged will not repair this protocol mismatch.";
347
+ const COMPILATION_CHANGED_DETAIL =
348
+ "The retained Compilation identity, provenance, or lifecycle progression changed while waiting.";
349
+ const COMPILATION_TIMEOUT_DETAIL =
350
+ "The retained Compilation is still processing after the bounded ten-minute wait.";
351
+ const COMPILATION_NOT_SUCCEEDED_DETAIL =
352
+ "The requested Compilation has not succeeded, so no artifact was downloaded.";
353
+ const COMPILATION_ARTIFACT_UNAVAILABLE_DETAIL =
354
+ "Could not download the requested Compilation artifact. No files were materialized.";
355
+ const COMPILATION_ARTIFACT_INVALID_DETAIL =
356
+ "The downloaded Compilation artifact did not satisfy the integrity contract. No files were materialized.";
357
+ const COMPILATION_MATERIALIZATION_FAILED_DETAIL =
358
+ "The validated Compilation artifact could not be materialized at the requested absent output path.";
359
+ const COMPILATION_INVALID_OUTPUT_PATH_DETAIL =
360
+ "The compilation output path must be absent beneath an existing real directory. No network request was made.";
361
+ const GENERATE_UUID_INVALID_ARGUMENTS_DETAIL =
362
+ "Invalid arguments. Run 'firstdraft generate uuid --help' for usage.";
363
+ const GENERATE_APPLICATION_KEY_INVALID_ARGUMENTS_DETAIL =
364
+ "Invalid arguments. Run 'firstdraft generate application-key --help' for usage.";
365
+
366
+ /**
367
+ * @typedef {object} Writer
368
+ * @property {(text: string) => unknown} write
369
+ */
370
+
371
+ /**
372
+ * @typedef {object} RunOptions
373
+ * @property {readonly string[]} argv
374
+ * @property {Writer} stdout
375
+ * @property {Writer} stderr
376
+ * @property {string} [cwd]
377
+ * @property {() => string} [getCwd]
378
+ * @property {() => string} [createProjectId]
379
+ * @property {() => string} [createUuid]
380
+ * @property {import("./commands/plan-init.js").FileSystem} [fileSystem]
381
+ * @property {typeof globalThis.fetch} [fetchFunction]
382
+ * @property {import("./commands/plan-push.js").PlanPushFileSystem} [planPushFileSystem]
383
+ * @property {() => string} [createTemporaryId]
384
+ * @property {(timeoutMs?: number) => AbortSignal} [createRequestSignal]
385
+ * @property {(delayMs: number) => Promise<void>} [planStatusSleep]
386
+ * @property {() => number} [planStatusNow]
387
+ * @property {(delayMs: number) => Promise<void>} [planCompileSleep]
388
+ * @property {() => number} [planCompileNow]
389
+ * @property {(delayMs: number) => Promise<void>} [planPublishSleep]
390
+ * @property {() => number} [planPublishNow]
391
+ * @property {(delayMs: number) => Promise<void>} [compilationSleep]
392
+ * @property {() => number} [compilationNow]
393
+ * @property {typeof pushPlan} [planCompilePush]
394
+ * @property {typeof readPlanStatus} [planCompileReadStatus]
395
+ * @property {typeof import("./commands/plan-publish.js").publishPlan} [planCompilePublish]
396
+ * @property {string} [apiUrl]
397
+ * @property {string} [apiToken]
398
+ */
399
+
400
+ /**
401
+ * @typedef {object} CommandOptions
402
+ * @property {readonly string[]} argv
403
+ * @property {Writer} stdout
404
+ * @property {Writer} stderr
405
+ * @property {string} cwd
406
+ * @property {() => string} createProjectId
407
+ * @property {() => string} createUuid
408
+ * @property {import("./commands/plan-init.js").FileSystem} [fileSystem]
409
+ * @property {typeof globalThis.fetch} [fetchFunction]
410
+ * @property {import("./commands/plan-push.js").PlanPushFileSystem} [planPushFileSystem]
411
+ * @property {() => string} [createTemporaryId]
412
+ * @property {(timeoutMs?: number) => AbortSignal} [createRequestSignal]
413
+ * @property {(delayMs: number) => Promise<void>} [planStatusSleep]
414
+ * @property {() => number} [planStatusNow]
415
+ * @property {(delayMs: number) => Promise<void>} [planCompileSleep]
416
+ * @property {() => number} [planCompileNow]
417
+ * @property {(delayMs: number) => Promise<void>} [planPublishSleep]
418
+ * @property {() => number} [planPublishNow]
419
+ * @property {(delayMs: number) => Promise<void>} [compilationSleep]
420
+ * @property {() => number} [compilationNow]
421
+ * @property {typeof pushPlan} [planCompilePush]
422
+ * @property {typeof readPlanStatus} [planCompileReadStatus]
423
+ * @property {typeof import("./commands/plan-publish.js").publishPlan} [planCompilePublish]
424
+ * @property {string} [apiUrl]
425
+ * @property {string} [apiToken]
426
+ */
427
+
428
+ /**
429
+ * @typedef {Omit<CommandOptions, "cwd" | "createUuid"> & {cwd?: string, getCwd: () => string}} PlanCommandOptions
430
+ */
431
+
432
+ /**
433
+ * @typedef {Pick<CommandOptions, "argv" | "stdout" | "stderr" | "createUuid">} GenerateCommandOptions
434
+ */
435
+
436
+ /**
437
+ * @typedef {Omit<CommandOptions, "cwd" | "createProjectId" | "createUuid" | "fileSystem" | "createTemporaryId" | "planStatusSleep" | "planStatusNow" | "planCompileSleep" | "planCompileNow" | "planPublishSleep" | "planPublishNow" | "apiUrl" | "planCompilePush" | "planCompileReadStatus" | "planCompilePublish"> & {cwd?: string, getCwd: () => string}} CompilationCommandOptions
438
+ */
439
+
440
+ /** @param {RunOptions} options */
441
+ export async function run({
442
+ argv,
443
+ stdout,
444
+ stderr,
445
+ cwd,
446
+ getCwd = process.cwd,
447
+ createProjectId = generateUuidV7,
448
+ createUuid = generateUuidV7,
449
+ fileSystem,
450
+ fetchFunction,
451
+ planPushFileSystem,
452
+ createTemporaryId,
453
+ createRequestSignal,
454
+ planStatusSleep,
455
+ planStatusNow,
456
+ planCompileSleep,
457
+ planCompileNow,
458
+ planPublishSleep,
459
+ planPublishNow,
460
+ compilationSleep,
461
+ compilationNow,
462
+ planCompilePush,
463
+ planCompileReadStatus,
464
+ planCompilePublish,
465
+ apiUrl = process.env.FIRSTDRAFT_API_URL,
466
+ apiToken = process.env.FIRSTDRAFT_API_TOKEN,
467
+ }) {
468
+ if (argv[0] === "generate") {
469
+ return runGenerate({
470
+ argv: argv.slice(1),
471
+ stdout,
472
+ stderr,
473
+ createUuid,
474
+ });
475
+ }
476
+
477
+ if (argv[0] === "plan") {
478
+ return runPlan({
479
+ argv: argv.slice(1),
480
+ stdout,
481
+ stderr,
482
+ cwd,
483
+ getCwd,
484
+ createProjectId,
485
+ fileSystem,
486
+ fetchFunction,
487
+ planPushFileSystem,
488
+ createTemporaryId,
489
+ createRequestSignal,
490
+ planStatusSleep,
491
+ planStatusNow,
492
+ planCompileSleep,
493
+ planCompileNow,
494
+ planPublishSleep,
495
+ planPublishNow,
496
+ planCompilePush,
497
+ planCompileReadStatus,
498
+ planCompilePublish,
499
+ apiUrl,
500
+ apiToken,
501
+ });
502
+ }
503
+
504
+ if (argv[0] === "compilation") {
505
+ return runCompilation({
506
+ argv: argv.slice(1),
507
+ stdout,
508
+ stderr,
509
+ cwd,
510
+ getCwd,
511
+ fetchFunction,
512
+ planPushFileSystem,
513
+ createRequestSignal,
514
+ compilationSleep,
515
+ compilationNow,
516
+ apiToken,
517
+ });
518
+ }
519
+
520
+ return runRoot({ argv, stdout, stderr });
521
+ }
522
+
523
+ /** @param {Pick<RunOptions, "argv" | "stdout" | "stderr">} options */
524
+ function runRoot({ argv, stdout, stderr }) {
525
+ const parsed = parseArguments(() =>
526
+ parseArgs({
527
+ args: [...argv],
528
+ options: {
529
+ help: { type: "boolean", short: "h" },
530
+ version: { type: "boolean", short: "V" },
531
+ },
532
+ allowPositionals: true,
533
+ strict: true,
534
+ }),
535
+ );
536
+
537
+ if (!parsed) {
538
+ stderr.write(ROOT_USAGE_ERROR);
539
+ return 2;
540
+ }
541
+
542
+ if (argv.length === 0) {
543
+ stdout.write(ROOT_HELP);
544
+ return 0;
545
+ }
546
+
547
+ if (parsed.positionals.length > 0) {
548
+ stderr.write(ROOT_UNKNOWN_COMMAND);
549
+ return 2;
550
+ }
551
+
552
+ if (parsed.values.help) {
553
+ stdout.write(ROOT_HELP);
554
+ return 0;
555
+ }
556
+
557
+ if (parsed.values.version) {
558
+ stdout.write(`${VERSION}\n`);
559
+ return 0;
560
+ }
561
+
562
+ stdout.write(ROOT_HELP);
563
+ return 0;
564
+ }
565
+
566
+ /** @param {PlanCommandOptions} options */
567
+ async function runPlan({
568
+ argv,
569
+ stdout,
570
+ stderr,
571
+ cwd,
572
+ getCwd,
573
+ createProjectId,
574
+ fileSystem,
575
+ fetchFunction,
576
+ planPushFileSystem,
577
+ createTemporaryId,
578
+ createRequestSignal,
579
+ planStatusSleep,
580
+ planStatusNow,
581
+ planCompileSleep,
582
+ planCompileNow,
583
+ planPublishSleep,
584
+ planPublishNow,
585
+ planCompilePush,
586
+ planCompileReadStatus,
587
+ planCompilePublish,
588
+ apiUrl,
589
+ apiToken,
590
+ }) {
591
+ if (argv[0] === "init") {
592
+ return runPlanInit({
593
+ argv: argv.slice(1),
594
+ stdout,
595
+ stderr,
596
+ cwd: cwd ?? getCwd(),
597
+ createProjectId,
598
+ fileSystem,
599
+ });
600
+ }
601
+
602
+ if (argv[0] === "push") {
603
+ return runPlanPush({
604
+ argv: argv.slice(1),
605
+ stdout,
606
+ stderr,
607
+ cwd: cwd ?? getCwd(),
608
+ fetchFunction,
609
+ planPushFileSystem,
610
+ createTemporaryId,
611
+ createRequestSignal,
612
+ apiUrl,
613
+ apiToken,
614
+ });
615
+ }
616
+
617
+ if (argv[0] === "status") {
618
+ return runPlanStatus({
619
+ argv: argv.slice(1),
620
+ stdout,
621
+ stderr,
622
+ cwd: cwd ?? getCwd(),
623
+ fetchFunction,
624
+ planPushFileSystem,
625
+ createRequestSignal,
626
+ planStatusSleep,
627
+ planStatusNow,
628
+ apiToken,
629
+ });
630
+ }
631
+
632
+ if (argv[0] === "compile") {
633
+ return runPlanCompile({
634
+ argv: argv.slice(1),
635
+ stdout,
636
+ stderr,
637
+ cwd: cwd ?? getCwd(),
638
+ fetchFunction,
639
+ planPushFileSystem,
640
+ createTemporaryId,
641
+ createRequestSignal,
642
+ planCompileSleep,
643
+ planCompileNow,
644
+ planPublishSleep,
645
+ planPublishNow,
646
+ planCompilePush,
647
+ planCompileReadStatus,
648
+ planCompilePublish,
649
+ apiUrl,
650
+ apiToken,
651
+ });
652
+ }
653
+
654
+ const parsed = parseArguments(() =>
655
+ parseArgs({
656
+ args: [...argv],
657
+ options: { help: { type: "boolean", short: "h" } },
658
+ allowPositionals: true,
659
+ strict: true,
660
+ }),
661
+ );
662
+
663
+ if (!parsed) {
664
+ stderr.write(PLAN_USAGE_ERROR);
665
+ return 2;
666
+ }
667
+
668
+ if (parsed.positionals.length > 0) {
669
+ stderr.write(PLAN_UNKNOWN_COMMAND);
670
+ return 2;
671
+ }
672
+
673
+ if (argv.length === 0 || parsed.values.help) {
674
+ stdout.write(PLAN_HELP);
675
+ return 0;
676
+ }
677
+
678
+ stdout.write(PLAN_HELP);
679
+ return 0;
680
+ }
681
+
682
+ /** @param {CompilationCommandOptions} options */
683
+ async function runCompilation({
684
+ argv,
685
+ stdout,
686
+ stderr,
687
+ cwd,
688
+ getCwd,
689
+ fetchFunction,
690
+ planPushFileSystem,
691
+ createRequestSignal,
692
+ compilationSleep,
693
+ compilationNow,
694
+ apiToken,
695
+ }) {
696
+ if (argv[0] === "status") {
697
+ return runCompilationStatus({
698
+ argv: argv.slice(1),
699
+ stdout,
700
+ stderr,
701
+ cwd: cwd ?? getCwd(),
702
+ fetchFunction,
703
+ planPushFileSystem,
704
+ createRequestSignal,
705
+ compilationSleep,
706
+ compilationNow,
707
+ apiToken,
708
+ });
709
+ }
710
+
711
+ if (argv[0] === "download") {
712
+ return runCompilationDownload({
713
+ argv: argv.slice(1),
714
+ stdout,
715
+ stderr,
716
+ cwd: cwd ?? getCwd(),
717
+ fetchFunction,
718
+ planPushFileSystem,
719
+ createRequestSignal,
720
+ apiToken,
721
+ });
722
+ }
723
+
724
+ const parsed = parseArguments(() =>
725
+ parseArgs({
726
+ args: [...argv],
727
+ options: { help: { type: "boolean", short: "h" } },
728
+ allowPositionals: true,
729
+ strict: true,
730
+ }),
731
+ );
732
+
733
+ if (!parsed) {
734
+ stderr.write(COMPILATION_USAGE_ERROR);
735
+ return 2;
736
+ }
737
+
738
+ if (parsed.positionals.length > 0) {
739
+ stderr.write(COMPILATION_UNKNOWN_COMMAND);
740
+ return 2;
741
+ }
742
+
743
+ if (argv.length === 0 || parsed.values.help) {
744
+ stdout.write(COMPILATION_HELP);
745
+ return 0;
746
+ }
747
+
748
+ stdout.write(COMPILATION_HELP);
749
+ return 0;
750
+ }
751
+
752
+ /**
753
+ * @param {Pick<CommandOptions, "argv" | "stdout" | "stderr" | "cwd" | "fetchFunction" | "planPushFileSystem" | "createRequestSignal" | "compilationSleep" | "compilationNow" | "apiToken">} options
754
+ */
755
+ async function runCompilationStatus({
756
+ argv,
757
+ stdout,
758
+ stderr,
759
+ cwd,
760
+ fetchFunction,
761
+ planPushFileSystem,
762
+ createRequestSignal,
763
+ compilationSleep,
764
+ compilationNow,
765
+ apiToken,
766
+ }) {
767
+ const parsed = parseArguments(() =>
768
+ parseArgs({
769
+ args: [...argv],
770
+ options: {
771
+ wait: { type: "boolean" },
772
+ help: { type: "boolean", short: "h" },
773
+ },
774
+ allowPositionals: true,
775
+ strict: true,
776
+ tokens: true,
777
+ }),
778
+ );
779
+
780
+ if (!parsed || repeatedValueOption(parsed.tokens)) {
781
+ writeCompilationInvalidArguments(
782
+ stderr,
783
+ COMPILATION_STATUS_INVALID_ARGUMENTS_DETAIL,
784
+ );
785
+ return 2;
786
+ }
787
+
788
+ if (parsed.values.help) {
789
+ stdout.write(COMPILATION_STATUS_HELP);
790
+ return 0;
791
+ }
792
+
793
+ const [compilationId] = parsed.positionals;
794
+ if (parsed.positionals.length !== 1 || !isUuidV7(compilationId)) {
795
+ writeCompilationInvalidArguments(
796
+ stderr,
797
+ COMPILATION_STATUS_INVALID_ARGUMENTS_DETAIL,
798
+ );
799
+ return 2;
800
+ }
801
+
802
+ const authorizedFetch = authenticatedFetch(fetchFunction, apiToken);
803
+ if (authorizedFetch === null) {
804
+ writeAuthenticationRequired(stderr);
805
+ return 1;
806
+ }
807
+
808
+ try {
809
+ const result = await readCompilation({
810
+ cwd,
811
+ compilationId,
812
+ wait: parsed.values.wait,
813
+ fetchFunction: authorizedFetch,
814
+ fileSystem: planPushFileSystem,
815
+ createRequestSignal,
816
+ sleep: compilationSleep,
817
+ now: compilationNow,
818
+ });
819
+ writeJson(stdout, result);
820
+ return 0;
821
+ } catch (error) {
822
+ const status = writeCompilationReadError(stderr, error, false);
823
+ if (status !== null) return status;
824
+ throw error;
825
+ }
826
+ }
827
+
828
+ /**
829
+ * @param {Pick<CommandOptions, "argv" | "stdout" | "stderr" | "cwd" | "fetchFunction" | "planPushFileSystem" | "createRequestSignal" | "apiToken">} options
830
+ */
831
+ async function runCompilationDownload({
832
+ argv,
833
+ stdout,
834
+ stderr,
835
+ cwd,
836
+ fetchFunction,
837
+ planPushFileSystem,
838
+ createRequestSignal,
839
+ apiToken,
840
+ }) {
841
+ const parsed = parseArguments(() =>
842
+ parseArgs({
843
+ args: [...argv],
844
+ options: {
845
+ output: { type: "string" },
846
+ help: { type: "boolean", short: "h" },
847
+ },
848
+ allowPositionals: true,
849
+ strict: true,
850
+ tokens: true,
851
+ }),
852
+ );
853
+
854
+ if (!parsed || repeatedValueOption(parsed.tokens)) {
855
+ writeCompilationInvalidArguments(
856
+ stderr,
857
+ COMPILATION_DOWNLOAD_INVALID_ARGUMENTS_DETAIL,
858
+ );
859
+ return 2;
860
+ }
861
+
862
+ if (parsed.values.help) {
863
+ stdout.write(COMPILATION_DOWNLOAD_HELP);
864
+ return 0;
865
+ }
866
+
867
+ const [compilationId] = parsed.positionals;
868
+ const output = parsed.values.output;
869
+ if (
870
+ parsed.positionals.length !== 1 ||
871
+ !isUuidV7(compilationId) ||
872
+ typeof output !== "string" ||
873
+ output.length === 0
874
+ ) {
875
+ writeCompilationInvalidArguments(
876
+ stderr,
877
+ COMPILATION_DOWNLOAD_INVALID_ARGUMENTS_DETAIL,
878
+ );
879
+ return 2;
880
+ }
881
+
882
+ const authorizedFetch = authenticatedFetch(fetchFunction, apiToken);
883
+ if (authorizedFetch === null) {
884
+ writeAuthenticationRequired(stderr);
885
+ return 1;
886
+ }
887
+
888
+ try {
889
+ const result = await downloadCompilation({
890
+ cwd,
891
+ compilationId,
892
+ output,
893
+ fetchFunction: authorizedFetch,
894
+ fileSystem: planPushFileSystem,
895
+ createRequestSignal,
896
+ });
897
+ writeJson(stdout, result);
898
+ return 0;
899
+ } catch (error) {
900
+ const readStatus = writeCompilationReadError(stderr, error, false);
901
+ if (readStatus !== null) return readStatus;
902
+
903
+ if (error instanceof CompilationNotSucceededError) {
904
+ writeJson(stderr, {
905
+ error: "compilation_not_succeeded",
906
+ detail: COMPILATION_NOT_SUCCEEDED_DETAIL,
907
+ current: error.current,
908
+ });
909
+ return 1;
910
+ }
911
+
912
+ if (error instanceof CompilationArtifactUnavailableError) {
913
+ if (isAuthenticationProblem(error.status, error.response)) {
914
+ writeAuthenticationRequired(
915
+ stderr,
916
+ error.status,
917
+ /** @type {Record<string, unknown>} */ (error.response),
918
+ );
919
+ return 1;
920
+ }
921
+ writeJson(stderr, {
922
+ error: "artifact_unavailable",
923
+ detail: COMPILATION_ARTIFACT_UNAVAILABLE_DETAIL,
924
+ ...(typeof error.status === "number" ? { status: error.status } : {}),
925
+ ...(error.response ? { response: error.response } : {}),
926
+ });
927
+ return 1;
928
+ }
929
+
930
+ if (
931
+ error instanceof CompilationArtifactResponseInvalidError ||
932
+ error instanceof CompilationArtifactInvalidError
933
+ ) {
934
+ writeJson(stderr, {
935
+ error: "invalid_artifact",
936
+ detail: COMPILATION_ARTIFACT_INVALID_DETAIL,
937
+ ...(error instanceof CompilationArtifactResponseInvalidError
938
+ ? { status: error.status }
939
+ : {}),
940
+ });
941
+ return 1;
942
+ }
943
+
944
+ if (error instanceof CompilationOutputPathError) {
945
+ writeJson(stderr, {
946
+ error: "invalid_output_path",
947
+ detail: COMPILATION_INVALID_OUTPUT_PATH_DETAIL,
948
+ });
949
+ return 2;
950
+ }
951
+
952
+ if (error instanceof CompilationMaterializationError) {
953
+ writeJson(stderr, {
954
+ error: "materialization_failed",
955
+ detail: COMPILATION_MATERIALIZATION_FAILED_DETAIL,
956
+ });
957
+ return 1;
958
+ }
959
+
960
+ throw error;
961
+ }
962
+ }
963
+
964
+ /** @param {Writer} writer @param {string} detail */
965
+ function writeCompilationInvalidArguments(writer, detail) {
966
+ writeJson(writer, { error: "invalid_arguments", detail });
967
+ }
968
+
969
+ /**
970
+ * @param {Writer} writer
971
+ * @param {unknown} error
972
+ * @param {boolean} [throwUnknown]
973
+ */
974
+ function writeCompilationReadError(writer, error, throwUnknown = true) {
975
+ if (error instanceof PlanPushLocalError) {
976
+ writeJson(writer, {
977
+ error: "local_input_unreadable",
978
+ detail: COMPILATION_LOCAL_INPUT_UNREADABLE_DETAIL,
979
+ });
980
+ return 1;
981
+ }
982
+
983
+ if (error instanceof CompilationNotPushedError) {
984
+ writeJson(writer, {
985
+ error: "project_not_pushed",
986
+ detail: COMPILATION_NOT_PUSHED_DETAIL,
987
+ });
988
+ return 1;
989
+ }
990
+
991
+ if (error instanceof CompilationStatusUnavailableError) {
992
+ if (isAuthenticationProblem(error.status, error.response)) {
993
+ writeAuthenticationRequired(
994
+ writer,
995
+ error.status,
996
+ /** @type {Record<string, unknown>} */ (error.response),
997
+ );
998
+ return 1;
999
+ }
1000
+ writeJson(writer, {
1001
+ error: "compilation_status_unavailable",
1002
+ detail: COMPILATION_STATUS_UNAVAILABLE_DETAIL,
1003
+ ...(typeof error.status === "number" ? { status: error.status } : {}),
1004
+ ...(error.response ? { response: error.response } : {}),
1005
+ });
1006
+ return 1;
1007
+ }
1008
+
1009
+ if (error instanceof CompilationStatusInvalidError) {
1010
+ writeJson(writer, {
1011
+ error: "invalid_compilation_status",
1012
+ detail: COMPILATION_STATUS_INVALID_DETAIL,
1013
+ status: error.status,
1014
+ });
1015
+ return 1;
1016
+ }
1017
+
1018
+ if (error instanceof CompilationChangedError) {
1019
+ writeJson(writer, {
1020
+ error: "compilation_changed",
1021
+ detail: COMPILATION_CHANGED_DETAIL,
1022
+ current: error.current,
1023
+ });
1024
+ return 1;
1025
+ }
1026
+
1027
+ if (error instanceof CompilationTimeoutError) {
1028
+ writeJson(writer, {
1029
+ error: "compilation_wait_timed_out",
1030
+ detail: COMPILATION_TIMEOUT_DETAIL,
1031
+ current: error.current,
1032
+ });
1033
+ return 1;
1034
+ }
1035
+
1036
+ if (throwUnknown) throw error;
1037
+ return null;
1038
+ }
1039
+
1040
+ /**
1041
+ * @param {GenerateCommandOptions} options
1042
+ */
1043
+ function runGenerate({ argv, stdout, stderr, createUuid }) {
1044
+ if (argv[0] === "uuid") {
1045
+ return runGenerateUuid({
1046
+ argv: argv.slice(1),
1047
+ stdout,
1048
+ stderr,
1049
+ createUuid,
1050
+ });
1051
+ }
1052
+
1053
+ if (argv[0] === "application-key") {
1054
+ return runGenerateApplicationKey({
1055
+ argv: argv.slice(1),
1056
+ stdout,
1057
+ stderr,
1058
+ });
1059
+ }
1060
+
1061
+ const parsed = parseArguments(() =>
1062
+ parseArgs({
1063
+ args: [...argv],
1064
+ options: { help: { type: "boolean", short: "h" } },
1065
+ allowPositionals: true,
1066
+ strict: true,
1067
+ }),
1068
+ );
1069
+
1070
+ if (!parsed) {
1071
+ stderr.write(GENERATE_USAGE_ERROR);
1072
+ return 2;
1073
+ }
1074
+
1075
+ if (parsed.positionals.length > 0) {
1076
+ stderr.write(GENERATE_UNKNOWN_COMMAND);
1077
+ return 2;
1078
+ }
1079
+
1080
+ if (argv.length === 0 || parsed.values.help) {
1081
+ stdout.write(GENERATE_HELP);
1082
+ return 0;
1083
+ }
1084
+
1085
+ stdout.write(GENERATE_HELP);
1086
+ return 0;
1087
+ }
1088
+
1089
+ /** @param {GenerateCommandOptions} options */
1090
+ function runGenerateUuid({ argv, stdout, stderr, createUuid }) {
1091
+ const parsed = parseArguments(() =>
1092
+ parseArgs({
1093
+ args: [...argv],
1094
+ options: {
1095
+ count: { type: "string" },
1096
+ help: { type: "boolean", short: "h" },
1097
+ },
1098
+ allowPositionals: false,
1099
+ strict: true,
1100
+ tokens: true,
1101
+ }),
1102
+ );
1103
+
1104
+ if (!parsed || repeatedValueOption(parsed.tokens)) {
1105
+ writeJson(stderr, {
1106
+ error: "invalid_arguments",
1107
+ detail: GENERATE_UUID_INVALID_ARGUMENTS_DETAIL,
1108
+ });
1109
+ return 2;
1110
+ }
1111
+
1112
+ if (parsed.values.help) {
1113
+ stdout.write(GENERATE_UUID_HELP);
1114
+ return 0;
1115
+ }
1116
+
1117
+ const count = parseUuidCount(parsed.values.count);
1118
+ if (count === null) {
1119
+ writeJson(stderr, {
1120
+ error: "invalid_arguments",
1121
+ detail: GENERATE_UUID_INVALID_ARGUMENTS_DETAIL,
1122
+ });
1123
+ return 2;
1124
+ }
1125
+
1126
+ for (let index = 0; index < count; index += 1) {
1127
+ stdout.write(`${createUuid()}\n`);
1128
+ }
1129
+ return 0;
1130
+ }
1131
+
1132
+ /**
1133
+ * @param {Pick<GenerateCommandOptions, "argv" | "stdout" | "stderr">} options
1134
+ */
1135
+ function runGenerateApplicationKey({ argv, stdout, stderr }) {
1136
+ const parsed = parseArguments(() =>
1137
+ parseArgs({
1138
+ args: [...argv],
1139
+ options: {
1140
+ name: { type: "string" },
1141
+ help: { type: "boolean", short: "h" },
1142
+ },
1143
+ allowPositionals: false,
1144
+ strict: true,
1145
+ tokens: true,
1146
+ }),
1147
+ );
1148
+
1149
+ if (!parsed || repeatedValueOption(parsed.tokens)) {
1150
+ writeJson(stderr, {
1151
+ error: "invalid_arguments",
1152
+ detail: GENERATE_APPLICATION_KEY_INVALID_ARGUMENTS_DETAIL,
1153
+ });
1154
+ return 2;
1155
+ }
1156
+
1157
+ if (parsed.values.help) {
1158
+ stdout.write(GENERATE_APPLICATION_KEY_HELP);
1159
+ return 0;
1160
+ }
1161
+
1162
+ if (!isValidApplicationName(parsed.values.name)) {
1163
+ writeJson(stderr, {
1164
+ error: "invalid_arguments",
1165
+ detail: GENERATE_APPLICATION_KEY_INVALID_ARGUMENTS_DETAIL,
1166
+ });
1167
+ return 2;
1168
+ }
1169
+
1170
+ stdout.write(`${deriveApplicationKey(parsed.values.name)}\n`);
1171
+ return 0;
1172
+ }
1173
+
1174
+ /**
1175
+ * @param {Pick<CommandOptions, "argv" | "stdout" | "stderr" | "cwd" | "fetchFunction" | "planPushFileSystem" | "createTemporaryId" | "createRequestSignal" | "apiUrl" | "apiToken">} options
1176
+ */
1177
+ async function runPlanPush({
1178
+ argv,
1179
+ stdout,
1180
+ stderr,
1181
+ cwd,
1182
+ fetchFunction,
1183
+ planPushFileSystem,
1184
+ createTemporaryId,
1185
+ createRequestSignal,
1186
+ apiUrl,
1187
+ apiToken,
1188
+ }) {
1189
+ const parsed = parseArguments(() =>
1190
+ parseArgs({
1191
+ args: [...argv],
1192
+ options: { help: { type: "boolean", short: "h" } },
1193
+ allowPositionals: false,
1194
+ strict: true,
1195
+ tokens: true,
1196
+ }),
1197
+ );
1198
+
1199
+ if (!parsed || repeatedValueOption(parsed.tokens)) {
1200
+ writeJson(stderr, {
1201
+ error: "invalid_arguments",
1202
+ detail: PLAN_PUSH_INVALID_ARGUMENTS_DETAIL,
1203
+ });
1204
+ return 2;
1205
+ }
1206
+
1207
+ if (parsed.values.help) {
1208
+ stdout.write(PLAN_PUSH_HELP);
1209
+ return 0;
1210
+ }
1211
+
1212
+ const authorizedFetch = authenticatedFetch(fetchFunction, apiToken);
1213
+ if (authorizedFetch === null) {
1214
+ writeAuthenticationRequired(stderr);
1215
+ return 1;
1216
+ }
1217
+
1218
+ let result;
1219
+ try {
1220
+ result = await pushPlan({
1221
+ cwd,
1222
+ apiUrl,
1223
+ fetchFunction: authorizedFetch,
1224
+ fileSystem: planPushFileSystem,
1225
+ createTemporaryId,
1226
+ createRequestSignal,
1227
+ });
1228
+ } catch (error) {
1229
+ if (error instanceof PlanPushConfigurationError) {
1230
+ writeJson(stderr, {
1231
+ error: "invalid_configuration",
1232
+ detail: PLAN_PUSH_INVALID_CONFIGURATION_DETAIL,
1233
+ });
1234
+ return 2;
1235
+ }
1236
+
1237
+ if (error instanceof PlanPushLocalError) {
1238
+ writeJson(stderr, {
1239
+ error: "local_input_unreadable",
1240
+ detail: PLAN_PUSH_LOCAL_INPUT_UNREADABLE_DETAIL,
1241
+ });
1242
+ return 1;
1243
+ }
1244
+
1245
+ if (
1246
+ error instanceof PlanPushNetworkError ||
1247
+ error instanceof PlanPushProtocolError
1248
+ ) {
1249
+ writeJson(stderr, {
1250
+ error: "request_outcome_unknown",
1251
+ detail: PLAN_PUSH_REQUEST_OUTCOME_UNKNOWN_DETAIL,
1252
+ ...(typeof error.status === "number" ? { status: error.status } : {}),
1253
+ });
1254
+ return 1;
1255
+ }
1256
+
1257
+ if (error instanceof PlanPushStateWriteError) {
1258
+ writeJson(stderr, {
1259
+ error: "local_state_not_saved",
1260
+ detail:
1261
+ "The Plan was accepted, but its ETag could not be saved. Do not push again until local state is repaired.",
1262
+ recovery_state: error.recoveryState,
1263
+ });
1264
+ return 1;
1265
+ }
1266
+
1267
+ throw error;
1268
+ }
1269
+
1270
+ if (!("etag" in result)) {
1271
+ if (result.responseKind === null) {
1272
+ writeJson(stderr, {
1273
+ error: "request_outcome_unknown",
1274
+ detail: PLAN_PUSH_REQUEST_OUTCOME_UNKNOWN_DETAIL,
1275
+ status: result.status,
1276
+ });
1277
+ return 1;
1278
+ }
1279
+
1280
+ const response = safeRejectedResponse(result.responseKind, result.body);
1281
+ if (isAuthenticationProblem(result.status, response)) {
1282
+ writeAuthenticationRequired(stderr, result.status, response);
1283
+ return 1;
1284
+ }
1285
+ writeJson(stderr, {
1286
+ error: "server_rejected",
1287
+ detail: PLAN_PUSH_SERVER_REJECTED_DETAIL,
1288
+ status: result.status,
1289
+ ...(response ? { response } : {}),
1290
+ });
1291
+ return 1;
1292
+ }
1293
+
1294
+ writeJson(stdout, {
1295
+ outcome: result.outcome,
1296
+ etag: result.etag,
1297
+ project: result.body.project,
1298
+ foundation_plan: result.body.foundation_plan,
1299
+ diagnostics: result.body.diagnostics,
1300
+ });
1301
+ return 0;
1302
+ }
1303
+
1304
+ /**
1305
+ * @param {Pick<CommandOptions, "argv" | "stdout" | "stderr" | "cwd" | "fetchFunction" | "planPushFileSystem" | "createRequestSignal" | "planStatusSleep" | "planStatusNow" | "apiToken">} options
1306
+ */
1307
+ async function runPlanStatus({
1308
+ argv,
1309
+ stdout,
1310
+ stderr,
1311
+ cwd,
1312
+ fetchFunction,
1313
+ planPushFileSystem,
1314
+ createRequestSignal,
1315
+ planStatusSleep,
1316
+ planStatusNow,
1317
+ apiToken,
1318
+ }) {
1319
+ const parsed = parseArguments(() =>
1320
+ parseArgs({
1321
+ args: [...argv],
1322
+ options: {
1323
+ help: { type: "boolean", short: "h" },
1324
+ wait: { type: "boolean" },
1325
+ },
1326
+ allowPositionals: false,
1327
+ strict: true,
1328
+ tokens: true,
1329
+ }),
1330
+ );
1331
+
1332
+ if (!parsed || repeatedValueOption(parsed.tokens)) {
1333
+ writeJson(stderr, {
1334
+ error: "invalid_arguments",
1335
+ detail: PLAN_STATUS_INVALID_ARGUMENTS_DETAIL,
1336
+ });
1337
+ return 2;
1338
+ }
1339
+
1340
+ if (parsed.values.help) {
1341
+ stdout.write(PLAN_STATUS_HELP);
1342
+ return 0;
1343
+ }
1344
+
1345
+ const authorizedFetch = authenticatedFetch(fetchFunction, apiToken);
1346
+ if (authorizedFetch === null) {
1347
+ writeAuthenticationRequired(stderr);
1348
+ return 1;
1349
+ }
1350
+
1351
+ let result;
1352
+ try {
1353
+ result = await readPlanStatus({
1354
+ cwd,
1355
+ wait: parsed.values.wait,
1356
+ fetchFunction: authorizedFetch,
1357
+ fileSystem: planPushFileSystem,
1358
+ createRequestSignal,
1359
+ sleep: planStatusSleep,
1360
+ now: planStatusNow,
1361
+ });
1362
+ } catch (error) {
1363
+ if (error instanceof PlanPushLocalError) {
1364
+ writeJson(stderr, {
1365
+ error: "local_input_unreadable",
1366
+ detail: PLAN_STATUS_LOCAL_INPUT_UNREADABLE_DETAIL,
1367
+ });
1368
+ return 1;
1369
+ }
1370
+
1371
+ if (error instanceof PlanStatusNotPushedError) {
1372
+ writeJson(stderr, {
1373
+ error: "project_not_pushed",
1374
+ detail: PLAN_STATUS_NOT_PUSHED_DETAIL,
1375
+ });
1376
+ return 1;
1377
+ }
1378
+
1379
+ if (error instanceof PlanStatusChangedError) {
1380
+ writeJson(stderr, {
1381
+ error: "analysis_changed",
1382
+ detail: PLAN_STATUS_CHANGED_DETAIL,
1383
+ current: error.current,
1384
+ });
1385
+ return 1;
1386
+ }
1387
+
1388
+ if (error instanceof PlanStatusTimeoutError) {
1389
+ writeJson(stderr, {
1390
+ error: "wait_timed_out",
1391
+ detail: PLAN_STATUS_TIMEOUT_DETAIL,
1392
+ current: error.current,
1393
+ });
1394
+ return 1;
1395
+ }
1396
+
1397
+ if (error instanceof PlanPushNetworkError) {
1398
+ writeJson(stderr, {
1399
+ error: "status_unavailable",
1400
+ detail: PLAN_STATUS_UNAVAILABLE_DETAIL,
1401
+ ...(typeof error.status === "number" ? { status: error.status } : {}),
1402
+ });
1403
+ return 1;
1404
+ }
1405
+
1406
+ if (error instanceof PlanPushProtocolError) {
1407
+ writeJson(stderr, {
1408
+ error: "invalid_server_response",
1409
+ detail: PLAN_STATUS_INVALID_RESPONSE_DETAIL,
1410
+ status: error.status,
1411
+ });
1412
+ return 1;
1413
+ }
1414
+
1415
+ throw error;
1416
+ }
1417
+
1418
+ if ("responseKind" in result) {
1419
+ if (result.responseKind === null) {
1420
+ writeJson(stderr, {
1421
+ error: "invalid_server_response",
1422
+ detail: PLAN_STATUS_INVALID_RESPONSE_DETAIL,
1423
+ status: result.status,
1424
+ });
1425
+ return 1;
1426
+ }
1427
+
1428
+ const response = safeRejectedResponse(result.responseKind, result.body);
1429
+ if (isAuthenticationProblem(result.status, response)) {
1430
+ writeAuthenticationRequired(stderr, result.status, response);
1431
+ return 1;
1432
+ }
1433
+ writeJson(stderr, {
1434
+ error: "server_rejected",
1435
+ detail: PLAN_STATUS_SERVER_REJECTED_DETAIL,
1436
+ status: result.status,
1437
+ ...(response ? { response } : {}),
1438
+ });
1439
+ return 1;
1440
+ }
1441
+
1442
+ writeJson(stdout, result.body);
1443
+ return 0;
1444
+ }
1445
+
1446
+ /**
1447
+ * @param {Pick<CommandOptions, "argv" | "stdout" | "stderr" | "cwd" | "fetchFunction" | "planPushFileSystem" | "createTemporaryId" | "createRequestSignal" | "planCompileSleep" | "planCompileNow" | "planPublishSleep" | "planPublishNow" | "planCompilePush" | "planCompileReadStatus" | "planCompilePublish" | "apiUrl" | "apiToken">} options
1448
+ */
1449
+ async function runPlanCompile({
1450
+ argv,
1451
+ stdout,
1452
+ stderr,
1453
+ cwd,
1454
+ fetchFunction,
1455
+ planPushFileSystem,
1456
+ createTemporaryId,
1457
+ createRequestSignal,
1458
+ planCompileSleep,
1459
+ planCompileNow,
1460
+ planPublishSleep,
1461
+ planPublishNow,
1462
+ planCompilePush,
1463
+ planCompileReadStatus,
1464
+ planCompilePublish,
1465
+ apiUrl,
1466
+ apiToken,
1467
+ }) {
1468
+ const parsed = parseArguments(() =>
1469
+ parseArgs({
1470
+ args: [...argv],
1471
+ options: { help: { type: "boolean", short: "h" } },
1472
+ allowPositionals: false,
1473
+ strict: true,
1474
+ tokens: true,
1475
+ }),
1476
+ );
1477
+
1478
+ if (!parsed || repeatedValueOption(parsed.tokens)) {
1479
+ writeJson(stderr, {
1480
+ error: "invalid_arguments",
1481
+ detail: PLAN_COMPILE_INVALID_ARGUMENTS_DETAIL,
1482
+ });
1483
+ return 2;
1484
+ }
1485
+
1486
+ if (parsed.values.help) {
1487
+ stdout.write(PLAN_COMPILE_HELP);
1488
+ return 0;
1489
+ }
1490
+
1491
+ const authorizedFetch = authenticatedFetch(fetchFunction, apiToken);
1492
+ if (authorizedFetch === null) {
1493
+ writeAuthenticationRequired(stderr);
1494
+ return 1;
1495
+ }
1496
+
1497
+ let result;
1498
+ try {
1499
+ result = await compilePlan({
1500
+ cwd,
1501
+ apiUrl,
1502
+ fetchFunction: authorizedFetch,
1503
+ fileSystem: planPushFileSystem,
1504
+ createTemporaryId,
1505
+ createRequestSignal,
1506
+ analysisSleep: planCompileSleep,
1507
+ analysisNow: planCompileNow,
1508
+ publicationSleep: planPublishSleep,
1509
+ publicationNow: planPublishNow,
1510
+ push: planCompilePush,
1511
+ readStatus: planCompileReadStatus,
1512
+ publish: planCompilePublish,
1513
+ });
1514
+ } catch (error) {
1515
+ return writePlanCompileError(stderr, error);
1516
+ }
1517
+
1518
+ writeJson(stdout, result);
1519
+ return 0;
1520
+ }
1521
+
1522
+ /** @param {Writer} writer @param {unknown} error */
1523
+ function writePlanCompileError(writer, error) {
1524
+ if (error instanceof PlanPushConfigurationError) {
1525
+ writeJson(writer, {
1526
+ error: "invalid_configuration",
1527
+ detail: PLAN_COMPILE_INCOMPATIBLE_STATE_DETAIL,
1528
+ });
1529
+ return 2;
1530
+ }
1531
+
1532
+ if (error instanceof PlanPushLocalError) {
1533
+ writeJson(writer, {
1534
+ error: "local_input_unreadable",
1535
+ detail: PLAN_COMPILE_LOCAL_INPUT_UNREADABLE_DETAIL,
1536
+ });
1537
+ return 1;
1538
+ }
1539
+
1540
+ if (
1541
+ error instanceof PlanPushNetworkError ||
1542
+ error instanceof PlanPushProtocolError
1543
+ ) {
1544
+ writeJson(writer, {
1545
+ error: "request_outcome_unknown",
1546
+ phase: "push",
1547
+ detail: PLAN_COMPILE_REQUEST_OUTCOME_UNKNOWN_DETAIL,
1548
+ ...(typeof error.status === "number" ? { status: error.status } : {}),
1549
+ });
1550
+ return 1;
1551
+ }
1552
+
1553
+ if (error instanceof PlanPushStateWriteError) {
1554
+ writeJson(writer, {
1555
+ error: "local_state_not_saved",
1556
+ detail:
1557
+ "The Plan was accepted, but its ETag could not be saved. Do not compile again until local state is repaired.",
1558
+ recovery_state: error.recoveryState,
1559
+ });
1560
+ return 1;
1561
+ }
1562
+
1563
+ if (error instanceof PlanCompilePushRejectedError) {
1564
+ const { result } = error;
1565
+ if (result.responseKind === null) {
1566
+ writeJson(writer, {
1567
+ error: "request_outcome_unknown",
1568
+ phase: "push",
1569
+ detail: PLAN_COMPILE_REQUEST_OUTCOME_UNKNOWN_DETAIL,
1570
+ status: result.status,
1571
+ });
1572
+ return 1;
1573
+ }
1574
+
1575
+ const response = safeRejectedResponse(result.responseKind, result.body);
1576
+ if (isAuthenticationProblem(result.status, response)) {
1577
+ writeAuthenticationRequired(writer, result.status, response);
1578
+ return 1;
1579
+ }
1580
+ writeJson(writer, {
1581
+ error: "server_rejected",
1582
+ detail: PLAN_COMPILE_PLAN_REJECTED_DETAIL,
1583
+ status: result.status,
1584
+ ...(response ? { response } : {}),
1585
+ });
1586
+ return 1;
1587
+ }
1588
+
1589
+ if (error instanceof PlanStatusNotPushedError) {
1590
+ writeJson(writer, {
1591
+ error: "project_not_pushed",
1592
+ detail: PLAN_COMPILE_NOT_PUSHED_DETAIL,
1593
+ });
1594
+ return 1;
1595
+ }
1596
+
1597
+ if (error instanceof PlanStatusChangedError) {
1598
+ writeJson(writer, {
1599
+ error: "analysis_changed",
1600
+ detail: PLAN_STATUS_CHANGED_DETAIL,
1601
+ current: error.current,
1602
+ });
1603
+ return 1;
1604
+ }
1605
+
1606
+ if (error instanceof PlanStatusTimeoutError) {
1607
+ writeJson(writer, {
1608
+ error: "analysis_wait_timed_out",
1609
+ detail: PLAN_STATUS_TIMEOUT_DETAIL,
1610
+ current: error.current,
1611
+ });
1612
+ return 1;
1613
+ }
1614
+
1615
+ if (error instanceof PlanCompileAnalysisUnavailableError) {
1616
+ writeJson(writer, {
1617
+ error: "analysis_status_unavailable",
1618
+ detail: PLAN_STATUS_UNAVAILABLE_DETAIL,
1619
+ ...(typeof error.status === "number" ? { status: error.status } : {}),
1620
+ });
1621
+ return 1;
1622
+ }
1623
+
1624
+ if (error instanceof PlanCompileAnalysisInvalidError) {
1625
+ writeJson(writer, {
1626
+ error: "invalid_analysis_status",
1627
+ detail: PLAN_STATUS_INVALID_RESPONSE_DETAIL,
1628
+ status: error.status,
1629
+ });
1630
+ return 1;
1631
+ }
1632
+
1633
+ if (error instanceof PlanCompileAnalysisRejectedError) {
1634
+ const { result } = error;
1635
+ if (result.responseKind === null) {
1636
+ writeJson(writer, {
1637
+ error: "invalid_analysis_status",
1638
+ detail: PLAN_STATUS_INVALID_RESPONSE_DETAIL,
1639
+ status: result.status,
1640
+ });
1641
+ return 1;
1642
+ }
1643
+
1644
+ const response = safeRejectedResponse(result.responseKind, result.body);
1645
+ if (isAuthenticationProblem(result.status, response)) {
1646
+ writeAuthenticationRequired(writer, result.status, response);
1647
+ return 1;
1648
+ }
1649
+ writeJson(writer, {
1650
+ error: "analysis_status_rejected",
1651
+ detail: PLAN_COMPILE_ANALYSIS_REJECTED_DETAIL,
1652
+ status: result.status,
1653
+ ...(response ? { response } : {}),
1654
+ });
1655
+ return 1;
1656
+ }
1657
+
1658
+ if (error instanceof PlanCompileAnalysisNotValidError) {
1659
+ writeJson(writer, {
1660
+ error: "plan_not_valid",
1661
+ detail: PLAN_COMPILE_ANALYSIS_NOT_VALID_DETAIL,
1662
+ current: error.current,
1663
+ });
1664
+ return 1;
1665
+ }
1666
+
1667
+ if (error instanceof PublicationLocalStateError) {
1668
+ writeJson(writer, {
1669
+ error: "invalid_configuration",
1670
+ detail: PLAN_PUBLISH_INCOMPATIBLE_STATE_DETAIL,
1671
+ });
1672
+ return 2;
1673
+ }
1674
+
1675
+ if (error instanceof PublicationNotPushedError) {
1676
+ writeJson(writer, {
1677
+ error: "project_not_pushed",
1678
+ detail: PLAN_PUBLISH_NOT_PUSHED_DETAIL,
1679
+ });
1680
+ return 1;
1681
+ }
1682
+
1683
+ if (error instanceof PublicationLocalPlanChangedError) {
1684
+ writeJson(writer, {
1685
+ error: "local_plan_changed",
1686
+ detail: PLAN_PUBLISH_LOCAL_PLAN_CHANGED_DETAIL,
1687
+ });
1688
+ return 1;
1689
+ }
1690
+
1691
+ if (
1692
+ (error instanceof PublicationStartRejectedError ||
1693
+ error instanceof PublicationStatusUnavailableError) &&
1694
+ isAuthenticationProblem(error.status, error.response)
1695
+ ) {
1696
+ writeAuthenticationRequired(
1697
+ writer,
1698
+ error.status,
1699
+ /** @type {Record<string, unknown>} */ (error.response),
1700
+ );
1701
+ return 1;
1702
+ }
1703
+
1704
+ if (error instanceof PublicationRequestOutcomeUnknownError) {
1705
+ writeJson(writer, {
1706
+ error: "request_outcome_unknown",
1707
+ phase: "publication",
1708
+ detail: PLAN_PUBLISH_REQUEST_OUTCOME_UNKNOWN_DETAIL,
1709
+ ...(typeof error.status === "number" ? { status: error.status } : {}),
1710
+ ...(error.response ? { response: error.response } : {}),
1711
+ });
1712
+ return 1;
1713
+ }
1714
+
1715
+ if (error instanceof PublicationStartRejectedError) {
1716
+ writeJson(writer, {
1717
+ error: "publication_start_rejected",
1718
+ detail: PLAN_PUBLISH_START_REJECTED_DETAIL,
1719
+ status: error.status,
1720
+ response: error.response,
1721
+ });
1722
+ return 1;
1723
+ }
1724
+
1725
+ if (error instanceof PublicationStatusUnavailableError) {
1726
+ writeJson(writer, {
1727
+ error: "publication_status_unavailable",
1728
+ detail: PLAN_PUBLISH_STATUS_UNAVAILABLE_DETAIL,
1729
+ ...(typeof error.status === "number" ? { status: error.status } : {}),
1730
+ ...(error.response ? { response: error.response } : {}),
1731
+ });
1732
+ return 1;
1733
+ }
1734
+
1735
+ if (error instanceof PublicationStatusInvalidError) {
1736
+ writeJson(writer, {
1737
+ error: "invalid_publication_status",
1738
+ detail: PLAN_PUBLISH_STATUS_INVALID_DETAIL,
1739
+ status: error.status,
1740
+ });
1741
+ return 1;
1742
+ }
1743
+
1744
+ if (error instanceof PublicationChangedError) {
1745
+ writeJson(writer, {
1746
+ error: "publication_changed",
1747
+ detail: PLAN_PUBLISH_CHANGED_DETAIL,
1748
+ current: error.current,
1749
+ rejected: error.rejected,
1750
+ });
1751
+ return 1;
1752
+ }
1753
+
1754
+ if (error instanceof PublicationTimeoutError) {
1755
+ writeJson(writer, {
1756
+ error: "publication_wait_timed_out",
1757
+ detail: PLAN_PUBLISH_TIMEOUT_DETAIL,
1758
+ current: error.current,
1759
+ });
1760
+ return 1;
1761
+ }
1762
+
1763
+ if (error instanceof PublicationFailedError) {
1764
+ writeJson(writer, {
1765
+ error: "publication_failed",
1766
+ detail: PLAN_PUBLISH_FAILED_DETAIL,
1767
+ current: error.current,
1768
+ });
1769
+ return 1;
1770
+ }
1771
+
1772
+ if (error instanceof PublicationCancelledError) {
1773
+ writeJson(writer, {
1774
+ error: "publication_cancelled",
1775
+ detail: PLAN_PUBLISH_CANCELLED_DETAIL,
1776
+ current: error.current,
1777
+ });
1778
+ return 1;
1779
+ }
1780
+
1781
+ throw error;
1782
+ }
1783
+
1784
+ /**
1785
+ * @param {Pick<CommandOptions, "argv" | "stdout" | "stderr" | "cwd" | "createProjectId" | "fileSystem">} options
1786
+ */
1787
+ function runPlanInit({
1788
+ argv,
1789
+ stdout,
1790
+ stderr,
1791
+ cwd,
1792
+ createProjectId,
1793
+ fileSystem,
1794
+ }) {
1795
+ const parsed = parseArguments(() =>
1796
+ parseArgs({
1797
+ args: [...argv],
1798
+ options: {
1799
+ "application-key": { type: "string" },
1800
+ name: { type: "string" },
1801
+ help: { type: "boolean", short: "h" },
1802
+ },
1803
+ allowPositionals: false,
1804
+ strict: true,
1805
+ tokens: true,
1806
+ }),
1807
+ );
1808
+
1809
+ if (!parsed || repeatedValueOption(parsed.tokens)) {
1810
+ writeJson(stderr, {
1811
+ error: "invalid_arguments",
1812
+ detail: PLAN_INIT_INVALID_ARGUMENTS_DETAIL,
1813
+ });
1814
+ return 2;
1815
+ }
1816
+
1817
+ if (parsed.values.help) {
1818
+ stdout.write(PLAN_INIT_HELP);
1819
+ return 0;
1820
+ }
1821
+
1822
+ const providedApplicationKey = parsed.values["application-key"];
1823
+ const providedName = parsed.values.name;
1824
+ if (
1825
+ (providedApplicationKey !== undefined &&
1826
+ !isValidApplicationKey(providedApplicationKey)) ||
1827
+ (providedName !== undefined && !isValidApplicationName(providedName)) ||
1828
+ (providedApplicationKey === undefined && providedName === undefined)
1829
+ ) {
1830
+ writeJson(stderr, {
1831
+ error: "invalid_arguments",
1832
+ detail: PLAN_INIT_INVALID_ARGUMENTS_DETAIL,
1833
+ });
1834
+ return 2;
1835
+ }
1836
+
1837
+ let applicationKey;
1838
+ let name;
1839
+ if (providedApplicationKey !== undefined) {
1840
+ applicationKey = providedApplicationKey;
1841
+ name =
1842
+ providedName === undefined
1843
+ ? deriveApplicationName(providedApplicationKey)
1844
+ : providedName;
1845
+ } else {
1846
+ name = /** @type {string} */ (providedName);
1847
+ applicationKey = deriveApplicationKey(name);
1848
+ }
1849
+
1850
+ const projectId = createProjectId();
1851
+
1852
+ try {
1853
+ initializePlan({
1854
+ applicationKey,
1855
+ name,
1856
+ projectId,
1857
+ cwd,
1858
+ fileSystem,
1859
+ });
1860
+ } catch (error) {
1861
+ if (!isFileSystemError(error)) throw error;
1862
+
1863
+ writeJson(stderr, {
1864
+ error: "local_initialization_failed",
1865
+ detail: PLAN_INIT_FAILED_DETAIL,
1866
+ });
1867
+ return 1;
1868
+ }
1869
+
1870
+ stdout.write(PLAN_INIT_SUCCESS);
1871
+ return 0;
1872
+ }
1873
+
1874
+ /** @param {unknown} value */
1875
+ function parseUuidCount(value) {
1876
+ if (value === undefined) return 1;
1877
+ if (typeof value !== "string" || !/^[1-9][0-9]*$/.test(value)) return null;
1878
+
1879
+ const count = Number(value);
1880
+ return Number.isSafeInteger(count) ? count : null;
1881
+ }
1882
+
1883
+ /**
1884
+ * @template T
1885
+ * @param {() => T} callback
1886
+ * @returns {T | null}
1887
+ */
1888
+ function parseArguments(callback) {
1889
+ try {
1890
+ return callback();
1891
+ } catch (error) {
1892
+ if (!isParseArgsError(error)) throw error;
1893
+
1894
+ return null;
1895
+ }
1896
+ }
1897
+
1898
+ /** @param {readonly {kind: string, name?: string}[]} tokens */
1899
+ function repeatedValueOption(tokens) {
1900
+ const names = tokens
1901
+ .filter(
1902
+ (token) =>
1903
+ token.kind === "option" &&
1904
+ typeof token.name === "string" &&
1905
+ token.name !== "help",
1906
+ )
1907
+ .map((token) => token.name);
1908
+
1909
+ return new Set(names).size !== names.length;
1910
+ }
1911
+
1912
+ /** @param {unknown} error */
1913
+ function isParseArgsError(error) {
1914
+ return (
1915
+ error instanceof Error &&
1916
+ "code" in error &&
1917
+ typeof error.code === "string" &&
1918
+ error.code.startsWith("ERR_PARSE_ARGS_")
1919
+ );
1920
+ }
1921
+
1922
+ /** @param {Writer} writer @param {unknown} value */
1923
+ function writeJson(writer, value) {
1924
+ writer.write(`${JSON.stringify(value, null, 2)}\n`);
1925
+ }
1926
+
1927
+ /**
1928
+ * @param {Writer} writer
1929
+ * @param {number} [status]
1930
+ * @param {Record<string, unknown>} [response]
1931
+ */
1932
+ function writeAuthenticationRequired(writer, status, response) {
1933
+ writeJson(writer, {
1934
+ error: "authentication_required",
1935
+ detail: AUTHENTICATION_REQUIRED_DETAIL,
1936
+ ...(status === undefined ? {} : { status }),
1937
+ ...(response === undefined ? {} : { response }),
1938
+ });
1939
+ }
1940
+
1941
+ /**
1942
+ * @param {"diagnostics" | "problem" | null} responseKind
1943
+ * @param {Record<string, unknown> | null} body
1944
+ */
1945
+ function safeRejectedResponse(responseKind, body) {
1946
+ if (
1947
+ responseKind === "diagnostics" &&
1948
+ body &&
1949
+ Array.isArray(body.diagnostics)
1950
+ ) {
1951
+ return {
1952
+ source_sha256: body.source_sha256,
1953
+ diagnostics: body.diagnostics.map(safeDiagnostic),
1954
+ };
1955
+ }
1956
+
1957
+ if (responseKind === "problem" && body) {
1958
+ return {
1959
+ ...(body.type === "about:blank" ? { type: body.type } : {}),
1960
+ title: body.title,
1961
+ status: body.status,
1962
+ code: body.code,
1963
+ detail: body.detail,
1964
+ };
1965
+ }
1966
+
1967
+ return null;
1968
+ }
1969
+
1970
+ /** @param {unknown} value */
1971
+ function safeDiagnostic(value) {
1972
+ if (!isRecord(value)) return {};
1973
+
1974
+ const location = safeSourceLocation(value.location);
1975
+ const subject = safeDiagnosticSubject(value.subject);
1976
+ const relatedLocations = safeSourceLocations(value.related_locations);
1977
+ const suggestions = safeSuggestions(value.suggestions);
1978
+
1979
+ return {
1980
+ ...(typeof value.code === "string" ? { code: value.code } : {}),
1981
+ ...(value.severity === "error" || value.severity === "warning"
1982
+ ? { severity: value.severity }
1983
+ : {}),
1984
+ ...(typeof value.message === "string" ? { message: value.message } : {}),
1985
+ ...(location ? { location } : {}),
1986
+ ...(value.subject === null ? { subject: null } : {}),
1987
+ ...(subject ? { subject } : {}),
1988
+ ...(relatedLocations ? { related_locations: relatedLocations } : {}),
1989
+ ...(suggestions ? { suggestions } : {}),
1990
+ };
1991
+ }
1992
+
1993
+ /** @param {unknown} value */
1994
+ function safeSourceLocations(value) {
1995
+ if (!Array.isArray(value)) return null;
1996
+
1997
+ const locations = value.map(safeSourceLocation);
1998
+ return locations.every(Boolean) ? locations : null;
1999
+ }
2000
+
2001
+ /** @param {unknown} value */
2002
+ function safeSuggestions(value) {
2003
+ if (
2004
+ !Array.isArray(value) ||
2005
+ !value.every((suggestion) => typeof suggestion === "string")
2006
+ ) {
2007
+ return null;
2008
+ }
2009
+
2010
+ return value;
2011
+ }
2012
+
2013
+ /** @param {unknown} value */
2014
+ function safeSourceLocation(value) {
2015
+ if (!isRecord(value)) return null;
2016
+
2017
+ if (typeof value.source_pointer === "string") {
2018
+ return { source_pointer: value.source_pointer };
2019
+ }
2020
+
2021
+ if (
2022
+ Number.isSafeInteger(value.line) &&
2023
+ Number(value.line) > 0 &&
2024
+ Number.isSafeInteger(value.column) &&
2025
+ Number(value.column) > 0
2026
+ ) {
2027
+ return { line: value.line, column: value.column };
2028
+ }
2029
+
2030
+ return null;
2031
+ }
2032
+
2033
+ /** @param {unknown} value */
2034
+ function safeDiagnosticSubject(value) {
2035
+ if (
2036
+ !isRecord(value) ||
2037
+ typeof value.kind !== "string" ||
2038
+ typeof value.readable_path !== "string" ||
2039
+ (value.subject_uuid !== undefined && typeof value.subject_uuid !== "string")
2040
+ ) {
2041
+ return null;
2042
+ }
2043
+
2044
+ return {
2045
+ kind: value.kind,
2046
+ readable_path: value.readable_path,
2047
+ ...(typeof value.subject_uuid === "string"
2048
+ ? { subject_uuid: value.subject_uuid }
2049
+ : {}),
2050
+ };
2051
+ }
2052
+
2053
+ /** @param {unknown} value @returns {value is Record<string, unknown>} */
2054
+ function isRecord(value) {
2055
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2056
+ }