@backifydev/cli 0.4.3 → 0.4.5

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/dist/index.js CHANGED
@@ -46,12 +46,12 @@ var init_delivery = __esm({
46
46
  "use strict";
47
47
  deliveryInstructions = `# Backify application delivery and prompt history
48
48
 
49
- Instruction version: 20
50
- Versioned guide: https://agent.backify.dev/v20/delivery.md
49
+ Instruction version: 21
50
+ Versioned guide: https://agent.backify.dev/v21/delivery.md
51
51
 
52
52
  ## Environment and documentation prerequisites
53
53
 
54
- Before installation or connection, read https://agent.backify.dev/v20 for execution capability checks, required endpoints (including https://docs.backify.dev), native permission requests, verified retries and fallback guidance. Follow the current tool's supported approval mechanism; never bypass restrictions. Read relevant capability documentation before implementation. Local validation must not depend on cloud deployment.
54
+ Before installation or connection, read https://agent.backify.dev/v21 for execution capability checks, required endpoints (including https://docs.backify.dev), native permission requests, verified retries and fallback guidance. Follow the current tool's supported approval mechanism; never bypass restrictions. Read relevant capability documentation before implementation. Local validation must not depend on cloud deployment.
55
55
 
56
56
  Before application implementation, all required setup checks and connected status must be verified OK. If any required check fails or remains unverified after supported recovery, stop setup and implementation; do not build a local website, minimal shell, placeholder, dependency-free fallback, or downloadable application archive. Report the blockers and recommend running the setup prompt in an AI coding tool such as Codex, Claude Code, or VS Code with GitHub Copilot agent mode, with terminal access, a persistent writable workspace, package installation, outbound HTTPS/DNS, and test execution enabled. Tool names alone do not guarantee readiness. Do not ask the application requirements question while setup is blocked. Later preview approval or deployment failures do not invalidate an already verified setup gate.
57
57
 
@@ -77,7 +77,7 @@ Initialize using App Id from the copied prompt and the current tool selection:
77
77
 
78
78
  npx @backifydev/cli@latest init --app <app-id> --agent <current-tool>
79
79
 
80
- For a tool without a built-in preset, replace --agent <current-tool> with --instruction-file <relative-path>. Read BACKIFY.md and the instruction file used by the current AI coding tool before changing application code. Create or update only instruction files used by that tool; never create files for other coding tools. Use --agent for a built-in tool preset or --instruction-file <relative-path> for the current tool's native instruction file, as described in the setup guide. Initialization installs this workflow alongside the persistent SDK instructions. Follow https://agent.backify.dev/v20 for rebuilt applications; use the guide matching instructionVersion in backify.config.ts (or the existing older workspace metadata). Do not silently upgrade its managed instruction version or overwrite instructions outside the managed block.
80
+ For a tool without a built-in preset, replace --agent <current-tool> with --instruction-file <relative-path>. Read BACKIFY.md and the instruction file used by the current AI coding tool before changing application code. Create or update only instruction files used by that tool; never create files for other coding tools. Use --agent for a built-in tool preset or --instruction-file <relative-path> for the current tool's native instruction file, as described in the setup guide. Initialization installs this workflow alongside the persistent SDK instructions. Follow https://agent.backify.dev/v21 for rebuilt applications; use the guide matching instructionVersion in backify.config.ts (or the existing older workspace metadata). Do not silently upgrade its managed instruction version or overwrite instructions outside the managed block.
81
81
 
82
82
  Run the following to discover the connected hosting target, repository, branch, reports, releases, and deployment failures:
83
83
 
@@ -123,9 +123,15 @@ After the required setup gate passes and application requirements are supplied,
123
123
 
124
124
  Start the application, wait for readiness, request the actual local application URL, and verify a representative user flow before shipping. Document safe seed data and local test identities where needed. A failed connection or required setup check must stop implementation, including local fallback. After setup passes, later preview approval or deployment failure must not prevent safe local testing; report those blockers separately without bypassing authorization. If requirements are missing after successful setup, ask the required final question without creating a minimal runnable shell. Never claim local readiness from a build or management-dashboard response alone.
125
125
 
126
- ## Verify, push, and deploy to preview
126
+ ## Verify, push, and deploy
127
127
 
128
- Plain deployment requests are preview-only. Requests such as "Now deploy", "deploy", "ship", "launch", or "merge and retry" do not authorize production. Approval to merge a remote commit, push source, retry deployment, or run checks applies only to that action and preserves the preview target. Never infer production intent from permissive policy, a healthy preview, or an existing production URL.
128
+ An application always has production. Preview and prototype are optional environments that exist only when they have been added. A release enters the earliest activated environment and is promoted through the activated ones in the order prototype, preview, production. Before shipping, list the application's environments:
129
+
130
+ npx @backifydev/cli@latest environments
131
+
132
+ A plain deployment request deploys to the earliest activated environment: prototype when it exists, otherwise preview, otherwise production. Tell the user where the release will land before shipping. When production is the only environment, say plainly that the deployment goes live in production. Add a pre-production stage with backify environments add preview|prototype only when the user asks for one; an added environment is billed through its own compute, database, and storage usage, so never add one unasked. Never remove an environment unless the user explicitly asks; removal takes it offline and requires the application slug as confirmation.
133
+
134
+ Requests such as "Now deploy", "deploy", "ship", "launch", or "merge and retry" do not authorize promoting a release beyond the earliest activated environment. Approval to merge a remote commit, push source, retry deployment, or run checks applies only to that action and preserves the same target environment. Never infer production intent from permissive policy, a healthy earlier environment, or an existing production URL.
129
135
 
130
136
  Run:
131
137
 
@@ -135,13 +141,19 @@ Fix relevant failures, then commit only application changes for this request usi
135
141
 
136
142
  npx @backifydev/cli@latest ship
137
143
 
138
- The CLI verifies the repository and branch, runs checks, pushes committed source using a short-lived repository-scoped credential, waits for the exact source's healthy preview, and returns the preview URL without requesting production publication. It never stages or commits files, force-pushes, changes hosting, fabricates preview testing, or bypasses approval. The legacy --preview-only flag is optional; preview is already the default.
144
+ The CLI verifies the repository and branch, runs checks, pushes committed source using a short-lived repository-scoped credential, waits for the exact source's healthy deployment in the earliest activated environment, and returns that environment's URL without promoting the release further. It never stages or commits files, force-pushes, changes hosting, fabricates testing, or bypasses approval. The --preview-only flag is optional; stopping after the first environment is already the default.
145
+
146
+ Promoting a release to the next activated environment requires an explicit user request, such as "promote this to preview" or "promote this to production". Only for that request run:
139
147
 
140
- Production requires an explicit user request to deploy to production, such as "deploy to production", "publish to production", or "promote this preview to production". Only for that request run:
148
+ npx @backifydev/cli@latest promote
149
+
150
+ Never pass --tested unless the user states that they tested the release. Use backify release-flow --json to read each environment's release, its checks, and what blocks the next promotion.
151
+
152
+ Production requires an explicit user request to deploy to production, such as "deploy to production", "publish to production", or "promote this preview to production", except when production is the application's only environment and is therefore where a plain deployment lands. Only for that explicit request run:
141
153
 
142
154
  npx @backifydev/cli@latest ship --production-deploy
143
155
 
144
- Production publication still follows existing Backify permissions, testing, and approval policy. If testing or approval is required, return the preview URL and explain the remaining action; never fabricate testing or bypass approval. Otherwise return the verified production URL and actual check results only after healthy activation. For a plain deployment request, stop at the verified healthy preview even when production testing and approval are not required. Inspect failures with the status command, fix them, and retry the same target without asking the user to perform routine deployment steps. Never invent a successful check or deployment.
156
+ Production publication still follows existing Backify permissions, testing, and approval policy. If testing or approval is required, return the earlier environment's URL and explain the remaining action; never fabricate testing or bypass approval. Otherwise return the verified production URL and actual check results only after healthy activation. For a plain deployment request, stop at the verified healthy deployment in the earliest activated environment even when production testing and approval are not required. A production-only application whose policy requires preview testing or production approval is refused with preview_required, because those rules need an environment before production: report the refusal, explain that adding a preview or prototype environment resolves it, and add one only when the user asks. An environment_not_activated response means the named environment has not been added; report it rather than targeting another environment. Inspect failures with the status command, fix them, and retry the same target without asking the user to perform routine deployment steps. Never invent a successful check or deployment.
145
157
 
146
158
  ## User-facing handoff
147
159
 
@@ -149,7 +161,7 @@ If setup is blocked, report the failed or unverified checks and recommend an AI
149
161
 
150
162
  Include the verified Local URL, exact start command, and local testing/sign-in steps even when cloud delivery is blocked. If local startup was not verified, say unavailable and explain the blocker.
151
163
 
152
- Include separate Preview URL and Production URL lines, using the actual URLs returned by CLI status or deployment results. Include both URLs when available. If either is unavailable, say not deployed or unavailable and explain why; never invent a URL or claim an unverified deployment is live. When production still serves an earlier release, label it as the existing production version and explain that the new changes are preview-only or awaiting approval.
164
+ Include a separate URL line for each activated environment, from Prototype URL, Preview URL and Production URL, using the actual URLs returned by CLI status or deployment results. Leave out environments the application has not added. If an activated environment's URL is unavailable, say not deployed or unavailable and explain why; never invent a URL or claim an unverified deployment is live. When production still serves an earlier release, label it as the existing production version and explain that the new changes are in an earlier environment or awaiting approval.
153
165
 
154
166
  If application requirements are missing after successful setup, finish the response with this exact question as its final line, without any text after it:
155
167
 
@@ -371,7 +383,7 @@ function validateProtectionConfig(value, fail, path = "protection") {
371
383
  if (access.denied !== void 0 && access.denied !== "403" && access.denied !== "404")
372
384
  fail(path + ".access.denied", 'Use "403" or "404"');
373
385
  if (access.environments !== void 0 && (!Array.isArray(access.environments) || access.environments.length === 0 || new Set(access.environments).size !== access.environments.length || access.environments.some((e) => !ENVIRONMENT_KINDS.includes(e))))
374
- fail(path + ".access.environments", "List environment kinds: preview, production");
386
+ fail(path + ".access.environments", "List environment kinds: prototype, preview, production");
375
387
  }
376
388
  }
377
389
  const page = value.blockedPage;
@@ -422,7 +434,7 @@ var init_protection = __esm({
422
434
  "../platform/dist/protection.js"() {
423
435
  "use strict";
424
436
  PROTECTION_MODES = ["off", "monitor", "standard", "strict"];
425
- ENVIRONMENT_KINDS = ["preview", "production"];
437
+ ENVIRONMENT_KINDS = ["prototype", "preview", "production"];
426
438
  PROTECTION_METHODS = ["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"];
427
439
  AI_CRAWLERS = Object.freeze([
428
440
  { token: "GPTBot", userAgent: "GPTBot", operator: "OpenAI" },
@@ -1223,6 +1235,13 @@ function validateLockfile(value) {
1223
1235
  }
1224
1236
  if (value.auth !== void 0 && (!object4(value.auth) || !Array.isArray(value.auth.providers) || !Array.isArray(value.auth.roles)))
1225
1237
  fail("auth requires providers and roles");
1238
+ else if (value.auth?.defaultProvider !== void 0 && (typeof value.auth.defaultProvider !== "string" || !value.auth.providers.includes(value.auth.defaultProvider)))
1239
+ fail("auth.defaultProvider must be one of auth.providers");
1240
+ if (object4(value.auth) && value.auth.session !== void 0) {
1241
+ const s = value.auth.session;
1242
+ if (!object4(s) || Object.keys(s).some((k) => !["duration", "refresh"].includes(k)) || s.duration !== void 0 && (typeof s.duration !== "string" || !/^(?:[1-9]|1[0-9]|2[0-4])h$/.test(s.duration)) || s.refresh !== void 0 && typeof s.refresh !== "boolean")
1243
+ fail("auth.session needs a 1h-24h duration and a boolean refresh, both optional");
1244
+ }
1226
1245
  if (!Array.isArray(value.secrets) || value.secrets.some((s) => typeof s !== "string"))
1227
1246
  fail("secrets must be an array of names");
1228
1247
  if (value.jobs?.length && !capabilities.has("jobs"))
@@ -1238,8 +1257,10 @@ function validateLockfile(value) {
1238
1257
  for (const issue2 of validateAppConfig({ app: { name: "lock-validation" }, kind: "worker", server: { entry: "server/index.ts" }, ...carried }))
1239
1258
  if (["config", "ai", "http", "mail", "integrations"].some((key) => issue2.path === key || issue2.path.startsWith(key + ".")))
1240
1259
  fail(issue2.path + ": " + issue2.message);
1260
+ if (value.workload !== void 0)
1261
+ validateWorkload(value.workload, fail);
1241
1262
  for (const key of Object.keys(value))
1242
- if (!["lockfileVersion", "app", "sdkVersion", "capabilities", "backend", "frontend", "jobs", "schedules", "events", "storage", "database", "auth", "secrets", "protection", "config", "ai", "http", "mail", "integrations", "retention"].includes(key))
1263
+ if (!["lockfileVersion", "app", "sdkVersion", "capabilities", "backend", "frontend", "jobs", "schedules", "events", "storage", "database", "auth", "secrets", "protection", "config", "ai", "http", "mail", "integrations", "retention", "workload"].includes(key))
1243
1264
  fail("Unknown lockfile field " + key);
1244
1265
  return errors;
1245
1266
  }
@@ -1264,7 +1285,29 @@ function serializeLockfile(lockfile) {
1264
1285
  const sort = (value) => Array.isArray(value) ? value.map(sort) : object4(value) ? Object.fromEntries(Object.keys(value).sort().filter((k) => value[k] !== void 0).map((k) => [k, sort(value[k])])) : value;
1265
1286
  return JSON.stringify(sort(lockfile), null, 2) + "\n";
1266
1287
  }
1267
- var LOCKFILE_VERSION, LOCKFILE_NAME, LOCKFILE_MAX_BYTES, HTTP_METHODS, object4, name, nonEmpty, sha256, ROUTE_PATH, CRON;
1288
+ function validateWorkload(value, fail) {
1289
+ if (!object4(value)) {
1290
+ fail("workload must be an object");
1291
+ return;
1292
+ }
1293
+ for (const [key, field] of Object.entries(value)) {
1294
+ if (key === "shape") {
1295
+ if (!WORKLOAD_SHAPES.includes(field))
1296
+ fail("workload.shape must be one of " + WORKLOAD_SHAPES.join(", "));
1297
+ } else if (key === "profile") {
1298
+ if (!TARGET_PROFILES.includes(field))
1299
+ fail("workload.profile must be one of " + TARGET_PROFILES.join(", "));
1300
+ } else if (key === "images") {
1301
+ if (!object4(field) || Object.entries(field).some(([role, digest]) => !["web", "worker", "migrate"].includes(role) || typeof digest !== "string" || digest.length !== 71 || !/^sha256:[0-9a-f]{64}$/.test(digest)))
1302
+ fail("workload.images must be an object mapping web, worker or migrate to an immutable SHA-256 digest");
1303
+ } else if (["ssr", "streaming", "batch", "accelerator"].includes(key)) {
1304
+ if (typeof field !== "boolean")
1305
+ fail("workload." + key + " must be true or false");
1306
+ } else
1307
+ fail("workload." + key + " must be absent; workload accepts shape, ssr, streaming, batch, accelerator, profile and images");
1308
+ }
1309
+ }
1310
+ var LOCKFILE_VERSION, LOCKFILE_NAME, LOCKFILE_MAX_BYTES, HTTP_METHODS, WORKLOAD_SHAPES, TARGET_PROFILES, object4, name, nonEmpty, sha256, ROUTE_PATH, CRON;
1268
1311
  var init_lockfile = __esm({
1269
1312
  "../platform/dist/lockfile.js"() {
1270
1313
  "use strict";
@@ -1275,6 +1318,8 @@ var init_lockfile = __esm({
1275
1318
  LOCKFILE_NAME = "backify.lock.json";
1276
1319
  LOCKFILE_MAX_BYTES = 2 * 1024 * 1024;
1277
1320
  HTTP_METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE"];
1321
+ WORKLOAD_SHAPES = ["static-artifact", "single-image", "separate-images"];
1322
+ TARGET_PROFILES = ["static-serving", "consumption", "dedicated"];
1278
1323
  object4 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
1279
1324
  name = (value) => typeof value === "string" && /^[a-z][a-z0-9-]{0,62}$/.test(value);
1280
1325
  nonEmpty = (value, max = 200) => typeof value === "string" && value.length > 0 && value.length <= max && !/[\x00-\x1f\x7f]/.test(value);
@@ -1701,7 +1746,7 @@ Run relevant tests, typechecking, lint, and builds using the repository's script
1701
1746
 
1702
1747
  ## Connected application delivery
1703
1748
 
1704
- For connected applications, follow \`BACKIFY.md\` and https://agent.backify.dev/v${INSTRUCTION_VERSION}/delivery.md before changing application code. Record every user build or modification request, including initial requirements, with attachment filenames only; never submit attachment contents or setup credentials. Verify checks and deploy to preview through the connected CLI workflow without bypassing testing, approval, or coding-tool permissions. Plain deployment requests are preview-only. Production requires an explicit user request to deploy to production; approval to merge, push, or retry does not authorize production. Use \`ship\` for preview and \`ship --production-deploy\` only for that explicit production request. Report only verified deployment URLs.
1749
+ For connected applications, follow \`BACKIFY.md\` and https://agent.backify.dev/v${INSTRUCTION_VERSION}/delivery.md before changing application code. Record every user build or modification request, including initial requirements, with attachment filenames only; never submit attachment contents or setup credentials. Verify checks and deploy through the connected CLI workflow without bypassing testing, approval, or coding-tool permissions. An application always has production; preview and prototype exist only when they have been added, and releases move through the activated environments in the order prototype, preview, production. Run \`backify environments\` before shipping and tell the user where the release will land. A plain deployment request deploys to the earliest activated environment with \`ship\`; that is production when production is the only environment. Promoting a release further toward production requires an explicit user request; approval to merge, push, or retry does not authorize it. Use \`ship --production-deploy\` only for an explicit production request. Add a pre-production stage with \`backify environments add preview|prototype\` only when the user asks for one; an added environment adds usage cost, so never add one unasked. Report only verified deployment URLs.
1705
1750
 
1706
1751
  ## Instruction maintenance
1707
1752
 
@@ -1769,7 +1814,7 @@ var init_dist = __esm({
1769
1814
  init_protection();
1770
1815
  init_auth_setup();
1771
1816
  init_operations();
1772
- INSTRUCTION_VERSION = 20;
1817
+ INSTRUCTION_VERSION = 21;
1773
1818
  SDK_PACKAGE = "@backifydev/sdk";
1774
1819
  DOCS_URL = "https://docs.backify.dev";
1775
1820
  MAIL_LIMITS = Object.freeze({
@@ -1914,6 +1959,479 @@ var init_project_metadata = __esm({
1914
1959
  }
1915
1960
  });
1916
1961
 
1962
+ // src/release-flow.ts
1963
+ var release_flow_exports = {};
1964
+ __export(release_flow_exports, {
1965
+ CommandError: () => CommandError,
1966
+ ENVIRONMENT_FLOW: () => ENVIRONMENT_FLOW,
1967
+ OPTIONAL_ENVIRONMENTS: () => OPTIONAL_ENVIRONMENTS,
1968
+ activatedEnvironments: () => activatedEnvironments,
1969
+ environmentsArguments: () => environmentsArguments,
1970
+ environmentsHelp: () => environmentsHelp,
1971
+ environmentsText: () => environmentsText,
1972
+ gateRows: () => gateRows,
1973
+ pad: () => pad,
1974
+ parse: () => parse,
1975
+ placementDetails: () => placementDetails,
1976
+ placementTargetsText: () => placementTargetsText,
1977
+ placementsText: () => placementsText,
1978
+ promote: () => promote,
1979
+ promoteArguments: () => promoteArguments,
1980
+ promoteHelp: () => promoteHelp,
1981
+ releaseFlow: () => releaseFlow,
1982
+ releaseFlowHelp: () => releaseFlowHelp,
1983
+ releaseFlowText: () => releaseFlowText,
1984
+ runEnvironments: () => runEnvironments,
1985
+ splitDetail: () => splitDetail
1986
+ });
1987
+ async function activatedEnvironments(call2, applicationId) {
1988
+ try {
1989
+ const view = await call2("/apps/" + applicationId + "/environments/options");
1990
+ return Array.isArray(view?.flow) && view.flow.every((kind2) => typeof kind2 === "string") && view.flow.length ? view.flow : void 0;
1991
+ } catch {
1992
+ return void 0;
1993
+ }
1994
+ }
1995
+ function parse(args2, command2, booleans, valued) {
1996
+ const flags = /* @__PURE__ */ new Set(), values = {}, positional = [];
1997
+ for (let index = 0; index < args2.length; index++) {
1998
+ const value = args2[index];
1999
+ if (booleans.includes(value)) {
2000
+ if (flags.has(value)) throw new Error("Duplicate option: " + value);
2001
+ flags.add(value);
2002
+ } else if (valued.includes(value)) {
2003
+ if (value in values || !args2[index + 1] || args2[index + 1].startsWith("--")) throw new Error("Specify one value for " + value);
2004
+ values[value] = args2[++index];
2005
+ } else if (value.startsWith("-")) throw new Error("Unknown option for " + command2 + ": " + value);
2006
+ else positional.push(value);
2007
+ }
2008
+ return { flags, values, positional };
2009
+ }
2010
+ function moveArguments(flags, values, positional) {
2011
+ const json2 = flags.has("--json"), yes = flags.has("--yes"), usage = "Use backify environments move <environment> --target <id> --window-start <ISO> --window-end <ISO> [--check] [--yes], or move status|start|abort|confirm <environment>.";
2012
+ if (values["--confirm"]) throw new Error(usage);
2013
+ const sub = positional[1]?.toLowerCase();
2014
+ const moveAction = sub === "status" || sub === "start" || sub === "abort" || sub === "confirm" ? sub : "request";
2015
+ const rawKind = moveAction === "request" ? positional[1] : positional[2];
2016
+ if (positional.length !== (moveAction === "request" ? 2 : 3) || !rawKind) throw new Error("Name the environment to move. " + usage);
2017
+ const kind2 = rawKind.toLowerCase();
2018
+ if (!ENVIRONMENT_FLOW.includes(kind2)) throw new Error("Unknown environment: " + rawKind + ". Use " + ENVIRONMENT_FLOW.join(", ") + ".");
2019
+ const target = values["--target"]?.toLowerCase(), active = values["--active"]?.toLowerCase(), start = values["--window-start"], end = values["--window-end"];
2020
+ if (moveAction !== "request" && (target || start || end || flags.has("--check"))) throw new Error("--target, --window-start, --window-end and --check apply only to requesting a move.");
2021
+ if (moveAction !== "confirm" && active) throw new Error("--active applies to environments move confirm.");
2022
+ if (moveAction === "status" && yes) throw new Error("move status takes only --app and --json.");
2023
+ if (moveAction === "request") {
2024
+ if (!target || !uuid3.test(target)) throw new Error("--target takes a deployment target ID.");
2025
+ if (!start || !end || Number.isNaN(Date.parse(start)) || Number.isNaN(Date.parse(end))) throw new Error("--window-start and --window-end take ISO date-times, for example 2026-11-20T22:00:00Z.");
2026
+ if (Date.parse(end) <= Date.parse(start)) throw new Error("--window-end must be after --window-start.");
2027
+ return { action: "move", moveAction, kind: kind2, target, windowStart: new Date(start).toISOString(), windowEnd: new Date(end).toISOString(), check: flags.has("--check"), yes, json: json2 };
2028
+ }
2029
+ if (moveAction === "confirm" && (!active || !uuid3.test(active))) throw new Error("--active takes the ID of the deployment target that is serving the environment.");
2030
+ return { action: "move", moveAction, kind: kind2, ...active ? { active } : {}, yes, json: json2 };
2031
+ }
2032
+ function moveBackArguments(flags, values, positional) {
2033
+ const usage = "Use backify environments move-back <environment> --window-start <ISO> --window-end <ISO> --confirm <application-slug>.";
2034
+ const rawKind = positional[1];
2035
+ if (positional.length !== 2 || !rawKind) throw new Error("Name the environment to move back. " + usage);
2036
+ const kind2 = rawKind.toLowerCase();
2037
+ if (!ENVIRONMENT_FLOW.includes(kind2)) throw new Error("Unknown environment: " + rawKind + ". Use " + ENVIRONMENT_FLOW.join(", ") + ".");
2038
+ if (values["--target"] || values["--active"] || flags.has("--check") || flags.has("--yes")) throw new Error("A move back goes to the hosting target the environment ran on before and is confirmed with --confirm <application-slug>. " + usage);
2039
+ const start = values["--window-start"], end = values["--window-end"];
2040
+ if (!start || !end || Number.isNaN(Date.parse(start)) || Number.isNaN(Date.parse(end))) throw new Error("--window-start and --window-end take ISO date-times, for example 2026-11-20T22:00:00Z.");
2041
+ if (Date.parse(end) <= Date.parse(start)) throw new Error("--window-end must be after --window-start.");
2042
+ return { action: "move-back", kind: kind2, windowStart: new Date(start).toISOString(), windowEnd: new Date(end).toISOString(), ...values["--confirm"] ? { confirm: values["--confirm"] } : {}, yes: false, json: flags.has("--json") };
2043
+ }
2044
+ function environmentsArguments(args2) {
2045
+ if (args2.includes("--help") || args2.includes("-h")) return "help";
2046
+ const { flags, values, positional } = parse(args2, "environments", ["--json", "--yes", "--check"], ["--app", "--confirm", "--target", "--window-start", "--window-end", "--active"]);
2047
+ const action = positional[0] ?? "list";
2048
+ if (action === "move") return moveArguments(flags, values, positional);
2049
+ if (action === "move-back") return moveBackArguments(flags, values, positional);
2050
+ if (action === "targets") {
2051
+ const kind3 = positional[1]?.toLowerCase();
2052
+ if (positional.length !== 2 || !kind3 || values["--confirm"] || values["--target"] || values["--window-start"] || values["--window-end"] || values["--active"] || flags.has("--yes") || flags.has("--check"))
2053
+ throw new Error("Use backify environments targets <environment> [--json].");
2054
+ if (!ENVIRONMENT_FLOW.includes(kind3)) throw new Error("Unknown environment: " + positional[1] + ". Use " + ENVIRONMENT_FLOW.join(", ") + ".");
2055
+ return { action, kind: kind3, yes: false, json: flags.has("--json") };
2056
+ }
2057
+ if (values["--window-start"] || values["--window-end"] || values["--active"]) throw new Error("--window-start, --window-end and --active apply to environments move.");
2058
+ if (action === "placement") {
2059
+ const json3 = flags.has("--json"), kind3 = positional[1]?.toLowerCase(), target = values["--target"]?.toLowerCase();
2060
+ if (values["--confirm"] || positional.length > 2) throw new Error("Use backify environments placement [<environment> --target <deployment-target-id|default> [--check] [--yes]].");
2061
+ if (!kind3) {
2062
+ if (target || flags.has("--check") || flags.has("--yes")) throw new Error("Name the environment to place: backify environments placement <environment> --target <deployment-target-id|default>.");
2063
+ return { action, yes: false, json: json3 };
2064
+ }
2065
+ if (!ENVIRONMENT_FLOW.includes(kind3)) throw new Error("Unknown environment: " + positional[1] + ". Use " + ENVIRONMENT_FLOW.join(", ") + ".");
2066
+ if (!target || target !== "default" && !uuid3.test(target)) throw new Error("--target takes a deployment target ID, or default for the application's own target.");
2067
+ return { action, kind: kind3, target, check: flags.has("--check"), yes: flags.has("--yes"), json: json3 };
2068
+ }
2069
+ if (flags.has("--check") || values["--target"]) throw new Error("--target and --check apply to environments placement.");
2070
+ if (action !== "list" && action !== "add" && action !== "remove") throw new Error("Unknown environments command: " + action + "\n\n" + environmentsHelp);
2071
+ const json2 = flags.has("--json");
2072
+ if (action === "list") {
2073
+ if (positional.length > 1 || flags.has("--yes") || values["--confirm"]) throw new Error("backify environments takes only --app and --json.\n\n" + environmentsHelp);
2074
+ return { action, yes: false, json: json2 };
2075
+ }
2076
+ const kind2 = positional[1]?.toLowerCase();
2077
+ if (positional.length !== 2 || !kind2) throw new Error(`Use backify environments ${action} <preview|prototype>.`);
2078
+ if (kind2 === "production") throw new Error(action === "add" ? "Production always exists. Add preview or prototype." : "Production cannot be removed. Delete the application instead.");
2079
+ if (!OPTIONAL_ENVIRONMENTS.includes(kind2)) throw new Error(`Unknown environment: ${positional[1]}. Use backify environments ${action} <preview|prototype>.`);
2080
+ if (action === "add" && values["--confirm"]) throw new Error("--confirm applies to environments remove. Use --yes to add without the prompt.");
2081
+ if (action === "remove" && flags.has("--yes")) throw new Error("Removing an environment is confirmed with --confirm <application-slug>, not --yes.");
2082
+ return { action, kind: kind2, confirm: values["--confirm"], yes: flags.has("--yes"), json: json2 };
2083
+ }
2084
+ function pad(rows) {
2085
+ const widths = rows[0].map((_, column) => Math.max(...rows.map((row) => row[column].length)));
2086
+ return rows.map((row) => row.map((cell, column) => column === row.length - 1 ? cell : cell.padEnd(widths[column])).join(" ").trimEnd());
2087
+ }
2088
+ function environmentsText(view) {
2089
+ const rows = [["ENVIRONMENT", "STATE", "HOSTNAME", "BILLING"], ...view.options.map((option2) => [option2.kind, option2.activated ? "activated" : "not activated", option2.hostname, option2.billing])];
2090
+ const addable = view.options.filter((option2) => !option2.activated).map((option2) => option2.kind);
2091
+ return [
2092
+ "Release flow: " + flowText(view.flow),
2093
+ "",
2094
+ ...pad(rows),
2095
+ ...addable.length ? ["", "Add one with backify environments add <" + addable.join("|") + ">."] : []
2096
+ ].join("\n");
2097
+ }
2098
+ function splitDetail(detail) {
2099
+ const text2 = (detail ?? "").trim(), match = /^(.*?)\s*\(([a-z][a-z0-9_]*_[a-z0-9_]+)\)\.?$/s.exec(text2);
2100
+ return match ? { message: match[1].trim(), code: match[2] } : { message: text2, code: null };
2101
+ }
2102
+ function placementDetails(item) {
2103
+ const lines = [];
2104
+ if (item.workloads?.length) lines.push(" workloads: " + item.workloads.map((workload) => (workloadRoles[workload.role] ?? workload.role) + " on " + (workloadProfiles[workload.profile] ?? workload.profile)).join("; "));
2105
+ if (item.foundation) lines.push(" foundation: " + (foundationModes[item.foundation.mode] ?? item.foundation.mode) + "; " + (foundationSeparations[item.foundation.separation] ?? item.foundation.separation));
2106
+ if (item.workloadConformance) {
2107
+ const refusal = splitDetail(item.workloadConformance);
2108
+ lines.push(" attention: " + refusal.message + (refusal.code ? " (" + refusal.code + ")" : ""));
2109
+ }
2110
+ return lines;
2111
+ }
2112
+ function placementsText(placements) {
2113
+ const rows = [["ENVIRONMENT", "HOSTING", "TARGET", "REGION", "RUNTIME", "DELIVERY"], ...placements.map((item) => [item.kind, hostingText(item.hosting), (item.targetName ?? "-") + (item.ownTarget ? " (own target)" : sourceText(item.targetSource)), item.region ?? "-", runtimeText(item.runtime), deliveryText(item.delivery)])];
2114
+ const locations = placements.flatMap((item) => ["", item.name + ":", ...item.locations.map((location) => " " + location.kind.padEnd(9) + " " + location.boundary + (location.region ? " (" + location.region + ")" : "") + ": " + location.detail), ...placementDetails(item)]);
2115
+ return [...pad(rows), ...locations].join("\n");
2116
+ }
2117
+ function placementTargetsText(kind2, result) {
2118
+ if (!result.targets.length) return "There are no hosting targets in this organization.";
2119
+ const rows = [["TARGET", "ID", "REGION", "HOSTING", "STATE", "REASON"], ...result.targets.map((target) => [target.name + (target.applicationTarget ? " (application)" : ""), target.deploymentTargetId, target.region, hostingText(target.hosting), targetState(target), target.eligible ? "" : splitDetail(target.reason).message])];
2120
+ const hints = [
2121
+ ...result.targets.some((target) => !target.current && target.eligible && !target.moveRequired) ? ["Place it with backify environments placement " + kind2 + " --target <id>."] : [],
2122
+ ...result.targets.some((target) => target.moveRequired && target.eligible) ? ["The " + kind2 + " environment has data where it runs now; reach the others with backify environments move."] : []
2123
+ ];
2124
+ return [...pad(rows), ...hints.length ? ["", ...hints] : []].join("\n");
2125
+ }
2126
+ async function runTargets(call2, prefix, options) {
2127
+ const placements = await call2(prefix + "/environments/placements");
2128
+ const current = placements.find((item) => item.kind === options.kind);
2129
+ if (!current) throw new CommandError("This application has no " + options.kind + " environment.", "environment_not_activated", { kind: options.kind });
2130
+ const result = await call2(prefix + "/environments/" + current.environmentId + "/placement/targets");
2131
+ return { value: result, text: placementTargetsText(options.kind, result) };
2132
+ }
2133
+ async function runPlacement(call2, prefix, options, context2) {
2134
+ const placements = await call2(prefix + "/environments/placements");
2135
+ if (!options.kind) return { value: { placements }, text: placementsText(placements) };
2136
+ const current = placements.find((item) => item.kind === options.kind);
2137
+ if (!current) throw new CommandError("This application has no " + options.kind + " environment.", "environment_not_activated", { kind: options.kind });
2138
+ const targetId = options.target === "default" ? null : options.target;
2139
+ const path = prefix + "/environments/" + current.environmentId + "/placement";
2140
+ const preflight = await call2(path + "/preflight" + (targetId ? "?deploymentTargetId=" + encodeURIComponent(targetId) : ""));
2141
+ const checks = pad([["CHECK", "RESULT", "DETAIL"], ...preflight.checks.map((check) => [check.name, check.state, check.detail ?? ""])]);
2142
+ const failed = preflight.checks.filter((check) => check.state === "failed").map((check) => check.id);
2143
+ if (!preflight.ready) return { exitCode: 2, value: { status: "blocked", kind: options.kind, deploymentTargetId: targetId, failed, checks: preflight.checks }, text: [...checks, "", "The " + options.kind + " environment cannot be placed on this hosting target. Nothing was changed."].join("\n") };
2144
+ if (options.check) return { value: { status: "ready", kind: options.kind, deploymentTargetId: targetId, checks: preflight.checks }, text: [...checks, "", "All checks passed. Nothing was changed; re-run without --check to approve the placement."].join("\n") };
2145
+ const summary = "Place the " + options.kind + " environment on " + (targetId ? "deployment target " + targetId : "the application's own hosting target") + ". Its compute, data, files, backups and secrets will be created there by the next release deployed to it.";
2146
+ if (!options.yes) {
2147
+ if (!context2.confirm) throw new CommandError("Refusing to change an environment's hosting target without confirmation. Review this and re-run with --yes:\n" + summary, "confirmation_required", { kind: options.kind, deploymentTargetId: targetId });
2148
+ if (!await context2.confirm(summary)) throw new CommandError("Not confirmed. Nothing was changed.", "not_confirmed");
2149
+ }
2150
+ const placement = await call2(path, { method: "PUT", body: JSON.stringify({ deploymentTargetId: targetId }) });
2151
+ return { value: { status: "placed", kind: options.kind, placement }, text: ["The " + options.kind + " environment is now placed on " + hostingText(placement.hosting) + (placement.targetName ? ", " + placement.targetName : "") + (placement.region ? " (" + placement.region + ")" : "") + ".", "", placementsText([placement])].join("\n") };
2152
+ }
2153
+ async function runMove(call2, prefix, options, context2) {
2154
+ const placements = await call2(prefix + "/environments/placements");
2155
+ const current = placements.find((item) => item.kind === options.kind);
2156
+ if (!current) throw new CommandError("This application has no " + options.kind + " environment.", "environment_not_activated", { kind: options.kind });
2157
+ const base = prefix + "/environments/" + current.environmentId + "/moves";
2158
+ const confirmed = async (summary, details) => {
2159
+ if (options.yes) return;
2160
+ if (!context2.confirm) throw new CommandError("Refusing to change a hosting move without confirmation. Review this and re-run with --yes:\n" + summary, "confirmation_required", { kind: options.kind, ...details });
2161
+ if (!await context2.confirm(summary)) throw new CommandError("Not confirmed. Nothing was changed.", "not_confirmed");
2162
+ };
2163
+ if (options.moveAction === "request") {
2164
+ const query = "destinationTargetId=" + encodeURIComponent(options.target) + "&windowStart=" + encodeURIComponent(options.windowStart) + "&windowEnd=" + encodeURIComponent(options.windowEnd);
2165
+ const preflight = await call2(base + "/preflight?" + query);
2166
+ const checks = pad([["CHECK", "RESULT", "DETAIL"], ...preflight.checks.map((check) => [check.name, check.state, check.detail ?? ""])]);
2167
+ const failed = preflight.checks.filter((check) => check.state === "failed").map((check) => check.id);
2168
+ if (!preflight.ready) return { exitCode: 2, value: { status: "blocked", kind: options.kind, destinationTargetId: options.target, failed, checks: preflight.checks }, text: [...checks, "", "The " + options.kind + " environment cannot be moved to this hosting target in this window. Nothing was changed."].join("\n") };
2169
+ if (options.check) return { value: { status: "ready", kind: options.kind, destinationTargetId: options.target, checks: preflight.checks }, text: [...checks, "", "All checks passed. Nothing was changed; re-run without --check to request the move."].join("\n") };
2170
+ await confirmed("Request moving the " + options.kind + " environment to deployment target " + options.target + " in the window " + options.windowStart + " to " + options.windowEnd + ". Another person must approve it; the environment goes into maintenance only when the move is started.", { destinationTargetId: options.target });
2171
+ const result = await call2(base, { method: "POST", body: JSON.stringify({ destinationTargetId: options.target, windowStart: options.windowStart, windowEnd: options.windowEnd }) });
2172
+ if (!result.created || !result.move) return { exitCode: 2, value: { status: "blocked", kind: options.kind, destinationTargetId: options.target, failed: result.preflight.checks.filter((check) => check.state === "failed").map((check) => check.id), checks: result.preflight.checks }, text: "The checks no longer pass. Nothing was changed." };
2173
+ return { value: { status: "requested", kind: options.kind, move: result.move }, text: ["The move of the " + options.kind + " environment awaits approval. Another person approves it on the organization's Approvals page.", "", ...moveSummary(result.move)].join("\n") };
2174
+ }
2175
+ const moves = await call2(base);
2176
+ const move = moves.find((item) => !moveTerminal(item)) ?? moves[0];
2177
+ if (options.moveAction === "status") return { value: { move: move ?? null }, text: move ? moveSummary(move).join("\n") : "The " + options.kind + " environment has no hosting move." };
2178
+ if (!move) throw new CommandError("The " + options.kind + " environment has no hosting move.", "hosting_move_not_found", { kind: options.kind });
2179
+ const action = options.moveAction;
2180
+ if (!move.actions.includes(action)) throw new CommandError("The " + options.kind + " move does not offer " + action + " now: it is in phase " + move.phase + ", state " + move.state + (move.approvalStatus ? ", approval " + move.approvalStatus : "") + ".", "hosting_move_action_unavailable", { kind: options.kind, action, phase: move.phase, state: move.state, actions: move.actions });
2181
+ if (action === "start") await confirmed("Start the move of the " + options.kind + " environment. It goes into maintenance during the window and writes are paused until the move finishes.", { action });
2182
+ if (action === "abort") await confirmed("Abort the move of the " + options.kind + " environment. It returns to its current hosting.", { action });
2183
+ if (action === "confirm") {
2184
+ if (options.active !== move.sourceTargetId && options.active !== move.destinationTargetId) throw new CommandError("--active must be the current target " + move.sourceTargetId + " or the destination " + move.destinationTargetId + ".", "hosting_move_confirm_target_invalid", { kind: options.kind });
2185
+ await confirmed("Confirm that deployment target " + options.active + " is serving the " + options.kind + " environment. The outcome of the switch is unknown; only confirm after checking.", { action, active: options.active });
2186
+ }
2187
+ const updated = await call2(base + "/" + move.id + "/" + action, { method: "POST", ...action === "confirm" ? { body: JSON.stringify({ activeTargetId: options.active }) } : {} });
2188
+ return { value: { status: action, kind: options.kind, move: updated }, text: ["The " + options.kind + " move: " + action + " accepted.", "", ...moveSummary(updated)].join("\n") };
2189
+ }
2190
+ async function runMoveBack(call2, prefix, options) {
2191
+ const placements = await call2(prefix + "/environments/placements");
2192
+ const current = placements.find((item) => item.kind === options.kind);
2193
+ if (!current) throw new CommandError("This application has no " + options.kind + " environment.", "environment_not_activated", { kind: options.kind });
2194
+ const base = prefix + "/environments/" + current.environmentId + "/moves";
2195
+ const moves = await call2(base);
2196
+ const completed = moves.find((item) => item.state === "completed");
2197
+ if (!completed) throw new CommandError("The " + options.kind + " environment has no completed hosting move to move back.", "hosting_move_not_found", { kind: options.kind });
2198
+ const kept2 = completed.retained ? " The copy there is kept until " + completed.retained.retainedUntil + "; it is reused and checked first." : "";
2199
+ const effect = "Move the " + options.kind + " environment, with its database and files, back to deployment target " + completed.sourceTargetId + " in the window " + options.windowStart + " to " + options.windowEnd + "." + kept2 + " Another person must approve it; the environment goes into maintenance only when the move is started.";
2200
+ const slug = (await call2(prefix)).slug;
2201
+ if (!options.confirm || options.confirm !== slug)
2202
+ throw new CommandError(
2203
+ effect + "\n" + (options.confirm ? "--confirm does not match the application slug. " : "") + "Confirm with the application slug: backify environments move-back " + options.kind + " --window-start " + options.windowStart + " --window-end " + options.windowEnd + " --confirm " + (slug ?? "<application-slug>"),
2204
+ "confirmation_required",
2205
+ { kind: options.kind, moveId: completed.id, ...slug ? { confirm: slug } : {} }
2206
+ );
2207
+ const result = await call2(base + "/" + completed.id + "/move-back", { method: "POST", body: JSON.stringify({ windowStart: options.windowStart, windowEnd: options.windowEnd }) });
2208
+ if (!result.created || !result.move) {
2209
+ const failed = result.preflight.checks.filter((check) => check.state === "failed");
2210
+ return {
2211
+ exitCode: 2,
2212
+ value: { status: "blocked", kind: options.kind, failed: failed.map((check) => check.id), checks: result.preflight.checks },
2213
+ text: [...pad([["CHECK", "RESULT", "DETAIL"], ...result.preflight.checks.map((check) => [check.name, check.state, check.detail ?? ""])]), "", "The " + options.kind + " environment cannot be moved back in this window. Nothing was changed."].join("\n")
2214
+ };
2215
+ }
2216
+ return { value: { status: "requested", kind: options.kind, move: result.move }, text: ["The move back of the " + options.kind + " environment awaits approval. Another person approves it on the organization's Approvals page; then start it with backify environments move start " + options.kind + ".", "", ...moveSummary(result.move)].join("\n") };
2217
+ }
2218
+ async function runEnvironments(call2, applicationId, options, context2 = {}) {
2219
+ if (!uuid3.test(applicationId)) throw new Error("Use a valid application ID.");
2220
+ const prefix = "/apps/" + applicationId;
2221
+ if (options.action === "placement") return runPlacement(call2, prefix, options, context2);
2222
+ if (options.action === "move") return runMove(call2, prefix, options, context2);
2223
+ if (options.action === "move-back") return runMoveBack(call2, prefix, options);
2224
+ if (options.action === "targets") return runTargets(call2, prefix, options);
2225
+ const view = await call2(prefix + "/environments/options");
2226
+ if (options.action === "list") return { value: { flow: view.flow, environments: view.options }, text: environmentsText(view) };
2227
+ const kind2 = options.kind, option2 = view.options.find((item) => item.kind === kind2);
2228
+ if (!option2) throw new CommandError("This Backify version has no " + kind2 + " environment.", "invalid_environment");
2229
+ if (options.action === "add") {
2230
+ if (option2.activated) throw new CommandError(`This application already has a ${kind2} environment at https://${option2.hostname}.`, "environment_exists", { kind: kind2, hostname: option2.hostname });
2231
+ const flow2 = ENVIRONMENT_FLOW.filter((item) => item === kind2 || view.flow.includes(item));
2232
+ const summary = [
2233
+ `Add the ${kind2} environment at https://${option2.hostname}.`,
2234
+ "Billing: " + option2.billing,
2235
+ `Releases will then move ${flowText(flow2)}; a new release deploys to ${flow2[0]} first. The environment is provisioned by the next release deployed to it.`
2236
+ ].join("\n");
2237
+ if (!options.yes) {
2238
+ if (!context2.confirm) throw new CommandError("Refusing to add an environment without confirmation. Review this and re-run with --yes:\n" + summary, "confirmation_required", { kind: kind2, hostname: option2.hostname, billing: option2.billing });
2239
+ if (!await context2.confirm(summary)) throw new CommandError("Not confirmed. Nothing was added.", "not_confirmed");
2240
+ }
2241
+ const environment = await call2(prefix + "/environments", { method: "POST", body: JSON.stringify({ kind: kind2 }) });
2242
+ return {
2243
+ value: { status: "added", kind: kind2, hostname: option2.hostname, billing: option2.billing, flow: flow2, environment },
2244
+ text: [`Added the ${kind2} environment: https://${option2.hostname}`, "Billing: " + option2.billing, "Release flow: " + flowText(flow2), `It is provisioned by the next release deployed to it${flow2[0] === kind2 ? " (backify ship)" : " (backify promote)"}.`].join("\n")
2245
+ };
2246
+ }
2247
+ if (!option2.activated) throw new CommandError(`This application has no ${kind2} environment.`, "environment_not_activated", { kind: kind2 });
2248
+ const effect = `Removing ${kind2} takes https://${option2.hostname} offline and removes it from the release flow. Its database, files, secrets and configuration are kept, and adding the environment again restores them.`;
2249
+ if (!options.confirm) {
2250
+ const slug = (await call2(prefix)).slug;
2251
+ throw new CommandError(`${effect}
2252
+ Confirm with the application slug: backify environments remove ${kind2} --confirm ${slug ?? "<application-slug>"}`, "confirmation_required", { kind: kind2, hostname: option2.hostname, dataRetained: true, ...slug ? { confirm: slug } : {} });
2253
+ }
2254
+ await call2(prefix + "/environments/" + kind2, { method: "DELETE", body: JSON.stringify({ confirm: options.confirm }) });
2255
+ const flow = view.flow.filter((item) => item !== kind2);
2256
+ return {
2257
+ value: { status: "removed", kind: kind2, hostname: option2.hostname, dataRetained: true, flow },
2258
+ text: [`Removed the ${kind2} environment: https://${option2.hostname} is offline.`, "Its database, files, secrets and configuration are kept; backify environments add " + kind2 + " restores them.", "Release flow: " + flowText(flow)].join("\n")
2259
+ };
2260
+ }
2261
+ function duration(seconds) {
2262
+ if (seconds === null || seconds === void 0) return "";
2263
+ return seconds >= 60 ? Math.floor(seconds / 60) + "m " + seconds % 60 + "s" : seconds + "s";
2264
+ }
2265
+ function promotionText(stage, promotion) {
2266
+ const label = "Promote to " + promotion.targetName + ": ";
2267
+ switch (promotion.state) {
2268
+ case "blocked":
2269
+ return label + "blocked by " + (promotion.blockedBy.join(", ") || "unfinished checks");
2270
+ case "ready":
2271
+ return label + "ready" + (promotion.permitted ? "" : " (you do not have permission to promote)") + (promotion.requiresTesting ? "; needs --tested" : "") + (promotion.requiresConfirmation ? "; needs confirmation" : "");
2272
+ case "empty":
2273
+ return label + "nothing to promote. " + (promotion.blockedBy[0] ?? "No release has been deployed to " + stage.name + " yet.");
2274
+ case "done":
2275
+ return "Promoted to " + promotion.targetName + (promotion.promotedBy ? " by " + promotion.promotedBy : "") + (promotion.promotedAt ? " at " + promotion.promotedAt : "");
2276
+ case "awaiting-approval":
2277
+ return label + "awaiting approval";
2278
+ case "awaiting-configuration":
2279
+ return label + "awaiting configuration";
2280
+ default:
2281
+ return label + promotion.state;
2282
+ }
2283
+ }
2284
+ function releaseFlowText(flow) {
2285
+ const lines = ["Release flow: " + flowText(flow.stages.map((stage) => stage.kind))];
2286
+ for (const stage of flow.stages) {
2287
+ lines.push("", `${stage.name} (${stage.kind}) ${stage.url}`);
2288
+ const release2 = stage.deployment;
2289
+ lines.push(release2 ? ` Release ${shortCommit(release2)}: ${release2.status}${release2.healthResult ? ", " + release2.healthResult : ""}` : " No release deployed yet");
2290
+ const groups = [...new Set(stage.gates.map((gate) => gate.group))];
2291
+ for (const group of groups) {
2292
+ lines.push(" " + group);
2293
+ const rows = stage.gates.filter((gate) => gate.group === group).map((gate) => [gate.state, gate.name, duration(gate.durationSeconds), [gate.detail, gate.actionUrl ? (gate.actionLabel ?? "Open") + ": " + gate.actionUrl : null].filter(Boolean).join(" ")]);
2294
+ for (const row of pad(rows)) lines.push(" " + row);
2295
+ }
2296
+ if (stage.promotion) lines.push(" " + promotionText(stage, stage.promotion));
2297
+ }
2298
+ return lines.join("\n");
2299
+ }
2300
+ function gateRows(flow) {
2301
+ return flow.stages.flatMap((stage) => stage.gates.map((gate) => ({ stage: stage.kind, group: gate.group, gate: gate.name, state: gate.state, durationSeconds: gate.durationSeconds ?? null, reason: gate.detail ?? null })));
2302
+ }
2303
+ async function releaseFlow(call2, applicationId) {
2304
+ if (!uuid3.test(applicationId)) throw new Error("Use a valid application ID.");
2305
+ const flow = await call2("/apps/" + applicationId + "/release-flow");
2306
+ return { value: flow, text: releaseFlowText(flow) };
2307
+ }
2308
+ function promoteArguments(args2) {
2309
+ if (args2.includes("--help") || args2.includes("-h")) return "help";
2310
+ const { flags, positional } = parse(args2, "promote", ["--json", "--yes", "--tested"], ["--app"]);
2311
+ if (positional.length) throw new Error("backify promote takes no arguments: it promotes to the next activated environment.\n\n" + promoteHelp);
2312
+ return { tested: flags.has("--tested"), yes: flags.has("--yes"), json: flags.has("--json") };
2313
+ }
2314
+ async function promote(call2, applicationId, options, context2 = {}) {
2315
+ if (!uuid3.test(applicationId)) throw new Error("Use a valid application ID.");
2316
+ const prefix = "/apps/" + applicationId;
2317
+ const flow = await call2(prefix + "/release-flow");
2318
+ const stage = flow.stages.find((item) => item.promotion?.state === "ready");
2319
+ if (!stage) {
2320
+ const waiting = flow.stages.filter((item) => item.promotion && item.promotion.state !== "done");
2321
+ const blocked = waiting.find((item) => item.promotion.state === "blocked");
2322
+ const value = {
2323
+ status: blocked ? "blocked" : waiting.length ? "not-ready" : "nothing-to-promote",
2324
+ stages: waiting.map((item) => ({ environment: item.kind, target: item.promotion.target, state: item.promotion.state, blockedBy: item.promotion.blockedBy, release: item.deployment ? shortCommit(item.deployment) : null }))
2325
+ };
2326
+ const text2 = waiting.length ? ["No release is ready to promote. Nothing was sent.", ...waiting.map((item) => `${item.name}: ${promotionText(item, item.promotion)}`), "Run backify release-flow for every check."].join("\n") : flow.stages.length < 2 ? "Production is this application's only environment; there is nothing to promote. Add one with backify environments add <preview|prototype>." : "Every release is already promoted. Nothing was sent.";
2327
+ return { value, text: text2, exitCode: waiting.length ? 2 : 0 };
2328
+ }
2329
+ const promotion = stage.promotion, release2 = stage.deployment;
2330
+ const source = promotion.sourceDeploymentId;
2331
+ if (!source) throw new CommandError("The release flow names no release to promote. Run backify release-flow.", "release_unavailable");
2332
+ const facts = { environment: stage.kind, target: promotion.target, release: shortCommit(release2), sourceDeploymentId: source };
2333
+ if (!promotion.permitted) throw new CommandError(`You do not have permission to promote to ${promotion.targetName}. Nothing was sent.`, "forbidden", facts);
2334
+ if (promotion.requiresTesting && !options.tested)
2335
+ throw new CommandError(`The publish rules require this release to be tested in ${stage.name} (${stage.url}) before it goes to ${promotion.targetName}. Test it, then re-run with --tested to confirm you did. Nothing was sent.`, "testing_required", facts);
2336
+ if (promotion.requiresConfirmation && !options.yes) {
2337
+ const application = await call2(prefix);
2338
+ const name2 = application.name ?? application.slug ?? applicationId;
2339
+ const message = `Promote ${name2} release ${shortCommit(release2)} from ${stage.name} to ${promotion.targetName}?` + (options.tested ? " This records that you tested the release." : "") + (flow.policy.requireProductionApproval ? " An approval request is created; production changes after someone else approves." : " Production changes immediately.");
2340
+ if (!context2.confirm) throw new CommandError("Refusing to promote to " + promotion.targetName + " without confirmation. Review this and re-run with --yes:\n" + message, "confirmation_required", { ...facts, application: name2 });
2341
+ if (!await context2.confirm(message)) throw new CommandError("Not confirmed. Nothing was promoted.", "not_confirmed");
2342
+ }
2343
+ const result = await call2(
2344
+ prefix + "/deployments/promote",
2345
+ { method: "POST", headers: { "Idempotency-Key": "cli-promote-" + source + "-" + promotion.target }, body: JSON.stringify({ previewDeploymentId: source, tested: options.tested, target: promotion.target }) }
2346
+ );
2347
+ const status = result.approvalId || result.status === "awaiting-approval" ? "awaiting-approval" : result.status === "awaiting-configuration" ? "awaiting-configuration" : "promoting";
2348
+ const outcome = status === "awaiting-approval" ? `Approval requested. ${promotion.targetName} changes after someone other than you approves.` : status === "awaiting-configuration" ? (result.error?.message ?? `${promotion.targetName} needs configuration before this release deploys.`) + (result.error?.setupUrl ? " " + result.error.setupUrl : "") : `Promotion to ${promotion.targetName} started.`;
2349
+ return { value: { ...facts, ...result, status }, text: `${stage.name} release ${shortCommit(release2)} -> ${promotion.targetName}
2350
+ ${outcome}
2351
+ Run backify release-flow to follow it.`, exitCode: status === "promoting" ? 0 : 2 };
2352
+ }
2353
+ var ENVIRONMENT_FLOW, OPTIONAL_ENVIRONMENTS, CommandError, environmentsHelp, releaseFlowHelp, promoteHelp, uuid3, flowText, shortCommit, hostingText, runtimeText, deliveryText, workloadRoles, workloadProfiles, foundationModes, foundationSeparations, sourceText, targetState, moveTerminal, moveSummary;
2354
+ var init_release_flow = __esm({
2355
+ "src/release-flow.ts"() {
2356
+ "use strict";
2357
+ ENVIRONMENT_FLOW = ["prototype", "preview", "production"];
2358
+ OPTIONAL_ENVIRONMENTS = ["preview", "prototype"];
2359
+ CommandError = class extends Error {
2360
+ constructor(message, code, details = {}) {
2361
+ super(message);
2362
+ this.code = code;
2363
+ this.details = details;
2364
+ }
2365
+ };
2366
+ environmentsHelp = [
2367
+ "Usage: backify environments [list|add|remove|placement|move|move-back] [options]",
2368
+ "",
2369
+ " backify environments Every environment kind in release order: activated or not, hostname and billing",
2370
+ " backify environments add <preview|prototype> [--yes] Add an environment; asks y/N on a terminal, otherwise needs --yes",
2371
+ " backify environments remove <preview|prototype> --confirm <application-slug>",
2372
+ " Take an environment offline; its data is kept and adding it again restores it",
2373
+ " backify environments placement Where each environment is hosted: target, region, Runtime state, data locations, where each workload runs and the regional foundation",
2374
+ " backify environments placement <environment> --target <deployment-target-id|default> [--check] [--yes]",
2375
+ " Check, then approve, an environment's hosting target; --check only runs the checks (exit 2 if any fails)",
2376
+ " backify environments targets <environment> The hosting targets the environment may use, each eligible or with the check that stops it and why",
2377
+ " backify environments move <environment> --target <deployment-target-id> --window-start <ISO> --window-end <ISO> [--check] [--yes]",
2378
+ " Move an environment that has data to another hosting target in a maintenance window; another person approves it (exit 2 if a check fails)",
2379
+ " backify environments move status <environment> The current or latest move: phase, state, window, approval, verification and what is retained",
2380
+ " backify environments move start|abort <environment> [--yes] Start an approved move (maintenance begins) or abort it (the environment stays on its current hosting)",
2381
+ " backify environments move confirm <environment> --active <deployment-target-id> [--yes]",
2382
+ " When the switch outcome is unknown: name the target you checked is serving",
2383
+ " backify environments move-back <environment> --window-start <ISO> --window-end <ISO> --confirm <application-slug>",
2384
+ " Move an environment back to the target its latest completed move left, while that target keeps its copy; another person approves it",
2385
+ "",
2386
+ "Options: --app <application> (default: the application in this folder) --json (machine-readable output and errors)",
2387
+ "Releases move prototype -> preview -> production through the activated environments only. Production always exists.",
2388
+ "A new release deploys to the earliest activated environment; backify promote moves it to the next one."
2389
+ ].join("\n");
2390
+ releaseFlowHelp = [
2391
+ "Usage: backify release-flow [--app <application>] [--json]",
2392
+ "",
2393
+ "Shows each activated environment in release order with its current release, its checks",
2394
+ "(passed, failed, running, waiting, skipped, pending) with durations, and the promotion to the next",
2395
+ "environment with what blocks it. Exit code 0; read-only."
2396
+ ].join("\n");
2397
+ promoteHelp = [
2398
+ "Usage: backify promote [--tested] [--yes] [--app <application>] [--json]",
2399
+ "",
2400
+ "Promotes the current release of the earliest environment whose promotion is ready to the next activated",
2401
+ "environment (prototype -> preview -> production). Nothing is sent when the promotion is blocked: the",
2402
+ "blocking checks are listed and the exit code is 2.",
2403
+ " --tested Confirms you tested this release; required when the publish rules ask for testing before production",
2404
+ " --yes Confirms a promotion to production without the y/N prompt (required when no terminal is attached)",
2405
+ "Production applies the publish rules: testing, approval and organization policies, as in the portal."
2406
+ ].join("\n");
2407
+ uuid3 = /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;
2408
+ flowText = (kinds) => kinds.join(" -> ");
2409
+ shortCommit = (release2) => (release2?.sourceCommitSha || release2?.commitSha || "").slice(0, 12) || "unknown commit";
2410
+ hostingText = (hosting) => hosting === "backify-cloud" ? "Backify Cloud" : hosting === "customer-azure" ? "Your Azure subscription" : "Local";
2411
+ runtimeText = (runtime) => runtime.state === "failed" ? "failed" + (runtime.failureCode ? " (" + runtime.failureCode + ")" : "") : runtime.state === "pending" ? "applying" : runtime.state === "applied" ? "up to date" : "-";
2412
+ deliveryText = (delivery) => !delivery ? "-" : delivery.state === "delivered" ? "delivered " + delivery.digest.replace(/^sha256:/i, "").slice(0, 12) : delivery.state === "importing" ? "delivering" : delivery.state === "pending" ? "waiting" : "failed" + (delivery.failureCode ? " (" + delivery.failureCode + ")" : "");
2413
+ workloadRoles = { frontend: "Static files", web: "Web", worker: "Worker", migrate: "Migrations" };
2414
+ workloadProfiles = { "static-serving": "Static serving", consumption: "Consumption", dedicated: "Dedicated" };
2415
+ foundationModes = { shared: "shared with other applications", dedicated: "dedicated to your organization", private: "private network", adopted: "your existing resources" };
2416
+ foundationSeparations = { required: "production and non-production run apart", shared: "production and non-production share it" };
2417
+ sourceText = (source) => source === "workspace-default" ? " (workspace default)" : source === "organization-default" ? " (organization default)" : "";
2418
+ targetState = (target) => target.current ? "current" : !target.eligible ? "not eligible" : target.moveRequired ? "needs a move" : "eligible";
2419
+ moveTerminal = (move) => move.state === "completed" || move.state === "aborted" || move.state === "failed";
2420
+ moveSummary = (move) => {
2421
+ const lines = ["Phase: " + move.phase, "State: " + move.state + (move.failureCode ? " (" + move.failureCode + ")" : ""), "Window: " + move.windowStart + " to " + move.windowEnd, "Approval: " + (move.approvalStatus ?? "-")];
2422
+ if (move.reversesMoveId) lines.push("Move back: reverses move " + move.reversesMoveId);
2423
+ if (move.detail) lines.push("Detail: " + move.detail);
2424
+ if (move.verification) {
2425
+ const v = move.verification;
2426
+ lines.push("Verified: " + (v.passed ? "passed" : "not passed") + ", " + v.tables + " tables, " + v.rows + " rows, " + v.files + " files" + (v.mismatches.length ? ", mismatches: " + v.mismatches.join("; ") : ""));
2427
+ }
2428
+ if (move.retained) lines.push("Retained: " + move.retained.assets.join(", ") + " on " + move.retained.targetId + " until " + move.retained.retainedUntil);
2429
+ lines.push("Actions: " + (move.actions.length ? move.actions.join(", ") : "none"));
2430
+ return lines;
2431
+ };
2432
+ }
2433
+ });
2434
+
1917
2435
  // src/human-task.ts
