modelence 0.21.0 → 0.22.0-rc.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-5XIH7C7R.js +37 -0
- package/dist/chunk-5XIH7C7R.js.map +1 -0
- package/dist/chunk-AMJHJA2V.js +2 -0
- package/dist/chunk-AMJHJA2V.js.map +1 -0
- package/dist/chunk-BCUSVRAY.js +2 -0
- package/dist/chunk-BCUSVRAY.js.map +1 -0
- package/dist/chunk-LCGVOLVA.js +3 -0
- package/dist/chunk-LCGVOLVA.js.map +1 -0
- package/dist/chunk-OJ3LMWVQ.js +2 -0
- package/dist/{chunk-TBGXZXAA.js.map → chunk-OJ3LMWVQ.js.map} +1 -1
- package/dist/{chunk-SNADMLAT.js → chunk-PJRYLKYW.js} +2 -2
- package/dist/{chunk-SNADMLAT.js.map → chunk-PJRYLKYW.js.map} +1 -1
- package/dist/chunk-VF4RU7MF.js +3 -0
- package/dist/chunk-VF4RU7MF.js.map +1 -0
- package/dist/chunk-YOJ4ZP5D.js +4 -0
- package/dist/chunk-YOJ4ZP5D.js.map +1 -0
- package/dist/client.d.ts +89 -4
- package/dist/client.js +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/{package-BVTS5E5V.js → package-6TCJHXFX.js} +2 -2
- package/dist/{package-BVTS5E5V.js.map → package-6TCJHXFX.js.map} +1 -1
- package/dist/render-CBIFY4DG.js +2 -0
- package/dist/render-CBIFY4DG.js.map +1 -0
- package/dist/renderApp-J347DR2B.js +2 -0
- package/dist/{renderApp-QYMNQ3KS.js.map → renderApp-J347DR2B.js.map} +1 -1
- package/dist/server-NBPRZYSI.js +2 -0
- package/dist/{server-KAHRRRDU.js.map → server-NBPRZYSI.js.map} +1 -1
- package/dist/server.d.ts +53 -8
- package/dist/server.js +1 -1
- package/dist/telemetry.d.ts +6 -1
- package/dist/telemetry.js +1 -1
- package/dist/transport-C7DEK6NV.js +2 -0
- package/dist/{transport-W6JIYZKZ.js.map → transport-C7DEK6NV.js.map} +1 -1
- package/dist/{types-B_R3eHmq.d.ts → types-B8uEAj0y.d.ts} +1 -1
- package/dist/{types-_BTBqn8b.d.ts → types-D_70a365.d.ts} +47 -2
- package/dist/types.d.ts +2 -2
- package/package.json +4 -6
- package/dist/chunk-3SGMDISS.js +0 -29
- package/dist/chunk-3SGMDISS.js.map +0 -1
- package/dist/chunk-7LPSX5A6.js +0 -3
- package/dist/chunk-7LPSX5A6.js.map +0 -1
- package/dist/chunk-KZZYA5HP.js +0 -3
- package/dist/chunk-KZZYA5HP.js.map +0 -1
- package/dist/chunk-SD3ERG2G.js +0 -3
- package/dist/chunk-SD3ERG2G.js.map +0 -1
- package/dist/chunk-TBGXZXAA.js +0 -2
- package/dist/chunk-YLLX26A4.js +0 -2
- package/dist/chunk-YLLX26A4.js.map +0 -1
- package/dist/chunk-YRR32LTF.js +0 -2
- package/dist/chunk-YRR32LTF.js.map +0 -1
- package/dist/render-STDR67WK.js +0 -2
- package/dist/render-STDR67WK.js.map +0 -1
- package/dist/renderApp-QYMNQ3KS.js +0 -2
- package/dist/server-KAHRRRDU.js +0 -2
- package/dist/transport-W6JIYZKZ.js +0 -2
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/app/module.ts","../src/data/schemaSerializer.ts","../src/data/schemaDefaults.ts","../src/data/indexErrors.ts","../src/data/store.ts","../src/data/types.ts","../src/auth/tokenHash.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/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","INDEX_ERROR_LOG_PREFIX","isUniqueIndexViolation","error","MongoServerError","formatUniqueIndexViolationReport","collectionName","details","aggregateOptions","aggregateCall","buildDuplicateLookupPipeline","fields","unwindStages","field","pathPrefixes","path","groupId","segments","_","COMPARABLE_INDEX_OPTION_FIELDS","hasModelencePrefix","getComparableIndexOptions","options","isSameIndexKey","left","right","leftEntries","rightEntries","leftField","leftDirection","rightField","rightDirection","isDeepStrictEqual","isSameIndexDefinition","existing","desired","getIndexKeySignature","direction","listIndexes","collection","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","hashToken","rawToken","createHash","linkNoncesCollection","issueLinkNonce","userId","nonce","randomBytes","time","consumeLinkNonce","entry","sessionsCollection","obtainSession","authToken","hashedToken","existingSession","isHex64","createSession","setSessionUser","clearSessionUser","invalidateAllUserSessions","now","expiresAt","processSessionHeartbeat","session","newExpiresAt","setAuthTokenCookie","res","clearAuthTokenCookie","session_default","args","user","getPublicConfigs","usersCollection","dbDisposableEmailDomains","emailVerificationTokensCollection","resetPasswordTokensCollection","magicLinkTokensCollection","roleMap","defaultRoles","initRoles","roles","_defaultRoles","definition","getUnauthenticatedRoles","getDefaultAuthenticatedRoles","requireAccess","requiredPermissions","missingPermission","permission","hasPermission","role","authenticate","userDoc","LiveData","isServer","requireServer","htmlToText","html","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","redactSensitive","response"],"mappings":"uTA0CO,IAAMA,EAAN,KAKL,CAqCA,YACEC,CAAAA,CACA,CACE,OAAAC,CAAAA,CAAS,GACT,OAAA,CAAAC,CAAAA,CAAU,EAAC,CACX,SAAA,CAAAC,EAAY,EAAC,CACb,OAAAC,CAAAA,CAAS,EAAC,CACV,QAAA,CAAAC,EAAW,EAAC,CACZ,aAAAC,CAAAA,CAAe,GACf,UAAA,CAAAC,CAAAA,CAAa,EAAC,CACd,QAAA,CAAAC,EAAW,EACb,EAUI,EAAC,CACL,CACA,IAAA,CAAK,IAAA,CAAOR,CAAAA,CACZ,IAAA,CAAK,OAASC,CAAAA,CACd,IAAA,CAAK,QAAUC,CAAAA,CACf,IAAA,CAAK,UAAYC,CAAAA,CACjB,IAAA,CAAK,OAASC,CAAAA,CACd,IAAA,CAAK,SAAWC,CAAAA,CAChB,IAAA,CAAK,aAAeC,CAAAA,CACpB,IAAA,CAAK,WAAaC,CAAAA,CAClB,IAAA,CAAK,SAAWC,EAClB,CAsBA,UAA4CC,CAAAA,CAAuC,CACjF,OAAOC,CAAAA,CAAW,CAAA,EAAG,KAAK,IAAI,CAAA,CAAA,EAAID,CAAG,CAAA,CAAE,CACzC,CACF,EC3EA,SAASE,CAAAA,CAAmBC,EAAsC,CAChE,IAAMC,EAAMD,CAAAA,CAAQ,IAAA,CAEpB,GAAIC,CAAAA,CAAI,QAAA,G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P,CAAAA,CAAM,OAAA,CAAAC,CAAQ,CAAA,CAAI7B,GAAAA,CAE1B,GAAI4B,CAAAA,GAAS,OAAA,CACX,MAAM,IAAI,KAAA,CAAM,6CAA6C,CAAA,CAG/D,IAAMI,CAAAA,CAAcC,CAAAA,CAAiB,QAAA,CAAU,CAAA,OAAA,EAAUzP,CAAI,CAAA,KAAA,CAAA,CAAS,CACpE,IAAA,CAAAoP,CAAAA,CACA,IAAA,CAAMM,CAAAA,CAAgBvE,CAAI,CAC5B,CAAC,CAAA,CAEGjJ,CAAAA,CACJ,GAAI,CAKF,GAJAiK,CAAAA,CAAc0B,CAAAA,CAAQ,KAAA,CAAOL,GAAAA,CAAO,WAAW,CAAA,CAE/CtL,CAAAA,CAAS,MAAMmN,CAAAA,CAAQlE,CAAAA,CAAM0C,CAAO,CAAA,CAEhC,EAAE3L,CAAAA,YAAkByK,CAAAA,CAAAA,CACtB,MAAM,IAAI,KAAA,CACR,CAAA,wBAAA,EAA2B3M,CAAI,CAAA,2GAAA,CACjC,CAEJ,CAAA,MAASuC,CAAAA,CAAO,CACd,MAAAiN,CAAAA,CAAY,GAAA,CAAI,OAAO,CAAA,CACjBjN,CACR,CAEA,OAAAiN,CAAAA,CAAY,GAAA,GAELtN,CACT","file":"chunk-YOJ4ZP5D.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 { Document, IndexDescription, MongoServerError } from 'mongodb';\n\n/**\n * Stable prefix for unique-index failure reports so log tooling and AI agents\n * can find them with a single grep, regardless of which store failed.\n */\nexport const INDEX_ERROR_LOG_PREFIX = '[modelence:index-error]';\n\n/**\n * Whether an index-creation error means the collection already contains\n * documents that violate a unique constraint (Mongo duplicate-key, E11000).\n * Index-build failures sometimes surface without the 11000 code, so the\n * message is checked as a fallback.\n */\nexport function isUniqueIndexViolation(error: unknown): error is MongoServerError {\n if (!(error instanceof MongoServerError)) {\n return false;\n }\n return error.code === 11000 || error.message.includes('E11000');\n}\n\n/**\n * Builds the report logged when a unique index cannot be created because\n * existing documents violate it. The report is designed to be actionable by\n * an AI agent operating the application: a greppable prefix, a single-line\n * JSON details block, a runnable aggregation that locates the conflicting\n * documents for this exact index spec, and the fix/retry procedure.\n */\nexport function formatUniqueIndexViolationReport(\n collectionName: string,\n index: IndexDescription,\n error: MongoServerError\n): string {\n const details = {\n problem: 'unique-index-violation',\n collection: collectionName,\n index: {\n name: index.name ?? null,\n key: index.key,\n collation: index.collation ?? null,\n partialFilterExpression: index.partialFilterExpression ?? null,\n },\n duplicateKey: error.keyValue ?? null,\n serverError: error.errmsg ?? error.message,\n };\n\n const aggregateOptions = index.collation ? { collation: index.collation } : undefined;\n const aggregateCall =\n `db.getCollection(${JSON.stringify(collectionName)})` +\n `.aggregate(${JSON.stringify(buildDuplicateLookupPipeline(index))}` +\n (aggregateOptions ? `, ${JSON.stringify(aggregateOptions)}` : '') +\n ')';\n\n return [\n `${INDEX_ERROR_LOG_PREFIX} Unique index '${index.name ?? JSON.stringify(index.key)}' on ` +\n `collection '${collectionName}' could not be created because existing documents already ` +\n 'violate it. Until this is resolved the constraint is NOT enforced, so new duplicates ' +\n 'can still be written.',\n `Details: ${JSON.stringify(details)}`,\n 'Find the conflicting documents with:',\n ` ${aggregateCall}`,\n 'Fix: merge, delete, or update the conflicting documents so each indexed value is unique, ' +\n 'then restart the app — the index build is retried on startup.',\n ].join('\\n');\n}\n\n/**\n * Aggregation that groups documents by the indexed fields and keeps groups\n * claimed by more than one document — i.e. exactly the rows blocking the\n * unique index. Mirrors the index's partial filter so non-indexed documents\n * are not reported. Capped so a badly corrupted collection cannot produce an\n * unbounded result.\n */\nfunction buildDuplicateLookupPipeline(index: IndexDescription): Document[] {\n const fields = Object.keys(index.key);\n\n // Unique indexes can be multikey (any path segment may be an array), and the\n // index spec alone cannot tell which. $unwind every prefix of every indexed\n // path so individual array values are compared: it passes non-array values\n // through unchanged, so this is also correct for plain scalar fields.\n // preserveNullAndEmptyArrays keeps documents missing the field — under a\n // non-partial unique index those collide on null and must be reported too.\n const unwindStages = fields.flatMap((field) =>\n pathPrefixes(field).map((path) => ({\n $unwind: { path: `$${path}`, preserveNullAndEmptyArrays: true },\n }))\n );\n\n const groupId = Object.fromEntries(\n // $group _id field names cannot contain dots; the value keeps the real path.\n fields.map((field) => [field.replace(/\\./g, '_'), `$${field}`])\n );\n\n return [\n ...(index.partialFilterExpression ? [{ $match: index.partialFilterExpression }] : []),\n ...unwindStages,\n // Distinct ids, not a row count: after $unwind one document repeating a\n // value in its own array yields several rows, but that is not a\n // cross-document conflict.\n { $group: { _id: groupId, ids: { $addToSet: '$_id' } } },\n { $match: { $expr: { $gt: [{ $size: '$ids' }, 1] } } },\n { $limit: 100 },\n ];\n}\n\nfunction pathPrefixes(field: string): string[] {\n const segments = field.split('.');\n return segments.map((_, index) => segments.slice(0, index + 1).join('.'));\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 CollationOptions,\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';\nimport { isUniqueIndexViolation, formatUniqueIndexViolationReport } from './indexErrors';\n\n/**\n * Result of {@link Store.findOneAndUpsert}: the post-op document plus whether\n * this call inserted it. Declared at module scope (not inline) so the `this`\n * polymorphic document type can be passed in as a type parameter — TS forbids\n * a `this` type inside an inline object-type literal in a return position.\n */\nexport type UpsertResult<TDoc> = {\n /** The document after the op; null only when `upsert: false` and nothing matched. */\n doc: TDoc | null;\n /** True exactly when this call inserted the document. */\n isNew: boolean;\n};\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 try {\n await collection.createIndexes([index]);\n } catch (error) {\n // A unique index failing on existing duplicates is silently dangerous\n // (the constraint stays unenforced), so log an actionable report an\n // operator or AI agent can resolve, then let the error propagate.\n if (index.unique && isUniqueIndexViolation(error)) {\n console.error(formatUniqueIndexViolationReport(this.name, index, error));\n }\n throw error;\n }\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; collation?: CollationOptions }\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 * Atomic find-or-create: runs `findOneAndUpdate` with `upsert` and reports,\n * as `isNew`, whether the returned document was newly inserted.\n *\n * The plain {@link findOneAndUpdate} deliberately hides result metadata and\n * returns only the document, so it can't distinguish an insert from a match.\n * This method surfaces the driver's `lastErrorObject.upserted` flag as\n * `isNew`, so callers can branch on create-vs-match without a separate\n * pre-existence read that would race with concurrent upserts.\n *\n * `upsert` defaults to `true` but is overridable — pass `upsert: false` to\n * make this a pure find-and-report (unknown selector → `{ doc: null, isNew:\n * false }`). `returnDocument` is always `'after'` and cannot be overridden.\n *\n * @example\n * ```ts\n * const { doc, isNew } = await dbUsers.findOneAndUpsert(\n * { email },\n * { $setOnInsert: { email, createdAt: new Date() } }\n * );\n * if (isNew) onSignup(doc); else onLogin(doc);\n * ```\n *\n * @returns `{ doc, isNew }` — `doc` is null only when `upsert: false` and\n * nothing matched; `isNew` is `true` exactly when this call inserted the doc.\n */\n async findOneAndUpsert(\n selector: TypedFilter<this['_type']> | string | ObjectId,\n update: UpdateFilter<this['_type']>,\n options?: Omit<FindOneAndUpdateOptions, 'includeResultMetadata' | 'returnDocument'>\n ): Promise<UpsertResult<this['_doc']>> {\n const result = await this.requireCollection().findOneAndUpdate(\n this.getSelector(selector),\n update,\n {\n upsert: true,\n ...options,\n // Always request the post-op doc and the metadata carrying `upserted`.\n returnDocument: 'after',\n includeResultMetadata: true,\n }\n );\n const doc = result.value ? this.wrapDocument(result.value as this['_rawDoc']) : null;\n return { doc, isNew: Boolean(result.lastErrorObject?.upserted) };\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 { createHash } from 'crypto';\n\n/**\n * Hashes a bearer token for storage at rest, so a db leak exposes no usable\n * tokens. SHA-256 (not bcrypt): these tokens are already 256-bit random, so\n * there's nothing to brute-force and a fast hash keeps lookups cheap.\n */\nexport function hashToken(rawToken: string): string {\n return createHash('sha256').update(rawToken).digest('hex');\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 { hashToken } from './tokenHash';\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 if (authToken) {\n const hashedToken = hashToken(authToken);\n let existingSession = await sessionsCollection.findOne({ authToken: hashedToken });\n\n // Legacy fallback: try raw token lookup (pre-hash sessions)\n // Ensure the authToken is not a hex-encoded SHA-256 hash to prevent\n // replay attacks using leaked hashed tokens.\n const isHex64 = /^[0-9a-f]{64}$/i.test(authToken);\n if (!existingSession && !isHex64) {\n existingSession = await sessionsCollection.findOne({ authToken });\n if (existingSession) {\n await sessionsCollection.updateOne(\n { _id: existingSession._id as ObjectId },\n { $set: { authToken: hashedToken } }\n );\n }\n }\n\n if (existingSession) {\n return {\n authToken,\n expiresAt: new Date(existingSession.expiresAt),\n userId: existingSession.userId ?? null,\n };\n }\n }\n\n return await createSession();\n}\n\nexport async function setSessionUser(authToken: string, userId: ObjectId) {\n await sessionsCollection.updateOne(\n { authToken: hashToken(authToken) },\n {\n $set: { userId },\n }\n );\n}\n\nexport async function clearSessionUser(authToken: string) {\n await sessionsCollection.updateOne(\n { authToken: hashToken(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: hashToken(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: hashToken(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 // Race-proof guard against two accounts sharing an email: the check-then-\n // insert in the signup paths (password + magic link) can interleave, so\n // the DB must enforce uniqueness. Case-insensitive collation matches the\n // `handle` index and the emails.address lookups. Partial so the many\n // legacy/optional docs without an `emails` array don't all collide on null.\n key: { 'emails.address': 1 },\n unique: true,\n collation: { locale: 'en', strength: 2 },\n partialFilterExpression: { 'emails.address': { $exists: true } },\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\n// No userId field: the login mutation re-resolves the user by email to support\n// find-or-create (magic link signs up unknown emails), and a userId captured at\n// send time could go stale before the link is clicked.\n//\n// Each doc backs two credentials for the same sign-in: the long `token` (link)\n// and the short `code` (typed one-time code). Consuming either deletes the doc,\n// invalidating both.\nexport const magicLinkTokensCollection = new Store('_modelenceMagicLinkTokens', {\n schema: {\n email: schema.string(),\n token: schema.string(),\n code: schema.string(),\n // Failed code guesses; docs at the attempt cap can no longer be used.\n attempts: schema.number(),\n createdAt: schema.date(),\n expiresAt: schema.date(),\n },\n indexes: [\n {\n key: { token: 1 },\n unique: true,\n },\n {\n // The one-time-code path is keyed by email: the login looks up\n // { email, code, attempts } and every wrong guess runs\n // updateMany({ email }). Both are attacker-reachable (rate-limited,\n // but still a hot path) and would be collection scans without this.\n key: { email: 1 },\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","import { Socket } from 'socket.io';\nimport { z } from 'zod';\nimport { authenticate } from '../auth';\nimport { runLiveMethod } from '../methods';\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 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, redactSensitive } 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}`, {\n type,\n args: redactSensitive(args),\n });\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`, {\n type,\n args: redactSensitive(args),\n });\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/client.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { b as ClientInfo, c as ConfigKey, d as ConfigParams, A as AnyMethodShape, V as ValueType, e as ConfigType, O as OAuthProvider, W as WebsocketClientProvider, f as ClientChannel } from './types-
|
|
1
|
+
import { b as ClientInfo, c as ConfigKey, d as ConfigParams, A as AnyMethodShape, V as ValueType, e as ConfigType, O as OAuthProvider, W as WebsocketClientProvider, f as ClientChannel } from './types-B8uEAj0y.js';
|
|
2
2
|
import { ObjectId } from 'mongodb';
|
|
3
3
|
import React, { ReactNode } from 'react';
|
|
4
4
|
import * as react_jsx_runtime from 'react/jsx-runtime';
|
|
@@ -17,6 +17,16 @@ interface ClientConfig {
|
|
|
17
17
|
* Defaults to `window.location.href` when not provided.
|
|
18
18
|
*/
|
|
19
19
|
openUrl?: (url: string) => void;
|
|
20
|
+
/**
|
|
21
|
+
* Credentials mode for method-call requests. Defaults to `'include'`, which
|
|
22
|
+
* browser apps need for the cookie-based flows (password reset, magic link).
|
|
23
|
+
*
|
|
24
|
+
* Clients configured with token-in-body auth (React Native / Expo) never use
|
|
25
|
+
* cookies, so set `'omit'` there — on Expo Web a credentialed cross-origin
|
|
26
|
+
* request is otherwise blocked by any server answering
|
|
27
|
+
* `Access-Control-Allow-Origin: *`, surfacing as "TypeError: Failed to fetch".
|
|
28
|
+
*/
|
|
29
|
+
credentials?: RequestCredentials;
|
|
20
30
|
}
|
|
21
31
|
/**
|
|
22
32
|
* Configure the Modelence client for non-browser environments like React Native.
|
|
@@ -423,13 +433,88 @@ declare function logout(): Promise<void>;
|
|
|
423
433
|
declare function sendResetPasswordToken(options: {
|
|
424
434
|
email: string;
|
|
425
435
|
}): Promise<void>;
|
|
436
|
+
/**
|
|
437
|
+
* Send a magic sign-in link to the given email address.
|
|
438
|
+
*
|
|
439
|
+
* Clicking the emailed link signs the user in. When the server enables
|
|
440
|
+
* `auth.magicLink.allowSignup`, this also works for new users — the account is
|
|
441
|
+
* created when the link is used; otherwise unknown emails receive no email.
|
|
442
|
+
* A generic response is always returned to avoid leaking account information.
|
|
443
|
+
*
|
|
444
|
+
* @example
|
|
445
|
+
* ```ts
|
|
446
|
+
* await sendMagicLink({ email: 'user@example.com' });
|
|
447
|
+
* ```
|
|
448
|
+
* @param options.email - The email address to send the magic link to.
|
|
449
|
+
*/
|
|
450
|
+
declare function sendMagicLink(options: {
|
|
451
|
+
email: string;
|
|
452
|
+
}): Promise<void>;
|
|
453
|
+
/**
|
|
454
|
+
* Complete a magic link sign-in.
|
|
455
|
+
*
|
|
456
|
+
* Call this from the page the magic link landing route redirects to. The
|
|
457
|
+
* token is exchanged server-side via an httpOnly cookie, so no arguments are
|
|
458
|
+
* needed. Signs the user in — creating the account first when the email is
|
|
459
|
+
* not registered yet and the server enables `auth.magicLink.allowSignup` —
|
|
460
|
+
* and returns the logged-in user.
|
|
461
|
+
*
|
|
462
|
+
* @example
|
|
463
|
+
* ```ts
|
|
464
|
+
* const user = await loginWithMagicLink();
|
|
465
|
+
* ```
|
|
466
|
+
*/
|
|
467
|
+
declare function loginWithMagicLink(): Promise<{
|
|
468
|
+
id: string;
|
|
469
|
+
handle: string;
|
|
470
|
+
roles: string[];
|
|
471
|
+
hasRole: (role: string) => boolean;
|
|
472
|
+
requireRole: (role: string) => void;
|
|
473
|
+
firstName?: string;
|
|
474
|
+
lastName?: string;
|
|
475
|
+
avatarUrl?: string;
|
|
476
|
+
} | null>;
|
|
477
|
+
/**
|
|
478
|
+
* Complete a magic link sign-in by typing the one-time code from the email.
|
|
479
|
+
*
|
|
480
|
+
* Alternative to `loginWithMagicLink()` for contexts where clicking the link
|
|
481
|
+
* can't reach the app — native apps without deep links, or when the email is
|
|
482
|
+
* read on a different device. Signs the user in — creating the account first
|
|
483
|
+
* when the email is not registered yet and the server enables
|
|
484
|
+
* `auth.magicLink.allowSignup` — and returns the logged-in user.
|
|
485
|
+
*
|
|
486
|
+
* @example
|
|
487
|
+
* ```ts
|
|
488
|
+
* const user = await loginWithOneTimeCode({ email: 'user@example.com', code: '482193' });
|
|
489
|
+
* ```
|
|
490
|
+
* @param options.email - The email the magic link was sent to.
|
|
491
|
+
* @param options.code - The one-time code from the email.
|
|
492
|
+
*/
|
|
493
|
+
declare function loginWithOneTimeCode(options: {
|
|
494
|
+
email: string;
|
|
495
|
+
code: string;
|
|
496
|
+
}): Promise<{
|
|
497
|
+
id: string;
|
|
498
|
+
handle: string;
|
|
499
|
+
roles: string[];
|
|
500
|
+
hasRole: (role: string) => boolean;
|
|
501
|
+
requireRole: (role: string) => void;
|
|
502
|
+
firstName?: string;
|
|
503
|
+
lastName?: string;
|
|
504
|
+
avatarUrl?: string;
|
|
505
|
+
} | null>;
|
|
426
506
|
/**
|
|
427
507
|
* Reset password.
|
|
428
|
-
*
|
|
508
|
+
*
|
|
509
|
+
* The token is normally exchanged server-side via an httpOnly cookie, so the
|
|
510
|
+
* client only submits the new password. Pass `token` only for legacy flows
|
|
511
|
+
* that still carry it client-side (deprecated).
|
|
512
|
+
*
|
|
513
|
+
* @param options.token - Reset token (optional; read from the httpOnly cookie when omitted).
|
|
429
514
|
* @param options.password - The new password.
|
|
430
515
|
*/
|
|
431
516
|
declare function resetPassword(options: {
|
|
432
|
-
token
|
|
517
|
+
token?: string;
|
|
433
518
|
password: string;
|
|
434
519
|
}): Promise<void>;
|
|
435
520
|
/**
|
|
@@ -472,4 +557,4 @@ declare function getLocalStorageSession(): any;
|
|
|
472
557
|
|
|
473
558
|
declare const AppProvider: any;
|
|
474
559
|
|
|
475
|
-
export { AppProvider, type CallMethodOptions, ClientChannel, type ClientConfig, type MethodArgs, MethodError, ModelenceQueryClient, type ModelenceQueryKey, ModelenceQueryProvider, type UserInfo, ValueType, callMethod, configureClient, connectModelenceQueryClient, createClientModule, createQueryKey, disconnectModelenceQueryClient, getConfig, getLocalStorageSession, getWebsocketClientProvider, linkOAuthProvider, loginWithPassword, logout, modelenceLiveQuery, modelenceMutation, modelenceQuery, renderApp, resendEmailVerification, resetPassword, sendResetPasswordToken, setWebsocketClientProvider, signupWithPassword, startWebsockets, subscribeLiveQuery, systemConfig, unlinkOAuthProvider, updateProfile, useSession, verifyEmail };
|
|
560
|
+
export { AppProvider, type CallMethodOptions, ClientChannel, type ClientConfig, type MethodArgs, MethodError, ModelenceQueryClient, type ModelenceQueryKey, ModelenceQueryProvider, type UserInfo, ValueType, callMethod, configureClient, connectModelenceQueryClient, createClientModule, createQueryKey, disconnectModelenceQueryClient, getConfig, getLocalStorageSession, getWebsocketClientProvider, linkOAuthProvider, loginWithMagicLink, loginWithOneTimeCode, loginWithPassword, logout, modelenceLiveQuery, modelenceMutation, modelenceQuery, renderApp, resendEmailVerification, resetPassword, sendMagicLink, sendResetPasswordToken, setWebsocketClientProvider, signupWithPassword, startWebsockets, subscribeLiveQuery, systemConfig, unlinkOAuthProvider, updateProfile, useSession, verifyEmail };
|
package/dist/client.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export{f as AppProvider,e as ClientChannel,a as createClientModule,d as renderApp,b as systemConfig}from'./chunk-
|
|
1
|
+
export{f as AppProvider,e as ClientChannel,a as createClientModule,d as renderApp,b as systemConfig}from'./chunk-OJ3LMWVQ.js';export{i as ModelenceQueryClient,n as ModelenceQueryProvider,f as connectModelenceQueryClient,m as createQueryKey,h as disconnectModelenceQueryClient,d as getWebsocketClientProvider,k as modelenceLiveQuery,l as modelenceMutation,j as modelenceQuery,c as setWebsocketClientProvider,e as startWebsockets,b as subscribeLiveQuery}from'./chunk-BCUSVRAY.js';export{t as MethodError,w as callMethod,b as configureClient,y as getConfig,a as getLocalStorageSession,o as linkOAuthProvider,l as loginWithMagicLink,m as loginWithOneTimeCode,e as loginWithPassword,i as logout,h as resendEmailVerification,n as resetPassword,k as sendMagicLink,j as sendResetPasswordToken,d as signupWithPassword,p as unlinkOAuthProvider,f as updateProfile,H as useSession,g as verifyEmail}from'./chunk-AMJHJA2V.js';import'./chunk-5M6FUMUK.js';import'./chunk-DO5TZLF5.js';//# sourceMappingURL=client.js.map
|
|
2
2
|
//# sourceMappingURL=client.js.map
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { C as ConfigSchema, W as WebsocketClientProvider, a as WebsocketServerProvider } from './types-
|
|
1
|
+
export { C as ConfigSchema, W as WebsocketClientProvider, a as WebsocketServerProvider } from './types-B8uEAj0y.js';
|
|
2
2
|
export { M as ModelenceConfig } from './index-CgNFVSg6.js';
|
|
3
3
|
import 'http';
|
|
4
4
|
import 'mongodb';
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export{l as author,i as bin,n as bugs,s as default,q as dependencies,d as description,p as devDependencies,g as exports,h as files,o as homepage,m as license,e as main,b as name,r as peerDependencies,k as repository,j as scripts,a as type,f as types,c as version}from'./chunk-
|
|
2
|
-
//# sourceMappingURL=package-
|
|
1
|
+
export{l as author,i as bin,n as bugs,s as default,q as dependencies,d as description,p as devDependencies,g as exports,h as files,o as homepage,m as license,e as main,b as name,r as peerDependencies,k as repository,j as scripts,a as type,f as types,c as version}from'./chunk-LCGVOLVA.js';//# sourceMappingURL=package-6TCJHXFX.js.map
|
|
2
|
+
//# sourceMappingURL=package-6TCJHXFX.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":[],"names":[],"mappings":"","file":"package-
|
|
1
|
+
{"version":3,"sources":[],"names":[],"mappings":"","file":"package-6TCJHXFX.js"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {a,b,c}from'./chunk-PJRYLKYW.js';import'./chunk-YOJ4ZP5D.js';import'./chunk-VF4RU7MF.js';import {a as a$1,n}from'./chunk-BCUSVRAY.js';import {F,x,G}from'./chunk-AMJHJA2V.js';import'./chunk-5M6FUMUK.js';import'./chunk-DO5TZLF5.js';import {renderToPipeableStream}from'react-dom/server';import {Writable}from'stream';import {QueryClient,dehydrate}from'@tanstack/react-query';import {jsx}from'react/jsx-runtime';var J=()=>{let r=c();return r?G(r.session.user):null},M=r=>{let n=c();if(n)return n.session.configs[r]?.value};function D(){F(J),x(M);}async function X(r){let{callContext:n$1,loadingElement:C,routesElement:S,router:u,location:x,onShellReady:E,onError:b$1}=r;D();let l=await a("_system.session.init",{},n$1),i=new QueryClient({defaultOptions:{queries:{retry:false,gcTime:0}}}),O=u?u({children:S,location:x}):S,Q=jsx(a$1,{loadingElement:C,children:jsx(n,{client:i,children:O})}),a$2=null;await new Promise((s,m)=>{b({callContext:n$1,queryClient:i,session:{user:l.user,configs:l.configs??{}}},()=>{let e=renderToPipeableStream(Q,{onShellReady(){a$2=e,E?.(),s(e);},onShellError(t){m(t);},onError(t){b$1?.(t);}});return e});});let d=null,_=s=>new Promise((m,e)=>{if(!a$2){e(new Error("SSR stream was not initialized"));return}let t=new Writable({write(o,c,I){s.write(o,N=>I(N??void 0));},final(o){try{let c=dehydrate(i);d=JSON.stringify(c);}finally{i.clear();}o(),m();}});t.on("error",o=>{s.destroy(o),e(o);}),s.on("error",e),a$2.pipe(t);});return {sessionState:JSON.stringify({session:l}),pipe:_,getQueryState:()=>{if(d===null)throw new Error("getQueryState() called before stream finished");return d}}}export{X as renderSsrTreeStream};//# sourceMappingURL=render-CBIFY4DG.js.map
|
|
2
|
+
//# sourceMappingURL=render-CBIFY4DG.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/ssr/render.tsx"],"names":["sessionResolver","ctx","getSsrContext","_parseSessionUser","configResolver","key","ensureSsrResolversInstalled","_setSsrSessionResolver","_setSsrConfigResolver","renderSsrTreeStream","options","callContext","loadingElement","routesElement","router","location","onShellReady","onError","sessionPayload","callInProcessMethod","queryClient","QueryClient","routedTree","tree","jsx","AppProvider","ModelenceQueryProvider","streamRef","resolve","reject","runWithSsrContext","stream","renderToPipeableStream","error","queryStateJson","pipe","destination","passthrough","Writable","chunk","_encoding","callback","err","dehydratedState","dehydrate"],"mappings":"+ZAkBA,IAAMA,CAAAA,CAAkB,IAAM,CAC5B,IAAMC,CAAAA,CAAMC,CAAAA,EAAc,CAC1B,OAAKD,EAGEE,CAAAA,CAAkBF,CAAAA,CAAI,OAAA,CAAQ,IAAI,EAFhC,IAGX,CAAA,CAEMG,EAAkBC,CAAAA,EAAmB,CACzC,IAAMJ,CAAAA,CAAMC,CAAAA,EAAc,CAC1B,GAAKD,EAGL,OAAOA,CAAAA,CAAI,OAAA,CAAQ,OAAA,CAAQI,CAAG,CAAA,EAAG,KACnC,CAAA,CAEA,SAASC,GAA8B,CACrCC,CAAAA,CAAuBP,CAAe,CAAA,CACtCQ,EAAsBJ,CAAc,EACtC,CA0BA,eAAsBK,EAAoBC,CAAAA,CAAqD,CAC7F,GAAM,CAAE,YAAAC,GAAAA,CAAa,cAAA,CAAAC,CAAAA,CAAgB,aAAA,CAAAC,EAAe,MAAA,CAAAC,CAAAA,CAAQ,SAAAC,CAAAA,CAAU,YAAA,CAAAC,EAAc,OAAA,CAAAC,GAAQ,CAAA,CAC1FP,CAAAA,CAEFJ,GAA4B,CAE5B,IAAMY,CAAAA,CAAiB,MAAMC,EAC3B,sBAAA,CACA,EAAC,CACDR,GACF,EAEMS,CAAAA,CAAc,IAAIC,WAAAA,CAAY,CAClC,eAAgB,CACd,OAAA,CAAS,CACP,KAAA,CAAO,MACP,MAAA,CAAQ,CACV,CACF,CACF,CAAC,CAAA,CAEKC,CAAAA,CAAaR,CAAAA,CAASA,CAAAA,CAAO,CAAE,QAAA,CAAUD,CAAAA,CAAe,SAAAE,CAAS,CAAC,EAAIF,CAAAA,CACtEU,CAAAA,CACJC,GAAAA,CAACC,GAAAA,CAAA,CAAY,cAAA,CAAgBb,CAAAA,CAC3B,QAAA,CAAAY,GAAAA,CAACE,EAAA,CAAuB,MAAA,CAAQN,CAAAA,CAAc,QAAA,CAAAE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,CACTb,CAAAA,GACF,CACF,CAAC,CAAA,CAEDS,CAAAA,CAAY,EAAA,CAAG,OAAA,CAAUK,GAAQ,CAC/BN,CAAAA,CAAY,QAAQM,CAAG,CAAA,CACvBb,EAAOa,CAAG,EACZ,CAAC,CAAA,CACDN,EAAY,EAAA,CAAG,OAAA,CAASP,CAAM,CAAA,CAE9BF,IAAU,IAAA,CAAKU,CAAW,EAC5B,CAAC,EAGH,OAAO,CACL,YAAA,CAAc,IAAA,CAAK,UAAU,CAAE,OAAA,CAASnB,CAAe,CAAC,EACxD,IAAA,CAAAiB,CAAAA,CACA,aAAA,CAAe,IAAM,CACnB,GAAID,CAAAA,GAAmB,IAAA,CACrB,MAAM,IAAI,KAAA,CAAM,+CAA+C,EAEjE,OAAOA,CACT,CACF,CACF","file":"render-CBIFY4DG.js","sourcesContent":["import React from 'react';\nimport { renderToPipeableStream, type PipeableStream } from 'react-dom/server';\nimport { Writable } from 'node:stream';\nimport { QueryClient, dehydrate, type DehydratedState } from '@tanstack/react-query';\nimport { AppProvider } from '../client/AppProvider';\nimport { ModelenceQueryProvider } from '../client/queryProvider';\nimport { getSsrContext, runWithSsrContext } from './context';\nimport { callInProcessMethod } from './callInProcess';\nimport type { Context } from '../methods/types';\nimport {\n _parseSessionUser,\n _setSsrSessionResolver,\n type SessionInitPayload,\n} from '../client/session';\nimport { _setSsrConfigResolver } from '../config/client';\nimport type { ConfigKey, Configs } from '../config/types';\nimport type { SsrRouter } from '../client/renderApp';\n\nconst sessionResolver = () => {\n const ctx = getSsrContext();\n if (!ctx) {\n return null;\n }\n return _parseSessionUser(ctx.session.user);\n};\n\nconst configResolver = (key: ConfigKey) => {\n const ctx = getSsrContext();\n if (!ctx) {\n return undefined;\n }\n return ctx.session.configs[key]?.value;\n};\n\nfunction ensureSsrResolversInstalled() {\n _setSsrSessionResolver(sessionResolver);\n _setSsrConfigResolver(configResolver);\n}\n\nexport type SsrRenderOptions = {\n callContext: Context;\n loadingElement: React.ReactNode;\n routesElement: React.ReactNode;\n router?: SsrRouter;\n location?: string;\n};\n\nexport type SsrStreamHandle = {\n /** Session bootstrap payload — inline before the shell flushes. */\n sessionState: string;\n /** Pipe React's HTML into `destination`. Resolves when streaming finishes. */\n pipe: (destination: Writable) => Promise<void>;\n /** Dehydrated query state. Only call after `pipe()` resolves. */\n getQueryState: () => string;\n};\n\nexport type SsrStreamOptions = SsrRenderOptions & {\n /** Fires when the shell is flushed; caller writes prelude + state here. */\n onShellReady?: () => void;\n /** Non-fatal SSR errors (Suspense fallbacks, etc.). */\n onError?: (error: unknown) => void;\n};\n\nexport async function renderSsrTreeStream(options: SsrStreamOptions): Promise<SsrStreamHandle> {\n const { callContext, loadingElement, routesElement, router, location, onShellReady, onError } =\n options;\n\n ensureSsrResolversInstalled();\n\n const sessionPayload = await callInProcessMethod<SessionInitPayload>(\n '_system.session.init',\n {},\n callContext\n );\n\n const queryClient = new QueryClient({\n defaultOptions: {\n queries: {\n retry: false,\n gcTime: 0,\n },\n },\n });\n\n const routedTree = router ? router({ children: routesElement, location }) : routesElement;\n const tree = (\n <AppProvider loadingElement={loadingElement}>\n <ModelenceQueryProvider client={queryClient}>{routedTree}</ModelenceQueryProvider>\n </AppProvider>\n );\n\n let streamRef: PipeableStream | null = null;\n // Resolves with the stream once React renders above-fallback content;\n // rejects on shell errors so the caller can fall back to a static response.\n const shellReady = new Promise<PipeableStream>((resolve, reject) => {\n // Run the render inside the SSR context so components can resolve\n // session/config/query state from the per-request scope.\n runWithSsrContext(\n {\n callContext,\n queryClient,\n session: {\n user: sessionPayload.user,\n configs: (sessionPayload.configs as Configs) ?? {},\n },\n },\n () => {\n const stream = renderToPipeableStream(tree, {\n onShellReady() {\n streamRef = stream;\n onShellReady?.();\n resolve(stream);\n },\n onShellError(error) {\n reject(error);\n },\n onError(error) {\n onError?.(error);\n },\n });\n return stream;\n }\n );\n });\n\n // Await so shell errors surface before the caller starts piping.\n await shellReady;\n\n let queryStateJson: string | null = null;\n\n const pipe = (destination: Writable): Promise<void> => {\n return new Promise((resolve, reject) => {\n if (!streamRef) {\n reject(new Error('SSR stream was not initialized'));\n return;\n }\n\n // react-dom calls `destination.end()` when done. The caller still needs\n // to write the epilogue + query state, so wrap with a passthrough whose\n // `final()` resolves the pipe promise without closing the response.\n const passthrough = new Writable({\n write(chunk, _encoding, callback) {\n destination.write(chunk, (err) => callback(err ?? undefined));\n },\n final(callback) {\n try {\n const dehydratedState: DehydratedState = dehydrate(queryClient);\n queryStateJson = JSON.stringify(dehydratedState);\n } finally {\n queryClient.clear();\n }\n callback();\n resolve();\n },\n });\n\n passthrough.on('error', (err) => {\n destination.destroy(err);\n reject(err);\n });\n destination.on('error', reject);\n\n streamRef.pipe(passthrough);\n });\n };\n\n return {\n sessionState: JSON.stringify({ session: sessionPayload }),\n pipe,\n getQueryState: () => {\n if (queryStateJson === null) {\n throw new Error('getQueryState() called before stream finished');\n }\n return queryStateJson;\n },\n };\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":[],"names":[],"mappings":"","file":"renderApp-
|
|
1
|
+
{"version":3,"sources":[],"names":[],"mappings":"","file":"renderApp-J347DR2B.js"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
export{g as getCallContext,f as startServer}from'./chunk-5XIH7C7R.js';import'./chunk-LCGVOLVA.js';import'./chunk-YOJ4ZP5D.js';import'./chunk-MIRF7FP3.js';import'./chunk-VF4RU7MF.js';import'./chunk-5M6FUMUK.js';import'./chunk-DO5TZLF5.js';//# sourceMappingURL=server-NBPRZYSI.js.map
|
|
2
|
+
//# sourceMappingURL=server-NBPRZYSI.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":[],"names":[],"mappings":"","file":"server-
|
|
1
|
+
{"version":3,"sources":[],"names":[],"mappings":"","file":"server-NBPRZYSI.js"}
|