@rpcbase/db 0.128.0 → 0.129.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js
CHANGED
|
@@ -606,6 +606,18 @@ var ZRBUploadSessionStatus = z$1.enum([
|
|
|
606
606
|
"done",
|
|
607
607
|
"error"
|
|
608
608
|
]);
|
|
609
|
+
var ZRBUploadAccessScope = z$1.enum([
|
|
610
|
+
"owner",
|
|
611
|
+
"tenant",
|
|
612
|
+
"public"
|
|
613
|
+
]);
|
|
614
|
+
var ZRBUploadDeduplication = z$1.object({
|
|
615
|
+
namespace: z$1.string(),
|
|
616
|
+
algorithm: z$1.literal("sha256"),
|
|
617
|
+
hash: z$1.string(),
|
|
618
|
+
key: z$1.string(),
|
|
619
|
+
pipelineVersion: z$1.number().int().min(1)
|
|
620
|
+
});
|
|
609
621
|
var ZRBUploadSession = z$1.object({
|
|
610
622
|
_id: z$1.string(),
|
|
611
623
|
userId: z$1.string().optional(),
|
|
@@ -620,6 +632,9 @@ var ZRBUploadSession = z$1.object({
|
|
|
620
632
|
expiresAt: z$1.date(),
|
|
621
633
|
fileId: z$1.string().optional(),
|
|
622
634
|
isPublic: z$1.boolean().optional(),
|
|
635
|
+
accessScope: ZRBUploadAccessScope.optional(),
|
|
636
|
+
deduplication: ZRBUploadDeduplication.optional(),
|
|
637
|
+
deduplicated: z$1.boolean().optional(),
|
|
623
638
|
error: z$1.string().optional()
|
|
624
639
|
});
|
|
625
640
|
var RBUploadSessionSchema = new Schema$1({
|
|
@@ -678,6 +693,41 @@ var RBUploadSessionSchema = new Schema$1({
|
|
|
678
693
|
type: Boolean,
|
|
679
694
|
required: false
|
|
680
695
|
},
|
|
696
|
+
accessScope: {
|
|
697
|
+
type: String,
|
|
698
|
+
required: false,
|
|
699
|
+
enum: ZRBUploadAccessScope.options
|
|
700
|
+
},
|
|
701
|
+
deduplication: {
|
|
702
|
+
type: new Schema$1({
|
|
703
|
+
namespace: {
|
|
704
|
+
type: String,
|
|
705
|
+
required: true
|
|
706
|
+
},
|
|
707
|
+
algorithm: {
|
|
708
|
+
type: String,
|
|
709
|
+
required: true,
|
|
710
|
+
enum: ["sha256"]
|
|
711
|
+
},
|
|
712
|
+
hash: {
|
|
713
|
+
type: String,
|
|
714
|
+
required: true
|
|
715
|
+
},
|
|
716
|
+
key: {
|
|
717
|
+
type: String,
|
|
718
|
+
required: true
|
|
719
|
+
},
|
|
720
|
+
pipelineVersion: {
|
|
721
|
+
type: Number,
|
|
722
|
+
required: true
|
|
723
|
+
}
|
|
724
|
+
}, { _id: false }),
|
|
725
|
+
required: false
|
|
726
|
+
},
|
|
727
|
+
deduplicated: {
|
|
728
|
+
type: Boolean,
|
|
729
|
+
required: false
|
|
730
|
+
},
|
|
681
731
|
error: {
|
|
682
732
|
type: String,
|
|
683
733
|
required: false
|
|
@@ -1111,7 +1161,9 @@ var models_exports = /* @__PURE__ */ __exportAll({
|
|
|
1111
1161
|
ZRBTenantSubscriptionScope: () => ZRBTenantSubscriptionScope,
|
|
1112
1162
|
ZRBTenantSubscriptionStatus: () => ZRBTenantSubscriptionStatus,
|
|
1113
1163
|
ZRBTenantSubscriptionType: () => ZRBTenantSubscriptionType,
|
|
1164
|
+
ZRBUploadAccessScope: () => ZRBUploadAccessScope,
|
|
1114
1165
|
ZRBUploadChunk: () => ZRBUploadChunk,
|
|
1166
|
+
ZRBUploadDeduplication: () => ZRBUploadDeduplication,
|
|
1115
1167
|
ZRBUploadSession: () => ZRBUploadSession,
|
|
1116
1168
|
ZRBUploadSessionStatus: () => ZRBUploadSessionStatus,
|
|
1117
1169
|
ZRBUser: () => ZRBUser
|
|
@@ -2180,6 +2232,6 @@ var createTenantBillingStorage = (params) => {
|
|
|
2180
2232
|
};
|
|
2181
2233
|
};
|
|
2182
2234
|
//#endregion
|
|
2183
|
-
export { E164_PHONE_OR_EMPTY_REGEX, E164_PHONE_REGEX, LANGUAGE_CODE_REGEX, PaginationValidationError, RBNotificationDeliveryPolicy, RBNotificationDeliverySchema, RBNotificationPolicy, RBNotificationSchema, RBNotificationSettingsPolicy, RBNotificationSettingsSchema, RBOAuthRequestSchema, RBRtsChangeSchema, RBRtsCounterSchema, RBTenantSchema, RBTenantSubscriptionEventSchema, RBTenantSubscriptionProjectionSchema, RBUploadChunkSchema, RBUploadSessionPolicy, RBUploadSessionSchema, RBUserSchema, Schema, ZRBNotification, ZRBNotificationDelivery, ZRBNotificationDigestFrequency, ZRBNotificationPlatformPayload, ZRBNotificationSettings, ZRBNotificationTopicPreference, ZRBOAuthRequest, ZRBRtsChange, ZRBRtsChangeOp, ZRBRtsCounter, ZRBTenant, ZRBTenantSubscriptionChangeDirection, ZRBTenantSubscriptionEvent, ZRBTenantSubscriptionEventSource, ZRBTenantSubscriptionEventType, ZRBTenantSubscriptionIntervalUnit, ZRBTenantSubscriptionProjection, ZRBTenantSubscriptionScope, ZRBTenantSubscriptionStatus, ZRBTenantSubscriptionType, ZRBUploadChunk, ZRBUploadSession, ZRBUploadSessionStatus, ZRBUser, buildAbility, buildAbilityFromSession, buildLocaleFallbackChain, buildSearchTextStage, can, createModels, createTenantBillingStorage, ensureSearchIndex, extendMongooseSchema, extendZod, getAccessibleByQuery, getRegisteredPolicies, getTenantFilesystemDb, getTenantFilesystemDbFromCtx, getTenantFilesystemDbName, getTenantIdFromLoadModelCtx, getTenantRolesFromSessionUser, hasRegisteredPolicy, isPaginationValidationError, localizedStringField, makeZE164Phone, model, models, mongoPaginationPlugin, mongoose, omitMongooseSchemaPaths, registerPoliciesFromModules, registerPolicy, resolveLocalizedString, searchMetaProjection, withLocalizedStringFallback, withTransaction, z, zE164Phone, zI18nString, zLocalizedString };
|
|
2235
|
+
export { E164_PHONE_OR_EMPTY_REGEX, E164_PHONE_REGEX, LANGUAGE_CODE_REGEX, PaginationValidationError, RBNotificationDeliveryPolicy, RBNotificationDeliverySchema, RBNotificationPolicy, RBNotificationSchema, RBNotificationSettingsPolicy, RBNotificationSettingsSchema, RBOAuthRequestSchema, RBRtsChangeSchema, RBRtsCounterSchema, RBTenantSchema, RBTenantSubscriptionEventSchema, RBTenantSubscriptionProjectionSchema, RBUploadChunkSchema, RBUploadSessionPolicy, RBUploadSessionSchema, RBUserSchema, Schema, ZRBNotification, ZRBNotificationDelivery, ZRBNotificationDigestFrequency, ZRBNotificationPlatformPayload, ZRBNotificationSettings, ZRBNotificationTopicPreference, ZRBOAuthRequest, ZRBRtsChange, ZRBRtsChangeOp, ZRBRtsCounter, ZRBTenant, ZRBTenantSubscriptionChangeDirection, ZRBTenantSubscriptionEvent, ZRBTenantSubscriptionEventSource, ZRBTenantSubscriptionEventType, ZRBTenantSubscriptionIntervalUnit, ZRBTenantSubscriptionProjection, ZRBTenantSubscriptionScope, ZRBTenantSubscriptionStatus, ZRBTenantSubscriptionType, ZRBUploadAccessScope, ZRBUploadChunk, ZRBUploadDeduplication, ZRBUploadSession, ZRBUploadSessionStatus, ZRBUser, buildAbility, buildAbilityFromSession, buildLocaleFallbackChain, buildSearchTextStage, can, createModels, createTenantBillingStorage, ensureSearchIndex, extendMongooseSchema, extendZod, getAccessibleByQuery, getRegisteredPolicies, getTenantFilesystemDb, getTenantFilesystemDbFromCtx, getTenantFilesystemDbName, getTenantIdFromLoadModelCtx, getTenantRolesFromSessionUser, hasRegisteredPolicy, isPaginationValidationError, localizedStringField, makeZE164Phone, model, models, mongoPaginationPlugin, mongoose, omitMongooseSchemaPaths, registerPoliciesFromModules, registerPolicy, resolveLocalizedString, searchMetaProjection, withLocalizedStringFallback, withTransaction, z, zE164Phone, zI18nString, zLocalizedString };
|
|
2184
2236
|
|
|
2185
2237
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["Schema","z","ZRBUser","object","email","string","optional","password","name","phone","tenants","array","tenantRoles","record","oauthProviders","subject","accessToken","refreshToken","idToken","scope","tokenType","expiresAt","date","rawUserInfo","unknown","createdAt","updatedAt","emailVerificationCode","length","emailVerificationExpiresAt","passwordResetCode","passwordResetCodeExpiresAt","passwordResetToken","passwordResetTokenExpiresAt","IRBUser","infer","RBUserSchema","type","String","unique","sparse","required","index","Map","of","default","Date","Types","Mixed","_id","Schema","z","ZRBTenant","object","tenantId","string","parentTenantId","optional","name","IRBTenant","infer","RBTenantSchema","type","String","required","unique","index","Schema","z","SUBSCRIPTION_CHANGE_DIRECTIONS","SUBSCRIPTION_EVENT_TYPES","SUBSCRIPTION_INTERVAL_UNITS","SUBSCRIPTION_SCOPES","SUBSCRIPTION_STATUSES","SUBSCRIPTION_TYPES","ZRBTenantSubscriptionStatus","enum","ZRBTenantSubscriptionIntervalUnit","ZRBTenantSubscriptionType","ZRBTenantSubscriptionScope","ZRBTenantSubscriptionEventType","ZRBTenantSubscriptionEventSource","ZRBTenantSubscriptionChangeDirection","subscriptionEventBaseSchema","object","tenantId","string","trim","min","subscriptionId","occurredAt","date","effectiveAt","subscriptionType","parentSubscriptionId","optional","scope","scopeId","fromPlanKey","toPlanKey","fromStatus","toStatus","fromModules","array","toModules","fromIntervalUnit","toIntervalUnit","fromIntervalCount","number","int","toIntervalCount","fromPriceId","toPriceId","billingAnchor","supersedesEventId","idempotencyKey","direction","actorUserId","source","reason","provider","providerEventId","providerPayload","unknown","metadata","record","subscriptionCreatedEventSchema","extend","type","literal","subscriptionPlanChangedEventSchema","subscriptionStatusChangedEventSchema","subscriptionResumedEventSchema","subscriptionCanceledEventSchema","subscriptionRenewedEventSchema","ZRBTenantSubscriptionEvent","discriminatedUnion","superRefine","event","ctx","addIssue","code","message","path","IRBTenantSubscriptionEvent","infer","SubscriptionEventDocument","requiredForEventTypes","types","Array","requiredForEventType","this","Boolean","includes","RBTenantSubscriptionEventSchema","String","required","index","options","Date","default","now","undefined","Number","Types","Mixed","unique","partialFilterExpression","$type","Schema","z","ZRBTenantSubscriptionIntervalUnit","ZRBTenantSubscriptionScope","ZRBTenantSubscriptionStatus","ZRBTenantSubscriptionType","ZRBTenantSubscriptionProjection","object","tenantId","string","subscriptionId","type","parentSubscriptionId","optional","scope","scopeId","planKey","priceId","status","intervalUnit","intervalCount","number","int","min","modules","array","billingAnchor","date","currentPeriodStart","currentPeriodEnd","cancelAtPeriodEnd","boolean","cancelAt","canceledAt","scheduledPlanKey","scheduledPlanEffectiveAt","provider","latestEventId","latestEventAt","projectedAt","IRBTenantSubscriptionProjection","infer","RBTenantSubscriptionProjectionSchema","String","required","index","enum","options","Number","default","Date","Boolean","unique","Schema","z","ZRBRtsCounter","object","_id","string","seq","number","int","min","IRBRtsCounter","infer","RBRtsCounterSchema","type","String","required","Number","default","versionKey","Schema","z","ttlSecondsRaw","process","env","RB_RTS_CHANGES_TTL_S","ttlSeconds","Number","isFinite","Math","max","floor","ZRBRtsChangeOp","enum","ZRBRtsChange","object","seq","number","int","min","modelName","string","op","docId","optional","ts","date","IRBRtsChange","infer","RBRtsChangeSchema","type","required","String","index","options","Date","default","now","versionKey","unique","expireAfterSeconds","Schema","z","AclPolicy","ZRBUploadSessionStatus","enum","ZRBUploadSession","object","_id","string","userId","optional","ownerKeyHash","filename","mimeType","totalSize","number","int","min","chunkSize","chunksTotal","status","createdAt","date","expiresAt","fileId","isPublic","boolean","error","IRBUploadSession","infer","RBUploadSessionSchema","type","String","required","index","Number","options","Date","default","now","Boolean","versionKey","expireAfterSeconds","RBUploadSessionPolicy","subject","define","builder","ctx","can","uploadKeyHash","claims","trim","Schema","z","ZRBUploadChunk","object","uploadId","string","index","number","int","min","data","unknown","size","sha256","optional","createdAt","date","expiresAt","IRBUploadChunk","infer","RBUploadChunkSchema","type","String","required","Number","Buffer","Date","default","now","versionKey","unique","expireAfterSeconds","Schema","z","AclPolicy","ZStringMap","record","string","ZRBNotificationPlatformPayload","object","webpush","unknown","optional","fcmOptions","android","apns","passthrough","IRBNotificationPlatformPayload","infer","ZRBNotification","userId","topic","tag","deliveryId","title","body","image","data","platform","drawerActive","boolean","createdAt","date","seenAt","readAt","archivedAt","IRBNotification","TTL_90_DAYS_S","RBNotificationSchema","type","String","required","index","Types","Mixed","Boolean","Date","default","now","versionKey","unique","partialFilterExpression","$exists","expireAfterSeconds","RBNotificationPolicy","subject","define","builder","ctx","can","Schema","z","AclPolicy","ZRBNotificationPlatformPayload","ZStringMap","record","string","ZRBNotificationDelivery","object","userId","notificationId","optional","deliveryId","topic","tag","title","body","image","data","platform","createdAt","date","IRBNotificationDelivery","infer","TTL_90_DAYS_S","RBNotificationDeliverySchema","type","String","required","index","unique","Types","Mixed","Date","default","now","versionKey","expireAfterSeconds","RBNotificationDeliveryPolicy","subject","define","builder","ctx","can","Schema","z","AclPolicy","ZRBNotificationDigestFrequency","enum","ZRBNotificationTopicPreference","object","topic","string","inApp","boolean","emailDigest","push","ZRBNotificationSettings","userId","digestFrequency","topicPreferences","array","optional","lastDigestSentAt","date","IRBNotificationSettings","infer","TopicPreferenceSchema","type","String","required","Boolean","default","_id","RBNotificationSettingsSchema","options","Date","versionKey","timestamps","index","unique","RBNotificationSettingsPolicy","subject","define","builder","ctx","can","Schema","z","ZRBOAuthRequest","object","_id","string","providerId","codeVerifier","returnTo","optional","createdAt","date","expiresAt","IRBOAuthRequest","infer","RBOAuthRequestSchema","type","String","required","index","Date","default","now","versionKey","expireAfterSeconds","Schema","MongooseSchemaExtension","Parameters","extendMongooseSchema","baseSchema","TSchema","extensions","schema","clone","forEach","extension","add","omitMongooseSchemaPaths","paths","path","remove","Schema","SchemaTypeOptions","LocalizedString","withLocalizedStringFallback","localizedStringField","options","Omit","userGet","get","type","Types","Mixed","value","PaginationErrorCode","PaginationValidationError","Error","code","statusCode","constructor","message","options","ErrorOptions","name","isPaginationValidationError","error","anyError","Partial","PaginationDirection","PaginationOrder","PaginationSpec","PaginationValidationError","DISALLOWED_MONGO_FIELD_SEGMENTS","Set","PAGINATION_LIMIT_MAX","NormalizedPaginationSpec","Omit","direction","limit","sort","Array","field","order","normalizePaginationSpec","spec","options","maxLimit","normalizeLimit","normalizeMaxLimit","isArray","length","map","assertSafeMongoFieldPath","normalizeOrder","seenFields","has","add","primaryOrder","push","undefined","Number","isSafeInteger","isFinite","isInteger","startsWith","parts","split","part","test","createHmac","timingSafeEqual","Types","PaginationSpec","PaginationValidationError","normalizePaginationSpec","CursorValue","$date","$oid","CursorPayloadV1","v","values","Record","PaginationCursorCodecOptions","signingSecret","Buffer","maxLimit","encodePaginationCursor","spec","node","options","normalized","Object","create","field","sort","value","readFieldValue","Error","encodeCursorValue","payload","payloadB64","from","JSON","stringify","toString","sigB64","signCursorPayloadB64","decodePaginationCursor","cursor","rest","split","length","verifyCursorSignature","payloadRaw","payloadUnknown","parse","Partial","decoded","prototype","hasOwnProperty","call","encodedValue","decodeCursorValue","secret","update","digest","expectedSigB64","a","b","unwrapCursorComparableValue","Date","ObjectId","current","depth","_id","comparableValue","toHexString","toISOString","d","Number","isNaN","getTime","isValid","undefined","get","path","reduce","acc","key","PaginationOrder","PaginationSpec","PaginationCursorCodecOptions","decodePaginationCursor","PaginationValidationError","NormalizedPaginationSpec","normalizePaginationSpec","CompiledMongoPagination","spec","mongoFilterDelta","Record","mongoSort","mongoLimit","CompileMongoPaginationOptions","cursor","compileMongoPagination","options","normalized","maxLimit","limit","toMongoSort","length","cursorValues","buildKeysetFilterDelta","Object","create","field","order","sort","forQueryOrder","direction","invertOrder","branches","i","current","and","j","prev","eq","push","op","getKeysetOp","cmpOp","cmp","$and","$or","PaginationResponse","PaginationCursorCodecOptions","encodePaginationCursor","CompiledMongoPagination","MaterializePaginationOptions","cursor","includeCursors","materializeMongoPagination","compiled","fetchedNodes","TNode","options","limit","spec","hasMore","length","trimmed","slice","nodes","direction","reverse","hasPrevPage","Boolean","hasNextPage","pageInfo","prevCursor","nextCursor","CompiledMongoPagination","MongoQueryLike","where","delta","Record","sort","limit","MongoAdapter","applyPagination","query","TQuery","compiled","mongoFilterDelta","mongoSort","mongoLimit","PaginationResponse","PaginationSpec","PaginationCursorCodecOptions","compileMongoPagination","materializeMongoPagination","MongoAdapter","MongoPaginateQueryLike","where","delta","Record","sort","limit","exec","Promise","TNode","PaginateMongoQueryOptions","cursor","includeCursors","paginateMongoQuery","query","pagination","options","compiled","applyPagination","fetchedNodes","Array","isArray","Error","mongoose","PaginationResponse","PaginationSpec","PaginationCursorCodecOptions","paginateMongoQuery","mongoPaginationPluginBrand","QueryOptionsLike","Record","getQueryOptions","query","undefined","getOptions","getPaginationFromOptions","options","pagination","getCursorFromOptions","paginationCursor","MongoPaginationPluginOptions","cursor","includeCursors","QueryResultNode","TResult","Array","TNode","Query","DocType","THelpers","RawDocType","QueryOp","TDocOverrides","paginate","Promise","ResultType","mongoPaginationPlugin","schema","Schema","pluginOptions","this","spec","Error","signingSecret","MongoDbLike","databaseName","command","Record","Promise","SearchTextStageOptions","index","query","path","highlightPath","SearchTextStage","$search","text","highlight","buildSearchTextStage","options","trim","Error","stage","searchMetaProjection","score","$meta","highlights","const","EnsureSearchIndexParams","db","collection","name","definition","listResultHasIndex","listResult","cursor","firstBatch","Array","isArray","some","idx","isIndexAlreadyExistsError","error","codeName","undefined","message","String","test","ensureSearchIndex","params","created","listSearchIndexes","createSearchIndexes","indexes","getAppName","env","NodeJS","ProcessEnv","process","appName","APP_NAME","trim","Error","GLOBAL_DB_SUFFIX","getGlobalDbName","getTenantDbName","tenantId","mongoose","getMongoDirectConnection","getMongoUrl","connections","Map","Connection","rootConnection","CONNECTION_MAX_LISTENERS","waitForOpen","connection","Promise","readyState","getMaxListeners","setMaxListeners","resolve","reject","once","ensureMongooseConnection","dbName","normalizedDbName","trim","Error","existing","get","mongoUrl","createConnection","sanitizeFilter","directConnection","name","useDb","useCache","set","mongoose","GLOBAL_DB_SUFFIX","RBRtsChangeSchema","IRBRtsChange","RBRtsCounterSchema","IRBRtsCounter","RtsChangeOp","RTS_COUNTER_ID","EXCLUDED_MODEL_NAMES","Set","maxDeleteIdsRaw","process","env","RB_RTS_DELETE_LOG_MAX_IDS","maxDeleteIds","Number","isFinite","Math","max","floor","DeleteMeta","modelName","ids","reset","session","ClientSession","deleteMetaByQuery","WeakMap","hasToString","value","toString","maybe","normalizeId","id","getDbName","db","name","databaseName","raw","isGlobalDb","endsWith","RtsCounterDoc","RtsChangeDoc","getQuerySession","query","MongooseQuery","opts","getOptions","undefined","getRtsModels","Connection","RtsCounter","models","RBRtsCounter","Model","model","RtsChange","RBRtsChange","allocateSeqRange","count","Promise","start","end","updated","findOneAndUpdate","_id","$inc","seq","upsert","returnDocument","setDefaultsOnInsert","projection","lean","insertChanges","changes","Array","op","docId","length","ts","Date","docs","map","c","insertMany","recordDeleteChanges","uniqueIds","from","filter","Boolean","idx","recordResetModel","Query","find","getFilter","getQuery","captureDeleteMeta","mode","String","startsWith","has","findQuery","s","limit","n","isArray","d","trimmedIds","meta","set","flushDeleteMeta","get","delete","rtsChangeLogPlugin","schema","Schema","pre","document","this","post","doc","mongoose","accessibleBy","AclAction","AclSubjectType","AppAbility","StoredAcl","ability","action","QueryOptionsLike","Record","PipelineStageLike","isRecord","value","Boolean","Array","isArray","mergeMongoQuery","left","right","leftQuery","Object","keys","length","$and","getQueryOptions","query","undefined","getOptions","getStoredAclFromQuery","options","raw","rbAcl","getStoredAclFromAggregate","aggregate","acl","addQueryAclFilter","Query","storedAcl","resolvedAction","modelName","model","accessQuery","ofType","and","injectAggregateMatch","pipeline","match","unshift","$match","first","geoNear","$geoNear","splice","addAggregateAclFilter","Aggregate","patchAggregateAcl","globalKey","Symbol","for","globalState","globalThis","AggregatePrototype","prototype","this","option","createModelAclProxy","Model","TModel","Proxy","get","target","prop","receiver","Error","Reflect","args","result","apply","mongooseAclPluginBrand","QueryOptions","DocType","AggregateOptions","ResultType","THelpers","RawDocType","QueryOp","TDocOverrides","TRawDocType","TQueryHelpers","TInstanceMethods","TVirtuals","THydratedDocumentType","TSchema","TLeanResultType","mongooseAclPlugin","schema","Schema","setOptions","statics","pre","_private","mongoose","accessibleRecordsPlugin","frameworkSchemas","rtsChangeLogPlugin","registerPoliciesFromModules","mongooseAclPlugin","mongoPaginationPlugin","ModelModules","Record","ModelsScope","RegisterModelsOptions","allowReservedRbModelNames","RegisteredSchemas","Schema","RegisteredModels","tenant","global","cachedModels","DEFAULT_GLOBAL_RB_MODEL_NAMES_SET","Set","assertSchema","exportName","value","Error","join","getFrameworkSchemaForModelName","modelName","applyTenantPlugins","schema","plugin","registerSchema","target","other","scope","buildSchemasFromModules","modules","Array","Object","entries","filter","key","endsWith","map","schemaValue","replace","registerModels","options","tenantSchemas","globalSchemas","has","cloned","clone","startsWith","frameworkSchema","allSchemas","models","model","getRegisteredModels","assert","getGlobalDbName","getTenantDbName","ensureMongooseConnection","getRegisteredModels","registerModels","ModelsScope","hasRegisteredPolicy","AppAbility","LoadModelCtx","tenantId","req","session","user","currentTenantId","ability","loadModelFromDb","modelName","dbName","scope","schemas","schema","Object","keys","join","modelConnection","models","model","normalizeTenantId","value","trim","getTenantIdFromLoadModelCtx","ctx","register","getUnsafe","get","resolvedAbility","isProtected","Error","acl","appAbility","getGlobal","const","LoadModelCtx","ModelModules","RegisterModelsOptions","frameworkSchemas","models","registerModels","ExtractModelNamesFromSchemas","TModules","K","Name","FrameworkModelName","RpcbaseGlobalModelName","Extract","TenantModelName","TTenantModules","GlobalModelName","TGlobalModules","LoadedTenantModel","Awaited","ReturnType","LoadedGlobalModel","ModelsGetFn","modelName","ctx","modelNames","TNames","Promise","ModelsGetUnsafeFn","ModelsGetGlobalFn","ModelsConfig","tenant","global","ModelsClient","register","modules","options","get","getUnsafe","getGlobal","createModels","Record","modelNameOrNames","Array","isArray","all","map","nextModules","nextOptions","assert","mongoose","ensureMongooseConnection","getTenantIdFromLoadModelCtx","LoadModelCtx","getAppName","appName","process","env","APP_NAME","trim","normalizeTenantId","tenantId","normalized","getTenantFilesystemDbName","getTenantFilesystemDb","Promise","Connection","getTenantFilesystemDbFromCtx","ctx","mongoose","ClientSession","getGlobalDbName","getTenantDbName","ensureMongooseConnection","getTenantIdFromLoadModelCtx","LoadModelCtx","getTenantFilesystemDbName","MongooseTransactionOptions","Parameters","TenantGlobalFilesystemTransactionCtx","tenantId","session","ctx","tenant","global","db","Connection","filesystem","WithTransactionScope","buildTenantLoadModelCtx","req","user","currentTenantId","withTransaction","fn","Promise","T","options","scope","normalizedTenantId","trim","Error","tenantDbName","globalDbName","filesystemDbName","tenantDb","globalDb","filesystemDb","startSession","tenantCtx","globalCtx","endSession","ClientSession","BillingStorage","BillingStorageTransaction","PersistedSubscriptionEvent","StoredSubscriptionProjection","SubscriptionEvent","ZRBTenantSubscriptionEvent","LoadModelCtx","models","withTransaction","MongoBillingTransaction","session","SubscriptionEventDocument","Record","_id","getTransactionSession","transaction","undefined","toSubscriptionEvent","document","parsed","parse","Error","id","String","getExistingEventQuery","event","tenantId","idempotencyKey","isDuplicateKeyError","error","Boolean","code","toProjectionDocument","projection","subscriptionId","type","parentSubscriptionId","scope","scopeId","planKey","priceId","status","intervalUnit","intervalCount","modules","billingAnchor","currentPeriodStart","currentPeriodEnd","cancelAtPeriodEnd","cancelAt","canceledAt","scheduledPlanKey","scheduledPlan","scheduledPlanEffectiveAt","effectiveAt","provider","latestEventId","latestEventAt","projectedAt","createTenantBillingStorage","params","ctx","findExistingEvent","query","Promise","EventModel","get","request","findOne","lean","runInTransaction","operation","createEvent","existingQuery","existing","eventDocument","documents","create","toObject","duplicate","listEvents","find","sort","occurredAt","map","upsertProjection","ProjectionModel","replaceOne","upsert","runValidators"],"sources":["../src/models/RBUser.ts","../src/models/RBTenant.ts","../src/models/RBTenantSubscriptionEvent.ts","../src/models/RBTenantSubscriptionProjection.ts","../src/models/RBRtsCounter.ts","../src/models/RBRtsChange.ts","../src/models/RBUploadSession.ts","../src/models/RBUploadChunk.ts","../src/models/RBNotification.ts","../src/models/RBNotificationDelivery.ts","../src/models/RBNotificationSettings.ts","../src/models/RBOAuthRequest.ts","../src/models/index.ts","../src/mongoose/extendMongooseSchema.ts","../src/mongoose/localizedStringField.ts","../src/mongoose/index.ts","../src/pagination/errors.ts","../src/pagination/normalizeSpec.ts","../src/pagination/cursor.ts","../src/pagination/compileMongoPagination.ts","../src/pagination/materializePagination.ts","../src/pagination/mongoAdapter.ts","../src/pagination/paginateMongoQuery.ts","../src/pagination/mongoPaginationPlugin.ts","../src/search/index.ts","../src/dbNames.ts","../src/ensureMongooseConnection.ts","../src/rtsChangeLogPlugin.ts","../src/acl/mongooseAclPlugin.ts","../src/registerModels.ts","../src/modelsApi.ts","../src/createModels.ts","../src/tenantFilesystemDb.ts","../src/transactions.ts","../src/billingStorage.ts"],"sourcesContent":["import { Schema } from \"mongoose\"\nimport { z } from \"zod\"\n\n\nexport const ZRBUser = z.object({\n email: z.string().email().optional(),\n password: z.string(),\n name: z.string().optional(),\n phone: z.string().optional(),\n tenants: z.array(z.string()),\n tenantRoles: z.record(z.string(), z.array(z.string())).optional(),\n oauthProviders: z.record(z.string(), z.object({\n subject: z.string(),\n email: z.string().email().optional(),\n name: z.string().optional(),\n accessToken: z.string().optional(),\n refreshToken: z.string().optional(),\n idToken: z.string().optional(),\n scope: z.string().optional(),\n tokenType: z.string().optional(),\n expiresAt: z.date().optional(),\n rawUserInfo: z.unknown().optional(),\n createdAt: z.date().optional(),\n updatedAt: z.date().optional(),\n })).optional(),\n emailVerificationCode: z.string().length(6).optional(),\n emailVerificationExpiresAt: z.date().optional(),\n passwordResetCode: z.string().length(6).optional(),\n passwordResetCodeExpiresAt: z.date().optional(),\n passwordResetToken: z.string().optional(),\n passwordResetTokenExpiresAt: z.date().optional(),\n})\n\nexport type IRBUser = z.infer<typeof ZRBUser>;\n\nexport const RBUserSchema: Schema = new Schema({\n email: { type: String, unique: true, sparse: true },\n phone: { type: String, unique: true, sparse: true },\n password: { type: String, required: true },\n name: String,\n tenants: { type: [String], index: true, required: true },\n tenantRoles: { type: Map, of: [String], required: false, default: {} },\n oauthProviders: {\n type: Map,\n of: new Schema({\n subject: { type: String, required: true },\n email: { type: String, required: false },\n name: { type: String, required: false },\n accessToken: { type: String, required: false },\n refreshToken: { type: String, required: false },\n idToken: { type: String, required: false },\n scope: { type: String, required: false },\n tokenType: { type: String, required: false },\n expiresAt: { type: Date, required: false },\n rawUserInfo: { type: Schema.Types.Mixed, required: false },\n createdAt: { type: Date, required: false },\n updatedAt: { type: Date, required: false },\n }, { _id: false }),\n default: {},\n required: false,\n },\n emailVerificationCode: { type: String, required: false },\n emailVerificationExpiresAt: { type: Date, required: false },\n passwordResetCode: { type: String, required: false },\n passwordResetCodeExpiresAt: { type: Date, required: false },\n passwordResetToken: { type: String, required: false },\n passwordResetTokenExpiresAt: { type: Date, required: false },\n})\n","import { Schema } from \"mongoose\"\nimport { z } from \"zod\"\n\n\nexport const ZRBTenant = z.object({\n tenantId: z.string(),\n parentTenantId: z.string().optional(),\n name: z.string().optional(),\n})\n\nexport type IRBTenant = z.infer<typeof ZRBTenant>;\n\nexport const RBTenantSchema: Schema = new Schema({\n tenantId: { type: String, required: true, unique: true, index: true },\n parentTenantId: { type: String },\n name: { type: String },\n})\n","import { Schema } from \"mongoose\"\nimport { z } from \"zod\"\nimport {\n SUBSCRIPTION_CHANGE_DIRECTIONS,\n SUBSCRIPTION_EVENT_TYPES,\n SUBSCRIPTION_INTERVAL_UNITS,\n SUBSCRIPTION_SCOPES,\n SUBSCRIPTION_STATUSES,\n SUBSCRIPTION_TYPES,\n} from \"@rpcbase/billing\"\n\n\nexport const ZRBTenantSubscriptionStatus = z.enum(SUBSCRIPTION_STATUSES)\n\nexport const ZRBTenantSubscriptionIntervalUnit = z.enum(SUBSCRIPTION_INTERVAL_UNITS)\n\nexport const ZRBTenantSubscriptionType = z.enum(SUBSCRIPTION_TYPES)\n\nexport const ZRBTenantSubscriptionScope = z.enum(SUBSCRIPTION_SCOPES)\n\nexport const ZRBTenantSubscriptionEventType = z.enum(SUBSCRIPTION_EVENT_TYPES)\n\n\nexport const ZRBTenantSubscriptionEventSource = z.enum([\n \"admin\",\n \"system\",\n \"webhook\",\n \"user\",\n])\n\nexport const ZRBTenantSubscriptionChangeDirection = z.enum(SUBSCRIPTION_CHANGE_DIRECTIONS)\n\nconst subscriptionEventBaseSchema = z.object({\n tenantId: z.string().trim().min(1),\n subscriptionId: z.string().trim().min(1),\n occurredAt: z.date(),\n effectiveAt: z.date(),\n subscriptionType: ZRBTenantSubscriptionType,\n parentSubscriptionId: z.string().optional(),\n scope: ZRBTenantSubscriptionScope,\n scopeId: z.string().optional(),\n fromPlanKey: z.string().optional(),\n toPlanKey: z.string().optional(),\n fromStatus: ZRBTenantSubscriptionStatus.optional(),\n toStatus: ZRBTenantSubscriptionStatus.optional(),\n fromModules: z.array(z.string()).optional(),\n toModules: z.array(z.string()).optional(),\n fromIntervalUnit: ZRBTenantSubscriptionIntervalUnit.optional(),\n toIntervalUnit: ZRBTenantSubscriptionIntervalUnit.optional(),\n fromIntervalCount: z.number().int().min(1).optional(),\n toIntervalCount: z.number().int().min(1).optional(),\n fromPriceId: z.string().optional(),\n toPriceId: z.string().optional(),\n billingAnchor: z.date().optional(),\n supersedesEventId: z.string().optional(),\n idempotencyKey: z.string().trim().min(1),\n direction: ZRBTenantSubscriptionChangeDirection.optional(),\n actorUserId: z.string().optional(),\n source: ZRBTenantSubscriptionEventSource.optional(),\n reason: z.string().optional(),\n provider: z.string().optional(),\n providerEventId: z.string().optional(),\n providerPayload: z.unknown().optional(),\n metadata: z.record(z.string(), z.unknown()).optional(),\n})\n\nconst subscriptionCreatedEventSchema = subscriptionEventBaseSchema.extend({\n type: z.literal(\"created\"),\n toPlanKey: z.string().trim().min(1),\n toStatus: ZRBTenantSubscriptionStatus,\n toModules: z.array(z.string()),\n toIntervalUnit: ZRBTenantSubscriptionIntervalUnit,\n toIntervalCount: z.number().int().min(1),\n billingAnchor: z.date(),\n})\n\nconst subscriptionPlanChangedEventSchema = subscriptionEventBaseSchema.extend({\n type: z.literal(\"plan_changed\"),\n fromPlanKey: z.string().trim().min(1),\n toPlanKey: z.string().trim().min(1),\n fromModules: z.array(z.string()),\n toModules: z.array(z.string()),\n fromIntervalUnit: ZRBTenantSubscriptionIntervalUnit,\n toIntervalUnit: ZRBTenantSubscriptionIntervalUnit,\n fromIntervalCount: z.number().int().min(1),\n toIntervalCount: z.number().int().min(1),\n})\n\nconst subscriptionStatusChangedEventSchema = subscriptionEventBaseSchema.extend({\n type: z.literal(\"status_changed\"),\n fromStatus: ZRBTenantSubscriptionStatus,\n toStatus: ZRBTenantSubscriptionStatus,\n})\n\nconst subscriptionResumedEventSchema = subscriptionEventBaseSchema.extend({\n type: z.literal(\"resumed\"),\n fromStatus: ZRBTenantSubscriptionStatus,\n toStatus: z.literal(\"active\"),\n})\n\nconst subscriptionCanceledEventSchema = subscriptionEventBaseSchema.extend({\n type: z.literal(\"canceled\"),\n fromStatus: ZRBTenantSubscriptionStatus,\n toStatus: z.literal(\"canceled\"),\n})\n\nconst subscriptionRenewedEventSchema = subscriptionEventBaseSchema.extend({\n type: z.literal(\"renewed\"),\n fromStatus: ZRBTenantSubscriptionStatus,\n toStatus: ZRBTenantSubscriptionStatus,\n})\n\nexport const ZRBTenantSubscriptionEvent = z.discriminatedUnion(\"type\", [\n subscriptionCreatedEventSchema,\n subscriptionPlanChangedEventSchema,\n subscriptionStatusChangedEventSchema,\n subscriptionResumedEventSchema,\n subscriptionCanceledEventSchema,\n subscriptionRenewedEventSchema,\n]).superRefine((event, ctx) => {\n if (event.subscriptionType === \"addon\" && !event.parentSubscriptionId?.trim()) {\n ctx.addIssue({\n code: \"custom\",\n message: \"parentSubscriptionId is required for add-on subscriptions\",\n path: [\"parentSubscriptionId\"],\n })\n }\n if (event.scope !== \"tenant\" && !event.scopeId?.trim()) {\n ctx.addIssue({\n code: \"custom\",\n message: \"scopeId is required for non-tenant subscriptions\",\n path: [\"scopeId\"],\n })\n }\n})\n\nexport type IRBTenantSubscriptionEvent = z.infer<typeof ZRBTenantSubscriptionEvent>\n\ntype SubscriptionEventDocument = {\n type?: typeof SUBSCRIPTION_EVENT_TYPES[number]\n subscriptionType?: typeof SUBSCRIPTION_TYPES[number]\n scope?: typeof SUBSCRIPTION_SCOPES[number]\n}\n\nconst requiredForEventTypes = (...types: Array<typeof SUBSCRIPTION_EVENT_TYPES[number]>) =>\n function requiredForEventType(this: SubscriptionEventDocument): boolean {\n return Boolean(this.type && types.includes(this.type))\n }\n\nexport const RBTenantSubscriptionEventSchema: Schema = new Schema(\n {\n tenantId: { type: String, required: true, index: true },\n subscriptionId: { type: String, required: true, index: true },\n type: { type: String, required: true, enum: ZRBTenantSubscriptionEventType.options },\n occurredAt: { type: Date, required: true, default: Date.now },\n effectiveAt: { type: Date, required: true },\n subscriptionType: { type: String, required: true, enum: ZRBTenantSubscriptionType.options },\n parentSubscriptionId: {\n type: String,\n required(this: SubscriptionEventDocument) {\n return this.subscriptionType === \"addon\"\n },\n },\n scope: { type: String, required: true, enum: ZRBTenantSubscriptionScope.options },\n scopeId: {\n type: String,\n required(this: SubscriptionEventDocument) {\n return Boolean(this.scope && this.scope !== \"tenant\")\n },\n },\n fromPlanKey: { type: String, required: requiredForEventTypes(\"plan_changed\") },\n toPlanKey: { type: String, required: requiredForEventTypes(\"created\", \"plan_changed\") },\n fromStatus: {\n type: String,\n required: requiredForEventTypes(\"status_changed\", \"resumed\", \"canceled\", \"renewed\"),\n enum: ZRBTenantSubscriptionStatus.options,\n },\n toStatus: {\n type: String,\n required: requiredForEventTypes(\"created\", \"status_changed\", \"resumed\", \"canceled\", \"renewed\"),\n enum: ZRBTenantSubscriptionStatus.options,\n },\n fromModules: { type: [String], required: requiredForEventTypes(\"plan_changed\"), default: undefined },\n toModules: { type: [String], required: requiredForEventTypes(\"created\", \"plan_changed\"), default: undefined },\n fromIntervalUnit: {\n type: String,\n required: requiredForEventTypes(\"plan_changed\"),\n enum: ZRBTenantSubscriptionIntervalUnit.options,\n },\n toIntervalUnit: {\n type: String,\n required: requiredForEventTypes(\"created\", \"plan_changed\"),\n enum: ZRBTenantSubscriptionIntervalUnit.options,\n },\n fromIntervalCount: { type: Number, required: requiredForEventTypes(\"plan_changed\"), min: 1 },\n toIntervalCount: { type: Number, required: requiredForEventTypes(\"created\", \"plan_changed\"), min: 1 },\n fromPriceId: { type: String },\n toPriceId: { type: String },\n billingAnchor: { type: Date, required: requiredForEventTypes(\"created\") },\n supersedesEventId: { type: String },\n idempotencyKey: { type: String, required: true },\n direction: { type: String, enum: ZRBTenantSubscriptionChangeDirection.options },\n actorUserId: { type: String },\n source: { type: String, enum: ZRBTenantSubscriptionEventSource.options },\n reason: { type: String },\n provider: { type: String },\n providerEventId: { type: String },\n providerPayload: { type: Schema.Types.Mixed },\n metadata: { type: Schema.Types.Mixed },\n },\n)\n\nRBTenantSubscriptionEventSchema.index({ tenantId: 1, subscriptionId: 1, effectiveAt: 1, occurredAt: 1 })\nRBTenantSubscriptionEventSchema.index(\n { provider: 1, providerEventId: 1 },\n {\n unique: true,\n partialFilterExpression: {\n provider: { $type: \"string\" },\n providerEventId: { $type: \"string\" },\n },\n },\n)\nRBTenantSubscriptionEventSchema.index({ tenantId: 1, idempotencyKey: 1 }, { unique: true })\n","import { Schema } from \"mongoose\"\nimport { z } from \"zod\"\n\nimport {\n ZRBTenantSubscriptionIntervalUnit,\n ZRBTenantSubscriptionScope,\n ZRBTenantSubscriptionStatus,\n ZRBTenantSubscriptionType,\n} from \"./RBTenantSubscriptionEvent\"\n\n\nexport const ZRBTenantSubscriptionProjection = z.object({\n tenantId: z.string(),\n subscriptionId: z.string(),\n type: ZRBTenantSubscriptionType,\n parentSubscriptionId: z.string().optional(),\n scope: ZRBTenantSubscriptionScope,\n scopeId: z.string().optional(),\n planKey: z.string(),\n priceId: z.string().optional(),\n status: ZRBTenantSubscriptionStatus,\n intervalUnit: ZRBTenantSubscriptionIntervalUnit,\n intervalCount: z.number().int().min(1),\n modules: z.array(z.string()),\n billingAnchor: z.date(),\n currentPeriodStart: z.date(),\n currentPeriodEnd: z.date(),\n cancelAtPeriodEnd: z.boolean(),\n cancelAt: z.date().optional(),\n canceledAt: z.date().optional(),\n scheduledPlanKey: z.string().optional(),\n scheduledPlanEffectiveAt: z.date().optional(),\n provider: z.string().optional(),\n latestEventId: z.string(),\n latestEventAt: z.date(),\n projectedAt: z.date(),\n})\n\nexport type IRBTenantSubscriptionProjection = z.infer<typeof ZRBTenantSubscriptionProjection>\n\nexport const RBTenantSubscriptionProjectionSchema: Schema = new Schema({\n tenantId: { type: String, required: true, index: true },\n subscriptionId: { type: String, required: true },\n type: { type: String, required: true, enum: ZRBTenantSubscriptionType.options },\n parentSubscriptionId: { type: String },\n scope: { type: String, required: true, enum: ZRBTenantSubscriptionScope.options },\n scopeId: { type: String },\n planKey: { type: String, required: true },\n priceId: { type: String },\n status: { type: String, required: true, enum: ZRBTenantSubscriptionStatus.options },\n intervalUnit: { type: String, required: true, enum: ZRBTenantSubscriptionIntervalUnit.options },\n intervalCount: { type: Number, required: true, min: 1 },\n modules: { type: [String], required: true, default: [] },\n billingAnchor: { type: Date, required: true },\n currentPeriodStart: { type: Date, required: true },\n currentPeriodEnd: { type: Date, required: true },\n cancelAtPeriodEnd: { type: Boolean, required: true, default: false },\n cancelAt: { type: Date },\n canceledAt: { type: Date },\n scheduledPlanKey: { type: String },\n scheduledPlanEffectiveAt: { type: Date },\n provider: { type: String },\n latestEventId: { type: String, required: true },\n latestEventAt: { type: Date, required: true },\n projectedAt: { type: Date, required: true },\n})\n\nRBTenantSubscriptionProjectionSchema.index({ tenantId: 1, subscriptionId: 1 }, { unique: true })\nRBTenantSubscriptionProjectionSchema.index({ tenantId: 1, scope: 1, scopeId: 1 })\n","import { Schema } from \"mongoose\"\nimport { z } from \"zod\"\n\n\nexport const ZRBRtsCounter = z.object({\n _id: z.string(),\n seq: z.number().int().min(0),\n})\n\nexport type IRBRtsCounter = z.infer<typeof ZRBRtsCounter>\n\nexport const RBRtsCounterSchema: Schema = new Schema(\n {\n _id: { type: String, required: true },\n seq: { type: Number, required: true, default: 0 },\n },\n {\n versionKey: false,\n },\n)\n","import { Schema } from \"mongoose\"\nimport { z } from \"zod\"\n\n\nconst ttlSecondsRaw = process.env.RB_RTS_CHANGES_TTL_S ?? \"\"\nconst ttlSeconds = Number.isFinite(Number(ttlSecondsRaw)) ? Math.max(60, Math.floor(Number(ttlSecondsRaw))) : 60 * 60 * 24 * 30\n\nexport const ZRBRtsChangeOp = z.enum([\"delete\", \"reset_model\"])\n\nexport const ZRBRtsChange = z.object({\n seq: z.number().int().min(0),\n modelName: z.string(),\n op: ZRBRtsChangeOp,\n docId: z.string().optional(),\n ts: z.date(),\n})\n\nexport type IRBRtsChange = z.infer<typeof ZRBRtsChange>\n\nexport const RBRtsChangeSchema: Schema = new Schema(\n {\n seq: { type: Number, required: true },\n modelName: { type: String, required: true, index: true },\n op: { type: String, required: true, enum: ZRBRtsChangeOp.options },\n docId: { type: String, required: false },\n ts: { type: Date, required: true, default: Date.now },\n },\n {\n versionKey: false,\n },\n)\n\nRBRtsChangeSchema.index({ seq: 1 }, { unique: true })\nRBRtsChangeSchema.index({ ts: 1 }, { expireAfterSeconds: ttlSeconds })\n","import { Schema } from \"mongoose\"\nimport { z } from \"zod\"\n\nimport type { AclPolicy } from \"../acl\"\n\n\nexport const ZRBUploadSessionStatus = z.enum([\"uploading\", \"assembling\", \"done\", \"error\"])\n\nexport const ZRBUploadSession = z.object({\n _id: z.string(),\n userId: z.string().optional(),\n ownerKeyHash: z.string().optional(),\n filename: z.string(),\n mimeType: z.string(),\n totalSize: z.number().int().min(0),\n chunkSize: z.number().int().min(1),\n chunksTotal: z.number().int().min(1),\n status: ZRBUploadSessionStatus,\n createdAt: z.date(),\n expiresAt: z.date(),\n fileId: z.string().optional(),\n isPublic: z.boolean().optional(),\n error: z.string().optional(),\n})\n\nexport type IRBUploadSession = z.infer<typeof ZRBUploadSession>\n\nexport const RBUploadSessionSchema: Schema = new Schema(\n {\n _id: { type: String, required: true },\n userId: { type: String, required: false, index: true },\n ownerKeyHash: { type: String, required: false },\n filename: { type: String, required: true },\n mimeType: { type: String, required: true },\n totalSize: { type: Number, required: true },\n chunkSize: { type: Number, required: true },\n chunksTotal: { type: Number, required: true },\n status: { type: String, required: true, enum: ZRBUploadSessionStatus.options },\n createdAt: { type: Date, required: true, default: Date.now },\n expiresAt: { type: Date, required: true },\n fileId: { type: String, required: false },\n isPublic: { type: Boolean, required: false },\n error: { type: String, required: false },\n },\n {\n versionKey: false,\n },\n)\n\nRBUploadSessionSchema.index({ expiresAt: 1 }, { expireAfterSeconds: 0 })\n\nexport const RBUploadSessionPolicy: AclPolicy = {\n subject: \"RBUploadSession\",\n define: (builder, ctx) => {\n builder.can(\"create\", \"RBUploadSession\")\n\n if (ctx.userId) {\n builder.can(\"read\", \"RBUploadSession\", { userId: ctx.userId })\n builder.can(\"update\", \"RBUploadSession\", { userId: ctx.userId })\n builder.can(\"delete\", \"RBUploadSession\", { userId: ctx.userId })\n }\n\n const uploadKeyHash = typeof ctx.claims?.uploadKeyHash === \"string\" ? ctx.claims.uploadKeyHash.trim() : \"\"\n if (uploadKeyHash) {\n builder.can(\"read\", \"RBUploadSession\", { ownerKeyHash: uploadKeyHash })\n builder.can(\"update\", \"RBUploadSession\", { ownerKeyHash: uploadKeyHash })\n builder.can(\"delete\", \"RBUploadSession\", { ownerKeyHash: uploadKeyHash })\n }\n },\n}\n","import { Schema } from \"mongoose\"\nimport { z } from \"zod\"\n\n\nexport const ZRBUploadChunk = z.object({\n uploadId: z.string(),\n index: z.number().int().min(0),\n data: z.unknown(),\n size: z.number().int().min(0),\n sha256: z.string().optional(),\n createdAt: z.date(),\n expiresAt: z.date(),\n})\n\nexport type IRBUploadChunk = z.infer<typeof ZRBUploadChunk>\n\nexport const RBUploadChunkSchema: Schema = new Schema(\n {\n uploadId: { type: String, required: true, index: true },\n index: { type: Number, required: true },\n data: { type: Buffer, required: true },\n size: { type: Number, required: true },\n sha256: { type: String, required: false },\n createdAt: { type: Date, required: true, default: Date.now },\n expiresAt: { type: Date, required: true },\n },\n {\n versionKey: false,\n },\n)\n\nRBUploadChunkSchema.index({ uploadId: 1, index: 1 }, { unique: true })\nRBUploadChunkSchema.index({ expiresAt: 1 }, { expireAfterSeconds: 0 })\n","import { Schema } from \"mongoose\"\nimport { z } from \"zod\"\n\nimport type { AclPolicy } from \"../acl\"\n\n\nconst ZStringMap = z.record(z.string(), z.string())\n\nexport const ZRBNotificationPlatformPayload = z.object({\n webpush: z.record(z.string(), z.unknown()).optional(),\n fcmOptions: z.record(z.string(), z.unknown()).optional(),\n android: z.record(z.string(), z.unknown()).optional(),\n apns: z.record(z.string(), z.unknown()).optional(),\n}).passthrough()\n\nexport type IRBNotificationPlatformPayload = z.infer<typeof ZRBNotificationPlatformPayload>\n\nexport const ZRBNotification = z.object({\n userId: z.string(),\n topic: z.string().optional(),\n tag: z.string().optional(),\n deliveryId: z.string().optional(),\n title: z.string(),\n body: z.string().optional(),\n image: z.string().optional(),\n data: ZStringMap.optional(),\n platform: ZRBNotificationPlatformPayload.optional(),\n drawerActive: z.boolean().optional(),\n createdAt: z.date(),\n seenAt: z.date().optional(),\n readAt: z.date().optional(),\n archivedAt: z.date().optional(),\n})\n\nexport type IRBNotification = z.infer<typeof ZRBNotification>\n\nconst TTL_90_DAYS_S = 60 * 60 * 24 * 90\n\nexport const RBNotificationSchema: Schema = new Schema(\n {\n userId: { type: String, required: true, index: true },\n topic: { type: String, required: false, index: true },\n tag: { type: String, required: false },\n deliveryId: { type: String, required: false },\n title: { type: String, required: true },\n body: { type: String, required: false },\n image: { type: String, required: false },\n data: { type: Schema.Types.Mixed, required: false },\n platform: { type: Schema.Types.Mixed, required: false },\n drawerActive: { type: Boolean, required: false },\n createdAt: { type: Date, required: true, default: Date.now, index: true },\n seenAt: { type: Date, required: false, index: true },\n readAt: { type: Date, required: false, index: true },\n archivedAt: { type: Date, required: false },\n },\n {\n versionKey: false,\n },\n)\n\nRBNotificationSchema.index({ userId: 1, archivedAt: 1, createdAt: -1 })\nRBNotificationSchema.index({ userId: 1, seenAt: 1, archivedAt: 1, createdAt: -1 })\nRBNotificationSchema.index({ userId: 1, readAt: 1, archivedAt: 1, createdAt: -1 })\nRBNotificationSchema.index(\n { userId: 1, tag: 1 },\n { unique: true, partialFilterExpression: { tag: { $exists: true }, drawerActive: true } },\n)\nRBNotificationSchema.index({ archivedAt: 1 }, { expireAfterSeconds: TTL_90_DAYS_S })\n\nexport const RBNotificationPolicy: AclPolicy = {\n subject: \"RBNotification\",\n define: (builder, ctx) => {\n if (!ctx.userId) return\n builder.can(\"create\", \"RBNotification\")\n builder.can(\"read\", \"RBNotification\", { userId: ctx.userId })\n builder.can(\"update\", \"RBNotification\", { userId: ctx.userId })\n builder.can(\"delete\", \"RBNotification\", { userId: ctx.userId })\n },\n}\n","import { Schema } from \"mongoose\"\nimport { z } from \"zod\"\n\nimport type { AclPolicy } from \"../acl\"\nimport { ZRBNotificationPlatformPayload } from \"./RBNotification\"\n\n\nconst ZStringMap = z.record(z.string(), z.string())\n\nexport const ZRBNotificationDelivery = z.object({\n userId: z.string(),\n notificationId: z.string().optional(),\n deliveryId: z.string(),\n topic: z.string().optional(),\n tag: z.string().optional(),\n title: z.string(),\n body: z.string().optional(),\n image: z.string().optional(),\n data: ZStringMap.optional(),\n platform: ZRBNotificationPlatformPayload.optional(),\n createdAt: z.date(),\n})\n\nexport type IRBNotificationDelivery = z.infer<typeof ZRBNotificationDelivery>\n\nconst TTL_90_DAYS_S = 60 * 60 * 24 * 90\n\nexport const RBNotificationDeliverySchema: Schema = new Schema(\n {\n userId: { type: String, required: true, index: true },\n notificationId: { type: String, required: false },\n deliveryId: { type: String, required: true, unique: true },\n topic: { type: String, required: false },\n tag: { type: String, required: false },\n title: { type: String, required: true },\n body: { type: String, required: false },\n image: { type: String, required: false },\n data: { type: Schema.Types.Mixed, required: false },\n platform: { type: Schema.Types.Mixed, required: false },\n createdAt: { type: Date, required: true, default: Date.now },\n },\n {\n versionKey: false,\n },\n)\n\nRBNotificationDeliverySchema.index({ userId: 1, createdAt: -1 })\nRBNotificationDeliverySchema.index({ createdAt: 1 }, { expireAfterSeconds: TTL_90_DAYS_S })\n\nexport const RBNotificationDeliveryPolicy: AclPolicy = {\n subject: \"RBNotificationDelivery\",\n define: (builder, ctx) => {\n if (!ctx.userId) return\n builder.can(\"create\", \"RBNotificationDelivery\")\n builder.can(\"read\", \"RBNotificationDelivery\", { userId: ctx.userId })\n },\n}\n","import { Schema } from \"mongoose\"\nimport { z } from \"zod\"\n\nimport type { AclPolicy } from \"../acl\"\n\n\nexport const ZRBNotificationDigestFrequency = z.enum([\"off\", \"daily\", \"weekly\"])\n\nexport const ZRBNotificationTopicPreference = z.object({\n topic: z.string(),\n inApp: z.boolean(),\n emailDigest: z.boolean(),\n push: z.boolean(),\n})\n\nexport const ZRBNotificationSettings = z.object({\n userId: z.string(),\n digestFrequency: ZRBNotificationDigestFrequency,\n topicPreferences: z.array(ZRBNotificationTopicPreference).optional(),\n lastDigestSentAt: z.date().optional(),\n})\n\nexport type IRBNotificationSettings = z.infer<typeof ZRBNotificationSettings>\n\nconst TopicPreferenceSchema = new Schema(\n {\n topic: { type: String, required: true },\n inApp: { type: Boolean, required: true, default: true },\n emailDigest: { type: Boolean, required: true, default: true },\n push: { type: Boolean, required: true, default: false },\n },\n { _id: false },\n)\n\nexport const RBNotificationSettingsSchema: Schema = new Schema(\n {\n userId: { type: String, required: true },\n digestFrequency: {\n type: String,\n required: true,\n enum: ZRBNotificationDigestFrequency.options,\n default: \"weekly\",\n },\n topicPreferences: {\n type: [TopicPreferenceSchema],\n default: [],\n },\n lastDigestSentAt: { type: Date, required: false },\n },\n {\n versionKey: false,\n timestamps: true,\n },\n)\n\nRBNotificationSettingsSchema.index({ userId: 1 }, { unique: true })\nRBNotificationSettingsSchema.index({ userId: 1, \"topicPreferences.topic\": 1 })\n\nexport const RBNotificationSettingsPolicy: AclPolicy = {\n subject: \"RBNotificationSettings\",\n define: (builder, ctx) => {\n if (!ctx.userId) return\n builder.can(\"create\", \"RBNotificationSettings\")\n builder.can(\"read\", \"RBNotificationSettings\", { userId: ctx.userId })\n builder.can(\"update\", \"RBNotificationSettings\", { userId: ctx.userId })\n },\n}\n","import { Schema } from \"mongoose\"\nimport { z } from \"zod\"\n\n\nexport const ZRBOAuthRequest = z.object({\n _id: z.string(),\n providerId: z.string(),\n codeVerifier: z.string(),\n returnTo: z.string().optional(),\n createdAt: z.date(),\n expiresAt: z.date(),\n})\n\nexport type IRBOAuthRequest = z.infer<typeof ZRBOAuthRequest>\n\nexport const RBOAuthRequestSchema: Schema = new Schema(\n {\n _id: { type: String, required: true },\n providerId: { type: String, required: true, index: true },\n codeVerifier: { type: String, required: true },\n returnTo: { type: String, required: false },\n createdAt: { type: Date, required: true, default: Date.now },\n expiresAt: { type: Date, required: true },\n },\n { versionKey: false },\n)\n\nRBOAuthRequestSchema.index({ expiresAt: 1 }, { expireAfterSeconds: 0 })\n","export * from \"./RBUser\"\nexport * from \"./RBTenant\"\nexport * from \"./RBTenantSubscriptionEvent\"\nexport * from \"./RBTenantSubscriptionProjection\"\nexport * from \"./RBRtsCounter\"\nexport * from \"./RBRtsChange\"\nexport * from \"./RBUploadSession\"\nexport * from \"./RBUploadChunk\"\nexport * from \"./RBNotification\"\nexport * from \"./RBNotificationDelivery\"\nexport * from \"./RBNotificationSettings\"\nexport * from \"./RBOAuthRequest\"\n","import { Schema } from \"mongoose\"\n\n\ntype MongooseSchemaExtension = Parameters<Schema[\"add\"]>[0]\n\nexport function extendMongooseSchema<TSchema extends Schema>(\n baseSchema: TSchema,\n ...extensions: MongooseSchemaExtension[]\n): TSchema {\n const schema = baseSchema.clone() as TSchema\n\n extensions.forEach((extension) => schema.add(extension))\n\n return schema\n}\n\nexport function omitMongooseSchemaPaths<TSchema extends Schema>(\n schema: TSchema,\n paths: string[],\n): TSchema {\n const clone = schema.clone() as TSchema\n paths.forEach((path) => clone.remove(path))\n return clone\n}\n","import { Schema } from \"mongoose\"\nimport type { SchemaTypeOptions } from \"mongoose\"\n\nimport type { LocalizedString } from \"../zod/localizedString\"\nimport { withLocalizedStringFallback } from \"../zod/localizedString\"\n\n\nexport function localizedStringField(\n options?: Omit<SchemaTypeOptions<LocalizedString>, \"type\">\n): SchemaTypeOptions<LocalizedString> {\n const userGet = options?.get\n\n return {\n ...options,\n type: Schema.Types.Mixed,\n get: (value: unknown) => withLocalizedStringFallback(userGet ? userGet(value) : value),\n }\n}\n","import mongoose from \"mongoose\"\nimport type { InferSchemaType } from \"mongoose\"\n\n\nconst { Schema, model } = mongoose\n\nexport { Schema, model, mongoose, type InferSchemaType }\nexport * from \"./extendMongooseSchema\"\nexport * from \"./localizedStringField\"\n","export type PaginationErrorCode = \"invalid_pagination\"\n\nexport class PaginationValidationError extends Error {\n readonly code: PaginationErrorCode = \"invalid_pagination\"\n readonly statusCode = 400\n\n constructor(message: string, options?: ErrorOptions) {\n super(message, options)\n this.name = \"PaginationValidationError\"\n }\n}\n\nexport const isPaginationValidationError = (error: unknown): error is PaginationValidationError => {\n if (!error || typeof error !== \"object\") return false\n const anyError = error as Partial<PaginationValidationError>\n return (\n anyError.name === \"PaginationValidationError\" &&\n anyError.code === \"invalid_pagination\" &&\n anyError.statusCode === 400\n )\n}\n","import type { PaginationDirection, PaginationOrder, PaginationSpec } from \"@rpcbase/api\"\n\nimport { PaginationValidationError } from \"./errors\"\n\n\nconst DISALLOWED_MONGO_FIELD_SEGMENTS = new Set([\"__proto__\", \"constructor\", \"prototype\"])\nconst PAGINATION_LIMIT_MAX = 128\nexport type NormalizedPaginationSpec = Omit<PaginationSpec, \"direction\" | \"sort\" | \"limit\"> & {\n direction: PaginationDirection;\n limit: number;\n sort: Array<{\n field: string;\n order: PaginationOrder;\n }>;\n}\n\nexport const normalizePaginationSpec = (\n spec: PaginationSpec,\n options: { maxLimit?: number } = {},\n): NormalizedPaginationSpec => {\n if (!spec || typeof spec !== \"object\") throw new PaginationValidationError(\"Invalid PaginationSpec\")\n\n const limit = normalizeLimit(spec.limit, normalizeMaxLimit(options.maxLimit))\n const direction = spec.direction ?? \"next\"\n if (direction !== \"next\" && direction !== \"prev\") throw new PaginationValidationError(\"Invalid pagination direction\")\n\n if (!Array.isArray(spec.sort) || spec.sort.length === 0) throw new PaginationValidationError(\"Invalid pagination sort\")\n\n const sort: NormalizedPaginationSpec[\"sort\"] = spec.sort.map(({ field, order }) => ({\n field: assertSafeMongoFieldPath(field),\n order: normalizeOrder(order),\n }))\n\n const seenFields = new Set<string>()\n for (const { field } of sort) {\n if (seenFields.has(field)) throw new PaginationValidationError(`Duplicate pagination sort field: ${field}`)\n seenFields.add(field)\n }\n\n const primaryOrder = sort[0]?.order\n\n if (!seenFields.has(\"_id\")) {\n sort.push({ field: \"_id\", order: primaryOrder })\n }\n\n return {\n ...spec,\n limit,\n direction,\n sort,\n }\n}\n\nconst normalizeMaxLimit = (maxLimit: unknown): number => {\n if (maxLimit === undefined) return PAGINATION_LIMIT_MAX\n if (!Number.isSafeInteger(maxLimit) || (maxLimit as number) <= 0) {\n throw new PaginationValidationError(\"Invalid pagination max limit\")\n }\n return maxLimit as number\n}\n\nconst normalizeLimit = (limit: unknown, maxLimit: number): number => {\n if (typeof limit !== \"number\" || !Number.isFinite(limit) || !Number.isInteger(limit) || limit <= 0) {\n throw new PaginationValidationError(\"Invalid pagination limit\")\n }\n if (limit > maxLimit) {\n throw new PaginationValidationError(\"Invalid pagination limit\")\n }\n return limit\n}\n\nconst normalizeOrder = (order: unknown): PaginationOrder => {\n if (order !== \"asc\" && order !== \"desc\") throw new PaginationValidationError(\"Invalid pagination order\")\n return order\n}\n\nconst assertSafeMongoFieldPath = (field: unknown): string => {\n if (typeof field !== \"string\" || field.length === 0) throw new PaginationValidationError(\"Invalid pagination sort field\")\n if (field.startsWith(\"$\")) throw new PaginationValidationError(\"Invalid pagination sort field\")\n\n const parts = field.split(\".\")\n for (const part of parts) {\n if (part.length === 0) throw new PaginationValidationError(\"Invalid pagination sort field\")\n if (DISALLOWED_MONGO_FIELD_SEGMENTS.has(part)) throw new PaginationValidationError(\"Invalid pagination sort field\")\n if (!/^[a-zA-Z0-9_]+$/.test(part)) throw new PaginationValidationError(\"Invalid pagination sort field\")\n }\n\n return field\n}\n","import { createHmac, timingSafeEqual } from \"node:crypto\"\n\nimport { Types } from \"mongoose\"\nimport type { PaginationSpec } from \"@rpcbase/api\"\n\nimport { PaginationValidationError } from \"./errors\"\nimport { normalizePaginationSpec } from \"./normalizeSpec\"\n\n\ntype CursorValue =\n | null\n | string\n | number\n | boolean\n | { $date: string }\n | { $oid: string }\n\ntype CursorPayloadV1 = {\n v: 1;\n values: Record<string, CursorValue>;\n}\n\nexport type PaginationCursorCodecOptions = {\n signingSecret: string | Buffer;\n maxLimit?: number;\n}\n\nexport const encodePaginationCursor = (\n spec: PaginationSpec,\n node: unknown,\n options: PaginationCursorCodecOptions,\n): string => {\n const normalized = normalizePaginationSpec(spec, { maxLimit: options.maxLimit })\n\n const values = Object.create(null) as Record<string, CursorValue>\n for (const { field } of normalized.sort) {\n const value = readFieldValue(node, field)\n if (typeof value === \"undefined\") {\n throw new Error(`Pagination cursor encode failed (missing field: ${field})`)\n }\n values[field] = encodeCursorValue(field, value)\n }\n\n const payload: CursorPayloadV1 = { v: 1, values }\n const payloadB64 = Buffer.from(JSON.stringify(payload), \"utf8\").toString(\"base64url\")\n\n const sigB64 = signCursorPayloadB64(payloadB64, options.signingSecret)\n return `${payloadB64}.${sigB64}`\n}\n\nexport const decodePaginationCursor = (\n spec: PaginationSpec,\n cursor: string,\n options: PaginationCursorCodecOptions,\n): Record<string, unknown> => {\n const normalized = normalizePaginationSpec(spec, { maxLimit: options.maxLimit })\n\n const [payloadB64, sigB64, ...rest] = cursor.split(\".\")\n if (rest.length > 0) throw new PaginationValidationError(\"Invalid pagination cursor format\")\n if (!sigB64) throw new PaginationValidationError(\"Invalid pagination cursor format\")\n verifyCursorSignature(payloadB64, sigB64, options.signingSecret)\n\n const payloadRaw = Buffer.from(payloadB64, \"base64url\").toString(\"utf8\")\n\n let payloadUnknown: unknown\n try {\n payloadUnknown = JSON.parse(payloadRaw)\n } catch {\n throw new PaginationValidationError(\"Invalid pagination cursor payload\")\n }\n\n if (!payloadUnknown || typeof payloadUnknown !== \"object\") throw new PaginationValidationError(\"Invalid pagination cursor payload\")\n const payload = payloadUnknown as Partial<CursorPayloadV1>\n\n if (payload.v !== 1) throw new PaginationValidationError(\"Unsupported pagination cursor version\")\n if (!payload.values || typeof payload.values !== \"object\") throw new PaginationValidationError(\"Invalid pagination cursor payload\")\n\n const decoded = Object.create(null) as Record<string, unknown>\n for (const { field } of normalized.sort) {\n if (!Object.prototype.hasOwnProperty.call(payload.values, field)) {\n throw new PaginationValidationError(`Pagination cursor missing field: ${field}`)\n }\n const encodedValue = (payload.values as Record<string, CursorValue>)[field]\n decoded[field] = decodeCursorValue(field, encodedValue)\n }\n\n return decoded\n}\n\nconst signCursorPayloadB64 = (payloadB64: string, secret: string | Buffer): string => {\n return createHmac(\"sha256\", secret).update(payloadB64, \"utf8\").digest(\"base64url\")\n}\n\nconst verifyCursorSignature = (payloadB64: string, sigB64: string, secret: string | Buffer): void => {\n const expectedSigB64 = signCursorPayloadB64(payloadB64, secret)\n const a = Buffer.from(sigB64, \"utf8\")\n const b = Buffer.from(expectedSigB64, \"utf8\")\n if (a.length !== b.length || !timingSafeEqual(a, b)) {\n throw new PaginationValidationError(\"Invalid pagination cursor signature\")\n }\n}\n\nconst unwrapCursorComparableValue = (value: unknown): unknown => {\n if (value === null || typeof value !== \"object\") return value\n if (value instanceof Date || value instanceof Types.ObjectId) return value\n\n let current: unknown = value\n for (let depth = 0; depth < 4; depth += 1) {\n if (!current || typeof current !== \"object\") return current\n if (current instanceof Date || current instanceof Types.ObjectId) return current\n if (!(\"_id\" in current)) return current\n current = (current as { _id: unknown })._id\n }\n\n return current\n}\n\nconst encodeCursorValue = (field: string, value: unknown): CursorValue => {\n const comparableValue = unwrapCursorComparableValue(value)\n\n if (comparableValue === null) return null\n\n if (field === \"_id\") {\n if (comparableValue instanceof Types.ObjectId) return { $oid: comparableValue.toHexString() }\n if (typeof comparableValue === \"string\") return comparableValue\n throw new Error(\"Pagination cursor encode failed (_id must be an ObjectId or string)\")\n }\n\n if (comparableValue instanceof Date) return { $date: comparableValue.toISOString() }\n\n if (\n typeof comparableValue === \"string\" ||\n typeof comparableValue === \"number\" ||\n typeof comparableValue === \"boolean\"\n ) {\n return comparableValue\n }\n\n if (comparableValue instanceof Types.ObjectId) return { $oid: comparableValue.toHexString() }\n\n throw new Error(`Unsupported pagination cursor value type for field: ${field}`)\n}\n\nconst decodeCursorValue = (field: string, value: CursorValue): unknown => {\n if (value === null) return null\n\n if (typeof value === \"string\") {\n return value\n }\n\n if (typeof value === \"number\" || typeof value === \"boolean\") return value\n\n if (!value || typeof value !== \"object\") throw new PaginationValidationError(`Invalid pagination cursor value for field: ${field}`)\n\n if (\"$date\" in value) {\n if (typeof value.$date !== \"string\") throw new PaginationValidationError(`Invalid pagination cursor date for field: ${field}`)\n const d = new Date(value.$date)\n if (Number.isNaN(d.getTime())) throw new PaginationValidationError(`Invalid pagination cursor date for field: ${field}`)\n return d\n }\n\n if (\"$oid\" in value) {\n if (typeof value.$oid !== \"string\" || !Types.ObjectId.isValid(value.$oid)) {\n throw new PaginationValidationError(`Invalid pagination cursor ObjectId for field: ${field}`)\n }\n return new Types.ObjectId(value.$oid)\n }\n\n throw new PaginationValidationError(`Invalid pagination cursor value for field: ${field}`)\n}\n\nconst readFieldValue = (node: unknown, field: string): unknown => {\n if (!node || typeof node !== \"object\") return undefined\n\n if (\"get\" in node && typeof (node as { get?: unknown }).get === \"function\") {\n return (node as { get: (path: string) => unknown }).get(field)\n }\n\n return field.split(\".\").reduce((acc, key) => {\n if (!acc || typeof acc !== \"object\") return undefined\n return (acc as Record<string, unknown>)[key]\n }, node as unknown)\n}\n","import type { PaginationOrder, PaginationSpec } from \"@rpcbase/api\"\n\nimport type { PaginationCursorCodecOptions } from \"./cursor\"\nimport { decodePaginationCursor } from \"./cursor\"\nimport { PaginationValidationError } from \"./errors\"\nimport type { NormalizedPaginationSpec } from \"./normalizeSpec\"\nimport { normalizePaginationSpec } from \"./normalizeSpec\"\n\n\nexport type CompiledMongoPagination = {\n spec: NormalizedPaginationSpec;\n mongoFilterDelta: Record<string, unknown>;\n mongoSort: Record<string, 1 | -1>;\n mongoLimit: number;\n}\n\nexport type CompileMongoPaginationOptions = {\n cursor: PaginationCursorCodecOptions;\n}\n\nexport const compileMongoPagination = (\n spec: PaginationSpec,\n options: CompileMongoPaginationOptions,\n): CompiledMongoPagination => {\n const normalized = normalizePaginationSpec(spec, { maxLimit: options.cursor.maxLimit })\n\n const mongoLimit = normalized.limit + 1\n const mongoSort = toMongoSort(normalized)\n\n if (normalized.cursor == null) {\n return {\n spec: normalized,\n mongoFilterDelta: {},\n mongoSort,\n mongoLimit,\n }\n }\n\n if (typeof normalized.cursor !== \"string\" || normalized.cursor.length === 0) {\n throw new PaginationValidationError(\"Invalid pagination cursor\")\n }\n\n const cursorValues = decodePaginationCursor(normalized, normalized.cursor, options.cursor)\n const mongoFilterDelta = buildKeysetFilterDelta(normalized, cursorValues)\n\n return {\n spec: normalized,\n mongoFilterDelta,\n mongoSort,\n mongoLimit,\n }\n}\n\nconst toMongoSort = (spec: NormalizedPaginationSpec): Record<string, 1 | -1> => {\n const mongoSort = Object.create(null) as Record<string, 1 | -1>\n for (const { field, order } of spec.sort) {\n const forQueryOrder = spec.direction === \"prev\" ? invertOrder(order) : order\n mongoSort[field] = forQueryOrder === \"asc\" ? 1 : -1\n }\n return mongoSort\n}\n\nconst buildKeysetFilterDelta = (\n spec: NormalizedPaginationSpec,\n cursorValues: Record<string, unknown>,\n): Record<string, unknown> => {\n const branches: Record<string, unknown>[] = []\n\n for (let i = 0; i < spec.sort.length; i++) {\n const current = spec.sort[i]\n if (!current) continue\n\n const and: Record<string, unknown>[] = []\n\n for (let j = 0; j < i; j++) {\n const prev = spec.sort[j]\n if (!prev) continue\n const eq = Object.create(null) as Record<string, unknown>\n eq[prev.field] = cursorValues[prev.field]\n and.push(eq)\n }\n\n const op = getKeysetOp(current.order, spec.direction)\n const cmpOp = Object.create(null) as Record<string, unknown>\n cmpOp[op] = cursorValues[current.field]\n const cmp = Object.create(null) as Record<string, unknown>\n cmp[current.field] = cmpOp\n and.push(cmp)\n\n branches.push(and.length === 1 ? and[0]! : { $and: and })\n }\n\n return { $or: branches }\n}\n\nconst getKeysetOp = (order: PaginationOrder, direction: NormalizedPaginationSpec[\"direction\"]): \"$gt\" | \"$lt\" => {\n if (direction === \"next\") return order === \"asc\" ? \"$gt\" : \"$lt\"\n return order === \"asc\" ? \"$lt\" : \"$gt\"\n}\n\nconst invertOrder = (order: PaginationOrder): PaginationOrder => {\n return order === \"asc\" ? \"desc\" : \"asc\"\n}\n","import type { PaginationResponse } from \"@rpcbase/api\"\n\nimport type { PaginationCursorCodecOptions } from \"./cursor\"\nimport { encodePaginationCursor } from \"./cursor\"\nimport type { CompiledMongoPagination } from \"./compileMongoPagination\"\n\n\nexport type MaterializePaginationOptions = {\n cursor: PaginationCursorCodecOptions;\n includeCursors?: boolean;\n}\n\nexport const materializeMongoPagination = <TNode>(\n compiled: CompiledMongoPagination,\n fetchedNodes: TNode[],\n options: MaterializePaginationOptions,\n): PaginationResponse<TNode> => {\n const limit = compiled.spec.limit\n const hasMore = fetchedNodes.length > limit\n\n const trimmed = fetchedNodes.slice(0, limit)\n const nodes = compiled.spec.direction === \"prev\" ? trimmed.reverse() : trimmed\n\n const hasPrevPage = compiled.spec.direction === \"next\" ? Boolean(compiled.spec.cursor) : hasMore\n const hasNextPage = compiled.spec.direction === \"next\" ? hasMore : Boolean(compiled.spec.cursor)\n\n const pageInfo: PaginationResponse<TNode>[\"pageInfo\"] = {\n hasNextPage,\n hasPrevPage,\n }\n\n if (nodes.length === 0) {\n return { nodes, pageInfo }\n }\n\n if (options.includeCursors !== false && hasPrevPage) {\n pageInfo.prevCursor = encodePaginationCursor(compiled.spec, nodes[0], options.cursor)\n }\n\n if (options.includeCursors !== false && hasNextPage) {\n pageInfo.nextCursor = encodePaginationCursor(compiled.spec, nodes[nodes.length - 1], options.cursor)\n }\n\n return { nodes, pageInfo }\n}\n","import type { CompiledMongoPagination } from \"./compileMongoPagination\"\n\n\ntype MongoQueryLike = {\n where: (delta: Record<string, unknown>) => unknown;\n sort: (sort: Record<string, 1 | -1>) => unknown;\n limit: (limit: number) => unknown;\n}\n\nexport const MongoAdapter = {\n applyPagination: <TQuery extends MongoQueryLike>(query: TQuery, compiled: CompiledMongoPagination): TQuery => {\n query.where(compiled.mongoFilterDelta)\n query.sort(compiled.mongoSort)\n query.limit(compiled.mongoLimit)\n return query\n },\n}\n\n","import type { PaginationResponse, PaginationSpec } from \"@rpcbase/api\"\n\nimport type { PaginationCursorCodecOptions } from \"./cursor\"\nimport { compileMongoPagination } from \"./compileMongoPagination\"\nimport { materializeMongoPagination } from \"./materializePagination\"\nimport { MongoAdapter } from \"./mongoAdapter\"\n\n\ntype MongoPaginateQueryLike<TNode> = {\n where: (delta: Record<string, unknown>) => unknown;\n sort: (sort: Record<string, 1 | -1>) => unknown;\n limit: (limit: number) => unknown;\n exec: () => Promise<TNode[]>;\n}\n\nexport type PaginateMongoQueryOptions = {\n cursor: PaginationCursorCodecOptions;\n includeCursors?: boolean;\n}\n\nexport const paginateMongoQuery = async <TNode>(\n query: MongoPaginateQueryLike<TNode>,\n pagination: PaginationSpec,\n options: PaginateMongoQueryOptions,\n): Promise<PaginationResponse<TNode>> => {\n const compiled = compileMongoPagination(pagination, { cursor: options.cursor })\n\n MongoAdapter.applyPagination(query, compiled)\n\n const fetchedNodes = await query.exec()\n if (!Array.isArray(fetchedNodes)) {\n throw new Error(\"paginateMongoQuery expects query.exec() to return an array\")\n }\n\n return materializeMongoPagination(compiled, fetchedNodes, {\n cursor: options.cursor,\n includeCursors: options.includeCursors,\n })\n}\n","import mongoose from \"mongoose\"\nimport type { PaginationResponse, PaginationSpec } from \"@rpcbase/api\"\n\nimport type { PaginationCursorCodecOptions } from \"./cursor\"\nimport { paginateMongoQuery } from \"./paginateMongoQuery\"\n\n\ndeclare const mongoPaginationPluginBrand: unique symbol\n\n\ntype QueryOptionsLike = Record<string, unknown>\n\nconst getQueryOptions = (query: unknown): QueryOptionsLike | undefined => {\n if (!query || typeof query !== \"object\") return undefined\n if (!(\"getOptions\" in query) || typeof (query as { getOptions?: unknown }).getOptions !== \"function\") return undefined\n return (query as { getOptions: () => QueryOptionsLike }).getOptions()\n}\n\nconst getPaginationFromOptions = (query: unknown): PaginationSpec | undefined => {\n const options = getQueryOptions(query)\n return options?.pagination as PaginationSpec | undefined\n}\n\nconst getCursorFromOptions = (query: unknown): PaginationCursorCodecOptions | undefined => {\n const options = getQueryOptions(query)\n return options?.paginationCursor as PaginationCursorCodecOptions | undefined\n}\n\nexport type MongoPaginationPluginOptions = {\n cursor: PaginationCursorCodecOptions;\n includeCursors?: boolean;\n}\n\ntype QueryResultNode<TResult> = TResult extends Array<infer TNode> ? TNode : unknown\n\ndeclare module \"mongoose\" {\n interface Query<\n ResultType,\n DocType,\n THelpers = {},\n RawDocType = unknown,\n QueryOp = \"find\",\n TDocOverrides = Record<string, never>,\n > {\n [mongoPaginationPluginBrand]?: [DocType, THelpers, RawDocType, QueryOp, TDocOverrides];\n paginate: (\n pagination?: PaginationSpec,\n options?: MongoPaginationPluginOptions,\n ) => Promise<PaginationResponse<QueryResultNode<ResultType>>>;\n }\n}\n\nexport const mongoPaginationPlugin = (schema: mongoose.Schema, pluginOptions?: MongoPaginationPluginOptions): void => {\n ;(schema.query as Record<string, unknown>).paginate = async function(\n this: mongoose.Query<unknown[], unknown>,\n pagination?: PaginationSpec,\n options?: MongoPaginationPluginOptions,\n ): Promise<PaginationResponse<unknown>> {\n const spec = pagination ?? getPaginationFromOptions(this)\n if (!spec) throw new Error(\"Missing pagination spec\")\n\n const cursor = options?.cursor ?? getCursorFromOptions(this) ?? pluginOptions?.cursor\n if (!cursor?.signingSecret) throw new Error(\"Missing pagination cursor signingSecret\")\n\n return await paginateMongoQuery(this, spec, {\n cursor,\n includeCursors: options?.includeCursors ?? pluginOptions?.includeCursors,\n })\n }\n}\n","type MongoDbLike = {\n databaseName?: string\n command: (command: Record<string, unknown>) => Promise<unknown>\n}\n\nexport type SearchTextStageOptions = {\n index: string\n query: string\n path: string | string[]\n highlightPath?: string | string[]\n}\n\nexport type SearchTextStage = {\n $search: {\n index: string\n text: {\n query: string\n path: string | string[]\n }\n highlight?: {\n path: string | string[]\n }\n }\n}\n\nexport const buildSearchTextStage = (options: SearchTextStageOptions): SearchTextStage => {\n const index = options.index.trim()\n if (!index) throw new Error(\"Missing search index name\")\n\n const query = options.query.trim()\n if (!query) throw new Error(\"Missing search query\")\n\n const stage: SearchTextStage = {\n $search: {\n index,\n text: {\n query,\n path: options.path,\n },\n },\n }\n\n if (options.highlightPath) {\n stage.$search.highlight = { path: options.highlightPath }\n }\n\n return stage\n}\n\nexport const searchMetaProjection = () => {\n return {\n score: { $meta: \"searchScore\" },\n highlights: { $meta: \"searchHighlights\" },\n } as const\n}\n\nexport type EnsureSearchIndexParams = {\n db: MongoDbLike\n collection: string\n name: string\n definition: Record<string, unknown>\n}\n\nconst listResultHasIndex = (listResult: unknown, name: string): boolean => {\n if (!listResult || typeof listResult !== \"object\") return false\n if (!(\"cursor\" in listResult)) return false\n const cursor = (listResult as { cursor?: unknown }).cursor\n if (!cursor || typeof cursor !== \"object\") return false\n const firstBatch = (cursor as { firstBatch?: unknown }).firstBatch\n if (!Array.isArray(firstBatch)) return false\n return firstBatch.some((idx) => idx && typeof idx === \"object\" && \"name\" in idx && (idx as { name?: unknown }).name === name)\n}\n\nconst isIndexAlreadyExistsError = (error: unknown): boolean => {\n if (!error || typeof error !== \"object\") return false\n const codeName = \"codeName\" in error ? (error as { codeName?: unknown }).codeName : undefined\n if (codeName === \"IndexAlreadyExists\") return true\n const message = \"message\" in error ? String((error as { message?: unknown }).message ?? \"\") : \"\"\n return /already exists/i.test(message)\n}\n\nexport const ensureSearchIndex = async (params: EnsureSearchIndexParams): Promise<{ created: boolean }> => {\n const collection = params.collection.trim()\n if (!collection) throw new Error(\"Missing collection name\")\n\n const name = params.name.trim()\n if (!name) throw new Error(\"Missing search index name\")\n\n let listResult: unknown\n try {\n listResult = await params.db.command({ listSearchIndexes: collection })\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n throw new Error(`listSearchIndexes failed for \"${collection}\": ${message}`)\n }\n\n if (listResultHasIndex(listResult, name)) {\n return { created: false }\n }\n\n try {\n await params.db.command({\n createSearchIndexes: collection,\n indexes: [{ name, definition: params.definition }],\n })\n } catch (error) {\n if (isIndexAlreadyExistsError(error)) {\n return { created: false }\n }\n const message = error instanceof Error ? error.message : String(error)\n throw new Error(`createSearchIndexes failed for \"${collection}\" (index \"${name}\"): ${message}`)\n }\n\n return { created: true }\n}\n","const getAppName = (env: NodeJS.ProcessEnv = process.env): string => {\n const appName = env.APP_NAME?.trim()\n if (!appName) {\n throw new Error(\"Missing APP_NAME\")\n }\n return appName\n}\n\nexport const GLOBAL_DB_SUFFIX = \"-global-db\"\n\nexport const getGlobalDbName = (env: NodeJS.ProcessEnv = process.env): string => {\n return `${getAppName(env)}${GLOBAL_DB_SUFFIX}`\n}\n\nexport const getTenantDbName = (tenantId: string, env: NodeJS.ProcessEnv = process.env): string => {\n return `${getAppName(env)}-${tenantId.trim()}-db`\n}\n","import mongoose from \"mongoose\"\n\nimport { getMongoDirectConnection, getMongoUrl } from \"./getMongoUrl\"\n\n\nconst connections = new Map<string, mongoose.Connection>()\nlet rootConnection: mongoose.Connection | null = null\nconst CONNECTION_MAX_LISTENERS = 50\n\nconst waitForOpen = async (connection: mongoose.Connection): Promise<void> => {\n if (connection.readyState === 1) return\n if (connection.getMaxListeners() < CONNECTION_MAX_LISTENERS) {\n connection.setMaxListeners(CONNECTION_MAX_LISTENERS)\n }\n\n await new Promise<void>((resolve, reject) => {\n connection.once(\"open\", resolve)\n connection.once(\"error\", reject)\n })\n}\n\nexport const ensureMongooseConnection = async (dbName: string): Promise<mongoose.Connection> => {\n const normalizedDbName = dbName.trim()\n if (!normalizedDbName) {\n throw new Error(\"Missing dbName\")\n }\n\n const existing = connections.get(normalizedDbName)\n if (existing) {\n await waitForOpen(existing)\n return existing\n }\n\n if (!rootConnection) {\n const mongoUrl = getMongoUrl()\n rootConnection = mongoose.createConnection(mongoUrl, {\n sanitizeFilter: true,\n dbName: normalizedDbName,\n directConnection: getMongoDirectConnection(),\n })\n }\n\n await waitForOpen(rootConnection)\n\n const connection = rootConnection.name === normalizedDbName\n ? rootConnection\n : rootConnection.useDb(normalizedDbName, { useCache: true })\n\n await waitForOpen(connection)\n\n connections.set(normalizedDbName, connection)\n return connection\n}\n","import type mongoose from \"mongoose\"\n\nimport { GLOBAL_DB_SUFFIX } from \"./dbNames\"\nimport { RBRtsChangeSchema, type IRBRtsChange } from \"./models/RBRtsChange\"\nimport { RBRtsCounterSchema, type IRBRtsCounter } from \"./models/RBRtsCounter\"\n\n\ntype RtsChangeOp = IRBRtsChange[\"op\"]\n\nconst RTS_COUNTER_ID = \"rts\"\nconst EXCLUDED_MODEL_NAMES = new Set([\"RBRtsChange\", \"RBRtsCounter\"])\n\nconst maxDeleteIdsRaw = process.env.RB_RTS_DELETE_LOG_MAX_IDS ?? \"\"\nconst maxDeleteIds = Number.isFinite(Number(maxDeleteIdsRaw)) ? Math.max(1, Math.floor(Number(maxDeleteIdsRaw))) : 5000\n\ntype DeleteMeta = {\n modelName: string\n ids: string[]\n reset: boolean\n session?: mongoose.ClientSession\n}\n\nconst deleteMetaByQuery = new WeakMap<object, DeleteMeta>()\n\nconst hasToString = (value: unknown): value is { toString: () => string } => {\n if (typeof value !== \"object\" || value === null) return false\n const maybe = value as { toString?: unknown }\n return typeof maybe.toString === \"function\"\n}\n\nconst normalizeId = (id: unknown): string | null => {\n if (!id) return null\n if (typeof id === \"string\") return id\n if (hasToString(id)) return id.toString()\n return null\n}\n\nconst getDbName = (db: unknown): string => {\n if (!db || typeof db !== \"object\") return \"\"\n const maybe = db as { name?: unknown; db?: { databaseName?: unknown } }\n const raw = maybe.name ?? maybe.db?.databaseName\n return typeof raw === \"string\" ? raw : \"\"\n}\n\nconst isGlobalDb = (db: unknown): boolean => getDbName(db).endsWith(GLOBAL_DB_SUFFIX)\n\ntype RtsCounterDoc = IRBRtsCounter\ntype RtsChangeDoc = IRBRtsChange\n\nconst getQuerySession = (query: MongooseQuery): mongoose.ClientSession | undefined => {\n const opts = typeof query.getOptions === \"function\" ? query.getOptions() : undefined\n if (!opts || typeof opts !== \"object\") return undefined\n const session = (opts as { session?: unknown }).session\n if (!session || typeof session !== \"object\") return undefined\n return session as mongoose.ClientSession\n}\n\nconst getRtsModels = (db: mongoose.Connection) => {\n const RtsCounter = (db.models.RBRtsCounter as mongoose.Model<RtsCounterDoc>)\n ?? db.model<RtsCounterDoc>(\"RBRtsCounter\", RBRtsCounterSchema)\n const RtsChange = (db.models.RBRtsChange as mongoose.Model<RtsChangeDoc>)\n ?? db.model<RtsChangeDoc>(\"RBRtsChange\", RBRtsChangeSchema)\n return { RtsCounter, RtsChange }\n}\n\nconst allocateSeqRange = async (\n db: mongoose.Connection,\n count: number,\n session?: mongoose.ClientSession,\n): Promise<{ start: number; end: number }> => {\n const { RtsCounter } = getRtsModels(db)\n const updated = await RtsCounter.findOneAndUpdate(\n { _id: RTS_COUNTER_ID },\n { $inc: { seq: count } },\n { upsert: true, returnDocument: \"after\", setDefaultsOnInsert: true, projection: { seq: 1 }, session },\n ).lean()\n\n const end = Number(updated?.seq ?? 0)\n const start = end - count + 1\n return { start, end }\n}\n\nconst insertChanges = async (\n db: mongoose.Connection,\n changes: Array<{ seq: number; modelName: string; op: RtsChangeOp; docId?: string | null }>,\n session?: mongoose.ClientSession,\n): Promise<void> => {\n if (!changes.length) return\n const { RtsChange } = getRtsModels(db)\n const ts = new Date()\n const docs = changes.map((c) => ({\n seq: c.seq,\n modelName: c.modelName,\n op: c.op,\n docId: c.docId ?? undefined,\n ts,\n }))\n\n if (session) {\n await RtsChange.insertMany(docs, { session })\n return\n }\n\n await RtsChange.insertMany(docs)\n}\n\nconst recordDeleteChanges = async (\n db: mongoose.Connection,\n modelName: string,\n ids: string[],\n session?: mongoose.ClientSession,\n): Promise<void> => {\n const uniqueIds = Array.from(new Set(ids)).filter(Boolean)\n if (!uniqueIds.length) return\n const { start } = await allocateSeqRange(db, uniqueIds.length, session)\n await insertChanges(db, uniqueIds.map((docId, idx) => ({\n seq: start + idx,\n modelName,\n op: \"delete\",\n docId,\n })), session)\n}\n\nconst recordResetModel = async (db: mongoose.Connection, modelName: string, session?: mongoose.ClientSession): Promise<void> => {\n const { start } = await allocateSeqRange(db, 1, session)\n await insertChanges(db, [{ seq: start, modelName, op: \"reset_model\" }], session)\n}\n\ntype MongooseQuery = mongoose.Query<unknown, unknown> & {\n model?: {\n modelName?: string\n db?: unknown\n find: (filter: unknown, projection: unknown) => unknown\n }\n getFilter?: () => unknown\n getQuery?: () => unknown\n getOptions?: () => unknown\n}\n\nconst captureDeleteMeta = async (query: MongooseQuery, mode: \"one\" | \"many\") => {\n const modelName = String(query?.model?.modelName ?? \"\")\n if (!modelName || modelName.startsWith(\"RB\") || EXCLUDED_MODEL_NAMES.has(modelName)) return\n if (isGlobalDb(query?.model?.db)) return\n\n const filter = typeof query.getFilter === \"function\" ? query.getFilter() : query.getQuery?.() ?? {}\n const session = getQuerySession(query)\n const findQuery = query.model.find(filter, { _id: 1 }) as unknown as {\n session?: (s: mongoose.ClientSession) => unknown\n limit: (n: number) => unknown\n lean: () => unknown\n }\n if (session && typeof findQuery.session === \"function\") {\n findQuery.session(session)\n }\n\n findQuery.lean()\n\n if (mode === \"one\") {\n findQuery.limit(1)\n } else {\n findQuery.limit(maxDeleteIds + 1)\n }\n\n const docs = await findQuery\n const ids = Array.isArray(docs)\n ? docs\n .map((d) => normalizeId((d as { _id?: unknown })?._id))\n .filter((id): id is string => Boolean(id))\n : []\n const reset = mode === \"many\" && ids.length > maxDeleteIds\n const trimmedIds = reset ? [] : ids\n\n const meta: DeleteMeta = {\n modelName,\n ids: trimmedIds,\n reset,\n session,\n }\n\n deleteMetaByQuery.set(query, meta)\n}\n\nconst flushDeleteMeta = async (query: MongooseQuery) => {\n const meta = deleteMetaByQuery.get(query)\n deleteMetaByQuery.delete(query)\n if (!meta) return\n\n const db = query?.model?.db as mongoose.Connection | undefined\n if (!db) return\n\n try {\n if (meta.reset) {\n await recordResetModel(db, meta.modelName, meta.session)\n } else {\n await recordDeleteChanges(db, meta.modelName, meta.ids, meta.session)\n }\n } catch {\n return\n }\n}\n\nexport const rtsChangeLogPlugin = (schema: mongoose.Schema): void => {\n schema.pre(\"deleteOne\", { query: true, document: false }, async function(this: MongooseQuery) {\n await captureDeleteMeta(this, \"one\")\n })\n\n schema.pre(\"deleteMany\", { query: true, document: false }, async function(this: MongooseQuery) {\n await captureDeleteMeta(this, \"many\")\n })\n\n schema.post(\"deleteOne\", { query: true, document: false }, async function(this: MongooseQuery) {\n await flushDeleteMeta(this)\n })\n\n schema.post(\"deleteMany\", { query: true, document: false }, async function(this: MongooseQuery) {\n await flushDeleteMeta(this)\n })\n\n schema.post(\"findOneAndDelete\", { query: true, document: false }, async function(this: MongooseQuery, doc: unknown) {\n const modelName = String(this?.model?.modelName ?? \"\")\n if (!modelName || modelName.startsWith(\"RB\") || EXCLUDED_MODEL_NAMES.has(modelName)) return\n\n const db = this?.model?.db as mongoose.Connection | undefined\n if (!db) return\n if (isGlobalDb(db)) return\n\n const docId = normalizeId((doc as { _id?: unknown } | null | undefined)?._id)\n if (!docId) return\n\n try {\n const session = getQuerySession(this)\n await recordDeleteChanges(db, modelName, [docId], session)\n } catch {\n return\n }\n })\n}\n","import mongoose from \"mongoose\"\nimport { accessibleBy } from \"@casl/mongoose\"\n\nimport type { AclAction, AclSubjectType, AppAbility } from \"./types\"\n\n\ntype StoredAcl = {\n ability: AppAbility\n action?: AclAction\n}\n\ntype QueryOptionsLike = Record<string, unknown>\n\ntype PipelineStageLike = Record<string, unknown>\n\nconst isRecord = (value: unknown): value is Record<string, unknown> => Boolean(value) && typeof value === \"object\" && !Array.isArray(value)\n\nconst mergeMongoQuery = (left: unknown, right: Record<string, unknown>): Record<string, unknown> => {\n const leftQuery = isRecord(left) ? left : {}\n if (Object.keys(leftQuery).length === 0) return right\n if (Object.keys(right).length === 0) return leftQuery\n return { $and: [leftQuery, right] }\n}\n\nconst getQueryOptions = (query: unknown): QueryOptionsLike | undefined => {\n if (!query || typeof query !== \"object\") return undefined\n if (!(\"getOptions\" in query) || typeof (query as { getOptions?: unknown }).getOptions !== \"function\") return undefined\n return (query as { getOptions: () => QueryOptionsLike }).getOptions()\n}\n\nconst getStoredAclFromQuery = (query: unknown): StoredAcl | null => {\n const options = getQueryOptions(query)\n const raw = options?.rbAcl\n if (!isRecord(raw)) return null\n if (!(\"ability\" in raw)) return null\n return raw as unknown as StoredAcl\n}\n\nconst getStoredAclFromAggregate = (aggregate: unknown): StoredAcl | null => {\n if (!aggregate || typeof aggregate !== \"object\") return null\n const raw = (aggregate as { options?: unknown }).options\n if (!isRecord(raw)) return null\n const acl = raw.rbAcl\n if (!isRecord(acl)) return null\n if (!(\"ability\" in acl)) return null\n return acl as unknown as StoredAcl\n}\n\nconst addQueryAclFilter = (query: mongoose.Query<unknown, unknown>, action: AclAction): void => {\n const storedAcl = getStoredAclFromQuery(query)\n if (!storedAcl) return\n\n const ability = storedAcl.ability\n const resolvedAction = storedAcl.action ?? action\n const modelName = query.model.modelName\n\n const accessQuery = accessibleBy(ability, resolvedAction).ofType(modelName as AclSubjectType)\n query.and([accessQuery])\n}\n\nconst injectAggregateMatch = (pipeline: PipelineStageLike[], match: Record<string, unknown>): void => {\n if (pipeline.length === 0) {\n pipeline.unshift({ $match: match })\n return\n }\n\n const first = pipeline[0]\n if (!isRecord(first)) {\n pipeline.unshift({ $match: match })\n return\n }\n\n if (\"$geoNear\" in first) {\n const geoNear = first.$geoNear\n if (isRecord(geoNear)) {\n geoNear.query = mergeMongoQuery(geoNear.query, match)\n return\n }\n }\n\n if (\"$search\" in first || \"$vectorSearch\" in first || \"$searchMeta\" in first) {\n pipeline.splice(1, 0, { $match: match })\n return\n }\n\n pipeline.unshift({ $match: match })\n}\n\nconst addAggregateAclFilter = (aggregate: mongoose.Aggregate<unknown>, action: AclAction): void => {\n const storedAcl = getStoredAclFromAggregate(aggregate)\n if (!storedAcl) return\n\n const ability = storedAcl.ability\n const resolvedAction = storedAcl.action ?? action\n const modelName = aggregate.model().modelName\n\n const accessQuery = accessibleBy(ability, resolvedAction).ofType(modelName as AclSubjectType)\n injectAggregateMatch(aggregate.pipeline() as unknown as PipelineStageLike[], accessQuery)\n}\n\nconst patchAggregateAcl = (): void => {\n const globalKey = Symbol.for(\"@rpcbase/db/acl/mongooseAggregateAclPatched\")\n const globalState = globalThis as unknown as Record<string | symbol, unknown>\n if (globalState[globalKey]) return\n globalState[globalKey] = true\n\n const AggregatePrototype = (mongoose.Aggregate as unknown as { prototype: Record<string, unknown> }).prototype\n if (typeof AggregatePrototype.acl === \"function\") return\n\n AggregatePrototype.acl = function(\n this: mongoose.Aggregate<unknown>,\n ability: AppAbility,\n action: AclAction = \"read\",\n ) {\n this.option({ rbAcl: { ability, action } })\n return this\n }\n}\n\nconst createModelAclProxy = <TModel extends mongoose.Model<unknown>>(\n model: TModel,\n ability: AppAbility,\n): TModel => {\n return new Proxy(model, {\n get(target, prop, receiver) {\n if (prop === \"acl\") {\n return () => {\n throw new Error(\n `Model \"${target.modelName}\" is already ACL-scoped. Do not call .acl(...) again.`,\n )\n }\n }\n\n const value = Reflect.get(target, prop, receiver) as unknown\n if (typeof value !== \"function\") return value\n return (...args: unknown[]) => {\n const result = Reflect.apply(value, target, args) as unknown\n if (result && typeof result === \"object\" && \"acl\" in result && typeof (result as { acl?: unknown }).acl === \"function\") {\n return (result as { acl: (ability: AppAbility) => unknown }).acl(ability)\n }\n return result\n }\n },\n }) as unknown as TModel\n}\n\ndeclare const mongooseAclPluginBrand: unique symbol\n\ndeclare module \"mongoose\" {\n interface QueryOptions<DocType = unknown> {\n rbAcl?: StoredAcl;\n [mongooseAclPluginBrand]?: DocType;\n }\n\n interface AggregateOptions {\n rbAcl?: StoredAcl;\n }\n\n interface Query<\n ResultType,\n DocType,\n THelpers = {},\n RawDocType = unknown,\n QueryOp = \"find\",\n TDocOverrides = Record<string, never>,\n > {\n [mongooseAclPluginBrand]?: [ResultType, DocType, THelpers, RawDocType, QueryOp, TDocOverrides];\n acl: (ability: AppAbility, action?: AclAction) => this;\n }\n\n interface Aggregate<ResultType> {\n [mongooseAclPluginBrand]?: ResultType;\n acl: (ability: AppAbility, action?: AclAction) => this;\n }\n\n interface Model<\n TRawDocType,\n TQueryHelpers,\n TInstanceMethods,\n TVirtuals,\n THydratedDocumentType,\n TSchema,\n TLeanResultType,\n > {\n [mongooseAclPluginBrand]?: [TRawDocType, TQueryHelpers, TInstanceMethods, TVirtuals, THydratedDocumentType, TSchema, TLeanResultType];\n acl: (ability: AppAbility) => this;\n }\n}\n\nexport const mongooseAclPlugin = (schema: mongoose.Schema): void => {\n patchAggregateAcl()\n\n ;(schema.query as Record<string, unknown>).acl = function(\n this: mongoose.Query<unknown, unknown>,\n ability: AppAbility,\n action?: AclAction,\n ) {\n this.setOptions({ rbAcl: { ability, action } })\n return this\n }\n\n ;(schema.statics as Record<string, unknown>).acl = function(\n this: mongoose.Model<unknown>,\n ability: AppAbility,\n ) {\n return createModelAclProxy(this, ability)\n }\n\n schema.pre(\"aggregate\", function() {\n addAggregateAclFilter(this, \"read\")\n })\n\n schema.pre(\"countDocuments\", function() {\n addQueryAclFilter(this, \"read\")\n })\n\n schema.pre(\"deleteMany\", function() {\n addQueryAclFilter(this, \"delete\")\n })\n\n schema.pre(\"deleteOne\", function() {\n addQueryAclFilter(this, \"delete\")\n })\n\n schema.pre(\"distinct\", function() {\n addQueryAclFilter(this, \"read\")\n })\n\n schema.pre(\"find\", function() {\n addQueryAclFilter(this, \"read\")\n })\n\n schema.pre(\"findOne\", function() {\n addQueryAclFilter(this, \"read\")\n })\n\n schema.pre(\"findOneAndDelete\", function() {\n addQueryAclFilter(this, \"delete\")\n })\n\n schema.pre(\"findOneAndReplace\", function() {\n addQueryAclFilter(this, \"update\")\n })\n\n schema.pre(\"findOneAndUpdate\", function() {\n addQueryAclFilter(this, \"update\")\n })\n\n schema.pre(\"replaceOne\", function() {\n addQueryAclFilter(this, \"update\")\n })\n\n schema.pre(\"updateMany\", function() {\n addQueryAclFilter(this, \"update\")\n })\n\n schema.pre(\"updateOne\", function() {\n addQueryAclFilter(this, \"update\")\n })\n}\n\nexport const _private = {\n createModelAclProxy,\n injectAggregateMatch,\n mergeMongoQuery,\n}\n","import mongoose from \"mongoose\"\nimport { accessibleRecordsPlugin } from \"@casl/mongoose\"\n\nimport * as frameworkSchemas from \"./models\"\nimport { rtsChangeLogPlugin } from \"./rtsChangeLogPlugin\"\nimport { registerPoliciesFromModules } from \"./acl\"\nimport { mongooseAclPlugin } from \"./acl/mongooseAclPlugin\"\nimport { mongoPaginationPlugin } from \"./pagination/mongoPaginationPlugin\"\n\n\ntype ModelModules = Record<string, unknown>\ntype ModelsScope = \"tenant\" | \"global\"\ntype RegisterModelsOptions = {\n allowReservedRbModelNames?: boolean;\n}\n\ntype RegisteredSchemas = Record<string, mongoose.Schema>\n\ntype RegisteredModels = {\n tenant: RegisteredSchemas\n global: RegisteredSchemas\n}\n\nlet cachedModels: RegisteredModels | null = null\n\nconst DEFAULT_GLOBAL_RB_MODEL_NAMES_SET = new Set<string>([\n \"RBUser\",\n \"RBTenant\",\n \"RBOAuthRequest\",\n])\n\nconst assertSchema = (exportName: string, value: unknown): mongoose.Schema => {\n if (value instanceof mongoose.Schema) return value\n\n throw new Error(\n [\n `Expected ${exportName} to be an instance of mongoose.Schema, but it was not.`,\n \"rpcbase supports mongoose 9+ only.\",\n \"Fix: ensure the project is using mongoose 9.x and that all packages resolve the same mongoose instance (try `npm ls mongoose`).\",\n ].join(\" \"),\n )\n}\n\nconst getFrameworkSchemaForModelName = (modelName: string): mongoose.Schema | null => {\n const exportName = `${modelName}Schema`\n const value = (frameworkSchemas as unknown as Record<string, unknown>)[exportName]\n if (!(value instanceof mongoose.Schema)) return null\n return value\n}\n\nconst applyTenantPlugins = (schema: mongoose.Schema): void => {\n schema.plugin(accessibleRecordsPlugin)\n schema.plugin(mongooseAclPlugin)\n schema.plugin(mongoPaginationPlugin)\n schema.plugin(rtsChangeLogPlugin)\n}\n\nconst registerSchema = (\n target: RegisteredSchemas,\n other: RegisteredSchemas,\n modelName: string,\n schema: mongoose.Schema,\n scope: ModelsScope,\n): void => {\n if (target[modelName] || other[modelName]) {\n throw new Error(`Duplicate model name \"${modelName}\" across tenant/global scopes`)\n }\n target[modelName] = schema\n}\n\nconst buildSchemasFromModules = (modules: ModelModules): Array<{ modelName: string; schema: mongoose.Schema }> =>\n Object.entries(modules)\n .filter(([key]) => key.endsWith(\"Schema\"))\n .map(([key, schemaValue]) => {\n const schema = assertSchema(key, schemaValue)\n const modelName = key.replace(/Schema$/, \"\")\n return { modelName, schema }\n })\n\nexport const registerModels = (\n { tenant, global }: { tenant: ModelModules; global?: ModelModules },\n options: RegisterModelsOptions = {},\n) => {\n registerPoliciesFromModules(frameworkSchemas as unknown as Record<string, unknown>)\n registerPoliciesFromModules(tenant)\n\n const tenantSchemas: RegisteredSchemas = {}\n const globalSchemas: RegisteredSchemas = {}\n const allowReservedRbModelNames = options.allowReservedRbModelNames === true\n\n for (const { modelName, schema } of buildSchemasFromModules(frameworkSchemas as unknown as ModelModules)) {\n if (DEFAULT_GLOBAL_RB_MODEL_NAMES_SET.has(modelName)) {\n const cloned = schema.clone()\n registerSchema(globalSchemas, tenantSchemas, modelName, cloned, \"global\")\n } else {\n const cloned = schema.clone()\n applyTenantPlugins(cloned)\n registerSchema(tenantSchemas, globalSchemas, modelName, cloned, \"tenant\")\n }\n }\n\n for (const { modelName, schema } of buildSchemasFromModules(tenant)) {\n if (modelName === \"RBUser\" || modelName === \"RBTenant\") {\n throw new Error(`Invalid tenant model name \"${modelName}\". RBUser/RBTenant are global models.`)\n }\n if (modelName.startsWith(\"RB\")) {\n const frameworkSchema = getFrameworkSchemaForModelName(modelName)\n if (frameworkSchema && schema === frameworkSchema) continue\n if (!allowReservedRbModelNames) {\n throw new Error(`Invalid tenant model name \"${modelName}\". RB* models are reserved for rpcbase.`)\n }\n }\n const cloned = schema.clone()\n applyTenantPlugins(cloned)\n registerSchema(tenantSchemas, globalSchemas, modelName, cloned, \"tenant\")\n }\n\n for (const { modelName, schema } of buildSchemasFromModules(global ?? {})) {\n if (modelName.startsWith(\"RB\")) {\n const frameworkSchema = getFrameworkSchemaForModelName(modelName)\n if (frameworkSchema && schema === frameworkSchema) continue\n if (!allowReservedRbModelNames) {\n throw new Error(`Invalid global model name \"${modelName}\". RB* models are reserved for rpcbase.`)\n }\n }\n const cloned = schema.clone()\n registerSchema(globalSchemas, tenantSchemas, modelName, cloned, \"global\")\n }\n\n const allSchemas = { ...globalSchemas, ...tenantSchemas }\n\n for (const [modelName, schema] of Object.entries(allSchemas)) {\n if (!mongoose.models[modelName]) {\n mongoose.model(modelName, schema)\n }\n }\n\n cachedModels = {\n tenant: { ...(cachedModels?.tenant ?? {}), ...tenantSchemas },\n global: { ...(cachedModels?.global ?? {}), ...globalSchemas },\n }\n}\n\nexport const getRegisteredModels = (scope: ModelsScope) => {\n if (!cachedModels) {\n throw new Error(\"Models not registered. Call createModels(...) once at startup (or import your models module) before using models.get.\")\n }\n return cachedModels[scope]\n}\n\nexport type { ModelModules, ModelsScope, RegisterModelsOptions }\n","import assert from \"assert\"\n\nimport { getGlobalDbName, getTenantDbName } from \"./dbNames\"\nimport { ensureMongooseConnection } from \"./ensureMongooseConnection\"\nimport { getRegisteredModels, registerModels, type ModelsScope } from \"./registerModels\"\nimport { hasRegisteredPolicy, type AppAbility } from \"./acl\"\n\n\nexport type LoadModelCtx = {\n tenantId?: string;\n req?: {\n session?: {\n user?: {\n currentTenantId?: string;\n }\n } | null;\n };\n ability?: AppAbility;\n};\n\nconst loadModelFromDb = async (\n modelName: string,\n dbName: string,\n scope: ModelsScope,\n) => {\n const schemas = getRegisteredModels(scope)\n const schema = schemas[modelName]\n assert(schema, `Model ${modelName} not registered. Available models: ${Object.keys(schemas).join(\", \")}`)\n\n const modelConnection = await ensureMongooseConnection(dbName)\n\n if (!modelConnection.models[modelName]) {\n modelConnection.model(modelName, schema)\n }\n\n return modelConnection.models[modelName]\n}\n\nconst normalizeTenantId = (value: unknown): string | null => {\n if (typeof value !== \"string\") return null\n const tenantId = value.trim()\n return tenantId || null\n}\n\nexport const getTenantIdFromLoadModelCtx = (ctx: LoadModelCtx): string => {\n const tenantId =\n normalizeTenantId(ctx.tenantId)\n ?? normalizeTenantId(ctx.req?.session?.user?.currentTenantId)\n assert(tenantId, \"Tenant ID is missing from ctx (expected ctx.tenantId or ctx.req.session.user.currentTenantId)\")\n return tenantId\n}\n\nexport const models = {\n register: registerModels,\n\n getUnsafe: async (modelName: string, ctx: LoadModelCtx) => {\n const tenantId = getTenantIdFromLoadModelCtx(ctx)\n const dbName = getTenantDbName(tenantId)\n return loadModelFromDb(modelName, dbName, \"tenant\")\n },\n\n get: async (modelName: string, ctx: LoadModelCtx) => {\n const model = await models.getUnsafe(modelName, ctx)\n const resolvedAbility = ctx.ability\n\n const isProtected = hasRegisteredPolicy(modelName)\n if (!isProtected) {\n return model\n }\n\n if (!resolvedAbility) {\n throw new Error(\n `Model \"${modelName}\" is ACL-protected. Set ctx.ability or use models.getUnsafe(...) explicitly.`,\n )\n }\n\n if (typeof (model as { acl?: unknown }).acl !== \"function\") return model\n return (model as { acl: (appAbility: AppAbility) => typeof model }).acl(resolvedAbility)\n },\n\n getGlobal: async (modelName: string, ctx: LoadModelCtx) => {\n const dbName = getGlobalDbName()\n return loadModelFromDb(modelName, dbName, \"global\")\n },\n} as const\n","import type { LoadModelCtx } from \"./modelsApi\"\nimport type { ModelModules, RegisterModelsOptions } from \"./registerModels\"\nimport type * as frameworkSchemas from \"./models\"\nimport { models } from \"./modelsApi\"\nimport { registerModels } from \"./registerModels\"\n\n\ntype ExtractModelNamesFromSchemas<TModules> = {\n [K in keyof TModules]-?: K extends `${infer Name}Schema` ? Name : never\n}[keyof TModules] & string\n\ntype FrameworkModelName = ExtractModelNamesFromSchemas<typeof frameworkSchemas>\n\ntype RpcbaseGlobalModelName = Extract<FrameworkModelName, \"RBUser\" | \"RBTenant\" | \"RBOAuthRequest\">\n\nexport type TenantModelName<TTenantModules extends ModelModules> =\n ExtractModelNamesFromSchemas<TTenantModules>\n\nexport type GlobalModelName<TGlobalModules extends ModelModules> =\n | RpcbaseGlobalModelName\n | ExtractModelNamesFromSchemas<TGlobalModules>\n\ntype LoadedTenantModel = Awaited<ReturnType<(typeof models)[\"get\"]>>\ntype LoadedGlobalModel = Awaited<ReturnType<(typeof models)[\"getGlobal\"]>>\n\ntype ModelsGetFn<TTenantModules extends ModelModules> = {\n (\n modelName: TenantModelName<TTenantModules>,\n ctx: LoadModelCtx,\n ): ReturnType<(typeof models)[\"get\"]>\n <const TNames extends readonly TenantModelName<TTenantModules>[]>(\n modelNames: TNames,\n ctx: LoadModelCtx,\n ): Promise<{ [K in keyof TNames]: LoadedTenantModel }>\n}\n\ntype ModelsGetUnsafeFn<TTenantModules extends ModelModules> = {\n (modelName: TenantModelName<TTenantModules>, ctx: LoadModelCtx): ReturnType<(typeof models)[\"getUnsafe\"]>\n <const TNames extends readonly TenantModelName<TTenantModules>[]>(\n modelNames: TNames,\n ctx: LoadModelCtx,\n ): Promise<{ [K in keyof TNames]: LoadedTenantModel }>\n}\n\ntype ModelsGetGlobalFn<TGlobalModules extends ModelModules> = {\n (modelName: GlobalModelName<TGlobalModules>, ctx: LoadModelCtx): ReturnType<(typeof models)[\"getGlobal\"]>\n <const TNames extends readonly GlobalModelName<TGlobalModules>[]>(\n modelNames: TNames,\n ctx: LoadModelCtx,\n ): Promise<{ [K in keyof TNames]: LoadedGlobalModel }>\n}\n\nexport type ModelsConfig<TTenantModules extends ModelModules, TGlobalModules extends ModelModules> = {\n tenant: TTenantModules\n global?: TGlobalModules\n}\n\nexport type ModelsClient<TTenantModules extends ModelModules, TGlobalModules extends ModelModules> = {\n register: (modules: ModelsConfig<TTenantModules, TGlobalModules>, options?: RegisterModelsOptions) => void\n get: ModelsGetFn<TTenantModules>\n getUnsafe: ModelsGetUnsafeFn<TTenantModules>\n getGlobal: ModelsGetGlobalFn<TGlobalModules>\n}\n\nexport const createModels = <\n TTenantModules extends ModelModules,\n TGlobalModules extends ModelModules = Record<string, never>,\n>(\n modules: ModelsConfig<TTenantModules, TGlobalModules>,\n options?: RegisterModelsOptions,\n ): ModelsClient<TTenantModules, TGlobalModules> => {\n registerModels(modules, options)\n\n const get = (async (\n modelNameOrNames: TenantModelName<TTenantModules> | readonly TenantModelName<TTenantModules>[],\n ctx: LoadModelCtx,\n ) => {\n if (Array.isArray(modelNameOrNames)) {\n return Promise.all(modelNameOrNames.map((modelName) => models.get(modelName as string, ctx)))\n }\n return models.get(modelNameOrNames as string, ctx)\n }) as ModelsClient<TTenantModules, TGlobalModules>[\"get\"]\n\n const getUnsafe = (async (\n modelNameOrNames: TenantModelName<TTenantModules> | readonly TenantModelName<TTenantModules>[],\n ctx: LoadModelCtx,\n ) => {\n if (Array.isArray(modelNameOrNames)) {\n return Promise.all(modelNameOrNames.map((modelName) => models.getUnsafe(modelName as string, ctx)))\n }\n return models.getUnsafe(modelNameOrNames as string, ctx)\n }) as ModelsClient<TTenantModules, TGlobalModules>[\"getUnsafe\"]\n\n const getGlobal = (async (\n modelNameOrNames: GlobalModelName<TGlobalModules> | readonly GlobalModelName<TGlobalModules>[],\n ctx: LoadModelCtx,\n ) => {\n if (Array.isArray(modelNameOrNames)) {\n return Promise.all(modelNameOrNames.map((modelName) => models.getGlobal(modelName as string, ctx)))\n }\n return models.getGlobal(modelNameOrNames as string, ctx)\n }) as ModelsClient<TTenantModules, TGlobalModules>[\"getGlobal\"]\n\n return {\n register: (nextModules, nextOptions) => registerModels(nextModules, nextOptions),\n get,\n getUnsafe,\n getGlobal,\n }\n}\n","import assert from \"assert\"\n\nimport type mongoose from \"mongoose\"\n\nimport { ensureMongooseConnection } from \"./ensureMongooseConnection\"\nimport { getTenantIdFromLoadModelCtx, type LoadModelCtx } from \"./modelsApi\"\n\n\nconst getAppName = (): string => {\n const appName = process.env.APP_NAME?.trim()\n assert(appName, \"Missing APP_NAME\")\n return appName\n}\n\nconst normalizeTenantId = (tenantId: string): string => {\n const normalized = tenantId.trim()\n assert(normalized, \"Tenant ID is missing\")\n return normalized\n}\n\nexport const getTenantFilesystemDbName = (tenantId: string): string =>\n `${getAppName()}-${normalizeTenantId(tenantId)}-filesystem-db`\n\nexport const getTenantFilesystemDb = async (tenantId: string): Promise<mongoose.Connection> =>\n ensureMongooseConnection(getTenantFilesystemDbName(tenantId))\n\nexport const getTenantFilesystemDbFromCtx = async (ctx: LoadModelCtx): Promise<mongoose.Connection> => {\n const tenantId = getTenantIdFromLoadModelCtx(ctx)\n return getTenantFilesystemDb(tenantId)\n}\n","import type mongoose from \"mongoose\"\nimport type { ClientSession } from \"mongoose\"\n\nimport { getGlobalDbName, getTenantDbName } from \"./dbNames\"\nimport { ensureMongooseConnection } from \"./ensureMongooseConnection\"\nimport { getTenantIdFromLoadModelCtx, type LoadModelCtx } from \"./modelsApi\"\nimport { getTenantFilesystemDbName } from \"./tenantFilesystemDb\"\n\n\ntype MongooseTransactionOptions = Parameters<ClientSession[\"withTransaction\"]>[1]\n\nexport type TenantGlobalFilesystemTransactionCtx = {\n tenantId: string\n session: ClientSession\n ctx: {\n tenant: LoadModelCtx\n global: LoadModelCtx\n }\n db: {\n tenant: mongoose.Connection\n global: mongoose.Connection\n filesystem: mongoose.Connection\n }\n}\n\ntype WithTransactionScope =\n | string\n | { tenantId: string }\n | { ctx: LoadModelCtx }\n\nconst buildTenantLoadModelCtx = (tenantId: string): LoadModelCtx => ({\n req: {\n session: {\n user: {\n currentTenantId: tenantId,\n },\n },\n },\n})\n\nexport function withTransaction<T>(\n tenantId: string,\n fn: (ctx: TenantGlobalFilesystemTransactionCtx) => Promise<T>,\n options?: MongooseTransactionOptions,\n): Promise<T>\nexport function withTransaction<T>(\n scope: { tenantId: string } | { ctx: LoadModelCtx },\n fn: (ctx: TenantGlobalFilesystemTransactionCtx) => Promise<T>,\n options?: MongooseTransactionOptions,\n): Promise<T>\nexport async function withTransaction<T>(\n scope: WithTransactionScope,\n fn: (ctx: TenantGlobalFilesystemTransactionCtx) => Promise<T>,\n options?: MongooseTransactionOptions,\n): Promise<T> {\n const normalizedTenantId = (() => {\n if (typeof scope === \"string\") return scope.trim()\n if (\"tenantId\" in scope) return scope.tenantId.trim()\n return getTenantIdFromLoadModelCtx(scope.ctx)\n })()\n\n if (!normalizedTenantId) throw new Error(\"Tenant ID is missing\")\n\n const tenantDbName = getTenantDbName(normalizedTenantId)\n const globalDbName = getGlobalDbName()\n const filesystemDbName = getTenantFilesystemDbName(normalizedTenantId)\n\n const tenantDb = await ensureMongooseConnection(tenantDbName)\n const globalDb = await ensureMongooseConnection(globalDbName)\n const filesystemDb = await ensureMongooseConnection(filesystemDbName)\n\n const session = await tenantDb.startSession()\n\n const tenantCtx: LoadModelCtx = typeof scope === \"object\" && \"ctx\" in scope\n ? scope.ctx\n : buildTenantLoadModelCtx(normalizedTenantId)\n\n const globalCtx: LoadModelCtx = { req: { session: null } }\n\n try {\n return await session.withTransaction(async () => fn({\n tenantId: normalizedTenantId,\n session,\n ctx: {\n tenant: tenantCtx,\n global: globalCtx,\n },\n db: {\n tenant: tenantDb,\n global: globalDb,\n filesystem: filesystemDb,\n },\n }), options)\n } finally {\n await session.endSession()\n }\n}\n","import type { ClientSession } from \"mongoose\"\nimport type {\n BillingStorage,\n BillingStorageTransaction,\n PersistedSubscriptionEvent,\n StoredSubscriptionProjection,\n SubscriptionEvent,\n} from \"@rpcbase/billing\"\n\nimport { ZRBTenantSubscriptionEvent } from \"./models/RBTenantSubscriptionEvent\"\nimport type { LoadModelCtx } from \"./modelsApi\"\nimport { models } from \"./modelsApi\"\nimport { withTransaction } from \"./transactions\"\n\n\ntype MongoBillingTransaction = {\n session: ClientSession\n}\n\ntype SubscriptionEventDocument = Record<string, unknown> & {\n _id?: unknown\n}\n\nconst getTransactionSession = (transaction?: BillingStorageTransaction): ClientSession | undefined => {\n if (!transaction || typeof transaction !== \"object\" || !(\"session\" in transaction)) return undefined\n return (transaction as MongoBillingTransaction).session\n}\n\nconst toSubscriptionEvent = (document: SubscriptionEventDocument): PersistedSubscriptionEvent => {\n const parsed = ZRBTenantSubscriptionEvent.parse(document)\n if (!document._id) throw new Error(\"Persisted subscription event is missing its id\")\n return {\n ...parsed,\n id: String(document._id),\n }\n}\n\nconst getExistingEventQuery = (event: SubscriptionEvent, tenantId: string): Record<string, unknown> => ({\n tenantId,\n idempotencyKey: event.idempotencyKey,\n})\n\nconst isDuplicateKeyError = (error: unknown): boolean =>\n Boolean(error && typeof error === \"object\" && \"code\" in error && error.code === 11000)\n\nconst toProjectionDocument = (projection: StoredSubscriptionProjection): Record<string, unknown> => ({\n tenantId: projection.tenantId,\n subscriptionId: projection.subscriptionId,\n type: projection.type,\n parentSubscriptionId: projection.parentSubscriptionId ?? undefined,\n scope: projection.scope,\n scopeId: projection.scopeId ?? undefined,\n planKey: projection.planKey,\n priceId: projection.priceId ?? undefined,\n status: projection.status,\n intervalUnit: projection.intervalUnit,\n intervalCount: projection.intervalCount,\n modules: projection.modules,\n billingAnchor: projection.billingAnchor,\n currentPeriodStart: projection.currentPeriodStart,\n currentPeriodEnd: projection.currentPeriodEnd,\n cancelAtPeriodEnd: projection.cancelAtPeriodEnd,\n cancelAt: projection.cancelAt ?? undefined,\n canceledAt: projection.canceledAt ?? undefined,\n scheduledPlanKey: projection.scheduledPlan?.planKey,\n scheduledPlanEffectiveAt: projection.scheduledPlan?.effectiveAt,\n provider: projection.provider ?? undefined,\n latestEventId: projection.latestEventId,\n latestEventAt: projection.latestEventAt,\n projectedAt: projection.projectedAt,\n})\n\nexport const createTenantBillingStorage = (params: {\n ctx: LoadModelCtx\n tenantId: string\n}): BillingStorage => {\n const findExistingEvent = async (\n query: Record<string, unknown>,\n transaction?: BillingStorageTransaction,\n ): Promise<PersistedSubscriptionEvent | null> => {\n const EventModel = await models.get(\"RBTenantSubscriptionEvent\", params.ctx)\n const request = EventModel.findOne(query)\n const session = getTransactionSession(transaction)\n if (session) request.session(session)\n const document = await request.lean() as SubscriptionEventDocument | null\n return document ? toSubscriptionEvent(document) : null\n }\n\n return {\n runInTransaction: (operation) => withTransaction(\n { ctx: params.ctx },\n ({ session }) => operation({ session } satisfies MongoBillingTransaction),\n ),\n createEvent: async (event, transaction) => {\n if (event.tenantId !== params.tenantId) {\n throw new Error(\"Billing event tenantId does not match the storage tenant\")\n }\n const existingQuery = getExistingEventQuery(event, params.tenantId)\n const existing = await findExistingEvent(existingQuery, transaction)\n if (existing) return existing\n\n const EventModel = await models.get(\"RBTenantSubscriptionEvent\", params.ctx)\n const eventDocument = ZRBTenantSubscriptionEvent.parse(event)\n const session = getTransactionSession(transaction)\n\n try {\n const documents = await EventModel.create([eventDocument], session ? { session } : undefined)\n const document = documents[0]?.toObject() as SubscriptionEventDocument | undefined\n if (!document) throw new Error(\"Subscription event was not persisted\")\n return toSubscriptionEvent(document)\n } catch (error) {\n if (!isDuplicateKeyError(error)) throw error\n const duplicate = await findExistingEvent(existingQuery, transaction)\n if (!duplicate) throw error\n return duplicate\n }\n },\n listEvents: async (tenantId, subscriptionId, transaction) => {\n if (tenantId !== params.tenantId) throw new Error(\"Billing storage tenant mismatch\")\n const EventModel = await models.get(\"RBTenantSubscriptionEvent\", params.ctx)\n const request = EventModel.find({ tenantId, subscriptionId })\n .sort({ effectiveAt: 1, occurredAt: 1, _id: 1 })\n const session = getTransactionSession(transaction)\n if (session) request.session(session)\n const documents = await request.lean() as SubscriptionEventDocument[]\n return documents.map(toSubscriptionEvent)\n },\n upsertProjection: async (projection, transaction) => {\n if (projection.tenantId !== params.tenantId) throw new Error(\"Billing projection tenant mismatch\")\n const ProjectionModel = await models.get(\"RBTenantSubscriptionProjection\", params.ctx)\n const session = getTransactionSession(transaction)\n await ProjectionModel.replaceOne(\n {\n tenantId: params.tenantId,\n subscriptionId: projection.subscriptionId,\n },\n toProjectionDocument(projection),\n {\n upsert: true,\n runValidators: true,\n ...(session ? { session } : {}),\n },\n )\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAIA,IAAaE,UAAUD,IAAEE,OAAO;CAC9BC,OAAOH,IAAEI,OAAO,CAAC,CAACD,MAAM,CAAC,CAACE,SAAS;CACnCC,UAAUN,IAAEI,OAAO;CACnBG,MAAMP,IAAEI,OAAO,CAAC,CAACC,SAAS;CAC1BG,OAAOR,IAAEI,OAAO,CAAC,CAACC,SAAS;CAC3BI,SAAST,IAAEU,MAAMV,IAAEI,OAAO,CAAC;CAC3BO,aAAaX,IAAEY,OAAOZ,IAAEI,OAAO,GAAGJ,IAAEU,MAAMV,IAAEI,OAAO,CAAC,CAAC,CAAC,CAACC,SAAS;CAChEQ,gBAAgBb,IAAEY,OAAOZ,IAAEI,OAAO,GAAGJ,IAAEE,OAAO;EAC5CY,SAASd,IAAEI,OAAO;EAClBD,OAAOH,IAAEI,OAAO,CAAC,CAACD,MAAM,CAAC,CAACE,SAAS;EACnCE,MAAMP,IAAEI,OAAO,CAAC,CAACC,SAAS;EAC1BU,aAAaf,IAAEI,OAAO,CAAC,CAACC,SAAS;EACjCW,cAAchB,IAAEI,OAAO,CAAC,CAACC,SAAS;EAClCY,SAASjB,IAAEI,OAAO,CAAC,CAACC,SAAS;EAC7Ba,OAAOlB,IAAEI,OAAO,CAAC,CAACC,SAAS;EAC3Bc,WAAWnB,IAAEI,OAAO,CAAC,CAACC,SAAS;EAC/Be,WAAWpB,IAAEqB,KAAK,CAAC,CAAChB,SAAS;EAC7BiB,aAAatB,IAAEuB,QAAQ,CAAC,CAAClB,SAAS;EAClCmB,WAAW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InE,mBAAmB;EAC1C;EACAoE,kBAAkB,OAAOpD,YAAYlB,gBAAgB;GACnD,IAAIkB,WAAWP,aAAakC,OAAOlC,UAAU,MAAM,IAAIL,MAAM,oCAAoC;GACjG,MAAMiE,kBAAkB,MAAM/E,OAAO2D,IAAI,kCAAkCN,OAAOC,GAAG;GACrF,MAAMnD,UAAUI,sBAAsBC,WAAW;GACjD,MAAMuE,gBAAgBC,WACpB;IACE7D,UAAUkC,OAAOlC;IACjBQ,gBAAgBD,WAAWC;GAC7B,GACAF,qBAAqBC,UAAU,GAC/B;IACEuD,QAAQ;IACRC,eAAe;IACf,GAAI/E,UAAU,EAAEA,QAAQ,IAAI,CAAC;GAC/B,CACF;EACF;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["Schema","z","ZRBUser","object","email","string","optional","password","name","phone","tenants","array","tenantRoles","record","oauthProviders","subject","accessToken","refreshToken","idToken","scope","tokenType","expiresAt","date","rawUserInfo","unknown","createdAt","updatedAt","emailVerificationCode","length","emailVerificationExpiresAt","passwordResetCode","passwordResetCodeExpiresAt","passwordResetToken","passwordResetTokenExpiresAt","IRBUser","infer","RBUserSchema","type","String","unique","sparse","required","index","Map","of","default","Date","Types","Mixed","_id","Schema","z","ZRBTenant","object","tenantId","string","parentTenantId","optional","name","IRBTenant","infer","RBTenantSchema","type","String","required","unique","index","Schema","z","SUBSCRIPTION_CHANGE_DIRECTIONS","SUBSCRIPTION_EVENT_TYPES","SUBSCRIPTION_INTERVAL_UNITS","SUBSCRIPTION_SCOPES","SUBSCRIPTION_STATUSES","SUBSCRIPTION_TYPES","ZRBTenantSubscriptionStatus","enum","ZRBTenantSubscriptionIntervalUnit","ZRBTenantSubscriptionType","ZRBTenantSubscriptionScope","ZRBTenantSubscriptionEventType","ZRBTenantSubscriptionEventSource","ZRBTenantSubscriptionChangeDirection","subscriptionEventBaseSchema","object","tenantId","string","trim","min","subscriptionId","occurredAt","date","effectiveAt","subscriptionType","parentSubscriptionId","optional","scope","scopeId","fromPlanKey","toPlanKey","fromStatus","toStatus","fromModules","array","toModules","fromIntervalUnit","toIntervalUnit","fromIntervalCount","number","int","toIntervalCount","fromPriceId","toPriceId","billingAnchor","supersedesEventId","idempotencyKey","direction","actorUserId","source","reason","provider","providerEventId","providerPayload","unknown","metadata","record","subscriptionCreatedEventSchema","extend","type","literal","subscriptionPlanChangedEventSchema","subscriptionStatusChangedEventSchema","subscriptionResumedEventSchema","subscriptionCanceledEventSchema","subscriptionRenewedEventSchema","ZRBTenantSubscriptionEvent","discriminatedUnion","superRefine","event","ctx","addIssue","code","message","path","IRBTenantSubscriptionEvent","infer","SubscriptionEventDocument","requiredForEventTypes","types","Array","requiredForEventType","this","Boolean","includes","RBTenantSubscriptionEventSchema","String","required","index","options","Date","default","now","undefined","Number","Types","Mixed","unique","partialFilterExpression","$type","Schema","z","ZRBTenantSubscriptionIntervalUnit","ZRBTenantSubscriptionScope","ZRBTenantSubscriptionStatus","ZRBTenantSubscriptionType","ZRBTenantSubscriptionProjection","object","tenantId","string","subscriptionId","type","parentSubscriptionId","optional","scope","scopeId","planKey","priceId","status","intervalUnit","intervalCount","number","int","min","modules","array","billingAnchor","date","currentPeriodStart","currentPeriodEnd","cancelAtPeriodEnd","boolean","cancelAt","canceledAt","scheduledPlanKey","scheduledPlanEffectiveAt","provider","latestEventId","latestEventAt","projectedAt","IRBTenantSubscriptionProjection","infer","RBTenantSubscriptionProjectionSchema","String","required","index","enum","options","Number","default","Date","Boolean","unique","Schema","z","ZRBRtsCounter","object","_id","string","seq","number","int","min","IRBRtsCounter","infer","RBRtsCounterSchema","type","String","required","Number","default","versionKey","Schema","z","ttlSecondsRaw","process","env","RB_RTS_CHANGES_TTL_S","ttlSeconds","Number","isFinite","Math","max","floor","ZRBRtsChangeOp","enum","ZRBRtsChange","object","seq","number","int","min","modelName","string","op","docId","optional","ts","date","IRBRtsChange","infer","RBRtsChangeSchema","type","required","String","index","options","Date","default","now","versionKey","unique","expireAfterSeconds","Schema","z","AclPolicy","ZRBUploadSessionStatus","enum","ZRBUploadAccessScope","ZRBUploadDeduplication","object","namespace","string","algorithm","literal","hash","key","pipelineVersion","number","int","min","ZRBUploadSession","_id","userId","optional","ownerKeyHash","filename","mimeType","totalSize","chunkSize","chunksTotal","status","createdAt","date","expiresAt","fileId","isPublic","boolean","accessScope","deduplication","deduplicated","error","IRBUploadSession","infer","RBUploadSessionSchema","type","String","required","index","Number","options","Date","default","now","Boolean","versionKey","expireAfterSeconds","RBUploadSessionPolicy","subject","define","builder","ctx","can","uploadKeyHash","claims","trim","Schema","z","ZRBUploadChunk","object","uploadId","string","index","number","int","min","data","unknown","size","sha256","optional","createdAt","date","expiresAt","IRBUploadChunk","infer","RBUploadChunkSchema","type","String","required","Number","Buffer","Date","default","now","versionKey","unique","expireAfterSeconds","Schema","z","AclPolicy","ZStringMap","record","string","ZRBNotificationPlatformPayload","object","webpush","unknown","optional","fcmOptions","android","apns","passthrough","IRBNotificationPlatformPayload","infer","ZRBNotification","userId","topic","tag","deliveryId","title","body","image","data","platform","drawerActive","boolean","createdAt","date","seenAt","readAt","archivedAt","IRBNotification","TTL_90_DAYS_S","RBNotificationSchema","type","String","required","index","Types","Mixed","Boolean","Date","default","now","versionKey","unique","partialFilterExpression","$exists","expireAfterSeconds","RBNotificationPolicy","subject","define","builder","ctx","can","Schema","z","AclPolicy","ZRBNotificationPlatformPayload","ZStringMap","record","string","ZRBNotificationDelivery","object","userId","notificationId","optional","deliveryId","topic","tag","title","body","image","data","platform","createdAt","date","IRBNotificationDelivery","infer","TTL_90_DAYS_S","RBNotificationDeliverySchema","type","String","required","index","unique","Types","Mixed","Date","default","now","versionKey","expireAfterSeconds","RBNotificationDeliveryPolicy","subject","define","builder","ctx","can","Schema","z","AclPolicy","ZRBNotificationDigestFrequency","enum","ZRBNotificationTopicPreference","object","topic","string","inApp","boolean","emailDigest","push","ZRBNotificationSettings","userId","digestFrequency","topicPreferences","array","optional","lastDigestSentAt","date","IRBNotificationSettings","infer","TopicPreferenceSchema","type","String","required","Boolean","default","_id","RBNotificationSettingsSchema","options","Date","versionKey","timestamps","index","unique","RBNotificationSettingsPolicy","subject","define","builder","ctx","can","Schema","z","ZRBOAuthRequest","object","_id","string","providerId","codeVerifier","returnTo","optional","createdAt","date","expiresAt","IRBOAuthRequest","infer","RBOAuthRequestSchema","type","String","required","index","Date","default","now","versionKey","expireAfterSeconds","Schema","MongooseSchemaExtension","Parameters","extendMongooseSchema","baseSchema","TSchema","extensions","schema","clone","forEach","extension","add","omitMongooseSchemaPaths","paths","path","remove","Schema","SchemaTypeOptions","LocalizedString","withLocalizedStringFallback","localizedStringField","options","Omit","userGet","get","type","Types","Mixed","value","PaginationErrorCode","PaginationValidationError","Error","code","statusCode","constructor","message","options","ErrorOptions","name","isPaginationValidationError","error","anyError","Partial","PaginationDirection","PaginationOrder","PaginationSpec","PaginationValidationError","DISALLOWED_MONGO_FIELD_SEGMENTS","Set","PAGINATION_LIMIT_MAX","NormalizedPaginationSpec","Omit","direction","limit","sort","Array","field","order","normalizePaginationSpec","spec","options","maxLimit","normalizeLimit","normalizeMaxLimit","isArray","length","map","assertSafeMongoFieldPath","normalizeOrder","seenFields","has","add","primaryOrder","push","undefined","Number","isSafeInteger","isFinite","isInteger","startsWith","parts","split","part","test","createHmac","timingSafeEqual","Types","PaginationSpec","PaginationValidationError","normalizePaginationSpec","CursorValue","$date","$oid","CursorPayloadV1","v","values","Record","PaginationCursorCodecOptions","signingSecret","Buffer","maxLimit","encodePaginationCursor","spec","node","options","normalized","Object","create","field","sort","value","readFieldValue","Error","encodeCursorValue","payload","payloadB64","from","JSON","stringify","toString","sigB64","signCursorPayloadB64","decodePaginationCursor","cursor","rest","split","length","verifyCursorSignature","payloadRaw","payloadUnknown","parse","Partial","decoded","prototype","hasOwnProperty","call","encodedValue","decodeCursorValue","secret","update","digest","expectedSigB64","a","b","unwrapCursorComparableValue","Date","ObjectId","current","depth","_id","comparableValue","toHexString","toISOString","d","Number","isNaN","getTime","isValid","undefined","get","path","reduce","acc","key","PaginationOrder","PaginationSpec","PaginationCursorCodecOptions","decodePaginationCursor","PaginationValidationError","NormalizedPaginationSpec","normalizePaginationSpec","CompiledMongoPagination","spec","mongoFilterDelta","Record","mongoSort","mongoLimit","CompileMongoPaginationOptions","cursor","compileMongoPagination","options","normalized","maxLimit","limit","toMongoSort","length","cursorValues","buildKeysetFilterDelta","Object","create","field","order","sort","forQueryOrder","direction","invertOrder","branches","i","current","and","j","prev","eq","push","op","getKeysetOp","cmpOp","cmp","$and","$or","PaginationResponse","PaginationCursorCodecOptions","encodePaginationCursor","CompiledMongoPagination","MaterializePaginationOptions","cursor","includeCursors","materializeMongoPagination","compiled","fetchedNodes","TNode","options","limit","spec","hasMore","length","trimmed","slice","nodes","direction","reverse","hasPrevPage","Boolean","hasNextPage","pageInfo","prevCursor","nextCursor","CompiledMongoPagination","MongoQueryLike","where","delta","Record","sort","limit","MongoAdapter","applyPagination","query","TQuery","compiled","mongoFilterDelta","mongoSort","mongoLimit","PaginationResponse","PaginationSpec","PaginationCursorCodecOptions","compileMongoPagination","materializeMongoPagination","MongoAdapter","MongoPaginateQueryLike","where","delta","Record","sort","limit","exec","Promise","TNode","PaginateMongoQueryOptions","cursor","includeCursors","paginateMongoQuery","query","pagination","options","compiled","applyPagination","fetchedNodes","Array","isArray","Error","mongoose","PaginationResponse","PaginationSpec","PaginationCursorCodecOptions","paginateMongoQuery","mongoPaginationPluginBrand","QueryOptionsLike","Record","getQueryOptions","query","undefined","getOptions","getPaginationFromOptions","options","pagination","getCursorFromOptions","paginationCursor","MongoPaginationPluginOptions","cursor","includeCursors","QueryResultNode","TResult","Array","TNode","Query","DocType","THelpers","RawDocType","QueryOp","TDocOverrides","paginate","Promise","ResultType","mongoPaginationPlugin","schema","Schema","pluginOptions","this","spec","Error","signingSecret","MongoDbLike","databaseName","command","Record","Promise","SearchTextStageOptions","index","query","path","highlightPath","SearchTextStage","$search","text","highlight","buildSearchTextStage","options","trim","Error","stage","searchMetaProjection","score","$meta","highlights","const","EnsureSearchIndexParams","db","collection","name","definition","listResultHasIndex","listResult","cursor","firstBatch","Array","isArray","some","idx","isIndexAlreadyExistsError","error","codeName","undefined","message","String","test","ensureSearchIndex","params","created","listSearchIndexes","createSearchIndexes","indexes","getAppName","env","NodeJS","ProcessEnv","process","appName","APP_NAME","trim","Error","GLOBAL_DB_SUFFIX","getGlobalDbName","getTenantDbName","tenantId","mongoose","getMongoDirectConnection","getMongoUrl","connections","Map","Connection","rootConnection","CONNECTION_MAX_LISTENERS","waitForOpen","connection","Promise","readyState","getMaxListeners","setMaxListeners","resolve","reject","once","ensureMongooseConnection","dbName","normalizedDbName","trim","Error","existing","get","mongoUrl","createConnection","sanitizeFilter","directConnection","name","useDb","useCache","set","mongoose","GLOBAL_DB_SUFFIX","RBRtsChangeSchema","IRBRtsChange","RBRtsCounterSchema","IRBRtsCounter","RtsChangeOp","RTS_COUNTER_ID","EXCLUDED_MODEL_NAMES","Set","maxDeleteIdsRaw","process","env","RB_RTS_DELETE_LOG_MAX_IDS","maxDeleteIds","Number","isFinite","Math","max","floor","DeleteMeta","modelName","ids","reset","session","ClientSession","deleteMetaByQuery","WeakMap","hasToString","value","toString","maybe","normalizeId","id","getDbName","db","name","databaseName","raw","isGlobalDb","endsWith","RtsCounterDoc","RtsChangeDoc","getQuerySession","query","MongooseQuery","opts","getOptions","undefined","getRtsModels","Connection","RtsCounter","models","RBRtsCounter","Model","model","RtsChange","RBRtsChange","allocateSeqRange","count","Promise","start","end","updated","findOneAndUpdate","_id","$inc","seq","upsert","returnDocument","setDefaultsOnInsert","projection","lean","insertChanges","changes","Array","op","docId","length","ts","Date","docs","map","c","insertMany","recordDeleteChanges","uniqueIds","from","filter","Boolean","idx","recordResetModel","Query","find","getFilter","getQuery","captureDeleteMeta","mode","String","startsWith","has","findQuery","s","limit","n","isArray","d","trimmedIds","meta","set","flushDeleteMeta","get","delete","rtsChangeLogPlugin","schema","Schema","pre","document","this","post","doc","mongoose","accessibleBy","AclAction","AclSubjectType","AppAbility","StoredAcl","ability","action","QueryOptionsLike","Record","PipelineStageLike","isRecord","value","Boolean","Array","isArray","mergeMongoQuery","left","right","leftQuery","Object","keys","length","$and","getQueryOptions","query","undefined","getOptions","getStoredAclFromQuery","options","raw","rbAcl","getStoredAclFromAggregate","aggregate","acl","addQueryAclFilter","Query","storedAcl","resolvedAction","modelName","model","accessQuery","ofType","and","injectAggregateMatch","pipeline","match","unshift","$match","first","geoNear","$geoNear","splice","addAggregateAclFilter","Aggregate","patchAggregateAcl","globalKey","Symbol","for","globalState","globalThis","AggregatePrototype","prototype","this","option","createModelAclProxy","Model","TModel","Proxy","get","target","prop","receiver","Error","Reflect","args","result","apply","mongooseAclPluginBrand","QueryOptions","DocType","AggregateOptions","ResultType","THelpers","RawDocType","QueryOp","TDocOverrides","TRawDocType","TQueryHelpers","TInstanceMethods","TVirtuals","THydratedDocumentType","TSchema","TLeanResultType","mongooseAclPlugin","schema","Schema","setOptions","statics","pre","_private","mongoose","accessibleRecordsPlugin","frameworkSchemas","rtsChangeLogPlugin","registerPoliciesFromModules","mongooseAclPlugin","mongoPaginationPlugin","ModelModules","Record","ModelsScope","RegisterModelsOptions","allowReservedRbModelNames","RegisteredSchemas","Schema","RegisteredModels","tenant","global","cachedModels","DEFAULT_GLOBAL_RB_MODEL_NAMES_SET","Set","assertSchema","exportName","value","Error","join","getFrameworkSchemaForModelName","modelName","applyTenantPlugins","schema","plugin","registerSchema","target","other","scope","buildSchemasFromModules","modules","Array","Object","entries","filter","key","endsWith","map","schemaValue","replace","registerModels","options","tenantSchemas","globalSchemas","has","cloned","clone","startsWith","frameworkSchema","allSchemas","models","model","getRegisteredModels","assert","getGlobalDbName","getTenantDbName","ensureMongooseConnection","getRegisteredModels","registerModels","ModelsScope","hasRegisteredPolicy","AppAbility","LoadModelCtx","tenantId","req","session","user","currentTenantId","ability","loadModelFromDb","modelName","dbName","scope","schemas","schema","Object","keys","join","modelConnection","models","model","normalizeTenantId","value","trim","getTenantIdFromLoadModelCtx","ctx","register","getUnsafe","get","resolvedAbility","isProtected","Error","acl","appAbility","getGlobal","const","LoadModelCtx","ModelModules","RegisterModelsOptions","frameworkSchemas","models","registerModels","ExtractModelNamesFromSchemas","TModules","K","Name","FrameworkModelName","RpcbaseGlobalModelName","Extract","TenantModelName","TTenantModules","GlobalModelName","TGlobalModules","LoadedTenantModel","Awaited","ReturnType","LoadedGlobalModel","ModelsGetFn","modelName","ctx","modelNames","TNames","Promise","ModelsGetUnsafeFn","ModelsGetGlobalFn","ModelsConfig","tenant","global","ModelsClient","register","modules","options","get","getUnsafe","getGlobal","createModels","Record","modelNameOrNames","Array","isArray","all","map","nextModules","nextOptions","assert","mongoose","ensureMongooseConnection","getTenantIdFromLoadModelCtx","LoadModelCtx","getAppName","appName","process","env","APP_NAME","trim","normalizeTenantId","tenantId","normalized","getTenantFilesystemDbName","getTenantFilesystemDb","Promise","Connection","getTenantFilesystemDbFromCtx","ctx","mongoose","ClientSession","getGlobalDbName","getTenantDbName","ensureMongooseConnection","getTenantIdFromLoadModelCtx","LoadModelCtx","getTenantFilesystemDbName","MongooseTransactionOptions","Parameters","TenantGlobalFilesystemTransactionCtx","tenantId","session","ctx","tenant","global","db","Connection","filesystem","WithTransactionScope","buildTenantLoadModelCtx","req","user","currentTenantId","withTransaction","fn","Promise","T","options","scope","normalizedTenantId","trim","Error","tenantDbName","globalDbName","filesystemDbName","tenantDb","globalDb","filesystemDb","startSession","tenantCtx","globalCtx","endSession","ClientSession","BillingStorage","BillingStorageTransaction","PersistedSubscriptionEvent","StoredSubscriptionProjection","SubscriptionEvent","ZRBTenantSubscriptionEvent","LoadModelCtx","models","withTransaction","MongoBillingTransaction","session","SubscriptionEventDocument","Record","_id","getTransactionSession","transaction","undefined","toSubscriptionEvent","document","parsed","parse","Error","id","String","getExistingEventQuery","event","tenantId","idempotencyKey","isDuplicateKeyError","error","Boolean","code","toProjectionDocument","projection","subscriptionId","type","parentSubscriptionId","scope","scopeId","planKey","priceId","status","intervalUnit","intervalCount","modules","billingAnchor","currentPeriodStart","currentPeriodEnd","cancelAtPeriodEnd","cancelAt","canceledAt","scheduledPlanKey","scheduledPlan","scheduledPlanEffectiveAt","effectiveAt","provider","latestEventId","latestEventAt","projectedAt","createTenantBillingStorage","params","ctx","findExistingEvent","query","Promise","EventModel","get","request","findOne","lean","runInTransaction","operation","createEvent","existingQuery","existing","eventDocument","documents","create","toObject","duplicate","listEvents","find","sort","occurredAt","map","upsertProjection","ProjectionModel","replaceOne","upsert","runValidators"],"sources":["../src/models/RBUser.ts","../src/models/RBTenant.ts","../src/models/RBTenantSubscriptionEvent.ts","../src/models/RBTenantSubscriptionProjection.ts","../src/models/RBRtsCounter.ts","../src/models/RBRtsChange.ts","../src/models/RBUploadSession.ts","../src/models/RBUploadChunk.ts","../src/models/RBNotification.ts","../src/models/RBNotificationDelivery.ts","../src/models/RBNotificationSettings.ts","../src/models/RBOAuthRequest.ts","../src/models/index.ts","../src/mongoose/extendMongooseSchema.ts","../src/mongoose/localizedStringField.ts","../src/mongoose/index.ts","../src/pagination/errors.ts","../src/pagination/normalizeSpec.ts","../src/pagination/cursor.ts","../src/pagination/compileMongoPagination.ts","../src/pagination/materializePagination.ts","../src/pagination/mongoAdapter.ts","../src/pagination/paginateMongoQuery.ts","../src/pagination/mongoPaginationPlugin.ts","../src/search/index.ts","../src/dbNames.ts","../src/ensureMongooseConnection.ts","../src/rtsChangeLogPlugin.ts","../src/acl/mongooseAclPlugin.ts","../src/registerModels.ts","../src/modelsApi.ts","../src/createModels.ts","../src/tenantFilesystemDb.ts","../src/transactions.ts","../src/billingStorage.ts"],"sourcesContent":["import { Schema } from \"mongoose\"\nimport { z } from \"zod\"\n\n\nexport const ZRBUser = z.object({\n email: z.string().email().optional(),\n password: z.string(),\n name: z.string().optional(),\n phone: z.string().optional(),\n tenants: z.array(z.string()),\n tenantRoles: z.record(z.string(), z.array(z.string())).optional(),\n oauthProviders: z.record(z.string(), z.object({\n subject: z.string(),\n email: z.string().email().optional(),\n name: z.string().optional(),\n accessToken: z.string().optional(),\n refreshToken: z.string().optional(),\n idToken: z.string().optional(),\n scope: z.string().optional(),\n tokenType: z.string().optional(),\n expiresAt: z.date().optional(),\n rawUserInfo: z.unknown().optional(),\n createdAt: z.date().optional(),\n updatedAt: z.date().optional(),\n })).optional(),\n emailVerificationCode: z.string().length(6).optional(),\n emailVerificationExpiresAt: z.date().optional(),\n passwordResetCode: z.string().length(6).optional(),\n passwordResetCodeExpiresAt: z.date().optional(),\n passwordResetToken: z.string().optional(),\n passwordResetTokenExpiresAt: z.date().optional(),\n})\n\nexport type IRBUser = z.infer<typeof ZRBUser>;\n\nexport const RBUserSchema: Schema = new Schema({\n email: { type: String, unique: true, sparse: true },\n phone: { type: String, unique: true, sparse: true },\n password: { type: String, required: true },\n name: String,\n tenants: { type: [String], index: true, required: true },\n tenantRoles: { type: Map, of: [String], required: false, default: {} },\n oauthProviders: {\n type: Map,\n of: new Schema({\n subject: { type: String, required: true },\n email: { type: String, required: false },\n name: { type: String, required: false },\n accessToken: { type: String, required: false },\n refreshToken: { type: String, required: false },\n idToken: { type: String, required: false },\n scope: { type: String, required: false },\n tokenType: { type: String, required: false },\n expiresAt: { type: Date, required: false },\n rawUserInfo: { type: Schema.Types.Mixed, required: false },\n createdAt: { type: Date, required: false },\n updatedAt: { type: Date, required: false },\n }, { _id: false }),\n default: {},\n required: false,\n },\n emailVerificationCode: { type: String, required: false },\n emailVerificationExpiresAt: { type: Date, required: false },\n passwordResetCode: { type: String, required: false },\n passwordResetCodeExpiresAt: { type: Date, required: false },\n passwordResetToken: { type: String, required: false },\n passwordResetTokenExpiresAt: { type: Date, required: false },\n})\n","import { Schema } from \"mongoose\"\nimport { z } from \"zod\"\n\n\nexport const ZRBTenant = z.object({\n tenantId: z.string(),\n parentTenantId: z.string().optional(),\n name: z.string().optional(),\n})\n\nexport type IRBTenant = z.infer<typeof ZRBTenant>;\n\nexport const RBTenantSchema: Schema = new Schema({\n tenantId: { type: String, required: true, unique: true, index: true },\n parentTenantId: { type: String },\n name: { type: String },\n})\n","import { Schema } from \"mongoose\"\nimport { z } from \"zod\"\nimport {\n SUBSCRIPTION_CHANGE_DIRECTIONS,\n SUBSCRIPTION_EVENT_TYPES,\n SUBSCRIPTION_INTERVAL_UNITS,\n SUBSCRIPTION_SCOPES,\n SUBSCRIPTION_STATUSES,\n SUBSCRIPTION_TYPES,\n} from \"@rpcbase/billing\"\n\n\nexport const ZRBTenantSubscriptionStatus = z.enum(SUBSCRIPTION_STATUSES)\n\nexport const ZRBTenantSubscriptionIntervalUnit = z.enum(SUBSCRIPTION_INTERVAL_UNITS)\n\nexport const ZRBTenantSubscriptionType = z.enum(SUBSCRIPTION_TYPES)\n\nexport const ZRBTenantSubscriptionScope = z.enum(SUBSCRIPTION_SCOPES)\n\nexport const ZRBTenantSubscriptionEventType = z.enum(SUBSCRIPTION_EVENT_TYPES)\n\n\nexport const ZRBTenantSubscriptionEventSource = z.enum([\n \"admin\",\n \"system\",\n \"webhook\",\n \"user\",\n])\n\nexport const ZRBTenantSubscriptionChangeDirection = z.enum(SUBSCRIPTION_CHANGE_DIRECTIONS)\n\nconst subscriptionEventBaseSchema = z.object({\n tenantId: z.string().trim().min(1),\n subscriptionId: z.string().trim().min(1),\n occurredAt: z.date(),\n effectiveAt: z.date(),\n subscriptionType: ZRBTenantSubscriptionType,\n parentSubscriptionId: z.string().optional(),\n scope: ZRBTenantSubscriptionScope,\n scopeId: z.string().optional(),\n fromPlanKey: z.string().optional(),\n toPlanKey: z.string().optional(),\n fromStatus: ZRBTenantSubscriptionStatus.optional(),\n toStatus: ZRBTenantSubscriptionStatus.optional(),\n fromModules: z.array(z.string()).optional(),\n toModules: z.array(z.string()).optional(),\n fromIntervalUnit: ZRBTenantSubscriptionIntervalUnit.optional(),\n toIntervalUnit: ZRBTenantSubscriptionIntervalUnit.optional(),\n fromIntervalCount: z.number().int().min(1).optional(),\n toIntervalCount: z.number().int().min(1).optional(),\n fromPriceId: z.string().optional(),\n toPriceId: z.string().optional(),\n billingAnchor: z.date().optional(),\n supersedesEventId: z.string().optional(),\n idempotencyKey: z.string().trim().min(1),\n direction: ZRBTenantSubscriptionChangeDirection.optional(),\n actorUserId: z.string().optional(),\n source: ZRBTenantSubscriptionEventSource.optional(),\n reason: z.string().optional(),\n provider: z.string().optional(),\n providerEventId: z.string().optional(),\n providerPayload: z.unknown().optional(),\n metadata: z.record(z.string(), z.unknown()).optional(),\n})\n\nconst subscriptionCreatedEventSchema = subscriptionEventBaseSchema.extend({\n type: z.literal(\"created\"),\n toPlanKey: z.string().trim().min(1),\n toStatus: ZRBTenantSubscriptionStatus,\n toModules: z.array(z.string()),\n toIntervalUnit: ZRBTenantSubscriptionIntervalUnit,\n toIntervalCount: z.number().int().min(1),\n billingAnchor: z.date(),\n})\n\nconst subscriptionPlanChangedEventSchema = subscriptionEventBaseSchema.extend({\n type: z.literal(\"plan_changed\"),\n fromPlanKey: z.string().trim().min(1),\n toPlanKey: z.string().trim().min(1),\n fromModules: z.array(z.string()),\n toModules: z.array(z.string()),\n fromIntervalUnit: ZRBTenantSubscriptionIntervalUnit,\n toIntervalUnit: ZRBTenantSubscriptionIntervalUnit,\n fromIntervalCount: z.number().int().min(1),\n toIntervalCount: z.number().int().min(1),\n})\n\nconst subscriptionStatusChangedEventSchema = subscriptionEventBaseSchema.extend({\n type: z.literal(\"status_changed\"),\n fromStatus: ZRBTenantSubscriptionStatus,\n toStatus: ZRBTenantSubscriptionStatus,\n})\n\nconst subscriptionResumedEventSchema = subscriptionEventBaseSchema.extend({\n type: z.literal(\"resumed\"),\n fromStatus: ZRBTenantSubscriptionStatus,\n toStatus: z.literal(\"active\"),\n})\n\nconst subscriptionCanceledEventSchema = subscriptionEventBaseSchema.extend({\n type: z.literal(\"canceled\"),\n fromStatus: ZRBTenantSubscriptionStatus,\n toStatus: z.literal(\"canceled\"),\n})\n\nconst subscriptionRenewedEventSchema = subscriptionEventBaseSchema.extend({\n type: z.literal(\"renewed\"),\n fromStatus: ZRBTenantSubscriptionStatus,\n toStatus: ZRBTenantSubscriptionStatus,\n})\n\nexport const ZRBTenantSubscriptionEvent = z.discriminatedUnion(\"type\", [\n subscriptionCreatedEventSchema,\n subscriptionPlanChangedEventSchema,\n subscriptionStatusChangedEventSchema,\n subscriptionResumedEventSchema,\n subscriptionCanceledEventSchema,\n subscriptionRenewedEventSchema,\n]).superRefine((event, ctx) => {\n if (event.subscriptionType === \"addon\" && !event.parentSubscriptionId?.trim()) {\n ctx.addIssue({\n code: \"custom\",\n message: \"parentSubscriptionId is required for add-on subscriptions\",\n path: [\"parentSubscriptionId\"],\n })\n }\n if (event.scope !== \"tenant\" && !event.scopeId?.trim()) {\n ctx.addIssue({\n code: \"custom\",\n message: \"scopeId is required for non-tenant subscriptions\",\n path: [\"scopeId\"],\n })\n }\n})\n\nexport type IRBTenantSubscriptionEvent = z.infer<typeof ZRBTenantSubscriptionEvent>\n\ntype SubscriptionEventDocument = {\n type?: typeof SUBSCRIPTION_EVENT_TYPES[number]\n subscriptionType?: typeof SUBSCRIPTION_TYPES[number]\n scope?: typeof SUBSCRIPTION_SCOPES[number]\n}\n\nconst requiredForEventTypes = (...types: Array<typeof SUBSCRIPTION_EVENT_TYPES[number]>) =>\n function requiredForEventType(this: SubscriptionEventDocument): boolean {\n return Boolean(this.type && types.includes(this.type))\n }\n\nexport const RBTenantSubscriptionEventSchema: Schema = new Schema(\n {\n tenantId: { type: String, required: true, index: true },\n subscriptionId: { type: String, required: true, index: true },\n type: { type: String, required: true, enum: ZRBTenantSubscriptionEventType.options },\n occurredAt: { type: Date, required: true, default: Date.now },\n effectiveAt: { type: Date, required: true },\n subscriptionType: { type: String, required: true, enum: ZRBTenantSubscriptionType.options },\n parentSubscriptionId: {\n type: String,\n required(this: SubscriptionEventDocument) {\n return this.subscriptionType === \"addon\"\n },\n },\n scope: { type: String, required: true, enum: ZRBTenantSubscriptionScope.options },\n scopeId: {\n type: String,\n required(this: SubscriptionEventDocument) {\n return Boolean(this.scope && this.scope !== \"tenant\")\n },\n },\n fromPlanKey: { type: String, required: requiredForEventTypes(\"plan_changed\") },\n toPlanKey: { type: String, required: requiredForEventTypes(\"created\", \"plan_changed\") },\n fromStatus: {\n type: String,\n required: requiredForEventTypes(\"status_changed\", \"resumed\", \"canceled\", \"renewed\"),\n enum: ZRBTenantSubscriptionStatus.options,\n },\n toStatus: {\n type: String,\n required: requiredForEventTypes(\"created\", \"status_changed\", \"resumed\", \"canceled\", \"renewed\"),\n enum: ZRBTenantSubscriptionStatus.options,\n },\n fromModules: { type: [String], required: requiredForEventTypes(\"plan_changed\"), default: undefined },\n toModules: { type: [String], required: requiredForEventTypes(\"created\", \"plan_changed\"), default: undefined },\n fromIntervalUnit: {\n type: String,\n required: requiredForEventTypes(\"plan_changed\"),\n enum: ZRBTenantSubscriptionIntervalUnit.options,\n },\n toIntervalUnit: {\n type: String,\n required: requiredForEventTypes(\"created\", \"plan_changed\"),\n enum: ZRBTenantSubscriptionIntervalUnit.options,\n },\n fromIntervalCount: { type: Number, required: requiredForEventTypes(\"plan_changed\"), min: 1 },\n toIntervalCount: { type: Number, required: requiredForEventTypes(\"created\", \"plan_changed\"), min: 1 },\n fromPriceId: { type: String },\n toPriceId: { type: String },\n billingAnchor: { type: Date, required: requiredForEventTypes(\"created\") },\n supersedesEventId: { type: String },\n idempotencyKey: { type: String, required: true },\n direction: { type: String, enum: ZRBTenantSubscriptionChangeDirection.options },\n actorUserId: { type: String },\n source: { type: String, enum: ZRBTenantSubscriptionEventSource.options },\n reason: { type: String },\n provider: { type: String },\n providerEventId: { type: String },\n providerPayload: { type: Schema.Types.Mixed },\n metadata: { type: Schema.Types.Mixed },\n },\n)\n\nRBTenantSubscriptionEventSchema.index({ tenantId: 1, subscriptionId: 1, effectiveAt: 1, occurredAt: 1 })\nRBTenantSubscriptionEventSchema.index(\n { provider: 1, providerEventId: 1 },\n {\n unique: true,\n partialFilterExpression: {\n provider: { $type: \"string\" },\n providerEventId: { $type: \"string\" },\n },\n },\n)\nRBTenantSubscriptionEventSchema.index({ tenantId: 1, idempotencyKey: 1 }, { unique: true })\n","import { Schema } from \"mongoose\"\nimport { z } from \"zod\"\n\nimport {\n ZRBTenantSubscriptionIntervalUnit,\n ZRBTenantSubscriptionScope,\n ZRBTenantSubscriptionStatus,\n ZRBTenantSubscriptionType,\n} from \"./RBTenantSubscriptionEvent\"\n\n\nexport const ZRBTenantSubscriptionProjection = z.object({\n tenantId: z.string(),\n subscriptionId: z.string(),\n type: ZRBTenantSubscriptionType,\n parentSubscriptionId: z.string().optional(),\n scope: ZRBTenantSubscriptionScope,\n scopeId: z.string().optional(),\n planKey: z.string(),\n priceId: z.string().optional(),\n status: ZRBTenantSubscriptionStatus,\n intervalUnit: ZRBTenantSubscriptionIntervalUnit,\n intervalCount: z.number().int().min(1),\n modules: z.array(z.string()),\n billingAnchor: z.date(),\n currentPeriodStart: z.date(),\n currentPeriodEnd: z.date(),\n cancelAtPeriodEnd: z.boolean(),\n cancelAt: z.date().optional(),\n canceledAt: z.date().optional(),\n scheduledPlanKey: z.string().optional(),\n scheduledPlanEffectiveAt: z.date().optional(),\n provider: z.string().optional(),\n latestEventId: z.string(),\n latestEventAt: z.date(),\n projectedAt: z.date(),\n})\n\nexport type IRBTenantSubscriptionProjection = z.infer<typeof ZRBTenantSubscriptionProjection>\n\nexport const RBTenantSubscriptionProjectionSchema: Schema = new Schema({\n tenantId: { type: String, required: true, index: true },\n subscriptionId: { type: String, required: true },\n type: { type: String, required: true, enum: ZRBTenantSubscriptionType.options },\n parentSubscriptionId: { type: String },\n scope: { type: String, required: true, enum: ZRBTenantSubscriptionScope.options },\n scopeId: { type: String },\n planKey: { type: String, required: true },\n priceId: { type: String },\n status: { type: String, required: true, enum: ZRBTenantSubscriptionStatus.options },\n intervalUnit: { type: String, required: true, enum: ZRBTenantSubscriptionIntervalUnit.options },\n intervalCount: { type: Number, required: true, min: 1 },\n modules: { type: [String], required: true, default: [] },\n billingAnchor: { type: Date, required: true },\n currentPeriodStart: { type: Date, required: true },\n currentPeriodEnd: { type: Date, required: true },\n cancelAtPeriodEnd: { type: Boolean, required: true, default: false },\n cancelAt: { type: Date },\n canceledAt: { type: Date },\n scheduledPlanKey: { type: String },\n scheduledPlanEffectiveAt: { type: Date },\n provider: { type: String },\n latestEventId: { type: String, required: true },\n latestEventAt: { type: Date, required: true },\n projectedAt: { type: Date, required: true },\n})\n\nRBTenantSubscriptionProjectionSchema.index({ tenantId: 1, subscriptionId: 1 }, { unique: true })\nRBTenantSubscriptionProjectionSchema.index({ tenantId: 1, scope: 1, scopeId: 1 })\n","import { Schema } from \"mongoose\"\nimport { z } from \"zod\"\n\n\nexport const ZRBRtsCounter = z.object({\n _id: z.string(),\n seq: z.number().int().min(0),\n})\n\nexport type IRBRtsCounter = z.infer<typeof ZRBRtsCounter>\n\nexport const RBRtsCounterSchema: Schema = new Schema(\n {\n _id: { type: String, required: true },\n seq: { type: Number, required: true, default: 0 },\n },\n {\n versionKey: false,\n },\n)\n","import { Schema } from \"mongoose\"\nimport { z } from \"zod\"\n\n\nconst ttlSecondsRaw = process.env.RB_RTS_CHANGES_TTL_S ?? \"\"\nconst ttlSeconds = Number.isFinite(Number(ttlSecondsRaw)) ? Math.max(60, Math.floor(Number(ttlSecondsRaw))) : 60 * 60 * 24 * 30\n\nexport const ZRBRtsChangeOp = z.enum([\"delete\", \"reset_model\"])\n\nexport const ZRBRtsChange = z.object({\n seq: z.number().int().min(0),\n modelName: z.string(),\n op: ZRBRtsChangeOp,\n docId: z.string().optional(),\n ts: z.date(),\n})\n\nexport type IRBRtsChange = z.infer<typeof ZRBRtsChange>\n\nexport const RBRtsChangeSchema: Schema = new Schema(\n {\n seq: { type: Number, required: true },\n modelName: { type: String, required: true, index: true },\n op: { type: String, required: true, enum: ZRBRtsChangeOp.options },\n docId: { type: String, required: false },\n ts: { type: Date, required: true, default: Date.now },\n },\n {\n versionKey: false,\n },\n)\n\nRBRtsChangeSchema.index({ seq: 1 }, { unique: true })\nRBRtsChangeSchema.index({ ts: 1 }, { expireAfterSeconds: ttlSeconds })\n","import { Schema } from \"mongoose\"\nimport { z } from \"zod\"\n\nimport type { AclPolicy } from \"../acl\"\n\n\nexport const ZRBUploadSessionStatus = z.enum([\"uploading\", \"assembling\", \"done\", \"error\"])\nexport const ZRBUploadAccessScope = z.enum([\"owner\", \"tenant\", \"public\"])\n\nexport const ZRBUploadDeduplication = z.object({\n namespace: z.string(),\n algorithm: z.literal(\"sha256\"),\n hash: z.string(),\n key: z.string(),\n pipelineVersion: z.number().int().min(1),\n})\n\nexport const ZRBUploadSession = z.object({\n _id: z.string(),\n userId: z.string().optional(),\n ownerKeyHash: z.string().optional(),\n filename: z.string(),\n mimeType: z.string(),\n totalSize: z.number().int().min(0),\n chunkSize: z.number().int().min(1),\n chunksTotal: z.number().int().min(1),\n status: ZRBUploadSessionStatus,\n createdAt: z.date(),\n expiresAt: z.date(),\n fileId: z.string().optional(),\n isPublic: z.boolean().optional(),\n accessScope: ZRBUploadAccessScope.optional(),\n deduplication: ZRBUploadDeduplication.optional(),\n deduplicated: z.boolean().optional(),\n error: z.string().optional(),\n})\n\nexport type IRBUploadSession = z.infer<typeof ZRBUploadSession>\n\nexport const RBUploadSessionSchema: Schema = new Schema(\n {\n _id: { type: String, required: true },\n userId: { type: String, required: false, index: true },\n ownerKeyHash: { type: String, required: false },\n filename: { type: String, required: true },\n mimeType: { type: String, required: true },\n totalSize: { type: Number, required: true },\n chunkSize: { type: Number, required: true },\n chunksTotal: { type: Number, required: true },\n status: { type: String, required: true, enum: ZRBUploadSessionStatus.options },\n createdAt: { type: Date, required: true, default: Date.now },\n expiresAt: { type: Date, required: true },\n fileId: { type: String, required: false },\n isPublic: { type: Boolean, required: false },\n accessScope: { type: String, required: false, enum: ZRBUploadAccessScope.options },\n deduplication: {\n type: new Schema(\n {\n namespace: { type: String, required: true },\n algorithm: { type: String, required: true, enum: [\"sha256\"] },\n hash: { type: String, required: true },\n key: { type: String, required: true },\n pipelineVersion: { type: Number, required: true },\n },\n { _id: false },\n ),\n required: false,\n },\n deduplicated: { type: Boolean, required: false },\n error: { type: String, required: false },\n },\n {\n versionKey: false,\n },\n)\n\nRBUploadSessionSchema.index({ expiresAt: 1 }, { expireAfterSeconds: 0 })\n\nexport const RBUploadSessionPolicy: AclPolicy = {\n subject: \"RBUploadSession\",\n define: (builder, ctx) => {\n builder.can(\"create\", \"RBUploadSession\")\n\n if (ctx.userId) {\n builder.can(\"read\", \"RBUploadSession\", { userId: ctx.userId })\n builder.can(\"update\", \"RBUploadSession\", { userId: ctx.userId })\n builder.can(\"delete\", \"RBUploadSession\", { userId: ctx.userId })\n }\n\n const uploadKeyHash = typeof ctx.claims?.uploadKeyHash === \"string\" ? ctx.claims.uploadKeyHash.trim() : \"\"\n if (uploadKeyHash) {\n builder.can(\"read\", \"RBUploadSession\", { ownerKeyHash: uploadKeyHash })\n builder.can(\"update\", \"RBUploadSession\", { ownerKeyHash: uploadKeyHash })\n builder.can(\"delete\", \"RBUploadSession\", { ownerKeyHash: uploadKeyHash })\n }\n },\n}\n","import { Schema } from \"mongoose\"\nimport { z } from \"zod\"\n\n\nexport const ZRBUploadChunk = z.object({\n uploadId: z.string(),\n index: z.number().int().min(0),\n data: z.unknown(),\n size: z.number().int().min(0),\n sha256: z.string().optional(),\n createdAt: z.date(),\n expiresAt: z.date(),\n})\n\nexport type IRBUploadChunk = z.infer<typeof ZRBUploadChunk>\n\nexport const RBUploadChunkSchema: Schema = new Schema(\n {\n uploadId: { type: String, required: true, index: true },\n index: { type: Number, required: true },\n data: { type: Buffer, required: true },\n size: { type: Number, required: true },\n sha256: { type: String, required: false },\n createdAt: { type: Date, required: true, default: Date.now },\n expiresAt: { type: Date, required: true },\n },\n {\n versionKey: false,\n },\n)\n\nRBUploadChunkSchema.index({ uploadId: 1, index: 1 }, { unique: true })\nRBUploadChunkSchema.index({ expiresAt: 1 }, { expireAfterSeconds: 0 })\n","import { Schema } from \"mongoose\"\nimport { z } from \"zod\"\n\nimport type { AclPolicy } from \"../acl\"\n\n\nconst ZStringMap = z.record(z.string(), z.string())\n\nexport const ZRBNotificationPlatformPayload = z.object({\n webpush: z.record(z.string(), z.unknown()).optional(),\n fcmOptions: z.record(z.string(), z.unknown()).optional(),\n android: z.record(z.string(), z.unknown()).optional(),\n apns: z.record(z.string(), z.unknown()).optional(),\n}).passthrough()\n\nexport type IRBNotificationPlatformPayload = z.infer<typeof ZRBNotificationPlatformPayload>\n\nexport const ZRBNotification = z.object({\n userId: z.string(),\n topic: z.string().optional(),\n tag: z.string().optional(),\n deliveryId: z.string().optional(),\n title: z.string(),\n body: z.string().optional(),\n image: z.string().optional(),\n data: ZStringMap.optional(),\n platform: ZRBNotificationPlatformPayload.optional(),\n drawerActive: z.boolean().optional(),\n createdAt: z.date(),\n seenAt: z.date().optional(),\n readAt: z.date().optional(),\n archivedAt: z.date().optional(),\n})\n\nexport type IRBNotification = z.infer<typeof ZRBNotification>\n\nconst TTL_90_DAYS_S = 60 * 60 * 24 * 90\n\nexport const RBNotificationSchema: Schema = new Schema(\n {\n userId: { type: String, required: true, index: true },\n topic: { type: String, required: false, index: true },\n tag: { type: String, required: false },\n deliveryId: { type: String, required: false },\n title: { type: String, required: true },\n body: { type: String, required: false },\n image: { type: String, required: false },\n data: { type: Schema.Types.Mixed, required: false },\n platform: { type: Schema.Types.Mixed, required: false },\n drawerActive: { type: Boolean, required: false },\n createdAt: { type: Date, required: true, default: Date.now, index: true },\n seenAt: { type: Date, required: false, index: true },\n readAt: { type: Date, required: false, index: true },\n archivedAt: { type: Date, required: false },\n },\n {\n versionKey: false,\n },\n)\n\nRBNotificationSchema.index({ userId: 1, archivedAt: 1, createdAt: -1 })\nRBNotificationSchema.index({ userId: 1, seenAt: 1, archivedAt: 1, createdAt: -1 })\nRBNotificationSchema.index({ userId: 1, readAt: 1, archivedAt: 1, createdAt: -1 })\nRBNotificationSchema.index(\n { userId: 1, tag: 1 },\n { unique: true, partialFilterExpression: { tag: { $exists: true }, drawerActive: true } },\n)\nRBNotificationSchema.index({ archivedAt: 1 }, { expireAfterSeconds: TTL_90_DAYS_S })\n\nexport const RBNotificationPolicy: AclPolicy = {\n subject: \"RBNotification\",\n define: (builder, ctx) => {\n if (!ctx.userId) return\n builder.can(\"create\", \"RBNotification\")\n builder.can(\"read\", \"RBNotification\", { userId: ctx.userId })\n builder.can(\"update\", \"RBNotification\", { userId: ctx.userId })\n builder.can(\"delete\", \"RBNotification\", { userId: ctx.userId })\n },\n}\n","import { Schema } from \"mongoose\"\nimport { z } from \"zod\"\n\nimport type { AclPolicy } from \"../acl\"\nimport { ZRBNotificationPlatformPayload } from \"./RBNotification\"\n\n\nconst ZStringMap = z.record(z.string(), z.string())\n\nexport const ZRBNotificationDelivery = z.object({\n userId: z.string(),\n notificationId: z.string().optional(),\n deliveryId: z.string(),\n topic: z.string().optional(),\n tag: z.string().optional(),\n title: z.string(),\n body: z.string().optional(),\n image: z.string().optional(),\n data: ZStringMap.optional(),\n platform: ZRBNotificationPlatformPayload.optional(),\n createdAt: z.date(),\n})\n\nexport type IRBNotificationDelivery = z.infer<typeof ZRBNotificationDelivery>\n\nconst TTL_90_DAYS_S = 60 * 60 * 24 * 90\n\nexport const RBNotificationDeliverySchema: Schema = new Schema(\n {\n userId: { type: String, required: true, index: true },\n notificationId: { type: String, required: false },\n deliveryId: { type: String, required: true, unique: true },\n topic: { type: String, required: false },\n tag: { type: String, required: false },\n title: { type: String, required: true },\n body: { type: String, required: false },\n image: { type: String, required: false },\n data: { type: Schema.Types.Mixed, required: false },\n platform: { type: Schema.Types.Mixed, required: false },\n createdAt: { type: Date, required: true, default: Date.now },\n },\n {\n versionKey: false,\n },\n)\n\nRBNotificationDeliverySchema.index({ userId: 1, createdAt: -1 })\nRBNotificationDeliverySchema.index({ createdAt: 1 }, { expireAfterSeconds: TTL_90_DAYS_S })\n\nexport const RBNotificationDeliveryPolicy: AclPolicy = {\n subject: \"RBNotificationDelivery\",\n define: (builder, ctx) => {\n if (!ctx.userId) return\n builder.can(\"create\", \"RBNotificationDelivery\")\n builder.can(\"read\", \"RBNotificationDelivery\", { userId: ctx.userId })\n },\n}\n","import { Schema } from \"mongoose\"\nimport { z } from \"zod\"\n\nimport type { AclPolicy } from \"../acl\"\n\n\nexport const ZRBNotificationDigestFrequency = z.enum([\"off\", \"daily\", \"weekly\"])\n\nexport const ZRBNotificationTopicPreference = z.object({\n topic: z.string(),\n inApp: z.boolean(),\n emailDigest: z.boolean(),\n push: z.boolean(),\n})\n\nexport const ZRBNotificationSettings = z.object({\n userId: z.string(),\n digestFrequency: ZRBNotificationDigestFrequency,\n topicPreferences: z.array(ZRBNotificationTopicPreference).optional(),\n lastDigestSentAt: z.date().optional(),\n})\n\nexport type IRBNotificationSettings = z.infer<typeof ZRBNotificationSettings>\n\nconst TopicPreferenceSchema = new Schema(\n {\n topic: { type: String, required: true },\n inApp: { type: Boolean, required: true, default: true },\n emailDigest: { type: Boolean, required: true, default: true },\n push: { type: Boolean, required: true, default: false },\n },\n { _id: false },\n)\n\nexport const RBNotificationSettingsSchema: Schema = new Schema(\n {\n userId: { type: String, required: true },\n digestFrequency: {\n type: String,\n required: true,\n enum: ZRBNotificationDigestFrequency.options,\n default: \"weekly\",\n },\n topicPreferences: {\n type: [TopicPreferenceSchema],\n default: [],\n },\n lastDigestSentAt: { type: Date, required: false },\n },\n {\n versionKey: false,\n timestamps: true,\n },\n)\n\nRBNotificationSettingsSchema.index({ userId: 1 }, { unique: true })\nRBNotificationSettingsSchema.index({ userId: 1, \"topicPreferences.topic\": 1 })\n\nexport const RBNotificationSettingsPolicy: AclPolicy = {\n subject: \"RBNotificationSettings\",\n define: (builder, ctx) => {\n if (!ctx.userId) return\n builder.can(\"create\", \"RBNotificationSettings\")\n builder.can(\"read\", \"RBNotificationSettings\", { userId: ctx.userId })\n builder.can(\"update\", \"RBNotificationSettings\", { userId: ctx.userId })\n },\n}\n","import { Schema } from \"mongoose\"\nimport { z } from \"zod\"\n\n\nexport const ZRBOAuthRequest = z.object({\n _id: z.string(),\n providerId: z.string(),\n codeVerifier: z.string(),\n returnTo: z.string().optional(),\n createdAt: z.date(),\n expiresAt: z.date(),\n})\n\nexport type IRBOAuthRequest = z.infer<typeof ZRBOAuthRequest>\n\nexport const RBOAuthRequestSchema: Schema = new Schema(\n {\n _id: { type: String, required: true },\n providerId: { type: String, required: true, index: true },\n codeVerifier: { type: String, required: true },\n returnTo: { type: String, required: false },\n createdAt: { type: Date, required: true, default: Date.now },\n expiresAt: { type: Date, required: true },\n },\n { versionKey: false },\n)\n\nRBOAuthRequestSchema.index({ expiresAt: 1 }, { expireAfterSeconds: 0 })\n","export * from \"./RBUser\"\nexport * from \"./RBTenant\"\nexport * from \"./RBTenantSubscriptionEvent\"\nexport * from \"./RBTenantSubscriptionProjection\"\nexport * from \"./RBRtsCounter\"\nexport * from \"./RBRtsChange\"\nexport * from \"./RBUploadSession\"\nexport * from \"./RBUploadChunk\"\nexport * from \"./RBNotification\"\nexport * from \"./RBNotificationDelivery\"\nexport * from \"./RBNotificationSettings\"\nexport * from \"./RBOAuthRequest\"\n","import { Schema } from \"mongoose\"\n\n\ntype MongooseSchemaExtension = Parameters<Schema[\"add\"]>[0]\n\nexport function extendMongooseSchema<TSchema extends Schema>(\n baseSchema: TSchema,\n ...extensions: MongooseSchemaExtension[]\n): TSchema {\n const schema = baseSchema.clone() as TSchema\n\n extensions.forEach((extension) => schema.add(extension))\n\n return schema\n}\n\nexport function omitMongooseSchemaPaths<TSchema extends Schema>(\n schema: TSchema,\n paths: string[],\n): TSchema {\n const clone = schema.clone() as TSchema\n paths.forEach((path) => clone.remove(path))\n return clone\n}\n","import { Schema } from \"mongoose\"\nimport type { SchemaTypeOptions } from \"mongoose\"\n\nimport type { LocalizedString } from \"../zod/localizedString\"\nimport { withLocalizedStringFallback } from \"../zod/localizedString\"\n\n\nexport function localizedStringField(\n options?: Omit<SchemaTypeOptions<LocalizedString>, \"type\">\n): SchemaTypeOptions<LocalizedString> {\n const userGet = options?.get\n\n return {\n ...options,\n type: Schema.Types.Mixed,\n get: (value: unknown) => withLocalizedStringFallback(userGet ? userGet(value) : value),\n }\n}\n","import mongoose from \"mongoose\"\nimport type { InferSchemaType } from \"mongoose\"\n\n\nconst { Schema, model } = mongoose\n\nexport { Schema, model, mongoose, type InferSchemaType }\nexport * from \"./extendMongooseSchema\"\nexport * from \"./localizedStringField\"\n","export type PaginationErrorCode = \"invalid_pagination\"\n\nexport class PaginationValidationError extends Error {\n readonly code: PaginationErrorCode = \"invalid_pagination\"\n readonly statusCode = 400\n\n constructor(message: string, options?: ErrorOptions) {\n super(message, options)\n this.name = \"PaginationValidationError\"\n }\n}\n\nexport const isPaginationValidationError = (error: unknown): error is PaginationValidationError => {\n if (!error || typeof error !== \"object\") return false\n const anyError = error as Partial<PaginationValidationError>\n return (\n anyError.name === \"PaginationValidationError\" &&\n anyError.code === \"invalid_pagination\" &&\n anyError.statusCode === 400\n )\n}\n","import type { PaginationDirection, PaginationOrder, PaginationSpec } from \"@rpcbase/api\"\n\nimport { PaginationValidationError } from \"./errors\"\n\n\nconst DISALLOWED_MONGO_FIELD_SEGMENTS = new Set([\"__proto__\", \"constructor\", \"prototype\"])\nconst PAGINATION_LIMIT_MAX = 128\nexport type NormalizedPaginationSpec = Omit<PaginationSpec, \"direction\" | \"sort\" | \"limit\"> & {\n direction: PaginationDirection;\n limit: number;\n sort: Array<{\n field: string;\n order: PaginationOrder;\n }>;\n}\n\nexport const normalizePaginationSpec = (\n spec: PaginationSpec,\n options: { maxLimit?: number } = {},\n): NormalizedPaginationSpec => {\n if (!spec || typeof spec !== \"object\") throw new PaginationValidationError(\"Invalid PaginationSpec\")\n\n const limit = normalizeLimit(spec.limit, normalizeMaxLimit(options.maxLimit))\n const direction = spec.direction ?? \"next\"\n if (direction !== \"next\" && direction !== \"prev\") throw new PaginationValidationError(\"Invalid pagination direction\")\n\n if (!Array.isArray(spec.sort) || spec.sort.length === 0) throw new PaginationValidationError(\"Invalid pagination sort\")\n\n const sort: NormalizedPaginationSpec[\"sort\"] = spec.sort.map(({ field, order }) => ({\n field: assertSafeMongoFieldPath(field),\n order: normalizeOrder(order),\n }))\n\n const seenFields = new Set<string>()\n for (const { field } of sort) {\n if (seenFields.has(field)) throw new PaginationValidationError(`Duplicate pagination sort field: ${field}`)\n seenFields.add(field)\n }\n\n const primaryOrder = sort[0]?.order\n\n if (!seenFields.has(\"_id\")) {\n sort.push({ field: \"_id\", order: primaryOrder })\n }\n\n return {\n ...spec,\n limit,\n direction,\n sort,\n }\n}\n\nconst normalizeMaxLimit = (maxLimit: unknown): number => {\n if (maxLimit === undefined) return PAGINATION_LIMIT_MAX\n if (!Number.isSafeInteger(maxLimit) || (maxLimit as number) <= 0) {\n throw new PaginationValidationError(\"Invalid pagination max limit\")\n }\n return maxLimit as number\n}\n\nconst normalizeLimit = (limit: unknown, maxLimit: number): number => {\n if (typeof limit !== \"number\" || !Number.isFinite(limit) || !Number.isInteger(limit) || limit <= 0) {\n throw new PaginationValidationError(\"Invalid pagination limit\")\n }\n if (limit > maxLimit) {\n throw new PaginationValidationError(\"Invalid pagination limit\")\n }\n return limit\n}\n\nconst normalizeOrder = (order: unknown): PaginationOrder => {\n if (order !== \"asc\" && order !== \"desc\") throw new PaginationValidationError(\"Invalid pagination order\")\n return order\n}\n\nconst assertSafeMongoFieldPath = (field: unknown): string => {\n if (typeof field !== \"string\" || field.length === 0) throw new PaginationValidationError(\"Invalid pagination sort field\")\n if (field.startsWith(\"$\")) throw new PaginationValidationError(\"Invalid pagination sort field\")\n\n const parts = field.split(\".\")\n for (const part of parts) {\n if (part.length === 0) throw new PaginationValidationError(\"Invalid pagination sort field\")\n if (DISALLOWED_MONGO_FIELD_SEGMENTS.has(part)) throw new PaginationValidationError(\"Invalid pagination sort field\")\n if (!/^[a-zA-Z0-9_]+$/.test(part)) throw new PaginationValidationError(\"Invalid pagination sort field\")\n }\n\n return field\n}\n","import { createHmac, timingSafeEqual } from \"node:crypto\"\n\nimport { Types } from \"mongoose\"\nimport type { PaginationSpec } from \"@rpcbase/api\"\n\nimport { PaginationValidationError } from \"./errors\"\nimport { normalizePaginationSpec } from \"./normalizeSpec\"\n\n\ntype CursorValue =\n | null\n | string\n | number\n | boolean\n | { $date: string }\n | { $oid: string }\n\ntype CursorPayloadV1 = {\n v: 1;\n values: Record<string, CursorValue>;\n}\n\nexport type PaginationCursorCodecOptions = {\n signingSecret: string | Buffer;\n maxLimit?: number;\n}\n\nexport const encodePaginationCursor = (\n spec: PaginationSpec,\n node: unknown,\n options: PaginationCursorCodecOptions,\n): string => {\n const normalized = normalizePaginationSpec(spec, { maxLimit: options.maxLimit })\n\n const values = Object.create(null) as Record<string, CursorValue>\n for (const { field } of normalized.sort) {\n const value = readFieldValue(node, field)\n if (typeof value === \"undefined\") {\n throw new Error(`Pagination cursor encode failed (missing field: ${field})`)\n }\n values[field] = encodeCursorValue(field, value)\n }\n\n const payload: CursorPayloadV1 = { v: 1, values }\n const payloadB64 = Buffer.from(JSON.stringify(payload), \"utf8\").toString(\"base64url\")\n\n const sigB64 = signCursorPayloadB64(payloadB64, options.signingSecret)\n return `${payloadB64}.${sigB64}`\n}\n\nexport const decodePaginationCursor = (\n spec: PaginationSpec,\n cursor: string,\n options: PaginationCursorCodecOptions,\n): Record<string, unknown> => {\n const normalized = normalizePaginationSpec(spec, { maxLimit: options.maxLimit })\n\n const [payloadB64, sigB64, ...rest] = cursor.split(\".\")\n if (rest.length > 0) throw new PaginationValidationError(\"Invalid pagination cursor format\")\n if (!sigB64) throw new PaginationValidationError(\"Invalid pagination cursor format\")\n verifyCursorSignature(payloadB64, sigB64, options.signingSecret)\n\n const payloadRaw = Buffer.from(payloadB64, \"base64url\").toString(\"utf8\")\n\n let payloadUnknown: unknown\n try {\n payloadUnknown = JSON.parse(payloadRaw)\n } catch {\n throw new PaginationValidationError(\"Invalid pagination cursor payload\")\n }\n\n if (!payloadUnknown || typeof payloadUnknown !== \"object\") throw new PaginationValidationError(\"Invalid pagination cursor payload\")\n const payload = payloadUnknown as Partial<CursorPayloadV1>\n\n if (payload.v !== 1) throw new PaginationValidationError(\"Unsupported pagination cursor version\")\n if (!payload.values || typeof payload.values !== \"object\") throw new PaginationValidationError(\"Invalid pagination cursor payload\")\n\n const decoded = Object.create(null) as Record<string, unknown>\n for (const { field } of normalized.sort) {\n if (!Object.prototype.hasOwnProperty.call(payload.values, field)) {\n throw new PaginationValidationError(`Pagination cursor missing field: ${field}`)\n }\n const encodedValue = (payload.values as Record<string, CursorValue>)[field]\n decoded[field] = decodeCursorValue(field, encodedValue)\n }\n\n return decoded\n}\n\nconst signCursorPayloadB64 = (payloadB64: string, secret: string | Buffer): string => {\n return createHmac(\"sha256\", secret).update(payloadB64, \"utf8\").digest(\"base64url\")\n}\n\nconst verifyCursorSignature = (payloadB64: string, sigB64: string, secret: string | Buffer): void => {\n const expectedSigB64 = signCursorPayloadB64(payloadB64, secret)\n const a = Buffer.from(sigB64, \"utf8\")\n const b = Buffer.from(expectedSigB64, \"utf8\")\n if (a.length !== b.length || !timingSafeEqual(a, b)) {\n throw new PaginationValidationError(\"Invalid pagination cursor signature\")\n }\n}\n\nconst unwrapCursorComparableValue = (value: unknown): unknown => {\n if (value === null || typeof value !== \"object\") return value\n if (value instanceof Date || value instanceof Types.ObjectId) return value\n\n let current: unknown = value\n for (let depth = 0; depth < 4; depth += 1) {\n if (!current || typeof current !== \"object\") return current\n if (current instanceof Date || current instanceof Types.ObjectId) return current\n if (!(\"_id\" in current)) return current\n current = (current as { _id: unknown })._id\n }\n\n return current\n}\n\nconst encodeCursorValue = (field: string, value: unknown): CursorValue => {\n const comparableValue = unwrapCursorComparableValue(value)\n\n if (comparableValue === null) return null\n\n if (field === \"_id\") {\n if (comparableValue instanceof Types.ObjectId) return { $oid: comparableValue.toHexString() }\n if (typeof comparableValue === \"string\") return comparableValue\n throw new Error(\"Pagination cursor encode failed (_id must be an ObjectId or string)\")\n }\n\n if (comparableValue instanceof Date) return { $date: comparableValue.toISOString() }\n\n if (\n typeof comparableValue === \"string\" ||\n typeof comparableValue === \"number\" ||\n typeof comparableValue === \"boolean\"\n ) {\n return comparableValue\n }\n\n if (comparableValue instanceof Types.ObjectId) return { $oid: comparableValue.toHexString() }\n\n throw new Error(`Unsupported pagination cursor value type for field: ${field}`)\n}\n\nconst decodeCursorValue = (field: string, value: CursorValue): unknown => {\n if (value === null) return null\n\n if (typeof value === \"string\") {\n return value\n }\n\n if (typeof value === \"number\" || typeof value === \"boolean\") return value\n\n if (!value || typeof value !== \"object\") throw new PaginationValidationError(`Invalid pagination cursor value for field: ${field}`)\n\n if (\"$date\" in value) {\n if (typeof value.$date !== \"string\") throw new PaginationValidationError(`Invalid pagination cursor date for field: ${field}`)\n const d = new Date(value.$date)\n if (Number.isNaN(d.getTime())) throw new PaginationValidationError(`Invalid pagination cursor date for field: ${field}`)\n return d\n }\n\n if (\"$oid\" in value) {\n if (typeof value.$oid !== \"string\" || !Types.ObjectId.isValid(value.$oid)) {\n throw new PaginationValidationError(`Invalid pagination cursor ObjectId for field: ${field}`)\n }\n return new Types.ObjectId(value.$oid)\n }\n\n throw new PaginationValidationError(`Invalid pagination cursor value for field: ${field}`)\n}\n\nconst readFieldValue = (node: unknown, field: string): unknown => {\n if (!node || typeof node !== \"object\") return undefined\n\n if (\"get\" in node && typeof (node as { get?: unknown }).get === \"function\") {\n return (node as { get: (path: string) => unknown }).get(field)\n }\n\n return field.split(\".\").reduce((acc, key) => {\n if (!acc || typeof acc !== \"object\") return undefined\n return (acc as Record<string, unknown>)[key]\n }, node as unknown)\n}\n","import type { PaginationOrder, PaginationSpec } from \"@rpcbase/api\"\n\nimport type { PaginationCursorCodecOptions } from \"./cursor\"\nimport { decodePaginationCursor } from \"./cursor\"\nimport { PaginationValidationError } from \"./errors\"\nimport type { NormalizedPaginationSpec } from \"./normalizeSpec\"\nimport { normalizePaginationSpec } from \"./normalizeSpec\"\n\n\nexport type CompiledMongoPagination = {\n spec: NormalizedPaginationSpec;\n mongoFilterDelta: Record<string, unknown>;\n mongoSort: Record<string, 1 | -1>;\n mongoLimit: number;\n}\n\nexport type CompileMongoPaginationOptions = {\n cursor: PaginationCursorCodecOptions;\n}\n\nexport const compileMongoPagination = (\n spec: PaginationSpec,\n options: CompileMongoPaginationOptions,\n): CompiledMongoPagination => {\n const normalized = normalizePaginationSpec(spec, { maxLimit: options.cursor.maxLimit })\n\n const mongoLimit = normalized.limit + 1\n const mongoSort = toMongoSort(normalized)\n\n if (normalized.cursor == null) {\n return {\n spec: normalized,\n mongoFilterDelta: {},\n mongoSort,\n mongoLimit,\n }\n }\n\n if (typeof normalized.cursor !== \"string\" || normalized.cursor.length === 0) {\n throw new PaginationValidationError(\"Invalid pagination cursor\")\n }\n\n const cursorValues = decodePaginationCursor(normalized, normalized.cursor, options.cursor)\n const mongoFilterDelta = buildKeysetFilterDelta(normalized, cursorValues)\n\n return {\n spec: normalized,\n mongoFilterDelta,\n mongoSort,\n mongoLimit,\n }\n}\n\nconst toMongoSort = (spec: NormalizedPaginationSpec): Record<string, 1 | -1> => {\n const mongoSort = Object.create(null) as Record<string, 1 | -1>\n for (const { field, order } of spec.sort) {\n const forQueryOrder = spec.direction === \"prev\" ? invertOrder(order) : order\n mongoSort[field] = forQueryOrder === \"asc\" ? 1 : -1\n }\n return mongoSort\n}\n\nconst buildKeysetFilterDelta = (\n spec: NormalizedPaginationSpec,\n cursorValues: Record<string, unknown>,\n): Record<string, unknown> => {\n const branches: Record<string, unknown>[] = []\n\n for (let i = 0; i < spec.sort.length; i++) {\n const current = spec.sort[i]\n if (!current) continue\n\n const and: Record<string, unknown>[] = []\n\n for (let j = 0; j < i; j++) {\n const prev = spec.sort[j]\n if (!prev) continue\n const eq = Object.create(null) as Record<string, unknown>\n eq[prev.field] = cursorValues[prev.field]\n and.push(eq)\n }\n\n const op = getKeysetOp(current.order, spec.direction)\n const cmpOp = Object.create(null) as Record<string, unknown>\n cmpOp[op] = cursorValues[current.field]\n const cmp = Object.create(null) as Record<string, unknown>\n cmp[current.field] = cmpOp\n and.push(cmp)\n\n branches.push(and.length === 1 ? and[0]! : { $and: and })\n }\n\n return { $or: branches }\n}\n\nconst getKeysetOp = (order: PaginationOrder, direction: NormalizedPaginationSpec[\"direction\"]): \"$gt\" | \"$lt\" => {\n if (direction === \"next\") return order === \"asc\" ? \"$gt\" : \"$lt\"\n return order === \"asc\" ? \"$lt\" : \"$gt\"\n}\n\nconst invertOrder = (order: PaginationOrder): PaginationOrder => {\n return order === \"asc\" ? \"desc\" : \"asc\"\n}\n","import type { PaginationResponse } from \"@rpcbase/api\"\n\nimport type { PaginationCursorCodecOptions } from \"./cursor\"\nimport { encodePaginationCursor } from \"./cursor\"\nimport type { CompiledMongoPagination } from \"./compileMongoPagination\"\n\n\nexport type MaterializePaginationOptions = {\n cursor: PaginationCursorCodecOptions;\n includeCursors?: boolean;\n}\n\nexport const materializeMongoPagination = <TNode>(\n compiled: CompiledMongoPagination,\n fetchedNodes: TNode[],\n options: MaterializePaginationOptions,\n): PaginationResponse<TNode> => {\n const limit = compiled.spec.limit\n const hasMore = fetchedNodes.length > limit\n\n const trimmed = fetchedNodes.slice(0, limit)\n const nodes = compiled.spec.direction === \"prev\" ? trimmed.reverse() : trimmed\n\n const hasPrevPage = compiled.spec.direction === \"next\" ? Boolean(compiled.spec.cursor) : hasMore\n const hasNextPage = compiled.spec.direction === \"next\" ? hasMore : Boolean(compiled.spec.cursor)\n\n const pageInfo: PaginationResponse<TNode>[\"pageInfo\"] = {\n hasNextPage,\n hasPrevPage,\n }\n\n if (nodes.length === 0) {\n return { nodes, pageInfo }\n }\n\n if (options.includeCursors !== false && hasPrevPage) {\n pageInfo.prevCursor = encodePaginationCursor(compiled.spec, nodes[0], options.cursor)\n }\n\n if (options.includeCursors !== false && hasNextPage) {\n pageInfo.nextCursor = encodePaginationCursor(compiled.spec, nodes[nodes.length - 1], options.cursor)\n }\n\n return { nodes, pageInfo }\n}\n","import type { CompiledMongoPagination } from \"./compileMongoPagination\"\n\n\ntype MongoQueryLike = {\n where: (delta: Record<string, unknown>) => unknown;\n sort: (sort: Record<string, 1 | -1>) => unknown;\n limit: (limit: number) => unknown;\n}\n\nexport const MongoAdapter = {\n applyPagination: <TQuery extends MongoQueryLike>(query: TQuery, compiled: CompiledMongoPagination): TQuery => {\n query.where(compiled.mongoFilterDelta)\n query.sort(compiled.mongoSort)\n query.limit(compiled.mongoLimit)\n return query\n },\n}\n\n","import type { PaginationResponse, PaginationSpec } from \"@rpcbase/api\"\n\nimport type { PaginationCursorCodecOptions } from \"./cursor\"\nimport { compileMongoPagination } from \"./compileMongoPagination\"\nimport { materializeMongoPagination } from \"./materializePagination\"\nimport { MongoAdapter } from \"./mongoAdapter\"\n\n\ntype MongoPaginateQueryLike<TNode> = {\n where: (delta: Record<string, unknown>) => unknown;\n sort: (sort: Record<string, 1 | -1>) => unknown;\n limit: (limit: number) => unknown;\n exec: () => Promise<TNode[]>;\n}\n\nexport type PaginateMongoQueryOptions = {\n cursor: PaginationCursorCodecOptions;\n includeCursors?: boolean;\n}\n\nexport const paginateMongoQuery = async <TNode>(\n query: MongoPaginateQueryLike<TNode>,\n pagination: PaginationSpec,\n options: PaginateMongoQueryOptions,\n): Promise<PaginationResponse<TNode>> => {\n const compiled = compileMongoPagination(pagination, { cursor: options.cursor })\n\n MongoAdapter.applyPagination(query, compiled)\n\n const fetchedNodes = await query.exec()\n if (!Array.isArray(fetchedNodes)) {\n throw new Error(\"paginateMongoQuery expects query.exec() to return an array\")\n }\n\n return materializeMongoPagination(compiled, fetchedNodes, {\n cursor: options.cursor,\n includeCursors: options.includeCursors,\n })\n}\n","import mongoose from \"mongoose\"\nimport type { PaginationResponse, PaginationSpec } from \"@rpcbase/api\"\n\nimport type { PaginationCursorCodecOptions } from \"./cursor\"\nimport { paginateMongoQuery } from \"./paginateMongoQuery\"\n\n\ndeclare const mongoPaginationPluginBrand: unique symbol\n\n\ntype QueryOptionsLike = Record<string, unknown>\n\nconst getQueryOptions = (query: unknown): QueryOptionsLike | undefined => {\n if (!query || typeof query !== \"object\") return undefined\n if (!(\"getOptions\" in query) || typeof (query as { getOptions?: unknown }).getOptions !== \"function\") return undefined\n return (query as { getOptions: () => QueryOptionsLike }).getOptions()\n}\n\nconst getPaginationFromOptions = (query: unknown): PaginationSpec | undefined => {\n const options = getQueryOptions(query)\n return options?.pagination as PaginationSpec | undefined\n}\n\nconst getCursorFromOptions = (query: unknown): PaginationCursorCodecOptions | undefined => {\n const options = getQueryOptions(query)\n return options?.paginationCursor as PaginationCursorCodecOptions | undefined\n}\n\nexport type MongoPaginationPluginOptions = {\n cursor: PaginationCursorCodecOptions;\n includeCursors?: boolean;\n}\n\ntype QueryResultNode<TResult> = TResult extends Array<infer TNode> ? TNode : unknown\n\ndeclare module \"mongoose\" {\n interface Query<\n ResultType,\n DocType,\n THelpers = {},\n RawDocType = unknown,\n QueryOp = \"find\",\n TDocOverrides = Record<string, never>,\n > {\n [mongoPaginationPluginBrand]?: [DocType, THelpers, RawDocType, QueryOp, TDocOverrides];\n paginate: (\n pagination?: PaginationSpec,\n options?: MongoPaginationPluginOptions,\n ) => Promise<PaginationResponse<QueryResultNode<ResultType>>>;\n }\n}\n\nexport const mongoPaginationPlugin = (schema: mongoose.Schema, pluginOptions?: MongoPaginationPluginOptions): void => {\n ;(schema.query as Record<string, unknown>).paginate = async function(\n this: mongoose.Query<unknown[], unknown>,\n pagination?: PaginationSpec,\n options?: MongoPaginationPluginOptions,\n ): Promise<PaginationResponse<unknown>> {\n const spec = pagination ?? getPaginationFromOptions(this)\n if (!spec) throw new Error(\"Missing pagination spec\")\n\n const cursor = options?.cursor ?? getCursorFromOptions(this) ?? pluginOptions?.cursor\n if (!cursor?.signingSecret) throw new Error(\"Missing pagination cursor signingSecret\")\n\n return await paginateMongoQuery(this, spec, {\n cursor,\n includeCursors: options?.includeCursors ?? pluginOptions?.includeCursors,\n })\n }\n}\n","type MongoDbLike = {\n databaseName?: string\n command: (command: Record<string, unknown>) => Promise<unknown>\n}\n\nexport type SearchTextStageOptions = {\n index: string\n query: string\n path: string | string[]\n highlightPath?: string | string[]\n}\n\nexport type SearchTextStage = {\n $search: {\n index: string\n text: {\n query: string\n path: string | string[]\n }\n highlight?: {\n path: string | string[]\n }\n }\n}\n\nexport const buildSearchTextStage = (options: SearchTextStageOptions): SearchTextStage => {\n const index = options.index.trim()\n if (!index) throw new Error(\"Missing search index name\")\n\n const query = options.query.trim()\n if (!query) throw new Error(\"Missing search query\")\n\n const stage: SearchTextStage = {\n $search: {\n index,\n text: {\n query,\n path: options.path,\n },\n },\n }\n\n if (options.highlightPath) {\n stage.$search.highlight = { path: options.highlightPath }\n }\n\n return stage\n}\n\nexport const searchMetaProjection = () => {\n return {\n score: { $meta: \"searchScore\" },\n highlights: { $meta: \"searchHighlights\" },\n } as const\n}\n\nexport type EnsureSearchIndexParams = {\n db: MongoDbLike\n collection: string\n name: string\n definition: Record<string, unknown>\n}\n\nconst listResultHasIndex = (listResult: unknown, name: string): boolean => {\n if (!listResult || typeof listResult !== \"object\") return false\n if (!(\"cursor\" in listResult)) return false\n const cursor = (listResult as { cursor?: unknown }).cursor\n if (!cursor || typeof cursor !== \"object\") return false\n const firstBatch = (cursor as { firstBatch?: unknown }).firstBatch\n if (!Array.isArray(firstBatch)) return false\n return firstBatch.some((idx) => idx && typeof idx === \"object\" && \"name\" in idx && (idx as { name?: unknown }).name === name)\n}\n\nconst isIndexAlreadyExistsError = (error: unknown): boolean => {\n if (!error || typeof error !== \"object\") return false\n const codeName = \"codeName\" in error ? (error as { codeName?: unknown }).codeName : undefined\n if (codeName === \"IndexAlreadyExists\") return true\n const message = \"message\" in error ? String((error as { message?: unknown }).message ?? \"\") : \"\"\n return /already exists/i.test(message)\n}\n\nexport const ensureSearchIndex = async (params: EnsureSearchIndexParams): Promise<{ created: boolean }> => {\n const collection = params.collection.trim()\n if (!collection) throw new Error(\"Missing collection name\")\n\n const name = params.name.trim()\n if (!name) throw new Error(\"Missing search index name\")\n\n let listResult: unknown\n try {\n listResult = await params.db.command({ listSearchIndexes: collection })\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n throw new Error(`listSearchIndexes failed for \"${collection}\": ${message}`)\n }\n\n if (listResultHasIndex(listResult, name)) {\n return { created: false }\n }\n\n try {\n await params.db.command({\n createSearchIndexes: collection,\n indexes: [{ name, definition: params.definition }],\n })\n } catch (error) {\n if (isIndexAlreadyExistsError(error)) {\n return { created: false }\n }\n const message = error instanceof Error ? error.message : String(error)\n throw new Error(`createSearchIndexes failed for \"${collection}\" (index \"${name}\"): ${message}`)\n }\n\n return { created: true }\n}\n","const getAppName = (env: NodeJS.ProcessEnv = process.env): string => {\n const appName = env.APP_NAME?.trim()\n if (!appName) {\n throw new Error(\"Missing APP_NAME\")\n }\n return appName\n}\n\nexport const GLOBAL_DB_SUFFIX = \"-global-db\"\n\nexport const getGlobalDbName = (env: NodeJS.ProcessEnv = process.env): string => {\n return `${getAppName(env)}${GLOBAL_DB_SUFFIX}`\n}\n\nexport const getTenantDbName = (tenantId: string, env: NodeJS.ProcessEnv = process.env): string => {\n return `${getAppName(env)}-${tenantId.trim()}-db`\n}\n","import mongoose from \"mongoose\"\n\nimport { getMongoDirectConnection, getMongoUrl } from \"./getMongoUrl\"\n\n\nconst connections = new Map<string, mongoose.Connection>()\nlet rootConnection: mongoose.Connection | null = null\nconst CONNECTION_MAX_LISTENERS = 50\n\nconst waitForOpen = async (connection: mongoose.Connection): Promise<void> => {\n if (connection.readyState === 1) return\n if (connection.getMaxListeners() < CONNECTION_MAX_LISTENERS) {\n connection.setMaxListeners(CONNECTION_MAX_LISTENERS)\n }\n\n await new Promise<void>((resolve, reject) => {\n connection.once(\"open\", resolve)\n connection.once(\"error\", reject)\n })\n}\n\nexport const ensureMongooseConnection = async (dbName: string): Promise<mongoose.Connection> => {\n const normalizedDbName = dbName.trim()\n if (!normalizedDbName) {\n throw new Error(\"Missing dbName\")\n }\n\n const existing = connections.get(normalizedDbName)\n if (existing) {\n await waitForOpen(existing)\n return existing\n }\n\n if (!rootConnection) {\n const mongoUrl = getMongoUrl()\n rootConnection = mongoose.createConnection(mongoUrl, {\n sanitizeFilter: true,\n dbName: normalizedDbName,\n directConnection: getMongoDirectConnection(),\n })\n }\n\n await waitForOpen(rootConnection)\n\n const connection = rootConnection.name === normalizedDbName\n ? rootConnection\n : rootConnection.useDb(normalizedDbName, { useCache: true })\n\n await waitForOpen(connection)\n\n connections.set(normalizedDbName, connection)\n return connection\n}\n","import type mongoose from \"mongoose\"\n\nimport { GLOBAL_DB_SUFFIX } from \"./dbNames\"\nimport { RBRtsChangeSchema, type IRBRtsChange } from \"./models/RBRtsChange\"\nimport { RBRtsCounterSchema, type IRBRtsCounter } from \"./models/RBRtsCounter\"\n\n\ntype RtsChangeOp = IRBRtsChange[\"op\"]\n\nconst RTS_COUNTER_ID = \"rts\"\nconst EXCLUDED_MODEL_NAMES = new Set([\"RBRtsChange\", \"RBRtsCounter\"])\n\nconst maxDeleteIdsRaw = process.env.RB_RTS_DELETE_LOG_MAX_IDS ?? \"\"\nconst maxDeleteIds = Number.isFinite(Number(maxDeleteIdsRaw)) ? Math.max(1, Math.floor(Number(maxDeleteIdsRaw))) : 5000\n\ntype DeleteMeta = {\n modelName: string\n ids: string[]\n reset: boolean\n session?: mongoose.ClientSession\n}\n\nconst deleteMetaByQuery = new WeakMap<object, DeleteMeta>()\n\nconst hasToString = (value: unknown): value is { toString: () => string } => {\n if (typeof value !== \"object\" || value === null) return false\n const maybe = value as { toString?: unknown }\n return typeof maybe.toString === \"function\"\n}\n\nconst normalizeId = (id: unknown): string | null => {\n if (!id) return null\n if (typeof id === \"string\") return id\n if (hasToString(id)) return id.toString()\n return null\n}\n\nconst getDbName = (db: unknown): string => {\n if (!db || typeof db !== \"object\") return \"\"\n const maybe = db as { name?: unknown; db?: { databaseName?: unknown } }\n const raw = maybe.name ?? maybe.db?.databaseName\n return typeof raw === \"string\" ? raw : \"\"\n}\n\nconst isGlobalDb = (db: unknown): boolean => getDbName(db).endsWith(GLOBAL_DB_SUFFIX)\n\ntype RtsCounterDoc = IRBRtsCounter\ntype RtsChangeDoc = IRBRtsChange\n\nconst getQuerySession = (query: MongooseQuery): mongoose.ClientSession | undefined => {\n const opts = typeof query.getOptions === \"function\" ? query.getOptions() : undefined\n if (!opts || typeof opts !== \"object\") return undefined\n const session = (opts as { session?: unknown }).session\n if (!session || typeof session !== \"object\") return undefined\n return session as mongoose.ClientSession\n}\n\nconst getRtsModels = (db: mongoose.Connection) => {\n const RtsCounter = (db.models.RBRtsCounter as mongoose.Model<RtsCounterDoc>)\n ?? db.model<RtsCounterDoc>(\"RBRtsCounter\", RBRtsCounterSchema)\n const RtsChange = (db.models.RBRtsChange as mongoose.Model<RtsChangeDoc>)\n ?? db.model<RtsChangeDoc>(\"RBRtsChange\", RBRtsChangeSchema)\n return { RtsCounter, RtsChange }\n}\n\nconst allocateSeqRange = async (\n db: mongoose.Connection,\n count: number,\n session?: mongoose.ClientSession,\n): Promise<{ start: number; end: number }> => {\n const { RtsCounter } = getRtsModels(db)\n const updated = await RtsCounter.findOneAndUpdate(\n { _id: RTS_COUNTER_ID },\n { $inc: { seq: count } },\n { upsert: true, returnDocument: \"after\", setDefaultsOnInsert: true, projection: { seq: 1 }, session },\n ).lean()\n\n const end = Number(updated?.seq ?? 0)\n const start = end - count + 1\n return { start, end }\n}\n\nconst insertChanges = async (\n db: mongoose.Connection,\n changes: Array<{ seq: number; modelName: string; op: RtsChangeOp; docId?: string | null }>,\n session?: mongoose.ClientSession,\n): Promise<void> => {\n if (!changes.length) return\n const { RtsChange } = getRtsModels(db)\n const ts = new Date()\n const docs = changes.map((c) => ({\n seq: c.seq,\n modelName: c.modelName,\n op: c.op,\n docId: c.docId ?? undefined,\n ts,\n }))\n\n if (session) {\n await RtsChange.insertMany(docs, { session })\n return\n }\n\n await RtsChange.insertMany(docs)\n}\n\nconst recordDeleteChanges = async (\n db: mongoose.Connection,\n modelName: string,\n ids: string[],\n session?: mongoose.ClientSession,\n): Promise<void> => {\n const uniqueIds = Array.from(new Set(ids)).filter(Boolean)\n if (!uniqueIds.length) return\n const { start } = await allocateSeqRange(db, uniqueIds.length, session)\n await insertChanges(db, uniqueIds.map((docId, idx) => ({\n seq: start + idx,\n modelName,\n op: \"delete\",\n docId,\n })), session)\n}\n\nconst recordResetModel = async (db: mongoose.Connection, modelName: string, session?: mongoose.ClientSession): Promise<void> => {\n const { start } = await allocateSeqRange(db, 1, session)\n await insertChanges(db, [{ seq: start, modelName, op: \"reset_model\" }], session)\n}\n\ntype MongooseQuery = mongoose.Query<unknown, unknown> & {\n model?: {\n modelName?: string\n db?: unknown\n find: (filter: unknown, projection: unknown) => unknown\n }\n getFilter?: () => unknown\n getQuery?: () => unknown\n getOptions?: () => unknown\n}\n\nconst captureDeleteMeta = async (query: MongooseQuery, mode: \"one\" | \"many\") => {\n const modelName = String(query?.model?.modelName ?? \"\")\n if (!modelName || modelName.startsWith(\"RB\") || EXCLUDED_MODEL_NAMES.has(modelName)) return\n if (isGlobalDb(query?.model?.db)) return\n\n const filter = typeof query.getFilter === \"function\" ? query.getFilter() : query.getQuery?.() ?? {}\n const session = getQuerySession(query)\n const findQuery = query.model.find(filter, { _id: 1 }) as unknown as {\n session?: (s: mongoose.ClientSession) => unknown\n limit: (n: number) => unknown\n lean: () => unknown\n }\n if (session && typeof findQuery.session === \"function\") {\n findQuery.session(session)\n }\n\n findQuery.lean()\n\n if (mode === \"one\") {\n findQuery.limit(1)\n } else {\n findQuery.limit(maxDeleteIds + 1)\n }\n\n const docs = await findQuery\n const ids = Array.isArray(docs)\n ? docs\n .map((d) => normalizeId((d as { _id?: unknown })?._id))\n .filter((id): id is string => Boolean(id))\n : []\n const reset = mode === \"many\" && ids.length > maxDeleteIds\n const trimmedIds = reset ? [] : ids\n\n const meta: DeleteMeta = {\n modelName,\n ids: trimmedIds,\n reset,\n session,\n }\n\n deleteMetaByQuery.set(query, meta)\n}\n\nconst flushDeleteMeta = async (query: MongooseQuery) => {\n const meta = deleteMetaByQuery.get(query)\n deleteMetaByQuery.delete(query)\n if (!meta) return\n\n const db = query?.model?.db as mongoose.Connection | undefined\n if (!db) return\n\n try {\n if (meta.reset) {\n await recordResetModel(db, meta.modelName, meta.session)\n } else {\n await recordDeleteChanges(db, meta.modelName, meta.ids, meta.session)\n }\n } catch {\n return\n }\n}\n\nexport const rtsChangeLogPlugin = (schema: mongoose.Schema): void => {\n schema.pre(\"deleteOne\", { query: true, document: false }, async function(this: MongooseQuery) {\n await captureDeleteMeta(this, \"one\")\n })\n\n schema.pre(\"deleteMany\", { query: true, document: false }, async function(this: MongooseQuery) {\n await captureDeleteMeta(this, \"many\")\n })\n\n schema.post(\"deleteOne\", { query: true, document: false }, async function(this: MongooseQuery) {\n await flushDeleteMeta(this)\n })\n\n schema.post(\"deleteMany\", { query: true, document: false }, async function(this: MongooseQuery) {\n await flushDeleteMeta(this)\n })\n\n schema.post(\"findOneAndDelete\", { query: true, document: false }, async function(this: MongooseQuery, doc: unknown) {\n const modelName = String(this?.model?.modelName ?? \"\")\n if (!modelName || modelName.startsWith(\"RB\") || EXCLUDED_MODEL_NAMES.has(modelName)) return\n\n const db = this?.model?.db as mongoose.Connection | undefined\n if (!db) return\n if (isGlobalDb(db)) return\n\n const docId = normalizeId((doc as { _id?: unknown } | null | undefined)?._id)\n if (!docId) return\n\n try {\n const session = getQuerySession(this)\n await recordDeleteChanges(db, modelName, [docId], session)\n } catch {\n return\n }\n })\n}\n","import mongoose from \"mongoose\"\nimport { accessibleBy } from \"@casl/mongoose\"\n\nimport type { AclAction, AclSubjectType, AppAbility } from \"./types\"\n\n\ntype StoredAcl = {\n ability: AppAbility\n action?: AclAction\n}\n\ntype QueryOptionsLike = Record<string, unknown>\n\ntype PipelineStageLike = Record<string, unknown>\n\nconst isRecord = (value: unknown): value is Record<string, unknown> => Boolean(value) && typeof value === \"object\" && !Array.isArray(value)\n\nconst mergeMongoQuery = (left: unknown, right: Record<string, unknown>): Record<string, unknown> => {\n const leftQuery = isRecord(left) ? left : {}\n if (Object.keys(leftQuery).length === 0) return right\n if (Object.keys(right).length === 0) return leftQuery\n return { $and: [leftQuery, right] }\n}\n\nconst getQueryOptions = (query: unknown): QueryOptionsLike | undefined => {\n if (!query || typeof query !== \"object\") return undefined\n if (!(\"getOptions\" in query) || typeof (query as { getOptions?: unknown }).getOptions !== \"function\") return undefined\n return (query as { getOptions: () => QueryOptionsLike }).getOptions()\n}\n\nconst getStoredAclFromQuery = (query: unknown): StoredAcl | null => {\n const options = getQueryOptions(query)\n const raw = options?.rbAcl\n if (!isRecord(raw)) return null\n if (!(\"ability\" in raw)) return null\n return raw as unknown as StoredAcl\n}\n\nconst getStoredAclFromAggregate = (aggregate: unknown): StoredAcl | null => {\n if (!aggregate || typeof aggregate !== \"object\") return null\n const raw = (aggregate as { options?: unknown }).options\n if (!isRecord(raw)) return null\n const acl = raw.rbAcl\n if (!isRecord(acl)) return null\n if (!(\"ability\" in acl)) return null\n return acl as unknown as StoredAcl\n}\n\nconst addQueryAclFilter = (query: mongoose.Query<unknown, unknown>, action: AclAction): void => {\n const storedAcl = getStoredAclFromQuery(query)\n if (!storedAcl) return\n\n const ability = storedAcl.ability\n const resolvedAction = storedAcl.action ?? action\n const modelName = query.model.modelName\n\n const accessQuery = accessibleBy(ability, resolvedAction).ofType(modelName as AclSubjectType)\n query.and([accessQuery])\n}\n\nconst injectAggregateMatch = (pipeline: PipelineStageLike[], match: Record<string, unknown>): void => {\n if (pipeline.length === 0) {\n pipeline.unshift({ $match: match })\n return\n }\n\n const first = pipeline[0]\n if (!isRecord(first)) {\n pipeline.unshift({ $match: match })\n return\n }\n\n if (\"$geoNear\" in first) {\n const geoNear = first.$geoNear\n if (isRecord(geoNear)) {\n geoNear.query = mergeMongoQuery(geoNear.query, match)\n return\n }\n }\n\n if (\"$search\" in first || \"$vectorSearch\" in first || \"$searchMeta\" in first) {\n pipeline.splice(1, 0, { $match: match })\n return\n }\n\n pipeline.unshift({ $match: match })\n}\n\nconst addAggregateAclFilter = (aggregate: mongoose.Aggregate<unknown>, action: AclAction): void => {\n const storedAcl = getStoredAclFromAggregate(aggregate)\n if (!storedAcl) return\n\n const ability = storedAcl.ability\n const resolvedAction = storedAcl.action ?? action\n const modelName = aggregate.model().modelName\n\n const accessQuery = accessibleBy(ability, resolvedAction).ofType(modelName as AclSubjectType)\n injectAggregateMatch(aggregate.pipeline() as unknown as PipelineStageLike[], accessQuery)\n}\n\nconst patchAggregateAcl = (): void => {\n const globalKey = Symbol.for(\"@rpcbase/db/acl/mongooseAggregateAclPatched\")\n const globalState = globalThis as unknown as Record<string | symbol, unknown>\n if (globalState[globalKey]) return\n globalState[globalKey] = true\n\n const AggregatePrototype = (mongoose.Aggregate as unknown as { prototype: Record<string, unknown> }).prototype\n if (typeof AggregatePrototype.acl === \"function\") return\n\n AggregatePrototype.acl = function(\n this: mongoose.Aggregate<unknown>,\n ability: AppAbility,\n action: AclAction = \"read\",\n ) {\n this.option({ rbAcl: { ability, action } })\n return this\n }\n}\n\nconst createModelAclProxy = <TModel extends mongoose.Model<unknown>>(\n model: TModel,\n ability: AppAbility,\n): TModel => {\n return new Proxy(model, {\n get(target, prop, receiver) {\n if (prop === \"acl\") {\n return () => {\n throw new Error(\n `Model \"${target.modelName}\" is already ACL-scoped. Do not call .acl(...) again.`,\n )\n }\n }\n\n const value = Reflect.get(target, prop, receiver) as unknown\n if (typeof value !== \"function\") return value\n return (...args: unknown[]) => {\n const result = Reflect.apply(value, target, args) as unknown\n if (result && typeof result === \"object\" && \"acl\" in result && typeof (result as { acl?: unknown }).acl === \"function\") {\n return (result as { acl: (ability: AppAbility) => unknown }).acl(ability)\n }\n return result\n }\n },\n }) as unknown as TModel\n}\n\ndeclare const mongooseAclPluginBrand: unique symbol\n\ndeclare module \"mongoose\" {\n interface QueryOptions<DocType = unknown> {\n rbAcl?: StoredAcl;\n [mongooseAclPluginBrand]?: DocType;\n }\n\n interface AggregateOptions {\n rbAcl?: StoredAcl;\n }\n\n interface Query<\n ResultType,\n DocType,\n THelpers = {},\n RawDocType = unknown,\n QueryOp = \"find\",\n TDocOverrides = Record<string, never>,\n > {\n [mongooseAclPluginBrand]?: [ResultType, DocType, THelpers, RawDocType, QueryOp, TDocOverrides];\n acl: (ability: AppAbility, action?: AclAction) => this;\n }\n\n interface Aggregate<ResultType> {\n [mongooseAclPluginBrand]?: ResultType;\n acl: (ability: AppAbility, action?: AclAction) => this;\n }\n\n interface Model<\n TRawDocType,\n TQueryHelpers,\n TInstanceMethods,\n TVirtuals,\n THydratedDocumentType,\n TSchema,\n TLeanResultType,\n > {\n [mongooseAclPluginBrand]?: [TRawDocType, TQueryHelpers, TInstanceMethods, TVirtuals, THydratedDocumentType, TSchema, TLeanResultType];\n acl: (ability: AppAbility) => this;\n }\n}\n\nexport const mongooseAclPlugin = (schema: mongoose.Schema): void => {\n patchAggregateAcl()\n\n ;(schema.query as Record<string, unknown>).acl = function(\n this: mongoose.Query<unknown, unknown>,\n ability: AppAbility,\n action?: AclAction,\n ) {\n this.setOptions({ rbAcl: { ability, action } })\n return this\n }\n\n ;(schema.statics as Record<string, unknown>).acl = function(\n this: mongoose.Model<unknown>,\n ability: AppAbility,\n ) {\n return createModelAclProxy(this, ability)\n }\n\n schema.pre(\"aggregate\", function() {\n addAggregateAclFilter(this, \"read\")\n })\n\n schema.pre(\"countDocuments\", function() {\n addQueryAclFilter(this, \"read\")\n })\n\n schema.pre(\"deleteMany\", function() {\n addQueryAclFilter(this, \"delete\")\n })\n\n schema.pre(\"deleteOne\", function() {\n addQueryAclFilter(this, \"delete\")\n })\n\n schema.pre(\"distinct\", function() {\n addQueryAclFilter(this, \"read\")\n })\n\n schema.pre(\"find\", function() {\n addQueryAclFilter(this, \"read\")\n })\n\n schema.pre(\"findOne\", function() {\n addQueryAclFilter(this, \"read\")\n })\n\n schema.pre(\"findOneAndDelete\", function() {\n addQueryAclFilter(this, \"delete\")\n })\n\n schema.pre(\"findOneAndReplace\", function() {\n addQueryAclFilter(this, \"update\")\n })\n\n schema.pre(\"findOneAndUpdate\", function() {\n addQueryAclFilter(this, \"update\")\n })\n\n schema.pre(\"replaceOne\", function() {\n addQueryAclFilter(this, \"update\")\n })\n\n schema.pre(\"updateMany\", function() {\n addQueryAclFilter(this, \"update\")\n })\n\n schema.pre(\"updateOne\", function() {\n addQueryAclFilter(this, \"update\")\n })\n}\n\nexport const _private = {\n createModelAclProxy,\n injectAggregateMatch,\n mergeMongoQuery,\n}\n","import mongoose from \"mongoose\"\nimport { accessibleRecordsPlugin } from \"@casl/mongoose\"\n\nimport * as frameworkSchemas from \"./models\"\nimport { rtsChangeLogPlugin } from \"./rtsChangeLogPlugin\"\nimport { registerPoliciesFromModules } from \"./acl\"\nimport { mongooseAclPlugin } from \"./acl/mongooseAclPlugin\"\nimport { mongoPaginationPlugin } from \"./pagination/mongoPaginationPlugin\"\n\n\ntype ModelModules = Record<string, unknown>\ntype ModelsScope = \"tenant\" | \"global\"\ntype RegisterModelsOptions = {\n allowReservedRbModelNames?: boolean;\n}\n\ntype RegisteredSchemas = Record<string, mongoose.Schema>\n\ntype RegisteredModels = {\n tenant: RegisteredSchemas\n global: RegisteredSchemas\n}\n\nlet cachedModels: RegisteredModels | null = null\n\nconst DEFAULT_GLOBAL_RB_MODEL_NAMES_SET = new Set<string>([\n \"RBUser\",\n \"RBTenant\",\n \"RBOAuthRequest\",\n])\n\nconst assertSchema = (exportName: string, value: unknown): mongoose.Schema => {\n if (value instanceof mongoose.Schema) return value\n\n throw new Error(\n [\n `Expected ${exportName} to be an instance of mongoose.Schema, but it was not.`,\n \"rpcbase supports mongoose 9+ only.\",\n \"Fix: ensure the project is using mongoose 9.x and that all packages resolve the same mongoose instance (try `npm ls mongoose`).\",\n ].join(\" \"),\n )\n}\n\nconst getFrameworkSchemaForModelName = (modelName: string): mongoose.Schema | null => {\n const exportName = `${modelName}Schema`\n const value = (frameworkSchemas as unknown as Record<string, unknown>)[exportName]\n if (!(value instanceof mongoose.Schema)) return null\n return value\n}\n\nconst applyTenantPlugins = (schema: mongoose.Schema): void => {\n schema.plugin(accessibleRecordsPlugin)\n schema.plugin(mongooseAclPlugin)\n schema.plugin(mongoPaginationPlugin)\n schema.plugin(rtsChangeLogPlugin)\n}\n\nconst registerSchema = (\n target: RegisteredSchemas,\n other: RegisteredSchemas,\n modelName: string,\n schema: mongoose.Schema,\n scope: ModelsScope,\n): void => {\n if (target[modelName] || other[modelName]) {\n throw new Error(`Duplicate model name \"${modelName}\" across tenant/global scopes`)\n }\n target[modelName] = schema\n}\n\nconst buildSchemasFromModules = (modules: ModelModules): Array<{ modelName: string; schema: mongoose.Schema }> =>\n Object.entries(modules)\n .filter(([key]) => key.endsWith(\"Schema\"))\n .map(([key, schemaValue]) => {\n const schema = assertSchema(key, schemaValue)\n const modelName = key.replace(/Schema$/, \"\")\n return { modelName, schema }\n })\n\nexport const registerModels = (\n { tenant, global }: { tenant: ModelModules; global?: ModelModules },\n options: RegisterModelsOptions = {},\n) => {\n registerPoliciesFromModules(frameworkSchemas as unknown as Record<string, unknown>)\n registerPoliciesFromModules(tenant)\n\n const tenantSchemas: RegisteredSchemas = {}\n const globalSchemas: RegisteredSchemas = {}\n const allowReservedRbModelNames = options.allowReservedRbModelNames === true\n\n for (const { modelName, schema } of buildSchemasFromModules(frameworkSchemas as unknown as ModelModules)) {\n if (DEFAULT_GLOBAL_RB_MODEL_NAMES_SET.has(modelName)) {\n const cloned = schema.clone()\n registerSchema(globalSchemas, tenantSchemas, modelName, cloned, \"global\")\n } else {\n const cloned = schema.clone()\n applyTenantPlugins(cloned)\n registerSchema(tenantSchemas, globalSchemas, modelName, cloned, \"tenant\")\n }\n }\n\n for (const { modelName, schema } of buildSchemasFromModules(tenant)) {\n if (modelName === \"RBUser\" || modelName === \"RBTenant\") {\n throw new Error(`Invalid tenant model name \"${modelName}\". RBUser/RBTenant are global models.`)\n }\n if (modelName.startsWith(\"RB\")) {\n const frameworkSchema = getFrameworkSchemaForModelName(modelName)\n if (frameworkSchema && schema === frameworkSchema) continue\n if (!allowReservedRbModelNames) {\n throw new Error(`Invalid tenant model name \"${modelName}\". RB* models are reserved for rpcbase.`)\n }\n }\n const cloned = schema.clone()\n applyTenantPlugins(cloned)\n registerSchema(tenantSchemas, globalSchemas, modelName, cloned, \"tenant\")\n }\n\n for (const { modelName, schema } of buildSchemasFromModules(global ?? {})) {\n if (modelName.startsWith(\"RB\")) {\n const frameworkSchema = getFrameworkSchemaForModelName(modelName)\n if (frameworkSchema && schema === frameworkSchema) continue\n if (!allowReservedRbModelNames) {\n throw new Error(`Invalid global model name \"${modelName}\". RB* models are reserved for rpcbase.`)\n }\n }\n const cloned = schema.clone()\n registerSchema(globalSchemas, tenantSchemas, modelName, cloned, \"global\")\n }\n\n const allSchemas = { ...globalSchemas, ...tenantSchemas }\n\n for (const [modelName, schema] of Object.entries(allSchemas)) {\n if (!mongoose.models[modelName]) {\n mongoose.model(modelName, schema)\n }\n }\n\n cachedModels = {\n tenant: { ...(cachedModels?.tenant ?? {}), ...tenantSchemas },\n global: { ...(cachedModels?.global ?? {}), ...globalSchemas },\n }\n}\n\nexport const getRegisteredModels = (scope: ModelsScope) => {\n if (!cachedModels) {\n throw new Error(\"Models not registered. Call createModels(...) once at startup (or import your models module) before using models.get.\")\n }\n return cachedModels[scope]\n}\n\nexport type { ModelModules, ModelsScope, RegisterModelsOptions }\n","import assert from \"assert\"\n\nimport { getGlobalDbName, getTenantDbName } from \"./dbNames\"\nimport { ensureMongooseConnection } from \"./ensureMongooseConnection\"\nimport { getRegisteredModels, registerModels, type ModelsScope } from \"./registerModels\"\nimport { hasRegisteredPolicy, type AppAbility } from \"./acl\"\n\n\nexport type LoadModelCtx = {\n tenantId?: string;\n req?: {\n session?: {\n user?: {\n currentTenantId?: string;\n }\n } | null;\n };\n ability?: AppAbility;\n};\n\nconst loadModelFromDb = async (\n modelName: string,\n dbName: string,\n scope: ModelsScope,\n) => {\n const schemas = getRegisteredModels(scope)\n const schema = schemas[modelName]\n assert(schema, `Model ${modelName} not registered. Available models: ${Object.keys(schemas).join(\", \")}`)\n\n const modelConnection = await ensureMongooseConnection(dbName)\n\n if (!modelConnection.models[modelName]) {\n modelConnection.model(modelName, schema)\n }\n\n return modelConnection.models[modelName]\n}\n\nconst normalizeTenantId = (value: unknown): string | null => {\n if (typeof value !== \"string\") return null\n const tenantId = value.trim()\n return tenantId || null\n}\n\nexport const getTenantIdFromLoadModelCtx = (ctx: LoadModelCtx): string => {\n const tenantId =\n normalizeTenantId(ctx.tenantId)\n ?? normalizeTenantId(ctx.req?.session?.user?.currentTenantId)\n assert(tenantId, \"Tenant ID is missing from ctx (expected ctx.tenantId or ctx.req.session.user.currentTenantId)\")\n return tenantId\n}\n\nexport const models = {\n register: registerModels,\n\n getUnsafe: async (modelName: string, ctx: LoadModelCtx) => {\n const tenantId = getTenantIdFromLoadModelCtx(ctx)\n const dbName = getTenantDbName(tenantId)\n return loadModelFromDb(modelName, dbName, \"tenant\")\n },\n\n get: async (modelName: string, ctx: LoadModelCtx) => {\n const model = await models.getUnsafe(modelName, ctx)\n const resolvedAbility = ctx.ability\n\n const isProtected = hasRegisteredPolicy(modelName)\n if (!isProtected) {\n return model\n }\n\n if (!resolvedAbility) {\n throw new Error(\n `Model \"${modelName}\" is ACL-protected. Set ctx.ability or use models.getUnsafe(...) explicitly.`,\n )\n }\n\n if (typeof (model as { acl?: unknown }).acl !== \"function\") return model\n return (model as { acl: (appAbility: AppAbility) => typeof model }).acl(resolvedAbility)\n },\n\n getGlobal: async (modelName: string, ctx: LoadModelCtx) => {\n const dbName = getGlobalDbName()\n return loadModelFromDb(modelName, dbName, \"global\")\n },\n} as const\n","import type { LoadModelCtx } from \"./modelsApi\"\nimport type { ModelModules, RegisterModelsOptions } from \"./registerModels\"\nimport type * as frameworkSchemas from \"./models\"\nimport { models } from \"./modelsApi\"\nimport { registerModels } from \"./registerModels\"\n\n\ntype ExtractModelNamesFromSchemas<TModules> = {\n [K in keyof TModules]-?: K extends `${infer Name}Schema` ? Name : never\n}[keyof TModules] & string\n\ntype FrameworkModelName = ExtractModelNamesFromSchemas<typeof frameworkSchemas>\n\ntype RpcbaseGlobalModelName = Extract<FrameworkModelName, \"RBUser\" | \"RBTenant\" | \"RBOAuthRequest\">\n\nexport type TenantModelName<TTenantModules extends ModelModules> =\n ExtractModelNamesFromSchemas<TTenantModules>\n\nexport type GlobalModelName<TGlobalModules extends ModelModules> =\n | RpcbaseGlobalModelName\n | ExtractModelNamesFromSchemas<TGlobalModules>\n\ntype LoadedTenantModel = Awaited<ReturnType<(typeof models)[\"get\"]>>\ntype LoadedGlobalModel = Awaited<ReturnType<(typeof models)[\"getGlobal\"]>>\n\ntype ModelsGetFn<TTenantModules extends ModelModules> = {\n (\n modelName: TenantModelName<TTenantModules>,\n ctx: LoadModelCtx,\n ): ReturnType<(typeof models)[\"get\"]>\n <const TNames extends readonly TenantModelName<TTenantModules>[]>(\n modelNames: TNames,\n ctx: LoadModelCtx,\n ): Promise<{ [K in keyof TNames]: LoadedTenantModel }>\n}\n\ntype ModelsGetUnsafeFn<TTenantModules extends ModelModules> = {\n (modelName: TenantModelName<TTenantModules>, ctx: LoadModelCtx): ReturnType<(typeof models)[\"getUnsafe\"]>\n <const TNames extends readonly TenantModelName<TTenantModules>[]>(\n modelNames: TNames,\n ctx: LoadModelCtx,\n ): Promise<{ [K in keyof TNames]: LoadedTenantModel }>\n}\n\ntype ModelsGetGlobalFn<TGlobalModules extends ModelModules> = {\n (modelName: GlobalModelName<TGlobalModules>, ctx: LoadModelCtx): ReturnType<(typeof models)[\"getGlobal\"]>\n <const TNames extends readonly GlobalModelName<TGlobalModules>[]>(\n modelNames: TNames,\n ctx: LoadModelCtx,\n ): Promise<{ [K in keyof TNames]: LoadedGlobalModel }>\n}\n\nexport type ModelsConfig<TTenantModules extends ModelModules, TGlobalModules extends ModelModules> = {\n tenant: TTenantModules\n global?: TGlobalModules\n}\n\nexport type ModelsClient<TTenantModules extends ModelModules, TGlobalModules extends ModelModules> = {\n register: (modules: ModelsConfig<TTenantModules, TGlobalModules>, options?: RegisterModelsOptions) => void\n get: ModelsGetFn<TTenantModules>\n getUnsafe: ModelsGetUnsafeFn<TTenantModules>\n getGlobal: ModelsGetGlobalFn<TGlobalModules>\n}\n\nexport const createModels = <\n TTenantModules extends ModelModules,\n TGlobalModules extends ModelModules = Record<string, never>,\n>(\n modules: ModelsConfig<TTenantModules, TGlobalModules>,\n options?: RegisterModelsOptions,\n ): ModelsClient<TTenantModules, TGlobalModules> => {\n registerModels(modules, options)\n\n const get = (async (\n modelNameOrNames: TenantModelName<TTenantModules> | readonly TenantModelName<TTenantModules>[],\n ctx: LoadModelCtx,\n ) => {\n if (Array.isArray(modelNameOrNames)) {\n return Promise.all(modelNameOrNames.map((modelName) => models.get(modelName as string, ctx)))\n }\n return models.get(modelNameOrNames as string, ctx)\n }) as ModelsClient<TTenantModules, TGlobalModules>[\"get\"]\n\n const getUnsafe = (async (\n modelNameOrNames: TenantModelName<TTenantModules> | readonly TenantModelName<TTenantModules>[],\n ctx: LoadModelCtx,\n ) => {\n if (Array.isArray(modelNameOrNames)) {\n return Promise.all(modelNameOrNames.map((modelName) => models.getUnsafe(modelName as string, ctx)))\n }\n return models.getUnsafe(modelNameOrNames as string, ctx)\n }) as ModelsClient<TTenantModules, TGlobalModules>[\"getUnsafe\"]\n\n const getGlobal = (async (\n modelNameOrNames: GlobalModelName<TGlobalModules> | readonly GlobalModelName<TGlobalModules>[],\n ctx: LoadModelCtx,\n ) => {\n if (Array.isArray(modelNameOrNames)) {\n return Promise.all(modelNameOrNames.map((modelName) => models.getGlobal(modelName as string, ctx)))\n }\n return models.getGlobal(modelNameOrNames as string, ctx)\n }) as ModelsClient<TTenantModules, TGlobalModules>[\"getGlobal\"]\n\n return {\n register: (nextModules, nextOptions) => registerModels(nextModules, nextOptions),\n get,\n getUnsafe,\n getGlobal,\n }\n}\n","import assert from \"assert\"\n\nimport type mongoose from \"mongoose\"\n\nimport { ensureMongooseConnection } from \"./ensureMongooseConnection\"\nimport { getTenantIdFromLoadModelCtx, type LoadModelCtx } from \"./modelsApi\"\n\n\nconst getAppName = (): string => {\n const appName = process.env.APP_NAME?.trim()\n assert(appName, \"Missing APP_NAME\")\n return appName\n}\n\nconst normalizeTenantId = (tenantId: string): string => {\n const normalized = tenantId.trim()\n assert(normalized, \"Tenant ID is missing\")\n return normalized\n}\n\nexport const getTenantFilesystemDbName = (tenantId: string): string =>\n `${getAppName()}-${normalizeTenantId(tenantId)}-filesystem-db`\n\nexport const getTenantFilesystemDb = async (tenantId: string): Promise<mongoose.Connection> =>\n ensureMongooseConnection(getTenantFilesystemDbName(tenantId))\n\nexport const getTenantFilesystemDbFromCtx = async (ctx: LoadModelCtx): Promise<mongoose.Connection> => {\n const tenantId = getTenantIdFromLoadModelCtx(ctx)\n return getTenantFilesystemDb(tenantId)\n}\n","import type mongoose from \"mongoose\"\nimport type { ClientSession } from \"mongoose\"\n\nimport { getGlobalDbName, getTenantDbName } from \"./dbNames\"\nimport { ensureMongooseConnection } from \"./ensureMongooseConnection\"\nimport { getTenantIdFromLoadModelCtx, type LoadModelCtx } from \"./modelsApi\"\nimport { getTenantFilesystemDbName } from \"./tenantFilesystemDb\"\n\n\ntype MongooseTransactionOptions = Parameters<ClientSession[\"withTransaction\"]>[1]\n\nexport type TenantGlobalFilesystemTransactionCtx = {\n tenantId: string\n session: ClientSession\n ctx: {\n tenant: LoadModelCtx\n global: LoadModelCtx\n }\n db: {\n tenant: mongoose.Connection\n global: mongoose.Connection\n filesystem: mongoose.Connection\n }\n}\n\ntype WithTransactionScope =\n | string\n | { tenantId: string }\n | { ctx: LoadModelCtx }\n\nconst buildTenantLoadModelCtx = (tenantId: string): LoadModelCtx => ({\n req: {\n session: {\n user: {\n currentTenantId: tenantId,\n },\n },\n },\n})\n\nexport function withTransaction<T>(\n tenantId: string,\n fn: (ctx: TenantGlobalFilesystemTransactionCtx) => Promise<T>,\n options?: MongooseTransactionOptions,\n): Promise<T>\nexport function withTransaction<T>(\n scope: { tenantId: string } | { ctx: LoadModelCtx },\n fn: (ctx: TenantGlobalFilesystemTransactionCtx) => Promise<T>,\n options?: MongooseTransactionOptions,\n): Promise<T>\nexport async function withTransaction<T>(\n scope: WithTransactionScope,\n fn: (ctx: TenantGlobalFilesystemTransactionCtx) => Promise<T>,\n options?: MongooseTransactionOptions,\n): Promise<T> {\n const normalizedTenantId = (() => {\n if (typeof scope === \"string\") return scope.trim()\n if (\"tenantId\" in scope) return scope.tenantId.trim()\n return getTenantIdFromLoadModelCtx(scope.ctx)\n })()\n\n if (!normalizedTenantId) throw new Error(\"Tenant ID is missing\")\n\n const tenantDbName = getTenantDbName(normalizedTenantId)\n const globalDbName = getGlobalDbName()\n const filesystemDbName = getTenantFilesystemDbName(normalizedTenantId)\n\n const tenantDb = await ensureMongooseConnection(tenantDbName)\n const globalDb = await ensureMongooseConnection(globalDbName)\n const filesystemDb = await ensureMongooseConnection(filesystemDbName)\n\n const session = await tenantDb.startSession()\n\n const tenantCtx: LoadModelCtx = typeof scope === \"object\" && \"ctx\" in scope\n ? scope.ctx\n : buildTenantLoadModelCtx(normalizedTenantId)\n\n const globalCtx: LoadModelCtx = { req: { session: null } }\n\n try {\n return await session.withTransaction(async () => fn({\n tenantId: normalizedTenantId,\n session,\n ctx: {\n tenant: tenantCtx,\n global: globalCtx,\n },\n db: {\n tenant: tenantDb,\n global: globalDb,\n filesystem: filesystemDb,\n },\n }), options)\n } finally {\n await session.endSession()\n }\n}\n","import type { ClientSession } from \"mongoose\"\nimport type {\n BillingStorage,\n BillingStorageTransaction,\n PersistedSubscriptionEvent,\n StoredSubscriptionProjection,\n SubscriptionEvent,\n} from \"@rpcbase/billing\"\n\nimport { ZRBTenantSubscriptionEvent } from \"./models/RBTenantSubscriptionEvent\"\nimport type { LoadModelCtx } from \"./modelsApi\"\nimport { models } from \"./modelsApi\"\nimport { withTransaction } from \"./transactions\"\n\n\ntype MongoBillingTransaction = {\n session: ClientSession\n}\n\ntype SubscriptionEventDocument = Record<string, unknown> & {\n _id?: unknown\n}\n\nconst getTransactionSession = (transaction?: BillingStorageTransaction): ClientSession | undefined => {\n if (!transaction || typeof transaction !== \"object\" || !(\"session\" in transaction)) return undefined\n return (transaction as MongoBillingTransaction).session\n}\n\nconst toSubscriptionEvent = (document: SubscriptionEventDocument): PersistedSubscriptionEvent => {\n const parsed = ZRBTenantSubscriptionEvent.parse(document)\n if (!document._id) throw new Error(\"Persisted subscription event is missing its id\")\n return {\n ...parsed,\n id: String(document._id),\n }\n}\n\nconst getExistingEventQuery = (event: SubscriptionEvent, tenantId: string): Record<string, unknown> => ({\n tenantId,\n idempotencyKey: event.idempotencyKey,\n})\n\nconst isDuplicateKeyError = (error: unknown): boolean =>\n Boolean(error && typeof error === \"object\" && \"code\" in error && error.code === 11000)\n\nconst toProjectionDocument = (projection: StoredSubscriptionProjection): Record<string, unknown> => ({\n tenantId: projection.tenantId,\n subscriptionId: projection.subscriptionId,\n type: projection.type,\n parentSubscriptionId: projection.parentSubscriptionId ?? undefined,\n scope: projection.scope,\n scopeId: projection.scopeId ?? undefined,\n planKey: projection.planKey,\n priceId: projection.priceId ?? undefined,\n status: projection.status,\n intervalUnit: projection.intervalUnit,\n intervalCount: projection.intervalCount,\n modules: projection.modules,\n billingAnchor: projection.billingAnchor,\n currentPeriodStart: projection.currentPeriodStart,\n currentPeriodEnd: projection.currentPeriodEnd,\n cancelAtPeriodEnd: projection.cancelAtPeriodEnd,\n cancelAt: projection.cancelAt ?? undefined,\n canceledAt: projection.canceledAt ?? undefined,\n scheduledPlanKey: projection.scheduledPlan?.planKey,\n scheduledPlanEffectiveAt: projection.scheduledPlan?.effectiveAt,\n provider: projection.provider ?? undefined,\n latestEventId: projection.latestEventId,\n latestEventAt: projection.latestEventAt,\n projectedAt: projection.projectedAt,\n})\n\nexport const createTenantBillingStorage = (params: {\n ctx: LoadModelCtx\n tenantId: string\n}): BillingStorage => {\n const findExistingEvent = async (\n query: Record<string, unknown>,\n transaction?: BillingStorageTransaction,\n ): Promise<PersistedSubscriptionEvent | null> => {\n const EventModel = await models.get(\"RBTenantSubscriptionEvent\", params.ctx)\n const request = EventModel.findOne(query)\n const session = getTransactionSession(transaction)\n if (session) request.session(session)\n const document = await request.lean() as SubscriptionEventDocument | null\n return document ? toSubscriptionEvent(document) : null\n }\n\n return {\n runInTransaction: (operation) => withTransaction(\n { ctx: params.ctx },\n ({ session }) => operation({ session } satisfies MongoBillingTransaction),\n ),\n createEvent: async (event, transaction) => {\n if (event.tenantId !== params.tenantId) {\n throw new Error(\"Billing event tenantId does not match the storage tenant\")\n }\n const existingQuery = getExistingEventQuery(event, params.tenantId)\n const existing = await findExistingEvent(existingQuery, transaction)\n if (existing) return existing\n\n const EventModel = await models.get(\"RBTenantSubscriptionEvent\", params.ctx)\n const eventDocument = ZRBTenantSubscriptionEvent.parse(event)\n const session = getTransactionSession(transaction)\n\n try {\n const documents = await EventModel.create([eventDocument], session ? { session } : undefined)\n const document = documents[0]?.toObject() as SubscriptionEventDocument | undefined\n if (!document) throw new Error(\"Subscription event was not persisted\")\n return toSubscriptionEvent(document)\n } catch (error) {\n if (!isDuplicateKeyError(error)) throw error\n const duplicate = await findExistingEvent(existingQuery, transaction)\n if (!duplicate) throw error\n return duplicate\n }\n },\n listEvents: async (tenantId, subscriptionId, transaction) => {\n if (tenantId !== params.tenantId) throw new Error(\"Billing storage tenant mismatch\")\n const EventModel = await models.get(\"RBTenantSubscriptionEvent\", params.ctx)\n const request = EventModel.find({ tenantId, subscriptionId })\n .sort({ effectiveAt: 1, occurredAt: 1, _id: 1 })\n const session = getTransactionSession(transaction)\n if (session) request.session(session)\n const documents = await request.lean() as SubscriptionEventDocument[]\n return documents.map(toSubscriptionEvent)\n },\n upsertProjection: async (projection, transaction) => {\n if (projection.tenantId !== params.tenantId) throw new Error(\"Billing projection tenant mismatch\")\n const ProjectionModel = await models.get(\"RBTenantSubscriptionProjection\", params.ctx)\n const session = getTransactionSession(transaction)\n await ProjectionModel.replaceOne(\n {\n tenantId: params.tenantId,\n subscriptionId: projection.subscriptionId,\n },\n toProjectionDocument(projection),\n {\n upsert: true,\n runValidators: true,\n ...(session ? { session } : {}),\n },\n )\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAIA,IAAaE,UAAUD,IAAEE,OAAO;CAC9BC,OAAOH,IAAEI,OAAO,CAAC,CAACD,MAAM,CAAC,CAACE,SAAS;CACnCC,UAAUN,IAAEI,OAAO;CACnBG,MAAMP,IAAEI,OAAO,CAAC,CAACC,SAAS;CAC1BG,OAAOR,IAAEI,OAAO,CAAC,CAACC,SAAS;CAC3BI,SAAST,IAAEU,MAAMV,IAAEI,OAAO,CAAC;CAC3BO,aAAaX,IAAEY,OAAOZ,IAAEI,OAAO,GAAGJ,IAAEU,MAAMV,IAAEI,OAAO,CAAC,CAAC,CAAC,CAACC,SAAS;CAChEQ,gBAAgBb,IAAEY,OAAOZ,IAAEI,OAAO,GAAGJ,IAAEE,OAAO;EAC5CY,SAASd,IAAEI,OAAO;EAClBD,OAAOH,IAAEI,OAAO,CAAC,CAACD,MAAM,CAAC,CAACE,SAAS;EACnCE,MAAMP,IAAEI,OAAO,CAAC,CAACC,SAAS;EAC1BU,aAAaf,IAAEI,OAAO,CAAC,CAACC,SAAS;EACjCW,cAAchB,IAAEI,OAAO,CAAC,CAACC,SAAS;EAClCY,SAASjB,IAAEI,OAAO,CAAC,CAACC,SAAS;EAC7Ba,OAAOlB,IAAEI,OAAO,CAAC,CAACC,SAAS;EAC3Bc,WAAWnB,IAAEI,OAAO,CAAC,CAACC,SAAS;EAC/Be,WAAWpB,IAAEqB,KAAK,CAAC,CAAChB,SAAS;EAC7BiB,aAAatB,IAAEuB,QAAQ,CAAC,CAAClB,SAAS;EAClCmB,WAAWxB,IAAEqB,KAAK,CAAC,CAAChB,SAAS;EAC7BoB,WAAWzB,IAAEqB,KAAK,CA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AQ;IACRC,eAAe;IACf,GAAI/E,UAAU,EAAEA,QAAQ,IAAI,CAAC;GAC/B,CACF;EACF;CACF;AACF"}
|
|
@@ -7,6 +7,18 @@ export declare const ZRBUploadSessionStatus: z.ZodEnum<{
|
|
|
7
7
|
uploading: "uploading";
|
|
8
8
|
assembling: "assembling";
|
|
9
9
|
}>;
|
|
10
|
+
export declare const ZRBUploadAccessScope: z.ZodEnum<{
|
|
11
|
+
owner: "owner";
|
|
12
|
+
tenant: "tenant";
|
|
13
|
+
public: "public";
|
|
14
|
+
}>;
|
|
15
|
+
export declare const ZRBUploadDeduplication: z.ZodObject<{
|
|
16
|
+
namespace: z.ZodString;
|
|
17
|
+
algorithm: z.ZodLiteral<"sha256">;
|
|
18
|
+
hash: z.ZodString;
|
|
19
|
+
key: z.ZodString;
|
|
20
|
+
pipelineVersion: z.ZodNumber;
|
|
21
|
+
}, z.core.$strip>;
|
|
10
22
|
export declare const ZRBUploadSession: z.ZodObject<{
|
|
11
23
|
_id: z.ZodString;
|
|
12
24
|
userId: z.ZodOptional<z.ZodString>;
|
|
@@ -26,6 +38,19 @@ export declare const ZRBUploadSession: z.ZodObject<{
|
|
|
26
38
|
expiresAt: z.ZodDate;
|
|
27
39
|
fileId: z.ZodOptional<z.ZodString>;
|
|
28
40
|
isPublic: z.ZodOptional<z.ZodBoolean>;
|
|
41
|
+
accessScope: z.ZodOptional<z.ZodEnum<{
|
|
42
|
+
owner: "owner";
|
|
43
|
+
tenant: "tenant";
|
|
44
|
+
public: "public";
|
|
45
|
+
}>>;
|
|
46
|
+
deduplication: z.ZodOptional<z.ZodObject<{
|
|
47
|
+
namespace: z.ZodString;
|
|
48
|
+
algorithm: z.ZodLiteral<"sha256">;
|
|
49
|
+
hash: z.ZodString;
|
|
50
|
+
key: z.ZodString;
|
|
51
|
+
pipelineVersion: z.ZodNumber;
|
|
52
|
+
}, z.core.$strip>>;
|
|
53
|
+
deduplicated: z.ZodOptional<z.ZodBoolean>;
|
|
29
54
|
error: z.ZodOptional<z.ZodString>;
|
|
30
55
|
}, z.core.$strip>;
|
|
31
56
|
export type IRBUploadSession = z.infer<typeof ZRBUploadSession>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"RBUploadSession.d.ts","sourceRoot":"","sources":["../../src/models/RBUploadSession.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,UAAU,CAAA;AACjC,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAA;AAEvB,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,QAAQ,CAAA;AAGvC,eAAO,MAAM,sBAAsB;;;;;EAAuD,CAAA;
|
|
1
|
+
{"version":3,"file":"RBUploadSession.d.ts","sourceRoot":"","sources":["../../src/models/RBUploadSession.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,UAAU,CAAA;AACjC,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAA;AAEvB,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,QAAQ,CAAA;AAGvC,eAAO,MAAM,sBAAsB;;;;;EAAuD,CAAA;AAC1F,eAAO,MAAM,oBAAoB;;;;EAAwC,CAAA;AAEzE,eAAO,MAAM,sBAAsB;;;;;;iBAMjC,CAAA;AAEF,eAAO,MAAM,gBAAgB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAkB3B,CAAA;AAEF,MAAM,MAAM,gBAAgB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,gBAAgB,CAAC,CAAA;AAE/D,eAAO,MAAM,qBAAqB,EAAE,MAmCnC,CAAA;AAID,eAAO,MAAM,qBAAqB,EAAE,SAkBnC,CAAA"}
|