1918
2436
  import { hostname } from "node:os";
1919
2437
  import { setTimeout as delay2 } from "node:timers/promises";
@@ -1923,7 +2441,7 @@ function portalOrigin2(input) {
1923
2441
  return url2.origin;
1924
2442
  }
1925
2443
  function validateHumanTask(status, kind2, applicationId) {
1926
- if (!status || !uuid3.test(status.id) || status.kind !== kind2 || !states.includes(status.state) || applicationId !== void 0 && status.applicationId?.toLowerCase() !== applicationId.toLowerCase() || status.subjectId !== null && !uuid3.test(status.subjectId))
2444
+ if (!status || !uuid4.test(status.id) || status.kind !== kind2 || !states.includes(status.state) || applicationId !== void 0 && status.applicationId?.toLowerCase() !== applicationId.toLowerCase() || status.subjectId !== null && !uuid4.test(status.subjectId))
1927
2445
  throw new Error("The server returned invalid task metadata.");
1928
2446
  return status;
1929
2447
  }
@@ -1973,16 +2491,16 @@ Check that the page shows the code ${status.matchCode}.` : ""));
1973
2491
  status = { ...next, matchCode: status.matchCode };
1974
2492
  }
1975
2493
  }
1976
- var uuid3, states, isUuid, humanTaskClient, readHumanTask;
2494
+ var uuid4, states, isUuid, humanTaskClient, readHumanTask;
1977
2495
  var init_human_task = __esm({
1978
2496
  "src/human-task.ts"() {
1979
2497
  "use strict";
1980
- uuid3 = /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;
2498
+ uuid4 = /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;
1981
2499
  states = ["pending", "completed", "declined", "expired", "failed"];
1982
- isUuid = (value) => uuid3.test(value);
2500
+ isUuid = (value) => uuid4.test(value);
1983
2501
  humanTaskClient = { clientName: "Backify CLI", clientDevice: hostname() };
1984
2502
  readHumanTask = (call2, id) => {
1985
- if (!uuid3.test(id)) throw new Error("Use a valid task ID.");
2503
+ if (!uuid4.test(id)) throw new Error("Use a valid task ID.");
1986
2504
  return call2("/tasks/" + id.toLowerCase());
1987
2505
  };
1988
2506
  }
@@ -1994,7 +2512,7 @@ var init_package = __esm({
1994
2512
  "package.json"() {
1995
2513
  package_default = {
1996
2514
  name: "@backifydev/cli",
1997
- version: "0.4.3",
2515
+ version: "0.4.5",
1998
2516
  description: "Command-line setup and diagnostics for Backify applications",
1999
2517
  type: "module",
2000
2518
  bin: {
@@ -2079,8 +2597,8 @@ function validateDeliveryInstructions(root) {
2079
2597
  function installDeliveryInstructions(root, instructionFiles2) {
2080
2598
  validateDeliveryInstructions(root);
2081
2599
  writeFileSync4(join4(root, "BACKIFY.md"), deliveryInstructions);
2082
- for (const relative4 of instructionFiles2) {
2083
- const instructionPath = join4(root, relative4), content = readFileSync4(instructionPath, "utf8");
2600
+ for (const relative5 of instructionFiles2) {
2601
+ const instructionPath = join4(root, relative5), content = readFileSync4(instructionPath, "utf8");
2084
2602
  const link = relativePath(dirname(instructionPath), join4(root, "BACKIFY.md")).replaceAll("\\", "/");
2085
2603
  const legacyLink = relativePath(dirname(instructionPath), join4(root, "BACKIFY-WORKFLOW.md")).replaceAll("\\", "/");
2086
2604
  const legacy = "For application delivery and recording each user request, follow [BACKIFY-WORKFLOW.md](" + legacyLink + ").";
@@ -2163,8 +2681,8 @@ function detectPackageManager(root = process.cwd()) {
2163
2681
  return "npm";
2164
2682
  }
2165
2683
  function updateInstructions(root = process.cwd(), agent, instructionFile) {
2166
- const updates = selectedInstructionFiles(root, agent, instructionFile).map((relative4) => {
2167
- const path = join6(root, relative4);
2684
+ const updates = selectedInstructionFiles(root, agent, instructionFile).map((relative5) => {
2685
+ const path = join6(root, relative5);
2168
2686
  return { path, content: updateManagedInstructions(existsSync5(path) ? readFileSync6(path, "utf8") : "") };
2169
2687
  });
2170
2688
  for (const { path, content } of updates) {
@@ -2213,7 +2731,7 @@ function initialize(appId, root = process.cwd(), install = true, agent, instruct
2213
2731
  if (existingApp && existingApp !== appId) throw new Error("The project is connected to a different application. Reconcile app.id before initializing.");
2214
2732
  const selected = instructionSelection(root, agent, instructionFile), files = selected.files;
2215
2733
  validateDeliveryInstructions(root);
2216
- for (const relative4 of files) if (existsSync5(join6(root, relative4))) updateManagedInstructions(readFileSync6(join6(root, relative4), "utf8"));
2734
+ for (const relative5 of files) if (existsSync5(join6(root, relative5))) updateManagedInstructions(readFileSync6(join6(root, relative5), "utf8"));
2217
2735
  const customContainer = !existsSync5(join6(root, "package.json")) && existsSync5(join6(root, "Dockerfile"));
2218
2736
  if (!customContainer) {
2219
2737
  ensurePackageManifest(root);
@@ -2250,10 +2768,10 @@ function doctor(root = process.cwd(), agent, instructionFile) {
2250
2768
  } catch (reason) {
2251
2769
  issues.push(reason instanceof Error ? reason.message : String(reason));
2252
2770
  }
2253
- for (const relative4 of files) {
2254
- const path = join6(root, relative4);
2771
+ for (const relative5 of files) {
2772
+ const path = join6(root, relative5);
2255
2773
  if (!existsSync5(path)) {
2256
- issues.push(`${relative4} is missing`);
2774
+ issues.push(`${relative5} is missing`);
2257
2775
  continue;
2258
2776
  }
2259
2777
  const content = readFileSync6(path, "utf8");
@@ -2261,10 +2779,10 @@ function doctor(root = process.cwd(), agent, instructionFile) {
2261
2779
  if (config2 && config2.instructionVersion < INSTRUCTION_VERSION) {
2262
2780
  const declared = content.match(/Instruction version:\s*(\d+)/)?.[1];
2263
2781
  const structural = managed.filter((issue2) => !issue2.includes("stale or inconsistent"));
2264
- issues.push(...structural.map((issue2) => relative4 + " " + issue2));
2265
- if (Number(declared) !== config2.instructionVersion || !content.includes("https://agent.backify.dev/v" + config2.instructionVersion)) issues.push(relative4 + " does not match the repository instruction version");
2266
- else warnings.push(relative4 + " uses supported older instructions; follow the versioned guide. Run backify sync only when intentionally upgrading instructions.");
2267
- } else issues.push(...managed.map((issue2) => relative4 + " " + issue2));
2782
+ issues.push(...structural.map((issue2) => relative5 + " " + issue2));
2783
+ if (Number(declared) !== config2.instructionVersion || !content.includes("https://agent.backify.dev/v" + config2.instructionVersion)) issues.push(relative5 + " does not match the repository instruction version");
2784
+ else warnings.push(relative5 + " uses supported older instructions; follow the versioned guide. Run backify sync only when intentionally upgrading instructions.");
2785
+ } else issues.push(...managed.map((issue2) => relative5 + " " + issue2));
2268
2786
  }
2269
2787
  let version2 = "unknown";
2270
2788
  try {
@@ -2393,6 +2911,7 @@ function apiClient(session, transport = fetch) {
2393
2911
  }
2394
2912
  throw new Error(message);
2395
2913
  }
2914
+ if (new Headers(init?.headers).get("accept")?.startsWith("text/plain")) return await response.text();
2396
2915
  return response.status === 204 ? void 0 : await response.json();
2397
2916
  };
2398
2917
  }
@@ -2406,7 +2925,15 @@ function saveUserConfig(path, config2) {
2406
2925
  const secured = spawnSync4("icacls", [temporary, "/inheritance:r", "/grant:r", account + ":(F)"], { windowsHide: true, encoding: "utf8" });
2407
2926
  if (secured.status !== 0) throw new Error("Could not restrict CLI credential file permissions.");
2408
2927
  }
2409
- renameSync(temporary, path);
2928
+ for (let attempt = 0; ; attempt++) {
2929
+ try {
2930
+ renameSync(temporary, path);
2931
+ break;
2932
+ } catch (error2) {
2933
+ if (process.platform !== "win32" || attempt >= 5 || !["EPERM", "EBUSY", "EACCES"].includes(error2.code ?? "")) throw error2;
2934
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 40 * (attempt + 1));
2935
+ }
2936
+ }
2410
2937
  } finally {
2411
2938
  rmSync(temporary, { force: true });
2412
2939
  }
@@ -2538,23 +3065,26 @@ function pushSource(appId, commit, branch, destination, root, environment) {
2538
3065
  git(["push", "--", destination, commit + ":refs/heads/" + branch], root, environment);
2539
3066
  return false;
2540
3067
  }
2541
- async function waitForPreview(call2, prefix, commit, options = {}) {
3068
+ async function waitForRelease(call2, prefix, commit, environment, options = {}) {
2542
3069
  const deadline = Date.now() + (options.timeoutMs ?? 20 * 6e4);
2543
- const sleep = options.sleep ?? ((delay4) => new Promise((resolve9) => setTimeout(resolve9, delay4)));
3070
+ const sleep = options.sleep ?? ((delay4) => new Promise((resolve10) => setTimeout(resolve10, delay4)));
3071
+ const untouched = environment === "production" ? "" : " No production release was requested.";
2544
3072
  do {
2545
3073
  const deployments = await call2(prefix + "/deployments");
2546
- const matching = deployments.find((release2) => release2.kind === "preview" && matchesSource(release2, commit) && !options.previousDeploymentIds?.includes(release2.id));
3074
+ const matching = deployments.find((release2) => release2.kind === environment && matchesSource(release2, commit) && !options.previousDeploymentIds?.includes(release2.id));
2547
3075
  if (matching?.status === "failed") throw new Error("Deployment of this source failed. Run backify status and inspect its deployment steps.");
2548
- const overview = await call2(prefix + "/releases");
2549
- if (matchesSource(overview.preview, commit) && overview.preview?.status === "succeeded" && overview.preview.healthResult === "healthy") return overview;
3076
+ const flow = await call2(prefix + "/release-flow");
3077
+ const stage = flow.stages?.find((item) => item.kind === environment);
3078
+ if (!stage) throw new Error(`The application no longer has a ${environment} environment. Run backify environments, then ship again.`);
3079
+ if (matchesSource(stage.deployment ?? void 0, commit) && healthy(stage.deployment)) return flow;
2550
3080
  const build2 = await call2(prefix + "/developer/build?commitSha=" + commit);
2551
3081
  if ((options.previousBuildRunId === void 0 || build2.runId !== options.previousBuildRunId) && ["failure", "cancelled", "timed_out", "action_required", "startup_failure"].includes(build2.conclusion ?? "")) {
2552
3082
  const details = build2.failure ? " Stage: " + build2.failure.stage + ". " + build2.failure.remediation : "";
2553
- throw new Error("GitHub build " + build2.conclusion + " for source " + commit + "." + details + " No production release was requested. " + (build2.url ?? "Run backify status for details."));
3083
+ throw new Error("GitHub build " + build2.conclusion + " for source " + commit + "." + details + untouched + " " + (build2.url ?? "Run backify status for details."));
2554
3084
  }
2555
3085
  await sleep(options.intervalMs ?? 4e3);
2556
3086
  } while (Date.now() < deadline);
2557
- throw new Error("Timed out waiting for this commit's healthy preview. Run backify status; no production release was requested.");
3087
+ throw new Error(`Timed out waiting for this commit's healthy ${environment} release. Run backify status.` + untouched);
2558
3088
  }
