@omnidotdev/odk 0.1.1 → 0.1.3

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.
@@ -114,25 +114,10 @@ function jsonSchemaToType(
114
114
 
115
115
  // Handle objects as models
116
116
  if (schema.type === "object" || schema.properties) {
117
- const fields: CompiledField[] = [];
118
- const required = new Set(schema.required || []);
119
-
120
- for (const [propName, propSchema] of Object.entries(
121
- schema.properties || {},
122
- )) {
123
- fields.push({
124
- name: propName,
125
- type: jsonSchemaPropertyToType(propSchema),
126
- optional: !required.has(propName),
127
- description: propSchema.description,
128
- constraints: extractConstraints(propSchema),
129
- });
130
- }
131
-
132
117
  return {
133
118
  model: {
134
119
  name,
135
- fields,
120
+ fields: objectFields(schema),
136
121
  description: schema.description,
137
122
  },
138
123
  };
@@ -211,21 +196,7 @@ function jsonSchemaPropertyToType(schema: JSONSchema): CompiledType {
211
196
 
212
197
  // Handle objects (inline)
213
198
  if (schema.type === "object" || schema.properties) {
214
- const fields: CompiledField[] = [];
215
- const required = new Set(schema.required || []);
216
-
217
- for (const [propName, propSchema] of Object.entries(
218
- schema.properties || {},
219
- )) {
220
- fields.push({
221
- name: propName,
222
- type: jsonSchemaPropertyToType(propSchema),
223
- optional: !required.has(propName),
224
- constraints: extractConstraints(propSchema),
225
- });
226
- }
227
-
228
- return { kind: "object", fields };
199
+ return { kind: "object", fields: objectFields(schema) };
229
200
  }
230
201
 
231
202
  // Handle type arrays (union of types)
@@ -239,6 +210,11 @@ function jsonSchemaPropertyToType(schema: JSONSchema): CompiledType {
239
210
  };
240
211
  }
241
212
 
213
+ // Handle integers, whose width depends on their bounds
214
+ if (schema.type === "integer") {
215
+ return { kind: "scalar", name: integerScalar(schema) };
216
+ }
217
+
242
218
  // Handle primitive types
243
219
  if (typeof schema.type === "string") {
244
220
  return { kind: "scalar", name: jsonTypeToScalar(schema.type) };
@@ -247,6 +223,127 @@ function jsonSchemaPropertyToType(schema: JSONSchema): CompiledType {
247
223
  return { kind: "scalar", name: "unknown" };
248
224
  }
249
225
 
226
+ /**
227
+ * Convert an object schema's properties to fields.
228
+ *
229
+ * A property with a default is optional (callers may omit it), and a property
230
+ * that admits `null` is marked nullable on its non-null type rather than being
231
+ * widened to a union with an unknown variant.
232
+ */
233
+ function objectFields(schema: JSONSchema): CompiledField[] {
234
+ const required = new Set(schema.required || []);
235
+
236
+ return Object.entries(schema.properties || {}).map(
237
+ ([propName, propSchema]) => {
238
+ const { schema: valueSchema, nullable } = stripNull(propSchema);
239
+ const hasDefault = propSchema.default !== undefined;
240
+
241
+ const field: CompiledField = {
242
+ name: propName,
243
+ type: jsonSchemaPropertyToType(valueSchema),
244
+ optional: !required.has(propName) || hasDefault,
245
+ description: propSchema.description,
246
+ constraints: extractConstraints(valueSchema),
247
+ };
248
+ if (nullable) field.nullable = true;
249
+ if (hasDefault) field.default = propSchema.default;
250
+
251
+ return field;
252
+ },
253
+ );
254
+ }
255
+
256
+ /**
257
+ * Split a schema that admits `null` into its non-null schema and a flag.
258
+ *
259
+ * Handles the three shapes JSON Schema generators use for nullability: a type
260
+ * array (`type: ["string", "null"]`), a union with a null branch
261
+ * (`anyOf: [{ type: "string" }, { type: "null" }]`), and an enum containing
262
+ * `null`. Keys on the outer schema (description, default) are preserved.
263
+ */
264
+ function stripNull(schema: JSONSchema): {
265
+ schema: JSONSchema;
266
+ nullable: boolean;
267
+ } {
268
+ if (Array.isArray(schema.type) && schema.type.includes("null")) {
269
+ const types = schema.type.filter((t) => t !== "null");
270
+ return {
271
+ schema: { ...schema, type: types.length === 1 ? types[0] : types },
272
+ nullable: true,
273
+ };
274
+ }
275
+
276
+ const branchKey = schema.anyOf ? "anyOf" : schema.oneOf ? "oneOf" : undefined;
277
+ const branches = branchKey ? schema[branchKey] : undefined;
278
+ if (branchKey && branches?.some(isNullSchema)) {
279
+ const nonNull = branches.filter((b) => !isNullSchema(b));
280
+ const { [branchKey]: _branches, ...outer } = schema;
281
+ const [single] = nonNull;
282
+
283
+ return {
284
+ schema:
285
+ nonNull.length === 1 && single
286
+ ? { ...single, ...outer }
287
+ : { ...outer, [branchKey]: nonNull },
288
+ nullable: true,
289
+ };
290
+ }
291
+
292
+ // The declared enum type omits null, but generators emit it for nullable
293
+ // enums, so check the runtime values
294
+ const enumValues: unknown[] | undefined = schema.enum;
295
+ if (schema.enum && enumValues?.includes(null)) {
296
+ return {
297
+ schema: { ...schema, enum: schema.enum.filter((v) => v !== null) },
298
+ nullable: true,
299
+ };
300
+ }
301
+
302
+ return { schema, nullable: false };
303
+ }
304
+
305
+ function isNullSchema(schema: JSONSchema): boolean {
306
+ return schema.type === "null";
307
+ }
308
+
309
+ /** Largest integer JS represents exactly, which validators emit as a bound */
310
+ const MAX_SAFE = Number.MAX_SAFE_INTEGER;
311
+ const INT32_MIN = -2147483648;
312
+ const INT32_MAX = 2147483647;
313
+
314
+ /**
315
+ * Pick the TypeSpec integer scalar for an integer schema.
316
+ *
317
+ * Validators for JS numbers bound integers to the safe range, so `safeint` is
318
+ * the faithful default (and renders as `type: integer`, unlike `int64`, which
319
+ * JSON Schema emitters render as a string). Explicit bounds that fit 32 bits
320
+ * narrow it to `int32`.
321
+ */
322
+ function integerScalar(schema: JSONSchema): ScalarType {
323
+ if (schema.format === "int64") return "int64";
324
+ if (schema.format === "int32") return "int32";
325
+
326
+ const min = schema.minimum ?? schema.exclusiveMinimum;
327
+ const max = schema.maximum ?? schema.exclusiveMaximum;
328
+ if (
329
+ min !== undefined &&
330
+ max !== undefined &&
331
+ !isSafeBound(min) &&
332
+ !isSafeBound(max) &&
333
+ min >= INT32_MIN &&
334
+ max <= INT32_MAX
335
+ ) {
336
+ return "int32";
337
+ }
338
+
339
+ return "safeint";
340
+ }
341
+
342
+ /** Whether a bound is the synthetic safe-integer limit, not a user constraint */
343
+ function isSafeBound(value: number): boolean {
344
+ return Math.abs(value) === MAX_SAFE;
345
+ }
346
+
250
347
  function jsonTypeToScalar(type: string): ScalarType {
251
348
  switch (type) {
252
349
  case "string":
@@ -254,7 +351,7 @@ function jsonTypeToScalar(type: string): ScalarType {
254
351
  case "number":
255
352
  return "float64";
256
353
  case "integer":
257
- return "int64";
354
+ return "safeint";
258
355
  case "boolean":
259
356
  return "boolean";
260
357
  case "null":
@@ -276,11 +373,20 @@ function extractConstraints(schema: JSONSchema): FieldConstraints | undefined {
276
373
  constraints.maxLength = schema.maxLength;
277
374
  hasConstraints = true;
278
375
  }
279
- if (schema.minimum !== undefined) {
376
+ // Integer bounds equal to the safe-integer limit are implied by the
377
+ // `safeint` scalar, so they are not user constraints worth emitting
378
+ const isInteger = schema.type === "integer";
379
+ if (
380
+ schema.minimum !== undefined &&
381
+ !(isInteger && isSafeBound(schema.minimum))
382
+ ) {
280
383
  constraints.minValue = schema.minimum;
281
384
  hasConstraints = true;
282
385
  }
283
- if (schema.maximum !== undefined) {
386
+ if (
387
+ schema.maximum !== undefined &&
388
+ !(isInteger && isSafeBound(schema.maximum))
389
+ ) {
284
390
  constraints.maxValue = schema.maximum;
285
391
  hasConstraints = true;
286
392
  }
@@ -304,6 +410,14 @@ function extractConstraints(schema: JSONSchema): FieldConstraints | undefined {
304
410
  constraints.multipleOf = schema.multipleOf;
305
411
  hasConstraints = true;
306
412
  }
413
+ if (schema.minItems !== undefined) {
414
+ constraints.minItems = schema.minItems;
415
+ hasConstraints = true;
416
+ }
417
+ if (schema.maxItems !== undefined) {
418
+ constraints.maxItems = schema.maxItems;
419
+ hasConstraints = true;
420
+ }
307
421
 
308
422
  return hasConstraints ? constraints : undefined;
309
423
  }
@@ -0,0 +1,202 @@
1
+ import { afterAll, describe, expect, test } from "bun:test";
2
+ import { mkdirSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import path from "node:path";
5
+
6
+ import { z } from "zod";
7
+
8
+ import { odk } from "./index.js";
9
+ import { findTypeSpecNodeModules } from "./typespecBridge.js";
10
+
11
+ const tempDirs: string[] = [];
12
+
13
+ const makeTempDir = () => {
14
+ const dir = mkdtempSync(path.join(tmpdir(), "odk-test-"));
15
+ tempDirs.push(dir);
16
+ return dir;
17
+ };
18
+
19
+ afterAll(() => {
20
+ for (const dir of tempDirs) rmSync(dir, { recursive: true, force: true });
21
+ });
22
+
23
+ /** Render a single Zod object as TypeSpec */
24
+ const tspFor = (shape: z.ZodRawShape) =>
25
+ odk.toTypeSpec(
26
+ odk.schema("Test", { Input: z.object(shape) }, { suppressWarnings: true }),
27
+ );
28
+
29
+ describe("Zod to TypeSpec fidelity", () => {
30
+ test("integers emit as safeint without the synthetic safe-integer bounds", () => {
31
+ const tsp = tspFor({ seed: z.number().int(), count: z.int() });
32
+
33
+ expect(tsp).toContain(" seed: safeint;");
34
+ expect(tsp).toContain(" count: safeint;");
35
+ expect(tsp).not.toContain("int64");
36
+ expect(tsp).not.toContain("9007199254740991");
37
+ });
38
+
39
+ test("integers with explicit bounds that fit 32 bits emit as int32", () => {
40
+ const tsp = tspFor({ steps: z.number().int().min(1).max(150) });
41
+
42
+ expect(tsp).toContain("@minValue(1) @maxValue(150) steps: int32;");
43
+ });
44
+
45
+ test("integers with one explicit bound keep it and stay safeint", () => {
46
+ const tsp = tspFor({ n: z.number().int().min(1) });
47
+
48
+ expect(tsp).toContain("@minValue(1) n: safeint;");
49
+ expect(tsp).not.toContain("@maxValue");
50
+ });
51
+
52
+ test("describe() emits @doc on properties and models", () => {
53
+ const tsp = odk.toTypeSpec(
54
+ odk.schema("Test", {
55
+ Input: z
56
+ .object({ prompt: z.string().describe('What "to" generate') })
57
+ .describe("Task input"),
58
+ }),
59
+ );
60
+
61
+ expect(tsp).toContain('@doc("Task input")\n@jsonSchema\nmodel Input {');
62
+ expect(tsp).toContain('@doc("What \\"to\\" generate") prompt: string;');
63
+ });
64
+
65
+ test("default() makes the field optional and emits the default", () => {
66
+ const tsp = tspFor({
67
+ mode: z.enum(["fast", "best"]).default("fast"),
68
+ steps: z.number().int().min(1).max(50).default(20),
69
+ tags: z.array(z.string()).default(["a"]),
70
+ hd: z.boolean().default(false),
71
+ });
72
+
73
+ expect(tsp).toContain(' mode?: "fast" | "best" = "fast";');
74
+ expect(tsp).toContain("@minValue(1) @maxValue(50) steps?: int32 = 20;");
75
+ expect(tsp).toContain(' tags?: string[] = #["a"];');
76
+ expect(tsp).toContain(" hd?: boolean = false;");
77
+ });
78
+
79
+ test("nullable() emits T | null instead of an unknown variant", () => {
80
+ const tsp = tspFor({
81
+ mask: z.string().nullable(),
82
+ maybe: z.string().nullable().optional(),
83
+ level: z.enum(["low", "high"]).nullable(),
84
+ seed: z.number().int().nullable().default(null),
85
+ });
86
+
87
+ expect(tsp).toContain(" mask: string | null;");
88
+ expect(tsp).toContain(" maybe?: string | null;");
89
+ expect(tsp).toContain(' level: "low" | "high" | null;');
90
+ expect(tsp).toContain(" seed?: safeint | null = null;");
91
+ expect(tsp).not.toContain("unknown");
92
+ });
93
+
94
+ test("enums emit as string-literal unions inline and enums at top level", () => {
95
+ const Mode = z.enum(["fast", "best"]);
96
+ const tsp = odk.toTypeSpec(
97
+ odk.schema("Test", { Mode, Input: z.object({ mode: Mode }) }),
98
+ );
99
+
100
+ expect(tsp).toContain("@jsonSchema\nenum Mode {\n fast,\n best,\n}");
101
+ expect(tsp).toContain(' mode: "fast" | "best";');
102
+ });
103
+
104
+ test("arrays keep item types and length bounds", () => {
105
+ const tsp = tspFor({
106
+ images: z.array(z.string()).min(1).max(4),
107
+ sizes: z.array(z.number().int()),
108
+ });
109
+
110
+ expect(tsp).toContain("@minItems(1) @maxItems(4) images: string[];");
111
+ expect(tsp).toContain(" sizes: safeint[];");
112
+ });
113
+
114
+ test("raw blocks and imports are emitted", () => {
115
+ const schema = odk.schema("Test", { Input: z.object({ a: z.string() }) });
116
+ odk.addImport(schema, "@typespec/http");
117
+ odk.raw(schema, '@route("/x") op x(): Input;', "Routes");
118
+
119
+ const tsp = odk.toTypeSpec(schema);
120
+
121
+ expect(tsp).toContain('import "@typespec/http";');
122
+ expect(tsp).toContain("using TypeSpec.Http;");
123
+ expect(tsp).toContain('// Routes\n@route("/x") op x(): Input;');
124
+ });
125
+ });
126
+
127
+ describe("findTypeSpecNodeModules", () => {
128
+ const install = (root: string, pkg: string) =>
129
+ mkdirSync(path.join(root, "node_modules", pkg), { recursive: true });
130
+
131
+ test("finds the consumer's node_modules from a nested directory", () => {
132
+ const root = makeTempDir();
133
+ install(root, "@typespec/compiler");
134
+ install(root, "@typespec/json-schema");
135
+ const nested = path.join(root, "src", "deep");
136
+ mkdirSync(nested, { recursive: true });
137
+
138
+ expect(findTypeSpecNodeModules([nested], ["@typespec/json-schema"])).toBe(
139
+ path.join(root, "node_modules"),
140
+ );
141
+ });
142
+
143
+ test("prefers a node_modules that also has every requested emitter", () => {
144
+ const outer = makeTempDir();
145
+ install(outer, "@typespec/compiler");
146
+ install(outer, "@typespec/openapi3");
147
+ const inner = path.join(outer, "pkg");
148
+ install(inner, "@typespec/compiler");
149
+
150
+ expect(findTypeSpecNodeModules([inner], ["@typespec/openapi3"])).toBe(
151
+ path.join(outer, "node_modules"),
152
+ );
153
+ });
154
+
155
+ test("falls back to the first compiler and then to undefined", () => {
156
+ const root = makeTempDir();
157
+ install(root, "@typespec/compiler");
158
+
159
+ expect(findTypeSpecNodeModules([root], ["@typespec/missing"])).toBe(
160
+ path.join(root, "node_modules"),
161
+ );
162
+ expect(findTypeSpecNodeModules([makeTempDir()], [])).toBeUndefined();
163
+ });
164
+ });
165
+
166
+ describe("emit", () => {
167
+ test("emits JSON Schema and OpenAPI with integers, docs, defaults, and null", async () => {
168
+ const outDir = makeTempDir();
169
+ const schema = odk.schema("Tasks", {
170
+ Input: z.object({
171
+ seed: z.number().int().optional(),
172
+ mode: z.enum(["fast", "best"]).default("fast"),
173
+ mask: z.string().nullable().optional(),
174
+ prompt: z.string().describe("What to generate"),
175
+ }),
176
+ });
177
+
178
+ await odk.emit(schema, {
179
+ targets: ["@typespec/json-schema", "@typespec/openapi3"],
180
+ outDir,
181
+ });
182
+
183
+ const jsonSchema = readFileSync(
184
+ path.join(outDir, "@typespec/json-schema/Input.yaml"),
185
+ "utf-8",
186
+ );
187
+ expect(jsonSchema).toContain("seed:\n type: integer\n");
188
+ expect(jsonSchema).toContain("default: fast");
189
+ expect(jsonSchema).toContain('- type: "null"');
190
+ expect(jsonSchema).toContain("description: What to generate");
191
+ expect(jsonSchema).toContain("required:\n - prompt\n");
192
+
193
+ const openapi = readFileSync(
194
+ path.join(outDir, "@typespec/openapi3/openapi.yaml"),
195
+ "utf-8",
196
+ );
197
+ expect(openapi).toContain("Input:");
198
+ expect(openapi).toContain("nullable: true");
199
+ expect(openapi).toContain("default: fast");
200
+ expect(openapi).toContain("description: What to generate");
201
+ });
202
+ });