@aglyn/aglyn 1.12.0 → 1.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/package.json +11 -11
  2. package/src/lib/app-utils/crm.js +8 -7
  3. package/src/lib/app-utils/crm.js.map +1 -1
  4. package/src/lib/app-utils/docs-help-sections.generated.js +8 -2
  5. package/src/lib/app-utils/docs-help-sections.generated.js.map +1 -1
  6. package/src/lib/app-utils/docs-help.generated.d.ts +1 -1
  7. package/src/lib/app-utils/docs-help.generated.js +7 -0
  8. package/src/lib/app-utils/docs-help.generated.js.map +1 -1
  9. package/src/lib/app-utils/docs-index.generated.js +48 -34
  10. package/src/lib/app-utils/docs-index.generated.js.map +1 -1
  11. package/src/lib/app-utils/dynamic-list-rule.js +9 -5
  12. package/src/lib/app-utils/dynamic-list-rule.js.map +1 -1
  13. package/src/lib/app-utils/host-permissions.d.ts +12 -0
  14. package/src/lib/app-utils/host-permissions.js +26 -1
  15. package/src/lib/app-utils/host-permissions.js.map +1 -1
  16. package/src/lib/app-utils/media-asset-facts.d.ts +2 -2
  17. package/src/lib/app-utils/media-asset-facts.js +4 -3
  18. package/src/lib/app-utils/media-asset-facts.js.map +1 -1
  19. package/src/lib/app-utils/media-cdn-scope.d.ts +19 -4
  20. package/src/lib/app-utils/media-cdn-scope.js +19 -5
  21. package/src/lib/app-utils/media-cdn-scope.js.map +1 -1
  22. package/src/lib/app-utils/media-ref.d.ts +10 -6
  23. package/src/lib/app-utils/media-ref.js +34 -8
  24. package/src/lib/app-utils/media-ref.js.map +1 -1
  25. package/src/lib/app-utils/native-nav.d.ts +2 -2
  26. package/src/lib/app-utils/native-nav.js +2 -2
  27. package/src/lib/app-utils/native-nav.js.map +1 -1
  28. package/src/lib/app-utils/org-permissions.d.ts +7 -0
  29. package/src/lib/app-utils/org-permissions.js +2 -0
  30. package/src/lib/app-utils/org-permissions.js.map +1 -1
  31. package/src/lib/app-utils/org-role-grants.d.ts +7 -0
  32. package/src/lib/app-utils/org-role-grants.js +7 -5
  33. package/src/lib/app-utils/org-role-grants.js.map +1 -1
  34. package/src/lib/app-utils/scope-tokens.d.ts +132 -3
  35. package/src/lib/app-utils/scope-tokens.js +276 -3
  36. package/src/lib/app-utils/scope-tokens.js.map +1 -1
  37. package/src/lib/app-utils/site-placement.d.ts +74 -0
  38. package/src/lib/app-utils/site-placement.js +80 -0
  39. package/src/lib/app-utils/site-placement.js.map +1 -0
  40. package/src/lib/app-utils/transfer-launcher-context.d.ts +17 -1
  41. package/src/lib/app-utils/transfer-launcher-context.js.map +1 -1
  42. package/src/lib/data-transfer/access.d.ts +10 -18
  43. package/src/lib/data-transfer/access.js +21 -25
  44. package/src/lib/data-transfer/access.js.map +1 -1
  45. package/src/lib/data-transfer/resource.d.ts +13 -14
  46. package/src/lib/data-transfer/resource.js +9 -10
  47. package/src/lib/data-transfer/resource.js.map +1 -1
  48. package/src/lib/plugin-manager/first-party-plugins.generated.js +3 -4
  49. package/src/lib/plugin-manager/first-party-plugins.generated.js.map +1 -1
  50. package/src/lib/plugin-manager/plugin-contact-capture.d.ts +10 -0
  51. package/src/lib/plugin-manager/plugin-contact-capture.js +11 -0
  52. package/src/lib/plugin-manager/plugin-contact-capture.js.map +1 -1
  53. package/src/lib/plugin-manager/plugin-entitlements.d.ts +12 -0
  54. package/src/lib/plugin-manager/plugin-entitlements.js +3 -1
  55. package/src/lib/plugin-manager/plugin-entitlements.js.map +1 -1
  56. package/src/lib/plugin-manager/plugin-scope-sharing.d.ts +52 -0
  57. package/src/lib/plugin-manager/plugin-scope-sharing.generated.d.ts +10 -0
  58. package/src/lib/plugin-manager/plugin-scope-sharing.generated.js +82 -0
  59. package/src/lib/plugin-manager/plugin-scope-sharing.generated.js.map +1 -0
  60. package/src/lib/plugin-manager/plugin-scope-sharing.js +85 -0
  61. package/src/lib/plugin-manager/plugin-scope-sharing.js.map +1 -0
  62. package/src/lib/plugin-manager/plugin-transfer-resources.d.ts +56 -1
  63. package/src/lib/plugin-manager/plugin-transfer-resources.js +13 -0
  64. package/src/lib/plugin-manager/plugin-transfer-resources.js.map +1 -1
@@ -326,6 +326,16 @@ export declare function labelContactSource(source: unknown, fallback?: string):
326
326
  * nothing answers to, without closing the list against a plugin's door.
327
327
  */
328
328
  export declare function isKnownContactSource(source: unknown): boolean;
329
+ /**
330
+ * Whether a capture source is a plugin's word rather than one of the core's.
331
+ *
332
+ * A capture writes its source into the holder's facet, and that is the only place
333
+ * a plugin's word has ever been. A list's sweep still reads the core's words off
334
+ * the top of the row, so reading them from the facet too would change who an
335
+ * existing source-filtered list selects. It asks this to read the facet for the
336
+ * words no existing list could have named.
337
+ */
338
+ export declare function isPluginContactSource(source: string): boolean;
329
339
  /** One source a filter offers: the stored word, and how it reads. */
