@firstdraft.com/cli 0.2.1 → 0.2.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/docs/commands.md CHANGED
@@ -153,9 +153,91 @@ the accepted source SHA-256 from the saved ETag, hashes the current local bytes,
153
153
 
154
154
  ### Materialize a direct Compilation
155
155
 
156
- With `--output`, the CLI requires an explicit absent destination beneath an existing real directory. It validates
157
- that destination before pushing the Plan, checks it again after analysis, and never overwrites, merges into, or
158
- repairs an existing path.
156
+ With `--output`, the CLI accepts either an explicit absent destination beneath an existing real directory or a path
157
+ that resolves to the physical current directory. It validates either destination before pushing the Plan. An absent
158
+ destination is checked again after analysis; root adoption instead holds its owned lock and performs the exact
159
+ pre-move identity recheck described below. Other existing destinations remain invalid, so
160
+ `--output ./application` retains its absent-directory contract.
161
+
162
+ `--output .` is the noninteractive root-adoption mode. `./`, an absolute spelling of the current directory, and
163
+ another spelling that resolves to that same physical directory select the same mode. It works at any real current
164
+ directory that meets the preconditions below and does not recognize Drawing Board or another repository layout
165
+ specially. This first root-adoption contract supports POSIX filesystems; Windows retains absent-directory output
166
+ and refuses root adoption as `root_platform_unsupported`. Before starting Compilation, the CLI requires:
167
+
168
+ - the current directory to be a real, writable, non-filesystem-root directory;
169
+ - no existing top-level path whose portable, case-insensitive name is `design` or the reserved
170
+ `.firstdraft-root-output` transaction path;
171
+ - every top-level entry other than `.git` to be a regular file or real directory on the current directory's
172
+ filesystem. Interior symlinks, dependency trees, sockets, and nested repositories move opaquely with their
173
+ top-level directory; the CLI neither follows nor repairs them; and
174
+ - when the current directory is the root of a Git worktree, a clean tracked worktree and index with no unmerged
175
+ entries, sparse checkout, or in-progress merge, rebase, cherry-pick, or revert. Untracked and ignored design
176
+ material may remain present. Submodules and tracked `.gitmodules` files are refused in this first root-adoption
177
+ contract rather than moved with broken Git wiring. A directory nested inside a higher Git worktree is refused
178
+ rather than treated as non-Git. A valid top-level `.git` file for a linked worktree is retained like a `.git`
179
+ directory.
180
+
181
+ Git-backed root adoption invokes the installed Git executable explicitly. Read-only discovery uses
182
+ `git --no-optional-locks` with stable NUL-delimited porcelain so it does not refresh the index. Before remote work,
183
+ the CLI verifies in a temporary preview that every currently ignored entry remains ignored after its path and
184
+ applicable worktree `.gitignore` files move beneath `design`; repository-local and configured global exclusions are
185
+ both honored. A refusal is `invalid_output_path` with a machine-readable `reason` and happens before Plan push.
186
+
187
+ The CLI creates `.firstdraft-root-output` with exclusive creation during the pre-push output check and holds it
188
+ through analysis, Compilation, and materialization. That directory is both the single-writer lock and the owned
189
+ transaction journal, so a concurrent root adoption is refused before either command sends a request. Immediately
190
+ after acquiring it, the CLI captures every other top-level entry's exact name, entry type, device, and inode. After
191
+ staging the artifact and any replacement Git index, it rechecks that set immediately before moving anything. Size,
192
+ modification time, and contents are deliberately not part of this identity: interior changes are not recursively
193
+ inventoried, and a top-level directory moves intact at the transaction boundary. A replaced, added, or removed
194
+ top-level entry stops materialization. The reserved-path precondition ignores only the transaction directory
195
+ created and still held by this invocation.
196
+
197
+ `compilation download --output .` acquires the same lock before its first status request and holds it through
198
+ artifact download and materialization. Either command removes its own transaction directory on every ordinary exit
199
+ before the journal records an irreversible move or index installation. Its signal handlers do the same when Node
200
+ dispatches the signal before that boundary. A journal whose phase records no irreversible operation is likewise
201
+ safe to remove; the manual reconciliation rule below applies only after `root_rollback_incomplete`.
202
+
203
+ The complete generated artifact is written and verified inside that in-root transaction directory before any
204
+ existing path moves. Staging inside the destination makes every later rename same-filesystem even when the current
205
+ directory itself is a container mount point. The artifact may not own a top-level path whose portable,
206
+ case-insensitive name is `design` or `.firstdraft-root-output`; artifact validation already excludes `.git` at any
207
+ depth.
208
+
209
+ The transaction creates `./design` with mode `0755` on POSIX, moves every preexisting non-Git top-level entry under
210
+ it, keeps an existing top-level `.git` file or directory at the root, and installs the artifact's top-level entries
211
+ at the root. Immediately before each artifact entry is installed, its root destination must still be absent; an
212
+ unexpected entry stops the transaction and is never overwritten. If the root contains no entry other than `.git`,
213
+ it does not retain an empty `design` directory. A
214
+ nested mount that cannot travel with its top-level directory may make its rename fail; that is a transactional
215
+ failure, not permission to copy or traverse the mount.
216
+
217
+ For a Git root, the CLI first prepares a replacement index that stages each formerly tracked path at
218
+ `design/<old-path>` and stages every exact generated artifact path at the root. This handles overlapping names such
219
+ as `README.md` and `.gitignore` without leaving the old design blob indexed at a generated path. Previously
220
+ untracked and ignored paths are never added to the index. Preparing that index writes the generated blobs into the
221
+ Git object database; a rollback may therefore leave unreachable blobs for ordinary Git garbage collection, while
222
+ `HEAD`, refs, configuration, and history remain unchanged. After the worktree renames finish, the CLI installs the
223
+ prepared index through Git's actual index lock path and atomic lock-file commit protocol, including in a linked
224
+ worktree whose index is outside the adopted root. The transaction journal retains whether an index existed plus an
225
+ exact private copy, mode, and digest of its prior bytes until final verification succeeds. The preflighted ignore
226
+ protection is rechecked after the move. The caller should inspect and commit this staged root-adoption change before
227
+ using destructive worktree or index restoration commands. A non-Git root remains non-Git and is not initialized.
228
+
229
+ The journal is a versioned private JSON record plus owned staging files. It records the physical root and original
230
+ top-level identity set, the transaction phase, completed design and artifact renames, and, for Git, the resolved
231
+ index path and original and prepared index digests. Each irreversible phase is recorded before the next one starts.
232
+ On any failure after a move, index installation, or post-install verification, the CLI first restores the exact
233
+ prior index through the same Git lock boundary, then reverses artifact and design renames in journal order. A fully
234
+ successful rollback removes only the owned transaction. If rollback itself cannot finish,
235
+ `materialization_failed` reports `reason: "root_rollback_incomplete"` and includes
236
+ `recovery_path: ".firstdraft-root-output"`; it leaves the journal and owned copies in place rather than guessing.
237
+ Do not delete that directory or run Git restoration commands. Inspect the versioned journal, restore the listed
238
+ index and paths to its recorded original identities, verify that snapshot, and only then remove the transaction
239
+ directory. Another root adoption reports `root_busy` until that state is reconciled; a foreign preexisting directory
240
+ with the same reserved name reports `root_reserved_path`.
159
241
 
