@hexagen-monaco/sync 0.5.2 → 0.6.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.
Files changed (104) hide show
  1. package/dist/cli.js +1191 -389
  2. package/dist/cli.js.map +1 -1
  3. package/dist/config.d.ts +7 -0
  4. package/dist/config.d.ts.map +1 -1
  5. package/dist/fs-utils.d.ts +13 -0
  6. package/dist/fs-utils.d.ts.map +1 -1
  7. package/dist/generators/apps-framework-templates.d.ts +2 -1
  8. package/dist/generators/apps-framework-templates.d.ts.map +1 -1
  9. package/dist/generators/apps.d.ts.map +1 -1
  10. package/dist/generators/architecture-files.d.ts.map +1 -1
  11. package/dist/generators/barrels/recursive.d.ts.map +1 -1
  12. package/dist/generators/cross-context.d.ts +5 -0
  13. package/dist/generators/cross-context.d.ts.map +1 -0
  14. package/dist/generators/eslint.d.ts +3 -1
  15. package/dist/generators/eslint.d.ts.map +1 -1
  16. package/dist/generators/layer-folders.d.ts.map +1 -1
  17. package/dist/generators/port-analyzer.d.ts +38 -4
  18. package/dist/generators/port-analyzer.d.ts.map +1 -1
  19. package/dist/generators/root-file-templates.d.ts +3 -3
  20. package/dist/generators/root-file-templates.d.ts.map +1 -1
  21. package/dist/generators/shared-kernel.d.ts +23 -0
  22. package/dist/generators/shared-kernel.d.ts.map +1 -0
  23. package/dist/generators/stubs.d.ts +13 -0
  24. package/dist/generators/stubs.d.ts.map +1 -1
  25. package/dist/index.js +950 -172
  26. package/dist/index.js.map +1 -1
  27. package/dist/scope-filter.d.ts +35 -0
  28. package/dist/scope-filter.d.ts.map +1 -0
  29. package/dist/sync-engine.d.ts.map +1 -1
  30. package/dist/templates/adobe-creative-production/manifest.json +2 -0
  31. package/dist/templates/adobe-express/manifest.json +2 -0
  32. package/dist/templates/adobe-firefly-composite/manifest.json +2 -0
  33. package/dist/templates/adobe-firefly-content-tagging/manifest.json +2 -0
  34. package/dist/templates/adobe-firefly-core/manifest.json +2 -0
  35. package/dist/templates/adobe-firefly-custom-models/manifest.json +2 -0
  36. package/dist/templates/adobe-firefly-generate/manifest.json +2 -0
  37. package/dist/templates/adobe-firefly-media/manifest.json +2 -0
  38. package/dist/templates/adobe-firefly-storage-azure/manifest.json +2 -0
  39. package/dist/templates/adobe-firefly-storage-gcs/manifest.json +2 -0
  40. package/dist/templates/adobe-firefly-storage-s3/manifest.json +2 -0
  41. package/dist/templates/adobe-firefly-upscale/manifest.json +2 -0
  42. package/dist/templates/adobe-illustrator/manifest.json +2 -0
  43. package/dist/templates/adobe-ims-spa/manifest.json +2 -0
  44. package/dist/templates/adobe-indesign/manifest.json +2 -0
  45. package/dist/templates/adobe-lightroom/manifest.json +2 -0
  46. package/dist/templates/adobe-photoshop/manifest.json +2 -0
  47. package/dist/templates/adobe-substance-3d/manifest.json +2 -0
  48. package/dist/templates/auth-mock/manifest.json +2 -0
  49. package/dist/templates/bedrock-agentcore-runtime/manifest.json +10 -2
  50. package/dist/templates/bedrock-agentcore-services/manifest.json +38 -9
  51. package/dist/templates/better-auth/manifest.json +2 -0
  52. package/dist/templates/bullmq/manifest.json +2 -0
  53. package/dist/templates/ci-github-actions/README.md +7 -0
  54. package/dist/templates/ci-github-actions/files/.github/dependabot.yml +16 -4
  55. package/dist/templates/ci-github-actions/files/.github/workflows/ci.yml +7 -3
  56. package/dist/templates/ci-github-actions/files/.github/workflows/preview.yml +20 -2
  57. package/dist/templates/ci-github-actions/manifest.json +26 -6
  58. package/dist/templates/clerk/manifest.json +2 -0
  59. package/dist/templates/design-system/manifest.json +14 -3
  60. package/dist/templates/docker/manifest.json +2 -0
  61. package/dist/templates/error-handling/manifest.json +2 -0
  62. package/dist/templates/eslint-no-console/manifest.json +2 -0
  63. package/dist/templates/github-oauth/manifest.json +2 -0
  64. package/dist/templates/google-oauth/manifest.json +2 -0
  65. package/dist/templates/langgraph/manifest.json +62 -15
  66. package/dist/templates/llm-adapter/manifest.json +2 -0
  67. package/dist/templates/magic-link/manifest.json +2 -0
  68. package/dist/templates/mcp-server/README.md +49 -0
  69. package/dist/templates/mcp-server/files/.env.mcp.example +6 -0
  70. package/dist/templates/mcp-server/files/.mcp.json.example +8 -0
  71. package/dist/templates/mcp-server/files/bin/cli.ts +15 -0
  72. package/dist/templates/mcp-server/files/src/infrastructure/mcp/prompts/example.prompt.ts +32 -0
  73. package/dist/templates/mcp-server/files/src/infrastructure/mcp/registry/register-all.ts +11 -0
  74. package/dist/templates/mcp-server/files/src/infrastructure/mcp/registry/tool-registry.test.ts +67 -0
  75. package/dist/templates/mcp-server/files/src/infrastructure/mcp/registry/tool-registry.ts +45 -0
  76. package/dist/templates/mcp-server/files/src/infrastructure/mcp/resources/example.resource.ts +28 -0
  77. package/dist/templates/mcp-server/files/src/infrastructure/mcp/sdk.ts +41 -0
  78. package/dist/templates/mcp-server/files/src/infrastructure/mcp/server.ts +52 -0
  79. package/dist/templates/mcp-server/files/src/infrastructure/mcp/tools/example.tool.test.ts +31 -0
  80. package/dist/templates/mcp-server/files/src/infrastructure/mcp/tools/example.tool.ts +74 -0
  81. package/dist/templates/mcp-server/files/src/infrastructure/mcp/transport/register-transports.ts +15 -0
  82. package/dist/templates/mcp-server/files/src/infrastructure/mcp/transport/stdio.ts +14 -0
  83. package/dist/templates/mcp-server/manifest.json +68 -0
  84. package/dist/templates/mcp-server-http/README.md +98 -0
  85. package/dist/templates/mcp-server-http/files/.env.mcp-http.example +22 -0
  86. package/dist/templates/mcp-server-http/files/src/infrastructure/mcp/auth/bearer.test.ts +54 -0
  87. package/dist/templates/mcp-server-http/files/src/infrastructure/mcp/auth/bearer.ts +49 -0
  88. package/dist/templates/mcp-server-http/files/src/infrastructure/mcp/auth/oauth.test.ts +50 -0
  89. package/dist/templates/mcp-server-http/files/src/infrastructure/mcp/auth/oauth.ts +53 -0
  90. package/dist/templates/mcp-server-http/files/src/infrastructure/mcp/guard.test.ts +75 -0
  91. package/dist/templates/mcp-server-http/files/src/infrastructure/mcp/guard.ts +26 -0
  92. package/dist/templates/mcp-server-http/files/src/infrastructure/mcp/transport/http.ts +94 -0
  93. package/dist/templates/mcp-server-http/files/src/infrastructure/mcp/transport/register-transports.ts +15 -0
  94. package/dist/templates/mcp-server-http/manifest.json +56 -0
  95. package/dist/templates/microsoft-entra/manifest.json +2 -0
  96. package/dist/templates/nextauth/manifest.json +2 -0
  97. package/dist/templates/observability/manifest.json +10 -2
  98. package/dist/templates/rate-limiting/manifest.json +2 -0
  99. package/dist/templates/shared-types/manifest.json +2 -0
  100. package/dist/templates/supabase/manifest.json +2 -0
  101. package/dist/templates/supabase-auth/manifest.json +2 -0
  102. package/dist/types/manifest/apps.d.ts +12 -1
  103. package/dist/types/manifest/apps.d.ts.map +1 -1
  104. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -1,11 +1,11 @@
1
1
  #!/usr/bin/env node
2
- import * as fs19 from 'fs';
3
- import fs19__default, { mkdirSync, writeFileSync, renameSync, unlinkSync, existsSync, readFileSync, realpathSync, lstatSync, createWriteStream } from 'fs';
2
+ import * as fs22 from 'fs';
3
+ import fs22__default, { mkdirSync, writeFileSync, renameSync, unlinkSync, existsSync, readFileSync, realpathSync, lstatSync, createWriteStream } from 'fs';
4
4
  import { fileURLToPath } from 'url';
5
- import * as path28 from 'path';
6
- import path28__default, { dirname, join } from 'path';
5
+ import * as path33 from 'path';
6
+ import path33__default, { dirname, join } from 'path';
7
7
  import { Command } from 'commander';
8
- import fs22, { readFile } from 'fs/promises';
8
+ import fs25, { readFile } from 'fs/promises';
9
9
  import { promisify } from 'util';
10
10
  import { exec, execSync, spawn } from 'child_process';
11
11
  import yaml9 from 'js-yaml';
@@ -25,7 +25,7 @@ var MigrationReport = class {
25
25
  this.entries.push({ type, target, message });
26
26
  }
