@palantir/pack.document-schema.type-gen 0.7.0 → 0.9.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/cli.js +2 -0
- package/build/esm/cli.js.map +1 -1
- package/build/esm/commands/asset/assetDeployHandler.js +60 -0
- package/build/esm/commands/asset/assetDeployHandler.js.map +1 -0
- package/build/esm/commands/asset/registerAssetCommands.js +22 -0
- package/build/esm/commands/asset/registerAssetCommands.js.map +1 -0
- package/build/esm/commands/ir/irDeployHandler.js +5 -4
- package/build/esm/commands/ir/irDeployHandler.js.map +1 -1
- package/build/esm/commands/ir/irGenAssetHandler.js +19 -13
- package/build/esm/commands/ir/irGenAssetHandler.js.map +1 -1
- package/build/esm/commands/schema/registerSchemaCommands.js +2 -0
- package/build/esm/commands/schema/registerSchemaCommands.js.map +1 -1
- package/build/esm/commands/schema/schemaGenTypesHandler.js +147 -0
- package/build/esm/commands/schema/schemaGenTypesHandler.js.map +1 -0
- package/build/esm/commands/steps/stepsGenIrHandler.js +6 -1
- package/build/esm/commands/steps/stepsGenIrHandler.js.map +1 -1
- package/build/esm/commands/types.js +2 -0
- package/build/esm/commands/types.js.map +1 -0
- package/build/esm/index.js +6 -0
- package/build/esm/index.js.map +1 -1
- package/build/esm/lib/pack-docschema-api/pack-docschema-ir/fieldDef.js.map +1 -1
- package/build/esm/lib/pack-docschema-api/pack-docschema-ir/fieldValueDatetime.js.map +1 -1
- package/build/esm/lib/pack-docschema-api/pack-docschema-ir/fieldValueMediaRef.js.map +1 -1
- package/build/esm/lib/pack-docschema-api/pack-docschema-ir/fieldValueText.js.map +1 -1
- package/build/esm/lib/pack-docschema-api/pack-docschema-ir/recordDef.js.map +1 -1
- package/build/esm/lib/pack-docschema-api/pack-docschema-ir/schemaMeta.js.map +1 -1
- package/build/esm/lib/pack-docschema-api/pack-docschema-ir/unionDef.js.map +1 -1
- package/build/esm/utils/generatedFileHeader.js +1 -0
- package/build/esm/utils/generatedFileHeader.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/ir/__tests__/convertIrToWireSchema.test.js +323 -0
- package/build/esm/utils/ir/__tests__/convertIrToWireSchema.test.js.map +1 -0
- package/build/esm/utils/ir/__tests__/generateModelsFromIr.test.js +43 -61
- package/build/esm/utils/ir/__tests__/generateModelsFromIr.test.js.map +1 -1
- package/build/esm/utils/ir/__tests__/generateZodSchemasFromIr.test.js +73 -103
- package/build/esm/utils/ir/__tests__/generateZodSchemasFromIr.test.js.map +1 -1
- package/build/esm/utils/ir/convertIrToWireSchema.js +201 -0
- package/build/esm/utils/ir/convertIrToWireSchema.js.map +1 -0
- package/build/esm/utils/ir/generateModelsFromIr.js +2 -2
- package/build/esm/utils/ir/generateModelsFromIr.js.map +1 -1
- package/build/esm/utils/ir/generateZodSchemasFromIr.js +2 -2
- package/build/esm/utils/ir/generateZodSchemasFromIr.js.map +1 -1
- package/build/esm/utils/schema/__tests__/__snapshots__/generateVersionsFromSchema/single-version.js +2 -0
- package/build/esm/utils/schema/__tests__/__snapshots__/generateVersionsFromSchema/single-version.js.map +1 -0
- package/build/esm/utils/schema/__tests__/__snapshots__/generateVersionsFromSchema/three-version-chain.js +2 -0
- package/build/esm/utils/schema/__tests__/__snapshots__/generateVersionsFromSchema/three-version-chain.js.map +1 -0
- package/build/esm/utils/schema/__tests__/__snapshots__/generateVersionsFromSchema/two-version.js +2 -0
- package/build/esm/utils/schema/__tests__/__snapshots__/generateVersionsFromSchema/two-version.js.map +1 -0
- package/build/esm/utils/schema/__tests__/fixtures.js +207 -0
- package/build/esm/utils/schema/__tests__/fixtures.js.map +1 -0
- package/build/esm/utils/schema/__tests__/generateInternalFromSchema.test.js +41 -0
- package/build/esm/utils/schema/__tests__/generateInternalFromSchema.test.js.map +1 -0
- package/build/esm/utils/schema/__tests__/generateModelMetadataFromSchema.test.js +41 -0
- package/build/esm/utils/schema/__tests__/generateModelMetadataFromSchema.test.js.map +1 -0
- package/build/esm/utils/schema/__tests__/generateScopeFromSchema.test.js +37 -0
- package/build/esm/utils/schema/__tests__/generateScopeFromSchema.test.js.map +1 -0
- package/build/esm/utils/schema/__tests__/generateVersionedTypesFromSchema.test.js +55 -0
- package/build/esm/utils/schema/__tests__/generateVersionedTypesFromSchema.test.js.map +1 -0
- package/build/esm/utils/schema/__tests__/generateVersionedZodFromSchema.test.js +55 -0
- package/build/esm/utils/schema/__tests__/generateVersionedZodFromSchema.test.js.map +1 -0
- package/build/esm/utils/schema/__tests__/generateVersionsFromSchema.test.js +37 -0
- package/build/esm/utils/schema/__tests__/generateVersionsFromSchema.test.js.map +1 -0
- package/build/esm/utils/schema/__tests__/snapshotUtils.js +106 -0
- package/build/esm/utils/schema/__tests__/snapshotUtils.js.map +1 -0
- package/build/esm/utils/schema/generateIndexFromSchema.js +72 -0
- package/build/esm/utils/schema/generateIndexFromSchema.js.map +1 -0
- package/build/esm/utils/schema/generateInternalFromSchema.js +380 -0
- package/build/esm/utils/schema/generateInternalFromSchema.js.map +1 -0
- package/build/esm/utils/schema/generateModelMetadataFromSchema.js +195 -0
- package/build/esm/utils/schema/generateModelMetadataFromSchema.js.map +1 -0
- package/build/esm/utils/schema/generateScopeFromSchema.js +155 -0
- package/build/esm/utils/schema/generateScopeFromSchema.js.map +1 -0
- package/build/esm/utils/schema/generateTypesFromSchema.js +16 -30
- package/build/esm/utils/schema/generateTypesFromSchema.js.map +1 -1
- package/build/esm/utils/schema/generateVersionedTypesFromSchema.js +281 -0
- package/build/esm/utils/schema/generateVersionedTypesFromSchema.js.map +1 -0
- package/build/esm/utils/schema/generateVersionedZodFromSchema.js +189 -0
- package/build/esm/utils/schema/generateVersionedZodFromSchema.js.map +1 -0
- package/build/esm/utils/schema/generateVersionsFromSchema.js +50 -0
- package/build/esm/utils/schema/generateVersionsFromSchema.js.map +1 -0
- package/build/esm/utils/schema/resolveSchemaChain.js +54 -0
- package/build/esm/utils/schema/resolveSchemaChain.js.map +1 -0
- package/build/esm/utils/schema/runtimeSchema.js +96 -0
- package/build/esm/utils/schema/runtimeSchema.js.map +1 -0
- 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/esm/utils/steps/__tests__/convertStepsToIr.test.js +81 -8
- package/build/esm/utils/steps/__tests__/convertStepsToIr.test.js.map +1 -1
- package/build/esm/utils/steps/convertStepsToIr.js +8 -13
- package/build/esm/utils/steps/convertStepsToIr.js.map +1 -1
- package/build/esm/utils/steps/parseMigrationSteps.js +4 -2
- package/build/esm/utils/steps/parseMigrationSteps.js.map +1 -1
- package/build/types/cli.d.ts.map +1 -1
- package/build/types/commands/asset/assetDeployHandler.d.ts +10 -0
- package/build/types/commands/asset/assetDeployHandler.d.ts.map +1 -0
- package/build/types/commands/asset/registerAssetCommands.d.ts +3 -0
- package/build/types/commands/asset/registerAssetCommands.d.ts.map +1 -0
- package/build/types/commands/ir/irDeployHandler.d.ts +1 -1
- package/build/types/commands/ir/irDeployHandler.d.ts.map +1 -1
- package/build/types/commands/ir/irGenAssetHandler.d.ts +1 -1
- package/build/types/commands/ir/irGenAssetHandler.d.ts.map +1 -1
- package/build/types/commands/schema/registerSchemaCommands.d.ts.map +1 -1
- package/build/types/commands/schema/schemaGenTypesHandler.d.ts +8 -0
- package/build/types/commands/schema/schemaGenTypesHandler.d.ts.map +1 -0
- package/build/types/commands/steps/stepsGenIrHandler.d.ts.map +1 -1
- package/build/types/commands/types.d.ts +12 -0
- package/build/types/commands/types.d.ts.map +1 -0
- package/build/types/index.d.ts +6 -0
- package/build/types/index.d.ts.map +1 -1
- package/build/types/lib/pack-docschema-api/pack-docschema-ir/fieldDef.d.ts +2 -2
- package/build/types/lib/pack-docschema-api/pack-docschema-ir/fieldDef.d.ts.map +1 -1
- package/build/types/lib/pack-docschema-api/pack-docschema-ir/fieldValueDatetime.d.ts +1 -0
- package/build/types/lib/pack-docschema-api/pack-docschema-ir/fieldValueDatetime.d.ts.map +1 -1
- package/build/types/lib/pack-docschema-api/pack-docschema-ir/fieldValueMediaRef.d.ts +1 -0
- package/build/types/lib/pack-docschema-api/pack-docschema-ir/fieldValueMediaRef.d.ts.map +1 -1
- package/build/types/lib/pack-docschema-api/pack-docschema-ir/fieldValueText.d.ts +3 -0
- package/build/types/lib/pack-docschema-api/pack-docschema-ir/fieldValueText.d.ts.map +1 -1
- package/build/types/lib/pack-docschema-api/pack-docschema-ir/recordDef.d.ts +0 -2
- package/build/types/lib/pack-docschema-api/pack-docschema-ir/recordDef.d.ts.map +1 -1
- package/build/types/lib/pack-docschema-api/pack-docschema-ir/schemaMeta.d.ts +2 -2
- package/build/types/lib/pack-docschema-api/pack-docschema-ir/schemaMeta.d.ts.map +1 -1
- package/build/types/lib/pack-docschema-api/pack-docschema-ir/unionDef.d.ts +1 -1
- package/build/types/lib/pack-docschema-api/pack-docschema-ir/unionDef.d.ts.map +1 -1
- package/build/types/utils/generatedFileHeader.d.ts +1 -0
- package/build/types/utils/generatedFileHeader.d.ts.map +1 -1
- package/build/types/utils/ir/__tests__/convertIrToWireSchema.test.d.ts +2 -0
- package/build/types/utils/ir/__tests__/convertIrToWireSchema.test.d.ts.map +1 -0
- package/build/types/utils/ir/convertIrToWireSchema.d.ts +17 -0
- package/build/types/utils/ir/convertIrToWireSchema.d.ts.map +1 -0
- package/build/types/utils/schema/__tests__/fixtures.d.ts +14 -0
- package/build/types/utils/schema/__tests__/fixtures.d.ts.map +1 -0
- package/build/types/utils/schema/__tests__/generateInternalFromSchema.test.d.ts +2 -0
- package/build/types/utils/schema/__tests__/generateInternalFromSchema.test.d.ts.map +1 -0
- package/build/types/utils/schema/__tests__/generateModelMetadataFromSchema.test.d.ts +2 -0
- package/build/types/utils/schema/__tests__/generateModelMetadataFromSchema.test.d.ts.map +1 -0
- package/build/types/utils/schema/__tests__/generateScopeFromSchema.test.d.ts +2 -0
- package/build/types/utils/schema/__tests__/generateScopeFromSchema.test.d.ts.map +1 -0
- package/build/types/utils/schema/__tests__/generateVersionedTypesFromSchema.test.d.ts +2 -0
- package/build/types/utils/schema/__tests__/generateVersionedTypesFromSchema.test.d.ts.map +1 -0
- package/build/types/utils/schema/__tests__/generateVersionedZodFromSchema.test.d.ts +2 -0
- package/build/types/utils/schema/__tests__/generateVersionedZodFromSchema.test.d.ts.map +1 -0
- package/build/types/utils/schema/__tests__/generateVersionsFromSchema.test.d.ts +2 -0
- package/build/types/utils/schema/__tests__/generateVersionsFromSchema.test.d.ts.map +1 -0
- package/build/types/utils/schema/__tests__/snapshotUtils.d.ts +47 -0
- package/build/types/utils/schema/__tests__/snapshotUtils.d.ts.map +1 -0
- package/build/types/utils/schema/generateIndexFromSchema.d.ts +14 -0
- package/build/types/utils/schema/generateIndexFromSchema.d.ts.map +1 -0
- package/build/types/utils/schema/generateInternalFromSchema.d.ts +18 -0
- package/build/types/utils/schema/generateInternalFromSchema.d.ts.map +1 -0
- package/build/types/utils/schema/generateModelMetadataFromSchema.d.ts +15 -0
- package/build/types/utils/schema/generateModelMetadataFromSchema.d.ts.map +1 -0
- package/build/types/utils/schema/generateScopeFromSchema.d.ts +13 -0
- package/build/types/utils/schema/generateScopeFromSchema.d.ts.map +1 -0
- package/build/types/utils/schema/generateTypesFromSchema.d.ts.map +1 -1
- package/build/types/utils/schema/generateVersionedTypesFromSchema.d.ts +18 -0
- package/build/types/utils/schema/generateVersionedTypesFromSchema.d.ts.map +1 -0
- package/build/types/utils/schema/generateVersionedZodFromSchema.d.ts +16 -0
- package/build/types/utils/schema/generateVersionedZodFromSchema.d.ts.map +1 -0
- package/build/types/utils/schema/generateVersionsFromSchema.d.ts +13 -0
- package/build/types/utils/schema/generateVersionsFromSchema.d.ts.map +1 -0
- package/build/types/utils/schema/resolveSchemaChain.d.ts +18 -0
- package/build/types/utils/schema/resolveSchemaChain.d.ts.map +1 -0
- package/build/types/utils/schema/runtimeSchema.d.ts +59 -0
- package/build/types/utils/schema/runtimeSchema.d.ts.map +1 -0
- package/build/types/utils/steps/convertStepsToIr.d.ts.map +1 -1
- package/build/types/utils/steps/parseMigrationSteps.d.ts.map +1 -1
- package/package.json +4 -4
|
@@ -0,0 +1,195 @@
|
|
|
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 { formatVariantName } from "../formatVariantName.js";
|
|
18
|
+
import { GENERATED_FILE_HEADER } from "../generatedFileHeader.js";
|
|
19
|
+
import { resolveSchemaChain } from "./resolveSchemaChain.js";
|
|
20
|
+
import { INTERNAL_UPGRADES_PATH, isRecordSchema, isUnionSchema, modelName, SCHEMA_REEXPORT_PATH, schemaName, TYPES_REEXPORT_PATH } from "./runtimeSchema.js";
|
|
21
|
+
/**
|
|
22
|
+
* Detect which external ref field types (docRef, mediaRef, objectRef, userRef)
|
|
23
|
+
* are present on a record for its model metadata.
|
|
24
|
+
*/
|
|
25
|
+
function findExternalRefType(field) {
|
|
26
|
+
switch (field.type) {
|
|
27
|
+
case "docRef":
|
|
28
|
+
return "docRef";
|
|
29
|
+
case "mediaRef":
|
|
30
|
+
return "mediaRef";
|
|
31
|
+
case "objectRef":
|
|
32
|
+
return "objectRef";
|
|
33
|
+
case "userRef":
|
|
34
|
+
return "userRef";
|
|
35
|
+
case "optional":
|
|
36
|
+
return field.item ? findExternalRefType(field.item) : undefined;
|
|
37
|
+
case "array":
|
|
38
|
+
return field.items ? findExternalRefType(field.items) : undefined;
|
|
39
|
+
default:
|
|
40
|
+
return undefined;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
function extractExternalRefFieldTypes(record) {
|
|
44
|
+
const refs = [];
|
|
45
|
+
for (const [fieldName, fieldType] of Object.entries(record.fields)) {
|
|
46
|
+
const refType = findExternalRefType(fieldType);
|
|
47
|
+
if (refType != null) {
|
|
48
|
+
refs.push([fieldName, refType]);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
return refs;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Generate models.ts and schema manifest from a versioned schema chain.
|
|
56
|
+
*
|
|
57
|
+
* @param schema - The schema definition (initial or versioned)
|
|
58
|
+
* @param minSupportedVersion - Minimum version this client supports (defaults to latest)
|
|
59
|
+
* @param options - Configuration for import paths
|
|
60
|
+
* @returns Object containing generated models.ts content and schema manifest JSON
|
|
61
|
+
*/
|
|
62
|
+
export function generateModelMetadataFromSchema(schema, minSupportedVersion) {
|
|
63
|
+
const {
|
|
64
|
+
chain,
|
|
65
|
+
latestVersion,
|
|
66
|
+
minVersion
|
|
67
|
+
} = resolveSchemaChain(schema, minSupportedVersion);
|
|
68
|
+
const latestSchema = chain[chain.length - 1].schema;
|
|
69
|
+
|
|
70
|
+
// --- Generate models.ts ---
|
|
71
|
+
let output = GENERATED_FILE_HEADER;
|
|
72
|
+
|
|
73
|
+
// Collect model names for imports
|
|
74
|
+
const recordNames = [];
|
|
75
|
+
const unionNames = [];
|
|
76
|
+
const variantNames = [];
|
|
77
|
+
for (const [exportName, item] of Object.entries(latestSchema)) {
|
|
78
|
+
if (isRecordSchema(item)) {
|
|
79
|
+
recordNames.push(exportName);
|
|
80
|
+
} else if (isUnionSchema(item)) {
|
|
81
|
+
unionNames.push(exportName);
|
|
82
|
+
for (const variantName of Object.keys(item.variants)) {
|
|
83
|
+
variantNames.push(`${exportName}${formatVariantName(variantName)}`);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
const allModelNames = [...recordNames, ...unionNames, ...variantNames].sort();
|
|
88
|
+
|
|
89
|
+
// Imports
|
|
90
|
+
const modelTypesImports = ["DocumentSchema"];
|
|
91
|
+
if (recordNames.length > 0) modelTypesImports.push("RecordModel");
|
|
92
|
+
if (unionNames.length > 0) modelTypesImports.push("UnionModel");
|
|
93
|
+
output += `import type { ${modelTypesImports.sort().join(", ")} } from "@palantir/pack.document-schema.model-types";\n`;
|
|
94
|
+
output += `import { Metadata } from "@palantir/pack.document-schema.model-types";\n`;
|
|
95
|
+
if (allModelNames.length > 0) {
|
|
96
|
+
output += `import type { ${allModelNames.join(", ")} } from "${TYPES_REEXPORT_PATH}";\n`;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// Schema imports
|
|
100
|
+
const schemaNames = allModelNames.map(n => schemaName(n));
|
|
101
|
+
if (schemaNames.length > 0) {
|
|
102
|
+
output += `import { ${schemaNames.join(", ")} } from "${SCHEMA_REEXPORT_PATH}";\n`;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// Upgrade imports (only if there are upgrades)
|
|
106
|
+
const upgradeNames = [...recordNames, ...unionNames].map(n => `${n}Upgrades`);
|
|
107
|
+
if (chain.length > 1 && upgradeNames.length > 0) {
|
|
108
|
+
output += `import { ${upgradeNames.join(", ")} } from "${INTERNAL_UPGRADES_PATH}";\n`;
|
|
109
|
+
}
|
|
110
|
+
output += "\n";
|
|
111
|
+
|
|
112
|
+
// Generate model constants
|
|
113
|
+
for (const [exportName, item] of Object.entries(latestSchema)) {
|
|
114
|
+
if (isRecordSchema(item)) {
|
|
115
|
+
const externalRefs = extractExternalRefFieldTypes(item);
|
|
116
|
+
const metadataFields = [];
|
|
117
|
+
if (externalRefs.length > 0) {
|
|
118
|
+
const entries = externalRefs.map(([field, type]) => ` ${field}: "${type}",`).join("\n");
|
|
119
|
+
metadataFields.push(` externalRefFieldTypes: {\n${entries}\n },`);
|
|
120
|
+
}
|
|
121
|
+
metadataFields.push(` name: "${exportName}",`);
|
|
122
|
+
output += `export interface ${modelName(exportName)} extends RecordModel<${exportName}, typeof ${schemaName(exportName)}> {}\n`;
|
|
123
|
+
output += `export const ${modelName(exportName)}: ${modelName(exportName)} = {\n`;
|
|
124
|
+
output += ` __type: {} as ${exportName},\n`;
|
|
125
|
+
output += ` zodSchema: ${schemaName(exportName)},\n`;
|
|
126
|
+
output += ` [Metadata]: {\n${metadataFields.join("\n")}\n },\n`;
|
|
127
|
+
output += `};\n\n`;
|
|
128
|
+
} else if (isUnionSchema(item)) {
|
|
129
|
+
const metadataFields = [];
|
|
130
|
+
metadataFields.push(` discriminant: "${item.discriminant}",`);
|
|
131
|
+
metadataFields.push(` name: "${exportName}",`);
|
|
132
|
+
output += `export interface ${modelName(exportName)} extends UnionModel<${exportName}, typeof ${schemaName(exportName)}> {}\n`;
|
|
133
|
+
output += `export const ${modelName(exportName)}: ${modelName(exportName)} = {\n`;
|
|
134
|
+
output += ` __type: {} as ${exportName},\n`;
|
|
135
|
+
output += ` zodSchema: ${schemaName(exportName)},\n`;
|
|
136
|
+
output += ` [Metadata]: {\n${metadataFields.join("\n")}\n },\n`;
|
|
137
|
+
output += `};\n\n`;
|
|
138
|
+
|
|
139
|
+
// Generate variant models
|
|
140
|
+
for (const variantName of Object.keys(item.variants)) {
|
|
141
|
+
const formattedVariant = formatVariantName(variantName);
|
|
142
|
+
const variantTypeName = `${exportName}${formattedVariant}`;
|
|
143
|
+
const variantMetadata = [];
|
|
144
|
+
variantMetadata.push(` discriminant: "${item.discriminant}",`);
|
|
145
|
+
variantMetadata.push(` name: "${variantTypeName}",`);
|
|
146
|
+
output += `export interface ${modelName(variantTypeName)} extends UnionModel<${variantTypeName}, typeof ${schemaName(variantTypeName)}> {}\n`;
|
|
147
|
+
output += `export const ${modelName(variantTypeName)}: ${modelName(variantTypeName)} = {\n`;
|
|
148
|
+
output += ` __type: {} as ${variantTypeName},\n`;
|
|
149
|
+
output += ` zodSchema: ${schemaName(variantTypeName)},\n`;
|
|
150
|
+
output += ` [Metadata]: {\n${variantMetadata.join("\n")}\n },\n`;
|
|
151
|
+
output += `};\n\n`;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// Generate DocumentModel
|
|
157
|
+
const modelEntries = [];
|
|
158
|
+
for (const [exportName, item] of Object.entries(latestSchema)) {
|
|
159
|
+
if (isRecordSchema(item)) {
|
|
160
|
+
modelEntries.push(` ${exportName}: ${modelName(exportName)}`);
|
|
161
|
+
} else if (isUnionSchema(item)) {
|
|
162
|
+
modelEntries.push(` ${exportName}: ${modelName(exportName)}`);
|
|
163
|
+
for (const variantName of Object.keys(item.variants)) {
|
|
164
|
+
const formattedVariant = formatVariantName(variantName);
|
|
165
|
+
const variantTypeName = `${exportName}${formattedVariant}`;
|
|
166
|
+
modelEntries.push(` ${variantTypeName}: ${modelName(variantTypeName)}`);
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
// Build upgrades map (includes both record and union entries)
|
|
172
|
+
let upgradesBlock;
|
|
173
|
+
const allUpgradeNames = [...recordNames, ...unionNames];
|
|
174
|
+
if (chain.length > 1 && allUpgradeNames.length > 0) {
|
|
175
|
+
const upgradeEntries = allUpgradeNames.map(n => ` ${n}: ${n}Upgrades,`).join("\n");
|
|
176
|
+
upgradesBlock = ` upgrades: {\n${upgradeEntries}\n },\n`;
|
|
177
|
+
} else {
|
|
178
|
+
upgradesBlock = "";
|
|
179
|
+
}
|
|
180
|
+
output += `export const DocumentModel = {\n`;
|
|
181
|
+
output += `${modelEntries.join(",\n")},\n`;
|
|
182
|
+
output += ` [Metadata]: {\n`;
|
|
183
|
+
output += ` version: ${latestVersion},\n`;
|
|
184
|
+
if (minVersion !== latestVersion) {
|
|
185
|
+
output += ` minSupportedVersion: ${minVersion},\n`;
|
|
186
|
+
}
|
|
187
|
+
output += upgradesBlock;
|
|
188
|
+
output += ` },\n`;
|
|
189
|
+
output += `} as const satisfies DocumentSchema;\n\n`;
|
|
190
|
+
output += `export type DocumentModel = typeof DocumentModel;\n`;
|
|
191
|
+
return {
|
|
192
|
+
modelsFile: output
|
|
193
|
+
};
|
|
194
|
+
}
|
|
195
|
+
//# sourceMappingURL=generateModelMetadataFromSchema.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"generateModelMetadataFromSchema.js","names":["formatVariantName","GENERATED_FILE_HEADER","resolveSchemaChain","INTERNAL_UPGRADES_PATH","isRecordSchema","isUnionSchema","modelName","SCHEMA_REEXPORT_PATH","schemaName","TYPES_REEXPORT_PATH","findExternalRefType","field","type","item","undefined","items","extractExternalRefFieldTypes","record","refs","fieldName","fieldType","Object","entries","fields","refType","push","generateModelMetadataFromSchema","schema","minSupportedVersion","chain","latestVersion","minVersion","latestSchema","length","output","recordNames","unionNames","variantNames","exportName","variantName","keys","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 { SchemaDefinition } from \"@palantir/pack.schema\";\nimport { formatVariantName } from \"../formatVariantName.js\";\nimport { GENERATED_FILE_HEADER } from \"../generatedFileHeader.js\";\nimport { resolveSchemaChain } from \"./resolveSchemaChain.js\";\nimport type { RuntimeSchemaRecord, SchemaField } from \"./runtimeSchema.js\";\nimport {\n INTERNAL_UPGRADES_PATH,\n isRecordSchema,\n isUnionSchema,\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\n/**\n * Detect which external ref field types (docRef, mediaRef, objectRef, userRef)\n * are present on a record for its model metadata.\n */\nfunction findExternalRefType(field: SchemaField): string | undefined {\n switch (field.type) {\n case \"docRef\":\n return \"docRef\";\n case \"mediaRef\":\n return \"mediaRef\";\n case \"objectRef\":\n return \"objectRef\";\n case \"userRef\":\n return \"userRef\";\n case \"optional\":\n return field.item ? findExternalRefType(field.item) : undefined;\n case \"array\":\n return field.items ? findExternalRefType(field.items) : undefined;\n default:\n return undefined;\n }\n}\n\nfunction extractExternalRefFieldTypes(\n record: RuntimeSchemaRecord,\n): Array<[string, string]> {\n const refs: Array<[string, string]> = [];\n for (const [fieldName, fieldType] of Object.entries(record.fields)) {\n const refType = findExternalRefType(fieldType);\n if (refType != null) {\n refs.push([fieldName, refType]);\n }\n }\n return refs;\n}\n\n/**\n * Generate models.ts and schema manifest from a versioned schema chain.\n *\n * @param schema - The schema definition (initial or versioned)\n * @param minSupportedVersion - Minimum version this client supports (defaults to latest)\n * @param options - Configuration for import paths\n * @returns Object containing generated models.ts content and schema manifest JSON\n */\nexport function generateModelMetadataFromSchema(\n schema: SchemaDefinition,\n minSupportedVersion?: number,\n): ModelMetadataOutput {\n const { chain, latestVersion, minVersion } = resolveSchemaChain(schema, minSupportedVersion);\n const latestSchema = chain[chain.length - 1]!.schema;\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 [exportName, item] of Object.entries(latestSchema)) {\n if (isRecordSchema(item)) {\n recordNames.push(exportName);\n } else if (isUnionSchema(item)) {\n unionNames.push(exportName);\n for (const variantName of Object.keys(item.variants)) {\n variantNames.push(`${exportName}${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 [exportName, item] of Object.entries(latestSchema)) {\n if (isRecordSchema(item)) {\n const externalRefs = extractExternalRefFieldTypes(item);\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: \"${exportName}\",`);\n\n output += `export interface ${\n modelName(exportName)\n } extends RecordModel<${exportName}, typeof ${schemaName(exportName)}> {}\\n`;\n output += `export const ${modelName(exportName)}: ${modelName(exportName)} = {\\n`;\n output += ` __type: {} as ${exportName},\\n`;\n output += ` zodSchema: ${schemaName(exportName)},\\n`;\n output += ` [Metadata]: {\\n${metadataFields.join(\"\\n\")}\\n },\\n`;\n output += `};\\n\\n`;\n } else if (isUnionSchema(item)) {\n const metadataFields: string[] = [];\n metadataFields.push(` discriminant: \"${item.discriminant}\",`);\n metadataFields.push(` name: \"${exportName}\",`);\n\n output += `export interface ${\n modelName(exportName)\n } extends UnionModel<${exportName}, typeof ${schemaName(exportName)}> {}\\n`;\n output += `export const ${modelName(exportName)}: ${modelName(exportName)} = {\\n`;\n output += ` __type: {} as ${exportName},\\n`;\n output += ` zodSchema: ${schemaName(exportName)},\\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(item.variants)) {\n const formattedVariant = formatVariantName(variantName);\n const variantTypeName = `${exportName}${formattedVariant}`;\n const variantMetadata: string[] = [];\n variantMetadata.push(` discriminant: \"${item.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 [exportName, item] of Object.entries(latestSchema)) {\n if (isRecordSchema(item)) {\n modelEntries.push(` ${exportName}: ${modelName(exportName)}`);\n } else if (isUnionSchema(item)) {\n modelEntries.push(` ${exportName}: ${modelName(exportName)}`);\n for (const variantName of Object.keys(item.variants)) {\n const formattedVariant = formatVariantName(variantName);\n const variantTypeName = `${exportName}${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 DocumentModel = typeof DocumentModel;\\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,qBA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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 { GENERATED_FILE_HEADER } from "../generatedFileHeader.js";
|
|
18
|
+
import { resolveSchemaChain } from "./resolveSchemaChain.js";
|
|
19
|
+
import { isRecordSchema, isUnionSchema, modelName, MODELS_PATH, typesFilePath, versionedTypeName, versionedWriteTypeName, writeTypesFilePath } from "./runtimeSchema.js";
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Generate versionedDocRef.ts from a versioned schema chain.
|
|
23
|
+
*
|
|
24
|
+
* Produces:
|
|
25
|
+
* - Per-version VersionedDocRef_vN interfaces extending DocumentRef<DocumentModel>
|
|
26
|
+
* - Union type VersionedDocRef = VersionedDocRef_v1 | VersionedDocRef_v2
|
|
27
|
+
*
|
|
28
|
+
* Every model gets a version-specific overload on every version so that
|
|
29
|
+
* write data is always typed to the exact version, not the latest.
|
|
30
|
+
*/
|
|
31
|
+
export function generateScopeFromSchema(schema, minSupportedVersion) {
|
|
32
|
+
const {
|
|
33
|
+
chain,
|
|
34
|
+
minVersion
|
|
35
|
+
} = resolveSchemaChain(schema, minSupportedVersion);
|
|
36
|
+
|
|
37
|
+
// Filter to supported versions
|
|
38
|
+
const supportedVersions = chain.filter(v => v.version >= minVersion);
|
|
39
|
+
|
|
40
|
+
// Collect all model names from the latest schema
|
|
41
|
+
const latestSchema = chain[chain.length - 1].schema;
|
|
42
|
+
const allModelNames = [];
|
|
43
|
+
for (const [exportName, item] of Object.entries(latestSchema)) {
|
|
44
|
+
if (isRecordSchema(item) || isUnionSchema(item)) {
|
|
45
|
+
allModelNames.push(exportName);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// Build output
|
|
50
|
+
let output = GENERATED_FILE_HEADER;
|
|
51
|
+
|
|
52
|
+
// Import model-types
|
|
53
|
+
output += `import type { DocumentRef, RecordId, RecordRef } from "@palantir/pack.document-schema.model-types";\n`;
|
|
54
|
+
|
|
55
|
+
// Import model types from models.ts
|
|
56
|
+
const modelImports = allModelNames.map(n => modelName(n));
|
|
57
|
+
const typeImportsFromModels = ["DocumentModel", ...modelImports];
|
|
58
|
+
output += `import type { ${typeImportsFromModels.join(", ")} } from "${MODELS_PATH}";\n`;
|
|
59
|
+
|
|
60
|
+
// Import per-version types
|
|
61
|
+
for (const {
|
|
62
|
+
version,
|
|
63
|
+
schema: versionSchema
|
|
64
|
+
} of supportedVersions) {
|
|
65
|
+
const readTypeImports = [];
|
|
66
|
+
const writeTypeImports = [];
|
|
67
|
+
for (const [exportName, item] of Object.entries(versionSchema)) {
|
|
68
|
+
if (isRecordSchema(item)) {
|
|
69
|
+
readTypeImports.push(versionedTypeName(exportName, version));
|
|
70
|
+
writeTypeImports.push(versionedWriteTypeName(exportName, version));
|
|
71
|
+
} else if (isUnionSchema(item)) {
|
|
72
|
+
readTypeImports.push(versionedTypeName(exportName, version));
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
if (readTypeImports.length > 0) {
|
|
76
|
+
output += `import type { ${readTypeImports.sort().join(", ")} } from "${typesFilePath(version)}";\n`;
|
|
77
|
+
}
|
|
78
|
+
if (writeTypeImports.length > 0) {
|
|
79
|
+
output += `import type { ${writeTypeImports.sort().join(", ")} } from "${writeTypesFilePath(version)}";\n`;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
output += "\n";
|
|
83
|
+
|
|
84
|
+
// Generate per-version VersionedDocRef interfaces extending DocumentRef.
|
|
85
|
+
// Every model gets a version-specific overload on every version so that
|
|
86
|
+
// write data is always typed to the exact version, not the latest.
|
|
87
|
+
for (const {
|
|
88
|
+
version,
|
|
89
|
+
schema: versionSchema
|
|
90
|
+
} of supportedVersions) {
|
|
91
|
+
output += `export interface VersionedDocRef_v${version} extends DocumentRef<DocumentModel> {\n`;
|
|
92
|
+
output += ` readonly version: ${version};\n`;
|
|
93
|
+
|
|
94
|
+
// updateRecord overloads — record models get write types, union models get Partial<read>
|
|
95
|
+
for (const [exportName, item] of Object.entries(versionSchema)) {
|
|
96
|
+
if (isRecordSchema(item)) {
|
|
97
|
+
const writeType = versionedWriteTypeName(exportName, version);
|
|
98
|
+
output += ` updateRecord(ref: RecordRef<typeof ${modelName(exportName)}>, data: ${writeType}): Promise<void>;\n`;
|
|
99
|
+
} else if (isUnionSchema(item)) {
|
|
100
|
+
const readType = versionedTypeName(exportName, version);
|
|
101
|
+
output += ` updateRecord(ref: RecordRef<typeof ${modelName(exportName)}>, data: Partial<${readType}>): Promise<void>;\n`;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// setCollectionRecord overloads
|
|
106
|
+
for (const [exportName, item] of Object.entries(versionSchema)) {
|
|
107
|
+
if (isRecordSchema(item) || isUnionSchema(item)) {
|
|
108
|
+
const readType = versionedTypeName(exportName, version);
|
|
109
|
+
output += ` setCollectionRecord(model: typeof ${modelName(exportName)}, id: RecordId, data: ${readType}): Promise<void>;\n`;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
output += `}\n\n`;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// Union type
|
|
116
|
+
if (supportedVersions.length === 1) {
|
|
117
|
+
output += `export type VersionedDocRef = VersionedDocRef_v${supportedVersions[0].version};\n`;
|
|
118
|
+
} else {
|
|
119
|
+
const unionMembers = supportedVersions.map(v => `VersionedDocRef_v${v.version}`).join(" | ");
|
|
120
|
+
output += `export type VersionedDocRef = ${unionMembers};\n`;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// asVersioned — identity cast to unlock version-specific write overloads
|
|
124
|
+
output += `\n/** Narrow a DocumentRef to a version-discriminated type for type-safe writes. */\n`;
|
|
125
|
+
output += `export function asVersioned(docRef: DocumentRef<DocumentModel>): VersionedDocRef {\n`;
|
|
126
|
+
output += ` return docRef as VersionedDocRef;\n`;
|
|
127
|
+
output += `}\n`;
|
|
128
|
+
|
|
129
|
+
// matchVersion — exhaustive version handler
|
|
130
|
+
const handlerProps = supportedVersions.map(v => ` readonly ${v.version}: (doc: VersionedDocRef_v${v.version}) => R;`).join("\n");
|
|
131
|
+
output += `\n/**\n`;
|
|
132
|
+
output += ` * Exhaustive version handler. TypeScript enforces that every supported\n`;
|
|
133
|
+
output += ` * version has a corresponding handler -- adding a new schema version\n`;
|
|
134
|
+
output += ` * produces a compile error at every call site until handled.\n`;
|
|
135
|
+
output += ` */\n`;
|
|
136
|
+
output += `export function matchVersion<R>(\n`;
|
|
137
|
+
output += ` doc: VersionedDocRef,\n`;
|
|
138
|
+
output += ` handlers: {\n`;
|
|
139
|
+
output += handlerProps + "\n";
|
|
140
|
+
output += ` },\n`;
|
|
141
|
+
output += `): R {\n`;
|
|
142
|
+
output += ` switch (doc.version) {\n`;
|
|
143
|
+
for (const {
|
|
144
|
+
version
|
|
145
|
+
} of supportedVersions) {
|
|
146
|
+
output += ` case ${version}:\n`;
|
|
147
|
+
output += ` return handlers[${version}](doc);\n`;
|
|
148
|
+
}
|
|
149
|
+
output += ` default:\n`;
|
|
150
|
+
output += ` throw new Error(\`Unexpected document version: \${(doc as any).version}\`);\n`;
|
|
151
|
+
output += ` }\n`;
|
|
152
|
+
output += `}\n`;
|
|
153
|
+
return output;
|
|
154
|
+
}
|
|
155
|
+
//# sourceMappingURL=generateScopeFromSchema.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"generateScopeFromSchema.js","names":["GENERATED_FILE_HEADER","resolveSchemaChain","isRecordSchema","isUnionSchema","modelName","MODELS_PATH","typesFilePath","versionedTypeName","versionedWriteTypeName","writeTypesFilePath","generateScopeFromSchema","schema","minSupportedVersion","chain","minVersion","supportedVersions","filter","v","version","latestSchema","length","allModelNames","exportName","item","Object","entries","push","output","modelImports","map","n","typeImportsFromModels","join","versionSchema","readTypeImports","writeTypeImports","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 type { SchemaDefinition } from \"@palantir/pack.schema\";\nimport { GENERATED_FILE_HEADER } from \"../generatedFileHeader.js\";\nimport { resolveSchemaChain } from \"./resolveSchemaChain.js\";\nimport {\n isRecordSchema,\n isUnionSchema,\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 generateScopeFromSchema(\n schema: SchemaDefinition,\n minSupportedVersion?: number,\n): string {\n const { chain, minVersion } = resolveSchemaChain(schema, 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 schema\n const latestSchema = chain[chain.length - 1]!.schema;\n const allModelNames: string[] = [];\n for (const [exportName, item] of Object.entries(latestSchema)) {\n if (isRecordSchema(item) || isUnionSchema(item)) {\n allModelNames.push(exportName);\n }\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, schema: versionSchema } of supportedVersions) {\n const readTypeImports: string[] = [];\n const writeTypeImports: string[] = [];\n\n for (const [exportName, item] of Object.entries(versionSchema)) {\n if (isRecordSchema(item)) {\n readTypeImports.push(versionedTypeName(exportName, version));\n writeTypeImports.push(versionedWriteTypeName(exportName, version));\n } else if (isUnionSchema(item)) {\n readTypeImports.push(versionedTypeName(exportName, 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 // 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 for (const { version, schema: versionSchema } 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 [exportName, item] of Object.entries(versionSchema)) {\n if (isRecordSchema(item)) {\n const writeType = versionedWriteTypeName(exportName, version);\n output += ` updateRecord(ref: RecordRef<typeof ${\n modelName(exportName)\n }>, data: ${writeType}): Promise<void>;\\n`;\n } else if (isUnionSchema(item)) {\n const readType = versionedTypeName(exportName, version);\n output += ` updateRecord(ref: RecordRef<typeof ${\n modelName(exportName)\n }>, data: Partial<${readType}>): Promise<void>;\\n`;\n }\n }\n\n // setCollectionRecord overloads\n for (const [exportName, item] of Object.entries(versionSchema)) {\n if (isRecordSchema(item) || isUnionSchema(item)) {\n const readType = versionedTypeName(exportName, version);\n output += ` setCollectionRecord(model: typeof ${\n modelName(exportName)\n }, id: RecordId, data: ${readType}): Promise<void>;\\n`;\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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AC,CAACc,IAAI,CAAC,KAAK,CAAC;IAC5FL,MAAM,IAAI,iCAAiCY,YAAY,KAAK;EAC9D;;EAEA;EACAZ,MAAM,IAAI,uFAAuF;EACjGA,MAAM,IAAI,sFAAsF;EAChGA,MAAM,IAAI,uCAAuC;EACjDA,MAAM,IAAI,KAAK;;EAEf;EACA,MAAMa,YAAY,GAAGzB,iBAAiB,CAACc,GAAG,CACxCZ,CAAC,IAAI,cAAcA,CAAC,CAACC,OAAO,4BAA4BD,CAAC,CAACC,OAAO,SACnE,CAAC,CAACc,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,IAAIa,YAAY,GAAG,IAAI;EAC7Bb,MAAM,IAAI,QAAQ;EAClBA,MAAM,IAAI,UAAU;EACpBA,MAAM,IAAI,4BAA4B;EACtC,KAAK,MAAM;IAAET;EAAQ,CAAC,IAAIH,iBAAiB,EAAE;IAC3CY,MAAM,IAAI,YAAYT,OAAO,KAAK;IAClCS,MAAM,IAAI,yBAAyBT,OAAO,WAAW;EACvD;EACAS,MAAM,IAAI,gBAAgB;EAC1BA,MAAM,IAAI,qFAAqF;EAC/FA,MAAM,IAAI,OAAO;EACjBA,MAAM,IAAI,KAAK;EAEf,OAAOA,MAAM;AACf","ignoreList":[]}
|
|
@@ -16,24 +16,7 @@
|
|
|
16
16
|
|
|
17
17
|
import { formatVariantName } from "../formatVariantName.js";
|
|
18
18
|
import { GENERATED_FILE_HEADER } from "../generatedFileHeader.js";
|
|
19
|
-
|
|
20
|
-
// Define schema types for internal use
|
|
21
|
-
const SchemaDefKind = {
|
|
22
|
-
RECORD: "record",
|
|
23
|
-
UNION: "union"
|
|
24
|
-
};
|
|
25
|
-
const TypeKind = {
|
|
26
|
-
ANY: "any",
|
|
27
|
-
ARRAY: "array",
|
|
28
|
-
DOC_REF: "docRef",
|
|
29
|
-
DOUBLE: "double",
|
|
30
|
-
MEDIA_REF: "mediaRef",
|
|
31
|
-
OBJECT_REF: "objectRef",
|
|
32
|
-
OPTIONAL: "optional",
|
|
33
|
-
REF: "ref",
|
|
34
|
-
STRING: "string",
|
|
35
|
-
USER_REF: "userRef"
|
|
36
|
-
};
|
|
19
|
+
import { SchemaDefKind, TypeKind } from "./runtimeSchema.js";
|
|
37
20
|
|
|
38
21
|
// Base type definition for schema fields
|
|
39
22
|
|
|
@@ -201,10 +184,10 @@ function convertTypeToTypeScript(fieldType, schema) {
|
|
|
201
184
|
case TypeKind.ANY:
|
|
202
185
|
return "any";
|
|
203
186
|
case TypeKind.ARRAY:
|
|
204
|
-
if (isArrayField(fieldType)) {
|
|
205
|
-
|
|
187
|
+
if (!isArrayField(fieldType)) {
|
|
188
|
+
throw new Error("Array field is missing items type");
|
|
206
189
|
}
|
|
207
|
-
return
|
|
190
|
+
return `readonly ${convertTypeToTypeScript(fieldType.items, schema)}[]`;
|
|
208
191
|
case TypeKind.DOC_REF:
|
|
209
192
|
return "DocumentRef";
|
|
210
193
|
case TypeKind.DOUBLE:
|
|
@@ -214,24 +197,27 @@ function convertTypeToTypeScript(fieldType, schema) {
|
|
|
214
197
|
case TypeKind.OBJECT_REF:
|
|
215
198
|
return "ObjectRef";
|
|
216
199
|
case TypeKind.OPTIONAL:
|
|
217
|
-
if (isOptionalField(fieldType)) {
|
|
218
|
-
|
|
200
|
+
if (!isOptionalField(fieldType)) {
|
|
201
|
+
throw new Error("Optional field is missing inner type");
|
|
219
202
|
}
|
|
220
|
-
return
|
|
203
|
+
return convertTypeToTypeScript(fieldType.item, schema);
|
|
221
204
|
case TypeKind.REF:
|
|
222
|
-
if (isRefField(fieldType)
|
|
205
|
+
if (!isRefField(fieldType)) {
|
|
206
|
+
throw new Error("Ref field is missing name or refType");
|
|
207
|
+
}
|
|
208
|
+
if (fieldType.refType === "record") {
|
|
223
209
|
const exportName = schema ? findRecordExportName(fieldType.name, schema) : null;
|
|
224
|
-
return exportName
|
|
225
|
-
} else if (isRefField(fieldType) && fieldType.refType === "union") {
|
|
226
|
-
return isRefField(fieldType) ? fieldType.name : "unknown";
|
|
210
|
+
return exportName ?? fieldType.name;
|
|
227
211
|
}
|
|
228
|
-
return
|
|
212
|
+
return fieldType.name;
|
|
229
213
|
case TypeKind.STRING:
|
|
230
214
|
return "string";
|
|
231
215
|
case TypeKind.USER_REF:
|
|
232
216
|
return "UserRef";
|
|
233
217
|
default:
|
|
234
|
-
|
|
218
|
+
{
|
|
219
|
+
throw new Error(`Unknown schema field type: ${fieldType.type}`);
|
|
220
|
+
}
|
|
235
221
|
}
|
|
236
222
|
}
|
|
237
223
|
//# sourceMappingURL=generateTypesFromSchema.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generateTypesFromSchema.js","names":["formatVariantName","GENERATED_FILE_HEADER","SchemaDefKind","RECORD","UNION","TypeKind","ANY","ARRAY","DOC_REF","DOUBLE","MEDIA_REF","OBJECT_REF","OPTIONAL","REF","STRING","USER_REF","isRecordSchema","item","type","isUnionSchema","isRefField","field","isArrayField","isOptionalField","detectUsedRefTypes","schema","refTypes","Set","scanField","items","add","Object","values","fields","variant","variants","generateTypesFromSchema","runtimeSchema","usedRefTypes","output","size","refTypesList","Array","from","sort","join","exportName","entries","generateRecordInterface","unionEntries","filter","_","forEach","i","unionOutput","generateUnionType","length","record","docs","fieldName","fieldType","tsType","convertTypeToTypeScript","optional","union","variantInterfaces","discriminantField","discriminant","variantName","variantType","interfaceName","push","name","discriminatorValue","refType","recordName","findRecordExportName","map","v"],"sources":["generateTypesFromSchema.ts"],"sourcesContent":["/*\n * Copyright 2025 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 { ReturnedSchema, Schema } from \"@palantir/pack.schema\";\nimport { formatVariantName } from \"../formatVariantName.js\";\nimport { GENERATED_FILE_HEADER } from \"../generatedFileHeader.js\";\n\n// Define schema types for internal use\nconst SchemaDefKind = {\n RECORD: \"record\",\n UNION: \"union\",\n} as const;\n\nconst TypeKind = {\n ANY: \"any\",\n ARRAY: \"array\",\n DOC_REF: \"docRef\",\n DOUBLE: \"double\",\n MEDIA_REF: \"mediaRef\",\n OBJECT_REF: \"objectRef\",\n OPTIONAL: \"optional\",\n REF: \"ref\",\n STRING: \"string\",\n USER_REF: \"userRef\",\n} as const;\n\n// Base type definition for schema fields\ninterface BaseSchemaField {\n readonly type: string;\n}\n\ninterface AnyField extends BaseSchemaField {\n readonly type: typeof TypeKind.ANY;\n}\n\ninterface ArrayField extends BaseSchemaField {\n readonly type: typeof TypeKind.ARRAY;\n readonly items: SchemaField;\n}\n\ninterface DocRefField extends BaseSchemaField {\n readonly type: typeof TypeKind.DOC_REF;\n}\n\ninterface DoubleField extends BaseSchemaField {\n readonly type: typeof TypeKind.DOUBLE;\n}\n\ninterface MediaRefField extends BaseSchemaField {\n readonly type: typeof TypeKind.MEDIA_REF;\n}\n\ninterface ObjectRefField extends BaseSchemaField {\n readonly type: typeof TypeKind.OBJECT_REF;\n}\n\ninterface OptionalField extends BaseSchemaField {\n readonly type: typeof TypeKind.OPTIONAL;\n readonly item: SchemaField;\n}\n\ninterface RefField extends BaseSchemaField {\n readonly type: typeof TypeKind.REF;\n readonly refType: \"record\" | \"union\";\n readonly name: string;\n}\n\ninterface StringField extends BaseSchemaField {\n readonly type: typeof TypeKind.STRING;\n}\n\ninterface UserRefField extends BaseSchemaField {\n readonly type: typeof TypeKind.USER_REF;\n}\n\ntype SchemaField =\n | AnyField\n | ArrayField\n | DocRefField\n | DoubleField\n | MediaRefField\n | ObjectRefField\n | OptionalField\n | RefField\n | StringField\n | UserRefField;\n\ninterface RuntimeSchemaRecord {\n readonly type: typeof SchemaDefKind.RECORD;\n readonly name: string;\n readonly docs?: string;\n readonly fields: Readonly<Record<string, SchemaField>>;\n readonly ref?: RefField & {\n readonly refType: \"record\";\n };\n}\n\ninterface RuntimeSchemaUnion {\n readonly type: typeof SchemaDefKind.UNION;\n readonly name?: string;\n readonly variants: Readonly<Record<string, SchemaField>>;\n readonly discriminant: string;\n readonly ref?: RefField & {\n readonly refType: \"union\";\n };\n}\n\ntype RuntimeSchemaItem = RuntimeSchemaRecord | RuntimeSchemaUnion;\ntype RuntimeSchema = Record<string, RuntimeSchemaItem>;\n\n// Type guards\nfunction isRecordSchema(item: RuntimeSchemaItem): item is RuntimeSchemaRecord {\n return item.type === SchemaDefKind.RECORD && \"name\" in item && \"fields\" in item;\n}\n\nfunction isUnionSchema(item: RuntimeSchemaItem): item is RuntimeSchemaUnion {\n return item.type === SchemaDefKind.UNION && \"variants\" in item && \"discriminant\" in item;\n}\n\nfunction isRefField(field: SchemaField): field is RefField {\n return field.type === TypeKind.REF && \"refType\" in field && \"name\" in field;\n}\n\nfunction isArrayField(field: SchemaField): field is ArrayField {\n return field.type === TypeKind.ARRAY && \"items\" in field;\n}\n\nfunction isOptionalField(field: SchemaField): field is OptionalField {\n return field.type === TypeKind.OPTIONAL && \"item\" in field;\n}\n\nfunction detectUsedRefTypes(schema: RuntimeSchema): Set<string> {\n const refTypes = new Set<string>();\n\n function scanField(field: SchemaField): void {\n switch (field.type) {\n case TypeKind.ARRAY:\n if (isArrayField(field)) {\n scanField(field.items);\n }\n break;\n case TypeKind.DOC_REF:\n refTypes.add(\"DocumentRef\");\n break;\n case TypeKind.MEDIA_REF:\n refTypes.add(\"MediaRef\");\n break;\n case TypeKind.OBJECT_REF:\n refTypes.add(\"ObjectRef\");\n break;\n case TypeKind.OPTIONAL:\n if (isOptionalField(field)) {\n scanField(field.item);\n }\n break;\n case TypeKind.USER_REF:\n refTypes.add(\"UserRef\");\n break;\n }\n }\n\n for (const item of Object.values(schema)) {\n if (isRecordSchema(item)) {\n for (const field of Object.values(item.fields)) {\n scanField(field);\n }\n } else if (isUnionSchema(item)) {\n for (const variant of Object.values(item.variants)) {\n scanField(variant);\n }\n }\n }\n\n return refTypes;\n}\n\nexport function generateTypesFromSchema<T extends ReturnedSchema>(\n schema: Schema<T>,\n): string {\n const runtimeSchema = schema as unknown as RuntimeSchema;\n\n // Detect which ref types are used in the schema\n const usedRefTypes = detectUsedRefTypes(runtimeSchema);\n\n let output = GENERATED_FILE_HEADER;\n\n // Add conditional imports based on which ref types are used\n if (usedRefTypes.size > 0) {\n const refTypesList = Array.from(usedRefTypes).sort().join(\", \");\n output +=\n `import type { ${refTypesList} } from \"@palantir/pack.document-schema.model-types\";\\n`;\n }\n\n output += \"\\n\";\n\n // First pass: generate record interfaces\n for (const [exportName, item] of Object.entries(runtimeSchema)) {\n if (item.type === SchemaDefKind.RECORD && isRecordSchema(item)) {\n output += generateRecordInterface(item, exportName, runtimeSchema);\n output += \"\\n\";\n }\n }\n\n // Second pass: generate union types\n const unionEntries = Object.entries(runtimeSchema).filter(\n ([_, item]) => item.type === SchemaDefKind.UNION && isUnionSchema(item),\n );\n\n unionEntries.forEach(([exportName, item], i) => {\n if (isUnionSchema(item)) {\n const unionOutput = generateUnionType(item, exportName, runtimeSchema);\n if (unionOutput) {\n output += unionOutput;\n // Only add newline if not the last union\n if (i < unionEntries.length - 1) {\n output += \"\\n\";\n }\n }\n }\n });\n\n return output;\n}\n\nfunction generateRecordInterface(\n record: RuntimeSchemaRecord,\n exportName: string,\n schema: RuntimeSchema,\n): string {\n let output = \"\";\n\n if (record.docs) {\n output += `/**\\n * ${record.docs}\\n */\\n`;\n }\n\n output += `export interface ${exportName} {\\n`;\n\n for (const [fieldName, fieldType] of Object.entries(record.fields)) {\n const tsType = convertTypeToTypeScript(fieldType, schema);\n const optional = fieldType.type === TypeKind.OPTIONAL ? \"?\" : \"\";\n output += ` readonly ${fieldName}${optional}: ${tsType};\\n`;\n }\n\n output += \"}\\n\";\n\n return output;\n}\n\nfunction generateUnionType(\n union: RuntimeSchemaUnion,\n exportName: string,\n schema: RuntimeSchema,\n): string {\n let output = \"\";\n const variantInterfaces: Array<{ name: string; discriminatorValue: string }> = [];\n const discriminantField = union.discriminant;\n\n // First pass: generate variant interfaces\n for (const [variantName, variantType] of Object.entries(union.variants)) {\n const interfaceName = `${exportName}${formatVariantName(variantName)}`;\n variantInterfaces.push({ name: interfaceName, discriminatorValue: variantName });\n\n if (variantType.type === TypeKind.REF && variantType.refType === \"record\") {\n // Find the corresponding record name in the schema\n const recordName = findRecordExportName(variantType.name, schema);\n if (recordName) {\n output += `export interface ${interfaceName} extends ${recordName} {\\n`;\n output += ` readonly ${discriminantField}: \"${variantName}\";\\n`;\n output += \"}\\n\\n\";\n }\n } else {\n // Handle value types\n const tsType = convertTypeToTypeScript(variantType, schema);\n output += `export interface ${interfaceName} {\\n`;\n output += ` readonly ${discriminantField}: \"${variantName}\";\\n`;\n output += ` readonly value: ${tsType};\\n`;\n output += \"}\\n\\n\";\n }\n }\n\n // Second pass: generate the union type\n output += `export type ${exportName} = ${variantInterfaces.map(v => v.name).join(\" | \")};\\n\\n`;\n\n // Third pass: generate type guards\n for (let i = 0; i < variantInterfaces.length; i++) {\n const variant = variantInterfaces[i]!;\n output +=\n `export function is${variant.name}(value: ${exportName}): value is ${variant.name} {\\n`;\n output += ` return value.${discriminantField} === \"${variant.discriminatorValue}\";\\n`;\n output += \"}\\n\\n\";\n }\n\n return output;\n}\n\nfunction findRecordExportName(\n recordName: string,\n schema: RuntimeSchema,\n): string | null {\n for (const [exportName, item] of Object.entries(schema)) {\n if (isRecordSchema(item) && item.name === recordName) {\n return exportName;\n }\n }\n return null;\n}\n\nfunction convertTypeToTypeScript(\n fieldType: SchemaField,\n schema?: RuntimeSchema,\n): string {\n switch (fieldType.type) {\n case TypeKind.ANY:\n return \"any\";\n case TypeKind.ARRAY:\n if (isArrayField(fieldType)) {\n return `readonly ${convertTypeToTypeScript(fieldType.items, schema)}[]`;\n }\n return \"readonly unknown[]\";\n case TypeKind.DOC_REF:\n return \"DocumentRef\";\n case TypeKind.DOUBLE:\n return \"number\";\n case TypeKind.MEDIA_REF:\n return \"MediaRef\";\n case TypeKind.OBJECT_REF:\n return \"ObjectRef\";\n case TypeKind.OPTIONAL:\n if (isOptionalField(fieldType)) {\n return convertTypeToTypeScript(fieldType.item, schema);\n }\n return \"unknown\";\n case TypeKind.REF:\n if (isRefField(fieldType) && fieldType.refType === \"record\") {\n const exportName = schema ? findRecordExportName(fieldType.name, schema) : null;\n return exportName || (isRefField(fieldType) ? fieldType.name : \"unknown\");\n } else if (isRefField(fieldType) && fieldType.refType === \"union\") {\n return isRefField(fieldType) ? fieldType.name : \"unknown\";\n }\n return \"unknown\";\n case TypeKind.STRING:\n return \"string\";\n case TypeKind.USER_REF:\n return \"UserRef\";\n default:\n fieldType satisfies never;\n return \"unknown\";\n }\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;;AAEjE;AACA,MAAMC,aAAa,GAAG;EACpBC,MAAM,EAAE,QAAQ;EAChBC,KAAK,EAAE;AACT,CAAU;AAEV,MAAMC,QAAQ,GAAG;EACfC,GAAG,EAAE,KAAK;EACVC,KAAK,EAAE,OAAO;EACdC,OAAO,EAAE,QAAQ;EACjBC,MAAM,EAAE,QAAQ;EAChBC,SAAS,EAAE,UAAU;EACrBC,UAAU,EAAE,WAAW;EACvBC,QAAQ,EAAE,UAAU;EACpBC,GAAG,EAAE,K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EE,OAAO,SAAS;EACpB;AACF","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"generateTypesFromSchema.js","names":["formatVariantName","GENERATED_FILE_HEADER","SchemaDefKind","TypeKind","isRecordSchema","item","type","RECORD","isUnionSchema","UNION","isRefField","field","REF","isArrayField","ARRAY","isOptionalField","OPTIONAL","detectUsedRefTypes","schema","refTypes","Set","scanField","items","DOC_REF","add","MEDIA_REF","OBJECT_REF","USER_REF","Object","values","fields","variant","variants","generateTypesFromSchema","runtimeSchema","usedRefTypes","output","size","refTypesList","Array","from","sort","join","exportName","entries","generateRecordInterface","unionEntries","filter","_","forEach","i","unionOutput","generateUnionType","length","record","docs","fieldName","fieldType","tsType","convertTypeToTypeScript","optional","union","variantInterfaces","discriminantField","discriminant","variantName","variantType","interfaceName","push","name","discriminatorValue","refType","recordName","findRecordExportName","map","v","ANY","Error","DOUBLE","STRING"],"sources":["generateTypesFromSchema.ts"],"sourcesContent":["/*\n * Copyright 2025 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 { ReturnedSchema, Schema } from \"@palantir/pack.schema\";\nimport { formatVariantName } from \"../formatVariantName.js\";\nimport { GENERATED_FILE_HEADER } from \"../generatedFileHeader.js\";\nimport { SchemaDefKind, TypeKind } from \"./runtimeSchema.js\";\n\n// Base type definition for schema fields\ninterface BaseSchemaField {\n readonly type: string;\n}\n\ninterface AnyField extends BaseSchemaField {\n readonly type: typeof TypeKind.ANY;\n}\n\ninterface ArrayField extends BaseSchemaField {\n readonly type: typeof TypeKind.ARRAY;\n readonly items: SchemaField;\n}\n\ninterface DocRefField extends BaseSchemaField {\n readonly type: typeof TypeKind.DOC_REF;\n}\n\ninterface DoubleField extends BaseSchemaField {\n readonly type: typeof TypeKind.DOUBLE;\n}\n\ninterface MediaRefField extends BaseSchemaField {\n readonly type: typeof TypeKind.MEDIA_REF;\n}\n\ninterface ObjectRefField extends BaseSchemaField {\n readonly type: typeof TypeKind.OBJECT_REF;\n}\n\ninterface OptionalField extends BaseSchemaField {\n readonly type: typeof TypeKind.OPTIONAL;\n readonly item: SchemaField;\n}\n\ninterface RefField extends BaseSchemaField {\n readonly type: typeof TypeKind.REF;\n readonly refType: \"record\" | \"union\";\n readonly name: string;\n}\n\ninterface StringField extends BaseSchemaField {\n readonly type: typeof TypeKind.STRING;\n}\n\ninterface UserRefField extends BaseSchemaField {\n readonly type: typeof TypeKind.USER_REF;\n}\n\ntype SchemaField =\n | AnyField\n | ArrayField\n | DocRefField\n | DoubleField\n | MediaRefField\n | ObjectRefField\n | OptionalField\n | RefField\n | StringField\n | UserRefField;\n\ninterface RuntimeSchemaRecord {\n readonly type: typeof SchemaDefKind.RECORD;\n readonly name: string;\n readonly docs?: string;\n readonly fields: Readonly<Record<string, SchemaField>>;\n readonly ref?: RefField & {\n readonly refType: \"record\";\n };\n}\n\ninterface RuntimeSchemaUnion {\n readonly type: typeof SchemaDefKind.UNION;\n readonly name?: string;\n readonly variants: Readonly<Record<string, SchemaField>>;\n readonly discriminant: string;\n readonly ref?: RefField & {\n readonly refType: \"union\";\n };\n}\n\ntype RuntimeSchemaItem = RuntimeSchemaRecord | RuntimeSchemaUnion;\ntype RuntimeSchema = Record<string, RuntimeSchemaItem>;\n\n// Type guards\nfunction isRecordSchema(item: RuntimeSchemaItem): item is RuntimeSchemaRecord {\n return item.type === SchemaDefKind.RECORD && \"name\" in item && \"fields\" in item;\n}\n\nfunction isUnionSchema(item: RuntimeSchemaItem): item is RuntimeSchemaUnion {\n return item.type === SchemaDefKind.UNION && \"variants\" in item && \"discriminant\" in item;\n}\n\nfunction isRefField(field: SchemaField): field is RefField {\n return field.type === TypeKind.REF && \"refType\" in field && \"name\" in field;\n}\n\nfunction isArrayField(field: SchemaField): field is ArrayField {\n return field.type === TypeKind.ARRAY && \"items\" in field;\n}\n\nfunction isOptionalField(field: SchemaField): field is OptionalField {\n return field.type === TypeKind.OPTIONAL && \"item\" in field;\n}\n\nfunction detectUsedRefTypes(schema: RuntimeSchema): Set<string> {\n const refTypes = new Set<string>();\n\n function scanField(field: SchemaField): void {\n switch (field.type) {\n case TypeKind.ARRAY:\n if (isArrayField(field)) {\n scanField(field.items);\n }\n break;\n case TypeKind.DOC_REF:\n refTypes.add(\"DocumentRef\");\n break;\n case TypeKind.MEDIA_REF:\n refTypes.add(\"MediaRef\");\n break;\n case TypeKind.OBJECT_REF:\n refTypes.add(\"ObjectRef\");\n break;\n case TypeKind.OPTIONAL:\n if (isOptionalField(field)) {\n scanField(field.item);\n }\n break;\n case TypeKind.USER_REF:\n refTypes.add(\"UserRef\");\n break;\n }\n }\n\n for (const item of Object.values(schema)) {\n if (isRecordSchema(item)) {\n for (const field of Object.values(item.fields)) {\n scanField(field);\n }\n } else if (isUnionSchema(item)) {\n for (const variant of Object.values(item.variants)) {\n scanField(variant);\n }\n }\n }\n\n return refTypes;\n}\n\nexport function generateTypesFromSchema<T extends ReturnedSchema>(\n schema: Schema<T>,\n): string {\n const runtimeSchema = schema as unknown as RuntimeSchema;\n\n // Detect which ref types are used in the schema\n const usedRefTypes = detectUsedRefTypes(runtimeSchema);\n\n let output = GENERATED_FILE_HEADER;\n\n // Add conditional imports based on which ref types are used\n if (usedRefTypes.size > 0) {\n const refTypesList = Array.from(usedRefTypes).sort().join(\", \");\n output +=\n `import type { ${refTypesList} } from \"@palantir/pack.document-schema.model-types\";\\n`;\n }\n\n output += \"\\n\";\n\n // First pass: generate record interfaces\n for (const [exportName, item] of Object.entries(runtimeSchema)) {\n if (item.type === SchemaDefKind.RECORD && isRecordSchema(item)) {\n output += generateRecordInterface(item, exportName, runtimeSchema);\n output += \"\\n\";\n }\n }\n\n // Second pass: generate union types\n const unionEntries = Object.entries(runtimeSchema).filter(\n ([_, item]) => item.type === SchemaDefKind.UNION && isUnionSchema(item),\n );\n\n unionEntries.forEach(([exportName, item], i) => {\n if (isUnionSchema(item)) {\n const unionOutput = generateUnionType(item, exportName, runtimeSchema);\n if (unionOutput) {\n output += unionOutput;\n // Only add newline if not the last union\n if (i < unionEntries.length - 1) {\n output += \"\\n\";\n }\n }\n }\n });\n\n return output;\n}\n\nfunction generateRecordInterface(\n record: RuntimeSchemaRecord,\n exportName: string,\n schema: RuntimeSchema,\n): string {\n let output = \"\";\n\n if (record.docs) {\n output += `/**\\n * ${record.docs}\\n */\\n`;\n }\n\n output += `export interface ${exportName} {\\n`;\n\n for (const [fieldName, fieldType] of Object.entries(record.fields)) {\n const tsType = convertTypeToTypeScript(fieldType, schema);\n const optional = fieldType.type === TypeKind.OPTIONAL ? \"?\" : \"\";\n output += ` readonly ${fieldName}${optional}: ${tsType};\\n`;\n }\n\n output += \"}\\n\";\n\n return output;\n}\n\nfunction generateUnionType(\n union: RuntimeSchemaUnion,\n exportName: string,\n schema: RuntimeSchema,\n): string {\n let output = \"\";\n const variantInterfaces: Array<{ name: string; discriminatorValue: string }> = [];\n const discriminantField = union.discriminant;\n\n // First pass: generate variant interfaces\n for (const [variantName, variantType] of Object.entries(union.variants)) {\n const interfaceName = `${exportName}${formatVariantName(variantName)}`;\n variantInterfaces.push({ name: interfaceName, discriminatorValue: variantName });\n\n if (variantType.type === TypeKind.REF && variantType.refType === \"record\") {\n // Find the corresponding record name in the schema\n const recordName = findRecordExportName(variantType.name, schema);\n if (recordName) {\n output += `export interface ${interfaceName} extends ${recordName} {\\n`;\n output += ` readonly ${discriminantField}: \"${variantName}\";\\n`;\n output += \"}\\n\\n\";\n }\n } else {\n // Handle value types\n const tsType = convertTypeToTypeScript(variantType, schema);\n output += `export interface ${interfaceName} {\\n`;\n output += ` readonly ${discriminantField}: \"${variantName}\";\\n`;\n output += ` readonly value: ${tsType};\\n`;\n output += \"}\\n\\n\";\n }\n }\n\n // Second pass: generate the union type\n output += `export type ${exportName} = ${variantInterfaces.map(v => v.name).join(\" | \")};\\n\\n`;\n\n // Third pass: generate type guards\n for (let i = 0; i < variantInterfaces.length; i++) {\n const variant = variantInterfaces[i]!;\n output +=\n `export function is${variant.name}(value: ${exportName}): value is ${variant.name} {\\n`;\n output += ` return value.${discriminantField} === \"${variant.discriminatorValue}\";\\n`;\n output += \"}\\n\\n\";\n }\n\n return output;\n}\n\nfunction findRecordExportName(\n recordName: string,\n schema: RuntimeSchema,\n): string | null {\n for (const [exportName, item] of Object.entries(schema)) {\n if (isRecordSchema(item) && item.name === recordName) {\n return exportName;\n }\n }\n return null;\n}\n\nfunction convertTypeToTypeScript(\n fieldType: SchemaField,\n schema?: RuntimeSchema,\n): string {\n switch (fieldType.type) {\n case TypeKind.ANY:\n return \"any\";\n case TypeKind.ARRAY:\n if (!isArrayField(fieldType)) {\n throw new Error(\"Array field is missing items type\");\n }\n return `readonly ${convertTypeToTypeScript(fieldType.items, schema)}[]`;\n case TypeKind.DOC_REF:\n return \"DocumentRef\";\n case TypeKind.DOUBLE:\n return \"number\";\n case TypeKind.MEDIA_REF:\n return \"MediaRef\";\n case TypeKind.OBJECT_REF:\n return \"ObjectRef\";\n case TypeKind.OPTIONAL:\n if (!isOptionalField(fieldType)) {\n throw new Error(\"Optional field is missing inner type\");\n }\n return convertTypeToTypeScript(fieldType.item, schema);\n case TypeKind.REF:\n if (!isRefField(fieldType)) {\n throw new Error(\"Ref field is missing name or refType\");\n }\n if (fieldType.refType === \"record\") {\n const exportName = schema ? findRecordExportName(fieldType.name, schema) : null;\n return exportName ?? fieldType.name;\n }\n return fieldType.name;\n case TypeKind.STRING:\n return \"string\";\n case TypeKind.USER_REF:\n return \"UserRef\";\n default: {\n const _exhaustive: never = fieldType;\n throw new Error(`Unknown schema field type: ${(_exhaustive as SchemaField).type}`);\n }\n }\n}\n"],"mappings":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