160
242
  After valid analysis, the CLI requests one Compilation for that exact reviewed Head and never starts GitHub
161
243
  Publication. It validates that the `202` response identifies the same Project, graph version, Head, Analysis,
@@ -166,10 +248,15 @@ and materialization failures retain the last validated Compilation projection so
166
248
  without starting duplicate work. Follow the [direct Compilation recovery procedure](errors.md#direct-compilation-recovery).
167
249
 
168
250
  Success writes one JSON object to stdout containing the validated Project, Compilation, and absolute output path.
169
- The installed directory contains exactly the artifact files and modes; the CLI does not add a Git repository, run a
170
- formatter, or repair generated source. When the output is nested inside another Git worktree, initialize the
171
- application as its own repository before running generated checks that inspect Git; otherwise Git resolves to the
172
- parent worktree. Progress on stderr reports analysis and Compilation only.
251
+ Root adoption additionally reports `root_adoption.design_path` (or `null` when no design directory was needed), its
252
+ top-level moved-entry count, whether a Git repository was preserved, and whether its index was replaced.
253
+ After final verification succeeds, the CLI removes its owned `.firstdraft-root-output` transaction directory.
254
+ An absent output directory contains exactly the artifact files and modes. Root adoption additionally contains the
255
+ preserved `design` directory and an existing root `.git`, when present; every artifact-owned path remains exact. The
256
+ CLI does not add a Git repository, run a formatter, or repair generated source. When an absent output is nested
257
+ inside another Git worktree, initialize the application as its own repository before running generated checks that
258
+ inspect Git; otherwise Git resolves to the parent worktree. Progress on stderr reports analysis and Compilation
259
+ only.
173
260
 
174
261
  ### Publish through GitHub
175
262
 
@@ -232,6 +319,16 @@ Materialize an already successful Compilation into an absent path:
232
319
  firstdraft compilation download 01900000-0000-7000-8000-000000000001 --output ../movie-catalog
233
320
  ```
234
321
 
322
+ The same command accepts `--output .` and applies the root-adoption transaction above. This is the recovery path
323
+ when a retained direct Compilation succeeded but an earlier root materialization failed _and fully rolled back_; it
324
+ never starts replacement work. An incomplete rollback leaves `.firstdraft-root-output` and requires journal
325
+ reconciliation before this command can run again.
326
+
327
+ Successful root adoption is intentionally one-way. The original `.firstdraft` authoring state moves under
328
+ `design/.firstdraft`; run later Plan commands from `design`, not from the generated application root. Compiling a
329
+ later Plan revision does not overwrite an already adopted root: choose a new absent output and deliberately
330
+ reconcile it with application work.
331
+
235
332
  The command validates the UUID and output path before network access, makes one status `GET`, requires `succeeded`,
236
333
  and makes one artifact `GET`. It never starts work or polls. Historical artifact validation uses the retained
237
334
  `compilation.head_source_sha256`, not the current local Plan or ETag, to pin the artifact's exact
package/docs/errors.md CHANGED
@@ -68,7 +68,13 @@ materialization failure envelopes include that last validated projection as `cur
68
68
  - after `artifact_unavailable`, wait if appropriate and use
69
69
  `firstdraft compilation download <current.compilation.id> --output <new-absent-path>`; and
70
70
  - after `materialization_failed`, repair the destination condition, then use the same lower-level download command
71
- with a new absent path.
71
+ with a new absent path. A root-output attempt whose transaction fully rolled back may instead retry that retained
72
+ download with `--output .`; `reason: "root_rollback_incomplete"` requires reconciliation of the retained
73
+ `.firstdraft-root-output` journal before another root attempt. Only that reason requires manual reconciliation:
74
+ do not delete its journal or run Git restoration commands; read its versioned record, restore the exact listed
75
+ index and path identities, verify its original snapshot, and then remove the transaction directory. A journal
76
+ whose phase records no irreversible operation is safe to remove. After `.firstdraft` has moved successfully under
77
+ `design`, run retained status and later Plan commands from `design`, not from the generated application root.
72
78
 
73
79
  After `compilation_wait_timed_out`, retained work may still continue. Use
74
80
  `firstdraft compilation status <current.compilation.id>` for one read-only status check; do not rerun
@@ -118,5 +124,13 @@ stopped without following the replacement.
118
124
  | `compilation status --wait` | `compilation_changed`, `compilation_wait_timed_out` | 1 | Retained identity/provenance changed or the wait ended. |
119
125
  | `compilation download` | `compilation_not_succeeded` | 1 | Status was not `succeeded`; no artifact request was made. |
120
126
  | Download commands | `artifact_unavailable`, `invalid_artifact` | 1 | Artifact transport or integrity validation failed; direct Compile post-start errors include `current`. |
121
- | Download commands | `invalid_output_path` | 2 | The destination was not an absent path beneath an existing real directory. |
122
- | Download commands | `materialization_failed` | 1 | The output raced or installation failed; direct Compile post-start errors include `current`. |
127
+ | Download commands | `invalid_output_path` | 2 | The absent destination or root-adoption preconditions failed; `reason` identifies the stable refusal. |
128
+ | Download commands | `materialization_failed` | 1 | The output changed or its transaction failed; `reason` identifies incomplete rollback when applicable. |
129
+
130
+ Root-output `invalid_output_path.reason` values are `destination_exists`, `root_not_real`, `root_not_writable`,
131
+ `root_platform_unsupported`, `root_reserved_path`, `root_entry_unsupported`, `root_enclosing_worktree`,
132
+ `root_git_unavailable`, `root_git_unsupported`, `root_git_dirty`, `root_ignore_not_preserved`, and `root_busy`. Git
133
+ refusing discovery, including a `safe.directory` refusal, is `root_git_unavailable`; a discovered but unsupported
134
+ Git shape such as a submodule is `root_git_unsupported`. Root-output `materialization_failed.reason` values are
135
+ `output_changed`, `root_artifact_collision`, `root_ignore_changed`, `root_transaction_failed`, and
136
+ `root_rollback_incomplete`.
@@ -38,3 +38,11 @@ source or documentation does not mutate either dist-tag.
38
38
  promoted stable release.
39
39
  - Package version `0.2.0` and protected tag `v0.2.0` are consumed and immutable. A backward-compatible addition to
40
40
  the `0.2.x` line therefore requires a higher patch version rather than reusing those identities.
41
+
42
+ ## 0.2.1 candidate publication
43
+
44
+ - On August 28, 2026, protected tag `v0.2.1` published ordinary version `0.2.1` under `next`; `latest` remained
45
+ `0.1.0`. The patch hardened direct Compilation recovery while preserving the `0.2.x` compatibility line.
46
+ - Package version `0.2.1` and protected tag `v0.2.1` are consumed and immutable. As observed on August 29, 2026,
47
+ current-directory root-output had integrated to `main` at `4352f64baf673ad93457e8bc84273e9d1d9a9501` (tree
48
+ `b43ba6de98e27328e548cc3410ba9f39dfa9fcee`) but was not part of those registry bytes.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@firstdraft.com/cli",
3
- "version": "0.2.1",
3
+ "version": "0.2.2",
4
4
  "description": "Command-line interface for First Draft",
5
5
  "license": "MIT",
6
6
  "type": "module",
package/src/cli.js CHANGED
@@ -181,11 +181,11 @@ const PLAN_COMPILE_HELP = `First Draft CLI
181
181
 
182
182
  Usage:
183
183
  firstdraft plan compile
184
- firstdraft plan compile --output <absent-directory>
184
+ firstdraft plan compile --output <absent-directory|.>
185
185
 
186
186
  Options:
187
- --output <absent-directory> Materialize the generated application here
188
- -h, --help Show help
187
+ --output <absent-directory|.> Materialize the generated application here
188
+ -h, --help Show help
189
189
 
190
190
  Environment:
191
191
  FIRSTDRAFT_API_TOKEN Authenticate API requests
@@ -195,7 +195,8 @@ The command submits the exact current whole-file Plan, waits for its analysis,
195
195
  and proceeds only when that analysis is valid. Without --output, it conditionally
196
196
  creates or replays the internal GitHub Publication lifecycle and prints the
197
197
  private repository URL. With --output, it starts one direct Compilation and
198
- atomically materializes the verified artifact into an absent directory without
198
+ atomically materializes the verified artifact into an absent directory, or
199
+ preserves existing root material under ./design when the output is ., without
199
200
  starting GitHub Publication. Progress is written to stderr.
200
201
  `;
201
202
 
@@ -232,18 +233,19 @@ cancelled terminal states are successful status reads.
232
233
  const COMPILATION_DOWNLOAD_HELP = `First Draft CLI
233
234
 
234
235
  Usage:
235
- firstdraft compilation download <compilation-id> --output <absent-path>
236
+ firstdraft compilation download <compilation-id> --output <absent-path|.>
236
237
 
237
238
  Options:
238
- --output <absent-path> Materialize the generated application here
239
- -h, --help Show help
239
+ --output <absent-path|.> Materialize the generated application here
240
+ -h, --help Show help
240
241
 
241
242
  Environment:
242
243
  FIRSTDRAFT_API_TOKEN Authenticate API requests
243
244
 
244
245
  The command reads the retained Compilation once, requires it to have
245
246
  succeeded, downloads and verifies its exact artifact once, and atomically
246
- renames the verified files into an absent output path. It never starts work.
247
+ materializes it into an absent output path or adopts the current directory
248
+ while preserving existing material under ./design. It never starts work.
247
249
  `;
248
250
 
249
251
  const PLAN_INIT_HELP = `First Draft CLI
@@ -386,7 +388,7 @@ const COMPILATION_ARTIFACT_UNAVAILABLE_DETAIL =
386
388
  const COMPILATION_ARTIFACT_INVALID_DETAIL =
387
389
  "The downloaded Compilation artifact did not satisfy the integrity contract. No files were materialized.";
388
390
  const COMPILATION_MATERIALIZATION_FAILED_DETAIL =
389
- "The validated Compilation artifact could not be materialized at the requested absent output path.";
391
+ "The validated Compilation artifact could not be materialized at the requested output path.";
390
392
  const PLAN_COMPILE_DIRECT_ARTIFACT_UNAVAILABLE_DETAIL =
391
393
  "Could not download the retained Compilation artifact. Use current.compilation.id with 'firstdraft compilation download'; do not start another Compilation.";
392
394
  const PLAN_COMPILE_DIRECT_ARTIFACT_INVALID_DETAIL =
@@ -394,7 +396,7 @@ const PLAN_COMPILE_DIRECT_ARTIFACT_INVALID_DETAIL =
394
396
  const PLAN_COMPILE_DIRECT_MATERIALIZATION_FAILED_DETAIL =
395
397
  "The retained Compilation artifact was validated but could not be materialized. Use current.compilation.id with 'firstdraft compilation download' after repairing the output path; do not start another Compilation.";
396
398
  const COMPILATION_INVALID_OUTPUT_PATH_DETAIL =
397
- "The compilation output path must be absent beneath an existing real directory. No network request was made.";
399
+ "The compilation output must be an absent path beneath an existing real directory or the eligible current directory.";
398
400
  const GENERATE_UUID_INVALID_ARGUMENTS_DETAIL =
399
401
  "Invalid arguments. Run 'firstdraft generate uuid --help' for usage.";
400
402
  const GENERATE_APPLICATION_KEY_INVALID_ARGUMENTS_DETAIL =
@@ -994,6 +996,7 @@ async function runCompilationDownload({
994
996
  writeJson(stderr, {
995
997
  error: "invalid_output_path",
996
998
  detail: COMPILATION_INVALID_OUTPUT_PATH_DETAIL,
999
+ ...(error.reason ? { reason: error.reason } : {}),
997
1000
  });
998
1001
  return 2;
999
1002
  }
@@ -1002,6 +1005,8 @@ async function runCompilationDownload({
1002
1005
  writeJson(stderr, {
1003
1006
  error: "materialization_failed",
1004
1007
  detail: COMPILATION_MATERIALIZATION_FAILED_DETAIL,
1008
+ ...(error.reason ? { reason: error.reason } : {}),
1009
+ ...(error.recoveryPath ? { recovery_path: error.recoveryPath } : {}),
1005
1010
  });
1006
1011
  return 1;
1007
1012
  }
@@ -1928,6 +1933,7 @@ function writePlanCompileError(writer, error) {
1928
1933
  writeJson(writer, {
1929
1934
  error: "invalid_output_path",
1930
1935
  detail: COMPILATION_INVALID_OUTPUT_PATH_DETAIL,
1936
+ ...(compilationError.reason ? { reason: compilationError.reason } : {}),
1931
1937
  });
1932
1938
  return 2;
1933
1939
  }
@@ -1936,6 +1942,10 @@ function writePlanCompileError(writer, error) {
1936
1942
  writeJson(writer, {
1937
1943
  error: "materialization_failed",
1938
1944
  detail: PLAN_COMPILE_DIRECT_MATERIALIZATION_FAILED_DETAIL,
1945
+ ...(compilationError.reason ? { reason: compilationError.reason } : {}),
1946
+ ...(compilationError.recoveryPath
1947
+ ? { recovery_path: compilationError.recoveryPath }
1948
+ : {}),
1939
1949
  ...(retainedCompilation ? { current: retainedCompilation } : {}),
1940
1950
  });
1941
1951
  return 1;
@@ -10,6 +10,8 @@ import {
10
10
  MAX_ARTIFACT_BYTES,
11
11
  materializeCompilationArtifact,
12
12
  parseCompilationArtifact,
13
+ prepareCompilationOutputTarget,
14
+ releaseCompilationOutputTarget,
13
15
  resolveOutputTarget,
14
16
  } from "../compilation-artifact.js";
15
17
  import {
@@ -312,43 +314,47 @@ export async function downloadCompilation({
312
314
  createRequestSignal = (timeoutMs) => AbortSignal.timeout(timeoutMs),
313
315
  }) {
314
316
  const context = readContext({ cwd, compilationId, fileSystem });
315
- const outputTarget = resolveOutputTarget({ cwd, output });
316
- const current = await readCompilationStatus({
317
- ...context,
318
- fetchFunction,
319
- createRequestSignal,
320
- requestTimeout: REQUEST_TIMEOUT_MS,
321
- });
322
- if (current.compilation.status !== "succeeded") {
323
- throw new CompilationNotSucceededError(current);
324
- }
317
+ const outputTarget = prepareCompilationOutputTarget({ cwd, output });
318
+ try {
319
+ const current = await readCompilationStatus({
320
+ ...context,
321
+ fetchFunction,
322
+ createRequestSignal,
323
+ requestTimeout: REQUEST_TIMEOUT_MS,
324
+ });
325
+ if (current.compilation.status !== "succeeded") {
326
+ throw new CompilationNotSucceededError(current);
327
+ }
325
328
 
326
- const metadata =
327
- /** @type {{path: string, sha256: string, media_type: string, byte_size: number}} */ (
328
- current.compilation.artifact
329
- );
330
- const source = await downloadArtifact({
331
- apiUrl: context.apiUrl,
332
- metadata,
333
- fetchFunction,
334
- createRequestSignal,
335
- });
336
- const artifact = parseCompilationArtifact(source, {
337
- projectId: context.projectId,
338
- compilationId: current.compilation.id,
339
- graphVersion: current.compilation.graph_version,
340
- headSourceSha256: current.compilation.head_source_sha256,
341
- analysisRunId: current.compilation.analysis_run_id,
342
- compilerRelease: current.compilation.compiler_release,
343
- target: current.compilation.target,
344
- });
345
- const materialized = materializeCompilationArtifact(artifact, outputTarget);
329
+ const metadata =
330
+ /** @type {{path: string, sha256: string, media_type: string, byte_size: number}} */ (
331
+ current.compilation.artifact
332
+ );
333
+ const source = await downloadArtifact({
334
+ apiUrl: context.apiUrl,
335
+ metadata,
336
+ fetchFunction,
337
+ createRequestSignal,
338
+ });
339
+ const artifact = parseCompilationArtifact(source, {
340
+ projectId: context.projectId,
341
+ compilationId: current.compilation.id,
342
+ graphVersion: current.compilation.graph_version,
343
+ headSourceSha256: current.compilation.head_source_sha256,
344
+ analysisRunId: current.compilation.analysis_run_id,
345
+ compilerRelease: current.compilation.compiler_release,
346
+ target: current.compilation.target,
347
+ });
348
+ const materialized = materializeCompilationArtifact(artifact, outputTarget);
346
349
 
347
- return {
348
- project: current.project,
349
- compilation: current.compilation,
350
- output: materialized,
351
- };
350
+ return {
351
+ project: current.project,
352
+ compilation: current.compilation,
353
+ output: materialized,
354
+ };
355
+ } finally {
356
+ releaseCompilationOutputTarget(outputTarget);
357
+ }
352
358
  }
353
359
 
354
360
  /**
@@ -367,6 +373,7 @@ export async function downloadCompilation({
367
373
  * @property {string} expectedEtag
368
374
  * @property {CurrentCompilationIdentity} expected
369
375
  * @property {string} output
376
+ * @property {string | import("../root-output.js").RootOutputTarget} [outputTarget]
370
377
  * @property {typeof globalThis.fetch} [fetchFunction]
371
378
  * @property {import("../plan-state.js").PlanStateFileSystem} [fileSystem]
372
379
  * @property {(timeoutMs: number) => AbortSignal} [createRequestSignal]
@@ -378,7 +385,8 @@ export async function downloadCompilation({
378
385
  /**
379
386
  * Start one Compilation for the exact Plan and reviewed Analysis accepted by
380
387
  * the current command, wait for that retained Compilation, and materialize its
381
- * authenticated artifact into an absent destination.
388
+ * authenticated artifact into an absent destination or the eligible current
389
+ * directory.
382
390
  *
383
391
  * @param {CompileAndDownloadOptions} options
384
392
  */
@@ -387,6 +395,7 @@ export async function compileAndDownload({
387
395
  expectedEtag,
388
396
  expected,
389
397
  output,
398
+ outputTarget: suppliedOutputTarget,
390
399
  fetchFunction = globalThis.fetch,
391
400
  fileSystem = DEFAULT_FILE_SYSTEM,
392
401
  createRequestSignal = (timeoutMs) => AbortSignal.timeout(timeoutMs),
@@ -394,89 +403,107 @@ export async function compileAndDownload({
394
403
  now = Date.now,
395
404
  onProgress = () => {},
396
405
  }) {
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
-
406
+ const ownsOutputTarget = suppliedOutputTarget === undefined;
407
+ const outputTarget =
408
+ suppliedOutputTarget ?? prepareCompilationOutputTarget({ cwd, output });
415
409
  try {
416
- while (!TERMINAL_STATUSES.has(current.compilation.status)) {
417
- const remaining = deadline - now();
418
- if (remaining <= 0) throw new CompilationTimeoutError(current);
410
+ const context = readStartContext({
411
+ cwd,
412
+ expectedEtag,
413
+ expected,
414
+ fileSystem,
415
+ });
416
+ if (
417
+ suppliedOutputTarget !== undefined &&
418
+ typeof outputTarget === "string"
419
+ ) {
420
+ resolveOutputTarget({ cwd, output });
421
+ }
422
+ const deadline = now() + WAIT_TIMEOUT_MS;
419
423
 
420
- await sleep(Math.min(POLL_INTERVAL_MS, remaining));
421
- if (now() >= deadline) throw new CompilationTimeoutError(current);
424
+ onProgress({ phase: "compilation", status: "waiting" });
425
+ const initial = await startCompilation({
426
+ ...context,
427
+ expected,
428
+ fetchFunction,
429
+ createRequestSignal,
430
+ });
431
+ let current = initial;
432
+
433
+ try {
434
+ while (!TERMINAL_STATUSES.has(current.compilation.status)) {
435
+ const remaining = deadline - now();
436
+ if (remaining <= 0) throw new CompilationTimeoutError(current);
437
+
438
+ await sleep(Math.min(POLL_INTERVAL_MS, remaining));
439
+ if (now() >= deadline) throw new CompilationTimeoutError(current);
440
+
441
+ const next = await readCompilationStatus({
442
+ apiUrl: context.apiUrl,
443
+ projectId: context.projectId,
444
+ compilationId: initial.compilation.id,
445
+ fetchFunction,
446
+ createRequestSignal,
447
+ requestTimeout: Math.max(
448
+ 1,
449
+ Math.min(REQUEST_TIMEOUT_MS, deadline - now()),
450
+ ),
451
+ });
452
+ if (
453
+ !sameCompilation(initial, next) ||
454
+ !validTransition(current, next)
455
+ ) {
456
+ throw new CompilationChangedError(next);
457
+ }
458
+ current = next;
459
+ }
460
+
461
+ if (current.compilation.status === "failed") {
462
+ throw new CompilationFailedError(current);
463
+ }
464
+ if (current.compilation.status === "cancelled") {
465
+ throw new CompilationCancelledError(current);
466
+ }
422
467
 
423
- const next = await readCompilationStatus({
468
+ onProgress({ phase: "compilation", status: "succeeded" });
469
+ const metadata =
470
+ /** @type {{path: string, sha256: string, media_type: string, byte_size: number}} */ (
471
+ current.compilation.artifact
472
+ );
473
+ const source = await downloadArtifact({
424
474
  apiUrl: context.apiUrl,
425
- projectId: context.projectId,
426
- compilationId: initial.compilation.id,
475
+ metadata,
427
476
  fetchFunction,
428
477
  createRequestSignal,
429
- requestTimeout: Math.max(
430
- 1,
431
- Math.min(REQUEST_TIMEOUT_MS, deadline - now()),
432
- ),
433
478
  });
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
479
+ const artifact = parseCompilationArtifact(source, {
480
+ projectId: context.projectId,
481
+ compilationId: current.compilation.id,
482
+ graphVersion: current.compilation.graph_version,
483
+ headSourceSha256: current.compilation.head_source_sha256,
484
+ analysisRunId: current.compilation.analysis_run_id,
485
+ compilerRelease: current.compilation.compiler_release,
486
+ target: current.compilation.target,
487
+ });
488
+ const materialized = materializeCompilationArtifact(
489
+ artifact,
490
+ outputTarget,
451
491
  );
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
492
 
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
- }
493
+ return {
494
+ project: current.project,
495
+ compilation: current.compilation,
496
+ output: materialized,
497
+ };
498
+ } catch (error) {
499
+ if (requiresRetainedRecovery(error)) {
500
+ throw new CompilationRetainedError(error, current);
501
+ }
478
502
 
479
- throw error;
503
+ throw error;
504
+ }
505
+ } finally {
506
+ if (ownsOutputTarget) releaseCompilationOutputTarget(outputTarget);
480
507
  }
481
508
  }
482
509