@justair/justair-library 7.5.0-alpha.45d4756 → 7.5.0-alpha.477bdf3

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.
@@ -5,4 +5,10 @@ export const DEVICE_TYPES: Readonly<{
5
5
  }>;
6
6
  export const DEVICE_TYPE_VALUES: readonly ("monitor" | "sample-site" | "linked-device")[];
7
7
  export function isAqiCapableDeviceType(deviceType: any): boolean;
8
+ /**
9
+ * The device-type vocabulary as a type, so consumers get autocomplete and a
10
+ * compile error on a mis-cased value like "sampleSite" — the exact bug the
11
+ * runtime comments in utils/subscribedDevices.js warn about at length.
12
+ */
13
+ export type DeviceType = (typeof DEVICE_TYPES)[keyof typeof DEVICE_TYPES];
8
14
  //# sourceMappingURL=deviceTypes.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"deviceTypes.d.ts","sourceRoot":"","sources":["../../src/constants/deviceTypes.js"],"names":[],"mappings":"AA0BA;;;;GAIG;AAEH,0FAA6E;AAStE,iEAEoC"}
1
+ {"version":3,"file":"deviceTypes.d.ts","sourceRoot":"","sources":["../../src/constants/deviceTypes.js"],"names":[],"mappings":"AA0BA;;;;GAIG;AAEH,0FAA6E;AAiBtE,iEAEoC;;;;;;yBAZ9B,CAAA,OAAO,YAAY,EAAC,MAAM,OAAO,YAAY,CAAC"}
package/dist/index.d.ts CHANGED
@@ -107,6 +107,9 @@ import { DEVICE_TYPES } from "./constants/deviceTypes.js";
107
107
  import { DEVICE_TYPE_VALUES } from "./constants/deviceTypes.js";
108
108
  import { isAqiCapableDeviceType } from "./constants/deviceTypes.js";
109
109
  import { projectSubscribedMonitors } from "./utils/subscribedDevices.js";
110
+ import { resolveMonitorIdsByUser } from "./utils/subscribedDevices.js";
111
+ import { VISIBLE_SITE_MONITOR_FILTER } from "./utils/subscribedDevices.js";
112
+ import { SUBSCRIBED_DEVICES_ERRORS } from "./utils/subscribedDevices.js";
110
113
  import { splitName } from "./utils/splitName.js";
111
114
  import { DEFAULT_QUIET_HOURS } from "./utils/quietHours.js";
112
115
  import { DEFAULT_TIMEZONE } from "./constants/timezones.js";
@@ -117,5 +120,5 @@ import { validateQuietHours } from "./utils/quietHours.js";
117
120
  import { getZoneMinutes } from "./utils/quietHours.js";
118
121
  import { isInQuietWindow } from "./utils/quietHours.js";
119
122
  import { resolveQuietHours } from "./utils/quietHours.js";
