@osdk/seed-compiler 0.11.0 → 0.12.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/CHANGELOG.md +11 -0
- package/README.md +52 -37
- package/build/browser/cli/main.js +3 -5
- package/build/browser/cli/main.js.map +1 -1
- package/build/browser/compileSeedData.js +42 -259
- package/build/browser/compileSeedData.js.map +1 -1
- package/build/browser/index.js +1 -2
- package/build/browser/index.js.map +1 -1
- package/build/cjs/index.cjs +33 -185
- package/build/cjs/index.cjs.map +1 -1
- package/build/cjs/index.d.cts +8 -82
- package/build/esm/cli/main.js +3 -5
- package/build/esm/cli/main.js.map +1 -1
- package/build/esm/compileSeedData.js +42 -259
- package/build/esm/compileSeedData.js.map +1 -1
- package/build/esm/index.js +1 -2
- package/build/esm/index.js.map +1 -1
- package/build/types/cli/main.d.ts.map +1 -1
- package/build/types/compileSeedData.d.ts +8 -58
- package/build/types/compileSeedData.d.ts.map +1 -1
- package/build/types/index.d.ts +1 -3
- package/build/types/index.d.ts.map +1 -1
- package/package.json +8 -2
- package/build/browser/schema.js +0 -51
- package/build/browser/schema.js.map +0 -1
- package/build/esm/schema.js +0 -51
- package/build/esm/schema.js.map +0 -1
- package/build/types/schema.d.ts +0 -24
- package/build/types/schema.d.ts.map +0 -1
|
@@ -16,109 +16,35 @@
|
|
|
16
16
|
|
|
17
17
|
import * as fs from "node:fs";
|
|
18
18
|
import * as path from "node:path";
|
|
19
|
+
import { SeedBuilder } from "@osdk/seed-helpers";
|
|
19
20
|
import { consola } from "consola";
|
|
20
21
|
import { createJiti } from "jiti";
|
|
21
22
|
|
|
22
23
|
/**
|
|
23
|
-
*
|
|
24
|
-
* match the wire format regex). Format failures are collected across the
|
|
25
|
-
* whole output and reported together at the end so users can fix many
|
|
26
|
-
* content mistakes in one pass. Structural failures (unknown object type,
|
|
27
|
-
* unknown property name, null value, wrong JS type) throw immediately
|
|
28
|
-
* instead — they're not aggregated, so they don't need this struct.
|
|
29
|
-
*/
|
|
30
|
-
|
|
31
|
-
/**
|
|
32
|
-
* Expected runtime JS type for each cataloged wire type.
|
|
33
|
-
*
|
|
34
|
-
* Used to fail fast on `as any` callers that pass a value of the wrong shape
|
|
35
|
-
* (e.g., `age: "30"` when `age` is an integer). Wire types not listed here
|
|
36
|
-
* are not strictly typed by this validator — currently `attachment`,
|
|
37
|
-
* `mediaReference`, `geopoint`, `geoshape`, `vector`, `array`, `struct`,
|
|
38
|
-
* which have non-primitive runtime shapes that need bespoke validation.
|
|
39
|
-
*/
|
|
40
|
-
const EXPECTED_JS_TYPE = {
|
|
41
|
-
// string-encoded primitives
|
|
42
|
-
string: "string",
|
|
43
|
-
marking: "string",
|
|
44
|
-
timestamp: "string",
|
|
45
|
-
date: "string",
|
|
46
|
-
datetime: "string",
|
|
47
|
-
long: "string",
|
|
48
|
-
decimal: "string",
|
|
49
|
-
ipAddress: "string",
|
|
50
|
-
cipherText: "string",
|
|
51
|
-
// numeric primitives
|
|
52
|
-
integer: "number",
|
|
53
|
-
byte: "number",
|
|
54
|
-
short: "number",
|
|
55
|
-
double: "number",
|
|
56
|
-
float: "number",
|
|
57
|
-
// boolean
|
|
58
|
-
boolean: "boolean"
|
|
59
|
-
};
|
|
60
|
-
|
|
61
|
-
/**
|
|
62
|
-
* Regex patterns for string-encoded wire types that TypeScript cannot validate.
|
|
24
|
+
* Merges one or more seed data files into a single JSON output.
|
|
63
25
|
*
|
|
64
|
-
*
|
|
65
|
-
* - timestamp: RFC 3339 parse on the Rust side — requires timezone, rejects trailing garbage
|
|
66
|
-
* - date: stored as raw string, but only YYYY-MM-DD works in SQLite queries
|
|
67
|
-
* - datetime: stored as raw string, same YYYY-MM-DD requirement for query correctness
|
|
68
|
-
* - long: strict decimal integer parse on the Rust side — no scientific notation
|
|
69
|
-
* - decimal: Rust stores any string (no validation), but we enforce numeric format
|
|
70
|
-
* to prevent obviously invalid values from silently passing through
|
|
71
|
-
*/
|
|
72
|
-
const WIRE_TYPE_FORMAT = {
|
|
73
|
-
timestamp: {
|
|
74
|
-
pattern: /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/u,
|
|
75
|
-
example: "2025-01-01T00:00:00Z"
|
|
76
|
-
},
|
|
77
|
-
date: {
|
|
78
|
-
pattern: /^\d{4}-\d{2}-\d{2}$/u,
|
|
79
|
-
example: "2025-01-01"
|
|
80
|
-
},
|
|
81
|
-
datetime: {
|
|
82
|
-
pattern: /^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})?)?$/u,
|
|
83
|
-
example: "2025-01-01T12:00:00Z"
|
|
84
|
-
},
|
|
85
|
-
long: {
|
|
86
|
-
// Strict decimal integer — matches Rust's str::parse::<i64>().
|
|
87
|
-
// No scientific notation, no decimal point, no whitespace.
|
|
88
|
-
pattern: /^-?\d+$/u,
|
|
89
|
-
example: "9007199254740993"
|
|
90
|
-
},
|
|
91
|
-
decimal: {
|
|
92
|
-
// Numeric string with optional decimal point. Anchored.
|
|
93
|
-
// Rust stores any string (no validation), but we reject obviously invalid values.
|
|
94
|
-
pattern: /^-?\d+(\.\d+)?$/u,
|
|
95
|
-
example: "123.45"
|
|
96
|
-
}
|
|
97
|
-
};
|
|
98
|
-
|
|
99
|
-
/**
|
|
100
|
-
* Compiles one or more seed data files into a single merged JSON output.
|
|
101
|
-
*
|
|
102
|
-
* Pipeline: load each file → merge → validate against schema → write JSON.
|
|
26
|
+
* Pipeline: load each file -> feed into one {@link SeedBuilder} -> write JSON.
|
|
103
27
|
*
|
|
104
28
|
* @param seedFiles - Absolute paths to seed `.mts` / `.ts` files.
|
|
105
29
|
* @param outputPath - Where to write the merged seed JSON.
|
|
106
|
-
* @param
|
|
107
|
-
*
|
|
108
|
-
* @throws if any seed file fails to compile or has an invalid export,
|
|
109
|
-
*
|
|
110
|
-
* primary key is duplicated across files, if any property value is
|
|
111
|
-
* null/undefined or has the wrong JS type, or if any string-encoded
|
|
112
|
-
* value has an invalid format.
|
|
30
|
+
* @param metadata - Ontology metadata, typically parsed from the
|
|
31
|
+
* `ontology-metadata.json` written by the SDK generator.
|
|
32
|
+
* @throws if any seed file fails to compile or has an invalid default export,
|
|
33
|
+
* or if the builder rejects any object or link it is given.
|
|
113
34
|
*/
|
|
114
|
-
export async function compileSeedData(seedFiles, outputPath,
|
|
35
|
+
export async function compileSeedData(seedFiles, outputPath, metadata) {
|
|
115
36
|
consola.info(`Compiling seed data from ${seedFiles.length} file(s)...`);
|
|
116
|
-
const
|
|
37
|
+
const builder = new SeedBuilder(metadata);
|
|
117
38
|
for (const seedFile of seedFiles) {
|
|
118
|
-
|
|
39
|
+
const output = await loadSeedFile(seedFile);
|
|
40
|
+
try {
|
|
41
|
+
builder.addAll(output);
|
|
42
|
+
} catch (e) {
|
|
43
|
+
const message = e instanceof Error ? e.message : String(e);
|
|
44
|
+
throw new Error(`Seed file '${path.basename(seedFile)}': ${message}`);
|
|
45
|
+
}
|
|
119
46
|
}
|
|
120
|
-
const merged =
|
|
121
|
-
validateSeedOutput(merged, schema);
|
|
47
|
+
const merged = builder.build();
|
|
122
48
|
const totalObjects = Object.values(merged.objects).reduce((sum, arr) => sum + arr.length, 0);
|
|
123
49
|
const outputDir = path.dirname(outputPath);
|
|
124
50
|
await fs.promises.mkdir(outputDir, {
|
|
@@ -127,172 +53,23 @@ export async function compileSeedData(seedFiles, outputPath, schema) {
|
|
|
127
53
|
await fs.promises.writeFile(outputPath, JSON.stringify(merged, null, 2));
|
|
128
54
|
consola.success(`Seed data compiled successfully (${totalObjects} objects, ${merged.links.length} links)`);
|
|
129
55
|
}
|
|
56
|
+
const isRecord = value => typeof value === "object" && value != null && !Array.isArray(value);
|
|
57
|
+
const isSeedOutput = value => isRecord(value) && isRecord(value.objects);
|
|
58
|
+
const isSeedResult = value => isRecord(value) && isSeedOutput(value.output);
|
|
130
59
|
|
|
131
60
|
/**
|
|
132
|
-
*
|
|
133
|
-
*
|
|
134
|
-
* - Objects for the same type combine additively.
|
|
135
|
-
* - Duplicate primary keys across files cause an error (checked by the actual
|
|
136
|
-
* PK field from the schema, not by comparing the full serialized object).
|
|
137
|
-
* - Duplicate links (same source, target, and link type) are deduplicated
|
|
138
|
-
* with a warning logged to the console.
|
|
139
|
-
*
|
|
140
|
-
* @param outputs - The individual seed outputs to merge.
|
|
141
|
-
* @param schemaMap - Used to resolve the primary key field name per object type.
|
|
142
|
-
* @returns A single merged SeedOutput ready for validation and writing.
|
|
143
|
-
* @throws if any primary key appears in more than one file for the same type.
|
|
144
|
-
*/
|
|
145
|
-
export function mergeSeedOutputs(outputs, schemaMap) {
|
|
146
|
-
const merged = {
|
|
147
|
-
objects: {},
|
|
148
|
-
links: []
|
|
149
|
-
};
|
|
150
|
-
const seenPks = new Map();
|
|
151
|
-
const seenLinks = new Set();
|
|
152
|
-
for (const output of outputs) {
|
|
153
|
-
mergeObjectsInto(merged, output.objects, schemaMap, seenPks);
|
|
154
|
-
mergeLinksInto(merged, output.links, seenLinks);
|
|
155
|
-
}
|
|
156
|
-
return merged;
|
|
157
|
-
}
|
|
158
|
-
function mergeObjectsInto(merged, source, schemaMap, seenPks) {
|
|
159
|
-
for (const [apiName, objects] of Object.entries(source)) {
|
|
160
|
-
const schema = schemaMap.get(apiName);
|
|
161
|
-
if (!schema) {
|
|
162
|
-
throw new Error(`Object type '${apiName}' in seed data is not defined in the ontology`);
|
|
163
|
-
}
|
|
164
|
-
const bucket = merged.objects[apiName] ??= [];
|
|
165
|
-
const pkSet = getOrInit(seenPks, apiName, () => new Set());
|
|
166
|
-
for (const obj of objects) {
|
|
167
|
-
const pk = String(obj[schema.primaryKeyApiName] ?? "");
|
|
168
|
-
if (pkSet.has(pk)) {
|
|
169
|
-
throw new Error(`Duplicate primary key '${pk}' for '${apiName}' across seed files`);
|
|
170
|
-
}
|
|
171
|
-
pkSet.add(pk);
|
|
172
|
-
bucket.push(obj);
|
|
173
|
-
}
|
|
174
|
-
}
|
|
175
|
-
}
|
|
176
|
-
function mergeLinksInto(merged, source, seenLinks) {
|
|
177
|
-
for (const link of source) {
|
|
178
|
-
const key = linkKey(link);
|
|
179
|
-
if (seenLinks.has(key)) {
|
|
180
|
-
consola.warn(`Duplicate link deduplicated: ${link.linkType}` + ` from ${link.sourceObjectType}:${link.sourceKey}` + ` to ${link.targetObjectType}:${link.targetKey}`);
|
|
181
|
-
continue;
|
|
182
|
-
}
|
|
183
|
-
seenLinks.add(key);
|
|
184
|
-
merged.links.push(link);
|
|
185
|
-
}
|
|
186
|
-
}
|
|
187
|
-
function linkKey(link) {
|
|
188
|
-
return `${link.sourceObjectType}:${link.sourceKey}` + `:${link.linkType}` + `:${link.targetObjectType}:${link.targetKey}`;
|
|
189
|
-
}
|
|
190
|
-
function getOrInit(map, key, init) {
|
|
191
|
-
let value = map.get(key);
|
|
192
|
-
if (value === undefined) {
|
|
193
|
-
value = init();
|
|
194
|
-
map.set(key, value);
|
|
195
|
-
}
|
|
196
|
-
return value;
|
|
197
|
-
}
|
|
198
|
-
|
|
199
|
-
/**
|
|
200
|
-
* Validates the seed output against the ontology schema.
|
|
201
|
-
*
|
|
202
|
-
* Hard errors (thrown immediately) for any of:
|
|
203
|
-
*
|
|
204
|
-
* - Object types in the seed output not defined in the ontology.
|
|
205
|
-
* - Property names on a seed object not defined on that type.
|
|
206
|
-
* - `null`/`undefined` property values. Typed callers can't reach this
|
|
207
|
-
* (the builder's `SeedProps<Q>` rejects `null`); any null at runtime is
|
|
208
|
-
* a sign of `as any` or a hand-rolled output.
|
|
209
|
-
* - JS type mismatches against the cataloged wire-type-to-JS-type map
|
|
210
|
-
* (e.g., `age: "30"` when `age` is an integer, or `score: 30` when
|
|
211
|
-
* `score` is a long).
|
|
212
|
-
*
|
|
213
|
-
* For wire types whose runtime shape this validator doesn't catalog
|
|
214
|
-
* (`attachment`, `mediaReference`, `geopoint`, `geoshape`, `vector`,
|
|
215
|
-
* `array`, `struct`), JS-type checking is skipped — they have non-primitive
|
|
216
|
-
* shapes that would need bespoke validation. They still go through the
|
|
217
|
-
* earlier object-type / property-name / null checks.
|
|
61
|
+
* Loads a single seed file via jiti and extracts the {@link SeedOutput} from
|
|
62
|
+
* its default export.
|
|
218
63
|
*
|
|
219
|
-
*
|
|
220
|
-
*
|
|
221
|
-
*
|
|
222
|
-
* `string` value matches its wire format (e.g., `"not-a-date"` vs
|
|
223
|
-
* `"2025-01-01T00:00:00Z"` are both valid `string` to the type system);
|
|
224
|
-
* format validation fills that gap.
|
|
225
|
-
*
|
|
226
|
-
* @throws Error on any structural violation listed above, or listing all
|
|
227
|
-
* format failures grouped by object type.
|
|
228
|
-
*/
|
|
229
|
-
export function validateSeedOutput(output, schemaMap) {
|
|
230
|
-
const errors = validateAndCollectFormatErrors(output, schemaMap);
|
|
231
|
-
if (errors.length > 0) {
|
|
232
|
-
throw new Error(formatValidationErrors(errors));
|
|
233
|
-
}
|
|
234
|
-
}
|
|
235
|
-
function validateAndCollectFormatErrors(output, schemaMap) {
|
|
236
|
-
const errors = [];
|
|
237
|
-
for (const [apiName, objects] of Object.entries(output.objects)) {
|
|
238
|
-
const schema = schemaMap.get(apiName);
|
|
239
|
-
if (!schema) {
|
|
240
|
-
throw new Error(`Object type '${apiName}' in seed data is not defined in the ontology`);
|
|
241
|
-
}
|
|
242
|
-
for (const [i, obj] of objects.entries()) {
|
|
243
|
-
for (const [key, value] of Object.entries(obj)) {
|
|
244
|
-
const wireType = schema.properties.get(key);
|
|
245
|
-
if (wireType === undefined) {
|
|
246
|
-
throw new Error(`Property '${key}' on '${apiName}' object` + ` (index ${i}) is not defined in the ontology`);
|
|
247
|
-
}
|
|
248
|
-
if (value == null) {
|
|
249
|
-
throw new Error(`Property '${key}' on '${apiName}' object` + ` (index ${i}) is null or undefined`);
|
|
250
|
-
}
|
|
251
|
-
const expectedJsType = EXPECTED_JS_TYPE[wireType];
|
|
252
|
-
if (expectedJsType !== undefined && typeof value !== expectedJsType) {
|
|
253
|
-
throw new Error(`Property '${key}' on '${apiName}' object` + ` (index ${i}) expects ${wireType} (a ${expectedJsType})` + ` but got ${typeof value}`);
|
|
254
|
-
}
|
|
255
|
-
const format = WIRE_TYPE_FORMAT[wireType];
|
|
256
|
-
if (!format) continue;
|
|
257
|
-
|
|
258
|
-
// Format regex only applies to string-encoded wire types, all of
|
|
259
|
-
// which have EXPECTED_JS_TYPE === "string"; the cast is safe here
|
|
260
|
-
// because the JS-type check above would have thrown otherwise.
|
|
261
|
-
if (format.pattern.test(value)) continue;
|
|
262
|
-
errors.push({
|
|
263
|
-
objectType: apiName,
|
|
264
|
-
objectIndex: i,
|
|
265
|
-
field: key,
|
|
266
|
-
message: `property '${key}' has invalid ${wireType}` + ` format: '${String(value)}'. Expected format like '${format.example}'`
|
|
267
|
-
});
|
|
268
|
-
}
|
|
269
|
-
}
|
|
270
|
-
}
|
|
271
|
-
return errors;
|
|
272
|
-
}
|
|
273
|
-
function formatValidationErrors(errors) {
|
|
274
|
-
const grouped = new Map();
|
|
275
|
-
for (const err of errors) {
|
|
276
|
-
const messages = getOrInit(grouped, err.objectType, () => []);
|
|
277
|
-
messages.push(` object[${err.objectIndex}]: ${err.message}`);
|
|
278
|
-
}
|
|
279
|
-
const body = [...grouped.entries()].map(([type, msgs]) => `${type}:\n${msgs.join("\n")}`).join("\n\n");
|
|
280
|
-
const errorWord = errors.length === 1 ? "error" : "errors";
|
|
281
|
-
const typeWord = grouped.size === 1 ? "object type" : "object types";
|
|
282
|
-
return `Seed data validation failed ` + `(${errors.length} ${errorWord} across ${grouped.size} ${typeWord}` + `):\n\n${body}`;
|
|
283
|
-
}
|
|
284
|
-
|
|
285
|
-
/**
|
|
286
|
-
* Loads a single seed file via jiti and extracts its default export.
|
|
287
|
-
*
|
|
288
|
-
* jiti.import() fully executes the module — the `createSeed()` builder
|
|
289
|
-
* function runs during import and the default export is the resulting
|
|
290
|
-
* SeedOutput.
|
|
64
|
+
* Both shapes a seed author naturally reaches for are accepted: the
|
|
65
|
+
* `createSeed(...)` result (`{ output, context }`) and its `.output` (a bare
|
|
66
|
+
* `SeedOutput`).
|
|
291
67
|
*
|
|
292
68
|
* @throws with a contextual message wrapping the original error and filename.
|
|
293
69
|
*/
|
|
294
70
|
async function loadSeedFile(seedFile) {
|
|
295
71
|
consola.info(`Loading seed file: ${seedFile}`);
|
|
72
|
+
const name = path.basename(seedFile);
|
|
296
73
|
let seedModule;
|
|
297
74
|
try {
|
|
298
75
|
const jiti = createJiti(seedFile, {
|
|
@@ -302,20 +79,26 @@ async function loadSeedFile(seedFile) {
|
|
|
302
79
|
seedModule = await jiti.import(seedFile);
|
|
303
80
|
} catch (e) {
|
|
304
81
|
const message = e instanceof Error ? e.message : String(e);
|
|
305
|
-
throw new Error(`Seed file '${
|
|
82
|
+
throw new Error(`Seed file '${name}' failed to compile:\n ${message}`);
|
|
306
83
|
}
|
|
307
|
-
if (!seedModule
|
|
308
|
-
throw new Error(`Seed file '${
|
|
84
|
+
if (!isRecord(seedModule) || !Object.hasOwn(seedModule, "default")) {
|
|
85
|
+
throw new Error(`Seed file '${name}' must have a default export. Export the result of ` + `createSeed(), which wraps createSeedWithMetadata() from ` + `@osdk/seed-helpers.`);
|
|
309
86
|
}
|
|
310
|
-
const
|
|
311
|
-
|
|
312
|
-
|
|
87
|
+
const defaultExport = seedModule.default;
|
|
88
|
+
const output = isSeedResult(defaultExport) ? defaultExport.output : isSeedOutput(defaultExport) ? defaultExport : undefined;
|
|
89
|
+
if (!output) {
|
|
90
|
+
throw new Error(`Seed file '${name}' default export is not a createSeed() result.\n` + `Export either createSeed(...) — an object with an 'output' property\n ` + `or createSeed(...).output — an object with an 'objects' property`);
|
|
91
|
+
}
|
|
92
|
+
for (const [apiName, objects] of Object.entries(output.objects)) {
|
|
93
|
+
if (!Array.isArray(objects)) {
|
|
94
|
+
throw new TypeError(`Seed file '${name}' has a non-array entry for object type ` + `'${apiName}': expected an array of objects`);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
if (output.links !== undefined && !Array.isArray(output.links)) {
|
|
98
|
+
throw new TypeError(`Seed file '${name}' has a non-array 'links': expected an array of link entries`);
|
|
313
99
|
}
|
|
314
|
-
|
|
315
|
-
// Normalize: links are optional in the export but required in SeedOutput.
|
|
316
|
-
// Spread to avoid mutating the module's exported object.
|
|
317
100
|
return {
|
|
318
|
-
|
|
101
|
+
objects: output.objects,
|
|
319
102
|
links: output.links ?? []
|
|
320
103
|
};
|
|
321
104
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"compileSeedData.js","names":["fs","path","consola","createJiti","EXPECTED_JS_TYPE","string","marking","timestamp","date","datetime","long","decimal","ipAddress","cipherText","integer","byte","short","double","float","boolean","WIRE_TYPE_FORMAT","pattern","example","compileSeedData","seedFiles","outputPath","schema","info","length","outputs","seedFile","push","loadSeedFile","merged","mergeSeedOutputs","validateSeedOutput","totalObjects","Object","values","objects","reduce","sum","arr","outputDir","dirname","promises","mkdir","recursive","writeFile","JSON","stringify","success","links","schemaMap","seenPks","Map","seenLinks","Set","output","mergeObjectsInto","mergeLinksInto","source","apiName","entries","get","Error","bucket","pkSet","getOrInit","obj","pk","String","primaryKeyApiName","has","add","link","key","linkKey","warn","linkType","sourceObjectType","sourceKey","targetObjectType","targetKey","map","init","value","undefined","set","errors","validateAndCollectFormatErrors","formatValidationErrors","i","wireType","properties","expectedJsType","format","test","objectType","objectIndex","field","message","grouped","err","messages","body","type","msgs","join","errorWord","typeWord","size","seedModule","jiti","moduleCache","debug","import","e","basename","default"],"sources":["compileSeedData.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 * as fs from \"node:fs\";\nimport * as path from \"node:path\";\n\nimport type { SeedLinkEntry, SeedOutput } from \"@osdk/seed-helpers\";\nimport { consola } from \"consola\";\nimport { createJiti } from \"jiti\";\n\nimport type { SchemaMap } from \"./schema.js\";\n\n/**\n * One string-format validation failure (e.g., a timestamp value that doesn't\n * match the wire format regex). Format failures are collected across the\n * whole output and reported together at the end so users can fix many\n * content mistakes in one pass. Structural failures (unknown object type,\n * unknown property name, null value, wrong JS type) throw immediately\n * instead — they're not aggregated, so they don't need this struct.\n */\ninterface FormatError {\n objectType: string;\n objectIndex: number;\n field: string;\n message: string;\n}\n\n/**\n * Expected runtime JS type for each cataloged wire type.\n *\n * Used to fail fast on `as any` callers that pass a value of the wrong shape\n * (e.g., `age: \"30\"` when `age` is an integer). Wire types not listed here\n * are not strictly typed by this validator — currently `attachment`,\n * `mediaReference`, `geopoint`, `geoshape`, `vector`, `array`, `struct`,\n * which have non-primitive runtime shapes that need bespoke validation.\n */\nconst EXPECTED_JS_TYPE: Record<string, \"string\" | \"number\" | \"boolean\"> = {\n // string-encoded primitives\n string: \"string\",\n marking: \"string\",\n timestamp: \"string\",\n date: \"string\",\n datetime: \"string\",\n long: \"string\",\n decimal: \"string\",\n ipAddress: \"string\",\n cipherText: \"string\",\n // numeric primitives\n integer: \"number\",\n byte: \"number\",\n short: \"number\",\n double: \"number\",\n float: \"number\",\n // boolean\n boolean: \"boolean\",\n};\n\n/**\n * Regex patterns for string-encoded wire types that TypeScript cannot validate.\n *\n * These patterns are aligned with the Rust backend's actual parsing behavior:\n * - timestamp: RFC 3339 parse on the Rust side — requires timezone, rejects trailing garbage\n * - date: stored as raw string, but only YYYY-MM-DD works in SQLite queries\n * - datetime: stored as raw string, same YYYY-MM-DD requirement for query correctness\n * - long: strict decimal integer parse on the Rust side — no scientific notation\n * - decimal: Rust stores any string (no validation), but we enforce numeric format\n * to prevent obviously invalid values from silently passing through\n */\nconst WIRE_TYPE_FORMAT: Record<string, { pattern: RegExp; example: string }> = {\n timestamp: {\n pattern:\n /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(Z|[+-]\\d{2}:\\d{2})$/u,\n example: \"2025-01-01T00:00:00Z\",\n },\n date: {\n pattern: /^\\d{4}-\\d{2}-\\d{2}$/u,\n example: \"2025-01-01\",\n },\n datetime: {\n pattern:\n /^\\d{4}-\\d{2}-\\d{2}(T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(Z|[+-]\\d{2}:\\d{2})?)?$/u,\n example: \"2025-01-01T12:00:00Z\",\n },\n long: {\n // Strict decimal integer — matches Rust's str::parse::<i64>().\n // No scientific notation, no decimal point, no whitespace.\n pattern: /^-?\\d+$/u,\n example: \"9007199254740993\",\n },\n decimal: {\n // Numeric string with optional decimal point. Anchored.\n // Rust stores any string (no validation), but we reject obviously invalid values.\n pattern: /^-?\\d+(\\.\\d+)?$/u,\n example: \"123.45\",\n },\n};\n\n/**\n * Compiles one or more seed data files into a single merged JSON output.\n *\n * Pipeline: load each file → merge → validate against schema → write JSON.\n *\n * @param seedFiles - Absolute paths to seed `.mts` / `.ts` files.\n * @param outputPath - Where to write the merged seed JSON.\n * @param schema - Per-object-type schema, typically built from\n * {@link import(\"./schema.js\").schemaFromMetadata}.\n * @throws if any seed file fails to compile or has an invalid export, if any\n * object type or property name is unknown to the schema, if any\n * primary key is duplicated across files, if any property value is\n * null/undefined or has the wrong JS type, or if any string-encoded\n * value has an invalid format.\n */\nexport async function compileSeedData(\n seedFiles: string[],\n outputPath: string,\n schema: SchemaMap,\n): Promise<void> {\n consola.info(`Compiling seed data from ${seedFiles.length} file(s)...`);\n\n const outputs: SeedOutput[] = [];\n for (const seedFile of seedFiles) {\n outputs.push(await loadSeedFile(seedFile));\n }\n\n const merged = mergeSeedOutputs(outputs, schema);\n validateSeedOutput(merged, schema);\n\n const totalObjects = Object.values(merged.objects).reduce(\n (sum, arr) => sum + arr.length,\n 0,\n );\n\n const outputDir = path.dirname(outputPath);\n await fs.promises.mkdir(outputDir, { recursive: true });\n await fs.promises.writeFile(outputPath, JSON.stringify(merged, null, 2));\n\n consola.success(\n `Seed data compiled successfully (${totalObjects} objects, ${merged.links.length} links)`,\n );\n}\n\n/**\n * Merges multiple {@link SeedOutput}s into one.\n *\n * - Objects for the same type combine additively.\n * - Duplicate primary keys across files cause an error (checked by the actual\n * PK field from the schema, not by comparing the full serialized object).\n * - Duplicate links (same source, target, and link type) are deduplicated\n * with a warning logged to the console.\n *\n * @param outputs - The individual seed outputs to merge.\n * @param schemaMap - Used to resolve the primary key field name per object type.\n * @returns A single merged SeedOutput ready for validation and writing.\n * @throws if any primary key appears in more than one file for the same type.\n */\nexport function mergeSeedOutputs(\n outputs: SeedOutput[],\n schemaMap: SchemaMap,\n): SeedOutput {\n const merged: SeedOutput = { objects: {}, links: [] };\n const seenPks = new Map<string, Set<string>>();\n const seenLinks = new Set<string>();\n\n for (const output of outputs) {\n mergeObjectsInto(merged, output.objects, schemaMap, seenPks);\n mergeLinksInto(merged, output.links, seenLinks);\n }\n return merged;\n}\n\nfunction mergeObjectsInto(\n merged: SeedOutput,\n source: SeedOutput[\"objects\"],\n schemaMap: SchemaMap,\n seenPks: Map<string, Set<string>>,\n): void {\n for (const [apiName, objects] of Object.entries(source)) {\n const schema = schemaMap.get(apiName);\n if (!schema) {\n throw new Error(\n `Object type '${apiName}' in seed data is not defined in the ontology`,\n );\n }\n\n const bucket = (merged.objects[apiName] ??= []);\n const pkSet = getOrInit(seenPks, apiName, () => new Set<string>());\n\n for (const obj of objects) {\n const pk = String(obj[schema.primaryKeyApiName] ?? \"\");\n if (pkSet.has(pk)) {\n throw new Error(\n `Duplicate primary key '${pk}' for '${apiName}' across seed files`,\n );\n }\n pkSet.add(pk);\n bucket.push(obj);\n }\n }\n}\n\nfunction mergeLinksInto(\n merged: SeedOutput,\n source: SeedOutput[\"links\"],\n seenLinks: Set<string>,\n): void {\n for (const link of source) {\n const key = linkKey(link);\n if (seenLinks.has(key)) {\n consola.warn(\n `Duplicate link deduplicated: ${link.linkType}` +\n ` from ${link.sourceObjectType}:${link.sourceKey}` +\n ` to ${link.targetObjectType}:${link.targetKey}`,\n );\n continue;\n }\n seenLinks.add(key);\n merged.links.push(link);\n }\n}\n\nfunction linkKey(link: SeedLinkEntry): string {\n return (\n `${link.sourceObjectType}:${link.sourceKey}` +\n `:${link.linkType}` +\n `:${link.targetObjectType}:${link.targetKey}`\n );\n}\n\nfunction getOrInit<K, V>(map: Map<K, V>, key: K, init: () => V): V {\n let value = map.get(key);\n if (value === undefined) {\n value = init();\n map.set(key, value);\n }\n return value;\n}\n\n/**\n * Validates the seed output against the ontology schema.\n *\n * Hard errors (thrown immediately) for any of:\n *\n * - Object types in the seed output not defined in the ontology.\n * - Property names on a seed object not defined on that type.\n * - `null`/`undefined` property values. Typed callers can't reach this\n * (the builder's `SeedProps<Q>` rejects `null`); any null at runtime is\n * a sign of `as any` or a hand-rolled output.\n * - JS type mismatches against the cataloged wire-type-to-JS-type map\n * (e.g., `age: \"30\"` when `age` is an integer, or `score: 30` when\n * `score` is a long).\n *\n * For wire types whose runtime shape this validator doesn't catalog\n * (`attachment`, `mediaReference`, `geopoint`, `geoshape`, `vector`,\n * `array`, `struct`), JS-type checking is skipped — they have non-primitive\n * shapes that would need bespoke validation. They still go through the\n * earlier object-type / property-name / null checks.\n *\n * After JS-type validation, string values are checked against the format\n * regex for their wire type (timestamp, date, datetime, long, decimal).\n * The one thing TypeScript cannot distinguish on its own is whether a\n * `string` value matches its wire format (e.g., `\"not-a-date\"` vs\n * `\"2025-01-01T00:00:00Z\"` are both valid `string` to the type system);\n * format validation fills that gap.\n *\n * @throws Error on any structural violation listed above, or listing all\n * format failures grouped by object type.\n */\nexport function validateSeedOutput(\n output: SeedOutput,\n schemaMap: SchemaMap,\n): void {\n const errors = validateAndCollectFormatErrors(output, schemaMap);\n if (errors.length > 0) {\n throw new Error(formatValidationErrors(errors));\n }\n}\n\nfunction validateAndCollectFormatErrors(\n output: SeedOutput,\n schemaMap: SchemaMap,\n): FormatError[] {\n const errors: FormatError[] = [];\n\n for (const [apiName, objects] of Object.entries(output.objects)) {\n const schema = schemaMap.get(apiName);\n if (!schema) {\n throw new Error(\n `Object type '${apiName}' in seed data is not defined in the ontology`,\n );\n }\n\n for (const [i, obj] of objects.entries()) {\n for (const [key, value] of Object.entries(obj)) {\n const wireType = schema.properties.get(key);\n if (wireType === undefined) {\n throw new Error(\n `Property '${key}' on '${apiName}' object` +\n ` (index ${i}) is not defined in the ontology`,\n );\n }\n\n if (value == null) {\n throw new Error(\n `Property '${key}' on '${apiName}' object` +\n ` (index ${i}) is null or undefined`,\n );\n }\n\n const expectedJsType = EXPECTED_JS_TYPE[wireType];\n if (expectedJsType !== undefined && typeof value !== expectedJsType) {\n throw new Error(\n `Property '${key}' on '${apiName}' object` +\n ` (index ${i}) expects ${wireType} (a ${expectedJsType})` +\n ` but got ${typeof value}`,\n );\n }\n\n const format = WIRE_TYPE_FORMAT[wireType];\n if (!format) continue;\n\n // Format regex only applies to string-encoded wire types, all of\n // which have EXPECTED_JS_TYPE === \"string\"; the cast is safe here\n // because the JS-type check above would have thrown otherwise.\n if (format.pattern.test(value as string)) continue;\n\n errors.push({\n objectType: apiName,\n objectIndex: i,\n field: key,\n message:\n `property '${key}' has invalid ${wireType}` +\n ` format: '${String(\n value,\n )}'. Expected format like '${format.example}'`,\n });\n }\n }\n }\n\n return errors;\n}\n\nfunction formatValidationErrors(errors: FormatError[]): string {\n const grouped = new Map<string, string[]>();\n for (const err of errors) {\n const messages = getOrInit(grouped, err.objectType, () => []);\n messages.push(` object[${err.objectIndex}]: ${err.message}`);\n }\n\n const body = [...grouped.entries()]\n .map(([type, msgs]) => `${type}:\\n${msgs.join(\"\\n\")}`)\n .join(\"\\n\\n\");\n\n const errorWord = errors.length === 1 ? \"error\" : \"errors\";\n const typeWord = grouped.size === 1 ? \"object type\" : \"object types\";\n\n return (\n `Seed data validation failed ` +\n `(${errors.length} ${errorWord} across ${grouped.size} ${typeWord}` +\n `):\\n\\n${body}`\n );\n}\n\n/**\n * Loads a single seed file via jiti and extracts its default export.\n *\n * jiti.import() fully executes the module — the `createSeed()` builder\n * function runs during import and the default export is the resulting\n * SeedOutput.\n *\n * @throws with a contextual message wrapping the original error and filename.\n */\nasync function loadSeedFile(seedFile: string): Promise<SeedOutput> {\n consola.info(`Loading seed file: ${seedFile}`);\n\n let seedModule: { default: SeedOutput };\n try {\n const jiti = createJiti(seedFile, {\n moduleCache: false,\n debug: false,\n });\n seedModule = (await jiti.import(seedFile)) as { default: SeedOutput };\n } catch (e: unknown) {\n const message = e instanceof Error ? e.message : String(e);\n throw new Error(\n `Seed file '${path.basename(seedFile)}' failed to compile:\\n ${message}`,\n );\n }\n\n if (!seedModule.default || typeof seedModule.default !== \"object\") {\n throw new Error(\n `Seed file '${path.basename(seedFile)}' must have a default export. ` +\n `Use createSeed() from @osdk/seed-helpers.`,\n );\n }\n\n const output = seedModule.default;\n\n if (!output.objects || typeof output.objects !== \"object\") {\n throw new Error(\n `Seed file '${path.basename(seedFile)}' default export is not a valid` +\n ` SeedOutput. Use createSeed() from @osdk/seed-helpers.`,\n );\n }\n\n // Normalize: links are optional in the export but required in SeedOutput.\n // Spread to avoid mutating the module's exported object.\n return { ...output, links: output.links ?? [] };\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,OAAO,KAAKA,EAAE,MAAM,SAAS;AAC7B,OAAO,KAAKC,IAAI,MAAM,WAAW;AAGjC,SAASC,OAAO,QAAQ,SAAS;AACjC,SAASC,UAAU,QAAQ,MAAM;;AAIjC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAQA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAMC,gBAAiE,GAAG;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,OAAO;IAAE,GAAG4B,MAAM;IAAEN,KAAK,EAAEM,MAAM,CAACN,KAAK,IAAI;EAAG,CAAC;AACjD","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"compileSeedData.js","names":["fs","path","SeedBuilder","consola","createJiti","compileSeedData","seedFiles","outputPath","metadata","info","length","builder","seedFile","output","loadSeedFile","addAll","e","message","Error","String","basename","merged","build","totalObjects","Object","values","objects","reduce","sum","arr","outputDir","dirname","promises","mkdir","recursive","writeFile","JSON","stringify","success","links","isRecord","value","Array","isArray","isSeedOutput","isSeedResult","name","seedModule","jiti","moduleCache","debug","import","hasOwn","defaultExport","default","undefined","apiName","entries","TypeError"],"sources":["compileSeedData.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 * as fs from \"node:fs\";\nimport * as path from \"node:path\";\n\nimport type { OntologyFullMetadata } from \"@osdk/foundry.ontologies\";\nimport { SeedBuilder, type SeedOutput } from \"@osdk/seed-helpers\";\nimport { consola } from \"consola\";\nimport { createJiti } from \"jiti\";\n\n/**\n * Merges one or more seed data files into a single JSON output.\n *\n * Pipeline: load each file -> feed into one {@link SeedBuilder} -> write JSON.\n *\n * @param seedFiles - Absolute paths to seed `.mts` / `.ts` files.\n * @param outputPath - Where to write the merged seed JSON.\n * @param metadata - Ontology metadata, typically parsed from the\n * `ontology-metadata.json` written by the SDK generator.\n * @throws if any seed file fails to compile or has an invalid default export,\n * or if the builder rejects any object or link it is given.\n */\nexport async function compileSeedData(\n seedFiles: string[],\n outputPath: string,\n metadata: OntologyFullMetadata,\n): Promise<void> {\n consola.info(`Compiling seed data from ${seedFiles.length} file(s)...`);\n const builder = new SeedBuilder(metadata);\n for (const seedFile of seedFiles) {\n const output = await loadSeedFile(seedFile);\n try {\n builder.addAll(output);\n } catch (e: unknown) {\n const message = e instanceof Error ? e.message : String(e);\n throw new Error(`Seed file '${path.basename(seedFile)}': ${message}`);\n }\n }\n const merged = builder.build();\n const totalObjects = Object.values(merged.objects).reduce(\n (sum, arr) => sum + arr.length,\n 0,\n );\n\n const outputDir = path.dirname(outputPath);\n await fs.promises.mkdir(outputDir, { recursive: true });\n await fs.promises.writeFile(outputPath, JSON.stringify(merged, null, 2));\n\n consola.success(\n `Seed data compiled successfully (${totalObjects} objects, ${merged.links.length} links)`,\n );\n}\n\ntype LoadedSeedOutput = Pick<SeedOutput, \"objects\"> &\n Partial<Pick<SeedOutput, \"links\">>;\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value != null && !Array.isArray(value);\n\nconst isSeedOutput = (value: unknown): value is LoadedSeedOutput =>\n isRecord(value) && isRecord(value.objects);\n\nconst isSeedResult = (value: unknown): value is { output: LoadedSeedOutput } =>\n isRecord(value) && isSeedOutput(value.output);\n\n/**\n * Loads a single seed file via jiti and extracts the {@link SeedOutput} from\n * its default export.\n *\n * Both shapes a seed author naturally reaches for are accepted: the\n * `createSeed(...)` result (`{ output, context }`) and its `.output` (a bare\n * `SeedOutput`).\n *\n * @throws with a contextual message wrapping the original error and filename.\n */\nasync function loadSeedFile(seedFile: string): Promise<SeedOutput> {\n consola.info(`Loading seed file: ${seedFile}`);\n const name = path.basename(seedFile);\n let seedModule: Record<string, unknown>;\n\n try {\n const jiti = createJiti(seedFile, {\n moduleCache: false,\n debug: false,\n });\n seedModule = (await jiti.import(seedFile)) as Record<string, unknown>;\n } catch (e: unknown) {\n const message = e instanceof Error ? e.message : String(e);\n throw new Error(`Seed file '${name}' failed to compile:\\n ${message}`);\n }\n\n if (!isRecord(seedModule) || !Object.hasOwn(seedModule, \"default\")) {\n throw new Error(\n `Seed file '${name}' must have a default export. Export the result of ` +\n `createSeed(), which wraps createSeedWithMetadata() from ` +\n `@osdk/seed-helpers.`,\n );\n }\n\n const defaultExport = seedModule.default;\n const output = isSeedResult(defaultExport)\n ? defaultExport.output\n : isSeedOutput(defaultExport)\n ? defaultExport\n : undefined;\n\n if (!output) {\n throw new Error(\n `Seed file '${name}' default export is not a createSeed() result.\\n` +\n `Export either createSeed(...) — an object with an 'output' property\\n ` +\n `or createSeed(...).output — an object with an 'objects' property`,\n );\n }\n\n for (const [apiName, objects] of Object.entries(output.objects)) {\n if (!Array.isArray(objects)) {\n throw new TypeError(\n `Seed file '${name}' has a non-array entry for object type ` +\n `'${apiName}': expected an array of objects`,\n );\n }\n }\n\n if (output.links !== undefined && !Array.isArray(output.links)) {\n throw new TypeError(\n `Seed file '${name}' has a non-array 'links': expected an array of link entries`,\n );\n }\n\n return { objects: output.objects, links: output.links ?? [] };\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,OAAO,KAAKA,EAAE,MAAM,SAAS;AAC7B,OAAO,KAAKC,IAAI,MAAM,WAAW;AAGjC,SAASC,WAAW,QAAyB,oBAAoB;AACjE,SAASC,OAAO,QAAQ,SAAS;AACjC,SAASC,UAAU,QAAQ,MAAM;;AAEjC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,eAAeC,eAAeA,CACnCC,SAAmB,EACnBC,UAAkB,EAClBC,QAA8B,EACf;EACfL,OAAO,CAACM,IAAI,CAAC,4BAA4BH,SAAS,CAACI,MAAM,aAAa,CAAC;EACvE,MAAMC,OAAO,GAAG,IAAIT,WAAW,CAACM,QAAQ,CAAC;EACzC,KAAK,MAAMI,QAAQ,IAAIN,SAAS,EAAE;IAChC,MAAMO,MAAM,GAAG,MAAMC,YAAY,CAACF,QAAQ,CAAC;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E,GACxE,kEACJ,CAAC;EACH;EAEA,KAAK,MAAM,CAACU,OAAO,EAAE9B,OAAO,CAAC,IAAIF,MAAM,CAACiC,OAAO,CAAC5C,MAAM,CAACa,OAAO,CAAC,EAAE;IAC/D,IAAI,CAACgB,KAAK,CAACC,OAAO,CAACjB,OAAO,CAAC,EAAE;MAC3B,MAAM,IAAIgC,SAAS,CACjB,cAAcZ,IAAI,0CAA0C,GAC1D,IAAIU,OAAO,iCACf,CAAC;IACH;EACF;EAEA,IAAI3C,MAAM,CAAC0B,KAAK,KAAKgB,SAAS,IAAI,CAACb,KAAK,CAACC,OAAO,CAAC9B,MAAM,CAAC0B,KAAK,CAAC,EAAE;IAC9D,MAAM,IAAImB,SAAS,CACjB,cAAcZ,IAAI,8DACpB,CAAC;EACH;EAEA,OAAO;IAAEpB,OAAO,EAAEb,MAAM,CAACa,OAAO;IAAEa,KAAK,EAAE1B,MAAM,CAAC0B,KAAK,IAAI;EAAG,CAAC;AAC/D","ignoreList":[]}
|
package/build/esm/index.js
CHANGED
|
@@ -14,6 +14,5 @@
|
|
|
14
14
|
* limitations under the License.
|
|
15
15
|
*/
|
|
16
16
|
|
|
17
|
-
export { compileSeedData
|
|
18
|
-
export { schemaFromMetadata } from "./schema.js";
|
|
17
|
+
export { compileSeedData } from "./compileSeedData.js";
|
|
19
18
|
//# sourceMappingURL=index.js.map
|
package/build/esm/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["compileSeedData"
|
|
1
|
+
{"version":3,"file":"index.js","names":["compileSeedData"],"sources":["index.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\nexport { compileSeedData } from \"./compileSeedData.js\";\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAASA,eAAe,QAAQ,sBAAsB","ignoreList":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"mappings":"
|
|
1
|
+
{"mappings":"eA2Be,SAAe,KAC5BA,kBACC","names":["args: string[]"],"sources":["../../../src/cli/main.ts"],"version":3,"file":"main.d.ts"}
|
|
@@ -1,64 +1,14 @@
|
|
|
1
|
-
import type {
|
|
2
|
-
import type { SchemaMap } from "./schema.js";
|
|
1
|
+
import type { OntologyFullMetadata } from "@osdk/foundry.ontologies";
|
|
3
2
|
/**
|
|
4
|
-
*
|
|
3
|
+
* Merges one or more seed data files into a single JSON output.
|
|
5
4
|
*
|
|
6
|
-
* Pipeline: load each file
|
|
5
|
+
* Pipeline: load each file -> feed into one {@link SeedBuilder} -> write JSON.
|
|
7
6
|
*
|
|
8
7
|
* @param seedFiles - Absolute paths to seed `.mts` / `.ts` files.
|
|
9
8
|
* @param outputPath - Where to write the merged seed JSON.
|
|
10
|
-
* @param
|
|
11
|
-
*
|
|
12
|
-
* @throws if any seed file fails to compile or has an invalid export,
|
|
13
|
-
*
|
|
14
|
-
* primary key is duplicated across files, if any property value is
|
|
15
|
-
* null/undefined or has the wrong JS type, or if any string-encoded
|
|
16
|
-
* value has an invalid format.
|
|
9
|
+
* @param metadata - Ontology metadata, typically parsed from the
|
|
10
|
+
* `ontology-metadata.json` written by the SDK generator.
|
|
11
|
+
* @throws if any seed file fails to compile or has an invalid default export,
|
|
12
|
+
* or if the builder rejects any object or link it is given.
|
|
17
13
|
*/
|
|
18
|
-
export declare function compileSeedData(seedFiles: string[], outputPath: string,
|
|
19
|
-
/**
|
|
20
|
-
* Merges multiple {@link SeedOutput}s into one.
|
|
21
|
-
*
|
|
22
|
-
* - Objects for the same type combine additively.
|
|
23
|
-
* - Duplicate primary keys across files cause an error (checked by the actual
|
|
24
|
-
* PK field from the schema, not by comparing the full serialized object).
|
|
25
|
-
* - Duplicate links (same source, target, and link type) are deduplicated
|
|
26
|
-
* with a warning logged to the console.
|
|
27
|
-
*
|
|
28
|
-
* @param outputs - The individual seed outputs to merge.
|
|
29
|
-
* @param schemaMap - Used to resolve the primary key field name per object type.
|
|
30
|
-
* @returns A single merged SeedOutput ready for validation and writing.
|
|
31
|
-
* @throws if any primary key appears in more than one file for the same type.
|
|
32
|
-
*/
|
|
33
|
-
export declare function mergeSeedOutputs(outputs: SeedOutput[], schemaMap: SchemaMap): SeedOutput;
|
|
34
|
-
/**
|
|
35
|
-
* Validates the seed output against the ontology schema.
|
|
36
|
-
*
|
|
37
|
-
* Hard errors (thrown immediately) for any of:
|
|
38
|
-
*
|
|
39
|
-
* - Object types in the seed output not defined in the ontology.
|
|
40
|
-
* - Property names on a seed object not defined on that type.
|
|
41
|
-
* - `null`/`undefined` property values. Typed callers can't reach this
|
|
42
|
-
* (the builder's `SeedProps<Q>` rejects `null`); any null at runtime is
|
|
43
|
-
* a sign of `as any` or a hand-rolled output.
|
|
44
|
-
* - JS type mismatches against the cataloged wire-type-to-JS-type map
|
|
45
|
-
* (e.g., `age: "30"` when `age` is an integer, or `score: 30` when
|
|
46
|
-
* `score` is a long).
|
|
47
|
-
*
|
|
48
|
-
* For wire types whose runtime shape this validator doesn't catalog
|
|
49
|
-
* (`attachment`, `mediaReference`, `geopoint`, `geoshape`, `vector`,
|
|
50
|
-
* `array`, `struct`), JS-type checking is skipped — they have non-primitive
|
|
51
|
-
* shapes that would need bespoke validation. They still go through the
|
|
52
|
-
* earlier object-type / property-name / null checks.
|
|
53
|
-
*
|
|
54
|
-
* After JS-type validation, string values are checked against the format
|
|
55
|
-
* regex for their wire type (timestamp, date, datetime, long, decimal).
|
|
56
|
-
* The one thing TypeScript cannot distinguish on its own is whether a
|
|
57
|
-
* `string` value matches its wire format (e.g., `"not-a-date"` vs
|
|
58
|
-
* `"2025-01-01T00:00:00Z"` are both valid `string` to the type system);
|
|
59
|
-
* format validation fills that gap.
|
|
60
|
-
*
|
|
61
|
-
* @throws Error on any structural violation listed above, or listing all
|
|
62
|
-
* format failures grouped by object type.
|
|
63
|
-
*/
|
|
64
|
-
export declare function validateSeedOutput(output: SeedOutput, schemaMap: SchemaMap): void;
|
|
14
|
+
export declare function compileSeedData(seedFiles: string[], outputPath: string, metadata: OntologyFullMetadata): Promise<void>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"mappings":"AAmBA,
|
|
1
|
+
{"mappings":"AAmBA,cAAc,4BAA4B,0BAA2B;;;;;;;;;;;;;AAiBrE,OAAO,iBAAe,gBACpBA,qBACAC,oBACAC,UAAU,uBACT","names":["seedFiles: string[]","outputPath: string","metadata: OntologyFullMetadata"],"sources":["../../src/compileSeedData.ts"],"version":3,"file":"compileSeedData.d.ts"}
|
package/build/types/index.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"mappings":"AAgBA,
|
|
1
|
+
{"mappings":"AAgBA,SAAS,uBAAuB","names":[],"sources":["../../src/index.ts"],"version":3,"file":"index.d.ts"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@osdk/seed-compiler",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.12.0",
|
|
4
4
|
"license": "Apache-2.0",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -32,13 +32,19 @@
|
|
|
32
32
|
"jiti": "^2.5.1",
|
|
33
33
|
"tiny-invariant": "^1.3.3",
|
|
34
34
|
"yargs": "^17.7.2",
|
|
35
|
-
"@osdk/seed-helpers": "~0.
|
|
35
|
+
"@osdk/seed-helpers": "~0.27.0"
|
|
36
|
+
},
|
|
37
|
+
"peerDependencies": {
|
|
38
|
+
"@osdk/api": "^2.57.0",
|
|
39
|
+
"@osdk/client": "^2.57.0"
|
|
36
40
|
},
|
|
37
41
|
"devDependencies": {
|
|
38
42
|
"@types/node": "^20.19.13",
|
|
39
43
|
"@types/yargs": "^17.0.33",
|
|
40
44
|
"typescript": "~5.5.4",
|
|
41
45
|
"vitest": "^3.2.4",
|
|
46
|
+
"@osdk/api": "~2.57.0",
|
|
47
|
+
"@osdk/client": "~2.57.0",
|
|
42
48
|
"@osdk/monorepo.tsconfig": "~0.7.0",
|
|
43
49
|
"@osdk/monorepo.api-extractor": "~0.7.0"
|
|
44
50
|
},
|
package/build/browser/schema.js
DELETED
|
@@ -1,51 +0,0 @@
|
|
|
1
|
-
/*
|
|
2
|
-
* Copyright 2025 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
|
-
/**
|
|
18
|
-
* Minimal schema for one object type — only what the compiler needs.
|
|
19
|
-
*
|
|
20
|
-
* - `properties`: property API name → wire type (e.g. `"timestamp"`, `"long"`),
|
|
21
|
-
* used by the validator to enforce property existence, JS-type expectations,
|
|
22
|
-
* and string format regexes.
|
|
23
|
-
* - `primaryKeyApiName`: PK field name (for cross-file duplicate detection in merge).
|
|
24
|
-
*/
|
|
25
|
-
|
|
26
|
-
/** Maps object type API name → its schema. */
|
|
27
|
-
|
|
28
|
-
/**
|
|
29
|
-
* Builds a {@link SchemaMap} from an `OntologyFullMetadata` document — the
|
|
30
|
-
* shape produced by the OSDK SDK generator and serialized to
|
|
31
|
-
* `ontology-metadata.json` alongside the generated `@ontology/sdk` package.
|
|
32
|
-
*
|
|
33
|
-
* Only `objectTypes` are read; the other top-level fields (action types,
|
|
34
|
-
* query types, interfaces, etc.) are not relevant to seed validation.
|
|
35
|
-
*/
|
|
36
|
-
export function schemaFromMetadata(metadata) {
|
|
37
|
-
const map = new Map();
|
|
38
|
-
for (const [apiName, full] of Object.entries(metadata.objectTypes)) {
|
|
39
|
-
const ot = full.objectType;
|
|
40
|
-
const properties = new Map();
|
|
41
|
-
for (const [propApiName, prop] of Object.entries(ot.properties)) {
|
|
42
|
-
properties.set(propApiName, prop.dataType.type);
|
|
43
|
-
}
|
|
44
|
-
map.set(apiName, {
|
|
45
|
-
properties,
|
|
46
|
-
primaryKeyApiName: ot.primaryKey
|
|
47
|
-
});
|
|
48
|
-
}
|
|
49
|
-
return map;
|
|
50
|
-
}
|
|
51
|
-
//# sourceMappingURL=schema.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"schema.js","names":["schemaFromMetadata","metadata","map","Map","apiName","full","Object","entries","objectTypes","ot","objectType","properties","propApiName","prop","set","dataType","type","primaryKeyApiName","primaryKey"],"sources":["schema.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 { OntologyFullMetadata } from \"@osdk/foundry.ontologies\";\n\n/**\n * Minimal schema for one object type — only what the compiler needs.\n *\n * - `properties`: property API name → wire type (e.g. `\"timestamp\"`, `\"long\"`),\n * used by the validator to enforce property existence, JS-type expectations,\n * and string format regexes.\n * - `primaryKeyApiName`: PK field name (for cross-file duplicate detection in merge).\n */\nexport interface ObjectTypeSchema {\n properties: Map<string, string>;\n primaryKeyApiName: string;\n}\n\n/** Maps object type API name → its schema. */\nexport type SchemaMap = Map<string, ObjectTypeSchema>;\n\n/**\n * Builds a {@link SchemaMap} from an `OntologyFullMetadata` document — the\n * shape produced by the OSDK SDK generator and serialized to\n * `ontology-metadata.json` alongside the generated `@ontology/sdk` package.\n *\n * Only `objectTypes` are read; the other top-level fields (action types,\n * query types, interfaces, etc.) are not relevant to seed validation.\n */\nexport function schemaFromMetadata(metadata: OntologyFullMetadata): SchemaMap {\n const map: SchemaMap = new Map();\n\n for (const [apiName, full] of Object.entries(metadata.objectTypes)) {\n const ot = full.objectType;\n\n const properties = new Map<string, string>();\n for (const [propApiName, prop] of Object.entries(ot.properties)) {\n properties.set(propApiName, prop.dataType.type);\n }\n\n map.set(apiName, {\n properties,\n primaryKeyApiName: ot.primaryKey,\n });\n }\n\n return map;\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAMA;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASA,kBAAkBA,CAACC,QAA8B,EAAa;EAC5E,MAAMC,GAAc,GAAG,IAAIC,GAAG,CAAC,CAAC;EAEhC,KAAK,MAAM,CAACC,OAAO,EAAEC,IAAI,CAAC,IAAIC,MAAM,CAACC,OAAO,CAACN,QAAQ,CAACO,WAAW,CAAC,EAAE;IAClE,MAAMC,EAAE,GAAGJ,IAAI,CAACK,UAAU;IAE1B,MAAMC,UAAU,GAAG,IAAIR,GAAG,CAAiB,CAAC;IAC5C,KAAK,MAAM,CAACS,WAAW,EAAEC,IAAI,CAAC,IAAIP,MAAM,CAACC,OAAO,CAACE,EAAE,CAACE,UAAU,CAAC,EAAE;MAC/DA,UAAU,CAACG,GAAG,CAACF,WAAW,EAAEC,IAAI,CAACE,QAAQ,CAACC,IAAI,CAAC;IACjD;IAEAd,GAAG,CAACY,GAAG,CAACV,OAAO,EAAE;MACfO,UAAU;MACVM,iBAAiB,EAAER,EAAE,CAACS;IACxB,CAAC,CAAC;EACJ;EAEA,OAAOhB,GAAG;AACZ","ignoreList":[]}
|