monorise 1.5.0 → 1.8.0-dev.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/base/index.d.ts +5 -0
- package/dist/base/index.js.map +1 -1
- package/dist/cli/cli.js +157 -2
- package/dist/cli/cli.js.map +1 -1
- package/dist/core/index.d.ts +135 -5
- package/dist/core/index.js +1135 -16
- package/dist/core/index.js.map +1 -1
- package/dist/react/bowser-RUCNDTEX.js +2822 -0
- package/dist/react/bowser-RUCNDTEX.js.map +1 -0
- package/dist/react/chunk-2U2REJF4.js +138 -0
- package/dist/react/chunk-2U2REJF4.js.map +1 -0
- package/dist/react/chunk-5CPIG7AN.js +449 -0
- package/dist/react/chunk-5CPIG7AN.js.map +1 -0
- package/dist/react/chunk-7BSJSLIL.js +528 -0
- package/dist/react/chunk-7BSJSLIL.js.map +1 -0
- package/dist/react/chunk-7MNBSDJI.js +3362 -0
- package/dist/react/chunk-7MNBSDJI.js.map +1 -0
- package/dist/react/chunk-JXBFOCBM.js +2929 -0
- package/dist/react/chunk-JXBFOCBM.js.map +1 -0
- package/dist/react/chunk-MIXAYX55.js +147 -0
- package/dist/react/chunk-MIXAYX55.js.map +1 -0
- package/dist/react/chunk-Q26JGAFF.js +47 -0
- package/dist/react/chunk-Q26JGAFF.js.map +1 -0
- package/dist/react/chunk-QZSEUOCY.js +2298 -0
- package/dist/react/chunk-QZSEUOCY.js.map +1 -0
- package/dist/react/chunk-W6S3JWZV.js +1045 -0
- package/dist/react/chunk-W6S3JWZV.js.map +1 -0
- package/dist/react/chunk-WUOPYF3V.js +127 -0
- package/dist/react/chunk-WUOPYF3V.js.map +1 -0
- package/dist/react/chunk-Z45ECZFO.js +995 -0
- package/dist/react/chunk-Z45ECZFO.js.map +1 -0
- package/dist/react/dist-es-2P6AKQM3.js +325 -0
- package/dist/react/dist-es-2P6AKQM3.js.map +1 -0
- package/dist/react/dist-es-CEMZ6HT6.js +294 -0
- package/dist/react/dist-es-CEMZ6HT6.js.map +1 -0
- package/dist/react/dist-es-NZWWHEBR.js +89 -0
- package/dist/react/dist-es-NZWWHEBR.js.map +1 -0
- package/dist/react/dist-es-QVQ2CPIM.js +376 -0
- package/dist/react/dist-es-QVQ2CPIM.js.map +1 -0
- package/dist/react/dist-es-VBWII54H.js +70 -0
- package/dist/react/dist-es-VBWII54H.js.map +1 -0
- package/dist/react/dist-es-VXN7IC3J.js +23 -0
- package/dist/react/dist-es-VXN7IC3J.js.map +1 -0
- package/dist/react/dist-es-YKVDPOOB.js +221 -0
- package/dist/react/dist-es-YKVDPOOB.js.map +1 -0
- package/dist/react/dist-es-ZPOY2Z6R.js +178 -0
- package/dist/react/dist-es-ZPOY2Z6R.js.map +1 -0
- package/dist/react/event-streams-NBH35WQC.js +44 -0
- package/dist/react/event-streams-NBH35WQC.js.map +1 -0
- package/dist/react/index.d.ts +17 -0
- package/dist/react/index.d.ts.map +1 -1
- package/dist/react/index.js +25670 -368
- package/dist/react/index.js.map +1 -1
- package/dist/react/loadSso-2GPAQE3H.js +583 -0
- package/dist/react/loadSso-2GPAQE3H.js.map +1 -0
- package/dist/react/services/core.service.d.ts +8 -0
- package/dist/react/services/core.service.d.ts.map +1 -1
- package/dist/react/signin-HT4EDHQE.js +821 -0
- package/dist/react/signin-HT4EDHQE.js.map +1 -0
- package/dist/react/sso-oidc-WA3BK6FI.js +830 -0
- package/dist/react/sso-oidc-WA3BK6FI.js.map +1 -0
- package/dist/react/sts-V7PNNQ2L.js +1114 -0
- package/dist/react/sts-V7PNNQ2L.js.map +1 -0
- package/dist/sst/components/analytics.d.ts +52 -0
- package/dist/sst/components/analytics.d.ts.map +1 -0
- package/dist/sst/components/monorise-core.d.ts +5 -1
- package/dist/sst/components/monorise-core.d.ts.map +1 -1
- package/dist/sst/components/single-table.d.ts +3 -1
- package/dist/sst/components/single-table.d.ts.map +1 -1
- package/dist/sst/index.js +344 -7
- package/dist/sst/index.js.map +1 -1
- package/package.json +4 -1
package/dist/base/index.d.ts
CHANGED
|
@@ -45,6 +45,11 @@ interface EntitySchemaMap {
|
|
|
45
45
|
* ```
|
|
46
46
|
*/
|
|
47
47
|
interface MutualConfig<MD extends z.ZodRawShape = z.ZodRawShape> {
|
|
48
|
+
/**
|
|
49
|
+
* Stable analytics dataset name. When provided, it must be lower-kebab-case;
|
|
50
|
+
* the generator validates this so unnamed mutuals remain backwards compatible.
|
|
51
|
+
*/
|
|
52
|
+
name?: string;
|
|
48
53
|
entities: [Entity, Entity];
|
|
49
54
|
mutualDataSchema: z.ZodObject<MD>;
|
|
50
55
|
}
|
package/dist/base/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../types/monorise.type.ts","../utils/index.ts"],"sourcesContent":["import type { z } from 'zod';\nimport type { WhereConditions } from './conditions.type';\n\nexport enum Entity {}\n\nexport interface EntitySchemaMap {\n [key: string]: Record<string, any>;\n}\n\n/**\n * @description Configuration for a mutual relationship between two entities.\n * Defines the schema for mutualData validation. Define once, reference from both entity configs.\n *\n * @example\n * ```ts\n * const enrollmentMutual = createMutualConfig({\n * entities: [Entity.STUDENT, Entity.COURSE],\n * mutualDataSchema: z.object({\n * role: z.enum(['student', 'auditor']),\n * enrolledAt: z.string().datetime(),\n * }),\n * });\n * ```\n */\nexport interface MutualConfig<\n MD extends z.ZodRawShape = z.ZodRawShape,\n> {\n entities: [Entity, Entity];\n mutualDataSchema: z.ZodObject<MD>;\n}\n\nexport type DraftEntity<T extends Entity = Entity> =\n T extends keyof EntitySchemaMap ? EntitySchemaMap[T] : never;\n\nexport type NumericFields<T> = {\n [K in keyof T as T[K] extends number ? K : never]?: number;\n};\n\nexport type CreatedEntity<T extends Entity = Entity> = {\n entityId: string;\n entityType: string;\n data: T extends keyof EntitySchemaMap ? EntitySchemaMap[T] : never;\n createdAt: string;\n updatedAt: string;\n};\n\n/**\n * @description Configuration for a monorise entity, a shared configuration that is used across frontend and backend.\n * This can be served as a single source of truth for the entity configuration.\n * It is used to define the schema, and mutual relationships between this entity and other entities.\n *\n * @example\n * ```ts\n * const baseSchema = z.object({\n * title: z.string(),\n * }).partial();\n *\n * const createSchema = baseSchema.extend({\n * title: z.string(),\n * })\n *\n * const config = createEntityConfig({\n * name: 'learner',\n * displayName: 'Learner',\n * baseSchema,\n * createSchema,\n * });\n * ```\n */\nexport interface MonoriseEntityConfig<\n T extends Entity = Entity,\n B extends z.ZodRawShape = z.ZodRawShape,\n C extends z.ZodRawShape = z.ZodRawShape,\n M extends z.ZodRawShape = z.ZodRawShape,\n CO extends z.ZodObject<C> | undefined = undefined,\n MO extends z.ZodObject<M> | undefined = undefined,\n> {\n /**\n * @description Name of the entity. Must be in **lower-kebab-case** and **unique** across all entities\n *\n * @example `learner`, `learning-activity`\n */\n name: string | T;\n\n /**\n * @description Display name of the entity. It is not required to be unique\n */\n displayName: string;\n\n /**\n * @description (DEPRECATED) Use `uniqueFields` instead, Monorise should not handle auth mechanism\n * @description (Optional) Specify the authentication method to be used for the entity\n */\n authMethod?: {\n /**\n * @description Authentication method using email\n *\n * Note: The email used for authentication is unique per entity.\n * For example, if `johndoe@mail.com` is used for `learner` entity,\n * it can be reused again on `admin` entity. However, the same email\n * address cannot be repeated for the same entity.\n */\n email: {\n /**\n * @description Number of milliseconds before the token expires\n */\n tokenExpiresIn: number;\n };\n };\n\n /**\n * @description Base schema for the entity\n */\n baseSchema: z.ZodObject<B>;\n\n /**\n * @description Minimal schema required to create an entity\n */\n createSchema?: CO;\n searchableFields?: (keyof B)[];\n uniqueFields?: (keyof B)[];\n\n /**\n * @description Define mutual relationship of this entity with other entities\n */\n mutual?: {\n /**\n * @description Subscribes to update events from specified entities in the array.\n * These events will be used to run prejoin processor.\n */\n subscribes?: { entityType: Entity }[];\n /**\n * @description Virtual schema for mutual relationship. The schema is only used for validation purpose, but these fields are not stored in the database\n */\n mutualSchema: MO;\n\n /**\n * @description Keys of `mutualFields` are fields defined in `mutualSchema`.\n * Each field is a mutual relationship between this entity and another entity.\n */\n mutualFields: {\n [key: string]: {\n entityType: Entity;\n toMutualIds?: (context: any) => string[];\n /**\n * @description (Optional) Custom function to process `mutualData`. If not provided, `mutualData` will be empty.\n *\n * @returns the final state of `mutualData` to be stored in the mutual record. Must be an object.\n */\n mutualDataProcessor?: (\n mutualIds: string[],\n currentMutual: any,\n customContext?: Record<string, any>,\n ) => Record<string, any>;\n /**\n * @description (Optional) Reference to a mutual config created by `createMutualConfig`.\n * Provides mutualData schema validation for create/update operations on this mutual relationship.\n */\n mutual?: MutualConfig;\n };\n };\n\n /**\n * @description (Optional) Better known as tree processor\n * This is used to prejoin entities that are not directly related as mutual.\n * For example, if `learner` entity is related to `course` entity, and `course` entity is related to `module` entity,\n * prejoins can be used to join `learner` and `module` entities.\n * With this, the `learner` entity can access the `module` entity without having to go through the `course` entity,\n * hence reducing the number of queries.\n *\n * DynamoDB best practices: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/bp-general-normalization.html\n *\n */\n prejoins?: {\n mutualField: string;\n targetEntityType: Entity;\n entityPaths: {\n skipCache?: boolean;\n entityType: Entity;\n processor?: (items: any[], context: Record<string, any>) => any;\n }[];\n }[];\n };\n /**\n * Use this function to perform side effects on the final schema for example refine/superRefine the schema\n *\n * @param schema The final schema of the entity (the combination of `baseSchema`/`createSchema` and `mutualSchema` if specified)\n * @returns void\n *\n * @example\n * ```ts\n * effect: (schema) => {\n * schema.refine(\n * // refinement logic here\n * )\n * }\n */\n effect?: (\n schema: z.ZodObject<z.ZodRawShape>,\n ) => z.ZodEffects<z.ZodObject<z.ZodRawShape>>;\n\n /**\n * @description (Optional) Use tags to create additional access patterns for the entity.\n * Time complexity for retrieving tagged entities is O(1).\n *\n * The following configuration will create a tag named `region` for the `organization` entity grouped by `region`.\n * You would then be able to retrieve all organizations in a specific region by:\n * GET `/core/tag/organization/region?group={region_name}`\n *\n * @example\n *\n * ```ts\n * {\n * name: 'organization',\n * tags: [\n * {\n * name: 'region',\n * processor: (entity) => {\n * return [\n * {\n * group: entity.data.region\n * }\n * ]\n * },\n * }\n * ]\n * }\n * ```\n *\n * @description\n *\n * The following configuration will create a tag named `dob` for the `user` entity sorted by `dob`.\n * You would then be able to retrieve all users sorted by `dob` by:\n * GET `/core/tag/user/dob?start=2000-01-01&end=2020-12-31`\n *\n * @example\n * ```ts\n * {\n * name: 'user',\n * tags: [\n * {\n * name: 'dob',\n * processor: (entity) => {\n * return [\n * {\n * sortValue: entity.data.dob\n * }\n * ]\n * },\n * }\n * ]\n * }\n * ```\n */\n tags?: {\n name: string;\n processor: (entity: { entityId: string; entityType: string; data: Record<string, any>; createdAt: string; updatedAt: string }) => {\n group?: string;\n sortValue?: string;\n }[];\n }[];\n\n /**\n * @description (Optional) Configure a DynamoDB TTL for this entity. When set, `expiresAt`\n * is computed via `processor` on create, and recomputed on every update/upsert. Once past,\n * DynamoDB automatically deletes the item (and its derived index rows, since they all carry\n * the same `expiresAt`).\n *\n * `processor` returning `undefined` means \"no TTL\" for that record. On updates, an `undefined`\n * result leaves any existing `expiresAt` untouched rather than clearing it.\n *\n * @example\n * ```ts\n * // fixed 30-day TTL from creation/each update\n * ttl: {\n * processor: () => Math.floor(Date.now() / 1000) + 30 * 24 * 60 * 60,\n * }\n * ```\n *\n * @example\n * ```ts\n * // data-driven TTL, eg. expire when a subscription ends\n * ttl: {\n * processor: (entity) => {\n * return entity.data.subscriptionEndsAt\n * ? new Date(entity.data.subscriptionEndsAt)\n * : undefined;\n * },\n * }\n * ```\n */\n ttl?: {\n /**\n * @description Returns the expiry as epoch seconds (absolute) or a `Date`.\n * Return `undefined` for no expiry.\n */\n processor: (entity: {\n entityId: string;\n entityType: string;\n data: Record<string, any>;\n createdAt: string;\n updatedAt: string;\n }) => number | Date | undefined;\n };\n\n /**\n * @description (Optional) Constraints for `adjustEntity` operations.\n * When adjusting numeric fields, these constraints are enforced at the database level.\n * If an adjustment would violate a constraint, the operation is rejected.\n *\n * @deprecated Use `conditions` instead. Will be removed in a future version.\n *\n * @example\n * ```ts\n * {\n * adjustmentConstraints: {\n * // Static: same for all entities of this type\n * balance: { min: 0 },\n * credits: { min: 0, max: 10000 },\n *\n * // Dynamic: reads constraint value from entity's own data\n * balance: { minField: 'minBalance' },\n * credits: { min: 0, maxField: 'creditLimit' },\n * }\n * }\n * ```\n */\n adjustmentConstraints?: {\n [fieldName: string]: {\n /** Static minimum value */\n min?: number;\n /** Static maximum value */\n max?: number;\n /** Field name on the entity whose value is used as the minimum (must be a numeric field) */\n minField?: keyof {\n [K in keyof B as B[K] extends z.ZodNumber | z.ZodOptional<z.ZodNumber> ? K : never]: K;\n } extends never ? string : keyof {\n [K in keyof B as B[K] extends z.ZodNumber | z.ZodOptional<z.ZodNumber> ? K : never]: K;\n };\n /** Field name on the entity whose value is used as the maximum (must be a numeric field) */\n maxField?: keyof {\n [K in keyof B as B[K] extends z.ZodNumber | z.ZodOptional<z.ZodNumber> ? K : never]: K;\n } extends never ? string : keyof {\n [K in keyof B as B[K] extends z.ZodNumber | z.ZodOptional<z.ZodNumber> ? K : never]: K;\n };\n };\n };\n\n /**\n * @description Named conditions for adjustEntity operations.\n * Each condition is either a static `WhereConditions` object or a function\n * `(data, adjustments) => WhereConditions` that receives the entity's current data\n * and the adjustment deltas.\n *\n * When defined, `$condition` is **required** in the adjustEntity request body.\n * The client sends a condition name (string), the server resolves it to a\n * DynamoDB ConditionExpression.\n *\n * @example\n * ```ts\n * {\n * adjustmentConditions: {\n * withdraw: (data, adjustments) => ({\n * balance: { $gte: (data.minBalance ?? 0) + Math.abs(adjustments?.balance ?? 0) },\n * }),\n * deposit: (data, adjustments) => ({\n * balance: { $lte: 1000000 - (adjustments.balance ?? 0) },\n * }),\n * }\n * }\n * ```\n */\n adjustmentConditions?: {\n [conditionName: string]:\n | WhereConditions\n | ((\n data: Partial<z.infer<z.ZodObject<B>>>,\n adjustments: Record<string, number>,\n ) => WhereConditions);\n };\n\n /**\n * @description Named conditions for updateEntity operations.\n * Each condition is either a static `WhereConditions` object or a function\n * `(data) => WhereConditions` that receives the entity's current data.\n *\n * `$condition` is always **optional** for updateEntity.\n * The client sends a condition name (string), the server resolves it to a\n * DynamoDB ConditionExpression. Replaces raw `$where` (deprecated).\n *\n * @example\n * ```ts\n * {\n * updateConditions: {\n * publish: { status: { $eq: 'draft' } },\n * archive: (data) => ({ status: { $ne: 'archived' } }),\n * }\n * }\n * ```\n */\n updateConditions?: {\n [conditionName: string]:\n | WhereConditions\n | ((data: Partial<z.infer<z.ZodObject<B>>>) => WhereConditions);\n };\n\n /**\n * @description (Optional) Opt in to accepting legacy raw `$where` on updateEntity.\n * Disabled by default: raw DynamoDB condition operators must never be\n * client-facing — an authenticated client could otherwise probe field\n * existence or guess values via the 200-vs-409 response status.\n *\n * Only enable this if you trust the caller (e.g. server-to-server) or have\n * your own validation in front of it. Prefer `updateConditions` instead.\n *\n * @default false\n */\n allowLegacyWhere?: boolean;\n}\n","import type { Entity, MonoriseEntityConfig, MutualConfig } from '../types/monorise.type';\nimport { z } from 'zod';\n\nfunction makeSchema<\n T extends Entity,\n B extends z.ZodRawShape,\n C extends z.ZodRawShape,\n M extends z.ZodRawShape,\n CO extends z.ZodObject<C> | undefined = undefined,\n MO extends z.ZodObject<M> | undefined = undefined,\n>(config: MonoriseEntityConfig<T, B, C, M, CO, MO>) {\n const { baseSchema, createSchema, mutual, effect } = config;\n const { mutualSchema } = mutual || {};\n\n type FinalSchemaType = CO extends z.AnyZodObject\n ? MO extends z.AnyZodObject\n ? z.ZodObject<MO['shape'] & CO['shape']>\n : CO\n : MO extends z.AnyZodObject\n ? z.ZodObject<MO['shape'] & B>\n : z.ZodObject<B>;\n\n const finalSchema = z.object({\n ...baseSchema.shape,\n ...createSchema?.shape,\n ...mutualSchema?.shape,\n }) as FinalSchemaType;\n\n if (effect) {\n return effect(finalSchema) as z.ZodEffects<FinalSchemaType>;\n }\n\n return finalSchema;\n}\n\nconst createEntityConfig = <\n T extends Entity,\n B extends z.ZodRawShape,\n C extends z.ZodRawShape,\n M extends z.ZodRawShape,\n CO extends z.ZodObject<C> | undefined = undefined,\n MO extends z.ZodObject<M> | undefined = undefined,\n>(\n config: MonoriseEntityConfig<T, B, C, M, CO, MO>,\n) => ({\n ...config,\n finalSchema: makeSchema(config),\n});\n\nconst createMutualConfig = <MD extends z.ZodRawShape>(\n config: MutualConfig<MD>,\n) => config;\n\nexport { createEntityConfig, createMutualConfig };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAGO,IAAK,SAAL,kBAAKA,YAAL;AAAK,SAAAA;AAAA,GAAA;;;ACFZ,SAAS,SAAS;AAElB,SAAS,WAOP,QAAkD;AAClD,QAAM,EAAE,YAAY,cAAc,QAAQ,OAAO,IAAI;AACrD,QAAM,EAAE,aAAa,IAAI,UAAU,CAAC;AAUpC,QAAM,cAAc,EAAE,OAAO,iDACxB,WAAW,QACX,6CAAc,QACd,6CAAc,MAClB;AAED,MAAI,QAAQ;AACV,WAAO,OAAO,WAAW;AAAA,EAC3B;AAEA,SAAO;AACT;AAEA,IAAM,qBAAqB,CAQzB,WACI,iCACD,SADC;AAAA,EAEJ,aAAa,WAAW,MAAM;AAChC;AAEA,IAAM,qBAAqB,CACzB,WACG;","names":["Entity"]}
|
|
1
|
+
{"version":3,"sources":["../types/monorise.type.ts","../utils/index.ts"],"sourcesContent":["import type { z } from 'zod';\nimport type { WhereConditions } from './conditions.type';\n\nexport enum Entity {}\n\nexport interface EntitySchemaMap {\n [key: string]: Record<string, any>;\n}\n\n/**\n * @description Configuration for a mutual relationship between two entities.\n * Defines the schema for mutualData validation. Define once, reference from both entity configs.\n *\n * @example\n * ```ts\n * const enrollmentMutual = createMutualConfig({\n * entities: [Entity.STUDENT, Entity.COURSE],\n * mutualDataSchema: z.object({\n * role: z.enum(['student', 'auditor']),\n * enrolledAt: z.string().datetime(),\n * }),\n * });\n * ```\n */\nexport interface MutualConfig<\n MD extends z.ZodRawShape = z.ZodRawShape,\n> {\n /**\n * Stable analytics dataset name. When provided, it must be lower-kebab-case;\n * the generator validates this so unnamed mutuals remain backwards compatible.\n */\n name?: string;\n entities: [Entity, Entity];\n mutualDataSchema: z.ZodObject<MD>;\n}\n\nexport type DraftEntity<T extends Entity = Entity> =\n T extends keyof EntitySchemaMap ? EntitySchemaMap[T] : never;\n\nexport type NumericFields<T> = {\n [K in keyof T as T[K] extends number ? K : never]?: number;\n};\n\nexport type CreatedEntity<T extends Entity = Entity> = {\n entityId: string;\n entityType: string;\n data: T extends keyof EntitySchemaMap ? EntitySchemaMap[T] : never;\n createdAt: string;\n updatedAt: string;\n};\n\n/**\n * @description Configuration for a monorise entity, a shared configuration that is used across frontend and backend.\n * This can be served as a single source of truth for the entity configuration.\n * It is used to define the schema, and mutual relationships between this entity and other entities.\n *\n * @example\n * ```ts\n * const baseSchema = z.object({\n * title: z.string(),\n * }).partial();\n *\n * const createSchema = baseSchema.extend({\n * title: z.string(),\n * })\n *\n * const config = createEntityConfig({\n * name: 'learner',\n * displayName: 'Learner',\n * baseSchema,\n * createSchema,\n * });\n * ```\n */\nexport interface MonoriseEntityConfig<\n T extends Entity = Entity,\n B extends z.ZodRawShape = z.ZodRawShape,\n C extends z.ZodRawShape = z.ZodRawShape,\n M extends z.ZodRawShape = z.ZodRawShape,\n CO extends z.ZodObject<C> | undefined = undefined,\n MO extends z.ZodObject<M> | undefined = undefined,\n> {\n /**\n * @description Name of the entity. Must be in **lower-kebab-case** and **unique** across all entities\n *\n * @example `learner`, `learning-activity`\n */\n name: string | T;\n\n /**\n * @description Display name of the entity. It is not required to be unique\n */\n displayName: string;\n\n /**\n * @description (DEPRECATED) Use `uniqueFields` instead, Monorise should not handle auth mechanism\n * @description (Optional) Specify the authentication method to be used for the entity\n */\n authMethod?: {\n /**\n * @description Authentication method using email\n *\n * Note: The email used for authentication is unique per entity.\n * For example, if `johndoe@mail.com` is used for `learner` entity,\n * it can be reused again on `admin` entity. However, the same email\n * address cannot be repeated for the same entity.\n */\n email: {\n /**\n * @description Number of milliseconds before the token expires\n */\n tokenExpiresIn: number;\n };\n };\n\n /**\n * @description Base schema for the entity\n */\n baseSchema: z.ZodObject<B>;\n\n /**\n * @description Minimal schema required to create an entity\n */\n createSchema?: CO;\n searchableFields?: (keyof B)[];\n uniqueFields?: (keyof B)[];\n\n /**\n * @description Define mutual relationship of this entity with other entities\n */\n mutual?: {\n /**\n * @description Subscribes to update events from specified entities in the array.\n * These events will be used to run prejoin processor.\n */\n subscribes?: { entityType: Entity }[];\n /**\n * @description Virtual schema for mutual relationship. The schema is only used for validation purpose, but these fields are not stored in the database\n */\n mutualSchema: MO;\n\n /**\n * @description Keys of `mutualFields` are fields defined in `mutualSchema`.\n * Each field is a mutual relationship between this entity and another entity.\n */\n mutualFields: {\n [key: string]: {\n entityType: Entity;\n toMutualIds?: (context: any) => string[];\n /**\n * @description (Optional) Custom function to process `mutualData`. If not provided, `mutualData` will be empty.\n *\n * @returns the final state of `mutualData` to be stored in the mutual record. Must be an object.\n */\n mutualDataProcessor?: (\n mutualIds: string[],\n currentMutual: any,\n customContext?: Record<string, any>,\n ) => Record<string, any>;\n /**\n * @description (Optional) Reference to a mutual config created by `createMutualConfig`.\n * Provides mutualData schema validation for create/update operations on this mutual relationship.\n */\n mutual?: MutualConfig;\n };\n };\n\n /**\n * @description (Optional) Better known as tree processor\n * This is used to prejoin entities that are not directly related as mutual.\n * For example, if `learner` entity is related to `course` entity, and `course` entity is related to `module` entity,\n * prejoins can be used to join `learner` and `module` entities.\n * With this, the `learner` entity can access the `module` entity without having to go through the `course` entity,\n * hence reducing the number of queries.\n *\n * DynamoDB best practices: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/bp-general-normalization.html\n *\n */\n prejoins?: {\n mutualField: string;\n targetEntityType: Entity;\n entityPaths: {\n skipCache?: boolean;\n entityType: Entity;\n processor?: (items: any[], context: Record<string, any>) => any;\n }[];\n }[];\n };\n /**\n * Use this function to perform side effects on the final schema for example refine/superRefine the schema\n *\n * @param schema The final schema of the entity (the combination of `baseSchema`/`createSchema` and `mutualSchema` if specified)\n * @returns void\n *\n * @example\n * ```ts\n * effect: (schema) => {\n * schema.refine(\n * // refinement logic here\n * )\n * }\n */\n effect?: (\n schema: z.ZodObject<z.ZodRawShape>,\n ) => z.ZodEffects<z.ZodObject<z.ZodRawShape>>;\n\n /**\n * @description (Optional) Use tags to create additional access patterns for the entity.\n * Time complexity for retrieving tagged entities is O(1).\n *\n * The following configuration will create a tag named `region` for the `organization` entity grouped by `region`.\n * You would then be able to retrieve all organizations in a specific region by:\n * GET `/core/tag/organization/region?group={region_name}`\n *\n * @example\n *\n * ```ts\n * {\n * name: 'organization',\n * tags: [\n * {\n * name: 'region',\n * processor: (entity) => {\n * return [\n * {\n * group: entity.data.region\n * }\n * ]\n * },\n * }\n * ]\n * }\n * ```\n *\n * @description\n *\n * The following configuration will create a tag named `dob` for the `user` entity sorted by `dob`.\n * You would then be able to retrieve all users sorted by `dob` by:\n * GET `/core/tag/user/dob?start=2000-01-01&end=2020-12-31`\n *\n * @example\n * ```ts\n * {\n * name: 'user',\n * tags: [\n * {\n * name: 'dob',\n * processor: (entity) => {\n * return [\n * {\n * sortValue: entity.data.dob\n * }\n * ]\n * },\n * }\n * ]\n * }\n * ```\n */\n tags?: {\n name: string;\n processor: (entity: { entityId: string; entityType: string; data: Record<string, any>; createdAt: string; updatedAt: string }) => {\n group?: string;\n sortValue?: string;\n }[];\n }[];\n\n /**\n * @description (Optional) Configure a DynamoDB TTL for this entity. When set, `expiresAt`\n * is computed via `processor` on create, and recomputed on every update/upsert. Once past,\n * DynamoDB automatically deletes the item (and its derived index rows, since they all carry\n * the same `expiresAt`).\n *\n * `processor` returning `undefined` means \"no TTL\" for that record. On updates, an `undefined`\n * result leaves any existing `expiresAt` untouched rather than clearing it.\n *\n * @example\n * ```ts\n * // fixed 30-day TTL from creation/each update\n * ttl: {\n * processor: () => Math.floor(Date.now() / 1000) + 30 * 24 * 60 * 60,\n * }\n * ```\n *\n * @example\n * ```ts\n * // data-driven TTL, eg. expire when a subscription ends\n * ttl: {\n * processor: (entity) => {\n * return entity.data.subscriptionEndsAt\n * ? new Date(entity.data.subscriptionEndsAt)\n * : undefined;\n * },\n * }\n * ```\n */\n ttl?: {\n /**\n * @description Returns the expiry as epoch seconds (absolute) or a `Date`.\n * Return `undefined` for no expiry.\n */\n processor: (entity: {\n entityId: string;\n entityType: string;\n data: Record<string, any>;\n createdAt: string;\n updatedAt: string;\n }) => number | Date | undefined;\n };\n\n /**\n * @description (Optional) Constraints for `adjustEntity` operations.\n * When adjusting numeric fields, these constraints are enforced at the database level.\n * If an adjustment would violate a constraint, the operation is rejected.\n *\n * @deprecated Use `conditions` instead. Will be removed in a future version.\n *\n * @example\n * ```ts\n * {\n * adjustmentConstraints: {\n * // Static: same for all entities of this type\n * balance: { min: 0 },\n * credits: { min: 0, max: 10000 },\n *\n * // Dynamic: reads constraint value from entity's own data\n * balance: { minField: 'minBalance' },\n * credits: { min: 0, maxField: 'creditLimit' },\n * }\n * }\n * ```\n */\n adjustmentConstraints?: {\n [fieldName: string]: {\n /** Static minimum value */\n min?: number;\n /** Static maximum value */\n max?: number;\n /** Field name on the entity whose value is used as the minimum (must be a numeric field) */\n minField?: keyof {\n [K in keyof B as B[K] extends z.ZodNumber | z.ZodOptional<z.ZodNumber> ? K : never]: K;\n } extends never ? string : keyof {\n [K in keyof B as B[K] extends z.ZodNumber | z.ZodOptional<z.ZodNumber> ? K : never]: K;\n };\n /** Field name on the entity whose value is used as the maximum (must be a numeric field) */\n maxField?: keyof {\n [K in keyof B as B[K] extends z.ZodNumber | z.ZodOptional<z.ZodNumber> ? K : never]: K;\n } extends never ? string : keyof {\n [K in keyof B as B[K] extends z.ZodNumber | z.ZodOptional<z.ZodNumber> ? K : never]: K;\n };\n };\n };\n\n /**\n * @description Named conditions for adjustEntity operations.\n * Each condition is either a static `WhereConditions` object or a function\n * `(data, adjustments) => WhereConditions` that receives the entity's current data\n * and the adjustment deltas.\n *\n * When defined, `$condition` is **required** in the adjustEntity request body.\n * The client sends a condition name (string), the server resolves it to a\n * DynamoDB ConditionExpression.\n *\n * @example\n * ```ts\n * {\n * adjustmentConditions: {\n * withdraw: (data, adjustments) => ({\n * balance: { $gte: (data.minBalance ?? 0) + Math.abs(adjustments?.balance ?? 0) },\n * }),\n * deposit: (data, adjustments) => ({\n * balance: { $lte: 1000000 - (adjustments.balance ?? 0) },\n * }),\n * }\n * }\n * ```\n */\n adjustmentConditions?: {\n [conditionName: string]:\n | WhereConditions\n | ((\n data: Partial<z.infer<z.ZodObject<B>>>,\n adjustments: Record<string, number>,\n ) => WhereConditions);\n };\n\n /**\n * @description Named conditions for updateEntity operations.\n * Each condition is either a static `WhereConditions` object or a function\n * `(data) => WhereConditions` that receives the entity's current data.\n *\n * `$condition` is always **optional** for updateEntity.\n * The client sends a condition name (string), the server resolves it to a\n * DynamoDB ConditionExpression. Replaces raw `$where` (deprecated).\n *\n * @example\n * ```ts\n * {\n * updateConditions: {\n * publish: { status: { $eq: 'draft' } },\n * archive: (data) => ({ status: { $ne: 'archived' } }),\n * }\n * }\n * ```\n */\n updateConditions?: {\n [conditionName: string]:\n | WhereConditions\n | ((data: Partial<z.infer<z.ZodObject<B>>>) => WhereConditions);\n };\n\n /**\n * @description (Optional) Opt in to accepting legacy raw `$where` on updateEntity.\n * Disabled by default: raw DynamoDB condition operators must never be\n * client-facing — an authenticated client could otherwise probe field\n * existence or guess values via the 200-vs-409 response status.\n *\n * Only enable this if you trust the caller (e.g. server-to-server) or have\n * your own validation in front of it. Prefer `updateConditions` instead.\n *\n * @default false\n */\n allowLegacyWhere?: boolean;\n}\n","import type { Entity, MonoriseEntityConfig, MutualConfig } from '../types/monorise.type';\nimport { z } from 'zod';\n\nfunction makeSchema<\n T extends Entity,\n B extends z.ZodRawShape,\n C extends z.ZodRawShape,\n M extends z.ZodRawShape,\n CO extends z.ZodObject<C> | undefined = undefined,\n MO extends z.ZodObject<M> | undefined = undefined,\n>(config: MonoriseEntityConfig<T, B, C, M, CO, MO>) {\n const { baseSchema, createSchema, mutual, effect } = config;\n const { mutualSchema } = mutual || {};\n\n type FinalSchemaType = CO extends z.AnyZodObject\n ? MO extends z.AnyZodObject\n ? z.ZodObject<MO['shape'] & CO['shape']>\n : CO\n : MO extends z.AnyZodObject\n ? z.ZodObject<MO['shape'] & B>\n : z.ZodObject<B>;\n\n const finalSchema = z.object({\n ...baseSchema.shape,\n ...createSchema?.shape,\n ...mutualSchema?.shape,\n }) as FinalSchemaType;\n\n if (effect) {\n return effect(finalSchema) as z.ZodEffects<FinalSchemaType>;\n }\n\n return finalSchema;\n}\n\nconst createEntityConfig = <\n T extends Entity,\n B extends z.ZodRawShape,\n C extends z.ZodRawShape,\n M extends z.ZodRawShape,\n CO extends z.ZodObject<C> | undefined = undefined,\n MO extends z.ZodObject<M> | undefined = undefined,\n>(\n config: MonoriseEntityConfig<T, B, C, M, CO, MO>,\n) => ({\n ...config,\n finalSchema: makeSchema(config),\n});\n\nconst createMutualConfig = <MD extends z.ZodRawShape>(\n config: MutualConfig<MD>,\n) => config;\n\nexport { createEntityConfig, createMutualConfig };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAGO,IAAK,SAAL,kBAAKA,YAAL;AAAK,SAAAA;AAAA,GAAA;;;ACFZ,SAAS,SAAS;AAElB,SAAS,WAOP,QAAkD;AAClD,QAAM,EAAE,YAAY,cAAc,QAAQ,OAAO,IAAI;AACrD,QAAM,EAAE,aAAa,IAAI,UAAU,CAAC;AAUpC,QAAM,cAAc,EAAE,OAAO,iDACxB,WAAW,QACX,6CAAc,QACd,6CAAc,MAClB;AAED,MAAI,QAAQ;AACV,WAAO,OAAO,WAAW;AAAA,EAC3B;AAEA,SAAO;AACT;AAEA,IAAM,qBAAqB,CAQzB,WACI,iCACD,SADC;AAAA,EAEJ,aAAa,WAAW,MAAM;AAChC;AAEA,IAAM,qBAAqB,CACzB,WACG;","names":["Entity"]}
|
package/dist/cli/cli.js
CHANGED
|
@@ -6,6 +6,143 @@ import fs2 from "fs";
|
|
|
6
6
|
import path2 from "path";
|
|
7
7
|
import { execSync } from "child_process";
|
|
8
8
|
import chokidar from "chokidar";
|
|
9
|
+
|
|
10
|
+
// commands/utils/analytics-manifest.ts
|
|
11
|
+
import { createHash } from "crypto";
|
|
12
|
+
var lowerKebabCase = /^[a-z]+(?:-[a-z]+)*$/;
|
|
13
|
+
function normalizeSqlIdentifier(name) {
|
|
14
|
+
const normalized = name.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/[^a-zA-Z0-9]+/g, "_").replace(/^_+|_+$/g, "").toLowerCase();
|
|
15
|
+
return /^[a-z_]/.test(normalized) ? normalized : `_${normalized}`;
|
|
16
|
+
}
|
|
17
|
+
function athenaType(schema, path3) {
|
|
18
|
+
let current = schema;
|
|
19
|
+
while (current._def?.typeName === "ZodOptional" || current._def?.typeName === "ZodNullable" || current._def?.typeName === "ZodDefault") {
|
|
20
|
+
const innerType = current._def?.innerType;
|
|
21
|
+
if (!innerType) break;
|
|
22
|
+
current = innerType;
|
|
23
|
+
}
|
|
24
|
+
switch (current._def?.typeName) {
|
|
25
|
+
case "ZodString":
|
|
26
|
+
return current._def.checks?.some((check) => check.kind === "datetime") ? "timestamp" : "string";
|
|
27
|
+
case "ZodNumber":
|
|
28
|
+
return "double";
|
|
29
|
+
case "ZodBoolean":
|
|
30
|
+
return "boolean";
|
|
31
|
+
case "ZodDate":
|
|
32
|
+
return "timestamp";
|
|
33
|
+
case "ZodArray":
|
|
34
|
+
case "ZodObject":
|
|
35
|
+
return "json";
|
|
36
|
+
default:
|
|
37
|
+
throw new Error(
|
|
38
|
+
`Unsupported analytics schema field ${path3}. Supported types are string, number, boolean, datetime, arrays, and objects.`
|
|
39
|
+
);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
function columns(schema, path3) {
|
|
43
|
+
if (!schema.shape) {
|
|
44
|
+
throw new Error(`Analytics schema ${path3} must be a Zod object.`);
|
|
45
|
+
}
|
|
46
|
+
const names = /* @__PURE__ */ new Map();
|
|
47
|
+
return Object.entries(schema.shape).map(([sourceName, field]) => {
|
|
48
|
+
const name = normalizeSqlIdentifier(sourceName);
|
|
49
|
+
const existing = names.get(name);
|
|
50
|
+
if (existing) {
|
|
51
|
+
throw new Error(
|
|
52
|
+
`Analytics column identifier collision in ${path3}: ${existing} and ${sourceName} both normalize to ${name}.`
|
|
53
|
+
);
|
|
54
|
+
}
|
|
55
|
+
names.set(name, sourceName);
|
|
56
|
+
return {
|
|
57
|
+
name,
|
|
58
|
+
sourceName,
|
|
59
|
+
type: athenaType(field, `${path3}.${sourceName}`)
|
|
60
|
+
};
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
function fingerprint(datasets) {
|
|
64
|
+
return createHash("sha256").update(JSON.stringify(datasets)).digest("hex");
|
|
65
|
+
}
|
|
66
|
+
function validateSchemaEvolution(previous, next) {
|
|
67
|
+
const nextDatasets = new Map(
|
|
68
|
+
next.datasets.map((dataset) => [dataset.identifier, dataset])
|
|
69
|
+
);
|
|
70
|
+
for (const previousDataset of previous.datasets) {
|
|
71
|
+
const nextDataset = nextDatasets.get(previousDataset.identifier);
|
|
72
|
+
if (!nextDataset) {
|
|
73
|
+
throw new Error(
|
|
74
|
+
`Analytics dataset ${previousDataset.name} was removed. Supply an explicit analytics migration.`
|
|
75
|
+
);
|
|
76
|
+
}
|
|
77
|
+
const nextColumns = new Map(
|
|
78
|
+
nextDataset.columns.map((column) => [column.name, column])
|
|
79
|
+
);
|
|
80
|
+
for (const previousColumn of previousDataset.columns) {
|
|
81
|
+
const nextColumn = nextColumns.get(previousColumn.name);
|
|
82
|
+
if (!nextColumn) {
|
|
83
|
+
throw new Error(
|
|
84
|
+
`Analytics field ${previousDataset.name}.${previousColumn.sourceName} was removed or renamed. Supply an explicit analytics migration.`
|
|
85
|
+
);
|
|
86
|
+
}
|
|
87
|
+
if (nextColumn.type !== previousColumn.type) {
|
|
88
|
+
throw new Error(
|
|
89
|
+
`Analytics field ${previousDataset.name}.${previousColumn.sourceName} changed from ${previousColumn.type} to ${nextColumn.type}. Supply an explicit analytics migration.`
|
|
90
|
+
);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
function createAnalyticsManifest(configs) {
|
|
96
|
+
const datasets = [];
|
|
97
|
+
const unnamedMutuals = /* @__PURE__ */ new Set();
|
|
98
|
+
const identifiers = /* @__PURE__ */ new Map();
|
|
99
|
+
const mutuals = /* @__PURE__ */ new Set();
|
|
100
|
+
const addDataset = (kind, name, schema) => {
|
|
101
|
+
if (!lowerKebabCase.test(name)) {
|
|
102
|
+
throw new Error(
|
|
103
|
+
`Invalid analytics ${kind} name: ${name}. Must be lower-kebab-case.`
|
|
104
|
+
);
|
|
105
|
+
}
|
|
106
|
+
const identifier = normalizeSqlIdentifier(name);
|
|
107
|
+
const existing = identifiers.get(identifier);
|
|
108
|
+
if (existing) {
|
|
109
|
+
throw new Error(
|
|
110
|
+
`Analytics dataset identifier collision: ${existing} and ${name} both normalize to ${identifier}.`
|
|
111
|
+
);
|
|
112
|
+
}
|
|
113
|
+
identifiers.set(identifier, name);
|
|
114
|
+
datasets.push({
|
|
115
|
+
kind,
|
|
116
|
+
name,
|
|
117
|
+
identifier,
|
|
118
|
+
currentTable: `${identifier}_${kind === "entity" ? "entities" : "mutuals"}`,
|
|
119
|
+
historyTable: `${identifier}_${kind === "entity" ? "entity_changes" : "mutual_changes"}`,
|
|
120
|
+
columns: columns(schema, `${kind} ${name}`),
|
|
121
|
+
partition: { granularity: "day" }
|
|
122
|
+
});
|
|
123
|
+
};
|
|
124
|
+
for (const config of configs) {
|
|
125
|
+
addDataset("entity", config.name, config.finalSchema);
|
|
126
|
+
for (const field of Object.values(config.mutual?.mutualFields ?? {})) {
|
|
127
|
+
const mutual = field.mutual;
|
|
128
|
+
if (!mutual?.name) {
|
|
129
|
+
unnamedMutuals.add(`${config.name}.${field.entityType}`);
|
|
130
|
+
continue;
|
|
131
|
+
}
|
|
132
|
+
if (mutuals.has(mutual)) continue;
|
|
133
|
+
mutuals.add(mutual);
|
|
134
|
+
addDataset("mutual", mutual.name, mutual.mutualDataSchema);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
return {
|
|
138
|
+
version: 1,
|
|
139
|
+
datasets,
|
|
140
|
+
unnamedMutuals: [...unnamedMutuals].sort(),
|
|
141
|
+
schemaFingerprint: fingerprint(datasets)
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// cli.ts
|
|
9
146
|
import { fileURLToPath } from "url";
|
|
10
147
|
|
|
11
148
|
// commands/utils/detect-package.ts
|
|
@@ -78,6 +215,7 @@ export enum Entity {}
|
|
|
78
215
|
const schemaEntries = [];
|
|
79
216
|
const allowedEntityEntries = [];
|
|
80
217
|
const entityWithEmailAuthEntries = [];
|
|
218
|
+
const analyticsConfigs = [];
|
|
81
219
|
const relativePathToConfigDir = path2.relative(monoriseOutputDir, configDir);
|
|
82
220
|
const importPathPrefix = relativePathToConfigDir ? `${relativePathToConfigDir}/` : "./";
|
|
83
221
|
for (const file of files) {
|
|
@@ -93,6 +231,7 @@ export enum Entity {}
|
|
|
93
231
|
throw new Error(`Duplicate name found: ${config.name} in ${file}`);
|
|
94
232
|
}
|
|
95
233
|
names.add(config.name);
|
|
234
|
+
analyticsConfigs.push(config);
|
|
96
235
|
const fileName = file.replace(/\.ts$/, "");
|
|
97
236
|
const variableName = kebabToCamel(fileName);
|
|
98
237
|
imports.push(
|
|
@@ -128,7 +267,7 @@ declare module '${moduleName}' {
|
|
|
128
267
|
${schemaMapEntries.join("\n ")}
|
|
129
268
|
}
|
|
130
269
|
}`;
|
|
131
|
-
const moduleAugmentations = usesCombinedPackage ? augmentationBlock("monorise/base") : augmentationBlock("
|
|
270
|
+
const moduleAugmentations = usesCombinedPackage ? augmentationBlock("monorise/base") : augmentationBlock("../base/index.js");
|
|
132
271
|
const configOutputContent = `
|
|
133
272
|
import type { z } from 'zod';
|
|
134
273
|
${imports.join("\n")}
|
|
@@ -175,6 +314,19 @@ export default config;
|
|
|
175
314
|
${moduleAugmentations}
|
|
176
315
|
`;
|
|
177
316
|
fs2.writeFileSync(configOutputPath, configOutputContent);
|
|
317
|
+
const analyticsManifestPath = path2.join(
|
|
318
|
+
monoriseOutputDir,
|
|
319
|
+
"analytics-manifest.json"
|
|
320
|
+
);
|
|
321
|
+
const manifest = createAnalyticsManifest(analyticsConfigs);
|
|
322
|
+
if (fs2.existsSync(analyticsManifestPath)) {
|
|
323
|
+
validateSchemaEvolution(
|
|
324
|
+
JSON.parse(fs2.readFileSync(analyticsManifestPath, "utf8")),
|
|
325
|
+
manifest
|
|
326
|
+
);
|
|
327
|
+
}
|
|
328
|
+
fs2.writeFileSync(analyticsManifestPath, `${JSON.stringify(manifest, null, 2)}
|
|
329
|
+
`);
|
|
178
330
|
console.log("Successfully generated config.ts!");
|
|
179
331
|
const indexOutputPath = path2.join(monoriseOutputDir, "index.ts");
|
|
180
332
|
fs2.writeFileSync(
|
|
@@ -227,7 +379,7 @@ async function generateHandleFile(monoriseConfig, projectRoot, monoriseOutputDir
|
|
|
227
379
|
appHandlerPayload = "{ routes }";
|
|
228
380
|
}
|
|
229
381
|
const usesCombinedPackage = detectCombinedPackage(projectRoot);
|
|
230
|
-
const coreImportPath = usesCombinedPackage ? "monorise/core" : "
|
|
382
|
+
const coreImportPath = usesCombinedPackage ? "monorise/core" : "../core/index.js";
|
|
231
383
|
const combinedContent = `
|
|
232
384
|
import CoreFactory from '${coreImportPath}';
|
|
233
385
|
import config from './config';
|
|
@@ -235,6 +387,9 @@ ${routesImportLine ? `${routesImportLine}
|
|
|
235
387
|
` : ""}const coreFactory = new CoreFactory(config);
|
|
236
388
|
|
|
237
389
|
export const replicationHandler = coreFactory.replicationProcessor;
|
|
390
|
+
export const analyticsHandler = coreFactory.analyticsProcessor;
|
|
391
|
+
export const analyticsBackfillHandler = coreFactory.analyticsBackfillProcessor;
|
|
392
|
+
export { analyticsMaterializationProcessor as analyticsMaterializationHandler } from '${coreImportPath}';
|
|
238
393
|
export const mutualHandler = coreFactory.mutualProcessor;
|
|
239
394
|
export const tagHandler = coreFactory.tagProcessor;
|
|
240
395
|
export const treeHandler = coreFactory.prejoinProcessor;
|
package/dist/cli/cli.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../cli.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 { fileURLToPath } from 'node:url';\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 {}\n`;\n fs.writeFileSync(configOutputPath, initialConfigContent);\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\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\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\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}`;\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 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): 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 routesModule;\n try {\n routesModule = await import(absoluteCustomRoutesPath);\n } catch (e: any) {\n throw new Error(\n `Failed to load custom routes file at '${absoluteCustomRoutesPath}'. Ensure it's a valid JavaScript/TypeScript module. Error: ${e.message}`,\n );\n }\n\n const routesExport = routesModule.default;\n\n if (\n !routesExport ||\n routesExport === null ||\n (typeof routesExport === 'object' &&\n !(\n 'get' in routesExport &&\n 'post' in routesExport &&\n 'use' in routesExport\n ))\n ) {\n throw new Error(\n `Custom routes file at '${absoluteCustomRoutesPath}' must default export an instance of Hono (or an object with .get, .post, .use methods). Or a function that consume the dependency container provided by route handler.`,\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\n const combinedContent = `\nimport CoreFactory from '${coreImportPath}';\nimport config from './config';\n${routesImportLine ? `${routesImportLine}\\n` : ''}const coreFactory = new CoreFactory(config);\n\nexport const replicationHandler = coreFactory.replicationProcessor;\nexport const mutualHandler = coreFactory.mutualProcessor;\nexport const tagHandler = coreFactory.tagProcessor;\nexport const treeHandler = coreFactory.prejoinProcessor;\nexport const appHandler = coreFactory.appHandler(${appHandlerPayload});\n`;\n fs.writeFileSync(handleOutputPath, combinedContent);\n console.log('Successfully generated handle.ts!');\n\n return handleOutputPath;\n}\n\nasync function generateFiles(rootPath?: string): Promise<string> {\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 await generateConfigFile(configDir, monoriseOutputDir, projectRoot);\n await generateHandleFile(monoriseConfig, projectRoot, monoriseOutputDir);\n\n return configDir;\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 API proxy routes\n console.log('🔀 Creating API proxy routes...');\n const apiDir = path.join(appDir, 'api');\n const catchAllDir = path.join(apiDir, '[...proxy]');\n fs.mkdirSync(catchAllDir, { recursive: true });\n fs.writeFileSync(\n path.join(apiDir, 'proxy-request.ts'),\n readTemplate('proxy-request.ts'),\n );\n fs.writeFileSync(\n path.join(catchAllDir, 'route.ts'),\n readTemplate('proxy-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(configDir: string, rootPath?: string) {\n console.log(MONORISE_LOGO);\n console.log(`Watching for changes in ${configDir}...`);\n const watcher = chokidar.watch(configDir, {\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 const configDir = await generateFiles(rootPath);\n await runDevCommand(configDir, 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 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;AACrB,SAAS,qBAAqB;;;ACP9B,OAAO,QAAQ;AACf,OAAO,UAAU;AAOV,SAAS,sBAAsB,UAA2B;AAC/D,MAAI,MAAM;AACV,SAAO,MAAM;AACX,QAAI,GAAG,WAAW,KAAK,KAAK,KAAK,gBAAgB,UAAU,CAAC,GAAG;AAC7D,aAAO;AAAA,IACT;AACA,UAAM,SAAS,KAAK,QAAQ,GAAG;AAC/B,QAAI,WAAW,IAAK;AACpB,UAAM;AAAA,EACR;AACA,SAAO;AACT;;;ACnBO,IAAM,yBAAyB;AAAA,EACpC,iBAAiB;AAAA,IACf,QAAQ;AAAA,IACR,QAAQ;AAAA,IACR,kBAAkB;AAAA,IAClB,iBAAiB;AAAA,IACjB,QAAQ;AAAA,IACR,cAAc;AAAA,IACd,KAAK;AAAA,IACL,OAAO;AAAA,MACL,cAAc,CAAC,YAAY;AAAA,MAC3B,gB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;AAChB,CAAC;","names":["fs","path","path","fs"]}
|
|
1
|
+
{"version":3,"sources":["../cli.ts","../commands/utils/analytics-manifest.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 createAnalyticsManifest,\n validateSchemaEvolution,\n type AnalyticsConfig,\n type AnalyticsManifest,\n} from './commands/utils/analytics-manifest';\nimport { fileURLToPath } from 'node:url';\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 {}\n`;\n fs.writeFileSync(configOutputPath, initialConfigContent);\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\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\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}`;\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 const analyticsManifestPath = path.join(\n monoriseOutputDir,\n 'analytics-manifest.json',\n );\n const manifest = createAnalyticsManifest(analyticsConfigs);\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 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): 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 routesModule;\n try {\n routesModule = await import(absoluteCustomRoutesPath);\n } catch (e: any) {\n throw new Error(\n `Failed to load custom routes file at '${absoluteCustomRoutesPath}'. Ensure it's a valid JavaScript/TypeScript module. Error: ${e.message}`,\n );\n }\n\n const routesExport = routesModule.default;\n\n if (\n !routesExport ||\n routesExport === null ||\n (typeof routesExport === 'object' &&\n !(\n 'get' in routesExport &&\n 'post' in routesExport &&\n 'use' in routesExport\n ))\n ) {\n throw new Error(\n `Custom routes file at '${absoluteCustomRoutesPath}' must default export an instance of Hono (or an object with .get, .post, .use methods). Or a function that consume the dependency container provided by route handler.`,\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\n const combinedContent = `\nimport CoreFactory from '${coreImportPath}';\nimport config from './config';\n${routesImportLine ? `${routesImportLine}\\n` : ''}const coreFactory = new CoreFactory(config);\n\nexport const replicationHandler = coreFactory.replicationProcessor;\nexport const analyticsHandler = coreFactory.analyticsProcessor;\nexport const analyticsBackfillHandler = coreFactory.analyticsBackfillProcessor;\nexport { analyticsMaterializationProcessor as analyticsMaterializationHandler } from '${coreImportPath}';\nexport const mutualHandler = coreFactory.mutualProcessor;\nexport const tagHandler = coreFactory.tagProcessor;\nexport const treeHandler = coreFactory.prejoinProcessor;\nexport const appHandler = coreFactory.appHandler(${appHandlerPayload});\n`;\n fs.writeFileSync(handleOutputPath, combinedContent);\n console.log('Successfully generated handle.ts!');\n\n return handleOutputPath;\n}\n\nasync function generateFiles(rootPath?: string): Promise<string> {\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 await generateConfigFile(configDir, monoriseOutputDir, projectRoot);\n await generateHandleFile(monoriseConfig, projectRoot, monoriseOutputDir);\n\n return configDir;\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 API proxy routes\n console.log('🔀 Creating API proxy routes...');\n const apiDir = path.join(appDir, 'api');\n const catchAllDir = path.join(apiDir, '[...proxy]');\n fs.mkdirSync(catchAllDir, { recursive: true });\n fs.writeFileSync(\n path.join(apiDir, 'proxy-request.ts'),\n readTemplate('proxy-request.ts'),\n );\n fs.writeFileSync(\n path.join(catchAllDir, 'route.ts'),\n readTemplate('proxy-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(configDir: string, rootPath?: string) {\n console.log(MONORISE_LOGO);\n console.log(`Watching for changes in ${configDir}...`);\n const watcher = chokidar.watch(configDir, {\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 const configDir = await generateFiles(rootPath);\n await runDevCommand(configDir, 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';\n\ntype ZodSchema = {\n _def?: {\n typeName?: string;\n innerType?: ZodSchema;\n schema?: ZodSchema;\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 currentTable: string;\n historyTable: string;\n columns: AnalyticsColumn[];\n partition: { granularity: 'day' };\n};\n\nexport type AnalyticsManifest = {\n version: 1;\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 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 while (\n current._def?.typeName === 'ZodOptional' ||\n current._def?.typeName === 'ZodNullable' ||\n current._def?.typeName === 'ZodDefault'\n ) {\n const innerType = current._def?.innerType;\n if (!innerType) break;\n current = innerType;\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 'ZodArray':\n case 'ZodObject':\n return 'json';\n default:\n throw new Error(\n `Unsupported analytics schema field ${path}. Supported types are string, number, boolean, datetime, arrays, and objects.`,\n );\n }\n}\n\nfunction columns(schema: ZodSchema, path: string): AnalyticsColumn[] {\n if (!schema.shape) {\n throw new Error(`Analytics schema ${path} must be a Zod object.`);\n }\n\n const names = new Map<string, string>();\n return Object.entries(schema.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 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 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\n const addDataset = (\n kind: AnalyticsDataset['kind'],\n name: string,\n schema: ZodSchema,\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 datasets.push({\n kind,\n name,\n identifier,\n currentTable: `${identifier}_${kind === 'entity' ? 'entities' : 'mutuals'}`,\n historyTable: `${identifier}_${kind === 'entity' ? 'entity_changes' : 'mutual_changes'}`,\n columns: columns(schema, `${kind} ${name}`),\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 addDataset('mutual', mutual.name, mutual.mutualDataSchema);\n }\n }\n\n return {\n version: 1,\n datasets,\n unnamedMutuals: [...unnamedMutuals].sort(),\n schemaFingerprint: fingerprint(datasets),\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;AAmD3B,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,SACE,QAAQ,MAAM,aAAa,iBAC3B,QAAQ,MAAM,aAAa,iBAC3B,QAAQ,MAAM,aAAa,cAC3B;AACA,UAAM,YAAY,QAAQ,MAAM;AAChC,QAAI,CAAC,UAAW;AAChB,cAAU;AAAA,EACZ;AAEA,UAAQ,QAAQ,MAAM,UAAU;AAAA,IAC9B,KAAK;AACH,aAAO,QAAQ,KAAK,QAAQ,KAAK,CAAC,UAAU,MAAM,SAA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