modelence 0.20.0-files.dev.0 → 0.21.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/{chunk-A2J5PPAQ.js → chunk-3SGMDISS.js} +11 -11
- package/dist/chunk-3SGMDISS.js.map +1 -0
- package/dist/chunk-KZZYA5HP.js +3 -0
- package/dist/chunk-KZZYA5HP.js.map +1 -0
- package/dist/{chunk-GPKIS2JI.js → chunk-SD3ERG2G.js} +3 -3
- package/dist/chunk-SD3ERG2G.js.map +1 -0
- package/dist/{chunk-JDYWT45S.js → chunk-SNADMLAT.js} +2 -2
- package/dist/{chunk-JDYWT45S.js.map → chunk-SNADMLAT.js.map} +1 -1
- package/dist/{package-OLG24DKG.js → package-BVTS5E5V.js} +2 -2
- package/dist/{package-OLG24DKG.js.map → package-BVTS5E5V.js.map} +1 -1
- package/dist/{render-A7HWHWAE.js → render-STDR67WK.js} +2 -2
- package/dist/{render-A7HWHWAE.js.map → render-STDR67WK.js.map} +1 -1
- package/dist/server-KAHRRRDU.js +2 -0
- package/dist/{server-OYDAIDR6.js.map → server-KAHRRRDU.js.map} +1 -1
- package/dist/server.js +1 -1
- package/dist/{transport-BBEHTFCG.js → transport-W6JIYZKZ.js} +2 -2
- package/dist/{transport-BBEHTFCG.js.map → transport-W6JIYZKZ.js.map} +1 -1
- package/package.json +1 -1
- package/dist/chunk-5LP23CUB.js +0 -3
- package/dist/chunk-5LP23CUB.js.map +0 -1
- package/dist/chunk-A2J5PPAQ.js.map +0 -1
- package/dist/chunk-GPKIS2JI.js.map +0 -1
- package/dist/server-OYDAIDR6.js +0 -2
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/app/module.ts","../src/data/schemaSerializer.ts","../src/data/schemaDefaults.ts","../src/data/store.ts","../src/data/types.ts","../src/auth/session.ts","../src/auth/db.ts","../src/auth/role.ts","../src/auth/index.ts","../src/live-query/context.ts","../src/utils/index.ts","../src/methods/clientAccess.ts","../src/live-query/handlers.ts","../src/methods/index.ts"],"names":["Module","name","stores","queries","mutations","routes","cronJobs","configSchema","rateLimits","channels","key","getConfig","serializeZodSchema","zodType","def","shape","serializedShape","value","effectsDef","serializeModelSchema","schema","serialized","item","isDocumentRecord","isZodType","getZodDef","getWrappedZodType","getZodDefaultValue","wrappedType","applyDefaultsToZodValue","applyDefaultsToModelSchema","applyDefaultsToSchemaDefinition","schemaDefinition","index","document","result","currentValue","defaultValue","COMPARABLE_INDEX_OPTION_FIELDS","hasModelencePrefix","getComparableIndexOptions","options","field","isSameIndexKey","left","right","leftEntries","rightEntries","leftField","leftDirection","rightField","rightDirection","isDeepStrictEqual","isSameIndexDefinition","existing","desired","getIndexKeySignature","direction","listIndexes","collection","error","MongoError","generateAutoIndexName","normalizeIndexName","autoName","Store","_Store","current","config","tail","extendedSchema","extendedIndexes","extendedSearchIndexes","combinedMethods","extendedStore","client","mode","shouldDropIndexes","shouldCreateIndexes","existingIndexes","indexByName","indexNamesByKey","droppedIndexNames","addIndexToLookup","existingIndex","keySignature","names","removeIndexFromLookup","indexName","dropIndexIfNeeded","currentIndexNames","idx","orphanedIndexes","existingIdx","orphanedIndex","requiresDropBeforeCreate","existingByName","existingNamesForKey","existingName","alignedIndex","searchIndex","selector","ObjectId","query","errorHandler","cursor","id","idSelector","docWithId","documents","update","replacement","filter","f","pipeline","operations","oldName","db","embedding","numCandidates","limit","projection","dimensions","similarity","schemaString","z","schemaNumber","schemaDate","schemaBoolean","schemaArray","schemaObject","schemaEnum","_collection","_schema","linkNoncesCollection","issueLinkNonce","userId","nonce","randomBytes","time","consumeLinkNonce","entry","sessionsCollection","obtainSession","authToken","existingSession","createSession","setSessionUser","clearSessionUser","invalidateAllUserSessions","now","expiresAt","processSessionHeartbeat","session","newExpiresAt","setAuthTokenCookie","res","clearAuthTokenCookie","session_default","args","user","getPublicConfigs","usersCollection","dbDisposableEmailDomains","emailVerificationTokensCollection","resetPasswordTokensCollection","roleMap","defaultRoles","initRoles","roles","_defaultRoles","definition","getUnauthenticatedRoles","getDefaultAuthenticatedRoles","requireAccess","requiredPermissions","missingPermission","permission","hasPermission","role","authenticate","userDoc","LiveData","isServer","requireServer","htmlToText","html","SYSTEM_PREFIX","CLIENT_CALLABLE_SYSTEM_METHODS","isClientCallableMethod","methodName","socketSubscriptions","getSocketSubs","socket","subs","handleSubscribeLiveQuery","payload","parsed","subscriptionId","method","clientInfo","existingSub","err","subscription","context","liveData","runLiveMethod","fetchAndEmit","data","sanitizeResult","getResponseTypeMap","isPendingPublish","isFetching","processPendingPublish","cleanup","handleUnsubscribeLiveQuery","sub","handleLiveQueryDisconnect","methods","createQuery","methodDef","validateMethodName","_createMethodInternal","createMutation","_createSystemQuery","validateSystemMethodName","_createSystemMutation","type","handler","permissions","runMethod","transaction","startTransaction","response"],"mappings":"yRA0CO,IAAMA,CAAAA,CAAN,KAKL,CAqCA,WAAA,CACEC,CAAAA,CACA,CACE,MAAA,CAAAC,CAAAA,CAAS,EAAC,CACV,OAAA,CAAAC,CAAAA,CAAU,EAAC,CACX,SAAA,CAAAC,CAAAA,CAAY,EAAC,CACb,MAAA,CAAAC,CAAAA,CAAS,EAAC,CACV,QAAA,CAAAC,CAAAA,CAAW,EAAC,CACZ,YAAA,CAAAC,CAAAA,CAAe,GACf,UAAA,CAAAC,CAAAA,CAAa,EAAC,CACd,QAAA,CAAAC,CAAAA,CAAW,EACb,CAAA,CAUI,EAAC,CACL,CACA,IAAA,CAAK,IAAA,CAAOR,CAAAA,CACZ,IAAA,CAAK,OAASC,CAAAA,CACd,IAAA,CAAK,OAAA,CAAUC,CAAAA,CACf,IAAA,CAAK,SAAA,CAAYC,CAAAA,CACjB,IAAA,CAAK,OAASC,CAAAA,CACd,IAAA,CAAK,QAAA,CAAWC,CAAAA,CAChB,IAAA,CAAK,YAAA,CAAeC,CAAAA,CACpB,IAAA,CAAK,WAAaC,CAAAA,CAClB,IAAA,CAAK,QAAA,CAAWC,EAClB,CAsBA,SAA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,CAAO,CAEd,MAAA2K,CAAAA,CAAY,GAAA,CAAI,OAAO,CAAA,CACjB3K,CACR,CAEA,OAAA2K,CAAAA,CAAY,GAAA,EAAI,CAETE,CACT,CAMA,eAAsB3B,EAAAA,CAAc7M,CAAAA,CAAc8J,CAAAA,CAAY6C,EAAqC,CACjGpB,CAAAA,EAAc,CAEd,IAAMe,CAAAA,CAASmB,CAAAA,CAAQzN,CAAI,CAAA,CAC3B,GAAI,CAACsM,CAAAA,CACH,MAAM,IAAI,KAAA,CAAM,CAAA,kBAAA,EAAqBtM,CAAI,CAAA,iBAAA,CAAmB,EAE9D,GAAM,CAAE,IAAA,CAAAkO,CAAAA,CAAM,OAAA,CAAAC,CAAQ,CAAA,CAAI7B,CAAAA,CAE1B,GAAI4B,CAAAA,GAAS,OAAA,CACX,MAAM,IAAI,KAAA,CAAM,6CAA6C,CAAA,CAG/D,IAAMI,CAAAA,CAAcC,CAAAA,CAAiB,QAAA,CAAU,CAAA,OAAA,EAAUvO,CAAI,CAAA,KAAA,CAAA,CAAS,CAAE,IAAA,CAAAkO,EAAM,IAAA,CAAApE,CAAK,CAAC,CAAA,CAEhF5H,CAAAA,CACJ,GAAI,CAKF,GAJA2I,EAAc8B,CAAAA,CAAQ,KAAA,CAAOL,CAAAA,CAAO,WAAW,CAAA,CAE/CpK,CAAAA,CAAS,MAAMiM,CAAAA,CAAQrE,CAAAA,CAAM6C,CAAO,CAAA,CAEhC,EAAEzK,CAAAA,YAAkBmJ,CAAAA,CAAAA,CACtB,MAAM,IAAI,MACR,CAAA,wBAAA,EAA2BrL,CAAI,CAAA,2GAAA,CACjC,CAEJ,CAAA,MAAS2D,CAAAA,CAAO,CACd,MAAA2K,EAAY,GAAA,CAAI,OAAO,CAAA,CACjB3K,CACR,CAEA,OAAA2K,CAAAA,CAAY,GAAA,GAELpM,CACT","file":"chunk-GPKIS2JI.js","sourcesContent":["import { ConfigSchema, ConfigParams, ValueType } from '../config/types';\nimport { getConfig as _getConfig } from '../config/server';\nimport { CronJobInputParams } from '../cron/types';\nimport { Store } from '../data/store';\nimport { AnyMethodShape } from '../methods/types';\nimport { RouteDefinition } from '../routes/types';\nimport { RateLimitRule } from '../rate-limit/types';\nimport { ServerChannel } from '@/websocket/serverChannel';\n\n/** Array of Store instances that will be provisioned when the module is loaded */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype Stores = Store<any, any>[];\n\n/** Record of query methods that can be called from the client */\ntype Queries = Record<string, AnyMethodShape>;\n\n/** Record of mutation methods that can be called from the client */\ntype Mutations = Record<string, AnyMethodShape>;\n\n/**\n * The Module class is a core building block of a Modelence application that encapsulates related functionality.\n * Modules can contain stores, queries, mutations, routes, cron jobs and configurations.\n *\n * @category Module\n *\n * @example\n * ```ts\n * const todoModule = new Module('todo', {\n * stores: [dbTodos],\n * queries: {\n * async getAll() {\n * // Fetch and return all Todo items\n * }\n * },\n * mutations: {\n * async create({ title }, { user }) {\n * // Create a new Todo item\n * }\n * }\n * });\n * ```\n */\nexport class Module<\n TName extends string = string,\n TSchema extends Record<string, ConfigParams> = ConfigSchema,\n TQueries extends Queries = Queries,\n TMutations extends Mutations = Mutations,\n> {\n /** @internal */\n public readonly name: TName;\n\n /** @internal */\n public readonly stores: Stores;\n\n /** @internal */\n public readonly queries: TQueries;\n\n /** @internal */\n public readonly mutations: TMutations;\n\n /** @internal */\n public readonly routes: RouteDefinition[];\n\n /** @internal */\n public readonly cronJobs: Record<string, CronJobInputParams>;\n\n /** @internal */\n public readonly configSchema: TSchema;\n\n /** @internal */\n public rateLimits: RateLimitRule[];\n\n /** @internal */\n public readonly channels: ServerChannel[];\n\n /**\n * Creates a new Module instance\n *\n * @param name - The unique name of the module.\n * This name is used to namespace queries, mutations,\n * cron jobs and configuration values with a prefix (e.g. \"todo.create\")\n *\n * @param options - Module configuration options\n */\n constructor(\n name: TName,\n {\n stores = [],\n queries = {} as TQueries,\n mutations = {} as TMutations,\n routes = [],\n cronJobs = {},\n configSchema = {} as TSchema,\n rateLimits = [],\n channels = [],\n }: {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n stores?: Store<any, any>[];\n queries?: TQueries;\n mutations?: TMutations;\n routes?: RouteDefinition[];\n cronJobs?: Record<string, CronJobInputParams>;\n configSchema?: TSchema;\n rateLimits?: RateLimitRule[];\n channels?: ServerChannel[];\n } = {}\n ) {\n this.name = name;\n this.stores = stores;\n this.queries = queries;\n this.mutations = mutations;\n this.routes = routes;\n this.cronJobs = cronJobs;\n this.configSchema = configSchema;\n this.rateLimits = rateLimits;\n this.channels = channels;\n }\n\n /**\n * Retrieves a typed configuration value for this module.\n * The return type is inferred from the schema — no casts needed.\n *\n * @example\n * ```ts\n * const myModule = new Module('payments', {\n * configSchema: {\n * apiKey: { type: 'secret', default: '', isPublic: false },\n * maxRetries: { type: 'number', default: 3, isPublic: false },\n * },\n * mutations: {\n * async charge({ amount }) {\n * const apiKey = myModule.getConfig('apiKey'); // string\n * const maxRetries = myModule.getConfig('maxRetries'); // number\n * },\n * },\n * });\n * ```\n */\n getConfig<K extends keyof TSchema & string>(key: K): ValueType<TSchema[K]['type']> {\n return _getConfig(`${this.name}.${key}`) as ValueType<TSchema[K]['type']>;\n }\n}\n","import { z } from 'zod';\nimport { ModelSchema } from './types';\n\ntype ObjectTypeDefinition = {\n [key: string]: z.ZodType | ObjectTypeDefinition | Array<z.ZodType | ObjectTypeDefinition>;\n};\n\nexport interface SerializedModelSchema {\n [key: string]:\n | SerializedSchema\n | (SerializedSchema | SerializedModelSchema)[]\n | SerializedModelSchema\n | 'v2';\n}\n\n// Type guards for Zod schema types\ntype ZodDefWithTypeName = {\n typeName: z.ZodFirstPartyTypeKind;\n};\n\ntype ZodArrayDef = ZodDefWithTypeName & {\n type: z.ZodType;\n};\n\ntype ZodObjectDef = ZodDefWithTypeName & {\n shape: () => Record<string, z.ZodType>;\n};\n\ntype ZodOptionalDef = ZodDefWithTypeName & {\n innerType: z.ZodType;\n};\n\ntype ZodNullableDef = ZodDefWithTypeName & {\n innerType: z.ZodType;\n};\n\ntype ZodEnumDef = ZodDefWithTypeName & {\n values: readonly [string, ...string[]];\n};\n\ntype ZodUnionDef = ZodDefWithTypeName & {\n options: readonly [z.ZodType, z.ZodType, ...z.ZodType[]];\n};\n\ntype ZodEffectsDef = ZodDefWithTypeName & {\n schema: z.ZodType;\n effect: { type: 'refinement' | 'transform' | 'preprocess' };\n description?: string;\n};\n\ntype BaseSerializedSchema =\n | { type: 'string' }\n | { type: 'number' }\n | { type: 'boolean' }\n | { type: 'date' }\n | { type: 'array'; items: SerializedSchema }\n | { type: 'object'; items: Record<string, SerializedSchema> }\n | { type: 'enum'; items: readonly string[] }\n | { type: 'union'; items: SerializedSchema[] }\n | { type: 'custom'; typeName: string };\n\ntype SerializedSchema = BaseSerializedSchema | (BaseSerializedSchema & { optional: true });\n\n/**\n * Serializes a Zod schema to a JSON-serializable format\n */\nfunction serializeZodSchema(zodType: z.ZodType): SerializedSchema {\n const def = zodType._def as ZodDefWithTypeName;\n\n if (def.typeName === 'ZodString') {\n return { type: 'string' };\n }\n if (def.typeName === 'ZodNumber') {\n return { type: 'number' };\n }\n if (def.typeName === 'ZodBoolean') {\n return { type: 'boolean' };\n }\n if (def.typeName === 'ZodDate') {\n return { type: 'date' };\n }\n if (def.typeName === 'ZodArray') {\n const arrayDef = def as ZodArrayDef;\n return {\n type: 'array',\n items: serializeZodSchema(arrayDef.type),\n };\n }\n if (def.typeName === 'ZodObject') {\n const objectDef = def as ZodObjectDef;\n const shape = objectDef.shape();\n const serializedShape: Record<string, SerializedSchema> = {};\n for (const [key, value] of Object.entries(shape)) {\n serializedShape[key] = serializeZodSchema(value as z.ZodType);\n }\n return {\n type: 'object',\n items: serializedShape,\n };\n }\n if (def.typeName === 'ZodOptional') {\n const optionalDef = def as ZodOptionalDef;\n return {\n ...serializeZodSchema(optionalDef.innerType),\n optional: true,\n };\n }\n if (def.typeName === 'ZodNullable') {\n const nullableDef = def as ZodNullableDef;\n return {\n ...serializeZodSchema(nullableDef.innerType),\n optional: true,\n };\n }\n if (def.typeName === 'ZodEnum') {\n const enumDef = def as ZodEnumDef;\n return {\n type: 'enum',\n items: enumDef.values,\n };\n }\n if (def.typeName === 'ZodUnion') {\n const unionDef = def as ZodUnionDef;\n return {\n type: 'union',\n items: unionDef.options.map(serializeZodSchema),\n };\n }\n if (def.typeName === 'ZodEffects') {\n // ZodEffects is used for z.instanceof(ObjectId), z.refine(), etc.\n const effectsDef = def as ZodEffectsDef;\n\n // Check description for custom types\n if (effectsDef.description) {\n return { type: 'custom', typeName: effectsDef.description } as SerializedSchema;\n }\n\n // For other effects, try to serialize the underlying schema\n return serializeZodSchema(effectsDef.schema);\n }\n\n // For custom types like ObjectId, ref, etc.\n return { type: 'custom', typeName: def.typeName };\n}\n\n/**\n * Serializes a model schema to a JSON-serializable format\n */\nexport function serializeModelSchema(schema: ModelSchema): SerializedModelSchema {\n const serialized: SerializedModelSchema = {};\n\n for (const [key, value] of Object.entries(schema)) {\n if (Array.isArray(value)) {\n // Handle array of schema definitions\n serialized[key] = value.map((item) => {\n if (typeof item === 'object' && '_def' in item) {\n return serializeZodSchema(item as z.ZodType);\n }\n return serializeModelSchema(item as ObjectTypeDefinition);\n });\n } else if (typeof value === 'object' && '_def' in value) {\n // It's a Zod type\n serialized[key] = serializeZodSchema(value as z.ZodType);\n } else {\n // It's a nested object definition\n serialized[key] = serializeModelSchema(value as ObjectTypeDefinition);\n }\n }\n\n return serialized;\n}\n","import { Document } from 'mongodb';\nimport { z } from 'zod';\n\ntype ZodDefWithTypeName = {\n typeName: string;\n};\n\ntype ZodWrapperDef = ZodDefWithTypeName & {\n innerType?: z.ZodType;\n schema?: z.ZodType;\n type?: z.ZodType;\n out?: z.ZodType;\n};\n\ntype ZodDefaultDef = ZodWrapperDef & {\n defaultValue: () => unknown;\n};\n\ntype ZodObjectDef = ZodDefWithTypeName & {\n shape: () => Record<string, z.ZodType>;\n};\n\ntype ZodArrayDef = ZodDefWithTypeName & {\n type: z.ZodType;\n};\n\nconst isDocumentRecord = (value: unknown): value is Document =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n\nconst isZodType = (value: unknown): value is z.ZodType =>\n isDocumentRecord(value) && '_def' in value;\n\nconst getZodDef = (zodType: z.ZodType): ZodDefWithTypeName => zodType._def as ZodDefWithTypeName;\n\nconst getWrappedZodType = (zodType: z.ZodType): z.ZodType | undefined => {\n const def = getZodDef(zodType) as ZodWrapperDef;\n\n if (\n def.typeName === 'ZodOptional' ||\n def.typeName === 'ZodNullable' ||\n def.typeName === 'ZodDefault' ||\n def.typeName === 'ZodCatch' ||\n def.typeName === 'ZodReadonly'\n ) {\n return def.innerType;\n }\n\n if (def.typeName === 'ZodEffects') {\n return def.schema;\n }\n\n if (def.typeName === 'ZodBranded') {\n return def.type;\n }\n\n if (def.typeName === 'ZodPipeline') {\n return def.out;\n }\n\n return undefined;\n};\n\nconst getZodDefaultValue = (zodType: z.ZodType): { hasDefault: boolean; value?: unknown } => {\n const def = getZodDef(zodType);\n\n if (def.typeName === 'ZodDefault') {\n return {\n hasDefault: true,\n value: (def as ZodDefaultDef).defaultValue(),\n };\n }\n\n const wrappedType = getWrappedZodType(zodType);\n if (wrappedType) {\n return getZodDefaultValue(wrappedType);\n }\n\n return { hasDefault: false };\n};\n\nconst applyDefaultsToZodValue = (zodType: z.ZodType, value: unknown): unknown => {\n const def = getZodDef(zodType);\n\n if (def.typeName === 'ZodObject' && isDocumentRecord(value)) {\n return applyDefaultsToModelSchema((def as ZodObjectDef).shape(), value);\n }\n\n if (def.typeName === 'ZodArray' && Array.isArray(value)) {\n return value.map((item) => applyDefaultsToZodValue((def as ZodArrayDef).type, item));\n }\n\n const wrappedType = getWrappedZodType(zodType);\n if (wrappedType) {\n return applyDefaultsToZodValue(wrappedType, value);\n }\n\n return value;\n};\n\nconst applyDefaultsToSchemaDefinition = (schemaDefinition: unknown, value: unknown): unknown => {\n if (isZodType(schemaDefinition)) {\n return applyDefaultsToZodValue(schemaDefinition, value);\n }\n\n if (Array.isArray(schemaDefinition) && Array.isArray(value)) {\n if (schemaDefinition.length === 1) {\n return value.map((item) => applyDefaultsToSchemaDefinition(schemaDefinition[0], item));\n }\n\n return value.map((item, index) =>\n applyDefaultsToSchemaDefinition(schemaDefinition[index], item)\n );\n }\n\n if (isDocumentRecord(schemaDefinition) && isDocumentRecord(value)) {\n return applyDefaultsToModelSchema(schemaDefinition, value);\n }\n\n return value;\n};\n\nexport const applyDefaultsToModelSchema = (\n schema: Record<string, unknown>,\n document: Document\n): Document => {\n const result: Document = { ...document };\n\n for (const [key, schemaDefinition] of Object.entries(schema)) {\n const currentValue = result[key];\n\n if (currentValue === undefined) {\n if (isZodType(schemaDefinition)) {\n const defaultValue = getZodDefaultValue(schemaDefinition);\n if (defaultValue.hasDefault) {\n result[key] = applyDefaultsToSchemaDefinition(schemaDefinition, defaultValue.value);\n }\n }\n continue;\n }\n\n result[key] = applyDefaultsToSchemaDefinition(schemaDefinition, currentValue);\n }\n\n return result;\n};\n","import { isDeepStrictEqual } from 'node:util';\n\nimport {\n AggregateOptions,\n AggregationCursor,\n Collection,\n DeleteResult,\n Document,\n IndexDescription,\n InsertOneResult,\n MongoClient,\n UpdateResult,\n Filter,\n WithId,\n WithoutId,\n OptionalUnlessRequiredId,\n FindOptions,\n UpdateFilter,\n ObjectId,\n BulkWriteResult,\n AnyBulkWriteOperation,\n InsertManyResult,\n ClientSession,\n SearchIndexDescription,\n MongoError,\n FilterOperators,\n SortDirection,\n FindOneAndUpdateOptions,\n FindOneAndDeleteOptions,\n FindOneAndReplaceOptions,\n ReplaceOptions,\n ChangeStream,\n ChangeStreamOptions,\n DistinctOptions,\n} from 'mongodb';\nimport { ModelSchema, InferDocumentType } from './types';\nimport { serializeModelSchema } from './schemaSerializer';\nimport { applyDefaultsToModelSchema } from './schemaDefaults';\n\n/**\n * Top-level query operators (logical and evaluation) - custom version without Document index signature\n * Based on MongoDB's RootFilterOperators but without the [key: string]: any from Document\n * @internal\n */\ntype StrictRootFilterOperators<TSchema> = {\n $and?: TypedFilter<TSchema>[];\n $or?: TypedFilter<TSchema>[];\n $nor?: TypedFilter<TSchema>[];\n $not?: TypedFilter<TSchema>;\n $text?: {\n $search: string;\n $language?: string;\n $caseSensitive?: boolean;\n $diacriticSensitive?: boolean;\n };\n\n $where?: string | ((this: TSchema) => boolean);\n $comment?: string | Document;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n $expr?: any;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n $jsonSchema?: any;\n};\n\n/**\n * Helper type to extract array element type\n * @internal\n */\ntype ArrayElement<T> = T extends (infer E)[] ? E : never;\ntype Flatten<T> = T extends ReadonlyArray<infer E> ? E : T;\n\n/**\n * Helper type for $in/$nin that accepts any array/tuple where elements are assignable to T\n * This solves the issue where TypeScript infers ['a', 'b'] as a tuple instead of ('a' | 'b')[]\n * and where Array<Union> gets distributed into Union1[] | Union2[] | ...\n * We wrap the Exclude in a tuple check to prevent distribution\n * @internal\n */\ntype NonUndefined<T> = T extends undefined ? never : T;\ntype ArrayLikeOfUnion<T> = [NonUndefined<T>] extends [never]\n ? never\n : ReadonlyArray<NonUndefined<T>> | Array<NonUndefined<T>>;\n\n/**\n * Enhanced FilterOperators that fixes $in and $nin to properly accept arrays of union types\n * MongoDB's native FilterOperators has issues with union types in $in/$nin arrays\n * because TypeScript distributes Array<Union> into Array1 | Array2 | ...\n * @internal\n */\ntype EnhancedFilterOperators<T> = Omit<FilterOperators<T>, '$in' | '$nin'> & {\n $in?: ArrayLikeOfUnion<T>;\n $nin?: ArrayLikeOfUnion<T>;\n};\n\ntype ExistingIndex = Document & {\n key?: Document;\n name?: string;\n};\n\ntype TypedFieldSelection<T, TValue> = {\n [K in keyof WithId<T> & string]?: TValue;\n} & {\n [key: `${string}.${string}`]: TValue;\n};\n\ntype ProjectionValue =\n | 0\n | 1\n | boolean\n | { $meta: string }\n | { $slice: number | [number, number] }\n | { $elemMatch: Document };\n\ntype TypedSort<T> = TypedFieldSelection<T, SortDirection>;\ntype TypedProjection<T> = TypedFieldSelection<T, ProjectionValue>;\n\ntype FetchOptions<T> = {\n sort?: TypedSort<T>;\n limit?: number;\n skip?: number;\n projection?: TypedProjection<T>;\n};\n\nexport type IndexCreationMode = 'blocking' | 'background';\nexport type IndexReconcileMode = 'full' | 'drop-only' | 'create-only';\n\nconst COMPARABLE_INDEX_OPTION_FIELDS = [\n 'background',\n 'bits',\n 'bucketSize',\n 'collation',\n 'default_language',\n 'expireAfterSeconds',\n 'hidden',\n 'language_override',\n 'max',\n 'min',\n 'partialFilterExpression',\n 'sparse',\n 'storageEngine',\n 'textIndexVersion',\n 'unique',\n 'weights',\n 'wildcardProjection',\n '2dsphereIndexVersion',\n] as const;\n\nconst isDocumentRecord = (value: unknown): value is Document =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n\nconst hasModelencePrefix = (name: string): boolean => name.startsWith('_modelence_');\n\nconst getComparableIndexOptions = (index: ExistingIndex | IndexDescription): Document => {\n const options: Document = {};\n\n for (const field of COMPARABLE_INDEX_OPTION_FIELDS) {\n const value = (index as Document)[field];\n if (value !== undefined) {\n options[field] = value;\n }\n }\n\n return options;\n};\n\n/**\n * MongoDB index key order is significant (e.g. { a: 1, b: 1 } !== { b: 1, a: 1 }).\n */\nconst isSameIndexKey = (left: unknown, right: unknown): boolean => {\n if (!isDocumentRecord(left) || !isDocumentRecord(right)) {\n return false;\n }\n\n const leftEntries = Object.entries(left);\n const rightEntries = Object.entries(right);\n\n if (leftEntries.length !== rightEntries.length) {\n return false;\n }\n\n return leftEntries.every(([leftField, leftDirection], index) => {\n const [rightField, rightDirection] = rightEntries[index] || [];\n return leftField === rightField && isDeepStrictEqual(leftDirection, rightDirection);\n });\n};\n\nconst isSameIndexDefinition = (existing: ExistingIndex, desired: IndexDescription): boolean => {\n if (!isSameIndexKey(existing.key, desired.key)) {\n return false;\n }\n\n return isDeepStrictEqual(getComparableIndexOptions(existing), getComparableIndexOptions(desired));\n};\n\nconst getIndexKeySignature = (key: unknown): string | null => {\n if (!isDocumentRecord(key)) {\n return null;\n }\n\n return Object.entries(key)\n .map(([field, direction]) => `${field}:${JSON.stringify(direction)}`)\n .join('|');\n};\n\n/**\n * Lists all indexes in a collection, returning an empty array if collection doesn't exist\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst listIndexes = async (collection: Collection<any>): Promise<Document[]> => {\n try {\n return await collection.listIndexes().toArray();\n } catch (error) {\n // If collection doesn't exist yet, return empty array\n // It will be created when we insert data or create indexes\n if (error instanceof MongoError && error.code === 26) {\n return [];\n }\n throw error;\n }\n};\n\n/**\n * Generates an auto-generated index name from the index keys\n * Mimics MongoDB's default naming: field1_direction1_field2_direction2\n */\nconst generateAutoIndexName = (key: Document): string => {\n return Object.entries(key)\n .map(([field, direction]) => `${field}_${direction}`)\n .join('_');\n};\n\n/**\n * Normalizes an index by ensuring it has a name with _modelence_ prefix\n */\nconst normalizeIndexName = (index: IndexDescription): IndexDescription => {\n if (index.name) {\n // If name is provided, add _modelence_ prefix if not already present\n const name = index.name.startsWith('_modelence_') ? index.name : `_modelence_${index.name}`;\n return { ...index, name };\n }\n\n // Auto-generate name with _modelence_ prefix\n const autoName = generateAutoIndexName(index.key);\n return { ...index, name: `_modelence_${autoName}` };\n};\n\n/**\n * Custom filter value type that handles array fields specially:\n * - For array fields: allows element type, full array type, or FilterOperators\n * - For non-array fields: allows exact type or FilterOperators\n * We use [T] to prevent distribution when T is a union type\n * @internal\n */\ntype FilterValue<T> = [T] extends [unknown[]]\n ? ArrayElement<T> | T | EnhancedFilterOperators<T>\n : [T] extends [never]\n ? never\n : T | EnhancedFilterOperators<[T] extends [never] ? never : T>;\n\n/**\n * Type-safe MongoDB filter that ensures only schema fields can be queried\n * while supporting all MongoDB query operators and dot notation for nested fields.\n *\n * This type combines:\n * - MongoDB's native `FilterOperators<T>` for field-level operators (comprehensive operator support)\n * - Custom `StrictRootFilterOperators<T>` for top-level operators without index signature\n * - Custom array field handling: allows passing single element when field is an array\n * - Custom restriction: only strings containing dots are allowed for nested field queries\n *\n * @example\n * ```ts\n * const dbUsers = new Store('users', {\n * schema: {\n * name: schema.string(),\n * age: schema.number(),\n * tags: schema.array(schema.string()),\n * collections: schema.array(schema.string()),\n * address: schema.object({\n * street: schema.string(),\n * city: schema.string(),\n * }),\n * },\n * indexes: []\n * });\n *\n * // ✅ Valid - field exists in schema\n * await dbUsers.findOne({ name: 'John' });\n *\n * // ✅ Valid - using MongoDB operators (from FilterOperators)\n * await dbUsers.findOne({ age: { $gt: 18 } });\n * await dbUsers.findOne({ tags: { $in: ['typescript', 'mongodb'] } });\n * await dbUsers.findOne({ $or: [{ name: 'John' }, { name: 'Jane' }] });\n *\n * // ✅ Valid - array field with single element (checks if array contains the element)\n * await dbUsers.findOne({ collections: 'users' });\n *\n * // ✅ Valid - dot notation for nested fields (must contain a dot)\n * await dbUsers.findOne({ 'address.city': 'New York' });\n * await dbUsers.findOne({ 'emails.0.address': 'test@example.com' });\n *\n * // ❌ TypeScript error - 'id' is not in schema and doesn't contain a dot\n * await dbUsers.findOne({ id: '123' });\n * ```\n */\nexport type TypedFilter<T> = {\n [K in keyof WithId<T>]?: FilterValue<WithId<T>[K]>;\n} & StrictRootFilterOperators<T> & {\n // Support for MongoDB dot notation (e.g., 'emails.address', 'profile.settings.theme')\n // Only strings containing dots are allowed, which provides better type safety\n // while still enabling MongoDB's nested field query syntax\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [K: `${string}.${string}`]: any;\n };\n\n/**\n * Helper type to preserve method types when extending a store.\n * Maps each method to work with the extended schema while preserving signatures.\n * @internal\n */\ntype PreserveMethodsForExtendedSchema<\n TBaseMethods extends Record<string, (...args: never[]) => unknown>,\n TExtendedSchema extends ModelSchema,\n> = {\n [K in keyof TBaseMethods]: TBaseMethods[K] extends (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this: any,\n ...args: infer Args\n ) => infer Return\n ? // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (this: WithId<InferDocumentType<TExtendedSchema>> & any, ...args: Args) => Return\n : never;\n};\n\n/**\n * Type-erased Store reference for chain traversal.\n * Chain members carry different TSchema/TMethods, so the generic\n * parameters must be erased. This alias contains the `any` in one place.\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyStore = Store<any, any>;\n\n/**\n * The Store class provides a type-safe interface for MongoDB collections with built-in schema validation and helper methods.\n *\n * @category Store\n * @typeParam TSchema - The document schema type\n * @typeParam TMethods - Custom methods that will be added to documents\n *\n * @example\n * ```ts\n * const dbTodos = new Store('todos', {\n * schema: {\n * title: schema.string(),\n * completed: schema.boolean(),\n * dueDate: schema.date().optional(),\n * userId: schema.userId(),\n * },\n * methods: {\n * isOverdue() {\n * return this.dueDate < new Date();\n * }\n * }\n * });\n * ```\n */\nexport class Store<\n TSchema extends ModelSchema,\n TMethods extends Record<\n string,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (this: WithId<InferDocumentType<TSchema>> & TMethods, ...args: any[]) => any\n >,\n> {\n /** @internal */\n readonly _type!: InferDocumentType<TSchema>;\n /** @internal */\n readonly _rawDoc!: WithId<this['_type']>;\n /** @internal */\n readonly _doc!: this['_rawDoc'] & TMethods;\n\n readonly Doc!: this['_doc'];\n\n private name: string;\n private readonly schema: TSchema;\n private readonly methods?: TMethods;\n private readonly indexes: IndexDescription[];\n private readonly searchIndexes: SearchIndexDescription[];\n private readonly indexCreationMode: IndexCreationMode;\n private collection?: Collection<this['_type']>;\n private client?: MongoClient;\n\n // Chain tracking for linear extension model\n private _chainParent: AnyStore | null = null;\n private _chainChild: AnyStore | null = null;\n\n /**\n * Creates a new Store instance\n *\n * @param name - The collection name in MongoDB\n * @param options - Store configuration (schema, indexes, methods, search indexes, and optional index creation mode)\n */\n constructor(\n name: string,\n options: {\n /** Document schema using Modelence schema types */\n schema: TSchema;\n /** Custom methods to add to documents */\n methods?: TMethods;\n /** MongoDB indexes to create */\n indexes: IndexDescription[];\n /** MongoDB Atlas Search */\n searchIndexes?: SearchIndexDescription[];\n /** Whether index creation should block startup or run in background (default: 'background') */\n indexCreationMode?: IndexCreationMode;\n }\n ) {\n this.name = name;\n this.schema = options.schema;\n this.methods = options.methods;\n // Normalize all indexes to have _modelence_ prefix\n this.indexes = options.indexes.map(normalizeIndexName);\n this.searchIndexes = options.searchIndexes || [];\n this.indexCreationMode = options.indexCreationMode ?? 'background';\n }\n\n getName() {\n return this.name;\n }\n\n getIndexCreationMode() {\n return this.indexCreationMode;\n }\n\n /** @internal */\n getSchema() {\n return this.schema;\n }\n\n /** @internal */\n getSerializedSchema() {\n return serializeModelSchema(this.schema);\n }\n\n /** @internal – normalized indexes (already have _modelence_ prefix) */\n getIndexes(): IndexDescription[] {\n return this.indexes;\n }\n\n /** @internal */\n getSearchIndexes(): SearchIndexDescription[] {\n return this.searchIndexes;\n }\n\n /** @internal – follows the chain to the latest extension */\n getChainTail(): AnyStore {\n let current: AnyStore = this;\n while (current._chainChild) {\n current = current._chainChild;\n }\n return current;\n }\n\n /** @internal – follows the chain back to the original store */\n getChainRoot(): AnyStore {\n let current: AnyStore = this;\n while (current._chainParent) {\n current = current._chainParent;\n }\n return current;\n }\n\n /**\n * Extends the store with additional schema fields, indexes, methods, and search indexes.\n * Returns a new Store instance with the extended schema and updated types.\n * Methods from the original store are preserved with updated type signatures.\n *\n * @param config - Additional schema fields, indexes, methods, search indexes, and optional index creation mode to add\n * @returns A new Store instance with the extended schema\n *\n * @example\n * ```ts\n * // Extend the users collection\n * export const dbUsers = baseUsersCollection.extend({\n * schema: {\n * firstName: schema.string(),\n * lastName: schema.string(),\n * companyId: schema.objectId().optional(),\n * },\n * indexes: [\n * { key: { companyId: 1 } },\n * { key: { lastName: 1, firstName: 1 } },\n * ],\n * methods: {\n * getFullName() {\n * return `${this.firstName} ${this.lastName}`;\n * }\n * }\n * });\n *\n * // Now fully typed with new fields\n * const user = await dbUsers.findOne({ firstName: 'John' });\n * console.log(user?.getFullName());\n * ```\n */\n extend<\n TExtendedSchema extends ModelSchema,\n TExtendedMethods extends Record<string, Function> = Record<string, never>,\n >(config: {\n schema?: TExtendedSchema;\n indexes?: IndexDescription[];\n methods?: TExtendedMethods;\n searchIndexes?: SearchIndexDescription[];\n /** Whether index creation should block startup or run in background */\n indexCreationMode?: IndexCreationMode;\n }): Store<\n TSchema & TExtendedSchema,\n PreserveMethodsForExtendedSchema<TMethods, TSchema & TExtendedSchema> & TExtendedMethods\n > {\n // Follow chain to the tail – extending always appends to the end\n const tail: AnyStore = this.getChainTail();\n\n if (this.client || tail.client) {\n throw new Error(\n `Store.extend() must be called before startApp(). Store '${this.name}' has already been initialized and cannot be extended.`\n );\n }\n\n type ExtendedSchema = TSchema & TExtendedSchema;\n\n const extendedSchema = {\n ...tail.schema,\n ...(config.schema || {}),\n } as ExtendedSchema;\n\n const extendedIndexes = [...tail.indexes, ...(config.indexes || [])];\n const extendedSearchIndexes = [...tail.searchIndexes, ...(config.searchIndexes || [])];\n\n type CombinedMethods = PreserveMethodsForExtendedSchema<TMethods, ExtendedSchema> &\n TExtendedMethods;\n\n const combinedMethods = {\n ...(tail.methods || {}),\n ...(config.methods || {}),\n } as CombinedMethods | undefined;\n\n const extendedStore = new Store<ExtendedSchema, CombinedMethods>(this.name, {\n schema: extendedSchema,\n methods: combinedMethods as unknown as CombinedMethods | undefined,\n indexes: extendedIndexes,\n searchIndexes: extendedSearchIndexes,\n indexCreationMode: config.indexCreationMode ?? tail.indexCreationMode,\n });\n\n // Link into the chain\n tail._chainChild = extendedStore;\n extendedStore._chainParent = tail;\n\n return extendedStore;\n }\n\n /** @internal */\n init(client: MongoClient) {\n if (this.collection) {\n throw new Error(`Collection ${this.name} is already initialized`);\n }\n\n this.client = client;\n this.collection = this.client.db().collection<this['_type']>(this.name);\n }\n\n /** @internal */\n async createIndexes(mode: IndexReconcileMode = 'full') {\n const collection = this.requireCollection();\n const shouldDropIndexes = mode !== 'create-only';\n const shouldCreateIndexes = mode !== 'drop-only';\n\n // Get all existing indexes in the collection (returns [] if collection doesn't exist)\n const existingIndexes = await listIndexes(collection);\n const indexByName = new Map<string, ExistingIndex & { name: string }>();\n const indexNamesByKey = new Map<string, Set<string>>();\n const droppedIndexNames = new Set<string>();\n\n const addIndexToLookup = (existingIndex: ExistingIndex & { name: string }) => {\n indexByName.set(existingIndex.name, existingIndex);\n\n const keySignature = getIndexKeySignature(existingIndex.key);\n if (!keySignature) {\n return;\n }\n\n const names = indexNamesByKey.get(keySignature);\n if (names) {\n names.add(existingIndex.name);\n } else {\n indexNamesByKey.set(keySignature, new Set([existingIndex.name]));\n }\n };\n\n const removeIndexFromLookup = (indexName: string) => {\n const existingIndex = indexByName.get(indexName);\n if (!existingIndex) {\n return;\n }\n\n indexByName.delete(indexName);\n\n const keySignature = getIndexKeySignature(existingIndex.key);\n if (!keySignature) {\n return;\n }\n\n const names = indexNamesByKey.get(keySignature);\n if (!names) {\n return;\n }\n\n names.delete(indexName);\n if (names.size === 0) {\n indexNamesByKey.delete(keySignature);\n }\n };\n\n for (const existingIndex of existingIndexes) {\n if (typeof existingIndex.name === 'string') {\n addIndexToLookup({\n ...existingIndex,\n name: existingIndex.name,\n });\n }\n }\n\n const dropIndexIfNeeded = async (indexName: string) => {\n if (indexName === '_id_' || droppedIndexNames.has(indexName)) {\n return;\n }\n try {\n await collection.dropIndex(indexName);\n } catch (error) {\n // Another concurrent reconciler may have already dropped it.\n if (!(error instanceof MongoError && error.code === 27)) {\n throw error;\n }\n }\n droppedIndexNames.add(indexName);\n removeIndexFromLookup(indexName);\n };\n\n if (shouldDropIndexes) {\n // Find all _modelence_ prefixed indexes that are not in the current schema\n const currentIndexNames = new Set(\n this.indexes\n .map((idx) => idx.name)\n .filter((name): name is string => typeof name === 'string')\n );\n const orphanedIndexes = [...indexByName.values()].filter(\n (existingIdx) =>\n hasModelencePrefix(existingIdx.name) && !currentIndexNames.has(existingIdx.name)\n );\n\n // Drop orphaned indexes\n for (const orphanedIndex of orphanedIndexes) {\n await dropIndexIfNeeded(orphanedIndex.name);\n }\n }\n\n // Reconcile code-defined indexes against the current DB metadata.\n // Code wins on conflicts; non-conflicting manual indexes are preserved.\n if (this.indexes.length > 0) {\n for (const index of this.indexes) {\n if (!index.name) {\n continue;\n }\n\n let requiresDropBeforeCreate = false;\n const existingByName = indexByName.get(index.name);\n if (existingByName && !isSameIndexDefinition(existingByName, index)) {\n if (shouldDropIndexes) {\n await dropIndexIfNeeded(existingByName.name);\n } else {\n requiresDropBeforeCreate = true;\n }\n }\n\n const keySignature = getIndexKeySignature(index.key);\n if (keySignature) {\n const existingNamesForKey = [...(indexNamesByKey.get(keySignature) || [])];\n for (const existingName of existingNamesForKey) {\n if (existingName !== index.name) {\n if (shouldDropIndexes) {\n await dropIndexIfNeeded(existingName);\n } else {\n requiresDropBeforeCreate = true;\n }\n }\n }\n }\n\n const alignedIndex = indexByName.get(index.name);\n const hasAlignedIndex = !!alignedIndex && isSameIndexDefinition(alignedIndex, index);\n\n if (!hasAlignedIndex && shouldCreateIndexes && !requiresDropBeforeCreate) {\n await collection.createIndexes([index]);\n addIndexToLookup({\n name: index.name,\n key: index.key,\n ...getComparableIndexOptions(index),\n });\n }\n }\n }\n if (shouldCreateIndexes && this.searchIndexes.length > 0) {\n for (const searchIndex of this.searchIndexes) {\n try {\n await collection.createSearchIndexes([searchIndex]);\n } catch (error) {\n if (error instanceof MongoError && error.code === 68 && searchIndex.name) {\n await collection.dropSearchIndex(searchIndex.name);\n await collection.createSearchIndexes([searchIndex]);\n } else {\n throw error;\n }\n }\n }\n }\n }\n\n private wrapDocument(document: this['_rawDoc']): this['_doc'] {\n if (!this.methods) {\n return document as unknown as this['_doc'];\n }\n\n const result = Object.create(\n null,\n Object.getOwnPropertyDescriptors({\n ...document,\n ...this.methods,\n })\n );\n\n return result as this['_doc'];\n }\n\n /**\n * For convenience, to also allow directy passing a string or ObjectId as the selector\n */\n private getSelector(selector: TypedFilter<this['_type']> | string | ObjectId) {\n if (typeof selector === 'string') {\n return { _id: new ObjectId(selector) } as Filter<this['_type']>;\n }\n\n if (selector instanceof ObjectId) {\n return { _id: selector } as Filter<this['_type']>;\n }\n\n return selector as Filter<this['_type']>;\n }\n\n /** @internal */\n requireCollection() {\n if (!this.collection) {\n throw new Error(`Collection ${this.name} is not provisioned`);\n }\n\n return this.collection;\n }\n\n /** @internal */\n requireClient() {\n if (!this.client) {\n throw new Error(`Database is not connected`);\n }\n\n return this.client;\n }\n\n /**\n * Finds a single document matching the query\n *\n * @param query - Type-safe query filter. Only schema fields, MongoDB operators, and dot notation are allowed.\n * @param options - Find options\n * @returns The document, or null if not found\n *\n * @example\n * ```ts\n * // ✅ Valid queries:\n * await store.findOne({ name: 'John' })\n * await store.findOne({ age: { $gt: 18 } })\n * await store.findOne({ _id: new ObjectId('...') })\n * await store.findOne({ tags: { $in: ['typescript', 'mongodb'] } })\n * await store.findOne({ $or: [{ name: 'John' }, { name: 'Jane' }] })\n * await store.findOne({ 'emails.address': 'test@example.com' }) // dot notation\n *\n * // ❌ TypeScript error - 'id' is not in schema:\n * await store.findOne({ id: '123' })\n * ```\n */\n async findOne(query: TypedFilter<this['_type']>, options?: FindOptions) {\n const document = await this.requireCollection().findOne<this['_rawDoc']>(\n query as Filter<this['_type']>,\n options\n );\n return document ? this.wrapDocument(document) : null;\n }\n\n async requireOne(\n query: TypedFilter<this['_type']>,\n options?: FindOptions,\n errorHandler?: () => Error\n ): Promise<this['_doc']> {\n const result = await this.findOne(query, options);\n if (!result) {\n throw errorHandler ? errorHandler() : new Error(`Record not found in ${this.name}`);\n }\n return result;\n }\n\n private find(query: TypedFilter<this['_type']>, options?: FetchOptions<this['_type']>) {\n const cursor = this.requireCollection().find(\n query as Filter<this['_type']>,\n options?.projection ? { projection: options.projection } : undefined\n );\n if (options?.sort) {\n cursor.sort(options.sort);\n }\n if (options?.limit) {\n cursor.limit(options.limit);\n }\n if (options?.skip) {\n cursor.skip(options.skip);\n }\n return cursor;\n }\n\n /**\n * Fetches a single document by its ID\n *\n * @param id - The ID of the document to find\n * @returns The document, or null if not found\n */\n async findById(id: string | ObjectId): Promise<this['_doc'] | null> {\n const idSelector = typeof id === 'string' ? { _id: new ObjectId(id) } : { _id: id };\n return await this.findOne(idSelector as TypedFilter<this['_type']>);\n }\n\n /**\n * Fetches a single document by its ID, or throws an error if not found\n *\n * @param id - The ID of the document to find\n * @param errorHandler - Optional error handler to return a custom error if the document is not found\n * @returns The document\n */\n async requireById(id: string | ObjectId, errorHandler?: () => Error): Promise<this['_doc']> {\n const result = await this.findById(id);\n if (!result) {\n throw errorHandler\n ? errorHandler()\n : new Error(`Record with id ${id} not found in ${this.name}`);\n }\n return result;\n }\n\n /**\n * Counts the number of documents that match a query\n *\n * @param query - The query to filter documents\n * @returns The number of documents that match the query\n */\n countDocuments(query: TypedFilter<this['_type']>): Promise<number> {\n return this.requireCollection().countDocuments(query as Filter<this['_type']>);\n }\n\n /**\n * Fetches multiple documents, equivalent to Node.js MongoDB driver's `find` and `toArray` methods combined.\n *\n * @param query - The query to filter documents\n * @param options - Optional fetch options\n * @param options.projection - Fields to include or exclude in the result documents\n * @param options.sort - Sort order for matching documents\n * @param options.limit - Maximum number of documents to return\n * @param options.skip - Number of matching documents to skip\n * @returns The documents\n *\n * @example\n * ```ts\n * // Include only selected fields\n * const docs = await store.fetch(\n * { userId: user.id },\n * { projection: { framework: 1, title: 1 }, sort: { createdAt: -1 }, limit: 50 }\n * );\n *\n * // Exclude large fields when not needed\n * const chunks = await store.fetch(\n * { documentId },\n * { projection: { embedding: 0 } }\n * );\n * ```\n */\n async fetch(\n query: TypedFilter<this['_type']>,\n options?: FetchOptions<this['_type']>\n ): Promise<this['_doc'][]> {\n const cursor = this.find(query, options);\n return (await cursor.toArray()).map(this.wrapDocument.bind(this));\n }\n\n /**\n * Inserts a single document\n *\n * @param document - The document to insert\n * @returns The result of the insert operation\n */\n async insertOne(\n document: OptionalUnlessRequiredId<InferDocumentType<TSchema>>,\n options?: { session?: ClientSession }\n ): Promise<InsertOneResult> {\n return await this.requireCollection().insertOne(document, options);\n }\n\n /**\n * Inserts a single document and returns the inserted document with its generated `_id`\n * and any helper methods applied.\n *\n * Unlike {@link insertOne}, which only returns the insert result metadata, this method\n * returns the full inserted document — useful when you need to immediately use the\n * newly created record (e.g. returning it from an API handler).\n *\n * @param document - The document to insert\n * @returns The inserted document with `_id` populated and methods applied\n *\n * @example\n * ```ts\n * const todo = await dbTodos.create({ title: 'Buy milk', completed: false });\n * console.log(todo._id); // ObjectId\n * console.log(todo.title); // 'Buy milk'\n * ```\n */\n async create(\n document: OptionalUnlessRequiredId<InferDocumentType<TSchema>>,\n options?: { session?: ClientSession }\n ): Promise<this['_doc']> {\n const docWithId = applyDefaultsToModelSchema(this.schema, {\n _id: new ObjectId(),\n ...document,\n }) as OptionalUnlessRequiredId<InferDocumentType<TSchema>>;\n\n await this.requireCollection().insertOne(docWithId, options);\n\n return this.wrapDocument(docWithId as unknown as this['_rawDoc']);\n }\n\n /**\n * Inserts multiple documents\n *\n * @param documents - The documents to insert\n * @returns The result of the insert operation\n */\n async insertMany(\n documents: OptionalUnlessRequiredId<InferDocumentType<TSchema>>[],\n options?: { session?: ClientSession }\n ): Promise<InsertManyResult> {\n return await this.requireCollection().insertMany(documents, options);\n }\n\n /**\n * Updates a single document\n *\n * @param selector - The selector to find the document to update\n * @param update - The update to apply to the document\n * @returns The result of the update operation\n */\n async updateOne(\n selector: TypedFilter<this['_type']> | string | ObjectId,\n update: UpdateFilter<this['_type']>,\n options?: { session?: ClientSession }\n ): Promise<UpdateResult> {\n return await this.requireCollection().updateOne(this.getSelector(selector), update, options);\n }\n\n /**\n * Updates a single document, or inserts it if it doesn't exist\n *\n * @param selector - The selector to find the document to update\n * @param update - The MongoDB modifier to apply to the document\n * @returns The result of the update operation\n */\n async upsertOne(\n selector: TypedFilter<this['_type']> | string | ObjectId,\n update: UpdateFilter<this['_type']>,\n options?: { session?: ClientSession }\n ): Promise<UpdateResult> {\n return await this.requireCollection().updateOne(this.getSelector(selector), update, {\n upsert: true,\n ...options,\n });\n }\n\n /**\n * Updates multiple documents\n *\n * @param selector - The selector to find the documents to update\n * @param update - The MongoDB modifier to apply to the documents\n * @returns The result of the update operation\n */\n async updateMany(\n selector: TypedFilter<this['_type']>,\n update: UpdateFilter<this['_type']>,\n options?: { session?: ClientSession }\n ): Promise<UpdateResult> {\n return await this.requireCollection().updateMany(\n selector as Filter<this['_type']>,\n update,\n options\n );\n }\n\n /**\n * Updates multiple documents, or inserts them if they don't exist\n *\n * @param selector - The selector to find the documents to update\n * @param update - The MongoDB modifier to apply to the documents\n * @returns The result of the update operation\n */\n async upsertMany(\n selector: TypedFilter<this['_type']>,\n update: UpdateFilter<this['_type']>,\n options?: { session?: ClientSession }\n ): Promise<UpdateResult> {\n return await this.requireCollection().updateMany(selector as Filter<this['_type']>, update, {\n upsert: true,\n ...options,\n });\n }\n\n /**\n * Deletes a single document\n *\n * @param selector - The selector to find the document to delete\n * @returns The result of the delete operation\n */\n async deleteOne(\n selector: TypedFilter<this['_type']> | string | ObjectId,\n options?: { session?: ClientSession }\n ): Promise<DeleteResult> {\n return await this.requireCollection().deleteOne(this.getSelector(selector), options);\n }\n\n /**\n * Deletes multiple documents\n *\n * @param selector - The selector to find the documents to delete\n * @returns The result of the delete operation\n */\n async deleteMany(\n selector: TypedFilter<this['_type']>,\n options?: { session?: ClientSession }\n ): Promise<DeleteResult> {\n return await this.requireCollection().deleteMany(selector as Filter<this['_type']>, options);\n }\n\n /**\n * Atomically finds a document and updates it, returning the document\n *\n * @param selector - The selector to find the document\n * @param update - The update to apply\n * @param options - Options including `returnDocument` ('before' or 'after'), `upsert`, `session`, etc.\n * @returns The document (before or after update, depending on options), or null if not found\n */\n async findOneAndUpdate(\n selector: TypedFilter<this['_type']> | string | ObjectId,\n update: UpdateFilter<this['_type']>,\n options?: Omit<FindOneAndUpdateOptions, 'includeResultMetadata'>\n ): Promise<this['_doc'] | null> {\n const result = await this.requireCollection().findOneAndUpdate(\n this.getSelector(selector),\n update,\n options ?? {}\n );\n return result ? this.wrapDocument(result as this['_rawDoc']) : null;\n }\n\n /**\n * Atomically finds a document and deletes it, returning the deleted document\n *\n * @param selector - The selector to find the document\n * @param options - Options including `session`, `projection`, etc.\n * @returns The deleted document, or null if not found\n */\n async findOneAndDelete(\n selector: TypedFilter<this['_type']> | string | ObjectId,\n options?: Omit<FindOneAndDeleteOptions, 'includeResultMetadata'>\n ): Promise<this['_doc'] | null> {\n const result = await this.requireCollection().findOneAndDelete(\n this.getSelector(selector),\n options ?? {}\n );\n return result ? this.wrapDocument(result as this['_rawDoc']) : null;\n }\n\n /**\n * Atomically finds a document and replaces it, returning the document\n *\n * @param selector - The selector to find the document\n * @param replacement - The replacement document\n * @param options - Options including `returnDocument` ('before' or 'after'), `upsert`, `session`, etc.\n * @returns The document (before or after replacement, depending on options), or null if not found\n */\n async findOneAndReplace(\n selector: TypedFilter<this['_type']> | string | ObjectId,\n replacement: WithoutId<this['_type']>,\n options?: Omit<FindOneAndReplaceOptions, 'includeResultMetadata'>\n ): Promise<this['_doc'] | null> {\n const result = await this.requireCollection().findOneAndReplace(\n this.getSelector(selector),\n replacement,\n options ?? {}\n );\n return result ? this.wrapDocument(result as this['_rawDoc']) : null;\n }\n\n /**\n * Replaces a single document\n *\n * @param selector - The selector to find the document to replace\n * @param replacement - The replacement document (must not contain update operators)\n * @param options - Options including `upsert`, `session`, etc.\n * @returns The result of the replace operation\n */\n async replaceOne(\n selector: TypedFilter<this['_type']> | string | ObjectId,\n replacement: WithoutId<this['_type']>,\n options?: ReplaceOptions\n ): Promise<UpdateResult> {\n return await this.requireCollection().replaceOne(\n this.getSelector(selector),\n replacement,\n options\n );\n }\n\n /**\n * Returns an array of distinct values for a field across the collection\n *\n * @param key - The field name (supports dot notation for nested fields)\n * @param filter - Optional filter to narrow the documents\n * @param options - Optional distinct options\n * @returns An array of distinct values\n */\n\n async distinct<K extends keyof this['_rawDoc'] & string>(\n key: K,\n filter?: TypedFilter<this['_type']>,\n options?: DistinctOptions\n ): Promise<Array<Flatten<this['_rawDoc'][K]>>> {\n const f = (filter ?? {}) as Filter<this['_type']>;\n return options !== undefined\n ? await this.requireCollection().distinct(key, f, options)\n : await this.requireCollection().distinct(key, f);\n }\n\n /**\n * Opens a change stream on the collection to watch for real-time changes\n *\n * @param pipeline - Optional aggregation pipeline to filter/transform change events\n * @param options - Optional change stream options\n * @returns A ChangeStream instance\n */\n watch(pipeline?: Document[], options?: ChangeStreamOptions): ChangeStream {\n return this.requireCollection().watch(pipeline, options);\n }\n\n /**\n * Aggregates documents using MongoDB's aggregation framework\n *\n * @param pipeline - The aggregation pipeline\n * @param options - Optional options\n * @returns The aggregation cursor\n */\n aggregate(pipeline: Document[], options?: AggregateOptions): AggregationCursor<Document> {\n return this.requireCollection().aggregate(pipeline, options);\n }\n\n /**\n * Performs a bulk write operation on the collection\n *\n * @param operations - The operations to perform\n * @returns The result of the bulk write operation\n */\n bulkWrite(operations: AnyBulkWriteOperation<this['_type']>[]): Promise<BulkWriteResult> {\n return this.requireCollection().bulkWrite(operations);\n }\n\n /**\n * Returns the raw MongoDB database instance for advanced operations\n * @returns The MongoDB database instance\n * @throws Error if the store is not provisioned\n */\n getDatabase() {\n return this.requireClient().db();\n }\n\n /**\n * Returns the raw MongoDB collection instance for advanced operations\n * @returns The MongoDB collection instance\n * @throws Error if the store is not provisioned\n */\n rawCollection() {\n return this.requireCollection();\n }\n\n /**\n * Renames an existing collection to this store's name, used for migrations\n * @param oldName - The previous name of the collection\n * @throws Error if the old collection doesn't exist or if this store's collection already exists\n */\n async renameFrom(oldName: string, options?: { session?: ClientSession }) {\n const db = this.getDatabase();\n\n if (!this.collection || !db) {\n throw new Error(`Store ${this.name} is not provisioned`);\n }\n\n const oldCollections = await db.listCollections({ name: oldName }).toArray();\n if (oldCollections.length === 0) {\n throw new Error(`Collection ${oldName} not found`);\n }\n\n const newCollections = await db.listCollections({ name: this.name }).toArray();\n if (newCollections.length > 0) {\n throw new Error(`Collection ${this.name} already exists`);\n }\n\n const existingCollection = db.collection<this['_type']>(oldName);\n\n await existingCollection.rename(this.name, options);\n }\n\n /**\n * Performs a vector similarity search using MongoDB Atlas Vector Search\n *\n * @param params - Vector search parameters\n * @param params.field - The field name containing the vector embeddings\n * @param params.embedding - The query vector to search for\n * @param params.numCandidates - Number of nearest neighbors to consider (default: 100)\n * @param params.limit - Maximum number of results to return (default: 10)\n * @param params.projection - Additional fields to include in the results\n * @param params.indexName - Name of index (default: field + VectorSearch)\n * @returns An aggregation cursor with search results and scores\n *\n * @example\n * ```ts\n * const results = await store.vectorSearch({\n * field: 'embedding',\n * embedding: [0.1, 0.2, 0.3, ...],\n * numCandidates: 100,\n * limit: 10,\n * projection: { title: 1, description: 1 }\n * });\n * ```\n */\n async vectorSearch({\n field,\n embedding,\n numCandidates,\n limit,\n projection,\n indexName,\n }: {\n field: string;\n embedding: number[];\n numCandidates?: number;\n limit?: number;\n projection?: Document;\n indexName?: string;\n }) {\n return this.aggregate([\n {\n $vectorSearch: {\n index: indexName || field + 'VectorSearch',\n path: field,\n queryVector: embedding,\n numCandidates: numCandidates || 100,\n limit: limit || 10,\n },\n },\n {\n $project: {\n _id: 1,\n score: { $meta: 'vectorSearchScore' },\n ...projection,\n },\n },\n ]);\n }\n\n /**\n * Creates a MongoDB Atlas Vector Search index definition\n *\n * @param params - Vector index parameters\n * @param params.field - The field name to create the vector index on\n * @param params.dimensions - The number of dimensions in the vector embeddings\n * @param params.similarity - The similarity metric to use (default: 'cosine')\n * @param params.indexName - Name of index (default: field + VectorSearch)\n * @returns A search index description object\n *\n * @example\n * ```ts\n * const store = new Store('documents', {\n * schema: {\n * title: schema.string(),\n * embedding: schema.array(schema.number()),\n * },\n * indexes: [],\n * searchIndexes: [\n * Store.vectorIndex({\n * field: 'embedding',\n * dimensions: 1536,\n * similarity: 'cosine'\n * })\n * ]\n * });\n * ```\n */\n static vectorIndex({\n field,\n dimensions,\n similarity = 'cosine',\n indexName,\n }: {\n field: string;\n dimensions: number;\n similarity?: 'cosine' | 'euclidean' | 'dotProduct';\n indexName?: string;\n }) {\n return {\n type: 'vectorSearch',\n name: indexName || field + 'VectorSearch',\n definition: {\n fields: [\n {\n type: 'vector',\n path: field,\n numDimensions: dimensions,\n similarity,\n },\n ],\n },\n };\n }\n}\n","import { ObjectId } from 'mongodb';\nimport { z, ZodArray, ZodNumber } from 'zod';\nimport { Store } from './store';\n\ntype ObjectTypeDefinition = {\n [key: string]: SchemaTypeDefinition;\n};\n\ntype SingularSchemaTypeDefinition = z.ZodType | ObjectTypeDefinition; // ReturnType<typeof schema[keyof typeof schema]>;\n\ntype SchemaTypeDefinition = SingularSchemaTypeDefinition | Array<SingularSchemaTypeDefinition>;\n\nexport type ModelSchema = {\n [key: string]: SchemaTypeDefinition;\n};\n\nconst schemaString: typeof z.string = z.string.bind(z);\n\nconst schemaNumber: typeof z.number = z.number.bind(z);\n\nconst schemaDate: typeof z.date = z.date.bind(z);\n\nconst schemaBoolean: typeof z.boolean = z.boolean.bind(z);\n\nconst schemaArray: typeof z.array = z.array.bind(z);\n\nconst schemaObject: typeof z.object = z.object.bind(z);\n\nconst schemaEnum: typeof z.enum = z.enum.bind(z);\n\nexport const schema = {\n string: schemaString,\n number: schemaNumber,\n date: schemaDate,\n boolean: schemaBoolean,\n array: schemaArray,\n object: schemaObject,\n enum: schemaEnum,\n embedding(): ZodArray<ZodNumber> {\n return z.array(z.number());\n },\n objectId(): z.ZodType<ObjectId> {\n return z.instanceof(ObjectId).describe('ObjectId');\n },\n userId(): z.ZodType<ObjectId> {\n return z.instanceof(ObjectId).describe('UserId');\n },\n ref<T extends ModelSchema>(\n _collection: string | Store<T, InferDocumentType<T>>\n ): z.ZodType<ObjectId> {\n return z.instanceof(ObjectId).describe('Ref');\n },\n union: z.union.bind(z),\n infer<T extends SchemaTypeDefinition>(_schema: T): InferDocumentType<T> {\n return {} as InferDocumentType<T>;\n },\n} as const;\n\nexport type InferDocumentType<T extends SchemaTypeDefinition> = {\n [K in keyof T as T[K] extends z.ZodOptional<z.ZodTypeAny> ? K : never]?: T[K] extends z.ZodType\n ? z.infer<T[K]>\n : never;\n} & {\n [K in keyof T as T[K] extends z.ZodOptional<z.ZodTypeAny> ? never : K]: T[K] extends z.ZodType\n ? z.infer<T[K]>\n : T[K] extends Array<infer ElementType extends SchemaTypeDefinition>\n ? Array<InferDocumentType<ElementType>>\n : T[K] extends ObjectTypeDefinition\n ? InferDocumentType<T[K]>\n : never;\n};\n\nexport namespace schema {\n export type infer<T extends SchemaTypeDefinition> = InferDocumentType<T>;\n}\n","import { randomBytes } from 'crypto';\nimport { type Response } from 'express';\nimport { ObjectId } from 'mongodb';\nimport { Module } from '../app/module';\nimport { getPublicConfigs } from '../config/server';\nimport { Store } from '../data/store';\nimport { schema } from '../data/types';\nimport { time } from '../time';\nimport { Session } from './types';\n\nexport const linkNoncesCollection = new Store('_modelenceLinkNonces', {\n schema: {\n nonce: schema.string(),\n userId: schema.string(),\n expiresAt: schema.date(),\n },\n indexes: [\n { key: { nonce: 1 }, unique: true },\n { key: { expiresAt: 1 }, expireAfterSeconds: 0 },\n ],\n});\n\nexport async function issueLinkNonce(userId: string): Promise<string> {\n const nonce = randomBytes(32).toString('hex');\n await linkNoncesCollection.insertOne({\n nonce,\n userId,\n expiresAt: new Date(Date.now() + time.minutes(10)),\n });\n return nonce;\n}\n\nexport async function consumeLinkNonce(nonce: string): Promise<string | null> {\n const entry = await linkNoncesCollection.findOneAndDelete({ nonce });\n if (!entry) return null;\n return entry.userId;\n}\n\nexport const sessionsCollection = new Store('_modelenceSessions', {\n schema: {\n authToken: schema.string(),\n createdAt: schema.date(),\n expiresAt: schema.date(),\n userId: schema.userId().nullable(),\n },\n indexes: [\n { key: { authToken: 1 }, unique: true },\n { key: { expiresAt: 1 }, expireAfterSeconds: 0 },\n { key: { userId: 1 } },\n ],\n});\n\nexport async function obtainSession(authToken: string | null): Promise<Session> {\n const existingSession = authToken ? await sessionsCollection.findOne({ authToken }) : null;\n\n if (existingSession) {\n return {\n authToken: String(existingSession.authToken),\n expiresAt: new Date(existingSession.expiresAt),\n userId: existingSession.userId ?? null,\n };\n }\n\n return await createSession();\n}\n\nexport async function setSessionUser(authToken: string, userId: ObjectId) {\n await sessionsCollection.updateOne(\n { authToken },\n {\n $set: { userId },\n }\n );\n}\n\nexport async function clearSessionUser(authToken: string) {\n await sessionsCollection.updateOne(\n { authToken },\n {\n $set: { userId: null },\n }\n );\n}\n\nexport async function invalidateAllUserSessions(userId: ObjectId) {\n await sessionsCollection.deleteMany({ userId });\n}\n\nexport async function createSession(userId: ObjectId | null = null): Promise<Session> {\n // TODO: add rate-limiting and captcha handling\n\n const authToken = randomBytes(32).toString('base64url');\n const now = Date.now();\n const expiresAt = new Date(now + time.days(7));\n\n await sessionsCollection.insertOne({\n authToken,\n createdAt: new Date(now),\n expiresAt,\n userId,\n });\n\n return {\n authToken,\n expiresAt,\n userId,\n };\n}\n\nasync function processSessionHeartbeat(session: Session) {\n const now = Date.now();\n const newExpiresAt = new Date(now + time.days(7));\n\n await sessionsCollection.updateOne(\n { authToken: session.authToken },\n {\n $set: {\n lastActiveDate: new Date(now),\n expiresAt: newExpiresAt,\n },\n }\n );\n}\n\nexport function setAuthTokenCookie(res: Response, authToken: string) {\n res.cookie('authToken', authToken, {\n httpOnly: true,\n secure: process.env.NODE_ENV === 'production',\n sameSite: 'lax',\n path: '/',\n maxAge: time.days(7),\n });\n}\n\nexport function clearAuthTokenCookie(res: Response) {\n res.clearCookie('authToken', {\n httpOnly: true,\n secure: process.env.NODE_ENV === 'production',\n sameSite: 'lax',\n path: '/',\n });\n}\n\nexport default new Module('_system.session', {\n stores: [sessionsCollection, linkNoncesCollection],\n mutations: {\n init: async function (args, { session, user, res }) {\n // Only refresh the cookie for logged-in sessions. Writing one for a\n // freshly-minted anonymous session creates a Set-Cookie that the\n // browser then attaches to the client's reconciliation request,\n // shadowing the localStorage token sent in the body — see\n // getCallContext's `cookie || body.authToken` precedence.\n if (res && session?.userId) {\n setAuthTokenCookie(res, session.authToken);\n }\n\n return {\n session,\n user,\n configs: getPublicConfigs(),\n };\n },\n heartbeat: async function (args, { session }) {\n // Session might not exist if there is no database/authentication setup\n if (session) {\n await processSessionHeartbeat(session);\n }\n },\n },\n});\n","import { schema } from '../data/types';\nimport { Store } from '../data/store';\n\n/**\n * Database collection for storing user accounts with authentication methods and profile information.\n *\n * This is where **signupWithPassword** automatically creates new users.\n *\n * @example\n * ```typescript\n * // Find user by email\n * const user = await dbUsers.findOne(\n * { 'emails.address': 'john@example.com' }\n * );\n * ```\n *\n */\nexport const usersCollection = new Store('_modelenceUsers', {\n schema: {\n handle: schema.string(),\n emails: schema\n .array(\n schema.object({\n address: schema.string(),\n verified: schema.boolean(),\n })\n )\n .optional(),\n status: schema.enum(['active', 'disabled', 'deleted']).optional(),\n firstName: schema.string().optional(),\n lastName: schema.string().optional(),\n avatarUrl: schema.string().optional(),\n createdAt: schema.date(),\n disabledAt: schema.date().optional(),\n deletedAt: schema.date().optional(),\n roles: schema.array(schema.string()).optional(),\n authMethods: schema.object({\n password: schema\n .object({\n hash: schema.string(),\n })\n .optional(),\n google: schema\n .object({\n id: schema.string(),\n })\n .optional(),\n github: schema\n .object({\n id: schema.string(),\n })\n .optional(),\n }),\n },\n indexes: [\n {\n key: { handle: 1 },\n unique: true,\n collation: { locale: 'en', strength: 2 }, // Case-insensitive\n },\n {\n key: { 'emails.address': 1, status: 1 },\n },\n {\n key: { 'authMethods.google.id': 1 },\n sparse: true,\n unique: true,\n },\n {\n key: { 'authMethods.github.id': 1 },\n sparse: true,\n unique: true,\n },\n ],\n});\n\nexport const dbDisposableEmailDomains = new Store('_modelenceDisposableEmailDomains', {\n schema: {\n domain: schema.string(),\n addedAt: schema.date(),\n },\n indexes: [\n {\n key: { domain: 1 },\n unique: true,\n },\n ],\n});\n\nexport const emailVerificationTokensCollection = new Store('_modelenceEmailVerificationTokens', {\n schema: {\n userId: schema.objectId(),\n email: schema.string().optional(),\n token: schema.string(),\n createdAt: schema.date(),\n expiresAt: schema.date(),\n },\n indexes: [\n {\n key: { token: 1 },\n unique: true,\n },\n {\n key: { expiresAt: 1 },\n expireAfterSeconds: 0,\n },\n ],\n});\n\nexport const resetPasswordTokensCollection = new Store('_modelenceResetPasswordTokens', {\n schema: {\n userId: schema.objectId(),\n email: schema.string().optional(),\n token: schema.string(),\n createdAt: schema.date(),\n expiresAt: schema.date(),\n },\n indexes: [\n {\n key: { token: 1 },\n unique: true,\n },\n {\n key: { expiresAt: 1 },\n expireAfterSeconds: 0,\n },\n ],\n});\n","import { RoleDefinition, Role, DefaultRoles, Permission } from './types';\n\nconst roleMap = new Map<Role, RoleDefinition>();\nconst defaultRoles: DefaultRoles = {\n authenticated: null,\n unauthenticated: null,\n};\n\nexport function initRoles(\n roles: Record<Role, RoleDefinition>,\n _defaultRoles: Record<string, Role>\n) {\n defaultRoles.authenticated = _defaultRoles.authenticated;\n defaultRoles.unauthenticated = _defaultRoles.unauthenticated;\n\n for (const [name, definition] of Object.entries(roles)) {\n roleMap.set(name, definition);\n }\n}\n\nexport function getUnauthenticatedRoles() {\n return defaultRoles.unauthenticated ? [defaultRoles.unauthenticated] : [];\n}\n\nexport function getDefaultAuthenticatedRoles() {\n return defaultRoles.authenticated ? [defaultRoles.authenticated] : [];\n}\n\nexport function hasAccess(roles: Role[], requiredPermissions: Permission[]) {\n return requiredPermissions.every((permission) => hasPermission(roles, permission));\n}\n\nexport function requireAccess(roles: Role[], requiredPermissions: Permission[]) {\n const missingPermission = requiredPermissions.find(\n (permission) => !hasPermission(roles, permission)\n );\n\n if (missingPermission) {\n throw new Error(`Access denied - missing permission: '${missingPermission}'`);\n }\n}\n\nexport function hasPermission(roles: Role[], permission: Permission) {\n for (const role of roles) {\n const definition = roleMap.get(role);\n\n if (definition?.permissions?.includes(permission)) {\n return true;\n }\n }\n\n return false;\n}\n","import { ObjectId } from 'mongodb';\n\nimport { obtainSession } from './session';\nimport { usersCollection } from './db';\nimport { getDefaultAuthenticatedRoles, getUnauthenticatedRoles } from './role';\nimport { Role, Session, UserInfo } from './types';\n\nexport async function authenticate(\n authToken: string | null\n): Promise<{ session: Session; user: UserInfo | null; roles: Role[] }> {\n const session = await obtainSession(authToken);\n\n const userDoc = session.userId\n ? await usersCollection.findOne({\n _id: new ObjectId(session.userId),\n status: { $nin: ['deleted', 'disabled'] },\n })\n : null;\n const user = userDoc\n ? {\n id: userDoc._id.toString(),\n handle: userDoc.handle,\n roles: userDoc.roles || [],\n hasRole: (role: string) => (userDoc.roles || []).includes(role),\n requireRole: (role: string) => {\n if (!(userDoc.roles || []).includes(role)) {\n throw new Error(`Access denied - role '${role}' required`);\n }\n },\n firstName: userDoc.firstName ?? undefined,\n lastName: userDoc.lastName ?? undefined,\n avatarUrl: userDoc.avatarUrl ?? undefined,\n }\n : null;\n\n const roles = user ? getDefaultAuthenticatedRoles() : getUnauthenticatedRoles();\n\n return {\n user,\n session,\n roles,\n };\n}\n","/**\n * Publish function provided to watch handlers.\n * Call this to trigger a re-fetch and send updated data to the client.\n */\nexport type LiveQueryPublish = () => void;\n\n/**\n * Cleanup function returned by watch handlers.\n * Called when the client unsubscribes.\n */\nexport type LiveQueryCleanup = () => void;\n\n/**\n * Context passed to watch handlers.\n */\nexport interface WatchContext {\n publish: LiveQueryPublish;\n}\n\n/**\n * Watch function that sets up real-time monitoring.\n * Receives a context with publish callback to trigger re-fetches.\n * Returns a cleanup function.\n */\nexport type LiveQueryWatch = (context: WatchContext) => LiveQueryCleanup | void;\n\n/**\n * Configuration for creating LiveData.\n */\nexport interface LiveDataConfig<T = unknown> {\n /**\n * Fetches the current data. Called initially and whenever watch triggers publish.\n */\n fetch: () => Promise<T> | T;\n /**\n * Sets up watching for changes. Receives publish callback and returns cleanup.\n */\n watch: LiveQueryWatch;\n}\n\n/**\n * LiveData object returned by live query handlers.\n *\n * @example\n * ```typescript\n * import { LiveData } from 'modelence/server';\n *\n * ...\n *\n * getTodos({ userId }, context) {\n * return new LiveData({\n * fetch: async () => await dbTodos.fetch({ userId }),\n * watch: ({ publish }) => {\n * // Subscribe to changes and call publish when data changes\n * listener.onChange(publish);\n *\n * return () => {\n * // Cleanup function to unsubscribe from changes\n * };\n * }\n * });\n * }\n * ```\n */\nexport class LiveData<T = unknown> {\n readonly fetch: () => Promise<T> | T;\n readonly watch: LiveQueryWatch;\n\n constructor(config: LiveDataConfig<T>) {\n this.fetch = config.fetch;\n this.watch = config.watch;\n }\n}\n","export function isServer() {\n return typeof window !== 'object';\n}\n\nexport function requireServer() {\n if (!isServer()) {\n throw new Error('This function can only be called on the server');\n }\n}\n\nexport function htmlToText(html: string) {\n return html\n .replace(/<[^>]*>/g, '')\n .replace(/\\s+/g, ' ')\n .trim();\n}\n","/**\n * Deny-by-default boundary for client-initiated method dispatch.\n *\n * Methods are dispatched by name from the browser via\n * `POST /api/_internal/method/:methodName` (and the live-query socket path),\n * where `:methodName` is taken verbatim from the request. The `_system.*`\n * namespace is reserved for framework-internal modules, many of which proxy\n * privileged operations (e.g. `_system.files.*` issues signed storage URLs and\n * deletes using the app's service token). Those modules are meant to be called\n * from server-side code — inside an app's own queries/mutations that enforce\n * their own authorization — NOT directly from an untrusted client.\n *\n * Rather than auth-gating each system method individually (easy to forget, and\n * silently default-open when omitted), we deny ALL `_system.*` methods from\n * client dispatch unless they appear on this explicit, hand-audited allowlist.\n * A newly added system method is therefore closed to the client by default and\n * must be consciously opened here. App-defined methods (no `_system.` prefix)\n * are unaffected.\n *\n * The allowlist is exactly the set of `_system.*` methods that the framework's\n * own client bundle (`modelence/client`) legitimately calls from the browser —\n * authentication, session, and profile flows that have no server-only caller.\n */\nconst SYSTEM_PREFIX = '_system.';\n\n/**\n * Exact set of `_system.*` methods the framework's own client bundle invokes.\n * Exported so a test can assert it stays in sync with the actual client callers.\n */\nexport const CLIENT_CALLABLE_SYSTEM_METHODS: ReadonlySet<string> = new Set([\n // Session lifecycle (bootstrapped from the browser / SSR)\n '_system.session.init',\n '_system.session.heartbeat',\n // Authentication + account flows (the browser is the only caller)\n '_system.user.signupWithPassword',\n '_system.user.loginWithPassword',\n '_system.user.logout',\n '_system.user.verifyEmail',\n '_system.user.resendEmailVerification',\n '_system.user.sendResetPasswordToken',\n '_system.user.resetPassword',\n '_system.user.updateProfile',\n '_system.user.unlinkOAuthProvider',\n]);\n\n/**\n * Returns `true` if `methodName` is allowed to be invoked from an untrusted\n * client. App methods are always allowed; `_system.*` methods only if\n * explicitly allowlisted.\n */\nexport function isClientCallableMethod(methodName: string): boolean {\n if (!methodName.startsWith(SYSTEM_PREFIX)) {\n return true;\n }\n return CLIENT_CALLABLE_SYSTEM_METHODS.has(methodName);\n}\n","import { Socket } from 'socket.io';\nimport { z } from 'zod';\nimport { authenticate } from '../auth';\nimport { runLiveMethod } from '../methods';\nimport { isClientCallableMethod } from '../methods/clientAccess';\nimport { getResponseTypeMap, sanitizeResult } from '../methods/serialize';\nimport { LiveQueryCleanup } from './context';\nimport { Context } from '@/methods/types';\n\ninterface ActiveSubscription {\n cleanup: LiveQueryCleanup | null;\n aborted?: boolean;\n}\n\nconst socketSubscriptions = new Map<string, Map<string, ActiveSubscription>>();\n\nfunction getSocketSubs(socket: Socket): Map<string, ActiveSubscription> {\n let subs = socketSubscriptions.get(socket.id);\n if (!subs) {\n subs = new Map();\n socketSubscriptions.set(socket.id, subs);\n }\n return subs;\n}\n\nexport async function handleSubscribeLiveQuery(socket: Socket, payload: unknown) {\n const parsed = z\n .object({\n subscriptionId: z.string().min(1),\n method: z.string().min(1),\n args: z.record(z.unknown()).default({}),\n authToken: z.string().nullish(),\n clientInfo: z\n .object({\n screenWidth: z.number(),\n screenHeight: z.number(),\n windowWidth: z.number(),\n windowHeight: z.number(),\n pixelRatio: z.number(),\n orientation: z.string().nullable(),\n })\n .optional(),\n })\n .safeParse(payload);\n if (!parsed.success) {\n socket.emit('liveQueryError', {\n subscriptionId: null,\n error: `Invalid payload: ${parsed.error.message}`,\n });\n return;\n }\n const { subscriptionId, method, args, authToken, clientInfo } = parsed.data;\n\n // Deny-by-default boundary: reserved `_system.*` methods are not dispatchable\n // from an untrusted client unless explicitly allowlisted. Keep this in sync\n // with the HTTP method route so live queries can't bypass the boundary.\n if (!isClientCallableMethod(method)) {\n socket.emit('liveQueryError', {\n subscriptionId,\n error: `Method with name '${method}' is not defined.`,\n });\n return;\n }\n\n const subs = getSocketSubs(socket);\n\n // Clean up any existing subscription with the same ID (handles reconnect race conditions)\n const existingSub = subs.get(subscriptionId);\n if (existingSub) {\n if (existingSub.cleanup) {\n try {\n existingSub.cleanup();\n } catch (err) {\n console.error('[LiveQuery] Error cleaning up existing subscription:', err);\n }\n } else {\n // Subscription is still initializing - mark it for abort so it cleans up when ready\n existingSub.aborted = true;\n }\n }\n\n // Create placeholder entry BEFORE the async call so disconnect handler can find it\n const subscription: ActiveSubscription = { cleanup: null };\n subs.set(subscriptionId, subscription);\n\n try {\n const { session, user, roles } = await authenticate(authToken ?? null);\n\n const context: Context = {\n session,\n user,\n roles,\n clientInfo: clientInfo ?? {\n screenWidth: 0,\n screenHeight: 0,\n windowWidth: 0,\n windowHeight: 0,\n pixelRatio: 1,\n orientation: null,\n },\n connectionInfo: {\n ip: socket.handshake.address,\n userAgent: socket.handshake.headers['user-agent'],\n },\n req: null,\n res: null,\n };\n\n const liveData = await runLiveMethod(method, args, context);\n\n const fetchAndEmit = async () => {\n const data = sanitizeResult(await liveData.fetch());\n if (subscription.aborted) {\n return;\n }\n socket.emit('liveQueryData', {\n subscriptionId,\n data,\n typeMap: getResponseTypeMap(data),\n });\n };\n\n // Set to true to perform initial fetch at the beginning\n let isPendingPublish = true;\n let isFetching = false;\n\n const processPendingPublish = () => {\n if (subscription.aborted || !isPendingPublish || isFetching) {\n return;\n }\n isPendingPublish = false;\n isFetching = true;\n fetchAndEmit()\n .catch((err) => {\n if (subscription.aborted) {\n return;\n }\n console.error(`[LiveQuery] Error fetching data for ${method}:`, err);\n socket.emit('liveQueryError', {\n subscriptionId,\n error: err instanceof Error ? err.message : String(err),\n });\n })\n .finally(() => {\n isFetching = false;\n // Process the next pending publish if another publish was triggered while fetching\n processPendingPublish();\n });\n };\n\n const cleanup = liveData.watch({\n publish: () => {\n /*\n Use a pending flag to ensure concurrent publishes are processed sequentially\n (and run only once if there have been multiple publishes while the previous one was processing)\n Without sequential processing, we could end up sending an older fetch after a newer one\n */\n isPendingPublish = true;\n processPendingPublish();\n },\n });\n\n if (subscription.aborted) {\n // Unsubscribe/disconnect happened during watch setup - clean up immediately\n if (cleanup) {\n try {\n cleanup();\n } catch (err) {\n console.error('[LiveQuery] Error cleaning up after disconnect during setup:', err);\n }\n }\n return;\n }\n\n subscription.cleanup = cleanup || null;\n\n // Process initial fetch\n processPendingPublish();\n } catch (error) {\n subs.delete(subscriptionId);\n console.error(`[LiveQuery] Error in ${method}:`, error);\n socket.emit('liveQueryError', {\n subscriptionId,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n}\n\nexport function handleUnsubscribeLiveQuery(socket: Socket, payload: unknown) {\n const parsed = z\n .object({\n subscriptionId: z.string().min(1),\n })\n .safeParse(payload);\n if (!parsed.success) {\n console.warn(`[LiveQuery] Invalid unsubscribe payload: ${parsed.error.message}`);\n return;\n }\n const { subscriptionId } = parsed.data;\n\n const subs = socketSubscriptions.get(socket.id);\n if (!subs) return;\n\n const sub = subs.get(subscriptionId);\n if (sub) {\n if (sub.cleanup) {\n try {\n sub.cleanup();\n } catch (err) {\n console.error('[LiveQuery] Error in cleanup:', err);\n }\n } else {\n sub.aborted = true;\n }\n subs.delete(subscriptionId);\n }\n}\n\nexport function handleLiveQueryDisconnect(socket: Socket) {\n const subs = socketSubscriptions.get(socket.id);\n if (subs) {\n // Clean up all subscriptions for this socket\n for (const sub of subs.values()) {\n if (sub.cleanup) {\n try {\n sub.cleanup();\n } catch (err) {\n console.error('[LiveQuery] Error in cleanup on disconnect:', err);\n }\n } else {\n sub.aborted = true;\n }\n }\n socketSubscriptions.delete(socket.id);\n }\n}\n","import { requireServer } from '../utils';\nimport { startTransaction } from '@/telemetry';\nimport { requireAccess } from '../auth/role';\nimport { Method, MethodDefinition, MethodType, Args, Context } from './types';\nimport { LiveData } from '../live-query';\n\nconst methods: Record<string, Method<unknown>> = {};\n\nexport function createQuery<T extends unknown[]>(name: string, methodDef: MethodDefinition<T>) {\n requireServer();\n validateMethodName(name);\n return _createMethodInternal('query', name, methodDef);\n}\n\nexport function createMutation<T extends unknown[]>(name: string, methodDef: MethodDefinition<T>) {\n requireServer();\n validateMethodName(name);\n return _createMethodInternal('mutation', name, methodDef);\n}\n\nexport function _createSystemQuery<T extends unknown[]>(\n name: string,\n methodDef: MethodDefinition<T>\n) {\n requireServer();\n validateSystemMethodName(name);\n return _createMethodInternal('query', name, methodDef);\n}\n\nexport function _createSystemMutation<T extends unknown[]>(\n name: string,\n methodDef: MethodDefinition<T>\n) {\n requireServer();\n validateSystemMethodName(name);\n return _createMethodInternal('mutation', name, methodDef);\n}\n\nfunction validateMethodName(name: string) {\n if (name.toLowerCase().startsWith('_system.')) {\n throw new Error(`Method name cannot start with a reserved prefix: '_system.' (${name})`);\n }\n}\n\nfunction validateSystemMethodName(name: string) {\n if (!name.toLowerCase().startsWith('_system.')) {\n throw new Error(`System method name must start with a prefix: '_system.' (${name})`);\n }\n}\n\nfunction _createMethodInternal<T = unknown>(\n type: MethodType,\n name: string,\n methodDef: MethodDefinition<T>\n) {\n requireServer();\n\n if (methods[name]) {\n throw new Error(`Method with name '${name}' is already defined.`);\n }\n\n const handler = typeof methodDef === 'function' ? methodDef : methodDef.handler;\n const permissions = typeof methodDef === 'function' ? [] : (methodDef.permissions ?? []);\n methods[name] = { type, name, handler, permissions };\n}\n\nexport async function runMethod(name: string, args: Args, context: Context) {\n requireServer();\n\n const method = methods[name];\n if (!method) {\n throw new Error(`Method with name '${name}' is not defined.`);\n }\n const { type, handler } = method;\n\n const transaction = startTransaction('method', `method:${name}`, { type, args });\n\n let response;\n try {\n requireAccess(context.roles, method.permissions);\n response = await handler(args, context);\n } catch (error) {\n // TODO: log error and associate it with the transaction\n transaction.end('error');\n throw error;\n }\n\n transaction.end();\n\n return response;\n}\n\n/**\n * Run a method as a live query.\n * The handler should return a LiveData object with fetch and watch functions.\n */\nexport async function runLiveMethod(name: string, args: Args, context: Context): Promise<LiveData> {\n requireServer();\n\n const method = methods[name];\n if (!method) {\n throw new Error(`Method with name '${name}' is not defined.`);\n }\n const { type, handler } = method;\n\n if (type !== 'query') {\n throw new Error(`Live methods are only supported for queries`);\n }\n\n const transaction = startTransaction('method', `method:${name}:live`, { type, args });\n\n let result;\n try {\n requireAccess(context.roles, method.permissions);\n\n result = await handler(args, context);\n\n if (!(result instanceof LiveData)) {\n throw new Error(\n `Live query handler for '${name}' must return a LiveData object with fetch and watch functions. See https://docs.modelence.com/live-queries`\n );\n }\n } catch (error) {\n transaction.end('error');\n throw error;\n }\n\n transaction.end();\n\n return result;\n}\n"]}
|
package/dist/server-OYDAIDR6.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
export{g as getCallContext,f as startServer}from'./chunk-A2J5PPAQ.js';import'./chunk-5LP23CUB.js';import'./chunk-GPKIS2JI.js';import'./chunk-MIRF7FP3.js';import'./chunk-7LPSX5A6.js';import'./chunk-5M6FUMUK.js';import'./chunk-DO5TZLF5.js';//# sourceMappingURL=server-OYDAIDR6.js.map
|
|
2
|
-
//# sourceMappingURL=server-OYDAIDR6.js.map
|