@palantir/pack.document-schema.type-gen 0.12.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/build/esm/commands/ir/irGenTypesHandler.js +6 -6
  2. package/build/esm/commands/ir/irGenTypesHandler.js.map +1 -1
  3. package/build/esm/utils/ir/__tests__/__snapshots__/generateModelsFromIr/custom-discriminant.js +1 -1
  4. package/build/esm/utils/ir/__tests__/__snapshots__/generateModelsFromIr/custom-discriminant.js.map +1 -1
  5. package/build/esm/utils/ir/__tests__/__snapshots__/generateModelsFromIr/external-refs.js +1 -1
  6. package/build/esm/utils/ir/__tests__/__snapshots__/generateModelsFromIr/external-refs.js.map +1 -1
  7. package/build/esm/utils/ir/__tests__/__snapshots__/generateModelsFromIr/simple-record.js +1 -1
  8. package/build/esm/utils/ir/__tests__/__snapshots__/generateModelsFromIr/simple-record.js.map +1 -1
  9. package/build/esm/utils/ir/__tests__/__snapshots__/generateModelsFromIr/union-types.js +1 -1
  10. package/build/esm/utils/ir/__tests__/__snapshots__/generateModelsFromIr/union-types.js.map +1 -1
  11. package/build/esm/utils/ir/__tests__/__snapshots__/generateZodSchemasFromIr/array-and-map-types.js +1 -1
  12. package/build/esm/utils/ir/__tests__/__snapshots__/generateZodSchemasFromIr/array-and-map-types.js.map +1 -1
  13. package/build/esm/utils/ir/__tests__/__snapshots__/generateZodSchemasFromIr/boolean-fields.js +1 -1
  14. package/build/esm/utils/ir/__tests__/__snapshots__/generateZodSchemasFromIr/boolean-fields.js.map +1 -1
  15. package/build/esm/utils/ir/__tests__/__snapshots__/generateZodSchemasFromIr/custom-discriminant.js +1 -1
  16. package/build/esm/utils/ir/__tests__/__snapshots__/generateZodSchemasFromIr/custom-discriminant.js.map +1 -1
  17. package/build/esm/utils/ir/__tests__/__snapshots__/generateZodSchemasFromIr/datetime-fields.js +1 -1
  18. package/build/esm/utils/ir/__tests__/__snapshots__/generateZodSchemasFromIr/datetime-fields.js.map +1 -1
  19. package/build/esm/utils/ir/__tests__/__snapshots__/generateZodSchemasFromIr/simple-records.js +1 -1
  20. package/build/esm/utils/ir/__tests__/__snapshots__/generateZodSchemasFromIr/simple-records.js.map +1 -1
  21. package/build/esm/utils/ir/__tests__/__snapshots__/generateZodSchemasFromIr/union-before-records.js +1 -1
  22. package/build/esm/utils/ir/__tests__/__snapshots__/generateZodSchemasFromIr/union-before-records.js.map +1 -1
  23. package/build/esm/utils/ir/__tests__/__snapshots__/generateZodSchemasFromIr/union-types.js +1 -1
  24. package/build/esm/utils/ir/__tests__/__snapshots__/generateZodSchemasFromIr/union-types.js.map +1 -1
  25. package/build/esm/utils/schema/__tests__/__snapshots__/generateDocumentTypeFromSchema/with-name-and-description.js +1 -1
  26. package/build/esm/utils/schema/__tests__/__snapshots__/generateDocumentTypeFromSchema/with-name-and-description.js.map +1 -1
  27. package/build/esm/utils/schema/__tests__/__snapshots__/generateVersionsFromSchema/single-version.js.map +1 -1
  28. package/build/esm/utils/schema/__tests__/__snapshots__/generateVersionsFromSchema/three-version-chain.js.map +1 -1
  29. package/build/esm/utils/schema/__tests__/__snapshots__/generateVersionsFromSchema/two-version.js.map +1 -1
  30. package/build/esm/utils/schema/__tests__/provenanceScenarios.test.js +184 -0
  31. package/build/esm/utils/schema/__tests__/provenanceScenarios.test.js.map +1 -0
  32. package/build/esm/utils/schema/__tests__/resolveSchemaChain.test.js +122 -0
  33. package/build/esm/utils/schema/__tests__/resolveSchemaChain.test.js.map +1 -0
  34. package/build/esm/utils/schema/generateInternalFromSchema.js +1 -1
  35. package/build/esm/utils/schema/generateInternalFromSchema.js.map +1 -1
  36. package/build/esm/utils/schema/generateScopeFromSchema.js +2 -2
  37. package/build/esm/utils/schema/generateScopeFromSchema.js.map +1 -1
  38. package/build/esm/utils/schema/loadSchemaModule.js +2 -5
  39. package/build/esm/utils/schema/loadSchemaModule.js.map +1 -1
  40. package/build/esm/utils/schema/resolveSchemaChain.js +98 -18
  41. package/build/esm/utils/schema/resolveSchemaChain.js.map +1 -1
  42. package/build/esm/utils/steps/__tests__/__snapshots__/types/arrayFields.js.map +1 -1
  43. package/build/esm/utils/steps/__tests__/__snapshots__/types/customDiscriminant.js +1 -1
  44. package/build/esm/utils/steps/__tests__/__snapshots__/types/customDiscriminant.js.map +1 -1
  45. package/build/esm/utils/steps/__tests__/__snapshots__/types/generateTypeScriptInterfaces.js +1 -1
  46. package/build/esm/utils/steps/__tests__/__snapshots__/types/generateTypeScriptInterfaces.js.map +1 -1
  47. package/build/esm/utils/steps/__tests__/__snapshots__/types/refTypes.js.map +1 -1
  48. package/build/esm/utils/steps/__tests__/__snapshots__/types/simpleRecord.js.map +1 -1
  49. package/build/esm/utils/steps/__tests__/__snapshots__/types/simpleSteps.js +1 -1
  50. package/build/esm/utils/steps/__tests__/__snapshots__/types/simpleSteps.js.map +1 -1
  51. package/build/esm/utils/steps/convertStepsToIr.js +49 -24
  52. package/build/esm/utils/steps/convertStepsToIr.js.map +1 -1
  53. package/build/types/commands/ir/irGenTypesHandler.d.ts.map +1 -1
  54. package/build/types/utils/schema/__tests__/provenanceScenarios.test.d.ts +2 -0
  55. package/build/types/utils/schema/__tests__/provenanceScenarios.test.d.ts.map +1 -0
  56. package/build/types/utils/schema/__tests__/resolveSchemaChain.test.d.ts +2 -0
  57. package/build/types/utils/schema/__tests__/resolveSchemaChain.test.d.ts.map +1 -0
  58. package/build/types/utils/schema/loadSchemaModule.d.ts.map +1 -1
  59. package/build/types/utils/schema/resolveSchemaChain.d.ts +12 -0
  60. package/build/types/utils/schema/resolveSchemaChain.d.ts.map +1 -1
  61. package/build/types/utils/steps/convertStepsToIr.d.ts +19 -4
  62. package/build/types/utils/steps/convertStepsToIr.d.ts.map +1 -1
  63. package/package.json +4 -4
