@ventrata/octo-types 0.0.16 → 0.0.18

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.
@@ -222,13 +222,22 @@ function toPascalCase(name: string): string {
222
222
  async function fixCircularDependencies(schemasDir: string): Promise<void> {
223
223
  const schemaFiles = glob.sync('**/*.ts', { cwd: schemasDir });
224
224
  const dependencyGraph = new Map<string, Set<string>>();
225
- const schemaContents = new Map<string, string>();
225
+ const schemaContents = new Map<
226
+ string,
227
+ {
228
+ content: string;
229
+ relativePath: string;
230
+ }
231
+ >();
226
232
 
227
233
  for (const schemaFile of schemaFiles) {
228
234
  const baseName = path.basename(schemaFile, '.ts');
229
235
  const schemaFilePath = path.join(schemasDir, schemaFile);
230
236
  const content = await promises.readFile(schemaFilePath, 'utf-8');
231
- schemaContents.set(baseName, content);
237
+ schemaContents.set(baseName, {
238
+ content,
239
+ relativePath: schemaFile,
240
+ });
232
241
 
233
242
  const dependencies = new Set<string>();
234
243
  const importRegex = /import\s+\{[^}]*\}\s+from\s+['"]([^'"]+)['"]/g;
@@ -247,25 +256,28 @@ async function fixCircularDependencies(schemasDir: string): Promise<void> {
247
256
  }
248
257
 
249
258
  const visited = new Set<string>();
250
- const recursionStack = new Set<string>();
259
+ const recursionStack: string[] = [];
251
260
  const circularSchemas = new Set<string>();
252
261
 
253
262
  function detectCycles(node: string): void {
254
- if (recursionStack.has(node)) {
255
- circularSchemas.add(node);
263
+ const existingIndex = recursionStack.indexOf(node);
264
+ if (existingIndex !== -1) {
265
+ for (const schema of recursionStack.slice(existingIndex)) {
266
+ circularSchemas.add(schema);
267
+ }
256
268
  return;
257
269
  }
258
270
  if (visited.has(node)) return;
259
271
 
260
272
  visited.add(node);
261
- recursionStack.add(node);
273
+ recursionStack.push(node);
262
274
 
263
275
  const dependencies = dependencyGraph.get(node) || new Set();
264
276
  for (const dep of dependencies) {
265
277
  detectCycles(dep);
266
278
  }
267
279
 
268
- recursionStack.delete(node);
280
+ recursionStack.pop();
269
281
  }
270
282
 
271
283
  for (const schema of dependencyGraph.keys()) {
@@ -275,47 +287,125 @@ async function fixCircularDependencies(schemasDir: string): Promise<void> {
275
287
  }
276
288
 
277
289
  for (const schemaName of circularSchemas) {
278
- const content = schemaContents.get(schemaName);
279
- if (!content) continue;
290
+ const metadata = schemaContents.get(schemaName);
291
+ if (!metadata) continue;
292
+ const { content, relativePath } = metadata;
280
293
 
281
- const exportConstRegex = /export\s+const\s+(\w+Schema)\s*=\s*z\.(object|union|array|record|tuple|map)\s*\(/;
282
- const match = content.match(exportConstRegex);
283
- if (!match) continue;
294
+ const exportMatches = Array.from(content.matchAll(/export\s+const\s+(\w+Schema)\s*=/g));
295
+ if (exportMatches.length === 0) continue;
284
296
 
285
- const schemaVarName = match[1];
286
- const typeName = toPascalCase(schemaName);
287
-
288
- const importTypeLine = `import { type ${typeName} } from "../models/${typeName}";`;
289
297
  let updatedContent = content;
298
+ const seenImports = new Set<string>();
290
299
 
291
- if (!content.includes(importTypeLine)) {
292
- const lines = content.split('\n');
293
- const insertAt = Math.min(3, lines.length);
294
- lines.splice(insertAt, 0, importTypeLine);
295
- updatedContent = lines.join('\n');
296
- }
300
+ for (const match of exportMatches) {
301
+ const schemaVarName = match[1];
302
+ const baseTypeName = schemaVarName.replace(/Schema$/, '');
303
+ const typeName = toPascalCase(baseTypeName);
304
+ const importTypeLine = getTypeImportLine(relativePath, typeName, schemasDir);
297
305
 
298
- const annotatedLazy = `export const ${schemaVarName}: z.ZodSchema<${typeName}> = z.lazy(() => z.$2(`;
299
- updatedContent = updatedContent.replace(exportConstRegex, annotatedLazy);
300
-
301
- const exportStart = updatedContent.indexOf(`export const ${schemaVarName}`);
302
- if (exportStart !== -1) {
303
- const afterStart = updatedContent.slice(exportStart);
304
- const closeIdx = afterStart.indexOf('});');
305
- if (closeIdx !== -1) {
306
- updatedContent =
307
- updatedContent.slice(0, exportStart) +
308
- afterStart.slice(0, closeIdx) +
309
- '}));' +
310
- afterStart.slice(closeIdx + 3);
306
+ if (!seenImports.has(importTypeLine)) {
307
+ updatedContent = ensureTypeImport(updatedContent, importTypeLine);
308
+ seenImports.add(importTypeLine);
311
309
  }
310
+
311
+ updatedContent = ensureSchemaIsLazy(updatedContent, schemaVarName, typeName);
312
312
  }
313
313
 
314
- const schemaFilePath = path.join(schemasDir, `${schemaName}.ts`);
314
+ const schemaFilePath = path.join(schemasDir, relativePath);
315
315
  await promises.writeFile(schemaFilePath, updatedContent);
316
316
  }
317
317
  }
318
318
 
319
+ function ensureTypeImport(content: string, importLine: string): string {
320
+ if (content.includes(importLine)) {
321
+ return content;
322
+ }
323
+
324
+ const lines = content.split('\n');
325
+ const trimmedImport = importLine.trimEnd();
326
+ const firstImportIndex = lines.findIndex((line) => line.startsWith('import '));
327
+
328
+ if (firstImportIndex !== -1) {
329
+ lines.splice(firstImportIndex, 0, trimmedImport);
330
+ } else {
331
+ let insertAt = 0;
332
+ while (insertAt < lines.length && lines[insertAt].startsWith('//')) {
333
+ insertAt += 1;
334
+ }
335
+ lines.splice(insertAt, 0, trimmedImport);
336
+ }
337
+
338
+ return lines.join('\n');
339
+ }
340
+
341
+ function ensureSchemaIsLazy(content: string, schemaVarName: string, typeName: string): string {
342
+ const exportRegex = new RegExp(`export\\s+const\\s+${schemaVarName}\\s*[:=]`);
343
+ if (!exportRegex.test(content)) {
344
+ return content;
345
+ }
346
+
347
+ let updatedContent = content;
348
+ const annotationRegex = new RegExp(`export\\s+const\\s+${schemaVarName}\\s*:\\s*z\\.ZodSchema<${typeName}>\\s*=`);
349
+ if (!annotationRegex.test(updatedContent)) {
350
+ const assignmentRegex = new RegExp(`export\\s+const\\s+${schemaVarName}\\s*=\\s*`);
351
+ updatedContent = updatedContent.replace(
352
+ assignmentRegex,
353
+ `export const ${schemaVarName}: z.ZodSchema<${typeName}> = `,
354
+ );
355
+ }
356
+
357
+ const exportIndex = updatedContent.indexOf(`export const ${schemaVarName}`);
358
+ if (exportIndex === -1) return updatedContent;
359
+
360
+ const equalsIndex = updatedContent.indexOf('=', exportIndex);
361
+ if (equalsIndex === -1) return updatedContent;
362
+
363
+ const semicolonIndex = findExpressionEnd(updatedContent, equalsIndex + 1);
364
+ if (semicolonIndex === -1) return updatedContent;
365
+
366
+ const expression = updatedContent.slice(equalsIndex + 1, semicolonIndex);
367
+ const trimmedExpression = expression.trimStart();
368
+
369
+ if (trimmedExpression.startsWith('z.lazy')) {
370
+ return updatedContent;
371
+ }
372
+
373
+ const leadingWhitespace = expression.slice(0, expression.length - trimmedExpression.length);
374
+ const wrappedExpression = `${leadingWhitespace}z.lazy(() => ${trimmedExpression})`;
375
+
376
+ return updatedContent.slice(0, equalsIndex + 1) + wrappedExpression + updatedContent.slice(semicolonIndex);
377
+ }
378
+
379
+ function getTypeImportLine(relativeSchemaPath: string, typeName: string, schemasDir: string): string {
380
+ const schemaFileDir = path.dirname(path.join(schemasDir, relativeSchemaPath));
381
+ const modelsDir = path.join(process.cwd(), CONFIG.relativePaths.models);
382
+ const targetTypePath = path.join(modelsDir, typeName);
383
+ let importPath = path.relative(schemaFileDir, targetTypePath);
384
+
385
+ if (!importPath.startsWith('.')) {
386
+ importPath = `./${importPath}`;
387
+ }
388
+
389
+ importPath = importPath.split(path.sep).join('/');
390
+
391
+ return `import { type ${typeName} } from '${importPath}';`;
392
+ }
393
+
394
+ function findExpressionEnd(content: string, startIndex: number): number {
395
+ let depth = 0;
396
+ for (let idx = startIndex; idx < content.length; idx++) {
397
+ const char = content[idx];
398
+ if (char === '(' || char === '{' || char === '[') {
399
+ depth += 1;
400
+ } else if (char === ')' || char === '}' || char === ']') {
401
+ depth = Math.max(depth - 1, 0);
402
+ } else if (char === ';' && depth === 0) {
403
+ return idx;
404
+ }
405
+ }
406
+ return -1;
407
+ }
408
+
319
409
  async function updateIndexFileWithSchemas(schemasDir: string): Promise<void> {
320
410
  try {
321
411
  const projectRoot = process.cwd();