monorise 1.3.0 → 1.5.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 +95 -1
- package/dist/base/index.js.map +1 -1
- package/dist/cli/cli.js +295 -102
- package/dist/cli/cli.js.map +1 -1
- package/dist/cli/templates/files/core-routes.ts +22 -0
- package/dist/cli/templates/files/example-page.tsx +103 -0
- package/dist/cli/templates/files/global-initializer.tsx +16 -0
- package/dist/cli/templates/files/global-loader.tsx +45 -0
- package/dist/cli/templates/files/globals.css +72 -0
- package/dist/cli/templates/files/lib-utils.ts +6 -0
- package/dist/cli/templates/files/monorise.config.ts +7 -0
- package/dist/cli/templates/files/proxy-request.ts +49 -0
- package/dist/cli/templates/files/proxy-route.ts +22 -0
- package/dist/cli/templates/files/sst.config.ts +30 -0
- package/dist/cli/templates/files/team-entity.ts +37 -0
- package/dist/cli/templates/files/team-membership.mutual.ts +16 -0
- package/dist/cli/templates/files/ui-button.tsx +65 -0
- package/dist/cli/templates/files/ui-card.tsx +103 -0
- package/dist/cli/templates/files/ui-input.tsx +19 -0
- package/dist/cli/templates/files/ui-label.tsx +24 -0
- package/dist/cli/templates/files/user-entity.ts +43 -0
- package/dist/core/index.d.ts +13 -28
- package/dist/core/index.js +205 -26
- package/dist/core/index.js.map +1 -1
- package/dist/react/index.d.ts +6 -2
- package/dist/react/index.d.ts.map +1 -1
- package/dist/react/index.js +2 -1
- package/dist/react/index.js.map +1 -1
- package/dist/react/services/core.service.d.ts +3 -1
- package/dist/react/services/core.service.d.ts.map +1 -1
- package/package.json +1 -1
package/dist/base/index.d.ts
CHANGED
|
@@ -1,5 +1,29 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
2
|
|
|
3
|
+
type WhereOperator = {
|
|
4
|
+
$eq: string | number | boolean;
|
|
5
|
+
} | {
|
|
6
|
+
$ne: string | number | boolean;
|
|
7
|
+
} | {
|
|
8
|
+
$gt: number;
|
|
9
|
+
} | {
|
|
10
|
+
$lt: number;
|
|
11
|
+
} | {
|
|
12
|
+
$gte: number;
|
|
13
|
+
} | {
|
|
14
|
+
$lte: number;
|
|
15
|
+
} | {
|
|
16
|
+
$exists: boolean;
|
|
17
|
+
} | {
|
|
18
|
+
$beginsWith: string;
|
|
19
|
+
};
|
|
20
|
+
type WhereClause = WhereOperator | string | number | boolean;
|
|
21
|
+
type WhereConditions = Record<string, WhereClause>;
|
|
22
|
+
type AdjustmentConditionFn<B extends z.ZodRawShape = z.ZodRawShape> = (data: Partial<z.infer<z.ZodObject<B>>>, adjustments: Record<string, number>) => WhereConditions;
|
|
23
|
+
type AdjustmentCondition<B extends z.ZodRawShape = z.ZodRawShape> = WhereConditions | AdjustmentConditionFn<B>;
|
|
24
|
+
type UpdateConditionFn<B extends z.ZodRawShape = z.ZodRawShape> = (data: Partial<z.infer<z.ZodObject<B>>>) => WhereConditions;
|
|
25
|
+
type UpdateCondition<B extends z.ZodRawShape = z.ZodRawShape> = WhereConditions | UpdateConditionFn<B>;
|
|
26
|
+
|
|
3
27
|
declare enum Entity {
|
|
4
28
|
}
|
|
5
29
|
interface EntitySchemaMap {
|
|
@@ -284,6 +308,8 @@ interface MonoriseEntityConfig<T extends Entity = Entity, B extends z.ZodRawShap
|
|
|
284
308
|
* When adjusting numeric fields, these constraints are enforced at the database level.
|
|
285
309
|
* If an adjustment would violate a constraint, the operation is rejected.
|
|
286
310
|
*
|
|
311
|
+
* @deprecated Use `conditions` instead. Will be removed in a future version.
|
|
312
|
+
*
|
|
287
313
|
* @example
|
|
288
314
|
* ```ts
|
|
289
315
|
* {
|
|
@@ -319,6 +345,67 @@ interface MonoriseEntityConfig<T extends Entity = Entity, B extends z.ZodRawShap
|
|
|
319
345
|
};
|
|
320
346
|
};
|
|
321
347
|
};
|
|
348
|
+
/**
|
|
349
|
+
* @description Named conditions for adjustEntity operations.
|
|
350
|
+
* Each condition is either a static `WhereConditions` object or a function
|
|
351
|
+
* `(data, adjustments) => WhereConditions` that receives the entity's current data
|
|
352
|
+
* and the adjustment deltas.
|
|
353
|
+
*
|
|
354
|
+
* When defined, `$condition` is **required** in the adjustEntity request body.
|
|
355
|
+
* The client sends a condition name (string), the server resolves it to a
|
|
356
|
+
* DynamoDB ConditionExpression.
|
|
357
|
+
*
|
|
358
|
+
* @example
|
|
359
|
+
* ```ts
|
|
360
|
+
* {
|
|
361
|
+
* adjustmentConditions: {
|
|
362
|
+
* withdraw: (data, adjustments) => ({
|
|
363
|
+
* balance: { $gte: (data.minBalance ?? 0) + Math.abs(adjustments?.balance ?? 0) },
|
|
364
|
+
* }),
|
|
365
|
+
* deposit: (data, adjustments) => ({
|
|
366
|
+
* balance: { $lte: 1000000 - (adjustments.balance ?? 0) },
|
|
367
|
+
* }),
|
|
368
|
+
* }
|
|
369
|
+
* }
|
|
370
|
+
* ```
|
|
371
|
+
*/
|
|
372
|
+
adjustmentConditions?: {
|
|
373
|
+
[conditionName: string]: WhereConditions | ((data: Partial<z.infer<z.ZodObject<B>>>, adjustments: Record<string, number>) => WhereConditions);
|
|
374
|
+
};
|
|
375
|
+
/**
|
|
376
|
+
* @description Named conditions for updateEntity operations.
|
|
377
|
+
* Each condition is either a static `WhereConditions` object or a function
|
|
378
|
+
* `(data) => WhereConditions` that receives the entity's current data.
|
|
379
|
+
*
|
|
380
|
+
* `$condition` is always **optional** for updateEntity.
|
|
381
|
+
* The client sends a condition name (string), the server resolves it to a
|
|
382
|
+
* DynamoDB ConditionExpression. Replaces raw `$where` (deprecated).
|
|
383
|
+
*
|
|
384
|
+
* @example
|
|
385
|
+
* ```ts
|
|
386
|
+
* {
|
|
387
|
+
* updateConditions: {
|
|
388
|
+
* publish: { status: { $eq: 'draft' } },
|
|
389
|
+
* archive: (data) => ({ status: { $ne: 'archived' } }),
|
|
390
|
+
* }
|
|
391
|
+
* }
|
|
392
|
+
* ```
|
|
393
|
+
*/
|
|
394
|
+
updateConditions?: {
|
|
395
|
+
[conditionName: string]: WhereConditions | ((data: Partial<z.infer<z.ZodObject<B>>>) => WhereConditions);
|
|
396
|
+
};
|
|
397
|
+
/**
|
|
398
|
+
* @description (Optional) Opt in to accepting legacy raw `$where` on updateEntity.
|
|
399
|
+
* Disabled by default: raw DynamoDB condition operators must never be
|
|
400
|
+
* client-facing — an authenticated client could otherwise probe field
|
|
401
|
+
* existence or guess values via the 200-vs-409 response status.
|
|
402
|
+
*
|
|
403
|
+
* Only enable this if you trust the caller (e.g. server-to-server) or have
|
|
404
|
+
* your own validation in front of it. Prefer `updateConditions` instead.
|
|
405
|
+
*
|
|
406
|
+
* @default false
|
|
407
|
+
*/
|
|
408
|
+
allowLegacyWhere?: boolean;
|
|
322
409
|
}
|
|
323
410
|
|
|
324
411
|
declare const createEntityConfig: <T extends Entity, B extends z.ZodRawShape, C extends z.ZodRawShape, M extends z.ZodRawShape, CO extends z.ZodObject<C> | undefined = undefined, MO extends z.ZodObject<M> | undefined = undefined>(config: MonoriseEntityConfig<T, B, C, M, CO, MO>) => {
|
|
@@ -388,7 +475,14 @@ declare const createEntityConfig: <T extends Entity, B extends z.ZodRawShape, C
|
|
|
388
475
|
maxField?: (keyof { [K_2 in keyof B as B[K_2] extends z.ZodNumber | z.ZodOptional<z.ZodNumber> ? K_2 : never]: K_2; } extends never ? string : keyof { [K_3 in keyof B as B[K_3] extends z.ZodNumber | z.ZodOptional<z.ZodNumber> ? K_3 : never]: K_3; }) | undefined;
|
|
389
476
|
};
|
|
390
477
|
} | undefined;
|
|
478
|
+
adjustmentConditions?: {
|
|
479
|
+
[conditionName: string]: undefined | ((data: Partial<z.objectUtil.addQuestionMarks<z.baseObjectOutputType<B>, any> extends infer T_27 ? { [k_4 in keyof T_27]: T_27[k_4]; } : never>, adjustments: Record<string, number>) => undefined);
|
|
480
|
+
} | undefined;
|
|
481
|
+
updateConditions?: {
|
|
482
|
+
[conditionName: string]: undefined | ((data: Partial<z.objectUtil.addQuestionMarks<z.baseObjectOutputType<B>, any> extends infer T_27 ? { [k_4 in keyof T_27]: T_27[k_4]; } : never>) => undefined);
|
|
483
|
+
} | undefined;
|
|
484
|
+
allowLegacyWhere?: boolean;
|
|
391
485
|
};
|
|
392
486
|
declare const createMutualConfig: <MD extends z.ZodRawShape>(config: MutualConfig<MD>) => MutualConfig<MD>;
|
|
393
487
|
|
|
394
|
-
export { type CreatedEntity, type DraftEntity, Entity, type EntitySchemaMap, type MonoriseEntityConfig, type MutualConfig, type NumericFields, createEntityConfig, createMutualConfig };
|
|
488
|
+
export { type AdjustmentCondition, type AdjustmentConditionFn, type CreatedEntity, type DraftEntity, Entity, type EntitySchemaMap, type MonoriseEntityConfig, type MutualConfig, type NumericFields, type UpdateCondition, type UpdateConditionFn, type WhereClause, type WhereConditions, type WhereOperator, createEntityConfig, createMutualConfig };
|
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';\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 * @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","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":";;;;;;;;;;;;;;;;;;;;;AAEO,IAAK,SAAL,kBAAKA,YAAL;AAAK,SAAAA;AAAA,GAAA;;;ACDZ,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 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
|
@@ -2,10 +2,11 @@
|
|
|
2
2
|
|
|
3
3
|
// cli.ts
|
|
4
4
|
import "tsx";
|
|
5
|
-
import "tsconfig-paths/register.js";
|
|
6
5
|
import fs2 from "fs";
|
|
7
6
|
import path2 from "path";
|
|
7
|
+
import { execSync } from "child_process";
|
|
8
8
|
import chokidar from "chokidar";
|
|
9
|
+
import { fileURLToPath } from "url";
|
|
9
10
|
|
|
10
11
|
// commands/utils/detect-package.ts
|
|
11
12
|
import fs from "fs";
|
|
@@ -23,13 +24,43 @@ function detectCombinedPackage(startDir) {
|
|
|
23
24
|
return false;
|
|
24
25
|
}
|
|
25
26
|
|
|
27
|
+
// templates/root-tsconfig.ts
|
|
28
|
+
var ROOT_TSCONFIG_TEMPLATE = {
|
|
29
|
+
compilerOptions: {
|
|
30
|
+
target: "ES2022",
|
|
31
|
+
module: "ESNext",
|
|
32
|
+
moduleResolution: "bundler",
|
|
33
|
+
esModuleInterop: true,
|
|
34
|
+
strict: true,
|
|
35
|
+
skipLibCheck: true,
|
|
36
|
+
jsx: "preserve",
|
|
37
|
+
paths: {
|
|
38
|
+
"#/shared/*": ["./shared/*"],
|
|
39
|
+
"#/monorise/*": ["./.monorise/*"],
|
|
40
|
+
"#/monorise": ["./.monorise/index"]
|
|
41
|
+
}
|
|
42
|
+
},
|
|
43
|
+
include: ["**/*.ts", ".monorise/**/*.ts"],
|
|
44
|
+
exclude: ["node_modules", "apps"]
|
|
45
|
+
};
|
|
46
|
+
|
|
26
47
|
// cli.ts
|
|
48
|
+
var __filename = fileURLToPath(import.meta.url);
|
|
49
|
+
var __dirname = path2.dirname(__filename);
|
|
50
|
+
var TEMPLATES_DIR = path2.join(__dirname, "templates", "files");
|
|
51
|
+
function readTemplate(filename) {
|
|
52
|
+
return fs2.readFileSync(path2.join(TEMPLATES_DIR, filename), "utf-8");
|
|
53
|
+
}
|
|
27
54
|
function kebabToCamel(str) {
|
|
28
55
|
return str.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());
|
|
29
56
|
}
|
|
30
57
|
function kebabToPascal(kebab) {
|
|
31
58
|
return kebab.split("-").map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join("");
|
|
32
59
|
}
|
|
60
|
+
function execCommand(command, cwd, stdio = "inherit") {
|
|
61
|
+
console.log(`Running: ${command}`);
|
|
62
|
+
execSync(command, { cwd, stdio });
|
|
63
|
+
}
|
|
33
64
|
async function generateConfigFile(configDir, monoriseOutputDir, projectRoot) {
|
|
34
65
|
const configOutputPath = path2.join(monoriseOutputDir, "config.ts");
|
|
35
66
|
const initialConfigContent = `
|
|
@@ -145,6 +176,14 @@ ${moduleAugmentations}
|
|
|
145
176
|
`;
|
|
146
177
|
fs2.writeFileSync(configOutputPath, configOutputContent);
|
|
147
178
|
console.log("Successfully generated config.ts!");
|
|
179
|
+
const indexOutputPath = path2.join(monoriseOutputDir, "index.ts");
|
|
180
|
+
fs2.writeFileSync(
|
|
181
|
+
indexOutputPath,
|
|
182
|
+
`export * from './config';
|
|
183
|
+
export { default } from './config';
|
|
184
|
+
`
|
|
185
|
+
);
|
|
186
|
+
console.log("Successfully generated index.ts!");
|
|
148
187
|
return configOutputPath;
|
|
149
188
|
}
|
|
150
189
|
async function generateHandleFile(monoriseConfig, projectRoot, monoriseOutputDir) {
|
|
@@ -278,123 +317,277 @@ var MONORISE_LOGO = `
|
|
|
278
317
|
|
|
279
318
|
`;
|
|
280
319
|
async function runInitCommand(rootPath) {
|
|
281
|
-
const projectRoot = rootPath ? path2.resolve(rootPath) : process.cwd();
|
|
282
320
|
console.log(MONORISE_LOGO);
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
// custom route file should export default an Hono object.
|
|
289
|
-
// customRoutes: './path/to/custom/routes.ts'
|
|
290
|
-
};
|
|
291
|
-
|
|
292
|
-
export default config;
|
|
293
|
-
`;
|
|
294
|
-
if (!fs2.existsSync(monoriseConfigTsPath)) {
|
|
295
|
-
fs2.writeFileSync(monoriseConfigTsPath, monoriseConfigContent.trimStart());
|
|
296
|
-
console.log(`Created ${path2.relative(projectRoot, monoriseConfigTsPath)}`);
|
|
321
|
+
let projectName = "my-app";
|
|
322
|
+
let projectRoot;
|
|
323
|
+
if (rootPath) {
|
|
324
|
+
projectRoot = path2.resolve(rootPath);
|
|
325
|
+
projectName = path2.basename(projectRoot);
|
|
297
326
|
} else {
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
)
|
|
327
|
+
const args = process.argv.slice(2);
|
|
328
|
+
const nameIndex = args.indexOf("--name");
|
|
329
|
+
if (nameIndex > -1 && args[nameIndex + 1]) {
|
|
330
|
+
projectName = args[nameIndex + 1];
|
|
331
|
+
}
|
|
332
|
+
projectRoot = path2.resolve(projectName);
|
|
301
333
|
}
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
.
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
334
|
+
console.log(`
|
|
335
|
+
\u{1F680} Creating Monorise project: ${projectName}
|
|
336
|
+
`);
|
|
337
|
+
if (fs2.existsSync(projectRoot)) {
|
|
338
|
+
console.error(`Error: Directory ${projectName} already exists.`);
|
|
339
|
+
process.exit(1);
|
|
340
|
+
}
|
|
341
|
+
console.log("\u{1F4C1} Creating project structure...");
|
|
342
|
+
fs2.mkdirSync(projectRoot, { recursive: true });
|
|
343
|
+
fs2.mkdirSync(path2.join(projectRoot, "apps"), { recursive: true });
|
|
344
|
+
fs2.mkdirSync(path2.join(projectRoot, "services", "core"), { recursive: true });
|
|
345
|
+
fs2.mkdirSync(path2.join(projectRoot, "monorise", "configs"), { recursive: true });
|
|
346
|
+
fs2.mkdirSync(path2.join(projectRoot, "monorise", "mutuals"), { recursive: true });
|
|
347
|
+
console.log("\u{1F4E6} Initializing root package.json...");
|
|
348
|
+
const rootPackageJson = {
|
|
349
|
+
name: projectName,
|
|
350
|
+
version: "0.0.0",
|
|
351
|
+
type: "module",
|
|
352
|
+
private: true,
|
|
353
|
+
workspaces: ["apps/*", "services/*"]
|
|
354
|
+
};
|
|
355
|
+
fs2.writeFileSync(
|
|
356
|
+
path2.join(projectRoot, "package.json"),
|
|
357
|
+
JSON.stringify(rootPackageJson, null, 2)
|
|
358
|
+
);
|
|
359
|
+
console.log("\u2699\uFE0F Creating root tsconfig.json...");
|
|
360
|
+
fs2.writeFileSync(
|
|
361
|
+
path2.join(projectRoot, "tsconfig.json"),
|
|
362
|
+
JSON.stringify(ROOT_TSCONFIG_TEMPLATE, null, 2)
|
|
363
|
+
);
|
|
364
|
+
console.log("\n\u{1F4F1} Creating Next.js app in apps/web...");
|
|
365
|
+
const nextAppDir = path2.join(projectRoot, "apps", "web");
|
|
366
|
+
try {
|
|
367
|
+
execCommand(
|
|
368
|
+
`npx create-next-app@latest web --typescript --tailwind --eslint --app --no-src-dir --import-alias "#/*" --no-turbopack --yes`,
|
|
369
|
+
path2.join(projectRoot, "apps")
|
|
333
370
|
);
|
|
371
|
+
} catch (error) {
|
|
372
|
+
console.error("Failed to create Next.js app:", error);
|
|
373
|
+
process.exit(1);
|
|
374
|
+
}
|
|
375
|
+
console.log("\n\u2601\uFE0F Installing SST v4...");
|
|
376
|
+
try {
|
|
377
|
+
execCommand("npm install sst@^4 --save-dev", projectRoot);
|
|
378
|
+
} catch (error) {
|
|
379
|
+
console.error("Failed to install SST:", error);
|
|
380
|
+
process.exit(1);
|
|
381
|
+
}
|
|
382
|
+
console.log("\n\u{1F4E6} Installing dependencies (monorise, hono, zod, shadcn utilities)...");
|
|
383
|
+
try {
|
|
384
|
+
execCommand("npm install monorise hono zod clsx class-variance-authority radix-ui lucide-react tailwind-merge react-hook-form @hookform/resolvers", projectRoot);
|
|
385
|
+
} catch (error) {
|
|
386
|
+
console.error("Failed to install dependencies:", error);
|
|
387
|
+
process.exit(1);
|
|
388
|
+
}
|
|
389
|
+
console.log("\u2699\uFE0F Creating monorise.config.ts...");
|
|
390
|
+
fs2.writeFileSync(
|
|
391
|
+
path2.join(projectRoot, "monorise.config.ts"),
|
|
392
|
+
readTemplate("monorise.config.ts")
|
|
393
|
+
);
|
|
394
|
+
console.log("\u{1F517} Creating team-membership mutual config...");
|
|
395
|
+
fs2.writeFileSync(
|
|
396
|
+
path2.join(projectRoot, "monorise", "mutuals", "team-membership.ts"),
|
|
397
|
+
readTemplate("team-membership.mutual.ts")
|
|
398
|
+
);
|
|
399
|
+
console.log("\u{1F464} Creating starter User entity...");
|
|
400
|
+
fs2.writeFileSync(
|
|
401
|
+
path2.join(projectRoot, "monorise", "configs", "user.ts"),
|
|
402
|
+
readTemplate("user-entity.ts")
|
|
403
|
+
);
|
|
404
|
+
console.log("\u{1F465} Creating starter Team entity...");
|
|
405
|
+
fs2.writeFileSync(
|
|
406
|
+
path2.join(projectRoot, "monorise", "configs", "team.ts"),
|
|
407
|
+
readTemplate("team-entity.ts")
|
|
408
|
+
);
|
|
409
|
+
console.log("\u{1F527} Creating services/core/routes.ts...");
|
|
410
|
+
fs2.writeFileSync(
|
|
411
|
+
path2.join(projectRoot, "services", "core", "routes.ts"),
|
|
412
|
+
readTemplate("core-routes.ts")
|
|
413
|
+
);
|
|
414
|
+
const servicesPackageJson = {
|
|
415
|
+
name: "@my-app/services",
|
|
416
|
+
version: "0.0.0",
|
|
417
|
+
type: "module"
|
|
418
|
+
};
|
|
419
|
+
fs2.writeFileSync(
|
|
420
|
+
path2.join(projectRoot, "services", "core", "package.json"),
|
|
421
|
+
JSON.stringify(servicesPackageJson, null, 2)
|
|
422
|
+
);
|
|
423
|
+
console.log("\u2699\uFE0F Creating sst.config.ts with Monorise...");
|
|
424
|
+
const sstConfigPath = path2.join(projectRoot, "sst.config.ts");
|
|
425
|
+
fs2.writeFileSync(sstConfigPath, readTemplate("sst.config.ts").replace("{{PROJECT_NAME}}", projectName));
|
|
426
|
+
console.log("\n\u2601\uFE0F Installing SST providers...");
|
|
427
|
+
try {
|
|
428
|
+
execCommand("npx sst install", projectRoot);
|
|
429
|
+
} catch (error) {
|
|
430
|
+
console.warn("Warning: SST install failed, continuing anyway...");
|
|
334
431
|
}
|
|
335
|
-
|
|
336
|
-
|
|
432
|
+
console.log("\u{1F4C4} Creating example page in apps/web...");
|
|
433
|
+
const webSrcAppDir = path2.join(projectRoot, "apps", "web", "src", "app");
|
|
434
|
+
const webAppDir = path2.join(projectRoot, "apps", "web", "app");
|
|
435
|
+
const pagePath = fs2.existsSync(webSrcAppDir) ? path2.join(webSrcAppDir, "page.tsx") : fs2.existsSync(webAppDir) ? path2.join(webAppDir, "page.tsx") : null;
|
|
436
|
+
if (pagePath) {
|
|
337
437
|
try {
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
438
|
+
fs2.writeFileSync(pagePath, readTemplate("example-page.tsx"));
|
|
439
|
+
console.log(`Created example page at ${path2.relative(projectRoot, pagePath)}`);
|
|
440
|
+
} catch (error) {
|
|
441
|
+
console.warn("Warning: Could not create example page:", error);
|
|
442
|
+
}
|
|
443
|
+
} else {
|
|
444
|
+
console.warn("Warning: Could not find apps/web/src/app or apps/web/app directory");
|
|
445
|
+
}
|
|
446
|
+
const webRoot = fs2.existsSync(webSrcAppDir) ? path2.join(projectRoot, "apps", "web", "src") : fs2.existsSync(webAppDir) ? path2.join(projectRoot, "apps", "web") : null;
|
|
447
|
+
if (webRoot) {
|
|
448
|
+
const appDir = fs2.existsSync(webSrcAppDir) ? webSrcAppDir : webAppDir;
|
|
449
|
+
fs2.mkdirSync(path2.join(webRoot, "components", "ui"), { recursive: true });
|
|
450
|
+
fs2.mkdirSync(path2.join(webRoot, "lib"), { recursive: true });
|
|
451
|
+
console.log("\u{1F310} Creating global components...");
|
|
452
|
+
fs2.writeFileSync(
|
|
453
|
+
path2.join(webRoot, "components", "global-initializer.tsx"),
|
|
454
|
+
readTemplate("global-initializer.tsx")
|
|
455
|
+
);
|
|
456
|
+
fs2.writeFileSync(
|
|
457
|
+
path2.join(webRoot, "components", "global-loader.tsx"),
|
|
458
|
+
readTemplate("global-loader.tsx")
|
|
459
|
+
);
|
|
460
|
+
console.log("\u{1F527} Creating lib/utils.ts...");
|
|
461
|
+
fs2.writeFileSync(
|
|
462
|
+
path2.join(webRoot, "lib", "utils.ts"),
|
|
463
|
+
readTemplate("lib-utils.ts")
|
|
464
|
+
);
|
|
465
|
+
console.log("\u{1F3A8} Creating shadcn UI components...");
|
|
466
|
+
fs2.writeFileSync(
|
|
467
|
+
path2.join(webRoot, "components", "ui", "button.tsx"),
|
|
468
|
+
readTemplate("ui-button.tsx")
|
|
469
|
+
);
|
|
470
|
+
fs2.writeFileSync(
|
|
471
|
+
path2.join(webRoot, "components", "ui", "card.tsx"),
|
|
472
|
+
readTemplate("ui-card.tsx")
|
|
473
|
+
);
|
|
474
|
+
fs2.writeFileSync(
|
|
475
|
+
path2.join(webRoot, "components", "ui", "input.tsx"),
|
|
476
|
+
readTemplate("ui-input.tsx")
|
|
477
|
+
);
|
|
478
|
+
fs2.writeFileSync(
|
|
479
|
+
path2.join(webRoot, "components", "ui", "label.tsx"),
|
|
480
|
+
readTemplate("ui-label.tsx")
|
|
481
|
+
);
|
|
482
|
+
console.log("\u{1F3A8} Setting up shadcn globals.css...");
|
|
483
|
+
const globalsCssPath = path2.join(appDir, "globals.css");
|
|
484
|
+
fs2.writeFileSync(globalsCssPath, readTemplate("globals.css"));
|
|
485
|
+
console.log("\u{1F4D0} Updating layout.tsx with global components...");
|
|
486
|
+
const layoutPath = path2.join(appDir, "layout.tsx");
|
|
487
|
+
if (fs2.existsSync(layoutPath)) {
|
|
488
|
+
try {
|
|
489
|
+
let layoutContent = fs2.readFileSync(layoutPath, "utf8");
|
|
490
|
+
const globalImports = `import GlobalInitializer from '#/components/global-initializer';
|
|
491
|
+
import GlobalLoader from '#/components/global-loader';`;
|
|
492
|
+
const lastImportIndex = layoutContent.lastIndexOf("import ");
|
|
493
|
+
const lineEnd = layoutContent.indexOf("\n", lastImportIndex);
|
|
494
|
+
layoutContent = layoutContent.slice(0, lineEnd + 1) + globalImports + "\n" + layoutContent.slice(lineEnd + 1);
|
|
495
|
+
layoutContent = layoutContent.replace(
|
|
496
|
+
/(<body[^>]*>)/,
|
|
497
|
+
`$1
|
|
498
|
+
<div id="loader-portal" />
|
|
499
|
+
<GlobalInitializer />
|
|
500
|
+
<GlobalLoader />`
|
|
349
501
|
);
|
|
502
|
+
fs2.writeFileSync(layoutPath, layoutContent);
|
|
503
|
+
} catch (error) {
|
|
504
|
+
console.warn("Warning: Could not update layout.tsx:", error);
|
|
350
505
|
}
|
|
351
|
-
}
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
506
|
+
}
|
|
507
|
+
const postcssPath = path2.join(projectRoot, "apps", "web", "postcss.config.mjs");
|
|
508
|
+
if (fs2.existsSync(postcssPath)) {
|
|
509
|
+
fs2.writeFileSync(
|
|
510
|
+
postcssPath,
|
|
511
|
+
`const config = {
|
|
512
|
+
plugins: {
|
|
513
|
+
'@tailwindcss/postcss': {},
|
|
514
|
+
},
|
|
515
|
+
};
|
|
516
|
+
|
|
517
|
+
export default config;
|
|
518
|
+
`
|
|
355
519
|
);
|
|
356
520
|
}
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
521
|
+
console.log("\u{1F500} Creating API proxy routes...");
|
|
522
|
+
const apiDir = path2.join(appDir, "api");
|
|
523
|
+
const catchAllDir = path2.join(apiDir, "[...proxy]");
|
|
524
|
+
fs2.mkdirSync(catchAllDir, { recursive: true });
|
|
525
|
+
fs2.writeFileSync(
|
|
526
|
+
path2.join(apiDir, "proxy-request.ts"),
|
|
527
|
+
readTemplate("proxy-request.ts")
|
|
528
|
+
);
|
|
529
|
+
fs2.writeFileSync(
|
|
530
|
+
path2.join(catchAllDir, "route.ts"),
|
|
531
|
+
readTemplate("proxy-route.ts")
|
|
360
532
|
);
|
|
361
533
|
}
|
|
362
|
-
|
|
363
|
-
|
|
534
|
+
console.log("\u2699\uFE0F Updating apps/web tsconfig.json...");
|
|
535
|
+
const webTsconfigPath = path2.join(projectRoot, "apps", "web", "tsconfig.json");
|
|
536
|
+
if (fs2.existsSync(webTsconfigPath)) {
|
|
364
537
|
try {
|
|
365
|
-
const
|
|
366
|
-
const
|
|
367
|
-
if (!
|
|
368
|
-
|
|
538
|
+
const webTsconfigContent = fs2.readFileSync(webTsconfigPath, "utf8");
|
|
539
|
+
const webTsconfig = JSON.parse(webTsconfigContent);
|
|
540
|
+
if (!webTsconfig.compilerOptions) {
|
|
541
|
+
webTsconfig.compilerOptions = {};
|
|
369
542
|
}
|
|
370
|
-
if (!
|
|
371
|
-
|
|
372
|
-
}
|
|
373
|
-
const pathKey = "#/monorise/*";
|
|
374
|
-
const pathValue = ["./.monorise/*"];
|
|
375
|
-
if (!tsconfig.compilerOptions.paths[pathKey]) {
|
|
376
|
-
tsconfig.compilerOptions.paths[pathKey] = pathValue;
|
|
377
|
-
fs2.writeFileSync(tsconfigPath, JSON.stringify(tsconfig, null, 2));
|
|
378
|
-
console.log(
|
|
379
|
-
`Added '${pathKey}' path alias in ${path2.relative(projectRoot, tsconfigPath)}`
|
|
380
|
-
);
|
|
381
|
-
} else {
|
|
382
|
-
console.log(
|
|
383
|
-
`'${pathKey}' path alias already set in ${path2.relative(projectRoot, tsconfigPath)}. Skipping.`
|
|
384
|
-
);
|
|
543
|
+
if (!webTsconfig.compilerOptions.paths) {
|
|
544
|
+
webTsconfig.compilerOptions.paths = {};
|
|
385
545
|
}
|
|
546
|
+
webTsconfig.compilerOptions.paths["#/shared/*"] = ["../../shared/*"];
|
|
547
|
+
webTsconfig.compilerOptions.paths["#/monorise/*"] = ["../../.monorise/*"];
|
|
548
|
+
webTsconfig.compilerOptions.paths["#/monorise"] = ["../../.monorise/index"];
|
|
549
|
+
const hasSrcDir = fs2.existsSync(path2.join(projectRoot, "apps", "web", "src"));
|
|
550
|
+
webTsconfig.compilerOptions.paths["#/*"] = [hasSrcDir ? "./src/*" : "./*"];
|
|
551
|
+
fs2.writeFileSync(webTsconfigPath, JSON.stringify(webTsconfig, null, 2));
|
|
386
552
|
} catch (error) {
|
|
387
|
-
console.error
|
|
388
|
-
`Error updating ${path2.relative(projectRoot, tsconfigPath)}:`,
|
|
389
|
-
error
|
|
390
|
-
);
|
|
553
|
+
console.warn("Warning: Could not update apps/web tsconfig.json:", error);
|
|
391
554
|
}
|
|
392
|
-
} else {
|
|
393
|
-
console.warn(
|
|
394
|
-
`Warning: ${path2.relative(projectRoot, tsconfigPath)} not found. Cannot add path alias.`
|
|
395
|
-
);
|
|
396
555
|
}
|
|
397
|
-
console.log("Monorise
|
|
556
|
+
console.log("\n\u{1F528} Running initial Monorise build...");
|
|
557
|
+
try {
|
|
558
|
+
execCommand("npx monorise build", projectRoot);
|
|
559
|
+
} catch (error) {
|
|
560
|
+
console.warn("Warning: Initial monorise build failed. You can run it manually later.");
|
|
561
|
+
}
|
|
562
|
+
console.log("\n" + "=".repeat(60));
|
|
563
|
+
console.log("\u2705 Monorise project created successfully!");
|
|
564
|
+
console.log("=".repeat(60));
|
|
565
|
+
console.log(`
|
|
566
|
+
\u{1F4C1} Project structure:`);
|
|
567
|
+
console.log(` ${projectName}/`);
|
|
568
|
+
console.log(` \u251C\u2500\u2500 apps/web/ # Next.js frontend`);
|
|
569
|
+
console.log(` \u251C\u2500\u2500 services/core/ # Backend routes (Hono)`);
|
|
570
|
+
console.log(` \u251C\u2500\u2500 monorise/configs/ # Entity definitions (User, Team)`);
|
|
571
|
+
console.log(` \u251C\u2500\u2500 monorise/mutuals/ # Shared mutual relationship configs`);
|
|
572
|
+
console.log(` \u2514\u2500\u2500 .monorise/ # Generated files`);
|
|
573
|
+
console.log(`
|
|
574
|
+
\u{1F4C2} Where to start coding:`);
|
|
575
|
+
console.log(` \u2022 Edit your data model \u2192 monorise/configs/user.ts`);
|
|
576
|
+
console.log(` (Add fields like phone, role, status to the User entity)`);
|
|
577
|
+
console.log(
|
|
578
|
+
` \u2022 Build your UI \u2192 ${pagePath ? path2.relative(projectRoot, pagePath) : "apps/web/app/page.tsx"}`
|
|
579
|
+
);
|
|
580
|
+
console.log(` (React components using useEntities and createEntity)`);
|
|
581
|
+
console.log(` \u2022 Add backend logic \u2192 services/core/routes.ts`);
|
|
582
|
+
console.log(` (Custom API endpoints with Hono)`);
|
|
583
|
+
console.log(` \u2022 See the User <-> Team relationship \u2192 monorise/mutuals/team-membership.ts`);
|
|
584
|
+
console.log(` (createMutualConfig \u2014 shared schema, referenced from both entity configs)`);
|
|
585
|
+
console.log(`
|
|
586
|
+
\u{1F680} Next steps:`);
|
|
587
|
+
console.log(` cd ${projectName}`);
|
|
588
|
+
console.log(` npx sst dev`);
|
|
589
|
+
console.log("\n\u{1F4DA} Documentation: https://monorise.dev");
|
|
590
|
+
console.log("");
|
|
398
591
|
}
|
|
399
592
|
async function runDevCommand(configDir, rootPath) {
|
|
400
593
|
console.log(MONORISE_LOGO);
|
|
@@ -465,10 +658,10 @@ async function main() {
|
|
|
465
658
|
} else if (command === "build") {
|
|
466
659
|
await runBuildCommand(rootPath);
|
|
467
660
|
} else if (command === "init") {
|
|
468
|
-
await runInitCommand(
|
|
661
|
+
await runInitCommand();
|
|
469
662
|
} else {
|
|
470
663
|
console.error(
|
|
471
|
-
"Unknown command. Usage
|
|
664
|
+
"Unknown command. Usage:\n monorise dev [--config-root <path>]\n monorise build [--config-root <path>]\n monorise init [--name <project-name>]"
|
|
472
665
|
);
|
|
473
666
|
process.exit(1);
|
|
474
667
|
}
|