@backifydev/cli 0.3.9 → 0.3.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +15 -5
  2. package/dist/index.js +887 -547
  3. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1275,9 +1275,9 @@ ${indent}`) + "'";
1275
1275
  return quotedString(value, ctx);
1276
1276
  }
1277
1277
  const indent = ctx.indent || (ctx.forceBlockIndent || containsDocumentMarker(value) ? " " : "");
1278
- const literal = blockQuote === "literal" ? true : blockQuote === "folded" || type === Scalar.Scalar.BLOCK_FOLDED ? false : type === Scalar.Scalar.BLOCK_LITERAL ? true : !lineLengthOverLimit(value, lineWidth, indent.length);
1278
+ const literal2 = blockQuote === "literal" ? true : blockQuote === "folded" || type === Scalar.Scalar.BLOCK_FOLDED ? false : type === Scalar.Scalar.BLOCK_LITERAL ? true : !lineLengthOverLimit(value, lineWidth, indent.length);
1279
1279
  if (!value)
1280
- return literal ? "|\n" : ">\n";
1280
+ return literal2 ? "|\n" : ">\n";
1281
1281
  let chomp;
1282
1282
  let endStart;
1283
1283
  for (endStart = value.length; endStart > 0; --endStart) {
@@ -1326,7 +1326,7 @@ ${indent}`) + "'";
1326
1326
  if (onComment)
1327
1327
  onComment();
1328
1328
  }
