@bridge_gpt/mcp-server 0.2.73 → 0.2.74

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.
Files changed (90) hide show
  1. package/README.md +5 -5
  2. package/build/agent-launchers/claude-executor-adapter.js +12 -0
  3. package/build/agents.generated.js +3 -3
  4. package/build/bridge-config.js +7 -1
  5. package/build/bridge-permissions.js +3 -0
  6. package/build/command-provisioning.js +4 -3
  7. package/build/commands.generated.js +5 -5
  8. package/build/conductor/bridge-api-client.js +26 -1
  9. package/build/conductor/command-drift.js +1 -1
  10. package/build/conductor/declared-extras.js +335 -0
  11. package/build/conductor/doctor.js +2 -0
  12. package/build/conductor/driver-pass-output.js +104 -0
  13. package/build/conductor/driver-pass.js +571 -0
  14. package/build/conductor/epic-branch-ci-inspection.js +61 -16
  15. package/build/conductor/epic-implementer-cli.js +33 -0
  16. package/build/conductor/epic-server-sfcc-upload.js +1567 -0
  17. package/build/conductor/epic-server-sfcc.js +58 -80
  18. package/build/conductor/epic-server.js +57 -4
  19. package/build/conductor/gate-discovery.js +46 -6
  20. package/build/conductor/gate-settings-review.js +51 -14
  21. package/build/credential-delivery.js +280 -0
  22. package/build/credential-launch-safety.js +142 -0
  23. package/build/credential-materialization.js +91 -16
  24. package/build/credential-references-node-deps.js +29 -0
  25. package/build/credential-references.js +1394 -0
  26. package/build/credential-references.test-fixtures.js +211 -0
  27. package/build/credential-scan-conventions.js +145 -0
  28. package/build/credential-scan.js +517 -0
  29. package/build/credential-store.js +50 -0
  30. package/build/credentials-cli.js +252 -3
  31. package/build/dependency-install-declarations.js +47 -1
  32. package/build/docs.generated.js +8 -1
  33. package/build/doctor.js +41 -0
  34. package/build/drive-epic.js +297 -37
  35. package/build/epic-branch-ci-summary.js +18 -1
  36. package/build/epic-capability-statement.js +71 -3
  37. package/build/epic-ci-workflow-drift.js +52 -13
  38. package/build/epic-ci-workflow-install.js +31 -6
  39. package/build/epic-ci-workflow-v3.js +273 -0
  40. package/build/epic-ci-workflow.js +128 -7
  41. package/build/epic-implementer-bin.js +161 -70
  42. package/build/epic-launch-context.js +102 -7
  43. package/build/epic-server-record.js +30 -15
  44. package/build/executor/credential-delivery-step.js +168 -0
  45. package/build/executor/deps.js +3 -1
  46. package/build/executor/env.js +39 -1
  47. package/build/executor/epic-server-context.js +23 -7
  48. package/build/executor/guarded-fast-forward-push.js +13 -8
  49. package/build/executor/job-runner.js +159 -17
  50. package/build/executor/permissions.js +85 -3
  51. package/build/executor/prompt-spec.js +37 -3
  52. package/build/executor-launch.js +4 -2
  53. package/build/git-exclude-lock.js +187 -0
  54. package/build/index.js +398 -269
  55. package/build/install-bridge-conductor-answers.js +84 -21
  56. package/build/install-bridge-conductor-apply.js +30 -1
  57. package/build/install-bridge-conductor-assessment.js +375 -48
  58. package/build/install-bridge-conductor-compact.js +27 -2
  59. package/build/install-bridge-conductor-contracts.js +10 -1
  60. package/build/install-bridge-conductor-gate.js +124 -11
  61. package/build/install-bridge-conductor-setup.js +46 -8
  62. package/build/install-bridge-conductor.js +625 -113
  63. package/build/install-bridge.js +88 -11
  64. package/build/install-doctor.js +38 -8
  65. package/build/install-sfcc-detection.js +120 -0
  66. package/build/install-sfcc-setup.js +185 -0
  67. package/build/mcp-grant-candidates.js +108 -96
  68. package/build/mcp-invoke.js +168 -4
  69. package/build/mcp-provisioning.js +21 -4
  70. package/build/mcp-server-invocation.js +13 -0
  71. package/build/merge-workflow-install.js +9 -1
  72. package/build/pipelines.generated.js +2 -1
  73. package/build/plane/status.js +8 -2
  74. package/build/printed-remedy-commands.js +5 -0
  75. package/build/project-root.js +40 -0
  76. package/build/readme.generated.js +1 -1
  77. package/build/repository-state-paths.js +5 -2
  78. package/build/repository-toolchains.js +6 -3
  79. package/build/setup-epic.js +116 -15
  80. package/build/sfcc/credentials.js +3 -2
  81. package/build/sfcc/hostname.js +98 -2
  82. package/build/sfcc/tool-wrapper.js +6 -95
  83. package/build/start-tickets.js +193 -29
  84. package/build/test-support/executor-source-files.js +200 -0
  85. package/build/testing-config-client.js +25 -2
  86. package/build/third-party-mcp-targets.js +35 -4
  87. package/build/version.generated.js +3 -3
  88. package/build/with-credentials.js +208 -0
  89. package/build/worktree-credential-delivery.js +340 -0
  90. package/package.json +1 -1