120
- export { Database, adminSchema, Admin, configurationsSchema, Configurations, measurementsSchema, Measurements, monitorRequestsSchema, MonitorRequests, monitorsSchema, Monitors, organizationsSchema, Organizations, usersSchema, Users, COOKIE_CONSENT_CATEGORIES, COOKIE_CONSENT_VALUES, validateCookieConsent, eventsSchema, Events, lightMonitorSchema, LightMonitors, monitorSuppliersSchema, MonitorSuppliers, contextsSchema, Contexts, parametersSchema, Parameters, announcementSchema, Announcements, jobsSchema, Jobs, apiKeySchema, ApiKey, UsageMetrics, usageMetricsSchema, Audit, auditSchema, EventsAudit, eventsAuditSchema, MonitorAudit, monitorAuditSchema, parametersEnum, deploymentTypesEnum, AlertsAudit, Alerts, alertsSchema, alertsAuditSchema, Features, featuresSchema, dataCompletenessSchema, DataCompleteness, networkMetricsSchema, NetworkMetrics, rateOfChangeSchema, RateOfChange, changeStreamCheckpointsSchema, ChangeStreamCheckpoints, sitesSchema, Sites, sampleSitesSchema, SampleSites, sampleSiteAuditSchema, SampleSiteAudit, sampleParametersEnum, samplesSchema, Samples, samplesAuditSchema, SamplesAudit, sampleParameterReferenceConcentrations, passwordResetTokenSchema, PasswordResetToken, monitorEpisodesSchema, MonitorEpisode, userNotificationsSchema, UserNotification, AqiAlertNotification, DeviceOfflineNotification, WeeklyDigestNotification, AccountNotification, NOTIFICATION_KINDS, NOTIFICATION_CHANNELS, DELIVERY_STATUSES, DATA_DOWNLOAD_TYPES, dataDownloadSchema, DataDownloads, AqiDataDownload, SampleDataDownload, DATA_DOWNLOAD_MAX_RANGE_DAYS, DATA_DOWNLOAD_ERRORS, validateDataDownloadDateOrder, validateDataDownloadMaxDateRange, validateDataDownloadEmail, normalizeDataDownloadEmail, validateDataDownloadTimezone, normalizeDataDownloadTimezone, PARAMETERS, HEAVY_METALS, ALERT_LEVEL_WEIGHTS, getAlertWeight, DEVICE_TYPES, DEVICE_TYPE_VALUES, isAqiCapableDeviceType, projectSubscribedMonitors, splitName, DEFAULT_QUIET_HOURS, DEFAULT_TIMEZONE, QUIET_HOURS_ERRORS, isValidTimeString, isValidIANATimezone, validateQuietHours, getZoneMinutes, isInQuietWindow, resolveQuietHours };
123
+ export { Database, adminSchema, Admin, configurationsSchema, Configurations, measurementsSchema, Measurements, monitorRequestsSchema, MonitorRequests, monitorsSchema, Monitors, organizationsSchema, Organizations, usersSchema, Users, COOKIE_CONSENT_CATEGORIES, COOKIE_CONSENT_VALUES, validateCookieConsent, eventsSchema, Events, lightMonitorSchema, LightMonitors, monitorSuppliersSchema, MonitorSuppliers, contextsSchema, Contexts, parametersSchema, Parameters, announcementSchema, Announcements, jobsSchema, Jobs, apiKeySchema, ApiKey, UsageMetrics, usageMetricsSchema, Audit, auditSchema, EventsAudit, eventsAuditSchema, MonitorAudit, monitorAuditSchema, parametersEnum, deploymentTypesEnum, AlertsAudit, Alerts, alertsSchema, alertsAuditSchema, Features, featuresSchema, dataCompletenessSchema, DataCompleteness, networkMetricsSchema, NetworkMetrics, rateOfChangeSchema, RateOfChange, changeStreamCheckpointsSchema, ChangeStreamCheckpoints, sitesSchema, Sites, sampleSitesSchema, SampleSites, sampleSiteAuditSchema, SampleSiteAudit, sampleParametersEnum, samplesSchema, Samples, samplesAuditSchema, SamplesAudit, sampleParameterReferenceConcentrations, passwordResetTokenSchema, PasswordResetToken, monitorEpisodesSchema, MonitorEpisode, userNotificationsSchema, UserNotification, AqiAlertNotification, DeviceOfflineNotification, WeeklyDigestNotification, AccountNotification, NOTIFICATION_KINDS, NOTIFICATION_CHANNELS, DELIVERY_STATUSES, DATA_DOWNLOAD_TYPES, dataDownloadSchema, DataDownloads, AqiDataDownload, SampleDataDownload, DATA_DOWNLOAD_MAX_RANGE_DAYS, DATA_DOWNLOAD_ERRORS, validateDataDownloadDateOrder, validateDataDownloadMaxDateRange, validateDataDownloadEmail, normalizeDataDownloadEmail, validateDataDownloadTimezone, normalizeDataDownloadTimezone, PARAMETERS, HEAVY_METALS, ALERT_LEVEL_WEIGHTS, getAlertWeight, DEVICE_TYPES, DEVICE_TYPE_VALUES, isAqiCapableDeviceType, projectSubscribedMonitors, resolveMonitorIdsByUser, VISIBLE_SITE_MONITOR_FILTER, SUBSCRIBED_DEVICES_ERRORS, splitName, DEFAULT_QUIET_HOURS, DEFAULT_TIMEZONE, QUIET_HOURS_ERRORS, isValidTimeString, isValidIANATimezone, validateQuietHours, getZoneMinutes, isInQuietWindow, resolveQuietHours };
121
124
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.js"],"names":[],"mappings":"AA0JA;;;iBAEC;yBA1FwB,oBAAoB;qBADxB,gBAAgB;4BAjEF,mBAAmB;sBAAnB,mBAAmB;qCAI/C,4BAA4B;+BAA5B,4BAA4B;mCAM5B,0BAA0B;6BAA1B,0BAA0B;sCAI1B,6BAA6B;gCAA7B,6BAA6B;+BAQ7B,sBAAsB;yBAAtB,sBAAsB;oCACsB,2BAA2B;8BAA3B,2BAA2B;4BAcvE,mBAAmB;sBAAnB,mBAAmB;0CAAnB,mBAAmB;sCAAnB,mBAAmB;sCAAnB,mBAAmB;6BAMnB,oBAAoB;uBAApB,oBAAoB;mCAnBuB,2BAA2B;8BAA3B,2BAA2B;uCAItE,8BAA8B;iCAA9B,8BAA8B;+BACI,sBAAsB;yBAAtB,sBAAsB;iCAClB,wBAAwB;2BAAxB,wBAAwB;mCAcnB,2BAA2B;8BAA3B,2BAA2B;2BAC5C,kBAAkB;qBAAlB,kBAAkB;6BACd,oBAAoB;uBAApB,oBAAoB;6BACR,0BAA0B;mCAA1B,0BAA0B;sBArCpE,0BAA0B;4BAA1B,0BAA0B;4BAiC1B,oBAAoB;kCAApB,oBAAoB;6BArBpB,sBAAsB;mCAAtB,sBAAsB;+BAAtB,sBAAsB;oCAAtB,sBAAsB;4BA+BtB,oBAAoB;uBAApB,oBAAoB;6BAApB,oBAAoB;kCAApB,oBAAoB;yBACc,sBAAsB;+BAAtB,sBAAsB;uCAIxD,8BAA8B;iCAA9B,8BAA8B;qCACgB,4BAA4B;+BAA5B,4BAA4B;mCAChC,0BAA0B;6BAA1B,0BAA0B;8CAIpE,qCAAqC;wCAArC,qCAAqC;4BAyCT,mBAAmB;sBAAnB,mBAAmB;kCAS/C,yBAAyB;4BAAzB,yBAAyB;sCAAzB,yBAAyB;gCAAzB,yBAAyB;qCAAzB,yBAAyB;8BASzB,qBAAqB;wBAArB,qBAAqB;mCAArB,qBAAqB;6BAArB,qBAAqB;uDAArB,qBAAqB;yCACiC,gCAAgC;mCAAhC,gCAAgC;sCA7CtF,6BAA6B;+BAA7B,6BAA6B;wCAW7B,+BAA+B;iCAA/B,+BAA+B;qCAA/B,+BAA+B;0CAA/B,+BAA+B;yCAA/B,+BAA+B;oCAA/B,+BAA+B;mCAA/B,+BAA+B;sCAA/B,+BAA+B;kCAA/B,+BAA+B;oCApBF,8BAA8B;mCA4D3D,2BAA2B;8BAA3B,2BAA2B;gCAA3B,2BAA2B;mCAA3B,2BAA2B;+DAsB3B,mCAAmC;qCAAnC,mCAAmC;mEAAnC,mCAAmC;yEAAnC,mCAAmC;mEAAnC,mCAAmC;qEAAnC,mCAAmC;yEAAnC,mCAAmC;2EAAnC,mCAAmC;2BArFD,2BAA2B;6BAA3B,2BAA2B;oCAChB,4BAA4B;+BAA5B,4BAA4B;6BAOzE,4BAA4B;mCAA5B,4BAA4B;uCAA5B,4BAA4B;0CA2BO,8BAA8B;0BAX9C,sBAAsB;oCASzC,uBAAuB;iCA/BG,0BAA0B;mCA+BpD,uBAAuB;kCAAvB,uBAAuB;oCACM,qBAAqB;mCADlD,uBAAuB;+BAAvB,uBAAuB;gCAAvB,uBAAuB;kCAAvB,uBAAuB"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.js"],"names":[],"mappings":"AA+JA;;;iBAEC;yBA/FwB,oBAAoB;qBADxB,gBAAgB;4BAjEF,mBAAmB;sBAAnB,mBAAmB;qCAI/C,4BAA4B;+BAA5B,4BAA4B;mCAM5B,0BAA0B;6BAA1B,0BAA0B;sCAI1B,6BAA6B;gCAA7B,6BAA6B;+BAQ7B,sBAAsB;yBAAtB,sBAAsB;oCACsB,2BAA2B;8BAA3B,2BAA2B;4BAcvE,mBAAmB;sBAAnB,mBAAmB;0CAAnB,mBAAmB;sCAAnB,mBAAmB;sCAAnB,mBAAmB;6BAMnB,oBAAoB;uBAApB,oBAAoB;mCAnBuB,2BAA2B;8BAA3B,2BAA2B;uCAItE,8BAA8B;iCAA9B,8BAA8B;+BACI,sBAAsB;yBAAtB,sBAAsB;iCAClB,wBAAwB;2BAAxB,wBAAwB;mCAcnB,2BAA2B;8BAA3B,2BAA2B;2BAC5C,kBAAkB;qBAAlB,kBAAkB;6BACd,oBAAoB;uBAApB,oBAAoB;6BACR,0BAA0B;mCAA1B,0BAA0B;sBArCpE,0BAA0B;4BAA1B,0BAA0B;4BAiC1B,oBAAoB;kCAApB,oBAAoB;6BArBpB,sBAAsB;mCAAtB,sBAAsB;+BAAtB,sBAAsB;oCAAtB,sBAAsB;4BA+BtB,oBAAoB;uBAApB,oBAAoB;6BAApB,oBAAoB;kCAApB,oBAAoB;yBACc,sBAAsB;+BAAtB,sBAAsB;uCAIxD,8BAA8B;iCAA9B,8BAA8B;qCACgB,4BAA4B;+BAA5B,4BAA4B;mCAChC,0BAA0B;6BAA1B,0BAA0B;8CAIpE,qCAAqC;wCAArC,qCAAqC;4BA8CT,mBAAmB;sBAAnB,mBAAmB;kCAS/C,yBAAyB;4BAAzB,yBAAyB;sCAAzB,yBAAyB;gCAAzB,yBAAyB;qCAAzB,yBAAyB;8BASzB,qBAAqB;wBAArB,qBAAqB;mCAArB,qBAAqB;6BAArB,qBAAqB;uDAArB,qBAAqB;yCACiC,gCAAgC;mCAAhC,gCAAgC;sCAlDtF,6BAA6B;+BAA7B,6BAA6B;wCAW7B,+BAA+B;iCAA/B,+BAA+B;qCAA/B,+BAA+B;0CAA/B,+BAA+B;yCAA/B,+BAA+B;oCAA/B,+BAA+B;mCAA/B,+BAA+B;sCAA/B,+BAA+B;kCAA/B,+BAA+B;oCApBF,8BAA8B;mCAiE3D,2BAA2B;8BAA3B,2BAA2B;gCAA3B,2BAA2B;mCAA3B,2BAA2B;+DAsB3B,mCAAmC;qCAAnC,mCAAmC;mEAAnC,mCAAmC;yEAAnC,mCAAmC;mEAAnC,mCAAmC;qEAAnC,mCAAmC;yEAAnC,mCAAmC;2EAAnC,mCAAmC;2BA1FD,2BAA2B;6BAA3B,2BAA2B;oCAChB,4BAA4B;+BAA5B,4BAA4B;6BAOzE,4BAA4B;mCAA5B,4BAA4B;uCAA5B,4BAA4B;0CAgC5B,8BAA8B;wCAA9B,8BAA8B;4CAA9B,8BAA8B;0CAA9B,8BAA8B;0BAhBX,sBAAsB;oCASzC,uBAAuB;iCA/BG,0BAA0B;mCA+BpD,uBAAuB;kCAAvB,uBAAuB;oCACM,qBAAqB;mCADlD,uBAAuB;+BAAvB,uBAAuB;gCAAvB,uBAAuB;kCAAvB,uBAAuB"}
@@ -1 +1 @@
1
- {"version":3,"file":"users.d.ts","sourceRoot":"","sources":["../../src/models/users.js"],"names":[],"mappings":"AAkFA,8BA6GE;AAiCF,wBAAmD;AAvNnD,iDAA4D;AAC5D,6CAAmD;AAUnD,4DAsBC"}
1
+ {"version":3,"file":"users.d.ts","sourceRoot":"","sources":["../../src/models/users.js"],"names":[],"mappings":"AAyFA,8BAgGE;AAiCF,wBAAmD;AAjNnD,iDAA4D;AAC5D,6CAAmD;AAUnD,4DAsBC"}
@@ -1,3 +1,31 @@
1
- export function projectSubscribedMonitors(subscribedDevices: any, { resolveSiteMonitorIds }?: {}): Promise<any>;
2
- export function hasAqiCapableSubscription(subscribedDevices: any): any;
1
+ export const SUBSCRIBED_DEVICES_ERRORS: Readonly<{
2
+ MISSING_SITE_RESOLVER: "missing_site_resolver";
3
+ RESOLVER_RETURNED_NON_ARRAY: "resolver_returned_non_array";
4
+ RESOLVER_RETURNED_NESTED_ARRAYS: "resolver_returned_nested_arrays";
5
+ RESOLVER_RETURNED_DOCUMENTS: "resolver_returned_documents";
6
+ MISSING_COHORT_SITE_RESOLVER: "missing_cohort_site_resolver";
7
+ COHORT_RESOLVER_RETURNED_NON_MAP: "cohort_resolver_returned_non_map";
8
+ COHORT_USER_MISSING_ID: "cohort_user_missing_id";
9
+ }>;
10
+ export const VISIBLE_SITE_MONITOR_FILTER: Readonly<{
11
+ isPrivate: {
12
+ $ne: boolean;
13
+ };
14
+ isActive: true;
15
+ }>;
16
+ export function projectSubscribedMonitors(subscribedDevices?: Array<{
17
+ deviceId: import("mongoose").Types.ObjectId;
18
+ deviceType: import("../constants/deviceTypes.js").DeviceType;
19
+ }>, { resolveSiteMonitorIds }?: {
20
+ resolveSiteMonitorIds?: (siteIds: import("mongoose").Types.ObjectId[]) => Promise<Array<import("mongoose").Types.ObjectId | null | undefined>>;
21
+ }): Promise<import("mongoose").Types.ObjectId[]>;
22
+ export function resolveMonitorIdsByUser(users?: Array<{
23
+ _id: any;
24
+ subscribedDevices?: Array<{
25
+ deviceId: import("mongoose").Types.ObjectId;
26
+ deviceType: import("../constants/deviceTypes.js").DeviceType;
27
+ }>;
28
+ }>, { resolveVisibleSiteMonitors }?: {
29
+ resolveVisibleSiteMonitors?: (siteIds: import("mongoose").Types.ObjectId[]) => Promise<Map<string, import("mongoose").Types.ObjectId[]>>;
30
+ }): Promise<Map<string, import("mongoose").Types.ObjectId[]>>;
3
31
  //# sourceMappingURL=subscribedDevices.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"subscribedDevices.d.ts","sourceRoot":"","sources":["../../src/utils/subscribedDevices.js"],"names":[],"mappings":"AAyIO,gHAoBN;AAOM,uEAGuD"}
