@monorise/base 4.7.0 → 4.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/index.d.ts CHANGED
@@ -590,4 +590,222 @@ interface MonoriseEntityConfig<T extends Entity = Entity, B extends z.ZodRawShap
590
590
  allowLegacyWhere?: boolean;
591
591
  }
592
592
 
593
- export { type AdjustmentCondition, type AdjustmentConditionFn, type CreatedEntity, type DraftEntity, Entity, type EntitySchemaMap, type MonoriseEntityConfig, type MutualConfig, type MutualConfigInput, type NumericFields, type UpdateCondition, type UpdateConditionFn, type WhereClause, type WhereConditions, type WhereOperator, createEntityConfig, createMutualConfig, resolveEffectiveMutualSchema };
593
+ /**
594
+ * @description An access level used as shorthand.
595
+ * - On a policy, it applies to every entity and every relationship.
596
+ * - On an entity, it grants every field, every tag, listing and, by default,
597
+ * every relationship from that entity at that level.
598
+ * - On a relationship, it grants every `mutualData` field at that level.
599
+ *
600
+ * `'write'` means read, create, update and delete.
601
+ */
602
+ type ApiKeyAccessLevel = 'none' | 'read' | 'write';
603
+ /**
604
+ * @description System fields a create payload may set only when the create
605
+ * list names them: `$entityId` for a caller-chosen `entityId`, `$createdAt`
606
+ * for a backdated `createdAt`.
607
+ */
608
+ type ApiKeySystemField = '$entityId' | '$createdAt';
609
+ /** `'*'` for every field, present and future, or an allowlist. */
610
+ type ApiKeyFieldList<F extends string = string> = '*' | F[];
611
+ type EntityField<T extends Entity> = Extract<keyof DraftEntity<T>, string>;
612
+ /**
613
+ * @description Each entity type's tag names. The CLI augments this from the
614
+ * entity configs, so `tags` in a policy accepts only real tag names.
615
+ */
616
+ interface ApiKeyEntityTags {
617
+ }
618
+ /**
619
+ * @description The `mutualData` field names of each direction whose pair has
620
+ * a mutual config. The CLI augments this from the entity configs, so a
621
+ * relationship grant's field lists accept only real `mutualData` fields.
622
+ */
623
+ interface ApiKeyMutualDataFields {
624
+ }
625
+ type TagName<T extends Entity> = T extends keyof ApiKeyEntityTags ? Extract<ApiKeyEntityTags[T], string> : string;
626
+ type MutualDataField<A extends Entity, B extends Entity> = A extends keyof ApiKeyMutualDataFields ? B extends keyof ApiKeyMutualDataFields[A] ? Extract<ApiKeyMutualDataFields[A][B], string> : string : string;
627
+ /**
628
+ * @description Access to one direction of a relationship, e.g. learner→course
629
+ * (`/mutual/learner/:id/course`). Field lists name `mutualData` fields.
630
+ */
631
+ type ApiKeyMutualGrant<A extends Entity = Entity, B extends Entity = Entity> = ApiKeyAccessLevel | {
632
+ read?: ApiKeyFieldList<MutualDataField<A, B>>;
633
+ create?: ApiKeyFieldList<MutualDataField<A, B>>;
634
+ update?: ApiKeyFieldList<MutualDataField<A, B>>;
635
+ /** Same as `create` and `update` with this list. */
636
+ write?: ApiKeyFieldList<MutualDataField<A, B>>;
637
+ delete?: boolean;
638
+ };
639
+ /**
640
+ * @description Access to one entity type.
641
+ *
642
+ * A shorthand string is broad: every field, every tag and every relationship
643
+ * from this entity at that level. An object is exact: only what it lists.
644
+ * Any write grant implies read on the same fields.
645
+ */
646
+ type ApiKeyEntityGrant<T extends Entity = Entity> = ApiKeyAccessLevel | {
647
+ /** Fields the key can read: get by ID or unique field, and every response's masking. */
648
+ read?: ApiKeyFieldList<EntityField<T>>;
649
+ /**
650
+ * Also list the whole type: `GET /entity/:type`, search and tag
651
+ * queries. Get only needs a reference to a record; listing needs none,
652
+ * so an object grant lists only when it says so.
653
+ */
654
+ list?: boolean;
655
+ /** Must include every field `createSchema` requires. */
656
+ create?: ApiKeyFieldList<EntityField<T> | ApiKeySystemField>;
657
+ update?: ApiKeyFieldList<EntityField<T>>;
658
+ /** Same as `create` and `update` with this list. */
659
+ write?: ApiKeyFieldList<EntityField<T> | ApiKeySystemField>;
660
+ delete?: boolean;
661
+ /** Defaults to every tag when `read` is `'*'`, otherwise to none. */
662
+ tags?: ApiKeyFieldList<TagName<T>>;
663
+ /**
664
+ * Relationships from this entity, keyed by the target entity type. An
665
+ * entry covers one direction only: `[Entity.COURSE]` under learner is
666
+ * learner→course and says nothing about course→learner. `'*'` sets the
667
+ * level for every direction without an entry; it defaults to `'none'`.
668
+ */
669
+ mutuals?: {
670
+ '*'?: ApiKeyAccessLevel;
671
+ } & {
672
+ [O in Entity]?: ApiKeyMutualGrant<T, O>;
673
+ };
674
+ };
675
+ /**
676
+ * @description A policy. The shorthands `'read'` and `'write'` apply to every
677
+ * entity and relationship, and grant no custom routes.
678
+ */
679
+ type ApiKeyPolicy = 'read' | 'write' | {
680
+ entities?: {
681
+ '*'?: ApiKeyAccessLevel;
682
+ } & {
683
+ [T in Entity]?: ApiKeyEntityGrant<T>;
684
+ };
685
+ /**
686
+ * Custom route permissions this policy grants: the names custom routes
687
+ * declare with `requires(...)`. A custom route without `requires(...)`
688
+ * is callable only by `full` keys.
689
+ */
690
+ routes?: string[];
691
+ };
692
+ /**
693
+ * @description Every custom route permission the project's policies grant.
694
+ * The CLI augments it from the policies, so `requires()` accepts only names
695
+ * some policy grants.
696
+ */
697
+ interface ApiKeyRoutePermissions {
698
+ }
699
+ /** A custom route permission name; any string until the CLI augments `ApiKeyRoutePermissions`. */
700
+ type ApiKeyRoutePermission = keyof ApiKeyRoutePermissions extends never ? string : Extract<keyof ApiKeyRoutePermissions, string>;
701
+ /**
702
+ * @description Policies keyed by name. `API_KEYS` maps these names to keys.
703
+ * `full` is built in and cannot be redefined.
704
+ */
705
+ type ApiKeyPolicies = Record<string, ApiKeyPolicy>;
706
+
707
+ /**
708
+ * @description Built-in policy: read, write and delete on every entity and
709
+ * relationship, plus every custom route. Every key in the legacy array form of
710
+ * `API_KEYS` maps to it.
711
+ */
712
+ declare const FULL_API_KEY_POLICY = "full";
713
+ /** `'*'` for every field, or the allowed fields. */
714
+ type ApiKeyFieldAccess = '*' | ReadonlySet<string>;
715
+ /** What a policy allows on one entity type. `null` means not granted. */
716
+ type ApiKeyEntityAccess = {
717
+ /**
718
+ * Whether the key can see the type at all: the policy grants it anything
719
+ * but `'none'`, by name or through its `'*'` entry. A type the key can't
720
+ * see answers 404, as if it didn't exist.
721
+ */
722
+ visible: boolean;
723
+ /** Fields the key can read, by ID or unique field, and in every response. */
724
+ read: ApiKeyFieldAccess | null;
725
+ /** Whether the key can list the whole type: listing, search and tag queries. */
726
+ list: boolean;
727
+ create: ApiKeyFieldAccess | null;
728
+ update: ApiKeyFieldAccess | null;
729
+ delete: boolean;
730
+ tags: ApiKeyFieldAccess | null;
731
+ };
732
+ /** What a policy allows on one direction of a relationship. Fields are `mutualData` fields. */
733
+ type ApiKeyMutualAccess = {
734
+ read: ApiKeyFieldAccess | null;
735
+ create: ApiKeyFieldAccess | null;
736
+ update: ApiKeyFieldAccess | null;
737
+ delete: boolean;
738
+ };
739
+ type CompiledApiKeyPolicy = {
740
+ name: string;
741
+ /** True only for the built-in `full` policy. */
742
+ full: boolean;
743
+ entity(entityType: string): ApiKeyEntityAccess;
744
+ /**
745
+ * Access to the direction `byEntityType`→`entityType`, as in
746
+ * `/mutual/:byEntityType/:byEntityId/:entityType`. `null` when either end
747
+ * type isn't visible.
748
+ */
749
+ mutual(byEntityType: string, entityType: string): ApiKeyMutualAccess | null;
750
+ /** Whether the policy grants a custom route permission. `full` grants every one. */
751
+ allowsRoute(permission: string): boolean;
752
+ };
753
+ /**
754
+ * @description Compiles a policy into the access it grants. Compiled entity
755
+ * grants are cached, so compile once per policy and reuse the result.
756
+ *
757
+ * `name === 'full'` compiles the built-in policy and ignores `policy`.
758
+ */
759
+ declare const compileApiKeyPolicy: (name: string, policy?: ApiKeyPolicy) => CompiledApiKeyPolicy;
760
+ /**
761
+ * @description The parts of an entity config that policy validation reads.
762
+ * Any config built by `createEntityConfig` satisfies it. Configs are keyed by
763
+ * entity type.
764
+ */
765
+ type ApiKeyPolicyEntityConfig = {
766
+ baseSchema: z.AnyZodObject;
767
+ createSchema?: z.AnyZodObject;
768
+ tags?: {
769
+ name: string;
770
+ }[];
771
+ mutual?: {
772
+ mutualSchema?: z.AnyZodObject;
773
+ createMutualSchema?: z.AnyZodObject;
774
+ mutualFields?: Record<string, {
775
+ entityType: string | Entity;
776
+ mutual?: {
777
+ mutualDataSchema?: z.AnyZodObject;
778
+ asEntity?: {
779
+ name: string | Entity;
780
+ };
781
+ };
782
+ }>;
783
+ };
784
+ };
785
+ /**
786
+ * @description Checks policies against the entity configs. Returns one message
787
+ * per problem; an empty array means the policies are valid. The CLI runs this
788
+ * at build time and the API handler at cold start.
789
+ */
790
+ declare const validateApiKeyPolicies: (policies: unknown, entityConfigs: Record<string, ApiKeyPolicyEntityConfig>) => string[];
791
+ /**
792
+ * @description Declares the API key policies. Export the result as the default
793
+ * export of the file `apiKeys` points to in `monorise.config.ts`; `API_KEYS`
794
+ * then maps each policy name to its keys. `full` is built in.
795
+ *
796
+ * @example
797
+ * ```ts
798
+ * export default defineApiKeyPolicies({
799
+ * 'agent-read': 'read',
800
+ * client: {
801
+ * entities: {
802
+ * [Entity.ORDER]: { read: '*', create: ['customerId', 'items'], update: ['status'] },
803
+ * [Entity.PRODUCT]: 'read',
804
+ * },
805
+ * },
806
+ * });
807
+ * ```
808
+ */
809
+ declare const defineApiKeyPolicies: (policies: ApiKeyPolicies) => ApiKeyPolicies;
810
+
811
+ export { type AdjustmentCondition, type AdjustmentConditionFn, type ApiKeyAccessLevel, type ApiKeyEntityAccess, type ApiKeyEntityGrant, type ApiKeyEntityTags, type ApiKeyFieldAccess, type ApiKeyFieldList, type ApiKeyMutualAccess, type ApiKeyMutualDataFields, type ApiKeyMutualGrant, type ApiKeyPolicies, type ApiKeyPolicy, type ApiKeyPolicyEntityConfig, type ApiKeyRoutePermission, type ApiKeyRoutePermissions, type ApiKeySystemField, type CompiledApiKeyPolicy, type CreatedEntity, type DraftEntity, Entity, type EntitySchemaMap, FULL_API_KEY_POLICY, type MonoriseEntityConfig, type MutualConfig, type MutualConfigInput, type NumericFields, type UpdateCondition, type UpdateConditionFn, type WhereClause, type WhereConditions, type WhereOperator, compileApiKeyPolicy, createEntityConfig, createMutualConfig, defineApiKeyPolicies, resolveEffectiveMutualSchema, validateApiKeyPolicies };
package/dist/index.js CHANGED
@@ -17,6 +17,18 @@ var __spreadValues = (a, b) => {
17
17
  return a;
18
18
  };
