@monorise/cli 4.5.0 → 4.6.0-dev.1

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.js CHANGED
@@ -2,8 +2,8 @@
2
2
 
3
3
  // cli.ts
4
4
  import "tsx";
5
- import fs4 from "fs";
6
- import path4 from "path";
5
+ import fs5 from "fs";
6
+ import path5 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, path5) {
19
+ function athenaType(schema, path6) {
20
20
  let current = schema;
21
21
  for (; ; ) {
22
22
  const typeName = current._def?.typeName;
@@ -65,7 +65,7 @@ function athenaType(schema, path5) {
65
65
  return "json";
66
66
  }
67
67
  }
68
- function columns(schema, path5) {
68
+ function columns(schema, path6) {
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, path5) {
79
79
  const existing = names.get(name);
80
80
  if (existing) {
81
81
  throw new Error(
82
- `Analytics column identifier collision in ${path5}: ${existing} and ${sourceName} both normalize to ${name}.`
82
+ `Analytics column identifier collision in ${path6}: ${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, `${path5}.${sourceName}`)
89
+ type: athenaType(field, `${path6}.${sourceName}`)
90
90
  };
91
91
  });
92
92
  }
@@ -290,16 +290,138 @@ function createAnalyticsManifest(configs) {
290
290
  // cli.ts
291
291
  import { fileURLToPath } from "url";
292
292
 
293
- // commands/utils/detect-package.ts
293
+ // commands/utils/api-key-policies.ts
294
294
  import fs2 from "fs";
295
+ import { createRequire } from "module";
295
296
  import path2 from "path";
297
+ import { pathToFileURL } from "url";
298
+ var require2 = createRequire(import.meta.url);
299
+ var VALIDATE_API_KEY_POLICIES = /* @__PURE__ */ Symbol.for("monorise.validateApiKeyPolicies");
300
+ function resolveApiKeysPath(projectRoot, apiKeys, configDir) {
301
+ if (!apiKeys) return void 0;
302
+ const absolutePath = path2.resolve(projectRoot, apiKeys);
303
+ if (!fs2.existsSync(absolutePath) && !fs2.existsSync(`${absolutePath}.ts`) && !fs2.existsSync(`${absolutePath}.js`)) {
304
+ throw new Error(
305
+ `API key policies file not found: '${absolutePath}'. Please ensure 'apiKeys' in monorise.config.ts points to a valid file.`
306
+ );
307
+ }
308
+ const fromConfigDir = path2.relative(configDir, absolutePath);
309
+ if (!fromConfigDir.startsWith("..") && !path2.isAbsolute(fromConfigDir)) {
310
+ throw new Error(
311
+ `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'.`
312
+ );
313
+ }
314
+ return absolutePath;
315
+ }
316
+ function apiKeysFile(apiKeysPath) {
317
+ return ["", ".ts", ".js"].map((extension) => `${apiKeysPath}${extension}`).find((file) => fs2.existsSync(file) && fs2.statSync(file).isFile()) ?? apiKeysPath;
318
+ }
319
+ var importFresh = (file) => {
320
+ delete require2.cache[file];
321
+ return import(`${pathToFileURL(file).href}?t=${Date.now()}`);
322
+ };
323
+ async function validateApiKeyPoliciesFile(apiKeysPath, configOutputPath) {
324
+ const { default: generatedConfig } = await importFresh(configOutputPath);
325
+ const { default: policies } = await importFresh(apiKeysFile(apiKeysPath));
326
+ const validate = policies?.[VALIDATE_API_KEY_POLICIES];
327
+ if (typeof validate !== "function") {
328
+ throw new Error(
329
+ `API key policies file at '${apiKeysPath}' must default export the result of defineApiKeyPolicies(...).`
330
+ );
331
+ }
332
+ const errors = validate(generatedConfig.EntityConfig);
333
+ if (errors.length) {
334
+ throw new Error(
335
+ `Invalid API key policies in '${apiKeysPath}':
336
+ - ${errors.join("\n - ")}`
337
+ );
338
+ }
339
+ console.log("Validated API key policies.");
340
+ return policies;
341
+ }
342
+ function routePermissionDeclarations(policies, baseModuleNames) {
343
+ const permissions = /* @__PURE__ */ new Set();
344
+ for (const policy of Object.values(policies)) {
345
+ const routes = policy?.routes;
346
+ if (Array.isArray(routes)) {
347
+ for (const permission of routes) permissions.add(permission);
348
+ }
349
+ }
350
+ if (permissions.size === 0) return "";
351
+ const members = [...permissions].sort().map((permission) => ` ${JSON.stringify(permission)}: true;`).join("\n");
352
+ return baseModuleNames.map(
353
+ (moduleName) => `
354
+ declare module '${moduleName}' {
355
+ interface ApiKeyRoutePermissions {
356
+ ${members}
357
+ }
358
+ }
359
+ `
360
+ ).join("");
361
+ }
362
+ function apiKeyPoliciesHandleParts(monoriseOutputDir, apiKeysPath) {
363
+ if (!apiKeysPath) return { importLine: "", coreFactoryArg: "config" };
364
+ const relativePath = path2.relative(monoriseOutputDir, apiKeysPath).replace(/\.(ts|js|mjs|cjs)$/, "");
365
+ const importPath = relativePath.startsWith(".") ? relativePath : `./${relativePath}`;
366
+ return {
367
+ importLine: `import apiKeyPolicies from '${importPath}';`,
368
+ coreFactoryArg: "{ ...config, ApiKeyPolicies: apiKeyPolicies }"
369
+ };
370
+ }
371
+
372
+ // commands/utils/api-key-types.ts
373
+ var literalUnion = (names) => names.length ? names.map((name) => JSON.stringify(name)).join(" | ") : "never";
374
+ function apiKeyTypeDeclarations(entities) {
375
+ const enumKeys = new Map(
376
+ entities.map((entity) => [entity.name, entity.enumKey])
377
+ );
378
+ const tagEntries = entities.map(
379
+ ({ enumKey, config }) => `[Entity.${enumKey}]: ${literalUnion((config.tags ?? []).map((tag) => tag.name))};`
380
+ );
381
+ const mutualFields = /* @__PURE__ */ new Map();
382
+ const setDirection = (from, to, fields) => {
383
+ const targets = mutualFields.get(from) ?? /* @__PURE__ */ new Map();
384
+ if (!targets.has(to)) targets.set(to, fields);
385
+ mutualFields.set(from, targets);
386
+ };
387
+ for (const pass of ["own", "reverse"]) {
388
+ for (const { name, config } of entities) {
389
+ for (const field of Object.values(config.mutual?.mutualFields ?? {})) {
390
+ const shape = field.mutual?.mutualDataSchema?.shape;
391
+ if (!shape || !enumKeys.has(field.entityType)) continue;
392
+ const fields = Object.keys(shape);
393
+ if (pass === "own") setDirection(name, field.entityType, fields);
394
+ else setDirection(field.entityType, name, fields);
395
+ }
396
+ }
397
+ }
398
+ const mutualEntries = [...mutualFields].map(
399
+ ([from, targets]) => `[Entity.${enumKeys.get(from)}]: {
400
+ ${[...targets].map(
401
+ ([to, fields]) => ` [Entity.${enumKeys.get(to)}]: ${literalUnion(fields)};`
402
+ ).join("\n")}
403
+ };`
404
+ );
405
+ return `
406
+ export interface ApiKeyEntityTags {
407
+ ${tagEntries.join("\n ")}
408
+ }
409
+
410
+ export interface ApiKeyMutualDataFields {
411
+ ${mutualEntries.join("\n ")}
412
+ }`;
413
+ }
414
+
415
+ // commands/utils/detect-package.ts
416
+ import fs3 from "fs";
417
+ import path3 from "path";
296
418
  function detectCombinedPackage(startDir) {
297
419
  let dir = startDir;
298
420
  while (true) {
299
- if (fs2.existsSync(path2.join(dir, "node_modules", "monorise"))) {
421
+ if (fs3.existsSync(path3.join(dir, "node_modules", "monorise"))) {
300
422
  return true;
301
423
  }
302
- const parent = path2.dirname(dir);
424
+ const parent = path3.dirname(dir);
303
425
  if (parent === dir) break;
304
426
  dir = parent;
305
427
  }
@@ -307,17 +429,17 @@ function detectCombinedPackage(startDir) {
307
429
  }
308
430
 
309
431
  // commands/utils/search-manifest.ts
310
- import fs3 from "fs";
311
- import { createRequire } from "module";
312
- import path3 from "path";
313
- import { pathToFileURL } from "url";
432
+ import fs4 from "fs";
433
+ import { createRequire as createRequire2 } from "module";
434
+ import path4 from "path";
435
+ import { pathToFileURL as pathToFileURL2 } from "url";
314
436
  function searchDefaultsDeclaration(defaults) {
315
437
  return `const SearchDefaults = ${JSON.stringify(defaults ?? {})};`;
316
438
  }
317
439
  async function loadProjectBase(projectRoot) {
318
440
  const name = detectCombinedPackage(projectRoot) ? "monorise/base" : "@monorise/base";
319
- const require2 = createRequire(path3.join(projectRoot, "package.json"));
320
- const base = await import(pathToFileURL(require2.resolve(name)).href);
441
+ const require3 = createRequire2(path4.join(projectRoot, "package.json"));
442
+ const base = await import(pathToFileURL2(require3.resolve(name)).href);
321
443
  if (typeof base.searchConfigHash !== "function") {
322
444
  throw new Error(
323
445
  `'search' needs a newer ${name}: this version doesn't support the search index.`
@@ -326,10 +448,10 @@ async function loadProjectBase(projectRoot) {
326
448
  return base;
327
449
  }
328
450
  async function writeSearchManifest(monoriseOutputDir, projectRoot, configs, defaults) {
329
- const manifestPath = path3.join(monoriseOutputDir, "search-manifest.json");
451
+ const manifestPath = path4.join(monoriseOutputDir, "search-manifest.json");
330
452
  const indexed = configs.filter((config) => config.search);
331
453
  if (!indexed.length) {
332
- fs3.rmSync(manifestPath, { force: true });
454
+ fs4.rmSync(manifestPath, { force: true });
333
455
  return;
334
456
  }
335
457
  const base = await loadProjectBase(projectRoot);
@@ -347,7 +469,7 @@ async function writeSearchManifest(monoriseOutputDir, projectRoot, configs, defa
347
469
  ])
348
470
  )
349
471
  };
350
- fs3.writeFileSync(manifestPath, `${JSON.stringify(manifest, null, 2)}
472
+ fs4.writeFileSync(manifestPath, `${JSON.stringify(manifest, null, 2)}
351
473
  `);
352
474
  }
353
475
 
@@ -373,10 +495,10 @@ var ROOT_TSCONFIG_TEMPLATE = {
373
495
 
374
496
  // cli.ts
375
497
  var __filename = fileURLToPath(import.meta.url);
376
- var __dirname = path4.dirname(__filename);
377
- var TEMPLATES_DIR = path4.join(__dirname, "templates", "files");
498
+ var __dirname = path5.dirname(__filename);
499
+ var TEMPLATES_DIR = path5.join(__dirname, "templates", "files");
378
500
  function readTemplate(filename) {
379
- return fs4.readFileSync(path4.join(TEMPLATES_DIR, filename), "utf-8");
501
+ return fs5.readFileSync(path5.join(TEMPLATES_DIR, filename), "utf-8");
380
502
  }
381
503
  function kebabToCamel(str) {
382
504
  return str.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());
@@ -389,19 +511,19 @@ function execCommand(command, cwd, stdio = "inherit") {
389
511
  execSync(command, { cwd, stdio });
390
512
  }
391
513
  async function generateConfigFile(configDir, monoriseOutputDir, projectRoot, searchDefaults) {
392
- const configOutputPath = path4.join(monoriseOutputDir, "config.ts");
514
+ const configOutputPath = path5.join(monoriseOutputDir, "config.ts");
393
515
  const initialConfigContent = `
394
516
  export enum Entity {}
395
517
  export default {};
396
518
  `;
397
- fs4.writeFileSync(configOutputPath, initialConfigContent);
398
- fs4.writeFileSync(
399
- path4.join(monoriseOutputDir, "index.ts"),
519
+ fs5.writeFileSync(configOutputPath, initialConfigContent);
520
+ fs5.writeFileSync(
521
+ path5.join(monoriseOutputDir, "index.ts"),
400
522
  `export * from './config';
401
523
  export { default } from './config';
402
524
  `
403
525
  );
404
- const files = fs4.readdirSync(configDir).filter((file) => file.endsWith(".ts") && file !== "index.ts");
526
+ const files = fs5.readdirSync(configDir).filter((file) => file.endsWith(".ts") && file !== "index.ts");
405
527
  const names = /* @__PURE__ */ new Set();
406
528
  const nameRegex = /^[a-z]+(-[a-z]+)*$/;
407
529
  const imports = [];
@@ -413,11 +535,12 @@ export { default } from './config';
413
535
  const allowedEntityEntries = [];
414
536
  const entityWithEmailAuthEntries = [];
415
537
  const analyticsConfigs = [];
538
+ const apiKeyTypeEntities = [];
416
539
  const searchConfigs = [];
417
- const relativePathToConfigDir = path4.relative(monoriseOutputDir, configDir);
540
+ const relativePathToConfigDir = path5.relative(monoriseOutputDir, configDir);
418
541
  const importPathPrefix = relativePathToConfigDir ? `${relativePathToConfigDir}/` : "./";
419
542
  for (const file of files) {
420
- const fullPath = path4.join(configDir, file);
543
+ const fullPath = path5.join(configDir, file);
421
544
  const module = await import(fullPath);
422
545
  const config = module.default;
423
546
  if (!nameRegex.test(config.name)) {
@@ -449,6 +572,7 @@ export { default } from './config';
449
572
  `[Entity.${enumKey}]: ${kebabToCamel(config.name)}.finalSchema,`
450
573
  );
451
574
  allowedEntityEntries.push(`Entity.${enumKey}`);
575
+ apiKeyTypeEntities.push({ name: config.name, enumKey, config });
452
576
  if (config.authMethod?.email) {
453
577
  entityWithEmailAuthEntries.push(`Entity.${enumKey}`);
454
578
  }
@@ -465,6 +589,7 @@ declare module '${moduleName}' {
465
589
  export interface EntitySchemaMap {
466
590
  ${schemaMapEntries.join("\n ")}
467
591
  }
592
+ ${apiKeyTypeDeclarations(apiKeyTypeEntities)}
468
593
  }`;
469
594
  const moduleAugmentations = usesCombinedPackage ? augmentationBlock("monorise/base") : augmentationBlock("@monorise/base");
470
595
  const configOutputContent = `
@@ -516,7 +641,7 @@ const config = {
516
641
  export default config;
517
642
  ${moduleAugmentations}
518
643
  `;
519
- fs4.writeFileSync(configOutputPath, configOutputContent);
644
+ fs5.writeFileSync(configOutputPath, configOutputContent);
520
645
  writeAnalyticsManifest(monoriseOutputDir, analyticsConfigs);
521
646
  await writeSearchManifest(
522
647
  monoriseOutputDir,
@@ -525,8 +650,8 @@ ${moduleAugmentations}
525
650
  searchDefaults
526
651
  );
527
652
  console.log("Successfully generated config.ts!");
528
- const indexOutputPath = path4.join(monoriseOutputDir, "index.ts");
529
- fs4.writeFileSync(
653
+ const indexOutputPath = path5.join(monoriseOutputDir, "index.ts");
654
+ fs5.writeFileSync(
530
655
  indexOutputPath,
531
656
  `export * from './config';
532
657
  export { default } from './config';
@@ -535,22 +660,22 @@ export { default } from './config';
535
660
  console.log("Successfully generated index.ts!");
536
661
  return configOutputPath;
537
662
  }
538
- async function generateHandleFile(monoriseConfig, projectRoot, monoriseOutputDir) {
539
- const handleOutputPath = path4.join(monoriseOutputDir, "handle.ts");
663
+ async function generateHandleFile(monoriseConfig, projectRoot, monoriseOutputDir, apiKeysPath) {
664
+ const handleOutputPath = path5.join(monoriseOutputDir, "handle.ts");
540
665
  const customRoutesPath = monoriseConfig.customRoutes;
541
666
  let routesImportLine = "";
542
667
  let appHandlerPayload = "{}";
543
668
  if (customRoutesPath) {
544
- const absoluteCustomRoutesPath = path4.resolve(
669
+ const absoluteCustomRoutesPath = path5.resolve(
545
670
  projectRoot,
546
671
  customRoutesPath
547
672
  );
548
- if (!fs4.existsSync(absoluteCustomRoutesPath) && !fs4.existsSync(`${absoluteCustomRoutesPath}.ts`) && !fs4.existsSync(`${absoluteCustomRoutesPath}.js`)) {
673
+ if (!fs5.existsSync(absoluteCustomRoutesPath) && !fs5.existsSync(`${absoluteCustomRoutesPath}.ts`) && !fs5.existsSync(`${absoluteCustomRoutesPath}.js`)) {
549
674
  throw new Error(
550
675
  `Custom routes file not found: '${absoluteCustomRoutesPath}'. Please ensure 'customRoutes' in monorise.config.ts points to a valid file.`
551
676
  );
552
677
  }
553
- let relativePathToRoutes = path4.relative(
678
+ let relativePathToRoutes = path5.relative(
554
679
  monoriseOutputDir,
555
680
  absoluteCustomRoutesPath
556
681
  );
@@ -563,12 +688,17 @@ async function generateHandleFile(monoriseConfig, projectRoot, monoriseOutputDir
563
688
  }
564
689
  const usesCombinedPackage = detectCombinedPackage(projectRoot);
565
690
  const coreImportPath = usesCombinedPackage ? "monorise/core" : "@monorise/core";
691
+ const apiKeyPolicies = apiKeyPoliciesHandleParts(
692
+ monoriseOutputDir,
693
+ apiKeysPath
694
+ );
566
695
  const combinedContent = `
567
696
  import CoreFactory, { analyticsMaterializationProcessor, analyticsModelProcessor, analyticsQueryHandler as createAnalyticsQueryHandler, analyticsViewProcessor } from '${coreImportPath}';
568
697
  import config from './config';
569
698
  import analyticsManifest from './analytics-manifest.json';
570
699
  ${routesImportLine ? `${routesImportLine}
571
- ` : ""}const coreFactory = new CoreFactory(config);
700
+ ` : ""}${apiKeyPolicies.importLine ? `${apiKeyPolicies.importLine}
701
+ ` : ""}const coreFactory = new CoreFactory(${apiKeyPolicies.coreFactoryArg});
572
702
 
573
703
  export const replicationHandler = coreFactory.replicationProcessor;
574
704
  export const searchReindexHandler = coreFactory.searchReindexProcessor;
@@ -589,38 +719,63 @@ export const wsDisconnect = coreFactory.wsDisconnect;
589
719
  export const wsDefault = coreFactory.wsDefault;
590
720
  export const wsBroadcast = coreFactory.wsBroadcast;
591
721
  `;
592
- fs4.writeFileSync(handleOutputPath, combinedContent);
722
+ fs5.writeFileSync(handleOutputPath, combinedContent);
593
723
  console.log("Successfully generated handle.ts!");
594
724
  return handleOutputPath;
595
725
  }
596
726
  async function generateFiles(rootPath) {
597
- const baseDir = rootPath ? path4.resolve(rootPath) : process.cwd();
598
- const configFilePathTS = path4.join(baseDir, "monorise.config.ts");
599
- const configFilePathJS = path4.join(baseDir, "monorise.config.js");
727
+ const baseDir = rootPath ? path5.resolve(rootPath) : process.cwd();
728
+ const configFilePathTS = path5.join(baseDir, "monorise.config.ts");
729
+ const configFilePathJS = path5.join(baseDir, "monorise.config.js");
600
730
  let configFilePath;
601
- if (fs4.existsSync(configFilePathTS)) {
731
+ if (fs5.existsSync(configFilePathTS)) {
602
732
  configFilePath = configFilePathTS;
603
- } else if (fs4.existsSync(configFilePathJS)) {
733
+ } else if (fs5.existsSync(configFilePathJS)) {
604
734
  configFilePath = configFilePathJS;
605
735
  } else {
606
736
  throw new Error(
607
737
  "Neither monorise.config.ts nor monorise.config.js found in the root of the project."
608
738
  );
609
739
  }
610
- const projectRoot = path4.dirname(configFilePath);
740
+ const projectRoot = path5.dirname(configFilePath);
611
741
  const monoriseConfigModule = await import(configFilePath);
612
742
  const monoriseConfig = monoriseConfigModule.default;
613
- const configDir = path4.resolve(projectRoot, monoriseConfig.configDir);
614
- const monoriseOutputDir = path4.join(projectRoot, ".monorise");
615
- fs4.mkdirSync(monoriseOutputDir, { recursive: true });
616
- await generateConfigFile(
743
+ const configDir = path5.resolve(projectRoot, monoriseConfig.configDir);
744
+ const monoriseOutputDir = path5.join(projectRoot, ".monorise");
745
+ fs5.mkdirSync(monoriseOutputDir, { recursive: true });
746
+ const apiKeysPath = resolveApiKeysPath(
747
+ projectRoot,
748
+ monoriseConfig.apiKeys,
749
+ configDir
750
+ );
751
+ const configOutputPath = await generateConfigFile(
617
752
  configDir,
618
753
  monoriseOutputDir,
619
754
  projectRoot,
620
755
  monoriseConfig.search
621
756
  );
622
- await generateHandleFile(monoriseConfig, projectRoot, monoriseOutputDir);
623
- return configDir;
757
+ if (apiKeysPath) {
758
+ const policies = await validateApiKeyPoliciesFile(
759
+ apiKeysPath,
760
+ configOutputPath
761
+ );
762
+ fs5.appendFileSync(
763
+ configOutputPath,
764
+ routePermissionDeclarations(policies, [
765
+ detectCombinedPackage(projectRoot) ? "monorise/base" : "@monorise/base"
766
+ ])
767
+ );
768
+ }
769
+ await generateHandleFile(
770
+ monoriseConfig,
771
+ projectRoot,
772
+ monoriseOutputDir,
773
+ apiKeysPath
774
+ );
775
+ return {
776
+ configDir,
777
+ apiKeysFile: apiKeysPath && apiKeysFile(apiKeysPath)
778
+ };
624
779
  }
625
780
  var MONORISE_LOGO = `
626
781
 
@@ -675,29 +830,29 @@ async function runInitCommand(rootPath) {
675
830
  let projectName = "my-app";
676
831
  let projectRoot;
677
832
  if (rootPath) {
678
- projectRoot = path4.resolve(rootPath);
679
- projectName = path4.basename(projectRoot);
833
+ projectRoot = path5.resolve(rootPath);
834
+ projectName = path5.basename(projectRoot);
680
835
  } else {
681
836
  const args = process.argv.slice(2);
682
837
  const nameIndex = args.indexOf("--name");
683
838
  if (nameIndex > -1 && args[nameIndex + 1]) {
684
839
  projectName = args[nameIndex + 1];
685
840
  }
686
- projectRoot = path4.resolve(projectName);
841
+ projectRoot = path5.resolve(projectName);
687
842
  }
688
843
  console.log(`
689
844
  \u{1F680} Creating Monorise project: ${projectName}
690
845
  `);
691
- if (fs4.existsSync(projectRoot)) {
846
+ if (fs5.existsSync(projectRoot)) {
692
847
  console.error(`Error: Directory ${projectName} already exists.`);
693
848
  process.exit(1);
694
849
  }
695
850
  console.log("\u{1F4C1} Creating project structure...");
696
- fs4.mkdirSync(projectRoot, { recursive: true });
697
- fs4.mkdirSync(path4.join(projectRoot, "apps"), { recursive: true });
698
- fs4.mkdirSync(path4.join(projectRoot, "services", "core"), { recursive: true });
699
- fs4.mkdirSync(path4.join(projectRoot, "monorise", "configs"), { recursive: true });
700
- fs4.mkdirSync(path4.join(projectRoot, "monorise", "mutuals"), { recursive: true });
851
+ fs5.mkdirSync(projectRoot, { recursive: true });
852
+ fs5.mkdirSync(path5.join(projectRoot, "apps"), { recursive: true });
853
+ fs5.mkdirSync(path5.join(projectRoot, "services", "core"), { recursive: true });
854
+ fs5.mkdirSync(path5.join(projectRoot, "monorise", "configs"), { recursive: true });
855
+ fs5.mkdirSync(path5.join(projectRoot, "monorise", "mutuals"), { recursive: true });
701
856
  console.log("\u{1F4E6} Initializing root package.json...");
702
857
  const rootPackageJson = {
703
858
  name: projectName,
@@ -706,21 +861,21 @@ async function runInitCommand(rootPath) {
706
861
  private: true,
707
862
  workspaces: ["apps/*", "services/*"]
708
863
  };
709
- fs4.writeFileSync(
710
- path4.join(projectRoot, "package.json"),
864
+ fs5.writeFileSync(
865
+ path5.join(projectRoot, "package.json"),
711
866
  JSON.stringify(rootPackageJson, null, 2)
712
867
  );
713
868
  console.log("\u2699\uFE0F Creating root tsconfig.json...");
714
- fs4.writeFileSync(
715
- path4.join(projectRoot, "tsconfig.json"),
869
+ fs5.writeFileSync(
870
+ path5.join(projectRoot, "tsconfig.json"),
716
871
  JSON.stringify(ROOT_TSCONFIG_TEMPLATE, null, 2)
717
872
  );
718
873
  console.log("\n\u{1F4F1} Creating Next.js app in apps/web...");
719
- const nextAppDir = path4.join(projectRoot, "apps", "web");
874
+ const nextAppDir = path5.join(projectRoot, "apps", "web");
720
875
  try {
721
876
  execCommand(
722
877
  `npx create-next-app@latest web --typescript --tailwind --eslint --app --no-src-dir --import-alias "#/*" --no-turbopack --yes`,
723
- path4.join(projectRoot, "apps")
878
+ path5.join(projectRoot, "apps")
724
879
  );
725
880
  } catch (error) {
726
881
  console.error("Failed to create Next.js app:", error);
@@ -741,28 +896,32 @@ async function runInitCommand(rootPath) {
741
896
  process.exit(1);
742
897
  }
743
898
  console.log("\u2699\uFE0F Creating monorise.config.ts...");
744
- fs4.writeFileSync(
745
- path4.join(projectRoot, "monorise.config.ts"),
899
+ fs5.writeFileSync(
900
+ path5.join(projectRoot, "monorise.config.ts"),
746
901
  readTemplate("monorise.config.ts")
747
902
  );
903
+ fs5.writeFileSync(
904
+ path5.join(projectRoot, "monorise", "api-keys.ts"),
905
+ readTemplate("api-keys.ts")
906
+ );
748
907
  console.log("\u{1F517} Creating team-membership mutual config...");
749
- fs4.writeFileSync(
750
- path4.join(projectRoot, "monorise", "mutuals", "team-membership.ts"),
908
+ fs5.writeFileSync(
909
+ path5.join(projectRoot, "monorise", "mutuals", "team-membership.ts"),
751
910
  readTemplate("team-membership.mutual.ts")
752
911
  );
753
912
  console.log("\u{1F464} Creating starter User entity...");
754
- fs4.writeFileSync(
755
- path4.join(projectRoot, "monorise", "configs", "user.ts"),
913
+ fs5.writeFileSync(
914
+ path5.join(projectRoot, "monorise", "configs", "user.ts"),
756
915
  readTemplate("user-entity.ts")
757
916
  );
758
917
  console.log("\u{1F465} Creating starter Team entity...");
759
- fs4.writeFileSync(
760
- path4.join(projectRoot, "monorise", "configs", "team.ts"),
918
+ fs5.writeFileSync(
919
+ path5.join(projectRoot, "monorise", "configs", "team.ts"),
761
920
  readTemplate("team-entity.ts")
762
921
  );
763
922
  console.log("\u{1F527} Creating services/core/routes.ts...");
764
- fs4.writeFileSync(
765
- path4.join(projectRoot, "services", "core", "routes.ts"),
923
+ fs5.writeFileSync(
924
+ path5.join(projectRoot, "services", "core", "routes.ts"),
766
925
  readTemplate("core-routes.ts")
767
926
  );
768
927
  const servicesPackageJson = {
@@ -770,13 +929,13 @@ async function runInitCommand(rootPath) {
770
929
  version: "0.0.0",
771
930
  type: "module"
772
931
  };
773
- fs4.writeFileSync(
774
- path4.join(projectRoot, "services", "core", "package.json"),
932
+ fs5.writeFileSync(
933
+ path5.join(projectRoot, "services", "core", "package.json"),
775
934
  JSON.stringify(servicesPackageJson, null, 2)
776
935
  );
777
936
  console.log("\u2699\uFE0F Creating sst.config.ts with Monorise...");
778
- const sstConfigPath = path4.join(projectRoot, "sst.config.ts");
779
- fs4.writeFileSync(sstConfigPath, readTemplate("sst.config.ts").replace("{{PROJECT_NAME}}", projectName));
937
+ const sstConfigPath = path5.join(projectRoot, "sst.config.ts");
938
+ fs5.writeFileSync(sstConfigPath, readTemplate("sst.config.ts").replace("{{PROJECT_NAME}}", projectName));
780
939
  console.log("\n\u2601\uFE0F Installing SST providers...");
781
940
  try {
782
941
  execCommand("npx sst install", projectRoot);
@@ -784,63 +943,63 @@ async function runInitCommand(rootPath) {
784
943
  console.warn("Warning: SST install failed, continuing anyway...");
785
944
  }
786
945
  console.log("\u{1F4C4} Creating example page in apps/web...");
787
- const webSrcAppDir = path4.join(projectRoot, "apps", "web", "src", "app");
788
- const webAppDir = path4.join(projectRoot, "apps", "web", "app");
789
- const pagePath = fs4.existsSync(webSrcAppDir) ? path4.join(webSrcAppDir, "page.tsx") : fs4.existsSync(webAppDir) ? path4.join(webAppDir, "page.tsx") : null;
946
+ const webSrcAppDir = path5.join(projectRoot, "apps", "web", "src", "app");
947
+ const webAppDir = path5.join(projectRoot, "apps", "web", "app");
948
+ const pagePath = fs5.existsSync(webSrcAppDir) ? path5.join(webSrcAppDir, "page.tsx") : fs5.existsSync(webAppDir) ? path5.join(webAppDir, "page.tsx") : null;
790
949
  if (pagePath) {
791
950
  try {
792
- fs4.writeFileSync(pagePath, readTemplate("example-page.tsx"));
793
- console.log(`Created example page at ${path4.relative(projectRoot, pagePath)}`);
951
+ fs5.writeFileSync(pagePath, readTemplate("example-page.tsx"));
952
+ console.log(`Created example page at ${path5.relative(projectRoot, pagePath)}`);
794
953
  } catch (error) {
795
954
  console.warn("Warning: Could not create example page:", error);
796
955
  }
797
956
  } else {
798
957
  console.warn("Warning: Could not find apps/web/src/app or apps/web/app directory");
799
958
  }
800
- const webRoot = fs4.existsSync(webSrcAppDir) ? path4.join(projectRoot, "apps", "web", "src") : fs4.existsSync(webAppDir) ? path4.join(projectRoot, "apps", "web") : null;
959
+ const webRoot = fs5.existsSync(webSrcAppDir) ? path5.join(projectRoot, "apps", "web", "src") : fs5.existsSync(webAppDir) ? path5.join(projectRoot, "apps", "web") : null;
801
960
  if (webRoot) {
802
- const appDir = fs4.existsSync(webSrcAppDir) ? webSrcAppDir : webAppDir;
803
- fs4.mkdirSync(path4.join(webRoot, "components", "ui"), { recursive: true });
804
- fs4.mkdirSync(path4.join(webRoot, "lib"), { recursive: true });
961
+ const appDir = fs5.existsSync(webSrcAppDir) ? webSrcAppDir : webAppDir;
962
+ fs5.mkdirSync(path5.join(webRoot, "components", "ui"), { recursive: true });
963
+ fs5.mkdirSync(path5.join(webRoot, "lib"), { recursive: true });
805
964
  console.log("\u{1F310} Creating global components...");
806
- fs4.writeFileSync(
807
- path4.join(webRoot, "components", "global-initializer.tsx"),
965
+ fs5.writeFileSync(
966
+ path5.join(webRoot, "components", "global-initializer.tsx"),
808
967
  readTemplate("global-initializer.tsx")
809
968
  );
810
- fs4.writeFileSync(
811
- path4.join(webRoot, "components", "global-loader.tsx"),
969
+ fs5.writeFileSync(
970
+ path5.join(webRoot, "components", "global-loader.tsx"),
812
971
  readTemplate("global-loader.tsx")
813
972
  );
814
973
  console.log("\u{1F527} Creating lib/utils.ts...");
815
- fs4.writeFileSync(
816
- path4.join(webRoot, "lib", "utils.ts"),
974
+ fs5.writeFileSync(
975
+ path5.join(webRoot, "lib", "utils.ts"),
817
976
  readTemplate("lib-utils.ts")
818
977
  );
819
978
  console.log("\u{1F3A8} Creating shadcn UI components...");
820
- fs4.writeFileSync(
821
- path4.join(webRoot, "components", "ui", "button.tsx"),
979
+ fs5.writeFileSync(
980
+ path5.join(webRoot, "components", "ui", "button.tsx"),
822
981
  readTemplate("ui-button.tsx")
823
982
  );
824
- fs4.writeFileSync(
825
- path4.join(webRoot, "components", "ui", "card.tsx"),
983
+ fs5.writeFileSync(
984
+ path5.join(webRoot, "components", "ui", "card.tsx"),
826
985
  readTemplate("ui-card.tsx")
827
986
  );
828
- fs4.writeFileSync(
829
- path4.join(webRoot, "components", "ui", "input.tsx"),
987
+ fs5.writeFileSync(
988
+ path5.join(webRoot, "components", "ui", "input.tsx"),
830
989
  readTemplate("ui-input.tsx")
831
990
  );
832
- fs4.writeFileSync(
833
- path4.join(webRoot, "components", "ui", "label.tsx"),
991
+ fs5.writeFileSync(
992
+ path5.join(webRoot, "components", "ui", "label.tsx"),
834
993
  readTemplate("ui-label.tsx")
835
994
  );
836
995
  console.log("\u{1F3A8} Setting up shadcn globals.css...");
837
- const globalsCssPath = path4.join(appDir, "globals.css");
838
- fs4.writeFileSync(globalsCssPath, readTemplate("globals.css"));
996
+ const globalsCssPath = path5.join(appDir, "globals.css");
997
+ fs5.writeFileSync(globalsCssPath, readTemplate("globals.css"));
839
998
  console.log("\u{1F4D0} Updating layout.tsx with global components...");
840
- const layoutPath = path4.join(appDir, "layout.tsx");
841
- if (fs4.existsSync(layoutPath)) {
999
+ const layoutPath = path5.join(appDir, "layout.tsx");
1000
+ if (fs5.existsSync(layoutPath)) {
842
1001
  try {
843
- let layoutContent = fs4.readFileSync(layoutPath, "utf8");
1002
+ let layoutContent = fs5.readFileSync(layoutPath, "utf8");
844
1003
  const globalImports = `import GlobalInitializer from '#/components/global-initializer';
845
1004
  import GlobalLoader from '#/components/global-loader';`;
846
1005
  const lastImportIndex = layoutContent.lastIndexOf("import ");
@@ -853,14 +1012,14 @@ import GlobalLoader from '#/components/global-loader';`;
853
1012
  <GlobalInitializer />
854
1013
  <GlobalLoader />`
855
1014
  );
856
- fs4.writeFileSync(layoutPath, layoutContent);
1015
+ fs5.writeFileSync(layoutPath, layoutContent);
857
1016
  } catch (error) {
858
1017
  console.warn("Warning: Could not update layout.tsx:", error);
859
1018
  }
860
1019
  }
861
- const postcssPath = path4.join(projectRoot, "apps", "web", "postcss.config.mjs");
862
- if (fs4.existsSync(postcssPath)) {
863
- fs4.writeFileSync(
1020
+ const postcssPath = path5.join(projectRoot, "apps", "web", "postcss.config.mjs");
1021
+ if (fs5.existsSync(postcssPath)) {
1022
+ fs5.writeFileSync(
864
1023
  postcssPath,
865
1024
  `const config = {
866
1025
  plugins: {
@@ -873,23 +1032,31 @@ export default config;
873
1032
  );
874
1033
  }
875
1034
  console.log("\u{1F500} Creating API proxy routes...");
876
- const apiDir = path4.join(appDir, "api");
877
- const catchAllDir = path4.join(apiDir, "[...proxy]");
878
- fs4.mkdirSync(catchAllDir, { recursive: true });
879
- fs4.writeFileSync(
880
- path4.join(apiDir, "proxy-request.ts"),
881
- readTemplate("proxy-request.ts")
1035
+ const coreApiDir = path5.join(appDir, "api", "core");
1036
+ const proxyDir = path5.join(coreApiDir, "[...path]");
1037
+ const ticketDir = path5.join(
1038
+ coreApiDir,
1039
+ "ws",
1040
+ "ticket",
1041
+ "[entityType]",
1042
+ "[entityId]"
882
1043
  );
883
- fs4.writeFileSync(
884
- path4.join(catchAllDir, "route.ts"),
1044
+ fs5.mkdirSync(proxyDir, { recursive: true });
1045
+ fs5.mkdirSync(ticketDir, { recursive: true });
1046
+ fs5.writeFileSync(
1047
+ path5.join(proxyDir, "route.ts"),
885
1048
  readTemplate("proxy-route.ts")
886
1049
  );
1050
+ fs5.writeFileSync(
1051
+ path5.join(ticketDir, "route.ts"),
1052
+ readTemplate("ws-ticket-route.ts")
1053
+ );
887
1054
  }
888
1055
  console.log("\u2699\uFE0F Updating apps/web tsconfig.json...");
889
- const webTsconfigPath = path4.join(projectRoot, "apps", "web", "tsconfig.json");
890
- if (fs4.existsSync(webTsconfigPath)) {
1056
+ const webTsconfigPath = path5.join(projectRoot, "apps", "web", "tsconfig.json");
1057
+ if (fs5.existsSync(webTsconfigPath)) {
891
1058
  try {
892
- const webTsconfigContent = fs4.readFileSync(webTsconfigPath, "utf8");
1059
+ const webTsconfigContent = fs5.readFileSync(webTsconfigPath, "utf8");
893
1060
  const webTsconfig = JSON.parse(webTsconfigContent);
894
1061
  if (!webTsconfig.compilerOptions) {
895
1062
  webTsconfig.compilerOptions = {};
@@ -899,10 +1066,10 @@ export default config;
899
1066
  }
900
1067
  webTsconfig.compilerOptions.paths["#/shared/*"] = ["../../shared/*"];
901
1068
  webTsconfig.compilerOptions.paths["#/monorise/*"] = ["../../.monorise/*"];
902
- webTsconfig.compilerOptions.paths["#/monorise"] = ["../../.monorise/index"];
903
- const hasSrcDir = fs4.existsSync(path4.join(projectRoot, "apps", "web", "src"));
1069
+ webTsconfig.compilerOptions.paths["#/monorise"] = ["../../.monorise/config"];
1070
+ const hasSrcDir = fs5.existsSync(path5.join(projectRoot, "apps", "web", "src"));
904
1071
  webTsconfig.compilerOptions.paths["#/*"] = [hasSrcDir ? "./src/*" : "./*"];
905
- fs4.writeFileSync(webTsconfigPath, JSON.stringify(webTsconfig, null, 2));
1072
+ fs5.writeFileSync(webTsconfigPath, JSON.stringify(webTsconfig, null, 2));
906
1073
  } catch (error) {
907
1074
  console.warn("Warning: Could not update apps/web tsconfig.json:", error);
908
1075
  }
@@ -929,7 +1096,7 @@ export default config;
929
1096
  console.log(` \u2022 Edit your data model \u2192 monorise/configs/user.ts`);
930
1097
  console.log(` (Add fields like phone, role, status to the User entity)`);
931
1098
  console.log(
932
- ` \u2022 Build your UI \u2192 ${pagePath ? path4.relative(projectRoot, pagePath) : "apps/web/app/page.tsx"}`
1099
+ ` \u2022 Build your UI \u2192 ${pagePath ? path5.relative(projectRoot, pagePath) : "apps/web/app/page.tsx"}`
933
1100
  );
934
1101
  console.log(` (React components using useEntities and createEntity)`);
935
1102
  console.log(` \u2022 Add backend logic \u2192 services/core/routes.ts`);
@@ -943,12 +1110,15 @@ export default config;
943
1110
  console.log("\n\u{1F4DA} Documentation: https://monorise.dev");
944
1111
  console.log("");
945
1112
  }
946
- async function runDevCommand(configDir, rootPath) {
1113
+ async function runDevCommand({ configDir, apiKeysFile: apiKeysFile2 }, rootPath) {
947
1114
  console.log(MONORISE_LOGO);
948
- console.log(`Watching for changes in ${configDir}...`);
949
- const watcher = chokidar.watch(configDir, {
1115
+ console.log(
1116
+ `Watching for changes in ${apiKeysFile2 ? `${configDir} and ${apiKeysFile2}` : configDir}...`
1117
+ );
1118
+ const watched = apiKeysFile2 ? [configDir, apiKeysFile2] : configDir;
1119
+ const watcher = chokidar.watch(watched, {
950
1120
  ignored: (watchedPath) => {
951
- const fileName = path4.basename(watchedPath);
1121
+ const fileName = path5.basename(watchedPath);
952
1122
  return fileName === "index.ts" || // Old name, still ignore in case it exists
953
1123
  fileName === "config.ts" || // Generated config file
954
1124
  fileName === "processors.ts" || // Generated processors file
@@ -1007,8 +1177,7 @@ async function main() {
1007
1177
  }
1008
1178
  try {
1009
1179
  if (command === "dev") {
1010
- const configDir = await generateFiles(rootPath);
1011
- await runDevCommand(configDir, rootPath);
1180
+ await runDevCommand(await generateFiles(rootPath), rootPath);
1012
1181
  } else if (command === "build") {
1013
1182
  await runBuildCommand(rootPath);
1014
1183
  } else if (command === "init") {