1
+ {"version":3,"file":"subscribedDevices.d.ts","sourceRoot":"","sources":["../../src/utils/subscribedDevices.js"],"names":[],"mappings":"AAmEA;;;;;;;;GASG;AAyBH;;;;;GAGG;AAiLI,8DANI,KAAK,CAAC;IAAE,QAAQ,EAAE,OAAO,UAAU,EAAE,KAAK,CAAC,QAAQ,CAAC;IAC1D,UAAU,EAAE,OAAO,6BAA6B,EAAE,UAAU,CAAA;CAAE,CAAC,8BACzD;IAAE,qBAAqB,CAAC,EAAE,CAAC,OAAO,EAAE,OAAO,UAAU,EAAE,KAAK,CAAC,QAAQ,EAAE,KAC7E,OAAO,CAAC,KAAK,CAAC,OAAO,UAAU,EAAE,KAAK,CAAC,QAAQ,GAAG,IAAI,GAAG,SAAS,CAAC,CAAC,CAAA;CAAE,GAC9D,OAAO,CAAC,OAAO,UAAU,EAAE,KAAK,CAAC,QAAQ,EAAE,CAAC,CA0BxD;AAkEM,gDAPI,KAAK,CAAC;IAAE,GAAG,EAAE,GAAG,CAAC;IAAC,iBAAiB,CAAC,EAAE,KAAK,CAAC;QAClD,QAAQ,EAAE,OAAO,UAAU,EAAE,KAAK,CAAC,QAAQ,CAAC;QAC5C,UAAU,EAAE,OAAO,6BAA6B,EAAE,UAAU,CAAA;KAAE,CAAC,CAAA;CAAE,CAAC,mCAC5D;IAAE,0BAA0B,CAAC,EAAE,CAAC,OAAO,EAAE,OAAO,UAAU,EAAE,KAAK,CAAC,QAAQ,EAAE,KAClF,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE,OAAO,UAAU,EAAE,KAAK,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAA;CAAE,GACnD,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE,OAAO,UAAU,EAAE,KAAK,CAAC,QAAQ,EAAE,CAAC,CAAC,CA2DrE"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=subscribedDevicesBarrel.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"subscribedDevicesBarrel.test.d.ts","sourceRoot":"","sources":["../../../src/utils/tests/subscribedDevicesBarrel.test.js"],"names":[],"mappings":""}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@justair/justair-library",
3
- "version": "7.5.0-alpha.45d4756",
3
+ "version": "7.5.0-alpha.477bdf3",
4
4
  "description": "JustAir Internal Library",
5
5
  "main": "src/index.js",
6
6
  "type": "module",
