@rpcbase/server 0.594.0 → 0.595.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/convertHeifToWebp-BT1n72DQ.js +148 -0
- package/dist/convertHeifToWebp-BT1n72DQ.js.map +1 -0
- package/dist/email-Co1GNjlT.js +7204 -0
- package/dist/email-Co1GNjlT.js.map +1 -0
- package/dist/handler-BqlcQ9sE.js +245 -0
- package/dist/handler-BqlcQ9sE.js.map +1 -0
- package/dist/handler-C92_gJkX.js +743 -0
- package/dist/handler-C92_gJkX.js.map +1 -0
- package/dist/handler-CapJTGzc.js +795 -0
- package/dist/handler-CapJTGzc.js.map +1 -0
- package/dist/handler-Fk-5fOSm.js +119 -0
- package/dist/handler-Fk-5fOSm.js.map +1 -0
- package/dist/htmlTemplate.d.ts +16 -0
- package/dist/htmlTemplate.d.ts.map +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +5140 -5286
- package/dist/index.js.map +1 -1
- package/dist/notifications.js +273 -382
- package/dist/notifications.js.map +1 -1
- package/dist/postProcessors-iffHvje4.js +89 -0
- package/dist/postProcessors-iffHvje4.js.map +1 -0
- package/dist/queryWindow-DP8zD0lb.js +555 -0
- package/dist/queryWindow-DP8zD0lb.js.map +1 -0
- package/dist/render_resend-B1SSQ4f7.js +7 -0
- package/dist/render_resend-B1SSQ4f7.js.map +1 -0
- package/dist/rts/index.js +990 -1207
- package/dist/rts/index.js.map +1 -1
- package/dist/schemas-B2fUvgYo.js +4151 -0
- package/dist/schemas-B2fUvgYo.js.map +1 -0
- package/dist/shared-DfrVDSp0.js +79 -0
- package/dist/shared-DfrVDSp0.js.map +1 -0
- package/dist/ssrMiddleware.d.ts +7 -3
- package/dist/ssrMiddleware.d.ts.map +1 -1
- package/dist/uploads/worker.js +139 -168
- package/dist/uploads/worker.js.map +1 -1
- package/dist/uploads.js +12 -22
- package/dist/uploads.js.map +1 -1
- package/package.json +1 -1
- package/dist/convertHeifToWebp-C-DGXZ2k.js +0 -169
- package/dist/convertHeifToWebp-C-DGXZ2k.js.map +0 -1
- package/dist/email-BCf24GmK.js +0 -8071
- package/dist/email-BCf24GmK.js.map +0 -1
- package/dist/handler-BqoKvylN.js +0 -147
- package/dist/handler-BqoKvylN.js.map +0 -1
- package/dist/handler-CUOJ51-w.js +0 -903
- package/dist/handler-CUOJ51-w.js.map +0 -1
- package/dist/handler-D-XdgeG_.js +0 -986
- package/dist/handler-D-XdgeG_.js.map +0 -1
- package/dist/handler-F0gFTzvh.js +0 -275
- package/dist/handler-F0gFTzvh.js.map +0 -1
- package/dist/postProcessors-D27fGZP0.js +0 -107
- package/dist/postProcessors-D27fGZP0.js.map +0 -1
- package/dist/queryWindow-Cdr7K-S1.js +0 -714
- package/dist/queryWindow-Cdr7K-S1.js.map +0 -1
- package/dist/render_resend_false-MiC__Smr.js +0 -6
- package/dist/render_resend_false-MiC__Smr.js.map +0 -1
- package/dist/schemas-Drf83ni9.js +0 -4517
- package/dist/schemas-Drf83ni9.js.map +0 -1
- package/dist/shared-CJrm9Wjp.js +0 -104
- package/dist/shared-CJrm9Wjp.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"notifications.js","sources":["../src/notifications/routes.ts","../src/notifications/createNotification.ts","../src/notifications/digest.ts"],"sourcesContent":["export const routes = Object.entries({\n ...import.meta.glob(\"./api/**/handler.ts\"),\n}).reduce<Record<string, unknown>>((acc, [path, mod]) => {\n acc[path.replace(\"./api/\", \"@rpcbase/server/notifications/api/\")] = mod\n return acc\n}, {})\n\n","import { randomUUID } from \"node:crypto\"\n\nimport type { Ctx } from \"@rpcbase/api\"\nimport { models, type IRBNotificationPlatformPayload } from \"@rpcbase/db\"\nimport type { AppAbility } from \"@rpcbase/db/acl\"\n\n\nexport type NotificationDataPayload = Record<string, string>\nexport type NotificationMetadataPayload = Record<string, unknown>\nexport type NotificationPlatformPayload = IRBNotificationPlatformPayload\nexport type NotificationUrlMode = \"navigate\" | \"merge_current_search\"\n\nexport type CreateNotificationInput = {\n userId: string\n topic?: string\n tag?: string\n title: string\n body?: string\n image?: string\n url?: string\n urlMode?: NotificationUrlMode\n metadata?: NotificationMetadataPayload\n data?: NotificationDataPayload\n platform?: NotificationPlatformPayload\n}\n\nexport type CreateNotificationForUserInput = Omit<CreateNotificationInput, \"userId\">\n\nexport type CreateNotificationsForUserInput = {\n userId: string\n notifications: CreateNotificationForUserInput[]\n}\n\nconst normalizeRequiredString = (value: unknown, name: string): string => {\n const normalized = typeof value === \"string\" ? value.trim() : \"\"\n if (!normalized) {\n throw new Error(`${name} is required`)\n }\n return normalized\n}\n\nconst normalizeOptionalString = (value: string | undefined): string | undefined => {\n const normalized = typeof value === \"string\" ? value.trim() : \"\"\n return normalized || undefined\n}\n\nconst normalizeUrlMode = (value: unknown): NotificationUrlMode => {\n return value === \"merge_current_search\" ? \"merge_current_search\" : \"navigate\"\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n Boolean(value) && typeof value === \"object\" && !Array.isArray(value)\n\nconst toNotificationDataString = (value: unknown): string | undefined => {\n if (typeof value === \"string\") {\n const trimmed = value.trim()\n return trimmed || undefined\n }\n if (typeof value === \"number\" && Number.isFinite(value)) return String(value)\n if (typeof value === \"boolean\") return String(value)\n if (typeof value === \"bigint\") return value.toString()\n if (value instanceof Date && Number.isFinite(value.getTime())) return value.toISOString()\n return undefined\n}\n\nconst normalizeNotificationActionLink = (url: string | undefined, urlMode: NotificationUrlMode): string | undefined => {\n const normalizedUrl = normalizeOptionalString(url)\n if (!normalizedUrl) return undefined\n if (urlMode === \"navigate\") return normalizedUrl\n\n try {\n const parsed = new URL(normalizedUrl, \"https://rpcbase.local/\")\n return `${parsed.search}${parsed.hash}` || undefined\n } catch {\n return normalizedUrl.startsWith(\"?\") ? normalizedUrl : undefined\n }\n}\n\nconst buildNotificationData = (\n input: Pick<CreateNotificationInput, \"data\" | \"metadata\"> & { link?: string; urlMode: NotificationUrlMode },\n): NotificationDataPayload | undefined => {\n const data: NotificationDataPayload = {}\n\n for (const [key, value] of Object.entries(input.metadata ?? {})) {\n const normalized = toNotificationDataString(value)\n if (normalized) {\n data[key] = normalized\n }\n }\n\n if (input.data) {\n Object.assign(data, input.data)\n }\n\n if (input.link) {\n data.link = input.link\n if (input.urlMode !== \"navigate\") {\n data.linkMode = input.urlMode\n }\n }\n\n return Object.keys(data).length > 0 ? data : undefined\n}\n\nconst buildNotificationPlatform = (\n platform: NotificationPlatformPayload | undefined,\n link: string | undefined,\n): NotificationPlatformPayload | undefined => {\n if (!link) return platform\n\n const webpush = isRecord(platform?.webpush) ? platform.webpush : {}\n const fcmOptions = isRecord(webpush.fcmOptions) ? webpush.fcmOptions : {}\n\n return {\n ...platform,\n webpush: {\n ...webpush,\n fcmOptions: {\n ...fcmOptions,\n link,\n },\n },\n }\n}\n\nconst createNotificationDocument = (input: CreateNotificationInput) => {\n const userId = normalizeRequiredString(input.userId, \"createNotification: userId\")\n const title = normalizeRequiredString(input.title, \"createNotification: title\")\n const topic = normalizeOptionalString(input.topic)\n const tag = normalizeOptionalString(input.tag)\n const body = normalizeOptionalString(input.body)\n const image = normalizeOptionalString(input.image)\n const urlMode = normalizeUrlMode(input.urlMode)\n const link = normalizeNotificationActionLink(input.url, urlMode)\n const data = buildNotificationData({ data: input.data, metadata: input.metadata, link, urlMode })\n const platform = buildNotificationPlatform(input.platform, link)\n\n return {\n userId,\n ...(topic ? { topic } : {}),\n ...(tag ? { tag } : {}),\n deliveryId: randomUUID(),\n title,\n ...(body ? { body } : {}),\n ...(image ? { image } : {}),\n ...(data ? { data } : {}),\n ...(platform ? { platform } : {}),\n drawerActive: true,\n createdAt: new Date(),\n }\n}\n\nconst assertCreateNotificationsForUserInput = (input: CreateNotificationsForUserInput): void => {\n if (typeof input.userId !== \"string\" || input.userId.trim().length === 0) {\n throw new Error(\"createNotificationsForUser: userId is required\")\n }\n if (!Array.isArray(input.notifications)) {\n throw new Error(\"createNotificationsForUser: notifications must be an array\")\n }\n}\n\nexport const createNotification = async (\n ctx: Ctx,\n input: CreateNotificationInput,\n ability: AppAbility,\n): Promise<{ id: string }> => {\n if (!ability.can(\"create\", \"RBNotification\")) {\n throw new Error(\"createNotification: forbidden\")\n }\n\n const modelCtx = { req: ctx.req, ability }\n const [NotificationModel, NotificationDeliveryModel] = await Promise.all([\n models.getUnsafe(\"RBNotification\", modelCtx),\n models.getUnsafe(\"RBNotificationDelivery\", modelCtx),\n ])\n const notification = createNotificationDocument(input)\n const delivery = await NotificationDeliveryModel.create(notification)\n const doc = notification.tag\n ? await NotificationModel.findOneAndReplace(\n { userId: notification.userId, tag: notification.tag, archivedAt: { $exists: false } },\n notification,\n { new: true, upsert: true, sort: { drawerActive: -1, createdAt: -1 } },\n )\n : await NotificationModel.create(notification)\n\n if (!doc) {\n throw new Error(\"createNotification: failed to persist notification\")\n }\n\n await NotificationDeliveryModel.updateOne(\n { _id: delivery._id },\n { $set: { notificationId: doc._id.toString() } },\n )\n\n return { id: doc._id.toString() }\n}\n\nexport const createNotificationsForUser = async (\n ctx: Ctx,\n input: CreateNotificationsForUserInput,\n ability: AppAbility,\n): Promise<{ ids: string[] }> => {\n assertCreateNotificationsForUserInput(input)\n if (input.notifications.length === 0) {\n return { ids: [] }\n }\n\n if (!ability.can(\"create\", \"RBNotification\")) {\n throw new Error(\"createNotificationsForUser: forbidden\")\n }\n\n const modelCtx = { req: ctx.req, ability }\n const [NotificationModel, NotificationDeliveryModel] = await Promise.all([\n models.getUnsafe(\"RBNotification\", modelCtx),\n models.getUnsafe(\"RBNotificationDelivery\", modelCtx),\n ])\n const ids: string[] = []\n for (const notification of input.notifications) {\n const document = createNotificationDocument({\n ...notification,\n userId: input.userId,\n })\n const delivery = await NotificationDeliveryModel.create(document)\n const doc = document.tag\n ? await NotificationModel.findOneAndReplace(\n { userId: document.userId, tag: document.tag, archivedAt: { $exists: false } },\n document,\n { new: true, upsert: true, sort: { drawerActive: -1, createdAt: -1 } },\n )\n : await NotificationModel.create(document)\n\n if (!doc) {\n throw new Error(\"createNotificationsForUser: failed to persist notification\")\n }\n await NotificationDeliveryModel.updateOne(\n { _id: delivery._id },\n { $set: { notificationId: doc._id.toString() } },\n )\n ids.push(doc._id.toString())\n }\n\n return { ids }\n}\n","import type { Ctx } from \"@rpcbase/api\"\nimport { models, type IRBNotification, type IRBNotificationSettings } from \"@rpcbase/db\"\nimport type { AppAbility } from \"@rpcbase/db/acl\"\n\nimport { sendEmail } from \"../email\"\n\n\nconst DAY_MS = 24 * 60 * 60 * 1000\nconst WEEK_MS = 7 * DAY_MS\n\ntype DigestFrequency = \"off\" | \"daily\" | \"weekly\"\n\ntype NotificationDoc = IRBNotification & { _id: unknown }\ntype SettingsDoc = IRBNotificationSettings & { _id: unknown }\n\nconst getDigestWindowMs = (frequency: DigestFrequency): number => {\n if (frequency === \"daily\") return DAY_MS\n if (frequency === \"weekly\") return WEEK_MS\n return 0\n}\n\nconst formatIso = (value: unknown): string | undefined => {\n if (!(value instanceof Date)) return undefined\n return value.toISOString()\n}\n\nconst getNotificationLink = (notification: NotificationDoc): string => {\n const dataLink = notification.data?.link?.trim()\n if (dataLink) return dataLink\n\n const platform = notification.platform\n if (!platform || typeof platform !== \"object\" || Array.isArray(platform)) return \"\"\n const webpush = (platform as { webpush?: unknown }).webpush\n if (!webpush || typeof webpush !== \"object\" || Array.isArray(webpush)) return \"\"\n const fcmOptions = (webpush as { fcmOptions?: unknown }).fcmOptions\n if (!fcmOptions || typeof fcmOptions !== \"object\" || Array.isArray(fcmOptions)) return \"\"\n const link = (fcmOptions as { link?: unknown }).link\n return typeof link === \"string\" ? link.trim() : \"\"\n}\n\nconst buildPreferencesByTopic = (settings: SettingsDoc | null): Record<string, { emailDigest: boolean }> => {\n const record: Record<string, { emailDigest: boolean }> = {}\n const raw = settings?.topicPreferences\n if (!Array.isArray(raw)) return record\n for (const pref of raw) {\n if (!pref || typeof pref !== \"object\") continue\n const topic = typeof (pref as { topic?: unknown }).topic === \"string\" ? (pref as { topic: string }).topic.trim() : \"\"\n if (!topic) continue\n const emailDigest = (pref as { emailDigest?: unknown }).emailDigest\n record[topic] = { emailDigest: emailDigest === true }\n }\n return record\n}\n\nexport const sendNotificationsDigestForUser = async (\n ctx: Ctx,\n {\n userId,\n ability,\n force = false,\n }: {\n userId: string\n ability: AppAbility\n force?: boolean\n },\n): Promise<{ ok: true; sent: boolean; skippedReason?: string } | { ok: false; error: string }> => {\n const modelCtx = { req: ctx.req, ability }\n const SettingsModel = await models.get(\"RBNotificationSettings\", modelCtx)\n const NotificationModel = await models.get(\"RBNotification\", modelCtx)\n\n const settings = (await SettingsModel.findOne({ userId }).lean()) as SettingsDoc | null\n\n const digestFrequencyRaw = typeof settings?.digestFrequency === \"string\" ? settings.digestFrequency : \"weekly\"\n const digestFrequency: DigestFrequency =\n digestFrequencyRaw === \"daily\" || digestFrequencyRaw === \"weekly\" || digestFrequencyRaw === \"off\"\n ? digestFrequencyRaw\n : \"weekly\"\n\n if (digestFrequency === \"off\") {\n return { ok: true, sent: false, skippedReason: \"digest_off\" }\n }\n\n const now = new Date()\n const windowMs = getDigestWindowMs(digestFrequency)\n const lastSentAt = settings?.lastDigestSentAt instanceof Date ? settings.lastDigestSentAt : null\n const since = lastSentAt ?? new Date(now.getTime() - windowMs)\n\n if (!force && lastSentAt && now.getTime() - lastSentAt.getTime() < windowMs) {\n return { ok: true, sent: false, skippedReason: \"not_due\" }\n }\n\n const preferencesByTopic = buildPreferencesByTopic(settings)\n const disabledTopics = Object.entries(preferencesByTopic)\n .filter(([, pref]) => pref.emailDigest === false)\n .map(([topic]) => topic)\n\n const query: Record<string, unknown> = {\n userId,\n archivedAt: { $exists: false },\n readAt: { $exists: false },\n createdAt: { $gt: since },\n }\n\n if (disabledTopics.length > 0) {\n query.topic = { $nin: disabledTopics }\n }\n\n const notifications = (await NotificationModel.find(query)\n .sort({ createdAt: -1 })\n .limit(50)\n .lean()) as NotificationDoc[]\n\n if (!notifications.length) {\n await SettingsModel.updateOne(\n { userId },\n { $set: { lastDigestSentAt: now }, $setOnInsert: { userId, digestFrequency: \"weekly\" } },\n { upsert: true },\n )\n return { ok: true, sent: false, skippedReason: \"empty\" }\n }\n\n const UserModel = await models.getGlobal(\"RBUser\", ctx)\n const user = (await UserModel.findById(userId, { email: 1 }).lean()) as { email?: unknown } | null\n const email = typeof user?.email === \"string\" ? user.email.trim() : \"\"\n if (!email) {\n return { ok: true, sent: false, skippedReason: \"missing_email\" }\n }\n\n const subject = \"Notifications digest\"\n const rows = notifications\n .map((n) => {\n const title = typeof n.title === \"string\" ? n.title : \"\"\n const body = typeof n.body === \"string\" ? n.body : \"\"\n const url = getNotificationLink(n)\n const createdAt = formatIso(n.createdAt) ?? \"\"\n const line = url\n ? `<li><strong>${title}</strong><br>${body}<br><a href=\"${url}\">${url}</a><br><small>${createdAt}</small></li>`\n : `<li><strong>${title}</strong><br>${body}<br><small>${createdAt}</small></li>`\n return line\n })\n .join(\"\")\n\n const html = `<div><p>Here is your notifications digest:</p><ul>${rows}</ul></div>`\n\n let emailResult\n try {\n emailResult = await sendEmail(\n { to: email, subject, html },\n { missingTransport: \"skip\" },\n )\n } catch (error) {\n return {\n ok: false,\n error: error instanceof Error ? error.message : \"Email delivery failed\",\n }\n }\n\n await SettingsModel.updateOne(\n { userId },\n { $set: { lastDigestSentAt: now }, $setOnInsert: { userId, digestFrequency: \"weekly\" } },\n { upsert: true },\n )\n\n return { ok: true, sent: emailResult.skipped !== true, ...(emailResult.skipped ? { skippedReason: \"email_skipped\" } : {}) }\n}\n"],"names":["routes","Object","entries","import","reduce","acc","path","mod","replace","normalizeRequiredString","value","name","normalized","trim","Error","normalizeOptionalString","undefined","normalizeUrlMode","isRecord","Boolean","Array","isArray","toNotificationDataString","trimmed","Number","isFinite","String","toString","Date","getTime","toISOString","normalizeNotificationActionLink","url","urlMode","normalizedUrl","parsed","URL","search","hash","startsWith","buildNotificationData","input","data","key","metadata","assign","link","linkMode","keys","length","buildNotificationPlatform","platform","webpush","fcmOptions","createNotificationDocument","userId","title","topic","tag","body","image","deliveryId","randomUUID","drawerActive","createdAt","assertCreateNotificationsForUserInput","notifications","createNotification","ctx","ability","can","modelCtx","req","NotificationModel","NotificationDeliveryModel","Promise","all","models","getUnsafe","notification","delivery","create","doc","findOneAndReplace","archivedAt","$exists","new","upsert","sort","updateOne","_id","$set","notificationId","id","createNotificationsForUser","ids","document","push","DAY_MS","WEEK_MS","getDigestWindowMs","frequency","formatIso","getNotificationLink","dataLink","buildPreferencesByTopic","settings","record","raw","topicPreferences","pref","emailDigest","sendNotificationsDigestForUser","force","SettingsModel","get","findOne","lean","digestFrequencyRaw","digestFrequency","ok","sent","skippedReason","now","windowMs","lastSentAt","lastDigestSentAt","since","preferencesByTopic","disabledTopics","filter","map","query","readAt","$gt","$nin","find","limit","$setOnInsert","UserModel","getGlobal","user","findById","email","subject","rows","n","line","join","html","emailResult","sendEmail","to","missingTransport","error","message","skipped"],"mappings":";;;AAAO,MAAMA,SAASC,OAAOC,QAAQ;AAAA,EACnC,GAAGC,uBAAAA,OAAAA,EAAAA,kCAAAA,MAAAA,OAAAA,uBAAAA,EAAAA,CAAAA;AACL,CAAC,EAAEC,OAAgC,CAACC,KAAK,CAACC,MAAMC,GAAG,MAAM;AACvDF,MAAIC,KAAKE,QAAQ,UAAU,oCAAoC,CAAC,IAAID;AACpE,SAAOF;AACT,GAAG,CAAA,CAAE;AC4BL,MAAMI,0BAA0BA,CAACC,OAAgBC,SAAyB;AACxE,QAAMC,aAAa,OAAOF,UAAU,WAAWA,MAAMG,SAAS;AAC9D,MAAI,CAACD,YAAY;AACf,UAAM,IAAIE,MAAM,GAAGH,IAAI,cAAc;AAAA,EACvC;AACA,SAAOC;AACT;AAEA,MAAMG,0BAA0BA,CAACL,UAAkD;AACjF,QAAME,aAAa,OAAOF,UAAU,WAAWA,MAAMG,SAAS;AAC9D,SAAOD,cAAcI;AACvB;AAEA,MAAMC,m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AO;AACnD,UAAM3B,MAAMuE,oBAAoB2C,CAAC;AACjC,UAAMlF,YAAYsC,UAAU4C,EAAElF,SAAS,KAAK;AAC5C,UAAMmF,OAAOnH,MACT,eAAewB,KAAK,gBAAgBG,IAAI,gBAAgB3B,GAAG,KAAKA,GAAG,kBAAkBgC,SAAS,kBAC9F,eAAeR,KAAK,gBAAgBG,IAAI,cAAcK,SAAS;AACnE,WAAOmF;AAAAA,EACT,CAAC,EACAC,KAAK,EAAE;AAEV,QAAMC,OAAO,qDAAqDJ,IAAI;AAEtE,MAAIK;AACJ,MAAI;AACFA,kBAAc,MAAMC,UAClB;AAAA,MAAEC,IAAIT;AAAAA,MAAOC;AAAAA,MAASK;AAAAA,IAAAA,GACtB;AAAA,MAAEI,kBAAkB;AAAA,IAAA,CACtB;AAAA,EACF,SAASC,OAAO;AACd,WAAO;AAAA,MACLlC,IAAI;AAAA,MACJkC,OAAOA,iBAAiB5I,QAAQ4I,MAAMC,UAAU;AAAA,IAAA;AAAA,EAEpD;AAEA,QAAMzC,cAAczB,UAClB;AAAA,IAAElC;AAAAA,EAAAA,GACF;AAAA,IAAEoC,MAAM;AAAA,MAAEmC,kBAAkBH;AAAAA,IAAAA;AAAAA,IAAOe,cAAc;AAAA,MAAEnF;AAAAA,MAAQgE,iBAAiB;AAAA,IAAA;AAAA,EAAS,GACrF;AAAA,IAAEhC,QAAQ;AAAA,EAAA,CACZ;AAEA,SAAO;AAAA,IAAEiC,IAAI;AAAA,IAAMC,MAAM6B,YAAYM,YAAY;AAAA,IAAM,GAAIN,YAAYM,UAAU;AAAA,MAAElC,eAAe;AAAA,IAAA,IAAoB,CAAA;AAAA,EAAC;AACzH;"}
|
|
1
|
+
{"version":3,"file":"notifications.js","names":["routes","Object","entries","import","meta","glob","reduce","Record","acc","path","mod","replace","randomUUID","Ctx","models","IRBNotificationPlatformPayload","AppAbility","NotificationDataPayload","Record","NotificationMetadataPayload","NotificationPlatformPayload","NotificationUrlMode","CreateNotificationInput","userId","topic","tag","title","body","image","url","urlMode","metadata","data","platform","CreateNotificationForUserInput","Omit","CreateNotificationsForUserInput","notifications","normalizeRequiredString","value","name","normalized","trim","Error","normalizeOptionalString","undefined","normalizeUrlMode","isRecord","Boolean","Array","isArray","toNotificationDataString","trimmed","Number","isFinite","String","toString","Date","getTime","toISOString","normalizeNotificationActionLink","normalizedUrl","parsed","URL","search","hash","startsWith","buildNotificationData","input","Pick","link","key","Object","entries","assign","linkMode","keys","length","buildNotificationPlatform","webpush","fcmOptions","createNotificationDocument","deliveryId","drawerActive","createdAt","assertCreateNotificationsForUserInput","createNotification","ctx","ability","Promise","id","can","modelCtx","req","NotificationModel","NotificationDeliveryModel","all","getUnsafe","notification","delivery","create","doc","findOneAndReplace","archivedAt","$exists","new","upsert","sort","updateOne","_id","$set","notificationId","createNotificationsForUser","ids","document","push","Ctx","models","IRBNotification","IRBNotificationSettings","AppAbility","sendEmail","DAY_MS","WEEK_MS","DigestFrequency","NotificationDoc","_id","SettingsDoc","getDigestWindowMs","frequency","formatIso","value","Date","undefined","toISOString","getNotificationLink","notification","dataLink","data","link","trim","platform","Array","isArray","webpush","fcmOptions","buildPreferencesByTopic","settings","Record","emailDigest","record","raw","topicPreferences","pref","topic","sendNotificationsDigestForUser","ctx","userId","ability","force","Promise","ok","sent","skippedReason","error","modelCtx","req","SettingsModel","get","NotificationModel","findOne","lean","digestFrequencyRaw","digestFrequency","now","windowMs","lastSentAt","lastDigestSentAt","since","getTime","preferencesByTopic","disabledTopics","Object","entries","filter","map","query","archivedAt","$exists","readAt","createdAt","$gt","length","$nin","notifications","find","sort","limit","updateOne","$set","$setOnInsert","upsert","UserModel","getGlobal","user","findById","email","subject","rows","n","title","body","url","line","join","html","emailResult","to","missingTransport","Error","message","skipped"],"sources":["../src/notifications/routes.ts","../src/notifications/createNotification.ts","../src/notifications/digest.ts"],"sourcesContent":["export const routes = Object.entries({\n ...import.meta.glob(\"./api/**/handler.ts\"),\n}).reduce<Record<string, unknown>>((acc, [path, mod]) => {\n acc[path.replace(\"./api/\", \"@rpcbase/server/notifications/api/\")] = mod\n return acc\n}, {})\n\n","import { randomUUID } from \"node:crypto\"\n\nimport type { Ctx } from \"@rpcbase/api\"\nimport { models, type IRBNotificationPlatformPayload } from \"@rpcbase/db\"\nimport type { AppAbility } from \"@rpcbase/db/acl\"\n\n\nexport type NotificationDataPayload = Record<string, string>\nexport type NotificationMetadataPayload = Record<string, unknown>\nexport type NotificationPlatformPayload = IRBNotificationPlatformPayload\nexport type NotificationUrlMode = \"navigate\" | \"merge_current_search\"\n\nexport type CreateNotificationInput = {\n userId: string\n topic?: string\n tag?: string\n title: string\n body?: string\n image?: string\n url?: string\n urlMode?: NotificationUrlMode\n metadata?: NotificationMetadataPayload\n data?: NotificationDataPayload\n platform?: NotificationPlatformPayload\n}\n\nexport type CreateNotificationForUserInput = Omit<CreateNotificationInput, \"userId\">\n\nexport type CreateNotificationsForUserInput = {\n userId: string\n notifications: CreateNotificationForUserInput[]\n}\n\nconst normalizeRequiredString = (value: unknown, name: string): string => {\n const normalized = typeof value === \"string\" ? value.trim() : \"\"\n if (!normalized) {\n throw new Error(`${name} is required`)\n }\n return normalized\n}\n\nconst normalizeOptionalString = (value: string | undefined): string | undefined => {\n const normalized = typeof value === \"string\" ? value.trim() : \"\"\n return normalized || undefined\n}\n\nconst normalizeUrlMode = (value: unknown): NotificationUrlMode => {\n return value === \"merge_current_search\" ? \"merge_current_search\" : \"navigate\"\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n Boolean(value) && typeof value === \"object\" && !Array.isArray(value)\n\nconst toNotificationDataString = (value: unknown): string | undefined => {\n if (typeof value === \"string\") {\n const trimmed = value.trim()\n return trimmed || undefined\n }\n if (typeof value === \"number\" && Number.isFinite(value)) return String(value)\n if (typeof value === \"boolean\") return String(value)\n if (typeof value === \"bigint\") return value.toString()\n if (value instanceof Date && Number.isFinite(value.getTime())) return value.toISOString()\n return undefined\n}\n\nconst normalizeNotificationActionLink = (url: string | undefined, urlMode: NotificationUrlMode): string | undefined => {\n const normalizedUrl = normalizeOptionalString(url)\n if (!normalizedUrl) return undefined\n if (urlMode === \"navigate\") return normalizedUrl\n\n try {\n const parsed = new URL(normalizedUrl, \"https://rpcbase.local/\")\n return `${parsed.search}${parsed.hash}` || undefined\n } catch {\n return normalizedUrl.startsWith(\"?\") ? normalizedUrl : undefined\n }\n}\n\nconst buildNotificationData = (\n input: Pick<CreateNotificationInput, \"data\" | \"metadata\"> & { link?: string; urlMode: NotificationUrlMode },\n): NotificationDataPayload | undefined => {\n const data: NotificationDataPayload = {}\n\n for (const [key, value] of Object.entries(input.metadata ?? {})) {\n const normalized = toNotificationDataString(value)\n if (normalized) {\n data[key] = normalized\n }\n }\n\n if (input.data) {\n Object.assign(data, input.data)\n }\n\n if (input.link) {\n data.link = input.link\n if (input.urlMode !== \"navigate\") {\n data.linkMode = input.urlMode\n }\n }\n\n return Object.keys(data).length > 0 ? data : undefined\n}\n\nconst buildNotificationPlatform = (\n platform: NotificationPlatformPayload | undefined,\n link: string | undefined,\n): NotificationPlatformPayload | undefined => {\n if (!link) return platform\n\n const webpush = isRecord(platform?.webpush) ? platform.webpush : {}\n const fcmOptions = isRecord(webpush.fcmOptions) ? webpush.fcmOptions : {}\n\n return {\n ...platform,\n webpush: {\n ...webpush,\n fcmOptions: {\n ...fcmOptions,\n link,\n },\n },\n }\n}\n\nconst createNotificationDocument = (input: CreateNotificationInput) => {\n const userId = normalizeRequiredString(input.userId, \"createNotification: userId\")\n const title = normalizeRequiredString(input.title, \"createNotification: title\")\n const topic = normalizeOptionalString(input.topic)\n const tag = normalizeOptionalString(input.tag)\n const body = normalizeOptionalString(input.body)\n const image = normalizeOptionalString(input.image)\n const urlMode = normalizeUrlMode(input.urlMode)\n const link = normalizeNotificationActionLink(input.url, urlMode)\n const data = buildNotificationData({ data: input.data, metadata: input.metadata, link, urlMode })\n const platform = buildNotificationPlatform(input.platform, link)\n\n return {\n userId,\n ...(topic ? { topic } : {}),\n ...(tag ? { tag } : {}),\n deliveryId: randomUUID(),\n title,\n ...(body ? { body } : {}),\n ...(image ? { image } : {}),\n ...(data ? { data } : {}),\n ...(platform ? { platform } : {}),\n drawerActive: true,\n createdAt: new Date(),\n }\n}\n\nconst assertCreateNotificationsForUserInput = (input: CreateNotificationsForUserInput): void => {\n if (typeof input.userId !== \"string\" || input.userId.trim().length === 0) {\n throw new Error(\"createNotificationsForUser: userId is required\")\n }\n if (!Array.isArray(input.notifications)) {\n throw new Error(\"createNotificationsForUser: notifications must be an array\")\n }\n}\n\nexport const createNotification = async (\n ctx: Ctx,\n input: CreateNotificationInput,\n ability: AppAbility,\n): Promise<{ id: string }> => {\n if (!ability.can(\"create\", \"RBNotification\")) {\n throw new Error(\"createNotification: forbidden\")\n }\n\n const modelCtx = { req: ctx.req, ability }\n const [NotificationModel, NotificationDeliveryModel] = await Promise.all([\n models.getUnsafe(\"RBNotification\", modelCtx),\n models.getUnsafe(\"RBNotificationDelivery\", modelCtx),\n ])\n const notification = createNotificationDocument(input)\n const delivery = await NotificationDeliveryModel.create(notification)\n const doc = notification.tag\n ? await NotificationModel.findOneAndReplace(\n { userId: notification.userId, tag: notification.tag, archivedAt: { $exists: false } },\n notification,\n { new: true, upsert: true, sort: { drawerActive: -1, createdAt: -1 } },\n )\n : await NotificationModel.create(notification)\n\n if (!doc) {\n throw new Error(\"createNotification: failed to persist notification\")\n }\n\n await NotificationDeliveryModel.updateOne(\n { _id: delivery._id },\n { $set: { notificationId: doc._id.toString() } },\n )\n\n return { id: doc._id.toString() }\n}\n\nexport const createNotificationsForUser = async (\n ctx: Ctx,\n input: CreateNotificationsForUserInput,\n ability: AppAbility,\n): Promise<{ ids: string[] }> => {\n assertCreateNotificationsForUserInput(input)\n if (input.notifications.length === 0) {\n return { ids: [] }\n }\n\n if (!ability.can(\"create\", \"RBNotification\")) {\n throw new Error(\"createNotificationsForUser: forbidden\")\n }\n\n const modelCtx = { req: ctx.req, ability }\n const [NotificationModel, NotificationDeliveryModel] = await Promise.all([\n models.getUnsafe(\"RBNotification\", modelCtx),\n models.getUnsafe(\"RBNotificationDelivery\", modelCtx),\n ])\n const ids: string[] = []\n for (const notification of input.notifications) {\n const document = createNotificationDocument({\n ...notification,\n userId: input.userId,\n })\n const delivery = await NotificationDeliveryModel.create(document)\n const doc = document.tag\n ? await NotificationModel.findOneAndReplace(\n { userId: document.userId, tag: document.tag, archivedAt: { $exists: false } },\n document,\n { new: true, upsert: true, sort: { drawerActive: -1, createdAt: -1 } },\n )\n : await NotificationModel.create(document)\n\n if (!doc) {\n throw new Error(\"createNotificationsForUser: failed to persist notification\")\n }\n await NotificationDeliveryModel.updateOne(\n { _id: delivery._id },\n { $set: { notificationId: doc._id.toString() } },\n )\n ids.push(doc._id.toString())\n }\n\n return { ids }\n}\n","import type { Ctx } from \"@rpcbase/api\"\nimport { models, type IRBNotification, type IRBNotificationSettings } from \"@rpcbase/db\"\nimport type { AppAbility } from \"@rpcbase/db/acl\"\n\nimport { sendEmail } from \"../email\"\n\n\nconst DAY_MS = 24 * 60 * 60 * 1000\nconst WEEK_MS = 7 * DAY_MS\n\ntype DigestFrequency = \"off\" | \"daily\" | \"weekly\"\n\ntype NotificationDoc = IRBNotification & { _id: unknown }\ntype SettingsDoc = IRBNotificationSettings & { _id: unknown }\n\nconst getDigestWindowMs = (frequency: DigestFrequency): number => {\n if (frequency === \"daily\") return DAY_MS\n if (frequency === \"weekly\") return WEEK_MS\n return 0\n}\n\nconst formatIso = (value: unknown): string | undefined => {\n if (!(value instanceof Date)) return undefined\n return value.toISOString()\n}\n\nconst getNotificationLink = (notification: NotificationDoc): string => {\n const dataLink = notification.data?.link?.trim()\n if (dataLink) return dataLink\n\n const platform = notification.platform\n if (!platform || typeof platform !== \"object\" || Array.isArray(platform)) return \"\"\n const webpush = (platform as { webpush?: unknown }).webpush\n if (!webpush || typeof webpush !== \"object\" || Array.isArray(webpush)) return \"\"\n const fcmOptions = (webpush as { fcmOptions?: unknown }).fcmOptions\n if (!fcmOptions || typeof fcmOptions !== \"object\" || Array.isArray(fcmOptions)) return \"\"\n const link = (fcmOptions as { link?: unknown }).link\n return typeof link === \"string\" ? link.trim() : \"\"\n}\n\nconst buildPreferencesByTopic = (settings: SettingsDoc | null): Record<string, { emailDigest: boolean }> => {\n const record: Record<string, { emailDigest: boolean }> = {}\n const raw = settings?.topicPreferences\n if (!Array.isArray(raw)) return record\n for (const pref of raw) {\n if (!pref || typeof pref !== \"object\") continue\n const topic = typeof (pref as { topic?: unknown }).topic === \"string\" ? (pref as { topic: string }).topic.trim() : \"\"\n if (!topic) continue\n const emailDigest = (pref as { emailDigest?: unknown }).emailDigest\n record[topic] = { emailDigest: emailDigest === true }\n }\n return record\n}\n\nexport const sendNotificationsDigestForUser = async (\n ctx: Ctx,\n {\n userId,\n ability,\n force = false,\n }: {\n userId: string\n ability: AppAbility\n force?: boolean\n },\n): Promise<{ ok: true; sent: boolean; skippedReason?: string } | { ok: false; error: string }> => {\n const modelCtx = { req: ctx.req, ability }\n const SettingsModel = await models.get(\"RBNotificationSettings\", modelCtx)\n const NotificationModel = await models.get(\"RBNotification\", modelCtx)\n\n const settings = (await SettingsModel.findOne({ userId }).lean()) as SettingsDoc | null\n\n const digestFrequencyRaw = typeof settings?.digestFrequency === \"string\" ? settings.digestFrequency : \"weekly\"\n const digestFrequency: DigestFrequency =\n digestFrequencyRaw === \"daily\" || digestFrequencyRaw === \"weekly\" || digestFrequencyRaw === \"off\"\n ? digestFrequencyRaw\n : \"weekly\"\n\n if (digestFrequency === \"off\") {\n return { ok: true, sent: false, skippedReason: \"digest_off\" }\n }\n\n const now = new Date()\n const windowMs = getDigestWindowMs(digestFrequency)\n const lastSentAt = settings?.lastDigestSentAt instanceof Date ? settings.lastDigestSentAt : null\n const since = lastSentAt ?? new Date(now.getTime() - windowMs)\n\n if (!force && lastSentAt && now.getTime() - lastSentAt.getTime() < windowMs) {\n return { ok: true, sent: false, skippedReason: \"not_due\" }\n }\n\n const preferencesByTopic = buildPreferencesByTopic(settings)\n const disabledTopics = Object.entries(preferencesByTopic)\n .filter(([, pref]) => pref.emailDigest === false)\n .map(([topic]) => topic)\n\n const query: Record<string, unknown> = {\n userId,\n archivedAt: { $exists: false },\n readAt: { $exists: false },\n createdAt: { $gt: since },\n }\n\n if (disabledTopics.length > 0) {\n query.topic = { $nin: disabledTopics }\n }\n\n const notifications = (await NotificationModel.find(query)\n .sort({ createdAt: -1 })\n .limit(50)\n .lean()) as NotificationDoc[]\n\n if (!notifications.length) {\n await SettingsModel.updateOne(\n { userId },\n { $set: { lastDigestSentAt: now }, $setOnInsert: { userId, digestFrequency: \"weekly\" } },\n { upsert: true },\n )\n return { ok: true, sent: false, skippedReason: \"empty\" }\n }\n\n const UserModel = await models.getGlobal(\"RBUser\", ctx)\n const user = (await UserModel.findById(userId, { email: 1 }).lean()) as { email?: unknown } | null\n const email = typeof user?.email === \"string\" ? user.email.trim() : \"\"\n if (!email) {\n return { ok: true, sent: false, skippedReason: \"missing_email\" }\n }\n\n const subject = \"Notifications digest\"\n const rows = notifications\n .map((n) => {\n const title = typeof n.title === \"string\" ? n.title : \"\"\n const body = typeof n.body === \"string\" ? n.body : \"\"\n const url = getNotificationLink(n)\n const createdAt = formatIso(n.createdAt) ?? \"\"\n const line = url\n ? `<li><strong>${title}</strong><br>${body}<br><a href=\"${url}\">${url}</a><br><small>${createdAt}</small></li>`\n : `<li><strong>${title}</strong><br>${body}<br><small>${createdAt}</small></li>`\n return line\n })\n .join(\"\")\n\n const html = `<div><p>Here is your notifications digest:</p><ul>${rows}</ul></div>`\n\n let emailResult\n try {\n emailResult = await sendEmail(\n { to: email, subject, html },\n { missingTransport: \"skip\" },\n )\n } catch (error) {\n return {\n ok: false,\n error: error instanceof Error ? error.message : \"Email delivery failed\",\n }\n }\n\n await SettingsModel.updateOne(\n { userId },\n { $set: { lastDigestSentAt: now }, $setOnInsert: { userId, digestFrequency: \"weekly\" } },\n { upsert: true },\n )\n\n return { ok: true, s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AAM,GAAIL,YAAYK,UAAU,EAAE1D,eAAe,gBAAgB,IAAI,CAAC;CAAG;AAC5H"}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { queue } from "@rpcbase/worker";
|
|
2
|
+
//#region src/uploads/api/file-uploads/postProcessors.ts
|
|
3
|
+
var processorsById = Object.create(null);
|
|
4
|
+
var uploadPostProcessorTaskName = "rb-upload-post-processors";
|
|
5
|
+
var normalizeProcessorId = (value) => typeof value === "string" ? value.trim() : "";
|
|
6
|
+
var normalizeProcessorVersion = (value) => {
|
|
7
|
+
if (typeof value !== "number") return void 0;
|
|
8
|
+
if (!Number.isInteger(value) || value < 1) return void 0;
|
|
9
|
+
return value;
|
|
10
|
+
};
|
|
11
|
+
var registerUploadPostProcessor = (processor) => {
|
|
12
|
+
const normalizedId = normalizeProcessorId(processor.id);
|
|
13
|
+
if (!normalizedId) throw new Error("Upload post processor id is required.");
|
|
14
|
+
const normalizedVersion = normalizeProcessorVersion(processor.version);
|
|
15
|
+
processorsById[normalizedId] = {
|
|
16
|
+
...processor,
|
|
17
|
+
id: normalizedId,
|
|
18
|
+
...normalizedVersion ? { version: normalizedVersion } : {}
|
|
19
|
+
};
|
|
20
|
+
};
|
|
21
|
+
var registerUploadProcessor = registerUploadPostProcessor;
|
|
22
|
+
var unregisterUploadPostProcessor = (id) => {
|
|
23
|
+
const normalizedId = normalizeProcessorId(id);
|
|
24
|
+
if (!normalizedId) return;
|
|
25
|
+
delete processorsById[normalizedId];
|
|
26
|
+
};
|
|
27
|
+
var unregisterUploadProcessor = unregisterUploadPostProcessor;
|
|
28
|
+
var clearUploadPostProcessors = () => {
|
|
29
|
+
for (const id of Object.keys(processorsById)) delete processorsById[id];
|
|
30
|
+
};
|
|
31
|
+
var clearUploadProcessors = clearUploadPostProcessors;
|
|
32
|
+
var getUploadPostProcessors = () => Object.values(processorsById);
|
|
33
|
+
var getUploadProcessors = getUploadPostProcessors;
|
|
34
|
+
var runUploadPostProcessors = async (ctx) => {
|
|
35
|
+
const processors = getUploadPostProcessors();
|
|
36
|
+
if (!processors.length) return;
|
|
37
|
+
for (const processor of processors) {
|
|
38
|
+
if (processor.match) try {
|
|
39
|
+
if (!processor.match(ctx)) continue;
|
|
40
|
+
} catch (error) {
|
|
41
|
+
console.error("Upload post processor failed", {
|
|
42
|
+
processorId: processor.id,
|
|
43
|
+
processorVersion: processor.version,
|
|
44
|
+
tenantId: ctx.tenantId,
|
|
45
|
+
uploadId: ctx.uploadId,
|
|
46
|
+
fileId: ctx.fileId,
|
|
47
|
+
stage: "match",
|
|
48
|
+
error
|
|
49
|
+
});
|
|
50
|
+
continue;
|
|
51
|
+
}
|
|
52
|
+
try {
|
|
53
|
+
await processor.process(ctx);
|
|
54
|
+
} catch (error) {
|
|
55
|
+
console.error("Upload post processor failed", {
|
|
56
|
+
processorId: processor.id,
|
|
57
|
+
processorVersion: processor.version,
|
|
58
|
+
tenantId: ctx.tenantId,
|
|
59
|
+
uploadId: ctx.uploadId,
|
|
60
|
+
fileId: ctx.fileId,
|
|
61
|
+
stage: "process",
|
|
62
|
+
error
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
};
|
|
67
|
+
var isUploadPostProcessorTaskRegistered = false;
|
|
68
|
+
var registerUploadPostProcessorTask = () => {
|
|
69
|
+
if (isUploadPostProcessorTaskRegistered) return;
|
|
70
|
+
queue.registerTask(uploadPostProcessorTaskName, async (payload) => {
|
|
71
|
+
await runUploadPostProcessors(payload);
|
|
72
|
+
});
|
|
73
|
+
isUploadPostProcessorTaskRegistered = true;
|
|
74
|
+
};
|
|
75
|
+
var enqueueUploadPostProcessors = async (ctx) => {
|
|
76
|
+
await queue.add(uploadPostProcessorTaskName, ctx, {
|
|
77
|
+
attempts: 3,
|
|
78
|
+
backoff: {
|
|
79
|
+
type: "exponential",
|
|
80
|
+
delay: 5e3
|
|
81
|
+
},
|
|
82
|
+
removeOnComplete: true,
|
|
83
|
+
removeOnFail: false
|
|
84
|
+
});
|
|
85
|
+
};
|
|
86
|
+
//#endregion
|
|
87
|
+
export { getUploadProcessors as a, registerUploadProcessor as c, unregisterUploadProcessor as d, uploadPostProcessorTaskName as f, getUploadPostProcessors as i, runUploadPostProcessors as l, clearUploadProcessors as n, registerUploadPostProcessor as o, enqueueUploadPostProcessors as r, registerUploadPostProcessorTask as s, clearUploadPostProcessors as t, unregisterUploadPostProcessor as u };
|
|
88
|
+
|
|
89
|
+
//# sourceMappingURL=postProcessors-iffHvje4.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"postProcessors-iffHvje4.js","names":["queue","UploadPostProcessorContext","tenantId","uploadId","fileId","filename","mimeType","clientMimeType","totalSize","isPublic","userId","ownerKeyHash","inlineProcessors","metadata","Record","UploadPostProcessor","id","version","match","ctx","process","Promise","processorsById","Object","create","uploadPostProcessorTaskName","normalizeProcessorId","value","trim","normalizeProcessorVersion","undefined","Number","isInteger","registerUploadPostProcessor","processor","normalizedId","Error","normalizedVersion","registerUploadProcessor","unregisterUploadPostProcessor","unregisterUploadProcessor","clearUploadPostProcessors","keys","clearUploadProcessors","getUploadPostProcessors","values","getUploadProcessors","runUploadPostProcessors","processors","length","error","console","processorId","processorVersion","stage","isUploadPostProcessorTaskRegistered","registerUploadPostProcessorTask","registerTask","payload","enqueueUploadPostProcessors","add","attempts","backoff","type","delay","removeOnComplete","removeOnFail"],"sources":["../src/uploads/api/file-uploads/postProcessors.ts"],"sourcesContent":["import { queue } from \"@rpcbase/worker\"\n\n\nexport type UploadPostProcessorContext = {\n tenantId: string\n uploadId: string\n fileId: string\n filename: string\n mimeType: string\n clientMimeType: string\n totalSize: number\n isPublic?: boolean\n userId?: string\n ownerKeyHash?: string\n inlineProcessors: string[]\n metadata: Record<string, unknown>\n}\n\nexport type UploadPostProcessor = {\n id: string\n version?: number\n match?: (ctx: UploadPostProcessorContext) => boolean\n process: (ctx: UploadPostProcessorContext) => Promise<unknown> | unknown\n}\n\nconst processorsById: Record<string, UploadPostProcessor> = Object.create(null)\nexport const uploadPostProcessorTaskName = \"rb-upload-post-processors\"\n\nconst normalizeProcessorId = (value: unknown): string => (typeof value === \"string\" ? value.trim() : \"\")\n\nconst normalizeProcessorVersion = (value: unknown): number | undefined => {\n if (typeof value !== \"number\") return undefined\n if (!Number.isInteger(value) || value < 1) return undefined\n return value\n}\n\nexport const registerUploadPostProcessor = (processor: UploadPostProcessor): void => {\n const normalizedId = normalizeProcessorId(processor.id)\n if (!normalizedId) {\n throw new Error(\"Upload post processor id is required.\")\n }\n\n const normalizedVersion = normalizeProcessorVersion(processor.version)\n\n processorsById[normalizedId] = {\n ...processor,\n id: normalizedId,\n ...(normalizedVersion ? { version: normalizedVersion } : {}),\n }\n}\n\nexport const registerUploadProcessor = registerUploadPostProcessor\n\nexport const unregisterUploadPostProcessor = (id: string): void => {\n const normalizedId = normalizeProcessorId(id)\n if (!normalizedId) return\n delete processorsById[normalizedId]\n}\n\nexport const unregisterUploadProcessor = unregisterUploadPostProcessor\n\nexport const clearUploadPostProcessors = (): void => {\n for (const id of Object.keys(processorsById)) {\n delete processorsById[id]\n }\n}\n\nexport const clearUploadProcessors = clearUploadPostProcessors\n\nexport const getUploadPostProcessors = (): UploadPostProcessor[] => Object.values(processorsById)\n\nexport const getUploadProcessors = getUploadPostProcessors\n\nexport const runUploadPostProcessors = async (ctx: UploadPostProcessorContext): Promise<void> => {\n const processors = getUploadPostProcessors()\n if (!processors.length) return\n\n for (const processor of processors) {\n if (processor.match) {\n try {\n if (!processor.match(ctx)) continue\n } catch (error) {\n console.error(\"Upload post processor failed\", {\n processorId: processor.id,\n processorVersion: processor.version,\n tenantId: ctx.tenantId,\n uploadId: ctx.uploadId,\n fileId: ctx.fileId,\n stage: \"match\",\n error,\n })\n continue\n }\n }\n\n try {\n await processor.process(ctx)\n } catch (error) {\n console.error(\"Upload post processor failed\", {\n processorId: processor.id,\n processorVersion: processor.version,\n tenantId: ctx.tenantId,\n uploadId: ctx.uploadId,\n fileId: ctx.fileId,\n stage: \"process\",\n error,\n })\n }\n }\n}\n\nlet isUploadPostProcessorTaskRegistered = false\n\nexport const registerUploadPostProcessorTask = (): void => {\n if (isUploadPostProcessorTaskRegistered) return\n\n queue.registerTask(uploadPostProcessorTaskName, async (payload) => {\n await runUploadPostProcessors(payload as UploadPostProcessorContext)\n })\n isUploadPostProcessorTaskRegistered = true\n}\n\nexport const enqueueUploadPostProcessors = async (ctx: UploadPostProcessorContext): Promise<void> => {\n await queue.add(uploadPostProcessorTaskName, ctx, {\n attempts: 3,\n backoff: { type: \"exponential\", delay: 5_000 },\n removeOnComplete: true,\n removeOnFail: false,\n })\n}\n"],"mappings":";;AAyBA,IAAMsB,iBAAsDC,OAAOC,OAAO,IAAI;AAC9E,IAAaC,8BAA8B;AAE3C,IAAMC,wBAAwBC,UAA4B,OAAOA,UAAU,WAAWA,MAAMC,KAAK,IAAI;AAErG,IAAMC,6BAA6BF,UAAuC;CACxE,IAAI,OAAOA,UAAU,UAAU,OAAOG,KAAAA;CACtC,IAAI,CAACC,OAAOC,UAAUL,KAAK,KAAKA,QAAQ,GAAG,OAAOG,KAAAA;CAClD,OAAOH;AACT;AAEA,IAAaM,+BAA+BC,cAAyC;CACnF,MAAMC,eAAeT,qBAAqBQ,UAAUlB,EAAE;CACtD,IAAI,CAACmB,cACH,MAAM,IAAIC,MAAM,uCAAuC;CAGzD,MAAMC,oBAAoBR,0BAA0BK,UAAUjB,OAAO;CAErEK,eAAea,gBAAgB;EAC7B,GAAGD;EACHlB,IAAImB;EACJ,GAAIE,oBAAoB,EAAEpB,SAASoB,kBAAkB,IAAI,CAAC;CAC5D;AACF;AAEA,IAAaC,0BAA0BL;AAEvC,IAAaM,iCAAiCvB,OAAqB;CACjE,MAAMmB,eAAeT,qBAAqBV,EAAE;CAC5C,IAAI,CAACmB,cAAc;CACnB,OAAOb,eAAea;AACxB;AAEA,IAAaK,4BAA4BD;AAEzC,IAAaE,kCAAwC;CACnD,KAAK,MAAMzB,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