@aglyn/aglyn 1.23.1 → 1.25.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 (69) hide show
  1. package/package.json +11 -11
  2. package/src/lib/app-utils/activity-labels.js +4 -1
  3. package/src/lib/app-utils/activity-labels.js.map +1 -1
  4. package/src/lib/app-utils/activity-presenter.d.ts +11 -0
  5. package/src/lib/app-utils/activity-presenter.js +9 -0
  6. package/src/lib/app-utils/activity-presenter.js.map +1 -1
  7. package/src/lib/app-utils/activity-search.d.ts +1 -0
  8. package/src/lib/app-utils/activity-search.js +1 -0
  9. package/src/lib/app-utils/activity-search.js.map +1 -1
  10. package/src/lib/app-utils/agent-api-catalog.d.ts +18 -0
  11. package/src/lib/app-utils/agent-api-catalog.js +8 -1
  12. package/src/lib/app-utils/agent-api-catalog.js.map +1 -1
  13. package/src/lib/app-utils/binding-token-catalog.d.ts +15 -0
  14. package/src/lib/app-utils/binding-token-catalog.js +16 -0
  15. package/src/lib/app-utils/binding-token-catalog.js.map +1 -1
  16. package/src/lib/app-utils/business-details.d.ts +5 -0
  17. package/src/lib/app-utils/business-details.js +4 -0
  18. package/src/lib/app-utils/business-details.js.map +1 -1
  19. package/src/lib/app-utils/connector-discovery.d.ts +80 -0
  20. package/src/lib/app-utils/connector-discovery.js +107 -0
  21. package/src/lib/app-utils/connector-discovery.js.map +1 -0
  22. package/src/lib/app-utils/crm.d.ts +17 -30
  23. package/src/lib/app-utils/crm.js +139 -3
  24. package/src/lib/app-utils/crm.js.map +1 -1
  25. package/src/lib/app-utils/docs-help-sections.generated.js +5 -1
  26. package/src/lib/app-utils/docs-help-sections.generated.js.map +1 -1
  27. package/src/lib/app-utils/docs-help.generated.d.ts +5 -5
  28. package/src/lib/app-utils/docs-help.generated.js +12 -3
  29. package/src/lib/app-utils/docs-help.generated.js.map +1 -1
  30. package/src/lib/app-utils/docs-index.generated.js +149 -9
  31. package/src/lib/app-utils/docs-index.generated.js.map +1 -1
  32. package/src/lib/app-utils/entity-picker-context.d.ts +6 -0
  33. package/src/lib/app-utils/entity-picker-context.js.map +1 -1
  34. package/src/lib/app-utils/expand-repeatables.js +25 -2
  35. package/src/lib/app-utils/expand-repeatables.js.map +1 -1
  36. package/src/lib/app-utils/host-tokens.d.ts +17 -0
  37. package/src/lib/app-utils/host-tokens.js +18 -0
  38. package/src/lib/app-utils/host-tokens.js.map +1 -1
  39. package/src/lib/app-utils/native-app-association.d.ts +9 -5
  40. package/src/lib/app-utils/native-app-association.js +10 -5
  41. package/src/lib/app-utils/native-app-association.js.map +1 -1
  42. package/src/lib/app-utils/native-nav.js +1 -1
  43. package/src/lib/app-utils/native-nav.js.map +1 -1
  44. package/src/lib/app-utils/organizations.js +4 -2
  45. package/src/lib/app-utils/organizations.js.map +1 -1
  46. package/src/lib/app-utils/plan-entitlements.d.ts +227 -36
  47. package/src/lib/app-utils/plan-entitlements.js +335 -43
  48. package/src/lib/app-utils/plan-entitlements.js.map +1 -1
  49. package/src/lib/app-utils/plugin-release-flags.generated.js +2 -2
  50. package/src/lib/app-utils/plugin-release-flags.generated.js.map +1 -1
  51. package/src/lib/app-utils/reusable-component-keys.d.ts +9 -0
  52. package/src/lib/app-utils/reusable-component-keys.js +9 -0
  53. package/src/lib/app-utils/reusable-component-keys.js.map +1 -1
  54. package/src/lib/app-utils/server.d.ts +1 -0
  55. package/src/lib/app-utils/server.js +1 -0
  56. package/src/lib/app-utils/server.js.map +1 -1
  57. package/src/lib/app-utils/sign-in-visibility.d.ts +78 -0
  58. package/src/lib/app-utils/sign-in-visibility.js +79 -0
  59. package/src/lib/app-utils/sign-in-visibility.js.map +1 -0
  60. package/src/lib/app-utils/site-live-url.d.ts +4 -1
  61. package/src/lib/app-utils/site-live-url.js +17 -3
  62. package/src/lib/app-utils/site-live-url.js.map +1 -1
  63. package/src/lib/app-utils/usage-level.d.ts +50 -0
  64. package/src/lib/app-utils/usage-level.js +94 -0
  65. package/src/lib/app-utils/usage-level.js.map +1 -0
  66. package/src/lib/foundation/definitions/org-billing.types.d.ts +24 -2
  67. package/src/lib/foundation/definitions/org-billing.types.js.map +1 -1
  68. package/src/lib/plugin-manager/plugin-contact-capture.d.ts +2 -0
  69. package/src/lib/plugin-manager/plugin-contact-capture.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../libs/aglyn/src/lib/app-utils/organizations.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 * Organization helpers (AGL-233): slug policy for workspace subdomains\n * (`{slug}.aglyn.com`) and role math shared by the org APIs, the console\n * UI, and the Firestore rules' mental model. See\n * docs/MULTI_TENANT_FIRESTORE.md.\n */\n\nimport type {\n AglynOrgMember,\n AglynOrgOwnerHandoff,\n HostAccessRole,\n HostUid,\n OrgRole,\n OwnerHandoffPreviousOwner,\n ScopeToken,\n UserOrgMembership,\n} from '../foundation'\nimport {\n consoleLabelUnder,\n generateSubdomain,\n isBlockedSubdomain,\n SUBDOMAIN_PATTERN,\n} from './host-naming'\nimport {\n hostScopeToken,\n ORG_SCOPE_TOKEN,\n visibleToTokens,\n} from './scope-tokens'\n\n/** Same lexical policy as host subdomains: 3–30 lowercase/digits/dashes. */\nexport const ORG_SLUG_PATTERN = SUBDOMAIN_PATTERN\n\n/**\n * Org workspace slugs ride the host reserved/profanity blocklist plus\n * console-specific labels the workspace router must own. `kiosk` is the\n * console's public device route (AGL-3608), which a static segment serves\n * ahead of any workspace of that name.\n */\nconst RESERVED_ORG_ONLY = new Set(['staff', 'org', 'orgs', 'workspace', 'kiosk'])\n\n/**\n * The label this deployment serves its own console on, when it has one\n * (AGL-3295).\n *\n * `app` and `console` are reserved above for every install. One whose console\n * lives at, say, `studio.example.com` needs `studio` refused as well, or an\n * organization could claim a workspace address the console itself answers.\n * Read from the same two settings the console's host gate reads; with either\n * unset nothing extra is reserved, because nothing extra is shadowed.\n */\nconst CONSOLE_LABEL = consoleLabelUnder(\n process.env.NEXT_PUBLIC_CONSOLE_URL,\n process.env.NEXT_PUBLIC_WORKSPACE_DOMAIN,\n)\n\nexport function isBlockedOrgSlug(slug: string): boolean {\n const normalized = slug.toLowerCase()\n return (\n RESERVED_ORG_ONLY.has(normalized) ||\n normalized === CONSOLE_LABEL ||\n isBlockedSubdomain(slug)\n )\n}\n\nexport function isValidOrgSlug(slug: string): boolean {\n return ORG_SLUG_PATTERN.test(slug) && !isBlockedOrgSlug(slug)\n}\n\n/** Best-effort slug from an org name; '' when nothing usable remains. */\nexport function generateOrgSlug(name: string): string {\n const slug = generateSubdomain(name)\n return slug && !isBlockedOrgSlug(slug) ? slug : ''\n}\n\nexport const ORG_ROLES: readonly OrgRole[] = [\n 'owner',\n 'admin',\n 'editor',\n 'viewer',\n]\n\nconst ORG_ROLE_WEIGHT: Record<OrgRole, number> = {\n owner: 3,\n admin: 2,\n editor: 1,\n viewer: 0,\n}\n\nexport function isOrgRole(value: unknown): value is OrgRole {\n return typeof value === 'string' && value in ORG_ROLE_WEIGHT\n}\n\nexport function orgRoleAtLeast(\n role: OrgRole | null | undefined,\n minimum: OrgRole,\n): boolean {\n if (!role || !(role in ORG_ROLE_WEIGHT)) return false\n return ORG_ROLE_WEIGHT[role] >= ORG_ROLE_WEIGHT[minimum]\n}\n\n/** Org settings, members, invites, host creation: admin and owner. */\nexport function canManageOrg(role: OrgRole | null | undefined): boolean {\n return orgRoleAtLeast(role, 'admin')\n}\n\n/**\n * The member's effective role on one host, or null for no access.\n * Owner/admin span every host; editor/viewer resolve through `allHosts`\n * (mapped to their org role) or the per-host access map.\n */\nexport function hostRoleFor(\n member: Partial<AglynOrgMember> | null | undefined,\n hostId: HostUid,\n): HostAccessRole | null {\n const role = member?.role\n if (!isOrgRole(role)) return null\n if (role === 'owner' || role === 'admin') return 'admin'\n const explicit = member?.hostAccess?.[hostId]\n if (explicit) return explicit\n return member?.allHosts ? role : null\n}\n\n/**\n * Host roles that may MUTATE content — the axis `canWriteHostContent()` in\n * the security rules asks (AGL-2334).\n *\n * `author` is here and absent from `HOST_PUBLISH_ROLES` below: that single\n * difference IS the \"edit content but not publish\" role. Kept as two named\n * sets rather than two inline comparisons because they are read in three\n * places that must not drift — this module, the ~20 server gates, and the\n * rules — and because a new host role added to the union has to be a\n * deliberate decision on BOTH lists rather than an omission from one.\n */\nexport const HOST_CONTENT_WRITE_ROLES: readonly HostAccessRole[] = [\n 'admin',\n 'editor',\n 'author',\n]\n\n/**\n * Host roles that may make content LIVE. Everything that registers a route,\n * moves a live-version pointer, schedules either of those for later, or\n * flips a collection entry to `published` asks this and not the set above.\n *\n * The list is short and it is the whole product decision: `author` is not on\n * it. If a role is ever added here, the rules' `canPublishHostContent()` and\n * the publish-surface field freezes below it must be updated in the same\n * change — they are the enforcement, this is the server-side echo of it.\n */\nexport const HOST_PUBLISH_ROLES: readonly HostAccessRole[] = ['admin', 'editor']\n\n/**\n * Whether the member may mutate a host's content — admin, editor **or\n * author** on it.\n *\n * An author is a content editor in every respect this predicate covers; what\n * it deliberately does NOT cover is publication. Any caller that is really\n * asking \"may this person make something live\" must call `canPublishHost`\n * instead — this one answering `true` for an author is the point of the role,\n * not a gap in it.\n */\nexport function canWriteHost(\n member: Partial<AglynOrgMember> | null | undefined,\n hostId: HostUid,\n): boolean {\n const role = hostRoleFor(member, hostId)\n return !!role && HOST_CONTENT_WRITE_ROLES.includes(role)\n}\n\n/**\n * Whether the member may PUBLISH on a host — register a route, move a live\n * version pointer, schedule either for later, or publish a collection entry.\n *\n * Strictly narrower than `canWriteHost`: `author` edits and does not publish.\n * This is the server-side echo of the rules, not the enforcement — publishing\n * is a set of client-direct Firestore writes across five document shapes, so\n * `cloud/firebase-firestore.rules` is where it is actually refused. Server\n * routes that schedule or trigger a publish ask this so the console can say\n * no with a message instead of surfacing a bare permission-denied.\n */\nexport function canPublishHost(\n member: Partial<AglynOrgMember> | null | undefined,\n hostId: HostUid,\n): boolean {\n const role = hostRoleFor(member, hostId)\n return !!role && HOST_PUBLISH_ROLES.includes(role)\n}\n\n/**\n * The same question asked of a bare `memberRoles` value rather than a member\n * document — the shape every Admin-SDK route already has in hand after its\n * `hosts/{hostId}` read, so it does not have to re-load the org membership.\n *\n * `String(role)` at the call sites keeps `undefined` out; an unknown value\n * is simply not in the set, which fails CLOSED.\n */\nexport function hostRoleCanWrite(role: unknown): boolean {\n return HOST_CONTENT_WRITE_ROLES.includes(role as HostAccessRole)\n}\n\n/** Publish-axis twin of `hostRoleCanWrite`; `author` is excluded. */\nexport function hostRoleCanPublish(role: unknown): boolean {\n return HOST_PUBLISH_ROLES.includes(role as HostAccessRole)\n}\n\n/**\n * Whether a member's reach is the whole org rather than a list of sites.\n *\n * Owner and admin always are; editor/viewer are only when `allHosts` says\n * so — **or** when the membership predates the flag entirely. A pre-\n * `allHosts` doc carries neither the flag nor a `hostAccess` map, and\n * reading that as \"scoped, with access to nothing\" would lock real members\n * out of their own workspace. A site collaborator ALWAYS has a non-empty\n * `hostAccess` (that is what `grantHostAccess` writes), so the absence of\n * both is the legacy shape, not a scoped one.\n *\n * Single source of truth for `resolveOrgPermissions` (the server gate),\n * `projectMemberScopeTokens` (the rules projection), and the rules'\n * own `isOrgWideMember()` — three copies of this predicate that disagree\n * is a privilege bug, not a style problem (AGL-1026, AGL-1038).\n */\nexport function isOrgWideMember(\n member: Partial<AglynOrgMember> | null | undefined,\n): boolean {\n if (!member) return false\n const role = member.role\n if (role === 'owner' || role === 'admin') return true\n if (member.allHosts === true) return true\n const scoping = member.hostAccess\n return (\n member.allHosts === undefined && !Object.keys(scoping ?? {}).length\n )\n}\n\n/**\n * How many of these roster entries consume a **manager** seat (AGL-1113).\n *\n * `orgs/{orgId}/members` holds BOTH org managers and site-scoped\n * collaborators — adding a collaborator to one site writes an org member doc\n * with `allHosts:false` + `hostAccess`, so a raw `.count()` of the collection\n * billed every collaborator as a manager. Collaborators are metered\n * separately, per host, against `membersPerHost` at\n * `hosts/{hostId}/members` — counting them here charged them twice and\n * tripped the manager gate for orgs nowhere near their manager limit.\n *\n * Reuses `isOrgWideMember` rather than filtering on `allHosts` directly:\n * owner/admin are managers whatever the flag says, and a pre-`allHosts` doc\n * is a manager too. A Firestore `where('allHosts','==',true)` count gets both\n * of those wrong, which is why callers pass entries in and count here.\n *\n * Accepts pending INVITES as well as members — an invite carries the same\n * `role`/`allHosts`/`hostAccess` shape and reserves the seat it will become.\n */\nexport function countManagerSeats(\n entries: ReadonlyArray<\n | (Partial<AglynOrgMember> & { handoff?: unknown })\n | null\n | undefined\n >,\n): number {\n let count = 0\n for (const entry of entries) {\n if (usesCustomerSeat(entry) && isOrgWideMember(entry)) count += 1\n }\n return count\n}\n\n/**\n * Whether a roster row or pending invite takes one of the customer's seats\n * at all (AGL-3466). Every seat counter asks this before it asks which kind\n * of seat, so the two populations below never include either exception.\n *\n * Two kinds of entry hold access without a seat:\n *\n * - **Platform staff.** A row or invite stamped `staffSeat: true` belongs to\n * an account holding the `staff` claim. Staff build workspaces for\n * prospects and join them to help; billing the customer a seat for either\n * is what made a Free workspace (one seat) unable to invite the client it\n * was built for without a hand-written override.\n * - **An owner handoff.** An invite carrying `handoff` moves the owner seat\n * from one person to another rather than adding one. Whether the outgoing\n * owner staying on needs a seat of their own is decided when the handoff is\n * sent and again when it is accepted, never by counting the invite.\n */\nexport function usesCustomerSeat(\n entry:\n | { staffSeat?: unknown; handoff?: unknown }\n | null\n | undefined,\n): boolean {\n if (!entry) return false\n if (entry.staffSeat === true) return false\n return !entry.handoff\n}\n\n/**\n * Whether a roster row belongs to platform staff (AGL-3466) — the Team\n * page's \"no seat\" chip, and the row every seat count leaves out.\n */\nexport function isStaffSeat(\n entry: { staffSeat?: unknown } | null | undefined,\n): boolean {\n return entry?.staffSeat === true\n}\n\n/** The outgoing owner's choices, in the order the picker offers them. */\nexport const OWNER_HANDOFF_PREVIOUS_OWNER: readonly OwnerHandoffPreviousOwner[] = [\n 'stay',\n 'leave',\n]\n\n/** What each choice does, for the picker and the confirmation. */\nexport const OWNER_HANDOFF_PREVIOUS_OWNER_LABELS: Record<\n OwnerHandoffPreviousOwner,\n string\n> = {\n stay: 'Stay on as an admin after the handoff',\n leave: 'Leave after the handoff',\n}\n\n/**\n * The handoff half of an invite request, or null when it is not a usable\n * one (AGL-3466).\n *\n * Read in one place because the same body reaches the server from three\n * surfaces (the Team page, the staff organization page and the staff site\n * page), and an unknown `previousOwner` must be refused rather than guessed:\n * guessing `leave` takes someone off a roster they meant to stay on, and\n * guessing `stay` spends a seat they meant to free.\n */\nexport function parseOwnerHandoff(raw: unknown): AglynOrgOwnerHandoff | null {\n if (!raw || typeof raw !== 'object') return null\n const previousOwner = (raw as { previousOwner?: unknown }).previousOwner\n return previousOwner === 'stay' || previousOwner === 'leave'\n ? { previousOwner }\n : null\n}\n\n/**\n * One roster row or pending invite, as the collaborator counter needs to see\n * it (AGL-2068). Deliberately structural rather than `Partial<AglynOrgMember>`\n * — an INVITE is not a member document, it is keyed by email and has no uid,\n * and the whole point of this counter is that the two populations must be\n * counted together or the cap is enforced against a fraction of itself.\n */\nexport interface CollaboratorSeatEntry {\n /** Member documents are keyed by uid; invites have none. */\n uid?: string | null\n email?: string | null\n role?: unknown\n allHosts?: boolean\n hostAccess?: Record<string, unknown> | null\n /** Platform staff hold no seat (AGL-3466) — see `usesCustomerSeat`. */\n staffSeat?: boolean | null\n /** An owner-handoff invite holds no seat (AGL-3466). */\n handoff?: unknown\n}\n\n/**\n * The identity key one entry occupies, or `''` when it identifies nobody.\n *\n * EMAIL FIRST, uid second, and that order is the join (AGL-2068). A person\n * admitted to a site is one seat whether they arrive as an accepted member or\n * as a still-pending invite, and those two rows live in different collections\n * keyed different ways — `orgs/{id}/members/{uid}` and\n * `orgs/{id}/invites/{inviteId}` — with the address as the only field both\n * carry. Counting by uid would count the invite and the membership it becomes\n * as two seats; counting only invites would miss every member.\n *\n * Legacy roster rows written before `email` was mirrored fall back to the uid,\n * which cannot collide with an address (the `uid:` prefix is not a legal\n * local-part/domain pair) and so is safe to mix into the same set.\n */\nfunction collaboratorSeatKey(entry: CollaboratorSeatEntry): string {\n const email =\n typeof entry.email === 'string' ? entry.email.trim().toLowerCase() : ''\n if (email) return email\n const uid = typeof entry.uid === 'string' ? entry.uid.trim() : ''\n return uid ? `uid:${uid}` : ''\n}\n\n/**\n * Every principal consuming a COLLABORATOR seat on one host (AGL-2068).\n *\n * ## Why this exists at all\n *\n * `membersPerHost` was enforced on one of the four doors that admit a site\n * collaborator, and that one door counted `hosts/{hostId}/members` — a\n * DISPLAY roster only `/api/hosts/members` writes. The other three\n * (`/api/orgs/invites` create, `/api/orgs/invites` accept, and the\n * `hostAccess` branch of `/api/orgs/members`) land in `orgs/{id}/members` and\n * the `hosts/{id}.memberRoles` projection, and were invisible to it. So the\n * cap was both skipped on three paths and under-counted on the fourth, and a\n * free org — `membersPerHost: 1` — could take on unlimited collaborators,\n * each with full site access, on a plan that is never invoiced.\n *\n * verbatim: **\"We need to make sure the free/hobby tier\n * does hard cap so it always actually stays free.\"**\n *\n * ## What counts\n *\n * A SCOPED grant on `hostId`, and nothing else. An org-wide member\n * (owner/admin, or `allHosts`) reaches every host but consumes a MANAGER\n * seat — `countManagerSeats` is that side, and charging them here would bill\n * one person twice and trip a cap they are not on. This is the same split\n * AGL-1113 drew; it is now drawn from one place instead of three.\n *\n * Pending invites count, for the reason the manager gate counts them: an\n * invite reserves the seat it will become, and a cap that only bites on\n * acceptance can be walked past by mailing out N invites first.\n */\nexport function collaboratorSeatKeys(\n entries: ReadonlyArray<CollaboratorSeatEntry | null | undefined>,\n hostId: string,\n): Set<string> {\n const keys = new Set<string>()\n if (!hostId) return keys\n for (const entry of entries) {\n if (!usesCustomerSeat(entry)) continue\n // Managers are the other counter's population, whatever host map they\n // happen to carry — a promoted collaborator keeps their old `hostAccess`.\n if (isOrgWideMember(entry as Partial<AglynOrgMember>)) continue\n if (!entry.hostAccess?.[hostId]) continue\n const key = collaboratorSeatKey(entry)\n if (key) keys.add(key)\n }\n return keys\n}\n\n/**\n * How many collaborator seats on `hostId` are spoken for by someone OTHER\n * than `exclude` (AGL-2068).\n *\n * `exclude` is the principal the caller is about to admit, and dropping them\n * is what makes this composable with `checkSeatQuota(…, used)`, whose\n * contract is \"usage BEFORE the resource being created\". Without it the\n * accept path refuses its own invite: at the moment acceptance is decided the\n * invitee holds a pending invite AND is about to hold a membership, so they\n * would be counted once or twice against a cap they are the subject of.\n *\n * Both identities are dropped, not whichever one is present. A person can be\n * on the roster under a uid with no mirrored email and hold an invite under\n * that address, and the seat is still one seat.\n *\n * ## `emails`, not `email` — an account holds several (AGL-2486)\n *\n * Since an invitation may be accepted at any CONFIRMED address on the account,\n * the pending invite the accepter is about to consume can be keyed by an\n * address that is not their primary. `exclude.email` alone is the primary, so\n * that invite survived the exclusion and the person was counted against a cap\n * they are the subject of — the exact double-count the paragraph above says\n * this function exists to prevent, re-opened by widening the accept match.\n *\n * It fails CLOSED (a spurious \"out of seats\" refusal, never a free seat), and\n * only for an org sitting exactly on its cap, which is why it survived review.\n *\n * `emails` takes every address PROVEN to belong to the principal being\n * admitted. Passing an address that is not theirs would hand out a free seat,\n * so callers must pass confirmed addresses for that uid and nothing else.\n */\nexport function countCollaboratorSeats(\n entries: ReadonlyArray<CollaboratorSeatEntry | null | undefined>,\n hostId: string,\n exclude?: {\n uid?: string | null\n email?: string | null\n /** Further addresses on the SAME account; see above. */\n emails?: readonly (string | null | undefined)[] | null\n },\n): number {\n const keys = collaboratorSeatKeys(entries, hostId)\n for (const candidate of [exclude?.email, ...(exclude?.emails ?? [])]) {\n const email = typeof candidate === 'string' ? candidate.trim().toLowerCase() : ''\n if (email) keys.delete(email)\n }\n const uid = typeof exclude?.uid === 'string' ? exclude.uid.trim() : ''\n if (uid) keys.delete(`uid:${uid}`)\n return keys.size\n}\n\n/**\n * Every principal consuming a MANAGER seat, as identities rather than rows.\n *\n * The org-wide half of `collaboratorSeatKeys`, drawn from the same entries and\n * split on the same predicate, so the two counters partition one roster\n * instead of overlapping on it.\n *\n * Deduplicating by identity is the difference from {@link countManagerSeats},\n * and it is what makes this composable with an `exclude`: a person holding a\n * pending invite AND the membership it became is one seat, and the row-wise\n * counter reports two because it is handed the two collections separately and\n * sums them.\n */\nexport function managerSeatKeys(\n entries: ReadonlyArray<CollaboratorSeatEntry | null | undefined>,\n): Set<string> {\n const keys = new Set<string>()\n for (const entry of entries) {\n if (!usesCustomerSeat(entry)) continue\n if (!isOrgWideMember(entry as Partial<AglynOrgMember>)) continue\n const key = collaboratorSeatKey(entry)\n if (key) keys.add(key)\n }\n return keys\n}\n\n/**\n * How many manager seats are spoken for by someone OTHER than `exclude`.\n *\n * The manager twin of {@link countCollaboratorSeats}, and it exists for the\n * same reason that one takes an `exclude`: `checkSeatQuota`'s contract is\n * \"usage BEFORE the resource being created\", and on the invite-accept path the\n * accepter holds a pending invite and is about to hold a membership at the\n * same instant. Counted plainly they are charged once or twice for a seat they\n * are the subject of, and an org on its last seat refuses its own invitation.\n *\n * Both identities are dropped, and `emails` carries the further addresses\n * proven to belong to that account — an invitation may be accepted at any\n * confirmed address, so the invite being consumed need not be keyed by the\n * primary one. Passing an address that is not theirs would hand out a free\n * seat, so callers must pass confirmed addresses for that uid and nothing\n * else.\n *\n * Kept SEPARATE from {@link countManagerSeats} rather than replacing it: that\n * one is row-wise and is what the billing and console surfaces count with, and\n * quietly making it identity-wise would change every one of those totals.\n */\nexport function countManagerSeatsExcluding(\n entries: ReadonlyArray<CollaboratorSeatEntry | null | undefined>,\n exclude?: {\n uid?: string | null\n email?: string | null\n /** Further addresses on the SAME account; see above. */\n emails?: readonly (string | null | undefined)[] | null\n },\n): number {\n const keys = managerSeatKeys(entries)\n for (const candidate of [exclude?.email, ...(exclude?.emails ?? [])]) {\n const email = typeof candidate === 'string' ? candidate.trim().toLowerCase() : ''\n if (email) keys.delete(email)\n }\n const uid = typeof exclude?.uid === 'string' ? exclude.uid.trim() : ''\n if (uid) keys.delete(`uid:${uid}`)\n return keys.size\n}\n\n/**\n * What KIND of user a console row represents (AGL-1114) — the distinction\n * that decides which seat they consume, and the one the Team table could not\n * express because a manager and a collaborator differ only by fields the\n * table never showed.\n *\n * Deliberately NOT the same axis as `role`. A `role: 'editor'` is a manager\n * when their reach is the whole org and a collaborator when it is two sites;\n * reading the role alone is the mistake that let a collaborator look like\n * team staff (see the org-leak and role-gate work).\n *\n * `siteMember` is the third kind and never appears in `orgs/{id}/members` at\n * all: it is an end-user account on a PUBLISHED site (`siteMembers`), not a\n * console user. It has no Firebase Auth record of any kind — a site member is\n * a Firestore document under `hosts/{hostId}/siteMembers` with its own scrypt\n * hash and its own session cookie — so no surface that lists AUTH accounts,\n * the staff user directory included, can contain one. The label is here so the\n * vocabulary is complete, for a surface that lists site accounts and needs a\n * word for them. Free and uncounted on every plan (AGL-889).\n */\nexport type ConsoleUserType = 'manager' | 'collaborator' | 'siteMember'\n\nexport const CONSOLE_USER_TYPE_LABELS: Record<ConsoleUserType, string> = {\n manager: 'Team manager',\n collaborator: 'Site collaborator',\n siteMember: 'Site member',\n}\n\n/** One line on what each kind is and what it costs — tooltip/legend copy. */\nexport const CONSOLE_USER_TYPE_HINTS: Record<ConsoleUserType, string> = {\n manager:\n 'Reaches the whole organization. Uses one of your team (manager) seats.',\n collaborator:\n 'Scoped to specific sites. Uses a collaborator seat on each site they ' +\n 'can reach, not a team seat.',\n siteMember:\n 'An end-user account on a published site, not a console user. Free and ' +\n 'unlimited on every plan.',\n}\n\n/**\n * Classify an `orgs/{orgId}/members` entry (or a pending invite, same shape).\n * Never returns `siteMember` — nothing in that collection is one; the value\n * exists for surfaces that list published-site accounts and must label them —\n * never for one that lists both, since the two populations do not share an\n * identity system.\n */\nexport function consoleUserType(\n member: Partial<AglynOrgMember> | null | undefined,\n): Exclude<ConsoleUserType, 'siteMember'> {\n return isOrgWideMember(member) ? 'manager' : 'collaborator'\n}\n\n/**\n * Whether an account is governed by enterprise SSO (AGL-1128) — it lives in\n * an org's GCIP tenant pool rather than the project pool, so its identity is\n * owned by the customer's IdP.\n *\n * `tenantId` is the whole signal: Firebase sets it on the user whenever the\n * account belongs to a tenant, and only SSO accounts do.\n */\nexport function isSsoGovernedAccount(\n user: { tenantId?: string | null } | null | undefined,\n): boolean {\n return Boolean(user?.tenantId)\n}\n\n/**\n * Whether the account may connect an additional consumer sign-in provider.\n *\n * **No, for any SSO-governed account.** The customer's IdP is the single gate\n * they bought: they revoke there, enforce MFA there, offboard there. A linked\n * personal Google account is a way in their IdP can never see or revoke —\n * exactly what SSO is purchased to prevent.\n *\n * Deliberately NOT gated on `sso.enforced`. That flag exists so we never\n * LOCK OUT an existing sign-in method; it is not a licence to hand out new\n * bypasses meanwhile. Nothing here removes a provider an account already has,\n * so this can never lock anyone out.\n *\n * This is the intent, not the boundary — the boundary is upstream, since a\n * GCIP tenant only accepts providers enabled on that tenant. Both matter: the\n * boundary is remote config that could drift, and a UI that offers a\n * security-regressing action is wrong even when the action would fail.\n */\nexport function canLinkSocialProvider(\n user: { tenantId?: string | null } | null | undefined,\n): boolean {\n return !isSsoGovernedAccount(user)\n}\n\n/**\n * The same question as `isOrgWideMember`, asked of the `users/{uid}/orgs`\n * reverse-index row instead of the member doc (AGL-1032).\n *\n * The console navigates from the index — it is what `useOrgScope` loads —\n * and the index carries a MIRROR of the predicate, not the inputs to it, so\n * this cannot recompute: `role: 'viewer'` on the index means \"viewer\",\n * whether the member reaches every site or one.\n *\n * Reads a missing flag as org-wide, for the same reason `isOrgWideMember`\n * reads a missing `allHosts` that way: rows written before the mirror\n * existed have no flag, and hiding the workspace from a real member is a\n * worse failure than showing org chrome to a collaborator whose reads the\n * rules refuse anyway. Owner/admin are org-wide by role regardless of the\n * mirror, so a stale row can never lock an admin out.\n *\n * Navigation only — never an access decision. AGL-1026 (rules) and the\n * Admin-SDK scope checks are the boundary.\n */\nexport function isOrgWideMembership(\n membership:\n | Pick<UserOrgMembership, 'role' | 'orgWide'>\n | null\n | undefined,\n): boolean {\n if (!membership) return true\n if (membership.role === 'owner' || membership.role === 'admin') return true\n return membership.orgWide !== false\n}\n\n/**\n * The `scopeTokens` projection stamped onto member docs (AGL-1038) so the\n * rules can intersect a caller's reach with a resource's `visibleTo` —\n * rules have no `.map()`, so `hostAccess`'s keys cannot be turned into\n * tokens at evaluation time and have to be denormalized here.\n *\n * Org-wide members get `['org']`; they own the org and read everything in\n * it, scoped or not (the rules short-circuit on them anyway). A scoped\n * collaborator gets `'org'` plus one token per granted host — `'org'`\n * because an org-WIDE resource stays readable by any member, which is\n * today's behavior and not something this project narrows.\n *\n * Not capped at `MAX_SCOPE_HOSTS`: the rules' `hasAny` has no 30-value\n * limit, only the client `array-contains-any` query does, so a member of\n * more than 30 sites is a listing problem for AGL-1044 to chunk, not a\n * reason to under-grant here.\n */\nexport function projectMemberScopeTokens(\n member: Partial<AglynOrgMember> | null | undefined,\n): ScopeToken[] {\n if (isOrgWideMember(member)) return [ORG_SCOPE_TOKEN]\n const hostIds = Object.keys(member?.hostAccess ?? {})\n return [ORG_SCOPE_TOKEN, ...hostIds.map(hostScopeToken)]\n}\n\n/**\n * A member's effective read set: the stored `scopeTokens` projection when it\n * is there, recomputed from the membership when it is not.\n *\n * The fallback is the security-relevant half and it was written out by hand\n * in four places (`use-scope-tokens`, `erase-scope`, the media sign route,\n * and by omission in `resolveMediaScope`, which only ever recomputed). Four\n * copies of \"what may this member see\" is the shape that eventually\n * disagrees, and a copy that reads `member.scopeTokens` WITHOUT the\n * `.length` guard silently grants nothing to a member the AGL-1040 backfill\n * has not reached — or, written the other way round, grants everything.\n *\n * Recomputing is the safe fallback rather than a convenience: it produces\n * exactly what `grantHostAccess` would have stamped, so an unstamped member\n * doc behaves as its `hostAccess` says, never as \"no access\" and never as\n * org-wide.\n */\nexport function memberScopeTokens(\n member: Partial<AglynOrgMember> | null | undefined,\n): ScopeToken[] {\n const stored = member?.scopeTokens\n return stored?.length ? stored : projectMemberScopeTokens(member)\n}\n\n/**\n * May this member see a resource carrying `visibleTo`? (AGL-1037/1038)\n *\n * The whole client-side/server-side authorization question in one place:\n * org-wide members read everything they own; everyone else needs their read\n * set to intersect the resource's scope. Absent/empty `visibleTo` is\n * org-wide by the same rule the Firestore rules use, so an unbackfilled\n * resource does not vanish.\n *\n * Every Admin-SDK path must call this (or `scopeAllows`, which wraps an\n * already-resolved scope) — the Admin SDK bypasses rules entirely, so this\n * IS the enforcement there, not a second opinion about it.\n *\n * NOT a membership check, and never a substitute for one: a `null` member\n * \"can see\" an org-wide resource here, because the question this answers is\n * \"is this resource in scope for that reach\", not \"is this person in the\n * org\". Resolve membership first and refuse the caller if there is none —\n * conflating the two is exactly how AGL-1026 exposed a whole org.\n */\nexport function memberCanSee(\n member: Partial<AglynOrgMember> | null | undefined,\n visibleTo: readonly string[] | null | undefined,\n): boolean {\n if (isOrgWideMember(member)) return true\n return visibleToTokens(visibleTo ?? undefined, memberScopeTokens(member))\n}\n\n/**\n * The `memberRoles` projection stamped onto host docs so Firestore rules\n * authorize host content with the single host-doc read they already do\n * (docs/MULTI_TENANT_FIRESTORE.md §5). Recomputed by the membership API\n * whenever a member changes; owner/admin appear on every host.\n */\nexport function projectHostMemberRoles(\n members: ReadonlyArray<Partial<AglynOrgMember> & { $id: string }>,\n hostId: HostUid,\n): Record<string, HostAccessRole> {\n const projection: Record<string, HostAccessRole> = {}\n for (const member of members) {\n const role = hostRoleFor(member, hostId)\n if (role) projection[member.$id] = role\n }\n return projection\n}\n"],"names":["consoleLabelUnder","generateSubdomain","isBlockedSubdomain","SUBDOMAIN_PATTERN","hostScopeToken","ORG_SCOPE_TOKEN","visibleToTokens","ORG_SLUG_PATTERN","RESERVED_ORG_ONLY","Set","CONSOLE_LABEL","process","env","NEXT_PUBLIC_CONSOLE_URL","NEXT_PUBLIC_WORKSPACE_DOMAIN","isBlockedOrgSlug","slug","normalized","toLowerCase","has","isValidOrgSlug","test","generateOrgSlug","name","ORG_ROLES","ORG_ROLE_WEIGHT","owner","admin","editor","viewer","isOrgRole","value","orgRoleAtLeast","role","minimum","canManageOrg","hostRoleFor","member","hostId","explicit","hostAccess","allHosts","HOST_CONTENT_WRITE_ROLES","HOST_PUBLISH_ROLES","canWriteHost","includes","canPublishHost","hostRoleCanWrite","hostRoleCanPublish","isOrgWideMember","scoping","undefined","Object","keys","length","countManagerSeats","entries","count","entry","usesCustomerSeat","staffSeat","handoff","isStaffSeat","OWNER_HANDOFF_PREVIOUS_OWNER","OWNER_HANDOFF_PREVIOUS_OWNER_LABELS","stay","leave","parseOwnerHandoff","raw","previousOwner","collaboratorSeatKey","email","trim","uid","collaboratorSeatKeys","key","add","countCollaboratorSeats","exclude","candidate","emails","delete","size","managerSeatKeys","countManagerSeatsExcluding","CONSOLE_USER_TYPE_LABELS","manager","collaborator","siteMember","CONSOLE_USER_TYPE_HINTS","consoleUserType","isSsoGovernedAccount","user","Boolean","tenantId","canLinkSocialProvider","isOrgWideMembership","membership","orgWide","projectMemberScopeTokens","hostIds","map","memberScopeTokens","stored","scopeTokens","memberCanSee","visibleTo","projectHostMemberRoles","members","projection","$id"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;CAKC,GAYD,SACEA,iBAAiB,EACjBC,iBAAiB,EACjBC,kBAAkB,EAClBC,iBAAiB,QACZ,mBAAe;AACtB,SACEC,cAAc,EACdC,eAAe,EACfC,eAAe,QACV,oBAAgB;AAEvB,0EAA0E,GAC1E,OAAO,MAAMC,mBAAmBJ,kBAAiB;AAEjD;;;;;CAKC,GACD,MAAMK,oBAAoB,IAAIC,IAAI;IAAC;IAAS;IAAO;IAAQ;IAAa;CAAQ;AAEhF;;;;;;;;;CASC,GACD,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OC,IAAI,SAAChB,0BAAAA,OAAQG,UAAU,mBAAI,CAAC;IACnD,OAAO;QAACnC;WAAoB+F,QAAQC,GAAG,CAACjG;KAAgB;AAC1D;AAEA;;;;;;;;;;;;;;;;CAgBC,GACD,OAAO,SAASkG,kBACdjE,MAAkD;IAElD,MAAMkE,SAASlE,0BAAAA,OAAQmE,WAAW;IAClC,OAAOD,CAAAA,0BAAAA,OAAQjD,MAAM,IAAGiD,SAASJ,yBAAyB9D;AAC5D;AAEA;;;;;;;;;;;;;;;;;;CAkBC,GACD,OAAO,SAASoE,aACdpE,MAAkD,EAClDqE,SAA+C;IAE/C,IAAIzD,gBAAgBZ,SAAS,OAAO;IACpC,OAAO/B,gBAAgBoG,oBAAAA,YAAavD,WAAWmD,kBAAkBjE;AACnE;AAEA;;;;;CAKC,GACD,OAAO,SAASsE,uBACdC,OAAiE,EACjEtE,MAAe;IAEf,MAAMuE,aAA6C,CAAC;IACpD,KAAK,MAAMxE,UAAUuE,QAAS;QAC5B,MAAM3E,OAAOG,YAAYC,QAAQC;QACjC,IAAIL,MAAM4E,UAAU,CAACxE,OAAOyE,GAAG,CAAC,GAAG7E;IACrC;IACA,OAAO4E;AACT"}
1
+ {"version":3,"sources":["../../../../../../libs/aglyn/src/lib/app-utils/organizations.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 * Organization helpers (AGL-233): slug policy for workspace subdomains\n * (`{slug}.aglyn.com`) and role math shared by the org APIs, the console\n * UI, and the Firestore rules' mental model. See\n * docs/MULTI_TENANT_FIRESTORE.md.\n */\n\nimport type {\n AglynOrgMember,\n AglynOrgOwnerHandoff,\n HostAccessRole,\n HostUid,\n OrgRole,\n OwnerHandoffPreviousOwner,\n ScopeToken,\n UserOrgMembership,\n} from '../foundation'\nimport {\n consoleLabelUnder,\n generateSubdomain,\n isBlockedSubdomain,\n SUBDOMAIN_PATTERN,\n} from './host-naming'\nimport {\n hostScopeToken,\n ORG_SCOPE_TOKEN,\n visibleToTokens,\n} from './scope-tokens'\n\n/** Same lexical policy as host subdomains: 3–30 lowercase/digits/dashes. */\nexport const ORG_SLUG_PATTERN = SUBDOMAIN_PATTERN\n\n/**\n * Org workspace slugs ride the host reserved/profanity blocklist plus\n * console-specific labels the workspace router must own. `kiosk` is the\n * console's public device route (AGL-3608), which a static segment serves\n * ahead of any workspace of that name; `oauth` is the connector consent page\n * (AGL-4225), the same way.\n */\nconst RESERVED_ORG_ONLY = new Set(['staff', 'org', 'orgs', 'workspace', 'kiosk', 'oauth'])\n\n/**\n * The label this deployment serves its own console on, when it has one\n * (AGL-3295).\n *\n * `app` and `console` are reserved above for every install. One whose console\n * lives at, say, `studio.example.com` needs `studio` refused as well, or an\n * organization could claim a workspace address the console itself answers.\n * Read from the same two settings the console's host gate reads; with either\n * unset nothing extra is reserved, because nothing extra is shadowed.\n */\nconst CONSOLE_LABEL = consoleLabelUnder(\n process.env.NEXT_PUBLIC_CONSOLE_URL,\n process.env.NEXT_PUBLIC_WORKSPACE_DOMAIN,\n)\n\nexport function isBlockedOrgSlug(slug: string): boolean {\n const normalized = slug.toLowerCase()\n return (\n RESERVED_ORG_ONLY.has(normalized) ||\n normalized === CONSOLE_LABEL ||\n isBlockedSubdomain(slug)\n )\n}\n\nexport function isValidOrgSlug(slug: string): boolean {\n return ORG_SLUG_PATTERN.test(slug) && !isBlockedOrgSlug(slug)\n}\n\n/** Best-effort slug from an org name; '' when nothing usable remains. */\nexport function generateOrgSlug(name: string): string {\n const slug = generateSubdomain(name)\n return slug && !isBlockedOrgSlug(slug) ? slug : ''\n}\n\nexport const ORG_ROLES: readonly OrgRole[] = [\n 'owner',\n 'admin',\n 'editor',\n 'viewer',\n]\n\nconst ORG_ROLE_WEIGHT: Record<OrgRole, number> = {\n owner: 3,\n admin: 2,\n editor: 1,\n viewer: 0,\n}\n\nexport function isOrgRole(value: unknown): value is OrgRole {\n return typeof value === 'string' && value in ORG_ROLE_WEIGHT\n}\n\nexport function orgRoleAtLeast(\n role: OrgRole | null | undefined,\n minimum: OrgRole,\n): boolean {\n if (!role || !(role in ORG_ROLE_WEIGHT)) return false\n return ORG_ROLE_WEIGHT[role] >= ORG_ROLE_WEIGHT[minimum]\n}\n\n/** Org settings, members, invites, host creation: admin and owner. */\nexport function canManageOrg(role: OrgRole | null | undefined): boolean {\n return orgRoleAtLeast(role, 'admin')\n}\n\n/**\n * The member's effective role on one host, or null for no access.\n * Owner/admin span every host; editor/viewer resolve through `allHosts`\n * (mapped to their org role) or the per-host access map.\n */\nexport function hostRoleFor(\n member: Partial<AglynOrgMember> | null | undefined,\n hostId: HostUid,\n): HostAccessRole | null {\n const role = member?.role\n if (!isOrgRole(role)) return null\n if (role === 'owner' || role === 'admin') return 'admin'\n const explicit = member?.hostAccess?.[hostId]\n if (explicit) return explicit\n return member?.allHosts ? role : null\n}\n\n/**\n * Host roles that may MUTATE content — the axis `canWriteHostContent()` in\n * the security rules asks (AGL-2334).\n *\n * `author` is here and absent from `HOST_PUBLISH_ROLES` below: that single\n * difference IS the \"edit content but not publish\" role. Kept as two named\n * sets rather than two inline comparisons because they are read in three\n * places that must not drift — this module, the ~20 server gates, and the\n * rules — and because a new host role added to the union has to be a\n * deliberate decision on BOTH lists rather than an omission from one.\n */\nexport const HOST_CONTENT_WRITE_ROLES: readonly HostAccessRole[] = [\n 'admin',\n 'editor',\n 'author',\n]\n\n/**\n * Host roles that may make content LIVE. Everything that registers a route,\n * moves a live-version pointer, schedules either of those for later, or\n * flips a collection entry to `published` asks this and not the set above.\n *\n * The list is short and it is the whole product decision: `author` is not on\n * it. If a role is ever added here, the rules' `canPublishHostContent()` and\n * the publish-surface field freezes below it must be updated in the same\n * change — they are the enforcement, this is the server-side echo of it.\n */\nexport const HOST_PUBLISH_ROLES: readonly HostAccessRole[] = ['admin', 'editor']\n\n/**\n * Whether the member may mutate a host's content — admin, editor **or\n * author** on it.\n *\n * An author is a content editor in every respect this predicate covers; what\n * it deliberately does NOT cover is publication. Any caller that is really\n * asking \"may this person make something live\" must call `canPublishHost`\n * instead — this one answering `true` for an author is the point of the role,\n * not a gap in it.\n */\nexport function canWriteHost(\n member: Partial<AglynOrgMember> | null | undefined,\n hostId: HostUid,\n): boolean {\n const role = hostRoleFor(member, hostId)\n return !!role && HOST_CONTENT_WRITE_ROLES.includes(role)\n}\n\n/**\n * Whether the member may PUBLISH on a host — register a route, move a live\n * version pointer, schedule either for later, or publish a collection entry.\n *\n * Strictly narrower than `canWriteHost`: `author` edits and does not publish.\n * This is the server-side echo of the rules, not the enforcement — publishing\n * is a set of client-direct Firestore writes across five document shapes, so\n * `cloud/firebase-firestore.rules` is where it is actually refused. Server\n * routes that schedule or trigger a publish ask this so the console can say\n * no with a message instead of surfacing a bare permission-denied.\n */\nexport function canPublishHost(\n member: Partial<AglynOrgMember> | null | undefined,\n hostId: HostUid,\n): boolean {\n const role = hostRoleFor(member, hostId)\n return !!role && HOST_PUBLISH_ROLES.includes(role)\n}\n\n/**\n * The same question asked of a bare `memberRoles` value rather than a member\n * document — the shape every Admin-SDK route already has in hand after its\n * `hosts/{hostId}` read, so it does not have to re-load the org membership.\n *\n * `String(role)` at the call sites keeps `undefined` out; an unknown value\n * is simply not in the set, which fails CLOSED.\n */\nexport function hostRoleCanWrite(role: unknown): boolean {\n return HOST_CONTENT_WRITE_ROLES.includes(role as HostAccessRole)\n}\n\n/** Publish-axis twin of `hostRoleCanWrite`; `author` is excluded. */\nexport function hostRoleCanPublish(role: unknown): boolean {\n return HOST_PUBLISH_ROLES.includes(role as HostAccessRole)\n}\n\n/**\n * Whether a member's reach is the whole org rather than a list of sites.\n *\n * Owner and admin always are; editor/viewer are only when `allHosts` says\n * so — **or** when the membership predates the flag entirely. A pre-\n * `allHosts` doc carries neither the flag nor a `hostAccess` map, and\n * reading that as \"scoped, with access to nothing\" would lock real members\n * out of their own workspace. A site collaborator ALWAYS has a non-empty\n * `hostAccess` (that is what `grantHostAccess` writes), so the absence of\n * both is the legacy shape, not a scoped one.\n *\n * Single source of truth for `resolveOrgPermissions` (the server gate),\n * `projectMemberScopeTokens` (the rules projection), and the rules'\n * own `isOrgWideMember()` — three copies of this predicate that disagree\n * is a privilege bug, not a style problem (AGL-1026, AGL-1038).\n */\nexport function isOrgWideMember(\n member: Partial<AglynOrgMember> | null | undefined,\n): boolean {\n if (!member) return false\n const role = member.role\n if (role === 'owner' || role === 'admin') return true\n if (member.allHosts === true) return true\n const scoping = member.hostAccess\n return (\n member.allHosts === undefined && !Object.keys(scoping ?? {}).length\n )\n}\n\n/**\n * How many of these roster entries consume a **manager** seat (AGL-1113).\n *\n * `orgs/{orgId}/members` holds BOTH org managers and site-scoped\n * collaborators — adding a collaborator to one site writes an org member doc\n * with `allHosts:false` + `hostAccess`, so a raw `.count()` of the collection\n * billed every collaborator as a manager. Collaborators are metered\n * separately, per host, against `membersPerHost` at\n * `hosts/{hostId}/members` — counting them here charged them twice and\n * tripped the manager gate for orgs nowhere near their manager limit.\n *\n * Reuses `isOrgWideMember` rather than filtering on `allHosts` directly:\n * owner/admin are managers whatever the flag says, and a pre-`allHosts` doc\n * is a manager too. A Firestore `where('allHosts','==',true)` count gets both\n * of those wrong, which is why callers pass entries in and count here.\n *\n * Accepts pending INVITES as well as members — an invite carries the same\n * `role`/`allHosts`/`hostAccess` shape and reserves the seat it will become.\n */\nexport function countManagerSeats(\n entries: ReadonlyArray<\n | (Partial<AglynOrgMember> & { handoff?: unknown })\n | null\n | undefined\n >,\n): number {\n let count = 0\n for (const entry of entries) {\n if (usesCustomerSeat(entry) && isOrgWideMember(entry)) count += 1\n }\n return count\n}\n\n/**\n * Whether a roster row or pending invite takes one of the customer's seats\n * at all (AGL-3466). Every seat counter asks this before it asks which kind\n * of seat, so the two populations below never include either exception.\n *\n * Two kinds of entry hold access without a seat:\n *\n * - **Platform staff.** A row or invite stamped `staffSeat: true` belongs to\n * an account holding the `staff` claim. Staff build workspaces for\n * prospects and join them to help; billing the customer a seat for either\n * is what made a Free workspace (one seat) unable to invite the client it\n * was built for without a hand-written override.\n * - **An owner handoff.** An invite carrying `handoff` moves the owner seat\n * from one person to another rather than adding one. Whether the outgoing\n * owner staying on needs a seat of their own is decided when the handoff is\n * sent and again when it is accepted, never by counting the invite.\n */\nexport function usesCustomerSeat(\n entry:\n | { staffSeat?: unknown; handoff?: unknown }\n | null\n | undefined,\n): boolean {\n if (!entry) return false\n if (entry.staffSeat === true) return false\n return !entry.handoff\n}\n\n/**\n * Whether a roster row belongs to platform staff (AGL-3466) — the Team\n * page's \"no seat\" chip, and the row every seat count leaves out.\n */\nexport function isStaffSeat(\n entry: { staffSeat?: unknown } | null | undefined,\n): boolean {\n return entry?.staffSeat === true\n}\n\n/** The outgoing owner's choices, in the order the picker offers them. */\nexport const OWNER_HANDOFF_PREVIOUS_OWNER: readonly OwnerHandoffPreviousOwner[] = [\n 'stay',\n 'leave',\n]\n\n/** What each choice does, for the picker and the confirmation. */\nexport const OWNER_HANDOFF_PREVIOUS_OWNER_LABELS: Record<\n OwnerHandoffPreviousOwner,\n string\n> = {\n stay: 'Stay on as an admin after the handoff',\n leave: 'Leave after the handoff',\n}\n\n/**\n * The handoff half of an invite request, or null when it is not a usable\n * one (AGL-3466).\n *\n * Read in one place because the same body reaches the server from three\n * surfaces (the Team page, the staff organization page and the staff site\n * page), and an unknown `previousOwner` must be refused rather than guessed:\n * guessing `leave` takes someone off a roster they meant to stay on, and\n * guessing `stay` spends a seat they meant to free.\n */\nexport function parseOwnerHandoff(raw: unknown): AglynOrgOwnerHandoff | null {\n if (!raw || typeof raw !== 'object') return null\n const previousOwner = (raw as { previousOwner?: unknown }).previousOwner\n return previousOwner === 'stay' || previousOwner === 'leave'\n ? { previousOwner }\n : null\n}\n\n/**\n * One roster row or pending invite, as the collaborator counter needs to see\n * it (AGL-2068). Deliberately structural rather than `Partial<AglynOrgMember>`\n * — an INVITE is not a member document, it is keyed by email and has no uid,\n * and the whole point of this counter is that the two populations must be\n * counted together or the cap is enforced against a fraction of itself.\n */\nexport interface CollaboratorSeatEntry {\n /** Member documents are keyed by uid; invites have none. */\n uid?: string | null\n email?: string | null\n role?: unknown\n allHosts?: boolean\n hostAccess?: Record<string, unknown> | null\n /** Platform staff hold no seat (AGL-3466) — see `usesCustomerSeat`. */\n staffSeat?: boolean | null\n /** An owner-handoff invite holds no seat (AGL-3466). */\n handoff?: unknown\n}\n\n/**\n * The identity key one entry occupies, or `''` when it identifies nobody.\n *\n * EMAIL FIRST, uid second, and that order is the join (AGL-2068). A person\n * admitted to a site is one seat whether they arrive as an accepted member or\n * as a still-pending invite, and those two rows live in different collections\n * keyed different ways — `orgs/{id}/members/{uid}` and\n * `orgs/{id}/invites/{inviteId}` — with the address as the only field both\n * carry. Counting by uid would count the invite and the membership it becomes\n * as two seats; counting only invites would miss every member.\n *\n * Legacy roster rows written before `email` was mirrored fall back to the uid,\n * which cannot collide with an address (the `uid:` prefix is not a legal\n * local-part/domain pair) and so is safe to mix into the same set.\n */\nfunction collaboratorSeatKey(entry: CollaboratorSeatEntry): string {\n const email =\n typeof entry.email === 'string' ? entry.email.trim().toLowerCase() : ''\n if (email) return email\n const uid = typeof entry.uid === 'string' ? entry.uid.trim() : ''\n return uid ? `uid:${uid}` : ''\n}\n\n/**\n * Every principal consuming a COLLABORATOR seat on one host (AGL-2068).\n *\n * ## Why this exists at all\n *\n * `membersPerHost` was enforced on one of the four doors that admit a site\n * collaborator, and that one door counted `hosts/{hostId}/members` — a\n * DISPLAY roster only `/api/hosts/members` writes. The other three\n * (`/api/orgs/invites` create, `/api/orgs/invites` accept, and the\n * `hostAccess` branch of `/api/orgs/members`) land in `orgs/{id}/members` and\n * the `hosts/{id}.memberRoles` projection, and were invisible to it. So the\n * cap was both skipped on three paths and under-counted on the fourth, and a\n * free org — `membersPerHost: 1` — could take on unlimited collaborators,\n * each with full site access, on a plan that is never invoiced.\n *\n * verbatim: **\"We need to make sure the free/hobby tier\n * does hard cap so it always actually stays free.\"**\n *\n * ## What counts\n *\n * A SCOPED grant on `hostId`, and nothing else. An org-wide member\n * (owner/admin, or `allHosts`) reaches every host but consumes a MANAGER\n * seat — `countManagerSeats` is that side, and charging them here would bill\n * one person twice and trip a cap they are not on. This is the same split\n * AGL-1113 drew; it is now drawn from one place instead of three.\n *\n * Pending invites count, for the reason the manager gate counts them: an\n * invite reserves the seat it will become, and a cap that only bites on\n * acceptance can be walked past by mailing out N invites first.\n */\nexport function collaboratorSeatKeys(\n entries: ReadonlyArray<CollaboratorSeatEntry | null | undefined>,\n hostId: string,\n): Set<string> {\n const keys = new Set<string>()\n if (!hostId) return keys\n for (const entry of entries) {\n if (!usesCustomerSeat(entry)) continue\n // Managers are the other counter's population, whatever host map they\n // happen to carry — a promoted collaborator keeps their old `hostAccess`.\n if (isOrgWideMember(entry as Partial<AglynOrgMember>)) continue\n if (!entry.hostAccess?.[hostId]) continue\n const key = collaboratorSeatKey(entry)\n if (key) keys.add(key)\n }\n return keys\n}\n\n/**\n * How many collaborator seats on `hostId` are spoken for by someone OTHER\n * than `exclude` (AGL-2068).\n *\n * `exclude` is the principal the caller is about to admit, and dropping them\n * is what makes this composable with `checkSeatQuota(…, used)`, whose\n * contract is \"usage BEFORE the resource being created\". Without it the\n * accept path refuses its own invite: at the moment acceptance is decided the\n * invitee holds a pending invite AND is about to hold a membership, so they\n * would be counted once or twice against a cap they are the subject of.\n *\n * Both identities are dropped, not whichever one is present. A person can be\n * on the roster under a uid with no mirrored email and hold an invite under\n * that address, and the seat is still one seat.\n *\n * ## `emails`, not `email` — an account holds several (AGL-2486)\n *\n * Since an invitation may be accepted at any CONFIRMED address on the account,\n * the pending invite the accepter is about to consume can be keyed by an\n * address that is not their primary. `exclude.email` alone is the primary, so\n * that invite survived the exclusion and the person was counted against a cap\n * they are the subject of — the exact double-count the paragraph above says\n * this function exists to prevent, re-opened by widening the accept match.\n *\n * It fails CLOSED (a spurious \"out of seats\" refusal, never a free seat), and\n * only for an org sitting exactly on its cap, which is why it survived review.\n *\n * `emails` takes every address PROVEN to belong to the principal being\n * admitted. Passing an address that is not theirs would hand out a free seat,\n * so callers must pass confirmed addresses for that uid and nothing else.\n */\nexport function countCollaboratorSeats(\n entries: ReadonlyArray<CollaboratorSeatEntry | null | undefined>,\n hostId: string,\n exclude?: {\n uid?: string | null\n email?: string | null\n /** Further addresses on the SAME account; see above. */\n emails?: readonly (string | null | undefined)[] | null\n },\n): number {\n const keys = collaboratorSeatKeys(entries, hostId)\n for (const candidate of [exclude?.email, ...(exclude?.emails ?? [])]) {\n const email = typeof candidate === 'string' ? candidate.trim().toLowerCase() : ''\n if (email) keys.delete(email)\n }\n const uid = typeof exclude?.uid === 'string' ? exclude.uid.trim() : ''\n if (uid) keys.delete(`uid:${uid}`)\n return keys.size\n}\n\n/**\n * Every principal consuming a MANAGER seat, as identities rather than rows.\n *\n * The org-wide half of `collaboratorSeatKeys`, drawn from the same entries and\n * split on the same predicate, so the two counters partition one roster\n * instead of overlapping on it.\n *\n * Deduplicating by identity is the difference from {@link countManagerSeats},\n * and it is what makes this composable with an `exclude`: a person holding a\n * pending invite AND the membership it became is one seat, and the row-wise\n * counter reports two because it is handed the two collections separately and\n * sums them.\n */\nexport function managerSeatKeys(\n entries: ReadonlyArray<CollaboratorSeatEntry | null | undefined>,\n): Set<string> {\n const keys = new Set<string>()\n for (const entry of entries) {\n if (!usesCustomerSeat(entry)) continue\n if (!isOrgWideMember(entry as Partial<AglynOrgMember>)) continue\n const key = collaboratorSeatKey(entry)\n if (key) keys.add(key)\n }\n return keys\n}\n\n/**\n * How many manager seats are spoken for by someone OTHER than `exclude`.\n *\n * The manager twin of {@link countCollaboratorSeats}, and it exists for the\n * same reason that one takes an `exclude`: `checkSeatQuota`'s contract is\n * \"usage BEFORE the resource being created\", and on the invite-accept path the\n * accepter holds a pending invite and is about to hold a membership at the\n * same instant. Counted plainly they are charged once or twice for a seat they\n * are the subject of, and an org on its last seat refuses its own invitation.\n *\n * Both identities are dropped, and `emails` carries the further addresses\n * proven to belong to that account — an invitation may be accepted at any\n * confirmed address, so the invite being consumed need not be keyed by the\n * primary one. Passing an address that is not theirs would hand out a free\n * seat, so callers must pass confirmed addresses for that uid and nothing\n * else.\n *\n * Kept SEPARATE from {@link countManagerSeats} rather than replacing it: that\n * one is row-wise and is what the billing and console surfaces count with, and\n * quietly making it identity-wise would change every one of those totals.\n */\nexport function countManagerSeatsExcluding(\n entries: ReadonlyArray<CollaboratorSeatEntry | null | undefined>,\n exclude?: {\n uid?: string | null\n email?: string | null\n /** Further addresses on the SAME account; see above. */\n emails?: readonly (string | null | undefined)[] | null\n },\n): number {\n const keys = managerSeatKeys(entries)\n for (const candidate of [exclude?.email, ...(exclude?.emails ?? [])]) {\n const email = typeof candidate === 'string' ? candidate.trim().toLowerCase() : ''\n if (email) keys.delete(email)\n }\n const uid = typeof exclude?.uid === 'string' ? exclude.uid.trim() : ''\n if (uid) keys.delete(`uid:${uid}`)\n return keys.size\n}\n\n/**\n * What KIND of user a console row represents (AGL-1114) — the distinction\n * that decides which seat they consume, and the one the Team table could not\n * express because a manager and a collaborator differ only by fields the\n * table never showed.\n *\n * Deliberately NOT the same axis as `role`. A `role: 'editor'` is a manager\n * when their reach is the whole org and a collaborator when it is two sites;\n * reading the role alone is the mistake that let a collaborator look like\n * team staff (see the org-leak and role-gate work).\n *\n * `siteMember` is the third kind and never appears in `orgs/{id}/members` at\n * all: it is an end-user account on a PUBLISHED site (`siteMembers`), not a\n * console user. It has no Firebase Auth record of any kind — a site member is\n * a Firestore document under `hosts/{hostId}/siteMembers` with its own scrypt\n * hash and its own session cookie — so no surface that lists AUTH accounts,\n * the staff user directory included, can contain one. The label is here so the\n * vocabulary is complete, for a surface that lists site accounts and needs a\n * word for them. Free and uncounted on every plan (AGL-889).\n */\nexport type ConsoleUserType = 'manager' | 'collaborator' | 'siteMember'\n\nexport const CONSOLE_USER_TYPE_LABELS: Record<ConsoleUserType, string> = {\n manager: 'Team manager',\n collaborator: 'Site collaborator',\n siteMember: 'Site member',\n}\n\n/** One line on what each kind is and what it costs — tooltip/legend copy. */\nexport const CONSOLE_USER_TYPE_HINTS: Record<ConsoleUserType, string> = {\n manager:\n 'Reaches the whole organization. Uses one of your team (manager) seats.',\n collaborator:\n 'Scoped to specific sites. Uses a collaborator seat on each site they ' +\n 'can reach, not a team seat.',\n siteMember:\n 'An end-user account on a published site, not a console user. Free and ' +\n 'unlimited on every plan.',\n}\n\n/**\n * Classify an `orgs/{orgId}/members` entry (or a pending invite, same shape).\n * Never returns `siteMember` — nothing in that collection is one; the value\n * exists for surfaces that list published-site accounts and must label them —\n * never for one that lists both, since the two populations do not share an\n * identity system.\n */\nexport function consoleUserType(\n member: Partial<AglynOrgMember> | null | undefined,\n): Exclude<ConsoleUserType, 'siteMember'> {\n return isOrgWideMember(member) ? 'manager' : 'collaborator'\n}\n\n/**\n * Whether an account is governed by enterprise SSO (AGL-1128) — it lives in\n * an org's GCIP tenant pool rather than the project pool, so its identity is\n * owned by the customer's IdP.\n *\n * `tenantId` is the whole signal: Firebase sets it on the user whenever the\n * account belongs to a tenant, and only SSO accounts do.\n */\nexport function isSsoGovernedAccount(\n user: { tenantId?: string | null } | null | undefined,\n): boolean {\n return Boolean(user?.tenantId)\n}\n\n/**\n * Whether the account may connect an additional consumer sign-in provider.\n *\n * **No, for any SSO-governed account.** The customer's IdP is the single gate\n * they bought: they revoke there, enforce MFA there, offboard there. A linked\n * personal Google account is a way in their IdP can never see or revoke —\n * exactly what SSO is purchased to prevent.\n *\n * Deliberately NOT gated on `sso.enforced`. That flag exists so we never\n * LOCK OUT an existing sign-in method; it is not a licence to hand out new\n * bypasses meanwhile. Nothing here removes a provider an account already has,\n * so this can never lock anyone out.\n *\n * This is the intent, not the boundary — the boundary is upstream, since a\n * GCIP tenant only accepts providers enabled on that tenant. Both matter: the\n * boundary is remote config that could drift, and a UI that offers a\n * security-regressing action is wrong even when the action would fail.\n */\nexport function canLinkSocialProvider(\n user: { tenantId?: string | null } | null | undefined,\n): boolean {\n return !isSsoGovernedAccount(user)\n}\n\n/**\n * The same question as `isOrgWideMember`, asked of the `users/{uid}/orgs`\n * reverse-index row instead of the member doc (AGL-1032).\n *\n * The console navigates from the index — it is what `useOrgScope` loads —\n * and the index carries a MIRROR of the predicate, not the inputs to it, so\n * this cannot recompute: `role: 'viewer'` on the index means \"viewer\",\n * whether the member reaches every site or one.\n *\n * Reads a missing flag as org-wide, for the same reason `isOrgWideMember`\n * reads a missing `allHosts` that way: rows written before the mirror\n * existed have no flag, and hiding the workspace from a real member is a\n * worse failure than showing org chrome to a collaborator whose reads the\n * rules refuse anyway. Owner/admin are org-wide by role regardless of the\n * mirror, so a stale row can never lock an admin out.\n *\n * Navigation only — never an access decision. AGL-1026 (rules) and the\n * Admin-SDK scope checks are the boundary.\n */\nexport function isOrgWideMembership(\n membership:\n | Pick<UserOrgMembership, 'role' | 'orgWide'>\n | null\n | undefined,\n): boolean {\n if (!membership) return true\n if (membership.role === 'owner' || membership.role === 'admin') return true\n return membership.orgWide !== false\n}\n\n/**\n * The `scopeTokens` projection stamped onto member docs (AGL-1038) so the\n * rules can intersect a caller's reach with a resource's `visibleTo` —\n * rules have no `.map()`, so `hostAccess`'s keys cannot be turned into\n * tokens at evaluation time and have to be denormalized here.\n *\n * Org-wide members get `['org']`; they own the org and read everything in\n * it, scoped or not (the rules short-circuit on them anyway). A scoped\n * collaborator gets `'org'` plus one token per granted host — `'org'`\n * because an org-WIDE resource stays readable by any member, which is\n * today's behavior and not something this project narrows.\n *\n * Not capped at `MAX_SCOPE_HOSTS`: the rules' `hasAny` has no 30-value\n * limit, only the client `array-contains-any` query does, so a member of\n * more than 30 sites is a listing problem for AGL-1044 to chunk, not a\n * reason to under-grant here.\n */\nexport function projectMemberScopeTokens(\n member: Partial<AglynOrgMember> | null | undefined,\n): ScopeToken[] {\n if (isOrgWideMember(member)) return [ORG_SCOPE_TOKEN]\n const hostIds = Object.keys(member?.hostAccess ?? {})\n return [ORG_SCOPE_TOKEN, ...hostIds.map(hostScopeToken)]\n}\n\n/**\n * A member's effective read set: the stored `scopeTokens` projection when it\n * is there, recomputed from the membership when it is not.\n *\n * The fallback is the security-relevant half and it was written out by hand\n * in four places (`use-scope-tokens`, `erase-scope`, the media sign route,\n * and by omission in `resolveMediaScope`, which only ever recomputed). Four\n * copies of \"what may this member see\" is the shape that eventually\n * disagrees, and a copy that reads `member.scopeTokens` WITHOUT the\n * `.length` guard silently grants nothing to a member the AGL-1040 backfill\n * has not reached — or, written the other way round, grants everything.\n *\n * Recomputing is the safe fallback rather than a convenience: it produces\n * exactly what `grantHostAccess` would have stamped, so an unstamped member\n * doc behaves as its `hostAccess` says, never as \"no access\" and never as\n * org-wide.\n */\nexport function memberScopeTokens(\n member: Partial<AglynOrgMember> | null | undefined,\n): ScopeToken[] {\n const stored = member?.scopeTokens\n return stored?.length ? stored : projectMemberScopeTokens(member)\n}\n\n/**\n * May this member see a resource carrying `visibleTo`? (AGL-1037/1038)\n *\n * The whole client-side/server-side authorization question in one place:\n * org-wide members read everything they own; everyone else needs their read\n * set to intersect the resource's scope. Absent/empty `visibleTo` is\n * org-wide by the same rule the Firestore rules use, so an unbackfilled\n * resource does not vanish.\n *\n * Every Admin-SDK path must call this (or `scopeAllows`, which wraps an\n * already-resolved scope) — the Admin SDK bypasses rules entirely, so this\n * IS the enforcement there, not a second opinion about it.\n *\n * NOT a membership check, and never a substitute for one: a `null` member\n * \"can see\" an org-wide resource here, because the question this answers is\n * \"is this resource in scope for that reach\", not \"is this person in the\n * org\". Resolve membership first and refuse the caller if there is none —\n * conflating the two is exactly how AGL-1026 exposed a whole org.\n */\nexport function memberCanSee(\n member: Partial<AglynOrgMember> | null | undefined,\n visibleTo: readonly string[] | null | undefined,\n): boolean {\n if (isOrgWideMember(member)) return true\n return visibleToTokens(visibleTo ?? undefined, memberScopeTokens(member))\n}\n\n/**\n * The `memberRoles` projection stamped onto host docs so Firestore rules\n * authorize host content with the single host-doc read they already do\n * (docs/MULTI_TENANT_FIRESTORE.md §5). Recomputed by the membership API\n * whenever a member changes; owner/admin appear on every host.\n */\nexport function projectHostMemberRoles(\n members: ReadonlyArray<Partial<AglynOrgMember> & { $id: string }>,\n hostId: HostUid,\n): Record<string, HostAccessRole> {\n const projection: Record<string, HostAccessRole> = {}\n for (const member of members) {\n const role = hostRoleFor(member, hostId)\n if (role) projection[member.$id] = role\n }\n return projection\n}\n"],"names":["consoleLabelUnder","generateSubdomain","isBlockedSubdomain","SUBDOMAIN_PATTERN","hostScopeToken","ORG_SCOPE_TOKEN","visibleToTokens","ORG_SLUG_PATTERN","RESERVED_ORG_ONLY","Set","CONSOLE_LABEL","process","env","NEXT_PUBLIC_CONSOLE_URL","NEXT_PUBLIC_WORKSPACE_DOMAIN","isBlockedOrgSlug","slug","normalized","toLowerCase","has","isValidOrgSlug","test","generateOrgSlug","name","ORG_ROLES","ORG_ROLE_WEIGHT","owner","admin","editor","viewer","isOrgRole","value","orgRoleAtLeast","role","minimum","canManageOrg","hostRoleFor","member","hostId","explicit","hostAccess","allHosts","HOST_CONTENT_WRITE_ROLES","HOST_PUBLISH_ROLES","canWriteHost","includes","canPublishHost","hostRoleCanWrite","hostRoleCanPublish","isOrgWideMember","scoping","undefined","Object","keys","length","countManagerSeats","entries","count","entry","usesCustomerSeat","staffSeat","handoff","isStaffSeat","OWNER_HANDOFF_PREVIOUS_OWNER","OWNER_HANDOFF_PREVIOUS_OWNER_LABELS","stay","leave","parseOwnerHandoff","raw","previousOwner","collaboratorSeatKey","email","trim","uid","collaboratorSeatKeys","key","add","countCollaboratorSeats","exclude","candidate","emails","delete","size","managerSeatKeys","countManagerSeatsExcluding","CONSOLE_USER_TYPE_LABELS","manager","collaborator","siteMember","CONSOLE_USER_TYPE_HINTS","consoleUserType","isSsoGovernedAccount","user","Boolean","tenantId","canLinkSocialProvider","isOrgWideMembership","membership","orgWide","projectMemberScopeTokens","hostIds","map","memberScopeTokens","stored","scopeTokens","memberCanSee","visibleTo","projectHostMemberRoles","members","projection","$id"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;CAKC,GAYD,SACEA,iBAAiB,EACjBC,iBAAiB,EACjBC,kBAAkB,EAClBC,iBAAiB,QACZ,mBAAe;AACtB,SACEC,cAAc,EACdC,eAAe,EACfC,eAAe,QACV,oBAAgB;AAEvB,0EAA0E,GAC1E,OAAO,MAAMC,mBAAmBJ,kBAAiB;AAEjD;;;;;;CAMC,GACD,MAAMK,oBAAoB,IAAIC,IAAI;IAAC;IAAS;IAAO;IAAQ;IAAa;IAAS;CAAQ;AAEzF;;;;;;;;;CASC,GACD,MAAMC,gBAAgBV,kBACpBW,QAAQC,GAAG,CAACC,uBAAuB,EACnCF,QAAQC,GAAG,CAACE,4BAA4B;AAG1C,OAAO,SAASC,iBAAiBC,IAAY;IAC3C,MAAMC,aAAaD,KAAKE,WAAW;IACnC,OACEV,kBAAkBW,GAAG,CAACF,eACtBA,eAAeP,iBACfR,mBAAmBc;AAEvB;AAEA,OAAO,SAASI,eAAeJ,IAAY;IACzC,OAAOT,iBAAiBc,IAAI,CAACL,SAAS,CAACD,iBAAiBC;AAC1D;AAEA,uEAAuE,GACvE,OAAO,SAASM,gBAAgBC,IAAY;IAC1C,MAAMP,OAAOf,kBAAkBsB;IAC/B,OAAOP,QAAQ,CAACD,iBAAiBC,QAAQA,OAAO;AAClD;AAEA,OAAO,MAAMQ,YAAgC;IAC3C;IACA;IACA;IACA;CACD,CAAA;AAED,MAAMC,kBAA2C;IAC/CC,OAAO;IACPC,OAAO;IACPC,QAAQ;IACRC,QAAQ;AACV;AAEA,OAAO,SAASC,UAAUC,KAAc;IACtC,O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AYC,QAAQC;QACjC,IAAIL,MAAM4E,UAAU,CAACxE,OAAOyE,GAAG,CAAC,GAAG7E;IACrC;IACA,OAAO4E;AACT"}
@@ -159,7 +159,8 @@ export declare const ENTERPRISE_EMAIL_SENDS_PER_MONTH = 260000;
159
159
  * (AGL-67, 2026-07-07): storage-per-host is media storage; the published
160
160
  * total-site-size cap it used to exceed by design was retired in AGL-2133.
161
161
  * Metered costs are passed through
162
- * from Firebase/Vercel at cost × 1.30 separately (AGL-41).
162
+ * from Firebase/Vercel separately (AGL-41), priced at cost ×
163
+ * `METERED_PRICE_MULTIPLE` (1.3388) so cost + 30% is kept after Stripe.
163
164
  */
164
165
  /** Legacy host-keyed dataset overrides resolved into org keys (AGL-240). */
165
166
  type LegacyEntitlementKeys = 'datasetsPerHost' | 'maxDatasetsPerHost';
@@ -407,9 +408,13 @@ export interface PlanPricing {
407
408
  * $16 per included host on annual prices and $12 to $22 on monthly: ten
408
409
  * Business sites plus fifteen extras came to $219 against Advanced's $299,
409
410
  * and plus ninety extras to $819 against Agency's $1,049, so on host count
410
- * alone no plan was ever worth upgrading to. $20 clears the steepest step on
411
- * both intervals: extra hosts are how a plan takes a few more sites, and
412
- * the next plan is how it takes many more (2026-09-20).
411
+ * alone no plan was ever worth upgrading to. $20 cleared the steepest step
412
+ * on both intervals when it was set (2026-09-20); pricing v4's $69 Pro made
413
+ * the Starter → Pro step $22 a site on monthly prices, so three Starter
414
+ * sites came to $65 against Pro's $69. Starter's is $25 since AGL-4227
415
+ * (three sites $75 monthly, $66 annual); every other plan stays at $20.
416
+ * Extra hosts are how a plan takes a few more sites, and the next plan is
417
+ * how it takes many more.
413
418
  */
414
419
  extraHostMonthlyUsd: number | null;
415
420
  /**
@@ -451,9 +456,10 @@ export interface PlanPricing {
451
456
  extraDataGbMonthlyUsd: number | null;
452
457
  /**
453
458
  * Metered overage per 1,000 customer REST API requests beyond
454
- * `apiRequestsPerMonth` (AGL-634). API access starts at Pro since pricing
455
- * v4 (Business before it) and every tier above it carries it, so Free and
456
- * Starter are null (no API to meter).
459
+ * `apiRequestsPerMonth` (AGL-634). API access starts at Starter since
460
+ * AGL-4226 (Pro from pricing v4, Business before it) and every tier above it
461
+ * carries it, so Free alone is null (no API to meter) beside Custom's
462
+ * contractual null. Starter's overage stops at `maxApiRequestsPerMonth`.
457
463
  */
458
464
  extraApiRequestsUsdPer1k: number | null;
459
465
  /**
@@ -553,20 +559,23 @@ export interface PlanPricing {
553
559
  *
554
560
  * Null wherever the plan has no email band to be over, and null on
555
561
  * enterprise, where every rate is the "not for sale" sentinel and the terms
556
- * are contractual. Free and Starter are the two banded at 0: campaign email
557
- * begins at Pro, and `emailSendsOverage` yields 0 against a non-positive
558
- * band, so a rate on either would advertise a fee that can never be
559
- * computed — the same defect as a rate beside an UNLIMITED band.
562
+ * are contractual. Free is banded at 0 and has no subscription to bill:
563
+ * `emailSendsOverage` yields 0 against a non-positive band, so a rate there
564
+ * would advertise a fee that can never be computed — the same defect as a
565
+ * rate beside an UNLIMITED band. (Starter's campaign band is 0 too, but it
566
+ * is billed against its own band — below.)
560
567
  *
561
568
  * Every tier whose band is POSITIVE carries one, Pro upward. A finite band
562
569
  * with no rate is silently free past the band, and since transactional mail
563
570
  * cannot be refused at any tier that would be unbounded absorbed spend
564
571
  * rather than "no overage".
565
572
  *
566
- * The Starter null therefore leaves that tier's transactional mail — the
567
- * only mail it can send — unbilled at any volume. Bounded in practice by
568
- * `hostLimit: 1` and a 1,000-contact CRM, and the alternative prices a
569
- * password reset, but it is the one place this axis absorbs cost by design.
573
+ * Starter is the exception since AGL-4227: its campaign band is 0, so its
574
+ * rate is measured against `INCLUDED_EMAIL_SENDS_BY_PLAN` — 1,000 emails a
575
+ * month of everything it sends — and bills past it. (This comment used to
576
+ * call Starter's unbilled mail "bounded in practice by `hostLimit: 1` and a
577
+ * 1,000-contact CRM"; neither bounded it — Starter buys extra sites and
578
+ * meters CRM records — and the real bound was the daily abuse ceiling.)
570
579
  */
571
580
  extraEmailSendsUsdPer1k: number | null;
572
581
  /**
@@ -1055,7 +1064,8 @@ export declare function publishedMeteredPrice(costPerQuotedUnitUsd: number, deci
1055
1064
  * and functions bill, in USD per view (AGL-1879, AGL-3444): the CDN requests
1056
1065
  * a cold load makes, and the one of them that reaches a function — the
1057
1066
  * analytics beacon. A page view billed past a plan's band is priced at
1058
- * `(perPageView + this) × METERED_MARKUP` — $0.80 per 1,000 — and every
1067
+ * `(perPageView + this) × METERED_PRICE_MULTIPLE`, rounded up — $0.83 per
1068
+ * 1,000 since AGL-3476 (this said $0.80 at × 1.3 until AGL-4227) — and every
1059
1069
  * `bandwidthGb` band is sized with it counted.
1060
1070
  *
1061
1071
  * ## Why a page view needs a second cost term
@@ -1126,8 +1136,9 @@ export declare const PAGE_VIEW_CDN_REQUEST_COST_USD = 0.00021635711;
1126
1136
  /**
1127
1137
  * Monthly unit costs for the meters the rollup already records (AGL-1134).
1128
1138
  *
1129
- * These are OUR costs, not prices — the org is billed at cost × 1.30
1130
- * (`METERED_MARKUP`, AGL-41). Storage/page-view/form rates match
1139
+ * These are OUR costs, not prices — the org is billed at cost ×
1140
+ * `METERED_PRICE_MULTIPLE` (1.3388, AGL-3476), which keeps cost + 30%
1141
+ * (`METERED_MARKUP`, AGL-41) after Stripe's 2.9%. Storage/page-view/form rates match
1131
1142
  * `METERED_UNIT_RATES_USD` in the metering module on purpose: two files
1132
1143
  * disagreeing about what a page view costs is exactly the drift this function
1133
1144
  * exists to remove.
@@ -1213,18 +1224,24 @@ export declare const ORG_COGS_UNIT_RATES_USD: {
1213
1224
  */
1214
1225
  dataStoragePerGbMonth: number;
1215
1226
  /**
1216
- * One `/v1` request — $117 per million (AGL-3444).
1227
+ * One `/v1` request — $120 per million (AGL-3444, re-derived for AGL-4226).
1217
1228
  *
1218
1229
  * Every request is a function invocation behind a CDN request, and it reads
1219
1230
  * before it answers (`apps/console/utils/api-v1.ts`). The ledger for a
1220
1231
  * default list page — 25 records, read as 26 — at Vercel's dearest region
1221
- * and nam5's list prices:
1232
+ * and nam5's list prices, as the pipeline stands after AGL-4226:
1222
1233
  *
1223
- * - reads: the key, the rate-limit window, the org, the month's quota
1224
- * counter, the site the resource sits under, and the page — 31, at
1225
- * $0.06 per 100,000 = $0.0000186
1226
- * - writes: the rate-limit window and the usage counter — 2, at $0.18 per
1227
- * 100,000 = $0.0000036
1234
+ * - reads: the key, the key's rate-limit window, the org, the WORKSPACE's
1235
+ * rate-limit window (AGL-4226), the site the resource sits under, and
1236
+ * the page — 31, at $0.06 per 100,000 = $0.0000186. A plan whose month
1237
+ * is MEASURED (Starter, for its ceiling; a comp; Custom's fallback
1238
+ * band) reads the month's counter as well, 32 in all ($0.0000192). Before the
1239
+ * workspace limit it was 30 on a plan that never measured, and the
1240
+ * comment said 31 — the counter read is paid only where a month can
1241
+ * refuse.
1242
+ * - writes: the two rate-limit windows and the usage counter — 3, at
1243
+ * $0.18 per 100,000 = $0.0000054 (the key's last-used stamp is written
1244
+ * at most once a minute, and is left out)
1228
1245
  * - the function, 0.4 s billed as active CPU at $0.221/hr, 2 GB at
1229
1246
  * $0.0183/GB-hr, $0.60 per million invocations = $0.0000292
1230
1247
  * - the CDN request: $3.20 per million = $0.0000032
@@ -1234,9 +1251,30 @@ export declare const ORG_COGS_UNIT_RATES_USD: {
1234
1251
  * of request and envelope, through Fast Data Transfer ($0.35 a GB) and
1235
1252
  * Fast Origin Transfer ($0.43 a GB), decimal GB = $0.0000615
1236
1253
  *
1237
- * $0.0001161, carried up to $0.000117. A page of 100 — the most a client
1238
- * may ask for — costs about three times that, so the figure is the default
1239
- * request rather than the ceiling; see the 2026-10-01 decision entry.
1254
+ * $0.0001179, or $0.0001185 where the month is measured, carried up to
1255
+ * $0.00012. It was $0.000117 before the workspace window's read and write.
1256
+ *
1257
+ * The figure is the DEFAULT request, not the ceiling — which is why a
1258
+ * request has been BILLED by size since AGL-4227: one unit per started
1259
+ * 256 KB of the larger of its request and response
1260
+ * (`API_BILLING_UNIT_BYTES`). At Pro's $0.50 per 1,000, $0.0005 a unit and
1261
+ * 97.1% of it kept after Stripe:
1262
+ *
1263
+ * - a full 256 KiB unit costs about $0.000262 (the $0.000057 fixed part
1264
+ * above plus 262,144 bytes at $0.78 a decimal GB): kept 1.86×, the
1265
+ * thinnest case, still above cost + 30%;
1266
+ * - a page of 100 — the most a client may ask for — is $0.000343 and
1267
+ * about 302 KiB, so 2 units ($0.001): kept 2.83×;
1268
+ * - a 1 MB body is 4 units ($0.002) against about $0.000837: kept 2.32×;
1269
+ * - a body at Vercel's 4.5 MB function limit (a base64 image upload, or a
1270
+ * page of large dataset records) is 18 units ($0.009) against about
1271
+ * $0.00357: kept 2.45×. Billed as one unit it lost about 7×.
1272
+ *
1273
+ * Before the unit, a request paid for itself only up to about 550 KB on the
1274
+ * wire; with it, every size clears cost + 30% at $0.50, and by more at
1275
+ * Starter's $3.00.
1276
+ *
1277
+ * See the 2026-10-01 and 2026-11-16 decision entries.
1240
1278
  */
1241
1279
  perApiRequest: number;
1242
1280
  /**
@@ -1290,8 +1328,10 @@ export declare const ORG_COGS_UNIT_RATES_USD: {
1290
1328
  * document returned — and a step that writes a dataset record or calls a
1291
1329
  * webhook adds to it, so this is the typical figure, not the ceiling.
1292
1330
  *
1293
- * It is a COST, not a price: no plan bills runs, and none refuses past the
1294
- * band on a metered plan. It exists so a tier's run bands reach
1331
+ * It is a COST, not a price. Since pricing v4 Pro bills runs past its bands
1332
+ * at `RUN_OVERAGE_USD_PER_1K` ($0.02, cost × the pass-through multiple) and
1333
+ * Starter refuses at its band (comment corrected in AGL-4227). It exists so
1334
+ * a tier's run bands reach
1295
1335
  * `orgMonthlyCogsUsd` and `tier-margin-floor.spec.ts` — Agency's 3,000,000
1296
1336
  * runs are $36 a month that read as nothing while this was absent.
1297
1337
  */
@@ -2454,14 +2494,48 @@ export interface ApiRequestQuotaResult {
2454
2494
  overageMonthlyUsd: number;
2455
2495
  /** Per-1,000 overage rate; null when the plan has no API. */
2456
2496
  overageRateUsd: number | null;
2497
+ /**
2498
+ * The most requests the month allows, overage included (AGL-4226):
2499
+ * `maxApiRequestsPerMonth`, never below `included`. `UNLIMITED` from Pro up.
2500
+ */
2501
+ ceiling: number;
2502
+ /**
2503
+ * Which limit refused, when `allowed` is false (AGL-4226): `'ceiling'` — a
2504
+ * metered plan at its monthly ceiling; `'band'` — a plan with no rate (or
2505
+ * whose overage cannot be collected) at its included band.
2506
+ */
2507
+ refusedBy: 'ceiling' | 'band' | null;
2457
2508
  }
2509
+ /**
2510
+ * The per-1,000 rate API requests past the band are SOLD at for this org, or
2511
+ * `null` when nothing past the band is sold (AGL-4226).
2512
+ *
2513
+ * The plan's rate (`resolvePlanPricing`, so a comp sells nothing), withheld
2514
+ * on EVERY plan when the overage could never be collected: no live billing
2515
+ * subscription (`isBillingSubscription` — a paid plan stored without one), or
2516
+ * a 100% whole-bill discount. A withheld rate turns the band into the wall
2517
+ * `checkApiRequestQuota` already enforces for a plan with no rate, so those
2518
+ * workspaces stop at the requests they were given rather than metering onto
2519
+ * an invoice nobody pays.
2520
+ *
2521
+ * Starter-only when it was written (AGL-4226); every plan since a read-only
2522
+ * production count on 2026-11-16 found no workspace it would cut off (none
2523
+ * of 275 on a paid plan without a live subscription, none on a 100%
2524
+ * whole-bill coupon; the only unbilled ones are staff comps, none of them
2525
+ * calling the API). An explicit uncapped staff comp is untouched: its band is
2526
+ * `UNLIMITED`, so a null rate refuses nothing. Custom carries no rate, so its
2527
+ * contracted band was already the wall.
2528
+ */
2529
+ export declare function apiOverageRateUsd(org: Partial<AglynOrgBilling> | null | undefined): number | null;
2458
2530
  /**
2459
2531
  * Customer REST API request meter (AGL-634): the monthly request count for an
2460
- * org. Pro (since pricing v4) and every tier above it carry `apiAccess` and an
2461
- * `extraApiRequestsUsdPer1k` rate, so requests past the included quota meter
2462
- * onto the monthly invoice
2463
- * (cost-plus, like storage overage — never a hard wall mid-integration); plans
2464
- * without API access have `included: 0` and always block.
2532
+ * org. Every plan with `apiAccess` but Custom carries an
2533
+ * `extraApiRequestsUsdPer1k` rate (Starter since AGL-4226, Pro since pricing
2534
+ * v4), so requests past the included band meter onto the monthly invoice up
2535
+ * to the plan's monthly CEILING (`maxApiRequestsPerMonth`: 20,000 on
2536
+ * Starter, none from Pro up). Plans without a rate — Free, a comp, Custom
2537
+ * on its fallback band, or a Starter workspace whose overage cannot be
2538
+ * collected (`apiOverageRateUsd`) — stop at the band.
2465
2539
  */
2466
2540
  export declare function checkApiRequestQuota(org: Partial<AglynOrgBilling> | null | undefined, usedRequests: number): ApiRequestQuotaResult;
2467
2541
  /** The two monthly run bands the workflows plugin's gates are held to. */
@@ -2512,6 +2586,19 @@ export interface CrmRecordsQuotaResult {
2512
2586
  overageMonthlyUsd: number;
2513
2587
  /** Per-1,000 overage rate; null when the plan hard-bands (free). */
2514
2588
  overageRateUsd: number | null;
2589
+ /**
2590
+ * The most records the plan allows, overage included (AGL-4227):
2591
+ * `maxCrmRecords`, never below `included`. Starter's is Pro's included
2592
+ * amount; `UNLIMITED` from Pro up.
2593
+ */
2594
+ ceiling: number;
2595
+ /**
2596
+ * Which limit refused, when `allowed` is false (AGL-4227): `'ceiling'` — a
2597
+ * metered plan at its records ceiling (Starter at Pro's band, where the
2598
+ * upgrade is the way on); `'band'` — a plan that sells nothing past its
2599
+ * included records (Free, a comp).
2600
+ */
2601
+ refusedBy: 'ceiling' | 'band' | null;
2515
2602
  }
2516
2603
  /**
2517
2604
  * The name this result carried while the band counted contacts alone.
@@ -2521,7 +2608,9 @@ export type ContactQuotaResult = CrmRecordsQuotaResult;
2521
2608
  /**
2522
2609
  * CRM records band meter (AGL-890, widened in AGL-2611): contacts, companies
2523
2610
  * and deals, counted together across the org and measured against the ONE
2524
- * band `contactsPerHost` names. Paid plans carry an `extraContactsUsdPer1k`
2611
+ * band `contactsPerHost` names, up to `maxCrmRecords` (AGL-4227: Starter
2612
+ * stops adding at Pro's included amount; records it already holds stay and
2613
+ * bill). Paid plans carry an `extraContactsUsdPer1k`
2525
2614
  * rate, so records past the included band meter onto the monthly invoice
2526
2615
  * (cost-plus, like storage and API overage — a growing audience is never
2527
2616
  * dropped); free has no rate and hard-bands at the included count, refusing
@@ -2609,6 +2698,56 @@ export interface CrmEmailQuotaResult {
2609
2698
  * told their limit by being refused.
2610
2699
  */
2611
2700
  export declare function checkCrmEmailQuota(org: Partial<AglynOrgBilling> | null | undefined, usedToday: number, now?: Date): CrmEmailQuotaResult;
2701
+ /**
2702
+ * The EMAIL BILLING band where it is not the campaign band (AGL-4227): the
2703
+ * emails a month a plan includes across ALL mail on the cost meter — receipts,
2704
+ * notices, workflow and one-to-one CRM mail as well as campaigns — before
2705
+ * `extraEmailSendsUsdPer1k` bills.
2706
+ *
2707
+ * Starter's campaign band is 0 (campaigns start at Pro), so measuring its
2708
+ * overage against that band priced nothing at any volume. It now includes
2709
+ * 1,000 emails a month of everything, one-to-one CRM mail inside the same
2710
+ * 1,000, and bills past it. Every other plan bills against its campaign band
2711
+ * as before; a plan absent here has no separate billing band.
2712
+ */
2713
+ export declare const INCLUDED_EMAIL_SENDS_BY_PLAN: Readonly<Partial<Record<OrgPlan, number>>>;
2714
+ /**
2715
+ * A HARD monthly cap on a plan's email (AGL-4227), across everything on the
2716
+ * cost meter but account and security mail: past it, the next email is not
2717
+ * sent until the month turns (UTC). For the plan that cannot be billed for
2718
+ * usage — Free — so its mail has a bound that is not an invoice.
2719
+ *
2720
+ * 300 on Free. What a Free workspace legitimately sends is small: 20 form
2721
+ * submissions a month (a notice and a confirmation each, at most 40), no
2722
+ * store, no bookings, no campaigns, no one-to-one CRM mail and no workflows;
2723
+ * invitations, sign-in links and password resets are exempt and never
2724
+ * counted. 300 is several times that, and costs at most $0.27 a month at
2725
+ * `perEmailSend`. Counted on its own field from the month it ships, so it
2726
+ * never refuses mail because of what was sent before it existed.
2727
+ *
2728
+ * A plan absent here has no monthly cap (its daily abuse ceiling still
2729
+ * applies). An org can be given its own figure on
2730
+ * `entitlements.emailSendsMonthlyCap`.
2731
+ */
2732
+ export declare const EMAIL_SENDS_MONTHLY_CAP_BY_PLAN: Readonly<Partial<Record<OrgPlan, number>>>;
2733
+ /** The per-org override key for the monthly email cap. */
2734
+ export declare const EMAIL_SENDS_MONTHLY_CAP_KEY = "emailSendsMonthlyCap";
2735
+ /**
2736
+ * The org's hard monthly email cap (AGL-4227): its own figure when staff
2737
+ * wrote one, else its plan's, else `UNLIMITED`. The ONE reader the send seam,
2738
+ * the usage page and the usage alerts ask. Read off the plan the org RESOLVES
2739
+ * as, so a lapsed paid plan reads as Free.
2740
+ */
2741
+ export declare function resolveMonthlyEmailCap(org: Partial<AglynOrgBilling> | null | undefined): number;
2742
+ /**
2743
+ * The band an org's month of email is billed against (AGL-4227):
2744
+ * `INCLUDED_EMAIL_SENDS_BY_PLAN` for its plan where one is set, else its
2745
+ * resolved `emailSendsPerMonth`. The ONE reader the rollup and the billing
2746
+ * page ask, so the invoice and the readout cannot measure different bands.
2747
+ * A comp prices nothing past any band (`compPricing`), so the band it reads
2748
+ * here never bills.
2749
+ */
2750
+ export declare function emailSendsBillingBand(org: Partial<AglynOrgBilling> | null | undefined): number;
2612
2751
  /**
2613
2752
  * Volume above the plan's included band, in emails.
2614
2753
  *
@@ -3135,3 +3274,55 @@ export declare function dataStorageEnforcementShape(org: Partial<AglynOrgBilling
3135
3274
  * anything has been measured. @see QuotaEnforcementShape
3136
3275
  */
3137
3276
  export declare function apiRequestEnforcementShape(org: Partial<AglynOrgBilling> | null | undefined): QuotaEnforcementShape;
3277
+ /**
3278
+ * Requests per minute the WHOLE workspace may make on the customer API, every
3279
+ * key and connection together (AGL-4226): the resolved
3280
+ * `apiRequestsPerMinutePerOrg`, or `UNLIMITED` when the plan sets none
3281
+ * (Custom without an agreed figure, an uncapped comp). Sits beside the
3282
+ * per-key 120 a minute, never instead of it.
3283
+ *
3284
+ * The ladder: Starter 120 (one key's worth), Pro 600, and each retired tier
3285
+ * above it at least Pro's — Business 600, Scale 1,200, Advanced 2,400,
3286
+ * Agency 6,000 — with Custom unlimited unless its agreement sets a number.
3287
+ */
3288
+ export declare function apiWorkspaceRateLimitPerMinute(org: Partial<AglynOrgBilling> | null | undefined): number;
3289
+ /**
3290
+ * The cheapest self-serve plan with no monthly API ceiling, by price — the
3291
+ * plan a refusal at the ceiling names as the way past it (AGL-4226). `null`
3292
+ * when every self-serve plan has one.
3293
+ */
3294
+ export declare function cheapestPlanWithoutApiCeiling(): OrgPlan | null;
3295
+ /**
3296
+ * What a monthly refusal says (AGL-4226), naming the limit that refused: the
3297
+ * plan's ceiling and the plan without one, or the band a plan that sells no
3298
+ * overage stopped at.
3299
+ */
3300
+ export declare function apiMonthlyRefusalMessage(org: Partial<AglynOrgBilling> | null | undefined, quota: Pick<ApiRequestQuotaResult, 'ceiling' | 'included' | 'refusedBy'>): string;
3301
+ /**
3302
+ * What a refused CRM record says (AGL-4227): at Starter's ceiling, the
3303
+ * ceiling and the plan that includes it; at a band a plan sells nothing past,
3304
+ * the band. Records already held are never touched, and the message says so.
3305
+ */
3306
+ export declare function crmRecordsRefusalMessage(org: Partial<AglynOrgBilling> | null | undefined, quota: Pick<CrmRecordsQuotaResult, 'ceiling' | 'included' | 'refusedBy'>): string;
3307
+ /**
3308
+ * The size of ONE billed API unit (AGL-4227): a request is billed one unit
3309
+ * per started 256 KB of the larger of its request and response body.
3310
+ *
3311
+ * Every request was one unit at any size, and a request costs its bytes: a
3312
+ * default page is about 77 KB on the wire, a page of 100 records about
3313
+ * 302 KB, and a body at Vercel's 4.5 MB function limit about $0.0035 in
3314
+ * transfer alone — roughly 7× what one unit brings in at $0.50 per 1,000. A
3315
+ * 256 KB unit costs at most about $0.00026 (transfer at $0.78 per decimal GB
3316
+ * plus the request's fixed cost), which $0.50 per 1,000 covers 1.9 times
3317
+ * after Stripe's fee. The unit counts on the monthly counter, so it reaches
3318
+ * the invoice, the ceiling and the usage meter alike; the per-minute limits
3319
+ * keep counting CALLS.
3320
+ */
3321
+ export declare const API_BILLING_UNIT_BYTES: number;
3322
+ /**
3323
+ * How many billed units a request is (AGL-4227): one per started
3324
+ * `API_BILLING_UNIT_BYTES` of the larger of its request and response body,
3325
+ * and never fewer than one. A size that is not a finite, non-negative number
3326
+ * reads as 0, so it can only ever charge the one unit every call is.
3327
+ */
3328
+ export declare function apiRequestBillingUnits(requestBytes: number, responseBytes: number): number;