@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.
@@ -5,12 +5,16 @@
5
5
  * the TypeSpec compiler to emit to various targets.
6
6
  */
7
7
 
8
+ import { existsSync } from "node:fs";
9
+ import path from "node:path";
10
+
8
11
  import type {
9
12
  CompiledField,
10
13
  CompiledModel,
11
14
  CompiledSchema,
12
15
  CompiledType,
13
16
  CompiledUnion,
17
+ ScalarType,
14
18
  } from "./compile.js";
15
19
 
16
20
  export interface EmitOptions {
@@ -32,35 +36,88 @@ export function compiledSchemaToTypeSpec(
32
36
  const lines: string[] = [];
33
37
  const ns = namespace || schema.name;
34
38
 
35
- // Imports
36
- lines.push('import "@typespec/json-schema";');
39
+ // Imports: JSON Schema is always needed for the @jsonSchema decorator, the
40
+ // rest come from the schema (odk.addImport / SchemaOptions.imports)
41
+ const imports = [
42
+ "@typespec/json-schema",
43
+ ...(schema.imports ?? []).filter((i) => i !== "@typespec/json-schema"),
44
+ ];
45
+ const uniqueImports = [...new Set(imports)];
46
+ for (const importPath of uniqueImports) {
47
+ lines.push(`import "${escapeString(importPath)}";`);
48
+ }
37
49
  lines.push("using TypeSpec.JsonSchema;");
50
+ for (const importPath of uniqueImports) {
51
+ const usingNs = importToUsingNamespace(importPath);
52
+ if (usingNs) lines.push(`using ${usingNs};`);
53
+ }
38
54
  lines.push("");
39
55
 
40
- // Namespace
56
+ // Namespace, declared as a service so the OpenAPI emitter includes its
57
+ // models as component schemas even when no operation references them
58
+ lines.push(`@service(#{ title: "${escapeString(ns)}" })`);
41
59
  lines.push(`namespace ${sanitizeIdentifier(ns)};`);
42
60
  lines.push("");
43
61
 
44
62
  // Emit unions first (enums)
45
63
  for (const union of schema.unions) {
46
- lines.push(emitUnion(union));
64
+ lines.push(emitUnion(union, schema));
47
65
  lines.push("");
48
66
  }
49
67
 
50
68
  // Emit models
51
69
  for (const model of schema.models) {
52
- lines.push(emitModel(model));
70
+ lines.push(emitModel(model, schema));
71
+ lines.push("");
72
+ }
73
+
74
+ // Emit raw TypeSpec blocks (odk.raw escape hatch)
75
+ for (const block of schema.rawBlocks ?? []) {
76
+ if (block.description) lines.push(`// ${block.description}`);
77
+ lines.push(block.content);
53
78
  lines.push("");
54
79
  }
55
80
 
56
81
  return lines.join("\n");
57
82
  }
58
83
 
59
- function emitUnion(union: CompiledUnion): string {
84
+ /**
85
+ * Map a TypeSpec library import to the namespace its decorators live in, so
86
+ * they resolve without qualification (mirrors the Rust CLI bridge).
87
+ */
88
+ function importToUsingNamespace(importPath: string): string | undefined {
89
+ switch (importPath) {
90
+ case "@typespec/http":
91
+ return "TypeSpec.Http";
92
+ case "@typespec/rest":
93
+ return "TypeSpec.Rest";
94
+ case "@typespec/openapi":
95
+ case "@typespec/openapi3":
96
+ return "TypeSpec.OpenAPI";
97
+ case "@typespec/protobuf":
98
+ return "TypeSpec.Protobuf";
99
+ case "@typespec/versioning":
100
+ return "TypeSpec.Versioning";
101
+ case "@typespec/xml":
102
+ return "TypeSpec.Xml";
103
+ case "@typespec/events":
104
+ return "TypeSpec.Events";
105
+ case "@typespec/streams":
106
+ return "TypeSpec.Streams";
107
+ case "@typespec/sse":
108
+ return "TypeSpec.SSE";
109
+ case "@omnidotdev/typespec-drizzle":
110
+ return "Drizzle";
111
+ default:
112
+ return undefined;
113
+ }
114
+ }
115
+
116
+ function emitUnion(union: CompiledUnion, schema: CompiledSchema): string {
60
117
  const lines: string[] = [];
61
118
 
62
119
  if (union.description) {
63
- lines.push(`/** ${union.description} */`);
120
+ lines.push(docDecorator(union.description));
64
121
  }
65
122
 
66
123
  // Check if it's a string literal enum
@@ -69,6 +126,7 @@ function emitUnion(union: CompiledUnion): string {
69
126
  );
70
127
 
71
128
  if (isStringEnum) {
129
+ lines.push("@jsonSchema");
72
130
  lines.push(`enum ${sanitizeIdentifier(union.name)} {`);
73
131
  for (const variant of union.variants) {
74
132
  const value = (variant.type as { kind: "literal"; value: string }).value;
@@ -87,7 +145,7 @@ function emitUnion(union: CompiledUnion): string {
87
145
  } else {
88
146
  // Union type
89
147
  const variantTypes = union.variants
90
- .map((v) => (v.type ? typeToString(v.type) : v.name))
148
+ .map((v) => (v.type ? typeToString(v.type, schema) : v.name))
91
149
  .join(" | ");
92
150
  lines.push(`alias ${sanitizeIdentifier(union.name)} = ${variantTypes};`);
93
151
  }
@@ -95,18 +153,18 @@ function emitUnion(union: CompiledUnion): string {
95
153
  return lines.join("\n");
96
154
  }
97
155
 
98
- function emitModel(model: CompiledModel): string {
156
+ function emitModel(model: CompiledModel, schema: CompiledSchema): string {
99
157
  const lines: string[] = [];
100
158
 
101
159
  if (model.description) {
102
- lines.push(`/** ${model.description} */`);
160
+ lines.push(docDecorator(model.description));
103
161
  }
104
162
 
105
163
  lines.push("@jsonSchema");
106
164
  lines.push(`model ${sanitizeIdentifier(model.name)} {`);
107
165
 
108
166
  for (const field of model.fields) {
109
- lines.push(emitField(field));
167
+ lines.push(` ${emitField(field, schema)};`);
110
168
  }
111
169
 
112
170
  lines.push("}");
@@ -114,9 +172,13 @@ function emitModel(model: CompiledModel): string {
114
172
  return lines.join("\n");
115
173
  }
116
174
 
117
- function emitField(field: CompiledField): string {
175
+ function emitField(field: CompiledField, schema: CompiledSchema): string {
118
176
  const decorators: string[] = [];
119
177
 
178
+ if (field.description) {
179
+ decorators.push(docDecorator(field.description));
180
+ }
181
+
120
182
  // Add constraint decorators
121
183
  if (field.constraints) {
122
184
  const c = field.constraints;
@@ -126,6 +188,8 @@ function emitField(field: CompiledField): string {
126
188
  decorators.push(`@maxLength(${c.maxLength})`);
127
189
  if (c.minValue !== undefined) decorators.push(`@minValue(${c.minValue})`);
128
190
  if (c.maxValue !== undefined) decorators.push(`@maxValue(${c.maxValue})`);
191
+ if (c.minItems !== undefined) decorators.push(`@minItems(${c.minItems})`);
192
+ if (c.maxItems !== undefined) decorators.push(`@maxItems(${c.maxItems})`);
129
193
  if (c.pattern !== undefined)
130
194
  decorators.push(`@pattern("${escapeString(c.pattern)}")`);
131
195
  if (c.multipleOf !== undefined)
@@ -150,25 +214,111 @@ function emitField(field: CompiledField): string {
150
214
  decorators.push('@format("date-time")');
151
215
  break;
152
216
  default:
153
- decorators.push(`@format("${c.format}")`);
217
+ decorators.push(`@format("${escapeString(c.format)}")`);
154
218
  }
155
219
  }
156
220
  }
157
221
 
158
222
  const decoratorStr = decorators.length > 0 ? `${decorators.join(" ")} ` : "";
159
- const optionalMark = field.optional ? "?" : "";
160
- const typeStr = typeToString(field.type);
223
+ // A defaulted field is optional: TypeSpec only allows defaults on optional
224
+ // properties, and callers may omit it
225
+ const defaultValue = defaultToTypeSpec(field.default, field.type, schema);
226
+ const optionalMark = field.optional || defaultValue !== undefined ? "?" : "";
227
+ const baseType = typeToString(field.type, schema);
228
+ const typeStr = field.nullable ? `${baseType} | null` : baseType;
229
+ const defaultStr = defaultValue !== undefined ? ` = ${defaultValue}` : "";
161
230
  const fieldName = sanitizeIdentifier(field.name);
162
231
 
163
- return ` ${decoratorStr}${fieldName}${optionalMark}: ${typeStr};`;
232
+ return `${decoratorStr}${fieldName}${optionalMark}: ${typeStr}${defaultStr}`;
233
+ }
234
+
235
+ /** Scalars whose defaults are plain value literals */
236
+ const LITERAL_DEFAULT_SCALARS = new Set<ScalarType>([
237
+ "string",
238
+ "int32",
239
+ "int64",
240
+ "safeint",
241
+ "float32",
242
+ "float64",
243
+ "boolean",
244
+ "unknown",
245
+ ]);
246
+
247
+ /**
248
+ * Render a field default as a TypeSpec value expression.
249
+ *
250
+ * Returns `undefined` when the default cannot be expressed for the field's
251
+ * type (e.g. a date-time scalar, which needs a constructor call), so the field
252
+ * is emitted without a default instead of failing compilation.
253
+ */
254
+ function defaultToTypeSpec(
255
+ value: unknown,
256
+ type: CompiledType,
257
+ schema: CompiledSchema,
258
+ ): string | undefined {
259
+ if (value === undefined) return undefined;
260
+
261
+ // A reference to a string enum takes a member reference, not a literal
262
+ if (type.kind === "ref") {
263
+ const union = schema.unions.find((u) => u.name === type.name);
264
+ const variant = union?.variants.find(
265
+ (v) => v.type?.kind === "literal" && v.type.value === value,
266
+ );
267
+ if (!union || !variant || !isValidIdentifier(variant.name)) {
268
+ return undefined;
269
+ }
270
+ return `${sanitizeIdentifier(union.name)}.${variant.name}`;
271
+ }
272
+
273
+ if (type.kind === "scalar" && !LITERAL_DEFAULT_SCALARS.has(type.name)) {
274
+ return undefined;
275
+ }
276
+
277
+ return valueToTypeSpec(value);
278
+ }
279
+
280
+ /** Render a JSON value as a TypeSpec value literal */
281
+ function valueToTypeSpec(value: unknown): string | undefined {
282
+ if (value === null) return "null";
283
+ if (typeof value === "string") return `"${escapeString(value)}"`;
284
+ if (typeof value === "number") {
285
+ return Number.isFinite(value) ? String(value) : undefined;
286
+ }
287
+ if (typeof value === "boolean") return String(value);
288
+ if (Array.isArray(value)) {
289
+ const items = value.map(valueToTypeSpec);
290
+ if (items.some((i) => i === undefined)) return undefined;
291
+ return `#[${items.join(", ")}]`;
292
+ }
293
+ if (typeof value === "object") {
294
+ const entries = Object.entries(value as Record<string, unknown>).map(
295
+ ([k, v]) => {
296
+ const rendered = valueToTypeSpec(v);
297
+ if (rendered === undefined) return undefined;
298
+ const key = isValidIdentifier(k) ? k : `\`${k.replace(/`/g, "\\`")}\``;
299
+ return `${key}: ${rendered}`;
300
+ },
301
+ );
302
+ if (entries.some((e) => e === undefined)) return undefined;
303
+ return `#{${entries.join(", ")}}`;
304
+ }
305
+ return undefined;
306
+ }
307
+
308
+ /** Render a description as a @doc decorator */
309
+ function docDecorator(description: string): string {
310
+ return `@doc("${escapeString(description)}")`;
164
311
  }
165
312
 
166
- function typeToString(type: CompiledType): string {
313
+ function typeToString(type: CompiledType, schema: CompiledSchema): string {
167
314
  switch (type.kind) {
168
315
  case "scalar":
169
316
  return scalarToTypeSpec(type.name);
170
- case "array":
171
- return `${typeToString(type.items)}[]`;
317
+ case "array": {
318
+ const items = typeToString(type.items, schema);
319
+ // Parenthesize unions so `[]` applies to the whole union
320
+ return type.items.kind === "union" ? `(${items})[]` : `${items}[]`;
321
+ }
172
322
  case "ref":
173
323
  return sanitizeIdentifier(type.name);
174
324
  case "literal":
@@ -177,14 +327,9 @@ function typeToString(type: CompiledType): string {
177
327
  }
178
328
  return String(type.value);
179
329
  case "union":
180
- return type.variants.map(typeToString).join(" | ");
330
+ return type.variants.map((v) => typeToString(v, schema)).join(" | ");
181
331
  case "object": {
182
- const fields = type.fields
183
- .map((f) => {
184
- const opt = f.optional ? "?" : "";
185
- return `${f.name}${opt}: ${typeToString(f.type)}`;
186
- })
187
- .join("; ");
332
+ const fields = type.fields.map((f) => emitField(f, schema)).join("; ");
188
333
  return `{ ${fields} }`;
189
334
  }
190
335
  default:
@@ -200,6 +345,8 @@ function scalarToTypeSpec(scalar: string): string {
200
345
  return "int32";
201
346
  case "int64":
202
347
  return "int64";
348
+ case "safeint":
349
+ return "safeint";
203
350
  case "float32":
204
351
  return "float32";
205
352
  case "float64":
@@ -232,7 +379,49 @@ function isValidIdentifier(name: string): boolean {
232
379
  }
233
380
 
234
381
  function escapeString(s: string): string {
235
- return s.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
382
+ return s
383
+ .replace(/\\/g, "\\\\")
384
+ .replace(/"/g, '\\"')
385
+ .replace(/\n/g, "\\n")
386
+ .replace(/\r/g, "\\r")
387
+ .replace(/\t/g, "\\t")
388
+ .replace(/\$\{/g, "\\${");
389
+ }
390
+
391
+ /**
392
+ * Find the `node_modules` directory that provides the TypeSpec toolchain.
393
+ *
394
+ * Walks up from each start directory (in order) the way Node resolves
395
+ * packages, and returns the first `node_modules` containing
396
+ * `@typespec/compiler` and every requested package. If none has them all, the
397
+ * first one containing the compiler wins, so emitter resolution errors still
398
+ * come from the compiler with a useful message. Returns `undefined` when no
399
+ * compiler is found.
400
+ */
401
+ export function findTypeSpecNodeModules(
402
+ startDirs: string[],
403
+ packages: string[],
404
+ ): string | undefined {
405
+ let compilerOnly: string | undefined;
406
+
407
+ for (const start of startDirs) {
408
+ let dir = path.resolve(start);
409
+ while (true) {
410
+ const candidate = path.join(dir, "node_modules");
411
+ if (existsSync(path.join(candidate, "@typespec", "compiler"))) {
412
+ if (packages.every((p) => existsSync(path.join(candidate, p)))) {
413
+ return candidate;
414
+ }
415
+ compilerOnly ??= candidate;
416
+ }
417
+
418
+ const parent = path.dirname(dir);
419
+ if (parent === dir) break;
420
+ dir = parent;
421
+ }
422
+ }
423
+
424
+ return compilerOnly;
236
425
  }
237
426
 
238
427
  /**
@@ -248,7 +437,6 @@ export async function emitToTargets(
248
437
  const { targets, outDir, namespace } = options;
249
438
 
250
439
  const fs = await import("node:fs/promises");
251
- const path = await import("node:path");
252
440
  const os = await import("node:os");
253
441
 
254
442
  // Generate TypeSpec source
@@ -278,16 +466,21 @@ export async function emitToTargets(
278
466
  "utf-8",
279
467
  );
280
468
 
281
- // Symlink node_modules from odk-ts to the temp directory
282
- // This avoids having to install packages
283
- const odkNodeModules = path.resolve(import.meta.dirname, "../node_modules");
469
+ // Symlink the node_modules holding the TypeSpec toolchain into the temp
470
+ // project so the compiler can resolve the imported emitters without an
471
+ // install. This is the consumer's node_modules when ODK is a dependency
472
+ const toolchainNodeModules =
473
+ findTypeSpecNodeModules(
474
+ [process.cwd(), import.meta.dirname],
475
+ ["@typespec/json-schema", ...targets],
476
+ ) ?? path.resolve(import.meta.dirname, "../node_modules");
284
477
  const tempNodeModules = path.join(tempDir, "node_modules");
285
478
 
286
479
  try {
287
- await fs.symlink(odkNodeModules, tempNodeModules, "dir");
480
+ await fs.symlink(toolchainNodeModules, tempNodeModules, "dir");
288
481
  } catch {
289
- // If symlink fails (e.g., on Windows without admin), copy the approach below
290
- // For now, just try to compile with the current working directory
482
+ // Symlinks can fail (e.g. Windows without privileges); compilation then
483
+ // falls back to resolving from the temp directory's ancestors
291
484
  }
292
485
 
293
486
  // Create tspconfig.yaml