@aglyn/tenant-data-admin 1.0.0-beta.260 → 1.0.0-beta.262

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aglyn/tenant-data-admin",
3
- "version": "1.0.0-beta.260",
3
+ "version": "1.0.0-beta.262",
4
4
  "license": "Apache-2.0",
5
5
  "homepage": "https://aglyn.com",
6
6
  "repository": {
@@ -25,12 +25,12 @@
25
25
  "./package.json": "./package.json"
26
26
  },
27
27
  "dependencies": {
28
- "@aglyn/aglyn": "1.0.0-beta.260",
29
- "@aglyn/shared-util-email": "1.0.0-beta.260",
30
- "@aglyn/shared-util-fbserver": "1.0.0-beta.260",
31
- "@aglyn/shared-util-first-touch": "1.0.0-beta.260",
32
- "@aglyn/shared-util-http": "1.0.0-beta.260",
33
- "@aglyn/shared-util-tools": "1.0.0-beta.260",
28
+ "@aglyn/aglyn": "1.0.0-beta.262",
29
+ "@aglyn/shared-util-email": "1.0.0-beta.262",
30
+ "@aglyn/shared-util-fbserver": "1.0.0-beta.262",
31
+ "@aglyn/shared-util-first-touch": "1.0.0-beta.262",
32
+ "@aglyn/shared-util-http": "1.0.0-beta.262",
33
+ "@aglyn/shared-util-tools": "1.0.0-beta.262",
34
34
  "@msgpack/msgpack": "^3.1.3",
35
35
  "@swc/helpers": "0.5.23",
36
36
  "sharp": "^0.35.5",
@@ -0,0 +1,44 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ import { type PluginFigureReader, type ResolvedPluginFigureReader } from '@aglyn/aglyn/plugin-manager/plugin-figures';
18
+ /**
19
+ * The figure readers a caller may read for one workspace or one site
20
+ * (AGL-2915): the caller's half of the `plugin-figures` contract.
21
+ *
22
+ * The registry carries no authorization, so before a reader is read this
23
+ * establishes that the workspace's plan includes the feature the figures are
24
+ * sold under, and that the plugin whose records they are runs here: past its
25
+ * release flag, on for the workspace and not switched off for the site. The
26
+ * site belonging to the workspace, and the person's reach, are the caller's
27
+ * own checks.
28
+ */
29
+ /** Which of a set of plugins are past their release flags for an org; the platform's flags by default. */
30
+ export type ReleasedFigurePlugins = (pluginIds: string[], orgId: string) => Promise<string[]>;
31
+ export interface FigureReaderContext {
32
+ orgId: string;
33
+ /** The site the figures are about; `null` for the workspace as a whole. */
34
+ hostId: string | null;
35
+ /** The org document. */
36
+ org: object | null;
37
+ /** The site's host document, already checked to belong to the org; `null` with no site. */
38
+ host: Record<string, unknown> | null;
39
+ /** Which readers the caller asks about at all, before the gates. */
40
+ accept: (reader: PluginFigureReader) => boolean;
41
+ released?: ReleasedFigurePlugins;
42
+ }
43
+ /** The readers that pass the gates, ordered by id so a list of them is the same on every call. */
44
+ export declare function eligibleFigureReaders(context: FigureReaderContext): Promise<ResolvedPluginFigureReader[]>;
@@ -0,0 +1,45 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */ import { checkEntitlement } from "@aglyn/aglyn/app-utils/plan-entitlements";
17
+ import { isHostPluginEnabled, isPluginEnabled } from "@aglyn/aglyn/plugin-manager/enabled-plugins";
18
+ import { listPluginFigureReaders, pluginFigureReaderPlugin } from "@aglyn/aglyn/plugin-manager/plugin-figures";
19
+ import { filterEnabledPluginsByReleaseFlags } from "./release-flags.js";
20
+ const releasedByFlags = (pluginIds, orgId)=>filterEnabledPluginsByReleaseFlags(pluginIds, {
21
+ orgId,
22
+ authorization: null
23
+ });
24
+ /** The readers that pass the gates, ordered by id so a list of them is the same on every call. */ export async function eligibleFigureReaders(context) {
25
+ var _context_released;
26
+ const org = context.org;
27
+ const candidates = listPluginFigureReaders().filter(({ reader })=>{
28
+ if (!context.accept(reader)) return false;
29
+ // A site reader needs a site; a workspace reader reads with or without one.
30
+ if (reader.scope === 'site' && !context.hostId) return false;
31
+ return !reader.feature || checkEntitlement(org, reader.feature);
32
+ });
33
+ const plugins = [
34
+ ...new Set(candidates.map(pluginFigureReaderPlugin).filter((id)=>Boolean(id)))
35
+ ];
36
+ const released = new Set(plugins.length ? await ((_context_released = context.released) != null ? _context_released : releasedByFlags)(plugins, context.orgId) : []);
37
+ return candidates.filter((resolved)=>{
38
+ const plugin = pluginFigureReaderPlugin(resolved);
39
+ if (!plugin) return true;
40
+ if (!released.has(plugin)) return false;
41
+ return context.hostId ? isHostPluginEnabled(org, context.host, plugin) : isPluginEnabled(org, plugin);
42
+ });
43
+ }
44
+
45
+ //# sourceMappingURL=figure-readers.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/figure-readers.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 { checkEntitlement } from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport { isHostPluginEnabled, isPluginEnabled } from '@aglyn/aglyn/plugin-manager/enabled-plugins'\nimport {\n listPluginFigureReaders,\n pluginFigureReaderPlugin,\n type PluginFigureReader,\n type ResolvedPluginFigureReader,\n} from '@aglyn/aglyn/plugin-manager/plugin-figures'\nimport { filterEnabledPluginsByReleaseFlags } from './release-flags'\n\n/**\n * The figure readers a caller may read for one workspace or one site\n * (AGL-2915): the caller's half of the `plugin-figures` contract.\n *\n * The registry carries no authorization, so before a reader is read this\n * establishes that the workspace's plan includes the feature the figures are\n * sold under, and that the plugin whose records they are runs here: past its\n * release flag, on for the workspace and not switched off for the site. The\n * site belonging to the workspace, and the person's reach, are the caller's\n * own checks.\n */\n\n/** Which of a set of plugins are past their release flags for an org; the platform's flags by default. */\nexport type ReleasedFigurePlugins = (pluginIds: string[], orgId: string) => Promise<string[]>\n\nconst releasedByFlags: ReleasedFigurePlugins = (pluginIds, orgId) =>\n filterEnabledPluginsByReleaseFlags(pluginIds, { orgId, authorization: null })\n\nexport interface FigureReaderContext {\n orgId: string\n /** The site the figures are about; `null` for the workspace as a whole. */\n hostId: string | null\n /** The org document. */\n org: object | null\n /** The site's host document, already checked to belong to the org; `null` with no site. */\n host: Record<string, unknown> | null\n /** Which readers the caller asks about at all, before the gates. */\n accept: (reader: PluginFigureReader) => boolean\n released?: ReleasedFigurePlugins\n}\n\n/** The readers that pass the gates, ordered by id so a list of them is the same on every call. */\nexport async function eligibleFigureReaders(\n context: FigureReaderContext,\n): Promise<ResolvedPluginFigureReader[]> {\n const org = context.org as { enabledPlugins?: string[] } | null\n const candidates = listPluginFigureReaders().filter(({ reader }) => {\n if (!context.accept(reader)) return false\n // A site reader needs a site; a workspace reader reads with or without one.\n if (reader.scope === 'site' && !context.hostId) return false\n return !reader.feature || checkEntitlement(org as never, reader.feature)\n })\n const plugins = [\n ...new Set(candidates.map(pluginFigureReaderPlugin).filter((id): id is string => Boolean(id))),\n ]\n const released = new Set(\n plugins.length ? await (context.released ?? releasedByFlags)(plugins, context.orgId) : [],\n )\n return candidates.filter((resolved) => {\n const plugin = pluginFigureReaderPlugin(resolved)\n if (!plugin) return true\n if (!released.has(plugin)) return false\n return context.hostId\n ? isHostPluginEnabled(org, context.host as { disabledPlugins?: string[] } | null, plugin)\n : isPluginEnabled(org, plugin)\n })\n}\n"],"names":["checkEntitlement","isHostPluginEnabled","isPluginEnabled","listPluginFigureReaders","pluginFigureReaderPlugin","filterEnabledPluginsByReleaseFlags","releasedByFlags","pluginIds","orgId","authorization","eligibleFigureReaders","context","org","candidates","filter","reader","accept","scope","hostId","feature","plugins","Set","map","id","Boolean","released","length","resolved","plugin","has","host"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,gBAAgB,QAAQ,2CAA0C;AAC3E,SAASC,mBAAmB,EAAEC,eAAe,QAAQ,8CAA6C;AAClG,SACEC,uBAAuB,EACvBC,wBAAwB,QAGnB,6CAA4C;AACnD,SAASC,kCAAkC,QAAQ,qBAAiB;AAiBpE,MAAMC,kBAAyC,CAACC,WAAWC,QACzDH,mCAAmCE,WAAW;QAAEC;QAAOC,eAAe;IAAK;AAe7E,gGAAgG,GAChG,OAAO,eAAeC,sBACpBC,OAA4B;QAaFA;IAX1B,MAAMC,MAAMD,QAAQC,GAAG;IACvB,MAAMC,aAAaV,0BAA0BW,MAAM,CAAC,CAAC,EAAEC,MAAM,EAAE;QAC7D,IAAI,CAACJ,QAAQK,MAAM,CAACD,SAAS,OAAO;QACpC,4EAA4E;QAC5E,IAAIA,OAAOE,KAAK,KAAK,UAAU,CAACN,QAAQO,MAAM,EAAE,OAAO;QACvD,OAAO,CAACH,OAAOI,OAAO,IAAInB,iBAAiBY,KAAcG,OAAOI,OAAO;IACzE;IACA,MAAMC,UAAU;WACX,IAAIC,IAAIR,WAAWS,GAAG,CAAClB,0BAA0BU,MAAM,CAAC,CAACS,KAAqBC,QAAQD;KAC1F;IACD,MAAME,WAAW,IAAIJ,IACnBD,QAAQM,MAAM,GAAG,MAAM,EAACf,oBAAAA,QAAQc,QAAQ,YAAhBd,oBAAoBL,iBAAiBc,SAAST,QAAQH,KAAK,IAAI,EAAE;IAE3F,OAAOK,WAAWC,MAAM,CAAC,CAACa;QACxB,MAAMC,SAASxB,yBAAyBuB;QACxC,IAAI,CAACC,QAAQ,OAAO;QACpB,IAAI,CAACH,SAASI,GAAG,CAACD,SAAS,OAAO;QAClC,OAAOjB,QAAQO,MAAM,GACjBjB,oBAAoBW,KAAKD,QAAQmB,IAAI,EAA2CF,UAChF1B,gBAAgBU,KAAKgB;IAC3B;AACF"}
@@ -24,21 +24,34 @@
24
24
  var _env_MOBILE_PUSH_ENABLED;
25
25
  return ((_env_MOBILE_PUSH_ENABLED = env['MOBILE_PUSH_ENABLED']) != null ? _env_MOBILE_PUSH_ENABLED : '').trim() !== '0';
26
26
  }
