@atomic-ehr/codegen 0.0.2-canary.20251121141554.c9f1e0b → 0.0.2-canary.20251121164115.c134ba7

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/dist/index.js CHANGED
@@ -44,51 +44,71 @@ var typeSchemaInfo = (schema) => {
44
44
  var FileSystemWriter = class {
45
45
  opts;
46
46
  currentDir;
47
- currentFileDescriptor;
48
- writtenFilesSet = /* @__PURE__ */ new Set();
47
+ currentFile;
48
+ writtenFilesBuffer = {};
49
49
  constructor(opts) {
50
50
  this.opts = opts;
51
- this.currentDir = opts.outputDir;
51
+ }
52
+ setOutputDir(path) {
53
+ if (this.currentDir) throw new Error("Can't change output dir while writing");
54
+ this.opts.outputDir = path;
52
55
  }
53
56
  logger() {
54
57
  return this.opts.logger;
55
58
  }
59
+ onDiskMkDir(path) {
60
+ if (this.opts.inMemoryOnly) return;
61
+ if (!fs.existsSync(path)) {
62
+ fs.mkdirSync(path, { recursive: true });
63
+ }
64
+ }
65
+ onDiskOpenFile(relPath) {
66
+ if (this.opts.inMemoryOnly) return -1;
67
+ return fs.openSync(relPath, "w");
68
+ }
69
+ onDiskCloseFile(descriptor) {
70
+ if (this.opts.inMemoryOnly) return;
71
+ fs.fsyncSync(descriptor);
72
+ fs.closeSync(descriptor);
73
+ }
74
+ onDiskWrite(descriptor, token) {
75
+ if (this.opts.inMemoryOnly) return;
76
+ fs.writeSync(descriptor, token);
77
+ }
56
78
  cd(path, gen) {
57
79
  const prev = this.currentDir;
58
- this.currentDir = path.startsWith("/") ? Path4.join(this.opts.outputDir, path) : Path4.join(this.currentDir, path);
59
- if (!fs.existsSync(this.currentDir)) {
60
- fs.mkdirSync(this.currentDir, { recursive: true });
61
- }
80
+ this.currentDir = path.startsWith("/") ? Path4.join(this.opts.outputDir, path) : Path4.join(this.currentDir ?? this.opts.outputDir, path);
81
+ this.onDiskMkDir(this.currentDir);
62
82
  this.logger()?.debug(`cd '${this.currentDir}'`);
63
83
  gen();
64
84
  this.currentDir = prev;
65
85
  }
66
86
  cat(fn, gen) {
67
- if (this.currentFileDescriptor) throw new Error("Can't open file in file");
87
+ if (this.currentFile) throw new Error("Can't open file when another file is open");
68
88
  if (fn.includes("/")) throw new Error(`Change file path separatly: ${fn}`);
69
- const fullFn = `${this.currentDir}/${fn}`;
89
+ const relPath = Path4.normalize(`${this.currentDir}/${fn}`);
70
90
  try {
71
- this.currentFileDescriptor = fs.openSync(fullFn, "w");
72
- this.writtenFilesSet.add(fn);
73
- this.logger()?.debug(`cat > '${fullFn}'`);
91
+ const descriptor = this.onDiskOpenFile(relPath);
92
+ this.logger()?.debug(`cat > '${relPath}'`);
93
+ this.currentFile = { descriptor, relPath };
94
+ this.writtenFilesBuffer[this.currentFile.relPath] = { relPath, absPath: Path4.resolve(relPath), tokens: [] };
74
95
  gen();
75
96
  } finally {
76
- if (this.currentFileDescriptor) {
77
- fs.fsyncSync(this.currentFileDescriptor);
78
- fs.closeSync(this.currentFileDescriptor);
79
- }
80
- this.currentFileDescriptor = void 0;
97
+ if (this.currentFile) this.onDiskCloseFile(this.currentFile.descriptor);
98
+ this.currentFile = void 0;
81
99
  }
82
100
  }
83
101
  write(str) {
84
- if (!this.currentFileDescriptor) throw new Error("No file opened");
85
- fs.writeSync(this.currentFileDescriptor, str);
86
- }
87
- async generate(_tsIndex) {
88
- throw new Error("Not implemented");
102
+ if (!this.currentFile) throw new Error("No file opened");
103
+ this.onDiskWrite(this.currentFile.descriptor, str);
104
+ const buf = this.writtenFilesBuffer[this.currentFile.relPath];
105
+ if (!buf) throw new Error("No buffer found");
106
+ buf.tokens.push(str);
89
107
  }
90
108
  writtenFiles() {
91
- return Array.from(this.writtenFilesSet);
109
+ return Object.values(this.writtenFilesBuffer).map(({ relPath, absPath, tokens }) => {
110
+ return { relPath, absPath, content: tokens.join() };
111
+ }).sort((a, b) => a.relPath.localeCompare(b.relPath));
92
112
  }
93
113
  };
94
114
  var Writer = class extends FileSystemWriter {
@@ -1360,7 +1380,7 @@ var mkTypeSchemaIndex = (schemas, logger) => {
1360
1380
  append(schema);
1361
1381
  }
1362
1382
  const relations = resourceRelatives(schemas);
1363
- const resolve2 = (id) => index[id.url]?.[id.package];
1383
+ const resolve3 = (id) => index[id.url]?.[id.package];
1364
1384
  const resolveByUrl = (pkgName, url) => index[url]?.[pkgName];
1365
1385
  const resourceChildren = (id) => {
1366
1386
  return relations.filter((relative) => relative.parent.name === id.name).map((relative) => relative.child);
@@ -1372,7 +1392,7 @@ var mkTypeSchemaIndex = (schemas, logger) => {
1372
1392
  res.push(cur);
1373
1393
  const base = cur.base;
1374
1394
  if (base === void 0) break;
1375
- const resolved = resolve2(base);
1395
+ const resolved = resolve3(base);
1376
1396
  if (!resolved) {
1377
1397
  logger?.warn(
1378
1398
  `Failed to resolve base type: ${res.map((e) => `${e.identifier.url} (${e.identifier.kind})`).join(", ")}`
@@ -1398,7 +1418,7 @@ var mkTypeSchemaIndex = (schemas, logger) => {
1398
1418
  return nonConstraintSchema;
1399
1419
  };
1400
1420
  const findLastSpecializationByIdentifier = (id) => {
1401
- const schema = resolve2(id);
1421
+ const schema = resolve3(id);
1402
1422
  if (!schema) return id;
1403
1423
  return findLastSpecialization(schema).identifier;
1404
1424
  };
@@ -1470,7 +1490,7 @@ var mkTypeSchemaIndex = (schemas, logger) => {
1470
1490
  collectResources: () => schemas.filter(isResourceTypeSchema),
1471
1491
  collectLogicalModels: () => schemas.filter(isLogicalTypeSchema),
1472
1492
  collectProfiles: () => schemas.filter(isProfileTypeSchema),
1473
- resolve: resolve2,
1493
+ resolve: resolve3,
1474
1494
  resolveByUrl,
1475
1495
  resourceChildren,
1476
1496
  tryHierarchy,
@@ -2054,25 +2074,6 @@ var TypeScript = class extends Writer {
2054
2074
  };
2055
2075
 
2056
2076
  // src/api/builder.ts
2057
- var writerToGenerator = (writerGen) => {
2058
- const getGeneratedFiles = () => {
2059
- return writerGen.writtenFiles().map((fn) => {
2060
- return {
2061
- path: Path4.normalize(Path4.join(writerGen.opts.outputDir, fn)),
2062
- filename: fn.replace(/^.*[\\/]/, ""),
2063
- timestamp: /* @__PURE__ */ new Date()
2064
- };
2065
- });
2066
- };
2067
- return {
2068
- generate: async ({ index: tsIndex }) => {
2069
- await writerGen.generate(tsIndex);
2070
- return getGeneratedFiles();
2071
- },
2072
- setOutputDir: (outputDir) => writerGen.opts.outputDir = outputDir,
2073
- build: async (_input) => getGeneratedFiles()
2074
- };
2075
- };
2076
2077
  var normalizeFileName = (str) => {
2077
2078
  const res = str.replace(/[^a-zA-Z0-9\-_.@#()]/g, "");
2078
2079
  if (res.length === 0) return "unknown";
@@ -2217,25 +2218,23 @@ var APIBuilder = class {
2217
2218
  ...defaultTsOpts,
2218
2219
  ...Object.fromEntries(Object.entries(userOpts).filter(([_, v]) => v !== void 0))
2219
2220
  };
2220
- const generator = writerToGenerator(new TypeScript(opts));
2221
+ const generator = new TypeScript(opts);
2221
2222
  this.generators.set("typescript", generator);
2222
2223
  this.logger.debug(`Configured TypeScript generator (${JSON.stringify(opts, void 0, 2)})`);
2223
2224
  return this;
2224
2225
  }
2225
2226
  csharp(namespace, staticSourceDir) {
2226
- const generator = writerToGenerator(
2227
- new CSharp({
2228
- outputDir: Path4.join(this.options.outputDir, "/types"),
2229
- staticSourceDir: staticSourceDir ?? void 0,
2230
- targetNamespace: namespace,
2231
- logger: new CodegenLogger({
2232
- prefix: "C#",
2233
- timestamp: true,
2234
- verbose: true,
2235
- suppressLoggingLevel: []
2236
- })
2227
+ const generator = new CSharp({
2228
+ outputDir: Path4.join(this.options.outputDir, "/types"),
2229
+ staticSourceDir: staticSourceDir ?? void 0,
2230
+ targetNamespace: namespace,
2231
+ logger: new CodegenLogger({
2232
+ prefix: "C#",
2233
+ timestamp: true,
2234
+ verbose: true,
2235
+ suppressLoggingLevel: []
2237
2236
  })
2238
- );
2237
+ });
2239
2238
  this.generators.set("C#", generator);
2240
2239
  this.logger.debug(`Configured C# generator`);
2241
2240
  return this;
@@ -2254,9 +2253,7 @@ var APIBuilder = class {
2254
2253
  this.logger.debug(`Setting output directory: ${directory}`);
2255
2254
  this.options.outputDir = directory;
2256
2255
  for (const generator of this.generators.values()) {
2257
- if (generator.setOutputDir) {
2258
- generator.setOutputDir(directory);
2259
- }
2256
+ generator.setOutputDir(directory);
2260
2257
  }
2261
2258
  return this;
2262
2259
  }
@@ -2315,10 +2312,7 @@ var APIBuilder = class {
2315
2312
  if (this.options.treeShake) tsIndex = treeShake(tsIndex, this.options.treeShake, this.logger);
2316
2313
  if (this.options.exportTypeTree) await tsIndex.exportTree(this.options.exportTypeTree);
2317
2314
  this.logger.debug(`Executing ${this.generators.size} generators`);
2318
- await this.executeGenerators(result, {
2319
- schemas: typeSchemas,
2320
- index: tsIndex
2321
- });
2315
+ await this.executeGenerators(result, tsIndex);
2322
2316
  this.logger.info("Generation completed successfully");
2323
2317
  result.success = result.errors.length === 0;
2324
2318
  this.logger.debug(`Generation completed: ${result.filesGenerated.length} files`);
@@ -2333,18 +2327,6 @@ var APIBuilder = class {
2333
2327
  duration: performance.now() - startTime
2334
2328
  };
2335
2329
  }
2336
- /**
2337
- * Generate and return the results without writing to files
2338
- */
2339
- async build() {
2340
- const results = {};
2341
- for (const [type, generator] of this.generators.entries()) {
2342
- if (generator.build) {
2343
- results[type] = await generator.build(this.schemas);
2344
- }
2345
- }
2346
- return results;
2347
- }
2348
2330
  /**
2349
2331
  * Clear all configuration and start fresh
2350
2332
  */
@@ -2366,12 +2348,13 @@ var APIBuilder = class {
2366
2348
  getGenerators() {
2367
2349
  return Array.from(this.generators.keys());
2368
2350
  }
2369
- async executeGenerators(result, input) {
2351
+ async executeGenerators(result, tsIndex) {
2370
2352
  for (const [type, generator] of this.generators.entries()) {
2371
2353
  this.logger.info(`Generating ${type}...`);
2372
2354
  try {
2373
- const files = await generator.generate(input);
2374
- result.filesGenerated.push(...files.map((f) => f.path || f.filename));
2355
+ await generator.generate(tsIndex);
2356
+ const fileBuffer = generator.writtenFiles();
2357
+ result.filesGenerated.push(...fileBuffer.map((e) => e.absPath));
2375
2358
  this.logger.info(`Generating ${type} finished successfully`);
2376
2359
  } catch (error) {
2377
2360
  result.errors.push(