modelence 0.21.0-ml.dev.1 → 0.21.0-ml.dev.2
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-L4HA6WDS.js → chunk-3RMUZGFT.js} +2 -2
- package/dist/chunk-3RMUZGFT.js.map +1 -0
- package/dist/chunk-5UXY2NRZ.js +2 -0
- package/dist/{chunk-OMZEJGMN.js.map → chunk-5UXY2NRZ.js.map} +1 -1
- package/dist/{chunk-3MACQTB3.js → chunk-7DT2YQTG.js} +3 -3
- package/dist/{chunk-3MACQTB3.js.map → chunk-7DT2YQTG.js.map} +1 -1
- package/dist/chunk-GISIHWCC.js +2 -0
- package/dist/{chunk-CIPGQ6HR.js.map → chunk-GISIHWCC.js.map} +1 -1
- package/dist/{chunk-AIQUY53H.js → chunk-LVB7YU4P.js} +3 -3
- package/dist/chunk-LVB7YU4P.js.map +1 -0
- package/dist/{chunk-NPAFMBRP.js → chunk-P2W2XOKE.js} +2 -2
- package/dist/{chunk-NPAFMBRP.js.map → chunk-P2W2XOKE.js.map} +1 -1
- package/dist/chunk-T4G5RAOK.js +37 -0
- package/dist/chunk-T4G5RAOK.js.map +1 -0
- package/dist/client.d.ts +29 -1
- package/dist/client.js +1 -1
- package/dist/{package-TMVJXVUQ.js → package-SYXH7HQF.js} +2 -2
- package/dist/{package-TMVJXVUQ.js.map → package-SYXH7HQF.js.map} +1 -1
- package/dist/{render-6BXZA746.js → render-HDPCEI2O.js} +2 -2
- package/dist/{render-6BXZA746.js.map → render-HDPCEI2O.js.map} +1 -1
- package/dist/renderApp-Y3OJU4PO.js +2 -0
- package/dist/{renderApp-GNV3UFAD.js.map → renderApp-Y3OJU4PO.js.map} +1 -1
- package/dist/server-WAXWRUOY.js +2 -0
- package/dist/{server-LJUY2OWZ.js.map → server-WAXWRUOY.js.map} +1 -1
- package/dist/server.d.ts +8 -0
- package/dist/server.js +1 -1
- package/dist/transport-UBIBRQF5.js +2 -0
- package/dist/{transport-RAUEYIZV.js.map → transport-UBIBRQF5.js.map} +1 -1
- package/package.json +1 -1
- package/dist/chunk-AIQUY53H.js.map +0 -1
- package/dist/chunk-CIPGQ6HR.js +0 -2
- package/dist/chunk-L4HA6WDS.js.map +0 -1
- package/dist/chunk-OMZEJGMN.js +0 -2
- package/dist/chunk-WAYG54Z2.js +0 -35
- package/dist/chunk-WAYG54Z2.js.map +0 -1
- package/dist/renderApp-GNV3UFAD.js +0 -2
- package/dist/server-LJUY2OWZ.js +0 -2
- package/dist/transport-RAUEYIZV.js +0 -2
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/app/module.ts","../src/data/schemaSerializer.ts","../src/data/schemaDefaults.ts","../src/data/store.ts","../src/data/types.ts","../src/auth/session.ts","../src/auth/db.ts","../src/auth/role.ts","../src/auth/index.ts","../src/live-query/context.ts","../src/utils/index.ts","../src/live-query/handlers.ts","../src/methods/index.ts"],"names":["Module","name","stores","queries","mutations","routes","cronJobs","configSchema","rateLimits","channels","key","getConfig","serializeZodSchema","zodType","def","shape","serializedShape","value","effectsDef","serializeModelSchema","schema","serialized","item","isDocumentRecord","isZodType","getZodDef","getWrappedZodType","getZodDefaultValue","wrappedType","applyDefaultsToZodValue","applyDefaultsToModelSchema","applyDefaultsToSchemaDefinition","schemaDefinition","index","document","result","currentValue","defaultValue","COMPARABLE_INDEX_OPTION_FIELDS","hasModelencePrefix","getComparableIndexOptions","options","field","isSameIndexKey","left","right","leftEntries","rightEntries","leftField","leftDirection","rightField","rightDirection","isDeepStrictEqual","isSameIndexDefinition","existing","desired","getIndexKeySignature","direction","listIndexes","collection","error","MongoError","generateAutoIndexName","normalizeIndexName","autoName","Store","_Store","current","config","tail","extendedSchema","extendedIndexes","extendedSearchIndexes","combinedMethods","extendedStore","client","mode","shouldDropIndexes","shouldCreateIndexes","existingIndexes","indexByName","indexNamesByKey","droppedIndexNames","addIndexToLookup","existingIndex","keySignature","names","removeIndexFromLookup","indexName","dropIndexIfNeeded","currentIndexNames","idx","orphanedIndexes","existingIdx","orphanedIndex","requiresDropBeforeCreate","existingByName","existingNamesForKey","existingName","alignedIndex","searchIndex","selector","ObjectId","query","errorHandler","cursor","id","idSelector","docWithId","documents","update","replacement","filter","f","pipeline","operations","oldName","db","embedding","numCandidates","limit","projection","dimensions","similarity","schemaString","z","schemaNumber","schemaDate","schemaBoolean","schemaArray","schemaObject","schemaEnum","_collection","_schema","linkNoncesCollection","issueLinkNonce","userId","nonce","randomBytes","time","consumeLinkNonce","entry","sessionsCollection","obtainSession","authToken","existingSession","createSession","setSessionUser","clearSessionUser","invalidateAllUserSessions","now","expiresAt","processSessionHeartbeat","session","newExpiresAt","setAuthTokenCookie","res","clearAuthTokenCookie","session_default","args","user","getPublicConfigs","usersCollection","dbDisposableEmailDomains","emailVerificationTokensCollection","resetPasswordTokensCollection","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":"2RA0CO,IAAMA,CAAAA,CAAN,KAKL,CAqCA,WAAA,CACEC,CAAAA,CACA,CACE,MAAA,CAAAC,CAAAA,CAAS,EAAC,CACV,OAAA,CAAAC,CAAAA,CAAU,EAAC,CACX,SAAA,CAAAC,CAAAA,CAAY,EAAC,CACb,MAAA,CAAAC,CAAAA,C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C5B,CAAC,CAAA,CAEG5H,CAAAA,CACJ,GAAI,CAKF,GAJA4I,EAAc0B,CAAAA,CAAQ,KAAA,CAAOL,CAAAA,CAAO,WAAW,CAAA,CAE/CjK,CAAAA,CAAS,MAAM8L,CAAAA,CAAQlE,CAAAA,CAAM0C,CAAO,CAAA,CAEhC,EAAEtK,CAAAA,YAAkBoJ,CAAAA,CAAAA,CACtB,MAAM,IAAI,MACR,CAAA,wBAAA,EAA2BtL,CAAI,CAAA,2GAAA,CACjC,CAEJ,CAAA,MAAS2D,CAAAA,CAAO,CACd,MAAAwK,EAAY,GAAA,CAAI,OAAO,CAAA,CACjBxK,CACR,CAEA,OAAAwK,CAAAA,CAAY,GAAA,GAELjM,CACT","file":"chunk-LVB7YU4P.js","sourcesContent":["import { ConfigSchema, ConfigParams, ValueType } from '../config/types';\nimport { getConfig as _getConfig } from '../config/server';\nimport { CronJobInputParams } from '../cron/types';\nimport { Store } from '../data/store';\nimport { AnyMethodShape } from '../methods/types';\nimport { RouteDefinition } from '../routes/types';\nimport { RateLimitRule } from '../rate-limit/types';\nimport { ServerChannel } from '@/websocket/serverChannel';\n\n/** Array of Store instances that will be provisioned when the module is loaded */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype Stores = Store<any, any>[];\n\n/** Record of query methods that can be called from the client */\ntype Queries = Record<string, AnyMethodShape>;\n\n/** Record of mutation methods that can be called from the client */\ntype Mutations = Record<string, AnyMethodShape>;\n\n/**\n * The Module class is a core building block of a Modelence application that encapsulates related functionality.\n * Modules can contain stores, queries, mutations, routes, cron jobs and configurations.\n *\n * @category Module\n *\n * @example\n * ```ts\n * const todoModule = new Module('todo', {\n * stores: [dbTodos],\n * queries: {\n * async getAll() {\n * // Fetch and return all Todo items\n * }\n * },\n * mutations: {\n * async create({ title }, { user }) {\n * // Create a new Todo item\n * }\n * }\n * });\n * ```\n */\nexport class Module<\n TName extends string = string,\n TSchema extends Record<string, ConfigParams> = ConfigSchema,\n TQueries extends Queries = Queries,\n TMutations extends Mutations = Mutations,\n> {\n /** @internal */\n public readonly name: TName;\n\n /** @internal */\n public readonly stores: Stores;\n\n /** @internal */\n public readonly queries: TQueries;\n\n /** @internal */\n public readonly mutations: TMutations;\n\n /** @internal */\n public readonly routes: RouteDefinition[];\n\n /** @internal */\n public readonly cronJobs: Record<string, CronJobInputParams>;\n\n /** @internal */\n public readonly configSchema: TSchema;\n\n /** @internal */\n public rateLimits: RateLimitRule[];\n\n /** @internal */\n public readonly channels: ServerChannel[];\n\n /**\n * Creates a new Module instance\n *\n * @param name - The unique name of the module.\n * This name is used to namespace queries, mutations,\n * cron jobs and configuration values with a prefix (e.g. \"todo.create\")\n *\n * @param options - Module configuration options\n */\n constructor(\n name: TName,\n {\n stores = [],\n queries = {} as TQueries,\n mutations = {} as TMutations,\n routes = [],\n cronJobs = {},\n configSchema = {} as TSchema,\n rateLimits = [],\n channels = [],\n }: {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n stores?: Store<any, any>[];\n queries?: TQueries;\n mutations?: TMutations;\n routes?: RouteDefinition[];\n cronJobs?: Record<string, CronJobInputParams>;\n configSchema?: TSchema;\n rateLimits?: RateLimitRule[];\n channels?: ServerChannel[];\n } = {}\n ) {\n this.name = name;\n this.stores = stores;\n this.queries = queries;\n this.mutations = mutations;\n this.routes = routes;\n this.cronJobs = cronJobs;\n this.configSchema = configSchema;\n this.rateLimits = rateLimits;\n this.channels = channels;\n }\n\n /**\n * Retrieves a typed configuration value for this module.\n * The return type is inferred from the schema — no casts needed.\n *\n * @example\n * ```ts\n * const myModule = new Module('payments', {\n * configSchema: {\n * apiKey: { type: 'secret', default: '', isPublic: false },\n * maxRetries: { type: 'number', default: 3, isPublic: false },\n * },\n * mutations: {\n * async charge({ amount }) {\n * const apiKey = myModule.getConfig('apiKey'); // string\n * const maxRetries = myModule.getConfig('maxRetries'); // number\n * },\n * },\n * });\n * ```\n */\n getConfig<K extends keyof TSchema & string>(key: K): ValueType<TSchema[K]['type']> {\n return _getConfig(`${this.name}.${key}`) as ValueType<TSchema[K]['type']>;\n }\n}\n","import { z } from 'zod';\nimport { ModelSchema } from './types';\n\ntype ObjectTypeDefinition = {\n [key: string]: z.ZodType | ObjectTypeDefinition | Array<z.ZodType | ObjectTypeDefinition>;\n};\n\nexport interface SerializedModelSchema {\n [key: string]:\n | SerializedSchema\n | (SerializedSchema | SerializedModelSchema)[]\n | SerializedModelSchema\n | 'v2';\n}\n\n// Type guards for Zod schema types\ntype ZodDefWithTypeName = {\n typeName: z.ZodFirstPartyTypeKind;\n};\n\ntype ZodArrayDef = ZodDefWithTypeName & {\n type: z.ZodType;\n};\n\ntype ZodObjectDef = ZodDefWithTypeName & {\n shape: () => Record<string, z.ZodType>;\n};\n\ntype ZodOptionalDef = ZodDefWithTypeName & {\n innerType: z.ZodType;\n};\n\ntype ZodNullableDef = ZodDefWithTypeName & {\n innerType: z.ZodType;\n};\n\ntype ZodEnumDef = ZodDefWithTypeName & {\n values: readonly [string, ...string[]];\n};\n\ntype ZodUnionDef = ZodDefWithTypeName & {\n options: readonly [z.ZodType, z.ZodType, ...z.ZodType[]];\n};\n\ntype ZodEffectsDef = ZodDefWithTypeName & {\n schema: z.ZodType;\n effect: { type: 'refinement' | 'transform' | 'preprocess' };\n description?: string;\n};\n\ntype BaseSerializedSchema =\n | { type: 'string' }\n | { type: 'number' }\n | { type: 'boolean' }\n | { type: 'date' }\n | { type: 'array'; items: SerializedSchema }\n | { type: 'object'; items: Record<string, SerializedSchema> }\n | { type: 'enum'; items: readonly string[] }\n | { type: 'union'; items: SerializedSchema[] }\n | { type: 'custom'; typeName: string };\n\ntype SerializedSchema = BaseSerializedSchema | (BaseSerializedSchema & { optional: true });\n\n/**\n * Serializes a Zod schema to a JSON-serializable format\n */\nfunction serializeZodSchema(zodType: z.ZodType): SerializedSchema {\n const def = zodType._def as ZodDefWithTypeName;\n\n if (def.typeName === 'ZodString') {\n return { type: 'string' };\n }\n if (def.typeName === 'ZodNumber') {\n return { type: 'number' };\n }\n if (def.typeName === 'ZodBoolean') {\n return { type: 'boolean' };\n }\n if (def.typeName === 'ZodDate') {\n return { type: 'date' };\n }\n if (def.typeName === 'ZodArray') {\n const arrayDef = def as ZodArrayDef;\n return {\n type: 'array',\n items: serializeZodSchema(arrayDef.type),\n };\n }\n if (def.typeName === 'ZodObject') {\n const objectDef = def as ZodObjectDef;\n const shape = objectDef.shape();\n const serializedShape: Record<string, SerializedSchema> = {};\n for (const [key, value] of Object.entries(shape)) {\n serializedShape[key] = serializeZodSchema(value as z.ZodType);\n }\n return {\n type: 'object',\n items: serializedShape,\n };\n }\n if (def.typeName === 'ZodOptional') {\n const optionalDef = def as ZodOptionalDef;\n return {\n ...serializeZodSchema(optionalDef.innerType),\n optional: true,\n };\n }\n if (def.typeName === 'ZodNullable') {\n const nullableDef = def as ZodNullableDef;\n return {\n ...serializeZodSchema(nullableDef.innerType),\n optional: true,\n };\n }\n if (def.typeName === 'ZodEnum') {\n const enumDef = def as ZodEnumDef;\n return {\n type: 'enum',\n items: enumDef.values,\n };\n }\n if (def.typeName === 'ZodUnion') {\n const unionDef = def as ZodUnionDef;\n return {\n type: 'union',\n items: unionDef.options.map(serializeZodSchema),\n };\n }\n if (def.typeName === 'ZodEffects') {\n // ZodEffects is used for z.instanceof(ObjectId), z.refine(), etc.\n const effectsDef = def as ZodEffectsDef;\n\n // Check description for custom types\n if (effectsDef.description) {\n return { type: 'custom', typeName: effectsDef.description } as SerializedSchema;\n }\n\n // For other effects, try to serialize the underlying schema\n return serializeZodSchema(effectsDef.schema);\n }\n\n // For custom types like ObjectId, ref, etc.\n return { type: 'custom', typeName: def.typeName };\n}\n\n/**\n * Serializes a model schema to a JSON-serializable format\n */\nexport function serializeModelSchema(schema: ModelSchema): SerializedModelSchema {\n const serialized: SerializedModelSchema = {};\n\n for (const [key, value] of Object.entries(schema)) {\n if (Array.isArray(value)) {\n // Handle array of schema definitions\n serialized[key] = value.map((item) => {\n if (typeof item === 'object' && '_def' in item) {\n return serializeZodSchema(item as z.ZodType);\n }\n return serializeModelSchema(item as ObjectTypeDefinition);\n });\n } else if (typeof value === 'object' && '_def' in value) {\n // It's a Zod type\n serialized[key] = serializeZodSchema(value as z.ZodType);\n } else {\n // It's a nested object definition\n serialized[key] = serializeModelSchema(value as ObjectTypeDefinition);\n }\n }\n\n return serialized;\n}\n","import { Document } from 'mongodb';\nimport { z } from 'zod';\n\ntype ZodDefWithTypeName = {\n typeName: string;\n};\n\ntype ZodWrapperDef = ZodDefWithTypeName & {\n innerType?: z.ZodType;\n schema?: z.ZodType;\n type?: z.ZodType;\n out?: z.ZodType;\n};\n\ntype ZodDefaultDef = ZodWrapperDef & {\n defaultValue: () => unknown;\n};\n\ntype ZodObjectDef = ZodDefWithTypeName & {\n shape: () => Record<string, z.ZodType>;\n};\n\ntype ZodArrayDef = ZodDefWithTypeName & {\n type: z.ZodType;\n};\n\nconst isDocumentRecord = (value: unknown): value is Document =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n\nconst isZodType = (value: unknown): value is z.ZodType =>\n isDocumentRecord(value) && '_def' in value;\n\nconst getZodDef = (zodType: z.ZodType): ZodDefWithTypeName => zodType._def as ZodDefWithTypeName;\n\nconst getWrappedZodType = (zodType: z.ZodType): z.ZodType | undefined => {\n const def = getZodDef(zodType) as ZodWrapperDef;\n\n if (\n def.typeName === 'ZodOptional' ||\n def.typeName === 'ZodNullable' ||\n def.typeName === 'ZodDefault' ||\n def.typeName === 'ZodCatch' ||\n def.typeName === 'ZodReadonly'\n ) {\n return def.innerType;\n }\n\n if (def.typeName === 'ZodEffects') {\n return def.schema;\n }\n\n if (def.typeName === 'ZodBranded') {\n return def.type;\n }\n\n if (def.typeName === 'ZodPipeline') {\n return def.out;\n }\n\n return undefined;\n};\n\nconst getZodDefaultValue = (zodType: z.ZodType): { hasDefault: boolean; value?: unknown } => {\n const def = getZodDef(zodType);\n\n if (def.typeName === 'ZodDefault') {\n return {\n hasDefault: true,\n value: (def as ZodDefaultDef).defaultValue(),\n };\n }\n\n const wrappedType = getWrappedZodType(zodType);\n if (wrappedType) {\n return getZodDefaultValue(wrappedType);\n }\n\n return { hasDefault: false };\n};\n\nconst applyDefaultsToZodValue = (zodType: z.ZodType, value: unknown): unknown => {\n const def = getZodDef(zodType);\n\n if (def.typeName === 'ZodObject' && isDocumentRecord(value)) {\n return applyDefaultsToModelSchema((def as ZodObjectDef).shape(), value);\n }\n\n if (def.typeName === 'ZodArray' && Array.isArray(value)) {\n return value.map((item) => applyDefaultsToZodValue((def as ZodArrayDef).type, item));\n }\n\n const wrappedType = getWrappedZodType(zodType);\n if (wrappedType) {\n return applyDefaultsToZodValue(wrappedType, value);\n }\n\n return value;\n};\n\nconst applyDefaultsToSchemaDefinition = (schemaDefinition: unknown, value: unknown): unknown => {\n if (isZodType(schemaDefinition)) {\n return applyDefaultsToZodValue(schemaDefinition, value);\n }\n\n if (Array.isArray(schemaDefinition) && Array.isArray(value)) {\n if (schemaDefinition.length === 1) {\n return value.map((item) => applyDefaultsToSchemaDefinition(schemaDefinition[0], item));\n }\n\n return value.map((item, index) =>\n applyDefaultsToSchemaDefinition(schemaDefinition[index], item)\n );\n }\n\n if (isDocumentRecord(schemaDefinition) && isDocumentRecord(value)) {\n return applyDefaultsToModelSchema(schemaDefinition, value);\n }\n\n return value;\n};\n\nexport const applyDefaultsToModelSchema = (\n schema: Record<string, unknown>,\n document: Document\n): Document => {\n const result: Document = { ...document };\n\n for (const [key, schemaDefinition] of Object.entries(schema)) {\n const currentValue = result[key];\n\n if (currentValue === undefined) {\n if (isZodType(schemaDefinition)) {\n const defaultValue = getZodDefaultValue(schemaDefinition);\n if (defaultValue.hasDefault) {\n result[key] = applyDefaultsToSchemaDefinition(schemaDefinition, defaultValue.value);\n }\n }\n continue;\n }\n\n result[key] = applyDefaultsToSchemaDefinition(schemaDefinition, currentValue);\n }\n\n return result;\n};\n","import { isDeepStrictEqual } from 'node:util';\n\nimport {\n AggregateOptions,\n AggregationCursor,\n Collection,\n DeleteResult,\n Document,\n IndexDescription,\n InsertOneResult,\n MongoClient,\n UpdateResult,\n Filter,\n WithId,\n WithoutId,\n OptionalUnlessRequiredId,\n FindOptions,\n UpdateFilter,\n ObjectId,\n BulkWriteResult,\n AnyBulkWriteOperation,\n InsertManyResult,\n ClientSession,\n SearchIndexDescription,\n MongoError,\n FilterOperators,\n SortDirection,\n FindOneAndUpdateOptions,\n FindOneAndDeleteOptions,\n FindOneAndReplaceOptions,\n ReplaceOptions,\n ChangeStream,\n ChangeStreamOptions,\n DistinctOptions,\n} from 'mongodb';\nimport { ModelSchema, InferDocumentType } from './types';\nimport { serializeModelSchema } from './schemaSerializer';\nimport { applyDefaultsToModelSchema } from './schemaDefaults';\n\n/**\n * Top-level query operators (logical and evaluation) - custom version without Document index signature\n * Based on MongoDB's RootFilterOperators but without the [key: string]: any from Document\n * @internal\n */\ntype StrictRootFilterOperators<TSchema> = {\n $and?: TypedFilter<TSchema>[];\n $or?: TypedFilter<TSchema>[];\n $nor?: TypedFilter<TSchema>[];\n $not?: TypedFilter<TSchema>;\n $text?: {\n $search: string;\n $language?: string;\n $caseSensitive?: boolean;\n $diacriticSensitive?: boolean;\n };\n\n $where?: string | ((this: TSchema) => boolean);\n $comment?: string | Document;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n $expr?: any;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n $jsonSchema?: any;\n};\n\n/**\n * Helper type to extract array element type\n * @internal\n */\ntype ArrayElement<T> = T extends (infer E)[] ? E : never;\ntype Flatten<T> = T extends ReadonlyArray<infer E> ? E : T;\n\n/**\n * Helper type for $in/$nin that accepts any array/tuple where elements are assignable to T\n * This solves the issue where TypeScript infers ['a', 'b'] as a tuple instead of ('a' | 'b')[]\n * and where Array<Union> gets distributed into Union1[] | Union2[] | ...\n * We wrap the Exclude in a tuple check to prevent distribution\n * @internal\n */\ntype NonUndefined<T> = T extends undefined ? never : T;\ntype ArrayLikeOfUnion<T> = [NonUndefined<T>] extends [never]\n ? never\n : ReadonlyArray<NonUndefined<T>> | Array<NonUndefined<T>>;\n\n/**\n * Enhanced FilterOperators that fixes $in and $nin to properly accept arrays of union types\n * MongoDB's native FilterOperators has issues with union types in $in/$nin arrays\n * because TypeScript distributes Array<Union> into Array1 | Array2 | ...\n * @internal\n */\ntype EnhancedFilterOperators<T> = Omit<FilterOperators<T>, '$in' | '$nin'> & {\n $in?: ArrayLikeOfUnion<T>;\n $nin?: ArrayLikeOfUnion<T>;\n};\n\ntype ExistingIndex = Document & {\n key?: Document;\n name?: string;\n};\n\ntype TypedFieldSelection<T, TValue> = {\n [K in keyof WithId<T> & string]?: TValue;\n} & {\n [key: `${string}.${string}`]: TValue;\n};\n\ntype ProjectionValue =\n | 0\n | 1\n | boolean\n | { $meta: string }\n | { $slice: number | [number, number] }\n | { $elemMatch: Document };\n\ntype TypedSort<T> = TypedFieldSelection<T, SortDirection>;\ntype TypedProjection<T> = TypedFieldSelection<T, ProjectionValue>;\n\ntype FetchOptions<T> = {\n sort?: TypedSort<T>;\n limit?: number;\n skip?: number;\n projection?: TypedProjection<T>;\n};\n\nexport type IndexCreationMode = 'blocking' | 'background';\nexport type IndexReconcileMode = 'full' | 'drop-only' | 'create-only';\n\nconst COMPARABLE_INDEX_OPTION_FIELDS = [\n 'background',\n 'bits',\n 'bucketSize',\n 'collation',\n 'default_language',\n 'expireAfterSeconds',\n 'hidden',\n 'language_override',\n 'max',\n 'min',\n 'partialFilterExpression',\n 'sparse',\n 'storageEngine',\n 'textIndexVersion',\n 'unique',\n 'weights',\n 'wildcardProjection',\n '2dsphereIndexVersion',\n] as const;\n\nconst isDocumentRecord = (value: unknown): value is Document =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n\nconst hasModelencePrefix = (name: string): boolean => name.startsWith('_modelence_');\n\nconst getComparableIndexOptions = (index: ExistingIndex | IndexDescription): Document => {\n const options: Document = {};\n\n for (const field of COMPARABLE_INDEX_OPTION_FIELDS) {\n const value = (index as Document)[field];\n if (value !== undefined) {\n options[field] = value;\n }\n }\n\n return options;\n};\n\n/**\n * MongoDB index key order is significant (e.g. { a: 1, b: 1 } !== { b: 1, a: 1 }).\n */\nconst isSameIndexKey = (left: unknown, right: unknown): boolean => {\n if (!isDocumentRecord(left) || !isDocumentRecord(right)) {\n return false;\n }\n\n const leftEntries = Object.entries(left);\n const rightEntries = Object.entries(right);\n\n if (leftEntries.length !== rightEntries.length) {\n return false;\n }\n\n return leftEntries.every(([leftField, leftDirection], index) => {\n const [rightField, rightDirection] = rightEntries[index] || [];\n return leftField === rightField && isDeepStrictEqual(leftDirection, rightDirection);\n });\n};\n\nconst isSameIndexDefinition = (existing: ExistingIndex, desired: IndexDescription): boolean => {\n if (!isSameIndexKey(existing.key, desired.key)) {\n return false;\n }\n\n return isDeepStrictEqual(getComparableIndexOptions(existing), getComparableIndexOptions(desired));\n};\n\nconst getIndexKeySignature = (key: unknown): string | null => {\n if (!isDocumentRecord(key)) {\n return null;\n }\n\n return Object.entries(key)\n .map(([field, direction]) => `${field}:${JSON.stringify(direction)}`)\n .join('|');\n};\n\n/**\n * Lists all indexes in a collection, returning an empty array if collection doesn't exist\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst listIndexes = async (collection: Collection<any>): Promise<Document[]> => {\n try {\n return await collection.listIndexes().toArray();\n } catch (error) {\n // If collection doesn't exist yet, return empty array\n // It will be created when we insert data or create indexes\n if (error instanceof MongoError && error.code === 26) {\n return [];\n }\n throw error;\n }\n};\n\n/**\n * Generates an auto-generated index name from the index keys\n * Mimics MongoDB's default naming: field1_direction1_field2_direction2\n */\nconst generateAutoIndexName = (key: Document): string => {\n return Object.entries(key)\n .map(([field, direction]) => `${field}_${direction}`)\n .join('_');\n};\n\n/**\n * Normalizes an index by ensuring it has a name with _modelence_ prefix\n */\nconst normalizeIndexName = (index: IndexDescription): IndexDescription => {\n if (index.name) {\n // If name is provided, add _modelence_ prefix if not already present\n const name = index.name.startsWith('_modelence_') ? index.name : `_modelence_${index.name}`;\n return { ...index, name };\n }\n\n // Auto-generate name with _modelence_ prefix\n const autoName = generateAutoIndexName(index.key);\n return { ...index, name: `_modelence_${autoName}` };\n};\n\n/**\n * Custom filter value type that handles array fields specially:\n * - For array fields: allows element type, full array type, or FilterOperators\n * - For non-array fields: allows exact type or FilterOperators\n * We use [T] to prevent distribution when T is a union type\n * @internal\n */\ntype FilterValue<T> = [T] extends [unknown[]]\n ? ArrayElement<T> | T | EnhancedFilterOperators<T>\n : [T] extends [never]\n ? never\n : T | EnhancedFilterOperators<[T] extends [never] ? never : T>;\n\n/**\n * Type-safe MongoDB filter that ensures only schema fields can be queried\n * while supporting all MongoDB query operators and dot notation for nested fields.\n *\n * This type combines:\n * - MongoDB's native `FilterOperators<T>` for field-level operators (comprehensive operator support)\n * - Custom `StrictRootFilterOperators<T>` for top-level operators without index signature\n * - Custom array field handling: allows passing single element when field is an array\n * - Custom restriction: only strings containing dots are allowed for nested field queries\n *\n * @example\n * ```ts\n * const dbUsers = new Store('users', {\n * schema: {\n * name: schema.string(),\n * age: schema.number(),\n * tags: schema.array(schema.string()),\n * collections: schema.array(schema.string()),\n * address: schema.object({\n * street: schema.string(),\n * city: schema.string(),\n * }),\n * },\n * indexes: []\n * });\n *\n * // ✅ Valid - field exists in schema\n * await dbUsers.findOne({ name: 'John' });\n *\n * // ✅ Valid - using MongoDB operators (from FilterOperators)\n * await dbUsers.findOne({ age: { $gt: 18 } });\n * await dbUsers.findOne({ tags: { $in: ['typescript', 'mongodb'] } });\n * await dbUsers.findOne({ $or: [{ name: 'John' }, { name: 'Jane' }] });\n *\n * // ✅ Valid - array field with single element (checks if array contains the element)\n * await dbUsers.findOne({ collections: 'users' });\n *\n * // ✅ Valid - dot notation for nested fields (must contain a dot)\n * await dbUsers.findOne({ 'address.city': 'New York' });\n * await dbUsers.findOne({ 'emails.0.address': 'test@example.com' });\n *\n * // ❌ TypeScript error - 'id' is not in schema and doesn't contain a dot\n * await dbUsers.findOne({ id: '123' });\n * ```\n */\nexport type TypedFilter<T> = {\n [K in keyof WithId<T>]?: FilterValue<WithId<T>[K]>;\n} & StrictRootFilterOperators<T> & {\n // Support for MongoDB dot notation (e.g., 'emails.address', 'profile.settings.theme')\n // Only strings containing dots are allowed, which provides better type safety\n // while still enabling MongoDB's nested field query syntax\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [K: `${string}.${string}`]: any;\n };\n\n/**\n * Helper type to preserve method types when extending a store.\n * Maps each method to work with the extended schema while preserving signatures.\n * @internal\n */\ntype PreserveMethodsForExtendedSchema<\n TBaseMethods extends Record<string, (...args: never[]) => unknown>,\n TExtendedSchema extends ModelSchema,\n> = {\n [K in keyof TBaseMethods]: TBaseMethods[K] extends (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this: any,\n ...args: infer Args\n ) => infer Return\n ? // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (this: WithId<InferDocumentType<TExtendedSchema>> & any, ...args: Args) => Return\n : never;\n};\n\n/**\n * Type-erased Store reference for chain traversal.\n * Chain members carry different TSchema/TMethods, so the generic\n * parameters must be erased. This alias contains the `any` in one place.\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyStore = Store<any, any>;\n\n/**\n * The Store class provides a type-safe interface for MongoDB collections with built-in schema validation and helper methods.\n *\n * @category Store\n * @typeParam TSchema - The document schema type\n * @typeParam TMethods - Custom methods that will be added to documents\n *\n * @example\n * ```ts\n * const dbTodos = new Store('todos', {\n * schema: {\n * title: schema.string(),\n * completed: schema.boolean(),\n * dueDate: schema.date().optional(),\n * userId: schema.userId(),\n * },\n * methods: {\n * isOverdue() {\n * return this.dueDate < new Date();\n * }\n * }\n * });\n * ```\n */\nexport class Store<\n TSchema extends ModelSchema,\n TMethods extends Record<\n string,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (this: WithId<InferDocumentType<TSchema>> & TMethods, ...args: any[]) => any\n >,\n> {\n /** @internal */\n readonly _type!: InferDocumentType<TSchema>;\n /** @internal */\n readonly _rawDoc!: WithId<this['_type']>;\n /** @internal */\n readonly _doc!: this['_rawDoc'] & TMethods;\n\n readonly Doc!: this['_doc'];\n\n private name: string;\n private readonly schema: TSchema;\n private readonly methods?: TMethods;\n private readonly indexes: IndexDescription[];\n private readonly searchIndexes: SearchIndexDescription[];\n private readonly indexCreationMode: IndexCreationMode;\n private collection?: Collection<this['_type']>;\n private client?: MongoClient;\n\n // Chain tracking for linear extension model\n private _chainParent: AnyStore | null = null;\n private _chainChild: AnyStore | null = null;\n\n /**\n * Creates a new Store instance\n *\n * @param name - The collection name in MongoDB\n * @param options - Store configuration (schema, indexes, methods, search indexes, and optional index creation mode)\n */\n constructor(\n name: string,\n options: {\n /** Document schema using Modelence schema types */\n schema: TSchema;\n /** Custom methods to add to documents */\n methods?: TMethods;\n /** MongoDB indexes to create */\n indexes: IndexDescription[];\n /** MongoDB Atlas Search */\n searchIndexes?: SearchIndexDescription[];\n /** Whether index creation should block startup or run in background (default: 'background') */\n indexCreationMode?: IndexCreationMode;\n }\n ) {\n this.name = name;\n this.schema = options.schema;\n this.methods = options.methods;\n // Normalize all indexes to have _modelence_ prefix\n this.indexes = options.indexes.map(normalizeIndexName);\n this.searchIndexes = options.searchIndexes || [];\n this.indexCreationMode = options.indexCreationMode ?? 'background';\n }\n\n getName() {\n return this.name;\n }\n\n getIndexCreationMode() {\n return this.indexCreationMode;\n }\n\n /** @internal */\n getSchema() {\n return this.schema;\n }\n\n /** @internal */\n getSerializedSchema() {\n return serializeModelSchema(this.schema);\n }\n\n /** @internal – normalized indexes (already have _modelence_ prefix) */\n getIndexes(): IndexDescription[] {\n return this.indexes;\n }\n\n /** @internal */\n getSearchIndexes(): SearchIndexDescription[] {\n return this.searchIndexes;\n }\n\n /** @internal – follows the chain to the latest extension */\n getChainTail(): AnyStore {\n let current: AnyStore = this;\n while (current._chainChild) {\n current = current._chainChild;\n }\n return current;\n }\n\n /** @internal – follows the chain back to the original store */\n getChainRoot(): AnyStore {\n let current: AnyStore = this;\n while (current._chainParent) {\n current = current._chainParent;\n }\n return current;\n }\n\n /**\n * Extends the store with additional schema fields, indexes, methods, and search indexes.\n * Returns a new Store instance with the extended schema and updated types.\n * Methods from the original store are preserved with updated type signatures.\n *\n * @param config - Additional schema fields, indexes, methods, search indexes, and optional index creation mode to add\n * @returns A new Store instance with the extended schema\n *\n * @example\n * ```ts\n * // Extend the users collection\n * export const dbUsers = baseUsersCollection.extend({\n * schema: {\n * firstName: schema.string(),\n * lastName: schema.string(),\n * companyId: schema.objectId().optional(),\n * },\n * indexes: [\n * { key: { companyId: 1 } },\n * { key: { lastName: 1, firstName: 1 } },\n * ],\n * methods: {\n * getFullName() {\n * return `${this.firstName} ${this.lastName}`;\n * }\n * }\n * });\n *\n * // Now fully typed with new fields\n * const user = await dbUsers.findOne({ firstName: 'John' });\n * console.log(user?.getFullName());\n * ```\n */\n extend<\n TExtendedSchema extends ModelSchema,\n TExtendedMethods extends Record<string, Function> = Record<string, never>,\n >(config: {\n schema?: TExtendedSchema;\n indexes?: IndexDescription[];\n methods?: TExtendedMethods;\n searchIndexes?: SearchIndexDescription[];\n /** Whether index creation should block startup or run in background */\n indexCreationMode?: IndexCreationMode;\n }): Store<\n TSchema & TExtendedSchema,\n PreserveMethodsForExtendedSchema<TMethods, TSchema & TExtendedSchema> & TExtendedMethods\n > {\n // Follow chain to the tail – extending always appends to the end\n const tail: AnyStore = this.getChainTail();\n\n if (this.client || tail.client) {\n throw new Error(\n `Store.extend() must be called before startApp(). Store '${this.name}' has already been initialized and cannot be extended.`\n );\n }\n\n type ExtendedSchema = TSchema & TExtendedSchema;\n\n const extendedSchema = {\n ...tail.schema,\n ...(config.schema || {}),\n } as ExtendedSchema;\n\n const extendedIndexes = [...tail.indexes, ...(config.indexes || [])];\n const extendedSearchIndexes = [...tail.searchIndexes, ...(config.searchIndexes || [])];\n\n type CombinedMethods = PreserveMethodsForExtendedSchema<TMethods, ExtendedSchema> &\n TExtendedMethods;\n\n const combinedMethods = {\n ...(tail.methods || {}),\n ...(config.methods || {}),\n } as CombinedMethods | undefined;\n\n const extendedStore = new Store<ExtendedSchema, CombinedMethods>(this.name, {\n schema: extendedSchema,\n methods: combinedMethods as unknown as CombinedMethods | undefined,\n indexes: extendedIndexes,\n searchIndexes: extendedSearchIndexes,\n indexCreationMode: config.indexCreationMode ?? tail.indexCreationMode,\n });\n\n // Link into the chain\n tail._chainChild = extendedStore;\n extendedStore._chainParent = tail;\n\n return extendedStore;\n }\n\n /** @internal */\n init(client: MongoClient) {\n if (this.collection) {\n throw new Error(`Collection ${this.name} is already initialized`);\n }\n\n this.client = client;\n this.collection = this.client.db().collection<this['_type']>(this.name);\n }\n\n /** @internal */\n async createIndexes(mode: IndexReconcileMode = 'full') {\n const collection = this.requireCollection();\n const shouldDropIndexes = mode !== 'create-only';\n const shouldCreateIndexes = mode !== 'drop-only';\n\n // Get all existing indexes in the collection (returns [] if collection doesn't exist)\n const existingIndexes = await listIndexes(collection);\n const indexByName = new Map<string, ExistingIndex & { name: string }>();\n const indexNamesByKey = new Map<string, Set<string>>();\n const droppedIndexNames = new Set<string>();\n\n const addIndexToLookup = (existingIndex: ExistingIndex & { name: string }) => {\n indexByName.set(existingIndex.name, existingIndex);\n\n const keySignature = getIndexKeySignature(existingIndex.key);\n if (!keySignature) {\n return;\n }\n\n const names = indexNamesByKey.get(keySignature);\n if (names) {\n names.add(existingIndex.name);\n } else {\n indexNamesByKey.set(keySignature, new Set([existingIndex.name]));\n }\n };\n\n const removeIndexFromLookup = (indexName: string) => {\n const existingIndex = indexByName.get(indexName);\n if (!existingIndex) {\n return;\n }\n\n indexByName.delete(indexName);\n\n const keySignature = getIndexKeySignature(existingIndex.key);\n if (!keySignature) {\n return;\n }\n\n const names = indexNamesByKey.get(keySignature);\n if (!names) {\n return;\n }\n\n names.delete(indexName);\n if (names.size === 0) {\n indexNamesByKey.delete(keySignature);\n }\n };\n\n for (const existingIndex of existingIndexes) {\n if (typeof existingIndex.name === 'string') {\n addIndexToLookup({\n ...existingIndex,\n name: existingIndex.name,\n });\n }\n }\n\n const dropIndexIfNeeded = async (indexName: string) => {\n if (indexName === '_id_' || droppedIndexNames.has(indexName)) {\n return;\n }\n try {\n await collection.dropIndex(indexName);\n } catch (error) {\n // Another concurrent reconciler may have already dropped it.\n if (!(error instanceof MongoError && error.code === 27)) {\n throw error;\n }\n }\n droppedIndexNames.add(indexName);\n removeIndexFromLookup(indexName);\n };\n\n if (shouldDropIndexes) {\n // Find all _modelence_ prefixed indexes that are not in the current schema\n const currentIndexNames = new Set(\n this.indexes\n .map((idx) => idx.name)\n .filter((name): name is string => typeof name === 'string')\n );\n const orphanedIndexes = [...indexByName.values()].filter(\n (existingIdx) =>\n hasModelencePrefix(existingIdx.name) && !currentIndexNames.has(existingIdx.name)\n );\n\n // Drop orphaned indexes\n for (const orphanedIndex of orphanedIndexes) {\n await dropIndexIfNeeded(orphanedIndex.name);\n }\n }\n\n // Reconcile code-defined indexes against the current DB metadata.\n // Code wins on conflicts; non-conflicting manual indexes are preserved.\n if (this.indexes.length > 0) {\n for (const index of this.indexes) {\n if (!index.name) {\n continue;\n }\n\n let requiresDropBeforeCreate = false;\n const existingByName = indexByName.get(index.name);\n if (existingByName && !isSameIndexDefinition(existingByName, index)) {\n if (shouldDropIndexes) {\n await dropIndexIfNeeded(existingByName.name);\n } else {\n requiresDropBeforeCreate = true;\n }\n }\n\n const keySignature = getIndexKeySignature(index.key);\n if (keySignature) {\n const existingNamesForKey = [...(indexNamesByKey.get(keySignature) || [])];\n for (const existingName of existingNamesForKey) {\n if (existingName !== index.name) {\n if (shouldDropIndexes) {\n await dropIndexIfNeeded(existingName);\n } else {\n requiresDropBeforeCreate = true;\n }\n }\n }\n }\n\n const alignedIndex = indexByName.get(index.name);\n const hasAlignedIndex = !!alignedIndex && isSameIndexDefinition(alignedIndex, index);\n\n if (!hasAlignedIndex && shouldCreateIndexes && !requiresDropBeforeCreate) {\n await collection.createIndexes([index]);\n addIndexToLookup({\n name: index.name,\n key: index.key,\n ...getComparableIndexOptions(index),\n });\n }\n }\n }\n if (shouldCreateIndexes && this.searchIndexes.length > 0) {\n for (const searchIndex of this.searchIndexes) {\n try {\n await collection.createSearchIndexes([searchIndex]);\n } catch (error) {\n if (error instanceof MongoError && error.code === 68 && searchIndex.name) {\n await collection.dropSearchIndex(searchIndex.name);\n await collection.createSearchIndexes([searchIndex]);\n } else {\n throw error;\n }\n }\n }\n }\n }\n\n private wrapDocument(document: this['_rawDoc']): this['_doc'] {\n if (!this.methods) {\n return document as unknown as this['_doc'];\n }\n\n const result = Object.create(\n null,\n Object.getOwnPropertyDescriptors({\n ...document,\n ...this.methods,\n })\n );\n\n return result as this['_doc'];\n }\n\n /**\n * For convenience, to also allow directy passing a string or ObjectId as the selector\n */\n private getSelector(selector: TypedFilter<this['_type']> | string | ObjectId) {\n if (typeof selector === 'string') {\n return { _id: new ObjectId(selector) } as Filter<this['_type']>;\n }\n\n if (selector instanceof ObjectId) {\n return { _id: selector } as Filter<this['_type']>;\n }\n\n return selector as Filter<this['_type']>;\n }\n\n /** @internal */\n requireCollection() {\n if (!this.collection) {\n throw new Error(`Collection ${this.name} is not provisioned`);\n }\n\n return this.collection;\n }\n\n /** @internal */\n requireClient() {\n if (!this.client) {\n throw new Error(`Database is not connected`);\n }\n\n return this.client;\n }\n\n /**\n * Finds a single document matching the query\n *\n * @param query - Type-safe query filter. Only schema fields, MongoDB operators, and dot notation are allowed.\n * @param options - Find options\n * @returns The document, or null if not found\n *\n * @example\n * ```ts\n * // ✅ Valid queries:\n * await store.findOne({ name: 'John' })\n * await store.findOne({ age: { $gt: 18 } })\n * await store.findOne({ _id: new ObjectId('...') })\n * await store.findOne({ tags: { $in: ['typescript', 'mongodb'] } })\n * await store.findOne({ $or: [{ name: 'John' }, { name: 'Jane' }] })\n * await store.findOne({ 'emails.address': 'test@example.com' }) // dot notation\n *\n * // ❌ TypeScript error - 'id' is not in schema:\n * await store.findOne({ id: '123' })\n * ```\n */\n async findOne(query: TypedFilter<this['_type']>, options?: FindOptions) {\n const document = await this.requireCollection().findOne<this['_rawDoc']>(\n query as Filter<this['_type']>,\n options\n );\n return document ? this.wrapDocument(document) : null;\n }\n\n async requireOne(\n query: TypedFilter<this['_type']>,\n options?: FindOptions,\n errorHandler?: () => Error\n ): Promise<this['_doc']> {\n const result = await this.findOne(query, options);\n if (!result) {\n throw errorHandler ? errorHandler() : new Error(`Record not found in ${this.name}`);\n }\n return result;\n }\n\n private find(query: TypedFilter<this['_type']>, options?: FetchOptions<this['_type']>) {\n const cursor = this.requireCollection().find(\n query as Filter<this['_type']>,\n options?.projection ? { projection: options.projection } : undefined\n );\n if (options?.sort) {\n cursor.sort(options.sort);\n }\n if (options?.limit) {\n cursor.limit(options.limit);\n }\n if (options?.skip) {\n cursor.skip(options.skip);\n }\n return cursor;\n }\n\n /**\n * Fetches a single document by its ID\n *\n * @param id - The ID of the document to find\n * @returns The document, or null if not found\n */\n async findById(id: string | ObjectId): Promise<this['_doc'] | null> {\n const idSelector = typeof id === 'string' ? { _id: new ObjectId(id) } : { _id: id };\n return await this.findOne(idSelector as TypedFilter<this['_type']>);\n }\n\n /**\n * Fetches a single document by its ID, or throws an error if not found\n *\n * @param id - The ID of the document to find\n * @param errorHandler - Optional error handler to return a custom error if the document is not found\n * @returns The document\n */\n async requireById(id: string | ObjectId, errorHandler?: () => Error): Promise<this['_doc']> {\n const result = await this.findById(id);\n if (!result) {\n throw errorHandler\n ? errorHandler()\n : new Error(`Record with id ${id} not found in ${this.name}`);\n }\n return result;\n }\n\n /**\n * Counts the number of documents that match a query\n *\n * @param query - The query to filter documents\n * @returns The number of documents that match the query\n */\n countDocuments(query: TypedFilter<this['_type']>): Promise<number> {\n return this.requireCollection().countDocuments(query as Filter<this['_type']>);\n }\n\n /**\n * Fetches multiple documents, equivalent to Node.js MongoDB driver's `find` and `toArray` methods combined.\n *\n * @param query - The query to filter documents\n * @param options - Optional fetch options\n * @param options.projection - Fields to include or exclude in the result documents\n * @param options.sort - Sort order for matching documents\n * @param options.limit - Maximum number of documents to return\n * @param options.skip - Number of matching documents to skip\n * @returns The documents\n *\n * @example\n * ```ts\n * // Include only selected fields\n * const docs = await store.fetch(\n * { userId: user.id },\n * { projection: { framework: 1, title: 1 }, sort: { createdAt: -1 }, limit: 50 }\n * );\n *\n * // Exclude large fields when not needed\n * const chunks = await store.fetch(\n * { documentId },\n * { projection: { embedding: 0 } }\n * );\n * ```\n */\n async fetch(\n query: TypedFilter<this['_type']>,\n options?: FetchOptions<this['_type']>\n ): Promise<this['_doc'][]> {\n const cursor = this.find(query, options);\n return (await cursor.toArray()).map(this.wrapDocument.bind(this));\n }\n\n /**\n * Inserts a single document\n *\n * @param document - The document to insert\n * @returns The result of the insert operation\n */\n async insertOne(\n document: OptionalUnlessRequiredId<InferDocumentType<TSchema>>,\n options?: { session?: ClientSession }\n ): Promise<InsertOneResult> {\n return await this.requireCollection().insertOne(document, options);\n }\n\n /**\n * Inserts a single document and returns the inserted document with its generated `_id`\n * and any helper methods applied.\n *\n * Unlike {@link insertOne}, which only returns the insert result metadata, this method\n * returns the full inserted document — useful when you need to immediately use the\n * newly created record (e.g. returning it from an API handler).\n *\n * @param document - The document to insert\n * @returns The inserted document with `_id` populated and methods applied\n *\n * @example\n * ```ts\n * const todo = await dbTodos.create({ title: 'Buy milk', completed: false });\n * console.log(todo._id); // ObjectId\n * console.log(todo.title); // 'Buy milk'\n * ```\n */\n async create(\n document: OptionalUnlessRequiredId<InferDocumentType<TSchema>>,\n options?: { session?: ClientSession }\n ): Promise<this['_doc']> {\n const docWithId = applyDefaultsToModelSchema(this.schema, {\n _id: new ObjectId(),\n ...document,\n }) as OptionalUnlessRequiredId<InferDocumentType<TSchema>>;\n\n await this.requireCollection().insertOne(docWithId, options);\n\n return this.wrapDocument(docWithId as unknown as this['_rawDoc']);\n }\n\n /**\n * Inserts multiple documents\n *\n * @param documents - The documents to insert\n * @returns The result of the insert operation\n */\n async insertMany(\n documents: OptionalUnlessRequiredId<InferDocumentType<TSchema>>[],\n options?: { session?: ClientSession }\n ): Promise<InsertManyResult> {\n return await this.requireCollection().insertMany(documents, options);\n }\n\n /**\n * Updates a single document\n *\n * @param selector - The selector to find the document to update\n * @param update - The update to apply to the document\n * @returns The result of the update operation\n */\n async updateOne(\n selector: TypedFilter<this['_type']> | string | ObjectId,\n update: UpdateFilter<this['_type']>,\n options?: { session?: ClientSession }\n ): Promise<UpdateResult> {\n return await this.requireCollection().updateOne(this.getSelector(selector), update, options);\n }\n\n /**\n * Updates a single document, or inserts it if it doesn't exist\n *\n * @param selector - The selector to find the document to update\n * @param update - The MongoDB modifier to apply to the document\n * @returns The result of the update operation\n */\n async upsertOne(\n selector: TypedFilter<this['_type']> | string | ObjectId,\n update: UpdateFilter<this['_type']>,\n options?: { session?: ClientSession }\n ): Promise<UpdateResult> {\n return await this.requireCollection().updateOne(this.getSelector(selector), update, {\n upsert: true,\n ...options,\n });\n }\n\n /**\n * Updates multiple documents\n *\n * @param selector - The selector to find the documents to update\n * @param update - The MongoDB modifier to apply to the documents\n * @returns The result of the update operation\n */\n async updateMany(\n selector: TypedFilter<this['_type']>,\n update: UpdateFilter<this['_type']>,\n options?: { session?: ClientSession }\n ): Promise<UpdateResult> {\n return await this.requireCollection().updateMany(\n selector as Filter<this['_type']>,\n update,\n options\n );\n }\n\n /**\n * Updates multiple documents, or inserts them if they don't exist\n *\n * @param selector - The selector to find the documents to update\n * @param update - The MongoDB modifier to apply to the documents\n * @returns The result of the update operation\n */\n async upsertMany(\n selector: TypedFilter<this['_type']>,\n update: UpdateFilter<this['_type']>,\n options?: { session?: ClientSession }\n ): Promise<UpdateResult> {\n return await this.requireCollection().updateMany(selector as Filter<this['_type']>, update, {\n upsert: true,\n ...options,\n });\n }\n\n /**\n * Deletes a single document\n *\n * @param selector - The selector to find the document to delete\n * @returns The result of the delete operation\n */\n async deleteOne(\n selector: TypedFilter<this['_type']> | string | ObjectId,\n options?: { session?: ClientSession }\n ): Promise<DeleteResult> {\n return await this.requireCollection().deleteOne(this.getSelector(selector), options);\n }\n\n /**\n * Deletes multiple documents\n *\n * @param selector - The selector to find the documents to delete\n * @returns The result of the delete operation\n */\n async deleteMany(\n selector: TypedFilter<this['_type']>,\n options?: { session?: ClientSession }\n ): Promise<DeleteResult> {\n return await this.requireCollection().deleteMany(selector as Filter<this['_type']>, options);\n }\n\n /**\n * Atomically finds a document and updates it, returning the document\n *\n * @param selector - The selector to find the document\n * @param update - The update to apply\n * @param options - Options including `returnDocument` ('before' or 'after'), `upsert`, `session`, etc.\n * @returns The document (before or after update, depending on options), or null if not found\n */\n async findOneAndUpdate(\n selector: TypedFilter<this['_type']> | string | ObjectId,\n update: UpdateFilter<this['_type']>,\n options?: Omit<FindOneAndUpdateOptions, 'includeResultMetadata'>\n ): Promise<this['_doc'] | null> {\n const result = await this.requireCollection().findOneAndUpdate(\n this.getSelector(selector),\n update,\n options ?? {}\n );\n return result ? this.wrapDocument(result as this['_rawDoc']) : null;\n }\n\n /**\n * Atomically finds a document and deletes it, returning the deleted document\n *\n * @param selector - The selector to find the document\n * @param options - Options including `session`, `projection`, etc.\n * @returns The deleted document, or null if not found\n */\n async findOneAndDelete(\n selector: TypedFilter<this['_type']> | string | ObjectId,\n options?: Omit<FindOneAndDeleteOptions, 'includeResultMetadata'>\n ): Promise<this['_doc'] | null> {\n const result = await this.requireCollection().findOneAndDelete(\n this.getSelector(selector),\n options ?? {}\n );\n return result ? this.wrapDocument(result as this['_rawDoc']) : null;\n }\n\n /**\n * Atomically finds a document and replaces it, returning the document\n *\n * @param selector - The selector to find the document\n * @param replacement - The replacement document\n * @param options - Options including `returnDocument` ('before' or 'after'), `upsert`, `session`, etc.\n * @returns The document (before or after replacement, depending on options), or null if not found\n */\n async findOneAndReplace(\n selector: TypedFilter<this['_type']> | string | ObjectId,\n replacement: WithoutId<this['_type']>,\n options?: Omit<FindOneAndReplaceOptions, 'includeResultMetadata'>\n ): Promise<this['_doc'] | null> {\n const result = await this.requireCollection().findOneAndReplace(\n this.getSelector(selector),\n replacement,\n options ?? {}\n );\n return result ? this.wrapDocument(result as this['_rawDoc']) : null;\n }\n\n /**\n * Replaces a single document\n *\n * @param selector - The selector to find the document to replace\n * @param replacement - The replacement document (must not contain update operators)\n * @param options - Options including `upsert`, `session`, etc.\n * @returns The result of the replace operation\n */\n async replaceOne(\n selector: TypedFilter<this['_type']> | string | ObjectId,\n replacement: WithoutId<this['_type']>,\n options?: ReplaceOptions\n ): Promise<UpdateResult> {\n return await this.requireCollection().replaceOne(\n this.getSelector(selector),\n replacement,\n options\n );\n }\n\n /**\n * Returns an array of distinct values for a field across the collection\n *\n * @param key - The field name (supports dot notation for nested fields)\n * @param filter - Optional filter to narrow the documents\n * @param options - Optional distinct options\n * @returns An array of distinct values\n */\n\n async distinct<K extends keyof this['_rawDoc'] & string>(\n key: K,\n filter?: TypedFilter<this['_type']>,\n options?: DistinctOptions\n ): Promise<Array<Flatten<this['_rawDoc'][K]>>> {\n const f = (filter ?? {}) as Filter<this['_type']>;\n return options !== undefined\n ? await this.requireCollection().distinct(key, f, options)\n : await this.requireCollection().distinct(key, f);\n }\n\n /**\n * Opens a change stream on the collection to watch for real-time changes\n *\n * @param pipeline - Optional aggregation pipeline to filter/transform change events\n * @param options - Optional change stream options\n * @returns A ChangeStream instance\n */\n watch(pipeline?: Document[], options?: ChangeStreamOptions): ChangeStream {\n return this.requireCollection().watch(pipeline, options);\n }\n\n /**\n * Aggregates documents using MongoDB's aggregation framework\n *\n * @param pipeline - The aggregation pipeline\n * @param options - Optional options\n * @returns The aggregation cursor\n */\n aggregate(pipeline: Document[], options?: AggregateOptions): AggregationCursor<Document> {\n return this.requireCollection().aggregate(pipeline, options);\n }\n\n /**\n * Performs a bulk write operation on the collection\n *\n * @param operations - The operations to perform\n * @returns The result of the bulk write operation\n */\n bulkWrite(operations: AnyBulkWriteOperation<this['_type']>[]): Promise<BulkWriteResult> {\n return this.requireCollection().bulkWrite(operations);\n }\n\n /**\n * Returns the raw MongoDB database instance for advanced operations\n * @returns The MongoDB database instance\n * @throws Error if the store is not provisioned\n */\n getDatabase() {\n return this.requireClient().db();\n }\n\n /**\n * Returns the raw MongoDB collection instance for advanced operations\n * @returns The MongoDB collection instance\n * @throws Error if the store is not provisioned\n */\n rawCollection() {\n return this.requireCollection();\n }\n\n /**\n * Renames an existing collection to this store's name, used for migrations\n * @param oldName - The previous name of the collection\n * @throws Error if the old collection doesn't exist or if this store's collection already exists\n */\n async renameFrom(oldName: string, options?: { session?: ClientSession }) {\n const db = this.getDatabase();\n\n if (!this.collection || !db) {\n throw new Error(`Store ${this.name} is not provisioned`);\n }\n\n const oldCollections = await db.listCollections({ name: oldName }).toArray();\n if (oldCollections.length === 0) {\n throw new Error(`Collection ${oldName} not found`);\n }\n\n const newCollections = await db.listCollections({ name: this.name }).toArray();\n if (newCollections.length > 0) {\n throw new Error(`Collection ${this.name} already exists`);\n }\n\n const existingCollection = db.collection<this['_type']>(oldName);\n\n await existingCollection.rename(this.name, options);\n }\n\n /**\n * Performs a vector similarity search using MongoDB Atlas Vector Search\n *\n * @param params - Vector search parameters\n * @param params.field - The field name containing the vector embeddings\n * @param params.embedding - The query vector to search for\n * @param params.numCandidates - Number of nearest neighbors to consider (default: 100)\n * @param params.limit - Maximum number of results to return (default: 10)\n * @param params.projection - Additional fields to include in the results\n * @param params.indexName - Name of index (default: field + VectorSearch)\n * @returns An aggregation cursor with search results and scores\n *\n * @example\n * ```ts\n * const results = await store.vectorSearch({\n * field: 'embedding',\n * embedding: [0.1, 0.2, 0.3, ...],\n * numCandidates: 100,\n * limit: 10,\n * projection: { title: 1, description: 1 }\n * });\n * ```\n */\n async vectorSearch({\n field,\n embedding,\n numCandidates,\n limit,\n projection,\n indexName,\n }: {\n field: string;\n embedding: number[];\n numCandidates?: number;\n limit?: number;\n projection?: Document;\n indexName?: string;\n }) {\n return this.aggregate([\n {\n $vectorSearch: {\n index: indexName || field + 'VectorSearch',\n path: field,\n queryVector: embedding,\n numCandidates: numCandidates || 100,\n limit: limit || 10,\n },\n },\n {\n $project: {\n _id: 1,\n score: { $meta: 'vectorSearchScore' },\n ...projection,\n },\n },\n ]);\n }\n\n /**\n * Creates a MongoDB Atlas Vector Search index definition\n *\n * @param params - Vector index parameters\n * @param params.field - The field name to create the vector index on\n * @param params.dimensions - The number of dimensions in the vector embeddings\n * @param params.similarity - The similarity metric to use (default: 'cosine')\n * @param params.indexName - Name of index (default: field + VectorSearch)\n * @returns A search index description object\n *\n * @example\n * ```ts\n * const store = new Store('documents', {\n * schema: {\n * title: schema.string(),\n * embedding: schema.array(schema.number()),\n * },\n * indexes: [],\n * searchIndexes: [\n * Store.vectorIndex({\n * field: 'embedding',\n * dimensions: 1536,\n * similarity: 'cosine'\n * })\n * ]\n * });\n * ```\n */\n static vectorIndex({\n field,\n dimensions,\n similarity = 'cosine',\n indexName,\n }: {\n field: string;\n dimensions: number;\n similarity?: 'cosine' | 'euclidean' | 'dotProduct';\n indexName?: string;\n }) {\n return {\n type: 'vectorSearch',\n name: indexName || field + 'VectorSearch',\n definition: {\n fields: [\n {\n type: 'vector',\n path: field,\n numDimensions: dimensions,\n similarity,\n },\n ],\n },\n };\n }\n}\n","import { ObjectId } from 'mongodb';\nimport { z, ZodArray, ZodNumber } from 'zod';\nimport { Store } from './store';\n\ntype ObjectTypeDefinition = {\n [key: string]: SchemaTypeDefinition;\n};\n\ntype SingularSchemaTypeDefinition = z.ZodType | ObjectTypeDefinition; // ReturnType<typeof schema[keyof typeof schema]>;\n\ntype SchemaTypeDefinition = SingularSchemaTypeDefinition | Array<SingularSchemaTypeDefinition>;\n\nexport type ModelSchema = {\n [key: string]: SchemaTypeDefinition;\n};\n\nconst schemaString: typeof z.string = z.string.bind(z);\n\nconst schemaNumber: typeof z.number = z.number.bind(z);\n\nconst schemaDate: typeof z.date = z.date.bind(z);\n\nconst schemaBoolean: typeof z.boolean = z.boolean.bind(z);\n\nconst schemaArray: typeof z.array = z.array.bind(z);\n\nconst schemaObject: typeof z.object = z.object.bind(z);\n\nconst schemaEnum: typeof z.enum = z.enum.bind(z);\n\nexport const schema = {\n string: schemaString,\n number: schemaNumber,\n date: schemaDate,\n boolean: schemaBoolean,\n array: schemaArray,\n object: schemaObject,\n enum: schemaEnum,\n embedding(): ZodArray<ZodNumber> {\n return z.array(z.number());\n },\n objectId(): z.ZodType<ObjectId> {\n return z.instanceof(ObjectId).describe('ObjectId');\n },\n userId(): z.ZodType<ObjectId> {\n return z.instanceof(ObjectId).describe('UserId');\n },\n ref<T extends ModelSchema>(\n _collection: string | Store<T, InferDocumentType<T>>\n ): z.ZodType<ObjectId> {\n return z.instanceof(ObjectId).describe('Ref');\n },\n union: z.union.bind(z),\n infer<T extends SchemaTypeDefinition>(_schema: T): InferDocumentType<T> {\n return {} as InferDocumentType<T>;\n },\n} as const;\n\nexport type InferDocumentType<T extends SchemaTypeDefinition> = {\n [K in keyof T as T[K] extends z.ZodOptional<z.ZodTypeAny> ? K : never]?: T[K] extends z.ZodType\n ? z.infer<T[K]>\n : never;\n} & {\n [K in keyof T as T[K] extends z.ZodOptional<z.ZodTypeAny> ? never : K]: T[K] extends z.ZodType\n ? z.infer<T[K]>\n : T[K] extends Array<infer ElementType extends SchemaTypeDefinition>\n ? Array<InferDocumentType<ElementType>>\n : T[K] extends ObjectTypeDefinition\n ? InferDocumentType<T[K]>\n : never;\n};\n\nexport namespace schema {\n export type infer<T extends SchemaTypeDefinition> = InferDocumentType<T>;\n}\n","import { randomBytes } from 'crypto';\nimport { type Response } from 'express';\nimport { ObjectId } from 'mongodb';\nimport { Module } from '../app/module';\nimport { getPublicConfigs } from '../config/server';\nimport { Store } from '../data/store';\nimport { schema } from '../data/types';\nimport { time } from '../time';\nimport { Session } from './types';\n\nexport const linkNoncesCollection = new Store('_modelenceLinkNonces', {\n schema: {\n nonce: schema.string(),\n userId: schema.string(),\n expiresAt: schema.date(),\n },\n indexes: [\n { key: { nonce: 1 }, unique: true },\n { key: { expiresAt: 1 }, expireAfterSeconds: 0 },\n ],\n});\n\nexport async function issueLinkNonce(userId: string): Promise<string> {\n const nonce = randomBytes(32).toString('hex');\n await linkNoncesCollection.insertOne({\n nonce,\n userId,\n expiresAt: new Date(Date.now() + time.minutes(10)),\n });\n return nonce;\n}\n\nexport async function consumeLinkNonce(nonce: string): Promise<string | null> {\n const entry = await linkNoncesCollection.findOneAndDelete({ nonce });\n if (!entry) return null;\n return entry.userId;\n}\n\nexport const sessionsCollection = new Store('_modelenceSessions', {\n schema: {\n authToken: schema.string(),\n createdAt: schema.date(),\n expiresAt: schema.date(),\n userId: schema.userId().nullable(),\n },\n indexes: [\n { key: { authToken: 1 }, unique: true },\n { key: { expiresAt: 1 }, expireAfterSeconds: 0 },\n { key: { userId: 1 } },\n ],\n});\n\nexport async function obtainSession(authToken: string | null): Promise<Session> {\n const existingSession = authToken ? await sessionsCollection.findOne({ authToken }) : null;\n\n if (existingSession) {\n return {\n authToken: String(existingSession.authToken),\n expiresAt: new Date(existingSession.expiresAt),\n userId: existingSession.userId ?? null,\n };\n }\n\n return await createSession();\n}\n\nexport async function setSessionUser(authToken: string, userId: ObjectId) {\n await sessionsCollection.updateOne(\n { authToken },\n {\n $set: { userId },\n }\n );\n}\n\nexport async function clearSessionUser(authToken: string) {\n await sessionsCollection.updateOne(\n { authToken },\n {\n $set: { userId: null },\n }\n );\n}\n\nexport async function invalidateAllUserSessions(userId: ObjectId) {\n await sessionsCollection.deleteMany({ userId });\n}\n\nexport async function createSession(userId: ObjectId | null = null): Promise<Session> {\n // TODO: add rate-limiting and captcha handling\n\n const authToken = randomBytes(32).toString('base64url');\n const now = Date.now();\n const expiresAt = new Date(now + time.days(7));\n\n await sessionsCollection.insertOne({\n authToken,\n createdAt: new Date(now),\n expiresAt,\n userId,\n });\n\n return {\n authToken,\n expiresAt,\n userId,\n };\n}\n\nasync function processSessionHeartbeat(session: Session) {\n const now = Date.now();\n const newExpiresAt = new Date(now + time.days(7));\n\n await sessionsCollection.updateOne(\n { authToken: session.authToken },\n {\n $set: {\n lastActiveDate: new Date(now),\n expiresAt: newExpiresAt,\n },\n }\n );\n}\n\nexport function setAuthTokenCookie(res: Response, authToken: string) {\n res.cookie('authToken', authToken, {\n httpOnly: true,\n secure: process.env.NODE_ENV === 'production',\n sameSite: 'lax',\n path: '/',\n maxAge: time.days(7),\n });\n}\n\nexport function clearAuthTokenCookie(res: Response) {\n res.clearCookie('authToken', {\n httpOnly: true,\n secure: process.env.NODE_ENV === 'production',\n sameSite: 'lax',\n path: '/',\n });\n}\n\nexport default new Module('_system.session', {\n stores: [sessionsCollection, linkNoncesCollection],\n mutations: {\n init: async function (args, { session, user, res }) {\n // Only refresh the cookie for logged-in sessions. Writing one for a\n // freshly-minted anonymous session creates a Set-Cookie that the\n // browser then attaches to the client's reconciliation request,\n // shadowing the localStorage token sent in the body — see\n // getCallContext's `cookie || body.authToken` precedence.\n if (res && session?.userId) {\n setAuthTokenCookie(res, session.authToken);\n }\n\n return {\n session,\n user,\n configs: getPublicConfigs(),\n };\n },\n heartbeat: async function (args, { session }) {\n // Session might not exist if there is no database/authentication setup\n if (session) {\n await processSessionHeartbeat(session);\n }\n },\n },\n});\n","import { schema } from '../data/types';\nimport { Store } from '../data/store';\n\n/**\n * Database collection for storing user accounts with authentication methods and profile information.\n *\n * This is where **signupWithPassword** automatically creates new users.\n *\n * @example\n * ```typescript\n * // Find user by email\n * const user = await dbUsers.findOne(\n * { 'emails.address': 'john@example.com' }\n * );\n * ```\n *\n */\nexport const usersCollection = new Store('_modelenceUsers', {\n schema: {\n handle: schema.string(),\n emails: schema\n .array(\n schema.object({\n address: schema.string(),\n verified: schema.boolean(),\n })\n )\n .optional(),\n status: schema.enum(['active', 'disabled', 'deleted']).optional(),\n firstName: schema.string().optional(),\n lastName: schema.string().optional(),\n avatarUrl: schema.string().optional(),\n createdAt: schema.date(),\n disabledAt: schema.date().optional(),\n deletedAt: schema.date().optional(),\n roles: schema.array(schema.string()).optional(),\n authMethods: schema.object({\n password: schema\n .object({\n hash: schema.string(),\n })\n .optional(),\n google: schema\n .object({\n id: schema.string(),\n })\n .optional(),\n github: schema\n .object({\n id: schema.string(),\n })\n .optional(),\n }),\n },\n indexes: [\n {\n key: { handle: 1 },\n unique: true,\n collation: { locale: 'en', strength: 2 }, // Case-insensitive\n },\n {\n key: { 'emails.address': 1, status: 1 },\n },\n {\n key: { 'authMethods.google.id': 1 },\n sparse: true,\n unique: true,\n },\n {\n key: { 'authMethods.github.id': 1 },\n sparse: true,\n unique: true,\n },\n ],\n});\n\nexport const dbDisposableEmailDomains = new Store('_modelenceDisposableEmailDomains', {\n schema: {\n domain: schema.string(),\n addedAt: schema.date(),\n },\n indexes: [\n {\n key: { domain: 1 },\n unique: true,\n },\n ],\n});\n\nexport const emailVerificationTokensCollection = new Store('_modelenceEmailVerificationTokens', {\n schema: {\n userId: schema.objectId(),\n email: schema.string().optional(),\n token: schema.string(),\n createdAt: schema.date(),\n expiresAt: schema.date(),\n },\n indexes: [\n {\n key: { token: 1 },\n unique: true,\n },\n {\n key: { expiresAt: 1 },\n expireAfterSeconds: 0,\n },\n ],\n});\n\nexport const resetPasswordTokensCollection = new Store('_modelenceResetPasswordTokens', {\n schema: {\n userId: schema.objectId(),\n email: schema.string().optional(),\n token: schema.string(),\n createdAt: schema.date(),\n expiresAt: schema.date(),\n },\n indexes: [\n {\n key: { token: 1 },\n unique: true,\n },\n {\n key: { expiresAt: 1 },\n expireAfterSeconds: 0,\n },\n ],\n});\n\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 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"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {C}from'./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import {C}from'./chunk-LVB7YU4P.js';import {a,b,c}from'./chunk-5M6FUMUK.js';import {AsyncLocalStorage}from'async_hooks';async function x(t,e,u){let n=a(await C(t,e,u)),a$1=b(n),y=JSON.parse(JSON.stringify(n));return c(y,a$1??void 0)}var p=new AsyncLocalStorage;function g(t,e){return p.run(t,e)}function d(){return p.getStore()}export{x as a,g as b,d as c};//# sourceMappingURL=chunk-P2W2XOKE.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-P2W2XOKE.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/ssr/callInProcess.ts","../src/ssr/context.ts"],"names":["callInProcessMethod","methodName","args","context","sanitized","sanitizeResult","runMethod","typeMap","getResponseTypeMap","jsonRoundTripped","reviveResponseTypes","storage","AsyncLocalStorage","runWithSsrContext","ctx","fn","getSsrContext"],"mappings":"wHAOA,eAAsBA,CAAAA,CACpBC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACY,CACZ,IAAMC,CAAAA,CAAYC,CAAAA,CAAe,MAAMC,CAAAA,CAAUL,CAAAA,CAAYC,CAAAA,CAAMC,CAAO,CAAC,CAAA,CACrEI,GAAAA,CAAUC,CAAAA,CAAmBJ,CAAS,CAAA,CACtCK,CAAAA,CAAmB,IAAA,CAAK,KAAA,CAAM,IAAA,CAAK,SAAA,CAAUL,CAAS,CAAC,CAAA,CAC7D,OAAOM,CAAAA,CAAoBD,CAAAA,CAAkBF,GAAAA,EAAW,MAAS,CACnE,CCAA,IAAMI,CAAAA,CAAU,IAAIC,iBAAAA,CAEb,SAASC,CAAAA,CAAqBC,CAAAA,CAAwBC,CAAAA,CAAgB,CAC3E,OAAOJ,CAAAA,CAAQ,GAAA,CAAIG,CAAAA,CAAKC,CAAE,CAC5B,CAEO,SAASC,CAAAA,EAA+C,CAC7D,OAAOL,CAAAA,CAAQ,QAAA,EACjB","file":"chunk-
|
|
1
|
+
{"version":3,"sources":["../src/ssr/callInProcess.ts","../src/ssr/context.ts"],"names":["callInProcessMethod","methodName","args","context","sanitized","sanitizeResult","runMethod","typeMap","getResponseTypeMap","jsonRoundTripped","reviveResponseTypes","storage","AsyncLocalStorage","runWithSsrContext","ctx","fn","getSsrContext"],"mappings":"wHAOA,eAAsBA,CAAAA,CACpBC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACY,CACZ,IAAMC,CAAAA,CAAYC,CAAAA,CAAe,MAAMC,CAAAA,CAAUL,CAAAA,CAAYC,CAAAA,CAAMC,CAAO,CAAC,CAAA,CACrEI,GAAAA,CAAUC,CAAAA,CAAmBJ,CAAS,CAAA,CACtCK,CAAAA,CAAmB,IAAA,CAAK,KAAA,CAAM,IAAA,CAAK,SAAA,CAAUL,CAAS,CAAC,CAAA,CAC7D,OAAOM,CAAAA,CAAoBD,CAAAA,CAAkBF,GAAAA,EAAW,MAAS,CACnE,CCAA,IAAMI,CAAAA,CAAU,IAAIC,iBAAAA,CAEb,SAASC,CAAAA,CAAqBC,CAAAA,CAAwBC,CAAAA,CAAgB,CAC3E,OAAOJ,CAAAA,CAAQ,GAAA,CAAIG,CAAAA,CAAKC,CAAE,CAC5B,CAEO,SAASC,CAAAA,EAA+C,CAC7D,OAAOL,CAAAA,CAAQ,QAAA,EACjB","file":"chunk-P2W2XOKE.js","sourcesContent":["import { runMethod } from '../methods';\nimport { sanitizeResult, getResponseTypeMap, reviveResponseTypes } from '../methods/serialize';\nimport type { Context, Args } from '../methods/types';\n\n// Invoke a method in-process and round-trip through the same JSON pipeline\n// as the HTTP transport so SSR output matches the dehydrated query cache.\n// The JSON.stringify/parse step is load-bearing: strips `undefined` props.\nexport async function callInProcessMethod<T = unknown>(\n methodName: string,\n args: Args,\n context: Context\n): Promise<T> {\n const sanitized = sanitizeResult(await runMethod(methodName, args, context));\n const typeMap = getResponseTypeMap(sanitized);\n const jsonRoundTripped = JSON.parse(JSON.stringify(sanitized));\n return reviveResponseTypes(jsonRoundTripped, typeMap ?? undefined) as T;\n}\n","import { AsyncLocalStorage } from 'node:async_hooks';\nimport type { QueryClient } from '@tanstack/react-query';\nimport type { Context } from '../methods/types';\nimport type { Configs } from '../config/types';\n\nexport type SsrSessionSnapshot = {\n user: unknown;\n configs: Configs;\n};\n\nexport type SsrRequestContext = {\n callContext: Context;\n queryClient: QueryClient;\n session: SsrSessionSnapshot;\n};\n\nconst storage = new AsyncLocalStorage<SsrRequestContext>();\n\nexport function runWithSsrContext<T>(ctx: SsrRequestContext, fn: () => T): T {\n return storage.run(ctx, fn);\n}\n\nexport function getSsrContext(): SsrRequestContext | undefined {\n return storage.getStore();\n}\n"]}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import {s as s$1}from'./chunk-7DT2YQTG.js';import {a,b,c,o,p,q as q$1,r,s,k,l,x as x$1,j,i,m,h as h$1,n,t,y as y$1,z as z$2,A as A$1,B as B$1,d as d$1,C as C$1,v,u,e as e$1,F as F$1,D as D$1,E as E$1}from'./chunk-LVB7YU4P.js';import {b as b$1,d,a as a$4}from'./chunk-MIRF7FP3.js';import {a as a$2,f,e,g,c as c$1,h as h$2,l as l$1,k as k$1,d as d$2,j as j$2,m as m$1,i as i$1,n as n$1}from'./chunk-ENHGU3X4.js';import {a as a$3,b as b$2}from'./chunk-5M6FUMUK.js';import {a as a$1}from'./chunk-DO5TZLF5.js';import tr from'dotenv';import Sn from'fs/promises';import Vr from'os';import K from'path';import {Server}from'socket.io';import {createAdapter}from'@socket.io/mongo-adapter';import {MongoClient,MongoError,ObjectId,MongoServerError}from'mongodb';export{ObjectId as m}from'mongodb';import br from'bcrypt';import D,{z as z$1}from'zod';import {randomBytes,randomInt,createHash,randomUUID}from'crypto';import {createServer,defineConfig,loadConfigFromFile,mergeConfig}from'vite';import ln from'@vitejs/plugin-react';import Re from'fs';import j$1,{Router}from'express';import ci from'cookie-parser';import li from'http';var ce=new a("_system",{configSchema:{mongodbUri:{type:"secret",isPublic:false,default:""},mongodbPoolSize:{type:"number",isPublic:false,default:10},"env.type":{type:"string",isPublic:true,default:""},"site.url":{type:"string",isPublic:true,default:""},multiInstance:{type:"boolean",isPublic:false,default:false}}});var N=null;async function jt(){if(N)return N;let e=F();if(!e)throw new Error("MongoDB URI is not set");let t=ce.getConfig("mongodbPoolSize");N=new MongoClient(e,{driverInfo:{name:"Modelence",version:s$1.version},ignoreUndefined:true,maxPoolSize:t});try{return await N.connect(),await N.db("admin").command({ping:1}),console.log("Pinged your deployment. You successfully connected to MongoDB!"),N}catch(o){throw console.error(o),N=null,o}}function F(){return ce.getConfig("mongodbUri")||void 0}function be(){return N}var le=null,gr="_modelenceSocketio",Ht=60;async function hr({httpServer:e,channels:t}){let o=be(),r=!!a$2("_system.multiInstance");console.log("Initializing Socket.IO server...");let n=null;if(r&&o){n=o.db().collection(gr);try{await n.createIndex({createdAt:1},{expireAfterSeconds:Ht,background:!0});}catch(i){if(i instanceof Error&&"code"in i&&i.code===85)try{await n.dropIndex("createdAt_1"),await n.createIndex({createdAt:1},{expireAfterSeconds:Ht,background:!0});}catch(s){console.error("Failed to recreate index on MongoDB collection for Socket.IO:",s);}else console.error("Failed to create index on MongoDB collection for Socket.IO:",i);}}le=new Server(e,{cors:{origin:"*",methods:["GET","POST"]},adapter:n?createAdapter(n):void 0,transports:["websocket"],perMessageDeflate:false}),le.on("error",i=>{console.error("Socket.IO error:",i);}),le.use(async(i,s)=>{let a=i.handshake.auth.token;try{i.data=await v(a);}finally{s();}}),le.on("connection",i=>{i.on("disconnect",()=>{F$1(i);}),i.on("joinChannel",async s=>{let[a]=s.split(":"),c=false;for(let l of t)if(l.category===a){(!l.canAccessChannel||await l.canAccessChannel(i.data))&&(i.join(s),c=true,i.emit("joinedChannel",s));break}c||i.emit("joinError",{channel:s,error:"Access denied"});}),i.on("leaveChannel",s=>{i.leave(s),console.log(`User ${i.id} left channel ${s}`),i.emit("leftChannel",s);}),i.on("subscribeLiveQuery",s=>D$1(i,s)),i.on("unsubscribeLiveQuery",s=>E$1(i,s));}),console.log("Socket.IO server initialized");}function wr({category:e,id:t,data:o}){le?.to(`${e}:${t}`).emit(e,o);}var Gt={init:hr,broadcast:wr};async function ve(e){let t=e.toLowerCase().trim().split("@");if(t.length!==2)return false;let o=t[1];return !!await p.findOne({domain:o})}var Ft={interval:a$1.days(1),async handler(){let e=await fetch("https://disposable.github.io/disposable-email-domains/domains.txt");if(!e.ok)throw new Error(`HTTP ${e.status}: ${e.statusText}`);let o=(await e.text()).split(`
|
|
2
|
+
`).map(i=>i.trim().toLowerCase()).filter(i=>i.length>0),r=new Date,n=500;for(let i=0;i<o.length;i+=n){let s=o.slice(i,i+n);try{await p.insertMany(s.map(a=>({domain:a,addedAt:r})));}catch(a){a&&typeof a=="object"&&"name"in a&&a.name;}}}};var Ce=3,V=50,Vt=8,Bt=128,qt=254,zt=e=>z$1.string().trim().min(e.min??1,{message:`must be at least ${e.min??1} characters`}).max(e.max,{message:`must be at most ${e.max} characters`}),je=e=>z$1.string().trim().max(e.max,{message:`must be at most ${e.max} characters`}).transform(t=>t===""?void 0:t).optional(),yr=z$1.object({firstName:je({max:50}),lastName:je({max:50}),avatarUrl:je({max:400}),handle:zt({min:Ce,max:V})}).strict();function ke(e){let t=yr.partial().safeParse(e);if(!t.success){let o=t.error.issues[0],r=o.path.join("."),n=r?`${r}: ${o.message}`:o.message;throw new Error(n)}return t.data}function Se(e){return z$1.string().min(Vt,{message:`Password must contain at least ${Vt} characters`}).max(Bt,{message:`Password must be at most ${Bt} characters`}).parse(e)}function x(e){return z$1.string().max(qt,{message:`Email must be at most ${qt} characters`}).email({message:"Invalid email address"}).parse(e).toLowerCase()}function Wt(e){return zt({min:Ce,max:V}).parse(e)}function Ae(e,t){return t?t.startsWith("http://")||t.startsWith("https://")?t:`${e}${t.startsWith("/")?"":"/"}${t}`:e}function B(e){return {id:e._id,handle:e.handle,roles:e.roles||[],firstName:e.firstName??void 0,lastName:e.lastName??void 0,avatarUrl:e.avatarUrl??void 0}}async function Jt(e){let t=e.slice(0,V);try{if(!await o.findOne({handle:t},{collation:{locale:"en",strength:2}}))return t}catch(n){throw new Error(`Database error while checking handle availability: ${n}`)}let o$1=51;for(let n=2;n<=o$1;n++){let i=`_${n}`,s=`${t.slice(0,V-i.length)}${i}`;try{if(!await o.findOne({handle:s},{collation:{locale:"en",strength:2}}))return s}catch(a){throw new Error(`Database error while checking handle "${s}": ${a}`)}}let r=10;for(let n=0;n<r;n++){let i=`_${randomBytes(3).toString("hex")}`,s=`${t.slice(0,V-i.length)}${i}`;try{if(!await o.findOne({handle:s},{collation:{locale:"en",strength:2}}))return s}catch(a){throw new Error(`Database error while checking handle "${s}": ${a}`)}}throw new Error(`Could not generate a unique handle for base "${e}" after exhausting all attempts.`)}async function O(e,t,{throwOnConflict:o$1=true}={}){if(e!=null&&String(e).trim()!==""){let n=Wt(String(e).trim());if(o$1){if(await o.findOne({handle:n},{collation:{locale:"en",strength:2}}))throw new Error("Handle already taken.");return n}return Jt(n)}let r=t.split("@")[0].padEnd(Ce,"_").slice(0,V);return Jt(r)}var He=Object.freeze({});function Ge(e){He=Object.freeze(Object.assign({},He,e));}function h(){return He}var Fe=Object.freeze({});function Kt(e){Fe=Object.freeze(Object.assign({},Fe,e));}function y(){return Fe}function Cr(){return h()?.provider?!!a$2("_system.user.auth.email.verification"):false}async function Qt(e,{user:t,session:o$1,connectionInfo:r,res:n}){try{if(!o$1)throw new Error("Session is not initialized");let i=r?.ip;i&&await C({bucket:"signin",type:"ip",value:i});let s=x(e.email),a=z$1.string().parse(e.password),c=await o.findOne({"emails.address":s,status:{$nin:["deleted","disabled"]}},{collation:{locale:"en",strength:2}}),l$1=c?.authMethods?.password?.hash;if(!l$1)throw Yt();if(!c.emails?.find(f=>f.address.toLowerCase()===s)?.verified&&Cr())throw new b$1("Your email address hasn't been verified yet. Please check your inbox for the verification email.","EMAIL_NOT_VERIFIED");if(!await br.compare(a,l$1))throw Yt();return await h$1(o$1.authToken,c._id),n&&l(n,o$1.authToken),y().onAfterLogin?.({provider:"email",user:c,session:o$1,connectionInfo:r}),y().login?.onSuccess?.(c),{user:B(c),session:{authToken:o$1.authToken}}}catch(i){throw i instanceof Error&&(y().onLoginError?.({provider:"email",error:i,session:o$1,connectionInfo:r}),y().login?.onError?.(i)),i}}async function Xt(e,{session:t,res:o}){if(!t)throw new Error("Session is not initialized");await i(t.authToken),o&&m(o);}function Yt(){return new Error("Incorrect email/password combination")}async function Zt(e,{user:t}){if(!t)throw new Error("Not authenticated");let o$1=await o.requireById(t.id);return {handle:o$1.handle,emails:o$1.emails,authMethods:Object.keys(o$1.authMethods||{}),firstName:o$1.firstName??void 0,lastName:o$1.lastName??void 0,avatarUrl:o$1.avatarUrl??void 0}}async function eo(e,{user:t}){if(!t)throw new Error("Not authenticated");let o$1=await o.requireById(t.id),r=ke(e);if(await y().validateProfileUpdate?.(r),"handle"in r&&r.handle!==void 0&&await o.findOne({handle:r.handle,_id:{$ne:o$1._id}},{collation:{locale:"en",strength:2}}))throw new Error("Handle already taken.");if(Object.keys(r).length>0){let n={},i={};for(let[a,c]of Object.entries(r))c===void 0?i[a]="":n[a]=c;let s={};Object.keys(n).length>0&&(s.$set=n),Object.keys(i).length>0&&(s.$unset=i);try{await o.updateOne({_id:o$1._id},s);let a=Object.fromEntries(Object.keys(i).map(c=>[c,void 0]));o$1={...o$1,...n,...a};}catch(a){throw a instanceof Error&&"code"in a&&a.code===11e3?new Error("Handle already taken."):a}}return {user:B(o$1)}}var Ve=["google","github"];async function to({provider:e},{user:t}){if(!t)throw new Error("You must be signed in to unlink a provider.");if(typeof e!="string"||!Ve.includes(e))throw new Error(`Invalid provider. Supported providers are: ${Ve.join(", ")}.`);let o$1=await o.requireById(t.id),r=o$1.authMethods??{};if(!r[e])throw new Error(`${e} is not linked to your account.`);if(Object.values(r).filter(Boolean).length<=1)throw new Error("Cannot unlink your only authentication method. Please add another method first.");let s=Object.keys(r).filter(l=>l!==e&&r[l]),a=s.length>0?{$or:s.map(l=>({[`authMethods.${l}`]:{$exists:true}}))}:{};if((await o.updateOne({_id:o$1._id,...a},{$unset:{[`authMethods.${e}`]:""}})).matchedCount===0)throw new Error("Cannot unlink your only authentication method. Please add another method first.")}var ue=new b("_modelenceRateLimits",{schema:{bucket:c.string(),type:c.enum(["ip","user","email"]),value:c.string(),windowMs:c.number(),windowStart:c.date(),windowCount:c.number(),prevWindowCount:c.number(),expiresAt:c.date()},indexes:[{key:{bucket:1,type:1,value:1,windowMs:1},unique:true},{key:{expiresAt:1},expireAfterSeconds:0}]});var Be=[];function oo(e){if(Be.length>0)throw new Error("Duplicate call to initRateLimits - already initialized");Be=e;}async function C(e){let{bucket:t,type:o,value:r,message:n}=e,i=Be.filter(a=>a.bucket===t&&a.type===o),s=n?()=>new d(n):void 0;for(let a of i)await kr(a,r,s);}async function kr(e,t,o){let r=()=>o?o():new d(`Rate limit exceeded for ${e.bucket}`),n=await ue.findOne({bucket:e.bucket,type:e.type,value:t,windowMs:e.window}),i=Date.now(),s=Math.floor(i/e.window)*e.window,{count:a,modifier:c}=n?Sr(n,s,i):{count:0,modifier:{$setOnInsert:{windowStart:new Date(s),windowCount:1,prevWindowCount:0,expiresAt:new Date(s+e.window+e.window)}}};if(a>=e.limit)throw r();await ue.upsertOne({bucket:e.bucket,type:e.type,value:t,windowMs:e.window},c);}function Sr(e,t,o){let r=t-e.windowMs;if(e.windowStart.getTime()===t){let n=e.windowCount,i=e.prevWindowCount,s=1-(o-t)/e.windowMs;return {count:Math.round(n+i*s),modifier:{$inc:{windowCount:1},$setOnInsert:{windowStart:new Date(t),prevWindowCount:0,expiresAt:new Date(t+e.windowMs+e.windowMs)}}}}if(e.windowStart.getTime()===r){let n=1-(o-t)/e.windowMs;return {count:Math.round(e.windowCount*n),modifier:{$set:{windowStart:new Date(t),windowCount:1,prevWindowCount:e.windowCount,expiresAt:new Date(t+e.windowMs+e.windowMs)}}}}return {count:0,modifier:{$set:{windowStart:new Date(t),windowCount:1,prevWindowCount:0,expiresAt:new Date(t+e.windowMs+e.windowMs)}}}}function ro({name:e,email:t,verificationUrl:o}){return `
|
|
3
|
+
<p>Hi${e?` ${e}`:""},</p>
|
|
4
|
+
<p>Please verify your email address ${t} by clicking the link below:</p>
|
|
5
|
+
<p><a href="${o}">${o}</a></p>
|
|
6
|
+
<p>If you did not request this, please ignore this email.</p>
|
|
7
|
+
`}async function Rr(e){let t=await q$1.findOne({token:e,expiresAt:{$gt:new Date}});if(!t)throw new Error("Invalid or expired verification token");if(!await o.findOne({_id:t.userId,status:{$nin:["deleted","disabled"]}}))throw new Error("User not found");let r=t.email;if(!r)throw new Error("Email not found in token");let n=await o.findOneAndUpdate({_id:t.userId,status:{$nin:["deleted","disabled"]},"emails.address":r,"emails.verified":{$ne:true}},{$set:{"emails.$.verified":true}},{returnDocument:"after"});if(!n)throw await o.findOne({_id:t.userId,"emails.address":r})?new Error("Email is already verified"):new Error("Email address not found for this user");return await q$1.deleteOne({_id:t._id}),{userDoc:n,email:r}}async function no(e){let t=a$2("_system.site.url"),o=h().verification?.redirectUrl||h().emailVerifiedRedirectUrl||t||"/";try{let r=z$1.string().parse(e.query.token),{userDoc:n}=await Rr(r);y().onAfterEmailVerification?.({provider:"email",user:n,session:null,connectionInfo:{baseUrl:t,ip:e.req.ip||e.req.socket.remoteAddress,userAgent:e.headers["user-agent"],acceptLanguage:e.headers["accept-language"],referrer:e.headers.referer}});let{authToken:s}=await k(n._id);return l(e.res,s),{status:301,headers:{"Referrer-Policy":"no-referrer"},redirect:`${o}?status=verified`}}catch(r){let n=r instanceof Error?r.message:"An unexpected error occurred";return r instanceof Error&&(y().onEmailVerificationError?.({provider:"email",error:r,session:null,connectionInfo:{baseUrl:t,ip:e.req.ip||e.req.socket.remoteAddress,userAgent:e.headers["user-agent"],acceptLanguage:e.headers["accept-language"],referrer:e.headers.referer}}),console.error("Error verifying email:",r)),{status:301,headers:{"Referrer-Policy":"no-referrer"},redirect:`${o}?status=error&message=${encodeURIComponent(n)}`}}}async function ze({userId:e,email:t,baseUrl:o}){let r=a$2("_system.site.url")||o;if(h().provider){let n=h().provider,i=randomBytes(32).toString("hex"),s=new Date(Date.now()+a$1.hours(24));await q$1.insertOne({userId:e,email:t,token:i,createdAt:new Date,expiresAt:s});let a=`${r}/api/_internal/auth/verify-email?token=${i}`,l=(h()?.verification?.template||ro)({name:"",email:t,verificationUrl:a}),d=x$1(l);await n?.sendEmail({to:t,from:h()?.from||"noreply@modelence.com",subject:h()?.verification?.subject||"Verify your email address",text:d,html:l});}}var qe={success:true,message:"If that email is registered and not yet verified, a verification email has been sent"};async function io(e,{connectionInfo:t}){let o$1=x(e.email),r=await o.findOne({"emails.address":o$1,status:{$nin:["deleted","disabled"]}},{collation:{locale:"en",strength:2}});if(!r)return qe;let n=r.emails?.find(i=>i.address.toLowerCase()===o$1);if(!n||n.verified)return qe;if(!h().provider)throw new Error("Email provider is not configured");return await C({bucket:"verification",type:"user",value:r._id.toString(),message:"Please wait at least 60 seconds before requesting another verification email"}),await ze({userId:r._id,email:o$1,baseUrl:t?.baseUrl}),qe}async function so(e,{user:t,session:o$1,connectionInfo:r}){let n=y();try{let i=e,{firstName:s,lastName:a,avatarUrl:c,handle:l}=i,d=x(i.email),p=Se(i.password),f=r?.ip;if(f&&await C({bucket:"signupAttempt",type:"ip",value:f}),!n.allowDisposableEmails&&await ve(d))throw new Error("Please use a permanent email address");let b=await o.findOne({"emails.address":d},{collation:{locale:"en",strength:2}});if(b){let he=b.emails?.find(P=>P.address.toLowerCase()===d);throw b.status==="disabled"?new Error("User is marked for deletion, please contact support if you want to restore the account."):new Error(`User with email already exists: ${he?.address}`)}await n.onBeforeSignup?.({email:d,firstName:s,lastName:a,handle:l,provider:"email",connectionInfo:r}),f&&await C({bucket:"signup",type:"ip",value:f});let v=ke({firstName:s,lastName:a,avatarUrl:c,handle:l});await n.validateSignup?.({email:d,password:p,...v});let S;if(v.handle)S=await O(v.handle,d);else if(n.generateHandle){let he=await n.generateHandle({email:d,firstName:v.firstName,lastName:v.lastName});S=await O(he,d,{throwOnConflict:!1});}else S=await O(void 0,d);let re=await br.hash(p,10),ne=await o.insertOne({handle:S,status:"active",emails:[{address:d,verified:!1}],createdAt:new Date,authMethods:{password:{hash:re}},...v.firstName!==void 0&&{firstName:v.firstName},...v.lastName!==void 0&&{lastName:v.lastName},...v.avatarUrl!==void 0&&{avatarUrl:v.avatarUrl}}),H=await o.findOne({_id:ne.insertedId},{readPreference:"primary"});if(!H)throw new Error("User not found");return await ze({userId:ne?.insertedId,email:d,baseUrl:r?.baseUrl}),n.onAfterSignup?.({provider:"email",user:H,session:o$1,connectionInfo:r}),n.signup?.onSuccess?.(H),ne.insertedId}catch(i){throw i instanceof Error&&(n.onSignupError?.({provider:"email",error:i,session:o$1,connectionInfo:r}),n.signup?.onError?.(i)),i}}function $(e){return createHash("sha256").update(e).digest("hex")}var Je="resetPasswordToken",Tr="/api/_internal/",lo={httpOnly:true,secure:process.env.NODE_ENV==="production",sameSite:"lax",path:Tr};async function uo(e){return r.findOne({token:$(e)})}async function ao(e){return r.findOneAndDelete({_id:e})}function Mr({email:e,resetUrl:t}){return `
|
|
8
|
+
<p>Hi,</p>
|
|
9
|
+
<p>We received a request to reset your password for ${e}.</p>
|
|
10
|
+
<p>Click the link below to reset your password:</p>
|
|
11
|
+
<p><a href="${t}">${t}</a></p>
|
|
12
|
+
<p>This link will expire in 1 hour.</p>
|
|
13
|
+
<p>If you did not request this password reset, please ignore this email.</p>
|
|
14
|
+
`}var We={success:true,message:"If an account with that email exists, a password reset link has been sent"};async function mo(e,{connectionInfo:t}){let o$1=x(e.email),r$1=t?.ip;r$1&&await C({bucket:"passwordReset",type:"ip",value:r$1}),await C({bucket:"passwordReset",type:"email",value:o$1});let n=await o.findOne({"emails.address":o$1,status:{$nin:["deleted","disabled"]}},{collation:{locale:"en",strength:2}});if(!n||!n.authMethods?.password)return We;let i=h().provider;if(!i)throw new Error("Email provider is not configured");let s=randomBytes(32).toString("hex"),a=Date.now(),c=new Date(a),l=new Date(a+a$1.hours(1));await r.insertOne({userId:n._id,email:o$1,token:$(s),createdAt:c,expiresAt:l});let d=a$2("_system.site.url")||t?.baseUrl;if(!d)throw new Error("Unable to build password reset link: set _system.site.url (MODELENCE_SITE_URL)");let p=`${d}/api/_internal/auth/reset-password?token=${s}`,b=(h()?.passwordReset?.template||Mr)({email:o$1,resetUrl:p,name:""}),v=x$1(b);return await i.sendEmail({to:o$1,from:h()?.from||"noreply@modelence.com",subject:h()?.passwordReset?.subject||"Reset your password",text:v,html:b}),We}async function po(e){let t=a$2("_system.site.url")||`${e.req.protocol}://${e.req.get("host")}`,o=Ae(t,h().passwordReset?.redirectUrl);try{let r=z$1.string().parse(e.query.token),n=await uo(r);if(!n||n.expiresAt<new Date)throw new Error("This password reset link is invalid or has expired.");return e.res.cookie(Je,r,{...lo,maxAge:a$1.hours(1)}),{status:302,headers:{"Referrer-Policy":"no-referrer"},redirect:o}}catch(r){return console.error("Error handling password reset landing:",r),{status:302,headers:{"Referrer-Policy":"no-referrer"},redirect:`${o}?status=error&message=${encodeURIComponent("This password reset link is invalid or has expired.")}`}}}async function fo(e,t){let o$1=t.req?.cookies?.[Je];!o$1&&e.token&&console.warn("[modelence] resetPassword received a token via request args instead of the httpOnly cookie. This path is deprecated and will be removed; ensure password reset emails link to /api/_internal/auth/reset-password so the token is exchanged server-side.");let r=z$1.string().parse(o$1??e.token),n=Se(e.password),i=()=>{t.res?.clearCookie(Je,lo);},s=await uo(r);if(!s)throw i(),new Error("Invalid or expired reset token");if(s.expiresAt<new Date)throw await ao(s._id),i(),new Error("Reset token has expired");let a=await o.findOne({_id:s.userId});if(!a)throw new Error("User not found");let c=await br.hash(n,10);if(!await ao(s._id))throw i(),new Error("Invalid or expired reset token");return await o.updateOne({_id:a._id},{$set:{"authMethods.password.hash":c}}),s.email&&await o.updateOne({_id:a._id,"emails.address":s.email},{$set:{"emails.$.verified":true}}),await j(a._id),i(),{success:true,message:"Password has been reset successfully"}}function go({name:e,email:t,magicLinkUrl:o,code:r}){return `
|
|
15
|
+
<p>Hi${e?` ${e}`:""},</p>
|
|
16
|
+
<p>Click the link below to sign in as ${t}:</p>
|
|
17
|
+
<p><a href="${o}">${o}</a></p>
|
|
18
|
+
<p>Or enter this one-time code in the app:</p>
|
|
19
|
+
<p><strong style="font-size: 24px; letter-spacing: 4px;">${r}</strong></p>
|
|
20
|
+
<p>The link and code can only be used once and will expire in 15 minutes.</p>
|
|
21
|
+
<p>If you did not request this, please ignore this email.</p>
|
|
22
|
+
`}var Ke="magicLinkToken",Nr="/api/_internal/",yo={httpOnly:true,secure:process.env.NODE_ENV==="production",sameSite:"lax",path:Nr},Eo=15,ho=6,$r=5;function Qe(){return !!y().magicLink?.enabled}async function bo(e){return s.findOne({token:$(e)})}async function me(e){return s.findOneAndDelete({_id:e})}var wo={success:true,message:"If this email can be used to sign in, a link has been sent"};async function vo(e,{connectionInfo:t}){if(!Qe())throw new Error("Magic link authentication is not enabled");let o$1=x(e.email),r=t?.ip;r&&await C({bucket:"magicLink",type:"ip",value:r}),await C({bucket:"magicLink",type:"email",value:o$1});let n=h().provider;if(!n)throw new Error("Email provider is not configured");if(!y().allowDisposableEmails&&await ve(o$1))throw new Error("Please use a permanent email address");let i=await o.findOne({"emails.address":o$1},{collation:{locale:"en",strength:2}});if(i&&(i.status==="disabled"||i.status==="deleted"))return wo;let s$1=randomBytes(32).toString("hex"),a=randomInt(0,10**ho).toString().padStart(ho,"0"),c=Date.now(),l=new Date(c),d=new Date(c+a$1.minutes(Eo));await s.insertOne({email:o$1,token:$(s$1),code:$(a),attempts:0,createdAt:l,expiresAt:d});let p=a$2("_system.site.url")||t?.baseUrl;if(!p)throw new Error("Unable to build magic link: set _system.site.url (MODELENCE_SITE_URL)");let f=`${p}/api/_internal/auth/magic-link?token=${s$1}`,v=(h()?.magicLink?.template||go)({email:o$1,magicLinkUrl:f,code:a,name:""}),S=x$1(v);return await n.sendEmail({to:o$1,from:h()?.from||"noreply@modelence.com",subject:h()?.magicLink?.subject||"Your sign-in link",text:S,html:v}),wo}async function Co(e){let t=a$2("_system.site.url")||`${e.req.protocol}://${e.req.get("host")}`,o=Ae(t,h().magicLink?.redirectUrl);try{let r=z$1.string().parse(e.query.token),n=await bo(r);if(!n||n.expiresAt<new Date)throw new Error("This sign-in link is invalid or has expired.");return e.res.cookie(Ke,r,{...yo,maxAge:a$1.minutes(Eo)}),{status:302,headers:{"Referrer-Policy":"no-referrer"},redirect:o}}catch(r){return console.error("Error handling magic link landing:",r),{status:302,headers:{"Referrer-Policy":"no-referrer"},redirect:`${o}?status=error&message=${encodeURIComponent("This sign-in link is invalid or has expired.")}`}}}async function ko(e,t){let{tokenDoc:o$1,session:r,connectionInfo:n,res:i,clearCookie:s}=t,a=y();try{if(e.status==="disabled"||e.status==="deleted")throw await me(o$1._id),s(),new Error("User account is not active");if(!await me(o$1._id))throw s(),new Error("Invalid or expired magic link");let d=!e.emails?.find(p=>p.address.toLowerCase()===o$1.email)?.verified;return await o.updateOne({_id:e._id,"emails.address":o$1.email},{$set:{"emails.$.verified":!0}}),await h$1(r.authToken,e._id),i&&l(i,r.authToken),d&&a.onAfterEmailVerification?.({provider:"magicLink",user:e,session:r,connectionInfo:n}),a.onAfterLogin?.({provider:"magicLink",user:e,session:r,connectionInfo:n}),s(),{user:B(e),session:{authToken:r.authToken}}}catch(c){throw c instanceof Error&&a.onLoginError?.({provider:"magicLink",error:c,session:r,connectionInfo:n}),c}}async function So(e){let{tokenDoc:t,session:o$1,connectionInfo:r,res:n,clearCookie:i}=e,s=t.email,a=y();try{await a.onBeforeSignup?.({email:s,provider:"magicLink",connectionInfo:r});let c=r?.ip;c&&await C({bucket:"signup",type:"ip",value:c});let l$1;if(a.generateHandle){let b=await a.generateHandle({email:s});l$1=await O(b,s,{throwOnConflict:!1});}else l$1=await O(void 0,s);if(!await me(t._id))throw i(),new Error("Invalid or expired magic link");let p=await o.insertOne({handle:l$1,status:"active",emails:[{address:s,verified:!0}],createdAt:new Date,authMethods:{}}),f=await o.findOne({_id:p.insertedId},{readPreference:"primary"});if(!f)throw new Error("User not found");return await h$1(o$1.authToken,f._id),n&&l(n,o$1.authToken),a.onAfterSignup?.({provider:"magicLink",user:f,session:o$1,connectionInfo:r}),i(),{user:B(f),session:{authToken:o$1.authToken}}}catch(c){throw c instanceof Error&&a.onSignupError?.({provider:"magicLink",error:c,session:o$1,connectionInfo:r}),c}}async function Ao(e,t){let{session:o$1,connectionInfo:r,res:n,req:i}=t;if(!o$1)throw new Error("Session is not initialized");if(!Qe())throw new Error("Magic link authentication is not enabled");let s=z$1.string().parse(i?.cookies?.[Ke]),a=()=>{n?.clearCookie(Ke,yo);},c=await bo(s);if(!c)throw a(),new Error("Invalid or expired magic link");if(c.expiresAt<new Date)throw await me(c._id),a(),new Error("Magic link has expired");let l=await o.findOne({"emails.address":c.email},{collation:{locale:"en",strength:2}}),d={tokenDoc:{_id:c._id,email:c.email},session:o$1,connectionInfo:r,res:n,clearCookie:a};return l?ko(l,d):So(d)}async function xo(e,t){let{session:o$1,connectionInfo:r,res:n}=t;if(!o$1)throw new Error("Session is not initialized");if(!Qe())throw new Error("Magic link authentication is not enabled");let i=x(e.email),s$1=z$1.string().parse(e.code).replace(/[\s-]/g,""),a=r?.ip;a&&await C({bucket:"oneTimeCode",type:"ip",value:a}),await C({bucket:"oneTimeCode",type:"email",value:i});let c=await s.findOne({email:i,code:$(s$1),attempts:{$lt:$r}});if(!c)throw await s.updateMany({email:i},{$inc:{attempts:1}}),new Error("Invalid or expired code");if(c.expiresAt<new Date)throw await me(c._id),new Error("Code has expired");let l=await o.findOne({"emails.address":i},{collation:{locale:"en",strength:2}}),d={tokenDoc:{_id:c._id,email:c.email},session:o$1,connectionInfo:r,res:n,clearCookie:()=>{}};return l?ko(l,d):So(d)}function Ro(e){return `${e.bucket}
|
|
23
|
+
${e.type}
|
|
24
|
+
${e.window}`}function Dr(){return [{bucket:"signup",type:"ip",window:a$1.minutes(15),limit:20},{bucket:"signup",type:"ip",window:a$1.days(1),limit:200},{bucket:"signupAttempt",type:"ip",window:a$1.minutes(15),limit:50},{bucket:"signupAttempt",type:"ip",window:a$1.days(1),limit:500},{bucket:"signin",type:"ip",window:a$1.minutes(15),limit:50},{bucket:"signin",type:"ip",window:a$1.days(1),limit:500},{bucket:"verification",type:"user",window:a$1.seconds(60),limit:1},{bucket:"verification",type:"user",window:a$1.days(1),limit:10},{bucket:"passwordReset",type:"ip",window:a$1.minutes(15),limit:10},{bucket:"passwordReset",type:"ip",window:a$1.days(1),limit:100},{bucket:"passwordReset",type:"email",window:a$1.hours(1),limit:5},{bucket:"passwordReset",type:"email",window:a$1.days(1),limit:10},{bucket:"magicLink",type:"ip",window:a$1.minutes(15),limit:10},{bucket:"magicLink",type:"ip",window:a$1.days(1),limit:100},{bucket:"magicLink",type:"email",window:a$1.hours(1),limit:5},{bucket:"magicLink",type:"email",window:a$1.days(1),limit:10},{bucket:"oneTimeCode",type:"ip",window:a$1.minutes(15),limit:20},{bucket:"oneTimeCode",type:"ip",window:a$1.days(1),limit:100},{bucket:"oneTimeCode",type:"email",window:a$1.hours(1),limit:10},{bucket:"oneTimeCode",type:"email",window:a$1.days(1),limit:20}]}function jr(e){let t=[],o=["signup","signupAttempt","signin","verification","passwordReset","magicLink","oneTimeCode"];for(let r of o){let n=e[r];if(n!==void 0)for(let i of n)t.push({bucket:r,...i});}return t}function Xe(e={}){let t=Dr(),o=jr(e),r=new Map;for(let s of o)r.set(Ro(s),s);let n=[],i=new Set;for(let s of t){let a=Ro(s),c=r.get(a);c!==void 0?(n.push(c),i.add(a)):n.push(s);}for(let[s,a]of r)i.has(s)||n.push(a);return n}var Ze=new a("_system.user",{stores:[o,p,q$1,r,s],queries:{getOwnProfile:Zt},mutations:{signupWithPassword:so,loginWithPassword:Qt,logout:Xt,resendEmailVerification:io,sendResetPasswordToken:mo,resetPassword:fo,sendMagicLink:vo,loginWithMagicLink:Ao,loginWithOneTimeCode:xo,updateProfile:eo,unlinkOAuthProvider:to},cronJobs:{updateDisposableEmailList:Ft},rateLimits:Xe(),configSchema:{"auth.email.enabled":{type:"boolean",isPublic:true,default:true},"auth.email.from":{type:"string",isPublic:false,default:""},"auth.email.verification":{type:"boolean",isPublic:true,default:true},"auth.google.enabled":{type:"boolean",isPublic:true,default:false},"auth.google.clientId":{type:"string",isPublic:false,default:""},"auth.google.clientSecret":{type:"secret",isPublic:false,default:""},"auth.github.enabled":{type:"boolean",isPublic:true,default:false},"auth.github.clientId":{type:"string",isPublic:false,default:""},"auth.github.clientSecret":{type:"secret",isPublic:false,default:""}},routes:[{path:"/api/_internal/auth/verify-email",handlers:{get:no}},{path:"/api/_internal/auth/reset-password",handlers:{get:po}},{path:"/api/_internal/auth/magic-link",handlers:{get:Co}}]});var Hr={withoutRemoteServer:{MONGODB_URI:"_system.mongodbUri",MONGODB_POOL_SIZE:"_system.mongodbPoolSize",MODELENCE_AUTH_GOOGLE_ENABLED:"_system.user.auth.google.enabled",MODELENCE_AUTH_GOOGLE_CLIENT_ID:"_system.user.auth.google.clientId",MODELENCE_AUTH_GOOGLE_CLIENT_SECRET:"_system.user.auth.google.clientSecret",MODELENCE_AUTH_GITHUB_ENABLED:"_system.user.auth.github.enabled",MODELENCE_AUTH_GITHUB_CLIENT_ID:"_system.user.auth.github.clientId",MODELENCE_AUTH_GITHUB_CLIENT_SECRET:"_system.user.auth.github.clientSecret",MODELENCE_AUTH_GITHUB_CLIENT_SCOPES:"_system.user.auth.github.scopes",MODELENCE_EMAIL_RESEND_API_KEY:"_system.email.resend.apiKey",MODELENCE_EMAIL_AWS_SES_REGION:"_system.email.awsSes.region",MODELENCE_EMAIL_AWS_SES_ACCESS_KEY_ID:"_system.email.awsSes.accessKeyId",MODELENCE_EMAIL_AWS_SES_SECRET_ACCESS_KEY:"_system.email.awsSes.secretAccessKey",MODELENCE_EMAIL_SMTP_HOST:"_system.email.smtp.host",MODELENCE_EMAIL_SMTP_PORT:"_system.email.smtp.port",MODELENCE_EMAIL_SMTP_USER:"_system.email.smtp.user",MODELENCE_EMAIL_SMTP_PASS:"_system.email.smtp.pass",MODELENCE_SITE_URL:"_system.site.url",MODELENCE_ENV_TYPE:"_system.env.type",MODELENCE_MULTI_INSTANCE:"_system.multiInstance",MODELENCE_ENV:"_system.env",GOOGLE_AUTH_ENABLED:"_system.user.auth.google.enabled",GOOGLE_AUTH_CLIENT_ID:"_system.user.auth.google.clientId",GOOGLE_AUTH_CLIENT_SECRET:"_system.user.auth.google.clientSecret"},withRemoteServer:{MODELENCE_SITE_URL:"_system.site.url"}};function Gr(e,t){if(t==="number"){let o=Number(e);if(isNaN(o))throw new Error(`Invalid number value for config: ${e}`);return o}if(t==="boolean"){if(e.toLowerCase()==="true")return true;if(e.toLowerCase()==="false")return false;throw new Error(`Invalid boolean value for config: ${e}`)}return e}function Fr(e,t){let o=[];for(let[r,n]of Object.entries(e)){let i=process.env[r],s=t[n];if(i){let a=s?.type??"string";o.push({key:n,type:a,value:Gr(i,a)});}}return o}function xe(e,t="withoutRemoteServer"){let o=Hr[t];return Fr(o,e)}async function Oo({configSchema:e,cronJobsMetadata:t,stores:o,roles:r}){let n=process.env.MODELENCE_CONTAINER_ID;if(!n)throw new Error("Unable to connect to Modelence Cloud: MODELENCE_CONTAINER_ID is not set");try{let i=(o??[]).map(a=>({name:a.getName(),schema:a.getSerializedSchema(),collections:[a.getName()],version:2,indexes:a.getIndexes(),searchIndexes:a.getSearchIndexes(),indexCreationMode:a.getIndexCreationMode()})),s=await _("/api/connect","POST",{hostname:Vr.hostname(),containerId:n,dataModels:i,configSchema:e,cronJobsMetadata:t,roles:r});if(s.status==="error")throw new Error(s.error);return console.log("Successfully connected to Modelence Cloud"),s}catch(i){throw console.error("Unable to connect to Modelence Cloud:",i),i}}async function _o(){return _("/api/configs","GET")}async function Lo(){return await _("/api/sync","POST",{containerId:process.env.MODELENCE_CONTAINER_ID})}async function _(e,t,o){let{MODELENCE_SERVICE_ENDPOINT:r,MODELENCE_SERVICE_TOKEN:n}=process.env;if(!r)throw new Error("Unable to connect to Modelence Cloud: MODELENCE_SERVICE_ENDPOINT is not set");let i=await fetch(`${r}${e}`,{method:t,headers:{Authorization:`Bearer ${n}`,...o?{"Content-Type":"application/json"}:{}},body:o?JSON.stringify(o):void 0});if(!i.ok){let s=await i.text(),a,c=s;try{a=JSON.parse(s);let d=a.error;if(typeof d=="string")c=d;else if(d&&typeof d=="object"){let p=d.message;typeof p=="string"&&(c=p);}}catch{}let l=new Error(`Unable to connect to Modelence Cloud: HTTP status: ${i.status}, ${c}`);throw a!==void 0&&(l.responseBody=a),l.status=i.status,l}if(!(i.status===204||i.headers?.get("content-length")==="0"))return await i.json()}var et=false,Br=a$1.seconds(10);function Po(){setInterval(async()=>{if(!et){et=true;try{await Lo();}catch(e){console.error("Error syncing status",e);}try{await qr();}catch(e){console.error("Error syncing config",e);}et=false;}},Br);}function tt(e){c$1(e),c$1(xe(d$2(),"withRemoteServer"));}async function qr(){let{configs:e}=await _o();tt(e);}var q=new b("_modelenceLocks",{schema:{_id:c.string(),instanceId:c.string(),acquiredAt:c.date(),resource:c.string()},indexes:[{key:{resource:1},unique:true},{key:{resource:1,instanceId:1}},{key:{resource:1,acquiredAt:1}}],indexCreationMode:"blocking"});var z={},To=a$1.seconds(10),No=randomBytes(32).toString("base64url"),Jr=a$1.seconds(30),Z=new Map,ot=e=>e instanceof MongoError&&e.code===11e3,Mo=(e,t)=>typeof e.keyPattern=="object"&&e.keyPattern!==null&&Object.prototype.hasOwnProperty.call(e.keyPattern,t),Kr=async({error:e,resource:t})=>{if(Mo(e,"resource"))return true;if(Mo(e,"_id"))return false;let o=await q.findOne({resource:t});return !!o&&o._id!==t},Io=async({resource:e,staleThresholdDate:t,instanceId:o})=>{let r=await q.upsertOne({_id:e,$or:[{instanceId:o},{acquiredAt:{$lt:t}}]},{$set:{resource:e,instanceId:o,acquiredAt:new Date},$setOnInsert:{_id:e}});return r.upsertedCount>0||r.modifiedCount>0},$o=async({resource:e,instanceId:t,staleThresholdDate:o})=>{let r=o?{resource:e,_id:{$ne:e},$or:[{instanceId:t},{acquiredAt:{$lt:o}}]}:{resource:e,instanceId:t};return (await q.deleteOne(r)).deletedCount>0},Yr=e=>{let t=e,o=Z.get(t);o&&(o.stopRequested=true,o.timer&&(clearTimeout(o.timer),o.timer=null),Z.delete(t));},Uo=({resource:e,lockDuration:t,instanceId:o})=>{let r=Math.floor(t/3),n=e,i=Z.get(n);if(i&&!i.stopRequested&&i.heartbeatInterval===r&&i.lockDuration===t)return;i&&(i.stopRequested=true,i.timer&&(clearTimeout(i.timer),i.timer=null),Z.delete(n));let s={timer:null,stopRequested:false,lockDuration:t,heartbeatInterval:r},a=()=>{s.timer=setTimeout(()=>{W(e,{lockDuration:t,bypassCache:true,instanceId:o}).then(c=>{c||(s.stopRequested=true,j$2(`Lost lock while refreshing heartbeat: ${e}`,{source:"lock",resource:e,instanceId:o}));}).finally(()=>{if(s.stopRequested){Z.delete(n);return}a();});},r);};Z.set(n,s),a();};async function W(e,{lockDuration:t=Jr,successfulLockCacheDuration:o=To,failedLockCacheDuration:r=To,heartbeat:n,bypassCache:i,instanceId:s=No}={}){let a=Date.now();if(!i&&z[e]&&a<z[e].expiresAt)return z[e].value&&n&&Uo({resource:e,lockDuration:t,instanceId:s}),z[e].value;let c=new Date(a-t);j$2(`Attempting to acquire lock: ${e}`,{source:"lock",resource:e,instanceId:s});try{let l=await Qr({resource:e,staleThresholdDate:c,instanceId:s});return z[e]={value:l,expiresAt:a+(l?o:r)},l?(n&&Uo({resource:e,lockDuration:t,instanceId:s}),j$2(`Lock acquired: ${e}`,{source:"lock",resource:e,instanceId:s})):j$2(`Failed to acquire lock (already held): ${e}`,{source:"lock",resource:e,instanceId:s}),l}catch{return z[e]={value:false,expiresAt:a+r},j$2(`Failed to acquire lock (already held): ${e}`,{source:"lock",resource:e,instanceId:s}),false}}var Qr=async({resource:e,staleThresholdDate:t,instanceId:o})=>{try{return await Io({resource:e,staleThresholdDate:t,instanceId:o})}catch(r){if(ot(r)&&await Kr({error:r,resource:e})){if(!await $o({resource:e,staleThresholdDate:t,instanceId:o}))return false;try{return await Io({resource:e,staleThresholdDate:t,instanceId:o})}catch(i){if(ot(i))return false;throw i}}if(ot(r))return false;throw r}};async function pe(e,{instanceId:t=No}={}){Yr(e);try{let o=await q.deleteOne({_id:e,instanceId:t});return o.deletedCount===0?await $o({resource:e,instanceId:t}):o.deletedCount>0}catch{return false}finally{delete z[e];}}var J={},rt=null,nt=new b("_modelenceCronJobs",{schema:{alias:c.string(),lastStartDate:c.date().optional()},indexes:[{key:{alias:1},unique:true,background:true}]});function jo(e,{description:t="",interval:o,timeout:r=Math.min(Math.max(o,a$1.minutes(1)),a$1.days(1)),handler:n}){if(J[e])throw new Error(`Duplicate cron job declaration: '${e}' already exists`);if(rt)throw new Error(`Unable to add a cron job - cron jobs have already been initialized: [${e}]`);if(o<a$1.seconds(5))throw new Error(`Cron job interval should not be less than 5 second [${e}]`);if(r>a$1.days(1))throw new Error(`Cron job timeout should not be longer than 1 day [${e}]`);J[e]={alias:e,params:{description:t,interval:o,timeout:r},handler:n,state:{isRunning:false}};}async function Ho(){if(rt)throw new Error("Cron jobs already started");let e=Object.keys(J);if(e.length>0){let t={alias:{$in:e}},o=await nt.fetch(t),r=Date.now();o.forEach(n=>{let i=J[n.alias];i&&(i.state.scheduledRunTs=n.lastStartDate?n.lastStartDate.getTime()+i.params.interval:r);}),Object.values(J).forEach(n=>{n.state.scheduledRunTs||(n.state.scheduledRunTs=r);}),rt=setInterval(Xr,a$1.seconds(1));}}async function Xr(){let e=Date.now();await W("cron",{successfulLockCacheDuration:a$1.seconds(10),failedLockCacheDuration:a$1.seconds(30)})&&Object.values(J).forEach(async o=>{let{params:r,state:n}=o;if(n.isRunning){n.startTs&&n.startTs+r.timeout<e&&(n.isRunning=false);return}n.scheduledRunTs&&n.scheduledRunTs<=e&&await Zr(o);});}async function Zr(e){let{alias:t,params:o,handler:r,state:n}=e;n.isRunning=true,n.startTs=Date.now(),await nt.updateOne({alias:t},{$set:{lastStartDate:new Date(n.startTs)}});let i=m$1("cron",`cron:${t}`);try{await r(),Do(n,o),i.end("success");}catch(s){Do(n,o);let a=s instanceof Error?s:new Error(String(s));n$1(a),i.end("error"),console.error(`Error in cron job '${t}':`,s);}}function Do(e,t){e.scheduledRunTs=e.startTs?e.startTs+t.interval:Date.now(),e.startTs=void 0,e.isRunning=false;}function Go(){return Object.values(J).map(({alias:e,params:t})=>({alias:e,description:t.description,interval:t.interval,timeout:t.timeout}))}var Fo=new a("_system.cron",{stores:[nt]});function Vo(e){let t=[...new Set(e)],o=new Map;for(let i of t){let s=i.getChainRoot();o.set(s,s.getChainTail());}let r=[...new Set(o.values())],n=new Map;for(let[i,s]of o){let a=s.getName(),c=n.get(a);if(c!==void 0&&c!==i)throw new Error(`Store collision: multiple unrelated stores use collection name '${a}'. Use .extend() to create a single extension chain instead of independent stores.`);n.set(a,i);}return {storesToInit:t,effectiveStores:r}}var it=new a("_system.lock",{stores:[q]});var fe=new b("_modelenceMigrations",{schema:{version:c.number(),status:c.enum(["completed","failed"]),description:c.string().optional(),output:c.string().optional(),appliedAt:c.date()},indexes:[{key:{version:1},unique:true},{key:{version:1,status:1}}]});async function st(e,{lockMode:t="acquire"}={}){if(e.length!==0){if(t==="acquire"&&!await W("migrations")){k$1("Another instance is running migrations. Skipping migration run.",{source:"migrations"});return}try{let o=e.map(({version:s})=>s),r=await fe.fetch({version:{$in:o}}),n=new Set(r.map(({version:s})=>s)),i=e.filter(({version:s})=>!n.has(s));if(i.length===0)return;k$1(`Running migrations (${i.length})...`,{source:"migrations"});for(let{version:s,description:a,handler:c}of i){k$1(`Running migration v${s}: ${a}`,{source:"migrations"});try{let d=(await c()||"").toString().trim(),p=15*1024*1024,f=d.length>p?d.slice(0,p)+`
|
|
25
|
+
[Output truncated - exceeded size limit]`:d;await fe.upsertOne({version:s},{$set:{version:s,status:"completed",description:a,output:f,appliedAt:new Date}}),k$1(`Migration v${s} complete`,{source:"migrations"});}catch(l){l instanceof Error&&(await fe.upsertOne({version:s},{$set:{version:s,status:"failed",description:a,output:l.message||"",appliedAt:new Date}}),k$1(`Migration v${s} is failed: ${l.message}`,{source:"migrations"}));}}}finally{t==="acquire"&&await pe("migrations");}}}function Bo(e){setTimeout(()=>{st(e).catch(t=>{console.error("Error running migrations:",t);});},0);}var qo=new a("_system.migration",{stores:[fe]});var zo=new a("_system.rateLimit",{stores:[ue]});async function en({filePath:e,contentType:t,visibility:o}){return await _("/api/files/upload","POST",{filePath:e,contentType:t,visibility:o})}async function tn(e){await _("/api/files/delete","POST",{filePath:e});}async function on(e){return await _("/api/files/download","POST",{filePath:e})}async function rn(e){return await _("/api/files/url","POST",{filePath:e})}var Wo=new a("_system.files",{});function at(e){return e.replace(/[<>&\u2028\u2029]/g,t=>`\\u${t.charCodeAt(0).toString(16).padStart(4,"0")}`)}var ge="./.modelence/build/client".replace(/\\/g,"/"),Ko="./.modelence/build/ssr".replace(/\\/g,"/"),Yo="/index.tsx",dn=/(<div\b[^>]*\bid\s*=\s*["']root["'][^>]*>)\s*<\/div>/i,un="</head>",ct=class{constructor(){this.ssrEnabled=false;this.ssrTransportInstalled=false;this.prodEntryLoaded=false;}enableSsr(){this.ssrEnabled=true;}async init({httpServer:t}){if(this.config=await yn(this.isDev()?t:void 0,{ssr:this.ssrEnabled}),this.isDev())console.log("Starting Vite dev server..."),this.viteServer=await createServer(this.config);else if(this.ssrEnabled){let o=K.resolve(process.cwd(),Ko,"index.mjs");if(!Re.existsSync(o))throw new Error(`Modelence: SSR is enabled (startApp({ ssr: true })) but the SSR bundle is missing at ${o}.
|
|
26
|
+
|
|
27
|
+
This usually means \`postBuildCommand\` is set in modelence.config.ts, which replaces the default Vite client build (and the SSR build along with it). Either:
|
|
28
|
+
\u2022 remove \`postBuildCommand\` so Modelence builds the SSR bundle, or
|
|
29
|
+
\u2022 remove \`ssr: true\` from startApp() if your custom toolchain handles SSR itself.`)}if(this.ssrEnabled&&!this.ssrTransportInstalled){let{installSsrCallMethodTransport:o}=await import('./transport-UBIBRQF5.js');o(),this.ssrTransportInstalled=true;}}middlewares(){if(this.isDev())return this.viteServer?.middlewares??[];let t=this.ssrEnabled?{index:false}:void 0,o=[j$1.static(ge,t)];return this.config?.publicDir&&o.push(j$1.static(this.config.publicDir,t)),o}async handler(t,o){if(this.ssrEnabled&&mn(t)){if(t.method==="HEAD"){o.setHeader("Content-Type","text/html; charset=utf-8"),o.setHeader("Cache-Control","no-store"),o.status(200).end();return}try{await this.handleSsr(t,o);}catch(r){if(this.isDev()&&this.viteServer&&r instanceof Error&&this.viteServer.ssrFixStacktrace(r),console.error("SSR render error:",{url:t.originalUrl,method:t.method,userAgent:t.get("user-agent"),error:r}),o.headersSent){o.end();return}this.serveStaticShell(o);}return}if(this.ssrEnabled){o.status(404).end();return}this.serveStaticShell(o);}async handleSsr(t,o){let r=await this.getTemplate(t.originalUrl),n=await this.captureSsrSnapshot();if(!n)throw new Error("Modelence SSR is enabled but no SSR snapshot was captured. Make sure 'src/client/index.tsx' calls renderApp(...) from 'modelence/client'.");let[{renderSsrTreeStream:i},{getCallContext:s},a]=await Promise.all([import('./render-HDPCEI2O.js'),import('./server-WAXWRUOY.js'),import('./collectCss-4YETFI7P.js')]),c=await s(t,o),l=this.collectCssAssets(a);gn(o,a.buildEarlyHintsLink(l));let{sessionState:d,pipe:p,getQueryState:f}=await i({callContext:c,loadingElement:n.loadingElement,routesElement:n.routesElement,router:n.router,location:t.originalUrl}),{prelude:b,rootOpenTag:v,epilogue:S}=pn(r),re=fn(b,a.renderStylesheetLinks(l));o.setHeader("Content-Type","text/html; charset=utf-8"),o.setHeader("Cache-Control","no-store"),o.status(200),o.write(re),o.write(`<script id="__MODELENCE_STATE__" type="application/json">${at(d)}</script>`),o.write(v),await p(o),o.write("</div>"),o.write(`<script id="__MODELENCE_QUERY_STATE__" type="application/json">${at(f())}</script>`),o.end(S);}collectCssAssets(t){return this.isDev()?this.viteServer?t.collectDevCssAssets(this.viteServer,Yo):{hrefs:[],source:"dev"}:(this.prodCssAssetsCache||(this.prodCssAssetsCache=t.loadProdCssAssets(ge)),this.prodCssAssetsCache)}async getTemplate(t){if(this.isDev()){let o=K.resolve(process.cwd(),"src/client/index.html"),r=Re.readFileSync(o,"utf-8");return this.viteServer&&(r=await this.viteServer.transformIndexHtml(t,r)),r}if(!this.prodTemplateCache){let o=K.resolve(process.cwd(),ge,"index.html");this.prodTemplateCache=Re.readFileSync(o,"utf-8");}return this.prodTemplateCache}async captureSsrSnapshot(){let{_getSsrSnapshot:t}=await import('./renderApp-Y3OJU4PO.js');if(this.isDev()){if(!this.viteServer)throw new Error("Vite dev server not initialized");return await this.viteServer.ssrLoadModule(Yo),t()}return this.prodEntryLoaded||(await import(K.resolve(process.cwd(),Ko,"index.mjs")),this.prodEntryLoaded=true),t()}serveStaticShell(t){if(this.isDev())try{t.setHeader("Cache-Control","no-store"),t.sendFile("index.html",{root:"./src/client"});}catch(o){console.error("Error serving index.html:",o),t.status(500).send("Internal Server Error");}else t.sendFile("index.html",{root:ge});}isDev(){return process.env.NODE_ENV!=="production"}};function mn(e){if(e.method!=="GET"&&e.method!=="HEAD")return false;let t=e.get("accept")??"";if(t&&!t.includes("text/html")&&!t.includes("*/*"))return false;let o=(e.path??e.url??"").split("?")[0];if(o.startsWith("/api/"))return false;let r=o.split("/").pop()??"",n=r.lastIndexOf(".");if(n>0){let i=r.slice(n).toLowerCase();if(i!==".html"&&i!==".htm")return false}return true}function pn(e){let t=e.match(dn);if(!t||t.index===void 0)throw new Error('SSR template is missing the expected `<div id="root"></div>` placeholder.');let o=e.slice(0,t.index),r=e.slice(t.index+t[0].length);return {prelude:o,rootOpenTag:t[1],epilogue:r}}function fn(e,t){if(!t)return e;let o=e.lastIndexOf(un);return o===-1?t+e:e.slice(0,o)+t+e.slice(o)}function gn(e,t){if(t.length===0)return;let o=e;if(typeof o.writeEarlyHints=="function")try{o.writeEarlyHints({link:t});}catch(r){process.env.NODE_ENV!=="production"&&console.warn("Modelence SSR: writeEarlyHints failed",r);}}async function hn(){let e=process.cwd();try{return (await loadConfigFromFile({command:"serve",mode:"development"},void 0,e))?.config||{}}catch(t){return console.warn("Could not load vite config:",t),{}}}function wn(e,t){let o=mergeConfig(e,t);if(o.plugins&&Array.isArray(o.plugins)){let r=new Set;o.plugins=o.plugins.flat().filter(n=>{if(!n||typeof n!="object"||Array.isArray(n))return true;let i=n.name;return !i||r.has(i)?false:(r.add(i),true)}).reverse(),o.plugins.reverse();}return o}async function yn(e,t={}){let o=process.cwd(),r=await hn(),n=[".eslintrc.js",".eslintrc.json",".eslintrc","eslint.config.js",".eslintrc.yml",".eslintrc.yaml"].find(a=>Re.existsSync(K.join(o,a))),i=[ln(),En()];if(n){let a=(await import('vite-plugin-eslint')).default;i.push(a({failOnError:false,include:["src/**/*.js","src/**/*.jsx","src/**/*.ts","src/**/*.tsx"],cwd:o,overrideConfigFile:K.resolve(o,n)}));}let s=defineConfig({plugins:i,build:{outDir:ge,emptyOutDir:true},server:{middlewareMode:true,hmr:e?{server:e}:void 0},appType:t.ssr?"custom":"spa",root:"./src/client",resolve:{alias:{"@":K.resolve(o,"src").replace(/\\/g,"/")}}});return wn(s,r)}function En(){return {name:"modelence-asset-handler",async transform(e,t){if(/\.(png|jpe?g|gif|svg|mpwebm|ogg|mp3|wav|flac|aac)$/.test(t))return process.env.NODE_ENV==="development",e}}}var Oe=new ct;function bn(e){return e?e.match(/^\s*"?([^"<]+?)"?\s*<[^>]+>\s*$/)?.[1]?.trim():void 0}function vn(e){if(e)return Array.isArray(e)?e:[e]}function Cn(e){return {to:Array.isArray(e.to)?e.to:[e.to],subject:e.subject,html:e.html,text:e.text,fromName:bn(e.from),replyTo:vn(e.replyTo)}}function kn(e){if(!(e instanceof Error))return new Error("Managed email send failed");let t=e.responseBody,o=t?.error?.code,r=t?.error?.message;return o&&r?new Error(`Managed email rejected (${o}): ${r}`):e}var Qo={async sendEmail(e){if(e.cc||e.bcc||e.attachments||e.headers)throw new Error("Modelence managed email does not support cc, bcc, attachments, or custom headers in v1. Configure your own provider (Resend, SES, SMTP) to use these features. See https://docs.modelence.com/email/managed.");try{await _("/api/email/send","POST",Cn(e));}catch(t){throw kn(t)}}};var lt=Object.freeze({});function Xo(e){lt=Object.freeze(Object.assign({},lt,e));}function Zo(){return lt}var dt=Object.freeze({});function er(e){dt=Object.freeze(Object.assign({},dt,e));}function _e(){return dt}async function Rn({modules:e$1=[],roles:t$1={},defaultRoles:o={},server:r=Oe,migrations:n$1=[],email:i={},auth:s={},security:a={},websocket:c={},ssr:l=false}){l&&r===Oe&&Oe.enableSsr(),tr.config(),tr.config({path:".modelence.env"});let d=!!process.env.MODELENCE_SERVICE_ENDPOINT;Dn().then(()=>{}).catch(()=>{});for(let P of e$1)if(P.name.toLowerCase().startsWith("_system."))throw new Error(`Invalid module name: '${P.name}'
|
|
30
|
+
|
|
31
|
+
The '_system.' prefix is reserved for internal use and cannot be used in user-defined modules.
|
|
32
|
+
|
|
33
|
+
Rename your module to something that does not start with '_system.'`);let p=[Ze,n,Fo,qo,zo,ce,it,Wo],f$1=[...p,...e$1];f(),_n(p),On(e$1),t(t$1,o);let b=Un(f$1);e(b);let v=Ln(f$1),S=Pn(f$1);Nn(f$1),Ze.rateLimits=Xe(s.rateLimits);let re=Tn(f$1);oo(re);let{storesToInit:ne,effectiveStores:H}=Vo(v);if(d){let{configs:P,environmentId:cr,appAlias:lr,environmentAlias:dr,telemetry:ur}=await Oo({configSchema:b,cronJobsMetadata:Go(),stores:H,roles:t$1});tt(P),g({environmentId:cr,appAlias:lr,environmentAlias:dr,telemetry:ur});}else c$1(xe(b));if(d&&!i.provider?Ge({...i,provider:Qo}):Ge(i),Kt(s),Xo(a),er({...c,provider:c.provider||Gt}),F()){await jt();let P=[...new Set([...ne,...H])];$n(P),await In(H,n$1);}else Bo(n$1);d&&(await h$2(),Po()),Ho().catch(console.error),await or(r,{combinedModules:f$1,channels:S});}function On(e){for(let t of e){for(let[o,r]of Object.entries(t.queries))y$1(`${t.name}.${o}`,r);for(let[o,r]of Object.entries(t.mutations))z$2(`${t.name}.${o}`,r);}}function _n(e){for(let t of e){for(let[o,r]of Object.entries(t.queries))A$1(`${t.name}.${o}`,r);for(let[o,r]of Object.entries(t.mutations))B$1(`${t.name}.${o}`,r);}}function Ln(e){return e.flatMap(t=>t.stores)}function Pn(e){return e.flatMap(t=>t.channels)}function Tn(e){return e.flatMap(t=>t.rateLimits)}function Mn(e,t){console.warn(`Failed to create indexes for store '${e}'. Continuing startup.`,t);}var ut="migrations";async function In(e,t){if(!await W(ut,{lockDuration:a$1.seconds(30),heartbeat:true}))return;let r,n;try{r=e.filter(a=>a.getIndexCreationMode()==="blocking"),n=e.filter(a=>a.getIndexCreationMode()==="background");for(let a of r)await mt(a,"full");for(let a of n)await mt(a,"drop-only");}catch(a){throw await pe(ut),a}let i=(async()=>{for(let a of n)await mt(a,"create-only");})(),s=st(t,{lockMode:"skip"});Promise.allSettled([i,s]).then(([a,c])=>{a.status==="rejected"&&console.error("Error creating background indexes:",a.reason),c.status==="rejected"&&console.error("Error running migrations:",c.reason);}).finally(async()=>{await pe(ut);});}async function mt(e,t="full"){let o=e.getName();try{await e.createIndexes(t);}catch(r){Mn(o,r);}}function Un(e){let t={};for(let o of e)for(let[r,n]of Object.entries(o.configSchema)){let i=`${o.name}.${r}`;if(i in t)throw new Error(`Duplicate config schema key: ${i} (${o.name})`);t[i]=n;}return t}function Nn(e){for(let t of e)for(let[o,r]of Object.entries(t.cronJobs))jo(`${t.name}.${o}`,r);}function $n(e){let t=be();if(!t)throw new Error("Failed to initialize stores: MongoDB client not initialized");for(let o of e)o.init(t);}async function Dn(){if(process.env.MODELENCE_TRACKING_ENABLED!=="false"){let t=process.env.MODELENCE_SERVICE_ENDPOINT??"https://cloud.modelence.com",o=process.env.MODELENCE_ENVIRONMENT_ID,r=await jn(),n=await import('./package-SYXH7HQF.js');await fetch(`${t}/api/track/app-start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectName:r.name,version:n.default.version,localHostname:Vr.hostname(),environmentId:o})});}}async function jn(){try{let e=K.join(process.cwd(),"package.json"),t=await Sn.readFile(e,"utf-8");return {name:JSON.parse(t).name||"unknown"}}catch{return {name:"unknown"}}}async function rr(e){await q$1.deleteMany({userId:e}),await r.deleteMany({userId:e});}async function Gn(e){await rr(e),await o.updateOne(e,{$set:{status:"disabled",disabledAt:new Date}});}async function Fn(e){await rr(e),await o.updateOne({_id:e},{$set:{handle:`deleted-${e}-${randomUUID()}`,status:"deleted",deletedAt:new Date,authMethods:{},emails:[]}});}var pt=class{constructor(t,o){this.category=t,this.canAccessChannel=o||null;}broadcast(t,o){let r=_e().provider;if(!r){l$1("Websockets provider should be added to startApp",{});return}r.broadcast({category:this.category,id:t,data:o});}};function Vn(e){if(!h().provider)throw new Error("Email provider is not configured, see https://docs.modelence.com/email for more details.");return h().provider?.sendEmail(e)}async function Le(e){return !e||typeof e!="string"?null:e$1(e)}function E(e,t,o){let r=y(),n=e.status(t);if(r.errorComponent)try{let i=r.errorComponent({error:o,statusCode:t});if(i)return n.send(i)}catch(i){console.error("Unhandled error in authConfig.errorComponent:",i);}return n.json({error:o})}async function ft(e,t){let{authToken:o}=await k(t);l(e,o),e.status(302),e.redirect("/");}async function qn(e,t,o$1,r,n){let i=y();try{if(o$1.status==="disabled"||o$1.status==="deleted"){E(e,400,"User account is not active.");return}let s={};o$1.firstName===void 0&&t.firstName&&(s.firstName=t.firstName),o$1.lastName===void 0&&t.lastName&&(s.lastName=t.lastName),o$1.avatarUrl===void 0&&t.avatarUrl&&(s.avatarUrl=t.avatarUrl);let a=o$1;Object.keys(s).length>0&&(await o.updateOne({_id:o$1._id},{$set:s}),a={...o$1,...s}),await ft(e,o$1._id),i.onAfterLogin?.({provider:t.providerName,user:a,session:r,connectionInfo:n}),i.login?.onSuccess?.(a);}catch(s){throw s instanceof Error&&(i.login?.onError?.(s),i.onLoginError?.({provider:t.providerName,error:s,session:r,connectionInfo:n})),s}}async function zn(e,t,o$1,r,n){let i=y();if((i.oauthAccountLinking??"manual")==="auto"&&t.emailVerified){if(o$1.status==="disabled"||o$1.status==="deleted"){E(e,400,"User account is not active.");return}if(!o$1.emails?.find(c=>c.address.toLowerCase()===t.email.toLowerCase())?.verified){E(e,400,"User with this email already exists. Please log in instead.");return}try{let c={...o$1.firstName===void 0&&t.firstName&&{firstName:t.firstName},...o$1.lastName===void 0&&t.lastName&&{lastName:t.lastName},...o$1.avatarUrl===void 0&&t.avatarUrl&&{avatarUrl:t.avatarUrl}};if(!((await o.updateOne({_id:o$1._id,status:{$nin:["deleted","disabled"]},$or:[{[`authMethods.${t.providerName}.id`]:{$exists:!1}},{[`authMethods.${t.providerName}.id`]:t.id}]},{$set:{[`authMethods.${t.providerName}.id`]:t.id,...c}})).matchedCount>0)){E(e,400,"User with this email already exists. Please log in instead.");return}await ft(e,o$1._id);let p={...o$1,...c,authMethods:{...o$1.authMethods,[t.providerName]:{id:t.id}}};i.onAfterLogin?.({provider:t.providerName,user:p,session:r,connectionInfo:n}),i.login?.onSuccess?.(p);return}catch(c){throw c instanceof Error&&(i.login?.onError?.(c),i.onLoginError?.({provider:t.providerName,error:c,session:r,connectionInfo:n})),c}}E(e,400,"User with this email already exists. Please log in instead.");}async function Wn(e,t,o$1,r){let n=y();try{let i;if(n.generateHandle){let l=await n.generateHandle({email:t.email,firstName:t.firstName,lastName:t.lastName});i=await O(l,t.email,{throwOnConflict:!1});}else i=await O(void 0,t.email);let s={handle:i,status:"active",emails:[{address:t.email,verified:t.emailVerified}],createdAt:new Date,authMethods:{[t.providerName]:{id:t.id}},...t.firstName!==void 0&&{firstName:t.firstName},...t.lastName!==void 0&&{lastName:t.lastName},...t.avatarUrl!==void 0&&{avatarUrl:t.avatarUrl}},a=await o.insertOne(s);await ft(e,a.insertedId);let c=await o.findOne({_id:a.insertedId},{readPreference:"primary"});c&&(n.onAfterSignup?.({provider:t.providerName,user:c,session:o$1,connectionInfo:r}),n.signup?.onSuccess?.(c));}catch(i){throw i instanceof Error&&(n.onSignupError?.({provider:t.providerName,error:i,session:o$1,connectionInfo:r}),n.signup?.onError?.(i)),i}}function te(e){return `${a$2("_system.site.url")}/api/_internal/auth/${e}/callback`}async function Pe(e,t,o$1){let r=await o.findOne({[`authMethods.${o$1.providerName}.id`]:o$1.id}),{session:n,connectionInfo:i}=await oe(e,t);if(r)return qn(t,o$1,r,n,i);if(!o$1.email){E(t,400,`Email address is required for ${o$1.providerName} authentication.`);return}let s;try{s=await o.findOne({"emails.address":o$1.email,status:{$ne:"deleted"}},{collation:{locale:"en",strength:2}});}catch(a){if(a instanceof Error){let c=y();c.onSignupError?.({provider:o$1.providerName,error:a,session:n,connectionInfo:i}),c.signup?.onError?.(a);}throw a}return s?zn(t,o$1,s,n,i):Wn(t,o$1,n,i)}function A(e){e.cookie("oauthLinkToken","",{httpOnly:true,maxAge:0,path:"/api/_internal/auth/",sameSite:"lax",secure:process.env.NODE_ENV==="production"});}function ee(e){if(e)try{e();}catch(t){console.error("Error executing OAuth hook:",t);}}function Te(e,t,o){let r=e.query.state,n=e.cookies[o],[i,s,a]=(n||"").split(":");return !r||!n||r!==i?(E(t,400,"Invalid OAuth state - possible CSRF attack"),null):(t.clearCookie(o),{mode:s||"login",...a?{linkedUserId:a}:{}})}async function Me(e,t,o$1,r){let n=y(),{session:i,connectionInfo:s}=await oe(e,t),a=null;if(r){if(!ObjectId.isValid(r)){A(t),E(t,400,"Invalid OAuth linking state.");return}a=new ObjectId(r);}else a=i?.userId??null;if(!a){A(t),E(t,401,"You must be signed in to link a provider.");return}let c=a;try{let l=`authMethods.${o$1.providerName}.id`;if((await o.updateOne({_id:c,status:{$nin:["deleted","disabled"]},$or:[{[l]:{$exists:!1}},{[l]:o$1.id}]},{$set:{[l]:o$1.id}})).matchedCount===0){let f=await o.findOne({_id:c});if(!f||f.status==="deleted"||f.status==="disabled"){ee(()=>n.onOAuthLinkError?.({provider:o$1.providerName,error:new Error("User account not found or not active"),session:i,connectionInfo:s})),A(t),E(t,400,"User account is not active.");return}let b=f?.authMethods?.[o$1.providerName]?.id;if(b&&b!==o$1.id){ee(()=>n.onOAuthLinkError?.({provider:o$1.providerName,error:new Error(`User already has a different ${o$1.providerName} account linked`),session:i,connectionInfo:s})),A(t),E(t,400,`You have already linked a different ${o$1.providerName} account.`);return}ee(()=>n.onOAuthLinkError?.({provider:o$1.providerName,error:new Error(`Unexpected OAuth linking state for ${o$1.providerName}`),session:i,connectionInfo:s})),A(t),E(t,400,`Unable to link ${o$1.providerName} account.`);return}let p=await o.findOne({_id:c},{readPreference:"primary"});p&&ee(()=>n.onAfterOAuthLink?.({provider:o$1.providerName,user:p,session:i,connectionInfo:s})),A(t),t.status(302).redirect("/");}catch(l){if(l instanceof MongoServerError&&l.code===11e3){ee(()=>n.onOAuthLinkError?.({provider:o$1.providerName,error:l,session:i,connectionInfo:s})),A(t),E(t,400,`This ${o$1.providerName} account is already linked to a different user.`);return}if(l instanceof Error&&ee(()=>n.onOAuthLinkError?.({provider:o$1.providerName,error:l,session:i,connectionInfo:s})),A(t),!t.headersSent)throw l}}function Ie(e){return !e||typeof e!="string"?null:e}async function Yn(e,t,o,r){let n=await fetch("https://oauth2.googleapis.com/token",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({code:e,client_id:t,client_secret:o,redirect_uri:r,grant_type:"authorization_code"})});if(!n.ok)throw new Error(`Failed to exchange code for token: ${n.statusText}`);return n.json()}async function Qn(e){let t=await fetch("https://www.googleapis.com/oauth2/v2/userinfo",{headers:{Authorization:`Bearer ${e}`}});if(!t.ok)throw new Error(`Failed to fetch user info: ${t.statusText}`);return t.json()}async function Xn(e,t){let o=Ie(e.query.code);if(!o){E(t,400,"Missing authorization code");return}let r=Te(e,t,"authStateGoogle");if(!r)return;let{mode:n,linkedUserId:i}=r,s=String(a$2("_system.user.auth.google.clientId")),a=String(a$2("_system.user.auth.google.clientSecret")),c=te("google");try{let l=await Yn(o,s,a,c),d=await Qn(l.access_token),p={id:d.id,email:d.email,emailVerified:d.verified_email,providerName:"google",firstName:d.given_name||void 0,lastName:d.family_name||void 0,avatarUrl:d.picture||void 0};n==="link"?await Me(e,t,p,i):await Pe(e,t,p);}catch(l){console.error("Google OAuth error:",l),n==="link"&&A(t),E(t,500,"Authentication failed");}}function Zn(){let e=Router(),t=(o,r,n)=>{let i=!!a$2("_system.user.auth.google.enabled"),s=String(a$2("_system.user.auth.google.clientId")),a=String(a$2("_system.user.auth.google.clientSecret"));if(!i||!s||!a){E(r,503,"Google authentication is not configured");return}n();};return e.get("/api/_internal/auth/google",t,async(o,r)=>{let n=String(a$2("_system.user.auth.google.clientId")),i=te("google"),s=randomBytes(32).toString("hex"),a=o.query.mode==="link"?"link":"login",c=null;if(a==="link"&&o.query.linkNonce&&(c=await Le(o.query.linkNonce),!c)){E(r,401,"Invalid or expired link nonce for OAuth linking.");return}let l=c?`${s}:${a}:${c}`:`${s}:${a}`;r.cookie("authStateGoogle",l,{httpOnly:true,secure:process.env.NODE_ENV==="production",sameSite:"lax",maxAge:a$1.minutes(10)});let d=new URL("https://accounts.google.com/o/oauth2/v2/auth");d.searchParams.append("client_id",n),d.searchParams.append("redirect_uri",i),d.searchParams.append("response_type","code"),d.searchParams.append("scope","profile email"),d.searchParams.append("access_type","online"),d.searchParams.append("state",s),r.redirect(d.toString());}),e.get("/api/_internal/auth/google/callback",t,Xn),e}var ir=Zn;async function oi(e,t,o,r){let n=await fetch("https://github.com/login/oauth/access_token",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({client_id:t,client_secret:o,code:e,redirect_uri:r})});if(!n.ok)throw new Error(`Failed to exchange code for token: ${n.statusText}`);return n.json()}async function ri(e){let t=await fetch("https://api.github.com/user",{headers:{Authorization:`Bearer ${e}`,Accept:"application/vnd.github.v3+json"}});if(!t.ok)throw new Error(`Failed to fetch user info: ${t.statusText}`);return t.json()}async function ni(e){let t=await fetch("https://api.github.com/user/emails",{headers:{Authorization:`Bearer ${e}`,Accept:"application/vnd.github.v3+json"}});if(!t.ok)throw new Error(`Failed to fetch user emails: ${t.statusText}`);return t.json()}async function ii(e,t){return e.email?e.email:(await ni(t)).find(r=>r.primary&&r.verified)?.email??null}async function si(e,t){let o=Ie(e.query.code);if(!o){E(t,400,"Missing authorization code");return}let r=Te(e,t,"authStateGithub");if(!r)return;let{mode:n,linkedUserId:i}=r,s=String(a$2("_system.user.auth.github.clientId")),a=String(a$2("_system.user.auth.github.clientSecret")),c=te("github");try{let l=await oi(o,s,a,c),d=await ri(l.access_token),p=await ii(d,l.access_token);if(!p){n==="link"&&A(t),E(t,400,"Unable to retrieve a primary verified email from GitHub. Please ensure your GitHub account has a verified email set as primary.");return}let f=d.name?d.name.trim().split(/\s+/):[],b=f[0]||void 0,v=f.length>1?f.slice(1).join(" "):void 0,S={id:String(d.id),email:p,emailVerified:!0,providerName:"github",firstName:b,lastName:v,avatarUrl:d.avatar_url||void 0};n==="link"?await Me(e,t,S,i):await Pe(e,t,S);}catch(l){console.error("GitHub OAuth error:",l),n==="link"&&A(t),E(t,500,"Authentication failed");}}function ai(){let e=Router(),t=(o,r,n)=>{let i=!!a$2("_system.user.auth.github.enabled"),s=String(a$2("_system.user.auth.github.clientId")),a=String(a$2("_system.user.auth.github.clientSecret"));if(!i||!s||!a){E(r,503,"GitHub authentication is not configured");return}n();};return e.get("/api/_internal/auth/github",t,async(o,r)=>{let n=String(a$2("_system.user.auth.github.clientId")),i=te("github"),s=a$2("_system.user.auth.github.scopes"),a=s?String(s).split(",").map(b=>b.trim()).join(" "):"user:email",c=randomBytes(32).toString("hex"),l=o.query.mode==="link"?"link":"login",d=null;if(l==="link"&&o.query.linkNonce&&(d=await Le(o.query.linkNonce),!d)){E(r,401,"Invalid or expired link nonce for OAuth linking.");return}let p=d?`${c}:${l}:${d}`:`${c}:${l}`;r.cookie("authStateGithub",p,{httpOnly:true,secure:process.env.NODE_ENV==="production",sameSite:"lax",maxAge:a$1.minutes(10)});let f=new URL("https://github.com/login/oauth/authorize");f.searchParams.append("client_id",n),f.searchParams.append("redirect_uri",i),f.searchParams.append("scope",a),f.searchParams.append("state",c),r.redirect(f.toString());}),e.get("/api/_internal/auth/github/callback",t,si),e}var sr=ai;function ar(e,t,o){return async(r,n,i)=>{let s=r.headers["x-modelence-auth-token"],a={session:null,user:null};if(typeof s=="string"&&F())try{let{session:l,user:d}=await v(s);a={session:l,user:d};}catch{}let c=m$1("route",`route:${e.toLowerCase()}:${t}`,{method:e,path:t,query:i$1(r.query),body:i$1(r.body),params:i$1(r.params)});try{let l=await o({query:r.query,body:r.body,params:r.params,headers:r.headers,cookies:r.cookies,rawBody:Buffer.isBuffer(r.body)?r.body:void 0,req:r,res:n,next:i},a);c.end(),l&&(n.status(l.status||200),l.headers&&Object.entries(l.headers).forEach(([d,p])=>{n.setHeader(d,p);}),l.redirect?n.redirect(l.redirect):n.send(l.data));}catch(l){c.end("error"),l instanceof a$4?n.status(l.status).send(l.message):(console.error(`Error in route handler: ${r.path}`),console.error(l),n.status(500).send(String(l)));}}}function di(e){let t=[];if(!e)return t.push(j$1.json({limit:"16mb"})),t.push(j$1.urlencoded({extended:true,limit:"16mb"})),t;if(e.json!==false){let o=typeof e.json=="object"?e.json:{limit:"16mb"};t.push(j$1.json(o));}if(e.urlencoded!==false){let o=typeof e.urlencoded=="object"?e.urlencoded:{extended:true,limit:"16mb"};t.push(j$1.urlencoded(o));}if(e.raw){let o=typeof e.raw=="object"?e.raw:{},r={limit:o.limit||"16mb",type:o.type||"*/*"};t.push(j$1.raw(r));}return t}function ui(e,t){for(let o of t)for(let r of o.routes){let{path:n,handlers:i,body:s}=r,a=di(s);Object.entries(i).forEach(([c,l])=>{e[c](n,...a,ar(c,n,l));});}}async function or(e,{combinedModules:t,channels:o}){let r=j$1();r.use(ci()),r.use(fi()),ui(r,t),r.use(j$1.json({limit:"16mb"})),r.use(j$1.urlencoded({extended:true,limit:"16mb"})),r.use(ir()),r.use(sr()),r.post("/api/_internal/auth/set-link-cookie",async(a,c)=>{let{session:l}=await oe(a,c);if(!l?.userId){c.status(401).json({error:"Not authenticated"});return}c.cookie("oauthLinkToken",l.authToken,{httpOnly:true,secure:process.env.NODE_ENV==="production",sameSite:"lax",path:"/api/_internal/auth/",maxAge:10*60*1e3}),c.json({ok:true});}),r.post("/api/_internal/auth/issue-link-nonce",async(a,c)=>{let{session:l}=await oe(a,c);if(!l?.userId){c.status(401).json({error:"Not authenticated"});return}let d=await d$1(String(l.userId));c.json({nonce:d});}),r.post("/api/_internal/method/:methodName(*)",async(a,c)=>{let l=a.params.methodName,d=await oe(a,c);try{let p=a$3(await C$1(l,a.body.args,d));c.json({data:p,typeMap:b$2(p)});}catch(p){mi(c,l,p);}});let n=li.createServer(r);await e.init({httpServer:n}),e.middlewares&&r.use(e.middlewares()),r.all("*",(a,c,l)=>{Promise.resolve(e.handler(a,c)).catch(l);}),process.on("unhandledRejection",(a,c)=>{console.error("Unhandled Promise Rejection:"),console.error(a instanceof Error?a.stack:a),console.error("Promise:",c);}),process.on("uncaughtException",a=>{console.error("Uncaught Exception:"),console.error(a.stack),console.trace("Full application stack:");});let i=_e()?.provider;i&&i.init({httpServer:n,channels:o});let s=process.env.MODELENCE_PORT||process.env.PORT||3e3;n.listen(s,()=>{k$1("Application started",{source:"app"});let a=a$2("_system.site.url")||`http://localhost:${s}`;console.log(`
|
|
34
|
+
Application started on ${a}
|
|
35
|
+
`);});}async function oe(e,t=null){let o=(e.path??e.url??"").split("?")[0],r=o.startsWith("/api/_internal/auth/")&&o.endsWith("/callback"),n=e.body??{},i=D.string().nullish().transform(l=>l??null).parse(e.cookies.authToken||(r?e.cookies.oauthLinkToken:null)||n.authToken),s=D.object({screenWidth:D.number(),screenHeight:D.number(),windowWidth:D.number(),windowHeight:D.number(),pixelRatio:D.number(),orientation:D.string().nullable()}).nullish().parse(n.clientInfo)??{screenWidth:0,screenHeight:0,windowWidth:0,windowHeight:0,pixelRatio:1,orientation:null},a={ip:hi(e),userAgent:e.get("user-agent"),acceptLanguage:e.get("accept-language"),referrer:e.get("referrer"),baseUrl:gi(e)};if(!!F()){let{session:l,user:d,roles:p}=await v(i);return {clientInfo:s,connectionInfo:a,session:l,user:d,roles:p,req:e,res:t}}return {clientInfo:s,connectionInfo:a,session:null,user:null,roles:u(),req:e,res:t}}function mi(e,t,o){if(o instanceof a$4){o.status>=500&&o.status<600&&console.error(`Error calling ${t}:`,o),o.code&&e.setHeader("X-Modelence-Error-Code",o.code),e.status(o.status).send(o.message);return}if(o instanceof Error&&o?.constructor?.name==="ZodError"&&"errors"in o){let r="";try{r=pi(o);}catch(n){console.error(`Error parsing Zod error in ${t}:`,n),r="Validation failed";}e.status(400).send(r);return}console.error(`Error calling ${t}:`,o),e.status(500).send(o instanceof Error?o.message:String(o));}function pi(e){let t=e.flatten(),o=Object.entries(t.fieldErrors).map(([i,s])=>`${i}: ${(s??[]).join(", ")}`),r=t.formErrors;return [...o,...r].filter(Boolean).join("; ")}function fi(){let{frameAncestors:e}=Zo(),t=e&&e.length>0,o=t?["'self'",...e].join(" "):"'self'";return (r,n,i)=>{n.setHeader("Content-Security-Policy",`frame-ancestors ${o}`),t||n.setHeader("X-Frame-Options","SAMEORIGIN"),i();}}function gi(e){let t=e.headers["x-forwarded-host"],o=(Array.isArray(t)?t[0]:t?.split(",")[0])?.trim()||e.get("host"),r=e.headers["x-forwarded-proto"];return `${(Array.isArray(r)?r[0]:r?.split(",")[0])?.trim()||e.protocol}://${o}`}function hi(e){let t=e.headers["x-forwarded-for"];if(t)return (Array.isArray(t)?t[0]:t.split(",")[0]).trim();let o=e.ip||e.socket?.remoteAddress;if(o)return o.startsWith("::ffff:")?o.substring(7):o}
|
|
36
|
+
export{C as a,en as b,tn as c,on as d,rn as e,or as f,oe as g,Rn as h,Gn as i,Fn as j,pt as k,Vn as l};//# sourceMappingURL=chunk-T4G5RAOK.js.map
|
|
37
|
+
//# sourceMappingURL=chunk-T4G5RAOK.js.map
|