monorise 1.15.0-dev.0 → 2.0.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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../cli.ts","../commands/utils/analytics-manifest.ts","../commands/utils/api-key-policies.ts","../commands/utils/api-key-types.ts","../commands/utils/detect-package.ts","../templates/root-tsconfig.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport 'tsx';\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { execSync, spawn } from 'node:child_process';\nimport chokidar from 'chokidar';\nimport {\n writeAnalyticsManifest,\n type AnalyticsConfig,\n} from './commands/utils/analytics-manifest';\nimport { fileURLToPath } from 'node:url';\nimport {\n apiKeyPoliciesHandleParts,\n apiKeysFile,\n resolveApiKeysPath,\n routePermissionDeclarations,\n validateApiKeyPoliciesFile,\n} from './commands/utils/api-key-policies';\nimport { apiKeyTypeDeclarations } from './commands/utils/api-key-types';\nimport { detectCombinedPackage } from './commands/utils/detect-package';\nimport { ROOT_TSCONFIG_TEMPLATE } from './templates/root-tsconfig';\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = path.dirname(__filename);\nconst TEMPLATES_DIR = path.join(__dirname, 'templates', 'files');\n\nfunction readTemplate(filename: string): string {\n return fs.readFileSync(path.join(TEMPLATES_DIR, filename), 'utf-8');\n}\n\nfunction kebabToCamel(str: string): string {\n return str.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());\n}\n\nfunction kebabToPascal(kebab: string): string {\n return kebab\n .split('-')\n .map((word) => word.charAt(0).toUpperCase() + word.slice(1))\n .join('');\n}\n\nfunction execCommand(\n command: string,\n cwd?: string,\n stdio: 'inherit' | 'pipe' = 'inherit',\n): void {\n console.log(`Running: ${command}`);\n execSync(command, { cwd, stdio });\n}\n\nasync function generateConfigFile(\n configDir: string,\n monoriseOutputDir: string,\n projectRoot: string,\n): Promise<string> {\n const configOutputPath = path.join(monoriseOutputDir, 'config.ts');\n const initialConfigContent = `\nexport enum Entity {}\nexport default {};\n`;\n fs.writeFileSync(configOutputPath, initialConfigContent);\n fs.writeFileSync(\n path.join(monoriseOutputDir, 'index.ts'),\n `export * from './config';\\nexport { default } from './config';\\n`,\n );\n\n const files = fs\n .readdirSync(configDir)\n .filter((file) => file.endsWith('.ts') && file !== 'index.ts');\n\n const names = new Set<string>();\n const nameRegex = /^[a-z]+(-[a-z]+)*$/;\n const imports: string[] = [];\n\n const enumEntries: string[] = [];\n const typeEntries: string[] = [];\n const schemaMapEntries: string[] = [];\n const configEntries: string[] = [];\n const schemaEntries: string[] = [];\n const allowedEntityEntries: string[] = [];\n const entityWithEmailAuthEntries: string[] = [];\n const analyticsConfigs: AnalyticsConfig[] = [];\n const apiKeyTypeEntities: Parameters<typeof apiKeyTypeDeclarations>[0] =\n [];\n\n const relativePathToConfigDir = path.relative(monoriseOutputDir, configDir);\n const importPathPrefix = relativePathToConfigDir\n ? `${relativePathToConfigDir}/`\n : './';\n\n for (const file of files) {\n const fullPath = path.join(configDir, file);\n const module = await import(fullPath);\n const config = module.default;\n\n if (!nameRegex.test(config.name)) {\n throw new Error(\n `Invalid name format: ${config.name} in ${file}. Must be kebab-case.`,\n );\n }\n\n if (names.has(config.name)) {\n throw new Error(`Duplicate name found: ${config.name} in ${file}`);\n }\n names.add(config.name);\n analyticsConfigs.push(config as AnalyticsConfig);\n\n const fileName = file.replace(/\\.ts$/, '');\n const variableName = kebabToCamel(fileName);\n imports.push(\n `import ${variableName} from '${importPathPrefix}${fileName}';`,\n );\n\n const enumKey = config.name.toUpperCase().replace(/-/g, '_');\n enumEntries.push(`${enumKey} = '${config.name}'`);\n typeEntries.push(\n `export type ${kebabToPascal(config.name)}Type = z.infer<(typeof ${variableName})['finalSchema']>;`,\n );\n schemaMapEntries.push(\n `[Entity.${enumKey}]: ${kebabToPascal(config.name)}Type;`,\n );\n\n configEntries.push(`[Entity.${enumKey}]: ${kebabToCamel(config.name)},`);\n schemaEntries.push(\n `[Entity.${enumKey}]: ${kebabToCamel(config.name)}.finalSchema,`,\n );\n\n allowedEntityEntries.push(`Entity.${enumKey}`);\n apiKeyTypeEntities.push({ name: config.name, enumKey, config });\n\n if (config.authMethod?.email) {\n entityWithEmailAuthEntries.push(`Entity.${enumKey}`);\n }\n }\n\n // Detect whether the consumer uses the combined 'monorise' package or scoped '@monorise/*' packages\n const usesCombinedPackage = detectCombinedPackage(projectRoot);\n\n // Build module augmentation block\n const augmentationBlock = (moduleName: string) => `\ndeclare module '${moduleName}' {\n export enum Entity {\n ${enumEntries.join(',\\n ')}\n }\n\n ${typeEntries.join('\\n ')}\n\n export interface EntitySchemaMap {\n ${schemaMapEntries.join('\\n ')}\n }\n${apiKeyTypeDeclarations(apiKeyTypeEntities)}\n}`;\n\n // Augment the correct module based on which package is installed\n const moduleAugmentations = usesCombinedPackage\n ? augmentationBlock('monorise/base')\n : augmentationBlock('@monorise/base');\n\n const configOutputContent = `\nimport type { z } from 'zod';\n${imports.join('\\n')}\n\nexport enum Entity {\n ${enumEntries.join(',\\n ')}\n}\n\n${typeEntries.join('\\n')}\n\nexport interface EntitySchemaMap {\n ${schemaMapEntries.join('\\n ')}\n}\n\nconst EntityConfig = {\n ${configEntries.join('\\n ')}\n};\n\nconst FormSchema = {\n ${schemaEntries.join('\\n ')}\n};\n\nconst AllowedEntityTypes = [\n ${allowedEntityEntries.join(',\\n ')}\n];\n\nconst EmailAuthEnabledEntities: Entity[] = [${entityWithEmailAuthEntries.join(', ')}];\n\nexport {\n EntityConfig,\n FormSchema,\n AllowedEntityTypes,\n EmailAuthEnabledEntities,\n};\n\nconst config = {\n EntityConfig,\n FormSchema,\n AllowedEntityTypes,\n EmailAuthEnabledEntities,\n};\n\nexport default config;\n${moduleAugmentations}\n`;\n\n fs.writeFileSync(configOutputPath, configOutputContent);\n writeAnalyticsManifest(monoriseOutputDir, analyticsConfigs);\n console.log('Successfully generated config.ts!');\n\n // Also generate index.ts re-exporting everything from config.ts, so consumers\n // can import from '#/monorise' directly instead of '#/monorise/config'.\n // config.ts keeps being generated for backward compatibility.\n const indexOutputPath = path.join(monoriseOutputDir, 'index.ts');\n fs.writeFileSync(\n indexOutputPath,\n `export * from './config';\\nexport { default } from './config';\\n`,\n );\n console.log('Successfully generated index.ts!');\n\n return configOutputPath;\n}\n\nasync function generateHandleFile(\n monoriseConfig: { customRoutes?: string; configDir: string },\n projectRoot: string,\n monoriseOutputDir: string,\n apiKeysPath?: string,\n): Promise<string> {\n const handleOutputPath = path.join(monoriseOutputDir, 'handle.ts');\n const customRoutesPath = monoriseConfig.customRoutes;\n\n let routesImportLine = '';\n let appHandlerPayload = '{}'; // Default to an empty object for appHandler if no custom routes\n\n if (customRoutesPath) {\n const absoluteCustomRoutesPath = path.resolve(\n projectRoot,\n customRoutesPath,\n );\n\n if (\n !fs.existsSync(absoluteCustomRoutesPath) &&\n !fs.existsSync(`${absoluteCustomRoutesPath}.ts`) &&\n !fs.existsSync(`${absoluteCustomRoutesPath}.js`)\n ) {\n throw new Error(\n `Custom routes file not found: '${absoluteCustomRoutesPath}'. Please ensure 'customRoutes' in monorise.config.ts points to a valid file.`,\n );\n }\n\n let relativePathToRoutes = path.relative(\n monoriseOutputDir,\n absoluteCustomRoutesPath,\n );\n relativePathToRoutes = relativePathToRoutes.replace(\n /\\.(ts|js|mjs|cjs)$/,\n '',\n );\n\n // If custom routes are provided, include the import statement and pass 'routes' to appHandler\n routesImportLine = `import routes from '${relativePathToRoutes}';`;\n appHandlerPayload = '{ routes }';\n }\n // If customRoutesPath is not provided, routesImportLine remains empty and appHandlerPayload remains `{}`\n\n // Detect whether the consumer uses the combined 'monorise' package or scoped '@monorise/*' packages\n const usesCombinedPackage = detectCombinedPackage(projectRoot);\n const coreImportPath = usesCombinedPackage ? 'monorise/core' : '@monorise/core';\n const apiKeyPolicies = apiKeyPoliciesHandleParts(\n monoriseOutputDir,\n apiKeysPath,\n );\n\n const combinedContent = `\nimport CoreFactory, { analyticsMaterializationProcessor, analyticsModelProcessor, analyticsQueryHandler as createAnalyticsQueryHandler, analyticsViewProcessor } from '${coreImportPath}';\nimport config from './config';\nimport analyticsManifest from './analytics-manifest.json';\n${routesImportLine ? `${routesImportLine}\\n` : ''}${apiKeyPolicies.importLine ? `${apiKeyPolicies.importLine}\\n` : ''}const coreFactory = new CoreFactory(${apiKeyPolicies.coreFactoryArg});\n\nexport const replicationHandler = coreFactory.replicationProcessor;\nexport const analyticsHandler = coreFactory.analyticsProcessor;\nexport const analyticsBackfillHandler = coreFactory.analyticsBackfillProcessor;\nexport const analyticsMaterializationHandler = analyticsMaterializationProcessor(analyticsManifest);\nexport const analyticsQueryHandler = createAnalyticsQueryHandler();\nexport const analyticsModelHandler = analyticsModelProcessor;\nexport const analyticsViewHandler = analyticsViewProcessor;\nexport const mutualHandler = coreFactory.mutualProcessor;\nexport const tagHandler = coreFactory.tagProcessor;\nexport const treeHandler = coreFactory.prejoinProcessor;\nexport const appHandler = coreFactory.appHandler(${appHandlerPayload});\n\n// WebSocket handlers (wrapped with DependencyContainer for SST to resolve)\nexport const wsConnect = coreFactory.wsConnect;\nexport const wsDisconnect = coreFactory.wsDisconnect;\nexport const wsDefault = coreFactory.wsDefault;\nexport const wsBroadcast = coreFactory.wsBroadcast;\n`;\n fs.writeFileSync(handleOutputPath, combinedContent);\n console.log('Successfully generated handle.ts!');\n\n return handleOutputPath;\n}\n\n// What `monorise dev` watches: the entity configs, and the policy file,\n// which lives outside them.\ntype GeneratedFrom = { configDir: string; apiKeysFile?: string };\n\nasync function generateFiles(rootPath?: string): Promise<GeneratedFrom> {\n const baseDir = rootPath ? path.resolve(rootPath) : process.cwd();\n const configFilePathTS = path.join(baseDir, 'monorise.config.ts');\n const configFilePathJS = path.join(baseDir, 'monorise.config.js');\n\n let configFilePath: string;\n if (fs.existsSync(configFilePathTS)) {\n configFilePath = configFilePathTS;\n } else if (fs.existsSync(configFilePathJS)) {\n configFilePath = configFilePathJS;\n } else {\n throw new Error(\n 'Neither monorise.config.ts nor monorise.config.js found in the root of the project.',\n );\n }\n\n const projectRoot = path.dirname(configFilePath);\n const monoriseConfigModule = await import(configFilePath);\n const monoriseConfig = monoriseConfigModule.default;\n\n const configDir = path.resolve(projectRoot, monoriseConfig.configDir);\n const monoriseOutputDir = path.join(projectRoot, '.monorise');\n\n fs.mkdirSync(monoriseOutputDir, { recursive: true });\n\n // Resolved first, so a misplaced policy file fails before it is loaded as\n // an entity config.\n const apiKeysPath = resolveApiKeysPath(\n projectRoot,\n monoriseConfig.apiKeys,\n configDir,\n );\n const configOutputPath = await generateConfigFile(\n configDir,\n monoriseOutputDir,\n projectRoot,\n );\n if (apiKeysPath) {\n const policies = await validateApiKeyPoliciesFile(\n apiKeysPath,\n configOutputPath,\n );\n fs.appendFileSync(\n configOutputPath,\n routePermissionDeclarations(policies, [\n detectCombinedPackage(projectRoot) ? 'monorise/base' : '@monorise/base',\n ]),\n );\n }\n await generateHandleFile(\n monoriseConfig,\n projectRoot,\n monoriseOutputDir,\n apiKeysPath,\n );\n\n return {\n configDir,\n apiKeysFile: apiKeysPath && apiKeysFile(apiKeysPath),\n };\n}\n\nconst MONORISE_LOGO = `\n\n\n\n ░░░░░░░\n ░░▒▒▒░░░░░░▒▒▒░\n ░▒▒░ ░▒▒░\n ░▒▒░ ░▒▒░\n ░▒░ ░▒▒░\n ░▒▒░ ▒▒▒░\n ░▒░░░▒░ ░▒░░▒▒░\n ░▒▒░ ░▒▒▒░ ░▒▒░ ░▒░░\n ░▒▒ ░▒▒░ ░▒▒░ ░▒░ ░▒░ ░▒░\n ░▒▒░ ░▒░ ░▒░░▒▒░░░ ░░▒▒░░▒░ ░▒▒ ░▒░\n ░░▒░ ░▒░ ░▒░ ░▒▒░░▒▒▒▒▒▒░░▒░ ░▒░░ ░▒░ ░▒░\n ░▒░ ░░▒░ ░▒░ ░░░ ░▒░ ░░ ░▒░ ░▒░ ░▒░░ ░░▒░\n ░▒░ ░▒░ ░▒░ ░▒ ░░ ░▒░ ░▒░ ░▒░ ░▒░ ░░░░\n ░░░ ░░░░ ░░░ ░░ ▒░ ░░░ ░░░ ░░░ ░░░ ░░░░\n ░░░ ░░░░ ░░░ ░░░ ░░░ ░░ ░░░ ░░░ ░░░ ░░░░\n ░░░ ░░░ ░░░ ░░░ ░░ ░░ ░░░ ░░░ ░░░ ░░░\n ░░░ ░░░░ ░░░ ░░░ ░░ ░░░ ░░ ░░░ ░░░ ░░░\n ░░ ░░░ ░░░ ░░░ ░░░ ░░ ░░░ ░░░ ░░░ ░░░\n ░░ ░░ ░░ ░░ ░░ ░░░ ░░░ ░░░ ░░░░ ░░░\n ░░░ ░░ ░░░ ░░░ ░░░\n ░░░░░▒░░░░░░░░░▒░░░░░░░░░ ░ ░░ ░░░ ░░░ ░░\n ░░░ ░░░░░░░░░ ░░░ ░░░\n ░░░ ░░░░░░ ░░ ░░░░░▒░░░░░░▒░░░░\n ░░░░░░░░░░░░░░░░░ ░░░░░ ░░░░░░░░ ░░\n ░░░░░░░ ░░░░░░░░░░░░░░ ░░░░ ░░░░░ ░▒░\n ░░░ ░░░░░░░ ░░░░░░ ░░░░░░░░\n ░░░░░░░░░░░░ ░░░░░░ ░░░░ ░░░░░░░░░░░░░\n ░▒▒░░░░░░░░░░░▒▒░░ ░░▒▒▒░░ ░▒▒░░ ░░░░\n ░▒░ ░░▒▒░ ░▒░ ░▒▒░ ░░▒░\n ░▒░ ░░░░▒▒▒▒▒▒▒▒▒▒░░ ░▒░ ▒▒░ ░░▒▒▒░\n ░▒▒▒▒▒░░░ ░░░▒▒▒▒▒░ ▒▒░ ░▒▒▒▒▒▒░\n ░▒▒░ ░▒▒▒▒ ▒▒▒ ▒▒▒\n ░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░░ ░▒▒▒▒▒░ ░▒▒\n ▒▒▒ ░░▒▒▒▒▒▒░ ▒▒▒ ░▒▒\n ▒▒▒ ░▒▒▒▒ ░▒▒▒░\n ▒▓▓▓▒▒▒▓▓▒▒▒░ ▒▒▒░░▒▒░\n ▒▓░ ░▒▒▓▓▒░ ▒▓▓░\n ░▒▓░ ░▒▓▒░▒▓▒\n ░▒▓▒░ ░▒▓▓▒\n ░▒▒▓▓▓▓▓▓▒▒░\n\n\n\n`;\n\nasync function runInitCommand(rootPath?: string) {\n console.log(MONORISE_LOGO);\n\n // Determine project name and root\n let projectName = 'my-app';\n let projectRoot: string;\n\n if (rootPath) {\n projectRoot = path.resolve(rootPath);\n projectName = path.basename(projectRoot);\n } else {\n // Prompt for project name (simple approach for now)\n const args = process.argv.slice(2);\n const nameIndex = args.indexOf('--name');\n if (nameIndex > -1 && args[nameIndex + 1]) {\n projectName = args[nameIndex + 1];\n }\n projectRoot = path.resolve(projectName);\n }\n\n console.log(`\\n🚀 Creating Monorise project: ${projectName}\\n`);\n\n // Check if directory exists\n if (fs.existsSync(projectRoot)) {\n console.error(`Error: Directory ${projectName} already exists.`);\n process.exit(1);\n }\n\n // Step 1: Create project directory structure\n console.log('📁 Creating project structure...');\n fs.mkdirSync(projectRoot, { recursive: true });\n fs.mkdirSync(path.join(projectRoot, 'apps'), { recursive: true });\n fs.mkdirSync(path.join(projectRoot, 'services', 'core'), { recursive: true });\n fs.mkdirSync(path.join(projectRoot, 'monorise', 'configs'), { recursive: true });\n fs.mkdirSync(path.join(projectRoot, 'monorise', 'mutuals'), { recursive: true });\n\n // Step 2: Create root package.json\n console.log('📦 Initializing root package.json...');\n const rootPackageJson = {\n name: projectName,\n version: '0.0.0',\n type: 'module',\n private: true,\n workspaces: ['apps/*', 'services/*'],\n };\n fs.writeFileSync(\n path.join(projectRoot, 'package.json'),\n JSON.stringify(rootPackageJson, null, 2),\n );\n\n // Step 3: Create root tsconfig.json\n console.log('⚙️ Creating root tsconfig.json...');\n fs.writeFileSync(\n path.join(projectRoot, 'tsconfig.json'),\n JSON.stringify(ROOT_TSCONFIG_TEMPLATE, null, 2),\n );\n\n // Step 4: Create Next.js app in apps/web\n console.log('\\n📱 Creating Next.js app in apps/web...');\n const nextAppDir = path.join(projectRoot, 'apps', 'web');\n try {\n execCommand(\n `npx create-next-app@latest web --typescript --tailwind --eslint --app --no-src-dir --import-alias \"#/*\" --no-turbopack --yes`,\n path.join(projectRoot, 'apps'),\n );\n } catch (error) {\n console.error('Failed to create Next.js app:', error);\n process.exit(1);\n }\n\n // Step 5: Install SST v4\n console.log('\\n☁️ Installing SST v4...');\n try {\n execCommand('npm install sst@^4 --save-dev', projectRoot);\n } catch (error) {\n console.error('Failed to install SST:', error);\n process.exit(1);\n }\n\n // Step 6: Install dependencies\n console.log('\\n📦 Installing dependencies (monorise, hono, zod, shadcn utilities)...');\n try {\n execCommand('npm install monorise hono zod clsx class-variance-authority radix-ui lucide-react tailwind-merge react-hook-form @hookform/resolvers', projectRoot);\n } catch (error) {\n console.error('Failed to install dependencies:', error);\n process.exit(1);\n }\n\n // Step 7: Create monorise.config.ts\n console.log('⚙️ Creating monorise.config.ts...');\n fs.writeFileSync(\n path.join(projectRoot, 'monorise.config.ts'),\n readTemplate('monorise.config.ts'),\n );\n\n // Step 8: Create shared mutual config (referenced by both User and Team)\n console.log('🔗 Creating team-membership mutual config...');\n fs.writeFileSync(\n path.join(projectRoot, 'monorise', 'mutuals', 'team-membership.ts'),\n readTemplate('team-membership.mutual.ts'),\n );\n\n // Step 9: Create starter entities (User <-> Team mutual relationship)\n console.log('👤 Creating starter User entity...');\n fs.writeFileSync(\n path.join(projectRoot, 'monorise', 'configs', 'user.ts'),\n readTemplate('user-entity.ts'),\n );\n console.log('👥 Creating starter Team entity...');\n fs.writeFileSync(\n path.join(projectRoot, 'monorise', 'configs', 'team.ts'),\n readTemplate('team-entity.ts'),\n );\n\n // Step 10: Create services/core/routes.ts\n console.log('🔧 Creating services/core/routes.ts...');\n fs.writeFileSync(\n path.join(projectRoot, 'services', 'core', 'routes.ts'),\n readTemplate('core-routes.ts'),\n );\n\n // Step 11: Create services package.json\n const servicesPackageJson = {\n name: '@my-app/services',\n version: '0.0.0',\n type: 'module',\n };\n fs.writeFileSync(\n path.join(projectRoot, 'services', 'core', 'package.json'),\n JSON.stringify(servicesPackageJson, null, 2),\n );\n\n // Step 12: Create sst.config.ts with monorise\n console.log('⚙️ Creating sst.config.ts with Monorise...');\n const sstConfigPath = path.join(projectRoot, 'sst.config.ts');\n fs.writeFileSync(sstConfigPath, readTemplate('sst.config.ts').replace('{{PROJECT_NAME}}', projectName));\n\n // Step 13: Install SST providers (after sst.config.ts exists)\n console.log('\\n☁️ Installing SST providers...');\n try {\n execCommand('npx sst install', projectRoot);\n } catch (error) {\n console.warn('Warning: SST install failed, continuing anyway...');\n }\n\n // Step 14: Create example page in apps/web\n console.log('📄 Creating example page in apps/web...');\n const webSrcAppDir = path.join(projectRoot, 'apps', 'web', 'src', 'app');\n const webAppDir = path.join(projectRoot, 'apps', 'web', 'app');\n const pagePath = fs.existsSync(webSrcAppDir)\n ? path.join(webSrcAppDir, 'page.tsx')\n : fs.existsSync(webAppDir)\n ? path.join(webAppDir, 'page.tsx')\n : null;\n\n if (pagePath) {\n try {\n fs.writeFileSync(pagePath, readTemplate('example-page.tsx'));\n console.log(`Created example page at ${path.relative(projectRoot, pagePath)}`);\n } catch (error) {\n console.warn('Warning: Could not create example page:', error);\n }\n } else {\n console.warn('Warning: Could not find apps/web/src/app or apps/web/app directory');\n }\n\n // Step 15: Create global components, lib/utils, UI components, and globals.css\n const webRoot = fs.existsSync(webSrcAppDir)\n ? path.join(projectRoot, 'apps', 'web', 'src')\n : fs.existsSync(webAppDir)\n ? path.join(projectRoot, 'apps', 'web')\n : null;\n\n if (webRoot) {\n const appDir = fs.existsSync(webSrcAppDir) ? webSrcAppDir : webAppDir;\n\n // Create directories\n fs.mkdirSync(path.join(webRoot, 'components', 'ui'), { recursive: true });\n fs.mkdirSync(path.join(webRoot, 'lib'), { recursive: true });\n\n // Global components\n console.log('🌐 Creating global components...');\n fs.writeFileSync(\n path.join(webRoot, 'components', 'global-initializer.tsx'),\n readTemplate('global-initializer.tsx'),\n );\n fs.writeFileSync(\n path.join(webRoot, 'components', 'global-loader.tsx'),\n readTemplate('global-loader.tsx'),\n );\n\n // lib/utils.ts\n console.log('🔧 Creating lib/utils.ts...');\n fs.writeFileSync(\n path.join(webRoot, 'lib', 'utils.ts'),\n readTemplate('lib-utils.ts'),\n );\n\n // Shadcn UI components\n console.log('🎨 Creating shadcn UI components...');\n fs.writeFileSync(\n path.join(webRoot, 'components', 'ui', 'button.tsx'),\n readTemplate('ui-button.tsx'),\n );\n fs.writeFileSync(\n path.join(webRoot, 'components', 'ui', 'card.tsx'),\n readTemplate('ui-card.tsx'),\n );\n fs.writeFileSync(\n path.join(webRoot, 'components', 'ui', 'input.tsx'),\n readTemplate('ui-input.tsx'),\n );\n fs.writeFileSync(\n path.join(webRoot, 'components', 'ui', 'label.tsx'),\n readTemplate('ui-label.tsx'),\n );\n\n // Replace globals.css with shadcn theme\n console.log('🎨 Setting up shadcn globals.css...');\n const globalsCssPath = path.join(appDir, 'globals.css');\n fs.writeFileSync(globalsCssPath, readTemplate('globals.css'));\n\n // Update layout.tsx with GlobalInitializer, GlobalLoader, and loader-portal\n console.log('📐 Updating layout.tsx with global components...');\n const layoutPath = path.join(appDir, 'layout.tsx');\n if (fs.existsSync(layoutPath)) {\n try {\n let layoutContent = fs.readFileSync(layoutPath, 'utf8');\n\n // Add imports after existing imports\n const globalImports = `import GlobalInitializer from '#/components/global-initializer';\\nimport GlobalLoader from '#/components/global-loader';`;\n // Insert after the last import statement\n const lastImportIndex = layoutContent.lastIndexOf('import ');\n const lineEnd = layoutContent.indexOf('\\n', lastImportIndex);\n layoutContent =\n layoutContent.slice(0, lineEnd + 1) +\n globalImports +\n '\\n' +\n layoutContent.slice(lineEnd + 1);\n\n // Add loader-portal div and global components inside <body>\n layoutContent = layoutContent.replace(\n /(<body[^>]*>)/,\n `$1\\n <div id=\"loader-portal\" />\\n <GlobalInitializer />\\n <GlobalLoader />`,\n );\n\n fs.writeFileSync(layoutPath, layoutContent);\n } catch (error) {\n console.warn('Warning: Could not update layout.tsx:', error);\n }\n }\n\n // Replace postcss.config.mjs with @tailwindcss/postcss\n const postcssPath = path.join(projectRoot, 'apps', 'web', 'postcss.config.mjs');\n if (fs.existsSync(postcssPath)) {\n fs.writeFileSync(\n postcssPath,\n `const config = {\\n plugins: {\\n '@tailwindcss/postcss': {},\\n },\\n};\\n\\nexport default config;\\n`,\n );\n }\n\n // Create the API proxy route, and the WebSocket ticket route the proxy\n // leaves to its own route\n console.log('🔀 Creating API proxy routes...');\n const coreApiDir = path.join(appDir, 'api', 'core');\n const proxyDir = path.join(coreApiDir, '[...path]');\n const ticketDir = path.join(\n coreApiDir,\n 'ws',\n 'ticket',\n '[entityType]',\n '[entityId]',\n );\n fs.mkdirSync(proxyDir, { recursive: true });\n fs.mkdirSync(ticketDir, { recursive: true });\n fs.writeFileSync(\n path.join(proxyDir, 'route.ts'),\n readTemplate('proxy-route.ts'),\n );\n fs.writeFileSync(\n path.join(ticketDir, 'route.ts'),\n readTemplate('ws-ticket-route.ts'),\n );\n }\n\n // Step 16: Update apps/web tsconfig.json with monorise path alias\n console.log('⚙️ Updating apps/web tsconfig.json...');\n const webTsconfigPath = path.join(projectRoot, 'apps', 'web', 'tsconfig.json');\n if (fs.existsSync(webTsconfigPath)) {\n try {\n const webTsconfigContent = fs.readFileSync(webTsconfigPath, 'utf8');\n const webTsconfig = JSON.parse(webTsconfigContent);\n\n if (!webTsconfig.compilerOptions) {\n webTsconfig.compilerOptions = {};\n }\n if (!webTsconfig.compilerOptions.paths) {\n webTsconfig.compilerOptions.paths = {};\n }\n\n // Add path aliases\n webTsconfig.compilerOptions.paths['#/shared/*'] = ['../../shared/*'];\n webTsconfig.compilerOptions.paths['#/monorise/*'] = ['../../.monorise/*'];\n // Exact-match alias so `import { Entity } from '#/monorise'` resolves to\n // the generated index.ts (re-exports config.ts, kept for backward compat).\n webTsconfig.compilerOptions.paths['#/monorise'] = ['../../.monorise/index'];\n const hasSrcDir = fs.existsSync(path.join(projectRoot, 'apps', 'web', 'src'));\n webTsconfig.compilerOptions.paths['#/*'] = [hasSrcDir ? './src/*' : './*'];\n\n fs.writeFileSync(webTsconfigPath, JSON.stringify(webTsconfig, null, 2));\n } catch (error) {\n console.warn('Warning: Could not update apps/web tsconfig.json:', error);\n }\n }\n\n // Step 16: Run initial monorise build to generate .monorise files\n console.log('\\n🔨 Running initial Monorise build...');\n try {\n execCommand('npx monorise build', projectRoot);\n } catch (error) {\n console.warn('Warning: Initial monorise build failed. You can run it manually later.');\n }\n\n console.log('\\n' + '='.repeat(60));\n console.log('✅ Monorise project created successfully!');\n console.log('='.repeat(60));\n console.log(`\\n📁 Project structure:`);\n console.log(` ${projectName}/`);\n console.log(` ├── apps/web/ # Next.js frontend`);\n console.log(` ├── services/core/ # Backend routes (Hono)`);\n console.log(` ├── monorise/configs/ # Entity definitions (User, Team)`);\n console.log(` ├── monorise/mutuals/ # Shared mutual relationship configs`);\n console.log(` └── .monorise/ # Generated files`);\n console.log(`\\n📂 Where to start coding:`);\n console.log(` • Edit your data model → monorise/configs/user.ts`);\n console.log(` (Add fields like phone, role, status to the User entity)`);\n console.log(\n ` • Build your UI → ${pagePath ? path.relative(projectRoot, pagePath) : 'apps/web/app/page.tsx'}`,\n );\n console.log(` (React components using useEntities and createEntity)`);\n console.log(` • Add backend logic → services/core/routes.ts`);\n console.log(` (Custom API endpoints with Hono)`);\n console.log(` • See the User <-> Team relationship → monorise/mutuals/team-membership.ts`);\n console.log(` (createMutualConfig — shared schema, referenced from both entity configs)`);\n console.log(`\\n🚀 Next steps:`);\n console.log(` cd ${projectName}`);\n console.log(` npx sst dev`);\n console.log('\\n📚 Documentation: https://monorise.dev');\n console.log('');\n}\n\nasync function runDevCommand(\n { configDir, apiKeysFile }: GeneratedFrom,\n rootPath?: string,\n) {\n console.log(MONORISE_LOGO);\n console.log(\n `Watching for changes in ${apiKeysFile ? `${configDir} and ${apiKeysFile}` : configDir}...`,\n );\n const watched = apiKeysFile ? [configDir, apiKeysFile] : configDir;\n const watcher = chokidar.watch(watched, {\n ignored: (watchedPath: string) => {\n const fileName = path.basename(watchedPath);\n return (\n fileName === 'index.ts' || // Old name, still ignore in case it exists\n fileName === 'config.ts' || // Generated config file\n fileName === 'processors.ts' || // Generated processors file\n fileName === 'app.ts' || // Generated app file\n fileName.startsWith('.') ||\n watchedPath.endsWith('.js') ||\n watchedPath.endsWith('.jsx') ||\n watchedPath.endsWith('.d.ts')\n );\n },\n persistent: true,\n ignoreInitial: true,\n });\n\n watcher.on('add', async (filePath) => {\n console.log(`File ${filePath} has been added. Regenerating...`);\n try {\n await generateFiles(rootPath);\n } catch (err) {\n console.error('Regeneration failed:', err);\n }\n });\n\n watcher.on('change', async (filePath) => {\n console.log(`File ${filePath} has been changed. Regenerating...`);\n try {\n await generateFiles(rootPath);\n } catch (err) {\n console.error('Regeneration failed:', err);\n }\n });\n\n watcher.on('unlink', async (filePath) => {\n console.log(`File ${filePath} has been removed. Regenerating...`);\n try {\n await generateFiles(rootPath);\n } catch (err) {\n console.error('Regeneration failed:', err);\n }\n });\n\n process.on('SIGINT', () => {\n console.log('Monorise dev terminated. Closing watcher and sst dev...');\n watcher.close();\n process.exit(0);\n });\n process.on('SIGTERM', () => {\n console.log('Monorise dev terminated. Closing watcher and sst dev...');\n watcher.close();\n process.exit(0);\n });\n}\n\nasync function runBuildCommand(rootPath?: string) {\n console.log('Starting sst build...');\n await generateFiles(rootPath);\n}\n\nasync function main() {\n const args = process.argv.slice(2);\n const command = args[0];\n\n let rootPath: string | undefined;\n const rootFlagIndex = args.indexOf('--config-root');\n if (rootFlagIndex > -1 && args[rootFlagIndex + 1]) {\n rootPath = args[rootFlagIndex + 1];\n }\n\n try {\n if (command === 'dev') {\n await runDevCommand(await generateFiles(rootPath), rootPath);\n } else if (command === 'build') {\n await runBuildCommand(rootPath);\n } else if (command === 'init') {\n // init is greenfield-only — it always creates a fresh directory named via\n // --name, never an existing path. --config-root doesn't apply here.\n await runInitCommand();\n } else {\n console.error(\n 'Unknown command. Usage:\\n' +\n ' monorise dev [--config-root <path>]\\n' +\n ' monorise build [--config-root <path>]\\n' +\n ' monorise init [--name <project-name>]',\n );\n process.exit(1);\n }\n } catch (err) {\n console.error('Monorise process failed:', err);\n process.exit(1);\n }\n}\n\nmain().catch((err) => {\n console.error('Monorise encountered an unhandled error:', err);\n process.exit(1);\n});\n","import { createHash } from 'node:crypto';\nimport fs from 'node:fs';\nimport path from 'node:path';\n\ntype ZodSchema = {\n _def?: {\n typeName?: string;\n innerType?: ZodSchema;\n schema?: ZodSchema;\n type?: ZodSchema;\n effect?: { type?: string };\n values?: Record<string, unknown>;\n value?: unknown;\n checks?: { kind?: string }[];\n };\n shape?: Record<string, ZodSchema>;\n};\n\nexport type AnalyticsColumn = {\n name: string;\n sourceName: string;\n type: 'boolean' | 'double' | 'string' | 'timestamp' | 'json';\n};\n\nexport type AnalyticsDataset = {\n kind: 'entity' | 'mutual';\n name: string;\n identifier: string;\n idColumn: string;\n endpoints: AnalyticsEndpoint[];\n currentTable: string;\n historyTable: string;\n columns: AnalyticsColumn[];\n partition: { granularity: 'day' };\n};\n\nexport type AnalyticsEndpoint = {\n entityName: string;\n column: string;\n role?: 'source' | 'target';\n};\n\nexport type AnalyticsManifest = {\n version: 2;\n datasets: AnalyticsDataset[];\n unnamedMutuals: string[];\n schemaFingerprint: string;\n};\n\nexport type AnalyticsConfig = {\n name: string;\n finalSchema: ZodSchema;\n mutual?: {\n mutualFields?: Record<\n string,\n { entityType: string; mutual?: AnalyticsMutual }\n >;\n };\n};\n\ntype AnalyticsMutual = {\n name?: string;\n entities?: [string, string];\n mutualDataSchema: ZodSchema;\n};\n\nconst lowerKebabCase = /^[a-z]+(?:-[a-z]+)*$/;\n\nexport function normalizeSqlIdentifier(name: string): string {\n const normalized = name\n .replace(/([a-z0-9])([A-Z])/g, '$1_$2')\n .replace(/[^a-zA-Z0-9]+/g, '_')\n .replace(/^_+|_+$/g, '')\n .toLowerCase();\n return /^[a-z_]/.test(normalized) ? normalized : `_${normalized}`;\n}\n\nfunction athenaType(schema: ZodSchema, path: string): AnalyticsColumn['type'] {\n let current = schema;\n for (;;) {\n const typeName = current._def?.typeName;\n if (typeName === 'ZodEffects') {\n // Refinements do not change the persisted shape. Transforms can, so retain\n // their value as JSON instead of inferring an incorrect scalar type.\n if (current._def?.effect?.type !== 'refinement') return 'json';\n if (!current._def.schema) return 'json';\n current = current._def.schema;\n continue;\n }\n if (\n typeName === 'ZodOptional' ||\n typeName === 'ZodNullable' ||\n typeName === 'ZodDefault' ||\n typeName === 'ZodCatch' ||\n typeName === 'ZodReadonly'\n ) {\n if (!current._def?.innerType) return 'json';\n current = current._def.innerType;\n continue;\n }\n if (typeName === 'ZodBranded') {\n if (!current._def?.type) return 'json';\n current = current._def.type;\n continue;\n }\n break;\n }\n\n switch (current._def?.typeName) {\n case 'ZodString':\n return current._def.checks?.some((check) => check.kind === 'datetime')\n ? 'timestamp'\n : 'string';\n case 'ZodNumber':\n return 'double';\n case 'ZodBoolean':\n return 'boolean';\n case 'ZodDate':\n return 'timestamp';\n case 'ZodEnum':\n return 'string';\n case 'ZodNativeEnum': {\n const values = current._def.values ?? {};\n const validValues = Object.keys(values)\n .filter((key) => typeof values[String(values[key])] !== 'number')\n .map((key) => values[key]);\n if (validValues.every((value) => typeof value === 'string')) return 'string';\n if (validValues.every((value) => typeof value === 'number')) return 'double';\n return 'json';\n }\n case 'ZodLiteral':\n return typeof current._def.value === 'string'\n ? 'string'\n : typeof current._def.value === 'number'\n ? 'double'\n : typeof current._def.value === 'boolean'\n ? 'boolean'\n : 'json';\n case 'ZodArray':\n case 'ZodObject':\n return 'json';\n default:\n // Keep every valid Zod field queryable without assigning an unsafe type.\n return 'json';\n }\n}\n\nfunction columns(schema: ZodSchema, path: string): AnalyticsColumn[] {\n let objectSchema = schema;\n // Entity effects commonly add superRefine validation around the final object.\n while (!objectSchema.shape && objectSchema._def?.typeName === 'ZodEffects') {\n const innerSchema = objectSchema._def.schema;\n if (!innerSchema) break;\n objectSchema = innerSchema;\n }\n if (!objectSchema.shape) return [];\n\n const names = new Map<string, string>();\n return Object.entries(objectSchema.shape).map(([sourceName, field]) => {\n const name = normalizeSqlIdentifier(sourceName);\n const existing = names.get(name);\n if (existing) {\n throw new Error(\n `Analytics column identifier collision in ${path}: ${existing} and ${sourceName} both normalize to ${name}.`,\n );\n }\n names.set(name, sourceName);\n return {\n name,\n sourceName,\n type: athenaType(field, `${path}.${sourceName}`),\n };\n });\n}\n\nfunction endpoints(entities: [string, string]): AnalyticsEndpoint[] {\n const [first, second] = entities;\n if (first === second) {\n const identifier = normalizeSqlIdentifier(first);\n return [\n { entityName: first, column: `${identifier}_source_id`, role: 'source' },\n { entityName: second, column: `${identifier}_target_id`, role: 'target' },\n ];\n }\n\n return [first, second]\n .sort()\n .map((entityName) => ({\n entityName,\n column: `${normalizeSqlIdentifier(entityName)}_id`,\n }));\n}\n\nfunction fingerprint(datasets: AnalyticsDataset[]): string {\n return createHash('sha256').update(JSON.stringify(datasets)).digest('hex');\n}\n\nexport function validateSchemaEvolution(\n previous: AnalyticsManifest,\n next: AnalyticsManifest,\n): void {\n const nextDatasets = new Map(\n next.datasets.map((dataset) => [dataset.identifier, dataset]),\n );\n for (const previousDataset of previous.datasets) {\n const nextDataset = nextDatasets.get(previousDataset.identifier);\n if (!nextDataset) {\n throw new Error(\n `Analytics dataset ${previousDataset.name} was removed. Supply an explicit analytics migration.`,\n );\n }\n const nextColumns = new Map(\n nextDataset.columns.map((column) => [column.name, column]),\n );\n for (const previousColumn of previousDataset.columns) {\n const nextColumn = nextColumns.get(previousColumn.name);\n if (!nextColumn) {\n throw new Error(\n `Analytics field ${previousDataset.name}.${previousColumn.sourceName} was removed or renamed. Supply an explicit analytics migration.`,\n );\n }\n if (nextColumn.type !== previousColumn.type) {\n throw new Error(\n `Analytics field ${previousDataset.name}.${previousColumn.sourceName} changed from ${previousColumn.type} to ${nextColumn.type}. Supply an explicit analytics migration.`,\n );\n }\n }\n }\n}\n\nexport function writeAnalyticsManifest(\n monoriseOutputDir: string,\n configs: AnalyticsConfig[],\n): void {\n const analyticsManifestPath = path.join(monoriseOutputDir, 'analytics-manifest.json');\n const manifest = createAnalyticsManifest(configs);\n if (manifest.unnamedMutuals.length) {\n console.warn(\n `Skipping unnamed mutual analytics datasets: ${manifest.unnamedMutuals.join(', ')}.`,\n );\n }\n if (fs.existsSync(analyticsManifestPath)) {\n validateSchemaEvolution(\n JSON.parse(fs.readFileSync(analyticsManifestPath, 'utf8')) as AnalyticsManifest,\n manifest,\n );\n }\n fs.writeFileSync(analyticsManifestPath, `${JSON.stringify(manifest, null, 2)}\\n`);\n}\n\nexport function createAnalyticsManifest(\n configs: AnalyticsConfig[],\n): AnalyticsManifest {\n const datasets: AnalyticsDataset[] = [];\n const unnamedMutuals = new Set<string>();\n const identifiers = new Map<string, string>();\n const mutuals = new Set<AnalyticsMutual>();\n const mutualPairs = new Map<string, string>();\n\n const addDataset = (\n kind: AnalyticsDataset['kind'],\n name: string,\n schema: ZodSchema,\n mutualEntities?: [string, string],\n ) => {\n if (!lowerKebabCase.test(name)) {\n throw new Error(\n `Invalid analytics ${kind} name: ${name}. Must be lower-kebab-case.`,\n );\n }\n const identifier = normalizeSqlIdentifier(name);\n const existing = identifiers.get(identifier);\n if (existing) {\n throw new Error(\n `Analytics dataset identifier collision: ${existing} and ${name} both normalize to ${identifier}.`,\n );\n }\n identifiers.set(identifier, name);\n const idColumn = `${identifier}_id`;\n const datasetEndpoints =\n kind === 'mutual' && mutualEntities ? endpoints(mutualEntities) : [];\n const datasetColumns = columns(schema, `${kind} ${name}`);\n const reservedNames = new Set([\n idColumn,\n ...datasetEndpoints.map((endpoint) => endpoint.column),\n 'event_id',\n 'idempotency_key',\n 'ordering_key',\n 'sequence_number',\n 'operation',\n 'occurred_at',\n 'before_json',\n 'after_json',\n ]);\n const collision = datasetColumns.find((column) =>\n reservedNames.has(column.name),\n );\n if (collision) {\n throw new Error(\n `Analytics field ${kind} ${name}.${collision.sourceName} conflicts with generated column ${collision.name}.`,\n );\n }\n datasets.push({\n kind,\n name,\n identifier,\n idColumn,\n endpoints: datasetEndpoints,\n currentTable: `${identifier}_${kind === 'entity' ? 'entities' : 'mutuals'}`,\n historyTable: `${identifier}_${kind === 'entity' ? 'entity_changes' : 'mutual_changes'}`,\n columns: datasetColumns,\n partition: { granularity: 'day' },\n });\n };\n\n for (const config of configs) {\n addDataset('entity', config.name, config.finalSchema);\n for (const field of Object.values(config.mutual?.mutualFields ?? {})) {\n const mutual = field.mutual;\n if (!mutual?.name) {\n unnamedMutuals.add(`${config.name}.${field.entityType}`);\n continue;\n }\n if (mutuals.has(mutual)) continue;\n mutuals.add(mutual);\n const entities: [string, string] = mutual.entities ?? [config.name, field.entityType];\n const pair = [...entities].sort().join('::');\n const existing = mutualPairs.get(pair);\n if (existing) {\n throw new Error(\n `Analytics mutual ${mutual.name} conflicts with ${existing}: both use the ${pair} entity pair.`,\n );\n }\n mutualPairs.set(pair, mutual.name);\n addDataset(\n 'mutual',\n mutual.name,\n mutual.mutualDataSchema,\n entities,\n );\n }\n }\n\n return {\n version: 2,\n datasets,\n unnamedMutuals: [...unnamedMutuals].sort(),\n schemaFingerprint: fingerprint(datasets),\n };\n}\n","import fs from 'node:fs';\nimport { createRequire } from 'node:module';\nimport path from 'node:path';\nimport { pathToFileURL } from 'node:url';\n\nconst require = createRequire(import.meta.url);\n\n// Set by `defineApiKeyPolicies` in @monorise/base. Reading the validator off\n// the policies object runs the same version of it the project's policies were\n// written against, without resolving @monorise/base from the project here.\nconst VALIDATE_API_KEY_POLICIES = Symbol.for('monorise.validateApiKeyPolicies');\n\n/**\n * Resolves `apiKeys` from monorise.config.ts to an absolute path, or\n * `undefined` when the project defines no policies.\n */\nexport function resolveApiKeysPath(\n projectRoot: string,\n apiKeys: string | undefined,\n configDir: string,\n): string | undefined {\n if (!apiKeys) return undefined;\n\n const absolutePath = path.resolve(projectRoot, apiKeys);\n if (\n !fs.existsSync(absolutePath) &&\n !fs.existsSync(`${absolutePath}.ts`) &&\n !fs.existsSync(`${absolutePath}.js`)\n ) {\n throw new Error(\n `API key policies file not found: '${absolutePath}'. Please ensure 'apiKeys' in monorise.config.ts points to a valid file.`,\n );\n }\n\n // Every file in configDir is loaded as an entity config, so a policy file\n // there would be read as an entity named 'undefined'.\n const fromConfigDir = path.relative(configDir, absolutePath);\n if (!fromConfigDir.startsWith('..') && !path.isAbsolute(fromConfigDir)) {\n throw new Error(\n `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'.`,\n );\n }\n return absolutePath;\n}\n\n/** The file `apiKeys` points at, with its extension: the one to watch. */\nexport function apiKeysFile(apiKeysPath: string): string {\n return (\n ['', '.ts', '.js']\n .map((extension) => `${apiKeysPath}${extension}`)\n .find((file) => fs.existsSync(file) && fs.statSync(file).isFile()) ??\n apiKeysPath\n );\n}\n\n// Imports a file as it is on disk now. `monorise dev` validates the policies\n// again after each edit, and both module caches would return the first version.\nconst importFresh = (file: string) => {\n delete require.cache[file];\n return import(`${pathToFileURL(file).href}?t=${Date.now()}`);\n};\n\n/**\n * Validates the project's policies against its entity configs. Runs after\n * config.ts is generated, because a policy file usually imports the generated\n * `Entity` enum.\n */\nexport async function validateApiKeyPoliciesFile(\n apiKeysPath: string,\n configOutputPath: string,\n): Promise<Record<string, unknown>> {\n const { default: generatedConfig } = await importFresh(configOutputPath);\n const { default: policies } = await importFresh(apiKeysFile(apiKeysPath));\n\n const validate = policies?.[VALIDATE_API_KEY_POLICIES];\n if (typeof validate !== 'function') {\n throw new Error(\n `API key policies file at '${apiKeysPath}' must default export the result of defineApiKeyPolicies(...).`,\n );\n }\n\n const errors: string[] = validate(generatedConfig.EntityConfig);\n if (errors.length) {\n throw new Error(\n `Invalid API key policies in '${apiKeysPath}':\\n - ${errors.join('\\n - ')}`,\n );\n }\n console.log('Validated API key policies.');\n return policies;\n}\n\n/**\n * Declares every custom route permission the policies grant, by augmenting\n * `ApiKeyRoutePermissions` in @monorise/base, so `requires()` only accepts\n * names some policy grants. Appended to config.ts.\n */\nexport function routePermissionDeclarations(\n policies: Record<string, unknown>,\n baseModuleNames: string[],\n): string {\n const permissions = new Set<string>();\n for (const policy of Object.values(policies)) {\n const routes = (policy as { routes?: unknown })?.routes;\n if (Array.isArray(routes)) {\n for (const permission of routes) permissions.add(permission);\n }\n }\n if (permissions.size === 0) return '';\n\n const members = [...permissions]\n .sort()\n .map((permission) => ` ${JSON.stringify(permission)}: true;`)\n .join('\\n');\n return baseModuleNames\n .map(\n (moduleName) => `\ndeclare module '${moduleName}' {\n interface ApiKeyRoutePermissions {\n${members}\n }\n}\n`,\n )\n .join('');\n}\n\n/**\n * The handle.ts import line for the policies, and the argument to pass to\n * `new CoreFactory(...)`. The policies are imported only by handle.ts, never\n * by config.ts, so a policy file can import the generated `Entity` enum\n * without a circular import.\n */\nexport function apiKeyPoliciesHandleParts(\n monoriseOutputDir: string,\n apiKeysPath: string | undefined,\n): { importLine: string; coreFactoryArg: string } {\n if (!apiKeysPath) return { importLine: '', coreFactoryArg: 'config' };\n\n const relativePath = path\n .relative(monoriseOutputDir, apiKeysPath)\n .replace(/\\.(ts|js|mjs|cjs)$/, '');\n const importPath = relativePath.startsWith('.')\n ? relativePath\n : `./${relativePath}`;\n\n return {\n importLine: `import apiKeyPolicies from '${importPath}';`,\n coreFactoryArg: '{ ...config, ApiKeyPolicies: apiKeyPolicies }',\n };\n}\n","type ApiKeyTypeEntity = {\n name: string;\n enumKey: string;\n config: {\n tags?: { name: string }[];\n mutual?: {\n mutualFields?: Record<\n string,\n {\n entityType: string;\n mutual?: { mutualDataSchema?: { shape?: Record<string, unknown> } };\n }\n >;\n };\n };\n};\n\nconst literalUnion = (names: string[]) =>\n names.length\n ? names.map((name) => JSON.stringify(name)).join(' | ')\n : 'never';\n\n/**\n * Declares each entity's tag names and each direction's mutualData field\n * names on @monorise/base's ApiKeyEntityTags and ApiKeyMutualDataFields, so a\n * policy's `tags` and relationship field lists are typed. The names are read\n * from the configs here, at build time. Goes inside the generated\n * `declare module` block for @monorise/base, where `Entity` is in scope.\n */\nexport function apiKeyTypeDeclarations(entities: ApiKeyTypeEntity[]): string {\n const enumKeys = new Map(\n entities.map((entity) => [entity.name, entity.enumKey]),\n );\n\n const tagEntries = entities.map(\n ({ enumKey, config }) =>\n `[Entity.${enumKey}]: ${literalUnion((config.tags ?? []).map((tag) => tag.name))};`,\n );\n\n // A pair's mutual config can be declared on either side and covers both\n // directions; each side's own declaration wins for its direction.\n const mutualFields = new Map<string, Map<string, string[]>>();\n const setDirection = (from: string, to: string, fields: string[]) => {\n const targets = mutualFields.get(from) ?? new Map<string, string[]>();\n if (!targets.has(to)) targets.set(to, fields);\n mutualFields.set(from, targets);\n };\n for (const pass of ['own', 'reverse'] as const) {\n for (const { name, config } of entities) {\n for (const field of Object.values(config.mutual?.mutualFields ?? {})) {\n const shape = field.mutual?.mutualDataSchema?.shape;\n if (!shape || !enumKeys.has(field.entityType)) continue;\n const fields = Object.keys(shape);\n if (pass === 'own') setDirection(name, field.entityType, fields);\n else setDirection(field.entityType, name, fields);\n }\n }\n }\n\n const mutualEntries = [...mutualFields].map(\n ([from, targets]) =>\n `[Entity.${enumKeys.get(from)}]: {\\n${[...targets]\n .map(\n ([to, fields]) =>\n ` [Entity.${enumKeys.get(to)}]: ${literalUnion(fields)};`,\n )\n .join('\\n')}\\n };`,\n );\n\n return `\n export interface ApiKeyEntityTags {\n ${tagEntries.join('\\n ')}\n }\n\n export interface ApiKeyMutualDataFields {\n ${mutualEntries.join('\\n ')}\n }`;\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\n\n/**\n * Detects whether the combined 'monorise' package is installed by walking up\n * the directory tree. This handles monorepo setups where dependencies are\n * hoisted to the root node_modules.\n */\nexport function detectCombinedPackage(startDir: string): boolean {\n let dir = startDir;\n while (true) {\n if (fs.existsSync(path.join(dir, 'node_modules', 'monorise'))) {\n return true;\n }\n const parent = path.dirname(dir);\n if (parent === dir) break; // reached filesystem root\n dir = parent;\n }\n return false;\n}\n","export const ROOT_TSCONFIG_TEMPLATE = {\n compilerOptions: {\n target: 'ES2022',\n module: 'ESNext',\n moduleResolution: 'bundler',\n esModuleInterop: true,\n strict: true,\n skipLibCheck: true,\n jsx: 'preserve',\n paths: {\n '#/shared/*': ['./shared/*'],\n '#/monorise/*': ['./.monorise/*'],\n '#/monorise': ['./.monorise/index'],\n },\n },\n include: ['**/*.ts', '.monorise/**/*.ts'],\n exclude: ['node_modules', 'apps'],\n};\n"],"mappings":";;;AAEA,OAAO;AACP,OAAOA,SAAQ;AACf,OAAOC,WAAU;AACjB,SAAS,gBAAuB;AAChC,OAAO,cAAc;;;ACNrB,SAAS,kBAAkB;AAC3B,OAAO,QAAQ;AACf,OAAO,UAAU;AAgEjB,IAAM,iBAAiB;AAEhB,SAAS,uBAAuB,MAAsB;AAC3D,QAAM,aAAa,KAChB,QAAQ,sBAAsB,OAAO,EACrC,QAAQ,kBAAkB,GAAG,EAC7B,QAAQ,YAAY,EAAE,EACtB,YAAY;AACf,SAAO,UAAU,KAAK,UAAU,IAAI,aAAa,IAAI,UAAU;AACjE;AAEA,SAAS,WAAW,QAAmBC,OAAuC;AAC5E,MAAI,UAAU;AACd,aAAS;AACP,UAAM,WAAW,QAAQ,MAAM;AAC/B,QAAI,aAAa,cAAc;AAG7B,UAAI,QAAQ,MAAM,QAAQ,SAAS,aAAc,QAAO;AACxD,UAAI,CAAC,QAAQ,KAAK,OAAQ,QAAO;AACjC,gBAAU,QAAQ,KAAK;AACvB;AAAA,IACF;AACA,QACE,aAAa,iBACb,aAAa,iBACb,aAAa,gBACb,aAAa,cACb,aAAa,eACb;AACA,UAAI,CAAC,QAAQ,MAAM,UAAW,QAAO;AACrC,gBAAU,QAAQ,KAAK;AACvB;AAAA,IACF;AACA,QAAI,aAAa,cAAc;AAC7B,UAAI,CAAC,QAAQ,MAAM,KAAM,QAAO;AAChC,gBAAU,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../commands/utils/analytics-manifest.ts","../commands/utils/api-key-policies.ts","../commands/utils/api-key-types.ts","../commands/utils/detect-package.ts","../templates/root-tsconfig.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport 'tsx';\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { execSync, spawn } from 'node:child_process';\nimport chokidar from 'chokidar';\nimport {\n writeAnalyticsManifest,\n type AnalyticsConfig,\n} from './commands/utils/analytics-manifest';\nimport { fileURLToPath } from 'node:url';\nimport {\n apiKeyPoliciesHandleParts,\n apiKeysFile,\n resolveApiKeysPath,\n routePermissionDeclarations,\n validateApiKeyPoliciesFile,\n} from './commands/utils/api-key-policies';\nimport { apiKeyTypeDeclarations } from './commands/utils/api-key-types';\nimport { detectCombinedPackage } from './commands/utils/detect-package';\nimport { ROOT_TSCONFIG_TEMPLATE } from './templates/root-tsconfig';\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = path.dirname(__filename);\nconst TEMPLATES_DIR = path.join(__dirname, 'templates', 'files');\n\nfunction readTemplate(filename: string): string {\n return fs.readFileSync(path.join(TEMPLATES_DIR, filename), 'utf-8');\n}\n\nfunction kebabToCamel(str: string): string {\n return str.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());\n}\n\nfunction kebabToPascal(kebab: string): string {\n return kebab\n .split('-')\n .map((word) => word.charAt(0).toUpperCase() + word.slice(1))\n .join('');\n}\n\nfunction execCommand(\n command: string,\n cwd?: string,\n stdio: 'inherit' | 'pipe' = 'inherit',\n): void {\n console.log(`Running: ${command}`);\n execSync(command, { cwd, stdio });\n}\n\nasync function generateConfigFile(\n configDir: string,\n monoriseOutputDir: string,\n projectRoot: string,\n): Promise<string> {\n const configOutputPath = path.join(monoriseOutputDir, 'config.ts');\n const initialConfigContent = `\nexport enum Entity {}\nexport default {};\n`;\n fs.writeFileSync(configOutputPath, initialConfigContent);\n fs.writeFileSync(\n path.join(monoriseOutputDir, 'index.ts'),\n `export * from './config';\\nexport { default } from './config';\\n`,\n );\n\n const files = fs\n .readdirSync(configDir)\n .filter((file) => file.endsWith('.ts') && file !== 'index.ts');\n\n const names = new Set<string>();\n const nameRegex = /^[a-z]+(-[a-z]+)*$/;\n const imports: string[] = [];\n\n const enumEntries: string[] = [];\n const typeEntries: string[] = [];\n const schemaMapEntries: string[] = [];\n const configEntries: string[] = [];\n const schemaEntries: string[] = [];\n const allowedEntityEntries: string[] = [];\n const entityWithEmailAuthEntries: string[] = [];\n const analyticsConfigs: AnalyticsConfig[] = [];\n const apiKeyTypeEntities: Parameters<typeof apiKeyTypeDeclarations>[0] =\n [];\n\n const relativePathToConfigDir = path.relative(monoriseOutputDir, configDir);\n const importPathPrefix = relativePathToConfigDir\n ? `${relativePathToConfigDir}/`\n : './';\n\n for (const file of files) {\n const fullPath = path.join(configDir, file);\n const module = await import(fullPath);\n const config = module.default;\n\n if (!nameRegex.test(config.name)) {\n throw new Error(\n `Invalid name format: ${config.name} in ${file}. Must be kebab-case.`,\n );\n }\n\n if (names.has(config.name)) {\n throw new Error(`Duplicate name found: ${config.name} in ${file}`);\n }\n names.add(config.name);\n analyticsConfigs.push(config as AnalyticsConfig);\n\n const fileName = file.replace(/\\.ts$/, '');\n const variableName = kebabToCamel(fileName);\n imports.push(\n `import ${variableName} from '${importPathPrefix}${fileName}';`,\n );\n\n const enumKey = config.name.toUpperCase().replace(/-/g, '_');\n enumEntries.push(`${enumKey} = '${config.name}'`);\n typeEntries.push(\n `export type ${kebabToPascal(config.name)}Type = z.infer<(typeof ${variableName})['finalSchema']>;`,\n );\n schemaMapEntries.push(\n `[Entity.${enumKey}]: ${kebabToPascal(config.name)}Type;`,\n );\n\n configEntries.push(`[Entity.${enumKey}]: ${kebabToCamel(config.name)},`);\n schemaEntries.push(\n `[Entity.${enumKey}]: ${kebabToCamel(config.name)}.finalSchema,`,\n );\n\n allowedEntityEntries.push(`Entity.${enumKey}`);\n apiKeyTypeEntities.push({ name: config.name, enumKey, config });\n\n if (config.authMethod?.email) {\n entityWithEmailAuthEntries.push(`Entity.${enumKey}`);\n }\n }\n\n // Detect whether the consumer uses the combined 'monorise' package or scoped '@monorise/*' packages\n const usesCombinedPackage = detectCombinedPackage(projectRoot);\n\n // Build module augmentation block\n const augmentationBlock = (moduleName: string) => `\ndeclare module '${moduleName}' {\n export enum Entity {\n ${enumEntries.join(',\\n ')}\n }\n\n ${typeEntries.join('\\n ')}\n\n export interface EntitySchemaMap {\n ${schemaMapEntries.join('\\n ')}\n }\n${apiKeyTypeDeclarations(apiKeyTypeEntities)}\n}`;\n\n // Augment the correct module based on which package is installed\n const moduleAugmentations = usesCombinedPackage\n ? augmentationBlock('monorise/base')\n : augmentationBlock('@monorise/base');\n\n const configOutputContent = `\nimport type { z } from 'zod';\n${imports.join('\\n')}\n\nexport enum Entity {\n ${enumEntries.join(',\\n ')}\n}\n\n${typeEntries.join('\\n')}\n\nexport interface EntitySchemaMap {\n ${schemaMapEntries.join('\\n ')}\n}\n\nconst EntityConfig = {\n ${configEntries.join('\\n ')}\n};\n\nconst FormSchema = {\n ${schemaEntries.join('\\n ')}\n};\n\nconst AllowedEntityTypes = [\n ${allowedEntityEntries.join(',\\n ')}\n];\n\nconst EmailAuthEnabledEntities: Entity[] = [${entityWithEmailAuthEntries.join(', ')}];\n\nexport {\n EntityConfig,\n FormSchema,\n AllowedEntityTypes,\n EmailAuthEnabledEntities,\n};\n\nconst config = {\n EntityConfig,\n FormSchema,\n AllowedEntityTypes,\n EmailAuthEnabledEntities,\n};\n\nexport default config;\n${moduleAugmentations}\n`;\n\n fs.writeFileSync(configOutputPath, configOutputContent);\n writeAnalyticsManifest(monoriseOutputDir, analyticsConfigs);\n console.log('Successfully generated config.ts!');\n\n // Also generate index.ts re-exporting everything from config.ts, so consumers\n // can import from '#/monorise' directly instead of '#/monorise/config'.\n // config.ts keeps being generated for backward compatibility.\n const indexOutputPath = path.join(monoriseOutputDir, 'index.ts');\n fs.writeFileSync(\n indexOutputPath,\n `export * from './config';\\nexport { default } from './config';\\n`,\n );\n console.log('Successfully generated index.ts!');\n\n return configOutputPath;\n}\n\nasync function generateHandleFile(\n monoriseConfig: { customRoutes?: string; configDir: string },\n projectRoot: string,\n monoriseOutputDir: string,\n apiKeysPath?: string,\n): Promise<string> {\n const handleOutputPath = path.join(monoriseOutputDir, 'handle.ts');\n const customRoutesPath = monoriseConfig.customRoutes;\n\n let routesImportLine = '';\n let appHandlerPayload = '{}'; // Default to an empty object for appHandler if no custom routes\n\n if (customRoutesPath) {\n const absoluteCustomRoutesPath = path.resolve(\n projectRoot,\n customRoutesPath,\n );\n\n if (\n !fs.existsSync(absoluteCustomRoutesPath) &&\n !fs.existsSync(`${absoluteCustomRoutesPath}.ts`) &&\n !fs.existsSync(`${absoluteCustomRoutesPath}.js`)\n ) {\n throw new Error(\n `Custom routes file not found: '${absoluteCustomRoutesPath}'. Please ensure 'customRoutes' in monorise.config.ts points to a valid file.`,\n );\n }\n\n let relativePathToRoutes = path.relative(\n monoriseOutputDir,\n absoluteCustomRoutesPath,\n );\n relativePathToRoutes = relativePathToRoutes.replace(\n /\\.(ts|js|mjs|cjs)$/,\n '',\n );\n\n // If custom routes are provided, include the import statement and pass 'routes' to appHandler\n routesImportLine = `import routes from '${relativePathToRoutes}';`;\n appHandlerPayload = '{ routes }';\n }\n // If customRoutesPath is not provided, routesImportLine remains empty and appHandlerPayload remains `{}`\n\n // Detect whether the consumer uses the combined 'monorise' package or scoped '@monorise/*' packages\n const usesCombinedPackage = detectCombinedPackage(projectRoot);\n const coreImportPath = usesCombinedPackage ? 'monorise/core' : '@monorise/core';\n const apiKeyPolicies = apiKeyPoliciesHandleParts(\n monoriseOutputDir,\n apiKeysPath,\n );\n\n const combinedContent = `\nimport CoreFactory, { analyticsMaterializationProcessor, analyticsModelProcessor, analyticsQueryHandler as createAnalyticsQueryHandler, analyticsViewProcessor } from '${coreImportPath}';\nimport config from './config';\nimport analyticsManifest from './analytics-manifest.json';\n${routesImportLine ? `${routesImportLine}\\n` : ''}${apiKeyPolicies.importLine ? `${apiKeyPolicies.importLine}\\n` : ''}const coreFactory = new CoreFactory(${apiKeyPolicies.coreFactoryArg});\n\nexport const replicationHandler = coreFactory.replicationProcessor;\nexport const analyticsHandler = coreFactory.analyticsProcessor;\nexport const analyticsBackfillHandler = coreFactory.analyticsBackfillProcessor;\nexport const analyticsMaterializationHandler = analyticsMaterializationProcessor(analyticsManifest);\nexport const analyticsQueryHandler = createAnalyticsQueryHandler();\nexport const analyticsModelHandler = analyticsModelProcessor;\nexport const analyticsViewHandler = analyticsViewProcessor;\nexport const mutualHandler = coreFactory.mutualProcessor;\nexport const tagHandler = coreFactory.tagProcessor;\nexport const treeHandler = coreFactory.prejoinProcessor;\nexport const appHandler = coreFactory.appHandler(${appHandlerPayload});\n\n// WebSocket handlers (wrapped with DependencyContainer for SST to resolve)\nexport const wsConnect = coreFactory.wsConnect;\nexport const wsDisconnect = coreFactory.wsDisconnect;\nexport const wsDefault = coreFactory.wsDefault;\nexport const wsBroadcast = coreFactory.wsBroadcast;\n`;\n fs.writeFileSync(handleOutputPath, combinedContent);\n console.log('Successfully generated handle.ts!');\n\n return handleOutputPath;\n}\n\n// What `monorise dev` watches: the entity configs, and the policy file,\n// which lives outside them.\ntype GeneratedFrom = { configDir: string; apiKeysFile?: string };\n\nasync function generateFiles(rootPath?: string): Promise<GeneratedFrom> {\n const baseDir = rootPath ? path.resolve(rootPath) : process.cwd();\n const configFilePathTS = path.join(baseDir, 'monorise.config.ts');\n const configFilePathJS = path.join(baseDir, 'monorise.config.js');\n\n let configFilePath: string;\n if (fs.existsSync(configFilePathTS)) {\n configFilePath = configFilePathTS;\n } else if (fs.existsSync(configFilePathJS)) {\n configFilePath = configFilePathJS;\n } else {\n throw new Error(\n 'Neither monorise.config.ts nor monorise.config.js found in the root of the project.',\n );\n }\n\n const projectRoot = path.dirname(configFilePath);\n const monoriseConfigModule = await import(configFilePath);\n const monoriseConfig = monoriseConfigModule.default;\n\n const configDir = path.resolve(projectRoot, monoriseConfig.configDir);\n const monoriseOutputDir = path.join(projectRoot, '.monorise');\n\n fs.mkdirSync(monoriseOutputDir, { recursive: true });\n\n // Resolved first, so a misplaced policy file fails before it is loaded as\n // an entity config.\n const apiKeysPath = resolveApiKeysPath(\n projectRoot,\n monoriseConfig.apiKeys,\n configDir,\n );\n const configOutputPath = await generateConfigFile(\n configDir,\n monoriseOutputDir,\n projectRoot,\n );\n if (apiKeysPath) {\n const policies = await validateApiKeyPoliciesFile(\n apiKeysPath,\n configOutputPath,\n );\n fs.appendFileSync(\n configOutputPath,\n routePermissionDeclarations(policies, [\n detectCombinedPackage(projectRoot) ? 'monorise/base' : '@monorise/base',\n ]),\n );\n }\n await generateHandleFile(\n monoriseConfig,\n projectRoot,\n monoriseOutputDir,\n apiKeysPath,\n );\n\n return {\n configDir,\n apiKeysFile: apiKeysPath && apiKeysFile(apiKeysPath),\n };\n}\n\nconst MONORISE_LOGO = `\n\n\n\n ░░░░░░░\n ░░▒▒▒░░░░░░▒▒▒░\n ░▒▒░ ░▒▒░\n ░▒▒░ ░▒▒░\n ░▒░ ░▒▒░\n ░▒▒░ ▒▒▒░\n ░▒░░░▒░ ░▒░░▒▒░\n ░▒▒░ ░▒▒▒░ ░▒▒░ ░▒░░\n ░▒▒ ░▒▒░ ░▒▒░ ░▒░ ░▒░ ░▒░\n ░▒▒░ ░▒░ ░▒░░▒▒░░░ ░░▒▒░░▒░ ░▒▒ ░▒░\n ░░▒░ ░▒░ ░▒░ ░▒▒░░▒▒▒▒▒▒░░▒░ ░▒░░ ░▒░ ░▒░\n ░▒░ ░░▒░ ░▒░ ░░░ ░▒░ ░░ ░▒░ ░▒░ ░▒░░ ░░▒░\n ░▒░ ░▒░ ░▒░ ░▒ ░░ ░▒░ ░▒░ ░▒░ ░▒░ ░░░░\n ░░░ ░░░░ ░░░ ░░ ▒░ ░░░ ░░░ ░░░ ░░░ ░░░░\n ░░░ ░░░░ ░░░ ░░░ ░░░ ░░ ░░░ ░░░ ░░░ ░░░░\n ░░░ ░░░ ░░░ ░░░ ░░ ░░ ░░░ ░░░ ░░░ ░░░\n ░░░ ░░░░ ░░░ ░░░ ░░ ░░░ ░░ ░░░ ░░░ ░░░\n ░░ ░░░ ░░░ ░░░ ░░░ ░░ ░░░ ░░░ ░░░ ░░░\n ░░ ░░ ░░ ░░ ░░ ░░░ ░░░ ░░░ ░░░░ ░░░\n ░░░ ░░ ░░░ ░░░ ░░░\n ░░░░░▒░░░░░░░░░▒░░░░░░░░░ ░ ░░ ░░░ ░░░ ░░\n ░░░ ░░░░░░░░░ ░░░ ░░░\n ░░░ ░░░░░░ ░░ ░░░░░▒░░░░░░▒░░░░\n ░░░░░░░░░░░░░░░░░ ░░░░░ ░░░░░░░░ ░░\n ░░░░░░░ ░░░░░░░░░░░░░░ ░░░░ ░░░░░ ░▒░\n ░░░ ░░░░░░░ ░░░░░░ ░░░░░░░░\n ░░░░░░░░░░░░ ░░░░░░ ░░░░ ░░░░░░░░░░░░░\n ░▒▒░░░░░░░░░░░▒▒░░ ░░▒▒▒░░ ░▒▒░░ ░░░░\n ░▒░ ░░▒▒░ ░▒░ ░▒▒░ ░░▒░\n ░▒░ ░░░░▒▒▒▒▒▒▒▒▒▒░░ ░▒░ ▒▒░ ░░▒▒▒░\n ░▒▒▒▒▒░░░ ░░░▒▒▒▒▒░ ▒▒░ ░▒▒▒▒▒▒░\n ░▒▒░ ░▒▒▒▒ ▒▒▒ ▒▒▒\n ░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░░ ░▒▒▒▒▒░ ░▒▒\n ▒▒▒ ░░▒▒▒▒▒▒░ ▒▒▒ ░▒▒\n ▒▒▒ ░▒▒▒▒ ░▒▒▒░\n ▒▓▓▓▒▒▒▓▓▒▒▒░ ▒▒▒░░▒▒░\n ▒▓░ ░▒▒▓▓▒░ ▒▓▓░\n ░▒▓░ ░▒▓▒░▒▓▒\n ░▒▓▒░ ░▒▓▓▒\n ░▒▒▓▓▓▓▓▓▒▒░\n\n\n\n`;\n\nasync function runInitCommand(rootPath?: string) {\n console.log(MONORISE_LOGO);\n\n // Determine project name and root\n let projectName = 'my-app';\n let projectRoot: string;\n\n if (rootPath) {\n projectRoot = path.resolve(rootPath);\n projectName = path.basename(projectRoot);\n } else {\n // Prompt for project name (simple approach for now)\n const args = process.argv.slice(2);\n const nameIndex = args.indexOf('--name');\n if (nameIndex > -1 && args[nameIndex + 1]) {\n projectName = args[nameIndex + 1];\n }\n projectRoot = path.resolve(projectName);\n }\n\n console.log(`\\n🚀 Creating Monorise project: ${projectName}\\n`);\n\n // Check if directory exists\n if (fs.existsSync(projectRoot)) {\n console.error(`Error: Directory ${projectName} already exists.`);\n process.exit(1);\n }\n\n // Step 1: Create project directory structure\n console.log('📁 Creating project structure...');\n fs.mkdirSync(projectRoot, { recursive: true });\n fs.mkdirSync(path.join(projectRoot, 'apps'), { recursive: true });\n fs.mkdirSync(path.join(projectRoot, 'services', 'core'), { recursive: true });\n fs.mkdirSync(path.join(projectRoot, 'monorise', 'configs'), { recursive: true });\n fs.mkdirSync(path.join(projectRoot, 'monorise', 'mutuals'), { recursive: true });\n\n // Step 2: Create root package.json\n console.log('📦 Initializing root package.json...');\n const rootPackageJson = {\n name: projectName,\n version: '0.0.0',\n type: 'module',\n private: true,\n workspaces: ['apps/*', 'services/*'],\n };\n fs.writeFileSync(\n path.join(projectRoot, 'package.json'),\n JSON.stringify(rootPackageJson, null, 2),\n );\n\n // Step 3: Create root tsconfig.json\n console.log('⚙️ Creating root tsconfig.json...');\n fs.writeFileSync(\n path.join(projectRoot, 'tsconfig.json'),\n JSON.stringify(ROOT_TSCONFIG_TEMPLATE, null, 2),\n );\n\n // Step 4: Create Next.js app in apps/web\n console.log('\\n📱 Creating Next.js app in apps/web...');\n const nextAppDir = path.join(projectRoot, 'apps', 'web');\n try {\n execCommand(\n `npx create-next-app@latest web --typescript --tailwind --eslint --app --no-src-dir --import-alias \"#/*\" --no-turbopack --yes`,\n path.join(projectRoot, 'apps'),\n );\n } catch (error) {\n console.error('Failed to create Next.js app:', error);\n process.exit(1);\n }\n\n // Step 5: Install SST v4\n console.log('\\n☁️ Installing SST v4...');\n try {\n execCommand('npm install sst@^4 --save-dev', projectRoot);\n } catch (error) {\n console.error('Failed to install SST:', error);\n process.exit(1);\n }\n\n // Step 6: Install dependencies\n console.log('\\n📦 Installing dependencies (monorise, hono, zod, shadcn utilities)...');\n try {\n execCommand('npm install monorise hono zod clsx class-variance-authority radix-ui lucide-react tailwind-merge react-hook-form @hookform/resolvers', projectRoot);\n } catch (error) {\n console.error('Failed to install dependencies:', error);\n process.exit(1);\n }\n\n // Step 7: Create monorise.config.ts, and the API key policies it points to\n console.log('⚙️ Creating monorise.config.ts...');\n fs.writeFileSync(\n path.join(projectRoot, 'monorise.config.ts'),\n readTemplate('monorise.config.ts'),\n );\n fs.writeFileSync(\n path.join(projectRoot, 'monorise', 'api-keys.ts'),\n readTemplate('api-keys.ts'),\n );\n\n // Step 8: Create shared mutual config (referenced by both User and Team)\n console.log('🔗 Creating team-membership mutual config...');\n fs.writeFileSync(\n path.join(projectRoot, 'monorise', 'mutuals', 'team-membership.ts'),\n readTemplate('team-membership.mutual.ts'),\n );\n\n // Step 9: Create starter entities (User <-> Team mutual relationship)\n console.log('👤 Creating starter User entity...');\n fs.writeFileSync(\n path.join(projectRoot, 'monorise', 'configs', 'user.ts'),\n readTemplate('user-entity.ts'),\n );\n console.log('👥 Creating starter Team entity...');\n fs.writeFileSync(\n path.join(projectRoot, 'monorise', 'configs', 'team.ts'),\n readTemplate('team-entity.ts'),\n );\n\n // Step 10: Create services/core/routes.ts\n console.log('🔧 Creating services/core/routes.ts...');\n fs.writeFileSync(\n path.join(projectRoot, 'services', 'core', 'routes.ts'),\n readTemplate('core-routes.ts'),\n );\n\n // Step 11: Create services package.json\n const servicesPackageJson = {\n name: '@my-app/services',\n version: '0.0.0',\n type: 'module',\n };\n fs.writeFileSync(\n path.join(projectRoot, 'services', 'core', 'package.json'),\n JSON.stringify(servicesPackageJson, null, 2),\n );\n\n // Step 12: Create sst.config.ts with monorise\n console.log('⚙️ Creating sst.config.ts with Monorise...');\n const sstConfigPath = path.join(projectRoot, 'sst.config.ts');\n fs.writeFileSync(sstConfigPath, readTemplate('sst.config.ts').replace('{{PROJECT_NAME}}', projectName));\n\n // Step 13: Install SST providers (after sst.config.ts exists)\n console.log('\\n☁️ Installing SST providers...');\n try {\n execCommand('npx sst install', projectRoot);\n } catch (error) {\n console.warn('Warning: SST install failed, continuing anyway...');\n }\n\n // Step 14: Create example page in apps/web\n console.log('📄 Creating example page in apps/web...');\n const webSrcAppDir = path.join(projectRoot, 'apps', 'web', 'src', 'app');\n const webAppDir = path.join(projectRoot, 'apps', 'web', 'app');\n const pagePath = fs.existsSync(webSrcAppDir)\n ? path.join(webSrcAppDir, 'page.tsx')\n : fs.existsSync(webAppDir)\n ? path.join(webAppDir, 'page.tsx')\n : null;\n\n if (pagePath) {\n try {\n fs.writeFileSync(pagePath, readTemplate('example-page.tsx'));\n console.log(`Created example page at ${path.relative(projectRoot, pagePath)}`);\n } catch (error) {\n console.warn('Warning: Could not create example page:', error);\n }\n } else {\n console.warn('Warning: Could not find apps/web/src/app or apps/web/app directory');\n }\n\n // Step 15: Create global components, lib/utils, UI components, and globals.css\n const webRoot = fs.existsSync(webSrcAppDir)\n ? path.join(projectRoot, 'apps', 'web', 'src')\n : fs.existsSync(webAppDir)\n ? path.join(projectRoot, 'apps', 'web')\n : null;\n\n if (webRoot) {\n const appDir = fs.existsSync(webSrcAppDir) ? webSrcAppDir : webAppDir;\n\n // Create directories\n fs.mkdirSync(path.join(webRoot, 'components', 'ui'), { recursive: true });\n fs.mkdirSync(path.join(webRoot, 'lib'), { recursive: true });\n\n // Global components\n console.log('🌐 Creating global components...');\n fs.writeFileSync(\n path.join(webRoot, 'components', 'global-initializer.tsx'),\n readTemplate('global-initializer.tsx'),\n );\n fs.writeFileSync(\n path.join(webRoot, 'components', 'global-loader.tsx'),\n readTemplate('global-loader.tsx'),\n );\n\n // lib/utils.ts\n console.log('🔧 Creating lib/utils.ts...');\n fs.writeFileSync(\n path.join(webRoot, 'lib', 'utils.ts'),\n readTemplate('lib-utils.ts'),\n );\n\n // Shadcn UI components\n console.log('🎨 Creating shadcn UI components...');\n fs.writeFileSync(\n path.join(webRoot, 'components', 'ui', 'button.tsx'),\n readTemplate('ui-button.tsx'),\n );\n fs.writeFileSync(\n path.join(webRoot, 'components', 'ui', 'card.tsx'),\n readTemplate('ui-card.tsx'),\n );\n fs.writeFileSync(\n path.join(webRoot, 'components', 'ui', 'input.tsx'),\n readTemplate('ui-input.tsx'),\n );\n fs.writeFileSync(\n path.join(webRoot, 'components', 'ui', 'label.tsx'),\n readTemplate('ui-label.tsx'),\n );\n\n // Replace globals.css with shadcn theme\n console.log('🎨 Setting up shadcn globals.css...');\n const globalsCssPath = path.join(appDir, 'globals.css');\n fs.writeFileSync(globalsCssPath, readTemplate('globals.css'));\n\n // Update layout.tsx with GlobalInitializer, GlobalLoader, and loader-portal\n console.log('📐 Updating layout.tsx with global components...');\n const layoutPath = path.join(appDir, 'layout.tsx');\n if (fs.existsSync(layoutPath)) {\n try {\n let layoutContent = fs.readFileSync(layoutPath, 'utf8');\n\n // Add imports after existing imports\n const globalImports = `import GlobalInitializer from '#/components/global-initializer';\\nimport GlobalLoader from '#/components/global-loader';`;\n // Insert after the last import statement\n const lastImportIndex = layoutContent.lastIndexOf('import ');\n const lineEnd = layoutContent.indexOf('\\n', lastImportIndex);\n layoutContent =\n layoutContent.slice(0, lineEnd + 1) +\n globalImports +\n '\\n' +\n layoutContent.slice(lineEnd + 1);\n\n // Add loader-portal div and global components inside <body>\n layoutContent = layoutContent.replace(\n /(<body[^>]*>)/,\n `$1\\n <div id=\"loader-portal\" />\\n <GlobalInitializer />\\n <GlobalLoader />`,\n );\n\n fs.writeFileSync(layoutPath, layoutContent);\n } catch (error) {\n console.warn('Warning: Could not update layout.tsx:', error);\n }\n }\n\n // Replace postcss.config.mjs with @tailwindcss/postcss\n const postcssPath = path.join(projectRoot, 'apps', 'web', 'postcss.config.mjs');\n if (fs.existsSync(postcssPath)) {\n fs.writeFileSync(\n postcssPath,\n `const config = {\\n plugins: {\\n '@tailwindcss/postcss': {},\\n },\\n};\\n\\nexport default config;\\n`,\n );\n }\n\n // Create the API proxy route, and the WebSocket ticket route the proxy\n // leaves to its own route\n console.log('🔀 Creating API proxy routes...');\n const coreApiDir = path.join(appDir, 'api', 'core');\n const proxyDir = path.join(coreApiDir, '[...path]');\n const ticketDir = path.join(\n coreApiDir,\n 'ws',\n 'ticket',\n '[entityType]',\n '[entityId]',\n );\n fs.mkdirSync(proxyDir, { recursive: true });\n fs.mkdirSync(ticketDir, { recursive: true });\n fs.writeFileSync(\n path.join(proxyDir, 'route.ts'),\n readTemplate('proxy-route.ts'),\n );\n fs.writeFileSync(\n path.join(ticketDir, 'route.ts'),\n readTemplate('ws-ticket-route.ts'),\n );\n }\n\n // Step 16: Update apps/web tsconfig.json with monorise path alias\n console.log('⚙️ Updating apps/web tsconfig.json...');\n const webTsconfigPath = path.join(projectRoot, 'apps', 'web', 'tsconfig.json');\n if (fs.existsSync(webTsconfigPath)) {\n try {\n const webTsconfigContent = fs.readFileSync(webTsconfigPath, 'utf8');\n const webTsconfig = JSON.parse(webTsconfigContent);\n\n if (!webTsconfig.compilerOptions) {\n webTsconfig.compilerOptions = {};\n }\n if (!webTsconfig.compilerOptions.paths) {\n webTsconfig.compilerOptions.paths = {};\n }\n\n // Add path aliases\n webTsconfig.compilerOptions.paths['#/shared/*'] = ['../../shared/*'];\n webTsconfig.compilerOptions.paths['#/monorise/*'] = ['../../.monorise/*'];\n // Exact-match alias so `import { Entity } from '#/monorise'` resolves to\n // the generated index.ts (re-exports config.ts, kept for backward compat).\n webTsconfig.compilerOptions.paths['#/monorise'] = ['../../.monorise/index'];\n const hasSrcDir = fs.existsSync(path.join(projectRoot, 'apps', 'web', 'src'));\n webTsconfig.compilerOptions.paths['#/*'] = [hasSrcDir ? './src/*' : './*'];\n\n fs.writeFileSync(webTsconfigPath, JSON.stringify(webTsconfig, null, 2));\n } catch (error) {\n console.warn('Warning: Could not update apps/web tsconfig.json:', error);\n }\n }\n\n // Step 16: Run initial monorise build to generate .monorise files\n console.log('\\n🔨 Running initial Monorise build...');\n try {\n execCommand('npx monorise build', projectRoot);\n } catch (error) {\n console.warn('Warning: Initial monorise build failed. You can run it manually later.');\n }\n\n console.log('\\n' + '='.repeat(60));\n console.log('✅ Monorise project created successfully!');\n console.log('='.repeat(60));\n console.log(`\\n📁 Project structure:`);\n console.log(` ${projectName}/`);\n console.log(` ├── apps/web/ # Next.js frontend`);\n console.log(` ├── services/core/ # Backend routes (Hono)`);\n console.log(` ├── monorise/configs/ # Entity definitions (User, Team)`);\n console.log(` ├── monorise/mutuals/ # Shared mutual relationship configs`);\n console.log(` └── .monorise/ # Generated files`);\n console.log(`\\n📂 Where to start coding:`);\n console.log(` • Edit your data model → monorise/configs/user.ts`);\n console.log(` (Add fields like phone, role, status to the User entity)`);\n console.log(\n ` • Build your UI → ${pagePath ? path.relative(projectRoot, pagePath) : 'apps/web/app/page.tsx'}`,\n );\n console.log(` (React components using useEntities and createEntity)`);\n console.log(` • Add backend logic → services/core/routes.ts`);\n console.log(` (Custom API endpoints with Hono)`);\n console.log(` • See the User <-> Team relationship → monorise/mutuals/team-membership.ts`);\n console.log(` (createMutualConfig — shared schema, referenced from both entity configs)`);\n console.log(`\\n🚀 Next steps:`);\n console.log(` cd ${projectName}`);\n console.log(` npx sst dev`);\n console.log('\\n📚 Documentation: https://monorise.dev');\n console.log('');\n}\n\nasync function runDevCommand(\n { configDir, apiKeysFile }: GeneratedFrom,\n rootPath?: string,\n) {\n console.log(MONORISE_LOGO);\n console.log(\n `Watching for changes in ${apiKeysFile ? `${configDir} and ${apiKeysFile}` : configDir}...`,\n );\n const watched = apiKeysFile ? [configDir, apiKeysFile] : configDir;\n const watcher = chokidar.watch(watched, {\n ignored: (watchedPath: string) => {\n const fileName = path.basename(watchedPath);\n return (\n fileName === 'index.ts' || // Old name, still ignore in case it exists\n fileName === 'config.ts' || // Generated config file\n fileName === 'processors.ts' || // Generated processors file\n fileName === 'app.ts' || // Generated app file\n fileName.startsWith('.') ||\n watchedPath.endsWith('.js') ||\n watchedPath.endsWith('.jsx') ||\n watchedPath.endsWith('.d.ts')\n );\n },\n persistent: true,\n ignoreInitial: true,\n });\n\n watcher.on('add', async (filePath) => {\n console.log(`File ${filePath} has been added. Regenerating...`);\n try {\n await generateFiles(rootPath);\n } catch (err) {\n console.error('Regeneration failed:', err);\n }\n });\n\n watcher.on('change', async (filePath) => {\n console.log(`File ${filePath} has been changed. Regenerating...`);\n try {\n await generateFiles(rootPath);\n } catch (err) {\n console.error('Regeneration failed:', err);\n }\n });\n\n watcher.on('unlink', async (filePath) => {\n console.log(`File ${filePath} has been removed. Regenerating...`);\n try {\n await generateFiles(rootPath);\n } catch (err) {\n console.error('Regeneration failed:', err);\n }\n });\n\n process.on('SIGINT', () => {\n console.log('Monorise dev terminated. Closing watcher and sst dev...');\n watcher.close();\n process.exit(0);\n });\n process.on('SIGTERM', () => {\n console.log('Monorise dev terminated. Closing watcher and sst dev...');\n watcher.close();\n process.exit(0);\n });\n}\n\nasync function runBuildCommand(rootPath?: string) {\n console.log('Starting sst build...');\n await generateFiles(rootPath);\n}\n\nasync function main() {\n const args = process.argv.slice(2);\n const command = args[0];\n\n let rootPath: string | undefined;\n const rootFlagIndex = args.indexOf('--config-root');\n if (rootFlagIndex > -1 && args[rootFlagIndex + 1]) {\n rootPath = args[rootFlagIndex + 1];\n }\n\n try {\n if (command === 'dev') {\n await runDevCommand(await generateFiles(rootPath), rootPath);\n } else if (command === 'build') {\n await runBuildCommand(rootPath);\n } else if (command === 'init') {\n // init is greenfield-only — it always creates a fresh directory named via\n // --name, never an existing path. --config-root doesn't apply here.\n await runInitCommand();\n } else {\n console.error(\n 'Unknown command. Usage:\\n' +\n ' monorise dev [--config-root <path>]\\n' +\n ' monorise build [--config-root <path>]\\n' +\n ' monorise init [--name <project-name>]',\n );\n process.exit(1);\n }\n } catch (err) {\n console.error('Monorise process failed:', err);\n process.exit(1);\n }\n}\n\nmain().catch((err) => {\n console.error('Monorise encountered an unhandled error:', err);\n process.exit(1);\n});\n","import { createHash } from 'node:crypto';\nimport fs from 'node:fs';\nimport path from 'node:path';\n\ntype ZodSchema = {\n _def?: {\n typeName?: string;\n innerType?: ZodSchema;\n schema?: ZodSchema;\n type?: ZodSchema;\n effect?: { type?: string };\n values?: Record<string, unknown>;\n value?: unknown;\n checks?: { kind?: string }[];\n };\n shape?: Record<string, ZodSchema>;\n};\n\nexport type AnalyticsColumn = {\n name: string;\n sourceName: string;\n type: 'boolean' | 'double' | 'string' | 'timestamp' | 'json';\n};\n\nexport type AnalyticsDataset = {\n kind: 'entity' | 'mutual';\n name: string;\n identifier: string;\n idColumn: string;\n endpoints: AnalyticsEndpoint[];\n currentTable: string;\n historyTable: string;\n columns: AnalyticsColumn[];\n partition: { granularity: 'day' };\n};\n\nexport type AnalyticsEndpoint = {\n entityName: string;\n column: string;\n role?: 'source' | 'target';\n};\n\nexport type AnalyticsManifest = {\n version: 2;\n datasets: AnalyticsDataset[];\n unnamedMutuals: string[];\n schemaFingerprint: string;\n};\n\nexport type AnalyticsConfig = {\n name: string;\n finalSchema: ZodSchema;\n mutual?: {\n mutualFields?: Record<\n string,\n { entityType: string; mutual?: AnalyticsMutual }\n >;\n };\n};\n\ntype AnalyticsMutual = {\n name?: string;\n entities?: [string, string];\n mutualDataSchema: ZodSchema;\n};\n\nconst lowerKebabCase = /^[a-z]+(?:-[a-z]+)*$/;\n\nexport function normalizeSqlIdentifier(name: string): string {\n const normalized = name\n .replace(/([a-z0-9])([A-Z])/g, '$1_$2')\n .replace(/[^a-zA-Z0-9]+/g, '_')\n .replace(/^_+|_+$/g, '')\n .toLowerCase();\n return /^[a-z_]/.test(normalized) ? normalized : `_${normalized}`;\n}\n\nfunction athenaType(schema: ZodSchema, path: string): AnalyticsColumn['type'] {\n let current = schema;\n for (;;) {\n const typeName = current._def?.typeName;\n if (typeName === 'ZodEffects') {\n // Refinements do not change the persisted shape. Transforms can, so retain\n // their value as JSON instead of inferring an incorrect scalar type.\n if (current._def?.effect?.type !== 'refinement') return 'json';\n if (!current._def.schema) return 'json';\n current = current._def.schema;\n continue;\n }\n if (\n typeName === 'ZodOptional' ||\n typeName === 'ZodNullable' ||\n typeName === 'ZodDefault' ||\n typeName === 'ZodCatch' ||\n typeName === 'ZodReadonly'\n ) {\n if (!current._def?.innerType) return 'json';\n current = current._def.innerType;\n continue;\n }\n if (typeName === 'ZodBranded') {\n if (!current._def?.type) return 'json';\n current = current._def.type;\n continue;\n }\n break;\n }\n\n switch (current._def?.typeName) {\n case 'ZodString':\n return current._def.checks?.some((check) => check.kind === 'datetime')\n ? 'timestamp'\n : 'string';\n case 'ZodNumber':\n return 'double';\n case 'ZodBoolean':\n return 'boolean';\n case 'ZodDate':\n return 'timestamp';\n case 'ZodEnum':\n return 'string';\n case 'ZodNativeEnum': {\n const values = current._def.values ?? {};\n const validValues = Object.keys(values)\n .filter((key) => typeof values[String(values[key])] !== 'number')\n .map((key) => values[key]);\n if (validValues.every((value) => typeof value === 'string')) return 'string';\n if (validValues.every((value) => typeof value === 'number')) return 'double';\n return 'json';\n }\n case 'ZodLiteral':\n return typeof current._def.value === 'string'\n ? 'string'\n : typeof current._def.value === 'number'\n ? 'double'\n : typeof current._def.value === 'boolean'\n ? 'boolean'\n : 'json';\n case 'ZodArray':\n case 'ZodObject':\n return 'json';\n default:\n // Keep every valid Zod field queryable without assigning an unsafe type.\n return 'json';\n }\n}\n\nfunction columns(schema: ZodSchema, path: string): AnalyticsColumn[] {\n let objectSchema = schema;\n // Entity effects commonly add superRefine validation around the final object.\n while (!objectSchema.shape && objectSchema._def?.typeName === 'ZodEffects') {\n const innerSchema = objectSchema._def.schema;\n if (!innerSchema) break;\n objectSchema = innerSchema;\n }\n if (!objectSchema.shape) return [];\n\n const names = new Map<string, string>();\n return Object.entries(objectSchema.shape).map(([sourceName, field]) => {\n const name = normalizeSqlIdentifier(sourceName);\n const existing = names.get(name);\n if (existing) {\n throw new Error(\n `Analytics column identifier collision in ${path}: ${existing} and ${sourceName} both normalize to ${name}.`,\n );\n }\n names.set(name, sourceName);\n return {\n name,\n sourceName,\n type: athenaType(field, `${path}.${sourceName}`),\n };\n });\n}\n\nfunction endpoints(entities: [string, string]): AnalyticsEndpoint[] {\n const [first, second] = entities;\n if (first === second) {\n const identifier = normalizeSqlIdentifier(first);\n return [\n { entityName: first, column: `${identifier}_source_id`, role: 'source' },\n { entityName: second, column: `${identifier}_target_id`, role: 'target' },\n ];\n }\n\n return [first, second]\n .sort()\n .map((entityName) => ({\n entityName,\n column: `${normalizeSqlIdentifier(entityName)}_id`,\n }));\n}\n\nfunction fingerprint(datasets: AnalyticsDataset[]): string {\n return createHash('sha256').update(JSON.stringify(datasets)).digest('hex');\n}\n\nexport function validateSchemaEvolution(\n previous: AnalyticsManifest,\n next: AnalyticsManifest,\n): void {\n const nextDatasets = new Map(\n next.datasets.map((dataset) => [dataset.identifier, dataset]),\n );\n for (const previousDataset of previous.datasets) {\n const nextDataset = nextDatasets.get(previousDataset.identifier);\n if (!nextDataset) {\n throw new Error(\n `Analytics dataset ${previousDataset.name} was removed. Supply an explicit analytics migration.`,\n );\n }\n const nextColumns = new Map(\n nextDataset.columns.map((column) => [column.name, column]),\n );\n for (const previousColumn of previousDataset.columns) {\n const nextColumn = nextColumns.get(previousColumn.name);\n if (!nextColumn) {\n throw new Error(\n `Analytics field ${previousDataset.name}.${previousColumn.sourceName} was removed or renamed. Supply an explicit analytics migration.`,\n );\n }\n if (nextColumn.type !== previousColumn.type) {\n throw new Error(\n `Analytics field ${previousDataset.name}.${previousColumn.sourceName} changed from ${previousColumn.type} to ${nextColumn.type}. Supply an explicit analytics migration.`,\n );\n }\n }\n }\n}\n\nexport function writeAnalyticsManifest(\n monoriseOutputDir: string,\n configs: AnalyticsConfig[],\n): void {\n const analyticsManifestPath = path.join(monoriseOutputDir, 'analytics-manifest.json');\n const manifest = createAnalyticsManifest(configs);\n if (manifest.unnamedMutuals.length) {\n console.warn(\n `Skipping unnamed mutual analytics datasets: ${manifest.unnamedMutuals.join(', ')}.`,\n );\n }\n if (fs.existsSync(analyticsManifestPath)) {\n validateSchemaEvolution(\n JSON.parse(fs.readFileSync(analyticsManifestPath, 'utf8')) as AnalyticsManifest,\n manifest,\n );\n }\n fs.writeFileSync(analyticsManifestPath, `${JSON.stringify(manifest, null, 2)}\\n`);\n}\n\nexport function createAnalyticsManifest(\n configs: AnalyticsConfig[],\n): AnalyticsManifest {\n const datasets: AnalyticsDataset[] = [];\n const unnamedMutuals = new Set<string>();\n const identifiers = new Map<string, string>();\n const mutuals = new Set<AnalyticsMutual>();\n const mutualPairs = new Map<string, string>();\n\n const addDataset = (\n kind: AnalyticsDataset['kind'],\n name: string,\n schema: ZodSchema,\n mutualEntities?: [string, string],\n ) => {\n if (!lowerKebabCase.test(name)) {\n throw new Error(\n `Invalid analytics ${kind} name: ${name}. Must be lower-kebab-case.`,\n );\n }\n const identifier = normalizeSqlIdentifier(name);\n const existing = identifiers.get(identifier);\n if (existing) {\n throw new Error(\n `Analytics dataset identifier collision: ${existing} and ${name} both normalize to ${identifier}.`,\n );\n }\n identifiers.set(identifier, name);\n const idColumn = `${identifier}_id`;\n const datasetEndpoints =\n kind === 'mutual' && mutualEntities ? endpoints(mutualEntities) : [];\n const datasetColumns = columns(schema, `${kind} ${name}`);\n const reservedNames = new Set([\n idColumn,\n ...datasetEndpoints.map((endpoint) => endpoint.column),\n 'event_id',\n 'idempotency_key',\n 'ordering_key',\n 'sequence_number',\n 'operation',\n 'occurred_at',\n 'before_json',\n 'after_json',\n ]);\n const collision = datasetColumns.find((column) =>\n reservedNames.has(column.name),\n );\n if (collision) {\n throw new Error(\n `Analytics field ${kind} ${name}.${collision.sourceName} conflicts with generated column ${collision.name}.`,\n );\n }\n datasets.push({\n kind,\n name,\n identifier,\n idColumn,\n endpoints: datasetEndpoints,\n currentTable: `${identifier}_${kind === 'entity' ? 'entities' : 'mutuals'}`,\n historyTable: `${identifier}_${kind === 'entity' ? 'entity_changes' : 'mutual_changes'}`,\n columns: datasetColumns,\n partition: { granularity: 'day' },\n });\n };\n\n for (const config of configs) {\n addDataset('entity', config.name, config.finalSchema);\n for (const field of Object.values(config.mutual?.mutualFields ?? {})) {\n const mutual = field.mutual;\n if (!mutual?.name) {\n unnamedMutuals.add(`${config.name}.${field.entityType}`);\n continue;\n }\n if (mutuals.has(mutual)) continue;\n mutuals.add(mutual);\n const entities: [string, string] = mutual.entities ?? [config.name, field.entityType];\n const pair = [...entities].sort().join('::');\n const existing = mutualPairs.get(pair);\n if (existing) {\n throw new Error(\n `Analytics mutual ${mutual.name} conflicts with ${existing}: both use the ${pair} entity pair.`,\n );\n }\n mutualPairs.set(pair, mutual.name);\n addDataset(\n 'mutual',\n mutual.name,\n mutual.mutualDataSchema,\n entities,\n );\n }\n }\n\n return {\n version: 2,\n datasets,\n unnamedMutuals: [...unnamedMutuals].sort(),\n schemaFingerprint: fingerprint(datasets),\n };\n}\n","import fs from 'node:fs';\nimport { createRequire } from 'node:module';\nimport path from 'node:path';\nimport { pathToFileURL } from 'node:url';\n\nconst require = createRequire(import.meta.url);\n\n// Set by `defineApiKeyPolicies` in @monorise/base. Reading the validator off\n// the policies object runs the same version of it the project's policies were\n// written against, without resolving @monorise/base from the project here.\nconst VALIDATE_API_KEY_POLICIES = Symbol.for('monorise.validateApiKeyPolicies');\n\n/**\n * Resolves `apiKeys` from monorise.config.ts to an absolute path, or\n * `undefined` when the project defines no policies.\n */\nexport function resolveApiKeysPath(\n projectRoot: string,\n apiKeys: string | undefined,\n configDir: string,\n): string | undefined {\n if (!apiKeys) return undefined;\n\n const absolutePath = path.resolve(projectRoot, apiKeys);\n if (\n !fs.existsSync(absolutePath) &&\n !fs.existsSync(`${absolutePath}.ts`) &&\n !fs.existsSync(`${absolutePath}.js`)\n ) {\n throw new Error(\n `API key policies file not found: '${absolutePath}'. Please ensure 'apiKeys' in monorise.config.ts points to a valid file.`,\n );\n }\n\n // Every file in configDir is loaded as an entity config, so a policy file\n // there would be read as an entity named 'undefined'.\n const fromConfigDir = path.relative(configDir, absolutePath);\n if (!fromConfigDir.startsWith('..') && !path.isAbsolute(fromConfigDir)) {\n throw new Error(\n `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'.`,\n );\n }\n return absolutePath;\n}\n\n/** The file `apiKeys` points at, with its extension: the one to watch. */\nexport function apiKeysFile(apiKeysPath: string): string {\n return (\n ['', '.ts', '.js']\n .map((extension) => `${apiKeysPath}${extension}`)\n .find((file) => fs.existsSync(file) && fs.statSync(file).isFile()) ??\n apiKeysPath\n );\n}\n\n// Imports a file as it is on disk now. `monorise dev` validates the policies\n// again after each edit, and both module caches would return the first version.\nconst importFresh = (file: string) => {\n delete require.cache[file];\n return import(`${pathToFileURL(file).href}?t=${Date.now()}`);\n};\n\n/**\n * Validates the project's policies against its entity configs. Runs after\n * config.ts is generated, because a policy file usually imports the generated\n * `Entity` enum.\n */\nexport async function validateApiKeyPoliciesFile(\n apiKeysPath: string,\n configOutputPath: string,\n): Promise<Record<string, unknown>> {\n const { default: generatedConfig } = await importFresh(configOutputPath);\n const { default: policies } = await importFresh(apiKeysFile(apiKeysPath));\n\n const validate = policies?.[VALIDATE_API_KEY_POLICIES];\n if (typeof validate !== 'function') {\n throw new Error(\n `API key policies file at '${apiKeysPath}' must default export the result of defineApiKeyPolicies(...).`,\n );\n }\n\n const errors: string[] = validate(generatedConfig.EntityConfig);\n if (errors.length) {\n throw new Error(\n `Invalid API key policies in '${apiKeysPath}':\\n - ${errors.join('\\n - ')}`,\n );\n }\n console.log('Validated API key policies.');\n return policies;\n}\n\n/**\n * Declares every custom route permission the policies grant, by augmenting\n * `ApiKeyRoutePermissions` in @monorise/base, so `requires()` only accepts\n * names some policy grants. Appended to config.ts.\n */\nexport function routePermissionDeclarations(\n policies: Record<string, unknown>,\n baseModuleNames: string[],\n): string {\n const permissions = new Set<string>();\n for (const policy of Object.values(policies)) {\n const routes = (policy as { routes?: unknown })?.routes;\n if (Array.isArray(routes)) {\n for (const permission of routes) permissions.add(permission);\n }\n }\n if (permissions.size === 0) return '';\n\n const members = [...permissions]\n .sort()\n .map((permission) => ` ${JSON.stringify(permission)}: true;`)\n .join('\\n');\n return baseModuleNames\n .map(\n (moduleName) => `\ndeclare module '${moduleName}' {\n interface ApiKeyRoutePermissions {\n${members}\n }\n}\n`,\n )\n .join('');\n}\n\n/**\n * The handle.ts import line for the policies, and the argument to pass to\n * `new CoreFactory(...)`. The policies are imported only by handle.ts, never\n * by config.ts, so a policy file can import the generated `Entity` enum\n * without a circular import.\n */\nexport function apiKeyPoliciesHandleParts(\n monoriseOutputDir: string,\n apiKeysPath: string | undefined,\n): { importLine: string; coreFactoryArg: string } {\n if (!apiKeysPath) return { importLine: '', coreFactoryArg: 'config' };\n\n const relativePath = path\n .relative(monoriseOutputDir, apiKeysPath)\n .replace(/\\.(ts|js|mjs|cjs)$/, '');\n const importPath = relativePath.startsWith('.')\n ? relativePath\n : `./${relativePath}`;\n\n return {\n importLine: `import apiKeyPolicies from '${importPath}';`,\n coreFactoryArg: '{ ...config, ApiKeyPolicies: apiKeyPolicies }',\n };\n}\n","type ApiKeyTypeEntity = {\n name: string;\n enumKey: string;\n config: {\n tags?: { name: string }[];\n mutual?: {\n mutualFields?: Record<\n string,\n {\n entityType: string;\n mutual?: { mutualDataSchema?: { shape?: Record<string, unknown> } };\n }\n >;\n };\n };\n};\n\nconst literalUnion = (names: string[]) =>\n names.length\n ? names.map((name) => JSON.stringify(name)).join(' | ')\n : 'never';\n\n/**\n * Declares each entity's tag names and each direction's mutualData field\n * names on @monorise/base's ApiKeyEntityTags and ApiKeyMutualDataFields, so a\n * policy's `tags` and relationship field lists are typed. The names are read\n * from the configs here, at build time. Goes inside the generated\n * `declare module` block for @monorise/base, where `Entity` is in scope.\n */\nexport function apiKeyTypeDeclarations(entities: ApiKeyTypeEntity[]): string {\n const enumKeys = new Map(\n entities.map((entity) => [entity.name, entity.enumKey]),\n );\n\n const tagEntries = entities.map(\n ({ enumKey, config }) =>\n `[Entity.${enumKey}]: ${literalUnion((config.tags ?? []).map((tag) => tag.name))};`,\n );\n\n // A pair's mutual config can be declared on either side and covers both\n // directions; each side's own declaration wins for its direction.\n const mutualFields = new Map<string, Map<string, string[]>>();\n const setDirection = (from: string, to: string, fields: string[]) => {\n const targets = mutualFields.get(from) ?? new Map<string, string[]>();\n if (!targets.has(to)) targets.set(to, fields);\n mutualFields.set(from, targets);\n };\n for (const pass of ['own', 'reverse'] as const) {\n for (const { name, config } of entities) {\n for (const field of Object.values(config.mutual?.mutualFields ?? {})) {\n const shape = field.mutual?.mutualDataSchema?.shape;\n if (!shape || !enumKeys.has(field.entityType)) continue;\n const fields = Object.keys(shape);\n if (pass === 'own') setDirection(name, field.entityType, fields);\n else setDirection(field.entityType, name, fields);\n }\n }\n }\n\n const mutualEntries = [...mutualFields].map(\n ([from, targets]) =>\n `[Entity.${enumKeys.get(from)}]: {\\n${[...targets]\n .map(\n ([to, fields]) =>\n ` [Entity.${enumKeys.get(to)}]: ${literalUnion(fields)};`,\n )\n .join('\\n')}\\n };`,\n );\n\n return `\n export interface ApiKeyEntityTags {\n ${tagEntries.join('\\n ')}\n }\n\n export interface ApiKeyMutualDataFields {\n ${mutualEntries.join('\\n ')}\n }`;\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\n\n/**\n * Detects whether the combined 'monorise' package is installed by walking up\n * the directory tree. This handles monorepo setups where dependencies are\n * hoisted to the root node_modules.\n */\nexport function detectCombinedPackage(startDir: string): boolean {\n let dir = startDir;\n while (true) {\n if (fs.existsSync(path.join(dir, 'node_modules', 'monorise'))) {\n return true;\n }\n const parent = path.dirname(dir);\n if (parent === dir) break; // reached filesystem root\n dir = parent;\n }\n return false;\n}\n","export const ROOT_TSCONFIG_TEMPLATE = {\n compilerOptions: {\n target: 'ES2022',\n module: 'ESNext',\n moduleResolution: 'bundler',\n esModuleInterop: true,\n strict: true,\n skipLibCheck: true,\n jsx: 'preserve',\n paths: {\n '#/shared/*': ['./shared/*'],\n '#/monorise/*': ['./.monorise/*'],\n '#/monorise': ['./.monorise/index'],\n },\n },\n include: ['**/*.ts', '.monorise/**/*.ts'],\n exclude: ['node_modules', 'apps'],\n};\n"],"mappings":";;;AAEA,OAAO;AACP,OAAOA,SAAQ;AACf,OAAOC,WAAU;AACjB,SAAS,gBAAuB;AAChC,OAAO,cAAc;;;ACNrB,SAAS,kBAAkB;AAC3B,OAAO,QAAQ;AACf,OAAO,UAAU;AAgEjB,IAAM,iBAAiB;AAEhB,SAAS,uBAAuB,MAAsB;AAC3D,QAAM,aAAa,KAChB,QAAQ,sBAAsB,OAAO,EACrC,QAAQ,kBAAkB,GAAG,EAC7B,QAAQ,YAAY,EAAE,EACtB,YAAY;AACf,SAAO,UAAU,KAAK,UAAU,IAAI,aAAa,IAAI,UAAU;AACjE;AAEA,SAAS,WAAW,QAAmBC,OAAuC;AAC5E,MAAI,UAAU;AACd,aAAS;AACP,UAAM,WAAW,QAAQ,MAAM;AAC/B,QAAI,aAAa,cAAc;AAG7B,UAAI,QAAQ,MAAM,QAAQ,SAAS,aAAc,QAAO;AACxD,UAAI,CAAC,QAAQ,KAAK,OAAQ,QAAO;AACjC,gBAAU,QAAQ,KAAK;AACvB;AAAA,IACF;AACA,QACE,aAAa,iBACb,aAAa,iBACb,aAAa,gBACb,aAAa,cACb,aAAa,eACb;AACA,UAAI,CAAC,QAAQ,MAAM,UAAW,QAAO;AACrC,gBAAU,QAAQ,KAAK;AACvB;AAAA,IACF;AACA,QAAI,aAAa,cAAc;AAC7B,UAAI,CAAC,QAAQ,MAAM,KAAM,QAAO;AAChC,gBAAU,QAAQ,KAAK;AACvB;AAAA,IACF;AACA;AAAA,EACF;AAEA,UAAQ,QAAQ,MAAM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@@ -0,0 +1,12 @@
1
+ import { defineApiKeyPolicies } from 'monorise/base';
2
+
3
+ // What each key in API_KEYS can reach. Keys under `default` can do everything
4
+ // until you define `default` here; then they get exactly what it grants, and
5
+ // the keys stay the same. https://monorise.dev/api-keys
6
+ export default defineApiKeyPolicies({
7
+ // default: {
8
+ // entities: {
9
+ // [Entity.USER]: { read: '*', update: ['displayName'] },
10
+ // },
11
+ // },
12
+ });
@@ -2,6 +2,8 @@ const config = {
2
2
  configDir: './monorise/configs',
3
3
  // custom routes should export default a Hono object.
4
4
  customRoutes: './services/core/routes.ts',
5
+ // API key policies: what each key in API_KEYS can reach.
6
+ apiKeys: './monorise/api-keys',
5
7
  };
6
8
 
7
9
  export default config;
@@ -4550,7 +4550,7 @@ declare class EntityServiceLifeCycle {
4550
4550
  private publishEvent;
4551
4551
  private eventUtils;
4552
4552
  constructor(EntityConfig: any, publishEvent: typeof publishEvent, eventUtils: EventUtils);
4553
- afterCreateEntityHook<T extends Entity$2>(entity: Entity$1<T>, entityPayload?: Record<string, unknown>, accountId?: string | string[]): Promise<void>;
4553
+ afterCreateEntityHook<T extends Entity$2>(entity: Entity$1<T>, entityPayload?: Record<string, unknown>): Promise<void>;
4554
4554
  }
4555
4555
 
4556
4556
  declare class EntityService {
@@ -4560,38 +4560,34 @@ declare class EntityService {
4560
4560
  private publishEvent;
4561
4561
  private entityServiceLifeCycle;
4562
4562
  constructor(EntityConfig: Record<Entity$2, ReturnType<typeof createEntityConfig>>, EmailAuthEnabledEntities: Entity$2[], entityRepository: EntityRepository, publishEvent: typeof publishEvent, entityServiceLifeCycle: EntityServiceLifeCycle);
4563
- createEntity: <T extends Entity$2>({ entityType, entityId, entityPayload, accountId, options, }: {
4563
+ createEntity: <T extends Entity$2>({ entityType, entityId, entityPayload, options, }: {
4564
4564
  entityType: T;
4565
4565
  entityPayload: EntitySchemaMap[T] | Record<string, any>;
4566
4566
  entityId?: string;
4567
- accountId?: string | string[];
4568
4567
  options?: {
4569
4568
  createAndUpdateDatetime?: string;
4570
4569
  mutualId?: string;
4571
4570
  };
4572
4571
  }) => Promise<Entity<T>>;
4573
- adjustEntity: <T extends Entity$2>({ entityType, entityId, adjustments, accountId, condition, }: {
4572
+ adjustEntity: <T extends Entity$2>({ entityType, entityId, adjustments, condition, }: {
4574
4573
  entityType: T;
4575
4574
  entityId: string;
4576
4575
  adjustments: Record<string, number>;
4577
- accountId?: string;
4578
4576
  condition?: string;
4579
4577
  }) => Promise<Entity<T>>;
4580
- updateEntity: <T extends Entity$2>({ entityType, entityId, entityPayload, accountId, condition, where, }: {
4578
+ updateEntity: <T extends Entity$2>({ entityType, entityId, entityPayload, condition, where, }: {
4581
4579
  entityType: T;
4582
4580
  entityId: string;
4583
4581
  entityPayload: Partial<EntitySchemaMap[T]>;
4584
- accountId?: string | string[];
4585
4582
  condition?: string;
4586
4583
  /** @deprecated Use `condition` (named condition) instead of raw `where`. */
4587
4584
  where?: WhereConditions;
4588
4585
  }) => Promise<Entity<T>>;
4589
4586
  /** @deprecated Converts legacy adjustmentConstraints to condition expression opts. */
4590
4587
  private buildLegacyAdjustCondition;
4591
- deleteEntity: <T extends Entity$2>({ entityType, entityId, accountId, }: {
4588
+ deleteEntity: <T extends Entity$2>({ entityType, entityId, }: {
4592
4589
  entityType: T;
4593
4590
  entityId: string;
4594
- accountId?: string | string[];
4595
4591
  }) => Promise<void>;
4596
4592
  }
4597
4593
 
@@ -4672,7 +4668,6 @@ type CreateMutualParams<B extends Entity$2, T extends Entity$2, A extends Entity
4672
4668
  entityType: T;
4673
4669
  entityId: string;
4674
4670
  mutualPayload?: Record<string, unknown>;
4675
- accountId?: string | string[];
4676
4671
  options?: {
4677
4672
  asEntity?: A;
4678
4673
  mutualId?: string;
@@ -4737,7 +4732,6 @@ declare class MutualService {
4737
4732
  parsedMutualPayload: {
4738
4733
  [x: string]: any;
4739
4734
  };
4740
- accountId: string | string[] | undefined;
4741
4735
  publishedAt: string;
4742
4736
  };
4743
4737
  }>;
@@ -4773,13 +4767,12 @@ declare class MutualService {
4773
4767
  TransactItems: _aws_sdk_client_dynamodb.TransactWriteItem[];
4774
4768
  parsedMutualPayload: Record<string, unknown>;
4775
4769
  }>;
4776
- updateMutual: <B extends Entity$2, T extends Entity$2, M extends Record<string, unknown>>({ byEntityType, byEntityId, entityType, entityId, mutualPayload, accountId, options, }: {
4770
+ updateMutual: <B extends Entity$2, T extends Entity$2, M extends Record<string, unknown>>({ byEntityType, byEntityId, entityType, entityId, mutualPayload, options, }: {
4777
4771
  byEntityType: B;
4778
4772
  byEntityId: string;
4779
4773
  entityType: T;
4780
4774
  entityId: string;
4781
4775
  mutualPayload: M;
4782
- accountId?: string | string[];
4783
4776
  options?: {
4784
4777
  maxObjectUpdateLevel?: number;
4785
4778
  returnUpdatedValue?: boolean;
@@ -4799,12 +4792,11 @@ declare class MutualService {
4799
4792
  mutual: Mutual<Entity$2, Entity$2, Record<string, unknown>>;
4800
4793
  TransactItems: _aws_sdk_client_dynamodb.TransactWriteItem[];
4801
4794
  }>;
4802
- deleteMutual: ({ byEntityType, byEntityId, entityType, entityId, accountId, }: {
4795
+ deleteMutual: ({ byEntityType, byEntityId, entityType, entityId, }: {
4803
4796
  byEntityType: Entity$2;
4804
4797
  byEntityId: string;
4805
4798
  entityType: Entity$2;
4806
4799
  entityId: string;
4807
- accountId?: string | string[];
4808
4800
  }) => Promise<Mutual<Entity$2, Entity$2, Record<string, unknown>>>;
4809
4801
  }
4810
4802
 
@@ -4938,7 +4930,7 @@ declare class TransactionService {
4938
4930
  private eventUtils;
4939
4931
  private mutualService?;
4940
4932
  constructor(EntityConfig: Record<Entity$2, ReturnType<typeof createEntityConfig>>, EmailAuthEnabledEntities: Entity$2[], entityRepository: EntityRepository, dynamodbClient: DynamoDB, publishEvent: typeof publishEvent, entityServiceLifeCycle: EntityServiceLifeCycle, eventUtils: EventUtils, mutualService?: MutualService | undefined);
4941
- executeTransaction: (operations: TransactionOperation[], accountId?: string) => Promise<TransactionResult>;
4933
+ executeTransaction: (operations: TransactionOperation[]) => Promise<TransactionResult>;
4942
4934
  private processOperation;
4943
4935
  private processCreateMutual;
4944
4936
  private processUpdateMutual;