@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.
@@ -0,0 +1,994 @@
1
+ import { createHash } from "node:crypto";
2
+ import { lstatSync, readFileSync } from "node:fs";
3
+ import path from "node:path";
4
+
5
+ import { isAuthenticationProblem } from "../api-authentication.js";
6
+ import {
7
+ FirstDraftNetworkError,
8
+ FirstDraftProtocolError,
9
+ isProblemBody,
10
+ readResponseBody,
11
+ responseMediaType,
12
+ sendRequest,
13
+ } from "../api-response.js";
14
+ import { isUuidV7, readLocalFile, readPlanState } from "../plan-state.js";
15
+
16
+ const MAX_PLAN_BYTES = 1024 * 1024;
17
+ const REQUEST_TIMEOUT_MS = 30_000;
18
+ const WAIT_TIMEOUT_MS = 10 * 60_000;
19
+ const POLL_INTERVAL_MS = 1_000;
20
+ const MAX_IDENTIFIER_BYTES = 256;
21
+ const MAX_REPOSITORY_NAME_BYTES = 100;
22
+ const MAX_LOGIN_BYTES = 39;
23
+ const MAX_FAILURE_CODE_BYTES = 256;
24
+ const HEAD_ETAG_PATTERN = /^"sha256:([0-9a-f]{64})"$/;
25
+ const SHA256_PATTERN = /^[0-9a-f]{64}$/;
26
+ const GIT_SHA_PATTERN = /^[0-9a-f]{40}$/;
27
+ const RELEASE_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:/-]*$/;
28
+ const GITHUB_NAME_PATTERN = /^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/;
29
+ const COMPILATION_STATUSES = new Set([
30
+ "queued",
31
+ "running",
32
+ "succeeded",
33
+ "failed",
34
+ "cancelled",
35
+ ]);
36
+ const PUBLICATION_STATUSES = new Set([
37
+ "compiling",
38
+ "provisioning_repository",
39
+ "repository_unknown",
40
+ "publishing",
41
+ "publication_unknown",
42
+ "succeeded",
43
+ "repository_conflict",
44
+ "failed",
45
+ "cancelled",
46
+ ]);
47
+ const TERMINAL_PUBLICATION_STATUSES = new Set([
48
+ "succeeded",
49
+ "repository_conflict",
50
+ "failed",
51
+ "cancelled",
52
+ ]);
53
+ const RESPONSE_KEYS = ["compilation", "project", "publication"];
54
+ const PROJECT_KEYS = ["graph_version", "head_source_sha256", "id"];
55
+ const COMPILATION_KEYS = [
56
+ "analysis_run_id",
57
+ "artifact",
58
+ "compiler_release",
59
+ "graph_version",
60
+ "head_source_sha256",
61
+ "id",
62
+ "status",
63
+ "target",
64
+ ];
65
+ const TARGET_KEYS = ["id", "profile"];
66
+ const ARTIFACT_KEYS = ["file_count", "manifest_sha256", "sha256"];
67
+ const PUBLICATION_KEYS = [
68
+ "completed_at",
69
+ "created_at",
70
+ "failure",
71
+ "id",
72
+ "repository",
73
+ "started_at",
74
+ "status",
75
+ ];
76
+ const FAILURE_KEYS = ["code", "phase"];
77
+ const REPOSITORY_KEYS = [
78
+ "commit_sha",
79
+ "default_branch",
80
+ "full_name",
81
+ "html_url",
82
+ "id",
83
+ "owner",
84
+ "private",
85
+ "tree_sha",
86
+ ];
87
+ const OWNER_KEYS = ["id", "login", "type"];
88
+
89
+ /**
90
+ * @typedef {object} PlanPublishFileSystem
91
+ * @property {typeof lstatSync} lstatSync
92
+ * @property {typeof readFileSync} readFileSync
93
+ */
94
+
95
+ /** @type {PlanPublishFileSystem} */
96
+ const DEFAULT_FILE_SYSTEM = { lstatSync, readFileSync };
97
+
98
+ export class PublicationNotPushedError extends Error {}
99
+ export class PublicationLocalStateError extends Error {}
100
+ export class PublicationLocalPlanChangedError extends Error {}
101
+
102
+ export class PublicationRequestOutcomeUnknownError extends Error {
103
+ /**
104
+ * @param {number | undefined} status
105
+ * @param {Record<string, unknown> | null} [response]
106
+ */
107
+ constructor(status, response = null) {
108
+ super("The publication request outcome is unknown.");
109
+ this.status = status;
110
+ this.response = response;
111
+ }
112
+ }
113
+
114
+ export class PublicationStartRejectedError extends Error {
115
+ /**
116
+ * @param {number} status
117
+ * @param {Record<string, unknown>} response
118
+ */
119
+ constructor(status, response) {
120
+ super("First Draft rejected the publication request.");
121
+ this.status = status;
122
+ this.response = response;
123
+ }
124
+ }
125
+
126
+ export class PublicationStatusUnavailableError extends Error {
127
+ /**
128
+ * @param {number | undefined} status
129
+ * @param {Record<string, unknown> | null} [response]
130
+ */
131
+ constructor(status, response = null) {
132
+ super("The publication status is unavailable.");
133
+ this.status = status;
134
+ this.response = response;
135
+ }
136
+ }
137
+
138
+ export class PublicationStatusInvalidError extends Error {
139
+ /** @param {number} status */
140
+ constructor(status) {
141
+ super("The publication status response is invalid.");
142
+ this.status = status;
143
+ }
144
+ }
145
+
146
+ export class PublicationChangedError extends Error {
147
+ /**
148
+ * @param {PublicationResponse} current
149
+ * @param {PublicationResponse} rejected
150
+ */
151
+ constructor(current, rejected) {
152
+ super("The pinned publication changed while it was being polled.");
153
+ this.current = current;
154
+ this.rejected = rejected;
155
+ }
156
+ }
157
+
158
+ export class PublicationTimeoutError extends Error {
159
+ /** @param {PublicationResponse} current */
160
+ constructor(current) {
161
+ super("The publication did not finish before the wait deadline.");
162
+ this.current = current;
163
+ }
164
+ }
165
+
166
+ export class PublicationFailedError extends Error {
167
+ /** @param {PublicationResponse} current */
168
+ constructor(current) {
169
+ super("The publication failed.");
170
+ this.current = current;
171
+ }
172
+ }
173
+
174
+ export class PublicationCancelledError extends Error {
175
+ /** @param {PublicationResponse} current */
176
+ constructor(current) {
177
+ super("The publication was cancelled.");
178
+ this.current = current;
179
+ }
180
+ }
181
+
182
+ /**
183
+ * @typedef {object} PublicationResponse
184
+ * @property {{id: string, graph_version: number, head_source_sha256: string}} project
185
+ * @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
187
+ */
188
+
189
+ /**
190
+ * @typedef {object} PublishPlanOptions
191
+ * @property {string} cwd
192
+ * @property {string} [expectedEtag]
193
+ * @property {typeof globalThis.fetch} [fetchFunction]
194
+ * @property {PlanPublishFileSystem} [fileSystem]
195
+ * @property {(timeoutMs: number) => AbortSignal} [createRequestSignal]
196
+ * @property {(delayMs: number) => Promise<void>} [sleep]
197
+ * @property {() => number} [now]
198
+ */
199
+
200
+ /**
201
+ * @param {PublishPlanOptions} options
202
+ * @returns {Promise<PublicationResponse>}
203
+ */
204
+ export async function publishPlan({
205
+ cwd,
206
+ expectedEtag,
207
+ fetchFunction = globalThis.fetch,
208
+ fileSystem = DEFAULT_FILE_SYSTEM,
209
+ createRequestSignal = (timeoutMs) => AbortSignal.timeout(timeoutMs),
210
+ sleep = sleepFor,
211
+ now = Date.now,
212
+ }) {
213
+ const state = readPlanState({ cwd, fileSystem });
214
+ if (state.api_url === undefined || state.foundation_plan_etag === undefined) {
215
+ throw new PublicationNotPushedError(
216
+ "The local Foundation Plan has not been pushed.",
217
+ );
218
+ }
219
+
220
+ if (
221
+ expectedEtag !== undefined &&
222
+ state.foundation_plan_etag !== expectedEtag
223
+ ) {
224
+ throw new PublicationLocalPlanChangedError(
225
+ "Local Plan state changed after this command accepted its Plan.",
226
+ );
227
+ }
228
+
229
+ const publicationEtag = expectedEtag ?? state.foundation_plan_etag;
230
+ const match = HEAD_ETAG_PATTERN.exec(publicationEtag);
231
+ if (match === null) {
232
+ throw new PublicationLocalStateError(
233
+ "The saved Foundation Plan ETag cannot identify its accepted source.",
234
+ );
235
+ }
236
+ const headSourceSha256 = match[1] ?? "";
237
+ const planSource = readLocalFile(
238
+ path.join(cwd, ".firstdraft", "foundation-plan.json"),
239
+ MAX_PLAN_BYTES,
240
+ fileSystem,
241
+ );
242
+ if (sha256(planSource) !== headSourceSha256) {
243
+ throw new PublicationLocalPlanChangedError(
244
+ "The local Foundation Plan differs from the accepted Plan.",
245
+ );
246
+ }
247
+
248
+ const endpoint = new URL(
249
+ `/v1/projects/${state.project_id}/github-publication`,
250
+ state.api_url,
251
+ );
252
+ const deadline = now() + WAIT_TIMEOUT_MS;
253
+ let initial;
254
+
255
+ try {
256
+ initial = await startPublication({
257
+ endpoint,
258
+ projectId: state.project_id,
259
+ headSourceSha256,
260
+ etag: publicationEtag,
261
+ fetchFunction,
262
+ createRequestSignal,
263
+ });
264
+ } catch (error) {
265
+ if (!(error instanceof PublicationRequestOutcomeUnknownError)) throw error;
266
+
267
+ try {
268
+ initial = await readPublicationStatus({
269
+ endpoint,
270
+ projectId: state.project_id,
271
+ headSourceSha256,
272
+ fetchFunction,
273
+ createRequestSignal,
274
+ requestTimeout: Math.max(
275
+ 1,
276
+ Math.min(REQUEST_TIMEOUT_MS, deadline - now()),
277
+ ),
278
+ });
279
+ } catch (reconciliationError) {
280
+ if (
281
+ reconciliationError instanceof PublicationStatusUnavailableError &&
282
+ isAuthenticationProblem(
283
+ reconciliationError.status,
284
+ reconciliationError.response,
285
+ )
286
+ ) {
287
+ throw reconciliationError;
288
+ }
289
+ if (
290
+ reconciliationError instanceof PublicationStatusUnavailableError ||
291
+ reconciliationError instanceof PublicationStatusInvalidError
292
+ ) {
293
+ let status = reconciliationError.status ?? error.status;
294
+ let response = error.response;
295
+ if (
296
+ reconciliationError instanceof PublicationStatusUnavailableError &&
297
+ reconciliationError.response !== null
298
+ ) {
299
+ status = reconciliationError.status;
300
+ response = reconciliationError.response;
301
+ } else if (error.response !== null) {
302
+ status = error.status;
303
+ }
304
+ throw new PublicationRequestOutcomeUnknownError(status, response);
305
+ }
306
+
307
+ throw reconciliationError;
308
+ }
309
+ }
310
+
311
+ let current = initial;
312
+ while (!TERMINAL_PUBLICATION_STATUSES.has(current.publication.status)) {
313
+ const remaining = deadline - now();
314
+ if (remaining <= 0) throw new PublicationTimeoutError(current);
315
+
316
+ await sleep(Math.min(POLL_INTERVAL_MS, remaining));
317
+ if (now() >= deadline) throw new PublicationTimeoutError(current);
318
+
319
+ const next = await readPublicationStatus({
320
+ endpoint,
321
+ projectId: state.project_id,
322
+ headSourceSha256,
323
+ fetchFunction,
324
+ createRequestSignal,
325
+ requestTimeout: Math.max(
326
+ 1,
327
+ Math.min(REQUEST_TIMEOUT_MS, deadline - now()),
328
+ ),
329
+ });
330
+ if (!samePublication(initial, next) || !validTransition(current, next)) {
331
+ throw new PublicationChangedError(current, next);
332
+ }
333
+ current = next;
334
+ }
335
+
336
+ if (
337
+ current.publication.status === "failed" ||
338
+ current.publication.status === "repository_conflict"
339
+ ) {
340
+ throw new PublicationFailedError(current);
341
+ }
342
+ if (current.publication.status === "cancelled") {
343
+ throw new PublicationCancelledError(current);
344
+ }
345
+
346
+ return current;
347
+ }
348
+
349
+ /**
350
+ * @param {object} options
351
+ * @param {URL} options.endpoint
352
+ * @param {string} options.projectId
353
+ * @param {string} options.headSourceSha256
354
+ * @param {string} options.etag
355
+ * @param {typeof globalThis.fetch} options.fetchFunction
356
+ * @param {(timeoutMs: number) => AbortSignal} options.createRequestSignal
357
+ */
358
+ async function startPublication({
359
+ endpoint,
360
+ projectId,
361
+ headSourceSha256,
362
+ etag,
363
+ fetchFunction,
364
+ createRequestSignal,
365
+ }) {
366
+ let response;
367
+ let body;
368
+ try {
369
+ response = await sendRequest(fetchFunction, endpoint, {
370
+ method: "PUT",
371
+ headers: {
372
+ Accept: "application/json, application/problem+json",
373
+ "If-Match": etag,
374
+ },
375
+ redirect: "error",
376
+ signal: createRequestSignal(REQUEST_TIMEOUT_MS),
377
+ });
378
+ body = await readResponseBody(response);
379
+ } catch (error) {
380
+ if (
381
+ error instanceof FirstDraftNetworkError ||
382
+ error instanceof FirstDraftProtocolError
383
+ ) {
384
+ throw new PublicationRequestOutcomeUnknownError(error.status);
385
+ }
386
+
387
+ throw error;
388
+ }
389
+
390
+ if (response.status !== 200 && response.status !== 201) {
391
+ const problem = safeProblem(response, body);
392
+ if (response.ok || problem === null) {
393
+ throw new PublicationRequestOutcomeUnknownError(response.status);
394
+ }
395
+ if (response.status === 408 || response.status >= 500) {
396
+ throw new PublicationRequestOutcomeUnknownError(response.status, problem);
397
+ }
398
+
399
+ throw new PublicationStartRejectedError(response.status, problem);
400
+ }
401
+
402
+ const parsed = parsePublicationResponse(body, projectId, headSourceSha256);
403
+ if (responseMediaType(response) !== "application/json" || parsed === null) {
404
+ throw new PublicationRequestOutcomeUnknownError(response.status);
405
+ }
406
+
407
+ return parsed;
408
+ }
409
+
410
+ /**
411
+ * @param {object} options
412
+ * @param {URL} options.endpoint
413
+ * @param {string} options.projectId
414
+ * @param {string} options.headSourceSha256
415
+ * @param {typeof globalThis.fetch} options.fetchFunction
416
+ * @param {(timeoutMs: number) => AbortSignal} options.createRequestSignal
417
+ * @param {number} options.requestTimeout
418
+ */
419
+ async function readPublicationStatus({
420
+ endpoint,
421
+ projectId,
422
+ headSourceSha256,
423
+ fetchFunction,
424
+ createRequestSignal,
425
+ requestTimeout,
426
+ }) {
427
+ let response;
428
+ let body;
429
+ try {
430
+ response = await sendRequest(fetchFunction, endpoint, {
431
+ method: "GET",
432
+ headers: { Accept: "application/json, application/problem+json" },
433
+ redirect: "error",
434
+ signal: createRequestSignal(requestTimeout),
435
+ });
436
+ body = await readResponseBody(response);
437
+ } catch (error) {
438
+ if (error instanceof FirstDraftNetworkError) {
439
+ throw new PublicationStatusUnavailableError(error.status);
440
+ }
441
+ if (error instanceof FirstDraftProtocolError) {
442
+ throw new PublicationStatusInvalidError(error.status);
443
+ }
444
+
445
+ throw error;
446
+ }
447
+
448
+ if (response.status !== 200) {
449
+ if (!response.ok) {
450
+ throw new PublicationStatusUnavailableError(
451
+ response.status,
452
+ safeProblem(response, body),
453
+ );
454
+ }
455
+ throw new PublicationStatusInvalidError(response.status);
456
+ }
457
+
458
+ const parsed = parsePublicationResponse(body, projectId, headSourceSha256);
459
+ if (responseMediaType(response) !== "application/json" || parsed === null) {
460
+ throw new PublicationStatusInvalidError(response.status);
461
+ }
462
+
463
+ return parsed;
464
+ }
465
+
466
+ /**
467
+ * @param {unknown} value
468
+ * @param {string} projectId
469
+ * @param {string} headSourceSha256
470
+ * @returns {PublicationResponse | null}
471
+ */
472
+ function parsePublicationResponse(value, projectId, headSourceSha256) {
473
+ if (
474
+ !hasExactKeySet(value, RESPONSE_KEYS) ||
475
+ !hasExactKeySet(value.project, PROJECT_KEYS) ||
476
+ !hasExactKeySet(value.compilation, COMPILATION_KEYS) ||
477
+ !hasExactKeySet(value.publication, PUBLICATION_KEYS)
478
+ ) {
479
+ return null;
480
+ }
481
+
482
+ const project = value.project;
483
+ const compilation = value.compilation;
484
+ const publication = value.publication;
485
+ if (
486
+ project.id !== projectId ||
487
+ !isGraphVersion(project.graph_version) ||
488
+ project.head_source_sha256 !== headSourceSha256 ||
489
+ !isUuidV7(compilation.id) ||
490
+ !isUuidV7(compilation.analysis_run_id) ||
491
+ compilation.graph_version !== project.graph_version ||
492
+ compilation.head_source_sha256 !== headSourceSha256 ||
493
+ typeof compilation.status !== "string" ||
494
+ !COMPILATION_STATUSES.has(compilation.status) ||
495
+ !isRelease(compilation.compiler_release) ||
496
+ !hasExactKeySet(compilation.target, TARGET_KEYS) ||
497
+ !isRelease(compilation.target.id) ||
498
+ !isRelease(compilation.target.profile) ||
499
+ !isNullableArtifact(compilation.artifact) ||
500
+ !isUuidV7(publication.id) ||
501
+ typeof publication.status !== "string" ||
502
+ !PUBLICATION_STATUSES.has(publication.status) ||
503
+ !isNullableRepository(publication.repository) ||
504
+ !isNullableFailure(publication.failure) ||
505
+ !isTimestamp(publication.created_at) ||
506
+ !isNullableTimestamp(publication.started_at) ||
507
+ !isNullableTimestamp(publication.completed_at) ||
508
+ !hasValidCompilationShape(compilation) ||
509
+ !hasValidPublicationShape(compilation, publication)
510
+ ) {
511
+ return null;
512
+ }
513
+
514
+ const target = /** @type {{id: string, profile: string}} */ (
515
+ compilation.target
516
+ );
517
+ const artifact =
518
+ /** @type {null | {sha256: string, manifest_sha256: string, file_count: number}} */ (
519
+ compilation.artifact
520
+ );
521
+ const repository =
522
+ /** @type {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}} */ (
523
+ publication.repository
524
+ );
525
+ const failure = /** @type {null | {phase: string, code: string}} */ (
526
+ publication.failure
527
+ );
528
+
529
+ return {
530
+ project: {
531
+ id: project.id,
532
+ graph_version: /** @type {number} */ (project.graph_version),
533
+ head_source_sha256: project.head_source_sha256,
534
+ },
535
+ compilation: {
536
+ id: compilation.id,
537
+ analysis_run_id: compilation.analysis_run_id,
538
+ graph_version: /** @type {number} */ (compilation.graph_version),
539
+ head_source_sha256: compilation.head_source_sha256,
540
+ status: compilation.status,
541
+ compiler_release: /** @type {string} */ (compilation.compiler_release),
542
+ target: { id: target.id, profile: target.profile },
543
+ artifact:
544
+ artifact === null
545
+ ? null
546
+ : {
547
+ sha256: artifact.sha256,
548
+ manifest_sha256: artifact.manifest_sha256,
549
+ file_count: artifact.file_count,
550
+ },
551
+ },
552
+ publication: {
553
+ id: publication.id,
554
+ status: publication.status,
555
+ repository:
556
+ repository === null
557
+ ? null
558
+ : {
559
+ id: repository.id,
560
+ private: true,
561
+ owner: {
562
+ id: repository.owner.id,
563
+ login: repository.owner.login,
564
+ type: "User",
565
+ },
566
+ full_name: repository.full_name,
567
+ default_branch: repository.default_branch,
568
+ html_url: repository.html_url,
569
+ tree_sha: repository.tree_sha,
570
+ commit_sha: repository.commit_sha,
571
+ },
572
+ failure:
573
+ failure === null ? null : { phase: failure.phase, code: failure.code },
574
+ created_at: /** @type {string} */ (publication.created_at),
575
+ started_at: /** @type {string | null} */ (publication.started_at),
576
+ completed_at: /** @type {string | null} */ (publication.completed_at),
577
+ },
578
+ };
579
+ }
580
+
581
+ /** @param {Record<string, unknown>} compilation */
582
+ function hasValidCompilationShape(compilation) {
583
+ return compilation.status === "succeeded"
584
+ ? compilation.artifact !== null
585
+ : compilation.artifact === null;
586
+ }
587
+
588
+ /**
589
+ * @param {Record<string, unknown>} compilation
590
+ * @param {Record<string, unknown>} publication
591
+ */
592
+ function hasValidPublicationShape(compilation, publication) {
593
+ const status = String(publication.status);
594
+ const terminal = TERMINAL_PUBLICATION_STATUSES.has(status);
595
+ const failureExpected =
596
+ status === "failed" || status === "repository_conflict";
597
+ const created = timestampMilliseconds(String(publication.created_at));
598
+ const started =
599
+ publication.started_at === null
600
+ ? null
601
+ : timestampMilliseconds(String(publication.started_at));
602
+ const completed =
603
+ publication.completed_at === null
604
+ ? null
605
+ : timestampMilliseconds(String(publication.completed_at));
606
+ const repository = /** @type {Record<string, unknown> | null} */ (
607
+ publication.repository
608
+ );
609
+
610
+ if (
611
+ (terminal && completed === null) ||
612
+ (!terminal && completed !== null) ||
613
+ (failureExpected && publication.failure === null) ||
614
+ (!failureExpected && publication.failure !== null) ||
615
+ (status !== "compiling" &&
616
+ started === null &&
617
+ !(
618
+ (status === "failed" && compilation.status === "failed") ||
619
+ (status === "cancelled" && compilation.status === "cancelled")
620
+ )) ||
621
+ (started !== null && started < created) ||
622
+ (completed !== null && completed < created) ||
623
+ (started !== null && completed !== null && completed < started) ||
624
+ (status === "compiling" &&
625
+ !["queued", "running", "succeeded"].includes(
626
+ String(compilation.status),
627
+ )) ||
628
+ (status === "failed" &&
629
+ !["failed", "succeeded"].includes(String(compilation.status))) ||
630
+ (status === "cancelled" &&
631
+ !["cancelled", "succeeded"].includes(String(compilation.status))) ||
632
+ (!["compiling", "failed", "cancelled"].includes(status) &&
633
+ compilation.status !== "succeeded") ||
634
+ (["publishing", "publication_unknown", "succeeded"].includes(status) &&
635
+ repository === null)
636
+ ) {
637
+ return false;
638
+ }
639
+
640
+ if (status !== "succeeded") return true;
641
+
642
+ return (
643
+ repository !== null &&
644
+ typeof repository.tree_sha === "string" &&
645
+ typeof repository.commit_sha === "string"
646
+ );
647
+ }
648
+
649
+ /** @param {unknown} value */
650
+ function isNullableArtifact(value) {
651
+ return (
652
+ value === null ||
653
+ (hasExactKeySet(value, ARTIFACT_KEYS) &&
654
+ typeof value.sha256 === "string" &&
655
+ SHA256_PATTERN.test(value.sha256) &&
656
+ typeof value.manifest_sha256 === "string" &&
657
+ SHA256_PATTERN.test(value.manifest_sha256) &&
658
+ Number.isSafeInteger(value.file_count) &&
659
+ Number(value.file_count) >= 0)
660
+ );
661
+ }
662
+
663
+ /** @param {unknown} value */
664
+ function isNullableFailure(value) {
665
+ return (
666
+ value === null ||
667
+ (hasExactKeySet(value, FAILURE_KEYS) &&
668
+ isRelease(value.phase) &&
669
+ isFailureCode(value.code))
670
+ );
671
+ }
672
+
673
+ /** @param {unknown} value */
674
+ function isNullableRepository(value) {
675
+ if (value === null) return true;
676
+ if (
677
+ !hasExactKeySet(value, REPOSITORY_KEYS) ||
678
+ !isPositiveInteger(value.id) ||
679
+ value.private !== true ||
680
+ !hasExactKeySet(value.owner, OWNER_KEYS) ||
681
+ !isPositiveInteger(value.owner.id) ||
682
+ value.owner.type !== "User" ||
683
+ !isGithubName(value.owner.login, MAX_LOGIN_BYTES) ||
684
+ typeof value.full_name !== "string" ||
685
+ typeof value.default_branch !== "string" ||
686
+ typeof value.html_url !== "string" ||
687
+ !isNullableGitSha(value.tree_sha) ||
688
+ !isNullableGitSha(value.commit_sha) ||
689
+ (value.tree_sha === null) !== (value.commit_sha === null)
690
+ ) {
691
+ return false;
692
+ }
693
+
694
+ const prefix = `${value.owner.login}/`;
695
+ const repositoryName = value.full_name.startsWith(prefix)
696
+ ? value.full_name.slice(prefix.length)
697
+ : "";
698
+ return (
699
+ isGithubName(repositoryName, MAX_REPOSITORY_NAME_BYTES) &&
700
+ isGitBranch(value.default_branch) &&
701
+ value.html_url === `https://github.com/${value.full_name}`
702
+ );
703
+ }
704
+
705
+ /** @param {PublicationResponse} first @param {PublicationResponse} current */
706
+ function samePublication(first, current) {
707
+ return (
708
+ current.project.id === first.project.id &&
709
+ current.project.graph_version === first.project.graph_version &&
710
+ current.project.head_source_sha256 === first.project.head_source_sha256 &&
711
+ current.compilation.id === first.compilation.id &&
712
+ current.compilation.analysis_run_id === first.compilation.analysis_run_id &&
713
+ current.compilation.graph_version === first.compilation.graph_version &&
714
+ current.compilation.head_source_sha256 ===
715
+ first.compilation.head_source_sha256 &&
716
+ current.compilation.compiler_release ===
717
+ first.compilation.compiler_release &&
718
+ current.compilation.target.id === first.compilation.target.id &&
719
+ current.compilation.target.profile === first.compilation.target.profile &&
720
+ current.publication.id === first.publication.id &&
721
+ current.publication.created_at === first.publication.created_at
722
+ );
723
+ }
724
+
725
+ /** @param {PublicationResponse} previous @param {PublicationResponse} current */
726
+ function validTransition(previous, current) {
727
+ if (!validCompilationTransition(previous.compilation, current.compilation)) {
728
+ return false;
729
+ }
730
+ if (!validPublicationStatusTransition(previous, current)) return false;
731
+ if (!validRepositoryTransition(previous, current)) return false;
732
+
733
+ return (
734
+ (previous.publication.started_at === null ||
735
+ current.publication.started_at === previous.publication.started_at) &&
736
+ (previous.publication.completed_at === null ||
737
+ current.publication.completed_at === previous.publication.completed_at) &&
738
+ (previous.publication.failure === null ||
739
+ JSON.stringify(current.publication.failure) ===
740
+ JSON.stringify(previous.publication.failure))
741
+ );
742
+ }
743
+
744
+ /**
745
+ * @param {PublicationResponse["compilation"]} previous
746
+ * @param {PublicationResponse["compilation"]} current
747
+ */
748
+ function validCompilationTransition(previous, current) {
749
+ if (previous.status === current.status) {
750
+ return (
751
+ JSON.stringify(previous.artifact) === JSON.stringify(current.artifact)
752
+ );
753
+ }
754
+
755
+ if (previous.status === "queued") {
756
+ return ["running", "succeeded", "failed", "cancelled"].includes(
757
+ current.status,
758
+ );
759
+ }
760
+ return (
761
+ previous.status === "running" &&
762
+ ["succeeded", "failed", "cancelled"].includes(current.status)
763
+ );
764
+ }
765
+
766
+ /** @param {PublicationResponse} previous @param {PublicationResponse} current */
767
+ function validPublicationStatusTransition(previous, current) {
768
+ const from = previous.publication.status;
769
+ const to = current.publication.status;
770
+ if (from === to) {
771
+ return (
772
+ current.publication.started_at === previous.publication.started_at &&
773
+ current.publication.completed_at === previous.publication.completed_at &&
774
+ JSON.stringify(current.publication.failure) ===
775
+ JSON.stringify(previous.publication.failure)
776
+ );
777
+ }
778
+
779
+ if (
780
+ (from === "repository_unknown" && to === "provisioning_repository") ||
781
+ (from === "publication_unknown" && to === "publishing")
782
+ ) {
783
+ return false;
784
+ }
785
+
786
+ return publicationStage(to) >= publicationStage(from);
787
+ }
788
+
789
+ /** @param {string} status */
790
+ function publicationStage(status) {
791
+ if (status === "compiling") return 0;
792
+ if (status === "provisioning_repository" || status === "repository_unknown") {
793
+ return 1;
794
+ }
795
+ if (status === "publishing" || status === "publication_unknown") return 2;
796
+ return 3;
797
+ }
798
+
799
+ /** @param {PublicationResponse} previous @param {PublicationResponse} current */
800
+ function validRepositoryTransition(previous, current) {
801
+ const before = previous.publication.repository;
802
+ const after = current.publication.repository;
803
+ if (before === null) return true;
804
+ if (after === null) return false;
805
+
806
+ return (
807
+ after.id === before.id &&
808
+ after.private === before.private &&
809
+ after.owner.id === before.owner.id &&
810
+ after.owner.login === before.owner.login &&
811
+ after.owner.type === before.owner.type &&
812
+ after.full_name === before.full_name &&
813
+ after.default_branch === before.default_branch &&
814
+ after.html_url === before.html_url &&
815
+ (before.tree_sha === null || after.tree_sha === before.tree_sha) &&
816
+ (before.commit_sha === null || after.commit_sha === before.commit_sha)
817
+ );
818
+ }
819
+
820
+ /** @param {Response} response @param {unknown} body */
821
+ function safeProblem(response, body) {
822
+ if (!isProblemBody(response, body)) return null;
823
+ const problem = /** @type {Record<string, unknown>} */ (body);
824
+
825
+ return {
826
+ ...(problem.type === "about:blank" ? { type: problem.type } : {}),
827
+ title: problem.title,
828
+ status: problem.status,
829
+ code: problem.code,
830
+ detail: problem.detail,
831
+ };
832
+ }
833
+
834
+ /** @param {number} delayMs */
835
+ function sleepFor(delayMs) {
836
+ return new Promise((resolve) => {
837
+ setTimeout(resolve, delayMs);
838
+ });
839
+ }
840
+
841
+ /** @param {Buffer} value */
842
+ function sha256(value) {
843
+ return createHash("sha256").update(value).digest("hex");
844
+ }
845
+
846
+ /** @param {unknown} value */
847
+ function isRelease(value) {
848
+ return (
849
+ typeof value === "string" &&
850
+ Buffer.byteLength(value) <= MAX_IDENTIFIER_BYTES &&
851
+ RELEASE_PATTERN.test(value)
852
+ );
853
+ }
854
+
855
+ /** @param {unknown} value */
856
+ function isFailureCode(value) {
857
+ return (
858
+ typeof value === "string" &&
859
+ Buffer.byteLength(value) <= MAX_FAILURE_CODE_BYTES &&
860
+ RELEASE_PATTERN.test(value)
861
+ );
862
+ }
863
+
864
+ /** @param {unknown} value */
865
+ function isGraphVersion(value) {
866
+ return Number.isSafeInteger(value) && Number(value) >= 1;
867
+ }
868
+
869
+ /** @param {unknown} value */
870
+ function isPositiveInteger(value) {
871
+ return Number.isSafeInteger(value) && Number(value) > 0;
872
+ }
873
+
874
+ /** @param {unknown} value */
875
+ function isNullableGitSha(value) {
876
+ return (
877
+ value === null || (typeof value === "string" && GIT_SHA_PATTERN.test(value))
878
+ );
879
+ }
880
+
881
+ /** @param {unknown} value @param {number} maximumBytes */
882
+ function isGithubName(value, maximumBytes) {
883
+ return (
884
+ typeof value === "string" &&
885
+ Buffer.byteLength(value) <= maximumBytes &&
886
+ GITHUB_NAME_PATTERN.test(value)
887
+ );
888
+ }
889
+
890
+ /** @param {unknown} value */
891
+ function isGitBranch(value) {
892
+ return (
893
+ typeof value === "string" &&
894
+ Buffer.byteLength(value) <= MAX_IDENTIFIER_BYTES &&
895
+ value.length > 0 &&
896
+ !value.startsWith(".") &&
897
+ !value.endsWith(".") &&
898
+ !value.endsWith("/") &&
899
+ !value.endsWith(".lock") &&
900
+ !value.includes("..") &&
901
+ !value.includes("//") &&
902
+ ![...value].some((character) => {
903
+ const codePoint = character.codePointAt(0) ?? 0;
904
+ return codePoint <= 0x20 || "~^:?*[\\".includes(character);
905
+ })
906
+ );
907
+ }
908
+
909
+ /** @param {unknown} value */
910
+ function isNullableTimestamp(value) {
911
+ return value === null || isTimestamp(value);
912
+ }
913
+
914
+ /** @param {unknown} value */
915
+ function isTimestamp(value) {
916
+ return timestampParts(value) !== null;
917
+ }
918
+
919
+ /** @param {string} value */
920
+ function timestampMilliseconds(value) {
921
+ const parsed = Date.parse(value);
922
+ if (Number.isFinite(parsed)) return parsed;
923
+
924
+ return Date.parse(value.replace(/:60(?=[.,Zz+-])/, ":59")) + 1_000;
925
+ }
926
+
927
+ /** @param {unknown} value */
928
+ function timestampParts(value) {
929
+ if (typeof value !== "string") return null;
930
+
931
+ const match =
932
+ /^(\d{4})-(\d{2})-(\d{2})[Tt](\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:[Zz]|([+-])(\d{2}):(\d{2}))$/.exec(
933
+ value,
934
+ );
935
+ if (!match) return null;
936
+
937
+ const year = Number(match[1]);
938
+ const month = Number(match[2]);
939
+ const day = Number(match[3]);
940
+ const hour = Number(match[4]);
941
+ const minute = Number(match[5]);
942
+ const second = Number(match[6]);
943
+ const offsetHour = match[8] === undefined ? 0 : Number(match[8]);
944
+ const offsetMinute = match[9] === undefined ? 0 : Number(match[9]);
945
+ if (
946
+ month < 1 ||
947
+ month > 12 ||
948
+ day < 1 ||
949
+ day > daysInMonth(year, month) ||
950
+ hour > 23 ||
951
+ minute > 59 ||
952
+ second > 60 ||
953
+ (second === 60 && (hour !== 23 || minute !== 59)) ||
954
+ offsetHour > 23 ||
955
+ offsetMinute > 59
956
+ ) {
957
+ return null;
958
+ }
959
+
960
+ return true;
961
+ }
962
+
963
+ /** @param {number} year @param {number} month */
964
+ function daysInMonth(year, month) {
965
+ if (month === 2) {
966
+ return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0) ? 29 : 28;
967
+ }
968
+
969
+ return [4, 6, 9, 11].includes(month) ? 30 : 31;
970
+ }
971
+
972
+ /**
973
+ * @param {unknown} value
974
+ * @param {string[]} keys
975
+ * @returns {value is Record<string, unknown>}
976
+ */
977
+ function hasExactKeySet(value, keys) {
978
+ return (
979
+ isRecord(value) && arraysEqual(Object.keys(value).sort(), [...keys].sort())
980
+ );
981
+ }
982
+
983
+ /** @param {unknown} value @returns {value is Record<string, unknown>} */
984
+ function isRecord(value) {
985
+ return typeof value === "object" && value !== null && !Array.isArray(value);
986
+ }
987
+
988
+ /** @param {unknown[]} left @param {unknown[]} right */
989
+ function arraysEqual(left, right) {
990
+ return (
991
+ left.length === right.length &&
992
+ left.every((value, index) => value === right[index])
993
+ );
994
+ }