@firstdraft.com/cli 0.2.0 → 0.2.1

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.
@@ -1,4 +1,6 @@
1
1
  import { createHash } from "node:crypto";
2
+ import { lstatSync, readFileSync } from "node:fs";
3
+ import path from "node:path";
2
4
 
3
5
  import {
4
6
  ARTIFACT_MEDIA_TYPE,
@@ -19,8 +21,9 @@ import {
19
21
  responseMediaType,
20
22
  sendRequest,
21
23
  } from "../api-response.js";
22
- import { isUuidV7, readPlanState } from "../plan-state.js";
24
+ import { isUuidV7, readLocalFile, readPlanState } from "../plan-state.js";
23
25
 
26
+ const MAX_PLAN_BYTES = 1024 * 1024;
24
27
  const REQUEST_TIMEOUT_MS = 30_000;
25
28
  const WAIT_TIMEOUT_MS = 10 * 60_000;
26
29
  const POLL_INTERVAL_MS = 1_000;
@@ -57,8 +60,50 @@ const SHA256_PATTERN = /^[0-9a-f]{64}$/;
57
60
  const RELEASE_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:/-]*$/;
58
61
  const MAX_IDENTIFIER_BYTES = 256;
59
62
  const MAX_FAILURE_MESSAGE_BYTES = 4_096;
63
+ const HEAD_ETAG_PATTERN = /^"sha256:([0-9a-f]{64})"$/;
64
+
65
+ /** @type {import("../plan-state.js").PlanStateFileSystem} */
66
+ const DEFAULT_FILE_SYSTEM = { lstatSync, readFileSync };
60
67
 
61
68
  export class CompilationNotPushedError extends Error {}
69
+ export class CompilationLocalStateError extends Error {}
70
+ export class CompilationLocalPlanChangedError extends Error {}
71
+
72
+ export class CompilationRequestOutcomeUnknownError extends Error {
73
+ /**
74
+ * @param {number | undefined} status
75
+ * @param {Record<string, unknown> | null} [response]
76
+ */
77
+ constructor(status, response = null) {
78
+ super("The compilation start request outcome is unknown.");
79
+ this.status = status;
80
+ this.response = response;
81
+ }
82
+ }
83
+
84
+ export class CompilationRetainedError extends Error {
85
+ /**
86
+ * @param {Error} error
87
+ * @param {CompilationResponse} current
88
+ */
89
+ constructor(error, current) {
90
+ super("The retained Compilation requires recovery.", { cause: error });
91
+ this.error = error;
92
+ this.current = current;
93
+ }
94
+ }
95
+
96
+ export class CompilationStartRejectedError extends Error {
97
+ /**
98
+ * @param {number} status
99
+ * @param {Record<string, unknown>} response
100
+ */
101
+ constructor(status, response) {
102
+ super("First Draft rejected the compilation start request.");
103
+ this.status = status;
104
+ this.response = response;
105
+ }
106
+ }
62
107
 