330
340
  export interface PluginContactSourceOption {
331
341
  value: string;
@@ -117,6 +117,17 @@ export const PLUGIN_CONTACT_SOURCES = definePluginServiceContract('core.contact-
117
117
  if (!word) return false;
118
118
  return Object.hasOwn(CONTACT_SOURCE_LABELS, word) || pluginContactSource(word) !== null;
119
119
  }
120
+ /**
121
+ * Whether a capture source is a plugin's word rather than one of the core's.
122
+ *
123
+ * A capture writes its source into the holder's facet, and that is the only place
124
+ * a plugin's word has ever been. A list's sweep still reads the core's words off
125
+ * the top of the row, so reading them from the facet too would change who an
126
+ * existing source-filtered list selects. It asks this to read the facet for the
127
+ * words no existing list could have named.
128
+ */ export function isPluginContactSource(source) {
129
+ return !Object.hasOwn(CONTACT_SOURCE_LABELS, source);
130
+ }
120
131
  /**
121
132
  * Every source a filter can offer: the core's, then each door a plugin
122
133
  * declared, each reading as {@link labelContactSource} reads it, so a filter's
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../libs/aglyn/src/lib/plugin-manager/plugin-contact-capture.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 { CONTACT_SOURCE_LABELS } from '../app-utils/contacts'\nimport { getRegisteringPluginId } from '../app-utils/registering-plugin'\nimport {\n definePluginServiceContract,\n registerPluginService,\n resolvePluginServices,\n} from './plugin-services'\n\n/**\n * A person met on a site, handed to whichever plugin keeps people (AGL-3124).\n *\n * Four silos capture the same thing and none of them is the record system: a\n * form submission, a site member signing up, an order, a booking. Each holds\n * an address, a name and the fact that something happened, and each wants the\n * workspace's person record to know. Today each one imports the writer, which\n * makes the highest-fan-in edge in the repo — thirty files in one plugin alone\n * — and makes the record system's plugin something a storefront cannot take a\n * payment without.\n *\n * So the silo stops importing and starts DECLARING: it registers the capture\n * door it owns, and hands a capture to this seam. The plugin that keeps people\n * registers the writer and does every part of the work that is a record\n * system's to do:\n *\n * - normalizing and keying the address, and deciding whether this is a new\n * person or a visit from one the workspace already holds;\n * - the audience band, the erasure rows, and every other refusal — answered,\n * never thrown, so a capture that is refused never costs the silo the order\n * or the submission it was recording;\n * - what a stage, an owner, a company and a tag mean, and what the arrival\n * of a new person sets off.\n *\n * The silo decides none of that. It reports what it saw.\n *\n * ## Why the profile is opaque\n *\n * `profile` is the owner's own field names with scalar values, not a core\n * type. A person's record shape belongs to the plugin that models it, and a\n * typed core shape would be that model spelled in the platform again — which\n * is the defect this seam exists to retire, not a smaller version of it. A key\n * the owner does not document is the owner's to ignore.\n *\n * `source` is the silo's own word for its door, and it is declared rather than\n * enumerated here for the same reason: core listing `form`, `member`, `order`\n * and `booking` would be core holding the plugin set again. A silo registers\n * its source with {@link registerPluginContactSource}, which is what lets a\n * timeline label an entry and a link point back at the thing that captured the\n * person, without the platform knowing what any of them are.\n *\n * ## One writer; many silos\n *\n * A workspace keeps one set of people, so the writer is a slot: a second\n * plugin's writer is refused naming both, and the incumbent keeps serving. A\n * SOURCE is per silo and there are many, but one source word has one owner —\n * two plugins claiming `order` would make the label and the link ambiguous at\n * the point they are read.\n *\n * ## The caller proves who is asking\n *\n * Like `plugin-record-timeline`, the registry authenticates nobody. A silo has\n * already decided, in its own terms and before it asks, that the capture is\n * the workspace's to record — that the submission was accepted, that the order\n * was paid.\n *\n * Server-side: reached by its own subpath, never through\n * `plugin-manager/index.ts`.\n */\n\n/** The person, as the capturing silo saw them. */\nexport interface PluginContactIdentity {\n /**\n * The address they gave. Raw: the owner normalizes and keys on it, and a\n * silo that normalized first would be keeping a second copy of that rule.\n */\n email: unknown\n name?: string | null\n}\n\n/** What happened, in the capturing silo's own words. */\nexport interface PluginContactInteraction {\n /** The silo's declared source word — see {@link registerPluginContactSource}. */\n source: string\n /** When it happened, epoch ms; the owner uses now when absent. */\n atMs?: number\n /**\n * The document it happened on, in the silo's terms\n * (`formSubmissions/{id}`, `orders/{id}`), so a timeline entry can point\n * back at it. Absent where the door leaves nothing to open.\n */\n refId?: string | null\n /** One line a person reads on the timeline. */\n summary?: string | null\n}\n\nexport interface PluginContactCaptureRequest {\n /**\n * Who caused the capture, when it was not the person captured (AGL-3376) —\n * a member adding someone by hand, an integration's key. A door where the\n * visitor acts for themselves (a form, a purchase) may leave it out.\n */\n actor?: {\n kind: 'member' | 'visitor' | 'apiKey' | 'platform'\n uid?: string | null\n email?: string | null\n apiKeyName?: string | null\n }\n orgId: string\n /** The site the person was met on: the brand whose form or checkout it was. */\n hostId: string\n identity: PluginContactIdentity\n interaction: PluginContactInteraction\n /**\n * An explicit marketing opt-in the capture surface carried, recorded against\n * `hostId`: consent to the MARKETING send purpose (`marketing-consent.ts`),\n * whichever plugin's mail later asks for it. Absent is not consent, and\n * filing a capture under a container is not consent either.\n */\n marketingConsent?: boolean\n /**\n * The disclosure key the capture surface rendered beside that opt-in\n * (`consentGroupDisclosureKey`, AGL-3320), passed through as the surface\n * sent it. The owner records the opt-in for the site's whole consent group\n * only when this is the group's current key, and for `hostId` alone\n * otherwise — so a silo whose surface shows no disclosure sends none.\n */\n disclosedConsentGroup?: string\n /** Tags the silo puts on this capture; the owner adds, never replaces. */\n tags?: readonly string[]\n /**\n * What the capture SURFACE is filed under — the merchant's own act — by\n * container kind (`plugin-containers.ts`): `{ [kind]: ids }`. The owner\n * files the person under the kinds it keeps. Filing is not consent.\n */\n containers?: Readonly<Record<string, readonly string[]>>\n /** Money the capture was worth, in cents, where the silo took some. */\n purchaseCents?: number\n /** The currency {@link purchaseCents} is in, lowercase, when the silo knows. */\n purchaseCurrency?: string\n /**\n * The earliest stage this capture describes, in the OWNER's words. A floor\n * and not a value: the owner fills an empty stage and advances an earlier\n * one, and never moves anybody back, so a repeat customer filling in a\n * contact form is still a customer.\n */\n lifecycleFloor?: string\n /**\n * What kind of door this is, which decides WHICH RECORD the person lands\n * on (AGL-3232) — the owner's rule is Salesforce's: one person is one\n * record, a lead until they are qualified and a contact after.\n *\n * - `lead`: a lead surface — a form whose author routes it to leads, a\n * booking request. The person is filed as a LEAD and nothing else,\n * unless the workspace already holds them as a contact, in which case\n * the capture lands on the contact and no lead is filed.\n * - `relationship`: an act that makes the person a known relationship —\n * a member account, a purchase. The person is filed as a CONTACT, and\n * an open lead the site held for them is stamped converted onto it.\n * - `touch`, the default: everything else — a form without lead routing,\n * a newsletter opt-in. The capture lands on the open lead when the site\n * holds one for the address, and on the contact otherwise.\n */\n surface?: 'lead' | 'relationship' | 'touch'\n /**\n * Profile fields the silo knows, keyed by the owner's own field names.\n * Only the keys given are written, so a silo that knows the phone number\n * does not blank a title somebody typed.\n */\n profile?: Readonly<Record<string, unknown>>\n /**\n * Profile fields written only where the record the person lands on holds\n * none (AGL-3493), keyed as {@link profile} is. For what a door learned\n * in passing — the phone a booking form asked for — and must not put over\n * a value somebody typed on the record or gave the business before.\n * A key also present in `profile` is `profile`'s to write.\n */\n profileFill?: Readonly<Record<string, unknown>>\n /**\n * Facts about THIS CAPTURE that the owner models and the platform does not\n * (AGL-3080) — which form was filled in, which page it was on, where the\n * visitor arrived from.\n *\n * Opaque for the reason {@link profile} is: every one of these is a concept\n * belonging to the plugin that keeps people or to the silo that saw it, and\n * a typed core field for each would be those models spelled out in the\n * platform again. `profile` describes the PERSON and outlives the visit;\n * this describes the visit and does not.\n *\n * A key the owner does not recognize is the owner's to ignore, and a silo\n * that sends nothing here loses nothing: every field is an enrichment of a\n * capture that is already complete without it.\n */\n detail?: Readonly<Record<string, unknown>>\n}\n\n/**\n * The owner's answer. `created: false` is a visit by somebody the workspace\n * already held, which is an interaction and not a new person.\n *\n * A refusal is RETURNED. Every one of these silos has already done the thing\n * it was recording, so a throw here would cost an accepted submission or a\n * paid order for a record it could not keep.\n */\nexport type PluginContactCaptured =\n /** The capture landed on a contact — the record every capture used to make. */\n | { ok: true; record: 'contact'; contactId: string; created: boolean }\n /**\n * The capture landed on a LEAD (AGL-3232): a lead surface met somebody the\n * workspace does not hold as a contact, or a touch reached an open lead.\n * `leadId` is the person key the lead is filed under on `hostId`.\n */\n | {\n ok: true\n record: 'lead'\n leadId: string\n created: boolean\n /**\n * Whether this capture's surface was new on the lead — a new person,\n * or one first met through another door. A form counts its leads by\n * it (AGL-3330): the people it filed, not the times they came back.\n * Absent from a writer that does not say, which a caller reads as\n * `created`.\n */\n sourceAdded?: boolean\n }\n | {\n ok: false\n /**\n * `invalid-email`: nothing usable to key a person on. `band`: the\n * workspace is at the audience it may hold. `erased`: the workspace\n * erased this person and a capture must not quietly rebuild them.\n * `error`: the owner failed, and said so rather than silently.\n */\n reason: 'invalid-email' | 'band' | 'erased' | 'error'\n /** Customer-safe: a caller may show or log it as it stands. */\n error: string\n }\n\nexport interface PluginContactCaptureWriter {\n /** Records one capture; a refusal is returned, never thrown. */\n capture(\n request: PluginContactCaptureRequest,\n ): Promise<PluginContactCaptured>\n}\n\n/** A capture door a silo owns. */\nexport interface PluginContactSourceDeclaration {\n /** The silo's word for the door, as its captures carry it. */\n source: string\n /** What a timeline entry from this door says: `Form submission`. */\n label: string\n /**\n * What a link from that entry says when there is something to open —\n * `Open submission`. Absent where the door leaves nothing to open, which\n * is the honest answer for an import or a by-hand add.\n */\n openLabel?: string\n /**\n * The record kind the silo's own document is, for\n * `plugin-record-routes` to address it with. Absent where the door has no\n * record of its own to open.\n */\n recordKind?: string\n}\n\n/** A source declaration with the silo that made it. */\nexport type ResolvedPluginContactSource = PluginContactSourceDeclaration & {\n pluginId: string\n}\n\nexport const PLUGIN_CONTACT_CAPTURE =\n definePluginServiceContract<PluginContactCaptureWriter>(\n 'core.contact-capture',\n { multiple: false },\n )\n\nexport const PLUGIN_CONTACT_SOURCES =\n definePluginServiceContract<PluginContactSourceDeclaration>(\n 'core.contact-capture-sources',\n { multiple: true },\n )\n\n/**\n * Registers the plugin that keeps people. The owner is the loader's marker\n * when a register fn is running, else `options.pluginId`; with neither the\n * registration throws, and a second plugin's writer is refused naming both —\n * the incumbent keeps serving.\n */\nexport function registerPluginContactCaptureWriter(\n writer: PluginContactCaptureWriter,\n options?: { pluginId?: string },\n): void {\n registerPluginService(PLUGIN_CONTACT_CAPTURE, writer, {\n ...(options?.pluginId ? { pluginId: options.pluginId } : {}),\n })\n}\n\n/** Declares a capture door. One source word has one owner. */\nexport function registerPluginContactSource(\n declaration: PluginContactSourceDeclaration,\n options?: { pluginId?: string },\n): void {\n const key = declaration.source?.trim() ?? ''\n if (!key) throw new Error('a contact capture source needs a source word')\n if (!declaration.label?.trim()) {\n throw new Error(`contact capture source \"${key}\" needs a label`)\n }\n const pluginId = (getRegisteringPluginId() ?? options?.pluginId ?? '').trim()\n const incumbent = resolvePluginServices(PLUGIN_CONTACT_SOURCES).find(\n (entry) => entry.key === key,\n )\n if (incumbent && pluginId && incumbent.pluginId !== pluginId) {\n throw new Error(\n `contact capture source \"${key}\" is already declared by ` +\n `\"${incumbent.pluginId}\"; refused \"${pluginId}\"`,\n )\n }\n registerPluginService(\n PLUGIN_CONTACT_SOURCES,\n { ...declaration, source: key },\n {\n ...(options?.pluginId ? { pluginId: options.pluginId } : {}),\n key,\n },\n )\n}\n\nexport interface ResolvedPluginContactCaptureWriter {\n /** The plugin that keeps people. */\n pluginId: string\n writer: PluginContactCaptureWriter\n}\n\n/** The writer with its owner, or `null` when no plugin keeps people here. */\nexport function pluginContactCaptureWriter(): ResolvedPluginContactCaptureWriter | null {\n const entry = resolvePluginServices(PLUGIN_CONTACT_CAPTURE)[0]\n return entry ? { pluginId: entry.pluginId, writer: entry.impl } : null\n}\n\n/**\n * Hands one capture to the plugin that keeps people, or answers `null` when\n * no plugin does.\n *\n * `null` and a refusal are different answers and a silo treats them\n * differently: `null` is a workspace with no record system, where there is\n * nothing to record and nothing has gone wrong; a refusal is a record system\n * that considered this person and declined.\n */\nexport async function capturePluginContact(\n request: PluginContactCaptureRequest,\n): Promise<PluginContactCaptured | null> {\n const found = pluginContactCaptureWriter()\n if (!found) return null\n return found.writer.capture(request)\n}\n\n/** Every declared capture door, with its silo, in registration order. */\nexport function listPluginContactSources(): ResolvedPluginContactSource[] {\n return resolvePluginServices(PLUGIN_CONTACT_SOURCES).map((entry) => ({\n ...entry.impl,\n pluginId: entry.pluginId,\n }))\n}\n\n/** One declared capture door by its source word, or `null`. */\nexport function pluginContactSource(\n source: string,\n): ResolvedPluginContactSource | null {\n const key = source.trim()\n const entry = resolvePluginServices(PLUGIN_CONTACT_SOURCES).find(\n (one) => one.key === key,\n )\n return entry ? { ...entry.impl, pluginId: entry.pluginId } : null\n}\n\n/**\n * How a contact's source word reads on screen, wherever it came from: the\n * core's own words from {@link CONTACT_SOURCE_LABELS}, then the label a\n * plugin declared for its door with {@link registerPluginContactSource},\n * then `fallback` when one is given, else the word itself.\n *\n * The core's map is a closed `Record<ContactSource, string>`, and a plugin's\n * door is an open string by design, so a list, a chip or a report that read\n * the map alone showed a plugin's raw word (`waiver` rather than its label).\n * This is the one place both are asked, in that order, so a plugin cannot\n * relabel a core source. It answers from what is registered in THIS process:\n * a plugin that declares its door from its `declarations` entry is known in\n * the console's browser and on both servers before a page renders.\n */\nexport function labelContactSource(source: unknown, fallback?: string): string {\n const word = typeof source === 'string' ? source.trim() : ''\n if (!word) return fallback ?? ''\n if (Object.hasOwn(CONTACT_SOURCE_LABELS, word)) {\n return CONTACT_SOURCE_LABELS[word as keyof typeof CONTACT_SOURCE_LABELS]\n }\n return pluginContactSource(word)?.label || (fallback ?? word)\n}\n\n/**\n * Whether a word is a source this process can name: one of the core's, or a\n * door a plugin declared. What keeps a saved filter from carrying a word\n * nothing answers to, without closing the list against a plugin's door.\n */\nexport function isKnownContactSource(source: unknown): boolean {\n const word = typeof source === 'string' ? source.trim() : ''\n if (!word) return false\n return Object.hasOwn(CONTACT_SOURCE_LABELS, word) || pluginContactSource(word) !== null\n}\n\n/** One source a filter offers: the stored word, and how it reads. */\nexport interface PluginContactSourceOption {\n value: string\n label: string\n}\n\n/**\n * Every source a filter can offer: the core's, then each door a plugin\n * declared, each reading as {@link labelContactSource} reads it, so a filter's\n * choice and a row's chip cannot disagree. A plugin that declares a core word\n * adds no second entry and does not change its label.\n */\nexport function listContactSourceOptions(): PluginContactSourceOption[] {\n const words = new Set([\n ...Object.keys(CONTACT_SOURCE_LABELS),\n ...listPluginContactSources().map((door) => door.source),\n ])\n return [...words].map((value) => ({ value, label: labelContactSource(value) }))\n}\n"],"names":["CONTACT_SOURCE_LABELS","getRegisteringPluginId","definePluginServiceContract","registerPluginService","resolvePluginServices","PLUGIN_CONTACT_CAPTURE","multiple","PLUGIN_CONTACT_SOURCES","registerPluginContactCaptureWriter","writer","options","pluginId","registerPluginContactSource","declaration","key","source","trim","Error","label","incumbent","find","entry","pluginContactCaptureWriter","impl","capturePluginContact","request","found","capture","listPluginContactSources","map","pluginContactSource","one","labelContactSource","fallback","word","Object","hasOwn","isKnownContactSource","listContactSourceOptions","words","Set","keys","door","value"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,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,MAAKe,mBAAAA,WAAYC;AAC1D;AAEA;;;;CAIC,GACD,OAAO,SAASG,qBAAqBtB,MAAe;IAClD,MAAMmB,OAAO,OAAOnB,WAAW,WAAWA,OAAOC,IAAI,KAAK;IAC1D,IAAI,CAACkB,MAAM,OAAO;IAClB,OAAOC,OAAOC,MAAM,CAACpC,uBAAuBkC,SAASJ,oBAAoBI,UAAU;AACrF;AAQA;;;;;CAKC,GACD,OAAO,SAASI;IACd,MAAMC,QAAQ,IAAIC,IAAI;WACjBL,OAAOM,IAAI,CAACzC;WACZ4B,2BAA2BC,GAAG,CAAC,CAACa,OAASA,KAAK3B,MAAM;KACxD;IACD,OAAO;WAAIwB;KAAM,CAACV,GAAG,CAAC,CAACc,QAAW,CAAA;YAAEA;YAAOzB,OAAOc,mBAAmBW;QAAO,CAAA;AAC9E"}
1
+ {"version":3,"sources":["../../../../../../libs/aglyn/src/lib/plugin-manager/plugin-contact-capture.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 { CONTACT_SOURCE_LABELS } from '../app-utils/contacts'\nimport { getRegisteringPluginId } from '../app-utils/registering-plugin'\nimport {\n definePluginServiceContract,\n registerPluginService,\n resolvePluginServices,\n} from './plugin-services'\n\n/**\n * A person met on a site, handed to whichever plugin keeps people (AGL-3124).\n *\n * Four silos capture the same thing and none of them is the record system: a\n * form submission, a site member signing up, an order, a booking. Each holds\n * an address, a name and the fact that something happened, and each wants the\n * workspace's person record to know. Today each one imports the writer, which\n * makes the highest-fan-in edge in the repo — thirty files in one plugin alone\n * — and makes the record system's plugin something a storefront cannot take a\n * payment without.\n *\n * So the silo stops importing and starts DECLARING: it registers the capture\n * door it owns, and hands a capture to this seam. The plugin that keeps people\n * registers the writer and does every part of the work that is a record\n * system's to do:\n *\n * - normalizing and keying the address, and deciding whether this is a new\n * person or a visit from one the workspace already holds;\n * - the audience band, the erasure rows, and every other refusal — answered,\n * never thrown, so a capture that is refused never costs the silo the order\n * or the submission it was recording;\n * - what a stage, an owner, a company and a tag mean, and what the arrival\n * of a new person sets off.\n *\n * The silo decides none of that. It reports what it saw.\n *\n * ## Why the profile is opaque\n *\n * `profile` is the owner's own field names with scalar values, not a core\n * type. A person's record shape belongs to the plugin that models it, and a\n * typed core shape would be that model spelled in the platform again — which\n * is the defect this seam exists to retire, not a smaller version of it. A key\n * the owner does not document is the owner's to ignore.\n *\n * `source` is the silo's own word for its door, and it is declared rather than\n * enumerated here for the same reason: core listing `form`, `member`, `order`\n * and `booking` would be core holding the plugin set again. A silo registers\n * its source with {@link registerPluginContactSource}, which is what lets a\n * timeline label an entry and a link point back at the thing that captured the\n * person, without the platform knowing what any of them are.\n *\n * ## One writer; many silos\n *\n * A workspace keeps one set of people, so the writer is a slot: a second\n * plugin's writer is refused naming both, and the incumbent keeps serving. A\n * SOURCE is per silo and there are many, but one source word has one owner —\n * two plugins claiming `order` would make the label and the link ambiguous at\n * the point they are read.\n *\n * ## The caller proves who is asking\n *\n * Like `plugin-record-timeline`, the registry authenticates nobody. A silo has\n * already decided, in its own terms and before it asks, that the capture is\n * the workspace's to record — that the submission was accepted, that the order\n * was paid.\n *\n * Server-side: reached by its own subpath, never through\n * `plugin-manager/index.ts`.\n */\n\n/** The person, as the capturing silo saw them. */\nexport interface PluginContactIdentity {\n /**\n * The address they gave. Raw: the owner normalizes and keys on it, and a\n * silo that normalized first would be keeping a second copy of that rule.\n */\n email: unknown\n name?: string | null\n}\n\n/** What happened, in the capturing silo's own words. */\nexport interface PluginContactInteraction {\n /** The silo's declared source word — see {@link registerPluginContactSource}. */\n source: string\n /** When it happened, epoch ms; the owner uses now when absent. */\n atMs?: number\n /**\n * The document it happened on, in the silo's terms\n * (`formSubmissions/{id}`, `orders/{id}`), so a timeline entry can point\n * back at it. Absent where the door leaves nothing to open.\n */\n refId?: string | null\n /** One line a person reads on the timeline. */\n summary?: string | null\n}\n\nexport interface PluginContactCaptureRequest {\n /**\n * Who caused the capture, when it was not the person captured (AGL-3376) —\n * a member adding someone by hand, an integration's key. A door where the\n * visitor acts for themselves (a form, a purchase) may leave it out.\n */\n actor?: {\n kind: 'member' | 'visitor' | 'apiKey' | 'platform'\n uid?: string | null\n email?: string | null\n apiKeyName?: string | null\n }\n orgId: string\n /** The site the person was met on: the brand whose form or checkout it was. */\n hostId: string\n identity: PluginContactIdentity\n interaction: PluginContactInteraction\n /**\n * An explicit marketing opt-in the capture surface carried, recorded against\n * `hostId`: consent to the MARKETING send purpose (`marketing-consent.ts`),\n * whichever plugin's mail later asks for it. Absent is not consent, and\n * filing a capture under a container is not consent either.\n */\n marketingConsent?: boolean\n /**\n * The disclosure key the capture surface rendered beside that opt-in\n * (`consentGroupDisclosureKey`, AGL-3320), passed through as the surface\n * sent it. The owner records the opt-in for the site's whole consent group\n * only when this is the group's current key, and for `hostId` alone\n * otherwise — so a silo whose surface shows no disclosure sends none.\n */\n disclosedConsentGroup?: string\n /** Tags the silo puts on this capture; the owner adds, never replaces. */\n tags?: readonly string[]\n /**\n * What the capture SURFACE is filed under — the merchant's own act — by\n * container kind (`plugin-containers.ts`): `{ [kind]: ids }`. The owner\n * files the person under the kinds it keeps. Filing is not consent.\n */\n containers?: Readonly<Record<string, readonly string[]>>\n /** Money the capture was worth, in cents, where the silo took some. */\n purchaseCents?: number\n /** The currency {@link purchaseCents} is in, lowercase, when the silo knows. */\n purchaseCurrency?: string\n /**\n * The earliest stage this capture describes, in the OWNER's words. A floor\n * and not a value: the owner fills an empty stage and advances an earlier\n * one, and never moves anybody back, so a repeat customer filling in a\n * contact form is still a customer.\n */\n lifecycleFloor?: string\n /**\n * What kind of door this is, which decides WHICH RECORD the person lands\n * on (AGL-3232) — the owner's rule is Salesforce's: one person is one\n * record, a lead until they are qualified and a contact after.\n *\n * - `lead`: a lead surface — a form whose author routes it to leads, a\n * booking request. The person is filed as a LEAD and nothing else,\n * unless the workspace already holds them as a contact, in which case\n * the capture lands on the contact and no lead is filed.\n * - `relationship`: an act that makes the person a known relationship —\n * a member account, a purchase. The person is filed as a CONTACT, and\n * an open lead the site held for them is stamped converted onto it.\n * - `touch`, the default: everything else — a form without lead routing,\n * a newsletter opt-in. The capture lands on the open lead when the site\n * holds one for the address, and on the contact otherwise.\n */\n surface?: 'lead' | 'relationship' | 'touch'\n /**\n * Profile fields the silo knows, keyed by the owner's own field names.\n * Only the keys given are written, so a silo that knows the phone number\n * does not blank a title somebody typed.\n */\n profile?: Readonly<Record<string, unknown>>\n /**\n * Profile fields written only where the record the person lands on holds\n * none (AGL-3493), keyed as {@link profile} is. For what a door learned\n * in passing — the phone a booking form asked for — and must not put over\n * a value somebody typed on the record or gave the business before.\n * A key also present in `profile` is `profile`'s to write.\n */\n profileFill?: Readonly<Record<string, unknown>>\n /**\n * Facts about THIS CAPTURE that the owner models and the platform does not\n * (AGL-3080) — which form was filled in, which page it was on, where the\n * visitor arrived from.\n *\n * Opaque for the reason {@link profile} is: every one of these is a concept\n * belonging to the plugin that keeps people or to the silo that saw it, and\n * a typed core field for each would be those models spelled out in the\n * platform again. `profile` describes the PERSON and outlives the visit;\n * this describes the visit and does not.\n *\n * A key the owner does not recognize is the owner's to ignore, and a silo\n * that sends nothing here loses nothing: every field is an enrichment of a\n * capture that is already complete without it.\n */\n detail?: Readonly<Record<string, unknown>>\n}\n\n/**\n * The owner's answer. `created: false` is a visit by somebody the workspace\n * already held, which is an interaction and not a new person.\n *\n * A refusal is RETURNED. Every one of these silos has already done the thing\n * it was recording, so a throw here would cost an accepted submission or a\n * paid order for a record it could not keep.\n */\nexport type PluginContactCaptured =\n /** The capture landed on a contact — the record every capture used to make. */\n | { ok: true; record: 'contact'; contactId: string; created: boolean }\n /**\n * The capture landed on a LEAD (AGL-3232): a lead surface met somebody the\n * workspace does not hold as a contact, or a touch reached an open lead.\n * `leadId` is the person key the lead is filed under on `hostId`.\n */\n | {\n ok: true\n record: 'lead'\n leadId: string\n created: boolean\n /**\n * Whether this capture's surface was new on the lead — a new person,\n * or one first met through another door. A form counts its leads by\n * it (AGL-3330): the people it filed, not the times they came back.\n * Absent from a writer that does not say, which a caller reads as\n * `created`.\n */\n sourceAdded?: boolean\n }\n | {\n ok: false\n /**\n * `invalid-email`: nothing usable to key a person on. `band`: the\n * workspace is at the audience it may hold. `erased`: the workspace\n * erased this person and a capture must not quietly rebuild them.\n * `error`: the owner failed, and said so rather than silently.\n */\n reason: 'invalid-email' | 'band' | 'erased' | 'error'\n /** Customer-safe: a caller may show or log it as it stands. */\n error: string\n }\n\nexport interface PluginContactCaptureWriter {\n /** Records one capture; a refusal is returned, never thrown. */\n capture(\n request: PluginContactCaptureRequest,\n ): Promise<PluginContactCaptured>\n}\n\n/** A capture door a silo owns. */\nexport interface PluginContactSourceDeclaration {\n /** The silo's word for the door, as its captures carry it. */\n source: string\n /** What a timeline entry from this door says: `Form submission`. */\n label: string\n /**\n * What a link from that entry says when there is something to open —\n * `Open submission`. Absent where the door leaves nothing to open, which\n * is the honest answer for an import or a by-hand add.\n */\n openLabel?: string\n /**\n * The record kind the silo's own document is, for\n * `plugin-record-routes` to address it with. Absent where the door has no\n * record of its own to open.\n */\n recordKind?: string\n}\n\n/** A source declaration with the silo that made it. */\nexport type ResolvedPluginContactSource = PluginContactSourceDeclaration & {\n pluginId: string\n}\n\nexport const PLUGIN_CONTACT_CAPTURE =\n definePluginServiceContract<PluginContactCaptureWriter>(\n 'core.contact-capture',\n { multiple: false },\n )\n\nexport const PLUGIN_CONTACT_SOURCES =\n definePluginServiceContract<PluginContactSourceDeclaration>(\n 'core.contact-capture-sources',\n { multiple: true },\n )\n\n/**\n * Registers the plugin that keeps people. The owner is the loader's marker\n * when a register fn is running, else `options.pluginId`; with neither the\n * registration throws, and a second plugin's writer is refused naming both —\n * the incumbent keeps serving.\n */\nexport function registerPluginContactCaptureWriter(\n writer: PluginContactCaptureWriter,\n options?: { pluginId?: string },\n): void {\n registerPluginService(PLUGIN_CONTACT_CAPTURE, writer, {\n ...(options?.pluginId ? { pluginId: options.pluginId } : {}),\n })\n}\n\n/** Declares a capture door. One source word has one owner. */\nexport function registerPluginContactSource(\n declaration: PluginContactSourceDeclaration,\n options?: { pluginId?: string },\n): void {\n const key = declaration.source?.trim() ?? ''\n if (!key) throw new Error('a contact capture source needs a source word')\n if (!declaration.label?.trim()) {\n throw new Error(`contact capture source \"${key}\" needs a label`)\n }\n const pluginId = (getRegisteringPluginId() ?? options?.pluginId ?? '').trim()\n const incumbent = resolvePluginServices(PLUGIN_CONTACT_SOURCES).find(\n (entry) => entry.key === key,\n )\n if (incumbent && pluginId && incumbent.pluginId !== pluginId) {\n throw new Error(\n `contact capture source \"${key}\" is already declared by ` +\n `\"${incumbent.pluginId}\"; refused \"${pluginId}\"`,\n )\n }\n registerPluginService(\n PLUGIN_CONTACT_SOURCES,\n { ...declaration, source: key },\n {\n ...(options?.pluginId ? { pluginId: options.pluginId } : {}),\n key,\n },\n )\n}\n\nexport interface ResolvedPluginContactCaptureWriter {\n /** The plugin that keeps people. */\n pluginId: string\n writer: PluginContactCaptureWriter\n}\n\n/** The writer with its owner, or `null` when no plugin keeps people here. */\nexport function pluginContactCaptureWriter(): ResolvedPluginContactCaptureWriter | null {\n const entry = resolvePluginServices(PLUGIN_CONTACT_CAPTURE)[0]\n return entry ? { pluginId: entry.pluginId, writer: entry.impl } : null\n}\n\n/**\n * Hands one capture to the plugin that keeps people, or answers `null` when\n * no plugin does.\n *\n * `null` and a refusal are different answers and a silo treats them\n * differently: `null` is a workspace with no record system, where there is\n * nothing to record and nothing has gone wrong; a refusal is a record system\n * that considered this person and declined.\n */\nexport async function capturePluginContact(\n request: PluginContactCaptureRequest,\n): Promise<PluginContactCaptured | null> {\n const found = pluginContactCaptureWriter()\n if (!found) return null\n return found.writer.capture(request)\n}\n\n/** Every declared capture door, with its silo, in registration order. */\nexport function listPluginContactSources(): ResolvedPluginContactSource[] {\n return resolvePluginServices(PLUGIN_CONTACT_SOURCES).map((entry) => ({\n ...entry.impl,\n pluginId: entry.pluginId,\n }))\n}\n\n/** One declared capture door by its source word, or `null`. */\nexport function pluginContactSource(\n source: string,\n): ResolvedPluginContactSource | null {\n const key = source.trim()\n const entry = resolvePluginServices(PLUGIN_CONTACT_SOURCES).find(\n (one) => one.key === key,\n )\n return entry ? { ...entry.impl, pluginId: entry.pluginId } : null\n}\n\n/**\n * How a contact's source word reads on screen, wherever it came from: the\n * core's own words from {@link CONTACT_SOURCE_LABELS}, then the label a\n * plugin declared for its door with {@link registerPluginContactSource},\n * then `fallback` when one is given, else the word itself.\n *\n * The core's map is a closed `Record<ContactSource, string>`, and a plugin's\n * door is an open string by design, so a list, a chip or a report that read\n * the map alone showed a plugin's raw word (`waiver` rather than its label).\n * This is the one place both are asked, in that order, so a plugin cannot\n * relabel a core source. It answers from what is registered in THIS process:\n * a plugin that declares its door from its `declarations` entry is known in\n * the console's browser and on both servers before a page renders.\n */\nexport function labelContactSource(source: unknown, fallback?: string): string {\n const word = typeof source === 'string' ? source.trim() : ''\n if (!word) return fallback ?? ''\n if (Object.hasOwn(CONTACT_SOURCE_LABELS, word)) {\n return CONTACT_SOURCE_LABELS[word as keyof typeof CONTACT_SOURCE_LABELS]\n }\n return pluginContactSource(word)?.label || (fallback ?? word)\n}\n\n/**\n * Whether a word is a source this process can name: one of the core's, or a\n * door a plugin declared. What keeps a saved filter from carrying a word\n * nothing answers to, without closing the list against a plugin's door.\n */\nexport function isKnownContactSource(source: unknown): boolean {\n const word = typeof source === 'string' ? source.trim() : ''\n if (!word) return false\n return Object.hasOwn(CONTACT_SOURCE_LABELS, word) || pluginContactSource(word) !== null\n}\n\n/**\n * Whether a capture source is a plugin's word rather than one of the core's.\n *\n * A capture writes its source into the holder's facet, and that is the only place\n * a plugin's word has ever been. A list's sweep still reads the core's words off\n * the top of the row, so reading them from the facet too would change who an\n * existing source-filtered list selects. It asks this to read the facet for the\n * words no existing list could have named.\n */\nexport function isPluginContactSource(source: string): boolean {\n return !Object.hasOwn(CONTACT_SOURCE_LABELS, source)\n}\n\n/** One source a filter offers: the stored word, and how it reads. */\nexport interface PluginContactSourceOption {\n value: string\n label: string\n}\n\n/**\n * Every source a filter can offer: the core's, then each door a plugin\n * declared, each reading as {@link labelContactSource} reads it, so a filter's\n * choice and a row's chip cannot disagree. A plugin that declares a core word\n * adds no second entry and does not change its label.\n */\nexport function listContactSourceOptions(): PluginContactSourceOption[] {\n const words = new Set([\n ...Object.keys(CONTACT_SOURCE_LABELS),\n ...listPluginContactSources().map((door) => door.source),\n ])\n return [...words].map((value) => ({ value, label: labelContactSource(value) }))\n}\n"],"names":["CONTACT_SOURCE_LABELS","getRegisteringPluginId","definePluginServiceContract","registerPluginService","resolvePluginServices","PLUGIN_CONTACT_CAPTURE","multiple","PLUGIN_CONTACT_SOURCES","registerPluginContactCaptureWriter","writer","options","pluginId","registerPluginContactSource","declaration","key","source","trim","Error","label","incumbent","find","entry","pluginContactCaptureWriter","impl","capturePluginContact","request","found","capture","listPluginContactSources","map","pluginContactSource","one","labelContactSource","fallback","word","Object","hasOwn","isKnownContactSource","isPluginContactSource","listContactSourceOptions","words","Set","keys","door","value"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,qBAAqB,QAAQ,2BAAuB;AAC7D,SAASC,sBAAsB,QAAQ,qCAAiC;AACxE,SACEC,2BAA2B,EAC3BC,qBAAqB,EACrBC,qBAAqB,QAChB,uBAAmB;AAuQ1B,OAAO,MAAMC,yBACXH,4BACE,wBACA;IAAEI,UAAU;AAAM,GACnB;AAEH,OAAO,MAAMC,yBACXL,4BACE,gCACA;IAAEI,UAAU;AAAK,GAClB;AAEH;;;;;CAKC,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O,SAASI,sBAAsBvB,MAAc;IAClD,OAAO,CAACoB,OAAOC,MAAM,CAACpC,uBAAuBe;AAC/C;AAQA;;;;;CAKC,GACD,OAAO,SAASwB;IACd,MAAMC,QAAQ,IAAIC,IAAI;WACjBN,OAAOO,IAAI,CAAC1C;WACZ4B,2BAA2BC,GAAG,CAAC,CAACc,OAASA,KAAK5B,MAAM;KACxD;IACD,OAAO;WAAIyB;KAAM,CAACX,GAAG,CAAC,CAACe,QAAW,CAAA;YAAEA;YAAO1B,OAAOc,mBAAmBY;QAAO,CAAA;AAC9E"}
@@ -186,6 +186,16 @@ export interface PluginOrgPermissionDeclaration {
186
186
  * key whose preset is the site role (`presetFromSiteRole`).
187
187
  */
188
188
  narrowsPerSite?: boolean | Partial<Record<OrgRole, boolean>>;
189
+ /**
190
+ * A site can also RAISE this key (AGL-4047). Where a member of the whole
191
+ * workspace has wider access to one site than their workspace role, the key
192
+ * reads `hostRoleDefaults` for that access there, unless a custom role or
193
+ * their own permissions decide it or the key it `follows`. For a key that
194
+ * narrows and raises with the site, which `presetFromSiteRole` cannot be:
195
+ * that gives up the workspace's verdict, and with it `narrowsPerSite`'s
196
+ * "Keep this permission". Needs `hostRoleDefaults`.
197
+ */
198
+ raisesPerSite?: boolean;
189
199
  /**
190
200
  * The key's preset is the member's role ON THE SITE, for every member
191
201
  * (AGL-4047), not only for a site collaborator: the owner and admins are
@@ -242,6 +252,8 @@ export interface PluginCatalogPermission {
242
252
  * default for whether it does, normalized from the declaration.
243
253
  */
244
254
  narrowsPerSite?: Readonly<Record<OrgRole, boolean>>;
255
+ /** A site can raise the key (AGL-4047); see the declaration's. */
256
+ raisesPerSite?: true;
245
257
  /** The key's preset is the member's role on the site (AGL-4047); see the declaration's. */
246
258
  presetFromSiteRole?: true;
247
259
  /** That preset holds for members of the whole workspace only (AGL-4047); see the declaration's. */
@@ -243,7 +243,9 @@ const reportedCatalogRefusals = new Set();
243
243
  presetFromSiteRole: true
244
244
  }, permission.workspaceMembersOnly ? {
245
245
  workspaceMembersOnly: true
246
- } : {}) : narrowingDefaultsOf(permission.narrowsPerSite)));
246
+ } : {}) : narrowingDefaultsOf(permission.narrowsPerSite), permission.raisesPerSite && permission.hostRoleDefaults && !permission.presetFromSiteRole ? {
247
+ raisesPerSite: true
248
+ } : {}));
247
249
  }