27
27
  async writeReport(config) {
28
- const reportPath = path28__default.join(
28
+ const reportPath = path33__default.join(
29
29
  config.workspaceRoot,
30
30
  "SYNC-MIGRATION-REPORT.md"
31
31
  );
@@ -42,9 +42,9 @@ var MigrationReport = class {
42
42
  };
43
43
  var LOCK_FILE = ".architecture/.sync.lock";
44
44
  var LockFile = class {
45
- constructor(workspaceRoot, fsImpl = fs22, logger2 = console) {
45
+ constructor(workspaceRoot, fsImpl = fs25, logger2 = console) {
46
46
  this.workspaceRoot = workspaceRoot;
47
- this.lockPath = path28__default.join(workspaceRoot, LOCK_FILE);
47
+ this.lockPath = path33__default.join(workspaceRoot, LOCK_FILE);
48
48
  this.fsImpl = fsImpl;
49
49
  this.logger = logger2;
50
50
  }
@@ -111,11 +111,11 @@ var LockFile = class {
111
111
  };
112
112
  var BIN_NAME = process.platform === "win32" ? "hexagen-lint.cmd" : "hexagen-lint";
113
113
  function resolveArchLinterBin(startDir) {
114
- let dir = path28__default.resolve(startDir);
114
+ let dir = path33__default.resolve(startDir);
115
115
  for (; ; ) {
116
- const candidate = path28__default.join(dir, "node_modules", ".bin", BIN_NAME);
117
- if (fs19__default.existsSync(candidate)) return candidate;
118
- const parent = path28__default.dirname(dir);
116
+ const candidate = path33__default.join(dir, "node_modules", ".bin", BIN_NAME);
117
+ if (fs22__default.existsSync(candidate)) return candidate;
118
+ const parent = path33__default.dirname(dir);
119
119
  if (parent === dir) return null;
120
120
  dir = parent;
121
121
  }
@@ -164,6 +164,46 @@ function createEmptyResult() {
164
164
  totalOps: 0
165
165
  };
166
166
  }
167
+
168
+ // src/scope-filter.ts
169
+ var GLOB_META = /[*?]/;
170
+ function normalize(p) {
171
+ return p.replace(/\\/g, "/").replace(/^\.?\//, "").replace(/\/+$/, "");
172
+ }
173
+ function globToRegExp(glob) {
174
+ let re = "";
175
+ for (let i = 0; i < glob.length; i++) {
176
+ const c = glob[i];
177
+ if (c === "*") {
178
+ if (glob[i + 1] === "*") {
179
+ re += ".*";
180
+ i++;
181
+ } else {
182
+ re += "[^/]*";
183
+ }
184
+ } else if (c === "?") {
185
+ re += "[^/]";
186
+ } else if ("\\^$.|+()[]{}".includes(c)) {
187
+ re += `\\${c}`;
188
+ } else {
189
+ re += c;
190
+ }
191
+ }
192
+ return new RegExp(`^${re}$`);
193
+ }
194
+ function matchesScope(relativePath, patterns) {
195
+ const rel = normalize(relativePath);
196
+ return patterns.some((raw) => {
197
+ const pat = normalize(raw);
198
+ if (pat === "") return false;
199
+ if (!GLOB_META.test(pat)) {
200
+ return rel === pat || rel.startsWith(`${pat}/`);
201
+ }
202
+ return globToRegExp(pat).test(rel);
203
+ });
204
+ }
205
+
206
+ // src/fs-utils.ts
167
207
  var GENERATED_MARKER = "// @generated by @hexagen/sync";
168
208
  var protectedFiles = /* @__PURE__ */ new Set([
169
209
  ".gitignore",
@@ -190,20 +230,29 @@ function isGeneratedFile(content) {
190
230
  return content.includes(GENERATED_MARKER);
191
231
  }
192
232
  function isProtectedRoot(filePath, config) {
193
- const relative = path28__default.relative(config.workspaceRoot, filePath);
233
+ const relative = path33__default.relative(config.workspaceRoot, filePath);
194
234
  const isRootLevel = !relative.startsWith("packages/") && !relative.startsWith("tools/") && !relative.startsWith("apps/");
195
235
  return isRootLevel && Array.from(protectedFiles).some(
196
236
  (f) => relative.endsWith(f) || relative.includes(f)
197
237
  );
198
238
  }
239
+ function isInScope(filePath, config) {
240
+ if (!config.only || config.only.length === 0) return true;
241
+ const relativePath = path33__default.relative(config.workspaceRoot, filePath);
242
+ return matchesScope(relativePath, config.only);
243
+ }
199
244
  async function safeWriteFileAtomic(filePath, content, config, report, skipGeneratedCheck = false) {
200
245
  const { dryRun, forceRoot, logger: logger2, workspaceRoot } = config;
201
- const relativePath = path28__default.relative(workspaceRoot, filePath);
246
+ const relativePath = path33__default.relative(workspaceRoot, filePath);
247
+ if (!isInScope(filePath, config)) {
248
+ logger2.debug(`skipped (outside --only) ${relativePath}`);
249
+ return "skipped";
250
+ }
202
251
  let exists = false;
203
252
  let currentContent = "";
204
253
  let currentHash = "";
205
254
  try {
206
- currentContent = await fs22.readFile(filePath, "utf8");
255
+ currentContent = await fs25.readFile(filePath, "utf8");
207
256
  currentHash = contentHash(currentContent);
208
257
  exists = true;
209
258
  } catch (e) {
@@ -215,36 +264,38 @@ async function safeWriteFileAtomic(filePath, content, config, report, skipGenera
215
264
  logger2.debug(`unchanged ${relativePath}`);
216
265
  return "unchanged";
217
266
  }
218
- if (dryRun) {
219
- const action = exists ? "update" : "create";
220
- logger2.info(`[DRY-RUN] would ${action} ${relativePath}`);
221
- return exists ? "updated" : "created";
222
- }
223
267
  if (isProtectedRoot(filePath, config) && !forceRoot) {
224
- logger2.warn(`skipped (root protected, use --force-root) ${relativePath}`);
268
+ const verb = dryRun ? "[DRY-RUN] would skip" : "skipped";
269
+ logger2.warn(`${verb} (root protected, use --force-root) ${relativePath}`);
225
270
  if (report) report.record("blocked", filePath, "Root file protected");
226
271
  return "protected";
227
272
  }
228
273
  if (exists && !forceRoot && !skipGeneratedCheck && !isGeneratedFile(currentContent)) {
274
+ const verb = dryRun ? "[DRY-RUN] would skip" : "skipped";
229
275
  logger2.warn(
230
- `skipped (hand-written, use --force-root to overwrite) ${relativePath}`
276
+ `${verb} (hand-written, use --force-root to overwrite) ${relativePath}`
231
277
  );
232
278
  return "skipped";
233
279
  }
234
- await fs22.mkdir(path28__default.dirname(filePath), { recursive: true });
235
- const tmpName = `.${path28__default.basename(filePath)}.${crypto.randomUUID()}.tmp`;
236
- const tmpPath = path28__default.join(path28__default.dirname(filePath), tmpName);
237
- await fs22.writeFile(tmpPath, content, { encoding: "utf8" });
280
+ if (dryRun) {
281
+ const action = exists ? "update" : "create";
282
+ logger2.info(`[DRY-RUN] would ${action} ${relativePath}`);
283
+ return exists ? "updated" : "created";
284
+ }
285
+ await fs25.mkdir(path33__default.dirname(filePath), { recursive: true });
286
+ const tmpName = `.${path33__default.basename(filePath)}.${crypto.randomUUID()}.tmp`;
287
+ const tmpPath = path33__default.join(path33__default.dirname(filePath), tmpName);
288
+ await fs25.writeFile(tmpPath, content, { encoding: "utf8" });
238
289
  try {
239
- await fs22.rename(tmpPath, filePath);
290
+ await fs25.rename(tmpPath, filePath);
240
291
  const status = exists ? "updated" : "created";
241
292
  logger2.info(`${status} ${relativePath}`);
242
293
  return status;
243
294
  } catch (err3) {
244
295
  if (err3 instanceof Error && "code" in err3 && err3.code === "EXDEV") {
245
296
  try {
246
- await fs22.copyFile(tmpPath, filePath);
247
- await fs22.unlink(tmpPath);
297
+ await fs25.copyFile(tmpPath, filePath);
298
+ await fs25.unlink(tmpPath);
248
299
  const status = exists ? "updated" : "created";
249
300
  logger2.info(`${status} ${relativePath}`);
250
301
  return status;
@@ -252,7 +303,7 @@ async function safeWriteFileAtomic(filePath, content, config, report, skipGenera
252
303
  logger2.warn(`EXDEV fallback failed for ${relativePath}: ${copyErr}`);
253
304
  }
254
305
  }
255
- await fs22.unlink(tmpPath).catch(() => {
306
+ await fs25.unlink(tmpPath).catch(() => {
256
307
  });
257
308
  throw err3;
258
309
  }
@@ -262,7 +313,7 @@ async function safeWriteFileAtomic(filePath, content, config, report, skipGenera
262
313
  var GENERATED_MARKER2 = "// @generated by @hexagen/sync";
263
314
  async function loadYamlSafe(filePath) {
264
315
  try {
265
- const content = await fs22.readFile(filePath, "utf8");
316
+ const content = await fs25.readFile(filePath, "utf8");
266
317
  return yaml9.load(content);
267
318
  } catch (e) {
268
319
  if (e instanceof Error && "code" in e && e.code === "ENOENT") {
@@ -274,7 +325,7 @@ async function loadYamlSafe(filePath) {
274
325
  async function generateBarrelContent(dirPath) {
275
326
  const exportLines = [];
276
327
  try {
277
- const entries = await fs22.readdir(dirPath, { withFileTypes: true });
328
+ const entries = await fs25.readdir(dirPath, { withFileTypes: true });
278
329
  for (const entry of entries) {
279
330
  if (entry.name === "index.ts" || entry.name.startsWith(".")) continue;
280
331
  if (entry.isFile() && entry.name.endsWith(".ts")) {
@@ -300,7 +351,7 @@ ${exportLines.join("\n")}
300
351
  async function ensureLayerFolders(moduleDir, layers, config, report) {
301
352
  const result = createEmptyResult();
302
353
  const { logger: logger2 } = config;
303
- const layerRulesPath = path28__default.join(
354
+ const layerRulesPath = path33__default.join(
304
355
  config.workspaceRoot,
305
356
  ".architecture",
306
357
  "invariants",
@@ -311,9 +362,13 @@ async function ensureLayerFolders(moduleDir, layers, config, report) {
311
362
  logger2.warn("layer-rules.yaml not found — skipping layer rule enforcement");
312
363
  }
313
364
  for (const [, layerConfig] of Object.entries(layers)) {
314
- const layerPath = path28__default.join(moduleDir, layerConfig.folder);
365
+ const layerPath = path33__default.join(moduleDir, layerConfig.folder);
366
+ const barrelPath = path33__default.join(layerPath, "index.ts");
367
+ if (!isInScope(barrelPath, config)) {
368
+ continue;
369
+ }
315
370
  try {
316
- await fs22.mkdir(layerPath, { recursive: true });
371
+ await fs25.mkdir(layerPath, { recursive: true });
317
372
  result.created.push(layerPath);
318
373
  result.totalOps += 1;
319
374
  } catch (e) {
@@ -323,7 +378,6 @@ async function ensureLayerFolders(moduleDir, layers, config, report) {
323
378
  throw e;
324
379
  }
325
380
  }
326
- const barrelPath = path28__default.join(layerPath, "index.ts");
327
381
  const barrelContent = await generateBarrelContent(layerPath);
328
382
  const barrelStatus = await safeWriteFileAtomic(
329
383
  barrelPath,
@@ -338,9 +392,13 @@ async function ensureLayerFolders(moduleDir, layers, config, report) {
338
392
  result.totalOps += barrelStatus === "created" || barrelStatus === "updated" ? 1 : 0;
339
393
  const subfolders = layerConfig.subfolders ?? [];
340
394
  for (const sub of subfolders) {
341
- const subPath = path28__default.join(layerPath, sub);
395
+ const subPath = path33__default.join(layerPath, sub);
396
+ const subBarrelPath = path33__default.join(subPath, "index.ts");
397
+ if (!isInScope(subBarrelPath, config)) {
398
+ continue;
399
+ }
342
400
  try {
343
- await fs22.mkdir(subPath, { recursive: true });
401
+ await fs25.mkdir(subPath, { recursive: true });
344
402
  result.created.push(subPath);
345
403
  result.totalOps += 1;
346
404
  } catch (e) {
@@ -350,7 +408,6 @@ async function ensureLayerFolders(moduleDir, layers, config, report) {
350
408
  throw e;
351
409
  }
352
410
  }
353
- const subBarrelPath = path28__default.join(subPath, "index.ts");
354
411
  const subBarrelContent = await generateBarrelContent(subPath);
355
412
  const subBarrelStatus = await safeWriteFileAtomic(
356
413
  subBarrelPath,
@@ -394,18 +451,18 @@ function contentHash2(content) {
394
451
  function detectCircularExports(exportGraph) {
395
452
  const visited = /* @__PURE__ */ new Set();
396
453
  const recursionStack = /* @__PURE__ */ new Set();
397
- const path32 = [];
454
+ const path37 = [];
398
455
  function dfs(node) {
399
456
  if (recursionStack.has(node)) {
400
- const cycleStart = path32.indexOf(node);
401
- return [...path32.slice(cycleStart), node];
457
+ const cycleStart = path37.indexOf(node);
458
+ return [...path37.slice(cycleStart), node];
402
459
  }
403
460
  if (visited.has(node)) {
404
461
  return null;
405
462
  }
406
463
  visited.add(node);
407
464
  recursionStack.add(node);
408
- path32.push(node);
465
+ path37.push(node);
409
466
  const exports$1 = exportGraph.get(node) ?? [];
410
467
  for (const exportPath of exports$1) {
411
468
  const cycle = dfs(exportPath);
@@ -413,7 +470,7 @@ function detectCircularExports(exportGraph) {
413
470
  return cycle;
414
471
  }
415
472
  }
416
- path32.pop();
473
+ path37.pop();
417
474
  recursionStack.delete(node);
418
475
  return null;
419
476
  }
@@ -430,8 +487,8 @@ function generateBarrelContent2(entries) {
430
487
  return null;
431
488
  }
432
489
  const exportLines = entries.sort((a, b) => a.name.localeCompare(b.name)).map((entry) => {
433
- const path32 = entry.isDirectory ? `./${entry.name}/index.js` : `./${entry.name}.js`;
434
- return `export * from "${path32}";`;
490
+ const path37 = entry.isDirectory ? `./${entry.name}/index.js` : `./${entry.name}.js`;
491
+ return `export * from "${path37}";`;
435
492
  });
436
493
  return `${GENERATED_MARKER3}
437
494
 
@@ -453,25 +510,47 @@ var CircularExportError = class extends Error {
453
510
  };
454
511
  async function generateRecursiveBarrels(moduleDir, config, report) {
455
512
  const result = createEmptyResult();
456
- const srcDir = path28__default.join(moduleDir, "src");
513
+ const srcDir = path33__default.join(moduleDir, "src");
457
514
  const layers = ["domain", "application", "infrastructure"];
458
515
  const pendingWrites = [];
459
516
  const preserved = [];
460
517
  const exportGraph = /* @__PURE__ */ new Map();
518
+ const layersWithContent = [];
461
519
  for (const layer of layers) {
462
- const layerDir = path28__default.join(srcDir, layer);
520
+ const layerDir = path33__default.join(srcDir, layer);
463
521
  try {
464
- await fs22.access(layerDir);
522
+ await fs25.access(layerDir);
465
523
  } catch {
466
524
  continue;
467
525
  }
468
- await walkDirectory(
526
+ const layerExports = await walkDirectory(
469
527
  layerDir,
470
528
  pendingWrites,
471
529
  preserved,
472
530
  exportGraph,
473
531
  config
474
532
  );
533
+ if (layerExports.length > 0) layersWithContent.push(layer);
534
+ }
535
+ if (config.mode === "external" && layersWithContent.length > 0) {
536
+ const rootBarrelPath = path33__default.join(srcDir, "index.ts");
537
+ if (await shouldGenerateBarrel(rootBarrelPath, preserved, config.logger)) {
538
+ const content = generateBarrelContent2(
539
+ layersWithContent.map((name) => ({ name, isDirectory: true }))
540
+ );
541
+ const existing = await readFileIfExists(rootBarrelPath);
542
+ if (content !== null && !(existing && contentHash2(existing) === contentHash2(content))) {
543
+ pendingWrites.push({
544
+ filePath: rootBarrelPath,
545
+ content,
546
+ isNew: !existing
547
+ });
548
+ exportGraph.set(
549
+ rootBarrelPath,
550
+ layersWithContent.map((name) => path33__default.join(srcDir, name, "index.ts"))
551
+ );
552
+ }
553
+ }
475
554
  }
476
555
  const circularCheck = detectCircularExports(exportGraph);
477
556
  if (circularCheck.hasCircular && circularCheck.cycle) {
@@ -480,7 +559,7 @@ async function generateRecursiveBarrels(moduleDir, config, report) {
480
559
  for (const pending of pendingWrites) {
481
560
  if (pending.content === "") {
482
561
  try {
483
- await fs22.unlink(pending.filePath);
562
+ await fs25.unlink(pending.filePath);
484
563
  result.created.push(pending.filePath);
485
564
  result.totalOps++;
486
565
  continue;
@@ -515,7 +594,7 @@ async function walkDirectory(dirPath, pendingWrites, preserved, exportGraph, con
515
594
  const exportEntries = [];
516
595
  let entries;
517
596
  try {
518
- entries = await fs22.readdir(dirPath, { withFileTypes: true });
597
+ entries = await fs25.readdir(dirPath, { withFileTypes: true });
519
598
  } catch {
520
599
  return exportEntries;
521
600
  }
@@ -532,7 +611,7 @@ async function walkDirectory(dirPath, pendingWrites, preserved, exportGraph, con
532
611
  }
533
612
  }
534
613
  for (const dir of directories) {
535
- const subDirPath = path28__default.join(dirPath, dir);
614
+ const subDirPath = path33__default.join(dirPath, dir);
536
615
  const subExports = await walkDirectory(
537
616
  subDirPath,
538
617
  pendingWrites,
@@ -540,7 +619,7 @@ async function walkDirectory(dirPath, pendingWrites, preserved, exportGraph, con
540
619
  exportGraph,
541
620
  config
542
621
  );
543
- const subBarrelPath = path28__default.join(subDirPath, "index.ts");
622
+ const subBarrelPath = path33__default.join(subDirPath, "index.ts");
544
623
  const isQueuedForDeletion = pendingWrites.some(
545
624
  (p) => p.filePath === subBarrelPath && p.content === ""
546
625
  );
@@ -552,9 +631,9 @@ async function walkDirectory(dirPath, pendingWrites, preserved, exportGraph, con
552
631
  exportEntries.push({ name: file, isDirectory: false });
553
632
  }
554
633
  if (exportEntries.length === 0) {
555
- const barrelPath2 = path28__default.join(dirPath, "index.ts");
634
+ const barrelPath2 = path33__default.join(dirPath, "index.ts");
556
635
  const existingBarrel = await readFileIfExists(barrelPath2);
557
- const dirName = path28__default.basename(dirPath);
636
+ const dirName = path33__default.basename(dirPath);
558
637
  const isLayerDir = ["domain", "application", "infrastructure"].includes(
559
638
  dirName
560
639
  );
@@ -604,7 +683,7 @@ export {};
604
683
  }
605
684
  return [];
606
685
  }
607
- const barrelPath = path28__default.join(dirPath, "index.ts");
686
+ const barrelPath = path33__default.join(dirPath, "index.ts");
608
687
  const shouldCreateBarrel = await shouldGenerateBarrel(
609
688
  barrelPath,
610
689
  preserved,
@@ -624,14 +703,14 @@ export {};
624
703
  content,
625
704
  isNew: !existingContent
626
705
  });
627
- const exportPaths = exportEntries.filter((e) => e.isDirectory).map((e) => path28__default.join(dirPath, e.name, "index.ts"));
706
+ const exportPaths = exportEntries.filter((e) => e.isDirectory).map((e) => path33__default.join(dirPath, e.name, "index.ts"));
628
707
  exportGraph.set(barrelPath, exportPaths);
629
708
  }
630
709
  return exportEntries;
631
710
  }
632
711
  async function hasBarrel(dirPath) {
633
712
  try {
634
- await fs22.access(path28__default.join(dirPath, "index.ts"));
713
+ await fs25.access(path33__default.join(dirPath, "index.ts"));
635
714
  return true;
636
715
  } catch {
637
716
  return false;
@@ -651,7 +730,7 @@ async function shouldGenerateBarrel(barrelPath, preserved, logger2) {
651
730
  }
652
731
  async function readFileIfExists(filePath) {
653
732
  try {
654
- return await fs22.readFile(filePath, "utf8");
733
+ return await fs25.readFile(filePath, "utf8");
655
734
  } catch (err3) {
656
735
  if (err3 && typeof err3 === "object" && "code" in err3 && err3.code === "ENOENT") {
657
736
  return null;
@@ -696,7 +775,7 @@ async function generatePackageJson(modulePath, moduleName, config, report) {
696
775
  const moduleOverrides = context?.packageJson ?? {};
697
776
  const scope = config.manifest ? resolveScope(config.manifest) : "generated-project";
698
777
  const dependsOnDeps = context ? expandDependsOn(context, scope) : {};
699
- const pkgPath = path28__default.join(modulePath, "package.json");
778
+ const pkgPath = path33__default.join(modulePath, "package.json");
700
779
  const desiredPkg = {
701
780
  name: `@${scope}/${moduleName}`,
702
781
  version: "0.1.0",
@@ -730,7 +809,7 @@ async function generatePackageJson(modulePath, moduleName, config, report) {
730
809
  };
731
810
  let currentPkg = {};
732
811
  try {
733
- const currentContent = await fs22.readFile(pkgPath, "utf8");
812
+ const currentContent = await fs25.readFile(pkgPath, "utf8");
734
813
  currentPkg = JSON.parse(currentContent);
735
814
  } catch (e) {
736
815
  if (!(e instanceof Error && "code" in e && e.code === "ENOENT")) {
@@ -844,7 +923,7 @@ function buildTemplate(base, context, scope) {
844
923
  }
845
924
  async function generateTsconfig(moduleDir, moduleName, config, report) {
846
925
  const result = createEmptyResult();
847
- const filePath = path28__default.join(moduleDir, "tsconfig.json");
926
+ const filePath = path33__default.join(moduleDir, "tsconfig.json");
848
927
  try {
849
928
  const base = resolveWorkspaceTemplate(config.manifest);
850
929
  const context = config.manifest.bounded_contexts?.find(
@@ -876,15 +955,15 @@ async function reapLegacyFolders(moduleDir, config, report) {
876
955
  const { dryRun, logger: logger2 } = config;
877
956
  const legacyLayers = ["domain", "application", "infrastructure"];
878
957
  for (const layer of legacyLayers) {
879
- const layerPath = path28__default.join(moduleDir, layer);
880
- const relativePath = path28__default.relative(config.workspaceRoot, layerPath);
958
+ const layerPath = path33__default.join(moduleDir, layer);
959
+ const relativePath = path33__default.relative(config.workspaceRoot, layerPath);
881
960
  try {
882
- const entries = await fs22.readdir(layerPath);
961
+ const entries = await fs25.readdir(layerPath);
883
962
  if (entries.length === 0) {
884
963
  if (dryRun) {
885
964
  logger2.info(`[DRY-RUN] would delete empty folder ${relativePath}`);
886
965
  } else {
887
- await fs22.rm(layerPath, { recursive: true, force: true });
966
+ await fs25.rm(layerPath, { recursive: true, force: true });
888
967
  logger2.info(`deleted empty folder ${relativePath}`);
889
968
  if (report) report.record("deleted", layerPath);
890
969
  }
@@ -1374,8 +1453,8 @@ function getErrorMap() {
1374
1453
 
1375
1454
  // ../../node_modules/zod/v3/helpers/parseUtil.js
1376
1455
  var makeIssue = (params) => {
1377
- const { data, path: path32, errorMaps, issueData } = params;
1378
- const fullPath = [...path32, ...issueData.path || []];
1456
+ const { data, path: path37, errorMaps, issueData } = params;
1457
+ const fullPath = [...path37, ...issueData.path || []];
1379
1458
  const fullIssue = {
1380
1459
  ...issueData,
1381
1460
  path: fullPath
@@ -1491,11 +1570,11 @@ var errorUtil;
1491
1570
 
1492
1571
  // ../../node_modules/zod/v3/types.js
1493
1572
  var ParseInputLazyPath = class {
1494
- constructor(parent, value, path32, key) {
1573
+ constructor(parent, value, path37, key) {
1495
1574
  this._cachedPath = [];
1496
1575
  this.parent = parent;
1497
1576
  this.data = value;
1498
- this._path = path32;
1577
+ this._path = path37;
1499
1578
  this._key = key;
1500
1579
  }
1501
1580
  get path() {
@@ -5026,6 +5105,7 @@ var BUILTIN_TSCONFIG_BASE_TEMPLATE = `{
5026
5105
  "module": "ESNext",
5027
5106
  "moduleResolution": "bundler",
5028
5107
  "strict": true,
5108
+ "skipLibCheck": true,
5029
5109
  "composite": true,
5030
5110
  "declaration": true,
5031
5111
  "emitDeclarationOnly": true,
@@ -5057,6 +5137,9 @@ var BUILTIN_TURBO_TEMPLATE = `{
5057
5137
  ]
5058
5138
  },
5059
5139
  "typecheck": {
5140
+ "dependsOn": [
5141
+ "^build"
5142
+ ],
5060
5143
  "outputs": [],
5061
5144
  "cache": true
5062
5145
  },
@@ -5077,7 +5160,13 @@ node_modules/
5077
5160
  dist/
5078
5161
  .turbo/
5079
5162
  .next/
5080
- out/
5163
+ .nitro/
5164
+ .output/
5165
+
5166
+ # Next.js static export — anchored to apps so a bare \`out/\` can't shadow a
5167
+ # bounded context's hexagonal \`src/application/ports/out/\` source (which a
5168
+ # pattern without a leading path matches at any depth).
5169
+ apps/*/out/
5081
5170
 
5082
5171
  # Test / coverage
5083
5172
  coverage/
@@ -5175,7 +5264,7 @@ async function generateRootFiles(config, report) {
5175
5264
  "package.json"
5176
5265
  );
5177
5266
  await writeRootFile(
5178
- path28__default.join(config.workspaceRoot, "package.json"),
5267
+ path33__default.join(config.workspaceRoot, "package.json"),
5179
5268
  packageJsonContent,
5180
5269
  config,
5181
5270
  report,
@@ -5192,7 +5281,7 @@ async function generateRootFiles(config, report) {
5192
5281
  "tsconfig.base.json"
5193
5282
  );
5194
5283
  await writeRootFile(
5195
- path28__default.join(config.workspaceRoot, "tsconfig.base.json"),
5284
+ path33__default.join(config.workspaceRoot, "tsconfig.base.json"),
5196
5285
  tsconfigContent,
5197
5286
  config,
5198
5287
  report,
@@ -5209,7 +5298,7 @@ async function generateRootFiles(config, report) {
5209
5298
  "turbo.json"
5210
5299
  );
5211
5300
  await writeRootFile(
5212
- path28__default.join(config.workspaceRoot, "turbo.json"),
5301
+ path33__default.join(config.workspaceRoot, "turbo.json"),
5213
5302
  turboContent,
5214
5303
  config,
5215
5304
  report,
@@ -5220,7 +5309,7 @@ async function generateRootFiles(config, report) {
5220
5309
  BUILTIN_GITIGNORE_TEMPLATE
5221
5310
  );
5222
5311
  await writeRootFile(
5223
- path28__default.join(config.workspaceRoot, ".gitignore"),
5312
+ path33__default.join(config.workspaceRoot, ".gitignore"),
5224
5313
  interpolateAndWarn(gitignoreTemplate, vars, config, ".gitignore"),
5225
5314
  config,
5226
5315
  report,
@@ -5231,7 +5320,7 @@ async function generateRootFiles(config, report) {
5231
5320
  BUILTIN_YARNRC_TEMPLATE
5232
5321
  );
5233
5322
  await writeRootFile(
5234
- path28__default.join(config.workspaceRoot, ".yarnrc.yml"),
5323
+ path33__default.join(config.workspaceRoot, ".yarnrc.yml"),
5235
5324
  interpolateAndWarn(yarnrcTemplate, vars, config, ".yarnrc.yml"),
5236
5325
  config,
5237
5326
  report,
@@ -5242,7 +5331,7 @@ async function generateRootFiles(config, report) {
5242
5331
  BUILTIN_SETUP_MD_TEMPLATE
5243
5332
  );
5244
5333
  await writeRootFile(
5245
- path28__default.join(config.workspaceRoot, "SETUP.md"),
5334
+ path33__default.join(config.workspaceRoot, "SETUP.md"),
5246
5335
  interpolateAndWarn(setupTemplate, vars, config, "SETUP.md"),
5247
5336
  config,
5248
5337
  report,
@@ -5479,12 +5568,17 @@ async function writeManifestIfFreshExternal(config, result, report) {
5479
5568
  if (config.mode !== "external") {
5480
5569
  return;
5481
5570
  }
5482
- const archDir = path28__default.join(config.workspaceRoot, ".architecture");
5483
- const manifestPath = path28__default.join(archDir, "manifest.yaml");
5484
- const relative = path28__default.relative(config.workspaceRoot, manifestPath);
5571
+ const archDir = path33__default.join(config.workspaceRoot, ".architecture");
5572
+ const manifestPath = path33__default.join(archDir, "manifest.yaml");
5573
+ const relative = path33__default.relative(config.workspaceRoot, manifestPath);
5574
+ if (!isInScope(manifestPath, config)) {
5575
+ config.logger.debug(`skipped (outside --only) ${relative}`);
5576
+ result.skipped.push(manifestPath);
5577
+ return;
5578
+ }
5485
5579
  let exists = false;
5486
5580
  try {
5487
- await fs22.access(manifestPath);
5581
+ await fs25.access(manifestPath);
5488
5582
  exists = true;
5489
5583
  } catch {
5490
5584
  exists = false;
@@ -5503,8 +5597,8 @@ async function writeManifestIfFreshExternal(config, result, report) {
5503
5597
  return;
5504
5598
  }
5505
5599
  const content = yaml9.dump(config.manifest);
5506
- await fs22.mkdir(archDir, { recursive: true });
5507
- await fs22.writeFile(manifestPath, content, { encoding: "utf8" });
5600
+ await fs25.mkdir(archDir, { recursive: true });
5601
+ await fs25.writeFile(manifestPath, content, { encoding: "utf8" });
5508
5602
  config.logger.info(`created ${relative}`);
5509
5603
  if (report)
5510
5604
  report.record(
@@ -5518,12 +5612,12 @@ async function writeManifestIfFreshExternal(config, result, report) {
5518
5612
  async function generateArchitectureFiles(config, report) {
5519
5613
  const result = createEmptyResult();
5520
5614
  const manifest = config.manifest;
5521
- const archRoot = path28__default.join(config.workspaceRoot, ".architecture");
5615
+ const archRoot = path33__default.join(config.workspaceRoot, ".architecture");
5522
5616
  const archInvariants = manifest.monorepo?.archInvariants;
5523
5617
  const vars = buildInterpolationVars(manifest);
5524
5618
  const workspaceTemplate = vars.workspaceTemplate ?? "modular-monolith";
5525
5619
  await writeManifestIfFreshExternal(config, result, report);
5526
- const layerRulesPath = path28__default.join(archRoot, "invariants", "layer-rules.yaml");
5620
+ const layerRulesPath = path33__default.join(archRoot, "invariants", "layer-rules.yaml");
5527
5621
  const layerRulesTemplate = resolveTemplate2(
5528
5622
  archInvariants?.layerRules,
5529
5623
  builtInLayerRules(workspaceTemplate)
@@ -5542,7 +5636,7 @@ async function generateArchitectureFiles(config, report) {
5542
5636
  true
5543
5637
  );
5544
5638
  recordStatus(result, layerRulesPath, layerRulesStatus);
5545
- const linterConfigPath = path28__default.join(
5639
+ const linterConfigPath = path33__default.join(
5546
5640
  archRoot,
5547
5641
  "invariants",
5548
5642
  "linter-config.yaml"
@@ -5565,7 +5659,7 @@ async function generateArchitectureFiles(config, report) {
5565
5659
  true
5566
5660
  );
5567
5661
  recordStatus(result, linterConfigPath, linterConfigStatus);
5568
- const generatorConfigPath = path28__default.join(archRoot, "generator.config.yaml");
5662
+ const generatorConfigPath = path33__default.join(archRoot, "generator.config.yaml");
5569
5663
  const generatorConfigTemplate = resolveTemplate2(
5570
5664
  archInvariants?.generatorConfig,
5571
5665
  GENERATOR_CONFIG_TEMPLATE
@@ -5713,6 +5807,50 @@ export function main(): void {
5713
5807
  // Application bootstrap for {appName}
5714
5808
  }
5715
5809
  `;
5810
+ var NITRO_PACKAGE_JSON_TEMPLATE = `{
5811
+ "name": "@{scope}/{appName}",
5812
+ "version": "0.0.0",
5813
+ "private": true,
5814
+ "type": "module",
5815
+ "scripts": {
5816
+ "build": "nitro build",
5817
+ "dev": "nitro dev",
5818
+ "preview": "node .output/server/index.mjs",
5819
+ "prepare": "nitro prepare",
5820
+ "lint": "eslint server --ext .ts",
5821
+ "typecheck": "nitro prepare && tsc --noEmit"
5822
+ },
5823
+ "dependencies": {
5824
+ "nitropack": "^2.13.0"
5825
+ },
5826
+ "devDependencies": {
5827
+ "typescript": "^5.5.4",
5828
+ "eslint": "^9.0.0",
5829
+ "@typescript-eslint/parser": "^8.0.0",
5830
+ "@typescript-eslint/eslint-plugin": "^8.0.0"
5831
+ }
5832
+ }
5833
+ `;
5834
+ var NITRO_TSCONFIG = {
5835
+ extends: "./.nitro/types/tsconfig.json",
5836
+ compilerOptions: {
5837
+ moduleResolution: "bundler",
5838
+ strict: true,
5839
+ skipLibCheck: true
5840
+ }
5841
+ };
5842
+ var NITRO_CONFIG_TEMPLATE = `import { defineNitroConfig } from "nitropack/config";
5843
+
5844
+ // https://nitro.build/config
5845
+ export default defineNitroConfig({
5846
+ srcDir: "server",
5847
+ compatibilityDate: "2025-01-01",
5848
+ });
5849
+ `;
5850
+ var NITRO_ROUTE_TEMPLATE = `// Auto-generated Nitro route — GET /
5851
+ // \`defineEventHandler\` is auto-imported by Nitro (see ./.nitro/types).
5852
+ export default defineEventHandler(() => ({ status: "ok", app: "{appName}" }));
5853
+ `;
5716
5854
  var BUILTIN_FRAMEWORK_TEMPLATES = {
5717
5855
  "next.js": {
5718
5856
  packageJson: { template: NEXTJS_PACKAGE_JSON_TEMPLATE },
@@ -5737,8 +5875,107 @@ var BUILTIN_FRAMEWORK_TEMPLATES = {
5737
5875
  path: "src/index.ts",
5738
5876
  template: PLAIN_TS_ENTRY_TEMPLATE
5739
5877
  }
5878
+ },
5879
+ nitro: {
5880
+ packageJson: { template: NITRO_PACKAGE_JSON_TEMPLATE },
5881
+ tsConfig: NITRO_TSCONFIG,
5882
+ entryPoint: {
5883
+ path: "server/routes/index.ts",
5884
+ template: NITRO_ROUTE_TEMPLATE
5885
+ },
5886
+ extraFiles: [{ path: "nitro.config.ts", template: NITRO_CONFIG_TEMPLATE }]
5740
5887
  }
5741
5888
  };
5889
+ var GENERATED_MARKER_LINE = "// @generated by @hexagen/sync";
5890
+ var BUILTIN_FALLBACK_TEMPLATE2 = `import eslint from '@eslint/js';
5891
+ import tseslint from 'typescript-eslint';
5892
+
5893
+ export default tseslint.config(
5894
+ eslint.configs.recommended,
5895
+ ...tseslint.configs.recommended,
5896
+ {
5897
+ rules: {
5898
+ '@typescript-eslint/no-explicit-any': 'warn',
5899
+ '@typescript-eslint/no-unused-vars': ['warn', { argsIgnorePattern: '^_' }],
5900
+ },
5901
+ },
5902
+ {
5903
+ ignores: ['dist/**', 'node_modules/**'],
5904
+ },
5905
+ );
5906
+ `;
5907
+ function resolveTemplate3(manifest, moduleName, usePerContextOverride) {
5908
+ const contextOverride = usePerContextOverride ? manifest.bounded_contexts?.find((c) => c.name === moduleName)?.generator?.eslint : void 0;
5909
+ if (contextOverride?.template !== void 0) {
5910
+ return { template: contextOverride.template, source: "per-context" };
5911
+ }
5912
+ const rootLevel = manifest.workspaceDefaults?.eslint;
5913
+ if (rootLevel?.template !== void 0) {
5914
+ return { template: rootLevel.template, source: "workspace" };
5915
+ }
5916
+ const monorepoLevel = manifest.monorepo?.workspaceDefaults?.eslint;
5917
+ if (monorepoLevel?.template !== void 0) {
5918
+ return { template: monorepoLevel.template, source: "workspace" };
5919
+ }
5920
+ return { template: BUILTIN_FALLBACK_TEMPLATE2, source: "fallback" };
5921
+ }
5922
+ function withGeneratedMarker(content) {
5923
+ if (content.startsWith(GENERATED_MARKER_LINE)) {
5924
+ return content;
5925
+ }
5926
+ return `${GENERATED_MARKER_LINE}
5927
+ ${content}`;
5928
+ }
5929
+ async function generateEslintConfig(moduleDir, moduleName, config, report, options = {}) {
5930
+ const result = createEmptyResult();
5931
+ const filePath = path33__default.join(moduleDir, "eslint.config.js");
5932
+ try {
5933
+ const { template, source } = resolveTemplate3(
5934
+ config.manifest,
5935
+ moduleName,
5936
+ options.usePerContextOverride ?? true
5937
+ );
5938
+ if (typeof template !== "string" || template.length === 0) {
5939
+ const message = `No eslint template resolved for ${moduleName} (source: ${source}); skipping`;
5940
+ config.logger.error(message);
5941
+ if (report) report.record("error", filePath, message);
5942
+ result.skipped.push(filePath);
5943
+ result.summary = message;
5944
+ return result;
5945
+ }
5946
+ const scope = resolveScope(config.manifest);
5947
+ const { output: interpolated, warnings } = interpolate(template, {
5948
+ packageName: moduleName,
5949
+ scope
5950
+ });
5951
+ for (const missingVar of warnings) {
5952
+ const message = `Missing interpolation variable "${missingVar}" in eslint template for ${moduleName} (source: ${source}); placeholder left verbatim`;
5953
+ config.logger.warn(message);
5954
+ if (report) report.record("warning", filePath, message);
5955
+ }
5956
+ const content = withGeneratedMarker(interpolated);
5957
+ const status = await safeWriteFileAtomic(
5958
+ filePath,
5959
+ content,
5960
+ config,
5961
+ report,
5962
+ false
5963
+ );
5964
+ if (status === "created") result.created.push(filePath);
5965
+ if (status === "updated") result.updated.push(filePath);
5966
+ if (status === "skipped" || status === "protected")
5967
+ result.skipped.push(filePath);
5968
+ result.totalOps += status === "created" || status === "updated" ? 1 : 0;
5969
+ return result;
5970
+ } catch (err3) {
5971
+ const message = err3 instanceof Error ? err3.message : String(err3);
5972
+ result.error = err3 instanceof Error ? err3 : new Error(`eslint generation failed for ${moduleName}: ${message}`);
5973
+ result.summary = `eslint generation failed for ${moduleName}: ${message}`;
5974
+ config.logger.error(result.summary);
5975
+ if (report) report.record("error", filePath, result.summary);
5976
+ return result;
5977
+ }
5978
+ }
5742
5979
 
5743
5980
  // src/generators/apps.ts
5744
5981
  function resolveFrameworkConfig(framework, manifestConfig) {
@@ -5749,7 +5986,8 @@ function resolveFrameworkConfig(framework, manifestConfig) {
5749
5986
  return {
5750
5987
  packageJson: manifestConfig.packageJson ?? builtin.packageJson,
5751
5988
  tsConfig: manifestConfig.tsConfig ?? builtin.tsConfig,
5752
- entryPoint: manifestConfig.entryPoint ?? builtin.entryPoint
5989
+ entryPoint: manifestConfig.entryPoint ?? builtin.entryPoint,
5990
+ extraFiles: manifestConfig.extraFiles ?? builtin.extraFiles
5753
5991
  };
5754
5992
  }
5755
5993
  function interpolateWithLogging2(template, vars, context, config) {
@@ -5773,6 +6011,57 @@ function recordStatus2(result, filePath, status) {
5773
6011
  result.skipped.push(filePath);
5774
6012
  }
5775
6013
  }
6014
+ function mergeResult(result, sub) {
6015
+ result.created.push(...sub.created);
6016
+ result.updated.push(...sub.updated);
6017
+ result.skipped.push(...sub.skipped);
6018
+ result.totalOps += sub.totalOps;
6019
+ if (sub.error && !result.error) {
6020
+ result.error = sub.error;
6021
+ result.summary = sub.summary;
6022
+ }
6023
+ }
6024
+ async function emitAppFile(appDir, relPath, template, vars, config, report, result, appName) {
6025
+ const content = interpolateWithLogging2(
6026
+ template,
6027
+ vars,
6028
+ `apps/${appName}/${relPath}`,
6029
+ config
6030
+ );
6031
+ const target = path33__default.resolve(appDir, relPath);
6032
+ const relative = path33__default.relative(appDir, target);
6033
+ if (relative === "" || relative.startsWith("..") || path33__default.isAbsolute(relative)) {
6034
+ config.logger.warn(
6035
+ `[apps] skipping file with unsafe path (escapes apps/${appName}): ${relPath}`
6036
+ );
6037
+ if (report) {
6038
+ report.record(
6039
+ "blocked",
6040
+ appName,
6041
+ `Unsafe file path (potential path traversal): ${relPath}`
6042
+ );
6043
+ }
6044
+ return "unsafe";
6045
+ }
6046
+ if (isInScope(target, config)) {
6047
+ try {
6048
+ await fs25.mkdir(path33__default.dirname(target), { recursive: true });
6049
+ } catch (err3) {
6050
+ const message = err3 instanceof Error ? err3.message : String(err3);
6051
+ config.logger.error(
6052
+ `[apps] failed to create dir for "${appName}" file ${relPath}: ${message}`
6053
+ );
6054
+ if (report) report.record("blocked", appName, message);
6055
+ return "error";
6056
+ }
6057
+ }
6058
+ recordStatus2(
6059
+ result,
6060
+ target,
6061
+ await safeWriteFileAtomic(target, content, config, report)
6062
+ );
6063
+ return "ok";
6064
+ }
5776
6065
  async function generateApps(config, report) {
5777
6066
  const result = createEmptyResult();
5778
6067
  try {
@@ -5792,6 +6081,19 @@ async function generateApps(config, report) {
5792
6081
  config.logger.warn(`[apps] skipping entry with missing or empty name`);
5793
6082
  continue;
5794
6083
  }
6084
+ if (app.name.includes("..") || app.name.includes("/") || app.name.includes("\\") || app.name.startsWith(".")) {
6085
+ config.logger.warn(
6086
+ `[apps] skipping app with unsafe name (potential path traversal): ${app.name}`
6087
+ );
6088
+ if (report) {
6089
+ report.record(
6090
+ "blocked",
6091
+ app.name,
6092
+ "Unsafe app name (potential path traversal)"
6093
+ );
6094
+ }
6095
+ continue;
6096
+ }
5795
6097
  if (seen.has(app.name)) {
5796
6098
  config.logger.warn(
5797
6099
  `[apps] duplicate app name "${app.name}" — keeping first occurrence, skipping this duplicate`
@@ -5834,18 +6136,20 @@ async function generateApps(config, report) {
5834
6136
  version: app.version ?? "",
5835
6137
  depends_on: (app.depends_on ?? []).join(", ")
5836
6138
  };
5837
- const appDir = path28__default.join(config.workspaceRoot, "apps", app.name);
5838
- const srcDir = path28__default.join(appDir, "src");
5839
- try {
5840
- await fs22.mkdir(appDir, { recursive: true });
5841
- await fs22.mkdir(srcDir, { recursive: true });
5842
- } catch (err3) {
5843
- const message = err3 instanceof Error ? err3.message : String(err3);
5844
- config.logger.error(
5845
- `[apps] failed to create directory for "${app.name}": ${message}`
5846
- );
5847
- if (report) report.record("blocked", app.name, message);
5848
- continue;
6139
+ const appDir = path33__default.join(config.workspaceRoot, "apps", app.name);
6140
+ const srcDir = path33__default.join(appDir, "src");
6141
+ if (isInScope(appDir, config)) {
6142
+ try {
6143
+ await fs25.mkdir(appDir, { recursive: true });
6144
+ await fs25.mkdir(srcDir, { recursive: true });
6145
+ } catch (err3) {
6146
+ const message = err3 instanceof Error ? err3.message : String(err3);
6147
+ config.logger.error(
6148
+ `[apps] failed to create directory for "${app.name}": ${message}`
6149
+ );
6150
+ if (report) report.record("blocked", app.name, message);
6151
+ continue;
6152
+ }
5849
6153
  }
5850
6154
  const pkgTemplate = frameworkConfig.packageJson?.template;
5851
6155
  if (pkgTemplate) {
@@ -5855,7 +6159,7 @@ async function generateApps(config, report) {
5855
6159
  `apps/${app.name}/package.json`,
5856
6160
  config
5857
6161
  );
5858
- const pkgPath = path28__default.join(appDir, "package.json");
6162
+ const pkgPath = path33__default.join(appDir, "package.json");
5859
6163
  const status = await safeWriteFileAtomic(
5860
6164
  pkgPath,
5861
6165
  pkgContent,
@@ -5871,7 +6175,7 @@ async function generateApps(config, report) {
5871
6175
  const tsConfig = frameworkConfig.tsConfig;
5872
6176
  if (tsConfig) {
5873
6177
  const tsContent = JSON.stringify(tsConfig, null, 2) + "\n";
5874
- const tsPath = path28__default.join(appDir, "tsconfig.json");
6178
+ const tsPath = path33__default.join(appDir, "tsconfig.json");
5875
6179
  const status = await safeWriteFileAtomic(
5876
6180
  tsPath,
5877
6181
  tsContent,
@@ -5886,37 +6190,47 @@ async function generateApps(config, report) {
5886
6190
  }
5887
6191
  const entry = frameworkConfig.entryPoint;
5888
6192
  if (entry?.path && entry.template !== void 0) {
5889
- const entryContent = interpolateWithLogging2(
6193
+ const status = await emitAppFile(
6194
+ appDir,
6195
+ entry.path,
5890
6196
  entry.template,
5891
6197
  vars,
5892
- `apps/${app.name}/${entry.path}`,
5893
- config
5894
- );
5895
- const entryPath = path28__default.join(appDir, entry.path);
5896
- try {
5897
- await fs22.mkdir(path28__default.dirname(entryPath), { recursive: true });
5898
- } catch (err3) {
5899
- const message = err3 instanceof Error ? err3.message : String(err3);
5900
- config.logger.error(
5901
- `[apps] failed to create entry-point dir for "${app.name}": ${message}`
5902
- );
5903
- if (report) report.record("blocked", app.name, message);
5904
- continue;
5905
- }
5906
- const status = await safeWriteFileAtomic(
5907
- entryPath,
5908
- entryContent,
5909
6198
  config,
5910
- report
6199
+ report,
6200
+ result,
6201
+ app.name
5911
6202
  );
5912
- recordStatus2(result, entryPath, status);
6203
+ if (status !== "ok") continue;
5913
6204
  } else {
5914
6205
  config.logger.warn(
5915
6206
  `[apps] framework "${framework}" has no entryPoint template — skipping entry file for "${app.name}"`
5916
6207
  );
5917
6208
  }
6209
+ for (const extra of frameworkConfig.extraFiles ?? []) {
6210
+ if (!extra?.path || extra.template === void 0) continue;
6211
+ await emitAppFile(
6212
+ appDir,
6213
+ extra.path,
6214
+ extra.template,
6215
+ vars,
6216
+ config,
6217
+ report,
6218
+ result,
6219
+ app.name
6220
+ );
6221
+ }
6222
+ const eslintResult = await generateEslintConfig(
6223
+ appDir,
6224
+ app.name,
6225
+ config,
6226
+ report,
6227
+ { usePerContextOverride: false }
6228
+ );
6229
+ mergeResult(result, eslintResult);
6230
+ }
6231
+ if (!result.error) {
6232
+ result.summary = `apps: ${result.created.length} created, ${result.updated.length} updated, ${result.skipped.length} skipped`;
5918
6233
  }
5919
- result.summary = `apps: ${result.created.length} created, ${result.updated.length} updated, ${result.skipped.length} skipped`;
5920
6234
  return result;
5921
6235
  } catch (err3) {
5922
6236
  const message = err3 instanceof Error ? err3.message : String(err3);
@@ -5925,91 +6239,69 @@ async function generateApps(config, report) {
5925
6239
  return result;
5926
6240
  }
5927
6241
  }
5928
- var GENERATED_MARKER_LINE = "// @generated by @hexagen/sync";
5929
- var BUILTIN_FALLBACK_TEMPLATE2 = `import eslint from '@eslint/js';
5930
- import tseslint from 'typescript-eslint';
5931
-
5932
- export default tseslint.config(
5933
- eslint.configs.recommended,
5934
- ...tseslint.configs.recommended,
5935
- {
5936
- rules: {
5937
- '@typescript-eslint/no-explicit-any': 'warn',
5938
- '@typescript-eslint/no-unused-vars': ['warn', { argsIgnorePattern: '^_' }],
5939
- },
5940
- },
5941
- {
5942
- ignores: ['dist/**', 'node_modules/**'],
5943
- },
5944
- );
5945
- `;
5946
- function resolveTemplate3(manifest, moduleName) {
5947
- const contextOverride = manifest.bounded_contexts?.find((c) => c.name === moduleName)?.generator?.eslint;
5948
- if (contextOverride?.template !== void 0) {
5949
- return { template: contextOverride.template, source: "per-context" };
5950
- }
5951
- const rootLevel = manifest.workspaceDefaults?.eslint;
5952
- if (rootLevel?.template !== void 0) {
5953
- return { template: rootLevel.template, source: "workspace" };
5954
- }
5955
- const monorepoLevel = manifest.monorepo?.workspaceDefaults?.eslint;
5956
- if (monorepoLevel?.template !== void 0) {
5957
- return { template: monorepoLevel.template, source: "workspace" };
5958
- }
5959
- return { template: BUILTIN_FALLBACK_TEMPLATE2, source: "fallback" };
5960
- }
5961
- function withGeneratedMarker(content) {
5962
- if (content.startsWith(GENERATED_MARKER_LINE)) {
5963
- return content;
5964
- }
5965
- return `${GENERATED_MARKER_LINE}
5966
- ${content}`;
5967
- }
5968
- async function generateEslintConfig(moduleDir, moduleName, config, report) {
5969
- const result = createEmptyResult();
5970
- const filePath = path28__default.join(moduleDir, "eslint.config.js");
5971
- try {
5972
- const { template, source } = resolveTemplate3(config.manifest, moduleName);
5973
- if (typeof template !== "string" || template.length === 0) {
5974
- const message = `No eslint template resolved for ${moduleName} (source: ${source}); skipping`;
5975
- config.logger.error(message);
5976
- if (report) report.record("error", filePath, message);
5977
- result.skipped.push(filePath);
5978
- result.summary = message;
5979
- return result;
5980
- }
5981
- const scope = resolveScope(config.manifest);
5982
- const { output: interpolated, warnings } = interpolate(template, {
5983
- packageName: moduleName,
5984
- scope
5985
- });
5986
- for (const missingVar of warnings) {
5987
- const message = `Missing interpolation variable "${missingVar}" in eslint template for ${moduleName} (source: ${source}); placeholder left verbatim`;
5988
- config.logger.warn(message);
5989
- if (report) report.record("warning", filePath, message);
5990
- }
5991
- const content = withGeneratedMarker(interpolated);
5992
- const status = await safeWriteFileAtomic(
5993
- filePath,
5994
- content,
5995
- config,
5996
- report,
5997
- false
5998
- );
5999
- if (status === "created") result.created.push(filePath);
6000
- if (status === "updated") result.updated.push(filePath);
6001
- if (status === "skipped" || status === "protected")
6002
- result.skipped.push(filePath);
6003
- result.totalOps += status === "created" || status === "updated" ? 1 : 0;
6004
- return result;
6005
- } catch (err3) {
6006
- const message = err3 instanceof Error ? err3.message : String(err3);
6007
- result.error = err3 instanceof Error ? err3 : new Error(`eslint generation failed for ${moduleName}: ${message}`);
6008
- result.summary = `eslint generation failed for ${moduleName}: ${message}`;
6009
- config.logger.error(result.summary);
6010
- if (report) report.record("error", filePath, result.summary);
6011
- return result;
6012
- }
6242
+ function relativeImportSpecifier(fromFile, toFile) {
6243
+ let rel = path33__default.relative(path33__default.dirname(fromFile), toFile).split(path33__default.sep).join("/").replace(/\.tsx?$/, ".js");
6244
+ if (!rel.startsWith(".")) rel = `./${rel}`;
6245
+ return rel;
6246
+ }
6247
+ function rewriteRelativeSpecifier(specifier, fromFile, toFile) {
6248
+ if (!specifier.startsWith(".")) return specifier;
6249
+ const absolute = path33__default.resolve(path33__default.dirname(fromFile), specifier);
6250
+ let rel = path33__default.relative(path33__default.dirname(toFile), absolute).split(path33__default.sep).join("/");
6251
+ if (!rel.startsWith(".")) rel = `./${rel}`;
6252
+ return rel;
6253
+ }
6254
+ var RESERVED_IDENTIFIERS = /* @__PURE__ */ new Set([
6255
+ "break",
6256
+ "case",
6257
+ "catch",
6258
+ "class",
6259
+ "const",
6260
+ "continue",
6261
+ "debugger",
6262
+ "default",
6263
+ "delete",
6264
+ "do",
6265
+ "else",
6266
+ "enum",
6267
+ "export",
6268
+ "extends",
6269
+ "false",
6270
+ "finally",
6271
+ "for",
6272
+ "function",
6273
+ "if",
6274
+ "import",
6275
+ "in",
6276
+ "instanceof",
6277
+ "new",
6278
+ "null",
6279
+ "return",
6280
+ "super",
6281
+ "switch",
6282
+ "this",
6283
+ "throw",
6284
+ "true",
6285
+ "try",
6286
+ "typeof",
6287
+ "var",
6288
+ "void",
6289
+ "while",
6290
+ "with",
6291
+ "yield",
6292
+ "let",
6293
+ "static",
6294
+ "implements",
6295
+ "interface",
6296
+ "package",
6297
+ "private",
6298
+ "protected",
6299
+ "public",
6300
+ "await"
6301
+ ]);
6302
+ function safeParamName(name) {
6303
+ const candidate = name.length === 0 ? "dep" : name;
6304
+ return RESERVED_IDENTIFIERS.has(candidate) ? `${candidate}_` : candidate;
6013
6305
  }
6014
6306
  function analyzePortFile(portFilePath) {
6015
6307
  try {
@@ -6086,13 +6378,22 @@ function extractImports(importDecls) {
6086
6378
  }
6087
6379
  return imports;
6088
6380
  }
6089
- function generateAdapterFromPort(analysis, adapterName) {
6381
+ function generateAdapterFromPort(analysis, adapterName, portImportSpecifier, outputFilePath) {
6090
6382
  const { interfaceName, methods, imports } = analysis;
6091
- const importStatements = imports.map((imp) => {
6092
- const typeOnly = imp.isTypeOnly ? "type " : "";
6093
- const names = imp.namedImports.join(", ");
6094
- return `import ${typeOnly}{ ${names} } from '${imp.moduleSpecifier}';`;
6095
- }).join("\n");
6383
+ const portImport = portImportSpecifier ? `import type { ${interfaceName} } from '${portImportSpecifier}';` : "";
6384
+ const importStatements = [
6385
+ portImport,
6386
+ ...imports.map((imp) => {
6387
+ const specifier = outputFilePath ? rewriteRelativeSpecifier(
6388
+ imp.moduleSpecifier,
6389
+ analysis.filePath,
6390
+ outputFilePath
6391
+ ) : imp.moduleSpecifier;
6392
+ const typeOnly = imp.isTypeOnly ? "type " : "";
6393
+ const names = imp.namedImports.join(", ");
6394
+ return `import ${typeOnly}{ ${names} } from '${specifier}';`;
6395
+ })
6396
+ ].filter(Boolean).join("\n");
6096
6397
  const methodImpls = methods.map((method) => {
6097
6398
  const params = method.parameters.map((p) => `${p.name}${p.isOptional ? "?" : ""}: ${p.type}`).join(", ");
6098
6399
  const asyncKeyword = method.isAsync ? "async " : "";
@@ -6120,16 +6421,48 @@ ${methodImpls}
6120
6421
  }
6121
6422
  `;
6122
6423
  }
6123
- function generateUseCaseFromPort(analysis, useCaseName, outPorts) {
6424
+ function generateUseCaseFromPort(analysis, useCaseName, outPorts, portImportSpecifier, outputFilePath) {
6124
6425
  const { interfaceName, methods, imports } = analysis;
6125
- const importStatements = imports.map((imp) => {
6426
+ const importLines = [];
6427
+ const taken = /* @__PURE__ */ new Set();
6428
+ const importType = (name, specifier) => {
6429
+ let local = name;
6430
+ let n = 2;
6431
+ while (taken.has(local)) local = `${name}_${n++}`;
6432
+ taken.add(local);
6433
+ importLines.push(
6434
+ local === name ? `import type { ${name} } from '${specifier}';` : `import type { ${name} as ${local} } from '${specifier}';`
6435
+ );
6436
+ return local;
6437
+ };
6438
+ const implementsName = portImportSpecifier ? importType(interfaceName, portImportSpecifier) : interfaceName;
6439
+ const seenDeps = /* @__PURE__ */ new Map();
6440
+ const usedParams = /* @__PURE__ */ new Set();
6441
+ const constructorEntries = [];
6442
+ for (const p of outPorts) {
6443
+ const depKey = `${p.interfaceName}|${p.importSpecifier}`;
6444
+ if (seenDeps.has(depKey)) continue;
6445
+ const localType = importType(p.interfaceName, p.importSpecifier);
6446
+ seenDeps.set(depKey, localType);
6447
+ let param = safeParamName(p.paramName);
6448
+ const paramBase = param;
6449
+ let n = 2;
6450
+ while (usedParams.has(param)) param = `${paramBase}${n++}`;
6451
+ usedParams.add(param);
6452
+ constructorEntries.push(`private readonly ${param}: ${localType}`);
6453
+ }
6454
+ for (const imp of imports) {
6455
+ const specifier = outputFilePath ? rewriteRelativeSpecifier(
6456
+ imp.moduleSpecifier,
6457
+ analysis.filePath,
6458
+ outputFilePath
6459
+ ) : imp.moduleSpecifier;
6126
6460
  const typeOnly = imp.isTypeOnly ? "type " : "";
6127
- const names = imp.namedImports.join(", ");
6128
- return `import ${typeOnly}{ ${names} } from '${imp.moduleSpecifier}';`;
6129
- }).join("\n");
6130
- const constructorParams = outPorts.map(
6131
- (port) => `private readonly ${port.charAt(0).toLowerCase() + port.slice(1)}: ${port}`
6132
- ).join(",\n ");
6461
+ const line = `import ${typeOnly}{ ${imp.namedImports.join(", ")} } from '${specifier}';`;
6462
+ if (!importLines.includes(line)) importLines.push(line);
6463
+ }
6464
+ const importStatements = importLines.join("\n");
6465
+ const constructorParams = constructorEntries.join(",\n ");
6133
6466
  const methodImpls = methods.map((method) => {
6134
6467
  const params = method.parameters.map((p) => `${p.name}${p.isOptional ? "?" : ""}: ${p.type}`).join(", ");
6135
6468
  const asyncKeyword = method.isAsync ? "async " : "";
@@ -6142,12 +6475,12 @@ function generateUseCaseFromPort(analysis, useCaseName, outPorts) {
6142
6475
  throw new Error('Not implemented: ${method.name}');
6143
6476
  }`;
6144
6477
  }).join("\n\n");
6145
- const constructorBlock = outPorts.length > 0 ? ` constructor(
6478
+ const constructorBlock = constructorEntries.length > 0 ? ` constructor(
6146
6479
  ${constructorParams}
6147
6480
  ) {}` : "";
6148
6481
  return `// @generated use-case stub — edit freely
6149
6482
  /**
6150
- * ${useCaseName} implements ${interfaceName}
6483
+ * ${useCaseName} implements ${implementsName}
6151
6484
  *
6152
6485
  * This use case was generated from the port interface.
6153
6486
  * Replace TODO implementations with actual business logic.
@@ -6155,7 +6488,7 @@ function generateUseCaseFromPort(analysis, useCaseName, outPorts) {
6155
6488
 
6156
6489
  ${importStatements}
6157
6490
 
6158
- export class ${useCaseName} implements ${interfaceName} {
6491
+ export class ${useCaseName} implements ${implementsName} {
6159
6492
  ${constructorBlock}
6160
6493
 
6161
6494
  ${methodImpls}
@@ -6548,9 +6881,15 @@ function resolveNaming(kind, contextNaming, manifestNaming) {
6548
6881
  return contextNaming?.[kind] ?? manifestNaming?.[kind] ?? DEFAULT_NAMING[kind];
6549
6882
  }
6550
6883
  async function writeStubFile(filePath, content, config, report) {
6884
+ if (!isInScope(filePath, config)) {
6885
+ config.logger.debug(
6886
+ `skipped (outside --only) ${path33__default.relative(config.workspaceRoot, filePath)}`
6887
+ );
6888
+ return "skipped";
6889
+ }
6551
6890
  try {
6552
- await fs22.stat(filePath);
6553
- const relative = path28__default.relative(config.workspaceRoot, filePath);
6891
+ await fs25.stat(filePath);
6892
+ const relative = path33__default.relative(config.workspaceRoot, filePath);
6554
6893
  config.logger.debug(`stub preserved ${relative}`);
6555
6894
  if (report) {
6556
6895
  report.record(
@@ -6565,15 +6904,17 @@ async function writeStubFile(filePath, content, config, report) {
6565
6904
  throw err3;
6566
6905
  }
6567
6906
  }
6568
- await fs22.mkdir(path28__default.dirname(filePath), { recursive: true });
6907
+ await fs25.mkdir(path33__default.dirname(filePath), { recursive: true });
6569
6908
  return safeWriteFileAtomic(filePath, content, config, report, false);
6570
6909
  }
6571
- async function tryAnalyzeRelatedPort(moduleDir, name, kind, context) {
6910
+ async function tryAnalyzeRelatedPort(moduleDir, name, kind, context, relatedPortNamingTemplate) {
6572
6911
  const portType = kind === "adapter" ? "out" : "in";
6573
6912
  const portSubdir = `application/ports/${portType}`;
6574
6913
  const derivedPortName = name.replace(/Adapter$|UseCase$/, "Port");
6575
6914
  const declaredPorts = portType === "in" ? context.layers?.application?.ports?.in || [] : context.layers?.application?.ports?.out || [];
6576
- if (!declaredPorts.some((p) => portName(p) === derivedPortName)) {
6915
+ if (!declaredPorts.some(
6916
+ (p) => normalizeStubName(portName(p), relatedPortNamingTemplate) === derivedPortName
6917
+ )) {
6577
6918
  return null;
6578
6919
  }
6579
6920
  const possibleFilenames = [
@@ -6582,7 +6923,7 @@ async function tryAnalyzeRelatedPort(moduleDir, name, kind, context) {
6582
6923
  `${derivedPortName}.ts`
6583
6924
  ];
6584
6925
  for (const filename of possibleFilenames) {
6585
- const portFilePath = path28__default.join(moduleDir, "src", portSubdir, filename);
6926
+ const portFilePath = path33__default.join(moduleDir, "src", portSubdir, filename);
6586
6927
  const analysis = analyzePortFile(portFilePath);
6587
6928
  if (analysis) {
6588
6929
  return analysis;
@@ -6590,6 +6931,15 @@ async function tryAnalyzeRelatedPort(moduleDir, name, kind, context) {
6590
6931
  }
6591
6932
  return null;
6592
6933
  }
6934
+ function normalizeStubName(rawName, namingTemplate) {
6935
+ const placeholder = "{name}";
6936
+ const idx = namingTemplate.lastIndexOf(placeholder);
6937
+ const ext = idx >= 0 ? namingTemplate.slice(idx + placeholder.length) : "";
6938
+ const base = ext && rawName.endsWith(ext) ? rawName.slice(0, -ext.length) : rawName;
6939
+ const pascal = base.split(/[^a-zA-Z0-9]+/).filter(Boolean).map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join("");
6940
+ if (pascal.length === 0) return "Stub";
6941
+ return /^[0-9]/.test(pascal) ? `Stub${pascal}` : pascal;
6942
+ }
6593
6943
  async function generateStubs(moduleDir, moduleName, config, report) {
6594
6944
  const result = createEmptyResult();
6595
6945
  const stubs = config.manifest.generator?.sync?.stubs;
@@ -6618,27 +6968,73 @@ async function generateStubs(moduleDir, moduleName, config, report) {
6618
6968
  for (const { kind, subdir, names } of plan) {
6619
6969
  const contentTemplate = resolveTemplate4(kind, manifestTemplates);
6620
6970
  const namingTemplate = resolveNaming(kind, contextNaming, manifestNaming);
6621
- for (const name of names) {
6971
+ for (const rawName of names) {
6972
+ const name = normalizeStubName(rawName, namingTemplate);
6622
6973
  const filename = interpolateWithLog(
6623
6974
  namingTemplate,
6624
6975
  name,
6625
6976
  `stubs.naming.${kind}`,
6626
6977
  config
6627
6978
  );
6979
+ const filePath = path33__default.join(moduleDir, "src", subdir, filename);
6628
6980
  let content;
6629
6981
  if (kind === "adapter" || kind === "useCase") {
6982
+ const relatedPortNaming = resolveNaming(
6983
+ kind === "adapter" ? "outPort" : "inPort",
6984
+ contextNaming,
6985
+ manifestNaming
6986
+ );
6630
6987
  const portAnalysis = await tryAnalyzeRelatedPort(
6631
6988
  moduleDir,
6632
6989
  name,
6633
6990
  kind,
6634
- context
6991
+ context,
6992
+ relatedPortNaming
6635
6993
  );
6636
6994
  if (portAnalysis) {
6637
6995
  if (kind === "adapter") {
6638
- content = generateAdapterFromPort(portAnalysis, name);
6996
+ content = generateAdapterFromPort(
6997
+ portAnalysis,
6998
+ name,
6999
+ relativeImportSpecifier(filePath, portAnalysis.filePath),
7000
+ filePath
7001
+ );
6639
7002
  } else {
6640
- const outPorts = context.layers?.application?.ports?.out?.map(portName) || [];
6641
- content = generateUseCaseFromPort(portAnalysis, name, outPorts);
7003
+ const outPortNaming = resolveNaming(
7004
+ "outPort",
7005
+ contextNaming,
7006
+ manifestNaming
7007
+ );
7008
+ const outPortDir = path33__default.join(
7009
+ moduleDir,
7010
+ "src",
7011
+ "application",
7012
+ "ports",
7013
+ "out"
7014
+ );
7015
+ const outPorts = (context.layers?.application?.ports?.out ?? []).map((p) => {
7016
+ const base = normalizeStubName(portName(p), outPortNaming);
7017
+ const outFile = interpolateWithLog(
7018
+ outPortNaming,
7019
+ base,
7020
+ "stubs.naming.outPort",
7021
+ config
7022
+ );
7023
+ const outPortPath = path33__default.join(outPortDir, outFile);
7024
+ const analyzed = analyzePortFile(outPortPath);
7025
+ return {
7026
+ interfaceName: analyzed?.interfaceName ?? `${base}Port`,
7027
+ paramName: base.charAt(0).toLowerCase() + base.slice(1),
7028
+ importSpecifier: relativeImportSpecifier(filePath, outPortPath)
7029
+ };
7030
+ });
7031
+ content = generateUseCaseFromPort(
7032
+ portAnalysis,
7033
+ name,
7034
+ outPorts,
7035
+ relativeImportSpecifier(filePath, portAnalysis.filePath),
7036
+ filePath
7037
+ );
6642
7038
  }
6643
7039
  config.logger.debug(`Generated ${kind} '${name}' from port analysis`);
6644
7040
  } else {
@@ -6657,7 +7053,6 @@ async function generateStubs(moduleDir, moduleName, config, report) {
6657
7053
  config
6658
7054
  );
6659
7055
  }
6660
- const filePath = path28__default.join(moduleDir, "src", subdir, filename);
6661
7056
  const status = await writeStubFile(filePath, content, config, report);
6662
7057
  if (status === "created") result.created.push(filePath);
6663
7058
  if (status === "updated") result.updated.push(filePath);
@@ -6668,6 +7063,347 @@ async function generateStubs(moduleDir, moduleName, config, report) {
6668
7063
  }
6669
7064
  return result;
6670
7065
  }
7066
+ var OHS_NOTE = "\n *\n * Open Host Service (open-host): this is this context's published language for consuming contexts — keep it stable.";
7067
+ var ACL_NOTE = "\n *\n * Anti-Corruption Layer (acl): translate the upstream contract into this context's own domain model; do not leak provider types inward.";
7068
+ function recordStatus3(result, filePath, status) {
7069
+ if (status === "created") result.created.push(filePath);
7070
+ else if (status === "updated") result.updated.push(filePath);
7071
+ else if (status === "skipped" || status === "protected")
7072
+ result.skipped.push(filePath);
7073
+ if (status === "created" || status === "updated") result.totalOps += 1;
7074
+ }
7075
+ function addAll(map, key, values) {
7076
+ const set = map.get(key) ?? /* @__PURE__ */ new Set();
7077
+ values.forEach((v) => set.add(v));
7078
+ map.set(key, set);
7079
+ }
7080
+ function toPascalCase2(stem) {
7081
+ return stem.split(/[-.]/).filter((part) => part.length > 0).map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join("");
7082
+ }
7083
+ function toCamelCase(pascal) {
7084
+ return pascal.length > 0 ? pascal.charAt(0).toLowerCase() + pascal.slice(1) : pascal;
7085
+ }
7086
+ function isSafePathSegment(name) {
7087
+ return name.length > 0 && !name.includes("..") && !name.includes("/") && !name.includes("\\") && !name.startsWith(".");
7088
+ }
7089
+ function isValidTsIdentifier(name) {
7090
+ return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name);
7091
+ }
7092
+ function eventContractContent(name) {
7093
+ return `// @generated cross-context event contract — edit freely
7094
+ /**
7095
+ * ${name} is a domain event published across an event-bus boundary.
7096
+ * Both the publishing and subscribing contexts depend on this shared contract.
7097
+ */
7098
+ export interface ${name} {
7099
+ // TODO: define the event payload
7100
+ readonly occurredAt: string;
7101
+ }
7102
+ `;
7103
+ }
7104
+ function dtoContent(op) {
7105
+ return `// @generated cross-context DTO — edit freely
7106
+ /**
7107
+ * Request/response payloads for the ${op} operation, exchanged across the
7108
+ * network boundary. Both the calling (client) and serving (controller) contexts
7109
+ * depend on these shared contracts.
7110
+ */
7111
+ export interface ${op}Request {
7112
+ // TODO: define the request fields
7113
+ readonly _placeholder?: never;
7114
+ }
7115
+
7116
+ export interface ${op}Response {
7117
+ // TODO: define the response fields
7118
+ readonly _placeholder?: never;
7119
+ }
7120
+ `;
7121
+ }
7122
+ function portContent(scope, interfaceName, methods, importedTypes, doc) {
7123
+ const uniqueImports = [...new Set(importedTypes)].sort();
7124
+ const importLine = uniqueImports.length > 0 ? `import type { ${uniqueImports.join(", ")} } from "@${scope}/shared";
7125
+
7126
+ ` : "";
7127
+ const methodLines = methods.map(
7128
+ (m) => ` ${m.name}(${m.paramName}: ${m.paramType}): Promise<${m.returnType}>;`
7129
+ ).join("\n");
7130
+ return `// @generated cross-context port — edit freely
7131
+ ${importLine}/**
7132
+ * ${doc}
7133
+ */
7134
+ export interface ${interfaceName} {
7135
+ ${methodLines}
7136
+ }
7137
+ `;
7138
+ }
7139
+ async function emitPortAndAdapter(result, config, report, scope, spec) {
7140
+ const moduleRoot = path33__default.join(
7141
+ config.workspaceRoot,
7142
+ "packages",
7143
+ spec.contextName
7144
+ );
7145
+ const portDir = path33__default.join(
7146
+ moduleRoot,
7147
+ "src",
7148
+ "application",
7149
+ "ports",
7150
+ spec.portKind
7151
+ );
7152
+ const portPath = path33__default.join(
7153
+ portDir,
7154
+ `${spec.portBase}.${spec.portKind}-port.ts`
7155
+ );
7156
+ if (!isInScope(portPath, config)) {
7157
+ return;
7158
+ }
7159
+ await fs25.mkdir(portDir, { recursive: true });
7160
+ recordStatus3(
7161
+ result,
7162
+ portPath,
7163
+ await safeWriteFileAtomic(
7164
+ portPath,
7165
+ portContent(
7166
+ scope,
7167
+ spec.interfaceName,
7168
+ spec.methods,
7169
+ spec.importedTypes,
7170
+ spec.doc
7171
+ ),
7172
+ config,
7173
+ report
7174
+ )
7175
+ );
7176
+ const analysis = analyzePortFile(portPath);
7177
+ if (!analysis) {
7178
+ config.logger.warn(
7179
+ `[cross-context] could not analyze ${portPath}; skipping adapter`
7180
+ );
7181
+ return;
7182
+ }
7183
+ const adapterDir = path33__default.join(moduleRoot, "src", "infrastructure", "adapters");
7184
+ const adapterPath = path33__default.join(adapterDir, `${spec.portBase}.adapter.ts`);
7185
+ if (!isInScope(adapterPath, config)) {
7186
+ return;
7187
+ }
7188
+ await fs25.mkdir(adapterDir, { recursive: true });
7189
+ const adapterClassName = `${toPascalCase2(spec.portBase)}Adapter`;
7190
+ const portSpecifier = relativeImportSpecifier(adapterPath, portPath);
7191
+ recordStatus3(
7192
+ result,
7193
+ adapterPath,
7194
+ await safeWriteFileAtomic(
7195
+ adapterPath,
7196
+ generateAdapterFromPort(analysis, adapterClassName, portSpecifier),
7197
+ config,
7198
+ report
7199
+ )
7200
+ );
7201
+ }
7202
+ function operationMethods(ops) {
7203
+ return ops.map((op) => ({
7204
+ name: toCamelCase(op),
7205
+ paramName: "request",
7206
+ paramType: `${op}Request`,
7207
+ returnType: `${op}Response`
7208
+ }));
7209
+ }
7210
+ function operationImports(ops) {
7211
+ return ops.flatMap((op) => [`${op}Request`, `${op}Response`]);
7212
+ }
7213
+ async function writeSharedContract(result, config, report, relSegments, content) {
7214
+ const contractPath = path33__default.join(
7215
+ config.workspaceRoot,
7216
+ "packages",
7217
+ "shared",
7218
+ "src",
7219
+ ...relSegments
7220
+ );
7221
+ await fs25.mkdir(path33__default.dirname(contractPath), { recursive: true });
7222
+ recordStatus3(
7223
+ result,
7224
+ contractPath,
7225
+ await safeWriteFileAtomic(contractPath, content, config, report)
7226
+ );
7227
+ }
7228
+ async function generateCrossContext(config, report) {
7229
+ const result = createEmptyResult();
7230
+ const edges = config.manifest.cross_context;
7231
+ if (!Array.isArray(edges) || edges.length === 0) return result;
7232
+ const scope = resolveScope(config.manifest);
7233
+ const allEvents = /* @__PURE__ */ new Set();
7234
+ const publisherEvents = /* @__PURE__ */ new Map();
7235
+ const subscriberEvents = /* @__PURE__ */ new Map();
7236
+ const allOperations = /* @__PURE__ */ new Set();
7237
+ const controllerOps = /* @__PURE__ */ new Map();
7238
+ const clientOps = /* @__PURE__ */ new Map();
7239
+ const ohsProviders = /* @__PURE__ */ new Set();
7240
+ const aclConsumers = /* @__PURE__ */ new Set();
7241
+ for (const edge of edges) {
7242
+ if (edge.provider && !isSafePathSegment(edge.provider) || edge.consumer && !isSafePathSegment(edge.consumer)) {
7243
+ config.logger.warn(
7244
+ `[cross-context] skipping edge with unsafe context name: ${edge.consumer} -> ${edge.provider}`
7245
+ );
7246
+ continue;
7247
+ }
7248
+ if (edge.integrationPattern === "open-host" && edge.provider)
7249
+ ohsProviders.add(edge.provider);
7250
+ if (edge.integrationPattern === "acl" && edge.consumer)
7251
+ aclConsumers.add(edge.consumer);
7252
+ if (edge.transport === "network") {
7253
+ const operations = (edge.operations ?? []).filter(
7254
+ (o) => typeof o === "string" && isValidTsIdentifier(o)
7255
+ );
7256
+ operations.forEach((o) => allOperations.add(o));
7257
+ if (edge.provider) addAll(controllerOps, edge.provider, operations);
7258
+ if (edge.consumer) addAll(clientOps, edge.consumer, operations);
7259
+ } else {
7260
+ const events = (edge.events ?? []).filter(
7261
+ (e) => typeof e === "string" && isValidTsIdentifier(e)
7262
+ );
7263
+ events.forEach((e) => allEvents.add(e));
7264
+ if (edge.provider) addAll(publisherEvents, edge.provider, events);
7265
+ if (edge.consumer) addAll(subscriberEvents, edge.consumer, events);
7266
+ }
7267
+ }
7268
+ for (const event of [...allEvents].sort()) {
7269
+ await writeSharedContract(
7270
+ result,
7271
+ config,
7272
+ report,
7273
+ ["domain", "events", `${event}.event.ts`],
7274
+ eventContractContent(event)
7275
+ );
7276
+ }
7277
+ for (const provider of [...publisherEvents.keys()].sort()) {
7278
+ const events = [...publisherEvents.get(provider) ?? []].sort();
7279
+ await emitPortAndAdapter(result, config, report, scope, {
7280
+ contextName: provider,
7281
+ portKind: "out",
7282
+ portBase: "message-publisher",
7283
+ interfaceName: "MessagePublisherPort",
7284
+ methods: [
7285
+ {
7286
+ name: "publish",
7287
+ paramName: "event",
7288
+ paramType: events.join(" | ") || "unknown",
7289
+ returnType: "void"
7290
+ }
7291
+ ],
7292
+ importedTypes: events,
7293
+ doc: "Publishes this context's domain events across the event-bus boundary." + (ohsProviders.has(provider) ? OHS_NOTE : "")
7294
+ });
7295
+ }
7296
+ for (const consumer of [...subscriberEvents.keys()].sort()) {
7297
+ const events = [...subscriberEvents.get(consumer) ?? []].sort();
7298
+ await emitPortAndAdapter(result, config, report, scope, {
7299
+ contextName: consumer,
7300
+ portKind: "in",
7301
+ portBase: "event-listener",
7302
+ interfaceName: "EventListenerPort",
7303
+ methods: [
7304
+ {
7305
+ name: "handle",
7306
+ paramName: "event",
7307
+ paramType: events.join(" | ") || "unknown",
7308
+ returnType: "void"
7309
+ }
7310
+ ],
7311
+ importedTypes: events,
7312
+ doc: "Handles cross-context events this context subscribes to." + (aclConsumers.has(consumer) ? ACL_NOTE : "")
7313
+ });
7314
+ }
7315
+ for (const op of [...allOperations].sort()) {
7316
+ await writeSharedContract(
7317
+ result,
7318
+ config,
7319
+ report,
7320
+ ["domain", "dtos", `${op}.dto.ts`],
7321
+ dtoContent(op)
7322
+ );
7323
+ }
7324
+ for (const provider of [...controllerOps.keys()].sort()) {
7325
+ const ops = [...controllerOps.get(provider) ?? []].sort();
7326
+ await emitPortAndAdapter(result, config, report, scope, {
7327
+ contextName: provider,
7328
+ portKind: "in",
7329
+ portBase: "rest-controller",
7330
+ interfaceName: "RestControllerPort",
7331
+ methods: operationMethods(ops),
7332
+ importedTypes: operationImports(ops),
7333
+ doc: "Serves this context's operations over the network boundary." + (ohsProviders.has(provider) ? OHS_NOTE : "")
7334
+ });
7335
+ }
7336
+ for (const consumer of [...clientOps.keys()].sort()) {
7337
+ const ops = [...clientOps.get(consumer) ?? []].sort();
7338
+ await emitPortAndAdapter(result, config, report, scope, {
7339
+ contextName: consumer,
7340
+ portKind: "out",
7341
+ portBase: "external-service-client",
7342
+ interfaceName: "ExternalServiceClientPort",
7343
+ methods: operationMethods(ops),
7344
+ importedTypes: operationImports(ops),
7345
+ doc: "Calls operations on the contexts this context depends on over the network." + (aclConsumers.has(consumer) ? ACL_NOTE : "")
7346
+ });
7347
+ }
7348
+ return result;
7349
+ }
7350
+ var RESULT_KERNEL = `// @generated by @hexagen/sync — shared Result kernel (edit freely)
7351
+ /**
7352
+ * Result is the explicit success/failure type generated use-cases return.
7353
+ * Mirrors @hexagen/shared's Result. Created once, then preserved on re-sync.
7354
+ */
7355
+ export type Result<T, E = unknown> =
7356
+ | { success: true; value: T }
7357
+ | { success: false; error: E };
7358
+
7359
+ export const ok = <T>(value: T): Result<T, never> => ({ success: true, value });
7360
+ export const err = <E>(error: E): Result<never, E> => ({
7361
+ success: false,
7362
+ error,
7363
+ });
7364
+ `;
7365
+ async function generateSharedKernel(config, report) {
7366
+ const result = createEmptyResult();
7367
+ if (config.mode !== "external") return result;
7368
+ const hasShared = (config.manifest.bounded_contexts ?? []).some(
7369
+ (bc) => bc.name?.toLowerCase() === "shared"
7370
+ );
7371
+ if (!hasShared) return result;
7372
+ const kernelPath = path33__default.join(
7373
+ config.workspaceRoot,
7374
+ "packages",
7375
+ "shared",
7376
+ "src",
7377
+ "domain",
7378
+ "result.ts"
7379
+ );
7380
+ if (!isInScope(kernelPath, config)) {
7381
+ result.skipped.push(kernelPath);
7382
+ return result;
7383
+ }
7384
+ try {
7385
+ await fs25.stat(kernelPath);
7386
+ result.skipped.push(kernelPath);
7387
+ return result;
7388
+ } catch (err3) {
7389
+ if (err3.code !== "ENOENT") throw err3;
7390
+ }
7391
+ await fs25.mkdir(path33__default.dirname(kernelPath), { recursive: true });
7392
+ const status = await safeWriteFileAtomic(
7393
+ kernelPath,
7394
+ RESULT_KERNEL,
7395
+ config,
7396
+ report,
7397
+ false
7398
+ );
7399
+ if (status === "created" || status === "updated") {
7400
+ result.created.push(kernelPath);
7401
+ result.totalOps += 1;
7402
+ } else {
7403
+ result.skipped.push(kernelPath);
7404
+ }
7405
+ return result;
7406
+ }
6671
7407
  var execAsync = promisify(exec);
6672
7408
  var MAX_BUFFER = 1024 * 1024 * 10;
6673
7409
  async function ensureDependenciesBuilt(config) {
@@ -6695,7 +7431,7 @@ async function ensureDependenciesBuilt(config) {
6695
7431
  }
6696
7432
 
6697
7433
  // src/sync-engine-helpers.ts
6698
- function mergeResult(dest, src) {
7434
+ function mergeResult2(dest, src) {
6699
7435
  dest.created.push(...src.created);
6700
7436
  dest.updated.push(...src.updated);
6701
7437
  dest.skipped.push(...src.skipped);
@@ -6847,12 +7583,23 @@ var IndexManifestSchema = external_exports.object({
6847
7583
  message: "Context plane does not match file path subdirectory",
6848
7584
  path: ["bounded_contexts"]
6849
7585
  });
7586
+ var CrossContextEdgeSchema = external_exports.object({
7587
+ consumer: external_exports.string(),
7588
+ provider: external_exports.string(),
7589
+ transport: external_exports.enum(["event-bus", "network"]),
7590
+ events: external_exports.array(external_exports.string()).optional(),
7591
+ operations: external_exports.array(external_exports.string()).optional(),
7592
+ integrationPattern: external_exports.enum(["open-host", "acl"]).optional()
7593
+ });
6850
7594
  var ManifestSchema = external_exports.object({
6851
7595
  version: external_exports.string().optional(),
6852
7596
  description: external_exports.string().optional(),
6853
7597
  system: external_exports.string().optional(),
6854
7598
  scope: external_exports.string().optional(),
6855
7599
  architecture: external_exports.string().optional(),
7600
+ // The wizard records the chosen workspace template (e.g. "strict-enterprise")
7601
+ // alongside `architecture`; persisted into .architecture/manifest.yaml.
7602
+ workspaceTemplate: external_exports.string().optional(),
6856
7603
  planes: external_exports.record(external_exports.array(external_exports.string())).optional(),
6857
7604
  monorepo: external_exports.record(external_exports.unknown()).optional(),
6858
7605
  generator: external_exports.record(external_exports.unknown()).optional(),
@@ -6867,6 +7614,7 @@ var ManifestSchema = external_exports.object({
6867
7614
  })).optional(),
6868
7615
  bounded_contexts: external_exports.array(BoundedContextSchema),
6869
7616
  apps: external_exports.array(AppSchema).optional(),
7617
+ cross_context: external_exports.array(CrossContextEdgeSchema).optional(),
6870
7618
  context_mappings: external_exports.array(external_exports.object({
6871
7619
  upstream: external_exports.string(),
6872
7620
  downstream: external_exports.string(),
@@ -6935,7 +7683,15 @@ var BoundedContextSchema2 = external_exports.object({
6935
7683
  id: external_exports.string(),
6936
7684
  name: external_exports.string().min(1, "Please enter a name for this bounded context (e.g., 'UserService', 'OrderProcessing')"),
6937
7685
  description: external_exports.string().optional(),
6938
- infrastructureTarget: external_exports.enum(["nestjs", "express", "serverless", "plain-ts"]).optional(),
7686
+ // ADR-0041: `infrastructureTarget` (API backend) and `uiFramework` (below)
7687
+ // are PROJECT-LEVEL choices managed by the wizard's Applications step, which
7688
+ // fans a single selection out to every context. They persist per-context (the
7689
+ // source of truth `deriveApps` reads), but are NOT direct per-context input —
7690
+ // do not re-add per-context UI/API editing without revisiting ADR-0041.
7691
+ // `"none"` = the project opts out of a separate API backend (UI-only, e.g. a
7692
+ // Next.js app with built-in routes); `deriveApps` then emits no `api` app.
7693
+ // Distinct from `undefined` (legacy/unset → defaults to the preset).
7694
+ infrastructureTarget: external_exports.enum(["nestjs", "express", "serverless", "plain-ts", "nitro", "none"]).optional(),
6939
7695
  coreDomainEntities: external_exports.array(external_exports.string()).default([]),
6940
7696
  valueObjects: external_exports.array(external_exports.string()).default([]),
6941
7697
  domainEvents: external_exports.array(external_exports.string()).default([]),
@@ -7020,21 +7776,21 @@ external_exports.object({
7020
7776
  turboConfig: external_exports.record(external_exports.unknown()).optional()
7021
7777
  });
7022
7778
  function assertPathWithinArchitecture(workspaceRoot, relativePath) {
7023
- const resolved = path28__default.resolve(workspaceRoot, ".architecture", relativePath);
7024
- const archRoot = path28__default.resolve(workspaceRoot, ".architecture");
7779
+ const resolved = path33__default.resolve(workspaceRoot, ".architecture", relativePath);
7780
+ const archRoot = path33__default.resolve(workspaceRoot, ".architecture");
7025
7781
  try {
7026
7782
  const realResolved = realpathSync(resolved);
7027
7783
  const realArchRoot = realpathSync(archRoot);
7028
- const archRootWithSep = realArchRoot + path28__default.sep;
7784
+ const archRootWithSep = realArchRoot + path33__default.sep;
7029
7785
  if (realResolved !== realArchRoot && !realResolved.startsWith(archRootWithSep)) {
7030
7786
  throw new Error(`Path traversal detected: "${relativePath}" resolves outside .architecture/`);
7031
7787
  }
7032
7788
  } catch (err3) {
7033
7789
  if (err3 instanceof Error && "code" in err3 && err3.code === "ENOENT") {
7034
7790
  let checkPath = archRoot;
7035
- const pathSegments = path28__default.relative(archRoot, resolved).split(path28__default.sep);
7791
+ const pathSegments = path33__default.relative(archRoot, resolved).split(path33__default.sep);
7036
7792
  for (const segment of pathSegments) {
7037
- checkPath = path28__default.join(checkPath, segment);
7793
+ checkPath = path33__default.join(checkPath, segment);
7038
7794
  try {
7039
7795
  const stat = lstatSync(checkPath);
7040
7796
  if (stat.isSymbolicLink()) {
@@ -7050,7 +7806,7 @@ function assertPathWithinArchitecture(workspaceRoot, relativePath) {
7050
7806
  throw statErr;
7051
7807
  }
7052
7808
  }
7053
- const archRootWithSep = archRoot + path28__default.sep;
7809
+ const archRootWithSep = archRoot + path33__default.sep;
7054
7810
  if (resolved !== archRoot && !resolved.startsWith(archRootWithSep)) {
7055
7811
  throw new Error(`Path traversal detected: "${relativePath}" resolves outside .architecture/`);
7056
7812
  }
@@ -7060,7 +7816,7 @@ function assertPathWithinArchitecture(workspaceRoot, relativePath) {
7060
7816
  }
7061
7817
  }
7062
7818
  async function mergeSplitManifest(workspaceRoot, manifestPath) {
7063
- const content = await fs22.readFile(manifestPath, "utf-8");
7819
+ const content = await fs25.readFile(manifestPath, "utf-8");
7064
7820
  const parsed = yaml9.load(content);
7065
7821
  if (parsed == null) {
7066
7822
  throw new Error("Manifest file is empty");
@@ -7093,10 +7849,10 @@ async function mergeSplitManifest(workspaceRoot, manifestPath) {
7093
7849
  continue;
7094
7850
  }
7095
7851
  assertPathWithinArchitecture(workspaceRoot, indexEntry.file);
7096
- const contextFilePath = path28__default.join(workspaceRoot, ".architecture", indexEntry.file);
7852
+ const contextFilePath = path33__default.join(workspaceRoot, ".architecture", indexEntry.file);
7097
7853
  let contextContent;
7098
7854
  try {
7099
- contextContent = await fs22.readFile(contextFilePath, "utf-8");
7855
+ contextContent = await fs25.readFile(contextFilePath, "utf-8");
7100
7856
  } catch (err3) {
7101
7857
  if (err3 instanceof Error && "code" in err3 && err3.code === "ENOENT") {
7102
7858
  throw new Error(`Context file not found: ${contextFilePath}`);
@@ -7128,10 +7884,10 @@ async function mergeSplitManifest(workspaceRoot, manifestPath) {
7128
7884
  continue;
7129
7885
  }
7130
7886
  assertPathWithinArchitecture(workspaceRoot, appEntry.file);
7131
- const appFilePath = path28__default.join(workspaceRoot, ".architecture", appEntry.file);
7887
+ const appFilePath = path33__default.join(workspaceRoot, ".architecture", appEntry.file);
7132
7888
  let appContent;
7133
7889
  try {
7134
- appContent = await fs22.readFile(appFilePath, "utf-8");
7890
+ appContent = await fs25.readFile(appFilePath, "utf-8");
7135
7891
  } catch (err3) {
7136
7892
  if (err3 instanceof Error && "code" in err3 && err3.code === "ENOENT") {
7137
7893
  throw new Error(`App file not found: ${appFilePath}`);
@@ -7150,23 +7906,23 @@ async function mergeSplitManifest(workspaceRoot, manifestPath) {
7150
7906
 
7151
7907
  // src/sync-engine-init.ts
7152
7908
  var __filename$1 = fileURLToPath(import.meta.url);
7153
- var __dirname$1 = path28__default.dirname(__filename$1);
7909
+ var __dirname$1 = path33__default.dirname(__filename$1);
7154
7910
  async function findWorkspaceRoot(options) {
7155
7911
  if (options.targetRoot) {
7156
7912
  return options.targetRoot;
7157
7913
  }
7158
7914
  let currentDir = __dirname$1;
7159
- while (currentDir !== path28__default.parse(currentDir).root) {
7915
+ while (currentDir !== path33__default.parse(currentDir).root) {
7160
7916
  try {
7161
- const pkgPath = path28__default.join(currentDir, "package.json");
7162
- const pkgContent = await fs22.readFile(pkgPath, "utf-8");
7917
+ const pkgPath = path33__default.join(currentDir, "package.json");
7918
+ const pkgContent = await fs25.readFile(pkgPath, "utf-8");
7163
7919
  const pkg = JSON.parse(pkgContent);
7164
7920
  if (pkg.workspaces && Array.isArray(pkg.workspaces)) {
7165
7921
  return currentDir;
7166
7922
  }
7167
7923
  } catch {
7168
7924
  }
7169
- currentDir = path28__default.dirname(currentDir);
7925
+ currentDir = path33__default.dirname(currentDir);
7170
7926
  }
7171
7927
  throw new Error(
7172
7928
  'Could not locate monorepo root. No package.json with "workspaces" field found.'
@@ -7177,7 +7933,7 @@ async function loadManifest(workspaceRoot, flags, options) {
7177
7933
  return options.manifest;
7178
7934
  }
7179
7935
  const { logger: logger2, dryRun } = flags;
7180
- const manifestPath = path28__default.join(workspaceRoot, ".architecture/manifest.yaml");
7936
+ const manifestPath = path33__default.join(workspaceRoot, ".architecture/manifest.yaml");
7181
7937
  logger2.debug(`[debug] __dirname (ESM): ${__dirname$1}`);
7182
7938
  logger2.debug(`[debug] resolved workspaceRoot: ${workspaceRoot}`);
7183
7939
  logger2.debug(`[debug] resolved manifestPath: ${manifestPath}`);
@@ -7266,7 +8022,7 @@ var SyncEngine = class {
7266
8022
  );
7267
8023
  continue;
7268
8024
  }
7269
- const moduleDir = path28__default.join(this.workspaceRoot, "packages", mod.name);
8025
+ const moduleDir = path33__default.join(this.workspaceRoot, "packages", mod.name);
7270
8026
  logger2.info(
7271
8027
  `Ensuring directories for module: ${mod.name} at ${moduleDir}`
7272
8028
  );
@@ -7294,7 +8050,7 @@ var SyncEngine = class {
7294
8050
  const stubs = createEmptyResult();
7295
8051
  for (const module of modules) {
7296
8052
  const moduleName = module.name;
7297
- const moduleDir = path28__default.join(this.workspaceRoot, "packages", moduleName);
8053
+ const moduleDir = path33__default.join(this.workspaceRoot, "packages", moduleName);
7298
8054
  if (moduleName.includes("..") || moduleName.includes("/") || moduleName.startsWith(".")) {
7299
8055
  logger2.warn(
7300
8056
  `Skipping invalid module name (potential path traversal): ${moduleName}`
@@ -7334,11 +8090,11 @@ var SyncEngine = class {
7334
8090
  if (this.partialConfig.mode === "self-regen") {
7335
8091
  await reapLegacyFolders(moduleDir, config, this.report);
7336
8092
  }
7337
- mergeResult(barrels, barrelResult);
7338
- mergeResult(pkgs, pkgResult);
7339
- mergeResult(tsconfigs, tsResult);
7340
- mergeResult(eslint, eslintResult);
7341
- mergeResult(stubs, stubResult);
8093
+ mergeResult2(barrels, barrelResult);
8094
+ mergeResult2(pkgs, pkgResult);
8095
+ mergeResult2(tsconfigs, tsResult);
8096
+ mergeResult2(eslint, eslintResult);
8097
+ mergeResult2(stubs, stubResult);
7342
8098
  }
7343
8099
  return {
7344
8100
  rootFiles: createEmptyResult(),
@@ -7439,6 +8195,14 @@ var SyncEngine = class {
7439
8195
  const { pkgs, tsconfigs, eslint, stubs } = coreResults;
7440
8196
  const firstPassBarrels = coreResults.barrels;
7441
8197
  const appsResult = await generateApps(this.fullConfig, this.report);
8198
+ const crossContextResult = await generateCrossContext(
8199
+ this.fullConfig,
8200
+ this.report
8201
+ );
8202
+ const sharedKernelResult = await generateSharedKernel(
8203
+ this.fullConfig,
8204
+ this.report
8205
+ );
7442
8206
  const secondPassBarrels = createEmptyResult();
7443
8207
  const modules = this.fullConfig.manifest.bounded_contexts ?? [];
7444
8208
  for (const module of modules) {
@@ -7446,16 +8210,16 @@ var SyncEngine = class {
7446
8210
  if (!moduleName || moduleName.includes("..") || moduleName.includes("/") || moduleName.startsWith(".")) {
7447
8211
  continue;
7448
8212
  }
7449
- const moduleDir = path28__default.join(this.workspaceRoot, "packages", moduleName);
8213
+ const moduleDir = path33__default.join(this.workspaceRoot, "packages", moduleName);
7450
8214
  const pass2 = await generateBarrels(
7451
8215
  moduleDir,
7452
8216
  this.fullConfig,
7453
8217
  this.report
7454
8218
  );
7455
- mergeResult(secondPassBarrels, pass2);
8219
+ mergeResult2(secondPassBarrels, pass2);
7456
8220
  }
7457
8221
  const barrels = mergeBarrelPasses(firstPassBarrels, secondPassBarrels);
7458
- const totalOps = rootFilesResult.totalOps + archFilesResult.totalOps + layerResult.totalOps + barrels.totalOps + pkgs.totalOps + tsconfigs.totalOps + eslint.totalOps + stubs.totalOps + appsResult.totalOps;
8222
+ const totalOps = rootFilesResult.totalOps + archFilesResult.totalOps + layerResult.totalOps + barrels.totalOps + pkgs.totalOps + tsconfigs.totalOps + eslint.totalOps + stubs.totalOps + appsResult.totalOps + crossContextResult.totalOps + sharedKernelResult.totalOps;
7459
8223
  if (mode === "self-regen") {
7460
8224
  await runArchLinter(this.fullConfig);
7461
8225
  await this.report.writeReport(this.fullConfig);
@@ -7481,6 +8245,12 @@ var SyncEngine = class {
7481
8245
  logger2.info(
7482
8246
  `• Barrels : ${barrels.created.length} created, ${barrels.updated.length} updated, ${barrels.skipped.length} skipped`
7483
8247
  );
8248
+ logger2.info(
8249
+ `• CrossContext : ${crossContextResult.created.length} created, ${crossContextResult.updated.length} updated, ${crossContextResult.skipped.length} skipped`
8250
+ );
8251
+ logger2.info(
8252
+ `• SharedKernel : ${sharedKernelResult.created.length} created, ${sharedKernelResult.updated.length} updated, ${sharedKernelResult.skipped.length} skipped`
8253
+ );
7484
8254
  logger2.info(
7485
8255
  `• package.json : ${pkgs.created.length} created, ${pkgs.updated.length} updated, ${pkgs.skipped.length} skipped`
7486
8256
  );
@@ -7539,7 +8309,7 @@ function err2(error) {
7539
8309
  var execAsync3 = promisify(exec);
7540
8310
  async function loadManifest2(workspaceRoot) {
7541
8311
  try {
7542
- const manifestPath = path28__default.join(
8312
+ const manifestPath = path33__default.join(
7543
8313
  workspaceRoot,
7544
8314
  ".architecture/manifest.yaml"
7545
8315
  );
@@ -7727,27 +8497,27 @@ var YamlSaveError = class extends Error {
7727
8497
  filePath;
7728
8498
  };
7729
8499
  var YamlService = class {
7730
- async loadManifest(path32) {
8500
+ async loadManifest(path37) {
7731
8501
  try {
7732
- const content = await readFile(path32, "utf-8");
8502
+ const content = await readFile(path37, "utf-8");
7733
8503
  const manifest = yaml9.load(content);
7734
8504
  return ok2(manifest);
7735
8505
  } catch (e) {
7736
8506
  const error = e;
7737
8507
  if (error.code === "ENOENT") {
7738
- return err2(new YamlLoadError(`File not found: ${path32}`, path32));
8508
+ return err2(new YamlLoadError(`File not found: ${path37}`, path37));
7739
8509
  }
7740
- return err2(new YamlLoadError(error.message, path32));
8510
+ return err2(new YamlLoadError(error.message, path37));
7741
8511
  }
7742
8512
  }
7743
- saveManifest(manifest, path32) {
7744
- const dir = dirname(path32);
7745
- const tempPath = `${path32}.tmp`;
8513
+ saveManifest(manifest, path37) {
8514
+ const dir = dirname(path37);
8515
+ const tempPath = `${path37}.tmp`;
7746
8516
  try {
7747
8517
  mkdirSync(dir, { recursive: true });
7748
8518
  const content = yaml9.dump(manifest, { indent: 2 });
7749
8519
  writeFileSync(tempPath, content, "utf-8");
7750
- renameSync(tempPath, path32);
8520
+ renameSync(tempPath, path37);
7751
8521
  return ok2(void 0);
7752
8522
  } catch (e) {
7753
8523
  const error = e;
@@ -7755,7 +8525,7 @@ var YamlService = class {
7755
8525
  if (existsSync(tempPath)) unlinkSync(tempPath);
7756
8526
  } catch {
7757
8527
  }
7758
- return err2(new YamlSaveError(error.message, path32));
8528
+ return err2(new YamlSaveError(error.message, path37));
7759
8529
  }
7760
8530
  }
7761
8531
  parse(content) {
@@ -7964,8 +8734,8 @@ function resolveTemplatesDir() {
7964
8734
  if (process.env.HEXAGEN_TEMPLATES_DIR) {
7965
8735
  return process.env.HEXAGEN_TEMPLATES_DIR;
7966
8736
  }
7967
- const cliDir = path28__default.dirname(fileURLToPath(import.meta.url));
7968
- return path28__default.resolve(cliDir, "templates");
8737
+ const cliDir = path33__default.dirname(fileURLToPath(import.meta.url));
8738
+ return path33__default.resolve(cliDir, "templates");
7969
8739
  }
7970
8740
 
7971
8741
  // src/commands/arch/port.ts
@@ -8593,8 +9363,8 @@ var removeCommander = new Command("remove").description("Remove a port or bounde
8593
9363
  function getManifestPath2(cwd) {
8594
9364
  return join(cwd, ".architecture", "manifest.yaml");
8595
9365
  }
8596
- async function loadManifestFromPath(path32) {
8597
- const result = await yamlService.loadManifest(path32);
9366
+ async function loadManifestFromPath(path37) {
9367
+ const result = await yamlService.loadManifest(path37);
8598
9368
  if (!result.success) {
8599
9369
  return err2(result.error);
8600
9370
  }
@@ -8878,7 +9648,26 @@ function validateManifest3(raw) {
8878
9648
  envVars: validatedStringArray(m.envVars, "envVars"),
8879
9649
  outputs: validatedOutputs(m.outputs, questionTypes),
8880
9650
  checklist: validatedStringArray(m.checklist, "checklist"),
8881
- branch: typeof m.branch === "string" ? m.branch : void 0
9651
+ branch: typeof m.branch === "string" ? m.branch : void 0,
9652
+ ...validatedMapping(m)
9653
+ };
9654
+ }
9655
+ function validatedMapping(m) {
9656
+ const { provides, scope } = m;
9657
+ if (provides !== void 0 && (typeof provides !== "string" || !provides.trim())) {
9658
+ throw new Error("Template manifest field 'provides' must be a non-empty string");
9659
+ }
9660
+ const scopes = ["context", "shared", "project"];
9661
+ if (scope !== void 0 && !(typeof scope === "string" && scopes.includes(scope))) {
9662
+ throw new Error("Template manifest field 'scope' must be one of: context, shared, project");
9663
+ }
9664
+ if (provides === void 0 !== (scope === void 0)) {
9665
+ throw new Error("Template manifest fields 'provides' and 'scope' must be set together");
9666
+ }
9667
+ return {
9668
+ // Trimmed so a padded capability key can't silently miss the canvas join.
9669
+ provides: provides === void 0 ? void 0 : provides.trim(),
9670
+ scope
8882
9671
  };
8883
9672
  }
8884
9673
  function validatedStringArray(raw, field) {
@@ -8993,7 +9782,7 @@ function isInstalled(config, templateId) {
8993
9782
  return templateId in config.templates;
8994
9783
  }
8995
9784
  function conflictFilePath(filePath) {
8996
- const ext = path28__default.extname(filePath);
9785
+ const ext = path33__default.extname(filePath);
8997
9786
  return ext ? filePath.slice(0, -ext.length) + ".hexagen-update" + ext : filePath + ".hexagen-update";
8998
9787
  }
8999
9788
 
@@ -9056,19 +9845,19 @@ function resolveDependencies(requested, registry) {
9056
9845
  }
9057
9846
  const sorted = [];
9058
9847
  const state = /* @__PURE__ */ new Map();
9059
- function visit(id, path32) {
9848
+ function visit(id, path37) {
9060
9849
  const s = state.get(id);
9061
9850
  if (s === "done")
9062
9851
  return;
9063
9852
  if (s === "visiting") {
9064
- const cycleStart = path32.indexOf(id);
9065
- throw new CyclicDependencyError([...path32.slice(cycleStart), id]);
9853
+ const cycleStart = path37.indexOf(id);
9854
+ throw new CyclicDependencyError([...path37.slice(cycleStart), id]);
9066
9855
  }
9067
9856
  state.set(id, "visiting");
9068
9857
  const manifest = registry.get(id);
9069
9858
  for (const dep of manifest.requires) {
9070
9859
  if (needed.has(dep))
9071
- visit(dep, [...path32, id]);
9860
+ visit(dep, [...path37, id]);
9072
9861
  }
9073
9862
  state.set(id, "done");
9074
9863
  sorted.push(id);
@@ -9085,11 +9874,13 @@ var AddTemplateUseCase = class {
9085
9874
  questionEngine;
9086
9875
  fileEmitter;
9087
9876
  configStore;
9088
- constructor(registry, questionEngine, fileEmitter, configStore) {
9877
+ quiet;
9878
+ constructor(registry, questionEngine, fileEmitter, configStore, quiet = false) {
9089
9879
  this.registry = registry;
9090
9880
  this.questionEngine = questionEngine;
9091
9881
  this.fileEmitter = fileEmitter;
9092
9882
  this.configStore = configStore;
9883
+ this.quiet = quiet;
9093
9884
  }
9094
9885
  async execute(input) {
9095
9886
  const { templateIds, projectRoot, overrideAnswers = {}, skipInstalled = true } = input;
@@ -9117,7 +9908,8 @@ var AddTemplateUseCase = class {
9117
9908
  };
9118
9909
  config.templates[id] = record;
9119
9910
  applied.push(id);
9120
- this.printChecklist(manifest);
9911
+ if (!this.quiet)
9912
+ this.printChecklist(manifest);
9121
9913
  }
9122
9914
  await this.configStore.save(projectRoot, config);
9123
9915
  return { applied, skipped, warnings: allWarnings };
@@ -9193,9 +9985,9 @@ var ValidateTemplatesUseCase = class {
9193
9985
  if (!isOutputEnabled(output, answers))
9194
9986
  continue;
9195
9987
  const rel = outputPath(output);
9196
- const abs = path28__default.join(projectRoot, rel);
9988
+ const abs = path33__default.join(projectRoot, rel);
9197
9989
  try {
9198
- await fs22.access(abs);
9990
+ await fs25.access(abs);
9199
9991
  } catch {
9200
9992
  missingFiles.push(rel);
9201
9993
  }
@@ -9210,10 +10002,10 @@ var ValidateTemplatesUseCase = class {
9210
10002
  for (const output of manifest.outputs) {
9211
10003
  if (!isOutputEnabled(output, answers))
9212
10004
  continue;
9213
- const absConflict = conflictFilePath(path28__default.join(projectRoot, outputPath(output)));
10005
+ const absConflict = conflictFilePath(path33__default.join(projectRoot, outputPath(output)));
9214
10006
  try {
9215
- await fs22.access(absConflict);
9216
- conflictFiles.push(path28__default.relative(projectRoot, absConflict));
10007
+ await fs25.access(absConflict);
10008
+ conflictFiles.push(path33__default.relative(projectRoot, absConflict));
9217
10009
  } catch {
9218
10010
  }
9219
10011
  }
@@ -9232,25 +10024,25 @@ var ValidateTemplatesUseCase = class {
9232
10024
  return { results, totalWarnings, totalErrors };
9233
10025
  }
9234
10026
  };
9235
- var PACKAGE_ROOT = path28__default.resolve(path28__default.dirname(fileURLToPath(import.meta.url)), "..", "..");
10027
+ var PACKAGE_ROOT = path33__default.resolve(path33__default.dirname(fileURLToPath(import.meta.url)), "..", "..");
9236
10028
  var FileSystemTemplateRegistry = class {
9237
10029
  templatesDir;
9238
10030
  cache = null;
9239
10031
  constructor(templatesDir) {
9240
- this.templatesDir = templatesDir ?? path28__default.join(PACKAGE_ROOT, "templates");
10032
+ this.templatesDir = templatesDir ?? path33__default.join(PACKAGE_ROOT, "templates");
9241
10033
  }
9242
10034
  async loadAll() {
9243
10035
  if (this.cache)
9244
10036
  return this.cache;
9245
10037
  let entries;
9246
10038
  try {
9247
- entries = await fs22.readdir(this.templatesDir);
10039
+ entries = await fs25.readdir(this.templatesDir);
9248
10040
  } catch {
9249
10041
  return [];
9250
10042
  }
9251
10043
  const manifests = [];
9252
10044
  for (const entry of entries) {
9253
- const manifestPath = path28__default.join(this.templatesDir, entry, "manifest.json");
10045
+ const manifestPath = path33__default.join(this.templatesDir, entry, "manifest.json");
9254
10046
  const manifest = await this.readManifest(manifestPath);
9255
10047
  if (manifest)
9256
10048
  manifests.push(manifest);
@@ -9259,16 +10051,22 @@ var FileSystemTemplateRegistry = class {
9259
10051
  return manifests;
9260
10052
  }
9261
10053
  async loadOne(id) {
9262
- const manifestPath = path28__default.join(this.templatesDir, id, "manifest.json");
10054
+ const manifestPath = path33__default.join(this.templatesDir, id, "manifest.json");
9263
10055
  return this.readManifest(manifestPath);
9264
10056
  }
9265
10057
  async readManifest(manifestPath) {
10058
+ let raw;
9266
10059
  try {
9267
- const raw = await fs22.readFile(manifestPath, "utf-8");
9268
- return validateManifest3(JSON.parse(raw));
10060
+ raw = await fs25.readFile(manifestPath, "utf-8");
9269
10061
  } catch {
9270
10062
  return null;
9271
10063
  }
10064
+ try {
10065
+ return validateManifest3(JSON.parse(raw));
10066
+ } catch (err3) {
10067
+ console.warn(`[template-registry] skipping invalid manifest ${manifestPath}: ${err3 instanceof Error ? err3.message : String(err3)}`);
10068
+ return null;
10069
+ }
9272
10070
  }
9273
10071
  };
9274
10072
  var InteractiveQuestionEngine = class {
@@ -9395,31 +10193,31 @@ ${prompt} (comma-separated numbers)`);
9395
10193
  }
9396
10194
  }
9397
10195
  };
9398
- var PACKAGE_ROOT2 = path28__default.resolve(path28__default.dirname(fileURLToPath(import.meta.url)), "..", "..");
10196
+ var PACKAGE_ROOT2 = path33__default.resolve(path33__default.dirname(fileURLToPath(import.meta.url)), "..", "..");
9399
10197
  var FileSystemFileEmitter = class {
9400
10198
  templatesDir;
9401
10199
  constructor(templatesDir) {
9402
- this.templatesDir = templatesDir ?? path28__default.join(PACKAGE_ROOT2, "templates");
10200
+ this.templatesDir = templatesDir ?? path33__default.join(PACKAGE_ROOT2, "templates");
9403
10201
  }
9404
10202
  async emit(manifest, answers, projectRoot, config) {
9405
10203
  const warnings = [];
9406
10204
  const generatedFiles = [];
9407
- const templateFilesDir = path28__default.join(this.templatesDir, manifest.id, "files");
9408
- const resolvedRoot = path28__default.resolve(projectRoot);
10205
+ const templateFilesDir = path33__default.join(this.templatesDir, manifest.id, "files");
10206
+ const resolvedRoot = path33__default.resolve(projectRoot);
9409
10207
  for (const out of manifest.outputs) {
9410
10208
  if (!isOutputEnabled(out, answers))
9411
10209
  continue;
9412
10210
  const outputRelPath = outputPath(out);
9413
- const destFile = path28__default.resolve(projectRoot, outputRelPath);
9414
- if (!destFile.startsWith(resolvedRoot + path28__default.sep) && destFile !== resolvedRoot) {
10211
+ const destFile = path33__default.resolve(projectRoot, outputRelPath);
10212
+ if (!destFile.startsWith(resolvedRoot + path33__default.sep) && destFile !== resolvedRoot) {
9415
10213
  throw new Error(`Output path '${outputRelPath}' escapes the project root`);
9416
10214
  }
9417
- const sourceFile = path28__default.join(templateFilesDir, outputRelPath);
10215
+ const sourceFile = path33__default.join(templateFilesDir, outputRelPath);
9418
10216
  let templateContent;
9419
10217
  let sourceMode = 420;
9420
10218
  try {
9421
- const raw = await fs22.readFile(sourceFile, "utf-8");
9422
- sourceMode = (await fs22.stat(sourceFile)).mode & 511;
10219
+ const raw = await fs25.readFile(sourceFile, "utf-8");
10220
+ sourceMode = (await fs25.stat(sourceFile)).mode & 511;
9423
10221
  const { output, warnings: interpWarnings } = interpolate(raw, answers);
9424
10222
  templateContent = output;
9425
10223
  for (const key of interpWarnings) {
@@ -9434,7 +10232,7 @@ var FileSystemFileEmitter = class {
9434
10232
  const templateHash = sha256(templateContent);
9435
10233
  let existingContent = null;
9436
10234
  try {
9437
- existingContent = await fs22.readFile(destFile, "utf-8");
10235
+ existingContent = await fs25.readFile(destFile, "utf-8");
9438
10236
  } catch {
9439
10237
  }
9440
10238
  if (existingContent !== null) {
@@ -9444,7 +10242,7 @@ var FileSystemFileEmitter = class {
9444
10242
  if (!isAlreadyIdentical && !wasGeneratedByHexagen) {
9445
10243
  const conflictDest = conflictFilePath(destFile);
9446
10244
  await atomicWrite(conflictDest, templateContent, sourceMode);
9447
- const rel = path28__default.relative(projectRoot, conflictDest);
10245
+ const rel = path33__default.relative(projectRoot, conflictDest);
9448
10246
  warnings.push(`⚠️ Conflict: ${outputRelPath} has local changes.
9449
10247
  New version written to ${rel}
9450
10248
  Review and merge manually, then delete the conflict file.`);
@@ -9458,18 +10256,18 @@ var FileSystemFileEmitter = class {
9458
10256
  }
9459
10257
  };
9460
10258
  async function atomicWrite(filePath, content, mode) {
9461
- await fs22.mkdir(path28__default.dirname(filePath), { recursive: true });
10259
+ await fs25.mkdir(path33__default.dirname(filePath), { recursive: true });
9462
10260
  const tmp = `${filePath}.tmp.${Date.now()}`;
9463
10261
  try {
9464
- await fs22.writeFile(tmp, content, "utf-8");
10262
+ await fs25.writeFile(tmp, content, "utf-8");
9465
10263
  if (mode !== void 0 && (mode & 73) !== 0) {
9466
- const created = (await fs22.stat(tmp)).mode & 511;
10264
+ const created = (await fs25.stat(tmp)).mode & 511;
9467
10265
  const execBits = mode & 73 & ~process.umask();
9468
- await fs22.chmod(tmp, created | execBits);
10266
+ await fs25.chmod(tmp, created | execBits);
9469
10267
  }
9470
- await fs22.rename(tmp, filePath);
10268
+ await fs25.rename(tmp, filePath);
9471
10269
  } catch (err3) {
9472
- await fs22.rm(tmp, { force: true }).catch(() => {
10270
+ await fs25.rm(tmp, { force: true }).catch(() => {
9473
10271
  });
9474
10272
  throw err3;
9475
10273
  }
@@ -9479,9 +10277,9 @@ function sha256(content) {
9479
10277
  }
9480
10278
  var FileSystemTemplateConfigStore = class {
9481
10279
  async load(projectRoot) {
9482
- const configPath = path28__default.join(projectRoot, TEMPLATE_CONFIG_FILE);
10280
+ const configPath = path33__default.join(projectRoot, TEMPLATE_CONFIG_FILE);
9483
10281
  try {
9484
- const raw = await fs22.readFile(configPath, "utf-8");
10282
+ const raw = await fs25.readFile(configPath, "utf-8");
9485
10283
  return JSON.parse(raw);
9486
10284
  } catch (err3) {
9487
10285
  if (err3.code === "ENOENT")
@@ -9490,10 +10288,10 @@ var FileSystemTemplateConfigStore = class {
9490
10288
  }
9491
10289
  }
9492
10290
  async save(projectRoot, config) {
9493
- const configPath = path28__default.join(projectRoot, TEMPLATE_CONFIG_FILE);
10291
+ const configPath = path33__default.join(projectRoot, TEMPLATE_CONFIG_FILE);
9494
10292
  const tmp = `${configPath}.tmp.${Date.now()}`;
9495
- await fs22.writeFile(tmp, JSON.stringify(config, null, 2), "utf-8");
9496
- await fs22.rename(tmp, configPath);
10293
+ await fs25.writeFile(tmp, JSON.stringify(config, null, 2), "utf-8");
10294
+ await fs25.rename(tmp, configPath);
9497
10295
  }
9498
10296
  };
9499
10297
 
@@ -9728,8 +10526,8 @@ Installed templates: ${installed}
9728
10526
  function getManifestPath3(cwd) {
9729
10527
  return join(cwd, ".architecture", "manifest.yaml");
9730
10528
  }
9731
- async function loadManifest4(path32) {
9732
- const result = await yamlService.loadManifest(path32);
10529
+ async function loadManifest4(path37) {
10530
+ const result = await yamlService.loadManifest(path37);
9733
10531
  if (!result.success) {
9734
10532
  throw result.error;
9735
10533
  }
@@ -9927,35 +10725,35 @@ var FileSystemWorkspaceAdapter = class {
9927
10725
  }
9928
10726
  workspaceRoot;
9929
10727
  listPackages() {
9930
- const packagesDir = path28.join(this.workspaceRoot, "packages");
9931
- if (!fs19.existsSync(packagesDir)) {
10728
+ const packagesDir = path33.join(this.workspaceRoot, "packages");
10729
+ if (!fs22.existsSync(packagesDir)) {
9932
10730
  return [];
9933
10731
  }
9934
- return fs19.readdirSync(packagesDir, { withFileTypes: true }).filter((dirent) => dirent.isDirectory()).map((dirent) => dirent.name);
10732
+ return fs22.readdirSync(packagesDir, { withFileTypes: true }).filter((dirent) => dirent.isDirectory()).map((dirent) => dirent.name);
9935
10733
  }
9936
10734
  listApps() {
9937
- const appsDir = path28.join(this.workspaceRoot, "apps");
9938
- if (!fs19.existsSync(appsDir)) {
10735
+ const appsDir = path33.join(this.workspaceRoot, "apps");
10736
+ if (!fs22.existsSync(appsDir)) {
9939
10737
  return [];
9940
10738
  }
9941
- return fs19.readdirSync(appsDir, { withFileTypes: true }).filter((dirent) => dirent.isDirectory()).map((dirent) => dirent.name);
10739
+ return fs22.readdirSync(appsDir, { withFileTypes: true }).filter((dirent) => dirent.isDirectory()).map((dirent) => dirent.name);
9942
10740
  }
9943
10741
  getSourceFiles(dir) {
9944
- if (!fs19.existsSync(dir)) {
10742
+ if (!fs22.existsSync(dir)) {
9945
10743
  return [];
9946
10744
  }
9947
- const entries = fs19.readdirSync(dir, { withFileTypes: true });
10745
+ const entries = fs22.readdirSync(dir, { withFileTypes: true });
9948
10746
  return entries.map((entry) => ({
9949
- path: path28.join(dir, entry.name),
10747
+ path: path33.join(dir, entry.name),
9950
10748
  isDirectory: entry.isDirectory()
9951
10749
  }));
9952
10750
  }
9953
10751
  fileExists(filePath) {
9954
- return fs19.existsSync(filePath);
10752
+ return fs22.existsSync(filePath);
9955
10753
  }
9956
10754
  readFile(filePath) {
9957
10755
  try {
9958
- return fs19.readFileSync(filePath, "utf-8");
10756
+ return fs22.readFileSync(filePath, "utf-8");
9959
10757
  } catch {
9960
10758
  return null;
9961
10759
  }
@@ -10374,15 +11172,15 @@ async function updateBarrelExport(sourceFile, oldName, newName) {
10374
11172
  }
10375
11173
  async function updateManifestEntry(workspaceRoot, updateFn) {
10376
11174
  try {
10377
- const manifestPath = path28__default.join(
11175
+ const manifestPath = path33__default.join(
10378
11176
  workspaceRoot,
10379
11177
  ".architecture/manifest.yaml"
10380
11178
  );
10381
- const content = await fs22.readFile(manifestPath, "utf-8");
11179
+ const content = await fs25.readFile(manifestPath, "utf-8");
10382
11180
  const manifest = yaml9.load(content);
10383
11181
  updateFn(manifest);
10384
11182
  const updatedContent = yaml9.dump(manifest, { indent: 2 });
10385
- await fs22.writeFile(manifestPath, updatedContent, "utf-8");
11183
+ await fs25.writeFile(manifestPath, updatedContent, "utf-8");
10386
11184
  return ok2(void 0);
10387
11185
  } catch (error) {
10388
11186
  return err2(error);
@@ -10446,7 +11244,7 @@ var RenamePortPattern = class {
10446
11244
  (f) => f.reason.includes("Declares")
10447
11245
  );
10448
11246
  for (const file of portFiles) {
10449
- const filePath = path28__default.join(this.workspaceRoot, file.path);
11247
+ const filePath = path33__default.join(this.workspaceRoot, file.path);
10450
11248
  const sourceFile = this.project.addSourceFileAtPath(filePath);
10451
11249
  const existingInterface = sourceFile.getInterface(request.newName);
10452
11250
  if (existingInterface) {
@@ -10468,7 +11266,7 @@ var RenamePortPattern = class {
10468
11266
  const warnings = [];
10469
11267
  try {
10470
11268
  for (const file of impact.filesToModify) {
10471
- const filePath = path28__default.join(this.workspaceRoot, file.path);
11269
+ const filePath = path33__default.join(this.workspaceRoot, file.path);
10472
11270
  if (file.path.endsWith(".ts") || file.path.endsWith(".tsx")) {
10473
11271
  try {
10474
11272
  this.project.addSourceFileAtPath(filePath);
@@ -10571,7 +11369,7 @@ var RenamePortPattern = class {
10571
11369
  */
10572
11370
  async renamePortFile(relativePath, oldName, newName) {
10573
11371
  try {
10574
- const filePath = path28__default.join(this.workspaceRoot, relativePath);
11372
+ const filePath = path33__default.join(this.workspaceRoot, relativePath);
10575
11373
  const sourceFile = this.project.getSourceFile(filePath);
10576
11374
  if (!sourceFile) {
10577
11375
  return err2(new Error(`Source file not found: ${relativePath}`));
@@ -10584,17 +11382,17 @@ var RenamePortPattern = class {
10584
11382
  if (typeAlias) {
10585
11383
  typeAlias.rename(newName);
10586
11384
  }
10587
- const oldFileName = path28__default.basename(relativePath);
11385
+ const oldFileName = path33__default.basename(relativePath);
10588
11386
  const newFileName = oldFileName.replace(
10589
11387
  toKebabCase(oldName),
10590
11388
  toKebabCase(newName)
10591
11389
  );
10592
11390
  if (oldFileName !== newFileName) {
10593
- const newFilePath = path28__default.join(path28__default.dirname(filePath), newFileName);
11391
+ const newFilePath = path33__default.join(path33__default.dirname(filePath), newFileName);
10594
11392
  await sourceFile.move(newFilePath);
10595
11393
  return ok2([
10596
11394
  relativePath,
10597
- path28__default.relative(this.workspaceRoot, newFilePath)
11395
+ path33__default.relative(this.workspaceRoot, newFilePath)
10598
11396
  ]);
10599
11397
  }
10600
11398
  return ok2([relativePath]);
@@ -10607,7 +11405,7 @@ var RenamePortPattern = class {
10607
11405
  */
10608
11406
  async updateImports(relativePath, oldName, newName) {
10609
11407
  try {
10610
- const filePath = path28__default.join(this.workspaceRoot, relativePath);
11408
+ const filePath = path33__default.join(this.workspaceRoot, relativePath);
10611
11409
  const sourceFile = this.project.getSourceFile(filePath);
10612
11410
  if (!sourceFile) {
10613
11411
  return ok2([]);
@@ -10623,7 +11421,7 @@ var RenamePortPattern = class {
10623
11421
  */
10624
11422
  async updateBarrelExport(relativePath, oldName, newName) {
10625
11423
  try {
10626
- const filePath = path28__default.join(this.workspaceRoot, relativePath);
11424
+ const filePath = path33__default.join(this.workspaceRoot, relativePath);
10627
11425
  const sourceFile = this.project.getSourceFile(filePath);
10628
11426
  if (!sourceFile) {
10629
11427
  return ok2([]);
@@ -10666,7 +11464,7 @@ var RenamePortPattern = class {
10666
11464
  */
10667
11465
  async updateTestDouble(relativePath, oldName, newName) {
10668
11466
  try {
10669
- const filePath = path28__default.join(this.workspaceRoot, relativePath);
11467
+ const filePath = path33__default.join(this.workspaceRoot, relativePath);
10670
11468
  const sourceFile = this.project.getSourceFile(filePath);
10671
11469
  if (!sourceFile) {
10672
11470
  return ok2([]);
@@ -10696,17 +11494,17 @@ var RenamePortPattern = class {
10696
11494
  );
10697
11495
  modified = modified || importsModified;
10698
11496
  if (modified) {
10699
- const oldFileName = path28__default.basename(relativePath);
11497
+ const oldFileName = path33__default.basename(relativePath);
10700
11498
  const newFileName = oldFileName.replace(
10701
11499
  toKebabCase(oldName),
10702
11500
  toKebabCase(newName)
10703
11501
  );
10704
11502
  if (oldFileName !== newFileName) {
10705
- const newFilePath = path28__default.join(path28__default.dirname(filePath), newFileName);
11503
+ const newFilePath = path33__default.join(path33__default.dirname(filePath), newFileName);
10706
11504
  await sourceFile.move(newFilePath);
10707
11505
  return ok2([
10708
11506
  relativePath,
10709
- path28__default.relative(this.workspaceRoot, newFilePath)
11507
+ path33__default.relative(this.workspaceRoot, newFilePath)
10710
11508
  ]);
10711
11509
  }
10712
11510
  }
@@ -10779,7 +11577,7 @@ var RenameUseCasePattern = class {
10779
11577
  const warnings = [];
10780
11578
  try {
10781
11579
  for (const file of impact.filesToModify) {
10782
- const filePath = path28__default.join(this.workspaceRoot, file.path);
11580
+ const filePath = path33__default.join(this.workspaceRoot, file.path);
10783
11581
  if (file.path.endsWith(".ts") || file.path.endsWith(".tsx")) {
10784
11582
  try {
10785
11583
  this.project.addSourceFileAtPath(filePath);
@@ -10890,7 +11688,7 @@ var RenameUseCasePattern = class {
10890
11688
  */
10891
11689
  async renameUseCaseFile(relativePath, oldName, newName) {
10892
11690
  try {
10893
- const filePath = path28__default.join(this.workspaceRoot, relativePath);
11691
+ const filePath = path33__default.join(this.workspaceRoot, relativePath);
10894
11692
  const sourceFile = this.project.getSourceFile(filePath);
10895
11693
  if (!sourceFile) {
10896
11694
  return err2(new Error(`Source file not found: ${relativePath}`));
@@ -10899,17 +11697,17 @@ var RenameUseCasePattern = class {
10899
11697
  if (classDecl) {
10900
11698
  classDecl.rename(newName);
10901
11699
  }
10902
- const oldFileName = path28__default.basename(relativePath);
11700
+ const oldFileName = path33__default.basename(relativePath);
10903
11701
  const newFileName = oldFileName.replace(
10904
11702
  toKebabCase(oldName),
10905
11703
  toKebabCase(newName)
10906
11704
  );
10907
11705
  if (oldFileName !== newFileName) {
10908
- const newFilePath = path28__default.join(path28__default.dirname(filePath), newFileName);
11706
+ const newFilePath = path33__default.join(path33__default.dirname(filePath), newFileName);
10909
11707
  await sourceFile.move(newFilePath);
10910
11708
  return ok2([
10911
11709
  relativePath,
10912
- path28__default.relative(this.workspaceRoot, newFilePath)
11710
+ path33__default.relative(this.workspaceRoot, newFilePath)
10913
11711
  ]);
10914
11712
  }
10915
11713
  return ok2([relativePath]);
@@ -10919,7 +11717,7 @@ var RenameUseCasePattern = class {
10919
11717
  }
10920
11718
  async updateImports(relativePath, oldName, newName) {
10921
11719
  try {
10922
- const filePath = path28__default.join(this.workspaceRoot, relativePath);
11720
+ const filePath = path33__default.join(this.workspaceRoot, relativePath);
10923
11721
  const sourceFile = this.project.getSourceFile(filePath);
10924
11722
  if (!sourceFile) {
10925
11723
  return ok2([]);
@@ -10935,7 +11733,7 @@ var RenameUseCasePattern = class {
10935
11733
  */
10936
11734
  async updateBarrelExport(relativePath, oldName, newName) {
10937
11735
  try {
10938
- const filePath = path28__default.join(this.workspaceRoot, relativePath);
11736
+ const filePath = path33__default.join(this.workspaceRoot, relativePath);
10939
11737
  const sourceFile = this.project.getSourceFile(filePath);
10940
11738
  if (!sourceFile) {
10941
11739
  return ok2([]);
@@ -10972,24 +11770,24 @@ var RenameUseCasePattern = class {
10972
11770
  */
10973
11771
  async updateTestFile(relativePath, oldName, newName) {
10974
11772
  try {
10975
- const filePath = path28__default.join(this.workspaceRoot, relativePath);
11773
+ const filePath = path33__default.join(this.workspaceRoot, relativePath);
10976
11774
  const sourceFile = this.project.getSourceFile(filePath);
10977
11775
  if (!sourceFile) {
10978
11776
  return ok2([]);
10979
11777
  }
10980
11778
  const modified = await updateImports(sourceFile, oldName, newName);
10981
11779
  if (modified) {
10982
- const oldFileName = path28__default.basename(relativePath);
11780
+ const oldFileName = path33__default.basename(relativePath);
10983
11781
  const newFileName = oldFileName.replace(
10984
11782
  toKebabCase(oldName),
10985
11783
  toKebabCase(newName)
10986
11784
  );
10987
11785
  if (oldFileName !== newFileName) {
10988
- const newFilePath = path28__default.join(path28__default.dirname(filePath), newFileName);
11786
+ const newFilePath = path33__default.join(path33__default.dirname(filePath), newFileName);
10989
11787
  await sourceFile.move(newFilePath);
10990
11788
  return ok2([
10991
11789
  relativePath,
10992
- path28__default.relative(this.workspaceRoot, newFilePath)
11790
+ path33__default.relative(this.workspaceRoot, newFilePath)
10993
11791
  ]);
10994
11792
  }
10995
11793
  }
@@ -11000,7 +11798,7 @@ var RenameUseCasePattern = class {
11000
11798
  }
11001
11799
  async updateCompositionRoot(relativePath, oldName, newName) {
11002
11800
  try {
11003
- const filePath = path28__default.join(this.workspaceRoot, relativePath);
11801
+ const filePath = path33__default.join(this.workspaceRoot, relativePath);
11004
11802
  const sourceFile = this.project.getSourceFile(filePath);
11005
11803
  if (!sourceFile) {
11006
11804
  return ok2([]);
@@ -11070,7 +11868,7 @@ var RenameEntityPattern = class {
11070
11868
  if (file.path.endsWith(".ts") || file.path.endsWith(".tsx")) {
11071
11869
  try {
11072
11870
  this.project.addSourceFileAtPath(
11073
- path28__default.join(this.workspaceRoot, file.path)
11871
+ path33__default.join(this.workspaceRoot, file.path)
11074
11872
  );
11075
11873
  } catch {
11076
11874
  }
@@ -11128,7 +11926,7 @@ var RenameEntityPattern = class {
11128
11926
  async renameEntityFile(relativePath, oldName, newName) {
11129
11927
  try {
11130
11928
  const sourceFile = this.project.getSourceFile(
11131
- path28__default.join(this.workspaceRoot, relativePath)
11929
+ path33__default.join(this.workspaceRoot, relativePath)
11132
11930
  );
11133
11931
  if (!sourceFile) return err2(new Error(`File not found: ${relativePath}`));
11134
11932
  const classDecl = sourceFile.getClass(oldName);
@@ -11145,7 +11943,7 @@ var RenameEntityPattern = class {
11145
11943
  async updateReferences(relativePath, oldName, newName) {
11146
11944
  try {
11147
11945
  const sourceFile = this.project.getSourceFile(
11148
- path28__default.join(this.workspaceRoot, relativePath)
11946
+ path33__default.join(this.workspaceRoot, relativePath)
11149
11947
  );
11150
11948
  if (!sourceFile) return ok2([]);
11151
11949
  let modified = false;
@@ -11164,11 +11962,11 @@ var RenameEntityPattern = class {
11164
11962
  }
11165
11963
  async updateManifest(oldName, newName) {
11166
11964
  try {
11167
- const manifestPath = path28__default.join(
11965
+ const manifestPath = path33__default.join(
11168
11966
  this.workspaceRoot,
11169
11967
  ".architecture/manifest.yaml"
11170
11968
  );
11171
- const content = await fs22.readFile(manifestPath, "utf-8");
11969
+ const content = await fs25.readFile(manifestPath, "utf-8");
11172
11970
  const manifest = yaml9.load(content);
11173
11971
  if (manifest.bounded_contexts) {
11174
11972
  for (const context of manifest.bounded_contexts) {
@@ -11180,7 +11978,7 @@ var RenameEntityPattern = class {
11180
11978
  }
11181
11979
  }
11182
11980
  }
11183
- await fs22.writeFile(
11981
+ await fs25.writeFile(
11184
11982
  manifestPath,
11185
11983
  yaml9.dump(manifest, { indent: 2 }),
11186
11984
  "utf-8"
@@ -11864,7 +12662,7 @@ var manifestSplitCommander = new Command("split").description("Split monolithic
11864
12662
  const dryRun = options.dryRun ?? false;
11865
12663
  try {
11866
12664
  const workspaceRoot = await findWorkspaceRoot({});
11867
- const monolithicManifestPath = path28__default.join(
12665
+ const monolithicManifestPath = path33__default.join(
11868
12666
  workspaceRoot,
11869
12667
  ".architecture/manifest.yaml"
11870
12668
  );
@@ -11873,7 +12671,7 @@ var manifestSplitCommander = new Command("split").description("Split monolithic
11873
12671
  );
11874
12672
  let manifestContent;
11875
12673
  try {
11876
- manifestContent = await fs22.readFile(monolithicManifestPath, "utf-8");
12674
+ manifestContent = await fs25.readFile(monolithicManifestPath, "utf-8");
11877
12675
  } catch {
11878
12676
  throw new Error(`Failed to read manifest.yaml. Does it exist?`);
11879
12677
  }
@@ -11901,14 +12699,14 @@ Validation successful. Found ${contexts.length} bounded contexts.`
11901
12699
  const planes = rawYaml.planes ?? {};
11902
12700
  const planeLookup = buildPlaneLookup(planes);
11903
12701
  console.log("Splitting manifest into the new directory structure...");
11904
- const archDir = path28__default.join(workspaceRoot, ".architecture");
11905
- const contextsDir = path28__default.join(archDir, "contexts");
11906
- const appsDir = path28__default.join(archDir, "apps");
11907
- const invariantsDir = path28__default.join(archDir, "invariants");
12702
+ const archDir = path33__default.join(workspaceRoot, ".architecture");
12703
+ const contextsDir = path33__default.join(archDir, "contexts");
12704
+ const appsDir = path33__default.join(archDir, "apps");
12705
+ const invariantsDir = path33__default.join(archDir, "invariants");
11908
12706
  if (!dryRun) {
11909
- await fs22.mkdir(contextsDir, { recursive: true });
11910
- await fs22.mkdir(appsDir, { recursive: true });
11911
- await fs22.mkdir(invariantsDir, { recursive: true });
12707
+ await fs25.mkdir(contextsDir, { recursive: true });
12708
+ await fs25.mkdir(appsDir, { recursive: true });
12709
+ await fs25.mkdir(invariantsDir, { recursive: true });
11912
12710
  }
11913
12711
  const CATEGORY_B_KEYS = /* @__PURE__ */ new Set(["monorepo", "generator"]);
11914
12712
  const workspaceConfig = {};
@@ -11948,12 +12746,12 @@ Validation successful. Found ${contexts.length} bounded contexts.`
11948
12746
  }
11949
12747
  for (const ctx of contexts) {
11950
12748
  const plane = planeLookup.get(ctx.name) ?? ctx.plane ?? "core";
11951
- const ctxDir = path28__default.join(contextsDir, plane, ctx.name);
12749
+ const ctxDir = path33__default.join(contextsDir, plane, ctx.name);
11952
12750
  const contextData = normalizeContextData(
11953
12751
  extractContextData(ctx)
11954
12752
  );
11955
12753
  contextData.plane = plane;
11956
- const ctxFilePath = path28__default.join(ctxDir, "context.yaml");
12754
+ const ctxFilePath = path33__default.join(ctxDir, "context.yaml");
11957
12755
  const ctxYaml = yaml9.dump(contextData, {
11958
12756
  noRefs: true,
11959
12757
  sortKeys: false,
@@ -11962,8 +12760,8 @@ Validation successful. Found ${contexts.length} bounded contexts.`
11962
12760
  if (dryRun) {
11963
12761
  console.log(`[dry-run] Would create: ${ctxFilePath}`);
11964
12762
  } else {
11965
- await fs22.mkdir(ctxDir, { recursive: true });
11966
- await fs22.writeFile(ctxFilePath, ctxYaml, "utf-8");
12763
+ await fs25.mkdir(ctxDir, { recursive: true });
12764
+ await fs25.writeFile(ctxFilePath, ctxYaml, "utf-8");
11967
12765
  }
11968
12766
  indexManifest.bounded_contexts.push({
11969
12767
  name: ctx.name,
@@ -11979,7 +12777,7 @@ Validation successful. Found ${contexts.length} bounded contexts.`
11979
12777
  if (typeof app === "object" && app !== null && "name" in app) {
11980
12778
  const typedApp = app;
11981
12779
  const appName = typedApp.name;
11982
- const appFilePath = path28__default.join(appsDir, `${appName}.app.yaml`);
12780
+ const appFilePath = path33__default.join(appsDir, `${appName}.app.yaml`);
11983
12781
  const appYaml = yaml9.dump(app, {
11984
12782
  noRefs: true,
11985
12783
  sortKeys: false,
@@ -11988,7 +12786,7 @@ Validation successful. Found ${contexts.length} bounded contexts.`
11988
12786
  if (dryRun) {
11989
12787
  console.log(`[dry-run] Would create: ${appFilePath}`);
11990
12788
  } else {
11991
- await fs22.writeFile(appFilePath, appYaml, "utf-8");
12789
+ await fs25.writeFile(appFilePath, appYaml, "utf-8");
11992
12790
  }
11993
12791
  indexManifest.apps.push({
11994
12792
  name: appName,
@@ -11996,7 +12794,7 @@ Validation successful. Found ${contexts.length} bounded contexts.`
11996
12794
  });
11997
12795
  }
11998
12796
  }
11999
- const workspaceConfigPath = path28__default.join(archDir, "workspace.config.yaml");
12797
+ const workspaceConfigPath = path33__default.join(archDir, "workspace.config.yaml");
12000
12798
  const workspaceConfigYaml = yaml9.dump(workspaceConfig, {
12001
12799
  noRefs: true,
12002
12800
  sortKeys: false,
@@ -12007,7 +12805,7 @@ Validation successful. Found ${contexts.length} bounded contexts.`
12007
12805
  console.log("\n--- Preview of workspace.config.yaml ---\n");
12008
12806
  console.log(workspaceConfigYaml);
12009
12807
  } else {
12010
- await fs22.writeFile(workspaceConfigPath, workspaceConfigYaml, "utf-8");
12808
+ await fs25.writeFile(workspaceConfigPath, workspaceConfigYaml, "utf-8");
12011
12809
  }
12012
12810
  const indexYaml = yaml9.dump(indexManifest, {
12013
12811
  noRefs: true,
@@ -12028,9 +12826,9 @@ Validation successful. Found ${contexts.length} bounded contexts.`
12028
12826
  console.log(header + indexYaml);
12029
12827
  } else {
12030
12828
  const backupPath = monolithicManifestPath + ".pre-split-backup";
12031
- await fs22.copyFile(monolithicManifestPath, backupPath);
12829
+ await fs25.copyFile(monolithicManifestPath, backupPath);
12032
12830
  console.log(`Backup created at ${backupPath}`);
12033
- await fs22.writeFile(monolithicManifestPath, header + indexYaml, "utf-8");
12831
+ await fs25.writeFile(monolithicManifestPath, header + indexYaml, "utf-8");
12034
12832
  }
12035
12833
  console.log("\n✅ Manifest split completed successfully!");
12036
12834
  if (dryRun) {
@@ -12095,13 +12893,17 @@ function buildProgram() {
12095
12893
  program2.command("sync").description("Run the HexaGen sync engine to generate artifacts").option("--dry-run", "Preview changes without writing files").option("--force", "Overwrite non-generated files in packages").option(
12096
12894
  "--force-root",
12097
12895
  "Overwrite protected root files (turbo.json, .gitignore)"
12098
- ).option("--allow-dirty", "Skip git clean check (for development)").option("--strict", "Fail on architecture linter warnings").action(async (options) => {
12896
+ ).option("--allow-dirty", "Skip git clean check (for development)").option("--strict", "Fail on architecture linter warnings").option(
12897
+ "--only <pattern...>",
12898
+ "Limit writes to workspace-relative paths/globs (e.g. packages/shared, 'packages/*/tsconfig.json'). Direct targets only — no dependency fan-out; run a full sync for cross-package changes."
12899
+ ).action(async (options) => {
12099
12900
  const flags = {
12100
12901
  dryRun: options.dryRun ?? false,
12101
12902
  force: options.force ?? false,
12102
12903
  forceRoot: options.forceRoot ?? false,
12103
12904
  allowDirty: options.allowDirty ?? false,
12104
12905
  strict: options.strict ?? false,
12906
+ only: options.only,
12105
12907
  mode: "self-regen",
12106
12908
  logger
12107
12909
  };