@neocompose/cli 0.42.1 → 0.43.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/neo.mjs CHANGED
@@ -288,6 +288,11 @@ function readWorkspaceState(root, options = {}) {
288
288
  if (typeof state.records !== "object" || state.records === null) {
289
289
  throw new Error(`"${statePath}" is missing the "records" object.`);
290
290
  }
291
+ if (state.derivedEdgeVersion !== void 0 && state.derivedEdgeVersion !== null && (!Number.isSafeInteger(state.derivedEdgeVersion) || state.derivedEdgeVersion < 0)) {
292
+ throw new Error(
293
+ `"${statePath}" field "derivedEdgeVersion" must be a non-negative safe integer or null.`
294
+ );
295
+ }
291
296
  for (const [key, value] of Object.entries(state.records)) {
292
297
  if (typeof value !== "object" || value === null) {
293
298
  throw new Error(
@@ -48107,6 +48112,31 @@ function worldAnimationChildOverrideBindingMember(projectId, classId) {
48107
48112
  updatedAt: 0
48108
48113
  };
48109
48114
  }
48115
+ function animationFamilyClassKinds(classes) {
48116
+ const classesById2 = new Map(classes.map((entry) => [entry.id, entry]));
48117
+ const resolved = /* @__PURE__ */ new Map();
48118
+ const resolve5 = (classId, visiting) => {
48119
+ const cached = resolved.get(classId);
48120
+ if (cached !== void 0) return cached;
48121
+ if (visiting.has(classId)) return null;
48122
+ const schemaClass2 = classesById2.get(classId);
48123
+ if (schemaClass2 === void 0) return null;
48124
+ const worldKind = schemaClass2.system?.worldKind;
48125
+ if (typeof worldKind === "string" && WORLD_SYSTEM_ANIMATION_KINDS.has(worldKind)) {
48126
+ resolved.set(classId, worldKind);
48127
+ return worldKind;
48128
+ }
48129
+ const result = typeof schemaClass2.extendsClassId === "string" ? resolve5(schemaClass2.extendsClassId, new Set(visiting).add(classId)) : null;
48130
+ resolved.set(classId, result);
48131
+ return result;
48132
+ };
48133
+ const family = /* @__PURE__ */ new Map();
48134
+ for (const classId of classesById2.keys()) {
48135
+ const worldKind = resolve5(classId, /* @__PURE__ */ new Set());
48136
+ if (worldKind !== null) family.set(classId, worldKind);
48137
+ }
48138
+ return family;
48139
+ }
48110
48140
  var WORLD_ANIMATION_CHILD_OVERRIDE_BINDING_MEMBER_NAME, WORLD_ANIMATION_CHILD_OVERRIDE_BINDING_MEMBER_NAMESPACE, WORLD_SYSTEM_CLASS_DEFINITION_BY_KIND, WORLD_SYSTEM_ANIMATION_KIND_MARKER, WORLD_SYSTEM_ANIMATION_KINDS, GENERIC_WORLD_SYSTEM_CLASS_KINDS, WORLD_SYSTEM_ALL_KINDS, WORLD_SYSTEM_SCHEMA_FIELD_SITES_BY_MEMBER_ID;
48111
48141
  var init_world_system_classes = __esm({
48112
48142
  "../src/models/classes/world-system-classes.ts"() {
@@ -49665,6 +49695,51 @@ function decodePackedValueRow(row) {
49665
49695
  packedChildIdsByParentId: state.edges
49666
49696
  };
49667
49697
  }
49698
+ function packedValuePositions(row) {
49699
+ if (!rowCarriesPackedValueContent(row)) return NO_POSITIONS;
49700
+ const positions = [];
49701
+ collectPackedPositions(row, {
49702
+ ownerLabel: `value "${row.id}"`,
49703
+ constructionRootId: isCollapseStampedInstanceRoot(row) ? row.id : null,
49704
+ path: [],
49705
+ positions
49706
+ });
49707
+ return positions;
49708
+ }
49709
+ function collectPackedPositions(content, scope) {
49710
+ collectPackedContainerPositions(content.value, "value", scope);
49711
+ collectPackedContainerPositions(
49712
+ content.constructorArgs,
49713
+ "constructorArgs",
49714
+ scope
49715
+ );
49716
+ }
49717
+ function collectPackedContainerPositions(container, field, scope) {
49718
+ if (!containerHoldsPackedEntry(container)) return;
49719
+ const entries = Array.isArray(
49720
+ container
49721
+ ) ? container.map((entry, index) => [String(index), entry]) : Object.entries(container);
49722
+ for (const [key, candidate] of entries) {
49723
+ if (!isPackedValueEnvelope(candidate)) continue;
49724
+ const label = `Packed value entry at ${scope.ownerLabel}.${field}[${JSON.stringify(key)}]`;
49725
+ const entry = candidate[PACKED_VALUE_ENTRY_KEY];
49726
+ assertDecodableEntry(entry, label);
49727
+ const valueId = packedEntryLogicalId(
49728
+ entry,
49729
+ label,
49730
+ scope.constructionRootId
49731
+ );
49732
+ const path = [...scope.path, field, key];
49733
+ scope.positions.push({ valueId, path, entry });
49734
+ if (isInitValueContent(entry)) continue;
49735
+ collectPackedPositions(entry, {
49736
+ ownerLabel: `packed value "${valueId}"`,
49737
+ constructionRootId: isCollapseStampedInstanceRoot(entry) ? valueId : scope.constructionRootId,
49738
+ path,
49739
+ positions: scope.positions
49740
+ });
49741
+ }
49742
+ }
49668
49743
  function encodePackedValueRow(args) {
49669
49744
  const scope = {
49670
49745
  parent: args.parent,
@@ -49984,7 +50059,7 @@ function registerEdge(edges, ownerId, childId) {
49984
50059
  if (existing === void 0) edges.set(ownerId, [childId]);
49985
50060
  else existing.push(childId);
49986
50061
  }
49987
- var PACKED_VALUE_ENTRY_KEY, PackedValueEncodingError, NO_CHILDREN, NO_EDGES, PACKED_ENTRY_FORBIDDEN_FIELDS;
50062
+ var PACKED_VALUE_ENTRY_KEY, PackedValueEncodingError, NO_CHILDREN, NO_EDGES, NO_POSITIONS, PACKED_ENTRY_FORBIDDEN_FIELDS;
49988
50063
  var init_packed_value_encoding = __esm({
49989
50064
  "../src/models/members/packed-value-encoding.ts"() {
49990
50065
  "use strict";
@@ -50000,6 +50075,7 @@ var init_packed_value_encoding = __esm({
50000
50075
  };
50001
50076
  NO_CHILDREN = [];
50002
50077
  NO_EDGES = /* @__PURE__ */ new Map();
50078
+ NO_POSITIONS = [];
50003
50079
  PACKED_ENTRY_FORBIDDEN_FIELDS = [
50004
50080
  "projectId",
50005
50081
  "containerId",
@@ -77995,13 +78071,13 @@ function ownedObjectChildMember(row, sourceMember, key, ctx) {
77995
78071
  return memberForCustomSchemaValue(classId, key, ctx);
77996
78072
  }
77997
78073
  function freshCloneValueId() {
77998
- const randomUUID6 = globalThis.crypto?.randomUUID;
77999
- if (randomUUID6 === void 0) {
78074
+ const randomUUID7 = globalThis.crypto?.randomUUID;
78075
+ if (randomUUID7 === void 0) {
78000
78076
  throw new NSGetterRuntimeError(
78001
78077
  "Class.Clone cannot mint a value id because crypto.randomUUID is unavailable."
78002
78078
  );
78003
78079
  }
78004
- return randomUUID6.call(globalThis.crypto);
78080
+ return randomUUID7.call(globalThis.crypto);
78005
78081
  }
78006
78082
  function parseDialogueMemoryPointer(pointer) {
78007
78083
  if (typeof pointer !== "string") return null;
@@ -81322,6 +81398,8 @@ var init_init_backed_value_materialization = __esm({
81322
81398
  function materializeDialogues(dialogueRecords, dialogueNodes) {
81323
81399
  return dialogueRecords.map((dialogue) => {
81324
81400
  if (!isRecordWithStringId(dialogue)) return dialogue;
81401
+ const { triggerNodeId: _triggerNodeId, ...dialoguePayload } = dialogue;
81402
+ void _triggerNodeId;
81325
81403
  const nodes = dialogueNodes.filter(
81326
81404
  (node) => getDialogueNodeDialogueId(node) === dialogue.id
81327
81405
  );
@@ -81334,7 +81412,7 @@ function materializeDialogues(dialogueRecords, dialogueNodes) {
81334
81412
  })
81335
81413
  );
81336
81414
  const materializedDialogue = {
81337
- ...dialogue,
81415
+ ...dialoguePayload,
81338
81416
  nodes: bodyNodes,
81339
81417
  triggerNode: triggerNode === null || triggerNode === void 0 ? null : toDialogueNodePayload(triggerNode)
81340
81418
  };
@@ -81560,10 +81638,12 @@ __export(project_document_read_exports, {
81560
81638
  readOptionalArrayField: () => readOptionalArrayField,
81561
81639
  readProjectDocument: () => readProjectDocument,
81562
81640
  readProjectDocumentContentHashHeads: () => readProjectDocumentContentHashHeads,
81641
+ readProjectDocumentManifestPage: () => readProjectDocumentManifestPage,
81563
81642
  readProjectDocumentManifestPageRecords: () => readProjectDocumentManifestPageRecords,
81564
81643
  readProjectDocumentManifestRecords: () => readProjectDocumentManifestRecords,
81565
81644
  readProjectDocumentRevisionMarker: () => readProjectDocumentRevisionMarker,
81566
- readStoredMembersField: () => readStoredMembersField
81645
+ readStoredMembersField: () => readStoredMembersField,
81646
+ withStoredValueBase: () => withStoredValueBase
81567
81647
  });
81568
81648
  async function fetchProjectDocumentRawChunked(runner, options = {}) {
81569
81649
  const mapKeys = options.mapKeys ?? [
@@ -82015,6 +82095,9 @@ function projectDocumentValueBuckets(rows) {
82015
82095
  if (expanded === rows) return { values: rows };
82016
82096
  return { values: [...expanded], physicalValues: rows };
82017
82097
  }
82098
+ function withStoredValueBase(document) {
82099
+ return document.physicalValues === void 0 ? { ...document, physicalValues: document.values } : document;
82100
+ }
82018
82101
  function readProjectDocument(value, options = {}) {
82019
82102
  if (!isObject4(value)) {
82020
82103
  throw new Error("Convex project document query returned a non-object.");
@@ -86414,11 +86497,12 @@ function isWorldAnimationStructuralMember(memberId, members) {
86414
86497
  }
86415
86498
  return false;
86416
86499
  }
86417
- function assertAnimationClipDocumentValid(document) {
86500
+ function assertAnimationClipDocumentValid(document, scope) {
86418
86501
  const context = new AnimationValidationContext(document);
86419
- context.validateSegments();
86502
+ context.validateSegments(scope);
86420
86503
  for (const member of document.members) {
86421
86504
  if (!isMemberClass(member)) continue;
86505
+ if (scope !== void 0 && !scope.memberIds.has(member.id)) continue;
86422
86506
  if (!context.classHasWorldKind(member.classId, "animationClip")) continue;
86423
86507
  if (isAbstractMember(member) === true) continue;
86424
86508
  context.validateClipMember(member);
@@ -87034,10 +87118,11 @@ var init_animation_clips = __esm({
87034
87118
  * files, and Session all hold segments, and a Session-stored `Duration` a
87035
87119
  * game writes at runtime is a feature, not drift.
87036
87120
  */
87037
- validateSegments() {
87121
+ validateSegments(scope) {
87038
87122
  const visited = /* @__PURE__ */ new Set();
87039
87123
  for (const member of this.document.members) {
87040
87124
  if (!isMemberClass(member)) continue;
87125
+ if (scope !== void 0 && !scope.memberIds.has(member.id)) continue;
87041
87126
  if (!this.classHasWorldKind(member.classId, "animationSegment")) continue;
87042
87127
  const node = this.optionalMemberRootNode(member);
87043
87128
  if (node === null) continue;
@@ -88847,44 +88932,61 @@ function transactionImpactsAnyOwnerMember(scope, impactedIds) {
88847
88932
  }
88848
88933
  return false;
88849
88934
  }
88850
- function collectNeoScriptRecompileTargets(args) {
88851
- if (args.forceRecompile === true) return completeTargets(args.postDocument);
88852
- const explicit = explicitTargetIds(args.changes);
88853
- const {
88854
- impactedIds,
88855
- changedValueIds,
88856
- impactedTypeNames,
88857
- constructedClassIds
88858
- } = collectChangedContractIds(args);
88859
- for (const id2 of args.additionalImpactedIds ?? []) impactedIds.add(id2);
88935
+ function collectNeoScriptRecompileImpact(args) {
88936
+ const impact = collectChangedContractIds(args);
88937
+ for (const id2 of args.additionalImpactedIds ?? []) impact.impactedIds.add(id2);
88860
88938
  for (const id2 of args.additionalChangedValueIds ?? []) {
88861
- changedValueIds.add(id2);
88862
- explicit.valueIds.add(id2);
88939
+ impact.changedValueIds.add(id2);
88863
88940
  }
88864
88941
  includeDerivedConstructionContracts(
88865
- constructedClassIds,
88942
+ impact.constructedClassIds,
88866
88943
  args.postDocument.classes
88867
88944
  );
88868
- const schemaRecords = [
88945
+ const dependentsById = /* @__PURE__ */ new Map();
88946
+ for (const record3 of [
88869
88947
  ...collectSchemaDependencyRecords(args.postDocument),
88870
88948
  ...collectStructuralDependencyRecords(args.postDocument)
88871
- ];
88872
- const dependentsById = /* @__PURE__ */ new Map();
88873
- for (const record3 of schemaRecords) {
88949
+ ]) {
88874
88950
  for (const dependencyId of collectCompilerReferenceIds(record3.value)) {
88875
88951
  const dependents = dependentsById.get(dependencyId) ?? [];
88876
88952
  dependents.push(record3);
88877
88953
  dependentsById.set(dependencyId, dependents);
88878
88954
  }
88879
88955
  }
88880
- const queue = [...impactedIds, ...changedValueIds];
88956
+ const queue = [...impact.impactedIds, ...impact.changedValueIds];
88881
88957
  for (let index = 0; index < queue.length; index += 1) {
88882
88958
  const dependencyId = queue[index];
88883
88959
  if (dependencyId === void 0) continue;
88884
88960
  for (const dependent of dependentsById.get(dependencyId) ?? []) {
88885
- addImpactedId(impactedIds, queue, dependent.id);
88961
+ addImpactedId(impact.impactedIds, queue, dependent.id);
88886
88962
  }
88887
88963
  }
88964
+ return impact;
88965
+ }
88966
+ function collectNeoScriptRecompileReferenceTargets(args) {
88967
+ const impact = collectNeoScriptRecompileImpact(args);
88968
+ return {
88969
+ ids: /* @__PURE__ */ new Set([
88970
+ ...impact.impactedIds,
88971
+ ...impact.changedValueIds,
88972
+ ...impact.constructedClassIds
88973
+ ]),
88974
+ names: impact.impactedTypeNames
88975
+ };
88976
+ }
88977
+ function collectNeoScriptRecompileTargets(args) {
88978
+ if (args.forceRecompile === true) return completeTargets(args.postDocument);
88979
+ const explicit = explicitTargetIds(args.changes);
88980
+ const {
88981
+ impactedIds,
88982
+ changedValueIds,
88983
+ impactedTypeNames,
88984
+ constructedClassIds
88985
+ } = collectNeoScriptRecompileImpact(args);
88986
+ for (const id2 of args.additionalChangedValueIds ?? []) {
88987
+ changedValueIds.add(id2);
88988
+ explicit.valueIds.add(id2);
88989
+ }
88888
88990
  const constructorOwnerById = constructorOwners(args.postDocument);
88889
88991
  const gradesSourceOnlyBodies = impactedIds.size > 0 || impactedTypeNames.size > 0;
88890
88992
  const impactScope = {
@@ -89026,7 +89128,9 @@ function collectCompilerReferenceNamesInto(value, field, names) {
89026
89128
  }
89027
89129
  }
89028
89130
  function isCompilerReferenceField(field) {
89029
- return /(?:member|class|enum|interface|constructor)(?:Type)?Ids?$/i.test(field) || field === "baseTypeIds" || field === "collectionValueId" || field === "fileId" || field === "primaryLinkedValueId" || field === "recordIds" || field === "valueId";
89131
+ return /(?:member|class|enum|interface|constructor|variant)(?:Type)?Ids?$/i.test(
89132
+ field
89133
+ ) || field === "baseTypeIds" || field === "collectionValueId" || field === "fileId" || field === "primaryLinkedValueId" || field === "recordIds" || field === "valueId";
89030
89134
  }
89031
89135
  function collectChangedContractIds(args) {
89032
89136
  const impactedIds = /* @__PURE__ */ new Set();
@@ -89556,7 +89660,7 @@ function withoutFields(value, ignored) {
89556
89660
  Object.entries(value).filter(([field]) => !ignored.has(field))
89557
89661
  );
89558
89662
  }
89559
- var NON_CONTRACT_MEMBER_FIELDS, NS_PROPERTY_BODY_FIELDS, NS_FUNCTION_BODY_FIELDS;
89663
+ var NON_CONTRACT_MEMBER_FIELDS, NS_PROPERTY_BODY_FIELDS, NS_FUNCTION_BODY_FIELDS, collectCompiledClassIds;
89560
89664
  var init_neo_script_recompile_scope = __esm({
89561
89665
  "../src/database/neo-script-recompile-scope.ts"() {
89562
89666
  "use strict";
@@ -89596,6 +89700,7 @@ var init_neo_script_recompile_scope = __esm({
89596
89700
  "bodyMode",
89597
89701
  "uiAction"
89598
89702
  ]);
89703
+ collectCompiledClassIds = collectConstructedClassIds;
89599
89704
  }
89600
89705
  });
89601
89706
 
@@ -97524,7 +97629,7 @@ function reconcileDirectOverrideChains(args) {
97524
97629
  }
97525
97630
  }
97526
97631
  }
97527
- function prepareServerOwnedSchemaCommit(args) {
97632
+ function* prepareServerOwnedSchemaCommitPasses(args) {
97528
97633
  if (args.forceRecompile === true) clearNeoScriptBodyCompileCache();
97529
97634
  assertUniqueChanges(args.changes);
97530
97635
  let authoredChanges = completeLocalizedTextCreateEnvelopes({
@@ -97542,7 +97647,8 @@ function prepareServerOwnedSchemaCommit(args) {
97542
97647
  args.document,
97543
97648
  authoredChanges
97544
97649
  ),
97545
- changes: authoredChanges
97650
+ changes: authoredChanges,
97651
+ createTextId: args.createLocalizedTextId
97546
97652
  });
97547
97653
  const explicitlyChangedMemberIds = /* @__PURE__ */ new Set();
97548
97654
  for (const change of authoredChanges) {
@@ -97572,6 +97678,7 @@ function prepareServerOwnedSchemaCommit(args) {
97572
97678
  if (!hasSchemaChange && !hasMigrationChange && !hasDialogueSourceChange && !hasValueChange && !hasAdditionalContractImpact) {
97573
97679
  return authoredChanges;
97574
97680
  }
97681
+ args.passLifecycle?.("start", "neo-script-recompile-targets");
97575
97682
  const authoredPostDocument = applyProjectVersionWriteChanges(
97576
97683
  args.document,
97577
97684
  authoredChanges
@@ -97792,26 +97899,46 @@ function prepareServerOwnedSchemaCommit(args) {
97792
97899
  recompileTargets,
97793
97900
  contentHashHeads: args.contentHashHeads
97794
97901
  });
97902
+ args.passLifecycle?.("complete", "neo-script-recompile-targets");
97903
+ yield {
97904
+ pass: "neo-script-recompile-targets",
97905
+ preparedChanges: prepared
97906
+ };
97795
97907
  const serverMintedBindingMemberIds = /* @__PURE__ */ new Set();
97908
+ args.passLifecycle?.("start", "authored-value-seeds");
97909
+ const seedPostDocument = applyProjectVersionWriteChanges(
97910
+ args.document,
97911
+ prepared
97912
+ );
97796
97913
  const pendingConstructedGraphValidations = materializeAuthoredValueSeeds({
97797
- document: applyProjectVersionWriteChanges(postDocument, prepared),
97914
+ document: seedPostDocument,
97798
97915
  prepared,
97799
97916
  authoredValueSeeds: args.authoredValueSeeds ?? [],
97800
97917
  contentHashHeads: args.contentHashHeads,
97801
- serverMintedBindingMemberIds
97918
+ serverMintedBindingMemberIds,
97919
+ createLocalizedTextId: args.createLocalizedTextId
97802
97920
  });
97803
97921
  prepareServerOwnedValueInitializerBodies({
97804
97922
  document: args.document,
97805
- postDocument,
97923
+ postDocument: seedPostDocument,
97806
97924
  prepared,
97807
97925
  targetIds: recompileTargets.valueIds,
97808
97926
  contentHashHeads: args.contentHashHeads
97809
97927
  });
97928
+ args.passLifecycle?.("complete", "authored-value-seeds");
97929
+ yield { pass: "authored-value-seeds", preparedChanges: prepared };
97930
+ args.passLifecycle?.("start", "variant-child-override-binding-members");
97810
97931
  materializeVariantChildOverrideBindingMembers({
97811
97932
  document: args.document,
97812
97933
  prepared,
97813
97934
  serverMintedBindingMemberIds
97814
97935
  });
97936
+ args.passLifecycle?.("complete", "variant-child-override-binding-members");
97937
+ yield {
97938
+ pass: "variant-child-override-binding-members",
97939
+ preparedChanges: prepared
97940
+ };
97941
+ args.passLifecycle?.("start", "prepared-instance-initializers");
97815
97942
  materializePreparedInstanceInitializers({
97816
97943
  document: args.document,
97817
97944
  prepared,
@@ -97829,13 +97956,22 @@ function prepareServerOwnedSchemaCommit(args) {
97829
97956
  prepared,
97830
97957
  pending: pendingConstructedGraphValidations
97831
97958
  });
97959
+ args.passLifecycle?.("complete", "prepared-instance-initializers");
97960
+ yield {
97961
+ pass: "prepared-instance-initializers",
97962
+ preparedChanges: prepared
97963
+ };
97964
+ args.passLifecycle?.("start", "delegate-value-bodies");
97832
97965
  prepareServerOwnedDelegateValueBodies({
97833
97966
  document: args.document,
97834
- postDocument,
97967
+ postDocument: applyProjectVersionWriteChanges(args.document, prepared),
97835
97968
  prepared,
97836
97969
  targetIds: recompileTargets.valueIds,
97837
97970
  contentHashHeads: args.contentHashHeads
97838
97971
  });
97972
+ args.passLifecycle?.("complete", "delegate-value-bodies");
97973
+ yield { pass: "delegate-value-bodies", preparedChanges: prepared };
97974
+ args.passLifecycle?.("start", "variant-constructor-args");
97839
97975
  reconcileVariantConstructorArgs({
97840
97976
  document: args.document,
97841
97977
  prepared,
@@ -97846,6 +97982,7 @@ function prepareServerOwnedSchemaCommit(args) {
97846
97982
  prepared,
97847
97983
  contentHashHeads: args.contentHashHeads
97848
97984
  });
97985
+ normalizePreparedServerTimestamps(prepared, args.serverTimestamp);
97849
97986
  const committedDocument = applyProjectVersionWriteChanges(
97850
97987
  args.document,
97851
97988
  prepared
@@ -97862,11 +97999,37 @@ function prepareServerOwnedSchemaCommit(args) {
97862
97999
  });
97863
98000
  attachPreparedValuePlacements(physical, committedDocument);
97864
98001
  attachPreparedConstructorAggregateEdges(physical, committedDocument);
97865
- return orderLocalizedTextWritesBesideLinks(
98002
+ const ordered = orderLocalizedTextWritesBesideLinks(
97866
98003
  orderVariantRootValuesWithVariants(
97867
- orderDeclaredMemberCreatesFirst(physical, postDocument)
98004
+ orderDeclaredMemberCreatesFirst(
98005
+ physical,
98006
+ applyProjectVersionWriteChanges(args.document, prepared)
98007
+ )
97868
98008
  )
97869
98009
  );
98010
+ args.passLifecycle?.("complete", "variant-constructor-args");
98011
+ yield { pass: "variant-constructor-args", preparedChanges: ordered };
98012
+ return ordered;
98013
+ }
98014
+ function normalizePreparedServerTimestamps(prepared, serverTimestamp) {
98015
+ if (serverTimestamp === void 0) return;
98016
+ for (const change of prepared) {
98017
+ if (change.operation === "delete" || change.nextData === null || typeof change.nextData !== "object") {
98018
+ continue;
98019
+ }
98020
+ const nextData = change.nextData;
98021
+ if (change.operation === "create" && "createdAt" in nextData) {
98022
+ nextData.createdAt = serverTimestamp;
98023
+ }
98024
+ if ("updatedAt" in nextData) nextData.updatedAt = serverTimestamp;
98025
+ }
98026
+ }
98027
+ function prepareServerOwnedSchemaCommit(args) {
98028
+ const passes = prepareServerOwnedSchemaCommitPasses(args);
98029
+ for (; ; ) {
98030
+ const step = passes.next();
98031
+ if (step.done) return step.value;
98032
+ }
97870
98033
  }
97871
98034
  function orderLocalizedTextWritesBesideLinks(prepared) {
97872
98035
  const indexByLinkKey = /* @__PURE__ */ new Map();
@@ -98791,8 +98954,12 @@ function prepareServerOwnedDialogueBodies(args) {
98791
98954
  explicitNodeIds.add(change.recordId);
98792
98955
  const next = asRecord2(change.nextData);
98793
98956
  const current = currentNodes.get(change.recordId);
98794
- const dialogueId = typeof next?.dialogueId === "string" ? next.dialogueId : typeof current?.dialogueId === "string" ? current.dialogueId : null;
98795
- if (dialogueId !== null) changedDialogueIds.add(dialogueId);
98957
+ if (typeof current?.dialogueId === "string") {
98958
+ changedDialogueIds.add(current.dialogueId);
98959
+ }
98960
+ if (typeof next?.dialogueId === "string") {
98961
+ changedDialogueIds.add(next.dialogueId);
98962
+ }
98796
98963
  continue;
98797
98964
  }
98798
98965
  if (change.recordKind === "dialogue-group") {
@@ -99042,7 +99209,8 @@ function materializeAuthoredValueSeeds(args) {
99042
99209
  pendingGraphValidations,
99043
99210
  memberChange: { index, change },
99044
99211
  member,
99045
- seed
99212
+ seed,
99213
+ createLocalizedTextId: args.createLocalizedTextId
99046
99214
  });
99047
99215
  continue;
99048
99216
  }
@@ -99103,7 +99271,8 @@ function materializeAuthoredValueSeeds(args) {
99103
99271
  // default builder evaluates it immediately, which bypasses both
99104
99272
  // the server-initializer-materialization grouping and the CLI's
99105
99273
  // parity/identity transport for evaluator-created interior rows.
99106
- seed: { ...seed, values: seed.values ?? [] }
99274
+ seed: { ...seed, values: seed.values ?? [] },
99275
+ createLocalizedTextId: args.createLocalizedTextId
99107
99276
  });
99108
99277
  const { createdValues, localizedTexts, storageKeyDeclarations, rootValue } = materialized;
99109
99278
  const ownedValueId = documentIndex.membersById.get(member.id)?.valueId ?? derivedMemberValueId(member.id);
@@ -99513,7 +99682,8 @@ function materializeInstanceDefaultSeed(args) {
99513
99682
  documentIndex: args.documentIndex,
99514
99683
  member: materializationMember,
99515
99684
  seed: { ...args.seed, values: args.seed.values },
99516
- allowExistingRows: args.memberChange === null || args.memberChange.change.operation === "update"
99685
+ allowExistingRows: args.memberChange === null || args.memberChange.change.operation === "update",
99686
+ createLocalizedTextId: args.createLocalizedTextId
99517
99687
  });
99518
99688
  stampCreatedValuesMapKey(createdValues, null);
99519
99689
  applyDeclaredStorageKeyOverrides({
@@ -99717,7 +99887,8 @@ function materializeAuthoredStaticSeed(args) {
99717
99887
  document: args.document,
99718
99888
  member: args.member,
99719
99889
  createdValues,
99720
- seededLocalizedTexts
99890
+ seededLocalizedTexts,
99891
+ createLocalizedTextId: args.createLocalizedTextId
99721
99892
  });
99722
99893
  return {
99723
99894
  rootValue,
@@ -99747,7 +99918,8 @@ function materializeSeedLocalizableStringWrites(args) {
99747
99918
  memberId: args.member.id
99748
99919
  }),
99749
99920
  expectedBaseContentHash: null
99750
- }))
99921
+ })),
99922
+ createTextId: args.createLocalizedTextId
99751
99923
  });
99752
99924
  const createdValuesById = new Map(
99753
99925
  args.createdValues.map((value) => [value.id, value])
@@ -102228,7 +102400,8 @@ function assertProjectVersionWholeGraphWritesValid(args) {
102228
102400
  assertStagedInternalRecordRelationsValid(args.document, projected, changes);
102229
102401
  assertStagedWorldContentLayerBindingsValid(args.document, projected, changes);
102230
102402
  assertAnimationClipDocumentValid(
102231
- materializeDeclarationInitializersForAnimationValidation(projected)
102403
+ materializeDeclarationInitializersForAnimationValidation(projected),
102404
+ args.animationValidationMemberIds === void 0 ? void 0 : { memberIds: args.animationValidationMemberIds }
102232
102405
  );
102233
102406
  if (args.operation === void 0 || !isSystemOwnedProjectVersionOperation(args.operation)) {
102234
102407
  assertProjectVersionSystemProtectedWritesValid({
@@ -102346,7 +102519,7 @@ function valueDematerializationRefusal(args) {
102346
102519
  return null;
102347
102520
  }
102348
102521
  function materializeDeclarationInitializersForAnimationValidation(document) {
102349
- const animationFamilyClassIds = animationFamilyClasses(document);
102522
+ const animationFamilyClassIds = animationFamilyClassKinds(document.classes);
102350
102523
  const initializers = document.values.filter(
102351
102524
  (value) => isInitValueContent(value)
102352
102525
  );
@@ -102520,31 +102693,6 @@ function materializeDeclarationInitializersForAnimationValidation(document) {
102520
102693
  }
102521
102694
  return { ...document, members, values: [...valuesById.values()] };
102522
102695
  }
102523
- function animationFamilyClasses(document) {
102524
- const classes = new Map(document.classes.map((entry) => [entry.id, entry]));
102525
- const animationKinds = new Set(WORLD_SYSTEM_ANIMATION_KINDS);
102526
- const result = /* @__PURE__ */ new Map();
102527
- const resolve5 = (classId, visiting) => {
102528
- const cached = result.get(classId);
102529
- if (cached !== void 0) return cached;
102530
- if (visiting.has(classId)) return false;
102531
- const schemaClass2 = classes.get(classId);
102532
- if (schemaClass2 === void 0) return false;
102533
- const worldKind = schemaClass2.system?.worldKind;
102534
- if (typeof worldKind === "string" && animationKinds.has(worldKind)) {
102535
- result.set(classId, true);
102536
- return true;
102537
- }
102538
- const nextVisiting = new Set(visiting).add(classId);
102539
- const belongs = typeof schemaClass2.extendsClassId === "string" && resolve5(schemaClass2.extendsClassId, nextVisiting);
102540
- result.set(classId, belongs);
102541
- return belongs;
102542
- };
102543
- for (const classId of classes.keys()) resolve5(classId, /* @__PURE__ */ new Set());
102544
- return new Set(
102545
- [...result].flatMap(([classId, belongs]) => belongs ? [classId] : [])
102546
- );
102547
- }
102548
102696
  function containsDirectValueId(value, ids) {
102549
102697
  if (Array.isArray(value)) {
102550
102698
  return value.some((entry) => typeof entry === "string" && ids.has(entry));
@@ -105699,6 +105847,1467 @@ var init_trusted_commit_verification = __esm({
105699
105847
  }
105700
105848
  });
105701
105849
 
105850
+ // ../src/database/project-snapshot-derived-edges.ts
105851
+ function extractProjectSnapshotDerivedEdges(source) {
105852
+ const edges = /* @__PURE__ */ new Map();
105853
+ const add = (edge) => {
105854
+ edges.set(edgeIdentity(edge), edge);
105855
+ };
105856
+ for (const targetKey of collectCompilerReferenceIds(source.data)) {
105857
+ add({
105858
+ edgeKind: "compiled-reference",
105859
+ targetKey,
105860
+ targetAddressing: "record",
105861
+ payloadJson: canonicalJsonStringify({ referenceKind: "record-id" })
105862
+ });
105863
+ }
105864
+ for (const targetKey of collectCompilerReferenceNames(source.data)) {
105865
+ add({
105866
+ edgeKind: "compiled-reference",
105867
+ targetKey,
105868
+ targetAddressing: "record",
105869
+ // neo-terminology-audit: allow-next-line legacy-stable-id -- REJECTS: treating compiler reference metadata as a stable ID.
105870
+ payloadJson: canonicalJsonStringify({ referenceKind: "type-name" })
105871
+ });
105872
+ }
105873
+ for (const targetKey of collectCompiledClassIds(source.data)) {
105874
+ add({
105875
+ edgeKind: "compiled-reference",
105876
+ targetKey,
105877
+ targetAddressing: "record",
105878
+ payloadJson: canonicalJsonStringify({
105879
+ referenceKind: "constructed-class-id"
105880
+ })
105881
+ });
105882
+ }
105883
+ const record3 = asRecord3(source.data);
105884
+ if (source.recordKind === "dialogue-node" && record3 !== null && typeof record3.dialogueId === "string") {
105885
+ add({
105886
+ edgeKind: "dialogue-membership",
105887
+ targetKey: record3.dialogueId,
105888
+ targetAddressing: "record",
105889
+ payloadJson: canonicalJsonStringify({ relation: "dialogue-node" })
105890
+ });
105891
+ }
105892
+ if (source.recordKind === "value" && record3 !== null) {
105893
+ const body = record3.value;
105894
+ if (Array.isArray(body) || asRecord3(body) !== null) {
105895
+ for (const targetKey of collectDirectBodyChildIds(body)) {
105896
+ add({
105897
+ edgeKind: "containment-child",
105898
+ targetKey,
105899
+ targetAddressing: "record",
105900
+ payloadJson: canonicalJsonStringify({
105901
+ relation: "body-child",
105902
+ depth: 1
105903
+ })
105904
+ });
105905
+ }
105906
+ }
105907
+ if (typeof record3.containerId === "string") {
105908
+ add({
105909
+ edgeKind: "containment-child",
105910
+ targetKey: record3.containerId,
105911
+ targetAddressing: "record",
105912
+ payloadJson: canonicalJsonStringify({
105913
+ relation: "container-join",
105914
+ childId: source.recordId
105915
+ })
105916
+ });
105917
+ }
105918
+ addStampBindingEdges(record3.genericBindings, add);
105919
+ addPackedChildEdges(source, record3, add);
105920
+ }
105921
+ for (const edge of source.constructorAggregateEdges ?? []) {
105922
+ if (edge.ownerValueId !== source.recordId) {
105923
+ throw new Error(
105924
+ `Constructor aggregate edge owner "${edge.ownerValueId}" does not match snapshot record "${source.recordId}".`
105925
+ );
105926
+ }
105927
+ add({
105928
+ edgeKind: "constructor-aggregate",
105929
+ targetKey: edge.targetValueId,
105930
+ targetAddressing: "record",
105931
+ payloadJson: canonicalJsonStringify({
105932
+ parameterId: edge.parameterId,
105933
+ typeInfo: edge.typeInfo
105934
+ })
105935
+ });
105936
+ }
105937
+ const constructorArgs = record3 === null ? null : asRecord3(record3.constructorArgs);
105938
+ return {
105939
+ edges: [...edges.values()].sort(compareEdges),
105940
+ complete: constructorArgs === null || Object.keys(constructorArgs).length === 0 || source.constructorAggregateEdges !== void 0
105941
+ };
105942
+ }
105943
+ function addStampBindingEdges(genericBindings, add) {
105944
+ const bindings = asRecord3(genericBindings);
105945
+ if (bindings === null) return;
105946
+ for (const [parameterId, stampedMemberId] of Object.entries(bindings)) {
105947
+ if (typeof stampedMemberId !== "string") continue;
105948
+ add({
105949
+ edgeKind: "stamp-binding",
105950
+ targetKey: stampedMemberId,
105951
+ targetAddressing: "record",
105952
+ payloadJson: canonicalJsonStringify({ parameterId, stampedMemberId })
105953
+ });
105954
+ }
105955
+ }
105956
+ function addPackedChildEdges(source, record3, add) {
105957
+ if (!rowCarriesPackedValueContent(record3)) return;
105958
+ if (!isMemberValue(source.data)) {
105959
+ throw new Error(
105960
+ `Value snapshot "${source.recordId}" stores packed children but is not a complete value row, so their positions cannot be addressed.`
105961
+ );
105962
+ }
105963
+ for (const position of packedValuePositions(source.data)) {
105964
+ add({
105965
+ edgeKind: "containment-child",
105966
+ targetKey: projectSnapshotDerivedPathTargetKey({
105967
+ recordId: source.recordId,
105968
+ path: position.path
105969
+ }),
105970
+ targetAddressing: "path",
105971
+ payloadJson: canonicalJsonStringify({
105972
+ relation: "packed-child",
105973
+ childId: position.valueId
105974
+ })
105975
+ });
105976
+ addStampBindingEdges(position.entry.genericBindings, add);
105977
+ }
105978
+ }
105979
+ function projectSnapshotDerivedPathTargetKey(args) {
105980
+ return canonicalJsonStringify({ recordId: args.recordId, path: args.path });
105981
+ }
105982
+ function projectSnapshotDerivedEdgeIdentity(edge) {
105983
+ return edgeIdentity(edge);
105984
+ }
105985
+ function edgeIdentity(edge) {
105986
+ return canonicalJsonStringify([
105987
+ edge.edgeKind,
105988
+ edge.targetAddressing,
105989
+ edge.targetKey,
105990
+ edge.payloadJson
105991
+ ]);
105992
+ }
105993
+ function compareEdges(left, right) {
105994
+ return edgeIdentity(left).localeCompare(edgeIdentity(right));
105995
+ }
105996
+ function collectDirectBodyChildIds(value) {
105997
+ const candidates = Array.isArray(value) ? value : Object.values(asRecord3(value) ?? {});
105998
+ return [
105999
+ ...new Set(
106000
+ candidates.filter(
106001
+ (candidate) => typeof candidate === "string" && STORED_PROJECT_RECORD_ID_PATTERN.test(candidate)
106002
+ )
106003
+ )
106004
+ ];
106005
+ }
106006
+ function asRecord3(value) {
106007
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
106008
+ }
106009
+ var PROJECT_SNAPSHOT_DERIVED_EDGE_EXTRACTOR_VERSION, STORED_PROJECT_RECORD_ID_PATTERN;
106010
+ var init_project_snapshot_derived_edges = __esm({
106011
+ "../src/database/project-snapshot-derived-edges.ts"() {
106012
+ "use strict";
106013
+ init_canonical_json();
106014
+ init_neo_script_recompile_scope();
106015
+ init_member_kinds();
106016
+ init_packed_value_encoding();
106017
+ PROJECT_SNAPSHOT_DERIVED_EDGE_EXTRACTOR_VERSION = 4;
106018
+ STORED_PROJECT_RECORD_ID_PATTERN = /^(?:system_)?[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu;
106019
+ }
106020
+ });
106021
+
106022
+ // ../src/database/commit-preparation-scope-planner.ts
106023
+ function nextCommitPreparationPass(completed) {
106024
+ const index = COMMIT_PREPARATION_PASS_ORDER.indexOf(completed);
106025
+ return COMMIT_PREPARATION_PASS_ORDER[index + 1] ?? null;
106026
+ }
106027
+ var COMMIT_PREPARATION_PROJECTED_BUCKETS, COMMIT_PREPARATION_PASS_ORDER, COMMIT_PREPARATION_CLOSURE_SPECS;
106028
+ var init_commit_preparation_scope_planner = __esm({
106029
+ "../src/database/commit-preparation-scope-planner.ts"() {
106030
+ "use strict";
106031
+ COMMIT_PREPARATION_PROJECTED_BUCKETS = [
106032
+ "project",
106033
+ "members",
106034
+ "classes",
106035
+ "constructors",
106036
+ "variants",
106037
+ "variantFolders",
106038
+ "enums",
106039
+ "interfaces",
106040
+ "internalRecordRelations",
106041
+ "projectFiles",
106042
+ "textureTemplates",
106043
+ "audioClipTemplates",
106044
+ "dialogues",
106045
+ "dialogueRecords",
106046
+ "dialogueGroups",
106047
+ "values",
106048
+ "dialogueNodes",
106049
+ "migrations"
106050
+ ];
106051
+ COMMIT_PREPARATION_PASS_ORDER = [
106052
+ "neo-script-recompile-targets",
106053
+ "authored-value-seeds",
106054
+ "variant-child-override-binding-members",
106055
+ "prepared-instance-initializers",
106056
+ "delegate-value-bodies",
106057
+ "variant-constructor-args"
106058
+ ];
106059
+ COMMIT_PREPARATION_CLOSURE_SPECS = {
106060
+ "neo-script-recompile-targets": {
106061
+ order: 1,
106062
+ entryPoint: "collectNeoScriptRecompileTargets",
106063
+ synthesizes: "recompile updates",
106064
+ // The one pass that does not rebuild a post-document — its caller hands it
106065
+ // both sides — so it is not held to the projection's bucket set.
106066
+ reads: [
106067
+ "project",
106068
+ "members",
106069
+ "classes",
106070
+ "constructors",
106071
+ "variants",
106072
+ "variantFolders",
106073
+ "enums",
106074
+ "interfaces",
106075
+ "values",
106076
+ "dialogues",
106077
+ "dialogueRecords",
106078
+ "dialogueGroups",
106079
+ "dialogueNodes",
106080
+ "migrations"
106081
+ ],
106082
+ closureRules: [
106083
+ "change-targets",
106084
+ "ancestor-paths",
106085
+ "animation-graph-closure",
106086
+ "member-default-value-closure",
106087
+ "compiled-reference-reverse-index",
106088
+ "dialogue-membership-peers",
106089
+ "every-variant-root",
106090
+ "localizable-reference-candidates",
106091
+ "source-only-rows",
106092
+ "whole-graph-validation-members",
106093
+ "world-value-ranges"
106094
+ ],
106095
+ mutatesDocument: []
106096
+ },
106097
+ "authored-value-seeds": {
106098
+ order: 2,
106099
+ entryPoint: "materializeAuthoredValueSeeds",
106100
+ synthesizes: "seed value rows, localized texts",
106101
+ // The one pass that reads the localization buckets: a static seed mints
106102
+ // localized texts, and the mint reads the project's localization config.
106103
+ reads: [
106104
+ ...COMMIT_PREPARATION_PROJECTED_BUCKETS,
106105
+ "localizationConfig",
106106
+ "localizedTexts"
106107
+ ],
106108
+ closureRules: [
106109
+ "change-targets",
106110
+ "ancestor-paths",
106111
+ "animation-graph-closure",
106112
+ "authored-seed-requested-ids",
106113
+ "member-default-value-closure",
106114
+ "every-variant-root",
106115
+ "localizable-reference-candidates",
106116
+ "world-value-ranges"
106117
+ ],
106118
+ // `materializeStaticSeedBindingMembers` pushes the binding member it mints
106119
+ // into the document the rest of this pass reads, not only into `prepared`.
106120
+ mutatesDocument: ["members"]
106121
+ },
106122
+ "variant-child-override-binding-members": {
106123
+ order: 3,
106124
+ entryPoint: "materializeVariantChildOverrideBindingMembers",
106125
+ synthesizes: "binding members",
106126
+ reads: [...COMMIT_PREPARATION_PROJECTED_BUCKETS],
106127
+ closureRules: [
106128
+ "change-targets",
106129
+ "ancestor-paths",
106130
+ "animation-graph-closure",
106131
+ "descendants",
106132
+ "member-default-value-closure",
106133
+ "every-variant-root",
106134
+ "stamp-edge-candidates",
106135
+ "world-value-ranges"
106136
+ ],
106137
+ // The minted binding member is pushed straight into the document the
106138
+ // later passes read, not only into `prepared`.
106139
+ mutatesDocument: ["members"]
106140
+ },
106141
+ "prepared-instance-initializers": {
106142
+ order: 4,
106143
+ entryPoint: "materializePreparedInstanceInitializers",
106144
+ synthesizes: "created value rows from evaluation",
106145
+ reads: [...COMMIT_PREPARATION_PROJECTED_BUCKETS],
106146
+ closureRules: [
106147
+ "change-targets",
106148
+ "every-variant-root",
106149
+ "full-content-dimension",
106150
+ "member-default-value-closure",
106151
+ "world-value-ranges"
106152
+ ],
106153
+ mutatesDocument: []
106154
+ },
106155
+ "delegate-value-bodies": {
106156
+ order: 5,
106157
+ entryPoint: "prepareServerOwnedDelegateValueBodies",
106158
+ synthesizes: "delegate-body rewrites",
106159
+ reads: [...COMMIT_PREPARATION_PROJECTED_BUCKETS],
106160
+ closureRules: [
106161
+ "change-targets",
106162
+ "ancestor-paths",
106163
+ "animation-graph-closure",
106164
+ "descendants",
106165
+ "member-default-value-closure",
106166
+ "every-variant-root",
106167
+ "source-only-rows",
106168
+ "world-value-ranges"
106169
+ ],
106170
+ mutatesDocument: []
106171
+ },
106172
+ "variant-constructor-args": {
106173
+ order: 6,
106174
+ entryPoint: "reconcileVariantConstructorArgs",
106175
+ synthesizes: "constructor-arg updates",
106176
+ reads: [...COMMIT_PREPARATION_PROJECTED_BUCKETS],
106177
+ closureRules: [
106178
+ "change-targets",
106179
+ "every-variant-root",
106180
+ "touched-variant-schema-key-children",
106181
+ "member-default-value-closure",
106182
+ "world-value-ranges"
106183
+ ],
106184
+ mutatesDocument: []
106185
+ }
106186
+ };
106187
+ }
106188
+ });
106189
+
106190
+ // ../src/database/commit-preparation-animation-scope.ts
106191
+ function commitPreparationAnimationSchema(document) {
106192
+ const classesById2 = new Map(
106193
+ document.classes.map((schemaClass2) => [schemaClass2.id, schemaClass2])
106194
+ );
106195
+ const rootKindByClassId = /* @__PURE__ */ new Map();
106196
+ for (const classId of animationFamilyClassKinds(document.classes).keys()) {
106197
+ const visited = /* @__PURE__ */ new Set();
106198
+ let current = classesById2.get(classId);
106199
+ while (current !== void 0 && !visited.has(current.id)) {
106200
+ visited.add(current.id);
106201
+ const worldKind = current.system?.worldKind;
106202
+ if (worldKind !== void 0 && ANIMATION_ROOT_KINDS.has(worldKind)) {
106203
+ rootKindByClassId.set(classId, worldKind);
106204
+ break;
106205
+ }
106206
+ current = typeof current.extendsClassId === "string" ? classesById2.get(current.extendsClassId) : void 0;
106207
+ }
106208
+ }
106209
+ const rootMemberIds2 = /* @__PURE__ */ new Set();
106210
+ for (const member of document.members) {
106211
+ if (isMemberClass(member) && rootKindByClassId.has(member.classId)) {
106212
+ rootMemberIds2.add(member.id);
106213
+ }
106214
+ }
106215
+ const segmentClassIds = /* @__PURE__ */ new Set();
106216
+ for (const [classId, worldKind] of rootKindByClassId) {
106217
+ if (worldKind === NeoWorldSystemClassKind.AnimationSegment) {
106218
+ segmentClassIds.add(classId);
106219
+ }
106220
+ }
106221
+ return { rootMemberIds: rootMemberIds2, segmentClassIds };
106222
+ }
106223
+ function isAnimationSegmentValueRow(data, schema) {
106224
+ if (data === null || typeof data !== "object") return false;
106225
+ const classId = Reflect.get(data, "classId");
106226
+ return typeof classId === "string" && schema.segmentClassIds.has(classId);
106227
+ }
106228
+ function animationClipMemberIdsTargetingClasses(document, classIds, schema) {
106229
+ if (classIds.size === 0) return [];
106230
+ const classesById2 = new Map(
106231
+ document.classes.map((schemaClass2) => [schemaClass2.id, schemaClass2])
106232
+ );
106233
+ const membersById2 = new Map(
106234
+ document.members.map((member) => [member.id, member])
106235
+ );
106236
+ const descendsFromChanged = (classId) => {
106237
+ const visited = /* @__PURE__ */ new Set();
106238
+ let current = classesById2.get(classId);
106239
+ while (current !== void 0 && !visited.has(current.id)) {
106240
+ if (classIds.has(current.id)) return true;
106241
+ visited.add(current.id);
106242
+ current = typeof current.extendsClassId === "string" ? classesById2.get(current.extendsClassId) : void 0;
106243
+ }
106244
+ return false;
106245
+ };
106246
+ const result = [];
106247
+ for (const member of document.members) {
106248
+ if (!isMemberClass(member)) continue;
106249
+ if (!schema.rootMemberIds.has(member.id)) continue;
106250
+ const binding = resolveInstanceEnv(
106251
+ member.classId,
106252
+ member.classArguments,
106253
+ document.classes
106254
+ ).get(WORLD_ANIMATION_CLIP_TARGET_PARAM_ID);
106255
+ const bindingMember = binding?.kind === "member" ? membersById2.get(binding.memberId) : void 0;
106256
+ if (!isMemberClass(bindingMember)) continue;
106257
+ if (descendsFromChanged(bindingMember.classId)) result.push(member.id);
106258
+ }
106259
+ return result;
106260
+ }
106261
+ var ANIMATION_ROOT_KINDS;
106262
+ var init_commit_preparation_animation_scope = __esm({
106263
+ "../src/database/commit-preparation-animation-scope.ts"() {
106264
+ "use strict";
106265
+ init_core();
106266
+ init_member_kinds();
106267
+ init_generics();
106268
+ init_world_system_classes();
106269
+ ANIMATION_ROOT_KINDS = /* @__PURE__ */ new Set([
106270
+ NeoWorldSystemClassKind.AnimationClip,
106271
+ NeoWorldSystemClassKind.AnimationSegment
106272
+ ]);
106273
+ }
106274
+ });
106275
+
106276
+ // ../src/database/project-commit-preparation-scoped-loader.ts
106277
+ function overlayPlanningRows(rows, recordKind, changes) {
106278
+ const result = new Map((rows ?? []).map((row) => [row.id, row]));
106279
+ for (const change of changes) {
106280
+ if (change.recordKind !== recordKind) continue;
106281
+ if (change.operation === "delete" || change.nextData === null) {
106282
+ result.delete(change.recordId);
106283
+ } else {
106284
+ result.set(change.recordId, change.nextData);
106285
+ }
106286
+ }
106287
+ return [...result.values()];
106288
+ }
106289
+ function overlayPlanningDocument(document, changes) {
106290
+ const projectChange = changes.findLast(
106291
+ (change) => change.recordKind === "project" && change.operation !== "delete" && change.nextData !== null
106292
+ );
106293
+ return {
106294
+ ...document,
106295
+ project: projectChange?.nextData ?? document.project,
106296
+ members: overlayPlanningRows(document.members, "member", changes),
106297
+ classes: overlayPlanningRows(document.classes, "class", changes),
106298
+ constructors: overlayPlanningRows(
106299
+ document.constructors,
106300
+ "constructor",
106301
+ changes
106302
+ ),
106303
+ variants: overlayPlanningRows(document.variants, "variant", changes),
106304
+ variantFolders: overlayPlanningRows(
106305
+ document.variantFolders,
106306
+ "variant-folder",
106307
+ changes
106308
+ ),
106309
+ enums: overlayPlanningRows(document.enums, "enum", changes),
106310
+ interfaces: overlayPlanningRows(document.interfaces, "interface", changes),
106311
+ values: overlayPlanningRows(document.values, "value", changes),
106312
+ dialogues: overlayPlanningRows(document.dialogues, "dialogue", changes),
106313
+ dialogueGroups: overlayPlanningRows(
106314
+ document.dialogueGroups,
106315
+ "dialogue-group",
106316
+ changes
106317
+ ),
106318
+ dialogueNodes: overlayPlanningRows(
106319
+ document.dialogueNodes,
106320
+ "dialogue-node",
106321
+ changes
106322
+ ),
106323
+ migrations: overlayPlanningRows(document.migrations, "migration", changes),
106324
+ localizedTexts: overlayPlanningRows(
106325
+ document.localizedTexts,
106326
+ "localized-text",
106327
+ changes
106328
+ )
106329
+ };
106330
+ }
106331
+ function worldKindByClassId(document) {
106332
+ const classes = new Map(
106333
+ document.classes.map((schemaClass2) => [schemaClass2.id, schemaClass2])
106334
+ );
106335
+ const result = /* @__PURE__ */ new Map();
106336
+ const resolve5 = (classId, visiting) => {
106337
+ if (result.has(classId)) return result.get(classId);
106338
+ if (visiting.has(classId)) return void 0;
106339
+ const schemaClass2 = classes.get(classId);
106340
+ if (schemaClass2 === void 0) return void 0;
106341
+ const own = schemaClass2.system?.worldKind;
106342
+ const resolved = typeof own === "string" ? own : schemaClass2.extendsClassId === void 0 ? void 0 : resolve5(schemaClass2.extendsClassId, new Set(visiting).add(classId));
106343
+ result.set(classId, resolved);
106344
+ return resolved;
106345
+ };
106346
+ for (const classId of classes.keys()) resolve5(classId, /* @__PURE__ */ new Set());
106347
+ return result;
106348
+ }
106349
+ function valueWorldKind(kinds, value) {
106350
+ if (value === null || typeof value !== "object") return void 0;
106351
+ const classId = Reflect.get(value, "classId");
106352
+ return typeof classId === "string" ? kinds.get(classId) : void 0;
106353
+ }
106354
+ function hasWorldLayerOverride(value) {
106355
+ if (value === null || typeof value !== "object") return false;
106356
+ const body = Reflect.get(value, "value");
106357
+ return body !== null && typeof body === "object" && typeof Reflect.get(body, "layerOverrideValueId") === "string";
106358
+ }
106359
+ function commitPreparationWorldScopeKinds(args) {
106360
+ const allKinds = new Set(
106361
+ args.postDocument.classes.flatMap(
106362
+ (schemaClass2) => typeof schemaClass2.system?.worldKind === "string" ? [schemaClass2.system.worldKind] : []
106363
+ )
106364
+ );
106365
+ if (args.changes.some((change) => change.recordKind === "class")) {
106366
+ return allKinds;
106367
+ }
106368
+ const kindsByClass = worldKindByClassId(args.postDocument);
106369
+ const current = projectDocumentRecordsByKey(args.currentDocument);
106370
+ const requiresWholeWorld = args.changes.some((change) => {
106371
+ if (change.recordKind !== "value") return false;
106372
+ const prior = current.get(commitPreparationRecordKey(change));
106373
+ return [prior, change.nextData].some((candidate) => {
106374
+ const worldKind = valueWorldKind(kindsByClass, candidate);
106375
+ return hasWorldLayerOverride(candidate) || worldKind === NeoWorldSystemClassKind.TileLayerLink || worldKind === NeoWorldSystemClassKind.ObjectLayerLink;
106376
+ });
106377
+ });
106378
+ return requiresWholeWorld ? allKinds : /* @__PURE__ */ new Set();
106379
+ }
106380
+ function commitPreparationMemberDefaultValueScope(args) {
106381
+ const exactValueIds = /* @__PURE__ */ new Set();
106382
+ const descendantValueIds = /* @__PURE__ */ new Set();
106383
+ const membersById2 = new Map(
106384
+ args.postDocument.members.map((member) => [member.id, member])
106385
+ );
106386
+ const classesById2 = new Map(
106387
+ args.postDocument.classes.map((schemaClass2) => [
106388
+ schemaClass2.id,
106389
+ schemaClass2
106390
+ ])
106391
+ );
106392
+ const visitedMemberIds = /* @__PURE__ */ new Set();
106393
+ const visitedClassIds = /* @__PURE__ */ new Set();
106394
+ const rememberDefaultIds = (value, descendants) => {
106395
+ for (const valueId of collectStoredRecordIds(value)) {
106396
+ exactValueIds.add(valueId);
106397
+ if (descendants) descendantValueIds.add(valueId);
106398
+ }
106399
+ };
106400
+ function visitMember(memberId) {
106401
+ if (visitedMemberIds.has(memberId)) return;
106402
+ visitedMemberIds.add(memberId);
106403
+ const rawMember = membersById2.get(memberId);
106404
+ if (rawMember === void 0) return;
106405
+ const member = resolveMember2(rawMember, args.postDocument.members);
106406
+ rememberDefaultIds(member.defaultValue, true);
106407
+ if (!isMemberClassBase(member)) return;
106408
+ const defaultClassId = Reflect.get(member.defaultValue ?? {}, "classId");
106409
+ visitClass(
106410
+ typeof defaultClassId === "string" ? defaultClassId : member.classId
106411
+ );
106412
+ }
106413
+ function visitClass(classId) {
106414
+ if (visitedClassIds.has(classId)) return;
106415
+ visitedClassIds.add(classId);
106416
+ if (!classesById2.has(classId)) return;
106417
+ for (const entry of mergeStoredInstanceSchema(
106418
+ classId,
106419
+ args.postDocument.classes,
106420
+ args.postDocument.members
106421
+ )) {
106422
+ visitMember(entry.memberId);
106423
+ }
106424
+ }
106425
+ for (const member of [
106426
+ ...args.currentDocument.members,
106427
+ ...args.postDocument.members
106428
+ ]) {
106429
+ rememberDefaultIds(member.defaultValue, false);
106430
+ }
106431
+ for (const seed of args.authoredValueSeeds) {
106432
+ visitMember(seed.memberId);
106433
+ if ("classId" in seed && typeof seed.classId === "string") {
106434
+ visitClass(seed.classId);
106435
+ }
106436
+ for (const row of seed.values ?? []) {
106437
+ visitMember(row.memberId);
106438
+ if ("classId" in row && typeof row.classId === "string") {
106439
+ visitClass(row.classId);
106440
+ }
106441
+ }
106442
+ }
106443
+ for (const change of args.changes) {
106444
+ if (change.recordKind === "member") {
106445
+ visitMember(change.recordId);
106446
+ const currentMember = args.currentDocument.members.find(
106447
+ (member) => member.id === change.recordId
106448
+ );
106449
+ if (currentMember !== void 0) {
106450
+ rememberDefaultIds(currentMember.defaultValue, true);
106451
+ }
106452
+ }
106453
+ if (change.recordKind === "value" && change.nextData !== null && typeof change.nextData === "object") {
106454
+ const classId = Reflect.get(change.nextData, "classId");
106455
+ if (typeof classId === "string") visitClass(classId);
106456
+ }
106457
+ }
106458
+ return { exactValueIds, descendantValueIds };
106459
+ }
106460
+ function planCommitPreparationInitialScope(args) {
106461
+ const rules = new Set(
106462
+ COMMIT_PREPARATION_CLOSURE_SPECS[args.pass].closureRules
106463
+ );
106464
+ const currentDocument = overlayPlanningDocument(args.document, []);
106465
+ const postDocument = overlayPlanningDocument(currentDocument, args.changes);
106466
+ const exactRecords = /* @__PURE__ */ new Map();
106467
+ const descendantRecords = /* @__PURE__ */ new Map();
106468
+ const rememberExact = (recordKind, recordId, includeDescendants = false) => {
106469
+ const record3 = { recordKind, recordId };
106470
+ const key = commitPreparationRecordKey(record3);
106471
+ exactRecords.set(key, record3);
106472
+ if (includeDescendants) descendantRecords.set(key, record3);
106473
+ };
106474
+ for (const change of args.changes) {
106475
+ rememberExact(change.recordKind, change.recordId, true);
106476
+ if (change.recordKind === "member") {
106477
+ rememberExact("value", derivedMemberValueId(change.recordId), true);
106478
+ const current = args.document.members.find(
106479
+ (member) => member.id === change.recordId
106480
+ );
106481
+ for (const candidate of [current, change.nextData]) {
106482
+ if (candidate === null || typeof candidate !== "object") continue;
106483
+ const valueId = Reflect.get(candidate, "valueId");
106484
+ if (typeof valueId === "string") rememberExact("value", valueId, true);
106485
+ }
106486
+ }
106487
+ for (const valueId of collectStoredRecordIds(change.nextData)) {
106488
+ rememberExact("value", valueId, true);
106489
+ }
106490
+ if (change.nextData !== null && typeof change.nextData === "object") {
106491
+ const candidate = change.recordKind === "member" && isMemberStringBase(change.nextData) && isLocalizedStringMember(change.nextData) ? Reflect.get(change.nextData, "defaultValue") : change.recordKind === "value" ? Reflect.get(change.nextData, "value") : void 0;
106492
+ const localizedTextId = candidate !== null && typeof candidate === "object" && typeof Reflect.get(candidate, "value") === "string" ? Reflect.get(candidate, "value") : candidate;
106493
+ if (typeof localizedTextId === "string") {
106494
+ rememberExact("localized-text", localizedTextId);
106495
+ }
106496
+ }
106497
+ }
106498
+ const memberById2 = new Map(
106499
+ postDocument.members.flatMap((member) => {
106500
+ const id2 = Reflect.get(member, "id");
106501
+ return typeof id2 === "string" ? [[id2, member]] : [];
106502
+ })
106503
+ );
106504
+ const rememberSeedLocalizedTextCandidate = (memberId, body) => {
106505
+ const member = memberById2.get(memberId);
106506
+ if (member === void 0 || !isMemberStringBase(member) || !isLocalizedStringMember(member) || typeof body !== "string") {
106507
+ return;
106508
+ }
106509
+ rememberExact("localized-text", body);
106510
+ };
106511
+ if (rules.has("authored-seed-requested-ids")) {
106512
+ for (const seed of args.authoredValueSeeds) {
106513
+ if (seed.valueId !== void 0) {
106514
+ rememberExact("value", seed.valueId);
106515
+ }
106516
+ rememberSeedLocalizedTextCandidate(
106517
+ seed.memberId,
106518
+ Reflect.get(seed, "value")
106519
+ );
106520
+ for (const row of seed.values ?? []) {
106521
+ rememberExact("value", row.id);
106522
+ rememberSeedLocalizedTextCandidate(
106523
+ row.memberId,
106524
+ Reflect.get(row, "value")
106525
+ );
106526
+ }
106527
+ for (const localizedText of seed.localizedTexts ?? []) {
106528
+ rememberExact("localized-text", localizedText.id);
106529
+ }
106530
+ for (const valueId of collectStoredRecordIds(seed)) {
106531
+ rememberExact("value", valueId);
106532
+ }
106533
+ }
106534
+ }
106535
+ if (rules.has("member-default-value-closure")) {
106536
+ const defaultScope = commitPreparationMemberDefaultValueScope({
106537
+ currentDocument,
106538
+ postDocument,
106539
+ changes: args.changes,
106540
+ authoredValueSeeds: args.authoredValueSeeds
106541
+ });
106542
+ for (const valueId of defaultScope.exactValueIds) {
106543
+ rememberExact(
106544
+ "value",
106545
+ valueId,
106546
+ defaultScope.descendantValueIds.has(valueId)
106547
+ );
106548
+ }
106549
+ }
106550
+ if (rules.has("every-variant-root")) {
106551
+ for (const variant of postDocument.variants ?? []) {
106552
+ rememberExact("value", variant.valueId);
106553
+ }
106554
+ for (const folder of postDocument.variantFolders ?? []) {
106555
+ const collectionValueId = Reflect.get(
106556
+ folder,
106557
+ "collectionValueId"
106558
+ );
106559
+ if (typeof collectionValueId === "string") {
106560
+ rememberExact("value", collectionValueId);
106561
+ }
106562
+ }
106563
+ }
106564
+ if (rules.has("touched-variant-schema-key-children")) {
106565
+ const valuesById = new Map(
106566
+ postDocument.values.map((value) => [value.id, value])
106567
+ );
106568
+ for (const variant of postDocument.variants ?? []) {
106569
+ const root = valuesById.get(variant.valueId);
106570
+ const body = root?.value;
106571
+ if (body === null || typeof body !== "object") continue;
106572
+ for (const schemaKey of [
106573
+ NEO_VARIANT_INITIALIZE_SCHEMA_KEY,
106574
+ NEO_VARIANT_APPLY_SCHEMA_KEY,
106575
+ NEO_VARIANT_OVERRIDES_SCHEMA_KEY,
106576
+ NEO_VARIANT_CHILD_OVERRIDES_SCHEMA_KEY
106577
+ ]) {
106578
+ const childId = Reflect.get(body, schemaKey);
106579
+ if (typeof childId === "string") rememberExact("value", childId);
106580
+ }
106581
+ }
106582
+ }
106583
+ const ranges = [];
106584
+ if (rules.has("source-only-rows")) {
106585
+ ranges.push({
106586
+ rangeKind: "source-only",
106587
+ targetKey: "true",
106588
+ limit: Math.min(
106589
+ args.rangeLimit,
106590
+ COMMIT_PREPARATION_SCOPE_SOURCE_ONLY_ROW_LIMIT
106591
+ )
106592
+ });
106593
+ }
106594
+ const valueOwnerMemberIds = /* @__PURE__ */ new Set();
106595
+ const animationValidationMemberIds = /* @__PURE__ */ new Set();
106596
+ if (rules.has("whole-graph-validation-members")) {
106597
+ for (const memberId of commitPreparationValidationCandidateMemberIds(
106598
+ postDocument
106599
+ )) {
106600
+ valueOwnerMemberIds.add(memberId);
106601
+ }
106602
+ for (const change of args.changes) {
106603
+ if (change.recordKind === "member") {
106604
+ valueOwnerMemberIds.add(change.recordId);
106605
+ }
106606
+ }
106607
+ const animationSchema = commitPreparationAnimationSchema(postDocument);
106608
+ const declaringClassIdsByMemberId = /* @__PURE__ */ new Map();
106609
+ for (const schemaClass2 of postDocument.classes) {
106610
+ for (const memberId of Object.values(schemaClass2.schema)) {
106611
+ const declaring = declaringClassIdsByMemberId.get(memberId) ?? [];
106612
+ declaring.push(schemaClass2.id);
106613
+ declaringClassIdsByMemberId.set(memberId, declaring);
106614
+ }
106615
+ }
106616
+ const changedClassIds = /* @__PURE__ */ new Set();
106617
+ for (const change of args.changes) {
106618
+ if (change.recordKind === "class") changedClassIds.add(change.recordId);
106619
+ if (change.recordKind !== "member") continue;
106620
+ if (animationSchema.rootMemberIds.has(change.recordId)) {
106621
+ animationValidationMemberIds.add(change.recordId);
106622
+ }
106623
+ for (const classId of declaringClassIdsByMemberId.get(change.recordId) ?? []) {
106624
+ changedClassIds.add(classId);
106625
+ }
106626
+ }
106627
+ for (const seed of args.authoredValueSeeds) {
106628
+ if (animationSchema.rootMemberIds.has(seed.memberId)) {
106629
+ animationValidationMemberIds.add(seed.memberId);
106630
+ }
106631
+ }
106632
+ for (const memberId of animationClipMemberIdsTargetingClasses(
106633
+ postDocument,
106634
+ changedClassIds,
106635
+ animationSchema
106636
+ )) {
106637
+ rememberExact("member", memberId, true);
106638
+ animationValidationMemberIds.add(memberId);
106639
+ }
106640
+ }
106641
+ for (const memberId of valueOwnerMemberIds) {
106642
+ ranges.push({
106643
+ rangeKind: "value-member",
106644
+ targetKey: memberId,
106645
+ limit: args.rangeLimit
106646
+ });
106647
+ }
106648
+ if (rules.has("world-value-ranges")) {
106649
+ for (const worldKind of commitPreparationWorldScopeKinds({
106650
+ currentDocument,
106651
+ postDocument,
106652
+ changes: args.changes
106653
+ })) {
106654
+ ranges.push({
106655
+ rangeKind: "world-kind",
106656
+ targetKey: worldKind,
106657
+ limit: args.rangeLimit
106658
+ });
106659
+ }
106660
+ }
106661
+ const postingKeys = /* @__PURE__ */ new Map();
106662
+ const rememberPosting = (edgeKind, targetKey) => {
106663
+ const request = { edgeKind, targetKey, limit: args.postingLimit };
106664
+ postingKeys.set(commitPreparationPostingRequestKey(request), request);
106665
+ };
106666
+ const currentByKey = projectDocumentRecordsByKey(currentDocument);
106667
+ if (rules.has("dialogue-membership-peers")) {
106668
+ for (const change of args.changes) {
106669
+ if (change.recordKind === "dialogue") {
106670
+ rememberPosting("dialogue-membership", change.recordId);
106671
+ continue;
106672
+ }
106673
+ if (change.recordKind !== "dialogue-node") continue;
106674
+ for (const candidate of [
106675
+ currentByKey.get(commitPreparationRecordKey(change)),
106676
+ change.nextData
106677
+ ]) {
106678
+ if (candidate === null || typeof candidate !== "object") continue;
106679
+ const dialogueId = Reflect.get(candidate, "dialogueId");
106680
+ if (typeof dialogueId === "string") {
106681
+ rememberPosting("dialogue-membership", dialogueId);
106682
+ }
106683
+ }
106684
+ }
106685
+ }
106686
+ if (rules.has("compiled-reference-reverse-index")) {
106687
+ const targets = collectNeoScriptRecompileReferenceTargets({
106688
+ currentDocument,
106689
+ postDocument,
106690
+ changes: args.changes,
106691
+ additionalImpactedIds: args.additionalImpactedIds,
106692
+ additionalChangedValueIds: args.additionalChangedValueIds
106693
+ });
106694
+ for (const id2 of targets.ids) rememberPosting("compiled-reference", id2);
106695
+ for (const name of targets.names) {
106696
+ rememberPosting("compiled-reference", name);
106697
+ }
106698
+ }
106699
+ for (const change of args.changes) {
106700
+ if (rules.has("compiled-reference-reverse-index")) {
106701
+ if (change.operation !== "create") {
106702
+ rememberPosting("compiled-reference", change.recordId);
106703
+ }
106704
+ for (const candidate of [
106705
+ currentByKey.get(commitPreparationRecordKey(change)),
106706
+ change.nextData
106707
+ ]) {
106708
+ if (candidate === null || typeof candidate !== "object") continue;
106709
+ const name = Reflect.get(candidate, "name");
106710
+ if (typeof name === "string" && change.operation !== "create") {
106711
+ rememberPosting("compiled-reference", name);
106712
+ }
106713
+ }
106714
+ }
106715
+ if (rules.has("stamp-edge-candidates") && change.recordKind === "member" && change.operation === "delete") {
106716
+ rememberPosting("stamp-binding", change.recordId);
106717
+ }
106718
+ if (rules.has("localizable-reference-candidates") && change.recordKind === "value" && change.operation === "create" && change.nextData !== null && typeof change.nextData === "object" && typeof Reflect.get(change.nextData, "value") === "string") {
106719
+ rememberPosting("containment-child", change.recordId);
106720
+ rememberPosting("compiled-reference", change.recordId);
106721
+ }
106722
+ }
106723
+ if (rules.has("localizable-reference-candidates")) {
106724
+ for (const seed of args.authoredValueSeeds) {
106725
+ const rootId = seed.valueId ?? derivedMemberValueId(seed.memberId);
106726
+ if (typeof Reflect.get(seed, "value") === "string") {
106727
+ rememberPosting("containment-child", rootId);
106728
+ rememberPosting("compiled-reference", rootId);
106729
+ }
106730
+ for (const row of seed.values ?? []) {
106731
+ if (typeof Reflect.get(row, "value") !== "string") continue;
106732
+ rememberPosting("containment-child", row.id);
106733
+ rememberPosting("compiled-reference", row.id);
106734
+ }
106735
+ }
106736
+ }
106737
+ return {
106738
+ exactRecords: [...exactRecords.values()].sort(compareRecordKeys),
106739
+ descendantRecords: [...descendantRecords.values()].sort(compareRecordKeys),
106740
+ ranges: ranges.sort(
106741
+ (left, right) => commitPreparationRangeRequestKey(left).localeCompare(
106742
+ commitPreparationRangeRequestKey(right)
106743
+ )
106744
+ ),
106745
+ postings: [...postingKeys.values()].sort(
106746
+ (left, right) => commitPreparationPostingRequestKey(left).localeCompare(
106747
+ commitPreparationPostingRequestKey(right)
106748
+ )
106749
+ ),
106750
+ fullContentDimension: rules.has("full-content-dimension") && (containsInitializerSource(args.changes) || containsInitializerSource(args.authoredValueSeeds)),
106751
+ ...animationValidationScope(animationValidationMemberIds)
106752
+ };
106753
+ }
106754
+ function planCommitPreparationLoadedClosureScope(args) {
106755
+ const rules = new Set(
106756
+ COMMIT_PREPARATION_CLOSURE_SPECS[args.pass].closureRules
106757
+ );
106758
+ const exactRecords = /* @__PURE__ */ new Map();
106759
+ const descendantRecords = /* @__PURE__ */ new Map();
106760
+ const ranges = /* @__PURE__ */ new Map();
106761
+ const postings = /* @__PURE__ */ new Map();
106762
+ const animationValidationMemberIds = /* @__PURE__ */ new Set();
106763
+ const rememberExact = (recordKind, recordId) => {
106764
+ const record3 = { recordKind, recordId };
106765
+ exactRecords.set(commitPreparationRecordKey(record3), record3);
106766
+ };
106767
+ const rememberDescendant = (recordKind, recordId) => {
106768
+ const record3 = { recordKind, recordId };
106769
+ const key = commitPreparationRecordKey(record3);
106770
+ exactRecords.set(key, record3);
106771
+ descendantRecords.set(key, record3);
106772
+ };
106773
+ const rememberRange = (range2) => {
106774
+ ranges.set(commitPreparationRangeRequestKey(range2), range2);
106775
+ };
106776
+ const rememberPosting = (posting) => {
106777
+ postings.set(commitPreparationPostingRequestKey(posting), posting);
106778
+ };
106779
+ for (const record3 of args.records) {
106780
+ if (rules.has("animation-graph-closure") && args.animationSchema !== void 0) {
106781
+ if (record3.recordKind === "value" && record3.includeDescendants === false && isAnimationSegmentValueRow(record3.data, args.animationSchema)) {
106782
+ rememberDescendant(record3.recordKind, record3.recordId);
106783
+ }
106784
+ if (record3.parentRecordKind === "member" && typeof record3.parentRecordId === "string" && args.animationSchema.rootMemberIds.has(record3.parentRecordId)) {
106785
+ rememberDescendant("member", record3.parentRecordId);
106786
+ animationValidationMemberIds.add(record3.parentRecordId);
106787
+ }
106788
+ }
106789
+ if (rules.has("ancestor-paths") && record3.parentRecordKind !== null && record3.parentRecordKind !== void 0 && record3.parentRecordId !== null && record3.parentRecordId !== void 0) {
106790
+ rememberExact(record3.parentRecordKind, record3.parentRecordId);
106791
+ }
106792
+ const canOwnStoredDescendants = record3.recordKind !== "value" || record3.data !== null && typeof record3.data === "object" && Reflect.get(record3.data, "value") !== null && typeof Reflect.get(record3.data, "value") === "object";
106793
+ if (rules.has("descendants") && record3.includeDescendants !== false && canOwnStoredDescendants && (record3.recordKind === "member" || record3.recordKind === "value" || record3.recordKind === "class" || record3.recordKind === "variant")) {
106794
+ rememberRange({
106795
+ rangeKind: "children",
106796
+ targetKey: commitPreparationRecordKey(record3),
106797
+ limit: args.rangeLimit
106798
+ });
106799
+ }
106800
+ if (rules.has("descendants") && record3.includeDescendants !== false && canOwnStoredDescendants && record3.recordKind === "value") {
106801
+ rememberRange({
106802
+ rangeKind: "container-members",
106803
+ targetKey: record3.recordId,
106804
+ limit: args.rangeLimit
106805
+ });
106806
+ }
106807
+ if (rules.has("dialogue-membership-peers") && record3.includeDescendants !== false && record3.recordKind === "dialogue-node" && record3.data !== null && typeof record3.data === "object") {
106808
+ const dialogueId = Reflect.get(record3.data, "dialogueId");
106809
+ if (typeof dialogueId === "string") {
106810
+ rememberPosting({
106811
+ edgeKind: "dialogue-membership",
106812
+ targetKey: dialogueId,
106813
+ limit: args.postingLimit
106814
+ });
106815
+ }
106816
+ }
106817
+ if (record3.includeDescendants !== false) {
106818
+ for (const valueId of collectStoredRecordIds(record3.data)) {
106819
+ rememberDescendant("value", valueId);
106820
+ }
106821
+ }
106822
+ }
106823
+ return {
106824
+ exactRecords: [...exactRecords.values()].sort(compareRecordKeys),
106825
+ descendantRecords: [...descendantRecords.values()].sort(compareRecordKeys),
106826
+ ranges: [...ranges.values()].sort(
106827
+ (left, right) => commitPreparationRangeRequestKey(left).localeCompare(
106828
+ commitPreparationRangeRequestKey(right)
106829
+ )
106830
+ ),
106831
+ postings: [...postings.values()].sort(
106832
+ (left, right) => commitPreparationPostingRequestKey(left).localeCompare(
106833
+ commitPreparationPostingRequestKey(right)
106834
+ )
106835
+ ),
106836
+ fullContentDimension: false,
106837
+ ...animationValidationScope(animationValidationMemberIds)
106838
+ };
106839
+ }
106840
+ function animationValidationScope(memberIds) {
106841
+ return memberIds.size === 0 ? {} : { animationValidationMemberIds: [...memberIds].sort() };
106842
+ }
106843
+ function withCommitPreparationInMemoryPlacement(records2) {
106844
+ const recordKeys = new Set(records2.map(commitPreparationRecordKey));
106845
+ const parentByChild = /* @__PURE__ */ new Map();
106846
+ const ambiguousParentsByChild = /* @__PURE__ */ new Map();
106847
+ const authorityRank = {
106848
+ "reverse-container": 1,
106849
+ forward: 2,
106850
+ persisted: 3
106851
+ };
106852
+ const rememberParent = (childKey, parent, authority) => {
106853
+ if (!recordKeys.has(childKey)) return;
106854
+ const prior = parentByChild.get(childKey);
106855
+ if (prior !== void 0) {
106856
+ const comparison = authorityRank[authority] - authorityRank[prior.authority];
106857
+ if (comparison < 0) return;
106858
+ if (comparison > 0) {
106859
+ ambiguousParentsByChild.delete(childKey);
106860
+ }
106861
+ if (comparison === 0) {
106862
+ if (prior.recordKind === parent.recordKind && prior.recordId === parent.recordId) {
106863
+ return;
106864
+ }
106865
+ const ambiguity = ambiguousParentsByChild.get(childKey) ?? {
106866
+ authority,
106867
+ parents: /* @__PURE__ */ new Set()
106868
+ };
106869
+ ambiguity.parents.add(`${prior.recordKind}:${prior.recordId}`);
106870
+ ambiguity.parents.add(`${parent.recordKind}:${parent.recordId}`);
106871
+ ambiguousParentsByChild.set(childKey, ambiguity);
106872
+ if (`${prior.recordKind}:${prior.recordId}`.localeCompare(
106873
+ `${parent.recordKind}:${parent.recordId}`
106874
+ ) <= 0) {
106875
+ return;
106876
+ }
106877
+ }
106878
+ }
106879
+ parentByChild.set(childKey, { ...parent, authority });
106880
+ };
106881
+ for (const record3 of records2) {
106882
+ const sourceKey = commitPreparationRecordKey(record3);
106883
+ if (record3.parentRecordKind !== void 0 && record3.parentRecordKind !== null && record3.parentRecordId !== void 0 && record3.parentRecordId !== null) {
106884
+ rememberParent(
106885
+ sourceKey,
106886
+ {
106887
+ recordKind: record3.parentRecordKind,
106888
+ recordId: record3.parentRecordId
106889
+ },
106890
+ "persisted"
106891
+ );
106892
+ }
106893
+ if (record3.recordKind === "dialogue-node") {
106894
+ const dialogueId = record3.data !== null && typeof record3.data === "object" ? Reflect.get(record3.data, "dialogueId") : void 0;
106895
+ if (typeof dialogueId === "string") {
106896
+ rememberParent(
106897
+ sourceKey,
106898
+ {
106899
+ recordKind: "dialogue",
106900
+ recordId: dialogueId
106901
+ },
106902
+ "forward"
106903
+ );
106904
+ }
106905
+ }
106906
+ for (const edge of extractProjectSnapshotDerivedEdges(record3).edges) {
106907
+ if (edge.edgeKind !== "containment-child" || edge.targetAddressing !== "record") {
106908
+ continue;
106909
+ }
106910
+ const payload = JSON.parse(edge.payloadJson);
106911
+ if (payload !== null && typeof payload === "object" && Reflect.get(payload, "relation") === "container-join") {
106912
+ rememberParent(
106913
+ sourceKey,
106914
+ {
106915
+ recordKind: "value",
106916
+ recordId: edge.targetKey
106917
+ },
106918
+ "reverse-container"
106919
+ );
106920
+ } else {
106921
+ rememberParent(
106922
+ `value:${edge.targetKey}`,
106923
+ {
106924
+ recordKind: record3.recordKind,
106925
+ recordId: record3.recordId
106926
+ },
106927
+ "forward"
106928
+ );
106929
+ }
106930
+ }
106931
+ }
106932
+ for (const [childKey, ambiguity] of ambiguousParentsByChild) {
106933
+ if (parentByChild.get(childKey)?.authority !== ambiguity.authority)
106934
+ continue;
106935
+ throw new Error(
106936
+ `Commit preparation placement for "${childKey}" has ambiguous ${ambiguity.authority} parents ${[
106937
+ ...ambiguity.parents
106938
+ ].sort().map((parent) => `"${parent}"`).join(" and ")}.`
106939
+ );
106940
+ }
106941
+ return records2.map((record3) => {
106942
+ const parent = parentByChild.get(commitPreparationRecordKey(record3));
106943
+ return parent === void 0 ? record3 : {
106944
+ ...record3,
106945
+ parentRecordKind: parent.recordKind,
106946
+ parentRecordId: parent.recordId
106947
+ };
106948
+ });
106949
+ }
106950
+ function commitPreparationPackedRootIds(records2) {
106951
+ const rootIdByChildId = /* @__PURE__ */ new Map();
106952
+ for (const record3 of records2) {
106953
+ if (record3.recordKind !== "value") continue;
106954
+ if (!isMemberValue(record3.data)) continue;
106955
+ if (!rowCarriesPackedValueContent(record3.data)) continue;
106956
+ for (const position of packedValuePositions(record3.data)) {
106957
+ rootIdByChildId.set(position.valueId, record3.recordId);
106958
+ }
106959
+ }
106960
+ return rootIdByChildId;
106961
+ }
106962
+ function readCommitPreparationScopeInMemory(args) {
106963
+ const records2 = withCommitPreparationInMemoryPlacement(args.records);
106964
+ const recordsByKey = new Map(
106965
+ records2.map((record3) => [commitPreparationRecordKey(record3), record3])
106966
+ );
106967
+ const packedRootIdByChildId = commitPreparationPackedRootIds(records2);
106968
+ const exactStates = /* @__PURE__ */ new Map();
106969
+ const packedRootKeyByExactKey = /* @__PURE__ */ new Map();
106970
+ for (const record3 of args.request.exactRecords) {
106971
+ const key = commitPreparationRecordKey(record3);
106972
+ if (recordsByKey.has(key)) {
106973
+ exactStates.set(key, "live");
106974
+ continue;
106975
+ }
106976
+ const rootId = record3.recordKind === "value" ? packedRootIdByChildId.get(record3.recordId) : void 0;
106977
+ if (rootId === void 0) {
106978
+ exactStates.set(key, "absent");
106979
+ continue;
106980
+ }
106981
+ const rootKey = commitPreparationRecordKey({
106982
+ recordKind: "value",
106983
+ recordId: rootId
106984
+ });
106985
+ exactStates.set(key, "live");
106986
+ exactStates.set(rootKey, "live");
106987
+ packedRootKeyByExactKey.set(key, rootKey);
106988
+ }
106989
+ const keysByKind = /* @__PURE__ */ new Map();
106990
+ const sourceOnlyKeys = [];
106991
+ const valueKeysByMemberId = /* @__PURE__ */ new Map();
106992
+ const valueKeysByClassId = /* @__PURE__ */ new Map();
106993
+ const valueKeysByContainerId = /* @__PURE__ */ new Map();
106994
+ const valueKeysByWorldKind = /* @__PURE__ */ new Map();
106995
+ const childKeysByParentKey = /* @__PURE__ */ new Map();
106996
+ const worldKindsByClass = args.document === void 0 ? /* @__PURE__ */ new Map() : worldKindByClassId(args.document);
106997
+ const semanticOwners = args.document === void 0 ? /* @__PURE__ */ new Map() : resolveSemanticOwnerMembersForValues(
106998
+ args.document,
106999
+ new Set(args.document.values.map((value) => value.id))
107000
+ );
107001
+ const rememberIndexed = (index, target, key) => {
107002
+ if (typeof target !== "string") return;
107003
+ const values = index.get(target) ?? [];
107004
+ values.push(key);
107005
+ index.set(target, values);
107006
+ };
107007
+ for (const record3 of records2) {
107008
+ const key = commitPreparationRecordKey(record3);
107009
+ const kindKeys = keysByKind.get(record3.recordKind) ?? [];
107010
+ kindKeys.push(key);
107011
+ keysByKind.set(record3.recordKind, kindKeys);
107012
+ if (containsAuthoredNeoScriptSource(record3.data) && !containsCompiledNeoScriptBody(record3.data)) {
107013
+ sourceOnlyKeys.push(key);
107014
+ }
107015
+ if (record3.recordKind !== "value") continue;
107016
+ const data = record3.data !== null && typeof record3.data === "object" ? record3.data : {};
107017
+ const explicitMemberId = Reflect.get(data, "valueMemberId") ?? Reflect.get(data, "memberId");
107018
+ rememberIndexed(
107019
+ valueKeysByMemberId,
107020
+ explicitMemberId ?? Reflect.get(semanticOwners.get(record3.recordId) ?? {}, "id"),
107021
+ key
107022
+ );
107023
+ rememberIndexed(valueKeysByClassId, Reflect.get(data, "classId"), key);
107024
+ const classId = Reflect.get(data, "classId");
107025
+ if (typeof classId === "string") {
107026
+ rememberIndexed(
107027
+ valueKeysByWorldKind,
107028
+ worldKindsByClass.get(classId),
107029
+ key
107030
+ );
107031
+ }
107032
+ rememberIndexed(
107033
+ valueKeysByContainerId,
107034
+ Reflect.get(data, "containerId"),
107035
+ key
107036
+ );
107037
+ }
107038
+ const rememberChild = (parentKey, childKey) => {
107039
+ const children = childKeysByParentKey.get(parentKey) ?? [];
107040
+ if (!children.includes(childKey)) children.push(childKey);
107041
+ childKeysByParentKey.set(parentKey, children);
107042
+ };
107043
+ for (const record3 of records2) {
107044
+ const sourceKey = commitPreparationRecordKey(record3);
107045
+ const parentRecordKind = record3.parentRecordKind;
107046
+ const parentRecordId = record3.parentRecordId;
107047
+ if (typeof parentRecordKind === "string" && typeof parentRecordId === "string") {
107048
+ const parentKey = `${parentRecordKind}:${parentRecordId}`;
107049
+ rememberChild(parentKey, sourceKey);
107050
+ }
107051
+ }
107052
+ const rangeRecordKeys = /* @__PURE__ */ new Map();
107053
+ for (const request of args.request.ranges) {
107054
+ const matching = request.rangeKind === "record-kind" ? keysByKind.get(request.targetKey) ?? [] : request.rangeKind === "source-only" ? sourceOnlyKeys : request.rangeKind === "value-member" ? valueKeysByMemberId.get(request.targetKey) ?? [] : request.rangeKind === "value-class" ? valueKeysByClassId.get(request.targetKey) ?? [] : request.rangeKind === "container-members" ? valueKeysByContainerId.get(request.targetKey) ?? [] : request.rangeKind === "children" ? childKeysByParentKey.get(request.targetKey) ?? [] : request.rangeKind === "world-kind" ? valueKeysByWorldKind.get(request.targetKey) ?? [] : keysByKind.get("value") ?? [];
107055
+ if (matching.length > request.limit) {
107056
+ return {
107057
+ kind: "fallback",
107058
+ reason: {
107059
+ code: "range-row-cap-exceeded",
107060
+ requestKey: commitPreparationRangeRequestKey(request),
107061
+ observed: matching.length,
107062
+ limit: request.limit
107063
+ }
107064
+ };
107065
+ }
107066
+ rangeRecordKeys.set(
107067
+ commitPreparationRangeRequestKey(request),
107068
+ [...matching].sort()
107069
+ );
107070
+ }
107071
+ const persisted = [];
107072
+ for (const record3 of records2) {
107073
+ const extraction = extractProjectSnapshotDerivedEdges(record3);
107074
+ if (!extraction.complete && args.request.postings.some(
107075
+ (request) => request.edgeKind === "constructor-aggregate"
107076
+ )) {
107077
+ return {
107078
+ kind: "fallback",
107079
+ reason: {
107080
+ code: "derived-edge-extraction-incomplete",
107081
+ recordKey: commitPreparationRecordKey(record3)
107082
+ }
107083
+ };
107084
+ }
107085
+ for (const edge of extraction.edges) {
107086
+ persisted.push({ ...record3, ...edge });
107087
+ }
107088
+ }
107089
+ const overlaid = overlayCommitPreparationDerivedEdgePostings({
107090
+ requests: args.request.postings,
107091
+ persisted,
107092
+ prepared: args.prepared
107093
+ });
107094
+ if (overlaid.kind === "fallback") return overlaid;
107095
+ return {
107096
+ kind: "complete",
107097
+ value: {
107098
+ exactStates,
107099
+ packedRootKeyByExactKey,
107100
+ rangeRecordKeys,
107101
+ postingSourceKeys: new Map(
107102
+ [...overlaid.value].map(([key, edges]) => [
107103
+ key,
107104
+ edges.map(commitPreparationRecordKey)
107105
+ ])
107106
+ )
107107
+ }
107108
+ };
107109
+ }
107110
+ function commitPreparationRecordKey(record3) {
107111
+ return `${record3.recordKind}:${record3.recordId}`;
107112
+ }
107113
+ function commitPreparationRangeRequestKey(request) {
107114
+ return `${request.rangeKind}:${request.targetKey}`;
107115
+ }
107116
+ function commitPreparationPostingRequestKey(request) {
107117
+ return `${request.edgeKind}:${request.targetKey}`;
107118
+ }
107119
+ function overlayCommitPreparationDerivedEdgePostings(args) {
107120
+ const requestsByKey = /* @__PURE__ */ new Map();
107121
+ const answersByKey = /* @__PURE__ */ new Map();
107122
+ for (const request of args.requests) {
107123
+ const key = commitPreparationPostingRequestKey(request);
107124
+ const prior = requestsByKey.get(key);
107125
+ if (prior === void 0 || prior.limit < request.limit) {
107126
+ requestsByKey.set(key, request);
107127
+ }
107128
+ if (!answersByKey.has(key)) answersByKey.set(key, /* @__PURE__ */ new Map());
107129
+ }
107130
+ const preparedBySource = /* @__PURE__ */ new Map();
107131
+ for (const change of args.prepared) {
107132
+ preparedBySource.set(commitPreparationRecordKey(change), change);
107133
+ }
107134
+ for (const edge of args.persisted) {
107135
+ const requestKey = commitPreparationPostingRequestKey(edge);
107136
+ const answer = answersByKey.get(requestKey);
107137
+ if (answer === void 0) continue;
107138
+ if (preparedBySource.has(commitPreparationRecordKey(edge))) continue;
107139
+ rememberOverlayEdge(answer, { ...edge, origin: "persisted" });
107140
+ }
107141
+ const constructorAggregateRequested = [...requestsByKey.values()].some(
107142
+ (request) => request.edgeKind === "constructor-aggregate"
107143
+ );
107144
+ for (const change of preparedBySource.values()) {
107145
+ if (change.operation === "delete" || change.deleted === true) continue;
107146
+ if (change.nextData === void 0) {
107147
+ return {
107148
+ kind: "fallback",
107149
+ reason: {
107150
+ code: "prepared-edge-source-missing-data",
107151
+ recordKey: commitPreparationRecordKey(change)
107152
+ }
107153
+ };
107154
+ }
107155
+ const extraction = extractProjectSnapshotDerivedEdges({
107156
+ recordKind: change.recordKind,
107157
+ recordId: change.recordId,
107158
+ data: change.nextData,
107159
+ constructorAggregateEdges: change.constructorAggregateEdges
107160
+ });
107161
+ if (!extraction.complete && constructorAggregateRequested) {
107162
+ return {
107163
+ kind: "fallback",
107164
+ reason: {
107165
+ code: "derived-edge-extraction-incomplete",
107166
+ recordKey: commitPreparationRecordKey(change)
107167
+ }
107168
+ };
107169
+ }
107170
+ for (const edge of extraction.edges) {
107171
+ const requestKey = commitPreparationPostingRequestKey(edge);
107172
+ const answer = answersByKey.get(requestKey);
107173
+ if (answer === void 0) continue;
107174
+ rememberOverlayEdge(answer, {
107175
+ ...edge,
107176
+ recordKind: change.recordKind,
107177
+ recordId: change.recordId,
107178
+ origin: "prepared"
107179
+ });
107180
+ }
107181
+ }
107182
+ const result = /* @__PURE__ */ new Map();
107183
+ for (const [requestKey, answer] of answersByKey) {
107184
+ const request = requestsByKey.get(requestKey);
107185
+ if (request === void 0) continue;
107186
+ if (answer.size > request.limit) {
107187
+ return {
107188
+ kind: "fallback",
107189
+ reason: {
107190
+ code: "posting-budget-exceeded",
107191
+ requestKey,
107192
+ observed: answer.size,
107193
+ limit: request.limit
107194
+ }
107195
+ };
107196
+ }
107197
+ result.set(
107198
+ requestKey,
107199
+ [...answer.values()].sort(
107200
+ (left, right) => overlayEdgeKey(left).localeCompare(overlayEdgeKey(right))
107201
+ )
107202
+ );
107203
+ }
107204
+ return { kind: "complete", value: result };
107205
+ }
107206
+ function rememberOverlayEdge(answer, edge) {
107207
+ answer.set(overlayEdgeKey(edge), edge);
107208
+ }
107209
+ function overlayEdgeKey(edge) {
107210
+ return `${commitPreparationRecordKey(edge)}:${projectSnapshotDerivedEdgeIdentity(edge)}`;
107211
+ }
107212
+ function commitPreparationValidationCandidateMemberIds(document) {
107213
+ const result = /* @__PURE__ */ new Set();
107214
+ for (const member of document.members) {
107215
+ if (member.kind === 26 /* NSAction */ || member.kind === 27 /* Variant */ || isReadOnlyMember(member)) {
107216
+ result.add(member.id);
107217
+ }
107218
+ }
107219
+ return result;
107220
+ }
107221
+ function projectDocumentRecordsByKey(document) {
107222
+ const result = /* @__PURE__ */ new Map();
107223
+ const add = (recordKind, records2) => {
107224
+ for (const record3 of records2) {
107225
+ if (record3 === null || typeof record3 !== "object") continue;
107226
+ const recordId = Reflect.get(record3, "id");
107227
+ if (typeof recordId !== "string") continue;
107228
+ result.set(commitPreparationRecordKey({ recordKind, recordId }), record3);
107229
+ }
107230
+ };
107231
+ add("project", [document.project]);
107232
+ add("member", document.members ?? []);
107233
+ add("class", document.classes ?? []);
107234
+ add("constructor", document.constructors ?? []);
107235
+ add("variant", document.variants ?? []);
107236
+ add("variant-folder", document.variantFolders ?? []);
107237
+ add("enum", document.enums ?? []);
107238
+ add("interface", document.interfaces ?? []);
107239
+ add("internal-record-relation", document.internalRecordRelations ?? []);
107240
+ add("project-file", document.projectFiles ?? []);
107241
+ add("dialogue", document.dialogueRecords ?? document.dialogues ?? []);
107242
+ add("dialogue-node", document.dialogueNodes ?? []);
107243
+ add("dialogue-group", document.dialogueGroups ?? []);
107244
+ add("priority-group", document.priorityGroups ?? []);
107245
+ add("unity-texture-template", document.textureTemplates ?? []);
107246
+ add("unity-audio-clip-template", document.audioClipTemplates ?? []);
107247
+ if (document.localizationConfig !== null) {
107248
+ add("localization-config", [document.localizationConfig]);
107249
+ }
107250
+ add("localization-status", document.localizationStatuses ?? []);
107251
+ add("localized-text", document.localizedTexts ?? []);
107252
+ add("migration", document.migrations ?? []);
107253
+ add("value", document.values ?? []);
107254
+ return result;
107255
+ }
107256
+ function collectStoredRecordIds(value) {
107257
+ const result = /* @__PURE__ */ new Set();
107258
+ const visit = (candidate) => {
107259
+ if (typeof candidate === "string") {
107260
+ if (STORED_RECORD_ID_PATTERN.test(candidate)) result.add(candidate);
107261
+ return;
107262
+ }
107263
+ if (Array.isArray(candidate)) {
107264
+ for (const entry of candidate) visit(entry);
107265
+ return;
107266
+ }
107267
+ if (candidate === null || typeof candidate !== "object") return;
107268
+ for (const entry of Object.values(candidate)) visit(entry);
107269
+ };
107270
+ visit(value);
107271
+ return result;
107272
+ }
107273
+ function containsInitializerSource(value) {
107274
+ if (Array.isArray(value)) return value.some(containsInitializerSource);
107275
+ if (value === null || typeof value !== "object") return false;
107276
+ const record3 = value;
107277
+ if (record3.init !== null && typeof record3.init === "object" && typeof Reflect.get(record3.init, "code") === "string") {
107278
+ return true;
107279
+ }
107280
+ return Object.values(record3).some(containsInitializerSource);
107281
+ }
107282
+ function compareRecordKeys(left, right) {
107283
+ return commitPreparationRecordKey(left).localeCompare(
107284
+ commitPreparationRecordKey(right)
107285
+ );
107286
+ }
107287
+ var COMMIT_PREPARATION_SCOPE_RANGE_ROW_LIMIT, COMMIT_PREPARATION_SCOPE_POSTING_ROW_LIMIT, COMMIT_PREPARATION_SCOPE_SOURCE_ONLY_ROW_LIMIT, STORED_RECORD_ID_PATTERN;
107288
+ var init_project_commit_preparation_scoped_loader = __esm({
107289
+ "../src/database/project-commit-preparation-scoped-loader.ts"() {
107290
+ "use strict";
107291
+ init_member_kind_enum();
107292
+ init_members();
107293
+ init_inheritance();
107294
+ init_core();
107295
+ init_member_value_id();
107296
+ init_member_kinds();
107297
+ init_packed_value_encoding();
107298
+ init_variants2();
107299
+ init_project_snapshot_derived_edges();
107300
+ init_neo_script_recompile_scope();
107301
+ init_constructor_argument_ownership();
107302
+ init_commit_preparation_scope_planner();
107303
+ init_commit_preparation_animation_scope();
107304
+ COMMIT_PREPARATION_SCOPE_RANGE_ROW_LIMIT = 4096;
107305
+ COMMIT_PREPARATION_SCOPE_POSTING_ROW_LIMIT = 64;
107306
+ COMMIT_PREPARATION_SCOPE_SOURCE_ONLY_ROW_LIMIT = 64;
107307
+ STORED_RECORD_ID_PATTERN = /^(?:system_)?[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu;
107308
+ }
107309
+ });
107310
+
105702
107311
  // src/project-source/server-preparation-preflight.ts
105703
107312
  function assertServerPreparationSucceeds(args) {
105704
107313
  for (const change of args.changes) {
@@ -105712,6 +107321,7 @@ function assertServerPreparationSucceeds(args) {
105712
107321
  });
105713
107322
  if (refusal !== null) throw new ServerPreparationPreflightError(refusal);
105714
107323
  }
107324
+ assertDerivedEdgeCompatibility(args.workspace);
105715
107325
  try {
105716
107326
  const prepared = prepareServerPreparationChanges(args);
105717
107327
  if (args.localInitializerMaterialization !== void 0) {
@@ -105725,6 +107335,42 @@ function assertServerPreparationSucceeds(args) {
105725
107335
  throw locateBodyCompileFailure(error, args.sourceByRecord);
105726
107336
  }
105727
107337
  }
107338
+ function assertDerivedEdgeCompatibility(workspace) {
107339
+ const localVersion = PROJECT_SNAPSHOT_DERIVED_EDGE_EXTRACTOR_VERSION;
107340
+ const serverVersion = workspace.state.derivedEdgeVersion;
107341
+ if (serverVersion === void 0) {
107342
+ throw new DerivedEdgeCompatibilityError(
107343
+ "workspace-metadata-missing",
107344
+ localVersion,
107345
+ serverVersion,
107346
+ "Dry-run server rehearsal requires derived-edge compatibility metadata. Run `neo pull` with this CLI, then retry."
107347
+ );
107348
+ }
107349
+ if (serverVersion === null) {
107350
+ throw new DerivedEdgeCompatibilityError(
107351
+ "watermark-missing",
107352
+ localVersion,
107353
+ serverVersion,
107354
+ `Project "${workspace.config.projectId}" has no derived-edge watermark. Run \`neo pull\` and retry. If this persists, repair the project's derived edge index.`
107355
+ );
107356
+ }
107357
+ if (serverVersion > localVersion) {
107358
+ throw new DerivedEdgeCompatibilityError(
107359
+ "cli-stale",
107360
+ localVersion,
107361
+ serverVersion,
107362
+ `This CLI uses derived-edge extractor v${localVersion}, but project "${workspace.config.projectId}" requires v${serverVersion}. Upgrade @neocompose/cli, run \`neo pull\`, then retry.`
107363
+ );
107364
+ }
107365
+ if (serverVersion < localVersion) {
107366
+ throw new DerivedEdgeCompatibilityError(
107367
+ "server-stale",
107368
+ localVersion,
107369
+ serverVersion,
107370
+ `This CLI uses derived-edge extractor v${localVersion}, but project "${workspace.config.projectId}" reports v${serverVersion}. Run \`neo pull\` and retry. If this persists, update the server and repair the project's derived edge index.`
107371
+ );
107372
+ }
107373
+ }
105728
107374
  function assertInitializerMaterializationParity(local, prepared) {
105729
107375
  const rowsById = /* @__PURE__ */ new Map();
105730
107376
  const createdByRoot = /* @__PURE__ */ new Map();
@@ -105796,9 +107442,27 @@ function locateBodyCompileFailure(error, sourceByRecord) {
105796
107442
  if (source === void 0) return error;
105797
107443
  return new Error(`${source.file}:${source.line} \u2014 ${error.message}`);
105798
107444
  }
107445
+ function prepareWithScopedSafetyValve(args) {
107446
+ try {
107447
+ const scoped = args.prepareScoped();
107448
+ if (scoped !== null) {
107449
+ args.validate(scoped);
107450
+ return scoped;
107451
+ }
107452
+ } catch {
107453
+ }
107454
+ const full = args.prepareFull();
107455
+ args.validate(full);
107456
+ return full;
107457
+ }
105799
107458
  function prepareServerPreparationChanges(args) {
107459
+ const serverTimestamp = args.serverTimestamp ?? Date.now();
105800
107460
  const rawDocument = pulledProjectDocumentRaw(args.workspace);
105801
- const document = readProjectDocument(rawDocument);
107461
+ const document = withReplayValueIdFactory(
107462
+ withStoredValueBase(readProjectDocument(rawDocument)),
107463
+ args.createValueId,
107464
+ serverTimestamp
107465
+ );
105802
107466
  const contentHashHeads = readProjectDocumentContentHashHeads(rawDocument);
105803
107467
  const changes = args.changes.map((change) => ({
105804
107468
  ...change,
@@ -105809,9 +107473,44 @@ function prepareServerPreparationChanges(args) {
105809
107473
  }));
105810
107474
  const trustedChanges = stampServerOwnedSourceCommitMetadata({
105811
107475
  rawDocument,
105812
- changes
107476
+ changes,
107477
+ timestamp: serverTimestamp
105813
107478
  });
105814
- const prepared = prepareServerOwnedSchemaCommit({
107479
+ const placedRecords = () => {
107480
+ const canonicalPlacementByValueId = projectValueHeadPlacementGraph({
107481
+ rootMembers: [
107482
+ { id: document.project.rootAssetsMemberId, label: "Assets" },
107483
+ { id: document.project.rootSaveFileMemberId, label: "Save" },
107484
+ { id: document.project.rootSessionMemberId, label: "Session" }
107485
+ ],
107486
+ variantRoots: (document.variants ?? []).map((variant) => ({
107487
+ variantId: variant.id,
107488
+ valueId: variant.valueId
107489
+ })),
107490
+ members: document.members,
107491
+ classes: document.classes,
107492
+ values: document.values
107493
+ });
107494
+ return withCommitPreparationInMemoryPlacement(
107495
+ Object.values(args.workspace.state.records).map((record3) => {
107496
+ const recordKind = narrowRecordKind(
107497
+ record3.recordKind,
107498
+ `${record3.recordKind}:${record3.recordId}`
107499
+ );
107500
+ const placement = recordKind === "value" ? canonicalPlacementByValueId.get(record3.recordId) : void 0;
107501
+ return {
107502
+ recordKind,
107503
+ recordId: record3.recordId,
107504
+ data: record3.data,
107505
+ ...placement?.parentRecordKind === null || placement?.parentRecordKind === void 0 || placement.parentRecordId === null ? {} : {
107506
+ parentRecordKind: placement.parentRecordKind,
107507
+ parentRecordId: placement.parentRecordId
107508
+ }
107509
+ };
107510
+ })
107511
+ );
107512
+ };
107513
+ const preparationArgs = {
105815
107514
  document,
105816
107515
  contentHashHeads,
105817
107516
  changes: trustedChanges,
@@ -105820,10 +107519,258 @@ function prepareServerPreparationChanges(args) {
105820
107519
  // A CLI push is always a trusted-source commit, so the server always
105821
107520
  // expands read-only source conversions for it.
105822
107521
  expandReadOnlySourceConversions: true,
105823
- forceRecompile: args.forceRecompile
107522
+ forceRecompile: args.forceRecompile,
107523
+ serverTimestamp,
107524
+ createLocalizedTextId: args.createLocalizedTextId
107525
+ };
107526
+ const prepareFull = (discardedScopedAttempt) => {
107527
+ if (discardedScopedAttempt) args.resetReplayIds?.();
107528
+ return prepareServerOwnedSchemaCommit(preparationArgs);
107529
+ };
107530
+ const validate2 = (prepared) => assertProjectVersionWholeGraphWritesValid({ document, changes: prepared });
107531
+ if (args.forceRecompile === true) {
107532
+ const prepared = prepareFull(false);
107533
+ validate2(prepared);
107534
+ return prepared;
107535
+ }
107536
+ return prepareWithScopedSafetyValve({
107537
+ prepareScoped: () => {
107538
+ const records2 = placedRecords();
107539
+ const initialScope = planCommitPreparationInitialScope({
107540
+ pass: COMMIT_PREPARATION_PASS_ORDER[0],
107541
+ document,
107542
+ changes,
107543
+ authoredValueSeeds: args.authoredValueSeeds,
107544
+ rangeLimit: COMMIT_PREPARATION_SCOPE_RANGE_ROW_LIMIT,
107545
+ postingLimit: COMMIT_PREPARATION_SCOPE_POSTING_ROW_LIMIT
107546
+ });
107547
+ if (initialScope.fullContentDimension) return null;
107548
+ const scopeAnswer = readCommitPreparationScopeInMemory({
107549
+ request: initialScope,
107550
+ records: records2,
107551
+ prepared: changes,
107552
+ document
107553
+ });
107554
+ if (scopeAnswer.kind === "fallback") return null;
107555
+ const selectedContentKeys = /* @__PURE__ */ new Set();
107556
+ const descendantRootKeys = /* @__PURE__ */ new Set();
107557
+ const absentExactKeys = /* @__PURE__ */ new Set();
107558
+ absorbInMemoryScopeAnswer(
107559
+ selectedContentKeys,
107560
+ scopeAnswer.value,
107561
+ descendantRootKeys,
107562
+ scopeDescendantKeys(initialScope),
107563
+ scopeDescendantRangeKeys(initialScope),
107564
+ absentExactKeys
107565
+ );
107566
+ const initialClosed = closeInMemoryLoadedScope({
107567
+ records: records2,
107568
+ selected: selectedContentKeys,
107569
+ descendantRoots: descendantRootKeys,
107570
+ absentExactKeys,
107571
+ prepared: changes,
107572
+ document,
107573
+ pass: COMMIT_PREPARATION_PASS_ORDER[0]
107574
+ });
107575
+ if (!initialClosed) return null;
107576
+ const scopedDocument = selectPreparationContentRows(
107577
+ document,
107578
+ selectedContentKeys
107579
+ );
107580
+ const scopedHeads = contentHashHeads.filter(
107581
+ (head) => !COMMIT_PREPARATION_CLI_CONTENT_KINDS.has(head.recordKind) || selectedContentKeys.has(`${head.recordKind}:${head.recordId}`)
107582
+ );
107583
+ const passes = prepareServerOwnedSchemaCommitPasses({
107584
+ ...preparationArgs,
107585
+ document: scopedDocument,
107586
+ contentHashHeads: scopedHeads
107587
+ });
107588
+ for (; ; ) {
107589
+ const step = passes.next();
107590
+ if (step.done) return step.value;
107591
+ const topUpRequest = planCommitPreparationInitialScope({
107592
+ pass: nextCommitPreparationPass(step.value.pass) ?? step.value.pass,
107593
+ document: scopedDocument,
107594
+ changes: step.value.preparedChanges,
107595
+ authoredValueSeeds: args.authoredValueSeeds,
107596
+ rangeLimit: COMMIT_PREPARATION_SCOPE_RANGE_ROW_LIMIT,
107597
+ postingLimit: COMMIT_PREPARATION_SCOPE_POSTING_ROW_LIMIT
107598
+ });
107599
+ if (topUpRequest.fullContentDimension) return null;
107600
+ const topUpAnswer = readCommitPreparationScopeInMemory({
107601
+ request: topUpRequest,
107602
+ records: records2,
107603
+ prepared: step.value.preparedChanges,
107604
+ document
107605
+ });
107606
+ if (topUpAnswer.kind === "fallback") return null;
107607
+ absorbInMemoryScopeAnswer(
107608
+ selectedContentKeys,
107609
+ topUpAnswer.value,
107610
+ descendantRootKeys,
107611
+ scopeDescendantKeys(topUpRequest),
107612
+ scopeDescendantRangeKeys(topUpRequest),
107613
+ absentExactKeys
107614
+ );
107615
+ for (const change of step.value.preparedChanges) {
107616
+ if (change.operation === "delete" || change.deleted === true)
107617
+ continue;
107618
+ descendantRootKeys.add(`${change.recordKind}:${change.recordId}`);
107619
+ }
107620
+ if (!closeInMemoryLoadedScope({
107621
+ records: records2,
107622
+ selected: selectedContentKeys,
107623
+ descendantRoots: descendantRootKeys,
107624
+ absentExactKeys,
107625
+ prepared: step.value.preparedChanges,
107626
+ document,
107627
+ pass: nextCommitPreparationPass(step.value.pass) ?? step.value.pass
107628
+ })) {
107629
+ return null;
107630
+ }
107631
+ Object.assign(
107632
+ scopedDocument,
107633
+ selectPreparationContentRows(document, selectedContentKeys)
107634
+ );
107635
+ scopedHeads.splice(
107636
+ 0,
107637
+ scopedHeads.length,
107638
+ ...contentHashHeads.filter(
107639
+ (head) => !COMMIT_PREPARATION_CLI_CONTENT_KINDS.has(head.recordKind) || selectedContentKeys.has(`${head.recordKind}:${head.recordId}`)
107640
+ )
107641
+ );
107642
+ }
107643
+ },
107644
+ prepareFull: () => prepareFull(true),
107645
+ validate: validate2
105824
107646
  });
105825
- assertProjectVersionWholeGraphWritesValid({ document, changes: prepared });
105826
- return prepared;
107647
+ }
107648
+ function withReplayValueIdFactory(document, createValueId, timestamp) {
107649
+ if (createValueId === void 0) return document;
107650
+ return Object.assign(document, {
107651
+ createValueRow: (projectId, body) => {
107652
+ const value = buildNewValue(projectId, body, timestamp);
107653
+ value.id = createValueId();
107654
+ return value;
107655
+ }
107656
+ });
107657
+ }
107658
+ function absorbInMemoryScopeAnswer(selected, answer, descendantRoots, descendantExactKeys = /* @__PURE__ */ new Set(), descendantRangeKeys = /* @__PURE__ */ new Set(), absentExactKeys) {
107659
+ for (const [key, state] of answer.exactStates) {
107660
+ if (state !== "live") {
107661
+ absentExactKeys?.add(key);
107662
+ continue;
107663
+ }
107664
+ const selectedKey = answer.packedRootKeyByExactKey.get(key) ?? key;
107665
+ selected.add(selectedKey);
107666
+ if (descendantExactKeys.has(key)) descendantRoots?.add(selectedKey);
107667
+ }
107668
+ for (const [requestKey, keys] of answer.rangeRecordKeys) {
107669
+ for (const key of keys) {
107670
+ selected.add(key);
107671
+ if (descendantRangeKeys.has(requestKey)) descendantRoots?.add(key);
107672
+ }
107673
+ }
107674
+ for (const keys of answer.postingSourceKeys.values()) {
107675
+ for (const key of keys) {
107676
+ selected.add(key);
107677
+ }
107678
+ }
107679
+ }
107680
+ function closeInMemoryLoadedScope(args) {
107681
+ const animationSchema = commitPreparationAnimationSchema(args.document);
107682
+ for (; ; ) {
107683
+ const closureRecords = args.records.filter(
107684
+ (record3) => args.selected.has(`${record3.recordKind}:${record3.recordId}`)
107685
+ ).map((record3) => ({
107686
+ ...record3,
107687
+ includeDescendants: args.descendantRoots.has(
107688
+ `${record3.recordKind}:${record3.recordId}`
107689
+ )
107690
+ }));
107691
+ const request = planCommitPreparationLoadedClosureScope({
107692
+ pass: args.pass,
107693
+ records: closureRecords,
107694
+ rangeLimit: COMMIT_PREPARATION_SCOPE_RANGE_ROW_LIMIT,
107695
+ postingLimit: COMMIT_PREPARATION_SCOPE_POSTING_ROW_LIMIT,
107696
+ animationSchema
107697
+ });
107698
+ const answer = readCommitPreparationScopeInMemory({
107699
+ request,
107700
+ records: args.records,
107701
+ prepared: args.prepared,
107702
+ document: args.document
107703
+ });
107704
+ if (answer.kind === "fallback") return false;
107705
+ const priorSelectedSize = args.selected.size;
107706
+ const priorDescendantSize = args.descendantRoots.size;
107707
+ absorbInMemoryScopeAnswer(
107708
+ args.selected,
107709
+ answer.value,
107710
+ args.descendantRoots,
107711
+ scopeDescendantKeys(request),
107712
+ scopeDescendantRangeKeys(request),
107713
+ args.absentExactKeys
107714
+ );
107715
+ if (args.selected.size === priorSelectedSize && args.descendantRoots.size === priorDescendantSize) {
107716
+ return selectedAncestorPathsIntact(
107717
+ args.records,
107718
+ args.selected,
107719
+ args.absentExactKeys
107720
+ );
107721
+ }
107722
+ }
107723
+ }
107724
+ function selectedAncestorPathsIntact(records2, selected, absentExactKeys) {
107725
+ if (absentExactKeys.size === 0) return true;
107726
+ const selectedRecords = records2.filter(
107727
+ (record3) => selected.has(`${record3.recordKind}:${record3.recordId}`)
107728
+ );
107729
+ const packedRootIdByChildId = commitPreparationPackedRootIds(selectedRecords);
107730
+ for (const record3 of selectedRecords) {
107731
+ if (record3.recordKind !== "value") continue;
107732
+ if (record3.parentRecordKind !== "value") continue;
107733
+ const parentId = record3.parentRecordId;
107734
+ if (typeof parentId !== "string") continue;
107735
+ if (selected.has(`value:${parentId}`)) continue;
107736
+ if (packedRootIdByChildId.has(parentId)) continue;
107737
+ if (absentExactKeys.has(`value:${parentId}`)) return false;
107738
+ }
107739
+ return true;
107740
+ }
107741
+ function scopeDescendantRangeKeys(scope) {
107742
+ return new Set(
107743
+ scope.ranges.filter(
107744
+ (range2) => range2.rangeKind === "children" || range2.rangeKind === "container-members"
107745
+ ).map((range2) => `${range2.rangeKind}:${range2.targetKey}`)
107746
+ );
107747
+ }
107748
+ function scopeDescendantKeys(scope) {
107749
+ return new Set(
107750
+ (scope.descendantRecords ?? []).map(
107751
+ (record3) => `${record3.recordKind}:${record3.recordId}`
107752
+ )
107753
+ );
107754
+ }
107755
+ function selectPreparationContentRows(document, selected) {
107756
+ const physicalValues = (document.physicalValues ?? document.values).filter(
107757
+ (row) => selected.has(`value:${row.id}`)
107758
+ );
107759
+ const values = expandPackedValueRows(physicalValues);
107760
+ return {
107761
+ ...document,
107762
+ values: values === physicalValues ? physicalValues : [...values],
107763
+ physicalValues,
107764
+ dialogueNodes: (document.dialogueNodes ?? []).filter(
107765
+ (row) => selected.has(`dialogue-node:${row.id}`)
107766
+ ),
107767
+ migrations: (document.migrations ?? []).filter(
107768
+ (row) => selected.has(`migration:${row.id}`)
107769
+ ),
107770
+ localizedTexts: (document.localizedTexts ?? []).filter(
107771
+ (row) => selected.has(`localized-text:${row.id}`)
107772
+ )
107773
+ };
105827
107774
  }
105828
107775
  function pulledProjectDocumentRaw(workspace) {
105829
107776
  const records2 = [];
@@ -105900,7 +107847,7 @@ function syntheticVersionMetadata(workspace) {
105900
107847
  releaseChannels: []
105901
107848
  };
105902
107849
  }
105903
- var ServerPreparationPreflightError;
107850
+ var ServerPreparationPreflightError, DerivedEdgeCompatibilityError, COMMIT_PREPARATION_CLI_CONTENT_KINDS;
105904
107851
  var init_server_preparation_preflight = __esm({
105905
107852
  "src/project-source/server-preparation-preflight.ts"() {
105906
107853
  "use strict";
@@ -105910,13 +107857,33 @@ var init_server_preparation_preflight = __esm({
105910
107857
  init_project_version_whole_graph_validation();
105911
107858
  init_projectRecordBuckets();
105912
107859
  init_compile_ns_property();
107860
+ init_valueHeadPlacementGraph();
105913
107861
  init_projection();
107862
+ init_project_snapshot_derived_edges();
107863
+ init_project_commit_preparation_scoped_loader();
107864
+ init_packed_value_encoding();
107865
+ init_commit_preparation_animation_scope();
107866
+ init_commit_preparation_scope_planner();
107867
+ init_build_default_member_value();
105914
107868
  ServerPreparationPreflightError = class extends Error {
105915
107869
  constructor(message) {
105916
107870
  super(message);
105917
107871
  this.name = "ServerPreparationPreflightError";
105918
107872
  }
105919
107873
  };
107874
+ DerivedEdgeCompatibilityError = class extends ServerPreparationPreflightError {
107875
+ constructor(reason, localVersion, serverVersion, message) {
107876
+ super(message);
107877
+ this.reason = reason;
107878
+ this.localVersion = localVersion;
107879
+ this.serverVersion = serverVersion;
107880
+ this.name = "DerivedEdgeCompatibilityError";
107881
+ }
107882
+ reason;
107883
+ localVersion;
107884
+ serverVersion;
107885
+ };
107886
+ COMMIT_PREPARATION_CLI_CONTENT_KINDS = /* @__PURE__ */ new Set(["value", "dialogue-node", "localized-text", "migration"]);
105920
107887
  }
105921
107888
  });
105922
107889
 
@@ -115325,7 +117292,8 @@ async function queryProjectDocumentSyncMarker(workspace, convex) {
115325
117292
  return {
115326
117293
  revision: revisionValue,
115327
117294
  headTransactionId: signal?.transactionId ?? null,
115328
- headTransactionHash: signal?.transactionHash ?? null
117295
+ headTransactionHash: signal?.transactionHash ?? null,
117296
+ derivedEdgeVersion: signal?.derivedEdgeVersion ?? null
115329
117297
  };
115330
117298
  }
115331
117299
  async function fetchProjectDocumentDelta(workspace, cursor) {
@@ -115334,7 +117302,8 @@ async function fetchProjectDocumentDelta(workspace, cursor) {
115334
117302
  if (marker.revision.versionsStamp !== cursor.versionsStamp) {
115335
117303
  return {
115336
117304
  fullResync: true,
115337
- headTransactionHash: marker.headTransactionHash
117305
+ headTransactionHash: marker.headTransactionHash,
117306
+ derivedEdgeVersion: marker.derivedEdgeVersion
115338
117307
  };
115339
117308
  }
115340
117309
  if (marker.headTransactionId === marker.revision.latestTransactionId && marker.headTransactionHash === workspace.state.headTransactionHash) {
@@ -115343,7 +117312,8 @@ async function fetchProjectDocumentDelta(workspace, cursor) {
115343
117312
  document: projectDocumentFromWorkspaceState(workspace.state, cursor),
115344
117313
  changedKeys: /* @__PURE__ */ new Set(),
115345
117314
  cursor,
115346
- headTransactionHash: marker.headTransactionHash
117315
+ headTransactionHash: marker.headTransactionHash,
117316
+ derivedEdgeVersion: marker.derivedEdgeVersion
115347
117317
  };
115348
117318
  }
115349
117319
  const result = await convex.query(api2.projectDocuments.getRecordsSince, {
@@ -115355,7 +117325,8 @@ async function fetchProjectDocumentDelta(workspace, cursor) {
115355
117325
  if (result.fullResync) {
115356
117326
  return {
115357
117327
  fullResync: true,
115358
- headTransactionHash: marker.headTransactionHash
117328
+ headTransactionHash: marker.headTransactionHash,
117329
+ derivedEdgeVersion: marker.derivedEdgeVersion
115359
117330
  };
115360
117331
  }
115361
117332
  const document = projectDocumentFromWorkspaceState(workspace.state, cursor);
@@ -115404,7 +117375,8 @@ async function fetchProjectDocumentDelta(workspace, cursor) {
115404
117375
  document: projectDocumentWithRevision(document, nextCursor),
115405
117376
  changedKeys,
115406
117377
  cursor: nextCursor,
115407
- headTransactionHash: marker.headTransactionHash
117378
+ headTransactionHash: marker.headTransactionHash,
117379
+ derivedEdgeVersion: marker.derivedEdgeVersion
115408
117380
  };
115409
117381
  }
115410
117382
  function projectDocumentFromWorkspaceState(state, cursor) {
@@ -116385,6 +118357,7 @@ ${blockingErrors.map((error) => ` ${error.message}`).join("\n")}`
116385
118357
  let changedRecordKeys = null;
116386
118358
  let nextCursor = null;
116387
118359
  let observedHeadTransactionHash;
118360
+ let observedDerivedEdgeVersion;
116388
118361
  let document = null;
116389
118362
  if (!destructive && hasBaseline) {
116390
118363
  progress.update("Checking remote changes\u2026");
@@ -116392,6 +118365,7 @@ ${blockingErrors.map((error) => ` ${error.message}`).join("\n")}`
116392
118365
  if (cursor !== void 0) {
116393
118366
  const delta = await fetchProjectDocumentDelta(workspace, cursor);
116394
118367
  observedHeadTransactionHash = delta.headTransactionHash;
118368
+ observedDerivedEdgeVersion = delta.derivedEdgeVersion;
116395
118369
  if (!delta.fullResync) {
116396
118370
  document = delta.document;
116397
118371
  changedRecordKeys = delta.changedKeys;
@@ -116402,11 +118376,13 @@ ${blockingErrors.map((error) => ` ${error.message}`).join("\n")}`
116402
118376
  delta.cursor
116403
118377
  );
116404
118378
  const headChanged = workspace.state.headTransactionHash !== delta.headTransactionHash;
116405
- if (cursorChanged || headChanged) {
118379
+ const derivedEdgeVersionChanged = workspace.state.derivedEdgeVersion !== delta.derivedEdgeVersion;
118380
+ if (cursorChanged || headChanged || derivedEdgeVersionChanged) {
116406
118381
  workspace.state.documentRevisionCursor = mutableCursor(
116407
118382
  delta.cursor
116408
118383
  );
116409
118384
  workspace.state.headTransactionHash = delta.headTransactionHash;
118385
+ workspace.state.derivedEdgeVersion = delta.derivedEdgeVersion;
116410
118386
  writeWorkspaceState(workspace.root, workspace.state);
116411
118387
  }
116412
118388
  progress.succeed("Already up to date.");
@@ -116416,9 +118392,11 @@ ${blockingErrors.map((error) => ` ${error.message}`).join("\n")}`
116416
118392
  } else if (!options.regenerateSourceNames && workspace.state.headTransactionHash !== void 0) {
116417
118393
  const marker = await fetchProjectDocumentSyncMarker(workspace);
116418
118394
  observedHeadTransactionHash = marker.headTransactionHash;
118395
+ observedDerivedEdgeVersion = marker.derivedEdgeVersion;
116419
118396
  if (marker.headTransactionId === marker.revision.latestTransactionId && marker.headTransactionHash === workspace.state.headTransactionHash) {
116420
118397
  const seededCursor = cursorFromRevision(marker.revision);
116421
118398
  workspace.state.documentRevisionCursor = mutableCursor(seededCursor);
118399
+ workspace.state.derivedEdgeVersion = marker.derivedEdgeVersion;
116422
118400
  writeWorkspaceState(workspace.root, workspace.state);
116423
118401
  progress.succeed("Already up to date.");
116424
118402
  return;
@@ -116557,6 +118535,7 @@ ${blockingErrors.map((error) => ` ${error.message}`).join("\n")}`
116557
118535
  changedRecordKeys,
116558
118536
  nextCursor,
116559
118537
  observedHeadTransactionHash,
118538
+ observedDerivedEdgeVersion,
116560
118539
  progress
116561
118540
  });
116562
118541
  }
@@ -116591,8 +118570,10 @@ async function runResetPull(workspace) {
116591
118570
  versionId: workspace.config.versionId
116592
118571
  });
116593
118572
  workspace.state.headTransactionHash = document.revision !== void 0 && signal?.transactionId === document.revision.latestTransactionId ? signal.transactionHash : null;
118573
+ workspace.state.derivedEdgeVersion = signal?.derivedEdgeVersion ?? null;
116594
118574
  } catch {
116595
118575
  workspace.state.headTransactionHash = null;
118576
+ delete workspace.state.derivedEdgeVersion;
116596
118577
  }
116597
118578
  if (document.revision !== void 0) {
116598
118579
  workspace.state.documentRevisionCursor = mutableCursor(
@@ -116624,6 +118605,7 @@ async function finishFormat4Pull(args) {
116624
118605
  changedRecordKeys,
116625
118606
  nextCursor,
116626
118607
  observedHeadTransactionHash,
118608
+ observedDerivedEdgeVersion,
116627
118609
  progress
116628
118610
  } = args;
116629
118611
  if (changedRecordKeys !== null && !regenerateSourceNames && conflictCount === 0 && localStatus !== null && !deltaRequiresSourceProjectionV4({
@@ -116639,6 +118621,7 @@ async function finishFormat4Pull(args) {
116639
118621
  changedRecordKeys,
116640
118622
  nextCursor,
116641
118623
  observedHeadTransactionHash,
118624
+ observedDerivedEdgeVersion,
116642
118625
  progress
116643
118626
  });
116644
118627
  return;
@@ -116823,10 +118806,15 @@ async function finishFormat4Pull(args) {
116823
118806
  versionId: workspace.config.versionId
116824
118807
  });
116825
118808
  workspace.state.headTransactionHash = document.revision !== void 0 && signal?.transactionId === document.revision.latestTransactionId ? signal.transactionHash : null;
118809
+ workspace.state.derivedEdgeVersion = signal?.derivedEdgeVersion ?? null;
116826
118810
  } catch {
116827
118811
  workspace.state.headTransactionHash = null;
118812
+ delete workspace.state.derivedEdgeVersion;
116828
118813
  }
116829
118814
  }
118815
+ if (observedDerivedEdgeVersion !== void 0) {
118816
+ workspace.state.derivedEdgeVersion = observedDerivedEdgeVersion;
118817
+ }
116830
118818
  writeWorkspaceState(workspace.root, workspace.state);
116831
118819
  if (conflictCount === 0) {
116832
118820
  writeProjectSourceAnalysisCacheV4(workspace.root, localResult.analysis);
@@ -116986,6 +118974,9 @@ function finishRecordOnlyDeltaPull(args) {
116986
118974
  if (args.observedHeadTransactionHash !== void 0) {
116987
118975
  args.workspace.state.headTransactionHash = args.observedHeadTransactionHash;
116988
118976
  }
118977
+ if (args.observedDerivedEdgeVersion !== void 0) {
118978
+ args.workspace.state.derivedEdgeVersion = args.observedDerivedEdgeVersion;
118979
+ }
116989
118980
  writeWorkspaceState(args.workspace.root, args.workspace.state);
116990
118981
  args.progress.succeed(
116991
118982
  `Pulled ${args.changedRecordKeys.size} changed record(s) \u2014 0 file(s) updated \u2014 0 removed.`
@@ -120437,7 +122428,7 @@ function normalizeSourceFiles(inputFiles) {
120437
122428
  return files;
120438
122429
  }
120439
122430
  function readSourceFile(value, index) {
120440
- const record3 = asRecord3(value, `Project source identity file ${index}`);
122431
+ const record3 = asRecord4(value, `Project source identity file ${index}`);
120441
122432
  assertExactKeys(record3, ["path", "kind", "content"]);
120442
122433
  if (typeof record3.path !== "string" || !isSafeSourcePath(record3.path)) {
120443
122434
  throw new Error(
@@ -120472,7 +122463,7 @@ function isSafeSourcePath(path) {
120472
122463
  }
120473
122464
  return neoProjectSourceKind(path) !== null;
120474
122465
  }
120475
- function asRecord3(value, label) {
122466
+ function asRecord4(value, label) {
120476
122467
  if (typeof value !== "object" || value === null || Array.isArray(value)) {
120477
122468
  throw new Error(`${label} must be an object.`);
120478
122469
  }
@@ -120674,6 +122665,17 @@ var init_push_hook = __esm({
120674
122665
  // src/project-source/project-file-push.ts
120675
122666
  import { basename as basename2, join as join13 } from "node:path";
120676
122667
  import { readFileSync as readFileSync14 } from "node:fs";
122668
+ import { randomUUID as randomUUID2 } from "node:crypto";
122669
+ async function cleanupRejectedProjectFilePushesV4(args) {
122670
+ if (args.stagedUploadSessionId === null) return;
122671
+ try {
122672
+ await args.client.post(
122673
+ versionPath(args.workspace, "files/cleanup-staged-upload"),
122674
+ { stagedUploadSessionId: args.stagedUploadSessionId }
122675
+ );
122676
+ } catch {
122677
+ }
122678
+ }
120677
122679
  function ensureProjectFileBinaryChangesV4(args) {
120678
122680
  for (const binary of args.binaryChanges) {
120679
122681
  if (binary.action !== "upload") continue;
@@ -120753,7 +122755,7 @@ async function stageProjectFilePushesV4(args) {
120753
122755
  assignedIds: args.assignedIds
120754
122756
  });
120755
122757
  const staged = [];
120756
- const cleanupKeys = [];
122758
+ const stagedUploadSessionId = args.stagedUploadSessionId ?? randomUUID2();
120757
122759
  const put = args.put ?? fetch;
120758
122760
  const interruptController = new AbortController();
120759
122761
  const interrupt = () => interruptController.abort(new ProjectFilePushCancelledError());
@@ -120770,11 +122772,8 @@ async function stageProjectFilePushesV4(args) {
120770
122772
  });
120771
122773
  report();
120772
122774
  try {
120773
- for (let offset = 0; offset < prepared.length; offset += PROJECT_FILE_UPLOAD_BATCH_SIZE) {
120774
- const batch = prepared.slice(
120775
- offset,
120776
- offset + PROJECT_FILE_UPLOAD_BATCH_SIZE
120777
- );
122775
+ for (let offset = 0; offset < prepared.length; offset += PRESIGN_BATCH_SIZE) {
122776
+ const batch = prepared.slice(offset, offset + PRESIGN_BATCH_SIZE);
120778
122777
  const presign = await postWithTimeout(
120779
122778
  args.client,
120780
122779
  versionPath(args.workspace, "upload"),
@@ -120782,6 +122781,7 @@ async function stageProjectFilePushesV4(args) {
120782
122781
  route: "projectFile",
120783
122782
  metadata: {
120784
122783
  deferredSourceCommit: true,
122784
+ stagedUploadSessionId,
120785
122785
  uploads: batch.map((file) => ({
120786
122786
  uploadToken: file.uploadToken,
120787
122787
  projectFileId: file.recordId,
@@ -120799,12 +122799,11 @@ async function stageProjectFilePushesV4(args) {
120799
122799
  signal
120800
122800
  );
120801
122801
  const entries = readPresignEntries(presign, batch);
120802
- for (const entry of entries) cleanupKeys.push(entry.storageKey);
120803
122802
  const batchController = new AbortController();
120804
122803
  try {
120805
122804
  await mapWithConcurrency(entries, UPLOAD_CONCURRENCY, async (entry) => {
120806
122805
  try {
120807
- await putWithRetry(
122806
+ await uploadWithRetry(
120808
122807
  put,
120809
122808
  entry,
120810
122809
  combineSignals(signal, batchController.signal)
@@ -120849,15 +122848,11 @@ async function stageProjectFilePushesV4(args) {
120849
122848
  return result;
120850
122849
  });
120851
122850
  } catch (error) {
120852
- if (cleanupKeys.length > 0) {
120853
- try {
120854
- await args.client.post(
120855
- versionPath(args.workspace, "files/cleanup-staged-upload"),
120856
- { storageKeys: cleanupKeys }
120857
- );
120858
- } catch {
120859
- }
120860
- }
122851
+ await cleanupRejectedProjectFilePushesV4({
122852
+ workspace: args.workspace,
122853
+ client: args.client,
122854
+ stagedUploadSessionId
122855
+ });
120861
122856
  if (interruptController.signal.aborted || args.signal?.aborted === true) {
120862
122857
  throw new ProjectFilePushCancelledError();
120863
122858
  }
@@ -120867,7 +122862,8 @@ async function stageProjectFilePushesV4(args) {
120867
122862
  }
120868
122863
  }
120869
122864
  function readPresignEntries(presign, batch) {
120870
- const entries = Array.isArray(presign.files) ? presign.files.filter(isObjectRecord2) : [];
122865
+ const multipart = isObjectRecord2(presign.multipart) ? presign.multipart : null;
122866
+ const entries = Array.isArray(multipart?.files) ? multipart.files.filter(isObjectRecord2) : Array.isArray(presign.files) ? presign.files.filter(isObjectRecord2) : [];
120871
122867
  return batch.map((file) => {
120872
122868
  const entry = entries.find((candidate) => {
120873
122869
  const info = isObjectRecord2(candidate.file) ? candidate.file : {};
@@ -120875,21 +122871,62 @@ function readPresignEntries(presign, batch) {
120875
122871
  });
120876
122872
  const fileInfo = isObjectRecord2(entry?.file) ? entry.file : {};
120877
122873
  const objectInfo = isObjectRecord2(fileInfo.objectInfo) ? fileInfo.objectInfo : {};
120878
- if (typeof entry?.signedUrl !== "string") {
122874
+ if (typeof objectInfo.key !== "string") {
120879
122875
  throw new Error(
120880
- `Upload presign response is missing signedUrl for ${file.name}.`
122876
+ `Upload presign response is missing a storage key for ${file.name}.`
120881
122877
  );
120882
122878
  }
120883
- if (typeof objectInfo.key !== "string") {
122879
+ if (multipart === null) {
122880
+ if (typeof entry?.signedUrl !== "string") {
122881
+ throw new Error(
122882
+ `Upload presign response is missing signedUrl for ${file.name}.`
122883
+ );
122884
+ }
122885
+ return {
122886
+ protocol: "single-put",
122887
+ file,
122888
+ signedUrl: entry.signedUrl,
122889
+ storageKey: objectInfo.key,
122890
+ headers: uploadHeaders(entry, objectInfo, file.mimeType)
122891
+ };
122892
+ }
122893
+ if (typeof entry?.completeSignedUrl !== "string") {
120884
122894
  throw new Error(
120885
- `Upload presign response is missing a storage key for ${file.name}.`
122895
+ `Multipart presign response is missing completeSignedUrl for ${file.name}.`
122896
+ );
122897
+ }
122898
+ if (!Array.isArray(entry.parts) || entry.parts.length === 0) {
122899
+ throw new Error(
122900
+ `Multipart presign response is missing parts for ${file.name}.`
122901
+ );
122902
+ }
122903
+ let offset = 0;
122904
+ const parts = entry.parts.map((candidate, index) => {
122905
+ if (!isObjectRecord2(candidate) || candidate.partNumber !== index + 1 || typeof candidate.size !== "number" || !Number.isSafeInteger(candidate.size) || candidate.size <= 0 || typeof candidate.signedUrl !== "string") {
122906
+ throw new Error(
122907
+ `Multipart presign response has invalid part ${index + 1} for ${file.name}.`
122908
+ );
122909
+ }
122910
+ const part = {
122911
+ partNumber: candidate.partNumber,
122912
+ offset,
122913
+ size: candidate.size,
122914
+ signedUrl: candidate.signedUrl
122915
+ };
122916
+ offset += candidate.size;
122917
+ return part;
122918
+ });
122919
+ if (offset !== file.byteLength) {
122920
+ throw new Error(
122921
+ `Multipart presign response covers ${offset}/${file.byteLength} bytes for ${file.name}.`
120886
122922
  );
120887
122923
  }
120888
122924
  return {
122925
+ protocol: "multipart",
120889
122926
  file,
120890
- signedUrl: entry.signedUrl,
120891
122927
  storageKey: objectInfo.key,
120892
- headers: uploadHeaders(entry, objectInfo, file.mimeType)
122928
+ completeSignedUrl: entry.completeSignedUrl,
122929
+ parts
120893
122930
  };
120894
122931
  });
120895
122932
  }
@@ -120908,7 +122945,11 @@ async function postWithTimeout(client, path, body, signal) {
120908
122945
  }
120909
122946
  throw new Error("Upload presign failed after all retry attempts.");
120910
122947
  }
120911
- async function putWithRetry(put, entry, signal) {
122948
+ async function uploadWithRetry(put, entry, signal) {
122949
+ if (entry.protocol === "multipart") {
122950
+ await uploadMultipartWithRetry(put, entry, signal);
122951
+ return;
122952
+ }
120912
122953
  let lastError;
120913
122954
  for (let attempt = 1; attempt <= STORAGE_PUT_ATTEMPTS; attempt += 1) {
120914
122955
  let response;
@@ -120940,6 +122981,83 @@ async function putWithRetry(put, entry, signal) {
120940
122981
  }
120941
122982
  throw lastError instanceof Error ? lastError : new Error(`Storage PUT failed for ${entry.file.name}.`);
120942
122983
  }
122984
+ async function uploadMultipartWithRetry(put, entry, signal) {
122985
+ const uploaded = await mapWithConcurrency(
122986
+ entry.parts,
122987
+ MULTIPART_PART_CONCURRENCY,
122988
+ async (part) => {
122989
+ const body2 = Buffer.from(
122990
+ entry.file.bytes.subarray(part.offset, part.offset + part.size)
122991
+ );
122992
+ const response2 = await requestStorageWithRetry(
122993
+ put,
122994
+ part.signedUrl,
122995
+ { method: "PUT", body: body2 },
122996
+ signal,
122997
+ `multipart part ${part.partNumber}`
122998
+ );
122999
+ const eTag = response2.headers.get("etag");
123000
+ if (eTag === null || eTag.length === 0) {
123001
+ throw new Error(
123002
+ `Multipart upload part ${part.partNumber} for ${entry.file.name} returned no ETag.`
123003
+ );
123004
+ }
123005
+ return { partNumber: part.partNumber, eTag };
123006
+ }
123007
+ );
123008
+ const body = `<CompleteMultipartUpload>${uploaded.sort((left, right) => left.partNumber - right.partNumber).map(
123009
+ ({ partNumber, eTag }) => `<Part><ETag>${escapeXml(eTag)}</ETag><PartNumber>${partNumber}</PartNumber></Part>`
123010
+ ).join("")}</CompleteMultipartUpload>`;
123011
+ const response = await put(entry.completeSignedUrl, {
123012
+ method: "POST",
123013
+ headers: { "content-type": "application/xml" },
123014
+ body,
123015
+ signal: combineSignals(signal, AbortSignal.timeout(STORAGE_PUT_TIMEOUT_MS))
123016
+ });
123017
+ const completion2 = await response.text();
123018
+ if (!response.ok) {
123019
+ throw new Error(
123020
+ `Multipart completion failed (${response.status}): ${completion2}`
123021
+ );
123022
+ }
123023
+ if (completion2.includes("<Error>")) {
123024
+ throw new Error(
123025
+ `Multipart completion for ${entry.file.name} reported an error: ${completion2}`
123026
+ );
123027
+ }
123028
+ }
123029
+ async function requestStorageWithRetry(request, url, init, signal, label) {
123030
+ let lastError;
123031
+ for (let attempt = 1; attempt <= STORAGE_PUT_ATTEMPTS; attempt += 1) {
123032
+ let response;
123033
+ try {
123034
+ response = await request(url, {
123035
+ ...init,
123036
+ signal: combineSignals(
123037
+ signal,
123038
+ AbortSignal.timeout(STORAGE_PUT_TIMEOUT_MS)
123039
+ )
123040
+ });
123041
+ } catch (error) {
123042
+ if (signal.aborted || attempt === STORAGE_PUT_ATTEMPTS) throw error;
123043
+ lastError = error;
123044
+ await waitForRetry(attempt, signal);
123045
+ continue;
123046
+ }
123047
+ if (response.ok) return response;
123048
+ if (!isRetryableStatus(response.status) || attempt === STORAGE_PUT_ATTEMPTS) {
123049
+ throw new Error(
123050
+ `Storage ${label} failed (${response.status}): ${await response.text()}`
123051
+ );
123052
+ }
123053
+ lastError = new Error(`Storage ${label} failed (${response.status}).`);
123054
+ await waitForRetry(attempt, signal);
123055
+ }
123056
+ throw lastError instanceof Error ? lastError : new Error(`Storage ${label} failed.`);
123057
+ }
123058
+ function escapeXml(value) {
123059
+ return value.replace(/&/gu, "&amp;").replace(/</gu, "&lt;").replace(/>/gu, "&gt;").replace(/"/gu, "&quot;").replace(/'/gu, "&apos;");
123060
+ }
120943
123061
  function isRetryableStatus(status) {
120944
123062
  return status === 408 || status === 429 || status >= 500;
120945
123063
  }
@@ -120975,13 +123093,14 @@ async function waitForRetry(attempt, signal) {
120975
123093
  async function mapWithConcurrency(values, concurrency, run) {
120976
123094
  let nextIndex = 0;
120977
123095
  let firstError;
123096
+ const results = new Array(values.length);
120978
123097
  const worker = async () => {
120979
123098
  while (firstError === void 0) {
120980
123099
  const index = nextIndex;
120981
123100
  nextIndex += 1;
120982
123101
  if (index >= values.length) return;
120983
123102
  try {
120984
- await run(values[index]);
123103
+ results[index] = await run(values[index]);
120985
123104
  } catch (error) {
120986
123105
  firstError ??= error;
120987
123106
  }
@@ -120991,6 +123110,7 @@ async function mapWithConcurrency(values, concurrency, run) {
120991
123110
  Array.from({ length: Math.min(concurrency, values.length) }, worker)
120992
123111
  );
120993
123112
  if (firstError !== void 0) throw firstError;
123113
+ return results;
120994
123114
  }
120995
123115
  function combineSignals(...signals) {
120996
123116
  const defined = signals.filter(
@@ -121018,7 +123138,7 @@ function uploadHeaders(entry, objectInfo, mimeType) {
121018
123138
  function versionPath(workspace, suffix) {
121019
123139
  return `/api/projects/${workspace.config.projectId}/versions/${workspace.config.versionId}/${suffix}`;
121020
123140
  }
121021
- var UPLOAD_CONCURRENCY, PRESIGN_TIMEOUT_MS, PRESIGN_ATTEMPTS, STORAGE_PUT_TIMEOUT_MS, STORAGE_PUT_ATTEMPTS, ProjectFilePushCancelledError, RETRYABLE_NETWORK_ERROR_CODES;
123141
+ var UPLOAD_CONCURRENCY, PRESIGN_BATCH_SIZE, MULTIPART_PART_CONCURRENCY, PRESIGN_TIMEOUT_MS, PRESIGN_ATTEMPTS, STORAGE_PUT_TIMEOUT_MS, STORAGE_PUT_ATTEMPTS, ProjectFilePushCancelledError, RETRYABLE_NETWORK_ERROR_CODES;
121022
123142
  var init_project_file_push = __esm({
121023
123143
  "src/project-source/project-file-push.ts"() {
121024
123144
  "use strict";
@@ -121026,6 +123146,11 @@ var init_project_file_push = __esm({
121026
123146
  init_projection();
121027
123147
  init_src();
121028
123148
  UPLOAD_CONCURRENCY = 6;
123149
+ PRESIGN_BATCH_SIZE = Math.min(
123150
+ UPLOAD_CONCURRENCY,
123151
+ PROJECT_FILE_UPLOAD_BATCH_SIZE
123152
+ );
123153
+ MULTIPART_PART_CONCURRENCY = 4;
121029
123154
  PRESIGN_TIMEOUT_MS = 3e4;
121030
123155
  PRESIGN_ATTEMPTS = 3;
121031
123156
  STORAGE_PUT_TIMEOUT_MS = 12e4;
@@ -121243,7 +123368,7 @@ __export(push_exports, {
121243
123368
  runPush: () => runPush,
121244
123369
  stripServerDerivedNeoScript: () => stripServerDerivedNeoScript
121245
123370
  });
121246
- import { createHash as createHash10, randomUUID as randomUUID2 } from "node:crypto";
123371
+ import { createHash as createHash10, randomUUID as randomUUID3 } from "node:crypto";
121247
123372
  import {
121248
123373
  mkdirSync as mkdirSync10,
121249
123374
  writeFileSync as writeFileSync10,
@@ -121289,7 +123414,7 @@ function assignPendingIds(changes, authoredValueSeeds, reconstructed3, localInit
121289
123414
  assigned.set(pendingId2, derived);
121290
123415
  return derived;
121291
123416
  }
121292
- const fresh = randomUUID2();
123417
+ const fresh = randomUUID3();
121293
123418
  assigned.set(pendingId2, fresh);
121294
123419
  return fresh;
121295
123420
  };
@@ -121988,6 +124113,7 @@ async function runPush(workspace, options, preparationOverride) {
121988
124113
  json: options.json === true,
121989
124114
  includeDocument: verifiesConfiguredHook,
121990
124115
  identifyArtifactErrors: true,
124116
+ refreshDerivedEdgeVersion: options.dryRun,
121991
124117
  onPhase: (label) => preparation?.update(label)
121992
124118
  });
121993
124119
  } catch (error) {
@@ -122155,6 +124281,7 @@ async function runPush(workspace, options, preparationOverride) {
122155
124281
  }
122156
124282
  const stagePreparedPush = async () => {
122157
124283
  const client2 = NeoApiClient.forBaseUrl(workspace.config.apiBaseUrl);
124284
+ const stagedUploadSessionId2 = preparedLocal.preparedFiles.length > 0 ? randomUUID3() : null;
122158
124285
  const stagedFiles2 = await stageProjectFilePushesV4({
122159
124286
  workspace,
122160
124287
  changes: status.changes,
@@ -122162,13 +124289,19 @@ async function runPush(workspace, options, preparationOverride) {
122162
124289
  assignedIds: preparedLocal.pendingAssignment.assigned,
122163
124290
  client: client2,
122164
124291
  prepared: preparedLocal.preparedFiles,
124292
+ ...stagedUploadSessionId2 === null ? {} : { stagedUploadSessionId: stagedUploadSessionId2 },
122165
124293
  onProgress: (upload) => progress.report({
122166
124294
  type: "push-progress",
122167
124295
  phase: "uploading",
122168
124296
  ...upload
122169
124297
  })
122170
124298
  });
122171
- return { ...preparedLocal, client: client2, stagedFiles: stagedFiles2 };
124299
+ return {
124300
+ ...preparedLocal,
124301
+ client: client2,
124302
+ stagedFiles: stagedFiles2,
124303
+ stagedUploadSessionId: stagedUploadSessionId2
124304
+ };
122172
124305
  };
122173
124306
  let preparedPush;
122174
124307
  try {
@@ -122189,9 +124322,9 @@ async function runPush(workspace, options, preparationOverride) {
122189
124322
  client,
122190
124323
  transportChanges,
122191
124324
  transportSeeds,
122192
- preparedFiles
124325
+ stagedUploadSessionId
122193
124326
  } = preparedPush;
122194
- let { stagedFiles } = preparedPush;
124327
+ const { stagedFiles } = preparedPush;
122195
124328
  const commit = async (force) => await client.post(
122196
124329
  `/api/projects/${workspace.config.projectId}/versions/${workspace.config.versionId}/schema/commit`,
122197
124330
  {
@@ -122200,12 +124333,14 @@ async function runPush(workspace, options, preparationOverride) {
122200
124333
  authoredValueSeeds: transportSeeds,
122201
124334
  initializerMaterialization: pendingAssignment.localInitializerMaterialization ?? { roots: [] },
122202
124335
  stagedFiles,
124336
+ stagedUploadSessionId,
122203
124337
  sourceHash: source.sourceHash,
122204
124338
  pendingIdAssignments: Object.fromEntries(pendingAssignment.assigned),
122205
124339
  summary: options.summary ?? "neo push",
122206
124340
  // P43 §4. The local evaluator computes against the pulled snapshot, so
122207
124341
  // the server rejects a push whose base is not the project head.
122208
124342
  headTransactionHash: workspace.state.headTransactionHash ?? null,
124343
+ derivedEdgeExtractorVersion: PROJECT_SNAPSHOT_DERIVED_EDGE_EXTRACTOR_VERSION,
122209
124344
  forceRecompile: options.forceRecompile === true
122210
124345
  },
122211
124346
  force ? { "x-neo-force-project-version-write": "true" } : void 0
@@ -122369,40 +124504,29 @@ async function runPush(workspace, options, preparationOverride) {
122369
124504
  fallback: false
122370
124505
  })) {
122371
124506
  progress = createPushProgressReporter(options.json === true);
124507
+ progress.report({
124508
+ type: "project-transaction-progress",
124509
+ transactionId: null,
124510
+ phase: "submitting",
124511
+ totalChangeCount: status.changes.length,
124512
+ appliedChangeCount: 0,
124513
+ totalChunkCount: null,
124514
+ appliedChunkCount: 0,
124515
+ errorCode: null,
124516
+ errorMessage: null
124517
+ });
122372
124518
  try {
122373
- stagedFiles = await stageProjectFilePushesV4({
122374
- workspace,
122375
- changes: status.changes,
122376
- binaryChanges: status.binaryChanges ?? [],
122377
- assignedIds: pendingAssignment.assigned,
122378
- client,
122379
- prepared: preparedFiles,
122380
- onProgress: (upload) => progress.report({
122381
- type: "push-progress",
122382
- phase: "uploading",
122383
- ...upload
122384
- })
122385
- });
122386
- progress.report({
122387
- type: "project-transaction-progress",
122388
- transactionId: null,
122389
- phase: "submitting",
122390
- totalChangeCount: status.changes.length,
122391
- appliedChangeCount: 0,
122392
- totalChunkCount: null,
122393
- appliedChunkCount: 0,
122394
- errorCode: null,
122395
- errorMessage: null
122396
- });
122397
124519
  result = await commit(true);
122398
124520
  } catch (retryError) {
122399
124521
  progress.stop();
122400
- if (retryError instanceof ProjectFilePushCancelledError) {
122401
- if (options.json !== true) console.error("Push cancelled.");
122402
- process.exitCode = 130;
122403
- return;
122404
- }
122405
124522
  if (retryError instanceof NeoApiError) {
124523
+ if (isDefinitiveSchemaCommitRejection(retryError)) {
124524
+ await cleanupRejectedProjectFilePushesV4({
124525
+ workspace,
124526
+ client,
124527
+ stagedUploadSessionId
124528
+ });
124529
+ }
122406
124530
  reportPushRejection(retryError.status, retryError.body);
122407
124531
  process.exitCode = 1;
122408
124532
  return;
@@ -122412,16 +124536,31 @@ async function runPush(workspace, options, preparationOverride) {
122412
124536
  await finishCommitResponse(result, progress);
122413
124537
  return;
122414
124538
  }
124539
+ await cleanupRejectedProjectFilePushesV4({
124540
+ workspace,
124541
+ client,
124542
+ stagedUploadSessionId
124543
+ });
122415
124544
  console.log("Push cancelled.");
122416
124545
  process.exitCode = 1;
122417
124546
  return;
122418
124547
  }
124548
+ if (isDefinitiveSchemaCommitRejection(error)) {
124549
+ await cleanupRejectedProjectFilePushesV4({
124550
+ workspace,
124551
+ client,
124552
+ stagedUploadSessionId
124553
+ });
124554
+ }
122419
124555
  reportPushRejection(error.status, rejection);
122420
124556
  process.exitCode = 1;
122421
124557
  return;
122422
124558
  }
122423
124559
  await finishCommitResponse(result, progress);
122424
124560
  }
124561
+ function isDefinitiveSchemaCommitRejection(error) {
124562
+ return error.status === 400 || error.status === 401 || error.status === 403 || error.status === 404 || error.status === 409;
124563
+ }
122425
124564
  async function prepareLocalPushArtifactsV4(workspace, status, onPhase = () => void 0, options = {
122426
124565
  fullValidation: true,
122427
124566
  forceRecompile: false
@@ -122533,6 +124672,14 @@ async function prepareLocalCandidateV4(workspace, options = {}) {
122533
124672
  if (status.changes.length > 0 || status.authoredValueSeeds.size > 0) {
122534
124673
  try {
122535
124674
  documentStatus = pushOptions.dryRun ? cloneStatusForDryRun(status) : status;
124675
+ if (options.refreshDerivedEdgeVersion === true) {
124676
+ const convex = await createConvexClient(workspace);
124677
+ const signal = await convex.query(api2.projectExportData.schemaSignal, {
124678
+ projectId: workspace.config.projectId,
124679
+ versionId: workspace.config.versionId
124680
+ });
124681
+ workspace.state.derivedEdgeVersion = signal?.derivedEdgeVersion ?? null;
124682
+ }
122536
124683
  preparedLocal = await prepareLocalPushArtifactsV4(
122537
124684
  workspace,
122538
124685
  documentStatus,
@@ -122968,8 +125115,10 @@ async function recoverHeadTransactionHashFromSchemaSignal(workspace) {
122968
125115
  versionId: workspace.config.versionId
122969
125116
  });
122970
125117
  workspace.state.headTransactionHash = signal?.transactionHash ?? null;
125118
+ workspace.state.derivedEdgeVersion = signal?.derivedEdgeVersion ?? null;
122971
125119
  } catch {
122972
125120
  workspace.state.headTransactionHash = null;
125121
+ delete workspace.state.derivedEdgeVersion;
122973
125122
  }
122974
125123
  }
122975
125124
  function immediateTransactionId(result) {
@@ -124185,6 +126334,7 @@ var init_push = __esm({
124185
126334
  init_merge();
124186
126335
  init_push_change_intent();
124187
126336
  init_push_body_diagnostics();
126337
+ init_project_snapshot_derived_edges();
124188
126338
  ({
124189
126339
  compileNSVoidBody: compileNSVoidBody2,
124190
126340
  compileNSFunction: compileNSFunction2,
@@ -124241,7 +126391,7 @@ var init_registry2 = __esm({
124241
126391
  PROJECT_SCHEMA_CONTRACT = Object.freeze({
124242
126392
  formatVersion: 4,
124243
126393
  contractVersion: "4.1",
124244
- cliVersion: "0.42.1",
126394
+ cliVersion: "0.43.0",
124245
126395
  projectFileUploadBatchSize: 32,
124246
126396
  documentRecords: {
124247
126397
  member: {
@@ -125664,7 +127814,7 @@ __export(test_exports, {
125664
127814
  maintainNeoTestBuildCache: () => maintainNeoTestBuildCache,
125665
127815
  runTest: () => runTest
125666
127816
  });
125667
- import { createHash as createHash11, randomUUID as randomUUID3 } from "node:crypto";
127817
+ import { createHash as createHash11, randomUUID as randomUUID4 } from "node:crypto";
125668
127818
  import {
125669
127819
  existsSync as existsSync13,
125670
127820
  mkdirSync as mkdirSync11,
@@ -126835,7 +128985,7 @@ async function executeRegisteredSpec(registered, document, selected, timeoutMs,
126835
128985
  }
126836
128986
  function atomicWrite(path, content) {
126837
128987
  mkdirSync11(dirname10(path), { recursive: true });
126838
- const temporary = `${path}.tmp-${String(process.pid)}-${randomUUID3()}`;
128988
+ const temporary = `${path}.tmp-${String(process.pid)}-${randomUUID4()}`;
126839
128989
  writeFileSync11(temporary, content, "utf8");
126840
128990
  renameSync5(temporary, path);
126841
128991
  }
@@ -127722,7 +129872,7 @@ __export(migrate_exports, {
127722
129872
  resolveWriteTarget: () => resolveWriteTarget,
127723
129873
  runMigrate: () => runMigrate
127724
129874
  });
127725
- import { randomUUID as randomUUID4 } from "node:crypto";
129875
+ import { randomUUID as randomUUID5 } from "node:crypto";
127726
129876
  import { existsSync as existsSync15, mkdirSync as mkdirSync12, readdirSync as readdirSync6, writeFileSync as writeFileSync12 } from "node:fs";
127727
129877
  import { join as join17 } from "node:path";
127728
129878
  async function runMigrate(workspace, subcommand, positional, targetRef, json, dependencies = {}) {
@@ -128707,7 +130857,7 @@ function planCollectionMutation(args) {
128707
130857
  `Migration "${migrationName}" adds a non-scalar collection entry; minting nested entries is not yet supported (build the value beforehand).`
128708
130858
  );
128709
130859
  }
128710
- const id2 = randomUUID4();
130860
+ const id2 = randomUUID5();
128711
130861
  changes.push({
128712
130862
  recordKind: "value",
128713
130863
  recordId: id2,
@@ -129497,7 +131647,7 @@ __export(content_exports, {
129497
131647
  runLoc: () => runLoc
129498
131648
  });
129499
131649
  import { readFileSync as readFileSync18 } from "node:fs";
129500
- import { randomUUID as randomUUID5 } from "node:crypto";
131650
+ import { randomUUID as randomUUID6 } from "node:crypto";
129501
131651
  function versionPath2(workspace, suffix) {
129502
131652
  return `/api/projects/${workspace.config.projectId}/versions/${workspace.config.versionId}/${suffix}`;
129503
131653
  }
@@ -129580,7 +131730,7 @@ async function runLoc(context, subcommand, positional, file) {
129580
131730
  const config = isObjectRecord2(raw.localizationConfig) ? raw.localizationConfig : {};
129581
131731
  const statusId = config.mainLocale === locale && typeof config.mainLocaleDefaultStatusId === "string" ? config.mainLocaleDefaultStatusId : "localization-status-needs-translation";
129582
131732
  const now = Date.now();
129583
- const textId = typeof body.id === "string" ? body.id : randomUUID5();
131733
+ const textId = typeof body.id === "string" ? body.id : randomUUID6();
129584
131734
  const existingHead = heads.get(`localized-text:${textId}`);
129585
131735
  const text = {
129586
131736
  id: textId,
@@ -131061,7 +133211,7 @@ There is no --keep-current: preserving current semantic state defines flatten.
131061
133211
  async function main() {
131062
133212
  const args = parseArgs(process.argv.slice(2));
131063
133213
  if (args.command === "--version") {
131064
- console.log("0.42.1");
133214
+ console.log("0.43.0");
131065
133215
  return;
131066
133216
  }
131067
133217
  if (args.command === null || args.command === "help" || args.command === "--help" || args.command === "-h") {