@neocompose/cli 0.81.0 → 0.81.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/neo.mjs CHANGED
@@ -1291,6 +1291,15 @@ function neoScriptRegistryEntryType(typeName) {
1291
1291
  }
1292
1292
  return REGISTRY_ENTRY_TYPES[typeName] ?? null;
1293
1293
  }
1294
+ function typeArgumentArityMessage(typeName, expected, provided) {
1295
+ return `Type '${typeName}' expects ${expected} type argument${expected === 1 ? "" : "s"}, but ${provided} ${provided === 1 ? "was" : "were"} provided.`;
1296
+ }
1297
+ function genericParameterArgumentsMessage(name) {
1298
+ return `Generic parameter '${name}' cannot receive type arguments.`;
1299
+ }
1300
+ function delegateArityMessage(provided) {
1301
+ return `Type 'NeoDelegate' expects a return type followed by up to ${NEOSCRIPT_DELEGATE_MAX_PARAMETERS} parameter types, but ${provided} type arguments were provided.`;
1302
+ }
1294
1303
  function neoScriptRegistryReferenceType(entryTypeName) {
1295
1304
  for (const definition2 of Object.values(REGISTRY_ENTRY_TYPES)) {
1296
1305
  if (definition2.entryType === entryTypeName) return definition2.refType;
@@ -1376,7 +1385,7 @@ function vectorTypes() {
1376
1385
  members: structuredLeafFieldProperties(name)
1377
1386
  }));
1378
1387
  }
