monorise 1.14.1 → 1.15.0-dev.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.
package/dist/cli/cli.js CHANGED
@@ -2,8 +2,8 @@
2
2
 
3
3
  // cli.ts
4
4
  import "tsx";
5
- import fs3 from "fs";
6
- import path3 from "path";
5
+ import fs4 from "fs";
6
+ import path4 from "path";
7
7
  import { execSync } from "child_process";
8
8
  import chokidar from "chokidar";
9
9
 
@@ -16,7 +16,7 @@ function normalizeSqlIdentifier(name) {
16
16
  const normalized = name.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/[^a-zA-Z0-9]+/g, "_").replace(/^_+|_+$/g, "").toLowerCase();
17
17
  return /^[a-z_]/.test(normalized) ? normalized : `_${normalized}`;
18
18
  }
19
- function athenaType(schema, path4) {
19
+ function athenaType(schema, path5) {
20
20
  let current = schema;
21
21
  for (; ; ) {
22
22
  const typeName = current._def?.typeName;
@@ -65,7 +65,7 @@ function athenaType(schema, path4) {
65
65
  return "json";
66
66
  }
67
67
  }
68
- function columns(schema, path4) {
68
+ function columns(schema, path5) {
69
69
  let objectSchema = schema;
70
70
  while (!objectSchema.shape && objectSchema._def?.typeName === "ZodEffects") {
71
71
  const innerSchema = objectSchema._def.schema;
@@ -79,14 +79,14 @@ function columns(schema, path4) {
79
79
  const existing = names.get(name);
80
80
  if (existing) {
81
81
  throw new Error(
82
- `Analytics column identifier collision in ${path4}: ${existing} and ${sourceName} both normalize to ${name}.`
82
+ `Analytics column identifier collision in ${path5}: ${existing} and ${sourceName} both normalize to ${name}.`
83
83
  );
84
84
  }
85
85
  names.set(name, sourceName);
86
86
  return {
87
87
  name,
88
88
  sourceName,
89
- type: athenaType(field, `${path4}.${sourceName}`)
89
+ type: athenaType(field, `${path5}.${sourceName}`)
90
90
  };
91
91
  });
92
92
  }
@@ -246,16 +246,138 @@ function createAnalyticsManifest(configs) {
246
246
  // cli.ts
247
247
  import { fileURLToPath } from "url";
248
248
 
249
- // commands/utils/detect-package.ts
249
+ // commands/utils/api-key-policies.ts
250
250
  import fs2 from "fs";
251
+ import { createRequire } from "module";
251
252
  import path2 from "path";
253
+ import { pathToFileURL } from "url";
254
+ var require2 = createRequire(import.meta.url);
255
+ var VALIDATE_API_KEY_POLICIES = /* @__PURE__ */ Symbol.for("monorise.validateApiKeyPolicies");
256
+ function resolveApiKeysPath(projectRoot, apiKeys, configDir) {
257
+ if (!apiKeys) return void 0;
258
+ const absolutePath = path2.resolve(projectRoot, apiKeys);
259
+ if (!fs2.existsSync(absolutePath) && !fs2.existsSync(`${absolutePath}.ts`) && !fs2.existsSync(`${absolutePath}.js`)) {
260
+ throw new Error(
261
+ `API key policies file not found: '${absolutePath}'. Please ensure 'apiKeys' in monorise.config.ts points to a valid file.`
262
+ );
263
+ }
264
+ const fromConfigDir = path2.relative(configDir, absolutePath);
265
+ if (!fromConfigDir.startsWith("..") && !path2.isAbsolute(fromConfigDir)) {
266
+ throw new Error(
267
+ `API key policies file '${absolutePath}' is inside configDir '${configDir}', where every file is loaded as an entity config. Move it outside, e.g. './monorise/api-keys.ts'.`
268
+ );
269
+ }
270
+ return absolutePath;
271
+ }
272
+ function apiKeysFile(apiKeysPath) {
273
+ return ["", ".ts", ".js"].map((extension) => `${apiKeysPath}${extension}`).find((file) => fs2.existsSync(file) && fs2.statSync(file).isFile()) ?? apiKeysPath;
274
+ }
275
+ var importFresh = (file) => {
276
+ delete require2.cache[file];
277
+ return import(`${pathToFileURL(file).href}?t=${Date.now()}`);
278
+ };
279
+ async function validateApiKeyPoliciesFile(apiKeysPath, configOutputPath) {
280
+ const { default: generatedConfig } = await importFresh(configOutputPath);
281
+ const { default: policies } = await importFresh(apiKeysFile(apiKeysPath));
282
+ const validate = policies?.[VALIDATE_API_KEY_POLICIES];
283
+ if (typeof validate !== "function") {
284
+ throw new Error(
285
+ `API key policies file at '${apiKeysPath}' must default export the result of defineApiKeyPolicies(...).`
286
+ );
287
+ }
288
+ const errors = validate(generatedConfig.EntityConfig);
289
+ if (errors.length) {
290
+ throw new Error(
291
+ `Invalid API key policies in '${apiKeysPath}':
292
+ - ${errors.join("\n - ")}`
293
+ );
294
+ }
295
+ console.log("Validated API key policies.");
296
+ return policies;
297
+ }
298
+ function routePermissionDeclarations(policies, baseModuleNames) {
299
+ const permissions = /* @__PURE__ */ new Set();
300
+ for (const policy of Object.values(policies)) {
301
+ const routes = policy?.routes;
302
+ if (Array.isArray(routes)) {
303
+ for (const permission of routes) permissions.add(permission);
304
+ }
305
+ }
306
+ if (permissions.size === 0) return "";
307
+ const members = [...permissions].sort().map((permission) => ` ${JSON.stringify(permission)}: true;`).join("\n");
308
+ return baseModuleNames.map(
309
+ (moduleName) => `
310
+ declare module '${moduleName}' {
311
+ interface ApiKeyRoutePermissions {
312
+ ${members}
313
+ }
314
+ }
315
+ `
316
+ ).join("");
317
+ }
318
+ function apiKeyPoliciesHandleParts(monoriseOutputDir, apiKeysPath) {
319
+ if (!apiKeysPath) return { importLine: "", coreFactoryArg: "config" };
320
+ const relativePath = path2.relative(monoriseOutputDir, apiKeysPath).replace(/\.(ts|js|mjs|cjs)$/, "");
321
+ const importPath = relativePath.startsWith(".") ? relativePath : `./${relativePath}`;
322
+ return {
323
+ importLine: `import apiKeyPolicies from '${importPath}';`,
324
+ coreFactoryArg: "{ ...config, ApiKeyPolicies: apiKeyPolicies }"
325
+ };
326
+ }
327
+
328
+ // commands/utils/api-key-types.ts
329
+ var literalUnion = (names) => names.length ? names.map((name) => JSON.stringify(name)).join(" | ") : "never";
330
+ function apiKeyTypeDeclarations(entities) {
331
+ const enumKeys = new Map(
332
+ entities.map((entity) => [entity.name, entity.enumKey])
333
+ );
334
+ const tagEntries = entities.map(
335
+ ({ enumKey, config }) => `[Entity.${enumKey}]: ${literalUnion((config.tags ?? []).map((tag) => tag.name))};`
336
+ );
337
+ const mutualFields = /* @__PURE__ */ new Map();
338
+ const setDirection = (from, to, fields) => {
339
+ const targets = mutualFields.get(from) ?? /* @__PURE__ */ new Map();
340
+ if (!targets.has(to)) targets.set(to, fields);
341
+ mutualFields.set(from, targets);
342
+ };
343
+ for (const pass of ["own", "reverse"]) {
344
+ for (const { name, config } of entities) {
345
+ for (const field of Object.values(config.mutual?.mutualFields ?? {})) {
346
+ const shape = field.mutual?.mutualDataSchema?.shape;
347
+ if (!shape || !enumKeys.has(field.entityType)) continue;
348
+ const fields = Object.keys(shape);
349
+ if (pass === "own") setDirection(name, field.entityType, fields);
350
+ else setDirection(field.entityType, name, fields);
351
+ }
352
+ }
353
+ }
354
+ const mutualEntries = [...mutualFields].map(
355
+ ([from, targets]) => `[Entity.${enumKeys.get(from)}]: {
356
+ ${[...targets].map(
357
+ ([to, fields]) => ` [Entity.${enumKeys.get(to)}]: ${literalUnion(fields)};`
358
+ ).join("\n")}
359
+ };`
360
+ );
361
+ return `
362
+ export interface ApiKeyEntityTags {
363
+ ${tagEntries.join("\n ")}
364
+ }
365
+
366
+ export interface ApiKeyMutualDataFields {
367
+ ${mutualEntries.join("\n ")}
368
+ }`;
369
+ }
370
+
371
+ // commands/utils/detect-package.ts
372
+ import fs3 from "fs";
373
+ import path3 from "path";
252
374
  function detectCombinedPackage(startDir) {
253
375
  let dir = startDir;
254
376
  while (true) {
255
- if (fs2.existsSync(path2.join(dir, "node_modules", "monorise"))) {
377
+ if (fs3.existsSync(path3.join(dir, "node_modules", "monorise"))) {
256
378
  return true;
257
379
  }
258
- const parent = path2.dirname(dir);
380
+ const parent = path3.dirname(dir);
259
381
  if (parent === dir) break;
260
382
  dir = parent;
261
383
  }
@@ -284,10 +406,10 @@ var ROOT_TSCONFIG_TEMPLATE = {
284
406
 
285
407
  // cli.ts
286
408
  var __filename = fileURLToPath(import.meta.url);
287
- var __dirname = path3.dirname(__filename);
288
- var TEMPLATES_DIR = path3.join(__dirname, "templates", "files");
409
+ var __dirname = path4.dirname(__filename);
410
+ var TEMPLATES_DIR = path4.join(__dirname, "templates", "files");
289
411
  function readTemplate(filename) {
290
- return fs3.readFileSync(path3.join(TEMPLATES_DIR, filename), "utf-8");
412
+ return fs4.readFileSync(path4.join(TEMPLATES_DIR, filename), "utf-8");
291
413
  }
292
414
  function kebabToCamel(str) {
293
415
  return str.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());
@@ -300,19 +422,19 @@ function execCommand(command, cwd, stdio = "inherit") {
300
422
  execSync(command, { cwd, stdio });
301
423
  }
302
424
  async function generateConfigFile(configDir, monoriseOutputDir, projectRoot) {
303
- const configOutputPath = path3.join(monoriseOutputDir, "config.ts");
425
+ const configOutputPath = path4.join(monoriseOutputDir, "config.ts");
304
426
  const initialConfigContent = `
305
427
  export enum Entity {}
306
428
  export default {};
307
429
  `;
308
- fs3.writeFileSync(configOutputPath, initialConfigContent);
309
- fs3.writeFileSync(
310
- path3.join(monoriseOutputDir, "index.ts"),
430
+ fs4.writeFileSync(configOutputPath, initialConfigContent);
431
+ fs4.writeFileSync(
432
+ path4.join(monoriseOutputDir, "index.ts"),
311
433
  `export * from './config';
312
434
  export { default } from './config';
313
435
  `
314
436
  );
315
- const files = fs3.readdirSync(configDir).filter((file) => file.endsWith(".ts") && file !== "index.ts");
437
+ const files = fs4.readdirSync(configDir).filter((file) => file.endsWith(".ts") && file !== "index.ts");
316
438
  const names = /* @__PURE__ */ new Set();
317
439
  const nameRegex = /^[a-z]+(-[a-z]+)*$/;
318
440
  const imports = [];
@@ -324,10 +446,11 @@ export { default } from './config';
324
446
  const allowedEntityEntries = [];
325
447
  const entityWithEmailAuthEntries = [];
326
448
  const analyticsConfigs = [];
327
- const relativePathToConfigDir = path3.relative(monoriseOutputDir, configDir);
449
+ const apiKeyTypeEntities = [];
450
+ const relativePathToConfigDir = path4.relative(monoriseOutputDir, configDir);
328
451
  const importPathPrefix = relativePathToConfigDir ? `${relativePathToConfigDir}/` : "./";
329
452
  for (const file of files) {
330
- const fullPath = path3.join(configDir, file);
453
+ const fullPath = path4.join(configDir, file);
331
454
  const module = await import(fullPath);
332
455
  const config = module.default;
333
456
  if (!nameRegex.test(config.name)) {
@@ -358,6 +481,7 @@ export { default } from './config';
358
481
  `[Entity.${enumKey}]: ${kebabToCamel(config.name)}.finalSchema,`
359
482
  );
360
483
  allowedEntityEntries.push(`Entity.${enumKey}`);
484
+ apiKeyTypeEntities.push({ name: config.name, enumKey, config });
361
485
  if (config.authMethod?.email) {
362
486
  entityWithEmailAuthEntries.push(`Entity.${enumKey}`);
363
487
  }
@@ -374,6 +498,7 @@ declare module '${moduleName}' {
374
498
  export interface EntitySchemaMap {
375
499
  ${schemaMapEntries.join("\n ")}
376
500
  }
501
+ ${apiKeyTypeDeclarations(apiKeyTypeEntities)}
377
502
  }`;
378
503
  const moduleAugmentations = usesCombinedPackage ? augmentationBlock("monorise/base") : augmentationBlock("../base/index.js");
379
504
  const configOutputContent = `
@@ -421,11 +546,11 @@ const config = {
421
546
  export default config;
422
547
  ${moduleAugmentations}
423
548
  `;
424
- fs3.writeFileSync(configOutputPath, configOutputContent);
549
+ fs4.writeFileSync(configOutputPath, configOutputContent);
425
550
  writeAnalyticsManifest(monoriseOutputDir, analyticsConfigs);
426
551
  console.log("Successfully generated config.ts!");
427
- const indexOutputPath = path3.join(monoriseOutputDir, "index.ts");
428
- fs3.writeFileSync(
552
+ const indexOutputPath = path4.join(monoriseOutputDir, "index.ts");
553
+ fs4.writeFileSync(
429
554
  indexOutputPath,
430
555
  `export * from './config';
431
556
  export { default } from './config';
@@ -434,22 +559,22 @@ export { default } from './config';
434
559
  console.log("Successfully generated index.ts!");
435
560
  return configOutputPath;
436
561
  }
437
- async function generateHandleFile(monoriseConfig, projectRoot, monoriseOutputDir) {
438
- const handleOutputPath = path3.join(monoriseOutputDir, "handle.ts");
562
+ async function generateHandleFile(monoriseConfig, projectRoot, monoriseOutputDir, apiKeysPath) {
563
+ const handleOutputPath = path4.join(monoriseOutputDir, "handle.ts");
439
564
  const customRoutesPath = monoriseConfig.customRoutes;
440
565
  let routesImportLine = "";
441
566
  let appHandlerPayload = "{}";
442
567
  if (customRoutesPath) {
443
- const absoluteCustomRoutesPath = path3.resolve(
568
+ const absoluteCustomRoutesPath = path4.resolve(
444
569
  projectRoot,
445
570
  customRoutesPath
446
571
  );
447
- if (!fs3.existsSync(absoluteCustomRoutesPath) && !fs3.existsSync(`${absoluteCustomRoutesPath}.ts`) && !fs3.existsSync(`${absoluteCustomRoutesPath}.js`)) {
572
+ if (!fs4.existsSync(absoluteCustomRoutesPath) && !fs4.existsSync(`${absoluteCustomRoutesPath}.ts`) && !fs4.existsSync(`${absoluteCustomRoutesPath}.js`)) {
448
573
  throw new Error(
449
574
  `Custom routes file not found: '${absoluteCustomRoutesPath}'. Please ensure 'customRoutes' in monorise.config.ts points to a valid file.`
450
575
  );
451
576
  }
452
- let relativePathToRoutes = path3.relative(
577
+ let relativePathToRoutes = path4.relative(
453
578
  monoriseOutputDir,
454
579
  absoluteCustomRoutesPath
455
580
  );
@@ -462,12 +587,17 @@ async function generateHandleFile(monoriseConfig, projectRoot, monoriseOutputDir
462
587
  }
463
588
  const usesCombinedPackage = detectCombinedPackage(projectRoot);
464
589
  const coreImportPath = usesCombinedPackage ? "monorise/core" : "../core/index.js";
590
+ const apiKeyPolicies = apiKeyPoliciesHandleParts(
591
+ monoriseOutputDir,
592
+ apiKeysPath
593
+ );
465
594
  const combinedContent = `
466
595
  import CoreFactory, { analyticsMaterializationProcessor, analyticsModelProcessor, analyticsQueryHandler as createAnalyticsQueryHandler, analyticsViewProcessor } from '${coreImportPath}';
467
596
  import config from './config';
468
597
  import analyticsManifest from './analytics-manifest.json';
469
598
  ${routesImportLine ? `${routesImportLine}
470
- ` : ""}const coreFactory = new CoreFactory(config);
599
+ ` : ""}${apiKeyPolicies.importLine ? `${apiKeyPolicies.importLine}
600
+ ` : ""}const coreFactory = new CoreFactory(${apiKeyPolicies.coreFactoryArg});
471
601
 
472
602
  export const replicationHandler = coreFactory.replicationProcessor;
473
603
  export const analyticsHandler = coreFactory.analyticsProcessor;
@@ -487,33 +617,62 @@ export const wsDisconnect = coreFactory.wsDisconnect;
487
617
  export const wsDefault = coreFactory.wsDefault;
488
618
  export const wsBroadcast = coreFactory.wsBroadcast;
489
619
  `;
490
- fs3.writeFileSync(handleOutputPath, combinedContent);
620
+ fs4.writeFileSync(handleOutputPath, combinedContent);
491
621
  console.log("Successfully generated handle.ts!");
492
622
  return handleOutputPath;
493
623
  }
494
624
  async function generateFiles(rootPath) {
495
- const baseDir = rootPath ? path3.resolve(rootPath) : process.cwd();
496
- const configFilePathTS = path3.join(baseDir, "monorise.config.ts");
497
- const configFilePathJS = path3.join(baseDir, "monorise.config.js");
625
+ const baseDir = rootPath ? path4.resolve(rootPath) : process.cwd();
626
+ const configFilePathTS = path4.join(baseDir, "monorise.config.ts");
627
+ const configFilePathJS = path4.join(baseDir, "monorise.config.js");
498
628
  let configFilePath;
499
- if (fs3.existsSync(configFilePathTS)) {
629
+ if (fs4.existsSync(configFilePathTS)) {
500
630
  configFilePath = configFilePathTS;
501
- } else if (fs3.existsSync(configFilePathJS)) {
631
+ } else if (fs4.existsSync(configFilePathJS)) {
502
632
  configFilePath = configFilePathJS;
503
633
  } else {
504
634
  throw new Error(
505
635
  "Neither monorise.config.ts nor monorise.config.js found in the root of the project."
506
636
  );
507
637
  }
508
- const projectRoot = path3.dirname(configFilePath);
638
+ const projectRoot = path4.dirname(configFilePath);
509
639
  const monoriseConfigModule = await import(configFilePath);
510
640
  const monoriseConfig = monoriseConfigModule.default;
511
- const configDir = path3.resolve(projectRoot, monoriseConfig.configDir);
512
- const monoriseOutputDir = path3.join(projectRoot, ".monorise");
513
- fs3.mkdirSync(monoriseOutputDir, { recursive: true });
514
- await generateConfigFile(configDir, monoriseOutputDir, projectRoot);
515
- await generateHandleFile(monoriseConfig, projectRoot, monoriseOutputDir);
516
- return configDir;
641
+ const configDir = path4.resolve(projectRoot, monoriseConfig.configDir);
642
+ const monoriseOutputDir = path4.join(projectRoot, ".monorise");
643
+ fs4.mkdirSync(monoriseOutputDir, { recursive: true });
644
+ const apiKeysPath = resolveApiKeysPath(
645
+ projectRoot,
646
+ monoriseConfig.apiKeys,
647
+ configDir
648
+ );
649
+ const configOutputPath = await generateConfigFile(
650
+ configDir,
651
+ monoriseOutputDir,
652
+ projectRoot
653
+ );
654
+ if (apiKeysPath) {
655
+ const policies = await validateApiKeyPoliciesFile(
656
+ apiKeysPath,
657
+ configOutputPath
658
+ );
659
+ fs4.appendFileSync(
660
+ configOutputPath,
661
+ routePermissionDeclarations(policies, [
662
+ detectCombinedPackage(projectRoot) ? "monorise/base" : "../base/index.js"
663
+ ])
664
+ );
665
+ }
666
+ await generateHandleFile(
667
+ monoriseConfig,
668
+ projectRoot,
669
+ monoriseOutputDir,
670
+ apiKeysPath
671
+ );
672
+ return {
673
+ configDir,
674
+ apiKeysFile: apiKeysPath && apiKeysFile(apiKeysPath)
675
+ };
517
676
  }
518
677
  var MONORISE_LOGO = `
519
678
 
@@ -568,29 +727,29 @@ async function runInitCommand(rootPath) {
568
727
  let projectName = "my-app";
569
728
  let projectRoot;
570
729
  if (rootPath) {
571
- projectRoot = path3.resolve(rootPath);
572
- projectName = path3.basename(projectRoot);
730
+ projectRoot = path4.resolve(rootPath);
731
+ projectName = path4.basename(projectRoot);
573
732
  } else {
574
733
  const args = process.argv.slice(2);
575
734
  const nameIndex = args.indexOf("--name");
576
735
  if (nameIndex > -1 && args[nameIndex + 1]) {
577
736
  projectName = args[nameIndex + 1];
578
737
  }
579
- projectRoot = path3.resolve(projectName);
738
+ projectRoot = path4.resolve(projectName);
580
739
  }
581
740
  console.log(`
582
741
  \u{1F680} Creating Monorise project: ${projectName}
583
742
  `);
584
- if (fs3.existsSync(projectRoot)) {
743
+ if (fs4.existsSync(projectRoot)) {
585
744
  console.error(`Error: Directory ${projectName} already exists.`);
586
745
  process.exit(1);
587
746
  }
588
747
  console.log("\u{1F4C1} Creating project structure...");
589
- fs3.mkdirSync(projectRoot, { recursive: true });
590
- fs3.mkdirSync(path3.join(projectRoot, "apps"), { recursive: true });
591
- fs3.mkdirSync(path3.join(projectRoot, "services", "core"), { recursive: true });
592
- fs3.mkdirSync(path3.join(projectRoot, "monorise", "configs"), { recursive: true });
593
- fs3.mkdirSync(path3.join(projectRoot, "monorise", "mutuals"), { recursive: true });
748
+ fs4.mkdirSync(projectRoot, { recursive: true });
749
+ fs4.mkdirSync(path4.join(projectRoot, "apps"), { recursive: true });
750
+ fs4.mkdirSync(path4.join(projectRoot, "services", "core"), { recursive: true });
751
+ fs4.mkdirSync(path4.join(projectRoot, "monorise", "configs"), { recursive: true });
752
+ fs4.mkdirSync(path4.join(projectRoot, "monorise", "mutuals"), { recursive: true });
594
753
  console.log("\u{1F4E6} Initializing root package.json...");
595
754
  const rootPackageJson = {
596
755
  name: projectName,
@@ -599,21 +758,21 @@ async function runInitCommand(rootPath) {
599
758
  private: true,
600
759
  workspaces: ["apps/*", "services/*"]
601
760
  };
602
- fs3.writeFileSync(
603
- path3.join(projectRoot, "package.json"),
761
+ fs4.writeFileSync(
762
+ path4.join(projectRoot, "package.json"),
604
763
  JSON.stringify(rootPackageJson, null, 2)
605
764
  );
606
765
  console.log("\u2699\uFE0F Creating root tsconfig.json...");
607
- fs3.writeFileSync(
608
- path3.join(projectRoot, "tsconfig.json"),
766
+ fs4.writeFileSync(
767
+ path4.join(projectRoot, "tsconfig.json"),
609
768
  JSON.stringify(ROOT_TSCONFIG_TEMPLATE, null, 2)
610
769
  );
611
770
  console.log("\n\u{1F4F1} Creating Next.js app in apps/web...");
612
- const nextAppDir = path3.join(projectRoot, "apps", "web");
771
+ const nextAppDir = path4.join(projectRoot, "apps", "web");
613
772
  try {
614
773
  execCommand(
615
774
  `npx create-next-app@latest web --typescript --tailwind --eslint --app --no-src-dir --import-alias "#/*" --no-turbopack --yes`,
616
- path3.join(projectRoot, "apps")
775
+ path4.join(projectRoot, "apps")
617
776
  );
618
777
  } catch (error) {
619
778
  console.error("Failed to create Next.js app:", error);
@@ -634,28 +793,28 @@ async function runInitCommand(rootPath) {
634
793
  process.exit(1);
635
794
  }
636
795
  console.log("\u2699\uFE0F Creating monorise.config.ts...");
637
- fs3.writeFileSync(
638
- path3.join(projectRoot, "monorise.config.ts"),
796
+ fs4.writeFileSync(
797
+ path4.join(projectRoot, "monorise.config.ts"),
639
798
  readTemplate("monorise.config.ts")
640
799
  );
641
800
  console.log("\u{1F517} Creating team-membership mutual config...");
642
- fs3.writeFileSync(
643
- path3.join(projectRoot, "monorise", "mutuals", "team-membership.ts"),
801
+ fs4.writeFileSync(
802
+ path4.join(projectRoot, "monorise", "mutuals", "team-membership.ts"),
644
803
  readTemplate("team-membership.mutual.ts")
645
804
  );
646
805
  console.log("\u{1F464} Creating starter User entity...");
647
- fs3.writeFileSync(
648
- path3.join(projectRoot, "monorise", "configs", "user.ts"),
806
+ fs4.writeFileSync(
807
+ path4.join(projectRoot, "monorise", "configs", "user.ts"),
649
808
  readTemplate("user-entity.ts")
650
809
  );
651
810
  console.log("\u{1F465} Creating starter Team entity...");
652
- fs3.writeFileSync(
653
- path3.join(projectRoot, "monorise", "configs", "team.ts"),
811
+ fs4.writeFileSync(
812
+ path4.join(projectRoot, "monorise", "configs", "team.ts"),
654
813
  readTemplate("team-entity.ts")
655
814
  );
656
815
  console.log("\u{1F527} Creating services/core/routes.ts...");
657
- fs3.writeFileSync(
658
- path3.join(projectRoot, "services", "core", "routes.ts"),
816
+ fs4.writeFileSync(
817
+ path4.join(projectRoot, "services", "core", "routes.ts"),
659
818
  readTemplate("core-routes.ts")
660
819
  );
661
820
  const servicesPackageJson = {
@@ -663,13 +822,13 @@ async function runInitCommand(rootPath) {
663
822
  version: "0.0.0",
664
823
  type: "module"
665
824
  };
666
- fs3.writeFileSync(
667
- path3.join(projectRoot, "services", "core", "package.json"),
825
+ fs4.writeFileSync(
826
+ path4.join(projectRoot, "services", "core", "package.json"),
668
827
  JSON.stringify(servicesPackageJson, null, 2)
669
828
  );
670
829
  console.log("\u2699\uFE0F Creating sst.config.ts with Monorise...");
671
- const sstConfigPath = path3.join(projectRoot, "sst.config.ts");
672
- fs3.writeFileSync(sstConfigPath, readTemplate("sst.config.ts").replace("{{PROJECT_NAME}}", projectName));
830
+ const sstConfigPath = path4.join(projectRoot, "sst.config.ts");
831
+ fs4.writeFileSync(sstConfigPath, readTemplate("sst.config.ts").replace("{{PROJECT_NAME}}", projectName));
673
832
  console.log("\n\u2601\uFE0F Installing SST providers...");
674
833
  try {
675
834
  execCommand("npx sst install", projectRoot);
@@ -677,63 +836,63 @@ async function runInitCommand(rootPath) {
677
836
  console.warn("Warning: SST install failed, continuing anyway...");
678
837
  }
679
838
  console.log("\u{1F4C4} Creating example page in apps/web...");
680
- const webSrcAppDir = path3.join(projectRoot, "apps", "web", "src", "app");
681
- const webAppDir = path3.join(projectRoot, "apps", "web", "app");
682
- const pagePath = fs3.existsSync(webSrcAppDir) ? path3.join(webSrcAppDir, "page.tsx") : fs3.existsSync(webAppDir) ? path3.join(webAppDir, "page.tsx") : null;
839
+ const webSrcAppDir = path4.join(projectRoot, "apps", "web", "src", "app");
840
+ const webAppDir = path4.join(projectRoot, "apps", "web", "app");
841
+ const pagePath = fs4.existsSync(webSrcAppDir) ? path4.join(webSrcAppDir, "page.tsx") : fs4.existsSync(webAppDir) ? path4.join(webAppDir, "page.tsx") : null;
683
842
  if (pagePath) {
684
843
  try {
685
- fs3.writeFileSync(pagePath, readTemplate("example-page.tsx"));
686
- console.log(`Created example page at ${path3.relative(projectRoot, pagePath)}`);
844
+ fs4.writeFileSync(pagePath, readTemplate("example-page.tsx"));
845
+ console.log(`Created example page at ${path4.relative(projectRoot, pagePath)}`);
687
846
  } catch (error) {
688
847
  console.warn("Warning: Could not create example page:", error);
689
848
  }
690
849
  } else {
691
850
  console.warn("Warning: Could not find apps/web/src/app or apps/web/app directory");
692
851
  }
693
- const webRoot = fs3.existsSync(webSrcAppDir) ? path3.join(projectRoot, "apps", "web", "src") : fs3.existsSync(webAppDir) ? path3.join(projectRoot, "apps", "web") : null;
852
+ const webRoot = fs4.existsSync(webSrcAppDir) ? path4.join(projectRoot, "apps", "web", "src") : fs4.existsSync(webAppDir) ? path4.join(projectRoot, "apps", "web") : null;
694
853
  if (webRoot) {
695
- const appDir = fs3.existsSync(webSrcAppDir) ? webSrcAppDir : webAppDir;
696
- fs3.mkdirSync(path3.join(webRoot, "components", "ui"), { recursive: true });
697
- fs3.mkdirSync(path3.join(webRoot, "lib"), { recursive: true });
854
+ const appDir = fs4.existsSync(webSrcAppDir) ? webSrcAppDir : webAppDir;
855
+ fs4.mkdirSync(path4.join(webRoot, "components", "ui"), { recursive: true });
856
+ fs4.mkdirSync(path4.join(webRoot, "lib"), { recursive: true });
698
857
  console.log("\u{1F310} Creating global components...");
699
- fs3.writeFileSync(
700
- path3.join(webRoot, "components", "global-initializer.tsx"),
858
+ fs4.writeFileSync(
859
+ path4.join(webRoot, "components", "global-initializer.tsx"),
701
860
  readTemplate("global-initializer.tsx")
702
861
  );
703
- fs3.writeFileSync(
704
- path3.join(webRoot, "components", "global-loader.tsx"),
862
+ fs4.writeFileSync(
863
+ path4.join(webRoot, "components", "global-loader.tsx"),
705
864
  readTemplate("global-loader.tsx")
706
865
  );
707
866
  console.log("\u{1F527} Creating lib/utils.ts...");
708
- fs3.writeFileSync(
709
- path3.join(webRoot, "lib", "utils.ts"),
867
+ fs4.writeFileSync(
868
+ path4.join(webRoot, "lib", "utils.ts"),
710
869
  readTemplate("lib-utils.ts")
711
870
  );
712
871
  console.log("\u{1F3A8} Creating shadcn UI components...");
713
- fs3.writeFileSync(
714
- path3.join(webRoot, "components", "ui", "button.tsx"),
872
+ fs4.writeFileSync(
873
+ path4.join(webRoot, "components", "ui", "button.tsx"),
715
874
  readTemplate("ui-button.tsx")
716
875
  );
717
- fs3.writeFileSync(
718
- path3.join(webRoot, "components", "ui", "card.tsx"),
876
+ fs4.writeFileSync(
877
+ path4.join(webRoot, "components", "ui", "card.tsx"),
719
878
  readTemplate("ui-card.tsx")
720
879
  );
721
- fs3.writeFileSync(
722
- path3.join(webRoot, "components", "ui", "input.tsx"),
880
+ fs4.writeFileSync(
881
+ path4.join(webRoot, "components", "ui", "input.tsx"),
723
882
  readTemplate("ui-input.tsx")
724
883
  );
725
- fs3.writeFileSync(
726
- path3.join(webRoot, "components", "ui", "label.tsx"),
884
+ fs4.writeFileSync(
885
+ path4.join(webRoot, "components", "ui", "label.tsx"),
727
886
  readTemplate("ui-label.tsx")
728
887
  );
729
888
  console.log("\u{1F3A8} Setting up shadcn globals.css...");
730
- const globalsCssPath = path3.join(appDir, "globals.css");
731
- fs3.writeFileSync(globalsCssPath, readTemplate("globals.css"));
889
+ const globalsCssPath = path4.join(appDir, "globals.css");
890
+ fs4.writeFileSync(globalsCssPath, readTemplate("globals.css"));
732
891
  console.log("\u{1F4D0} Updating layout.tsx with global components...");
733
- const layoutPath = path3.join(appDir, "layout.tsx");
734
- if (fs3.existsSync(layoutPath)) {
892
+ const layoutPath = path4.join(appDir, "layout.tsx");
893
+ if (fs4.existsSync(layoutPath)) {
735
894
  try {
736
- let layoutContent = fs3.readFileSync(layoutPath, "utf8");
895
+ let layoutContent = fs4.readFileSync(layoutPath, "utf8");
737
896
  const globalImports = `import GlobalInitializer from '#/components/global-initializer';
738
897
  import GlobalLoader from '#/components/global-loader';`;
739
898
  const lastImportIndex = layoutContent.lastIndexOf("import ");
@@ -746,14 +905,14 @@ import GlobalLoader from '#/components/global-loader';`;
746
905
  <GlobalInitializer />
747
906
  <GlobalLoader />`
748
907
  );
749
- fs3.writeFileSync(layoutPath, layoutContent);
908
+ fs4.writeFileSync(layoutPath, layoutContent);
750
909
  } catch (error) {
751
910
  console.warn("Warning: Could not update layout.tsx:", error);
752
911
  }
753
912
  }
754
- const postcssPath = path3.join(projectRoot, "apps", "web", "postcss.config.mjs");
755
- if (fs3.existsSync(postcssPath)) {
756
- fs3.writeFileSync(
913
+ const postcssPath = path4.join(projectRoot, "apps", "web", "postcss.config.mjs");
914
+ if (fs4.existsSync(postcssPath)) {
915
+ fs4.writeFileSync(
757
916
  postcssPath,
758
917
  `const config = {
759
918
  plugins: {
@@ -766,23 +925,31 @@ export default config;
766
925
  );
767
926
  }
768
927
  console.log("\u{1F500} Creating API proxy routes...");
769
- const apiDir = path3.join(appDir, "api");
770
- const catchAllDir = path3.join(apiDir, "[...proxy]");
771
- fs3.mkdirSync(catchAllDir, { recursive: true });
772
- fs3.writeFileSync(
773
- path3.join(apiDir, "proxy-request.ts"),
774
- readTemplate("proxy-request.ts")
928
+ const coreApiDir = path4.join(appDir, "api", "core");
929
+ const proxyDir = path4.join(coreApiDir, "[...path]");
930
+ const ticketDir = path4.join(
931
+ coreApiDir,
932
+ "ws",
933
+ "ticket",
934
+ "[entityType]",
935
+ "[entityId]"
775
936
  );
776
- fs3.writeFileSync(
777
- path3.join(catchAllDir, "route.ts"),
937
+ fs4.mkdirSync(proxyDir, { recursive: true });
938
+ fs4.mkdirSync(ticketDir, { recursive: true });
939
+ fs4.writeFileSync(
940
+ path4.join(proxyDir, "route.ts"),
778
941
  readTemplate("proxy-route.ts")
779
942
  );
943
+ fs4.writeFileSync(
944
+ path4.join(ticketDir, "route.ts"),
945
+ readTemplate("ws-ticket-route.ts")
946
+ );
780
947
  }
781
948
  console.log("\u2699\uFE0F Updating apps/web tsconfig.json...");
782
- const webTsconfigPath = path3.join(projectRoot, "apps", "web", "tsconfig.json");
783
- if (fs3.existsSync(webTsconfigPath)) {
949
+ const webTsconfigPath = path4.join(projectRoot, "apps", "web", "tsconfig.json");
950
+ if (fs4.existsSync(webTsconfigPath)) {
784
951
  try {
785
- const webTsconfigContent = fs3.readFileSync(webTsconfigPath, "utf8");
952
+ const webTsconfigContent = fs4.readFileSync(webTsconfigPath, "utf8");
786
953
  const webTsconfig = JSON.parse(webTsconfigContent);
787
954
  if (!webTsconfig.compilerOptions) {
788
955
  webTsconfig.compilerOptions = {};
@@ -793,9 +960,9 @@ export default config;
793
960
  webTsconfig.compilerOptions.paths["#/shared/*"] = ["../../shared/*"];
794
961
  webTsconfig.compilerOptions.paths["#/monorise/*"] = ["../../.monorise/*"];
795
962
  webTsconfig.compilerOptions.paths["#/monorise"] = ["../../.monorise/index"];
796
- const hasSrcDir = fs3.existsSync(path3.join(projectRoot, "apps", "web", "src"));
963
+ const hasSrcDir = fs4.existsSync(path4.join(projectRoot, "apps", "web", "src"));
797
964
  webTsconfig.compilerOptions.paths["#/*"] = [hasSrcDir ? "./src/*" : "./*"];
798
- fs3.writeFileSync(webTsconfigPath, JSON.stringify(webTsconfig, null, 2));
965
+ fs4.writeFileSync(webTsconfigPath, JSON.stringify(webTsconfig, null, 2));
799
966
  } catch (error) {
800
967
  console.warn("Warning: Could not update apps/web tsconfig.json:", error);
801
968
  }
@@ -822,7 +989,7 @@ export default config;
822
989
  console.log(` \u2022 Edit your data model \u2192 monorise/configs/user.ts`);
823
990
  console.log(` (Add fields like phone, role, status to the User entity)`);
824
991
  console.log(
825
- ` \u2022 Build your UI \u2192 ${pagePath ? path3.relative(projectRoot, pagePath) : "apps/web/app/page.tsx"}`
992
+ ` \u2022 Build your UI \u2192 ${pagePath ? path4.relative(projectRoot, pagePath) : "apps/web/app/page.tsx"}`
826
993
  );
827
994
  console.log(` (React components using useEntities and createEntity)`);
828
995
  console.log(` \u2022 Add backend logic \u2192 services/core/routes.ts`);
@@ -836,12 +1003,15 @@ export default config;
836
1003
  console.log("\n\u{1F4DA} Documentation: https://monorise.dev");
837
1004
  console.log("");
838
1005
  }
839
- async function runDevCommand(configDir, rootPath) {
1006
+ async function runDevCommand({ configDir, apiKeysFile: apiKeysFile2 }, rootPath) {
840
1007
  console.log(MONORISE_LOGO);
841
- console.log(`Watching for changes in ${configDir}...`);
842
- const watcher = chokidar.watch(configDir, {
1008
+ console.log(
1009
+ `Watching for changes in ${apiKeysFile2 ? `${configDir} and ${apiKeysFile2}` : configDir}...`
1010
+ );
1011
+ const watched = apiKeysFile2 ? [configDir, apiKeysFile2] : configDir;
1012
+ const watcher = chokidar.watch(watched, {
843
1013
  ignored: (watchedPath) => {
844
- const fileName = path3.basename(watchedPath);
1014
+ const fileName = path4.basename(watchedPath);
845
1015
  return fileName === "index.ts" || // Old name, still ignore in case it exists
846
1016
  fileName === "config.ts" || // Generated config file
847
1017
  fileName === "processors.ts" || // Generated processors file
@@ -900,8 +1070,7 @@ async function main() {
900
1070
  }
901
1071
  try {
902
1072
  if (command === "dev") {
903
- const configDir = await generateFiles(rootPath);
904
- await runDevCommand(configDir, rootPath);
1073
+ await runDevCommand(await generateFiles(rootPath), rootPath);
905
1074
  } else if (command === "build") {
906
1075
  await runBuildCommand(rootPath);
907
1076
  } else if (command === "init") {