27
- const senders = new Set();
27
+ /*
28
+ * The registry lives on `globalThis`, not in this module: `instrumentation.ts`
29
+ * registers the senders in its own copy of this module, and a route handler's
30
+ * `notifyUsers` reads another one (AGL-3412). A module-scoped set is empty
31
+ * where it is read, and every push is silently skipped.
32
+ */ const SENDERS_KEY = Symbol.for('@aglyn/tenant-data-admin:mobile-push-senders');
33
+ const globalScope = globalThis;
34
+ function senders() {
35
+ const existing = globalScope[SENDERS_KEY];
36
+ if (existing) return existing;
37
+ const created = new Set();
38
+ globalScope[SENDERS_KEY] = created;
39
+ return created;
40
+ }
28
41
  /**
29
42
  * Adds a push transport to the fan-out. `notifyUsers` hands every registered
30
43
  * sender the recipients whose preferences say push, after the feed entries
31
44
  * are committed and only while the kill switch is up. With none registered,
32
45
  * nothing is pushed. Returns the unregister function.
33
46
  */ export function registerMobilePushSender(sender) {
34
- senders.add(sender);
47
+ senders().add(sender);
35
48
  return ()=>{
36
- senders.delete(sender);
49
+ senders().delete(sender);
37
50
  };
38
51
  }
39
52
  /** The registered push transports, in registration order. */ export function mobilePushSenders() {
40
53
  return [
41
- ...senders
54
+ ...senders()
42
55
  ];
43
56
  }
44
57
 
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/mobile-push-switch.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 { AglynNotification } from '@aglyn/aglyn/server'\nimport type { Firestore } from 'firebase-admin/firestore'\n\n/**\n * Whether this deployment sends mobile push (AGL-3648).\n *\n * On unless `MOBILE_PUSH_ENABLED=0`: the variable is a kill switch, not an\n * opt-in, and it governs every push sender. Kept apart from the senders so\n * `notifyUsers` can ask before it calls one, and every caller reads the same\n * answer.\n */\nexport function mobilePushEnabled(env: Record<string, string | undefined> = process.env): boolean {\n return (env['MOBILE_PUSH_ENABLED'] ?? '').trim() !== '0'\n}\n\n/** The notification a push sender is handed, as the fan-out wrote it. */\nexport type MobilePushPayload = Omit<AglynNotification, '$id' | 'createdAt' | 'readAt'>\n\n/**\n * A push transport (APNs, FCM): sends one notification to the registered\n * devices (`users/{uid}/devices`) of `uids`. Must not throw on a delivery\n * failure; the console notification is the record and a push is a courtesy.\n */\nexport type MobilePushSender = (\n uids: readonly string[],\n payload: MobilePushPayload,\n context: { db: Firestore },\n) => Promise<void>\n\nconst senders = new Set<MobilePushSender>()\n\n/**\n * Adds a push transport to the fan-out. `notifyUsers` hands every registered\n * sender the recipients whose preferences say push, after the feed entries\n * are committed and only while the kill switch is up. With none registered,\n * nothing is pushed. Returns the unregister function.\n */\nexport function registerMobilePushSender(sender: MobilePushSender): () => void {\n senders.add(sender)\n return () => {\n senders.delete(sender)\n }\n}\n\n/** The registered push transports, in registration order. */\nexport function mobilePushSenders(): MobilePushSender[] {\n return [...senders]\n}\n"],"names":["mobilePushEnabled","env","process","trim","senders","Set","registerMobilePushSender","sender","add","delete","mobilePushSenders"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAKD;;;;;;;CAOC,GACD,OAAO,SAASA,kBAAkBC,MAA0CC,QAAQD,GAAG;QAC7EA;IAAR,OAAO,EAACA,2BAAAA,GAAG,CAAC,sBAAsB,YAA1BA,2BAA8B,IAAIE,IAAI,OAAO;AACvD;AAgBA,MAAMC,UAAU,IAAIC;AAEpB;;;;;CAKC,GACD,OAAO,SAASC,yBAAyBC,MAAwB;IAC/DH,QAAQI,GAAG,CAACD;IACZ,OAAO;QACLH,QAAQK,MAAM,CAACF;IACjB;AACF;AAEA,2DAA2D,GAC3D,OAAO,SAASG;IACd,OAAO;WAAIN;KAAQ;AACrB"}
1
+ {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/mobile-push-switch.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 { AglynNotification } from '@aglyn/aglyn/server'\nimport type { Firestore } from 'firebase-admin/firestore'\n\n/**\n * Whether this deployment sends mobile push (AGL-3648).\n *\n * On unless `MOBILE_PUSH_ENABLED=0`: the variable is a kill switch, not an\n * opt-in, and it governs every push sender. Kept apart from the senders so\n * `notifyUsers` can ask before it calls one, and every caller reads the same\n * answer.\n */\nexport function mobilePushEnabled(env: Record<string, string | undefined> = process.env): boolean {\n return (env['MOBILE_PUSH_ENABLED'] ?? '').trim() !== '0'\n}\n\n/** The notification a push sender is handed, as the fan-out wrote it. */\nexport type MobilePushPayload = Omit<AglynNotification, '$id' | 'createdAt' | 'readAt'>\n\n/**\n * A push transport (APNs, FCM): sends one notification to the registered\n * devices (`users/{uid}/devices`) of `uids`. Must not throw on a delivery\n * failure; the console notification is the record and a push is a courtesy.\n */\nexport type MobilePushSender = (\n uids: readonly string[],\n payload: MobilePushPayload,\n context: { db: Firestore },\n) => Promise<void>\n\n/*\n * The registry lives on `globalThis`, not in this module: `instrumentation.ts`\n * registers the senders in its own copy of this module, and a route handler's\n * `notifyUsers` reads another one (AGL-3412). A module-scoped set is empty\n * where it is read, and every push is silently skipped.\n */\nconst SENDERS_KEY = Symbol.for('@aglyn/tenant-data-admin:mobile-push-senders')\n\nconst globalScope = globalThis as typeof globalThis & {\n [SENDERS_KEY]?: Set<MobilePushSender>\n}\n\nfunction senders(): Set<MobilePushSender> {\n const existing = globalScope[SENDERS_KEY]\n if (existing) return existing\n const created = new Set<MobilePushSender>()\n globalScope[SENDERS_KEY] = created\n return created\n}\n\n/**\n * Adds a push transport to the fan-out. `notifyUsers` hands every registered\n * sender the recipients whose preferences say push, after the feed entries\n * are committed and only while the kill switch is up. With none registered,\n * nothing is pushed. Returns the unregister function.\n */\nexport function registerMobilePushSender(sender: MobilePushSender): () => void {\n senders().add(sender)\n return () => {\n senders().delete(sender)\n }\n}\n\n/** The registered push transports, in registration order. */\nexport function mobilePushSenders(): MobilePushSender[] {\n return [...senders()]\n}\n"],"names":["mobilePushEnabled","env","process","trim","SENDERS_KEY","Symbol","for","globalScope","globalThis","senders","existing","created","Set","registerMobilePushSender","sender","add","delete","mobilePushSenders"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAKD;;;;;;;CAOC,GACD,OAAO,SAASA,kBAAkBC,MAA0CC,QAAQD,GAAG;QAC7EA;IAAR,OAAO,EAACA,2BAAAA,GAAG,CAAC,sBAAsB,YAA1BA,2BAA8B,IAAIE,IAAI,OAAO;AACvD;AAgBA;;;;;CAKC,GACD,MAAMC,cAAcC,OAAOC,GAAG,CAAC;AAE/B,MAAMC,cAAcC;AAIpB,SAASC;IACP,MAAMC,WAAWH,WAAW,CAACH,YAAY;IACzC,IAAIM,UAAU,OAAOA;IACrB,MAAMC,UAAU,IAAIC;IACpBL,WAAW,CAACH,YAAY,GAAGO;IAC3B,OAAOA;AACT;AAEA;;;;;CAKC,GACD,OAAO,SAASE,yBAAyBC,MAAwB;IAC/DL,UAAUM,GAAG,CAACD;IACd,OAAO;QACLL,UAAUO,MAAM,CAACF;IACnB;AACF;AAEA,2DAA2D,GAC3D,OAAO,SAASG;IACd,OAAO;WAAIR;KAAU;AACvB"}
@@ -22,10 +22,13 @@
22
22
  * `push-delivery.ts`, and through it each transport, only when a
23
23
  * notification has push recipients.
24
24
  */ import { registerMobilePushSender } from "./mobile-push-switch.js";
