@aglyn/aglyn 1.0.0-beta.227 → 1.0.0-beta.229

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.
@@ -326,6 +326,20 @@ export declare const NOTIFICATION_CHANNEL_DEFAULTS: Readonly<Record<Notification
326
326
  email: boolean;
327
327
  console: boolean;
328
328
  }>>;
329
+ /**
330
+ * The types whose default differs from their category's: a site's own
331
+ * transactions — a form submitted, a booking made, an order placed — email
332
+ * the people who run it unless they said otherwise.
333
+ *
334
+ * Below every stored answer, the category's included, so a person who
335
+ * switched content email off keeps it off; above the category default, so
336
+ * everyone who never answered (every account, new or old) is emailed.
337
+ * These are the events a site exists to produce, and an owner who hears
338
+ * about them only by opening the console misses the customer.
339
+ */
340
+ export declare const NOTIFICATION_TYPE_CHANNEL_DEFAULTS: Partial<Record<AglynNotificationType, Partial<Record<NotificationChannel, boolean>>>>;
341
+ /** What a type does on a channel when nobody has answered for it or its category. */
342
+ export declare function notificationTypeChannelDefault(type: AglynNotificationType | string, channel: NotificationChannel): boolean;
329
343
  /**
330
344
  * The types that send their OWN email and must never be mailed again by the
331
345
  * generic channel (AGL-3224).
@@ -284,7 +284,9 @@ export const NOTIFICATION_SETTINGS_FIELD = 'notificationSettings';
284
284
  /**
285
285
  * What a category does when nobody has said otherwise.
286
286
  *
287
- * Console on, email OFF, everywhere. Email defaults off because the inbox is
287
+ * Console on, email OFF, for every category — a site's own transactions are
288
+ * the exception, by type, in {@link NOTIFICATION_TYPE_CHANNEL_DEFAULTS}.
289
+ * Email defaults off because the inbox is
288
290
  * not ours to fill: the product already sends transactional mail nobody opted
289
291
  * into — welcome, verification, invites, dunning, usage alerts — and every one
290
292
  * of those leaves on the same domain a customer's password reset depends on.
@@ -327,6 +329,32 @@ export const NOTIFICATION_SETTINGS_FIELD = 'notificationSettings';
327
329
  }
328
330
  };
329
331
  export const NOTIFICATION_CHANNEL_DEFAULTS = inCategoryOrder(CORE_CHANNEL_DEFAULTS, (declaration)=>_extends({}, declaration.defaults));
332
+ /**
333
+ * The types whose default differs from their category's: a site's own
334
+ * transactions — a form submitted, a booking made, an order placed — email
335
+ * the people who run it unless they said otherwise.
336
+ *
337
+ * Below every stored answer, the category's included, so a person who
338
+ * switched content email off keeps it off; above the category default, so
339
+ * everyone who never answered (every account, new or old) is emailed.
340
+ * These are the events a site exists to produce, and an owner who hears
341
+ * about them only by opening the console misses the customer.
342
+ */ export const NOTIFICATION_TYPE_CHANNEL_DEFAULTS = {
343
+ 'content.formSubmission': {
344
+ email: true
345
+ },
346
+ 'content.booking': {
347
+ email: true
348
+ },
349
+ 'content.order': {
350
+ email: true
351
+ }
352
+ };
353
+ /** What a type does on a channel when nobody has answered for it or its category. */ export function notificationTypeChannelDefault(type, channel) {
354
+ var _NOTIFICATION_TYPE_CHANNEL_DEFAULTS_type;
355
+ const own = (_NOTIFICATION_TYPE_CHANNEL_DEFAULTS_type = NOTIFICATION_TYPE_CHANNEL_DEFAULTS[type]) == null ? void 0 : _NOTIFICATION_TYPE_CHANNEL_DEFAULTS_type[channel];
356
+ return typeof own === 'boolean' ? own : NOTIFICATION_CHANNEL_DEFAULTS[notificationCategory(type)][channel];
357
+ }
330
358
  /**
331
359
  * The types that send their OWN email and must never be mailed again by the
332
360
  * generic channel (AGL-3224).
@@ -424,7 +452,7 @@ export const NOTIFICATION_CHANNEL_DEFAULTS = inCategoryOrder(CORE_CHANNEL_DEFAUL
424
452
  if (typeof answer === 'boolean') return answer;
425
453
  }
426
454
  if (channel === 'console' && notificationMuted(legacyPrefs, type)) return false;
427
- return NOTIFICATION_CHANNEL_DEFAULTS[category][channel];
455
+ return notificationTypeChannelDefault(type, channel);
428
456
  }
429
457
  /**
430
458
  * What one scope says, with no inheritance applied — what the settings page
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../libs/aglyn/src/lib/app-utils/notifications.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { ITimestamp } from '@aglyn/shared-util-timestamp'\nimport { buildRoute, Route } from './console-routes'\nimport {\n PLUGIN_NOTIFICATION_CATEGORIES_DECLARED,\n PLUGIN_NOTIFICATION_DIGESTS_DECLARED,\n} from '../plugin-manager/first-party-plugins.generated'\n\n/**\n * In-app notifications (AGL-259): per-user docs at\n * `users/{uid}/notifications/{id}`, written by the Admin SDK (emitters in\n * the API routes + the `notifyAdmins` automation step) and read/marked by\n * their owner. Types follow the common SaaS taxonomy so the console can\n * icon/group them without a registry.\n */\nexport type AglynNotificationType =\n | 'billing.invoice'\n | 'billing.paymentFailed'\n // Stripe gave up on a failed renewal and CANCELLED the subscription\n // (AGL-1877). Distinct from `paymentFailed`, which announces one failed\n // attempt inside a retry window the customer can still recover from; this\n // one is the window having closed. Measured on the test account with a\n // test clock: five attempts over 21.08 days, then\n // `cancellation_details.reason: 'payment_failed'` — and until this existed\n // the org went silently to Free at that moment, with the `past_due` banner\n // disappearing at exactly the instant the consequence arrived.\n | 'billing.subscriptionCanceled'\n | 'billing.usage'\n | 'team.invite'\n | 'team.roleChanged'\n | 'team.hostAccessGranted'\n | 'content.formSubmission'\n | 'content.booking'\n | 'content.order'\n | 'content.lowStock'\n // A CRM task was assigned to the recipient by somebody else (AGL-2599).\n // `content.` because it is the same kind of message as a form submission\n // or a booking: a thing on the site that now needs this person's hands,\n // not a change to their standing (`team.`) and not a platform notice\n // (`system.`). Someone who has muted the operational stream has said they\n // do not want to be told about work as it arrives, and a task is work.\n | 'content.taskAssigned'\n // A CRM task's reminder came due (AGL-2659): the hourly runner telling\n // the assignee, at the task's own time, that the task is due. `content.`\n // beside `taskAssigned` for the same reason it gives — work on the site,\n // not standing — and so the one mute that stops \"work arriving\" stops\n // \"work falling due\" with it. The mute governs the whole reminder, mail\n // included, unlike the digest's: a reminder is one message about one\n // task, and there is no schedule to keep separately from it.\n | 'content.taskReminder'\n // A contact, or a lead, became the recipient's to work (AGL-2618): a\n // capture the assignment rules or the site's default owner routed to\n // them, a lead somebody converted and handed to them, or an automation's\n // \"assign an owner\" step — every server path that writes `ownerUid`\n // except the recipient assigning themselves. Two types rather than one\n // because the record the person opens differs: a lead is the site's own\n // working record and a contact is the org's, and the link goes to the\n // one they will actually work. `content.`, beside `taskAssigned`, for the\n // same reason: work arriving, not standing changing.\n | 'content.contactAssigned'\n | 'content.leadAssigned'\n // The morning's CRM digest (AGL-2619): what the recipient owes today —\n // overdue and due-today tasks, and the leads nobody has worked. `content.`\n // for the reason `taskAssigned` is: it is about work on the site, and the\n // person who muted the operational stream has asked not to be told about\n // work. The digest EMAIL is governed separately, by its switch in\n // `digestPrefs` (see `digestEnabled`): the mute is a fact about the console\n // feed and the digest switch is a fact about the digest.\n | 'content.crmDailyDigest'\n // The weekly insights (AGL-2915): what a site's figures showed that week,\n // for a person who asked for them. `content.` beside the CRM digest, for the\n // reason that one gives: it is about the site's work, and the operational\n // mute governs the console notification while the person's own switch for\n // the digest governs the digest.\n | 'content.insightsDigest'\n // An AI job the recipient started (AGL-3593): its plan is ready and waits\n // for them to confirm it, it finished and its drafts are ready to open, or\n // it stopped. Raised by the jobs machine where the job's state changes —\n // on the beat as often as in a request — to the person who created the\n // job, once per change. `content.` beside the insights digest: work on the\n // workspace's sites arriving for the person, which the operational mute\n // governs. The plan-ready one is how a person who left the dialog learns\n // their site is waiting on them.\n | 'content.aiJobNeedsYou'\n | 'content.aiJobDone'\n | 'content.aiJobFailed'\n // Marketplace review verdicts (AGL-432/653).\n | 'marketplace.review'\n // Support desk, staff audience (AGL-850): a subscriber opened or replied to\n // a ticket. Fanned out to staff-claim holders, not org members.\n | 'support.ticketOpened'\n | 'support.ticketReply'\n | 'system.announcement'\n // A live plugin version stopped passing the static verifier (AGL-1086).\n // Staff audience: bytes we told workspaces were checked now fail checks\n // that did not exist when they were approved.\n //\n // Deliberately NOT under `marketplace.` (AGL-1088). Category is the prefix,\n // categories are mutable per user, and Marketplace is the category a staff\n // member mutes to stop routine listing-review chatter — which would drop\n // this alert as collateral. `system` is the bucket nobody mutes to reduce\n // noise. The adminAudit record survives a mute either way; the timeliness\n // does not, and timeliness is the whole point of the alert.\n | 'system.pluginVerifierRegression'\n // A sign-in method was removed from the user's own account because their\n // organization turned on SSO enforcement (AGL-1129). `system.`, not\n // `team.`, for the AGL-1088 reason above: `team` is the category someone\n // mutes to stop routine roster chatter, and \"the way you sign in just\n // changed\" is not chatter — the next sign-in fails without it.\n | 'system.signInMethodRemoved'\n // Documents in a scoped collection carrying no `visibleTo` (AGL-1478).\n // Staff audience: the weekly dry run found resources that are invisible\n // to every site-scoped read, which always means a creation path forgot\n // the field. `system.` for the AGL-1088 reason above, and because the\n // collection it names may be `marketplace`-adjacent or not.\n | 'system.scopeDrift'\n // An SSO domain that WAS DNS-proven has stopped answering with our\n // challenge record, for three consecutive weekly sweeps (AGL-1210).\n // Nothing has been turned off — sign-in for that domain still routes\n // exactly as it did — and that is precisely why this has to be said out\n // loud rather than left in a log.\n //\n // `system.`, not `team.`, for the AGL-1088 reason above and one of its\n // own: the audience is the org's own admins, the subject is whether their\n // people can still sign in, and it must reach them BEFORE anybody decides\n // to revoke the routing. A category somebody mutes to quieten roster\n // chatter is the wrong place for the one warning that precedes a lockout.\n | 'system.ssoDomainUnverified'\n // A site hit the per-month form-submission abuse ceiling and further\n // submissions are being refused (AGL-1655). `system.`, not `content.`, for\n // the AGL-1088 reason above and more sharply than any of them: `content` is\n // literally the category a site owner mutes to stop routine form-submission\n // chatter, and this is the one form notification that says the form has\n // STOPPED accepting. Filing it under the muted bucket would guarantee it\n // reaches nobody on exactly the sites busy enough to trip it.\n | 'system.formSubmissionsPaused'\n // A site reached the flat platform ceiling on member accounts or on lead\n // records, so further ones are being refused (AGL-1529). `system.` for the\n // same reason as `formSubmissionsPaused` directly above, and with the same\n // sharpness: `content.` is the bucket an owner mutes to stop routine\n // sign-up and lead chatter, and this is the one notification saying the\n // sign-ups have STOPPED — muted exactly on the sites busy enough to trip it.\n | 'system.visitorRecordsPaused'\n // An outsider reported one of our sites for phishing, malware or CSAM\n // (AGL-1964). `system` for the AGL-1088 reason and, again, more sharply\n // than most: this notification goes to STAFF, not to a customer, and its\n // subject is somebody else's site. There is no bucket a recipient could\n // mute it into that would be honest — nobody has opted into being told a\n // stranger is being phished through our platform, and nobody should be able\n // to opt out of it either.\n //\n // Only the urgent categories raise one, and only on a first report. See the\n // fan-out in apps/tenant/app/api/report-abuse/route.ts for why: a flood of\n // alerts IS the flood, and the alert it would cost us is the phishing one.\n | 'system.abuseReportUrgent'\n // Something on the recipient's OWN workspace was held, flagged, locked or\n // paused (AGL-3368): an email or page held for review, a flagged domain,\n // a fraud signal on a payment, a lock and its lift. Written by\n // `notifyRiskEvent` from the risk notice catalog, which says what happened,\n // what it means and how to request a review. `system.` for the AGL-1088\n // reason: it is the one message saying the owner's work has STOPPED, and a\n // category muted to quieten routine chatter must not swallow it. It sends\n // its own email, transactional and preference-free, so it is also in\n // NOTIFICATION_SELF_SENT_EMAIL_TYPES.\n | 'system.riskNotice'\n // The §512(g) counter-notice (AGL-1983), and the one place the \"only urgent\n // categories raise a notification\" restraint above is deliberately not\n // applied. Every counter-notice carries a statutory deadline that is\n // ALREADY RUNNING when it arrives — the clock counts from the subscriber's\n // submission, not from our attention — so there is no low-value tail of\n // these to drown out the important ones, and the one that goes unread is a\n // customer locked out of their own work plus an unmet obligation under\n // §512(g)(2)(A). Raised on first submission only, like the one above, so a\n // resubmitting customer cannot re-alert.\n | 'system.dmcaCounterNotice'\n // A site crossed the per-month bandwidth abuse ceiling (AGL-2155). Two\n // audiences share one type: staff, because an uncompensated free site\n // serving six figures of page views is an incident; and the site's own\n // managers, because on free the site is now serving a capped notice and\n // nobody should learn that from a visitor.\n //\n // `system.`, not `billing.`, for the AGL-1088 reason and one specific to\n // this meter: on the free plan there is no bill, so `billing` would be the\n // one category where the message is literally never about money — and it is\n // exactly the free-tier trip that changes what visitors see.\n | 'system.bandwidthCeilingTripped'\n // A free site crossed its PLAN's included bandwidth and is now serving the\n // capped notice (AGL-2413). Distinct from the ceiling above on purpose: that\n // one is an incident at 10x the band and goes to staff first; this one is an\n // ordinary quota at 1x, concerns only the site's own managers, and its\n // remedy is an upgrade rather than an investigation. Sending both under one\n // type would tell an owner their traffic was being treated as suspected\n // abuse when it is simply a successful free site.\n | 'system.bandwidthCapEngaged'\n // A Stripe billing webhook threw AFTER its handlers had begun (AGL-2157),\n // so its side effects may be half applied and its idempotency claim is\n // being HELD — Stripe will not retry it. Staff audience: this is the one\n // failure on that route no automatic retry can make safe, because the\n // handlers behind it are not all idempotent, and a human has to reconcile.\n | 'system.billingWebhookHalfApplied'\n // A card dispute arrived that NOTHING in the platform claimed (AGL-2429):\n // no `platformRevenue` row, no storefront order, no marketplace purchase.\n // Staff audience, and the reason it needs a type of its own is that its\n // absence was the bug — the routine case (a storefront or marketplace\n // chargeback, which the plugins own) and the fault case were the same\n // silence from the route's side, so a dispute nobody handled looked\n // exactly like one somebody did.\n //\n // `system.`, not `billing.`, for the AGL-1088 reason and one specific to\n // this alert: `billing` is the category a recipient is most likely to have\n // muted as routine invoice traffic, and this is the one message on that\n // route where muting it means money moves with nobody looking.\n | 'system.disputeUnattributed'\n // An operator alert from the registry in `./operator-alerts` (AGL-3377)\n // that has no notification type of its own: a lost dispute, a failed\n // erasure, a degraded health check. One type for all of them because the\n // registry, not the taxonomy, is what names the alert; the title and body\n // say which one it is. `system.` for the AGL-1088 reason above: these are\n // the faults nobody may mute away as routine chatter.\n | 'system.operatorAlert'\n // Somebody created an account, and somebody created a workspace\n // (AGL-3225). Staff audience, and the only two types in the taxonomy whose\n // subject is the platform's own growth rather than anybody's work.\n //\n // `staff.`, and NOT `system.`, and the AGL-1088 note above is the reason\n // rather than an exception to it: `system` is the bucket nobody mutes to\n // reduce noise, which is exactly what makes it the wrong home for the two\n // routine, high-volume events in the product. A staff member must be able\n // to stop hearing about every sign-up without also dropping the verifier\n // regression and the unattributed dispute that share that bucket — and\n // before this category existed, there was nowhere to put them where that\n // was true.\n //\n // The category also tells the settings page who a row is for: `staff` is\n // rendered only to claim holders, so no customer is shown a switch for\n // notifications they could never receive.\n | 'staff.userSignedUp'\n | 'staff.orgCreated'\n // And somebody created a site (AGL-3491): the third growth event, the one\n // that says an account started building. Same category, same reason.\n | 'staff.siteCreated'\n // And when money moves (AGL-3267). The category was two signup types, so\n // the one thing a platform feed exists to report — revenue starting,\n // changing and stopping — was the one thing it did not.\n //\n // `staff.paymentFailed` is deliberately NOT the customer's\n // `billing.paymentFailed`: different audience, different action. The\n // customer is told to fix their card; staff are told a paying workspace is\n // about to stop paying.\n | 'staff.subscriptionStarted'\n | 'staff.subscriptionCanceled'\n | 'staff.planChanged'\n | 'staff.paymentFailed'\n\nexport interface AglynNotification {\n $id?: string\n type: AglynNotificationType\n title: string\n body?: string\n /** Console path the notification opens (e.g. a host inbox). */\n link?: string\n orgId?: string\n hostId?: string\n /**\n * The pending invitation this notification offers the recipient\n * (AGL-3402), under `orgs/{orgId}/invites`. Present only on the invitee's\n * own `team.invite`; the console opens the accept/decline dialog for it\n * instead of following `link`, and answering marks it read.\n */\n inviteId?: string\n createdAt?: ITimestamp\n /** When the owner read it; absent or null while unread. */\n readAt?: ITimestamp | null\n /**\n * Whether the owner has read it — `false` on create, `true` beside\n * `readAt` when read (AGL-3321).\n *\n * A boolean rather than `readAt: null`, because the feed filters by it\n * under its newest-first cursor. Equality on a boolean answers BOTH\n * states (`read == false`, `read == true`) beneath `orderBy('createdAt')`\n * with one composite index. A nullable timestamp answers \"unread\" by\n * equality but \"read\" only as `readAt != null`, and Firestore requires an\n * inequality's field to be the FIRST sort, which would order the feed by\n * when things were read instead of when they arrived. Absent only on\n * notifications written before the field existed, which\n * `tools/scripts/backfill-notification-read.mjs` stamps.\n */\n read?: boolean\n /**\n * How urgently this one notification asks to be read (AGL-3437), stamped\n * by its emitter. Absent on a notification whose emitter has no reason to\n * say more than its type does, and on everything written before the field\n * existed; read it through {@link notificationLevel}, never directly.\n */\n level?: NotificationLevel\n}\n\nexport const NOTIFICATION_TYPE_LABELS: Record<AglynNotificationType, string> = {\n 'billing.invoice': 'Invoice available',\n 'billing.paymentFailed': 'Payment failed',\n 'billing.subscriptionCanceled': 'Subscription canceled',\n 'billing.usage': 'Usage threshold',\n 'team.invite': 'Team invite',\n 'team.roleChanged': 'Role changed',\n 'team.hostAccessGranted': 'Site access granted',\n 'content.formSubmission': 'Form submission',\n 'content.booking': 'New booking',\n 'content.order': 'New order',\n 'content.lowStock': 'Low stock',\n 'content.taskAssigned': 'Task assigned to you',\n 'content.taskReminder': 'Task reminder',\n 'content.contactAssigned': 'Contact assigned to you',\n 'content.leadAssigned': 'Lead assigned to you',\n 'content.crmDailyDigest': 'Daily CRM digest',\n 'content.insightsDigest': 'Weekly insights',\n 'content.aiJobNeedsYou': 'AI job needs you',\n 'content.aiJobDone': 'AI job finished',\n 'content.aiJobFailed': 'AI job stopped',\n 'marketplace.review': 'Listing review',\n\n 'support.ticketOpened': 'New support ticket',\n 'support.ticketReply': 'Support ticket reply',\n 'system.announcement': 'Announcement',\n 'system.pluginVerifierRegression': 'Plugin verifier regression',\n 'system.signInMethodRemoved': 'Sign-in method removed',\n 'system.scopeDrift': 'Resources missing a sharing scope',\n 'system.ssoDomainUnverified': 'SSO domain no longer proves ownership',\n 'system.formSubmissionsPaused': 'Form submissions paused',\n 'system.visitorRecordsPaused': 'Sign-ups or leads paused',\n 'system.abuseReportUrgent': 'Urgent abuse report',\n 'system.riskNotice': 'Held, flagged or locked on your workspace',\n 'system.dmcaCounterNotice': 'DMCA counter-notice',\n 'system.bandwidthCeilingTripped': 'Bandwidth ceiling reached',\n 'system.bandwidthCapEngaged': 'Monthly traffic limit reached',\n 'system.billingWebhookHalfApplied': 'Billing webhook half applied',\n 'system.disputeUnattributed': 'Card dispute with no owner',\n 'system.operatorAlert': 'Operator alert',\n 'staff.userSignedUp': 'New account',\n 'staff.orgCreated': 'New workspace',\n 'staff.siteCreated': 'New site',\n 'staff.subscriptionStarted': 'New subscription',\n 'staff.subscriptionCanceled': 'Subscription canceled',\n 'staff.planChanged': 'Plan changed',\n 'staff.paymentFailed': 'Payment failed (workspace)',\n}\n\n/**\n * HOW LOUD A NOTIFICATION IS (AGL-3437), which the console draws as its\n * color, icon and accent.\n *\n * - `critical` — something stopped, money is moving with nobody looking, or\n * fraud: a fraud signal, a failed payment, a form that stopped accepting.\n * - `warning` — something degraded or is close to stopping: a health check\n * degraded, a limit reached, low stock.\n * - `success` — good news: an account, a workspace or a subscription\n * started, an order or a booking arrived, a health check recovered.\n * - `info` — worth reading, nothing wrong: an invite, a ticket reply, a\n * usage step on the way to a limit.\n * - `neutral` — routine work arriving: a form submission, an assignment, a\n * digest.\n *\n * A level is a property of the NOTIFICATION, not only of its type: one\n * `system.operatorAlert` says a check degraded and the next says it\n * recovered, and a usage notice at 75% is not the one at 100%. The emitter\n * stamps `level` when it knows more than the type; the type's default in\n * {@link NOTIFICATION_TYPE_LEVELS} answers for everything else.\n */\nexport type NotificationLevel =\n | 'critical'\n | 'warning'\n | 'success'\n | 'info'\n | 'neutral'\n\n/** Every level, loudest first — the order {@link loudestNotificationLevel} ranks by. */\nexport const NOTIFICATION_LEVELS: readonly NotificationLevel[] = [\n 'critical',\n 'warning',\n 'success',\n 'info',\n 'neutral',\n]\n\nexport const NOTIFICATION_LEVEL_LABELS: Record<NotificationLevel, string> = {\n critical: 'Critical',\n warning: 'Warning',\n success: 'Good news',\n info: 'Info',\n neutral: 'Routine',\n}\n\n/**\n * Each core type's level when its emitter stamps none. A plugin's types are\n * not listed: a plugin emitter stamps `level` itself, and an unstamped one\n * reads as `neutral`.\n *\n * A type the operator alert registry raises under its own notification type\n * must agree with that alert's level, so the backlog written before `level`\n * existed reads the same as what the registry writes today\n * (`notification-levels.spec.ts` holds the two together).\n */\nexport const NOTIFICATION_TYPE_LEVELS: Record<\n AglynNotificationType,\n NotificationLevel\n> = {\n 'billing.invoice': 'neutral',\n 'billing.paymentFailed': 'critical',\n 'billing.subscriptionCanceled': 'critical',\n // At a limit. A step on the way to it is stamped `info` by its emitter.\n 'billing.usage': 'warning',\n 'team.invite': 'info',\n 'team.roleChanged': 'info',\n 'team.hostAccessGranted': 'info',\n 'content.formSubmission': 'neutral',\n 'content.booking': 'success',\n 'content.order': 'success',\n 'content.lowStock': 'warning',\n 'content.taskAssigned': 'neutral',\n 'content.taskReminder': 'info',\n 'content.contactAssigned': 'neutral',\n 'content.leadAssigned': 'neutral',\n 'content.crmDailyDigest': 'neutral',\n 'content.insightsDigest': 'neutral',\n // A plan waits for the person; nothing is built until they confirm it.\n 'content.aiJobNeedsYou': 'warning',\n 'content.aiJobDone': 'success',\n 'content.aiJobFailed': 'warning',\n 'marketplace.review': 'info',\n 'support.ticketOpened': 'info',\n 'support.ticketReply': 'info',\n 'system.announcement': 'info',\n 'system.pluginVerifierRegression': 'warning',\n 'system.signInMethodRemoved': 'warning',\n 'system.scopeDrift': 'info',\n 'system.ssoDomainUnverified': 'warning',\n 'system.formSubmissionsPaused': 'critical',\n 'system.visitorRecordsPaused': 'critical',\n 'system.abuseReportUrgent': 'critical',\n 'system.riskNotice': 'critical',\n 'system.dmcaCounterNotice': 'critical',\n 'system.bandwidthCeilingTripped': 'warning',\n // The site is serving the capped notice to its visitors.\n 'system.bandwidthCapEngaged': 'critical',\n 'system.billingWebhookHalfApplied': 'critical',\n 'system.disputeUnattributed': 'critical',\n // The registry stamps each alert's own level; this answers only for one\n // written before it did.\n 'system.operatorAlert': 'warning',\n 'staff.userSignedUp': 'success',\n 'staff.orgCreated': 'success',\n 'staff.siteCreated': 'success',\n 'staff.subscriptionStarted': 'success',\n 'staff.subscriptionCanceled': 'warning',\n 'staff.planChanged': 'info',\n 'staff.paymentFailed': 'warning',\n}\n\nconst LEVEL_SET: ReadonlySet<string> = new Set(NOTIFICATION_LEVELS)\n\n/** Whether a stored value is a level this build knows. */\nexport function isNotificationLevel(value: unknown): value is NotificationLevel {\n return typeof value === 'string' && LEVEL_SET.has(value)\n}\n\n/**\n * A notification's level: what its emitter stamped, else its type's\n * default, else `neutral`. A stamped value this build does not know — a\n * level added later, read by an older console — falls back the same way\n * rather than drawing nothing.\n */\nexport function notificationLevel(\n notification: { type?: string; level?: unknown } | null | undefined,\n): NotificationLevel {\n const stamped = notification?.level\n if (isNotificationLevel(stamped)) return stamped\n const byType = (NOTIFICATION_TYPE_LEVELS as Record<string, NotificationLevel>)[\n notification?.type ?? ''\n ]\n return byType ?? 'neutral'\n}\n\n/**\n * A usage notice's level at `percent` of its allowance: `info` on a step\n * toward it, `warning` once it is reached. Every usage, budget and allotment\n * notice says the same thing at the same step, so they share this.\n */\nexport function usageNotificationLevel(percent: number): NotificationLevel {\n return percent >= 100 ? 'warning' : 'info'\n}\n\n/** The loudest of several levels, or `neutral` for none. */\nexport function loudestNotificationLevel(\n levels: Iterable<NotificationLevel>,\n): NotificationLevel {\n let best = NOTIFICATION_LEVELS.length - 1\n for (const level of levels) {\n const rank = NOTIFICATION_LEVELS.indexOf(level)\n if (rank >= 0 && rank < best) best = rank\n }\n return NOTIFICATION_LEVELS[best]\n}\n\n/**\n * The preference buckets the platform owns (AGL-267): the prefix before the\n * dot. A plugin adds its own through {@link NotificationCategoryDeclaration},\n * so this union is the core's and nothing else's.\n */\nexport type CoreNotificationCategory =\n | 'billing'\n | 'team'\n | 'content'\n | 'support'\n | 'system'\n // Staff-only, and shown only to staff (AGL-3225) — see\n // {@link STAFF_NOTIFICATION_CATEGORIES}.\n | 'staff'\n\n/**\n * A preference bucket: one of the core's, or one a first-party plugin\n * declares. The id is persisted — it keys every stored preference map — so a\n * declared id keeps its meaning only while its declaration keeps its spelling.\n */\nexport type NotificationCategory = CoreNotificationCategory | (string & {})\n\n/**\n * A notification category a plugin declares for the notifications it sends\n * (AGL-3080), under `notificationCategories` in `plugins.config.json`.\n *\n * Compiled rather than registered: `notifyUsers` resolves a recipient's\n * channels in server processes that load no plugin, and the settings page\n * draws its rows before any plugin could register. A category that had to\n * wait for its plugin would read as `system` until then — so a person who had\n * muted it would be told, and a person who had asked for its email would not.\n * The generator refuses an id the core owns or another plugin declares.\n */\nexport interface NotificationCategoryDeclaration {\n /** The plugin whose notifications carry this prefix. */\n pluginId: string\n /** The type prefix, and the key every stored preference is written under. */\n id: string\n /** The row's name on the settings page. */\n label: string\n /** What arrives under it, in the reader's words — see {@link NOTIFICATION_CATEGORY_DESCRIPTIONS}. */\n description: string\n /** What each channel does before anybody says — see {@link NOTIFICATION_CHANNEL_DEFAULTS}. */\n defaults: Record<NotificationChannel, boolean>\n}\n\n/**\n * The declared categories, in the order the settings page lists them: after\n * the workspace's own work and before the platform's notices, which is where\n * a plugin's traffic sits in a reader's day.\n */\nconst DECLARED_CATEGORIES: readonly NotificationCategoryDeclaration[] =\n PLUGIN_NOTIFICATION_CATEGORIES_DECLARED\n\n/**\n * The core's rows listed before the declared ones. Every other core category\n * follows them, in the order its `Record` spells it, so a new core category\n * cannot be left off the page.\n */\nconst LEADING_CATEGORIES: readonly CoreNotificationCategory[] = [\n 'billing',\n 'team',\n 'content',\n]\n\nfunction inCategoryOrder<T>(\n core: Record<CoreNotificationCategory, T>,\n declared: (declaration: NotificationCategoryDeclaration) => T,\n): Readonly<Record<NotificationCategory, T>> {\n // Every core id is written below, so the keys the type promises are there.\n const out = {} as Record<NotificationCategory, T>\n for (const id of LEADING_CATEGORIES) out[id] = core[id]\n for (const declaration of DECLARED_CATEGORIES) {\n out[declaration.id] = declared(declaration)\n }\n for (const id of Object.keys(core) as CoreNotificationCategory[]) {\n if (!LEADING_CATEGORIES.includes(id)) out[id] = core[id]\n }\n return out\n}\n\nconst CORE_CATEGORY_LABELS: Record<CoreNotificationCategory, string> = {\n billing: 'Billing',\n team: 'Team & access',\n content: 'Forms & bookings',\n support: 'Support',\n system: 'Product & system',\n staff: 'Platform growth',\n}\n\n/** Every category's row name, the core's and the declared, in page order. */\nexport const NOTIFICATION_CATEGORY_LABELS = inCategoryOrder(\n CORE_CATEGORY_LABELS,\n (declaration) => declaration.label,\n)\n\n/**\n * The categories only staff can receive (AGL-3225).\n *\n * The settings page hides these rows from everybody else, because a switch\n * for mail that can never arrive is a promise the product does not keep. It\n * is presentation only: `notifyStaff` is what decides the audience, and it\n * enumerates the `staff` claim rather than reading this.\n */\nexport const STAFF_NOTIFICATION_CATEGORIES: ReadonlySet<NotificationCategory> =\n new Set<NotificationCategory>(['staff'])\n\n/**\n * What each category actually covers, in the reader's words (AGL-3251).\n *\n * The settings page listed seven bare labels and two switches, so deciding\n * whether to silence `Product & system` meant guessing what was in it. The\n * type labels beneath each row now name the contents exactly; this is the\n * one-line answer for somebody who does not want to expand anything.\n *\n * Written as what ARRIVES rather than as what the bucket is called: \"someone\n * joins, a role changes\" is checkable against your own feed in a way that\n * \"team and access events\" is not. Exhaustive over the core's categories,\n * like the channel defaults below, and required of every declaration — a new\n * category cannot ship without somebody saying in plain words what lands in\n * it.\n */\nconst CORE_CATEGORY_DESCRIPTIONS: Record<CoreNotificationCategory, string> = {\n billing:\n 'Invoices, failed payments, cancellations, and usage that crosses a plan limit.',\n team: 'Somebody joins or leaves, a role changes, or a site is shared with you.',\n content:\n 'Work arriving on your sites: form submissions, bookings, orders, low stock, and the tasks and leads assigned to you.',\n support: 'New support tickets and replies on tickets you are following.',\n system:\n 'Announcements, and the faults the platform finds in your account: sign-in methods removed, traffic limits reached, billing or sharing left in a broken state.',\n staff:\n 'New accounts, new workspaces, and money moving — subscriptions starting, changing, failing and ending — across the whole platform. Only staff receive these.',\n}\n\nexport const NOTIFICATION_CATEGORY_DESCRIPTIONS = inCategoryOrder(\n CORE_CATEGORY_DESCRIPTIONS,\n (declaration) => declaration.description,\n)\n\n/**\n * The bucket a type falls in: its prefix, when a category of that id exists,\n * and `system` otherwise — the bucket nobody mutes to reduce noise, so a type\n * nothing claims still reaches the person rather than riding a mute they set\n * for something else.\n */\nexport function notificationCategory(\n type: AglynNotificationType | string,\n): NotificationCategory {\n const prefix = String(type).split('.')[0]\n return Object.prototype.hasOwnProperty.call(\n NOTIFICATION_CATEGORY_LABELS,\n prefix,\n )\n ? prefix\n : 'system'\n}\n\n/**\n * Per-user mute map stored at `users/{uid}.notificationPrefs`\n * (`{ [category]: false }` mutes); absent categories stay on.\n */\nexport function notificationMuted(\n prefs: Record<string, boolean> | null | undefined,\n type: AglynNotificationType | string,\n): boolean {\n return prefs?.[notificationCategory(type)] === false\n}\n\n/**\n * The field on `users/{uid}` that holds a person's digest switches\n * (AGL-2619): `{ [digestKey]: false }` turns one digest off, and an absent key\n * leaves it on. Its own map rather than a key in `notificationPrefs`, because\n * that map is keyed by CATEGORY and read by {@link notificationMuted} — a\n * digest is a schedule a person keeps or drops, not a bucket of types, and one\n * switch governs both the console notification and the email it travels with.\n */\nexport const DIGEST_PREFS_FIELD = 'digestPrefs'\n\n/**\n * A digest a plugin sends on its own schedule (AGL-3080), declared under\n * `notificationDigests` in `plugins.config.json` so the settings page can draw\n * its switch without loading the plugin, and the plugin's sender and that\n * switch read one key.\n *\n * On until the person turns it off: the key is stored in\n * {@link DIGEST_PREFS_FIELD} only once somebody has said no. The key is\n * persisted, so it keeps its spelling for as long as anybody's switch is\n * stored under it.\n */\nexport interface NotificationDigestDeclaration {\n /** The plugin that composes and sends it. */\n pluginId: string\n /** The key its switch is stored under in {@link DIGEST_PREFS_FIELD}. */\n key: string\n /** The switch's name. */\n label: string\n /** When it arrives and what it holds, in the reader's words. */\n description: string\n}\n\n/** Every declared digest, in the order the settings page lists them. */\nexport const NOTIFICATION_DIGESTS: readonly NotificationDigestDeclaration[] =\n PLUGIN_NOTIFICATION_DIGESTS_DECLARED\n\n/**\n * Whether a person keeps one digest: on unless its key is stored `false`. It\n * reads only its own key — a category mute lives in a different map and does\n * not reach it.\n */\nexport function digestEnabled(\n prefs: Record<string, boolean> | null | undefined,\n key: string,\n): boolean {\n return prefs?.[key] !== false\n}\n\n/**\n * The field on `users/{uid}` naming the workspaces whose weekly insights a\n * person asked for (AGL-2915): `{ [orgId]: true }`. OPT-IN, unlike the CRM\n * digest — an absent key is off — because a weekly insight is generated, and a\n * generation spends the workspace's credits. The person turns it on beside the\n * answers themselves, where the plan, the release and their permission have\n * already been checked, and off again there or in Notifications; the weekly\n * sweep checks all three again before it spends anything.\n */\nexport const INSIGHT_DIGESTS_FIELD = 'insightDigests'\n\n/** Whether a person asked for a workspace's weekly insights. */\nexport function insightDigestSubscribed(\n value: Record<string, boolean> | null | undefined,\n orgId: string,\n): boolean {\n return Boolean(orgId) && value?.[orgId] === true\n}\n\n/**\n * The channels a notification can travel on (AGL-3223).\n *\n * `console` is the feed at `/manage/notifications` and the app-bar dropdown\n * that reads it — the only channel that existed. `email` is the message the\n * fan-out sends beside that doc when the recipient asked for one.\n */\nexport type NotificationChannel = 'console' | 'email'\n\n/**\n * One scope's answer for one category. **Tri-state on purpose**: `true` and\n * `false` decide, and an ABSENT key inherits from the scope above.\n *\n * Inheritance is the whole reason this is a partial rather than a pair of\n * booleans. A person who wants form submissions from one busy site and not\n * from the other five has to be able to say that about the one site without\n * restating their answer for every other category at every other scope — and\n * a two-valued leaf cannot express \"I have not said\", so every override would\n * have to be written out in full and would then stop tracking the account\n * default it was never meant to detach from.\n */\nexport interface NotificationChannelPrefs {\n console?: boolean\n email?: boolean\n}\n\nexport type NotificationCategoryPrefs = Partial<\n Record<NotificationCategory, NotificationChannelPrefs>\n>\n\n/**\n * One scope's answer for a single notification TYPE (AGL-3251), tri-state on\n * the same terms as {@link NotificationChannelPrefs}: an absent key falls\n * through to the category.\n *\n * Its own map rather than extra keys in {@link NotificationCategoryPrefs},\n * because that one is an exhaustive record keyed by category and a type key\n * inside it would type-check only by widening the thing that makes a missing\n * category a compile error.\n */\nexport type NotificationTypePrefs = Partial<\n Record<AglynNotificationType, NotificationChannelPrefs>\n>\n\n/**\n * Per-scope, per-channel notification preferences (AGL-3223), stored at\n * `users/{uid}.notificationSettings`.\n *\n * Three layers, narrowest first when resolving: the SITE a notification\n * concerns, then the WORKSPACE, then the account. Anything none of them\n * answers falls to {@link NOTIFICATION_CHANNEL_DEFAULTS}.\n *\n * ON THE USER DOCUMENT, not on `orgs/{orgId}/members/{uid}`, and that is a\n * cost decision rather than a modelling preference. `notifyUsers` already\n * does exactly one `getAll` over the recipients' user docs to read their\n * category mutes, so every layer living here means per-site preferences are\n * read for free on the fan-out's hot path. The member row would add a read\n * per recipient per notification to answer a question the document already in\n * hand could have answered.\n */\nexport interface NotificationSettings {\n account?: NotificationCategoryPrefs\n /**\n * Per-TYPE answers at the account scope (AGL-3251), consulted before\n * {@link NotificationSettings.account}'s category answer and never above a\n * narrower scope — see {@link notificationChannelEnabled}.\n *\n * ACCOUNT ONLY, deliberately. The per-workspace and per-site card is\n * already seven categories by three states by two channels, and a type row\n * for each of the ~thirty types, per workspace AND per site, is a page\n * nobody can read — which is the complaint this whole issue started as.\n * The account scope is where \"stop telling me about THIS\" belongs anyway:\n * it is a statement about the kind of thing, and kinds do not vary by site.\n */\n accountTypes?: NotificationTypePrefs\n /** Keyed by org id. */\n orgs?: Record<string, NotificationCategoryPrefs>\n /** Keyed by host id — a site's own answer, narrower than its workspace's. */\n hosts?: Record<string, NotificationCategoryPrefs>\n /**\n * Per-TYPE answers at the workspace and site scopes (AGL-3267), beside the\n * category maps above rather than nested inside them.\n *\n * Parallel maps because the category maps are already stored under `orgs`\n * and `hosts` on live user documents: folding both into one\n * `{ categories, types }` object per scope would be a migration of every\n * preference anybody has set, to express something two more keys express\n * without touching a byte of what exists.\n *\n * This supersedes the account-only limit AGL-3251 shipped under. That was\n * the right call for a card nobody had used yet and the wrong one once it\n * existed: \"quiet this one type down on this one busy site\" is the question\n * the scope card is FOR, and answering it only for whole categories made\n * the fine grain stop exactly where the noise is worst.\n */\n orgTypes?: Record<string, NotificationTypePrefs>\n hostTypes?: Record<string, NotificationTypePrefs>\n}\n\nexport const NOTIFICATION_SETTINGS_FIELD = 'notificationSettings'\n\n/**\n * What a category does when nobody has said otherwise.\n *\n * Console on, email OFF, everywhere. Email defaults off because the inbox is\n * not ours to fill: the product already sends transactional mail nobody opted\n * into — welcome, verification, invites, dunning, usage alerts — and every one\n * of those leaves on the same domain a customer's password reset depends on.\n * Turning a busy site's form submissions into mail by default would put that\n * domain's reputation behind traffic the recipient never asked for.\n *\n * Exhaustive over the core's categories deliberately: a new\n * {@link CoreNotificationCategory} is a compile error here until somebody\n * decides what it does by default, which is the one question a new category\n * must not be able to ship without answering — and a declared category may not\n * compile without its `defaults` for the same reason.\n */\nconst CORE_CHANNEL_DEFAULTS: Record<\n CoreNotificationCategory,\n Record<NotificationChannel, boolean>\n> = {\n billing: { console: true, email: false },\n team: { console: true, email: false },\n content: { console: true, email: false },\n support: { console: true, email: false },\n system: { console: true, email: false },\n // Console ON, because the complaint this answers is that staff never heard\n // about a sign-up at all; email off, like everything else, because that is\n // what the channel defaults to and a sign-up is not urgent enough to be the\n // exception that starts filling inboxes by default.\n staff: { console: true, email: false },\n}\n\nexport const NOTIFICATION_CHANNEL_DEFAULTS = inCategoryOrder(\n CORE_CHANNEL_DEFAULTS,\n (declaration) => ({ ...declaration.defaults }),\n)\n\n/**\n * The types that send their OWN email and must never be mailed again by the\n * generic channel (AGL-3224).\n *\n * Both digests compose a message the fan-out could not reproduce — a day's\n * owed tasks, a week's figures — and send it from their own route under their\n * own switch (a key in `digestPrefs`, `insightDigests.{orgId}`). A recipient\n * who switches the `content` email channel on would otherwise receive the\n * digest twice: once as the digest, once as a one-line \"Daily CRM digest\"\n * notification saying that the digest happened.\n */\nexport const NOTIFICATION_SELF_SENT_EMAIL_TYPES: ReadonlySet<string> =\n new Set<AglynNotificationType>([\n 'content.crmDailyDigest',\n 'content.insightsDigest',\n // The task-reminders route mails one reminder per member per run, listing\n // every task due, and writes one notification per task; mailed again\n // here, each task would arrive a second time as its own email (AGL-3432).\n 'content.taskReminder',\n // Emailed by `notifyRiskEvent` itself, as account mail (AGL-3368).\n 'system.riskNotice',\n ])\n\n/**\n * The tooltip on a self-sent type's disabled email switch: it names what\n * DOES govern that mail, which differs by type (AGL-3432). Calling a task\n * reminder a digest sent people looking for a Digests switch that is not it.\n */\nexport function selfSentEmailNote(type: string): string {\n switch (type) {\n case 'content.taskReminder':\n return 'Task reminders send their own email, one per run listing every task due. Mute this category to stop them.'\n case 'system.riskNotice':\n return 'Risk and account notices are always emailed, whatever this switch says.'\n default:\n return 'This digest sends its own email, under its switch in Digests.'\n }\n}\n\n/**\n * Whether a channel is on for one notification, at its own scope.\n *\n * Resolution order, first answer wins: the notification's SITE, its\n * WORKSPACE, the account, then {@link NOTIFICATION_CHANNEL_DEFAULTS}. A scope\n * that holds no entry for the category, or an entry with the channel key\n * absent, does not answer — see {@link NotificationChannelPrefs}.\n *\n * `legacyPrefs` is the flat `notificationPrefs` mute map this replaces\n * (AGL-267), and it sits BELOW the account layer rather than beside it.\n * Nothing migrates it: a person who never opens the new settings page keeps\n * being governed by the mutes they set years ago, and the first thing they do\n * set on the account layer overrides the old map for that category without\n * disturbing the rest of it. It answers for `console` only, because the map\n * predates there being a second channel and reading a console mute as an\n * email preference would be inventing an answer its author never gave.\n */\nexport function notificationChannelEnabled(\n settings: NotificationSettings | null | undefined,\n channel: NotificationChannel,\n type: AglynNotificationType | string,\n scope?: { orgId?: string | null; hostId?: string | null },\n legacyPrefs?: Record<string, boolean> | null,\n): boolean {\n const category = notificationCategory(type)\n /*\n * ⛔ A STAFF NOTIFICATION HAS NO SCOPE TO BE NARROWED BY (AGL-3267).\n *\n * It is about the platform, and the workspace one MENTIONS is its subject,\n * not its audience: the staff member reading \"Acme Co subscribed\" is\n * almost never a member of Acme Co, and if they happen to be, their\n * preferences for their own membership have nothing to do with it.\n *\n * This was already true by accident — no staff emitter passes `orgId` or\n * `hostId`, so the scope layers never matched — which made every\n * \"Platform growth\" row in the per-workspace card a control that could be\n * set and could never do anything. Stating it here rather than only hiding\n * those rows is the difference between the model being right and the UI\n * covering for a model that is wrong: a `staff.*` type that ever does\n * start carrying an `orgId`, for its link or its subject line, must not\n * silently become mutable per workspace.\n */\n const staffWide = STAFF_NOTIFICATION_CATEGORIES.has(category)\n /*\n * Narrowest scope first, and within each scope the TYPE before its\n * CATEGORY (AGL-3251, widened to every scope by AGL-3267).\n *\n * Both halves matter and they answer different questions. Scope order is\n * \"where is this from\" — a site's answer beats its workspace's, which beats\n * the account's, because quietening one busy site is the thing the scope\n * card exists for. Type-before-category is \"what kind of thing is this\" —\n * somebody who switched `Payment failed` off said something about that\n * type, and it must beat their own broader `Billing` answer at the SAME\n * scope without leaking upward past a narrower one.\n */\n const layers: Array<NotificationChannelPrefs | undefined> = staffWide\n ? [\n settings?.accountTypes?.[type as AglynNotificationType],\n settings?.account?.[category],\n ]\n : [\n scope?.hostId\n ? settings?.hostTypes?.[scope.hostId]?.[type as AglynNotificationType]\n : undefined,\n scope?.hostId ? settings?.hosts?.[scope.hostId]?.[category] : undefined,\n scope?.orgId\n ? settings?.orgTypes?.[scope.orgId]?.[type as AglynNotificationType]\n : undefined,\n scope?.orgId ? settings?.orgs?.[scope.orgId]?.[category] : undefined,\n settings?.accountTypes?.[type as AglynNotificationType],\n settings?.account?.[category],\n ]\n for (const layer of layers) {\n const answer = layer?.[channel]\n if (typeof answer === 'boolean') return answer\n }\n if (channel === 'console' && notificationMuted(legacyPrefs, type))\n return false\n return NOTIFICATION_CHANNEL_DEFAULTS[category][channel]\n}\n\n/**\n * What one scope says, with no inheritance applied — what the settings page\n * renders as Inherit / On / Off, and `undefined` is Inherit.\n *\n * `scope` names the layer directly rather than being derived from a\n * notification, because the page edits a layer whether or not anything has\n * ever arrived from it.\n */\n/**\n * What the account scope says about one TYPE, with no inheritance applied\n * (AGL-3251) — `undefined` means the row follows its category.\n *\n * The page needs the unresolved answer to draw the difference between \"on\n * because Billing is on\" and \"on because you said so\": only the second can be\n * reset, and a switch that cannot show which one it is leaves a person unable\n * to get back to following the category.\n */\nexport function notificationAccountTypePref(\n settings: NotificationSettings | null | undefined,\n type: AglynNotificationType | string,\n channel: NotificationChannel,\n): boolean | undefined {\n return settings?.accountTypes?.[type as AglynNotificationType]?.[channel]\n}\n\n/**\n * Every type in a category, in the order the labels declare them\n * (AGL-3251) — what the settings page expands a category row into.\n *\n * Derived from {@link NOTIFICATION_TYPE_LABELS} rather than held as a second\n * map, so a type added there appears under its category without anybody\n * remembering to list it twice.\n */\nexport function notificationTypesInCategory(\n category: NotificationCategory,\n): AglynNotificationType[] {\n return (\n Object.keys(NOTIFICATION_TYPE_LABELS) as AglynNotificationType[]\n ).filter((type) => notificationCategory(type) === category)\n}\n\n/**\n * What ONE scope says about ONE type, with no inheritance applied\n * (AGL-3267) — `undefined` means the row follows its category at that scope.\n *\n * The scope-aware sibling of {@link notificationAccountTypePref}, which stays\n * as the account-only shorthand its callers already use.\n */\nexport function notificationScopeTypePref(\n settings: NotificationSettings | null | undefined,\n scope: { kind: 'account' } | { kind: 'org' | 'host'; id: string },\n type: AglynNotificationType | string,\n channel: NotificationChannel,\n): boolean | undefined {\n const layer =\n scope.kind === 'account'\n ? settings?.accountTypes\n : scope.kind === 'org'\n ? settings?.orgTypes?.[scope.id]\n : settings?.hostTypes?.[scope.id]\n return layer?.[type as AglynNotificationType]?.[channel]\n}\n\nexport function notificationScopePref(\n settings: NotificationSettings | null | undefined,\n scope: { kind: 'account' } | { kind: 'org' | 'host'; id: string },\n category: NotificationCategory,\n channel: NotificationChannel,\n): boolean | undefined {\n const layer =\n scope.kind === 'account'\n ? settings?.account\n : scope.kind === 'org'\n ? settings?.orgs?.[scope.id]\n : settings?.hosts?.[scope.id]\n return layer?.[category]?.[channel]\n}\n\n/**\n * The scopes this person has said something different about — what the\n * settings page lists so an override is never somewhere you have to go\n * looking for.\n *\n * Returns ids, not names: the page holds the org and host rosters and this\n * module holds no lookups. An id with no name is still worth listing, because\n * a preference about a workspace somebody left is exactly the kind of\n * leftover that is invisible until it is listed.\n */\nexport function notificationOverriddenScopes(\n settings: NotificationSettings | null | undefined,\n): { orgIds: string[]; hostIds: string[] } {\n /*\n * BOTH maps for a scope, categories and types (AGL-3267).\n *\n * Reading only the category map would make a scope whose ONLY answer is a\n * per-type one invisible here — and this list is the single place a person\n * can find an override they set months ago. Silencing one type on one busy\n * site and then being unable to find where you did it is precisely the\n * failure this function exists to prevent.\n */\n const answered = (prefs: Record<string, NotificationChannelPrefs> | undefined) =>\n Object.values(prefs ?? {}).some((channels) =>\n Object.values(channels ?? {}).some((value) => typeof value === 'boolean'),\n )\n const named = (\n categories: Record<string, NotificationCategoryPrefs> | undefined,\n types: Record<string, NotificationTypePrefs> | undefined,\n ) =>\n [\n ...new Set([\n ...Object.keys(categories ?? {}),\n ...Object.keys(types ?? {}),\n ]),\n ]\n .filter(\n (id) =>\n answered(categories?.[id] as Record<string, NotificationChannelPrefs>) ||\n answered(types?.[id] as Record<string, NotificationChannelPrefs>),\n )\n .sort()\n return {\n orgIds: named(settings?.orgs, settings?.orgTypes),\n hostIds: named(settings?.hosts, settings?.hostTypes),\n }\n}\n\n/**\n * Rewrites a stored notification link onto the current URL scheme (AGL-644).\n *\n * A notification's `link` is frozen at write time — `notifyUsers` persists\n * whatever string the emitter passed and never normalizes it. So every\n * notification written before the org-slug migration (AGL-621) and the\n * subdomain migration (AGL-622) still points at a route that no longer\n * exists, and fixing the emitters alone would leave that whole backlog dead.\n * Normalizing when the link is FOLLOWED repairs old and new alike, and keeps\n * working for emitters that haven't been migrated yet.\n *\n * Rewrites, in order — each prefix also followed by a query string, as\n * `/{hostDocId}?aiJob={id}` (AGL-3593):\n * - `/{hostDocId}` or `/{hostDocId}/rest` → `/{orgSlug}/hosts/{subdomain}/rest`\n * - `/org` or `/org/rest` → `/{orgSlug}/rest`\n * - `/hosts` (exactly) → `/{orgSlug}/hosts`\n *\n * Anything already canonical, user-scoped (`/manage/...`), staff (`/admin/...`)\n * or absolute is returned untouched. Every rewrite is gated on having the\n * context it needs, so an unresolvable link degrades to its stored value\n * rather than to a wrong destination.\n *\n * The host rewrite is keyed on the notification's own `hostId` rather than\n * guessing from the path shape, so it can never mistake a real first segment\n * for a doc id.\n *\n * The email copy of a notification goes through it too (AGL-3367): a button\n * in an inbox is a followed link with no console around it to repair it.\n */\nexport function normalizeNotificationLink(\n link: string | undefined | null,\n context: {\n orgSlug?: string | null\n /** The notification's `hostId` (a Firestore doc id). */\n hostId?: string | null\n /** That host's subdomain, which the current routes are keyed by. */\n hostSubdomain?: string | null\n },\n): string | undefined {\n if (!link) return undefined\n // Absolute URLs (staff broadcasts can carry them) are not ours to rewrite.\n if (!link.startsWith('/')) return link\n\n const { orgSlug, hostId, hostSubdomain } = context\n\n if (orgSlug && hostId && hostSubdomain) {\n const prefix = `/${hostId}`\n if (link === prefix || link.startsWith(`${prefix}/`) || link.startsWith(`${prefix}?`)) {\n return `${buildRoute(Route.HOST_DASHBOARD, {\n orgSlug,\n host: hostSubdomain,\n })}${link.slice(prefix.length)}`\n }\n }\n\n if (orgSlug) {\n if (link === '/org' || link.startsWith('/org/') || link.startsWith('/org?')) {\n return `${buildRoute(Route.ORG_HOME, { orgSlug })}${link.slice(\n '/org'.length,\n )}`\n }\n // Only the bare list — `/hosts/{docId}` would still need a subdomain, and\n // guessing one is worse than leaving the link alone.\n if (link === '/hosts') return buildRoute(Route.HOST_LIST, { orgSlug })\n }\n\n return link\n}\n"],"names":["buildRoute","Route","PLUGIN_NOTIFICATION_CATEGORIES_DECLARED","PLUGIN_NOTIFICATION_DIGESTS_DECLARED","NOTIFICATION_TYPE_LABELS","NOTIFICATION_LEVELS","NOTIFICATION_LEVEL_LABELS","critical","warning","success","info","neutral","NOTIFICATION_TYPE_LEVELS","LEVEL_SET","Set","isNotificationLevel","value","has","notificationLevel","notification","stamped","level","byType","type","usageNotificationLevel","percent","loudestNotificationLevel","levels","best","length","rank","indexOf","DECLARED_CATEGORIES","LEADING_CATEGORIES","inCategoryOrder","core","declared","out","id","declaration","Object","keys","includes","CORE_CATEGORY_LABELS","billing","team","content","support","system","staff","NOTIFICATION_CATEGORY_LABELS","label","STAFF_NOTIFICATION_CATEGORIES","CORE_CATEGORY_DESCRIPTIONS","NOTIFICATION_CATEGORY_DESCRIPTIONS","description","notificationCategory","prefix","String","split","prototype","hasOwnProperty","call","notificationMuted","prefs","DIGEST_PREFS_FIELD","NOTIFICATION_DIGESTS","digestEnabled","key","INSIGHT_DIGESTS_FIELD","insightDigestSubscribed","orgId","Boolean","NOTIFICATION_SETTINGS_FIELD","CORE_CHANNEL_DEFAULTS","console","email","NOTIFICATION_CHANNEL_DEFAULTS","defaults","NOTIFICATION_SELF_SENT_EMAIL_TYPES","selfSentEmailNote","notificationChannelEnabled","settings","channel","scope","legacyPrefs","category","staffWide","layers","accountTypes","account","hostId","hostTypes","undefined","hosts","orgTypes","orgs","layer","answer","notificationAccountTypePref","notificationTypesInCategory","filter","notificationScopeTypePref","kind","notificationScopePref","notificationOverriddenScopes","answered","values","some","channels","named","categories","types","sort","orgIds","hostIds","normalizeNotificationLink","link","context","startsWith","orgSlug","hostSubdomain","HOST_DASHBOARD","host","slice","ORG_HOME","HOST_LIST"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAGD,SAASA,UAAU,EAAEC,KAAK,QAAQ,sBAAkB;AACpD,SACEC,uCAAuC,EACvCC,oCAAoC,QAC/B,qDAAiD;AAmSxD,OAAO,MAAMC,2BAAkE;IAC7E,mBAAmB;IACnB,yBAAyB;IACzB,gCAAgC;IAChC,iBAAiB;IACjB,eAAe;IACf,oBAAoB;IACpB,0BAA0B;IAC1B,0BAA0B;IAC1B,mBAAmB;IACnB,iBAAiB;IACjB,oBAAoB;IACpB,wBAAwB;IACxB,wBAAwB;IACxB,2BAA2B;IAC3B,wBAAwB;IACxB,0B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,GAAGH;IAE3C,IAAIE,WAAW7B,UAAU8B,eAAe;QACtC,MAAMhE,SAAS,CAAC,CAAC,EAAEkC,QAAQ;QAC3B,IAAI0B,SAAS5D,UAAU4D,KAAKE,UAAU,CAAC,GAAG9D,OAAO,CAAC,CAAC,KAAK4D,KAAKE,UAAU,CAAC,GAAG9D,OAAO,CAAC,CAAC,GAAG;YACrF,OAAO,GAAGzD,WAAWC,MAAMyH,cAAc,EAAE;gBACzCF;gBACAG,MAAMF;YACR,KAAKJ,KAAKO,KAAK,CAACnE,OAAO5B,MAAM,GAAG;QAClC;IACF;IAEA,IAAI2F,SAAS;QACX,IAAIH,SAAS,UAAUA,KAAKE,UAAU,CAAC,YAAYF,KAAKE,UAAU,CAAC,UAAU;YAC3E,OAAO,GAAGvH,WAAWC,MAAM4H,QAAQ,EAAE;gBAAEL;YAAQ,KAAKH,KAAKO,KAAK,CAC5D,OAAO/F,MAAM,GACZ;QACL;QACA,0EAA0E;QAC1E,qDAAqD;QACrD,IAAIwF,SAAS,UAAU,OAAOrH,WAAWC,MAAM6H,SAAS,EAAE;YAAEN;QAAQ;IACtE;IAEA,OAAOH;AACT"}
1
+ {"version":3,"sources":["../../../../../../libs/aglyn/src/lib/app-utils/notifications.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { ITimestamp } from '@aglyn/shared-util-timestamp'\nimport { buildRoute, Route } from './console-routes'\nimport {\n PLUGIN_NOTIFICATION_CATEGORIES_DECLARED,\n PLUGIN_NOTIFICATION_DIGESTS_DECLARED,\n} from '../plugin-manager/first-party-plugins.generated'\n\n/**\n * In-app notifications (AGL-259): per-user docs at\n * `users/{uid}/notifications/{id}`, written by the Admin SDK (emitters in\n * the API routes + the `notifyAdmins` automation step) and read/marked by\n * their owner. Types follow the common SaaS taxonomy so the console can\n * icon/group them without a registry.\n */\nexport type AglynNotificationType =\n | 'billing.invoice'\n | 'billing.paymentFailed'\n // Stripe gave up on a failed renewal and CANCELLED the subscription\n // (AGL-1877). Distinct from `paymentFailed`, which announces one failed\n // attempt inside a retry window the customer can still recover from; this\n // one is the window having closed. Measured on the test account with a\n // test clock: five attempts over 21.08 days, then\n // `cancellation_details.reason: 'payment_failed'` — and until this existed\n // the org went silently to Free at that moment, with the `past_due` banner\n // disappearing at exactly the instant the consequence arrived.\n | 'billing.subscriptionCanceled'\n | 'billing.usage'\n | 'team.invite'\n | 'team.roleChanged'\n | 'team.hostAccessGranted'\n | 'content.formSubmission'\n | 'content.booking'\n | 'content.order'\n | 'content.lowStock'\n // A CRM task was assigned to the recipient by somebody else (AGL-2599).\n // `content.` because it is the same kind of message as a form submission\n // or a booking: a thing on the site that now needs this person's hands,\n // not a change to their standing (`team.`) and not a platform notice\n // (`system.`). Someone who has muted the operational stream has said they\n // do not want to be told about work as it arrives, and a task is work.\n | 'content.taskAssigned'\n // A CRM task's reminder came due (AGL-2659): the hourly runner telling\n // the assignee, at the task's own time, that the task is due. `content.`\n // beside `taskAssigned` for the same reason it gives — work on the site,\n // not standing — and so the one mute that stops \"work arriving\" stops\n // \"work falling due\" with it. The mute governs the whole reminder, mail\n // included, unlike the digest's: a reminder is one message about one\n // task, and there is no schedule to keep separately from it.\n | 'content.taskReminder'\n // A contact, or a lead, became the recipient's to work (AGL-2618): a\n // capture the assignment rules or the site's default owner routed to\n // them, a lead somebody converted and handed to them, or an automation's\n // \"assign an owner\" step — every server path that writes `ownerUid`\n // except the recipient assigning themselves. Two types rather than one\n // because the record the person opens differs: a lead is the site's own\n // working record and a contact is the org's, and the link goes to the\n // one they will actually work. `content.`, beside `taskAssigned`, for the\n // same reason: work arriving, not standing changing.\n | 'content.contactAssigned'\n | 'content.leadAssigned'\n // The morning's CRM digest (AGL-2619): what the recipient owes today —\n // overdue and due-today tasks, and the leads nobody has worked. `content.`\n // for the reason `taskAssigned` is: it is about work on the site, and the\n // person who muted the operational stream has asked not to be told about\n // work. The digest EMAIL is governed separately, by its switch in\n // `digestPrefs` (see `digestEnabled`): the mute is a fact about the console\n // feed and the digest switch is a fact about the digest.\n | 'content.crmDailyDigest'\n // The weekly insights (AGL-2915): what a site's figures showed that week,\n // for a person who asked for them. `content.` beside the CRM digest, for the\n // reason that one gives: it is about the site's work, and the operational\n // mute governs the console notification while the person's own switch for\n // the digest governs the digest.\n | 'content.insightsDigest'\n // An AI job the recipient started (AGL-3593): its plan is ready and waits\n // for them to confirm it, it finished and its drafts are ready to open, or\n // it stopped. Raised by the jobs machine where the job's state changes —\n // on the beat as often as in a request — to the person who created the\n // job, once per change. `content.` beside the insights digest: work on the\n // workspace's sites arriving for the person, which the operational mute\n // governs. The plan-ready one is how a person who left the dialog learns\n // their site is waiting on them.\n | 'content.aiJobNeedsYou'\n | 'content.aiJobDone'\n | 'content.aiJobFailed'\n // Marketplace review verdicts (AGL-432/653).\n | 'marketplace.review'\n // Support desk, staff audience (AGL-850): a subscriber opened or replied to\n // a ticket. Fanned out to staff-claim holders, not org members.\n | 'support.ticketOpened'\n | 'support.ticketReply'\n | 'system.announcement'\n // A live plugin version stopped passing the static verifier (AGL-1086).\n // Staff audience: bytes we told workspaces were checked now fail checks\n // that did not exist when they were approved.\n //\n // Deliberately NOT under `marketplace.` (AGL-1088). Category is the prefix,\n // categories are mutable per user, and Marketplace is the category a staff\n // member mutes to stop routine listing-review chatter — which would drop\n // this alert as collateral. `system` is the bucket nobody mutes to reduce\n // noise. The adminAudit record survives a mute either way; the timeliness\n // does not, and timeliness is the whole point of the alert.\n | 'system.pluginVerifierRegression'\n // A sign-in method was removed from the user's own account because their\n // organization turned on SSO enforcement (AGL-1129). `system.`, not\n // `team.`, for the AGL-1088 reason above: `team` is the category someone\n // mutes to stop routine roster chatter, and \"the way you sign in just\n // changed\" is not chatter — the next sign-in fails without it.\n | 'system.signInMethodRemoved'\n // Documents in a scoped collection carrying no `visibleTo` (AGL-1478).\n // Staff audience: the weekly dry run found resources that are invisible\n // to every site-scoped read, which always means a creation path forgot\n // the field. `system.` for the AGL-1088 reason above, and because the\n // collection it names may be `marketplace`-adjacent or not.\n | 'system.scopeDrift'\n // An SSO domain that WAS DNS-proven has stopped answering with our\n // challenge record, for three consecutive weekly sweeps (AGL-1210).\n // Nothing has been turned off — sign-in for that domain still routes\n // exactly as it did — and that is precisely why this has to be said out\n // loud rather than left in a log.\n //\n // `system.`, not `team.`, for the AGL-1088 reason above and one of its\n // own: the audience is the org's own admins, the subject is whether their\n // people can still sign in, and it must reach them BEFORE anybody decides\n // to revoke the routing. A category somebody mutes to quieten roster\n // chatter is the wrong place for the one warning that precedes a lockout.\n | 'system.ssoDomainUnverified'\n // A site hit the per-month form-submission abuse ceiling and further\n // submissions are being refused (AGL-1655). `system.`, not `content.`, for\n // the AGL-1088 reason above and more sharply than any of them: `content` is\n // literally the category a site owner mutes to stop routine form-submission\n // chatter, and this is the one form notification that says the form has\n // STOPPED accepting. Filing it under the muted bucket would guarantee it\n // reaches nobody on exactly the sites busy enough to trip it.\n | 'system.formSubmissionsPaused'\n // A site reached the flat platform ceiling on member accounts or on lead\n // records, so further ones are being refused (AGL-1529). `system.` for the\n // same reason as `formSubmissionsPaused` directly above, and with the same\n // sharpness: `content.` is the bucket an owner mutes to stop routine\n // sign-up and lead chatter, and this is the one notification saying the\n // sign-ups have STOPPED — muted exactly on the sites busy enough to trip it.\n | 'system.visitorRecordsPaused'\n // An outsider reported one of our sites for phishing, malware or CSAM\n // (AGL-1964). `system` for the AGL-1088 reason and, again, more sharply\n // than most: this notification goes to STAFF, not to a customer, and its\n // subject is somebody else's site. There is no bucket a recipient could\n // mute it into that would be honest — nobody has opted into being told a\n // stranger is being phished through our platform, and nobody should be able\n // to opt out of it either.\n //\n // Only the urgent categories raise one, and only on a first report. See the\n // fan-out in apps/tenant/app/api/report-abuse/route.ts for why: a flood of\n // alerts IS the flood, and the alert it would cost us is the phishing one.\n | 'system.abuseReportUrgent'\n // Something on the recipient's OWN workspace was held, flagged, locked or\n // paused (AGL-3368): an email or page held for review, a flagged domain,\n // a fraud signal on a payment, a lock and its lift. Written by\n // `notifyRiskEvent` from the risk notice catalog, which says what happened,\n // what it means and how to request a review. `system.` for the AGL-1088\n // reason: it is the one message saying the owner's work has STOPPED, and a\n // category muted to quieten routine chatter must not swallow it. It sends\n // its own email, transactional and preference-free, so it is also in\n // NOTIFICATION_SELF_SENT_EMAIL_TYPES.\n | 'system.riskNotice'\n // The §512(g) counter-notice (AGL-1983), and the one place the \"only urgent\n // categories raise a notification\" restraint above is deliberately not\n // applied. Every counter-notice carries a statutory deadline that is\n // ALREADY RUNNING when it arrives — the clock counts from the subscriber's\n // submission, not from our attention — so there is no low-value tail of\n // these to drown out the important ones, and the one that goes unread is a\n // customer locked out of their own work plus an unmet obligation under\n // §512(g)(2)(A). Raised on first submission only, like the one above, so a\n // resubmitting customer cannot re-alert.\n | 'system.dmcaCounterNotice'\n // A site crossed the per-month bandwidth abuse ceiling (AGL-2155). Two\n // audiences share one type: staff, because an uncompensated free site\n // serving six figures of page views is an incident; and the site's own\n // managers, because on free the site is now serving a capped notice and\n // nobody should learn that from a visitor.\n //\n // `system.`, not `billing.`, for the AGL-1088 reason and one specific to\n // this meter: on the free plan there is no bill, so `billing` would be the\n // one category where the message is literally never about money — and it is\n // exactly the free-tier trip that changes what visitors see.\n | 'system.bandwidthCeilingTripped'\n // A free site crossed its PLAN's included bandwidth and is now serving the\n // capped notice (AGL-2413). Distinct from the ceiling above on purpose: that\n // one is an incident at 10x the band and goes to staff first; this one is an\n // ordinary quota at 1x, concerns only the site's own managers, and its\n // remedy is an upgrade rather than an investigation. Sending both under one\n // type would tell an owner their traffic was being treated as suspected\n // abuse when it is simply a successful free site.\n | 'system.bandwidthCapEngaged'\n // A Stripe billing webhook threw AFTER its handlers had begun (AGL-2157),\n // so its side effects may be half applied and its idempotency claim is\n // being HELD — Stripe will not retry it. Staff audience: this is the one\n // failure on that route no automatic retry can make safe, because the\n // handlers behind it are not all idempotent, and a human has to reconcile.\n | 'system.billingWebhookHalfApplied'\n // A card dispute arrived that NOTHING in the platform claimed (AGL-2429):\n // no `platformRevenue` row, no storefront order, no marketplace purchase.\n // Staff audience, and the reason it needs a type of its own is that its\n // absence was the bug — the routine case (a storefront or marketplace\n // chargeback, which the plugins own) and the fault case were the same\n // silence from the route's side, so a dispute nobody handled looked\n // exactly like one somebody did.\n //\n // `system.`, not `billing.`, for the AGL-1088 reason and one specific to\n // this alert: `billing` is the category a recipient is most likely to have\n // muted as routine invoice traffic, and this is the one message on that\n // route where muting it means money moves with nobody looking.\n | 'system.disputeUnattributed'\n // An operator alert from the registry in `./operator-alerts` (AGL-3377)\n // that has no notification type of its own: a lost dispute, a failed\n // erasure, a degraded health check. One type for all of them because the\n // registry, not the taxonomy, is what names the alert; the title and body\n // say which one it is. `system.` for the AGL-1088 reason above: these are\n // the faults nobody may mute away as routine chatter.\n | 'system.operatorAlert'\n // Somebody created an account, and somebody created a workspace\n // (AGL-3225). Staff audience, and the only two types in the taxonomy whose\n // subject is the platform's own growth rather than anybody's work.\n //\n // `staff.`, and NOT `system.`, and the AGL-1088 note above is the reason\n // rather than an exception to it: `system` is the bucket nobody mutes to\n // reduce noise, which is exactly what makes it the wrong home for the two\n // routine, high-volume events in the product. A staff member must be able\n // to stop hearing about every sign-up without also dropping the verifier\n // regression and the unattributed dispute that share that bucket — and\n // before this category existed, there was nowhere to put them where that\n // was true.\n //\n // The category also tells the settings page who a row is for: `staff` is\n // rendered only to claim holders, so no customer is shown a switch for\n // notifications they could never receive.\n | 'staff.userSignedUp'\n | 'staff.orgCreated'\n // And somebody created a site (AGL-3491): the third growth event, the one\n // that says an account started building. Same category, same reason.\n | 'staff.siteCreated'\n // And when money moves (AGL-3267). The category was two signup types, so\n // the one thing a platform feed exists to report — revenue starting,\n // changing and stopping — was the one thing it did not.\n //\n // `staff.paymentFailed` is deliberately NOT the customer's\n // `billing.paymentFailed`: different audience, different action. The\n // customer is told to fix their card; staff are told a paying workspace is\n // about to stop paying.\n | 'staff.subscriptionStarted'\n | 'staff.subscriptionCanceled'\n | 'staff.planChanged'\n | 'staff.paymentFailed'\n\nexport interface AglynNotification {\n $id?: string\n type: AglynNotificationType\n title: string\n body?: string\n /** Console path the notification opens (e.g. a host inbox). */\n link?: string\n orgId?: string\n hostId?: string\n /**\n * The pending invitation this notification offers the recipient\n * (AGL-3402), under `orgs/{orgId}/invites`. Present only on the invitee's\n * own `team.invite`; the console opens the accept/decline dialog for it\n * instead of following `link`, and answering marks it read.\n */\n inviteId?: string\n createdAt?: ITimestamp\n /** When the owner read it; absent or null while unread. */\n readAt?: ITimestamp | null\n /**\n * Whether the owner has read it — `false` on create, `true` beside\n * `readAt` when read (AGL-3321).\n *\n * A boolean rather than `readAt: null`, because the feed filters by it\n * under its newest-first cursor. Equality on a boolean answers BOTH\n * states (`read == false`, `read == true`) beneath `orderBy('createdAt')`\n * with one composite index. A nullable timestamp answers \"unread\" by\n * equality but \"read\" only as `readAt != null`, and Firestore requires an\n * inequality's field to be the FIRST sort, which would order the feed by\n * when things were read instead of when they arrived. Absent only on\n * notifications written before the field existed, which\n * `tools/scripts/backfill-notification-read.mjs` stamps.\n */\n read?: boolean\n /**\n * How urgently this one notification asks to be read (AGL-3437), stamped\n * by its emitter. Absent on a notification whose emitter has no reason to\n * say more than its type does, and on everything written before the field\n * existed; read it through {@link notificationLevel}, never directly.\n */\n level?: NotificationLevel\n}\n\nexport const NOTIFICATION_TYPE_LABELS: Record<AglynNotificationType, string> = {\n 'billing.invoice': 'Invoice available',\n 'billing.paymentFailed': 'Payment failed',\n 'billing.subscriptionCanceled': 'Subscription canceled',\n 'billing.usage': 'Usage threshold',\n 'team.invite': 'Team invite',\n 'team.roleChanged': 'Role changed',\n 'team.hostAccessGranted': 'Site access granted',\n 'content.formSubmission': 'Form submission',\n 'content.booking': 'New booking',\n 'content.order': 'New order',\n 'content.lowStock': 'Low stock',\n 'content.taskAssigned': 'Task assigned to you',\n 'content.taskReminder': 'Task reminder',\n 'content.contactAssigned': 'Contact assigned to you',\n 'content.leadAssigned': 'Lead assigned to you',\n 'content.crmDailyDigest': 'Daily CRM digest',\n 'content.insightsDigest': 'Weekly insights',\n 'content.aiJobNeedsYou': 'AI job needs you',\n 'content.aiJobDone': 'AI job finished',\n 'content.aiJobFailed': 'AI job stopped',\n 'marketplace.review': 'Listing review',\n\n 'support.ticketOpened': 'New support ticket',\n 'support.ticketReply': 'Support ticket reply',\n 'system.announcement': 'Announcement',\n 'system.pluginVerifierRegression': 'Plugin verifier regression',\n 'system.signInMethodRemoved': 'Sign-in method removed',\n 'system.scopeDrift': 'Resources missing a sharing scope',\n 'system.ssoDomainUnverified': 'SSO domain no longer proves ownership',\n 'system.formSubmissionsPaused': 'Form submissions paused',\n 'system.visitorRecordsPaused': 'Sign-ups or leads paused',\n 'system.abuseReportUrgent': 'Urgent abuse report',\n 'system.riskNotice': 'Held, flagged or locked on your workspace',\n 'system.dmcaCounterNotice': 'DMCA counter-notice',\n 'system.bandwidthCeilingTripped': 'Bandwidth ceiling reached',\n 'system.bandwidthCapEngaged': 'Monthly traffic limit reached',\n 'system.billingWebhookHalfApplied': 'Billing webhook half applied',\n 'system.disputeUnattributed': 'Card dispute with no owner',\n 'system.operatorAlert': 'Operator alert',\n 'staff.userSignedUp': 'New account',\n 'staff.orgCreated': 'New workspace',\n 'staff.siteCreated': 'New site',\n 'staff.subscriptionStarted': 'New subscription',\n 'staff.subscriptionCanceled': 'Subscription canceled',\n 'staff.planChanged': 'Plan changed',\n 'staff.paymentFailed': 'Payment failed (workspace)',\n}\n\n/**\n * HOW LOUD A NOTIFICATION IS (AGL-3437), which the console draws as its\n * color, icon and accent.\n *\n * - `critical` — something stopped, money is moving with nobody looking, or\n * fraud: a fraud signal, a failed payment, a form that stopped accepting.\n * - `warning` — something degraded or is close to stopping: a health check\n * degraded, a limit reached, low stock.\n * - `success` — good news: an account, a workspace or a subscription\n * started, an order or a booking arrived, a health check recovered.\n * - `info` — worth reading, nothing wrong: an invite, a ticket reply, a\n * usage step on the way to a limit.\n * - `neutral` — routine work arriving: a form submission, an assignment, a\n * digest.\n *\n * A level is a property of the NOTIFICATION, not only of its type: one\n * `system.operatorAlert` says a check degraded and the next says it\n * recovered, and a usage notice at 75% is not the one at 100%. The emitter\n * stamps `level` when it knows more than the type; the type's default in\n * {@link NOTIFICATION_TYPE_LEVELS} answers for everything else.\n */\nexport type NotificationLevel =\n | 'critical'\n | 'warning'\n | 'success'\n | 'info'\n | 'neutral'\n\n/** Every level, loudest first — the order {@link loudestNotificationLevel} ranks by. */\nexport const NOTIFICATION_LEVELS: readonly NotificationLevel[] = [\n 'critical',\n 'warning',\n 'success',\n 'info',\n 'neutral',\n]\n\nexport const NOTIFICATION_LEVEL_LABELS: Record<NotificationLevel, string> = {\n critical: 'Critical',\n warning: 'Warning',\n success: 'Good news',\n info: 'Info',\n neutral: 'Routine',\n}\n\n/**\n * Each core type's level when its emitter stamps none. A plugin's types are\n * not listed: a plugin emitter stamps `level` itself, and an unstamped one\n * reads as `neutral`.\n *\n * A type the operator alert registry raises under its own notification type\n * must agree with that alert's level, so the backlog written before `level`\n * existed reads the same as what the registry writes today\n * (`notification-levels.spec.ts` holds the two together).\n */\nexport const NOTIFICATION_TYPE_LEVELS: Record<\n AglynNotificationType,\n NotificationLevel\n> = {\n 'billing.invoice': 'neutral',\n 'billing.paymentFailed': 'critical',\n 'billing.subscriptionCanceled': 'critical',\n // At a limit. A step on the way to it is stamped `info` by its emitter.\n 'billing.usage': 'warning',\n 'team.invite': 'info',\n 'team.roleChanged': 'info',\n 'team.hostAccessGranted': 'info',\n 'content.formSubmission': 'neutral',\n 'content.booking': 'success',\n 'content.order': 'success',\n 'content.lowStock': 'warning',\n 'content.taskAssigned': 'neutral',\n 'content.taskReminder': 'info',\n 'content.contactAssigned': 'neutral',\n 'content.leadAssigned': 'neutral',\n 'content.crmDailyDigest': 'neutral',\n 'content.insightsDigest': 'neutral',\n // A plan waits for the person; nothing is built until they confirm it.\n 'content.aiJobNeedsYou': 'warning',\n 'content.aiJobDone': 'success',\n 'content.aiJobFailed': 'warning',\n 'marketplace.review': 'info',\n 'support.ticketOpened': 'info',\n 'support.ticketReply': 'info',\n 'system.announcement': 'info',\n 'system.pluginVerifierRegression': 'warning',\n 'system.signInMethodRemoved': 'warning',\n 'system.scopeDrift': 'info',\n 'system.ssoDomainUnverified': 'warning',\n 'system.formSubmissionsPaused': 'critical',\n 'system.visitorRecordsPaused': 'critical',\n 'system.abuseReportUrgent': 'critical',\n 'system.riskNotice': 'critical',\n 'system.dmcaCounterNotice': 'critical',\n 'system.bandwidthCeilingTripped': 'warning',\n // The site is serving the capped notice to its visitors.\n 'system.bandwidthCapEngaged': 'critical',\n 'system.billingWebhookHalfApplied': 'critical',\n 'system.disputeUnattributed': 'critical',\n // The registry stamps each alert's own level; this answers only for one\n // written before it did.\n 'system.operatorAlert': 'warning',\n 'staff.userSignedUp': 'success',\n 'staff.orgCreated': 'success',\n 'staff.siteCreated': 'success',\n 'staff.subscriptionStarted': 'success',\n 'staff.subscriptionCanceled': 'warning',\n 'staff.planChanged': 'info',\n 'staff.paymentFailed': 'warning',\n}\n\nconst LEVEL_SET: ReadonlySet<string> = new Set(NOTIFICATION_LEVELS)\n\n/** Whether a stored value is a level this build knows. */\nexport function isNotificationLevel(value: unknown): value is NotificationLevel {\n return typeof value === 'string' && LEVEL_SET.has(value)\n}\n\n/**\n * A notification's level: what its emitter stamped, else its type's\n * default, else `neutral`. A stamped value this build does not know — a\n * level added later, read by an older console — falls back the same way\n * rather than drawing nothing.\n */\nexport function notificationLevel(\n notification: { type?: string; level?: unknown } | null | undefined,\n): NotificationLevel {\n const stamped = notification?.level\n if (isNotificationLevel(stamped)) return stamped\n const byType = (NOTIFICATION_TYPE_LEVELS as Record<string, NotificationLevel>)[\n notification?.type ?? ''\n ]\n return byType ?? 'neutral'\n}\n\n/**\n * A usage notice's level at `percent` of its allowance: `info` on a step\n * toward it, `warning` once it is reached. Every usage, budget and allotment\n * notice says the same thing at the same step, so they share this.\n */\nexport function usageNotificationLevel(percent: number): NotificationLevel {\n return percent >= 100 ? 'warning' : 'info'\n}\n\n/** The loudest of several levels, or `neutral` for none. */\nexport function loudestNotificationLevel(\n levels: Iterable<NotificationLevel>,\n): NotificationLevel {\n let best = NOTIFICATION_LEVELS.length - 1\n for (const level of levels) {\n const rank = NOTIFICATION_LEVELS.indexOf(level)\n if (rank >= 0 && rank < best) best = rank\n }\n return NOTIFICATION_LEVELS[best]\n}\n\n/**\n * The preference buckets the platform owns (AGL-267): the prefix before the\n * dot. A plugin adds its own through {@link NotificationCategoryDeclaration},\n * so this union is the core's and nothing else's.\n */\nexport type CoreNotificationCategory =\n | 'billing'\n | 'team'\n | 'content'\n | 'support'\n | 'system'\n // Staff-only, and shown only to staff (AGL-3225) — see\n // {@link STAFF_NOTIFICATION_CATEGORIES}.\n | 'staff'\n\n/**\n * A preference bucket: one of the core's, or one a first-party plugin\n * declares. The id is persisted — it keys every stored preference map — so a\n * declared id keeps its meaning only while its declaration keeps its spelling.\n */\nexport type NotificationCategory = CoreNotificationCategory | (string & {})\n\n/**\n * A notification category a plugin declares for the notifications it sends\n * (AGL-3080), under `notificationCategories` in `plugins.config.json`.\n *\n * Compiled rather than registered: `notifyUsers` resolves a recipient's\n * channels in server processes that load no plugin, and the settings page\n * draws its rows before any plugin could register. A category that had to\n * wait for its plugin would read as `system` until then — so a person who had\n * muted it would be told, and a person who had asked for its email would not.\n * The generator refuses an id the core owns or another plugin declares.\n */\nexport interface NotificationCategoryDeclaration {\n /** The plugin whose notifications carry this prefix. */\n pluginId: string\n /** The type prefix, and the key every stored preference is written under. */\n id: string\n /** The row's name on the settings page. */\n label: string\n /** What arrives under it, in the reader's words — see {@link NOTIFICATION_CATEGORY_DESCRIPTIONS}. */\n description: string\n /** What each channel does before anybody says — see {@link NOTIFICATION_CHANNEL_DEFAULTS}. */\n defaults: Record<NotificationChannel, boolean>\n}\n\n/**\n * The declared categories, in the order the settings page lists them: after\n * the workspace's own work and before the platform's notices, which is where\n * a plugin's traffic sits in a reader's day.\n */\nconst DECLARED_CATEGORIES: readonly NotificationCategoryDeclaration[] =\n PLUGIN_NOTIFICATION_CATEGORIES_DECLARED\n\n/**\n * The core's rows listed before the declared ones. Every other core category\n * follows them, in the order its `Record` spells it, so a new core category\n * cannot be left off the page.\n */\nconst LEADING_CATEGORIES: readonly CoreNotificationCategory[] = [\n 'billing',\n 'team',\n 'content',\n]\n\nfunction inCategoryOrder<T>(\n core: Record<CoreNotificationCategory, T>,\n declared: (declaration: NotificationCategoryDeclaration) => T,\n): Readonly<Record<NotificationCategory, T>> {\n // Every core id is written below, so the keys the type promises are there.\n const out = {} as Record<NotificationCategory, T>\n for (const id of LEADING_CATEGORIES) out[id] = core[id]\n for (const declaration of DECLARED_CATEGORIES) {\n out[declaration.id] = declared(declaration)\n }\n for (const id of Object.keys(core) as CoreNotificationCategory[]) {\n if (!LEADING_CATEGORIES.includes(id)) out[id] = core[id]\n }\n return out\n}\n\nconst CORE_CATEGORY_LABELS: Record<CoreNotificationCategory, string> = {\n billing: 'Billing',\n team: 'Team & access',\n content: 'Forms & bookings',\n support: 'Support',\n system: 'Product & system',\n staff: 'Platform growth',\n}\n\n/** Every category's row name, the core's and the declared, in page order. */\nexport const NOTIFICATION_CATEGORY_LABELS = inCategoryOrder(\n CORE_CATEGORY_LABELS,\n (declaration) => declaration.label,\n)\n\n/**\n * The categories only staff can receive (AGL-3225).\n *\n * The settings page hides these rows from everybody else, because a switch\n * for mail that can never arrive is a promise the product does not keep. It\n * is presentation only: `notifyStaff` is what decides the audience, and it\n * enumerates the `staff` claim rather than reading this.\n */\nexport const STAFF_NOTIFICATION_CATEGORIES: ReadonlySet<NotificationCategory> =\n new Set<NotificationCategory>(['staff'])\n\n/**\n * What each category actually covers, in the reader's words (AGL-3251).\n *\n * The settings page listed seven bare labels and two switches, so deciding\n * whether to silence `Product & system` meant guessing what was in it. The\n * type labels beneath each row now name the contents exactly; this is the\n * one-line answer for somebody who does not want to expand anything.\n *\n * Written as what ARRIVES rather than as what the bucket is called: \"someone\n * joins, a role changes\" is checkable against your own feed in a way that\n * \"team and access events\" is not. Exhaustive over the core's categories,\n * like the channel defaults below, and required of every declaration — a new\n * category cannot ship without somebody saying in plain words what lands in\n * it.\n */\nconst CORE_CATEGORY_DESCRIPTIONS: Record<CoreNotificationCategory, string> = {\n billing:\n 'Invoices, failed payments, cancellations, and usage that crosses a plan limit.',\n team: 'Somebody joins or leaves, a role changes, or a site is shared with you.',\n content:\n 'Work arriving on your sites: form submissions, bookings, orders, low stock, and the tasks and leads assigned to you.',\n support: 'New support tickets and replies on tickets you are following.',\n system:\n 'Announcements, and the faults the platform finds in your account: sign-in methods removed, traffic limits reached, billing or sharing left in a broken state.',\n staff:\n 'New accounts, new workspaces, and money moving — subscriptions starting, changing, failing and ending — across the whole platform. Only staff receive these.',\n}\n\nexport const NOTIFICATION_CATEGORY_DESCRIPTIONS = inCategoryOrder(\n CORE_CATEGORY_DESCRIPTIONS,\n (declaration) => declaration.description,\n)\n\n/**\n * The bucket a type falls in: its prefix, when a category of that id exists,\n * and `system` otherwise — the bucket nobody mutes to reduce noise, so a type\n * nothing claims still reaches the person rather than riding a mute they set\n * for something else.\n */\nexport function notificationCategory(\n type: AglynNotificationType | string,\n): NotificationCategory {\n const prefix = String(type).split('.')[0]\n return Object.prototype.hasOwnProperty.call(\n NOTIFICATION_CATEGORY_LABELS,\n prefix,\n )\n ? prefix\n : 'system'\n}\n\n/**\n * Per-user mute map stored at `users/{uid}.notificationPrefs`\n * (`{ [category]: false }` mutes); absent categories stay on.\n */\nexport function notificationMuted(\n prefs: Record<string, boolean> | null | undefined,\n type: AglynNotificationType | string,\n): boolean {\n return prefs?.[notificationCategory(type)] === false\n}\n\n/**\n * The field on `users/{uid}` that holds a person's digest switches\n * (AGL-2619): `{ [digestKey]: false }` turns one digest off, and an absent key\n * leaves it on. Its own map rather than a key in `notificationPrefs`, because\n * that map is keyed by CATEGORY and read by {@link notificationMuted} — a\n * digest is a schedule a person keeps or drops, not a bucket of types, and one\n * switch governs both the console notification and the email it travels with.\n */\nexport const DIGEST_PREFS_FIELD = 'digestPrefs'\n\n/**\n * A digest a plugin sends on its own schedule (AGL-3080), declared under\n * `notificationDigests` in `plugins.config.json` so the settings page can draw\n * its switch without loading the plugin, and the plugin's sender and that\n * switch read one key.\n *\n * On until the person turns it off: the key is stored in\n * {@link DIGEST_PREFS_FIELD} only once somebody has said no. The key is\n * persisted, so it keeps its spelling for as long as anybody's switch is\n * stored under it.\n */\nexport interface NotificationDigestDeclaration {\n /** The plugin that composes and sends it. */\n pluginId: string\n /** The key its switch is stored under in {@link DIGEST_PREFS_FIELD}. */\n key: string\n /** The switch's name. */\n label: string\n /** When it arrives and what it holds, in the reader's words. */\n description: string\n}\n\n/** Every declared digest, in the order the settings page lists them. */\nexport const NOTIFICATION_DIGESTS: readonly NotificationDigestDeclaration[] =\n PLUGIN_NOTIFICATION_DIGESTS_DECLARED\n\n/**\n * Whether a person keeps one digest: on unless its key is stored `false`. It\n * reads only its own key — a category mute lives in a different map and does\n * not reach it.\n */\nexport function digestEnabled(\n prefs: Record<string, boolean> | null | undefined,\n key: string,\n): boolean {\n return prefs?.[key] !== false\n}\n\n/**\n * The field on `users/{uid}` naming the workspaces whose weekly insights a\n * person asked for (AGL-2915): `{ [orgId]: true }`. OPT-IN, unlike the CRM\n * digest — an absent key is off — because a weekly insight is generated, and a\n * generation spends the workspace's credits. The person turns it on beside the\n * answers themselves, where the plan, the release and their permission have\n * already been checked, and off again there or in Notifications; the weekly\n * sweep checks all three again before it spends anything.\n */\nexport const INSIGHT_DIGESTS_FIELD = 'insightDigests'\n\n/** Whether a person asked for a workspace's weekly insights. */\nexport function insightDigestSubscribed(\n value: Record<string, boolean> | null | undefined,\n orgId: string,\n): boolean {\n return Boolean(orgId) && value?.[orgId] === true\n}\n\n/**\n * The channels a notification can travel on (AGL-3223).\n *\n * `console` is the feed at `/manage/notifications` and the app-bar dropdown\n * that reads it — the only channel that existed. `email` is the message the\n * fan-out sends beside that doc when the recipient asked for one.\n */\nexport type NotificationChannel = 'console' | 'email'\n\n/**\n * One scope's answer for one category. **Tri-state on purpose**: `true` and\n * `false` decide, and an ABSENT key inherits from the scope above.\n *\n * Inheritance is the whole reason this is a partial rather than a pair of\n * booleans. A person who wants form submissions from one busy site and not\n * from the other five has to be able to say that about the one site without\n * restating their answer for every other category at every other scope — and\n * a two-valued leaf cannot express \"I have not said\", so every override would\n * have to be written out in full and would then stop tracking the account\n * default it was never meant to detach from.\n */\nexport interface NotificationChannelPrefs {\n console?: boolean\n email?: boolean\n}\n\nexport type NotificationCategoryPrefs = Partial<\n Record<NotificationCategory, NotificationChannelPrefs>\n>\n\n/**\n * One scope's answer for a single notification TYPE (AGL-3251), tri-state on\n * the same terms as {@link NotificationChannelPrefs}: an absent key falls\n * through to the category.\n *\n * Its own map rather than extra keys in {@link NotificationCategoryPrefs},\n * because that one is an exhaustive record keyed by category and a type key\n * inside it would type-check only by widening the thing that makes a missing\n * category a compile error.\n */\nexport type NotificationTypePrefs = Partial<\n Record<AglynNotificationType, NotificationChannelPrefs>\n>\n\n/**\n * Per-scope, per-channel notification preferences (AGL-3223), stored at\n * `users/{uid}.notificationSettings`.\n *\n * Three layers, narrowest first when resolving: the SITE a notification\n * concerns, then the WORKSPACE, then the account. Anything none of them\n * answers falls to {@link NOTIFICATION_CHANNEL_DEFAULTS}.\n *\n * ON THE USER DOCUMENT, not on `orgs/{orgId}/members/{uid}`, and that is a\n * cost decision rather than a modelling preference. `notifyUsers` already\n * does exactly one `getAll` over the recipients' user docs to read their\n * category mutes, so every layer living here means per-site preferences are\n * read for free on the fan-out's hot path. The member row would add a read\n * per recipient per notification to answer a question the document already in\n * hand could have answered.\n */\nexport interface NotificationSettings {\n account?: NotificationCategoryPrefs\n /**\n * Per-TYPE answers at the account scope (AGL-3251), consulted before\n * {@link NotificationSettings.account}'s category answer and never above a\n * narrower scope — see {@link notificationChannelEnabled}.\n *\n * ACCOUNT ONLY, deliberately. The per-workspace and per-site card is\n * already seven categories by three states by two channels, and a type row\n * for each of the ~thirty types, per workspace AND per site, is a page\n * nobody can read — which is the complaint this whole issue started as.\n * The account scope is where \"stop telling me about THIS\" belongs anyway:\n * it is a statement about the kind of thing, and kinds do not vary by site.\n */\n accountTypes?: NotificationTypePrefs\n /** Keyed by org id. */\n orgs?: Record<string, NotificationCategoryPrefs>\n /** Keyed by host id — a site's own answer, narrower than its workspace's. */\n hosts?: Record<string, NotificationCategoryPrefs>\n /**\n * Per-TYPE answers at the workspace and site scopes (AGL-3267), beside the\n * category maps above rather than nested inside them.\n *\n * Parallel maps because the category maps are already stored under `orgs`\n * and `hosts` on live user documents: folding both into one\n * `{ categories, types }` object per scope would be a migration of every\n * preference anybody has set, to express something two more keys express\n * without touching a byte of what exists.\n *\n * This supersedes the account-only limit AGL-3251 shipped under. That was\n * the right call for a card nobody had used yet and the wrong one once it\n * existed: \"quiet this one type down on this one busy site\" is the question\n * the scope card is FOR, and answering it only for whole categories made\n * the fine grain stop exactly where the noise is worst.\n */\n orgTypes?: Record<string, NotificationTypePrefs>\n hostTypes?: Record<string, NotificationTypePrefs>\n}\n\nexport const NOTIFICATION_SETTINGS_FIELD = 'notificationSettings'\n\n/**\n * What a category does when nobody has said otherwise.\n *\n * Console on, email OFF, for every category — a site's own transactions are\n * the exception, by type, in {@link NOTIFICATION_TYPE_CHANNEL_DEFAULTS}.\n * Email defaults off because the inbox is\n * not ours to fill: the product already sends transactional mail nobody opted\n * into — welcome, verification, invites, dunning, usage alerts — and every one\n * of those leaves on the same domain a customer's password reset depends on.\n * Turning a busy site's form submissions into mail by default would put that\n * domain's reputation behind traffic the recipient never asked for.\n *\n * Exhaustive over the core's categories deliberately: a new\n * {@link CoreNotificationCategory} is a compile error here until somebody\n * decides what it does by default, which is the one question a new category\n * must not be able to ship without answering — and a declared category may not\n * compile without its `defaults` for the same reason.\n */\nconst CORE_CHANNEL_DEFAULTS: Record<\n CoreNotificationCategory,\n Record<NotificationChannel, boolean>\n> = {\n billing: { console: true, email: false },\n team: { console: true, email: false },\n content: { console: true, email: false },\n support: { console: true, email: false },\n system: { console: true, email: false },\n // Console ON, because the complaint this answers is that staff never heard\n // about a sign-up at all; email off, like everything else, because that is\n // what the channel defaults to and a sign-up is not urgent enough to be the\n // exception that starts filling inboxes by default.\n staff: { console: true, email: false },\n}\n\nexport const NOTIFICATION_CHANNEL_DEFAULTS = inCategoryOrder(\n CORE_CHANNEL_DEFAULTS,\n (declaration) => ({ ...declaration.defaults }),\n)\n\n/**\n * The types whose default differs from their category's: a site's own\n * transactions — a form submitted, a booking made, an order placed — email\n * the people who run it unless they said otherwise.\n *\n * Below every stored answer, the category's included, so a person who\n * switched content email off keeps it off; above the category default, so\n * everyone who never answered (every account, new or old) is emailed.\n * These are the events a site exists to produce, and an owner who hears\n * about them only by opening the console misses the customer.\n */\nexport const NOTIFICATION_TYPE_CHANNEL_DEFAULTS: Partial<\n Record<AglynNotificationType, Partial<Record<NotificationChannel, boolean>>>\n> = {\n 'content.formSubmission': { email: true },\n 'content.booking': { email: true },\n 'content.order': { email: true },\n}\n\n/** What a type does on a channel when nobody has answered for it or its category. */\nexport function notificationTypeChannelDefault(\n type: AglynNotificationType | string,\n channel: NotificationChannel,\n): boolean {\n const own = NOTIFICATION_TYPE_CHANNEL_DEFAULTS[type as AglynNotificationType]?.[channel]\n return typeof own === 'boolean'\n ? own\n : NOTIFICATION_CHANNEL_DEFAULTS[notificationCategory(type)][channel]\n}\n\n/**\n * The types that send their OWN email and must never be mailed again by the\n * generic channel (AGL-3224).\n *\n * Both digests compose a message the fan-out could not reproduce — a day's\n * owed tasks, a week's figures — and send it from their own route under their\n * own switch (a key in `digestPrefs`, `insightDigests.{orgId}`). A recipient\n * who switches the `content` email channel on would otherwise receive the\n * digest twice: once as the digest, once as a one-line \"Daily CRM digest\"\n * notification saying that the digest happened.\n */\nexport const NOTIFICATION_SELF_SENT_EMAIL_TYPES: ReadonlySet<string> =\n new Set<AglynNotificationType>([\n 'content.crmDailyDigest',\n 'content.insightsDigest',\n // The task-reminders route mails one reminder per member per run, listing\n // every task due, and writes one notification per task; mailed again\n // here, each task would arrive a second time as its own email (AGL-3432).\n 'content.taskReminder',\n // Emailed by `notifyRiskEvent` itself, as account mail (AGL-3368).\n 'system.riskNotice',\n ])\n\n/**\n * The tooltip on a self-sent type's disabled email switch: it names what\n * DOES govern that mail, which differs by type (AGL-3432). Calling a task\n * reminder a digest sent people looking for a Digests switch that is not it.\n */\nexport function selfSentEmailNote(type: string): string {\n switch (type) {\n case 'content.taskReminder':\n return 'Task reminders send their own email, one per run listing every task due. Mute this category to stop them.'\n case 'system.riskNotice':\n return 'Risk and account notices are always emailed, whatever this switch says.'\n default:\n return 'This digest sends its own email, under its switch in Digests.'\n }\n}\n\n/**\n * Whether a channel is on for one notification, at its own scope.\n *\n * Resolution order, first answer wins: the notification's SITE, its\n * WORKSPACE, the account, then {@link NOTIFICATION_CHANNEL_DEFAULTS}. A scope\n * that holds no entry for the category, or an entry with the channel key\n * absent, does not answer — see {@link NotificationChannelPrefs}.\n *\n * `legacyPrefs` is the flat `notificationPrefs` mute map this replaces\n * (AGL-267), and it sits BELOW the account layer rather than beside it.\n * Nothing migrates it: a person who never opens the new settings page keeps\n * being governed by the mutes they set years ago, and the first thing they do\n * set on the account layer overrides the old map for that category without\n * disturbing the rest of it. It answers for `console` only, because the map\n * predates there being a second channel and reading a console mute as an\n * email preference would be inventing an answer its author never gave.\n */\nexport function notificationChannelEnabled(\n settings: NotificationSettings | null | undefined,\n channel: NotificationChannel,\n type: AglynNotificationType | string,\n scope?: { orgId?: string | null; hostId?: string | null },\n legacyPrefs?: Record<string, boolean> | null,\n): boolean {\n const category = notificationCategory(type)\n /*\n * ⛔ A STAFF NOTIFICATION HAS NO SCOPE TO BE NARROWED BY (AGL-3267).\n *\n * It is about the platform, and the workspace one MENTIONS is its subject,\n * not its audience: the staff member reading \"Acme Co subscribed\" is\n * almost never a member of Acme Co, and if they happen to be, their\n * preferences for their own membership have nothing to do with it.\n *\n * This was already true by accident — no staff emitter passes `orgId` or\n * `hostId`, so the scope layers never matched — which made every\n * \"Platform growth\" row in the per-workspace card a control that could be\n * set and could never do anything. Stating it here rather than only hiding\n * those rows is the difference between the model being right and the UI\n * covering for a model that is wrong: a `staff.*` type that ever does\n * start carrying an `orgId`, for its link or its subject line, must not\n * silently become mutable per workspace.\n */\n const staffWide = STAFF_NOTIFICATION_CATEGORIES.has(category)\n /*\n * Narrowest scope first, and within each scope the TYPE before its\n * CATEGORY (AGL-3251, widened to every scope by AGL-3267).\n *\n * Both halves matter and they answer different questions. Scope order is\n * \"where is this from\" — a site's answer beats its workspace's, which beats\n * the account's, because quietening one busy site is the thing the scope\n * card exists for. Type-before-category is \"what kind of thing is this\" —\n * somebody who switched `Payment failed` off said something about that\n * type, and it must beat their own broader `Billing` answer at the SAME\n * scope without leaking upward past a narrower one.\n */\n const layers: Array<NotificationChannelPrefs | undefined> = staffWide\n ? [\n settings?.accountTypes?.[type as AglynNotificationType],\n settings?.account?.[category],\n ]\n : [\n scope?.hostId\n ? settings?.hostTypes?.[scope.hostId]?.[type as AglynNotificationType]\n : undefined,\n scope?.hostId ? settings?.hosts?.[scope.hostId]?.[category] : undefined,\n scope?.orgId\n ? settings?.orgTypes?.[scope.orgId]?.[type as AglynNotificationType]\n : undefined,\n scope?.orgId ? settings?.orgs?.[scope.orgId]?.[category] : undefined,\n settings?.accountTypes?.[type as AglynNotificationType],\n settings?.account?.[category],\n ]\n for (const layer of layers) {\n const answer = layer?.[channel]\n if (typeof answer === 'boolean') return answer\n }\n if (channel === 'console' && notificationMuted(legacyPrefs, type))\n return false\n return notificationTypeChannelDefault(type, channel)\n}\n\n/**\n * What one scope says, with no inheritance applied — what the settings page\n * renders as Inherit / On / Off, and `undefined` is Inherit.\n *\n * `scope` names the layer directly rather than being derived from a\n * notification, because the page edits a layer whether or not anything has\n * ever arrived from it.\n */\n/**\n * What the account scope says about one TYPE, with no inheritance applied\n * (AGL-3251) — `undefined` means the row follows its category.\n *\n * The page needs the unresolved answer to draw the difference between \"on\n * because Billing is on\" and \"on because you said so\": only the second can be\n * reset, and a switch that cannot show which one it is leaves a person unable\n * to get back to following the category.\n */\nexport function notificationAccountTypePref(\n settings: NotificationSettings | null | undefined,\n type: AglynNotificationType | string,\n channel: NotificationChannel,\n): boolean | undefined {\n return settings?.accountTypes?.[type as AglynNotificationType]?.[channel]\n}\n\n/**\n * Every type in a category, in the order the labels declare them\n * (AGL-3251) — what the settings page expands a category row into.\n *\n * Derived from {@link NOTIFICATION_TYPE_LABELS} rather than held as a second\n * map, so a type added there appears under its category without anybody\n * remembering to list it twice.\n */\nexport function notificationTypesInCategory(\n category: NotificationCategory,\n): AglynNotificationType[] {\n return (\n Object.keys(NOTIFICATION_TYPE_LABELS) as AglynNotificationType[]\n ).filter((type) => notificationCategory(type) === category)\n}\n\n/**\n * What ONE scope says about ONE type, with no inheritance applied\n * (AGL-3267) — `undefined` means the row follows its category at that scope.\n *\n * The scope-aware sibling of {@link notificationAccountTypePref}, which stays\n * as the account-only shorthand its callers already use.\n */\nexport function notificationScopeTypePref(\n settings: NotificationSettings | null | undefined,\n scope: { kind: 'account' } | { kind: 'org' | 'host'; id: string },\n type: AglynNotificationType | string,\n channel: NotificationChannel,\n): boolean | undefined {\n const layer =\n scope.kind === 'account'\n ? settings?.accountTypes\n : scope.kind === 'org'\n ? settings?.orgTypes?.[scope.id]\n : settings?.hostTypes?.[scope.id]\n return layer?.[type as AglynNotificationType]?.[channel]\n}\n\nexport function notificationScopePref(\n settings: NotificationSettings | null | undefined,\n scope: { kind: 'account' } | { kind: 'org' | 'host'; id: string },\n category: NotificationCategory,\n channel: NotificationChannel,\n): boolean | undefined {\n const layer =\n scope.kind === 'account'\n ? settings?.account\n : scope.kind === 'org'\n ? settings?.orgs?.[scope.id]\n : settings?.hosts?.[scope.id]\n return layer?.[category]?.[channel]\n}\n\n/**\n * The scopes this person has said something different about — what the\n * settings page lists so an override is never somewhere you have to go\n * looking for.\n *\n * Returns ids, not names: the page holds the org and host rosters and this\n * module holds no lookups. An id with no name is still worth listing, because\n * a preference about a workspace somebody left is exactly the kind of\n * leftover that is invisible until it is listed.\n */\nexport function notificationOverriddenScopes(\n settings: NotificationSettings | null | undefined,\n): { orgIds: string[]; hostIds: string[] } {\n /*\n * BOTH maps for a scope, categories and types (AGL-3267).\n *\n * Reading only the category map would make a scope whose ONLY answer is a\n * per-type one invisible here — and this list is the single place a person\n * can find an override they set months ago. Silencing one type on one busy\n * site and then being unable to find where you did it is precisely the\n * failure this function exists to prevent.\n */\n const answered = (prefs: Record<string, NotificationChannelPrefs> | undefined) =>\n Object.values(prefs ?? {}).some((channels) =>\n Object.values(channels ?? {}).some((value) => typeof value === 'boolean'),\n )\n const named = (\n categories: Record<string, NotificationCategoryPrefs> | undefined,\n types: Record<string, NotificationTypePrefs> | undefined,\n ) =>\n [\n ...new Set([\n ...Object.keys(categories ?? {}),\n ...Object.keys(types ?? {}),\n ]),\n ]\n .filter(\n (id) =>\n answered(categories?.[id] as Record<string, NotificationChannelPrefs>) ||\n answered(types?.[id] as Record<string, NotificationChannelPrefs>),\n )\n .sort()\n return {\n orgIds: named(settings?.orgs, settings?.orgTypes),\n hostIds: named(settings?.hosts, settings?.hostTypes),\n }\n}\n\n/**\n * Rewrites a stored notification link onto the current URL scheme (AGL-644).\n *\n * A notification's `link` is frozen at write time — `notifyUsers` persists\n * whatever string the emitter passed and never normalizes it. So every\n * notification written before the org-slug migration (AGL-621) and the\n * subdomain migration (AGL-622) still points at a route that no longer\n * exists, and fixing the emitters alone would leave that whole backlog dead.\n * Normalizing when the link is FOLLOWED repairs old and new alike, and keeps\n * working for emitters that haven't been migrated yet.\n *\n * Rewrites, in order — each prefix also followed by a query string, as\n * `/{hostDocId}?aiJob={id}` (AGL-3593):\n * - `/{hostDocId}` or `/{hostDocId}/rest` → `/{orgSlug}/hosts/{subdomain}/rest`\n * - `/org` or `/org/rest` → `/{orgSlug}/rest`\n * - `/hosts` (exactly) → `/{orgSlug}/hosts`\n *\n * Anything already canonical, user-scoped (`/manage/...`), staff (`/admin/...`)\n * or absolute is returned untouched. Every rewrite is gated on having the\n * context it needs, so an unresolvable link degrades to its stored value\n * rather than to a wrong destination.\n *\n * The host rewrite is keyed on the notification's own `hostId` rather than\n * guessing from the path shape, so it can never mistake a real first segment\n * for a doc id.\n *\n * The email copy of a notification goes through it too (AGL-3367): a button\n * in an inbox is a followed link with no console around it to repair it.\n */\nexport function normalizeNotificationLink(\n link: string | undefined | null,\n context: {\n orgSlug?: string | null\n /** The notification's `hostId` (a Firestore doc id). */\n hostId?: string | null\n /** That host's subdomain, which the current routes are keyed by. */\n hostSubdomain?: string | null\n },\n): string | undefined {\n if (!link) return undefined\n // Absolute URLs (staff broadcasts can carry them) are not ours to rewrite.\n if (!link.startsWith('/')) return link\n\n const { orgSlug, hostId, hostSubdomain } = context\n\n if (orgSlug && hostId && hostSubdomain) {\n const prefix = `/${hostId}`\n if (link === prefix || link.startsWith(`${prefix}/`) || link.startsWith(`${prefix}?`)) {\n return `${buildRoute(Route.HOST_DASHBOARD, {\n orgSlug,\n host: hostSubdomain,\n })}${link.slice(prefix.length)}`\n }\n }\n\n if (orgSlug) {\n if (link === '/org' || link.startsWith('/org/') || link.startsWith('/org?')) {\n return `${buildRoute(Route.ORG_HOME, { orgSlug })}${link.slice(\n '/org'.length,\n )}`\n }\n // Only the bare list — `/hosts/{docId}` would still need a subdomain, and\n // guessing one is worse than leaving the link alone.\n if (link === '/hosts') return buildRoute(Route.HOST_LIST, { orgSlug })\n }\n\n return link\n}\n"],"names":["buildRoute","Route","PLUGIN_NOTIFICATION_CATEGORIES_DECLARED","PLUGIN_NOTIFICATION_DIGESTS_DECLARED","NOTIFICATION_TYPE_LABELS","NOTIFICATION_LEVELS","NOTIFICATION_LEVEL_LABELS","critical","warning","success","info","neutral","NOTIFICATION_TYPE_LEVELS","LEVEL_SET","Set","isNotificationLevel","value","has","notificationLevel","notification","stamped","level","byType","type","usageNotificationLevel","percent","loudestNotificationLevel","levels","best","length","rank","indexOf","DECLARED_CATEGORIES","LEADING_CATEGORIES","inCategoryOrder","core","declared","out","id","declaration","Object","keys","includes","CORE_CATEGORY_LABELS","billing","team","content","support","system","staff","NOTIFICATION_CATEGORY_LABELS","label","STAFF_NOTIFICATION_CATEGORIES","CORE_CATEGORY_DESCRIPTIONS","NOTIFICATION_CATEGORY_DESCRIPTIONS","description","notificationCategory","prefix","String","split","prototype","hasOwnProperty","call","notificationMuted","prefs","DIGEST_PREFS_FIELD","NOTIFICATION_DIGESTS","digestEnabled","key","INSIGHT_DIGESTS_FIELD","insightDigestSubscribed","orgId","Boolean","NOTIFICATION_SETTINGS_FIELD","CORE_CHANNEL_DEFAULTS","console","email","NOTIFICATION_CHANNEL_DEFAULTS","defaults","NOTIFICATION_TYPE_CHANNEL_DEFAULTS","notificationTypeChannelDefault","channel","own","NOTIFICATION_SELF_SENT_EMAIL_TYPES","selfSentEmailNote","notificationChannelEnabled","settings","scope","legacyPrefs","category","staffWide","layers","accountTypes","account","hostId","hostTypes","undefined","hosts","orgTypes","orgs","layer","answer","notificationAccountTypePref","notificationTypesInCategory","filter","notificationScopeTypePref","kind","notificationScopePref","notificationOverriddenScopes","answered","values","some","channels","named","categories","types","sort","orgIds","hostIds","normalizeNotificationLink","link","context","startsWith","orgSlug","hostSubdomain","HOST_DASHBOARD","host","slice","ORG_HOME","HOST_LIST"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAGD,SAASA,UAAU,EAAEC,KAAK,QAAQ,sBAAkB;AACpD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;YAAQ,KAAKH,KAAKO,KAAK,CAC5D,OAAOlG,MAAM,GACZ;QACL;QACA,0EAA0E;QAC1E,qDAAqD;QACrD,IAAI2F,SAAS,UAAU,OAAOxH,WAAWC,MAAMgI,SAAS,EAAE;YAAEN;QAAQ;IACtE;IAEA,OAAOH;AACT"}
@@ -21,34 +21,31 @@ import type { ResolvedBrandingProfile } from './platform-brand';
21
21
  /** Sentinel for quotas a plan does not cap; `checkQuota` always allows. */
22
22
  export declare const UNLIMITED: number;
23
23
  /**
24
- * How many saved form definitions one site may hold, on every plan that can
25
- * build them at all.
26
- *
27
- * ⛔ **Not a tier lever, and must not become one.** The website-building field
28
- * does not meter form COUNT: Squarespace, HubSpot and Mailchimp publish no cap
29
- * whatsoever, Webflow abandoned the lever above its free tier, and of the two
30
- * that do meter it one is Wix (4/10/25/75) and the other is Jotform
31
- * (5/25/50/100), a form-first product where a form IS the billable unit. What
32
- * this platform meters on the forms axis is `formSubmissionsPerMonth`, which
33
- * is tiered, metered and part of a charged price.
34
- *
35
- * So this is an abuse ceiling wearing an entitlement's clothes. It rides
36
- * `formsPerHost` because that is where `checkQuota` can refuse a create inside
37
- * the counting transaction, not because the number is sold — and it resolves
38
- * to the same value on Starter through Enterprise. Only Free differs, and only
39
- * because the form entity rides `reusableComponents`, which Free lacks.
40
- *
41
- * The value clears every published competitor number by 5x and the largest
42
- * real catalog by far, and it stays STRICTLY below `FORMS_MAX_PER_HOST` — the
43
- * page size two listing reads use. The gap is deliberate: a catalog can sit
44
- * above this ceiling when a per-org override is withdrawn, and the two
45
- * numbers must stay tellable apart so a surface reading the window where it
46
- * means the ceiling is never accidentally right. `forms.spec.ts` pins both
47
- * halves.
48
- *
49
- * A per-org `entitlements.formsPerHost` override still resolves ahead of this,
50
- * so a contract can raise or lower it for one org without moving the ceiling
51
- * everyone else is measured against.
24
+ * How many saved form definitions one site may hold on the plans at the top
25
+ * of the ladder: Scale, Advanced, Agency and Enterprise.
26
+ *
27
+ * Since 2026-10-06 the saved-form catalog IS a tier lever (AGL-3597): Free 1,
28
+ * Starter 5, Pro 25, Business 100, and this ceiling above them. Before that
29
+ * date every paid plan carried this number and Free carried none, which made
30
+ * a Starter catalog of 500 forms a give-away no pricing page listed. The
31
+ * ladder sits close to the published form-count ladders in the field (Wix
32
+ * 4/10/25/75, Jotform 5/25/50/100), and the allowance is listed on the
33
+ * pricing pages as "Saved forms per site".
34
+ *
35
+ * A form is no longer gated by `reusableComponents`: a Free site can save its
36
+ * one form, and only components stay Starter-and-above. The count is refused
37
+ * at the CREATE and nowhere else, so a site already holding more than its new
38
+ * allowance keeps every form it has; it only cannot add another.
39
+ *
40
+ * The value stays STRICTLY below `FORMS_MAX_PER_HOST` — the page size two
41
+ * listing reads use. The gap is deliberate: a catalog can sit above this
42
+ * ceiling when a per-org override is withdrawn, and the two numbers must stay
43
+ * tellable apart so a surface reading the window where it means the ceiling
44
+ * is never accidentally right. `forms.spec.ts` pins both halves.
45
+ *
46
+ * A per-org `entitlements.formsPerHost` override still resolves ahead of the
47
+ * plan's number, so a contract can raise or lower it for one org without
48
+ * moving the allowance everyone else on the plan is measured against.
52
49
  */
53
50
  export declare const FORMS_PER_HOST_CEILING = 500;
54
51
  /**