@omnidotdev/odk 0.0.0-stage → 0.1.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.
@@ -0,0 +1,338 @@
1
+ /**
2
+ * TypeSpec Bridge
3
+ *
4
+ * Converts CompiledSchema to TypeSpec source code, then uses
5
+ * the TypeSpec compiler to emit to various targets.
6
+ */
7
+
8
+ import type {
9
+ CompiledSchema,
10
+ CompiledModel,
11
+ CompiledUnion,
12
+ CompiledField,
13
+ CompiledType,
14
+ } from "./compile.js";
15
+
16
+ export interface EmitOptions {
17
+ /** Target emitters (e.g., "@typespec/openapi3", "@typespec/protobuf") */
18
+ targets: string[];
19
+ /** Output directory */
20
+ outDir: string;
21
+ /** Namespace for generated TypeSpec */
22
+ namespace?: string;
23
+ }
24
+
25
+ /**
26
+ * Convert CompiledSchema to TypeSpec source code.
27
+ */
28
+ export function compiledSchemaToTypeSpec(
29
+ schema: CompiledSchema,
30
+ namespace?: string,
31
+ ): string {
32
+ const lines: string[] = [];
33
+ const ns = namespace || schema.name;
34
+
35
+ // Imports
36
+ lines.push('import "@typespec/json-schema";');
37
+ lines.push("using TypeSpec.JsonSchema;");
38
+ lines.push("");
39
+
40
+ // Namespace
41
+ lines.push(`namespace ${sanitizeIdentifier(ns)};`);
42
+ lines.push("");
43
+
44
+ // Emit unions first (enums)
45
+ for (const union of schema.unions) {
46
+ lines.push(emitUnion(union));
47
+ lines.push("");
48
+ }
49
+
50
+ // Emit models
51
+ for (const model of schema.models) {
52
+ lines.push(emitModel(model));
53
+ lines.push("");
54
+ }
55
+
56
+ return lines.join("\n");
57
+ }
58
+
59
+ function emitUnion(union: CompiledUnion): string {
60
+ const lines: string[] = [];
61
+
62
+ if (union.description) {
63
+ lines.push(`/** ${union.description} */`);
64
+ }
65
+
66
+ // Check if it's a string literal enum
67
+ const isStringEnum = union.variants.every(
68
+ (v) => v.type?.kind === "literal" && typeof v.type.value === "string",
69
+ );
70
+
71
+ if (isStringEnum) {
72
+ lines.push(`enum ${sanitizeIdentifier(union.name)} {`);
73
+ for (const variant of union.variants) {
74
+ const value = (variant.type as { kind: "literal"; value: string }).value;
75
+ // If the name is a valid identifier, use it; otherwise quote it
76
+ if (isValidIdentifier(variant.name)) {
77
+ if (variant.name === value) {
78
+ lines.push(` ${variant.name},`);
79
+ } else {
80
+ lines.push(` ${variant.name}: "${value}",`);
81
+ }
82
+ } else {
83
+ lines.push(` "${value}",`);
84
+ }
85
+ }
86
+ lines.push("}");
87
+ } else {
88
+ // Union type
89
+ const variantTypes = union.variants
90
+ .map((v) => (v.type ? typeToString(v.type) : v.name))
91
+ .join(" | ");
92
+ lines.push(`alias ${sanitizeIdentifier(union.name)} = ${variantTypes};`);
93
+ }
94
+
95
+ return lines.join("\n");
96
+ }
97
+
98
+ function emitModel(model: CompiledModel): string {
99
+ const lines: string[] = [];
100
+
101
+ if (model.description) {
102
+ lines.push(`/** ${model.description} */`);
103
+ }
104
+
105
+ lines.push("@jsonSchema");
106
+ lines.push(`model ${sanitizeIdentifier(model.name)} {`);
107
+
108
+ for (const field of model.fields) {
109
+ lines.push(emitField(field));
110
+ }
111
+
112
+ lines.push("}");
113
+
114
+ return lines.join("\n");
115
+ }
116
+
117
+ function emitField(field: CompiledField): string {
118
+ const decorators: string[] = [];
119
+
120
+ // Add constraint decorators
121
+ if (field.constraints) {
122
+ const c = field.constraints;
123
+ if (c.minLength !== undefined)
124
+ decorators.push(`@minLength(${c.minLength})`);
125
+ if (c.maxLength !== undefined)
126
+ decorators.push(`@maxLength(${c.maxLength})`);
127
+ if (c.minValue !== undefined) decorators.push(`@minValue(${c.minValue})`);
128
+ if (c.maxValue !== undefined) decorators.push(`@maxValue(${c.maxValue})`);
129
+ if (c.pattern !== undefined)
130
+ decorators.push(`@pattern("${escapeString(c.pattern)}")`);
131
+ if (c.multipleOf !== undefined)
132
+ decorators.push(`@multipleOf(${c.multipleOf})`);
133
+ if (c.format !== undefined) {
134
+ // Map common formats to TypeSpec decorators
135
+ switch (c.format) {
136
+ case "uuid":
137
+ decorators.push('@format("uuid")');
138
+ break;
139
+ case "email":
140
+ decorators.push('@format("email")');
141
+ break;
142
+ case "uri":
143
+ case "url":
144
+ decorators.push('@format("uri")');
145
+ break;
146
+ case "date":
147
+ decorators.push('@format("date")');
148
+ break;
149
+ case "date-time":
150
+ decorators.push('@format("date-time")');
151
+ break;
152
+ default:
153
+ decorators.push(`@format("${c.format}")`);
154
+ }
155
+ }
156
+ }
157
+
158
+ const decoratorStr = decorators.length > 0 ? decorators.join(" ") + " " : "";
159
+ const optionalMark = field.optional ? "?" : "";
160
+ const typeStr = typeToString(field.type);
161
+ const fieldName = sanitizeIdentifier(field.name);
162
+
163
+ return ` ${decoratorStr}${fieldName}${optionalMark}: ${typeStr};`;
164
+ }
165
+
166
+ function typeToString(type: CompiledType): string {
167
+ switch (type.kind) {
168
+ case "scalar":
169
+ return scalarToTypeSpec(type.name);
170
+ case "array":
171
+ return `${typeToString(type.items)}[]`;
172
+ case "ref":
173
+ return sanitizeIdentifier(type.name);
174
+ case "literal":
175
+ if (typeof type.value === "string") {
176
+ return `"${escapeString(type.value)}"`;
177
+ }
178
+ return String(type.value);
179
+ case "union":
180
+ return type.variants.map(typeToString).join(" | ");
181
+ 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("; ");
188
+ return `{ ${fields} }`;
189
+ default:
190
+ return "unknown";
191
+ }
192
+ }
193
+
194
+ function scalarToTypeSpec(scalar: string): string {
195
+ switch (scalar) {
196
+ case "string":
197
+ return "string";
198
+ case "int32":
199
+ return "int32";
200
+ case "int64":
201
+ return "int64";
202
+ case "float32":
203
+ return "float32";
204
+ case "float64":
205
+ return "float64";
206
+ case "boolean":
207
+ return "boolean";
208
+ case "date":
209
+ return "plainDate";
210
+ case "datetime":
211
+ return "utcDateTime";
212
+ case "bytes":
213
+ return "bytes";
214
+ default:
215
+ return "unknown";
216
+ }
217
+ }
218
+
219
+ function sanitizeIdentifier(name: string): string {
220
+ // Replace invalid characters with underscores
221
+ let sanitized = name.replace(/[^A-Za-z0-9_]/g, "_");
222
+ // Ensure it doesn't start with a number
223
+ if (/^[0-9]/.test(sanitized)) {
224
+ sanitized = "_" + sanitized;
225
+ }
226
+ return sanitized || "_";
227
+ }
228
+
229
+ function isValidIdentifier(name: string): boolean {
230
+ return /^[A-Za-z_][A-Za-z0-9_]*$/.test(name);
231
+ }
232
+
233
+ function escapeString(s: string): string {
234
+ return s.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
235
+ }
236
+
237
+ /**
238
+ * Emit CompiledSchema to target formats using TypeSpec compiler.
239
+ *
240
+ * This creates a temporary TypeSpec project with proper package.json
241
+ * to resolve emitter dependencies.
242
+ */
243
+ export async function emitToTargets(
244
+ schema: CompiledSchema,
245
+ options: EmitOptions,
246
+ ): Promise<void> {
247
+ const { targets, outDir, namespace } = options;
248
+
249
+ const fs = await import("node:fs/promises");
250
+ const path = await import("node:path");
251
+ const os = await import("node:os");
252
+
253
+ // Generate TypeSpec source
254
+ const tspSource = compiledSchemaToTypeSpec(schema, namespace);
255
+
256
+ // Create temp directory with a proper TypeSpec project structure
257
+ const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), "odk-"));
258
+ const tspPath = path.join(tempDir, "main.tsp");
259
+
260
+ try {
261
+ // Write the TypeSpec source
262
+ await fs.writeFile(tspPath, tspSource, "utf-8");
263
+
264
+ // Create package.json with dependencies so TypeSpec can find them
265
+ const packageJson = {
266
+ name: "odk-temp-project",
267
+ type: "module",
268
+ dependencies: {
269
+ "@typespec/compiler": "*",
270
+ "@typespec/json-schema": "*",
271
+ ...Object.fromEntries(targets.map((t) => [t, "*"])),
272
+ },
273
+ };
274
+ await fs.writeFile(
275
+ path.join(tempDir, "package.json"),
276
+ JSON.stringify(packageJson, null, 2),
277
+ "utf-8",
278
+ );
279
+
280
+ // Symlink node_modules from odk-ts to the temp directory
281
+ // This avoids having to install packages
282
+ const odkNodeModules = path.resolve(import.meta.dirname, "../node_modules");
283
+ const tempNodeModules = path.join(tempDir, "node_modules");
284
+
285
+ try {
286
+ await fs.symlink(odkNodeModules, tempNodeModules, "dir");
287
+ } catch {
288
+ // If symlink fails (e.g., on Windows without admin), copy the approach below
289
+ // For now, just try to compile with the current working directory
290
+ }
291
+
292
+ // Create tspconfig.yaml
293
+ const absoluteOutDir = path.resolve(process.cwd(), outDir);
294
+ const tspConfigContent = `
295
+ emit:
296
+ ${targets.map((t) => ` - "${t}"`).join("\n")}
297
+ options:
298
+ ${targets.map((t) => ` "${t}":\n output-dir: "${absoluteOutDir}"`).join("\n")}
299
+ `;
300
+ await fs.writeFile(
301
+ path.join(tempDir, "tspconfig.yaml"),
302
+ tspConfigContent,
303
+ "utf-8",
304
+ );
305
+
306
+ // Ensure output directory exists
307
+ await fs.mkdir(absoluteOutDir, { recursive: true });
308
+
309
+ // Run TypeSpec compiler
310
+ const { compile, NodeHost } = await import("@typespec/compiler");
311
+ const program = await compile(NodeHost, tspPath, {
312
+ outputDir: absoluteOutDir,
313
+ emit: targets,
314
+ });
315
+
316
+ if (program.diagnostics.length > 0) {
317
+ for (const diag of program.diagnostics) {
318
+ if (diag.severity === "error") {
319
+ console.error(`TypeSpec error: ${diag.message}`);
320
+ } else {
321
+ console.warn(`TypeSpec warning: ${diag.message}`);
322
+ }
323
+ }
324
+
325
+ const errors = program.diagnostics.filter((d) => d.severity === "error");
326
+ if (errors.length > 0) {
327
+ throw new Error(
328
+ `TypeSpec compilation failed with ${errors.length} errors`,
329
+ );
330
+ }
331
+ }
332
+
333
+ console.log(`Emitted to ${absoluteOutDir}`);
334
+ } finally {
335
+ // Cleanup temp files
336
+ await fs.rm(tempDir, { recursive: true, force: true });
337
+ }
338
+ }