25
- let registered = false;
25
+ // On `globalThis` for the same reason as the registry itself: a second
26
+ // module copy must not register a second sender and push everything twice.
27
+ const REGISTERED_KEY = Symbol.for('@aglyn/tenant-data-admin:native-push-registered');
28
+ const globalScope = globalThis;
26
29
  export function registerNativePushSenders() {
27
- if (registered) return;
28
- registered = true;
30
+ if (globalScope[REGISTERED_KEY]) return;
31
+ globalScope[REGISTERED_KEY] = true;
29
32
  registerMobilePushSender(async (uids, payload, context)=>{
30
33
  const { nativePushSender } = await import("./push-delivery.js");
31
34
  await nativePushSender(uids, payload, context);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/native-push.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\n/**\n * Registers the native apps' push delivery (APNs and FCM, AGL-3651) with the\n * fan-out, once per server instance. A deployment's server entry calls it at\n * boot (the console's and the tenant's `instrumentation.ts`).\n *\n * This file imports nothing heavy: the sender it registers imports\n * `push-delivery.ts`, and through it each transport, only when a\n * notification has push recipients.\n */\n\nimport { registerMobilePushSender } from './mobile-push-switch'\n\nlet registered = false\n\nexport function registerNativePushSenders(): void {\n if (registered) return\n registered = true\n registerMobilePushSender(async (uids, payload, context) => {\n const { nativePushSender } = await import('./push-delivery')\n await nativePushSender(uids, payload, context)\n })\n}\n"],"names":["registerMobilePushSender","registered","registerNativePushSenders","uids","payload","context","nativePushSender"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;CAQC,GAED,SAASA,wBAAwB,QAAQ,0BAAsB;AAE/D,IAAIC,aAAa;AAEjB,OAAO,SAASC;IACd,IAAID,YAAY;IAChBA,aAAa;IACbD,yBAAyB,OAAOG,MAAMC,SAASC;QAC7C,MAAM,EAAEC,gBAAgB,EAAE,GAAG,MAAM,MAAM,CAAC;QAC1C,MAAMA,iBAAiBH,MAAMC,SAASC;IACxC;AACF"}
1
+ {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/native-push.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\n/**\n * Registers the native apps' push delivery (APNs and FCM, AGL-3651) with the\n * fan-out, once per server instance. A deployment's server entry calls it at\n * boot (the console's and the tenant's `instrumentation.ts`).\n *\n * This file imports nothing heavy: the sender it registers imports\n * `push-delivery.ts`, and through it each transport, only when a\n * notification has push recipients.\n */\n\nimport { registerMobilePushSender } from './mobile-push-switch'\n\n// On `globalThis` for the same reason as the registry itself: a second\n// module copy must not register a second sender and push everything twice.\nconst REGISTERED_KEY = Symbol.for('@aglyn/tenant-data-admin:native-push-registered')\n\nconst globalScope = globalThis as typeof globalThis & { [REGISTERED_KEY]?: true }\n\nexport function registerNativePushSenders(): void {\n if (globalScope[REGISTERED_KEY]) return\n globalScope[REGISTERED_KEY] = true\n registerMobilePushSender(async (uids, payload, context) => {\n const { nativePushSender } = await import('./push-delivery')\n await nativePushSender(uids, payload, context)\n })\n}\n"],"names":["registerMobilePushSender","REGISTERED_KEY","Symbol","for","globalScope","globalThis","registerNativePushSenders","uids","payload","context","nativePushSender"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;CAQC,GAED,SAASA,wBAAwB,QAAQ,0BAAsB;AAE/D,uEAAuE;AACvE,2EAA2E;AAC3E,MAAMC,iBAAiBC,OAAOC,GAAG,CAAC;AAElC,MAAMC,cAAcC;AAEpB,OAAO,SAASC;IACd,IAAIF,WAAW,CAACH,eAAe,EAAE;IACjCG,WAAW,CAACH,eAAe,GAAG;IAC9BD,yBAAyB,OAAOO,MAAMC,SAASC;QAC7C,MAAM,EAAEC,gBAAgB,EAAE,GAAG,MAAM,MAAM,CAAC;QAC1C,MAAMA,iBAAiBH,MAAMC,SAASC;IACxC;AACF"}
@@ -47,10 +47,10 @@ const firestore = ()=>firebaseAdmin.app().firestore();
47
47
  * At most this many directory lookups per fan-out, and at most this many
48
48
  * notification emails.
49
49
  *
50
- * Both ceilings only ever bite on a fan-out where many recipients have
51
- * OPTED IN — the email channel defaults off outside a site's transactions
52
- * (`NOTIFICATION_TYPE_CHANNEL_DEFAULTS`), so the ordinary notification
53
- * costs exactly what it cost before this existed. They are here because a
50
+ * Both ceilings bite only on a fan-out where many recipients are emailed —
51
+ * the email channel defaults off outside the types in
52
+ * `NOTIFICATION_TYPE_CHANNEL_DEFAULTS`, and every fan-out goes to one
53
+ * workspace's or one site's people, or to staff. They are here because a
54
54
  * fan-out takes up to 400 uids and `notifyUsers` runs inside the mutation
55
55
  * that emitted it: a notification must not be able to turn one write into
56
56
  * four hundred directory reads and four hundred sends.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/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 {\n buildRoute,\n NOTIFICATION_SELF_SENT_EMAIL_TYPES,\n NOTIFICATION_SETTINGS_FIELD,\n normalizeNotificationLink,\n notificationChannelEnabled,\n type AglynNotification,\n Route,\n type NotificationSettings,\n} from '@aglyn/aglyn/server'\nimport { operatorAlertForNotificationType } from '@aglyn/aglyn/plugin-manager/operator-alerts'\nimport { isEmailConfigured, sendEmail } from '@aglyn/shared-util-email'\nimport { notificationPushEnabled } from '@aglyn/aglyn/app-utils/notification-push'\nimport { platformConsoleOrigin } from '@aglyn/aglyn/app-utils/platform-brand'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport { withoutMailWithheldAccounts } from './account-mail'\nimport { findUserByUidAcrossPools, listStaffUidsAcrossPools } from './auth-pools'\nimport { filterSuppressedEmails } from './email-suppression'\nimport { meterOrgEmail, meterPlatformEmail } from './email-metering'\nimport firebaseAdmin from './firebase-admin'\nimport { mobilePushEnabled, mobilePushSenders } from './mobile-push-switch'\nimport { listOrgMembers } from './organizations'\nimport {\n loadSystemEmail,\n renderLoadedSystemEmail,\n systemEmailBrand,\n systemEmailContent,\n type SystemEmailBrand,\n} from './render-system-email'\n\nconst firestore = () => firebaseAdmin.app().firestore()\n\nexport type NotificationPayload = Omit<\n AglynNotification,\n '$id' | 'createdAt' | 'readAt'\n>\n\nexport interface NotifyUsersOptions {\n /**\n * Addresses the caller already holds, by uid (AGL-3224).\n *\n * Purely an optimization, and one worth taking where it is free: a caller\n * that read the roster — `notifyOrgAdmins` does — has every address in hand\n * already, and without this the email half would look each one up again in\n * the directory. Absent uids fall back to that lookup, so passing a partial\n * map is fine and passing none is correct.\n */\n emails?: Readonly<Record<string, string | null | undefined>>\n /**\n * Who the fan-out is for (AGL-3367). `staff` is the platform talking to its\n * own people, so the email wears the platform's brand and is the platform's\n * cost even when the notification is ABOUT an org, which a canceled\n * subscription or a new ticket always is. Anything else speaks in the org's\n * brand when the notification names one.\n */\n audience?: 'staff'\n /**\n * Write the console notification only, and mail nobody through the\n * per-person email channel (AGL-3375): the caller has emailed the same\n * alert to the operator's inbox, and a staff member who also switched\n * email on would otherwise get it twice.\n */\n skipEmail?: boolean\n /**\n * People not to mail through the email channel for this one notification,\n * because the caller emails them the same event itself — the seller's\n * designed sale email beside a Buy Now order's notification. Everyone else\n * the fan-out reaches is mailed as their preferences say.\n */\n skipEmailFor?: readonly string[]\n /**\n * Particulars the email carries and the notification does not: a form\n * submission's answers, so the person reading the email has the inquiry\n * without opening the console.\n *\n * Email only, never written to the notification document or pushed. The\n * document is copied once per recipient and outlives the record it points\n * at, and a push lands on a lock screen; the record itself stays the one\n * place the visitor's answers are kept.\n */\n emailDetails?: readonly NotificationEmailDetail[]\n}\n\n/** One labeled line of a notification email's details. */\nexport interface NotificationEmailDetail {\n label: string\n value: string\n}\n\n/**\n * At most this many characters of details per email. A submission is capped\n * at 2,000 characters a field, so a long form would otherwise be a long email.\n */\nconst NOTIFY_EMAIL_MAX_DETAILS_CHARS = 10_000\n\n/**\n * The details as the email prints them: `Label: value`, one per line, a\n * value's own line breaks kept and blank values left out.\n */\nexport function formatNotificationEmailDetails(\n details: readonly NotificationEmailDetail[] | undefined,\n): string {\n const text = (details ?? [])\n .map(({ label, value }) => ({ label: label.trim(), value: value.trim() }))\n .filter(({ value }) => value)\n .map(({ label, value }) => (label ? `${label}: ${value}` : value))\n .join('\\n')\n return text.length > NOTIFY_EMAIL_MAX_DETAILS_CHARS\n ? `${text.slice(0, NOTIFY_EMAIL_MAX_DETAILS_CHARS).trimEnd()}…`\n : text\n}\n\n/**\n * At most this many directory lookups per fan-out, and at most this many\n * notification emails.\n *\n * Both ceilings only ever bite on a fan-out where many recipients have\n * OPTED IN — the email channel defaults off outside a site's transactions\n * (`NOTIFICATION_TYPE_CHANNEL_DEFAULTS`), so the ordinary notification\n * costs exactly what it cost before this existed. They are here because a\n * fan-out takes up to 400 uids and `notifyUsers` runs inside the mutation\n * that emitted it: a notification must not be able to turn one write into\n * four hundred directory reads and four hundred sends.\n */\nconst NOTIFY_EMAIL_MAX_LOOKUPS = 25\nconst NOTIFY_EMAIL_MAX_SENDS = 50\n\n/**\n * The email beside the console notification (AGL-3224).\n *\n * One send per recipient, never a shared `to:` list — two people who manage\n * the same site have not agreed to be shown each other's addresses, and the\n * settings link in the footer belongs to one person.\n *\n * `List-Unsubscribe` points at the settings page rather than at a one-click\n * endpoint: this is not marketing mail and RFC 8058's POST form would be\n * claiming a capability that does not exist. What it does do is put the way\n * out in the headers as well as the body, so a client that surfaces it shows\n * the person the page where the switch they want actually is.\n *\n * Rendered through the `notification` system email (AGL-3367), which is what\n * gives it the header and footer every other system email wears, and makes\n * it designable on the staff System emails page. It used to hand `sendEmail`\n * bare text, which is the unbranded card the fallback HTML part draws. The\n * template is read once per fan-out and rendered per recipient.\n *\n * Never throws, like everything else on this path.\n */\nasync function emailNotification(\n uids: string[],\n payload: NotificationPayload,\n known: Readonly<Record<string, string | null | undefined>>,\n audience: NotifyUsersOptions['audience'],\n emailDetails: NotifyUsersOptions['emailDetails'],\n): Promise<void> {\n /*\n * `platformConsoleOrigin`, never `NEXT_PUBLIC_CONSOLE_URL` read bare: this\n * runs in the site app as well as the console, and the site app's\n * deployment does not set that variable. Read bare, a notification a site\n * sends (a form submission, an order) would carry a button that opens\n * nothing and a settings line with no address.\n */\n const origin = platformConsoleOrigin()\n const settingsUrl = `${origin}${buildRoute(Route.MANAGE_NOTIFICATION_SETTINGS)}`\n const context = await notificationEmailContext(payload, audience)\n const url = notificationEmailUrl(payload, context, origin)\n const details = formatNotificationEmailDetails(emailDetails)\n const loaded = await loadSystemEmail('notification').catch(() => null)\n const fallbackText = [\n payload.title,\n payload.body ?? '',\n details,\n url,\n `Change what you are emailed about: ${settingsUrl}`,\n ]\n .filter(Boolean)\n .join('\\n\\n')\n let lookups = 0\n let sent = 0\n for (const uid of uids) {\n if (sent >= NOTIFY_EMAIL_MAX_SENDS) break\n let address = String(known[uid] ?? '').trim().toLowerCase()\n if (!address.includes('@')) {\n if (lookups >= NOTIFY_EMAIL_MAX_LOOKUPS) continue\n lookups += 1\n const pooled = await findUserByUidAcrossPools(uid).catch(() => null)\n address = String(pooled?.record?.email ?? '').trim().toLowerCase()\n }\n if (!address.includes('@')) continue\n const recipients = await filterSuppressedEmails([address])\n if (!recipients.length) continue\n const rendered = loaded\n ? renderLoadedSystemEmail(\n loaded,\n {\n ...context.brand.merge,\n 'notification.title': payload.title,\n 'notification.body': payload.body ?? '',\n 'notification.details': details,\n 'notification.url': url,\n settingsUrl,\n },\n context.brand.options,\n )\n : null\n const result = await sendEmail({\n to: recipients,\n ...systemEmailContent(rendered, {\n subject: payload.title,\n text: fallbackText,\n }),\n ...(context.brand.fromName ? { fromName: context.brand.fromName } : {}),\n context: 'notification',\n headers: { 'List-Unsubscribe': `<${settingsUrl}>` },\n })\n if (!result.sent) continue\n sent += 1\n // Whose cost it is: a notification to a workspace's people is that\n // workspace's mail, and a staff alert or an account-level notice is the\n // platform's, whichever org it is about.\n await (payload.orgId && audience !== 'staff'\n ? meterOrgEmail(payload.orgId)\n : meterPlatformEmail()\n ).catch(() => undefined)\n }\n}\n\n/** What a notification email needs from the org and site it is about. */\ninterface NotificationEmailContext {\n brand: SystemEmailBrand\n orgSlug?: string\n hostSubdomain?: string\n}\n\n/**\n * The org's brand, and the slug and subdomain its stored link is rewritten\n * with (AGL-3367): at most two reads per fan-out, made only when someone is\n * being emailed.\n *\n * A staff fan-out reads nothing. Its brand is the platform's, and its links\n * are staff routes that need no rewriting.\n */\nasync function notificationEmailContext(\n payload: NotificationPayload,\n audience: NotifyUsersOptions['audience'],\n): Promise<NotificationEmailContext> {\n if (audience === 'staff' || !payload.orgId) {\n return { brand: systemEmailBrand(null) }\n }\n try {\n const db = firestore()\n const [org, host] = await Promise.all([\n db.collection('orgs').doc(payload.orgId).get(),\n payload.hostId\n ? db.collection('hosts').doc(payload.hostId).get()\n : Promise.resolve(null),\n ])\n const slug = org.get('slug')\n const subdomain = host?.get('subdomain')\n return {\n brand: systemEmailBrand(org.exists ? (org.data() ?? null) : null),\n ...(typeof slug === 'string' && slug ? { orgSlug: slug } : {}),\n ...(typeof subdomain === 'string' && subdomain\n ? { hostSubdomain: subdomain }\n : {}),\n }\n } catch (error) {\n console.error('notification email context failed', error)\n return { brand: systemEmailBrand(null) }\n }\n}\n\n/**\n * Where the email's button goes: the notification's own link, rewritten onto\n * today's routes the way the console rewrites it when it is clicked, else\n * the notifications page. A stored host link is `/{hostDocId}/…`, which only\n * that rewrite turns into a page that exists.\n */\nfunction notificationEmailUrl(\n payload: NotificationPayload,\n context: NotificationEmailContext,\n origin: string,\n): string {\n const link = normalizeNotificationLink(payload.link, {\n orgSlug: context.orgSlug,\n hostId: payload.hostId,\n hostSubdomain: context.hostSubdomain,\n })\n if (link && /^https?:\\/\\//i.test(link)) return link\n return `${origin}${link?.startsWith('/') ? link : buildRoute(Route.MANAGE_NOTIFICATIONS)}`\n}\n\n/**\n * Notification fan-out (AGL-259): batch-writes one doc per recipient at\n * `users/{uid}/notifications`, and — for recipients who asked for it\n * (AGL-3224) — sends one email beside it. Never throws: a notification miss,\n * or a send that failed, must not break the mutation that emitted it.\n */\nexport async function notifyUsers(\n uids: Iterable<string>,\n payload: NotificationPayload,\n options: NotifyUsersOptions = {},\n): Promise<void> {\n try {\n const db = firestore()\n const targets = [...new Set(uids)].filter(Boolean).slice(0, 400)\n if (!targets.length) return\n // Per-user preferences (AGL-267, AGL-3223): one getAll over the user\n // docs, which now answers for both channels and for all three scopes —\n // the settings live on this document precisely so that stays one read.\n const userDocs = await db.getAll(\n ...targets.map((uid) => db.collection('users').doc(uid)),\n )\n const scope = { orgId: payload.orgId, hostId: payload.hostId }\n const batch = db.batch()\n let count = 0\n const mailTo: string[] = []\n const pushTo: string[] = []\n for (const userDoc of userDocs) {\n const settings = userDoc.get(NOTIFICATION_SETTINGS_FIELD) as\n | NotificationSettings\n | undefined\n const legacy = userDoc.get('notificationPrefs') as\n | Record<string, boolean>\n | undefined\n if (\n notificationChannelEnabled(\n settings,\n 'console',\n payload.type,\n scope,\n legacy,\n )\n ) {\n batch.set(\n db\n .collection('users')\n .doc(userDoc.id)\n .collection('notifications')\n .doc(),\n // `read: false` on create, so the feed can ask for unread and read\n // alike by equality (AGL-3321; see `AglynNotification.read`).\n { ...payload, read: false, createdAt: FieldValue.serverTimestamp() },\n )\n count += 1\n }\n // The mobile push channel (AGL-3620); unanswered, it follows the feed.\n if (notificationPushEnabled(settings, payload.type, scope, legacy)) {\n pushTo.push(userDoc.id)\n }\n if (\n notificationChannelEnabled(settings, 'email', payload.type, scope, legacy) &&\n !options.skipEmailFor?.includes(userDoc.id)\n ) {\n mailTo.push(userDoc.id)\n }\n }\n if (count > 0) await batch.commit()\n /*\n * The push after the commit for the same reason as the email below:\n * every registered transport is handed the recipients whose preferences\n * say push, unless the deployment has pulled the kill switch. A failing\n * transport is logged and never stops the email or another transport.\n */\n if (pushTo.length && mobilePushEnabled()) {\n for (const send of mobilePushSenders()) {\n try {\n await send(pushTo, payload, { db })\n } catch (error) {\n console.error('push delivery failed', error)\n }\n }\n }\n /*\n * THE EMAIL AFTER THE COMMIT, and not inside its `try`.\n *\n * The console notification is the durable record and the send is a\n * courtesy on top of it, so the order is the one where a failing network\n * call cannot lose the record. The two channels are independent by\n * design — a person may have muted the feed and asked for mail, or the\n * reverse — so neither is gated on the other having happened.\n *\n * Digests are excluded: they compose and send their own mail, under\n * their own switches, and the generic channel would send a second\n * message announcing that the first one had been sent.\n *\n * A locked or disabled account is not mailed (AGL-3418); its feed entry\n * above still records the event.\n */\n if (\n mailTo.length &&\n !options.skipEmail &&\n isEmailConfigured() &&\n !NOTIFICATION_SELF_SENT_EMAIL_TYPES.has(payload.type)\n ) {\n const reachable = await withoutMailWithheldAccounts(mailTo)\n if (!reachable.length) return\n await emailNotification(\n reachable,\n payload,\n options.emails ?? {},\n options.audience,\n options.emailDetails,\n )\n }\n } catch (error) {\n console.error('notification fan-out failed', error)\n }\n}\n\n// Staff are identified by a Firebase Auth custom claim (`staff`), which is not\n// a Firestore query — so the roster comes from paginating the auth users. A\n// burst of ticket activity shouldn't rescan every time, so the (small) result\n// is cached briefly. Fails soft to an empty list.\nlet staffUidCache: { uids: string[]; at: number } | null = null\nconst STAFF_CACHE_MS = 60_000\n\nasync function listStaffUids(): Promise<string[]> {\n const now = Date.now()\n if (staffUidCache && now - staffUidCache.at < STAFF_CACHE_MS) {\n return staffUidCache.uids\n }\n // Across ALL auth pools (AGL-1122). This scanned only the project pool, so\n // a staff member who signs in through enterprise SSO — whose account lives\n // in a GCIP tenant pool — was never in the fan-out. Nothing errored; the\n // notification simply never arrived, which is the worst shape a miss can\n // take on an alerting path.\n const uids = await listStaffUidsAcrossPools()\n staffUidCache = { uids, at: now }\n return uids\n}\n\n/**\n * Notifies every staff-claim holder (AGL-850) — the support-desk audience.\n * Staff are not org members, so `notifyOrgAdmins`/`notifyHostManagers` never\n * reach them; this enumerates the `staff` custom claim instead. The docs land\n * at `users/{uid}/notifications`, which the console notifications menu already\n * renders, so no separate staff inbox is needed. Never throws.\n *\n * A type the operator alert registry names (AGL-3377) — a fraud or risk\n * alert, a dispute nobody owns, a support ticket — is raised as that alert\n * instead: the same console notification, plus staff's switches, the\n * operator email or digest, and the webhook. See `raiseOperatorAlert`.\n */\nexport async function notifyStaff(payload: NotificationPayload): Promise<void> {\n try {\n const alert = operatorAlertForNotificationType(payload.type)\n if (alert) {\n const { raiseOperatorAlert } = await import('./operator-alerts')\n await raiseOperatorAlert(alert, {\n subject: payload.title,\n ...(payload.body ? { body: payload.body } : {}),\n ...(payload.level ? { level: payload.level } : {}),\n ...(payload.link ? { url: payload.link } : {}),\n ...(payload.orgId ? { orgId: payload.orgId } : {}),\n ...(payload.hostId ? { hostId: payload.hostId } : {}),\n })\n return\n }\n await notifyStaffConsole(payload)\n } catch (error) {\n console.error('staff notification failed', error)\n }\n}\n\n/**\n * The staff console notification alone, with the per-person email channel\n * it carries: what `notifyStaff` did before the registry, and what\n * `raiseOperatorAlert` writes as its first step. Never throws.\n */\nexport async function notifyStaffConsole(\n payload: NotificationPayload,\n options: { skipEmail?: boolean } = {},\n): Promise<void> {\n try {\n await notifyUsers(await listStaffUids(), payload, {\n audience: 'staff',\n ...(options.skipEmail ? { skipEmail: true } : {}),\n })\n } catch (error) {\n console.error('staff notification failed', error)\n }\n}\n\n/**\n * Notifies the org's owner + admins (billing, membership, org events).\n *\n * `skipEmail` is for a caller that emails the same notice to the same people\n * itself — the usage alerts do (AGL-3431) — so an admin who switched the\n * email channel on is not sent it twice.\n */\nexport async function notifyOrgAdmins(\n orgId: string,\n payload: NotificationPayload,\n options: Pick<NotifyUsersOptions, 'skipEmail'> = {},\n): Promise<void> {\n try {\n const members = await listOrgMembers(orgId)\n const admins = members.filter(\n (member) => member.role === 'owner' || member.role === 'admin',\n )\n // The roster rows carry addresses, so the email channel (AGL-3224) needs\n // no directory lookup for anyone reached this way.\n const emails: Record<string, string | undefined> = {}\n for (const member of admins) {\n if (member.email) emails[member.$id] = member.email\n }\n await notifyUsers(\n admins.map((member) => member.$id),\n { ...payload, orgId },\n { emails, ...(options.skipEmail ? { skipEmail: true } : {}) },\n )\n } catch (error) {\n console.error('org admin notification failed', error)\n }\n}\n\n/**\n * The name a site's managers know it by: the name they gave it, then its\n * address, then — for a doc with neither — its id.\n */\nexport function hostDisplayName(\n host: Record<string, unknown> | undefined,\n hostId: string,\n): string {\n for (const value of [host?.['displayName'], host?.['subdomain']]) {\n if (typeof value === 'string' && value.trim()) return value.trim()\n }\n return hostId\n}\n\n/**\n * Fills `{site}` in a host notification's title or body (AGL-3432).\n *\n * A manager of ten storefronts reads \"New order — $42.00\" and cannot tell\n * which store it came from, and the email shows only the body to someone who\n * skips the subject. `notifyHostManagers` already reads the host doc, so a\n * caller writes \"New order on {site}\" and pays no read of its own.\n */\nexport function withSiteName(text: string, site: string): string {\n return text.includes('{site}') ? text.split('{site}').join(site) : text\n}\n\n/**\n * Notifies everyone who manages a host (admin/editor in the host doc's\n * `memberRoles` projection) — the audience for form submissions and\n * bookings on that site.\n *\n * The OWNING ORG travels with the notification (AGL-1773). Host links are\n * stored in the legacy `/{hostDocId}/rest` shape and rewritten to\n * `/{orgSlug}/hosts/{subdomain}/rest` when they are FOLLOWED\n * (`normalizeNotificationLink`, AGL-644) — a rewrite that needs an org slug.\n * With no `orgId` on the doc the console had nothing to key on and fell back\n * to whichever org the reader happens to have OPEN, so a manager who belongs\n * to more than one workspace was routed to `/{other-org}/hosts/{subdomain}/…`\n * and got a designed 404: `HostGuard` only resolves subdomains belonging to\n * the current org. `notifyOrgAdmins` has always stamped it; the host fan-out\n * — every form submission, booking, order and stock alert — never did.\n *\n * The host doc already carries `orgId` (AGL-233), so this costs no extra\n * read. Spread conditionally: the field is optional on the host model and\n * Firestore rejects `undefined`.\n */\nexport async function notifyHostManagers(\n hostId: string,\n payload: NotificationPayload,\n options: {\n /**\n * Mail the workspace owner nothing through the email channel, because\n * the caller sends them their own email about the same event.\n */\n skipOwnerEmail?: boolean\n /** What the email alone carries; see {@link NotifyUsersOptions.emailDetails}. */\n emailDetails?: readonly NotificationEmailDetail[]\n } = {},\n): Promise<void> {\n try {\n const host = await firestore().collection('hosts').doc(hostId).get()\n const memberRoles =\n (host.get('memberRoles') as Record<string, string> | undefined) ?? {}\n const managers = Object.entries(memberRoles)\n .filter(([, role]) => role === 'admin' || role === 'editor')\n .map(([uid]) => uid)\n const orgId = payload.orgId ?? (host.get('orgId') as string | undefined)\n const site = hostDisplayName(host.data(), hostId)\n const ownerUid =\n options.skipOwnerEmail && orgId\n ? ((await firestore().collection('orgs').doc(orgId).get()).get('ownerUid') as\n | string\n | undefined)\n : undefined\n await notifyUsers(\n managers,\n {\n ...payload,\n title: withSiteName(payload.title, site),\n ...(payload.body !== undefined\n ? { body: withSiteName(payload.body, site) }\n : {}),\n hostId,\n ...(orgId ? { orgId } : {}),\n },\n {\n ...(ownerUid ? { skipEmailFor: [ownerUid] } : {}),\n ...(options.emailDetails ? { emailDetails: options.emailDetails } : {}),\n },\n )\n } catch (error) {\n console.error('host manager notification failed', error)\n }\n}\n"],"names":["buildRoute","NOTIFICATION_SELF_SENT_EMAIL_TYPES","NOTIFICATION_SETTINGS_FIELD","normalizeNotificationLink","notificationChannelEnabled","Route","operatorAlertForNotificationType","isEmailConfigured","sendEmail","notificationPushEnabled","platformConsoleOrigin","FieldValue","withoutMailWithheldAccounts","findUserByUidAcrossPools","listStaffUidsAcrossPools","filterSuppressedEmails","meterOrgEmail","meterPlatformEmail","firebaseAdmin","mobilePushEnabled","mobilePushSenders","listOrgMembers","loadSystemEmail","renderLoadedSystemEmail","systemEmailBrand","systemEmailContent","firestore","app","NOTIFY_EMAIL_MAX_DETAILS_CHARS","formatNotificationEmailDetails","details","text","map","label","value","trim","filter","join","length","slice","trimEnd","NOTIFY_EMAIL_MAX_LOOKUPS","NOTIFY_EMAIL_MAX_SENDS","emailNotification","uids","payload","known","audience","emailDetails","origin","settingsUrl","MANAGE_NOTIFICATION_SETTINGS","context","notificationEmailContext","url","notificationEmailUrl","loaded","catch","fallbackText","title","body","Boolean","lookups","sent","uid","address","String","toLowerCase","includes","pooled","record","email","recipients","rendered","brand","merge","options","result","to","subject","fromName","headers","orgId","undefined","org","db","host","Promise","all","collection","doc","get","hostId","resolve","slug","subdomain","exists","data","orgSlug","hostSubdomain","error","console","link","test","startsWith","MANAGE_NOTIFICATIONS","notifyUsers","targets","Set","userDocs","getAll","scope","batch","count","mailTo","pushTo","userDoc","settings","legacy","type","set","id","read","createdAt","serverTimestamp","push","skipEmailFor","commit","send","skipEmail","has","reachable","emails","staffUidCache","STAFF_CACHE_MS","listStaffUids","now","Date","at","notifyStaff","alert","raiseOperatorAlert","level","notifyStaffConsole","notifyOrgAdmins","members","admins","member","role","$id","hostDisplayName","withSiteName","site","split","notifyHostManagers","memberRoles","managers","Object","entries","ownerUid","skipOwnerEmail"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,UAAU,EACVC,kCAAkC,EAClCC,2BAA2B,EAC3BC,yBAAyB,EACzBC,0BAA0B,EAE1BC,KAAK,QAEA,sBAAqB;AAC5B,SAASC,gCAAgC,QAAQ,8CAA6C;AAC9F,SAASC,iBAAiB,EAAEC,SAAS,QAAQ,2BAA0B;AACvE,SAASC,uBAAuB,QAAQ,2CAA0C;AAClF,SAASC,qBAAqB,QAAQ,wCAAuC;AAC7E,SAASC,UAAU,QAAQ,2BAA0B;AACrD,SAASC,2BAA2B,QAAQ,oBAAgB;AAC5D,SAASC,wBAAwB,EAAEC,wBAAwB,QAAQ,kBAAc;AACjF,SAASC,sBAAsB,QAAQ,yBAAqB;AAC5D,SAASC,aAAa,EAAEC,kBAAkB,QAAQ,sBAAkB;AACpE,OAAOC,mBAAmB,sBAAkB;AAC5C,SAASC,iBAAiB,EAAEC,iBAAiB,QAAQ,0BAAsB;AAC3E,SAASC,cAAc,QAAQ,qBAAiB;AAChD,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AG;YAAEA,cAAc4B,QAAQ5B,YAAY;QAAC,IAAI,CAAC;IAG3E,EAAE,OAAOoD,OAAO;QACdC,QAAQD,KAAK,CAAC,oCAAoCA;IACpD;AACF"}
1
+ {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/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 {\n buildRoute,\n NOTIFICATION_SELF_SENT_EMAIL_TYPES,\n NOTIFICATION_SETTINGS_FIELD,\n normalizeNotificationLink,\n notificationChannelEnabled,\n type AglynNotification,\n Route,\n type NotificationSettings,\n} from '@aglyn/aglyn/server'\nimport { operatorAlertForNotificationType } from '@aglyn/aglyn/plugin-manager/operator-alerts'\nimport { isEmailConfigured, sendEmail } from '@aglyn/shared-util-email'\nimport { notificationPushEnabled } from '@aglyn/aglyn/app-utils/notification-push'\nimport { platformConsoleOrigin } from '@aglyn/aglyn/app-utils/platform-brand'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport { withoutMailWithheldAccounts } from './account-mail'\nimport { findUserByUidAcrossPools, listStaffUidsAcrossPools } from './auth-pools'\nimport { filterSuppressedEmails } from './email-suppression'\nimport { meterOrgEmail, meterPlatformEmail } from './email-metering'\nimport firebaseAdmin from './firebase-admin'\nimport { mobilePushEnabled, mobilePushSenders } from './mobile-push-switch'\nimport { listOrgMembers } from './organizations'\nimport {\n loadSystemEmail,\n renderLoadedSystemEmail,\n systemEmailBrand,\n systemEmailContent,\n type SystemEmailBrand,\n} from './render-system-email'\n\nconst firestore = () => firebaseAdmin.app().firestore()\n\nexport type NotificationPayload = Omit<\n AglynNotification,\n '$id' | 'createdAt' | 'readAt'\n>\n\nexport interface NotifyUsersOptions {\n /**\n * Addresses the caller already holds, by uid (AGL-3224).\n *\n * Purely an optimization, and one worth taking where it is free: a caller\n * that read the roster — `notifyOrgAdmins` does — has every address in hand\n * already, and without this the email half would look each one up again in\n * the directory. Absent uids fall back to that lookup, so passing a partial\n * map is fine and passing none is correct.\n */\n emails?: Readonly<Record<string, string | null | undefined>>\n /**\n * Who the fan-out is for (AGL-3367). `staff` is the platform talking to its\n * own people, so the email wears the platform's brand and is the platform's\n * cost even when the notification is ABOUT an org, which a canceled\n * subscription or a new ticket always is. Anything else speaks in the org's\n * brand when the notification names one.\n */\n audience?: 'staff'\n /**\n * Write the console notification only, and mail nobody through the\n * per-person email channel (AGL-3375): the caller has emailed the same\n * alert to the operator's inbox, and a staff member who also switched\n * email on would otherwise get it twice.\n */\n skipEmail?: boolean\n /**\n * People not to mail through the email channel for this one notification,\n * because the caller emails them the same event itself — the seller's\n * designed sale email beside a Buy Now order's notification. Everyone else\n * the fan-out reaches is mailed as their preferences say.\n */\n skipEmailFor?: readonly string[]\n /**\n * Particulars the email carries and the notification does not: a form\n * submission's answers, so the person reading the email has the inquiry\n * without opening the console.\n *\n * Email only, never written to the notification document or pushed. The\n * document is copied once per recipient and outlives the record it points\n * at, and a push lands on a lock screen; the record itself stays the one\n * place the visitor's answers are kept.\n */\n emailDetails?: readonly NotificationEmailDetail[]\n}\n\n/** One labeled line of a notification email's details. */\nexport interface NotificationEmailDetail {\n label: string\n value: string\n}\n\n/**\n * At most this many characters of details per email. A submission is capped\n * at 2,000 characters a field, so a long form would otherwise be a long email.\n */\nconst NOTIFY_EMAIL_MAX_DETAILS_CHARS = 10_000\n\n/**\n * The details as the email prints them: `Label: value`, one per line, a\n * value's own line breaks kept and blank values left out.\n */\nexport function formatNotificationEmailDetails(\n details: readonly NotificationEmailDetail[] | undefined,\n): string {\n const text = (details ?? [])\n .map(({ label, value }) => ({ label: label.trim(), value: value.trim() }))\n .filter(({ value }) => value)\n .map(({ label, value }) => (label ? `${label}: ${value}` : value))\n .join('\\n')\n return text.length > NOTIFY_EMAIL_MAX_DETAILS_CHARS\n ? `${text.slice(0, NOTIFY_EMAIL_MAX_DETAILS_CHARS).trimEnd()}…`\n : text\n}\n\n/**\n * At most this many directory lookups per fan-out, and at most this many\n * notification emails.\n *\n * Both ceilings bite only on a fan-out where many recipients are emailed —\n * the email channel defaults off outside the types in\n * `NOTIFICATION_TYPE_CHANNEL_DEFAULTS`, and every fan-out goes to one\n * workspace's or one site's people, or to staff. They are here because a\n * fan-out takes up to 400 uids and `notifyUsers` runs inside the mutation\n * that emitted it: a notification must not be able to turn one write into\n * four hundred directory reads and four hundred sends.\n */\nconst NOTIFY_EMAIL_MAX_LOOKUPS = 25\nconst NOTIFY_EMAIL_MAX_SENDS = 50\n\n/**\n * The email beside the console notification (AGL-3224).\n *\n * One send per recipient, never a shared `to:` list — two people who manage\n * the same site have not agreed to be shown each other's addresses, and the\n * settings link in the footer belongs to one person.\n *\n * `List-Unsubscribe` points at the settings page rather than at a one-click\n * endpoint: this is not marketing mail and RFC 8058's POST form would be\n * claiming a capability that does not exist. What it does do is put the way\n * out in the headers as well as the body, so a client that surfaces it shows\n * the person the page where the switch they want actually is.\n *\n * Rendered through the `notification` system email (AGL-3367), which is what\n * gives it the header and footer every other system email wears, and makes\n * it designable on the staff System emails page. It used to hand `sendEmail`\n * bare text, which is the unbranded card the fallback HTML part draws. The\n * template is read once per fan-out and rendered per recipient.\n *\n * Never throws, like everything else on this path.\n */\nasync function emailNotification(\n uids: string[],\n payload: NotificationPayload,\n known: Readonly<Record<string, string | null | undefined>>,\n audience: NotifyUsersOptions['audience'],\n emailDetails: NotifyUsersOptions['emailDetails'],\n): Promise<void> {\n /*\n * `platformConsoleOrigin`, never `NEXT_PUBLIC_CONSOLE_URL` read bare: this\n * runs in the site app as well as the console, and the site app's\n * deployment does not set that variable. Read bare, a notification a site\n * sends (a form submission, an order) would carry a button that opens\n * nothing and a settings line with no address.\n */\n const origin = platformConsoleOrigin()\n const settingsUrl = `${origin}${buildRoute(Route.MANAGE_NOTIFICATION_SETTINGS)}`\n const context = await notificationEmailContext(payload, audience)\n const url = notificationEmailUrl(payload, context, origin)\n const details = formatNotificationEmailDetails(emailDetails)\n const loaded = await loadSystemEmail('notification').catch(() => null)\n const fallbackText = [\n payload.title,\n payload.body ?? '',\n details,\n url,\n `Change what you are emailed about: ${settingsUrl}`,\n ]\n .filter(Boolean)\n .join('\\n\\n')\n let lookups = 0\n let sent = 0\n for (const uid of uids) {\n if (sent >= NOTIFY_EMAIL_MAX_SENDS) break\n let address = String(known[uid] ?? '').trim().toLowerCase()\n if (!address.includes('@')) {\n if (lookups >= NOTIFY_EMAIL_MAX_LOOKUPS) continue\n lookups += 1\n const pooled = await findUserByUidAcrossPools(uid).catch(() => null)\n address = String(pooled?.record?.email ?? '').trim().toLowerCase()\n }\n if (!address.includes('@')) continue\n const recipients = await filterSuppressedEmails([address])\n if (!recipients.length) continue\n const rendered = loaded\n ? renderLoadedSystemEmail(\n loaded,\n {\n ...context.brand.merge,\n 'notification.title': payload.title,\n 'notification.body': payload.body ?? '',\n 'notification.details': details,\n 'notification.url': url,\n settingsUrl,\n },\n context.brand.options,\n )\n : null\n const result = await sendEmail({\n to: recipients,\n ...systemEmailContent(rendered, {\n subject: payload.title,\n text: fallbackText,\n }),\n ...(context.brand.fromName ? { fromName: context.brand.fromName } : {}),\n context: 'notification',\n headers: { 'List-Unsubscribe': `<${settingsUrl}>` },\n })\n if (!result.sent) continue\n sent += 1\n // Whose cost it is: a notification to a workspace's people is that\n // workspace's mail, and a staff alert or an account-level notice is the\n // platform's, whichever org it is about.\n await (payload.orgId && audience !== 'staff'\n ? meterOrgEmail(payload.orgId)\n : meterPlatformEmail()\n ).catch(() => undefined)\n }\n}\n\n/** What a notification email needs from the org and site it is about. */\ninterface NotificationEmailContext {\n brand: SystemEmailBrand\n orgSlug?: string\n hostSubdomain?: string\n}\n\n/**\n * The org's brand, and the slug and subdomain its stored link is rewritten\n * with (AGL-3367): at most two reads per fan-out, made only when someone is\n * being emailed.\n *\n * A staff fan-out reads nothing. Its brand is the platform's, and its links\n * are staff routes that need no rewriting.\n */\nasync function notificationEmailContext(\n payload: NotificationPayload,\n audience: NotifyUsersOptions['audience'],\n): Promise<NotificationEmailContext> {\n if (audience === 'staff' || !payload.orgId) {\n return { brand: systemEmailBrand(null) }\n }\n try {\n const db = firestore()\n const [org, host] = await Promise.all([\n db.collection('orgs').doc(payload.orgId).get(),\n payload.hostId\n ? db.collection('hosts').doc(payload.hostId).get()\n : Promise.resolve(null),\n ])\n const slug = org.get('slug')\n const subdomain = host?.get('subdomain')\n return {\n brand: systemEmailBrand(org.exists ? (org.data() ?? null) : null),\n ...(typeof slug === 'string' && slug ? { orgSlug: slug } : {}),\n ...(typeof subdomain === 'string' && subdomain\n ? { hostSubdomain: subdomain }\n : {}),\n }\n } catch (error) {\n console.error('notification email context failed', error)\n return { brand: systemEmailBrand(null) }\n }\n}\n\n/**\n * Where the email's button goes: the notification's own link, rewritten onto\n * today's routes the way the console rewrites it when it is clicked, else\n * the notifications page. A stored host link is `/{hostDocId}/…`, which only\n * that rewrite turns into a page that exists.\n */\nfunction notificationEmailUrl(\n payload: NotificationPayload,\n context: NotificationEmailContext,\n origin: string,\n): string {\n const link = normalizeNotificationLink(payload.link, {\n orgSlug: context.orgSlug,\n hostId: payload.hostId,\n hostSubdomain: context.hostSubdomain,\n })\n if (link && /^https?:\\/\\//i.test(link)) return link\n return `${origin}${link?.startsWith('/') ? link : buildRoute(Route.MANAGE_NOTIFICATIONS)}`\n}\n\n/**\n * Notification fan-out (AGL-259): batch-writes one doc per recipient at\n * `users/{uid}/notifications`, and — for recipients who asked for it\n * (AGL-3224) — sends one email beside it. Never throws: a notification miss,\n * or a send that failed, must not break the mutation that emitted it.\n */\nexport async function notifyUsers(\n uids: Iterable<string>,\n payload: NotificationPayload,\n options: NotifyUsersOptions = {},\n): Promise<void> {\n try {\n const db = firestore()\n const targets = [...new Set(uids)].filter(Boolean).slice(0, 400)\n if (!targets.length) return\n // Per-user preferences (AGL-267, AGL-3223): one getAll over the user\n // docs, which now answers for both channels and for all three scopes —\n // the settings live on this document precisely so that stays one read.\n const userDocs = await db.getAll(\n ...targets.map((uid) => db.collection('users').doc(uid)),\n )\n const scope = { orgId: payload.orgId, hostId: payload.hostId }\n const batch = db.batch()\n let count = 0\n const mailTo: string[] = []\n const pushTo: string[] = []\n for (const userDoc of userDocs) {\n const settings = userDoc.get(NOTIFICATION_SETTINGS_FIELD) as\n | NotificationSettings\n | undefined\n const legacy = userDoc.get('notificationPrefs') as\n | Record<string, boolean>\n | undefined\n if (\n notificationChannelEnabled(\n settings,\n 'console',\n payload.type,\n scope,\n legacy,\n )\n ) {\n batch.set(\n db\n .collection('users')\n .doc(userDoc.id)\n .collection('notifications')\n .doc(),\n // `read: false` on create, so the feed can ask for unread and read\n // alike by equality (AGL-3321; see `AglynNotification.read`).\n { ...payload, read: false, createdAt: FieldValue.serverTimestamp() },\n )\n count += 1\n }\n // The mobile push channel (AGL-3620); unanswered, it follows the feed.\n if (notificationPushEnabled(settings, payload.type, scope, legacy)) {\n pushTo.push(userDoc.id)\n }\n if (\n notificationChannelEnabled(settings, 'email', payload.type, scope, legacy) &&\n !options.skipEmailFor?.includes(userDoc.id)\n ) {\n mailTo.push(userDoc.id)\n }\n }\n if (count > 0) await batch.commit()\n /*\n * The push after the commit for the same reason as the email below:\n * every registered transport is handed the recipients whose preferences\n * say push, unless the deployment has pulled the kill switch. A failing\n * transport is logged and never stops the email or another transport.\n */\n if (pushTo.length && mobilePushEnabled()) {\n for (const send of mobilePushSenders()) {\n try {\n await send(pushTo, payload, { db })\n } catch (error) {\n console.error('push delivery failed', error)\n }\n }\n }\n /*\n * THE EMAIL AFTER THE COMMIT, and not inside its `try`.\n *\n * The console notification is the durable record and the send is a\n * courtesy on top of it, so the order is the one where a failing network\n * call cannot lose the record. The two channels are independent by\n * design — a person may have muted the feed and asked for mail, or the\n * reverse — so neither is gated on the other having happened.\n *\n * Digests are excluded: they compose and send their own mail, under\n * their own switches, and the generic channel would send a second\n * message announcing that the first one had been sent.\n *\n * A locked or disabled account is not mailed (AGL-3418); its feed entry\n * above still records the event.\n */\n if (\n mailTo.length &&\n !options.skipEmail &&\n isEmailConfigured() &&\n !NOTIFICATION_SELF_SENT_EMAIL_TYPES.has(payload.type)\n ) {\n const reachable = await withoutMailWithheldAccounts(mailTo)\n if (!reachable.length) return\n await emailNotification(\n reachable,\n payload,\n options.emails ?? {},\n options.audience,\n options.emailDetails,\n )\n }\n } catch (error) {\n console.error('notification fan-out failed', error)\n }\n}\n\n// Staff are identified by a Firebase Auth custom claim (`staff`), which is not\n// a Firestore query — so the roster comes from paginating the auth users. A\n// burst of ticket activity shouldn't rescan every time, so the (small) result\n// is cached briefly. Fails soft to an empty list.\nlet staffUidCache: { uids: string[]; at: number } | null = null\nconst STAFF_CACHE_MS = 60_000\n\nasync function listStaffUids(): Promise<string[]> {\n const now = Date.now()\n if (staffUidCache && now - staffUidCache.at < STAFF_CACHE_MS) {\n return staffUidCache.uids\n }\n // Across ALL auth pools (AGL-1122). This scanned only the project pool, so\n // a staff member who signs in through enterprise SSO — whose account lives\n // in a GCIP tenant pool — was never in the fan-out. Nothing errored; the\n // notification simply never arrived, which is the worst shape a miss can\n // take on an alerting path.\n const uids = await listStaffUidsAcrossPools()\n staffUidCache = { uids, at: now }\n return uids\n}\n\n/**\n * Notifies every staff-claim holder (AGL-850) — the support-desk audience.\n * Staff are not org members, so `notifyOrgAdmins`/`notifyHostManagers` never\n * reach them; this enumerates the `staff` custom claim instead. The docs land\n * at `users/{uid}/notifications`, which the console notifications menu already\n * renders, so no separate staff inbox is needed. Never throws.\n *\n * A type the operator alert registry names (AGL-3377) — a fraud or risk\n * alert, a dispute nobody owns, a support ticket — is raised as that alert\n * instead: the same console notification, plus staff's switches, the\n * operator email or digest, and the webhook. See `raiseOperatorAlert`.\n */\nexport async function notifyStaff(payload: NotificationPayload): Promise<void> {\n try {\n const alert = operatorAlertForNotificationType(payload.type)\n if (alert) {\n const { raiseOperatorAlert } = await import('./operator-alerts')\n await raiseOperatorAlert(alert, {\n subject: payload.title,\n ...(payload.body ? { body: payload.body } : {}),\n ...(payload.level ? { level: payload.level } : {}),\n ...(payload.link ? { url: payload.link } : {}),\n ...(payload.orgId ? { orgId: payload.orgId } : {}),\n ...(payload.hostId ? { hostId: payload.hostId } : {}),\n })\n return\n }\n await notifyStaffConsole(payload)\n } catch (error) {\n console.error('staff notification failed', error)\n }\n}\n\n/**\n * The staff console notification alone, with the per-person email channel\n * it carries: what `notifyStaff` did before the registry, and what\n * `raiseOperatorAlert` writes as its first step. Never throws.\n */\nexport async function notifyStaffConsole(\n payload: NotificationPayload,\n options: { skipEmail?: boolean } = {},\n): Promise<void> {\n try {\n await notifyUsers(await listStaffUids(), payload, {\n audience: 'staff',\n ...(options.skipEmail ? { skipEmail: true } : {}),\n })\n } catch (error) {\n console.error('staff notification failed', error)\n }\n}\n\n/**\n * Notifies the org's owner + admins (billing, membership, org events).\n *\n * `skipEmail` is for a caller that emails the same notice to the same people\n * itself — the usage alerts do (AGL-3431) — so an admin who switched the\n * email channel on is not sent it twice.\n */\nexport async function notifyOrgAdmins(\n orgId: string,\n payload: NotificationPayload,\n options: Pick<NotifyUsersOptions, 'skipEmail'> = {},\n): Promise<void> {\n try {\n const members = await listOrgMembers(orgId)\n const admins = members.filter(\n (member) => member.role === 'owner' || member.role === 'admin',\n )\n // The roster rows carry addresses, so the email channel (AGL-3224) needs\n // no directory lookup for anyone reached this way.\n const emails: Record<string, string | undefined> = {}\n for (const member of admins) {\n if (member.email) emails[member.$id] = member.email\n }\n await notifyUsers(\n admins.map((member) => member.$id),\n { ...payload, orgId },\n { emails, ...(options.skipEmail ? { skipEmail: true } : {}) },\n )\n } catch (error) {\n console.error('org admin notification failed', error)\n }\n}\n\n/**\n * The name a site's managers know it by: the name they gave it, then its\n * address, then — for a doc with neither — its id.\n */\nexport function hostDisplayName(\n host: Record<string, unknown> | undefined,\n hostId: string,\n): string {\n for (const value of [host?.['displayName'], host?.['subdomain']]) {\n if (typeof value === 'string' && value.trim()) return value.trim()\n }\n return hostId\n}\n\n/**\n * Fills `{site}` in a host notification's title or body (AGL-3432).\n *\n * A manager of ten storefronts reads \"New order — $42.00\" and cannot tell\n * which store it came from, and the email shows only the body to someone who\n * skips the subject. `notifyHostManagers` already reads the host doc, so a\n * caller writes \"New order on {site}\" and pays no read of its own.\n */\nexport function withSiteName(text: string, site: string): string {\n return text.includes('{site}') ? text.split('{site}').join(site) : text\n}\n\n/**\n * Notifies everyone who manages a host (admin/editor in the host doc's\n * `memberRoles` projection) — the audience for form submissions and\n * bookings on that site.\n *\n * The OWNING ORG travels with the notification (AGL-1773). Host links are\n * stored in the legacy `/{hostDocId}/rest` shape and rewritten to\n * `/{orgSlug}/hosts/{subdomain}/rest` when they are FOLLOWED\n * (`normalizeNotificationLink`, AGL-644) — a rewrite that needs an org slug.\n * With no `orgId` on the doc the console had nothing to key on and fell back\n * to whichever org the reader happens to have OPEN, so a manager who belongs\n * to more than one workspace was routed to `/{other-org}/hosts/{subdomain}/…`\n * and got a designed 404: `HostGuard` only resolves subdomains belonging to\n * the current org. `notifyOrgAdmins` has always stamped it; the host fan-out\n * — every form submission, booking, order and stock alert — never did.\n *\n * The host doc already carries `orgId` (AGL-233), so this costs no extra\n * read. Spread conditionally: the field is optional on the host model and\n * Firestore rejects `undefined`.\n */\nexport async function notifyHostManagers(\n hostId: string,\n payload: NotificationPayload,\n options: {\n /**\n * Mail the workspace owner nothing through the email channel, because\n * the caller sends them their own email about the same event.\n */\n skipOwnerEmail?: boolean\n /** What the email alone carries; see {@link NotifyUsersOptions.emailDetails}. */\n emailDetails?: readonly NotificationEmailDetail[]\n } = {},\n): Promise<void> {\n try {\n const host = await firestore().collection('hosts').doc(hostId).get()\n const memberRoles =\n (host.get('memberRoles') as Record<string, string> | undefined) ?? {}\n const managers = Object.entries(memberRoles)\n .filter(([, role]) => role === 'admin' || role === 'editor')\n .map(([uid]) => uid)\n const orgId = payload.orgId ?? (host.get('orgId') as string | undefined)\n const site = hostDisplayName(host.data(), hostId)\n const ownerUid =\n options.skipOwnerEmail && orgId\n ? ((await firestore().collection('orgs').doc(orgId).get()).get('ownerUid') as\n | string\n | undefined)\n : undefined\n await notifyUsers(\n managers,\n {\n ...payload,\n title: withSiteName(payload.title, site),\n ...(payload.body !== undefined\n ? { body: withSiteName(payload.body, site) }\n : {}),\n hostId,\n ...(orgId ? { orgId } : {}),\n },\n {\n ...(ownerUid ? { skipEmailFor: [ownerUid] } : {}),\n ...(options.emailDetails ? { emailDetails: options.emailDetails } : {}),\n },\n )\n } catch (error) {\n console.error('host manager notification failed', error)\n }\n}\n"],"names":["buildRoute","NOTIFICATION_SELF_SENT_EMAIL_TYPES","NOTIFICATION_SETTINGS_FIELD","normalizeNotificationLink","notificationChannelEnabled","Route","operatorAlertForNotificationType","isEmailConfigured","sendEmail","notificationPushEnabled","platformConsoleOrigin","FieldValue","withoutMailWithheldAccounts","findUserByUidAcrossPools","listStaffUidsAcrossPools","filterSuppressedEmails","meterOrgEmail","meterPlatformEmail","firebaseAdmin","mobilePushEnabled","mobilePushSenders","listOrgMembers","loadSystemEmail","renderLoadedSystemEmail","systemEmailBrand","systemEmailContent","firestore","app","NOTIFY_EMAIL_MAX_DETAILS_CHARS","formatNotificationEmailDetails","details","text","map","label","value","trim","filter","join","length","slice","trimEnd","NOTIFY_EMAIL_MAX_LOOKUPS","NOTIFY_EMAIL_MAX_SENDS","emailNotification","uids","payload","known","audience","emailDetails","origin","settingsUrl","MANAGE_NOTIFICATION_SETTINGS","context","notificationEmailContext","url","notificationEmailUrl","loaded","catch","fallbackText","title","body","Boolean","lookups","sent","uid","address","String","toLowerCase","includes","pooled","record","email","recipients","rendered","brand","merge","options","result","to","subject","fromName","headers","orgId","undefined","org","db","host","Promise","all","collection","doc","get","hostId","resolve","slug","subdomain","exists","data","orgSlug","hostSubdomain","error","console","link","test","startsWith","MANAGE_NOTIFICATIONS","notifyUsers","targets","Set","userDocs","getAll","scope","batch","count","mailTo","pushTo","userDoc","settings","legacy","type","set","id","read","createdAt","serverTimestamp","push","skipEmailFor","commit","send","skipEmail","has","reachable","emails","staffUidCache","STAFF_CACHE_MS","listStaffUids","now","Date","at","notifyStaff","alert","raiseOperatorAlert","level","notifyStaffConsole","notifyOrgAdmins","members","admins","member","role","$id","hostDisplayName","withSiteName","site","split","notifyHostManagers","memberRoles","managers","Object","entries","ownerUid","skipOwnerEmail"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,UAAU,EACVC,kCAAkC,EAClCC,2BAA2B,EAC3BC,yBAAyB,EACzBC,0BAA0B,EAE1BC,KAAK,QAEA,sBAAqB;AAC5B,SAASC,gCAAgC,QAAQ,8CAA6C;AAC9F,SAASC,iBAAiB,EAAEC,SAAS,QAAQ,2BAA0B;AACvE,SAASC,uBAAuB,QAAQ,2CAA0C;AAClF,SAASC,qBAAqB,QAAQ,wCAAuC;AAC7E,SAASC,UAAU,QAAQ,2BAA0B;AACrD,SAASC,2BAA2B,QAAQ,oBAAgB;AAC5D,SAASC,wBAAwB,EAAEC,wBAAwB,QAAQ,kBAAc;AACjF,SAASC,sBAAsB,QAAQ,yBAAqB;AAC5D,SAASC,aAAa,EAAEC,kBAAkB,QAAQ,sBAAkB;AACpE,OAAOC,mBAAmB,sBAAkB;AAC5C,SAASC,iBAAiB,EAAEC,iBAAiB,QAAQ,0BAAsB;AAC3E,SAASC,cAAc,QAAQ,qBAAiB;AAChD,SACEC,eAAe,EACfC,uBAAuB,EACvBC,gBAAgB,EAChBC,kBAAkB,QAEb,2BAAuB;AAE9B,MAAMC,YAAY,IAAMR,cAAcS,GAAG,GAAGD,SAAS;AA2DrD;;;CAGC,GACD,MAAME,iCAAiC;AAEvC;;;CAGC,GACD,OAA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.
77
77
  */
78
78
  level?: NotificationLevel;
79
+ /**
80
+ * The tier as the caller judged it, for an alert that grows more urgent
81
+ * the longer its condition lasts (a check still degraded after 2 h). Sets
82
+ * the `[Must know]` prefix and the tier the webhook routes on; the console
83
+ * level follows it unless the definition or `level` names one.
84
+ */
85
+ tier?: OperatorAlertDefinition['tier'];
79
86
  orgId?: string;
80
87
  hostId?: string;
81
88
  }
@@ -351,7 +351,7 @@ function consoleOrigin() {
351
351
  return unregisteredDefinition(type);
352
352
  }
353
353
  export function renderOperatorAlert(definition, options = {}) {
354
- var _options_context, _options_subject, _options_body, _options_url, _definition_notificationType;
354
+ var _options_context, _options_subject, _options_body, _options_tier, _options_url, _definition_notificationType;
355
355
  const context = _extends({}, options.subject ? {
356
356
  title: options.subject
357
357
  } : {}, options.body ? {
@@ -362,7 +362,7 @@ export function renderOperatorAlert(definition, options = {}) {
362
362
  return _extends({
363
363
  type: definition.type,
364
364
  label: definition.label,
365
- tier: definition.tier,
365
+ tier: (_options_tier = options.tier) != null ? _options_tier : definition.tier,
366
366
  category: definition.category,
367
367
  title,
368
368
  body,
@@ -412,7 +412,10 @@ export function renderOperatorAlert(definition, options = {}) {
412
412
  }, alert.body ? {
413
413
  body: alert.body
414
414
  } : {}, {
415
- level: (_options_level = options.level) != null ? _options_level : operatorAlertLevel(definition)
415
+ level: (_options_level = options.level) != null ? _options_level : operatorAlertLevel({
416
+ tier: alert.tier,
417
+ level: definition.level
418
+ })
416
419
  }, alert.link && alert.link.startsWith('/') ? {
417
420
  link: alert.link
418
421
  } : {}, alert.orgId ? {