@@ -0,0 +1,122 @@
1
+ /*
2
+ * Copyright 2026 Palantir Technologies, Inc. All rights reserved.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+
17
+ import * as P from "@palantir/pack.schema";
18
+ import { defineRecord, defineSchema, defineSchemaUpdate, nextSchema } from "@palantir/pack.schema";
19
+ import { describe, expect, it } from "vitest";
20
+ import { resolveSchemaChain, stripDeprecatedFieldsForSdk } from "../resolveSchemaChain.js";
21
+
22
+ /** Index a record model's fields by key for a given chain entry. */
23
+ function fieldsByKey(entry, modelKey) {
24
+ const model = entry.ir.models[modelKey];
25
+ if (model.type !== "record") throw new Error(`${modelKey} is not a record`);
26
+ return Object.fromEntries(model.record.fields.map(f => [f.key, f]));
27
+ }
28
+ describe("resolveSchemaChain provenance", () => {
29
+ const v1 = defineSchema({
30
+ ShapeBox: defineRecord("ShapeBox", {
31
+ docs: "A box",
32
+ fields: {
33
+ left: P.Double,
34
+ color: P.Optional(P.String)
35
+ }
36
+ })
37
+ });
38
+ const colorSplit = defineSchemaUpdate("colorSplit", schema => ({
39
+ ShapeBox: schema.ShapeBox.addField("fillColor", P.Optional(P.String), {
40
+ derivedFrom: ["color"]
41
+ }).addField("strokeColor", P.Optional(P.String), {
42
+ derivedFrom: ["color"]
43
+ }).deprecateField("color", "use fillColor/strokeColor").build()
44
+ }));
45
+ const v2 = nextSchema(v1).addSchemaUpdate(colorSplit).build();
46
+ it("derives addedInVersion from first appearance in the chain", () => {
47
+ const {
48
+ chain
49
+ } = resolveSchemaChain(v2);
50
+ const v2Fields = fieldsByKey(chain.find(c => c.version === 2), "ShapeBox");
51
+ expect(v2Fields.left.metadata.addedInVersion).toBe(1);
52
+ expect(v2Fields.fillColor.metadata.addedInVersion).toBe(2);
53
+ expect(v2Fields.strokeColor.metadata.addedInVersion).toBe(2);
54
+ });
55
+ it("keeps a deprecated field present and stamps deprecatedFromVersion + message", () => {
56
+ const {
57
+ chain
58
+ } = resolveSchemaChain(v2);
59
+ const v2Fields = fieldsByKey(chain.find(c => c.version === 2), "ShapeBox");
60
+ expect(v2Fields.color).toBeDefined();
61
+ expect(v2Fields.color.metadata.addedInVersion).toBe(1);
62
+ expect(v2Fields.color.metadata.deprecatedFromVersion).toBe(2);
63
+ expect(v2Fields.color.metadata.deprecatedMessage).toBe("use fillColor/strokeColor");
64
+ });
65
+ it("does not mark the field deprecated in versions before the deprecation", () => {
66
+ const {
67
+ chain
68
+ } = resolveSchemaChain(v2);
69
+ const v1Fields = fieldsByKey(chain.find(c => c.version === 1), "ShapeBox");
70
+ expect(v1Fields.color).toBeDefined();
71
+ expect(v1Fields.color.metadata.deprecatedFromVersion ?? undefined).toBeUndefined();
72
+ expect(v1Fields.fillColor).toBeUndefined();
73
+ });
74
+ it("stripDeprecatedFieldsForSdk drops deprecated fields from v>=deprecation only", () => {
75
+ const {
76
+ chain
77
+ } = resolveSchemaChain(v2);
78
+ const stripped = stripDeprecatedFieldsForSdk(chain);
79
+ const v1Fields = fieldsByKey(stripped.find(c => c.version === 1), "ShapeBox");
80
+ expect(v1Fields.color).toBeDefined();
81
+ const v2Fields = fieldsByKey(stripped.find(c => c.version === 2), "ShapeBox");
82
+ expect(v2Fields.color).toBeUndefined();
83
+ expect(v2Fields.fillColor).toBeDefined();
84
+ expect(fieldsByKey(chain.find(c => c.version === 2), "ShapeBox").color).toBeDefined();
85
+ });
86
+ });
87
+ describe("resolveSchemaChain — union provenance", () => {
88
+ const v1 = defineSchema({
89
+ Box: defineRecord("Box", {
90
+ docs: "",
91
+ fields: {
92
+ a: P.Double
93
+ }
94
+ }),
95
+ NodeShape: P.defineUnion("NodeShape", {
96
+ docs: "shape",
97
+ variants: {
98
+ box: defineRecord("Inner", {
99
+ docs: "",
100
+ fields: {
101
+ z: P.Double
102
+ }
103
+ })
104
+ }
105
+ })
106
+ });
107
+ const addB = defineSchemaUpdate("addB", schema => ({
108
+ Box: schema.Box.addField("b", P.Optional(P.String)).build()
109
+ }));
110
+ const v2 = nextSchema(v1).addSchemaUpdate(addB).build();
111
+ it("a v1-defined union stays addedInVersion 1 in every version", () => {
112
+ const {
113
+ chain
114
+ } = resolveSchemaChain(v2);
115
+ for (const version of [1, 2]) {
116
+ const union = chain.find(c => c.version === version).ir.models.NodeShape;
117
+ if (union.type !== "union") throw new Error("NodeShape should be a union");
118
+ expect(union.union.metadata.addedInVersion).toBe(1);
119
+ }
120
+ });
121
+ });
122
+ //# sourceMappingURL=resolveSchemaChain.test.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"resolveSchemaChain.test.js","names":["P","defineRecord","defineSchema","defineSchemaUpdate","nextSchema","describe","expect","it","resolveSchemaChain","stripDeprecatedFieldsForSdk","fieldsByKey","entry","modelKey","model","ir","models","type","Error","Object","fromEntries","record","fields","map","f","key","v1","ShapeBox","docs","left","Double","color","Optional","String","colorSplit","schema","addField","derivedFrom","deprecateField","build","v2","addSchemaUpdate","chain","v2Fields","find","c","version","metadata","addedInVersion","toBe","fillColor","strokeColor","toBeDefined","deprecatedFromVersion","deprecatedMessage","v1Fields","undefined","toBeUndefined","stripped","Box","a","NodeShape","defineUnion","variants","box","z","addB","union"],"sources":["resolveSchemaChain.test.ts"],"sourcesContent":["/*\n * Copyright 2026 Palantir Technologies, Inc. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport * as P from \"@palantir/pack.schema\";\nimport { defineRecord, defineSchema, defineSchemaUpdate, nextSchema } from \"@palantir/pack.schema\";\nimport { describe, expect, it } from \"vitest\";\nimport type {\n IFieldDef,\n IModelDef,\n} from \"../../../lib/pack-docschema-api/pack-docschema-ir/index.js\";\nimport {\n resolveSchemaChain,\n stripDeprecatedFieldsForSdk,\n type VersionedIrEntry,\n} from \"../resolveSchemaChain.js\";\n\n/** Index a record model's fields by key for a given chain entry. */\nfunction fieldsByKey(entry: VersionedIrEntry, modelKey: string): Record<string, IFieldDef> {\n const model: IModelDef = entry.ir.models[modelKey]!;\n if (model.type !== \"record\") throw new Error(`${modelKey} is not a record`);\n return Object.fromEntries(model.record.fields.map(f => [f.key, f]));\n}\n\ndescribe(\"resolveSchemaChain provenance\", () => {\n const v1 = defineSchema({\n ShapeBox: defineRecord(\"ShapeBox\", {\n docs: \"A box\",\n fields: { left: P.Double, color: P.Optional(P.String) },\n }),\n });\n\n const colorSplit = defineSchemaUpdate(\n \"colorSplit\",\n (schema: P.SchemaBuilder<typeof v1.models>) => ({\n ShapeBox: schema.ShapeBox\n .addField(\"fillColor\", P.Optional(P.String), { derivedFrom: [\"color\"] })\n .addField(\"strokeColor\", P.Optional(P.String), { derivedFrom: [\"color\"] })\n .deprecateField(\"color\", \"use fillColor/strokeColor\")\n .build(),\n }),\n );\n\n const v2 = nextSchema(v1).addSchemaUpdate(colorSplit).build();\n\n it(\"derives addedInVersion from first appearance in the chain\", () => {\n const { chain } = resolveSchemaChain(v2);\n const v2Fields = fieldsByKey(chain.find(c => c.version === 2)!, \"ShapeBox\");\n\n expect(v2Fields.left!.metadata.addedInVersion).toBe(1);\n expect(v2Fields.fillColor!.metadata.addedInVersion).toBe(2);\n expect(v2Fields.strokeColor!.metadata.addedInVersion).toBe(2);\n });\n\n it(\"keeps a deprecated field present and stamps deprecatedFromVersion + message\", () => {\n const { chain } = resolveSchemaChain(v2);\n const v2Fields = fieldsByKey(chain.find(c => c.version === 2)!, \"ShapeBox\");\n\n expect(v2Fields.color).toBeDefined();\n expect(v2Fields.color!.metadata.addedInVersion).toBe(1);\n expect(v2Fields.color!.metadata.deprecatedFromVersion).toBe(2);\n expect(v2Fields.color!.metadata.deprecatedMessage).toBe(\"use fillColor/strokeColor\");\n });\n\n it(\"does not mark the field deprecated in versions before the deprecation\", () => {\n const { chain } = resolveSchemaChain(v2);\n const v1Fields = fieldsByKey(chain.find(c => c.version === 1)!, \"ShapeBox\");\n\n expect(v1Fields.color).toBeDefined();\n expect(v1Fields.color!.metadata.deprecatedFromVersion ?? undefined).toBeUndefined();\n expect(v1Fields.fillColor).toBeUndefined();\n });\n\n it(\"stripDeprecatedFieldsForSdk drops deprecated fields from v>=deprecation only\", () => {\n const { chain } = resolveSchemaChain(v2);\n const stripped = stripDeprecatedFieldsForSdk(chain);\n\n const v1Fields = fieldsByKey(stripped.find(c => c.version === 1)!, \"ShapeBox\");\n expect(v1Fields.color).toBeDefined();\n\n const v2Fields = fieldsByKey(stripped.find(c => c.version === 2)!, \"ShapeBox\");\n expect(v2Fields.color).toBeUndefined();\n expect(v2Fields.fillColor).toBeDefined();\n\n expect(fieldsByKey(chain.find(c => c.version === 2)!, \"ShapeBox\").color).toBeDefined();\n });\n});\n\ndescribe(\"resolveSchemaChain — union provenance\", () => {\n const v1 = defineSchema({\n Box: defineRecord(\"Box\", { docs: \"\", fields: { a: P.Double } }),\n NodeShape: P.defineUnion(\"NodeShape\", {\n docs: \"shape\",\n variants: { box: defineRecord(\"Inner\", { docs: \"\", fields: { z: P.Double } }) },\n }),\n });\n const addB = defineSchemaUpdate(\n \"addB\",\n (schema: P.SchemaBuilder<typeof v1.models>) => ({\n Box: schema.Box.addField(\"b\", P.Optional(P.String)).build(),\n }),\n );\n const v2 = nextSchema(v1).addSchemaUpdate(addB).build();\n\n it(\"a v1-defined union stays addedInVersion 1 in every version\", () => {\n const { chain } = resolveSchemaChain(v2);\n for (const version of [1, 2]) {\n const union = chain.find(c => c.version === version)!.ir.models.NodeShape!;\n if (union.type !== \"union\") throw new Error(\"NodeShape should be a union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B,GAAG,EAAExB,MAAM,CAACwB,GAAG,CAACvB,QAAQ,CAAC,GAAG,EAAEnC,CAAC,CAAC+B,QAAQ,CAAC/B,CAAC,CAACgC,MAAM,CAAC,CAAC,CAACM,KAAK,CAAC;EAC5D,CAAC,CACH,CAAC;EACD,MAAMC,EAAE,GAAGnC,UAAU,CAACqB,EAAE,CAAC,CAACe,eAAe,CAACyB,IAAI,CAAC,CAAC3B,KAAK,CAAC,CAAC;EAEvD/B,EAAE,CAAC,4DAA4D,EAAE,MAAM;IACrE,MAAM;MAAEkC;IAAM,CAAC,GAAGjC,kBAAkB,CAAC+B,EAAE,CAAC;IACxC,KAAK,MAAMM,OAAO,IAAI,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE;MAC5B,MAAMqB,KAAK,GAAGzB,KAAK,CAACE,IAAI,CAACC,CAAC,IAAIA,CAAC,CAACC,OAAO,KAAKA,OAAO,CAAC,CAAE/B,EAAE,CAACC,MAAM,CAAC6C,SAAU;MAC1E,IAAIM,KAAK,CAAClD,IAAI,KAAK,OAAO,EAAE,MAAM,IAAIC,KAAK,CAAC,6BAA6B,CAAC;MAC1EX,MAAM,CAAC4D,KAAK,CAACA,KAAK,CAACpB,QAAQ,CAACC,cAAc,CAAC,CAACC,IAAI,CAAC,CAAC,CAAC;IACrD;EACF,CAAC,CAAC;AACJ,CAAC,CAAC","ignoreList":[]}
@@ -105,7 +105,7 @@ function collectRecordModels(chain) {
105
105
  }
106
106
  }
107
107
 
108
- // Fields removed in this version
108
+ // Fields absent from this version relative to the previous one (i.e. deprecated fields).
109
109
  const removedFields = [];