2559
3089
  async function ship(call2, appId, options = {}) {
2560
3090
  const root = options.root ?? process.cwd(), prefix = "/apps/" + applicationGuid(appId);
@@ -2571,10 +3101,25 @@ async function ship(call2, appId, options = {}) {
2571
3101
  if (git(["branch", "--show-current"], root) !== status.branch) throw new Error("Use the connected branch: " + status.branch);
2572
3102
  if (git(["status", "--porcelain"], root)) throw new Error("Commit application changes before shipping. The CLI never stages or commits unrelated files.");
2573
3103
  const commit = git(["rev-parse", "HEAD"], root);
3104
+ const planned = await call2(prefix + "/release-flow");
3105
+ const entry = planned.stages?.[0];
3106
+ if (!entry) throw new Error("The application has no environment to deploy to. Run backify environments.");
3107
+ const kinds = planned.stages.map((stage) => stage.kind);
2574
3108
  if (options.dryRun) {
2575
- const preview = status.releases.preview, planned = localReport(false, root);
2576
- const promotion = !options.productionDeploy || options.previewOnly ? "not requested; the healthy preview is the result" : status.releases.policy.requirePreviewTesting ? "requested; the preview must be marked tested before promotion" : status.releases.policy.requireProductionApproval ? "requested; promotion waits for production approval" : "requested; the healthy preview for this commit is promoted to production";
2577
- return { status: "dry-run", repository: status.repository, branch: status.branch, commit, push: { destination: "https://github.com/" + status.repository + ".git", ref: "refs/heads/" + status.branch, commit }, checks: planned.checks.map((check) => check.name), preview: matchesSource(preview, commit) ? { status: preview.status, healthResult: preview.healthResult, url: preview.url, reused: preview.status === "succeeded" } : { status: "will-build", previous: preview ? { commit: preview.commitSha, status: preview.status } : null }, production: promotion };
3109
+ const current = entry.deployment, checks = localReport(false, root), staging = planned.stages.at(-2);
3110
+ const production = entry.kind === "production" ? "this release deploys straight to production, the application's only environment" : !options.productionDeploy || options.previewOnly ? `not requested; the healthy ${entry.kind} release is the result` : planned.policy.requirePreviewTesting ? `requested; the release must be marked tested in ${staging.kind} before promotion to production` : planned.policy.requireProductionApproval ? "requested; promotion waits for production approval" : "requested; the healthy release for this commit is promoted " + kinds.join(" -> ");
3111
+ return {
3112
+ status: "dry-run",
3113
+ repository: status.repository,
3114
+ branch: status.branch,
3115
+ commit,
3116
+ push: { destination: "https://github.com/" + status.repository + ".git", ref: "refs/heads/" + status.branch, commit },
3117
+ checks: checks.checks.map((check) => check.name),
3118
+ flow: kinds,
3119
+ release: matchesSource(current ?? void 0, commit) ? { environment: entry.kind, status: current.status, healthResult: current.healthResult, url: stageUrl(entry), reused: current.status === "succeeded" } : { environment: entry.kind, status: "will-build", previous: current ? { commit: current.commitSha, status: current.status } : null },
3120
+ promotions: entry.kind === "production" || !options.productionDeploy || options.previewOnly ? [] : planned.stages.slice(1).map((stage) => stage.kind),
3121
+ production
3122
+ };
2578
3123
  }
2579
3124
  const report = localReport(true, root);
2580
3125
  await call2(prefix + "/developer/report", { method: "POST", body: JSON.stringify(report) });
@@ -2592,41 +3137,73 @@ async function ship(call2, appId, options = {}) {
2592
3137
  const environment = gitEnvironment(status.repository, credential.token);
2593
3138
  const destination = "https://github.com/" + status.repository + ".git";
2594
3139
  const alreadyPushed = pushSource(appId, commit, status.branch, destination, root, environment);
2595
- const currentPreview = previousDeployments.find((release2) => release2.kind === "preview" && matchesSource(release2, commit));
2596
- if (alreadyPushed && (!currentPreview || currentPreview.status === "failed") && !(matchesSource(status.releases.preview, commit) && status.releases.preview?.status === "succeeded")) await call2(prefix + "/deployments/preview", { method: "POST", body: JSON.stringify({ sourceRevision: "latest" }) });
2597
- const overview = await waitForPreview(call2, prefix, commit, { timeoutMs: options.timeoutMs, previousDeploymentIds: previousDeployments.filter((deployment) => deployment.status === "failed").map((deployment) => deployment.id), previousBuildRunId: previousBuild.runId ?? null });
2598
- if (overview.preview.commitSha !== commit) {
2599
- if (git(["status", "--porcelain"], root) || git(["rev-parse", "HEAD"], root) !== commit) throw new Error("Local work changed while the preview built. Review it before synchronizing the build commit.");
3140
+ const currentRelease = previousDeployments.find((release2) => release2.kind === entry.kind && matchesSource(release2, commit));
3141
+ if (alreadyPushed && (!currentRelease || currentRelease.status === "failed") && !(matchesSource(entry.deployment ?? void 0, commit) && entry.deployment?.status === "succeeded")) await call2(prefix + "/deployments/preview", { method: "POST", body: JSON.stringify({ sourceRevision: "latest" }) });
3142
+ const flow = await waitForRelease(call2, prefix, commit, entry.kind, { timeoutMs: options.timeoutMs, previousDeploymentIds: previousDeployments.filter((deployment) => deployment.status === "failed").map((deployment) => deployment.id), previousBuildRunId: previousBuild.runId ?? null });
3143
+ const deployed = flow.stages.find((stage) => stage.kind === entry.kind).deployment;
3144
+ if (deployed.commitSha !== commit) {
3145
+ if (git(["status", "--porcelain"], root) || git(["rev-parse", "HEAD"], root) !== commit) throw new Error("Local work changed while the release built. Review it before synchronizing the build commit.");
2600
3146
  const refreshed = await call2(prefix + "/developer/git-credential", { method: "POST" });
2601
3147
  if (refreshed.repository.toLowerCase() !== status.repository.toLowerCase()) throw new Error("Repository changed while building.");
2602
3148
  git(["fetch", "--", destination, "refs/heads/" + status.branch], root, gitEnvironment(status.repository, refreshed.token));
2603
- git(["merge", "--ff-only", overview.preview.commitSha], root);
2604
- }
2605
- return publishPreview(call2, prefix, overview, options);
2606
- }
2607
- async function publishPreview(call2, prefix, overview, options = {}) {
2608
- if (!overview.preview || overview.preview.status !== "succeeded" || overview.preview.healthResult !== "healthy") throw new Error("Only a verified healthy preview can be published.");
2609
- const preview = overview.preview;
2610
- if (!options.productionDeploy || options.previewOnly) return { status: "preview-ready", url: preview.url };
2611
- if (overview.policy.requirePreviewTesting && !preview.testedAt) return { status: "testing-required", url: preview.url };
2612
- if (overview.live?.previewDeploymentId === preview.id && overview.live.status === "succeeded") return { status: "live", url: overview.live.url };
2613
- const promotion = await call2(prefix + "/deployments/promote", { method: "POST", headers: { "Idempotency-Key": "cli-ship-" + preview.id }, body: JSON.stringify({ previewDeploymentId: preview.id, tested: false }) });
2614
- if (promotion.status === "awaiting-approval" || promotion.approvalId) return { status: "awaiting-approval", url: preview.url };
2615
- if (!promotion.operationId) throw new Error("Publication returned no operation to verify. Run backify status.");
3149
+ git(["merge", "--ff-only", deployed.commitSha], root);
3150
+ }
3151
+ return publishRelease(call2, prefix, flow, entry.kind, options);
3152
+ }
3153
+ async function publishRelease(call2, prefix, flow, environment, options = {}) {
3154
+ let stage = flow.stages.find((item) => item.kind === environment);
3155
+ if (!stage || !healthy(stage.deployment)) throw new Error("Only a verified healthy release can be published.");
3156
+ if (stage.kind === "production" || !options.productionDeploy || options.previewOnly) return { status: readyStatus(stage.kind), environment: stage.kind, url: stageUrl(stage) };
2616
3157
  const deadline = Date.now() + (options.timeoutMs ?? 20 * 6e4);
2617
- do {
2618
- const operation = await call2("/operations/" + promotion.operationId);
2619
- if (operation.status === "failed" || operation.status === "cancelled") throw new Error(operation.errorMessage ?? "Production deployment did not complete.");
2620
- if (operation.status === "succeeded") {
2621
- const releases = await call2(prefix + "/releases");
2622
- if (releases.live?.previewDeploymentId !== preview.id || releases.live.status !== "succeeded" || releases.live.healthResult !== "healthy") throw new Error("Production did not activate this healthy release. Run backify status.");
2623
- return { status: "live", url: releases.live.url };
2624
- }
2625
- await new Promise((resolve9) => setTimeout(resolve9, 4e3));
2626
- } while (Date.now() < deadline);
2627
- throw new Error("Publication is still pending. Run backify status; deployment success has not been verified.");
3158
+ const pause = () => new Promise((resolve10) => setTimeout(resolve10, options.intervalMs ?? 4e3));
3159
+ const read = async () => (await call2(prefix + "/release-flow")).stages;
3160
+ let stages = flow.stages;
3161
+ while (stage.kind !== "production") {
3162
+ const source = stage, promotion = source.promotion, release2 = source.deployment, at = { environment: source.kind, url: stageUrl(source) };
3163
+ if (!promotion) throw new Error(`The release flow has no promotion from ${source.kind}. Run backify release-flow.`);
3164
+ const target = promotion.target;
3165
+ const reached = () => {
3166
+ const next = stages.find((item) => item.kind === target);
3167
+ if (!next || next.deployment?.previewDeploymentId !== release2.id || !healthy(next.deployment)) throw new Error(`${target === "production" ? "Production" : "The " + target + " environment"} did not activate this healthy release. Run backify status.`);
3168
+ return next;
3169
+ };
3170
+ if (promotion.state === "done") {
3171
+ stage = reached();
3172
+ continue;
3173
+ }
3174
+ if (target === "production" && promotion.requiresTesting) return { status: "testing-required", ...at };
3175
+ if (promotion.state === "awaiting-approval") return { status: "awaiting-approval", ...at };
3176
+ if (promotion.state === "awaiting-configuration") return { status: "awaiting-configuration", ...at, target };
3177
+ if (promotion.state === "blocked" || promotion.state === "empty") return { status: "promotion-blocked", ...at, target, blockedBy: promotion.blockedBy };
3178
+ if (promotion.state === "in-progress") {
3179
+ let current = source;
3180
+ while (current?.promotion?.state === "in-progress") {
3181
+ if (Date.now() >= deadline) throw new Error("Promotion is still pending. Run backify status; deployment success has not been verified.");
3182
+ await pause();
3183
+ stages = await read();
3184
+ current = stages.find((item) => item.kind === source.kind);
3185
+ }
3186
+ if (!current || current.promotion?.state === "ready") throw new Error(`Promotion to ${target} did not complete. Run backify release-flow.`);
3187
+ stage = current;
3188
+ continue;
3189
+ }
3190
+ const requested = await call2(prefix + "/deployments/promote", { method: "POST", headers: { "Idempotency-Key": "cli-ship-" + release2.id }, body: JSON.stringify({ previewDeploymentId: release2.id, tested: false, target }) });
3191
+ if (requested.status === "awaiting-approval" || requested.approvalId) return { status: "awaiting-approval", ...at };
3192
+ if (requested.status === "awaiting-configuration") return { status: "awaiting-configuration", ...at, target };
3193
+ if (!requested.operationId) throw new Error("Publication returned no operation to verify. Run backify status.");
3194
+ for (; ; ) {
3195
+ const operation = await call2("/operations/" + requested.operationId);
3196
+ if (operation.status === "failed" || operation.status === "cancelled") throw new Error(operation.errorMessage ?? `${target === "production" ? "Production deployment" : "Promotion to " + target} did not complete.`);
3197
+ if (operation.status === "succeeded") break;
3198
+ if (Date.now() >= deadline) throw new Error("Publication is still pending. Run backify status; deployment success has not been verified.");
3199
+ await pause();
3200
+ }
3201
+ stages = await read();
3202
+ stage = reached();
3203
+ }
3204
+ return { status: "live", environment: "production", url: stageUrl(stage) };
2628
3205
  }
2629
- var CliAuthenticationRequired;
3206
+ var CliAuthenticationRequired, healthy, stageUrl, readyStatus;
2630
3207
  var init_development = __esm({
2631
3208
  "src/development.ts"() {
2632
3209
  "use strict";
@@ -2640,6 +3217,9 @@ var init_development = __esm({
2640
3217
  super("Backify CLI authentication expired or was revoked. Ask the user to sign in, then run backify connect --reauth. The browser lets them choose 7, 14, 30, or 90 days.");
2641
3218
  }
2642
3219
  };
3220
+ healthy = (release2) => release2?.status === "succeeded" && release2.healthResult === "healthy";
3221
+ stageUrl = (stage) => stage.deployment?.url || stage.url;
3222
+ readyStatus = (kind2) => kind2 === "production" ? "live" : kind2 + "-ready";
2643
3223
  }
2644
3224
  });
2645
3225
 
@@ -2677,7 +3257,7 @@ async function refreshMcpGrant(grant, transport) {
2677
3257
  }
2678
3258
  function storedGrant(config2, endpoint2) {
2679
3259
  const grant = config2.mcp;
2680
- return grant && grant.endpoint === resourceOf(endpoint2) && /^bfmcpr_[A-Za-z0-9_-]{43}$/.test(grant.refreshToken) && Array.isArray(grant.organizationIds) && grant.organizationIds.length > 0 && grant.organizationIds.every((id) => uuid6.test(id)) ? grant : void 0;
3260
+ return grant && grant.endpoint === resourceOf(endpoint2) && /^bfmcpr_[A-Za-z0-9_-]{43}$/.test(grant.refreshToken) && Array.isArray(grant.organizationIds) && grant.organizationIds.length > 0 && grant.organizationIds.every((id) => uuid7.test(id)) ? grant : void 0;
2681
3261
  }
2682
3262
  async function renewStoredGrant(file, endpoint2, transport) {
2683
3263
  for (let attempt = 0; ; attempt++) {
@@ -2693,7 +3273,7 @@ async function renewStoredGrant(file, endpoint2, transport) {
2693
3273
  }
2694
3274
  }
2695
3275
  }
2696
- var cliClientId, McpGrantRejected, scopes, resourceOf, uuid6;
3276
+ var cliClientId, McpGrantRejected, scopes, resourceOf, uuid7;
2697
3277
  var init_mcp_grant = __esm({
2698
3278
  "src/mcp-grant.ts"() {
2699
3279
  "use strict";
@@ -2702,7 +3282,7 @@ var init_mcp_grant = __esm({
2702
3282
  };
2703
3283
  scopes = /* @__PURE__ */ new Set(["organization:read", "organization:write", "deployment:manage", "billing:manage", "access:manage"]);
2704
3284
  resourceOf = (endpoint2) => new URL(endpoint2).href.replace(/\/$/, "");
2705
- uuid6 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
3285
+ uuid7 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
2706
3286
  }
2707
3287
  });
2708
3288
 
@@ -2762,8 +3342,8 @@ function installedVersion(root, name2) {
2762
3342
  }
2763
3343
  function mergeIgnoreFile(template, destination) {
2764
3344
  const current = readFileSync9(destination, "utf8");
2765
- const present2 = new Set(current.split(/\r?\n/).map((line) => line.trim()));
2766
- const missing = readFileSync9(template, "utf8").split(/\r?\n/).map((line) => line.trim()).filter((line) => line && !present2.has(line));
3345
+ const present2 = new Set(current.split(/\r?\n/).map((line2) => line2.trim()));
3346
+ const missing = readFileSync9(template, "utf8").split(/\r?\n/).map((line2) => line2.trim()).filter((line2) => line2 && !present2.has(line2));
2767
3347
  if (!missing.length) return false;
2768
3348
  writeFileSync7(destination, (current && !current.endsWith("\n") ? current + "\n" : current) + missing.join("\n") + "\n");
2769
3349
  return true;
@@ -2792,15 +3372,15 @@ function createApp(options) {
2792
3372
  const written = [];
2793
3373
  mkdirSync2(target, { recursive: true });
2794
3374
  for (const file of walk(staging)) {
2795
- const relative4 = file.slice(staging.length + 1);
2796
- const destination = join9(target, relative4);
2797
- if (existsSync8(destination) && relative4 !== "package.json") {
2798
- if ((relative4 === ".gitignore" || relative4 === ".dockerignore") && mergeIgnoreFile(file, destination)) written.push(relative4);
3375
+ const relative5 = file.slice(staging.length + 1);
3376
+ const destination = join9(target, relative5);
3377
+ if (existsSync8(destination) && relative5 !== "package.json") {
3378
+ if ((relative5 === ".gitignore" || relative5 === ".dockerignore") && mergeIgnoreFile(file, destination)) written.push(relative5);
2799
3379
  continue;
2800
3380
  }
2801
3381
  mkdirSync2(dirname4(destination), { recursive: true });
2802
3382
  cpSync2(file, destination);
2803
- written.push(relative4);
3383
+ written.push(relative5);
2804
3384
  }
2805
3385
  if (connected.appId && existsSync8(join9(target, APP_CONFIG_FILE))) {
2806
3386
  rmSync2(join9(target, "backify.json"), { force: true });
@@ -4041,17 +4621,17 @@ var init_parse = __esm({
4041
4621
  return result.issues.length === 0;
4042
4622
  };
4043
4623
  _encode = (_Err) => {
4044
- const parse3 = _parse(_Err);
4624
+ const parse4 = _parse(_Err);
4045
4625
  const fn = (schema, value, _ctx, _params) => {
4046
4626
  const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" };
4047
- return parse3(schema, value, ctx, finalizeParams(fn, _params));
4627
+ return parse4(schema, value, ctx, finalizeParams(fn, _params));
4048
4628
  };
4049
4629
  return fn;
4050
4630
  };
4051
4631
  _decode = (_Err) => {
4052
- const parse3 = _parse(_Err);
4632
+ const parse4 = _parse(_Err);
4053
4633
  const fn = (schema, value, _ctx, _params) => {
4054
- return parse3(schema, value, _ctx, finalizeParams(fn, _params));
4634
+ return parse4(schema, value, _ctx, finalizeParams(fn, _params));
4055
4635
  };
4056
4636
  return fn;
4057
4637
  };
@@ -4113,7 +4693,7 @@ function datetime(args2) {
4113
4693
  const timeRegex = args2.local ? `${qualified}|${timeSource({ precision: args2.precision })}` : qualified;
4114
4694
  return new RegExp(`^${dateSource}T(?:${timeRegex})$`);
4115
4695
  }
4116
- var cuid, cuid2, ulid, xid, ksuid, nanoid, duration, guid3, uuid7, email, _emoji, ipv4, ipv6, cidrv4, cidrv6, base642, base64url, httpProtocol, e164, dateSource, date, anyString, bigint, integer, number, boolean, _null, lowercase, uppercase;
4696
+ var cuid, cuid2, ulid, xid, ksuid, nanoid, duration2, guid3, uuid8, email, _emoji, ipv4, ipv6, cidrv4, cidrv6, base642, base64url, httpProtocol, e164, dateSource, date, anyString, bigint, integer, number, boolean, _null, lowercase, uppercase;
4117
4697
  var init_regexes = __esm({
4118
4698
  "../../node_modules/zod/v4/core/regexes.js"() {
4119
4699
  cuid = /^[cC][0-9a-z]{6,}$/;
@@ -4122,9 +4702,9 @@ var init_regexes = __esm({
4122
4702
  xid = /^[0-9a-vA-V]{20}$/;
4123
4703
  ksuid = /^[A-Za-z0-9]{27}$/;
4124
4704
  nanoid = /^[a-zA-Z0-9_-]{21}$/;
4125
- duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;
4705
+ duration2 = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;
4126
4706
  guid3 = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;
4127
- uuid7 = (version2) => {
4707
+ uuid8 = (version2) => {
4128
4708
  if (!version2)
4129
4709
  return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;
4130
4710
  return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version2}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);
@@ -4510,8 +5090,8 @@ var init_doc = __esm({
4510
5090
  const lines = content.split("\n").filter((x) => x);
4511
5091
  const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length));
4512
5092
  const dedented = lines.map((x) => x.slice(minIndent)).map((x) => " ".repeat(this.indent * 2) + x);
4513
- for (const line of dedented) {
4514
- this.content.push(line);
5093
+ for (const line2 of dedented) {
5094
+ this.content.push(line2);
4515
5095
  }
4516
5096
  }
4517
5097
  compile() {
@@ -4666,7 +5246,7 @@ function capSize(inst, size) {
4666
5246
  if (!caps.length)
4667
5247
  return;
4668
5248
  const cap = Math.min(...caps.map((c) => c[0]));
4669
- const parse3 = inst._zod.parse;
5249
+ const parse4 = inst._zod.parse;
4670
5250
  inst._zod.parse = (payload, ctx) => {
4671
5251
  const n = size(payload.value);
4672
5252
  if (n > cap && !ctx?.skipChecks && ctx?.direction !== "backward") {
@@ -4680,7 +5260,7 @@ function capSize(inst, size) {
4680
5260
  }
4681
5261
  }
4682
5262
  }
4683
- return parse3(payload, ctx);
5263
+ return parse4(payload, ctx);
4684
5264
  };
4685
5265
  }
4686
5266
  function handleArrayResult(result, final, index) {
@@ -5156,9 +5736,9 @@ var init_schemas = __esm({
5156
5736
  const v = versionMap[def.version];
5157
5737
  if (v === void 0)
5158
5738
  throw new Error(`Invalid UUID version: "${def.version}"`);
5159
- def.pattern ?? (def.pattern = uuid7(v));
5739
+ def.pattern ?? (def.pattern = uuid8(v));
5160
5740
  } else
5161
- def.pattern ?? (def.pattern = uuid7());
5741
+ def.pattern ?? (def.pattern = uuid8());
5162
5742
  $ZodStringFormat.init(inst, def);
5163
5743
  });
5164
5744
  $ZodEmail = /* @__PURE__ */ $constructor("$ZodEmail", (inst, def) => {
@@ -5277,7 +5857,7 @@ var init_schemas = __esm({
5277
5857
  $ZodStringFormat.init(inst, def);
5278
5858
  });
5279
5859
  $ZodISODuration = /* @__PURE__ */ $constructor("$ZodISODuration", (inst, def) => {
5280
- def.pattern ?? (def.pattern = duration);
5860
+ def.pattern ?? (def.pattern = duration2);
5281
5861
  $ZodStringFormat.init(inst, def);
5282
5862
  });
5283
5863
  $ZodIPv4 = /* @__PURE__ */ $constructor("$ZodIPv4", (inst, def) => {
@@ -6272,7 +6852,7 @@ function isRef(value) {
6272
6852
  function cloneIssues(issues) {
6273
6853
  return issues.map((iss) => iss.path ? { ...iss, path: iss.path.slice() } : { ...iss });
6274
6854
  }
6275
- function isRecursive(inst, stack, resolve9) {
6855
+ function isRecursive(inst, stack, resolve10) {
6276
6856
  const cached2 = recursive.get(inst);
6277
6857
  if (cached2 !== void 0)
6278
6858
  return cached2 ? PROVEN : NONE;
@@ -6282,7 +6862,7 @@ function isRecursive(inst, stack, resolve9) {
6282
6862
  let result = NONE;
6283
6863
  const check = (child) => {
6284
6864
  if (result !== PROVEN && child?._zod) {
6285
- const answer = isRecursive(child, stack, resolve9);
6865
+ const answer = isRecursive(child, stack, resolve10);
6286
6866
  if (answer > result)
6287
6867
  result = answer;
6288
6868
  }
@@ -6293,7 +6873,7 @@ function isRecursive(inst, stack, resolve9) {
6293
6873
  const desc = Object.getOwnPropertyDescriptor(sh, key);
6294
6874
  if (spread && !desc.enumerable)
6295
6875
  continue;
6296
- const child = desc.get ? ASSUMED : desc.value?._zod ? isRecursive(desc.value, stack, resolve9) : NONE;
6876
+ const child = desc.get ? ASSUMED : desc.value?._zod ? isRecursive(desc.value, stack, resolve10) : NONE;
6297
6877
  if (child > answer)
6298
6878
  answer = child;
6299
6879
  }
@@ -6357,7 +6937,7 @@ function isRecursive(inst, stack, resolve9) {
6357
6937
  break;
6358
6938
  // `$ZodLazy` caches its inner on the def, so a resolved edge is followed exactly
6359
6939
  case "lazy": {
6360
- const inner = def._cachedInner ?? (resolve9 ? inst._zod.innerType : void 0);
6940
+ const inner = def._cachedInner ?? (resolve10 ? inst._zod.innerType : void 0);
6361
6941
  merge2(inner ? isRecursive(inner, stack, false) : ASSUMED);
6362
6942
  break;
6363
6943
  }
@@ -8613,13 +9193,13 @@ var init_errors2 = __esm({
8613
9193
  });
8614
9194
 
8615
9195
  // ../../node_modules/zod/v4/classic/parse.js
8616
- var parse2, parseAsync2, safeParse3, safeParseAsync2, encode2, decode2, encodeAsync2, decodeAsync2, safeEncode2, safeDecode2, safeEncodeAsync2, safeDecodeAsync2;
9196
+ var parse3, parseAsync2, safeParse3, safeParseAsync2, encode2, decode2, encodeAsync2, decodeAsync2, safeEncode2, safeDecode2, safeEncodeAsync2, safeDecodeAsync2;
8617
9197
  var init_parse3 = __esm({
8618
9198
  "../../node_modules/zod/v4/classic/parse.js"() {
8619
9199
  init_core2();
8620
9200
  init_errors2();
8621
9201
  init_core2();
8622
- parse2 = /* @__PURE__ */ _parse(ZodRealError);
9202
+ parse3 = /* @__PURE__ */ _parse(ZodRealError);
8623
9203
  parseAsync2 = /* @__PURE__ */ _parseAsync(ZodRealError);
8624
9204
  safeParse3 = /* @__PURE__ */ _safeParse(ZodRealError);
8625
9205
  safeParseAsync2 = /* @__PURE__ */ _safeParseAsync(ZodRealError);
@@ -8953,7 +9533,7 @@ var init_schemas3 = __esm({
8953
9533
  util_exports.own(this, "~standard", value);
8954
9534
  },
8955
9535
  parse: function _parse2(data, params) {
8956
- return parse2(this, data, params, { callee: _parse2 });
9536
+ return parse3(this, data, params, { callee: _parse2 });
8957
9537
  },
8958
9538
  parseAsync: async function _parseAsync2(data, params) {
8959
9539
  return await parseAsync2(this, data, params, { callee: _parseAsync2 });
@@ -9699,7 +10279,7 @@ __export(iso_exports2, {
9699
10279
  ZodISOTime: () => ZodISOTime,
9700
10280
  date: () => date2,
9701
10281
  datetime: () => datetime2,
9702
- duration: () => duration2,
10282
+ duration: () => duration3,
9703
10283
  time: () => time2
9704
10284
  });
9705
10285
  function datetime2(params) {
@@ -9711,7 +10291,7 @@ function date2(params) {
9711
10291
  function time2(params) {
9712
10292
  return _isoTime(ZodISOTime, params);
9713
10293
  }
9714
- function duration2(params) {
10294
+ function duration3(params) {
9715
10295
  return _isoDuration(ZodISODuration, params);
9716
10296
  }
9717
10297
  var init_iso2 = __esm({
@@ -12242,7 +12822,7 @@ var init_protocol = __esm({
12242
12822
  return;
12243
12823
  }
12244
12824
  const pollInterval = task2.pollInterval ?? this._options?.defaultTaskPollInterval ?? 1e3;
12245
- await new Promise((resolve9) => setTimeout(resolve9, pollInterval));
12825
+ await new Promise((resolve10) => setTimeout(resolve10, pollInterval));
12246
12826
  options?.signal?.throwIfAborted();
12247
12827
  }
12248
12828
  } catch (error2) {
@@ -12259,7 +12839,7 @@ var init_protocol = __esm({
12259
12839
  */
12260
12840
  request(request, resultSchema, options) {
12261
12841
  const { relatedRequestId, resumptionToken, onresumptiontoken, task, relatedTask } = options ?? {};
12262
- return new Promise((resolve9, reject) => {
12842
+ return new Promise((resolve10, reject) => {
12263
12843
  const earlyReject = (error2) => {
12264
12844
  reject(error2);
12265
12845
  };
@@ -12337,7 +12917,7 @@ var init_protocol = __esm({
12337
12917
  if (!parseResult.success) {
12338
12918
  reject(parseResult.error);
12339
12919
  } else {
12340
- resolve9(parseResult.data);
12920
+ resolve10(parseResult.data);
12341
12921
  }
12342
12922
  } catch (error2) {
12343
12923
  reject(error2);
@@ -12599,12 +13179,12 @@ var init_protocol = __esm({
12599
13179
  }
12600
13180
  } catch {
12601
13181
  }
12602
- return new Promise((resolve9, reject) => {
13182
+ return new Promise((resolve10, reject) => {
12603
13183
  if (signal.aborted) {
12604
13184
  reject(new McpError(ErrorCode.InvalidRequest, "Request cancelled"));
12605
13185
  return;
12606
13186
  }
12607
- const timeoutId = setTimeout(resolve9, interval);
13187
+ const timeoutId = setTimeout(resolve10, interval);
12608
13188
  signal.addEventListener("abort", () => {
12609
13189
  clearTimeout(timeoutId);
12610
13190
  reject(new McpError(ErrorCode.InvalidRequest, "Request cancelled"));
@@ -12893,13 +13473,13 @@ var require_scope = __commonJS({
12893
13473
  }
12894
13474
  };
12895
13475
  exports.ValueScopeName = ValueScopeName;
12896
- var line = (0, code_1._)`\n`;
13476
+ var line2 = (0, code_1._)`\n`;
12897
13477
  var ValueScope = class extends Scope {
12898
13478
  constructor(opts) {
12899
13479
  super(opts);
12900
13480
  this._values = {};
12901
13481
  this._scope = opts.scope;
12902
- this.opts = { ...opts, _n: opts.lines ? line : code_1.nil };
13482
+ this.opts = { ...opts, _n: opts.lines ? line2 : code_1.nil };
12903
13483
  }
12904
13484
  get() {
12905
13485
  return this._scope;
@@ -15631,7 +16211,7 @@ var require_compile = __commonJS({
15631
16211
  const schOrFunc = root.refs[ref];
15632
16212
  if (schOrFunc)
15633
16213
  return schOrFunc;
15634
- let _sch = resolve9.call(this, root, ref);
16214
+ let _sch = resolve10.call(this, root, ref);
15635
16215
  if (_sch === void 0) {
15636
16216
  const schema = (_a3 = root.localRefs) === null || _a3 === void 0 ? void 0 : _a3[ref];
15637
16217
  const { schemaId } = this.opts;
@@ -15658,7 +16238,7 @@ var require_compile = __commonJS({
15658
16238
  function sameSchemaEnv(s1, s2) {
15659
16239
  return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId;
15660
16240
  }
15661
- function resolve9(root, ref) {
16241
+ function resolve10(root, ref) {
15662
16242
  let sch;
15663
16243
  while (typeof (sch = this.refs[ref]) == "string")
15664
16244
  ref = sch;
@@ -16518,11 +17098,11 @@ var require_fast_uri = __commonJS({
16518
17098
  normalizeString(uri, options);
16519
17099
  } else if (typeof uri === "object") {
16520
17100
  uri = /** @type {T} */
16521
- parse3(serialize(uri, options), options);
17101
+ parse4(serialize(uri, options), options);
16522
17102
  }
16523
17103
  return uri;
16524
17104
  }
16525
- function resolve9(baseURI, relativeURI, options) {
17105
+ function resolve10(baseURI, relativeURI, options) {
16526
17106
  const schemelessOptions = options ? Object.assign({ scheme: "null" }, options) : { scheme: "null" };
16527
17107
  const {
16528
17108
  parsed: baseParsed,
@@ -16558,50 +17138,50 @@ var require_fast_uri = __commonJS({
16558
17138
  schemelessOptions.skipEscape = true;
16559
17139
  return serialize(resolved, schemelessOptions);
16560
17140
  }
16561
- function resolveComponent(base, relative4, options, skipNormalization) {
17141
+ function resolveComponent(base, relative5, options, skipNormalization) {
16562
17142
  const target = {};
16563
17143
  if (!skipNormalization) {
16564
- base = parse3(serialize(base, options), options);
16565
- relative4 = parse3(serialize(relative4, options), options);
17144
+ base = parse4(serialize(base, options), options);
17145
+ relative5 = parse4(serialize(relative5, options), options);
16566
17146
  }
16567
17147
  options = options || {};
16568
- if (!options.tolerant && relative4.scheme) {
16569
- target.scheme = relative4.scheme;
16570
- target.userinfo = relative4.userinfo;
16571
- target.host = relative4.host;
16572
- target.port = relative4.port;
16573
- target.path = removeDotSegments(relative4.path || "");
16574
- target.query = relative4.query;
17148
+ if (!options.tolerant && relative5.scheme) {
17149
+ target.scheme = relative5.scheme;
17150
+ target.userinfo = relative5.userinfo;
17151
+ target.host = relative5.host;
17152
+ target.port = relative5.port;
17153
+ target.path = removeDotSegments(relative5.path || "");
17154
+ target.query = relative5.query;
16575
17155
  } else {
16576
- if (relative4.userinfo !== void 0 || relative4.host !== void 0 || relative4.port !== void 0) {
16577
- target.userinfo = relative4.userinfo;
16578
- target.host = relative4.host;
16579
- target.port = relative4.port;
16580
- target.path = removeDotSegments(relative4.path || "");
16581
- target.query = relative4.query;
17156
+ if (relative5.userinfo !== void 0 || relative5.host !== void 0 || relative5.port !== void 0) {
17157
+ target.userinfo = relative5.userinfo;
17158
+ target.host = relative5.host;
17159
+ target.port = relative5.port;
17160
+ target.path = removeDotSegments(relative5.path || "");
17161
+ target.query = relative5.query;
16582
17162
  } else {
16583
- if (!relative4.path) {
17163
+ if (!relative5.path) {
16584
17164
  target.path = base.path;
16585
- if (relative4.query !== void 0) {
16586
- target.query = relative4.query;
17165
+ if (relative5.query !== void 0) {
17166
+ target.query = relative5.query;
16587
17167
  } else {
16588
17168
  target.query = base.query;
16589
17169
  }
16590
17170
  } else {
16591
- if (relative4.path[0] === "/") {
16592
- target.path = removeDotSegments(relative4.path);
17171
+ if (relative5.path[0] === "/") {
17172
+ target.path = removeDotSegments(relative5.path);
16593
17173
  } else {
16594
17174
  const baseHasAuthority = base.userinfo !== void 0 || base.host !== void 0 || base.port !== void 0;
16595
17175
  if (baseHasAuthority && !base.path) {
16596
- target.path = "/" + relative4.path;
17176
+ target.path = "/" + relative5.path;
16597
17177
  } else if (!base.path) {
16598
- target.path = relative4.path;
17178
+ target.path = relative5.path;
16599
17179
  } else {
16600
- target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative4.path;
17180
+ target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative5.path;
16601
17181
  }
16602
17182
  target.path = base.scheme === void 0 && !baseHasAuthority && target.path[0] !== "/" ? removeDotSegmentsRelative(target.path) : removeDotSegments(target.path);
16603
17183
  }
16604
- target.query = relative4.query;
17184
+ target.query = relative5.query;
16605
17185
  }
16606
17186
  target.userinfo = base.userinfo;
16607
17187
  target.host = base.host;
@@ -16609,7 +17189,7 @@ var require_fast_uri = __commonJS({
16609
17189
  }
16610
17190
  target.scheme = base.scheme;
16611
17191
  }
16612
- target.fragment = relative4.fragment;
17192
+ target.fragment = relative5.fragment;
16613
17193
  return target;
16614
17194
  }
16615
17195
  function equal(uriA, uriB, options) {
@@ -16880,7 +17460,7 @@ var require_fast_uri = __commonJS({
16880
17460
  }
16881
17461
  return { parsed, malformedAuthorityOrPort, malformedPercentEncoding, malformedSchemeSpecific, malformedHost, malformedScheme };
16882
17462
  }
16883
- function parse3(uri, opts) {
17463
+ function parse4(uri, opts) {
16884
17464
  return parseWithStatus(uri, opts).parsed;
16885
17465
  }
16886
17466
  function normalizeString(uri, opts) {
@@ -16913,11 +17493,11 @@ var require_fast_uri = __commonJS({
16913
17493
  var fastUri = {
16914
17494
  SCHEMES,
16915
17495
  normalize,
16916
- resolve: resolve9,
17496
+ resolve: resolve10,
16917
17497
  resolveComponent,
16918
17498
  equal,
16919
17499
  serialize,
16920
- parse: parse3
17500
+ parse: parse4
16921
17501
  };
16922
17502
  module.exports = fastUri;
16923
17503
  module.exports.default = fastUri;
@@ -20707,7 +21287,7 @@ var require_content_type = __commonJS({
20707
21287
  var QUOTE_REGEXP = /([\\"])/g;
20708
21288
  var TYPE_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
20709
21289
  exports.format = format;
20710
- exports.parse = parse3;
21290
+ exports.parse = parse4;
20711
21291
  function format(obj) {
20712
21292
  if (!obj || typeof obj !== "object") {
20713
21293
  throw new TypeError("argument obj is required");
@@ -20731,7 +21311,7 @@ var require_content_type = __commonJS({
20731
21311
  }
20732
21312
  return string4;
20733
21313
  }
20734
- function parse3(string4) {
21314
+ function parse4(string4) {
20735
21315
  if (!string4) {
20736
21316
  throw new TypeError("argument string is required");
20737
21317
  }
@@ -21952,20 +22532,20 @@ ${value2}`, dataLines++;
21952
22532
  }
21953
22533
  if (firstCharCode === 58) {
21954
22534
  if (onComment) {
21955
- const line2 = chunk.slice(start, end);
21956
- onComment(line2.slice(chunk.charCodeAt(start + 1) === SPACE ? 2 : 1));
22535
+ const line22 = chunk.slice(start, end);
22536
+ onComment(line22.slice(chunk.charCodeAt(start + 1) === SPACE ? 2 : 1));
21957
22537
  }
21958
22538
  return;
21959
22539
  }
21960
- const line = chunk.slice(start, end), fieldSeparatorIndex = line.indexOf(":");
22540
+ const line2 = chunk.slice(start, end), fieldSeparatorIndex = line2.indexOf(":");
21961
22541
  if (fieldSeparatorIndex === -1) {
21962
- processField(line, "", line);
22542
+ processField(line2, "", line2);
21963
22543
  return;
21964
22544
  }
21965
- const field = line.slice(0, fieldSeparatorIndex), offset = line.charCodeAt(fieldSeparatorIndex + 1) === SPACE ? 2 : 1, value = line.slice(fieldSeparatorIndex + offset);
21966
- processField(field, value, line);
22545
+ const field = line2.slice(0, fieldSeparatorIndex), offset = line2.charCodeAt(fieldSeparatorIndex + 1) === SPACE ? 2 : 1, value = line2.slice(fieldSeparatorIndex + offset);
22546
+ processField(field, value, line2);
21967
22547
  }
21968
- function processField(field, value, line) {
22548
+ function processField(field, value, line2) {
21969
22549
  switch (field) {
21970
22550
  case "event":
21971
22551
  eventType = value || void 0;
@@ -21982,7 +22562,7 @@ ${value}`, dataLines++;
21982
22562
  new ParseError(`Invalid \`retry\` value: "${value}"`, {
21983
22563
  type: "invalid-retry",
21984
22564
  value,
21985
- line
22565
+ line: line2
21986
22566
  })
21987
22567
  );
21988
22568
  break;
@@ -21990,7 +22570,7 @@ ${value}`, dataLines++;
21990
22570
  onError(
21991
22571
  new ParseError(
21992
22572
  `Unknown field "${field.length > 20 ? `${field.slice(0, 20)}\u2026` : field}"`,
21993
- { type: "unknown-field", field, value, line }
22573
+ { type: "unknown-field", field, value, line: line2 }
21994
22574
  )
21995
22575
  );
21996
22576
  break;
@@ -23084,8 +23664,8 @@ var init_server2 = __esm({
23084
23664
  });
23085
23665
 
23086
23666
  // ../../node_modules/@modelcontextprotocol/sdk/dist/esm/shared/stdio.js
23087
- function deserializeMessage(line) {
23088
- return JSONRPCMessageSchema.parse(JSON.parse(line));
23667
+ function deserializeMessage(line2) {
23668
+ return JSONRPCMessageSchema.parse(JSON.parse(line2));
23089
23669
  }
23090
23670
  function serializeMessage(message) {
23091
23671
  return JSON.stringify(message) + "\n";
@@ -23115,9 +23695,9 @@ var init_stdio = __esm({
23115
23695
  if (index === -1) {
23116
23696
  return null;
23117
23697
  }
23118
- const line = this._buffer.toString("utf8", 0, index).replace(/\r$/, "");
23698
+ const line2 = this._buffer.toString("utf8", 0, index).replace(/\r$/, "");
23119
23699
  this._buffer = this._buffer.subarray(index + 1);
23120
- return deserializeMessage(line);
23700
+ return deserializeMessage(line2);
23121
23701
  }
23122
23702
  clear() {
23123
23703
  this._buffer = void 0;
@@ -23187,12 +23767,12 @@ var init_stdio2 = __esm({
23187
23767
  this.onclose?.();
23188
23768
  }
23189
23769
  send(message) {
23190
- return new Promise((resolve9) => {
23770
+ return new Promise((resolve10) => {
23191
23771
  const json2 = serializeMessage(message);
23192
23772
  if (this._stdout.write(json2)) {
23193
- resolve9();
23773
+ resolve10();
23194
23774
  } else {
23195
- this._stdout.once("drain", resolve9);
23775
+ this._stdout.once("drain", resolve10);
23196
23776
  }
23197
23777
  });
23198
23778
  }
@@ -23225,7 +23805,7 @@ function createCodingMcpServer(options = {}) {
23225
23805
  throw new McpError(ErrorCode.InvalidRequest, signIn);
23226
23806
  }
23227
23807
  };
23228
- const uuid9 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
23808
+ const uuid16 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
23229
23809
  const grantOf = (config2) => storedGrant(config2, endpoint2.href);
23230
23810
  async function renew() {
23231
23811
  try {
@@ -23241,7 +23821,7 @@ function createCodingMcpServer(options = {}) {
23241
23821
  const config2 = readConfig();
23242
23822
  const grant = grantOf(config2);
23243
23823
  const organizationIds = grant ? grant.organizationIds : config2.organizationId ? [config2.organizationId] : [];
23244
- if (!grant && (!config2.organizationId || !uuid9.test(config2.organizationId) || !config2.token || /[\r\n]/.test(config2.token) || /^bf(?:cli|agent|mcp)_/i.test(config2.token)))
23824
+ if (!grant && (!config2.organizationId || !uuid16.test(config2.organizationId) || !config2.token || /[\r\n]/.test(config2.token) || /^bf(?:cli|agent|mcp)_/i.test(config2.token)))
23245
23825
  throw new McpError(ErrorCode.InvalidRequest, signIn);
23246
23826
  if (boundOrganizationId && !organizationIds.some((id) => id.toLowerCase() === boundOrganizationId.toLowerCase()))
23247
23827
  throw new McpError(ErrorCode.InvalidRequest, "Organization changed. Restart the Backify MCP connection to explicitly select the new organization.");
@@ -23341,7 +23921,7 @@ function opsArguments(args2) {
23341
23921
  if (value === void 0 || flag !== "--param" && value.startsWith("--")) throw new Error(flag + " needs a value.");
23342
23922
  switch (flag) {
23343
23923
  case "--organization":
23344
- if (!uuid8.test(value)) throw new Error("--organization must be an organization ID (UUID).");
23924
+ if (!uuid9.test(value)) throw new Error("--organization must be an organization ID (UUID).");
23345
23925
  parsed.organizationId = value;
23346
23926
  break;
23347
23927
  case "--group":
@@ -23588,7 +24168,7 @@ function searchResult(catalog, session, options) {
23588
24168
  const routeWidth = Math.min(64, Math.max(0, ...page.map((operation) => operation.method.length + operation.path.length + 1)) + 2);
23589
24169
  for (const operation of page) {
23590
24170
  const access = operation.missingScopes === null ? " [not delegable]" : operation.missingScopes.length ? ` [needs ${operation.missingScopes.join(" ")}]` : "";
23591
- lines.push(" " + pad(operation.id, idWidth) + pad(`${operation.method} ${operation.path}`, routeWidth) + (operation.summary ?? "") + access);
24171
+ lines.push(" " + pad2(operation.id, idWidth) + pad2(`${operation.method} ${operation.path}`, routeWidth) + (operation.summary ?? "") + access);
23592
24172
  }
23593
24173
  if (groups) lines.push("", "Groups: " + groups.join(", "));
23594
24174
  if (page.length) lines.push("", "Next: backify ops describe <operationId>");
@@ -23674,7 +24254,7 @@ async function organizationCall(context2, organizationId) {
23674
24254
  const session = await signIn2(context2, organizationId);
23675
24255
  return { call: sessionCall(session, context2), organizationId: session.organizationId };
23676
24256
  }
23677
- var opsHelp, OpsError, uuid8, valueFlags, booleanFlags, reconnect, contentTypes, sensitiveKey, pad;
24257
+ var opsHelp, OpsError, uuid9, valueFlags, booleanFlags, reconnect, contentTypes, sensitiveKey, pad2;
23678
24258
  var init_ops = __esm({
23679
24259
  "src/ops.ts"() {
23680
24260
  "use strict";
@@ -23704,7 +24284,7 @@ var init_ops = __esm({
23704
24284
  this.details = details;
23705
24285
  }
23706
24286
  };
23707
- uuid8 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
24287
+ uuid9 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
23708
24288
  valueFlags = {
23709
24289
  "--organization": ["search", "describe", "get", "run"],
23710
24290
  "--group": ["search"],
@@ -23736,7 +24316,7 @@ var init_ops = __esm({
23736
24316
  ".tgz": "application/gzip"
23737
24317
  };
23738
24318
  sensitiveKey = /secret|password|passphrase|token|credential|private|api[-_]?key|connection[-_]?string/i;
23739
- pad = (value, width) => value.length >= width ? value + " " : value + " ".repeat(width - value.length);
24319
+ pad2 = (value, width) => value.length >= width ? value + " " : value + " ".repeat(width - value.length);
23740
24320
  }
23741
24321
  });
23742
24322
 
@@ -23745,12 +24325,29 @@ var tasks_exports = {};
23745
24325
  __export(tasks_exports, {
23746
24326
  opsHumanTaskHandler: () => opsHumanTaskHandler,
23747
24327
  runTaskCommand: () => runTaskCommand,
24328
+ runtimeUpgradeText: () => runtimeUpgradeText,
23748
24329
  startTask: () => startTask,
23749
24330
  taskArguments: () => taskArguments,
23750
24331
  taskDraft: () => taskDraft,
23751
24332
  taskHelp: () => taskHelp
23752
24333
  });
23753
24334
  import { readFileSync as readFileSync12 } from "node:fs";
24335
+ function runtimeUpgradeText(deployment) {
24336
+ const upgrade = deployment.upgrade;
24337
+ if (!upgrade) return deployment.updateAvailable ? `Runtime ${deployment.version ?? "unknown"}. Version ${deployment.latestVersion} is available; no upgrade has been proposed yet.` : `Runtime ${deployment.version ?? "unknown"} is up to date.`;
24338
+ const lines = [`Upgrade to ${upgrade.targetVersion} from ${upgrade.previousVersion ?? deployment.version ?? "unknown"}: ${upgrade.phase} (${upgrade.state})`];
24339
+ const verification = upgrade.verification;
24340
+ if (verification?.signature === "valid") lines.push("Verification: signature and digest verified" + (verification.protocol ? `; protocol versions ${verification.protocol.min} to ${verification.protocol.max}` : "") + (verification.stateSchema?.reads ? `; reads data formats ${verification.stateSchema.reads.min} to ${verification.stateSchema.reads.max}` : ""));
24341
+ if (upgrade.phase === "canary" || upgrade.canary) {
24342
+ const outcome = upgrade.canary ?? { succeeded: 0, failed: 0, running: 0 };
24343
+ lines.push(`Canary: ${outcome.succeeded + outcome.failed} commands finished, ${outcome.failed} failed, ${outcome.running} running` + (upgrade.soakUntil && upgrade.phase === "canary" ? `; observation period ends ${upgrade.soakUntil}` : ""));
24344
+ }
24345
+ if (upgrade.phase === "canary" || upgrade.phase === "promoted") lines.push("The previous version is kept and can be restored until the upgrade is committed.");
24346
+ if (upgrade.phase === "rolled-back") lines.push(`Rolled back: ${upgrade.detail ?? upgrade.failureCode ?? "reason not reported"}`);
24347
+ if (upgrade.phase === "failed") lines.push(`Failed: ${[upgrade.failureCode, upgrade.detail].filter(Boolean).join(": ") || "no details reported"}`);
24348
+ if (upgrade.state === "awaiting-approval") lines.push("Approve it with: backify azure update-runtime --connection <id>");
24349
+ return lines.join("\n");
24350
+ }
23754
24351
  function taskArguments(args2) {
23755
24352
  const options = { noBrowser: false, noWait: false, json: false, yes: false };
23756
24353
  const positional = [], values = {};
@@ -23879,8 +24476,29 @@ async function runTaskCommand(command2, args2, context2) {
23879
24476
  return { result: await start("azure.connect", { ...values.subscription ? { subscriptionId: values.subscription[0] } : {}, ...values.region ? { region: values.region[0] } : {} }), json: options.json };
23880
24477
  case "azure reconnect":
23881
24478
  return { result: await start("azure.elevate", { connectionId: connection(values) }), json: options.json };
23882
- case "azure update-agent":
23883
- return { result: await start("azure.agent_update", { connectionId: connection(values) }), json: options.json };
24479
+ case "azure update-runtime": {
24480
+ const id = connection(values);
24481
+ const alreadyRunning = (deployment) => upgradeInProgress(deployment?.upgrade) ? { result: { value: { state: "in-progress", exitCode: 0, upgrade: deployment.upgrade }, text: "An upgrade is already in progress.\n" + runtimeUpgradeText(deployment), exitCode: 0 }, json: options.json } : void 0;
24482
+ const current = await call2("/cloud-connections/" + id + "/runtime").catch(() => void 0);
24483
+ const running = alreadyRunning(current);
24484
+ if (running) return running;
24485
+ try {
24486
+ return { result: await start("azure.runtime_update", { connectionId: id }), json: options.json };
24487
+ } catch (error2) {
24488
+ if (error2?.code !== "runtime_upgrade_in_progress" && !String(error2?.message).includes("runtime_upgrade_in_progress")) throw error2;
24489
+ return alreadyRunning(await call2("/cloud-connections/" + id + "/runtime").catch(() => void 0)) ?? { result: { value: { state: "in-progress", exitCode: 0 }, text: "An upgrade is already in progress.", exitCode: 0 }, json: options.json };
24490
+ }
24491
+ }
24492
+ case "azure runtime-upgrade": {
24493
+ const deployment = await call2("/cloud-connections/" + connection(values) + "/runtime");
24494
+ return { result: { value: deployment, text: runtimeUpgradeText(deployment), exitCode: 0 }, json: options.json };
24495
+ }
24496
+ case "azure grant-scope": {
24497
+ const scope = await call2("/cloud-connections/" + connection(values) + "/grant-scope");
24498
+ return { result: { value: scope, text: JSON.stringify(scope, null, 2), exitCode: 0 }, json: options.json };
24499
+ }
24500
+ case "azure rescope-grants":
24501
+ return { result: await start("azure.grant_rescope", { connectionId: connection(values) }), json: options.json };
23884
24502
  case "azure uninstall":
23885
24503
  return { result: await start("azure.uninstall", { connectionId: connection(values) }), json: options.json };
23886
24504
  case "azure remove":
@@ -23965,7 +24583,7 @@ async function runTaskCommand(command2, args2, context2) {
23965
24583
  throw new Error("Unknown command.\n\n" + taskHelp);
23966
24584
  }
23967
24585
  }
23968
- var taskHelp, purposes, connection;
24586
+ var taskHelp, purposes, upgradeEnded, upgradeInProgress, connection;
23969
24587
  var init_tasks = __esm({
23970
24588
  "src/tasks.ts"() {
23971
24589
  "use strict";
@@ -23980,10 +24598,15 @@ var init_tasks = __esm({
23980
24598
  "",
23981
24599
  " backify github connect Install or choose the Backify GitHub App (github.install)",
23982
24600
  " backify azure connect [--subscription <id>] [--region <name>] Connect an Azure subscription (azure.connect)",
23983
- " backify azure reconnect|update-agent|uninstall|remove --connection <id>",
23984
- " Renew authorization, approve an agent update, uninstall the agent,",
23985
- " or remove everything Backify created (azure.elevate, azure.agent_update,",
23986
- " azure.uninstall, azure.remove)",
24601
+ " backify azure reconnect|update-runtime|uninstall|remove --connection <id>",
24602
+ " Renew authorization, approve a proposed Runtime upgrade (applications are not",
24603
+ " redeployed; the previous version is kept until it is committed), uninstall the",
24604
+ " Runtime, or remove everything Backify created (azure.elevate, azure.runtime_update,",
24605
+ " azure.uninstall, azure.remove). update-runtime exits 0 with the current phase",
24606
+ " when an upgrade is already in progress.",
24607
+ " backify azure grant-scope --connection <id> [--json] Show the grant scope, proposed changes and latest re-scope operation",
24608
+ " backify azure rescope-grants --connection <id> Request Azure administrator review and approval of scoped grants",
24609
+ " backify azure runtime-upgrade --connection <id> [--json] Show the Runtime upgrade: phase, versions, verification, canary outcome, end state",
23987
24610
  " backify org Organization summary",
23988
24611
  " backify billing Subscription status",
23989
24612
  " backify billing checkout|change-plan [--plan <plan>] [--interval <interval>] [--currency <currency>]",
@@ -24002,7 +24625,8 @@ var init_tasks = __esm({
24002
24625
  "github.install",
24003
24626
  "azure.connect",
24004
24627
  "azure.elevate",
24005
- "azure.agent_update",
24628
+ "azure.runtime_update",
24629
+ "azure.grant_rescope",
24006
24630
  "azure.uninstall",
24007
24631
  "azure.remove",
24008
24632
  "approval",
@@ -24023,8 +24647,9 @@ var init_tasks = __esm({
24023
24647
  "github.install": "connect GitHub",
24024
24648
  "azure.connect": "connect Azure",
24025
24649
  "azure.elevate": "renew Backify's Azure authorization",
24026
- "azure.agent_update": "approve the Backify Cloud Agent update",
24027
- "azure.uninstall": "uninstall the Backify Cloud Agent",
24650
+ "azure.runtime_update": "approve the proposed Backify Runtime upgrade",
24651
+ "azure.grant_rescope": "review and approve scoped Azure grants",
24652
+ "azure.uninstall": "uninstall the Backify Runtime",
24028
24653
  "azure.remove": "remove everything Backify created in Azure",
24029
24654
  "approval": "approve or reject the request",
24030
24655
  "sso.test_signin": "test single sign-on",
@@ -24038,6 +24663,8 @@ var init_tasks = __esm({
24038
24663
  "billing.checkout": "review the subscription and complete Stripe Checkout",
24039
24664
  "billing.change_plan": "review the plan change"
24040
24665
  };
24666
+ upgradeEnded = (upgrade) => ["committed", "rolled-back", "failed"].includes(upgrade.phase);
24667
+ upgradeInProgress = (upgrade) => !!upgrade && !upgradeEnded(upgrade) && upgrade.state !== "awaiting-approval";
24041
24668
  connection = (values) => {
24042
24669
  const id = values.connection?.[0];
24043
24670
  if (!id || !isUuid(id)) throw new Error("Pass --connection <cloud-connection-id>.");
@@ -24070,9 +24697,9 @@ function configureCodingTool(options) {
24070
24697
  if (!codingTools.includes(options.agent)) throw new Error("Select --agent copilot, cursor, gemini, cline, or windsurf. Codex and Claude Code use the Backify plugin.");
24071
24698
  const agent = options.agent, transport = options.transport ?? "http";
24072
24699
  if (transport !== "http" && transport !== "stdio") throw new Error("Select --transport http or stdio.");
24073
- const relative4 = options.configPath ?? defaultPaths[agent];
24074
- if (!relative4) throw new Error("Open this tool's MCP configuration and supply its exact path with --config. Backify will not guess or modify an editor's global storage.");
24075
- const path = resolve5(options.root ?? process.cwd(), relative4);
24700
+ const relative5 = options.configPath ?? defaultPaths[agent];
24701
+ if (!relative5) throw new Error("Open this tool's MCP configuration and supply its exact path with --config. Backify will not guess or modify an editor's global storage.");
24702
+ const path = resolve5(options.root ?? process.cwd(), relative5);
24076
24703
  for (let current = path; ; current = dirname5(current)) {
24077
24704
  if (existsSync9(current) && (lstatSync4(current).isSymbolicLink() || current === path && !lstatSync4(current).isFile())) throw new Error("MCP configuration cannot traverse symlinks or replace a directory.");
24078
24705
  if (dirname5(current) === current) break;
@@ -24119,6 +24746,131 @@ var init_coding_tools = __esm({
24119
24746
  }
24120
24747
  });
24121
24748
 
24749
+ // src/auth-identity.ts
24750
+ var auth_identity_exports = {};
24751
+ __export(auth_identity_exports, {
24752
+ authIdentityArguments: () => authIdentityArguments,
24753
+ authIdentityHelp: () => authIdentityHelp,
24754
+ identityFailureText: () => identityFailureText,
24755
+ identityStatusText: () => identityStatusText,
24756
+ resolveEnvironment: () => resolveEnvironment,
24757
+ runAuthIdentity: () => runAuthIdentity
24758
+ });
24759
+ function authIdentityArguments(args2) {
24760
+ if (args2.includes("--help") || args2.includes("-h")) return "help";
24761
+ const { flags, values, positional } = parse(args2, "auth identity", ["--json"], ["--app", "--environment", "--confirm"]);
24762
+ const action = (positional[0] ?? "status").toLowerCase(), json2 = flags.has("--json");
24763
+ if (!["status", "move", "move-back", "clear"].includes(action) || positional.length > 1) throw new Error("Unknown auth identity command: " + positional.join(" ") + "\n\n" + authIdentityHelp);
24764
+ if (action === "status" && (values["--environment"] !== void 0 || values["--confirm"] !== void 0)) throw new Error("--environment and --confirm apply to auth identity move.");
24765
+ if (action === "clear" && values["--confirm"] !== void 0) throw new Error("--confirm applies to auth identity move and move-back.");
24766
+ if (action !== "status" && values["--environment"] === void 0) throw new Error("Name the environment to " + (action === "clear" ? "clear" : "move") + " with --environment <name|id>.");
24767
+ return { action, ...values["--environment"] !== void 0 ? { environment: values["--environment"] } : {}, ...values["--confirm"] !== void 0 ? { confirm: values["--confirm"] } : {}, json: json2 };
24768
+ }
24769
+ function pad3(rows) {
24770
+ const widths = rows[0].map((_, column) => Math.max(...rows.map((row) => row[column].length)));
24771
+ return rows.map((row) => row.map((cell, column) => column === row.length - 1 ? cell : cell.padEnd(widths[column])).join(" ").trimEnd());
24772
+ }
24773
+ function identityStatusText(statuses, names = /* @__PURE__ */ new Map()) {
24774
+ if (!statuses.length) return "This application has no environments.";
24775
+ const name2 = (status) => names.get(status.environmentId) ?? status.kind;
24776
+ const rows = pad3([["ENVIRONMENT", "SIGN-IN DATA", "WAITING FOR RUNTIME"], ...statuses.map((status) => [name2(status), where(status.authority), status.pendingCommands ? status.pendingCommands + " change" + (status.pendingCommands === 1 ? "" : "s") + (status.oldestPendingAt ? " since " + status.oldestPendingAt : "") : "-"])]);
24777
+ const notes = statuses.flatMap((status) => {
24778
+ const relocation = status.relocation;
24779
+ if (status.authority === "relocating") return [name2(status) + ": moving sign-in data. Sign-in for this environment and user management for the application are paused."];
24780
+ if (status.authority === "returning") return [name2(status) + ": moving sign-in data back to Backify. Sign-in for this environment and user management for the application are paused."];
24781
+ const back = relocation?.direction === "to-control-plane";
24782
+ const reason = (code) => (identityFailureText[code ?? ""] ?? "Nothing was changed.") + (code ? " (" + code + ")" : "");
24783
+ if (relocation?.state === "failed" && back && status.authority === "environment") return [name2(status) + ": the last move back to Backify did not finish. " + reason(relocation.failureCode)];
24784
+ if (relocation?.state === "failed" && !back && status.authority !== "environment") {
24785
+ if (relocation.clearedAt) return [];
24786
+ if (relocation.clearRequestedAt) return [name2(status) + ": clearing what the failed move left in the environment's database."];
24787
+ return [name2(status) + ": the last move did not finish. " + reason(relocation.failureCode) + " Clear it with: backify auth identity clear --environment " + name2(status)];
24788
+ }
24789
+ return [];
24790
+ });
24791
+ const waiting = statuses.some((status) => status.pendingCommands > 0) ? ["Role and session changes wait until the Runtime applies them, usually within about 30 seconds, and stay waiting while the Runtime is unreachable."] : [];
24792
+ return [...rows, ...notes.length || waiting.length ? [""] : [], ...notes, ...waiting].join("\n");
24793
+ }
24794
+ function resolveEnvironment(input, environments, statuses) {
24795
+ const wanted = input.trim().toLowerCase();
24796
+ const matches = statuses.filter((status) => {
24797
+ const named = environments.find((value) => value.id === status.environmentId);
24798
+ const labels = [status.environmentId, status.kind, named?.name, named?.kind, status.kind === "live" ? "production" : void 0].filter((value) => Boolean(value)).map((value) => value.toLowerCase());
24799
+ return labels.includes(wanted);
24800
+ });
24801
+ if (matches.length === 1) return matches[0];
24802
+ const available = statuses.map((status) => environments.find((value) => value.id === status.environmentId)?.name ?? status.kind).join(", ");
24803
+ throw new CommandError((matches.length ? "More than one environment matches " : "No environment matches ") + input + ". Use an environment name or ID" + (available ? " (" + available + ")" : "") + ".", "environment_not_found", { environment: input });
24804
+ }
24805
+ async function runAuthIdentity(call2, applicationId, options) {
24806
+ if (!uuid10.test(applicationId)) throw new Error("Use a valid application ID.");
24807
+ const prefix = "/apps/" + applicationId, base = prefix + "/auth/identity";
24808
+ const statuses = await call2(base);
24809
+ const environments = await call2(prefix + "/environments").catch(() => []);
24810
+ const names = new Map(environments.map((value) => [value.id, value.name]));
24811
+ if (options.action === "status") return { value: statuses, text: identityStatusText(statuses, names) };
24812
+ const target = resolveEnvironment(options.environment, environments, statuses), label = names.get(target.environmentId) ?? target.kind;
24813
+ if (target.authority === "relocating" || target.authority === "returning") throw new CommandError("Sign-in data for " + label + " is already being moved.", "identity_relocation_in_progress", { environmentId: target.environmentId });
24814
+ if (options.action === "clear") {
24815
+ const relocation2 = await call2(base + "/clear", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ environmentId: target.environmentId }) });
24816
+ return {
24817
+ value: { status: relocation2.clearedAt ? "cleared" : "clearing", environmentId: target.environmentId, relocation: relocation2 },
24818
+ text: relocation2.clearedAt ? "What the failed move left in " + label + "'s database is already cleared." : "Clearing what the failed move left in " + label + "'s database. Sign-in for " + label + " stays with Backify.\nCheck progress with: backify auth identity"
24819
+ };
24820
+ }
24821
+ if (options.action === "move-back") {
24822
+ if (target.authority !== "environment") throw new CommandError("Sign-in data for " + label + " is already kept by Backify.", "identity_move_back_not_needed", { environmentId: target.environmentId });
24823
+ const slug2 = (await call2(prefix)).slug;
24824
+ if (!options.confirm || options.confirm !== slug2) {
24825
+ const summary = "Moving sign-in data for " + label + " back to Backify pauses sign-in for that environment and user management for the application while the data is moved. Users, roles, passkeys and signed-in sessions are kept. Afterwards, sign-in for " + label + " stops working while Backify is unavailable.";
24826
+ throw new CommandError((options.confirm ? "The confirmation does not match the application slug. " : "") + summary + "\nConfirm with the application slug: backify auth identity move-back --environment " + options.environment + " --confirm " + (slug2 ?? "<application-slug>"), options.confirm ? "confirmation_mismatch" : "confirmation_required", slug2 ? { confirm: slug2 } : {});
24827
+ }
24828
+ const relocation2 = await call2(base + "/move-back", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ environmentId: target.environmentId }) });
24829
+ return { value: { status: "moving-back", environmentId: target.environmentId, relocation: relocation2 }, text: ["Moving sign-in data for " + label + " back to Backify.", "Sign-in for this environment and user management for the application are paused until it finishes, usually within a minute.", "Check progress with: backify auth identity"].join("\n") };
24830
+ }
24831
+ if (target.authority === "relocating") throw new CommandError("Sign-in data for " + label + " is already being moved.", "identity_relocation_in_progress", { environmentId: target.environmentId });
24832
+ if (target.authority === "environment") throw new CommandError("Sign-in data for " + label + " is already in its own database.", "identity_relocation_not_needed", { environmentId: target.environmentId });
24833
+ const slug = (await call2(prefix)).slug;
24834
+ if (!options.confirm || options.confirm !== slug) {
24835
+ const summary = "Moving sign-in data for " + label + " pauses sign-in for that environment and user management for the application while the data is moved. It can be moved back later with backify auth identity move-back. Afterwards, sign-in for " + label + " keeps working if Backify is unavailable.";
24836
+ throw new CommandError((options.confirm ? "The confirmation does not match the application slug. " : "") + summary + "\nConfirm with the application slug: backify auth identity move --environment " + options.environment + " --confirm " + (slug ?? "<application-slug>"), options.confirm ? "confirmation_mismatch" : "confirmation_required", slug ? { confirm: slug } : {});
24837
+ }
24838
+ const relocation = await call2(base + "/relocate", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ environmentId: target.environmentId }) });
24839
+ return { value: { status: "moving", environmentId: target.environmentId, relocation }, text: ["Moving sign-in data for " + label + ": " + relocation.users + " users, " + relocation.links + " linked identities, " + relocation.passkeys + " passkeys, " + relocation.sessions + " sessions.", "Sign-in for this environment and user management for the application are paused until it finishes, usually within a minute.", "Check progress with: backify auth identity"].join("\n") };
24840
+ }
24841
+ var authIdentityHelp, uuid10, where, identityFailureText;
24842
+ var init_auth_identity = __esm({
24843
+ "src/auth-identity.ts"() {
24844
+ "use strict";
24845
+ init_release_flow();
24846
+ authIdentityHelp = [
24847
+ "Usage: backify auth identity [options]",
24848
+ " backify auth identity move --environment <name|id> --confirm <application-slug> [options]",
24849
+ " backify auth identity move-back --environment <name|id> --confirm <application-slug> [options]",
24850
+ " backify auth identity clear --environment <name|id> [options]",
24851
+ "",
24852
+ " backify auth identity Where each environment's sign-in data lives (Backify or the environment's database),",
24853
+ " changes still waiting for the Runtime and the latest move",
24854
+ " backify auth identity move Move one environment's sign-in data (users, roles, passkeys, sessions) into its own database",
24855
+ " backify auth identity move-back Move it back from the environment's database to Backify, keeping users, roles, links and sessions",
24856
+ " backify auth identity clear Clear what a failed move left in the environment's database (sign-in stays with Backify)",
24857
+ "",
24858
+ "Options: --app <application> (default: the application in this folder) --json (machine-readable output and errors)",
24859
+ "Moving and clearing need permission to manage access. While the data is moved, sign-in for that environment and user management",
24860
+ "for the application pause. In the environment's database, sign-in keeps working if Backify is unavailable; moved back, it does not.",
24861
+ "Moving back is refused while a handoff or hosting move is active. Without --confirm a move changes nothing and prints the slug to confirm with."
24862
+ ].join("\n");
24863
+ uuid10 = /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;
24864
+ where = (authority) => authority === "environment" ? "this environment's database" : authority === "relocating" ? "moving to this environment's database" : authority === "returning" ? "moving back to Backify" : "Backify";
24865
+ identityFailureText = {
24866
+ identity_relocation_mismatch: "The moved data did not match what Backify holds, so nothing was changed.",
24867
+ identity_relocation_source_changed: "Sign-in data changed while it was being moved, so nothing was changed.",
24868
+ identity_relocation_too_large: "The application has more sign-in data than one move can carry.",
24869
+ identity_relocation_conflict: "Some of the moved data belongs to another application, so nothing was changed."
24870
+ };
24871
+ }
24872
+ });
24873
+
24122
24874
  // src/app/project.ts
24123
24875
  var project_exports = {};
24124
24876
  __export(project_exports, {
@@ -24364,8 +25116,8 @@ function analyzeAppDeclarations(files) {
24364
25116
  continue;
24365
25117
  const source = ts2.createSourceFile(path, file.content, ts2.ScriptTarget.Latest, true, /\.[jt]sx$/.test(path) ? ts2.ScriptKind.TSX : ts2.ScriptKind.TS);
24366
25118
  const report = (node2, severity, code, message) => {
24367
- const { line, character } = source.getLineAndCharacterOfPosition(node2.getStart(source));
24368
- diagnostics.push({ severity, code, message, file: path, line: line + 1, column: character + 1, docs: DOCS });
25119
+ const { line: line2, character } = source.getLineAndCharacterOfPosition(node2.getStart(source));
25120
+ diagnostics.push({ severity, code, message, file: path, line: line2 + 1, column: character + 1, docs: DOCS });
24369
25121
  };
24370
25122
  const imported = /* @__PURE__ */ new Map();
24371
25123
  const namespaces = /* @__PURE__ */ new Set();
@@ -24612,32 +25364,32 @@ function analyzeFile(file, used, diagnostics, wrappers) {
24612
25364
  if (!element.isTypeOnly)
24613
25365
  bind(element.name, memberReference(base, (element.propertyName ?? element.name).text));
24614
25366
  }
24615
- const resolve9 = (node2) => {
25367
+ const resolve10 = (node2) => {
24616
25368
  if (ts3.isParenthesizedExpression(node2) || ts3.isAsExpression(node2) || ts3.isNonNullExpression(node2) || ts3.isAwaitExpression(node2) || ts3.isSatisfiesExpression(node2))
24617
- return resolve9(node2.expression);
25369
+ return resolve10(node2.expression);
24618
25370
  if (ts3.isIdentifier(node2)) {
24619
25371
  const value = symbol(node2);
24620
25372
  return value ? references.get(value) : void 0;
24621
25373
  }
24622
25374
  if (ts3.isPropertyAccessExpression(node2))
24623
- return memberReference(resolve9(node2.expression), node2.name.text);
25375
+ return memberReference(resolve10(node2.expression), node2.name.text);
24624
25376
  if (ts3.isElementAccessExpression(node2) && ts3.isStringLiteralLike(node2.argumentExpression))
24625
- return memberReference(resolve9(node2.expression), node2.argumentExpression.text);
25377
+ return memberReference(resolve10(node2.expression), node2.argumentExpression.text);
24626
25378
  if (ts3.isCallExpression(node2)) {
24627
25379
  const loaded = loadedModule(node2);
24628
25380
  if (loaded !== void 0)
24629
25381
  return loaded === null ? void 0 : moduleReference(loaded);
24630
- return resolve9(node2.expression)?.kind === "factory" ? { kind: "root" } : void 0;
25382
+ return resolve10(node2.expression)?.kind === "factory" ? { kind: "root" } : void 0;
24631
25383
  }
24632
25384
  return void 0;
24633
25385
  };
24634
25386
  const capability2 = (node2) => {
24635
- const reference = resolve9(node2);
25387
+ const reference = resolve10(node2);
24636
25388
  return reference?.kind === "capability" ? reference.capability : void 0;
24637
25389
  };
24638
25390
  const collect = (node2) => {
24639
25391
  if (ts3.isVariableDeclaration(node2) && node2.initializer) {
24640
- const base = resolve9(node2.initializer);
25392
+ const base = resolve10(node2.initializer);
24641
25393
  if (base && ts3.isIdentifier(node2.name))
24642
25394
  bind(node2.name, base);
24643
25395
  else if (base && ts3.isObjectBindingPattern(node2.name))
@@ -24713,8 +25465,8 @@ var init_dist3 = __esm({
24713
25465
  sdkCapability = (name2) => Object.hasOwn(SDK_IMPORT_CAPABILITIES, name2) ? SDK_IMPORT_CAPABILITIES[name2] : void 0;
24714
25466
  modulePath = (path) => posix.normalize(path.replaceAll("\\", "/")).replace(/\.[cm]?[jt]sx?$/, "").replace(/\/index$/, "");
24715
25467
  position = (source, node2) => {
24716
- const { line, character } = source.getLineAndCharacterOfPosition(node2.getStart(source));
24717
- return { line: line + 1, column: character + 1 };
25468
+ const { line: line2, character } = source.getLineAndCharacterOfPosition(node2.getStart(source));
25469
+ return { line: line2 + 1, column: character + 1 };
24718
25470
  };
24719
25471
  }
24720
25472
  });
@@ -24740,7 +25492,14 @@ function usedCapabilities(root, files) {
24740
25492
  function migrationDigests(root, config2) {
24741
25493
  const directory = join14(root, config2.database?.migrations ?? "db/migrations");
24742
25494
  if (!existsSync11(directory)) return [];
24743
- return readdirSync4(directory).filter((f) => f.endsWith(".sql")).sort().map((file) => ({ file, sha256: createHash4("sha256").update(readFileSync16(join14(directory, file))).digest("hex") }));
25495
+ return readdirSync4(directory).filter((f) => f.endsWith(".sql")).sort().map((file) => ({ file, sha256: createHash4("sha256").update(withLfLineEndings(readFileSync16(join14(directory, file)))).digest("hex") }));
25496
+ }
25497
+ function withLfLineEndings(content) {
25498
+ if (!content.includes("\r\n")) return content;
25499
+ const out = Buffer.allocUnsafe(content.length);
25500
+ let length = 0;
25501
+ for (let i = 0; i < content.length; i++) if (content[i] !== 13 || content[i + 1] !== 10) out[length++] = content[i];
25502
+ return out.subarray(0, length);
24744
25503
  }
24745
25504
  function declarationDiagnostics(root, files) {
24746
25505
  const sources = files.filter((file) => /\.[cm]?[jt]sx?$/.test(file)).map((file) => ({ path: file, content: readFileSync16(join14(root, file), "utf8") }));
@@ -24764,9 +25523,9 @@ async function generateLockfile(root) {
24764
25523
  warnings.push(...declarations.warnings);
24765
25524
  const result = await runNode(["--enable-source-maps", runner, "describe", bundle.file], { cwd: root, env: isolatedEnv({ BACKIFY_PROCESS_ROLE: "describe", BACKIFY_HEALTH_PATH: config2.server.health ?? "/healthz" }) });
24766
25525
  if (result.code !== 0) throw new ProjectError("Describing the server failed. Declarations must run at module top level without connecting to databases or services.\n" + (result.stderr || result.stdout).trim().split("\n").slice(-15).join("\n"));
24767
- const line = result.stdout.trim().split("\n").at(-1) ?? "";
25526
+ const line2 = result.stdout.trim().split("\n").at(-1) ?? "";
24768
25527
  try {
24769
- catalog = JSON.parse(line);
25528
+ catalog = JSON.parse(line2);
24770
25529
  } catch {
24771
25530
  throw new ProjectError("backify-run describe printed unexpected output:\n" + result.stdout.slice(-2e3));
24772
25531
  }
@@ -24780,8 +25539,8 @@ async function generateLockfile(root) {
24780
25539
  if (used.has("events") || catalog.jobs.length) capabilities.add("database");
24781
25540
  const needsConfig = { storage: "storage.buckets", ai: "ai", mail: "mail", http: "http.allow", integrations: "integrations", secrets: "secrets", database: "database", protection: "protection" };
24782
25541
  for (const capability2 of used) {
24783
- const where = needsConfig[capability2];
24784
- if (where && !configuredCapabilities(config2).includes(capability2) && !(capability2 === "database" && capabilities.has("jobs"))) problems.push(`Server code uses ${capability2} but backify.config.ts does not configure ${where}`);
25542
+ const where2 = needsConfig[capability2];
25543
+ if (where2 && !configuredCapabilities(config2).includes(capability2) && !(capability2 === "database" && capabilities.has("jobs"))) problems.push(`Server code uses ${capability2} but backify.config.ts does not configure ${where2}`);
24785
25544
  }
24786
25545
  if (config2.server && !catalog.backend && config2.kind !== "worker") problems.push(`A ${config2.kind} app needs a backend: call defineBackend() in ${config2.server.entry}`);
24787
25546
  if (config2.kind === "worker" && catalog.backend) problems.push('Worker apps cannot declare a backend; use kind "api" instead');
@@ -24803,7 +25562,7 @@ async function generateLockfile(root) {
24803
25562
  extensions: config2.database?.extensions?.length ? [...config2.database.extensions].sort() : void 0,
24804
25563
  personalData: config2.database?.personalData ? normalizePersonalData(config2.database.personalData) : void 0
24805
25564
  } : void 0,
24806
- auth: config2.auth ? { providers: [...config2.auth.providers], roles: [...config2.auth.roles ?? []].sort() } : void 0,
25565
+ auth: config2.auth ? { providers: [...config2.auth.providers], defaultProvider: config2.auth.defaultProvider, roles: [...config2.auth.roles ?? []].sort(), session: lockSession(config2.auth.session) } : void 0,
24807
25566
  config: config2.config,
24808
25567
  ai: config2.ai,
24809
25568
  http: config2.http,
@@ -24823,6 +25582,10 @@ async function generateLockfile(root) {
24823
25582
  problems.push(...validateLockfile(lockfile));
24824
25583
  return { lockfile, text: serializeLockfile(lockfile), problems, warnings };
24825
25584
  }
25585
+ function lockSession(session) {
25586
+ if (session?.duration === void 0 && session?.refresh === void 0) return void 0;
25587
+ return { duration: session.duration, refresh: session.refresh };
25588
+ }
24826
25589
  function personalDataWarnings(root, config2, declared) {
24827
25590
  const directory = join14(root, config2.database?.migrations ?? "db/migrations");
24828
25591
  const files = existsSync11(directory) ? readdirSync4(directory).filter((f) => f.endsWith(".sql")).sort().map((file) => ({ file: (config2.database?.migrations ?? "db/migrations") + "/" + file, sql: readFileSync16(join14(directory, file), "utf8") })) : [];
@@ -24839,8 +25602,8 @@ function personalDataWarnings(root, config2, declared) {
24839
25602
  byTable.set(table, [...byTable.get(table) ?? [], column]);
24840
25603
  }
24841
25604
  for (const [table, columns] of byTable) {
24842
- const where = schema.tables.get(table)?.find((c) => c.name === columns[0]);
24843
- warnings.push(`${where ? `${where.file}:${where.line}: ` : ""}${columns.map((c) => table + "." + c).join(", ")} may hold personal data but ${columns.length === 1 ? "is" : "are"} not declared. If so, add to database.personalData: ${declared.some((t) => t.table === table) ? `the column${columns.length === 1 ? "" : "s"} under ${table}.columns` : personalDataSnippet(table, columns)}`);
25605
+ const where2 = schema.tables.get(table)?.find((c) => c.name === columns[0]);
25606
+ warnings.push(`${where2 ? `${where2.file}:${where2.line}: ` : ""}${columns.map((c) => table + "." + c).join(", ")} may hold personal data but ${columns.length === 1 ? "is" : "are"} not declared. If so, add to database.personalData: ${declared.some((t) => t.table === table) ? `the column${columns.length === 1 ? "" : "s"} under ${table}.columns` : personalDataSnippet(table, columns)}`);
24844
25607
  }
24845
25608
  return warnings;
24846
25609
  }
@@ -24889,10 +25652,10 @@ import { spawn as spawn2 } from "node:child_process";
24889
25652
  import { existsSync as existsSync12, readFileSync as readFileSync17 } from "node:fs";
24890
25653
  import { join as join15 } from "node:path";
24891
25654
  function runScript(root, script) {
24892
- return new Promise((resolve9) => {
25655
+ return new Promise((resolve10) => {
24893
25656
  const child = spawn2(process.platform === "win32" ? "npm.cmd" : "npm", ["run", script], { cwd: root, stdio: "inherit", shell: process.platform === "win32" });
24894
- child.on("close", (code) => resolve9(code ?? 1));
24895
- child.on("error", () => resolve9(1));
25657
+ child.on("close", (code) => resolve10(code ?? 1));
25658
+ child.on("error", () => resolve10(1));
24896
25659
  });
24897
25660
  }
24898
25661
  async function checkCommand(root, options = {}) {
@@ -25169,7 +25932,7 @@ var require_postgres_interval = __commonJS({
25169
25932
  if (!(this instanceof PostgresInterval)) {
25170
25933
  return new PostgresInterval(raw);
25171
25934
  }
25172
- extend2(this, parse3(raw));
25935
+ extend2(this, parse4(raw));
25173
25936
  }
25174
25937
  var properties = ["seconds", "minutes", "hours", "days", "months", "years"];
25175
25938
  PostgresInterval.prototype.toPostgres = function() {
@@ -25230,7 +25993,7 @@ var require_postgres_interval = __commonJS({
25230
25993
  var microseconds = fraction + "000000".slice(fraction.length);
25231
25994
  return parseInt(microseconds, 10) / 1e3;
25232
25995
  }
25233
- function parse3(interval) {
25996
+ function parse4(interval) {
25234
25997
  if (!interval) return {};
25235
25998
  var matches = INTERVAL.exec(interval);
25236
25999
  var isNegative = matches[8] === "-";
@@ -25504,7 +26267,7 @@ var require_pg_int8 = __commonJS({
25504
26267
  var carry;
25505
26268
  var t;
25506
26269
  var digits;
25507
- var pad2;
26270
+ var pad5;
25508
26271
  var l;
25509
26272
  var i;
25510
26273
  {
@@ -25516,12 +26279,12 @@ var require_pg_int8 = __commonJS({
25516
26279
  if (low === 0 && high === 0) {
25517
26280
  return sign + digits + result;
25518
26281
  }
25519
- pad2 = "";
26282
+ pad5 = "";
25520
26283
  l = 6 - digits.length;
25521
26284
  for (i = 0; i < l; i++) {
25522
- pad2 += "0";
26285
+ pad5 += "0";
25523
26286
  }
25524
- result = pad2 + digits + result;
26287
+ result = pad5 + digits + result;
25525
26288
  }
25526
26289
  {
25527
26290
  carry = high % BASE;
@@ -25532,12 +26295,12 @@ var require_pg_int8 = __commonJS({
25532
26295
  if (low === 0 && high === 0) {
25533
26296
  return sign + digits + result;
25534
26297
  }
25535
- pad2 = "";
26298
+ pad5 = "";
25536
26299
  l = 6 - digits.length;
25537
26300
  for (i = 0; i < l; i++) {
25538
- pad2 += "0";
26301
+ pad5 += "0";
25539
26302
  }
25540
- result = pad2 + digits + result;
26303
+ result = pad5 + digits + result;
25541
26304
  }
25542
26305
  {
25543
26306
  carry = high % BASE;
@@ -25548,12 +26311,12 @@ var require_pg_int8 = __commonJS({
25548
26311
  if (low === 0 && high === 0) {
25549
26312
  return sign + digits + result;
25550
26313
  }
25551
- pad2 = "";
26314
+ pad5 = "";
25552
26315
  l = 6 - digits.length;
25553
26316
  for (i = 0; i < l; i++) {
25554
- pad2 += "0";
26317
+ pad5 += "0";
25555
26318
  }
25556
- result = pad2 + digits + result;
26319
+ result = pad5 + digits + result;
25557
26320
  }
25558
26321
  {
25559
26322
  carry = high % BASE;
@@ -25717,13 +26480,13 @@ var require_binaryParsers = __commonJS({
25717
26480
  console.log("ERROR: ElementType not implemented: " + elementType2);
25718
26481
  }
25719
26482
  };
25720
- var parse3 = function(dimension, elementType2) {
26483
+ var parse4 = function(dimension, elementType2) {
25721
26484
  var array2 = [];
25722
26485
  var i2;
25723
26486
  if (dimension.length > 1) {
25724
26487
  var count = dimension.shift();
25725
26488
  for (i2 = 0; i2 < count; i2++) {
25726
- array2[i2] = parse3(dimension, elementType2);
26489
+ array2[i2] = parse4(dimension, elementType2);
25727
26490
  }
25728
26491
  dimension.unshift(count);
25729
26492
  } else {
@@ -25733,7 +26496,7 @@ var require_binaryParsers = __commonJS({
25733
26496
  }
25734
26497
  return array2;
25735
26498
  };
25736
- return parse3(dims, elementType);
26499
+ return parse4(dims, elementType);
25737
26500
  };
25738
26501
  var parseText = function(value) {
25739
26502
  return value.toString("utf8");
@@ -26116,7 +26879,7 @@ var require_utils3 = __commonJS({
26116
26879
  postgresMd5PasswordHash,
26117
26880
  randomBytes: randomBytes6,
26118
26881
  deriveKey,
26119
- sha256: sha2562,
26882
+ sha256: sha2563,
26120
26883
  hashByName,
26121
26884
  hmacSha256,
26122
26885
  md5
@@ -26141,7 +26904,7 @@ var require_utils3 = __commonJS({
26141
26904
  const outer = await md5(Buffer.concat([Buffer.from(inner), salt]));
26142
26905
  return "md5" + outer;
26143
26906
  }
26144
- async function sha2562(text2) {
26907
+ async function sha2563(text2) {
26145
26908
  return await subtleCrypto.digest("SHA-256", text2);
26146
26909
  }
26147
26910
  async function hashByName(hashName, text2) {
@@ -26496,7 +27259,7 @@ var require_type_overrides = __commonJS({
26496
27259
  var require_pg_connection_string = __commonJS({
26497
27260
  "../../node_modules/pg-connection-string/index.js"(exports, module) {
26498
27261
  "use strict";
26499
- function parse3(str, options = {}) {
27262
+ function parse4(str, options = {}) {
26500
27263
  if (str.charAt(0) === "/") {
26501
27264
  const config3 = str.split(" ");
26502
27265
  return { host: config3[0], database: config3[1] };
@@ -26658,7 +27421,7 @@ var require_pg_connection_string = __commonJS({
26658
27421
  return poolConfig;
26659
27422
  }
26660
27423
  function parseIntoClientConfig(str) {
26661
- return toClientConfig(parse3(str));
27424
+ return toClientConfig(parse4(str));
26662
27425
  }
26663
27426
  function deprecatedSslModeWarning(sslmode) {
26664
27427
  if (!deprecatedSslModeWarning.warned && typeof process !== "undefined" && process.emitWarning) {
@@ -26673,10 +27436,10 @@ To prepare for this change:
26673
27436
  See https://www.postgresql.org/docs/current/libpq-ssl.html for libpq SSL mode definitions.`);
26674
27437
  }
26675
27438
  }
26676
- module.exports = parse3;
26677
- parse3.parse = parse3;
26678
- parse3.toClientConfig = toClientConfig;
26679
- parse3.parseIntoClientConfig = parseIntoClientConfig;
27439
+ module.exports = parse4;
27440
+ parse4.parse = parse4;
27441
+ parse4.toClientConfig = toClientConfig;
27442
+ parse4.parseIntoClientConfig = parseIntoClientConfig;
26680
27443
  }
26681
27444
  });
26682
27445
 
@@ -26686,7 +27449,7 @@ var require_connection_parameters = __commonJS({
26686
27449
  "use strict";
26687
27450
  var dns = __require("dns");
26688
27451
  var defaults2 = require_defaults2();
26689
- var parse3 = require_pg_connection_string().parse;
27452
+ var parse4 = require_pg_connection_string().parse;
26690
27453
  var val = function(key, config2, envVar) {
26691
27454
  if (config2[key]) {
26692
27455
  return config2[key];
@@ -26724,9 +27487,9 @@ var require_connection_parameters = __commonJS({
26724
27487
  };
26725
27488
  var ConnectionParameters = class {
26726
27489
  constructor(config2) {
26727
- config2 = typeof config2 === "string" ? parse3(config2) : config2 || {};
27490
+ config2 = typeof config2 === "string" ? parse4(config2) : config2 || {};
26728
27491
  if (config2.connectionString) {
26729
- config2 = Object.assign({}, config2, parse3(config2.connectionString));
27492
+ config2 = Object.assign({}, config2, parse4(config2.connectionString));
26730
27493
  }
26731
27494
  this.user = val("user", config2);
26732
27495
  this.database = val("database", config2);
@@ -27452,7 +28215,7 @@ var require_serializer = __commonJS({
27452
28215
  );
27453
28216
  };
27454
28217
  var emptyArray = [];
27455
- var parse3 = (query2) => {
28218
+ var parse4 = (query2) => {
27456
28219
  const name2 = query2.name || "";
27457
28220
  if (name2.length > 63) {
27458
28221
  console.error("Warning! Postgres only supports 63 characters for query names.");
@@ -27599,7 +28362,7 @@ var require_serializer = __commonJS({
27599
28362
  sendSASLInitialResponseMessage,
27600
28363
  sendSCRAMClientFinalMessage,
27601
28364
  query,
27602
- parse: parse3,
28365
+ parse: parse4,
27603
28366
  bind,
27604
28367
  execute,
27605
28368
  describe: describe2,
@@ -27988,7 +28751,7 @@ var require_dist2 = __commonJS({
27988
28751
  "use strict";
27989
28752
  Object.defineProperty(exports, "__esModule", { value: true });
27990
28753
  exports.DatabaseError = exports.serialize = void 0;
27991
- exports.parse = parse3;
28754
+ exports.parse = parse4;
27992
28755
  var messages_1 = require_messages();
27993
28756
  Object.defineProperty(exports, "DatabaseError", { enumerable: true, get: function() {
27994
28757
  return messages_1.DatabaseError;
@@ -27998,10 +28761,10 @@ var require_dist2 = __commonJS({
27998
28761
  return serializer_1.serialize;
27999
28762
  } });
28000
28763
  var parser_1 = require_parser();
28001
- function parse3(stream, callback) {
28764
+ function parse4(stream, callback) {
28002
28765
  const parser = new parser_1.Parser();
28003
28766
  stream.on("data", (buffer) => parser.parse(buffer, callback));
28004
- return new Promise((resolve9) => stream.on("end", () => resolve9()));
28767
+ return new Promise((resolve10) => stream.on("end", () => resolve10()));
28005
28768
  }
28006
28769
  }
28007
28770
  });
@@ -28086,7 +28849,7 @@ var require_connection = __commonJS({
28086
28849
  "../../node_modules/pg/lib/connection.js"(exports, module) {
28087
28850
  "use strict";
28088
28851
  var EventEmitter = __require("events").EventEmitter;
28089
- var { parse: parse3, serialize } = require_dist2();
28852
+ var { parse: parse4, serialize } = require_dist2();
28090
28853
  var stream = require_stream();
28091
28854
  var { getStream } = stream;
28092
28855
  var flushBuffer = serialize.flush();
@@ -28192,7 +28955,7 @@ var require_connection = __commonJS({
28192
28955
  self.emit("sslconnect");
28193
28956
  }
28194
28957
  attachListeners(stream2) {
28195
- parse3(stream2, (msg) => {
28958
+ parse4(stream2, (msg) => {
28196
28959
  const eventName = msg.name === "error" ? "errorMessage" : msg.name;
28197
28960
  if (this._emitMessage) {
28198
28961
  this.emit("message", msg);
@@ -28461,8 +29224,8 @@ var require_helper = __commonJS({
28461
29224
  module.exports.getPassword = function(connInfo, stream, cb) {
28462
29225
  var pass;
28463
29226
  var lineStream = stream.pipe(split());
28464
- function onLine(line) {
28465
- var entry = parseLine(line);
29227
+ function onLine(line2) {
29228
+ var entry = parseLine(line2);
28466
29229
  if (entry && isValidEntry(entry) && matcher(connInfo, entry)) {
28467
29230
  pass = entry[passKey];
28468
29231
  lineStream.end();
@@ -28480,8 +29243,8 @@ var require_helper = __commonJS({
28480
29243
  stream.on("error", onErr);
28481
29244
  lineStream.on("data", onLine).on("end", onEnd).on("error", onErr);
28482
29245
  };
28483
- var parseLine = module.exports.parseLine = function(line) {
28484
- if (line.length < 11 || line.match(/^\s+#/)) {
29246
+ var parseLine = module.exports.parseLine = function(line2) {
29247
+ if (line2.length < 11 || line2.match(/^\s+#/)) {
28485
29248
  return null;
28486
29249
  }
28487
29250
  var curChar = "";
@@ -28492,15 +29255,15 @@ var require_helper = __commonJS({
28492
29255
  var obj = {};
28493
29256
  var isLastField = false;
28494
29257
  var addToObj = function(idx, i0, i1) {
28495
- var field = line.substring(i0, i1);
29258
+ var field = line2.substring(i0, i1);
28496
29259
  if (!Object.hasOwnProperty.call(process.env, "PGPASS_NO_DEESCAPE")) {
28497
29260
  field = field.replace(/\\([:\\])/g, "$1");
28498
29261
  }
28499
29262
  obj[fieldNames[idx]] = field;
28500
29263
  };
28501
- for (var i = 0; i < line.length - 1; i += 1) {
28502
- curChar = line.charAt(i + 1);
28503
- prevChar = line.charAt(i);
29264
+ for (var i = 0; i < line2.length - 1; i += 1) {
29265
+ curChar = line2.charAt(i + 1);
29266
+ prevChar = line2.charAt(i);
28504
29267
  isLastField = fieldIdx == nrOfFields - 1;
28505
29268
  if (isLastField) {
28506
29269
  addToObj(fieldIdx, startIdx);
@@ -28770,12 +29533,12 @@ var require_client = __commonJS({
28770
29533
  this._connect(callback);
28771
29534
  return;
28772
29535
  }
28773
- return new this._Promise((resolve9, reject) => {
29536
+ return new this._Promise((resolve10, reject) => {
28774
29537
  this._connect((error2) => {
28775
29538
  if (error2) {
28776
29539
  reject(error2);
28777
29540
  } else {
28778
- resolve9(this);
29541
+ resolve10(this);
28779
29542
  }
28780
29543
  });
28781
29544
  });
@@ -29157,8 +29920,8 @@ var require_client = __commonJS({
29157
29920
  } else {
29158
29921
  query = new Query2(config2, values, callback);
29159
29922
  if (!query.callback) {
29160
- result = new this._Promise((resolve9, reject) => {
29161
- query.callback = (err, res) => err ? reject(err) : resolve9(res);
29923
+ result = new this._Promise((resolve10, reject) => {
29924
+ query.callback = (err, res) => err ? reject(err) : resolve10(res);
29162
29925
  }).catch((err) => {
29163
29926
  Error.captureStackTrace(err);
29164
29927
  throw err;
@@ -29258,8 +30021,8 @@ var require_client = __commonJS({
29258
30021
  if (cb) {
29259
30022
  this.connection.once("end", cb);
29260
30023
  } else {
29261
- return new this._Promise((resolve9) => {
29262
- this.connection.once("end", resolve9);
30024
+ return new this._Promise((resolve10) => {
30025
+ this.connection.once("end", resolve10);
29263
30026
  });
29264
30027
  }
29265
30028
  }
@@ -29308,8 +30071,8 @@ var require_pg_pool = __commonJS({
29308
30071
  const cb = function(err, client) {
29309
30072
  err ? rej(err) : res(client);
29310
30073
  };
29311
- const result = new Promise2(function(resolve9, reject) {
29312
- res = resolve9;
30074
+ const result = new Promise2(function(resolve10, reject) {
30075
+ res = resolve10;
29313
30076
  rej = reject;
29314
30077
  }).catch((err) => {
29315
30078
  Error.captureStackTrace(err);
@@ -29370,7 +30133,7 @@ var require_pg_pool = __commonJS({
29370
30133
  if (typeof Promise2.try === "function") {
29371
30134
  return Promise2.try(f);
29372
30135
  }
29373
- return new Promise2((resolve9) => resolve9(f()));
30136
+ return new Promise2((resolve10) => resolve10(f()));
29374
30137
  }
29375
30138
  _isFull() {
29376
30139
  return this._clients.length >= this.options.max;
@@ -29765,8 +30528,8 @@ var require_query2 = __commonJS({
29765
30528
  NativeQuery.prototype._getPromise = function() {
29766
30529
  if (this._promise) return this._promise;
29767
30530
  this._promise = new Promise(
29768
- function(resolve9, reject) {
29769
- this._once("end", resolve9);
30531
+ function(resolve10, reject) {
30532
+ this._once("end", resolve10);
29770
30533
  this._once("error", reject);
29771
30534
  }.bind(this)
29772
30535
  );
@@ -29945,12 +30708,12 @@ var require_client2 = __commonJS({
29945
30708
  this._connect(callback);
29946
30709
  return;
29947
30710
  }
29948
- return new this._Promise((resolve9, reject) => {
30711
+ return new this._Promise((resolve10, reject) => {
29949
30712
  this._connect((error2) => {
29950
30713
  if (error2) {
29951
30714
  reject(error2);
29952
30715
  } else {
29953
- resolve9(this);
30716
+ resolve10(this);
29954
30717
  }
29955
30718
  });
29956
30719
  });
@@ -29974,8 +30737,8 @@ var require_client2 = __commonJS({
29974
30737
  query = new NativeQuery(config2, values, callback);
29975
30738
  if (!query.callback) {
29976
30739
  let resolveOut, rejectOut;
29977
- result = new this._Promise((resolve9, reject) => {
29978
- resolveOut = resolve9;
30740
+ result = new this._Promise((resolve10, reject) => {
30741
+ resolveOut = resolve10;
29979
30742
  rejectOut = reject;
29980
30743
  }).catch((err) => {
29981
30744
  Error.captureStackTrace(err);
@@ -30038,8 +30801,8 @@ var require_client2 = __commonJS({
30038
30801
  }
30039
30802
  let result;
30040
30803
  if (!cb) {
30041
- result = new this._Promise(function(resolve9, reject) {
30042
- cb = (err) => err ? reject(err) : resolve9();
30804
+ result = new this._Promise(function(resolve10, reject) {
30805
+ cb = (err) => err ? reject(err) : resolve10();
30043
30806
  });
30044
30807
  }
30045
30808
  const doEnd = function() {
@@ -30297,12 +31060,12 @@ function findPostgresBin() {
30297
31060
  throw new Error("PostgreSQL 16+ was not found. Install it (https://www.postgresql.org/download/) or set BACKIFY_POSTGRES_BIN to its bin directory.");
30298
31061
  }
30299
31062
  function freePort(preferred = 0) {
30300
- return new Promise((resolve9, reject) => {
31063
+ return new Promise((resolve10, reject) => {
30301
31064
  const server = createServer3();
30302
- server.once("error", (error2) => preferred ? freePort(0).then(resolve9, reject) : reject(error2));
31065
+ server.once("error", (error2) => preferred ? freePort(0).then(resolve10, reject) : reject(error2));
30303
31066
  server.listen(preferred, "127.0.0.1", () => {
30304
31067
  const port = server.address().port;
30305
- server.close(() => resolve9(port));
31068
+ server.close(() => resolve10(port));
30306
31069
  });
30307
31070
  });
30308
31071
  }
@@ -30335,10 +31098,10 @@ async function startLocalDatabase(root, extensions = []) {
30335
31098
  const port = state.port = running ? state.port : await freePort(state.port);
30336
31099
  writeFileSync11(statePath, JSON.stringify(state), { mode: 384 });
30337
31100
  if (!running) {
30338
- await new Promise((resolve9, reject) => {
31101
+ await new Promise((resolve10, reject) => {
30339
31102
  const child = spawn3(join16(bin, exe("pg_ctl")), ["-D", data, "-l", join16(home, "postgres.log"), "-o", `-h 127.0.0.1 -p ${port}`, "-w", "start"], { stdio: "ignore", windowsHide: true, detached: process.platform !== "win32" });
30340
31103
  child.on("error", reject);
30341
- child.on("exit", (code) => code === 0 ? resolve9() : reject(new Error(`PostgreSQL did not start; see ${join16(home, "postgres.log")}`)));
31104
+ child.on("exit", (code) => code === 0 ? resolve10() : reject(new Error(`PostgreSQL did not start; see ${join16(home, "postgres.log")}`)));
30342
31105
  });
30343
31106
  }
30344
31107
  const url2 = (user, password, database) => `postgres://${user}:${encodeURIComponent(password)}@127.0.0.1:${port}/${database}`;
@@ -30780,19 +31543,19 @@ function prefixOutput(child, label, code) {
30780
31543
  buffer += chunk.toString();
30781
31544
  const lines = buffer.split(/\r?\n/);
30782
31545
  buffer = lines.pop() ?? "";
30783
- for (const line of lines) if (line.trim()) say(label, prettyLog(line), code);
31546
+ for (const line2 of lines) if (line2.trim()) say(label, prettyLog(line2), code);
30784
31547
  });
30785
31548
  }
30786
31549
  }
30787
- function prettyLog(line) {
31550
+ function prettyLog(line2) {
30788
31551
  try {
30789
- const entry = JSON.parse(line);
30790
- if (!entry.message) return line;
31552
+ const entry = JSON.parse(line2);
31553
+ if (!entry.message) return line2;
30791
31554
  const { time: _time, level, message, ...fields } = entry;
30792
31555
  const extra = Object.keys(fields).length ? " " + JSON.stringify(fields) : "";
30793
31556
  return `${level === "error" ? color(31, "error") : level === "warn" ? color(33, "warn") : ""}${level === "error" || level === "warn" ? " " : ""}${message}${extra}`;
30794
31557
  } catch {
30795
- return line;
31558
+ return line2;
30796
31559
  }
30797
31560
  }
30798
31561
  function localSecrets(root) {
@@ -30932,6 +31695,632 @@ var init_dev = __esm({
30932
31695
  }
30933
31696
  });
30934
31697
 
31698
+ // src/hosting.ts
31699
+ var hosting_exports = {};
31700
+ __export(hosting_exports, {
31701
+ ROLLBACK_NOTICE: () => ROLLBACK_NOTICE,
31702
+ hostingArguments: () => hostingArguments,
31703
+ hostingHelp: () => hostingHelp,
31704
+ hostingText: () => hostingText2,
31705
+ rollbackArguments: () => rollbackArguments,
31706
+ rollbackHelp: () => rollbackHelp,
31707
+ runHosting: () => runHosting,
31708
+ runRollback: () => runRollback
31709
+ });
31710
+ function hostingArguments(args2) {
31711
+ if (args2.includes("--help") || args2.includes("-h")) return "help";
31712
+ const { flags, positional } = parse(withoutApp(args2), "hosting", ["--json"], []);
31713
+ if (positional.length) throw new Error(hostingHelp);
31714
+ return { json: flags.has("--json") };
31715
+ }
31716
+ function rollbackArguments(args2) {
31717
+ if (args2.includes("--help") || args2.includes("-h")) return "help";
31718
+ const { flags, positional } = parse(withoutApp(args2), "rollback", ["--yes", "--json"], []);
31719
+ if (positional.length !== 1 || !uuid11.test(positional[0])) throw new Error("Name the deployment to roll back to by its ID. " + rollbackHelp);
31720
+ return { deploymentId: positional[0].toLowerCase(), yes: flags.has("--yes"), json: flags.has("--json") };
31721
+ }
31722
+ function hostingText2(hosting) {
31723
+ const environmentName = (id) => id ? hosting.environments?.find((item) => item.id === id)?.name ?? id : "application-wide";
31724
+ const ordered = [...hosting.resources.filter((item) => !kept(item)), ...hosting.resources.filter(kept)];
31725
+ const lines = [
31726
+ "Hosting: " + (hosting.hostingTargetType === "backify-cloud" ? "Backify Cloud" : "Bring your own cloud") + (hosting.target ? ", " + hosting.target.name : "") + (hosting.region ? " (" + hosting.region + ")" : "") + (hosting.isOffline ? ", offline" : ""),
31727
+ ""
31728
+ ];
31729
+ if (!ordered.length) return [...lines, "No application infrastructure has been recorded."].join("\n");
31730
+ const rows = [["RESOURCE", "ENVIRONMENT", "STATUS", "DATA"], ...ordered.map((item) => [item.capability, environmentName(item.environmentId), item.status, kept(item) ? "KEPT since " + item.retainedAt : item.stateful ? "persistent" : "-"])];
31731
+ const retained = ordered.filter(kept), plural = retained.length !== 1;
31732
+ return [...lines, ...pad(rows), ...retained.length ? ["", `${retained.length} ${plural ? "resources are" : "resource is"} kept with ${plural ? "their" : "its"} data and no longer declared. Deleting ${plural ? "them" : "it"} needs a separate authorization; nothing here deletes data.`] : []].join("\n");
31733
+ }
31734
+ async function runHosting(call2, applicationId) {
31735
+ if (!uuid11.test(applicationId)) throw new Error("Use a valid application ID.");
31736
+ const hosting = await call2("/apps/" + applicationId + "/hosting");
31737
+ if (!hosting || !Array.isArray(hosting.resources)) throw new CommandError("Hosting details are unavailable.", "hosting_unavailable");
31738
+ return { value: hosting, text: hostingText2(hosting) };
31739
+ }
31740
+ async function runRollback(call2, applicationId, options, context2 = {}) {
31741
+ if (!uuid11.test(applicationId)) throw new Error("Use a valid application ID.");
31742
+ if (!options.yes) {
31743
+ const message = "Roll back production to deployment " + options.deploymentId + "? This changes the version served to visitors. " + ROLLBACK_NOTICE;
31744
+ if (!context2.confirm) throw new CommandError("Refusing to roll back without confirmation. Review this and re-run with --yes:\n" + message, "confirmation_required", { deploymentId: options.deploymentId, databaseRecovery: "separate", notice: ROLLBACK_NOTICE });
31745
+ if (!await context2.confirm(message)) throw new CommandError("Not confirmed. Nothing was rolled back.", "not_confirmed");
31746
+ }
31747
+ const accepted = await call2("/apps/" + applicationId + "/rollback", { method: "POST", headers: { "Idempotency-Key": "cli-rollback-" + options.deploymentId }, body: JSON.stringify({ deploymentId: options.deploymentId }) });
31748
+ const notice = accepted?.notice?.trim() || ROLLBACK_NOTICE;
31749
+ return { value: { databaseRecovery: "separate", ...accepted, notice }, text: ["Rollback queued" + (accepted?.operationId ? " (operation " + accepted.operationId + ")" : "") + ".", notice].join("\n") };
31750
+ }
31751
+ var uuid11, hostingHelp, rollbackHelp, ROLLBACK_NOTICE, withoutApp, kept;
31752
+ var init_hosting = __esm({
31753
+ "src/hosting.ts"() {
31754
+ "use strict";
31755
+ init_release_flow();
31756
+ uuid11 = /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;
31757
+ hostingHelp = [
31758
+ "Usage: backify hosting [--app <application>] [--json]",
31759
+ "",
31760
+ "Shows the application's hosting: target, environments and infrastructure resources.",
31761
+ "A stateful resource that is no longer declared is marked KEPT: it stays with its data until its deletion is separately authorized.",
31762
+ "Nothing here deletes it. --json prints the hosting overview unchanged, including retainedAt."
31763
+ ].join("\n");
31764
+ rollbackHelp = [
31765
+ "Usage: backify rollback <deployment-id> [--yes] [--app <application>] [--json]",
31766
+ "",
31767
+ "Rolls production back to an earlier deployment (find IDs in the portal's activity list). Asks y/N on a terminal, otherwise needs --yes.",
31768
+ "A rollback restores compatible web revisions and worker configuration only. It never restores or rewinds the database; restore a backup separately.",
31769
+ '--json prints the accepted response: operationId, status, databaseRecovery (always "separate") and notice.'
31770
+ ].join("\n");
31771
+ ROLLBACK_NOTICE = "A rollback restores compatible web revisions and worker configuration only. It never restores or rewinds the database; restore a backup separately.";
31772
+ withoutApp = (args2) => args2.filter((value, index) => value !== "--app" && args2[index - 1] !== "--app");
31773
+ kept = (resource) => Boolean(resource.retainedAt);
31774
+ }
31775
+ });
31776
+
31777
+ // src/handoff.ts
31778
+ var handoff_exports = {};
31779
+ __export(handoff_exports, {
31780
+ handoffArguments: () => handoffArguments,
31781
+ handoffHelp: () => handoffHelp,
31782
+ handoffStatusText: () => handoffStatusText,
31783
+ inventoryText: () => inventoryText,
31784
+ packageFilePath: () => packageFilePath,
31785
+ replacementReason: () => replacementReason,
31786
+ replacementSettings: () => replacementSettings,
31787
+ replacementState: () => replacementState,
31788
+ resolveReplacementEnvironment: () => resolveReplacementEnvironment,
31789
+ runHandoff: () => runHandoff,
31790
+ validSecretName: () => validSecretName
31791
+ });
31792
+ import { createHash as createHash5 } from "node:crypto";
31793
+ import { existsSync as existsSync16, mkdirSync as mkdirSync7, writeFileSync as writeFileSync13 } from "node:fs";
31794
+ import { dirname as dirname8, isAbsolute as isAbsolute2, relative as relative4, resolve as resolve9, sep as sep2 } from "node:path";
31795
+ function extractSettings(args2) {
31796
+ const rest = [], settings = {};
31797
+ for (let index = 0; index < args2.length; index++) {
31798
+ const arg = args2[index];
31799
+ if (secretFlag.test(arg)) throw new Error(secretRefusal);
31800
+ const inline = arg.startsWith("--setting=");
31801
+ if (arg !== "--setting" && !inline) {
31802
+ rest.push(arg);
31803
+ continue;
31804
+ }
31805
+ const pair = inline ? arg.slice("--setting=".length) : args2[++index], at = pair ? pair.indexOf("=") : -1;
31806
+ if (!pair || at < 1) throw new Error("Write each setting as key=value, for example --setting host=smtp.example.com.");
31807
+ const key = pair.slice(0, at);
31808
+ if (key in settings) throw new Error("Duplicate setting: " + key);
31809
+ settings[key] = pair.slice(at + 1);
31810
+ }
31811
+ return { rest, settings };
31812
+ }
31813
+ function replacementsArguments(positional, flags, values, settings, json2, yes) {
31814
+ const sub = (positional[1] ?? "list").toLowerCase();
31815
+ if (!["list", "add", "verify", "remove"].includes(sub)) throw new Error("Unknown replacements command: " + positional.slice(1).join(" ") + "\n\n" + handoffHelp);
31816
+ const takesId = sub === "verify" || sub === "remove";
31817
+ if (positional.length > (takesId ? 3 : 2)) throw new Error("Unknown replacements command: " + positional.slice(1).join(" ") + "\n\n" + handoffHelp);
31818
+ if (takesId && !positional[2]) throw new Error("Name the replacement: backify handoff replacements " + sub + " <id>. List the ids with backify handoff replacements.");
31819
+ if (values["--confirm"] !== void 0 || values["--out"] !== void 0) throw new Error("--confirm and --out do not apply to handoff replacements.");
31820
+ if (sub !== "add" && (addOnlyFlags.some((name2) => values[name2] !== void 0) || Object.keys(settings).length > 0 || flags.has("--consent"))) throw new Error(addOnlyMessage);
31821
+ if (yes && sub !== "remove") throw new Error("--yes applies to handoff replacements remove. Adding a replacement is consented with --consent.");
31822
+ if (sub !== "add") return { action: "replacements", yes, json: json2, replacement: { action: sub, ...takesId ? { id: positional[2] } : {}, settings: {}, consent: false } };
31823
+ const kind2 = values["--kind"]?.toLowerCase(), secretName = values["--secret-name"];
31824
+ if (!values["--environment"]) throw new Error("Name the environment with --environment <name|id|kind>.");
31825
+ if (!kind2 || !replacementKinds.includes(kind2)) throw new Error("Choose what you are replacing with --kind " + replacementKinds.join(", ") + ".");
31826
+ if (!secretName) throw new Error("Name the secret in your environment's vault with --secret-name <vault secret name>. " + secretRefusal);
31827
+ if (!validSecretName(secretName)) throw new Error("--secret-name is the name of a vault secret: letters, digits and hyphens, at most 127, and not starting with backify-rt-. It is not the secret's value.");
31828
+ const subject = values["--subject"] ?? (kind2 === "mail" || kind2 === "ai" ? kind2 : void 0);
31829
+ if (!subject) throw new Error("Name what the replacement is for with --subject: the connection ID for an integration, entra or google for a sign-in provider.");
31830
+ return { action: "replacements", yes, json: json2, replacement: { action: "add", environment: values["--environment"], kind: kind2, subject, settings, secretName, consent: flags.has("--consent") } };
31831
+ }
31832
+ function handoffArguments(args2) {
31833
+ if (args2.includes("--help") || args2.includes("-h")) return "help";
31834
+ const { rest, settings } = extractSettings(args2);
31835
+ const { flags, values, positional } = parse(rest, "handoff", ["--json", "--yes", "--consent"], ["--app", "--confirm", "--out", "--azure-session", ...addOnlyFlags]);
31836
+ const action = (positional[0] ?? "status").toLowerCase(), json2 = flags.has("--json"), yes = flags.has("--yes");
31837
+ const azureSessionId = values["--azure-session"];
31838
+ if (azureSessionId !== void 0 && (action !== "start" || !uuid12.test(azureSessionId))) throw new Error("--azure-session requires a valid Azure session ID and applies to handoff start.");
31839
+ if (action === "replacements") return replacementsArguments(positional, flags, values, settings, json2, yes);
31840
+ if (Object.keys(settings).length || flags.has("--consent") || addOnlyFlags.some((name2) => values[name2] !== void 0)) throw new Error(addOnlyMessage);
31841
+ if (!["status", "check", "request", "start", "abort", "foundation", "package"].includes(action) || positional.length > 1) throw new Error("Unknown handoff command: " + positional.join(" ") + "\n\n" + handoffHelp);
31842
+ if (values["--confirm"] !== void 0 && action !== "request") throw new Error("--confirm applies to handoff request.");
31843
+ if (values["--out"] !== void 0 && action !== "package" && action !== "foundation") throw new Error("--out applies to handoff foundation and handoff package.");
31844
+ if (yes && action !== "start" && action !== "abort") throw new Error(action === "request" ? "Requesting a handoff is confirmed with --confirm <application-slug>, not --yes." : "--yes applies to handoff start and abort.");
31845
+ return { action, ...values["--confirm"] !== void 0 ? { confirm: values["--confirm"] } : {}, ...values["--out"] !== void 0 ? { out: values["--out"] } : {}, ...azureSessionId !== void 0 ? { azureSessionId } : {}, yes, json: json2 };
31846
+ }
31847
+ function pad4(rows) {
31848
+ const widths = rows[0].map((_, column) => Math.max(...rows.map((row) => row[column].length)));
31849
+ return rows.map((row) => row.map((cell, column) => column === row.length - 1 ? cell : cell.padEnd(widths[column])).join(" ").trimEnd());
31850
+ }
31851
+ function inventoryText(inventory) {
31852
+ const count = (classification) => inventory.resources.filter((item) => item.classification === classification).length;
31853
+ const kept2 = inventory.hostnames.filter((item) => item.kept).length;
31854
+ const users = inventory.reauthentication.reduce((total, item) => total + item.count, 0);
31855
+ return [
31856
+ "Resources: " + inventory.resources.length + " (" + count("dedicated") + " dedicated, " + count("shared-separable") + " shared and separable, " + count("shared-platform") + " shared platform)",
31857
+ "Access Backify holds: " + inventory.accessPaths.length,
31858
+ "Backify-hosted dependencies: " + inventory.dependencies.length + (inventory.dependencies.some((item) => !item.customerReplacement) ? " (some have no replacement yet)" : ""),
31859
+ "Hostnames: " + kept2 + " kept, " + (inventory.hostnames.length - kept2) + " not kept",
31860
+ "People who must sign in or register passkeys again: " + users
31861
+ ];
31862
+ }
31863
+ function handoffLines(handoff2) {
31864
+ const lines = ["Phase: " + handoff2.phase, "State: " + handoff2.state + (handoff2.failureCode ? " (" + handoff2.failureCode + ")" : ""), "Approval: " + (handoff2.approvalStatus ?? "-")];
31865
+ if (handoff2.detail) lines.push((handoff2.state === "stopped" ? "Stopped: " : "Detail: ") + handoff2.detail);
31866
+ lines.push("Actions: " + (handoff2.actions?.length ? handoff2.actions.join(", ") : "none"));
31867
+ if (handoff2.hosts?.length) lines.push("", "Hosts:", ...pad4([["HOSTNAME", "TLS", "DNS", "HEALTH", "SERVED BY"], ...handoff2.hosts.map((host) => [host.hostname, host.tls, host.dns, host.health, host.served])]).map((line2) => " " + line2));
31868
+ const open2 = handoff2.humanTasks?.filter((task) => task.state !== "completed") ?? [];
31869
+ if (open2.length) lines.push("", "Only you can do:", ...open2.flatMap((task) => [" " + task.kind + (task.hostname ? " " + task.hostname : "") + " (" + task.state + ")", ...task.instructions ? [" " + task.instructions] : []]));
31870
+ if (handoff2.revocation?.length) {
31871
+ const removed = handoff2.revocation.filter((item) => item.removed).length, verified = handoff2.revocation.filter((item) => item.verified).length;
31872
+ lines.push("", "Access removal: " + removed + " of " + handoff2.revocation.length + " removed, " + verified + " verified", ...pad4([["ACCESS", "REMOVED", "VERIFIED", "EVIDENCE"], ...handoff2.revocation.map((item) => [item.kind + (item.principal ? " " + item.principal : ""), item.removed ? "yes" : "no", item.verified ? "yes" : "no", item.failureCode ? "failed (" + item.failureCode + ")" : item.evidence ?? ""])]).map((line2) => " " + line2));
31873
+ }
31874
+ return lines;
31875
+ }
31876
+ function handoffStatusText(status) {
31877
+ const heading = status.handoffState === "handed-off" ? "This application has been handed off. It is read-only in Backify." : status.handoffState === "in-progress" ? "A handoff is in progress." : "This application has no handoff.";
31878
+ if (!status.handoff) return [heading, "", ...inventoryText(status.inventory), "", "Run backify handoff check to see whether it can be handed off."].join("\n");
31879
+ return [heading, "", ...handoffLines(status.handoff)].join("\n");
31880
+ }
31881
+ function manifestText(manifest) {
31882
+ const files = manifestFiles(manifest);
31883
+ if (!files.length) return "The handoff package lists no files.";
31884
+ return ["Handoff package: " + files.length + " file" + (files.length === 1 ? "" : "s"), "", ...pad4([["FILE", "SIZE", "SHA-256"], ...files.map((file) => [file.path, sizeText(file.bytes), file.sha256 ?? ""])])].join("\n");
31885
+ }
31886
+ function packageFilePath(root, filePath) {
31887
+ if (!filePath || filePath.includes("\0") || isAbsolute2(filePath) || /^[a-z]:/i.test(filePath) || filePath.startsWith("\\")) return void 0;
31888
+ const target = resolve9(root, filePath), inside = relative4(resolve9(root), target);
31889
+ return inside && !isAbsolute2(inside) && !inside.split(sep2).includes("..") ? target : void 0;
31890
+ }
31891
+ async function runFoundation(call2, prefix, out) {
31892
+ const plan = await call2(prefix + "/foundation");
31893
+ if (typeof plan?.template !== "string" || typeof plan.parameters !== "string")
31894
+ throw new CommandError("The API did not return the foundation template and parameters.", "handoff_foundation_invalid");
31895
+ const ownerRuntimeTemplate = plan.ownerRuntimeTemplate;
31896
+ const includeOwnerRuntime = typeof ownerRuntimeTemplate === "string";
31897
+ if (!out) return { value: plan, text: "The foundation plan includes app-foundation.bicep and app.parameters.json" + (includeOwnerRuntime ? ", plus owner-runtime.bicep." : ".") + " Save the files with backify handoff foundation --out <directory>." };
31898
+ const root = resolve9(out);
31899
+ const files = [
31900
+ { path: resolve9(root, "app-foundation.bicep"), content: plan.template },
31901
+ { path: resolve9(root, "app.parameters.json"), content: plan.parameters }
31902
+ ];
31903
+ if (includeOwnerRuntime) files.push({ path: resolve9(root, "owner-runtime.bicep"), content: ownerRuntimeTemplate });
31904
+ const existing = files.find((file) => existsSync16(file.path));
31905
+ if (existing) throw new CommandError("A foundation file already exists. Choose another directory to preserve it.", "handoff_foundation_file_exists", { path: existing.path });
31906
+ mkdirSync7(root, { recursive: true });
31907
+ for (const file of files) writeFileSync13(file.path, file.content, { encoding: "utf8", flag: "wx" });
31908
+ return { value: { out: root, files: files.map((file) => file.path) }, text: "Saved the handoff templates and parameters in " + root + ". Fill in your Entra group in app.parameters.json before deploying." };
31909
+ }
31910
+ async function runPackage(call2, prefix, options) {
31911
+ const manifest = await call2(prefix + "/package");
31912
+ if (!options.out) return { value: manifest, text: manifestText(manifest) };
31913
+ const files = manifestFiles(manifest), root = resolve9(options.out);
31914
+ for (const file of files) if (!packageFilePath(root, file.path)) throw new CommandError("The package lists a file outside the output directory: " + file.path + ". Nothing was written.", "handoff_package_path_invalid", { path: file.path });
31915
+ mkdirSync7(root, { recursive: true });
31916
+ const written = [];
31917
+ for (const file of files) {
31918
+ const text2 = await call2(prefix + "/package/" + file.path.split("/").map(encodeURIComponent).join("/"), { headers: { accept: "text/plain" } });
31919
+ if (typeof text2 !== "string") throw new CommandError("The package file " + file.path + " was not returned as text.", "handoff_package_file_invalid", { path: file.path });
31920
+ if (file.sha256 && sha2562(text2) !== normalizedHash(file.sha256)) throw new CommandError("The package file " + file.path + " does not match its checksum in the manifest. It was not written; " + written.length + " earlier file(s) were.", "handoff_package_checksum_mismatch", { path: file.path, written: written.map((item) => item.path) });
31921
+ const target = packageFilePath(root, file.path);
31922
+ mkdirSync7(dirname8(target), { recursive: true });
31923
+ writeFileSync13(target, text2, "utf8");
31924
+ written.push({ path: file.path, bytes: Buffer.byteLength(text2, "utf8"), verified: Boolean(file.sha256) });
31925
+ }
31926
+ const unverified = written.filter((item) => !item.verified).length;
31927
+ return { value: { status: "written", out: root, files: written, manifest }, text: [manifestText(manifest), "", "Wrote " + written.length + " file" + (written.length === 1 ? "" : "s") + " to " + root + (unverified ? "; " + unverified + " had no checksum in the manifest to verify." : ", each verified against the manifest checksum.")].join("\n") };
31928
+ }
31929
+ function replacementState(replacement) {
31930
+ switch (replacement.verification) {
31931
+ case "verified":
31932
+ return "verified" + (replacement.verifiedAt ? " " + replacement.verifiedAt : "");
31933
+ case "failed":
31934
+ return "could not be verified";
31935
+ case "unverified":
31936
+ return "not verified";
31937
+ default:
31938
+ return "waiting for check";
31939
+ }
31940
+ }
31941
+ function resolveReplacementEnvironment(named, environments) {
31942
+ const wanted = named.trim().toLowerCase(), found = environments?.find((item) => item.id.toLowerCase() === wanted || item.kind.toLowerCase() === wanted);
31943
+ if (found) return found.id;
31944
+ if (!environments?.length && uuid12.test(named)) return named;
31945
+ throw new CommandError("This application has no environment " + named + ". " + (environments?.length ? "Use " + environments.map((item) => item.kind).join(", ") + " or an environment ID." : "Use an environment ID."), "environment_not_found", { environment: named });
31946
+ }
31947
+ function replacementSettings(settings) {
31948
+ const result = {}, deployments = {};
31949
+ for (const [key, value] of Object.entries(settings)) {
31950
+ if (key.startsWith("deployments.")) {
31951
+ const model = key.slice("deployments.".length);
31952
+ if (!model) throw new Error("Write AI deployments as deployments.<model>=<deployment>.");
31953
+ deployments[model] = value;
31954
+ } else if (key === "port") {
31955
+ if (!/^\d{1,5}$/.test(value)) throw new Error("--setting port must be a number such as 587.");
31956
+ result.port = Number(value);
31957
+ } else result[key] = value;
31958
+ }
31959
+ if (Object.keys(deployments).length) result.deployments = deployments;
31960
+ return result;
31961
+ }
31962
+ async function runReplacements(call2, prefix, options, context2) {
31963
+ const replacement = options.replacement, base = prefix + "/replacements";
31964
+ if (replacement.action === "add") {
31965
+ const { kind: kind2, subject, secretName, environment: named } = replacement;
31966
+ if (!replacement.consent) throw new CommandError(consentSummary(kind2, subject, named, secretName) + "\nNothing was changed. Add --consent to record it.", "consent_required", { kind: kind2, subject, secretName });
31967
+ const status = await call2(prefix), environmentId = resolveReplacementEnvironment(named, status.inventory?.environments);
31968
+ const created = await call2(base, { method: "POST", body: JSON.stringify({ environmentId, kind: kind2, subject, settings: replacementSettings(replacement.settings), secretReference: secretName, consent: true }) });
31969
+ return { value: { status: "recorded", replacement: created }, text: ["Replacement recorded for " + subjectText(created) + " in " + named + ".", "Your environment is checking it: " + replacementState(created) + ". Run backify handoff replacements to see the result, or backify handoff replacements verify " + created.id + " to check again."].join("\n") };
31970
+ }
31971
+ if (replacement.action === "verify") {
31972
+ if (!uuid12.test(replacement.id)) throw new Error("Use a valid replacement ID. List them with backify handoff replacements.");
31973
+ const checked2 = await call2(base + "/" + replacement.id + "/verify", { method: "POST" });
31974
+ return { value: { status: "verifying", replacement: checked2 }, text: "Check requested for " + subjectText(checked2) + ": " + replacementState(checked2) + ". It usually takes a minute; run backify handoff replacements to see the result." };
31975
+ }
31976
+ if (replacement.action === "remove") {
31977
+ if (!uuid12.test(replacement.id)) throw new Error("Use a valid replacement ID. List them with backify handoff replacements.");
31978
+ const summary = "Remove this replacement. The dependency counts as hosted by Backify again, and the application cannot be handed off until you record a new one. The secret in your vault is not touched.";
31979
+ if (!options.yes) {
31980
+ if (!context2.confirm) throw new CommandError("Refusing to remove a replacement without confirmation. Review this and re-run with --yes:\n" + summary, "confirmation_required", { id: replacement.id });
31981
+ if (!await context2.confirm(summary)) throw new CommandError("Not confirmed. Nothing was changed.", "not_confirmed");
31982
+ }
31983
+ await call2(base + "/" + replacement.id, { method: "DELETE" });
31984
+ return { value: { status: "removed", id: replacement.id }, text: "Replacement removed. The dependency counts as hosted by Backify again." };
31985
+ }
31986
+ const list = await call2(base);
31987
+ let environments = [];
31988
+ try {
31989
+ environments = (await call2(prefix)).inventory?.environments ?? [];
31990
+ } catch {
31991
+ }
31992
+ if (!list.length) return { value: list, text: "No replacements are recorded. Run backify handoff check to see what Backify hosts for you, then backify handoff replacements add." };
31993
+ const kindOf = (id) => environments.find((item) => item.id === id)?.kind ?? id;
31994
+ const rows = pad4([["ENVIRONMENT", "FOR", "STATE", "SECRET NAME", "ID"], ...list.map((item) => [kindOf(item.environmentId), subjectText(item), replacementState(item), item.secretReference, item.id])]);
31995
+ const problems = list.filter((item) => item.verification === "failed" || item.verification === "unverified").flatMap((item) => [" " + subjectText(item) + " (" + kindOf(item.environmentId) + "): " + replacementReason(item.verificationCode)]);
31996
+ return { value: list, text: [...rows, ...problems.length ? ["", "Not verified:", ...problems] : []].join("\n") };
31997
+ }
31998
+ async function runHandoff(call2, applicationId, options, context2 = {}) {
31999
+ if (!uuid12.test(applicationId)) throw new Error("Use a valid application ID.");
32000
+ const prefix = "/apps/" + applicationId + "/handoff";
32001
+ if (options.action === "foundation") return runFoundation(call2, prefix, options.out);
32002
+ if (options.action === "package") return runPackage(call2, prefix, options);
32003
+ if (options.action === "replacements") return runReplacements(call2, prefix, options, context2);
32004
+ if (options.action === "status") {
32005
+ const status = await call2(prefix);
32006
+ return { value: status, text: handoffStatusText(status) };
32007
+ }
32008
+ if (options.action === "check" || options.action === "request") {
32009
+ const preflight = await call2(prefix + "/preflight");
32010
+ const failed = failedIds(preflight.checks), table = checkRows(preflight.checks);
32011
+ if (!preflight.ready) return { exitCode: 2, value: { status: "blocked", failed, checks: preflight.checks, inventory: preflight.inventory }, text: [table, "", ...inventoryText(preflight.inventory), "", "This application cannot be handed off yet" + (failed.length ? ": " + preflight.checks.filter((check) => check.state === "failed").map((check) => check.name).join(", ") : "") + ". Nothing was changed."].join("\n") };
32012
+ if (options.action === "check") return { value: { status: "ready", checks: preflight.checks, inventory: preflight.inventory }, text: [table, "", ...inventoryText(preflight.inventory), "", "All checks passed. Nothing was changed; run backify handoff request --confirm <application-slug> to request the handoff."].join("\n") };
32013
+ if (!options.confirm) {
32014
+ const slug = (await call2("/apps/" + applicationId)).slug;
32015
+ throw new CommandError("Requesting a handoff gives the application to you and removes the access Backify holds. Another person must approve it, and you can abort it before it is delivered.\nConfirm with the application slug: backify handoff request --confirm " + (slug ?? "<application-slug>"), "confirmation_required", slug ? { confirm: slug } : {});
32016
+ }
32017
+ const result = await call2(prefix, { method: "POST", body: JSON.stringify({ confirmation: options.confirm }) });
32018
+ if (!result.created || !result.handoff) return { exitCode: 2, value: { status: "blocked", failed: failedIds(result.preflight.checks), checks: result.preflight.checks }, text: "The checks no longer pass. Nothing was changed." };
32019
+ return { value: { status: "requested", handoff: result.handoff }, text: ["The handoff awaits approval. Another person approves it on the organization's Approvals page.", "", ...handoffLines(result.handoff)].join("\n") };
32020
+ }
32021
+ const action = options.action;
32022
+ const current = (await call2(prefix)).handoff;
32023
+ if (!current) throw new CommandError("This application has no handoff.", "app_handoff_not_found");
32024
+ if (!current.actions?.includes(action)) throw new CommandError("The handoff does not offer " + action + " now: it is in phase " + current.phase + ", state " + current.state + (current.approvalStatus ? ", approval " + current.approvalStatus : "") + ".", "handoff_action_unavailable", { action, phase: current.phase, state: current.state, actions: current.actions ?? [] });
32025
+ const resume = action === "start" && current.state === "stopped";
32026
+ if (resume && !options.azureSessionId && current.humanTasks?.some((task) => task.kind === "destination-access" && task.state === "pending"))
32027
+ throw new CommandError("Open the application's Handoff page and sign in as the owner Azure administrator to verify access. You can finish there or pass the returned session ID with --azure-session.", "app_handoff_destination_access_unverified");
32028
+ const summary = action === "abort" ? "Abort the handoff. The application stays with Backify and nothing more is changed. Access that was already removed is not restored." : (resume ? "Resume" : "Start") + " the handoff. Backify prepares your Azure, switches the hostnames you keep and then removes the access it holds. After it is delivered, every change to the application in Backify is refused.";
32029
+ if (!options.yes) {
32030
+ if (!context2.confirm) throw new CommandError("Refusing to change a handoff without confirmation. Review this and re-run with --yes:\n" + summary, "confirmation_required", { action });
32031
+ if (!await context2.confirm(summary)) throw new CommandError("Not confirmed. Nothing was changed.", "not_confirmed");
32032
+ }
32033
+ const updated = await call2(prefix + "/" + action, { method: "POST", ...options.azureSessionId ? { body: JSON.stringify({ azureSessionId: options.azureSessionId }) } : {} });
32034
+ return { value: { status: action, handoff: updated }, text: ["The handoff: " + (resume ? "resume" : action) + " accepted.", "", ...handoffLines(updated)].join("\n") };
32035
+ }
32036
+ var handoffHelp, secretFlag, replacementKinds, addOnlyFlags, validSecretName, secretRefusal, addOnlyMessage, uuid12, checkRows, failedIds, sizeText, manifestFiles, sha2562, normalizedHash, reasons, replacementReason, subjectText, consentSummary;
32037
+ var init_handoff = __esm({
32038
+ "src/handoff.ts"() {
32039
+ "use strict";
32040
+ init_release_flow();
32041
+ handoffHelp = [
32042
+ "Usage: backify handoff [status|check|request|start|abort|foundation|package] [options]",
32043
+ "",
32044
+ " backify handoff [status] State, phase, summary, hosts, tasks only you can do and access removal progress",
32045
+ " backify handoff check The checks and what would be handed over; exit 2 when the application cannot be handed off yet",
32046
+ " backify handoff request --confirm <application-slug>",
32047
+ " Run the checks, then request the handoff; another person approves it (exit 2 if a check fails)",
32048
+ " backify handoff start|abort [--yes] Start (or resume) an approved handoff, or abort it before it is delivered",
32049
+ " backify handoff start --azure-session <id> Verify owner Azure access and resume after administrator sign-in in the Portal",
32050
+ " backify handoff foundation [--out <directory>] Get the owner foundation and Runtime templates before handoff",
32051
+ " backify handoff package [--out <directory>] The handoff package manifest; --out writes every file there and verifies its checksum",
32052
+ " backify handoff replacements Your replacements for what Backify hosts (mail, AI, integrations, sign-in) and whether each was verified",
32053
+ " backify handoff replacements add --environment <name|id|kind> --kind <mail|ai|integration|auth-provider> --subject <subject>",
32054
+ " [--setting key=value ...] --secret-name <vault secret name> --consent",
32055
+ " Record a replacement. Store the secret itself in your environment's vault and give only its name here",
32056
+ " backify handoff replacements verify <id> Ask your environment to check a replacement again",
32057
+ " backify handoff replacements remove <id> [--yes] Remove a replacement; the dependency counts as hosted by Backify again",
32058
+ "",
32059
+ "Replacement subjects: mail and ai use their own name; integration uses the connection ID; auth-provider uses entra or google.",
32060
+ "Replacement settings: mail host, port, security (starttls or tls), username, sender, senderName, replyTo; ai endpoint and deployments.<model>=<deployment>;",
32061
+ "integration probeOperation; auth-provider clientId and tenantId (entra only). Secrets are never accepted on the command line.",
32062
+ "Runtime OAuth uses an approved read-only probeOperation and a Runtime vault reference backify-oauth-<environmentId>-<connectionId> with both IDs lowercase and without hyphens.",
32063
+ "",
32064
+ "Options: --app <application> (default: the application in this folder) --json (machine-readable output and errors)",
32065
+ "A handoff gives you the application to run independently in your own Azure and removes the access Backify holds.",
32066
+ "After it is delivered, every change to the application in Backify is refused."
32067
+ ].join("\n");
32068
+ secretFlag = /^--(secret|secret-value|secret-text|value|password|passphrase|token|api-key|apikey|key|client-secret|credential|credentials|connection-string)(=|$)/i;
32069
+ replacementKinds = ["mail", "ai", "integration", "auth-provider"];
32070
+ addOnlyFlags = ["--environment", "--kind", "--subject", "--secret-name"];
32071
+ validSecretName = (name2) => /^[A-Za-z0-9-]{1,127}$/.test(name2) && !name2.toLowerCase().startsWith("backify-rt-");
32072
+ secretRefusal = "A secret value is never accepted on the command line, where it would stay in your shell history. Store the secret in your environment's vault, then pass only its name with --secret-name <vault secret name>.";
32073
+ addOnlyMessage = "--environment, --kind, --subject, --setting, --secret-name and --consent apply to handoff replacements add.";
32074
+ uuid12 = /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;
32075
+ checkRows = (checks) => pad4([["CHECK", "RESULT", "DETAIL"], ...checks.map((check) => [check.name, check.state, check.detail ?? ""])]);
32076
+ failedIds = (checks) => checks.filter((check) => check.state === "failed").map((check) => check.id);
32077
+ sizeText = (bytes) => bytes === void 0 ? "" : bytes < 1024 ? bytes + " B" : bytes < 1024 * 1024 ? (bytes / 1024).toFixed(1) + " KB" : (bytes / 1024 / 1024).toFixed(1) + " MB";
32078
+ manifestFiles = (manifest) => Array.isArray(manifest.files) ? manifest.files.map((file) => ({ ...file, path: file.name ?? file.path ?? "" })) : [];
32079
+ sha2562 = (text2) => createHash5("sha256").update(text2, "utf8").digest("hex");
32080
+ normalizedHash = (value) => value.trim().toLowerCase().replace(/^sha256[:-]/, "");
32081
+ reasons = {
32082
+ replacement_secret_missing: "There is no secret with that name in your environment's vault.",
32083
+ replacement_credential_rejected: "The service did not accept the credential.",
32084
+ replacement_probe_failed: "The check could not reach the service.",
32085
+ replacement_settings_invalid: "Your environment did not accept the settings.",
32086
+ replacement_probe_unavailable: "There is no safe check for this replacement yet. For an integration, record a read-only operation as --setting probeOperation=<operation>."
32087
+ };
32088
+ replacementReason = (code) => (code ? reasons[code] : void 0) ?? "The check did not pass. Check the settings and the secret name, then run backify handoff replacements verify <id>.";
32089
+ subjectText = (replacement) => replacement.kind === "mail" || replacement.kind === "ai" ? replacement.kind : replacement.kind + " " + replacement.subject;
32090
+ consentSummary = (kind2, subject, environment, secretName) => "Recording a replacement means you state that the secret named " + secretName + " in your environment's vault is yours, that the settings you give are yours, and that they replace what Backify hosts for " + subjectText({ kind: kind2, subject }) + " in " + environment + ". Your environment then checks it.";
32091
+ }
32092
+ });
32093
+
32094
+ // src/logs-history.ts
32095
+ var logs_history_exports = {};
32096
+ __export(logs_history_exports, {
32097
+ LOG_STREAMS: () => LOG_STREAMS,
32098
+ MAX_HISTORY_PAGES: () => MAX_HISTORY_PAGES,
32099
+ historyPath: () => historyPath,
32100
+ logsArguments: () => logsArguments,
32101
+ logsHelp: () => logsHelp,
32102
+ parseDuration: () => parseDuration,
32103
+ resolveEnvironment: () => resolveEnvironment2,
32104
+ runLogsHistory: () => runLogsHistory,
32105
+ runLogsRecent: () => runLogsRecent
32106
+ });
32107
+ function parseDuration(value) {
32108
+ const match = /^(\d{1,4})([mhd])$/.exec(value);
32109
+ const amount = match ? Number(match[1]) : 0;
32110
+ if (!match || amount < 1) throw new Error("--since takes a duration such as 30m, 24h or 7d.");
32111
+ return amount * { m: 6e4, h: 36e5, d: 864e5 }[match[2]];
32112
+ }
32113
+ function isoTime(flag, value) {
32114
+ const time3 = /^\d{4}-\d{2}-\d{2}(?:T.*)?$/.test(value) ? new Date(value) : /* @__PURE__ */ new Date(NaN);
32115
+ if (Number.isNaN(time3.getTime())) throw new Error(flag + " takes an ISO time such as 2026-11-14T08:00:00Z.");
32116
+ return time3.toISOString();
32117
+ }
32118
+ function logsArguments(args2) {
32119
+ if (args2.includes("--help") || args2.includes("-h")) return "help";
32120
+ const { flags, values, positional } = parse(args2, "logs", ["--all", "--json"], ["--app", "--environment", "--stream", "--since", "--from", "--to", "--contains", "--limit"]);
32121
+ if (!(positional[0] === "history" || positional[0] === "recent") || positional.length > 1) throw new Error("Unknown logs command. Use backify logs history or backify logs recent.\n\n" + logsHelp);
32122
+ const kind2 = values["--environment"]?.toLowerCase();
32123
+ if (positional[0] === "recent") {
32124
+ if (Object.keys(values).some((flag) => flag !== "--app" && flag !== "--environment") || flags.has("--all")) throw new Error("backify logs recent takes only --environment, --app and --json.");
32125
+ if (kind2 && !(uuid13.test(kind2) || ENVIRONMENT_FLOW.includes(kind2))) throw new Error("--environment takes prototype, preview, production or an environment UUID.");
32126
+ return { action: "recent", ...kind2 ? { environment: kind2 } : {}, json: flags.has("--json") };
32127
+ }
32128
+ if (!kind2 || !(uuid13.test(kind2) || ENVIRONMENT_FLOW.includes(kind2)))
32129
+ throw new Error("--environment takes prototype, preview, production or an environment UUID.");
32130
+ const stream = values["--stream"]?.toLowerCase() ?? "console";
32131
+ if (!LOG_STREAMS.includes(stream)) throw new Error("--stream takes console, system or audit.");
32132
+ if (values["--since"] && (values["--from"] || values["--to"])) throw new Error("Use either --since or --from/--to, not both.");
32133
+ const from = values["--from"] ? isoTime("--from", values["--from"]) : void 0, to = values["--to"] ? isoTime("--to", values["--to"]) : void 0;
32134
+ if (from && to && Date.parse(to) <= Date.parse(from)) throw new Error("--to must be after --from.");
32135
+ const limitText = values["--limit"];
32136
+ if (limitText !== void 0 && (!/^\d{1,4}$/.test(limitText) || Number(limitText) < 1 || Number(limitText) > 1e3)) throw new Error("--limit takes a number from 1 to 1000.");
32137
+ return { environment: kind2, stream, sinceMs: values["--since"] ? parseDuration(values["--since"]) : void 0, from, to, contains: values["--contains"], limit: limitText ? Number(limitText) : DEFAULT_LIMIT, all: flags.has("--all"), json: flags.has("--json") };
32138
+ }
32139
+ async function resolveEnvironment2(call2, prefix, environment) {
32140
+ if (uuid13.test(environment)) return environment;
32141
+ const view = await call2(prefix + "/environments/options");
32142
+ const option2 = view.options.find((item) => item.kind === environment);
32143
+ if (!option2?.activated || !option2.environmentId) throw new CommandError("This application has no " + environment + " environment. Run backify environments to see the activated ones.", "environment_not_activated", { kind: environment });
32144
+ return option2.environmentId;
32145
+ }
32146
+ function historyPath(prefix, environmentId, options, range, continuation) {
32147
+ const query = new URLSearchParams({ environmentId, stream: options.stream });
32148
+ if (range.from) query.set("from", range.from);
32149
+ if (range.to) query.set("to", range.to);
32150
+ if (options.contains) query.set("contains", options.contains);
32151
+ query.set("limit", String(options.limit));
32152
+ if (continuation) query.set("continuation", continuation);
32153
+ return prefix + "/logs/history?" + query.toString().replace(/\+/g, "%20");
32154
+ }
32155
+ async function runLogsRecent(call2, applicationId, options) {
32156
+ if (!uuid13.test(applicationId)) throw new Error("Use a valid application ID.");
32157
+ const prefix = "/apps/" + applicationId;
32158
+ const environmentId = options.environment ? await resolveEnvironment2(call2, prefix, options.environment) : void 0;
32159
+ const lines = await call2(prefix + "/logs" + (environmentId ? "?environmentId=" + encodeURIComponent(environmentId) : ""));
32160
+ return { value: { ...environmentId ? { environmentId } : {}, lines }, text: lines.length ? lines.join("\n") : "No recent log lines." };
32161
+ }
32162
+ async function runLogsHistory(call2, applicationId, options, now = /* @__PURE__ */ new Date()) {
32163
+ if (!uuid13.test(applicationId)) throw new Error("Use a valid application ID.");
32164
+ const prefix = "/apps/" + applicationId;
32165
+ const environmentId = await resolveEnvironment2(call2, prefix, options.environment);
32166
+ const range = options.from || options.to ? { from: options.from, to: options.to } : { from: new Date(now.getTime() - (options.sinceMs ?? DEFAULT_SINCE_MS)).toISOString(), to: now.toISOString() };
32167
+ const lines = [];
32168
+ let dropped = 0, earliest = null, continuation = null, pages = 0;
32169
+ do {
32170
+ const page = await call2(historyPath(prefix, environmentId, options, range, continuation));
32171
+ pages++;
32172
+ lines.push(...page.lines);
32173
+ dropped += page.droppedLines;
32174
+ earliest = page.earliestAvailable ?? earliest;
32175
+ continuation = page.continuation;
32176
+ } while (options.all && continuation && pages < MAX_HISTORY_PAGES);
32177
+ const capped = options.all && continuation !== null;
32178
+ const value = { environmentId, stream: options.stream, lines, droppedLines: dropped, earliestAvailable: earliest, continuation, pages, ...capped ? { capped: true } : {} };
32179
+ const text2 = [
32180
+ ...lines.length ? [...lines].reverse().map((line2) => `${line2.time} ${line2.level.padEnd(5)} ${line2.message}`) : ["No log lines in this range."],
32181
+ ...dropped > 0 ? ["", `${dropped} ${dropped === 1 ? "line was" : "lines were"} dropped because this environment went over its daily log budget.`] : [],
32182
+ ...earliest ? [...dropped > 0 ? [] : [""], `Logs are kept for a limited time. The earliest available entry is ${earliest}.`] : [],
32183
+ ...capped ? ["", `Stopped after ${MAX_HISTORY_PAGES} pages; older lines remain. Narrow the range or add --contains.`] : continuation ? ["", "Older lines are available. Use --all or a larger --limit."] : []
32184
+ ].join("\n");
32185
+ return { value, text: text2 };
32186
+ }
32187
+ var LOG_STREAMS, MAX_HISTORY_PAGES, DEFAULT_LIMIT, DEFAULT_SINCE_MS, uuid13, logsHelp;
32188
+ var init_logs_history = __esm({
32189
+ "src/logs-history.ts"() {
32190
+ "use strict";
32191
+ init_release_flow();
32192
+ LOG_STREAMS = ["console", "system", "audit"];
32193
+ MAX_HISTORY_PAGES = 20;
32194
+ DEFAULT_LIMIT = 200;
32195
+ DEFAULT_SINCE_MS = 36e5;
32196
+ uuid13 = /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;
32197
+ logsHelp = [
32198
+ "Usage: backify logs history --environment <prototype|preview|production|UUID> [options]",
32199
+ " backify logs recent [--environment <prototype|preview|production|UUID>] [--json]",
32200
+ "",
32201
+ " recent The latest runtime log lines from the environment's hosting. --environment is needed once",
32202
+ " the application's environments run on different hosting targets",
32203
+ "",
32204
+ " --stream console|system|audit Which log stream to read (default: console)",
32205
+ " --since <duration> How far back to read: a number and m, h or d, such as 30m, 24h or 7d (default: 1h)",
32206
+ " --from <ISO> --to <ISO> An explicit time range instead of --since (either may be given alone)",
32207
+ " --contains <text> Only lines that contain this text",
32208
+ " --limit <n> Lines per page, 1 to 1000 (default: 200)",
32209
+ " --all Follow older pages, at most " + MAX_HISTORY_PAGES + " pages",
32210
+ " --json Print the merged API result; errors are JSON too",
32211
+ " --app <application> Default: the application in this folder",
32212
+ "",
32213
+ "Reads stored logs from the environment's hosting. Lines print oldest first. Reading history is recorded in the audit log."
32214
+ ].join("\n");
32215
+ }
32216
+ });
32217
+
32218
+ // src/monitoring.ts
32219
+ var monitoring_exports = {};
32220
+ __export(monitoring_exports, {
32221
+ MONITORING_RANGES: () => MONITORING_RANGES,
32222
+ monitoringArguments: () => monitoringArguments,
32223
+ monitoringHelp: () => monitoringHelp,
32224
+ runMonitoring: () => runMonitoring
32225
+ });
32226
+ function monitoringArguments(args2) {
32227
+ if (args2.includes("--help") || args2.includes("-h")) return "help";
32228
+ const { flags, values, positional } = parse(args2, "monitoring", ["--json"], ["--app", "--environment", "--range"]);
32229
+ if (positional.length) throw new Error("Unknown monitoring command: " + positional.join(" ") + "\n\n" + monitoringHelp);
32230
+ const environment = values["--environment"]?.toLowerCase();
32231
+ if (environment && !(uuid14.test(environment) || ENVIRONMENT_FLOW.includes(environment))) throw new Error("--environment takes prototype, preview, production or an environment UUID.");
32232
+ const range = values["--range"]?.toLowerCase() ?? "24h";
32233
+ if (!MONITORING_RANGES.includes(range)) throw new Error("--range takes 1h, 6h, 24h or 7d.");
32234
+ return { ...environment ? { environment } : {}, range, json: flags.has("--json") };
32235
+ }
32236
+ async function runMonitoring(call2, applicationId, options) {
32237
+ if (!uuid14.test(applicationId)) throw new Error("Use a valid application ID.");
32238
+ const prefix = "/apps/" + applicationId;
32239
+ const environmentId = options.environment ? await resolveEnvironment2(call2, prefix, options.environment) : void 0;
32240
+ const query = new URLSearchParams({ range: options.range });
32241
+ if (environmentId) query.set("environmentId", environmentId);
32242
+ const snapshot = await call2(prefix + "/monitoring?" + query.toString());
32243
+ const rows = [["METRIC", "UNIT", "LATEST", "PEAK"], ...snapshot.metrics.map((metric) => [metric.name, metric.unit, reading(metric.points.at(-1)?.value), reading(metric.points.length ? Math.max(...metric.points.map((point) => point.value)) : void 0)])];
32244
+ const text2 = [
32245
+ "Collected " + snapshot.collectedAt + (snapshot.stale ? " (stale: the provider is unavailable, so these are the last readings)" : "") + ". Availability: " + snapshot.availability + ".",
32246
+ ...snapshot.runtime ? ["Observed runtime: " + snapshot.runtime.state + " (" + snapshot.runtime.providerState + ") at " + snapshot.runtime.observedAt + "."] : [],
32247
+ "",
32248
+ ...snapshot.metrics.length ? pad(rows) : ["No metrics were reported for this range."]
32249
+ ].join("\n");
32250
+ return { value: { ...environmentId ? { environmentId } : {}, range: options.range, ...snapshot }, text: text2 };
32251
+ }
32252
+ var MONITORING_RANGES, uuid14, monitoringHelp, reading;
32253
+ var init_monitoring = __esm({
32254
+ "src/monitoring.ts"() {
32255
+ "use strict";
32256
+ init_logs_history();
32257
+ init_release_flow();
32258
+ MONITORING_RANGES = ["1h", "6h", "24h", "7d"];
32259
+ uuid14 = /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;
32260
+ monitoringHelp = [
32261
+ "Usage: backify monitoring [--environment <prototype|preview|production|UUID>] [--range 1h|6h|24h|7d] [--json]",
32262
+ "",
32263
+ "Runtime metrics of one environment, read through the Runtime of the hosting target it runs on: the latest and peak",
32264
+ "reading of each metric over the range (default 24h). Without --environment it reads production; --environment is",
32265
+ "needed once the application's environments run on different hosting targets. Deployment state does not verify uptime.",
32266
+ " --app <application> Default: the application in this folder"
32267
+ ].join("\n");
32268
+ reading = (value) => value === void 0 ? "-" : Number.isInteger(value) ? String(value) : value.toFixed(2);
32269
+ }
32270
+ });
32271
+
32272
+ // src/operation-progress.ts
32273
+ var operation_progress_exports = {};
32274
+ __export(operation_progress_exports, {
32275
+ operationArguments: () => operationArguments,
32276
+ operationHelp: () => operationHelp,
32277
+ runOperation: () => runOperation
32278
+ });
32279
+ function operationArguments(args2) {
32280
+ if (args2.includes("--help") || args2.includes("-h")) return "help";
32281
+ const { flags, positional } = parse(args2, "operation", ["--wait", "--json"], ["--app"]);
32282
+ if (positional.length !== 1 || !uuid15.test(positional[0])) throw new Error("Use backify operation <operation-id> [--wait] [--json].");
32283
+ return { operationId: positional[0].toLowerCase(), wait: flags.has("--wait"), json: flags.has("--json") };
32284
+ }
32285
+ async function runOperation(call2, options, context2 = {}) {
32286
+ const path = "/operations/" + options.operationId;
32287
+ const sleep = context2.sleep ?? ((ms) => new Promise((resolve10) => setTimeout(resolve10, ms)));
32288
+ const seen = /* @__PURE__ */ new Set();
32289
+ let operation = await call2(path), logs = await call2(path + "/logs");
32290
+ for (let poll = 0; options.wait && !finished.has(operation.status) && poll < (context2.maxPolls ?? 1200); poll++) {
32291
+ for (const entry of logs) if (!seen.has(entry.id)) {
32292
+ seen.add(entry.id);
32293
+ context2.progress?.(line(entry));
32294
+ }
32295
+ await sleep(context2.intervalMs ?? 3e3);
32296
+ [operation, logs] = [await call2(path), await call2(path + "/logs")];
32297
+ }
32298
+ const text2 = [
32299
+ "Operation " + operation.id + " (" + operation.kind + "): " + operation.status + (operation.errorMessage ? ". " + operation.errorMessage : operation.errorCode ? " (" + operation.errorCode + ")" : ""),
32300
+ ...logs.some((entry) => !seen.has(entry.id)) ? ["", ...logs.filter((entry) => !seen.has(entry.id)).map(line)] : []
32301
+ ].join("\n");
32302
+ return { value: { operation, logs }, text: text2, ...operation.status === "failed" ? { exitCode: 1 } : options.wait && !finished.has(operation.status) ? { exitCode: 2 } : {} };
32303
+ }
32304
+ var uuid15, finished, operationHelp, line;
32305
+ var init_operation_progress = __esm({
32306
+ "src/operation-progress.ts"() {
32307
+ "use strict";
32308
+ init_release_flow();
32309
+ uuid15 = /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;
32310
+ finished = /* @__PURE__ */ new Set(["succeeded", "failed", "cancelled"]);
32311
+ operationHelp = [
32312
+ "Usage: backify operation <operation-id> [--wait] [--json]",
32313
+ "",
32314
+ "Shows a background operation's state and activity log, such as deleting an application or connecting a repository.",
32315
+ "When an application's environments run on different hosting targets, the log has one line per target as it is",
32316
+ "removed or prepared, and a failure names the target. --wait follows the log until the operation finishes",
32317
+ "(exit 1 when it failed).",
32318
+ " --app <application> Read it with this application's session (default: the application in this folder, or your sign-in)"
32319
+ ].join("\n");
32320
+ line = (entry) => entry.createdAt + " " + entry.level.padEnd(11) + " " + entry.message;
32321
+ }
32322
+ });
32323
+
30935
32324
  // src/index.ts
30936
32325
  init_project_metadata();
30937
32326
 
@@ -31132,22 +32521,22 @@ async function diagnoseEnvironment(root = process.cwd(), options = {}, probes =
31132
32521
 
31133
32522
  // src/integrations.ts
31134
32523
  function integrationDiscoveryPath(command2, options) {
31135
- const uuid9 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
31136
- if (!uuid9.test(options.applicationId)) throw new Error("An application UUID is required");
32524
+ const uuid16 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
32525
+ if (!uuid16.test(options.applicationId)) throw new Error("An application UUID is required");
31137
32526
  const base = "/apps/" + options.applicationId + "/integrations/connectors";
31138
32527
  if (command2 === "list") return base;
31139
32528
  if (command2 === "catalog") return "/apps/" + options.applicationId + "/integrations/catalog";
31140
32529
  if (command2 === "discover") return "/apps/" + options.applicationId + "/integrations/discover?" + new URLSearchParams({ query: options.query ?? "" });
31141
32530
  if (command2 === "prepare") return "/apps/" + options.applicationId + "/integrations/prepare";
31142
32531
  if (command2 === "contract" && options.revisionId) {
31143
- if (!uuid9.test(options.revisionId)) throw new Error("Use --revision with a discovered revision UUID");
32532
+ if (!uuid16.test(options.revisionId)) throw new Error("Use --revision with a discovered revision UUID");
31144
32533
  return "/apps/" + options.applicationId + "/integrations/definitions/" + options.revisionId;
31145
32534
  }
31146
32535
  if (command2 === "status") {
31147
- if (!options.adoptionId || !uuid9.test(options.adoptionId)) throw new Error("Use --adoption with an adoption request UUID");
32536
+ if (!options.adoptionId || !uuid16.test(options.adoptionId)) throw new Error("Use --adoption with an adoption request UUID");
31148
32537
  return "/apps/" + options.applicationId + "/integrations/adoptions/" + options.adoptionId;
31149
32538
  }
31150
- if (!options.connectionId || !uuid9.test(options.connectionId)) throw new Error("Use --connection with an integration connection UUID");
32539
+ if (!options.connectionId || !uuid16.test(options.connectionId)) throw new Error("Use --connection with an integration connection UUID");
31151
32540
  const connection2 = base + "/" + options.connectionId;
31152
32541
  if (command2 === "contract" || command2 === "types") return connection2 + "/" + command2;
31153
32542
  if (command2 === "describe") {
@@ -31168,6 +32557,19 @@ function integrationPreparation(input) {
31168
32557
  if (!["application", "user"].includes(mode) || !operations.length || operations.length > 500 || new Set(operations).size !== operations.length) throw new Error("Use --mode application|user and distinct --operations separated by commas");
31169
32558
  return { definitionId: input.definitionId, revisionId: input.revisionId, environmentId: input.environmentId, mode, operations };
31170
32559
  }
32560
+ var integrationWebhooksUsage = "Use backify integrations webhooks|webhook-deliveries --connection <UUID> --environment <UUID>, webhook-job with --binding <UUID> --job <name>, or webhook-replay with --receipt <UUID> --yes.";
32561
+ function integrationWebhookCall(command2, options) {
32562
+ const uuid16 = /^(?:[a-f0-9]{8}-)(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$/i;
32563
+ if (!options.connectionId || !options.environmentId || ![options.applicationId, options.connectionId, options.environmentId].every((id) => uuid16.test(id))) throw new Error(integrationWebhooksUsage);
32564
+ const path = "/apps/" + options.applicationId + "/integrations/connectors/" + options.connectionId;
32565
+ if (command2 === "webhooks" || command2 === "webhook-deliveries") return { path: path + "/" + command2 + "?" + new URLSearchParams({ environmentId: options.environmentId }) };
32566
+ const headers = { "content-type": "application/json" };
32567
+ if (command2 === "webhook-job" && options.bindingId && uuid16.test(options.bindingId) && /^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/.test(options.job ?? ""))
32568
+ return { path: path + "/webhooks/" + options.bindingId, init: { method: "PUT", headers, body: JSON.stringify({ environmentId: options.environmentId, job: options.job }) } };
32569
+ if (command2 === "webhook-replay" && options.receiptId && uuid16.test(options.receiptId) && options.confirm)
32570
+ return { path: path + "/webhook-deliveries/" + options.receiptId + "/replay", init: { method: "POST", headers, body: JSON.stringify({ environmentId: options.environmentId, confirm: true }) } };
32571
+ throw new Error(integrationWebhooksUsage);
32572
+ }
31171
32573
 
31172
32574
  // src/integration-connect.ts
31173
32575
  import { setTimeout as delay } from "node:timers/promises";
@@ -31300,28 +32702,32 @@ function integrationConnectArguments(args2) {
31300
32702
  }
31301
32703
 
31302
32704
  // src/domain-connect.ts
32705
+ init_release_flow();
31303
32706
  init_human_task();
31304
32707
  import { randomUUID as randomUUID2 } from "node:crypto";
31305
32708
  import { domainToASCII } from "node:url";
31306
- var domainConnectHelp = `backify domains connect [hostname] [--app <application>] [--environment preview|production]
32709
+ var domainConnectHelp = `backify domains connect [hostname] [--app <application>] [--environment <environment>]
31307
32710
  backify domains connect --request <UUID> [--app <application>]
31308
32711
  Options: --hostname <hostname> --no-browser --no-wait --timeout <seconds, 1-3600> --json
32712
+ --environment takes one of the application's activated environments, in release order
32713
+ prototype|preview|production (backify environments lists them); omit it to choose in the browser.
31309
32714
  Requests a Backify task and opens its page, where an authorized user signs in
31310
32715
  and confirms the hostname and environment. Returns as soon as the domain is confirmed. It does not wait for DNS: Backify verifies the DNS records, issues managed HTTPS and starts
31311
32716
  routing automatically once the user adds them. Exit code 0 means confirmed; 2 means not yet confirmed or blocked.
31312
32717
  Re-run with --request <task-id> to read the current status without reopening the browser.`;
31313
32718
  var kind = "domain.confirm";
31314
- var uuid4 = /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;
32719
+ var uuid5 = /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;
31315
32720
  var confirmedStates = ["dns_required", "certificate_pending", "ready"];
31316
32721
  function customHostname(input) {
31317
32722
  const hostname3 = domainToASCII(input.trim().replace(/\.$/, "")).toLowerCase(), labels = hostname3.split(".");
31318
32723
  if (/[\s:/\\@?#%*]/.test(input.trim()) || hostname3.length > 253 || labels.length < 2 || labels.some((label) => !/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(label)) || !/^[a-z][a-z0-9-]*$/.test(labels.at(-1)) || ["backify.dev", "backify.site"].some((suffix) => hostname3 === suffix || hostname3.endsWith("." + suffix))) throw new Error("Use a custom DNS hostname without a URL, path, port or wildcard.");
31319
32724
  return hostname3;
31320
32725
  }
32726
+ var knownEnvironment = (value) => ENVIRONMENT_FLOW.includes(value ?? "");
31321
32727
  function validate(status, app) {
31322
- if (!uuid4.test(status.id) || status.applicationId !== app || !["review_required", "dns_required", "certificate_pending", "ready", "blocked"].includes(status.state) || status.domainId !== null && !uuid4.test(status.domainId)) throw new Error("The server returned invalid domain setup metadata.");
31323
- if (["dns_required", "certificate_pending"].includes(status.state) && (!status.domainId || !status.hostname || !["preview", "production"].includes(status.environment ?? ""))) throw new Error("The server returned invalid domain setup metadata.");
31324
- if (status.state === "ready" && (!status.domainId || !status.hostname || customHostname(status.hostname) !== status.hostname || status.verificationStatus !== "verified" || status.certificateStatus !== "managed" || status.bindingStatus !== "ready" || !["preview", "production"].includes(status.environment ?? "") || status.url !== "https://" + status.hostname)) throw new Error("The server has not established verified DNS, managed HTTPS and routing for this domain.");
32728
+ if (!uuid5.test(status.id) || status.applicationId !== app || !["review_required", "dns_required", "certificate_pending", "ready", "blocked"].includes(status.state) || status.domainId !== null && !uuid5.test(status.domainId)) throw new Error("The server returned invalid domain setup metadata.");
32729
+ if (["dns_required", "certificate_pending"].includes(status.state) && (!status.domainId || !status.hostname || !knownEnvironment(status.environment))) throw new Error("The server returned invalid domain setup metadata.");
32730
+ if (status.state === "ready" && (!status.domainId || !status.hostname || customHostname(status.hostname) !== status.hostname || status.verificationStatus !== "verified" || status.certificateStatus !== "managed" || status.bindingStatus !== "ready" || !knownEnvironment(status.environment) || status.url !== "https://" + status.hostname)) throw new Error("The server has not established verified DNS, managed HTTPS and routing for this domain.");
31325
32731
  }
31326
32732
  function checked(task, app) {
31327
32733
  validateHumanTask(task, kind, app);
@@ -31331,10 +32737,14 @@ function checked(task, app) {
31331
32737
  }
31332
32738
  async function connectDomain(call2, options) {
31333
32739
  const app = options.applicationId.toLowerCase();
31334
- if (!uuid4.test(app) || options.requestId && !uuid4.test(options.requestId)) throw new Error("Use valid application and domain setup request IDs.");
31335
- if (options.environment && !["preview", "production"].includes(options.environment)) throw new Error("Use --environment preview|production, or choose in the browser.");
32740
+ if (!uuid5.test(app) || options.requestId && !uuid5.test(options.requestId)) throw new Error("Use valid application and domain setup request IDs.");
31336
32741
  const hostname3 = options.hostname === void 0 ? void 0 : customHostname(options.hostname);
31337
- const initial = checked(options.requestId ? await readHumanTask(call2, options.requestId) : await requestHumanTask(call2, kind, { applicationId: app, hostname: hostname3 ?? null, environment: options.environment ?? null, requestKey: randomUUID2() }), app);
32742
+ const environment = options.environment?.toLowerCase();
32743
+ if (environment && environment !== "production" && !options.requestId) {
32744
+ const activated = await activatedEnvironments(call2, app) ?? ENVIRONMENT_FLOW;
32745
+ if (!activated.includes(environment)) throw new Error((knownEnvironment(environment) ? `This application has no ${environment} environment. ` : "") + "Use --environment " + activated.join("|") + ", or choose in the browser.");
32746
+ }
32747
+ const initial = checked(options.requestId ? await readHumanTask(call2, options.requestId) : await requestHumanTask(call2, kind, { applicationId: app, hostname: hostname3 ?? null, environment: environment ?? null, requestKey: randomUUID2() }), app);
31338
32748
  const { status: task, link, reason } = await waitForHumanTask(initial, async () => checked(await readHumanTask(call2, initial.id), app), options, "sign in and confirm the custom domain");
31339
32749
  const status = task.result;
31340
32750
  return {
@@ -31389,7 +32799,7 @@ on the Backify auth host. Client IDs and secrets are entered there, never in the
31389
32799
  provider has a setting in every environment. Email and passkeys need no configuration, so a request for only those
31390
32800
  completes at once. Exit code 0 means completed; 2 means setup is still required or blocked. Re-run with --request
31391
32801
  to read the status without reopening the browser.`;
31392
- var uuid5 = /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;
32802
+ var uuid6 = /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;
31393
32803
  function authOrigin(input) {
31394
32804
  const url2 = new URL(input);
31395
32805
  if (url2.protocol !== "https:" && !(url2.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(url2.hostname)) || url2.username || url2.password || url2.search || url2.hash || url2.pathname !== "/") throw new Error("Use a trusted HTTPS auth origin, or an explicit loopback development origin.");
@@ -31398,7 +32808,7 @@ function authOrigin(input) {
31398
32808
  function setupUrl(origin, app, status) {
31399
32809
  if (!status.setupPath || !status.id) throw new Error("The server returned no sign-in setup link.");
31400
32810
  const url2 = new URL(status.setupPath, origin);
31401
- if (url2.origin !== origin || url2.pathname.toLowerCase() !== "/setup/auth/" + app + "/" + status.id.toLowerCase() || [...url2.searchParams.keys()].join() !== "organization" || !uuid5.test(url2.searchParams.get("organization")) || url2.username || url2.password || url2.hash)
32811
+ if (url2.origin !== origin || url2.pathname.toLowerCase() !== "/setup/auth/" + app + "/" + status.id.toLowerCase() || [...url2.searchParams.keys()].join() !== "organization" || !uuid6.test(url2.searchParams.get("organization")) || url2.username || url2.password || url2.hash)
31402
32812
  throw new Error("The server returned an invalid sign-in setup link.");
31403
32813
  return url2.href;
31404
32814
  }
@@ -31411,7 +32821,7 @@ function configuredProviders(values) {
31411
32821
  }
31412
32822
  async function setupAuth(call2, options) {
31413
32823
  const app = options.applicationId.toLowerCase(), timeout = options.timeoutMs ?? 9e5;
31414
- if (!uuid5.test(app) || options.requestId && !uuid5.test(options.requestId)) throw new Error("Use valid application and sign-in setup request IDs.");
32824
+ if (!uuid6.test(app) || options.requestId && !uuid6.test(options.requestId)) throw new Error("Use valid application and sign-in setup request IDs.");
31415
32825
  if (!Number.isFinite(timeout) || timeout < 1e3 || timeout > 36e5) throw new Error("Use --timeout between 1 and 3600 seconds.");
31416
32826
  const origin = authOrigin(options.authUrl), now = options.now ?? Date.now, deadline = now() + timeout;
31417
32827
  const base = "/apps/" + app + "/auth/setup/requests";
@@ -31644,8 +33054,8 @@ async function browserAuthenticate(options) {
31644
33054
  };
31645
33055
  let rejectSession = () => {
31646
33056
  };
31647
- const completed = new Promise((resolve9, reject) => {
31648
- resolveSession = resolve9;
33057
+ const completed = new Promise((resolve10, reject) => {
33058
+ resolveSession = resolve10;
31649
33059
  rejectSession = reject;
31650
33060
  });
31651
33061
  let accepted = false;
@@ -31767,13 +33177,13 @@ function reconnectingApiClient(session, reconnect2, transport = fetch) {
31767
33177
  init_development();
31768
33178
  init_setup();
31769
33179
  init_dist();
31770
- import { readFileSync as readFileSync21, existsSync as existsSync16, rmSync as rmSync5 } from "node:fs";
33180
+ import { readFileSync as readFileSync21, existsSync as existsSync17, rmSync as rmSync5 } from "node:fs";
31771
33181
  import { homedir as homedir2 } from "node:os";
31772
33182
  import { join as join19 } from "node:path";
31773
33183
  import { spawn as spawn5 } from "node:child_process";
31774
33184
  var [command, ...args] = process.argv.slice(2);
31775
33185
  var configPath = join19(homedir2(), ".backify.json");
31776
- var userConfig = command !== "mcp" && existsSync16(configPath) ? JSON.parse(readFileSync21(configPath, "utf8")) : {};
33186
+ var userConfig = command !== "mcp" && existsSync17(configPath) ? JSON.parse(readFileSync21(configPath, "utf8")) : {};
31777
33187
  async function call(path, init) {
31778
33188
  let appId = option("--app");
31779
33189
  if (!appId && hasProjectConfig(process.cwd())) appId = projectApplication();
@@ -31800,10 +33210,18 @@ var help = [
31800
33210
  "Account: signup [--name <organization>] [--plan <plan>] | login | logout | connect | disconnect | status | apps",
31801
33211
  "Coding: tools configure --agent <tool> [--transport http|stdio] [--config <path>] [--dry-run] | mcp [--organization <organization-id>]",
31802
33212
  "Org admin: ops search [<query>] | ops describe <operation-id> | ops get|run <operation-id> [--param <name>=<value>] [--body <file>] [--yes] [--organization <id>] [--json]",
31803
- "Org tasks: task start <kind> [--draft <json>] | task get|wait|open <id> | github connect | azure connect|reconnect|update-agent|uninstall|remove | org | billing | members add|invite|list|invitations|join-links|domains (backify task --help)",
33213
+ "Org tasks: task start <kind> [--draft <json>] | task get|wait|open <id> | github connect | azure connect|reconnect|update-runtime|runtime-upgrade|grant-scope|rescope-grants|uninstall|remove | org | billing | members add|invite|list|invitations|join-links|domains (backify task --help)",
31804
33214
  "Delivery: pull | report [--check] | ship [--production-deploy|--preview-only] [--dry-run] | deploy [<application-id>] [<source-revision>] | request | workflow refresh",
33215
+ " ship deploys to the earliest activated environment (production when it is the only one); --production-deploy then promotes",
33216
+ " through every activated environment to production; --preview-only stops after the first environment",
31805
33217
  " prompt record --stdin --id <UUID>",
31806
- "Platform: database extensions|insights --environment <UUID> [--hours <n>] | privacy requests list|show|create|update|close|preview | events environments|inspect|test | outbound show|default|allow|block|remove|destinations|requests --environment <UUID> | auth setup [--providers <list>] | domains connect [hostname] | integrations connect <provider>|discover|prepare|status|list|catalog|search|describe|contract|types",
33218
+ "Releases: environments [add <preview|prototype> [--yes] | remove <preview|prototype> --confirm <application-slug> | placement [<environment> --target <id|default> [--check] [--yes]] | targets <environment> | move <environment> --target <id> --window-start <ISO> --window-end <ISO> [--check] [--yes] | move status|start|abort|confirm <environment> [--active <id>] [--yes]] | release-flow [--json] | promote [--tested] [--yes]",
33219
+ " Releases move prototype -> preview -> production through the activated environments (backify environments --help)",
33220
+ " hosting [--json] shows targets, environments and resources, marking kept ones | rollback <deployment-id> [--yes] (a rollback never restores the database)",
33221
+ "Logs: logs history --environment <prototype|preview|production|UUID> [--stream console|system|audit] [--since <30m|24h|7d> | --from <ISO> --to <ISO>] [--contains <text>] [--limit <n>] [--all] [--json] | logs recent [--environment <...>] (backify logs --help)",
33222
+ "Monitoring: monitoring [--environment <prototype|preview|production|UUID>] [--range 1h|6h|24h|7d] [--json] | operation <operation-id> [--wait] [--json] (activity log, one line per hosting target)",
33223
+ "Handoff: handoff [status|check] | handoff request --confirm <application-slug> | handoff start|abort [--yes] | handoff package [--out <directory>] | handoff replacements [add|verify|remove] (backify handoff --help)",
33224
+ "Platform: database extensions|insights --environment <UUID> [--hours <n>] | privacy requests list|show|create|update|close|preview | events environments|inspect|test | outbound show|default|allow|block|remove|destinations|requests --environment <UUID> | auth setup [--providers <list>] | auth identity [move|move-back --environment <name|id> --confirm <application-slug> | clear --environment <name|id>] | domains connect [hostname] [--environment <activated environment>] | integrations connect <provider>|discover|prepare|status|list|catalog|search|describe|contract|types",
31807
33225
  "",
31808
33226
  "Docs: https://docs.backify.dev/"
31809
33227
  ].join("\n");
@@ -31945,6 +33363,26 @@ async function main() {
31945
33363
  break;
31946
33364
  }
31947
33365
  case "auth": {
33366
+ if (args[0] === "identity") {
33367
+ const identity = await Promise.resolve().then(() => (init_auth_identity(), auth_identity_exports));
33368
+ const { CommandError: CommandError2 } = await Promise.resolve().then(() => (init_release_flow(), release_flow_exports));
33369
+ const json2 = args.includes("--json");
33370
+ try {
33371
+ const options2 = identity.authIdentityArguments(args.slice(1));
33372
+ if (options2 === "help") {
33373
+ console.log(identity.authIdentityHelp);
33374
+ break;
33375
+ }
33376
+ const result = await identity.runAuthIdentity(call, applicationGuid(option("--app") ?? projectApplication()), options2);
33377
+ console.log(json2 ? JSON.stringify(result.value, null, 2) : result.text);
33378
+ if (result.exitCode !== void 0) process.exitCode = result.exitCode;
33379
+ } catch (error2) {
33380
+ if (!(error2 instanceof CommandError2) || !json2) throw error2;
33381
+ console.log(JSON.stringify({ schemaVersion: 1, status: "failed", exitCode: 1, error: error2.message, code: error2.code, ...error2.details }, null, 2));
33382
+ process.exitCode = 1;
33383
+ }
33384
+ break;
33385
+ }
31948
33386
  if (args[0] !== "setup" || args.includes("--help")) {
31949
33387
  console.log(authSetupHelp);
31950
33388
  if (args[0] !== "setup" && !args.includes("--help")) process.exitCode = 2;
@@ -32026,6 +33464,24 @@ async function main() {
32026
33464
  break;
32027
33465
  }
32028
33466
  case "integrations": {
33467
+ if (["webhooks", "webhook-job", "webhook-deliveries", "webhook-replay"].includes(args[0])) {
33468
+ if (args.includes("--help")) {
33469
+ console.log(integrationWebhooksUsage);
33470
+ break;
33471
+ }
33472
+ const webhook = integrationWebhookCall(args[0], {
33473
+ applicationId: applicationGuid(option("--app") ?? projectApplication()),
33474
+ connectionId: option("--connection"),
33475
+ environmentId: option("--environment"),
33476
+ bindingId: option("--binding"),
33477
+ receiptId: option("--receipt"),
33478
+ job: option("--job"),
33479
+ confirm: args.includes("--yes")
33480
+ });
33481
+ const value2 = await call(webhook.path, webhook.init);
33482
+ console.log(JSON.stringify(value2 ?? { updated: true }, null, 2));
33483
+ break;
33484
+ }
32029
33485
  if (args[0] === "connect") {
32030
33486
  if (args.includes("--help")) {
32031
33487
  console.log(integrationConnectHelp);
@@ -32093,7 +33549,7 @@ Next: ${here ? "" : `cd ${directory} && `}npm install && npm run dev`);
32093
33549
  }
32094
33550
  case "dev": {
32095
33551
  const port = portOption("--port");
32096
- if (!existsSync16(join19(process.cwd(), "backify.config.ts"))) throw new Error("backify dev runs apps with a backify.config.ts. Create one with backify new <name>.");
33552
+ if (!existsSync17(join19(process.cwd(), "backify.config.ts"))) throw new Error("backify dev runs apps with a backify.config.ts. Create one with backify new <name>.");
32097
33553
  const { devCommand: devCommand2 } = await Promise.resolve().then(() => (init_dev(), dev_exports));
32098
33554
  process.exitCode = await devCommand2(process.cwd(), { port });
32099
33555
  break;
@@ -32167,7 +33623,7 @@ Next: ${here ? "" : `cd ${directory} && `}npm install && npm run dev`);
32167
33623
  userConfig.sessions[key] ??= session;
32168
33624
  saveUserConfig(configPath, userConfig);
32169
33625
  if (args.includes("--clone")) await cloneProject(client, appId);
32170
- else if (existsSync16(join19(process.cwd(), ".git"))) {
33626
+ else if (existsSync17(join19(process.cwd(), ".git"))) {
32171
33627
  const update = await pullProject(client, appId);
32172
33628
  console.log(JSON.stringify(update, null, 2));
32173
33629
  if (update.status === "blocked") throw new Error(update.reason);
@@ -32225,6 +33681,125 @@ Next: ${here ? "" : `cd ${directory} && `}npm install && npm run dev`);
32225
33681
  console.log(JSON.stringify(await ship(call, projectApplication(), { productionDeploy: args.includes("--production-deploy"), previewOnly: args.includes("--preview-only"), timeoutMs: timeout * 1e3, dryRun: args.includes("--dry-run") }), null, 2));
32226
33682
  break;
32227
33683
  }
33684
+ case "environments":
33685
+ case "release-flow":
33686
+ case "promote": {
33687
+ const flow = await Promise.resolve().then(() => (init_release_flow(), release_flow_exports));
33688
+ const { terminalConfirm: terminalConfirm2 } = await Promise.resolve().then(() => (init_ops(), ops_exports));
33689
+ const json2 = args.includes("--json");
33690
+ try {
33691
+ const options = command === "environments" ? flow.environmentsArguments(args) : command === "promote" ? flow.promoteArguments(args) : args.includes("--help") || args.includes("-h") ? "help" : void 0;
33692
+ if (options === "help") {
33693
+ console.log(command === "environments" ? flow.environmentsHelp : command === "promote" ? flow.promoteHelp : flow.releaseFlowHelp);
33694
+ break;
33695
+ }
33696
+ if (command === "release-flow" && args.some((value, index) => value !== "--json" && value !== "--app" && args[index - 1] !== "--app")) throw new Error(flow.releaseFlowHelp);
33697
+ const application = applicationGuid(option("--app") ?? projectApplication()), context2 = { confirm: terminalConfirm2() };
33698
+ const result = command === "environments" ? await flow.runEnvironments(call, application, options, context2) : command === "promote" ? await flow.promote(call, application, options, context2) : await flow.releaseFlow(call, application);
33699
+ console.log(json2 ? JSON.stringify(result.value, null, 2) : result.text);
33700
+ if (result.exitCode !== void 0) process.exitCode = result.exitCode;
33701
+ } catch (error2) {
33702
+ if (!(error2 instanceof flow.CommandError) || !json2) throw error2;
33703
+ console.log(JSON.stringify({ schemaVersion: 1, status: "failed", exitCode: 1, error: error2.message, code: error2.code, ...error2.details }, null, 2));
33704
+ process.exitCode = 1;
33705
+ }
33706
+ break;
33707
+ }
33708
+ case "hosting":
33709
+ case "rollback": {
33710
+ const hostingModule = await Promise.resolve().then(() => (init_hosting(), hosting_exports));
33711
+ const { CommandError: CommandError2 } = await Promise.resolve().then(() => (init_release_flow(), release_flow_exports));
33712
+ const { terminalConfirm: terminalConfirm2 } = await Promise.resolve().then(() => (init_ops(), ops_exports));
33713
+ const json2 = args.includes("--json");
33714
+ try {
33715
+ const options = command === "hosting" ? hostingModule.hostingArguments(args) : hostingModule.rollbackArguments(args);
33716
+ if (options === "help") {
33717
+ console.log(command === "hosting" ? hostingModule.hostingHelp : hostingModule.rollbackHelp);
33718
+ break;
33719
+ }
33720
+ const application = applicationGuid(option("--app") ?? projectApplication());
33721
+ const result = command === "hosting" ? await hostingModule.runHosting(call, application) : await hostingModule.runRollback(call, application, options, { confirm: terminalConfirm2() });
33722
+ console.log(json2 ? JSON.stringify(result.value, null, 2) : result.text);
33723
+ } catch (error2) {
33724
+ if (!(error2 instanceof CommandError2) || !json2) throw error2;
33725
+ console.log(JSON.stringify({ schemaVersion: 1, status: "failed", exitCode: 1, error: error2.message, code: error2.code, ...error2.details }, null, 2));
33726
+ process.exitCode = 1;
33727
+ }
33728
+ break;
33729
+ }
33730
+ case "handoff": {
33731
+ const handoff2 = await Promise.resolve().then(() => (init_handoff(), handoff_exports));
33732
+ const { CommandError: CommandError2 } = await Promise.resolve().then(() => (init_release_flow(), release_flow_exports));
33733
+ const { terminalConfirm: terminalConfirm2 } = await Promise.resolve().then(() => (init_ops(), ops_exports));
33734
+ const json2 = args.includes("--json");
33735
+ try {
33736
+ const options = handoff2.handoffArguments(args);
33737
+ if (options === "help") {
33738
+ console.log(handoff2.handoffHelp);
33739
+ break;
33740
+ }
33741
+ const result = await handoff2.runHandoff(call, applicationGuid(option("--app") ?? projectApplication()), options, { confirm: terminalConfirm2() });
33742
+ console.log(json2 ? JSON.stringify(result.value, null, 2) : result.text);
33743
+ if (result.exitCode !== void 0) process.exitCode = result.exitCode;
33744
+ } catch (error2) {
33745
+ if (!(error2 instanceof CommandError2) || !json2) throw error2;
33746
+ console.log(JSON.stringify({ schemaVersion: 1, status: "failed", exitCode: 1, error: error2.message, code: error2.code, ...error2.details }, null, 2));
33747
+ process.exitCode = 1;
33748
+ }
33749
+ break;
33750
+ }
33751
+ case "logs": {
33752
+ const history = await Promise.resolve().then(() => (init_logs_history(), logs_history_exports));
33753
+ const json2 = args.includes("--json");
33754
+ try {
33755
+ const options = history.logsArguments(args);
33756
+ if (options === "help") {
33757
+ console.log(history.logsHelp);
33758
+ break;
33759
+ }
33760
+ const application = applicationGuid(option("--app") ?? projectApplication());
33761
+ const result = options.action === "recent" ? await history.runLogsRecent(call, application, options) : await history.runLogsHistory(call, application, options);
33762
+ console.log(json2 ? JSON.stringify(result.value, null, 2) : result.text);
33763
+ } catch (error2) {
33764
+ const flow = await Promise.resolve().then(() => (init_release_flow(), release_flow_exports));
33765
+ if (!(error2 instanceof flow.CommandError) || !json2) throw error2;
33766
+ console.log(JSON.stringify({ schemaVersion: 1, status: "failed", exitCode: 1, error: error2.message, code: error2.code, ...error2.details }, null, 2));
33767
+ process.exitCode = 1;
33768
+ }
33769
+ break;
33770
+ }
33771
+ case "monitoring":
33772
+ case "operation": {
33773
+ const flow = await Promise.resolve().then(() => (init_release_flow(), release_flow_exports));
33774
+ const json2 = args.includes("--json");
33775
+ try {
33776
+ let result;
33777
+ if (command === "monitoring") {
33778
+ const monitoring = await Promise.resolve().then(() => (init_monitoring(), monitoring_exports));
33779
+ const options = monitoring.monitoringArguments(args);
33780
+ if (options === "help") {
33781
+ console.log(monitoring.monitoringHelp);
33782
+ break;
33783
+ }
33784
+ result = await monitoring.runMonitoring(call, applicationGuid(option("--app") ?? projectApplication()), options);
33785
+ } else {
33786
+ const progress = await Promise.resolve().then(() => (init_operation_progress(), operation_progress_exports));
33787
+ const options = progress.operationArguments(args);
33788
+ if (options === "help") {
33789
+ console.log(progress.operationHelp);
33790
+ break;
33791
+ }
33792
+ result = await progress.runOperation(call, options, { progress: json2 ? void 0 : (text2) => console.log(text2) });
33793
+ }
33794
+ console.log(json2 ? JSON.stringify(result.value, null, 2) : result.text);
33795
+ if (result.exitCode !== void 0) process.exitCode = result.exitCode;
33796
+ } catch (error2) {
33797
+ if (!(error2 instanceof flow.CommandError) || !json2) throw error2;
33798
+ console.log(JSON.stringify({ schemaVersion: 1, status: "failed", exitCode: 1, error: error2.message, code: error2.code, ...error2.details }, null, 2));
33799
+ process.exitCode = 1;
33800
+ }
33801
+ break;
33802
+ }
32228
33803
  case "request": {
32229
33804
  const workspaceId = option("--workspace"), name2 = option("--name"), slug = option("--slug"), description = option("--description"), configurationFile = option("--configuration");
32230
33805
  if (!workspaceId || !name2 || !slug || !description) throw new Error("Use backify request --workspace <id> --name <name> --slug <slug> --description <purpose> [--configuration <json-file>]");