@@ -32,6 +32,14 @@ export const DEVICE_TYPES = Object.freeze({
32
32
 
33
33
  export const DEVICE_TYPE_VALUES = Object.freeze(Object.values(DEVICE_TYPES));
34
34
 
35
+ /**
36
+ * The device-type vocabulary as a type, so consumers get autocomplete and a
37
+ * compile error on a mis-cased value like "sampleSite" — the exact bug the
38
+ * runtime comments in utils/subscribedDevices.js warn about at length.
39
+ *
40
+ * @typedef {typeof DEVICE_TYPES[keyof typeof DEVICE_TYPES]} DeviceType
41
+ */
42
+
35
43
  // Whether a device of this type can ever report AQI, and therefore whether a
36
44
  // subscription to it can contribute to AQI alert delivery.
37
45
  //
package/src/index.js CHANGED
@@ -100,7 +100,12 @@ import {
100
100
  resolveQuietHours,
101
101
  } from "./utils/quietHours.js";
102
102
  import { isValidIANATimezone } from "./utils/timezone.js";
103
- import { projectSubscribedMonitors } from "./utils/subscribedDevices.js";
103
+ import {
104
+ projectSubscribedMonitors,
105
+ resolveMonitorIdsByUser,
106
+ VISIBLE_SITE_MONITOR_FILTER,
107
+ SUBSCRIBED_DEVICES_ERRORS,
108
+ } from "./utils/subscribedDevices.js";
104
109
 
105
110
  // Sites related imports
106
111
  import { sitesSchema, Sites } from "./models/sites.js";
@@ -269,14 +274,27 @@ export {
269
274
  DEVICE_TYPES,
270
275
  DEVICE_TYPE_VALUES,
271
276
  isAqiCapableDeviceType,
272
- // subscribedDevices → subscribedMonitors projection (JA-3110 / JA-3335).
273
- // Every consumer that writes a subscription recomputes the AQI audience with
274
- // this instead of re-implementing the per-device-type rule.
277
+ // subscribedDevices → monitor ids, resolved at READ time (JA-3110 / JA-3335).
278
+ // Users.subscribedDevices is the source of truth; Users.subscribedMonitors is
279
+ // being retired rather than kept in step with it. Nothing should store this
280
+ // result — see the module header for the five bugs a stored copy caused.
275
281
  //
276
- // hasAqiCapableSubscription is deliberately NOT re-exported here: nothing
277
- // consumes it yet, and an export cannot be withdrawn without a major bump.
278
- // It stays module-internal until a consumer needs it.
282
+ // resolveMonitorIdsByUser — the batch form. One Sites lookup for a whole
283
+ // cohort. What alert runs, org pages and session
284
+ // responses should call.
285
+ // projectSubscribedMonitors — the single-user rule the batch form is built
286
+ // on. Named after the field being retired; it
287
+ // gets renamed when that field is dropped.
288
+ // VISIBLE_SITE_MONITOR_FILTER — the privacy predicate every consumer must
289
+ // apply when turning a Site into monitor ids.
290
+ // Sites.monitorIds is unfiltered; reading it
291
+ // straight through leaks private monitors.
292
+ // SUBSCRIBED_DEVICES_ERRORS — stable `err.code` vocabulary; consumers
293
+ // branch on it, never on message wording.
279
294
  projectSubscribedMonitors,
295
+ resolveMonitorIdsByUser,
296
+ VISIBLE_SITE_MONITOR_FILTER,
297
+ SUBSCRIBED_DEVICES_ERRORS,
280
298
  // Utilities
281
299
  splitName,
282
300
  // Quiet hours (JA-3054): shared validation + window evaluation
@@ -61,6 +61,13 @@ const validateCookieConsent = (consent) => {
61
61
  // fails silently (the notification service just filters it away). Consumers on
62
62
  // the subscribe path should `$pull { deviceId }` before `$addToSet` so a
63
63
  // re-subscribe with a corrected type replaces the row instead of adding one.
64
+ //
65
+ // That is two sequential updates, not one. MongoDB rejects `$pull` and
66
+ // `$addToSet` on the same path in a single update document ("would create a
67
+ // conflict at 'subscribedDevices'"), so the pull must be awaited before the
68
+ // add. Between the two writes the user reads as unsubscribed from that device;
69
+ // the window is only worth closing with a transaction if a concurrent read
70
+ // acting on it would be harmful.
64
71
  const subscribedDeviceSchema = mongoose.Schema(
65
72
  {
66
73
  deviceId: { type: mongoose.Types.ObjectId, required: true },
@@ -96,30 +103,17 @@ const usersSchema = mongoose.Schema(
96
103
  // Subscribed devices (JA-3110 / JA-3335) — the source of truth for what the
97
104
  // user has added to "My Monitors", across all three device types.
98
105
  //
99
- // Relationship to subscribedMonitors above: that array stays monitor ids
100
- // ONLY, and is the AQI-alert projection of this one. A subscribed
101
- // linked-device contributes the monitorIds of its Site to it; a subscribed
102
- // sample-site contributes nothing, having no live AQI. The two must be
103
- // written together on every subscribe/unsubscribe path.
104
- //
105
- // Do not re-implement that rule per consumer: recompute the projection with
106
- // `projectSubscribedMonitors` from src/utils/subscribedDevices.js (exported
107
- // from src/index.js). It is deliberately not a schema validator — a
108
- // projection is a write-path computation and needs a Site lookup, which the
109
- // schema has no business doing.
110
- //
111
- // Writing subscribedMonitors has a hard precondition (a blanket overwrite
112
- // drops the subscriptions of any user who predates this field) and a known
113
- // staleness gap. Both are specified once, in the PRECONDITION and STALENESS
114
- // notes at the top of src/utils/subscribedDevices.js — read them there
115
- // rather than trusting a summary here.
106
+ // subscribedMonitors above is its derived AQI-alert projection (monitor ids
107
+ // only). The two must be written together on every subscribe and
108
+ // unsubscribe path, using `projectSubscribedMonitors` rather than a
109
+ // per-consumer reimplementation. It is deliberately not a schema validator:
110
+ // the projection needs a Site lookup, which the schema has no business
111
+ // doing.
116
112
  //
117
- // Why the split matters: JustAirNotificationService reads subscribedMonitors
118
- // and drops ids that do not resolve to a Monitor (statusAlerts.js
119
- // `.filter(monitor => monitor)`). Writing a Site or SampleSite id in there
120
- // therefore throws no error — it silently delivers no alerts. Keeping the
121
- // polymorphic ids in their own field preserves that invariant for every
122
- // library consumer.
113
+ // Everything else — the per-device-type rule, the backfill PRECONDITION,
114
+ // the STALENESS gap, and why the field is split at all — is specified once,
115
+ // in the header of src/utils/subscribedDevices.js. Read it there; it is
116
+ // deliberately not summarised here.
123
117
  subscribedDevices: [subscribedDeviceSchema],
124
118
  currentAlertMode: {
125
119
  type: String,
@@ -1,15 +1,6 @@
1
- // Subscribed devices (JA-3110 / JA-3335): the shared projection from
2
- // Users.subscribedDevices (source of truth, all three device types) to
3
- // Users.subscribedMonitors (monitor ids only, the AQI-alert audience).
4
- //
5
- // Single source of truth for every consumer that writes a subscription —
6
- // JustAirUserService recomputes on subscribe/unsubscribe, and any backfill or
7
- // repair script uses the same function. Pure: no DB, no logger, no clock. The
8
- // one thing it cannot know on its own is which monitors a Site links, so that
9
- // lookup is injected as `resolveSiteMonitorIds`.
10
- //
11
- // The rule, per JA-3110 AC "user will receive AQI notifications if the site
12
- // has an AQI":
1
+ // Subscribed devices (JA-3110 / JA-3335): resolving Users.subscribedDevices —
2
+ // the source of truth for what a user follows, across all three device types —
3
+ // down to the flat monitor ids that make up their AQI-alert audience.
13
4
  //
14
5
  // monitor → contributes its own deviceId
15
6
  // linked-device → contributes the monitorIds of its Site (none if the Site
@@ -18,56 +9,100 @@
18
9
  // sample-site → contributes nothing; no live AQI, so it can never trigger
19
10
  // an AQI alert
20
11
  //
21
- // Recompute-whole, not delta: callers pass the complete post-change
22
- // subscribedDevices array and overwrite subscribedMonitors with the result.
23
- // That makes unsubscribe fall out for free — a Site's monitors disappear from
24
- // the projection only when no other subscribed device still contributes them —
25
- // and makes the function idempotent, so a repair run over existing users is
26
- // safe to repeat.
12
+ // Pure: no DB, no logger, no clock. The one thing this module cannot know on
13
+ // its own is which monitors a Site links, so that lookup is injected.
27
14
  //
28
15
  // ---------------------------------------------------------------------------
29
- // PRECONDITION — do not overwrite subscribedMonitors before the backfill
16
+ // THIS IS A READ-TIME RESOLUTION, NOT A STORED PROJECTION
30
17
  // ---------------------------------------------------------------------------
31
- // Every user who existed before this field shipped has a populated
32
- // subscribedMonitors and an empty or absent subscribedDevices (pinned by the
33
- // "reads pre-backfill users cleanly" case in models/tests/users.test.js). For
34
- // such a user this function correctly returns a projection of *nothing they
35
- // have migrated yet* — so a consumer that overwrites subscribedMonitors with
36
- // it on the user's next subscribe silently drops every monitor they were
37
- // already subscribed to, and their AQI alerts stop with no error anywhere.
38
- //
39
- // Callers MUST therefore do one of these, per user, and the ordering is not
40
- // optional:
41
- // 1. Backfill subscribedDevices from subscribedMonitors first (one
42
- // { deviceId, deviceType: "monitor" } entry per existing id), then
43
- // overwrite freely. This is the target state.
44
- // 2. Until that backfill has run for the user, union the projection with the
45
- // existing subscribedMonitors instead of overwriting.
46
- //
47
- // This module deliberately does NOT offer a `union: true` flag. A blanket
48
- // union is correct for subscribe and silently wrong for unsubscribe — it would
49
- // make removal a no-op — so the choice belongs at the call site, which knows
50
- // which operation it is performing. The backfill itself is consumer-side
51
- // (JustAirUserService owns the write path) and is not shipped in this library;
52
- // it needs its own ticket under JA-3110 before any consumer moves to
53
- // overwrite-always.
18
+ // `Users.subscribedMonitors` used to be a denormalized copy of this result,
19
+ // written on every subscribe and unsubscribe. It is being removed
20
+ // (JA-3110 "Retire subscribedMonitors"), and this module is what replaces it:
21
+ // consumers resolve the audience when they need it and store nothing.
22
+ //
23
+ // That decision came out of the JA-3110 review, where five separate
24
+ // silent-failure bugs all traced back to keeping a stored copy in step with
25
+ // the source of truth:
26
+ //
27
+ // * a legacy id with no subscribedDevices row being dropped when a Site that
28
+ // linked the same monitor was unfollowed
29
+ // * "half-migrated" users — a stored copy holding ids the source of truth
30
+ // did not — passing a migration gate that checked presence, not content
31
+ // * unsubscribe computing a removal set from a snapshot, so a concurrent
32
+ // subscribe lost its contribution
33
+ // * a hard-deleted Site leaving its monitors in the stored copy forever
34
+ // * a Site gaining or losing a monitor never reaching its existing followers
35
+ //
36
+ // None of those exist here. There is no snapshot to go stale, nothing to
37
+ // reproject when a Site changes, and unsubscribe is a plain `$pull` of one
38
+ // subscribedDevices entry. If you find yourself reintroducing a stored copy of
39
+ // this result, you are reintroducing all five.
40
+ //
41
+ // ---------------------------------------------------------------------------
42
+ // PRIVACY IS THE CALLER'S JOB, AND IT IS NOT OPTIONAL
43
+ // ---------------------------------------------------------------------------
44
+ // A Site's `monitorIds` is a raw membership list with no visibility filtering.
45
+ // Reading it straight through enrols a Site's followers in alerts for any
46
+ // private monitor it links — a real leak, not a theoretical one, because the
47
+ // notification service filters monitors on `monitorState`/`isActive` and not on
48
+ // `isPrivate`.
49
+ //
50
+ // So the injected resolver must return only VISIBLE monitors, which is why it
51
+ // is named `resolveVisibleSiteMonitors` and why VISIBLE_SITE_MONITOR_FILTER
52
+ // exists below: three repos need the same predicate, and `$ne: true` (rather
53
+ // than `false`) is the half that is easy to get wrong on documents written
54
+ // before `isPrivate` existed.
54
55
  //
55
56
  // ---------------------------------------------------------------------------
56
- // STALENESS — this is a write-path projection only
57
+ // NAMING
57
58
  // ---------------------------------------------------------------------------
58
- // The result is only as current as the last time a caller ran it. Nothing here
59
- // watches Sites: if a Site gains or loses a monitor after a user subscribed to
60
- // it, that user's subscribedMonitors stays as it was and their AQI audience is
61
- // wrong — a monitor added to a Site never alerts its existing subscribers, and
62
- // a removed one keeps alerting them, in both cases silently. Any code that
63
- // mutates Sites.monitorIds is therefore responsible for reprojecting the
64
- // affected subscribers. That reprojection is not implemented anywhere yet and
65
- // needs a follow-up ticket under JA-3110.
66
-
67
- import {
68
- DEVICE_TYPES,
69
- isAqiCapableDeviceType,
70
- } from "../constants/deviceTypes.js";
59
+ // `projectSubscribedMonitors` is named after the field being retired. It is
60
+ // kept under that name while consumers migrate; renaming it to something that
61
+ // does not reference a dead field belongs in the step that drops the field.
62
+
63
+ import { DEVICE_TYPES } from "../constants/deviceTypes.js";
64
+
65
+ // Stable error codes thrown by this module. Consumers filter on `err.code`
66
+ // — never on message wording, which is free to change. Same contract as
67
+ // QUIET_HOURS_ERRORS in utils/quietHours.js.
68
+ export const SUBSCRIBED_DEVICES_ERRORS = Object.freeze({
69
+ MISSING_SITE_RESOLVER: "missing_site_resolver",
70
+ RESOLVER_RETURNED_NON_ARRAY: "resolver_returned_non_array",
71
+ RESOLVER_RETURNED_NESTED_ARRAYS: "resolver_returned_nested_arrays",
72
+ RESOLVER_RETURNED_DOCUMENTS: "resolver_returned_documents",
73
+ // resolveMonitorIdsByUser only
74
+ MISSING_COHORT_SITE_RESOLVER: "missing_cohort_site_resolver",
75
+ COHORT_RESOLVER_RETURNED_NON_MAP: "cohort_resolver_returned_non_map",
76
+ COHORT_USER_MISSING_ID: "cohort_user_missing_id",
77
+ });
78
+
79
+ // The predicate that makes a Site's monitor visible to its followers. Frozen
80
+ // and exported because JustAirService, JustAirUserService and
81
+ // JustAirNotificationService all need the same one, and a fourth hand-written
82
+ // copy is how one of them quietly starts leaking private monitors.
83
+ //
84
+ // `isPrivate: { $ne: true }` rather than `{ $eq: false }`: the field has a
85
+ // schema default but that only governs writes made through mongoose, so
86
+ // documents written before it existed have no key at all and would vanish
87
+ // under an exact match. Same rule the public-map path uses.
88
+ //
89
+ // Spread it into the Monitors query the resolver is built from:
90
+ //
91
+ // const monitors = await Monitors.find(
92
+ // { _id: { $in: siteMonitorIds }, ...VISIBLE_SITE_MONITOR_FILTER },
93
+ // "_id",
94
+ // ).lean();
95
+ //
96
+ // `monitorState: "Deployed"` is deliberately NOT here. That is an
97
+ // alerting-eligibility rule, not a visibility rule, and it belongs to the
98
+ // notification service alone — the org admin page and the session response
99
+ // must still show a follower the monitors they follow while those monitors sit
100
+ // in a non-Deployed state. Do not consolidate the two filters; keep
101
+ // JustAirNotificationService's own `monitorState` predicate where it is.
102
+ export const VISIBLE_SITE_MONITOR_FILTER = Object.freeze({
103
+ isPrivate: { $ne: true },
104
+ isActive: true,
105
+ });
71
106
 
72
107
  // Dedupe by string form, keep the caller's ObjectId instances. Two equal
73
108
  // ObjectIds are different object identities, so Set/includes on the raw values
@@ -114,6 +149,92 @@ const linkedSiteIds = (entries) =>
114
149
  .filter((entry) => entry.deviceType === DEVICE_TYPES.LINKED_DEVICE)
115
150
  .map((entry) => entry.deviceId);
116
151
 
152
+ // The resolver is consumer-supplied, so its return is the one input this
153
+ // module cannot check at the type boundary. Validate it rather than trust it:
154
+ // both bad shapes below would otherwise corrupt subscribedMonitors silently,
155
+ // and silent is the failure mode this whole field split exists to avoid.
156
+ // Nullish stays tolerated — a consumer whose Sites resolved to nothing may
157
+ // legitimately return nothing.
158
+ const validateResolvedSiteMonitorIds = (resolved) => {
159
+ if (resolved === null || resolved === undefined) {
160
+ return [];
161
+ }
162
+
163
+ if (!Array.isArray(resolved)) {
164
+ const error = new TypeError(
165
+ "resolveSiteMonitorIds must resolve to an array of monitor ids"
166
+ );
167
+ error.code = SUBSCRIBED_DEVICES_ERRORS.RESOLVER_RETURNED_NON_ARRAY;
168
+ throw error;
169
+ }
170
+
171
+ // `.map` instead of `.flatMap` yields [[m1, m2]]. An array is not a plain
172
+ // object, so the document check below never sees it, and it fails
173
+ // inconsistently downstream: one monitor per Site casts back to the id and
174
+ // silently works, two throws a CastError at write time, far from the cause.
175
+ if (resolved.some(Array.isArray)) {
176
+ const error = new TypeError(
177
+ "resolveSiteMonitorIds must resolve to a flat array of monitor ids"
178
+ );
179
+ error.code = SUBSCRIBED_DEVICES_ERRORS.RESOLVER_RETURNED_NESTED_ARRAYS;
180
+ throw error;
181
+ }
182
+
183
+ // Discriminating a document from an id without importing mongoose: test for
184
+ // what only an id has. `toHexString` is on ObjectId (mongoose-patched or raw
185
+ // bson) and on nothing a Sites query returns, hydrated or lean.
186
+ //
187
+ // Deliberately not keyed on `_id`, which is wrong in both directions: every
188
+ // ObjectId appears to carry one (mongoose defines `_id` on ObjectId.prototype
189
+ // as a self-reference), and a lean read that projects it away
190
+ // (`Sites.find(..., "monitorIds -_id").lean()`) carries none.
191
+ if (
192
+ resolved.some(
193
+ (id) => isPlainObject(id) && typeof id.toHexString !== "function"
194
+ )
195
+ ) {
196
+ const error = new TypeError(
197
+ "resolveSiteMonitorIds must resolve to monitor ids, not Site documents"
198
+ );
199
+ error.code = SUBSCRIBED_DEVICES_ERRORS.RESOLVER_RETURNED_DOCUMENTS;
200
+ throw error;
201
+ }
202
+
203
+ return resolved;
204
+ };
205
+
206
+ // The cohort resolver's return, checked the same way and for the same reason:
207
+ // it is consumer-supplied, and every bad shape below would otherwise resolve to
208
+ // an empty audience rather than an error — a user silently stops getting
209
+ // alerts, which is the one outcome this module exists to prevent.
210
+ //
211
+ // Keys are re-derived with String() rather than trusted. A consumer who builds
212
+ // `new Map([[site._id, ids]])` with raw ObjectId keys produces a Map that looks
213
+ // correct, passes every type check, and misses on every `.get(String(id))`
214
+ // because two equal ObjectIds are different object identities. Normalising is
215
+ // forgiving in precisely the place where strictness would fail silently.
216
+ const validateResolvedSiteMonitorMap = (resolved) => {
217
+ if (resolved === null || resolved === undefined) {
218
+ return new Map();
219
+ }
220
+
221
+ if (!(resolved instanceof Map)) {
222
+ const error = new TypeError(
223
+ "resolveVisibleSiteMonitors must resolve to a Map of site id to monitor ids"
224
+ );
225
+ error.code = SUBSCRIBED_DEVICES_ERRORS.COHORT_RESOLVER_RETURNED_NON_MAP;
226
+ throw error;
227
+ }
228
+
229
+ return new Map(
230
+ [...resolved.entries()].map(([siteId, monitorIds]) => [
231
+ String(siteId),
232
+ validateResolvedSiteMonitorIds(monitorIds),
233
+ ])
234
+ );
235
+ };
236
+
237
+
117
238
  // Returns the monitor ids that should be stored in Users.subscribedMonitors for
118
239
  // the given subscribedDevices array. Order is deterministic — direct `monitor`
119
240
  // subscriptions in array order, then Site-derived ids in resolver order, first
@@ -126,15 +247,38 @@ const linkedSiteIds = (entries) =>
126
247
  //
127
248
  // `resolveSiteMonitorIds(siteIds)` is called at most once, with every
128
249
  // linked-device id at a time, and must resolve to the flat union of those
129
- // Sites' monitorIds (`Sites.find({ _id: { $in: siteIds } }, "monitorIds")`).
250
+ // Sites' monitorIds — the ids themselves, not the Site documents:
251
+ //
252
+ // const sites = await Sites.find({ _id: { $in: siteIds } }, "monitorIds").lean();
253
+ // return sites.flatMap((site) => site.monitorIds ?? []);
254
+ //
255
+ // Returning the documents is the easy mistake, so it is rejected rather than
256
+ // merely documented: the return is validated and a document-shaped entry
257
+ // throws RESOLVER_RETURNED_DOCUMENTS, as a non-array return throws
258
+ // RESOLVER_RETURNED_NON_ARRAY. Left unchecked it would fail silently — each
259
+ // Site doc casts to its own _id on write and subscribedMonitors fills with
260
+ // Site ids, exactly the polymorphic id this field split exists to keep out.
261
+ //
130
262
  // It is not called at all when nothing is subscribed to a linked-device, so a
131
263
  // consumer that only handles monitors pays no query. A resolver may return
132
264
  // nullish entries — Sites.monitorIds is `default: undefined`, so a sample-only
133
265
  // Site has no array — and they are filtered out here rather than trusted to
134
266
  // the caller.
135
267
  //
136
- // Read the PRECONDITION and STALENESS notes at the top of this file before
137
- // writing the result to Users.subscribedMonitors.
268
+ // Do NOT store this result. Read the "THIS IS A READ-TIME RESOLUTION" note at
269
+ // the top of this file — a stored copy is where all five JA-3110 bugs came
270
+ // from. Its privacy obligation applies here too: the ids this returns are only
271
+ // as safe to alert on as the resolver that produced them.
272
+ //
273
+ // For a whole cohort of users, prefer resolveMonitorIdsByUser below — it does
274
+ // the Sites lookup once for the batch instead of once per user.
275
+ /**
276
+ * @param {Array<{ deviceId: import("mongoose").Types.ObjectId,
277
+ * deviceType: import("../constants/deviceTypes.js").DeviceType }>} [subscribedDevices]
278
+ * @param {{ resolveSiteMonitorIds?: (siteIds: import("mongoose").Types.ObjectId[]) =>
279
+ * Promise<Array<import("mongoose").Types.ObjectId | null | undefined>> }} [options]
280
+ * @returns {Promise<import("mongoose").Types.ObjectId[]>}
281
+ */
138
282
  export const projectSubscribedMonitors = async (
139
283
  subscribedDevices,
140
284
  { resolveSiteMonitorIds } = {}
@@ -148,21 +292,138 @@ export const projectSubscribedMonitors = async (
148
292
  }
149
293
 
150
294
  if (typeof resolveSiteMonitorIds !== "function") {
151
- throw new TypeError(
295
+ const error = new TypeError(
152
296
  "projectSubscribedMonitors requires resolveSiteMonitorIds when a linked-device is subscribed"
153
297
  );
298
+ error.code = SUBSCRIBED_DEVICES_ERRORS.MISSING_SITE_RESOLVER;
299
+ throw error;
154
300
  }
155
301
 
156
- const siteMonitorIds = (await resolveSiteMonitorIds(siteIds)) ?? [];
302
+ const siteMonitorIds = validateResolvedSiteMonitorIds(
303
+ await resolveSiteMonitorIds(siteIds)
304
+ );
157
305
  return dedupeById([...direct, ...siteMonitorIds]);
158
306
  };
159
307
 
160
- // Whether a subscribedDevices array can produce any AQI audience at all,
161
- // without resolving Sites. `false` is certain (nothing subscribed can ever
162
- // alert); `true` only means a linked-device is present and its Site still has
163
- // to be checked — the same necessary-but-not-sufficient asymmetry as
164
- // isAqiCapableDeviceType.
165
- export const hasAqiCapableSubscription = (subscribedDevices) =>
166
- (subscribedDevices ?? [])
167
- .filter(isPlainObject)
168
- .some((entry) => isAqiCapableDeviceType(entry.deviceType));
308
+ // ---------------------------------------------------------------------------
309
+ // Cohort-scoped resolution
310
+ // ---------------------------------------------------------------------------
311
+ // The batch form of the above, and the one every read-time consumer should
312
+ // reach for: an alert run, an org admin page, a session response. Resolves a
313
+ // whole list of users with ONE Sites lookup covering every Site anyone in the
314
+ // cohort follows, rather than one lookup per user.
315
+ //
316
+ // That distinction is the difference between a constant-cost alert run and an
317
+ // N+1 across the entire user base, which is the shape this codebase keeps
318
+ // re-learning. The lookup is not performed at all when nobody in the cohort
319
+ // follows a linked-device.
320
+ //
321
+ // resolveVisibleSiteMonitors(siteIds) -> Map<string siteId, ObjectId[]>
322
+ //
323
+ // The resolver is keyed per Site rather than returning a flat union, because
324
+ // each user needs their own Sites' monitors, not the cohort's. It must return
325
+ // only VISIBLE monitors — see the privacy note at the top of this file, and
326
+ // build it from VISIBLE_SITE_MONITOR_FILTER:
327
+ //
328
+ // const sites = await Sites.find(
329
+ // { _id: { $in: siteIds } }, "monitorIds",
330
+ // ).lean();
331
+ // const monitors = await Monitors.find(
332
+ // {
333
+ // _id: { $in: sites.flatMap((s) => s.monitorIds ?? []) },
334
+ // ...VISIBLE_SITE_MONITOR_FILTER,
335
+ // },
336
+ // "_id",
337
+ // ).lean();
338
+ // const visible = new Set(monitors.map((m) => String(m._id)));
339
+ // return new Map(sites.map((s) => [
340
+ // String(s._id),
341
+ // (s.monitorIds ?? []).filter((id) => visible.has(String(id))),
342
+ // ]));
343
+ //
344
+ // A Site id the resolver omits resolves to no monitors for that user rather
345
+ // than throwing — a followed Site that has since been deleted is an ordinary
346
+ // state, not an error. What that user is left holding (an entry that resolves
347
+ // to nothing, so their alerts stop) is the subscription-identity question
348
+ // tracked in TODOS, and is deliberately not papered over here.
349
+ //
350
+ // Users are keyed by `String(user._id)`, so callers look up with the same. A
351
+ // user with no `_id` throws rather than being skipped: skipping would silently
352
+ // remove a real person from an alert audience, which is the failure mode this
353
+ // whole module exists to avoid.
354
+ //
355
+ // Consumers can shrink the cohort by pushing the AQI-capability predicate into
356
+ // the Users query, so rows that can never alert are not loaded at all:
357
+ //
358
+ // { "subscribedDevices.deviceType": { $in: AQI_CAPABLE_DEVICE_TYPES } }
359
+ //
360
+ // There is no index on `subscribedDevices.deviceType` (only on
361
+ // `subscribedDevices.deviceId`), so this narrows the documents returned rather
362
+ // than the documents scanned — still worth it on a cohort query that is already
363
+ // scanning, not worth building a JS-side filter for.
364
+ /**
365
+ * @param {Array<{ _id: any, subscribedDevices?: Array<{
366
+ * deviceId: import("mongoose").Types.ObjectId,
367
+ * deviceType: import("../constants/deviceTypes.js").DeviceType }> }>} [users]
368
+ * @param {{ resolveVisibleSiteMonitors?: (siteIds: import("mongoose").Types.ObjectId[]) =>
369
+ * Promise<Map<string, import("mongoose").Types.ObjectId[]>> }} [options]
370
+ * @returns {Promise<Map<string, import("mongoose").Types.ObjectId[]>>}
371
+ */
372
+ export const resolveMonitorIdsByUser = async (
373
+ users,
374
+ { resolveVisibleSiteMonitors } = {}
375
+ ) => {
376
+ const cohort = (users ?? []).filter(isPlainObject);
377
+
378
+ const missing = cohort.find(
379
+ (user) => user._id === null || user._id === undefined
380
+ );
381
+ if (missing) {
382
+ const error = new TypeError(
383
+ "resolveMonitorIdsByUser requires every user to carry an _id"
384
+ );
385
+ error.code = SUBSCRIBED_DEVICES_ERRORS.COHORT_USER_MISSING_ID;
386
+ throw error;
387
+ }
388
+
389
+ // Every Site anyone in the cohort follows, deduped across users — the point
390
+ // of the batch form. Two users following the same Site cost one entry.
391
+ const siteIds = dedupeById(
392
+ cohort.flatMap((user) =>
393
+ linkedSiteIds((user.subscribedDevices ?? []).filter(isPlainObject))
394
+ )
395
+ );
396
+
397
+ let monitorIdsBySite = new Map();
398
+ if (siteIds.length > 0) {
399
+ if (typeof resolveVisibleSiteMonitors !== "function") {
400
+ const error = new TypeError(
401
+ "resolveMonitorIdsByUser requires resolveVisibleSiteMonitors when anyone in the cohort follows a linked-device"
402
+ );
403
+ error.code = SUBSCRIBED_DEVICES_ERRORS.MISSING_COHORT_SITE_RESOLVER;
404
+ throw error;
405
+ }
406
+ monitorIdsBySite = validateResolvedSiteMonitorMap(
407
+ await resolveVisibleSiteMonitors(siteIds)
408
+ );
409
+ }
410
+
411
+ // Synchronous and Map-backed, so the per-user projections below issue no
412
+ // further lookups no matter how large the cohort is. Per-entry validation
413
+ // (arrays, not nested arrays, ids rather than documents) is inherited from
414
+ // projectSubscribedMonitors rather than duplicated.
415
+ const resolveSiteMonitorIds = (ids) =>
416
+ ids.flatMap((id) => monitorIdsBySite.get(String(id)) ?? []);
417
+
418
+ const resolved = await Promise.all(
419
+ cohort.map((user) =>
420
+ projectSubscribedMonitors(user.subscribedDevices, {
421
+ resolveSiteMonitorIds,
422
+ })
423
+ )
424
+ );
425
+
426
+ return new Map(
427
+ cohort.map((user, index) => [String(user._id), resolved[index]])
428
+ );
429
+ };
@@ -1,7 +1,14 @@
1
1
  import mongoose from 'mongoose';
2
+ import { Users } from '../../models/users.js';
3
+ import {
4
+ DEVICE_TYPE_VALUES,
5
+ isAqiCapableDeviceType,
6
+ } from '../../constants/deviceTypes.js';
2
7
  import {
3
8
  projectSubscribedMonitors,
4
- hasAqiCapableSubscription,
9
+ resolveMonitorIdsByUser,
10
+ VISIBLE_SITE_MONITOR_FILTER,
11
+ SUBSCRIBED_DEVICES_ERRORS,
5
12
  } from '../subscribedDevices.js';
6
13
 
7
14
  const oid = () => new mongoose.Types.ObjectId();
@@ -111,9 +118,104 @@ describe('projectSubscribedMonitors', () => {
111
118
  test('throws when a linked-device is subscribed and no resolver is injected', async () => {
112
119
  // Loud on the one input it genuinely cannot project alone, rather than
113
120
  // silently returning a short audience and dropping real alerts.
121
+ // The `code` is the contract consumers branch on; the message is not.
114
122
  await expect(
115
123
  projectSubscribedMonitors([{ deviceId: oid(), deviceType: 'linked-device' }]),
116
- ).rejects.toThrow(/resolveSiteMonitorIds/);
124
+ ).rejects.toMatchObject({
125
+ code: SUBSCRIBED_DEVICES_ERRORS.MISSING_SITE_RESOLVER,
126
+ });
127
+ });
128
+
129
+ test('rejects a resolver that returns Site documents rather than monitor ids', async () => {
130
+ // The silent-corruption case: without this guard each doc survives
131
+ // dedupeById and casts to its own _id on write, filling subscribedMonitors
132
+ // with Site ids that the notification service then quietly drops.
133
+ const siteId = oid();
134
+ await expect(
135
+ projectSubscribedMonitors([{ deviceId: siteId, deviceType: 'linked-device' }], {
136
+ resolveSiteMonitorIds: async () => [{ _id: siteId, monitorIds: [oid()] }],
137
+ }),
138
+ ).rejects.toMatchObject({
139
+ code: SUBSCRIBED_DEVICES_ERRORS.RESOLVER_RETURNED_DOCUMENTS,
140
+ });
141
+ });
142
+
143
+ test('rejects a resolver that returns nested arrays (.map instead of .flatMap)', async () => {
144
+ const siteId = oid();
145
+ await expect(
146
+ projectSubscribedMonitors([{ deviceId: siteId, deviceType: 'linked-device' }], {
147
+ resolveSiteMonitorIds: async () => [[oid(), oid()]],
148
+ }),
149
+ ).rejects.toMatchObject({
150
+ code: SUBSCRIBED_DEVICES_ERRORS.RESOLVER_RETURNED_NESTED_ARRAYS,
151
+ });
152
+ });
153
+
154
+ test('rejects a lean Site read that projected _id away', async () => {
155
+ // The `_id`-based discriminator missed this: `Sites.find(..., "monitorIds
156
+ // -_id").lean()` yields objects carrying no _id at all, which would
157
+ // otherwise key as "[object Object]" in dedupeById and land in
158
+ // subscribedMonitors as junk.
159
+ await expect(
160
+ projectSubscribedMonitors([{ deviceId: oid(), deviceType: 'linked-device' }], {
161
+ resolveSiteMonitorIds: async () => [{ monitorIds: [oid()] }],
162
+ }),
163
+ ).rejects.toMatchObject({
164
+ code: SUBSCRIBED_DEVICES_ERRORS.RESOLVER_RETURNED_DOCUMENTS,
165
+ });
166
+ });
167
+
168
+ test('rejects a hydrated Site document (the forgot-.lean() case)', async () => {
169
+ // The likeliest real-world shape of this mistake. A throwaway model keeps
170
+ // this file off the real Sites schema; hydration needs no connection.
171
+ const HydratedSite = mongoose.model(
172
+ 'SubscribedDevicesProbeSite',
173
+ new mongoose.Schema({ monitorIds: [mongoose.Schema.Types.ObjectId] }),
174
+ );
175
+
176
+ await expect(
177
+ projectSubscribedMonitors([{ deviceId: oid(), deviceType: 'linked-device' }], {
178
+ resolveSiteMonitorIds: async () => [new HydratedSite({ monitorIds: [oid()] })],
179
+ }),
180
+ ).rejects.toMatchObject({
181
+ code: SUBSCRIBED_DEVICES_ERRORS.RESOLVER_RETURNED_DOCUMENTS,
182
+ });
183
+ });
184
+
185
+ test('does not mistake ordinary ObjectIds for documents', async () => {
186
+ // Regression guard for the discriminator: an id has `toHexString`, a Site
187
+ // document does not. Keying on `_id` instead gets it wrong both ways —
188
+ // mongoose defines `_id` on ObjectId.prototype as a self-reference, so a
189
+ // naive "has _id" check rejects every legitimate resolver result.
190
+ const siteId = oid();
191
+ const monitorId = oid();
192
+
193
+ expect(monitorId._id).toBe(monitorId);
194
+ await expect(
195
+ projectSubscribedMonitors([{ deviceId: siteId, deviceType: 'linked-device' }], {
196
+ resolveSiteMonitorIds: async () => [monitorId],
197
+ }),
198
+ ).resolves.toEqual([monitorId]);
199
+ });
200
+
201
+ test('rejects a resolver that does not return an array', async () => {
202
+ await expect(
203
+ projectSubscribedMonitors([{ deviceId: oid(), deviceType: 'linked-device' }], {
204
+ resolveSiteMonitorIds: async () => oid(),
205
+ }),
206
+ ).rejects.toMatchObject({
207
+ code: SUBSCRIBED_DEVICES_ERRORS.RESOLVER_RETURNED_NON_ARRAY,
208
+ });
209
+ });
210
+
211
+ test('still tolerates a resolver that returns nothing', async () => {
212
+ // Distinct from the two rejections above: resolving to nothing is a real
213
+ // state (a sample-only Site links no monitors), not a consumer mistake.
214
+ await expect(
215
+ projectSubscribedMonitors([{ deviceId: oid(), deviceType: 'linked-device' }], {
216
+ resolveSiteMonitorIds: async () => undefined,
217
+ }),
218
+ ).resolves.toEqual([]);
117
219
  });
118
220
 
119
221
  test('dedupes a monitor reached both directly and through a Site', async () => {
@@ -268,39 +370,296 @@ describe('projectSubscribedMonitors', () => {
268
370
  });
269
371
  });
270
372
 
271
- // Pins the export-contract decision, not behaviour: src/index.js is the public
272
- // surface of this package and an export there cannot be withdrawn without a
273
- // major bump. projectSubscribedMonitors is the sanctioned consumer entry point;
274
- // hasAqiCapableSubscription has no caller yet, so it stays module-internal
275
- // until one exists. Flipping either line is a deliberate contract change.
276
- describe('barrel surface', () => {
277
- test('exports projectSubscribedMonitors and withholds hasAqiCapableSubscription', async () => {
278
- const barrel = await import('../../index.js');
373
+ // Two encodings of "which device types can produce AQI" exist: the predicate
374
+ // isAqiCapableDeviceType, and the selectors inside projectSubscribedMonitors.
375
+ // Nothing structural keeps them in step, so a fourth type added to one and not
376
+ // the other would report as AQI-capable while contributing no audience — the
377
+ // silent failure this module exists to prevent. This pins them together.
378
+ // Every other case here passes plain object literals, but the real call site
379
+ // hands in user.subscribedDevices — a mongoose DocumentArray of subdocuments,
380
+ // which has to survive the isPlainObject filter. If it ever stopped doing so
381
+ // every entry would be dropped and the projection would return an empty
382
+ // audience with no error. Hydration needs no connection, so this stays DB-free.
383
+ describe('accepts real mongoose subdocuments, not just object literals', () => {
384
+ test('projects a hydrated user.subscribedDevices the same as plain objects', async () => {
385
+ const monitorId = oid();
386
+ const siteId = oid();
387
+ const siteMonitorId = oid();
279
388
 
280
- expect(barrel.projectSubscribedMonitors).toBe(projectSubscribedMonitors);
281
- expect(barrel.hasAqiCapableSubscription).toBeUndefined();
389
+ const user = new Users({
390
+ subscribedDevices: [
391
+ { deviceId: monitorId, deviceType: 'monitor' },
392
+ { deviceId: siteId, deviceType: 'linked-device' },
393
+ { deviceId: oid(), deviceType: 'sample-site' },
394
+ ],
395
+ });
396
+
397
+ await expect(
398
+ projectSubscribedMonitors(user.subscribedDevices, {
399
+ resolveSiteMonitorIds: async () => [siteMonitorId],
400
+ }),
401
+ ).resolves.toEqual([monitorId, siteMonitorId]);
282
402
  });
283
403
  });
284
404
 
285
- describe('hasAqiCapableSubscription', () => {
286
- test('false when only sample-sites are subscribed', () => {
287
- expect(
288
- hasAqiCapableSubscription([{ deviceId: oid(), deviceType: 'sample-site' }]),
289
- ).toBe(false);
405
+ describe('isAqiCapableDeviceType agrees with the projection', () => {
406
+ test.each(DEVICE_TYPE_VALUES)('%s', async (deviceType) => {
407
+ const deviceId = oid();
408
+ const projected = await projectSubscribedMonitors(
409
+ [{ deviceId, deviceType }],
410
+ // Resolves as though the id were a Site linking exactly one monitor, so
411
+ // a linked-device yields an audience and a sample-site still yields none.
412
+ { resolveSiteMonitorIds: async () => [oid()] },
413
+ );
414
+
415
+ expect(projected.length > 0).toBe(isAqiCapableDeviceType(deviceType));
290
416
  });
417
+ });
418
+
419
+ // ---------------------------------------------------------------------------
420
+ // resolveMonitorIdsByUser — the cohort form
421
+ // ---------------------------------------------------------------------------
422
+ // The batch form exists for exactly two reasons, and both are asserted here
423
+ // rather than just described: it must issue ONE Sites lookup for a whole
424
+ // cohort (never one per user), and each user must get THEIR OWN Sites'
425
+ // monitors, not the cohort's union. Get the second wrong and every follower of
426
+ // any Site is enrolled in every other Site's alerts — a bug that looks like
427
+ // working code on a one-user fixture.
428
+
429
+ // Records what the cohort resolver was asked for, so the tests can assert the
430
+ // call shape and not just the result.
431
+ const recordingSiteMap = (byId) => {
432
+ const calls = [];
433
+ const resolve = async (siteIds) => {
434
+ calls.push(siteIds);
435
+ return new Map(siteIds.map((id) => [String(id), byId[String(id)] ?? []]));
436
+ };
437
+ return { resolve, calls };
438
+ };
439
+
440
+ const user = (subscribedDevices) => ({ _id: oid(), subscribedDevices });
441
+
442
+ describe('resolveMonitorIdsByUser', () => {
443
+ test('keys the result by String(user._id)', async () => {
444
+ const u = user([]);
445
+
446
+ const result = await resolveMonitorIdsByUser([u]);
447
+
448
+ expect([...result.keys()]).toEqual([String(u._id)]);
449
+ });
450
+
451
+ test('a monitor-only cohort never touches the Sites resolver', async () => {
452
+ // The cheap path: a consumer whose users follow no Sites pays no lookup.
453
+ const { resolve, calls } = recordingSiteMap({});
454
+ const [m1, m2] = [oid(), oid()];
455
+ const [u1, u2] = [
456
+ user([{ deviceId: m1, deviceType: 'monitor' }]),
457
+ user([{ deviceId: m2, deviceType: 'monitor' }]),
458
+ ];
459
+
460
+ const result = await resolveMonitorIdsByUser([u1, u2], {
461
+ resolveVisibleSiteMonitors: resolve,
462
+ });
463
+
464
+ expect(calls).toEqual([]);
465
+ expect(result.get(String(u1._id))).toEqual([m1]);
466
+ expect(result.get(String(u2._id))).toEqual([m2]);
467
+ });
468
+
469
+ test('issues exactly ONE resolver call for the whole cohort, deduped', async () => {
470
+ // Two users following the same Site must cost one entry, not two — this is
471
+ // the entire point of the batch form.
472
+ const [siteA, siteB] = [oid(), oid()];
473
+ const { resolve, calls } = recordingSiteMap({
474
+ [siteA]: [oid()],
475
+ [siteB]: [oid()],
476
+ });
477
+
478
+ await resolveMonitorIdsByUser(
479
+ [
480
+ user([{ deviceId: siteA, deviceType: 'linked-device' }]),
481
+ user([{ deviceId: siteA, deviceType: 'linked-device' }]),
482
+ user([{ deviceId: siteB, deviceType: 'linked-device' }]),
483
+ ],
484
+ { resolveVisibleSiteMonitors: resolve },
485
+ );
291
486
 
292
- test('true for a monitor, and for a linked-device pending its Site check', () => {
293
- expect(
294
- hasAqiCapableSubscription([{ deviceId: oid(), deviceType: 'monitor' }]),
295
- ).toBe(true);
296
- expect(
297
- hasAqiCapableSubscription([{ deviceId: oid(), deviceType: 'linked-device' }]),
298
- ).toBe(true);
487
+ expect(calls).toHaveLength(1);
488
+ expect(calls[0].map(String).sort()).toEqual(
489
+ [String(siteA), String(siteB)].sort(),
490
+ );
491
+ });
492
+
493
+ test('each user gets only THEIR sites monitors, never the cohort union', async () => {
494
+ const [siteA, siteB] = [oid(), oid()];
495
+ const [a1, b1] = [oid(), oid()];
496
+ const { resolve } = recordingSiteMap({ [siteA]: [a1], [siteB]: [b1] });
497
+ const [ua, ub] = [
498
+ user([{ deviceId: siteA, deviceType: 'linked-device' }]),
499
+ user([{ deviceId: siteB, deviceType: 'linked-device' }]),
500
+ ];
501
+
502
+ const result = await resolveMonitorIdsByUser([ua, ub], {
503
+ resolveVisibleSiteMonitors: resolve,
504
+ });
505
+
506
+ expect(result.get(String(ua._id))).toEqual([a1]);
507
+ expect(result.get(String(ub._id))).toEqual([b1]);
508
+ });
509
+
510
+ test('dedupes a monitor followed both directly and through a Site', async () => {
511
+ const siteId = oid();
512
+ const shared = oid();
513
+ const { resolve } = recordingSiteMap({ [siteId]: [shared] });
514
+ const u = user([
515
+ { deviceId: shared, deviceType: 'monitor' },
516
+ { deviceId: siteId, deviceType: 'linked-device' },
517
+ ]);
518
+
519
+ const result = await resolveMonitorIdsByUser([u], {
520
+ resolveVisibleSiteMonitors: resolve,
521
+ });
522
+
523
+ expect(result.get(String(u._id))).toEqual([shared]);
524
+ });
525
+
526
+ test('a sample-site follower resolves to no monitors', async () => {
527
+ const u = user([{ deviceId: oid(), deviceType: 'sample-site' }]);
528
+
529
+ const result = await resolveMonitorIdsByUser([u]);
530
+
531
+ expect(result.get(String(u._id))).toEqual([]);
532
+ });
533
+
534
+ test('a Site the resolver omits resolves to nothing, not an error', async () => {
535
+ // A followed Site that has since been hard-deleted. Their alerts stopping
536
+ // is the subscription-identity question, not a crash in the resolver.
537
+ const deletedSite = oid();
538
+ const { resolve } = recordingSiteMap({});
539
+ const u = user([{ deviceId: deletedSite, deviceType: 'linked-device' }]);
540
+
541
+ const result = await resolveMonitorIdsByUser([u], {
542
+ resolveVisibleSiteMonitors: resolve,
543
+ });
544
+
545
+ expect(result.get(String(u._id))).toEqual([]);
546
+ });
547
+
548
+ test('normalises ObjectId keys in the returned Map', async () => {
549
+ // The silent-miss trap: `new Map([[site._id, ids]])` type-checks, looks
550
+ // correct, and misses every lookup because two equal ObjectIds are
551
+ // different object identities. Forgiven here rather than failing quietly.
552
+ const siteId = oid();
553
+ const monitorId = oid();
554
+ const u = user([{ deviceId: siteId, deviceType: 'linked-device' }]);
555
+
556
+ const result = await resolveMonitorIdsByUser([u], {
557
+ resolveVisibleSiteMonitors: async () => new Map([[siteId, [monitorId]]]),
558
+ });
559
+
560
+ expect(result.get(String(u._id))).toEqual([monitorId]);
561
+ });
562
+
563
+ test('tolerates a user with no subscribedDevices key at all', async () => {
564
+ const u = { _id: oid() };
565
+
566
+ const result = await resolveMonitorIdsByUser([u]);
567
+
568
+ expect(result.get(String(u._id))).toEqual([]);
569
+ });
570
+
571
+ test('an empty or nullish cohort resolves to an empty Map', async () => {
572
+ expect(await resolveMonitorIdsByUser([])).toEqual(new Map());
573
+ expect(await resolveMonitorIdsByUser(undefined)).toEqual(new Map());
574
+ });
575
+ });
576
+
577
+ describe('resolveMonitorIdsByUser — rejects what would otherwise fail silently', () => {
578
+ test('throws MISSING_COHORT_SITE_RESOLVER when anyone follows a linked-device', async () => {
579
+ await expect(
580
+ resolveMonitorIdsByUser([
581
+ user([{ deviceId: oid(), deviceType: 'linked-device' }]),
582
+ ]),
583
+ ).rejects.toMatchObject({
584
+ code: SUBSCRIBED_DEVICES_ERRORS.MISSING_COHORT_SITE_RESOLVER,
585
+ });
586
+ });
587
+
588
+ test('does NOT require a resolver when nobody follows a linked-device', async () => {
589
+ const monitorId = oid();
590
+ const u = user([{ deviceId: monitorId, deviceType: 'monitor' }]);
591
+
592
+ const result = await resolveMonitorIdsByUser([u]);
593
+
594
+ expect(result.get(String(u._id))).toEqual([monitorId]);
595
+ });
596
+
597
+ test('throws COHORT_RESOLVER_RETURNED_NON_MAP for an array of entries', async () => {
598
+ // The natural mistake: returning `[[siteId, ids]]` instead of a Map.
599
+ const siteId = oid();
600
+
601
+ await expect(
602
+ resolveMonitorIdsByUser(
603
+ [user([{ deviceId: siteId, deviceType: 'linked-device' }])],
604
+ { resolveVisibleSiteMonitors: async () => [[String(siteId), [oid()]]] },
605
+ ),
606
+ ).rejects.toMatchObject({
607
+ code: SUBSCRIBED_DEVICES_ERRORS.COHORT_RESOLVER_RETURNED_NON_MAP,
608
+ });
609
+ });
610
+
611
+ test('a nullish resolver return is an empty audience, not a throw', async () => {
612
+ const u = user([{ deviceId: oid(), deviceType: 'linked-device' }]);
613
+
614
+ const result = await resolveMonitorIdsByUser([u], {
615
+ resolveVisibleSiteMonitors: async () => null,
616
+ });
617
+
618
+ expect(result.get(String(u._id))).toEqual([]);
619
+ });
620
+
621
+ test('inherits the per-value guard: Site documents in a value are rejected', async () => {
622
+ // Same failure projectSubscribedMonitors guards against, reached through
623
+ // the Map. Left unchecked each doc casts to its own _id and Site ids land
624
+ // in the alert audience.
625
+ const siteId = oid();
626
+
627
+ await expect(
628
+ resolveMonitorIdsByUser(
629
+ [user([{ deviceId: siteId, deviceType: 'linked-device' }])],
630
+ {
631
+ resolveVisibleSiteMonitors: async () =>
632
+ new Map([[String(siteId), [{ _id: oid(), monitorIds: [] }]]]),
633
+ },
634
+ ),
635
+ ).rejects.toMatchObject({
636
+ code: SUBSCRIBED_DEVICES_ERRORS.RESOLVER_RETURNED_DOCUMENTS,
637
+ });
638
+ });
639
+
640
+ test('throws COHORT_USER_MISSING_ID rather than silently dropping the user', async () => {
641
+ // Skipping would remove a real person from an alert audience with no error
642
+ // anywhere — the exact failure mode this module exists to prevent.
643
+ await expect(
644
+ resolveMonitorIdsByUser([{ subscribedDevices: [] }]),
645
+ ).rejects.toMatchObject({
646
+ code: SUBSCRIBED_DEVICES_ERRORS.COHORT_USER_MISSING_ID,
647
+ });
648
+ });
649
+ });
650
+
651
+ describe('VISIBLE_SITE_MONITOR_FILTER', () => {
652
+ test('excludes private monitors with $ne: true, not an exact false match', () => {
653
+ // $ne matches both `false` and a MISSING key. Documents written before
654
+ // isPrivate existed carry no key, and an exact { isPrivate: false } match
655
+ // would drop them from every Site's audience.
656
+ expect(VISIBLE_SITE_MONITOR_FILTER).toEqual({
657
+ isPrivate: { $ne: true },
658
+ isActive: true,
659
+ });
299
660
  });
300
661
 
301
- test('false for a missing, empty, or unrecognised array', () => {
302
- expect(hasAqiCapableSubscription(undefined)).toBe(false);
303
- expect(hasAqiCapableSubscription([])).toBe(false);
304
- expect(hasAqiCapableSubscription([{ deviceType: 'Monitor' }])).toBe(false);
662
+ test('is frozen — one consumer mutating it must not change it for the rest', () => {
663
+ expect(Object.isFrozen(VISIBLE_SITE_MONITOR_FILTER)).toBe(true);
305
664
  });
306
665
  });
@@ -0,0 +1,42 @@
1
+ // Pins the public export surface for the subscribedDevices module, kept in its
2
+ // own file because asserting on the root barrel imports src/index.js, which
3
+ // registers every mongoose model. Mixing that into the pure unit tests would
4
+ // make them fail whenever any unrelated model failed to load. Same shape as
5
+ // constants/tests/constantsBarrel.test.js.
6
+ //
7
+ // src/index.js is the published surface of this package, so an export here
8
+ // cannot be withdrawn without a major bump. Flipping either assertion is a
9
+ // deliberate contract change, not a test fix.
10
+ import {
11
+ projectSubscribedMonitors,
12
+ resolveMonitorIdsByUser,
13
+ VISIBLE_SITE_MONITOR_FILTER,
14
+ SUBSCRIBED_DEVICES_ERRORS,
15
+ } from '../subscribedDevices.js';
16
+ import {
17
+ DEVICE_TYPES,
18
+ DEVICE_TYPE_VALUES,
19
+ isAqiCapableDeviceType,
20
+ } from '../../constants/deviceTypes.js';
21
+
22
+ test('barrel re-exports the subscribedDevices surface unchanged (identity, not copies)', async () => {
23
+ const barrel = await import('../../index.js');
24
+
25
+ expect(barrel.projectSubscribedMonitors).toBe(projectSubscribedMonitors);
26
+ expect(barrel.resolveMonitorIdsByUser).toBe(resolveMonitorIdsByUser);
27
+ expect(barrel.VISIBLE_SITE_MONITOR_FILTER).toBe(VISIBLE_SITE_MONITOR_FILTER);
28
+ expect(barrel.SUBSCRIBED_DEVICES_ERRORS).toBe(SUBSCRIBED_DEVICES_ERRORS);
29
+ });
30
+
31
+ // constants/tests/deviceTypes.test.js pins these on the `./constants` barrel;
32
+ // the root barrel re-exports them through a separate hand-written import and
33
+ // export pair, so a dropped line there publishes cleanly and only fails at
34
+ // runtime inside a consuming service. Pinned here rather than there because
35
+ // this is the file that already carries the root-barrel dependency.
36
+ test('barrel re-exports the device-type vocabulary unchanged (identity, not copies)', async () => {
37
+ const barrel = await import('../../index.js');
38
+
39
+ expect(barrel.DEVICE_TYPES).toBe(DEVICE_TYPES);
40
+ expect(barrel.DEVICE_TYPE_VALUES).toBe(DEVICE_TYPE_VALUES);
41
+ expect(barrel.isAqiCapableDeviceType).toBe(isAqiCapableDeviceType);
42
+ });