@tempo-ai/visual-review 0.0.138 → 0.0.139
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/README.md +34 -0
- package/dist/bin.js +3 -3
- package/dist/{chunk-HEFIVQ57.js → chunk-BTZJDIC4.js} +86 -15
- package/dist/chunk-BTZJDIC4.js.map +1 -0
- package/dist/chunk-H7MXR6QX.js +360 -0
- package/dist/chunk-H7MXR6QX.js.map +1 -0
- package/dist/{chunk-IID6AAUD.js → chunk-PI6TS733.js} +100 -34
- package/dist/chunk-PI6TS733.js.map +1 -0
- package/dist/chunk-TEVWNWZ6.js +376 -0
- package/dist/chunk-TEVWNWZ6.js.map +1 -0
- package/dist/{chunk-V4U3XAR5.js → chunk-VZDQYZCX.js} +115 -26
- package/dist/{chunk-V4U3XAR5.js.map → chunk-VZDQYZCX.js.map} +1 -1
- package/dist/{claim-WYI6X53C.js → claim-TARSUW6K.js} +3 -4
- package/dist/{cli-774NVTY7.js → cli-HWGJAH23.js} +4 -3
- package/dist/index.d.ts +66 -1
- package/dist/index.js +8 -6
- package/dist/{report-TDZOUKSY.js → report-XRYE2D5O.js} +4 -4
- package/package.json +3 -2
- package/templates/bitbucket-pipelines.yml +86 -0
- package/dist/chunk-CKMUCU6E.js +0 -181
- package/dist/chunk-CKMUCU6E.js.map +0 -1
- package/dist/chunk-HEFIVQ57.js.map +0 -1
- package/dist/chunk-IID6AAUD.js.map +0 -1
- package/dist/chunk-PDNKZ3PI.js +0 -38
- package/dist/chunk-PDNKZ3PI.js.map +0 -1
- /package/dist/{claim-WYI6X53C.js.map → claim-TARSUW6K.js.map} +0 -0
- /package/dist/{cli-774NVTY7.js.map → cli-HWGJAH23.js.map} +0 -0
- /package/dist/{report-TDZOUKSY.js.map → report-XRYE2D5O.js.map} +0 -0
package/README.md
CHANGED
|
@@ -35,6 +35,40 @@ The backend checks the signed PR identity against GitHub's current head and
|
|
|
35
35
|
reads skip declarations from the live PR. Declarations cannot be replayed
|
|
36
36
|
after removal, and reporting failures preserve an existing Tempo verdict.
|
|
37
37
|
|
|
38
|
+
## Bitbucket Pipelines
|
|
39
|
+
|
|
40
|
+
`templates/bitbucket-pipelines.yml` runs the same commands in Bitbucket
|
|
41
|
+
Pipelines. The CLI reads `BITBUCKET_*` instead of the GitHub context
|
|
42
|
+
(`src/ci-context.ts`) and differs in these ways:
|
|
43
|
+
|
|
44
|
+
- **Identity.** The step sets `oidc: true`. The CLI sends
|
|
45
|
+
`BITBUCKET_STEP_OIDC_TOKEN` together with the repo key it is used for.
|
|
46
|
+
That token carries only workspace, repository and pipeline UUIDs. Tempo
|
|
47
|
+
takes the commit, PR and branch from Bitbucket's pipeline record, read
|
|
48
|
+
through the repository grant that an org member authorized in Tempo. The
|
|
49
|
+
token cannot be re-minted, so `claim`, `capture` and `report` run in one
|
|
50
|
+
step and must finish within the token's lifetime.
|
|
51
|
+
- **Step state.** The commands share a small JSON file in the step's temp
|
|
52
|
+
dir instead of `GITHUB_ENV`/`GITHUB_OUTPUT`. It carries the capture owner
|
|
53
|
+
token and the run's status URL.
|
|
54
|
+
- **PR base.** `capture` fetches `origin/$BITBUCKET_PR_DESTINATION_BRANCH`
|
|
55
|
+
and then computes the merge-base.
|
|
56
|
+
- **Declarations.** Bitbucket has no labels, so there is no bypass. For a
|
|
57
|
+
PR, `capture` first asks Tempo whether the live PR description contains
|
|
58
|
+
`<!-- tempo-no-visual-change -->`. If it does, Tempo posts success and
|
|
59
|
+
nothing is captured.
|
|
60
|
+
- **Status and approvals.** Tempo posts the `visual-review` build status.
|
|
61
|
+
Approvals are scoped to the exact head commit, so a new push needs a new
|
|
62
|
+
approval.
|
|
63
|
+
- **Sticky comment.** `report` writes a markdown comment, authenticated with
|
|
64
|
+
`TEMPO_VISUAL_REVIEW_BITBUCKET_TOKEN`. This is a repository access token
|
|
65
|
+
with pull-request write access, stored as a secured repository variable.
|
|
66
|
+
Without it the comment is skipped.
|
|
67
|
+
- **Merge blocking.** Blocking merges needs the Tempo custom merge check
|
|
68
|
+
(`tempo-modules/bitbucket-merge-check`) on a plan with custom merge checks
|
|
69
|
+
(Premium). "Minimum successful builds" counts any build status, so it is
|
|
70
|
+
not an exact "Tempo approved" requirement.
|
|
71
|
+
|
|
38
72
|
## Releases and rollback
|
|
39
73
|
|
|
40
74
|
Every production release publishes this package at the app version under
|
package/dist/bin.js
CHANGED
|
@@ -7,11 +7,11 @@ async function main(argv = process.argv.slice(2)) {
|
|
|
7
7
|
const [command, ...commandArgs] = argv;
|
|
8
8
|
switch (command) {
|
|
9
9
|
case "capture":
|
|
10
|
-
return await (await import("./cli-
|
|
10
|
+
return await (await import("./cli-HWGJAH23.js")).main(commandArgs);
|
|
11
11
|
case "claim":
|
|
12
|
-
return await (await import("./claim-
|
|
12
|
+
return await (await import("./claim-TARSUW6K.js")).main(commandArgs);
|
|
13
13
|
case "report":
|
|
14
|
-
return await (await import("./report-
|
|
14
|
+
return await (await import("./report-XRYE2D5O.js")).main(commandArgs);
|
|
15
15
|
case "install-browsers":
|
|
16
16
|
return await (await import("./install-browsers-VPIMDVB6.js")).main(commandArgs);
|
|
17
17
|
default:
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import { createRequire as __tempoCreateRequire } from 'node:module'; const require = __tempoCreateRequire(import.meta.url);
|
|
2
|
-
import {
|
|
3
|
-
publishWorkflowStatus
|
|
4
|
-
} from "./chunk-PDNKZ3PI.js";
|
|
5
2
|
import {
|
|
6
3
|
DEFAULT_VISUAL_REVIEW_INGEST_URL,
|
|
7
|
-
|
|
8
|
-
|
|
4
|
+
detectCiContext,
|
|
5
|
+
publishWorkflowStatus,
|
|
6
|
+
readCiState,
|
|
7
|
+
writeCiState
|
|
8
|
+
} from "./chunk-H7MXR6QX.js";
|
|
9
9
|
|
|
10
10
|
// src/claim.ts
|
|
11
11
|
import { randomUUID } from "crypto";
|
|
@@ -32,7 +32,8 @@ async function postClaimRequest(options) {
|
|
|
32
32
|
method: "POST",
|
|
33
33
|
headers: {
|
|
34
34
|
"Content-Type": "application/json",
|
|
35
|
-
"x-visual-review-oidc": options.oidcToken
|
|
35
|
+
"x-visual-review-oidc": options.oidcToken,
|
|
36
|
+
...options.repoKeyHeader ? { "x-visual-review-repo-key": options.repoKeyHeader } : {}
|
|
36
37
|
},
|
|
37
38
|
body: JSON.stringify(options.body)
|
|
38
39
|
}
|
|
@@ -44,16 +45,34 @@ async function postClaimRequest(options) {
|
|
|
44
45
|
}
|
|
45
46
|
return await response.json();
|
|
46
47
|
}
|
|
48
|
+
async function claimAuth(options, fetchImpl) {
|
|
49
|
+
if (options.oidcToken !== void 0) {
|
|
50
|
+
return {
|
|
51
|
+
oidcToken: options.oidcToken,
|
|
52
|
+
repoKey: options.repoKey,
|
|
53
|
+
repoKeyHeader: options.repoKey
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
return {
|
|
57
|
+
oidcToken: await mintOidcToken({
|
|
58
|
+
oidcRequestUrl: options.oidcRequestUrl,
|
|
59
|
+
oidcRequestToken: options.oidcRequestToken,
|
|
60
|
+
fetchImpl
|
|
61
|
+
}),
|
|
62
|
+
repoKey: `github.com/${options.repository.toLowerCase()}`
|
|
63
|
+
};
|
|
64
|
+
}
|
|
47
65
|
async function announceCapture(options) {
|
|
48
66
|
const ownerToken = options.ownerToken ?? randomUUID();
|
|
49
67
|
const fetchImpl = options.fetchImpl ?? fetch;
|
|
50
|
-
const
|
|
68
|
+
const auth = await claimAuth(options, fetchImpl);
|
|
51
69
|
const result = await postClaimRequest({
|
|
52
70
|
ingestUrl: options.ingestUrl,
|
|
53
|
-
oidcToken,
|
|
71
|
+
oidcToken: auth.oidcToken,
|
|
72
|
+
repoKeyHeader: auth.repoKeyHeader,
|
|
54
73
|
path: "claim",
|
|
55
74
|
body: {
|
|
56
|
-
repoKey:
|
|
75
|
+
repoKey: auth.repoKey,
|
|
57
76
|
commitSha: options.headSha,
|
|
58
77
|
envFingerprint: PENDING_ENVIRONMENT,
|
|
59
78
|
ownerToken
|
|
@@ -68,13 +87,14 @@ async function announceCapture(options) {
|
|
|
68
87
|
}
|
|
69
88
|
async function releaseCaptureClaim(options) {
|
|
70
89
|
const fetchImpl = options.fetchImpl ?? fetch;
|
|
71
|
-
const
|
|
90
|
+
const auth = await claimAuth(options, fetchImpl);
|
|
72
91
|
const result = await postClaimRequest({
|
|
73
92
|
ingestUrl: options.ingestUrl,
|
|
74
|
-
oidcToken,
|
|
93
|
+
oidcToken: auth.oidcToken,
|
|
94
|
+
repoKeyHeader: auth.repoKeyHeader,
|
|
75
95
|
path: "fail",
|
|
76
96
|
body: {
|
|
77
|
-
repoKey:
|
|
97
|
+
repoKey: auth.repoKey,
|
|
78
98
|
commitSha: options.headSha,
|
|
79
99
|
ownerToken: options.ownerToken,
|
|
80
100
|
error: "workflow ended before the capture claim completed"
|
|
@@ -91,13 +111,14 @@ function parseArgs(argv) {
|
|
|
91
111
|
}
|
|
92
112
|
async function main(argv = process.argv.slice(2)) {
|
|
93
113
|
const { release } = parseArgs(argv);
|
|
94
|
-
const
|
|
114
|
+
const ci = detectCiContext();
|
|
115
|
+
if (ci.provider === "bitbucket") return await bitbucketMain(release, ci);
|
|
95
116
|
const required = {
|
|
96
117
|
ingestUrl: process.env.VISUAL_REVIEW_INGEST_URL ?? DEFAULT_VISUAL_REVIEW_INGEST_URL,
|
|
97
118
|
repository: process.env.GITHUB_REPOSITORY,
|
|
98
119
|
// GITHUB_SHA is a merge ref on pull_request runs; the event payload is
|
|
99
120
|
// the only standard environment source for the actual PR head SHA.
|
|
100
|
-
headSha: process.env.CAPTURE_HEAD_SHA ??
|
|
121
|
+
headSha: process.env.CAPTURE_HEAD_SHA ?? ci.headSha,
|
|
101
122
|
oidcRequestUrl: process.env.ACTIONS_ID_TOKEN_REQUEST_URL,
|
|
102
123
|
oidcRequestToken: process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN,
|
|
103
124
|
...release ? { ownerToken: process.env.VISUAL_REVIEW_CAPTURE_OWNER_TOKEN } : {}
|
|
@@ -147,10 +168,60 @@ async function main(argv = process.argv.slice(2)) {
|
|
|
147
168
|
return 0;
|
|
148
169
|
}
|
|
149
170
|
}
|
|
171
|
+
async function bitbucketMain(release, ci) {
|
|
172
|
+
const required = {
|
|
173
|
+
ingestUrl: process.env.VISUAL_REVIEW_INGEST_URL ?? DEFAULT_VISUAL_REVIEW_INGEST_URL,
|
|
174
|
+
repository: ci.repoFullName,
|
|
175
|
+
repoKey: ci.repoKey,
|
|
176
|
+
headSha: process.env.CAPTURE_HEAD_SHA ?? ci.headSha,
|
|
177
|
+
oidcToken: process.env.BITBUCKET_STEP_OIDC_TOKEN ?? process.env.VISUAL_REVIEW_OIDC_TOKEN,
|
|
178
|
+
...release ? {
|
|
179
|
+
ownerToken: process.env.VISUAL_REVIEW_CAPTURE_OWNER_TOKEN ?? readCiState().captureOwnerToken
|
|
180
|
+
} : {}
|
|
181
|
+
};
|
|
182
|
+
const missing = Object.entries(required).filter(([, value]) => !value).map(([name]) => name === "oidcToken" ? "BITBUCKET_STEP_OIDC_TOKEN (oidc: true)" : name);
|
|
183
|
+
if (missing.length > 0) {
|
|
184
|
+
console.warn(
|
|
185
|
+
`capture announcement skipped; missing ${missing.join(", ")} (capture will claim after setup)`
|
|
186
|
+
);
|
|
187
|
+
return 0;
|
|
188
|
+
}
|
|
189
|
+
const options = required;
|
|
190
|
+
if (!release && ci.trigger === "pr") {
|
|
191
|
+
try {
|
|
192
|
+
await publishWorkflowStatus("capture-started", options.headSha);
|
|
193
|
+
} catch (error) {
|
|
194
|
+
console.warn(
|
|
195
|
+
`pending status unavailable: ${error instanceof Error ? error.message : error}`
|
|
196
|
+
);
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
try {
|
|
200
|
+
if (release) {
|
|
201
|
+
const result2 = await releaseCaptureClaim({
|
|
202
|
+
...options,
|
|
203
|
+
ownerToken: options.ownerToken
|
|
204
|
+
});
|
|
205
|
+
console.log(
|
|
206
|
+
`capture claim release: ${result2.released ? "released" : "already complete or transferred"}`
|
|
207
|
+
);
|
|
208
|
+
return 0;
|
|
209
|
+
}
|
|
210
|
+
const result = await announceCapture(options);
|
|
211
|
+
console.log(`capture announcement: ${result.status}`);
|
|
212
|
+
if (result.ownerToken) writeCiState({ captureOwnerToken: result.ownerToken });
|
|
213
|
+
return 0;
|
|
214
|
+
} catch (error) {
|
|
215
|
+
console.warn(
|
|
216
|
+
`capture announcement failed; deferring to capture: ${error instanceof Error ? error.message : error}`
|
|
217
|
+
);
|
|
218
|
+
return 0;
|
|
219
|
+
}
|
|
220
|
+
}
|
|
150
221
|
|
|
151
222
|
export {
|
|
152
223
|
announceCapture,
|
|
153
224
|
releaseCaptureClaim,
|
|
154
225
|
main
|
|
155
226
|
};
|
|
156
|
-
//# sourceMappingURL=chunk-
|
|
227
|
+
//# sourceMappingURL=chunk-BTZJDIC4.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/claim.ts"],"sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport { appendFile } from \"node:fs/promises\";\n\nimport { detectCiContext, readCiState, writeCiState } from \"./ci-context\";\nimport { DEFAULT_VISUAL_REVIEW_INGEST_URL } from \"./constants\";\nimport { publishWorkflowStatus } from \"./workflow-status\";\n\nconst PENDING_ENVIRONMENT = \"pending\";\nconst OIDC_AUDIENCE = \"tempo-visual-review\";\n\n/** The slice of `fetch` the claim protocol uses. A plain `(url, init)` mock\n * satisfies it without impersonating the overloaded global. */\ntype FetchLike = (input: string, init?: RequestInit) => Promise<Response>;\n\nasync function mintOidcToken(options: {\n oidcRequestUrl: string;\n oidcRequestToken: string;\n fetchImpl: FetchLike;\n}): Promise<string> {\n const separator = options.oidcRequestUrl.includes(\"?\") ? \"&\" : \"?\";\n const tokenResponse = await options.fetchImpl(\n `${options.oidcRequestUrl}${separator}audience=${OIDC_AUDIENCE}`,\n { headers: { Authorization: `Bearer ${options.oidcRequestToken}` } },\n );\n if (!tokenResponse.ok) {\n throw new Error(`OIDC token request failed: ${tokenResponse.status}`);\n }\n const { value } = (await tokenResponse.json()) as { value?: string };\n if (!value) throw new Error(\"OIDC token response had no value\");\n return value;\n}\n\nasync function postClaimRequest(options: {\n ingestUrl: string;\n oidcToken: string;\n /** Bitbucket only: names the repo the step token is used for. */\n repoKeyHeader?: string;\n path: \"claim\" | \"fail\";\n body: Record<string, string>;\n fetchImpl: FetchLike;\n}): Promise<Record<string, unknown>> {\n const response = await options.fetchImpl(\n `${options.ingestUrl.replace(/\\/$/, \"\")}/visual-review/baseline/${options.path}`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-visual-review-oidc\": options.oidcToken,\n ...(options.repoKeyHeader\n ? { \"x-visual-review-repo-key\": options.repoKeyHeader }\n : {}),\n },\n body: JSON.stringify(options.body),\n },\n );\n if (!response.ok) {\n throw new Error(\n `capture ${options.path} failed: ${response.status} ${(await response.text()).slice(0, 200)}`,\n );\n }\n return (await response.json()) as Record<string, unknown>;\n}\n\n/**\n * How the claim protocol authenticates: GitHub mints a fresh id-token per\n * request; Bitbucket hands the step ONE token (`oidcToken`) that cannot be\n * re-minted, used together with the Bitbucket repo key it is for.\n */\ntype ClaimCredential =\n | { oidcRequestUrl: string; oidcRequestToken: string; oidcToken?: undefined; repoKey?: undefined }\n | { oidcToken: string; repoKey: string; oidcRequestUrl?: undefined; oidcRequestToken?: undefined };\n\nasync function claimAuth(\n options: ClaimCredential & { repository: string },\n fetchImpl: FetchLike,\n): Promise<{ oidcToken: string; repoKey: string; repoKeyHeader?: string }> {\n if (options.oidcToken !== undefined) {\n return {\n oidcToken: options.oidcToken,\n repoKey: options.repoKey,\n repoKeyHeader: options.repoKey,\n };\n }\n return {\n oidcToken: await mintOidcToken({\n oidcRequestUrl: options.oidcRequestUrl,\n oidcRequestToken: options.oidcRequestToken,\n fetchImpl,\n }),\n repoKey: `github.com/${options.repository.toLowerCase()}`,\n };\n}\n\nexport async function announceCapture(\n options: {\n ingestUrl: string;\n repository: string;\n headSha: string;\n ownerToken?: string;\n fetchImpl?: FetchLike;\n } & ClaimCredential,\n): Promise<{ ownerToken?: string; status?: string }> {\n const ownerToken = options.ownerToken ?? randomUUID();\n const fetchImpl = options.fetchImpl ?? fetch;\n const auth = await claimAuth(options, fetchImpl);\n const result = await postClaimRequest({\n ingestUrl: options.ingestUrl,\n oidcToken: auth.oidcToken,\n repoKeyHeader: auth.repoKeyHeader,\n path: \"claim\",\n body: {\n repoKey: auth.repoKey,\n commitSha: options.headSha,\n envFingerprint: PENDING_ENVIRONMENT,\n ownerToken,\n },\n fetchImpl,\n });\n const status = typeof result.status === \"string\" ? result.status : undefined;\n return {\n ownerToken: status === \"claimed\" ? ownerToken : undefined,\n status,\n };\n}\n\nexport async function releaseCaptureClaim(\n options: {\n ingestUrl: string;\n repository: string;\n headSha: string;\n ownerToken: string;\n fetchImpl?: FetchLike;\n } & ClaimCredential,\n): Promise<{ released?: boolean }> {\n const fetchImpl = options.fetchImpl ?? fetch;\n const auth = await claimAuth(options, fetchImpl);\n const result = await postClaimRequest({\n ingestUrl: options.ingestUrl,\n oidcToken: auth.oidcToken,\n repoKeyHeader: auth.repoKeyHeader,\n path: \"fail\",\n body: {\n repoKey: auth.repoKey,\n commitSha: options.headSha,\n ownerToken: options.ownerToken,\n error: \"workflow ended before the capture claim completed\",\n },\n fetchImpl,\n });\n return { released: result.released === true };\n}\n\nfunction parseArgs(argv: string[]) {\n if (argv.some((arg) => arg !== \"--release\")) {\n throw new Error(\"claim accepts only the optional --release flag\");\n }\n return { release: argv.includes(\"--release\") };\n}\n\nexport async function main(argv = process.argv.slice(2)): Promise<number> {\n const { release } = parseArgs(argv);\n const ci = detectCiContext();\n if (ci.provider === \"bitbucket\") return await bitbucketMain(release, ci);\n const required = {\n ingestUrl:\n process.env.VISUAL_REVIEW_INGEST_URL ?? DEFAULT_VISUAL_REVIEW_INGEST_URL,\n repository: process.env.GITHUB_REPOSITORY,\n // GITHUB_SHA is a merge ref on pull_request runs; the event payload is\n // the only standard environment source for the actual PR head SHA.\n headSha: process.env.CAPTURE_HEAD_SHA ?? ci.headSha,\n oidcRequestUrl: process.env.ACTIONS_ID_TOKEN_REQUEST_URL,\n oidcRequestToken: process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN,\n ...(release\n ? { ownerToken: process.env.VISUAL_REVIEW_CAPTURE_OWNER_TOKEN }\n : {}),\n };\n const missing = Object.entries(required)\n .filter(([, value]) => !value)\n .map(([name]) => name);\n if (missing.length > 0) {\n console.warn(\n `capture announcement skipped; missing ${missing.join(\", \")} (capture will claim after setup)`,\n );\n return 0;\n }\n\n if (\n !release &&\n process.env.GITHUB_EVENT_NAME === \"pull_request\" &&\n required.headSha\n ) {\n try {\n await publishWorkflowStatus(\"capture-started\", required.headSha);\n } catch (error) {\n // Capture still gets a chance to complete and publish its real gate.\n console.warn(\n `pending status unavailable: ${error instanceof Error ? error.message : error}`,\n );\n }\n }\n\n try {\n if (release) {\n const result = await releaseCaptureClaim(\n required as Parameters<typeof releaseCaptureClaim>[0],\n );\n console.log(\n `capture claim release: ${result.released ? \"released\" : \"already complete or transferred\"}`,\n );\n return 0;\n }\n const result = await announceCapture(\n required as Parameters<typeof announceCapture>[0],\n );\n console.log(`capture announcement: ${result.status}`);\n if (result.ownerToken && process.env.GITHUB_ENV) {\n await appendFile(\n process.env.GITHUB_ENV,\n `VISUAL_REVIEW_CAPTURE_OWNER_TOKEN=${result.ownerToken}\\n`,\n );\n }\n return 0;\n } catch (error) {\n // The capture command repeats the atomic claim with the real environment\n // fingerprint; an early announcement outage must not suppress coverage.\n console.warn(\n `capture announcement failed; deferring to capture: ${error instanceof Error ? error.message : error}`,\n );\n return 0;\n }\n}\n\n/**\n * Bitbucket Pipelines: the same announcement, authenticated with the step's\n * OIDC token. The owner token travels to `capture` and the after-script's\n * `claim --release` through the step state file (no GITHUB_ENV here).\n */\nasync function bitbucketMain(\n release: boolean,\n ci: ReturnType<typeof detectCiContext>,\n): Promise<number> {\n const required = {\n ingestUrl:\n process.env.VISUAL_REVIEW_INGEST_URL ?? DEFAULT_VISUAL_REVIEW_INGEST_URL,\n repository: ci.repoFullName,\n repoKey: ci.repoKey,\n headSha: process.env.CAPTURE_HEAD_SHA ?? ci.headSha,\n oidcToken:\n process.env.BITBUCKET_STEP_OIDC_TOKEN ??\n process.env.VISUAL_REVIEW_OIDC_TOKEN,\n ...(release\n ? {\n ownerToken:\n process.env.VISUAL_REVIEW_CAPTURE_OWNER_TOKEN ??\n readCiState().captureOwnerToken,\n }\n : {}),\n };\n const missing = Object.entries(required)\n .filter(([, value]) => !value)\n .map(([name]) => name === \"oidcToken\" ? \"BITBUCKET_STEP_OIDC_TOKEN (oidc: true)\" : name);\n if (missing.length > 0) {\n console.warn(\n `capture announcement skipped; missing ${missing.join(\", \")} (capture will claim after setup)`,\n );\n return 0;\n }\n const options = required as {\n ingestUrl: string;\n repository: string;\n repoKey: string;\n headSha: string;\n oidcToken: string;\n ownerToken?: string;\n };\n\n if (!release && ci.trigger === \"pr\") {\n try {\n await publishWorkflowStatus(\"capture-started\", options.headSha);\n } catch (error) {\n console.warn(\n `pending status unavailable: ${error instanceof Error ? error.message : error}`,\n );\n }\n }\n\n try {\n if (release) {\n const result = await releaseCaptureClaim({\n ...options,\n ownerToken: options.ownerToken!,\n });\n console.log(\n `capture claim release: ${result.released ? \"released\" : \"already complete or transferred\"}`,\n );\n return 0;\n }\n const result = await announceCapture(options);\n console.log(`capture announcement: ${result.status}`);\n if (result.ownerToken) writeCiState({ captureOwnerToken: result.ownerToken });\n return 0;\n } catch (error) {\n console.warn(\n `capture announcement failed; deferring to capture: ${error instanceof Error ? error.message : error}`,\n );\n return 0;\n }\n}\n"],"mappings":";;;;;;;;;;AAAA,SAAS,kBAAkB;AAC3B,SAAS,kBAAkB;AAM3B,IAAM,sBAAsB;AAC5B,IAAM,gBAAgB;AAMtB,eAAe,cAAc,SAIT;AAClB,QAAM,YAAY,QAAQ,eAAe,SAAS,G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AAAA,QACH,YAAY,QAAQ;AAAA,MACtB,CAAC;AACD,cAAQ;AAAA,QACN,0BAA0BA,QAAO,WAAW,aAAa,iCAAiC;AAAA,MAC5F;AACA,aAAO;AAAA,IACT;AACA,UAAM,SAAS,MAAM,gBAAgB,OAAO;AAC5C,YAAQ,IAAI,yBAAyB,OAAO,MAAM,EAAE;AACpD,QAAI,OAAO,WAAY,cAAa,EAAE,mBAAmB,OAAO,WAAW,CAAC;AAC5E,WAAO;AAAA,EACT,SAAS,OAAO;AACd,YAAQ;AAAA,MACN,sDAAsD,iBAAiB,QAAQ,MAAM,UAAU,KAAK;AAAA,IACtG;AACA,WAAO;AAAA,EACT;AACF;","names":["result"]}
|
|
@@ -0,0 +1,360 @@
|
|
|
1
|
+
import { createRequire as __tempoCreateRequire } from 'node:module'; const require = __tempoCreateRequire(import.meta.url);
|
|
2
|
+
|
|
3
|
+
// src/github-actions.ts
|
|
4
|
+
import { readFileSync } from "fs";
|
|
5
|
+
function readGithubActionsEvent(eventPath = process.env.GITHUB_EVENT_PATH) {
|
|
6
|
+
if (!eventPath) return null;
|
|
7
|
+
try {
|
|
8
|
+
return JSON.parse(readFileSync(eventPath, "utf8"));
|
|
9
|
+
} catch {
|
|
10
|
+
return null;
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
function githubPullRequestContext(event = readGithubActionsEvent()) {
|
|
14
|
+
const pullRequest = event?.pull_request;
|
|
15
|
+
if (!pullRequest) return null;
|
|
16
|
+
return {
|
|
17
|
+
number: pullRequest.number ?? event?.number,
|
|
18
|
+
headRef: pullRequest.head?.ref,
|
|
19
|
+
headSha: pullRequest.head?.sha,
|
|
20
|
+
baseRef: pullRequest.base?.ref,
|
|
21
|
+
baseSha: pullRequest.base?.sha
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
function visualReviewPrDeclaration(event = readGithubActionsEvent()) {
|
|
25
|
+
const pullRequest = event?.pull_request;
|
|
26
|
+
return {
|
|
27
|
+
bypass: pullRequest?.labels?.some(
|
|
28
|
+
(label) => label.name === "visual-review:bypass"
|
|
29
|
+
) ?? false,
|
|
30
|
+
noVisualChange: pullRequest?.body?.includes("<!-- tempo-no-visual-change -->") ?? false
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// src/ci-context.ts
|
|
35
|
+
import { mkdirSync, readFileSync as readFileSync2, writeFileSync } from "fs";
|
|
36
|
+
import { tmpdir } from "os";
|
|
37
|
+
import path from "path";
|
|
38
|
+
|
|
39
|
+
// ../git-provider/bitbucket/pipelines.ts
|
|
40
|
+
function readBitbucketPipelinesEnv(env) {
|
|
41
|
+
const repoFullName = env.BITBUCKET_REPO_FULL_NAME;
|
|
42
|
+
const commit = env.BITBUCKET_COMMIT;
|
|
43
|
+
if (!repoFullName || !commit) return null;
|
|
44
|
+
const prId = env.BITBUCKET_PR_ID && /^\d+$/.test(env.BITBUCKET_PR_ID) ? Number(env.BITBUCKET_PR_ID) : null;
|
|
45
|
+
return {
|
|
46
|
+
provider: "bitbucket",
|
|
47
|
+
repoFullName,
|
|
48
|
+
workspace: env.BITBUCKET_WORKSPACE ?? repoFullName.split("/")[0],
|
|
49
|
+
commit,
|
|
50
|
+
branch: env.BITBUCKET_BRANCH ?? null,
|
|
51
|
+
prId,
|
|
52
|
+
prDestinationBranch: env.BITBUCKET_PR_DESTINATION_BRANCH ?? null,
|
|
53
|
+
buildNumber: env.BITBUCKET_BUILD_NUMBER ?? null,
|
|
54
|
+
pipelineUuid: env.BITBUCKET_PIPELINE_UUID ?? null,
|
|
55
|
+
stepUuid: env.BITBUCKET_STEP_UUID ?? null,
|
|
56
|
+
oidcToken: env.BITBUCKET_STEP_OIDC_TOKEN ?? null
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// src/ci-context.ts
|
|
61
|
+
function detectCiContext(env = process.env, readEvent = () => env.GITHUB_EVENT_PATH ? readGithubActionsEvent(env.GITHUB_EVENT_PATH) : null) {
|
|
62
|
+
const bitbucket = env.GITHUB_ACTIONS === "true" ? null : readBitbucketPipelinesEnv(env);
|
|
63
|
+
if (bitbucket) {
|
|
64
|
+
const trigger = bitbucket.prId !== null ? "pr" : bitbucket.branch ? "main" : "manual";
|
|
65
|
+
return {
|
|
66
|
+
provider: "bitbucket",
|
|
67
|
+
isCi: true,
|
|
68
|
+
trigger,
|
|
69
|
+
prNumber: bitbucket.prId ?? void 0,
|
|
70
|
+
headSha: bitbucket.commit,
|
|
71
|
+
branch: bitbucket.branch ?? void 0,
|
|
72
|
+
baseRef: bitbucket.prDestinationBranch ?? void 0,
|
|
73
|
+
repoFullName: bitbucket.repoFullName,
|
|
74
|
+
repoKey: `bitbucket.org/${bitbucket.repoFullName}`.toLowerCase(),
|
|
75
|
+
declaration: { bypass: false, noVisualChange: false }
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
const event = readEvent();
|
|
79
|
+
const pullRequest = githubPullRequestContext(event);
|
|
80
|
+
const eventName = env.GITHUB_EVENT_NAME;
|
|
81
|
+
return {
|
|
82
|
+
provider: env.GITHUB_ACTIONS === "true" ? "github" : "local",
|
|
83
|
+
isCi: env.GITHUB_ACTIONS === "true",
|
|
84
|
+
trigger: eventName === "pull_request" ? "pr" : eventName === "push" ? "main" : "manual",
|
|
85
|
+
prNumber: pullRequest?.number,
|
|
86
|
+
headSha: pullRequest?.headSha ?? env.GITHUB_SHA,
|
|
87
|
+
branch: pullRequest?.headRef ?? env.GITHUB_HEAD_REF ?? env.GITHUB_REF_NAME,
|
|
88
|
+
baseRef: pullRequest?.baseRef ?? env.GITHUB_BASE_REF,
|
|
89
|
+
baseSha: pullRequest?.baseSha,
|
|
90
|
+
repoFullName: env.GITHUB_REPOSITORY,
|
|
91
|
+
declaration: visualReviewPrDeclaration(event)
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
function ciStatePath(env = process.env) {
|
|
95
|
+
if (env.TEMPO_VISUAL_REVIEW_STATE_FILE) return env.TEMPO_VISUAL_REVIEW_STATE_FILE;
|
|
96
|
+
const step = (env.BITBUCKET_STEP_UUID ?? "local").replace(/[^A-Za-z0-9-]/g, "");
|
|
97
|
+
return path.join(tmpdir(), "tempo-visual-review", `step-${step || "local"}.json`);
|
|
98
|
+
}
|
|
99
|
+
function readCiState(env = process.env) {
|
|
100
|
+
try {
|
|
101
|
+
return JSON.parse(readFileSync2(ciStatePath(env), "utf8"));
|
|
102
|
+
} catch {
|
|
103
|
+
return {};
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
function writeCiState(patch, env = process.env) {
|
|
107
|
+
const file = ciStatePath(env);
|
|
108
|
+
mkdirSync(path.dirname(file), { recursive: true });
|
|
109
|
+
writeFileSync(file, JSON.stringify({ ...readCiState(env), ...patch }));
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// src/constants.ts
|
|
113
|
+
var DEFAULT_VISUAL_REVIEW_INGEST_URL = "https://greedy-jackal-526.convex.site";
|
|
114
|
+
|
|
115
|
+
// src/http.ts
|
|
116
|
+
var ATTEMPTS = 3;
|
|
117
|
+
var REQUEST_TIMEOUT_MS = 3e4;
|
|
118
|
+
var TRANSIENT_STATUS = /* @__PURE__ */ new Set([408, 429, 500, 502, 503, 504]);
|
|
119
|
+
var TRANSIENT_CODE = /* @__PURE__ */ new Set([
|
|
120
|
+
"ECONNRESET",
|
|
121
|
+
"ECONNREFUSED",
|
|
122
|
+
"EPIPE",
|
|
123
|
+
"ETIMEDOUT",
|
|
124
|
+
"EAI_AGAIN",
|
|
125
|
+
"ENOTFOUND",
|
|
126
|
+
"UND_ERR_SOCKET",
|
|
127
|
+
"UND_ERR_CONNECT_TIMEOUT",
|
|
128
|
+
"UND_ERR_HEADERS_TIMEOUT",
|
|
129
|
+
"UND_ERR_BODY_TIMEOUT"
|
|
130
|
+
]);
|
|
131
|
+
function networkFailure(error) {
|
|
132
|
+
const codes = [];
|
|
133
|
+
let timeout = false;
|
|
134
|
+
let current = error;
|
|
135
|
+
for (let depth = 0; depth < 5 && current instanceof Error; depth++) {
|
|
136
|
+
timeout ||= current.name === "TimeoutError";
|
|
137
|
+
const code = current.code;
|
|
138
|
+
if (typeof code === "string" && /^[A-Z][A-Z0-9_]{1,50}$/.test(code))
|
|
139
|
+
codes.push(code);
|
|
140
|
+
current = current.cause;
|
|
141
|
+
}
|
|
142
|
+
return {
|
|
143
|
+
detail: timeout ? "request timed out" : codes.join(" / ") || "fetch failed",
|
|
144
|
+
retryable: timeout || codes.some((code) => TRANSIENT_CODE.has(code)) || codes.length === 0 && error instanceof TypeError && error.message === "fetch failed"
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
async function fetchWithRetry(url, init, operation, retryResponse = async () => true) {
|
|
148
|
+
const endpoint = new URL(url);
|
|
149
|
+
const label = `${operation} (${endpoint.origin}${endpoint.pathname})`;
|
|
150
|
+
for (let attempt = 1; attempt <= ATTEMPTS; attempt++) {
|
|
151
|
+
const request = typeof init === "function" ? await init() : init;
|
|
152
|
+
const controller = new AbortController();
|
|
153
|
+
const timeout = setTimeout(
|
|
154
|
+
() => controller.abort(new DOMException("Request timed out", "TimeoutError")),
|
|
155
|
+
REQUEST_TIMEOUT_MS
|
|
156
|
+
);
|
|
157
|
+
let response;
|
|
158
|
+
let failure;
|
|
159
|
+
let retryAfter = 0;
|
|
160
|
+
try {
|
|
161
|
+
response = await fetch(url, { ...request, signal: controller.signal });
|
|
162
|
+
const body = await response.arrayBuffer();
|
|
163
|
+
response = new Response(body.byteLength ? body : null, {
|
|
164
|
+
status: response.status,
|
|
165
|
+
statusText: response.statusText,
|
|
166
|
+
headers: response.headers
|
|
167
|
+
});
|
|
168
|
+
if (!TRANSIENT_STATUS.has(response.status) || !await retryResponse(response.clone()) || attempt === ATTEMPTS)
|
|
169
|
+
return response;
|
|
170
|
+
failure = `HTTP ${response.status}`;
|
|
171
|
+
const retryHeader = response.headers.get("retry-after");
|
|
172
|
+
if (retryHeader) {
|
|
173
|
+
const seconds = Number(retryHeader);
|
|
174
|
+
const requestedDelay = Number.isFinite(seconds) ? seconds * 1e3 : Date.parse(retryHeader) - Date.now();
|
|
175
|
+
if (requestedDelay > 5e3) return response;
|
|
176
|
+
if (Number.isFinite(requestedDelay))
|
|
177
|
+
retryAfter = Math.max(0, requestedDelay);
|
|
178
|
+
}
|
|
179
|
+
} catch (error) {
|
|
180
|
+
const info = networkFailure(
|
|
181
|
+
controller.signal.aborted ? controller.signal.reason : error
|
|
182
|
+
);
|
|
183
|
+
failure = info.detail;
|
|
184
|
+
if (!info.retryable || attempt === ATTEMPTS) {
|
|
185
|
+
throw new Error(
|
|
186
|
+
`${label} failed after ${attempt}/${ATTEMPTS} attempts: ${failure}`
|
|
187
|
+
);
|
|
188
|
+
}
|
|
189
|
+
} finally {
|
|
190
|
+
clearTimeout(timeout);
|
|
191
|
+
}
|
|
192
|
+
const delay = Math.max(retryAfter, 250 * 4 ** (attempt - 1));
|
|
193
|
+
console.warn(
|
|
194
|
+
`[visual-review] ${label}: ${failure}; retrying after ${delay}ms (attempt ${attempt + 1}/${ATTEMPTS})`
|
|
195
|
+
);
|
|
196
|
+
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
197
|
+
}
|
|
198
|
+
throw new Error(`${label}: retry budget exhausted`);
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
// src/oidc.ts
|
|
202
|
+
var OIDC_TOKEN_LIFETIME_MS = 5 * 6e4;
|
|
203
|
+
var OIDC_TOKEN_REFRESH_MARGIN_MS = 6e4;
|
|
204
|
+
var VISUAL_REVIEW_OIDC_AUDIENCE = "tempo-visual-review";
|
|
205
|
+
function githubOidcProvider(requestUrl, requestToken) {
|
|
206
|
+
let cached = null;
|
|
207
|
+
let pending = null;
|
|
208
|
+
const mint = async () => {
|
|
209
|
+
const separator = requestUrl.includes("?") ? "&" : "?";
|
|
210
|
+
const response = await fetchWithRetry(
|
|
211
|
+
`${requestUrl}${separator}audience=${VISUAL_REVIEW_OIDC_AUDIENCE}`,
|
|
212
|
+
{ headers: { Authorization: `Bearer ${requestToken}` } },
|
|
213
|
+
"GitHub OIDC token mint/refresh"
|
|
214
|
+
);
|
|
215
|
+
if (!response.ok) {
|
|
216
|
+
throw new Error(
|
|
217
|
+
`minting the GitHub OIDC token failed: ${response.status} ${(await response.text()).slice(0, 200)}`
|
|
218
|
+
);
|
|
219
|
+
}
|
|
220
|
+
const body = await response.json();
|
|
221
|
+
if (!body.value)
|
|
222
|
+
throw new Error("GitHub OIDC token endpoint returned no value");
|
|
223
|
+
cached = { value: body.value, mintedAtMs: Date.now() };
|
|
224
|
+
return { kind: "oidc", value: body.value };
|
|
225
|
+
};
|
|
226
|
+
return async () => {
|
|
227
|
+
if (cached && Date.now() - cached.mintedAtMs < OIDC_TOKEN_LIFETIME_MS - OIDC_TOKEN_REFRESH_MARGIN_MS) {
|
|
228
|
+
return { kind: "oidc", value: cached.value };
|
|
229
|
+
}
|
|
230
|
+
pending ??= mint().finally(() => {
|
|
231
|
+
pending = null;
|
|
232
|
+
});
|
|
233
|
+
return pending;
|
|
234
|
+
};
|
|
235
|
+
}
|
|
236
|
+
function jwtExpirySeconds(token) {
|
|
237
|
+
const payload = token.split(".")[1];
|
|
238
|
+
if (!payload) return null;
|
|
239
|
+
try {
|
|
240
|
+
const claims = JSON.parse(
|
|
241
|
+
Buffer.from(payload, "base64url").toString("utf8")
|
|
242
|
+
);
|
|
243
|
+
return typeof claims.exp === "number" ? claims.exp : null;
|
|
244
|
+
} catch {
|
|
245
|
+
return null;
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
function bitbucketOidcProvider(token, repoKey, log) {
|
|
249
|
+
let announced = false;
|
|
250
|
+
return async () => {
|
|
251
|
+
const exp = jwtExpirySeconds(token);
|
|
252
|
+
const nowSeconds = Date.now() / 1e3;
|
|
253
|
+
if (exp !== null && exp <= nowSeconds) {
|
|
254
|
+
throw new Error(
|
|
255
|
+
`the Bitbucket step OIDC token expired at ${new Date(exp * 1e3).toISOString()}; it cannot be re-minted, so claim, capture and report must finish inside one step within its lifetime \u2014 re-run the step`
|
|
256
|
+
);
|
|
257
|
+
}
|
|
258
|
+
if (!announced) {
|
|
259
|
+
announced = true;
|
|
260
|
+
if (exp !== null) {
|
|
261
|
+
log(
|
|
262
|
+
`Bitbucket step OIDC token valid for ${Math.round((exp - nowSeconds) / 60)} more minute(s); it cannot be re-minted within this step`
|
|
263
|
+
);
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
return { kind: "oidc", value: token, repoKey };
|
|
267
|
+
};
|
|
268
|
+
}
|
|
269
|
+
function resolveIngestCredential(oidcOnly = false, env = process.env) {
|
|
270
|
+
const requestUrl = env.ACTIONS_ID_TOKEN_REQUEST_URL;
|
|
271
|
+
const requestToken = env.ACTIONS_ID_TOKEN_REQUEST_TOKEN;
|
|
272
|
+
if (requestUrl && requestToken)
|
|
273
|
+
return githubOidcProvider(requestUrl, requestToken);
|
|
274
|
+
const bitbucket = env.GITHUB_ACTIONS === "true" ? null : readBitbucketPipelinesEnv(env);
|
|
275
|
+
const bitbucketRepoKey = bitbucket ? `bitbucket.org/${bitbucket.repoFullName}`.toLowerCase() : null;
|
|
276
|
+
if (bitbucket?.oidcToken && bitbucketRepoKey) {
|
|
277
|
+
return bitbucketOidcProvider(
|
|
278
|
+
bitbucket.oidcToken,
|
|
279
|
+
bitbucketRepoKey,
|
|
280
|
+
(line) => console.log(`[visual-review] ${line}`)
|
|
281
|
+
);
|
|
282
|
+
}
|
|
283
|
+
const oidc = env.VISUAL_REVIEW_OIDC_TOKEN;
|
|
284
|
+
if (oidc) {
|
|
285
|
+
return async () => bitbucketRepoKey ? { kind: "oidc", value: oidc, repoKey: bitbucketRepoKey } : { kind: "oidc", value: oidc };
|
|
286
|
+
}
|
|
287
|
+
const secret = env.VISUAL_REVIEW_UPLOAD_SECRET;
|
|
288
|
+
if (!oidcOnly && secret)
|
|
289
|
+
return async () => ({ kind: "secret", value: secret });
|
|
290
|
+
if (bitbucket) {
|
|
291
|
+
throw new Error(
|
|
292
|
+
oidcOnly ? "BITBUCKET_STEP_OIDC_TOKEN is missing: add `oidc: true` to the visual-review step in bitbucket-pipelines.yml" : "BITBUCKET_STEP_OIDC_TOKEN is missing: add `oidc: true` to the visual-review step in bitbucket-pipelines.yml (or set VISUAL_REVIEW_OIDC_TOKEN / VISUAL_REVIEW_UPLOAD_SECRET)"
|
|
293
|
+
);
|
|
294
|
+
}
|
|
295
|
+
throw new Error(
|
|
296
|
+
oidcOnly ? "GitHub Actions id-token: write or VISUAL_REVIEW_OIDC_TOKEN is required to publish through the Tempo GitHub App" : "GitHub Actions id-token permission, VISUAL_REVIEW_OIDC_TOKEN, or VISUAL_REVIEW_UPLOAD_SECRET is required for --upload"
|
|
297
|
+
);
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
// src/workflow-status.ts
|
|
301
|
+
function publisherName() {
|
|
302
|
+
return detectCiContext().provider === "bitbucket" ? "Tempo Bitbucket status" : "Tempo GitHub App status";
|
|
303
|
+
}
|
|
304
|
+
async function postWorkflowStatus(kind, headSha) {
|
|
305
|
+
const credential = await resolveIngestCredential(true)();
|
|
306
|
+
const origin = (process.env.VISUAL_REVIEW_INGEST_URL ?? DEFAULT_VISUAL_REVIEW_INGEST_URL).replace(/\/$/, "");
|
|
307
|
+
return await fetch(`${origin}/visual-review/workflow-status`, {
|
|
308
|
+
method: "POST",
|
|
309
|
+
headers: {
|
|
310
|
+
"Content-Type": "application/json",
|
|
311
|
+
"x-visual-review-oidc": credential.value,
|
|
312
|
+
...credential.kind === "oidc" && credential.repoKey ? { "x-visual-review-repo-key": credential.repoKey } : {}
|
|
313
|
+
},
|
|
314
|
+
body: JSON.stringify({ headSha, kind })
|
|
315
|
+
});
|
|
316
|
+
}
|
|
317
|
+
async function publishWorkflowStatus(kind, headSha) {
|
|
318
|
+
const response = await postWorkflowStatus(kind, headSha);
|
|
319
|
+
const publisher = publisherName();
|
|
320
|
+
if (!response.ok) {
|
|
321
|
+
throw new Error(
|
|
322
|
+
`${publisher} publishing failed (${response.status}): ${(await response.text()).slice(0, 500)}`
|
|
323
|
+
);
|
|
324
|
+
}
|
|
325
|
+
const result = await response.json();
|
|
326
|
+
if (result.status !== "posted" && result.status !== "skipped") {
|
|
327
|
+
throw new Error(`${publisher} returned an invalid status publishing response`);
|
|
328
|
+
}
|
|
329
|
+
console.log(
|
|
330
|
+
`${publisher}: ${result.status}${result.reason ? ` (${result.reason})` : ""}`
|
|
331
|
+
);
|
|
332
|
+
}
|
|
333
|
+
async function declareNoVisualChangeIfPresent(headSha) {
|
|
334
|
+
const response = await postWorkflowStatus("no-visual-change", headSha);
|
|
335
|
+
if (response.ok) {
|
|
336
|
+
const result = await response.json();
|
|
337
|
+
return result.status === "posted";
|
|
338
|
+
}
|
|
339
|
+
const body = await response.text();
|
|
340
|
+
if (response.status === 403 && body.includes("visual_review_declaration_missing")) {
|
|
341
|
+
return false;
|
|
342
|
+
}
|
|
343
|
+
throw new Error(
|
|
344
|
+
`checking the no-visual-change declaration failed (${response.status}): ${body.slice(0, 500)}`
|
|
345
|
+
);
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
export {
|
|
349
|
+
visualReviewPrDeclaration,
|
|
350
|
+
detectCiContext,
|
|
351
|
+
readCiState,
|
|
352
|
+
writeCiState,
|
|
353
|
+
DEFAULT_VISUAL_REVIEW_INGEST_URL,
|
|
354
|
+
fetchWithRetry,
|
|
355
|
+
VISUAL_REVIEW_OIDC_AUDIENCE,
|
|
356
|
+
resolveIngestCredential,
|
|
357
|
+
publishWorkflowStatus,
|
|
358
|
+
declareNoVisualChangeIfPresent
|
|
359
|
+
};
|
|
360
|
+
//# sourceMappingURL=chunk-H7MXR6QX.js.map
|