19
19
  var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
20
+ var __objRest = (source, exclude) => {
21
+ var target = {};
22
+ for (var prop in source)
23
+ if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
24
+ target[prop] = source[prop];
25
+ if (source != null && __getOwnPropSymbols)
26
+ for (var prop of __getOwnPropSymbols(source)) {
27
+ if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
28
+ target[prop] = source[prop];
29
+ }
30
+ return target;
31
+ };
20
32
 
21
33
  // types/monorise.type.ts
22
34
  var Entity = /* @__PURE__ */ ((Entity2) => {
@@ -77,10 +89,378 @@ var createMutualConfig = (config) => {
77
89
  mutualDataSchema: config.asEntity.finalSchema
78
90
  });
79
91
  };
92
+
93
+ // utils/api-key-policy.ts
94
+ var FULL_API_KEY_POLICY = "full";
95
+ var ACCESS_LEVELS = ["none", "read", "write"];
96
+ var SYSTEM_FIELDS = ["$entityId", "$createdAt"];
97
+ var ENTITY_GRANT_KEYS = [
98
+ "read",
99
+ "list",
100
+ "create",
101
+ "update",
102
+ "write",
103
+ "delete",
104
+ "tags",
105
+ "mutuals"
106
+ ];
107
+ var MUTUAL_GRANT_KEYS = ["read", "create", "update", "write", "delete"];
108
+ var POLICY_KEYS = ["entities", "routes"];
109
+ var hasOwn = (object, key) => Object.prototype.hasOwnProperty.call(object, key);
110
+ var toAccess = (list) => list === void 0 ? null : list === "*" ? "*" : new Set(list);
111
+ var union = (...accesses) => {
112
+ let fields = null;
113
+ for (const access of accesses) {
114
+ if (access === null) continue;
115
+ if (access === "*") return "*";
116
+ fields = /* @__PURE__ */ new Set([...fields != null ? fields : [], ...access]);
117
+ }
118
+ return fields;
119
+ };
120
+ var withoutSystemFields = (access) => access === null || access === "*" ? access : new Set([...access].filter((field) => !SYSTEM_FIELDS.includes(field)));
121
+ var HIDDEN = {
122
+ access: {
123
+ visible: false,
124
+ read: null,
125
+ list: false,
126
+ create: null,
127
+ update: null,
128
+ delete: false,
129
+ tags: null
130
+ },
131
+ mutualDefault: "none",
132
+ mutuals: /* @__PURE__ */ new Map()
133
+ };
134
+ var compileEntityGrant = (grant) => {
135
+ var _a;
136
+ if (grant === void 0 || grant === "none") return HIDDEN;
137
+ if (grant === "read" || grant === "write") {
138
+ const write = grant === "write";
139
+ return {
140
+ access: {
141
+ visible: true,
142
+ read: "*",
143
+ list: true,
144
+ create: write ? "*" : null,
145
+ update: write ? "*" : null,
146
+ delete: write,
147
+ tags: "*"
148
+ },
149
+ mutualDefault: grant,
150
+ mutuals: /* @__PURE__ */ new Map()
151
+ };
152
+ }
153
+ const create = union(toAccess(grant.create), toAccess(grant.write));
154
+ const update = union(toAccess(grant.update), toAccess(grant.write));
155
+ const read = union(toAccess(grant.read), withoutSystemFields(create), update);
156
+ const _b = (_a = grant.mutuals) != null ? _a : {}, { "*": mutualDefault = "none" } = _b, mutuals = __objRest(_b, ["*"]);
157
+ return {
158
+ access: {
159
+ visible: true,
160
+ read,
161
+ list: grant.list === true,
162
+ create,
163
+ update,
164
+ delete: grant.delete === true,
165
+ tags: grant.tags !== void 0 ? toAccess(grant.tags) : read === "*" ? "*" : null
166
+ },
167
+ mutualDefault,
168
+ mutuals: new Map(Object.entries(mutuals))
169
+ };
170
+ };
171
+ var compileMutualGrant = (grant) => {
172
+ if (grant === "none" || grant === "read" || grant === "write") {
173
+ const write = grant === "write";
174
+ return {
175
+ read: grant === "none" ? null : "*",
176
+ create: write ? "*" : null,
177
+ update: write ? "*" : null,
178
+ delete: write
179
+ };
180
+ }
181
+ const create = union(toAccess(grant.create), toAccess(grant.write));
182
+ const update = union(toAccess(grant.update), toAccess(grant.write));
183
+ return {
184
+ read: union(toAccess(grant.read), create, update),
185
+ create,
186
+ update,
187
+ delete: grant.delete === true
188
+ };
189
+ };
190
+ var compileApiKeyPolicy = (name, policy) => {
191
+ var _a, _b;
192
+ const full = name === FULL_API_KEY_POLICY;
193
+ const entities = full ? { "*": "write" } : policy === "read" || policy === "write" ? { "*": policy } : (_a = policy == null ? void 0 : policy.entities) != null ? _a : {};
194
+ const routes = new Set(
195
+ !full && typeof policy === "object" ? (_b = policy.routes) != null ? _b : [] : []
196
+ );
197
+ const cache = /* @__PURE__ */ new Map();
198
+ const compiled = (entityType) => {
199
+ const grantKey = hasOwn(entities, entityType) ? entityType : "*";
200
+ let entry = cache.get(grantKey);
201
+ if (!entry) {
202
+ entry = compileEntityGrant(
203
+ hasOwn(entities, grantKey) ? entities[grantKey] : void 0
204
+ );
205
+ cache.set(grantKey, entry);
206
+ }
207
+ return entry;
208
+ };
209
+ return {
210
+ name,
211
+ full,
212
+ entity: (entityType) => compiled(entityType).access,
213
+ mutual: (byEntityType, entityType) => {
214
+ var _a2;
215
+ const from = compiled(byEntityType);
216
+ if (!from.access.visible || !compiled(entityType).access.visible) {
217
+ return null;
218
+ }
219
+ return compileMutualGrant(
220
+ (_a2 = from.mutuals.get(entityType)) != null ? _a2 : from.mutualDefault
221
+ );
222
+ },
223
+ allowsRoute: (permission) => full || routes.has(permission)
224
+ };
225
+ };
226
+ var isPlainObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
227
+ var quoteList = (items) => [...items].map((item) => `'${item}'`).join(", ");
228
+ var validateApiKeyPolicies = (policies, entityConfigs) => {
229
+ var _a, _b, _c, _d;
230
+ const errors = [];
231
+ if (!isPlainObject(policies)) {
232
+ return ["API key policies must be an object keyed by policy name"];
233
+ }
234
+ const entityNames = Object.keys(entityConfigs);
235
+ const isEntityType = (name) => hasOwn(entityConfigs, name);
236
+ const mutualFieldNames = (config) => {
237
+ var _a2, _b2, _c2, _d2, _e, _f, _g, _h;
238
+ return /* @__PURE__ */ new Set([
239
+ ...Object.keys((_b2 = (_a2 = config.mutual) == null ? void 0 : _a2.mutualFields) != null ? _b2 : {}),
240
+ ...Object.keys((_e = (_d2 = (_c2 = config.mutual) == null ? void 0 : _c2.mutualSchema) == null ? void 0 : _d2.shape) != null ? _e : {}),
241
+ ...Object.keys((_h = (_g = (_f = config.mutual) == null ? void 0 : _f.createMutualSchema) == null ? void 0 : _g.shape) != null ? _h : {})
242
+ ]);
243
+ };
244
+ const ownFields = (config) => {
245
+ var _a2, _b2, _c2, _d2;
246
+ return /* @__PURE__ */ new Set([
247
+ ...Object.keys((_b2 = (_a2 = config.baseSchema) == null ? void 0 : _a2.shape) != null ? _b2 : {}),
248
+ ...Object.keys((_d2 = (_c2 = config.createSchema) == null ? void 0 : _c2.shape) != null ? _d2 : {})
249
+ ]);
250
+ };
251
+ const mutualConfig = (byEntityType, entityType) => {
252
+ var _a2;
253
+ const declared = (from, to) => {
254
+ var _a3, _b2, _c2, _d2;
255
+ return (_d2 = Object.values((_c2 = (_b2 = (_a3 = entityConfigs[from]) == null ? void 0 : _a3.mutual) == null ? void 0 : _b2.mutualFields) != null ? _c2 : {}).find(
256
+ (field) => field.entityType === to && field.mutual
257
+ )) == null ? void 0 : _d2.mutual;
258
+ };
259
+ return (_a2 = declared(byEntityType, entityType)) != null ? _a2 : declared(entityType, byEntityType);
260
+ };
261
+ const checkFieldList = (where, list, allowed, describe) => {
262
+ if (list === "*") return;
263
+ if (!Array.isArray(list) || !list.every((field) => typeof field === "string")) {
264
+ errors.push(`${where} must be '*' or an array of field names`);
265
+ return;
266
+ }
267
+ for (const field of list) {
268
+ const problem = describe(field);
269
+ if (problem) errors.push(`${where}: ${problem}`);
270
+ else if (allowed && !allowed.has(field)) {
271
+ errors.push(`${where}: unknown field '${field}'`);
272
+ }
273
+ }
274
+ };
275
+ const checkUnknownKeys = (where, value, known) => {
276
+ for (const key of Object.keys(value)) {
277
+ if (!known.includes(key)) {
278
+ errors.push(
279
+ `${where}: unknown key '${key}' (expected ${quoteList(known)})`
280
+ );
281
+ }
282
+ }
283
+ };
284
+ const checkLevel = (where, value) => {
285
+ if (!ACCESS_LEVELS.includes(value)) {
286
+ errors.push(`${where} must be one of ${quoteList(ACCESS_LEVELS)}`);
287
+ }
288
+ };
289
+ const checkMutualGrant = (where, grant, byEntityType, entityType) => {
290
+ var _a2, _b2;
291
+ if (typeof grant === "string") return checkLevel(where, grant);
292
+ if (!isPlainObject(grant)) {
293
+ errors.push(`${where} must be an access level or an object`);
294
+ return;
295
+ }
296
+ checkUnknownKeys(where, grant, MUTUAL_GRANT_KEYS);
297
+ const dataFields = (_b2 = (_a2 = mutualConfig(byEntityType, entityType)) == null ? void 0 : _a2.mutualDataSchema) == null ? void 0 : _b2.shape;
298
+ const allowed = dataFields ? new Set(Object.keys(dataFields)) : void 0;
299
+ for (const key of ["read", "create", "update", "write"]) {
300
+ if (grant[key] === void 0) continue;
301
+ checkFieldList(`${where}.${key}`, grant[key], allowed, () => void 0);
302
+ }
303
+ if (grant.delete !== void 0 && typeof grant.delete !== "boolean") {
304
+ errors.push(`${where}.delete must be a boolean`);
305
+ }
306
+ };
307
+ const checkEntityGrant = (where, grant, entityType) => {
308
+ var _a2;
309
+ const config = entityConfigs[entityType];
310
+ if (typeof grant === "string") return checkLevel(where, grant);
311
+ if (!isPlainObject(grant)) {
312
+ errors.push(`${where} must be an access level or an object`);
313
+ return;
314
+ }
315
+ checkUnknownKeys(where, grant, ENTITY_GRANT_KEYS);
316
+ const fields = ownFields(config);
317
+ const mutualFields = mutualFieldNames(config);
318
+ const fieldListErrors = errors.length;
319
+ for (const key of ["read", "create", "update", "write"]) {
320
+ if (grant[key] === void 0) continue;
321
+ const allowsSystemFields = key === "create" || key === "write";
322
+ const allowed = allowsSystemFields ? /* @__PURE__ */ new Set([...fields, ...SYSTEM_FIELDS]) : fields;
323
+ checkFieldList(`${where}.${key}`, grant[key], allowed, (field) => {
324
+ if (SYSTEM_FIELDS.includes(field)) {
325
+ return allowsSystemFields ? void 0 : `'${field}' can only be granted in 'create' or 'write'`;
326
+ }
327
+ if (mutualFields.has(field) && !fields.has(field)) {
328
+ return `'${field}' is a relationship field; grant it under 'mutuals' instead`;
329
+ }
330
+ return void 0;
331
+ });
332
+ }
333
+ if (grant.delete !== void 0 && typeof grant.delete !== "boolean") {
334
+ errors.push(`${where}.delete must be a boolean`);
335
+ }
336
+ if (grant.list !== void 0 && typeof grant.list !== "boolean") {
337
+ errors.push(`${where}.list must be a boolean`);
338
+ } else if (grant.list === true && errors.length === fieldListErrors) {
339
+ const { read } = compileEntityGrant(grant).access;
340
+ if (read === null || read !== "*" && read.size === 0) {
341
+ errors.push(
342
+ `${where}.list needs fields to read; a listing would return no data`
343
+ );
344
+ }
345
+ }
346
+ if (grant.tags !== void 0) {
347
+ checkFieldList(
348
+ `${where}.tags`,
349
+ grant.tags,
350
+ new Set(((_a2 = config.tags) != null ? _a2 : []).map((tag) => tag.name)),
351
+ () => void 0
352
+ );
353
+ }
354
+ if (grant.mutuals !== void 0) {
355
+ if (!isPlainObject(grant.mutuals)) {
356
+ errors.push(`${where}.mutuals must be an object`);
357
+ return;
358
+ }
359
+ for (const [target, mutualGrant] of Object.entries(grant.mutuals)) {
360
+ const mutualWhere = `${where}.mutuals.${target}`;
361
+ if (target === "*") {
362
+ checkLevel(mutualWhere, mutualGrant);
363
+ } else if (!isEntityType(target)) {
364
+ errors.push(`${mutualWhere}: unknown entity type '${target}'`);
365
+ } else {
366
+ checkMutualGrant(mutualWhere, mutualGrant, entityType, target);
367
+ }
368
+ }
369
+ }
370
+ };
371
+ const checkCreateIsSatisfiable = (where, policy, entityType) => {
372
+ var _a2, _b2, _c2, _d2, _e, _f, _g, _h, _i;
373
+ const config = entityConfigs[entityType];
374
+ const { create } = policy.entity(entityType);
375
+ if (create === null) return;
376
+ if (create !== "*") {
377
+ const shape = __spreadValues(__spreadValues({}, (_a2 = config.baseSchema) == null ? void 0 : _a2.shape), (_b2 = config.createSchema) == null ? void 0 : _b2.shape);
378
+ const missing = Object.entries(shape).filter(([field, schema]) => !schema.isOptional() && !create.has(field)).map(([field]) => field);
379
+ if (missing.length) {
380
+ errors.push(
381
+ `${where}: create omits required field(s) ${quoteList(missing)}, so a key with this policy could never create one`
382
+ );
383
+ }
384
+ }
385
+ const requiredMutuals = (_e = (_d2 = (_c2 = config.mutual) == null ? void 0 : _c2.createMutualSchema) == null ? void 0 : _d2.shape) != null ? _e : {};
386
+ for (const [field, schema] of Object.entries(
387
+ requiredMutuals
388
+ )) {
389
+ const target = (_h = (_g = (_f = config.mutual) == null ? void 0 : _f.mutualFields) == null ? void 0 : _g[field]) == null ? void 0 : _h.entityType;
390
+ if (schema.isOptional() || !target) continue;
391
+ if (!((_i = policy.mutual(entityType, target)) == null ? void 0 : _i.create)) {
392
+ errors.push(
393
+ `${where}: create needs create on ${entityType}\u2192${target}, because createMutualSchema requires '${field}'`
394
+ );
395
+ }
396
+ }
397
+ };
398
+ for (const [name, policy] of Object.entries(policies)) {
399
+ const where = `policy '${name}'`;
400
+ const errorsBefore = errors.length;
401
+ if (name === FULL_API_KEY_POLICY) {
402
+ errors.push(`${where} is built in and cannot be redefined`);
403
+ continue;
404
+ }
405
+ if (policy === "read" || policy === "write") continue;
406
+ if (!isPlainObject(policy)) {
407
+ errors.push(`${where} must be 'read', 'write' or an object`);
408
+ continue;
409
+ }
410
+ checkUnknownKeys(where, policy, POLICY_KEYS);
411
+ if (policy.routes !== void 0 && (!Array.isArray(policy.routes) || !policy.routes.every(
412
+ (permission) => typeof permission === "string" && permission.length
413
+ ))) {
414
+ errors.push(`${where}.routes must be an array of permission names`);
415
+ }
416
+ const entities = (_a = policy.entities) != null ? _a : {};
417
+ if (!isPlainObject(entities)) {
418
+ errors.push(`${where}.entities must be an object`);
419
+ continue;
420
+ }
421
+ for (const [entityType, grant] of Object.entries(entities)) {
422
+ const entityWhere = `${where}.entities.${entityType}`;
423
+ if (entityType === "*") {
424
+ checkLevel(entityWhere, grant);
425
+ } else if (!isEntityType(entityType)) {
426
+ errors.push(`${entityWhere}: unknown entity type '${entityType}'`);
427
+ } else {
428
+ checkEntityGrant(entityWhere, grant, entityType);
429
+ }
430
+ }
431
+ if (errors.length > errorsBefore) continue;
432
+ const compiled = compileApiKeyPolicy(name, policy);
433
+ for (const entityType of entityNames) {
434
+ const entityWhere = `${where}.entities.${entityType}`;
435
+ checkCreateIsSatisfiable(entityWhere, compiled, entityType);
436
+ for (const target of entityNames) {
437
+ const asEntity = (_c = (_b = mutualConfig(entityType, target)) == null ? void 0 : _b.asEntity) == null ? void 0 : _c.name;
438
+ if (asEntity && ((_d = compiled.mutual(entityType, target)) == null ? void 0 : _d.create) && !compiled.entity(asEntity).create) {
439
+ errors.push(
440
+ `${entityWhere}: create on ${entityType}\u2192${target} also creates a '${asEntity}' entity, so it needs create on '${asEntity}'`
441
+ );
442
+ }
443
+ }
444
+ }
445
+ }
446
+ return errors;
447
+ };
448
+ var VALIDATE_API_KEY_POLICIES = /* @__PURE__ */ Symbol.for("monorise.validateApiKeyPolicies");
449
+ var defineApiKeyPolicies = (policies) => {
450
+ Object.defineProperty(policies, VALIDATE_API_KEY_POLICIES, {
451
+ value: (entityConfigs) => validateApiKeyPolicies(policies, entityConfigs),
452
+ enumerable: false
453
+ });
454
+ return policies;
455
+ };
80
456
  export {
81
457
  Entity,
458
+ FULL_API_KEY_POLICY,
459
+ compileApiKeyPolicy,
82
460
  createEntityConfig,
83
461
  createMutualConfig,
84
- resolveEffectiveMutualSchema
462
+ defineApiKeyPolicies,
463
+ resolveEffectiveMutualSchema,
464
+ validateApiKeyPolicies
85
465
  };