248
250
  for (const permission of listPluginPermissions()){
249
251
  var _permission_description, _permission_group1, _permission_groupLabel1;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../libs/aglyn/src/lib/plugin-manager/plugin-entitlements.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 * Plugin-declared billing and access keys (AGL-2940).\n *\n * A plugin that sells something, gates something, or can be switched off in\n * an incident declares the KEYS here — a seat add-on, a feature flag, a\n * lockdown lever, a permission — and the core catalogs that used to be\n * edited for each one read the declarations instead:\n *\n * - `plan-entitlements` folds every registered seat add-on into\n * `resolveOrgEntitlements` (a quota raised per unit, features switched on)\n * and answers a registered feature's plan defaults;\n * - `lockdown` lists a registered lever on the staff page, carries its label,\n * its staff-bypass rule and its visitor notice, and maps the API paths it\n * names onto it for the plugin dispatcher;\n * - `plugin-permissions` receives the permissions with the owner filled in;\n * - `org-permissions` folds every declared catalog key into the org\n * permission catalog — the role editor, custom roles, per-member overrides\n * and the rules stamp — and `host-permissions` decides the keys that\n * declare host-role defaults for a site collaborator, per site.\n *\n * The NUMBERS stay where they are checked. A seat add-on's price is a row in\n * `PLAN_PRICING`, read by the Stripe wiring and reconciled by\n * `check-pricing-drift`; a declaration names the quota it widens and by how\n * much per plan, and nothing here restates a price.\n *\n * Registration order is deterministic: the catalog order of\n * `FIRST_PARTY_PLUGINS`, then any other id alphabetically. Plugin modules\n * load in parallel, so the order they REGISTER in is whatever the network\n * gave, and a list that followed it would put the staff lockdown checklist\n * in a different order per session.\n */\n\nimport type { AglynOrgBilling, HostAccessRole, OrgPlan, OrgRole } from '../foundation'\nimport { declarationRoleDefaults } from '../app-utils/org-role-grants'\nimport { FIRST_PARTY_PLUGINS } from './enabled-plugins'\nimport {\n listPluginPermissions,\n registerPluginPermissions,\n type PluginPermission,\n} from './plugin-permissions'\n\nexport interface PluginSeatAddonDeclaration {\n /** The `org.seatAddons` key the purchase is stored under (`aiAddon`). */\n key: string\n label: string\n /**\n * How many purchased units count. `1` for an org-wide add-on that is\n * bought once, where a doubled webhook item or a hand edit above one is\n * still one purchase; absent to count the stored quantity.\n */\n maxUnits?: number\n /**\n * The quota each unit widens: the resolved entitlement named by `key`\n * gains `perUnit(org, plan) × units` when the figure depends on WHAT was\n * bought (the Aglyn AI tier, AGL-3965), else `perUnitByPlan[plan] × units`.\n * A plan the add-on is not sold on answers 0.\n */\n quota?: {\n key: string\n perUnitByPlan?: Readonly<Record<OrgPlan, number>>\n /**\n * The per-unit figure read off the org itself. `org` is the billing\n * document as `resolveOrgEntitlements` received it and `plan` its\n * effective plan.\n */\n perUnit?: (org: Readonly<Partial<AglynOrgBilling>>, plan: OrgPlan) => number\n }\n /** Feature flags a purchased unit switches on. */\n features?: readonly string[]\n /**\n * Whether a plan sells the add-on, when `perUnitByPlan` cannot say so\n * (a `perUnit` quota, AGL-3965). Absent: sold where `perUnitByPlan` names\n * a figure above zero, or everywhere for an add-on with no quota.\n */\n soldOn?: (plan: OrgPlan) => boolean\n}\n\n/**\n * Whether a plan sells a declared seat add-on: its own `soldOn`, else a\n * `perUnitByPlan` figure above zero for the plan, else (no quota) yes.\n */\nexport function pluginSeatAddonSoldOn(\n addon: PluginSeatAddonDeclaration,\n plan: OrgPlan,\n): boolean {\n if (addon.soldOn) return addon.soldOn(plan)\n if (!addon.quota) return true\n return (addon.quota.perUnitByPlan?.[plan] ?? 0) > 0\n}\n\nexport interface PluginFeatureDeclaration {\n /** The `OrgFeatureFlags` key. */\n key: string\n label: string\n /**\n * The plan defaults, when the key is not one the plan tables already\n * carry. Absent means the plan tables decide, which is the case for every\n * key that predates this registry.\n */\n defaultByPlan?: Readonly<Partial<Record<OrgPlan, boolean>>>\n}\n\nexport interface PluginLockdownFeatureDeclaration {\n /** The lever's wire identity (`ai-generate`). */\n key: string\n /** The staff checklist's label. */\n label: string\n /**\n * What the lever is called in the customer's mail when staff pull it for\n * their workspace (`media uploads`, `AI generation`). A noun phrase that\n * reads right mid-sentence (\"our team paused media uploads\") and after a\n * colon, so lowercase unless it starts with a name or an acronym. The\n * staff `label` never reaches a customer.\n */\n customerName: string\n /**\n * Whether a verified staff claim passes the lock. Granted where a staff\n * action aids incident response — one real call proves a provider is back\n * — and withheld where the staff action would BE the incident.\n */\n staffBypass: boolean\n /**\n * What a visitor reads while the lever is pulled: what is paused AND what\n * still works. The expected-back window is appended by the notice builder.\n */\n notice: { title: string; body: string }\n /**\n * Plugin API paths the lever gates at the dispatcher: exact paths, and\n * prefixes matched on a segment boundary (`ai/generate` also gates\n * `ai/generate/section`, never `ai/generated-report`).\n */\n apiPaths?: { exact?: readonly string[]; prefixes?: readonly string[] }\n}\n\n/**\n * A key a plugin adds to the org permission CATALOG (AGL-2984): the granular\n * map custom roles and per-member overrides are stored in, that\n * `resolveOrgPermissions` layers and the rules stamp carries, and that the\n * role editor lists. A declared key is stored, layered and resolved exactly\n * like a core key; the declaration supplies what a core key's catalog entry\n * and role table supply.\n */\nexport interface PluginOrgPermissionDeclaration {\n /** The dotted key a custom role and a per-member override store (`reviews.reply`). */\n key: string\n /** The role editor's line for the key, and the word a refusal names. */\n label: string\n /** What the key opens, under the label in the role editor. */\n description: string\n /** Each org role's verdict when no custom role or per-member override sets the key. */\n roleDefaults: Readonly<Record<OrgRole, boolean>>\n /**\n * Each HOST role's verdict, for a key a site collaborator holds per site.\n *\n * A collaborator's membership carries no org standing to refine — it\n * exists only to carry access to named sites — so a key with this field is\n * decided for them on the site a request names: the host role they hold\n * there, refined by the per-site toggle on their member document. A key\n * without it is never held by a collaborator.\n */\n hostRoleDefaults?: Readonly<Record<HostAccessRole, boolean>>\n /**\n * The role editor's group for the key (AGL-4047): a core group id\n * (`CORE_ORG_PERMISSION_GROUPS`) or, absent, a group of the plugin's own.\n */\n group?: string\n /** The heading of a group of the plugin's own; absent: the plugin's catalog label. */\n groupLabel?: string\n /**\n * A broader key this one is a finer part of (AGL-4047): never granted\n * without it, and following it where nothing sets this key. See\n * `PluginPermission.refines`.\n */\n refines?: string\n /**\n * A key this one takes its verdict from where nothing sets it, without\n * needing it (AGL-4047). See `PluginPermission.follows`.\n */\n follows?: string\n /**\n * A site can narrow this key, and the built-in roles' default for whether\n * it does (AGL-4047). See `PluginPermission.narrowsPerSite`. Ignored on a\n * key whose preset is the site role (`presetFromSiteRole`).\n */\n narrowsPerSite?: boolean | Partial<Record<OrgRole, boolean>>\n /**\n * The key's preset is the member's role ON THE SITE, for every member\n * (AGL-4047), not only for a site collaborator: the owner and admins are\n * admins of every site, a workspace-wide editor or viewer holds their\n * workspace role on a site unless the site gives them other access there\n * (narrower or wider), and a collaborator holds their site role. So the\n * key reads `hostRoleDefaults` for whatever access the member has on the\n * site a request names, exactly as a gate on that host role did, and a\n * custom role, the member's own permissions and that site's toggle then\n * grant or refuse it like any other key. Needs `hostRoleDefaults`, and\n * `roleDefaults` that match them tier for tier (the owner and admins on\n * Admin, editors on Editor, viewers on Viewer), which is the answer with\n * no site named.\n *\n * For a key that replaces a gate on the site role (who may edit a site's\n * stays, say), so the built-in roles keep exactly the access they had\n * while the key becomes grantable and deniable like every other.\n */\n presetFromSiteRole?: boolean\n /**\n * With `presetFromSiteRole`: the site role is the preset only for a member\n * of the WHOLE workspace (AGL-4047). Someone added to one site only holds\n * the key there when the site's toggle grants it, whatever their site role,\n * and `hostRoleDefaults` is not their default. For a key that replaces a\n * gate asking for an admin of the whole workspace who is also this site's\n * admin (refunds, say): a site's Members card can make a contractor the\n * admin of one site, and that never carried those acts.\n */\n workspaceMembersOnly?: boolean\n}\n\n/**\n * One key of the ONE permission catalog that a plugin contributes (AGL-4047),\n * whichever of the two declaration APIs it came through:\n * `registerPluginEntitlements({ orgPermissions })` (`source: 'catalog'`) or\n * `registerPluginPermissions` (`source: 'tier'`, its per-tier defaults read\n * as org-role defaults, the owner on the admin tier).\n */\nexport interface PluginCatalogPermission {\n key: string\n label: string\n description: string\n pluginId: string\n roleDefaults: Readonly<Record<OrgRole, boolean>>\n hostRoleDefaults?: Readonly<Record<HostAccessRole, boolean>>\n group: string\n groupLabel: string\n source: 'catalog' | 'tier'\n /** The broader key this one refines, when it does. */\n refines?: string\n /** The key this one follows without needing it, when it does. */\n follows?: string\n /**\n * Present when a site can narrow the key (AGL-4047): each built-in role's\n * default for whether it does, normalized from the declaration.\n */\n narrowsPerSite?: Readonly<Record<OrgRole, boolean>>\n /** The key's preset is the member's role on the site (AGL-4047); see the declaration's. */\n presetFromSiteRole?: true\n /** That preset holds for members of the whole workspace only (AGL-4047); see the declaration's. */\n workspaceMembersOnly?: true\n}\n\nexport interface PluginEntitlementRegistration {\n pluginId: string\n seatAddons?: readonly PluginSeatAddonDeclaration[]\n features?: readonly PluginFeatureDeclaration[]\n lockdownFeatures?: readonly PluginLockdownFeatureDeclaration[]\n /** Per-tier keys a plugin's own pages read (`registerPluginPermissions`). */\n permissions?: readonly Omit<PluginPermission, 'pluginId'>[]\n /** Keys added to the org permission catalog — see {@link PluginOrgPermissionDeclaration}. */\n orgPermissions?: readonly PluginOrgPermissionDeclaration[]\n}\n\n/**\n * The registrations and their listeners, held on `globalThis` rather than in\n * module `const`s (AGL-3596), as the custom field registry and the\n * declarations repair hook are (AGL-3412).\n *\n * An app registers the plugins' declarations from `instrumentation.ts`, which\n * Next compiles into a different module graph from the routes. A module-scoped\n * map was filled in the instrumentation's copy and read empty in a route's, so\n * a core route that never loaded a plugin knew none of its keys: the site\n * create door asked for `ai.generate`, read `undefined` from a catalog that\n * had never heard of it, and every guided AI start was born with the starter.\n * One map per process, under a `Symbol.for` key, is the same map in every\n * copy.\n */\nconst REGISTRY_KEY = Symbol.for('@aglyn/aglyn:plugin-entitlements')\n\ninterface PluginEntitlementsRegistry {\n registrations: Map<string, PluginEntitlementRegistration>\n /**\n * Readers of the registrations that keep a derived view in step with them —\n * every copy of the org permission catalog rebuilds itself on every\n * registration and reset, because a plugin's declarations can register\n * after a module that imported the catalog was evaluated, and in another\n * module graph's copy of this file.\n */\n listeners: Set<() => void>\n}\n\nconst globalScope = globalThis as typeof globalThis & {\n [REGISTRY_KEY]?: PluginEntitlementsRegistry\n}\n\nconst registry: PluginEntitlementsRegistry = (globalScope[REGISTRY_KEY] ??= {\n registrations: new Map(),\n listeners: new Set(),\n})\n\nconst registrations = registry.registrations\nconst listeners = registry.listeners\n\n/** Calls `listener` after every registration and reset; answers the unsubscribe. */\nexport function subscribePluginEntitlements(listener: () => void): () => void {\n listeners.add(listener)\n return () => {\n listeners.delete(listener)\n }\n}\n\nfunction notifyListeners(): void {\n for (const listener of [...listeners]) listener()\n}\n\nconst CATALOG_ORDER = new Map(\n FIRST_PARTY_PLUGINS.map((plugin, index) => [plugin.id, index]),\n)\n\nfunction catalogRank(pluginId: string): number {\n return CATALOG_ORDER.get(pluginId) ?? Number.MAX_SAFE_INTEGER\n}\n\nfunction orderedRegistrations(): PluginEntitlementRegistration[] {\n return [...registrations.values()].sort(\n (a, b) =>\n catalogRank(a.pluginId) - catalogRank(b.pluginId) ||\n a.pluginId.localeCompare(b.pluginId),\n )\n}\n\nfunction refuseStolenKeys(\n pluginId: string,\n kind: 'seat add-on' | 'lockdown feature' | 'org permission',\n keys: readonly string[],\n ownerOf: (key: string) => string | undefined,\n): void {\n for (const key of keys) {\n const owner = ownerOf(key)\n if (owner && owner !== pluginId) {\n throw new Error(\n `${kind} \"${key}\" is already declared by \"${owner}\"; refused \"${pluginId}\"`,\n )\n }\n }\n}\n\n/**\n * Idempotent per plugin — re-registration replaces that plugin's\n * declarations. A seat add-on, lockdown or catalog permission key another\n * plugin already owns refuses the whole registration: one key, one owner,\n * or the two declarations disagree about what the key means.\n */\nexport function registerPluginEntitlements(\n registration: PluginEntitlementRegistration,\n): void {\n const pluginId = registration.pluginId.trim()\n if (!pluginId) throw new Error('plugin entitlements need a pluginId')\n refuseStolenKeys(\n pluginId,\n 'seat add-on',\n (registration.seatAddons ?? []).map((entry) => entry.key),\n (key) => pluginSeatAddonOwner(key),\n )\n refuseStolenKeys(\n pluginId,\n 'lockdown feature',\n (registration.lockdownFeatures ?? []).map((entry) => entry.key),\n (key) => pluginLockdownFeatureOwner(key),\n )\n refuseStolenKeys(\n pluginId,\n 'org permission',\n (registration.orgPermissions ?? []).map((entry) => entry.key),\n (key) => pluginOrgPermissionOwner(key) ?? pluginTierPermissionOwner(key),\n )\n registrations.set(pluginId, { ...registration, pluginId })\n if (registration.permissions?.length) {\n registerPluginPermissions(\n registration.permissions.map((permission) => ({ ...permission, pluginId })),\n )\n }\n notifyListeners()\n}\n\nfunction pluginSeatAddonOwner(key: string): string | undefined {\n for (const entry of registrations.values()) {\n if (entry.seatAddons?.some((addon) => addon.key === key)) return entry.pluginId\n }\n return undefined\n}\n\nfunction pluginLockdownFeatureOwner(key: string): string | undefined {\n for (const entry of registrations.values()) {\n if (entry.lockdownFeatures?.some((feature) => feature.key === key)) {\n return entry.pluginId\n }\n }\n return undefined\n}\n\nfunction pluginOrgPermissionOwner(key: string): string | undefined {\n for (const entry of registrations.values()) {\n if (entry.orgPermissions?.some((permission) => permission.key === key)) {\n return entry.pluginId\n }\n }\n return undefined\n}\n\nfunction pluginTierPermissionOwner(key: string): string | undefined {\n return listPluginPermissions().find((permission) => permission.key === key)?.pluginId\n}\n\n/** Refusals already logged by `listPluginCatalogPermissions`, so each is reported once. */\n// boot-registry: per copy — it only de-duplicates a warning; a second compiled copy logging the same refusal once more is harmless, and nothing reads it to decide anything.\nconst reportedCatalogRefusals = new Set<string>()\n\n/** A plugin's catalog label, the heading its own permission group carries. */\nfunction pluginLabel(pluginId: string): string {\n return FIRST_PARTY_PLUGINS.find((plugin) => plugin.id === pluginId)?.label ?? pluginId\n}\n\n/**\n * A declaration's `narrowsPerSite`, normalized to each built-in role's\n * default (AGL-4047): `true` or `false` names every role, a map names each,\n * a role it leaves out keeps. Absent: the key is not one a site can narrow.\n */\nfunction narrowingDefaultsOf(\n declared: boolean | Partial<Record<OrgRole, boolean>> | undefined,\n): { narrowsPerSite?: Readonly<Record<OrgRole, boolean>> } {\n if (declared === undefined || declared === null) return {}\n const every = typeof declared === 'boolean' ? declared : undefined\n const map = typeof declared === 'object' ? declared : {}\n return {\n narrowsPerSite: {\n owner: every ?? map.owner === true,\n admin: every ?? map.admin === true,\n editor: every ?? map.editor === true,\n viewer: every ?? map.viewer === true,\n },\n }\n}\n\n/**\n * Every key plugins contribute to the permission catalog, through EITHER\n * declaration API, in catalog order (AGL-4047): per plugin, its\n * `orgPermissions` declarations and then its `registerPluginPermissions`\n * keys. A key both APIs carry for the same plugin is the catalog\n * declaration's; one a DIFFERENT plugin already declared is refused and\n * logged once, the first declaration keeping its meaning and defaults.\n *\n * Read live: both registries fill at plugin module scope, which can be after\n * any reader of this was evaluated.\n */\nexport function listPluginCatalogPermissions(): PluginCatalogPermission[] {\n const byPlugin = new Map<string, PluginCatalogPermission[]>()\n const owner = new Map<string, string>()\n const add = (entry: PluginCatalogPermission): void => {\n const incumbent = owner.get(entry.key)\n if (incumbent !== undefined) {\n if (incumbent !== entry.pluginId) {\n const refusal = `${entry.pluginId}\\x00${entry.key}`\n if (!reportedCatalogRefusals.has(refusal)) {\n reportedCatalogRefusals.add(refusal)\n console.error(\n `[plugins] refused permission key \"${entry.key}\" to \"${entry.pluginId}\": ` +\n `already declared by \"${incumbent}\"`,\n )\n }\n }\n return\n }\n owner.set(entry.key, entry.pluginId)\n const list = byPlugin.get(entry.pluginId) ?? []\n list.push(entry)\n byPlugin.set(entry.pluginId, list)\n }\n for (const permission of listPluginOrgPermissions()) {\n add({\n key: permission.key,\n label: permission.label,\n description: permission.description,\n pluginId: permission.pluginId,\n roleDefaults: declarationRoleDefaults(permission),\n ...(permission.hostRoleDefaults ? { hostRoleDefaults: permission.hostRoleDefaults } : {}),\n group: permission.group ?? permission.pluginId,\n groupLabel: permission.groupLabel ?? pluginLabel(permission.pluginId),\n source: 'catalog',\n ...(permission.refines ? { refines: permission.refines } : {}),\n ...(permission.follows ? { follows: permission.follows } : {}),\n // A key whose preset is the site role follows every site's access\n // already, so it offers no narrowing control (AGL-4047).\n ...(permission.presetFromSiteRole && permission.hostRoleDefaults\n ? {\n presetFromSiteRole: true as const,\n ...(permission.workspaceMembersOnly ? { workspaceMembersOnly: true as const } : {}),\n }\n : narrowingDefaultsOf(permission.narrowsPerSite)),\n })\n }\n for (const permission of listPluginPermissions()) {\n add({\n key: permission.key,\n label: permission.label,\n description: permission.description ?? '',\n pluginId: permission.pluginId,\n roleDefaults: declarationRoleDefaults(permission),\n group: permission.group ?? permission.pluginId,\n groupLabel: permission.groupLabel ?? pluginLabel(permission.pluginId),\n source: 'tier',\n ...(permission.refines ? { refines: permission.refines } : {}),\n ...(permission.follows ? { follows: permission.follows } : {}),\n ...narrowingDefaultsOf(permission.narrowsPerSite),\n })\n }\n return [...byPlugin.keys()]\n .sort((a, b) => catalogRank(a) - catalogRank(b) || a.localeCompare(b))\n .flatMap((pluginId) => byPlugin.get(pluginId) ?? [])\n}\n\n/** Every declared catalog permission, in catalog order, with the plugin that declared it. */\nexport function listPluginOrgPermissions(): Array<\n PluginOrgPermissionDeclaration & { pluginId: string }\n> {\n return orderedRegistrations().flatMap((entry) =>\n (entry.orgPermissions ?? []).map((permission) => ({\n ...permission,\n pluginId: entry.pluginId,\n })),\n )\n}\n\n/** Every declared seat add-on, in catalog order. */\nexport function listPluginSeatAddons(): PluginSeatAddonDeclaration[] {\n return orderedRegistrations().flatMap((entry) => [...(entry.seatAddons ?? [])])\n}\n\n/** One declared seat add-on by its `seatAddons` key. */\nexport function pluginSeatAddon(key: string): PluginSeatAddonDeclaration | undefined {\n return listPluginSeatAddons().find((entry) => entry.key === key)\n}\n\n/** Every declared feature, in catalog order. */\nexport function listPluginFeatures(): PluginFeatureDeclaration[] {\n return orderedRegistrations().flatMap((entry) => [...(entry.features ?? [])])\n}\n\n/** Every declared lockdown lever, in catalog order. */\nexport function listPluginLockdownFeatures(): PluginLockdownFeatureDeclaration[] {\n return orderedRegistrations().flatMap((entry) => [\n ...(entry.lockdownFeatures ?? []),\n ])\n}\n\n/** One declared lockdown lever by key. */\nexport function pluginLockdownFeature(\n key: string,\n): PluginLockdownFeatureDeclaration | undefined {\n return listPluginLockdownFeatures().find((entry) => entry.key === key)\n}\n\n/** The plugin that declared a lockdown lever, for attribution. */\nexport function pluginIdForLockdownFeature(key: string): string | undefined {\n return pluginLockdownFeatureOwner(key)\n}\n\n/** Every registration, in catalog order. */\nexport function listPluginEntitlementRegistrations(): PluginEntitlementRegistration[] {\n return orderedRegistrations()\n}\n\n/**\n * Test seam: forget every registration. The per-tier permissions stay\n * registered; the catalog permissions go with their registrations.\n */\nexport function resetPluginEntitlementsForTests(): void {\n registrations.clear()\n notifyListeners()\n}\n"],"names":["globalScope","REGISTRY_KEY","declarationRoleDefaults","FIRST_PARTY_PLUGINS","listPluginPermissions","registerPluginPermissions","pluginSeatAddonSoldOn","addon","plan","soldOn","quota","perUnitByPlan","Symbol","for","globalThis","registry","registrations","Map","listeners","Set","subscribePluginEntitlements","listener","add","delete","notifyListeners","CATALOG_ORDER","map","plugin","index","id","catalogRank","pluginId","get","Number","MAX_SAFE_INTEGER","orderedRegistrations","values","sort","a","b","localeCompare","refuseStolenKeys","kind","keys","ownerOf","key","owner","Error","registerPluginEntitlements","registration","trim","seatAddons","entry","pluginSeatAddonOwner","lockdownFeatures","pluginLockdownFeatureOwner","orgPermissions","pluginOrgPermissionOwner","pluginTierPermissionOwner","set","permissions","length","permission","some","undefined","feature","find","reportedCatalogRefusals","pluginLabel","label","narrowingDefaultsOf","declared","every","narrowsPerSite","admin","editor","viewer","listPluginCatalogPermissions","byPlugin","incumbent","refusal","has","console","error","list","push","listPluginOrgPermissions","description","roleDefaults","hostRoleDefaults","group","groupLabel","source","refines","follows","presetFromSiteRole","workspaceMembersOnly","flatMap","listPluginSeatAddons","pluginSeatAddon","listPluginFeatures","features","listPluginLockdownFeatures","pluginLockdownFeature","pluginIdForLockdownFeature","listPluginEntitlementRegistrations","resetPluginEntitlementsForTests","clear"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA8BC;IAqQ6CA,cAAYC,eAAZD;AAlQ9C,SAASE,uBAAuB,QAAQ,kCAA8B;AACtE,SAASC,mBAAmB,QAAQ,uBAAmB;AACvD,SACEC,qBAAqB,EACrBC,yBAAyB,QAEpB,0BAAsB;AAsC7B;;;CAGC,GACD,OAAO,SAASC,sBACdC,KAAiC,EACjCC,IAAa;;QAILD;IAFR,IAAIA,MAAME,MAAM,EAAE,OAAOF,MAAME,MAAM,CAACD;IACtC,IAAI,CAACD,MAAMG,KAAK,EAAE,OAAO;IACzB,OAAO,UAACH,6BAAAA,MAAMG,KAAK,CAACC,aAAa,qBAAzBJ,0BAA2B,CAACC,KAAK,mBAAI,KAAK;AACpD;AA2KA;;;;;;;;;;;;;CAaC,GACD,MAAMP,eAAeW,OAAOC,GAAG,CAAC;AAchC,MAAMb,cAAcc;AAIpB,MAAMC,YAAwCf,IAAAA,CAAAA,eAAAA,YAAW,CAACC,gBAAAA,aAAa,YAAzBD,IAAAA,YAAW,CAACC,cAAa,GAAK;IAC1Ee,eAAe,IAAIC;IACnBC,WAAW,IAAIC;AACjB;AAEA,MAAMH,gBAAgBD,SAASC,aAAa;AAC5C,MAAME,YAAYH,SAASG,SAAS;AAEpC,kF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ACH/B,UAAUqB,MAAMrB,QAAQ;;;AAG9B;AAEA,kDAAkD,GAClD,OAAO,SAASmE;IACd,OAAO/D,uBAAuB8D,OAAO,CAAC,CAAC7C;YAAeA;eAAL;gBAAKA,oBAAAA,MAAMD,UAAU,YAAhBC,oBAAoB,EAAE;SAAE;;AAChF;AAEA,sDAAsD,GACtD,OAAO,SAAS+C,gBAAgBtD,GAAW;IACzC,OAAOqD,uBAAuBhC,IAAI,CAAC,CAACd,QAAUA,MAAMP,GAAG,KAAKA;AAC9D;AAEA,8CAA8C,GAC9C,OAAO,SAASuD;IACd,OAAOjE,uBAAuB8D,OAAO,CAAC,CAAC7C;YAAeA;eAAL;gBAAKA,kBAAAA,MAAMiD,QAAQ,YAAdjD,kBAAkB,EAAE;SAAE;;AAC9E;AAEA,qDAAqD,GACrD,OAAO,SAASkD;IACd,OAAOnE,uBAAuB8D,OAAO,CAAC,CAAC7C;YACjCA;eAD2C;gBAC3CA,0BAAAA,MAAME,gBAAgB,YAAtBF,0BAA0B,EAAE;SACjC;;AACH;AAEA,wCAAwC,GACxC,OAAO,SAASmD,sBACd1D,GAAW;IAEX,OAAOyD,6BAA6BpC,IAAI,CAAC,CAACd,QAAUA,MAAMP,GAAG,KAAKA;AACpE;AAEA,gEAAgE,GAChE,OAAO,SAAS2D,2BAA2B3D,GAAW;IACpD,OAAOU,2BAA2BV;AACpC;AAEA,0CAA0C,GAC1C,OAAO,SAAS4D;IACd,OAAOtE;AACT;AAEA;;;CAGC,GACD,OAAO,SAASuE;IACd1F,cAAc2F,KAAK;IACnBnF;AACF"}
1
+ {"version":3,"sources":["../../../../../../libs/aglyn/src/lib/plugin-manager/plugin-entitlements.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 * Plugin-declared billing and access keys (AGL-2940).\n *\n * A plugin that sells something, gates something, or can be switched off in\n * an incident declares the KEYS here — a seat add-on, a feature flag, a\n * lockdown lever, a permission — and the core catalogs that used to be\n * edited for each one read the declarations instead:\n *\n * - `plan-entitlements` folds every registered seat add-on into\n * `resolveOrgEntitlements` (a quota raised per unit, features switched on)\n * and answers a registered feature's plan defaults;\n * - `lockdown` lists a registered lever on the staff page, carries its label,\n * its staff-bypass rule and its visitor notice, and maps the API paths it\n * names onto it for the plugin dispatcher;\n * - `plugin-permissions` receives the permissions with the owner filled in;\n * - `org-permissions` folds every declared catalog key into the org\n * permission catalog — the role editor, custom roles, per-member overrides\n * and the rules stamp — and `host-permissions` decides the keys that\n * declare host-role defaults for a site collaborator, per site.\n *\n * The NUMBERS stay where they are checked. A seat add-on's price is a row in\n * `PLAN_PRICING`, read by the Stripe wiring and reconciled by\n * `check-pricing-drift`; a declaration names the quota it widens and by how\n * much per plan, and nothing here restates a price.\n *\n * Registration order is deterministic: the catalog order of\n * `FIRST_PARTY_PLUGINS`, then any other id alphabetically. Plugin modules\n * load in parallel, so the order they REGISTER in is whatever the network\n * gave, and a list that followed it would put the staff lockdown checklist\n * in a different order per session.\n */\n\nimport type { AglynOrgBilling, HostAccessRole, OrgPlan, OrgRole } from '../foundation'\nimport { declarationRoleDefaults } from '../app-utils/org-role-grants'\nimport { FIRST_PARTY_PLUGINS } from './enabled-plugins'\nimport {\n listPluginPermissions,\n registerPluginPermissions,\n type PluginPermission,\n} from './plugin-permissions'\n\nexport interface PluginSeatAddonDeclaration {\n /** The `org.seatAddons` key the purchase is stored under (`aiAddon`). */\n key: string\n label: string\n /**\n * How many purchased units count. `1` for an org-wide add-on that is\n * bought once, where a doubled webhook item or a hand edit above one is\n * still one purchase; absent to count the stored quantity.\n */\n maxUnits?: number\n /**\n * The quota each unit widens: the resolved entitlement named by `key`\n * gains `perUnit(org, plan) × units` when the figure depends on WHAT was\n * bought (the Aglyn AI tier, AGL-3965), else `perUnitByPlan[plan] × units`.\n * A plan the add-on is not sold on answers 0.\n */\n quota?: {\n key: string\n perUnitByPlan?: Readonly<Record<OrgPlan, number>>\n /**\n * The per-unit figure read off the org itself. `org` is the billing\n * document as `resolveOrgEntitlements` received it and `plan` its\n * effective plan.\n */\n perUnit?: (org: Readonly<Partial<AglynOrgBilling>>, plan: OrgPlan) => number\n }\n /** Feature flags a purchased unit switches on. */\n features?: readonly string[]\n /**\n * Whether a plan sells the add-on, when `perUnitByPlan` cannot say so\n * (a `perUnit` quota, AGL-3965). Absent: sold where `perUnitByPlan` names\n * a figure above zero, or everywhere for an add-on with no quota.\n */\n soldOn?: (plan: OrgPlan) => boolean\n}\n\n/**\n * Whether a plan sells a declared seat add-on: its own `soldOn`, else a\n * `perUnitByPlan` figure above zero for the plan, else (no quota) yes.\n */\nexport function pluginSeatAddonSoldOn(\n addon: PluginSeatAddonDeclaration,\n plan: OrgPlan,\n): boolean {\n if (addon.soldOn) return addon.soldOn(plan)\n if (!addon.quota) return true\n return (addon.quota.perUnitByPlan?.[plan] ?? 0) > 0\n}\n\nexport interface PluginFeatureDeclaration {\n /** The `OrgFeatureFlags` key. */\n key: string\n label: string\n /**\n * The plan defaults, when the key is not one the plan tables already\n * carry. Absent means the plan tables decide, which is the case for every\n * key that predates this registry.\n */\n defaultByPlan?: Readonly<Partial<Record<OrgPlan, boolean>>>\n}\n\nexport interface PluginLockdownFeatureDeclaration {\n /** The lever's wire identity (`ai-generate`). */\n key: string\n /** The staff checklist's label. */\n label: string\n /**\n * What the lever is called in the customer's mail when staff pull it for\n * their workspace (`media uploads`, `AI generation`). A noun phrase that\n * reads right mid-sentence (\"our team paused media uploads\") and after a\n * colon, so lowercase unless it starts with a name or an acronym. The\n * staff `label` never reaches a customer.\n */\n customerName: string\n /**\n * Whether a verified staff claim passes the lock. Granted where a staff\n * action aids incident response — one real call proves a provider is back\n * — and withheld where the staff action would BE the incident.\n */\n staffBypass: boolean\n /**\n * What a visitor reads while the lever is pulled: what is paused AND what\n * still works. The expected-back window is appended by the notice builder.\n */\n notice: { title: string; body: string }\n /**\n * Plugin API paths the lever gates at the dispatcher: exact paths, and\n * prefixes matched on a segment boundary (`ai/generate` also gates\n * `ai/generate/section`, never `ai/generated-report`).\n */\n apiPaths?: { exact?: readonly string[]; prefixes?: readonly string[] }\n}\n\n/**\n * A key a plugin adds to the org permission CATALOG (AGL-2984): the granular\n * map custom roles and per-member overrides are stored in, that\n * `resolveOrgPermissions` layers and the rules stamp carries, and that the\n * role editor lists. A declared key is stored, layered and resolved exactly\n * like a core key; the declaration supplies what a core key's catalog entry\n * and role table supply.\n */\nexport interface PluginOrgPermissionDeclaration {\n /** The dotted key a custom role and a per-member override store (`reviews.reply`). */\n key: string\n /** The role editor's line for the key, and the word a refusal names. */\n label: string\n /** What the key opens, under the label in the role editor. */\n description: string\n /** Each org role's verdict when no custom role or per-member override sets the key. */\n roleDefaults: Readonly<Record<OrgRole, boolean>>\n /**\n * Each HOST role's verdict, for a key a site collaborator holds per site.\n *\n * A collaborator's membership carries no org standing to refine — it\n * exists only to carry access to named sites — so a key with this field is\n * decided for them on the site a request names: the host role they hold\n * there, refined by the per-site toggle on their member document. A key\n * without it is never held by a collaborator.\n */\n hostRoleDefaults?: Readonly<Record<HostAccessRole, boolean>>\n /**\n * The role editor's group for the key (AGL-4047): a core group id\n * (`CORE_ORG_PERMISSION_GROUPS`) or, absent, a group of the plugin's own.\n */\n group?: string\n /** The heading of a group of the plugin's own; absent: the plugin's catalog label. */\n groupLabel?: string\n /**\n * A broader key this one is a finer part of (AGL-4047): never granted\n * without it, and following it where nothing sets this key. See\n * `PluginPermission.refines`.\n */\n refines?: string\n /**\n * A key this one takes its verdict from where nothing sets it, without\n * needing it (AGL-4047). See `PluginPermission.follows`.\n */\n follows?: string\n /**\n * A site can narrow this key, and the built-in roles' default for whether\n * it does (AGL-4047). See `PluginPermission.narrowsPerSite`. Ignored on a\n * key whose preset is the site role (`presetFromSiteRole`).\n */\n narrowsPerSite?: boolean | Partial<Record<OrgRole, boolean>>\n /**\n * A site can also RAISE this key (AGL-4047). Where a member of the whole\n * workspace has wider access to one site than their workspace role, the key\n * reads `hostRoleDefaults` for that access there, unless a custom role or\n * their own permissions decide it or the key it `follows`. For a key that\n * narrows and raises with the site, which `presetFromSiteRole` cannot be:\n * that gives up the workspace's verdict, and with it `narrowsPerSite`'s\n * \"Keep this permission\". Needs `hostRoleDefaults`.\n */\n raisesPerSite?: boolean\n /**\n * The key's preset is the member's role ON THE SITE, for every member\n * (AGL-4047), not only for a site collaborator: the owner and admins are\n * admins of every site, a workspace-wide editor or viewer holds their\n * workspace role on a site unless the site gives them other access there\n * (narrower or wider), and a collaborator holds their site role. So the\n * key reads `hostRoleDefaults` for whatever access the member has on the\n * site a request names, exactly as a gate on that host role did, and a\n * custom role, the member's own permissions and that site's toggle then\n * grant or refuse it like any other key. Needs `hostRoleDefaults`, and\n * `roleDefaults` that match them tier for tier (the owner and admins on\n * Admin, editors on Editor, viewers on Viewer), which is the answer with\n * no site named.\n *\n * For a key that replaces a gate on the site role (who may edit a site's\n * stays, say), so the built-in roles keep exactly the access they had\n * while the key becomes grantable and deniable like every other.\n */\n presetFromSiteRole?: boolean\n /**\n * With `presetFromSiteRole`: the site role is the preset only for a member\n * of the WHOLE workspace (AGL-4047). Someone added to one site only holds\n * the key there when the site's toggle grants it, whatever their site role,\n * and `hostRoleDefaults` is not their default. For a key that replaces a\n * gate asking for an admin of the whole workspace who is also this site's\n * admin (refunds, say): a site's Members card can make a contractor the\n * admin of one site, and that never carried those acts.\n */\n workspaceMembersOnly?: boolean\n}\n\n/**\n * One key of the ONE permission catalog that a plugin contributes (AGL-4047),\n * whichever of the two declaration APIs it came through:\n * `registerPluginEntitlements({ orgPermissions })` (`source: 'catalog'`) or\n * `registerPluginPermissions` (`source: 'tier'`, its per-tier defaults read\n * as org-role defaults, the owner on the admin tier).\n */\nexport interface PluginCatalogPermission {\n key: string\n label: string\n description: string\n pluginId: string\n roleDefaults: Readonly<Record<OrgRole, boolean>>\n hostRoleDefaults?: Readonly<Record<HostAccessRole, boolean>>\n group: string\n groupLabel: string\n source: 'catalog' | 'tier'\n /** The broader key this one refines, when it does. */\n refines?: string\n /** The key this one follows without needing it, when it does. */\n follows?: string\n /**\n * Present when a site can narrow the key (AGL-4047): each built-in role's\n * default for whether it does, normalized from the declaration.\n */\n narrowsPerSite?: Readonly<Record<OrgRole, boolean>>\n /** A site can raise the key (AGL-4047); see the declaration's. */\n raisesPerSite?: true\n /** The key's preset is the member's role on the site (AGL-4047); see the declaration's. */\n presetFromSiteRole?: true\n /** That preset holds for members of the whole workspace only (AGL-4047); see the declaration's. */\n workspaceMembersOnly?: true\n}\n\nexport interface PluginEntitlementRegistration {\n pluginId: string\n seatAddons?: readonly PluginSeatAddonDeclaration[]\n features?: readonly PluginFeatureDeclaration[]\n lockdownFeatures?: readonly PluginLockdownFeatureDeclaration[]\n /** Per-tier keys a plugin's own pages read (`registerPluginPermissions`). */\n permissions?: readonly Omit<PluginPermission, 'pluginId'>[]\n /** Keys added to the org permission catalog — see {@link PluginOrgPermissionDeclaration}. */\n orgPermissions?: readonly PluginOrgPermissionDeclaration[]\n}\n\n/**\n * The registrations and their listeners, held on `globalThis` rather than in\n * module `const`s (AGL-3596), as the custom field registry and the\n * declarations repair hook are (AGL-3412).\n *\n * An app registers the plugins' declarations from `instrumentation.ts`, which\n * Next compiles into a different module graph from the routes. A module-scoped\n * map was filled in the instrumentation's copy and read empty in a route's, so\n * a core route that never loaded a plugin knew none of its keys: the site\n * create door asked for `ai.generate`, read `undefined` from a catalog that\n * had never heard of it, and every guided AI start was born with the starter.\n * One map per process, under a `Symbol.for` key, is the same map in every\n * copy.\n */\nconst REGISTRY_KEY = Symbol.for('@aglyn/aglyn:plugin-entitlements')\n\ninterface PluginEntitlementsRegistry {\n registrations: Map<string, PluginEntitlementRegistration>\n /**\n * Readers of the registrations that keep a derived view in step with them —\n * every copy of the org permission catalog rebuilds itself on every\n * registration and reset, because a plugin's declarations can register\n * after a module that imported the catalog was evaluated, and in another\n * module graph's copy of this file.\n */\n listeners: Set<() => void>\n}\n\nconst globalScope = globalThis as typeof globalThis & {\n [REGISTRY_KEY]?: PluginEntitlementsRegistry\n}\n\nconst registry: PluginEntitlementsRegistry = (globalScope[REGISTRY_KEY] ??= {\n registrations: new Map(),\n listeners: new Set(),\n})\n\nconst registrations = registry.registrations\nconst listeners = registry.listeners\n\n/** Calls `listener` after every registration and reset; answers the unsubscribe. */\nexport function subscribePluginEntitlements(listener: () => void): () => void {\n listeners.add(listener)\n return () => {\n listeners.delete(listener)\n }\n}\n\nfunction notifyListeners(): void {\n for (const listener of [...listeners]) listener()\n}\n\nconst CATALOG_ORDER = new Map(\n FIRST_PARTY_PLUGINS.map((plugin, index) => [plugin.id, index]),\n)\n\nfunction catalogRank(pluginId: string): number {\n return CATALOG_ORDER.get(pluginId) ?? Number.MAX_SAFE_INTEGER\n}\n\nfunction orderedRegistrations(): PluginEntitlementRegistration[] {\n return [...registrations.values()].sort(\n (a, b) =>\n catalogRank(a.pluginId) - catalogRank(b.pluginId) ||\n a.pluginId.localeCompare(b.pluginId),\n )\n}\n\nfunction refuseStolenKeys(\n pluginId: string,\n kind: 'seat add-on' | 'lockdown feature' | 'org permission',\n keys: readonly string[],\n ownerOf: (key: string) => string | undefined,\n): void {\n for (const key of keys) {\n const owner = ownerOf(key)\n if (owner && owner !== pluginId) {\n throw new Error(\n `${kind} \"${key}\" is already declared by \"${owner}\"; refused \"${pluginId}\"`,\n )\n }\n }\n}\n\n/**\n * Idempotent per plugin — re-registration replaces that plugin's\n * declarations. A seat add-on, lockdown or catalog permission key another\n * plugin already owns refuses the whole registration: one key, one owner,\n * or the two declarations disagree about what the key means.\n */\nexport function registerPluginEntitlements(\n registration: PluginEntitlementRegistration,\n): void {\n const pluginId = registration.pluginId.trim()\n if (!pluginId) throw new Error('plugin entitlements need a pluginId')\n refuseStolenKeys(\n pluginId,\n 'seat add-on',\n (registration.seatAddons ?? []).map((entry) => entry.key),\n (key) => pluginSeatAddonOwner(key),\n )\n refuseStolenKeys(\n pluginId,\n 'lockdown feature',\n (registration.lockdownFeatures ?? []).map((entry) => entry.key),\n (key) => pluginLockdownFeatureOwner(key),\n )\n refuseStolenKeys(\n pluginId,\n 'org permission',\n (registration.orgPermissions ?? []).map((entry) => entry.key),\n (key) => pluginOrgPermissionOwner(key) ?? pluginTierPermissionOwner(key),\n )\n registrations.set(pluginId, { ...registration, pluginId })\n if (registration.permissions?.length) {\n registerPluginPermissions(\n registration.permissions.map((permission) => ({ ...permission, pluginId })),\n )\n }\n notifyListeners()\n}\n\nfunction pluginSeatAddonOwner(key: string): string | undefined {\n for (const entry of registrations.values()) {\n if (entry.seatAddons?.some((addon) => addon.key === key)) return entry.pluginId\n }\n return undefined\n}\n\nfunction pluginLockdownFeatureOwner(key: string): string | undefined {\n for (const entry of registrations.values()) {\n if (entry.lockdownFeatures?.some((feature) => feature.key === key)) {\n return entry.pluginId\n }\n }\n return undefined\n}\n\nfunction pluginOrgPermissionOwner(key: string): string | undefined {\n for (const entry of registrations.values()) {\n if (entry.orgPermissions?.some((permission) => permission.key === key)) {\n return entry.pluginId\n }\n }\n return undefined\n}\n\nfunction pluginTierPermissionOwner(key: string): string | undefined {\n return listPluginPermissions().find((permission) => permission.key === key)?.pluginId\n}\n\n/** Refusals already logged by `listPluginCatalogPermissions`, so each is reported once. */\n// boot-registry: per copy — it only de-duplicates a warning; a second compiled copy logging the same refusal once more is harmless, and nothing reads it to decide anything.\nconst reportedCatalogRefusals = new Set<string>()\n\n/** A plugin's catalog label, the heading its own permission group carries. */\nfunction pluginLabel(pluginId: string): string {\n return FIRST_PARTY_PLUGINS.find((plugin) => plugin.id === pluginId)?.label ?? pluginId\n}\n\n/**\n * A declaration's `narrowsPerSite`, normalized to each built-in role's\n * default (AGL-4047): `true` or `false` names every role, a map names each,\n * a role it leaves out keeps. Absent: the key is not one a site can narrow.\n */\nfunction narrowingDefaultsOf(\n declared: boolean | Partial<Record<OrgRole, boolean>> | undefined,\n): { narrowsPerSite?: Readonly<Record<OrgRole, boolean>> } {\n if (declared === undefined || declared === null) return {}\n const every = typeof declared === 'boolean' ? declared : undefined\n const map = typeof declared === 'object' ? declared : {}\n return {\n narrowsPerSite: {\n owner: every ?? map.owner === true,\n admin: every ?? map.admin === true,\n editor: every ?? map.editor === true,\n viewer: every ?? map.viewer === true,\n },\n }\n}\n\n/**\n * Every key plugins contribute to the permission catalog, through EITHER\n * declaration API, in catalog order (AGL-4047): per plugin, its\n * `orgPermissions` declarations and then its `registerPluginPermissions`\n * keys. A key both APIs carry for the same plugin is the catalog\n * declaration's; one a DIFFERENT plugin already declared is refused and\n * logged once, the first declaration keeping its meaning and defaults.\n *\n * Read live: both registries fill at plugin module scope, which can be after\n * any reader of this was evaluated.\n */\nexport function listPluginCatalogPermissions(): PluginCatalogPermission[] {\n const byPlugin = new Map<string, PluginCatalogPermission[]>()\n const owner = new Map<string, string>()\n const add = (entry: PluginCatalogPermission): void => {\n const incumbent = owner.get(entry.key)\n if (incumbent !== undefined) {\n if (incumbent !== entry.pluginId) {\n const refusal = `${entry.pluginId}\\x00${entry.key}`\n if (!reportedCatalogRefusals.has(refusal)) {\n reportedCatalogRefusals.add(refusal)\n console.error(\n `[plugins] refused permission key \"${entry.key}\" to \"${entry.pluginId}\": ` +\n `already declared by \"${incumbent}\"`,\n )\n }\n }\n return\n }\n owner.set(entry.key, entry.pluginId)\n const list = byPlugin.get(entry.pluginId) ?? []\n list.push(entry)\n byPlugin.set(entry.pluginId, list)\n }\n for (const permission of listPluginOrgPermissions()) {\n add({\n key: permission.key,\n label: permission.label,\n description: permission.description,\n pluginId: permission.pluginId,\n roleDefaults: declarationRoleDefaults(permission),\n ...(permission.hostRoleDefaults ? { hostRoleDefaults: permission.hostRoleDefaults } : {}),\n group: permission.group ?? permission.pluginId,\n groupLabel: permission.groupLabel ?? pluginLabel(permission.pluginId),\n source: 'catalog',\n ...(permission.refines ? { refines: permission.refines } : {}),\n ...(permission.follows ? { follows: permission.follows } : {}),\n // A key whose preset is the site role follows every site's access\n // already, so it offers no narrowing control (AGL-4047).\n ...(permission.presetFromSiteRole && permission.hostRoleDefaults\n ? {\n presetFromSiteRole: true as const,\n ...(permission.workspaceMembersOnly ? { workspaceMembersOnly: true as const } : {}),\n }\n : narrowingDefaultsOf(permission.narrowsPerSite)),\n ...(permission.raisesPerSite && permission.hostRoleDefaults && !permission.presetFromSiteRole\n ? { raisesPerSite: true as const }\n : {}),\n })\n }\n for (const permission of listPluginPermissions()) {\n add({\n key: permission.key,\n label: permission.label,\n description: permission.description ?? '',\n pluginId: permission.pluginId,\n roleDefaults: declarationRoleDefaults(permission),\n group: permission.group ?? permission.pluginId,\n groupLabel: permission.groupLabel ?? pluginLabel(permission.pluginId),\n source: 'tier',\n ...(permission.refines ? { refines: permission.refines } : {}),\n ...(permission.follows ? { follows: permission.follows } : {}),\n ...narrowingDefaultsOf(permission.narrowsPerSite),\n })\n }\n return [...byPlugin.keys()]\n .sort((a, b) => catalogRank(a) - catalogRank(b) || a.localeCompare(b))\n .flatMap((pluginId) => byPlugin.get(pluginId) ?? [])\n}\n\n/** Every declared catalog permission, in catalog order, with the plugin that declared it. */\nexport function listPluginOrgPermissions(): Array<\n PluginOrgPermissionDeclaration & { pluginId: string }\n> {\n return orderedRegistrations().flatMap((entry) =>\n (entry.orgPermissions ?? []).map((permission) => ({\n ...permission,\n pluginId: entry.pluginId,\n })),\n )\n}\n\n/** Every declared seat add-on, in catalog order. */\nexport function listPluginSeatAddons(): PluginSeatAddonDeclaration[] {\n return orderedRegistrations().flatMap((entry) => [...(entry.seatAddons ?? [])])\n}\n\n/** One declared seat add-on by its `seatAddons` key. */\nexport function pluginSeatAddon(key: string): PluginSeatAddonDeclaration | undefined {\n return listPluginSeatAddons().find((entry) => entry.key === key)\n}\n\n/** Every declared feature, in catalog order. */\nexport function listPluginFeatures(): PluginFeatureDeclaration[] {\n return orderedRegistrations().flatMap((entry) => [...(entry.features ?? [])])\n}\n\n/** Every declared lockdown lever, in catalog order. */\nexport function listPluginLockdownFeatures(): PluginLockdownFeatureDeclaration[] {\n return orderedRegistrations().flatMap((entry) => [\n ...(entry.lockdownFeatures ?? []),\n ])\n}\n\n/** One declared lockdown lever by key. */\nexport function pluginLockdownFeature(\n key: string,\n): PluginLockdownFeatureDeclaration | undefined {\n return listPluginLockdownFeatures().find((entry) => entry.key === key)\n}\n\n/** The plugin that declared a lockdown lever, for attribution. */\nexport function pluginIdForLockdownFeature(key: string): string | undefined {\n return pluginLockdownFeatureOwner(key)\n}\n\n/** Every registration, in catalog order. */\nexport function listPluginEntitlementRegistrations(): PluginEntitlementRegistration[] {\n return orderedRegistrations()\n}\n\n/**\n * Test seam: forget every registration. The per-tier permissions stay\n * registered; the catalog permissions go with their registrations.\n */\nexport function resetPluginEntitlementsForTests(): void {\n registrations.clear()\n notifyListeners()\n}\n"],"names":["globalScope","REGISTRY_KEY","declarationRoleDefaults","FIRST_PARTY_PLUGINS","listPluginPermissions","registerPluginPermissions","pluginSeatAddonSoldOn","addon","plan","soldOn","quota","perUnitByPlan","Symbol","for","globalThis","registry","registrations","Map","listeners","Set","subscribePluginEntitlements","listener","add","delete","notifyListeners","CATALOG_ORDER","map","plugin","index","id","catalogRank","pluginId","get","Number","MAX_SAFE_INTEGER","orderedRegistrations","values","sort","a","b","localeCompare","refuseStolenKeys","kind","keys","ownerOf","key","owner","Error","registerPluginEntitlements","registration","trim","seatAddons","entry","pluginSeatAddonOwner","lockdownFeatures","pluginLockdownFeatureOwner","orgPermissions","pluginOrgPermissionOwner","pluginTierPermissionOwner","set","permissions","length","permission","some","undefined","feature","find","reportedCatalogRefusals","pluginLabel","label","narrowingDefaultsOf","declared","every","narrowsPerSite","admin","editor","viewer","listPluginCatalogPermissions","byPlugin","incumbent","refusal","has","console","error","list","push","listPluginOrgPermissions","description","roleDefaults","hostRoleDefaults","group","groupLabel","source","refines","follows","presetFromSiteRole","workspaceMembersOnly","raisesPerSite","flatMap","listPluginSeatAddons","pluginSeatAddon","listPluginFeatures","features","listPluginLockdownFeatures","pluginLockdownFeature","pluginIdForLockdownFeature","listPluginEntitlementRegistrations","resetPluginEntitlementsForTests","clear"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA8BC;IAiR6CA,cAAYC,eAAZD;AA9Q9C,SAASE,uBAAuB,QAAQ,kCAA8B;AACtE,SAASC,mBAAmB,QAAQ,uBAAmB;AACvD,SACEC,qBAAqB,EACrBC,yBAAyB,QAEpB,0BAAsB;AAsC7B;;;CAGC,GACD,OAAO,SAASC,sBACdC,KAAiC,EACjCC,IAAa;;QAILD;IAFR,IAAIA,MAAME,MAAM,EAAE,OAAOF,MAAME,MAAM,CAACD;IACtC,IAAI,CAACD,MAAMG,KAAK,EAAE,OAAO;IACzB,OAAO,UAACH,6BAAAA,MAAMG,KAAK,CAACC,aAAa,qBAAzBJ,0BAA2B,CAACC,KAAK,mBAAI,KAAK;AACpD;AAuLA;;;;;;;;;;;;;CAaC,GACD,MAAMP,eAAeW,OAAOC,GAAG,CAAC;AAchC,MAAMb,cAAcc;AAIpB,MAAMC,YAAwCf,IAAAA,CAAAA,eAAAA,YAAW,CAACC,gBAAAA,aAAa,YAAzBD,IAAAA,YAAW,CAACC,cAAa,GAAK;IAC1Ee,eAAe,IAAIC;IACnBC,WAAW,IAAIC;AACjB;AAEA,MAAMH,gBAAgBD,SAASC,aAAa;AAC5C,MAAME,YAAYH,SAASG,SAAS;AAEpC,kFAAkF,GAClF,OAAO,SAASE,4BAA4BC,QAAoB;IAC9DH,UAAUI,GAAG,CAACD;IACd,OAAO;QACLH,UAAUK,MAAM,CAACF;IACnB;AACF;AAEA,SAASG;IACP,KAAK,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,QAAQ;;;AAG9B;AAEA,kDAAkD,GAClD,OAAO,SAASoE;IACd,OAAOhE,uBAAuB+D,OAAO,CAAC,CAAC9C;YAAeA;eAAL;gBAAKA,oBAAAA,MAAMD,UAAU,YAAhBC,oBAAoB,EAAE;SAAE;;AAChF;AAEA,sDAAsD,GACtD,OAAO,SAASgD,gBAAgBvD,GAAW;IACzC,OAAOsD,uBAAuBjC,IAAI,CAAC,CAACd,QAAUA,MAAMP,GAAG,KAAKA;AAC9D;AAEA,8CAA8C,GAC9C,OAAO,SAASwD;IACd,OAAOlE,uBAAuB+D,OAAO,CAAC,CAAC9C;YAAeA;eAAL;gBAAKA,kBAAAA,MAAMkD,QAAQ,YAAdlD,kBAAkB,EAAE;SAAE;;AAC9E;AAEA,qDAAqD,GACrD,OAAO,SAASmD;IACd,OAAOpE,uBAAuB+D,OAAO,CAAC,CAAC9C;YACjCA;eAD2C;gBAC3CA,0BAAAA,MAAME,gBAAgB,YAAtBF,0BAA0B,EAAE;SACjC;;AACH;AAEA,wCAAwC,GACxC,OAAO,SAASoD,sBACd3D,GAAW;IAEX,OAAO0D,6BAA6BrC,IAAI,CAAC,CAACd,QAAUA,MAAMP,GAAG,KAAKA;AACpE;AAEA,gEAAgE,GAChE,OAAO,SAAS4D,2BAA2B5D,GAAW;IACpD,OAAOU,2BAA2BV;AACpC;AAEA,0CAA0C,GAC1C,OAAO,SAAS6D;IACd,OAAOvE;AACT;AAEA;;;CAGC,GACD,OAAO,SAASwE;IACd3F,cAAc4F,KAAK;IACnBpF;AACF"}
@@ -0,0 +1,52 @@
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
+ /** One collection under `orgs/{orgId}` whose documents can be all-except. */
18
+ export interface ScopeSharingCollection {
19
+ /** The subcollection, spelled as Firestore holds it. */
20
+ name: string;
21
+ /** Stored fields follow `visibleTo`: a patch function is registered. */
22
+ patch?: boolean;
23
+ /** The most sites one document may reach; past it the list stops widening. */
24
+ maxIncluded?: number;
25
+ /** Fields naming sites that stay included though they are excluded. */
26
+ keepSiteFields?: string[];
27
+ }
28
+ /** A declaration with its owner; `core` for what the platform holds itself. */
29
+ export type ResolvedScopeSharingCollection = ScopeSharingCollection & {
30
+ pluginId: string;
31
+ };
32
+ /**
33
+ * Every collection the sweep walks, in a stable order: a sweep's cursor names
34
+ * a position in this list, and resuming relies on the ones before it being done.
35
+ */
36
+ export declare function listScopeSharingCollections(): ResolvedScopeSharingCollection[];
37
+ /**
38
+ * Recomputes the fields a document derives from its scope: `next` is the whole
39
+ * document as it will be stored, and the answer is merged into the write.
40
+ */
41
+ export type ScopeSharingPatch = (collection: string, next: Record<string, unknown>) => Promise<Record<string, unknown>> | Record<string, unknown>;
42
+ /**
43
+ * Registers the patch for collections a plugin declared with `patch: true`.
44
+ * Refuses a collection another plugin declared, or one declared without it.
45
+ */
46
+ export declare function registerPluginScopeSharingPatch(collections: readonly string[], patch: ScopeSharingPatch, options?: {
47
+ pluginId?: string;
48
+ }): void;
49
+ /** The patch registered for a collection, or `null`. */
50
+ export declare function scopeSharingPatchFor(collection: string): ScopeSharingPatch | null;
51
+ /** Test seam: forget every patch. */
52
+ export declare function resetScopeSharingPatchesForTests(): void;
@@ -0,0 +1,10 @@
1
+ /**
2
+ * GENERATED FILE — do not edit. Regenerate with:
3
+ * node tools/scripts/generate-plugin-manifests.mjs
4
+ *
5
+ * The collections plugins keep documents shared with all sites except some
6
+ * (AGL-4047): each plugin's `scopeSharingCollections` block in
7
+ * plugins.config.json. Core's `plugin-scope-sharing.ts` reads them.
8
+ */
9
+ import type { ResolvedScopeSharingCollection } from './plugin-scope-sharing';
10
+ export declare const PLUGIN_SCOPE_SHARING_COLLECTIONS_DECLARED: readonly ResolvedScopeSharingCollection[];
@@ -0,0 +1,82 @@
1
+ /**
2
+ * GENERATED FILE — do not edit. Regenerate with:
3
+ * node tools/scripts/generate-plugin-manifests.mjs
4
+ *
5
+ * The collections plugins keep documents shared with all sites except some
6
+ * (AGL-4047): each plugin's `scopeSharingCollections` block in
7
+ * plugins.config.json. Core's `plugin-scope-sharing.ts` reads them.
8
+ */ export const PLUGIN_SCOPE_SHARING_COLLECTIONS_DECLARED = [
9
+ {
10
+ "pluginId": "crm",
11
+ "name": "contacts",
12
+ "patch": true,
13
+ "maxIncluded": 30,
14
+ "keepSiteFields": [
15
+ "hostId",
16
+ "capturedByHostIds"
17
+ ]
18
+ },
19
+ {
20
+ "pluginId": "crm",
21
+ "name": "leads",
22
+ "patch": true,
23
+ "maxIncluded": 30,
24
+ "keepSiteFields": [
25
+ "hostId",
26
+ "capturedByHostIds"
27
+ ]
28
+ },
29
+ {
30
+ "pluginId": "crm",
31
+ "name": "companies",
32
+ "patch": true,
33
+ "maxIncluded": 30,
34
+ "keepSiteFields": [
35
+ "hostId",
36
+ "capturedByHostIds"
37
+ ]
38
+ },
39
+ {
40
+ "pluginId": "crm",
41
+ "name": "deals",
42
+ "patch": true,
43
+ "maxIncluded": 30,
44
+ "keepSiteFields": [
45
+ "hostId",
46
+ "capturedByHostIds"
47
+ ]
48
+ },
49
+ {
50
+ "pluginId": "crm",
51
+ "name": "crmTasks",
52
+ "patch": true,
53
+ "maxIncluded": 30,
54
+ "keepSiteFields": [
55
+ "hostId",
56
+ "capturedByHostIds"
57
+ ]
58
+ },
59
+ {
60
+ "pluginId": "crm",
61
+ "name": "crmActivities",
62
+ "maxIncluded": 30,
63
+ "keepSiteFields": [
64
+ "hostId",
65
+ "capturedByHostIds"
66
+ ]
67
+ },
68
+ {
69
+ "pluginId": "data",
70
+ "name": "datasets"
71
+ },
72
+ {
73
+ "pluginId": "marketing",
74
+ "name": "emailCampaigns"
75
+ },
76
+ {
77
+ "pluginId": "workflows",
78
+ "name": "automations"
79
+ }
80
+ ];
81
+
82
+ //# sourceMappingURL=plugin-scope-sharing.generated.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../libs/aglyn/src/lib/plugin-manager/plugin-scope-sharing.generated.ts"],"sourcesContent":["/**\n * GENERATED FILE — do not edit. Regenerate with:\n * node tools/scripts/generate-plugin-manifests.mjs\n *\n * The collections plugins keep documents shared with all sites except some\n * (AGL-4047): each plugin's `scopeSharingCollections` block in\n * plugins.config.json. Core's `plugin-scope-sharing.ts` reads them.\n */\n\nimport type { ResolvedScopeSharingCollection } from './plugin-scope-sharing'\n\nexport const PLUGIN_SCOPE_SHARING_COLLECTIONS_DECLARED: readonly ResolvedScopeSharingCollection[] = [\n {\n \"pluginId\": \"crm\",\n \"name\": \"contacts\",\n \"patch\": true,\n \"maxIncluded\": 30,\n \"keepSiteFields\": [\n \"hostId\",\n \"capturedByHostIds\"\n ]\n },\n {\n \"pluginId\": \"crm\",\n \"name\": \"leads\",\n \"patch\": true,\n \"maxIncluded\": 30,\n \"keepSiteFields\": [\n \"hostId\",\n \"capturedByHostIds\"\n ]\n },\n {\n \"pluginId\": \"crm\",\n \"name\": \"companies\",\n \"patch\": true,\n \"maxIncluded\": 30,\n \"keepSiteFields\": [\n \"hostId\",\n \"capturedByHostIds\"\n ]\n },\n {\n \"pluginId\": \"crm\",\n \"name\": \"deals\",\n \"patch\": true,\n \"maxIncluded\": 30,\n \"keepSiteFields\": [\n \"hostId\",\n \"capturedByHostIds\"\n ]\n },\n {\n \"pluginId\": \"crm\",\n \"name\": \"crmTasks\",\n \"patch\": true,\n \"maxIncluded\": 30,\n \"keepSiteFields\": [\n \"hostId\",\n \"capturedByHostIds\"\n ]\n },\n {\n \"pluginId\": \"crm\",\n \"name\": \"crmActivities\",\n \"maxIncluded\": 30,\n \"keepSiteFields\": [\n \"hostId\",\n \"capturedByHostIds\"\n ]\n },\n {\n \"pluginId\": \"data\",\n \"name\": \"datasets\"\n },\n {\n \"pluginId\": \"marketing\",\n \"name\": \"emailCampaigns\"\n },\n {\n \"pluginId\": \"workflows\",\n \"name\": \"automations\"\n }\n]\n"],"names":["PLUGIN_SCOPE_SHARING_COLLECTIONS_DECLARED"],"mappings":"AAAA;;;;;;;CAOC,GAID,OAAO,MAAMA,4CAAuF;IAClG;QACE,YAAY;QACZ,QAAQ;QACR,SAAS;QACT,eAAe;QACf,kBAAkB;YAChB;YACA;SACD;IACH;IACA;QACE,YAAY;QACZ,QAAQ;QACR,SAAS;QACT,eAAe;QACf,kBAAkB;YAChB;YACA;SACD;IACH;IACA;QACE,YAAY;QACZ,QAAQ;QACR,SAAS;QACT,eAAe;QACf,kBAAkB;YAChB;YACA;SACD;IACH;IACA;QACE,YAAY;QACZ,QAAQ;QACR,SAAS;QACT,eAAe;QACf,kBAAkB;YAChB;YACA;SACD;IACH;IACA;QACE,YAAY;QACZ,QAAQ;QACR,SAAS;QACT,eAAe;QACf,kBAAkB;YAChB;YACA;SACD;IACH;IACA;QACE,YAAY;QACZ,QAAQ;QACR,eAAe;QACf,kBAAkB;YAChB;YACA;SACD;IACH;IACA;QACE,YAAY;QACZ,QAAQ;IACV;IACA;QACE,YAAY;QACZ,QAAQ;IACV;IACA;QACE,YAAY;QACZ,QAAQ;IACV;CACD,CAAA"}
@@ -0,0 +1,85 @@
1
+ import { _ as _extends } from "@swc/helpers/_/_extends";
2
+ var _globalScope_PATCHES_KEY;
3
+ /**
4
+ * @license
5
+ * Copyright 2026 Aglyn LLC
6
+ *
7
+ * Licensed under the Apache License, Version 2.0 (the "License");
8
+ * you may not use this file except in compliance with the License.
9
+ * You may obtain a copy of the License at
10
+ *
11
+ * http://www.apache.org/licenses/LICENSE-2.0
12
+ *
13
+ * Unless required by applicable law or agreed to in writing, software
14
+ * distributed under the License is distributed on an "AS IS" BASIS,
15
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ * See the License for the specific language governing permissions and
17
+ * limitations under the License.
18
+ */ /**
19
+ * WHICH COLLECTIONS HOLD DOCUMENTS SHARED WITH "ALL SITES EXCEPT…" (AGL-4047).
20
+ *
21
+ * Such a document names its included sites in `visibleTo`, so that list has
22
+ * to change when a site joins or leaves the workspace. One sweep does that for
23
+ * every collection (`scope-sharing-sweep.ts`), and it can only walk what it
24
+ * has been told about, so a plugin declares its collections in the
25
+ * `scopeSharingCollections` block of `plugins.config.json`, compiled like its
26
+ * other storage. Media belongs to the platform and is listed here.
27
+ *
28
+ * A collection whose documents store fields derived from `visibleTo` declares
29
+ * `patch: true` and registers the function that recomputes them. The sweep
30
+ * refuses to write such a collection while the function is missing, because a
31
+ * `visibleTo` written without them leaves a document its list cannot find.
32
+ */ import { getRegisteringPluginId } from "../app-utils/registering-plugin.js";
33
+ import { PLUGIN_SCOPE_SHARING_COLLECTIONS_DECLARED } from "./plugin-scope-sharing.generated.js";
34
+ /** The platform's own: media belongs to no plugin. */ const CORE_SCOPE_SHARING_COLLECTIONS = [
35
+ {
36
+ pluginId: 'core',
37
+ name: 'media'
38
+ },
39
+ {
40
+ pluginId: 'core',
41
+ name: 'mediaFolders'
42
+ }
43
+ ];
44
+ /**
45
+ * Every collection the sweep walks, in a stable order: a sweep's cursor names
46
+ * a position in this list, and resuming relies on the ones before it being done.
47
+ */ export function listScopeSharingCollections() {
48
+ return [
49
+ ...CORE_SCOPE_SHARING_COLLECTIONS,
50
+ ...PLUGIN_SCOPE_SHARING_COLLECTIONS_DECLARED
51
+ ].map((row)=>_extends({}, row));
52
+ }
53
+ /**
54
+ * One map per process, on `globalThis`, for the reason `plugin-site-resources`
55
+ * gives: the declarations register from `instrumentation.ts`, which Next
56
+ * compiles apart from the route that runs the sweep.
57
+ */ const PATCHES_KEY = Symbol.for('@aglyn/aglyn:plugin-scope-sharing-patches');
58
+ const globalScope = globalThis;
59
+ const patches = (_globalScope_PATCHES_KEY = globalScope[PATCHES_KEY]) != null ? _globalScope_PATCHES_KEY : globalScope[PATCHES_KEY] = new Map();
60
+ /**
61
+ * Registers the patch for collections a plugin declared with `patch: true`.
62
+ * Refuses a collection another plugin declared, or one declared without it.
63
+ */ export function registerPluginScopeSharingPatch(collections, patch, options) {
64
+ var _ref, _getRegisteringPluginId;
65
+ const pluginId = ((_ref = (_getRegisteringPluginId = getRegisteringPluginId()) != null ? _getRegisteringPluginId : options == null ? void 0 : options.pluginId) != null ? _ref : '').trim();
66
+ if (!pluginId) {
67
+ throw new Error('a scope-sharing patch was registered with no owner: pass { pluginId } ' + 'when registering outside a plugin register fn');
68
+ }
69
+ for (const name of collections){
70
+ const declared = PLUGIN_SCOPE_SHARING_COLLECTIONS_DECLARED.find((row)=>row.name === name);
71
+ if ((declared == null ? void 0 : declared.pluginId) !== pluginId || !declared.patch) {
72
+ throw new Error(`${pluginId} did not declare ${name} with patch: true in scopeSharingCollections`);
73
+ }
74
+ }
75
+ for (const name of collections)patches.set(name, patch);
76
+ }
77
+ /** The patch registered for a collection, or `null`. */ export function scopeSharingPatchFor(collection) {
78
+ var _patches_get;
79
+ return (_patches_get = patches.get(collection)) != null ? _patches_get : null;
80
+ }
81
+ /** Test seam: forget every patch. */ export function resetScopeSharingPatchesForTests() {
82
+ patches.clear();
83
+ }
84
+
85
+ //# sourceMappingURL=plugin-scope-sharing.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../libs/aglyn/src/lib/plugin-manager/plugin-scope-sharing.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 * WHICH COLLECTIONS HOLD DOCUMENTS SHARED WITH \"ALL SITES EXCEPT…\" (AGL-4047).\n *\n * Such a document names its included sites in `visibleTo`, so that list has\n * to change when a site joins or leaves the workspace. One sweep does that for\n * every collection (`scope-sharing-sweep.ts`), and it can only walk what it\n * has been told about, so a plugin declares its collections in the\n * `scopeSharingCollections` block of `plugins.config.json`, compiled like its\n * other storage. Media belongs to the platform and is listed here.\n *\n * A collection whose documents store fields derived from `visibleTo` declares\n * `patch: true` and registers the function that recomputes them. The sweep\n * refuses to write such a collection while the function is missing, because a\n * `visibleTo` written without them leaves a document its list cannot find.\n */\n\nimport { getRegisteringPluginId } from '../app-utils/registering-plugin'\nimport { PLUGIN_SCOPE_SHARING_COLLECTIONS_DECLARED } from './plugin-scope-sharing.generated'\n\n/** One collection under `orgs/{orgId}` whose documents can be all-except. */\nexport interface ScopeSharingCollection {\n /** The subcollection, spelled as Firestore holds it. */\n name: string\n /** Stored fields follow `visibleTo`: a patch function is registered. */\n patch?: boolean\n /** The most sites one document may reach; past it the list stops widening. */\n maxIncluded?: number\n /** Fields naming sites that stay included though they are excluded. */\n keepSiteFields?: string[]\n}\n\n/** A declaration with its owner; `core` for what the platform holds itself. */\nexport type ResolvedScopeSharingCollection = ScopeSharingCollection & {\n pluginId: string\n}\n\n/** The platform's own: media belongs to no plugin. */\nconst CORE_SCOPE_SHARING_COLLECTIONS: readonly ResolvedScopeSharingCollection[] = [\n { pluginId: 'core', name: 'media' },\n { pluginId: 'core', name: 'mediaFolders' },\n]\n\n/**\n * Every collection the sweep walks, in a stable order: a sweep's cursor names\n * a position in this list, and resuming relies on the ones before it being done.\n */\nexport function listScopeSharingCollections(): ResolvedScopeSharingCollection[] {\n return [\n ...CORE_SCOPE_SHARING_COLLECTIONS,\n ...PLUGIN_SCOPE_SHARING_COLLECTIONS_DECLARED,\n ].map((row) => ({ ...row }))\n}\n\n/**\n * Recomputes the fields a document derives from its scope: `next` is the whole\n * document as it will be stored, and the answer is merged into the write.\n */\nexport type ScopeSharingPatch = (\n collection: string,\n next: Record<string, unknown>,\n) => Promise<Record<string, unknown>> | Record<string, unknown>\n\n/**\n * One map per process, on `globalThis`, for the reason `plugin-site-resources`\n * gives: the declarations register from `instrumentation.ts`, which Next\n * compiles apart from the route that runs the sweep.\n */\nconst PATCHES_KEY = Symbol.for('@aglyn/aglyn:plugin-scope-sharing-patches')\n\nconst globalScope = globalThis as typeof globalThis & {\n [PATCHES_KEY]?: Map<string, ScopeSharingPatch>\n}\n\nconst patches: Map<string, ScopeSharingPatch> =\n globalScope[PATCHES_KEY] ?? (globalScope[PATCHES_KEY] = new Map())\n\n/**\n * Registers the patch for collections a plugin declared with `patch: true`.\n * Refuses a collection another plugin declared, or one declared without it.\n */\nexport function registerPluginScopeSharingPatch(\n collections: readonly string[],\n patch: ScopeSharingPatch,\n options?: { pluginId?: string },\n): void {\n const pluginId = (getRegisteringPluginId() ?? options?.pluginId ?? '').trim()\n if (!pluginId) {\n throw new Error(\n 'a scope-sharing patch was registered with no owner: pass { pluginId } ' +\n 'when registering outside a plugin register fn',\n )\n }\n for (const name of collections) {\n const declared = PLUGIN_SCOPE_SHARING_COLLECTIONS_DECLARED.find((row) => row.name === name)\n if (declared?.pluginId !== pluginId || !declared.patch) {\n throw new Error(`${pluginId} did not declare ${name} with patch: true in scopeSharingCollections`)\n }\n }\n for (const name of collections) patches.set(name, patch)\n}\n\n/** The patch registered for a collection, or `null`. */\nexport function scopeSharingPatchFor(collection: string): ScopeSharingPatch | null {\n return patches.get(collection) ?? null\n}\n\n/** Test seam: forget every patch. */\nexport function resetScopeSharingPatchesForTests(): void {\n patches.clear()\n}\n"],"names":["globalScope","getRegisteringPluginId","PLUGIN_SCOPE_SHARING_COLLECTIONS_DECLARED","CORE_SCOPE_SHARING_COLLECTIONS","pluginId","name","listScopeSharingCollections","map","row","PATCHES_KEY","Symbol","for","globalThis","patches","Map","registerPluginScopeSharingPatch","collections","patch","options","trim","Error","declared","find","set","scopeSharingPatchFor","collection","get","resetScopeSharingPatchesForTests","clear"],"mappings":";IA2FEA;AA3FF;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;CAcC,GAED,SAASC,sBAAsB,QAAQ,qCAAiC;AACxE,SAASC,yCAAyC,QAAQ,sCAAkC;AAmB5F,oDAAoD,GACpD,MAAMC,iCAA4E;IAChF;QAAEC,UAAU;QAAQC,MAAM;IAAQ;IAClC;QAAED,UAAU;QAAQC,MAAM;IAAe;CAC1C;AAED;;;CAGC,GACD,OAAO,SAASC;IACd,OAAO;WACFH;WACAD;KACJ,CAACK,GAAG,CAAC,CAACC,MAAS,aAAKA;AACvB;AAWA;;;;CAIC,GACD,MAAMC,cAAcC,OAAOC,GAAG,CAAC;AAE/B,MAAMX,cAAcY;AAIpB,MAAMC,WACJb,2BAAAA,WAAW,CAACS,YAAY,YAAxBT,2BAA6BA,WAAW,CAACS,YAAY,GAAG,IAAIK;AAE9D;;;CAGC,GACD,OAAO,SAASC,gCACdC,WAA8B,EAC9BC,KAAwB,EACxBC,OAA+B;QAEbjB,MAAAA;IAAlB,MAAMG,WAAW,EAACH,QAAAA,0BAAAA,oCAAAA,0BAA4BiB,2BAAAA,QAASd,QAAQ,YAA7CH,OAAiD,IAAIkB,IAAI;IAC3E,IAAI,CAACf,UAAU;QACb,MAAM,IAAIgB,MACR,2EACE;IAEN;IACA,KAAK,MAAMf,QAAQW,YAAa;QAC9B,MAAMK,WAAWnB,0CAA0CoB,IAAI,CAAC,CAACd,MAAQA,IAAIH,IAAI,KAAKA;QACtF,IAAIgB,CAAAA,4BAAAA,SAAUjB,QAAQ,MAAKA,YAAY,CAACiB,SAASJ,KAAK,EAAE;YACtD,MAAM,IAAIG,MAAM,GAAGhB,SAAS,iBAAiB,EAAEC,KAAK,4CAA4C,CAAC;QACnG;IACF;IACA,KAAK,MAAMA,QAAQW,YAAaH,QAAQU,GAAG,C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