63
108
  export class CompilationStatusUnavailableError extends Error {
64
109
  /**
@@ -106,6 +151,22 @@ export class CompilationNotSucceededError extends Error {
106
151
  }
107
152
  }
108
153
 
154
+ export class CompilationFailedError extends Error {
155
+ /** @param {CompilationResponse} current */
156
+ constructor(current) {
157
+ super("The compilation failed.");
158
+ this.current = current;
159
+ }
160
+ }
161
+
162
+ export class CompilationCancelledError extends Error {
163
+ /** @param {CompilationResponse} current */
164
+ constructor(current) {
165
+ super("The compilation was cancelled.");
166
+ this.current = current;
167
+ }
168
+ }
169
+
109
170
  export class CompilationArtifactUnavailableError extends Error {
110
171
  /**
111
172
  * @param {number | undefined} status
@@ -290,6 +351,186 @@ export async function downloadCompilation({
290
351
  };
291
352
  }
292
353
 
354
+ /**
355
+ * @typedef {object} CurrentCompilationIdentity
356
+ * @property {string} projectId
357
+ * @property {number} graphVersion
358
+ * @property {string} headSourceSha256
359
+ * @property {string} analysisRunId
360
+ * @property {string} compilerRelease
361
+ * @property {{id: string, profile: string}} target
362
+ */
363
+
364
+ /**
365
+ * @typedef {object} CompileAndDownloadOptions
366
+ * @property {string} cwd
367
+ * @property {string} expectedEtag
368
+ * @property {CurrentCompilationIdentity} expected
369
+ * @property {string} output
370
+ * @property {typeof globalThis.fetch} [fetchFunction]
371
+ * @property {import("../plan-state.js").PlanStateFileSystem} [fileSystem]
372
+ * @property {(timeoutMs: number) => AbortSignal} [createRequestSignal]
373
+ * @property {(delayMs: number) => Promise<void>} [sleep]
374
+ * @property {() => number} [now]
375
+ * @property {(progress: import("../plan-compile-progress.js").PlanCompileProgress) => void} [onProgress]
376
+ */
377
+
378
+ /**
379
+ * Start one Compilation for the exact Plan and reviewed Analysis accepted by
380
+ * the current command, wait for that retained Compilation, and materialize its
381
+ * authenticated artifact into an absent destination.
382
+ *
383
+ * @param {CompileAndDownloadOptions} options
384
+ */
385
+ export async function compileAndDownload({
386
+ cwd,
387
+ expectedEtag,
388
+ expected,
389
+ output,
390
+ fetchFunction = globalThis.fetch,
391
+ fileSystem = DEFAULT_FILE_SYSTEM,
392
+ createRequestSignal = (timeoutMs) => AbortSignal.timeout(timeoutMs),
393
+ sleep = sleepFor,
394
+ now = Date.now,
395
+ onProgress = () => {},
396
+ }) {
397
+ const outputTarget = resolveOutputTarget({ cwd, output });
398
+ const context = readStartContext({
399
+ cwd,
400
+ expectedEtag,
401
+ expected,
402
+ fileSystem,
403
+ });
404
+ const deadline = now() + WAIT_TIMEOUT_MS;
405
+
406
+ onProgress({ phase: "compilation", status: "waiting" });
407
+ const initial = await startCompilation({
408
+ ...context,
409
+ expected,
410
+ fetchFunction,
411
+ createRequestSignal,
412
+ });
413
+ let current = initial;
414
+
415
+ try {
416
+ while (!TERMINAL_STATUSES.has(current.compilation.status)) {
417
+ const remaining = deadline - now();
418
+ if (remaining <= 0) throw new CompilationTimeoutError(current);
419
+
420
+ await sleep(Math.min(POLL_INTERVAL_MS, remaining));
421
+ if (now() >= deadline) throw new CompilationTimeoutError(current);
422
+
423
+ const next = await readCompilationStatus({
424
+ apiUrl: context.apiUrl,
425
+ projectId: context.projectId,
426
+ compilationId: initial.compilation.id,
427
+ fetchFunction,
428
+ createRequestSignal,
429
+ requestTimeout: Math.max(
430
+ 1,
431
+ Math.min(REQUEST_TIMEOUT_MS, deadline - now()),
432
+ ),
433
+ });
434
+ if (!sameCompilation(initial, next) || !validTransition(current, next)) {
435
+ throw new CompilationChangedError(next);
436
+ }
437
+ current = next;
438
+ }
439
+
440
+ if (current.compilation.status === "failed") {
441
+ throw new CompilationFailedError(current);
442
+ }
443
+ if (current.compilation.status === "cancelled") {
444
+ throw new CompilationCancelledError(current);
445
+ }
446
+
447
+ onProgress({ phase: "compilation", status: "succeeded" });
448
+ const metadata =
449
+ /** @type {{path: string, sha256: string, media_type: string, byte_size: number}} */ (
450
+ current.compilation.artifact
451
+ );
452
+ const source = await downloadArtifact({
453
+ apiUrl: context.apiUrl,
454
+ metadata,
455
+ fetchFunction,
456
+ createRequestSignal,
457
+ });
458
+ const artifact = parseCompilationArtifact(source, {
459
+ projectId: context.projectId,
460
+ compilationId: current.compilation.id,
461
+ graphVersion: current.compilation.graph_version,
462
+ headSourceSha256: current.compilation.head_source_sha256,
463
+ analysisRunId: current.compilation.analysis_run_id,
464
+ compilerRelease: current.compilation.compiler_release,
465
+ target: current.compilation.target,
466
+ });
467
+ const materialized = materializeCompilationArtifact(artifact, outputTarget);
468
+
469
+ return {
470
+ project: current.project,
471
+ compilation: current.compilation,
472
+ output: materialized,
473
+ };
474
+ } catch (error) {
475
+ if (requiresRetainedRecovery(error)) {
476
+ throw new CompilationRetainedError(error, current);
477
+ }
478
+
479
+ throw error;
480
+ }
481
+ }
482
+
483
+ /**
484
+ * @param {object} options
485
+ * @param {string} options.cwd
486
+ * @param {string} options.expectedEtag
487
+ * @param {CurrentCompilationIdentity} options.expected
488
+ * @param {import("../plan-state.js").PlanStateFileSystem} options.fileSystem
489
+ */
490
+ function readStartContext({ cwd, expectedEtag, expected, fileSystem }) {
491
+ const state = readPlanState({ cwd, fileSystem });
492
+ if (state.api_url === undefined || state.foundation_plan_etag === undefined) {
493
+ throw new CompilationNotPushedError(
494
+ "The local Foundation Plan has not been pushed.",
495
+ );
496
+ }
497
+ if (
498
+ state.project_id !== expected.projectId ||
499
+ state.foundation_plan_etag !== expectedEtag
500
+ ) {
501
+ throw new CompilationLocalPlanChangedError(
502
+ "Local Plan state changed after this command accepted its Plan.",
503
+ );
504
+ }
505
+
506
+ const match = HEAD_ETAG_PATTERN.exec(expectedEtag);
507
+ if (match === null) {
508
+ throw new CompilationLocalStateError(
509
+ "The saved Foundation Plan ETag cannot identify its accepted source.",
510
+ );
511
+ }
512
+ const headSourceSha256 = match[1] ?? "";
513
+ const planSource = readLocalFile(
514
+ path.join(cwd, ".firstdraft", "foundation-plan.json"),
515
+ MAX_PLAN_BYTES,
516
+ fileSystem,
517
+ );
518
+ if (
519
+ headSourceSha256 !== expected.headSourceSha256 ||
520
+ sha256(planSource) !== headSourceSha256
521
+ ) {
522
+ throw new CompilationLocalPlanChangedError(
523
+ "The local Foundation Plan differs from the accepted Plan.",
524
+ );
525
+ }
526
+
527
+ return {
528
+ apiUrl: state.api_url,
529
+ projectId: state.project_id,
530
+ etag: expectedEtag,
531
+ };
532
+ }
533
+
293
534
  /**
294
535
  * @param {object} options
295
536
  * @param {string} options.cwd
@@ -315,6 +556,73 @@ function readContext({ cwd, compilationId, fileSystem }) {
315
556
  };
316
557
  }
317
558
 
559
+ /**
560
+ * @param {object} options
561
+ * @param {string} options.apiUrl
562
+ * @param {string} options.projectId
563
+ * @param {string} options.etag
564
+ * @param {CurrentCompilationIdentity} options.expected
565
+ * @param {typeof globalThis.fetch} options.fetchFunction
566
+ * @param {(timeoutMs: number) => AbortSignal} options.createRequestSignal
567
+ */
568
+ async function startCompilation({
569
+ apiUrl,
570
+ projectId,
571
+ etag,
572
+ expected,
573
+ fetchFunction,
574
+ createRequestSignal,
575
+ }) {
576
+ const endpoint = new URL(`/v1/projects/${projectId}/compilations`, apiUrl);
577
+ let response;
578
+ let body;
579
+ try {
580
+ response = await sendRequest(fetchFunction, endpoint, {
581
+ method: "POST",
582
+ headers: {
583
+ Accept: "application/json, application/problem+json",
584
+ "If-Match": etag,
585
+ },
586
+ redirect: "error",
587
+ signal: createRequestSignal(REQUEST_TIMEOUT_MS),
588
+ });
589
+ body = await readResponseBody(response);
590
+ } catch (error) {
591
+ if (
592
+ error instanceof FirstDraftNetworkError ||
593
+ error instanceof FirstDraftProtocolError
594
+ ) {
595
+ throw new CompilationRequestOutcomeUnknownError(error.status);
596
+ }
597
+
598
+ throw error;
599
+ }
600
+
601
+ if (response.status !== 202) {
602
+ const problem = safeProblem(response, body);
603
+ if (response.ok || problem === null) {
604
+ throw new CompilationRequestOutcomeUnknownError(response.status);
605
+ }
606
+ if (response.status === 408 || response.status >= 500) {
607
+ throw new CompilationRequestOutcomeUnknownError(response.status, problem);
608
+ }
609
+
610
+ throw new CompilationStartRejectedError(response.status, problem);
611
+ }
612
+
613
+ const parsed = parseStartedCompilationResponse(body, projectId);
614
+ if (
615
+ responseMediaType(response) !== "application/json" ||
616
+ parsed === null ||
617
+ response.headers.get("location") !== parsed.compilation.status_path ||
618
+ !matchesExpectedCompilation(parsed, expected)
619
+ ) {
620
+ throw new CompilationRequestOutcomeUnknownError(response.status);
621
+ }
622
+
623
+ return parsed;
624
+ }
625
+
318
626
  /**
319
627
  * @param {object} options
320
628
  * @param {string} options.apiUrl
@@ -377,6 +685,40 @@ async function readCompilationStatus({
377
685
  return parsed;
378
686
  }
379
687
 
688
+ /**
689
+ * @param {unknown} value
690
+ * @param {string} projectId
691
+ * @returns {CompilationResponse | null}
692
+ */
693
+ function parseStartedCompilationResponse(value, projectId) {
694
+ if (
695
+ !hasExactKeySet(value, RESPONSE_KEYS) ||
696
+ !hasExactKeySet(value.compilation, COMPILATION_KEYS) ||
697
+ !isUuidV7(value.compilation.id)
698
+ ) {
699
+ return null;
700
+ }
701
+
702
+ return parseCompilationResponse(value, projectId, value.compilation.id);
703
+ }
704
+
705
+ /**
706
+ * @param {CompilationResponse} current
707
+ * @param {CurrentCompilationIdentity} expected
708
+ */
709
+ function matchesExpectedCompilation(current, expected) {
710
+ return (
711
+ current.project.id === expected.projectId &&
712
+ current.project.graph_version === expected.graphVersion &&
713
+ current.compilation.graph_version === expected.graphVersion &&
714
+ current.compilation.head_source_sha256 === expected.headSourceSha256 &&
715
+ current.compilation.analysis_run_id === expected.analysisRunId &&
716
+ current.compilation.compiler_release === expected.compilerRelease &&
717
+ current.compilation.target.id === expected.target.id &&
718
+ current.compilation.target.profile === expected.target.profile
719
+ );
720
+ }
721
+
380
722
  /**
381
723
  * @param {object} options
382
724
  * @param {string} options.apiUrl
@@ -700,6 +1042,18 @@ function validTransition(previous, current) {
700
1042
  );
701
1043
  }
702
1044
 
1045
+ /** @param {unknown} error */
1046
+ function requiresRetainedRecovery(error) {
1047
+ return (
1048
+ error instanceof CompilationStatusUnavailableError ||
1049
+ error instanceof CompilationStatusInvalidError ||
1050
+ error instanceof CompilationArtifactUnavailableError ||
1051
+ error instanceof CompilationArtifactResponseInvalidError ||
1052
+ error instanceof CompilationArtifactInvalidError ||
1053
+ error instanceof CompilationMaterializationError
1054
+ );
1055
+ }
1056
+
703
1057
  /** @param {Response} response @param {unknown} body */
704
1058
  function safeProblem(response, body) {
705
1059
  if (!isRecord(body) || !isProblemBody(response, body)) return null;
@@ -1,4 +1,6 @@
1
1
  import { publishPlan } from "./plan-publish.js";
2
+ import { compileAndDownload } from "./compilation.js";
3
+ import { resolveOutputTarget } from "../compilation-artifact.js";
2
4
  import {
3
5
  PlanPushNetworkError,
4
6
  PlanPushProtocolError,
@@ -90,6 +92,122 @@ export async function compilePlan({
90
92
  push = pushPlan,
91
93
  readStatus = readPlanStatus,
92
94
  publish = publishPlan,
95
+ }) {
96
+ const prepared = await preparePlan({
97
+ cwd,
98
+ apiUrl,
99
+ fetchFunction,
100
+ fileSystem,
101
+ createTemporaryId,
102
+ createRequestSignal,
103
+ analysisSleep,
104
+ analysisNow,
105
+ onProgress,
106
+ push,
107
+ readStatus,
108
+ });
109
+
110
+ return publish({
111
+ cwd,
112
+ fetchFunction,
113
+ fileSystem,
114
+ createRequestSignal,
115
+ sleep: publicationSleep,
116
+ now: publicationNow,
117
+ expectedEtag: prepared.pushed.etag,
118
+ onProgress,
119
+ });
120
+ }
121
+
122
+ /**
123
+ * @typedef {CompilePlanOptions & {
124
+ * output: string,
125
+ * compilationSleep?: (delayMs: number) => Promise<void>,
126
+ * compilationNow?: () => number,
127
+ * compile?: typeof compileAndDownload
128
+ * }} CompilePlanToDirectoryOptions
129
+ */
130
+
131
+ /**
132
+ * Submit and analyze the exact current local Plan, then start one direct
133
+ * Compilation and materialize its verified artifact into an absent directory.
134
+ * GitHub Publication remains the no-output mode owned by compilePlan.
135
+ *
136
+ * @param {CompilePlanToDirectoryOptions} options
137
+ */
138
+ export async function compilePlanToDirectory({
139
+ cwd,
140
+ output,
141
+ apiUrl,
142
+ fetchFunction,
143
+ fileSystem,
144
+ createTemporaryId,
145
+ createRequestSignal,
146
+ analysisSleep,
147
+ analysisNow,
148
+ compilationSleep,
149
+ compilationNow,
150
+ onProgress = () => {},
151
+ push = pushPlan,
152
+ readStatus = readPlanStatus,
153
+ compile = compileAndDownload,
154
+ }) {
155
+ // Reject an unavailable destination before the Plan push can mutate remote
156
+ // state. The Compilation boundary checks it again after Analysis in case the
157
+ // filesystem changes while this command is waiting.
158
+ resolveOutputTarget({ cwd, output });
159
+
160
+ const prepared = await preparePlan({
161
+ cwd,
162
+ apiUrl,
163
+ fetchFunction,
164
+ fileSystem,
165
+ createTemporaryId,
166
+ createRequestSignal,
167
+ analysisSleep,
168
+ analysisNow,
169
+ onProgress,
170
+ push,
171
+ readStatus,
172
+ });
173
+ const body = prepared.status.body;
174
+
175
+ return compile({
176
+ cwd,
177
+ expectedEtag: prepared.pushed.etag,
178
+ expected: {
179
+ projectId: body.project.id,
180
+ graphVersion: body.project.graph_version,
181
+ headSourceSha256: body.analysis.head_source_sha256,
182
+ analysisRunId: body.analysis.id,
183
+ compilerRelease: body.analysis.compiler_release,
184
+ target: body.analysis.target,
185
+ },
186
+ output,
187
+ fetchFunction,
188
+ fileSystem,
189
+ createRequestSignal,
190
+ sleep: compilationSleep,
191
+ now: compilationNow,
192
+ onProgress,
193
+ });
194
+ }
195
+
196
+ /**
197
+ * @param {Omit<CompilePlanOptions, "publicationSleep" | "publicationNow" | "publish">} options
198
+ */
199
+ async function preparePlan({
200
+ cwd,
201
+ apiUrl,
202
+ fetchFunction,
203
+ fileSystem,
204
+ createTemporaryId,
205
+ createRequestSignal,
206
+ analysisSleep,
207
+ analysisNow,
208
+ onProgress = () => {},
209
+ push = pushPlan,
210
+ readStatus = readPlanStatus,
93
211
  }) {
94
212
  const pushed = await push({
95
213
  cwd,
@@ -146,14 +264,5 @@ export async function compilePlan({
146
264
  }
147
265
  onProgress({ phase: "analysis", status: "valid" });
148
266
 
149
- return publish({
150
- cwd,
151
- fetchFunction,
152
- fileSystem,
153
- createRequestSignal,
154
- sleep: publicationSleep,
155
- now: publicationNow,
156
- expectedEtag: pushed.etag,
157
- onProgress,
158
- });
267
+ return { pushed, status };
159
268
  }
@@ -27,7 +27,7 @@ const PUBLICATION_MESSAGES = new Map([
27
27
  /**
28
28
  * @typedef {object} CompilationProgress
29
29
  * @property {"compilation"} phase
30
- * @property {"waiting"} status
30
+ * @property {"waiting" | "succeeded"} status
31
31
  */
32
32
 
33
33
  /**
@@ -77,7 +77,11 @@ export function createPlanCompileProgressReporter(writer) {
77
77
  }
78
78
 
79
79
  if (progress.phase === "compilation") {
80
- write("Compiling application...");
80
+ write(
81
+ progress.status === "waiting"
82
+ ? "Compiling application..."
83
+ : "Application compiled.",
84
+ );
81
85
  return;
82
86
  }
83
87