1329
- if (!literal) {
1329
+ if (!literal2) {
1330
1330
  const foldedValue = value.replace(/\n+/g, "\n$&").replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g, "$1$2").replace(/\n+/g, `$&${indent}`);
1331
1331
  let literalFallback = false;
1332
1332
  const foldOptions = getFoldOptions(ctx, true);
@@ -4598,9 +4598,9 @@ var require_resolve_block_scalar = __commonJS({
4598
4598
  default: {
4599
4599
  const message = `Unexpected token in block scalar header: ${token.type}`;
4600
4600
  onError(token, "UNEXPECTED_TOKEN", message);
4601
- const ts3 = token.source;
4602
- if (ts3 && typeof ts3 === "string")
4603
- length += ts3.length;
4601
+ const ts4 = token.source;
4602
+ if (ts4 && typeof ts4 === "string")
4603
+ length += ts4.length;
4604
4604
  }
4605
4605
  }
4606
4606
  }
@@ -4910,9 +4910,9 @@ var require_compose_scalar = __commonJS({
4910
4910
  if (schema.compat) {
4911
4911
  const compat = schema.compat.find((tag2) => tag2.default && tag2.test?.test(value)) ?? schema[identity.SCALAR];
4912
4912
  if (tag.tag !== compat.tag) {
4913
- const ts3 = directives.tagString(tag.tag);
4913
+ const ts4 = directives.tagString(tag.tag);
4914
4914
  const cs = directives.tagString(compat.tag);
4915
- const msg = `Value may be parsed as either ${ts3} or ${cs}`;
4915
+ const msg = `Value may be parsed as either ${ts4} or ${cs}`;
4916
4916
  onError(token, "TAG_RESOLVE_FAILED", msg, true);
4917
4917
  }
4918
4918
  }
@@ -7812,7 +7812,7 @@ var require_luxon = __commonJS({
7812
7812
  * @param {string} opts.locale - What locale to return the offset name in.
7813
7813
  * @return {string}
7814
7814
  */
7815
- offsetName(ts3, opts) {
7815
+ offsetName(ts4, opts) {
7816
7816
  throw new ZoneIsAbstractError();
7817
7817
  }
7818
7818
  /**
@@ -7823,7 +7823,7 @@ var require_luxon = __commonJS({
7823
7823
  * Accepts 'narrow', 'short', or 'techie'. Returning '+6', '+06:00', or '+0600' respectively
7824
7824
  * @return {string}
7825
7825
  */
7826
- formatOffset(ts3, format) {
7826
+ formatOffset(ts4, format) {
7827
7827
  throw new ZoneIsAbstractError();
7828
7828
  }
7829
7829
  /**
@@ -7832,7 +7832,7 @@ var require_luxon = __commonJS({
7832
7832
  * @param {number} ts - Epoch milliseconds for which to compute the offset
7833
7833
  * @return {number}
7834
7834
  */
7835
- offset(ts3) {
7835
+ offset(ts4) {
7836
7836
  throw new ZoneIsAbstractError();
7837
7837
  }
7838
7838
  /**
@@ -7878,19 +7878,19 @@ var require_luxon = __commonJS({
7878
7878
  return false;
7879
7879
  }
7880
7880
  /** @override **/
7881
- offsetName(ts3, {
7881
+ offsetName(ts4, {
7882
7882
  format,
7883
7883
  locale
7884
7884
  }) {
7885
- return parseZoneInfo(ts3, format, locale);
7885
+ return parseZoneInfo(ts4, format, locale);
7886
7886
  }
7887
7887
  /** @override **/
7888
- formatOffset(ts3, format) {
7889
- return formatOffset(this.offset(ts3), format);
7888
+ formatOffset(ts4, format) {
7889
+ return formatOffset(this.offset(ts4), format);
7890
7890
  }
7891
7891
  /** @override **/
7892
- offset(ts3) {
7893
- return -new Date(ts3).getTimezoneOffset();
7892
+ offset(ts4) {
7893
+ return -new Date(ts4).getTimezoneOffset();
7894
7894
  }
7895
7895
  /** @override **/
7896
7896
  equals(otherZone) {
@@ -8042,11 +8042,11 @@ var require_luxon = __commonJS({
8042
8042
  * @param {string} opts.locale - What locale to return the offset name in.
8043
8043
  * @return {string}
8044
8044
  */
8045
- offsetName(ts3, {
8045
+ offsetName(ts4, {
8046
8046
  format,
8047
8047
  locale
8048
8048
  }) {
8049
- return parseZoneInfo(ts3, format, locale, this.name);
8049
+ return parseZoneInfo(ts4, format, locale, this.name);
8050
8050
  }
8051
8051
  /**
8052
8052
  * Returns the offset's value as a string
@@ -8056,8 +8056,8 @@ var require_luxon = __commonJS({
8056
8056
  * Accepts 'narrow', 'short', or 'techie'. Returning '+6', '+06:00', or '+0600' respectively
8057
8057
  * @return {string}
8058
8058
  */
8059
- formatOffset(ts3, format) {
8060
- return formatOffset(this.offset(ts3), format);
8059
+ formatOffset(ts4, format) {
8060
+ return formatOffset(this.offset(ts4), format);
8061
8061
  }
8062
8062
  /**
8063
8063
  * Return the offset in minutes for this zone at the specified timestamp.
@@ -8065,9 +8065,9 @@ var require_luxon = __commonJS({
8065
8065
  * @param {number} ts - Epoch milliseconds for which to compute the offset
8066
8066
  * @return {number}
8067
8067
  */
8068
- offset(ts3) {
8068
+ offset(ts4) {
8069
8069
  if (!this.valid) return NaN;
8070
- const date = new Date(ts3);
8070
+ const date = new Date(ts4);
8071
8071
  if (isNaN(date)) return NaN;
8072
8072
  const dtf = makeDTF(this.name);
8073
8073
  let [year, month, day, adOrBc, hour, minute, second] = dtf.formatToParts ? partsOffset(dtf, date) : hackyOffset(dtf, date);
@@ -8654,7 +8654,7 @@ var require_luxon = __commonJS({
8654
8654
  * Accepts 'narrow', 'short', or 'techie'. Returning '+6', '+06:00', or '+0600' respectively
8655
8655
  * @return {string}
8656
8656
  */
8657
- formatOffset(ts3, format) {
8657
+ formatOffset(ts4, format) {
8658
8658
  return formatOffset(this.fixed, format);
8659
8659
  }
8660
8660
  /**
@@ -9340,8 +9340,8 @@ var require_luxon = __commonJS({
9340
9340
  return year;
9341
9341
  } else return year > Settings.twoDigitCutoffYear ? 1900 + year : 2e3 + year;
9342
9342
  }
9343
- function parseZoneInfo(ts3, offsetFormat, locale, timeZone = null) {
9344
- const date = new Date(ts3), intlOpts = {
9343
+ function parseZoneInfo(ts4, offsetFormat, locale, timeZone = null) {
9344
+ const date = new Date(ts4), intlOpts = {
9345
9345
  hourCycle: "h23",
9346
9346
  year: "numeric",
9347
9347
  month: "2-digit",
@@ -9867,9 +9867,9 @@ var require_luxon = __commonJS({
9867
9867
  return token;
9868
9868
  }
9869
9869
  }, tokens = _Formatter.parseFormat(fmt), realTokens = tokens.reduce((found, {
9870
- literal,
9870
+ literal: literal2,
9871
9871
  val
9872
- }) => literal ? found : found.concat(val), []), collapsed = dur.shiftTo(...realTokens.map(tokenToField).filter((t) => t)), durationInfo = {
9872
+ }) => literal2 ? found : found.concat(val), []), collapsed = dur.shiftTo(...realTokens.map(tokenToField).filter((t) => t)), durationInfo = {
9873
9873
  isNegativeDuration: collapsed < 0,
9874
9874
  // this relies on "collapsed" being based on "shiftTo", which builds up the object
9875
9875
  // in order
@@ -11779,13 +11779,13 @@ var require_luxon = __commonJS({
11779
11779
  return value.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&");
11780
11780
  }
11781
11781
  function unitForToken(token, loc) {
11782
- const one = digitRegex(loc), two = digitRegex(loc, "{2}"), three = digitRegex(loc, "{3}"), four = digitRegex(loc, "{4}"), six = digitRegex(loc, "{6}"), oneOrTwo = digitRegex(loc, "{1,2}"), oneToThree = digitRegex(loc, "{1,3}"), oneToSix = digitRegex(loc, "{1,6}"), oneToNine = digitRegex(loc, "{1,9}"), twoToFour = digitRegex(loc, "{2,4}"), fourToSix = digitRegex(loc, "{4,6}"), literal = (t) => ({
11782
+ const one = digitRegex(loc), two = digitRegex(loc, "{2}"), three = digitRegex(loc, "{3}"), four = digitRegex(loc, "{4}"), six = digitRegex(loc, "{6}"), oneOrTwo = digitRegex(loc, "{1,2}"), oneToThree = digitRegex(loc, "{1,3}"), oneToSix = digitRegex(loc, "{1,6}"), oneToNine = digitRegex(loc, "{1,9}"), twoToFour = digitRegex(loc, "{2,4}"), fourToSix = digitRegex(loc, "{4,6}"), literal2 = (t) => ({
11783
11783
  regex: RegExp(escapeToken(t.val)),
11784
11784
  deser: ([s2]) => s2,
11785
11785
  literal: true
11786
11786
  }), unitate = (t) => {
11787
11787
  if (token.literal) {
11788
- return literal(t);
11788
+ return literal2(t);
11789
11789
  }
11790
11790
  switch (t.val) {
11791
11791
  // era
@@ -11902,7 +11902,7 @@ var require_luxon = __commonJS({
11902
11902
  case " ":
11903
11903
  return simple(/[^\S\n\r]/);
11904
11904
  default:
11905
- return literal(t);
11905
+ return literal2(t);
11906
11906
  }
11907
11907
  };
11908
11908
  const unit = unitate(token) || {
@@ -12218,9 +12218,9 @@ var require_luxon = __commonJS({
12218
12218
  }
12219
12219
  return [localTS - Math.min(o2, o3) * 60 * 1e3, Math.max(o2, o3)];
12220
12220
  }
12221
- function tsToObj(ts3, offset2) {
12222
- ts3 += offset2 * 60 * 1e3;
12223
- const d = new Date(ts3);
12221
+ function tsToObj(ts4, offset2) {
12222
+ ts4 += offset2 * 60 * 1e3;
12223
+ const d = new Date(ts4);
12224
12224
  return {
12225
12225
  year: d.getUTCFullYear(),
12226
12226
  month: d.getUTCMonth() + 1,
@@ -12251,13 +12251,13 @@ var require_luxon = __commonJS({
12251
12251
  seconds: dur.seconds,
12252
12252
  milliseconds: dur.milliseconds
12253
12253
  }).as("milliseconds"), localTS = objToLocalTS(c);
12254
- let [ts3, o] = fixOffset(localTS, oPre, inst.zone);
12254
+ let [ts4, o] = fixOffset(localTS, oPre, inst.zone);
12255
12255
  if (millisToAdd !== 0) {
12256
- ts3 += millisToAdd;
12257
- o = inst.zone.offset(ts3);
12256
+ ts4 += millisToAdd;
12257
+ o = inst.zone.offset(ts4);
12258
12258
  }
12259
12259
  return {
12260
- ts: ts3,
12260
+ ts: ts4,
12261
12261
  o
12262
12262
  };
12263
12263
  }
@@ -12444,7 +12444,7 @@ var require_luxon = __commonJS({
12444
12444
  return DateTime.invalid(unsupportedZone(zone));
12445
12445
  }
12446
12446
  const loc = Locale.fromObject(opts);
12447
- let ts3, o;
12447
+ let ts4, o;
12448
12448
  if (!isUndefined(obj.year)) {
12449
12449
  for (const u of orderedUnits) {
12450
12450
  if (isUndefined(obj[u])) {
@@ -12456,12 +12456,12 @@ var require_luxon = __commonJS({
12456
12456
  return DateTime.invalid(invalid2);
12457
12457
  }
12458
12458
  const offsetProvis = guessOffsetForZone(zone);
12459
- [ts3, o] = objToTS(obj, offsetProvis, zone);
12459
+ [ts4, o] = objToTS(obj, offsetProvis, zone);
12460
12460
  } else {
12461
- ts3 = Settings.now();
12461
+ ts4 = Settings.now();
12462
12462
  }
12463
12463
  return new DateTime({
12464
- ts: ts3,
12464
+ ts: ts4,
12465
12465
  zone,
12466
12466
  loc,
12467
12467
  o
@@ -12624,8 +12624,8 @@ var require_luxon = __commonJS({
12624
12624
  * @return {DateTime}
12625
12625
  */
12626
12626
  static fromJSDate(date, options = {}) {
12627
- const ts3 = isDate(date) ? date.valueOf() : NaN;
12628
- if (Number.isNaN(ts3)) {
12627
+ const ts4 = isDate(date) ? date.valueOf() : NaN;
12628
+ if (Number.isNaN(ts4)) {
12629
12629
  return _DateTime.invalid("invalid input");
12630
12630
  }
12631
12631
  const zoneToUse = normalizeZone(options.zone, Settings.defaultZone);
@@ -12633,7 +12633,7 @@ var require_luxon = __commonJS({
12633
12633
  return _DateTime.invalid(unsupportedZone(zoneToUse));
12634
12634
  }
12635
12635
  return new _DateTime({
12636
- ts: ts3,
12636
+ ts: ts4,
12637
12637
  zone: zoneToUse,
12638
12638
  loc: Locale.fromObject(options)
12639
12639
  });
@@ -13493,9 +13493,9 @@ var require_luxon = __commonJS({
13493
13493
  mixed.day = Math.min(daysInMonth(mixed.year, mixed.month), mixed.day);
13494
13494
  }
13495
13495
  }
13496
- const [ts3, o] = objToTS(mixed, this.o, this.zone);
13496
+ const [ts4, o] = objToTS(mixed, this.o, this.zone);
13497
13497
  return clone(this, {
13498
- ts: ts3,
13498
+ ts: ts4,
13499
13499
  o
13500
13500
  });
13501
13501
  }
@@ -17660,85 +17660,12 @@ async function packageFunctions(entry, output) {
17660
17660
  return outputPath;
17661
17661
  }
17662
17662
 
17663
- // src/cli-session.ts
17664
- import { hostname, platform, release, arch } from "node:os";
17665
-
17666
- // package.json
17667
- var package_default = {
17668
- name: "@backifydev/cli",
17669
- version: "0.3.9",
17670
- description: "Command-line setup and diagnostics for Backify applications",
17671
- type: "module",
17672
- bin: {
17673
- backify: "dist/index.js"
17674
- },
17675
- files: [
17676
- "dist/index.js",
17677
- "README.md"
17678
- ],
17679
- scripts: {
17680
- prebuild: "npm run build -w @backify/platform && npm run build -w @backifydev/sdk && npm run build -w @backify/analyzer",
17681
- build: `esbuild src/index.ts --bundle --platform=node --format=esm --external:esbuild --external:typescript --outfile=dist/index.js --banner:js="import { createRequire as __backifyCreateRequire } from 'node:module'; var require = __backifyCreateRequire(import.meta.url);"`,
17682
- prepack: "npm run build",
17683
- pretypecheck: "npm run build -w @backify/platform && npm run build -w @backifydev/sdk && npm run build -w @backify/analyzer",
17684
- typecheck: "tsc --noEmit",
17685
- pretest: "npm run build -w @backify/platform && npm run build -w @backifydev/sdk && npm run build -w @backify/analyzer",
17686
- test: "vitest run"
17687
- },
17688
- publishConfig: {
17689
- access: "public"
17690
- },
17691
- repository: {
17692
- type: "git",
17693
- url: "git+https://github.com/frejnorling/backify.git",
17694
- directory: "packages/cli"
17695
- },
17696
- homepage: "https://agent.backify.dev/",
17697
- license: "MIT",
17698
- engines: {
17699
- node: ">=20"
17700
- },
17701
- dependencies: {
17702
- "@azure/functions": "^4.7.2",
17703
- "@backifydev/sdk": "^0.1.1",
17704
- esbuild: "^0.25.10",
17705
- fflate: "^0.8.2",
17706
- typescript: "^5.9.2"
17707
- },
17708
- devDependencies: {
17709
- "@backify/analyzer": "*",
17710
- "@backify/platform": "*",
17711
- "@hono/node-server": "2.1.3",
17712
- "@types/node": "^24.3.1",
17713
- hono: "4.13.12",
17714
- vitest: "^4.1.11"
17715
- }
17716
- };
17717
-
17718
- // src/cli-session.ts
17719
- function cliDevice() {
17720
- return { deviceName: hostname(), operatingSystem: platform() + " " + release(), architecture: arch(), cliVersion: package_default.version };
17721
- }
17722
- var cliUserAgent = "BackifyCLI/" + package_default.version;
17723
- async function registerCliSession(client, applicationId, apiUrl) {
17724
- const session = await client("/apps/" + applicationId + "/developer/session", { method: "POST", body: JSON.stringify(cliDevice()) });
17725
- return { ...session, apiUrl };
17726
- }
17727
-
17728
- // src/browser-auth.ts
17729
- import { randomBytes } from "node:crypto";
17730
- import { createServer } from "node:http";
17731
-
17732
- // src/development.ts
17733
- import { existsSync as existsSync4, readFileSync as readFileSync3, readdirSync as readdirSync2, writeFileSync as writeFileSync4, renameSync, rmSync, mkdtempSync, lstatSync as lstatSync2, cpSync } from "node:fs";
17734
- import { dirname as dirname4, join as join3, resolve as resolve3 } from "node:path";
17735
- import { spawnSync as spawnSync2 } from "node:child_process";
17736
- import { randomUUID } from "node:crypto";
17737
-
17738
- // src/setup.ts
17739
- import { existsSync as existsSync3, readFileSync as readFileSync2, writeFileSync as writeFileSync3, mkdirSync as mkdirSync2, readdirSync, lstatSync } from "node:fs";
17740
- import { basename, dirname as dirname3, join as join2, resolve as resolve2, isAbsolute } from "node:path";
17663
+ // src/environment.ts
17741
17664
  import { spawnSync } from "node:child_process";
17665
+ import { randomUUID } from "node:crypto";
17666
+ import { readFileSync, unlinkSync, writeFileSync as writeFileSync2 } from "node:fs";
17667
+ import { createServer } from "node:http";
17668
+ import { join, resolve as resolve2 } from "node:path";
17742
17669
 
17743
17670
  // ../platform/dist/manifest.js
17744
17671
  var import_yaml = __toESM(require_dist(), 1);
@@ -17773,6 +17700,12 @@ function parseApplicationManifest(source) {
17773
17700
  validatePortableSettings(settings);
17774
17701
  if (name2 === "auth")
17775
17702
  validateAuthSettings(settings);
17703
+ if (name2 === "ai") {
17704
+ if (Object.keys(settings).some((key) => !["enabled", "models"].includes(key)))
17705
+ throw new Error("Unknown AI setting");
17706
+ if (settings.models !== void 0 && (!Array.isArray(settings.models) || settings.models.length === 0 || settings.models.length > 100 || settings.models.some((model) => typeof model !== "string" || !["default", "fast", "smart"].includes(model) && (model.length !== 32 || !/^foundry-[0-9a-f]{24}$/.test(model))) || new Set(settings.models).size !== settings.models.length))
17707
+ throw new Error("AI models must be distinct logical names or Foundry IDs from the application AI catalog");
17708
+ }
17776
17709
  if (settings.enabled !== void 0 && typeof settings.enabled !== "boolean")
17777
17710
  throw new Error("enabled must be boolean: " + name2);
17778
17711
  if (name2 === "database" && settings.engine !== void 0 && settings.engine !== "postgres")
@@ -17833,8 +17766,14 @@ function manifestDiagnostics(manifest, used, authentication) {
17833
17766
  // ../platform/dist/delivery.js
17834
17767
  var deliveryInstructions = `# Backify application delivery and prompt history
17835
17768
 
17836
- Instruction version: 5
17837
- Versioned guide: https://agent.backify.dev/v5/delivery.md
17769
+ Instruction version: 9
17770
+ Versioned guide: https://agent.backify.dev/v9/delivery.md
17771
+
17772
+ ## Environment and documentation prerequisites
17773
+
17774
+ Before installation or connection, read https://agent.backify.dev/v9 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.
17775
+
17776
+ 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.
17838
17777
 
17839
17778
  These instructions are for AI coding tools building applications on Backify, not the Backify platform implementation. Complete the application and deliver a verified deployment, not just SDK setup. Respect the coding tool's own permissions and confirmation settings; preserve unrelated work and applicable repository instructions.
17840
17779
 
@@ -17844,7 +17783,7 @@ The copied Backify prompt supplies App Id, Organization, and, when available, Pa
17844
17783
 
17845
17784
  npx @backifydev/cli@latest connect --app <app-id> --organization <organization-id> --api https://api.backify.dev/api --pair <pairing-code>
17846
17785
 
17847
- If Pair is absent, omit --pair and use CLI browser login. Pairing expires after 15 minutes. Never record the code or setup prompt in project files, Git, prompt history, or logs. The CLI stores an application-scoped session outside the repository. If access expires, obtain a new setup prompt or use CLI browser login.
17786
+ If Pair is absent, omit --pair and use CLI browser login. Pairing expires after 15 minutes. Never record the code or setup prompt in project files, Git, prompt history, or logs. The CLI stores an application-scoped session outside the repository. If CLI access expires, use the browser reauthentication workflow below, never another setup prompt. A fresh pairing code is needed only if initial pairing expired or was consumed.
17848
17787
 
17849
17788
  Before connecting, inspect the current folder. If it is not a Git repository, is missing its .git directory or file, or has no Git remote, add --clone to the connect command. Default AI coding-tool directories and instruction files do not make a workspace an existing application. Run connect --clone in the current folder even when tool scaffolding exists, including configuration, rules, agents, skills, commands, prompts, and work/output directories. This is tool-independent: preserve the current tool's metadata and instructions regardless of its name; never delete or overwrite them to make the folder empty. The CLI recognizes empty directories of any name, hidden tool-metadata directories and files, Markdown instruction files, and default work/outputs directories, including their contents. It clones into a temporary folder, checks for file conflicts, and safely merges the repository into the current workspace. If actual application source or an existing .git is present, or repository files conflict with existing entries, stop and reconcile the workspace or use a new folder; never overwrite user work. In an existing repository with a remote, verify it matches the connected repository and branch; never overwrite unrelated files or force-push.
17850
17789
 
@@ -17852,7 +17791,7 @@ Initialize using App Id from the copied prompt and the current tool selection:
17852
17791
 
17853
17792
  npx @backifydev/cli@latest init --app <app-id> --agent <current-tool>
17854
17793
 
17855
- 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/v5 for instruction version 5; use the guide matching backify.json in an existing application. Do not silently upgrade its managed instruction version or overwrite instructions outside the managed block.
17794
+ 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/v9 for instruction version 9; use the guide matching backify.json in an existing application. Do not silently upgrade its managed instruction version or overwrite instructions outside the managed block.
17856
17795
 
17857
17796
  Run the following to discover the connected hosting target, repository, branch, reports, releases, and deployment failures:
17858
17797
 
@@ -17892,9 +17831,9 @@ Do not claim unsupported hosted server functions or SDK execution paths work. Re
17892
17831
 
17893
17832
  ## Local development before delivery
17894
17833
 
17895
- From the first setup, make every new application runnable and testable locally without a cloud deployment. Follow the matching setup guide's local development steps: preserve the framework, provide a package-manager dev script and README, use @backifydev/sdk/local for platform capabilities and tests, and keep local state and credentials out of Git. Use a native framework dev server for frontend-only apps; for Backify server capabilities, configure backify.yaml and npx @backifydev/cli@latest dev --mode lightweight --json with the supported frontend adapter when needed. Disclose emulator limits and any full-runtime prerequisites.
17834
+ After the required setup gate passes and application requirements are supplied, make every new application runnable and testable locally without a cloud deployment. Follow the matching setup guide's local development steps: preserve the framework, provide a package-manager dev script and README, use @backifydev/sdk/local for platform capabilities and tests, and keep local state and credentials out of Git. Use a native framework dev server for frontend-only apps; for Backify server capabilities, configure backify.yaml and npx @backifydev/cli@latest dev --mode lightweight --json with the supported frontend adapter when needed. Disclose emulator limits and any full-runtime prerequisites.
17896
17835
 
17897
- 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. Cloud connection, preview approval, or deployment failure must not prevent safe local testing; report those blockers separately without bypassing authorization. If requirements are missing, verify a minimal runnable shell before asking the required final question. Never claim local readiness from a build or management-dashboard response alone.
17836
+ 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.
17898
17837
 
17899
17838
  ## Verify, push, and publish
17900
17839
 
@@ -17912,13 +17851,13 @@ If testing or approval is required, return the preview URL and explain the remai
17912
17851
 
17913
17852
  ## User-facing handoff
17914
17853
 
17915
- After setup or a delivery attempt, give the user concise instructions: explain what is ready, how to open and use the application, and any sign-in, testing, approval, or other next steps. Summarize actual checks and blockers without exposing credentials or asking the user to perform routine deployment work the coding tool can complete.
17854
+ If setup is blocked, report the failed or unverified checks and recommend an AI coding tool as described above and stop. Do not present a local application, download, or start command as a substitute for successful setup. After successful setup or a later delivery attempt, give the user concise instructions: explain what is ready, how to open and use the application, and any sign-in, testing, approval, or other next steps. Summarize actual checks and blockers without exposing credentials or asking the user to perform routine deployment work the coding tool can complete.
17916
17855
 
17917
17856
  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.
17918
17857
 
17919
17858
  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.
17920
17859
 
17921
- If application requirements are missing after setup, finish the response with this exact question as its final line, without any text after it:
17860
+ If application requirements are missing after successful setup, finish the response with this exact question as its final line, without any text after it:
17922
17861
 
17923
17862
  What should the application do, and what should it look like?
17924
17863
 
@@ -17926,7 +17865,7 @@ These instructions are an explicit agent workflow, not a universal chat intercep
17926
17865
  `;
17927
17866
 
17928
17867
  // ../platform/dist/index.js
17929
- var INSTRUCTION_VERSION = 5;
17868
+ var INSTRUCTION_VERSION = 9;
17930
17869
  var SDK_PACKAGE = "@backifydev/sdk";
17931
17870
  var DOCS_URL = "https://docs.backify.dev";
17932
17871
  var MAIL_LIMITS = Object.freeze({
@@ -17951,17 +17890,18 @@ var CAPABILITIES = [
17951
17890
  capability("functions", "functions", "Server function declarations"),
17952
17891
  capability("jobs", "jobs", "Reliable background work", true),
17953
17892
  capability("scheduler", "jobs.schedule", "Scheduled job declarations"),
17954
- capability("events", "events", "Inbound webhooks and governed outbound HTTP", true),
17893
+ capability("events", "events", "Event tracking, inbound webhooks and governed outbound HTTP", true),
17955
17894
  { ...capability("mail", "mail", "Server-only mail.send: to accepts an address or address array; 25 attempts per application per UTC month shared by all environments; 50 total To/CC/BCC recipients; 10 attachments totaling 10 MiB decoded; 256 KiB combined text/HTML; 998-character subject. Identical sends without an explicit idempotency key are deduplicated for a rolling 5 minutes. sensitive: true never stores original subjects or bodies. Read the mail capability guide and mail.limits before implementing sends.", true), limits: MAIL_LIMITS },
17956
17895
  capability("secrets", "secrets", "Server-side secret retrieval", true),
17896
+ capability("integrations", "integrations", "Approved, versioned API contracts and environment-scoped operation grants", true),
17957
17897
  capability("http", "http", "Governed outbound HTTP"),
17958
- capability("ai", "ai", "Provider-independent generative AI"),
17898
+ capability("ai", "ai", "Server-only ai.generate, ai.extract, ai.classify and ai.embed. Declare capabilities.ai in backify.yaml; optional models may use default, fast, smart or foundry- IDs from the application's location-aware AI catalog, within its allowed-model policy. Backify provisions isolated Azure Foundry model deployments and supplies scoped runtime credentials automatically. Do not add Azure/OpenAI credentials to application code."),
17959
17899
  capability("audit", "audit", "Structured audit records"),
17960
17900
  capability("logs", "logs", "Structured application logging"),
17961
17901
  capability("config", "config", "Non-secret application configuration")
17962
17902
  ];
17963
17903
  var CAPABILITY_REGISTRY = Object.fromEntries(CAPABILITIES.map((x) => [x.name, x]));
17964
- var SDK_IMPORT_CAPABILITIES = { defineJob: "jobs", database: "database", auth: "auth", db: "database", storage: "storage", functions: "functions", defineFunction: "functions", jobs: "jobs", mail: "mail", events: "events", secrets: "secrets", http: "http", ai: "ai", audit: "audit", logs: "logs", logging: "logs", config: "config" };
17904
+ var SDK_IMPORT_CAPABILITIES = { integrations: "integrations", defineJob: "jobs", database: "database", auth: "auth", db: "database", storage: "storage", functions: "functions", defineFunction: "functions", jobs: "jobs", mail: "mail", webhooks: "events", events: "events", secrets: "secrets", http: "http", ai: "ai", audit: "audit", logs: "logs", logging: "logs", config: "config" };
17965
17905
  var MANAGED_START = "<!-- BACKIFY:MANAGED:START -->";
17966
17906
  var MANAGED_END = "<!-- BACKIFY:MANAGED:END -->";
17967
17907
  function managedInstructions() {
@@ -17979,6 +17919,8 @@ Use \`@backifydev/sdk\` for platform capabilities. Do not directly integrate or
17979
17919
 
17980
17920
  ## SDK capability map
17981
17921
 
17922
+ Before dependent setup operations, follow the environment checks and permission recovery in https://agent.backify.dev/v${INSTRUCTION_VERSION}. Retrieve and read the relevant documentation at ${DOCS_URL}/capabilities/ before implementing capabilities, then verify installed SDK types. If access is blocked, use only the coding tool's supported native approval mechanism, retry after approval, and report unverified work honestly. Never bypass restrictions or invent approval tools. 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.
17923
+
17982
17924
  - Authentication and authorization: \`auth\`.
17983
17925
  - Persistent data and files: \`db\` and \`storage\`.
17984
17926
  - Server functions: \`defineFunction\`; background work and schedules: \`jobs\` and \`jobs.schedule\`.
@@ -18059,39 +18001,277 @@ function validateConfig(value) {
18059
18001
  }
18060
18002
  var BACKIFY_SCHEMA = { $schema: "https://json-schema.org/draft/2020-12/schema", $id: `${DOCS_URL}/schema/backify.json`, type: "object", additionalProperties: false, required: ["$schema", "platform", "sdk", "appId", "instructionVersion", "docs", "instructions"], properties: { $schema: { const: `${DOCS_URL}/schema/backify.json` }, platform: { const: "backify" }, sdk: { const: SDK_PACKAGE }, appId: { type: "string", pattern: "^app_[A-Za-z0-9_-]+$" }, instructionVersion: { type: "integer", minimum: 1 }, agent: { enum: ["codex", "claude", "copilot", "gemini", "custom"] }, instructionFile: { type: "string", minLength: 1 }, docs: { type: "string", format: "uri" }, instructions: { type: "object", additionalProperties: false, required: ["preferBackifyCapabilities", "allowDirectCloudInfrastructure"], properties: { preferBackifyCapabilities: { const: true }, allowDirectCloudInfrastructure: { const: false } } } } };
18061
18003
 
18004
+ // src/environment.ts
18005
+ function classifyEnvironmentFailure(error) {
18006
+ const value = error;
18007
+ const code = value?.code;
18008
+ if (code === "EACCES" || code === "EPERM") return "permission";
18009
+ if (code === "ENOTFOUND" || code === "EAI_AGAIN") return "dns";
18010
+ if (code && /CERT|TLS|SSL/.test(code)) return "tls";
18011
+ if (value?.name === "TimeoutError" || value?.name === "AbortError" || code === "ETIMEDOUT" || code === "UND_ERR_CONNECT_TIMEOUT") return "timeout";
18012
+ if (code === "ECONNREFUSED" || code === "ECONNRESET" || code === "ENETUNREACH" || code === "EHOSTUNREACH") return "connection";
18013
+ if (code === "ENOENT") return "missing_tool";
18014
+ if (value?.cause && value.cause !== error) return classifyEnvironmentFailure(value.cause);
18015
+ return "unknown";
18016
+ }
18017
+ function environmentRecovery(failure2) {
18018
+ switch (failure2) {
18019
+ case "permission":
18020
+ return "Use the current agent's supported native approval mechanism for minimum required access, retry after approval and verify. If unsupported or denied, enable access or switch environments; never bypass restrictions.";
18021
+ case "dns":
18022
+ return "Check DNS and the endpoint hostname; retry once for a temporary failure. Request network access only if policy confirms it is blocked.";
18023
+ case "tls":
18024
+ return "Check the certificate, system clock and trusted proxy configuration; never disable TLS verification.";
18025
+ case "timeout":
18026
+ case "connection":
18027
+ return "Check connectivity and exposed network policy; retry once if temporary. A timeout or connection error alone does not prove a sandbox restriction.";
18028
+ case "authentication":
18029
+ return "HTTP 401/403 indicates authentication or access denial, not necessarily a sandbox. For expired CLI sessions use backify connect --reauth; never request another setup prompt or send credentials to a public probe.";
18030
+ case "not_found":
18031
+ return "Check the documented URL and resource; HTTP 404 is not an environment restriction.";
18032
+ case "rate_limit":
18033
+ return "Respect Retry-After within the task's time budget; do not repeatedly retry.";
18034
+ case "server":
18035
+ return "Report the endpoint's HTTP 5xx; retry once if temporary and keep cloud failures separate from local work.";
18036
+ case "missing_tool":
18037
+ return "Install the missing prerequisite with authorized tools or use a terminal-enabled environment that supplies it.";
18038
+ default:
18039
+ return "Report the failed check without exposing credentials. Consult https://agent.backify.dev for diagnosis and safe fallback; do not claim verification succeeded.";
18040
+ }
18041
+ }
18042
+ function environmentEndpoints(capability2) {
18043
+ if (capability2 !== void 0 && !Object.hasOwn(CAPABILITY_REGISTRY, capability2)) throw new Error("Select a documented Backify capability name.");
18044
+ return [
18045
+ "https://agent.backify.dev/",
18046
+ "https://docs.backify.dev/",
18047
+ "https://api.backify.dev/health",
18048
+ "https://registry.npmjs.org/@backifydev%2fcli",
18049
+ "https://registry.npmjs.org/@backifydev%2fsdk",
18050
+ ...capability2 ? [CAPABILITY_REGISTRY[capability2].docs] : []
18051
+ ];
18052
+ }
18053
+ async function probeEndpoint(url, transport = fetch) {
18054
+ const response = await transport(url, { signal: AbortSignal.timeout(5e3), redirect: "error", credentials: "omit" });
18055
+ await response.body?.cancel();
18056
+ return response.status;
18057
+ }
18058
+ function workspaceProbe(root) {
18059
+ const directory2 = resolve2(root);
18060
+ const filename2 = join(directory2, ".backify-environment-" + randomUUID());
18061
+ const content = randomUUID();
18062
+ let created = false;
18063
+ try {
18064
+ writeFileSync2(filename2, content, { flag: "wx" });
18065
+ created = true;
18066
+ if (readFileSync(filename2, "utf8") !== content) throw new Error("Workspace read/write failed.");
18067
+ } finally {
18068
+ if (created) unlinkSync(filename2);
18069
+ }
18070
+ }
18071
+ async function localhostProbe() {
18072
+ const server = createServer((_request, response) => {
18073
+ response.end("backify-environment-probe");
18074
+ });
18075
+ try {
18076
+ await new Promise((accept, reject) => {
18077
+ server.once("error", reject);
18078
+ server.listen(0, "127.0.0.1", () => accept());
18079
+ });
18080
+ const address = server.address();
18081
+ if (!address || typeof address === "string") throw new Error("No loopback address.");
18082
+ const response = await fetch("http://127.0.0.1:" + address.port, { signal: AbortSignal.timeout(5e3), redirect: "error" });
18083
+ if (!response.ok || await response.text() !== "backify-environment-probe") throw new Error("Loopback verification failed.");
18084
+ } finally {
18085
+ server.closeAllConnections();
18086
+ if (server.listening) await new Promise((accept) => server.close(() => accept()));
18087
+ }
18088
+ }
18089
+ function environmentProbes(root) {
18090
+ return {
18091
+ nodeVersion: process.versions.node,
18092
+ command: (name2) => {
18093
+ const windowsNpm = name2 === "npm" && process.platform === "win32";
18094
+ const executable = windowsNpm ? process.env.ComSpec ?? "cmd.exe" : name2;
18095
+ const argumentsList = windowsNpm ? ["/d", "/s", "/c", "npm.cmd --version"] : ["--version"];
18096
+ const result = spawnSync(executable, argumentsList, { timeout: 5e3, stdio: "ignore", windowsHide: true });
18097
+ if (result.error) throw result.error;
18098
+ if (result.status !== 0) throw Object.assign(new Error("Prerequisite command failed."), { code: result.status === 127 || result.status === 9009 ? "ENOENT" : void 0 });
18099
+ },
18100
+ workspace: () => workspaceProbe(root),
18101
+ localhost: localhostProbe,
18102
+ request: probeEndpoint
18103
+ };
18104
+ }
18105
+ async function diagnoseEnvironment(root = process.cwd(), options = {}, probes = environmentProbes(root)) {
18106
+ const endpoints = environmentEndpoints(options.capability);
18107
+ const checks = [];
18108
+ const check = async (name2, required, operation) => {
18109
+ try {
18110
+ await operation();
18111
+ checks.push({ name: name2, required, status: "passed" });
18112
+ } catch (error) {
18113
+ const failure2 = classifyEnvironmentFailure(error);
18114
+ checks.push({ name: name2, required, status: "failed", failure: failure2, recovery: environmentRecovery(failure2) });
18115
+ }
18116
+ };
18117
+ checks.push({ name: "node", required: true, status: Number(probes.nodeVersion.split(".")[0]) >= 20 ? "passed" : "failed", ...Number(probes.nodeVersion.split(".")[0]) >= 20 ? {} : { failure: "missing_tool", recovery: "Install Node.js 20 or later with authorized tools." } });
18118
+ await check("npm", true, () => probes.command("npm"));
18119
+ await check("git", false, () => probes.command("git"));
18120
+ await check("workspace", true, probes.workspace);
18121
+ await check("localhost", true, probes.localhost);
18122
+ for (const endpoint of endpoints) {
18123
+ if (!options.network) {
18124
+ checks.push({ name: "network", endpoint, required: true, status: "unverified", recovery: "Run backify doctor --environment --network using authorized network access." });
18125
+ continue;
18126
+ }
18127
+ try {
18128
+ const httpStatus = await probes.request(endpoint);
18129
+ const failure2 = httpStatus === 401 || httpStatus === 403 ? "authentication" : httpStatus === 404 ? "not_found" : httpStatus === 429 ? "rate_limit" : httpStatus >= 500 ? "server" : httpStatus >= 200 && httpStatus < 300 ? void 0 : "http";
18130
+ checks.push({ name: "network", endpoint, required: true, httpStatus, status: failure2 ? "failed" : "passed", ...failure2 ? { failure: failure2, recovery: environmentRecovery(failure2) } : {} });
18131
+ } catch (error) {
18132
+ const failure2 = classifyEnvironmentFailure(error);
18133
+ checks.push({ name: "network", endpoint, required: true, status: "failed", failure: failure2, recovery: environmentRecovery(failure2) });
18134
+ }
18135
+ }
18136
+ for (const name2 of ["agent_approval_support", "browser_authentication", "cross_session_persistence", "application_tests", "deployment_authorization"]) checks.push({ name: name2, required: false, status: "unverified", recovery: "Verify with the current agent's exposed tools and the actual workflow; CLI diagnostics cannot grant or infer authorization." });
18137
+ return { schemaVersion: 1, valid: !checks.some((item) => item.required && item.status === "failed"), verified: checks.filter((item) => item.required).every((item) => item.status === "passed"), checks };
18138
+ }
18139
+
18140
+ // src/integrations.ts
18141
+ function integrationDiscoveryPath(command3, options) {
18142
+ const uuid4 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
18143
+ if (!uuid4.test(options.applicationId)) throw new Error("An application UUID is required");
18144
+ const base = "/apps/" + options.applicationId + "/integrations/connectors";
18145
+ if (command3 === "list") return base;
18146
+ if (command3 === "catalog") return "/apps/" + options.applicationId + "/integrations/catalog";
18147
+ if (!options.connectionId || !uuid4.test(options.connectionId)) throw new Error("Use --connection with an integration connection UUID");
18148
+ const connection = base + "/" + options.connectionId;
18149
+ if (command3 === "contract" || command3 === "types") return connection + "/" + command3;
18150
+ if (command3 === "describe") {
18151
+ if (!options.operationId) throw new Error("Use --operation to select an operation");
18152
+ return connection + "/operations/" + encodeURIComponent(options.operationId);
18153
+ }
18154
+ if (command3 === "search") {
18155
+ if (!Number.isInteger(options.offset ?? 0) || (options.offset ?? 0) < 0 || (options.offset ?? 0) > 500) throw new Error("Offset must be between 0 and 500");
18156
+ const query = new URLSearchParams({ query: options.query ?? "", offset: String(options.offset ?? 0), limit: "50" });
18157
+ return connection + "/operations?" + query;
18158
+ }
18159
+ throw new Error("Use backify integrations list|catalog|search|describe|contract|types");
18160
+ }
18161
+
18162
+ // src/cli-session.ts
18163
+ import { hostname, platform, release, arch } from "node:os";
18164
+
18165
+ // package.json
18166
+ var package_default = {
18167
+ name: "@backifydev/cli",
18168
+ version: "0.3.11",
18169
+ description: "Command-line setup and diagnostics for Backify applications",
18170
+ type: "module",
18171
+ bin: {
18172
+ backify: "dist/index.js"
18173
+ },
18174
+ files: [
18175
+ "dist/index.js",
18176
+ "README.md"
18177
+ ],
18178
+ scripts: {
18179
+ prebuild: "npm run build -w @backify/platform && npm run build -w @backifydev/sdk && npm run build -w @backify/analyzer",
18180
+ build: `esbuild src/index.ts --bundle --platform=node --format=esm --external:esbuild --external:typescript --outfile=dist/index.js --banner:js="import { createRequire as __backifyCreateRequire } from 'node:module'; var require = __backifyCreateRequire(import.meta.url);"`,
18181
+ prepack: "npm run build",
18182
+ pretypecheck: "npm run build -w @backify/platform && npm run build -w @backifydev/sdk && npm run build -w @backify/analyzer",
18183
+ typecheck: "tsc --noEmit",
18184
+ pretest: "npm run build -w @backify/platform && npm run build -w @backifydev/sdk && npm run build -w @backify/analyzer",
18185
+ test: "vitest run"
18186
+ },
18187
+ publishConfig: {
18188
+ access: "public"
18189
+ },
18190
+ repository: {
18191
+ type: "git",
18192
+ url: "git+https://github.com/frejnorling/backify.git",
18193
+ directory: "packages/cli"
18194
+ },
18195
+ homepage: "https://agent.backify.dev/",
18196
+ license: "MIT",
18197
+ engines: {
18198
+ node: ">=20"
18199
+ },
18200
+ dependencies: {
18201
+ "@azure/functions": "^4.7.2",
18202
+ "@backifydev/sdk": "^0.1.1",
18203
+ esbuild: "^0.25.10",
18204
+ fflate: "^0.8.2",
18205
+ typescript: "^5.9.2"
18206
+ },
18207
+ devDependencies: {
18208
+ "@backify/analyzer": "*",
18209
+ "@backify/platform": "*",
18210
+ "@hono/node-server": "2.1.3",
18211
+ "@types/node": "^24.3.1",
18212
+ hono: "4.13.12",
18213
+ vitest: "^4.1.11"
18214
+ }
18215
+ };
18216
+
18217
+ // src/cli-session.ts
18218
+ function cliDevice() {
18219
+ return { deviceName: hostname(), operatingSystem: platform() + " " + release(), architecture: arch(), cliVersion: package_default.version };
18220
+ }
18221
+ var cliUserAgent = "BackifyCLI/" + package_default.version;
18222
+ async function registerCliSession(client, applicationId, apiUrl) {
18223
+ const session = await client("/apps/" + applicationId + "/developer/session", { method: "POST", body: JSON.stringify(cliDevice()) });
18224
+ return { ...session, apiUrl };
18225
+ }
18226
+
18227
+ // src/browser-auth.ts
18228
+ import { randomBytes } from "node:crypto";
18229
+ import { createServer as createServer2 } from "node:http";
18230
+
18231
+ // src/development.ts
18232
+ import { existsSync as existsSync4, readFileSync as readFileSync4, readdirSync as readdirSync2, writeFileSync as writeFileSync5, renameSync, rmSync, mkdtempSync, lstatSync as lstatSync2, cpSync } from "node:fs";
18233
+ import { dirname as dirname4, join as join4, resolve as resolve4 } from "node:path";
18234
+ import { spawnSync as spawnSync3 } from "node:child_process";
18235
+ import { randomUUID as randomUUID2 } from "node:crypto";
18236
+
18237
+ // src/setup.ts
18238
+ import { existsSync as existsSync3, readFileSync as readFileSync3, writeFileSync as writeFileSync4, mkdirSync as mkdirSync2, readdirSync, lstatSync } from "node:fs";
18239
+ import { basename, dirname as dirname3, join as join3, resolve as resolve3, isAbsolute } from "node:path";
18240
+ import { spawnSync as spawnSync2 } from "node:child_process";
18241
+
18062
18242
  // src/delivery.ts
18063
- import { existsSync as existsSync2, readFileSync, writeFileSync as writeFileSync2 } from "node:fs";
18064
- import { dirname as dirname2, join, relative as relativePath } from "node:path";
18243
+ import { existsSync as existsSync2, readFileSync as readFileSync2, writeFileSync as writeFileSync3 } from "node:fs";
18244
+ import { dirname as dirname2, join as join2, relative as relativePath } from "node:path";
18065
18245
  import { createHash } from "node:crypto";
18066
18246
  var previousGeneratedWorkflowHashes = /* @__PURE__ */ new Set(["33e962274e8493f7cbac2afbac05a4e96afeec49ee08cf2bf82f8add9081b28b", "578dfb4c771c623fd04454e8a604efd701d5563d11e11191324862369bd24718", "6eb280ae7bdb14c390011686c41400f59c023304c3015d8440b7e80aaafa1c11", "545e03a1d5b996ade179e0e60ed5c86accdadc1982c1c25efd094e34f72f47ee"]);
18067
18247
  function validateDeliveryInstructions(root) {
18068
18248
  for (const filename2 of ["BACKIFY.md", "BACKIFY-WORKFLOW.md"]) {
18069
- const path = join(root, filename2);
18249
+ const path = join2(root, filename2);
18070
18250
  if (existsSync2(path)) {
18071
- const existing = readFileSync(path, "utf8").replace(/\r\n/g, "\n");
18251
+ const existing = readFileSync2(path, "utf8").replace(/\r\n/g, "\n");
18072
18252
  if (existing !== deliveryInstructions && !previousGeneratedWorkflowHashes.has(createHash("sha256").update(existing).digest("hex"))) throw new Error(filename2 + " contains different instructions. Review it before initializing; it will not be overwritten.");
18073
18253
  }
18074
18254
  }
18075
18255
  }
18076
18256
  function installDeliveryInstructions(root, instructionFiles2) {
18077
18257
  validateDeliveryInstructions(root);
18078
- writeFileSync2(join(root, "BACKIFY.md"), deliveryInstructions);
18258
+ writeFileSync3(join2(root, "BACKIFY.md"), deliveryInstructions);
18079
18259
  for (const relative11 of instructionFiles2) {
18080
- const instructionPath = join(root, relative11), content = readFileSync(instructionPath, "utf8");
18081
- const link = relativePath(dirname2(instructionPath), join(root, "BACKIFY.md")).replaceAll("\\", "/");
18082
- const legacyLink = relativePath(dirname2(instructionPath), join(root, "BACKIFY-WORKFLOW.md")).replaceAll("\\", "/");
18260
+ const instructionPath = join2(root, relative11), content = readFileSync2(instructionPath, "utf8");
18261
+ const link = relativePath(dirname2(instructionPath), join2(root, "BACKIFY.md")).replaceAll("\\", "/");
18262
+ const legacyLink = relativePath(dirname2(instructionPath), join2(root, "BACKIFY-WORKFLOW.md")).replaceAll("\\", "/");
18083
18263
  const legacy = "For application delivery and recording each user request, follow [BACKIFY-WORKFLOW.md](" + legacyLink + ").";
18084
18264
  const guidance = "For application delivery and recording each user request, follow [BACKIFY.md](" + link + ").";
18085
- if (content.includes(legacy)) writeFileSync2(instructionPath, content.replace(legacy, guidance));
18086
- else if (!content.includes("## Backify delivery")) writeFileSync2(instructionPath, content.trimEnd() + "\n\n## Backify delivery\n\n" + guidance + "\n");
18265
+ if (content.includes(legacy)) writeFileSync3(instructionPath, content.replace(legacy, guidance));
18266
+ else if (!content.includes("## Backify delivery")) writeFileSync3(instructionPath, content.trimEnd() + "\n\n## Backify delivery\n\n" + guidance + "\n");
18087
18267
  }
18088
18268
  }
18089
18269
 
18090
18270
  // src/setup.ts
18091
18271
  var instructionFiles = ["AGENTS.md"];
18092
- var agentInstructionFiles = { codex: "AGENTS.md", claude: "CLAUDE.md", copilot: join2(".github", "copilot-instructions.md"), gemini: "GEMINI.md" };
18272
+ var agentInstructionFiles = { codex: "AGENTS.md", claude: "CLAUDE.md", copilot: join3(".github", "copilot-instructions.md"), gemini: "GEMINI.md" };
18093
18273
  function instructionSelection(root, agent, instructionFile) {
18094
- const configPath2 = join2(root, "backify.json"), configured = existsSync3(configPath2) ? JSON.parse(readFileSync2(configPath2, "utf8")) : {};
18274
+ const configPath2 = join3(root, "backify.json"), configured = existsSync3(configPath2) ? JSON.parse(readFileSync3(configPath2, "utf8")) : {};
18095
18275
  const custom = instructionFile ?? (agent === void 0 ? configured.instructionFile : void 0);
18096
18276
  const selected = instructionFile !== void 0 ? "custom" : agent ?? configured.agent ?? "codex";
18097
18277
  if (typeof selected !== "string" || selected !== "custom" && !Object.hasOwn(agentInstructionFiles, selected)) throw new Error("Select the current tool with --agent or --instruction-file <relative-path>.");
@@ -18100,7 +18280,7 @@ function instructionSelection(root, agent, instructionFile) {
18100
18280
  const normalized = filename2.replaceAll("\\", "/"), parts = normalized.split("/");
18101
18281
  if (isAbsolute(filename2) || /^[A-Za-z]:/.test(filename2) || parts.some((part) => !part || part === "." || part === ".." || part.toLowerCase() === ".git") || ["backify.md", "backify-workflow.md", "backify.json", "package.json", "package-lock.json"].includes(normalized.toLowerCase())) throw new Error("Instruction file must be a relative tool-instruction path inside the project, not Git metadata or a Backify configuration file.");
18102
18282
  for (let index = 1; index <= parts.length; index++) {
18103
- const entry = join2(root, ...parts.slice(0, index));
18283
+ const entry = join3(root, ...parts.slice(0, index));
18104
18284
  try {
18105
18285
  const metadata = lstatSync(entry);
18106
18286
  if (metadata.isSymbolicLink() || index < parts.length && !metadata.isDirectory() || index === parts.length && !metadata.isFile()) throw new Error("Instruction file path cannot traverse symlinks or replace a directory.");
@@ -18115,26 +18295,26 @@ function selectedInstructionFiles(root = process.cwd(), agent, instructionFile)
18115
18295
  }
18116
18296
  function isToolWorkspaceEntry(entry, root = process.cwd()) {
18117
18297
  if (entry.name.toLowerCase() === ".git" || entry.name.toLowerCase() === ".env" || entry.name.toLowerCase().startsWith(".env.")) return false;
18118
- return entry.isDirectory() && (entry.name.startsWith(".") || ["work", "outputs"].includes(entry.name) || readdirSync(join2(root, entry.name)).length === 0) || entry.isFile() && (entry.name.startsWith(".") || /\.(md|mdc)$/i.test(entry.name));
18298
+ return entry.isDirectory() && (entry.name.startsWith(".") || ["work", "outputs"].includes(entry.name) || readdirSync(join3(root, entry.name)).length === 0) || entry.isFile() && (entry.name.startsWith(".") || /\.(md|mdc)$/i.test(entry.name));
18119
18299
  }
18120
18300
  function detectPackageManager(root = process.cwd()) {
18121
- for (const [file, name2] of [["pnpm-lock.yaml", "pnpm"], ["yarn.lock", "yarn"], ["bun.lockb", "bun"], ["bun.lock", "bun"], ["package-lock.json", "npm"]]) if (existsSync3(join2(root, file))) return name2;
18301
+ for (const [file, name2] of [["pnpm-lock.yaml", "pnpm"], ["yarn.lock", "yarn"], ["bun.lockb", "bun"], ["bun.lock", "bun"], ["package-lock.json", "npm"]]) if (existsSync3(join3(root, file))) return name2;
18122
18302
  return "npm";
18123
18303
  }
18124
18304
  function updateInstructions(root = process.cwd(), agent, instructionFile) {
18125
18305
  const updates = selectedInstructionFiles(root, agent, instructionFile).map((relative11) => {
18126
- const path = join2(root, relative11);
18127
- return { path, content: updateManagedInstructions(existsSync3(path) ? readFileSync2(path, "utf8") : "") };
18306
+ const path = join3(root, relative11);
18307
+ return { path, content: updateManagedInstructions(existsSync3(path) ? readFileSync3(path, "utf8") : "") };
18128
18308
  });
18129
18309
  for (const { path, content } of updates) {
18130
18310
  mkdirSync2(dirname3(path), { recursive: true });
18131
- writeFileSync3(path, content);
18311
+ writeFileSync4(path, content);
18132
18312
  }
18133
18313
  }
18134
18314
  function synchronize(root = process.cwd(), agent, instructionFile) {
18135
- const path = join2(root, "backify.json");
18315
+ const path = join3(root, "backify.json");
18136
18316
  if (!existsSync3(path)) throw new Error("backify.json is missing; run backify init --app app_xxxxx");
18137
- const value = JSON.parse(readFileSync2(path, "utf8")), issues = validateConfig(value);
18317
+ const value = JSON.parse(readFileSync3(path, "utf8")), issues = validateConfig(value);
18138
18318
  if (issues.length) throw new Error(issues.join("; "));
18139
18319
  if (value.instructionVersion > INSTRUCTION_VERSION) throw new Error("This app uses newer instructions. Install a matching or newer CLI before syncing.");
18140
18320
  const selected = instructionSelection(root, agent, instructionFile);
@@ -18144,11 +18324,11 @@ function synchronize(root = process.cwd(), agent, instructionFile) {
18144
18324
  value.agent = selected.agent;
18145
18325
  value.instructionFile = selected.instructionFile;
18146
18326
  value.instructionVersion = INSTRUCTION_VERSION;
18147
- writeFileSync3(path, JSON.stringify(value, null, 2) + "\n");
18327
+ writeFileSync4(path, JSON.stringify(value, null, 2) + "\n");
18148
18328
  }
18149
18329
  function sdkInstalled(root = process.cwd()) {
18150
18330
  try {
18151
- const pkg = JSON.parse(readFileSync2(join2(root, "package.json"), "utf8"));
18331
+ const pkg = JSON.parse(readFileSync3(join3(root, "package.json"), "utf8"));
18152
18332
  return Boolean(pkg.dependencies?.[SDK_PACKAGE] || pkg.devDependencies?.[SDK_PACKAGE]);
18153
18333
  } catch {
18154
18334
  return false;
@@ -18156,26 +18336,26 @@ function sdkInstalled(root = process.cwd()) {
18156
18336
  }
18157
18337
  function installSdk(root = process.cwd()) {
18158
18338
  if (sdkInstalled(root)) return;
18159
- const manager = detectPackageManager(root), args2 = manager === "npm" ? ["install", SDK_PACKAGE] : ["add", SDK_PACKAGE], result = spawnSync(manager, args2, { cwd: root, stdio: "inherit", shell: process.platform === "win32" });
18339
+ const manager = detectPackageManager(root), args2 = manager === "npm" ? ["install", SDK_PACKAGE] : ["add", SDK_PACKAGE], result = spawnSync2(manager, args2, { cwd: root, stdio: "inherit", shell: process.platform === "win32" });
18160
18340
  if (result.status !== 0) throw new Error(`Could not install ${SDK_PACKAGE} with ${manager}`);
18161
18341
  }
18162
18342
  function ensurePackageManifest(root) {
18163
- const path = join2(root, "package.json");
18343
+ const path = join3(root, "package.json");
18164
18344
  if (existsSync3(path)) return;
18165
18345
  const setupFiles = /* @__PURE__ */ new Set([".git", ".gitignore", ".github", "AGENTS.md", "CLAUDE.md", "GEMINI.md", "BACKIFY.md", "BACKIFY-WORKFLOW.md", "README.md", "LICENSE", "backify.json"]);
18166
18346
  if (readdirSync(root, { withFileTypes: true }).some((entry) => !setupFiles.has(entry.name) && !isToolWorkspaceEntry(entry, root))) throw new Error("package.json is missing. Run backify init from the existing application's JavaScript/TypeScript package directory, or start in an empty folder. See https://agent.backify.dev/");
18167
- const name2 = basename(resolve2(root)).toLowerCase().replace(/[^a-z0-9-]+/g, "-").replace(/^-+|-+$/g, "") || "backify-app";
18168
- writeFileSync3(path, JSON.stringify({ name: name2, version: "0.0.0", private: true, type: "module" }, null, 2) + "\n", { flag: "wx" });
18347
+ const name2 = basename(resolve3(root)).toLowerCase().replace(/[^a-z0-9-]+/g, "-").replace(/^-+|-+$/g, "") || "backify-app";
18348
+ writeFileSync4(path, JSON.stringify({ name: name2, version: "0.0.0", private: true, type: "module" }, null, 2) + "\n", { flag: "wx" });
18169
18349
  }
18170
18350
  function initialize(appId, root = process.cwd(), install = true, agent, instructionFile) {
18171
18351
  if (!/^app_[A-Za-z0-9_-]+$/.test(appId)) throw new Error("Provide an application ID using --app app_xxxxx");
18172
18352
  const selected = instructionSelection(root, agent, instructionFile), files = selected.files;
18173
18353
  validateDeliveryInstructions(root);
18174
- for (const relative11 of files) if (existsSync3(join2(root, relative11))) updateManagedInstructions(readFileSync2(join2(root, relative11), "utf8"));
18354
+ for (const relative11 of files) if (existsSync3(join3(root, relative11))) updateManagedInstructions(readFileSync3(join3(root, relative11), "utf8"));
18175
18355
  ensurePackageManifest(root);
18176
18356
  if (install) installSdk(root);
18177
- const configPath2 = join2(root, "backify.json"), existing = existsSync3(configPath2) ? JSON.parse(readFileSync2(configPath2, "utf8")) : {};
18178
- writeFileSync3(configPath2, JSON.stringify({ ...existing, ...createConfig(appId), agent: selected.agent, instructionFile: selected.instructionFile }, null, 2) + "\n");
18357
+ const configPath2 = join3(root, "backify.json"), existing = existsSync3(configPath2) ? JSON.parse(readFileSync3(configPath2, "utf8")) : {};
18358
+ writeFileSync4(configPath2, JSON.stringify({ ...existing, ...createConfig(appId), agent: selected.agent, instructionFile: selected.instructionFile }, null, 2) + "\n");
18179
18359
  updateInstructions(root, selected.agent, selected.instructionFile);
18180
18360
  installDeliveryInstructions(root, files);
18181
18361
  }
@@ -18184,7 +18364,7 @@ function doctor(root = process.cwd(), agent, instructionFile) {
18184
18364
  if (!sdkInstalled(root)) issues.push(`${SDK_PACKAGE} is not installed`);
18185
18365
  let config;
18186
18366
  try {
18187
- config = JSON.parse(readFileSync2(join2(root, "backify.json"), "utf8"));
18367
+ config = JSON.parse(readFileSync3(join3(root, "backify.json"), "utf8"));
18188
18368
  issues.push(...validateConfig(config));
18189
18369
  } catch {
18190
18370
  issues.push("backify.json is missing or invalid JSON");
@@ -18197,16 +18377,16 @@ function doctor(root = process.cwd(), agent, instructionFile) {
18197
18377
  issues.push(reason instanceof Error ? reason.message : String(reason));
18198
18378
  }
18199
18379
  for (const relative11 of files) {
18200
- const path = join2(root, relative11);
18380
+ const path = join3(root, relative11);
18201
18381
  if (!existsSync3(path)) {
18202
18382
  issues.push(`${relative11} is missing`);
18203
18383
  continue;
18204
18384
  }
18205
- issues.push(...managedInstructionIssues(readFileSync2(path, "utf8")).map((issue) => `${relative11} ${issue}`));
18385
+ issues.push(...managedInstructionIssues(readFileSync3(path, "utf8")).map((issue) => `${relative11} ${issue}`));
18206
18386
  }
18207
18387
  let version = "unknown";
18208
18388
  try {
18209
- const pkg = JSON.parse(readFileSync2(join2(root, "package.json"), "utf8"));
18389
+ const pkg = JSON.parse(readFileSync3(join3(root, "package.json"), "utf8"));
18210
18390
  version = pkg.dependencies?.[SDK_PACKAGE] ?? pkg.devDependencies?.[SDK_PACKAGE] ?? "missing";
18211
18391
  } catch {
18212
18392
  }
@@ -18214,6 +18394,14 @@ function doctor(root = process.cwd(), agent, instructionFile) {
18214
18394
  }
18215
18395
 
18216
18396
  // src/development.ts
18397
+ function promptContext(root = process.cwd()) {
18398
+ let commitSha = null;
18399
+ try {
18400
+ commitSha = git(["rev-parse", "HEAD"], root);
18401
+ } catch {
18402
+ }
18403
+ return { device: cliDevice(), commitSha };
18404
+ }
18217
18405
  function promptMetadata(args2) {
18218
18406
  const fields5 = [["--model", "model", 200], ["--ai-tool", "aiTool", 200], ["--access-level", "accessLevel", 500]];
18219
18407
  const metadata = {};
@@ -18225,6 +18413,12 @@ function promptMetadata(args2) {
18225
18413
  throw new Error(`Provide ${flag} with a nonempty value of at most ${maxLength} characters without control characters or credentials.`);
18226
18414
  metadata[field] = value;
18227
18415
  }
18416
+ const commitIndex = args2.indexOf("--commit-sha");
18417
+ if (commitIndex >= 0) {
18418
+ const value = args2[commitIndex + 1];
18419
+ if (!value || !/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/i.test(value)) throw new Error("Provide --commit-sha with a full hexadecimal Git commit.");
18420
+ metadata.commitSha = value;
18421
+ }
18228
18422
  return metadata;
18229
18423
  }
18230
18424
  function applicationGuid(appId) {
@@ -18235,8 +18429,8 @@ function applicationGuid(appId) {
18235
18429
  return [value.slice(0, 8), value.slice(8, 12), value.slice(12, 16), value.slice(16, 20), value.slice(20)].join("-");
18236
18430
  }
18237
18431
  function projectApplication(root = process.cwd()) {
18238
- if (!existsSync4(join3(root, "backify.json"))) throw new Error("Run backify connect --app <application-id>, then backify init.");
18239
- return JSON.parse(readFileSync3(join3(root, "backify.json"), "utf8")).appId;
18432
+ if (!existsSync4(join4(root, "backify.json"))) throw new Error("Run backify connect --app <application-id>, then backify init.");
18433
+ return JSON.parse(readFileSync4(join4(root, "backify.json"), "utf8")).appId;
18240
18434
  }
18241
18435
  function apiAddress(value) {
18242
18436
  const address = new URL(value);
@@ -18269,13 +18463,13 @@ function apiClient(session, transport = fetch) {
18269
18463
  };
18270
18464
  }
18271
18465
  function saveUserConfig(path, config) {
18272
- const temporary = path + "." + randomUUID() + ".tmp";
18466
+ const temporary = path + "." + randomUUID2() + ".tmp";
18273
18467
  try {
18274
- writeFileSync4(temporary, JSON.stringify(config, null, 2) + "\n", { mode: 384, flag: "wx" });
18468
+ writeFileSync5(temporary, JSON.stringify(config, null, 2) + "\n", { mode: 384, flag: "wx" });
18275
18469
  if (process.platform === "win32") {
18276
18470
  const account = [process.env.USERDOMAIN, process.env.USERNAME].filter(Boolean).join("\\");
18277
18471
  if (!account) throw new Error("Cannot identify the account to protect CLI credentials.");
18278
- const secured = spawnSync2("icacls", [temporary, "/inheritance:r", "/grant:r", account + ":(F)"], { windowsHide: true, encoding: "utf8" });
18472
+ const secured = spawnSync3("icacls", [temporary, "/inheritance:r", "/grant:r", account + ":(F)"], { windowsHide: true, encoding: "utf8" });
18279
18473
  if (secured.status !== 0) throw new Error("Could not restrict CLI credential file permissions.");
18280
18474
  }
18281
18475
  renameSync(temporary, path);
@@ -18289,7 +18483,7 @@ function repositoryName(remote) {
18289
18483
  return match[1].toLowerCase();
18290
18484
  }
18291
18485
  function git(args2, root = process.cwd(), environment = process.env) {
18292
- const result = spawnSync2("git", args2, { cwd: root, env: environment, encoding: "utf8", windowsHide: true, maxBuffer: 2 * 1024 * 1024 });
18486
+ const result = spawnSync3("git", args2, { cwd: root, env: environment, encoding: "utf8", windowsHide: true, maxBuffer: 2 * 1024 * 1024 });
18293
18487
  if (result.status !== 0) throw new Error("Git " + args2[0] + " failed. Check repository access, branch protection, and local changes.");
18294
18488
  return result.stdout.trim();
18295
18489
  }
@@ -18299,7 +18493,7 @@ function gitEnvironment(repository, token) {
18299
18493
  }
18300
18494
  function validateCloneMerge(source, target) {
18301
18495
  for (const entry of readdirSync2(source, { withFileTypes: true })) {
18302
- const destination = join3(target, entry.name);
18496
+ const destination = join4(target, entry.name);
18303
18497
  let existing;
18304
18498
  try {
18305
18499
  existing = lstatSync2(destination);
@@ -18307,7 +18501,7 @@ function validateCloneMerge(source, target) {
18307
18501
  if (reason.code === "ENOENT") continue;
18308
18502
  throw reason;
18309
18503
  }
18310
- if (entry.isDirectory() && existing.isDirectory() && !existing.isSymbolicLink()) validateCloneMerge(join3(source, entry.name), destination);
18504
+ if (entry.isDirectory() && existing.isDirectory() && !existing.isSymbolicLink()) validateCloneMerge(join4(source, entry.name), destination);
18311
18505
  else throw new Error("Clone conflicts with existing workspace entry: " + destination + ". Existing files are never overwritten; reconcile the conflict or use a new folder.");
18312
18506
  }
18313
18507
  }
@@ -18317,22 +18511,22 @@ async function cloneProject(call2, appId, root = process.cwd()) {
18317
18511
  if (readdirSync2(root, { withFileTypes: true }).some((entry) => !isToolWorkspaceEntry(entry, root))) throw new Error("--clone requires an empty directory or a workspace containing only AI tool metadata and default work/outputs directories. Existing application files and Git repositories are never overwritten.");
18318
18512
  const credential = await call2("/apps/" + applicationGuid(appId) + "/developer/git-credential", { method: "POST" });
18319
18513
  if (credential.repository.toLowerCase() !== status.repository.toLowerCase()) throw new Error("Repository changed. Run connect again.");
18320
- const staging = mkdtempSync(join3(dirname4(resolve3(root)), ".backify-clone-"));
18514
+ const staging = mkdtempSync(join4(dirname4(resolve4(root)), ".backify-clone-"));
18321
18515
  try {
18322
18516
  git(["clone", "--single-branch", "--branch", status.branch, "--", "https://github.com/" + status.repository + ".git", "."], staging, gitEnvironment(status.repository, credential.token));
18323
18517
  validateCloneMerge(staging, root);
18324
- for (const entry of readdirSync2(staging)) cpSync(join3(staging, entry), join3(root, entry), { recursive: true, force: false, errorOnExist: true, dereference: false });
18518
+ for (const entry of readdirSync2(staging)) cpSync(join4(staging, entry), join4(root, entry), { recursive: true, force: false, errorOnExist: true, dereference: false });
18325
18519
  } finally {
18326
- if (dirname4(staging) !== dirname4(resolve3(root)) || !staging.startsWith(join3(dirname4(resolve3(root)), ".backify-clone-"))) throw new Error("Refusing to clean up an unexpected clone staging path.");
18520
+ if (dirname4(staging) !== dirname4(resolve4(root)) || !staging.startsWith(join4(dirname4(resolve4(root)), ".backify-clone-"))) throw new Error("Refusing to clean up an unexpected clone staging path.");
18327
18521
  rmSync(staging, { recursive: true, force: true });
18328
18522
  }
18329
18523
  }
18330
18524
  async function pullProject(call2, appId, root = process.cwd()) {
18331
- if (existsSync4(join3(root, "backify.json")) && applicationGuid(projectApplication(root)) !== applicationGuid(appId)) throw new Error("Local application ID does not match the connected application.");
18525
+ if (existsSync4(join4(root, "backify.json")) && applicationGuid(projectApplication(root)) !== applicationGuid(appId)) throw new Error("Local application ID does not match the connected application.");
18332
18526
  const prefix = "/apps/" + applicationGuid(appId);
18333
18527
  const status = await call2(prefix + "/developer");
18334
18528
  if (!status.repository || !status.branch) throw new Error("Connect the repository and branch in Backify before pulling.");
18335
- if (resolve3(git(["rev-parse", "--show-toplevel"], root)) !== resolve3(root)) throw new Error("Run pull from the connected repository root.");
18529
+ if (resolve4(git(["rev-parse", "--show-toplevel"], root)) !== resolve4(root)) throw new Error("Run pull from the connected repository root.");
18336
18530
  if (repositoryName(git(["remote", "get-url", "origin"], root)) !== status.repository.toLowerCase()) throw new Error("Local origin does not match the repository connected in Backify.");
18337
18531
  if (git(["branch", "--show-current"], root) !== status.branch) throw new Error("Local branch does not match the branch connected in Backify. The CLI never switches branches automatically.");
18338
18532
  git(["check-ref-format", "--branch", status.branch], root);
@@ -18372,7 +18566,7 @@ function attachmentNames(values) {
18372
18566
  }))];
18373
18567
  }
18374
18568
  function localReport(runChecks, root = process.cwd()) {
18375
- const pkg = JSON.parse(readFileSync3(join3(root, "package.json"), "utf8"));
18569
+ const pkg = JSON.parse(readFileSync4(join4(root, "package.json"), "utf8"));
18376
18570
  const dependencies = { ...pkg.devDependencies, ...pkg.dependencies };
18377
18571
  const framework = ["next", "vite", "astro", "@sveltejs/kit", "nuxt", "react", "express"].find((name2) => dependencies[name2]) ?? "unknown";
18378
18572
  const setup = doctor(root);
@@ -18380,7 +18574,7 @@ function localReport(runChecks, root = process.cwd()) {
18380
18574
  const manager = detectPackageManager(root);
18381
18575
  for (const name2 of ["typecheck", "lint", "test", "build"]) {
18382
18576
  if (!pkg.scripts?.[name2]) continue;
18383
- const result = runChecks ? spawnSync2(manager, ["run", name2], { cwd: root, stdio: ["ignore", "inherit", "inherit"], env: { ...process.env, CI: "true" }, shell: process.platform === "win32", windowsHide: true, timeout: 10 * 6e4 }) : void 0;
18577
+ const result = runChecks ? spawnSync3(manager, ["run", name2], { cwd: root, stdio: ["ignore", "inherit", "inherit"], env: { ...process.env, CI: "true" }, shell: process.platform === "win32", windowsHide: true, timeout: 10 * 6e4 }) : void 0;
18384
18578
  checks.push({ name: name2, status: result ? result.status === 0 ? "passed" : "failed" : "not-run" });
18385
18579
  }
18386
18580
  let branch = null, commitSha = null, dirty = true;
@@ -18390,8 +18584,8 @@ function localReport(runChecks, root = process.cwd()) {
18390
18584
  dirty = Boolean(git(["status", "--porcelain"], root));
18391
18585
  } catch {
18392
18586
  }
18393
- const outputDirectory = ["dist", "build", "out", "."].find((directory2) => existsSync4(join3(root, directory2, "index.html"))) ?? null;
18394
- return { framework, sdkVersion: dependencies["@backifydev/sdk"] ?? null, branch, commitSha, dirty, buildCommand: pkg.scripts?.build ? manager + " run build" : null, outputDirectory, hasDockerfile: existsSync4(join3(root, "Dockerfile")), checks };
18587
+ const outputDirectory = ["dist", "build", "out", "."].find((directory2) => existsSync4(join4(root, directory2, "index.html"))) ?? null;
18588
+ return { framework, sdkVersion: dependencies["@backifydev/sdk"] ?? null, branch, commitSha, dirty, buildCommand: pkg.scripts?.build ? manager + " run build" : null, outputDirectory, hasDockerfile: existsSync4(join4(root, "Dockerfile")), checks };
18395
18589
  }
18396
18590
  function matchesSource(release2, commit) {
18397
18591
  return release2?.commitSha === commit || release2?.sourceCommitSha === commit;
@@ -18433,7 +18627,7 @@ async function ship(call2, appId, options = {}) {
18433
18627
  if (!doctor(root).valid) throw new Error("Run backify doctor and fix project setup before shipping.");
18434
18628
  if (applicationGuid(projectApplication(root)) !== applicationGuid(appId)) throw new Error("Local application ID does not match the application being shipped.");
18435
18629
  const actualRoot = git(["rev-parse", "--show-toplevel"], root);
18436
- if (resolve3(actualRoot).toLowerCase() !== resolve3(root).toLowerCase()) throw new Error("Shipping currently requires the application at the repository root.");
18630
+ if (resolve4(actualRoot).toLowerCase() !== resolve4(root).toLowerCase()) throw new Error("Shipping currently requires the application at the repository root.");
18437
18631
  const origin = git(["remote", "get-url", "origin"], root);
18438
18632
  const pushOrigin = git(["remote", "get-url", "--push", "origin"], root);
18439
18633
  if (repositoryName(origin) !== status.repository.toLowerCase() || repositoryName(pushOrigin) !== status.repository.toLowerCase()) throw new Error("Local repository does not match this Backify application.");
@@ -18468,7 +18662,7 @@ async function ship(call2, appId, options = {}) {
18468
18662
  async function publishPreview(call2, prefix, overview, options = {}) {
18469
18663
  if (!overview.preview || overview.preview.status !== "succeeded" || overview.preview.healthResult !== "healthy") throw new Error("Only a verified healthy preview can be published.");
18470
18664
  const preview = overview.preview;
18471
- if (options.previewOnly) return { status: "preview-ready", url: preview.url };
18665
+ if (!options.productionDeploy || options.previewOnly) return { status: "preview-ready", url: preview.url };
18472
18666
  if (overview.policy.requirePreviewTesting && !preview.testedAt) return { status: "testing-required", url: preview.url };
18473
18667
  if (overview.live?.previewDeploymentId === preview.id && overview.live.status === "succeeded") return { status: "live", url: overview.live.url };
18474
18668
  const promotion = await call2(prefix + "/deployments/promote", { method: "POST", headers: { "Idempotency-Key": "cli-ship-" + preview.id }, body: JSON.stringify({ previewDeploymentId: preview.id, tested: false }) });
@@ -18501,7 +18695,7 @@ async function browserAuthenticate(options) {
18501
18695
  rejectSession = reject;
18502
18696
  });
18503
18697
  let accepted = false;
18504
- const server = createServer((request, response) => {
18698
+ const server = createServer2((request, response) => {
18505
18699
  if (request.headers.origin !== auth.origin) {
18506
18700
  response.writeHead(403);
18507
18701
  response.end();
@@ -18601,11 +18795,11 @@ function reconnectingApiClient(session, reconnect, transport = fetch) {
18601
18795
  }
18602
18796
 
18603
18797
  // src/local-runtime.ts
18604
- import { createHash as createHash2, randomUUID as randomUUID2 } from "node:crypto";
18605
- import { chmodSync, existsSync as existsSync5, lstatSync as lstatSync3, mkdirSync as mkdirSync3, readFileSync as readFileSync4, readdirSync as readdirSync3, writeFileSync as writeFileSync5 } from "node:fs";
18606
- import { dirname as dirname5, join as join4, resolve as resolve4, sep } from "node:path";
18798
+ import { createHash as createHash2, randomUUID as randomUUID3 } from "node:crypto";
18799
+ import { chmodSync, existsSync as existsSync5, lstatSync as lstatSync3, mkdirSync as mkdirSync3, readFileSync as readFileSync5, readdirSync as readdirSync3, writeFileSync as writeFileSync6 } from "node:fs";
18800
+ import { dirname as dirname5, join as join5, resolve as resolve5, sep } from "node:path";
18607
18801
  import { homedir } from "node:os";
18608
- import { spawnSync as spawnSync3 } from "node:child_process";
18802
+ import { spawnSync as spawnSync4 } from "node:child_process";
18609
18803
 
18610
18804
  // src/local-state.ts
18611
18805
  import { renameSync as renameSync2 } from "node:fs";
@@ -18634,8 +18828,8 @@ function runtimeIdentifier(platform2 = process.platform, architecture = process.
18634
18828
  return system + "-" + architecture;
18635
18829
  }
18636
18830
  function checkedPath(root, filename2) {
18637
- const target = resolve4(root, filename2);
18638
- if (target !== resolve4(root) && !target.startsWith(resolve4(root) + sep)) throw new Error("Runtime path escapes its installation");
18831
+ const target = resolve5(root, filename2);
18832
+ if (target !== resolve5(root) && !target.startsWith(resolve5(root) + sep)) throw new Error("Runtime path escapes its installation");
18639
18833
  let current = target;
18640
18834
  while (true) {
18641
18835
  if (existsSync5(current) && lstatSync3(current).isSymbolicLink()) throw new Error("Runtime installation must not follow links");
@@ -18646,25 +18840,25 @@ function checkedPath(root, filename2) {
18646
18840
  }
18647
18841
  function verifyInstallationFiles(root, expected, directory2 = root) {
18648
18842
  for (const entry of readdirSync3(directory2, { withFileTypes: true })) {
18649
- const path = checkedPath(root, join4(directory2, entry.name));
18843
+ const path = checkedPath(root, join5(directory2, entry.name));
18650
18844
  if (entry.isDirectory()) verifyInstallationFiles(root, expected, path);
18651
18845
  else if (!entry.isFile() || !Object.hasOwn(expected, path.slice(root.length + 1).split(sep).join("/"))) throw new Error("Installed runtime contains unexpected files; reinstall a reviewed version");
18652
18846
  }
18653
18847
  }
18654
- function installedLocalRuntime(base = join4(homedir(), ".backify")) {
18848
+ function installedLocalRuntime(base = join5(homedir(), ".backify")) {
18655
18849
  const pointer = checkedPath(base, "runtime.json");
18656
18850
  if (!existsSync5(pointer)) return void 0;
18657
- const installed = JSON.parse(readFileSync4(pointer, "utf8"));
18851
+ const installed = JSON.parse(readFileSync5(pointer, "utf8"));
18658
18852
  if (!/^v[0-9]+\.[0-9]+\.[0-9]+$/.test(installed.version) || installed.rid !== runtimeIdentifier() || !installed.files || Object.keys(installed.files).length > 3e3) throw new Error("Invalid local runtime installation receipt");
18659
- const root = checkedPath(base, join4("runtimes", installed.version, installed.rid));
18853
+ const root = checkedPath(base, join5("runtimes", installed.version, installed.rid));
18660
18854
  verifyInstallationFiles(root, installed.files);
18661
18855
  for (const [filename2, digest4] of Object.entries(installed.files)) {
18662
18856
  const path = checkedPath(root, filename2);
18663
- if (!/^[a-f0-9]{64}$/.test(digest4) || !lstatSync3(path).isFile() || lstatSync3(path).size > maxArchiveBytes || hash(readFileSync4(path)) !== digest4) throw new Error("Installed runtime bytes changed; reinstall a reviewed version");
18857
+ if (!/^[a-f0-9]{64}$/.test(digest4) || !lstatSync3(path).isFile() || lstatSync3(path).size > maxArchiveBytes || hash(readFileSync5(path)) !== digest4) throw new Error("Installed runtime bytes changed; reinstall a reviewed version");
18664
18858
  }
18665
18859
  const executableName = installed.rid.startsWith("win-") ? "Backify.Hcr.exe" : "Backify.Hcr";
18666
18860
  if (!installed.files["Backify.Hcr.dll"] || !installed.files[executableName]) throw new Error("Runtime archive requires the self-contained HCR executable and DLL");
18667
- return { path: join4(root, "Backify.Hcr.dll"), executable: join4(root, executableName), version: installed.version, rid: installed.rid };
18861
+ return { path: join5(root, "Backify.Hcr.dll"), executable: join5(root, executableName), version: installed.version, rid: installed.rid };
18668
18862
  }
18669
18863
  function installLocalRuntime(archive, options) {
18670
18864
  if (!/^v[0-9]+\.[0-9]+\.[0-9]+$/.test(options.version) || !/^[a-f0-9]{64}$/.test(options.sha256)) throw new Error("Provide a release version vX.Y.Z and an independently reviewed SHA-256");
@@ -18678,28 +18872,28 @@ function installLocalRuntime(archive, options) {
18678
18872
  const rid = runtimeIdentifier();
18679
18873
  const executable = rid.startsWith("win-") ? "Backify.Hcr.exe" : "Backify.Hcr";
18680
18874
  if (!files["Backify.Hcr.dll"] || !files[executable] || !files["sql/events-v1.sql"] || !files["sql/jobs-v1.sql"]) throw new Error("Runtime archive is missing required host assets");
18681
- const base = options.base ?? join4(homedir(), ".backify");
18682
- const parent = checkedPath(base, join4("runtimes", options.version));
18875
+ const base = options.base ?? join5(homedir(), ".backify");
18876
+ const parent = checkedPath(base, join5("runtimes", options.version));
18683
18877
  mkdirSync3(parent, { recursive: true, mode: 448 });
18684
18878
  const destination = checkedPath(parent, rid);
18685
18879
  const receipt = { version: options.version, rid, files: Object.fromEntries(Object.entries(files).map(([name2, bytes]) => [name2, hash(bytes)])) };
18686
18880
  if (!existsSync5(destination)) {
18687
- const staging = checkedPath(parent, ".install-" + randomUUID2());
18881
+ const staging = checkedPath(parent, ".install-" + randomUUID3());
18688
18882
  mkdirSync3(staging, { mode: 448 });
18689
18883
  for (const [name2, bytes] of Object.entries(files)) {
18690
18884
  const filename2 = checkedPath(staging, name2);
18691
18885
  mkdirSync3(dirname5(filename2), { recursive: true, mode: 448 });
18692
- writeFileSync5(filename2, bytes, { flag: "wx", mode: name2 === executable ? 448 : 384 });
18886
+ writeFileSync6(filename2, bytes, { flag: "wx", mode: name2 === executable ? 448 : 384 });
18693
18887
  }
18694
- if (process.platform !== "win32") chmodSync(join4(staging, executable), 448);
18888
+ if (process.platform !== "win32") chmodSync(join5(staging, executable), 448);
18695
18889
  renameLocalFile(staging, destination);
18696
18890
  } else {
18697
18891
  verifyInstallationFiles(destination, receipt.files);
18698
- for (const [name2, digest4] of Object.entries(receipt.files)) if (hash(readFileSync4(checkedPath(destination, name2))) !== digest4) throw new Error("Runtime version already exists with different bytes; never overwrite an installation");
18892
+ for (const [name2, digest4] of Object.entries(receipt.files)) if (hash(readFileSync5(checkedPath(destination, name2))) !== digest4) throw new Error("Runtime version already exists with different bytes; never overwrite an installation");
18699
18893
  }
18700
18894
  const pointer = checkedPath(base, "runtime.json");
18701
- const temporary = checkedPath(base, ".runtime-" + randomUUID2() + ".json");
18702
- writeFileSync5(temporary, JSON.stringify(receipt), { flag: "wx", mode: 384 });
18895
+ const temporary = checkedPath(base, ".runtime-" + randomUUID3() + ".json");
18896
+ writeFileSync6(temporary, JSON.stringify(receipt), { flag: "wx", mode: 384 });
18703
18897
  renameLocalFile(temporary, pointer);
18704
18898
  return installedLocalRuntime(base);
18705
18899
  }
@@ -18727,10 +18921,10 @@ async function downloadLocalRuntime(version) {
18727
18921
  }
18728
18922
  function localPrerequisites() {
18729
18923
  const runtime = installedLocalRuntime();
18730
- const directory2 = process.env.BACKIFY_LOCAL_POSTGRES_BIN ?? (process.platform === "win32" ? join4(process.env.ProgramFiles ?? "C:/Program Files", "PostgreSQL", "17", "bin") : void 0);
18924
+ const directory2 = process.env.BACKIFY_LOCAL_POSTGRES_BIN ?? (process.platform === "win32" ? join5(process.env.ProgramFiles ?? "C:/Program Files", "PostgreSQL", "17", "bin") : void 0);
18731
18925
  const checks = ["initdb", "pg_ctl", "psql"].map((name2) => {
18732
- const executable = directory2 ? join4(directory2, name2 + (process.platform === "win32" ? ".exe" : "")) : name2;
18733
- const result = spawnSync3(executable, ["--version"], { windowsHide: true, timeout: 1e4, encoding: "utf8" });
18926
+ const executable = directory2 ? join5(directory2, name2 + (process.platform === "win32" ? ".exe" : "")) : name2;
18927
+ const result = spawnSync4(executable, ["--version"], { windowsHide: true, timeout: 1e4, encoding: "utf8" });
18734
18928
  return { name: name2, available: result.status === 0 };
18735
18929
  });
18736
18930
  return { rid: runtimeIdentifier(), runtime: runtime ? { installed: true, version: runtime.version } : { installed: false }, postgres: checks, ready: !!runtime && checks.every((check) => check.available) };
@@ -18739,20 +18933,20 @@ function localPrerequisites() {
18739
18933
  // src/workload.ts
18740
18934
  import { build as build2 } from "esbuild";
18741
18935
  import { createHash as createHash14 } from "node:crypto";
18742
- import { existsSync as existsSync12, mkdirSync as mkdirSync7, readFileSync as readFileSync19, realpathSync as realpathSync6, readdirSync as readdirSync6, writeFileSync as writeFileSync11 } from "node:fs";
18743
- import { dirname as dirname13, isAbsolute as isAbsolute14, join as join13, relative as relative8, resolve as resolve18 } from "node:path";
18936
+ import { existsSync as existsSync12, mkdirSync as mkdirSync7, readFileSync as readFileSync20, realpathSync as realpathSync6, readdirSync as readdirSync6, writeFileSync as writeFileSync12 } from "node:fs";
18937
+ import { dirname as dirname13, isAbsolute as isAbsolute14, join as join14, relative as relative8, resolve as resolve19 } from "node:path";
18744
18938
 
18745
18939
  // src/local-development.ts
18746
18940
  import { context as context2 } from "esbuild";
18747
18941
  import { spawn as spawn4 } from "node:child_process";
18748
- import { randomBytes as randomBytes6, randomUUID as randomUUID9, createHash as createHash13 } from "node:crypto";
18749
- import { existsSync as existsSync11, lstatSync as lstatSync15, mkdirSync as mkdirSync6, readFileSync as readFileSync18, realpathSync as realpathSync5, writeFileSync as writeFileSync10, unlinkSync as unlinkSync4 } from "node:fs";
18750
- import { resolve as resolve17, join as join12, relative as relative7, isAbsolute as isAbsolute13, dirname as dirname12 } from "node:path";
18942
+ import { randomBytes as randomBytes6, randomUUID as randomUUID10, createHash as createHash13 } from "node:crypto";
18943
+ import { existsSync as existsSync11, lstatSync as lstatSync15, mkdirSync as mkdirSync6, readFileSync as readFileSync19, realpathSync as realpathSync5, writeFileSync as writeFileSync11, unlinkSync as unlinkSync5 } from "node:fs";
18944
+ import { resolve as resolve18, join as join13, relative as relative7, isAbsolute as isAbsolute13, dirname as dirname12 } from "node:path";
18751
18945
 
18752
18946
  // ../analyzer/dist/index.js
18753
- import ts2 from "typescript";
18754
- import { readFileSync as readFileSync5, readdirSync as readdirSync4, existsSync as existsSync6 } from "node:fs";
18755
- import { join as join5, extname } from "node:path";
18947
+ import ts3 from "typescript";
18948
+ import { readFileSync as readFileSync6, readdirSync as readdirSync4, existsSync as existsSync6 } from "node:fs";
18949
+ import { join as join6, extname } from "node:path";
18756
18950
 
18757
18951
  // ../analyzer/dist/authentication.js
18758
18952
  import ts from "typescript";
@@ -18867,6 +19061,191 @@ function analyzeAuthentication(files) {
18867
19061
  return { used, providers: [...providers].sort(), dynamicFiles: [...dynamicFiles].sort() };
18868
19062
  }
18869
19063
 
19064
+ // ../analyzer/dist/schedules.js
19065
+ import ts2 from "typescript";
19066
+ var dynamic = Symbol("dynamic");
19067
+ function literal(node) {
19068
+ if (!node)
19069
+ return void 0;
19070
+ if (ts2.isStringLiteral(node) || ts2.isNoSubstitutionTemplateLiteral(node))
19071
+ return node.text;
19072
+ if (ts2.isNumericLiteral(node))
19073
+ return Number(node.text);
19074
+ if (ts2.isPrefixUnaryExpression(node) && node.operator === ts2.SyntaxKind.MinusToken && ts2.isNumericLiteral(node.operand))
19075
+ return -Number(node.operand.text);
19076
+ if (node.kind === ts2.SyntaxKind.TrueKeyword)
19077
+ return true;
19078
+ if (node.kind === ts2.SyntaxKind.FalseKeyword)
19079
+ return false;
19080
+ if (node.kind === ts2.SyntaxKind.NullKeyword)
19081
+ return null;
19082
+ if (ts2.isParenthesizedExpression(node) || ts2.isAsExpression(node) || ts2.isSatisfiesExpression(node))
19083
+ return literal(node.expression);
19084
+ if (ts2.isArrayLiteralExpression(node)) {
19085
+ const values = node.elements.map((item) => literal(item));
19086
+ return values.includes(dynamic) ? dynamic : values;
19087
+ }
19088
+ if (ts2.isObjectLiteralExpression(node)) {
19089
+ const result = {};
19090
+ for (const property of node.properties) {
19091
+ if (!ts2.isPropertyAssignment(property) || !ts2.isIdentifier(property.name) && !ts2.isStringLiteral(property.name))
19092
+ return dynamic;
19093
+ const value = literal(property.initializer);
19094
+ if (value === dynamic)
19095
+ return dynamic;
19096
+ Object.defineProperty(result, property.name.text, { value, enumerable: true });
19097
+ }
19098
+ return result;
19099
+ }
19100
+ return dynamic;
19101
+ }
19102
+ function analyzeSchedules(files) {
19103
+ const schedules = [], diagnostics = [];
19104
+ for (const file of files) {
19105
+ const sourcePath = file.path.replaceAll(String.fromCharCode(92), "/");
19106
+ if (/(^|\/)(tests?|__tests__|fixtures)\/|\.(test|spec)\.[cm]?[jt]sx?$/.test(sourcePath))
19107
+ continue;
19108
+ const source = ts2.createSourceFile(sourcePath, file.content, ts2.ScriptTarget.Latest, true, file.path.endsWith("x") ? ts2.ScriptKind.TSX : ts2.ScriptKind.TS);
19109
+ const program = ts2.createProgram([sourcePath], { noLib: true, noResolve: true, allowJs: true }, {
19110
+ getSourceFile: (path) => path === sourcePath ? source : void 0,
19111
+ getDefaultLibFileName: () => "",
19112
+ writeFile: () => {
19113
+ },
19114
+ getCurrentDirectory: () => "/",
19115
+ getDirectories: () => [],
19116
+ fileExists: (path) => path === sourcePath,
19117
+ readFile: (path) => path === sourcePath ? file.content : void 0,
19118
+ getCanonicalFileName: (path) => path,
19119
+ useCaseSensitiveFileNames: () => true,
19120
+ getNewLine: () => "\n"
19121
+ });
19122
+ const checker = program.getTypeChecker();
19123
+ const jobSymbols = /* @__PURE__ */ new Set(), scheduleSymbols = /* @__PURE__ */ new Set(), roots = /* @__PURE__ */ new Set(), namespaces = /* @__PURE__ */ new Set(), factories = /* @__PURE__ */ new Set();
19124
+ const has = (symbols, node) => {
19125
+ const symbol = checker.getSymbolAtLocation(node);
19126
+ return !!symbol && symbols.has(symbol);
19127
+ };
19128
+ const add = (symbols, node) => {
19129
+ const symbol = checker.getSymbolAtLocation(node);
19130
+ if (symbol)
19131
+ symbols.add(symbol);
19132
+ };
19133
+ for (const statement of source.statements) {
19134
+ if (!ts2.isImportDeclaration(statement) || !ts2.isStringLiteral(statement.moduleSpecifier) || !["@backifydev/sdk", "@backifydev/sdk/server"].includes(statement.moduleSpecifier.text) || statement.importClause?.isTypeOnly)
19135
+ continue;
19136
+ const bindings = statement.importClause?.namedBindings;
19137
+ if (bindings && ts2.isNamespaceImport(bindings))
19138
+ add(namespaces, bindings.name);
19139
+ if (bindings && ts2.isNamedImports(bindings))
19140
+ for (const binding of bindings.elements) {
19141
+ if (binding.isTypeOnly)
19142
+ continue;
19143
+ const name2 = (binding.propertyName ?? binding.name).text;
19144
+ if (name2 === "jobs")
19145
+ add(jobSymbols, binding.name);
19146
+ if (name2 === "backify")
19147
+ add(roots, binding.name);
19148
+ if (name2 === "createServerClient")
19149
+ add(factories, binding.name);
19150
+ }
19151
+ }
19152
+ const isNamespace = (node) => ts2.isIdentifier(node) && has(namespaces, node);
19153
+ const isRoot = (node) => ts2.isIdentifier(node) && has(roots, node) || ts2.isPropertyAccessExpression(node) && node.name.text === "backify" && isNamespace(node.expression) || ts2.isCallExpression(node) && (ts2.isIdentifier(node.expression) && has(factories, node.expression) || ts2.isPropertyAccessExpression(node.expression) && node.expression.name.text === "createServerClient" && isNamespace(node.expression.expression));
19154
+ const isJobs = (node) => ts2.isIdentifier(node) && has(jobSymbols, node) || ts2.isPropertyAccessExpression(node) && node.name.text === "jobs" && (isRoot(node.expression) || isNamespace(node.expression));
19155
+ const collect = (node) => {
19156
+ if (ts2.isVariableDeclaration(node) && node.initializer) {
19157
+ if (ts2.isIdentifier(node.name)) {
19158
+ if (isRoot(node.initializer))
19159
+ add(roots, node.name);
19160
+ if (isJobs(node.initializer))
19161
+ add(jobSymbols, node.name);
19162
+ if (ts2.isPropertyAccessExpression(node.initializer) && node.initializer.name.text === "schedule" && isJobs(node.initializer.expression) || ts2.isIdentifier(node.initializer) && has(scheduleSymbols, node.initializer))
19163
+ add(scheduleSymbols, node.name);
19164
+ } else if (ts2.isObjectBindingPattern(node.name)) {
19165
+ for (const binding of node.name.elements) {
19166
+ if (!ts2.isIdentifier(binding.name) || binding.dotDotDotToken || binding.initializer)
19167
+ continue;
19168
+ const propertyName = binding.propertyName ?? binding.name;
19169
+ if (!ts2.isIdentifier(propertyName) && !ts2.isStringLiteral(propertyName))
19170
+ continue;
19171
+ if (propertyName.text === "jobs" && (isRoot(node.initializer) || isNamespace(node.initializer)))
19172
+ add(jobSymbols, binding.name);
19173
+ if (propertyName.text === "schedule" && isJobs(node.initializer))
19174
+ add(scheduleSymbols, binding.name);
19175
+ if (propertyName.text === "backify" && isNamespace(node.initializer))
19176
+ add(roots, binding.name);
19177
+ if (propertyName.text === "createServerClient" && isNamespace(node.initializer))
19178
+ add(factories, binding.name);
19179
+ }
19180
+ }
19181
+ }
19182
+ ts2.forEachChild(node, collect);
19183
+ };
19184
+ let previousSize = -1;
19185
+ while (previousSize !== jobSymbols.size + scheduleSymbols.size + roots.size + factories.size) {
19186
+ previousSize = jobSymbols.size + scheduleSymbols.size + roots.size + factories.size;
19187
+ collect(source);
19188
+ }
19189
+ const report = (code, message, severity = "warning") => diagnostics.push({ code, message, severity, file: file.path, docs: "https://docs.backify.dev/capabilities/scheduler" });
19190
+ const property = (node, name2) => node.properties.find((item) => ts2.isPropertyAssignment(item) && (ts2.isIdentifier(item.name) || ts2.isStringLiteral(item.name)) && item.name.text === name2);
19191
+ const visit = (node) => {
19192
+ if (ts2.isCallExpression(node) && ts2.isPropertyAccessExpression(node.expression)) {
19193
+ const method = node.expression.name.text, receiver = node.expression.expression;
19194
+ let name2, definition;
19195
+ if (method === "define" && isJobs(receiver) && node.arguments[0] && ts2.isObjectLiteralExpression(node.arguments[0])) {
19196
+ const schedule = property(node.arguments[0], "schedule");
19197
+ if (schedule) {
19198
+ name2 = literal(property(node.arguments[0], "name")?.initializer);
19199
+ definition = node.arguments[0].properties.some((item) => ts2.isSpreadAssignment(item) || item.name && ts2.isComputedPropertyName(item.name)) ? dynamic : literal(schedule.initializer);
19200
+ } else if (node.arguments[0].properties.some((item) => ts2.isShorthandPropertyAssignment(item) && item.name.text === "schedule")) {
19201
+ definition = dynamic;
19202
+ }
19203
+ } else if ((ts2.isPropertyAccessExpression(receiver) && receiver.name.text === "schedule" && isJobs(receiver.expression) || ts2.isIdentifier(receiver) && has(scheduleSymbols, receiver)) && ["daily", "weekly", "hourly", "cron", "once", "interval"].includes(method)) {
19204
+ name2 = literal(node.arguments[0]);
19205
+ definition = { kind: method, ...method === "weekly" ? { day: literal(node.arguments[2]) ?? "monday", at: literal(node.arguments[3]) ?? "00:00", timeZone: literal(node.arguments[4]) ?? "UTC" } : method === "interval" ? { intervalSeconds: literal(node.arguments[2]) } : method === "cron" ? { expression: literal(node.arguments[2]), timeZone: literal(node.arguments[3]) ?? "UTC" } : { at: literal(node.arguments[2]), timeZone: literal(node.arguments[3]) ?? "UTC" } };
19206
+ }
19207
+ if (definition !== void 0) {
19208
+ if (typeof name2 !== "string" || !definition || typeof definition !== "object" || Object.values(definition).includes(dynamic))
19209
+ report("dynamic-schedule", "Use literal schedule declarations for automatic deployment provisioning, or jobs.schedule.sync() in a trusted server setup step for dynamic declarations.");
19210
+ else {
19211
+ const settings = definition, kind = settings.kind;
19212
+ const schedule = { name: name2, job: name2, kind: String(kind), timeZone: String(settings.timeZone ?? "UTC"), ...settings.payload !== void 0 ? { payload: settings.payload } : {} };
19213
+ if (["daily", "weekly", "hourly"].includes(String(kind))) {
19214
+ const time = settings.at ?? "00:00", day = ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"].indexOf(String(settings.day ?? "monday").toLowerCase());
19215
+ if (typeof time !== "string" || !/^([01]\d|2[0-3]):[0-5]\d$/.test(time) || kind === "weekly" && day < 0)
19216
+ report("invalid-schedule", "Use HH:mm and a valid weekday for scheduled jobs.", "error");
19217
+ else {
19218
+ const [hour, minute] = time.split(":").map(Number);
19219
+ schedule.kind = "cron";
19220
+ schedule.expression = kind === "hourly" ? "0 * * * *" : minute + " " + hour + " * * " + (kind === "weekly" ? day : "*");
19221
+ schedules.push(schedule);
19222
+ }
19223
+ } else if (kind === "cron" || kind === "once" || kind === "interval") {
19224
+ if (kind === "cron")
19225
+ schedule.expression = settings.expression;
19226
+ if (kind === "once")
19227
+ schedule.at = settings.at;
19228
+ if (kind === "interval")
19229
+ schedule.intervalSeconds = settings.intervalSeconds;
19230
+ schedules.push(schedule);
19231
+ } else
19232
+ report("invalid-schedule", "Unknown schedule declaration kind.", "error");
19233
+ }
19234
+ }
19235
+ }
19236
+ ts2.forEachChild(node, visit);
19237
+ };
19238
+ visit(source);
19239
+ }
19240
+ const unique = /* @__PURE__ */ new Map();
19241
+ for (const schedule of schedules) {
19242
+ if (unique.has(schedule.name) && JSON.stringify(unique.get(schedule.name)) !== JSON.stringify(schedule))
19243
+ diagnostics.push({ severity: "error", code: "duplicate-schedule", message: "Conflicting schedule declarations: " + schedule.name, docs: "https://docs.backify.dev/capabilities/scheduler" });
19244
+ unique.set(schedule.name, schedule);
19245
+ }
19246
+ return { schedules: [...unique.values()], diagnostics };
19247
+ }
19248
+
18870
19249
  // ../analyzer/dist/index.js
18871
19250
  var bypass = { "@azure/storage-blob": { capability: "storage", replacement: "storage" }, "@aws-sdk/client-s3": { capability: "storage", replacement: "storage" }, "firebase-admin": { capability: "database", replacement: "db" }, "@supabase/supabase-js": { capability: "database", replacement: "db" }, "@azure/service-bus": { capability: "jobs", replacement: "jobs" } };
18872
19251
  function analyzeSources(files, options = {}) {
@@ -18875,7 +19254,17 @@ function analyzeSources(files, options = {}) {
18875
19254
  analyzeFile(file, used, diagnostics);
18876
19255
  if (used.has("http"))
18877
19256
  used.add("events");
19257
+ if (used.has("integrations")) {
19258
+ used.add("events");
19259
+ used.add("secrets");
19260
+ }
18878
19261
  const authentication = analyzeAuthentication(files);
19262
+ const scheduling = analyzeSchedules(files);
19263
+ if (scheduling.schedules.length || scheduling.diagnostics.length) {
19264
+ used.add("jobs");
19265
+ used.add("scheduler");
19266
+ }
19267
+ diagnostics.push(...scheduling.diagnostics);
18879
19268
  if (authentication.used)
18880
19269
  used.add("auth");
18881
19270
  else
@@ -18883,6 +19272,8 @@ function analyzeSources(files, options = {}) {
18883
19272
  const capabilities = Object.fromEntries([...used].sort().map((name2) => [name2, { version: CAPABILITY_REGISTRY[name2].version }]));
18884
19273
  if (capabilities.auth && (authentication.providers.length || authentication.dynamicFiles.length))
18885
19274
  capabilities.auth.configuration = { providers: authentication.providers, dynamicProviders: authentication.dynamicFiles.length > 0 };
19275
+ if (capabilities.scheduler && scheduling.schedules.length)
19276
+ capabilities.scheduler.configuration = { schedules: scheduling.schedules };
18886
19277
  for (const file of authentication.dynamicFiles)
18887
19278
  diagnostics.push({ severity: "warning", code: "dynamic-auth-provider", file, docs: CAPABILITY_REGISTRY.auth.docs, message: "Declare every possible authentication provider in backify.yaml; dynamic provider selection cannot be provisioned from source alone." });
18888
19279
  for (const provider of authentication.providers)
@@ -18891,9 +19282,9 @@ function analyzeSources(files, options = {}) {
18891
19282
  return { schemaVersion: 1, applicationId: options.applicationId ?? "unknown", commit: options.commit ?? "unknown", sdkVersion: options.sdkVersion ?? "unknown", capabilities, diagnostics };
18892
19283
  }
18893
19284
  function analyzeFile(file, used, diagnostics) {
18894
- const source = ts2.createSourceFile(file.path, file.content, ts2.ScriptTarget.Latest, true, file.path.endsWith("x") ? ts2.ScriptKind.TSX : ts2.ScriptKind.TS), named = /* @__PURE__ */ new Map(), namespaces = /* @__PURE__ */ new Set(), roots = /* @__PURE__ */ new Set(), factories = /* @__PURE__ */ new Set();
19285
+ const source = ts3.createSourceFile(file.path, file.content, ts3.ScriptTarget.Latest, true, file.path.endsWith("x") ? ts3.ScriptKind.TSX : ts3.ScriptKind.TS), named = /* @__PURE__ */ new Map(), namespaces = /* @__PURE__ */ new Set(), roots = /* @__PURE__ */ new Set(), factories = /* @__PURE__ */ new Set();
18895
19286
  source.forEachChild((node) => {
18896
- if (!ts2.isImportDeclaration(node) || !ts2.isStringLiteral(node.moduleSpecifier))
19287
+ if (!ts3.isImportDeclaration(node) || !ts3.isStringLiteral(node.moduleSpecifier))
18897
19288
  return;
18898
19289
  const module = node.moduleSpecifier.text;
18899
19290
  if (bypass[module]) {
@@ -18905,9 +19296,9 @@ function analyzeFile(file, used, diagnostics) {
18905
19296
  const bindings = node.importClause.namedBindings;
18906
19297
  if (!bindings)
18907
19298
  return;
18908
- if (ts2.isNamespaceImport(bindings))
19299
+ if (ts3.isNamespaceImport(bindings))
18909
19300
  namespaces.add(bindings.name.text);
18910
- else if (ts2.isNamedImports(bindings))
19301
+ else if (ts3.isNamedImports(bindings))
18911
19302
  for (const element of bindings.elements) {
18912
19303
  const imported = (element.propertyName ?? element.name).text, local = element.name.text;
18913
19304
  if (imported === "createServerClient")
@@ -18922,17 +19313,19 @@ function analyzeFile(file, used, diagnostics) {
18922
19313
  }
18923
19314
  });
18924
19315
  const visit = (node) => {
18925
- if (ts2.isVariableDeclaration(node) && ts2.isIdentifier(node.name) && node.initializer && ts2.isCallExpression(node.initializer) && ts2.isIdentifier(node.initializer.expression) && factories.has(node.initializer.expression.text))
19316
+ if (ts3.isCallExpression(node) && ts3.isPropertyAccessExpression(node.expression) && ["createWebhook", "create"].includes(node.expression.name.text) && rootCapability(node.expression.expression, named, namespaces, roots) === "events")
19317
+ used.add("functions");
19318
+ if (ts3.isVariableDeclaration(node) && ts3.isIdentifier(node.name) && node.initializer && ts3.isCallExpression(node.initializer) && ts3.isIdentifier(node.initializer.expression) && factories.has(node.initializer.expression.text))
18926
19319
  roots.add(node.name.text);
18927
- if (ts2.isCallExpression(node) && ts2.isIdentifier(node.expression) && named.get(node.expression.text) === "jobs" && node.arguments.some((argument) => ts2.isObjectLiteralExpression(argument) && argument.properties.some((property) => ts2.isPropertyAssignment(property) && property.name.getText(source) === "schedule")))
19320
+ if (ts3.isCallExpression(node) && ts3.isIdentifier(node.expression) && named.get(node.expression.text) === "jobs" && node.arguments.some((argument) => ts3.isObjectLiteralExpression(argument) && argument.properties.some((property) => ts3.isPropertyAssignment(property) && property.name.getText(source) === "schedule")))
18928
19321
  used.add("scheduler");
18929
- if (ts2.isIdentifier(node)) {
19322
+ if (ts3.isIdentifier(node)) {
18930
19323
  const parent = node.parent;
18931
- if (named.has(node.text) && !ts2.isImportSpecifier(parent) && isValueUse(node))
19324
+ if (named.has(node.text) && !ts3.isImportSpecifier(parent) && isValueUse(node))
18932
19325
  used.add(named.get(node.text));
18933
19326
  }
18934
- if (ts2.isPropertyAccessExpression(node)) {
18935
- if (ts2.isIdentifier(node.expression)) {
19327
+ if (ts3.isPropertyAccessExpression(node)) {
19328
+ if (ts3.isIdentifier(node.expression)) {
18936
19329
  if (namespaces.has(node.expression.text)) {
18937
19330
  const cap = SDK_IMPORT_CAPABILITIES[node.name.text];
18938
19331
  if (cap)
@@ -18947,18 +19340,18 @@ function analyzeFile(file, used, diagnostics) {
18947
19340
  if (node.name.text === "schedule" && rootCapability(node.expression, named, namespaces, roots) === "jobs")
18948
19341
  used.add("scheduler");
18949
19342
  }
18950
- ts2.forEachChild(node, visit);
19343
+ ts3.forEachChild(node, visit);
18951
19344
  };
18952
19345
  visit(source);
18953
19346
  }
18954
19347
  function isValueUse(node) {
18955
19348
  const p = node.parent;
18956
- return !(ts2.isImportSpecifier(p) || ts2.isExportSpecifier(p) || ts2.isTypeReferenceNode(p) || ts2.isTypeQueryNode(p));
19349
+ return !(ts3.isImportSpecifier(p) || ts3.isExportSpecifier(p) || ts3.isTypeReferenceNode(p) || ts3.isTypeQueryNode(p));
18957
19350
  }
18958
19351
  function rootCapability(node, named, namespaces, roots) {
18959
- if (ts2.isIdentifier(node))
19352
+ if (ts3.isIdentifier(node))
18960
19353
  return named.get(node.text);
18961
- if (ts2.isPropertyAccessExpression(node) && ts2.isIdentifier(node.expression)) {
19354
+ if (ts3.isPropertyAccessExpression(node) && ts3.isIdentifier(node.expression)) {
18962
19355
  if (namespaces.has(node.expression.text) || roots.has(node.expression.text))
18963
19356
  return SDK_IMPORT_CAPABILITIES[node.name.text];
18964
19357
  }
@@ -18970,11 +19363,11 @@ function repositorySources(root) {
18970
19363
  for (const entry of readdirSync4(dir, { withFileTypes: true })) {
18971
19364
  if (entry.name === "node_modules" || entry.name === "dist" || entry.name === ".backify" || entry.name.startsWith(".git"))
18972
19365
  continue;
18973
- const path = join5(dir, entry.name);
19366
+ const path = join6(dir, entry.name);
18974
19367
  if (entry.isDirectory())
18975
19368
  walk(path);
18976
19369
  else if ([".ts", ".tsx", ".js", ".jsx", ".mts", ".mjs"].includes(extname(path)))
18977
- result.push({ path, content: readFileSync5(path, "utf8") });
19370
+ result.push({ path, content: readFileSync6(path, "utf8") });
18978
19371
  }
18979
19372
  };
18980
19373
  if (existsSync6(root))
@@ -19138,6 +19531,10 @@ function createLocalNativeEvents(local, native) {
19138
19531
  if (typeof name2 !== "string" || !/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/.test(name2) || /[\r\n]/.test(name2)) throw new Error("Invalid event name");
19139
19532
  };
19140
19533
  return {
19534
+ track: (name2, data, options) => {
19535
+ if (!local.track) throw new Error("Upgrade the local SDK to enable event tracking");
19536
+ return local.track(name2, data, options);
19537
+ },
19141
19538
  async emit(name2, payload, options) {
19142
19539
  validateName2(name2);
19143
19540
  if (options?.idempotencyKey !== void 0 && (typeof options.idempotencyKey !== "string" || !options.idempotencyKey || options.idempotencyKey.length > 128)) throw new Error("Invalid idempotency key");
@@ -19187,8 +19584,8 @@ function createLocalNativeEvents(local, native) {
19187
19584
  // src/local-job-executor.ts
19188
19585
  import { spawn as spawn2 } from "node:child_process";
19189
19586
  import { createHash as createHash10 } from "node:crypto";
19190
- import { lstatSync as lstatSync11, readFileSync as readFileSync12 } from "node:fs";
19191
- import { isAbsolute as isAbsolute8, join as join8, relative as relative3, resolve as resolve11 } from "node:path";
19587
+ import { lstatSync as lstatSync11, readFileSync as readFileSync13 } from "node:fs";
19588
+ import { isAbsolute as isAbsolute8, join as join9, relative as relative3, resolve as resolve12 } from "node:path";
19192
19589
 
19193
19590
  // ../sdk/dist/schedules.js
19194
19591
  var import_cron_parser = __toESM(require_dist2(), 1);
@@ -19399,14 +19796,14 @@ function createApplicationAuthProvider(source, options) {
19399
19796
  }
19400
19797
 
19401
19798
  // ../sdk/dist/application-auth-state.js
19402
- import { createHash as createHash3, randomUUID as randomUUID3 } from "node:crypto";
19403
- import { closeSync, constants, fstatSync, fsyncSync, lstatSync as lstatSync4, openSync, readSync, renameSync as renameSync3, unlinkSync, writeFileSync as writeFileSync6 } from "node:fs";
19404
- import { dirname as dirname6, isAbsolute as isAbsolute2, parse, resolve as resolve5, sep as sep2 } from "node:path";
19799
+ import { createHash as createHash3, randomUUID as randomUUID4 } from "node:crypto";
19800
+ import { closeSync, constants, fstatSync, fsyncSync, lstatSync as lstatSync4, openSync, readSync, renameSync as renameSync3, unlinkSync as unlinkSync2, writeFileSync as writeFileSync7 } from "node:fs";
19801
+ import { dirname as dirname6, isAbsolute as isAbsolute2, parse, resolve as resolve6, sep as sep2 } from "node:path";
19405
19802
  function unavailable2() {
19406
19803
  throw new ApplicationAuthenticationError("application_identity_unavailable");
19407
19804
  }
19408
19805
  function safePath(filename2) {
19409
- if (!isAbsolute2(filename2) || resolve5(filename2) !== filename2 || filename2 === parse(filename2).root)
19806
+ if (!isAbsolute2(filename2) || resolve6(filename2) !== filename2 || filename2 === parse(filename2).root)
19410
19807
  unavailable2();
19411
19808
  if (process.platform === "win32" && filename2.slice(parse(filename2).root.length).split(sep2).some((component) => component.includes(":") || /[. ]$/.test(component) || /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(component)))
19412
19809
  unavailable2();
@@ -19472,10 +19869,10 @@ function readState(filename2) {
19472
19869
  }
19473
19870
  }
19474
19871
  function persist(filename2, state) {
19475
- const temporary = filename2 + "." + randomUUID3() + ".tmp";
19872
+ const temporary = filename2 + "." + randomUUID4() + ".tmp";
19476
19873
  const descriptor2 = openSync(temporary, "wx", 384);
19477
19874
  try {
19478
- writeFileSync6(descriptor2, JSON.stringify(state));
19875
+ writeFileSync7(descriptor2, JSON.stringify(state));
19479
19876
  fsyncSync(descriptor2);
19480
19877
  } finally {
19481
19878
  closeSync(descriptor2);
@@ -19487,7 +19884,7 @@ function checkpoint(filename2, trust, initialize2) {
19487
19884
  try {
19488
19885
  if (!isAbsolute2(filename2))
19489
19886
  unavailable2();
19490
- filename2 = resolve5(filename2);
19887
+ filename2 = resolve6(filename2);
19491
19888
  safePath(filename2);
19492
19889
  const lock = filename2 + ".lock";
19493
19890
  const next = { version: 1, scope: trust.scope, revision: trust.revision, digest: createHash3("sha256").update(trust.content).digest("hex") };
@@ -19506,7 +19903,7 @@ function checkpoint(filename2, trust, initialize2) {
19506
19903
  }
19507
19904
  const descriptor2 = openSync(lock, "wx", 384);
19508
19905
  try {
19509
- writeFileSync6(descriptor2, "backify-application-auth-state-v1");
19906
+ writeFileSync7(descriptor2, "backify-application-auth-state-v1");
19510
19907
  fsyncSync(descriptor2);
19511
19908
  } finally {
19512
19909
  closeSync(descriptor2);
@@ -19537,7 +19934,7 @@ function checkpoint(filename2, trust, initialize2) {
19537
19934
  }
19538
19935
  } finally {
19539
19936
  if (!writePending) {
19540
- unlinkSync(lock);
19937
+ unlinkSync2(lock);
19541
19938
  syncDirectory(filename2);
19542
19939
  }
19543
19940
  }
@@ -19553,9 +19950,9 @@ function createPersistentApplicationAuthProvider(source, options) {
19553
19950
  }
19554
19951
 
19555
19952
  // ../sdk/dist/application-auth-sync.js
19556
- import { createHash as createHash4, createPublicKey as createPublicKey2, randomUUID as randomUUID4, verify as verify2 } from "node:crypto";
19557
- import { closeSync as closeSync2, constants as constants2, fsyncSync as fsyncSync2, lstatSync as lstatSync5, openSync as openSync2, readFileSync as readFileSync6, renameSync as renameSync4, unlinkSync as unlinkSync2, writeFileSync as writeFileSync7 } from "node:fs";
19558
- import { dirname as dirname7, isAbsolute as isAbsolute3, parse as parse2, resolve as resolve6, sep as sep3 } from "node:path";
19953
+ import { createHash as createHash4, createPublicKey as createPublicKey2, randomUUID as randomUUID5, verify as verify2 } from "node:crypto";
19954
+ import { closeSync as closeSync2, constants as constants2, fsyncSync as fsyncSync2, lstatSync as lstatSync5, openSync as openSync2, readFileSync as readFileSync7, renameSync as renameSync4, unlinkSync as unlinkSync3, writeFileSync as writeFileSync8 } from "node:fs";
19955
+ import { dirname as dirname7, isAbsolute as isAbsolute3, parse as parse2, resolve as resolve7, sep as sep3 } from "node:path";
19559
19956
  var maximumBytes = 512 * 1024;
19560
19957
  var identifier = (value) => typeof value === "string" && /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(value) && value !== "00000000-0000-0000-0000-000000000000";
19561
19958
  function unavailable3() {
@@ -19564,7 +19961,7 @@ function unavailable3() {
19564
19961
  function filename(value) {
19565
19962
  if (typeof value !== "string" || /[\x00-\x1f\x7f]/.test(value) || !isAbsolute3(value))
19566
19963
  unavailable3();
19567
- const result = resolve6(value);
19964
+ const result = resolve7(value);
19568
19965
  if (result === parse2(result).root || process.platform === "win32" && result.slice(parse2(result).root.length).split(sep3).some((component) => component.includes(":") || /[. ]$/.test(component) || /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(component)))
19569
19966
  unavailable3();
19570
19967
  return result;
@@ -19626,7 +20023,7 @@ function currentPublicFile(filename2) {
19626
20023
  const metadata = lstatSync5(filename2);
19627
20024
  if (!metadata.isFile() || metadata.isSymbolicLink() || metadata.nlink !== 1 || metadata.size > 131072 || process.platform !== "win32" && (metadata.uid !== process.getuid?.() || (metadata.mode & 18) !== 0))
19628
20025
  unavailable3();
19629
- const bytes = readFileSync6(filename2);
20026
+ const bytes = readFileSync7(filename2);
19630
20027
  if (bytes.length > 131072)
19631
20028
  unavailable3();
19632
20029
  return new TextDecoder("utf8", { fatal: true }).decode(bytes);
@@ -19693,7 +20090,7 @@ async function synchronizeApplicationAuthTrustWithDigest(options) {
19693
20090
  const lock = prepared.stateFile + ".delivery.lock";
19694
20091
  const descriptor2 = openSync2(lock, "wx", 384);
19695
20092
  try {
19696
- writeFileSync7(descriptor2, "backify-application-auth-delivery-v1");
20093
+ writeFileSync8(descriptor2, "backify-application-auth-delivery-v1");
19697
20094
  fsyncSync2(descriptor2);
19698
20095
  } finally {
19699
20096
  closeSync2(descriptor2);
@@ -19708,10 +20105,10 @@ async function synchronizeApplicationAuthTrustWithDigest(options) {
19708
20105
  if (current === content)
19709
20106
  return { status: "unchanged", revision: trust.revision, validUntil: trust.validUntil, trustDigest };
19710
20107
  writePending = true;
19711
- const temporary = prepared.trustFile + "." + randomUUID4() + ".tmp";
20108
+ const temporary = prepared.trustFile + "." + randomUUID5() + ".tmp";
19712
20109
  const output = openSync2(temporary, "wx", process.platform === "win32" ? 384 : 292);
19713
20110
  try {
19714
- writeFileSync7(output, content);
20111
+ writeFileSync8(output, content);
19715
20112
  fsyncSync2(output);
19716
20113
  } finally {
19717
20114
  closeSync2(output);
@@ -19722,7 +20119,7 @@ async function synchronizeApplicationAuthTrustWithDigest(options) {
19722
20119
  return { status: "updated", revision: trust.revision, validUntil: trust.validUntil, trustDigest };
19723
20120
  } finally {
19724
20121
  if (!writePending) {
19725
- unlinkSync2(lock);
20122
+ unlinkSync3(lock);
19726
20123
  syncDirectory2(lock);
19727
20124
  }
19728
20125
  }
@@ -20293,16 +20690,16 @@ function jsonValue(value) {
20293
20690
 
20294
20691
  // src/local-services.ts
20295
20692
  import { spawn, execFile } from "node:child_process";
20296
- import { createHash as createHash6, generateKeyPairSync, randomBytes as randomBytes3, randomUUID as randomUUID6, sign } from "node:crypto";
20297
- import { createServer as createServer2 } from "node:net";
20298
- import { existsSync as existsSync8, lstatSync as lstatSync7, mkdirSync as mkdirSync4, readFileSync as readFileSync8, readdirSync as readdirSync5, realpathSync, unlinkSync as unlinkSync3, writeFileSync as writeFileSync8 } from "node:fs";
20299
- import { basename as basename2, dirname as dirname9, isAbsolute as isAbsolute4, join as join7, relative, resolve as resolve7 } from "node:path";
20693
+ import { createHash as createHash6, generateKeyPairSync, randomBytes as randomBytes3, randomUUID as randomUUID7, sign } from "node:crypto";
20694
+ import { createServer as createServer3 } from "node:net";
20695
+ import { existsSync as existsSync8, lstatSync as lstatSync7, mkdirSync as mkdirSync4, readFileSync as readFileSync9, readdirSync as readdirSync5, realpathSync, unlinkSync as unlinkSync4, writeFileSync as writeFileSync9 } from "node:fs";
20696
+ import { basename as basename2, dirname as dirname9, isAbsolute as isAbsolute4, join as join8, relative, resolve as resolve8 } from "node:path";
20300
20697
 
20301
20698
  // src/local-job-services.ts
20302
- import { createHash as createHash5, randomBytes as randomBytes2, randomUUID as randomUUID5 } from "node:crypto";
20303
- import { existsSync as existsSync7, lstatSync as lstatSync6, readFileSync as readFileSync7 } from "node:fs";
20699
+ import { createHash as createHash5, randomBytes as randomBytes2, randomUUID as randomUUID6 } from "node:crypto";
20700
+ import { existsSync as existsSync7, lstatSync as lstatSync6, readFileSync as readFileSync8 } from "node:fs";
20304
20701
  import { isIP } from "node:net";
20305
- import { dirname as dirname8, join as join6 } from "node:path";
20702
+ import { dirname as dirname8, join as join7 } from "node:path";
20306
20703
  function fields3(value, names) {
20307
20704
  return !!value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === names.length && names.every((name2) => Object.hasOwn(value, name2));
20308
20705
  }
@@ -20353,9 +20750,9 @@ function validLocalJobState(value, otherIds) {
20353
20750
  function prepareLocalJobService(hcrPath, retained, artifacts, applyMigrations) {
20354
20751
  const requested = validateLocalJobArtifacts(artifacts);
20355
20752
  const readSchema = (name2) => {
20356
- const filename2 = join6(dirname8(hcrPath), "sql", name2), info = existsSync7(filename2) ? lstatSync6(filename2) : void 0;
20753
+ const filename2 = join7(dirname8(hcrPath), "sql", name2), info = existsSync7(filename2) ? lstatSync6(filename2) : void 0;
20357
20754
  if (!info?.isFile() || info.isSymbolicLink() || info.size > 65536) throw new Error("Native jobs require the reviewed jobs-v1.sql and jobs-producer-v1.sql assets beside the HCR host");
20358
- return readFileSync7(filename2, "utf8");
20755
+ return readFileSync8(filename2, "utf8");
20359
20756
  };
20360
20757
  const base = readSchema("jobs-v1.sql"), producer = readSchema("jobs-producer-v1.sql");
20361
20758
  const schemaDigests = { base: createHash5("sha256").update(base).digest("hex"), producer: createHash5("sha256").update(producer).digest("hex") };
@@ -20367,15 +20764,15 @@ function prepareLocalJobService(hcrPath, retained, artifacts, applyMigrations) {
20367
20764
  if (previous && JSON.stringify(previous) !== JSON.stringify(artifact)) throw new Error("Retained local job artifact metadata cannot change; preserve the original pins and policies");
20368
20765
  if (!previous) retainedArtifacts.push(artifact);
20369
20766
  }
20370
- const state = { ...retained ?? { id: randomUUID5(), password: randomBytes2(32).toString("hex"), initialized: false }, schemaDigests, artifacts: validateLocalJobArtifacts(retainedArtifacts) };
20767
+ const state = { ...retained ?? { id: randomUUID6(), password: randomBytes2(32).toString("hex"), initialized: false }, schemaDigests, artifacts: validateLocalJobArtifacts(retainedArtifacts) };
20371
20768
  return { state, base, producer };
20372
20769
  }
20373
20770
 
20374
20771
  // src/local-services.ts
20375
20772
  function writePrivate(filename2, value) {
20376
20773
  if (isLink(filename2)) throw new Error("Local service files must not be symbolic links");
20377
- const temporary = filename2 + "." + randomUUID6() + ".tmp";
20378
- writeFileSync8(temporary, value, { flag: "wx", mode: 384 });
20774
+ const temporary = filename2 + "." + randomUUID7() + ".tmp";
20775
+ writeFileSync9(temporary, value, { flag: "wx", mode: 384 });
20379
20776
  renameLocalFile(temporary, filename2);
20380
20777
  }
20381
20778
  function isLink(filename2) {
@@ -20388,35 +20785,35 @@ function isLink(filename2) {
20388
20785
  }
20389
20786
  function assertLocalStatePath(root, filename2) {
20390
20787
  const base = realpathSync(root);
20391
- for (let current = resolve7(filename2); current !== base; current = resolve7(current, "..")) {
20788
+ for (let current = resolve8(filename2); current !== base; current = resolve8(current, "..")) {
20392
20789
  const part = relative(base, current);
20393
20790
  if (part === ".." || part.startsWith(".." + (process.platform === "win32" ? "\\" : "/")) || isAbsolute4(part)) throw new Error("Local service state must stay inside the repository");
20394
20791
  if (isLink(current)) throw new Error("Local service paths must not contain links");
20395
20792
  }
20396
20793
  }
20397
20794
  function stateValid(value) {
20398
- const uuid5 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
20795
+ const uuid4 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
20399
20796
  if (value?.jobs !== void 0 && !validLocalJobState(value.jobs, [value.databaseId, value.storageId, ...Object.values(value.storageBindings ?? {}), ...value.events ? [value.events.id] : []].filter((identifier2) => typeof identifier2 === "string"))) return false;
20400
- if (value?.events !== void 0 && (!value.events || typeof value.events !== "object" || Array.isArray(value.events) || typeof value.events.id !== "string" || value.events.id.length !== 36 || !uuid5.test(value.events.id) || value.events.id === "00000000-0000-0000-0000-000000000000" || [value.databaseId, value.storageId, ...Object.values(value.storageBindings ?? {})].some((identifier2) => typeof identifier2 === "string" && identifier2.toLowerCase() === value.events.id.toLowerCase()) || typeof value.events.password !== "string" || value.events.password.length !== 64 || !/^[a-f0-9]{64}$/.test(value.events.password) || typeof value.events.schemaDigest !== "string" || value.events.schemaDigest.length !== 64 || !/^[a-f0-9]{64}$/.test(value.events.schemaDigest) || typeof value.events.initialized !== "boolean")) return false;
20401
- return value?.version === 1 && value.scope && [value.scope.organizationId, value.scope.applicationId, value.scope.environmentId, value.databaseId, value.storageId].every((identifier2) => typeof identifier2 === "string" && uuid5.test(identifier2)) && Number.isSafeInteger(value.configurationVersion) && value.configurationVersion >= 0 && /^[a-f0-9]{64}$/.test(value.adminPassword) && /^[a-f0-9]{64}$/.test(value.databasePassword) && (value.retainedDatabasePort === void 0 || Number.isInteger(value.retainedDatabasePort) && value.retainedDatabasePort > 0 && value.retainedDatabasePort <= 65535);
20797
+ if (value?.events !== void 0 && (!value.events || typeof value.events !== "object" || Array.isArray(value.events) || typeof value.events.id !== "string" || value.events.id.length !== 36 || !uuid4.test(value.events.id) || value.events.id === "00000000-0000-0000-0000-000000000000" || [value.databaseId, value.storageId, ...Object.values(value.storageBindings ?? {})].some((identifier2) => typeof identifier2 === "string" && identifier2.toLowerCase() === value.events.id.toLowerCase()) || typeof value.events.password !== "string" || value.events.password.length !== 64 || !/^[a-f0-9]{64}$/.test(value.events.password) || typeof value.events.schemaDigest !== "string" || value.events.schemaDigest.length !== 64 || !/^[a-f0-9]{64}$/.test(value.events.schemaDigest) || typeof value.events.initialized !== "boolean")) return false;
20798
+ return value?.version === 1 && value.scope && [value.scope.organizationId, value.scope.applicationId, value.scope.environmentId, value.databaseId, value.storageId].every((identifier2) => typeof identifier2 === "string" && uuid4.test(identifier2)) && Number.isSafeInteger(value.configurationVersion) && value.configurationVersion >= 0 && /^[a-f0-9]{64}$/.test(value.adminPassword) && /^[a-f0-9]{64}$/.test(value.databasePassword) && (value.retainedDatabasePort === void 0 || Number.isInteger(value.retainedDatabasePort) && value.retainedDatabasePort > 0 && value.retainedDatabasePort <= 65535);
20402
20799
  }
20403
20800
  function acquireLocalLease(root, relativePath2 = ".backify/dev/development.lock") {
20404
- const filename2 = join7(root, relativePath2);
20801
+ const filename2 = join8(root, relativePath2);
20405
20802
  assertLocalStatePath(root, filename2);
20406
- mkdirSync4(resolve7(filename2, ".."), { recursive: true, mode: 448 });
20407
- const owner = JSON.stringify({ version: 1, pid: process.pid, id: randomUUID6() });
20803
+ mkdirSync4(resolve8(filename2, ".."), { recursive: true, mode: 448 });
20804
+ const owner = JSON.stringify({ version: 1, pid: process.pid, id: randomUUID7() });
20408
20805
  try {
20409
- writeFileSync8(filename2, owner, { flag: "wx", mode: 384 });
20806
+ writeFileSync9(filename2, owner, { flag: "wx", mode: 384 });
20410
20807
  } catch {
20411
20808
  throw new Error("Local development already owns this repository, or a stale lifecycle lock requires explicit recovery");
20412
20809
  }
20413
20810
  return () => {
20414
- if (existsSync8(filename2) && readFileSync8(filename2, "utf8") === owner) unlinkSync3(filename2);
20811
+ if (existsSync8(filename2) && readFileSync9(filename2, "utf8") === owner) unlinkSync4(filename2);
20415
20812
  };
20416
20813
  }
20417
20814
  async function allocateLocalPort(requested) {
20418
20815
  if (requested !== void 0 && (!Number.isInteger(requested) || requested < 0 || requested > 65535)) throw new Error("Local service ports must be 0-65535");
20419
- const server = createServer2();
20816
+ const server = createServer3();
20420
20817
  return new Promise((resolvePort, reject) => {
20421
20818
  server.once("error", reject);
20422
20819
  server.listen(requested ?? 0, "127.0.0.1", () => {
@@ -20454,13 +20851,13 @@ function command(executable, args2, options = {}) {
20454
20851
  });
20455
20852
  }
20456
20853
  function postgresExecutable(name2, bin) {
20457
- const directory2 = bin ?? process.env.BACKIFY_LOCAL_POSTGRES_BIN ?? (process.platform === "win32" ? join7(process.env.ProgramFiles ?? "C:/Program Files", "PostgreSQL", "17", "bin") : void 0);
20458
- return directory2 ? join7(directory2, name2 + (process.platform === "win32" ? ".exe" : "")) : name2;
20854
+ const directory2 = bin ?? process.env.BACKIFY_LOCAL_POSTGRES_BIN ?? (process.platform === "win32" ? join8(process.env.ProgramFiles ?? "C:/Program Files", "PostgreSQL", "17", "bin") : void 0);
20855
+ return directory2 ? join8(directory2, name2 + (process.platform === "win32" ? ".exe" : "")) : name2;
20459
20856
  }
20460
20857
  function localMigrationFiles(root, directory2) {
20461
20858
  if (directory2 === void 0) return [];
20462
20859
  if (typeof directory2 !== "string") throw new Error("Local migrations require a repository-relative directory");
20463
- const folder = resolve7(root, directory2);
20860
+ const folder = resolve8(root, directory2);
20464
20861
  assertLocalStatePath(root, folder);
20465
20862
  if (!existsSync8(folder)) throw new Error("Declared migration directory does not exist");
20466
20863
  const entries = readdirSync5(folder);
@@ -20469,11 +20866,11 @@ function localMigrationFiles(root, directory2) {
20469
20866
  let total = 0;
20470
20867
  return filenames.map((name2) => {
20471
20868
  if (!/^[A-Za-z0-9_.-]{1,150}\.sql$/.test(name2)) throw new Error("Invalid migration filename");
20472
- const filename2 = join7(folder, name2);
20869
+ const filename2 = join8(folder, name2);
20473
20870
  assertLocalStatePath(root, filename2);
20474
20871
  const info = lstatSync7(filename2);
20475
20872
  if (!info.isFile() || info.size > 1024 * 1024 || (total += info.size) > 4 * 1024 * 1024) throw new Error("Migration SQL exceeds supported limits");
20476
- const sql = readFileSync8(filename2, "utf8");
20873
+ const sql = readFileSync9(filename2, "utf8");
20477
20874
  if (!sql.trim()) throw new Error("Migration SQL must not be empty");
20478
20875
  validateLocalMigrationSql(sql);
20479
20876
  return { name: name2, digest: createHash6("sha256").update(sql).digest("hex"), sql };
@@ -20550,19 +20947,19 @@ async function startLocalServices(root, manifest, options = {}) {
20550
20947
  const reviewedScope = options.jobIdentityScope;
20551
20948
  if (reviewedScope !== void 0 && (!jobs || !manifest.capabilities.auth || manifest.capabilities.auth.enabled === false || !reviewedScope || Object.keys(reviewedScope).sort().join(",") !== "applicationId,environmentId,organizationId" || Object.values(reviewedScope).some((value) => typeof value !== "string" || value.length !== 36 || !/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(value) || value === "00000000-0000-0000-0000-000000000000"))) throw new Error("Native worker identity scope requires reviewed jobs and enabled auth");
20552
20949
  const installed = options.hcrPath || process.env.BACKIFY_LOCAL_HCR_PATH ? void 0 : installedLocalRuntime();
20553
- const hcrPath = resolve7(options.hcrPath ?? process.env.BACKIFY_LOCAL_HCR_PATH ?? installed?.path ?? join7(root, "apps/hcr/bin/Debug/net9.0/Backify.Hcr.dll"));
20950
+ const hcrPath = resolve8(options.hcrPath ?? process.env.BACKIFY_LOCAL_HCR_PATH ?? installed?.path ?? join8(root, "apps/hcr/bin/Debug/net9.0/Backify.Hcr.dll"));
20554
20951
  if (!existsSync8(hcrPath) || !lstatSync7(hcrPath).isFile() || !hcrPath.endsWith(".dll")) throw new Error("Full-fidelity mode requires a built Backify.Hcr.dll; set --hcr-path or BACKIFY_LOCAL_HCR_PATH");
20555
- const directory2 = join7(root, ".backify", "dev", "services");
20952
+ const directory2 = join8(root, ".backify", "dev", "services");
20556
20953
  assertLocalStatePath(root, directory2);
20557
20954
  mkdirSync4(directory2, { recursive: true, mode: 448 });
20558
20955
  assertLocalStatePath(root, directory2);
20559
- const statePath = join7(directory2, "host.json");
20956
+ const statePath = join8(directory2, "host.json");
20560
20957
  assertLocalStatePath(root, statePath);
20561
20958
  let existing;
20562
20959
  if (existsSync8(statePath)) {
20563
20960
  if (lstatSync7(statePath).size > 16384) throw new Error("Local ownership state exceeds supported limits");
20564
20961
  try {
20565
- existing = JSON.parse(readFileSync8(statePath, "utf8"));
20962
+ existing = JSON.parse(readFileSync9(statePath, "utf8"));
20566
20963
  } catch {
20567
20964
  throw new Error("Invalid local service ownership state; preserve the data and repair explicitly");
20568
20965
  }
@@ -20570,9 +20967,9 @@ async function startLocalServices(root, manifest, options = {}) {
20570
20967
  }
20571
20968
  const state = existing ?? {
20572
20969
  version: 1,
20573
- scope: reviewedScope ? structuredClone(reviewedScope) : { organizationId: randomUUID6(), applicationId: randomUUID6(), environmentId: randomUUID6() },
20574
- databaseId: randomUUID6(),
20575
- storageId: randomUUID6(),
20970
+ scope: reviewedScope ? structuredClone(reviewedScope) : { organizationId: randomUUID7(), applicationId: randomUUID7(), environmentId: randomUUID7() },
20971
+ databaseId: randomUUID7(),
20972
+ storageId: randomUUID7(),
20576
20973
  configurationVersion: 0,
20577
20974
  adminPassword: randomBytes3(32).toString("hex"),
20578
20975
  databasePassword: randomBytes3(32).toString("hex")
@@ -20581,20 +20978,20 @@ async function startLocalServices(root, manifest, options = {}) {
20581
20978
  if (reviewedScope && ["organizationId", "applicationId", "environmentId"].some((name2) => state.scope[name2] !== reviewedScope[name2])) throw new Error("Reviewed native worker identity scope conflicts with retained local ownership; preserve data and use a separate reviewed workspace");
20582
20979
  let eventSchema;
20583
20980
  if (events) {
20584
- const filename2 = join7(dirname9(hcrPath), "sql", "events-v1.sql");
20981
+ const filename2 = join8(dirname9(hcrPath), "sql", "events-v1.sql");
20585
20982
  if (!existsSync8(filename2) || lstatSync7(filename2).isSymbolicLink() || !lstatSync7(filename2).isFile() || lstatSync7(filename2).size > 65536) throw new Error("Native events require the reviewed events-v1.sql asset beside the HCR host.");
20586
- eventSchema = readFileSync8(filename2, "utf8");
20983
+ eventSchema = readFileSync9(filename2, "utf8");
20587
20984
  const digest4 = createHash6("sha256").update(eventSchema).digest("hex");
20588
20985
  if (state.events && state.events.schemaDigest !== digest4) throw new Error("Native event schema changed; preserve its database and plan an explicit migration.");
20589
20986
  if (!state.events?.initialized && !options.applyMigrations) throw new Error("Review the HCR events-v1.sql asset and pass --apply-migrations for explicit native event schema approval.");
20590
- state.events ??= { id: randomUUID6(), password: randomBytes3(32).toString("hex"), schemaDigest: digest4, initialized: false };
20987
+ state.events ??= { id: randomUUID7(), password: randomBytes3(32).toString("hex"), schemaDigest: digest4, initialized: false };
20591
20988
  }
20592
20989
  const jobSchema = jobs ? prepareLocalJobService(hcrPath, state.jobs, options.jobArtifacts, options.applyMigrations) : void 0;
20593
20990
  if (jobSchema) state.jobs = jobSchema.state;
20594
20991
  const storageNames = manifest.capabilities.storage?.buckets === void 0 ? ["default"] : manifest.capabilities.storage.buckets.map((bucket) => bucket.name);
20595
20992
  state.storageBindings ??= { default: state.storageId };
20596
20993
  if (typeof state.storageBindings !== "object" || state.storageBindings === null || Array.isArray(state.storageBindings) || Object.entries(state.storageBindings).some(([name2, identifier2]) => !/^[A-Za-z0-9_-]{1,100}$/.test(name2) || typeof identifier2 !== "string" || !/^[0-9a-f-]{36}$/i.test(identifier2))) throw new Error("Invalid local storage binding ownership state");
20597
- for (const name2 of storageNames) state.storageBindings[name2] ??= randomUUID6();
20994
+ for (const name2 of storageNames) state.storageBindings[name2] ??= randomUUID7();
20598
20995
  if (Object.keys(state.storageBindings).length > 100) throw new Error("Local storage ownership history exceeds 100 bindings; preserve the data and plan an explicit migration");
20599
20996
  if (Buffer.byteLength(JSON.stringify({ ...state, configurationVersion: Number.MAX_SAFE_INTEGER, retainedDatabasePort: 65535 }), "utf8") > 16384) throw new Error("Local ownership history exceeds supported limits; preserve state and plan an explicit migration");
20600
20997
  const migrations = database ? localMigrationFiles(root, manifest.capabilities.database?.migrations) : [];
@@ -20602,7 +20999,7 @@ async function startLocalServices(root, manifest, options = {}) {
20602
20999
  const databasePort = database || events || jobs ? await allocateLocalPort(options.databasePort) : void 0;
20603
21000
  if (databasePort !== void 0) state.retainedDatabasePort = databasePort;
20604
21001
  if (databasePort === hcrPort) throw new Error("HCR and PostgreSQL require separate ports");
20605
- const cluster = join7(directory2, "postgres");
21002
+ const cluster = join8(directory2, "postgres");
20606
21003
  assertLocalStatePath(root, cluster);
20607
21004
  const release2 = acquireLocalLease(root, ".backify/dev/services/lifecycle.lock");
20608
21005
  let postgresStarted = false;
@@ -20618,7 +21015,7 @@ async function startLocalServices(root, manifest, options = {}) {
20618
21015
  }
20619
21016
  };
20620
21017
  const runtimeUrl = "http://127.0.0.1:" + hcrPort;
20621
- const tokenPath = join7(directory2, "workload-token");
21018
+ const tokenPath = join8(directory2, "workload-token");
20622
21019
  const stop = () => stopping ??= (async () => {
20623
21020
  if (timer) clearInterval(timer);
20624
21021
  if (snapshotTimer) clearInterval(snapshotTimer);
@@ -20637,9 +21034,9 @@ async function startLocalServices(root, manifest, options = {}) {
20637
21034
  }
20638
21035
  notify("hcr", "stopped");
20639
21036
  try {
20640
- if (postgresStarted && existsSync8(join7(cluster, "postmaster.pid"))) await command(postgresExecutable("pg_ctl", options.postgresBin), ["-D", cluster, "-m", "fast", "-w", "stop"]);
21037
+ if (postgresStarted && existsSync8(join8(cluster, "postmaster.pid"))) await command(postgresExecutable("pg_ctl", options.postgresBin), ["-D", cluster, "-m", "fast", "-w", "stop"]);
20641
21038
  if (postgresStarted) notify("postgres", "stopped");
20642
- if (existsSync8(tokenPath)) unlinkSync3(tokenPath);
21039
+ if (existsSync8(tokenPath)) unlinkSync4(tokenPath);
20643
21040
  } finally {
20644
21041
  release2();
20645
21042
  }
@@ -20649,28 +21046,28 @@ async function startLocalServices(root, manifest, options = {}) {
20649
21046
  writePrivate(statePath, JSON.stringify(state));
20650
21047
  if (database || events || jobs) {
20651
21048
  notify("postgres", "starting");
20652
- if (!existsSync8(join7(cluster, "PG_VERSION"))) {
20653
- const passwordPath = join7(directory2, "init-password");
21049
+ if (!existsSync8(join8(cluster, "PG_VERSION"))) {
21050
+ const passwordPath = join8(directory2, "init-password");
20654
21051
  writePrivate(passwordPath, state.adminPassword);
20655
21052
  try {
20656
21053
  await command(postgresExecutable("initdb", options.postgresBin), ["-D", cluster, "-U", "backify_admin", "--auth-host=scram-sha-256", "--auth-local=scram-sha-256", "--pwfile=" + passwordPath, "--no-locale", "--encoding=UTF8"]);
20657
21054
  } finally {
20658
- if (existsSync8(passwordPath)) unlinkSync3(passwordPath);
21055
+ if (existsSync8(passwordPath)) unlinkSync4(passwordPath);
20659
21056
  }
20660
21057
  }
20661
- if (existsSync8(join7(cluster, "postmaster.pid"))) throw new Error("A retained local PostgreSQL server is still running; stop or recover that exact owned cluster before restarting dev");
21058
+ if (existsSync8(join8(cluster, "postmaster.pid"))) throw new Error("A retained local PostgreSQL server is still running; stop or recover that exact owned cluster before restarting dev");
20662
21059
  postgresStarted = true;
20663
- await command(postgresExecutable("pg_ctl", options.postgresBin), ["-D", cluster, "-l", join7(directory2, "postgres.log"), "-o", "-h 127.0.0.1 -p " + databasePort, "-w", "start"]);
21060
+ await command(postgresExecutable("pg_ctl", options.postgresBin), ["-D", cluster, "-l", join8(directory2, "postgres.log"), "-o", "-h 127.0.0.1 -p " + databasePort, "-w", "start"]);
20664
21061
  notify("postgres", "ready");
20665
21062
  const sql = (query, application = false) => command(postgresExecutable("psql", options.postgresBin), ["-h", "127.0.0.1", "-p", String(databasePort), "-U", application ? "backify_local" : "backify_admin", "-d", application ? "backify_local" : "postgres", "-X", "-q", "-t", "-A", "-v", "ON_ERROR_STOP=1", "-c", query], { env: { ...process.env, PGPASSWORD: application ? state.databasePassword : state.adminPassword } });
20666
21063
  if (database) {
20667
21064
  if ((await sql("SELECT count(*) FROM pg_roles WHERE rolname='backify_local'")).trim() === "0") {
20668
- const filename2 = join7(directory2, "role-" + randomUUID6() + ".sql");
21065
+ const filename2 = join8(directory2, "role-" + randomUUID7() + ".sql");
20669
21066
  writePrivate(filename2, "CREATE ROLE backify_local LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE PASSWORD '" + state.databasePassword + "';");
20670
21067
  try {
20671
21068
  await command(postgresExecutable("psql", options.postgresBin), ["-h", "127.0.0.1", "-p", String(databasePort), "-U", "backify_admin", "-d", "postgres", "-X", "-q", "-v", "ON_ERROR_STOP=1", "-f", filename2], { env: { ...process.env, PGPASSWORD: state.adminPassword } });
20672
21069
  } finally {
20673
- if (existsSync8(filename2)) unlinkSync3(filename2);
21070
+ if (existsSync8(filename2)) unlinkSync4(filename2);
20674
21071
  }
20675
21072
  }
20676
21073
  if ((await sql("SELECT count(*) FROM pg_database WHERE datname='backify_local'")).trim() === "0") await sql("CREATE DATABASE backify_local OWNER backify_local");
@@ -20685,12 +21082,12 @@ async function startLocalServices(root, manifest, options = {}) {
20685
21082
  notify("migrations", "starting");
20686
21083
  if (pending.length) await sql("CREATE TABLE IF NOT EXISTS public.__backify_migrations (name text PRIMARY KEY, digest text NOT NULL, applied_at timestamptz NOT NULL DEFAULT now())", true);
20687
21084
  for (const migration of pending) {
20688
- const filename2 = join7(directory2, "apply-" + randomUUID6() + ".sql");
21085
+ const filename2 = join8(directory2, "apply-" + randomUUID7() + ".sql");
20689
21086
  writePrivate(filename2, "BEGIN;\n" + migration.sql + "\n;\nINSERT INTO public.__backify_migrations(name,digest) VALUES ('" + migration.name + "','" + migration.digest + "');\nCOMMIT;\n");
20690
21087
  try {
20691
21088
  await command(postgresExecutable("psql", options.postgresBin), ["-h", "127.0.0.1", "-p", String(databasePort), "-U", "backify_local", "-d", "backify_local", "-X", "-q", "-v", "ON_ERROR_STOP=1", "-f", filename2], { env: { ...process.env, PGPASSWORD: state.databasePassword } });
20692
21089
  } finally {
20693
- if (existsSync8(filename2)) unlinkSync3(filename2);
21090
+ if (existsSync8(filename2)) unlinkSync4(filename2);
20694
21091
  }
20695
21092
  applied.push(migration.name);
20696
21093
  }
@@ -20701,20 +21098,20 @@ async function startLocalServices(root, manifest, options = {}) {
20701
21098
  const eventSql = (query) => command(postgresExecutable("psql", options.postgresBin), ["-h", "127.0.0.1", "-p", String(databasePort), "-U", "backify_events", "-d", "backify_events", "-X", "-q", "-t", "-A", "-v", "ON_ERROR_STOP=1", "-c", query], { env: { ...process.env, PGPASSWORD: eventState.password } });
20702
21099
  if (!eventState.initialized) {
20703
21100
  if ((await sql("SELECT count(*) FROM pg_database WHERE datname='backify_events'")).trim() !== "0" || (await sql("SELECT count(*) FROM pg_roles WHERE rolname='backify_events'")).trim() !== "0") throw new Error("Uninitialized native event ownership conflicts with retained state; preserve it and repair explicitly.");
20704
- const roleFile = join7(directory2, "event-role-" + randomUUID6() + ".sql");
21101
+ const roleFile = join8(directory2, "event-role-" + randomUUID7() + ".sql");
20705
21102
  writePrivate(roleFile, "CREATE ROLE backify_events LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE PASSWORD '" + eventState.password + "';");
20706
21103
  try {
20707
21104
  await command(postgresExecutable("psql", options.postgresBin), ["-h", "127.0.0.1", "-p", String(databasePort), "-U", "backify_admin", "-d", "postgres", "-X", "-q", "-v", "ON_ERROR_STOP=1", "-f", roleFile], { env: { ...process.env, PGPASSWORD: state.adminPassword } });
20708
21105
  } finally {
20709
- if (existsSync8(roleFile)) unlinkSync3(roleFile);
21106
+ if (existsSync8(roleFile)) unlinkSync4(roleFile);
20710
21107
  }
20711
21108
  await sql("CREATE DATABASE backify_events OWNER backify_events");
20712
- const schemaFile = join7(directory2, "event-schema-" + randomUUID6() + ".sql");
21109
+ const schemaFile = join8(directory2, "event-schema-" + randomUUID7() + ".sql");
20713
21110
  writePrivate(schemaFile, eventSchema);
20714
21111
  try {
20715
21112
  await command(postgresExecutable("psql", options.postgresBin), ["-h", "127.0.0.1", "-p", String(databasePort), "-U", "backify_events", "-d", "backify_events", "-X", "-q", "-v", "ON_ERROR_STOP=1", "-f", schemaFile], { env: { ...process.env, PGPASSWORD: eventState.password } });
20716
21113
  } finally {
20717
- if (existsSync8(schemaFile)) unlinkSync3(schemaFile);
21114
+ if (existsSync8(schemaFile)) unlinkSync4(schemaFile);
20718
21115
  }
20719
21116
  eventState.initialized = true;
20720
21117
  writePrivate(statePath, JSON.stringify(state));
@@ -20728,21 +21125,21 @@ async function startLocalServices(root, manifest, options = {}) {
20728
21125
  const adminSql = (query, databaseName = "postgres") => jobCommand("backify_admin", state.adminPassword, databaseName, ["-c", query]);
20729
21126
  if (!jobState.initialized) {
20730
21127
  if ((await adminSql("SELECT count(*) FROM pg_database WHERE datname='backify_jobs'")).trim() !== "0" || (await adminSql("SELECT count(*) FROM pg_roles WHERE rolname='backify_jobs'")).trim() !== "0") throw new Error("Uninitialized native job ownership conflicts with retained state; preserve it and repair explicitly");
20731
- const roleFile = join7(directory2, "job-role-" + randomUUID6() + ".sql");
21128
+ const roleFile = join8(directory2, "job-role-" + randomUUID7() + ".sql");
20732
21129
  writePrivate(roleFile, "CREATE ROLE backify_jobs LOGIN NOINHERIT NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS PASSWORD '" + jobState.password + "';");
20733
21130
  try {
20734
21131
  await jobCommand("backify_admin", state.adminPassword, "postgres", ["-f", roleFile]);
20735
21132
  } finally {
20736
- if (existsSync8(roleFile)) unlinkSync3(roleFile);
21133
+ if (existsSync8(roleFile)) unlinkSync4(roleFile);
20737
21134
  }
20738
21135
  await adminSql("CREATE DATABASE backify_jobs OWNER backify_admin");
20739
21136
  for (const schema of [jobSchema.base, jobSchema.producer]) {
20740
- const filename2 = join7(directory2, "job-schema-" + randomUUID6() + ".sql");
21137
+ const filename2 = join8(directory2, "job-schema-" + randomUUID7() + ".sql");
20741
21138
  writePrivate(filename2, schema);
20742
21139
  try {
20743
21140
  await jobCommand("backify_admin", state.adminPassword, "backify_jobs", ["-f", filename2]);
20744
21141
  } finally {
20745
- if (existsSync8(filename2)) unlinkSync3(filename2);
21142
+ if (existsSync8(filename2)) unlinkSync4(filename2);
20746
21143
  }
20747
21144
  }
20748
21145
  await adminSql("REVOKE ALL ON DATABASE backify_jobs FROM PUBLIC; GRANT CONNECT ON DATABASE backify_jobs TO backify_jobs; REVOKE CREATE ON SCHEMA public FROM PUBLIC; GRANT USAGE ON SCHEMA __backify_jobs TO backify_jobs; GRANT SELECT ON __backify_jobs.schema_version,__backify_jobs.producer_schema_version TO backify_jobs; GRANT SELECT,INSERT,UPDATE ON __backify_jobs.runs,__backify_jobs.attempts TO backify_jobs; GRANT SELECT,INSERT ON __backify_jobs.producers TO backify_jobs", "backify_jobs");
@@ -20771,7 +21168,7 @@ async function startLocalServices(root, manifest, options = {}) {
20771
21168
  ...events ? [{ id: state.events.id, scope: state.scope, capability: "events", contractVersion: 1, logicalBinding: "default", provider: "postgres-events", resourceReference: "backify_events", ownership: "Managed", accessMode: "Gateway", permissions: ["events.emit", "events.receive", "events.complete", "events.inspect"], status: "ready" }] : [],
20772
21169
  ...jobs ? [{ id: state.jobs.id, scope: state.scope, capability: "jobs", contractVersion: 1, logicalBinding: "default", provider: "postgres-jobs", resourceReference: "backify_jobs", ownership: "Managed", accessMode: "Gateway", permissions: ["jobs.enqueue", "jobs.receive", "jobs.complete", "jobs.cancel", "jobs.inspect", "jobs.retry"], status: "ready" }] : []
20773
21170
  ];
20774
- const snapshotPath = join7(directory2, "snapshot.json");
21171
+ const snapshotPath = join8(directory2, "snapshot.json");
20775
21172
  const writeSnapshot = () => writePrivate(snapshotPath, JSON.stringify({ schemaVersion: 1, configurationVersion: state.configurationVersion, expiresAt: new Date(Date.now() + 7 * 864e5).toISOString(), bindings }));
20776
21173
  const renewConfiguration = () => {
20777
21174
  if (stopping) throw new Error("Stopped local services cannot renew configuration");
@@ -20781,15 +21178,15 @@ async function startLocalServices(root, manifest, options = {}) {
20781
21178
  writeSnapshot();
20782
21179
  };
20783
21180
  writeSnapshot();
20784
- const settingsPath = join7(directory2, "appsettings.json");
21181
+ const settingsPath = join8(directory2, "appsettings.json");
20785
21182
  writePrivate(settingsPath, JSON.stringify({ Hcr: {
20786
21183
  Authentication: { PublicKeyPem: publicKey.export({ type: "spki", format: "pem" }), Issuer: "backify-local", Audience: "backify-local-hcr" },
20787
21184
  SnapshotPath: snapshotPath,
20788
- SnapshotJournalPath: join7(directory2, "journal.json"),
21185
+ SnapshotJournalPath: join8(directory2, "journal.json"),
20789
21186
  Postgres: { Bindings: state.retainedDatabasePort ? { [state.databaseId]: { Scope: state.scope, ConnectionString: "Host=127.0.0.1;Port=" + state.retainedDatabasePort + ";Database=backify_local;Username=backify_local;Password=" + state.databasePassword } } : {} },
20790
21187
  Events: { Bindings: state.retainedDatabasePort && state.events?.initialized ? { [state.events.id]: { Scope: state.scope, ConnectionString: "Host=127.0.0.1;Port=" + state.retainedDatabasePort + ";Database=backify_events;Username=backify_events;Password=" + state.events.password } } : {} },
20791
21188
  Jobs: { Bindings: state.retainedDatabasePort && state.jobs?.initialized ? { [state.jobs.id]: { Scope: state.scope, ConnectionString: "Host=127.0.0.1;Port=" + state.retainedDatabasePort + ";Database=backify_jobs;Username=backify_jobs;Password=" + state.jobs.password, Artifacts: state.jobs.artifacts } } : {} },
20792
- Storage: { Bindings: Object.fromEntries(Object.entries(state.storageBindings).map(([name2, identifier2]) => [identifier2, { Scope: state.scope, ResourceReference: name2, RootPath: join7(directory2, "objects", identifier2) }])) }
21189
+ Storage: { Bindings: Object.fromEntries(Object.entries(state.storageBindings).map(([name2, identifier2]) => [identifier2, { Scope: state.scope, ResourceReference: name2, RootPath: join8(directory2, "objects", identifier2) }])) }
20793
21190
  } }));
20794
21191
  issueToken();
20795
21192
  notify("hcr", "starting");
@@ -20803,7 +21200,7 @@ async function startLocalServices(root, manifest, options = {}) {
20803
21200
  while (true) {
20804
21201
  if (spawnFailed || hcr.exitCode !== null || hcr.signalCode !== null || Date.now() > deadline) throw new Error("Local HCR could not become ready; check the .NET runtime, bindings and retained journal");
20805
21202
  try {
20806
- const response = await fetch(runtimeUrl + "/v1/health", { headers: { authorization: "Bearer " + readFileSync8(tokenPath, "utf8") }, signal: AbortSignal.timeout(500), redirect: "error", credentials: "omit", cache: "no-store" });
21203
+ const response = await fetch(runtimeUrl + "/v1/health", { headers: { authorization: "Bearer " + readFileSync9(tokenPath, "utf8") }, signal: AbortSignal.timeout(500), redirect: "error", credentials: "omit", cache: "no-store" });
20807
21204
  if (response.ok) {
20808
21205
  const status = await response.json();
20809
21206
  if (status.status === "ready" && status.configurationVersion === state.configurationVersion) break;
@@ -20812,8 +21209,8 @@ async function startLocalServices(root, manifest, options = {}) {
20812
21209
  }
20813
21210
  await new Promise((resolveDelay) => setTimeout(resolveDelay, 100));
20814
21211
  }
20815
- if (events) await createHcrEventsProvider({ runtimeUrl, token: () => readFileSync8(tokenPath, "utf8") }).inspect();
20816
- if (jobs) await createHcrJobsProvider({ runtimeUrl, token: () => readFileSync8(tokenPath, "utf8") }).inspect();
21212
+ if (events) await createHcrEventsProvider({ runtimeUrl, token: () => readFileSync9(tokenPath, "utf8") }).inspect();
21213
+ if (jobs) await createHcrJobsProvider({ runtimeUrl, token: () => readFileSync9(tokenPath, "utf8") }).inspect();
20817
21214
  timer = setInterval(() => {
20818
21215
  try {
20819
21216
  issueToken();
@@ -20839,24 +21236,24 @@ async function startLocalServices(root, manifest, options = {}) {
20839
21236
 
20840
21237
  // src/local-job-auth.ts
20841
21238
  import { createHash as createHash7 } from "node:crypto";
20842
- import { lstatSync as lstatSync8, readFileSync as readFileSync9 } from "node:fs";
20843
- import { isAbsolute as isAbsolute5, resolve as resolve8 } from "node:path";
21239
+ import { lstatSync as lstatSync8, readFileSync as readFileSync10 } from "node:fs";
21240
+ import { isAbsolute as isAbsolute5, resolve as resolve9 } from "node:path";
20844
21241
  function prepareLocalJobAuth(root, filename2) {
20845
21242
  const read = (path, maximum) => {
20846
21243
  assertLocalStatePath(root, path);
20847
21244
  const metadata = lstatSync8(path);
20848
21245
  if (!metadata.isFile() || metadata.isSymbolicLink() || metadata.nlink !== 1 || metadata.size > maximum) throw new Error();
20849
- const bytes = readFileSync9(path);
21246
+ const bytes = readFileSync10(path);
20850
21247
  if (bytes.length > maximum) throw new Error();
20851
21248
  return bytes;
20852
21249
  };
20853
21250
  try {
20854
21251
  if (!filename2 || isAbsolute5(filename2)) throw new Error();
20855
- const input = JSON.parse(new TextDecoder("utf8", { fatal: true }).decode(read(resolve8(root, filename2), 16384)));
21252
+ const input = JSON.parse(new TextDecoder("utf8", { fatal: true }).decode(read(resolve9(root, filename2), 16384)));
20856
21253
  if (!input || Object.keys(input).sort().join(",") !== "revision,schemaVersion,scope,stateFile,trustDigest,trustFile" || input.schemaVersion !== 1 || !Number.isSafeInteger(input.revision) || input.revision < 1 || typeof input.trustDigest !== "string" || input.trustDigest.length !== 64 || !/^[a-f0-9]{64}$/.test(input.trustDigest)) throw new Error();
20857
21254
  if (!input.scope || Object.keys(input.scope).sort().join(",") !== "applicationId,environmentId,organizationId" || Object.values(input.scope).some((value) => typeof value !== "string" || value.length !== 36 || !/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(value) || value === "00000000-0000-0000-0000-000000000000")) throw new Error();
20858
21255
  if ([input.trustFile, input.stateFile].some((path) => typeof path !== "string" || !path || isAbsolute5(path))) throw new Error();
20859
- const trustFile = resolve8(root, input.trustFile), stateFile = resolve8(root, input.stateFile);
21256
+ const trustFile = resolve9(root, input.trustFile), stateFile = resolve9(root, input.stateFile);
20860
21257
  if (trustFile === stateFile) throw new Error();
20861
21258
  const bytes = read(trustFile, 131072), trust = JSON.parse(new TextDecoder("utf8", { fatal: true }).decode(bytes));
20862
21259
  read(stateFile, 2048);
@@ -20870,24 +21267,24 @@ function prepareLocalJobAuth(root, filename2) {
20870
21267
 
20871
21268
  // src/local-job-trust-renewal.ts
20872
21269
  import { createHash as createHash9 } from "node:crypto";
20873
- import { lstatSync as lstatSync10, readFileSync as readFileSync11 } from "node:fs";
20874
- import { isAbsolute as isAbsolute7, relative as relative2, resolve as resolve10 } from "node:path";
21270
+ import { lstatSync as lstatSync10, readFileSync as readFileSync12 } from "node:fs";
21271
+ import { isAbsolute as isAbsolute7, relative as relative2, resolve as resolve11 } from "node:path";
20875
21272
 
20876
21273
  // src/workload-trust-sync.ts
20877
- import { lstatSync as lstatSync9, readFileSync as readFileSync10 } from "node:fs";
20878
- import { isAbsolute as isAbsolute6, resolve as resolve9 } from "node:path";
21274
+ import { lstatSync as lstatSync9, readFileSync as readFileSync11 } from "node:fs";
21275
+ import { isAbsolute as isAbsolute6, resolve as resolve10 } from "node:path";
20879
21276
  import { createHash as createHash8 } from "node:crypto";
20880
21277
  function prepareWorkloadTrustSynchronization(filename2) {
20881
21278
  try {
20882
21279
  if (!isAbsolute6(filename2)) throw new Error();
20883
21280
  const metadata = lstatSync9(filename2);
20884
21281
  if (!metadata.isFile() || metadata.isSymbolicLink() || metadata.nlink !== 1 || metadata.size > 65536) throw new Error();
20885
- const bytes = readFileSync10(filename2);
21282
+ const bytes = readFileSync11(filename2);
20886
21283
  if (bytes.length > 65536) throw new Error();
20887
21284
  const value = JSON.parse(new TextDecoder("utf8", { fatal: true }).decode(bytes));
20888
21285
  const allowed = ["controlPlaneUrl", "agentId", "expectedScope", "managementIssuer", "managementAudience", "managementPublicKeyPem", "credentialFile", "trustFile", "stateFile", "intervalSeconds"];
20889
21286
  if (!value || typeof value !== "object" || Array.isArray(value) || Object.keys(value).some((name2) => !allowed.includes(name2)) || typeof value.credentialFile !== "string" || !isAbsolute6(value.credentialFile) || typeof value.trustFile !== "string" || !isAbsolute6(value.trustFile) || typeof value.stateFile !== "string" || !isAbsolute6(value.stateFile)) throw new Error();
20890
- const credentialFile = resolve9(value.credentialFile), trustFile = resolve9(value.trustFile), stateFile = resolve9(value.stateFile);
21287
+ const credentialFile = resolve10(value.credentialFile), trustFile = resolve10(value.trustFile), stateFile = resolve10(value.stateFile);
20891
21288
  const comparison = (filename3) => process.platform === "win32" ? filename3.toLowerCase() : filename3;
20892
21289
  if ([trustFile, stateFile, stateFile + ".lock", stateFile + ".delivery.lock"].map(comparison).includes(comparison(credentialFile))) throw new Error();
20893
21290
  const intervalSeconds = value.intervalSeconds ?? 30;
@@ -20895,7 +21292,7 @@ function prepareWorkloadTrustSynchronization(filename2) {
20895
21292
  const credential = () => {
20896
21293
  const metadata2 = lstatSync9(credentialFile);
20897
21294
  if (!metadata2.isFile() || metadata2.isSymbolicLink() || metadata2.nlink !== 1 || metadata2.size > 256 || process.platform !== "win32" && (metadata2.uid !== process.getuid?.() || (metadata2.mode & 63) !== 0)) throw new Error("Management credential unavailable");
20898
- const bytes2 = readFileSync10(credentialFile);
21295
+ const bytes2 = readFileSync11(credentialFile);
20899
21296
  if (bytes2.length > 256) throw new Error("Management credential unavailable");
20900
21297
  return new TextDecoder("utf8", { fatal: true }).decode(bytes2).trim();
20901
21298
  };
@@ -20953,7 +21350,7 @@ async function workloadTrustSynchronization(args2, settings = {}) {
20953
21350
  function prepareLocalJobTrustRenewal(root, filename2, mount) {
20954
21351
  try {
20955
21352
  if (!filename2 || isAbsolute7(filename2)) throw new Error();
20956
- const configurationFile = resolve10(root, filename2);
21353
+ const configurationFile = resolve11(root, filename2);
20957
21354
  assertLocalStatePath(root, configurationFile);
20958
21355
  const configured = prepareWorkloadTrustSynchronization(configurationFile);
20959
21356
  const { credential, ...options } = configured.options;
@@ -20967,8 +21364,8 @@ function prepareLocalJobTrustRenewal(root, filename2, mount) {
20967
21364
  throw new Error("Invalid reviewed native worker trust renewal; preserve trust and state and review explicitly");
20968
21365
  }
20969
21366
  }
20970
- function createLocalJobTrustRenewal(root, mounts, settings = {}, dependencies = { createHash: createHash9, lstatSync: lstatSync10, readFileSync: readFileSync11, isAbsolute: isAbsolute7, relative: relative2, resolve: resolve10, createPersistentApplicationAuthProvider, synchronizeApplicationAuthTrustWithDigest }) {
20971
- const { createHash: createHash16, lstatSync: lstatSync20, readFileSync: readFileSync25, isAbsolute: isAbsolute17, relative: relative11, resolve: resolve24, createPersistentApplicationAuthProvider: createPersistentApplicationAuthProvider2, synchronizeApplicationAuthTrustWithDigest: synchronizeApplicationAuthTrustWithDigest2 } = dependencies;
21367
+ function createLocalJobTrustRenewal(root, mounts, settings = {}, dependencies = { createHash: createHash9, lstatSync: lstatSync10, readFileSync: readFileSync12, isAbsolute: isAbsolute7, relative: relative2, resolve: resolve11, createPersistentApplicationAuthProvider, synchronizeApplicationAuthTrustWithDigest }) {
21368
+ const { createHash: createHash16, lstatSync: lstatSync19, readFileSync: readFileSync25, isAbsolute: isAbsolute17, relative: relative11, resolve: resolve24, createPersistentApplicationAuthProvider: createPersistentApplicationAuthProvider2, synchronizeApplicationAuthTrustWithDigest: synchronizeApplicationAuthTrustWithDigest2 } = dependencies;
20972
21369
  const key = (filename2) => process.platform === "win32" ? resolve24(filename2).toLowerCase() : resolve24(filename2);
20973
21370
  const groups = [];
20974
21371
  for (const mount of mounts) {
@@ -20988,9 +21385,9 @@ function createLocalJobTrustRenewal(root, mounts, settings = {}, dependencies =
20988
21385
  const read = (filename2, maximum, privateFile2 = false) => {
20989
21386
  for (let current = resolve24(filename2); current !== root; current = resolve24(current, "..")) {
20990
21387
  const part = relative11(root, current);
20991
- if (part === ".." || part.startsWith("../") || part.startsWith("..\\") || isAbsolute17(part) || lstatSync20(current).isSymbolicLink()) throw new Error();
21388
+ if (part === ".." || part.startsWith("../") || part.startsWith("..\\") || isAbsolute17(part) || lstatSync19(current).isSymbolicLink()) throw new Error();
20992
21389
  }
20993
- const metadata = lstatSync20(filename2);
21390
+ const metadata = lstatSync19(filename2);
20994
21391
  if (!metadata.isFile() || metadata.nlink !== 1 || metadata.size > maximum || privateFile2 && process.platform !== "win32" && (metadata.uid !== process.getuid?.() || (metadata.mode & 63) !== 0)) throw new Error();
20995
21392
  const bytes = readFileSync25(filename2);
20996
21393
  if (bytes.length > maximum) throw new Error();
@@ -21073,11 +21470,11 @@ function prepareLocalJobWorker(root, directory2, artifacts, manifest, authFile,
21073
21470
  if (trustSyncFile !== void 0 && authFile === void 0) throw new Error("Native worker trust renewal requires explicit reviewed auth mounts");
21074
21471
  const authTrust = authFile === void 0 ? void 0 : prepareLocalJobAuth(root, authFile);
21075
21472
  if (authTrust && trustSyncFile !== void 0) authTrust.renewal = prepareLocalJobTrustRenewal(root, trustSyncFile, authTrust);
21076
- const workerFile = join8(resolve11(root, directory2), "workload.mjs"), metadataFile = join8(resolve11(root, directory2), "artifact.json");
21473
+ const workerFile = join9(resolve12(root, directory2), "workload.mjs"), metadataFile = join9(resolve12(root, directory2), "artifact.json");
21077
21474
  for (const filename2 of [workerFile, metadataFile]) assertLocalStatePath(root, filename2);
21078
21475
  if (!lstatSync11(workerFile).isFile() || lstatSync11(workerFile).size > 16777216 || !lstatSync11(metadataFile).isFile() || lstatSync11(metadataFile).size > 65536) throw new Error("Invalid bounded native worker artifact");
21079
- const metadata = JSON.parse(readFileSync12(metadataFile, "utf8"));
21080
- const bundle = readFileSync12(workerFile);
21476
+ const metadata = JSON.parse(readFileSync13(metadataFile, "utf8"));
21477
+ const bundle = readFileSync13(workerFile);
21081
21478
  const actual = createHash10("sha256").update(bundle).digest("hex");
21082
21479
  const scheduleDiscovery = bundle.subarray(0, 100).toString("utf8").startsWith('var __backifyWorkerProtocols = ["hcr-v1","hcr-schedules-v1"];\n');
21083
21480
  if (!metadata || metadata.schemaVersion !== 1 || metadata.kind !== "worker" || metadata.artifactVersion !== actual || metadata.manifestVersion !== createHash10("sha256").update(JSON.stringify(manifest)).digest("hex")) throw new Error("Native worker kind, bundle or manifest pin does not match the reviewed artifact");
@@ -21088,28 +21485,28 @@ function prepareLocalJobWorker(root, directory2, artifacts, manifest, authFile,
21088
21485
  }
21089
21486
  function readLocalJobArtifacts(root, filename2) {
21090
21487
  if (!filename2 || isAbsolute8(filename2)) throw new Error("Job artifact admission requires a repository-relative reviewed JSON file");
21091
- const path = resolve11(root, filename2);
21488
+ const path = resolve12(root, filename2);
21092
21489
  assertLocalStatePath(root, path);
21093
21490
  if (!lstatSync11(path).isFile() || lstatSync11(path).size > 16384) throw new Error("Reviewed job artifact admission exceeds supported bounds");
21094
- return validateLocalJobArtifacts(JSON.parse(readFileSync12(path, "utf8")));
21491
+ return validateLocalJobArtifacts(JSON.parse(readFileSync13(path, "utf8")));
21095
21492
  }
21096
- function createLocalJobExecutor(options, dependencies = { spawn: spawn2, createHash: createHash10, lstatSync: lstatSync11, readFileSync: readFileSync12, isAbsolute: isAbsolute8, relative: relative3, resolve: resolve11, validateWorkloadJobSchedules, createPersistentApplicationAuthProvider }) {
21097
- const { spawn: spawn6, createHash: createHash16, lstatSync: lstatSync20, readFileSync: readFileSync25, isAbsolute: isAbsolute17, relative: relative11, resolve: resolve24, validateWorkloadJobSchedules: validateWorkloadJobSchedules2, createPersistentApplicationAuthProvider: createPersistentApplicationAuthProvider2 } = dependencies;
21493
+ function createLocalJobExecutor(options, dependencies = { spawn: spawn2, createHash: createHash10, lstatSync: lstatSync11, readFileSync: readFileSync13, isAbsolute: isAbsolute8, relative: relative3, resolve: resolve12, validateWorkloadJobSchedules, createPersistentApplicationAuthProvider }) {
21494
+ const { spawn: spawn6, createHash: createHash16, lstatSync: lstatSync19, readFileSync: readFileSync25, isAbsolute: isAbsolute17, relative: relative11, resolve: resolve24, validateWorkloadJobSchedules: validateWorkloadJobSchedules2, createPersistentApplicationAuthProvider: createPersistentApplicationAuthProvider2 } = dependencies;
21098
21495
  const assertReady = () => {
21099
21496
  for (let current = resolve24(options.workerFile); current !== options.root; current = resolve24(current, "..")) {
21100
21497
  const part = relative11(options.root, current);
21101
- if (part === ".." || part.startsWith("../") || part.startsWith("..\\") || isAbsolute17(part) || lstatSync20(current).isSymbolicLink()) throw new Error("Native worker paths or pins changed");
21498
+ if (part === ".." || part.startsWith("../") || part.startsWith("..\\") || isAbsolute17(part) || lstatSync19(current).isSymbolicLink()) throw new Error("Native worker paths or pins changed");
21102
21499
  }
21103
- if (!lstatSync20(options.workerFile).isFile() || lstatSync20(options.workerFile).size > 16777216 || createHash16("sha256").update(readFileSync25(options.workerFile)).digest("hex") !== options.artifact.artifactVersion) throw new Error("Native worker paths or pins changed");
21500
+ if (!lstatSync19(options.workerFile).isFile() || lstatSync19(options.workerFile).size > 16777216 || createHash16("sha256").update(readFileSync25(options.workerFile)).digest("hex") !== options.artifact.artifactVersion) throw new Error("Native worker paths or pins changed");
21104
21501
  if (options.authTrust) {
21105
21502
  try {
21106
21503
  const mount = options.authTrust;
21107
21504
  for (const path of [mount.trustFile, mount.stateFile]) {
21108
21505
  for (let current = resolve24(path); current !== options.root; current = resolve24(current, "..")) {
21109
21506
  const part = relative11(options.root, current);
21110
- if (part === ".." || part.startsWith("../") || part.startsWith("..\\") || isAbsolute17(part) || lstatSync20(current).isSymbolicLink()) throw new Error();
21507
+ if (part === ".." || part.startsWith("../") || part.startsWith("..\\") || isAbsolute17(part) || lstatSync19(current).isSymbolicLink()) throw new Error();
21111
21508
  }
21112
- const metadata = lstatSync20(path);
21509
+ const metadata = lstatSync19(path);
21113
21510
  if (!metadata.isFile() || metadata.nlink !== 1 || metadata.size > (path === mount.trustFile ? 131072 : 2048)) throw new Error();
21114
21511
  }
21115
21512
  const bytes = readFileSync25(mount.trustFile);
@@ -21486,9 +21883,9 @@ process.on("SIGTERM", stop); process.on("SIGINT", stop); process.once("disconnec
21486
21883
 
21487
21884
  // src/local-frontend.ts
21488
21885
  import { spawn as spawn3 } from "node:child_process";
21489
- import { readFileSync as readFileSync14, realpathSync as realpathSync3, existsSync as existsSync9, statSync } from "node:fs";
21886
+ import { readFileSync as readFileSync15, realpathSync as realpathSync3, existsSync as existsSync9, statSync } from "node:fs";
21490
21887
  import { createRequire as createRequire3 } from "node:module";
21491
- import { dirname as dirname10, isAbsolute as isAbsolute10, join as join10, relative as relative5, resolve as resolve13 } from "node:path";
21888
+ import { dirname as dirname10, isAbsolute as isAbsolute10, join as join11, relative as relative5, resolve as resolve14 } from "node:path";
21492
21889
  import { pathToFileURL } from "node:url";
21493
21890
 
21494
21891
  // src/local-frontend-guard.ts
@@ -21555,21 +21952,21 @@ await server.listen();
21555
21952
  `;
21556
21953
 
21557
21954
  // src/local-static-frontend.ts
21558
- import { createServer as createServer3 } from "node:http";
21559
- import { lstatSync as lstatSync12, readFileSync as readFileSync13, realpathSync as realpathSync2, watch } from "node:fs";
21560
- import { extname as extname2, isAbsolute as isAbsolute9, join as join9, relative as relative4, resolve as resolve12, sep as sep4 } from "node:path";
21955
+ import { createServer as createServer4 } from "node:http";
21956
+ import { lstatSync as lstatSync12, readFileSync as readFileSync14, realpathSync as realpathSync2, watch } from "node:fs";
21957
+ import { extname as extname2, isAbsolute as isAbsolute9, join as join10, relative as relative4, resolve as resolve13, sep as sep4 } from "node:path";
21561
21958
  var contentTypes = { ".html": "text/html; charset=utf-8", ".js": "text/javascript; charset=utf-8", ".mjs": "text/javascript; charset=utf-8", ".css": "text/css; charset=utf-8", ".json": "application/json", ".txt": "text/plain; charset=utf-8", ".svg": "image/svg+xml", ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".gif": "image/gif", ".webp": "image/webp", ".ico": "image/x-icon", ".woff": "font/woff", ".woff2": "font/woff2", ".ttf": "font/ttf" };
21562
21959
  var publicParts = (parts) => parts.every((part) => part.length > 0 && !part.startsWith(".") && !part.includes(":") && !part.includes("\\") && !part.includes("\0") && !["node_modules", "__backify"].includes(part.toLowerCase()));
21563
21960
  function publicFile(directory2, pathname) {
21564
21961
  const parts = pathname.split("/").slice(1);
21565
21962
  if (parts.at(-1) === "") parts[parts.length - 1] = "index.html";
21566
21963
  if (!publicParts(parts)) throw new Error("refused");
21567
- const filename2 = resolve12(directory2, ...parts), part = relative4(directory2, filename2);
21964
+ const filename2 = resolve13(directory2, ...parts), part = relative4(directory2, filename2);
21568
21965
  if (part === ".." || part.startsWith(".." + sep4) || isAbsolute9(part) || !contentTypes[extname2(filename2).toLowerCase()]) throw new Error("refused");
21569
21966
  let current = directory2;
21570
21967
  if (lstatSync12(current).isSymbolicLink() || realpathSync2(current) !== directory2) throw new Error("refused");
21571
21968
  for (const segment of parts) {
21572
- current = join9(current, segment);
21969
+ current = join10(current, segment);
21573
21970
  if (lstatSync12(current).isSymbolicLink()) throw new Error("refused");
21574
21971
  }
21575
21972
  const stat = lstatSync12(filename2);
@@ -21587,7 +21984,7 @@ async function startLocalStaticFrontend(directory2, port, backendUrl) {
21587
21984
  const watcher = watch(directory2, { recursive: true }, (_, filename2) => {
21588
21985
  if (filename2 && publicParts(filename2.toString().split(/[\\/]/)) && contentTypes[extname2(filename2.toString()).toLowerCase()]) revision++;
21589
21986
  });
21590
- const server = createServer3((request, response) => {
21987
+ const server = createServer4((request, response) => {
21591
21988
  const send = (status, type, body) => {
21592
21989
  response.writeHead(status, { "content-type": type, "cache-control": "no-store", "x-content-type-options": "nosniff", "content-length": Buffer.byteLength(body) });
21593
21990
  response.end(request.method === "HEAD" ? void 0 : body);
@@ -21600,7 +21997,7 @@ async function startLocalStaticFrontend(directory2, port, backendUrl) {
21600
21997
  if (pathname === "/__backify/revision") return send(200, "text/plain", String(revision));
21601
21998
  if (pathname === "/__backify/config.json") return send(200, "application/json", JSON.stringify({ backendUrl: backendUrl ?? null }));
21602
21999
  const filename2 = publicFile(directory2, pathname);
21603
- const content = readFileSync13(filename2);
22000
+ const content = readFileSync14(filename2);
21604
22001
  if (content.length > 5242880) throw new Error("refused");
21605
22002
  const extension = extname2(filename2).toLowerCase();
21606
22003
  const body = extension === ".html" ? content.toString("utf8") + '\n<script src="/__backify/reload.js?revision=' + revision + '"></script>\n' : content;
@@ -21643,24 +22040,24 @@ function prepareLocalFrontend(root, options, privateFiles = []) {
21643
22040
  if (options.frontendPort !== void 0) throw new Error("Frontend port requires an explicit frontend directory");
21644
22041
  return void 0;
21645
22042
  }
21646
- const directory2 = realpathSync3(resolve13(root, options.frontend));
22043
+ const directory2 = realpathSync3(resolve14(root, options.frontend));
21647
22044
  const part = relative5(realpathSync3(root), directory2);
21648
22045
  if (part === ".." || part.startsWith("../") || part.startsWith("..\\") || isAbsolute10(part) || !statSync(directory2).isDirectory()) throw new Error("Frontend must be a directory inside this repository");
21649
22046
  if (options.frontendAdapter === "static") {
21650
22047
  if (part && part.split(/[\\/]/).some((segment) => segment.startsWith(".") || segment.toLowerCase() === "node_modules")) throw new Error("Static frontend must not use a private state or dependency directory");
21651
22048
  return prepareLocalStaticFrontend(directory2);
21652
22049
  }
21653
- if (!existsSync9(join10(directory2, "package.json"))) throw new Error("Frontend requires an existing package.json and installed Vite");
21654
- const require3 = createRequire3(join10(directory2, "package.json"));
22050
+ if (!existsSync9(join11(directory2, "package.json"))) throw new Error("Frontend requires an existing package.json and installed Vite");
22051
+ const require3 = createRequire3(join11(directory2, "package.json"));
21655
22052
  let packagePath;
21656
22053
  try {
21657
22054
  packagePath = require3.resolve("vite/package.json");
21658
22055
  } catch {
21659
22056
  throw new Error("Frontend requires locally installed Vite; Backify does not install dependencies automatically");
21660
22057
  }
21661
- const metadata = JSON.parse(readFileSync14(packagePath, "utf8"));
22058
+ const metadata = JSON.parse(readFileSync15(packagePath, "utf8"));
21662
22059
  if (metadata.name !== "vite" || typeof metadata.bin?.vite !== "string") throw new Error("Installed Vite has no supported CLI entrypoint");
21663
- const executable = realpathSync3(resolve13(dirname10(packagePath), metadata.bin.vite));
22060
+ const executable = realpathSync3(resolve14(dirname10(packagePath), metadata.bin.vite));
21664
22061
  const executablePart = relative5(realpathSync3(dirname10(packagePath)), executable);
21665
22062
  if (executablePart === ".." || executablePart.startsWith("../") || executablePart.startsWith("..\\") || isAbsolute10(executablePart)) throw new Error("Vite CLI entrypoint must remain inside its package");
21666
22063
  const timeout = options.frontendStartupTimeoutMs ?? 3e4;
@@ -21722,8 +22119,8 @@ async function startLocalFrontend(prepared, port, backendUrl) {
21722
22119
  }
21723
22120
 
21724
22121
  // src/local-identity.ts
21725
- import { readFileSync as readFileSync15, statSync as statSync2 } from "node:fs";
21726
- import { resolve as resolve14 } from "node:path";
22122
+ import { readFileSync as readFileSync16, statSync as statSync2 } from "node:fs";
22123
+ import { resolve as resolve15 } from "node:path";
21727
22124
 
21728
22125
  // ../sdk/dist/local-identity.js
21729
22126
  import { createHash as createHash12, randomBytes as randomBytes4 } from "node:crypto";
@@ -21735,14 +22132,14 @@ function createLocalIdentityProvider(options) {
21735
22132
  serverOnly();
21736
22133
  if (typeof process !== "undefined" && process.env.NODE_ENV === "production")
21737
22134
  throw new Error("Local Backify identities must not run in production");
21738
- const uuid5 = (value) => typeof value === "string" && /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(value) && value !== "00000000-0000-0000-0000-000000000000";
22135
+ const uuid4 = (value) => typeof value === "string" && /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(value) && value !== "00000000-0000-0000-0000-000000000000";
21739
22136
  const text3 = (value, maximum) => typeof value === "string" && value.length > 0 && value.length <= maximum && !/[\x00-\x1f\x7f]/.test(value);
21740
- if (!options.scope || Object.keys(options.scope).length !== 3 || !uuid5(options.scope.organizationId) || !uuid5(options.scope.applicationId) || !uuid5(options.scope.environmentId) || !text3(options.organizationName, 200) || !Array.isArray(options.users) || options.users.length < 1 || options.users.length > 32 || !Array.isArray(options.requestOrigins) || options.requestOrigins.length < 1 || options.requestOrigins.length > 8)
22137
+ if (!options.scope || Object.keys(options.scope).length !== 3 || !uuid4(options.scope.organizationId) || !uuid4(options.scope.applicationId) || !uuid4(options.scope.environmentId) || !text3(options.organizationName, 200) || !Array.isArray(options.users) || options.users.length < 1 || options.users.length > 32 || !Array.isArray(options.requestOrigins) || options.requestOrigins.length < 1 || options.requestOrigins.length > 8)
21741
22138
  throw new Error("Invalid local identity configuration");
21742
22139
  const scope = { ...options.scope }, organizationName = options.organizationName;
21743
22140
  const users = /* @__PURE__ */ new Map();
21744
22141
  for (const user of options.users) {
21745
- if (!user || Object.keys(user).some((name2) => !["id", "displayName", "email", "roles"].includes(name2)) || !uuid5(user.id) || users.has(user.id) || !text3(user.displayName, 200) || user.email !== void 0 && !text3(user.email, 320))
22142
+ if (!user || Object.keys(user).some((name2) => !["id", "displayName", "email", "roles"].includes(name2)) || !uuid4(user.id) || users.has(user.id) || !text3(user.displayName, 200) || user.email !== void 0 && !text3(user.email, 320))
21746
22143
  throw new Error("Invalid local identity user");
21747
22144
  if (user.roles !== void 0 && (!Array.isArray(user.roles) || user.roles.length > 32 || user.roles.some((role) => !role || Object.keys(role).some((name2) => !["name", "permissions"].includes(name2)) || !text3(role.name, 100) || !Array.isArray(role.permissions) || role.permissions.length > 128 || role.permissions.some((permission) => !text3(permission, 100)) || new Set(role.permissions).size !== role.permissions.length) || new Set(user.roles.map((role) => role.name)).size !== user.roles.length))
21748
22145
  throw new Error("Invalid local identity roles");
@@ -21822,22 +22219,22 @@ function createLocalIdentityProvider(options) {
21822
22219
  }
21823
22220
 
21824
22221
  // src/local-identity.ts
21825
- import { randomUUID as randomUUID7 } from "node:crypto";
22222
+ import { randomUUID as randomUUID8 } from "node:crypto";
21826
22223
  function prepareLocalIdentity(root, filename2) {
21827
22224
  if (filename2 === void 0) return void 0;
21828
- const path = resolve14(root, filename2);
22225
+ const path = resolve15(root, filename2);
21829
22226
  assertLocalStatePath(root, path);
21830
22227
  if (!statSync2(path).isFile() || statSync2(path).size > 16384) throw new Error("Local identity profiles require a file at most 16 KiB");
21831
22228
  let input;
21832
22229
  try {
21833
- input = JSON.parse(readFileSync15(path, "utf8"));
22230
+ input = JSON.parse(readFileSync16(path, "utf8"));
21834
22231
  } catch {
21835
22232
  throw new Error("Invalid local identity profile JSON");
21836
22233
  }
21837
22234
  if (!input || typeof input !== "object" || Array.isArray(input) || Object.keys(input).some((name2) => !["version", "organizationName", "users"].includes(name2))) throw new Error("Invalid local identity profiles");
21838
22235
  const value = input;
21839
22236
  if (value.version !== 1) throw new Error("Invalid local identity profile version");
21840
- const identity = createLocalIdentityProvider({ scope: { organizationId: randomUUID7(), applicationId: randomUUID7(), environmentId: randomUUID7() }, organizationName: value.organizationName, users: value.users, requestOrigins: ["http://127.0.0.1:3000"] });
22237
+ const identity = createLocalIdentityProvider({ scope: { organizationId: randomUUID8(), applicationId: randomUUID8(), environmentId: randomUUID8() }, organizationName: value.organizationName, users: value.users, requestOrigins: ["http://127.0.0.1:3000"] });
21841
22238
  return { organizationName: value.organizationName, users: identity.profiles() };
21842
22239
  }
21843
22240
  function localIdentityCommand(args2) {
@@ -21863,17 +22260,17 @@ function localIdentityCommand(args2) {
21863
22260
  }
21864
22261
 
21865
22262
  // src/local-job-history.ts
21866
- import { lstatSync as lstatSync13, readFileSync as readFileSync16 } from "node:fs";
21867
- import { isAbsolute as isAbsolute11, resolve as resolve15 } from "node:path";
22263
+ import { lstatSync as lstatSync13, readFileSync as readFileSync17 } from "node:fs";
22264
+ import { isAbsolute as isAbsolute11, resolve as resolve16 } from "node:path";
21868
22265
  function prepareLocalJobHistory(root, filename2, artifacts, manifest, current) {
21869
22266
  if (filename2 === void 0) return [];
21870
22267
  const read = (filename3, maximum) => {
21871
22268
  if (typeof filename3 !== "string" || !filename3 || isAbsolute11(filename3)) throw new Error();
21872
- const path = resolve15(root, filename3);
22269
+ const path = resolve16(root, filename3);
21873
22270
  assertLocalStatePath(root, path);
21874
22271
  const metadata = lstatSync13(path);
21875
22272
  if (!metadata.isFile() || metadata.isSymbolicLink() || metadata.nlink !== 1 || metadata.size > maximum) throw new Error();
21876
- const bytes = readFileSync16(path);
22273
+ const bytes = readFileSync17(path);
21877
22274
  if (bytes.length > maximum) throw new Error();
21878
22275
  return new TextDecoder("utf8", { fatal: true }).decode(bytes);
21879
22276
  };
@@ -21919,30 +22316,30 @@ function prepareLocalJobHistory(root, filename2, artifacts, manifest, current) {
21919
22316
  }
21920
22317
 
21921
22318
  // src/local-secrets.ts
21922
- import { createCipheriv, createDecipheriv, randomBytes as randomBytes5, randomUUID as randomUUID8 } from "node:crypto";
21923
- import { closeSync as closeSync3, existsSync as existsSync10, fsyncSync as fsyncSync3, lstatSync as lstatSync14, mkdirSync as mkdirSync5, openSync as openSync3, readFileSync as readFileSync17, realpathSync as realpathSync4, writeFileSync as writeFileSync9 } from "node:fs";
21924
- import { dirname as dirname11, isAbsolute as isAbsolute12, join as join11, relative as relative6, resolve as resolve16 } from "node:path";
22319
+ import { createCipheriv, createDecipheriv, randomBytes as randomBytes5, randomUUID as randomUUID9 } from "node:crypto";
22320
+ import { closeSync as closeSync3, existsSync as existsSync10, fsyncSync as fsyncSync3, lstatSync as lstatSync14, mkdirSync as mkdirSync5, openSync as openSync3, readFileSync as readFileSync18, realpathSync as realpathSync4, writeFileSync as writeFileSync10 } from "node:fs";
22321
+ import { dirname as dirname11, isAbsolute as isAbsolute12, join as join12, relative as relative6, resolve as resolve17 } from "node:path";
21925
22322
  var maximumBytes2 = 1048576;
21926
22323
  var secretName = /^[A-Z][A-Z0-9_]{0,127}$/;
21927
22324
  var failure = () => new Error("Local secret vault unavailable or invalid; review the vault and external key privately");
21928
22325
  function vaultPath(root) {
21929
- return join11(realpathSync4(root), ".backify", "dev", "secrets.enc.json");
22326
+ return join12(realpathSync4(root), ".backify", "dev", "secrets.enc.json");
21930
22327
  }
21931
22328
  function inside(root, filename2) {
21932
22329
  const part = relative6(root, filename2);
21933
22330
  return part !== ".." && !part.startsWith("../") && !part.startsWith("..\\") && !isAbsolute12(part);
21934
22331
  }
21935
22332
  function privateFile(filename2, limit) {
21936
- for (let current = resolve16(filename2); ; current = dirname11(current)) {
22333
+ for (let current = resolve17(filename2); ; current = dirname11(current)) {
21937
22334
  if (lstatSync14(current).isSymbolicLink()) throw failure();
21938
22335
  if (dirname11(current) === current) break;
21939
22336
  }
21940
22337
  const stat = lstatSync14(filename2);
21941
22338
  if (!stat.isFile() || stat.size > limit || stat.nlink !== 1 || process.platform !== "win32" && (stat.mode & 63) !== 0) throw failure();
21942
- return readFileSync17(filename2);
22339
+ return readFileSync18(filename2);
21943
22340
  }
21944
22341
  function externalKey(root, filename2) {
21945
- const keyFile = resolve16(filename2);
22342
+ const keyFile = resolve17(filename2);
21946
22343
  if (inside(realpathSync4(root), keyFile) || inside(realpathSync4(root), realpathSync4(keyFile))) throw failure();
21947
22344
  const encoded = privateFile(keyFile, 64).toString("utf8");
21948
22345
  if (!/^[a-f0-9]{64}$/.test(encoded)) throw failure();
@@ -21971,17 +22368,17 @@ function encrypt(root, application, key, secrets) {
21971
22368
  function writePrivate2(filename2, value) {
21972
22369
  const descriptor2 = openSync3(filename2, "wx", 384);
21973
22370
  try {
21974
- writeFileSync9(descriptor2, value);
22371
+ writeFileSync10(descriptor2, value);
21975
22372
  fsyncSync3(descriptor2);
21976
22373
  } finally {
21977
22374
  closeSync3(descriptor2);
21978
22375
  }
21979
22376
  }
21980
22377
  function ensureIgnored(root) {
21981
- const filename2 = join11(root, ".gitignore");
22378
+ const filename2 = join12(root, ".gitignore");
21982
22379
  assertLocalStatePath(root, filename2);
21983
- const current = existsSync10(filename2) ? readFileSync17(filename2, "utf8") : "";
21984
- if (!current.split(/\r?\n/).some((line) => line.trim() === ".backify/")) writeFileSync9(filename2, current + (current && !current.endsWith("\n") ? "\n" : "") + ".backify/\n");
22380
+ const current = existsSync10(filename2) ? readFileSync18(filename2, "utf8") : "";
22381
+ if (!current.split(/\r?\n/).some((line) => line.trim() === ".backify/")) writeFileSync10(filename2, current + (current && !current.endsWith("\n") ? "\n" : "") + ".backify/\n");
21985
22382
  }
21986
22383
  function readLocalSecrets(root, application, keyFile) {
21987
22384
  const filename2 = vaultPath(root);
@@ -22014,7 +22411,7 @@ function readLocalSecrets(root, application, keyFile) {
22014
22411
  }
22015
22412
  }
22016
22413
  function initializeLocalSecrets(root, application, keyFile) {
22017
- const filename2 = vaultPath(root), external = resolve16(keyFile);
22414
+ const filename2 = vaultPath(root), external = resolve17(keyFile);
22018
22415
  assertLocalStatePath(root, filename2);
22019
22416
  if (existsSync10(filename2) || existsSync10(external)) throw new Error("Local secret initialization never overwrites an existing vault or key");
22020
22417
  if (inside(realpathSync4(root), external) || inside(realpathSync4(root), realpathSync4(dirname11(external)))) throw new Error("Local secret key must be outside the repository in an existing private directory");
@@ -22048,7 +22445,7 @@ function setLocalSecret(root, application, keyFile, name2, value) {
22048
22445
  const secrets = readLocalSecrets(root, application, keyFile);
22049
22446
  secrets[name2] = value;
22050
22447
  key = externalKey(root, keyFile);
22051
- const temporary = filename2 + "." + randomUUID8() + ".tmp";
22448
+ const temporary = filename2 + "." + randomUUID9() + ".tmp";
22052
22449
  assertLocalStatePath(root, temporary);
22053
22450
  writePrivate2(temporary, encrypt(root, application, key, secrets));
22054
22451
  renameLocalFile(temporary, filename2);
@@ -22085,10 +22482,10 @@ async function localSecretsCommand(args2, root, application, input = process.std
22085
22482
 
22086
22483
  // src/local-development.ts
22087
22484
  function localManifest(root = process.cwd()) {
22088
- const filename2 = join12(root, "backify.yaml");
22485
+ const filename2 = join13(root, "backify.yaml");
22089
22486
  if (!existsSync11(filename2)) throw new Error("Create backify.yaml with version, application, runtime and explicit capabilities before running backify dev");
22090
- const manifest = parseApplicationManifest(readFileSync18(filename2, "utf8"));
22091
- const entry = resolve17(root, manifest.runtime.entrypoint);
22487
+ const manifest = parseApplicationManifest(readFileSync19(filename2, "utf8"));
22488
+ const entry = resolve18(root, manifest.runtime.entrypoint);
22092
22489
  if (!existsSync11(entry) || !inside2(root, realpathSync5(entry))) throw new Error("Runtime entrypoint must exist inside this repository");
22093
22490
  const discovered = analyzeSources(repositorySources(root));
22094
22491
  const diagnostics = manifestDiagnostics(manifest, Object.keys(discovered.capabilities), discovered.capabilities.auth?.configuration);
@@ -22100,12 +22497,12 @@ function inside2(root, path) {
22100
22497
  return part !== ".." && !part.startsWith(".." + (process.platform === "win32" ? "\\" : "/")) && !isAbsolute13(part);
22101
22498
  }
22102
22499
  function sessionPath(root) {
22103
- return join12(root, ".backify", "dev", "session.json");
22500
+ return join13(root, ".backify", "dev", "session.json");
22104
22501
  }
22105
22502
  async function localRequest(path, input, root = process.cwd()) {
22106
22503
  if (!/^\/v1\/[a-z/-]+$/.test(path)) throw new Error("Invalid local command path");
22107
22504
  if (!existsSync11(sessionPath(root))) throw new Error("Start backify dev before using local commands");
22108
- const session = JSON.parse(readFileSync18(sessionPath(root), "utf8"));
22505
+ const session = JSON.parse(readFileSync19(sessionPath(root), "utf8"));
22109
22506
  if (session.version !== 1 || !Number.isInteger(session.port) || session.port < 1 || session.port > 65535 || !/^[a-f0-9]{64}$/.test(session.token)) throw new Error("Invalid local session");
22110
22507
  const response = await fetch("http://127.0.0.1:" + session.port + path, { method: input === void 0 ? "GET" : "POST", headers: { authorization: "Bearer " + session.token, "content-type": "application/json" }, body: input === void 0 ? void 0 : JSON.stringify(input), redirect: "error", signal: AbortSignal.timeout(35e3) });
22111
22508
  if (!response.ok) {
@@ -22138,7 +22535,7 @@ async function startLocalDevelopment(options = {}) {
22138
22535
  if (options.jobTrustSyncFile !== void 0 && options.jobAuthFile === void 0) throw new Error("Native worker trust renewal requires explicit reviewed auth mounts");
22139
22536
  if (options.jobHistoryFile !== void 0 && options.jobWorkerDirectory === void 0) throw new Error("Historical workers require paired reviewed job artifacts and current worker");
22140
22537
  if (options.jobAuthFile !== void 0 && options.identityUsers !== void 0) throw new Error("Reviewed worker issuer trust cannot be mixed with local identity fixtures");
22141
- const root = resolve17(options.root ?? process.cwd());
22538
+ const root = resolve18(options.root ?? process.cwd());
22142
22539
  const manifest = localManifest(root);
22143
22540
  const validateSecretIntent = (values, intent = manifest) => {
22144
22541
  if (Object.keys(values).length && (!intent.capabilities.secrets || intent.capabilities.secrets.enabled === false)) throw new Error("Encrypted local secrets require enabled capabilities.secrets");
@@ -22155,15 +22552,15 @@ async function startLocalDevelopment(options = {}) {
22155
22552
  createLocalJobTrustRenewal(root, authMounts);
22156
22553
  const identityProfiles = prepareLocalIdentity(root, options.identityUsers);
22157
22554
  if (identityProfiles && (!manifest.capabilities.auth || manifest.capabilities.auth.enabled === false || options.backendPort === void 0)) throw new Error("Explicit local identities require capabilities.auth and --backend-port");
22158
- const preparedFrontend = prepareLocalFrontend(root, options, options.localSecretsKey ? [realpathSync5(resolve17(options.localSecretsKey))] : []);
22159
- const ignorePath = join12(root, ".gitignore");
22555
+ const preparedFrontend = prepareLocalFrontend(root, options, options.localSecretsKey ? [realpathSync5(resolve18(options.localSecretsKey))] : []);
22556
+ const ignorePath = join13(root, ".gitignore");
22160
22557
  if (existsSync11(ignorePath) && lstatSync15(ignorePath).isSymbolicLink()) throw new Error("Local development cannot update a symlinked .gitignore");
22161
- const ignore = existsSync11(ignorePath) ? readFileSync18(ignorePath, "utf8") : "";
22162
- if (!ignore.split(/\r?\n/).some((line) => line.trim() === ".backify/")) writeFileSync10(ignorePath, ignore + (ignore.endsWith("\n") || !ignore ? "" : "\n") + ".backify/\n");
22558
+ const ignore = existsSync11(ignorePath) ? readFileSync19(ignorePath, "utf8") : "";
22559
+ if (!ignore.split(/\r?\n/).some((line) => line.trim() === ".backify/")) writeFileSync11(ignorePath, ignore + (ignore.endsWith("\n") || !ignore ? "" : "\n") + ".backify/\n");
22163
22560
  if (options.port !== void 0 && (!Number.isInteger(options.port) || options.port < 0 || options.port > 65535)) throw new Error("Dashboard port must be 0-65535");
22164
- const directory2 = join12(root, ".backify", "dev");
22561
+ const directory2 = join13(root, ".backify", "dev");
22165
22562
  assertLocalStatePath(root, directory2);
22166
- for (const filename2 of ["session.json", "session.json.tmp", "worker.mjs", "worker.mjs.map", "state.json", "state.json.tmp"]) assertLocalStatePath(root, join12(directory2, filename2));
22563
+ for (const filename2 of ["session.json", "session.json.tmp", "worker.mjs", "worker.mjs.map", "state.json", "state.json.tmp"]) assertLocalStatePath(root, join13(directory2, filename2));
22167
22564
  mkdirSync6(directory2, { recursive: true });
22168
22565
  if (!inside2(root, realpathSync5(directory2))) throw new Error("Local state directory must remain inside this repository");
22169
22566
  if (existsSync11(sessionPath(root))) {
@@ -22197,14 +22594,14 @@ async function startLocalDevelopment(options = {}) {
22197
22594
  throw error;
22198
22595
  }
22199
22596
  const token = randomBytes6(32).toString("hex");
22200
- const identityScope = services?.identityScope ?? { organizationId: randomUUID9(), applicationId: randomUUID9(), environmentId: randomUUID9() };
22597
+ const identityScope = services?.identityScope ?? { organizationId: randomUUID10(), applicationId: randomUUID10(), environmentId: randomUUID10() };
22201
22598
  const workerEnvironment = (worker) => {
22202
22599
  if (!worker.authTrust) return worker;
22203
22600
  const { renewal, ...authTrust } = worker.authTrust;
22204
22601
  return { ...worker, authTrust };
22205
22602
  };
22206
22603
  const identityEnvironment = () => ({ BACKIFY_LOCAL_IDENTITY: identityProfiles ? JSON.stringify({ ...identityProfiles, scope: identityScope, requestOrigins: [backendUrl, frontend?.url].filter(Boolean) }) : "", BACKIFY_LOCAL_JOB_WORKER: jobWorker ? JSON.stringify({ ...workerEnvironment(jobWorker), scope: identityScope, historicalWorkers: historicalWorkers.map(workerEnvironment) }) : "", BACKIFY_LOCAL_JOBS: services?.jobs ? "postgres-jobs" : "snapshot-emulator" });
22207
- const outfile = join12(directory2, "worker.mjs");
22604
+ const outfile = join13(directory2, "worker.mjs");
22208
22605
  let child;
22209
22606
  const trustRenewal = createLocalJobTrustRenewal(root, authMounts, { onFailure: () => console.error("Native worker trust renewal unavailable; existing validity and pin guards remain enforced."), onUpdate: () => {
22210
22607
  if (child?.connected) child.send({ type: "trust-renewed", workers: activeWorkers.filter((worker) => worker.authTrust).map((worker) => ({ artifactVersion: worker.artifact.artifactVersion, revision: worker.authTrust.revision, trustDigest: worker.authTrust.trustDigest })) }, (error) => {
@@ -22242,8 +22639,8 @@ async function startLocalDevelopment(options = {}) {
22242
22639
  }
22243
22640
  await stopChild(child);
22244
22641
  if (stopping) return;
22245
- const version = createHash13("sha256").update(readFileSync18(outfile)).update(services?.configurationFingerprint ?? "lightweight").digest("hex");
22246
- const worker = spawn4(process.execPath, [outfile], { cwd: root, windowsHide: true, stdio: ["ignore", 2, 2, "ipc"], env: { ...process.env, ...identityEnvironment(), BACKIFY_LOCAL_SECRETS_IPC: "1", HOST: "127.0.0.1", ...backendPort === void 0 ? {} : { PORT: String(backendPort) }, BACKIFY_LOCAL_BACKEND_URL: backendUrl ?? "", BACKIFY_LOCAL_FRONTEND_URL: frontend?.url ?? "", BACKIFY_LOCAL_DATABASE_ENABLED: manifest.capabilities.database && manifest.capabilities.database.enabled !== false ? "1" : "0", BACKIFY_LOCAL_STORAGE_ENABLED: manifest.capabilities.storage && manifest.capabilities.storage.enabled !== false ? "1" : "0", BACKIFY_LOCAL_STORAGE_BUCKETS: JSON.stringify(manifest.capabilities.storage?.buckets?.map((bucket) => bucket.name) ?? (manifest.capabilities.storage ? ["default"] : [])), BACKIFY_LOCAL_TOKEN: token, BACKIFY_LOCAL_PORT: String(dashboardPort), BACKIFY_LOCAL_STATE: join12(directory2, "state.json"), BACKIFY_LOCAL_VERSION: version, BACKIFY_LOCAL_HCR_URL: services?.runtimeUrl ?? "", BACKIFY_LOCAL_WORKLOAD_TOKEN_PATH: services?.tokenPath ?? "", BACKIFY_LOCAL_DATABASE: services ? services.database ? "postgres" : "disabled" : "document-emulator", BACKIFY_LOCAL_EVENTS: services?.events ? "postgres-events" : services ? "disabled" : "snapshot-emulator", BACKIFY_LOCAL_STORAGE: services ? services.storage ? "filesystem" : "disabled" : "snapshot-emulator" } });
22642
+ const version = createHash13("sha256").update(readFileSync19(outfile)).update(services?.configurationFingerprint ?? "lightweight").digest("hex");
22643
+ const worker = spawn4(process.execPath, [outfile], { cwd: root, windowsHide: true, stdio: ["ignore", 2, 2, "ipc"], env: { ...process.env, ...identityEnvironment(), BACKIFY_LOCAL_SECRETS_IPC: "1", HOST: "127.0.0.1", ...backendPort === void 0 ? {} : { PORT: String(backendPort) }, BACKIFY_LOCAL_BACKEND_URL: backendUrl ?? "", BACKIFY_LOCAL_FRONTEND_URL: frontend?.url ?? "", BACKIFY_LOCAL_DATABASE_ENABLED: manifest.capabilities.database && manifest.capabilities.database.enabled !== false ? "1" : "0", BACKIFY_LOCAL_STORAGE_ENABLED: manifest.capabilities.storage && manifest.capabilities.storage.enabled !== false ? "1" : "0", BACKIFY_LOCAL_STORAGE_BUCKETS: JSON.stringify(manifest.capabilities.storage?.buckets?.map((bucket) => bucket.name) ?? (manifest.capabilities.storage ? ["default"] : [])), BACKIFY_LOCAL_TOKEN: token, BACKIFY_LOCAL_PORT: String(dashboardPort), BACKIFY_LOCAL_STATE: join13(directory2, "state.json"), BACKIFY_LOCAL_VERSION: version, BACKIFY_LOCAL_HCR_URL: services?.runtimeUrl ?? "", BACKIFY_LOCAL_WORKLOAD_TOKEN_PATH: services?.tokenPath ?? "", BACKIFY_LOCAL_DATABASE: services ? services.database ? "postgres" : "disabled" : "document-emulator", BACKIFY_LOCAL_EVENTS: services?.events ? "postgres-events" : services ? "disabled" : "snapshot-emulator", BACKIFY_LOCAL_STORAGE: services ? services.storage ? "filesystem" : "disabled" : "snapshot-emulator" } });
22247
22644
  child = worker;
22248
22645
  worker.send({ type: "local-secrets", secrets }, (error) => {
22249
22646
  if (error) {
@@ -22265,7 +22662,7 @@ async function startLocalDevelopment(options = {}) {
22265
22662
  workerReady = true;
22266
22663
  const session = { version: 1, port: message.port, token, pid: worker.pid };
22267
22664
  const temp = sessionPath(root) + ".tmp";
22268
- writeFileSync10(temp, JSON.stringify(session), { mode: 384 });
22665
+ writeFileSync11(temp, JSON.stringify(session), { mode: 384 });
22269
22666
  renameLocalFile(temp, sessionPath(root));
22270
22667
  const url = "http://127.0.0.1:" + message.port;
22271
22668
  options.onReady?.(url, { frontendUrl: frontend?.url, backendUrl });
@@ -22277,17 +22674,17 @@ async function startLocalDevelopment(options = {}) {
22277
22674
  });
22278
22675
  };
22279
22676
  try {
22280
- buildContext = await context2({ absWorkingDir: root, stdin: { contents: localWorkerSource(resolve17(root, manifest.runtime.entrypoint)), resolveDir: root, sourcefile: "backify-local-worker.ts", loader: "ts" }, bundle: true, platform: "node", format: "esm", target: "node20", outfile, sourcemap: true, banner: { js: 'import { createRequire as __backifyCreateRequire } from "node:module"; var require = __backifyCreateRequire(import.meta.url);' }, plugins: [{ name: "backify-local-lifecycle", setup(build3) {
22677
+ buildContext = await context2({ absWorkingDir: root, stdin: { contents: localWorkerSource(resolve18(root, manifest.runtime.entrypoint)), resolveDir: root, sourcefile: "backify-local-worker.ts", loader: "ts" }, bundle: true, platform: "node", format: "esm", target: "node20", outfile, sourcemap: true, banner: { js: 'import { createRequire as __backifyCreateRequire } from "node:module"; var require = __backifyCreateRequire(import.meta.url);' }, plugins: [{ name: "backify-local-lifecycle", setup(build3) {
22281
22678
  build3.onLoad({ filter: /./, namespace: "file" }, (input) => {
22282
- if (input.path !== resolve17(root, manifest.runtime.entrypoint)) return;
22679
+ if (input.path !== resolve18(root, manifest.runtime.entrypoint)) return;
22283
22680
  try {
22284
22681
  const updated = localManifest(root);
22285
22682
  if (services && JSON.stringify(updated.capabilities) !== JSON.stringify(manifest.capabilities)) throw new Error("Full-fidelity capability or migration intent changed; restart backify dev to review and apply it");
22286
22683
  if (updated.runtime.entrypoint !== manifest.runtime.entrypoint) throw new Error("Runtime entrypoint changed; restart backify dev");
22287
22684
  } catch (error) {
22288
- return { errors: [{ text: error instanceof Error ? error.message : "Manifest validation failed" }], watchFiles: [join12(root, "backify.yaml")] };
22685
+ return { errors: [{ text: error instanceof Error ? error.message : "Manifest validation failed" }], watchFiles: [join13(root, "backify.yaml")] };
22289
22686
  }
22290
- return { contents: readFileSync18(input.path, "utf8"), loader: input.path.endsWith(".tsx") ? "tsx" : /\.(ts|mts|cts)$/.test(input.path) ? "ts" : input.path.endsWith(".jsx") ? "jsx" : "js", watchFiles: [join12(root, "backify.yaml")] };
22687
+ return { contents: readFileSync19(input.path, "utf8"), loader: input.path.endsWith(".tsx") ? "tsx" : /\.(ts|mts|cts)$/.test(input.path) ? "ts" : input.path.endsWith(".jsx") ? "jsx" : "js", watchFiles: [join13(root, "backify.yaml")] };
22291
22688
  });
22292
22689
  build3.onEnd((result) => {
22293
22690
  if (result.errors.length) rejectStartup(new Error("Local application build failed"));
@@ -22344,8 +22741,8 @@ async function startLocalDevelopment(options = {}) {
22344
22741
  }
22345
22742
  }
22346
22743
  if (existsSync11(sessionPath(root))) {
22347
- const session = JSON.parse(readFileSync18(sessionPath(root), "utf8"));
22348
- if (session.token === token) unlinkSync4(sessionPath(root));
22744
+ const session = JSON.parse(readFileSync19(sessionPath(root), "utf8"));
22745
+ if (session.token === token) unlinkSync5(sessionPath(root));
22349
22746
  }
22350
22747
  };
22351
22748
  return {
@@ -22358,10 +22755,10 @@ async function startLocalDevelopment(options = {}) {
22358
22755
  }
22359
22756
  async function runLocalTests(root = process.cwd()) {
22360
22757
  const manifest = localManifest(root);
22361
- const project = JSON.parse(readFileSync18(join12(root, "package.json"), "utf8"));
22758
+ const project = JSON.parse(readFileSync19(join13(root, "package.json"), "utf8"));
22362
22759
  if (!project.scripts?.test) throw new Error("Add a test script to package.json so AI agents can run backify test");
22363
22760
  const result = await new Promise((resolveResult, reject) => {
22364
- const npmPath = process.platform === "win32" ? process.env.npm_execpath ?? join12(dirname12(process.execPath), "node_modules", "npm", "bin", "npm-cli.js") : void 0;
22761
+ const npmPath = process.platform === "win32" ? process.env.npm_execpath ?? join13(dirname12(process.execPath), "node_modules", "npm", "bin", "npm-cli.js") : void 0;
22365
22762
  if (npmPath && !existsSync11(npmPath)) {
22366
22763
  reject(new Error("Cannot locate npm-cli.js; run backify test through npx or npm"));
22367
22764
  return;
@@ -22389,7 +22786,7 @@ function digest3(contents) {
22389
22786
  }
22390
22787
  function packageDirectory(filename2) {
22391
22788
  for (let current = dirname13(filename2); ; current = dirname13(current)) {
22392
- if (existsSync12(join13(current, "package.json"))) return current;
22789
+ if (existsSync12(join14(current, "package.json"))) return current;
22393
22790
  if (dirname13(current) === current) throw new Error("Cannot locate an installed dependency package");
22394
22791
  }
22395
22792
  }
@@ -22471,11 +22868,11 @@ main().catch(() => finish({ schemaVersion: 1, status: "failed", error: "workload
22471
22868
  `.replace("__KIND__", JSON.stringify(kind)).replace("__CAPABILITIES__", JSON.stringify(capabilities)).replace("__AUTH_ENABLED__", String(capabilities.includes("auth"))).replace("__ENTRY__", JSON.stringify(entry));
22472
22869
  }
22473
22870
  async function prepareWorkload(options) {
22474
- const root = realpathSync6(resolve18(options.root ?? process.cwd()));
22871
+ const root = realpathSync6(resolve19(options.root ?? process.cwd()));
22475
22872
  const manifest = localManifest(root);
22476
22873
  if (options.kind !== "http" && options.kind !== "worker") throw new Error("Workload kind must be http or worker");
22477
22874
  if (options.kind === "worker" && !options.entry) throw new Error("Workers require an explicit declaration-only entrypoint");
22478
- const entry = realpathSync6(resolve18(root, options.entry ?? manifest.runtime.entrypoint));
22875
+ const entry = realpathSync6(resolve19(root, options.entry ?? manifest.runtime.entrypoint));
22479
22876
  if (!inside3(root, entry)) throw new Error("Workload entrypoint must stay inside this repository");
22480
22877
  const enabled = Object.entries(manifest.capabilities).filter(([, settings]) => settings?.enabled !== false).map(([name2]) => name2).sort();
22481
22878
  if (options.kind === "worker" && !enabled.includes("jobs")) throw new Error("Workers require declared jobs capability");
@@ -22501,11 +22898,11 @@ async function prepareWorkload(options) {
22501
22898
  context3.onResolve({ filter: /./ }, async (input) => {
22502
22899
  if (input.pluginData?.backifyResolved) return;
22503
22900
  if (input.path === "@backifydev/sdk/local" || input.path === "@backifydev/sdk/runtime" && input.namespace !== "backify-workload-host") return { errors: [{ text: "Production application code must not import local emulators or host-only runtime configuration" }] };
22504
- const resolved = await context3.resolve(input.path, { importer: input.namespace === "backify-workload-host" ? join13(root, input.importer) : input.importer, resolveDir: input.resolveDir, kind: input.kind, pluginData: { backifyResolved: true } });
22901
+ const resolved = await context3.resolve(input.path, { importer: input.namespace === "backify-workload-host" ? join14(root, input.importer) : input.importer, resolveDir: input.resolveDir, kind: input.kind, pluginData: { backifyResolved: true } });
22505
22902
  if (!resolved.external && !resolved.errors.length && resolved.path) {
22506
22903
  const directory2 = realpathSync6(packageDirectory(resolved.path));
22507
22904
  const target = relative8(directory2, realpathSync6(resolved.path)).replaceAll("\\", "/");
22508
- if (JSON.parse(readFileSync19(join13(directory2, "package.json"), "utf8")).name === "@backifydev/sdk") {
22905
+ if (JSON.parse(readFileSync20(join14(directory2, "package.json"), "utf8")).name === "@backifydev/sdk") {
22509
22906
  if (/^(src|dist)\/local\.(ts|js)$/.test(target) || /^(src|dist)\/runtime\.(ts|js)$/.test(target) && input.namespace !== "backify-workload-host" && !inside3(directory2, realpathSync6(input.importer))) return { errors: [{ text: "Production application code must not import local emulators or host-only runtime configuration" }] };
22510
22907
  }
22511
22908
  if (!isAbsolute14(input.path) && !input.path.startsWith(".")) trustedPackages.add(directory2);
@@ -22567,30 +22964,30 @@ async function packageWorkload(options) {
22567
22964
  if (plan.blockers.includes("bundle-warning-review-required")) throw new Error("Workload bundle warnings require review before packaging");
22568
22965
  const dockerfile = ["FROM " + options.baseImage, "WORKDIR /app", "COPY --chown=1000:1000 workload.mjs artifact.json ./", "ENV NODE_ENV=production PORT=8080 BACKIFY_ARTIFACT_SHA256=" + plan.artifactVersion + " BACKIFY_WORKLOAD_TOKEN_FILE=/run/backify/workload/token", "USER 1000:1000", ...options.kind === "http" ? ["EXPOSE 8080"] : [], "STOPSIGNAL SIGTERM", 'ENTRYPOINT ["node", "workload.mjs"]', ""].join("\n");
22569
22966
  const files = { "workload.mjs": bundle, "artifact.json": JSON.stringify(plan, null, 2) + "\n", "Dockerfile": dockerfile, ".dockerignore": "**\n!Dockerfile\n!workload.mjs\n!artifact.json\n!.dockerignore\n" };
22570
- const output = resolve18(root, options.output ?? ".backify/artifacts/" + options.kind + "-" + plan.artifactVersion.slice(0, 16));
22967
+ const output = resolve19(root, options.output ?? ".backify/artifacts/" + options.kind + "-" + plan.artifactVersion.slice(0, 16));
22571
22968
  assertLocalStatePath(root, output);
22572
22969
  if (existsSync12(output)) {
22573
22970
  if (JSON.stringify(readdirSync6(output).sort()) !== JSON.stringify(Object.keys(files).sort()) || Object.entries(files).some(([name2, value]) => {
22574
- assertLocalStatePath(root, join13(output, name2));
22575
- return !readFileSync19(join13(output, name2)).equals(Buffer.from(value));
22971
+ assertLocalStatePath(root, join14(output, name2));
22972
+ return !readFileSync20(join14(output, name2)).equals(Buffer.from(value));
22576
22973
  })) throw new Error("Refusing to overwrite an existing workload artifact directory");
22577
22974
  } else {
22578
22975
  mkdirSync7(output, { recursive: true });
22579
- for (const [name2, value] of Object.entries(files)) writeFileSync11(join13(output, name2), value, { flag: "wx", mode: 384 });
22976
+ for (const [name2, value] of Object.entries(files)) writeFileSync12(join14(output, name2), value, { flag: "wx", mode: 384 });
22580
22977
  }
22581
22978
  return { ...plan, outputDirectory: relative8(root, output).replaceAll("\\", "/") };
22582
22979
  }
22583
22980
 
22584
22981
  // src/workload-provenance.ts
22585
22982
  import { execFileSync } from "node:child_process";
22586
- import { mkdirSync as mkdirSync8, mkdtempSync as mkdtempSync2, readdirSync as readdirSync7, rmSync as rmSync2, writeFileSync as writeFileSync12 } from "node:fs";
22983
+ import { mkdirSync as mkdirSync8, mkdtempSync as mkdtempSync2, readdirSync as readdirSync7, rmSync as rmSync2, writeFileSync as writeFileSync13 } from "node:fs";
22587
22984
  import { tmpdir } from "node:os";
22588
- import { basename as basename3, dirname as dirname15, isAbsolute as isAbsolute15, join as join15, relative as relative9, resolve as resolve20 } from "node:path";
22985
+ import { basename as basename3, dirname as dirname15, isAbsolute as isAbsolute15, join as join16, relative as relative9, resolve as resolve21 } from "node:path";
22589
22986
 
22590
22987
  // src/workload-provenance-oci.ts
22591
22988
  import { createHash as createHash15 } from "node:crypto";
22592
- import { createReadStream, lstatSync as lstatSync16, readFileSync as readFileSync20 } from "node:fs";
22593
- import { dirname as dirname14, join as join14, parse as parse3, resolve as resolve19 } from "node:path";
22989
+ import { createReadStream, lstatSync as lstatSync16, readFileSync as readFileSync21 } from "node:fs";
22990
+ import { dirname as dirname14, join as join15, parse as parse3, resolve as resolve20 } from "node:path";
22594
22991
  import { Transform, Writable } from "node:stream";
22595
22992
  import { pipeline } from "node:stream/promises";
22596
22993
  import { createGunzip } from "node:zlib";
@@ -22605,14 +23002,14 @@ function provenanceRef(value) {
22605
23002
  return value.slice(value.lastIndexOf("@") + 1);
22606
23003
  }
22607
23004
  function provenanceFile(filename2, maximum) {
22608
- const absolute = resolve19(filename2);
23005
+ const absolute = resolve20(filename2);
22609
23006
  for (let ancestor = absolute; ; ancestor = dirname14(ancestor)) {
22610
23007
  if (lstatSync16(ancestor).isSymbolicLink()) throw new Error("Provenance paths must not contain links");
22611
23008
  if (ancestor === parse3(absolute).root) break;
22612
23009
  }
22613
23010
  const stat = lstatSync16(absolute);
22614
23011
  if (!stat.isFile() || stat.nlink !== 1 || stat.size < 1 || stat.size > maximum) throw new Error("Invalid provenance file");
22615
- const bytes = readFileSync20(absolute);
23012
+ const bytes = readFileSync21(absolute);
22616
23013
  if (bytes.length !== stat.size) throw new Error("Provenance file changed during read");
22617
23014
  return bytes;
22618
23015
  }
@@ -22621,7 +23018,7 @@ function descriptor(value) {
22621
23018
  return value;
22622
23019
  }
22623
23020
  function blobPath(root, value) {
22624
- return join14(root, "blobs", "sha256", descriptor(value).digest.slice(7));
23021
+ return join15(root, "blobs", "sha256", descriptor(value).digest.slice(7));
22625
23022
  }
22626
23023
  function jsonBlob(root, value) {
22627
23024
  const bytes = provenanceFile(blobPath(root, value), 1024 * 1024);
@@ -22630,8 +23027,8 @@ function jsonBlob(root, value) {
22630
23027
  }
22631
23028
  async function inspectProvenanceImage(root, architecture, requestedDigest) {
22632
23029
  if (!["amd64", "arm64"].includes(architecture) || requestedDigest && !digestPattern.test(requestedDigest)) throw new Error("Invalid OCI platform or digest");
22633
- if (JSON.parse(provenanceFile(join14(root, "oci-layout"), 1024).toString()).imageLayoutVersion !== "1.0.0") throw new Error("OCI layout required");
22634
- const indexBytes = provenanceFile(join14(root, "index.json"), 1024 * 1024);
23030
+ if (JSON.parse(provenanceFile(join15(root, "oci-layout"), 1024).toString()).imageLayoutVersion !== "1.0.0") throw new Error("OCI layout required");
23031
+ const indexBytes = provenanceFile(join15(root, "index.json"), 1024 * 1024);
22635
23032
  let current = JSON.parse(indexBytes.toString());
22636
23033
  let selected;
22637
23034
  let manifestDigest = provenanceHash(indexBytes);
@@ -22688,7 +23085,7 @@ async function inspectProvenanceImage(root, architecture, requestedDigest) {
22688
23085
  return { manifestDigest, configDigest: configuration.digest, architecture, layers };
22689
23086
  }
22690
23087
  function provenanceFileMetadata(filename2, expectedSize) {
22691
- const absolute = resolve19(filename2);
23088
+ const absolute = resolve20(filename2);
22692
23089
  for (let ancestor = absolute; ; ancestor = dirname14(ancestor)) {
22693
23090
  if (lstatSync16(ancestor).isSymbolicLink()) throw new Error("Provenance paths must not contain links");
22694
23091
  if (ancestor === parse3(absolute).root) break;
@@ -22751,28 +23148,28 @@ function dependencyMaterials(lock) {
22751
23148
  return { digest: provenanceHash(canonical(materials.sort((left, right) => left.path.localeCompare(right.path, "en")))), count: materials.length };
22752
23149
  }
22753
23150
  async function captureWorkloadProvenance(options) {
22754
- const root = resolve20(options.root ?? process.cwd());
23151
+ const root = resolve21(options.root ?? process.cwd());
22755
23152
  if (!repositoryPattern.test(options.repository) || !["first", "second"].includes(options.replica)) throw new Error("Invalid provenance repository or replica");
22756
- const applicationPath = relative9(root, resolve20(root, options.application)).replaceAll("\\", "/");
23153
+ const applicationPath = relative9(root, resolve21(root, options.application)).replaceAll("\\", "/");
22757
23154
  if (!applicationPath || isAbsolute15(applicationPath) || applicationPath.split("/").includes("..")) throw new Error("Application must be inside the source checkout");
22758
23155
  if (git2(root, ["rev-parse", "--show-toplevel"]).replaceAll("\\", "/").toLowerCase() !== root.replaceAll("\\", "/").toLowerCase() || git2(root, ["status", "--porcelain", "--untracked-files=all"]) || git2(root, ["ls-files", "--stage"]).split("\n").some((line) => line.startsWith("160000 "))) throw new Error("Clean root checkout without submodules required");
22759
23156
  const commit = git2(root, ["rev-parse", "HEAD"]), tree = git2(root, ["rev-parse", "HEAD^{tree}"]);
22760
23157
  if (!sha.test(commit) || !sha.test(tree)) throw new Error("Full Git commit and tree required");
22761
23158
  const origin = git2(root, ["remote", "get-url", "origin"]);
22762
23159
  if (!["https://github.com/" + options.repository, "https://github.com/" + options.repository + ".git", "git@github.com:" + options.repository + ".git"].includes(origin)) throw new Error("Source repository does not match origin");
22763
- const lockBytes = provenanceFile(join15(root, "package-lock.json"), 16 * 1024 * 1024);
23160
+ const lockBytes = provenanceFile(join16(root, "package-lock.json"), 16 * 1024 * 1024);
22764
23161
  const dependencies = dependencyMaterials(JSON.parse(lockBytes.toString("utf8")));
22765
- const context3 = resolve20(root, options.context);
23162
+ const context3 = resolve21(root, options.context);
22766
23163
  if (canonical(readdirSync7(context3).sort()) !== canonical(contextNames)) throw new Error("Exact allowlisted workload context required");
22767
23164
  const contextDigests = {};
22768
- for (const name2 of contextNames) contextDigests[name2] = provenanceHash(provenanceFile(join15(context3, name2), name2 === "workload.mjs" ? 16 * 1024 * 1024 : 65536));
22769
- const plan = boundedJson(join15(context3, "artifact.json"));
23165
+ for (const name2 of contextNames) contextDigests[name2] = provenanceHash(provenanceFile(join16(context3, name2), name2 === "workload.mjs" ? 16 * 1024 * 1024 : 65536));
23166
+ const plan = boundedJson(join16(context3, "artifact.json"));
22770
23167
  const baseDigest = provenanceRef(options.baseImage);
22771
23168
  if (plan.schemaVersion !== 1 || plan.kind !== "worker" || plan.baseImage !== options.baseImage || !/^[a-f0-9]{64}$/.test(plan.artifactVersion) || !/^[a-f0-9]{64}$/.test(plan.manifestVersion) || contextDigests["workload.mjs"] !== "sha256:" + plan.artifactVersion || typeof plan.entrypoint !== "string") throw new Error("Worker context does not match artifact metadata");
22772
23169
  const dockerfile = ["FROM " + options.baseImage, "WORKDIR /app", "COPY --chown=1000:1000 workload.mjs artifact.json ./", "ENV NODE_ENV=production PORT=8080 BACKIFY_ARTIFACT_SHA256=" + plan.artifactVersion + " BACKIFY_WORKLOAD_TOKEN_FILE=/run/backify/workload/token", "USER 1000:1000", "STOPSIGNAL SIGTERM", 'ENTRYPOINT ["node", "workload.mjs"]', ""].join("\n");
22773
- if (!provenanceFile(join15(context3, "Dockerfile"), 65536).equals(Buffer.from(dockerfile)) || provenanceFile(join15(context3, ".dockerignore"), 65536).toString() !== "**\n!Dockerfile\n!workload.mjs\n!artifact.json\n!.dockerignore\n") throw new Error("Unreviewed workload build recipe");
22774
- const base = await inspectProvenanceImage(resolve20(root, options.baseLayout), options.architecture, baseDigest);
22775
- const image2 = await inspectProvenanceImage(resolve20(root, options.imageLayout), options.architecture);
23170
+ if (!provenanceFile(join16(context3, "Dockerfile"), 65536).equals(Buffer.from(dockerfile)) || provenanceFile(join16(context3, ".dockerignore"), 65536).toString() !== "**\n!Dockerfile\n!workload.mjs\n!artifact.json\n!.dockerignore\n") throw new Error("Unreviewed workload build recipe");
23171
+ const base = await inspectProvenanceImage(resolve21(root, options.baseLayout), options.architecture, baseDigest);
23172
+ const image2 = await inspectProvenanceImage(resolve21(root, options.imageLayout), options.architecture);
22776
23173
  verifyBaseLineage(base, image2);
22777
23174
  let npm;
22778
23175
  try {
@@ -22845,17 +23242,17 @@ function verifyWorkloadProvenance(options, now = /* @__PURE__ */ new Date()) {
22845
23242
  if (provenanceHash(baseSubject) !== provenanceRef(policy.baseImage)) throw new Error("Base attestation subject does not match the approved image digest");
22846
23243
  evidence.push({ bytes: baseSubject, bundle: provenanceFile(options.baseBundle, 4 * 1024 * 1024), identity: { ...policy, ...supplier } });
22847
23244
  }
22848
- const scratchRoot = resolve20(tmpdir());
22849
- const scratch = mkdtempSync2(join15(scratchRoot, "backify-provenance-"));
23245
+ const scratchRoot = resolve21(tmpdir());
23246
+ const scratch = mkdtempSync2(join16(scratchRoot, "backify-provenance-"));
22850
23247
  if (dirname15(scratch) !== scratchRoot || !basename3(scratch).startsWith("backify-provenance-")) throw new Error("Unsafe provenance evidence directory");
22851
23248
  try {
22852
- mkdirSync8(join15(scratch, "evidence"), { mode: 448 });
22853
- const trustedRoot = join15(scratch, "evidence", "trusted-root.jsonl");
22854
- writeFileSync12(trustedRoot, rootBytes, { flag: "wx", mode: 384 });
23249
+ mkdirSync8(join16(scratch, "evidence"), { mode: 448 });
23250
+ const trustedRoot = join16(scratch, "evidence", "trusted-root.jsonl");
23251
+ writeFileSync13(trustedRoot, rootBytes, { flag: "wx", mode: 384 });
22855
23252
  for (const [index, { bytes, bundle: bundleBytes, identity }] of evidence.entries()) {
22856
- const report = join15(scratch, "evidence", "report-" + index + ".json"), bundle = join15(scratch, "evidence", "bundle-" + index + ".jsonl");
22857
- writeFileSync12(report, bytes, { flag: "wx", mode: 384 });
22858
- writeFileSync12(bundle, bundleBytes, { flag: "wx", mode: 384 });
23253
+ const report = join16(scratch, "evidence", "report-" + index + ".json"), bundle = join16(scratch, "evidence", "bundle-" + index + ".jsonl");
23254
+ writeFileSync13(report, bytes, { flag: "wx", mode: 384 });
23255
+ writeFileSync13(bundle, bundleBytes, { flag: "wx", mode: 384 });
22859
23256
  try {
22860
23257
  const result = execFileSync("gh", ["attestation", "verify", report, "--bundle", bundle, "--custom-trusted-root", trustedRoot, "--hostname", "github.com", "--repo", identity.repository, "--signer-workflow", identity.signerWorkflow, "--signer-digest", identity.signerDigest, "--source-digest", identity.sourceCommit, "--source-ref", identity.sourceRef, "--deny-self-hosted-runners", "--predicate-type", "https://slsa.dev/provenance/v1", "--format", "json"], { encoding: "utf8", windowsHide: true, timeout: 12e4, maxBuffer: 4 * 1024 * 1024, stdio: ["ignore", "pipe", "pipe"] });
22861
23258
  if (!Array.isArray(JSON.parse(result)) || !JSON.parse(result).length) throw new Error();
@@ -22886,79 +23283,12 @@ async function workloadProvenanceCommand(args2) {
22886
23283
  return verifyWorkloadProvenance({ policy: required("--policy"), firstReport: options.get("--report") ?? required("--first-report"), firstBundle: options.get("--bundle") ?? required("--first-bundle"), secondReport: options.get("--second-report"), secondBundle: options.get("--second-bundle"), baseSubject: options.get("--base-subject"), baseBundle: options.get("--base-bundle"), trustedRoot: required("--trusted-root") });
22887
23284
  }
22888
23285
  const result = await captureWorkloadProvenance({ root: options.get("--root"), repository: required("--repository"), application: required("--application"), context: required("--context"), baseLayout: required("--base-layout"), imageLayout: required("--image-layout"), baseImage: required("--base-image"), architecture: required("--architecture"), replica: options.get("--replica") ?? "first" });
22889
- writeFileSync12(resolve20(required("--output")), JSON.stringify(result, null, 2) + "\n", { flag: "wx", mode: 384 });
23286
+ writeFileSync13(resolve21(required("--output")), JSON.stringify(result, null, 2) + "\n", { flag: "wx", mode: 384 });
22890
23287
  return { schemaVersion: 1, status: "captured-unsigned", deploymentReady: false, reportDigest: provenanceHash(JSON.stringify(result, null, 2) + "\n") };
22891
23288
  }
22892
23289
 
22893
- // src/workload-artifact-plan.ts
22894
- import { existsSync as existsSync13, lstatSync as lstatSync17, readFileSync as readFileSync21, realpathSync as realpathSync7 } from "node:fs";
22895
- import { resolve as resolve21 } from "node:path";
22896
- function uuid4(value) {
22897
- return typeof value === "string" && value.length === 36 && /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(value) && value !== "00000000-0000-0000-0000-000000000000";
22898
- }
22899
- function validImage(value) {
22900
- if (typeof value !== "string" || value.length > 512 || /[\r\n]/.test(value) || !/^[a-z0-9][a-z0-9.:-]*\/[a-z0-9]+(?:(?:[._]|__|-+)[a-z0-9]+)*(?:\/[a-z0-9]+(?:(?:[._]|__|-+)[a-z0-9]+)*)*@sha256:[a-f0-9]{64}$/.test(value)) return false;
22901
- const registry = value.slice(0, value.indexOf("/")), parts = registry.split(":");
22902
- if (parts.length > 2 || parts[0].length > 253 || parts[0].split(".").some((label) => !/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(label)) || parts.length === 2 && (!/^[0-9]+$/.test(parts[1]) || Number(parts[1]) < 1 || Number(parts[1]) > 65535)) return false;
22903
- return true;
22904
- }
22905
- function jobMetadata(value) {
22906
- if (!Array.isArray(value) || value.length < 1 || value.length > 100) throw new Error("Invalid bounded worker job metadata");
22907
- const names = /* @__PURE__ */ new Set();
22908
- return value.map((item) => {
22909
- if (!item || typeof item !== "object" || Array.isArray(item) || Object.keys(item).some((key) => !["name", "retries", "timeoutSeconds", "concurrency", "backoff"].includes(key)) || typeof item.name !== "string" || item.name.length > 100 || /[\r\n]/.test(item.name) || !/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,99}$/.test(item.name) || names.has(item.name)) throw new Error("Invalid bounded worker job metadata");
22910
- const job = { name: item.name, retries: item.retries === void 0 ? 0 : item.retries, timeoutSeconds: item.timeoutSeconds === void 0 ? 30 : item.timeoutSeconds, concurrency: item.concurrency === void 0 ? 1 : item.concurrency, backoff: item.backoff === void 0 ? "fixed" : item.backoff };
22911
- if (!Number.isInteger(job.retries) || job.retries < 0 || job.retries > 100 || !Number.isInteger(job.timeoutSeconds) || job.timeoutSeconds < 1 || job.timeoutSeconds > 86400 || !Number.isInteger(job.concurrency) || job.concurrency < 1 || job.concurrency > 100 || !["fixed", "exponential"].includes(job.backoff)) throw new Error("Invalid bounded worker job metadata");
22912
- names.add(job.name);
22913
- return job;
22914
- }).sort((first, second) => first.name < second.name ? -1 : first.name > second.name ? 1 : 0);
22915
- }
22916
- function parseWorkerArtifactPlan(args2) {
22917
- const fields5 = /* @__PURE__ */ new Map([["--root", "root"], ["--organization", "organizationId"], ["--app", "applicationId"], ["--environment", "environmentId"], ["--deployment", "deploymentId"], ["--source-commit", "sourceCommit"], ["--image", "imageReference"], ["--jobs-file", "jobsFile"], ["--entry", "entry"], ["--base-image", "baseImage"]]);
22918
- const result = {}, seen = /* @__PURE__ */ new Set();
22919
- for (let index = 0; index < args2.length; index++) {
22920
- const option2 = args2[index];
22921
- if (seen.has(option2)) throw new Error("Duplicate worker artifact planning option");
22922
- seen.add(option2);
22923
- if (option2 === "--json") continue;
22924
- const field = fields5.get(option2), value = args2[++index];
22925
- if (!field || !value || value.startsWith("--")) throw new Error("Unsupported or missing worker artifact planning option");
22926
- result[field] = value;
22927
- }
22928
- for (const field of ["organizationId", "applicationId", "environmentId", "deploymentId", "sourceCommit", "imageReference", "jobsFile", "entry"]) if (!result[field]) throw new Error("Supply all worker artifact scope, source, image, jobs and entry pins");
22929
- return result;
22930
- }
22931
- async function planWorkerArtifactRegistration(options) {
22932
- if (![options.organizationId, options.applicationId, options.environmentId, options.deploymentId].every(uuid4) || typeof options.sourceCommit !== "string" || ![40, 64].includes(options.sourceCommit.length) || !/^[a-f0-9]+$/.test(options.sourceCommit) || !validImage(options.imageReference)) throw new Error("Invalid worker artifact scope, source or image pin");
22933
- const root = realpathSync7(resolve21(options.root ?? process.cwd()));
22934
- if (typeof options.jobsFile !== "string" || !options.jobsFile || typeof options.entry !== "string" || !options.entry) throw new Error("Worker artifact planning requires explicit jobs and entry files");
22935
- const filename2 = resolve21(root, options.jobsFile);
22936
- assertLocalStatePath(root, filename2);
22937
- if (!existsSync13(filename2) || !lstatSync17(filename2).isFile() || lstatSync17(filename2).size > 32768) throw new Error("Worker job metadata file must be a bounded repository file");
22938
- let jobs;
22939
- try {
22940
- jobs = jobMetadata(JSON.parse(readFileSync21(filename2, "utf8")));
22941
- } catch {
22942
- throw new Error("Invalid bounded worker job metadata");
22943
- }
22944
- const workload = await planWorkload({ root, kind: "worker", entry: options.entry, baseImage: options.baseImage });
22945
- const scope = { organizationId: options.organizationId.toLowerCase(), applicationId: options.applicationId.toLowerCase(), environmentId: options.environmentId.toLowerCase() };
22946
- const body = { schemaVersion: 1, deploymentId: options.deploymentId.toLowerCase(), artifactVersion: workload.artifactVersion, imageReference: options.imageReference, sourceCommit: options.sourceCommit, jobs };
22947
- return {
22948
- schemaVersion: 1,
22949
- status: "planned",
22950
- scope,
22951
- deploymentReady: false,
22952
- sourceCommitVerified: false,
22953
- imageVerified: false,
22954
- registration: { method: "POST", path: "/api/apps/" + scope.applicationId + "/worker-artifacts/environments/" + scope.environmentId, headers: { "X-Organization-ID": scope.organizationId, "content-type": "application/json" }, body },
22955
- requiredBindings: workload.capabilityBindings,
22956
- blockers: [.../* @__PURE__ */ new Set([...workload.blockers, "deployment-source-match-required", "artifact-source-conformance-required", "immutable-image-conformance-required", "job-declaration-conformance-required", "durable-provider-dispatch-required", "workload-credential-broker-required"])].sort()
22957
- };
22958
- }
22959
-
22960
23290
  // src/workload-trust-state.ts
22961
- import { lstatSync as lstatSync18, readFileSync as readFileSync22 } from "node:fs";
23291
+ import { lstatSync as lstatSync17, readFileSync as readFileSync22 } from "node:fs";
22962
23292
  import { isAbsolute as isAbsolute16, resolve as resolve22 } from "node:path";
22963
23293
  function parseWorkloadTrustState(args2) {
22964
23294
  const action = args2[0];
@@ -22984,7 +23314,7 @@ function workloadTrustState(options) {
22984
23314
  if (!["plan", "initialize"].includes(options.action) || !isAbsolute16(options.trustFile) || !isAbsolute16(options.stateFile) || resolve22(options.trustFile) === resolve22(options.stateFile) || !Number.isSafeInteger(options.expectedRevision) || options.expectedRevision < 1) throw new Error("Specify separate absolute trust/state paths and a positive reviewed revision");
22985
23315
  let trust;
22986
23316
  try {
22987
- const metadata = lstatSync18(options.trustFile);
23317
+ const metadata = lstatSync17(options.trustFile);
22988
23318
  if (!metadata.isFile() || metadata.isSymbolicLink() || metadata.nlink !== 1 || metadata.size > 131072) throw new Error();
22989
23319
  const bytes = readFileSync22(options.trustFile);
22990
23320
  if (bytes.length > 131072) throw new Error();
@@ -23002,8 +23332,8 @@ function workloadTrustState(options) {
23002
23332
  }
23003
23333
 
23004
23334
  // src/scaffold.ts
23005
- import { existsSync as existsSync14, lstatSync as lstatSync19, mkdirSync as mkdirSync9, readFileSync as readFileSync23, readdirSync as readdirSync8, realpathSync as realpathSync8, writeFileSync as writeFileSync13 } from "node:fs";
23006
- import { dirname as dirname16, join as join16, relative as relative10, resolve as resolve23 } from "node:path";
23335
+ import { existsSync as existsSync13, lstatSync as lstatSync18, mkdirSync as mkdirSync9, readFileSync as readFileSync23, readdirSync as readdirSync8, realpathSync as realpathSync7, writeFileSync as writeFileSync14 } from "node:fs";
23336
+ import { dirname as dirname16, join as join17, relative as relative10, resolve as resolve23 } from "node:path";
23007
23337
  function json2(value) {
23008
23338
  return JSON.stringify(value, null, 2) + "\n";
23009
23339
  }
@@ -23182,19 +23512,19 @@ provider-readiness claim, cloud deployment or browser authentication is implied.
23182
23512
  function scaffoldFullStack(options) {
23183
23513
  const files = fullStackTemplate(options.appId, options.name);
23184
23514
  const root = resolve23(options.root ?? process.cwd());
23185
- if (!existsSync14(root) || !lstatSync19(root).isDirectory() || lstatSync19(root).isSymbolicLink()) throw new Error("Scaffold destination must be an existing non-linked directory");
23515
+ if (!existsSync13(root) || !lstatSync18(root).isDirectory() || lstatSync18(root).isSymbolicLink()) throw new Error("Scaffold destination must be an existing non-linked directory");
23186
23516
  const allowed = /* @__PURE__ */ new Set([...Object.keys(files).map((filename2) => filename2.split("/")[0]), ".git", "node_modules", "package-lock.json", ".backify"]);
23187
23517
  if (readdirSync8(root).some((filename2) => !allowed.has(filename2))) throw new Error("Scaffolding requires an empty folder or an unchanged generated starter");
23188
- const canonicalRoot = realpathSync8(root);
23518
+ const canonicalRoot = realpathSync7(root);
23189
23519
  const pending = [];
23190
23520
  for (const [filename2, content] of Object.entries(files)) {
23191
- const destination = join16(root, filename2);
23521
+ const destination = join17(root, filename2);
23192
23522
  let current = destination;
23193
23523
  while (current !== root) {
23194
23524
  try {
23195
- const stat = lstatSync19(current);
23525
+ const stat = lstatSync18(current);
23196
23526
  if (stat.isSymbolicLink() || current !== destination && !stat.isDirectory()) throw new Error("Scaffolding refuses linked or invalid output paths: " + filename2);
23197
- if (relative10(canonicalRoot, realpathSync8(current)).startsWith("..")) throw new Error("Scaffold output must remain inside its directory");
23527
+ if (relative10(canonicalRoot, realpathSync7(current)).startsWith("..")) throw new Error("Scaffold output must remain inside its directory");
23198
23528
  if (current === destination && (!stat.isFile() || readFileSync23(current, "utf8") !== content)) throw new Error("Scaffolding refuses to overwrite existing content: " + filename2);
23199
23529
  } catch (error) {
23200
23530
  if (!(error instanceof Error) || !("code" in error) || error.code !== "ENOENT") throw error;
@@ -23204,9 +23534,9 @@ function scaffoldFullStack(options) {
23204
23534
  }
23205
23535
  }
23206
23536
  for (const filename2 of pending) {
23207
- const destination = join16(root, filename2);
23537
+ const destination = join17(root, filename2);
23208
23538
  mkdirSync9(dirname16(destination), { recursive: true });
23209
- writeFileSync13(destination, files[filename2], { flag: "wx" });
23539
+ writeFileSync14(destination, files[filename2], { flag: "wx" });
23210
23540
  }
23211
23541
  return { template: "react-vite-hono", created: pending, unchanged: Object.keys(files).length - pending.length, installed: false, deployed: false };
23212
23542
  }
@@ -23250,16 +23580,16 @@ function localInspectionCommand(args2) {
23250
23580
  }
23251
23581
 
23252
23582
  // src/index.ts
23253
- import { readFileSync as readFileSync24, existsSync as existsSync15, rmSync as rmSync3 } from "node:fs";
23583
+ import { readFileSync as readFileSync24, existsSync as existsSync14, rmSync as rmSync3 } from "node:fs";
23254
23584
  import { homedir as homedir2 } from "node:os";
23255
- import { join as join17 } from "node:path";
23585
+ import { join as join18 } from "node:path";
23256
23586
  import { spawn as spawn5 } from "node:child_process";
23257
- var configPath = join17(homedir2(), ".backify.json");
23258
- var userConfig = existsSync15(configPath) ? JSON.parse(readFileSync24(configPath, "utf8")) : {};
23587
+ var configPath = join18(homedir2(), ".backify.json");
23588
+ var userConfig = existsSync14(configPath) ? JSON.parse(readFileSync24(configPath, "utf8")) : {};
23259
23589
  var [command2, ...args] = process.argv.slice(2);
23260
23590
  async function call(path, init) {
23261
23591
  let appId = option("--app");
23262
- if (!appId && existsSync15(join17(process.cwd(), "backify.json"))) appId = projectApplication();
23592
+ if (!appId && existsSync14(join18(process.cwd(), "backify.json"))) appId = projectApplication();
23263
23593
  const session = appId ? userConfig.sessions?.[sessionKey(appId)] : void 0;
23264
23594
  const credential = session ?? { token: userConfig.token ?? "", organizationId: userConfig.organizationId ?? "", apiUrl: process.env.BACKIFY_API_URL ?? userConfig.apiUrl ?? "https://api.backify.dev/api" };
23265
23595
  return (appId ? applicationClient(credential, appId) : apiClient(credential))(path, init);
@@ -23299,6 +23629,13 @@ function applicationClient(session, appId) {
23299
23629
  }
23300
23630
  async function main() {
23301
23631
  switch (command2) {
23632
+ case "integrations": {
23633
+ const path = integrationDiscoveryPath(args[0], { applicationId: applicationGuid(option("--app") ?? projectApplication()), connectionId: option("--connection"), operationId: option("--operation"), query: option("--query"), offset: Number(option("--offset") ?? 0) });
23634
+ const value = await call(path);
23635
+ if (args[0] === "types") console.log(value.source);
23636
+ else console.log(JSON.stringify(value, null, 2));
23637
+ break;
23638
+ }
23302
23639
  case "workload": {
23303
23640
  if (args[0] === "provenance") {
23304
23641
  console.log(JSON.stringify(await workloadProvenanceCommand(args.slice(1)), null, 2));
@@ -23323,11 +23660,7 @@ async function main() {
23323
23660
  console.log(JSON.stringify(workloadTrustState(parseWorkloadTrustState(args.slice(1))), null, 2));
23324
23661
  break;
23325
23662
  }
23326
- if (args[0] === "artifact-plan") {
23327
- console.log(JSON.stringify(await planWorkerArtifactRegistration(parseWorkerArtifactPlan(args.slice(1))), null, 2));
23328
- break;
23329
- }
23330
- if (args[0] !== "plan" && args[0] !== "package") throw new Error("Use backify workload plan|package --kind http|worker, workload artifact-plan or workload provenance capture|verify");
23663
+ if (args[0] !== "plan" && args[0] !== "package") throw new Error("Use backify workload plan|package --kind http|worker or workload provenance capture|verify");
23331
23664
  const options = { kind: option("--kind"), entry: option("--entry"), baseImage: option("--base-image"), output: option("--output") };
23332
23665
  console.log(JSON.stringify(await (args[0] === "plan" ? planWorkload(options) : packageWorkload(options)), null, 2));
23333
23666
  break;
@@ -23437,6 +23770,12 @@ async function main() {
23437
23770
  console.log("Backify instructions synchronized to version " + INSTRUCTION_VERSION);
23438
23771
  break;
23439
23772
  case "doctor": {
23773
+ if (args.includes("--environment")) {
23774
+ const result2 = await diagnoseEnvironment(process.cwd(), { network: args.includes("--network"), capability: option("--capability") });
23775
+ console.log(JSON.stringify(result2, null, 2));
23776
+ if (!result2.valid) process.exitCode = 1;
23777
+ break;
23778
+ }
23440
23779
  const result = doctor(process.cwd(), option("--agent"), option("--instruction-file"));
23441
23780
  console.log(JSON.stringify(result, null, 2));
23442
23781
  if (!result.valid) process.exitCode = 1;
@@ -23447,7 +23786,7 @@ async function main() {
23447
23786
  userConfig.token = args[0];
23448
23787
  userConfig.organizationId = args[1] ?? userConfig.organizationId;
23449
23788
  saveUserConfig(configPath, userConfig);
23450
- } else await browserLogin(option("--app") ?? (existsSync15(join17(process.cwd(), "backify.json")) ? projectApplication() : void 0), option("--organization"));
23789
+ } else await browserLogin(option("--app") ?? (existsSync14(join18(process.cwd(), "backify.json")) ? projectApplication() : void 0), option("--organization"));
23451
23790
  console.log("Logged in to Backify");
23452
23791
  break;
23453
23792
  case "logout":
@@ -23486,7 +23825,7 @@ async function main() {
23486
23825
  userConfig.sessions[key] ??= session;
23487
23826
  saveUserConfig(configPath, userConfig);
23488
23827
  if (args.includes("--clone")) await cloneProject(client, appId);
23489
- else if (existsSync15(join17(process.cwd(), ".git"))) {
23828
+ else if (existsSync14(join18(process.cwd(), ".git"))) {
23490
23829
  const update = await pullProject(client, appId);
23491
23830
  console.log(JSON.stringify(update, null, 2));
23492
23831
  if (update.status === "blocked") throw new Error(update.reason);
@@ -23532,13 +23871,13 @@ async function main() {
23532
23871
  break;
23533
23872
  }
23534
23873
  case "prompt": {
23535
- if (args[0] !== "record" || !args.includes("--stdin")) throw new Error("Use backify prompt record --stdin --id <UUID> [--filename <name> ...] [--model <model>] [--ai-tool <tool>] [--access-level <access>]. Only user text, filenames, and AI context metadata are sent.");
23874
+ if (args[0] !== "record" || !args.includes("--stdin")) throw new Error("Use backify prompt record --stdin --id <UUID> [--filename <name> ...] [--model <model>] [--ai-tool <tool>] [--access-level <access>] [--commit-sha <full-SHA>]. Only user text, filenames, device, commit, and AI context metadata are sent.");
23536
23875
  const id = option("--id");
23537
23876
  if (!id || !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(id)) throw new Error("Provide a UUID with --id; reuse it when retrying this prompt.");
23538
23877
  const filenames = attachmentNames(args.flatMap((value, index) => value === "--filename" ? [args[index + 1] ?? ""] : []));
23539
23878
  const metadata = promptMetadata(args);
23540
23879
  const text3 = await readPrompt(process.stdin);
23541
- console.log(JSON.stringify(await call("/apps/" + applicationGuid(projectApplication()) + "/prompts", { method: "POST", body: JSON.stringify({ clientPromptId: id, text: text3, filenames, ...metadata }) })));
23880
+ console.log(JSON.stringify(await call("/apps/" + applicationGuid(projectApplication()) + "/prompts", { method: "POST", body: JSON.stringify({ clientPromptId: id, text: text3, filenames, ...promptContext(), ...metadata }) })));
23542
23881
  break;
23543
23882
  }
23544
23883
  case "runtime": {
@@ -23555,9 +23894,10 @@ async function main() {
23555
23894
  break;
23556
23895
  }
23557
23896
  case "ship": {
23897
+ if (args.includes("--production-deploy") && args.includes("--preview-only")) throw new Error("--production-deploy cannot be combined with --preview-only.");
23558
23898
  const timeout = Number(option("--timeout") ?? "1200");
23559
23899
  if (!Number.isFinite(timeout) || timeout < 1 || timeout > 7200) throw new Error("--timeout must be between 1 and 7200 seconds.");
23560
- console.log(JSON.stringify(await ship(call, projectApplication(), { previewOnly: args.includes("--preview-only"), timeoutMs: timeout * 1e3 }), null, 2));
23900
+ console.log(JSON.stringify(await ship(call, projectApplication(), { productionDeploy: args.includes("--production-deploy"), previewOnly: args.includes("--preview-only"), timeoutMs: timeout * 1e3 }), null, 2));
23561
23901
  break;
23562
23902
  }
23563
23903
  case "request": {
@@ -23592,7 +23932,7 @@ async function main() {
23592
23932
  console.log(await call("/apps/" + applicationGuid(args[0]) + "/deployments/preview", { method: "POST", body: JSON.stringify({ sourceRevision: args[1] ?? "latest" }) }));
23593
23933
  break;
23594
23934
  default:
23595
- console.log("backify connect | init | doctor | sync | login | logout | disconnect | status | dev | secrets local init|set|list --key-file <external-file> | test --json | inspect tables|rows|buckets|objects|preview|events --local [--json] | identity users|issue|clear --local [--json] | jobs | pull | report [--check] | prompt record --stdin --id <UUID> | ship [--preview-only] | request | events environments|inspect|test | workload plan|package|artifact-plan|trust-state|trust-sync|provenance capture|verify | apps | deploy");
23935
+ console.log("backify connect | init | doctor | sync | login | logout | disconnect | status | dev | secrets local init|set|list --key-file <external-file> | test --json | inspect tables|rows|buckets|objects|preview|events --local [--json] | identity users|issue|clear --local [--json] | jobs | pull | report [--check] | prompt record --stdin --id <UUID> | ship [--production-deploy] | request | events environments|inspect|test | integrations list|catalog|search|describe|contract|types | workload plan|package|artifact-plan|trust-state|trust-sync|provenance capture|verify | apps | deploy");
23596
23936
  }
23597
23937
  }
23598
23938
  main().catch((error) => {