110
110
  for (const fieldKey of prevFields) {
111
111
  if (!currFields.has(fieldKey)) {
@@ -1 +1 @@
1
- {"version":3,"file":"generateInternalFromSchema.js","names":["GENERATED_FILE_HEADER","convertFieldTypeToDescriptor","convertFieldTypeToInternalTypeScript","convertFieldTypeToInternalZod","chainHasDerivedFields","sortedEntries","map","Array","from","entries","sort","a","b","localeCompare","collectRecordModels","chain","allRecordModels","Map","version","ir","modelKey","modelDef","Object","models","type","has","set","allFields","steps","model","get","field","record","fields","existing","key","fieldType","isOptional","presentInVersions","Set","alwaysOptional","everOptional","add","i","length","prevEntry","currEntry","currModelDef","prevModelDef","prevFields","f","currFields","addedFields","recordUpgrades","migrations","fieldKey","annotation","derivedFrom","removedFields","push","size","addedInVersion","totalVersions","values","fieldInfo","generateInternalTypes","output","fieldName","tsType","optional","generatePerVersionInternalTypes","perModelVersions","list","sortedModels","versions","sortedFields","generateUpgrades","latestIr","hasRecords","hasUnions","some","m","imports","join","typeDescriptor","step","fieldMeta","d","default","undefined","JSON","stringify","union","discriminant","variantKey","variantModelKey","variants","generateInternalSchemaContent","zodType","generateUpgradeFns","perModel","neededTypes","currentIdx","findIndex","c","priorVersion","currentVersion","sorted","pickKeys","generateInternalFromChain","resolved","internalTypes","upgrades","internalSchema","internalUpgradeFns"],"sources":["generateInternalFromSchema.ts"],"sourcesContent":["/*\n * Copyright 2026 Palantir Technologies, Inc. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type {\n IFieldDef,\n IFieldTypeUnion,\n IRealTimeDocumentSchema,\n} from \"../../lib/pack-docschema-api/pack-docschema-ir/index.js\";\nimport { GENERATED_FILE_HEADER } from \"../generatedFileHeader.js\";\nimport {\n convertFieldTypeToDescriptor,\n convertFieldTypeToInternalTypeScript,\n convertFieldTypeToInternalZod,\n} from \"../ir/irFieldHelpers.js\";\nimport {\n chainHasDerivedFields,\n type ResolvedIrChain,\n type VersionedIrEntry,\n} from \"./resolveSchemaChain.js\";\n\nexport interface InternalTypesOutput {\n /** _internal/types.ts content */\n internalTypes: string;\n /** _internal/upgrades.ts content */\n upgrades: string;\n /** _internal/schema.ts content */\n internalSchema: string;\n /** _internal/upgradeFns.ts content */\n internalUpgradeFns: string;\n}\n\n/** Collected info about all fields for a model across all versions. */\ninterface AllFieldInfo {\n fieldType: IFieldTypeUnion;\n isOptional: boolean;\n /** Versions where this field exists. */\n presentInVersions: Set<number>;\n /** Whether field is always optional. */\n alwaysOptional: boolean;\n /** Whether field is optional in at least one version. */\n everOptional: boolean;\n}\n\n/**\n * Represents an upgrade step for a model between version transitions.\n */\ninterface UpgradeStep {\n addedInVersion: number;\n fields: Map<string, { derivedFrom: string[]; default?: unknown }>;\n removedFields: string[];\n}\n\ninterface RecordModelInfo {\n allFields: Map<string, AllFieldInfo>;\n steps: UpgradeStep[];\n}\n\n/**\n * Helper to iterate sorted entries of a Map.\n */\nfunction sortedEntries<V>(map: Map<string, V>): [string, V][] {\n return Array.from(map.entries()).sort(([a], [b]) => a.localeCompare(b));\n}\n\n/**\n * Collect all record model info across all versions and compute upgrade steps.\n */\nfunction collectRecordModels(\n chain: VersionedIrEntry[],\n): Map<string, RecordModelInfo> {\n const allRecordModels = new Map<string, RecordModelInfo>();\n\n // Initialize models from all versions\n for (const { version, ir } of chain) {\n for (const [modelKey, modelDef] of Object.entries(ir.models)) {\n if (modelDef.type !== \"record\") continue;\n\n if (!allRecordModels.has(modelKey)) {\n allRecordModels.set(modelKey, {\n allFields: new Map(),\n steps: [],\n });\n }\n\n const model = allRecordModels.get(modelKey)!;\n\n for (const field of modelDef.record.fields) {\n const existing = model.allFields.get(field.key);\n if (existing == null) {\n model.allFields.set(field.key, {\n fieldType: field.fieldType,\n isOptional: field.isOptional === true,\n presentInVersions: new Set([version]),\n alwaysOptional: field.isOptional === true,\n everOptional: field.isOptional === true,\n });\n } else {\n existing.presentInVersions.add(version);\n if (field.isOptional !== true) {\n existing.alwaysOptional = false;\n }\n if (field.isOptional === true) {\n existing.everOptional = true;\n }\n }\n }\n }\n }\n\n // Compute upgrade steps from version diffs\n for (let i = 1; i < chain.length; i++) {\n const prevEntry = chain[i - 1]!;\n const currEntry = chain[i]!;\n\n for (const [modelKey, currModelDef] of Object.entries(currEntry.ir.models)) {\n if (currModelDef.type !== \"record\") continue;\n\n const prevModelDef = prevEntry.ir.models[modelKey];\n if (prevModelDef == null || prevModelDef.type !== \"record\") continue;\n\n const model = allRecordModels.get(modelKey);\n if (model == null) continue;\n\n const prevFields = new Set(prevModelDef.record.fields.map(f => f.key));\n const currFields = new Set(currModelDef.record.fields.map(f => f.key));\n\n // Fields added in this version\n const addedFields = new Map<\n string,\n { derivedFrom: string[]; default?: unknown }\n >();\n const recordUpgrades = currEntry.migrations?.[modelKey];\n for (const fieldKey of currFields) {\n if (!prevFields.has(fieldKey)) {\n const annotation = recordUpgrades?.[fieldKey];\n if (annotation != null) {\n addedFields.set(fieldKey, {\n derivedFrom: [...annotation.derivedFrom],\n });\n } else {\n addedFields.set(fieldKey, {\n derivedFrom: [],\n });\n }\n }\n }\n\n // Fields removed in this version\n const removedFields: string[] = [];\n for (const fieldKey of prevFields) {\n if (!currFields.has(fieldKey)) {\n removedFields.push(fieldKey);\n }\n }\n\n if (addedFields.size > 0 || removedFields.length > 0) {\n model.steps.push({\n addedInVersion: currEntry.version,\n fields: addedFields,\n removedFields,\n });\n }\n }\n }\n\n // Mark fields that are not present in ALL versions as optional in internal type\n const totalVersions = chain.length;\n for (const model of allRecordModels.values()) {\n for (const [, fieldInfo] of model.allFields) {\n if (fieldInfo.presentInVersions.size < totalVersions) {\n fieldInfo.alwaysOptional = true;\n }\n }\n }\n\n return allRecordModels;\n}\n\n/**\n * Generate _internal/types.ts content.\n */\nfunction generateInternalTypes(\n allRecordModels: Map<string, RecordModelInfo>,\n): string {\n let output = GENERATED_FILE_HEADER;\n output += \"\\n\";\n\n for (const [modelKey, model] of sortedEntries(allRecordModels)) {\n output += `/** Internal representation containing all fields across all schema versions. */\\n`;\n output += `export interface ${modelKey}__Internal {\\n`;\n\n for (const [fieldName, fieldInfo] of sortedEntries(model.allFields)) {\n const tsType = convertFieldTypeToInternalTypeScript(\n fieldInfo.fieldType,\n fieldInfo.isOptional,\n );\n const optional = fieldInfo.alwaysOptional ? \"?\" : \"\";\n output += ` readonly ${fieldName}${optional}: ${tsType};\\n`;\n }\n\n output += \"}\\n\\n\";\n }\n\n return output;\n}\n\n/**\n * Generate per-version internal interfaces (e.g. `ShapeBox__v1`, `ShapeBox__v2`).\n *\n * Each interface contains only the fields present in that version, with their\n * actual optionality taken straight from that version's IR. The downstream\n * `DocumentUpgradeFns` generator uses these so each upgrade function's\n * parameter can `Pick` the prior version's fields and its return type can\n * index the current version's field type precisely.\n */\nfunction generatePerVersionInternalTypes(\n chain: VersionedIrEntry[],\n): string {\n // Group by model so each model's versions appear together in ascending order.\n const perModelVersions = new Map<\n string,\n { version: number; fields: readonly IFieldDef[] }[]\n >();\n\n for (const { version, ir } of chain) {\n for (const [modelKey, modelDef] of Object.entries(ir.models)) {\n if (modelDef.type !== \"record\") continue;\n let list = perModelVersions.get(modelKey);\n if (list == null) {\n list = [];\n perModelVersions.set(modelKey, list);\n }\n list.push({ version, fields: modelDef.record.fields });\n }\n }\n\n let output = \"\";\n const sortedModels = Array.from(perModelVersions.entries()).sort(([a], [b]) =>\n a.localeCompare(b)\n );\n for (const [modelKey, versions] of sortedModels) {\n for (const { version, fields } of versions) {\n output += `/** Internal representation of ${modelKey} at schema version ${version}. */\\n`;\n output += `export interface ${modelKey}__v${version} {\\n`;\n const sortedFields = [...fields].sort((a, b) => a.key.localeCompare(b.key));\n for (const field of sortedFields) {\n const tsType = convertFieldTypeToInternalTypeScript(\n field.fieldType,\n field.isOptional === true,\n );\n const optional = field.isOptional === true ? \"?\" : \"\";\n output += ` readonly ${field.key}${optional}: ${tsType};\\n`;\n }\n output += \"}\\n\\n\";\n }\n }\n return output;\n}\n\n/**\n * Generate _internal/upgrades.ts content.\n */\nfunction generateUpgrades(\n allRecordModels: Map<string, RecordModelInfo>,\n latestIr: IRealTimeDocumentSchema,\n): string {\n let output = GENERATED_FILE_HEADER;\n\n const hasRecords = allRecordModels.size > 0;\n const hasUnions = Object.values(latestIr.models).some(m => m.type === \"union\");\n\n const imports: string[] = [];\n if (hasRecords) imports.push(\"UpgradeRegistry\");\n if (hasUnions) imports.push(\"UnionUpgradeRegistry\");\n\n if (imports.length > 0) {\n output += `import type { ${\n imports.join(\", \")\n } } from \"@palantir/pack.document-schema.model-types\";\\n\\n`;\n }\n\n for (const [modelKey, model] of sortedEntries(allRecordModels)) {\n output += `export const ${modelKey}Upgrades: UpgradeRegistry<\"${modelKey}\"> = {\\n`;\n output += ` modelName: \"${modelKey}\",\\n`;\n\n // allFields\n output += ` allFields: {\\n`;\n for (const [fieldName, fieldInfo] of sortedEntries(model.allFields)) {\n const typeDescriptor = convertFieldTypeToDescriptor(\n fieldInfo.fieldType,\n fieldInfo.isOptional,\n );\n output += ` ${fieldName}: { type: ${typeDescriptor} },\\n`;\n }\n output += ` },\\n`;\n\n // steps\n output += ` steps: [\\n`;\n for (const step of model.steps) {\n output += ` {\\n`;\n output += ` addedInVersion: ${step.addedInVersion},\\n`;\n output += ` fields: {\\n`;\n for (const [fieldName, fieldMeta] of step.fields) {\n output += ` ${fieldName}: {\\n`;\n output += ` derivedFrom: [${\n fieldMeta.derivedFrom.map(d => `\"${d}\"`).join(\", \")\n }],\\n`;\n if (fieldMeta.default !== undefined) {\n output += ` default: ${JSON.stringify(fieldMeta.default)},\\n`;\n }\n output += ` },\\n`;\n }\n output += ` },\\n`;\n if (step.removedFields.length > 0) {\n output += ` removedFields: [${step.removedFields.map(f => `\"${f}\"`).join(\", \")}],\\n`;\n }\n output += ` },\\n`;\n }\n output += ` ],\\n`;\n\n output += `};\\n\\n`;\n }\n\n // Generate UnionUpgradeRegistry entries for union models\n for (const [modelKey, modelDef] of Object.entries(latestIr.models)) {\n if (modelDef.type !== \"union\") continue;\n\n const union = modelDef.union;\n output += `export const ${modelKey}Upgrades: UnionUpgradeRegistry<\"${modelKey}\"> = {\\n`;\n output += ` modelName: \"${modelKey}\",\\n`;\n output += ` discriminant: \"${union.discriminant}\",\\n`;\n output += ` variants: {\\n`;\n for (const [variantKey, variantModelKey] of Object.entries(union.variants)) {\n output += ` \"${variantKey}\": \"${variantModelKey}\",\\n`;\n }\n output += ` },\\n`;\n output += `};\\n\\n`;\n }\n\n return output;\n}\n\n/**\n * Generate _internal/schema.ts content.\n */\nfunction generateInternalSchemaContent(\n allRecordModels: Map<string, RecordModelInfo>,\n): string {\n let output = GENERATED_FILE_HEADER;\n output += `import { z } from \"zod\";\\n\\n`;\n\n for (const [modelKey, model] of sortedEntries(allRecordModels)) {\n output += `export const ${modelKey}InternalSchema = z.object({\\n`;\n\n for (const [fieldName, fieldInfo] of sortedEntries(model.allFields)) {\n // Use everOptional: a field optional in ANY version must stay optional\n // in the internal schema because older documents may legitimately omit it.\n const zodType = convertFieldTypeToInternalZod(\n fieldInfo.fieldType,\n fieldInfo.alwaysOptional || fieldInfo.everOptional,\n );\n output += ` ${fieldName}: ${zodType},\\n`;\n }\n\n output += `}).passthrough();\\n\\n`;\n }\n\n return output;\n}\n\n/**\n * Generate _internal/upgradeFns.ts content: a typed `DocumentUpgradeFns`\n * interface enumerating every upgrade function the app must supply at boot.\n *\n * For every `(modelName, v${version}, fieldName)` triple where `derivedFrom` is\n * non-empty, emit a property typed\n * `(oldFields: Pick<<Model>__v<prior>, derivedFrom[number]>) => <Model>__v<current>[fieldName]`.\n * Additive fields (empty `derivedFrom`) are intentionally absent — they are\n * handled by the structural `default` in `_internal/upgrades.ts`.\n *\n * The interface is consumed by the generated `DocumentModel` factory in\n * `models.ts`, which requires it as a parameter when the schema has any\n * derived fields. Schemas without derived fields emit an empty interface\n * (still exported for type-uniformity in downstream code).\n */\nfunction generateUpgradeFns(\n chain: VersionedIrEntry[],\n allRecordModels: Map<string, RecordModelInfo>,\n): string {\n interface UpgradeFnEntry {\n fieldName: string;\n derivedFrom: readonly string[];\n }\n interface StepEntry {\n currentVersion: number;\n priorVersion: number;\n fields: UpgradeFnEntry[];\n }\n\n const perModel = new Map<string, StepEntry[]>();\n const neededTypes = new Set<string>();\n\n for (const [modelKey, model] of sortedEntries(allRecordModels)) {\n for (const step of model.steps) {\n const currentIdx = chain.findIndex(c => c.version === step.addedInVersion);\n if (currentIdx <= 0) continue;\n const priorVersion = chain[currentIdx - 1]!.version;\n\n const fields: UpgradeFnEntry[] = [];\n for (const [fieldName, fieldMeta] of step.fields) {\n if (fieldMeta.derivedFrom.length === 0) continue;\n fields.push({ fieldName, derivedFrom: [...fieldMeta.derivedFrom] });\n }\n if (fields.length === 0) continue;\n\n let list = perModel.get(modelKey);\n if (list == null) {\n list = [];\n perModel.set(modelKey, list);\n }\n list.push({\n currentVersion: step.addedInVersion,\n priorVersion,\n fields,\n });\n neededTypes.add(`${modelKey}__v${priorVersion}`);\n neededTypes.add(`${modelKey}__v${step.addedInVersion}`);\n }\n }\n\n let output = GENERATED_FILE_HEADER;\n output += `\\n`;\n\n if (neededTypes.size > 0) {\n const sorted = Array.from(neededTypes).sort();\n output += `import type { ${sorted.join(\", \")} } from \"./types.js\";\\n\\n`;\n }\n\n output += `/**\\n`;\n output += ` * Typed upgrade functions the application must supply at boot. Coverage is\\n`;\n output +=\n ` * exhaustive: missing or extra entries fail type-check at the \\`DocumentModel(...)\\`\\n`;\n output += ` * call site. Additive fields (empty \\`derivedFrom\\`) are intentionally absent.\\n`;\n output += ` */\\n`;\n if (perModel.size === 0) {\n output += `// eslint-disable-next-line @typescript-eslint/no-empty-object-type\\n`;\n output += `export interface DocumentUpgradeFns {}\\n`;\n } else {\n output += `export interface DocumentUpgradeFns {\\n`;\n for (\n const [modelKey, steps] of Array.from(perModel.entries()).sort(([a], [b]) =>\n a.localeCompare(b)\n )\n ) {\n output += ` ${modelKey}: {\\n`;\n for (const step of steps) {\n output += ` v${step.currentVersion}: {\\n`;\n for (const f of step.fields) {\n const pickKeys = f.derivedFrom.map(d => `\"${d}\"`).join(\" | \");\n output +=\n ` ${f.fieldName}: (oldFields: Pick<${modelKey}__v${step.priorVersion}, ${pickKeys}>) => ${modelKey}__v${step.currentVersion}[\"${f.fieldName}\"];\\n`;\n }\n output += ` };\\n`;\n }\n output += ` };\\n`;\n }\n output += `}\\n`;\n }\n\n return output;\n}\n\n/**\n * Generate _internal/types.ts, _internal/upgrades.ts, _internal/schema.ts and\n * _internal/upgradeFns.ts from an already-resolved versioned IR chain.\n */\nexport function generateInternalFromChain(\n resolved: ResolvedIrChain,\n): InternalTypesOutput {\n const { chain } = resolved;\n const latestIr = chain[chain.length - 1]!.ir;\n\n const allRecordModels = collectRecordModels(chain);\n\n const internalTypes = generateInternalTypes(allRecordModels)\n + (chainHasDerivedFields(chain) ? generatePerVersionInternalTypes(chain) : \"\");\n const upgrades = generateUpgrades(allRecordModels, latestIr);\n const internalSchema = generateInternalSchemaContent(allRecordModels);\n const internalUpgradeFns = generateUpgradeFns(chain, allRecordModels);\n\n return { internalTypes, upgrades, internalSchema, internalUpgradeFns };\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAOA,SAASA,qBAAqB,QAAQ,2BAA2B;AACjE,SACEC,4BAA4B,EAC5BC,oCAAoC,EACpCC,6BAA6B,QACxB,yBAAyB;AAChC,SACEC,qBAAqB,QAGhB,yBAAyB;;AAahC;;AAYA;AACA;AACA;;AAYA;AACA;AACA;AACA,SAASC,aAAaA,CAAIC,GAAmB,EAAiB;EAC5D,OAAOC,KAAK,CAACC,IAAI,CAACF,GAAG,CAACG,OAAO,CAAC,CAAC,CAAC,CAACC,IAAI,CAAC,CAAC,CAACC,CAAC,CAAC,EAAE,CAACC,CAAC,CAAC,KAAKD,CAAC,CAACE,aAAa,CAACD,CAAC,CAAC,CAAC;AACzE;;AAEA;AACA;AACA;AACA,SAASE,mBAAmBA,CAC1BC,KAAyB,EACK;EAC9B,MAAMC,eAA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,CAACoB,YAAY,KAAKG,QAAQ,SAASxF,QAAQ,MAAMiE,IAAI,CAACqB,cAAc,KAAKxD,CAAC,CAACiB,SAAS,OAAO;QAC3J;QACAD,MAAM,IAAI,UAAU;MACtB;MACAA,MAAM,IAAI,QAAQ;IACpB;IACAA,MAAM,IAAI,KAAK;EACjB;EAEA,OAAOA,MAAM;AACf;;AAEA;AACA;AACA;AACA;AACA,OAAO,SAAS2C,yBAAyBA,CACvCC,QAAyB,EACJ;EACrB,MAAM;IAAE/F;EAAM,CAAC,GAAG+F,QAAQ;EAC1B,MAAMjC,QAAQ,GAAG9D,KAAK,CAACA,KAAK,CAAC6B,MAAM,GAAG,CAAC,CAAC,CAAEzB,EAAE;EAE5C,MAAMH,eAAe,GAAGF,mBAAmB,CAACC,KAAK,CAAC;EAElD,MAAMgG,aAAa,GAAG9C,qBAAqB,CAACjD,eAAe,CAAC,IACvDZ,qBAAqB,CAACW,KAAK,CAAC,GAAGuD,+BAA+B,CAACvD,KAAK,CAAC,GAAG,EAAE,CAAC;EAChF,MAAMiG,QAAQ,GAAGpC,gBAAgB,CAAC5D,eAAe,EAAE6D,QAAQ,CAAC;EAC5D,MAAMoC,cAAc,GAAGhB,6BAA6B,CAACjF,eAAe,CAAC;EACrE,MAAMkG,kBAAkB,GAAGf,kBAAkB,CAACpF,KAAK,EAAEC,eAAe,CAAC;EAErE,OAAO;IAAE+F,aAAa;IAAEC,QAAQ;IAAEC,cAAc;IAAEC;EAAmB,CAAC;AACxE","ignoreList":[]}
1
+ {"version":3,"file":"generateInternalFromSchema.js","names":["GENERATED_FILE_HEADER","convertFieldTypeToDescriptor","convertFieldTypeToInternalTypeScript","convertFieldTypeToInternalZod","chainHasDerivedFields","sortedEntries","map","Array","from","entries","sort","a","b","localeCompare","collectRecordModels","chain","allRecordModels","Map","version","ir","modelKey","modelDef","Object","models","type","has","set","allFields","steps","model","get","field","record","fields","existing","key","fieldType","isOptional","presentInVersions","Set","alwaysOptional","everOptional","add","i","length","prevEntry","currEntry","currModelDef","prevModelDef","prevFields","f","currFields","addedFields","recordUpgrades","migrations","fieldKey","annotation","derivedFrom","removedFields","push","size","addedInVersion","totalVersions","values","fieldInfo","generateInternalTypes","output","fieldName","tsType","optional","generatePerVersionInternalTypes","perModelVersions","list","sortedModels","versions","sortedFields","generateUpgrades","latestIr","hasRecords","hasUnions","some","m","imports","join","typeDescriptor","step","fieldMeta","d","default","undefined","JSON","stringify","union","discriminant","variantKey","variantModelKey","variants","generateInternalSchemaContent","zodType","generateUpgradeFns","perModel","neededTypes","currentIdx","findIndex","c","priorVersion","currentVersion","sorted","pickKeys","generateInternalFromChain","resolved","internalTypes","upgrades","internalSchema","internalUpgradeFns"],"sources":["generateInternalFromSchema.ts"],"sourcesContent":["/*\n * Copyright 2026 Palantir Technologies, Inc. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type {\n IFieldDef,\n IFieldTypeUnion,\n IRealTimeDocumentSchema,\n} from \"../../lib/pack-docschema-api/pack-docschema-ir/index.js\";\nimport { GENERATED_FILE_HEADER } from \"../generatedFileHeader.js\";\nimport {\n convertFieldTypeToDescriptor,\n convertFieldTypeToInternalTypeScript,\n convertFieldTypeToInternalZod,\n} from \"../ir/irFieldHelpers.js\";\nimport {\n chainHasDerivedFields,\n type ResolvedIrChain,\n type VersionedIrEntry,\n} from \"./resolveSchemaChain.js\";\n\nexport interface InternalTypesOutput {\n /** _internal/types.ts content */\n internalTypes: string;\n /** _internal/upgrades.ts content */\n upgrades: string;\n /** _internal/schema.ts content */\n internalSchema: string;\n /** _internal/upgradeFns.ts content */\n internalUpgradeFns: string;\n}\n\n/** Collected info about all fields for a model across all versions. */\ninterface AllFieldInfo {\n fieldType: IFieldTypeUnion;\n isOptional: boolean;\n /** Versions where this field exists. */\n presentInVersions: Set<number>;\n /** Whether field is always optional. */\n alwaysOptional: boolean;\n /** Whether field is optional in at least one version. */\n everOptional: boolean;\n}\n\n/**\n * Represents an upgrade step for a model between version transitions.\n */\ninterface UpgradeStep {\n addedInVersion: number;\n fields: Map<string, { derivedFrom: string[]; default?: unknown }>;\n removedFields: string[];\n}\n\ninterface RecordModelInfo {\n allFields: Map<string, AllFieldInfo>;\n steps: UpgradeStep[];\n}\n\n/**\n * Helper to iterate sorted entries of a Map.\n */\nfunction sortedEntries<V>(map: Map<string, V>): [string, V][] {\n return Array.from(map.entries()).sort(([a], [b]) => a.localeCompare(b));\n}\n\n/**\n * Collect all record model info across all versions and compute upgrade steps.\n */\nfunction collectRecordModels(\n chain: VersionedIrEntry[],\n): Map<string, RecordModelInfo> {\n const allRecordModels = new Map<string, RecordModelInfo>();\n\n // Initialize models from all versions\n for (const { version, ir } of chain) {\n for (const [modelKey, modelDef] of Object.entries(ir.models)) {\n if (modelDef.type !== \"record\") continue;\n\n if (!allRecordModels.has(modelKey)) {\n allRecordModels.set(modelKey, {\n allFields: new Map(),\n steps: [],\n });\n }\n\n const model = allRecordModels.get(modelKey)!;\n\n for (const field of modelDef.record.fields) {\n const existing = model.allFields.get(field.key);\n if (existing == null) {\n model.allFields.set(field.key, {\n fieldType: field.fieldType,\n isOptional: field.isOptional === true,\n presentInVersions: new Set([version]),\n alwaysOptional: field.isOptional === true,\n everOptional: field.isOptional === true,\n });\n } else {\n existing.presentInVersions.add(version);\n if (field.isOptional !== true) {\n existing.alwaysOptional = false;\n }\n if (field.isOptional === true) {\n existing.everOptional = true;\n }\n }\n }\n }\n }\n\n // Compute upgrade steps from version diffs\n for (let i = 1; i < chain.length; i++) {\n const prevEntry = chain[i - 1]!;\n const currEntry = chain[i]!;\n\n for (const [modelKey, currModelDef] of Object.entries(currEntry.ir.models)) {\n if (currModelDef.type !== \"record\") continue;\n\n const prevModelDef = prevEntry.ir.models[modelKey];\n if (prevModelDef == null || prevModelDef.type !== \"record\") continue;\n\n const model = allRecordModels.get(modelKey);\n if (model == null) continue;\n\n const prevFields = new Set(prevModelDef.record.fields.map(f => f.key));\n const currFields = new Set(currModelDef.record.fields.map(f => f.key));\n\n // Fields added in this version\n const addedFields = new Map<\n string,\n { derivedFrom: string[]; default?: unknown }\n >();\n const recordUpgrades = currEntry.migrations?.[modelKey];\n for (const fieldKey of currFields) {\n if (!prevFields.has(fieldKey)) {\n const annotation = recordUpgrades?.[fieldKey];\n if (annotation != null) {\n addedFields.set(fieldKey, {\n derivedFrom: [...annotation.derivedFrom],\n });\n } else {\n addedFields.set(fieldKey, {\n derivedFrom: [],\n });\n }\n }\n }\n\n // Fields absent from this version relative to the previous one (i.e. deprecated fields).\n const removedFields: string[] = [];\n for (const fieldKey of prevFields) {\n if (!currFields.has(fieldKey)) {\n removedFields.push(fieldKey);\n }\n }\n\n if (addedFields.size > 0 || removedFields.length > 0) {\n model.steps.push({\n addedInVersion: currEntry.version,\n fields: addedFields,\n removedFields,\n });\n }\n }\n }\n\n // Mark fields that are not present in ALL versions as optional in internal type\n const totalVersions = chain.length;\n for (const model of allRecordModels.values()) {\n for (const [, fieldInfo] of model.allFields) {\n if (fieldInfo.presentInVersions.size < totalVersions) {\n fieldInfo.alwaysOptional = true;\n }\n }\n }\n\n return allRecordModels;\n}\n\n/**\n * Generate _internal/types.ts content.\n */\nfunction generateInternalTypes(\n allRecordModels: Map<string, RecordModelInfo>,\n): string {\n let output = GENERATED_FILE_HEADER;\n output += \"\\n\";\n\n for (const [modelKey, model] of sortedEntries(allRecordModels)) {\n output += `/** Internal representation containing all fields across all schema versions. */\\n`;\n output += `export interface ${modelKey}__Internal {\\n`;\n\n for (const [fieldName, fieldInfo] of sortedEntries(model.allFields)) {\n const tsType = convertFieldTypeToInternalTypeScript(\n fieldInfo.fieldType,\n fieldInfo.isOptional,\n );\n const optional = fieldInfo.alwaysOptional ? \"?\" : \"\";\n output += ` readonly ${fieldName}${optional}: ${tsType};\\n`;\n }\n\n output += \"}\\n\\n\";\n }\n\n return output;\n}\n\n/**\n * Generate per-version internal interfaces (e.g. `ShapeBox__v1`, `ShapeBox__v2`).\n *\n * Each interface contains only the fields present in that version, with their\n * actual optionality taken straight from that version's IR. The downstream\n * `DocumentUpgradeFns` generator uses these so each upgrade function's\n * parameter can `Pick` the prior version's fields and its return type can\n * index the current version's field type precisely.\n */\nfunction generatePerVersionInternalTypes(\n chain: VersionedIrEntry[],\n): string {\n // Group by model so each model's versions appear together in ascending order.\n const perModelVersions = new Map<\n string,\n { version: number; fields: readonly IFieldDef[] }[]\n >();\n\n for (const { version, ir } of chain) {\n for (const [modelKey, modelDef] of Object.entries(ir.models)) {\n if (modelDef.type !== \"record\") continue;\n let list = perModelVersions.get(modelKey);\n if (list == null) {\n list = [];\n perModelVersions.set(modelKey, list);\n }\n list.push({ version, fields: modelDef.record.fields });\n }\n }\n\n let output = \"\";\n const sortedModels = Array.from(perModelVersions.entries()).sort(([a], [b]) =>\n a.localeCompare(b)\n );\n for (const [modelKey, versions] of sortedModels) {\n for (const { version, fields } of versions) {\n output += `/** Internal representation of ${modelKey} at schema version ${version}. */\\n`;\n output += `export interface ${modelKey}__v${version} {\\n`;\n const sortedFields = [...fields].sort((a, b) => a.key.localeCompare(b.key));\n for (const field of sortedFields) {\n const tsType = convertFieldTypeToInternalTypeScript(\n field.fieldType,\n field.isOptional === true,\n );\n const optional = field.isOptional === true ? \"?\" : \"\";\n output += ` readonly ${field.key}${optional}: ${tsType};\\n`;\n }\n output += \"}\\n\\n\";\n }\n }\n return output;\n}\n\n/**\n * Generate _internal/upgrades.ts content.\n */\nfunction generateUpgrades(\n allRecordModels: Map<string, RecordModelInfo>,\n latestIr: IRealTimeDocumentSchema,\n): string {\n let output = GENERATED_FILE_HEADER;\n\n const hasRecords = allRecordModels.size > 0;\n const hasUnions = Object.values(latestIr.models).some(m => m.type === \"union\");\n\n const imports: string[] = [];\n if (hasRecords) imports.push(\"UpgradeRegistry\");\n if (hasUnions) imports.push(\"UnionUpgradeRegistry\");\n\n if (imports.length > 0) {\n output += `import type { ${\n imports.join(\", \")\n } } from \"@palantir/pack.document-schema.model-types\";\\n\\n`;\n }\n\n for (const [modelKey, model] of sortedEntries(allRecordModels)) {\n output += `export const ${modelKey}Upgrades: UpgradeRegistry<\"${modelKey}\"> = {\\n`;\n output += ` modelName: \"${modelKey}\",\\n`;\n\n // allFields\n output += ` allFields: {\\n`;\n for (const [fieldName, fieldInfo] of sortedEntries(model.allFields)) {\n const typeDescriptor = convertFieldTypeToDescriptor(\n fieldInfo.fieldType,\n fieldInfo.isOptional,\n );\n output += ` ${fieldName}: { type: ${typeDescriptor} },\\n`;\n }\n output += ` },\\n`;\n\n // steps\n output += ` steps: [\\n`;\n for (const step of model.steps) {\n output += ` {\\n`;\n output += ` addedInVersion: ${step.addedInVersion},\\n`;\n output += ` fields: {\\n`;\n for (const [fieldName, fieldMeta] of step.fields) {\n output += ` ${fieldName}: {\\n`;\n output += ` derivedFrom: [${\n fieldMeta.derivedFrom.map(d => `\"${d}\"`).join(\", \")\n }],\\n`;\n if (fieldMeta.default !== undefined) {\n output += ` default: ${JSON.stringify(fieldMeta.default)},\\n`;\n }\n output += ` },\\n`;\n }\n output += ` },\\n`;\n if (step.removedFields.length > 0) {\n output += ` removedFields: [${step.removedFields.map(f => `\"${f}\"`).join(\", \")}],\\n`;\n }\n output += ` },\\n`;\n }\n output += ` ],\\n`;\n\n output += `};\\n\\n`;\n }\n\n // Generate UnionUpgradeRegistry entries for union models\n for (const [modelKey, modelDef] of Object.entries(latestIr.models)) {\n if (modelDef.type !== \"union\") continue;\n\n const union = modelDef.union;\n output += `export const ${modelKey}Upgrades: UnionUpgradeRegistry<\"${modelKey}\"> = {\\n`;\n output += ` modelName: \"${modelKey}\",\\n`;\n output += ` discriminant: \"${union.discriminant}\",\\n`;\n output += ` variants: {\\n`;\n for (const [variantKey, variantModelKey] of Object.entries(union.variants)) {\n output += ` \"${variantKey}\": \"${variantModelKey}\",\\n`;\n }\n output += ` },\\n`;\n output += `};\\n\\n`;\n }\n\n return output;\n}\n\n/**\n * Generate _internal/schema.ts content.\n */\nfunction generateInternalSchemaContent(\n allRecordModels: Map<string, RecordModelInfo>,\n): string {\n let output = GENERATED_FILE_HEADER;\n output += `import { z } from \"zod\";\\n\\n`;\n\n for (const [modelKey, model] of sortedEntries(allRecordModels)) {\n output += `export const ${modelKey}InternalSchema = z.object({\\n`;\n\n for (const [fieldName, fieldInfo] of sortedEntries(model.allFields)) {\n // Use everOptional: a field optional in ANY version must stay optional\n // in the internal schema because older documents may legitimately omit it.\n const zodType = convertFieldTypeToInternalZod(\n fieldInfo.fieldType,\n fieldInfo.alwaysOptional || fieldInfo.everOptional,\n );\n output += ` ${fieldName}: ${zodType},\\n`;\n }\n\n output += `}).passthrough();\\n\\n`;\n }\n\n return output;\n}\n\n/**\n * Generate _internal/upgradeFns.ts content: a typed `DocumentUpgradeFns`\n * interface enumerating every upgrade function the app must supply at boot.\n *\n * For every `(modelName, v${version}, fieldName)` triple where `derivedFrom` is\n * non-empty, emit a property typed\n * `(oldFields: Pick<<Model>__v<prior>, derivedFrom[number]>) => <Model>__v<current>[fieldName]`.\n * Additive fields (empty `derivedFrom`) are intentionally absent — they are\n * handled by the structural `default` in `_internal/upgrades.ts`.\n *\n * The interface is consumed by the generated `DocumentModel` factory in\n * `models.ts`, which requires it as a parameter when the schema has any\n * derived fields. Schemas without derived fields emit an empty interface\n * (still exported for type-uniformity in downstream code).\n */\nfunction generateUpgradeFns(\n chain: VersionedIrEntry[],\n allRecordModels: Map<string, RecordModelInfo>,\n): string {\n interface UpgradeFnEntry {\n fieldName: string;\n derivedFrom: readonly string[];\n }\n interface StepEntry {\n currentVersion: number;\n priorVersion: number;\n fields: UpgradeFnEntry[];\n }\n\n const perModel = new Map<string, StepEntry[]>();\n const neededTypes = new Set<string>();\n\n for (const [modelKey, model] of sortedEntries(allRecordModels)) {\n for (const step of model.steps) {\n const currentIdx = chain.findIndex(c => c.version === step.addedInVersion);\n if (currentIdx <= 0) continue;\n const priorVersion = chain[currentIdx - 1]!.version;\n\n const fields: UpgradeFnEntry[] = [];\n for (const [fieldName, fieldMeta] of step.fields) {\n if (fieldMeta.derivedFrom.length === 0) continue;\n fields.push({ fieldName, derivedFrom: [...fieldMeta.derivedFrom] });\n }\n if (fields.length === 0) continue;\n\n let list = perModel.get(modelKey);\n if (list == null) {\n list = [];\n perModel.set(modelKey, list);\n }\n list.push({\n currentVersion: step.addedInVersion,\n priorVersion,\n fields,\n });\n neededTypes.add(`${modelKey}__v${priorVersion}`);\n neededTypes.add(`${modelKey}__v${step.addedInVersion}`);\n }\n }\n\n let output = GENERATED_FILE_HEADER;\n output += `\\n`;\n\n if (neededTypes.size > 0) {\n const sorted = Array.from(neededTypes).sort();\n output += `import type { ${sorted.join(\", \")} } from \"./types.js\";\\n\\n`;\n }\n\n output += `/**\\n`;\n output += ` * Typed upgrade functions the application must supply at boot. Coverage is\\n`;\n output +=\n ` * exhaustive: missing or extra entries fail type-check at the \\`DocumentModel(...)\\`\\n`;\n output += ` * call site. Additive fields (empty \\`derivedFrom\\`) are intentionally absent.\\n`;\n output += ` */\\n`;\n if (perModel.size === 0) {\n output += `// eslint-disable-next-line @typescript-eslint/no-empty-object-type\\n`;\n output += `export interface DocumentUpgradeFns {}\\n`;\n } else {\n output += `export interface DocumentUpgradeFns {\\n`;\n for (\n const [modelKey, steps] of Array.from(perModel.entries()).sort(([a], [b]) =>\n a.localeCompare(b)\n )\n ) {\n output += ` ${modelKey}: {\\n`;\n for (const step of steps) {\n output += ` v${step.currentVersion}: {\\n`;\n for (const f of step.fields) {\n const pickKeys = f.derivedFrom.map(d => `\"${d}\"`).join(\" | \");\n output +=\n ` ${f.fieldName}: (oldFields: Pick<${modelKey}__v${step.priorVersion}, ${pickKeys}>) => ${modelKey}__v${step.currentVersion}[\"${f.fieldName}\"];\\n`;\n }\n output += ` };\\n`;\n }\n output += ` };\\n`;\n }\n output += `}\\n`;\n }\n\n return output;\n}\n\n/**\n * Generate _internal/types.ts, _internal/upgrades.ts, _internal/schema.ts and\n * _internal/upgradeFns.ts from an already-resolved versioned IR chain.\n */\nexport function generateInternalFromChain(\n resolved: ResolvedIrChain,\n): InternalTypesOutput {\n const { chain } = resolved;\n const latestIr = chain[chain.length - 1]!.ir;\n\n const allRecordModels = collectRecordModels(chain);\n\n const internalTypes = generateInternalTypes(allRecordModels)\n + (chainHasDerivedFields(chain) ? generatePerVersionInternalTypes(chain) : \"\");\n const upgrades = generateUpgrades(allRecordModels, latestIr);\n const internalSchema = generateInternalSchemaContent(allRecordModels);\n const internalUpgradeFns = generateUpgradeFns(chain, allRecordModels);\n\n return { internalTypes, upgrades, internalSchema, internalUpgradeFns };\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAOA,SAASA,qBAAqB,QAAQ,2BAA2B;AACjE,SACEC,4BAA4B,EAC5BC,oCAAoC,EACpCC,6BAA6B,QACxB,yBAAyB;AAChC,SACEC,qBAAqB,QAGhB,yBAAyB;;AAahC;;AAYA;AACA;AACA;;AAYA;AACA;AACA;AACA,SAASC,aAAaA,CAAIC,GAAmB,EAAiB;EAC5D,OAAOC,KAAK,CAACC,IAAI,CAACF,GAAG,CAACG,OAAO,CAAC,CAAC,CAAC,CAACC,IAAI,CAAC,CAAC,CAACC,CAAC,CAAC,EAAE,CAACC,CAAC,CAAC,KAAKD,CAAC,CAACE,aAAa,CAACD,CAAC,CAAC,CAAC;AACzE;;AAEA;AACA;AACA;AACA,SAASE,mBAAmBA,CAC1BC,KAAyB,EACK;EAC9B,MAAMC,eAAe,GAAG,IAAIC,GAAG,CAA0B,CAAC;;EAE1D;EACA,KAAK,MAAM;IAAEC,OAAO;IAAEC;EAAG,CAAC,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SAAS,OAAO;QAC3J;QACAD,MAAM,IAAI,UAAU;MACtB;MACAA,MAAM,IAAI,QAAQ;IACpB;IACAA,MAAM,IAAI,KAAK;EACjB;EAEA,OAAOA,MAAM;AACf;;AAEA;AACA;AACA;AACA;AACA,OAAO,SAAS2C,yBAAyBA,CACvCC,QAAyB,EACJ;EACrB,MAAM;IAAE/F;EAAM,CAAC,GAAG+F,QAAQ;EAC1B,MAAMjC,QAAQ,GAAG9D,KAAK,CAACA,KAAK,CAAC6B,MAAM,GAAG,CAAC,CAAC,CAAEzB,EAAE;EAE5C,MAAMH,eAAe,GAAGF,mBAAmB,CAACC,KAAK,CAAC;EAElD,MAAMgG,aAAa,GAAG9C,qBAAqB,CAACjD,eAAe,CAAC,IACvDZ,qBAAqB,CAACW,KAAK,CAAC,GAAGuD,+BAA+B,CAACvD,KAAK,CAAC,GAAG,EAAE,CAAC;EAChF,MAAMiG,QAAQ,GAAGpC,gBAAgB,CAAC5D,eAAe,EAAE6D,QAAQ,CAAC;EAC5D,MAAMoC,cAAc,GAAGhB,6BAA6B,CAACjF,eAAe,CAAC;EACrE,MAAMkG,kBAAkB,GAAGf,kBAAkB,CAACpF,KAAK,EAAEC,eAAe,CAAC;EAErE,OAAO;IAAE+F,aAAa;IAAEC,QAAQ;IAAEC,cAAc;IAAEC;EAAmB,CAAC;AACxE","ignoreList":[]}
@@ -100,10 +100,10 @@ export function generateScopeFromChain(resolved, minSupportedVersion) {
100
100
  }
101
101
  }
102
102
 
103
- // setCollectionRecord overloads
103
+ // setRecord overloads
104
104
  for (const [modelKey] of Object.entries(ir.models)) {
105
105
  const readType = versionedTypeName(modelKey, version);
106
- output += ` setCollectionRecord(model: typeof ${modelName(modelKey)}, id: RecordId, data: ${readType}): Promise<void>;\n`;
106
+ output += ` setRecord(model: typeof ${modelName(modelKey)}, id: RecordId, data: ${readType}): Promise<void>;\n`;
107
107
  }
108
108
  output += `}\n\n`;
109
109
  }
@@ -1 +1 @@
1
- {"version":3,"file":"generateScopeFromSchema.js","names":["GENERATED_FILE_HEADER","resolveMinVersion","modelName","MODELS_PATH","typesFilePath","versionedTypeName","versionedWriteTypeName","writeTypesFilePath","generateScopeFromChain","resolved","minSupportedVersion","chain","minVersion","supportedVersions","filter","v","version","latestIr","length","ir","allModelNames","modelKey","Object","keys","models","push","output","modelImports","map","n","typeImportsFromModels","join","readTypeImports","writeTypeImports","modelDef","entries","type","sort","writeType","readType","unionMembers","handlerProps"],"sources":["generateScopeFromSchema.ts"],"sourcesContent":["/*\n * Copyright 2026 Palantir Technologies, Inc. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { GENERATED_FILE_HEADER } from \"../generatedFileHeader.js\";\nimport type { ResolvedIrChain } from \"./resolveSchemaChain.js\";\nimport { resolveMinVersion } from \"./resolveSchemaChain.js\";\nimport {\n modelName,\n MODELS_PATH,\n typesFilePath,\n versionedTypeName,\n versionedWriteTypeName,\n writeTypesFilePath,\n} from \"./runtimeSchema.js\";\n\n/**\n * Generate versionedDocRef.ts from a versioned schema chain.\n *\n * Produces:\n * - Per-version VersionedDocRef_vN interfaces extending DocumentRef<DocumentModel>\n * - Union type VersionedDocRef = VersionedDocRef_v1 | VersionedDocRef_v2\n *\n * Every model gets a version-specific overload on every version so that\n * write data is always typed to the exact version, not the latest.\n */\nexport function generateScopeFromChain(\n resolved: ResolvedIrChain,\n minSupportedVersion?: number,\n): string {\n const { chain } = resolved;\n const { minVersion } = resolveMinVersion(chain, minSupportedVersion);\n\n // Filter to supported versions\n const supportedVersions = chain.filter(v => v.version >= minVersion);\n\n // Collect all model names from the latest IR\n const latestIr = chain[chain.length - 1]!.ir;\n const allModelNames: string[] = [];\n for (const modelKey of Object.keys(latestIr.models)) {\n allModelNames.push(modelKey);\n }\n\n // Build output\n let output = GENERATED_FILE_HEADER;\n\n // Import model-types\n output +=\n `import type { DocumentRef, RecordId, RecordRef } from \"@palantir/pack.document-schema.model-types\";\\n`;\n\n // Import model types from models.ts\n const modelImports = allModelNames.map(n => modelName(n));\n const typeImportsFromModels = [\"DocumentModel\", ...modelImports];\n output += `import type { ${typeImportsFromModels.join(\", \")} } from \"${MODELS_PATH}\";\\n`;\n\n // Import per-version types\n for (const { version, ir } of supportedVersions) {\n const readTypeImports: string[] = [];\n const writeTypeImports: string[] = [];\n\n for (const [modelKey, modelDef] of Object.entries(ir.models)) {\n if (modelDef.type === \"record\") {\n readTypeImports.push(versionedTypeName(modelKey, version));\n writeTypeImports.push(versionedWriteTypeName(modelKey, version));\n } else if (modelDef.type === \"union\") {\n readTypeImports.push(versionedTypeName(modelKey, version));\n }\n }\n\n if (readTypeImports.length > 0) {\n output += `import type { ${readTypeImports.sort().join(\", \")} } from \"${\n typesFilePath(version)\n }\";\\n`;\n }\n if (writeTypeImports.length > 0) {\n output += `import type { ${writeTypeImports.sort().join(\", \")} } from \"${\n writeTypesFilePath(version)\n }\";\\n`;\n }\n }\n\n output += \"\\n\";\n\n // Generate per-version VersionedDocRef interfaces extending DocumentRef.\n for (const { version, ir } of supportedVersions) {\n output += `export interface VersionedDocRef_v${version} extends DocumentRef<DocumentModel> {\\n`;\n output += ` readonly version: ${version};\\n`;\n\n // updateRecord overloads — record models get write types, union models get Partial<read>\n for (const [modelKey, modelDef] of Object.entries(ir.models)) {\n if (modelDef.type === \"record\") {\n const writeType = versionedWriteTypeName(modelKey, version);\n output += ` updateRecord(ref: RecordRef<typeof ${\n modelName(modelKey)\n }>, data: ${writeType}): Promise<void>;\\n`;\n } else if (modelDef.type === \"union\") {\n const readType = versionedTypeName(modelKey, version);\n output += ` updateRecord(ref: RecordRef<typeof ${\n modelName(modelKey)\n }>, data: Partial<${readType}>): Promise<void>;\\n`;\n }\n }\n\n // setCollectionRecord overloads\n for (const [modelKey] of Object.entries(ir.models)) {\n const readType = versionedTypeName(modelKey, version);\n output += ` setCollectionRecord(model: typeof ${\n modelName(modelKey)\n }, id: RecordId, data: ${readType}): Promise<void>;\\n`;\n }\n\n output += `}\\n\\n`;\n }\n\n // Union type\n if (supportedVersions.length === 1) {\n output += `export type VersionedDocRef = VersionedDocRef_v${supportedVersions[0]!.version};\\n`;\n } else {\n const unionMembers = supportedVersions.map(v => `VersionedDocRef_v${v.version}`).join(\" | \");\n output += `export type VersionedDocRef = ${unionMembers};\\n`;\n }\n\n // asVersioned — identity cast to unlock version-specific write overloads\n output += `\\n/** Narrow a DocumentRef to a version-discriminated type for type-safe writes. */\\n`;\n output += `export function asVersioned(docRef: DocumentRef<DocumentModel>): VersionedDocRef {\\n`;\n output += ` return docRef as VersionedDocRef;\\n`;\n output += `}\\n`;\n\n // matchVersion — exhaustive version handler\n const handlerProps = supportedVersions.map(\n v => ` readonly ${v.version}: (doc: VersionedDocRef_v${v.version}) => R;`,\n ).join(\"\\n\");\n\n output += `\\n/**\\n`;\n output += ` * Exhaustive version handler. TypeScript enforces that every supported\\n`;\n output += ` * version has a corresponding handler -- adding a new schema version\\n`;\n output += ` * produces a compile error at every call site until handled.\\n`;\n output += ` */\\n`;\n output += `export function matchVersion<R>(\\n`;\n output += ` doc: VersionedDocRef,\\n`;\n output += ` handlers: {\\n`;\n output += handlerProps + \"\\n\";\n output += ` },\\n`;\n output += `): R {\\n`;\n output += ` switch (doc.version) {\\n`;\n for (const { version } of supportedVersions) {\n output += ` case ${version}:\\n`;\n output += ` return handlers[${version}](doc);\\n`;\n }\n output += ` default:\\n`;\n output += ` throw new Error(\\`Unexpected document version: \\${(doc as any).version}\\`);\\n`;\n output += ` }\\n`;\n output += `}\\n`;\n\n return output;\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA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AG5B,iBAAiB,CAACe,GAAG,CACxCb,CAAC,IAAI,cAAcA,CAAC,CAACC,OAAO,4BAA4BD,CAAC,CAACC,OAAO,SACnE,CAAC,CAACe,IAAI,CAAC,IAAI,CAAC;EAEZL,MAAM,IAAI,SAAS;EACnBA,MAAM,IAAI,2EAA2E;EACrFA,MAAM,IAAI,yEAAyE;EACnFA,MAAM,IAAI,iEAAiE;EAC3EA,MAAM,IAAI,OAAO;EACjBA,MAAM,IAAI,oCAAoC;EAC9CA,MAAM,IAAI,2BAA2B;EACrCA,MAAM,IAAI,iBAAiB;EAC3BA,MAAM,IAAIe,YAAY,GAAG,IAAI;EAC7Bf,MAAM,IAAI,QAAQ;EAClBA,MAAM,IAAI,UAAU;EACpBA,MAAM,IAAI,4BAA4B;EACtC,KAAK,MAAM;IAAEV;EAAQ,CAAC,IAAIH,iBAAiB,EAAE;IAC3Ca,MAAM,IAAI,YAAYV,OAAO,KAAK;IAClCU,MAAM,IAAI,yBAAyBV,OAAO,WAAW;EACvD;EACAU,MAAM,IAAI,gBAAgB;EAC1BA,MAAM,IAAI,qFAAqF;EAC/FA,MAAM,IAAI,OAAO;EACjBA,MAAM,IAAI,KAAK;EAEf,OAAOA,MAAM;AACf","ignoreList":[]}
1
+ {"version":3,"file":"generateScopeFromSchema.js","names":["GENERATED_FILE_HEADER","resolveMinVersion","modelName","MODELS_PATH","typesFilePath","versionedTypeName","versionedWriteTypeName","writeTypesFilePath","generateScopeFromChain","resolved","minSupportedVersion","chain","minVersion","supportedVersions","filter","v","version","latestIr","length","ir","allModelNames","modelKey","Object","keys","models","push","output","modelImports","map","n","typeImportsFromModels","join","readTypeImports","writeTypeImports","modelDef","entries","type","sort","writeType","readType","unionMembers","handlerProps"],"sources":["generateScopeFromSchema.ts"],"sourcesContent":["/*\n * Copyright 2026 Palantir Technologies, Inc. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { GENERATED_FILE_HEADER } from \"../generatedFileHeader.js\";\nimport type { ResolvedIrChain } from \"./resolveSchemaChain.js\";\nimport { resolveMinVersion } from \"./resolveSchemaChain.js\";\nimport {\n modelName,\n MODELS_PATH,\n typesFilePath,\n versionedTypeName,\n versionedWriteTypeName,\n writeTypesFilePath,\n} from \"./runtimeSchema.js\";\n\n/**\n * Generate versionedDocRef.ts from a versioned schema chain.\n *\n * Produces:\n * - Per-version VersionedDocRef_vN interfaces extending DocumentRef<DocumentModel>\n * - Union type VersionedDocRef = VersionedDocRef_v1 | VersionedDocRef_v2\n *\n * Every model gets a version-specific overload on every version so that\n * write data is always typed to the exact version, not the latest.\n */\nexport function generateScopeFromChain(\n resolved: ResolvedIrChain,\n minSupportedVersion?: number,\n): string {\n const { chain } = resolved;\n const { minVersion } = resolveMinVersion(chain, minSupportedVersion);\n\n // Filter to supported versions\n const supportedVersions = chain.filter(v => v.version >= minVersion);\n\n // Collect all model names from the latest IR\n const latestIr = chain[chain.length - 1]!.ir;\n const allModelNames: string[] = [];\n for (const modelKey of Object.keys(latestIr.models)) {\n allModelNames.push(modelKey);\n }\n\n // Build output\n let output = GENERATED_FILE_HEADER;\n\n // Import model-types\n output +=\n `import type { DocumentRef, RecordId, RecordRef } from \"@palantir/pack.document-schema.model-types\";\\n`;\n\n // Import model types from models.ts\n const modelImports = allModelNames.map(n => modelName(n));\n const typeImportsFromModels = [\"DocumentModel\", ...modelImports];\n output += `import type { ${typeImportsFromModels.join(\", \")} } from \"${MODELS_PATH}\";\\n`;\n\n // Import per-version types\n for (const { version, ir } of supportedVersions) {\n const readTypeImports: string[] = [];\n const writeTypeImports: string[] = [];\n\n for (const [modelKey, modelDef] of Object.entries(ir.models)) {\n if (modelDef.type === \"record\") {\n readTypeImports.push(versionedTypeName(modelKey, version));\n writeTypeImports.push(versionedWriteTypeName(modelKey, version));\n } else if (modelDef.type === \"union\") {\n readTypeImports.push(versionedTypeName(modelKey, version));\n }\n }\n\n if (readTypeImports.length > 0) {\n output += `import type { ${readTypeImports.sort().join(\", \")} } from \"${\n typesFilePath(version)\n }\";\\n`;\n }\n if (writeTypeImports.length > 0) {\n output += `import type { ${writeTypeImports.sort().join(\", \")} } from \"${\n writeTypesFilePath(version)\n }\";\\n`;\n }\n }\n\n output += \"\\n\";\n\n // Generate per-version VersionedDocRef interfaces extending DocumentRef.\n for (const { version, ir } of supportedVersions) {\n output += `export interface VersionedDocRef_v${version} extends DocumentRef<DocumentModel> {\\n`;\n output += ` readonly version: ${version};\\n`;\n\n // updateRecord overloads — record models get write types, union models get Partial<read>\n for (const [modelKey, modelDef] of Object.entries(ir.models)) {\n if (modelDef.type === \"record\") {\n const writeType = versionedWriteTypeName(modelKey, version);\n output += ` updateRecord(ref: RecordRef<typeof ${\n modelName(modelKey)\n }>, data: ${writeType}): Promise<void>;\\n`;\n } else if (modelDef.type === \"union\") {\n const readType = versionedTypeName(modelKey, version);\n output += ` updateRecord(ref: RecordRef<typeof ${\n modelName(modelKey)\n }>, data: Partial<${readType}>): Promise<void>;\\n`;\n }\n }\n\n // setRecord overloads\n for (const [modelKey] of Object.entries(ir.models)) {\n const readType = versionedTypeName(modelKey, version);\n output += ` setRecord(model: typeof ${\n modelName(modelKey)\n }, id: RecordId, data: ${readType}): Promise<void>;\\n`;\n }\n\n output += `}\\n\\n`;\n }\n\n // Union type\n if (supportedVersions.length === 1) {\n output += `export type VersionedDocRef = VersionedDocRef_v${supportedVersions[0]!.version};\\n`;\n } else {\n const unionMembers = supportedVersions.map(v => `VersionedDocRef_v${v.version}`).join(\" | \");\n output += `export type VersionedDocRef = ${unionMembers};\\n`;\n }\n\n // asVersioned — identity cast to unlock version-specific write overloads\n output += `\\n/** Narrow a DocumentRef to a version-discriminated type for type-safe writes. */\\n`;\n output += `export function asVersioned(docRef: DocumentRef<DocumentModel>): VersionedDocRef {\\n`;\n output += ` return docRef as VersionedDocRef;\\n`;\n output += `}\\n`;\n\n // matchVersion — exhaustive version handler\n const handlerProps = supportedVersions.map(\n v => ` readonly ${v.version}: (doc: VersionedDocRef_v${v.version}) => R;`,\n ).join(\"\\n\");\n\n output += `\\n/**\\n`;\n output += ` * Exhaustive version handler. TypeScript enforces that every supported\\n`;\n output += ` * version has a corresponding handler -- adding a new schema version\\n`;\n output += ` * produces a compile error at every call site until handled.\\n`;\n output += ` */\\n`;\n output += `export function matchVersion<R>(\\n`;\n output += ` doc: VersionedDocRef,\\n`;\n output += ` handlers: {\\n`;\n output += handlerProps + \"\\n\";\n output += ` },\\n`;\n output += `): R {\\n`;\n output += ` switch (doc.version) {\\n`;\n for (const { version } of supportedVersions) {\n output += ` case ${version}:\\n`;\n output += ` return handlers[${version}](doc);\\n`;\n }\n output += ` default:\\n`;\n output += ` throw new Error(\\`Unexpected document version: \\${(doc as any).version}\\`);\\n`;\n output += ` }\\n`;\n output += `}\\n`;\n\n return output;\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAASA,qBAAqB,QAAQ,2BAA2B;AAEjE,SAASC,iBAAiB,QAAQ,yBAAyB;AAC3D,SACEC,SAAS,EACTC,WAAW,EACXC,aAAa,EACbC,iBAAiB,EACjBC,sBAAsB,EACtBC,kBAAkB,QACb,oBAAoB;;AAE3B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASC,sBAAsBA,CACpCC,QAAyB,EACzBC,mBAA4B,EACpB;EACR,MAAM;IAAEC;EAAM,CAAC,GAAGF,QAAQ;EAC1B,MAAM;IAAEG;EAAW,CAAC,GAAGX,iBAAiB,CAACU,KAAK,EAAED,mBAAmB,CAAC;;EAEpE;E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U;EACpBA,MAAM,IAAI,4BAA4B;EACtC,KAAK,MAAM;IAAEV;EAAQ,CAAC,IAAIH,iBAAiB,EAAE;IAC3Ca,MAAM,IAAI,YAAYV,OAAO,KAAK;IAClCU,MAAM,IAAI,yBAAyBV,OAAO,WAAW;EACvD;EACAU,MAAM,IAAI,gBAAgB;EAC1BA,MAAM,IAAI,qFAAqF;EAC/FA,MAAM,IAAI,OAAO;EACjBA,MAAM,IAAI,KAAK;EAEf,OAAOA,MAAM;AACf","ignoreList":[]}
@@ -14,6 +14,7 @@
14
14
  * limitations under the License.
15
15
  */
16
16
 
17
+ import { defineSchema } from "@palantir/pack.schema";
17
18
  import fs from "fs-extra";
18
19
  import path from "path";
19
20
  import { pathToFileURL } from "url";
@@ -31,11 +32,7 @@ export function extractSchemaDefinition(schemaModule) {
31
32
  return defaultExport;
32
33
  }
33
34
  const models = extractValidSchema(schemaModule);
34
- return {
35
- type: "initial",
36
- version: 1,
37
- models
38
- };
35
+ return defineSchema(models);
39
36
  }
40
37
 
41
38
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"loadSchemaModule.js","names":["fs","path","pathToFileURL","extractValidSchema","extractSchemaDefinition","schemaModule","defaultExport","default","type","models","version","loadSchemaModule","filePath","inputPath","resolve","pathExists","Error","href"],"sources":["loadSchemaModule.ts"],"sourcesContent":["/*\n * Copyright 2026 Palantir Technologies, Inc. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { InitialSchema, SchemaDefinition } from \"@palantir/pack.schema\";\nimport fs from \"fs-extra\";\nimport path from \"path\";\nimport { pathToFileURL } from \"url\";\nimport { extractValidSchema } from \"./validateSchemaModule.js\";\n\n/**\n * Pull a `SchemaDefinition` out of an imported module. Accepts either a chain\n * built via `defineSchemaUpdate(...)` (`type: \"initial\" | \"versioned\"`) or a\n * plain `ModelDefs` object exported as `default` (which is wrapped in an\n * `InitialSchema` at version 1).\n */\nexport function extractSchemaDefinition(schemaModule: unknown): SchemaDefinition {\n const mod = schemaModule as Record<string, unknown>;\n const defaultExport = mod.default;\n\n if (\n typeof defaultExport === \"object\" && defaultExport != null\n && \"type\" in defaultExport\n && (defaultExport.type === \"initial\" || defaultExport.type === \"versioned\")\n ) {\n return defaultExport as SchemaDefinition;\n }\n\n const models = extractValidSchema(schemaModule);\n return { type: \"initial\", version: 1, models } satisfies InitialSchema;\n}\n\n/**\n * Resolve and import a schema module from a file path, returning a\n * `SchemaDefinition` ready for IR resolution.\n */\nexport async function loadSchemaModule(filePath: string): Promise<SchemaDefinition> {\n const inputPath = path.resolve(filePath);\n if (!(await fs.pathExists(inputPath))) {\n throw new Error(`Input file not found: ${inputPath}`);\n }\n const schemaModule: unknown = await import(pathToFileURL(inputPath).href);\n return extractSchemaDefinition(schemaModule);\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAGA,OAAOA,EAAE,MAAM,UAAU;AACzB,OAAOC,IAAI,MAAM,MAAM;AACvB,SAASC,aAAa,QAAQ,KAAK;AACnC,SAASC,kBAAkB,QAAQ,2BAA2B;;AAE9D;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASC,uBAAuBA,CAACC,YAAqB,EAAoB;EAE/E,MAAMC,aAAa,GADPD,YAAY,CACEE,OAAO;EAEjC,IACE,OAAOD,aAAa,KAAK,QAAQ,IAAIA,aAAa,IAAI,IAAI,IACvD,MAAM,IAAIA,aAAa,KACtBA,aAAa,CAACE,IAAI,KAAK,SAAS,IAAIF,aAAa,CAACE,IAAI,KAAK,WAAW,CAAC,EAC3E;IACA,OAAOF,aAAa;EACtB;EAEA,MAAMG,MAAM,GAAGN,kBAAkB,CAACE,YAAY,CAAC;EAC/C,OAAO;IAAEG,IAAI,EAAE,SAAS;IAAEE,OAAO,EAAE,CAAC;IAAED;EAAO,CAAC;AAChD;;AAEA;AACA;AACA;AACA;AACA,OAAO,eAAeE,gBAAgBA,CAACC,QAAgB,EAA6B;EAClF,MAAMC,SAAS,GAAGZ,IAAI,CAACa,OAAO,CAACF,QAAQ,CAAC;EACxC,IAAI,EAAE,MAAMZ,EAAE,CAACe,UAAU,CAACF,SAAS,CAAC,CAAC,EAAE;IACrC,MAAM,IAAIG,KAAK,CAAC,yBAAyBH,SAAS,EAAE,CAAC;EACvD;EACA,MAAMR,YAAqB,GAAG,MAAM,MAAM,CAACH,aAAa,CAACW,SAAS,CAAC,CAACI,IAAI,CAAC;EACzE,OAAOb,uBAAuB,CAACC,YAAY,CAAC;AAC9C","ignoreList":[]}
1
+ {"version":3,"file":"loadSchemaModule.js","names":["defineSchema","fs","path","pathToFileURL","extractValidSchema","extractSchemaDefinition","schemaModule","defaultExport","default","type","models","loadSchemaModule","filePath","inputPath","resolve","pathExists","Error","href"],"sources":["loadSchemaModule.ts"],"sourcesContent":["/*\n * Copyright 2026 Palantir Technologies, Inc. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { SchemaDefinition } from \"@palantir/pack.schema\";\nimport { defineSchema } from \"@palantir/pack.schema\";\nimport fs from \"fs-extra\";\nimport path from \"path\";\nimport { pathToFileURL } from \"url\";\nimport { extractValidSchema } from \"./validateSchemaModule.js\";\n\n/**\n * Pull a `SchemaDefinition` out of an imported module. Accepts either a chain\n * built via `defineSchemaUpdate(...)` (`type: \"initial\" | \"versioned\"`) or a\n * plain `ModelDefs` object exported as `default` (which is wrapped in an\n * `InitialSchema` at version 1).\n */\nexport function extractSchemaDefinition(schemaModule: unknown): SchemaDefinition {\n const mod = schemaModule as Record<string, unknown>;\n const defaultExport = mod.default;\n\n if (\n typeof defaultExport === \"object\" && defaultExport != null\n && \"type\" in defaultExport\n && (defaultExport.type === \"initial\" || defaultExport.type === \"versioned\")\n ) {\n return defaultExport as SchemaDefinition;\n }\n\n const models = extractValidSchema(schemaModule);\n return defineSchema(models);\n}\n\n/**\n * Resolve and import a schema module from a file path, returning a\n * `SchemaDefinition` ready for IR resolution.\n */\nexport async function loadSchemaModule(filePath: string): Promise<SchemaDefinition> {\n const inputPath = path.resolve(filePath);\n if (!(await fs.pathExists(inputPath))) {\n throw new Error(`Input file not found: ${inputPath}`);\n }\n const schemaModule: unknown = await import(pathToFileURL(inputPath).href);\n return extractSchemaDefinition(schemaModule);\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAGA,SAASA,YAAY,QAAQ,uBAAuB;AACpD,OAAOC,EAAE,MAAM,UAAU;AACzB,OAAOC,IAAI,MAAM,MAAM;AACvB,SAASC,aAAa,QAAQ,KAAK;AACnC,SAASC,kBAAkB,QAAQ,2BAA2B;;AAE9D;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASC,uBAAuBA,CAACC,YAAqB,EAAoB;EAE/E,MAAMC,aAAa,GADPD,YAAY,CACEE,OAAO;EAEjC,IACE,OAAOD,aAAa,KAAK,QAAQ,IAAIA,aAAa,IAAI,IAAI,IACvD,MAAM,IAAIA,aAAa,KACtBA,aAAa,CAACE,IAAI,KAAK,SAAS,IAAIF,aAAa,CAACE,IAAI,KAAK,WAAW,CAAC,EAC3E;IACA,OAAOF,aAAa;EACtB;EAEA,MAAMG,MAAM,GAAGN,kBAAkB,CAACE,YAAY,CAAC;EAC/C,OAAON,YAAY,CAACU,MAAM,CAAC;AAC7B;;AAEA;AACA;AACA;AACA;AACA,OAAO,eAAeC,gBAAgBA,CAACC,QAAgB,EAA6B;EAClF,MAAMC,SAAS,GAAGX,IAAI,CAACY,OAAO,CAACF,QAAQ,CAAC;EACxC,IAAI,EAAE,MAAMX,EAAE,CAACc,UAAU,CAACF,SAAS,CAAC,CAAC,EAAE;IACrC,MAAM,IAAIG,KAAK,CAAC,yBAAyBH,SAAS,EAAE,CAAC;EACvD;EACA,MAAMP,YAAqB,GAAG,MAAM,MAAM,CAACH,aAAa,CAACU,SAAS,CAAC,CAACI,IAAI,CAAC;EACzE,OAAOZ,uBAAuB,CAACC,YAAY,CAAC;AAC9C","ignoreList":[]}
@@ -14,6 +14,7 @@
14
14
  * limitations under the License.
15
15
  */
16
16
 
17
+ import { IModelDef as IModelDefCtor } from "../../lib/pack-docschema-api/pack-docschema-ir/index.js";
17
18
  import { convertSchemaToIr } from "../steps/convertStepsToIr.js";
18
19
 
19
20
  /** JSON-serializable form of a single field migration. */
@@ -21,29 +22,70 @@ import { convertSchemaToIr } from "../steps/convertStepsToIr.js";
21
22
  /** Serialized migrations keyed by `[recordModelName][fieldName]`. */
22
23
 
23
24
  function collectVersionedIrChain(input, identity) {
24
- const chain = [];
25
+ const schemas = collectSchemaDefinitions(input);
26
+ const provenances = deriveProvenance(schemas);
27
+ return schemas.map((schema, index) => ({
28
+ version: schema.version,
29
+ ir: convertSchemaToIr(schema.models, {
30
+ version: schema.version,
31
+ name: identity.name,
32
+ description: identity.description
33
+ }, provenances[index]),
34
+ ...(schema.type === "versioned" ? {
35
+ migrations: serializeMigrations(schema.migrations)
36
+ } : {})
37
+ }));
38
+ }
39
+ function collectSchemaDefinitions(input) {
40
+ const schemas = [];
25
41
  let current = input;
26
42
  while (current.type === "versioned") {
27
- chain.unshift({
28
- version: current.version,
29
- ir: convertSchemaToIr(current.models, {
30
- version: current.version,
31
- name: identity.name,
32
- description: identity.description
33
- }),
34
- migrations: serializeMigrations(current.migrations)
35
- });
43
+ schemas.unshift(current);
36
44
  current = current.previous;
37
45
  }
38
- chain.unshift({
39
- version: current.version,
40
- ir: convertSchemaToIr(current.models, {
41
- version: current.version,
42
- name: identity.name,
43
- description: identity.description
44
- })
46
+ schemas.unshift(current);
47
+ return schemas;
48
+ }
49
+
50
+ /**
51
+ * Build field/model provenance by walking the version chain from oldest to
52
+ * newest. The first version where a model key or record field appears is the
53
+ * version stamped into IR metadata.
54
+ */
55
+ function deriveProvenance(schemas) {
56
+ const firstModelVersions = new Map();
57
+ const firstFieldVersions = new Map();
58
+ return schemas.map(schema => {
59
+ const modelVersions = {};
60
+ const fieldVersions = {};
61
+ for (const [modelKey, modelDef] of Object.entries(schema.models)) {
62
+ if (!firstModelVersions.has(modelKey)) {
63
+ firstModelVersions.set(modelKey, schema.version);
64
+ }
65
+ modelVersions[modelKey] = firstModelVersions.get(modelKey);
66
+ if (modelDef.type !== "record") continue;
67
+ let fieldVersionsForModel = firstFieldVersions.get(modelKey);
68
+ if (fieldVersionsForModel == null) {
69
+ fieldVersionsForModel = new Map();
70
+ firstFieldVersions.set(modelKey, fieldVersionsForModel);
71
+ }
72
+ const fields = {};
73
+ for (const fieldKey of Object.keys(modelDef.fields)) {
74
+ if (!fieldVersionsForModel.has(fieldKey)) {
75
+ fieldVersionsForModel.set(fieldKey, schema.version);
76
+ }
77
+ fields[fieldKey] = fieldVersionsForModel.get(fieldKey);
78
+ }
79
+ if (Object.keys(fields).length > 0) {
80
+ fieldVersions[modelKey] = fields;
81
+ }
82
+ }
83
+ return {
84
+ fieldVersions,
85
+ modelVersions,
86
+ deprecations: "deprecations" in schema ? schema.deprecations : undefined
87
+ };
45
88
  });
46
- return chain;
47
89
  }
48
90
 
49
91
  /** Convert schema-builder migrations to their JSON-serializable form. */
@@ -101,6 +143,44 @@ export function resolveSchemaChain(schema, minSupportedVersion, identity = {}) {
101
143
  };
102
144
  }
103
145
 
146
+ /**
147
+ * Return a copy of the chain with deprecated fields removed from every version
148
+ * at or after the version in which they were deprecated.
149
+ *
150
+ * The SDK type generators (`writeAllSdkFiles` and friends) must treat a
151
+ * deprecated field exactly as a removed field: it disappears from that version's
152
+ * public read/write types and per-version internal types, and the prev/curr diff
153
+ * records it as a `removedField` (driving the upgrade lens). The field is still
154
+ * collected into the all-versions `__Internal` type from earlier versions, which
155
+ * are left untouched.
156
+ */
157
+ export function stripDeprecatedFieldsForSdk(chain) {
158
+ return chain.map(entry => {
159
+ const models = {};
160
+ for (const [modelKey, modelDef] of Object.entries(entry.ir.models)) {
161
+ if (modelDef.type === "record") {
162
+ const fields = modelDef.record.fields.filter(field => {
163
+ const dep = field.metadata.deprecatedFromVersion;
164
+ return dep == null || entry.version < dep;
165
+ });
166
+ models[modelKey] = IModelDefCtor.record({
167
+ ...modelDef.record,
168
+ fields
169
+ });
170
+ } else {
171
+ models[modelKey] = modelDef;
172
+ }
173
+ }
174
+ return {
175
+ ...entry,
176
+ ir: {
177
+ ...entry.ir,
178
+ models
179
+ }
180
+ };
181
+ });
182
+ }
183
+
104
184
  /**
105
185
  * True if any migration in the chain declares a non-empty `derivedFrom`. Drives
106
186
  * whether the generated SDK emits `DocumentModel` as a factory (requires the