@firstdraft.com/cli 0.1.0-alpha.2 → 0.2.0

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.
@@ -69,11 +69,13 @@ const PUBLICATION_KEYS = [
69
69
  "created_at",
70
70
  "failure",
71
71
  "id",
72
+ "progress",
72
73
  "repository",
73
74
  "started_at",
74
75
  "status",
75
76
  ];
76
77
  const FAILURE_KEYS = ["code", "phase"];
78
+ const PROGRESS_KEYS = ["phase", "reason_code", "retry_at", "retry_count"];
77
79
  const REPOSITORY_KEYS = [
78
80
  "commit_sha",
79
81
  "default_branch",
@@ -85,6 +87,41 @@ const REPOSITORY_KEYS = [
85
87
  "tree_sha",
86
88
  ];
87
89
  const OWNER_KEYS = ["id", "login", "type"];
90
+ const PROGRESS_PHASES = new Set([
91
+ "compiling",
92
+ "preparing_repository",
93
+ "github_preflight",
94
+ "creating_repository",
95
+ "preparing_repository_reconciliation",
96
+ "reconciling_repository",
97
+ "preparing_artifact",
98
+ "publishing_artifact",
99
+ "preparing_publication_reconciliation",
100
+ "reconciling_publication",
101
+ "completed",
102
+ "failed",
103
+ "cancelled",
104
+ ]);
105
+ const PROGRESS_REASON_CODES = new Set([
106
+ "github.configuration_missing",
107
+ "github.oauth_unavailable",
108
+ "github.api_unavailable",
109
+ "github.reauthorization_required",
110
+ "github.account_mismatch",
111
+ "github.installation_unavailable",
112
+ "github.installation_not_ready",
113
+ "github.preflight_unavailable",
114
+ "github.preflight_unclassified",
115
+ "github.preflight_unavailable.configuration",
116
+ "github.preflight_unavailable.authorization",
117
+ "github.preflight_unavailable.repository_client",
118
+ "github.preflight_unavailable.artifact_preparation",
119
+ "github.preflight_unavailable.installation_token",
120
+ "github.preflight_unavailable.publication_preparation",
121
+ "github.preflight_unavailable.repository_ref_client",
122
+ ]);
123
+ const MAX_PROGRESS_RETRY_COUNT = 7;
124
+ const RETRY_TIMESTAMP_PATTERN = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{6}Z$/;
88
125
 
89
126
  /**
90
127
  * @typedef {object} PlanPublishFileSystem
@@ -183,7 +220,7 @@ export class PublicationCancelledError extends Error {
183
220
  * @typedef {object} PublicationResponse
184
221
  * @property {{id: string, graph_version: number, head_source_sha256: string}} project
185
222
  * @property {{id: string, analysis_run_id: string, graph_version: number, head_source_sha256: string, status: string, compiler_release: string, target: {id: string, profile: string}, artifact: null | {sha256: string, manifest_sha256: string, file_count: number}}} compilation
186
- * @property {{id: string, status: string, repository: null | {id: number, private: true, owner: {id: number, login: string, type: "User"}, full_name: string, default_branch: string, html_url: string, tree_sha: string | null, commit_sha: string | null}, failure: null | {phase: string, code: string}, created_at: string, started_at: string | null, completed_at: string | null}} publication
223
+ * @property {{id: string, status: string, repository: null | {id: number, private: true, owner: {id: number, login: string, type: "User"}, full_name: string, default_branch: string, html_url: string, tree_sha: string | null, commit_sha: string | null}, failure: null | {phase: string, code: string}, progress: {phase: string, retry_at: string | null, retry_count: number, reason_code: string | null}, created_at: string, started_at: string | null, completed_at: string | null}} publication
187
224
  */
188
225
 
189
226
  /**
@@ -195,6 +232,7 @@ export class PublicationCancelledError extends Error {
195
232
  * @property {(timeoutMs: number) => AbortSignal} [createRequestSignal]
196
233
  * @property {(delayMs: number) => Promise<void>} [sleep]
197
234
  * @property {() => number} [now]
235
+ * @property {(progress: import("../plan-compile-progress.js").PlanCompileProgress) => void} [onProgress]
198
236
  */
199
237
 
200
238
  /**
@@ -209,6 +247,7 @@ export async function publishPlan({
209
247
  createRequestSignal = (timeoutMs) => AbortSignal.timeout(timeoutMs),
210
248
  sleep = sleepFor,
211
249
  now = Date.now,
250
+ onProgress = () => {},
212
251
  }) {
213
252
  const state = readPlanState({ cwd, fileSystem });
214
253
  if (state.api_url === undefined || state.foundation_plan_etag === undefined) {
@@ -252,6 +291,8 @@ export async function publishPlan({
252
291
  const deadline = now() + WAIT_TIMEOUT_MS;
253
292
  let initial;
254
293
 
294
+ onProgress({ phase: "compilation", status: "waiting" });
295
+
255
296
  try {
256
297
  initial = await startPublication({
257
298
  endpoint,
@@ -309,6 +350,7 @@ export async function publishPlan({
309
350
  }
310
351
 
311
352
  let current = initial;
353
+ reportProgress(onProgress, current);
312
354
  while (!TERMINAL_PUBLICATION_STATUSES.has(current.publication.status)) {
313
355
  const remaining = deadline - now();
314
356
  if (remaining <= 0) throw new PublicationTimeoutError(current);
@@ -331,6 +373,7 @@ export async function publishPlan({
331
373
  throw new PublicationChangedError(current, next);
332
374
  }
333
375
  current = next;
376
+ reportProgress(onProgress, current);
334
377
  }
335
378
 
336
379
  if (
@@ -502,6 +545,7 @@ function parsePublicationResponse(value, projectId, headSourceSha256) {
502
545
  !PUBLICATION_STATUSES.has(publication.status) ||
503
546
  !isNullableRepository(publication.repository) ||
504
547
  !isNullableFailure(publication.failure) ||
548
+ !isProgress(publication.progress, publication.status) ||
505
549
  !isTimestamp(publication.created_at) ||
506
550
  !isNullableTimestamp(publication.started_at) ||
507
551
  !isNullableTimestamp(publication.completed_at) ||
@@ -525,6 +569,10 @@ function parsePublicationResponse(value, projectId, headSourceSha256) {
525
569
  const failure = /** @type {null | {phase: string, code: string}} */ (
526
570
  publication.failure
527
571
  );
572
+ const progress =
573
+ /** @type {{phase: string, retry_at: string | null, retry_count: number, reason_code: string | null}} */ (
574
+ publication.progress
575
+ );
528
576
 
529
577
  return {
530
578
  project: {
@@ -571,6 +619,12 @@ function parsePublicationResponse(value, projectId, headSourceSha256) {
571
619
  },
572
620
  failure:
573
621
  failure === null ? null : { phase: failure.phase, code: failure.code },
622
+ progress: {
623
+ phase: progress.phase,
624
+ retry_at: progress.retry_at,
625
+ retry_count: progress.retry_count,
626
+ reason_code: progress.reason_code,
627
+ },
574
628
  created_at: /** @type {string} */ (publication.created_at),
575
629
  started_at: /** @type {string | null} */ (publication.started_at),
576
630
  completed_at: /** @type {string | null} */ (publication.completed_at),
@@ -670,6 +724,82 @@ function isNullableFailure(value) {
670
724
  );
671
725
  }
672
726
 
727
+ /** @param {unknown} value @param {unknown} publicationStatus */
728
+ function isProgress(value, publicationStatus) {
729
+ if (
730
+ !hasExactKeySet(value, PROGRESS_KEYS) ||
731
+ typeof value.phase !== "string" ||
732
+ !PROGRESS_PHASES.has(value.phase) ||
733
+ !Number.isSafeInteger(value.retry_count) ||
734
+ Number(value.retry_count) < 0 ||
735
+ Number(value.retry_count) > MAX_PROGRESS_RETRY_COUNT ||
736
+ !isNullableRetryTimestamp(value.retry_at) ||
737
+ !(
738
+ value.reason_code === null ||
739
+ (typeof value.reason_code === "string" &&
740
+ PROGRESS_REASON_CODES.has(value.reason_code))
741
+ ) ||
742
+ !progressMatchesPublicationStatus(value.phase, publicationStatus)
743
+ ) {
744
+ return false;
745
+ }
746
+
747
+ if (value.phase !== "github_preflight") {
748
+ return (
749
+ value.retry_at === null &&
750
+ value.retry_count === 0 &&
751
+ value.reason_code === null
752
+ );
753
+ }
754
+
755
+ return value.retry_count === 0
756
+ ? value.retry_at === null && value.reason_code === null
757
+ : value.reason_code !== null;
758
+ }
759
+
760
+ /** @param {string} progressPhase @param {unknown} publicationStatus */
761
+ function progressMatchesPublicationStatus(progressPhase, publicationStatus) {
762
+ if (progressPhase === "compiling") return publicationStatus === "compiling";
763
+ if (progressPhase === "completed") return publicationStatus === "succeeded";
764
+ if (progressPhase === "failed") {
765
+ return (
766
+ publicationStatus === "failed" ||
767
+ publicationStatus === "repository_conflict"
768
+ );
769
+ }
770
+ if (progressPhase === "cancelled") return publicationStatus === "cancelled";
771
+ if (progressPhase === "github_preflight") {
772
+ return [
773
+ "provisioning_repository",
774
+ "repository_unknown",
775
+ "publishing",
776
+ "publication_unknown",
777
+ ].includes(String(publicationStatus));
778
+ }
779
+
780
+ const expectedStatus = new Map([
781
+ ["preparing_repository", "provisioning_repository"],
782
+ ["creating_repository", "provisioning_repository"],
783
+ ["preparing_repository_reconciliation", "repository_unknown"],
784
+ ["reconciling_repository", "repository_unknown"],
785
+ ["preparing_artifact", "publishing"],
786
+ ["publishing_artifact", "publishing"],
787
+ ["preparing_publication_reconciliation", "publication_unknown"],
788
+ ["reconciling_publication", "publication_unknown"],
789
+ ]).get(progressPhase);
790
+ return publicationStatus === expectedStatus;
791
+ }
792
+
793
+ /** @param {unknown} value */
794
+ function isNullableRetryTimestamp(value) {
795
+ return (
796
+ value === null ||
797
+ (typeof value === "string" &&
798
+ RETRY_TIMESTAMP_PATTERN.test(value) &&
799
+ isTimestamp(value))
800
+ );
801
+ }
802
+
673
803
  /** @param {unknown} value */
674
804
  function isNullableRepository(value) {
675
805
  if (value === null) return true;
@@ -817,6 +947,25 @@ function validRepositoryTransition(previous, current) {
817
947
  );
818
948
  }
819
949
 
950
+ /**
951
+ * @param {(progress: import("../plan-compile-progress.js").PlanCompileProgress) => void} onProgress
952
+ * @param {PublicationResponse} current
953
+ */
954
+ function reportProgress(onProgress, current) {
955
+ const progress = current.publication.progress;
956
+ onProgress({
957
+ phase: "publication",
958
+ compilationStatus:
959
+ /** @type {"queued" | "running" | "succeeded" | "failed" | "cancelled"} */ (
960
+ current.compilation.status
961
+ ),
962
+ publicationPhase: progress.phase,
963
+ retryAt: progress.retry_at,
964
+ retryCount: progress.retry_count,
965
+ reasonCode: progress.reason_code,
966
+ });
967
+ }
968
+
820
969
  /** @param {Response} response @param {unknown} body */
821
970
  function safeProblem(response, body) {
822
971
  if (!isProblemBody(response, body)) return null;
@@ -1,3 +1,4 @@
1
+ import { createHash } from "node:crypto";
1
2
  import { lstatSync, readFileSync } from "node:fs";
2
3
 
3
4
  import {
@@ -13,6 +14,9 @@ import { isUuidV7, readPlanState } from "../plan-state.js";
13
14
  const REQUEST_TIMEOUT_MS = 30_000;
14
15
  const WAIT_TIMEOUT_MS = 120_000;
15
16
  const POLL_INTERVAL_MS = 1_000;
17
+ export const MAX_PLAN_STATUS_RESPONSE_BYTES = 128 * 1024 * 1024;
18
+ const GAP_SET_FORMAT = "firstdraft.foundation-gaps/2";
19
+ const GAP_TEXT_MAX_BYTES = 64 * 1024;
16
20
  const TERMINAL_STATUSES = new Set([
17
21
  "valid",
18
22
  "issues_found",
@@ -23,14 +27,50 @@ const ALL_STATUSES = new Set(["processing", ...TERMINAL_STATUSES]);
23
27
  const RESPONSE_KEYS = ["analysis", "project"];
24
28
  const PROJECT_KEYS = ["graph_version", "id"];
25
29
  const ANALYSIS_KEYS = [
30
+ "id",
31
+ "graph_version",
32
+ "head_source_sha256",
26
33
  "analyzer_release",
27
- "completed_at",
34
+ "compiler_release",
35
+ "target",
36
+ "status",
28
37
  "diagnostics",
29
- "graph_version",
30
- "id",
38
+ "gap_set",
39
+ "gap_set_sha256",
31
40
  "started_at",
41
+ "completed_at",
42
+ ];
43
+ const TARGET_KEYS = ["id", "profile"];
44
+ const GAP_SET_KEYS = [
45
+ "format",
46
+ "source",
47
+ "project",
48
+ "analysis",
49
+ "compiler_release",
50
+ "target",
51
+ "gaps",
52
+ ];
53
+ const GAP_SOURCE_KEYS = ["sha256"];
54
+ const GAP_PROJECT_KEYS = ["id", "graph_version"];
55
+ const GAP_ANALYSIS_KEYS = ["release"];
56
+ const GAP_REQUIRED_ENTRY_KEYS = [
57
+ "classification",
58
+ "code",
59
+ "kind",
32
60
  "status",
61
+ "reason",
62
+ "consequence",
33
63
  ];
64
+ const GAP_OPTIONAL_ENTRY_KEYS = ["pointer", "readable_path", "cause"];
65
+ const GAP_CLASSIFICATIONS = new Set([
66
+ "service_support_gap",
67
+ "target_support_gap",
68
+ ]);
69
+ const GAP_STATUSES = new Set([
70
+ "skipped_at_import",
71
+ "not_generated",
72
+ "partially_generated",
73
+ ]);
34
74
  const DIAGNOSTIC_KEYS = [
35
75
  "code",
36
76
  "location",
@@ -40,6 +80,8 @@ const DIAGNOSTIC_KEYS = [
40
80
  "subject",
41
81
  "suggestions",
42
82
  ];
83
+ const SHA256_PATTERN = /^[0-9a-f]{64}$/;
84
+ const IDENTIFIER_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:/-]*$/;
43
85
 
44
86
  /**
45
87
  * @typedef {object} PlanStatusFileSystem
@@ -83,7 +125,7 @@ export class PlanStatusTimeoutError extends Error {
83
125
  /**
84
126
  * @typedef {object} AnalysisResponse
85
127
  * @property {{id: string, graph_version: number}} project
86
- * @property {{id: string, graph_version: number, analyzer_release: string, status: string, diagnostics: Record<string, unknown>[], started_at: string | null, completed_at: string | null}} analysis
128
+ * @property {{id: string, graph_version: number, head_source_sha256: string, analyzer_release: string, compiler_release: string, target: {id: string, profile: string}, status: string, diagnostics: Record<string, unknown>[], gap_set: Record<string, unknown> | null, gap_set_sha256: string | null, started_at: string | null, completed_at: string | null}} analysis
87
129
  */
88
130
 
89
131
  /** @typedef {{source_pointer: string} | {line: number, column: number}} SourceLocation */
@@ -152,7 +194,10 @@ export async function readPlanStatus({
152
194
  redirect: "error",
153
195
  signal: createRequestSignal(requestTimeout),
154
196
  });
155
- body = await readResponseBody(response);
197
+ body = await readResponseBody(
198
+ response,
199
+ response.status === 200 ? MAX_PLAN_STATUS_RESPONSE_BYTES : undefined,
200
+ );
156
201
  } catch (error) {
157
202
  if (
158
203
  error instanceof FirstDraftNetworkError &&
@@ -247,6 +292,7 @@ function parseAnalysisResponse(value, projectId) {
247
292
 
248
293
  const project = value.project;
249
294
  const analysis = value.analysis;
295
+ const target = isRecord(analysis) ? analysis.target : null;
250
296
  if (
251
297
  !hasRequiredKeys(project, PROJECT_KEYS) ||
252
298
  !hasRequiredKeys(analysis, ANALYSIS_KEYS) ||
@@ -255,13 +301,17 @@ function parseAnalysisResponse(value, projectId) {
255
301
  !isUuidV7(analysis.id) ||
256
302
  !isGraphVersion(analysis.graph_version) ||
257
303
  analysis.graph_version !== project.graph_version ||
258
- typeof analysis.analyzer_release !== "string" ||
259
- Buffer.byteLength(analysis.analyzer_release) === 0 ||
260
- Buffer.byteLength(analysis.analyzer_release) > 256 ||
304
+ typeof analysis.head_source_sha256 !== "string" ||
305
+ !SHA256_PATTERN.test(analysis.head_source_sha256) ||
306
+ !isIdentifier(analysis.analyzer_release) ||
307
+ !isIdentifier(analysis.compiler_release) ||
308
+ !isTarget(target) ||
261
309
  typeof analysis.status !== "string" ||
262
310
  !ALL_STATUSES.has(analysis.status) ||
263
311
  !Array.isArray(analysis.diagnostics) ||
264
312
  !analysis.diagnostics.every(isStructuredDiagnostic) ||
313
+ (analysis.gap_set_sha256 !== null &&
314
+ typeof analysis.gap_set_sha256 !== "string") ||
265
315
  !isNullableTimestamp(analysis.started_at) ||
266
316
  !isNullableTimestamp(analysis.completed_at)
267
317
  ) {
@@ -269,6 +319,16 @@ function parseAnalysisResponse(value, projectId) {
269
319
  }
270
320
 
271
321
  const terminal = TERMINAL_STATUSES.has(analysis.status);
322
+ const gapSet = parseGapSet(analysis.gap_set, {
323
+ projectId: project.id,
324
+ graphVersion: project.graph_version,
325
+ headSourceSha256: analysis.head_source_sha256,
326
+ analyzerRelease: analysis.analyzer_release,
327
+ compilerRelease: analysis.compiler_release,
328
+ target,
329
+ });
330
+ const gapSetSha256 = analysis.gap_set_sha256;
331
+ const hasGapSet = gapSet !== null && typeof gapSetSha256 === "string";
272
332
  if (
273
333
  (terminal && analysis.completed_at === null) ||
274
334
  (!terminal && analysis.completed_at !== null) ||
@@ -283,7 +343,13 @@ function parseAnalysisResponse(value, projectId) {
283
343
  (analysis.status === "issues_found" &&
284
344
  !analysis.diagnostics.some(
285
345
  (diagnostic) => diagnostic.severity === "error",
286
- ))
346
+ )) ||
347
+ (analysis.status === "valid") !== hasGapSet ||
348
+ (analysis.gap_set === null) !== (gapSetSha256 === null) ||
349
+ (analysis.gap_set !== null && gapSet === null) ||
350
+ (typeof gapSetSha256 === "string" &&
351
+ (!SHA256_PATTERN.test(gapSetSha256) ||
352
+ gapSetSha256 !== sha256(canonicalGapSetSource(gapSet))))
287
353
  ) {
288
354
  return null;
289
355
  }
@@ -296,15 +362,238 @@ function parseAnalysisResponse(value, projectId) {
296
362
  analysis: {
297
363
  id: analysis.id,
298
364
  graph_version: analysis.graph_version,
365
+ head_source_sha256: analysis.head_source_sha256,
299
366
  analyzer_release: analysis.analyzer_release,
367
+ compiler_release: analysis.compiler_release,
368
+ target: { id: target.id, profile: target.profile },
300
369
  status: analysis.status,
301
370
  diagnostics: analysis.diagnostics.map(copyDiagnostic),
371
+ gap_set: gapSet,
372
+ gap_set_sha256: gapSetSha256,
302
373
  started_at: analysis.started_at,
303
374
  completed_at: analysis.completed_at,
304
375
  },
305
376
  };
306
377
  }
307
378
 
379
+ /** @param {unknown} value @returns {value is string} */
380
+ function isIdentifier(value) {
381
+ return (
382
+ typeof value === "string" &&
383
+ Buffer.byteLength(value) > 0 &&
384
+ Buffer.byteLength(value) <= 256 &&
385
+ IDENTIFIER_PATTERN.test(value)
386
+ );
387
+ }
388
+
389
+ /**
390
+ * @param {unknown} value
391
+ * @returns {value is Record<string, unknown> & {id: string, profile: string}}
392
+ */
393
+ function isTarget(value) {
394
+ return (
395
+ hasExactKeys(value, TARGET_KEYS) &&
396
+ isIdentifier(value.id) &&
397
+ isIdentifier(value.profile)
398
+ );
399
+ }
400
+
401
+ /**
402
+ * @param {unknown} value
403
+ * @param {{projectId: string, graphVersion: number, headSourceSha256: string, analyzerRelease: string, compilerRelease: string, target: {id: string, profile: string}}} identity
404
+ * @returns {Record<string, unknown> | null}
405
+ */
406
+ function parseGapSet(value, identity) {
407
+ if (value === null) return null;
408
+ if (!hasExactKeys(value, GAP_SET_KEYS)) return null;
409
+
410
+ const source = value.source;
411
+ const project = value.project;
412
+ const analysis = value.analysis;
413
+ const target = value.target;
414
+ if (
415
+ value.format !== GAP_SET_FORMAT ||
416
+ !hasExactKeys(source, GAP_SOURCE_KEYS) ||
417
+ source.sha256 !== identity.headSourceSha256 ||
418
+ !hasExactKeys(project, GAP_PROJECT_KEYS) ||
419
+ project.id !== identity.projectId ||
420
+ project.graph_version !== identity.graphVersion ||
421
+ !hasExactKeys(analysis, GAP_ANALYSIS_KEYS) ||
422
+ analysis.release !== identity.analyzerRelease ||
423
+ value.compiler_release !== identity.compilerRelease ||
424
+ !hasExactKeys(target, TARGET_KEYS) ||
425
+ target.id !== identity.target.id ||
426
+ target.profile !== identity.target.profile ||
427
+ !Array.isArray(value.gaps) ||
428
+ !value.gaps.every(isGapEntry) ||
429
+ !gapsAreCanonicallyOrdered(value.gaps)
430
+ ) {
431
+ return null;
432
+ }
433
+
434
+ return {
435
+ format: GAP_SET_FORMAT,
436
+ source: { sha256: source.sha256 },
437
+ project: { id: project.id, graph_version: project.graph_version },
438
+ analysis: { release: analysis.release },
439
+ compiler_release: value.compiler_release,
440
+ target: { id: target.id, profile: target.profile },
441
+ gaps: value.gaps.map(copyGapEntry),
442
+ };
443
+ }
444
+
445
+ /** @param {Record<string, unknown>[]} gaps */
446
+ function gapsAreCanonicallyOrdered(gaps) {
447
+ return gaps.every((entry, index) => {
448
+ const previous = gaps[index - 1];
449
+ return previous === undefined || compareGapEntries(previous, entry) <= 0;
450
+ });
451
+ }
452
+
453
+ /** @param {Record<string, unknown>} left @param {Record<string, unknown>} right */
454
+ function compareGapEntries(left, right) {
455
+ return (
456
+ compareGapLocations(left, right) ||
457
+ compareUtf8(String(left.code), String(right.code)) ||
458
+ compareUtf8(String(left.kind), String(right.kind))
459
+ );
460
+ }
461
+
462
+ /** @param {Record<string, unknown>} left @param {Record<string, unknown>} right */
463
+ function compareGapLocations(left, right) {
464
+ const leftPointer = typeof left.pointer === "string";
465
+ const rightPointer = typeof right.pointer === "string";
466
+ if (leftPointer !== rightPointer) return leftPointer ? -1 : 1;
467
+ if (typeof left.pointer !== "string" || typeof right.pointer !== "string") {
468
+ return compareUtf8(
469
+ typeof left.readable_path === "string" ? left.readable_path : "",
470
+ typeof right.readable_path === "string" ? right.readable_path : "",
471
+ );
472
+ }
473
+
474
+ const leftTokens = pointerSortTokens(left.pointer);
475
+ const rightTokens = pointerSortTokens(right.pointer);
476
+ for (
477
+ let index = 0;
478
+ index < Math.min(leftTokens.length, rightTokens.length);
479
+ index += 1
480
+ ) {
481
+ const leftToken = leftTokens[index];
482
+ const rightToken = rightTokens[index];
483
+ if (leftToken === undefined || rightToken === undefined) {
484
+ throw new TypeError("GapSet pointer token comparison is inconsistent.");
485
+ }
486
+ const comparison = comparePointerTokens(leftToken, rightToken);
487
+ if (comparison !== 0) return comparison;
488
+ }
489
+ return leftTokens.length - rightTokens.length;
490
+ }
491
+
492
+ /** @param {string} pointer */
493
+ function pointerSortTokens(pointer) {
494
+ return pointer
495
+ .split("/")
496
+ .slice(1)
497
+ .map((token) => {
498
+ const decoded = token.replaceAll("~1", "/").replaceAll("~0", "~");
499
+ return /^(?:0|[1-9][0-9]*)$/.test(decoded)
500
+ ? { kind: 0, value: BigInt(decoded) }
501
+ : { kind: 1, value: decoded };
502
+ });
503
+ }
504
+
505
+ /**
506
+ * @param {{kind: number, value: bigint | string}} left
507
+ * @param {{kind: number, value: bigint | string}} right
508
+ */
509
+ function comparePointerTokens(left, right) {
510
+ if (left.kind !== right.kind) return left.kind - right.kind;
511
+ if (typeof left.value === "bigint" && typeof right.value === "bigint") {
512
+ return left.value < right.value ? -1 : left.value > right.value ? 1 : 0;
513
+ }
514
+ return compareUtf8(String(left.value), String(right.value));
515
+ }
516
+
517
+ /** @param {string} left @param {string} right */
518
+ function compareUtf8(left, right) {
519
+ return Buffer.compare(Buffer.from(left, "utf8"), Buffer.from(right, "utf8"));
520
+ }
521
+
522
+ /** @param {unknown} value */
523
+ function isGapEntry(value) {
524
+ if (!isRecord(value)) return false;
525
+ const keys = Object.keys(value);
526
+ if (
527
+ !GAP_REQUIRED_ENTRY_KEYS.every((key) => keys.includes(key)) ||
528
+ !keys.every(
529
+ (key) =>
530
+ GAP_REQUIRED_ENTRY_KEYS.includes(key) ||
531
+ GAP_OPTIONAL_ENTRY_KEYS.includes(key),
532
+ ) ||
533
+ !isGapText(value.classification) ||
534
+ !GAP_CLASSIFICATIONS.has(value.classification) ||
535
+ !isGapIdentifier(value.code) ||
536
+ !isGapIdentifier(value.kind) ||
537
+ !isGapText(value.status) ||
538
+ !GAP_STATUSES.has(value.status) ||
539
+ !isGapText(value.reason) ||
540
+ !isGapText(value.consequence) ||
541
+ (value.pointer !== undefined &&
542
+ (!isGapText(value.pointer) || !isJsonPointer(value.pointer))) ||
543
+ (value.readable_path !== undefined && !isGapText(value.readable_path)) ||
544
+ (value.cause !== undefined && !isGapText(value.cause))
545
+ ) {
546
+ return false;
547
+ }
548
+
549
+ return value.classification === "service_support_gap"
550
+ ? value.status === "skipped_at_import"
551
+ : value.status === "not_generated" ||
552
+ value.status === "partially_generated";
553
+ }
554
+
555
+ /** @param {unknown} value @returns {value is string} */
556
+ function isGapIdentifier(value) {
557
+ return isGapText(value) && IDENTIFIER_PATTERN.test(value);
558
+ }
559
+
560
+ /** @param {unknown} value @returns {value is string} */
561
+ function isGapText(value) {
562
+ return (
563
+ typeof value === "string" &&
564
+ Buffer.byteLength(value) > 0 &&
565
+ Buffer.byteLength(value) <= GAP_TEXT_MAX_BYTES &&
566
+ !value.includes("\0")
567
+ );
568
+ }
569
+
570
+ /** @param {Record<string, unknown>} entry */
571
+ function copyGapEntry(entry) {
572
+ return {
573
+ classification: entry.classification,
574
+ code: entry.code,
575
+ kind: entry.kind,
576
+ status: entry.status,
577
+ ...(entry.pointer === undefined ? {} : { pointer: entry.pointer }),
578
+ ...(entry.readable_path === undefined
579
+ ? {}
580
+ : { readable_path: entry.readable_path }),
581
+ reason: entry.reason,
582
+ consequence: entry.consequence,
583
+ ...(entry.cause === undefined ? {} : { cause: entry.cause }),
584
+ };
585
+ }
586
+
587
+ /** @param {Record<string, unknown> | null} gapSet */
588
+ function canonicalGapSetSource(gapSet) {
589
+ return Buffer.from(`${JSON.stringify(gapSet, null, 2)}\n`, "utf8");
590
+ }
591
+
592
+ /** @param {Buffer} source */
593
+ function sha256(source) {
594
+ return createHash("sha256").update(source).digest("hex");
595
+ }
596
+
308
597
  /** @param {unknown} value @returns {value is StructuredDiagnostic} */
309
598
  function isStructuredDiagnostic(value) {
310
599
  if (
@@ -474,6 +763,19 @@ function hasRequiredKeys(value, keys) {
474
763
  return isRecord(value) && keys.every((key) => hasOwn(value, key));
475
764
  }
476
765
 
766
+ /**
767
+ * @param {unknown} value
768
+ * @param {string[]} keys
769
+ * @returns {value is Record<string, unknown>}
770
+ */
771
+ function hasExactKeys(value, keys) {
772
+ return (
773
+ isRecord(value) &&
774
+ Object.keys(value).length === keys.length &&
775
+ keys.every((key) => hasOwn(value, key))
776
+ );
777
+ }
778
+
477
779
  /** @param {Record<string, unknown>} value @param {string} key */
478
780
  function hasOwn(value, key) {
479
781
  return Object.prototype.hasOwnProperty.call(value, key);
@@ -19,7 +19,7 @@ export const ARTIFACT_MEDIA_TYPE =
19
19
  "application/vnd.firstdraft.compilation-artifact+json";
20
20
  export const ARTIFACT_FORMAT = "firstdraft.compilation-artifact/1";
21
21
  export const FOUNDATION_PLAN_FORMAT = "firstdraft.foundation-plan.sketch/0.19";
22
- export const MAX_ARTIFACT_BYTES = 16 * 1024 * 1024;
22
+ export const MAX_ARTIFACT_BYTES = 128 * 1024 * 1024;
23
23
 
24
24
  const ARTIFACT_KEYS = ["format", "provenance", "manifest_sha256", "files"];
25
25
  const PROVENANCE_KEYS = [