1379
- var NEO_PROJECT_IGNORED_DIRECTORY_NAMES, NEOSCRIPT_KEYWORDS, NEOSCRIPT_INFERRED_LOCAL_KEYWORD, NEOSCRIPT_CONSTRUCTOR_KEYWORD, NEOSCRIPT_PRIMITIVE_TYPES, NEOSCRIPT_BUILTIN_ANNOTATION_TYPES, NEOSCRIPT_BUILTIN_NAMESPACES, NEOSCRIPT_BUILTIN_TYPES, NEO_VARIANT_TYPE_NAME, NEO_VARIANT_FOLDER_TYPE_NAME, NEO_LOOKUP_VARIANT_TYPE_NAME, NEO_LOOKUP_VARIANT_FOLDER_TYPE_NAME, NEO_VARIANT_SCOPE_NAME, NEO_VARIANT_RESERVED_NAME, NEO_VARIANT_FOLDER_PATH_SEPARATOR, NEOSCRIPT_OPERATORS, STRING_TYPE2, INT_TYPE2, FLOAT_TYPE, DECIMAL_TYPE, BOOL_TYPE2, IMAGE_REF_TYPE, SPRITE_INFO_TYPE, VECTOR2_TYPE, FLOAT_OPTIONAL_TYPE, NEOSCRIPT_STRUCTURED_LEAF_FIELDS, NEOSCRIPT_IMAGE_REGISTRY_TYPE, NEOSCRIPT_AUDIO_CLIP_REGISTRY_TYPE, NEOSCRIPT_PENDING_SYMBOL_ID_PREFIX, REGISTRY_ENTRY_TYPES, NEOSCRIPT_GLOBALS, NEOSCRIPT_SCALAR_METHODS, NEOSCRIPT_CLASS_ID_MEMBER, NEOSCRIPT_ON_CHANGED_MEMBER, NEOSCRIPT_CLASS_ID_SYMBOL, NEOSCRIPT_PRIMITIVE_DERIVED_MEMBERS, NEOSCRIPT_SPRITE_INFO_EMPTY_MEMBER_ID, NEOSCRIPT_SPRITE_INFO_EMPTY_VALUE, NEOSCRIPT_MATH_TYPE_ID, MATH_INFERENCE_RULE, MATH_INTEGRAL_RULE, NEOSCRIPT_LIST_TYPE_NAME, NEOSCRIPT_LIST_TYPE_ID, NEOSCRIPT_LIST_REPEAT_NAME, LIST_ENTRY_TYPE, NEOSCRIPT_BUILTIN_TYPE_SYMBOLS;
1388
+ var NEO_PROJECT_IGNORED_DIRECTORY_NAMES, NEOSCRIPT_KEYWORDS, NEOSCRIPT_INFERRED_LOCAL_KEYWORD, NEOSCRIPT_CONSTRUCTOR_KEYWORD, NEOSCRIPT_PRIMITIVE_TYPES, NEOSCRIPT_BUILTIN_ANNOTATION_TYPES, NEOSCRIPT_BUILTIN_NAMESPACES, NEOSCRIPT_BUILTIN_TYPES, NEO_VARIANT_TYPE_NAME, NEO_VARIANT_FOLDER_TYPE_NAME, NEO_LOOKUP_VARIANT_TYPE_NAME, NEO_LOOKUP_VARIANT_FOLDER_TYPE_NAME, NEO_VARIANT_SCOPE_NAME, NEO_VARIANT_RESERVED_NAME, NEO_VARIANT_FOLDER_PATH_SEPARATOR, NEOSCRIPT_OPERATORS, STRING_TYPE2, INT_TYPE2, FLOAT_TYPE, DECIMAL_TYPE, BOOL_TYPE2, IMAGE_REF_TYPE, SPRITE_INFO_TYPE, VECTOR2_TYPE, FLOAT_OPTIONAL_TYPE, NEOSCRIPT_STRUCTURED_LEAF_FIELDS, NEOSCRIPT_IMAGE_REGISTRY_TYPE, NEOSCRIPT_AUDIO_CLIP_REGISTRY_TYPE, NEOSCRIPT_PENDING_SYMBOL_ID_PREFIX, REGISTRY_ENTRY_TYPES, NEOSCRIPT_DELEGATE_MAX_PARAMETERS, NEOSCRIPT_GLOBALS, NEOSCRIPT_SCALAR_METHODS, NEOSCRIPT_CLASS_ID_MEMBER, NEOSCRIPT_ON_CHANGED_MEMBER, NEOSCRIPT_CLASS_ID_SYMBOL, NEOSCRIPT_PRIMITIVE_DERIVED_MEMBERS, NEOSCRIPT_SPRITE_INFO_EMPTY_MEMBER_ID, NEOSCRIPT_SPRITE_INFO_EMPTY_VALUE, NEOSCRIPT_MATH_TYPE_ID, MATH_INFERENCE_RULE, MATH_INTEGRAL_RULE, NEOSCRIPT_LIST_TYPE_NAME, NEOSCRIPT_LIST_TYPE_ID, NEOSCRIPT_LIST_REPEAT_NAME, LIST_ENTRY_TYPE, NEOSCRIPT_BUILTIN_TYPE_SYMBOLS;
1380
1389
  var init_language_spec = __esm({
1381
1390
  "../packages/neoscript-language/src/language-spec.ts"() {
1382
1391
  "use strict";
@@ -1652,6 +1661,7 @@ var init_language_spec = __esm({
1652
1661
  refType: { kind: "primitive", name: "AudioClipRef" }
1653
1662
  }
1654
1663
  };
1664
+ NEOSCRIPT_DELEGATE_MAX_PARAMETERS = 16;
1655
1665
  NEOSCRIPT_GLOBALS = [
1656
1666
  builtinFunction(
1657
1667
  "VisitCount",
@@ -2910,6 +2920,8 @@ function isNSFunctionVariantApply(value) {
2910
2920
  if (!isNSPointer(info.variantPointer)) return false;
2911
2921
  if (info.rowPointer !== void 0 && !isNSPointer(info.rowPointer))
2912
2922
  return false;
2923
+ if (info.declarativeReplay !== void 0 && info.declarativeReplay !== true)
2924
+ return false;
2913
2925
  return isNSTypeInfoClass(info.schemaClassInfo) && info.schemaClassInfo.required;
2914
2926
  }
2915
2927
  function isNSFunctionClassConstructor(value) {
@@ -4920,7 +4932,9 @@ function isLiteralValueContent(value) {
4920
4932
  for (const field of [
4921
4933
  "instanceConstructorId",
4922
4934
  "instanceVariantId",
4923
- "instanceVariantRowValueId"
4935
+ "instanceVariantRowValueId",
4936
+ "instanceAppliedVariantId",
4937
+ "instanceAppliedVariantRowValueId"
4924
4938
  ]) {
4925
4939
  const provenance = getField(value, field);
4926
4940
  if (provenance !== void 0 && provenance !== null && (typeof provenance !== "string" || provenance.length === 0)) {
@@ -4946,6 +4960,9 @@ function isInitValueContent(value) {
4946
4960
  if (getField(value, "instanceConstructorId") !== void 0) return false;
4947
4961
  if (getField(value, "instanceVariantId") !== void 0) return false;
4948
4962
  if (getField(value, "instanceVariantRowValueId") !== void 0) return false;
4963
+ if (getField(value, "instanceAppliedVariantId") !== void 0) return false;
4964
+ if (getField(value, "instanceAppliedVariantRowValueId") !== void 0)
4965
+ return false;
4949
4966
  const classIdField = getField(value, "classId");
4950
4967
  return classIdField === void 0 || classIdField === null;
4951
4968
  }
@@ -5949,7 +5966,11 @@ function encodeStoredValueNode(node) {
5949
5966
  ...node.constructorArgs === void 0 ? {} : { constructorArgs: node.constructorArgs },
5950
5967
  ...node.instanceConstructorId === void 0 ? {} : { instanceConstructorId: node.instanceConstructorId },
5951
5968
  ...node.instanceVariantId === void 0 ? {} : { instanceVariantId: node.instanceVariantId },
5952
- ...node.instanceVariantRowValueId === void 0 ? {} : { instanceVariantRowValueId: node.instanceVariantRowValueId }
5969
+ ...node.instanceVariantRowValueId === void 0 ? {} : { instanceVariantRowValueId: node.instanceVariantRowValueId },
5970
+ ...node.instanceAppliedVariantId === void 0 ? {} : { instanceAppliedVariantId: node.instanceAppliedVariantId },
5971
+ ...node.instanceAppliedVariantRowValueId === void 0 ? {} : {
5972
+ instanceAppliedVariantRowValueId: node.instanceAppliedVariantRowValueId
5973
+ }
5953
5974
  };
5954
5975
  }
5955
5976
  function encodeStoredValueRowFields(row) {
@@ -5976,6 +5997,9 @@ function canonicalInstanceProvenanceViolation(value) {
5976
5997
  if ("instanceVariantRowValueId" in value && typeof value.instanceVariantRowValueId === "string" && typeof variantId !== "string") {
5977
5998
  return "variant-row-without-variant";
5978
5999
  }
6000
+ if ("instanceAppliedVariantRowValueId" in value && typeof value.instanceAppliedVariantRowValueId === "string" && !("instanceAppliedVariantId" in value && typeof value.instanceAppliedVariantId === "string")) {
6001
+ return "applied-variant-row-without-applied-variant";
6002
+ }
5979
6003
  return null;
5980
6004
  }
5981
6005
  var init_value_graph = __esm({
@@ -6005,7 +6029,11 @@ function pickInstanceProvenance(source) {
6005
6029
  ...source.constructorArgs === void 0 ? {} : { constructorArgs: source.constructorArgs },
6006
6030
  ...source.instanceConstructorId === void 0 ? {} : { instanceConstructorId: source.instanceConstructorId },
6007
6031
  ...source.instanceVariantId === void 0 ? {} : { instanceVariantId: source.instanceVariantId },
6008
- ...source.instanceVariantRowValueId === void 0 ? {} : { instanceVariantRowValueId: source.instanceVariantRowValueId }
6032
+ ...source.instanceVariantRowValueId === void 0 ? {} : { instanceVariantRowValueId: source.instanceVariantRowValueId },
6033
+ ...source.instanceAppliedVariantId === void 0 ? {} : { instanceAppliedVariantId: source.instanceAppliedVariantId },
6034
+ ...source.instanceAppliedVariantRowValueId === void 0 ? {} : {
6035
+ instanceAppliedVariantRowValueId: source.instanceAppliedVariantRowValueId
6036
+ }
6009
6037
  };
6010
6038
  }
6011
6039
  function isVirtualInstanceRootShape(value) {
@@ -6033,6 +6061,8 @@ var init_instance_provenance = __esm({
6033
6061
  "instanceConstructorId",
6034
6062
  "instanceVariantId",
6035
6063
  "instanceVariantRowValueId",
6064
+ "instanceAppliedVariantId",
6065
+ "instanceAppliedVariantRowValueId",
6036
6066
  "genericBindings"
6037
6067
  ];
6038
6068
  }
@@ -6299,7 +6329,7 @@ function decodeContentField(container, field, scope, children) {
6299
6329
  )
6300
6330
  };
6301
6331
  }
6302
- const decoded = {};
6332
+ const decoded = /* @__PURE__ */ Object.create(null);
6303
6333
  for (const [key, entry] of Object.entries(
6304
6334
  container
6305
6335
  )) {
@@ -6451,7 +6481,7 @@ function encodeContentField(container, pending, scope) {
6451
6481
  }
6452
6482
  if (typeof container !== "object" || container === null) return null;
6453
6483
  let changed = false;
6454
- const encoded = {};
6484
+ const encoded = /* @__PURE__ */ Object.create(null);
6455
6485
  for (const [key, entry] of Object.entries(
6456
6486
  container
6457
6487
  )) {
@@ -12119,12 +12149,8 @@ function evaluateLiteralContainer(args) {
12119
12149
  const literal3 = {
12120
12150
  value: evaluated.value,
12121
12151
  classId: evaluated.classId,
12122
- ...evaluated.constructorArgs === void 0 ? {} : { constructorArgs: deepClonePlainData(evaluated.constructorArgs) },
12123
- ...evaluated.instanceConstructorId === void 0 ? {} : { instanceConstructorId: evaluated.instanceConstructorId },
12124
- ...evaluated.instanceVariantId === void 0 ? {} : { instanceVariantId: evaluated.instanceVariantId },
12125
- ...evaluated.instanceVariantRowValueId === void 0 ? {} : {
12126
- instanceVariantRowValueId: evaluated.instanceVariantRowValueId
12127
- }
12152
+ ...pickInstanceProvenance(evaluated),
12153
+ ...evaluated.constructorArgs === void 0 ? {} : { constructorArgs: deepClonePlainData(evaluated.constructorArgs) }
12128
12154
  };
12129
12155
  if (isMemberLookupBase(args.member)) {
12130
12156
  if (evaluated.existingValueRow !== void 0) {
@@ -12457,15 +12483,9 @@ function buildNewValue(projectId, body, timestamp2 = Date.now()) {
12457
12483
  if (body.constructorArgs !== void 0 && body.constructorArgs !== null) {
12458
12484
  props.constructorArgs = deepClonePlainData(body.constructorArgs);
12459
12485
  }
12460
- if (body.instanceConstructorId !== void 0) {
12461
- props.instanceConstructorId = body.instanceConstructorId;
12462
- }
12463
- if (body.instanceVariantId !== void 0) {
12464
- props.instanceVariantId = body.instanceVariantId;
12465
- }
12466
- if (body.instanceVariantRowValueId !== void 0) {
12467
- props.instanceVariantRowValueId = body.instanceVariantRowValueId;
12468
- }
12486
+ const { constructorArgs: _constructorArgs, ...provenance } = pickInstanceProvenance(body);
12487
+ void _constructorArgs;
12488
+ Object.assign(props, provenance);
12469
12489
  return props;
12470
12490
  }
12471
12491
  function retargetInitializerRootValueIds(rows, fromValueId, toValueId) {
@@ -12657,7 +12677,7 @@ function cloneDefaultDictionaryRecord(args) {
12657
12677
  args.document,
12658
12678
  args.member.entryMemberId
12659
12679
  );
12660
- const value = {};
12680
+ const value = /* @__PURE__ */ Object.create(null);
12661
12681
  for (const [key, sourceValueId] of Object.entries(sourceValue)) {
12662
12682
  value[key] = cloneDefaultValueForMember({
12663
12683
  document: args.document,
@@ -12934,9 +12954,7 @@ function cloneMemberValueBase(body) {
12934
12954
  return {
12935
12955
  value: deepClonePlainData(body.value),
12936
12956
  classId: body.classId,
12937
- ...body.instanceConstructorId === void 0 ? {} : { instanceConstructorId: body.instanceConstructorId },
12938
- ...body.instanceVariantId === void 0 ? {} : { instanceVariantId: body.instanceVariantId },
12939
- ...body.instanceVariantRowValueId === void 0 ? {} : { instanceVariantRowValueId: body.instanceVariantRowValueId },
12957
+ ...pickInstanceProvenance({ ...body, constructorArgs: void 0 }),
12940
12958
  ...body.constructorArgs === void 0 || body.constructorArgs === null ? {} : {
12941
12959
  constructorArgs: deepClonePlainData(body.constructorArgs)
12942
12960
  }
@@ -13246,6 +13264,7 @@ var init_build_default_member_value = __esm({
13246
13264
  "../packages/models/src/members/build-default-member-value.ts"() {
13247
13265
  "use strict";
13248
13266
  init_member_value_id();
13267
+ init_instance_provenance();
13249
13268
  init_member_change_listeners();
13250
13269
  init_construction_requirements();
13251
13270
  init_deep_clone_plain_data();
@@ -24236,7 +24255,7 @@ function toCanonical(value) {
24236
24255
  if (Array.isArray(value)) return value.map((item) => toCanonical(item));
24237
24256
  if (typeof value === "object") {
24238
24257
  const entries = Object.entries(value).filter(([, entryValue]) => entryValue !== void 0).sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0);
24239
- const result = {};
24258
+ const result = /* @__PURE__ */ Object.create(null);
24240
24259
  for (const [key, entryValue] of entries) {
24241
24260
  result[key] = toCanonical(entryValue);
24242
24261
  }
@@ -30973,21 +30992,34 @@ function resolveNeoScriptType(type, context, project) {
30973
30992
  const declaringType = declaringTypeRef?.kind === "named" ? project.typeById.get(declaringTypeRef.typeId) : void 0;
30974
30993
  const byName = (candidate) => candidate.name === type.name;
30975
30994
  const typeParameter2 = context.typeParameters?.find(byName) ?? declaringType?.typeParameters?.find(byName);
30995
+ const written = type.typeArguments?.length ?? 0;
30976
30996
  if (typeParameter2?.type.kind === "typeParameter") {
30997
+ if (written > 0)
30998
+ throw new CompileError(
30999
+ genericParameterArgumentsMessage(type.name),
31000
+ type.pos
31001
+ );
30977
31002
  resolved = typeParameter2.type;
30978
31003
  break;
30979
31004
  }
30980
31005
  const builtin = namedPrimitive(type.name);
31006
+ const registryReference = builtin ? null : neoScriptRegistryReferenceType(type.name);
31007
+ if ((builtin || registryReference) && written > 0)
31008
+ throw new CompileError(
31009
+ typeArgumentArityMessage(type.name, 0, written),
31010
+ type.pos
31011
+ );
30981
31012
  if (builtin) {
30982
31013
  resolved = { kind: "primitive", name: builtin };
30983
31014
  break;
30984
31015
  }
30985
- const registryReference = neoScriptRegistryReferenceType(type.name);
30986
31016
  if (registryReference) {
30987
31017
  resolved = registryReference;
30988
31018
  break;
30989
31019
  }
30990
31020
  if (type.name === "NeoDelegate") {
31021
+ if (written > NEOSCRIPT_DELEGATE_MAX_PARAMETERS + 1)
31022
+ throw new CompileError(delegateArityMessage(written), type.pos);
30991
31023
  const [returnType, ...parameterTypes] = (type.typeArguments ?? []).map(
30992
31024
  (argument2) => resolveNeoScriptType(argument2, context, project)
30993
31025
  );
@@ -31005,6 +31037,7 @@ function resolveNeoScriptType(type, context, project) {
31005
31037
  renamedDialogueTypeMessage(type.name, "value") ?? `Unknown type '${type.name}'`,
31006
31038
  type.pos
31007
31039
  );
31040
+ if (written > 0) assertTypeArgumentCount(named, written, type.pos);
31008
31041
  resolved = {
31009
31042
  kind: "named",
31010
31043
  typeId: named.id,
@@ -31073,6 +31106,14 @@ function assertDirectTypeParameterArguments(target, pos, project) {
31073
31106
  const message = wrappedTypeParameterMessage(target, project);
31074
31107
  if (message !== null) throw new CompileError(message, pos);
31075
31108
  }
31109
+ function assertTypeArgumentCount(declaring, count, pos) {
31110
+ const expected = declaring.typeParameters?.length ?? 0;
31111
+ if (count === expected) return;
31112
+ throw new CompileError(
31113
+ typeArgumentArityMessage(declaring.name, expected, count),
31114
+ pos
31115
+ );
31116
+ }
31076
31117
  function assertTypeArgumentConstraints(declaring, type, pos, project) {
31077
31118
  declaring.typeParameters?.forEach((parameter4, index) => {
31078
31119
  const argument2 = type.typeArguments?.[index];
@@ -35693,7 +35734,7 @@ var init_strict_resolver = __esm({
35693
35734
  };
35694
35735
  }
35695
35736
  resolveDictionaryKey(expectedKey, keyAst, scope, pos, requireNonOptional, dictionaryLiteral = false) {
35696
- const key = this.resolveExpression(keyAst, scope);
35737
+ const key = this.resolveExpression(keyAst, scope, expectedKey);
35697
35738
  if (requireNonOptional && isNullable(key.type)) {
35698
35739
  throw new CompileError(
35699
35740
  `Dictionary keys must be non-optional; got ${this.describe(key.type)}`,
@@ -36840,13 +36881,12 @@ var init_strict_resolver = __esm({
36840
36881
  const typeArguments = expression.typeArguments?.map(
36841
36882
  (argument2) => this.resolveType(argument2)
36842
36883
  );
36843
- if (typeArguments !== void 0 && typeArguments.length !== (schemaClass2.typeParameters?.length ?? 0)) {
36844
- throw new CompileError(
36845
- `Class '${schemaClass2.name}' expects ${schemaClass2.typeParameters?.length ?? 0} type argument${schemaClass2.typeParameters?.length === 1 ? "" : "s"} but got ${typeArguments.length}.`,
36884
+ if (typeArguments !== void 0) {
36885
+ assertTypeArgumentCount(
36886
+ schemaClass2,
36887
+ typeArguments.length,
36846
36888
  expression.pos
36847
36889
  );
36848
- }
36849
- if (typeArguments !== void 0) {
36850
36890
  const target = {
36851
36891
  kind: "named",
36852
36892
  typeId: schemaClass2.id,
@@ -50937,20 +50977,20 @@ function validateTypeApplication(uri, type, genericParameters, environment, diag
50937
50977
  uri,
50938
50978
  type.range,
50939
50979
  "generic-parameter-arguments",
50940
- `Generic parameter '${type.name}' cannot receive type arguments.`
50980
+ genericParameterArgumentsMessage(type.name)
50941
50981
  );
50942
50982
  }
50943
50983
  return;
50944
50984
  }
50945
50985
  const target = environment.declarations.get(type.name);
50946
50986
  if (type.name === "NeoDelegate") {
50947
- if (type.typeArguments.length < 1 || type.typeArguments.length > 17) {
50987
+ if (type.typeArguments.length < 1 || type.typeArguments.length > NEOSCRIPT_DELEGATE_MAX_PARAMETERS + 1) {
50948
50988
  diagnose(
50949
50989
  diagnostics,
50950
50990
  uri,
50951
50991
  type.range,
50952
50992
  "generic-argument-arity",
50953
- `Type 'NeoDelegate' expects a return type followed by up to 16 parameter types, but ${type.typeArguments.length} type arguments were provided.`
50993
+ delegateArityMessage(type.typeArguments.length)
50954
50994
  );
50955
50995
  }
50956
50996
  return;
@@ -50965,13 +51005,13 @@ function validateTypeApplication(uri, type, genericParameters, environment, diag
50965
51005
  "Type 'NeoAction' cannot use 'void' as a parameter type; spell a zero-argument action as bare 'NeoAction'."
50966
51006
  );
50967
51007
  }
50968
- if (type.typeArguments.length > 16) {
51008
+ if (type.typeArguments.length > NEOSCRIPT_DELEGATE_MAX_PARAMETERS) {
50969
51009
  diagnose(
50970
51010
  diagnostics,
50971
51011
  uri,
50972
51012
  type.range,
50973
51013
  "generic-argument-arity",
50974
- `Type 'NeoAction' expects up to 16 parameter types, but ${type.typeArguments.length} type arguments were provided.`
51014
+ `Type 'NeoAction' expects up to ${NEOSCRIPT_DELEGATE_MAX_PARAMETERS} parameter types, but ${type.typeArguments.length} type arguments were provided.`
50975
51015
  );
50976
51016
  }
50977
51017
  if (type.nullable) {
@@ -50993,7 +51033,7 @@ function validateTypeApplication(uri, type, genericParameters, environment, diag
50993
51033
  uri,
50994
51034
  type.range,
50995
51035
  "generic-argument-arity",
50996
- `Type '${type.name}' expects ${expected} type argument${expected === 1 ? "" : "s"}, but ${type.typeArguments.length} ${type.typeArguments.length === 1 ? "was" : "were"} provided.`,
51036
+ typeArgumentArityMessage(type.name, expected, type.typeArguments.length),
50997
51037
  target ? related(target.location, "The type declaration is here.") : void 0
50998
51038
  );
50999
51039
  return;
@@ -54524,7 +54564,7 @@ var init_registry = __esm({
54524
54564
  "../packages/manifest/schema-contract/registry.mjs"() {
54525
54565
  "use strict";
54526
54566
  PROJECT_SCHEMA_CONTRACT = Object.freeze({
54527
- cliVersion: "0.81.0",
54567
+ cliVersion: "0.81.2",
54528
54568
  projectFileUploadBatchSize: 32,
54529
54569
  documentRecords: {
54530
54570
  member: {
@@ -65746,7 +65786,7 @@ function toCanonicalJsonValue(value) {
65746
65786
  });
65747
65787
  }
65748
65788
  const entries = Object.entries(value).sort(([a], [b]) => a.localeCompare(b));
65749
- const canonicalObject = {};
65789
+ const canonicalObject = /* @__PURE__ */ Object.create(null);
65750
65790
  for (const [key, entryValue] of entries) {
65751
65791
  const canonicalValue = toCanonicalJsonValue(entryValue);
65752
65792
  if (canonicalValue === void 0) continue;
@@ -75948,6 +75988,7 @@ function makeUnindexedEvaluatorLookups(members, storedValues) {
75948
75988
  hasStoredValueId: (id2) => valueById.has(id2),
75949
75989
  unorderedListEntryIds: (containerValueId) => unorderedListMembership.get(containerValueId) ?? [],
75950
75990
  virtualInstanceRowsForValue: () => [],
75991
+ virtualInstanceRootIdForValue: () => null,
75951
75992
  rowForValueReference: (value) => valueRefMap.get(value) ?? null
75952
75993
  };
75953
75994
  }
@@ -76000,6 +76041,7 @@ function createInitializerBatchLookups(document) {
76000
76041
  },
76001
76042
  rowForValueReference: (value) => build.result.rowByValueReference.get(value) ?? null,
76002
76043
  virtualInstanceRowsForValue: () => [],
76044
+ virtualInstanceRootIdForValue: () => null,
76003
76045
  evaluatorIndexes: { ...build.result },
76004
76046
  constructorInitializerIndexes: constructorInitializerIndexes2
76005
76047
  });
@@ -76201,6 +76243,7 @@ function createEvaluatorLookupsBuild(members, storedValues, options = {}) {
76201
76243
  hasStoredValueId: (id2) => valueById.has(id2),
76202
76244
  unorderedListEntryIds: (containerValueId) => unorderedListMembership.get(containerValueId) ?? [],
76203
76245
  virtualInstanceRowsForValue: () => [],
76246
+ virtualInstanceRootIdForValue: () => null,
76204
76247
  rowForValueReference: (value) => rowByValueReference.get(value) ?? null,
76205
76248
  evaluatorIndexes: indexes3.result,
76206
76249
  ...options.constructorInitializerDocument === void 0 ? {} : {
@@ -76318,6 +76361,7 @@ function layerEvaluatorLookups(base, overlay) {
76318
76361
  hasStoredValueId: (id2) => overlay.rows.has(id2) || !overlay.hiddenIds.has(id2) && (base.hasStoredValueId?.(id2) ?? false),
76319
76362
  unorderedListEntryIds: unorderedListEntryIds2,
76320
76363
  virtualInstanceRowsForValue: () => [],
76364
+ virtualInstanceRootIdForValue: () => null,
76321
76365
  rowForValueReference: (value) => evaluatorIndexes2.rowByValueReference.get(value) ?? null,
76322
76366
  evaluatorIndexes: evaluatorIndexes2,
76323
76367
  constructorInitializerIndexes: constructorInitializerIndexes2
@@ -76723,13 +76767,15 @@ function bindThisValue(ctx, thisValue) {
76723
76767
  function observeValueWrite(ctx, row) {
76724
76768
  ctx.beforeValueWrite?.(row);
76725
76769
  ctx.__getterSubscriptions?.noteValueWrite(row.id);
76770
+ forgetVariantResolutionCopy(ctx, row.id);
76726
76771
  }
76727
76772
  function assertStoredReplayMutableValue(value, ctx, label, key) {
76728
- const observesWrites = ctx.beforeValueWrite !== void 0 || ctx.__getterSubscriptions?.empty === false;
76773
+ const observesWrites = ctx.beforeValueWrite !== void 0 || ctx.__getterSubscriptions?.empty === false || hasVariantResolutionCopies(ctx);
76729
76774
  if (ctx.storedConstructionReplay !== true && !ctx.assertValueWritable && !observesWrites)
76730
76775
  return;
76731
76776
  let rowId = findKnownRowIdByValueReference(value, ctx);
76732
76777
  if (rowId === null) return;
76778
+ forgetVariantResolutionCopy(ctx, rowId);
76733
76779
  const container = ctx.beforeValueWrite && evalValueById(ctx, rowId, ctx.__runtimeSessionValues, ctx.__valueOverlay);
76734
76780
  if (container) ctx.beforeValueWrite?.(container);
76735
76781
  if (key !== void 0 && value !== null && typeof value === "object") {
@@ -77362,7 +77408,7 @@ function readNeoScriptRuntimeRow(ctx, valueId) {
77362
77408
  }
77363
77409
  function inspectNeoScriptValueReference(ctx, value, collection, index) {
77364
77410
  let id2 = findKnownRowIdByValueReference(value, ctx);
77365
- if (id2 === null && collection !== void 0 && index !== void 0 && typeof value === "string" && (findKnownRowIdByValueReference(collection, ctx) !== null || Array.isArray(collection) && typeof index === "number" && ctx.__unorderedListProjections?.referenceEntryIndexesByArray.get(collection)?.has(index) || typeof collection === "object" && collection !== null && typeof index === "string" && ctx.__unorderedListProjections?.referenceEntryKeysByRecord.get(collection)?.has(index))) {
77411
+ if (id2 === null && collection !== void 0 && index !== void 0 && typeof value === "string" && isReferenceEntry(collectionReferences(collection, ctx), index)) {
77366
77412
  id2 = value;
77367
77413
  }
77368
77414
  if (id2 === null) return null;
@@ -79023,15 +79069,9 @@ function evalActionListenerInstruction(ins, scope, ctx, options) {
79023
79069
  }
79024
79070
  let destination;
79025
79071
  const target = ins.target.pointer;
79026
- const currentValue = target.type === "keyOf" /* keyOf */ ? evalKeyOf(
79027
- target.keyOf,
79028
- scope,
79029
- ctx,
79030
- target.optional === true,
79031
- (resolved) => {
79032
- destination = resolved;
79033
- }
79034
- ) : evalPointer(target, scope, ctx);
79072
+ const currentValue = target.type === "keyOf" /* keyOf */ ? evalKeyOf(target, scope, ctx, (resolved) => {
79073
+ destination = resolved;
79074
+ }) : evalPointer(target, scope, ctx);
79035
79075
  const current = actionListenersOf(currentValue, () => `'${operator}' target`);
79036
79076
  const identity2 = nsActionListenerIdentity(listener);
79037
79077
  const present = current.some(
@@ -79102,38 +79142,26 @@ function applyOverlayAssignment(target, targetTypeInfo, value, scope, ctx, desti
79102
79142
  );
79103
79143
  }
79104
79144
  receiver[index] = referenceValueId;
79105
- setCollectionReferenceProvenance(receiver, index, true, ctx);
79145
+ recordWrittenEntry(receiver, index, true, ctx);
79106
79146
  invalidateEvaluatorIndexes(ctx, receiver);
79107
79147
  return;
79108
79148
  }
79109
- if (ctx.__unorderedListProjections?.referenceEntryIndexesByArray.has(
79110
- receiver
79111
- ) === true) {
79112
- receiver[index] = value;
79113
- setCollectionReferenceProvenance(receiver, index, false, ctx);
79114
- invalidateEvaluatorIndexes(ctx, receiver);
79149
+ if (collectionReferences(receiver, ctx) === 0 /* RowIds */ && replaceEntryRowValue(
79150
+ receiver,
79151
+ receiver[index],
79152
+ value,
79153
+ targetTypeInfo,
79154
+ ctx
79155
+ ))
79115
79156
  return;
79116
- }
79117
- const existing2 = receiver[index];
79118
- if (typeof existing2 === "string") {
79119
- const row = evalValueById(
79120
- ctx,
79121
- existing2,
79122
- ctx.__runtimeSessionValues,
79123
- ctx.__valueOverlay
79124
- );
79125
- if (row !== null) {
79126
- replaceRowValue(row, value, receiver, ctx);
79127
- updateUnorderedListProjectionAfterAssignment(row, value, ctx);
79128
- return;
79129
- }
79130
- }
79131
79157
  receiver[index] = value;
79158
+ recordWrittenEntry(receiver, index, false, ctx);
79132
79159
  invalidateEvaluatorIndexes(ctx, receiver);
79133
79160
  return;
79134
79161
  }
79135
79162
  const object2 = objectArg(receiver, "Assignment target");
79136
79163
  const stringKey = String(key);
79164
+ const field = target.memberId !== void 0;
79137
79165
  if (referenceValueId !== null) {
79138
79166
  const parentId = findKnownRowIdByValueReference(receiver, ctx);
79139
79167
  if (parentId !== null) {
@@ -79148,26 +79176,41 @@ function applyOverlayAssignment(target, targetTypeInfo, value, scope, ctx, desti
79148
79176
  );
79149
79177
  }
79150
79178
  object2[stringKey] = referenceValueId;
79179
+ if (!field) recordWrittenEntry(object2, stringKey, true, ctx);
79151
79180
  invalidateEvaluatorIndexes(ctx, receiver);
79152
79181
  return;
79153
79182
  }
79154
- const existing = object2[stringKey];
79155
- if (typeof existing === "string") {
79156
- const row = evalValueById(
79157
- ctx,
79158
- existing,
79159
- ctx.__runtimeSessionValues,
79160
- ctx.__valueOverlay
79161
- );
79162
- if (row !== null) {
79163
- replaceRowValue(row, value, receiver, ctx);
79164
- updateUnorderedListProjectionAfterAssignment(row, value, ctx);
79165
- return;
79166
- }
79167
- }
79183
+ if (collectionReferences(object2, ctx) === 0 /* RowIds */ && replaceEntryRowValue(object2, object2[stringKey], value, targetTypeInfo, ctx))
79184
+ return;
79168
79185
  object2[stringKey] = value;
79186
+ if (!field) recordWrittenEntry(object2, stringKey, false, ctx);
79169
79187
  invalidateEvaluatorIndexes(ctx, receiver);
79170
79188
  }
79189
+ function replaceEntryRowValue(receiver, existing, value, targetTypeInfo, ctx) {
79190
+ if (typeof existing !== "string") return false;
79191
+ const row = evalValueById(
79192
+ ctx,
79193
+ existing,
79194
+ ctx.__runtimeSessionValues,
79195
+ ctx.__valueOverlay
79196
+ );
79197
+ if (row === null) return false;
79198
+ keepAssignedCollectionValues(value, targetTypeInfo, ctx);
79199
+ replaceRowValue(row, value, receiver, ctx);
79200
+ updateUnorderedListProjectionAfterAssignment(row, value, ctx);
79201
+ return true;
79202
+ }
79203
+ function keepAssignedCollectionValues(value, targetTypeInfo, ctx) {
79204
+ const cache = unorderedListProjectionCache(ctx);
79205
+ if (Array.isArray(value) && (targetTypeInfo.type === 6 /* List */ || targetTypeInfo.type === 28 /* Set */)) {
79206
+ if (!cache.referenceEntryIndexesByArray.has(value))
79207
+ cache.referenceEntryIndexesByArray.set(value, /* @__PURE__ */ new Set());
79208
+ return;
79209
+ }
79210
+ if (targetTypeInfo.type === 5 /* Dictionary */ && typeof value === "object" && value !== null && !cache.referenceEntryKeysByRecord.has(value)) {
79211
+ cache.referenceEntryKeysByRecord.set(value, /* @__PURE__ */ new Set());
79212
+ }
79213
+ }
79171
79214
  function replaceRowValue(row, value, receiver, ctx) {
79172
79215
  const indexes3 = ctx.__indexes;
79173
79216
  if (indexes3 === void 0 || ctx.__runtimeSessionValues?.get(row.id) !== row || !indexes3.indexedRowIds.has(row.id)) {
@@ -79605,9 +79648,11 @@ function evalCollectionMutationInstruction(ins, scope, ctx, options) {
79605
79648
  );
79606
79649
  }
79607
79650
  const unorderedEntriesBeforeMutation = unorderedContainerValueId === null || !Array.isArray(targetValue) || ins.mutation === "Add" /* Add */ ? null : [...targetValue];
79608
- if ((ins.mutation === "Add" /* Add */ || ins.mutation === "Insert" /* Insert */) && !isLookupSet) {
79651
+ const writesEntry = (ins.mutation === "Add" /* Add */ || ins.mutation === "Insert" /* Insert */) && !isLookupSet;
79652
+ let attachedValueId = null;
79653
+ if (writesEntry) {
79609
79654
  const attachedValue = isArrayCollection(targetValue) && ins.mutation !== "Insert" /* Insert */ ? args[0] : args[1];
79610
- const attachedValueId = findKnownRowIdByValueReference(attachedValue, ctx);
79655
+ attachedValueId = findKnownRowIdByValueReference(attachedValue, ctx);
79611
79656
  const parentId = findKnownRowIdByValueReference(targetValue, ctx);
79612
79657
  if (attachedValueId !== null && parentId !== null) {
79613
79658
  ctx.assertCollectionEntryAttachable?.(
@@ -79644,6 +79689,23 @@ function evalCollectionMutationInstruction(ins, scope, ctx, options) {
79644
79689
  removedIndex,
79645
79690
  ctx
79646
79691
  );
79692
+ if (writesEntry && !(targetValue instanceof RuntimeSet)) {
79693
+ const writtenAsRowId = attachedValueId !== null || unorderedContainerValueId !== null;
79694
+ if (Array.isArray(targetValue))
79695
+ recordWrittenEntry(
79696
+ targetValue,
79697
+ removedIndex ?? targetValue.length - 1,
79698
+ writtenAsRowId,
79699
+ ctx
79700
+ );
79701
+ else
79702
+ recordWrittenEntry(
79703
+ objectArg(targetValue, "Dictionary Add target"),
79704
+ String(args[0]),
79705
+ writtenAsRowId,
79706
+ ctx
79707
+ );
79708
+ }
79647
79709
  if (unorderedEntriesBeforeMutation !== null && Array.isArray(targetValue)) {
79648
79710
  detachRemovedUnorderedScalarEntries(
79649
79711
  unorderedEntriesBeforeMutation,
@@ -79845,9 +79907,10 @@ function runtimeSet(array3, reference2, enumEntries, ctx) {
79845
79907
  const existing = sets.get(array3);
79846
79908
  if (existing !== void 0) return existing;
79847
79909
  const set = new RuntimeSet(array3, reference2, enumEntries);
79910
+ const references = collectionReferences(array3, ctx);
79848
79911
  for (let index = 0; index < array3.length; index++) {
79849
79912
  const raw = array3[index];
79850
- const resolves = collectionEntryUsesReferenceResolution(array3, index, ctx);
79913
+ const resolves = isReferenceEntry(references, index);
79851
79914
  const value = resolves ? resolveValueIfId(raw, ctx) : raw;
79852
79915
  const key = runtimeSetKey(value, set, ctx);
79853
79916
  set.add(key, enumEntries ? key : raw, !enumEntries && resolves);
@@ -79856,9 +79919,9 @@ function runtimeSet(array3, reference2, enumEntries, ctx) {
79856
79919
  (ctx.__dirtyRuntimeSets ??= /* @__PURE__ */ new Set()).add(set);
79857
79920
  return set;
79858
79921
  }
79859
- function storedSetEntryMatch(raw, entryMember, ctx) {
79922
+ function storedSetEntryMatch(raw, reference2, entryMember, ctx) {
79860
79923
  const byIdentity = entryMember.kind === 7 /* Class */;
79861
- const row = byIdentity || typeof raw !== "string" ? null : evalValueById(ctx, raw, ctx.__runtimeSessionValues, ctx.__valueOverlay);
79924
+ const row = byIdentity || !reference2 || typeof raw !== "string" ? null : evalValueById(ctx, raw, ctx.__runtimeSessionValues, ctx.__valueOverlay);
79862
79925
  const valueId = byIdentity && typeof raw === "string" ? raw : row?.id ?? null;
79863
79926
  const entry = row === null ? { id: "", value: raw } : { id: row.id, value: row.value };
79864
79927
  const key = byIdentity ? valueId ?? referenceIdOf(raw, ctx) : setEntryKey(entryMember, entry);
@@ -79869,8 +79932,14 @@ function storedSetEntries(set, entryMember, ctx) {
79869
79932
  const existing = indexes3.get(set);
79870
79933
  if (existing !== void 0) return existing;
79871
79934
  const entries = /* @__PURE__ */ new Map();
79872
- for (const raw of set) {
79873
- const match = storedSetEntryMatch(raw, entryMember, ctx);
79935
+ const references = collectionReferences(set, ctx);
79936
+ for (let index = 0; index < set.length; index++) {
79937
+ const match = storedSetEntryMatch(
79938
+ set[index],
79939
+ isReferenceEntry(references, index),
79940
+ entryMember,
79941
+ ctx
79942
+ );
79874
79943
  if (match !== null && !entries.has(match.key)) {
79875
79944
  entries.set(match.key, match);
79876
79945
  }
@@ -79882,7 +79951,13 @@ function syncStoredSetEntries(set, mutation, removed, entryMember, ctx) {
79882
79951
  const entries = ctx.__setEntryIndexes?.get(set);
79883
79952
  if (entries === void 0) return;
79884
79953
  if (entryMember !== null && mutation === "Add" /* Add */) {
79885
- const added = storedSetEntryMatch(set[set.length - 1], entryMember, ctx);
79954
+ const index = set.length - 1;
79955
+ const added = storedSetEntryMatch(
79956
+ set[index],
79957
+ isReferenceEntry(collectionReferences(set, ctx), index),
79958
+ entryMember,
79959
+ ctx
79960
+ );
79886
79961
  if (added !== null) entries.set(added.key, added);
79887
79962
  return;
79888
79963
  }
@@ -79948,6 +80023,7 @@ function applyLocalCollectionMutation(targetValue, mutation, args, ctx, unique =
79948
80023
  return null;
79949
80024
  case "Remove" /* Remove */:
79950
80025
  if (Array.isArray(targetValue)) {
80026
+ const references = resolveRemovalEntries ? collectionReferences(targetValue, ctx) : recordedReferenceEntries(targetValue, ctx) ?? 1 /* Values */;
79951
80027
  let index = -1;
79952
80028
  for (let candidate = 0; candidate < targetValue.length; candidate += 1) {
79953
80029
  const entry = targetValue[candidate];
@@ -79958,9 +80034,8 @@ function applyLocalCollectionMutation(targetValue, mutation, args, ctx, unique =
79958
80034
  }
79959
80035
  continue;
79960
80036
  }
79961
- const referenceEntry = ctx.__unorderedListProjections?.referenceEntryIndexesByArray.get(targetValue)?.has(candidate) === true;
79962
80037
  if (jsEqual(
79963
- resolveRemovalEntries || referenceEntry ? resolveCollectionEntry(targetValue, entry, candidate, ctx) : entry,
80038
+ typeof entry === "string" && isReferenceEntry(references, candidate) ? resolveValueIfId(entry, ctx) : entry,
79964
80039
  args[0]
79965
80040
  )) {
79966
80041
  index = candidate;
@@ -79993,13 +80068,6 @@ function applyLocalCollectionMutation(targetValue, mutation, args, ctx, unique =
79993
80068
  return null;
79994
80069
  }
79995
80070
  }
79996
- function setCollectionReferenceProvenance(targetValue, index, reference2, ctx) {
79997
- const cache = ctx.__unorderedListProjections;
79998
- const indexes3 = cache?.referenceEntryIndexesByArray.get(targetValue);
79999
- if (cache === void 0 || indexes3 === void 0) return;
80000
- if (reference2) indexes3.add(index);
80001
- else indexes3.delete(index);
80002
- }
80003
80071
  function updateCollectionReferenceProvenance(targetValue, mutation, removedIndex, ctx) {
80004
80072
  if (!Array.isArray(targetValue)) return;
80005
80073
  const cache = ctx.__unorderedListProjections;
@@ -80273,7 +80341,7 @@ function evalPointerCore(pointer, scope, ctx, resultUsage = "value") {
80273
80341
  case "staticMember" /* staticMember */:
80274
80342
  return evalStaticMember(pointer.memberId, ctx);
80275
80343
  case "keyOf" /* keyOf */:
80276
- return evalKeyOf(pointer.keyOf, scope, ctx, pointer.optional === true);
80344
+ return evalKeyOf(pointer, scope, ctx);
80277
80345
  case "operation" /* operation */:
80278
80346
  return evalOperation(pointer.operation, scope, ctx);
80279
80347
  case "function" /* function */:
@@ -80923,15 +80991,9 @@ function readActionWithOwner(pointer, scope, ctx) {
80923
80991
  return { action: evalPointer(pointer, scope, ctx), owner: null };
80924
80992
  }
80925
80993
  let owner = null;
80926
- const action = evalKeyOf(
80927
- pointer.keyOf,
80928
- scope,
80929
- ctx,
80930
- pointer.optional === true,
80931
- (destination) => {
80932
- owner = destination.receiver;
80933
- }
80934
- );
80994
+ const action = evalKeyOf(pointer, scope, ctx, (destination) => {
80995
+ owner = destination.receiver;
80996
+ });
80935
80997
  return { action, owner };
80936
80998
  }
80937
80999
  function actionPointerLabel(pointer, ctx) {
@@ -81848,7 +81910,9 @@ function isRuntimeSpriteValue(value) {
81848
81910
  const sliceIndex = value.sliceIndex;
81849
81911
  return typeof sliceIndex === "number" && Number.isInteger(sliceIndex) && sliceIndex >= 0;
81850
81912
  }
81851
- function evalKeyOf(keyOf, scope, ctx, optional2 = false, onDestination) {
81913
+ function evalKeyOf(pointer, scope, ctx, onDestination) {
81914
+ const { keyOf } = pointer;
81915
+ const optional2 = pointer.optional === true;
81852
81916
  const receiver = evalPointer(keyOf.pointer, scope, ctx);
81853
81917
  if (optional2 && (receiver === null || receiver === void 0)) {
81854
81918
  return null;
@@ -81909,7 +81973,7 @@ function evalKeyOf(keyOf, scope, ctx, optional2 = false, onDestination) {
81909
81973
  if (dispatched.kind === "ok") return dispatched.value;
81910
81974
  if (Object.prototype.hasOwnProperty.call(receiver, k)) {
81911
81975
  const at3 = receiver[k];
81912
- return resolveValueIfId(at3, ctx);
81976
+ return typeof at3 === "string" && (pointer.memberId !== void 0 || isReferenceEntry(collectionReferences(receiver, ctx), k)) ? resolveValueIfId(at3, ctx) : at3;
81913
81977
  }
81914
81978
  const expanded = virtualExpandedRecordForReceiver(receiver, ctx);
81915
81979
  if (expanded !== null && Object.prototype.hasOwnProperty.call(expanded, k)) {
@@ -82641,7 +82705,7 @@ function evaluateSystemNative(memberId, receiver, args, ctx, typeArguments) {
82641
82705
  shift,
82642
82706
  accepts
82643
82707
  );
82644
- return { handled: true, value };
82708
+ return { handled: true, value: referenceEntryList(value, ctx) };
82645
82709
  }
82646
82710
  if (memberId === NEO_OBJECT_GRID_MEMBER_IDS.GetTiles) {
82647
82711
  const value = index.tiles(
@@ -82651,7 +82715,7 @@ function evaluateSystemNative(memberId, receiver, args, ctx, typeArguments) {
82651
82715
  shift,
82652
82716
  accepts
82653
82717
  );
82654
- return { handled: true, value };
82718
+ return { handled: true, value: referenceEntryList(value, ctx) };
82655
82719
  }
82656
82720
  const tile = index.tile(
82657
82721
  placement,
@@ -83260,7 +83324,17 @@ function evalDeclaredListIndex(info, scope, ctx) {
83260
83324
  collectionIndexes.set(cacheKey, index);
83261
83325
  }
83262
83326
  if (info.keyPointer === void 0) {
83263
- return Object.fromEntries(index);
83327
+ const view = Object.fromEntries(index);
83328
+ if (info.unique) {
83329
+ unorderedListProjectionCache(ctx).referenceEntryKeysByRecord.set(
83330
+ view,
83331
+ new Set(index.keys())
83332
+ );
83333
+ } else {
83334
+ for (const bucket of index.values())
83335
+ if (Array.isArray(bucket)) referenceEntryList(bucket, ctx);
83336
+ }
83337
+ return view;
83264
83338
  }
83265
83339
  const key = evalPointer(info.keyPointer, scope, ctx);
83266
83340
  if (typeof key !== "string") {
@@ -83272,7 +83346,12 @@ function evalDeclaredListIndex(info, scope, ctx) {
83272
83346
  if (info.unique) {
83273
83347
  return typeof hit === "string" ? resolveValueIfId(hit, ctx) : null;
83274
83348
  }
83275
- return Array.isArray(hit) ? [...hit] : [];
83349
+ return referenceEntryList(Array.isArray(hit) ? [...hit] : [], ctx);
83350
+ }
83351
+ function referenceEntryList(list, ctx) {
83352
+ const indexes3 = unorderedListProjectionCache(ctx).referenceEntryIndexesByArray;
83353
+ if (!indexes3.has(list)) indexes3.set(list, new Set(list.keys()));
83354
+ return list;
83276
83355
  }
83277
83356
  function prepareCollectionCallback(callback, parentScope, ctx, isList, returnContract, onPredicateMatch) {
83278
83357
  const metrics = ctx.__collectionCallbackPreparationMetrics;
@@ -83836,7 +83915,7 @@ function evalFunction(fn, scope, ctx) {
83836
83915
  if (fn.info.reference === true) {
83837
83916
  return referenceIndexOf(c, target, ctx) !== null;
83838
83917
  }
83839
- const targetReferenceId = typeof target === "string" ? target : findKnownRowIdByValueReference(target, ctx);
83918
+ const targetReferenceId = typeof target === "string" ? null : findKnownRowIdByValueReference(target, ctx);
83840
83919
  let containsResolvedEntry = false;
83841
83920
  iterateCollection(c, ctx, (entry, _key, valueId) => {
83842
83921
  if (valueId !== null && valueId === targetReferenceId || jsEqual(entry, target)) {
@@ -83857,7 +83936,7 @@ function evalFunction(fn, scope, ctx) {
83857
83936
  const index = referenceIndexOf(collection, target, ctx);
83858
83937
  return index === null ? -1 : numberArg(index, "IndexOf index");
83859
83938
  }
83860
- const targetReferenceId = typeof target === "string" ? target : findKnownRowIdByValueReference(target, ctx);
83939
+ const targetReferenceId = typeof target === "string" ? null : findKnownRowIdByValueReference(target, ctx);
83861
83940
  let found = -1;
83862
83941
  iterateCollection(collection, ctx, (entry, key, valueId) => {
83863
83942
  if (valueId !== null && valueId === targetReferenceId || jsEqual(entry, target)) {
@@ -84999,6 +85078,8 @@ function evaluateDeclaredConstructorArguments(info, record7, scope, ctx) {
84999
85078
  );
85000
85079
  }
85001
85080
  const value = byName.get(parameter4.name);
85081
+ if (parameter4.type === 9 /* Lookup */ && Array.isArray(value))
85082
+ return referenceEntryList(value, ctx);
85002
85083
  if (typeof value !== "number") return value;
85003
85084
  if (parameter4.type === 4 /* Float */) return Math.fround(value);
85004
85085
  if (parameter4.type !== 20 /* Decimal */) return value;
@@ -85493,12 +85574,7 @@ function evaluateInitializerInContext(init, member, ctx, createdValues, argument
85493
85574
  deleteRuntimeSessionValue(ctx, rootRow.id);
85494
85575
  ctx.__executionState?.constructorGroups.delete(rootRow.id);
85495
85576
  const constructorArgs2 = typeof result.value === "object" && result.value !== null ? ctx.__constructedArgumentsByValue.get(result.value) ?? rootRow.constructorArgs ?? void 0 : void 0;
85496
- const provenance = pickInstanceProvenance({
85497
- constructorArgs: constructorArgs2,
85498
- instanceConstructorId: rootRow.instanceConstructorId,
85499
- instanceVariantId: rootRow.instanceVariantId,
85500
- instanceVariantRowValueId: rootRow.instanceVariantRowValueId
85501
- });
85577
+ const provenance = pickInstanceProvenance({ ...rootRow, constructorArgs: constructorArgs2 });
85502
85578
  return {
85503
85579
  value: result.value,
85504
85580
  classId: rootRow.classId ?? null,
@@ -86363,7 +86439,7 @@ function evalVariantInitialize(info, scope, ctx) {
86363
86439
  scope,
86364
86440
  ctx
86365
86441
  );
86366
- stampInstanceVariantProvenance(instance, selection2, ctx, true);
86442
+ stampInstanceVariantProvenance(instance, selection2, ctx);
86367
86443
  return instance;
86368
86444
  }
86369
86445
  const graph = resolveVariantGraph(selection2, ctx);
@@ -86394,12 +86470,16 @@ function evalVariantInitialize(info, scope, ctx) {
86394
86470
  ctx,
86395
86471
  ctx.__variantDeclarativeAnsweredValueIds
86396
86472
  );
86397
- stampInstanceVariantProvenance(instance, selection2, ctx, true);
86473
+ stampInstanceVariantProvenance(instance, selection2, ctx);
86398
86474
  return instance;
86399
86475
  } finally {
86400
86476
  closeFrame();
86401
86477
  }
86402
86478
  }
86479
+ function isInsideAnotherExpansion(valueId, ctx) {
86480
+ const ownerRootId = ctx.vm.databaseVM?.virtualInstanceRootIdForValue(valueId) ?? null;
86481
+ return ownerRootId !== null && ownerRootId !== valueId;
86482
+ }
86403
86483
  function evalVariantApply(info, scope, ctx) {
86404
86484
  const receiver = evalPointer(info.receiverPointer, scope, ctx);
86405
86485
  if (receiver === null || receiver === void 0) {
@@ -86411,12 +86491,12 @@ function evalVariantApply(info, scope, ctx) {
86411
86491
  evalPointer(info.variantPointer, scope, ctx),
86412
86492
  "ToVariant argument"
86413
86493
  );
86414
- if (selection2.variantId === null) {
86415
- stampInstanceVariantProvenance(receiver, selection2, ctx);
86494
+ const graph = selection2.variantId === null ? null : resolveVariantGraph(selection2, ctx);
86495
+ if (info.declarativeReplay === true) {
86496
+ if (graph !== null) applyVariantDeclarativeHalves(receiver, graph, ctx);
86416
86497
  return receiver;
86417
86498
  }
86418
- const graph = resolveVariantGraph(selection2, ctx);
86419
- const rowParameters = resolveVariantRowParameter({
86499
+ const rowParameters = graph === null ? [] : resolveVariantRowParameter({
86420
86500
  graph,
86421
86501
  selection: selection2,
86422
86502
  explicitPointer: info.rowPointer,
@@ -86425,13 +86505,18 @@ function evalVariantApply(info, scope, ctx) {
86425
86505
  });
86426
86506
  const rootRow = trackedRowForValueReference(receiver, ctx);
86427
86507
  if (rootRow === null || !isLiteralValueContent(rootRow)) {
86508
+ if (graph === null) return receiver;
86428
86509
  throw new NSGetterRuntimeError(
86429
86510
  "ToVariant receiver has no addressable instance root."
86430
86511
  );
86431
86512
  }
86432
- const priorInstanceRoot = ctx.__runtimeSessionValues?.has(rootRow.id) === true ? null : deepClonePlainData(rootRow);
86433
- const applyValue = graph.root.Apply;
86434
- if (applyValue !== void 0 && applyValue !== null) {
86513
+ if (graph === null && typeof rootRow.instanceAppliedVariantId !== "string") {
86514
+ return receiver;
86515
+ }
86516
+ const inPlace = ctx.__runtimeSessionValues?.has(rootRow.id) === true || isInsideAnotherExpansion(rootRow.id, ctx);
86517
+ const priorInstanceRoot = inPlace ? null : deepClonePlainData(rootRow);
86518
+ const applyValue = graph?.root.Apply;
86519
+ if (graph !== null && applyValue !== void 0 && applyValue !== null) {
86435
86520
  invokeVariantClosure({
86436
86521
  closureValueId: applyValue,
86437
86522
  ctx,
@@ -86441,17 +86526,12 @@ function evalVariantApply(info, scope, ctx) {
86441
86526
  });
86442
86527
  }
86443
86528
  if (priorInstanceRoot === null) {
86444
- stampInstanceVariantProvenance(receiver, selection2, ctx);
86445
- applyVariantDeclarativeHalves(receiver, graph, ctx);
86529
+ if (graph !== null) applyVariantDeclarativeHalves(receiver, graph, ctx);
86446
86530
  return receiver;
86447
86531
  }
86448
86532
  priorInstanceRoot.value = deepClonePlainData(rootRow.value);
86449
- const answeredSlots = collectVariantDeclarativeAnsweredSlots(
86450
- receiver,
86451
- graph,
86452
- ctx
86453
- );
86454
- stampInstanceVariantProvenance(receiver, selection2, ctx);
86533
+ const answeredSlots = graph === null ? [] : collectVariantDeclarativeAnsweredSlots(receiver, graph, ctx);
86534
+ stampAppliedVariantProvenance(rootRow, receiver, selection2, ctx);
86455
86535
  const resolver = ctx.vm.databaseVM?.resolveVariantInstanceGraph;
86456
86536
  if (resolver === void 0) {
86457
86537
  if (answeredSlots.length > 0) {
@@ -86460,26 +86540,41 @@ function evalVariantApply(info, scope, ctx) {
86460
86540
  );
86461
86541
  }
86462
86542
  } else {
86543
+ const overlay = ctx.__valueOverlay;
86544
+ const copies = overlay === void 0 ? void 0 : variantResolutionCopies(overlay);
86463
86545
  const resolution = resolver.call(ctx.vm.databaseVM, {
86464
86546
  priorInstanceRoot,
86465
86547
  nextInstanceRoot: deepClonePlainData(rootRow),
86466
86548
  answeredValueIds: [...new Set(answeredSlots.map((slot) => slot.valueId))],
86467
86549
  localRows: [
86468
86550
  ...ctx.__runtimeSessionValues?.values() ?? [],
86469
- ...ctx.__valueOverlay?.values() ?? []
86470
- ]
86551
+ ...overlay?.values() ?? []
86552
+ ],
86553
+ virtualCopyIds: unwrittenVariantResolutionCopyIds(
86554
+ overlay,
86555
+ copies?.byRootId.get(rootRow.id)
86556
+ )
86471
86557
  });
86472
86558
  for (const valueId of resolution.clearedValueIds) {
86473
86559
  const previous = readNeoScriptRuntimeRow(ctx, valueId);
86474
86560
  if (previous) observeValueWrite(ctx, previous);
86475
86561
  deleteRuntimeSessionValue(ctx, valueId);
86476
- ctx.__valueOverlay?.delete(valueId);
86562
+ overlay?.delete(valueId);
86563
+ }
86564
+ for (const valueId of copies?.byRootId.get(rootRow.id)?.keys() ?? []) {
86565
+ forgetVariantResolutionCopy(ctx, valueId);
86477
86566
  }
86567
+ const virtualValueIds = new Set(resolution.virtualValueIds);
86478
86568
  for (const row of resolution.rows) {
86479
86569
  if (row.id === rootRow.id) continue;
86480
86570
  const previous = readNeoScriptRuntimeRow(ctx, row.id);
86481
86571
  if (previous) observeValueWrite(ctx, previous);
86482
- ctx.__valueOverlay?.set(row.id, deepClonePlainData(row));
86572
+ if (overlay === void 0 || copies === void 0) continue;
86573
+ const copy = deepClonePlainData(row);
86574
+ overlay.set(row.id, copy);
86575
+ if (virtualValueIds.has(row.id)) {
86576
+ trackVariantResolutionCopy(copies, rootRow.id, copy);
86577
+ }
86483
86578
  }
86484
86579
  if (typeof receiver !== "object" || receiver === null || Array.isArray(receiver) || typeof resolution.root.value !== "object" || resolution.root.value === null || Array.isArray(resolution.root.value)) {
86485
86580
  throw new NSGetterRuntimeError(
@@ -86493,14 +86588,69 @@ function evalVariantApply(info, scope, ctx) {
86493
86588
  }
86494
86589
  return receiver;
86495
86590
  }
86496
- function stampInstanceVariantProvenance(instance, selection2, ctx, preserveLookupRow = false) {
86591
+ function variantResolutionCopies(overlay) {
86592
+ let copies = variantResolutionCopiesByOverlay.get(overlay);
86593
+ if (copies === void 0) {
86594
+ copies = { byRootId: /* @__PURE__ */ new Map(), rootIdByValueId: /* @__PURE__ */ new Map() };
86595
+ variantResolutionCopiesByOverlay.set(overlay, copies);
86596
+ }
86597
+ return copies;
86598
+ }
86599
+ function hasVariantResolutionCopies(ctx) {
86600
+ const overlay = ctx.__valueOverlay;
86601
+ if (overlay === void 0) return false;
86602
+ const copies = variantResolutionCopiesByOverlay.get(overlay);
86603
+ return copies !== void 0 && copies.rootIdByValueId.size > 0;
86604
+ }
86605
+ function trackVariantResolutionCopy(copies, rootId, copy) {
86606
+ let rootCopies = copies.byRootId.get(rootId);
86607
+ if (rootCopies === void 0) {
86608
+ rootCopies = /* @__PURE__ */ new Map();
86609
+ copies.byRootId.set(rootId, rootCopies);
86610
+ }
86611
+ rootCopies.set(copy.id, copy);
86612
+ copies.rootIdByValueId.set(copy.id, rootId);
86613
+ }
86614
+ function unwrittenVariantResolutionCopyIds(overlay, rootCopies) {
86615
+ if (overlay === void 0 || rootCopies === void 0) return [];
86616
+ const ids = [];
86617
+ for (const [id2, copy] of rootCopies) {
86618
+ if (overlay.get(id2) === copy) ids.push(id2);
86619
+ }
86620
+ return ids;
86621
+ }
86622
+ function forgetVariantResolutionCopy(ctx, valueId) {
86623
+ const overlay = ctx.__valueOverlay;
86624
+ if (overlay === void 0) return;
86625
+ const copies = variantResolutionCopiesByOverlay.get(overlay);
86626
+ const rootId = copies?.rootIdByValueId.get(valueId);
86627
+ if (copies === void 0 || rootId === void 0) return;
86628
+ copies.rootIdByValueId.delete(valueId);
86629
+ copies.byRootId.get(rootId)?.delete(valueId);
86630
+ }
86631
+ function stampInstanceVariantProvenance(instance, selection2, ctx) {
86497
86632
  const row = trackedRowForValueReference(instance, ctx);
86498
86633
  if (row === null || !isLiteralValueContent(row)) return;
86499
- if (preserveLookupRow && row.id === selection2.rowValueId) return;
86634
+ if (row.id === selection2.rowValueId) return;
86500
86635
  assertStoredReplayMutableValue(instance, ctx, "variant provenance");
86501
86636
  row.instanceVariantId = selection2.variantId;
86502
86637
  row.instanceVariantRowValueId = selection2.rowValueId;
86503
86638
  }
86639
+ function stampAppliedVariantProvenance(rootRow, instance, selection2, ctx) {
86640
+ const applied = typeof rootRow.instanceAppliedVariantId === "string";
86641
+ const variantId = applied ? rootRow.instanceAppliedVariantId : rootRow.instanceVariantId ?? null;
86642
+ const rowValueId = applied ? rootRow.instanceAppliedVariantRowValueId : rootRow.instanceVariantRowValueId;
86643
+ if (variantId === selection2.variantId && (rowValueId ?? null) === selection2.rowValueId) {
86644
+ return;
86645
+ }
86646
+ assertStoredReplayMutableValue(instance, ctx, "variant provenance");
86647
+ if (!isVirtualInstanceRootShape(rootRow)) {
86648
+ rootRow.instanceConstructorId = null;
86649
+ rootRow.constructorArgs = {};
86650
+ }
86651
+ rootRow.instanceAppliedVariantId = selection2.variantId;
86652
+ rootRow.instanceAppliedVariantRowValueId = selection2.rowValueId;
86653
+ }
86504
86654
  function constructDeclaredClassValue(info, scope, ctx) {
86505
86655
  const descriptor = validateClassConstructorDescriptor(info, ctx, false);
86506
86656
  const schemaClass2 = descriptor.schemaClass;
@@ -86583,6 +86733,7 @@ function constructDeclaredClassValueWithinFrame(descriptor, record7, info, scope
86583
86733
  );
86584
86734
  }
86585
86735
  const rootRecord = root.value;
86736
+ recordConstructedFieldSchemaKeys(ctx, rootRecord, descriptor);
86586
86737
  if (record7 !== null) {
86587
86738
  const encoded = {};
86588
86739
  for (let index = 0; index < argumentValues.length; index += 1) {
@@ -86623,7 +86774,6 @@ function constructDeclaredClassValueWithinFrame(descriptor, record7, info, scope
86623
86774
  }
86624
86775
  const argumentsByValue = ctx.__constructedArgumentsByValue ?? (ctx.__constructedArgumentsByValue = /* @__PURE__ */ new WeakMap());
86625
86776
  argumentsByValue.set(rootRecord, encoded);
86626
- recordConstructedFieldSchemaKeys(ctx, rootRecord, descriptor);
86627
86777
  root.constructorArgs = deepClonePlainData(encoded);
86628
86778
  root.instanceConstructorId = record7.id;
86629
86779
  } else {
@@ -87016,7 +87166,7 @@ function cloneConstructorArgumentGraph(args) {
87016
87166
  member.classArguments,
87017
87167
  args.ctx.vm.classes
87018
87168
  );
87019
- const record7 = {};
87169
+ const record7 = /* @__PURE__ */ Object.create(null);
87020
87170
  clone.value = record7;
87021
87171
  const sourceRecord = {
87022
87172
  ...virtualExpandedRecordForReceiver(source.value, args.ctx),
@@ -87060,7 +87210,7 @@ function cloneConstructorArgumentGraph(args) {
87060
87210
  `Constructor import references missing Dictionary entry member '${member.entryMemberId}'.`
87061
87211
  );
87062
87212
  }
87063
- const record7 = {};
87213
+ const record7 = /* @__PURE__ */ Object.create(null);
87064
87214
  clone.value = record7;
87065
87215
  const entryEnv = envFromStamp(clone.genericBindings);
87066
87216
  for (const [key, childId] of Object.entries(source.value)) {
@@ -87303,7 +87453,7 @@ function materializeConstructorArgumentValue(args) {
87303
87453
  args.ctx.vm.members
87304
87454
  );
87305
87455
  const row = registerConstructorArgumentRow(args, {});
87306
- const record7 = {};
87456
+ const record7 = /* @__PURE__ */ Object.create(null);
87307
87457
  for (const [key, rawEntry] of Object.entries(args.value)) {
87308
87458
  const entry = constructorCollectionEntryValue(
87309
87459
  rawEntry,
@@ -87883,14 +88033,10 @@ function collectionLength(c) {
87883
88033
  }
87884
88034
  function snapshotCollectionMembership(collection, ctx) {
87885
88035
  const membership = [];
87886
- const valid = forEachRawCollectionEntry(collection, (entry) => {
88036
+ const valid = forEachRawCollectionEntry(collection, ctx, (entry) => {
87887
88037
  membership.push({
87888
88038
  raw: entry.raw,
87889
- resolveAsReference: collectionEntryUsesReferenceResolution(
87890
- collection,
87891
- entry.key,
87892
- ctx
87893
- )
88039
+ resolveAsReference: entry.valueId !== null
87894
88040
  });
87895
88041
  return 0 /* Continue */;
87896
88042
  });
@@ -87899,7 +88045,7 @@ function snapshotCollectionMembership(collection, ctx) {
87899
88045
  "NeoScript foreach requires a present collection."
87900
88046
  );
87901
88047
  }
87902
- function forEachRawCollectionEntry(c, callback) {
88048
+ function forEachRawCollectionEntry(c, ctx, callback) {
87903
88049
  if (c instanceof RuntimeSet) {
87904
88050
  for (const [key, entry] of c.membership().entries()) {
87905
88051
  if (callback({
@@ -87911,35 +88057,34 @@ function forEachRawCollectionEntry(c, callback) {
87911
88057
  }
87912
88058
  return true;
87913
88059
  }
88060
+ if (typeof c !== "object" || c === null) return false;
88061
+ const references = collectionReferences(c, ctx);
87914
88062
  if (Array.isArray(c)) {
87915
88063
  for (let key = 0; key < c.length; key += 1) {
87916
88064
  const raw = c[key];
87917
88065
  const control = callback({
87918
88066
  raw,
87919
88067
  key,
87920
- valueId: typeof raw === "string" ? raw : null
88068
+ valueId: typeof raw === "string" && isReferenceEntry(references, key) ? raw : null
87921
88069
  });
87922
88070
  if (control === 1 /* Break */) break;
87923
88071
  }
87924
88072
  return true;
87925
88073
  }
87926
- if (typeof c === "object" && c !== null) {
87927
- for (const [key, raw] of Object.entries(c)) {
87928
- const control = callback({
87929
- raw,
87930
- key,
87931
- valueId: typeof raw === "string" ? raw : null
87932
- });
87933
- if (control === 1 /* Break */) break;
87934
- }
87935
- return true;
88074
+ for (const [key, raw] of Object.entries(c)) {
88075
+ const control = callback({
88076
+ raw,
88077
+ key,
88078
+ valueId: typeof raw === "string" && isReferenceEntry(references, key) ? raw : null
88079
+ });
88080
+ if (control === 1 /* Break */) break;
87936
88081
  }
87937
- return false;
88082
+ return true;
87938
88083
  }
87939
88084
  function collectionEntries(c, ctx) {
87940
88085
  const entries = [];
87941
- forEachRawCollectionEntry(c, ({ raw, key }) => {
87942
- entries.push(resolveCollectionEntry(c, raw, key, ctx));
88086
+ forEachRawCollectionEntry(c, ctx, ({ raw, valueId }) => {
88087
+ entries.push(valueId === null ? raw : resolveValueIfId(valueId, ctx));
87943
88088
  return 0 /* Continue */;
87944
88089
  });
87945
88090
  return entries;
@@ -87947,7 +88092,7 @@ function collectionEntries(c, ctx) {
87947
88092
  function referenceIndexOf(c, target, ctx) {
87948
88093
  const targetId = target === null || target === void 0 ? null : referenceIdOf(target, ctx);
87949
88094
  let found = null;
87950
- forEachRawCollectionEntry(c, ({ raw, key }) => {
88095
+ forEachRawCollectionEntry(c, ctx, ({ raw, key }) => {
87951
88096
  if (raw === target || targetId !== null && raw !== null && raw !== void 0 && referenceIdOf(raw, ctx) === targetId) {
87952
88097
  found = key;
87953
88098
  return 1 /* Break */;
@@ -87957,28 +88102,63 @@ function referenceIndexOf(c, target, ctx) {
87957
88102
  return found;
87958
88103
  }
87959
88104
  function iterateCollection(c, ctx, callback) {
87960
- forEachRawCollectionEntry(c, ({ raw, key, valueId }) => {
87961
- const effectiveValueId = collectionEntryUsesReferenceResolution(c, key, ctx) ? valueId : null;
87962
- return callback(
87963
- resolveCollectionEntry(c, raw, key, ctx),
88105
+ forEachRawCollectionEntry(
88106
+ c,
88107
+ ctx,
88108
+ ({ raw, key, valueId }) => callback(
88109
+ valueId === null ? raw : resolveValueIfId(valueId, ctx),
87964
88110
  key,
87965
- effectiveValueId
87966
- );
87967
- });
88111
+ valueId
88112
+ )
88113
+ );
87968
88114
  }
87969
88115
  function resolveCollectionEntry(collection, raw, key, ctx) {
87970
- return collectionEntryUsesReferenceResolution(collection, key, ctx) ? resolveValueIfId(raw, ctx) : raw;
88116
+ return typeof raw === "string" && isReferenceEntry(collectionReferences(collection, ctx), key) ? resolveValueIfId(raw, ctx) : raw;
87971
88117
  }
87972
- function collectionEntryUsesReferenceResolution(collection, key, ctx) {
87973
- if (collection instanceof RuntimeSet && typeof key === "number")
87974
- return collection.membership()[key]?.reference === true;
87975
- if (!Array.isArray(collection) || typeof key !== "number") return true;
87976
- const referenceIndexes = ctx.__unorderedListProjections?.referenceEntryIndexesByArray.get(
87977
- collection
87978
- );
87979
- return referenceIndexes === void 0 || referenceIndexes.has(key);
88118
+ function recordedReferenceEntries(collection, ctx) {
88119
+ const cache = ctx.__unorderedListProjections;
88120
+ if (Array.isArray(collection))
88121
+ return cache?.referenceEntryIndexesByArray.get(collection);
88122
+ if (typeof collection === "object" && collection !== null)
88123
+ return cache?.referenceEntryKeysByRecord.get(collection);
88124
+ return void 0;
88125
+ }
88126
+ function collectionReferences(collection, ctx) {
88127
+ return recordedReferenceEntries(collection, ctx) ?? (findKnownRowIdByValueReference(collection, ctx) === null ? 1 /* Values */ : 0 /* RowIds */);
88128
+ }
88129
+ function isReferenceEntry(references, key) {
88130
+ if (references === 0 /* RowIds */) return true;
88131
+ if (references === 1 /* Values */) return false;
88132
+ return references.has(key);
88133
+ }
88134
+ function recordWrittenEntry(collection, key, reference2, ctx) {
88135
+ const references = collectionReferences(collection, ctx);
88136
+ if (typeof references !== "object") {
88137
+ if (reference2 === (references === 0 /* RowIds */)) return;
88138
+ const written = Array.isArray(collection) ? collection[Number(key)] : collection[String(key)];
88139
+ if (!reference2 && typeof written !== "string") return;
88140
+ }
88141
+ const rowIds = references === 0 /* RowIds */;
88142
+ const cache = unorderedListProjectionCache(ctx);
88143
+ if (Array.isArray(collection)) {
88144
+ let indexes3 = cache.referenceEntryIndexesByArray.get(collection);
88145
+ if (indexes3 === void 0) {
88146
+ indexes3 = new Set(rowIds ? collection.keys() : []);
88147
+ cache.referenceEntryIndexesByArray.set(collection, indexes3);
88148
+ }
88149
+ if (reference2) indexes3.add(Number(key));
88150
+ else indexes3.delete(Number(key));
88151
+ return;
88152
+ }
88153
+ let keys = cache.referenceEntryKeysByRecord.get(collection);
88154
+ if (keys === void 0) {
88155
+ keys = new Set(rowIds ? Object.keys(collection) : []);
88156
+ cache.referenceEntryKeysByRecord.set(collection, keys);
88157
+ }
88158
+ if (reference2) keys.add(String(key));
88159
+ else keys.delete(String(key));
87980
88160
  }
87981
- var DELEGATE_LEXICAL_THIS, DELEGATE_LEXICAL_ROOT, DELEGATE_LEXICAL_TYPE_ARGUMENTS, NonCatchableNSGetterRuntimeError, NativeFunctionDelegateUnavailableError, CorruptNeoScriptIRError, NeoScriptWallClockTimeoutError, liveListIndexesByProject, evaluatorOwnershipCachesByBase, MAX_CONSTRUCTION_DEPTH, resolutionCacheByMembers, NO_SCHEMA_REVISION, LazyValueOverlay, READONLY_FOREACH_BINDING_ERROR, READONLY_CATCH_BINDING_ERROR, DIALOGUE_CONTEXT_PARAMETER_ID, FORWARDING_TYPE_ARGUMENTS, constantDeclarationRoots, NS_MATH_OP_NAMES, DOUBLE_INTEGRAL_MAGNITUDE, EMPTY_SUPPLIED_CONSTRUCTOR_FIELDS;
88161
+ var DELEGATE_LEXICAL_THIS, DELEGATE_LEXICAL_ROOT, DELEGATE_LEXICAL_TYPE_ARGUMENTS, NonCatchableNSGetterRuntimeError, NativeFunctionDelegateUnavailableError, CorruptNeoScriptIRError, NeoScriptWallClockTimeoutError, liveListIndexesByProject, evaluatorOwnershipCachesByBase, MAX_CONSTRUCTION_DEPTH, resolutionCacheByMembers, NO_SCHEMA_REVISION, LazyValueOverlay, READONLY_FOREACH_BINDING_ERROR, READONLY_CATCH_BINDING_ERROR, DIALOGUE_CONTEXT_PARAMETER_ID, FORWARDING_TYPE_ARGUMENTS, constantDeclarationRoots, NS_MATH_OP_NAMES, DOUBLE_INTEGRAL_MAGNITUDE, EMPTY_SUPPLIED_CONSTRUCTOR_FIELDS, variantResolutionCopiesByOverlay;
87982
88162
  var init_evaluateNSGetter = __esm({
87983
88163
  "../packages/neoscript-runtime/src/neoscript/evaluateNSGetter.ts"() {
87984
88164
  "use strict";
@@ -88188,6 +88368,7 @@ var init_evaluateNSGetter = __esm({
88188
88368
  };
88189
88369
  DOUBLE_INTEGRAL_MAGNITUDE = 2 ** 53;
88190
88370
  EMPTY_SUPPLIED_CONSTRUCTOR_FIELDS = [];
88371
+ variantResolutionCopiesByOverlay = /* @__PURE__ */ new WeakMap();
88191
88372
  }
88192
88373
  });
88193
88374
 
@@ -89880,6 +90061,8 @@ function expandStoredInstance(args) {
89880
90061
  instanceConstructorId: _instanceConstructorId,
89881
90062
  instanceVariantId: _instanceVariantId,
89882
90063
  instanceVariantRowValueId: _instanceVariantRowValueId,
90064
+ instanceAppliedVariantId: _instanceAppliedVariantId,
90065
+ instanceAppliedVariantRowValueId: _instanceAppliedVariantRowValueId,
89883
90066
  ...envelope
89884
90067
  } = instanceRoot;
89885
90068
  void _value;
@@ -89888,6 +90071,8 @@ function expandStoredInstance(args) {
89888
90071
  void _instanceConstructorId;
89889
90072
  void _instanceVariantId;
89890
90073
  void _instanceVariantRowValueId;
90074
+ void _instanceAppliedVariantId;
90075
+ void _instanceAppliedVariantRowValueId;
89891
90076
  const closedRootMember = closeClassArgumentsFromRowStamp(
89892
90077
  rootMember,
89893
90078
  instanceRoot
@@ -89969,11 +90154,26 @@ function expandStoredInstance(args) {
89969
90154
  }
89970
90155
  };
89971
90156
  };
89972
- const materialized = derivesContentFromMemberDefault({
90157
+ const constructed = derivesContentFromMemberDefault({
89973
90158
  member: replayMember,
89974
90159
  instanceRoot,
89975
90160
  effectiveClassId: classId
89976
90161
  }) ? replayDeclaredDefault() : replay([]);
90162
+ const appliedVariantId = instanceRoot.instanceAppliedVariantId;
90163
+ const materialized = typeof appliedVariantId !== "string" ? constructed : trackMaterialization(
90164
+ () => replayAppliedVariant({
90165
+ evaluateInitializer: args.evaluateInitializer,
90166
+ document: args.document,
90167
+ member: replayMember,
90168
+ constructed,
90169
+ classId,
90170
+ variantId: appliedVariantId,
90171
+ variantRowValueId: instanceRoot.instanceAppliedVariantRowValueId ?? null,
90172
+ ...readTracking === void 0 ? {} : { readTracking },
90173
+ saveStaticBindings: args.saveStaticBindings,
90174
+ sessionStaticBindings: args.sessionStaticBindings
90175
+ })
90176
+ );
89977
90177
  const rows = [materialized.root, ...materialized.createdValues];
89978
90178
  assertVirtualExpansionIsLiteral(rows);
89979
90179
  return {
@@ -89982,6 +90182,80 @@ function expandStoredInstance(args) {
89982
90182
  pinnedRootSchemaKeys: /* @__PURE__ */ new Set()
89983
90183
  };
89984
90184
  }
90185
+ function replayAppliedVariant(args) {
90186
+ const rootId = args.constructed.root.id;
90187
+ const sessionValues = /* @__PURE__ */ new Map();
90188
+ sessionValues.set(rootId, args.constructed.root);
90189
+ for (const row of args.constructed.createdValues)
90190
+ sessionValues.set(row.id, row);
90191
+ const variant2 = args.document.databaseVM?.variantById?.(args.variantId) ?? args.document.variants?.find((entry) => entry.id === args.variantId);
90192
+ const variantClassId = variant2?.classId ?? args.classId;
90193
+ const schemaClassInfo = {
90194
+ type: 7 /* Class */,
90195
+ required: true,
90196
+ classId: args.classId
90197
+ };
90198
+ args.evaluateInitializer({
90199
+ init: {
90200
+ code: `virtual-applied-variant:${rootId}`,
90201
+ compiled: {
90202
+ compilerRevision: NEOSCRIPT_COMPILER_REVISION,
90203
+ parameters: evaluatorEnvelopeParameters(),
90204
+ instructions: [
90205
+ {
90206
+ type: "return" /* return */,
90207
+ pointer: {
90208
+ type: "function" /* function */,
90209
+ function: {
90210
+ type: "variantApply" /* variantApply */,
90211
+ info: {
90212
+ receiverPointer: {
90213
+ type: "reference" /* reference */,
90214
+ valueId: rootId
90215
+ },
90216
+ variantPointer: {
90217
+ type: "variant" /* variant */,
90218
+ classId: variantClassId,
90219
+ variantId: args.variantId,
90220
+ rowValueId: args.variantRowValueId
90221
+ },
90222
+ schemaClassInfo,
90223
+ declarativeReplay: true
90224
+ }
90225
+ }
90226
+ }
90227
+ }
90228
+ ],
90229
+ typeInfo: schemaClassInfo
90230
+ }
90231
+ },
90232
+ member: args.member,
90233
+ document: args.document,
90234
+ createdValues: [],
90235
+ sessionValues,
90236
+ storedConstructionReplay: true,
90237
+ sourceValueId: rootId,
90238
+ ...args.readTracking === void 0 ? {} : { readTracking: args.readTracking },
90239
+ saveStaticBindings: args.saveStaticBindings,
90240
+ sessionStaticBindings: args.sessionStaticBindings
90241
+ });
90242
+ const root = sessionValues.get(rootId);
90243
+ if (root === void 0) {
90244
+ throw new Error(
90245
+ `Applied variant "${args.variantId}" replay lost instance root "${rootId}".`
90246
+ );
90247
+ }
90248
+ sessionValues.delete(rootId);
90249
+ return {
90250
+ ...args.constructed,
90251
+ root: {
90252
+ ...root,
90253
+ instanceAppliedVariantId: args.variantId,
90254
+ instanceAppliedVariantRowValueId: args.variantRowValueId
90255
+ },
90256
+ createdValues: [...sessionValues.values()]
90257
+ };
90258
+ }
89985
90259
  function resolveVirtualInstanceGraph(args) {
89986
90260
  const expansion = args.expansionIndex ?? indexExpansion(args);
89987
90261
  const recorder = args.readRecorder ?? null;
@@ -90955,6 +91229,11 @@ function expandStoredClassValue(args) {
90955
91229
  pinnedRootSchemaKeys: /* @__PURE__ */ new Set()
90956
91230
  };
90957
91231
  }
91232
+ function owningInstanceRootId(graph) {
91233
+ let owner = graph;
91234
+ while (owner?.containingGraph !== void 0) owner = owner.containingGraph;
91235
+ return owner?.instanceRootId ?? null;
91236
+ }
90958
91237
  function isStoredClassResolutionRoot(value) {
90959
91238
  if (!isLiteralValueContent(value)) return false;
90960
91239
  if (isVirtualInstanceRootShape(value)) return true;
@@ -91268,6 +91547,7 @@ function planCollapseVirtualInstance(args) {
91268
91547
  if (provenance.sameRecipe) return true;
91269
91548
  if (typeof stored.instanceConstructorId === "string") return false;
91270
91549
  if (typeof stored.instanceVariantId === "string") return false;
91550
+ if (typeof stored.instanceAppliedVariantId === "string") return false;
91271
91551
  const storedArgs = stored.constructorArgs;
91272
91552
  if (storedArgs != null && Object.keys(storedArgs).length > 0) return false;
91273
91553
  return !isInitValueContent(child2.member.defaultValue);
@@ -91666,10 +91946,35 @@ function sparsifyConstructedInstance(args) {
91666
91946
  if (typeof entryId === "string")
91667
91947
  protectArgument(entryId, type.entryTypeInfo);
91668
91948
  };
91949
+ const argumentValueIds = /* @__PURE__ */ new Set();
91950
+ const pinnedSubtreeIds = /* @__PURE__ */ new Set();
91951
+ const pinSubtree = (valueId) => {
91952
+ if (pinnedSubtreeIds.has(valueId)) return;
91953
+ pinnedSubtreeIds.add(valueId);
91954
+ protectedValueIds.add(valueId);
91955
+ const row = materializedGraph.valuesById.get(valueId);
91956
+ if (row === void 0) return;
91957
+ for (const childId of materializedGraph.referencedValueIds(row))
91958
+ pinSubtree(childId);
91959
+ };
91960
+ const pinArgumentFields = (valueId) => {
91961
+ if (argumentValueIds.has(valueId)) return;
91962
+ argumentValueIds.add(valueId);
91963
+ const row = materializedGraph.valuesById.get(valueId);
91964
+ if (row === void 0) return;
91965
+ const fields = isObjectRecord2(row.value) ? row.value : {};
91966
+ for (const schemaKey of args.pinnedSchemaKeysByValueId?.get(valueId) ?? []) {
91967
+ const fieldId = fields[schemaKey];
91968
+ if (typeof fieldId === "string") pinSubtree(fieldId);
91969
+ }
91970
+ for (const childId of materializedGraph.referencedValueIds(row))
91971
+ pinArgumentFields(childId);
91972
+ };
91669
91973
  for (const edge of materializedGraph.constructorEdges(
91670
91974
  args.constructed.root
91671
91975
  )) {
91672
91976
  protectArgument(edge.targetValueId, edge.typeInfo);
91977
+ pinArgumentFields(edge.targetValueId);
91673
91978
  }
91674
91979
  for (const schemaKey of args.pinnedRootSchemaKeys ?? []) {
91675
91980
  const location3 = graph.locationsByPath.get(
@@ -92324,7 +92629,9 @@ function compareContextualCreationProvenance(left, right, context) {
92324
92629
  constructorArgs: literal3.constructorArgs ?? {},
92325
92630
  instanceConstructorId: literal3.instanceConstructorId ?? null,
92326
92631
  instanceVariantId: literal3.instanceVariantId ?? null,
92327
- instanceVariantRowValueId: literal3.instanceVariantRowValueId ?? null
92632
+ instanceVariantRowValueId: literal3.instanceVariantRowValueId ?? null,
92633
+ instanceAppliedVariantId: literal3.instanceAppliedVariantId ?? null,
92634
+ instanceAppliedVariantRowValueId: literal3.instanceAppliedVariantRowValueId ?? null
92328
92635
  };
92329
92636
  };
92330
92637
  return {
@@ -92622,40 +92929,37 @@ function resolveVariantInstanceGraphForDocument(args) {
92622
92929
  rootMember,
92623
92930
  readRecorder: args.readRecorder
92624
92931
  });
92625
- const priorGraph = resolveVirtualInstanceGraph({
92932
+ let priorInstanceRoot = args.priorInstanceRoot;
92933
+ let nextInstanceRoot = args.nextInstanceRoot;
92934
+ const resolvePriorGraph = () => resolveVirtualInstanceGraph({
92626
92935
  document,
92627
- instanceRoot: args.priorInstanceRoot,
92936
+ instanceRoot: priorInstanceRoot,
92628
92937
  rootMember,
92629
92938
  expandedRoot: priorExpanded.root,
92630
92939
  expandedRows: priorExpanded.rows,
92631
92940
  materializedRows: [...materializedById.values()],
92632
92941
  readRecorder: args.readRecorder
92633
92942
  });
92634
- const priorAnsweredIds = [];
92635
- const incomingAnsweredIds = [];
92636
- for (const valueId of args.answeredValueIds) {
92637
- const bucket = priorGraph.locationsById.has(valueId) ? priorAnsweredIds : incomingAnsweredIds;
92638
- bucket.push(valueId);
92639
- }
92640
92943
  const clearedValueIds = /* @__PURE__ */ new Set();
92641
- let nextInstanceRoot = args.nextInstanceRoot;
92642
- const resetAnsweredValues = (graph, valueIds) => {
92643
- if (valueIds.length === 0) return;
92644
- const reset = planVirtualOverrideResets({ graph, valueIds });
92944
+ const applyReset = (graph, reset) => {
92645
92945
  for (const valueId of reset.deletes) {
92646
92946
  clearedValueIds.add(valueId);
92647
92947
  materializedById.delete(valueId);
92648
92948
  }
92649
92949
  for (const update of reset.updates) {
92650
92950
  if (update.valueId === nextInstanceRoot.id) {
92651
- const nextRecord = { ...stringRecord2(nextInstanceRoot.value) };
92652
92951
  const resetRecord = stringRecord2(update.value);
92653
92952
  const priorRecord = stringRecord2(graph.root.materializedRow?.value);
92654
- for (const schemaKey of Object.keys(priorRecord)) {
92655
- if (!Object.hasOwn(resetRecord, schemaKey))
92656
- delete nextRecord[schemaKey];
92657
- }
92658
- nextInstanceRoot = { ...nextInstanceRoot, value: nextRecord };
92953
+ const withoutReset = (root2) => {
92954
+ const record7 = { ...stringRecord2(root2.value) };
92955
+ for (const schemaKey of Object.keys(priorRecord)) {
92956
+ if (!Object.hasOwn(resetRecord, schemaKey))
92957
+ delete record7[schemaKey];
92958
+ }
92959
+ return { ...root2, value: record7 };
92960
+ };
92961
+ priorInstanceRoot = withoutReset(literalRow(priorInstanceRoot));
92962
+ nextInstanceRoot = withoutReset(literalRow(nextInstanceRoot));
92659
92963
  }
92660
92964
  const existing = materializedById.get(update.valueId);
92661
92965
  if (existing !== void 0) {
@@ -92667,6 +92971,28 @@ function resolveVariantInstanceGraphForDocument(args) {
92667
92971
  }
92668
92972
  materializedById.set(nextInstanceRoot.id, nextInstanceRoot);
92669
92973
  };
92974
+ let priorGraph = resolvePriorGraph();
92975
+ if (args.virtualCopyIds !== void 0 && args.virtualCopyIds.length > 0) {
92976
+ const collapse = planCollapseVirtualInstance({
92977
+ graph: priorGraph,
92978
+ removableValueIds: new Set(args.virtualCopyIds)
92979
+ });
92980
+ if (collapse.deletes.length > 0 || collapse.updates.length > 0) {
92981
+ applyReset(priorGraph, collapse);
92982
+ materializedById.set(priorInstanceRoot.id, priorInstanceRoot);
92983
+ priorGraph = resolvePriorGraph();
92984
+ }
92985
+ }
92986
+ const priorAnsweredIds = [];
92987
+ const incomingAnsweredIds = [];
92988
+ for (const valueId of args.answeredValueIds) {
92989
+ const bucket = priorGraph.locationsById.has(valueId) ? priorAnsweredIds : incomingAnsweredIds;
92990
+ bucket.push(valueId);
92991
+ }
92992
+ const resetAnsweredValues = (graph, valueIds) => {
92993
+ if (valueIds.length === 0) return;
92994
+ applyReset(graph, planVirtualOverrideResets({ graph, valueIds }));
92995
+ };
92670
92996
  resetAnsweredValues(priorGraph, priorAnsweredIds);
92671
92997
  materializedById.set(nextInstanceRoot.id, nextInstanceRoot);
92672
92998
  const nextExpanded = expandStoredInstance({
@@ -92710,10 +93036,15 @@ function resolveVariantInstanceGraphForDocument(args) {
92710
93036
  `ToVariant failed to resolve instance root '${args.nextInstanceRoot.id}'.`
92711
93037
  );
92712
93038
  }
93039
+ const virtualValueIds = /* @__PURE__ */ new Set();
93040
+ for (const location3 of nextGraph.locationsById.values()) {
93041
+ if (location3.materializedRow === null) virtualValueIds.add(location3.id);
93042
+ }
92713
93043
  return {
92714
93044
  root,
92715
93045
  rows: [...nextGraph.rowsById.values()],
92716
- clearedValueIds: [...clearedValueIds]
93046
+ clearedValueIds: [...clearedValueIds],
93047
+ virtualValueIds: [...virtualValueIds]
92717
93048
  };
92718
93049
  }
92719
93050
  function variantSwapDeclaredMember(document, rootValueId) {
@@ -93040,6 +93371,7 @@ var KEPT_ROW_SAMPLE_LIMIT, VirtualExpansionUnsupportedError, ROOT_PATH, OpenGene
93040
93371
  var init_virtual_instance_graph = __esm({
93041
93372
  "../packages/neoscript-runtime/src/virtual-instance-graph.ts"() {
93042
93373
  "use strict";
93374
+ init_value_comparison();
93043
93375
  init_listener_endpoint_projection();
93044
93376
  init_overlay_readonly_map();
93045
93377
  init_member_change_listeners();
@@ -93142,6 +93474,7 @@ function initializerEvaluatorLookups(document, readTracking) {
93142
93474
  return resolved;
93143
93475
  },
93144
93476
  virtualInstanceRowsForValue: (receiverValueId) => databaseVM.virtualInstanceRowsForValue(receiverValueId),
93477
+ virtualInstanceRootIdForValue: (valueId) => databaseVM.virtualInstanceRootIdForValue(valueId),
93145
93478
  ...databaseVM.worldGridQueryIndex === void 0 ? {} : { worldGridQueryIndex: () => databaseVM.worldGridQueryIndex() },
93146
93479
  rowForValueReference: (value) => databaseVM.rowForValueReference?.(value) ?? null,
93147
93480
  resolveVariantInstanceGraph: (args) => {
@@ -93197,6 +93530,9 @@ function initializerEvaluatorLookups(document, readTracking) {
93197
93530
  valueById: (id2) => indexedLookups.valueById(id2) ?? headlessVirtualResolver.valueById(id2),
93198
93531
  rowForValueReference: (value) => indexedLookups.rowForValueReference?.(value) ?? headlessVirtualResolver.rowForValueReference(value),
93199
93532
  virtualInstanceRowsForValue: (receiverValueId) => headlessVirtualResolver.virtualInstanceRowsForValue(receiverValueId),
93533
+ virtualInstanceRootIdForValue: (valueId) => owningInstanceRootId(
93534
+ headlessVirtualResolver.virtualInstanceGraphForValue(valueId)
93535
+ ),
93200
93536
  recordVirtualInstanceReads: (reads, read) => headlessVirtualResolver.recordReads(reads, read),
93201
93537
  // Headless hosts still evaluate `ToVariant` during
93202
93538
  // stored-construction replay — production's variant-constructed
@@ -93430,6 +93766,7 @@ function createInitializerMaterializationBatch(authoredDocument, pendingInitiali
93430
93766
  if (entry.global) globalReads.add(entry);
93431
93767
  return entry.rows;
93432
93768
  },
93769
+ virtualInstanceRootIdForValue: (id2) => owningInstanceRootId(virtual().virtualInstanceGraphForValue(id2)),
93433
93770
  resolveVariantInstanceGraph: (args) => resolveVariantInstanceGraphForDocument({
93434
93771
  evaluateInitializer: evaluateMemberInitializer,
93435
93772
  document,
@@ -93513,6 +93850,7 @@ function evaluateMemberInitializer(args) {
93513
93850
  );
93514
93851
  const compiled = compileMemberInitializer(args, databaseVM);
93515
93852
  const ctx = {
93853
+ ...args.sessionValues === void 0 ? {} : { __runtimeSessionValues: args.sessionValues },
93516
93854
  debugSink: args.document.debugSink,
93517
93855
  beforeValueAllocation: args.document.beforeValueAllocation,
93518
93856
  listenerDefaultCapture: args.document.listenerDefaultCapture,
@@ -93583,10 +93921,13 @@ function evaluateMemberInitializer(args) {
93583
93921
  args.argumentValues ?? [],
93584
93922
  {
93585
93923
  exportInitializerValues: true,
93586
- initializerResult: {
93587
- member: args.member,
93588
- genericEnv: args.genericEnv
93589
- }
93924
+ // Seeded rows already hold their placement.
93925
+ ...args.sessionValues === void 0 ? {
93926
+ initializerResult: {
93927
+ member: args.member,
93928
+ genericEnv: args.genericEnv
93929
+ }
93930
+ } : {}
93590
93931
  }
93591
93932
  );
93592
93933
  } catch (error) {
@@ -93609,9 +93950,12 @@ function evaluateMemberInitializer(args) {
93609
93950
  );
93610
93951
  }
93611
93952
  const rootRow = initializerRootRow(result.value, created);
93953
+ const pinnedSchemaKeysByValueId = /* @__PURE__ */ new Map();
93612
93954
  for (const row of created) {
93613
93955
  if (row === rootRow) continue;
93614
93956
  args.createdValues.push(row);
93957
+ const keys = typeof row.value === "object" && row.value !== null ? ctx.__constructedFieldSchemaKeysByValue?.get(row.value) : void 0;
93958
+ if (keys !== void 0) pinnedSchemaKeysByValueId.set(row.id, keys);
93615
93959
  }
93616
93960
  if (rootRow === null) return { value: result.value, classId: null };
93617
93961
  const constructorArgs2 = (typeof result.value === "object" && result.value !== null ? ctx.__constructedArgumentsByValue?.get(result.value) : void 0) ?? // An implicit `new()` records its empty args on the row rather than in
@@ -93619,17 +93963,13 @@ function evaluateMemberInitializer(args) {
93619
93963
  // origin or the recipe reads as an unrecorded overload.
93620
93964
  rootRow.constructorArgs ?? void 0;
93621
93965
  const pinnedRootSchemaKeys = typeof result.value === "object" && result.value !== null ? ctx.__constructedFieldSchemaKeysByValue?.get(result.value) : void 0;
93622
- const provenance = pickInstanceProvenance({
93623
- constructorArgs: constructorArgs2,
93624
- instanceConstructorId: rootRow.instanceConstructorId,
93625
- instanceVariantId: rootRow.instanceVariantId,
93626
- instanceVariantRowValueId: rootRow.instanceVariantRowValueId
93627
- });
93966
+ const provenance = pickInstanceProvenance({ ...rootRow, constructorArgs: constructorArgs2 });
93628
93967
  return {
93629
93968
  value: result.value,
93630
93969
  classId: rootRow.classId ?? null,
93631
93970
  ...rootRow.genericBindings === void 0 ? {} : { genericBindings: { ...rootRow.genericBindings } },
93632
93971
  ...pinnedRootSchemaKeys === void 0 ? {} : { pinnedRootSchemaKeys },
93972
+ ...pinnedSchemaKeysByValueId.size === 0 ? {} : { pinnedSchemaKeysByValueId },
93633
93973
  provisionalRootId: rootRow.id,
93634
93974
  ...provenance,
93635
93975
  ...provenance.constructorArgs === void 0 ? {} : {
@@ -93835,12 +94175,7 @@ function materializeInitializerValue(args) {
93835
94175
  value: evaluated.value,
93836
94176
  ...evaluated.classId === null ? {} : { classId: evaluated.classId },
93837
94177
  ...evaluated.genericBindings === void 0 ? {} : { genericBindings: { ...evaluated.genericBindings } },
93838
- ...evaluated.constructorArgs === void 0 ? {} : { constructorArgs: deepClonePlainData(evaluated.constructorArgs) },
93839
- ...evaluated.instanceConstructorId === void 0 ? {} : { instanceConstructorId: evaluated.instanceConstructorId },
93840
- ...evaluated.instanceVariantId === void 0 ? {} : { instanceVariantId: evaluated.instanceVariantId },
93841
- ...evaluated.instanceVariantRowValueId === void 0 ? {} : {
93842
- instanceVariantRowValueId: evaluated.instanceVariantRowValueId
93843
- }
94178
+ ...deepClonePlainData(pickInstanceProvenance(evaluated))
93844
94179
  };
93845
94180
  const allCreated = [root, ...createdValues];
93846
94181
  if (evaluated.provisionalRootId !== void 0) {
@@ -93863,7 +94198,8 @@ function materializeInitializerValue(args) {
93863
94198
  return {
93864
94199
  root,
93865
94200
  createdValues,
93866
- pinnedRootSchemaKeys: evaluated.pinnedRootSchemaKeys ?? /* @__PURE__ */ new Set()
94201
+ pinnedRootSchemaKeys: evaluated.pinnedRootSchemaKeys ?? /* @__PURE__ */ new Set(),
94202
+ pinnedSchemaKeysByValueId: evaluated.pinnedSchemaKeysByValueId ?? /* @__PURE__ */ new Map()
93867
94203
  };
93868
94204
  }
93869
94205
  function materializeMemberDefaultValue(args) {
@@ -93980,7 +94316,12 @@ function materializeMemberDefaultValue(args) {
93980
94316
  storageKeyDeclarations,
93981
94317
  supersededRootId: built.id
93982
94318
  });
93983
- return { root, createdValues: interior, pinnedRootSchemaKeys: /* @__PURE__ */ new Set() };
94319
+ return {
94320
+ root,
94321
+ createdValues: interior,
94322
+ pinnedRootSchemaKeys: /* @__PURE__ */ new Set(),
94323
+ pinnedSchemaKeysByValueId: /* @__PURE__ */ new Map()
94324
+ };
93984
94325
  }
93985
94326
  var declarationInitializerContextByDocument, defaultValuePlansByDocument;
93986
94327
  var init_initializer_materialization = __esm({
@@ -93989,6 +94330,7 @@ var init_initializer_materialization = __esm({
93989
94330
  init_deep_clone_plain_data();
93990
94331
  init_members();
93991
94332
  init_inheritance();
94333
+ init_instance_provenance();
93992
94334
  init_generics();
93993
94335
  init_evaluateInitializer();
93994
94336
  init_evaluateNSGetter();
@@ -94061,6 +94403,28 @@ function createTypedValueNormalizer(reader, document, childrenByContainerId, par
94061
94403
  }
94062
94404
  return normalizeLiteral(value);
94063
94405
  };
94406
+ const bindingTypes = /* @__PURE__ */ new Map();
94407
+ const bindingType = (memberId) => {
94408
+ const member = memberById2(memberId);
94409
+ if (member === void 0) return memberId;
94410
+ try {
94411
+ return genericBindingTypeInfo(member, /* @__PURE__ */ new Map(), document.members);
94412
+ } catch {
94413
+ return memberId;
94414
+ }
94415
+ };
94416
+ const normalizeGenericBindings = (bindings) => {
94417
+ const result = /* @__PURE__ */ Object.create(null);
94418
+ for (const [paramId, memberId] of Object.entries(bindings)) {
94419
+ let type = bindingTypes.get(memberId);
94420
+ if (type === void 0) {
94421
+ type = bindingType(memberId);
94422
+ bindingTypes.set(memberId, type);
94423
+ }
94424
+ result[paramId] = type;
94425
+ }
94426
+ return result;
94427
+ };
94064
94428
  const normalizeTypedRow = (valueId, typeInfo, placement, parentEnv = /* @__PURE__ */ new Map()) => {
94065
94429
  const row = reader.row(valueId, typeInfo, placement);
94066
94430
  if (row === void 0) return valueId;
@@ -94142,7 +94506,7 @@ function createTypedValueNormalizer(reader, document, childrenByContainerId, par
94142
94506
  const normalized = {
94143
94507
  ...rowIdentities?.has(valueId) ? { id: valueId } : {},
94144
94508
  ...typeof row.classId === "string" ? { classId: row.classId } : {},
94145
- ...row.genericBindings === void 0 ? {} : { genericBindings: row.genericBindings },
94509
+ ...row.genericBindings === void 0 ? {} : { genericBindings: normalizeGenericBindings(row.genericBindings) },
94146
94510
  value,
94147
94511
  ...carriesSemanticConstructorArguments(row) ? {
94148
94512
  constructorArgs: normalizeConstructorArgs(
@@ -94179,7 +94543,7 @@ function createTypedValueNormalizer(reader, document, childrenByContainerId, par
94179
94543
  const normalized = {
94180
94544
  ...rowIdentities?.has(valueId) ? { id: valueId } : {},
94181
94545
  ...typeof row.classId === "string" ? { classId: row.classId } : {},
94182
- ...row.genericBindings === void 0 ? {} : { genericBindings: row.genericBindings },
94546
+ ...row.genericBindings === void 0 ? {} : { genericBindings: normalizeGenericBindings(row.genericBindings) },
94183
94547
  // The containing Class schema proves this is an owned row edge, but an
94184
94548
  // unresolved generic member does not prove anything about strings in
94185
94549
  // the row's payload. Keep those strings literal instead of guessing
@@ -94531,10 +94895,15 @@ var init_effective_value_reader = __esm({
94531
94895
  return row;
94532
94896
  if (this.resolvedRoots.has(valueId)) return row;
94533
94897
  if (this.mode(valueId) === "partial") return row;
94898
+ if (this.context.overrideRows === "constructed" && this.overrides.has(valueId) && !this.graph.valuesById.has(valueId))
94899
+ return row;
94534
94900
  const schema = this.schema(classId);
94535
- if (schema.every(
94536
- (entry) => Object.prototype.hasOwnProperty.call(row.value, entry.schemaKey)
94537
- ))
94901
+ const record7 = row.value;
94902
+ if (schema.every((entry) => {
94903
+ if (Object.hasOwn(record7, entry.schemaKey)) return true;
94904
+ const member2 = this.memberForId(entry.memberId);
94905
+ return member2 !== null && !memberKindOwnsStoredValue(member2.kind);
94906
+ }))
94538
94907
  return row;
94539
94908
  this.resolvedRoots.add(valueId);
94540
94909
  const member = this.placementFor(valueId) ?? this.graph.ownerForValue(valueId) ?? {
@@ -94731,6 +95100,8 @@ var init_effective_value_reader = __esm({
94731
95100
  {
94732
95101
  ...this.context,
94733
95102
  containerMembership: options.containerMembership ?? this.context.containerMembership,
95103
+ // Describes this reader's overrides, not a fork's.
95104
+ overrideRows: void 0,
94734
95105
  ...options.readTracking === void 0 ? {} : { readTracking: options.readTracking }
94735
95106
  },
94736
95107
  this,
@@ -110382,7 +110753,7 @@ function toCanonicalJsonValue2(value) {
110382
110753
  if (!isPlainRecord2(value)) {
110383
110754
  throw new Error("Cannot canonicalize a non-plain object.");
110384
110755
  }
110385
- const canonical = {};
110756
+ const canonical = /* @__PURE__ */ Object.create(null);
110386
110757
  const entries = Object.entries(value).sort(
110387
110758
  ([left], [right]) => left.localeCompare(right)
110388
110759
  );
@@ -113765,6 +114136,7 @@ function headlessVirtualInstanceLookups(document, options = {}) {
113765
114136
  valueById: (id2) => indexed.valueById(id2) ?? virtual.valueById(id2),
113766
114137
  rowForValueReference: (value) => indexed.rowForValueReference(value) ?? virtual.rowForValueReference(value),
113767
114138
  virtualInstanceRowsForValue: (receiverValueId) => virtual.virtualInstanceRowsForValue(receiverValueId),
114139
+ virtualInstanceRootIdForValue: (valueId) => owningInstanceRootId(virtual.virtualInstanceGraphForValue(valueId)),
113768
114140
  // Stored-construction replay evaluates `ToVariant`, and production's
113769
114141
  // variant-constructed placements collapse through exactly this path.
113770
114142
  resolveVariantInstanceGraph: (args) => resolveVariantInstanceGraphForDocument2({
@@ -114673,6 +115045,7 @@ function validateWorldPlacementSidecars(args) {
114673
115045
  validatePlacementVariantBinding({
114674
115046
  assetClassId,
114675
115047
  placementId: args.placement.id,
115048
+ layer: "built",
114676
115049
  variantId: optionalNonEmptyString(
114677
115050
  args.isTile || !hasObjectSidecar ? getField(args.placement, "instanceVariantId") : record7.variantId
114678
115051
  ),
@@ -114681,12 +115054,25 @@ function validateWorldPlacementSidecars(args) {
114681
115054
  ),
114682
115055
  context: args.context
114683
115056
  });
115057
+ validatePlacementVariantBinding({
115058
+ assetClassId,
115059
+ placementId: args.placement.id,
115060
+ layer: "applied",
115061
+ variantId: optionalNonEmptyString(
115062
+ getField(args.placement, "instanceAppliedVariantId")
115063
+ ),
115064
+ rowValueId: optionalNonEmptyString(
115065
+ getField(args.placement, "instanceAppliedVariantRowValueId")
115066
+ ),
115067
+ context: args.context
115068
+ });
114684
115069
  }
114685
115070
  function validatePlacementVariantBinding(args) {
115071
+ const noun = args.layer === "built" ? "variant" : "applied variant";
114686
115072
  if (args.variantId === null) {
114687
115073
  if (args.rowValueId !== null) {
114688
115074
  throw new Error(
114689
- `Placement value "${args.placementId}" binds row "${args.rowValueId}" without a variant.`
115075
+ `Placement value "${args.placementId}" binds row "${args.rowValueId}" without a ${noun}.`
114690
115076
  );
114691
115077
  }
114692
115078
  return;
@@ -114694,19 +115080,24 @@ function validatePlacementVariantBinding(args) {
114694
115080
  const variant2 = args.context.variantsById.get(args.variantId);
114695
115081
  if (variant2 === void 0) {
114696
115082
  throw new Error(
114697
- `Placement value "${args.placementId}" references variant "${args.variantId}", which does not resolve to a live variant record.`
115083
+ `Placement value "${args.placementId}" references ${noun} "${args.variantId}", which does not resolve to a live variant record.`
114698
115084
  );
114699
115085
  }
114700
- if (variant2.classId !== args.assetClassId) {
115086
+ if (args.layer === "built" && variant2.classId !== args.assetClassId) {
114701
115087
  throw new Error(
114702
115088
  `Placement value "${args.placementId}" places class "${args.assetClassId}" but names variant "${args.variantId}" of class "${variant2.classId}"; variant lookup is not virtual.`
114703
115089
  );
114704
115090
  }
115091
+ if (args.layer === "applied" && !args.context.relationResolver.classAncestry(args.assetClassId).includes(variant2.classId)) {
115092
+ throw new Error(
115093
+ `Placement value "${args.placementId}" places class "${args.assetClassId}" but applies variant "${args.variantId}" of class "${variant2.classId}", which is not that class or a base of it.`
115094
+ );
115095
+ }
114705
115096
  const lookupRows = variant2.lookupRowValueIds;
114706
115097
  if (lookupRows === void 0) {
114707
115098
  if (args.rowValueId !== null) {
114708
115099
  throw new Error(
114709
- `Placement value "${args.placementId}" binds a row to plain variant "${args.variantId}".`
115100
+ `Placement value "${args.placementId}" binds a row to plain ${noun} "${args.variantId}".`
114710
115101
  );
114711
115102
  }
114712
115103
  return;
@@ -114718,7 +115109,7 @@ function validatePlacementVariantBinding(args) {
114718
115109
  }
114719
115110
  if (args.rowValueId === null || !rowIds.has(args.rowValueId)) {
114720
115111
  throw new Error(
114721
- `Placement value "${args.placementId}" must bind a live row from lookup variant "${args.variantId}".`
115112
+ `Placement value "${args.placementId}" must bind a live row from lookup ${noun} "${args.variantId}".`
114722
115113
  );
114723
115114
  }
114724
115115
  }
@@ -117793,6 +118184,12 @@ function materializePreparedInstanceInitializers(args) {
117793
118184
  );
117794
118185
  let currentReader = null;
117795
118186
  const requireCurrentReader = () => currentReader ??= new EffectiveValueReader(materializationScope.document);
118187
+ let ownedValueCollector;
118188
+ let valueHashes;
118189
+ const liveValueHashes = () => valueHashes ??= indexLiveContentHashesByRecordId(
118190
+ args.contentHashHeads,
118191
+ "value"
118192
+ );
117796
118193
  const owners = resolveSemanticOwnerMembersForValues(
117797
118194
  materializationScope.document,
117798
118195
  new Set(sites.keys()),
@@ -117840,7 +118237,17 @@ function materializePreparedInstanceInitializers(args) {
117840
118237
  storedConstructionReplay: true
117841
118238
  });
117842
118239
  if (existingConstructedRoot !== void 0) {
117843
- if (!isLiteralValueContent(materialized.root) || existingConstructedRoot.classId !== materialized.root.classId || !replayedCreationDataMatches({
118240
+ if (!isLiteralValueContent(materialized.root)) {
118241
+ throw new Error(
118242
+ `construction-arguments-conflict: Value "${valueId}" is already materialized, and its construction no longer evaluates to a stored instance. Delete and recreate the value with the new construction.`
118243
+ );
118244
+ }
118245
+ if (existingConstructedRoot.classId !== materialized.root.classId) {
118246
+ throw new Error(
118247
+ `construction-arguments-conflict: Value "${valueId}" is already materialized as class "${String(existingConstructedRoot.classId)}", and this construction builds class "${String(materialized.root.classId)}". Delete and recreate the value to change its class.`
118248
+ );
118249
+ }
118250
+ if (replayedCreationDataMatches({
117844
118251
  // The synthetic variant binding members are part of the ownership
117845
118252
  // scope that compiled and evaluated this initializer. Stored replay
117846
118253
  // closes its generic slot from the same ephemeral member id, so its
@@ -117851,13 +118258,10 @@ function materializePreparedInstanceInitializers(args) {
117851
118258
  replayRoot: materialized.root,
117852
118259
  replayCreated: materialized.createdValues
117853
118260
  })) {
117854
- throw new Error(
117855
- `construction-arguments-conflict: Value "${valueId}" is already materialized, and this construction changes its original arguments. Edit the instance's members, or delete and recreate the value with the new construction.`
117856
- );
118261
+ replayOnlyIndexes.push(site.index);
118262
+ batch.upsert([existingConstructedRoot]);
118263
+ return;
117857
118264
  }
117858
- replayOnlyIndexes.push(site.index);
117859
- batch.upsert([existingConstructedRoot]);
117860
- return;
117861
118265
  }
117862
118266
  const baseline = materializeInitializerValue2({
117863
118267
  document: currentDocument,
@@ -117884,7 +118288,8 @@ function materializePreparedInstanceInitializers(args) {
117884
118288
  // §4: a call-site field is an explicit override even when it equals
117885
118289
  // the class default, so the evaluated construction's own field list is
117886
118290
  // what pins rows against collapse.
117887
- pinnedRootSchemaKeys: materialized.pinnedRootSchemaKeys
118291
+ pinnedRootSchemaKeys: materialized.pinnedRootSchemaKeys,
118292
+ pinnedSchemaKeysByValueId: materialized.pinnedSchemaKeysByValueId
117888
118293
  });
117889
118294
  assertStoredClosuresKeepNoCaptures({
117890
118295
  sourceValueId: valueId,
@@ -117897,15 +118302,40 @@ function materializePreparedInstanceInitializers(args) {
117897
118302
  ...original,
117898
118303
  nextData: sparse2.root
117899
118304
  };
118305
+ if (existingConstructedRoot !== void 0) {
118306
+ const produced = new Set(sparse2.createdChildren.map((row) => row.id));
118307
+ ownedValueCollector ??= createOwnedValueDeletionCollector(args.document);
118308
+ for (const ownedId of ownedValueCollector.collect({
118309
+ rootIds: [valueId],
118310
+ rootMembers: /* @__PURE__ */ new Map([[valueId, member]])
118311
+ })) {
118312
+ if (ownedId === valueId || produced.has(ownedId)) continue;
118313
+ const contentHash = liveValueHashes().get(ownedId);
118314
+ if (contentHash === void 0) continue;
118315
+ args.prepared.push({
118316
+ recordKind: "value",
118317
+ recordId: ownedId,
118318
+ operation: "delete",
118319
+ deleted: true,
118320
+ expectedBaseContentHash: contentHash,
118321
+ intent: createProjectVersionIntent("value.delete", {
118322
+ source: "server-initializer-materialization",
118323
+ sourceValueId: valueId
118324
+ })
118325
+ });
118326
+ existingValueById.delete(ownedId);
118327
+ }
118328
+ }
117900
118329
  for (const created of sparse2.createdChildren) {
117901
118330
  const existing = existingValueById.get(created.id);
117902
118331
  if (existing !== void 0) {
117903
118332
  if (materializedValueRowsEqual(existing, created)) continue;
117904
- const contentHash = liveContentHash(
117905
- args.contentHashHeads,
117906
- "value",
117907
- created.id
117908
- );
118333
+ const contentHash = liveValueHashes().get(created.id);
118334
+ if (contentHash === void 0) {
118335
+ throw new Error(
118336
+ `Cannot reconcile materialized initializer row "${created.id}": its live content hash is unavailable.`
118337
+ );
118338
+ }
117909
118339
  args.prepared.push({
117910
118340
  recordKind: "value",
117911
118341
  recordId: created.id,
@@ -119138,7 +119568,11 @@ function seedRootRow(member, seed, rootId) {
119138
119568
  ...seed.constructorArgs === void 0 ? {} : { constructorArgs: seed.constructorArgs },
119139
119569
  ...seed.instanceConstructorId === void 0 ? {} : { instanceConstructorId: seed.instanceConstructorId },
119140
119570
  ...seed.instanceVariantId === void 0 ? {} : { instanceVariantId: seed.instanceVariantId },
119141
- ...seed.instanceVariantRowValueId === void 0 ? {} : { instanceVariantRowValueId: seed.instanceVariantRowValueId }
119571
+ ...seed.instanceVariantRowValueId === void 0 ? {} : { instanceVariantRowValueId: seed.instanceVariantRowValueId },
119572
+ ...seed.instanceAppliedVariantId === void 0 ? {} : { instanceAppliedVariantId: seed.instanceAppliedVariantId },
119573
+ ...seed.instanceAppliedVariantRowValueId === void 0 ? {} : {
119574
+ instanceAppliedVariantRowValueId: seed.instanceAppliedVariantRowValueId
119575
+ }
119142
119576
  };
119143
119577
  }
119144
119578
  function authoredSeedRowMatchesValue(row, value) {
@@ -119155,7 +119589,7 @@ function authoredSeedRowMatchesValue(row, value) {
119155
119589
  return isLiteralValueContent(value);
119156
119590
  }
119157
119591
  if (isInitValueContent(value)) return false;
119158
- const seedDeclaresProvenance = row.constructorArgs !== void 0 || row.instanceConstructorId !== void 0 || row.instanceVariantId !== void 0 || row.instanceVariantRowValueId !== void 0;
119592
+ const seedDeclaresProvenance = row.constructorArgs !== void 0 || row.instanceConstructorId !== void 0 || row.instanceVariantId !== void 0 || row.instanceVariantRowValueId !== void 0 || row.instanceAppliedVariantId !== void 0 || row.instanceAppliedVariantRowValueId !== void 0;
119159
119593
  return canonicallyEqual2(
119160
119594
  {
119161
119595
  value: row.value,
@@ -119281,6 +119715,10 @@ function materializeAuthoredSeedRow(args) {
119281
119715
  },
119282
119716
  ...args.row.instanceVariantId === void 0 ? {} : { instanceVariantId: args.row.instanceVariantId },
119283
119717
  ...args.row.instanceVariantRowValueId === void 0 ? {} : { instanceVariantRowValueId: args.row.instanceVariantRowValueId },
119718
+ ...args.row.instanceAppliedVariantId === void 0 ? {} : { instanceAppliedVariantId: args.row.instanceAppliedVariantId },
119719
+ ...args.row.instanceAppliedVariantRowValueId === void 0 ? {} : {
119720
+ instanceAppliedVariantRowValueId: args.row.instanceAppliedVariantRowValueId
119721
+ },
119284
119722
  ...args.row.containerId === void 0 ? {} : { containerId: args.row.containerId },
119285
119723
  ...args.row.genericBindings === void 0 ? {} : { genericBindings: { ...args.row.genericBindings } },
119286
119724
  ...args.row.sourceValueId === void 0 ? {} : { sourceValueId: args.row.sourceValueId },
@@ -129577,6 +130015,7 @@ function prepareClientPush(args) {
129577
130015
  if (change.recordKind !== "value" || change.operation !== "update") {
129578
130016
  continue;
129579
130017
  }
130018
+ if (isInitValueContent(change.nextData)) continue;
129580
130019
  const refusal = valueDematerializationRefusal({
129581
130020
  valueId: change.recordId,
129582
130021
  baseData: args.base.records.get(`value:${change.recordId}`)?.data,
@@ -129745,6 +130184,7 @@ var init_server_preparation_preflight = __esm({
129745
130184
  init_project_document_read();
129746
130185
  init_project_snapshot_derived_edges();
129747
130186
  init_project_version_whole_graph_validation();
130187
+ init_members();
129748
130188
  init_performance();
129749
130189
  init_trusted_commit_verification();
129750
130190
  ServerPreparationPreflightError = class extends Error {
@@ -129842,17 +130282,8 @@ function replayStoredConstructionV4(args) {
129842
130282
  createdAt: 0,
129843
130283
  updatedAt: 0
129844
130284
  };
129845
- const rootRecord = root;
129846
- const envelope = { ...rootRecord };
129847
- delete envelope.value;
129848
- delete envelope.classId;
129849
- delete envelope.constructorArgs;
129850
- delete envelope.instanceConstructorId;
129851
- delete envelope.instanceVariantId;
129852
- delete envelope.instanceVariantRowValueId;
129853
- delete envelope.init;
129854
130285
  const candidate = {
129855
- ...envelope,
130286
+ ...withoutMaterializedInstanceFields(root),
129856
130287
  init: args.compiledInitializer ?? { code: args.code }
129857
130288
  };
129858
130289
  if (args.compiledInitializer === void 0)
@@ -129911,7 +130342,7 @@ function replayStoredConstructionV4(args) {
129911
130342
  ...args.omitConstructionFields === true ? { constructionBaselineReplay: true } : {},
129912
130343
  ...args.initializerArgumentValues === void 0 ? {} : { argumentValues: args.initializerArgumentValues }
129913
130344
  });
129914
- args.onPinnedRootSchemaKeys?.(materialized.pinnedRootSchemaKeys);
130345
+ args.onPinnedSchemaKeys?.(materialized);
129915
130346
  return new Map(
129916
130347
  [materialized.root, ...materialized.createdValues].map((row) => [
129917
130348
  row.id,
@@ -130015,6 +130446,18 @@ function compilePulledProjectDocumentForEvaluationV4(document, compilationProjec
130015
130446
  }
130016
130447
  return compiled;
130017
130448
  }
130449
+ function withoutMaterializedInstanceFields(row) {
130450
+ const envelope = { ...row };
130451
+ delete envelope.value;
130452
+ delete envelope.classId;
130453
+ delete envelope.constructorArgs;
130454
+ delete envelope.instanceConstructorId;
130455
+ delete envelope.instanceVariantId;
130456
+ delete envelope.instanceVariantRowValueId;
130457
+ delete envelope.instanceAppliedVariantId;
130458
+ delete envelope.instanceAppliedVariantRowValueId;
130459
+ return envelope;
130460
+ }
130018
130461
  function assertPulledConstructorsCompiled(document, replayContext) {
130019
130462
  if (replayContext !== void 0 && replayContext.document !== document) {
130020
130463
  throw new Error(
@@ -132320,22 +132763,7 @@ function mergedOverStoredRow(base, lowered) {
132320
132763
  const code = storedInitCode(base, lowered.init.code);
132321
132764
  if (code !== lowered.init.code) merged.init = { ...lowered.init, code };
132322
132765
  }
132323
- const {
132324
- value: _value,
132325
- classId: _classId,
132326
- constructorArgs: _constructorArgs,
132327
- instanceConstructorId: _instanceConstructorId,
132328
- instanceVariantId: _instanceVariantId,
132329
- instanceVariantRowValueId: _instanceVariantRowValueId,
132330
- ...initializer
132331
- } = merged;
132332
- void _value;
132333
- void _classId;
132334
- void _constructorArgs;
132335
- void _instanceConstructorId;
132336
- void _instanceVariantId;
132337
- void _instanceVariantRowValueId;
132338
- return initializer;
132766
+ return withoutMaterializedInstanceFields(merged);
132339
132767
  }
132340
132768
  function storedCompiledClosure(stored, lowered) {
132341
132769
  if (!isNSDelegateClosureValueDraft(lowered)) return null;
@@ -132609,7 +133037,7 @@ function lowerMemberDefaultSourcesV4(state, analysis, manifest, options = {}) {
132609
133037
  `Member default ${label} was classified as an owned literal graph but lowered as an initializer.`
132610
133038
  );
132611
133039
  }
132612
- const emptyInlineClassDefault = member.kind === "class" && isObjectRecord2(seed.value) && Object.keys(seed.value).length === 0 && (seed.constructorArgs === void 0 || Object.keys(seed.constructorArgs).length === 0) && seed.instanceConstructorId == null && seed.instanceVariantId == null && seed.instanceVariantRowValueId == null;
133040
+ const emptyInlineClassDefault = member.kind === "class" && isObjectRecord2(seed.value) && Object.keys(seed.value).length === 0 && (seed.constructorArgs === void 0 || Object.keys(seed.constructorArgs).length === 0) && seed.instanceConstructorId == null && seed.instanceVariantId == null && seed.instanceVariantRowValueId == null && seed.instanceAppliedVariantId == null && seed.instanceAppliedVariantRowValueId == null;
132613
133041
  const matchesStoredDefault = storedDefault !== null && canonicallyEqual(seed.value, storedDefault.value) && (seed.classId ?? null) === (typeof storedDefaultClassId === "string" ? storedDefaultClassId : null);
132614
133042
  if ((emptyInlineClassDefault || matchesStoredDefault) && (seed.values === void 0 || seed.values.length === 0) && (seed.bindingMembers === void 0 || seed.bindingMembers.length === 0) && (seed.localizedTexts === void 0 || seed.localizedTexts.length === 0)) {
132615
133043
  for (const id2 of context.pendingValues.keys()) {
@@ -134127,7 +134555,11 @@ function readInstanceProvenance(value) {
134127
134555
  },
134128
134556
  instanceConstructorId: nullableString5(value.instanceConstructorId),
134129
134557
  instanceVariantId: nullableString5(value.instanceVariantId),
134130
- instanceVariantRowValueId: nullableString5(value.instanceVariantRowValueId)
134558
+ instanceVariantRowValueId: nullableString5(value.instanceVariantRowValueId),
134559
+ instanceAppliedVariantId: nullableString5(value.instanceAppliedVariantId),
134560
+ instanceAppliedVariantRowValueId: nullableString5(
134561
+ value.instanceAppliedVariantRowValueId
134562
+ )
134131
134563
  };
134132
134564
  }
134133
134565
  function preserveReboundValue(context, currentValueId, nextValueId, binding) {
@@ -134177,6 +134609,10 @@ function lowerStaticSeed(context, member, sourceExpression, source, valueId) {
134177
134609
  ...root.instanceConstructorId === void 0 ? {} : { instanceConstructorId: root.instanceConstructorId },
134178
134610
  ...root.instanceVariantId === void 0 ? {} : { instanceVariantId: root.instanceVariantId },
134179
134611
  ...root.instanceVariantRowValueId === void 0 ? {} : { instanceVariantRowValueId: root.instanceVariantRowValueId },
134612
+ ...root.instanceAppliedVariantId === void 0 ? {} : { instanceAppliedVariantId: root.instanceAppliedVariantId },
134613
+ ...root.instanceAppliedVariantRowValueId === void 0 ? {} : {
134614
+ instanceAppliedVariantRowValueId: root.instanceAppliedVariantRowValueId
134615
+ },
134180
134616
  ...rows.size === 0 && member.kind !== "class" && member.kind !== "list" && member.kind !== "set" && member.kind !== "dictionary" && localizedTexts.size === 0 ? {} : { values: [...rows.values()] },
134181
134617
  ...bindingMembers.length === 0 ? {} : { bindingMembers },
134182
134618
  ...localizedTexts.size === 0 ? {} : { localizedTexts: [...localizedTexts.values()] }
@@ -135586,37 +136022,15 @@ function lowerClassValue(context, member, expression, base, source, outerEnviron
135586
136022
  }
135587
136023
  }
135588
136024
  if (materializedConstruction !== "lower") {
135589
- if (materializedConstruction === "preserve" && isObjectRecord2(base.constructorArgs) && // An explicit `null` IS the recorded identity of a parameterless
135590
- // construction, so it owns no argument rows to retain. Inferring an
135591
- // overload for it would resolve the wrong constructor or refuse the
135592
- // plan outright.
135593
- base.instanceConstructorId !== null) {
135594
- const constructor2 = storedValueConstructor(
136025
+ if (materializedConstruction === "preserve" && classId === currentClassId) {
136026
+ retainConstructionArguments(
135595
136027
  context,
136028
+ base,
135596
136029
  schemaClass2,
135597
- recordedStoredConstructorId(base, schemaClass2)
135598
- );
135599
- const authoredArguments = constructorArgumentExpressions(expression);
135600
- for (let index = 0; index < constructor2.arguments.length; index += 1) {
135601
- const argument2 = constructor2.arguments[index];
135602
- if (argument2 === void 0) continue;
135603
- const valueId = base.constructorArgs[`__arg_${index}__`];
135604
- if (typeof valueId !== "string") continue;
135605
- if (!constructorArgumentOwnsRow(
135606
- argument2.type,
135607
- authoredArguments.get(argument2.name)
135608
- )) {
135609
- continue;
135610
- }
135611
- retainStoredValueSubgraph(
135612
- context,
135613
- valueId,
135614
- source.source,
135615
- /* @__PURE__ */ new Set(),
135616
- null,
135617
- environment
135618
- );
135619
- }
136030
+ expression,
136031
+ source.source,
136032
+ environment
136033
+ );
135620
136034
  }
135621
136035
  }
135622
136036
  return {
@@ -135625,6 +136039,163 @@ function lowerClassValue(context, member, expression, base, source, outerEnviron
135625
136039
  ...classId === currentClassId ? {} : { classId }
135626
136040
  };
135627
136041
  }
136042
+ function retainConstructionArguments(context, row, schemaClass2, expression, source, environment) {
136043
+ const constructorArgs2 = row.constructorArgs;
136044
+ if (!isObjectRecord2(constructorArgs2)) return;
136045
+ if (row.instanceConstructorId === null) return;
136046
+ const constructor2 = storedValueConstructor(
136047
+ context,
136048
+ schemaClass2,
136049
+ recordedStoredConstructorId(row, schemaClass2)
136050
+ );
136051
+ const authoredArguments = constructorArgumentExpressions(expression);
136052
+ const argumentEnvironment = valueGenericEnvironment(row, environment);
136053
+ for (let index = 0; index < constructor2.arguments.length; index += 1) {
136054
+ const argument2 = constructor2.arguments[index];
136055
+ if (argument2 === void 0) continue;
136056
+ const valueId = constructorArgs2[`__arg_${index}__`];
136057
+ if (typeof valueId !== "string") continue;
136058
+ const authored = authoredArguments.get(argument2.name);
136059
+ if (!constructorArgumentOwnsRow(argument2.type, authored)) continue;
136060
+ retainStoredValueSubgraph(
136061
+ context,
136062
+ valueId,
136063
+ source,
136064
+ /* @__PURE__ */ new Set(),
136065
+ null,
136066
+ argumentEnvironment
136067
+ );
136068
+ const building2 = authored === void 0 ? null : rowBuildingExpression(authored);
136069
+ if (building2 === null) continue;
136070
+ retainInlineConstructionArguments(
136071
+ context,
136072
+ valueId,
136073
+ argument2.type,
136074
+ building2,
136075
+ source,
136076
+ argumentEnvironment
136077
+ );
136078
+ }
136079
+ }
136080
+ function rowBuildingExpression(expression) {
136081
+ const unwrapped = annotatedValue(expression).expression;
136082
+ return unwrapped.kind === "new" || unwrapped.kind === "litList" || unwrapped.kind === "litDict" ? unwrapped : null;
136083
+ }
136084
+ function retainInlineConstructionArguments(context, valueId, slot, authored, source, environment) {
136085
+ const row = context.state[`value:${valueId}`]?.data;
136086
+ if (!isObjectRecord2(row)) return;
136087
+ if (authored.kind === "new") {
136088
+ const classId = stringOrNull2(row.classId);
136089
+ const schemaClass2 = classId === null ? void 0 : context.classes.get(classId);
136090
+ if (schemaClass2 === void 0) return;
136091
+ retainConstructionArguments(
136092
+ context,
136093
+ row,
136094
+ schemaClass2,
136095
+ authored,
136096
+ source,
136097
+ environment
136098
+ );
136099
+ if (authored.initializer === void 0) return;
136100
+ if (!isObjectRecord2(row.value)) return;
136101
+ retainInitializerConstructionArguments(
136102
+ context,
136103
+ row,
136104
+ row.value,
136105
+ schemaClass2.id,
136106
+ authored.initializer,
136107
+ source,
136108
+ environment
136109
+ );
136110
+ return;
136111
+ }
136112
+ const settled = settledArgumentSlot(context, slot, environment);
136113
+ if (authored.kind === "litList" && settled.kind === "list" && Array.isArray(row.value)) {
136114
+ const entrySlot = argumentSlotEntry(context, settled);
136115
+ if (entrySlot === null) return;
136116
+ for (const [index, element] of authored.elements.entries()) {
136117
+ const entryId = row.value[index];
136118
+ if (typeof entryId !== "string") continue;
136119
+ const building2 = rowBuildingExpression(element);
136120
+ if (building2 === null) continue;
136121
+ retainInlineConstructionArguments(
136122
+ context,
136123
+ entryId,
136124
+ entrySlot,
136125
+ building2,
136126
+ source,
136127
+ environment
136128
+ );
136129
+ }
136130
+ return;
136131
+ }
136132
+ if (authored.kind === "litDict" && settled.kind === "dictionary" && isObjectRecord2(row.value)) {
136133
+ const entrySlot = argumentSlotEntry(context, settled);
136134
+ if (entrySlot === null) return;
136135
+ const keyEnumId = dictionarySlotKeyEnumId(settled);
136136
+ const keyEnum = keyEnumId === null ? null : keyEnumById(context, keyEnumId);
136137
+ for (const entry of authored.entries) {
136138
+ const key = nestedDictionaryKey(entry.key, keyEnum);
136139
+ const entryId = key === null ? void 0 : row.value[key];
136140
+ if (typeof entryId !== "string") continue;
136141
+ const building2 = rowBuildingExpression(entry.value);
136142
+ if (building2 === null) continue;
136143
+ retainInlineConstructionArguments(
136144
+ context,
136145
+ entryId,
136146
+ entrySlot,
136147
+ building2,
136148
+ source,
136149
+ environment
136150
+ );
136151
+ }
136152
+ }
136153
+ }
136154
+ function settledArgumentSlot(context, slot, environment) {
136155
+ if (slot.kind !== "generic") return slot;
136156
+ if ("source" in slot) {
136157
+ return resolveGenericSchemaMember(context, slot, environment);
136158
+ }
136159
+ return storedGenericArgumentType(
136160
+ { manifestMembers: context.members },
136161
+ slot,
136162
+ environment
136163
+ );
136164
+ }
136165
+ function argumentSlotEntry(context, slot) {
136166
+ if ("entryType" in slot) return slot.entryType;
136167
+ return memberById(context, slot.entryMemberId);
136168
+ }
136169
+ function dictionarySlotKeyEnumId(slot) {
136170
+ if ("keyEnumId" in slot) return slot.keyEnumId;
136171
+ return slot.key.kind === "enum" ? slot.key.enumId : null;
136172
+ }
136173
+ function retainInitializerConstructionArguments(context, row, body, classId, initializer, source, environment) {
136174
+ const authoredMembers = /* @__PURE__ */ new Map();
136175
+ for (const assignment of initializer) {
136176
+ const building2 = rowBuildingExpression(assignment.value);
136177
+ if (building2 !== null) authoredMembers.set(assignment.name, building2);
136178
+ }
136179
+ if (authoredMembers.size === 0) return;
136180
+ const memberIds = storedClassSchemaMemberIds(context, classId);
136181
+ const renames = renamedSchemaKeys(context, classId);
136182
+ const memberEnvironment = valueGenericEnvironment(row, environment);
136183
+ for (const [storedKey, childId] of Object.entries(body)) {
136184
+ if (typeof childId !== "string") continue;
136185
+ const building2 = authoredMembers.get(renames.get(storedKey) ?? storedKey);
136186
+ if (building2 === void 0) continue;
136187
+ const member = memberById(context, memberIds.get(storedKey));
136188
+ if (member === null) continue;
136189
+ retainInlineConstructionArguments(
136190
+ context,
136191
+ childId,
136192
+ member,
136193
+ building2,
136194
+ source,
136195
+ memberEnvironment
136196
+ );
136197
+ }
136198
+ }
135628
136199
  function constructorArgumentOwnsRow(type, authoredArgument) {
135629
136200
  if (type.kind !== "class" && type.kind !== "interface" && type.kind !== "generic" && type.kind !== "list" && type.kind !== "set" && type.kind !== "dictionary") {
135630
136201
  return false;
@@ -137672,6 +138243,7 @@ function freshChildReplaysDeclaredDefault(args) {
137672
138243
  if (child2.genericBindings !== void 0) return false;
137673
138244
  if (child2.instanceVariantId != null) return false;
137674
138245
  if (child2.instanceVariantRowValueId != null) return false;
138246
+ if (child2.instanceAppliedVariantId != null) return false;
137675
138247
  if (context.collectionBindingMemberIds.has(childMember.id)) return false;
137676
138248
  const resolved = resolveGenericSchemaMember(
137677
138249
  context,
@@ -138142,15 +138714,16 @@ function requiredMember(context, id2) {
138142
138714
  }
138143
138715
  function dictionaryKeyEnum(context, member) {
138144
138716
  if (member.key.kind === "string") return null;
138145
- const name = context.enumNames.get(member.key.enumId);
138146
- const optionsByName = context.enumOptions.get(member.key.enumId);
138717
+ return keyEnumById(context, member.key.enumId);
138718
+ }
138719
+ function keyEnumById(context, enumId) {
138720
+ const name = context.enumNames.get(enumId);
138721
+ const optionsByName = context.enumOptions.get(enumId);
138147
138722
  if (name === void 0) {
138148
- throw new Error(`Unknown dictionary key enum ${member.key.enumId}.`);
138723
+ throw new Error(`Unknown dictionary key enum ${enumId}.`);
138149
138724
  }
138150
138725
  if (optionsByName === void 0) {
138151
- throw new Error(
138152
- `Dictionary key enum ${member.key.enumId} has no option index.`
138153
- );
138726
+ throw new Error(`Dictionary key enum ${enumId} has no option index.`);
138154
138727
  }
138155
138728
  return { name, optionsByName };
138156
138729
  }
@@ -138446,7 +139019,7 @@ function classValueBody(context, member, value, visited, targetTyped, outerEnvir
138446
139019
  context,
138447
139020
  value.id,
138448
139021
  replayConstruction,
138449
- concreteClassMemberForReplay(member, environment)
139022
+ concreteClassMemberForReplay(context, member, environment)
138450
139023
  );
138451
139024
  const replayRoot = replayRows === null || typeof value.id !== "string" ? void 0 : replayRows.get(value.id);
138452
139025
  const graph = replayRows === null || typeof value.id !== "string" ? null : context.readEffectiveValues().withRowOverrides(
@@ -138493,7 +139066,11 @@ function classValueBody(context, member, value, visited, targetTyped, outerEnvir
138493
139066
  if (!context.values.has(childId)) {
138494
139067
  const reader = context.readEffectiveValues();
138495
139068
  if (reader.row(childId) === void 0) {
138496
- const placement = concreteClassMemberForReplay(member, environment);
139069
+ const placement = concreteClassMemberForReplay(
139070
+ context,
139071
+ member,
139072
+ environment
139073
+ );
138497
139074
  if (!isAnyMemberBase(placement))
138498
139075
  throw new Error(
138499
139076
  `Stored class ${name} has no typed member placement.`
@@ -138657,7 +139234,7 @@ function storedReplayLeafValueMatches(type, value) {
138657
139234
  }
138658
139235
  function literalStoredReplayInitializer(context, valueId, code, member) {
138659
139236
  const value = context.values.get(valueId);
138660
- if (value === void 0 || typeof value.classId !== "string" || typeof value.instanceConstructorId !== "string" || typeof value.instanceVariantId === "string" || !isObjectRecord2(value.constructorArgs))
139237
+ if (value === void 0 || typeof value.classId !== "string" || typeof value.instanceConstructorId !== "string" || typeof value.instanceVariantId === "string" || typeof value.instanceAppliedVariantId === "string" || !isObjectRecord2(value.constructorArgs))
138661
139238
  return void 0;
138662
139239
  const schemaClass2 = context.manifestClasses.get(value.classId);
138663
139240
  if (schemaClass2?.requiredConstructorId !== value.instanceConstructorId)
@@ -138769,22 +139346,23 @@ function storedConstructionReplayRows(context, valueId, code, member) {
138769
139346
  context.constructionReplays.set(valueId, replay);
138770
139347
  return replay;
138771
139348
  }
138772
- function concreteClassMemberForReplay(member, environment) {
139349
+ function concreteClassMemberForReplay(context, member, environment) {
138773
139350
  if (numberField(member, "kind") !== 7 /* Class */) return member;
138774
139351
  const classArguments2 = isObjectRecord2(member.classArguments) ? member.classArguments : {};
139352
+ const parameters = context.manifestClasses.get(stringField2(member, "classId"))?.genericParameters ?? [];
138775
139353
  let changed = false;
138776
- const concreteArguments = Object.fromEntries(
138777
- Object.entries(classArguments2).map(([genericParamId, binding]) => {
138778
- const forwardedParamId = isObjectRecord2(binding) && (binding.kind === void 0 || binding.kind === 0 /* Generic */) && typeof binding.genericParamId === "string" ? binding.genericParamId : null;
138779
- const bindingMemberId = environment.get(genericParamId) ?? (forwardedParamId === null ? void 0 : environment.get(forwardedParamId));
138780
- if (bindingMemberId === void 0) return [genericParamId, binding];
138781
- changed = true;
138782
- return [
138783
- genericParamId,
138784
- { kind: 1 /* Member */, memberId: bindingMemberId }
138785
- ];
138786
- })
138787
- );
139354
+ const concreteArguments = { ...classArguments2 };
139355
+ for (const { id: genericParamId } of parameters) {
139356
+ const binding = classArguments2[genericParamId];
139357
+ const forwardedParamId = isObjectRecord2(binding) && (binding.kind === void 0 || binding.kind === 0 /* Generic */) && typeof binding.genericParamId === "string" ? binding.genericParamId : null;
139358
+ const bindingMemberId = environment.get(genericParamId) ?? (forwardedParamId === null ? void 0 : environment.get(forwardedParamId));
139359
+ if (bindingMemberId === void 0) continue;
139360
+ changed = true;
139361
+ concreteArguments[genericParamId] = {
139362
+ kind: 1 /* Member */,
139363
+ memberId: bindingMemberId
139364
+ };
139365
+ }
138788
139366
  return changed ? { ...member, classArguments: concreteArguments } : member;
138789
139367
  }
138790
139368
  function storedLookupIdentityIds(values, reader) {
@@ -139166,7 +139744,8 @@ function storedConstructorArgumentSource(context, type, value, environment, visi
139166
139744
  visited,
139167
139745
  false,
139168
139746
  false,
139169
- constructorOwnsGraph
139747
+ constructorOwnsGraph,
139748
+ cloneAggregateArguments
139170
139749
  );
139171
139750
  case "lookup":
139172
139751
  return referenceValue(
@@ -139501,7 +140080,7 @@ function storedSchemaTypeName(context, type, environment, valueId) {
139501
140080
  return "null";
139502
140081
  }
139503
140082
  }
139504
- function storedTypedRowSource(context, type, valueId, environment, visited, writeIdentity, partial = false, constructorOwnsGraph = false) {
140083
+ function storedTypedRowSource(context, type, valueId, environment, visited, writeIdentity, partial = false, constructorOwnsGraph = false, cloneAggregateArguments = false) {
139505
140084
  const symbol = context.symbolsByValueId.get(valueId);
139506
140085
  if (symbol !== void 0) return symbol;
139507
140086
  const row = context.values.get(valueId);
@@ -139510,6 +140089,31 @@ function storedTypedRowSource(context, type, valueId, environment, visited, writ
139510
140089
  `Stored ${type.kind} constructor argument references missing value row ${valueId}.`
139511
140090
  );
139512
140091
  }
140092
+ if (type.kind === "generic" && typeof row.classId !== "string") {
140093
+ return storedTypedRowSource(
140094
+ context,
140095
+ storedGenericArgumentType(context, type, environment),
140096
+ valueId,
140097
+ environment,
140098
+ visited,
140099
+ writeIdentity,
140100
+ partial,
140101
+ constructorOwnsGraph,
140102
+ cloneAggregateArguments
140103
+ );
140104
+ }
140105
+ if (cloneAggregateArguments) {
140106
+ const settled = type.kind === "generic" ? storedGenericArgumentType(context, type, environment) : type;
140107
+ if (settled.kind === "class" || settled.kind === "interface") {
140108
+ return storedAggregateReplaySource(
140109
+ context,
140110
+ settled,
140111
+ valueId,
140112
+ environment,
140113
+ constructorOwnsGraph
140114
+ );
140115
+ }
140116
+ }
139513
140117
  if (isSharedConstructorArgument(context, valueId, constructorOwnsGraph)) {
139514
140118
  return `Reference<${storedSchemaTypeName(context, type, environment, valueId)}>(id: ${quote3(valueId)})`;
139515
140119
  }
@@ -139522,8 +140126,8 @@ function storedTypedRowSource(context, type, valueId, environment, visited, writ
139522
140126
  visited.add(valueId);
139523
140127
  try {
139524
140128
  if (type.kind === "class" || type.kind === "interface" || type.kind === "generic") {
139525
- const classId = type.kind === "class" ? type.classId : typeof row.classId === "string" ? row.classId : null;
139526
- if (classId === null) {
140129
+ const classId = type.kind === "class" ? type.classId : row.classId;
140130
+ if (typeof classId !== "string") {
139527
140131
  throw new Error(
139528
140132
  `Stored ${type.kind} constructor argument ${valueId} has no concrete class.`
139529
140133
  );
@@ -139566,7 +140170,8 @@ ${ids.map(
139566
140170
  visited,
139567
140171
  true,
139568
140172
  false,
139569
- constructorOwnsGraph
140173
+ constructorOwnsGraph,
140174
+ cloneAggregateArguments
139570
140175
  ),
139571
140176
  2
139572
140177
  )
@@ -139595,7 +140200,8 @@ ${entries.flatMap(
139595
140200
  visited,
139596
140201
  false,
139597
140202
  false,
139598
- constructorOwnsGraph
140203
+ constructorOwnsGraph,
140204
+ cloneAggregateArguments
139599
140205
  )}`,
139600
140206
  2
139601
140207
  )
@@ -141205,8 +141811,8 @@ function initializerRecompileTargets(args) {
141205
141811
  })
141206
141812
  });
141207
141813
  }
141208
- function materializedInitializerReconciliationFailuresV4(args) {
141209
- if (args.reconciliations.size === 0) return [];
141814
+ function reconcileMaterializedInitializersV4(args) {
141815
+ if (args.reconciliations.size === 0) return { failures: [], rebuilds: [] };
141210
141816
  const records3 = reconciliationRecords(
141211
141817
  args.workspace,
141212
141818
  args.changes,
@@ -141284,7 +141890,6 @@ function materializedInitializerReconciliationFailuresV4(args) {
141284
141890
  }
141285
141891
  }
141286
141892
  const expressionsGrew = canonicalExpressions.size > (cached?.expressions.size ?? 0);
141287
- const authoredConstructionChangedByValueId = /* @__PURE__ */ new Map();
141288
141893
  const replayableValueIds = /* @__PURE__ */ new Set();
141289
141894
  for (const [valueId, reconciliation] of constructions) {
141290
141895
  const owner = candidateOwners.get(valueId);
@@ -141296,11 +141901,7 @@ function materializedInitializerReconciliationFailuresV4(args) {
141296
141901
  );
141297
141902
  }
141298
141903
  const authoredConstructionChanged = args.manifest !== void 0 && canonicalExpression !== reconciliation.construction;
141299
- authoredConstructionChangedByValueId.set(
141300
- valueId,
141301
- authoredConstructionChanged
141302
- );
141303
- if (reconciliation.kind === "storedArguments" && (authoredConstructionChanged || currentState().recompileTargets.valueIds.has(valueId))) {
141904
+ if (authoredConstructionChanged || reconciliation.kind === "storedArguments" && currentState().recompileTargets.valueIds.has(valueId)) {
141304
141905
  replayableValueIds.add(valueId);
141305
141906
  }
141306
141907
  }
@@ -141367,26 +141968,9 @@ function materializedInitializerReconciliationFailuresV4(args) {
141367
141968
  }
141368
141969
  let currentRows;
141369
141970
  let currentReader;
141971
+ let ownedValues;
141972
+ const rebuilds = [];
141370
141973
  for (const reconciliation of constructions.values()) {
141371
- if (reconciliation.kind === "canonicalConstruction") {
141372
- if (authoredConstructionChangedByValueId.get(reconciliation.valueId) !== true) {
141373
- continue;
141374
- }
141375
- const position2 = composeReferenceSitePosition(
141376
- reconciliation.site,
141377
- args.sourceTextByUri
141378
- );
141379
- failures.push(
141380
- new SchemaSourceError(
141381
- `construction-arguments-conflict: Value "${reconciliation.valueId}" is already materialized without durable constructor arguments, and this construction no longer matches its pulled canonical projection. Delete and recreate the value to change its construction.`,
141382
- position2.file,
141383
- position2.line,
141384
- position2.column,
141385
- "construction-arguments-conflict"
141386
- )
141387
- );
141388
- continue;
141389
- }
141390
141974
  if (!replayableValueIds.has(reconciliation.valueId)) continue;
141391
141975
  const owner = candidateOwners.get(reconciliation.valueId);
141392
141976
  if (owner === void 0) {
@@ -141414,7 +141998,7 @@ function materializedInitializerReconciliationFailuresV4(args) {
141414
141998
  }
141415
141999
  } catch (error) {
141416
142000
  if (error instanceof NSGetterRuntimeError && error.source === void 0 && args.forceRecompile !== true) {
141417
- return materializedInitializerReconciliationFailuresV4({
142001
+ return reconcileMaterializedInitializersV4({
141418
142002
  ...args,
141419
142003
  forceRecompile: true,
141420
142004
  useBuildCaches: false,
@@ -141438,34 +142022,81 @@ function materializedInitializerReconciliationFailuresV4(args) {
141438
142022
  );
141439
142023
  currentReader ??= new EffectiveValueReader(replayDocument, currentRows);
141440
142024
  const replay = replayRows.get(reconciliation.valueId);
141441
- const replayArgs = replay !== void 0 && isLiteralValueContent(replay) ? replay.constructorArgs : void 0;
142025
+ if (replay === void 0) {
142026
+ throw new Error(
142027
+ `Construction replay for value "${reconciliation.valueId}" produced no root row.`
142028
+ );
142029
+ }
141442
142030
  const currentRoot = currentRows.get(reconciliation.valueId);
141443
- const [storedArgs, replayedArgs] = isObjectRecord2(replayArgs) ? withoutSharedArguments(reconciliation.storedConstructorArgs, replayArgs) : [reconciliation.storedConstructorArgs, replayArgs];
141444
- const currentNormalized = currentRoot === void 0 ? void 0 : currentReader.normalizeConstructorArguments(
141445
- storedArgs,
142031
+ if (currentRoot === void 0) {
142032
+ throw new Error(
142033
+ `Cannot reconcile stored construction for value "${reconciliation.valueId}": its stored row is missing.`
142034
+ );
142035
+ }
142036
+ if (replay.classId !== currentRoot.classId) {
142037
+ const position = composeReferenceSitePosition(
142038
+ reconciliation.site,
142039
+ args.sourceTextByUri
142040
+ );
142041
+ failures.push(
142042
+ new SchemaSourceError(
142043
+ `construction-arguments-conflict: Value "${reconciliation.valueId}" is already materialized as another class. Delete and recreate the value to change its class.`,
142044
+ position.file,
142045
+ position.line,
142046
+ position.column,
142047
+ "construction-arguments-conflict"
142048
+ )
142049
+ );
142050
+ continue;
142051
+ }
142052
+ if (reconciliation.kind === "storedArguments" && storedArgumentsMatch({
142053
+ reader: currentReader,
142054
+ stored: reconciliation.storedConstructorArgs,
141446
142055
  currentRoot,
142056
+ replay,
142057
+ replayRows,
141447
142058
  owner
141448
- );
141449
- const replayNormalized = replay === void 0 || !isObjectRecord2(replayedArgs) ? void 0 : currentReader.withRowOverrides(replayRows).normalizeConstructorArguments(replayedArgs, replay, owner);
141450
- const argumentsMatch = isObjectRecord2(replayArgs) && currentRoot !== void 0 && replay !== void 0 && effectiveValuesEqual(currentNormalized, replayNormalized);
141451
- if (argumentsMatch) {
142059
+ })) {
141452
142060
  continue;
141453
142061
  }
141454
- const position = composeReferenceSitePosition(
141455
- reconciliation.site,
141456
- args.sourceTextByUri
141457
- );
141458
- failures.push(
141459
- new SchemaSourceError(
141460
- `construction-arguments-conflict: Value "${reconciliation.valueId}" is already materialized, and this construction changes its original arguments. Edit the instance's members, or delete and recreate the value with the new construction.`,
141461
- position.file,
141462
- position.line,
141463
- position.column,
141464
- "construction-arguments-conflict"
141465
- )
141466
- );
142062
+ const stored = currentState().records.get(
142063
+ `value:${reconciliation.valueId}`
142064
+ )?.data;
142065
+ if (!isObjectRecord2(stored)) {
142066
+ throw new Error(
142067
+ `Cannot rebuild construction for value "${reconciliation.valueId}": its pulled row is missing.`
142068
+ );
142069
+ }
142070
+ ownedValues ??= createOwnedValueDeletionCollector(replayDocument);
142071
+ rebuilds.push({
142072
+ valueId: reconciliation.valueId,
142073
+ row: rebuiltConstructionRow(stored, reconciliation.code),
142074
+ ownedValueIds: ownedValues.collect({
142075
+ rootIds: [reconciliation.valueId],
142076
+ rootMembers: /* @__PURE__ */ new Map([[reconciliation.valueId, owner]])
142077
+ })
142078
+ });
141467
142079
  }
141468
- return failures;
142080
+ return { failures, rebuilds };
142081
+ }
142082
+ function storedArgumentsMatch(args) {
142083
+ const replayArgs = isLiteralValueContent(args.replay) ? args.replay.constructorArgs : void 0;
142084
+ if (!isObjectRecord2(replayArgs)) return false;
142085
+ const [storedArgs, replayedArgs] = withoutSharedArguments(
142086
+ args.stored,
142087
+ replayArgs
142088
+ );
142089
+ return effectiveValuesEqual(
142090
+ args.reader.normalizeConstructorArguments(
142091
+ storedArgs,
142092
+ args.currentRoot,
142093
+ args.owner
142094
+ ),
142095
+ args.reader.withRowOverrides(args.replayRows).normalizeConstructorArguments(replayedArgs, args.replay, args.owner)
142096
+ );
142097
+ }
142098
+ function rebuiltConstructionRow(data, code) {
142099
+ return { ...withoutMaterializedInstanceFields(data), init: { code } };
141469
142100
  }
141470
142101
  function retainedLiteralCompiles(document, retained, owners, rootOwners, stored) {
141471
142102
  if (retained.length === 0) return null;
@@ -141767,7 +142398,10 @@ function materializeInitializersLocallyV4(args) {
141767
142398
  });
141768
142399
  const code = initializerCode(records3, sourceValueId);
141769
142400
  let compiledInitializer;
141770
- let pinnedRootSchemaKeys = /* @__PURE__ */ new Set();
142401
+ let pinned = {
142402
+ pinnedRootSchemaKeys: /* @__PURE__ */ new Set(),
142403
+ pinnedSchemaKeysByValueId: /* @__PURE__ */ new Map()
142404
+ };
141771
142405
  const evaluated = replayStoredConstructionV4({
141772
142406
  records: records3,
141773
142407
  document,
@@ -141781,8 +142415,8 @@ function materializeInitializersLocallyV4(args) {
141781
142415
  compiledInitializer = init;
141782
142416
  compiledInitializers.set(sourceValueId, init);
141783
142417
  },
141784
- onPinnedRootSchemaKeys: (schemaKeys) => {
141785
- pinnedRootSchemaKeys = schemaKeys;
142418
+ onPinnedSchemaKeys: (keys) => {
142419
+ pinned = keys;
141786
142420
  }
141787
142421
  });
141788
142422
  const evaluatedRoot = evaluated.get(sourceValueId);
@@ -141846,7 +142480,8 @@ function materializeInitializersLocallyV4(args) {
141846
142480
  // §4: a call-site field is an explicit override even when it equals the
141847
142481
  // class default, so the evaluated construction's own field list is what
141848
142482
  // pins rows against collapse. Push preparation pins the same set.
141849
- pinnedRootSchemaKeys,
142483
+ pinnedRootSchemaKeys: pinned.pinnedRootSchemaKeys,
142484
+ pinnedSchemaKeysByValueId: pinned.pinnedSchemaKeysByValueId,
141850
142485
  virtualValueIdForSource: (instanceRootId, sourceIdentity3) => isPendingId(instanceRootId) || hasPendingVirtualSourceIdentity(sourceIdentity3) ? pendingVirtualValueId(instanceRootId, sourceIdentity3) : virtualValueId(instanceRootId, sourceIdentity3)
141851
142486
  });
141852
142487
  const evaluatedRows = [sparse2.root, ...sparse2.createdChildren];
@@ -142035,6 +142670,7 @@ var init_local_initializer_materialization = __esm({
142035
142670
  init_constructor_argument_ownership();
142036
142671
  init_neo_script_recompile_scope();
142037
142672
  init_compiler_adapter();
142673
+ init_owned_value_deletion();
142038
142674
  init_compiled_construction_types();
142039
142675
  init_project_version_schema_commit();
142040
142676
  init_value_row_owner_members();
@@ -148912,23 +149548,28 @@ function computeStatus(workspace, options, conflictedFiles, parseErrors, parseWa
148912
149548
  }
148913
149549
  if (!parseErrors.some(isBlockingSchemaSourceError)) {
148914
149550
  try {
148915
- parseErrors.push(
148916
- ...materializedInitializerReconciliationFailuresV4({
148917
- workspace,
148918
- changes,
148919
- authoredValueSeeds,
148920
- reconciliations: valueLowerRegistry.initializerReconciliations,
148921
- canonicalConstructions: valueLowerRegistry.materializedConstructorExpressions,
148922
- localizedTextDependencies,
148923
- manifest,
148924
- analysis: projectAnalysisV4,
148925
- forceRecompile: options.forceRecompile,
148926
- useBuildCaches: options.useBuildCaches,
148927
- sourceTextByUri: new Map(
148928
- sourceEntries.map((entry) => [entry.relPath, entry.source])
148929
- )
148930
- })
148931
- );
149551
+ const reconciliation = reconcileMaterializedInitializersV4({
149552
+ workspace,
149553
+ changes,
149554
+ authoredValueSeeds,
149555
+ reconciliations: valueLowerRegistry.initializerReconciliations,
149556
+ canonicalConstructions: valueLowerRegistry.materializedConstructorExpressions,
149557
+ localizedTextDependencies,
149558
+ manifest,
149559
+ analysis: projectAnalysisV4,
149560
+ forceRecompile: options.forceRecompile,
149561
+ useBuildCaches: options.useBuildCaches,
149562
+ sourceTextByUri: new Map(
149563
+ sourceEntries.map((entry) => [entry.relPath, entry.source])
149564
+ )
149565
+ });
149566
+ parseErrors.push(...reconciliation.failures);
149567
+ applyConstructionRebuildsV4({
149568
+ workspace,
149569
+ reconstructed: reconstructed3,
149570
+ changes,
149571
+ rebuilds: reconciliation.rebuilds
149572
+ });
148932
149573
  } catch (error) {
148933
149574
  parseErrors.push(
148934
149575
  error instanceof SchemaSourceError ? error : new SchemaSourceError(
@@ -149405,6 +150046,58 @@ function expandProspectiveAnimationInstances(document) {
149405
150046
  }
149406
150047
  return [...byId.values()];
149407
150048
  }
150049
+ function applyConstructionRebuildsV4(args) {
150050
+ if (args.rebuilds.length === 0) return;
150051
+ const replanned = /* @__PURE__ */ new Set();
150052
+ for (const rebuild of args.rebuilds) {
150053
+ for (const id2 of rebuild.ownedValueIds) {
150054
+ if (id2 === rebuild.valueId) continue;
150055
+ const key = recordStateKey("value", id2);
150056
+ replanned.add(key);
150057
+ const base = args.workspace.state.records[key];
150058
+ if (base === void 0) {
150059
+ args.reconstructed.delete(key);
150060
+ continue;
150061
+ }
150062
+ const reconstructed3 = args.reconstructed.get(key);
150063
+ if (reconstructed3 === void 0) continue;
150064
+ if (!isObjectRecord2(base.data)) {
150065
+ throw new Error(
150066
+ `Cannot replan value "${id2}" for a rebuilt construction: its pulled row is not an object.`
150067
+ );
150068
+ }
150069
+ args.reconstructed.set(key, { ...reconstructed3, fullData: base.data });
150070
+ }
150071
+ }
150072
+ const output = /* @__PURE__ */ new Map();
150073
+ for (const change of args.changes) {
150074
+ const key = recordStateKey(change.recordKind, change.recordId);
150075
+ if (!replanned.has(key)) output.set(key, change);
150076
+ }
150077
+ for (const rebuild of args.rebuilds) {
150078
+ const key = recordStateKey("value", rebuild.valueId);
150079
+ const base = args.workspace.state.records[key];
150080
+ if (base === void 0) {
150081
+ throw new Error(
150082
+ `Cannot rebuild construction for value "${rebuild.valueId}": it has no pulled row.`
150083
+ );
150084
+ }
150085
+ const reconstructed3 = args.reconstructed.get(key);
150086
+ if (reconstructed3 !== void 0)
150087
+ args.reconstructed.set(key, { ...reconstructed3, fullData: rebuild.row });
150088
+ output.set(
150089
+ key,
150090
+ recordUpsertChange({
150091
+ base,
150092
+ recordKind: "value",
150093
+ recordId: rebuild.valueId,
150094
+ file: reconstructed3?.file ?? output.get(key)?.file ?? null,
150095
+ nextData: rebuild.row
150096
+ })
150097
+ );
150098
+ }
150099
+ args.changes.splice(0, args.changes.length, ...output.values());
150100
+ }
149408
150101
  function collapseLocalizedSourceRevertsV4(args) {
149409
150102
  const edited = args.changes.filter(
149410
150103
  (change) => change.recordKind === "value" && change.kind !== "delete" && isMemberValue(change.nextData) && typeof change.nextData.value === "string" && args.loweringRecords[recordStateKey("localized-text", change.nextData.value)] === void 0 && !recordsSemanticallyEqual(
@@ -185144,7 +185837,9 @@ function rewrittenSeedProvenance(memberId, seed) {
185144
185837
  for (const field of [
185145
185838
  "instanceConstructorId",
185146
185839
  "instanceVariantId",
185147
- "instanceVariantRowValueId"
185840
+ "instanceVariantRowValueId",
185841
+ "instanceAppliedVariantId",
185842
+ "instanceAppliedVariantRowValueId"
185148
185843
  ]) {
185149
185844
  const candidate = seed[field];
185150
185845
  if (candidate !== void 0 && candidate !== null && typeof candidate !== "string") {
@@ -185161,6 +185856,12 @@ function rewrittenSeedProvenance(memberId, seed) {
185161
185856
  ...seed.instanceVariantId === void 0 ? {} : { instanceVariantId: seed.instanceVariantId },
185162
185857
  ...seed.instanceVariantRowValueId === void 0 ? {} : {
185163
185858
  instanceVariantRowValueId: seed.instanceVariantRowValueId
185859
+ },
185860
+ ...seed.instanceAppliedVariantId === void 0 ? {} : {
185861
+ instanceAppliedVariantId: seed.instanceAppliedVariantId
185862
+ },
185863
+ ...seed.instanceAppliedVariantRowValueId === void 0 ? {} : {
185864
+ instanceAppliedVariantRowValueId: seed.instanceAppliedVariantRowValueId
185164
185865
  }
185165
185866
  };
185166
185867
  }
@@ -201074,7 +201775,7 @@ There is no --keep-current: preserving current semantic state defines flatten.
201074
201775
  async function main() {
201075
201776
  const args = parseArgs(process.argv.slice(2));
201076
201777
  if (args.command === "--version") {
201077
- console.log("0.81.0");
201778
+ console.log("0.81.2");
201078
201779
  return;
201079
201780
  }
201080
201781
  if (args.command === null || args.command === "help" || args.command === "--help" || args.command === "-h") {