@palantir/pack.document-schema.type-gen 0.10.0 → 0.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/esm/commands/asset/assetUpdateSchemaHandler.js +84 -0
- package/build/esm/commands/asset/assetUpdateSchemaHandler.js.map +1 -0
- package/build/esm/commands/asset/registerAssetCommands.js +2 -0
- package/build/esm/commands/asset/registerAssetCommands.js.map +1 -1
- package/build/esm/utils/ir/__tests__/__snapshots__/generateModelsFromIr/custom-discriminant.js +1 -1
- package/build/esm/utils/ir/__tests__/__snapshots__/generateModelsFromIr/custom-discriminant.js.map +1 -1
- package/build/esm/utils/ir/__tests__/__snapshots__/generateModelsFromIr/external-refs.js +1 -1
- package/build/esm/utils/ir/__tests__/__snapshots__/generateModelsFromIr/external-refs.js.map +1 -1
- package/build/esm/utils/ir/__tests__/__snapshots__/generateModelsFromIr/simple-record.js +1 -1
- package/build/esm/utils/ir/__tests__/__snapshots__/generateModelsFromIr/simple-record.js.map +1 -1
- package/build/esm/utils/ir/__tests__/__snapshots__/generateModelsFromIr/union-types.js +1 -1
- package/build/esm/utils/ir/__tests__/__snapshots__/generateModelsFromIr/union-types.js.map +1 -1
- package/build/esm/utils/ir/__tests__/__snapshots__/generateZodSchemasFromIr/array-and-map-types.js +1 -1
- package/build/esm/utils/ir/__tests__/__snapshots__/generateZodSchemasFromIr/array-and-map-types.js.map +1 -1
- package/build/esm/utils/ir/__tests__/__snapshots__/generateZodSchemasFromIr/boolean-fields.js +1 -1
- package/build/esm/utils/ir/__tests__/__snapshots__/generateZodSchemasFromIr/boolean-fields.js.map +1 -1
- package/build/esm/utils/ir/__tests__/__snapshots__/generateZodSchemasFromIr/custom-discriminant.js +1 -1
- package/build/esm/utils/ir/__tests__/__snapshots__/generateZodSchemasFromIr/custom-discriminant.js.map +1 -1
- package/build/esm/utils/ir/__tests__/__snapshots__/generateZodSchemasFromIr/datetime-fields.js +1 -1
- package/build/esm/utils/ir/__tests__/__snapshots__/generateZodSchemasFromIr/datetime-fields.js.map +1 -1
- package/build/esm/utils/ir/__tests__/__snapshots__/generateZodSchemasFromIr/simple-records.js +1 -1
- package/build/esm/utils/ir/__tests__/__snapshots__/generateZodSchemasFromIr/simple-records.js.map +1 -1
- package/build/esm/utils/ir/__tests__/__snapshots__/generateZodSchemasFromIr/union-before-records.js +1 -1
- package/build/esm/utils/ir/__tests__/__snapshots__/generateZodSchemasFromIr/union-before-records.js.map +1 -1
- package/build/esm/utils/ir/__tests__/__snapshots__/generateZodSchemasFromIr/union-types.js +1 -1
- package/build/esm/utils/ir/__tests__/__snapshots__/generateZodSchemasFromIr/union-types.js.map +1 -1
- package/build/esm/utils/schema/__tests__/__snapshots__/generateVersionsFromSchema/single-version.js.map +1 -1
- package/build/esm/utils/schema/__tests__/__snapshots__/generateVersionsFromSchema/three-version-chain.js.map +1 -1
- package/build/esm/utils/schema/__tests__/__snapshots__/generateVersionsFromSchema/two-version.js.map +1 -1
- package/build/esm/utils/schema/__tests__/fixtures.js +2 -8
- package/build/esm/utils/schema/__tests__/fixtures.js.map +1 -1
- package/build/esm/utils/schema/__tests__/generateModelMetadataFromSchema.test.js +5 -1
- package/build/esm/utils/schema/__tests__/generateModelMetadataFromSchema.test.js.map +1 -1
- package/build/esm/utils/schema/__tests__/snapshotUtils.js +3 -0
- package/build/esm/utils/schema/__tests__/snapshotUtils.js.map +1 -1
- package/build/esm/utils/schema/generateIndexFromSchema.js +7 -2
- package/build/esm/utils/schema/generateIndexFromSchema.js.map +1 -1
- package/build/esm/utils/schema/generateInternalFromSchema.js +138 -11
- package/build/esm/utils/schema/generateInternalFromSchema.js.map +1 -1
- package/build/esm/utils/schema/generateModelMetadataFromSchema.js +45 -13
- package/build/esm/utils/schema/generateModelMetadataFromSchema.js.map +1 -1
- package/build/esm/utils/schema/resolveSchemaChain.js +20 -11
- package/build/esm/utils/schema/resolveSchemaChain.js.map +1 -1
- package/build/esm/utils/schema/runtimeSchema.js +3 -0
- package/build/esm/utils/schema/runtimeSchema.js.map +1 -1
- package/build/esm/utils/schema/writeAllSdkFiles.js +2 -0
- package/build/esm/utils/schema/writeAllSdkFiles.js.map +1 -1
- package/build/esm/utils/steps/__tests__/__snapshots__/types/arrayFields.js.map +1 -1
- package/build/esm/utils/steps/__tests__/__snapshots__/types/customDiscriminant.js +1 -1
- package/build/esm/utils/steps/__tests__/__snapshots__/types/customDiscriminant.js.map +1 -1
- package/build/esm/utils/steps/__tests__/__snapshots__/types/generateTypeScriptInterfaces.js +1 -1
- package/build/esm/utils/steps/__tests__/__snapshots__/types/generateTypeScriptInterfaces.js.map +1 -1
- package/build/esm/utils/steps/__tests__/__snapshots__/types/refTypes.js.map +1 -1
- package/build/esm/utils/steps/__tests__/__snapshots__/types/simpleRecord.js.map +1 -1
- package/build/esm/utils/steps/__tests__/__snapshots__/types/simpleSteps.js +1 -1
- package/build/esm/utils/steps/__tests__/__snapshots__/types/simpleSteps.js.map +1 -1
- package/build/types/commands/asset/assetUpdateSchemaHandler.d.ts +12 -0
- package/build/types/commands/asset/assetUpdateSchemaHandler.d.ts.map +1 -0
- package/build/types/commands/asset/registerAssetCommands.d.ts.map +1 -1
- package/build/types/utils/schema/__tests__/fixtures.d.ts.map +1 -1
- package/build/types/utils/schema/__tests__/snapshotUtils.d.ts +2 -0
- package/build/types/utils/schema/__tests__/snapshotUtils.d.ts.map +1 -1
- package/build/types/utils/schema/generateIndexFromSchema.d.ts +3 -1
- package/build/types/utils/schema/generateIndexFromSchema.d.ts.map +1 -1
- package/build/types/utils/schema/generateInternalFromSchema.d.ts +5 -3
- package/build/types/utils/schema/generateInternalFromSchema.d.ts.map +1 -1
- package/build/types/utils/schema/generateModelMetadataFromSchema.d.ts.map +1 -1
- package/build/types/utils/schema/resolveSchemaChain.d.ts +7 -7
- package/build/types/utils/schema/resolveSchemaChain.d.ts.map +1 -1
- package/build/types/utils/schema/runtimeSchema.d.ts +2 -0
- package/build/types/utils/schema/runtimeSchema.d.ts.map +1 -1
- package/build/types/utils/schema/writeAllSdkFiles.d.ts.map +1 -1
- package/package.json +4 -4
|
@@ -17,16 +17,18 @@
|
|
|
17
17
|
import { formatVariantName } from "../formatVariantName.js";
|
|
18
18
|
import { GENERATED_FILE_HEADER } from "../generatedFileHeader.js";
|
|
19
19
|
import { resolveMinVersion } from "./resolveSchemaChain.js";
|
|
20
|
-
import { MODELS_PATH, TYPES_REEXPORT_PATH, typesFilePath, VERSIONED_DOC_REF_PATH, versionedTypeName, VERSIONS_PATH } from "./runtimeSchema.js";
|
|
20
|
+
import { INTERNAL_UPGRADE_FNS_PATH, MODELS_PATH, TYPES_REEXPORT_PATH, typesFilePath, VERSIONED_DOC_REF_PATH, versionedTypeName, VERSIONS_PATH } from "./runtimeSchema.js";
|
|
21
21
|
|
|
22
22
|
/**
|
|
23
23
|
* Generate the index.ts barrel export from a versioned schema.
|
|
24
24
|
*
|
|
25
25
|
* Exports:
|
|
26
|
-
* - `models.js` (star export — model constants and DocumentModel
|
|
26
|
+
* - `models.js` (star export — model constants and `DocumentModel`; emitted
|
|
27
|
+
* as a factory function when the schema has derived fields, otherwise a const)
|
|
27
28
|
* - `types.js` (star export — latest-version type aliases)
|
|
28
29
|
* - `versions.js` (star export — SupportedVersions, LatestVersion, MinSupportedVersion)
|
|
29
30
|
* - `versionedDocRef.js` (star export — VersionedDocRef types and factory)
|
|
31
|
+
* - `DocumentUpgradeFns` type (the typed shape the factory accepts)
|
|
30
32
|
* - Per supported version: explicit named type exports from `types_vN.js`
|
|
31
33
|
* (not star exports, to avoid polluting autocomplete for read-only consumers)
|
|
32
34
|
*/
|
|
@@ -44,6 +46,9 @@ export function generateIndexFromChain(resolved, minSupportedVersion) {
|
|
|
44
46
|
output += `export * from "${TYPES_REEXPORT_PATH}";\n`;
|
|
45
47
|
output += `export * from "${VERSIONS_PATH}";\n`;
|
|
46
48
|
output += `export * from "${VERSIONED_DOC_REF_PATH}";\n`;
|
|
49
|
+
// The typed upgrade-function table shape. Apps reference this type when
|
|
50
|
+
// constructing the value passed to `DocumentModel(...)`.
|
|
51
|
+
output += `export { type DocumentUpgradeFns } from "${INTERNAL_UPGRADE_FNS_PATH}";\n`;
|
|
47
52
|
|
|
48
53
|
// Per-version explicit named type exports
|
|
49
54
|
for (const {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generateIndexFromSchema.js","names":["formatVariantName","GENERATED_FILE_HEADER","resolveMinVersion","MODELS_PATH","TYPES_REEXPORT_PATH","typesFilePath","VERSIONED_DOC_REF_PATH","versionedTypeName","VERSIONS_PATH","generateIndexFromChain","resolved","minSupportedVersion","chain","minVersion","output","version","ir","typeNames","modelKey","modelDef","Object","entries","models","type","push","variantName","keys","union","variants","formattedVariant","length","sort","join"],"sources":["generateIndexFromSchema.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 { formatVariantName } from \"../formatVariantName.js\";\nimport { GENERATED_FILE_HEADER } from \"../generatedFileHeader.js\";\nimport type { ResolvedIrChain } from \"./resolveSchemaChain.js\";\nimport { resolveMinVersion } from \"./resolveSchemaChain.js\";\nimport {\n MODELS_PATH,\n TYPES_REEXPORT_PATH,\n typesFilePath,\n VERSIONED_DOC_REF_PATH,\n versionedTypeName,\n VERSIONS_PATH,\n} from \"./runtimeSchema.js\";\n\n/**\n * Generate the index.ts barrel export from a versioned schema.\n *\n * Exports:\n * - `models.js` (star export — model constants and DocumentModel)\n * - `types.js` (star export — latest-version type aliases)\n * - `versions.js` (star export — SupportedVersions, LatestVersion, MinSupportedVersion)\n * - `versionedDocRef.js` (star export — VersionedDocRef types and factory)\n * - Per supported version: explicit named type exports from `types_vN.js`\n * (not star exports, to avoid polluting autocomplete for read-only consumers)\n */\nexport function generateIndexFromChain(\n resolved: ResolvedIrChain,\n minSupportedVersion?: number,\n): string {\n const { chain } = resolved;\n const { minVersion } = resolveMinVersion(chain, minSupportedVersion);\n\n let output = GENERATED_FILE_HEADER;\n\n // Star exports for core modules\n output += `export * from \"${MODELS_PATH}\";\\n`;\n output += `export * from \"${TYPES_REEXPORT_PATH}\";\\n`;\n output += `export * from \"${VERSIONS_PATH}\";\\n`;\n output += `export * from \"${VERSIONED_DOC_REF_PATH}\";\\n`;\n\n // Per-version explicit named type exports\n for (const { version, ir } of chain) {\n if (version < minVersion) continue;\n\n const typeNames: string[] = [];\n\n for (const [modelKey, modelDef] of Object.entries(ir.models)) {\n if (modelDef.type === \"record\") {\n typeNames.push(versionedTypeName(modelKey, version));\n } else if (modelDef.type === \"union\") {\n typeNames.push(versionedTypeName(modelKey, version));\n\n // Union variant types\n for (const variantName of Object.keys(modelDef.union.variants)) {\n const formattedVariant = formatVariantName(variantName);\n typeNames.push(`${versionedTypeName(modelKey, version)}${formattedVariant}`);\n }\n }\n }\n\n if (typeNames.length > 0) {\n output += `export type { ${typeNames.sort().join(\", \")} } from \"${\n typesFilePath(version)\n }\";\\n`;\n }\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,iBAAiB,QAAQ,yBAAyB;AAC3D,SAASC,qBAAqB,QAAQ,2BAA2B;AAEjE,SAASC,iBAAiB,QAAQ,yBAAyB;AAC3D,SACEC,WAAW,EACXC,mBAAmB,EACnBC,aAAa,EACbC,sBAAsB,EACtBC,iBAAiB,EACjBC,aAAa,QACR,oBAAoB;;AAE3B;AACA;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,
|
|
1
|
+
{"version":3,"file":"generateIndexFromSchema.js","names":["formatVariantName","GENERATED_FILE_HEADER","resolveMinVersion","INTERNAL_UPGRADE_FNS_PATH","MODELS_PATH","TYPES_REEXPORT_PATH","typesFilePath","VERSIONED_DOC_REF_PATH","versionedTypeName","VERSIONS_PATH","generateIndexFromChain","resolved","minSupportedVersion","chain","minVersion","output","version","ir","typeNames","modelKey","modelDef","Object","entries","models","type","push","variantName","keys","union","variants","formattedVariant","length","sort","join"],"sources":["generateIndexFromSchema.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 { formatVariantName } from \"../formatVariantName.js\";\nimport { GENERATED_FILE_HEADER } from \"../generatedFileHeader.js\";\nimport type { ResolvedIrChain } from \"./resolveSchemaChain.js\";\nimport { resolveMinVersion } from \"./resolveSchemaChain.js\";\nimport {\n INTERNAL_UPGRADE_FNS_PATH,\n MODELS_PATH,\n TYPES_REEXPORT_PATH,\n typesFilePath,\n VERSIONED_DOC_REF_PATH,\n versionedTypeName,\n VERSIONS_PATH,\n} from \"./runtimeSchema.js\";\n\n/**\n * Generate the index.ts barrel export from a versioned schema.\n *\n * Exports:\n * - `models.js` (star export — model constants and `DocumentModel`; emitted\n * as a factory function when the schema has derived fields, otherwise a const)\n * - `types.js` (star export — latest-version type aliases)\n * - `versions.js` (star export — SupportedVersions, LatestVersion, MinSupportedVersion)\n * - `versionedDocRef.js` (star export — VersionedDocRef types and factory)\n * - `DocumentUpgradeFns` type (the typed shape the factory accepts)\n * - Per supported version: explicit named type exports from `types_vN.js`\n * (not star exports, to avoid polluting autocomplete for read-only consumers)\n */\nexport function generateIndexFromChain(\n resolved: ResolvedIrChain,\n minSupportedVersion?: number,\n): string {\n const { chain } = resolved;\n const { minVersion } = resolveMinVersion(chain, minSupportedVersion);\n\n let output = GENERATED_FILE_HEADER;\n\n // Star exports for core modules\n output += `export * from \"${MODELS_PATH}\";\\n`;\n output += `export * from \"${TYPES_REEXPORT_PATH}\";\\n`;\n output += `export * from \"${VERSIONS_PATH}\";\\n`;\n output += `export * from \"${VERSIONED_DOC_REF_PATH}\";\\n`;\n // The typed upgrade-function table shape. Apps reference this type when\n // constructing the value passed to `DocumentModel(...)`.\n output += `export { type DocumentUpgradeFns } from \"${INTERNAL_UPGRADE_FNS_PATH}\";\\n`;\n\n // Per-version explicit named type exports\n for (const { version, ir } of chain) {\n if (version < minVersion) continue;\n\n const typeNames: string[] = [];\n\n for (const [modelKey, modelDef] of Object.entries(ir.models)) {\n if (modelDef.type === \"record\") {\n typeNames.push(versionedTypeName(modelKey, version));\n } else if (modelDef.type === \"union\") {\n typeNames.push(versionedTypeName(modelKey, version));\n\n // Union variant types\n for (const variantName of Object.keys(modelDef.union.variants)) {\n const formattedVariant = formatVariantName(variantName);\n typeNames.push(`${versionedTypeName(modelKey, version)}${formattedVariant}`);\n }\n }\n }\n\n if (typeNames.length > 0) {\n output += `export type { ${typeNames.sort().join(\", \")} } from \"${\n typesFilePath(version)\n }\";\\n`;\n }\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,iBAAiB,QAAQ,yBAAyB;AAC3D,SAASC,qBAAqB,QAAQ,2BAA2B;AAEjE,SAASC,iBAAiB,QAAQ,yBAAyB;AAC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I,CAACP,QAAQ,CAACQ,KAAK,CAACC,QAAQ,CAAC,EAAE;UAC9D,MAAMC,gBAAgB,GAAG9B,iBAAiB,CAAC0B,WAAW,CAAC;UACvDR,SAAS,CAACO,IAAI,CAAC,GAAGjB,iBAAiB,CAACW,QAAQ,EAAEH,OAAO,CAAC,GAAGc,gBAAgB,EAAE,CAAC;QAC9E;MACF;IACF;IAEA,IAAIZ,SAAS,CAACa,MAAM,GAAG,CAAC,EAAE;MACxBhB,MAAM,IAAI,iBAAiBG,SAAS,CAACc,IAAI,CAAC,CAAC,CAACC,IAAI,CAAC,IAAI,CAAC,YACpD3B,aAAa,CAACU,OAAO,CAAC,MAClB;IACR;EACF;EAEA,OAAOD,MAAM;AACf","ignoreList":[]}
|
|
@@ -16,6 +16,7 @@
|
|
|
16
16
|
|
|
17
17
|
import { GENERATED_FILE_HEADER } from "../generatedFileHeader.js";
|
|
18
18
|
import { convertFieldTypeToDescriptor, convertFieldTypeToInternalTypeScript, convertFieldTypeToInternalZod } from "../ir/irFieldHelpers.js";
|
|
19
|
+
import { chainHasDerivedFields } from "./resolveSchemaChain.js";
|
|
19
20
|
|
|
20
21
|
/** Collected info about all fields for a model across all versions. */
|
|
21
22
|
|
|
@@ -94,13 +95,11 @@ function collectRecordModels(chain) {
|
|
|
94
95
|
const annotation = recordUpgrades?.[fieldKey];
|
|
95
96
|
if (annotation != null) {
|
|
96
97
|
addedFields.set(fieldKey, {
|
|
97
|
-
derivedFrom: [...annotation.derivedFrom]
|
|
98
|
-
forwardSource: annotation.forwardSource
|
|
98
|
+
derivedFrom: [...annotation.derivedFrom]
|
|
99
99
|
});
|
|
100
100
|
} else {
|
|
101
101
|
addedFields.set(fieldKey, {
|
|
102
|
-
derivedFrom: []
|
|
103
|
-
forwardSource: "() => undefined"
|
|
102
|
+
derivedFrom: []
|
|
104
103
|
});
|
|
105
104
|
}
|
|
106
105
|
}
|
|
@@ -115,7 +114,6 @@ function collectRecordModels(chain) {
|
|
|
115
114
|
}
|
|
116
115
|
if (addedFields.size > 0 || removedFields.length > 0) {
|
|
117
116
|
model.steps.push({
|
|
118
|
-
name: `v${currEntry.version}`,
|
|
119
117
|
addedInVersion: currEntry.version,
|
|
120
118
|
fields: addedFields,
|
|
121
119
|
removedFields
|
|
@@ -155,6 +153,56 @@ function generateInternalTypes(allRecordModels) {
|
|
|
155
153
|
return output;
|
|
156
154
|
}
|
|
157
155
|
|
|
156
|
+
/**
|
|
157
|
+
* Generate per-version internal interfaces (e.g. `ShapeBox__v1`, `ShapeBox__v2`).
|
|
158
|
+
*
|
|
159
|
+
* Each interface contains only the fields present in that version, with their
|
|
160
|
+
* actual optionality taken straight from that version's IR. The downstream
|
|
161
|
+
* `DocumentUpgradeFns` generator uses these so each upgrade function's
|
|
162
|
+
* parameter can `Pick` the prior version's fields and its return type can
|
|
163
|
+
* index the current version's field type precisely.
|
|
164
|
+
*/
|
|
165
|
+
function generatePerVersionInternalTypes(chain) {
|
|
166
|
+
// Group by model so each model's versions appear together in ascending order.
|
|
167
|
+
const perModelVersions = new Map();
|
|
168
|
+
for (const {
|
|
169
|
+
version,
|
|
170
|
+
ir
|
|
171
|
+
} of chain) {
|
|
172
|
+
for (const [modelKey, modelDef] of Object.entries(ir.models)) {
|
|
173
|
+
if (modelDef.type !== "record") continue;
|
|
174
|
+
let list = perModelVersions.get(modelKey);
|
|
175
|
+
if (list == null) {
|
|
176
|
+
list = [];
|
|
177
|
+
perModelVersions.set(modelKey, list);
|
|
178
|
+
}
|
|
179
|
+
list.push({
|
|
180
|
+
version,
|
|
181
|
+
fields: modelDef.record.fields
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
let output = "";
|
|
186
|
+
const sortedModels = Array.from(perModelVersions.entries()).sort(([a], [b]) => a.localeCompare(b));
|
|
187
|
+
for (const [modelKey, versions] of sortedModels) {
|
|
188
|
+
for (const {
|
|
189
|
+
version,
|
|
190
|
+
fields
|
|
191
|
+
} of versions) {
|
|
192
|
+
output += `/** Internal representation of ${modelKey} at schema version ${version}. */\n`;
|
|
193
|
+
output += `export interface ${modelKey}__v${version} {\n`;
|
|
194
|
+
const sortedFields = [...fields].sort((a, b) => a.key.localeCompare(b.key));
|
|
195
|
+
for (const field of sortedFields) {
|
|
196
|
+
const tsType = convertFieldTypeToInternalTypeScript(field.fieldType, field.isOptional === true);
|
|
197
|
+
const optional = field.isOptional === true ? "?" : "";
|
|
198
|
+
output += ` readonly ${field.key}${optional}: ${tsType};\n`;
|
|
199
|
+
}
|
|
200
|
+
output += "}\n\n";
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
return output;
|
|
204
|
+
}
|
|
205
|
+
|
|
158
206
|
/**
|
|
159
207
|
* Generate _internal/upgrades.ts content.
|
|
160
208
|
*/
|
|
@@ -184,13 +232,11 @@ function generateUpgrades(allRecordModels, latestIr) {
|
|
|
184
232
|
output += ` steps: [\n`;
|
|
185
233
|
for (const step of model.steps) {
|
|
186
234
|
output += ` {\n`;
|
|
187
|
-
output += ` name: "${step.name}",\n`;
|
|
188
235
|
output += ` addedInVersion: ${step.addedInVersion},\n`;
|
|
189
236
|
output += ` fields: {\n`;
|
|
190
237
|
for (const [fieldName, fieldMeta] of step.fields) {
|
|
191
238
|
output += ` ${fieldName}: {\n`;
|
|
192
239
|
output += ` derivedFrom: [${fieldMeta.derivedFrom.map(d => `"${d}"`).join(", ")}],\n`;
|
|
193
|
-
output += ` forward: ${fieldMeta.forwardSource},\n`;
|
|
194
240
|
if (fieldMeta.default !== undefined) {
|
|
195
241
|
output += ` default: ${JSON.stringify(fieldMeta.default)},\n`;
|
|
196
242
|
}
|
|
@@ -243,8 +289,87 @@ function generateInternalSchemaContent(allRecordModels) {
|
|
|
243
289
|
}
|
|
244
290
|
|
|
245
291
|
/**
|
|
246
|
-
* Generate _internal/
|
|
247
|
-
*
|
|
292
|
+
* Generate _internal/upgradeFns.ts content: a typed `DocumentUpgradeFns`
|
|
293
|
+
* interface enumerating every upgrade function the app must supply at boot.
|
|
294
|
+
*
|
|
295
|
+
* For every `(modelName, v${version}, fieldName)` triple where `derivedFrom` is
|
|
296
|
+
* non-empty, emit a property typed
|
|
297
|
+
* `(oldFields: Pick<<Model>__v<prior>, derivedFrom[number]>) => <Model>__v<current>[fieldName]`.
|
|
298
|
+
* Additive fields (empty `derivedFrom`) are intentionally absent — they are
|
|
299
|
+
* handled by the structural `default` in `_internal/upgrades.ts`.
|
|
300
|
+
*
|
|
301
|
+
* The interface is consumed by the generated `DocumentModel` factory in
|
|
302
|
+
* `models.ts`, which requires it as a parameter when the schema has any
|
|
303
|
+
* derived fields. Schemas without derived fields emit an empty interface
|
|
304
|
+
* (still exported for type-uniformity in downstream code).
|
|
305
|
+
*/
|
|
306
|
+
function generateUpgradeFns(chain, allRecordModels) {
|
|
307
|
+
const perModel = new Map();
|
|
308
|
+
const neededTypes = new Set();
|
|
309
|
+
for (const [modelKey, model] of sortedEntries(allRecordModels)) {
|
|
310
|
+
for (const step of model.steps) {
|
|
311
|
+
const currentIdx = chain.findIndex(c => c.version === step.addedInVersion);
|
|
312
|
+
if (currentIdx <= 0) continue;
|
|
313
|
+
const priorVersion = chain[currentIdx - 1].version;
|
|
314
|
+
const fields = [];
|
|
315
|
+
for (const [fieldName, fieldMeta] of step.fields) {
|
|
316
|
+
if (fieldMeta.derivedFrom.length === 0) continue;
|
|
317
|
+
fields.push({
|
|
318
|
+
fieldName,
|
|
319
|
+
derivedFrom: [...fieldMeta.derivedFrom]
|
|
320
|
+
});
|
|
321
|
+
}
|
|
322
|
+
if (fields.length === 0) continue;
|
|
323
|
+
let list = perModel.get(modelKey);
|
|
324
|
+
if (list == null) {
|
|
325
|
+
list = [];
|
|
326
|
+
perModel.set(modelKey, list);
|
|
327
|
+
}
|
|
328
|
+
list.push({
|
|
329
|
+
currentVersion: step.addedInVersion,
|
|
330
|
+
priorVersion,
|
|
331
|
+
fields
|
|
332
|
+
});
|
|
333
|
+
neededTypes.add(`${modelKey}__v${priorVersion}`);
|
|
334
|
+
neededTypes.add(`${modelKey}__v${step.addedInVersion}`);
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
let output = GENERATED_FILE_HEADER;
|
|
338
|
+
output += `\n`;
|
|
339
|
+
if (neededTypes.size > 0) {
|
|
340
|
+
const sorted = Array.from(neededTypes).sort();
|
|
341
|
+
output += `import type { ${sorted.join(", ")} } from "./types.js";\n\n`;
|
|
342
|
+
}
|
|
343
|
+
output += `/**\n`;
|
|
344
|
+
output += ` * Typed upgrade functions the application must supply at boot. Coverage is\n`;
|
|
345
|
+
output += ` * exhaustive: missing or extra entries fail type-check at the \`DocumentModel(...)\`\n`;
|
|
346
|
+
output += ` * call site. Additive fields (empty \`derivedFrom\`) are intentionally absent.\n`;
|
|
347
|
+
output += ` */\n`;
|
|
348
|
+
if (perModel.size === 0) {
|
|
349
|
+
output += `// eslint-disable-next-line @typescript-eslint/no-empty-object-type\n`;
|
|
350
|
+
output += `export interface DocumentUpgradeFns {}\n`;
|
|
351
|
+
} else {
|
|
352
|
+
output += `export interface DocumentUpgradeFns {\n`;
|
|
353
|
+
for (const [modelKey, steps] of Array.from(perModel.entries()).sort(([a], [b]) => a.localeCompare(b))) {
|
|
354
|
+
output += ` ${modelKey}: {\n`;
|
|
355
|
+
for (const step of steps) {
|
|
356
|
+
output += ` v${step.currentVersion}: {\n`;
|
|
357
|
+
for (const f of step.fields) {
|
|
358
|
+
const pickKeys = f.derivedFrom.map(d => `"${d}"`).join(" | ");
|
|
359
|
+
output += ` ${f.fieldName}: (oldFields: Pick<${modelKey}__v${step.priorVersion}, ${pickKeys}>) => ${modelKey}__v${step.currentVersion}["${f.fieldName}"];\n`;
|
|
360
|
+
}
|
|
361
|
+
output += ` };\n`;
|
|
362
|
+
}
|
|
363
|
+
output += ` };\n`;
|
|
364
|
+
}
|
|
365
|
+
output += `}\n`;
|
|
366
|
+
}
|
|
367
|
+
return output;
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
/**
|
|
371
|
+
* Generate _internal/types.ts, _internal/upgrades.ts, _internal/schema.ts and
|
|
372
|
+
* _internal/upgradeFns.ts from an already-resolved versioned IR chain.
|
|
248
373
|
*/
|
|
249
374
|
export function generateInternalFromChain(resolved) {
|
|
250
375
|
const {
|
|
@@ -252,13 +377,15 @@ export function generateInternalFromChain(resolved) {
|
|
|
252
377
|
} = resolved;
|
|
253
378
|
const latestIr = chain[chain.length - 1].ir;
|
|
254
379
|
const allRecordModels = collectRecordModels(chain);
|
|
255
|
-
const internalTypes = generateInternalTypes(allRecordModels);
|
|
380
|
+
const internalTypes = generateInternalTypes(allRecordModels) + (chainHasDerivedFields(chain) ? generatePerVersionInternalTypes(chain) : "");
|
|
256
381
|
const upgrades = generateUpgrades(allRecordModels, latestIr);
|
|
257
382
|
const internalSchema = generateInternalSchemaContent(allRecordModels);
|
|
383
|
+
const internalUpgradeFns = generateUpgradeFns(chain, allRecordModels);
|
|
258
384
|
return {
|
|
259
385
|
internalTypes,
|
|
260
386
|
upgrades,
|
|
261
|
-
internalSchema
|
|
387
|
+
internalSchema,
|
|
388
|
+
internalUpgradeFns
|
|
262
389
|
};
|
|
263
390
|
}
|
|
264
391
|
//# sourceMappingURL=generateInternalFromSchema.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generateInternalFromSchema.js","names":["GENERATED_FILE_HEADER","convertFieldTypeToDescriptor","convertFieldTypeToInternalTypeScript","convertFieldTypeToInternalZod","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","forwardSource","removedFields","push","size","name","addedInVersion","totalVersions","values","fieldInfo","generateInternalTypes","output","fieldName","tsType","optional","generateUpgrades","latestIr","hasRecords","hasUnions","some","m","imports","join","typeDescriptor","step","fieldMeta","d","default","undefined","JSON","stringify","union","discriminant","variantKey","variantModelKey","variants","generateInternalSchemaContent","zodType","generateInternalFromChain","resolved","internalTypes","upgrades","internalSchema"],"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 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 type { ResolvedIrChain, VersionedIrEntry } 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}\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 name: string;\n addedInVersion: number;\n fields: Map<string, { derivedFrom: string[]; forwardSource: 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[]; forwardSource: 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 forwardSource: annotation.forwardSource,\n });\n } else {\n addedFields.set(fieldKey, {\n derivedFrom: [],\n forwardSource: \"() => undefined\",\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 name: `v${currEntry.version}`,\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 _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 += ` name: \"${step.name}\",\\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 output += ` forward: ${fieldMeta.forwardSource},\\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/types.ts, _internal/upgrades.ts, and _internal/schema.ts\n * 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 const upgrades = generateUpgrades(allRecordModels, latestIr);\n const internalSchema = generateInternalSchemaContent(allRecordModels);\n\n return { internalTypes, upgrades, internalSchema };\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAMA,SAASA,qBAAqB,QAAQ,2BAA2B;AACjE,SACEC,4BAA4B,EAC5BC,oCAAoC,EACpCC,6BAA6B,QACxB,yBAAyB;;AAYhC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e,GAAGF,mBAAmB,CAACC,KAAK,CAAC;EAElD,MAAMkF,aAAa,GAAG9B,qBAAqB,CAACnD,eAAe,CAAC;EAC5D,MAAMkF,QAAQ,GAAG1B,gBAAgB,CAACxD,eAAe,EAAEyD,QAAQ,CAAC;EAC5D,MAAM0B,cAAc,GAAGN,6BAA6B,CAAC7E,eAAe,CAAC;EAErE,OAAO;IAAEiF,aAAa;IAAEC,QAAQ;IAAEC;EAAe,CAAC;AACpD","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 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;;AAO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hB,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":[]}
|
|
@@ -17,8 +17,8 @@
|
|
|
17
17
|
import { formatVariantName } from "../formatVariantName.js";
|
|
18
18
|
import { GENERATED_FILE_HEADER } from "../generatedFileHeader.js";
|
|
19
19
|
import { findExternalRefType } from "../ir/irFieldHelpers.js";
|
|
20
|
-
import { resolveMinVersion } from "./resolveSchemaChain.js";
|
|
21
|
-
import { INTERNAL_UPGRADES_PATH, modelName, SCHEMA_REEXPORT_PATH, schemaName, TYPES_REEXPORT_PATH } from "./runtimeSchema.js";
|
|
20
|
+
import { chainHasDerivedFields, resolveMinVersion } from "./resolveSchemaChain.js";
|
|
21
|
+
import { INTERNAL_UPGRADE_FNS_PATH, INTERNAL_UPGRADES_PATH, modelName, SCHEMA_REEXPORT_PATH, schemaName, TYPES_REEXPORT_PATH } from "./runtimeSchema.js";
|
|
22
22
|
function extractExternalRefFieldTypes(record) {
|
|
23
23
|
const refs = [];
|
|
24
24
|
for (const field of record.fields) {
|
|
@@ -42,6 +42,7 @@ export function generateModelMetadataFromChain(resolved, minSupportedVersion) {
|
|
|
42
42
|
minVersion
|
|
43
43
|
} = resolveMinVersion(chain, minSupportedVersion);
|
|
44
44
|
const latestIr = chain[chain.length - 1].ir;
|
|
45
|
+
const hasDerivedFields = chainHasDerivedFields(chain);
|
|
45
46
|
|
|
46
47
|
// --- Generate models.ts ---
|
|
47
48
|
let output = GENERATED_FILE_HEADER;
|
|
@@ -66,6 +67,7 @@ export function generateModelMetadataFromChain(resolved, minSupportedVersion) {
|
|
|
66
67
|
const modelTypesImports = ["DocumentSchema"];
|
|
67
68
|
if (recordNames.length > 0) modelTypesImports.push("RecordModel");
|
|
68
69
|
if (unionNames.length > 0) modelTypesImports.push("UnionModel");
|
|
70
|
+
if (hasDerivedFields) modelTypesImports.push("UpgradeFns");
|
|
69
71
|
output += `import type { ${modelTypesImports.sort().join(", ")} } from "@palantir/pack.document-schema.model-types";\n`;
|
|
70
72
|
output += `import { Metadata } from "@palantir/pack.document-schema.model-types";\n`;
|
|
71
73
|
if (allModelNames.length > 0) {
|
|
@@ -83,6 +85,11 @@ export function generateModelMetadataFromChain(resolved, minSupportedVersion) {
|
|
|
83
85
|
if (chain.length > 1 && upgradeNames.length > 0) {
|
|
84
86
|
output += `import { ${upgradeNames.join(", ")} } from "${INTERNAL_UPGRADES_PATH}";\n`;
|
|
85
87
|
}
|
|
88
|
+
|
|
89
|
+
// DocumentUpgradeFns type is needed by the factory's parameter signature.
|
|
90
|
+
if (hasDerivedFields) {
|
|
91
|
+
output += `import type { DocumentUpgradeFns } from "${INTERNAL_UPGRADE_FNS_PATH}";\n`;
|
|
92
|
+
}
|
|
86
93
|
output += "\n";
|
|
87
94
|
|
|
88
95
|
// Generate model constants
|
|
@@ -149,22 +156,47 @@ export function generateModelMetadataFromChain(resolved, minSupportedVersion) {
|
|
|
149
156
|
let upgradesBlock;
|
|
150
157
|
const allUpgradeNames = [...recordNames, ...unionNames];
|
|
151
158
|
if (chain.length > 1 && allUpgradeNames.length > 0) {
|
|
152
|
-
const upgradeEntries = allUpgradeNames.map(n => `
|
|
153
|
-
upgradesBlock = `
|
|
159
|
+
const upgradeEntries = allUpgradeNames.map(n => ` ${n}: ${n}Upgrades,`).join("\n");
|
|
160
|
+
upgradesBlock = ` upgrades: {\n${upgradeEntries}\n },\n`;
|
|
154
161
|
} else {
|
|
155
162
|
upgradesBlock = "";
|
|
156
163
|
}
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
164
|
+
|
|
165
|
+
// Common metadata literal: shared between the const and factory forms.
|
|
166
|
+
let metadataBody = ` [Metadata]: {\n`;
|
|
167
|
+
metadataBody += ` version: ${latestVersion},\n`;
|
|
161
168
|
if (minVersion !== latestVersion) {
|
|
162
|
-
|
|
169
|
+
metadataBody += ` minSupportedVersion: ${minVersion},\n`;
|
|
170
|
+
}
|
|
171
|
+
metadataBody += upgradesBlock;
|
|
172
|
+
const modelEntriesBody = modelEntries.map(e => ` ${e}`).join(",\n");
|
|
173
|
+
if (hasDerivedFields) {
|
|
174
|
+
// Factory form: schema has derived fields, so the runtime requires the app
|
|
175
|
+
// to supply typed upgrade functions. The factory makes this a compile-time
|
|
176
|
+
// requirement — apps can't get a DocumentSchema value without passing them.
|
|
177
|
+
output += `/**\n`;
|
|
178
|
+
output += ` * Construct the DocumentModel for this SDK, wiring in the typed forward\n`;
|
|
179
|
+
output += ` * functions the runtime needs to materialize derived fields.\n`;
|
|
180
|
+
output += ` */\n`;
|
|
181
|
+
output += `export function DocumentModel(upgradeFns: DocumentUpgradeFns): DocumentSchema {\n`;
|
|
182
|
+
output += ` return {\n`;
|
|
183
|
+
output += `${modelEntriesBody},\n`;
|
|
184
|
+
output += metadataBody;
|
|
185
|
+
output += ` upgradeFns: upgradeFns as unknown as UpgradeFns,\n`;
|
|
186
|
+
output += ` },\n`;
|
|
187
|
+
output += ` };\n`;
|
|
188
|
+
output += `}\n\n`;
|
|
189
|
+
output += `export type DocumentModel = ReturnType<typeof DocumentModel>;\n`;
|
|
190
|
+
} else {
|
|
191
|
+
// Const form: no derived fields means no upgrade functions are required.
|
|
192
|
+
output += `export const DocumentModel = {\n`;
|
|
193
|
+
output += `${modelEntriesBody},\n`;
|
|
194
|
+
// Const form indents one level less than the factory body.
|
|
195
|
+
output += metadataBody.replace(/^ {4}/gm, " ");
|
|
196
|
+
output += ` },\n`;
|
|
197
|
+
output += `} as const satisfies DocumentSchema;\n\n`;
|
|
198
|
+
output += `export type DocumentModel = typeof DocumentModel;\n`;
|
|
163
199
|
}
|
|
164
|
-
output += upgradesBlock;
|
|
165
|
-
output += ` },\n`;
|
|
166
|
-
output += `} as const satisfies DocumentSchema;\n\n`;
|
|
167
|
-
output += `export type DocumentModel = typeof DocumentModel;\n`;
|
|
168
200
|
return {
|
|
169
201
|
modelsFile: output
|
|
170
202
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generateModelMetadataFromSchema.js","names":["formatVariantName","GENERATED_FILE_HEADER","findExternalRefType","resolveMinVersion","INTERNAL_UPGRADES_PATH","modelName","SCHEMA_REEXPORT_PATH","schemaName","TYPES_REEXPORT_PATH","extractExternalRefFieldTypes","record","refs","field","fields","refType","fieldType","push","key","generateModelMetadataFromChain","resolved","minSupportedVersion","chain","latestVersion","minVersion","latestIr","length","ir","output","recordNames","unionNames","variantNames","modelKey","modelDef","Object","entries","models","type","variantName","keys","union","variants","allModelNames","sort","modelTypesImports","join","schemaNames","map","n","upgradeNames","externalRefs","metadataFields","discriminant","formattedVariant","variantTypeName","variantMetadata","modelEntries","upgradesBlock","allUpgradeNames","upgradeEntries","modelsFile"],"sources":["generateModelMetadataFromSchema.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 { IRecordDef } from \"../../lib/pack-docschema-api/pack-docschema-ir/index.js\";\nimport { formatVariantName } from \"../formatVariantName.js\";\nimport { GENERATED_FILE_HEADER } from \"../generatedFileHeader.js\";\nimport { findExternalRefType } from \"../ir/irFieldHelpers.js\";\nimport type { ResolvedIrChain } from \"./resolveSchemaChain.js\";\nimport { resolveMinVersion } from \"./resolveSchemaChain.js\";\nimport {\n INTERNAL_UPGRADES_PATH,\n modelName,\n SCHEMA_REEXPORT_PATH,\n schemaName,\n TYPES_REEXPORT_PATH,\n} from \"./runtimeSchema.js\";\n\nexport interface ModelMetadataOutput {\n /** models.ts content -- DocumentModel with version metadata and upgrade references */\n modelsFile: string;\n}\n\nfunction extractExternalRefFieldTypes(\n record: IRecordDef,\n): Array<[string, string]> {\n const refs: Array<[string, string]> = [];\n for (const field of record.fields) {\n const refType = findExternalRefType(field.fieldType);\n if (refType != null) {\n refs.push([field.key, refType]);\n }\n }\n return refs;\n}\n\n/**\n * Generate models.ts from an already-resolved versioned IR chain.\n */\nexport function generateModelMetadataFromChain(\n resolved: ResolvedIrChain,\n minSupportedVersion?: number,\n): ModelMetadataOutput {\n const { chain } = resolved;\n const { latestVersion, minVersion } = resolveMinVersion(chain, minSupportedVersion);\n const latestIr = chain[chain.length - 1]!.ir;\n\n // --- Generate models.ts ---\n let output = GENERATED_FILE_HEADER;\n\n // Collect model names for imports\n const recordNames: string[] = [];\n const unionNames: string[] = [];\n const variantNames: string[] = [];\n\n for (const [modelKey, modelDef] of Object.entries(latestIr.models)) {\n if (modelDef.type === \"record\") {\n recordNames.push(modelKey);\n } else if (modelDef.type === \"union\") {\n unionNames.push(modelKey);\n for (const variantName of Object.keys(modelDef.union.variants)) {\n variantNames.push(`${modelKey}${formatVariantName(variantName)}`);\n }\n }\n }\n\n const allModelNames = [...recordNames, ...unionNames, ...variantNames].sort();\n\n // Imports\n const modelTypesImports: string[] = [\"DocumentSchema\"];\n if (recordNames.length > 0) modelTypesImports.push(\"RecordModel\");\n if (unionNames.length > 0) modelTypesImports.push(\"UnionModel\");\n\n output += `import type { ${\n modelTypesImports.sort().join(\", \")\n } } from \"@palantir/pack.document-schema.model-types\";\\n`;\n output += `import { Metadata } from \"@palantir/pack.document-schema.model-types\";\\n`;\n\n if (allModelNames.length > 0) {\n output += `import type { ${allModelNames.join(\", \")} } from \"${TYPES_REEXPORT_PATH}\";\\n`;\n }\n\n // Schema imports\n const schemaNames = allModelNames.map(n => schemaName(n));\n if (schemaNames.length > 0) {\n output += `import { ${schemaNames.join(\", \")} } from \"${SCHEMA_REEXPORT_PATH}\";\\n`;\n }\n\n // Upgrade imports (only if there are upgrades)\n const upgradeNames = [...recordNames, ...unionNames].map(n => `${n}Upgrades`);\n if (chain.length > 1 && upgradeNames.length > 0) {\n output += `import { ${upgradeNames.join(\", \")} } from \"${INTERNAL_UPGRADES_PATH}\";\\n`;\n }\n\n output += \"\\n\";\n\n // Generate model constants\n for (const [modelKey, modelDef] of Object.entries(latestIr.models)) {\n if (modelDef.type === \"record\") {\n const externalRefs = extractExternalRefFieldTypes(modelDef.record);\n const metadataFields: string[] = [];\n\n if (externalRefs.length > 0) {\n const entries = externalRefs.map(([field, type]) => ` ${field}: \"${type}\",`).join(\n \"\\n\",\n );\n metadataFields.push(` externalRefFieldTypes: {\\n${entries}\\n },`);\n }\n metadataFields.push(` name: \"${modelKey}\",`);\n\n output += `export interface ${modelName(modelKey)} extends RecordModel<${modelKey}, typeof ${\n schemaName(modelKey)\n }> {}\\n`;\n output += `export const ${modelName(modelKey)}: ${modelName(modelKey)} = {\\n`;\n output += ` __type: {} as ${modelKey},\\n`;\n output += ` zodSchema: ${schemaName(modelKey)},\\n`;\n output += ` [Metadata]: {\\n${metadataFields.join(\"\\n\")}\\n },\\n`;\n output += `};\\n\\n`;\n } else if (modelDef.type === \"union\") {\n const union = modelDef.union;\n const metadataFields: string[] = [];\n metadataFields.push(` discriminant: \"${union.discriminant}\",`);\n metadataFields.push(` name: \"${modelKey}\",`);\n\n output += `export interface ${modelName(modelKey)} extends UnionModel<${modelKey}, typeof ${\n schemaName(modelKey)\n }> {}\\n`;\n output += `export const ${modelName(modelKey)}: ${modelName(modelKey)} = {\\n`;\n output += ` __type: {} as ${modelKey},\\n`;\n output += ` zodSchema: ${schemaName(modelKey)},\\n`;\n output += ` [Metadata]: {\\n${metadataFields.join(\"\\n\")}\\n },\\n`;\n output += `};\\n\\n`;\n\n // Generate variant models\n for (const variantName of Object.keys(union.variants)) {\n const formattedVariant = formatVariantName(variantName);\n const variantTypeName = `${modelKey}${formattedVariant}`;\n const variantMetadata: string[] = [];\n variantMetadata.push(` discriminant: \"${union.discriminant}\",`);\n variantMetadata.push(` name: \"${variantTypeName}\",`);\n\n output += `export interface ${\n modelName(variantTypeName)\n } extends UnionModel<${variantTypeName}, typeof ${schemaName(variantTypeName)}> {}\\n`;\n output += `export const ${modelName(variantTypeName)}: ${modelName(variantTypeName)} = {\\n`;\n output += ` __type: {} as ${variantTypeName},\\n`;\n output += ` zodSchema: ${schemaName(variantTypeName)},\\n`;\n output += ` [Metadata]: {\\n${variantMetadata.join(\"\\n\")}\\n },\\n`;\n output += `};\\n\\n`;\n }\n }\n }\n\n // Generate DocumentModel\n const modelEntries: string[] = [];\n for (const [modelKey, modelDef] of Object.entries(latestIr.models)) {\n if (modelDef.type === \"record\") {\n modelEntries.push(` ${modelKey}: ${modelName(modelKey)}`);\n } else if (modelDef.type === \"union\") {\n modelEntries.push(` ${modelKey}: ${modelName(modelKey)}`);\n for (const variantName of Object.keys(modelDef.union.variants)) {\n const formattedVariant = formatVariantName(variantName);\n const variantTypeName = `${modelKey}${formattedVariant}`;\n modelEntries.push(` ${variantTypeName}: ${modelName(variantTypeName)}`);\n }\n }\n }\n\n // Build upgrades map (includes both record and union entries)\n let upgradesBlock: string;\n const allUpgradeNames = [...recordNames, ...unionNames];\n if (chain.length > 1 && allUpgradeNames.length > 0) {\n const upgradeEntries = allUpgradeNames.map(n => ` ${n}: ${n}Upgrades,`).join(\"\\n\");\n upgradesBlock = ` upgrades: {\\n${upgradeEntries}\\n },\\n`;\n } else {\n upgradesBlock = \"\";\n }\n\n output += `export const DocumentModel = {\\n`;\n output += `${modelEntries.join(\",\\n\")},\\n`;\n output += ` [Metadata]: {\\n`;\n output += ` version: ${latestVersion},\\n`;\n if (minVersion !== latestVersion) {\n output += ` minSupportedVersion: ${minVersion},\\n`;\n }\n output += upgradesBlock;\n output += ` },\\n`;\n output += `} as const satisfies DocumentSchema;\\n\\n`;\n output += `export type Document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tB,QAAQ,GAAGqB,gBAAgB,EAAE;QACxDG,YAAY,CAACvC,IAAI,CAAC,KAAKqC,eAAe,KAAKhD,SAAS,CAACgD,eAAe,CAAC,EAAE,CAAC;MAC1E;IACF;EACF;;EAEA;EACA,IAAIG,aAAqB;EACzB,MAAMC,eAAe,GAAG,CAAC,GAAG7B,WAAW,EAAE,GAAGC,UAAU,CAAC;EACvD,IAAIR,KAAK,CAACI,MAAM,GAAG,CAAC,IAAIgC,eAAe,CAAChC,MAAM,GAAG,CAAC,EAAE;IAClD,MAAMiC,cAAc,GAAGD,eAAe,CAACX,GAAG,CAACC,CAAC,IAAI,SAASA,CAAC,KAAKA,CAAC,WAAW,CAAC,CAACH,IAAI,CAAC,IAAI,CAAC;IACvFY,aAAa,GAAG,oBAAoBE,cAAc,YAAY;EAChE,CAAC,MAAM;IACLF,aAAa,GAAG,EAAE;EACpB;EAEA7B,MAAM,IAAI,kCAAkC;EAC5CA,MAAM,IAAI,GAAG4B,YAAY,CAACX,IAAI,CAAC,KAAK,CAAC,KAAK;EAC1CjB,MAAM,IAAI,mBAAmB;EAC7BA,MAAM,IAAI,gBAAgBL,aAAa,KAAK;EAC5C,IAAIC,UAAU,KAAKD,aAAa,EAAE;IAChCK,MAAM,IAAI,4BAA4BJ,UAAU,KAAK;EACvD;EACAI,MAAM,IAAI6B,aAAa;EACvB7B,MAAM,IAAI,QAAQ;EAClBA,MAAM,IAAI,0CAA0C;EACpDA,MAAM,IAAI,qDAAqD;EAE/D,OAAO;IAAEgC,UAAU,EAAEhC;EAAO,CAAC;AAC/B","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"generateModelMetadataFromSchema.js","names":["formatVariantName","GENERATED_FILE_HEADER","findExternalRefType","chainHasDerivedFields","resolveMinVersion","INTERNAL_UPGRADE_FNS_PATH","INTERNAL_UPGRADES_PATH","modelName","SCHEMA_REEXPORT_PATH","schemaName","TYPES_REEXPORT_PATH","extractExternalRefFieldTypes","record","refs","field","fields","refType","fieldType","push","key","generateModelMetadataFromChain","resolved","minSupportedVersion","chain","latestVersion","minVersion","latestIr","length","ir","hasDerivedFields","output","recordNames","unionNames","variantNames","modelKey","modelDef","Object","entries","models","type","variantName","keys","union","variants","allModelNames","sort","modelTypesImports","join","schemaNames","map","n","upgradeNames","externalRefs","metadataFields","discriminant","formattedVariant","variantTypeName","variantMetadata","modelEntries","upgradesBlock","allUpgradeNames","upgradeEntries","metadataBody","modelEntriesBody","e","replace","modelsFile"],"sources":["generateModelMetadataFromSchema.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 { IRecordDef } from \"../../lib/pack-docschema-api/pack-docschema-ir/index.js\";\nimport { formatVariantName } from \"../formatVariantName.js\";\nimport { GENERATED_FILE_HEADER } from \"../generatedFileHeader.js\";\nimport { findExternalRefType } from \"../ir/irFieldHelpers.js\";\nimport type { ResolvedIrChain } from \"./resolveSchemaChain.js\";\nimport { chainHasDerivedFields, resolveMinVersion } from \"./resolveSchemaChain.js\";\nimport {\n INTERNAL_UPGRADE_FNS_PATH,\n INTERNAL_UPGRADES_PATH,\n modelName,\n SCHEMA_REEXPORT_PATH,\n schemaName,\n TYPES_REEXPORT_PATH,\n} from \"./runtimeSchema.js\";\n\nexport interface ModelMetadataOutput {\n /** models.ts content -- DocumentModel with version metadata and upgrade references */\n modelsFile: string;\n}\n\nfunction extractExternalRefFieldTypes(\n record: IRecordDef,\n): Array<[string, string]> {\n const refs: Array<[string, string]> = [];\n for (const field of record.fields) {\n const refType = findExternalRefType(field.fieldType);\n if (refType != null) {\n refs.push([field.key, refType]);\n }\n }\n return refs;\n}\n\n/**\n * Generate models.ts from an already-resolved versioned IR chain.\n */\nexport function generateModelMetadataFromChain(\n resolved: ResolvedIrChain,\n minSupportedVersion?: number,\n): ModelMetadataOutput {\n const { chain } = resolved;\n const { latestVersion, minVersion } = resolveMinVersion(chain, minSupportedVersion);\n const latestIr = chain[chain.length - 1]!.ir;\n const hasDerivedFields = chainHasDerivedFields(chain);\n\n // --- Generate models.ts ---\n let output = GENERATED_FILE_HEADER;\n\n // Collect model names for imports\n const recordNames: string[] = [];\n const unionNames: string[] = [];\n const variantNames: string[] = [];\n\n for (const [modelKey, modelDef] of Object.entries(latestIr.models)) {\n if (modelDef.type === \"record\") {\n recordNames.push(modelKey);\n } else if (modelDef.type === \"union\") {\n unionNames.push(modelKey);\n for (const variantName of Object.keys(modelDef.union.variants)) {\n variantNames.push(`${modelKey}${formatVariantName(variantName)}`);\n }\n }\n }\n\n const allModelNames = [...recordNames, ...unionNames, ...variantNames].sort();\n\n // Imports\n const modelTypesImports: string[] = [\"DocumentSchema\"];\n if (recordNames.length > 0) modelTypesImports.push(\"RecordModel\");\n if (unionNames.length > 0) modelTypesImports.push(\"UnionModel\");\n if (hasDerivedFields) modelTypesImports.push(\"UpgradeFns\");\n\n output += `import type { ${\n modelTypesImports.sort().join(\", \")\n } } from \"@palantir/pack.document-schema.model-types\";\\n`;\n output += `import { Metadata } from \"@palantir/pack.document-schema.model-types\";\\n`;\n\n if (allModelNames.length > 0) {\n output += `import type { ${allModelNames.join(\", \")} } from \"${TYPES_REEXPORT_PATH}\";\\n`;\n }\n\n // Schema imports\n const schemaNames = allModelNames.map(n => schemaName(n));\n if (schemaNames.length > 0) {\n output += `import { ${schemaNames.join(\", \")} } from \"${SCHEMA_REEXPORT_PATH}\";\\n`;\n }\n\n // Upgrade imports (only if there are upgrades)\n const upgradeNames = [...recordNames, ...unionNames].map(n => `${n}Upgrades`);\n if (chain.length > 1 && upgradeNames.length > 0) {\n output += `import { ${upgradeNames.join(\", \")} } from \"${INTERNAL_UPGRADES_PATH}\";\\n`;\n }\n\n // DocumentUpgradeFns type is needed by the factory's parameter signature.\n if (hasDerivedFields) {\n output += `import type { DocumentUpgradeFns } from \"${INTERNAL_UPGRADE_FNS_PATH}\";\\n`;\n }\n\n output += \"\\n\";\n\n // Generate model constants\n for (const [modelKey, modelDef] of Object.entries(latestIr.models)) {\n if (modelDef.type === \"record\") {\n const externalRefs = extractExternalRefFieldTypes(modelDef.record);\n const metadataFields: string[] = [];\n\n if (externalRefs.length > 0) {\n const entries = externalRefs.map(([field, type]) => ` ${field}: \"${type}\",`).join(\n \"\\n\",\n );\n metadataFields.push(` externalRefFieldTypes: {\\n${entries}\\n },`);\n }\n metadataFields.push(` name: \"${modelKey}\",`);\n\n output += `export interface ${modelName(modelKey)} extends RecordModel<${modelKey}, typeof ${\n schemaName(modelKey)\n }> {}\\n`;\n output += `export const ${modelName(modelKey)}: ${modelName(modelKey)} = {\\n`;\n output += ` __type: {} as ${modelKey},\\n`;\n output += ` zodSchema: ${schemaName(modelKey)},\\n`;\n output += ` [Metadata]: {\\n${metadataFields.join(\"\\n\")}\\n },\\n`;\n output += `};\\n\\n`;\n } else if (modelDef.type === \"union\") {\n const union = modelDef.union;\n const metadataFields: string[] = [];\n metadataFields.push(` discriminant: \"${union.discriminant}\",`);\n metadataFields.push(` name: \"${modelKey}\",`);\n\n output += `export interface ${modelName(modelKey)} extends UnionModel<${modelKey}, typeof ${\n schemaName(modelKey)\n }> {}\\n`;\n output += `export const ${modelName(modelKey)}: ${modelName(modelKey)} = {\\n`;\n output += ` __type: {} as ${modelKey},\\n`;\n output += ` zodSchema: ${schemaName(modelKey)},\\n`;\n output += ` [Metadata]: {\\n${metadataFields.join(\"\\n\")}\\n },\\n`;\n output += `};\\n\\n`;\n\n // Generate variant models\n for (const variantName of Object.keys(union.variants)) {\n const formattedVariant = formatVariantName(variantName);\n const variantTypeName = `${modelKey}${formattedVariant}`;\n const variantMetadata: string[] = [];\n variantMetadata.push(` discriminant: \"${union.discriminant}\",`);\n variantMetadata.push(` name: \"${variantTypeName}\",`);\n\n output += `export interface ${\n modelName(variantTypeName)\n } extends UnionModel<${variantTypeName}, typeof ${schemaName(variantTypeName)}> {}\\n`;\n output += `export const ${modelName(variantTypeName)}: ${modelName(variantTypeName)} = {\\n`;\n output += ` __type: {} as ${variantTypeName},\\n`;\n output += ` zodSchema: ${schemaName(variantTypeName)},\\n`;\n output += ` [Metadata]: {\\n${variantMetadata.join(\"\\n\")}\\n },\\n`;\n output += `};\\n\\n`;\n }\n }\n }\n\n // Generate DocumentModel\n const modelEntries: string[] = [];\n for (const [modelKey, modelDef] of Object.entries(latestIr.models)) {\n if (modelDef.type === \"record\") {\n modelEntries.push(` ${modelKey}: ${modelName(modelKey)}`);\n } else if (modelDef.type === \"union\") {\n modelEntries.push(` ${modelKey}: ${modelName(modelKey)}`);\n for (const variantName of Object.keys(modelDef.union.variants)) {\n const formattedVariant = formatVariantName(variantName);\n const variantTypeName = `${modelKey}${formattedVariant}`;\n modelEntries.push(` ${variantTypeName}: ${modelName(variantTypeName)}`);\n }\n }\n }\n\n // Build upgrades map (includes both record and union entries)\n let upgradesBlock: string;\n const allUpgradeNames = [...recordNames, ...unionNames];\n if (chain.length > 1 && allUpgradeNames.length > 0) {\n const upgradeEntries = allUpgradeNames.map(n => ` ${n}: ${n}Upgrades,`).join(\"\\n\");\n upgradesBlock = ` upgrades: {\\n${upgradeEntries}\\n },\\n`;\n } else {\n upgradesBlock = \"\";\n }\n\n // Common metadata literal: shared between the const and factory forms.\n let metadataBody = ` [Metadata]: {\\n`;\n metadataBody += ` version: ${latestVersion},\\n`;\n if (minVersion !== latestVersion) {\n metadataBody += ` minSupportedVersion: ${minVersion},\\n`;\n }\n metadataBody += upgradesBlock;\n\n const modelEntriesBody = modelEntries.map(e => ` ${e}`).join(\",\\n\");\n\n if (hasDerivedFields) {\n // Factory form: schema has derived fields, so the runtime requires the app\n // to supply typed upgrade functions. The factory makes this a compile-time\n // requirement — apps can't get a DocumentSchema value without passing them.\n output += `/**\\n`;\n output += ` * Construct the DocumentModel for this SDK, wiring in the typed forward\\n`;\n output += ` * functions the runtime needs to materialize derived fields.\\n`;\n output += ` */\\n`;\n output += `export function DocumentModel(upgradeFns: DocumentUpgradeFns): DocumentSchema {\\n`;\n output += ` return {\\n`;\n output += `${modelEntriesBody},\\n`;\n output += metadataBody;\n output += ` upgradeFns: upgradeFns as unknown as UpgradeFns,\\n`;\n output += ` },\\n`;\n output += ` };\\n`;\n output += `}\\n\\n`;\n output += `export type DocumentModel = ReturnType<typeof DocumentModel>;\\n`;\n } else {\n // Const form: no derived fields means no upgrade functions are required.\n output += `export const DocumentModel = {\\n`;\n output += `${modelEntriesBody},\\n`;\n // Const form indents one level less than the factory body.\n output += metadataBody.replace(/^ {4}/gm, \" \");\n output += ` },\\n`;\n output += `} as const satisfies DocumentSchema;\\n\\n`;\n output += `export type DocumentModel = typeof DocumentModel;\\n`;\n }\n\n return { modelsFile: output };\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAGA,SAASA,iBAAiB,QAAQ,yBAAyB;AAC3D,SAASC,qBAAqB,QAAQ,2BAA2B;AACjE,SAASC,mBAAmB,QAAQ,yBAAyB;AAE7D,SAASC,qBAAqB,EAAEC,iBAAiB,QAAQ,yBAAyB;AAClF,SACEC,yBAAyB,EACzBC,sBAAsB,EACtBC,SAAS,EACTC,oBAAoB,EACpBC,UAAU,EACVC,mBAAmB,QACd,oBAAoB;AAO3B,SAASC,4BAA4BA,CACnCC,MAAkB,EACO;EACzB,MAAMC,IAA6B,GAAG,EAAE;EACxC,KAAK,MAAMC,KAAK,IAAIF,MAAM,CAACG,MAAM,EAAE;IACjC,MAAMC,OAAO,GAAGd,mBAAmB,CAACY,KAAK,CAACG,SAAS,CAAC;IACpD,IAAID,OAAO,IAAI,IAAI,EAAE;MACnBH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