@neocompose/cli 0.42.0 → 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",
@@ -67138,6 +67214,21 @@ function findOwningMembersForValues(document, valueIds, additionalRoots, travers
67138
67214
  rows.push(value);
67139
67215
  }
67140
67216
  }
67217
+ let declaringClassIdByMemberId = null;
67218
+ const declaringClassEnv = (memberId) => {
67219
+ if (declaringClassIdByMemberId === null) {
67220
+ declaringClassIdByMemberId = /* @__PURE__ */ new Map();
67221
+ for (const schemaClass2 of document.classes) {
67222
+ for (const declaredId of Object.values(schemaClass2.schema)) {
67223
+ if (declaringClassIdByMemberId.has(declaredId)) continue;
67224
+ declaringClassIdByMemberId.set(declaredId, schemaClass2.id);
67225
+ }
67226
+ }
67227
+ }
67228
+ const classId = declaringClassIdByMemberId.get(memberId);
67229
+ if (classId === void 0) return envFromStamp(void 0);
67230
+ return resolveInstanceEnv(classId, void 0, document.classes);
67231
+ };
67141
67232
  const queue = [];
67142
67233
  const enqueueClassInstanceChildren = (args) => {
67143
67234
  const merged = mergeStoredInstanceSchema(
@@ -67191,18 +67282,57 @@ function findOwningMembersForValues(document, valueIds, additionalRoots, travers
67191
67282
  }
67192
67283
  const defaultValue = member.defaultValue;
67193
67284
  if (defaultValue == null) continue;
67194
- if (!isMemberClassBase(member)) continue;
67195
- if (!isRecordValue(defaultValue.value)) continue;
67196
- enqueueClassInstanceChildren({
67197
- member,
67198
- record: defaultValue.value,
67199
- effectiveClassId: defaultValue.classId ?? member.classId,
67200
- // A declaration default is never itself an override graph (D10).
67201
- insideAnimationOverrideGraph: false,
67202
- // The default graph hangs off the MEMBER record, so its children have no
67203
- // owning value row (P76: they stay physically sparse).
67204
- parentValueId: null
67205
- });
67285
+ if (isMemberClassBase(member)) {
67286
+ if (!isRecordValue(defaultValue.value)) continue;
67287
+ enqueueClassInstanceChildren({
67288
+ member,
67289
+ record: defaultValue.value,
67290
+ effectiveClassId: defaultValue.classId ?? member.classId,
67291
+ // A declaration default is never itself an override graph (D10).
67292
+ insideAnimationOverrideGraph: false,
67293
+ // The default graph hangs off the MEMBER record, so its children have
67294
+ // no owning value row (P76: they stay physically sparse).
67295
+ parentValueId: null
67296
+ });
67297
+ continue;
67298
+ }
67299
+ let entryMemberId;
67300
+ let entryValueIds;
67301
+ if (isMemberDictionaryBase(member)) {
67302
+ if (!isRecordValue(defaultValue.value)) continue;
67303
+ entryMemberId = member.entryMemberId;
67304
+ entryValueIds = Object.values(defaultValue.value);
67305
+ } else if (isMemberListBase(member)) {
67306
+ if (listKindOf(member) === 1 /* Unordered */) continue;
67307
+ if (!isStringListValue(defaultValue.value)) continue;
67308
+ entryMemberId = member.entryMemberId;
67309
+ entryValueIds = defaultValue.value;
67310
+ } else {
67311
+ continue;
67312
+ }
67313
+ const entryMemberRecord = membersById2.get(entryMemberId);
67314
+ if (entryMemberRecord === void 0) continue;
67315
+ let entryMember;
67316
+ try {
67317
+ entryMember = substituteMember(
67318
+ entryMemberRecord,
67319
+ declaringClassEnv(member.id),
67320
+ document.members
67321
+ );
67322
+ } catch {
67323
+ continue;
67324
+ }
67325
+ for (const entryValueId of entryValueIds) {
67326
+ queue.push({
67327
+ member: entryMember,
67328
+ memberRecordId: entryMemberRecord.id,
67329
+ id: entryValueId,
67330
+ // A declaration default is never itself an override graph (D10).
67331
+ insideAnimationOverrideGraph: false,
67332
+ // Reached from the MEMBER record: no owning value row.
67333
+ parentValueId: null
67334
+ });
67335
+ }
67206
67336
  }
67207
67337
  const visited = /* @__PURE__ */ new Set();
67208
67338
  for (let cursor = 0; cursor < queue.length; cursor += 1) {
@@ -77941,13 +78071,13 @@ function ownedObjectChildMember(row, sourceMember, key, ctx) {
77941
78071
  return memberForCustomSchemaValue(classId, key, ctx);
77942
78072
  }
77943
78073
  function freshCloneValueId() {
77944
- const randomUUID6 = globalThis.crypto?.randomUUID;
77945
- if (randomUUID6 === void 0) {
78074
+ const randomUUID7 = globalThis.crypto?.randomUUID;
78075
+ if (randomUUID7 === void 0) {
77946
78076
  throw new NSGetterRuntimeError(
77947
78077
  "Class.Clone cannot mint a value id because crypto.randomUUID is unavailable."
77948
78078
  );
77949
78079
  }
77950
- return randomUUID6.call(globalThis.crypto);
78080
+ return randomUUID7.call(globalThis.crypto);
77951
78081
  }
77952
78082
  function parseDialogueMemoryPointer(pointer) {
77953
78083
  if (typeof pointer !== "string") return null;
@@ -81268,6 +81398,8 @@ var init_init_backed_value_materialization = __esm({
81268
81398
  function materializeDialogues(dialogueRecords, dialogueNodes) {
81269
81399
  return dialogueRecords.map((dialogue) => {
81270
81400
  if (!isRecordWithStringId(dialogue)) return dialogue;
81401
+ const { triggerNodeId: _triggerNodeId, ...dialoguePayload } = dialogue;
81402
+ void _triggerNodeId;
81271
81403
  const nodes = dialogueNodes.filter(
81272
81404
  (node) => getDialogueNodeDialogueId(node) === dialogue.id
81273
81405
  );
@@ -81280,7 +81412,7 @@ function materializeDialogues(dialogueRecords, dialogueNodes) {
81280
81412
  })
81281
81413
  );
81282
81414
  const materializedDialogue = {
81283
- ...dialogue,
81415
+ ...dialoguePayload,
81284
81416
  nodes: bodyNodes,
81285
81417
  triggerNode: triggerNode === null || triggerNode === void 0 ? null : toDialogueNodePayload(triggerNode)
81286
81418
  };
@@ -81506,10 +81638,12 @@ __export(project_document_read_exports, {
81506
81638
  readOptionalArrayField: () => readOptionalArrayField,
81507
81639
  readProjectDocument: () => readProjectDocument,
81508
81640
  readProjectDocumentContentHashHeads: () => readProjectDocumentContentHashHeads,
81641
+ readProjectDocumentManifestPage: () => readProjectDocumentManifestPage,
81509
81642
  readProjectDocumentManifestPageRecords: () => readProjectDocumentManifestPageRecords,
81510
81643
  readProjectDocumentManifestRecords: () => readProjectDocumentManifestRecords,
81511
81644
  readProjectDocumentRevisionMarker: () => readProjectDocumentRevisionMarker,
81512
- readStoredMembersField: () => readStoredMembersField
81645
+ readStoredMembersField: () => readStoredMembersField,
81646
+ withStoredValueBase: () => withStoredValueBase
81513
81647
  });
81514
81648
  async function fetchProjectDocumentRawChunked(runner, options = {}) {
81515
81649
  const mapKeys = options.mapKeys ?? [
@@ -81961,6 +82095,9 @@ function projectDocumentValueBuckets(rows) {
81961
82095
  if (expanded === rows) return { values: rows };
81962
82096
  return { values: [...expanded], physicalValues: rows };
81963
82097
  }
82098
+ function withStoredValueBase(document) {
82099
+ return document.physicalValues === void 0 ? { ...document, physicalValues: document.values } : document;
82100
+ }
81964
82101
  function readProjectDocument(value, options = {}) {
81965
82102
  if (!isObject4(value)) {
81966
82103
  throw new Error("Convex project document query returned a non-object.");
@@ -86360,11 +86497,12 @@ function isWorldAnimationStructuralMember(memberId, members) {
86360
86497
  }
86361
86498
  return false;
86362
86499
  }
86363
- function assertAnimationClipDocumentValid(document) {
86500
+ function assertAnimationClipDocumentValid(document, scope) {
86364
86501
  const context = new AnimationValidationContext(document);
86365
- context.validateSegments();
86502
+ context.validateSegments(scope);
86366
86503
  for (const member of document.members) {
86367
86504
  if (!isMemberClass(member)) continue;
86505
+ if (scope !== void 0 && !scope.memberIds.has(member.id)) continue;
86368
86506
  if (!context.classHasWorldKind(member.classId, "animationClip")) continue;
86369
86507
  if (isAbstractMember(member) === true) continue;
86370
86508
  context.validateClipMember(member);
@@ -86980,10 +87118,11 @@ var init_animation_clips = __esm({
86980
87118
  * files, and Session all hold segments, and a Session-stored `Duration` a
86981
87119
  * game writes at runtime is a feature, not drift.
86982
87120
  */
86983
- validateSegments() {
87121
+ validateSegments(scope) {
86984
87122
  const visited = /* @__PURE__ */ new Set();
86985
87123
  for (const member of this.document.members) {
86986
87124
  if (!isMemberClass(member)) continue;
87125
+ if (scope !== void 0 && !scope.memberIds.has(member.id)) continue;
86987
87126
  if (!this.classHasWorldKind(member.classId, "animationSegment")) continue;
86988
87127
  const node = this.optionalMemberRootNode(member);
86989
87128
  if (node === null) continue;
@@ -88793,44 +88932,61 @@ function transactionImpactsAnyOwnerMember(scope, impactedIds) {
88793
88932
  }
88794
88933
  return false;
88795
88934
  }
88796
- function collectNeoScriptRecompileTargets(args) {
88797
- if (args.forceRecompile === true) return completeTargets(args.postDocument);
88798
- const explicit = explicitTargetIds(args.changes);
88799
- const {
88800
- impactedIds,
88801
- changedValueIds,
88802
- impactedTypeNames,
88803
- constructedClassIds
88804
- } = collectChangedContractIds(args);
88805
- 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);
88806
88938
  for (const id2 of args.additionalChangedValueIds ?? []) {
88807
- changedValueIds.add(id2);
88808
- explicit.valueIds.add(id2);
88939
+ impact.changedValueIds.add(id2);
88809
88940
  }
88810
88941
  includeDerivedConstructionContracts(
88811
- constructedClassIds,
88942
+ impact.constructedClassIds,
88812
88943
  args.postDocument.classes
88813
88944
  );
88814
- const schemaRecords = [
88945
+ const dependentsById = /* @__PURE__ */ new Map();
88946
+ for (const record3 of [
88815
88947
  ...collectSchemaDependencyRecords(args.postDocument),
88816
88948
  ...collectStructuralDependencyRecords(args.postDocument)
88817
- ];
88818
- const dependentsById = /* @__PURE__ */ new Map();
88819
- for (const record3 of schemaRecords) {
88949
+ ]) {
88820
88950
  for (const dependencyId of collectCompilerReferenceIds(record3.value)) {
88821
88951
  const dependents = dependentsById.get(dependencyId) ?? [];
88822
88952
  dependents.push(record3);
88823
88953
  dependentsById.set(dependencyId, dependents);
88824
88954
  }
88825
88955
  }
88826
- const queue = [...impactedIds, ...changedValueIds];
88956
+ const queue = [...impact.impactedIds, ...impact.changedValueIds];
88827
88957
  for (let index = 0; index < queue.length; index += 1) {
88828
88958
  const dependencyId = queue[index];
88829
88959
  if (dependencyId === void 0) continue;
88830
88960
  for (const dependent of dependentsById.get(dependencyId) ?? []) {
88831
- addImpactedId(impactedIds, queue, dependent.id);
88961
+ addImpactedId(impact.impactedIds, queue, dependent.id);
88832
88962
  }
88833
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
+ }
88834
88990
  const constructorOwnerById = constructorOwners(args.postDocument);
88835
88991
  const gradesSourceOnlyBodies = impactedIds.size > 0 || impactedTypeNames.size > 0;
88836
88992
  const impactScope = {
@@ -88972,7 +89128,9 @@ function collectCompilerReferenceNamesInto(value, field, names) {
88972
89128
  }
88973
89129
  }
88974
89130
  function isCompilerReferenceField(field) {
88975
- 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";
88976
89134
  }
88977
89135
  function collectChangedContractIds(args) {
88978
89136
  const impactedIds = /* @__PURE__ */ new Set();
@@ -89502,7 +89660,7 @@ function withoutFields(value, ignored) {
89502
89660
  Object.entries(value).filter(([field]) => !ignored.has(field))
89503
89661
  );
89504
89662
  }
89505
- 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;
89506
89664
  var init_neo_script_recompile_scope = __esm({
89507
89665
  "../src/database/neo-script-recompile-scope.ts"() {
89508
89666
  "use strict";
@@ -89542,6 +89700,7 @@ var init_neo_script_recompile_scope = __esm({
89542
89700
  "bodyMode",
89543
89701
  "uiAction"
89544
89702
  ]);
89703
+ collectCompiledClassIds = collectConstructedClassIds;
89545
89704
  }
89546
89705
  });
89547
89706
 
@@ -97470,7 +97629,7 @@ function reconcileDirectOverrideChains(args) {
97470
97629
  }
97471
97630
  }
97472
97631
  }
97473
- function prepareServerOwnedSchemaCommit(args) {
97632
+ function* prepareServerOwnedSchemaCommitPasses(args) {
97474
97633
  if (args.forceRecompile === true) clearNeoScriptBodyCompileCache();
97475
97634
  assertUniqueChanges(args.changes);
97476
97635
  let authoredChanges = completeLocalizedTextCreateEnvelopes({
@@ -97488,7 +97647,8 @@ function prepareServerOwnedSchemaCommit(args) {
97488
97647
  args.document,
97489
97648
  authoredChanges
97490
97649
  ),
97491
- changes: authoredChanges
97650
+ changes: authoredChanges,
97651
+ createTextId: args.createLocalizedTextId
97492
97652
  });
97493
97653
  const explicitlyChangedMemberIds = /* @__PURE__ */ new Set();
97494
97654
  for (const change of authoredChanges) {
@@ -97518,6 +97678,7 @@ function prepareServerOwnedSchemaCommit(args) {
97518
97678
  if (!hasSchemaChange && !hasMigrationChange && !hasDialogueSourceChange && !hasValueChange && !hasAdditionalContractImpact) {
97519
97679
  return authoredChanges;
97520
97680
  }
97681
+ args.passLifecycle?.("start", "neo-script-recompile-targets");
97521
97682
  const authoredPostDocument = applyProjectVersionWriteChanges(
97522
97683
  args.document,
97523
97684
  authoredChanges
@@ -97738,26 +97899,46 @@ function prepareServerOwnedSchemaCommit(args) {
97738
97899
  recompileTargets,
97739
97900
  contentHashHeads: args.contentHashHeads
97740
97901
  });
97902
+ args.passLifecycle?.("complete", "neo-script-recompile-targets");
97903
+ yield {
97904
+ pass: "neo-script-recompile-targets",
97905
+ preparedChanges: prepared
97906
+ };
97741
97907
  const serverMintedBindingMemberIds = /* @__PURE__ */ new Set();
97908
+ args.passLifecycle?.("start", "authored-value-seeds");
97909
+ const seedPostDocument = applyProjectVersionWriteChanges(
97910
+ args.document,
97911
+ prepared
97912
+ );
97742
97913
  const pendingConstructedGraphValidations = materializeAuthoredValueSeeds({
97743
- document: applyProjectVersionWriteChanges(postDocument, prepared),
97914
+ document: seedPostDocument,
97744
97915
  prepared,
97745
97916
  authoredValueSeeds: args.authoredValueSeeds ?? [],
97746
97917
  contentHashHeads: args.contentHashHeads,
97747
- serverMintedBindingMemberIds
97918
+ serverMintedBindingMemberIds,
97919
+ createLocalizedTextId: args.createLocalizedTextId
97748
97920
  });
97749
97921
  prepareServerOwnedValueInitializerBodies({
97750
97922
  document: args.document,
97751
- postDocument,
97923
+ postDocument: seedPostDocument,
97752
97924
  prepared,
97753
97925
  targetIds: recompileTargets.valueIds,
97754
97926
  contentHashHeads: args.contentHashHeads
97755
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");
97756
97931
  materializeVariantChildOverrideBindingMembers({
97757
97932
  document: args.document,
97758
97933
  prepared,
97759
97934
  serverMintedBindingMemberIds
97760
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");
97761
97942
  materializePreparedInstanceInitializers({
97762
97943
  document: args.document,
97763
97944
  prepared,
@@ -97775,13 +97956,22 @@ function prepareServerOwnedSchemaCommit(args) {
97775
97956
  prepared,
97776
97957
  pending: pendingConstructedGraphValidations
97777
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");
97778
97965
  prepareServerOwnedDelegateValueBodies({
97779
97966
  document: args.document,
97780
- postDocument,
97967
+ postDocument: applyProjectVersionWriteChanges(args.document, prepared),
97781
97968
  prepared,
97782
97969
  targetIds: recompileTargets.valueIds,
97783
97970
  contentHashHeads: args.contentHashHeads
97784
97971
  });
97972
+ args.passLifecycle?.("complete", "delegate-value-bodies");
97973
+ yield { pass: "delegate-value-bodies", preparedChanges: prepared };
97974
+ args.passLifecycle?.("start", "variant-constructor-args");
97785
97975
  reconcileVariantConstructorArgs({
97786
97976
  document: args.document,
97787
97977
  prepared,
@@ -97792,6 +97982,7 @@ function prepareServerOwnedSchemaCommit(args) {
97792
97982
  prepared,
97793
97983
  contentHashHeads: args.contentHashHeads
97794
97984
  });
97985
+ normalizePreparedServerTimestamps(prepared, args.serverTimestamp);
97795
97986
  const committedDocument = applyProjectVersionWriteChanges(
97796
97987
  args.document,
97797
97988
  prepared
@@ -97808,11 +97999,37 @@ function prepareServerOwnedSchemaCommit(args) {
97808
97999
  });
97809
98000
  attachPreparedValuePlacements(physical, committedDocument);
97810
98001
  attachPreparedConstructorAggregateEdges(physical, committedDocument);
97811
- return orderLocalizedTextWritesBesideLinks(
98002
+ const ordered = orderLocalizedTextWritesBesideLinks(
97812
98003
  orderVariantRootValuesWithVariants(
97813
- orderDeclaredMemberCreatesFirst(physical, postDocument)
98004
+ orderDeclaredMemberCreatesFirst(
98005
+ physical,
98006
+ applyProjectVersionWriteChanges(args.document, prepared)
98007
+ )
97814
98008
  )
97815
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
+ }
97816
98033
  }
97817
98034
  function orderLocalizedTextWritesBesideLinks(prepared) {
97818
98035
  const indexByLinkKey = /* @__PURE__ */ new Map();
@@ -98737,8 +98954,12 @@ function prepareServerOwnedDialogueBodies(args) {
98737
98954
  explicitNodeIds.add(change.recordId);
98738
98955
  const next = asRecord2(change.nextData);
98739
98956
  const current = currentNodes.get(change.recordId);
98740
- const dialogueId = typeof next?.dialogueId === "string" ? next.dialogueId : typeof current?.dialogueId === "string" ? current.dialogueId : null;
98741
- 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
+ }
98742
98963
  continue;
98743
98964
  }
98744
98965
  if (change.recordKind === "dialogue-group") {
@@ -98988,7 +99209,8 @@ function materializeAuthoredValueSeeds(args) {
98988
99209
  pendingGraphValidations,
98989
99210
  memberChange: { index, change },
98990
99211
  member,
98991
- seed
99212
+ seed,
99213
+ createLocalizedTextId: args.createLocalizedTextId
98992
99214
  });
98993
99215
  continue;
98994
99216
  }
@@ -99049,7 +99271,8 @@ function materializeAuthoredValueSeeds(args) {
99049
99271
  // default builder evaluates it immediately, which bypasses both
99050
99272
  // the server-initializer-materialization grouping and the CLI's
99051
99273
  // parity/identity transport for evaluator-created interior rows.
99052
- seed: { ...seed, values: seed.values ?? [] }
99274
+ seed: { ...seed, values: seed.values ?? [] },
99275
+ createLocalizedTextId: args.createLocalizedTextId
99053
99276
  });
99054
99277
  const { createdValues, localizedTexts, storageKeyDeclarations, rootValue } = materialized;
99055
99278
  const ownedValueId = documentIndex.membersById.get(member.id)?.valueId ?? derivedMemberValueId(member.id);
@@ -99459,7 +99682,8 @@ function materializeInstanceDefaultSeed(args) {
99459
99682
  documentIndex: args.documentIndex,
99460
99683
  member: materializationMember,
99461
99684
  seed: { ...args.seed, values: args.seed.values },
99462
- allowExistingRows: args.memberChange === null || args.memberChange.change.operation === "update"
99685
+ allowExistingRows: args.memberChange === null || args.memberChange.change.operation === "update",
99686
+ createLocalizedTextId: args.createLocalizedTextId
99463
99687
  });
99464
99688
  stampCreatedValuesMapKey(createdValues, null);
99465
99689
  applyDeclaredStorageKeyOverrides({
@@ -99663,7 +99887,8 @@ function materializeAuthoredStaticSeed(args) {
99663
99887
  document: args.document,
99664
99888
  member: args.member,
99665
99889
  createdValues,
99666
- seededLocalizedTexts
99890
+ seededLocalizedTexts,
99891
+ createLocalizedTextId: args.createLocalizedTextId
99667
99892
  });
99668
99893
  return {
99669
99894
  rootValue,
@@ -99693,7 +99918,8 @@ function materializeSeedLocalizableStringWrites(args) {
99693
99918
  memberId: args.member.id
99694
99919
  }),
99695
99920
  expectedBaseContentHash: null
99696
- }))
99921
+ })),
99922
+ createTextId: args.createLocalizedTextId
99697
99923
  });
99698
99924
  const createdValuesById = new Map(
99699
99925
  args.createdValues.map((value) => [value.id, value])
@@ -102174,7 +102400,8 @@ function assertProjectVersionWholeGraphWritesValid(args) {
102174
102400
  assertStagedInternalRecordRelationsValid(args.document, projected, changes);
102175
102401
  assertStagedWorldContentLayerBindingsValid(args.document, projected, changes);
102176
102402
  assertAnimationClipDocumentValid(
102177
- materializeDeclarationInitializersForAnimationValidation(projected)
102403
+ materializeDeclarationInitializersForAnimationValidation(projected),
102404
+ args.animationValidationMemberIds === void 0 ? void 0 : { memberIds: args.animationValidationMemberIds }
102178
102405
  );
102179
102406
  if (args.operation === void 0 || !isSystemOwnedProjectVersionOperation(args.operation)) {
102180
102407
  assertProjectVersionSystemProtectedWritesValid({
@@ -102292,7 +102519,7 @@ function valueDematerializationRefusal(args) {
102292
102519
  return null;
102293
102520
  }
102294
102521
  function materializeDeclarationInitializersForAnimationValidation(document) {
102295
- const animationFamilyClassIds = animationFamilyClasses(document);
102522
+ const animationFamilyClassIds = animationFamilyClassKinds(document.classes);
102296
102523
  const initializers = document.values.filter(
102297
102524
  (value) => isInitValueContent(value)
102298
102525
  );
@@ -102466,31 +102693,6 @@ function materializeDeclarationInitializersForAnimationValidation(document) {
102466
102693
  }
102467
102694
  return { ...document, members, values: [...valuesById.values()] };
102468
102695
  }
102469
- function animationFamilyClasses(document) {
102470
- const classes = new Map(document.classes.map((entry) => [entry.id, entry]));
102471
- const animationKinds = new Set(WORLD_SYSTEM_ANIMATION_KINDS);
102472
- const result = /* @__PURE__ */ new Map();
102473
- const resolve5 = (classId, visiting) => {
102474
- const cached = result.get(classId);
102475
- if (cached !== void 0) return cached;
102476
- if (visiting.has(classId)) return false;
102477
- const schemaClass2 = classes.get(classId);
102478
- if (schemaClass2 === void 0) return false;
102479
- const worldKind = schemaClass2.system?.worldKind;
102480
- if (typeof worldKind === "string" && animationKinds.has(worldKind)) {
102481
- result.set(classId, true);
102482
- return true;
102483
- }
102484
- const nextVisiting = new Set(visiting).add(classId);
102485
- const belongs = typeof schemaClass2.extendsClassId === "string" && resolve5(schemaClass2.extendsClassId, nextVisiting);
102486
- result.set(classId, belongs);
102487
- return belongs;
102488
- };
102489
- for (const classId of classes.keys()) resolve5(classId, /* @__PURE__ */ new Set());
102490
- return new Set(
102491
- [...result].flatMap(([classId, belongs]) => belongs ? [classId] : [])
102492
- );
102493
- }
102494
102696
  function containsDirectValueId(value, ids) {
102495
102697
  if (Array.isArray(value)) {
102496
102698
  return value.some((entry) => typeof entry === "string" && ids.has(entry));
@@ -105645,6 +105847,1467 @@ var init_trusted_commit_verification = __esm({
105645
105847
  }
105646
105848
  });
105647
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
+
105648
107311
  // src/project-source/server-preparation-preflight.ts
105649
107312
  function assertServerPreparationSucceeds(args) {
105650
107313
  for (const change of args.changes) {
@@ -105658,6 +107321,7 @@ function assertServerPreparationSucceeds(args) {
105658
107321
  });
105659
107322
  if (refusal !== null) throw new ServerPreparationPreflightError(refusal);
105660
107323
  }
107324
+ assertDerivedEdgeCompatibility(args.workspace);
105661
107325
  try {
105662
107326
  const prepared = prepareServerPreparationChanges(args);
105663
107327
  if (args.localInitializerMaterialization !== void 0) {
@@ -105671,6 +107335,42 @@ function assertServerPreparationSucceeds(args) {
105671
107335
  throw locateBodyCompileFailure(error, args.sourceByRecord);
105672
107336
  }
105673
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
+ }
105674
107374
  function assertInitializerMaterializationParity(local, prepared) {
105675
107375
  const rowsById = /* @__PURE__ */ new Map();
105676
107376
  const createdByRoot = /* @__PURE__ */ new Map();
@@ -105742,9 +107442,27 @@ function locateBodyCompileFailure(error, sourceByRecord) {
105742
107442
  if (source === void 0) return error;
105743
107443
  return new Error(`${source.file}:${source.line} \u2014 ${error.message}`);
105744
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
+ }
105745
107458
  function prepareServerPreparationChanges(args) {
107459
+ const serverTimestamp = args.serverTimestamp ?? Date.now();
105746
107460
  const rawDocument = pulledProjectDocumentRaw(args.workspace);
105747
- const document = readProjectDocument(rawDocument);
107461
+ const document = withReplayValueIdFactory(
107462
+ withStoredValueBase(readProjectDocument(rawDocument)),
107463
+ args.createValueId,
107464
+ serverTimestamp
107465
+ );
105748
107466
  const contentHashHeads = readProjectDocumentContentHashHeads(rawDocument);
105749
107467
  const changes = args.changes.map((change) => ({
105750
107468
  ...change,
@@ -105755,9 +107473,44 @@ function prepareServerPreparationChanges(args) {
105755
107473
  }));
105756
107474
  const trustedChanges = stampServerOwnedSourceCommitMetadata({
105757
107475
  rawDocument,
105758
- changes
107476
+ changes,
107477
+ timestamp: serverTimestamp
105759
107478
  });
105760
- 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 = {
105761
107514
  document,
105762
107515
  contentHashHeads,
105763
107516
  changes: trustedChanges,
@@ -105766,10 +107519,258 @@ function prepareServerPreparationChanges(args) {
105766
107519
  // A CLI push is always a trusted-source commit, so the server always
105767
107520
  // expands read-only source conversions for it.
105768
107521
  expandReadOnlySourceConversions: true,
105769
- 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
107646
+ });
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
+ }
105770
107656
  });
105771
- assertProjectVersionWholeGraphWritesValid({ document, changes: prepared });
105772
- return prepared;
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
+ };
105773
107774
  }
105774
107775
  function pulledProjectDocumentRaw(workspace) {
105775
107776
  const records2 = [];
@@ -105846,7 +107847,7 @@ function syntheticVersionMetadata(workspace) {
105846
107847
  releaseChannels: []
105847
107848
  };
105848
107849
  }
105849
- var ServerPreparationPreflightError;
107850
+ var ServerPreparationPreflightError, DerivedEdgeCompatibilityError, COMMIT_PREPARATION_CLI_CONTENT_KINDS;
105850
107851
  var init_server_preparation_preflight = __esm({
105851
107852
  "src/project-source/server-preparation-preflight.ts"() {
105852
107853
  "use strict";
@@ -105856,13 +107857,33 @@ var init_server_preparation_preflight = __esm({
105856
107857
  init_project_version_whole_graph_validation();
105857
107858
  init_projectRecordBuckets();
105858
107859
  init_compile_ns_property();
107860
+ init_valueHeadPlacementGraph();
105859
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();
105860
107868
  ServerPreparationPreflightError = class extends Error {
105861
107869
  constructor(message) {
105862
107870
  super(message);
105863
107871
  this.name = "ServerPreparationPreflightError";
105864
107872
  }
105865
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"]);
105866
107887
  }
105867
107888
  });
105868
107889
 
@@ -115271,7 +117292,8 @@ async function queryProjectDocumentSyncMarker(workspace, convex) {
115271
117292
  return {
115272
117293
  revision: revisionValue,
115273
117294
  headTransactionId: signal?.transactionId ?? null,
115274
- headTransactionHash: signal?.transactionHash ?? null
117295
+ headTransactionHash: signal?.transactionHash ?? null,
117296
+ derivedEdgeVersion: signal?.derivedEdgeVersion ?? null
115275
117297
  };
115276
117298
  }
115277
117299
  async function fetchProjectDocumentDelta(workspace, cursor) {
@@ -115280,7 +117302,8 @@ async function fetchProjectDocumentDelta(workspace, cursor) {
115280
117302
  if (marker.revision.versionsStamp !== cursor.versionsStamp) {
115281
117303
  return {
115282
117304
  fullResync: true,
115283
- headTransactionHash: marker.headTransactionHash
117305
+ headTransactionHash: marker.headTransactionHash,
117306
+ derivedEdgeVersion: marker.derivedEdgeVersion
115284
117307
  };
115285
117308
  }
115286
117309
  if (marker.headTransactionId === marker.revision.latestTransactionId && marker.headTransactionHash === workspace.state.headTransactionHash) {
@@ -115289,7 +117312,8 @@ async function fetchProjectDocumentDelta(workspace, cursor) {
115289
117312
  document: projectDocumentFromWorkspaceState(workspace.state, cursor),
115290
117313
  changedKeys: /* @__PURE__ */ new Set(),
115291
117314
  cursor,
115292
- headTransactionHash: marker.headTransactionHash
117315
+ headTransactionHash: marker.headTransactionHash,
117316
+ derivedEdgeVersion: marker.derivedEdgeVersion
115293
117317
  };
115294
117318
  }
115295
117319
  const result = await convex.query(api2.projectDocuments.getRecordsSince, {
@@ -115301,7 +117325,8 @@ async function fetchProjectDocumentDelta(workspace, cursor) {
115301
117325
  if (result.fullResync) {
115302
117326
  return {
115303
117327
  fullResync: true,
115304
- headTransactionHash: marker.headTransactionHash
117328
+ headTransactionHash: marker.headTransactionHash,
117329
+ derivedEdgeVersion: marker.derivedEdgeVersion
115305
117330
  };
115306
117331
  }
115307
117332
  const document = projectDocumentFromWorkspaceState(workspace.state, cursor);
@@ -115350,7 +117375,8 @@ async function fetchProjectDocumentDelta(workspace, cursor) {
115350
117375
  document: projectDocumentWithRevision(document, nextCursor),
115351
117376
  changedKeys,
115352
117377
  cursor: nextCursor,
115353
- headTransactionHash: marker.headTransactionHash
117378
+ headTransactionHash: marker.headTransactionHash,
117379
+ derivedEdgeVersion: marker.derivedEdgeVersion
115354
117380
  };
115355
117381
  }
115356
117382
  function projectDocumentFromWorkspaceState(state, cursor) {
@@ -116331,6 +118357,7 @@ ${blockingErrors.map((error) => ` ${error.message}`).join("\n")}`
116331
118357
  let changedRecordKeys = null;
116332
118358
  let nextCursor = null;
116333
118359
  let observedHeadTransactionHash;
118360
+ let observedDerivedEdgeVersion;
116334
118361
  let document = null;
116335
118362
  if (!destructive && hasBaseline) {
116336
118363
  progress.update("Checking remote changes\u2026");
@@ -116338,6 +118365,7 @@ ${blockingErrors.map((error) => ` ${error.message}`).join("\n")}`
116338
118365
  if (cursor !== void 0) {
116339
118366
  const delta = await fetchProjectDocumentDelta(workspace, cursor);
116340
118367
  observedHeadTransactionHash = delta.headTransactionHash;
118368
+ observedDerivedEdgeVersion = delta.derivedEdgeVersion;
116341
118369
  if (!delta.fullResync) {
116342
118370
  document = delta.document;
116343
118371
  changedRecordKeys = delta.changedKeys;
@@ -116348,11 +118376,13 @@ ${blockingErrors.map((error) => ` ${error.message}`).join("\n")}`
116348
118376
  delta.cursor
116349
118377
  );
116350
118378
  const headChanged = workspace.state.headTransactionHash !== delta.headTransactionHash;
116351
- if (cursorChanged || headChanged) {
118379
+ const derivedEdgeVersionChanged = workspace.state.derivedEdgeVersion !== delta.derivedEdgeVersion;
118380
+ if (cursorChanged || headChanged || derivedEdgeVersionChanged) {
116352
118381
  workspace.state.documentRevisionCursor = mutableCursor(
116353
118382
  delta.cursor
116354
118383
  );
116355
118384
  workspace.state.headTransactionHash = delta.headTransactionHash;
118385
+ workspace.state.derivedEdgeVersion = delta.derivedEdgeVersion;
116356
118386
  writeWorkspaceState(workspace.root, workspace.state);
116357
118387
  }
116358
118388
  progress.succeed("Already up to date.");
@@ -116362,9 +118392,11 @@ ${blockingErrors.map((error) => ` ${error.message}`).join("\n")}`
116362
118392
  } else if (!options.regenerateSourceNames && workspace.state.headTransactionHash !== void 0) {
116363
118393
  const marker = await fetchProjectDocumentSyncMarker(workspace);
116364
118394
  observedHeadTransactionHash = marker.headTransactionHash;
118395
+ observedDerivedEdgeVersion = marker.derivedEdgeVersion;
116365
118396
  if (marker.headTransactionId === marker.revision.latestTransactionId && marker.headTransactionHash === workspace.state.headTransactionHash) {
116366
118397
  const seededCursor = cursorFromRevision(marker.revision);
116367
118398
  workspace.state.documentRevisionCursor = mutableCursor(seededCursor);
118399
+ workspace.state.derivedEdgeVersion = marker.derivedEdgeVersion;
116368
118400
  writeWorkspaceState(workspace.root, workspace.state);
116369
118401
  progress.succeed("Already up to date.");
116370
118402
  return;
@@ -116503,6 +118535,7 @@ ${blockingErrors.map((error) => ` ${error.message}`).join("\n")}`
116503
118535
  changedRecordKeys,
116504
118536
  nextCursor,
116505
118537
  observedHeadTransactionHash,
118538
+ observedDerivedEdgeVersion,
116506
118539
  progress
116507
118540
  });
116508
118541
  }
@@ -116537,8 +118570,10 @@ async function runResetPull(workspace) {
116537
118570
  versionId: workspace.config.versionId
116538
118571
  });
116539
118572
  workspace.state.headTransactionHash = document.revision !== void 0 && signal?.transactionId === document.revision.latestTransactionId ? signal.transactionHash : null;
118573
+ workspace.state.derivedEdgeVersion = signal?.derivedEdgeVersion ?? null;
116540
118574
  } catch {
116541
118575
  workspace.state.headTransactionHash = null;
118576
+ delete workspace.state.derivedEdgeVersion;
116542
118577
  }
116543
118578
  if (document.revision !== void 0) {
116544
118579
  workspace.state.documentRevisionCursor = mutableCursor(
@@ -116570,6 +118605,7 @@ async function finishFormat4Pull(args) {
116570
118605
  changedRecordKeys,
116571
118606
  nextCursor,
116572
118607
  observedHeadTransactionHash,
118608
+ observedDerivedEdgeVersion,
116573
118609
  progress
116574
118610
  } = args;
116575
118611
  if (changedRecordKeys !== null && !regenerateSourceNames && conflictCount === 0 && localStatus !== null && !deltaRequiresSourceProjectionV4({
@@ -116585,6 +118621,7 @@ async function finishFormat4Pull(args) {
116585
118621
  changedRecordKeys,
116586
118622
  nextCursor,
116587
118623
  observedHeadTransactionHash,
118624
+ observedDerivedEdgeVersion,
116588
118625
  progress
116589
118626
  });
116590
118627
  return;
@@ -116769,10 +118806,15 @@ async function finishFormat4Pull(args) {
116769
118806
  versionId: workspace.config.versionId
116770
118807
  });
116771
118808
  workspace.state.headTransactionHash = document.revision !== void 0 && signal?.transactionId === document.revision.latestTransactionId ? signal.transactionHash : null;
118809
+ workspace.state.derivedEdgeVersion = signal?.derivedEdgeVersion ?? null;
116772
118810
  } catch {
116773
118811
  workspace.state.headTransactionHash = null;
118812
+ delete workspace.state.derivedEdgeVersion;
116774
118813
  }
116775
118814
  }
118815
+ if (observedDerivedEdgeVersion !== void 0) {
118816
+ workspace.state.derivedEdgeVersion = observedDerivedEdgeVersion;
118817
+ }
116776
118818
  writeWorkspaceState(workspace.root, workspace.state);
116777
118819
  if (conflictCount === 0) {
116778
118820
  writeProjectSourceAnalysisCacheV4(workspace.root, localResult.analysis);
@@ -116932,6 +118974,9 @@ function finishRecordOnlyDeltaPull(args) {
116932
118974
  if (args.observedHeadTransactionHash !== void 0) {
116933
118975
  args.workspace.state.headTransactionHash = args.observedHeadTransactionHash;
116934
118976
  }
118977
+ if (args.observedDerivedEdgeVersion !== void 0) {
118978
+ args.workspace.state.derivedEdgeVersion = args.observedDerivedEdgeVersion;
118979
+ }
116935
118980
  writeWorkspaceState(args.workspace.root, args.workspace.state);
116936
118981
  args.progress.succeed(
116937
118982
  `Pulled ${args.changedRecordKeys.size} changed record(s) \u2014 0 file(s) updated \u2014 0 removed.`
@@ -120383,7 +122428,7 @@ function normalizeSourceFiles(inputFiles) {
120383
122428
  return files;
120384
122429
  }
120385
122430
  function readSourceFile(value, index) {
120386
- const record3 = asRecord3(value, `Project source identity file ${index}`);
122431
+ const record3 = asRecord4(value, `Project source identity file ${index}`);
120387
122432
  assertExactKeys(record3, ["path", "kind", "content"]);
120388
122433
  if (typeof record3.path !== "string" || !isSafeSourcePath(record3.path)) {
120389
122434
  throw new Error(
@@ -120418,7 +122463,7 @@ function isSafeSourcePath(path) {
120418
122463
  }
120419
122464
  return neoProjectSourceKind(path) !== null;
120420
122465
  }
120421
- function asRecord3(value, label) {
122466
+ function asRecord4(value, label) {
120422
122467
  if (typeof value !== "object" || value === null || Array.isArray(value)) {
120423
122468
  throw new Error(`${label} must be an object.`);
120424
122469
  }
@@ -120620,6 +122665,17 @@ var init_push_hook = __esm({
120620
122665
  // src/project-source/project-file-push.ts
120621
122666
  import { basename as basename2, join as join13 } from "node:path";
120622
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
+ }
120623
122679
  function ensureProjectFileBinaryChangesV4(args) {
120624
122680
  for (const binary of args.binaryChanges) {
120625
122681
  if (binary.action !== "upload") continue;
@@ -120699,7 +122755,7 @@ async function stageProjectFilePushesV4(args) {
120699
122755
  assignedIds: args.assignedIds
120700
122756
  });
120701
122757
  const staged = [];
120702
- const cleanupKeys = [];
122758
+ const stagedUploadSessionId = args.stagedUploadSessionId ?? randomUUID2();
120703
122759
  const put = args.put ?? fetch;
120704
122760
  const interruptController = new AbortController();
120705
122761
  const interrupt = () => interruptController.abort(new ProjectFilePushCancelledError());
@@ -120716,11 +122772,8 @@ async function stageProjectFilePushesV4(args) {
120716
122772
  });
120717
122773
  report();
120718
122774
  try {
120719
- for (let offset = 0; offset < prepared.length; offset += PROJECT_FILE_UPLOAD_BATCH_SIZE) {
120720
- const batch = prepared.slice(
120721
- offset,
120722
- offset + PROJECT_FILE_UPLOAD_BATCH_SIZE
120723
- );
122775
+ for (let offset = 0; offset < prepared.length; offset += PRESIGN_BATCH_SIZE) {
122776
+ const batch = prepared.slice(offset, offset + PRESIGN_BATCH_SIZE);
120724
122777
  const presign = await postWithTimeout(
120725
122778
  args.client,
120726
122779
  versionPath(args.workspace, "upload"),
@@ -120728,6 +122781,7 @@ async function stageProjectFilePushesV4(args) {
120728
122781
  route: "projectFile",
120729
122782
  metadata: {
120730
122783
  deferredSourceCommit: true,
122784
+ stagedUploadSessionId,
120731
122785
  uploads: batch.map((file) => ({
120732
122786
  uploadToken: file.uploadToken,
120733
122787
  projectFileId: file.recordId,
@@ -120745,12 +122799,11 @@ async function stageProjectFilePushesV4(args) {
120745
122799
  signal
120746
122800
  );
120747
122801
  const entries = readPresignEntries(presign, batch);
120748
- for (const entry of entries) cleanupKeys.push(entry.storageKey);
120749
122802
  const batchController = new AbortController();
120750
122803
  try {
120751
122804
  await mapWithConcurrency(entries, UPLOAD_CONCURRENCY, async (entry) => {
120752
122805
  try {
120753
- await putWithRetry(
122806
+ await uploadWithRetry(
120754
122807
  put,
120755
122808
  entry,
120756
122809
  combineSignals(signal, batchController.signal)
@@ -120795,15 +122848,11 @@ async function stageProjectFilePushesV4(args) {
120795
122848
  return result;
120796
122849
  });
120797
122850
  } catch (error) {
120798
- if (cleanupKeys.length > 0) {
120799
- try {
120800
- await args.client.post(
120801
- versionPath(args.workspace, "files/cleanup-staged-upload"),
120802
- { storageKeys: cleanupKeys }
120803
- );
120804
- } catch {
120805
- }
120806
- }
122851
+ await cleanupRejectedProjectFilePushesV4({
122852
+ workspace: args.workspace,
122853
+ client: args.client,
122854
+ stagedUploadSessionId
122855
+ });
120807
122856
  if (interruptController.signal.aborted || args.signal?.aborted === true) {
120808
122857
  throw new ProjectFilePushCancelledError();
120809
122858
  }
@@ -120813,7 +122862,8 @@ async function stageProjectFilePushesV4(args) {
120813
122862
  }
120814
122863
  }
120815
122864
  function readPresignEntries(presign, batch) {
120816
- 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) : [];
120817
122867
  return batch.map((file) => {
120818
122868
  const entry = entries.find((candidate) => {
120819
122869
  const info = isObjectRecord2(candidate.file) ? candidate.file : {};
@@ -120821,21 +122871,62 @@ function readPresignEntries(presign, batch) {
120821
122871
  });
120822
122872
  const fileInfo = isObjectRecord2(entry?.file) ? entry.file : {};
120823
122873
  const objectInfo = isObjectRecord2(fileInfo.objectInfo) ? fileInfo.objectInfo : {};
120824
- if (typeof entry?.signedUrl !== "string") {
122874
+ if (typeof objectInfo.key !== "string") {
120825
122875
  throw new Error(
120826
- `Upload presign response is missing signedUrl for ${file.name}.`
122876
+ `Upload presign response is missing a storage key for ${file.name}.`
120827
122877
  );
120828
122878
  }
120829
- 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") {
120830
122894
  throw new Error(
120831
- `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}.`
120832
122922
  );
120833
122923
  }
120834
122924
  return {
122925
+ protocol: "multipart",
120835
122926
  file,
120836
- signedUrl: entry.signedUrl,
120837
122927
  storageKey: objectInfo.key,
120838
- headers: uploadHeaders(entry, objectInfo, file.mimeType)
122928
+ completeSignedUrl: entry.completeSignedUrl,
122929
+ parts
120839
122930
  };
120840
122931
  });
120841
122932
  }
@@ -120854,7 +122945,11 @@ async function postWithTimeout(client, path, body, signal) {
120854
122945
  }
120855
122946
  throw new Error("Upload presign failed after all retry attempts.");
120856
122947
  }
120857
- 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
+ }
120858
122953
  let lastError;
120859
122954
  for (let attempt = 1; attempt <= STORAGE_PUT_ATTEMPTS; attempt += 1) {
120860
122955
  let response;
@@ -120886,6 +122981,83 @@ async function putWithRetry(put, entry, signal) {
120886
122981
  }
120887
122982
  throw lastError instanceof Error ? lastError : new Error(`Storage PUT failed for ${entry.file.name}.`);
120888
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
+ }
120889
123061
  function isRetryableStatus(status) {
120890
123062
  return status === 408 || status === 429 || status >= 500;
120891
123063
  }
@@ -120921,13 +123093,14 @@ async function waitForRetry(attempt, signal) {
120921
123093
  async function mapWithConcurrency(values, concurrency, run) {
120922
123094
  let nextIndex = 0;
120923
123095
  let firstError;
123096
+ const results = new Array(values.length);
120924
123097
  const worker = async () => {
120925
123098
  while (firstError === void 0) {
120926
123099
  const index = nextIndex;
120927
123100
  nextIndex += 1;
120928
123101
  if (index >= values.length) return;
120929
123102
  try {
120930
- await run(values[index]);
123103
+ results[index] = await run(values[index]);
120931
123104
  } catch (error) {
120932
123105
  firstError ??= error;
120933
123106
  }
@@ -120937,6 +123110,7 @@ async function mapWithConcurrency(values, concurrency, run) {
120937
123110
  Array.from({ length: Math.min(concurrency, values.length) }, worker)
120938
123111
  );
120939
123112
  if (firstError !== void 0) throw firstError;
123113
+ return results;
120940
123114
  }
120941
123115
  function combineSignals(...signals) {
120942
123116
  const defined = signals.filter(
@@ -120964,7 +123138,7 @@ function uploadHeaders(entry, objectInfo, mimeType) {
120964
123138
  function versionPath(workspace, suffix) {
120965
123139
  return `/api/projects/${workspace.config.projectId}/versions/${workspace.config.versionId}/${suffix}`;
120966
123140
  }
120967
- 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;
120968
123142
  var init_project_file_push = __esm({
120969
123143
  "src/project-source/project-file-push.ts"() {
120970
123144
  "use strict";
@@ -120972,6 +123146,11 @@ var init_project_file_push = __esm({
120972
123146
  init_projection();
120973
123147
  init_src();
120974
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;
120975
123154
  PRESIGN_TIMEOUT_MS = 3e4;
120976
123155
  PRESIGN_ATTEMPTS = 3;
120977
123156
  STORAGE_PUT_TIMEOUT_MS = 12e4;
@@ -121189,7 +123368,7 @@ __export(push_exports, {
121189
123368
  runPush: () => runPush,
121190
123369
  stripServerDerivedNeoScript: () => stripServerDerivedNeoScript
121191
123370
  });
121192
- import { createHash as createHash10, randomUUID as randomUUID2 } from "node:crypto";
123371
+ import { createHash as createHash10, randomUUID as randomUUID3 } from "node:crypto";
121193
123372
  import {
121194
123373
  mkdirSync as mkdirSync10,
121195
123374
  writeFileSync as writeFileSync10,
@@ -121235,7 +123414,7 @@ function assignPendingIds(changes, authoredValueSeeds, reconstructed3, localInit
121235
123414
  assigned.set(pendingId2, derived);
121236
123415
  return derived;
121237
123416
  }
121238
- const fresh = randomUUID2();
123417
+ const fresh = randomUUID3();
121239
123418
  assigned.set(pendingId2, fresh);
121240
123419
  return fresh;
121241
123420
  };
@@ -121934,6 +124113,7 @@ async function runPush(workspace, options, preparationOverride) {
121934
124113
  json: options.json === true,
121935
124114
  includeDocument: verifiesConfiguredHook,
121936
124115
  identifyArtifactErrors: true,
124116
+ refreshDerivedEdgeVersion: options.dryRun,
121937
124117
  onPhase: (label) => preparation?.update(label)
121938
124118
  });
121939
124119
  } catch (error) {
@@ -122101,6 +124281,7 @@ async function runPush(workspace, options, preparationOverride) {
122101
124281
  }
122102
124282
  const stagePreparedPush = async () => {
122103
124283
  const client2 = NeoApiClient.forBaseUrl(workspace.config.apiBaseUrl);
124284
+ const stagedUploadSessionId2 = preparedLocal.preparedFiles.length > 0 ? randomUUID3() : null;
122104
124285
  const stagedFiles2 = await stageProjectFilePushesV4({
122105
124286
  workspace,
122106
124287
  changes: status.changes,
@@ -122108,13 +124289,19 @@ async function runPush(workspace, options, preparationOverride) {
122108
124289
  assignedIds: preparedLocal.pendingAssignment.assigned,
122109
124290
  client: client2,
122110
124291
  prepared: preparedLocal.preparedFiles,
124292
+ ...stagedUploadSessionId2 === null ? {} : { stagedUploadSessionId: stagedUploadSessionId2 },
122111
124293
  onProgress: (upload) => progress.report({
122112
124294
  type: "push-progress",
122113
124295
  phase: "uploading",
122114
124296
  ...upload
122115
124297
  })
122116
124298
  });
122117
- return { ...preparedLocal, client: client2, stagedFiles: stagedFiles2 };
124299
+ return {
124300
+ ...preparedLocal,
124301
+ client: client2,
124302
+ stagedFiles: stagedFiles2,
124303
+ stagedUploadSessionId: stagedUploadSessionId2
124304
+ };
122118
124305
  };
122119
124306
  let preparedPush;
122120
124307
  try {
@@ -122135,9 +124322,9 @@ async function runPush(workspace, options, preparationOverride) {
122135
124322
  client,
122136
124323
  transportChanges,
122137
124324
  transportSeeds,
122138
- preparedFiles
124325
+ stagedUploadSessionId
122139
124326
  } = preparedPush;
122140
- let { stagedFiles } = preparedPush;
124327
+ const { stagedFiles } = preparedPush;
122141
124328
  const commit = async (force) => await client.post(
122142
124329
  `/api/projects/${workspace.config.projectId}/versions/${workspace.config.versionId}/schema/commit`,
122143
124330
  {
@@ -122146,12 +124333,14 @@ async function runPush(workspace, options, preparationOverride) {
122146
124333
  authoredValueSeeds: transportSeeds,
122147
124334
  initializerMaterialization: pendingAssignment.localInitializerMaterialization ?? { roots: [] },
122148
124335
  stagedFiles,
124336
+ stagedUploadSessionId,
122149
124337
  sourceHash: source.sourceHash,
122150
124338
  pendingIdAssignments: Object.fromEntries(pendingAssignment.assigned),
122151
124339
  summary: options.summary ?? "neo push",
122152
124340
  // P43 §4. The local evaluator computes against the pulled snapshot, so
122153
124341
  // the server rejects a push whose base is not the project head.
122154
124342
  headTransactionHash: workspace.state.headTransactionHash ?? null,
124343
+ derivedEdgeExtractorVersion: PROJECT_SNAPSHOT_DERIVED_EDGE_EXTRACTOR_VERSION,
122155
124344
  forceRecompile: options.forceRecompile === true
122156
124345
  },
122157
124346
  force ? { "x-neo-force-project-version-write": "true" } : void 0
@@ -122315,40 +124504,29 @@ async function runPush(workspace, options, preparationOverride) {
122315
124504
  fallback: false
122316
124505
  })) {
122317
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
+ });
122318
124518
  try {
122319
- stagedFiles = await stageProjectFilePushesV4({
122320
- workspace,
122321
- changes: status.changes,
122322
- binaryChanges: status.binaryChanges ?? [],
122323
- assignedIds: pendingAssignment.assigned,
122324
- client,
122325
- prepared: preparedFiles,
122326
- onProgress: (upload) => progress.report({
122327
- type: "push-progress",
122328
- phase: "uploading",
122329
- ...upload
122330
- })
122331
- });
122332
- progress.report({
122333
- type: "project-transaction-progress",
122334
- transactionId: null,
122335
- phase: "submitting",
122336
- totalChangeCount: status.changes.length,
122337
- appliedChangeCount: 0,
122338
- totalChunkCount: null,
122339
- appliedChunkCount: 0,
122340
- errorCode: null,
122341
- errorMessage: null
122342
- });
122343
124519
  result = await commit(true);
122344
124520
  } catch (retryError) {
122345
124521
  progress.stop();
122346
- if (retryError instanceof ProjectFilePushCancelledError) {
122347
- if (options.json !== true) console.error("Push cancelled.");
122348
- process.exitCode = 130;
122349
- return;
122350
- }
122351
124522
  if (retryError instanceof NeoApiError) {
124523
+ if (isDefinitiveSchemaCommitRejection(retryError)) {
124524
+ await cleanupRejectedProjectFilePushesV4({
124525
+ workspace,
124526
+ client,
124527
+ stagedUploadSessionId
124528
+ });
124529
+ }
122352
124530
  reportPushRejection(retryError.status, retryError.body);
122353
124531
  process.exitCode = 1;
122354
124532
  return;
@@ -122358,16 +124536,31 @@ async function runPush(workspace, options, preparationOverride) {
122358
124536
  await finishCommitResponse(result, progress);
122359
124537
  return;
122360
124538
  }
124539
+ await cleanupRejectedProjectFilePushesV4({
124540
+ workspace,
124541
+ client,
124542
+ stagedUploadSessionId
124543
+ });
122361
124544
  console.log("Push cancelled.");
122362
124545
  process.exitCode = 1;
122363
124546
  return;
122364
124547
  }
124548
+ if (isDefinitiveSchemaCommitRejection(error)) {
124549
+ await cleanupRejectedProjectFilePushesV4({
124550
+ workspace,
124551
+ client,
124552
+ stagedUploadSessionId
124553
+ });
124554
+ }
122365
124555
  reportPushRejection(error.status, rejection);
122366
124556
  process.exitCode = 1;
122367
124557
  return;
122368
124558
  }
122369
124559
  await finishCommitResponse(result, progress);
122370
124560
  }
124561
+ function isDefinitiveSchemaCommitRejection(error) {
124562
+ return error.status === 400 || error.status === 401 || error.status === 403 || error.status === 404 || error.status === 409;
124563
+ }
122371
124564
  async function prepareLocalPushArtifactsV4(workspace, status, onPhase = () => void 0, options = {
122372
124565
  fullValidation: true,
122373
124566
  forceRecompile: false
@@ -122479,6 +124672,14 @@ async function prepareLocalCandidateV4(workspace, options = {}) {
122479
124672
  if (status.changes.length > 0 || status.authoredValueSeeds.size > 0) {
122480
124673
  try {
122481
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
+ }
122482
124683
  preparedLocal = await prepareLocalPushArtifactsV4(
122483
124684
  workspace,
122484
124685
  documentStatus,
@@ -122914,8 +125115,10 @@ async function recoverHeadTransactionHashFromSchemaSignal(workspace) {
122914
125115
  versionId: workspace.config.versionId
122915
125116
  });
122916
125117
  workspace.state.headTransactionHash = signal?.transactionHash ?? null;
125118
+ workspace.state.derivedEdgeVersion = signal?.derivedEdgeVersion ?? null;
122917
125119
  } catch {
122918
125120
  workspace.state.headTransactionHash = null;
125121
+ delete workspace.state.derivedEdgeVersion;
122919
125122
  }
122920
125123
  }
122921
125124
  function immediateTransactionId(result) {
@@ -124131,6 +126334,7 @@ var init_push = __esm({
124131
126334
  init_merge();
124132
126335
  init_push_change_intent();
124133
126336
  init_push_body_diagnostics();
126337
+ init_project_snapshot_derived_edges();
124134
126338
  ({
124135
126339
  compileNSVoidBody: compileNSVoidBody2,
124136
126340
  compileNSFunction: compileNSFunction2,
@@ -124187,7 +126391,7 @@ var init_registry2 = __esm({
124187
126391
  PROJECT_SCHEMA_CONTRACT = Object.freeze({
124188
126392
  formatVersion: 4,
124189
126393
  contractVersion: "4.1",
124190
- cliVersion: "0.42.0",
126394
+ cliVersion: "0.43.0",
124191
126395
  projectFileUploadBatchSize: 32,
124192
126396
  documentRecords: {
124193
126397
  member: {
@@ -125610,7 +127814,7 @@ __export(test_exports, {
125610
127814
  maintainNeoTestBuildCache: () => maintainNeoTestBuildCache,
125611
127815
  runTest: () => runTest
125612
127816
  });
125613
- import { createHash as createHash11, randomUUID as randomUUID3 } from "node:crypto";
127817
+ import { createHash as createHash11, randomUUID as randomUUID4 } from "node:crypto";
125614
127818
  import {
125615
127819
  existsSync as existsSync13,
125616
127820
  mkdirSync as mkdirSync11,
@@ -126781,7 +128985,7 @@ async function executeRegisteredSpec(registered, document, selected, timeoutMs,
126781
128985
  }
126782
128986
  function atomicWrite(path, content) {
126783
128987
  mkdirSync11(dirname10(path), { recursive: true });
126784
- const temporary = `${path}.tmp-${String(process.pid)}-${randomUUID3()}`;
128988
+ const temporary = `${path}.tmp-${String(process.pid)}-${randomUUID4()}`;
126785
128989
  writeFileSync11(temporary, content, "utf8");
126786
128990
  renameSync5(temporary, path);
126787
128991
  }
@@ -127668,7 +129872,7 @@ __export(migrate_exports, {
127668
129872
  resolveWriteTarget: () => resolveWriteTarget,
127669
129873
  runMigrate: () => runMigrate
127670
129874
  });
127671
- import { randomUUID as randomUUID4 } from "node:crypto";
129875
+ import { randomUUID as randomUUID5 } from "node:crypto";
127672
129876
  import { existsSync as existsSync15, mkdirSync as mkdirSync12, readdirSync as readdirSync6, writeFileSync as writeFileSync12 } from "node:fs";
127673
129877
  import { join as join17 } from "node:path";
127674
129878
  async function runMigrate(workspace, subcommand, positional, targetRef, json, dependencies = {}) {
@@ -128653,7 +130857,7 @@ function planCollectionMutation(args) {
128653
130857
  `Migration "${migrationName}" adds a non-scalar collection entry; minting nested entries is not yet supported (build the value beforehand).`
128654
130858
  );
128655
130859
  }
128656
- const id2 = randomUUID4();
130860
+ const id2 = randomUUID5();
128657
130861
  changes.push({
128658
130862
  recordKind: "value",
128659
130863
  recordId: id2,
@@ -129443,7 +131647,7 @@ __export(content_exports, {
129443
131647
  runLoc: () => runLoc
129444
131648
  });
129445
131649
  import { readFileSync as readFileSync18 } from "node:fs";
129446
- import { randomUUID as randomUUID5 } from "node:crypto";
131650
+ import { randomUUID as randomUUID6 } from "node:crypto";
129447
131651
  function versionPath2(workspace, suffix) {
129448
131652
  return `/api/projects/${workspace.config.projectId}/versions/${workspace.config.versionId}/${suffix}`;
129449
131653
  }
@@ -129526,7 +131730,7 @@ async function runLoc(context, subcommand, positional, file) {
129526
131730
  const config = isObjectRecord2(raw.localizationConfig) ? raw.localizationConfig : {};
129527
131731
  const statusId = config.mainLocale === locale && typeof config.mainLocaleDefaultStatusId === "string" ? config.mainLocaleDefaultStatusId : "localization-status-needs-translation";
129528
131732
  const now = Date.now();
129529
- const textId = typeof body.id === "string" ? body.id : randomUUID5();
131733
+ const textId = typeof body.id === "string" ? body.id : randomUUID6();
129530
131734
  const existingHead = heads.get(`localized-text:${textId}`);
129531
131735
  const text = {
129532
131736
  id: textId,
@@ -131007,7 +133211,7 @@ There is no --keep-current: preserving current semantic state defines flatten.
131007
133211
  async function main() {
131008
133212
  const args = parseArgs(process.argv.slice(2));
131009
133213
  if (args.command === "--version") {
131010
- console.log("0.42.0");
133214
+ console.log("0.43.0");
131011
133215
  return;
131012
133216
  }
131013
133217
  if (args.command === null || args.command === "help" || args.command === "--help" || args.command === "-h") {