86
466
  //# sourceMappingURL=index.js.map
package/dist/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 { createEntityConfig } from '../utils';\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 */\n/**\n * @description The shape `createMutualConfig(...)` is CALLED with — looser than the resolved\n * `MutualConfig` it returns. `mutualDataSchema` is optional here (and mutually exclusive with\n * `asEntity`) because `createMutualConfig` resolves it before returning: every OTHER consumer in\n * this codebase (`mutualFields[key].mutual`, `MutualService`, the processors) reads the resolved\n * `MutualConfig` type below, where `mutualDataSchema` stays REQUIRED — the same \"loose input,\n * strict resolved output\" split `createEntityConfig`/`MonoriseEntityConfig` already use for\n * `finalSchema`/`effectiveMutualSchema`. Import this type only if you're writing something that\n * itself calls `createMutualConfig`; every other call site should keep using `MutualConfig`.\n */\nexport interface MutualConfigInput<MD extends z.ZodRawShape = z.ZodRawShape> {\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 /** Required unless `asEntity` is set — see `asEntity`'s own doc comment. */\n mutualDataSchema?: z.ZodObject<MD>;\n\n /**\n * @description (Optional) Materialize this mutual relationship as a real,\n * independently-queryable `Entity` whenever it's created — whether imperatively via\n * `MutualService.createMutual` or automatically via a declarative `mutualFields` entry that\n * references this config — by passing the `createEntityConfig(...)` return value for the\n * entity type it should materialize as.\n *\n * When set, in addition to the mutual edge, a real `Entity` is created:\n * `entityType = asEntity.name`, `entityId = <the mutual's own generated ulid>`,\n * `data = <the mutual's own parsed mutualData>`. This lets the relationship be looked up via\n * monorise's `tags` mechanism (an indexed GSI lookup) instead of scanning and filtering every\n * edge in application code, and lets the synthetic entity carry its own `mutualFields`.\n *\n * `mutualDataSchema` must be OMITTED when `asEntity` is set: it's derived automatically from\n * `asEntity.finalSchema` (that entity's own `baseSchema` + `createSchema` +\n * `effectiveMutualSchema`, merged — the same schema this codebase already validates every\n * normal `createEntity` payload against). Chosen over a narrower `baseSchema`/`createSchema`\n * derivation because `MutualService.createMutual`'s `asEntity` path fires\n * `afterCreateEntityHook` on the synthetic entity — the same hook that wires up an entity's\n * OWN further `mutualFields` — so anything narrower than `finalSchema` would silently break\n * that wiring for any `asEntity`-targeted entity that itself declares further relationships.\n * Providing both `asEntity` and `mutualDataSchema` is a build-time AND runtime error.\n *\n * The synthetic entity is always created SYNCHRONOUSLY, in the same DynamoDB transaction as\n * the mutual write, with its `afterCreateEntityHook` (tags/mutualFields wiring) firing\n * immediately after the commit. There is no asynchronous mode: the entity either exists the\n * moment the mutual does, or neither is written. That costs a `TransactWriteItems` (2x WCU\n * versus a plain write) but leaves no window in which the mutual exists and its projection\n * does not.\n *\n * An explicit `options.asEntity` passed directly at an imperative `createMutual(...)` call\n * site always overrides this config-level value — see `resolveAsEntity` in `@monorise/core`'s\n * `mutual.service`.\n *\n * @example\n * ```ts\n * const enrollmentMutual = createMutualConfig({\n * entities: [Entity.STUDENT, Entity.COURSE],\n * asEntity: enrollmentEntityConfig, // the createEntityConfig(...) result for Entity.ENROLLMENT\n * });\n * ```\n */\n asEntity?: ReturnType<typeof createEntityConfig>;\n}\n\n/**\n * @description The resolved shape `createMutualConfig(...)` RETURNS, and what every other\n * consumer in this codebase (`mutualFields[key].mutual`, `MutualService`, the mutual processor)\n * actually references. Unlike `MutualConfigInput`, `mutualDataSchema` is REQUIRED here — by the\n * time a `MutualConfig` object exists, `createMutualConfig` has already derived it from\n * `asEntity.finalSchema` when needed, so every existing `.mutualDataSchema` read across this\n * codebase keeps its original, always-defined guarantee regardless of whether the mutual uses\n * `asEntity` or not.\n */\nexport interface MutualConfig<MD extends z.ZodRawShape = z.ZodRawShape>\n extends Omit<MutualConfigInput<MD>, 'mutualDataSchema'> {\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 CMO extends z.AnyZodObject | 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 * Used to validate mutual fields on create, and — derived to a partial — on update. You do NOT need to author this `.partial()`: the SDK partials it for the update path, so an update that doesn't touch every mutual relationship stays valid regardless of how this is declared.\n */\n mutualSchema: MO;\n\n /**\n * @description (Optional) Stricter schema applied ONLY when the entity is created — falls back to `mutualSchema` if not provided, so existing configs are unaffected. When provided, its shape is merged over `mutualSchema` for create; fields only `mutualSchema` declares (and `createMutualSchema` doesn't mention) are still validated and wired, not dropped.\n *\n * Use this when a mutual relationship must always be wired at creation time (e.g. every Competition must have an owning Organisation from the start). It does not affect updates either way — the update path derives a partial from `mutualSchema` itself, so a required-at-create relationship never has to be resent on an unrelated patch.\n *\n * Without this, a create silently succeeds even if a required mutual link is omitted from the payload — the entity is created but never gets wired to the relationship, with no error anywhere.\n *\n * Note: this only strengthens the *runtime* validation on create — `EntitySchemaMap` (the type callers see back from a read, generated from `finalSchema`) stays `MO`-shaped regardless, since mutual fields are never stored and a read can never actually return one. Don't expect a `createMutualSchema`-required field to show up as required in generated read types.\n *\n * The same-named `PUT /entity/:type/:id` upsert endpoint applies this schema only when the entity doesn't already exist — the same call is strict or lenient purely depending on whether that ID was already there.\n *\n * @example\n * ```ts\n * const mutualSchema = z.object({ organisationIds: z.string().array() }).partial();\n * const createMutualSchema = z.object({ organisationIds: z.string().array() }); // required on create\n * ```\n */\n createMutualSchema?: CMO;\n // Deliberately typed via its own `CMO` generic rather than `MO` — the\n // whole point is that it's allowed to be a DIFFERENT (stricter) shape\n // than `mutualSchema`, e.g. built via `mutualSchema.required({ field:\n // true })`, which is a structurally different ZodObject type, not `MO`\n // itself. Only the runtime merge (`resolveEffectiveMutualSchema` /\n // `effectiveMutualSchema`, see `packages/base/utils`) combines `MO` and\n // `CMO` — `finalSchema`'s TYPE deliberately stays `MO`-based; see the\n // note above and `makeSchema`'s own comment for why.\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: {\n entityId: string;\n entityType: string;\n data: Record<string, any>;\n createdAt: string;\n updatedAt: string;\n }) => {\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>\n ? K\n : never]: K;\n } extends never\n ? string\n : keyof {\n [K in keyof B as B[K] extends\n | z.ZodNumber\n | z.ZodOptional<z.ZodNumber>\n ? K\n : 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>\n ? K\n : never]: K;\n } extends never\n ? string\n : keyof {\n [K in keyof B as B[K] extends\n | z.ZodNumber\n | z.ZodOptional<z.ZodNumber>\n ? K\n : 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 { z } from 'zod';\nimport type {\n Entity,\n MonoriseEntityConfig,\n MutualConfig,\n MutualConfigInput,\n} from '../types/monorise.type';\n\n/**\n * @description Merges `mutualSchema` and `createMutualSchema` into the schema\n * actually used to validate a create payload. A plain `createMutualSchema ||\n * mutualSchema` fallback would DROP any mutual field that's declared on\n * `mutualSchema` but omitted from `createMutualSchema` (e.g. a\n * `createMutualSchema` authored to cover only the newly-required field,\n * without repeating every other optional mutual field) — `.parse()` strips\n * unknown keys, so that field's wiring would silently never fire even when\n * the caller supplied it. Merging shapes (with `createMutualSchema`'s keys\n * taking precedence on overlap, since it's the stricter one) keeps every\n * mutual field in play while still enforcing the create-only requirement.\n */\nfunction resolveEffectiveMutualSchema<M extends z.AnyZodObject | undefined>(\n mutualSchema: M,\n createMutualSchema?: z.AnyZodObject,\n): M extends z.AnyZodObject ? z.AnyZodObject : z.AnyZodObject | undefined {\n if (!createMutualSchema) return mutualSchema as any;\n if (!mutualSchema) return createMutualSchema as any;\n\n return mutualSchema.merge(createMutualSchema) as any;\n}\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 CMO extends z.AnyZodObject | undefined = undefined,\n>(\n config: MonoriseEntityConfig<T, B, C, M, CO, MO, CMO>,\n effectiveMutualSchema: z.AnyZodObject | undefined,\n) {\n const { baseSchema, createSchema, effect } = config;\n\n // Deliberately NOT `MO & CMO`-typed: finalSchema.parse() runs against\n // effectiveMutualSchema's real runtime shape (below), but EntitySchemaMap\n // — the type callers see back from a *read* — is generated from this\n // same FinalSchemaType (packages/cli/commands/utils/generate.ts). Mutual\n // fields are never stored, so a required createMutualSchema field must\n // stay optional here; only the create-path runtime validation is allowed\n // to be strict.\n type FinalSchemaType = CO extends z.AnyZodObject\n ? MO extends z.AnyZodObject\n ? z.ZodObject<B & CO['shape'] & MO['shape']>\n : z.ZodObject<B & CO['shape']>\n : MO extends z.AnyZodObject\n ? z.ZodObject<B & MO['shape']>\n : z.ZodObject<B>;\n\n const finalSchema = z.object({\n ...baseSchema.shape,\n ...createSchema?.shape,\n ...effectiveMutualSchema?.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 CMO extends z.AnyZodObject | undefined = undefined,\n>(\n config: MonoriseEntityConfig<T, B, C, M, CO, MO, CMO>,\n) => {\n // Computed once here (config-definition time, not per-request/per-item)\n // and reused by every create-path call site (afterCreateEntityHook,\n // TransactionService.collectCreateEvents, UpsertEntityController) instead\n // of each rebuilding the same merged ZodObject from scratch.\n const { mutualSchema, createMutualSchema } = config.mutual || {};\n const effectiveMutualSchema = resolveEffectiveMutualSchema(\n mutualSchema,\n createMutualSchema,\n );\n\n return {\n ...config,\n // Derived output, not an input on MonoriseEntityConfig — there's\n // nowhere to declare this on the config type itself. Read by name\n // across packages/core (EntityServiceLifeCycle, TransactionService,\n // UpsertEntityController); don't hand-set it on a config object built\n // outside this factory (e.g. a test fixture) — build through\n // createEntityConfig instead, or it silently falls out of sync with\n // mutual.mutualSchema/createMutualSchema.\n effectiveMutualSchema,\n finalSchema: makeSchema(config, effectiveMutualSchema),\n };\n};\n\nconst createMutualConfig = <MD extends z.ZodRawShape>(\n config: MutualConfigInput<MD>,\n): MutualConfig<MD> => {\n // Catches a specific footgun before it falls through to the generic\n // \"one of mutualDataSchema or asEntity is required\" error below: a config\n // module that does `asEntity: importedEntityConfig` where\n // `importedEntityConfig` comes from a circular import (e.g. student.ts\n // imports enrollmentEntityConfig, which itself lives in a module that\n // imports student.ts) evaluates to `undefined` at this point, not a\n // missing key — `'asEntity' in config` is true, `config.asEntity` is not.\n // The generic error below would say \"one of ... is required\", which sends\n // people looking for a typo instead of an import cycle.\n if ('asEntity' in config && config.asEntity === undefined) {\n throw new Error(\n \"createMutualConfig: 'asEntity' is undefined — likely a circular import between entity config files (the imported entity config module hasn't finished initializing yet). Restructure the imports to break the cycle.\",\n );\n }\n\n if (config.asEntity && config.mutualDataSchema) {\n throw new Error(\n \"createMutualConfig: 'asEntity' and 'mutualDataSchema' are mutually exclusive. \" +\n \"When 'asEntity' is set, mutualDataSchema is derived automatically from \" +\n \"asEntity.finalSchema — remove the explicit mutualDataSchema (or drop 'asEntity' \" +\n 'if this mutual should keep its own independently-authored schema).',\n );\n }\n\n if (!config.asEntity && !config.mutualDataSchema) {\n throw new Error(\n \"createMutualConfig: one of 'mutualDataSchema' or 'asEntity' is required.\",\n );\n }\n\n // Unchanged identity behavior when `asEntity` isn't set — existing configs are unaffected.\n // `mutualDataSchema` is guaranteed present here (checked above), so this cast just tells\n // TypeScript what the runtime guard already established.\n if (!config.asEntity) return config as MutualConfig<MD>;\n\n // `finalSchema` (not baseSchema/createSchema alone) on purpose: the declarative mutual\n // processor's `afterCreateEntityHook` call needs the full schema to correctly wire the\n // synthetic entity's own further `mutualFields` too (see mutual-processor.ts).\n //\n // This does NOT mean finalSchema-shaped data is what gets PERSISTED as this mutual's\n // `mutualData` or the synthetic entity's `data` — both `MutualService.createMutual` and\n // `mutual-processor.ts` re-derive a narrower `asEntity.createSchema ?? asEntity.baseSchema`\n // parse for anything actually written to storage, specifically so the target entity's own\n // mutual-field keys (e.g. `courseIds`, if the target entity itself declares `mutualFields`)\n // never get baked into stored data — the same \"mutual fields are never stored\" invariant\n // `makeSchema` already documents for ordinary entities. `mutualDataSchema` staying as\n // `finalSchema` is what makes the fuller shape available to whichever call site needs it for\n // hook-wiring purposes, without that fuller shape leaking into what's actually persisted.\n return {\n ...config,\n mutualDataSchema: config.asEntity.finalSchema as unknown as z.ZodObject<MD>,\n };\n};\n\nexport { createEntityConfig, createMutualConfig, resolveEffectiveMutualSchema };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAIO,IAAK,SAAL,kBAAKA,YAAL;AAAK,SAAAA;AAAA,GAAA;;;ACJZ,SAAS,SAAS;AAoBlB,SAAS,6BACP,cACA,oBACwE;AACxE,MAAI,CAAC,mBAAoB,QAAO;AAChC,MAAI,CAAC,aAAc,QAAO;AAE1B,SAAO,aAAa,MAAM,kBAAkB;AAC9C;AAEA,SAAS,WASP,QACA,uBACA;AACA,QAAM,EAAE,YAAY,cAAc,OAAO,IAAI;AAiB7C,QAAM,cAAc,EAAE,OAAO,iDACxB,WAAW,QACX,6CAAc,QACd,+DAAuB,MAC3B;AAED,MAAI,QAAQ;AACV,WAAO,OAAO,WAAW;AAAA,EAC3B;AAEA,SAAO;AACT;AAEA,IAAM,qBAAqB,CASzB,WACG;AAKH,QAAM,EAAE,cAAc,mBAAmB,IAAI,OAAO,UAAU,CAAC;AAC/D,QAAM,wBAAwB;AAAA,IAC5B;AAAA,IACA;AAAA,EACF;AAEA,SAAO,iCACF,SADE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IASL;AAAA,IACA,aAAa,WAAW,QAAQ,qBAAqB;AAAA,EACvD;AACF;AAEA,IAAM,qBAAqB,CACzB,WACqB;AAUrB,MAAI,cAAc,UAAU,OAAO,aAAa,QAAW;AACzD,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAEA,MAAI,OAAO,YAAY,OAAO,kBAAkB;AAC9C,UAAM,IAAI;AAAA,MACR;AAAA,IAIF;AAAA,EACF;AAEA,MAAI,CAAC,OAAO,YAAY,CAAC,OAAO,kBAAkB;AAChD,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAKA,MAAI,CAAC,OAAO,SAAU,QAAO;AAe7B,SAAO,iCACF,SADE;AAAA,IAEL,kBAAkB,OAAO,SAAS;AAAA,EACpC;AACF;","names":["Entity"]}
1
+ {"version":3,"sources":["../types/monorise.type.ts","../utils/index.ts","../utils/api-key-policy.ts"],"sourcesContent":["import type { z } from 'zod';\nimport type { createEntityConfig } from '../utils';\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 */\n/**\n * @description The shape `createMutualConfig(...)` is CALLED with — looser than the resolved\n * `MutualConfig` it returns. `mutualDataSchema` is optional here (and mutually exclusive with\n * `asEntity`) because `createMutualConfig` resolves it before returning: every OTHER consumer in\n * this codebase (`mutualFields[key].mutual`, `MutualService`, the processors) reads the resolved\n * `MutualConfig` type below, where `mutualDataSchema` stays REQUIRED — the same \"loose input,\n * strict resolved output\" split `createEntityConfig`/`MonoriseEntityConfig` already use for\n * `finalSchema`/`effectiveMutualSchema`. Import this type only if you're writing something that\n * itself calls `createMutualConfig`; every other call site should keep using `MutualConfig`.\n */\nexport interface MutualConfigInput<MD extends z.ZodRawShape = z.ZodRawShape> {\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 /** Required unless `asEntity` is set — see `asEntity`'s own doc comment. */\n mutualDataSchema?: z.ZodObject<MD>;\n\n /**\n * @description (Optional) Materialize this mutual relationship as a real,\n * independently-queryable `Entity` whenever it's created — whether imperatively via\n * `MutualService.createMutual` or automatically via a declarative `mutualFields` entry that\n * references this config — by passing the `createEntityConfig(...)` return value for the\n * entity type it should materialize as.\n *\n * When set, in addition to the mutual edge, a real `Entity` is created:\n * `entityType = asEntity.name`, `entityId = <the mutual's own generated ulid>`,\n * `data = <the mutual's own parsed mutualData>`. This lets the relationship be looked up via\n * monorise's `tags` mechanism (an indexed GSI lookup) instead of scanning and filtering every\n * edge in application code, and lets the synthetic entity carry its own `mutualFields`.\n *\n * `mutualDataSchema` must be OMITTED when `asEntity` is set: it's derived automatically from\n * `asEntity.finalSchema` (that entity's own `baseSchema` + `createSchema` +\n * `effectiveMutualSchema`, merged — the same schema this codebase already validates every\n * normal `createEntity` payload against). Chosen over a narrower `baseSchema`/`createSchema`\n * derivation because `MutualService.createMutual`'s `asEntity` path fires\n * `afterCreateEntityHook` on the synthetic entity — the same hook that wires up an entity's\n * OWN further `mutualFields` — so anything narrower than `finalSchema` would silently break\n * that wiring for any `asEntity`-targeted entity that itself declares further relationships.\n * Providing both `asEntity` and `mutualDataSchema` is a build-time AND runtime error.\n *\n * The synthetic entity is always created SYNCHRONOUSLY, in the same DynamoDB transaction as\n * the mutual write, with its `afterCreateEntityHook` (tags/mutualFields wiring) firing\n * immediately after the commit. There is no asynchronous mode: the entity either exists the\n * moment the mutual does, or neither is written. That costs a `TransactWriteItems` (2x WCU\n * versus a plain write) but leaves no window in which the mutual exists and its projection\n * does not.\n *\n * An explicit `options.asEntity` passed directly at an imperative `createMutual(...)` call\n * site always overrides this config-level value — see `resolveAsEntity` in `@monorise/core`'s\n * `mutual.service`.\n *\n * @example\n * ```ts\n * const enrollmentMutual = createMutualConfig({\n * entities: [Entity.STUDENT, Entity.COURSE],\n * asEntity: enrollmentEntityConfig, // the createEntityConfig(...) result for Entity.ENROLLMENT\n * });\n * ```\n */\n asEntity?: ReturnType<typeof createEntityConfig>;\n}\n\n/**\n * @description The resolved shape `createMutualConfig(...)` RETURNS, and what every other\n * consumer in this codebase (`mutualFields[key].mutual`, `MutualService`, the mutual processor)\n * actually references. Unlike `MutualConfigInput`, `mutualDataSchema` is REQUIRED here — by the\n * time a `MutualConfig` object exists, `createMutualConfig` has already derived it from\n * `asEntity.finalSchema` when needed, so every existing `.mutualDataSchema` read across this\n * codebase keeps its original, always-defined guarantee regardless of whether the mutual uses\n * `asEntity` or not.\n */\nexport interface MutualConfig<MD extends z.ZodRawShape = z.ZodRawShape>\n extends Omit<MutualConfigInput<MD>, 'mutualDataSchema'> {\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 CMO extends z.AnyZodObject | 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 * Used to validate mutual fields on create, and — derived to a partial — on update. You do NOT need to author this `.partial()`: the SDK partials it for the update path, so an update that doesn't touch every mutual relationship stays valid regardless of how this is declared.\n */\n mutualSchema: MO;\n\n /**\n * @description (Optional) Stricter schema applied ONLY when the entity is created — falls back to `mutualSchema` if not provided, so existing configs are unaffected. When provided, its shape is merged over `mutualSchema` for create; fields only `mutualSchema` declares (and `createMutualSchema` doesn't mention) are still validated and wired, not dropped.\n *\n * Use this when a mutual relationship must always be wired at creation time (e.g. every Competition must have an owning Organisation from the start). It does not affect updates either way — the update path derives a partial from `mutualSchema` itself, so a required-at-create relationship never has to be resent on an unrelated patch.\n *\n * Without this, a create silently succeeds even if a required mutual link is omitted from the payload — the entity is created but never gets wired to the relationship, with no error anywhere.\n *\n * Note: this only strengthens the *runtime* validation on create — `EntitySchemaMap` (the type callers see back from a read, generated from `finalSchema`) stays `MO`-shaped regardless, since mutual fields are never stored and a read can never actually return one. Don't expect a `createMutualSchema`-required field to show up as required in generated read types.\n *\n * The same-named `PUT /entity/:type/:id` upsert endpoint applies this schema only when the entity doesn't already exist — the same call is strict or lenient purely depending on whether that ID was already there.\n *\n * @example\n * ```ts\n * const mutualSchema = z.object({ organisationIds: z.string().array() }).partial();\n * const createMutualSchema = z.object({ organisationIds: z.string().array() }); // required on create\n * ```\n */\n createMutualSchema?: CMO;\n // Deliberately typed via its own `CMO` generic rather than `MO` — the\n // whole point is that it's allowed to be a DIFFERENT (stricter) shape\n // than `mutualSchema`, e.g. built via `mutualSchema.required({ field:\n // true })`, which is a structurally different ZodObject type, not `MO`\n // itself. Only the runtime merge (`resolveEffectiveMutualSchema` /\n // `effectiveMutualSchema`, see `packages/base/utils`) combines `MO` and\n // `CMO` — `finalSchema`'s TYPE deliberately stays `MO`-based; see the\n // note above and `makeSchema`'s own comment for why.\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: {\n entityId: string;\n entityType: string;\n data: Record<string, any>;\n createdAt: string;\n updatedAt: string;\n }) => {\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>\n ? K\n : never]: K;\n } extends never\n ? string\n : keyof {\n [K in keyof B as B[K] extends\n | z.ZodNumber\n | z.ZodOptional<z.ZodNumber>\n ? K\n : 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>\n ? K\n : never]: K;\n } extends never\n ? string\n : keyof {\n [K in keyof B as B[K] extends\n | z.ZodNumber\n | z.ZodOptional<z.ZodNumber>\n ? K\n : 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 { z } from 'zod';\nimport type {\n Entity,\n MonoriseEntityConfig,\n MutualConfig,\n MutualConfigInput,\n} from '../types/monorise.type';\n\n/**\n * @description Merges `mutualSchema` and `createMutualSchema` into the schema\n * actually used to validate a create payload. A plain `createMutualSchema ||\n * mutualSchema` fallback would DROP any mutual field that's declared on\n * `mutualSchema` but omitted from `createMutualSchema` (e.g. a\n * `createMutualSchema` authored to cover only the newly-required field,\n * without repeating every other optional mutual field) — `.parse()` strips\n * unknown keys, so that field's wiring would silently never fire even when\n * the caller supplied it. Merging shapes (with `createMutualSchema`'s keys\n * taking precedence on overlap, since it's the stricter one) keeps every\n * mutual field in play while still enforcing the create-only requirement.\n */\nfunction resolveEffectiveMutualSchema<M extends z.AnyZodObject | undefined>(\n mutualSchema: M,\n createMutualSchema?: z.AnyZodObject,\n): M extends z.AnyZodObject ? z.AnyZodObject : z.AnyZodObject | undefined {\n if (!createMutualSchema) return mutualSchema as any;\n if (!mutualSchema) return createMutualSchema as any;\n\n return mutualSchema.merge(createMutualSchema) as any;\n}\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 CMO extends z.AnyZodObject | undefined = undefined,\n>(\n config: MonoriseEntityConfig<T, B, C, M, CO, MO, CMO>,\n effectiveMutualSchema: z.AnyZodObject | undefined,\n) {\n const { baseSchema, createSchema, effect } = config;\n\n // Deliberately NOT `MO & CMO`-typed: finalSchema.parse() runs against\n // effectiveMutualSchema's real runtime shape (below), but EntitySchemaMap\n // — the type callers see back from a *read* — is generated from this\n // same FinalSchemaType (packages/cli/commands/utils/generate.ts). Mutual\n // fields are never stored, so a required createMutualSchema field must\n // stay optional here; only the create-path runtime validation is allowed\n // to be strict.\n type FinalSchemaType = CO extends z.AnyZodObject\n ? MO extends z.AnyZodObject\n ? z.ZodObject<B & CO['shape'] & MO['shape']>\n : z.ZodObject<B & CO['shape']>\n : MO extends z.AnyZodObject\n ? z.ZodObject<B & MO['shape']>\n : z.ZodObject<B>;\n\n const finalSchema = z.object({\n ...baseSchema.shape,\n ...createSchema?.shape,\n ...effectiveMutualSchema?.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 CMO extends z.AnyZodObject | undefined = undefined,\n>(\n config: MonoriseEntityConfig<T, B, C, M, CO, MO, CMO>,\n) => {\n // Computed once here (config-definition time, not per-request/per-item)\n // and reused by every create-path call site (afterCreateEntityHook,\n // TransactionService.collectCreateEvents, UpsertEntityController) instead\n // of each rebuilding the same merged ZodObject from scratch.\n const { mutualSchema, createMutualSchema } = config.mutual || {};\n const effectiveMutualSchema = resolveEffectiveMutualSchema(\n mutualSchema,\n createMutualSchema,\n );\n\n return {\n ...config,\n // Derived output, not an input on MonoriseEntityConfig — there's\n // nowhere to declare this on the config type itself. Read by name\n // across packages/core (EntityServiceLifeCycle, TransactionService,\n // UpsertEntityController); don't hand-set it on a config object built\n // outside this factory (e.g. a test fixture) — build through\n // createEntityConfig instead, or it silently falls out of sync with\n // mutual.mutualSchema/createMutualSchema.\n effectiveMutualSchema,\n finalSchema: makeSchema(config, effectiveMutualSchema),\n };\n};\n\nconst createMutualConfig = <MD extends z.ZodRawShape>(\n config: MutualConfigInput<MD>,\n): MutualConfig<MD> => {\n // Catches a specific footgun before it falls through to the generic\n // \"one of mutualDataSchema or asEntity is required\" error below: a config\n // module that does `asEntity: importedEntityConfig` where\n // `importedEntityConfig` comes from a circular import (e.g. student.ts\n // imports enrollmentEntityConfig, which itself lives in a module that\n // imports student.ts) evaluates to `undefined` at this point, not a\n // missing key — `'asEntity' in config` is true, `config.asEntity` is not.\n // The generic error below would say \"one of ... is required\", which sends\n // people looking for a typo instead of an import cycle.\n if ('asEntity' in config && config.asEntity === undefined) {\n throw new Error(\n \"createMutualConfig: 'asEntity' is undefined — likely a circular import between entity config files (the imported entity config module hasn't finished initializing yet). Restructure the imports to break the cycle.\",\n );\n }\n\n if (config.asEntity && config.mutualDataSchema) {\n throw new Error(\n \"createMutualConfig: 'asEntity' and 'mutualDataSchema' are mutually exclusive. \" +\n \"When 'asEntity' is set, mutualDataSchema is derived automatically from \" +\n \"asEntity.finalSchema — remove the explicit mutualDataSchema (or drop 'asEntity' \" +\n 'if this mutual should keep its own independently-authored schema).',\n );\n }\n\n if (!config.asEntity && !config.mutualDataSchema) {\n throw new Error(\n \"createMutualConfig: one of 'mutualDataSchema' or 'asEntity' is required.\",\n );\n }\n\n // Unchanged identity behavior when `asEntity` isn't set — existing configs are unaffected.\n // `mutualDataSchema` is guaranteed present here (checked above), so this cast just tells\n // TypeScript what the runtime guard already established.\n if (!config.asEntity) return config as MutualConfig<MD>;\n\n // `finalSchema` (not baseSchema/createSchema alone) on purpose: the declarative mutual\n // processor's `afterCreateEntityHook` call needs the full schema to correctly wire the\n // synthetic entity's own further `mutualFields` too (see mutual-processor.ts).\n //\n // This does NOT mean finalSchema-shaped data is what gets PERSISTED as this mutual's\n // `mutualData` or the synthetic entity's `data` — both `MutualService.createMutual` and\n // `mutual-processor.ts` re-derive a narrower `asEntity.createSchema ?? asEntity.baseSchema`\n // parse for anything actually written to storage, specifically so the target entity's own\n // mutual-field keys (e.g. `courseIds`, if the target entity itself declares `mutualFields`)\n // never get baked into stored data — the same \"mutual fields are never stored\" invariant\n // `makeSchema` already documents for ordinary entities. `mutualDataSchema` staying as\n // `finalSchema` is what makes the fuller shape available to whichever call site needs it for\n // hook-wiring purposes, without that fuller shape leaking into what's actually persisted.\n return {\n ...config,\n mutualDataSchema: config.asEntity.finalSchema as unknown as z.ZodObject<MD>,\n };\n};\n\nexport { createEntityConfig, createMutualConfig, resolveEffectiveMutualSchema };\n","import type { z } from 'zod';\nimport type {\n ApiKeyAccessLevel,\n ApiKeyEntityGrant,\n ApiKeyFieldList,\n ApiKeyMutualGrant,\n ApiKeyPolicies,\n ApiKeyPolicy,\n} from '../types/api-key-policy.type';\nimport type { Entity } from '../types/monorise.type';\n\n/**\n * @description Built-in policy: read, write and delete on every entity and\n * relationship, plus every custom route. Every key in the legacy array form of\n * `API_KEYS` maps to it.\n */\nexport const FULL_API_KEY_POLICY = 'full';\n\nconst ACCESS_LEVELS: readonly ApiKeyAccessLevel[] = ['none', 'read', 'write'];\nconst SYSTEM_FIELDS = ['$entityId', '$createdAt'];\nconst ENTITY_GRANT_KEYS = [\n 'read',\n 'list',\n 'create',\n 'update',\n 'write',\n 'delete',\n 'tags',\n 'mutuals',\n];\nconst MUTUAL_GRANT_KEYS = ['read', 'create', 'update', 'write', 'delete'];\nconst POLICY_KEYS = ['entities', 'routes'];\n\n/** `'*'` for every field, or the allowed fields. */\nexport type ApiKeyFieldAccess = '*' | ReadonlySet<string>;\n\n/** What a policy allows on one entity type. `null` means not granted. */\nexport type ApiKeyEntityAccess = {\n /**\n * Whether the key can see the type at all: the policy grants it anything\n * but `'none'`, by name or through its `'*'` entry. A type the key can't\n * see answers 404, as if it didn't exist.\n */\n visible: boolean;\n /** Fields the key can read, by ID or unique field, and in every response. */\n read: ApiKeyFieldAccess | null;\n /** Whether the key can list the whole type: listing, search and tag queries. */\n list: boolean;\n create: ApiKeyFieldAccess | null;\n update: ApiKeyFieldAccess | null;\n delete: boolean;\n tags: ApiKeyFieldAccess | null;\n};\n\n/** What a policy allows on one direction of a relationship. Fields are `mutualData` fields. */\nexport type ApiKeyMutualAccess = {\n read: ApiKeyFieldAccess | null;\n create: ApiKeyFieldAccess | null;\n update: ApiKeyFieldAccess | null;\n delete: boolean;\n};\n\nexport type CompiledApiKeyPolicy = {\n name: string;\n /** True only for the built-in `full` policy. */\n full: boolean;\n entity(entityType: string): ApiKeyEntityAccess;\n /**\n * Access to the direction `byEntityType`→`entityType`, as in\n * `/mutual/:byEntityType/:byEntityId/:entityType`. `null` when either end\n * type isn't visible.\n */\n mutual(byEntityType: string, entityType: string): ApiKeyMutualAccess | null;\n /** Whether the policy grants a custom route permission. `full` grants every one. */\n allowsRoute(permission: string): boolean;\n};\n\ntype CompiledEntity = {\n access: ApiKeyEntityAccess;\n mutualDefault: ApiKeyAccessLevel;\n mutuals: ReadonlyMap<string, ApiKeyMutualGrant>;\n};\n\nconst hasOwn = (object: object, key: string) =>\n Object.prototype.hasOwnProperty.call(object, key);\n\nconst toAccess = (list: ApiKeyFieldList | undefined) =>\n list === undefined ? null : list === '*' ? '*' : new Set<string>(list);\n\nconst union = (\n ...accesses: (ApiKeyFieldAccess | null)[]\n): ApiKeyFieldAccess | null => {\n let fields: Set<string> | null = null;\n for (const access of accesses) {\n if (access === null) continue;\n if (access === '*') return '*';\n fields = new Set([...(fields ?? []), ...access]);\n }\n return fields;\n};\n\nconst withoutSystemFields = (access: ApiKeyFieldAccess | null) =>\n access === null || access === '*'\n ? access\n : new Set([...access].filter((field) => !SYSTEM_FIELDS.includes(field)));\n\nconst HIDDEN: CompiledEntity = {\n access: {\n visible: false,\n read: null,\n list: false,\n create: null,\n update: null,\n delete: false,\n tags: null,\n },\n mutualDefault: 'none',\n mutuals: new Map(),\n};\n\nconst compileEntityGrant = (\n grant: ApiKeyEntityGrant | undefined,\n): CompiledEntity => {\n if (grant === undefined || grant === 'none') return HIDDEN;\n\n if (grant === 'read' || grant === 'write') {\n const write = grant === 'write';\n return {\n access: {\n visible: true,\n read: '*',\n list: true,\n create: write ? '*' : null,\n update: write ? '*' : null,\n delete: write,\n tags: '*',\n },\n mutualDefault: grant,\n mutuals: new Map(),\n };\n }\n\n const create = union(toAccess(grant.create), toAccess(grant.write));\n const update = union(toAccess(grant.update), toAccess(grant.write));\n const read = union(toAccess(grant.read), withoutSystemFields(create), update);\n const { '*': mutualDefault = 'none', ...mutuals } = grant.mutuals ?? {};\n\n return {\n access: {\n visible: true,\n read,\n list: grant.list === true,\n create,\n update,\n delete: grant.delete === true,\n tags:\n grant.tags !== undefined\n ? toAccess(grant.tags)\n : read === '*'\n ? '*'\n : null,\n },\n mutualDefault,\n mutuals: new Map(Object.entries(mutuals) as [string, ApiKeyMutualGrant][]),\n };\n};\n\nconst compileMutualGrant = (grant: ApiKeyMutualGrant): ApiKeyMutualAccess => {\n if (grant === 'none' || grant === 'read' || grant === 'write') {\n const write = grant === 'write';\n return {\n read: grant === 'none' ? null : '*',\n create: write ? '*' : null,\n update: write ? '*' : null,\n delete: write,\n };\n }\n\n const create = union(toAccess(grant.create), toAccess(grant.write));\n const update = union(toAccess(grant.update), toAccess(grant.write));\n return {\n read: union(toAccess(grant.read), create, update),\n create,\n update,\n delete: grant.delete === true,\n };\n};\n\n/**\n * @description Compiles a policy into the access it grants. Compiled entity\n * grants are cached, so compile once per policy and reuse the result.\n *\n * `name === 'full'` compiles the built-in policy and ignores `policy`.\n */\nexport const compileApiKeyPolicy = (\n name: string,\n policy?: ApiKeyPolicy,\n): CompiledApiKeyPolicy => {\n const full = name === FULL_API_KEY_POLICY;\n const entities: Record<string, ApiKeyEntityGrant | undefined> = full\n ? { '*': 'write' }\n : policy === 'read' || policy === 'write'\n ? { '*': policy }\n : (policy?.entities ?? {});\n\n const routes = new Set(\n !full && typeof policy === 'object' ? (policy.routes ?? []) : [],\n );\n\n // Entity types come from request URLs and bodies. Looking them up as own\n // keys stops 'constructor' or '__proto__' from finding Object.prototype, and\n // caching by the grant used means a type the policy doesn't name shares the\n // '*' entry instead of adding one per string a caller sends.\n const cache = new Map<string, CompiledEntity>();\n const compiled = (entityType: string) => {\n const grantKey = hasOwn(entities, entityType) ? entityType : '*';\n let entry = cache.get(grantKey);\n if (!entry) {\n entry = compileEntityGrant(\n hasOwn(entities, grantKey) ? entities[grantKey] : undefined,\n );\n cache.set(grantKey, entry);\n }\n return entry;\n };\n\n return {\n name,\n full,\n entity: (entityType) => compiled(entityType).access,\n mutual: (byEntityType, entityType) => {\n const from = compiled(byEntityType);\n if (!from.access.visible || !compiled(entityType).access.visible) {\n return null;\n }\n return compileMutualGrant(\n from.mutuals.get(entityType) ?? from.mutualDefault,\n );\n },\n allowsRoute: (permission) => full || routes.has(permission),\n };\n};\n\n/**\n * @description The parts of an entity config that policy validation reads.\n * Any config built by `createEntityConfig` satisfies it. Configs are keyed by\n * entity type.\n */\nexport type ApiKeyPolicyEntityConfig = {\n baseSchema: z.AnyZodObject;\n createSchema?: z.AnyZodObject;\n tags?: { name: string }[];\n mutual?: {\n mutualSchema?: z.AnyZodObject;\n createMutualSchema?: z.AnyZodObject;\n mutualFields?: Record<\n string,\n {\n entityType: string | Entity;\n mutual?: {\n mutualDataSchema?: z.AnyZodObject;\n asEntity?: { name: string | Entity };\n };\n }\n >;\n };\n};\n\nconst isPlainObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n\nconst quoteList = (items: Iterable<string>) =>\n [...items].map((item) => `'${item}'`).join(', ');\n\n/**\n * @description Checks policies against the entity configs. Returns one message\n * per problem; an empty array means the policies are valid. The CLI runs this\n * at build time and the API handler at cold start.\n */\nexport const validateApiKeyPolicies = (\n policies: unknown,\n entityConfigs: Record<string, ApiKeyPolicyEntityConfig>,\n): string[] => {\n const errors: string[] = [];\n if (!isPlainObject(policies)) {\n return ['API key policies must be an object keyed by policy name'];\n }\n\n const entityNames = Object.keys(entityConfigs);\n const isEntityType = (name: string) => hasOwn(entityConfigs, name);\n\n const mutualFieldNames = (config: ApiKeyPolicyEntityConfig) =>\n new Set([\n ...Object.keys(config.mutual?.mutualFields ?? {}),\n ...Object.keys(config.mutual?.mutualSchema?.shape ?? {}),\n ...Object.keys(config.mutual?.createMutualSchema?.shape ?? {}),\n ]);\n\n const ownFields = (config: ApiKeyPolicyEntityConfig) =>\n new Set([\n ...Object.keys(config.baseSchema?.shape ?? {}),\n ...Object.keys(config.createSchema?.shape ?? {}),\n ]);\n\n // The mutual config for a pair can be declared on either side.\n const mutualConfig = (byEntityType: string, entityType: string) => {\n const declared = (from: string, to: string) =>\n Object.values(entityConfigs[from]?.mutual?.mutualFields ?? {}).find(\n (field) => field.entityType === to && field.mutual,\n )?.mutual;\n return (\n declared(byEntityType, entityType) ?? declared(entityType, byEntityType)\n );\n };\n\n const checkFieldList = (\n where: string,\n list: unknown,\n allowed: Set<string> | undefined,\n describe: (field: string) => string | undefined,\n ) => {\n if (list === '*') return;\n if (\n !Array.isArray(list) ||\n !list.every((field) => typeof field === 'string')\n ) {\n errors.push(`${where} must be '*' or an array of field names`);\n return;\n }\n for (const field of list) {\n const problem = describe(field);\n if (problem) errors.push(`${where}: ${problem}`);\n else if (allowed && !allowed.has(field)) {\n errors.push(`${where}: unknown field '${field}'`);\n }\n }\n };\n\n const checkUnknownKeys = (\n where: string,\n value: Record<string, unknown>,\n known: string[],\n ) => {\n for (const key of Object.keys(value)) {\n if (!known.includes(key)) {\n errors.push(\n `${where}: unknown key '${key}' (expected ${quoteList(known)})`,\n );\n }\n }\n };\n\n const checkLevel = (where: string, value: unknown) => {\n if (!ACCESS_LEVELS.includes(value as ApiKeyAccessLevel)) {\n errors.push(`${where} must be one of ${quoteList(ACCESS_LEVELS)}`);\n }\n };\n\n const checkMutualGrant = (\n where: string,\n grant: unknown,\n byEntityType: string,\n entityType: string,\n ) => {\n if (typeof grant === 'string') return checkLevel(where, grant);\n if (!isPlainObject(grant)) {\n errors.push(`${where} must be an access level or an object`);\n return;\n }\n checkUnknownKeys(where, grant, MUTUAL_GRANT_KEYS);\n const dataFields = mutualConfig(byEntityType, entityType)?.mutualDataSchema\n ?.shape;\n const allowed = dataFields ? new Set(Object.keys(dataFields)) : undefined;\n for (const key of ['read', 'create', 'update', 'write']) {\n if (grant[key] === undefined) continue;\n checkFieldList(`${where}.${key}`, grant[key], allowed, () => undefined);\n }\n if (grant.delete !== undefined && typeof grant.delete !== 'boolean') {\n errors.push(`${where}.delete must be a boolean`);\n }\n };\n\n const checkEntityGrant = (\n where: string,\n grant: unknown,\n entityType: string,\n ) => {\n const config = entityConfigs[entityType];\n if (typeof grant === 'string') return checkLevel(where, grant);\n if (!isPlainObject(grant)) {\n errors.push(`${where} must be an access level or an object`);\n return;\n }\n checkUnknownKeys(where, grant, ENTITY_GRANT_KEYS);\n\n const fields = ownFields(config);\n const mutualFields = mutualFieldNames(config);\n const fieldListErrors = errors.length;\n for (const key of ['read', 'create', 'update', 'write']) {\n if (grant[key] === undefined) continue;\n const allowsSystemFields = key === 'create' || key === 'write';\n const allowed = allowsSystemFields\n ? new Set([...fields, ...SYSTEM_FIELDS])\n : fields;\n checkFieldList(`${where}.${key}`, grant[key], allowed, (field) => {\n if (SYSTEM_FIELDS.includes(field)) {\n return allowsSystemFields\n ? undefined\n : `'${field}' can only be granted in 'create' or 'write'`;\n }\n if (mutualFields.has(field) && !fields.has(field)) {\n return `'${field}' is a relationship field; grant it under 'mutuals' instead`;\n }\n return undefined;\n });\n }\n if (grant.delete !== undefined && typeof grant.delete !== 'boolean') {\n errors.push(`${where}.delete must be a boolean`);\n }\n if (grant.list !== undefined && typeof grant.list !== 'boolean') {\n errors.push(`${where}.list must be a boolean`);\n } else if (grant.list === true && errors.length === fieldListErrors) {\n // Compiling needs valid field lists; a malformed one is reported above.\n const { read } = compileEntityGrant(grant as ApiKeyEntityGrant).access;\n if (read === null || (read !== '*' && read.size === 0)) {\n errors.push(\n `${where}.list needs fields to read; a listing would return no data`,\n );\n }\n }\n if (grant.tags !== undefined) {\n checkFieldList(\n `${where}.tags`,\n grant.tags,\n new Set((config.tags ?? []).map((tag) => tag.name)),\n () => undefined,\n );\n }\n if (grant.mutuals !== undefined) {\n if (!isPlainObject(grant.mutuals)) {\n errors.push(`${where}.mutuals must be an object`);\n return;\n }\n for (const [target, mutualGrant] of Object.entries(grant.mutuals)) {\n const mutualWhere = `${where}.mutuals.${target}`;\n if (target === '*') {\n checkLevel(mutualWhere, mutualGrant);\n } else if (!isEntityType(target)) {\n errors.push(`${mutualWhere}: unknown entity type '${target}'`);\n } else {\n checkMutualGrant(mutualWhere, mutualGrant, entityType, target);\n }\n }\n }\n };\n\n // A create grant that can never succeed is almost certainly a mistake.\n const checkCreateIsSatisfiable = (\n where: string,\n policy: CompiledApiKeyPolicy,\n entityType: string,\n ) => {\n const config = entityConfigs[entityType];\n const { create } = policy.entity(entityType);\n if (create === null) return;\n\n if (create !== '*') {\n const shape: Record<string, z.ZodTypeAny> = {\n ...config.baseSchema?.shape,\n ...config.createSchema?.shape,\n };\n const missing = Object.entries(shape)\n .filter(([field, schema]) => !schema.isOptional() && !create.has(field))\n .map(([field]) => field);\n if (missing.length) {\n errors.push(\n `${where}: create omits required field(s) ${quoteList(missing)}, so a key with this policy could never create one`,\n );\n }\n }\n\n const requiredMutuals = config.mutual?.createMutualSchema?.shape ?? {};\n for (const [field, schema] of Object.entries(\n requiredMutuals as Record<string, z.ZodTypeAny>,\n )) {\n const target = config.mutual?.mutualFields?.[field]?.entityType as\n | string\n | undefined;\n if (schema.isOptional() || !target) continue;\n if (!policy.mutual(entityType, target)?.create) {\n errors.push(\n `${where}: create needs create on ${entityType}→${target}, because createMutualSchema requires '${field}'`,\n );\n }\n }\n };\n\n for (const [name, policy] of Object.entries(policies)) {\n const where = `policy '${name}'`;\n const errorsBefore = errors.length;\n if (name === FULL_API_KEY_POLICY) {\n errors.push(`${where} is built in and cannot be redefined`);\n continue;\n }\n if (policy === 'read' || policy === 'write') continue;\n if (!isPlainObject(policy)) {\n errors.push(`${where} must be 'read', 'write' or an object`);\n continue;\n }\n checkUnknownKeys(where, policy, POLICY_KEYS);\n\n if (\n policy.routes !== undefined &&\n (!Array.isArray(policy.routes) ||\n !policy.routes.every(\n (permission) => typeof permission === 'string' && permission.length,\n ))\n ) {\n errors.push(`${where}.routes must be an array of permission names`);\n }\n\n const entities = policy.entities ?? {};\n if (!isPlainObject(entities)) {\n errors.push(`${where}.entities must be an object`);\n continue;\n }\n for (const [entityType, grant] of Object.entries(entities)) {\n const entityWhere = `${where}.entities.${entityType}`;\n if (entityType === '*') {\n checkLevel(entityWhere, grant);\n } else if (!isEntityType(entityType)) {\n errors.push(`${entityWhere}: unknown entity type '${entityType}'`);\n } else {\n checkEntityGrant(entityWhere, grant, entityType);\n }\n }\n\n // Structural errors would make the semantic checks below misleading.\n if (errors.length > errorsBefore) continue;\n\n const compiled = compileApiKeyPolicy(name, policy as ApiKeyPolicy);\n for (const entityType of entityNames) {\n const entityWhere = `${where}.entities.${entityType}`;\n checkCreateIsSatisfiable(entityWhere, compiled, entityType);\n\n for (const target of entityNames) {\n const asEntity = mutualConfig(entityType, target)?.asEntity?.name as\n | string\n | undefined;\n if (\n asEntity &&\n compiled.mutual(entityType, target)?.create &&\n !compiled.entity(asEntity).create\n ) {\n errors.push(\n `${entityWhere}: create on ${entityType}→${target} also creates a '${asEntity}' entity, so it needs create on '${asEntity}'`,\n );\n }\n }\n }\n }\n\n return errors;\n};\n\nconst VALIDATE_API_KEY_POLICIES = Symbol.for('monorise.validateApiKeyPolicies');\n\n/**\n * @description Declares the API key policies. Export the result as the default\n * export of the file `apiKeys` points to in `monorise.config.ts`; `API_KEYS`\n * then maps each policy name to its keys. `full` is built in.\n *\n * @example\n * ```ts\n * export default defineApiKeyPolicies({\n * 'agent-read': 'read',\n * client: {\n * entities: {\n * [Entity.ORDER]: { read: '*', create: ['customerId', 'items'], update: ['status'] },\n * [Entity.PRODUCT]: 'read',\n * },\n * },\n * });\n * ```\n */\nexport const defineApiKeyPolicies = (\n policies: ApiKeyPolicies,\n): ApiKeyPolicies => {\n // Lets the CLI validate the policies with this same version of the\n // validator, without resolving @monorise/base from the project itself.\n Object.defineProperty(policies, VALIDATE_API_KEY_POLICIES, {\n value: (entityConfigs: Record<string, ApiKeyPolicyEntityConfig>) =>\n validateApiKeyPolicies(policies, entityConfigs),\n enumerable: false,\n });\n return policies;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIO,IAAK,SAAL,kBAAKA,YAAL;AAAK,SAAAA;AAAA,GAAA;;;ACJZ,SAAS,SAAS;AAoBlB,SAAS,6BACP,cACA,oBACwE;AACxE,MAAI,CAAC,mBAAoB,QAAO;AAChC,MAAI,CAAC,aAAc,QAAO;AAE1B,SAAO,aAAa,MAAM,kBAAkB;AAC9C;AAEA,SAAS,WASP,QACA,uBACA;AACA,QAAM,EAAE,YAAY,cAAc,OAAO,IAAI;AAiB7C,QAAM,cAAc,EAAE,OAAO,iDACxB,WAAW,QACX,6CAAc,QACd,+DAAuB,MAC3B;AAED,MAAI,QAAQ;AACV,WAAO,OAAO,WAAW;AAAA,EAC3B;AAEA,SAAO;AACT;AAEA,IAAM,qBAAqB,CASzB,WACG;AAKH,QAAM,EAAE,cAAc,mBAAmB,IAAI,OAAO,UAAU,CAAC;AAC/D,QAAM,wBAAwB;AAAA,IAC5B;AAAA,IACA;AAAA,EACF;AAEA,SAAO,iCACF,SADE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IASL;AAAA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;AAAA,IAChD,YAAY;AAAA,EACd,CAAC;AACD,SAAO;AACT;","names":["Entity","_a","_b","_c","_d"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@monorise/base",
3
- "version": "4.7.0",
3
+ "version": "4.8.0-dev.0",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/monorist/monorise.git",