@@ -0,0 +1,1567 @@
1
+ /**
2
+ * `epic-implementer epic-server sfcc-upload` (BAPI-1669).
3
+ *
4
+ * One verb, three forms, one shared SFCC code version:
5
+ *
6
+ * sfcc-upload --ticket <KEY> --head <SHA> worker: changed cartridge files only
7
+ * sfcc-upload --full --epic <KEY> --epic-run-id <id> --head <SHA> driver: the whole cartridge tree + baseline
8
+ * sfcc-upload --check read-only readiness, no network
9
+ *
10
+ * Upload is independent of the epic-server mode. It needs only an approved
11
+ * sandbox. Each form prints ONE secret-free JSON record with a closed outcome.
12
+ * A failure is a `no_live_server` hand-off, never a park, gate, or halt.
13
+ *
14
+ * What it never does: print or return b2c output, put a credential in an
15
+ * argument, write `dw.json`, pass `--reload`, upload an uncommitted edit, or
16
+ * wait on a browser sign-in. It uploads from COMMITTED blobs with `git archive`
17
+ * and `b2c webdav put/unzip/rm`, because `b2c code deploy` takes no file list.
18
+ *
19
+ * Every external effect goes through an injected seam so tests run with a fake
20
+ * b2c runner, a temporary git repository, and a fake clock.
21
+ */
22
+ import { spawn, execFile } from "node:child_process";
23
+ import { createHash, randomBytes } from "node:crypto";
24
+ import * as nodeFs from "node:fs/promises";
25
+ import { constants as fsConstants } from "node:fs";
26
+ import path from "node:path";
27
+ import { isValidSfccSandboxId } from "../epic-server-record.js";
28
+ import { canonicalizeSfccHostname, isApprovedSfccSandboxHost } from "../sfcc/hostname.js";
29
+ import { OWNERSHIP_TAG_ENV } from "../executor/process-containment.js";
30
+ import { createDefaultEpicServerStateFs, EPIC_SERVER_RUN_ID_ENV, ensurePrivateDirectory, epicServerRunPaths, findEpicServerRunPaths, isFullCommitShaLike, isValidEpicKey, isValidEpicRunId, readPrivateJson, writePrivateFileAtomic, } from "./epic-server-state.js";
31
+ import { createDefaultEpicServerProcessDeps, readProcessStartTime } from "./epic-server-processes.js";
32
+ import { SFCC_B2C_CLI_PINNED_PACKAGE, SFCC_B2C_NPX_MIN_NODE, SFCC_EVIDENCE_LABEL, SFCC_UPLOAD_FULL_BUDGET_SECONDS, SFCC_UPLOAD_FULL_CALL_SECONDS, SFCC_UPLOAD_FULL_COMMAND_SECONDS, SFCC_UPLOAD_FULL_LOCK_WAIT_SECONDS, SFCC_UPLOAD_LOCK_MAX_HOLD_SECONDS, SFCC_UPLOAD_LOCK_POLL_SECONDS, SFCC_UPLOAD_LOCK_WAIT_SECONDS, SFCC_UPLOAD_MAX_ARCHIVE_BYTES, SFCC_UPLOAD_MAX_WORKER_DELETES, SFCC_UPLOAD_WORKER_BUDGET_SECONDS, SFCC_UPLOAD_WORKER_CALL_SECONDS, SFCC_UPLOAD_WORKER_COMMAND_SECONDS, } from "./epic-server-sfcc.js";
33
+ // ---------------------------------------------------------------------------
34
+ // Closed vocabularies
35
+ // ---------------------------------------------------------------------------
36
+ export const SFCC_UPLOAD_OUTCOMES = ["uploaded", "nothing_to_upload", "ready", "unavailable", "refused"];
37
+ export const SFCC_UPLOAD_UNAVAILABLE_REASONS = [
38
+ "cli_unavailable",
39
+ "node_too_old",
40
+ "server_missing",
41
+ "code_version_missing",
42
+ "credentials_missing",
43
+ "interactive_auth_required",
44
+ "config_unreadable",
45
+ "no_run_id",
46
+ "no_run_baseline",
47
+ "base_unresolved",
48
+ "git_failed",
49
+ "upload_lock_timeout",
50
+ "upload_timeout",
51
+ "upload_failed",
52
+ "archive_too_large",
53
+ "baseline_write_failed",
54
+ "cartridge_name_conflict",
55
+ ];
56
+ export const SFCC_UPLOAD_REFUSED_REASONS = [
57
+ "not_a_sandbox_host",
58
+ "sandbox_mismatch",
59
+ "head_mismatch",
60
+ "driver_only",
61
+ "no_approved_sandbox",
62
+ "repo_unresolved",
63
+ ];
64
+ /** The nine readiness reasons the check form (and child 3) may report. */
65
+ export const SFCC_UPLOAD_CHECK_MISSING_REASONS = [
66
+ "cli_unavailable",
67
+ "node_too_old",
68
+ "server_missing",
69
+ "not_a_sandbox_host",
70
+ "sandbox_mismatch",
71
+ "code_version_missing",
72
+ "credentials_missing",
73
+ "interactive_auth_required",
74
+ "config_unreadable",
75
+ ];
76
+ /** Fixed hint text. A record never carries free text. */
77
+ export const SFCC_UPLOAD_HINTS = {
78
+ incomplete_extraction: "A put or unzip did not finish. The server may still be extracting. Rerun the same command once.",
79
+ stale_files: "A delete did not complete. The stale file stays until the next full upload.",
80
+ activation_failed: "Activation did not complete. Files are uploaded to the shared code version.",
81
+ zip_cleanup_failed: "A remote upload archive could not be removed. It is harmless and can be removed later.",
82
+ empty_snapshot: "No eligible cartridge files at this head. Nothing was uploaded.",
83
+ };
84
+ /** The upload files inside a run directory. `EpicServerRunPaths` is left alone. */
85
+ export function sfccUploadPaths(runDir) {
86
+ return {
87
+ lock: path.join(runDir, "sfcc-upload.lock"),
88
+ baseline: path.join(runDir, "sfcc-baseline.json"),
89
+ staging: path.join(runDir, "sfcc-staging"),
90
+ };
91
+ }
92
+ // ---------------------------------------------------------------------------
93
+ // Small pure helpers
94
+ // ---------------------------------------------------------------------------
95
+ const EXCLUDED_DIRS = new Set(["node_modules", ".git", "dist", "build", "coverage", ".cache", "tmp", "temp"]);
96
+ const SANDBOX_ID_LABEL_RE = /^[a-z0-9-]+$/;
97
+ const BASE_BRANCH_RE = /^[A-Za-z0-9][A-Za-z0-9._/-]{0,199}$/;
98
+ const REGULAR_MODES = new Set(["100644", "100755"]);
99
+ const RECLAIM_GUARD_MAX_AGE_MS = 30_000;
100
+ const CHECK_DEADLINE_MS = 15_000;
101
+ const CLEANUP_RESERVE_MS = 5_000;
102
+ const NODE_NPX_MIN = SFCC_B2C_NPX_MIN_NODE.split(".").map(Number);
103
+ /** A code version or path segment that is safe as one remote path segment. */
104
+ export function isSafeSfccPathSegment(value) {
105
+ if (typeof value !== "string" || value.length === 0 || value.length > 255)
106
+ return false;
107
+ if (value === "." || value === ".." || value.includes(".."))
108
+ return false;
109
+ if (/[\u0000-\u001f\u007f\\/#?%\s]/.test(value))
110
+ return false;
111
+ if (value.startsWith("-"))
112
+ return false;
113
+ return true;
114
+ }
115
+ function nonEmptyString(value) {
116
+ return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
117
+ }
118
+ function nodeAtLeastMin(version) {
119
+ const parts = version.replace(/^v/, "").split(".").map((n) => Number.parseInt(n, 10));
120
+ for (let i = 0; i < NODE_NPX_MIN.length; i++) {
121
+ const have = Number.isFinite(parts[i]) ? parts[i] : 0;
122
+ const need = NODE_NPX_MIN[i];
123
+ if (have > need)
124
+ return true;
125
+ if (have < need)
126
+ return false;
127
+ }
128
+ return true;
129
+ }
130
+ /** The first DNS label of a canonical host equals the approved sandbox id (case-insensitive, `_` as `-`). */
131
+ export function sandboxLabelMatches(canonicalHost, sandboxId) {
132
+ const label = canonicalHost.split(".")[0] ?? "";
133
+ const id = sandboxId.toLowerCase().replace(/_/g, "-");
134
+ return SANDBOX_ID_LABEL_RE.test(id) && label === id;
135
+ }
136
+ function runDigest(runId) {
137
+ return createHash("sha256").update(runId).digest("hex").slice(0, 8);
138
+ }
139
+ function pick(source, names) {
140
+ if (source === null)
141
+ return null;
142
+ for (const name of names) {
143
+ const value = nonEmptyString(source[name]);
144
+ if (value !== null)
145
+ return value;
146
+ }
147
+ return null;
148
+ }
149
+ function parseCartridgeList(raw) {
150
+ let items;
151
+ if (typeof raw === "string")
152
+ items = raw.split(/[:,]/);
153
+ else if (Array.isArray(raw) && raw.every((v) => typeof v === "string"))
154
+ items = raw;
155
+ else
156
+ return null;
157
+ const names = items.map((s) => s.trim()).filter((s) => s.length > 0);
158
+ return names.length > 0 ? names : null;
159
+ }
160
+ /**
161
+ * Read the one effective configuration for a repository root and environment.
162
+ * Reads only the root `dw.json`, never writes it, and reduces every secret to
163
+ * "is it non-empty" before returning.
164
+ */
165
+ export async function readSfccEffectiveConfig(repoRoot, env, deps) {
166
+ let dwJson = "absent";
167
+ let dw = null;
168
+ let unreadable = false;
169
+ let text = null;
170
+ try {
171
+ text = await deps.readText(path.join(repoRoot, "dw.json"));
172
+ }
173
+ catch (err) {
174
+ if (err.code !== "ENOENT") {
175
+ dwJson = "unreadable";
176
+ unreadable = true;
177
+ }
178
+ }
179
+ if (text !== null) {
180
+ try {
181
+ const parsed = JSON.parse(text);
182
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed))
183
+ throw new Error("shape");
184
+ let top = parsed;
185
+ if (top.configs !== undefined) {
186
+ if (!Array.isArray(top.configs))
187
+ throw new Error("configs");
188
+ if (top.configs.length > 0) {
189
+ const active = top.configs.filter((c) => c !== null && typeof c === "object" && !Array.isArray(c) && c.active === true);
190
+ if (active.length !== 1 || active.length !== top.configs.filter((c) => c !== null && typeof c === "object" && c.active === true).length) {
191
+ throw new Error("active");
192
+ }
193
+ // The active entry alone: no merge with the top level.
194
+ top = active[0];
195
+ }
196
+ }
197
+ dw = top;
198
+ dwJson = "present";
199
+ }
200
+ catch {
201
+ dwJson = "unreadable";
202
+ unreadable = true;
203
+ dw = null;
204
+ }
205
+ }
206
+ const envHost = nonEmptyString(env.SFCC_SERVER);
207
+ const dwHost = pick(dw, ["hostname", "server"]);
208
+ // A different SFCC_SERVER makes the CLI ignore the file: its values are absent.
209
+ let dwUsable = dw;
210
+ if (envHost !== null && dwHost !== null && envHost.toLowerCase() !== dwHost.toLowerCase())
211
+ dwUsable = null;
212
+ const username = nonEmptyString(env.SFCC_USERNAME) ?? pick(dwUsable, ["username"]);
213
+ const password = nonEmptyString(env.SFCC_PASSWORD) ?? pick(dwUsable, ["password"]);
214
+ const clientId = nonEmptyString(env.SFCC_CLIENT_ID) ?? pick(dwUsable, ["client-id", "clientId"]);
215
+ const clientSecret = nonEmptyString(env.SFCC_CLIENT_SECRET) ?? pick(dwUsable, ["client-secret", "clientSecret"]);
216
+ const shortCode = nonEmptyString(env.SFCC_SHORTCODE) ?? nonEmptyString(env.SFCC_SHORT_CODE) ?? pick(dwUsable, ["short-code", "shortCode"]);
217
+ const tenantId = nonEmptyString(env.SFCC_TENANT_ID) ?? pick(dwUsable, ["tenant-id", "tenantId"]);
218
+ const userPass = username !== null && password !== null;
219
+ const clientPair = clientId !== null && clientSecret !== null;
220
+ const anyOfFour = username !== null || password !== null || clientId !== null || clientSecret !== null;
221
+ const auth = userPass || clientPair ? "complete" : anyOfFour ? "interactive" : "missing";
222
+ const filterRaw = dwUsable === null ? undefined : (dwUsable.cartridges ?? dwUsable.cartridgesPath);
223
+ const envPresent = Object.keys(env).some((k) => k.startsWith("SFCC_") && nonEmptyString(env[k]) !== null && k !== "SFCC_DISABLE_TELEMETRY");
224
+ return {
225
+ dwJson,
226
+ envPresent,
227
+ hostRaw: envHost ?? dwHost,
228
+ codeVersionRaw: nonEmptyString(env.SFCC_CODE_VERSION) ?? pick(dwUsable, ["code-version", "codeVersion"]),
229
+ cartridgeFilter: filterRaw === undefined ? null : parseCartridgeList(filterRaw),
230
+ auth,
231
+ activationAvailable: clientId !== null && clientSecret !== null && shortCode !== null && tenantId !== null,
232
+ unreadable,
233
+ };
234
+ }
235
+ function checkHost(hostRaw, approvedSandboxId) {
236
+ if (hostRaw === null)
237
+ return { ok: false, kind: "unavailable", reason: "server_missing" };
238
+ // Whitespace is rejected before canonicalization so it is not silently repaired.
239
+ if (/\s/.test(hostRaw))
240
+ return { ok: false, kind: "refused", reason: "not_a_sandbox_host" };
241
+ const canonical = canonicalizeSfccHostname(hostRaw);
242
+ if (canonical === null || !isApprovedSfccSandboxHost(canonical)) {
243
+ return { ok: false, kind: "refused", reason: "not_a_sandbox_host" };
244
+ }
245
+ if (typeof approvedSandboxId === "string" && approvedSandboxId.length > 0 && !sandboxLabelMatches(canonical, approvedSandboxId)) {
246
+ return { ok: false, kind: "refused", reason: "sandbox_mismatch" };
247
+ }
248
+ return { ok: true, host: canonical };
249
+ }
250
+ async function resolveCli(repoRoot, deps) {
251
+ const bin = path.join(repoRoot, "node_modules", ".bin", "b2c");
252
+ try {
253
+ const realBin = await deps.cli.realpath(bin);
254
+ const realModules = await deps.cli.realpath(path.join(repoRoot, "node_modules"));
255
+ const rel = path.relative(realModules, realBin);
256
+ if (rel !== "" && !rel.startsWith("..") && !path.isAbsolute(rel) && (await deps.cli.isExecutable(realBin))) {
257
+ return { ok: true, source: "repo_bin", argv0: realBin, prefix: [] };
258
+ }
259
+ }
260
+ catch {
261
+ /* no usable repository bin: fall through to the pinned fallback */
262
+ }
263
+ const npx = await deps.cli.findOnPath("npx", deps.env);
264
+ if (npx === null)
265
+ return { ok: false, reason: "cli_unavailable" };
266
+ if (!nodeAtLeastMin(deps.cli.nodeVersion()))
267
+ return { ok: false, reason: "node_too_old" };
268
+ return { ok: true, source: "npx", argv0: npx, prefix: ["-y", SFCC_B2C_CLI_PINNED_PACKAGE] };
269
+ }
270
+ const PINNED_VERSION = SFCC_B2C_CLI_PINNED_PACKAGE.slice(SFCC_B2C_CLI_PINNED_PACKAGE.lastIndexOf("@") + 1);
271
+ function b2cEnv(base) {
272
+ const env = {};
273
+ for (const [k, v] of Object.entries(base))
274
+ if (typeof v === "string")
275
+ env[k] = v;
276
+ env.B2C_SKIP_NEW_VERSION_CHECK = "true";
277
+ env.SFCC_DISABLE_TELEMETRY = "true";
278
+ env.SF_DISABLE_TELEMETRY = "true";
279
+ return env;
280
+ }
281
+ function commonArgs(t, withRootAndJson) {
282
+ const args = [];
283
+ if (withRootAndJson)
284
+ args.push("--root", "cartridges");
285
+ args.push("--server", t.host, "--code-version", t.version, "--auth-methods", "client-credentials,basic");
286
+ if (withRootAndJson)
287
+ args.push("--json");
288
+ return args;
289
+ }
290
+ const b2cArgs = {
291
+ put: (t, local, remote) => ["webdav", "put", local, remote, ...commonArgs(t, true)],
292
+ unzip: (t, remote) => ["webdav", "unzip", remote, ...commonArgs(t, true)],
293
+ rm: (t, remote) => ["webdav", "rm", remote, "--force", ...commonArgs(t, true)],
294
+ activate: (t) => ["code", "activate", t.version, ...commonArgs(t, false)],
295
+ };
296
+ class UploadRecord {
297
+ now;
298
+ startedAt;
299
+ startedAtMs;
300
+ form;
301
+ command;
302
+ ticket = null;
303
+ head = null;
304
+ sandboxId = null;
305
+ codeVersion = null;
306
+ diffBase = null;
307
+ diffBaseSha = null;
308
+ baselineHead = null;
309
+ cartridges = [];
310
+ filesUploaded = 0;
311
+ filesDeleted = 0;
312
+ deletesFailed = 0;
313
+ deletesDeferred = 0;
314
+ skipped = 0;
315
+ activation = "not_attempted";
316
+ lockWaitMs = 0;
317
+ cli = { source: "none", version: null };
318
+ hints = new Set();
319
+ constructor(form, command, now) {
320
+ this.now = now;
321
+ this.form = form;
322
+ this.command = command;
323
+ this.startedAtMs = now();
324
+ this.startedAt = new Date(this.startedAtMs).toISOString();
325
+ }
326
+ /** Copies only approved fields. Never a hostname, credential, file list, b2c output, or exception text. */
327
+ build(outcome, reason) {
328
+ const hintOrder = [
329
+ "incomplete_extraction",
330
+ "activation_failed",
331
+ "stale_files",
332
+ "zip_cleanup_failed",
333
+ "empty_snapshot",
334
+ ];
335
+ const hintKey = hintOrder.find((k) => this.hints.has(k));
336
+ const failed = outcome === "unavailable" || outcome === "refused";
337
+ return {
338
+ verb: "sfcc-upload",
339
+ form: this.form,
340
+ outcome,
341
+ ...(reason !== null ? { reason } : {}),
342
+ ...(failed ? { cause: "no_live_server" } : {}),
343
+ label: SFCC_EVIDENCE_LABEL,
344
+ command: this.command,
345
+ ticket: this.ticket,
346
+ head: this.head,
347
+ sandbox_id: this.sandboxId,
348
+ code_version: this.codeVersion,
349
+ diff_base: this.diffBase,
350
+ diff_base_sha: this.diffBaseSha,
351
+ baseline_head: this.baselineHead,
352
+ cartridges: this.cartridges,
353
+ files_uploaded: this.filesUploaded,
354
+ files_deleted: this.filesDeleted,
355
+ deletes_failed: this.deletesFailed,
356
+ deletes_deferred: this.deletesDeferred,
357
+ skipped: this.skipped,
358
+ activation: this.activation,
359
+ lock_wait_ms: this.lockWaitMs,
360
+ started_at: this.startedAt,
361
+ ended_at: new Date(this.now()).toISOString(),
362
+ cli: this.cli,
363
+ ...(hintKey !== undefined ? { hint: SFCC_UPLOAD_HINTS[hintKey] } : {}),
364
+ };
365
+ }
366
+ }
367
+ /** Single-emission finalizer: prints one record and returns the exit code. */
368
+ class Finalizer {
369
+ deps;
370
+ record;
371
+ done = false;
372
+ constructor(deps, record) {
373
+ this.deps = deps;
374
+ this.record = record;
375
+ }
376
+ finish(outcome, reason = null) {
377
+ if (this.done)
378
+ return outcome === "uploaded" || outcome === "nothing_to_upload" ? 0 : 1;
379
+ this.done = true;
380
+ this.deps.stdout(JSON.stringify(this.record.build(outcome, reason)));
381
+ if (outcome === "uploaded" || outcome === "nothing_to_upload")
382
+ return 0;
383
+ this.deps.stderr(`epic-server: no_live_server (${reason ?? outcome}); record the step under the hand-off rules, nothing parks`);
384
+ return 1;
385
+ }
386
+ }
387
+ class Stop extends Error {
388
+ outcome;
389
+ reason;
390
+ constructor(outcome, reason) {
391
+ super(reason);
392
+ this.outcome = outcome;
393
+ this.reason = reason;
394
+ }
395
+ }
396
+ const unavailableStop = (reason) => new Stop("unavailable", reason);
397
+ const refusedStop = (reason) => new Stop("refused", reason);
398
+ function remainingCommandMs(ctx) {
399
+ return ctx.startMs + ctx.commandMs - ctx.deps.now();
400
+ }
401
+ function throwIfCancelled(ctx) {
402
+ if (ctx.cancelled)
403
+ throw unavailableStop("upload_failed");
404
+ }
405
+ /** One b2c call under the cumulative budget, the per-call cap, and the command deadline. */
406
+ async function runB2c(ctx, args) {
407
+ throwIfCancelled(ctx);
408
+ const allowed = Math.min(ctx.callCapMs, ctx.budgetMs - ctx.spentMs, remainingCommandMs(ctx) - CLEANUP_RESERVE_MS);
409
+ if (allowed <= 0)
410
+ return "timeout";
411
+ const began = ctx.deps.now();
412
+ let result;
413
+ try {
414
+ result = await ctx.deps.b2c([ctx.cli.argv0, ...ctx.cli.prefix, ...args], {
415
+ cwd: ctx.cwd,
416
+ env: ctx.env,
417
+ timeoutMs: allowed,
418
+ signal: ctx.abort.signal,
419
+ });
420
+ }
421
+ catch {
422
+ result = { exitCode: null, timedOut: false };
423
+ }
424
+ ctx.spentMs += Math.max(0, ctx.deps.now() - began);
425
+ if (ctx.cancelled)
426
+ throw unavailableStop("upload_failed");
427
+ if (result.timedOut)
428
+ return "timeout";
429
+ return result.exitCode === 0 ? "ok" : "failed";
430
+ }
431
+ // ---------------------------------------------------------------------------
432
+ // Git helpers (local data only)
433
+ // ---------------------------------------------------------------------------
434
+ const GIT_ENV = { GIT_TERMINAL_PROMPT: "0", GIT_OPTIONAL_LOCKS: "0" };
435
+ class GitFailure extends Error {
436
+ }
437
+ async function git(deps, cwd, args, extra = {}) {
438
+ let result;
439
+ try {
440
+ result = await deps.git(args, { cwd, env: { ...GIT_ENV, ...(extra.env ?? {}) }, timeoutMs: extra.timeoutMs ?? 60_000, input: extra.input });
441
+ }
442
+ catch {
443
+ throw new GitFailure();
444
+ }
445
+ const ok = extra.okCodes ?? [0];
446
+ if (result.timedOut || result.exitCode === null || !ok.includes(result.exitCode))
447
+ throw new GitFailure();
448
+ return { exitCode: result.exitCode, stdout: result.stdout };
449
+ }
450
+ function parseLsTree(out) {
451
+ const entries = [];
452
+ for (const record of out.split("\0")) {
453
+ if (record === "")
454
+ continue;
455
+ const tab = record.indexOf("\t");
456
+ if (tab === -1)
457
+ throw new GitFailure();
458
+ const [mode, type, sha] = record.slice(0, tab).split(" ");
459
+ if (!mode || !type || !sha)
460
+ throw new GitFailure();
461
+ entries.push({ mode, type, sha, path: record.slice(tab + 1) });
462
+ }
463
+ return entries;
464
+ }
465
+ function parseDiffRaw(out) {
466
+ const parts = out.split("\0");
467
+ const entries = [];
468
+ for (let i = 0; i + 1 < parts.length; i += 2) {
469
+ const meta = parts[i];
470
+ if (!meta.startsWith(":")) {
471
+ if (meta === "")
472
+ continue;
473
+ throw new GitFailure();
474
+ }
475
+ const fields = meta.slice(1).split(" ");
476
+ const status = (fields[4] ?? "")[0] ?? "";
477
+ entries.push({ status, newMode: fields[1] ?? "", path: parts[i + 1] });
478
+ }
479
+ return entries;
480
+ }
481
+ function discoverCartridges(entries, filter, skips) {
482
+ const roots = new Map();
483
+ for (const entry of entries) {
484
+ if (entry.type !== "blob")
485
+ continue;
486
+ const segments = entry.path.split("/");
487
+ if (segments[segments.length - 1] !== ".project" || segments.length < 2)
488
+ continue;
489
+ const dirSegments = segments.slice(0, -1);
490
+ if (dirSegments.some((s) => EXCLUDED_DIRS.has(s)))
491
+ continue;
492
+ const name = dirSegments[dirSegments.length - 1];
493
+ if (!isSafeSfccPathSegment(name)) {
494
+ skips.count += 1;
495
+ continue;
496
+ }
497
+ roots.set(dirSegments.join("/"), { root: dirSegments.join("/"), name });
498
+ }
499
+ let list = [...roots.values()];
500
+ if (filter !== null) {
501
+ const wanted = new Set(filter);
502
+ list = list.filter((c) => wanted.has(c.name));
503
+ }
504
+ return list.sort((a, b) => a.root.localeCompare(b.root));
505
+ }
506
+ function hasNameConflict(roots) {
507
+ const names = new Set();
508
+ for (const r of roots) {
509
+ if (names.has(r.name))
510
+ return true;
511
+ names.add(r.name);
512
+ }
513
+ return false;
514
+ }
515
+ /** The deepest cartridge root containing `repoPath`, with the path relative to it. */
516
+ function owningCartridge(roots, repoPath) {
517
+ let best = null;
518
+ for (const r of roots) {
519
+ if (repoPath.startsWith(`${r.root}/`) && (best === null || r.root.length > best.root.length))
520
+ best = r;
521
+ }
522
+ return best === null ? null : { cart: best, rel: repoPath.slice(best.root.length + 1) };
523
+ }
524
+ function isSecretName(base) {
525
+ return base === "dw.json" || base === ".env" || base.startsWith(".env.");
526
+ }
527
+ function judgeRelPath(rel) {
528
+ const segments = rel.split("/");
529
+ const base = segments[segments.length - 1];
530
+ if (segments.slice(0, -1).some((s) => EXCLUDED_DIRS.has(s)))
531
+ return "skip";
532
+ if (isSecretName(base) || base === ".gitattributes")
533
+ return "skip";
534
+ // A path that cannot be sent safely is skipped, not repaired.
535
+ if (segments.some((s) => s === "" || s === "." || s === ".." || /[\u0000-\u001f\u007f\\]/.test(s)))
536
+ return "unsafe";
537
+ return "ok";
538
+ }
539
+ function planFromTree(entries, roots, only, skips) {
540
+ const files = [];
541
+ for (const entry of entries) {
542
+ if (only !== null && !only.has(entry.path))
543
+ continue;
544
+ const owned = owningCartridge(roots, entry.path);
545
+ if (owned === null)
546
+ continue;
547
+ if (!REGULAR_MODES.has(entry.mode) || entry.type !== "blob") {
548
+ skips.count += 1;
549
+ continue;
550
+ }
551
+ if (judgeRelPath(owned.rel) !== "ok") {
552
+ skips.count += 1;
553
+ continue;
554
+ }
555
+ files.push({ cartridge: owned.cart.name, rel: owned.rel, mode: entry.mode, sha: entry.sha });
556
+ }
557
+ return files;
558
+ }
559
+ function validDeleteSegments(rel) {
560
+ return rel
561
+ .split("/")
562
+ .every((s) => s !== "" && s !== "." && s !== ".." && !s.startsWith("-") && !/[\u0000-\u001f\u007f\\]/.test(s));
563
+ }
564
+ // ---------------------------------------------------------------------------
565
+ // ZIP central-directory reader (entry names only)
566
+ // ---------------------------------------------------------------------------
567
+ /** The file entry names of a ZIP, or null when it is not a plain (non-ZIP64) archive. */
568
+ export function readZipFileEntryNames(buf) {
569
+ const view = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
570
+ const minEocd = 22;
571
+ if (view.length < minEocd)
572
+ return null;
573
+ let eocd = -1;
574
+ for (let i = view.length - minEocd; i >= Math.max(0, view.length - minEocd - 0xffff); i--) {
575
+ if (view.readUInt32LE(i) === 0x06054b50) {
576
+ eocd = i;
577
+ break;
578
+ }
579
+ }
580
+ if (eocd === -1)
581
+ return null;
582
+ const count = view.readUInt16LE(eocd + 10);
583
+ const cdOffset = view.readUInt32LE(eocd + 16);
584
+ if (count === 0xffff || cdOffset === 0xffffffff)
585
+ return null;
586
+ const names = [];
587
+ let p = cdOffset;
588
+ for (let n = 0; n < count; n++) {
589
+ if (p + 46 > view.length || view.readUInt32LE(p) !== 0x02014b50)
590
+ return null;
591
+ const nameLen = view.readUInt16LE(p + 28);
592
+ const extraLen = view.readUInt16LE(p + 30);
593
+ const commentLen = view.readUInt16LE(p + 32);
594
+ if (p + 46 + nameLen > view.length)
595
+ return null;
596
+ const name = view.toString("utf8", p + 46, p + 46 + nameLen);
597
+ if (!name.endsWith("/"))
598
+ names.push(name);
599
+ p += 46 + nameLen + extraLen + commentLen;
600
+ }
601
+ return names;
602
+ }
603
+ async function realObjectDir(deps, repoRoot) {
604
+ const out = (await git(deps, repoRoot, ["rev-parse", "--git-path", "objects"])).stdout.trim();
605
+ if (out === "")
606
+ throw new GitFailure();
607
+ return path.resolve(repoRoot, out);
608
+ }
609
+ /**
610
+ * Build one zip per touched cartridge from selected blob ids. A temporary
611
+ * isolated git directory and index mean no write to the real index, config, or
612
+ * object database, and no repository attributes (`info/attributes`,
613
+ * `.gitattributes`) can transform an entry.
614
+ */
615
+ async function buildArchives(deps, repoRoot, stagingDir, files) {
616
+ const byCartridge = new Map();
617
+ for (const f of files)
618
+ byCartridge.set(f.cartridge, [...(byCartridge.get(f.cartridge) ?? []), f]);
619
+ const objects = await realObjectDir(deps, repoRoot);
620
+ const built = [];
621
+ let n = 0;
622
+ for (const [cartridge, group] of byCartridge) {
623
+ n += 1;
624
+ const gitDir = path.join(stagingDir, `g${n}`);
625
+ const index = path.join(stagingDir, `i${n}`);
626
+ const zipPath = path.join(stagingDir, `a${n}.zip`);
627
+ await git(deps, stagingDir, ["init", "--bare", "-q", gitDir]);
628
+ await ensurePrivateDirectory(deps.fs, path.join(gitDir, "objects", "info"));
629
+ const alt = await deps.fs.open(path.join(gitDir, "objects", "info", "alternates"), "wx", 0o600);
630
+ try {
631
+ await alt.writeFile(`${objects}\n`, { encoding: "utf-8" });
632
+ }
633
+ finally {
634
+ await alt.close();
635
+ }
636
+ const env = { GIT_DIR: gitDir, GIT_INDEX_FILE: index };
637
+ const indexInfo = group.map((f) => `${f.mode} ${f.sha}\t${f.cartridge}/${f.rel}\0`).join("");
638
+ await git(deps, stagingDir, ["update-index", "-z", "--add", "--index-info"], { env, input: indexInfo });
639
+ const tree = (await git(deps, stagingDir, ["write-tree"], { env })).stdout.trim();
640
+ if (!/^[0-9a-f]{40,64}$/.test(tree))
641
+ throw new GitFailure();
642
+ await git(deps, stagingDir, ["-c", "core.attributesFile=/dev/null", "archive", "--format=zip", "-o", zipPath, tree], { env });
643
+ const meta = await deps.statMeta(zipPath);
644
+ if (meta === null)
645
+ throw new GitFailure();
646
+ if (meta.size > SFCC_UPLOAD_MAX_ARCHIVE_BYTES)
647
+ throw unavailableStop("archive_too_large");
648
+ const entries = readZipFileEntryNames(await deps.readBinary(zipPath));
649
+ const expected = group.map((f) => `${f.cartridge}/${f.rel}`).sort();
650
+ const actual = entries === null ? null : [...entries].sort();
651
+ if (actual === null || actual.length !== expected.length || actual.some((e, i) => e !== expected[i]))
652
+ throw new GitFailure();
653
+ built.push({ cartridge, zipPath, fileCount: group.length });
654
+ }
655
+ return built;
656
+ }
657
+ function validateBaseline(raw, runDir, runId) {
658
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw))
659
+ return null;
660
+ const b = raw;
661
+ if (b.version !== 1)
662
+ return null;
663
+ const epicKey = path.basename(path.dirname(path.dirname(runDir)));
664
+ if (b.epic_run_id !== runId || b.epic_key !== epicKey || !isValidEpicKey(b.epic_key))
665
+ return null;
666
+ if (!isValidSfccSandboxId(b.sandbox_id))
667
+ return null;
668
+ if (!isSafeSfccPathSegment(b.code_version))
669
+ return null;
670
+ if (!isFullCommitShaLike(b.head))
671
+ return null;
672
+ if (typeof b.uploaded_at !== "string" || b.uploaded_at.length === 0 || b.uploaded_at.length > 64)
673
+ return null;
674
+ return {
675
+ version: 1,
676
+ epic_key: b.epic_key,
677
+ epic_run_id: runId,
678
+ sandbox_id: b.sandbox_id,
679
+ code_version: b.code_version,
680
+ head: b.head,
681
+ uploaded_at: b.uploaded_at,
682
+ };
683
+ }
684
+ async function readBaseline(deps, runDir, runId) {
685
+ return validateBaseline(await readPrivateJson(deps.fs, sfccUploadPaths(runDir).baseline), runDir, runId);
686
+ }
687
+ function parseLock(text) {
688
+ try {
689
+ const raw = JSON.parse(text);
690
+ if (raw === null || typeof raw !== "object")
691
+ return null;
692
+ const l = raw;
693
+ if ((l.holder !== "worker" && l.holder !== "driver") || typeof l.nonce !== "string" || l.nonce.length === 0)
694
+ return null;
695
+ if (typeof l.pid !== "number" || !Number.isSafeInteger(l.pid) || l.pid <= 1)
696
+ return null;
697
+ if (typeof l.acquired_at !== "string" || Number.isNaN(Date.parse(l.acquired_at)))
698
+ return null;
699
+ return {
700
+ holder: l.holder,
701
+ ticket: typeof l.ticket === "string" ? l.ticket : null,
702
+ pid: l.pid,
703
+ started_at: typeof l.started_at === "string" ? l.started_at : null,
704
+ nonce: l.nonce,
705
+ acquired_at: l.acquired_at,
706
+ };
707
+ }
708
+ catch {
709
+ return null;
710
+ }
711
+ }
712
+ class UploadLock {
713
+ deps;
714
+ holder;
715
+ ticket;
716
+ owned = null;
717
+ lockPath;
718
+ guardPath;
719
+ constructor(deps, runDir, holder, ticket) {
720
+ this.deps = deps;
721
+ this.holder = holder;
722
+ this.ticket = ticket;
723
+ this.lockPath = sfccUploadPaths(runDir).lock;
724
+ this.guardPath = `${this.lockPath}.reclaim`;
725
+ }
726
+ async exclusiveWrite(file, text) {
727
+ let handle;
728
+ try {
729
+ handle = await this.deps.fs.open(file, "wx", 0o600);
730
+ }
731
+ catch (err) {
732
+ if (err.code === "EEXIST")
733
+ return false;
734
+ throw err;
735
+ }
736
+ try {
737
+ await handle.writeFile(text, { encoding: "utf-8" });
738
+ await handle.sync();
739
+ }
740
+ finally {
741
+ await handle.close();
742
+ }
743
+ return true;
744
+ }
745
+ async readLockText() {
746
+ try {
747
+ const st = await this.deps.fs.lstat(this.lockPath);
748
+ if (st.isSymbolicLink() || !st.isFile())
749
+ return "";
750
+ return await this.deps.fs.readFile(this.lockPath, "utf-8");
751
+ }
752
+ catch (err) {
753
+ if (err.code === "ENOENT")
754
+ return null;
755
+ return "";
756
+ }
757
+ }
758
+ async isStale(text) {
759
+ const lock = parseLock(text);
760
+ const maxHoldMs = SFCC_UPLOAD_LOCK_MAX_HOLD_SECONDS * 1000;
761
+ if (lock === null) {
762
+ // Empty or unreadable: held until its filesystem age passes the maximum hold.
763
+ const meta = await this.deps.statMeta(this.lockPath);
764
+ return meta !== null && this.deps.now() - meta.mtimeMs > maxHoldMs;
765
+ }
766
+ if (this.deps.now() - Date.parse(lock.acquired_at) > maxHoldMs)
767
+ return true;
768
+ if (this.deps.isPidAlive(lock.pid) === false)
769
+ return true;
770
+ if (lock.started_at !== null) {
771
+ const live = await this.deps.readProcessStartTime(lock.pid);
772
+ // An unknown start time is inconclusive, never stale.
773
+ if (live !== null && live !== lock.started_at)
774
+ return true;
775
+ }
776
+ return false;
777
+ }
778
+ sameLock(a, b) {
779
+ const la = parseLock(a);
780
+ const lb = parseLock(b);
781
+ return la !== null && lb !== null ? la.nonce === lb.nonce : a === b;
782
+ }
783
+ /** Remove the lock only if, under the guard, it is still the one judged. */
784
+ async removeIfStill(judged) {
785
+ const guarded = await this.takeGuard();
786
+ if (!guarded)
787
+ return;
788
+ try {
789
+ const now = await this.readLockText();
790
+ if (now !== null && this.sameLock(now, judged))
791
+ await this.deps.fs.unlink(this.lockPath).catch(() => undefined);
792
+ }
793
+ finally {
794
+ await this.deps.fs.unlink(this.guardPath).catch(() => undefined);
795
+ }
796
+ }
797
+ async takeGuard() {
798
+ if (await this.exclusiveWrite(this.guardPath, `${this.deps.pid}\n`))
799
+ return true;
800
+ const meta = await this.deps.statMeta(this.guardPath);
801
+ if (meta !== null && this.deps.now() - meta.mtimeMs > RECLAIM_GUARD_MAX_AGE_MS) {
802
+ await this.deps.fs.unlink(this.guardPath).catch(() => undefined);
803
+ }
804
+ return false;
805
+ }
806
+ /** Wait up to `waitMs` for the lock. Returns the milliseconds waited, or null on timeout. */
807
+ async acquire(waitMs, isCancelled) {
808
+ const began = this.deps.now();
809
+ const nonce = this.deps.randomHex(16);
810
+ const startedAt = await this.deps.readProcessStartTime(this.deps.pid);
811
+ for (;;) {
812
+ if (isCancelled())
813
+ return null;
814
+ const content = {
815
+ holder: this.holder,
816
+ ticket: this.ticket,
817
+ pid: this.deps.pid,
818
+ started_at: startedAt,
819
+ nonce,
820
+ acquired_at: new Date(this.deps.now()).toISOString(),
821
+ };
822
+ if (await this.exclusiveWrite(this.lockPath, `${JSON.stringify(content)}\n`)) {
823
+ this.owned = nonce;
824
+ return this.deps.now() - began;
825
+ }
826
+ const text = await this.readLockText();
827
+ if (text !== null && (await this.isStale(text))) {
828
+ await this.removeIfStill(text);
829
+ continue;
830
+ }
831
+ if (this.deps.now() - began + SFCC_UPLOAD_LOCK_POLL_SECONDS * 1000 > waitMs)
832
+ return null;
833
+ await this.deps.sleep(SFCC_UPLOAD_LOCK_POLL_SECONDS * 1000);
834
+ }
835
+ }
836
+ /** Delete only a lock this invocation's nonce owns. */
837
+ async release() {
838
+ const mine = this.owned;
839
+ if (mine === null)
840
+ return;
841
+ this.owned = null;
842
+ try {
843
+ const text = await this.readLockText();
844
+ const lock = text === null ? null : parseLock(text);
845
+ if (lock === null || lock.nonce !== mine)
846
+ return;
847
+ await this.removeIfStill(text);
848
+ }
849
+ catch {
850
+ /* best effort: a stale lock is reclaimed by age */
851
+ }
852
+ }
853
+ }
854
+ /** put, unzip, then a forced remove of the remote zip. A cleanup failure never fails the upload. */
855
+ async function uploadArchive(s, archive, n) {
856
+ const remote = `${s.target.version}/_bridge-${s.digest}-${n}.zip`;
857
+ const put = await runB2c(s.ctx, b2cArgs.put(s.target, archive.zipPath, remote));
858
+ if (put !== "ok") {
859
+ s.rec.hints.add("incomplete_extraction");
860
+ throw unavailableStop(put === "timeout" ? "upload_timeout" : "upload_failed");
861
+ }
862
+ const unzip = await runB2c(s.ctx, b2cArgs.unzip(s.target, remote));
863
+ if (unzip !== "ok") {
864
+ s.rec.hints.add("incomplete_extraction");
865
+ throw unavailableStop(unzip === "timeout" ? "upload_timeout" : "upload_failed");
866
+ }
867
+ s.rec.filesUploaded += archive.fileCount;
868
+ s.rec.cartridges.push(archive.cartridge);
869
+ if ((await runB2c(s.ctx, b2cArgs.rm(s.target, remote))) !== "ok")
870
+ s.rec.hints.add("zip_cleanup_failed");
871
+ }
872
+ /** Activation once, never `--reload`, never fails an upload that already extracted. */
873
+ async function activate(s) {
874
+ if (!s.activationAvailable) {
875
+ s.rec.activation = "not_attempted";
876
+ return;
877
+ }
878
+ const allowed = Math.min(s.ctx.callCapMs, s.ctx.budgetMs - s.ctx.spentMs, remainingCommandMs(s.ctx) - CLEANUP_RESERVE_MS);
879
+ if (allowed <= 0) {
880
+ s.rec.activation = "not_attempted";
881
+ return;
882
+ }
883
+ try {
884
+ const result = await runB2c(s.ctx, b2cArgs.activate(s.target));
885
+ s.rec.activation = result === "ok" ? "ensured" : "failed";
886
+ }
887
+ catch {
888
+ s.rec.activation = "failed";
889
+ }
890
+ if (s.rec.activation === "failed")
891
+ s.rec.hints.add("activation_failed");
892
+ }
893
+ async function removeStaging(deps, dir) {
894
+ if (dir === null)
895
+ return;
896
+ await deps.fs.rm(dir, { recursive: true, force: true }).catch(() => undefined);
897
+ }
898
+ async function probeCliVersion(cli, deps, timeoutMs) {
899
+ if (cli.source === "npx")
900
+ return PINNED_VERSION;
901
+ try {
902
+ const v = await deps.cli.probeVersion(cli.argv0, Math.max(1, timeoutMs));
903
+ return v !== null && /^\d{1,4}\.\d{1,4}\.\d{1,4}$/.test(v) ? v : null;
904
+ }
905
+ catch {
906
+ return null;
907
+ }
908
+ }
909
+ async function validateTarget(deps, repoRoot, version, approvedSandboxId) {
910
+ const cfg = await readSfccEffectiveConfig(repoRoot, deps.env, deps);
911
+ if (cfg.unreadable)
912
+ throw unavailableStop("config_unreadable");
913
+ const host = checkHost(cfg.hostRaw, approvedSandboxId);
914
+ if (!host.ok)
915
+ throw host.kind === "refused" ? refusedStop(host.reason) : unavailableStop(host.reason);
916
+ let resolved = version;
917
+ if (resolved === null) {
918
+ if (cfg.codeVersionRaw === null)
919
+ throw unavailableStop("code_version_missing");
920
+ if (!isSafeSfccPathSegment(cfg.codeVersionRaw))
921
+ throw unavailableStop("config_unreadable");
922
+ resolved = cfg.codeVersionRaw;
923
+ }
924
+ if (cfg.auth === "missing")
925
+ throw unavailableStop("credentials_missing");
926
+ if (cfg.auth === "interactive")
927
+ throw unavailableStop("interactive_auth_required");
928
+ const cli = await resolveCli(repoRoot, deps);
929
+ if (!cli.ok)
930
+ throw unavailableStop(cli.reason);
931
+ return { host: host.host, version: resolved, cfg, cli };
932
+ }
933
+ function baseBranchFrom(env) {
934
+ const raw = env.BAPI_BASE_BRANCH;
935
+ if (typeof raw !== "string" || !BASE_BRANCH_RE.test(raw) || raw.includes("..") || raw.endsWith("/") || raw.endsWith(".lock"))
936
+ return null;
937
+ return raw;
938
+ }
939
+ // ---------------------------------------------------------------------------
940
+ // Worker form
941
+ // ---------------------------------------------------------------------------
942
+ async function runWorkerForm(deps, cmd, rec, ctxBase) {
943
+ rec.ticket = cmd.ticket;
944
+ rec.head = cmd.head;
945
+ const repoRoot = deps.resolveRepoRoot();
946
+ if (repoRoot === null)
947
+ throw unavailableStop("git_failed");
948
+ let currentHead;
949
+ try {
950
+ currentHead = (await git(deps, repoRoot, ["rev-parse", "HEAD"])).stdout.trim();
951
+ }
952
+ catch {
953
+ throw unavailableStop("git_failed");
954
+ }
955
+ if (currentHead !== cmd.head)
956
+ throw refusedStop("head_mismatch");
957
+ const runId = deps.env[EPIC_SERVER_RUN_ID_ENV];
958
+ if (!isValidEpicRunId(runId))
959
+ throw unavailableStop("no_run_id");
960
+ const paths = await findEpicServerRunPaths(deps.homedir(), runId, deps.fs, deps.tmpdir());
961
+ if (paths === null)
962
+ throw unavailableStop("no_run_baseline");
963
+ let baseline = await readBaseline(deps, paths.runDir, runId);
964
+ if (baseline === null)
965
+ throw unavailableStop("no_run_baseline");
966
+ rec.sandboxId = baseline.sandbox_id;
967
+ rec.codeVersion = baseline.code_version;
968
+ rec.baselineHead = baseline.head;
969
+ let prelim = await validateTarget(deps, repoRoot, baseline.code_version, baseline.sandbox_id);
970
+ rec.cli = { source: prelim.cli.source, version: null };
971
+ rec.cli.version = await probeCliVersion(prelim.cli, deps, 5_000);
972
+ const lock = new UploadLock(deps, paths.runDir, "worker", cmd.ticket);
973
+ await ensurePrivateDirectory(deps.fs, paths.runDir);
974
+ const waited = await lock.acquire(SFCC_UPLOAD_LOCK_WAIT_SECONDS * 1000, ctxBase.isCancelled);
975
+ if (waited === null)
976
+ throw unavailableStop(ctxBase.isCancelled() ? "upload_failed" : "upload_lock_timeout");
977
+ rec.lockWaitMs = waited;
978
+ let staging = null;
979
+ try {
980
+ // Re-read the baseline under the lock: a full upload may have replaced it.
981
+ const again = await readBaseline(deps, paths.runDir, runId);
982
+ if (again === null)
983
+ throw unavailableStop("no_run_baseline");
984
+ if (again.head !== baseline.head || again.code_version !== baseline.code_version || again.sandbox_id !== baseline.sandbox_id) {
985
+ baseline = again;
986
+ rec.sandboxId = baseline.sandbox_id;
987
+ rec.codeVersion = baseline.code_version;
988
+ rec.baselineHead = baseline.head;
989
+ prelim = await validateTarget(deps, repoRoot, baseline.code_version, baseline.sandbox_id);
990
+ }
991
+ const skips = { count: 0 };
992
+ const plan = await planWorkerChanges(deps, repoRoot, cmd.head, baseline, prelim.cfg.cartridgeFilter, skips, rec);
993
+ rec.skipped = skips.count;
994
+ rec.deletesFailed += plan.unsafeDeletes;
995
+ if (plan.files.length === 0 && plan.deletes.length === 0) {
996
+ return { outcome: "nothing_to_upload" };
997
+ }
998
+ const sessionDir = path.join(sfccUploadPaths(paths.runDir).staging, deps.randomHex(8));
999
+ await ensurePrivateDirectory(deps.fs, sessionDir);
1000
+ staging = sessionDir;
1001
+ const archives = plan.files.length > 0 ? await buildArchives(deps, repoRoot, sessionDir, plan.files) : [];
1002
+ const ctx = {
1003
+ deps,
1004
+ startMs: rec.startedAtMs,
1005
+ commandMs: SFCC_UPLOAD_WORKER_COMMAND_SECONDS * 1000,
1006
+ budgetMs: SFCC_UPLOAD_WORKER_BUDGET_SECONDS * 1000,
1007
+ callCapMs: SFCC_UPLOAD_WORKER_CALL_SECONDS * 1000,
1008
+ spentMs: 0,
1009
+ abort: ctxBase.abort,
1010
+ get cancelled() {
1011
+ return ctxBase.isCancelled();
1012
+ },
1013
+ cwd: repoRoot,
1014
+ cli: prelim.cli,
1015
+ env: b2cEnv(deps.env),
1016
+ };
1017
+ const session = {
1018
+ ctx,
1019
+ rec,
1020
+ target: { host: prelim.host, version: baseline.code_version },
1021
+ digest: runDigest(runId),
1022
+ activationAvailable: prelim.cfg.activationAvailable,
1023
+ };
1024
+ let n = 0;
1025
+ for (const archive of archives) {
1026
+ n += 1;
1027
+ await uploadArchive(session, archive, n);
1028
+ }
1029
+ // Deletes are advisory after extraction: a failure here never fails the upload.
1030
+ let attempted = 0;
1031
+ for (const d of plan.deletes) {
1032
+ if (attempted >= SFCC_UPLOAD_MAX_WORKER_DELETES) {
1033
+ rec.deletesDeferred += 1;
1034
+ continue;
1035
+ }
1036
+ const allowed = Math.min(ctx.callCapMs, ctx.budgetMs - ctx.spentMs, remainingCommandMs(ctx) - CLEANUP_RESERVE_MS);
1037
+ if (allowed <= 0) {
1038
+ rec.deletesDeferred += 1;
1039
+ continue;
1040
+ }
1041
+ attempted += 1;
1042
+ let result = "failed";
1043
+ try {
1044
+ result = await runB2c(ctx, b2cArgs.rm(session.target, `${session.target.version}/${d.cartridge}/${d.rel}`));
1045
+ }
1046
+ catch (err) {
1047
+ if (err instanceof Stop)
1048
+ throw err;
1049
+ }
1050
+ if (result === "ok")
1051
+ rec.filesDeleted += 1;
1052
+ else {
1053
+ rec.deletesFailed += 1;
1054
+ rec.hints.add("stale_files");
1055
+ }
1056
+ }
1057
+ if (rec.deletesFailed > 0)
1058
+ rec.hints.add("stale_files");
1059
+ await activate(session);
1060
+ return { outcome: "uploaded" };
1061
+ }
1062
+ finally {
1063
+ await removeStaging(deps, staging);
1064
+ await lock.release();
1065
+ }
1066
+ }
1067
+ async function planWorkerChanges(deps, repoRoot, head, baseline, filter, skips, rec) {
1068
+ let baseSha;
1069
+ try {
1070
+ const ancestor = await git(deps, repoRoot, ["merge-base", "--is-ancestor", baseline.head, head], { okCodes: [0, 1, 128] });
1071
+ if (ancestor.exitCode === 0) {
1072
+ rec.diffBase = "baseline";
1073
+ baseSha = baseline.head;
1074
+ }
1075
+ else {
1076
+ const branch = baseBranchFrom(deps.env);
1077
+ let found = null;
1078
+ if (branch !== null) {
1079
+ for (const ref of [`refs/remotes/origin/${branch}`, `refs/heads/${branch}`]) {
1080
+ const r = await git(deps, repoRoot, ["merge-base", head, ref], { okCodes: [0, 1, 128] });
1081
+ const sha = r.stdout.trim();
1082
+ if (r.exitCode === 0 && isFullCommitShaLike(sha)) {
1083
+ found = sha;
1084
+ break;
1085
+ }
1086
+ }
1087
+ }
1088
+ if (found === null)
1089
+ throw unavailableStop("base_unresolved");
1090
+ rec.diffBase = "merge_base";
1091
+ baseSha = found;
1092
+ }
1093
+ rec.diffBaseSha = baseSha;
1094
+ const diff = parseDiffRaw((await git(deps, repoRoot, ["diff", "--raw", "-z", "--no-renames", baseSha, head])).stdout);
1095
+ const headEntries = parseLsTree((await git(deps, repoRoot, ["ls-tree", "-r", "-z", head])).stdout);
1096
+ const headRoots = discoverCartridges(headEntries, filter, skips);
1097
+ const changedPaths = new Set(diff.filter((d) => d.status !== "D").map((d) => d.path));
1098
+ const deletedPaths = diff.filter((d) => d.status === "D").map((d) => d.path);
1099
+ const files = planFromTree(headEntries, headRoots, changedPaths, skips);
1100
+ const deletes = [];
1101
+ let unsafeDeletes = 0;
1102
+ let allRoots = headRoots;
1103
+ if (deletedPaths.length > 0) {
1104
+ const baseEntries = parseLsTree((await git(deps, repoRoot, ["ls-tree", "-r", "-z", baseSha])).stdout);
1105
+ const baseRoots = discoverCartridges(baseEntries, filter, { count: 0 });
1106
+ const seen = new Set(headRoots.map((r) => r.root));
1107
+ allRoots = [...headRoots, ...baseRoots.filter((r) => !seen.has(r.root))];
1108
+ for (const p of deletedPaths) {
1109
+ const owned = owningCartridge(allRoots, p);
1110
+ if (owned === null)
1111
+ continue;
1112
+ const verdict = judgeRelPath(owned.rel);
1113
+ if (verdict === "skip") {
1114
+ skips.count += 1;
1115
+ continue;
1116
+ }
1117
+ if (verdict === "unsafe" || !validDeleteSegments(owned.rel)) {
1118
+ unsafeDeletes += 1;
1119
+ continue;
1120
+ }
1121
+ deletes.push({ cartridge: owned.cart.name, rel: owned.rel });
1122
+ }
1123
+ }
1124
+ if (hasNameConflict(allRoots))
1125
+ throw unavailableStop("cartridge_name_conflict");
1126
+ return { cartridges: allRoots.map((r) => r.name), files, deletes, unsafeDeletes };
1127
+ }
1128
+ catch (err) {
1129
+ if (err instanceof Stop)
1130
+ throw err;
1131
+ throw unavailableStop("git_failed");
1132
+ }
1133
+ }
1134
+ // ---------------------------------------------------------------------------
1135
+ // Full (driver) form
1136
+ // ---------------------------------------------------------------------------
1137
+ async function runFullForm(deps, cmd, rec, ctxBase) {
1138
+ rec.head = cmd.head;
1139
+ const tag = deps.env[OWNERSHIP_TAG_ENV];
1140
+ if (typeof tag === "string" && tag.length > 0)
1141
+ throw refusedStop("driver_only");
1142
+ const repoName = await deps.resolveRepoName();
1143
+ if (repoName === null)
1144
+ throw refusedStop("repo_unresolved");
1145
+ let record;
1146
+ try {
1147
+ record = await deps.readRecord(repoName);
1148
+ }
1149
+ catch {
1150
+ record = { state: "unusable" };
1151
+ }
1152
+ // The mode is never checked; `credential_ref` is never read.
1153
+ if (record.state !== "ok" || record.record.sfcc === undefined)
1154
+ throw refusedStop("no_approved_sandbox");
1155
+ const sandboxId = record.record.sfcc.sandbox_id;
1156
+ rec.sandboxId = sandboxId;
1157
+ const repoRoot = deps.resolveRepoRoot();
1158
+ if (repoRoot === null)
1159
+ throw unavailableStop("git_failed");
1160
+ const prelim = await validateTarget(deps, repoRoot, null, sandboxId);
1161
+ rec.codeVersion = prelim.version;
1162
+ rec.cli = { source: prelim.cli.source, version: await probeCliVersion(prelim.cli, deps, 5_000) };
1163
+ const paths = epicServerRunPaths(deps.homedir(), { epicKey: cmd.epicKey, epicRunId: cmd.epicRunId }, deps.tmpdir());
1164
+ if (paths === null)
1165
+ throw unavailableStop("git_failed");
1166
+ // Resolve files from the supplied commit; the checkout is neither required to be at it nor switched.
1167
+ const skips = { count: 0 };
1168
+ let files;
1169
+ try {
1170
+ await git(deps, repoRoot, ["cat-file", "-e", `${cmd.head}^{commit}`]);
1171
+ const entries = parseLsTree((await git(deps, repoRoot, ["ls-tree", "-r", "-z", cmd.head])).stdout);
1172
+ const roots = discoverCartridges(entries, prelim.cfg.cartridgeFilter, skips);
1173
+ if (hasNameConflict(roots))
1174
+ throw unavailableStop("cartridge_name_conflict");
1175
+ files = planFromTree(entries, roots, null, skips);
1176
+ }
1177
+ catch (err) {
1178
+ if (err instanceof Stop)
1179
+ throw err;
1180
+ throw unavailableStop("git_failed");
1181
+ }
1182
+ rec.skipped = skips.count;
1183
+ await ensurePrivateDirectory(deps.fs, paths.runDir);
1184
+ const lock = new UploadLock(deps, paths.runDir, "driver", null);
1185
+ const waited = await lock.acquire(SFCC_UPLOAD_FULL_LOCK_WAIT_SECONDS * 1000, ctxBase.isCancelled);
1186
+ if (waited === null)
1187
+ throw unavailableStop(ctxBase.isCancelled() ? "upload_failed" : "upload_lock_timeout");
1188
+ rec.lockWaitMs = waited;
1189
+ let staging = null;
1190
+ try {
1191
+ const ctx = {
1192
+ deps,
1193
+ startMs: rec.startedAtMs,
1194
+ commandMs: SFCC_UPLOAD_FULL_COMMAND_SECONDS * 1000,
1195
+ budgetMs: SFCC_UPLOAD_FULL_BUDGET_SECONDS * 1000,
1196
+ callCapMs: SFCC_UPLOAD_FULL_CALL_SECONDS * 1000,
1197
+ spentMs: 0,
1198
+ abort: ctxBase.abort,
1199
+ get cancelled() {
1200
+ return ctxBase.isCancelled();
1201
+ },
1202
+ cwd: repoRoot,
1203
+ cli: prelim.cli,
1204
+ env: b2cEnv(deps.env),
1205
+ };
1206
+ const session = {
1207
+ ctx,
1208
+ rec,
1209
+ target: { host: prelim.host, version: prelim.version },
1210
+ digest: runDigest(cmd.epicRunId),
1211
+ activationAvailable: prelim.cfg.activationAvailable,
1212
+ };
1213
+ if (files.length === 0) {
1214
+ rec.hints.add("empty_snapshot");
1215
+ }
1216
+ else {
1217
+ const sessionDir = path.join(sfccUploadPaths(paths.runDir).staging, deps.randomHex(8));
1218
+ await ensurePrivateDirectory(deps.fs, sessionDir);
1219
+ staging = sessionDir;
1220
+ // Every archive is built and validated before the first destructive operation.
1221
+ const archives = await buildArchives(deps, repoRoot, sessionDir, files);
1222
+ let n = 0;
1223
+ for (const archive of archives) {
1224
+ n += 1;
1225
+ // Clear files deleted on branches; a failure is ignored (the budget still applies).
1226
+ await runB2c(ctx, b2cArgs.rm(session.target, `${session.target.version}/${archive.cartridge}`));
1227
+ await uploadArchive(session, archive, n);
1228
+ }
1229
+ await activate(session);
1230
+ }
1231
+ const baseline = {
1232
+ version: 1,
1233
+ epic_key: cmd.epicKey,
1234
+ epic_run_id: cmd.epicRunId,
1235
+ sandbox_id: sandboxId,
1236
+ code_version: prelim.version,
1237
+ head: cmd.head,
1238
+ uploaded_at: new Date(deps.now()).toISOString(),
1239
+ };
1240
+ try {
1241
+ await writePrivateFileAtomic(deps.fs, sfccUploadPaths(paths.runDir).baseline, `${JSON.stringify(baseline, null, 2)}\n`);
1242
+ }
1243
+ catch {
1244
+ throw unavailableStop("baseline_write_failed");
1245
+ }
1246
+ return { outcome: "uploaded" };
1247
+ }
1248
+ finally {
1249
+ await removeStaging(deps, staging);
1250
+ await lock.release();
1251
+ }
1252
+ }
1253
+ // ---------------------------------------------------------------------------
1254
+ // Check form
1255
+ // ---------------------------------------------------------------------------
1256
+ /**
1257
+ * Read-only readiness: no network call, no write, no lock, no staging, and no
1258
+ * npx run. Safe for child 3 to call in-process.
1259
+ */
1260
+ export async function checkSfccUpload(input, deps) {
1261
+ const missing = new Set();
1262
+ const cfg = await readSfccEffectiveConfig(input.repoRoot, input.env, deps);
1263
+ if (cfg.unreadable)
1264
+ missing.add("config_unreadable");
1265
+ const host = checkHost(cfg.hostRaw, input.approvedSandboxId ?? null);
1266
+ if (!host.ok)
1267
+ missing.add(host.reason);
1268
+ let codeVersion = null;
1269
+ if (cfg.codeVersionRaw === null)
1270
+ missing.add("code_version_missing");
1271
+ else if (!isSafeSfccPathSegment(cfg.codeVersionRaw))
1272
+ missing.add("config_unreadable");
1273
+ else
1274
+ codeVersion = cfg.codeVersionRaw;
1275
+ if (cfg.auth === "missing")
1276
+ missing.add("credentials_missing");
1277
+ if (cfg.auth === "interactive")
1278
+ missing.add("interactive_auth_required");
1279
+ const cliDeps = { ...deps, env: input.env };
1280
+ const cli = await resolveCli(input.repoRoot, cliDeps);
1281
+ let cliOut = { source: "none", version: null };
1282
+ if (!cli.ok)
1283
+ missing.add(cli.reason);
1284
+ else
1285
+ cliOut = { source: cli.source, version: await probeCliVersion(cli, deps, CHECK_DEADLINE_MS) };
1286
+ const sorted = [...missing].sort();
1287
+ return {
1288
+ verb: "sfcc-upload",
1289
+ form: "check",
1290
+ outcome: sorted.length === 0 ? "ready" : "unavailable",
1291
+ missing: sorted,
1292
+ cli: cliOut,
1293
+ credential_sources: { dw_json: cfg.dwJson, env: cfg.envPresent ? "present" : "absent" },
1294
+ code_version: codeVersion,
1295
+ activation: cfg.activationAvailable ? "available" : "unavailable",
1296
+ epic_server_mode: "unknown",
1297
+ };
1298
+ }
1299
+ async function runCheckForm(deps) {
1300
+ const empty = {
1301
+ verb: "sfcc-upload",
1302
+ form: "check",
1303
+ outcome: "unavailable",
1304
+ missing: ["config_unreadable"],
1305
+ cli: { source: "none", version: null },
1306
+ credential_sources: { dw_json: "unreadable", env: "absent" },
1307
+ code_version: null,
1308
+ activation: "unavailable",
1309
+ epic_server_mode: "unknown",
1310
+ };
1311
+ try {
1312
+ const repoRoot = deps.resolveRepoRoot() ?? deps.cwd();
1313
+ let mode = "unknown";
1314
+ let approved = null;
1315
+ const repoName = await deps.resolveRepoName();
1316
+ if (repoName !== null) {
1317
+ let record;
1318
+ try {
1319
+ record = await deps.readRecord(repoName);
1320
+ }
1321
+ catch {
1322
+ record = { state: "unusable" };
1323
+ }
1324
+ if (record.state === "ok") {
1325
+ mode = record.record.mode;
1326
+ approved = record.record.sfcc?.sandbox_id ?? null;
1327
+ }
1328
+ else if (record.state === "absent")
1329
+ mode = "none";
1330
+ }
1331
+ let timer;
1332
+ const deadline = new Promise((resolve) => {
1333
+ timer = setTimeout(() => resolve(null), CHECK_DEADLINE_MS);
1334
+ timer.unref();
1335
+ });
1336
+ const result = await Promise.race([checkSfccUpload({ repoRoot, env: deps.env, approvedSandboxId: approved }, deps), deadline]).finally(() => clearTimeout(timer));
1337
+ deps.stdout(JSON.stringify(result === null ? empty : { ...result, epic_server_mode: mode }));
1338
+ }
1339
+ catch {
1340
+ deps.stdout(JSON.stringify(empty));
1341
+ }
1342
+ return 0;
1343
+ }
1344
+ // ---------------------------------------------------------------------------
1345
+ // Entry point
1346
+ // ---------------------------------------------------------------------------
1347
+ function commandText(cmd) {
1348
+ if (cmd.form === "worker")
1349
+ return `epic-implementer epic-server sfcc-upload --ticket ${cmd.ticket} --head ${cmd.head}`;
1350
+ if (cmd.form === "full") {
1351
+ return `epic-implementer epic-server sfcc-upload --full --epic ${cmd.epicKey} --epic-run-id ${cmd.epicRunId} --head ${cmd.head}`;
1352
+ }
1353
+ return "epic-implementer epic-server sfcc-upload --check";
1354
+ }
1355
+ /**
1356
+ * Run one form. Owns result emission and the numeric exit status. It never
1357
+ * throws: an unexpected exception is `unavailable` / `upload_failed`.
1358
+ */
1359
+ export async function runSfccUpload(cmd, deps) {
1360
+ if (cmd.form === "check")
1361
+ return runCheckForm(deps);
1362
+ const rec = new UploadRecord(cmd.form, commandText(cmd), deps.now);
1363
+ const fin = new Finalizer(deps, rec);
1364
+ const abort = new AbortController();
1365
+ let cancelled = false;
1366
+ const unsubscribe = deps.onSignal(() => {
1367
+ cancelled = true;
1368
+ abort.abort();
1369
+ });
1370
+ const base = { abort, isCancelled: () => cancelled };
1371
+ try {
1372
+ const result = cmd.form === "worker" ? await runWorkerForm(deps, cmd, rec, base) : await runFullForm(deps, cmd, rec, base);
1373
+ return fin.finish(result.outcome);
1374
+ }
1375
+ catch (err) {
1376
+ if (err instanceof Stop)
1377
+ return fin.finish(err.outcome, err.reason);
1378
+ return fin.finish("unavailable", "upload_failed");
1379
+ }
1380
+ finally {
1381
+ unsubscribe();
1382
+ }
1383
+ }
1384
+ // ---------------------------------------------------------------------------
1385
+ // Production dependencies
1386
+ // ---------------------------------------------------------------------------
1387
+ const GIT_OUTPUT_CAP = 256 * 1024 * 1024;
1388
+ function killGroup(pid, signal) {
1389
+ if (typeof pid !== "number" || pid <= 1)
1390
+ return;
1391
+ try {
1392
+ process.kill(-pid, signal);
1393
+ }
1394
+ catch {
1395
+ try {
1396
+ process.kill(pid, signal);
1397
+ }
1398
+ catch {
1399
+ /* already gone */
1400
+ }
1401
+ }
1402
+ }
1403
+ export const defaultSfccB2cRunner = (argv, options) => new Promise((resolve) => {
1404
+ const [file, ...args] = argv;
1405
+ if (file === undefined) {
1406
+ resolve({ exitCode: null, timedOut: false });
1407
+ return;
1408
+ }
1409
+ let settled = false;
1410
+ let timedOut = false;
1411
+ let child;
1412
+ try {
1413
+ // Shell-free, stdin closed, its own process group. Output is drained and discarded.
1414
+ child = spawn(file, args, { cwd: options.cwd, env: options.env, stdio: ["ignore", "pipe", "pipe"], detached: true });
1415
+ }
1416
+ catch {
1417
+ resolve({ exitCode: null, timedOut: false });
1418
+ return;
1419
+ }
1420
+ child.stdout?.resume();
1421
+ child.stderr?.resume();
1422
+ const kill = () => {
1423
+ killGroup(child.pid, "SIGTERM");
1424
+ setTimeout(() => killGroup(child.pid, "SIGKILL"), 2_000).unref();
1425
+ };
1426
+ const timer = setTimeout(() => {
1427
+ timedOut = true;
1428
+ kill();
1429
+ }, options.timeoutMs);
1430
+ const onAbort = () => kill();
1431
+ options.signal?.addEventListener("abort", onAbort, { once: true });
1432
+ const done = (exitCode) => {
1433
+ if (settled)
1434
+ return;
1435
+ settled = true;
1436
+ clearTimeout(timer);
1437
+ options.signal?.removeEventListener("abort", onAbort);
1438
+ resolve({ exitCode, timedOut });
1439
+ };
1440
+ child.on("error", () => done(null));
1441
+ child.on("close", (code) => done(code));
1442
+ });
1443
+ export const defaultSfccGitRunner = (args, options) => new Promise((resolve) => {
1444
+ let settled = false;
1445
+ let timedOut = false;
1446
+ const chunks = [];
1447
+ let total = 0;
1448
+ let child;
1449
+ try {
1450
+ child = spawn("git", args, {
1451
+ cwd: options.cwd,
1452
+ env: { ...process.env, ...(options.env ?? {}) },
1453
+ stdio: [options.input !== undefined ? "pipe" : "ignore", "pipe", "ignore"],
1454
+ });
1455
+ }
1456
+ catch {
1457
+ resolve({ exitCode: null, stdout: "", timedOut: false });
1458
+ return;
1459
+ }
1460
+ child.stdout?.on("data", (d) => {
1461
+ total += d.length;
1462
+ if (total <= GIT_OUTPUT_CAP)
1463
+ chunks.push(d);
1464
+ });
1465
+ if (options.input !== undefined) {
1466
+ child.stdin?.on("error", () => undefined);
1467
+ child.stdin?.end(options.input);
1468
+ }
1469
+ const timer = setTimeout(() => {
1470
+ timedOut = true;
1471
+ child.kill("SIGKILL");
1472
+ }, options.timeoutMs);
1473
+ const done = (exitCode) => {
1474
+ if (settled)
1475
+ return;
1476
+ settled = true;
1477
+ clearTimeout(timer);
1478
+ resolve({ exitCode: total > GIT_OUTPUT_CAP ? null : exitCode, stdout: Buffer.concat(chunks).toString("utf8"), timedOut });
1479
+ };
1480
+ child.on("error", () => done(null));
1481
+ child.on("close", (code) => done(code));
1482
+ });
1483
+ /** Build the production dependencies from the dispatcher's own seams. */
1484
+ export function createDefaultSfccUploadDeps(base) {
1485
+ const proc = createDefaultEpicServerProcessDeps();
1486
+ return {
1487
+ ...base,
1488
+ fs: createDefaultEpicServerStateFs(),
1489
+ git: defaultSfccGitRunner,
1490
+ b2c: defaultSfccB2cRunner,
1491
+ now: () => Date.now(),
1492
+ sleep: (ms) => new Promise((r) => setTimeout(r, ms)),
1493
+ randomHex: (bytes) => randomBytes(bytes).toString("hex"),
1494
+ pid: process.pid,
1495
+ isPidAlive: (pid) => {
1496
+ try {
1497
+ process.kill(pid, 0);
1498
+ return true;
1499
+ }
1500
+ catch (err) {
1501
+ return err.code === "ESRCH" ? false : null;
1502
+ }
1503
+ },
1504
+ readProcessStartTime: (pid) => readProcessStartTime(pid, proc),
1505
+ statMeta: async (p) => {
1506
+ try {
1507
+ const st = await nodeFs.lstat(p);
1508
+ return { size: st.size, mtimeMs: st.mtimeMs };
1509
+ }
1510
+ catch {
1511
+ return null;
1512
+ }
1513
+ },
1514
+ readText: (p) => nodeFs.readFile(p, "utf8"),
1515
+ readBinary: (p) => nodeFs.readFile(p),
1516
+ cli: {
1517
+ realpath: (p) => nodeFs.realpath(p),
1518
+ isExecutable: async (p) => {
1519
+ try {
1520
+ await nodeFs.access(p, fsConstants.X_OK);
1521
+ return true;
1522
+ }
1523
+ catch {
1524
+ return false;
1525
+ }
1526
+ },
1527
+ findOnPath: async (name, env) => {
1528
+ for (const dir of (env.PATH ?? "").split(path.delimiter)) {
1529
+ if (dir === "" || !path.isAbsolute(dir))
1530
+ continue;
1531
+ const candidate = path.join(dir, name);
1532
+ try {
1533
+ await nodeFs.access(candidate, fsConstants.X_OK);
1534
+ return candidate;
1535
+ }
1536
+ catch {
1537
+ /* next */
1538
+ }
1539
+ }
1540
+ return null;
1541
+ },
1542
+ nodeVersion: () => process.versions.node,
1543
+ probeVersion: (bin, timeoutMs) => new Promise((resolve) => {
1544
+ try {
1545
+ execFile(bin, ["--version"], { timeout: timeoutMs, maxBuffer: 64 * 1024, env: b2cEnv(base.env) }, (err, stdout) => {
1546
+ if (err)
1547
+ return resolve(null);
1548
+ const m = /(\d{1,4}\.\d{1,4}\.\d{1,4})/.exec(String(stdout));
1549
+ resolve(m ? m[1] : null);
1550
+ });
1551
+ }
1552
+ catch {
1553
+ resolve(null);
1554
+ }
1555
+ }),
1556
+ },
1557
+ onSignal: (handler) => {
1558
+ const signals = ["SIGTERM", "SIGINT", "SIGHUP"];
1559
+ for (const s of signals)
1560
+ process.on(s, handler);
1561
+ return () => {
1562
+ for (const s of signals)
1563
+ process.off(s, handler);
1564
+ };
1565
+ },
1566
+ };
1567
+ }