@floless/app 0.137.1 → 0.137.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -55058,7 +55058,7 @@ function appVersion() {
55058
55058
  return resolveVersion({
55059
55059
  isSea: isSea2(),
55060
55060
  sqVersionXml: readSqVersionXml(),
55061
- define: true ? "0.137.1" : void 0,
55061
+ define: true ? "0.137.2" : void 0,
55062
55062
  pkgVersion: readPkgVersion()
55063
55063
  });
55064
55064
  }
@@ -55074,7 +55074,7 @@ function resolveChannel(s) {
55074
55074
  function appChannel() {
55075
55075
  return resolveChannel({
55076
55076
  isSea: isSea2(),
55077
- define: true ? "0.137.1" : void 0,
55077
+ define: true ? "0.137.2" : void 0,
55078
55078
  // argv[1] is the entry the runtime actually loaded (…/dist/floless-server.cjs), which is what
55079
55079
  // carries the npx cache prefix. Absent under the SEA exe, which never reaches the npx branch.
55080
55080
  modulePath: process.argv[1]
@@ -58945,6 +58945,10 @@ function etagsOf(doc) {
58945
58945
  const superseded = `"${supersededContractIdentityHash(doc)}"`;
58946
58946
  return { current, superseded: superseded === current ? null : superseded };
58947
58947
  }
58948
+ function recordedEtagsNameDocument(recorded, doc) {
58949
+ const etags = etagsOf(doc);
58950
+ return recorded.map((tag) => recordedEtagNamesContract(tag, etags));
58951
+ }
58948
58952
  function recordedEtagNamesContract(recorded, etags) {
58949
58953
  if (!recorded) return false;
58950
58954
  return recorded === etags.current || etags.superseded !== null && recorded === etags.superseded;
@@ -65975,6 +65979,49 @@ function withDeterministicFilterIds(document) {
65975
65979
  return copy;
65976
65980
  }
65977
65981
 
65982
+ // steel-shell-invariants.ts
65983
+ var SHELL_REGISTRATION_FIELDS = [
65984
+ "id",
65985
+ "sheet",
65986
+ "viewKind",
65987
+ "elevation_in",
65988
+ "pt_per_ft",
65989
+ "datum_at",
65990
+ "datum_ref",
65991
+ "control2_at",
65992
+ "control2_ref",
65993
+ "frame",
65994
+ "sourceRegistration"
65995
+ ];
65996
+ function planRegistrationOf(doc) {
65997
+ const plans = doc?.plans;
65998
+ if (!Array.isArray(plans)) return [];
65999
+ return plans.map((raw) => Object.fromEntries(
66000
+ SHELL_REGISTRATION_FIELDS.filter((key2) => raw && typeof raw === "object" && key2 in raw).map((key2) => [key2, raw[key2]])
66001
+ ));
66002
+ }
66003
+ function shellDeviations(shell, candidate) {
66004
+ const deviations = [];
66005
+ const compare = (invariant, detail, left, right) => {
66006
+ const shellHash = contractHash(left);
66007
+ const candidateHash = contractHash(right);
66008
+ if (shellHash !== candidateHash) deviations.push({ invariant, detail, shellHash, candidateHash });
66009
+ };
66010
+ compare(
66011
+ "grid",
66012
+ "the submitted model changed the saved grid",
66013
+ shell?.grid,
66014
+ candidate?.grid
66015
+ );
66016
+ compare(
66017
+ "registration",
66018
+ "the submitted model changed saved plan registration",
66019
+ planRegistrationOf(shell),
66020
+ planRegistrationOf(candidate)
66021
+ );
66022
+ return deviations;
66023
+ }
66024
+
65978
66025
  // steel-prepass-status.ts
65979
66026
  function hasSteelFilterCheckpoint(document) {
65980
66027
  if (!document || typeof document !== "object" || Array.isArray(document)) return false;
@@ -71765,6 +71812,19 @@ function evaluateSteelRead(context) {
71765
71812
  else if (!checkpointModeCanonical) add("filter-checkpoint", "block", "the saved Filter's match-on mode is empty or not canonical; reopen the Drawing Filter and save it again");
71766
71813
  else if (!checkpointControlValuesOk) add("filter-checkpoint", "block", "the saved Filter has a layer, thickness or colour control whose value is not a value for that control");
71767
71814
  else add("filter-checkpoint", "pass", "candidate uses the exact saved server-owned Filter");
71815
+ if (context.initialFilterCheckpoint) {
71816
+ const deviations = shellDeviations(context.current, candidate);
71817
+ if (deviations.length) {
71818
+ add(
71819
+ "shell-preserved",
71820
+ "block",
71821
+ `${deviations.map((deviation) => deviation.detail).join("; ")} \u2014 an initial read may fill the saved Drawing Filter checkpoint in, but may not restate it`,
71822
+ deviations.map((deviation) => `${deviation.invariant}: shell ${deviation.shellHash} vs candidate ${deviation.candidateHash}`)
71823
+ );
71824
+ } else {
71825
+ add("shell-preserved", "pass", "candidate preserves the saved grid and plan registration");
71826
+ }
71827
+ }
71768
71828
  const validation = validateSteelModelV2(candidate);
71769
71829
  if (!validation.valid) add("contract-validity", "block", `${validation.errors.length} v2 schema/semantic error(s)`, validation.errors.map((error) => `${error.path}: ${error.message}`));
71770
71830
  else add("contract-validity", "pass", "final candidate is valid steel.model/v2");
@@ -72320,10 +72380,8 @@ async function runNativeInitialRead(opts) {
72320
72380
  const checked = validateSteelFilter(candidate, opts.source?.files.map((file) => file.sha256.toLowerCase()));
72321
72381
  if (!checked.ok) throw new ContractTransactionError("This filter no longer matches the attached drawing set. Reload the Drawing Filter and review it again.", "filter-invalid", checked.errors);
72322
72382
  if (contractHash(shell.filter) !== contractHash(candidate.filter)) throw new ContractTransactionError("the submitted model does not contain the exact saved Drawing Filter", "filter-changed");
72323
- if (contractHash(shell.grid) !== contractHash(candidate.grid)) throw new ContractTransactionError("the submitted model changed the saved grid", "shell-changed");
72324
- const fields = ["id", "sheet", "viewKind", "elevation_in", "pt_per_ft", "datum_at", "datum_ref", "control2_at", "control2_ref", "frame", "sourceRegistration"];
72325
- const registration = (doc) => (Array.isArray(doc.plans) ? doc.plans : []).map((raw) => Object.fromEntries(fields.filter((key2) => raw && typeof raw === "object" && key2 in raw).map((key2) => [key2, raw[key2]])));
72326
- if (contractHash(registration(shell)) !== contractHash(registration(candidate))) throw new ContractTransactionError("the submitted model changed saved plan registration", "shell-changed");
72383
+ const deviation = shellDeviations(shell, candidate)[0];
72384
+ if (deviation) throw new ContractTransactionError(deviation.detail, "shell-changed");
72327
72385
  const normalized = normalizeSteelMemberEndsForRead(opts.candidate);
72328
72386
  let readAuditReport;
72329
72387
  let storedReadAudit;
@@ -72334,6 +72392,11 @@ async function runNativeInitialRead(opts) {
72334
72392
  candidate: normalized.model,
72335
72393
  attestation: input.attestation,
72336
72394
  current,
72395
+ // Definitionally true here: this function refuses anything but an exact checkpoint shell with
72396
+ // empty history (above), which is the same pair of clauses the routes compute. The check can
72397
+ // only pass by the time it runs — the deviation throw is earlier — but the report is what the
72398
+ // receipt stores, and it must say the same thing the preview said (#962).
72399
+ initialFilterCheckpoint: true,
72337
72400
  normalization: normalized
72338
72401
  });
72339
72402
  if (readAuditReport.status !== "read-complete") {
@@ -76734,7 +76797,13 @@ function loadAuthoritativeSteelAuditState(project, requestId, attestation, allow
76734
76797
  attestation: parsedAttestation,
76735
76798
  current,
76736
76799
  baseVersion: request.baseVersion ?? 0,
76737
- baseHash: current == null ? null : etagOf(current)?.replace(/^"|"$/g, "") ?? null
76800
+ baseHash: current == null ? null : etagOf(current)?.replace(/^"|"$/g, "") ?? null,
76801
+ // Whether the publish gate will hold this candidate to the shell invariants, computed HERE so both
76802
+ // `evaluateSteelRead` call sites get the one answer (#962). The expression is the initial-read
76803
+ // dispatch condition of the commit route, which is what makes the audit's verdict predict the
76804
+ // publish's: same question, same two clauses. A revision read gets `false` and is not asked to
76805
+ // preserve a grid it is entitled to rewrite.
76806
+ initialFilterCheckpoint: (listVersions(project.id)[0]?.n ?? 0) === 0 && isExactFilterCheckpointShell(current)
76738
76807
  };
76739
76808
  }
76740
76809
  function preparedManifestNeedsRegeneration(project, request) {
@@ -76866,6 +76935,7 @@ async function stageForReviewAudited(reply, project, requestId, candidateInput,
76866
76935
  candidate,
76867
76936
  attestation: state2.attestation,
76868
76937
  current: state2.current,
76938
+ initialFilterCheckpoint: state2.initialFilterCheckpoint,
76869
76939
  normalization: normalized
76870
76940
  });
76871
76941
  if (report.status === "blocked") {
@@ -77953,6 +78023,7 @@ function registerRevisionRoutes(app, deps = {}) {
77953
78023
  candidate,
77954
78024
  attestation: state2.attestation,
77955
78025
  current: state2.current,
78026
+ initialFilterCheckpoint: state2.initialFilterCheckpoint,
77956
78027
  normalization: normalized
77957
78028
  });
77958
78029
  const normalization = {
@@ -78629,43 +78700,456 @@ function registerRevisionRoutes(app, deps = {}) {
78629
78700
  );
78630
78701
  }
78631
78702
 
78632
- // member-end-resolution-store.ts
78703
+ // workspace-approved-snapshot.ts
78704
+ var WorkspaceSnapshotError = class extends Error {
78705
+ constructor(status, message, notReviewable, version) {
78706
+ super(message);
78707
+ this.status = status;
78708
+ this.notReviewable = notReviewable;
78709
+ this.version = version;
78710
+ }
78711
+ status;
78712
+ notReviewable;
78713
+ version;
78714
+ };
78715
+ var NoApprovedVersionError = class extends WorkspaceSnapshotError {
78716
+ constructor() {
78717
+ super(409, "project has no approved version");
78718
+ this.name = "NoApprovedVersionError";
78719
+ }
78720
+ };
78721
+ function approvedRows(projectId) {
78722
+ const project = getProject(projectId);
78723
+ if (!project) return [];
78724
+ const allRows = listVersions(projectId);
78725
+ if (project.uuid) {
78726
+ const tainted = allRows.find((v) => v.gate === "model" && v.kind === "approve" && !v.approval);
78727
+ if (tainted) {
78728
+ throw new WorkspaceSnapshotError(409, `project has no approved version: approved version ${tainted.n} has no approval proof`, void 0, tainted.n);
78729
+ }
78730
+ }
78731
+ const projectTime = Date.parse(project.createdAt);
78732
+ return allRows.filter((v) => v.gate === "model" && v.kind === "approve").filter((v) => v.approval ? !!project.uuid && v.approval.projectUuid === project.uuid : Number.isFinite(projectTime) && Date.parse(v.ts) >= projectTime).map(({ current: _current, ...meta }) => meta);
78733
+ }
78734
+ function latestApprovedVersion(projectId) {
78735
+ return approvedRows(projectId)[0] ?? null;
78736
+ }
78737
+ function listApprovedVersionMetadata(projectId) {
78738
+ return approvedRows(projectId);
78739
+ }
78740
+ function currentApprovedSnapshot(projectId, version) {
78741
+ const project = getProject(projectId);
78742
+ if (!project) throw new WorkspaceSnapshotError(404, `unknown project: ${projectId}`);
78743
+ const rows2 = approvedRows(projectId);
78744
+ const row = version === void 0 ? rows2[0] : rows2.find((v) => v.n === version);
78745
+ if (!row) {
78746
+ if (version === void 0) throw new NoApprovedVersionError();
78747
+ throw new WorkspaceSnapshotError(404, `approved version not found: ${version}`);
78748
+ }
78749
+ const latest = rows2[0];
78750
+ const assertOwned = (candidate, hash3) => {
78751
+ if (candidate.approval) {
78752
+ if (!project.uuid || candidate.approval.projectUuid !== project.uuid) {
78753
+ throw new WorkspaceSnapshotError(409, `approved version ${candidate.n} belongs to another project incarnation`);
78754
+ }
78755
+ if (candidate.approval.candidateHash !== hash3) {
78756
+ throw new WorkspaceSnapshotError(409, `approved version ${candidate.n} failed its content-hash proof`);
78757
+ }
78758
+ return;
78759
+ }
78760
+ const rowTime = Date.parse(candidate.ts);
78761
+ const projectTime = Date.parse(project.createdAt);
78762
+ if (!Number.isFinite(rowTime) || !Number.isFinite(projectTime) || rowTime < projectTime) {
78763
+ throw new WorkspaceSnapshotError(409, `approved version ${candidate.n} has no ownership proof`);
78764
+ }
78765
+ };
78766
+ const contract = readAcceptedVersion(projectId, row.n, { appId: project.app, projectId, operation: "read" });
78767
+ if (contract == null) throw new WorkspaceSnapshotError(409, `approved version ${row.n} is unreadable`);
78768
+ const selectedHash = contractHash(contract);
78769
+ assertOwned(row, selectedHash);
78770
+ const latestContract = latest.n === row.n ? contract : readAcceptedVersion(projectId, latest.n, { appId: project.app, projectId, operation: "read" });
78771
+ if (latestContract == null) throw new WorkspaceSnapshotError(409, `approved version ${latest.n} is unreadable`);
78772
+ const latestHash = contractHash(latestContract);
78773
+ assertOwned(latest, latestHash);
78774
+ const draft = readAcceptedForRequest(project.app, projectId, "read");
78775
+ const comparable = comparableContractHash;
78776
+ const dirtySinceApproval = draft == null || comparable(draft) !== comparable(latestContract);
78777
+ return {
78778
+ project,
78779
+ version: row,
78780
+ contract,
78781
+ contractHash: selectedHash,
78782
+ currentApprovedAt: project.approvedAt ?? null,
78783
+ dirtySinceApproval,
78784
+ latestApprovedVersion: latest.n,
78785
+ headDiverged: row.n !== latest.n
78786
+ };
78787
+ }
78788
+ function approvedSnapshotForMetadata(projectId, surface, onRefusal) {
78789
+ try {
78790
+ return currentApprovedSnapshot(projectId);
78791
+ } catch (error) {
78792
+ if (error instanceof NoApprovedVersionError) return null;
78793
+ if (error instanceof WorkspaceSnapshotError && error.status === 404) throw error;
78794
+ if (error instanceof WorkspaceSnapshotError || error instanceof ContractPolicyError) {
78795
+ const status = error instanceof WorkspaceSnapshotError ? error.status : error.code;
78796
+ onRefusal?.(error);
78797
+ console.error(
78798
+ `${surface}: project ${projectId} has an approved version the gate refused to serve (${status}) \u2014 reporting no approved head. ${error.message}`
78799
+ );
78800
+ return null;
78801
+ }
78802
+ throw error;
78803
+ }
78804
+ }
78805
+
78806
+ // working-revision-manifest.ts
78633
78807
  var import_node_crypto32 = require("node:crypto");
78634
78808
  var import_node_fs47 = require("node:fs");
78635
78809
  var import_node_path42 = require("node:path");
78810
+ var nativePublicationIdentity = (projectUuid) => `project:${projectUuid}`;
78811
+ var pathOf = (projectId) => (0, import_node_path42.join)(projectDir(projectId), ".floless-working-revision-state-v1.json");
78812
+ var checksumOf = (body) => hashOf(body);
78813
+ function bodyOf(value) {
78814
+ const { checksum: _checksum, ...body } = value;
78815
+ return body;
78816
+ }
78817
+ function assertProject(project) {
78818
+ if (!project.uuid) throw new Error(`project ${project.id} has no incarnation UUID`);
78819
+ return project.uuid;
78820
+ }
78821
+ function readWorkingRevisionManifest(project) {
78822
+ const uuid = assertProject(project);
78823
+ try {
78824
+ const value = JSON.parse((0, import_node_fs47.readFileSync)(pathOf(project.id), "utf8"));
78825
+ if (value?.schema !== 1 || value.projectUuid !== uuid || !Number.isInteger(value.epoch) || value.epoch < 0) return null;
78826
+ return checksumOf(bodyOf(value)) === value.checksum ? value : null;
78827
+ } catch {
78828
+ return null;
78829
+ }
78830
+ }
78831
+ function ensureWorkingRevisionManifest(input) {
78832
+ const existing = readWorkingRevisionManifest(input.project);
78833
+ if (existing) return existing;
78834
+ const body = {
78835
+ schema: 1,
78836
+ projectUuid: assertProject(input.project),
78837
+ publicationIdentity: input.publicationIdentity,
78838
+ revisionId: (0, import_node_crypto32.randomUUID)(),
78839
+ epoch: 0,
78840
+ source: { kind: "working" },
78841
+ workingBase: input.workingBase,
78842
+ draftHash: hashOf(input.contract),
78843
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
78844
+ };
78845
+ const value = { ...body, checksum: checksumOf(body) };
78846
+ (0, import_node_fs47.mkdirSync)(projectDir(input.project.id), { recursive: true });
78847
+ if (!(0, import_node_fs47.existsSync)(pathOf(input.project.id))) writeJsonAtomic(pathOf(input.project.id), value);
78848
+ return readWorkingRevisionManifest(input.project) ?? value;
78849
+ }
78850
+ function advanceWorkingRevisionManifest(input) {
78851
+ const current = readWorkingRevisionManifest(input.project);
78852
+ if (!current) throw new Error("working revision state is missing or corrupt");
78853
+ if (current.epoch !== input.expectedEpoch || current.draftHash !== input.expectedDraftHash) {
78854
+ throw new Error("working revision changed; reload before continuing");
78855
+ }
78856
+ if (current.publicationIdentity !== input.publicationIdentity) throw new Error("working revision belongs to another app publication");
78857
+ const body = {
78858
+ ...bodyOf(current),
78859
+ revisionId: (0, import_node_crypto32.randomUUID)(),
78860
+ epoch: current.epoch + 1,
78861
+ source: input.source,
78862
+ workingBase: input.workingBase,
78863
+ draftHash: hashOf(input.contract),
78864
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
78865
+ };
78866
+ const value = { ...body, checksum: checksumOf(body) };
78867
+ writeJsonAtomic(pathOf(input.project.id), value);
78868
+ return value;
78869
+ }
78870
+ function refreshWorkingDraftHash(input) {
78871
+ const current = readWorkingRevisionManifest(input.project);
78872
+ if (!current) throw new Error("working revision state is missing or corrupt");
78873
+ if (current.epoch !== input.expectedEpoch || current.draftHash !== input.expectedDraftHash) {
78874
+ throw new Error("working revision changed; reload before saving");
78875
+ }
78876
+ const body = { ...bodyOf(current), draftHash: hashOf(input.contract), updatedAt: (/* @__PURE__ */ new Date()).toISOString() };
78877
+ const value = { ...body, checksum: checksumOf(body) };
78878
+ writeJsonAtomic(pathOf(input.project.id), value);
78879
+ return value;
78880
+ }
78881
+
78882
+ // project-checkpoints-store.ts
78883
+ var import_node_crypto33 = require("node:crypto");
78884
+ var import_node_fs48 = require("node:fs");
78885
+ var import_node_path43 = require("node:path");
78886
+ var HASH_RE3 = /^[0-9a-f]{64}$/;
78887
+ function root5(projectId) {
78888
+ return (0, import_node_path43.join)(projectDir(projectId), ".floless-checkpoints-store-v1");
78889
+ }
78890
+ var objectsDir2 = (projectId) => (0, import_node_path43.join)(root5(projectId), "objects");
78891
+ var eventsPath = (projectId) => (0, import_node_path43.join)(root5(projectId), "events.json");
78892
+ function readEvents(projectId) {
78893
+ try {
78894
+ const parsed = JSON.parse((0, import_node_fs48.readFileSync)(eventsPath(projectId), "utf8"));
78895
+ if (parsed?.schema !== 1 || !Array.isArray(parsed.events)) return { schema: 1, events: [] };
78896
+ return { schema: 1, events: parsed.events.filter(validEvent) };
78897
+ } catch {
78898
+ return { schema: 1, events: [] };
78899
+ }
78900
+ }
78901
+ function validEvent(value) {
78902
+ if (!value || typeof value !== "object") return false;
78903
+ const e = value;
78904
+ return typeof e.eventId === "string" && typeof e.checkpointId === "string" && HASH_RE3.test(e.checkpointId) && (e.kind === "captured" || e.kind === "archived" || e.kind === "incorporated") && typeof e.at === "string" && Number.isInteger(e.revisionEpoch) && typeof e.appIdAtCapture === "string";
78905
+ }
78906
+ function readContent(projectId, id) {
78907
+ if (!HASH_RE3.test(id)) return null;
78908
+ try {
78909
+ const value = JSON.parse((0, import_node_fs48.readFileSync)((0, import_node_path43.join)(objectsDir2(projectId), `${id}.json`), "utf8"));
78910
+ if (value?.schema !== 1 || value.id !== id || hashCheckpoint(value) !== id) return null;
78911
+ return value;
78912
+ } catch {
78913
+ return null;
78914
+ }
78915
+ }
78916
+ function hashCheckpoint(value) {
78917
+ const { id: _id, ...identity } = value;
78918
+ return hashOf(identity);
78919
+ }
78920
+ function requireIdentity(project) {
78921
+ if (!project.uuid) throw new Error(`project ${project.id} has no incarnation UUID`);
78922
+ return project.uuid;
78923
+ }
78924
+ function appendEvent(projectId, event) {
78925
+ (0, import_node_fs48.mkdirSync)(root5(projectId), { recursive: true });
78926
+ const log2 = readEvents(projectId);
78927
+ const row = { ...event, eventId: (0, import_node_crypto33.randomUUID)(), at: (/* @__PURE__ */ new Date()).toISOString() };
78928
+ log2.events.push(row);
78929
+ writeJsonAtomic(eventsPath(projectId), log2);
78930
+ return row;
78931
+ }
78932
+ function captureProjectCheckpoint(input) {
78933
+ const projectUuid = requireIdentity(input.project);
78934
+ const withoutId = {
78935
+ schema: 1,
78936
+ projectUuid,
78937
+ publicationIdentity: input.publicationIdentity,
78938
+ base: input.base,
78939
+ draftHash: hashOf(input.contract),
78940
+ contract: input.contract
78941
+ };
78942
+ const id = hashCheckpoint(withoutId);
78943
+ (0, import_node_fs48.mkdirSync)(objectsDir2(input.project.id), { recursive: true });
78944
+ const path = (0, import_node_path43.join)(objectsDir2(input.project.id), `${id}.json`);
78945
+ if (!(0, import_node_fs48.existsSync)(path)) writeJsonAtomic(path, { ...withoutId, id });
78946
+ const event = appendEvent(input.project.id, {
78947
+ checkpointId: id,
78948
+ kind: "captured",
78949
+ revisionEpoch: input.revisionEpoch,
78950
+ appIdAtCapture: input.project.app
78951
+ });
78952
+ return describe(input.project.id, { ...withoutId, id }, event.eventId);
78953
+ }
78954
+ function describe(projectId, content, latestEventId) {
78955
+ const events = readEvents(projectId).events.filter((event) => event.checkpointId === content.id);
78956
+ const captures = events.filter((event) => event.kind === "captured");
78957
+ const first = captures[0];
78958
+ const latest = events.at(-1);
78959
+ if (!first || !latest) return null;
78960
+ return {
78961
+ ...content,
78962
+ capturedAt: first.at,
78963
+ archived: latest.kind === "archived",
78964
+ incorporated: events.some((event) => event.kind === "incorporated"),
78965
+ captureCount: captures.length,
78966
+ latestEventId: latestEventId ?? latest.eventId
78967
+ };
78968
+ }
78969
+ function listProjectCheckpoints(project) {
78970
+ const uuid = requireIdentity(project);
78971
+ const ids = [...new Set(readEvents(project.id).events.map((event) => event.checkpointId))];
78972
+ return ids.map((id) => readContent(project.id, id)).filter((v) => v !== null).filter((v) => v.projectUuid === uuid).map((v) => describe(project.id, v)).filter((v) => v !== null).sort((a, b) => b.capturedAt.localeCompare(a.capturedAt));
78973
+ }
78974
+ function readProjectCheckpoint(project, checkpointId) {
78975
+ const content = readContent(project.id, checkpointId);
78976
+ return content && content.projectUuid === requireIdentity(project) ? describe(project.id, content) : null;
78977
+ }
78978
+ function markProjectCheckpoint(project, checkpointId, kind, expectedEventId) {
78979
+ const current = readProjectCheckpoint(project, checkpointId);
78980
+ if (!current) throw new Error(`unknown checkpoint: ${checkpointId}`);
78981
+ if (current.latestEventId !== expectedEventId) throw new Error("checkpoint changed; reload saved work");
78982
+ const event = appendEvent(project.id, { checkpointId, kind, revisionEpoch: 0, appIdAtCapture: project.app });
78983
+ return describe(project.id, current, event.eventId);
78984
+ }
78985
+
78986
+ // project-revision-start-routes.ts
78987
+ function registerProjectRevisionStartRoutes(app, deps) {
78988
+ const { broadcast: broadcast2 } = deps;
78989
+ app.post(
78990
+ "/api/projects/:id/revisions/start",
78991
+ async (req, reply) => {
78992
+ const project = getProject(req.params.id);
78993
+ if (!project?.uuid) return reply.status(project ? 409 : 404).send({ ok: false, error: project ? "project has no incarnation identity" : `unknown project: ${req.params.id}` });
78994
+ const version = Number(req.body?.version);
78995
+ if (!Number.isInteger(version) || version < 1) return reply.status(400).send({ ok: false, error: "choose a valid approved version" });
78996
+ return withLifecycleLock("project", project.id, async () => {
78997
+ let target;
78998
+ try {
78999
+ target = currentApprovedSnapshot(project.id, version);
79000
+ } catch (error) {
79001
+ if (error instanceof WorkspaceSnapshotError) return reply.status(error.status).send({ ok: false, error: error.message });
79002
+ throw error;
79003
+ }
79004
+ const current = readAcceptedForRequest(project.app, project.id, "read");
79005
+ if (current == null) return reply.status(409).send({ ok: false, error: "the current working copy is unreadable" });
79006
+ const actualEtags = storeEtags(project.app, project.id);
79007
+ const suppliedEpoch = req.body && Object.prototype.hasOwnProperty.call(req.body, "expectedEpoch") ? req.body.expectedEpoch : void 0;
79008
+ if (typeof req.body?.expectedEtag !== "string" || suppliedEpoch !== null && (!Number.isInteger(Number(suppliedEpoch)) || Number(suppliedEpoch) < 0)) {
79009
+ return reply.status(428).send({ ok: false, error: "Reload History and send the working ETag and revision epoch." });
79010
+ }
79011
+ if (!recordedEtagNamesContract(req.body.expectedEtag, actualEtags)) {
79012
+ return reply.status(409).send({ ok: false, error: "The working copy changed. Reload History before starting." });
79013
+ }
79014
+ const observedManifest = readWorkingRevisionManifest(project);
79015
+ if ((observedManifest?.epoch ?? null) !== (suppliedEpoch === null ? null : Number(suppliedEpoch))) {
79016
+ return reply.status(409).send({ ok: false, error: "The working revision changed. Reload History before starting." });
79017
+ }
79018
+ const publicationIdentity = observedManifest?.publicationIdentity ?? nativePublicationIdentity(project.uuid);
79019
+ let manifest = ensureWorkingRevisionManifest({
79020
+ project,
79021
+ publicationIdentity,
79022
+ contract: current,
79023
+ workingBase: { version: target.latestApprovedVersion, hash: currentApprovedSnapshot(project.id).contractHash }
79024
+ });
79025
+ if (manifest.draftHash !== contractHash(current)) {
79026
+ manifest = refreshWorkingDraftHash({ project, expectedEpoch: manifest.epoch, expectedDraftHash: manifest.draftHash, contract: current });
79027
+ }
79028
+ const latest = currentApprovedSnapshot(project.id);
79029
+ const dirty = comparableContractHash(current) !== comparableContractHash(latest.contract);
79030
+ const checkpoint = dirty ? captureProjectCheckpoint({
79031
+ project,
79032
+ publicationIdentity,
79033
+ base: manifest.workingBase,
79034
+ contract: current,
79035
+ revisionEpoch: manifest.epoch
79036
+ }) : null;
79037
+ let publication = null;
79038
+ try {
79039
+ const written = await writeContractGenerationChecked(project.app, target.contract, project.id, `start a new revision from approved v${version}`, { restoring: true });
79040
+ publication = written;
79041
+ } catch (error) {
79042
+ if (error instanceof ContractError) return reply.status(409).send({ ok: false, error: error.message });
79043
+ throw error;
79044
+ }
79045
+ clearApproval(project.id);
79046
+ const next = advanceWorkingRevisionManifest({
79047
+ project,
79048
+ expectedEpoch: manifest.epoch,
79049
+ expectedDraftHash: manifest.draftHash,
79050
+ publicationIdentity,
79051
+ contract: normalisePlanViewIds(target.contract),
79052
+ // The PROOFS stay the ledger's raw hashes — `workingBase.hash` is checked against History and
79053
+ // `source.hash` names the version this came from — while `contract:` above is the document the
79054
+ // gateway actually wrote, which is canonical. Hashing raw bytes into `draftHash` for a document
79055
+ // stored canonically made the manifest disagree with the store the instant it was written.
79056
+ source: { kind: "approved", version, hash: target.contractHash },
79057
+ workingBase: { version, hash: target.contractHash }
79058
+ });
79059
+ broadcast2(contractChangedWithReason(project.app, project.id, publication.etag, publication.storeRevision, "rollback"));
79060
+ return {
79061
+ ok: true,
79062
+ checkpoint,
79063
+ revision: next,
79064
+ workingBaseVersion: version,
79065
+ latestApprovedVersion: latest.version.n,
79066
+ message: checkpoint ? `Saved pending work${checkpoint.base ? ` from v${checkpoint.base.version}` : ""}. Started a DRAFT from v${version}.` : `Started a DRAFT from v${version}.`
79067
+ };
79068
+ }, { label: `starting a revision from v${version}` });
79069
+ }
79070
+ );
79071
+ app.post(
79072
+ "/api/projects/:id/checkpoints/:checkpointId/resume",
79073
+ async (req, reply) => {
79074
+ const project = getProject(req.params.id);
79075
+ if (!project?.uuid) return reply.status(project ? 409 : 404).send({ ok: false, error: project ? "project has no incarnation identity" : `unknown project: ${req.params.id}` });
79076
+ return withLifecycleLock("project", project.id, async () => {
79077
+ const saved = readProjectCheckpoint(project, req.params.checkpointId);
79078
+ if (!saved) return reply.status(404).send({ ok: false, error: "checkpoint not found" });
79079
+ const current = readAcceptedForRequest(project.app, project.id, "read");
79080
+ if (current == null) return reply.status(409).send({ ok: false, error: "the current working copy is unreadable" });
79081
+ const suppliedEpoch = req.body && Object.prototype.hasOwnProperty.call(req.body, "expectedEpoch") ? req.body.expectedEpoch : void 0;
79082
+ if (typeof req.body?.expectedEtag !== "string" || suppliedEpoch !== null && (!Number.isInteger(Number(suppliedEpoch)) || Number(suppliedEpoch) < 0)) {
79083
+ return reply.status(428).send({ ok: false, error: "Reload Saved work and send the working ETag and revision epoch." });
79084
+ }
79085
+ if (!recordedEtagNamesContract(req.body.expectedEtag, storeEtags(project.app, project.id))) return reply.status(409).send({ ok: false, error: "The working copy changed. Reload Saved work." });
79086
+ const observedManifest = readWorkingRevisionManifest(project);
79087
+ if ((observedManifest?.epoch ?? null) !== (suppliedEpoch === null ? null : Number(suppliedEpoch))) return reply.status(409).send({ ok: false, error: "The working revision changed. Reload Saved work." });
79088
+ const publicationIdentity = saved.publicationIdentity;
79089
+ let manifest = ensureWorkingRevisionManifest({ project, publicationIdentity, contract: current, workingBase: saved.base });
79090
+ if (manifest.draftHash !== contractHash(current)) manifest = refreshWorkingDraftHash({ project, expectedEpoch: manifest.epoch, expectedDraftHash: manifest.draftHash, contract: current });
79091
+ const latest = approvedSnapshotForMetadata(project.id, "resuming saved work");
79092
+ if (!latest || comparableContractHash(current) !== comparableContractHash(latest.contract)) captureProjectCheckpoint({ project, publicationIdentity, base: manifest.workingBase, contract: current, revisionEpoch: manifest.epoch });
79093
+ let publication;
79094
+ try {
79095
+ publication = await writeContractGenerationChecked(project.app, saved.contract, project.id, "resume an explicitly selected saved-work checkpoint", { restoring: true });
79096
+ } catch (error) {
79097
+ return reply.status(409).send({ ok: false, error: error instanceof Error ? error.message : "checkpoint cannot be resumed" });
79098
+ }
79099
+ clearApproval(project.id);
79100
+ const next = advanceWorkingRevisionManifest({
79101
+ project,
79102
+ expectedEpoch: manifest.epoch,
79103
+ expectedDraftHash: manifest.draftHash,
79104
+ publicationIdentity,
79105
+ contract: normalisePlanViewIds(saved.contract),
79106
+ source: { kind: "checkpoint", checkpointId: saved.id, hash: saved.draftHash },
79107
+ workingBase: saved.base
79108
+ });
79109
+ broadcast2(contractChangedWithReason(project.app, project.id, publication.etag, publication.storeRevision, "rollback"));
79110
+ return { ok: true, revision: next, checkpoint: saved, latestApprovedVersion: latest?.version.n ?? null };
79111
+ }, { label: "resuming saved work" });
79112
+ }
79113
+ );
79114
+ }
79115
+
79116
+ // member-end-resolution-store.ts
79117
+ var import_node_crypto34 = require("node:crypto");
79118
+ var import_node_fs49 = require("node:fs");
79119
+ var import_node_path44 = require("node:path");
78636
79120
  var VERSION = 1;
78637
79121
  var RETAIN_MAX = 100;
78638
79122
  var RETAIN_MS = 30 * 24 * 60 * 60 * 1e3;
78639
79123
  var contentHash = (value) => `sha256:${hashOf(value)}`;
78640
- var storeRoot = (projectId) => (0, import_node_path42.join)(projectDir(projectId), ".member-end-resolution");
78641
- var artifactRoot = (projectId) => (0, import_node_path42.join)(storeRoot(projectId), "artifacts");
78642
- var registryPath = (projectId) => (0, import_node_path42.join)(storeRoot(projectId), "tokens.json");
79124
+ var storeRoot = (projectId) => (0, import_node_path44.join)(projectDir(projectId), ".member-end-resolution");
79125
+ var artifactRoot = (projectId) => (0, import_node_path44.join)(storeRoot(projectId), "artifacts");
79126
+ var registryPath = (projectId) => (0, import_node_path44.join)(storeRoot(projectId), "tokens.json");
78643
79127
  function atomicJson(path, value) {
78644
- const temp = `${path}.${process.pid}.${(0, import_node_crypto32.randomUUID)()}.tmp`;
78645
- (0, import_node_fs47.writeFileSync)(temp, JSON.stringify(value));
78646
- (0, import_node_fs47.renameSync)(temp, path);
79128
+ const temp = `${path}.${process.pid}.${(0, import_node_crypto34.randomUUID)()}.tmp`;
79129
+ (0, import_node_fs49.writeFileSync)(temp, JSON.stringify(value));
79130
+ (0, import_node_fs49.renameSync)(temp, path);
78647
79131
  }
78648
79132
  function readRegistry(projectId) {
78649
79133
  const path = registryPath(projectId);
78650
- if (!(0, import_node_fs47.existsSync)(path)) return { version: VERSION, tokens: [] };
79134
+ if (!(0, import_node_fs49.existsSync)(path)) return { version: VERSION, tokens: [] };
78651
79135
  try {
78652
- const value = JSON.parse((0, import_node_fs47.readFileSync)(path, "utf8"));
79136
+ const value = JSON.parse((0, import_node_fs49.readFileSync)(path, "utf8"));
78653
79137
  return value?.version === VERSION && Array.isArray(value.tokens) ? value : { version: VERSION, tokens: [] };
78654
79138
  } catch {
78655
79139
  return { version: VERSION, tokens: [] };
78656
79140
  }
78657
79141
  }
78658
79142
  function persistRegistry(projectId, registry2) {
78659
- (0, import_node_fs47.mkdirSync)(storeRoot(projectId), { recursive: true });
79143
+ (0, import_node_fs49.mkdirSync)(storeRoot(projectId), { recursive: true });
78660
79144
  const now = Date.now();
78661
79145
  const retained = registry2.tokens.filter((record4) => record4.status !== "consumed" || Date.parse(record4.expiresAt) > now).sort((a, b) => Date.parse(b.createdAt) - Date.parse(a.createdAt)).slice(0, RETAIN_MAX);
78662
79146
  atomicJson(registryPath(projectId), { version: VERSION, tokens: retained });
78663
79147
  const referenced = new Set(retained.filter((record4) => record4.status !== "consumed" && Date.parse(record4.expiresAt) > now).map((record4) => `${record4.targetArtifact.slice(7)}.json`));
78664
79148
  const artifacts = artifactRoot(projectId);
78665
- if ((0, import_node_fs47.existsSync)(artifacts)) {
78666
- for (const entry2 of (0, import_node_fs47.readdirSync)(artifacts, { withFileTypes: true })) {
79149
+ if ((0, import_node_fs49.existsSync)(artifacts)) {
79150
+ for (const entry2 of (0, import_node_fs49.readdirSync)(artifacts, { withFileTypes: true })) {
78667
79151
  if (entry2.isFile() && /^[a-f0-9]{64}\.json$/.test(entry2.name) && !referenced.has(entry2.name)) {
78668
- (0, import_node_fs47.rmSync)((0, import_node_path42.join)(artifacts, entry2.name));
79152
+ (0, import_node_fs49.rmSync)((0, import_node_path44.join)(artifacts, entry2.name));
78669
79153
  }
78670
79154
  }
78671
79155
  }
@@ -78673,14 +79157,14 @@ function persistRegistry(projectId, registry2) {
78673
79157
  function persistArtifact(projectId, contract) {
78674
79158
  const hash3 = contentHash(contract);
78675
79159
  const root6 = artifactRoot(projectId);
78676
- (0, import_node_fs47.mkdirSync)(root6, { recursive: true });
78677
- const path = (0, import_node_path42.join)(root6, `${hash3.slice(7)}.json`);
78678
- if (!(0, import_node_fs47.existsSync)(path)) atomicJson(path, { hash: hash3, contract });
79160
+ (0, import_node_fs49.mkdirSync)(root6, { recursive: true });
79161
+ const path = (0, import_node_path44.join)(root6, `${hash3.slice(7)}.json`);
79162
+ if (!(0, import_node_fs49.existsSync)(path)) atomicJson(path, { hash: hash3, contract });
78679
79163
  return hash3;
78680
79164
  }
78681
79165
  function readArtifact(projectId, hash3) {
78682
- const path = (0, import_node_path42.join)(artifactRoot(projectId), `${hash3.slice(7)}.json`);
78683
- const value = JSON.parse((0, import_node_fs47.readFileSync)(path, "utf8"));
79166
+ const path = (0, import_node_path44.join)(artifactRoot(projectId), `${hash3.slice(7)}.json`);
79167
+ const value = JSON.parse((0, import_node_fs49.readFileSync)(path, "utf8"));
78684
79168
  if (value?.hash !== hash3 || contentHash(value.contract) !== hash3) throw new Error("member-end undo artifact failed its content hash");
78685
79169
  return value.contract;
78686
79170
  }
@@ -78690,8 +79174,8 @@ function stageResolutionToken(projectId, expectedContract, targetContract, direc
78690
79174
  const targetArtifact = persistArtifact(projectId, targetContract);
78691
79175
  const record4 = {
78692
79176
  version: VERSION,
78693
- token: (0, import_node_crypto32.randomUUID)(),
78694
- operationId: (0, import_node_crypto32.randomUUID)(),
79177
+ token: (0, import_node_crypto34.randomUUID)(),
79178
+ operationId: (0, import_node_crypto34.randomUUID)(),
78695
79179
  direction,
78696
79180
  expectedHash: contentHash(expectedContract),
78697
79181
  targetHash: targetArtifact,
@@ -79377,8 +79861,8 @@ function registerSteelPrepassRoute(app, deps) {
79377
79861
  }
79378
79862
 
79379
79863
  // reference-routes.ts
79380
- var import_node_crypto35 = require("node:crypto");
79381
- var import_node_fs50 = require("node:fs");
79864
+ var import_node_crypto37 = require("node:crypto");
79865
+ var import_node_fs52 = require("node:fs");
79382
79866
 
79383
79867
  // reference-import.ts
79384
79868
  var AGENT2 = "ifc-reference-reader";
@@ -79887,14 +80371,14 @@ async function readReferenceModel(companionId, ifcPath, opts = {}) {
79887
80371
  }
79888
80372
 
79889
80373
  // reference-progress.ts
79890
- var import_node_crypto33 = require("node:crypto");
80374
+ var import_node_crypto35 = require("node:crypto");
79891
80375
  var MAX_BUFFER_BYTES = 8 * 1024 * 1024;
79892
80376
  var SESSION_TTL_MS = 10 * 6e4;
79893
80377
  var UNCLAIMED_TTL_MS = 2 * 6e4;
79894
80378
  var SWEEP_MS = 3e4;
79895
80379
  var sessions = /* @__PURE__ */ new Map();
79896
80380
  function createProgressSession(appId, project) {
79897
- const id = (0, import_node_crypto33.randomUUID)();
80381
+ const id = (0, import_node_crypto35.randomUUID)();
79898
80382
  sessions.set(id, {
79899
80383
  id,
79900
80384
  appId,
@@ -80005,15 +80489,15 @@ var sweep = setInterval(() => {
80005
80489
  sweep.unref?.();
80006
80490
 
80007
80491
  // reference-store.ts
80008
- var import_node_crypto34 = require("node:crypto");
80009
- var import_node_fs49 = require("node:fs");
80492
+ var import_node_crypto36 = require("node:crypto");
80493
+ var import_node_fs51 = require("node:fs");
80010
80494
  var import_promises4 = require("node:fs/promises");
80011
80495
  var import_promises5 = require("node:stream/promises");
80012
- var import_node_path43 = require("node:path");
80496
+ var import_node_path45 = require("node:path");
80013
80497
 
80014
80498
  // reference-binary.ts
80015
80499
  var import_node_zlib = require("node:zlib");
80016
- var import_node_fs48 = require("node:fs");
80500
+ var import_node_fs50 = require("node:fs");
80017
80501
  var import_node_util4 = require("node:util");
80018
80502
  var REFERENCE_BINARY_TYPE = "application/vnd.floless.reference-geometry-v7";
80019
80503
  var REFERENCE_BINARY_HEADER_BYTES = 192;
@@ -80159,14 +80643,14 @@ async function encodeReferenceBinaryAsync(cache2) {
80159
80643
  }
80160
80644
  function readReferenceBinaryHandleManifest(fd2, actualSize) {
80161
80645
  const header = Buffer.alloc(REFERENCE_BINARY_HEADER_BYTES);
80162
- if ((0, import_node_fs48.readSync)(fd2, header, 0, header.length, 0) !== header.length || !header.subarray(0, 8).equals(MAGIC)) throw new Error("not a reference binary");
80646
+ if ((0, import_node_fs50.readSync)(fd2, header, 0, header.length, 0) !== header.length || !header.subarray(0, 8).equals(MAGIC)) throw new Error("not a reference binary");
80163
80647
  if (header.readUInt32LE(8) !== 7 || header.readUInt32LE(12) !== REFERENCE_BINARY_HEADER_BYTES) throw new Error("unsupported reference binary version");
80164
80648
  const total = get64(header, 16);
80165
80649
  if (total !== actualSize || total > MAX_FILE) throw new Error("reference binary length mismatch");
80166
80650
  const offset = get64(header, 24), length2 = get64(header, 32);
80167
80651
  if (offset % 8 || length2 > MAX_META || offset + length2 > total) throw new Error("invalid manifest section");
80168
80652
  const manifest = Buffer.alloc(length2);
80169
- if ((0, import_node_fs48.readSync)(fd2, manifest, 0, length2, offset) !== length2 || referenceCrc32(manifest) !== header.readUInt32LE(40)) throw new Error("manifest checksum mismatch");
80653
+ if ((0, import_node_fs50.readSync)(fd2, manifest, 0, length2, offset) !== length2 || referenceCrc32(manifest) !== header.readUInt32LE(40)) throw new Error("manifest checksum mismatch");
80170
80654
  const parsed = JSON.parse(manifest.toString("utf8"));
80171
80655
  if (!Number.isInteger(parsed.v) || typeof parsed.sourceHash !== "string") throw new Error("reference manifest is incomplete");
80172
80656
  return { v: parsed.v, sourceHash: parsed.sourceHash, filter: parsed.filter ?? null };
@@ -80181,70 +80665,70 @@ function insideProject(projectId, relPath) {
80181
80665
  throw new ReferenceImportError("that reference does not name one of its own files, so it cannot be read or removed");
80182
80666
  }
80183
80667
  const root6 = realish(projectDir(projectId));
80184
- const abs = (0, import_node_path43.resolve)(root6, REFERENCE_DIR, name);
80185
- if (realish((0, import_node_path43.join)(root6, REFERENCE_DIR)) !== (0, import_node_path43.resolve)(root6, REFERENCE_DIR)) {
80668
+ const abs = (0, import_node_path45.resolve)(root6, REFERENCE_DIR, name);
80669
+ if (realish((0, import_node_path45.join)(root6, REFERENCE_DIR)) !== (0, import_node_path45.resolve)(root6, REFERENCE_DIR)) {
80186
80670
  throw new ReferenceImportError("this project\u2019s references folder is a link to somewhere else, so it will not be written to");
80187
80671
  }
80188
- if (!abs.startsWith(root6 + import_node_path43.sep)) {
80672
+ if (!abs.startsWith(root6 + import_node_path45.sep)) {
80189
80673
  throw new ReferenceImportError("that reference points outside its project, so it cannot be read or removed");
80190
80674
  }
80191
80675
  return abs;
80192
80676
  }
80193
80677
  function realish(p) {
80194
80678
  try {
80195
- return import_node_fs49.realpathSync.native((0, import_node_path43.resolve)(p));
80679
+ return import_node_fs51.realpathSync.native((0, import_node_path45.resolve)(p));
80196
80680
  } catch {
80197
- return (0, import_node_path43.resolve)(p);
80681
+ return (0, import_node_path45.resolve)(p);
80198
80682
  }
80199
80683
  }
80200
80684
  var REFERENCE_CACHE_VERSION = 7;
80201
- var legacyJsonCachePath = (projectId, refId2) => (0, import_node_path43.join)(projectDir(projectId), `.floless-refcache-${safeId2(refId2)}.json`);
80685
+ var legacyJsonCachePath = (projectId, refId2) => (0, import_node_path45.join)(projectDir(projectId), `.floless-refcache-${safeId2(refId2)}.json`);
80202
80686
  var binaryCachePrefix = (refId2) => `.floless-refcache-${safeId2(refId2)}-`;
80203
80687
  var cacheGenerationSequence = 0;
80204
80688
  var activePendingCacheGenerations = /* @__PURE__ */ new Set();
80205
80689
  var cachePruneTimers = /* @__PURE__ */ new Map();
80206
80690
  var CACHE_PENDING_TTL_MS = 10 * 6e4;
80207
80691
  var binaryCachePath = (projectId, refId2, sourceHash, filter, version = REFERENCE_CACHE_VERSION) => {
80208
- const key2 = (0, import_node_crypto34.createHash)("sha256").update(String(version)).update("\0").update(sourceHash).update("\0").update(filterKey(filter) ?? "").digest("hex").slice(0, 20);
80209
- return (0, import_node_path43.join)(projectDir(projectId), `${binaryCachePrefix(refId2)}${key2}.bin`);
80692
+ const key2 = (0, import_node_crypto36.createHash)("sha256").update(String(version)).update("\0").update(sourceHash).update("\0").update(filterKey(filter) ?? "").digest("hex").slice(0, 20);
80693
+ return (0, import_node_path45.join)(projectDir(projectId), `${binaryCachePrefix(refId2)}${key2}.bin`);
80210
80694
  };
80211
- var legacyBinaryCachePath = (projectId, refId2) => (0, import_node_path43.join)(projectDir(projectId), `.floless-refcache-${safeId2(refId2)}.bin`);
80212
- var cacheCurrentPath = (projectId, refId2) => (0, import_node_path43.join)(projectDir(projectId), `${binaryCachePrefix(refId2)}current`);
80695
+ var legacyBinaryCachePath = (projectId, refId2) => (0, import_node_path45.join)(projectDir(projectId), `.floless-refcache-${safeId2(refId2)}.bin`);
80696
+ var cacheCurrentPath = (projectId, refId2) => (0, import_node_path45.join)(projectDir(projectId), `${binaryCachePrefix(refId2)}current`);
80213
80697
  function currentCacheGeneration(projectId, refId2) {
80214
80698
  const pointer = cacheCurrentPath(projectId, refId2);
80215
- if (!(0, import_node_fs49.existsSync)(pointer)) return null;
80699
+ if (!(0, import_node_fs51.existsSync)(pointer)) return null;
80216
80700
  try {
80217
- const name = (0, import_node_fs49.readFileSync)(pointer, "utf8").trim();
80218
- if (!name || (0, import_node_path43.basename)(name) !== name) return null;
80219
- return cacheGenerationTarget(projectId, refId2, (0, import_node_path43.join)(projectDir(projectId), name), [".bin"]);
80701
+ const name = (0, import_node_fs51.readFileSync)(pointer, "utf8").trim();
80702
+ if (!name || (0, import_node_path45.basename)(name) !== name) return null;
80703
+ return cacheGenerationTarget(projectId, refId2, (0, import_node_path45.join)(projectDir(projectId), name), [".bin"]);
80220
80704
  } catch {
80221
80705
  return null;
80222
80706
  }
80223
80707
  }
80224
80708
  function publishCurrentCacheGeneration(projectId, refId2, generationName) {
80225
80709
  const pointer = cacheCurrentPath(projectId, refId2);
80226
- const pending = `${pointer}.${process.pid}.${(0, import_node_crypto34.randomUUID)()}.part`;
80710
+ const pending = `${pointer}.${process.pid}.${(0, import_node_crypto36.randomUUID)()}.part`;
80227
80711
  try {
80228
- (0, import_node_fs49.writeFileSync)(pending, generationName, "utf8");
80229
- (0, import_node_fs49.renameSync)(pending, pointer);
80712
+ (0, import_node_fs51.writeFileSync)(pending, generationName, "utf8");
80713
+ (0, import_node_fs51.renameSync)(pending, pointer);
80230
80714
  } finally {
80231
- (0, import_node_fs49.rmSync)(pending, { force: true });
80715
+ (0, import_node_fs51.rmSync)(pending, { force: true });
80232
80716
  }
80233
80717
  }
80234
80718
  function binaryCacheCandidates(projectId, refId2, sourceHash, filter) {
80235
80719
  collectStalePendingCacheGenerations(projectId, refId2);
80236
- if ((0, import_node_fs49.existsSync)(cacheCurrentPath(projectId, refId2))) {
80720
+ if ((0, import_node_fs51.existsSync)(cacheCurrentPath(projectId, refId2))) {
80237
80721
  const current = currentCacheGeneration(projectId, refId2);
80238
80722
  if (current) sweepExpiredCacheGenerations(projectId, refId2, current);
80239
80723
  return current ? [current] : [];
80240
80724
  }
80241
80725
  const exact = binaryCachePath(projectId, refId2, sourceHash, filter);
80242
- const generationPrefix = (0, import_node_path43.basename)(exact, ".bin") + "-";
80726
+ const generationPrefix = (0, import_node_path45.basename)(exact, ".bin") + "-";
80243
80727
  let generated = [];
80244
80728
  try {
80245
- generated = (0, import_node_fs49.readdirSync)(projectDir(projectId)).filter((name) => name.startsWith(generationPrefix) && name.endsWith(".bin")).map((name) => (0, import_node_path43.join)(projectDir(projectId), name)).sort((a, b) => {
80729
+ generated = (0, import_node_fs51.readdirSync)(projectDir(projectId)).filter((name) => name.startsWith(generationPrefix) && name.endsWith(".bin")).map((name) => (0, import_node_path45.join)(projectDir(projectId), name)).sort((a, b) => {
80246
80730
  try {
80247
- return (0, import_node_fs49.statSync)(b).mtimeMs - (0, import_node_fs49.statSync)(a).mtimeMs || (0, import_node_path43.basename)(b).localeCompare((0, import_node_path43.basename)(a));
80731
+ return (0, import_node_fs51.statSync)(b).mtimeMs - (0, import_node_fs51.statSync)(a).mtimeMs || (0, import_node_path45.basename)(b).localeCompare((0, import_node_path45.basename)(a));
80248
80732
  } catch {
80249
80733
  return 0;
80250
80734
  }
@@ -80257,13 +80741,13 @@ function binaryCacheCandidates(projectId, refId2, sourceHash, filter) {
80257
80741
  function sweepExpiredCacheGenerations(projectId, refId2, preserve) {
80258
80742
  const staleBefore = Date.now() - CACHE_PENDING_TTL_MS;
80259
80743
  try {
80260
- for (const name of (0, import_node_fs49.readdirSync)(projectDir(projectId))) {
80744
+ for (const name of (0, import_node_fs51.readdirSync)(projectDir(projectId))) {
80261
80745
  if (!name.startsWith(binaryCachePrefix(refId2)) || !name.endsWith(".bin") && !name.endsWith(".pending")) continue;
80262
- const candidate = (0, import_node_path43.join)(projectDir(projectId), name);
80263
- if ((0, import_node_path43.resolve)(candidate) === (0, import_node_path43.resolve)(preserve)) continue;
80264
- if (activePendingCacheGenerations.has((0, import_node_path43.resolve)(candidate))) continue;
80746
+ const candidate = (0, import_node_path45.join)(projectDir(projectId), name);
80747
+ if ((0, import_node_path45.resolve)(candidate) === (0, import_node_path45.resolve)(preserve)) continue;
80748
+ if (activePendingCacheGenerations.has((0, import_node_path45.resolve)(candidate))) continue;
80265
80749
  try {
80266
- if ((0, import_node_fs49.statSync)(candidate).mtimeMs < staleBefore) (0, import_node_fs49.rmSync)(candidate, { force: true });
80750
+ if ((0, import_node_fs51.statSync)(candidate).mtimeMs < staleBefore) (0, import_node_fs51.rmSync)(candidate, { force: true });
80267
80751
  } catch {
80268
80752
  }
80269
80753
  }
@@ -80276,21 +80760,21 @@ function safeId2(refId2) {
80276
80760
  return s;
80277
80761
  }
80278
80762
  async function hashFile(path) {
80279
- const h = (0, import_node_crypto34.createHash)("sha256");
80280
- await (0, import_promises5.pipeline)((0, import_node_fs49.createReadStream)(path), h);
80763
+ const h = (0, import_node_crypto36.createHash)("sha256");
80764
+ await (0, import_promises5.pipeline)((0, import_node_fs51.createReadStream)(path), h);
80281
80765
  return h.digest("hex");
80282
80766
  }
80283
80767
  function copyOriginal(projectId, relPath, sourceAbs, tag) {
80284
80768
  const abs = insideProject(projectId, relPath);
80285
- (0, import_node_fs49.mkdirSync)((0, import_node_path43.dirname)(abs), { recursive: true });
80769
+ (0, import_node_fs51.mkdirSync)((0, import_node_path45.dirname)(abs), { recursive: true });
80286
80770
  const tmp = `${abs}.${safeId2(tag)}.part`;
80287
- (0, import_node_fs49.copyFileSync)(sourceAbs, tmp);
80288
- (0, import_node_fs49.renameSync)(tmp, abs);
80771
+ (0, import_node_fs51.copyFileSync)(sourceAbs, tmp);
80772
+ (0, import_node_fs51.renameSync)(tmp, abs);
80289
80773
  return abs;
80290
80774
  }
80291
80775
  function referenceFilesOnDisk(projectId) {
80292
80776
  try {
80293
- return (0, import_node_fs49.readdirSync)((0, import_node_path43.join)(projectDir(projectId), REFERENCE_DIR)).map((f) => `${REFERENCE_DIR}/${f}`);
80777
+ return (0, import_node_fs51.readdirSync)((0, import_node_path45.join)(projectDir(projectId), REFERENCE_DIR)).map((f) => `${REFERENCE_DIR}/${f}`);
80294
80778
  } catch (e) {
80295
80779
  if (e.code === "ENOENT") return [];
80296
80780
  throw new ReferenceImportError(
@@ -80300,16 +80784,16 @@ function referenceFilesOnDisk(projectId) {
80300
80784
  }
80301
80785
  function originalPath(projectId, relPath) {
80302
80786
  const abs = insideProject(projectId, relPath);
80303
- return (0, import_node_fs49.existsSync)(abs) ? abs : null;
80787
+ return (0, import_node_fs51.existsSync)(abs) ? abs : null;
80304
80788
  }
80305
80789
  async function writeCache2(projectId, refId2, cache2, options = {}) {
80306
80790
  collectStalePendingCacheGenerations(projectId, refId2);
80307
80791
  const binary = binaryCachePath(projectId, refId2, cache2.sourceHash, cache2.filter, cache2.v);
80308
80792
  const sequence = (++cacheGenerationSequence).toString(36).padStart(8, "0");
80309
80793
  const suffix = options.staged ? ".pending" : ".bin";
80310
- const generation = `${binary.slice(0, -4)}-${Date.now().toString(36)}-${sequence}-${(0, import_node_crypto34.randomUUID)()}${suffix}`;
80794
+ const generation = `${binary.slice(0, -4)}-${Date.now().toString(36)}-${sequence}-${(0, import_node_crypto36.randomUUID)()}${suffix}`;
80311
80795
  const binaryTmp = `${generation}.${process.pid}.part`;
80312
- const pendingToken = options.staged ? (0, import_node_path43.resolve)(generation) : null;
80796
+ const pendingToken = options.staged ? (0, import_node_path45.resolve)(generation) : null;
80313
80797
  if (pendingToken) activePendingCacheGenerations.add(pendingToken);
80314
80798
  let encoded;
80315
80799
  try {
@@ -80331,10 +80815,10 @@ async function writeCache2(projectId, refId2, cache2, options = {}) {
80331
80815
  return generation;
80332
80816
  }
80333
80817
  function cacheGenerationTarget(projectId, refId2, path, suffixes) {
80334
- const root6 = (0, import_node_path43.resolve)(projectDir(projectId));
80335
- const target = (0, import_node_path43.resolve)(path);
80336
- const name = (0, import_node_path43.basename)(target);
80337
- if ((0, import_node_path43.dirname)(target) !== root6 || !name.startsWith(binaryCachePrefix(refId2)) || !suffixes.some((suffix) => name.endsWith(suffix))) {
80818
+ const root6 = (0, import_node_path45.resolve)(projectDir(projectId));
80819
+ const target = (0, import_node_path45.resolve)(path);
80820
+ const name = (0, import_node_path45.basename)(target);
80821
+ if ((0, import_node_path45.dirname)(target) !== root6 || !name.startsWith(binaryCachePrefix(refId2)) || !suffixes.some((suffix) => name.endsWith(suffix))) {
80338
80822
  throw new ReferenceImportError("that reference cache generation cannot be changed safely");
80339
80823
  }
80340
80824
  return target;
@@ -80342,24 +80826,24 @@ function cacheGenerationTarget(projectId, refId2, path, suffixes) {
80342
80826
  function commitCacheGeneration(projectId, refId2, pendingPath) {
80343
80827
  const pending = cacheGenerationTarget(projectId, refId2, pendingPath, [".pending"]);
80344
80828
  const committed = `${pending.slice(0, -".pending".length)}.bin`;
80345
- (0, import_node_fs49.renameSync)(pending, committed);
80829
+ (0, import_node_fs51.renameSync)(pending, committed);
80346
80830
  activePendingCacheGenerations.delete(pending);
80347
80831
  return committed;
80348
80832
  }
80349
80833
  function removeCacheGeneration(projectId, refId2, path) {
80350
80834
  const target = cacheGenerationTarget(projectId, refId2, path, [".bin", ".pending"]);
80351
80835
  activePendingCacheGenerations.delete(target);
80352
- (0, import_node_fs49.rmSync)(target, { force: true });
80836
+ (0, import_node_fs51.rmSync)(target, { force: true });
80353
80837
  }
80354
80838
  function collectStalePendingCacheGenerations(projectId, refId2) {
80355
80839
  const staleBefore = Date.now() - CACHE_PENDING_TTL_MS;
80356
80840
  try {
80357
- for (const name of (0, import_node_fs49.readdirSync)(projectDir(projectId))) {
80841
+ for (const name of (0, import_node_fs51.readdirSync)(projectDir(projectId))) {
80358
80842
  if (!name.startsWith(binaryCachePrefix(refId2)) || !name.endsWith(".pending")) continue;
80359
- const candidate = (0, import_node_path43.resolve)((0, import_node_path43.join)(projectDir(projectId), name));
80843
+ const candidate = (0, import_node_path45.resolve)((0, import_node_path45.join)(projectDir(projectId), name));
80360
80844
  if (activePendingCacheGenerations.has(candidate)) continue;
80361
80845
  try {
80362
- if ((0, import_node_fs49.statSync)(candidate).mtimeMs < staleBefore) (0, import_node_fs49.rmSync)(candidate, { force: true });
80846
+ if ((0, import_node_fs51.statSync)(candidate).mtimeMs < staleBefore) (0, import_node_fs51.rmSync)(candidate, { force: true });
80363
80847
  } catch {
80364
80848
  }
80365
80849
  }
@@ -80369,21 +80853,21 @@ function collectStalePendingCacheGenerations(projectId, refId2) {
80369
80853
  }
80370
80854
  }
80371
80855
  function pruneCache(projectId, refId2, committedGeneration, options = {}) {
80372
- const root6 = (0, import_node_path43.resolve)(projectDir(projectId));
80373
- const preserve = (0, import_node_path43.resolve)(committedGeneration);
80374
- const preserveName = (0, import_node_path43.basename)(preserve);
80375
- if ((0, import_node_path43.dirname)(preserve) !== root6 || !preserveName.startsWith(binaryCachePrefix(refId2)) || !preserveName.endsWith(".bin") || !(0, import_node_fs49.existsSync)(preserve)) {
80856
+ const root6 = (0, import_node_path45.resolve)(projectDir(projectId));
80857
+ const preserve = (0, import_node_path45.resolve)(committedGeneration);
80858
+ const preserveName = (0, import_node_path45.basename)(preserve);
80859
+ if ((0, import_node_path45.dirname)(preserve) !== root6 || !preserveName.startsWith(binaryCachePrefix(refId2)) || !preserveName.endsWith(".bin") || !(0, import_node_fs51.existsSync)(preserve)) {
80376
80860
  throw new Error("the committed reference cache generation is unavailable");
80377
80861
  }
80378
80862
  try {
80379
- publishCurrentCacheGeneration(projectId, refId2, (0, import_node_path43.basename)(preserve));
80863
+ publishCurrentCacheGeneration(projectId, refId2, (0, import_node_path45.basename)(preserve));
80380
80864
  } catch (error) {
80381
- (0, import_node_fs49.rmSync)(preserve, { force: true });
80865
+ (0, import_node_fs51.rmSync)(preserve, { force: true });
80382
80866
  throw error;
80383
80867
  }
80384
80868
  const committedAt = /* @__PURE__ */ new Date();
80385
80869
  try {
80386
- (0, import_node_fs49.utimesSync)(preserve, committedAt, committedAt);
80870
+ (0, import_node_fs51.utimesSync)(preserve, committedAt, committedAt);
80387
80871
  } catch {
80388
80872
  }
80389
80873
  sweepExpiredCacheGenerations(projectId, refId2, preserve);
@@ -80409,19 +80893,19 @@ function filterKey(filter) {
80409
80893
  function cachedGeometryBinary(projectId, refId2, expectHash, expectFilter) {
80410
80894
  const candidates = binaryCacheCandidates(projectId, refId2, expectHash, expectFilter);
80411
80895
  for (const path of candidates) {
80412
- if (!(0, import_node_fs49.existsSync)(path)) continue;
80896
+ if (!(0, import_node_fs51.existsSync)(path)) continue;
80413
80897
  let fd2 = null;
80414
80898
  try {
80415
- fd2 = (0, import_node_fs49.openSync)(path, "r");
80416
- const size = (0, import_node_fs49.fstatSync)(fd2).size;
80899
+ fd2 = (0, import_node_fs51.openSync)(path, "r");
80900
+ const size = (0, import_node_fs51.fstatSync)(fd2).size;
80417
80901
  const manifest = readReferenceBinaryHandleManifest(fd2, size);
80418
80902
  if (manifest.v !== REFERENCE_CACHE_VERSION || manifest.sourceHash !== expectHash || filterKey(manifest.filter) !== filterKey(expectFilter)) {
80419
- (0, import_node_fs49.closeSync)(fd2);
80903
+ (0, import_node_fs51.closeSync)(fd2);
80420
80904
  return null;
80421
80905
  }
80422
80906
  return { fd: fd2, size, path };
80423
80907
  } catch (error) {
80424
- if (fd2 !== null) (0, import_node_fs49.closeSync)(fd2);
80908
+ if (fd2 !== null) (0, import_node_fs51.closeSync)(fd2);
80425
80909
  const code = error?.code;
80426
80910
  if (code && ["EACCES", "EBUSY", "EMFILE", "ENFILE"].includes(code)) {
80427
80911
  throw new ReferenceImportError("the reference cache could not be opened \u2014 check the project folder is readable and try again");
@@ -80432,20 +80916,20 @@ function cachedGeometryBinary(projectId, refId2, expectHash, expectFilter) {
80432
80916
  return null;
80433
80917
  }
80434
80918
  function dropCache(projectId, refId2) {
80435
- const timerKey = `${(0, import_node_path43.resolve)(projectDir(projectId))}\0${safeId2(refId2)}`;
80919
+ const timerKey = `${(0, import_node_path45.resolve)(projectDir(projectId))}\0${safeId2(refId2)}`;
80436
80920
  const timer = cachePruneTimers.get(timerKey);
80437
80921
  if (timer) {
80438
80922
  clearTimeout(timer);
80439
80923
  cachePruneTimers.delete(timerKey);
80440
80924
  }
80441
- (0, import_node_fs49.rmSync)(legacyJsonCachePath(projectId, refId2), { force: true });
80442
- (0, import_node_fs49.rmSync)(legacyBinaryCachePath(projectId, refId2), { force: true });
80443
- (0, import_node_fs49.rmSync)(cacheCurrentPath(projectId, refId2), { force: true });
80925
+ (0, import_node_fs51.rmSync)(legacyJsonCachePath(projectId, refId2), { force: true });
80926
+ (0, import_node_fs51.rmSync)(legacyBinaryCachePath(projectId, refId2), { force: true });
80927
+ (0, import_node_fs51.rmSync)(cacheCurrentPath(projectId, refId2), { force: true });
80444
80928
  const prefix = binaryCachePrefix(refId2);
80445
80929
  try {
80446
- for (const name of (0, import_node_fs49.readdirSync)(projectDir(projectId))) if (name.startsWith(prefix) && (name.endsWith(".bin") || name.endsWith(".pending") || name.endsWith(".part"))) {
80447
- activePendingCacheGenerations.delete((0, import_node_path43.resolve)((0, import_node_path43.join)(projectDir(projectId), name)));
80448
- (0, import_node_fs49.rmSync)((0, import_node_path43.join)(projectDir(projectId), name), { force: true });
80930
+ for (const name of (0, import_node_fs51.readdirSync)(projectDir(projectId))) if (name.startsWith(prefix) && (name.endsWith(".bin") || name.endsWith(".pending") || name.endsWith(".part"))) {
80931
+ activePendingCacheGenerations.delete((0, import_node_path45.resolve)((0, import_node_path45.join)(projectDir(projectId), name)));
80932
+ (0, import_node_fs51.rmSync)((0, import_node_path45.join)(projectDir(projectId), name), { force: true });
80449
80933
  }
80450
80934
  } catch (error) {
80451
80935
  if (error.code !== "ENOENT") throw error;
@@ -80453,10 +80937,10 @@ function dropCache(projectId, refId2) {
80453
80937
  }
80454
80938
  function removeReference(projectId, refId2, relPath) {
80455
80939
  dropCache(projectId, refId2);
80456
- if (relPath) (0, import_node_fs49.rmSync)(insideProject(projectId, relPath), { force: true });
80940
+ if (relPath) (0, import_node_fs51.rmSync)(insideProject(projectId, relPath), { force: true });
80457
80941
  }
80458
80942
  function removeReferenceFile(projectId, relPath) {
80459
- (0, import_node_fs49.rmSync)(insideProject(projectId, relPath), { force: true });
80943
+ (0, import_node_fs51.rmSync)(insideProject(projectId, relPath), { force: true });
80460
80944
  }
80461
80945
  function takenReferencePaths(refs) {
80462
80946
  return new Set((refs ?? []).map((r) => r.file).filter((f) => typeof f === "string"));
@@ -81074,7 +81558,7 @@ function registerReferenceRoutes(app, deps) {
81074
81558
  return reply.status(404).send({ ok: false, error: "the uploaded IFC is no longer available \u2014 drop the file again" });
81075
81559
  }
81076
81560
  const displayName = String(name || "model.ifc");
81077
- const id = (0, import_node_crypto35.randomUUID)();
81561
+ const id = (0, import_node_crypto37.randomUUID)();
81078
81562
  let rel;
81079
81563
  try {
81080
81564
  rel = await withLifecycleLock("project", g.project, () => {
@@ -81244,7 +81728,7 @@ function registerReferenceRoutes(app, deps) {
81244
81728
  const stored2 = entry2.filter;
81245
81729
  const hit = rebuild ? null : cachedGeometryBinary(g.project, entry2.id, sourceHash, stored2);
81246
81730
  if (hit) {
81247
- return reply.type(REFERENCE_BINARY_TYPE).header("content-length", String(hit.size)).header("x-floless-reference-cache", "hit").send((0, import_node_fs50.createReadStream)(hit.path, { fd: hit.fd, autoClose: true }));
81731
+ return reply.type(REFERENCE_BINARY_TYPE).header("content-length", String(hit.size)).header("x-floless-reference-cache", "hit").send((0, import_node_fs52.createReadStream)(hit.path, { fd: hit.fd, autoClose: true }));
81248
81732
  }
81249
81733
  let preview2 = null;
81250
81734
  try {
@@ -81301,7 +81785,7 @@ function registerReferenceRoutes(app, deps) {
81301
81785
  }
81302
81786
  const built = cachedGeometryBinary(g.project, entry2.id, sourceHash, stored2);
81303
81787
  if (!built) throw new Error("the reference binary was not published");
81304
- return reply.type(REFERENCE_BINARY_TYPE).header("content-length", String(built.size)).header("x-floless-reference-cache", "miss").send((0, import_node_fs50.createReadStream)(built.path, { fd: built.fd, autoClose: true }));
81788
+ return reply.type(REFERENCE_BINARY_TYPE).header("content-length", String(built.size)).header("x-floless-reference-cache", "miss").send((0, import_node_fs52.createReadStream)(built.path, { fd: built.fd, autoClose: true }));
81305
81789
  } catch (e) {
81306
81790
  if (e instanceof LifecycleLockBusyError) throw e;
81307
81791
  const r = importRefusal(e);
@@ -81383,7 +81867,7 @@ function registerReferenceRoutes(app, deps) {
81383
81867
  };
81384
81868
  try {
81385
81869
  try {
81386
- assertAcceptable((0, import_node_fs50.statSync)(source).size, displayName);
81870
+ assertAcceptable((0, import_node_fs52.statSync)(source).size, displayName);
81387
81871
  } catch (e) {
81388
81872
  const r = importRefusal(e);
81389
81873
  if (r) return reply.status(r.status).send(r.body);
@@ -81988,10 +82472,10 @@ function registerReferenceRoutes(app, deps) {
81988
82472
 
81989
82473
  // bom-export.ts
81990
82474
  var import_node_os27 = require("node:os");
81991
- var import_node_path44 = require("node:path");
82475
+ var import_node_path46 = require("node:path");
81992
82476
 
81993
82477
  // node_modules/write-excel-file/modules/export/writeXlsxFileNode.js
81994
- var import_node_fs51 = __toESM(require("node:fs"), 1);
82478
+ var import_node_fs53 = __toESM(require("node:fs"), 1);
81995
82479
 
81996
82480
  // node_modules/write-excel-file/modules/xlsx/helpers/features/getAdditionalContent.js
81997
82481
  function _createForOfIteratorHelperLoose(r, e) {
@@ -85091,7 +85575,7 @@ function writeXlsxFile(arg1, arg2, arg3) {
85091
85575
  },
85092
85576
  toFile: function toFile(filePath) {
85093
85577
  return createReadableStream().then(function(readableStream) {
85094
- return pipe(readableStream, import_node_fs51.default.createWriteStream(filePath));
85578
+ return pipe(readableStream, import_node_fs53.default.createWriteStream(filePath));
85095
85579
  });
85096
85580
  }
85097
85581
  };
@@ -85353,8 +85837,8 @@ var BOM_EXPORT_KIND = {
85353
85837
  html: "bom-html"
85354
85838
  };
85355
85839
  function bomExportPath(appId, format) {
85356
- const root6 = process.env.FLOLESS_HOME ?? (0, import_node_path44.join)((0, import_node_os27.homedir)(), ".floless");
85357
- return (0, import_node_path44.join)(root6, "exports", appId, `${appId}-bom.${format}`);
85840
+ const root6 = process.env.FLOLESS_HOME ?? (0, import_node_path46.join)((0, import_node_os27.homedir)(), ".floless");
85841
+ return (0, import_node_path46.join)(root6, "exports", appId, `${appId}-bom.${format}`);
85358
85842
  }
85359
85843
  function csvField(v) {
85360
85844
  let s = String(v);
@@ -85532,7 +86016,14 @@ function registerContractAccessRoutes(app, deps) {
85532
86016
  if (!snapshot && req.query.quietMissing === "1") return reply.status(204).send();
85533
86017
  if (!snapshot) return reply.status(404).send({ ok: false, error: "no contract for this app yet" });
85534
86018
  reply.header("ETag", snapshot.etag);
85535
- return snapshot;
86019
+ const asked = (Array.isArray(req.query.recordedEtag) ? req.query.recordedEtag : [req.query.recordedEtag]).filter((tag) => typeof tag === "string" && tag !== "");
86020
+ const recorded = [...new Set(asked)].slice(0, 4);
86021
+ if (!recorded.length) return snapshot;
86022
+ const names2 = deps.recordedEtagsNameDocument(recorded, snapshot.contract);
86023
+ return {
86024
+ ...snapshot,
86025
+ recordedBases: recorded.map((tag, i) => ({ recorded: tag, namesSnapshot: names2[i] === true }))
86026
+ };
85536
86027
  });
85537
86028
  app.post(
85538
86029
  "/api/contract/:appId/scene",
@@ -85753,8 +86244,8 @@ function workspaceContractLifecycle(contract, hasHistory = false) {
85753
86244
  }
85754
86245
 
85755
86246
  // project-export-files.ts
85756
- var import_node_fs52 = require("node:fs");
85757
- var import_node_path45 = require("node:path");
86247
+ var import_node_fs54 = require("node:fs");
86248
+ var import_node_path47 = require("node:path");
85758
86249
  function projectExportFiles(appId, kindOf2 = appId) {
85759
86250
  if (kindOf2 === "vectorize") {
85760
86251
  return [{ kind: "svg", filename: `${appId}.svg` }];
@@ -85783,119 +86274,16 @@ function exportFileBase(projectId, appId, now = /* @__PURE__ */ new Date()) {
85783
86274
  }
85784
86275
  function uniqueProjectExportFilename(projectId, preferred) {
85785
86276
  const dir = projectExportsDir(projectId);
85786
- if (!(0, import_node_fs52.existsSync)((0, import_node_path45.join)(dir, preferred))) return preferred;
85787
- const extension = (0, import_node_path45.extname)(preferred);
86277
+ if (!(0, import_node_fs54.existsSync)((0, import_node_path47.join)(dir, preferred))) return preferred;
86278
+ const extension = (0, import_node_path47.extname)(preferred);
85788
86279
  const stem = preferred.slice(0, preferred.length - extension.length);
85789
86280
  for (let suffix = 2; suffix <= 9999; suffix += 1) {
85790
86281
  const candidate = `${stem}-${suffix}${extension}`;
85791
- if (!(0, import_node_fs52.existsSync)((0, import_node_path45.join)(dir, candidate))) return candidate;
86282
+ if (!(0, import_node_fs54.existsSync)((0, import_node_path47.join)(dir, candidate))) return candidate;
85792
86283
  }
85793
86284
  throw new Error("could not allocate a unique project export filename");
85794
86285
  }
85795
86286
 
85796
- // workspace-approved-snapshot.ts
85797
- var WorkspaceSnapshotError = class extends Error {
85798
- constructor(status, message, notReviewable, version) {
85799
- super(message);
85800
- this.status = status;
85801
- this.notReviewable = notReviewable;
85802
- this.version = version;
85803
- }
85804
- status;
85805
- notReviewable;
85806
- version;
85807
- };
85808
- var NoApprovedVersionError = class extends WorkspaceSnapshotError {
85809
- constructor() {
85810
- super(409, "project has no approved version");
85811
- this.name = "NoApprovedVersionError";
85812
- }
85813
- };
85814
- function approvedRows(projectId) {
85815
- const project = getProject(projectId);
85816
- if (!project) return [];
85817
- const allRows = listVersions(projectId);
85818
- if (project.uuid) {
85819
- const tainted = allRows.find((v) => v.gate === "model" && v.kind === "approve" && !v.approval);
85820
- if (tainted) {
85821
- throw new WorkspaceSnapshotError(409, `project has no approved version: approved version ${tainted.n} has no approval proof`, void 0, tainted.n);
85822
- }
85823
- }
85824
- const projectTime = Date.parse(project.createdAt);
85825
- return allRows.filter((v) => v.gate === "model" && v.kind === "approve").filter((v) => v.approval ? !!project.uuid && v.approval.projectUuid === project.uuid : Number.isFinite(projectTime) && Date.parse(v.ts) >= projectTime).map(({ current: _current, ...meta }) => meta);
85826
- }
85827
- function latestApprovedVersion(projectId) {
85828
- return approvedRows(projectId)[0] ?? null;
85829
- }
85830
- function listApprovedVersionMetadata(projectId) {
85831
- return approvedRows(projectId);
85832
- }
85833
- function currentApprovedSnapshot(projectId, version) {
85834
- const project = getProject(projectId);
85835
- if (!project) throw new WorkspaceSnapshotError(404, `unknown project: ${projectId}`);
85836
- const rows2 = approvedRows(projectId);
85837
- const row = version === void 0 ? rows2[0] : rows2.find((v) => v.n === version);
85838
- if (!row) {
85839
- if (version === void 0) throw new NoApprovedVersionError();
85840
- throw new WorkspaceSnapshotError(404, `approved version not found: ${version}`);
85841
- }
85842
- const latest = rows2[0];
85843
- const assertOwned = (candidate, hash3) => {
85844
- if (candidate.approval) {
85845
- if (!project.uuid || candidate.approval.projectUuid !== project.uuid) {
85846
- throw new WorkspaceSnapshotError(409, `approved version ${candidate.n} belongs to another project incarnation`);
85847
- }
85848
- if (candidate.approval.candidateHash !== hash3) {
85849
- throw new WorkspaceSnapshotError(409, `approved version ${candidate.n} failed its content-hash proof`);
85850
- }
85851
- return;
85852
- }
85853
- const rowTime = Date.parse(candidate.ts);
85854
- const projectTime = Date.parse(project.createdAt);
85855
- if (!Number.isFinite(rowTime) || !Number.isFinite(projectTime) || rowTime < projectTime) {
85856
- throw new WorkspaceSnapshotError(409, `approved version ${candidate.n} has no ownership proof`);
85857
- }
85858
- };
85859
- const contract = readAcceptedVersion(projectId, row.n, { appId: project.app, projectId, operation: "read" });
85860
- if (contract == null) throw new WorkspaceSnapshotError(409, `approved version ${row.n} is unreadable`);
85861
- const selectedHash = contractHash(contract);
85862
- assertOwned(row, selectedHash);
85863
- const latestContract = latest.n === row.n ? contract : readAcceptedVersion(projectId, latest.n, { appId: project.app, projectId, operation: "read" });
85864
- if (latestContract == null) throw new WorkspaceSnapshotError(409, `approved version ${latest.n} is unreadable`);
85865
- const latestHash = contractHash(latestContract);
85866
- assertOwned(latest, latestHash);
85867
- const draft = readAcceptedForRequest(project.app, projectId, "read");
85868
- const comparable = comparableContractHash;
85869
- const dirtySinceApproval = draft == null || comparable(draft) !== comparable(latestContract);
85870
- return {
85871
- project,
85872
- version: row,
85873
- contract,
85874
- contractHash: selectedHash,
85875
- currentApprovedAt: project.approvedAt ?? null,
85876
- dirtySinceApproval,
85877
- latestApprovedVersion: latest.n,
85878
- headDiverged: row.n !== latest.n
85879
- };
85880
- }
85881
- function approvedSnapshotForMetadata(projectId, surface, onRefusal) {
85882
- try {
85883
- return currentApprovedSnapshot(projectId);
85884
- } catch (error) {
85885
- if (error instanceof NoApprovedVersionError) return null;
85886
- if (error instanceof WorkspaceSnapshotError && error.status === 404) throw error;
85887
- if (error instanceof WorkspaceSnapshotError || error instanceof ContractPolicyError) {
85888
- const status = error instanceof WorkspaceSnapshotError ? error.status : error.code;
85889
- onRefusal?.(error);
85890
- console.error(
85891
- `${surface}: project ${projectId} has an approved version the gate refused to serve (${status}) \u2014 reporting no approved head. ${error.message}`
85892
- );
85893
- return null;
85894
- }
85895
- throw error;
85896
- }
85897
- }
85898
-
85899
86287
  // approval-partition.ts
85900
86288
  var unchangedNode = (value) => ({ materialize: () => value });
85901
86289
  var atomicNode = (groupId, before, after) => ({
@@ -86480,82 +86868,6 @@ function buildApprovalReview(input) {
86480
86868
  return prepared;
86481
86869
  }
86482
86870
 
86483
- // working-revision-manifest.ts
86484
- var import_node_crypto36 = require("node:crypto");
86485
- var import_node_fs53 = require("node:fs");
86486
- var import_node_path46 = require("node:path");
86487
- var nativePublicationIdentity = (projectUuid) => `project:${projectUuid}`;
86488
- var pathOf = (projectId) => (0, import_node_path46.join)(projectDir(projectId), ".floless-working-revision-state-v1.json");
86489
- var checksumOf = (body) => hashOf(body);
86490
- function bodyOf(value) {
86491
- const { checksum: _checksum, ...body } = value;
86492
- return body;
86493
- }
86494
- function assertProject(project) {
86495
- if (!project.uuid) throw new Error(`project ${project.id} has no incarnation UUID`);
86496
- return project.uuid;
86497
- }
86498
- function readWorkingRevisionManifest(project) {
86499
- const uuid = assertProject(project);
86500
- try {
86501
- const value = JSON.parse((0, import_node_fs53.readFileSync)(pathOf(project.id), "utf8"));
86502
- if (value?.schema !== 1 || value.projectUuid !== uuid || !Number.isInteger(value.epoch) || value.epoch < 0) return null;
86503
- return checksumOf(bodyOf(value)) === value.checksum ? value : null;
86504
- } catch {
86505
- return null;
86506
- }
86507
- }
86508
- function ensureWorkingRevisionManifest(input) {
86509
- const existing = readWorkingRevisionManifest(input.project);
86510
- if (existing) return existing;
86511
- const body = {
86512
- schema: 1,
86513
- projectUuid: assertProject(input.project),
86514
- publicationIdentity: input.publicationIdentity,
86515
- revisionId: (0, import_node_crypto36.randomUUID)(),
86516
- epoch: 0,
86517
- source: { kind: "working" },
86518
- workingBase: input.workingBase,
86519
- draftHash: hashOf(input.contract),
86520
- updatedAt: (/* @__PURE__ */ new Date()).toISOString()
86521
- };
86522
- const value = { ...body, checksum: checksumOf(body) };
86523
- (0, import_node_fs53.mkdirSync)(projectDir(input.project.id), { recursive: true });
86524
- if (!(0, import_node_fs53.existsSync)(pathOf(input.project.id))) writeJsonAtomic(pathOf(input.project.id), value);
86525
- return readWorkingRevisionManifest(input.project) ?? value;
86526
- }
86527
- function advanceWorkingRevisionManifest(input) {
86528
- const current = readWorkingRevisionManifest(input.project);
86529
- if (!current) throw new Error("working revision state is missing or corrupt");
86530
- if (current.epoch !== input.expectedEpoch || current.draftHash !== input.expectedDraftHash) {
86531
- throw new Error("working revision changed; reload before continuing");
86532
- }
86533
- if (current.publicationIdentity !== input.publicationIdentity) throw new Error("working revision belongs to another app publication");
86534
- const body = {
86535
- ...bodyOf(current),
86536
- revisionId: (0, import_node_crypto36.randomUUID)(),
86537
- epoch: current.epoch + 1,
86538
- source: input.source,
86539
- workingBase: input.workingBase,
86540
- draftHash: hashOf(input.contract),
86541
- updatedAt: (/* @__PURE__ */ new Date()).toISOString()
86542
- };
86543
- const value = { ...body, checksum: checksumOf(body) };
86544
- writeJsonAtomic(pathOf(input.project.id), value);
86545
- return value;
86546
- }
86547
- function refreshWorkingDraftHash(input) {
86548
- const current = readWorkingRevisionManifest(input.project);
86549
- if (!current) throw new Error("working revision state is missing or corrupt");
86550
- if (current.epoch !== input.expectedEpoch || current.draftHash !== input.expectedDraftHash) {
86551
- throw new Error("working revision changed; reload before saving");
86552
- }
86553
- const body = { ...bodyOf(current), draftHash: hashOf(input.contract), updatedAt: (/* @__PURE__ */ new Date()).toISOString() };
86554
- const value = { ...body, checksum: checksumOf(body) };
86555
- writeJsonAtomic(pathOf(input.project.id), value);
86556
- return value;
86557
- }
86558
-
86559
86871
  // three-way-contract-merge.ts
86560
86872
  var MISSING = /* @__PURE__ */ Symbol("missing");
86561
86873
  var same3 = (a, b) => canonicalJson(a) === canonicalJson(b);
@@ -86791,110 +87103,6 @@ function projectApprovalCandidateAccepted(appId, projectId, candidate) {
86791
87103
  return acceptSteelForRoute(candidate, { appId, projectId }, "stored").accepted;
86792
87104
  }
86793
87105
 
86794
- // project-checkpoints-store.ts
86795
- var import_node_crypto37 = require("node:crypto");
86796
- var import_node_fs54 = require("node:fs");
86797
- var import_node_path47 = require("node:path");
86798
- var HASH_RE3 = /^[0-9a-f]{64}$/;
86799
- function root5(projectId) {
86800
- return (0, import_node_path47.join)(projectDir(projectId), ".floless-checkpoints-store-v1");
86801
- }
86802
- var objectsDir2 = (projectId) => (0, import_node_path47.join)(root5(projectId), "objects");
86803
- var eventsPath = (projectId) => (0, import_node_path47.join)(root5(projectId), "events.json");
86804
- function readEvents(projectId) {
86805
- try {
86806
- const parsed = JSON.parse((0, import_node_fs54.readFileSync)(eventsPath(projectId), "utf8"));
86807
- if (parsed?.schema !== 1 || !Array.isArray(parsed.events)) return { schema: 1, events: [] };
86808
- return { schema: 1, events: parsed.events.filter(validEvent) };
86809
- } catch {
86810
- return { schema: 1, events: [] };
86811
- }
86812
- }
86813
- function validEvent(value) {
86814
- if (!value || typeof value !== "object") return false;
86815
- const e = value;
86816
- return typeof e.eventId === "string" && typeof e.checkpointId === "string" && HASH_RE3.test(e.checkpointId) && (e.kind === "captured" || e.kind === "archived" || e.kind === "incorporated") && typeof e.at === "string" && Number.isInteger(e.revisionEpoch) && typeof e.appIdAtCapture === "string";
86817
- }
86818
- function readContent(projectId, id) {
86819
- if (!HASH_RE3.test(id)) return null;
86820
- try {
86821
- const value = JSON.parse((0, import_node_fs54.readFileSync)((0, import_node_path47.join)(objectsDir2(projectId), `${id}.json`), "utf8"));
86822
- if (value?.schema !== 1 || value.id !== id || hashCheckpoint(value) !== id) return null;
86823
- return value;
86824
- } catch {
86825
- return null;
86826
- }
86827
- }
86828
- function hashCheckpoint(value) {
86829
- const { id: _id, ...identity } = value;
86830
- return hashOf(identity);
86831
- }
86832
- function requireIdentity(project) {
86833
- if (!project.uuid) throw new Error(`project ${project.id} has no incarnation UUID`);
86834
- return project.uuid;
86835
- }
86836
- function appendEvent(projectId, event) {
86837
- (0, import_node_fs54.mkdirSync)(root5(projectId), { recursive: true });
86838
- const log2 = readEvents(projectId);
86839
- const row = { ...event, eventId: (0, import_node_crypto37.randomUUID)(), at: (/* @__PURE__ */ new Date()).toISOString() };
86840
- log2.events.push(row);
86841
- writeJsonAtomic(eventsPath(projectId), log2);
86842
- return row;
86843
- }
86844
- function captureProjectCheckpoint(input) {
86845
- const projectUuid = requireIdentity(input.project);
86846
- const withoutId = {
86847
- schema: 1,
86848
- projectUuid,
86849
- publicationIdentity: input.publicationIdentity,
86850
- base: input.base,
86851
- draftHash: hashOf(input.contract),
86852
- contract: input.contract
86853
- };
86854
- const id = hashCheckpoint(withoutId);
86855
- (0, import_node_fs54.mkdirSync)(objectsDir2(input.project.id), { recursive: true });
86856
- const path = (0, import_node_path47.join)(objectsDir2(input.project.id), `${id}.json`);
86857
- if (!(0, import_node_fs54.existsSync)(path)) writeJsonAtomic(path, { ...withoutId, id });
86858
- const event = appendEvent(input.project.id, {
86859
- checkpointId: id,
86860
- kind: "captured",
86861
- revisionEpoch: input.revisionEpoch,
86862
- appIdAtCapture: input.project.app
86863
- });
86864
- return describe(input.project.id, { ...withoutId, id }, event.eventId);
86865
- }
86866
- function describe(projectId, content, latestEventId) {
86867
- const events = readEvents(projectId).events.filter((event) => event.checkpointId === content.id);
86868
- const captures = events.filter((event) => event.kind === "captured");
86869
- const first = captures[0];
86870
- const latest = events.at(-1);
86871
- if (!first || !latest) return null;
86872
- return {
86873
- ...content,
86874
- capturedAt: first.at,
86875
- archived: latest.kind === "archived",
86876
- incorporated: events.some((event) => event.kind === "incorporated"),
86877
- captureCount: captures.length,
86878
- latestEventId: latestEventId ?? latest.eventId
86879
- };
86880
- }
86881
- function listProjectCheckpoints(project) {
86882
- const uuid = requireIdentity(project);
86883
- const ids = [...new Set(readEvents(project.id).events.map((event) => event.checkpointId))];
86884
- return ids.map((id) => readContent(project.id, id)).filter((v) => v !== null).filter((v) => v.projectUuid === uuid).map((v) => describe(project.id, v)).filter((v) => v !== null).sort((a, b) => b.capturedAt.localeCompare(a.capturedAt));
86885
- }
86886
- function readProjectCheckpoint(project, checkpointId) {
86887
- const content = readContent(project.id, checkpointId);
86888
- return content && content.projectUuid === requireIdentity(project) ? describe(project.id, content) : null;
86889
- }
86890
- function markProjectCheckpoint(project, checkpointId, kind, expectedEventId) {
86891
- const current = readProjectCheckpoint(project, checkpointId);
86892
- if (!current) throw new Error(`unknown checkpoint: ${checkpointId}`);
86893
- if (current.latestEventId !== expectedEventId) throw new Error("checkpoint changed; reload saved work");
86894
- const event = appendEvent(project.id, { checkpointId, kind, revisionEpoch: 0, appIdAtCapture: project.app });
86895
- return describe(project.id, current, event.eventId);
86896
- }
86897
-
86898
87106
  // export-source.ts
86899
87107
  var import_node_crypto38 = require("node:crypto");
86900
87108
  var import_node_fs55 = require("node:fs");
@@ -100308,131 +100516,7 @@ async function startServer() {
100308
100516
  }))
100309
100517
  }), { label: "listing saved work" });
100310
100518
  });
100311
- app.post(
100312
- "/api/projects/:id/revisions/start",
100313
- async (req, reply) => {
100314
- const project = getProject(req.params.id);
100315
- if (!project?.uuid) return reply.status(project ? 409 : 404).send({ ok: false, error: project ? "project has no incarnation identity" : `unknown project: ${req.params.id}` });
100316
- const version = Number(req.body?.version);
100317
- if (!Number.isInteger(version) || version < 1) return reply.status(400).send({ ok: false, error: "choose a valid approved version" });
100318
- return withLifecycleLock("project", project.id, async () => {
100319
- let target;
100320
- try {
100321
- target = currentApprovedSnapshot(project.id, version);
100322
- } catch (error) {
100323
- if (error instanceof WorkspaceSnapshotError) return reply.status(error.status).send({ ok: false, error: error.message });
100324
- throw error;
100325
- }
100326
- const current = readAcceptedForRequest(project.app, project.id, "read");
100327
- if (current == null) return reply.status(409).send({ ok: false, error: "the current working copy is unreadable" });
100328
- const actualEtags = storeEtags(project.app, project.id);
100329
- const suppliedEpoch = req.body && Object.prototype.hasOwnProperty.call(req.body, "expectedEpoch") ? req.body.expectedEpoch : void 0;
100330
- if (typeof req.body?.expectedEtag !== "string" || suppliedEpoch !== null && (!Number.isInteger(Number(suppliedEpoch)) || Number(suppliedEpoch) < 0)) {
100331
- return reply.status(428).send({ ok: false, error: "Reload History and send the working ETag and revision epoch." });
100332
- }
100333
- if (!recordedEtagNamesContract(req.body.expectedEtag, actualEtags)) {
100334
- return reply.status(409).send({ ok: false, error: "The working copy changed. Reload History before starting." });
100335
- }
100336
- const observedManifest = readWorkingRevisionManifest(project);
100337
- if ((observedManifest?.epoch ?? null) !== (suppliedEpoch === null ? null : Number(suppliedEpoch))) {
100338
- return reply.status(409).send({ ok: false, error: "The working revision changed. Reload History before starting." });
100339
- }
100340
- const publicationIdentity = observedManifest?.publicationIdentity ?? nativePublicationIdentity(project.uuid);
100341
- let manifest = ensureWorkingRevisionManifest({
100342
- project,
100343
- publicationIdentity,
100344
- contract: current,
100345
- workingBase: { version: target.latestApprovedVersion, hash: currentApprovedSnapshot(project.id).contractHash }
100346
- });
100347
- if (manifest.draftHash !== contractHash(current)) {
100348
- manifest = refreshWorkingDraftHash({ project, expectedEpoch: manifest.epoch, expectedDraftHash: manifest.draftHash, contract: current });
100349
- }
100350
- const latest = currentApprovedSnapshot(project.id);
100351
- const dirty = comparableContractHash(current) !== comparableContractHash(latest.contract);
100352
- const checkpoint = dirty ? captureProjectCheckpoint({
100353
- project,
100354
- publicationIdentity,
100355
- base: manifest.workingBase,
100356
- contract: current,
100357
- revisionEpoch: manifest.epoch
100358
- }) : null;
100359
- let publication = null;
100360
- try {
100361
- const written = await writeContractGenerationChecked(project.app, target.contract, project.id, `start a new revision from approved v${version}`, { restoring: true });
100362
- publication = written;
100363
- } catch (error) {
100364
- if (error instanceof ContractError) return reply.status(409).send({ ok: false, error: error.message });
100365
- throw error;
100366
- }
100367
- clearApproval(project.id);
100368
- const next = advanceWorkingRevisionManifest({
100369
- project,
100370
- expectedEpoch: manifest.epoch,
100371
- expectedDraftHash: manifest.draftHash,
100372
- publicationIdentity,
100373
- contract: normalisePlanViewIds(target.contract),
100374
- // The PROOFS stay the ledger's raw hashes — `workingBase.hash` is checked against History and
100375
- // `source.hash` names the version this came from — while `contract:` above is the document the
100376
- // gateway actually wrote, which is canonical. Hashing raw bytes into `draftHash` for a document
100377
- // stored canonically made the manifest disagree with the store the instant it was written.
100378
- source: { kind: "approved", version, hash: target.contractHash },
100379
- workingBase: { version, hash: target.contractHash }
100380
- });
100381
- broadcast(contractChangedWithReason(project.app, project.id, publication.etag, publication.storeRevision, "rollback"));
100382
- return {
100383
- ok: true,
100384
- checkpoint,
100385
- revision: next,
100386
- workingBaseVersion: version,
100387
- latestApprovedVersion: latest.version.n,
100388
- message: checkpoint ? `Saved pending work${checkpoint.base ? ` from v${checkpoint.base.version}` : ""}. Started a DRAFT from v${version}.` : `Started a DRAFT from v${version}.`
100389
- };
100390
- }, { label: `starting a revision from v${version}` });
100391
- }
100392
- );
100393
- app.post(
100394
- "/api/projects/:id/checkpoints/:checkpointId/resume",
100395
- async (req, reply) => {
100396
- const project = getProject(req.params.id);
100397
- if (!project?.uuid) return reply.status(project ? 409 : 404).send({ ok: false, error: project ? "project has no incarnation identity" : `unknown project: ${req.params.id}` });
100398
- return withLifecycleLock("project", project.id, async () => {
100399
- const saved = readProjectCheckpoint(project, req.params.checkpointId);
100400
- if (!saved) return reply.status(404).send({ ok: false, error: "checkpoint not found" });
100401
- const current = readAcceptedForRequest(project.app, project.id, "read");
100402
- if (current == null) return reply.status(409).send({ ok: false, error: "the current working copy is unreadable" });
100403
- const suppliedEpoch = req.body && Object.prototype.hasOwnProperty.call(req.body, "expectedEpoch") ? req.body.expectedEpoch : void 0;
100404
- if (typeof req.body?.expectedEtag !== "string" || suppliedEpoch !== null && (!Number.isInteger(Number(suppliedEpoch)) || Number(suppliedEpoch) < 0)) {
100405
- return reply.status(428).send({ ok: false, error: "Reload Saved work and send the working ETag and revision epoch." });
100406
- }
100407
- if (!recordedEtagNamesContract(req.body.expectedEtag, storeEtags(project.app, project.id))) return reply.status(409).send({ ok: false, error: "The working copy changed. Reload Saved work." });
100408
- const observedManifest = readWorkingRevisionManifest(project);
100409
- if ((observedManifest?.epoch ?? null) !== (suppliedEpoch === null ? null : Number(suppliedEpoch))) return reply.status(409).send({ ok: false, error: "The working revision changed. Reload Saved work." });
100410
- const publicationIdentity = saved.publicationIdentity;
100411
- let manifest = ensureWorkingRevisionManifest({ project, publicationIdentity, contract: current, workingBase: saved.base });
100412
- if (manifest.draftHash !== contractHash(current)) manifest = refreshWorkingDraftHash({ project, expectedEpoch: manifest.epoch, expectedDraftHash: manifest.draftHash, contract: current });
100413
- const latest = approvedSnapshotForMetadata(project.id, "resuming saved work");
100414
- if (!latest || comparableContractHash(current) !== comparableContractHash(latest.contract)) captureProjectCheckpoint({ project, publicationIdentity, base: manifest.workingBase, contract: current, revisionEpoch: manifest.epoch });
100415
- let publication;
100416
- try {
100417
- publication = await writeContractGenerationChecked(project.app, saved.contract, project.id, "resume an explicitly selected saved-work checkpoint", { restoring: true });
100418
- } catch (error) {
100419
- return reply.status(409).send({ ok: false, error: error instanceof Error ? error.message : "checkpoint cannot be resumed" });
100420
- }
100421
- clearApproval(project.id);
100422
- const next = advanceWorkingRevisionManifest({
100423
- project,
100424
- expectedEpoch: manifest.epoch,
100425
- expectedDraftHash: manifest.draftHash,
100426
- publicationIdentity,
100427
- contract: normalisePlanViewIds(saved.contract),
100428
- source: { kind: "checkpoint", checkpointId: saved.id, hash: saved.draftHash },
100429
- workingBase: saved.base
100430
- });
100431
- broadcast(contractChangedWithReason(project.app, project.id, publication.etag, publication.storeRevision, "rollback"));
100432
- return { ok: true, revision: next, checkpoint: saved, latestApprovedVersion: latest?.version.n ?? null };
100433
- }, { label: "resuming saved work" });
100434
- }
100435
- );
100519
+ registerProjectRevisionStartRoutes(app, { broadcast });
100436
100520
  app.get("/api/projects/:id/export-sources", async (req, reply) => {
100437
100521
  const project = getProject(req.params.id);
100438
100522
  if (!project) return reply.status(404).send({ ok: false, error: `unknown project: ${req.params.id}` });
@@ -100664,6 +100748,11 @@ async function startServer() {
100664
100748
  resolveAppContract,
100665
100749
  etagOf,
100666
100750
  storeEtag,
100751
+ // Passed BY NAME, never composed here: an expression at this wiring site is one no test can reach
100752
+ // (every route test stubs the dep, every editor test stubs the fetch), and review proved that
100753
+ // rewriting it to an exact compare left the whole suite green while #957 was unfixed in production.
100754
+ // The composition and its tests live in project-contract-hash.
100755
+ recordedEtagsNameDocument,
100667
100756
  postProcessVector: (doc) => postProcess(doc),
100668
100757
  parseSelection: readSelectionFromBody,
100669
100758
  genericBakeHostLabel,