@aglyn/plugins-marketplace 1.0.0-beta.285 → 1.0.0-beta.288

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 (49) hide show
  1. package/package.json +14 -14
  2. package/src/lib/declarations.d.ts +26 -0
  3. package/src/lib/declarations.js +37 -0
  4. package/src/lib/declarations.js.map +1 -0
  5. package/src/lib/declarations.server.d.ts +2 -1
  6. package/src/lib/declarations.server.js +18 -1
  7. package/src/lib/declarations.server.js.map +1 -1
  8. package/src/lib/model/marketplace-site-permissions.d.ts +26 -0
  9. package/src/lib/model/marketplace-site-permissions.js +62 -0
  10. package/src/lib/model/marketplace-site-permissions.js.map +1 -0
  11. package/src/lib/model/marketplace.d.ts +24 -0
  12. package/src/lib/model/marketplace.js.map +1 -1
  13. package/src/lib/model/site-starter-listing.d.ts +49 -0
  14. package/src/lib/model/site-starter-listing.js +75 -0
  15. package/src/lib/model/site-starter-listing.js.map +1 -0
  16. package/src/lib/server/install-email-starter.js +7 -4
  17. package/src/lib/server/install-email-starter.js.map +1 -1
  18. package/src/lib/server/install-email-template.js +8 -5
  19. package/src/lib/server/install-email-template.js.map +1 -1
  20. package/src/lib/server/install-layout.js +7 -4
  21. package/src/lib/server/install-layout.js.map +1 -1
  22. package/src/lib/server/install-plugin.js +8 -8
  23. package/src/lib/server/install-plugin.js.map +1 -1
  24. package/src/lib/server/install-template.js +7 -4
  25. package/src/lib/server/install-template.js.map +1 -1
  26. package/src/lib/server/install-theme.js +10 -7
  27. package/src/lib/server/install-theme.js.map +1 -1
  28. package/src/lib/server/install.js +7 -4
  29. package/src/lib/server/install.js.map +1 -1
  30. package/src/lib/server/publish-email-starter.js +8 -5
  31. package/src/lib/server/publish-email-starter.js.map +1 -1
  32. package/src/lib/server/publish-email-template.js +8 -5
  33. package/src/lib/server/publish-email-template.js.map +1 -1
  34. package/src/lib/server/publish-layout.js +8 -5
  35. package/src/lib/server/publish-layout.js.map +1 -1
  36. package/src/lib/server/publish-starter.d.ts +37 -0
  37. package/src/lib/server/publish-starter.js +501 -0
  38. package/src/lib/server/publish-starter.js.map +1 -0
  39. package/src/lib/server/publish-template.js +9 -6
  40. package/src/lib/server/publish-template.js.map +1 -1
  41. package/src/lib/server/publish-theme.js +8 -5
  42. package/src/lib/server/publish-theme.js.map +1 -1
  43. package/src/lib/server/publish.js +8 -5
  44. package/src/lib/server/publish.js.map +1 -1
  45. package/src/lib/server/site-starter-source.d.ts +19 -0
  46. package/src/lib/server/site-starter-source.js +189 -0
  47. package/src/lib/server/site-starter-source.js.map +1 -0
  48. package/src/lib/server.js +3 -0
  49. package/src/lib/server.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/marketplace/src/lib/model/marketplace.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 * Marketplace marketplace v1 (AGL-44): shared types + the server-side\n * sanitization pass that gates publishing a host component definition as a\n * public listing. Pure data module — safe to import from API routes.\n */\n\n// The leaf module, not a barrel: this model is reached from both the browser\n// and API routes, and `@aglyn/aglyn` carries `createContext` (illegal in a\n// Server Component) while `@aglyn/aglyn/server` carries `node:fs` (illegal in\n// the browser). Neither is safe from here; the deep path has no dependencies.\nimport {\n isFirstPartyMediaSrc,\n MEDIA_REF_PREFIX,\n} from '@aglyn/aglyn/app-utils/media-ref'\nimport { marketplaceMinPriceUsd } from './listing-price-floor'\nimport type { InstallableArtifactType as MarketplaceArtifactType } from '@aglyn/aglyn/app-utils/artifact-provenance'\nimport type { ListingVerificationRequest } from './listing-verification'\nimport {\n offeredPluginVersion,\n type PluginRevocation,\n} from '@aglyn/aglyn/app-utils/plugin-manifest'\n// Visibility lives in core (AGL-876), for the same reason the artifact-type\n// union and the verification policy do: the console's listing route asks the\n// question and `scope:app` may not depend on `aglyn:addons`. Imported AND\n// re-exported — `installTargetsFor` and `listingArtifactLabel` below call\n// `listingArtifactType` locally, and a bare `export … from` binds nothing.\n// The write-deny classification (AGL-1361) rides along for the same reason:\n// it is a statement about the fields this policy reads, and the guard that\n// enforces it lives in core beside the rules parser.\nimport {\n isListingBrowsable,\n isListingDeleted,\n isPrivateListing,\n LISTING_CLIENT_WRITABLE_FIELDS,\n LISTING_UNPERSISTED_FIELDS,\n listingArtifactType,\n} from './listing-visibility'\n\nexport {\n isListingBrowsable,\n isListingDeleted,\n isPrivateListing,\n LISTING_CLIENT_WRITABLE_FIELDS,\n LISTING_UNPERSISTED_FIELDS,\n listingArtifactType,\n}\n\n/**\n * `profiles/{uid}` — a person's public identity.\n *\n * NOT a publisher identity as of AGL-652: publishing is org-only, and the\n * marketplace presence lives on `publisherProfiles/{orgId}` below. This doc\n * survives because it is also the support forum's author identity, which\n * renders poster names from `displayName`.\n */\nexport interface MarketplaceProfile {\n handle: string\n displayName: string\n bio?: string\n avatarUrl?: string\n}\n\n/**\n * `publisherProfiles/{orgId}` — an organization's marketplace presence\n * (AGL-652). Publishing is org-only: an org publishes, an org gets paid, and\n * the org is who buyers see. Keyed by org id so authorization is a plain org\n * role check with no ownership indirection.\n *\n * `stripeAccountId` / `stripeChargesEnabled` / `stripeAccountLivemode` are\n * written only by the Connect route via the Admin SDK and are frozen from\n * client writes by the rules — they decide who receives money, and\n * `stripeAccountLivemode` is a gate INPUT (AGL-2471), so a client that could\n * write it could re-open the hole by asserting its own readiness.\n */\nexport interface MarketplacePublisherProfile {\n /** Unique marketplace handle; reserved in `publisherHandles/{handle}`. */\n handle: string\n displayName: string\n bio?: string\n avatarUrl?: string\n website?: string\n /** Server-only. */\n stripeAccountId?: string\n /** Server-only; true once Connect onboarding can accept charges. */\n stripeChargesEnabled?: boolean\n /**\n * Server-only; which Stripe world the account belongs to (AGL-2471).\n * `true` = live, `false` = test, ABSENT = never established — and on a live\n * deployment absent refuses the sale, because a payout destination whose\n * mode nobody verified is exactly what shipped three unusable storefronts.\n */\n stripeAccountLivemode?: boolean\n}\n\n/**\n * `publisherHandles/{handle}` — uniqueness reservation for publisher handles,\n * mirroring `orgSlugs` (AGL-652). Without it two publishers could claim the\n * same handle, which the marketplace URL space cannot represent. `movedTo`\n * tombstones a renamed handle so old links can still resolve.\n */\nexport interface PublisherHandleReservation {\n orgId: string\n movedTo?: string\n}\n\n/**\n * Publisher handles share the org-slug shape: 3–30 chars, lowercase\n * alphanumeric plus internal hyphens. Single source of truth — the two\n * marketplace pages historically applied two subtly different regexes to the\n * same field (AGL-653).\n */\nexport const PUBLISHER_HANDLE_PATTERN = /^[a-z0-9][a-z0-9-]{1,28}[a-z0-9]$/\n\nexport function isValidPublisherHandle(handle: string): boolean {\n return PUBLISHER_HANDLE_PATTERN.test(handle)\n}\n\n/**\n * `marketplaceListings/{listingId}` — public component listing. Version\n * snapshots live in the `versions/{n}` subcollection; installs copy a pinned\n * version into `hosts/{hostId}/components` so the existing drawer/graft\n * pipeline applies unchanged.\n */\nexport interface MarketplaceListing {\n profileId: string\n displayName: string\n description?: string\n category?: string\n /**\n * What this listing publishes (AGL-654). One discriminator for every\n * artifact type — the previous scheme split across two orthogonal fields\n * (`type: 'component'|'plugin'` plus a separate `kind: 'template'`), so a\n * template was \"kind template with no type\" and each installer branched on\n * whichever field it happened to care about. That does not survive adding\n * layouts, dataset schemas and email templates.\n *\n * Read it through `listingArtifactType()`, never directly — listings\n * written before this field still carry only the legacy pair.\n */\n artifactType?: MarketplaceArtifactType\n /** @deprecated Legacy discriminator; use `artifactType` (AGL-654). */\n type?: 'component' | 'plugin'\n /** @deprecated Legacy discriminator; use `artifactType` (AGL-654). */\n kind?: 'template'\n latestVersion: number | string\n /** Plugin manifest id, for `type: 'plugin'` listings (AGL-45). */\n pluginId?: string\n /** One-time price in whole USD; 0/absent = free (AGL-46). */\n priceUsd?: number\n deletedAt?: unknown\n // Listing content (AGL-430, Strapi Market parity) — publisher-authored,\n // rendered on the marketplace detail page. All optional; validated by\n // validateListingContent on the API path and SANITIZED at render time\n // (the doc is publisher-writable, so renderers never trust it).\n logoUrl?: string\n screenshots?: string[]\n /** Markdown documentation shown on the listing page (no raw HTML). */\n readme?: string\n homepageUrl?: string\n repositoryUrl?: string\n /** SPDX-ish license label, e.g. \"MIT\". */\n license?: string\n categories?: string[]\n /**\n * Marketplace review lifecycle (AGL-432). Absent = legacy listing,\n * treated as 'listed'. New plugin listings start 'submitted'; staff move\n * them through the queue. Only 'listed'/'verified' (or legacy) plugin\n * listings appear in browse for non-owners.\n */\n reviewStatus?: ListingReviewStatus\n /**\n * The publisher's standing ask for the Verified badge (AGL-1217).\n *\n * Its own field, never a `reviewStatus` member — see\n * {@link ListingVerificationRequest}. Server-owned: the publisher route only\n * moves it to `pending`/`withdrawn`, and only staff can decide it. Asking\n * never grants anything; the checklist gate on `verify` stays the one route\n * to the badge.\n */\n verificationRequest?: ListingVerificationRequest\n // Server-managed. These were written by the publish/install/review paths\n // but never declared, so callers reached for `as any` (AGL-654).\n /** Publishing org id — the publisher profile's doc id (AGL-652). */\n publisherOrgId?: string\n /** Source component for a `component` listing. */\n sourceComponentId?: string\n /** Source site for a `template` listing. */\n sourceHostId?: string\n /** Incremented by the install API; frozen from client writes. */\n installCount?: number\n /**\n * How many installs are LIVE right now — `installCount`'s sibling, and\n * undeclared here until AGL-1420 went looking for it.\n *\n * That omission was the whole bug. AGL-1361's coverage guard builds the\n * listing's field universe from this interface, the rules deny-list and the\n * resolvers, so a server-owned field in none of the three is not classified\n * as exposed — it is INVISIBLE to the guard, which is a worse failure than\n * being classified wrongly. `installCount` was denied and this was not, so\n * the sibling counter a publisher-org owner/admin could write was the one\n * the browse grid and the listing header print to buyers.\n *\n * Written by the install/uninstall routes and by AGL-1419's derivation.\n */\n activeInstalls?: number\n /**\n * AGL-1419's derived-count cache: the pin count as last verified, the wall\n * clock it was verified at, and the per-version split.\n *\n * Server-owned for a stronger reason than the counters themselves. They are\n * not merely a number that could be wrong — `verifiedLivePins` treats the\n * triple as FRESH when `pinnedActiveInstalls === activeInstalls` and the\n * timestamp is inside the TTL, and then returns `pinnedVersionInstalls`\n * without querying anything. A client that could write all four could pin\n * the cache open on numbers it chose and suppress the re-derivation that\n * exists to bring a count back down.\n */\n pinnedActiveInstalls?: number\n pinsVerifiedAtMs?: number\n pinnedVersionInstalls?: Record<string, number>\n previewImageUrl?: string\n screenCount?: number\n versionHistory?: Array<{ version: number | string; publishedAt?: unknown }>\n createdAt?: unknown\n updatedAt?: unknown\n /** Staff review audit (AGL-432); server-owned (AGL-651). */\n reviewedBy?: string\n reviewedAt?: unknown\n rejectionReason?: string\n /**\n * What the marketplace lists query by (AGL-3321), derived by the server\n * from the fields above after every write (`listingQueryFields`,\n * `refreshListingQueryFields`) and denied to clients.\n */\n nameLower?: string\n nameTokens?: string[]\n nameReversed?: string\n browseAudience?: string[]\n browseTokens?: string[]\n takenDown?: boolean\n /**\n * The publishing workspace is locked (AGL-3365): the listing is out of\n * browse, search and its page until the lift clears it. Written only by\n * the lockdown's marketplace participant, which clears exactly the\n * listings it stamped; server-owned.\n */\n workspaceLockedAt?: unknown\n}\n\n/**\n * Everything an org can publish to the marketplace (AGL-654): every kind of\n * content the platform can install.\n *\n * The union is core's `InstallableArtifactType` — installed content is read by\n * surfaces that are not the marketplace, through the provenance stamp — and is\n * re-exported here under the name publishing code has always used.\n */\nexport type { MarketplaceArtifactType }\n\nexport {\n ARTIFACT_TYPE_LABELS,\n INSTALL_TARGETS,\n type InstallPin,\n type InstallTarget,\n LISTING_CATEGORIES,\n type OrgInstallSite,\n type OrgInstallSummary,\n type PluginInstallState,\n resolveOrgInstallSummary,\n resolvePluginInstallState,\n resolveUninstallTargets,\n type UninstallTarget,\n} from './marketplace-catalog'\nimport { ARTIFACT_TYPE_LABELS, INSTALL_TARGETS, type InstallPin, type InstallTarget, LISTING_CATEGORIES } from './marketplace-catalog'\n\n/** The friendly artifact-type label for a listing (AGL-864). */\nexport function listingArtifactLabel(listing: {\n artifactType?: string\n type?: string\n kind?: string\n}): string {\n return ARTIFACT_TYPE_LABELS[listingArtifactType(listing)] ?? 'Component'\n}\n\n/** Targets a listing can be installed to, defaulting to host-only. */\nexport function installTargetsFor(listing: {\n artifactType?: string\n type?: string\n kind?: string\n}): readonly InstallTarget[] {\n return INSTALL_TARGETS[listingArtifactType(listing)] ?? ['host']\n}\n\n\n/** How the admin chose to target an install from the org marketplace. */\nexport type InstallTargeting = 'all-sites' | 'selected-sites'\n\n/** One concrete install operation: an org pin, or a pin on a named host. */\nexport interface InstallPlanStep {\n scope: InstallTarget\n /** Present iff `scope === 'host'`. */\n hostId?: string\n}\n\n/**\n * Turns a targeting choice into the concrete install operations for a listing\n * (AGL-773), honoring what each artifact type physically supports (see\n * {@link INSTALL_TARGETS}).\n *\n * The rules aren't uniform, and the picker must not promise what an artifact\n * can't do:\n * - **Org-pinnable** (plugin, datasetSchema) + \"all sites\" → a SINGLE org pin,\n * which also covers sites created later.\n * - **Host-scoped** (component, template, layout, emailTemplate) has no org\n * pin, so \"all sites\" fans out to every CURRENT host — new sites are NOT\n * covered automatically. The UI has to say so.\n * - \"Selected sites\" is always host pins, even for an org-pinnable artifact:\n * the admin named specific sites, so honor that literally — UNLESS the\n * artifact can't host-pin at all (datasetSchema), where the per-site choice\n * is meaningless and collapses to the org pin.\n */\nexport function resolveInstallPlan(\n listing: { artifactType?: string; type?: string; kind?: string },\n targeting: InstallTargeting,\n hosts: {\n selectedHostIds: readonly string[]\n allHostIds: readonly string[]\n },\n): InstallPlanStep[] {\n const targets = installTargetsFor(listing)\n const canOrgPin = targets.includes('org')\n const canHostPin = targets.includes('host')\n if (targeting === 'all-sites') {\n if (canOrgPin) return [{ scope: 'org' }]\n return hosts.allHostIds.map((hostId) => ({ scope: 'host', hostId }))\n }\n // selected-sites\n if (!canHostPin) return [{ scope: 'org' }]\n return hosts.selectedHostIds.map((hostId) => ({ scope: 'host', hostId }))\n}\n\nexport type ListingReviewStatus =\n | 'submitted'\n | 'in_review'\n | 'listed'\n | 'verified'\n | 'rejected'\n\n/**\n * Verification requests lived in core from AGL-1217 because the console's\n * STAFF REVIEW ROUTE needed the policy and `scope:app` may not depend on\n * `aglyn:addons`. That route is the plugin's own surface since `38c4b533c`,\n * so the reason expired with it and the module came home (AGL-3080).\n *\n * Still re-exported from here, which is the part that did not change:\n * publishing code keeps one import site whether the policy is a lib away or\n * a file away.\n */\nexport {\n VERIFICATION_BLOCK_MESSAGES,\n VERIFICATION_DECLINE_COOLDOWN_DAYS,\n timestampMs,\n verificationRequestBlock,\n} from './listing-verification'\nexport type {\n ListingVerificationRequest,\n TimestampLike,\n VerifiableListing,\n VerificationRequestBlock,\n VerificationRequestState,\n} from './listing-verification'\n\n\n/**\n * Per-VERSION review state (AGL-966).\n *\n * Approval is a statement about specific bytes, so it lives on the version\n * doc beside the verifier verdict and the review checklist — both already\n * keyed to sha256. It used to live on the listing, which meant a publisher\n * could get v1.0.0 verified and then ship v1.0.1 containing anything: the\n * listing kept its status, the queue never surfaced the update, and\n * installs resolved `latestVersion`.\n */\nexport type PluginVersionReviewState = 'pending' | 'approved' | 'rejected'\n\n/**\n * The LISTING's cached summary of the version it currently offers.\n *\n * A different field from the one above and a different set of values, which is\n * the whole reason it is written down here. `reviewState` lives on the version\n * document and is a verdict about specific bytes;\n * `latestVersionReviewState` lives on the LISTING and exists so browse cards\n * and the listing page can answer \"have the bytes on offer been read?\" without\n * a per-listing subcollection read.\n *\n * `'revoked'` is the value that only ever appears HERE. A kill is not a review\n * verdict: the version keeps the `'approved'` it earned — the staff surface\n * shows \"Disabled\" beside that verdict rather than instead of it, because\n * collapsing the two would erase what the publisher earned — and it is only\n * this listing-level summary that flips, so the \"Reviewed\" chip drops and the\n * caution alert raises while the audit trail stays intact.\n *\n * The practical consequence, and the reason this is a type rather than a\n * comment: the staff review QUEUE keys on the version's `reviewState`, never\n * on this field. Were it to key on this one, every revoked version would\n * reappear in the queue indistinguishable from one awaiting its first review,\n * and a reviewer acting in good faith on a queue they trusted could approve a\n * version somebody had deliberately killed. The two fields are not\n * interchangeable and this names why.\n */\nexport type ListingLatestVersionReviewState =\n | PluginVersionReviewState\n | 'revoked'\n\n\nexport interface ReviewableVersion {\n version?: string\n reviewState?: string\n publishedAt?: { toMillis?: () => number } | null\n}\n\n/** Only approved bytes may be installed. Absent state is NOT approval. */\nexport function isVersionApproved(\n version: { reviewState?: string } | null | undefined,\n): boolean {\n return version?.reviewState === 'approved'\n}\n\n/**\n * Whether an install would hand the viewer UNREVIEWED bytes (AGL-1083).\n *\n * `install-plugin` deliberately lets a publisher install their own\n * unapproved version — you cannot test a version you cannot install, and\n * the AGL-969 checklist asks them to confirm they tested these exact bytes\n * on a site they control. The route reaches that case through\n * `newestApprovedVersion(...) ?? fallback`, where the fallback is\n * `latestVersion` and applies ONLY when the caller owns the listing and no\n * approved version exists at all.\n *\n * Lives here rather than in the listing component because the UI has to\n * describe exactly what the route will do. Two independent readings of\n * \"would this be unreviewed?\" is how the affordance ends up warning about\n * the wrong installs, or staying silent on the right ones.\n *\n * The route's `newest` is `newestInstallableVersion` since AGL-2368 — a\n * revoked version is no longer a candidate, so it no longer suppresses the\n * fallback either. `revocation` is optional because most callers have none;\n * without it this asks the pre-AGL-2368 question, which is the same answer\n * whenever the mirror is current.\n */\nexport function installsUnreviewedFallback(\n listing:\n | {\n profileId?: string\n latestVersion?: string | number\n latestApprovedVersion?: string | number\n }\n | null\n | undefined,\n viewerOrgId: string | null | undefined,\n revocation?: PluginRevocation | null,\n): boolean {\n if (!listing?.profileId || !viewerOrgId) return false\n // Only the publishing org gets the fallback; everyone else is refused.\n if (listing.profileId !== viewerOrgId) return false\n // An INSTALLABLE version exists → the route serves THAT, however much newer\n // the pending one is. Not an unreviewed install. Reading approval alone got\n // this backwards for a revoked listing: the route would fall back to\n // `latestVersion` for the owner and hand over unreviewed bytes, while the\n // page said nothing, because a stopped version still counted as approved.\n if (offeredPluginVersion(listing, revocation)) return false\n return Boolean(String(listing.latestVersion ?? ''))\n}\n\n/**\n * The version a fresh install should pin: newest APPROVED, never\n * `latestVersion`. A pending update is simply not offered, so publishing\n * cannot ship code past review, and the previously approved version keeps\n * installing while the new one waits.\n */\nexport function newestApprovedVersion<T extends ReviewableVersion>(\n versions: readonly T[],\n): T | null {\n const approved = versions.filter((entry) => isVersionApproved(entry))\n if (!approved.length) return null\n return approved.reduce((best, entry) =>\n (entry.publishedAt?.toMillis?.() ?? 0) >\n (best.publishedAt?.toMillis?.() ?? 0)\n ? entry\n : best,\n )\n}\n\n/**\n * What a listing is still missing before it can face the marketplace\n * (AGL-968/994).\n *\n * A private plugin is allowed to be undocumented — its only audience already\n * knows what it is and why it exists. A public one is not: description,\n * README and license are what a stranger deciding whether to run your code\n * has to go on, and they are exactly the fields the review checklist asks\n * about. So going public is gated on the METADATA, never on a re-review —\n * approval is a statement about bytes, and the bytes did not change.\n *\n * Returns the human field names, so the caller can say what to fix rather\n * than just refusing.\n */\nexport function missingPublicListingContent(listing: {\n description?: string\n readme?: string\n license?: string\n}): string[] {\n const missing: string[] = []\n if (!listing.description?.trim()) missing.push('a description')\n if (!listing.readme?.trim()) missing.push('a README')\n if (!listing.license?.trim()) missing.push('a license')\n return missing\n}\n\n\nexport const LISTING_README_MAX_CHARS = 20_000\nexport const LISTING_MAX_SCREENSHOTS = 6\n\nconst HTTPS_URL = /^https:\\/\\/[^\\s]+$/\n\n/**\n * The message every listing IMAGE field returns when it is refused. Names the\n * remedy, because \"must be an https URL\" was true of the value the publisher\n * just typed and told them nothing.\n */\nexport const LISTING_IMAGE_ERROR =\n 'must be an image from your media library — paste a link and the people ' +\n 'browsing your listing would be loading it from a server you control'\n\n/** Length cap shared by every listing URL field. */\nconst LISTING_URL_MAX_CHARS = 500\n\n/**\n * Whether a listing image field is one we will store (AGL-1701).\n *\n * Listing artwork is the one publisher-supplied value that OTHER orgs' users\n * load. It is also, established while fixing this, gated by nothing: review\n * is a statement about a version's bytes (AGL-966), the staff review route\n * never projects `logoUrl`/`screenshots` so a reviewer cannot see them even\n * if the checklist asked, and `update-listing` writes them at any time\n * without touching `reviewStatus` — so a listing can pass review with benign\n * artwork and swap it afterwards while still reading `verified`.\n *\n * Constraining the INPUT rather than sanitizing the output is the whole\n * point: the render sites are three components and an `og:image`, and the\n * next one added would not know to sanitize.\n */\nfunction isListingImageValue(value: unknown): value is string {\n return (\n typeof value === 'string' &&\n value.length <= LISTING_URL_MAX_CHARS &&\n isFirstPartyMediaSrc(value)\n )\n}\n\n/**\n * Whether a value may be a publisher's LOGO (AGL-3260).\n *\n * The listing-image rule, minus the private `media:` reference. A listing's\n * logo may be one because a caller that signs its own links can resolve it;\n * nothing that renders a publisher avatar signs anything, so a reference\n * there would store a value every render site must turn back into the\n * fallback initial — a logo that looks saved and is never seen.\n *\n * `startsWith` rather than `isMediaRef`, for the reason that predicate's own\n * neighbour gives: negating a `value is string` guard on a value already\n * known to be a string leaves the else branch `never`.\n */\nfunction isPublisherAvatarValue(value: unknown): value is string {\n return isListingImageValue(value) && !value.startsWith(MEDIA_REF_PREFIX)\n}\n\n/**\n * Validates publisher-editable listing content (AGL-430). Returns the\n * normalized subset to persist, or an error. Shared by publish and the\n * update-listing action so both paths accept exactly the same shapes.\n *\n * IMAGE fields and LINK fields are validated differently (AGL-1701).\n * `homepageUrl` and `repositoryUrl` stay any-https: they are anchors a reader\n * chooses to follow, and a publisher's homepage living on the publisher's\n * domain is the entire point of the field. `logoUrl` and `screenshots` are\n * `<img src>`, which fetches with no such choice, so those are held to\n * first-party media.\n */\nexport function validateListingContent(input: Record<string, unknown>): {\n ok: boolean\n error?: string\n content?: Partial<MarketplaceListing>\n} {\n const content: Partial<MarketplaceListing> = {}\n for (const key of ['homepageUrl', 'repositoryUrl'] as const) {\n const value = input[key]\n if (value === undefined || value === '') continue\n if (\n typeof value !== 'string' ||\n !HTTPS_URL.test(value) ||\n value.length > LISTING_URL_MAX_CHARS\n ) {\n return { ok: false, error: `${key} must be an https URL` }\n }\n content[key] = value\n }\n const logoUrl = input['logoUrl']\n if (logoUrl !== undefined && logoUrl !== '') {\n if (!isListingImageValue(logoUrl)) {\n return { ok: false, error: `logoUrl ${LISTING_IMAGE_ERROR}` }\n }\n content.logoUrl = logoUrl\n }\n const screenshots = input['screenshots']\n if (screenshots !== undefined) {\n if (\n !Array.isArray(screenshots) ||\n screenshots.length > LISTING_MAX_SCREENSHOTS ||\n screenshots.some((url) => !isListingImageValue(url))\n ) {\n return {\n ok: false,\n error:\n `screenshots must be up to ${LISTING_MAX_SCREENSHOTS} images, and ` +\n `each ${LISTING_IMAGE_ERROR}`,\n }\n }\n content.screenshots = screenshots as string[]\n }\n const readme = input['readme']\n if (readme !== undefined) {\n if (typeof readme !== 'string' || readme.length > LISTING_README_MAX_CHARS) {\n return {\n ok: false,\n error: `readme must be markdown up to ${LISTING_README_MAX_CHARS} chars`,\n }\n }\n if (readme.trim()) content.readme = readme\n }\n const license = input['license']\n if (license !== undefined && license !== '') {\n if (typeof license !== 'string' || license.length > 40) {\n return { ok: false, error: 'license must be a short label (max 40)' }\n }\n content.license = license\n }\n const categories = input['categories']\n if (categories !== undefined) {\n if (\n !Array.isArray(categories) ||\n categories.length > 3 ||\n categories.some((entry) => !LISTING_CATEGORIES.includes(String(entry)))\n ) {\n return {\n ok: false,\n error: 'categories must be up to 3 entries from the fixed taxonomy',\n }\n }\n content.categories = categories.map(String)\n }\n return { ok: true, content }\n}\n\n/**\n * Publisher-profile fields beyond the identity trio (AGL-1009): the logo,\n * the support contact, and a FIXED set of external links. Fixed on purpose —\n * the storefront renders each as a known icon, and a free-form list would\n * turn the trust panel into a link farm.\n */\nexport interface PublisherProfileContent {\n avatarUrl?: string\n website?: string\n supportEmail?: string\n supportUrl?: string\n githubUrl?: string\n xUrl?: string\n linkedinUrl?: string\n}\n\n/** Social keys whose URL must live on the network's own host. */\nconst PUBLISHER_SOCIAL_HOSTS: Record<string, readonly string[]> = {\n githubUrl: ['github.com'],\n xUrl: ['x.com', 'twitter.com'],\n linkedinUrl: ['linkedin.com'],\n}\n\nconst SUPPORT_EMAIL = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/\n\n/**\n * Validates the publisher-profile extras (AGL-1009), sharing\n * `validateListingContent`'s discipline on both of its halves: the LINKS are\n * https only and length capped, the LOGO is first-party media (AGL-3260).\n * Validated on the save route (server-owned like the handle — no client\n * write path carries these). An explicit empty string comes back as `''` so\n * the save route can distinguish \"clear this field\" from \"left untouched\".\n */\nexport function validatePublisherProfileContent(\n input: Record<string, unknown>,\n): { ok: boolean; error?: string; content?: PublisherProfileContent } {\n const content: PublisherProfileContent = {}\n /**\n * THE LOGO IS AN IMAGE FIELD, NOT A LINK FIELD (AGL-3260).\n *\n * It was validated as a link — any https URL — and the panel that edits it\n * only ever offers the media library, which since AGL-1215 hands back the\n * media-id-keyed CDN path (`/api/media/cdn/…`) rather than a storage URL.\n * A root-relative path is not an https URL, so the one value the form could\n * produce was the one value the route refused, and the publisher was told\n * their logo was malformed.\n *\n * Held to the same first-party rule as `logoUrl` and `screenshots` for the\n * reason given there (AGL-1701): this is an `<img src>` that other orgs'\n * users load on every listing's Publisher card, so it fetches with no\n * reader choice. That makes the fix a TIGHTENING as well — a third-party\n * `https://cdn.publisher.example/logo.png` no longer passes.\n */\n const avatarUrl = input['avatarUrl']\n if (avatarUrl !== undefined) {\n if (avatarUrl === '') {\n content.avatarUrl = ''\n } else if (!isPublisherAvatarValue(avatarUrl)) {\n return { ok: false, error: `avatarUrl ${LISTING_IMAGE_ERROR}` }\n } else {\n content.avatarUrl = avatarUrl\n }\n }\n const urlKeys = [\n 'website',\n 'supportUrl',\n 'githubUrl',\n 'xUrl',\n 'linkedinUrl',\n ] as const\n for (const key of urlKeys) {\n const value = input[key]\n if (value === undefined) continue\n if (value === '') {\n content[key] = ''\n continue\n }\n // The same https-or-nothing rule as listing URLs: `javascript:`, `data:`\n // and plain http all fail the one test.\n if (typeof value !== 'string' || !HTTPS_URL.test(value) || value.length > 500) {\n return { ok: false, error: `${key} must be an https URL` }\n }\n const hosts = PUBLISHER_SOCIAL_HOSTS[key]\n if (hosts) {\n let host = ''\n try {\n host = new URL(value).hostname.toLowerCase()\n } catch {\n return { ok: false, error: `${key} must be an https URL` }\n }\n if (!hosts.some((allowed) => host === allowed || host.endsWith(`.${allowed}`))) {\n return { ok: false, error: `${key} must link to ${hosts[0]}` }\n }\n }\n content[key] = value\n }\n const supportEmail = input['supportEmail']\n if (supportEmail !== undefined) {\n if (supportEmail === '') {\n content.supportEmail = ''\n } else if (\n typeof supportEmail !== 'string' ||\n supportEmail.length > 200 ||\n !SUPPORT_EMAIL.test(supportEmail)\n ) {\n return { ok: false, error: 'supportEmail must be an email address' }\n } else {\n content.supportEmail = supportEmail\n }\n }\n return { ok: true, content }\n}\n\n/**\n * Render-time guard for publisher links (AGL-1009): only an `https://` URL\n * is ever emitted as an href. The save route already refuses anything else,\n * but the doc is client-updatable on its cosmetic fields historically, so\n * the renderer must not trust stored data it did not write.\n */\nexport function safePublisherHref(url: unknown): string | undefined {\n return typeof url === 'string' && /^https:\\/\\//i.test(url) && url.length <= 500\n ? url\n : undefined\n}\n\n/**\n * The same guard for the publisher's LOGO (AGL-3260), which is an `<img src>`\n * rather than an href and so has a different safe set: the media library's\n * root-relative CDN path is the value the picker produces and must render,\n * and a third-party https URL — fine as a link the reader chooses to follow —\n * is exactly what must not be fetched on their behalf.\n */\nexport function safePublisherImageSrc(src: unknown): string | undefined {\n return isPublisherAvatarValue(src) ? src : undefined\n}\n\n/**\n * Platform revenue share on paid listings (AGL-46) — UI COPY ONLY. The\n * checkout route prices from the `marketplaceFeePct` ENTITLEMENT\n * (`resolveMarketplaceFeePct`, AGL-1543), which resolves the effective\n * plan and per-org overrides; these constants exist for seller-facing\n * copy and must be kept in step with the plan table.\n */\nexport const MARKETPLACE_PLATFORM_FEE_PERCENT = 20\n/** Free-plan publishers pay a higher share. See AGL-1543 note above. */\nexport const MARKETPLACE_PLATFORM_FEE_PERCENT_FREE_PLAN = 30\n/** One-time listing price ceiling (whole USD). */\nexport const MARKETPLACE_MAX_PRICE_USD = 1000\n\n/**\n * One-time listing price FLOOR for a PAID listing (whole USD, AGL-2343).\n *\n * Marketplace checkout is a destination charge with no `application_fee_amount`\n * — deliberately, so the sales tax stays with the platform that owes it\n * (AGL-1544) — which means Stripe debits its fee from the PLATFORM's balance.\n * Stripe's fixed 30¢ dominates at low prices, so under this figure the\n * platform's cut is smaller than the cost of collecting it and every sale is a\n * loss. The floor is the cheapest listing price that still clears the cost of\n * processing it.\n *\n * NOT A CHOSEN NUMBER. `marketplaceMinPriceUsd` derives it from the plan\n * table's lowest take rate and the dearest enabled payment method; this is a\n * re-export so that the routes and the console forms cannot quote different\n * minimums at the same publisher. Zero stays legal — a free listing takes no\n * payment and costs nothing to process.\n */\nexport const MARKETPLACE_MIN_PRICE_USD = marketplaceMinPriceUsd()\n\n/**\n * The refusal message for a listing price, or `undefined` when the price may\n * be published (AGL-2343).\n *\n * ONE VALIDATOR FOR SEVEN DOORS. Each publish route used to inline its own\n * range check against the maximum — and `publish-theme.ts` and\n * `publish-layout.ts` had none at all, so a $250,000 theme was publishable.\n * The doors call this, and `publishPreconditionRefusal` calls it too, so a\n * route that forgets is still covered.\n *\n * Takes the price the route already rounded: a listing price is whole dollars\n * everywhere, and a validator that accepted $2.99 would be validating a number\n * that is never stored.\n */\nexport function marketplacePriceRefusal(priceUsd: number): string | undefined {\n if (!Number.isFinite(priceUsd) || priceUsd < 0) {\n return `Price must be 0 (free) or $${MARKETPLACE_MIN_PRICE_USD}–$${MARKETPLACE_MAX_PRICE_USD} USD`\n }\n if (priceUsd > MARKETPLACE_MAX_PRICE_USD) {\n return `Price must be 0 (free) or $${MARKETPLACE_MIN_PRICE_USD}–$${MARKETPLACE_MAX_PRICE_USD} USD`\n }\n // Zero is not \"below the floor\" — it is the free listing, which takes no\n // payment at all and so costs nothing to process.\n if (priceUsd > 0 && priceUsd < MARKETPLACE_MIN_PRICE_USD) {\n return (\n `A paid listing must be at least $${MARKETPLACE_MIN_PRICE_USD} USD — ` +\n `below that, processing the payment costs more than the platform fee ` +\n `on the sale. Use 0 for a free listing.`\n )\n }\n return undefined\n}\n\n/**\n * The rule a node tree meets before it lands on a canvas that did not author\n * it is core's (`@aglyn/aglyn/app-utils/node-definition-sanitizer`, AGL-2939),\n * under neutral names, because a model-generated tree passes through it too.\n * A publisher reads it as the marketplace's rule, so the marketplace re-exports\n * it under the names its publish routes and its docs use.\n */\nexport {\n PORTABLE_COMPONENT_ID_ALLOWLIST as MARKETPLACE_COMPONENT_ID_ALLOWLIST,\n PORTABLE_EMAIL_COMPONENT_ID_ALLOWLIST as MARKETPLACE_EMAIL_COMPONENT_ID_ALLOWLIST,\n PORTABLE_EMAIL_STARTER_COMPONENT_ID_ALLOWLIST as MARKETPLACE_EMAIL_STARTER_COMPONENT_ID_ALLOWLIST,\n sanitizePortableDefinition as sanitizeMarketplaceDefinition,\n portableDefinitionToNested as marketplaceDefinitionToNested,\n PORTABLE_SAFE_HREF as MARKETPLACE_SAFE_HREF,\n PORTABLE_SAFE_SRC as MARKETPLACE_SAFE_SRC,\n PORTABLE_DEFINITION_MAX_BYTES as MARKETPLACE_DEFINITION_MAX_BYTES,\n type PortableDefinitionNodes as MarketplaceDefinitionNodes,\n} from '@aglyn/aglyn/app-utils/node-definition-sanitizer'\n\n/** One row of the listing detail's `What's included` checklist. */\nexport interface ListingInclusion {\n label: string\n /** Whether the row is a positive inclusion or a stated limit. */\n tone: 'included' | 'note'\n}\n\n/** What each artifact type drops into the org when it installs. */\nconst ARTIFACT_INSTALL_RESULT: Record<MarketplaceArtifactType, string> = {\n plugin: 'A plugin, sandboxed on its own origin with a per-plugin CSP',\n component: 'An editable component you can place on any page',\n template: 'Editable pages you can rework in Besigner',\n layout: 'An editable layout you can apply to any page',\n datasetSchema: 'A new empty dataset with its fields already defined',\n emailTemplate: 'An editable email design you can send campaigns from',\n emailStarter:\n 'A new email in your Email templates list, ready to edit and send',\n theme: 'A theme applied to the site you choose',\n siteStarter: 'A new site, created from these pages and this theme',\n}\n\n/**\n * The `WHAT'S INCLUDED` checklist the marketplace listing mockup shows\n * (AGL-2173), derived entirely from facts the listing already carries.\n *\n * The mockup's own bullets — `12 responsive screens`, `Blog & work\n * layouts` — are publisher-authored prose, and nothing collects them:\n * there is no content manifest on a listing or a version, so counting\n * screens would mean inventing a number. What IS knowable is what the\n * install physically does, where it lands, whether it has been reviewed,\n * and under what licence — which is the question a shopper is asking when\n * they read that box.\n *\n * Ordered decision-first: what you get, then where it goes, then the two\n * facts that most often stop an install.\n */\nexport function listingInclusions(\n listing: {\n artifactType?: string\n type?: string\n kind?: string\n license?: string\n priceUsd?: number\n reviewStatus?: string\n },\n options: { reviewedVersion?: boolean } = {},\n): ListingInclusion[] {\n const type = listingArtifactType(listing)\n const rows: ListingInclusion[] = [\n { label: ARTIFACT_INSTALL_RESULT[type] ?? 'An installable artifact', tone: 'included' },\n ]\n const targets = installTargetsFor(listing)\n rows.push({\n label: targets.includes('org')\n ? 'Installs org-wide, covering sites you add later'\n : 'Installs per site — new sites are not covered automatically',\n // The host-only case is a real limit and the picker already has to say\n // so; softening it here would put the caveat only where nobody reads.\n tone: targets.includes('org') ? 'included' : 'note',\n })\n if (options.reviewedVersion) {\n rows.push({\n label: 'This version passed marketplace review',\n tone: 'included',\n })\n }\n if (listing.license) {\n rows.push({ label: `Licensed ${listing.license}`, tone: 'included' })\n }\n rows.push({\n label: Number(listing.priceUsd ?? 0) > 0\n ? 'A one-time purchase — updates to this listing are included'\n : 'Free, including every future update',\n tone: 'included',\n })\n return rows\n}\n\n/**\n * WHO STILL OWNS WHAT THEY BOUGHT — the one predicate (AGL-2158).\n *\n * `hasLivePurchase` (server/purchase-entitlement.ts) is the gate on all eight\n * ways into paid content, and it reads exactly one field: a purchase with\n * `refundedAt` — stamped by the `charge.refunded` and lost-`charge.dispute`\n * doors of the marketplace billing webhook — no longer entitles.\n *\n * The listing page carried its OWN copy of that question,\n * `some(p => p.listingId === listingId)`, with no refund test at all. The two\n * then disagreed on the one buyer they must not disagree on: the refunded\n * one. The page showed \"Purchased\", hid the buy button, and the install\n * routes answered 402 — a buyer who could neither install nor re-purchase.\n *\n * It lives HERE, in the model, rather than in the server module, because the\n * server module is the wrong side of the client/server boundary for a React\n * component and copying four characters of predicate is precisely how the two\n * came apart. This module is context-free by construction (see the header) —\n * importable from a client component, an API route and another plugin alike.\n */\nexport interface PurchaseLiveness {\n /** Stamped when a full refund or a lost dispute un-buys the listing. */\n refundedAt?: unknown\n listingId?: unknown\n /**\n * THE ORGANIZATION THE LICENCE BELONGS TO (AGL-2331).\n *\n * Absent on every purchase written before AGL-2331 — see\n * `purchaseEntitlesOrg` for what that absence means and why it is never\n * treated as \"no licence\".\n */\n buyerOrgId?: unknown\n /** The person who paid. Kept for the receipt trail and the legacy grant. */\n buyerUid?: unknown\n}\n\n/**\n * True when this purchase document still entitles.\n *\n * Deliberately a truthiness test and not `!= null`: `refundedAt` is a\n * Firestore Timestamp on the server, a client Timestamp in the browser and a\n * sentinel in the webhook's own tests, and every one of those is truthy while\n * a missing field (every purchase written before AGL-1546) is not.\n */\nexport function isLivePurchase(\n purchase: PurchaseLiveness | null | undefined,\n): boolean {\n return Boolean(purchase) && !purchase?.refundedAt\n}\n\n/**\n * True when this buyer's purchase documents include a live one for `listingId`.\n *\n * Both callers pass everything they read — the server's query is already\n * narrowed to the listing, the client's is narrowed only to the buyer — so the\n * listing filter belongs inside the shared predicate too, not beside it.\n */\nexport function hasLivePurchaseOf(\n purchases: readonly (PurchaseLiveness | null | undefined)[] | null | undefined,\n listingId: string,\n): boolean {\n if (!listingId) return false\n return (purchases ?? []).some(\n (purchase) =>\n purchase?.listingId === listingId && isLivePurchase(purchase),\n )\n}\n/**\n * WHO A PURCHASE LICENSES (AGL-2331).\n *\n * ## The model\n *\n * **A marketplace purchase licenses an ORGANIZATION, not a person.** That is\n * not a new decision — it is the one already published. The Marketplace\n * Publisher Agreement §8.1 says a paid Artifact is licensed \"to the installing\n * organization\", and §2 grants the right to sublicense \"to organizations that\n * install it\". Until now the code enforced a per-PERSON licence instead, and\n * the mismatch cut both ways: an agency developer who is an owner across five\n * client workspaces bought once and installed into all five, and — because the\n * duplicate-purchase guard shares this predicate — could not buy a second\n * licence even when they wanted to. Conforming the code to the published terms\n * is the smaller of the two changes; the alternative amends a version-pinned\n * legal document and stops every publisher until they re-accept it.\n *\n * Three consequences follow, and all three are the point:\n *\n * 1. A licence held by org A does not install into org B. The agency buys per\n * client workspace, which is what the agreement says they are buying.\n * 2. Buying a second licence is a real second sale, not a `409`.\n * 3. Any member of the owning org with `installPlugins` may install what the\n * ORG bought — including colleagues who were not the buyer, and including\n * the buyer's replacement after they leave. A licence that evaporates when\n * one employee's account is deleted is not an organizational licence.\n *\n * ## The legacy grant, and why it never expires\n *\n * A purchase written before this change carries NO `buyerOrgId` — there was\n * no buyer org anywhere in the pipeline to record. Those are real purchases by\n * real customers, and reinterpreting one as \"licensed to no organization\"\n * would revoke access somebody paid for. So a purchase with no `buyerOrgId` at\n * all keeps its ORIGINAL, person-scoped meaning, forever: it entitles the uid\n * that bought it, in every org that uid can install into. Nothing is\n * migrated, nothing is claimed by the first org to use it, and nothing is\n * revoked — the ambiguity resolves in the customer's favour by construction,\n * with no backfill to get right and no window during which a paying customer\n * is locked out.\n *\n * The grandfather is bounded by time rather than policed: it can only ever\n * apply to purchases already written, because from AGL-2331 onward checkout\n * refuses to open a session that does not name a validated buyer org. It is\n * therefore a shrinking set that never grows, not a hole left open.\n *\n * `orgId` may be empty (a site with no owning org). That is not a licence to\n * anything, so only the legacy uid grant can hold — never a `buyerOrgId ===\n * ''` match, which is why the org branch tests for a non-empty string on the\n * document itself rather than comparing the two values directly.\n */\nexport function purchaseEntitlesOrg(\n purchase: PurchaseLiveness | null | undefined,\n actor: { orgId?: string | null; uid?: string | null },\n): boolean {\n if (!isLivePurchase(purchase)) return false\n const purchaseOrgId = purchase?.buyerOrgId\n if (typeof purchaseOrgId === 'string' && purchaseOrgId) {\n return Boolean(actor.orgId) && purchaseOrgId === actor.orgId\n }\n // Legacy: no buyer org was ever recorded, so it means what it meant when it\n // was sold. Never revoked, never migrated.\n return Boolean(actor.uid) && purchase?.buyerUid === actor.uid\n}\n\n/**\n * True when these purchase documents include one that licenses `orgId` for\n * `listingId` — the org-scoped counterpart of `hasLivePurchaseOf`.\n *\n * Same shape and same home as the liveness predicate, and for the same reason\n * (AGL-2158): the install routes, the checkout duplicate guard and the listing\n * page all have to answer \"does this workspace hold a licence\" identically, and\n * the way they came apart last time was four characters of predicate copied\n * into a component.\n */\nexport function hasOrgLicenceOf(\n purchases: readonly (PurchaseLiveness | null | undefined)[] | null | undefined,\n listingId: string,\n actor: { orgId?: string | null; uid?: string | null },\n): boolean {\n if (!listingId) return false\n return (purchases ?? []).some(\n (purchase) =>\n purchase?.listingId === listingId && purchaseEntitlesOrg(purchase, actor),\n )\n}\n\n/**\n * Every org id these purchases license for `listingId`, in document order.\n *\n * What the console renders so a buyer can see WHICH workspace a licence they\n * paid for belongs to (AGL-2331) — the question that has no answer at all\n * while entitlement is person-scoped, and the one an agency has to answer\n * before deciding whether it needs another.\n *\n * Legacy person-scoped purchases contribute no org id, because they name\n * none; a caller rendering this list has to say so rather than invent one.\n */\nexport function licensedOrgIdsFor(\n purchases: readonly (PurchaseLiveness | null | undefined)[] | null | undefined,\n listingId: string,\n): string[] {\n const seen: string[] = []\n for (const purchase of purchases ?? []) {\n if (purchase?.listingId !== listingId || !isLivePurchase(purchase)) continue\n const orgId = purchase?.buyerOrgId\n if (typeof orgId === 'string' && orgId && !seen.includes(orgId)) {\n seen.push(orgId)\n }\n }\n return seen\n}\n\n"],"names":["isFirstPartyMediaSrc","MEDIA_REF_PREFIX","marketplaceMinPriceUsd","offeredPluginVersion","isListingBrowsable","isListingDeleted","isPrivateListing","LISTING_CLIENT_WRITABLE_FIELDS","LISTING_UNPERSISTED_FIELDS","listingArtifactType","PUBLISHER_HANDLE_PATTERN","isValidPublisherHandle","handle","test","ARTIFACT_TYPE_LABELS","INSTALL_TARGETS","LISTING_CATEGORIES","resolveOrgInstallSummary","resolvePluginInstallState","resolveUninstallTargets","listingArtifactLabel","listing","installTargetsFor","resolveInstallPlan","targeting","hosts","targets","canOrgPin","includes","canHostPin","scope","allHostIds","map","hostId","selectedHostIds","VERIFICATION_BLOCK_MESSAGES","VERIFICATION_DECLINE_COOLDOWN_DAYS","timestampMs","verificationRequestBlock","isVersionApproved","version","reviewState","installsUnreviewedFallback","viewerOrgId","revocation","profileId","Boolean","String","latestVersion","newestApprovedVersion","versions","approved","filter","entry","length","reduce","best","publishedAt","toMillis","missingPublicListingContent","missing","description","trim","push","readme","license","LISTING_README_MAX_CHARS","LISTING_MAX_SCREENSHOTS","HTTPS_URL","LISTING_IMAGE_ERROR","LISTING_URL_MAX_CHARS","isListingImageValue","value","isPublisherAvatarValue","startsWith","validateListingContent","input","content","key","undefined","ok","error","logoUrl","screenshots","Array","isArray","some","url","categories","PUBLISHER_SOCIAL_HOSTS","githubUrl","xUrl","linkedinUrl","SUPPORT_EMAIL","validatePublisherProfileContent","avatarUrl","urlKeys","host","URL","hostname","toLowerCase","allowed","endsWith","supportEmail","safePublisherHref","safePublisherImageSrc","src","MARKETPLACE_PLATFORM_FEE_PERCENT","MARKETPLACE_PLATFORM_FEE_PERCENT_FREE_PLAN","MARKETPLACE_MAX_PRICE_USD","MARKETPLACE_MIN_PRICE_USD","marketplacePriceRefusal","priceUsd","Number","isFinite","PORTABLE_COMPONENT_ID_ALLOWLIST","MARKETPLACE_COMPONENT_ID_ALLOWLIST","PORTABLE_EMAIL_COMPONENT_ID_ALLOWLIST","MARKETPLACE_EMAIL_COMPONENT_ID_ALLOWLIST","PORTABLE_EMAIL_STARTER_COMPONENT_ID_ALLOWLIST","MARKETPLACE_EMAIL_STARTER_COMPONENT_ID_ALLOWLIST","sanitizePortableDefinition","sanitizeMarketplaceDefinition","portableDefinitionToNested","marketplaceDefinitionToNested","PORTABLE_SAFE_HREF","MARKETPLACE_SAFE_HREF","PORTABLE_SAFE_SRC","MARKETPLACE_SAFE_SRC","PORTABLE_DEFINITION_MAX_BYTES","MARKETPLACE_DEFINITION_MAX_BYTES","ARTIFACT_INSTALL_RESULT","plugin","component","template","layout","datasetSchema","emailTemplate","emailStarter","theme","siteStarter","listingInclusions","options","type","rows","label","tone","reviewedVersion","isLivePurchase","purchase","refundedAt","hasLivePurchaseOf","purchases","listingId","purchaseEntitlesOrg","actor","purchaseOrgId","buyerOrgId","orgId","uid","buyerUid","hasOrgLicenceOf","licensedOrgIdsFor","seen"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;CAIC,GAED,6EAA6E;AAC7E,2EAA2E;AAC3E,8EAA8E;AAC9E,8EAA8E;AAC9E,SACEA,oBAAoB,EACpBC,gBAAgB,QACX,mCAAkC;AACzC,SAASC,sBAAsB,QAAQ,2BAAuB;AAG9D,SACEC,oBAAoB,QAEf,yCAAwC;AAC/C,4EAA4E;AAC5E,6EAA6E;AAC7E,0EAA0E;AAC1E,0EAA0E;AAC1E,2EAA2E;AAC3E,4EAA4E;AAC5E,2EAA2E;AAC3E,qDAAqD;AACrD,SACEC,kBAAkB,EAClBC,gBAAgB,EAChBC,gBAAgB,EAChBC,8BAA8B,EAC9BC,0BAA0B,EAC1BC,mBAAmB,QACd,0BAAsB;AAE7B,SACEL,kBAAkB,EAClBC,gBAAgB,EAChBC,gBAAgB,EAChBC,8BAA8B,EAC9BC,0BAA0B,EAC1BC,mBAAmB,KACpB;AA4DD;;;;;CAKC,GACD,OAAO,MAAMC,2BAA2B,oCAAmC;AAE3E,OAAO,SAASC,uBAAuBC,MAAc;IACnD,OAAOF,yBA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,CAACF,WAAW,OAAO;IACvB,OAAO,CAACD,oBAAAA,YAAa,EAAE,EAAElE,IAAI,CAC3B,CAAC+D,WACCA,CAAAA,4BAAAA,SAAUI,SAAS,MAAKA,aAAaC,oBAAoBL,UAAUM;AAEzE;AAEA;;;;;;;;;;CAUC,GACD,OAAO,SAASO,kBACdV,SAA8E,EAC9EC,SAAiB;IAEjB,MAAMU,OAAiB,EAAE;IACzB,KAAK,MAAMd,YAAYG,oBAAAA,YAAa,EAAE,CAAE;QACtC,IAAIH,CAAAA,4BAAAA,SAAUI,SAAS,MAAKA,aAAa,CAACL,eAAeC,WAAW;QACpE,MAAMS,QAAQT,4BAAAA,SAAUQ,UAAU;QAClC,IAAI,OAAOC,UAAU,YAAYA,SAAS,CAACK,KAAKvI,QAAQ,CAACkI,QAAQ;YAC/DK,KAAKpG,IAAI,CAAC+F;QACZ;IACF;IACA,OAAOK;AACT"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/marketplace/src/lib/model/marketplace.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 * Marketplace marketplace v1 (AGL-44): shared types + the server-side\n * sanitization pass that gates publishing a host component definition as a\n * public listing. Pure data module — safe to import from API routes.\n */\n\n// The leaf module, not a barrel: this model is reached from both the browser\n// and API routes, and `@aglyn/aglyn` carries `createContext` (illegal in a\n// Server Component) while `@aglyn/aglyn/server` carries `node:fs` (illegal in\n// the browser). Neither is safe from here; the deep path has no dependencies.\nimport {\n isFirstPartyMediaSrc,\n MEDIA_REF_PREFIX,\n} from '@aglyn/aglyn/app-utils/media-ref'\nimport { marketplaceMinPriceUsd } from './listing-price-floor'\nimport type { InstallableArtifactType as MarketplaceArtifactType } from '@aglyn/aglyn/app-utils/artifact-provenance'\nimport type { ListingVerificationRequest } from './listing-verification'\nimport {\n offeredPluginVersion,\n type PluginRevocation,\n} from '@aglyn/aglyn/app-utils/plugin-manifest'\n// Visibility lives in core (AGL-876), for the same reason the artifact-type\n// union and the verification policy do: the console's listing route asks the\n// question and `scope:app` may not depend on `aglyn:addons`. Imported AND\n// re-exported — `installTargetsFor` and `listingArtifactLabel` below call\n// `listingArtifactType` locally, and a bare `export … from` binds nothing.\n// The write-deny classification (AGL-1361) rides along for the same reason:\n// it is a statement about the fields this policy reads, and the guard that\n// enforces it lives in core beside the rules parser.\nimport {\n isListingBrowsable,\n isListingDeleted,\n isPrivateListing,\n LISTING_CLIENT_WRITABLE_FIELDS,\n LISTING_UNPERSISTED_FIELDS,\n listingArtifactType,\n} from './listing-visibility'\n\nexport {\n isListingBrowsable,\n isListingDeleted,\n isPrivateListing,\n LISTING_CLIENT_WRITABLE_FIELDS,\n LISTING_UNPERSISTED_FIELDS,\n listingArtifactType,\n}\n\n/**\n * `profiles/{uid}` — a person's public identity.\n *\n * NOT a publisher identity as of AGL-652: publishing is org-only, and the\n * marketplace presence lives on `publisherProfiles/{orgId}` below. This doc\n * survives because it is also the support forum's author identity, which\n * renders poster names from `displayName`.\n */\nexport interface MarketplaceProfile {\n handle: string\n displayName: string\n bio?: string\n avatarUrl?: string\n}\n\n/**\n * `publisherProfiles/{orgId}` — an organization's marketplace presence\n * (AGL-652). Publishing is org-only: an org publishes, an org gets paid, and\n * the org is who buyers see. Keyed by org id so authorization is a plain org\n * role check with no ownership indirection.\n *\n * `stripeAccountId` / `stripeChargesEnabled` / `stripeAccountLivemode` are\n * written only by the Connect route via the Admin SDK and are frozen from\n * client writes by the rules — they decide who receives money, and\n * `stripeAccountLivemode` is a gate INPUT (AGL-2471), so a client that could\n * write it could re-open the hole by asserting its own readiness.\n */\nexport interface MarketplacePublisherProfile {\n /** Unique marketplace handle; reserved in `publisherHandles/{handle}`. */\n handle: string\n displayName: string\n bio?: string\n avatarUrl?: string\n website?: string\n /** Server-only. */\n stripeAccountId?: string\n /** Server-only; true once Connect onboarding can accept charges. */\n stripeChargesEnabled?: boolean\n /**\n * Server-only; which Stripe world the account belongs to (AGL-2471).\n * `true` = live, `false` = test, ABSENT = never established — and on a live\n * deployment absent refuses the sale, because a payout destination whose\n * mode nobody verified is exactly what shipped three unusable storefronts.\n */\n stripeAccountLivemode?: boolean\n}\n\n/**\n * `publisherHandles/{handle}` — uniqueness reservation for publisher handles,\n * mirroring `orgSlugs` (AGL-652). Without it two publishers could claim the\n * same handle, which the marketplace URL space cannot represent. `movedTo`\n * tombstones a renamed handle so old links can still resolve.\n */\nexport interface PublisherHandleReservation {\n orgId: string\n movedTo?: string\n}\n\n/**\n * Publisher handles share the org-slug shape: 3–30 chars, lowercase\n * alphanumeric plus internal hyphens. Single source of truth — the two\n * marketplace pages historically applied two subtly different regexes to the\n * same field (AGL-653).\n */\nexport const PUBLISHER_HANDLE_PATTERN = /^[a-z0-9][a-z0-9-]{1,28}[a-z0-9]$/\n\nexport function isValidPublisherHandle(handle: string): boolean {\n return PUBLISHER_HANDLE_PATTERN.test(handle)\n}\n\n/**\n * `marketplaceListings/{listingId}` — public component listing. Version\n * snapshots live in the `versions/{n}` subcollection; installs copy a pinned\n * version into `hosts/{hostId}/components` so the existing drawer/graft\n * pipeline applies unchanged.\n */\nexport interface MarketplaceListing {\n profileId: string\n displayName: string\n description?: string\n category?: string\n /**\n * What this listing publishes (AGL-654). One discriminator for every\n * artifact type — the previous scheme split across two orthogonal fields\n * (`type: 'component'|'plugin'` plus a separate `kind: 'template'`), so a\n * template was \"kind template with no type\" and each installer branched on\n * whichever field it happened to care about. That does not survive adding\n * layouts, dataset schemas and email templates.\n *\n * Read it through `listingArtifactType()`, never directly — listings\n * written before this field still carry only the legacy pair.\n */\n artifactType?: MarketplaceArtifactType\n /** @deprecated Legacy discriminator; use `artifactType` (AGL-654). */\n type?: 'component' | 'plugin'\n /** @deprecated Legacy discriminator; use `artifactType` (AGL-654). */\n kind?: 'template'\n latestVersion: number | string\n /** Plugin manifest id, for `type: 'plugin'` listings (AGL-45). */\n pluginId?: string\n /** One-time price in whole USD; 0/absent = free (AGL-46). */\n priceUsd?: number\n deletedAt?: unknown\n // Listing content (AGL-430, Strapi Market parity) — publisher-authored,\n // rendered on the marketplace detail page. All optional; validated by\n // validateListingContent on the API path and SANITIZED at render time\n // (the doc is publisher-writable, so renderers never trust it).\n logoUrl?: string\n screenshots?: string[]\n /** Markdown documentation shown on the listing page (no raw HTML). */\n readme?: string\n homepageUrl?: string\n repositoryUrl?: string\n /** SPDX-ish license label, e.g. \"MIT\". */\n license?: string\n categories?: string[]\n /**\n * Marketplace review lifecycle (AGL-432). Absent = legacy listing,\n * treated as 'listed'. New plugin listings start 'submitted'; staff move\n * them through the queue. Only 'listed'/'verified' (or legacy) plugin\n * listings appear in browse for non-owners.\n */\n reviewStatus?: ListingReviewStatus\n /**\n * The publisher's standing ask for the Verified badge (AGL-1217).\n *\n * Its own field, never a `reviewStatus` member — see\n * {@link ListingVerificationRequest}. Server-owned: the publisher route only\n * moves it to `pending`/`withdrawn`, and only staff can decide it. Asking\n * never grants anything; the checklist gate on `verify` stays the one route\n * to the badge.\n */\n verificationRequest?: ListingVerificationRequest\n // Server-managed. These were written by the publish/install/review paths\n // but never declared, so callers reached for `as any` (AGL-654).\n /** Publishing org id — the publisher profile's doc id (AGL-652). */\n publisherOrgId?: string\n /** Source component for a `component` listing. */\n sourceComponentId?: string\n /** Source site for a `template` listing. */\n sourceHostId?: string\n /**\n * Source site for a `siteStarter` listing (AGL-4049): the one-listing-per-\n * source key `publish-starter` looks up. Its own field, never `sourceHostId`:\n * the template, layout and theme doors write that one and key on it with a\n * `limit(1)`, so a shared key would cross a site's starter with its template.\n */\n sourceStarterHostId?: string\n /**\n * The platform published it (AGL-4049). Server-owned and ordering only: the\n * starter picker lists these first. No door, price or checkout branches on\n * it; the seed and staff write it, a publish never does.\n */\n official?: boolean\n /**\n * A site starter's facets (AGL-4049), stamped from its payload by\n * `siteStarterFacetFields` so a starter search can match them. Server-owned:\n * they describe the stored version, so a client rewrite would list a\n * starter under a kind, theme or page count it does not create.\n */\n starterKind?: string | null\n starterBase?: string | null\n starterFonts?: string | null\n starterPages?: number\n starterMode?: 'base' | 'ai'\n /** Incremented by the install API; frozen from client writes. */\n installCount?: number\n /**\n * How many installs are LIVE right now — `installCount`'s sibling, and\n * undeclared here until AGL-1420 went looking for it.\n *\n * That omission was the whole bug. AGL-1361's coverage guard builds the\n * listing's field universe from this interface, the rules deny-list and the\n * resolvers, so a server-owned field in none of the three is not classified\n * as exposed — it is INVISIBLE to the guard, which is a worse failure than\n * being classified wrongly. `installCount` was denied and this was not, so\n * the sibling counter a publisher-org owner/admin could write was the one\n * the browse grid and the listing header print to buyers.\n *\n * Written by the install/uninstall routes and by AGL-1419's derivation.\n */\n activeInstalls?: number\n /**\n * AGL-1419's derived-count cache: the pin count as last verified, the wall\n * clock it was verified at, and the per-version split.\n *\n * Server-owned for a stronger reason than the counters themselves. They are\n * not merely a number that could be wrong — `verifiedLivePins` treats the\n * triple as FRESH when `pinnedActiveInstalls === activeInstalls` and the\n * timestamp is inside the TTL, and then returns `pinnedVersionInstalls`\n * without querying anything. A client that could write all four could pin\n * the cache open on numbers it chose and suppress the re-derivation that\n * exists to bring a count back down.\n */\n pinnedActiveInstalls?: number\n pinsVerifiedAtMs?: number\n pinnedVersionInstalls?: Record<string, number>\n previewImageUrl?: string\n screenCount?: number\n versionHistory?: Array<{ version: number | string; publishedAt?: unknown }>\n createdAt?: unknown\n updatedAt?: unknown\n /** Staff review audit (AGL-432); server-owned (AGL-651). */\n reviewedBy?: string\n reviewedAt?: unknown\n rejectionReason?: string\n /**\n * What the marketplace lists query by (AGL-3321), derived by the server\n * from the fields above after every write (`listingQueryFields`,\n * `refreshListingQueryFields`) and denied to clients.\n */\n nameLower?: string\n nameTokens?: string[]\n nameReversed?: string\n browseAudience?: string[]\n browseTokens?: string[]\n takenDown?: boolean\n /**\n * The publishing workspace is locked (AGL-3365): the listing is out of\n * browse, search and its page until the lift clears it. Written only by\n * the lockdown's marketplace participant, which clears exactly the\n * listings it stamped; server-owned.\n */\n workspaceLockedAt?: unknown\n}\n\n/**\n * Everything an org can publish to the marketplace (AGL-654): every kind of\n * content the platform can install.\n *\n * The union is core's `InstallableArtifactType` — installed content is read by\n * surfaces that are not the marketplace, through the provenance stamp — and is\n * re-exported here under the name publishing code has always used.\n */\nexport type { MarketplaceArtifactType }\n\nexport {\n ARTIFACT_TYPE_LABELS,\n INSTALL_TARGETS,\n type InstallPin,\n type InstallTarget,\n LISTING_CATEGORIES,\n type OrgInstallSite,\n type OrgInstallSummary,\n type PluginInstallState,\n resolveOrgInstallSummary,\n resolvePluginInstallState,\n resolveUninstallTargets,\n type UninstallTarget,\n} from './marketplace-catalog'\nimport { ARTIFACT_TYPE_LABELS, INSTALL_TARGETS, type InstallPin, type InstallTarget, LISTING_CATEGORIES } from './marketplace-catalog'\n\n/** The friendly artifact-type label for a listing (AGL-864). */\nexport function listingArtifactLabel(listing: {\n artifactType?: string\n type?: string\n kind?: string\n}): string {\n return ARTIFACT_TYPE_LABELS[listingArtifactType(listing)] ?? 'Component'\n}\n\n/** Targets a listing can be installed to, defaulting to host-only. */\nexport function installTargetsFor(listing: {\n artifactType?: string\n type?: string\n kind?: string\n}): readonly InstallTarget[] {\n return INSTALL_TARGETS[listingArtifactType(listing)] ?? ['host']\n}\n\n\n/** How the admin chose to target an install from the org marketplace. */\nexport type InstallTargeting = 'all-sites' | 'selected-sites'\n\n/** One concrete install operation: an org pin, or a pin on a named host. */\nexport interface InstallPlanStep {\n scope: InstallTarget\n /** Present iff `scope === 'host'`. */\n hostId?: string\n}\n\n/**\n * Turns a targeting choice into the concrete install operations for a listing\n * (AGL-773), honoring what each artifact type physically supports (see\n * {@link INSTALL_TARGETS}).\n *\n * The rules aren't uniform, and the picker must not promise what an artifact\n * can't do:\n * - **Org-pinnable** (plugin, datasetSchema) + \"all sites\" → a SINGLE org pin,\n * which also covers sites created later.\n * - **Host-scoped** (component, template, layout, emailTemplate) has no org\n * pin, so \"all sites\" fans out to every CURRENT host — new sites are NOT\n * covered automatically. The UI has to say so.\n * - \"Selected sites\" is always host pins, even for an org-pinnable artifact:\n * the admin named specific sites, so honor that literally — UNLESS the\n * artifact can't host-pin at all (datasetSchema), where the per-site choice\n * is meaningless and collapses to the org pin.\n */\nexport function resolveInstallPlan(\n listing: { artifactType?: string; type?: string; kind?: string },\n targeting: InstallTargeting,\n hosts: {\n selectedHostIds: readonly string[]\n allHostIds: readonly string[]\n },\n): InstallPlanStep[] {\n const targets = installTargetsFor(listing)\n const canOrgPin = targets.includes('org')\n const canHostPin = targets.includes('host')\n if (targeting === 'all-sites') {\n if (canOrgPin) return [{ scope: 'org' }]\n return hosts.allHostIds.map((hostId) => ({ scope: 'host', hostId }))\n }\n // selected-sites\n if (!canHostPin) return [{ scope: 'org' }]\n return hosts.selectedHostIds.map((hostId) => ({ scope: 'host', hostId }))\n}\n\nexport type ListingReviewStatus =\n | 'submitted'\n | 'in_review'\n | 'listed'\n | 'verified'\n | 'rejected'\n\n/**\n * Verification requests lived in core from AGL-1217 because the console's\n * STAFF REVIEW ROUTE needed the policy and `scope:app` may not depend on\n * `aglyn:addons`. That route is the plugin's own surface since `38c4b533c`,\n * so the reason expired with it and the module came home (AGL-3080).\n *\n * Still re-exported from here, which is the part that did not change:\n * publishing code keeps one import site whether the policy is a lib away or\n * a file away.\n */\nexport {\n VERIFICATION_BLOCK_MESSAGES,\n VERIFICATION_DECLINE_COOLDOWN_DAYS,\n timestampMs,\n verificationRequestBlock,\n} from './listing-verification'\nexport type {\n ListingVerificationRequest,\n TimestampLike,\n VerifiableListing,\n VerificationRequestBlock,\n VerificationRequestState,\n} from './listing-verification'\n\n\n/**\n * Per-VERSION review state (AGL-966).\n *\n * Approval is a statement about specific bytes, so it lives on the version\n * doc beside the verifier verdict and the review checklist — both already\n * keyed to sha256. It used to live on the listing, which meant a publisher\n * could get v1.0.0 verified and then ship v1.0.1 containing anything: the\n * listing kept its status, the queue never surfaced the update, and\n * installs resolved `latestVersion`.\n */\nexport type PluginVersionReviewState = 'pending' | 'approved' | 'rejected'\n\n/**\n * The LISTING's cached summary of the version it currently offers.\n *\n * A different field from the one above and a different set of values, which is\n * the whole reason it is written down here. `reviewState` lives on the version\n * document and is a verdict about specific bytes;\n * `latestVersionReviewState` lives on the LISTING and exists so browse cards\n * and the listing page can answer \"have the bytes on offer been read?\" without\n * a per-listing subcollection read.\n *\n * `'revoked'` is the value that only ever appears HERE. A kill is not a review\n * verdict: the version keeps the `'approved'` it earned — the staff surface\n * shows \"Disabled\" beside that verdict rather than instead of it, because\n * collapsing the two would erase what the publisher earned — and it is only\n * this listing-level summary that flips, so the \"Reviewed\" chip drops and the\n * caution alert raises while the audit trail stays intact.\n *\n * The practical consequence, and the reason this is a type rather than a\n * comment: the staff review QUEUE keys on the version's `reviewState`, never\n * on this field. Were it to key on this one, every revoked version would\n * reappear in the queue indistinguishable from one awaiting its first review,\n * and a reviewer acting in good faith on a queue they trusted could approve a\n * version somebody had deliberately killed. The two fields are not\n * interchangeable and this names why.\n */\nexport type ListingLatestVersionReviewState =\n | PluginVersionReviewState\n | 'revoked'\n\n\nexport interface ReviewableVersion {\n version?: string\n reviewState?: string\n publishedAt?: { toMillis?: () => number } | null\n}\n\n/** Only approved bytes may be installed. Absent state is NOT approval. */\nexport function isVersionApproved(\n version: { reviewState?: string } | null | undefined,\n): boolean {\n return version?.reviewState === 'approved'\n}\n\n/**\n * Whether an install would hand the viewer UNREVIEWED bytes (AGL-1083).\n *\n * `install-plugin` deliberately lets a publisher install their own\n * unapproved version — you cannot test a version you cannot install, and\n * the AGL-969 checklist asks them to confirm they tested these exact bytes\n * on a site they control. The route reaches that case through\n * `newestApprovedVersion(...) ?? fallback`, where the fallback is\n * `latestVersion` and applies ONLY when the caller owns the listing and no\n * approved version exists at all.\n *\n * Lives here rather than in the listing component because the UI has to\n * describe exactly what the route will do. Two independent readings of\n * \"would this be unreviewed?\" is how the affordance ends up warning about\n * the wrong installs, or staying silent on the right ones.\n *\n * The route's `newest` is `newestInstallableVersion` since AGL-2368 — a\n * revoked version is no longer a candidate, so it no longer suppresses the\n * fallback either. `revocation` is optional because most callers have none;\n * without it this asks the pre-AGL-2368 question, which is the same answer\n * whenever the mirror is current.\n */\nexport function installsUnreviewedFallback(\n listing:\n | {\n profileId?: string\n latestVersion?: string | number\n latestApprovedVersion?: string | number\n }\n | null\n | undefined,\n viewerOrgId: string | null | undefined,\n revocation?: PluginRevocation | null,\n): boolean {\n if (!listing?.profileId || !viewerOrgId) return false\n // Only the publishing org gets the fallback; everyone else is refused.\n if (listing.profileId !== viewerOrgId) return false\n // An INSTALLABLE version exists → the route serves THAT, however much newer\n // the pending one is. Not an unreviewed install. Reading approval alone got\n // this backwards for a revoked listing: the route would fall back to\n // `latestVersion` for the owner and hand over unreviewed bytes, while the\n // page said nothing, because a stopped version still counted as approved.\n if (offeredPluginVersion(listing, revocation)) return false\n return Boolean(String(listing.latestVersion ?? ''))\n}\n\n/**\n * The version a fresh install should pin: newest APPROVED, never\n * `latestVersion`. A pending update is simply not offered, so publishing\n * cannot ship code past review, and the previously approved version keeps\n * installing while the new one waits.\n */\nexport function newestApprovedVersion<T extends ReviewableVersion>(\n versions: readonly T[],\n): T | null {\n const approved = versions.filter((entry) => isVersionApproved(entry))\n if (!approved.length) return null\n return approved.reduce((best, entry) =>\n (entry.publishedAt?.toMillis?.() ?? 0) >\n (best.publishedAt?.toMillis?.() ?? 0)\n ? entry\n : best,\n )\n}\n\n/**\n * What a listing is still missing before it can face the marketplace\n * (AGL-968/994).\n *\n * A private plugin is allowed to be undocumented — its only audience already\n * knows what it is and why it exists. A public one is not: description,\n * README and license are what a stranger deciding whether to run your code\n * has to go on, and they are exactly the fields the review checklist asks\n * about. So going public is gated on the METADATA, never on a re-review —\n * approval is a statement about bytes, and the bytes did not change.\n *\n * Returns the human field names, so the caller can say what to fix rather\n * than just refusing.\n */\nexport function missingPublicListingContent(listing: {\n description?: string\n readme?: string\n license?: string\n}): string[] {\n const missing: string[] = []\n if (!listing.description?.trim()) missing.push('a description')\n if (!listing.readme?.trim()) missing.push('a README')\n if (!listing.license?.trim()) missing.push('a license')\n return missing\n}\n\n\nexport const LISTING_README_MAX_CHARS = 20_000\nexport const LISTING_MAX_SCREENSHOTS = 6\n\nconst HTTPS_URL = /^https:\\/\\/[^\\s]+$/\n\n/**\n * The message every listing IMAGE field returns when it is refused. Names the\n * remedy, because \"must be an https URL\" was true of the value the publisher\n * just typed and told them nothing.\n */\nexport const LISTING_IMAGE_ERROR =\n 'must be an image from your media library — paste a link and the people ' +\n 'browsing your listing would be loading it from a server you control'\n\n/** Length cap shared by every listing URL field. */\nconst LISTING_URL_MAX_CHARS = 500\n\n/**\n * Whether a listing image field is one we will store (AGL-1701).\n *\n * Listing artwork is the one publisher-supplied value that OTHER orgs' users\n * load. It is also, established while fixing this, gated by nothing: review\n * is a statement about a version's bytes (AGL-966), the staff review route\n * never projects `logoUrl`/`screenshots` so a reviewer cannot see them even\n * if the checklist asked, and `update-listing` writes them at any time\n * without touching `reviewStatus` — so a listing can pass review with benign\n * artwork and swap it afterwards while still reading `verified`.\n *\n * Constraining the INPUT rather than sanitizing the output is the whole\n * point: the render sites are three components and an `og:image`, and the\n * next one added would not know to sanitize.\n */\nfunction isListingImageValue(value: unknown): value is string {\n return (\n typeof value === 'string' &&\n value.length <= LISTING_URL_MAX_CHARS &&\n isFirstPartyMediaSrc(value)\n )\n}\n\n/**\n * Whether a value may be a publisher's LOGO (AGL-3260).\n *\n * The listing-image rule, minus the private `media:` reference. A listing's\n * logo may be one because a caller that signs its own links can resolve it;\n * nothing that renders a publisher avatar signs anything, so a reference\n * there would store a value every render site must turn back into the\n * fallback initial — a logo that looks saved and is never seen.\n *\n * `startsWith` rather than `isMediaRef`, for the reason that predicate's own\n * neighbour gives: negating a `value is string` guard on a value already\n * known to be a string leaves the else branch `never`.\n */\nfunction isPublisherAvatarValue(value: unknown): value is string {\n return isListingImageValue(value) && !value.startsWith(MEDIA_REF_PREFIX)\n}\n\n/**\n * Validates publisher-editable listing content (AGL-430). Returns the\n * normalized subset to persist, or an error. Shared by publish and the\n * update-listing action so both paths accept exactly the same shapes.\n *\n * IMAGE fields and LINK fields are validated differently (AGL-1701).\n * `homepageUrl` and `repositoryUrl` stay any-https: they are anchors a reader\n * chooses to follow, and a publisher's homepage living on the publisher's\n * domain is the entire point of the field. `logoUrl` and `screenshots` are\n * `<img src>`, which fetches with no such choice, so those are held to\n * first-party media.\n */\nexport function validateListingContent(input: Record<string, unknown>): {\n ok: boolean\n error?: string\n content?: Partial<MarketplaceListing>\n} {\n const content: Partial<MarketplaceListing> = {}\n for (const key of ['homepageUrl', 'repositoryUrl'] as const) {\n const value = input[key]\n if (value === undefined || value === '') continue\n if (\n typeof value !== 'string' ||\n !HTTPS_URL.test(value) ||\n value.length > LISTING_URL_MAX_CHARS\n ) {\n return { ok: false, error: `${key} must be an https URL` }\n }\n content[key] = value\n }\n const logoUrl = input['logoUrl']\n if (logoUrl !== undefined && logoUrl !== '') {\n if (!isListingImageValue(logoUrl)) {\n return { ok: false, error: `logoUrl ${LISTING_IMAGE_ERROR}` }\n }\n content.logoUrl = logoUrl\n }\n const screenshots = input['screenshots']\n if (screenshots !== undefined) {\n if (\n !Array.isArray(screenshots) ||\n screenshots.length > LISTING_MAX_SCREENSHOTS ||\n screenshots.some((url) => !isListingImageValue(url))\n ) {\n return {\n ok: false,\n error:\n `screenshots must be up to ${LISTING_MAX_SCREENSHOTS} images, and ` +\n `each ${LISTING_IMAGE_ERROR}`,\n }\n }\n content.screenshots = screenshots as string[]\n }\n const readme = input['readme']\n if (readme !== undefined) {\n if (typeof readme !== 'string' || readme.length > LISTING_README_MAX_CHARS) {\n return {\n ok: false,\n error: `readme must be markdown up to ${LISTING_README_MAX_CHARS} chars`,\n }\n }\n if (readme.trim()) content.readme = readme\n }\n const license = input['license']\n if (license !== undefined && license !== '') {\n if (typeof license !== 'string' || license.length > 40) {\n return { ok: false, error: 'license must be a short label (max 40)' }\n }\n content.license = license\n }\n const categories = input['categories']\n if (categories !== undefined) {\n if (\n !Array.isArray(categories) ||\n categories.length > 3 ||\n categories.some((entry) => !LISTING_CATEGORIES.includes(String(entry)))\n ) {\n return {\n ok: false,\n error: 'categories must be up to 3 entries from the fixed taxonomy',\n }\n }\n content.categories = categories.map(String)\n }\n return { ok: true, content }\n}\n\n/**\n * Publisher-profile fields beyond the identity trio (AGL-1009): the logo,\n * the support contact, and a FIXED set of external links. Fixed on purpose —\n * the storefront renders each as a known icon, and a free-form list would\n * turn the trust panel into a link farm.\n */\nexport interface PublisherProfileContent {\n avatarUrl?: string\n website?: string\n supportEmail?: string\n supportUrl?: string\n githubUrl?: string\n xUrl?: string\n linkedinUrl?: string\n}\n\n/** Social keys whose URL must live on the network's own host. */\nconst PUBLISHER_SOCIAL_HOSTS: Record<string, readonly string[]> = {\n githubUrl: ['github.com'],\n xUrl: ['x.com', 'twitter.com'],\n linkedinUrl: ['linkedin.com'],\n}\n\nconst SUPPORT_EMAIL = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/\n\n/**\n * Validates the publisher-profile extras (AGL-1009), sharing\n * `validateListingContent`'s discipline on both of its halves: the LINKS are\n * https only and length capped, the LOGO is first-party media (AGL-3260).\n * Validated on the save route (server-owned like the handle — no client\n * write path carries these). An explicit empty string comes back as `''` so\n * the save route can distinguish \"clear this field\" from \"left untouched\".\n */\nexport function validatePublisherProfileContent(\n input: Record<string, unknown>,\n): { ok: boolean; error?: string; content?: PublisherProfileContent } {\n const content: PublisherProfileContent = {}\n /**\n * THE LOGO IS AN IMAGE FIELD, NOT A LINK FIELD (AGL-3260).\n *\n * It was validated as a link — any https URL — and the panel that edits it\n * only ever offers the media library, which since AGL-1215 hands back the\n * media-id-keyed CDN path (`/api/media/cdn/…`) rather than a storage URL.\n * A root-relative path is not an https URL, so the one value the form could\n * produce was the one value the route refused, and the publisher was told\n * their logo was malformed.\n *\n * Held to the same first-party rule as `logoUrl` and `screenshots` for the\n * reason given there (AGL-1701): this is an `<img src>` that other orgs'\n * users load on every listing's Publisher card, so it fetches with no\n * reader choice. That makes the fix a TIGHTENING as well — a third-party\n * `https://cdn.publisher.example/logo.png` no longer passes.\n */\n const avatarUrl = input['avatarUrl']\n if (avatarUrl !== undefined) {\n if (avatarUrl === '') {\n content.avatarUrl = ''\n } else if (!isPublisherAvatarValue(avatarUrl)) {\n return { ok: false, error: `avatarUrl ${LISTING_IMAGE_ERROR}` }\n } else {\n content.avatarUrl = avatarUrl\n }\n }\n const urlKeys = [\n 'website',\n 'supportUrl',\n 'githubUrl',\n 'xUrl',\n 'linkedinUrl',\n ] as const\n for (const key of urlKeys) {\n const value = input[key]\n if (value === undefined) continue\n if (value === '') {\n content[key] = ''\n continue\n }\n // The same https-or-nothing rule as listing URLs: `javascript:`, `data:`\n // and plain http all fail the one test.\n if (typeof value !== 'string' || !HTTPS_URL.test(value) || value.length > 500) {\n return { ok: false, error: `${key} must be an https URL` }\n }\n const hosts = PUBLISHER_SOCIAL_HOSTS[key]\n if (hosts) {\n let host = ''\n try {\n host = new URL(value).hostname.toLowerCase()\n } catch {\n return { ok: false, error: `${key} must be an https URL` }\n }\n if (!hosts.some((allowed) => host === allowed || host.endsWith(`.${allowed}`))) {\n return { ok: false, error: `${key} must link to ${hosts[0]}` }\n }\n }\n content[key] = value\n }\n const supportEmail = input['supportEmail']\n if (supportEmail !== undefined) {\n if (supportEmail === '') {\n content.supportEmail = ''\n } else if (\n typeof supportEmail !== 'string' ||\n supportEmail.length > 200 ||\n !SUPPORT_EMAIL.test(supportEmail)\n ) {\n return { ok: false, error: 'supportEmail must be an email address' }\n } else {\n content.supportEmail = supportEmail\n }\n }\n return { ok: true, content }\n}\n\n/**\n * Render-time guard for publisher links (AGL-1009): only an `https://` URL\n * is ever emitted as an href. The save route already refuses anything else,\n * but the doc is client-updatable on its cosmetic fields historically, so\n * the renderer must not trust stored data it did not write.\n */\nexport function safePublisherHref(url: unknown): string | undefined {\n return typeof url === 'string' && /^https:\\/\\//i.test(url) && url.length <= 500\n ? url\n : undefined\n}\n\n/**\n * The same guard for the publisher's LOGO (AGL-3260), which is an `<img src>`\n * rather than an href and so has a different safe set: the media library's\n * root-relative CDN path is the value the picker produces and must render,\n * and a third-party https URL — fine as a link the reader chooses to follow —\n * is exactly what must not be fetched on their behalf.\n */\nexport function safePublisherImageSrc(src: unknown): string | undefined {\n return isPublisherAvatarValue(src) ? src : undefined\n}\n\n/**\n * Platform revenue share on paid listings (AGL-46) — UI COPY ONLY. The\n * checkout route prices from the `marketplaceFeePct` ENTITLEMENT\n * (`resolveMarketplaceFeePct`, AGL-1543), which resolves the effective\n * plan and per-org overrides; these constants exist for seller-facing\n * copy and must be kept in step with the plan table.\n */\nexport const MARKETPLACE_PLATFORM_FEE_PERCENT = 20\n/** Free-plan publishers pay a higher share. See AGL-1543 note above. */\nexport const MARKETPLACE_PLATFORM_FEE_PERCENT_FREE_PLAN = 30\n/** One-time listing price ceiling (whole USD). */\nexport const MARKETPLACE_MAX_PRICE_USD = 1000\n\n/**\n * One-time listing price FLOOR for a PAID listing (whole USD, AGL-2343).\n *\n * Marketplace checkout is a destination charge with no `application_fee_amount`\n * — deliberately, so the sales tax stays with the platform that owes it\n * (AGL-1544) — which means Stripe debits its fee from the PLATFORM's balance.\n * Stripe's fixed 30¢ dominates at low prices, so under this figure the\n * platform's cut is smaller than the cost of collecting it and every sale is a\n * loss. The floor is the cheapest listing price that still clears the cost of\n * processing it.\n *\n * NOT A CHOSEN NUMBER. `marketplaceMinPriceUsd` derives it from the plan\n * table's lowest take rate and the dearest enabled payment method; this is a\n * re-export so that the routes and the console forms cannot quote different\n * minimums at the same publisher. Zero stays legal — a free listing takes no\n * payment and costs nothing to process.\n */\nexport const MARKETPLACE_MIN_PRICE_USD = marketplaceMinPriceUsd()\n\n/**\n * The refusal message for a listing price, or `undefined` when the price may\n * be published (AGL-2343).\n *\n * ONE VALIDATOR FOR SEVEN DOORS. Each publish route used to inline its own\n * range check against the maximum — and `publish-theme.ts` and\n * `publish-layout.ts` had none at all, so a $250,000 theme was publishable.\n * The doors call this, and `publishPreconditionRefusal` calls it too, so a\n * route that forgets is still covered.\n *\n * Takes the price the route already rounded: a listing price is whole dollars\n * everywhere, and a validator that accepted $2.99 would be validating a number\n * that is never stored.\n */\nexport function marketplacePriceRefusal(priceUsd: number): string | undefined {\n if (!Number.isFinite(priceUsd) || priceUsd < 0) {\n return `Price must be 0 (free) or $${MARKETPLACE_MIN_PRICE_USD}–$${MARKETPLACE_MAX_PRICE_USD} USD`\n }\n if (priceUsd > MARKETPLACE_MAX_PRICE_USD) {\n return `Price must be 0 (free) or $${MARKETPLACE_MIN_PRICE_USD}–$${MARKETPLACE_MAX_PRICE_USD} USD`\n }\n // Zero is not \"below the floor\" — it is the free listing, which takes no\n // payment at all and so costs nothing to process.\n if (priceUsd > 0 && priceUsd < MARKETPLACE_MIN_PRICE_USD) {\n return (\n `A paid listing must be at least $${MARKETPLACE_MIN_PRICE_USD} USD — ` +\n `below that, processing the payment costs more than the platform fee ` +\n `on the sale. Use 0 for a free listing.`\n )\n }\n return undefined\n}\n\n/**\n * The rule a node tree meets before it lands on a canvas that did not author\n * it is core's (`@aglyn/aglyn/app-utils/node-definition-sanitizer`, AGL-2939),\n * under neutral names, because a model-generated tree passes through it too.\n * A publisher reads it as the marketplace's rule, so the marketplace re-exports\n * it under the names its publish routes and its docs use.\n */\nexport {\n PORTABLE_COMPONENT_ID_ALLOWLIST as MARKETPLACE_COMPONENT_ID_ALLOWLIST,\n PORTABLE_EMAIL_COMPONENT_ID_ALLOWLIST as MARKETPLACE_EMAIL_COMPONENT_ID_ALLOWLIST,\n PORTABLE_EMAIL_STARTER_COMPONENT_ID_ALLOWLIST as MARKETPLACE_EMAIL_STARTER_COMPONENT_ID_ALLOWLIST,\n sanitizePortableDefinition as sanitizeMarketplaceDefinition,\n portableDefinitionToNested as marketplaceDefinitionToNested,\n PORTABLE_SAFE_HREF as MARKETPLACE_SAFE_HREF,\n PORTABLE_SAFE_SRC as MARKETPLACE_SAFE_SRC,\n PORTABLE_DEFINITION_MAX_BYTES as MARKETPLACE_DEFINITION_MAX_BYTES,\n type PortableDefinitionNodes as MarketplaceDefinitionNodes,\n} from '@aglyn/aglyn/app-utils/node-definition-sanitizer'\n\n/** One row of the listing detail's `What's included` checklist. */\nexport interface ListingInclusion {\n label: string\n /** Whether the row is a positive inclusion or a stated limit. */\n tone: 'included' | 'note'\n}\n\n/** What each artifact type drops into the org when it installs. */\nconst ARTIFACT_INSTALL_RESULT: Record<MarketplaceArtifactType, string> = {\n plugin: 'A plugin, sandboxed on its own origin with a per-plugin CSP',\n component: 'An editable component you can place on any page',\n template: 'Editable pages you can rework in Besigner',\n layout: 'An editable layout you can apply to any page',\n datasetSchema: 'A new empty dataset with its fields already defined',\n emailTemplate: 'An editable email design you can send campaigns from',\n emailStarter:\n 'A new email in your Email templates list, ready to edit and send',\n theme: 'A theme applied to the site you choose',\n siteStarter: 'A new site, created from these pages and this theme',\n}\n\n/**\n * The `WHAT'S INCLUDED` checklist the marketplace listing mockup shows\n * (AGL-2173), derived entirely from facts the listing already carries.\n *\n * The mockup's own bullets — `12 responsive screens`, `Blog & work\n * layouts` — are publisher-authored prose, and nothing collects them:\n * there is no content manifest on a listing or a version, so counting\n * screens would mean inventing a number. What IS knowable is what the\n * install physically does, where it lands, whether it has been reviewed,\n * and under what licence — which is the question a shopper is asking when\n * they read that box.\n *\n * Ordered decision-first: what you get, then where it goes, then the two\n * facts that most often stop an install.\n */\nexport function listingInclusions(\n listing: {\n artifactType?: string\n type?: string\n kind?: string\n license?: string\n priceUsd?: number\n reviewStatus?: string\n },\n options: { reviewedVersion?: boolean } = {},\n): ListingInclusion[] {\n const type = listingArtifactType(listing)\n const rows: ListingInclusion[] = [\n { label: ARTIFACT_INSTALL_RESULT[type] ?? 'An installable artifact', tone: 'included' },\n ]\n const targets = installTargetsFor(listing)\n rows.push({\n label: targets.includes('org')\n ? 'Installs org-wide, covering sites you add later'\n : 'Installs per site — new sites are not covered automatically',\n // The host-only case is a real limit and the picker already has to say\n // so; softening it here would put the caveat only where nobody reads.\n tone: targets.includes('org') ? 'included' : 'note',\n })\n if (options.reviewedVersion) {\n rows.push({\n label: 'This version passed marketplace review',\n tone: 'included',\n })\n }\n if (listing.license) {\n rows.push({ label: `Licensed ${listing.license}`, tone: 'included' })\n }\n rows.push({\n label: Number(listing.priceUsd ?? 0) > 0\n ? 'A one-time purchase — updates to this listing are included'\n : 'Free, including every future update',\n tone: 'included',\n })\n return rows\n}\n\n/**\n * WHO STILL OWNS WHAT THEY BOUGHT — the one predicate (AGL-2158).\n *\n * `hasLivePurchase` (server/purchase-entitlement.ts) is the gate on all eight\n * ways into paid content, and it reads exactly one field: a purchase with\n * `refundedAt` — stamped by the `charge.refunded` and lost-`charge.dispute`\n * doors of the marketplace billing webhook — no longer entitles.\n *\n * The listing page carried its OWN copy of that question,\n * `some(p => p.listingId === listingId)`, with no refund test at all. The two\n * then disagreed on the one buyer they must not disagree on: the refunded\n * one. The page showed \"Purchased\", hid the buy button, and the install\n * routes answered 402 — a buyer who could neither install nor re-purchase.\n *\n * It lives HERE, in the model, rather than in the server module, because the\n * server module is the wrong side of the client/server boundary for a React\n * component and copying four characters of predicate is precisely how the two\n * came apart. This module is context-free by construction (see the header) —\n * importable from a client component, an API route and another plugin alike.\n */\nexport interface PurchaseLiveness {\n /** Stamped when a full refund or a lost dispute un-buys the listing. */\n refundedAt?: unknown\n listingId?: unknown\n /**\n * THE ORGANIZATION THE LICENCE BELONGS TO (AGL-2331).\n *\n * Absent on every purchase written before AGL-2331 — see\n * `purchaseEntitlesOrg` for what that absence means and why it is never\n * treated as \"no licence\".\n */\n buyerOrgId?: unknown\n /** The person who paid. Kept for the receipt trail and the legacy grant. */\n buyerUid?: unknown\n}\n\n/**\n * True when this purchase document still entitles.\n *\n * Deliberately a truthiness test and not `!= null`: `refundedAt` is a\n * Firestore Timestamp on the server, a client Timestamp in the browser and a\n * sentinel in the webhook's own tests, and every one of those is truthy while\n * a missing field (every purchase written before AGL-1546) is not.\n */\nexport function isLivePurchase(\n purchase: PurchaseLiveness | null | undefined,\n): boolean {\n return Boolean(purchase) && !purchase?.refundedAt\n}\n\n/**\n * True when this buyer's purchase documents include a live one for `listingId`.\n *\n * Both callers pass everything they read — the server's query is already\n * narrowed to the listing, the client's is narrowed only to the buyer — so the\n * listing filter belongs inside the shared predicate too, not beside it.\n */\nexport function hasLivePurchaseOf(\n purchases: readonly (PurchaseLiveness | null | undefined)[] | null | undefined,\n listingId: string,\n): boolean {\n if (!listingId) return false\n return (purchases ?? []).some(\n (purchase) =>\n purchase?.listingId === listingId && isLivePurchase(purchase),\n )\n}\n/**\n * WHO A PURCHASE LICENSES (AGL-2331).\n *\n * ## The model\n *\n * **A marketplace purchase licenses an ORGANIZATION, not a person.** That is\n * not a new decision — it is the one already published. The Marketplace\n * Publisher Agreement §8.1 says a paid Artifact is licensed \"to the installing\n * organization\", and §2 grants the right to sublicense \"to organizations that\n * install it\". Until now the code enforced a per-PERSON licence instead, and\n * the mismatch cut both ways: an agency developer who is an owner across five\n * client workspaces bought once and installed into all five, and — because the\n * duplicate-purchase guard shares this predicate — could not buy a second\n * licence even when they wanted to. Conforming the code to the published terms\n * is the smaller of the two changes; the alternative amends a version-pinned\n * legal document and stops every publisher until they re-accept it.\n *\n * Three consequences follow, and all three are the point:\n *\n * 1. A licence held by org A does not install into org B. The agency buys per\n * client workspace, which is what the agreement says they are buying.\n * 2. Buying a second licence is a real second sale, not a `409`.\n * 3. Any member of the owning org with `installPlugins` may install what the\n * ORG bought — including colleagues who were not the buyer, and including\n * the buyer's replacement after they leave. A licence that evaporates when\n * one employee's account is deleted is not an organizational licence.\n *\n * ## The legacy grant, and why it never expires\n *\n * A purchase written before this change carries NO `buyerOrgId` — there was\n * no buyer org anywhere in the pipeline to record. Those are real purchases by\n * real customers, and reinterpreting one as \"licensed to no organization\"\n * would revoke access somebody paid for. So a purchase with no `buyerOrgId` at\n * all keeps its ORIGINAL, person-scoped meaning, forever: it entitles the uid\n * that bought it, in every org that uid can install into. Nothing is\n * migrated, nothing is claimed by the first org to use it, and nothing is\n * revoked — the ambiguity resolves in the customer's favour by construction,\n * with no backfill to get right and no window during which a paying customer\n * is locked out.\n *\n * The grandfather is bounded by time rather than policed: it can only ever\n * apply to purchases already written, because from AGL-2331 onward checkout\n * refuses to open a session that does not name a validated buyer org. It is\n * therefore a shrinking set that never grows, not a hole left open.\n *\n * `orgId` may be empty (a site with no owning org). That is not a licence to\n * anything, so only the legacy uid grant can hold — never a `buyerOrgId ===\n * ''` match, which is why the org branch tests for a non-empty string on the\n * document itself rather than comparing the two values directly.\n */\nexport function purchaseEntitlesOrg(\n purchase: PurchaseLiveness | null | undefined,\n actor: { orgId?: string | null; uid?: string | null },\n): boolean {\n if (!isLivePurchase(purchase)) return false\n const purchaseOrgId = purchase?.buyerOrgId\n if (typeof purchaseOrgId === 'string' && purchaseOrgId) {\n return Boolean(actor.orgId) && purchaseOrgId === actor.orgId\n }\n // Legacy: no buyer org was ever recorded, so it means what it meant when it\n // was sold. Never revoked, never migrated.\n return Boolean(actor.uid) && purchase?.buyerUid === actor.uid\n}\n\n/**\n * True when these purchase documents include one that licenses `orgId` for\n * `listingId` — the org-scoped counterpart of `hasLivePurchaseOf`.\n *\n * Same shape and same home as the liveness predicate, and for the same reason\n * (AGL-2158): the install routes, the checkout duplicate guard and the listing\n * page all have to answer \"does this workspace hold a licence\" identically, and\n * the way they came apart last time was four characters of predicate copied\n * into a component.\n */\nexport function hasOrgLicenceOf(\n purchases: readonly (PurchaseLiveness | null | undefined)[] | null | undefined,\n listingId: string,\n actor: { orgId?: string | null; uid?: string | null },\n): boolean {\n if (!listingId) return false\n return (purchases ?? []).some(\n (purchase) =>\n purchase?.listingId === listingId && purchaseEntitlesOrg(purchase, actor),\n )\n}\n\n/**\n * Every org id these purchases license for `listingId`, in document order.\n *\n * What the console renders so a buyer can see WHICH workspace a licence they\n * paid for belongs to (AGL-2331) — the question that has no answer at all\n * while entitlement is person-scoped, and the one an agency has to answer\n * before deciding whether it needs another.\n *\n * Legacy person-scoped purchases contribute no org id, because they name\n * none; a caller rendering this list has to say so rather than invent one.\n */\nexport function licensedOrgIdsFor(\n purchases: readonly (PurchaseLiveness | null | undefined)[] | null | undefined,\n listingId: string,\n): string[] {\n const seen: string[] = []\n for (const purchase of purchases ?? []) {\n if (purchase?.listingId !== listingId || !isLivePurchase(purchase)) continue\n const orgId = purchase?.buyerOrgId\n if (typeof orgId === 'string' && orgId && !seen.includes(orgId)) {\n seen.push(orgId)\n }\n }\n return seen\n}\n\n"],"names":["isFirstPartyMediaSrc","MEDIA_REF_PREFIX","marketplaceMinPriceUsd","offeredPluginVersion","isListingBrowsable","isListingDeleted","isPrivateListing","LISTING_CLIENT_WRITABLE_FIELDS","LISTING_UNPERSISTED_FIELDS","listingArtifactType","PUBLISHER_HANDLE_PATTERN","isValidPublisherHandle","handle","test","ARTIFACT_TYPE_LABELS","INSTALL_TARGETS","LISTING_CATEGORIES","resolveOrgInstallSummary","resolvePluginInstallState","resolveUninstallTargets","listingArtifactLabel","listing","installTargetsFor","resolveInstallPlan","targeting","hosts","targets","canOrgPin","includes","canHostPin","scope","allHostIds","map","hostId","selectedHostIds","VERIFICATION_BLOCK_MESSAGES","VERIFICATION_DECLINE_COOLDOWN_DAYS","timestampMs","verificationRequestBlock","isVersionApproved","version","reviewState","installsUnreviewedFallback","viewerOrgId","revocation","profileId","Boolean","String","latestVersion","newestApprovedVersion","versions","approved","filter","entry","length","reduce","best","publishedAt","toMillis","missingPublicListingContent","missing","description","trim","push","readme","license","LISTING_README_MAX_CHARS","LISTING_MAX_SCREENSHOTS","HTTPS_URL","LISTING_IMAGE_ERROR","LISTING_URL_MAX_CHARS","isListingImageValue","value","isPublisherAvatarValue","startsWith","validateListingContent","input","content","key","undefined","ok","error","logoUrl","screenshots","Array","isArray","some","url","categories","PUBLISHER_SOCIAL_HOSTS","githubUrl","xUrl","linkedinUrl","SUPPORT_EMAIL","validatePublisherProfileContent","avatarUrl","urlKeys","host","URL","hostname","toLowerCase","allowed","endsWith","supportEmail","safePublisherHref","safePublisherImageSrc","src","MARKETPLACE_PLATFORM_FEE_PERCENT","MARKETPLACE_PLATFORM_FEE_PERCENT_FREE_PLAN","MARKETPLACE_MAX_PRICE_USD","MARKETPLACE_MIN_PRICE_USD","marketplacePriceRefusal","priceUsd","Number","isFinite","PORTABLE_COMPONENT_ID_ALLOWLIST","MARKETPLACE_COMPONENT_ID_ALLOWLIST","PORTABLE_EMAIL_COMPONENT_ID_ALLOWLIST","MARKETPLACE_EMAIL_COMPONENT_ID_ALLOWLIST","PORTABLE_EMAIL_STARTER_COMPONENT_ID_ALLOWLIST","MARKETPLACE_EMAIL_STARTER_COMPONENT_ID_ALLOWLIST","sanitizePortableDefinition","sanitizeMarketplaceDefinition","portableDefinitionToNested","marketplaceDefinitionToNested","PORTABLE_SAFE_HREF","MARKETPLACE_SAFE_HREF","PORTABLE_SAFE_SRC","MARKETPLACE_SAFE_SRC","PORTABLE_DEFINITION_MAX_BYTES","MARKETPLACE_DEFINITION_MAX_BYTES","ARTIFACT_INSTALL_RESULT","plugin","component","template","layout","datasetSchema","emailTemplate","emailStarter","theme","siteStarter","listingInclusions","options","type","rows","label","tone","reviewedVersion","isLivePurchase","purchase","refundedAt","hasLivePurchaseOf","purchases","listingId","purchaseEntitlesOrg","actor","purchaseOrgId","buyerOrgId","orgId","uid","buyerUid","hasOrgLicenceOf","licensedOrgIdsFor","seen"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;CAIC,GAED,6EAA6E;AAC7E,2EAA2E;AAC3E,8E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5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ import { type SiteStarterKnownIds } from '@aglyn/aglyn/app-utils/site-starter';
18
+ import type { SiteStarterSummary } from '@aglyn/aglyn/plugin-manager/plugin-site-starters';
19
+ /**
20
+ * A site starter as a marketplace listing (AGL-4049): the pure half of the
21
+ * publish door and the starter source, so both read a starter one way.
22
+ */
23
+ /**
24
+ * The bases and font pairings a starter may name, checked by
25
+ * `siteStarterRefusal` at publish and again at resolve. Kinds are left
26
+ * unchecked: the core keeps no list of them.
27
+ */
28
+ export declare const SITE_STARTER_KNOWN_IDS: SiteStarterKnownIds;
29
+ /** The most starters one search answers. */
30
+ export declare const SITE_STARTER_SEARCH_MAX = 50;
31
+ /**
32
+ * The `browseTokens` a typed search asks for: each word through the same
33
+ * normalizer browse uses, scoped to everyone as the listing writers stamp
34
+ * them (`*~word`), so a starter search finds only what anyone may see. At
35
+ * most thirty, Firestore's ceiling for one `array-contains-any`; none for a
36
+ * search with nothing searchable in it.
37
+ */
38
+ export declare function siteStarterSearchTokens(word: string | null | undefined): string[];
39
+ /** A search's `limit`, as a whole number from 0 to {@link SITE_STARTER_SEARCH_MAX}. */
40
+ export declare function siteStarterSearchLimit(limit: unknown): number;
41
+ /** One starter listing as a search lists it. */
42
+ export declare function siteStarterSummaryOf(listingId: string, listing: Record<string, any>, authorName: string): SiteStarterSummary;
43
+ /**
44
+ * The platform's own starters first, everything else in the order it came,
45
+ * which is newest first. Ordering only: `official` decides nothing else.
46
+ */
47
+ export declare function officialStartersFirst<T extends {
48
+ official: boolean;
49
+ }>(rows: readonly T[]): T[];
@@ -0,0 +1,75 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */ import { nameSearchKey, nameSearchToken, SCOPED_SEARCH_JOIN } from "@aglyn/aglyn/app-utils/name-search";
17
+ import { SITE_FONT_PAIRINGS } from "@aglyn/aglyn/app-utils/site-font-pairings";
18
+ import { SITE_THEME_BASES, siteStarterFacetsOf } from "@aglyn/aglyn/app-utils/site-starter";
19
+ import { BROWSE_EVERYONE } from "./listing-query.js";
20
+ /**
21
+ * A site starter as a marketplace listing (AGL-4049): the pure half of the
22
+ * publish door and the starter source, so both read a starter one way.
23
+ */ /**
24
+ * The bases and font pairings a starter may name, checked by
25
+ * `siteStarterRefusal` at publish and again at resolve. Kinds are left
26
+ * unchecked: the core keeps no list of them.
27
+ */ export const SITE_STARTER_KNOWN_IDS = {
28
+ bases: new Set(SITE_THEME_BASES),
29
+ fonts: new Set(SITE_FONT_PAIRINGS.map((pairing)=>pairing.id))
30
+ };
31
+ /** The most starters one search answers. */ export const SITE_STARTER_SEARCH_MAX = 50;
32
+ /** Firestore's ceiling on the values of one `array-contains-any`. */ const ARRAY_CONTAINS_ANY_MAX = 30;
33
+ /**
34
+ * The `browseTokens` a typed search asks for: each word through the same
35
+ * normalizer browse uses, scoped to everyone as the listing writers stamp
36
+ * them (`*~word`), so a starter search finds only what anyone may see. At
37
+ * most thirty, Firestore's ceiling for one `array-contains-any`; none for a
38
+ * search with nothing searchable in it.
39
+ */ export function siteStarterSearchTokens(word) {
40
+ const words = nameSearchKey(word).split(' ');
41
+ const tokens = [
42
+ ...new Set(words.map((one)=>nameSearchToken(one)).filter(Boolean))
43
+ ];
44
+ return tokens.slice(0, ARRAY_CONTAINS_ANY_MAX).map((token)=>`${BROWSE_EVERYONE}${SCOPED_SEARCH_JOIN}${token}`);
45
+ }
46
+ /** A search's `limit`, as a whole number from 0 to {@link SITE_STARTER_SEARCH_MAX}. */ export function siteStarterSearchLimit(limit) {
47
+ const value = Math.floor(Number(limit));
48
+ if (!Number.isFinite(value) || value <= 0) return 0;
49
+ return Math.min(value, SITE_STARTER_SEARCH_MAX);
50
+ }
51
+ /** One starter listing as a search lists it. */ export function siteStarterSummaryOf(listingId, listing, authorName) {
52
+ var _listing_priceUsd;
53
+ const price = Number((_listing_priceUsd = listing.priceUsd) != null ? _listing_priceUsd : 0);
54
+ return {
55
+ listingId,
56
+ displayName: typeof listing.displayName === 'string' ? listing.displayName : '',
57
+ description: typeof listing.description === 'string' ? listing.description : '',
58
+ authorName,
59
+ official: listing.official === true,
60
+ priceUsd: Number.isFinite(price) && price > 0 ? price : 0,
61
+ previewImageUrl: typeof listing.previewImageUrl === 'string' && listing.previewImageUrl ? listing.previewImageUrl : null,
62
+ facets: siteStarterFacetsOf(listing)
63
+ };
64
+ }
65
+ /**
66
+ * The platform's own starters first, everything else in the order it came,
67
+ * which is newest first. Ordering only: `official` decides nothing else.
68
+ */ export function officialStartersFirst(rows) {
69
+ return [
70
+ ...rows.filter((row)=>row.official),
71
+ ...rows.filter((row)=>!row.official)
72
+ ];
73
+ }
74
+
75
+ //# sourceMappingURL=site-starter-listing.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/marketplace/src/lib/model/site-starter-listing.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { nameSearchKey, nameSearchToken, SCOPED_SEARCH_JOIN } from '@aglyn/aglyn/app-utils/name-search'\nimport { SITE_FONT_PAIRINGS } from '@aglyn/aglyn/app-utils/site-font-pairings'\nimport {\n SITE_THEME_BASES,\n siteStarterFacetsOf,\n type SiteStarterKnownIds,\n} from '@aglyn/aglyn/app-utils/site-starter'\nimport type { SiteStarterSummary } from '@aglyn/aglyn/plugin-manager/plugin-site-starters'\nimport { BROWSE_EVERYONE } from './listing-query'\n\n/**\n * A site starter as a marketplace listing (AGL-4049): the pure half of the\n * publish door and the starter source, so both read a starter one way.\n */\n\n/**\n * The bases and font pairings a starter may name, checked by\n * `siteStarterRefusal` at publish and again at resolve. Kinds are left\n * unchecked: the core keeps no list of them.\n */\nexport const SITE_STARTER_KNOWN_IDS: SiteStarterKnownIds = {\n bases: new Set(SITE_THEME_BASES),\n fonts: new Set(SITE_FONT_PAIRINGS.map((pairing) => pairing.id)),\n}\n\n/** The most starters one search answers. */\nexport const SITE_STARTER_SEARCH_MAX = 50\n\n/** Firestore's ceiling on the values of one `array-contains-any`. */\nconst ARRAY_CONTAINS_ANY_MAX = 30\n\n/**\n * The `browseTokens` a typed search asks for: each word through the same\n * normalizer browse uses, scoped to everyone as the listing writers stamp\n * them (`*~word`), so a starter search finds only what anyone may see. At\n * most thirty, Firestore's ceiling for one `array-contains-any`; none for a\n * search with nothing searchable in it.\n */\nexport function siteStarterSearchTokens(word: string | null | undefined): string[] {\n const words = nameSearchKey(word).split(' ')\n const tokens = [...new Set(words.map((one) => nameSearchToken(one)).filter(Boolean))]\n return tokens\n .slice(0, ARRAY_CONTAINS_ANY_MAX)\n .map((token) => `${BROWSE_EVERYONE}${SCOPED_SEARCH_JOIN}${token}`)\n}\n\n/** A search's `limit`, as a whole number from 0 to {@link SITE_STARTER_SEARCH_MAX}. */\nexport function siteStarterSearchLimit(limit: unknown): number {\n const value = Math.floor(Number(limit))\n if (!Number.isFinite(value) || value <= 0) return 0\n return Math.min(value, SITE_STARTER_SEARCH_MAX)\n}\n\n/** One starter listing as a search lists it. */\nexport function siteStarterSummaryOf(\n listingId: string,\n listing: Record<string, any>,\n authorName: string,\n): SiteStarterSummary {\n const price = Number(listing.priceUsd ?? 0)\n return {\n listingId,\n displayName: typeof listing.displayName === 'string' ? listing.displayName : '',\n description: typeof listing.description === 'string' ? listing.description : '',\n authorName,\n official: listing.official === true,\n priceUsd: Number.isFinite(price) && price > 0 ? price : 0,\n previewImageUrl:\n typeof listing.previewImageUrl === 'string' && listing.previewImageUrl\n ? listing.previewImageUrl\n : null,\n facets: siteStarterFacetsOf(listing),\n }\n}\n\n/**\n * The platform's own starters first, everything else in the order it came,\n * which is newest first. Ordering only: `official` decides nothing else.\n */\nexport function officialStartersFirst<T extends { official: boolean }>(rows: readonly T[]): T[] {\n return [...rows.filter((row) => row.official), ...rows.filter((row) => !row.official)]\n}\n"],"names":["nameSearchKey","nameSearchToken","SCOPED_SEARCH_JOIN","SITE_FONT_PAIRINGS","SITE_THEME_BASES","siteStarterFacetsOf","BROWSE_EVERYONE","SITE_STARTER_KNOWN_IDS","bases","Set","fonts","map","pairing","id","SITE_STARTER_SEARCH_MAX","ARRAY_CONTAINS_ANY_MAX","siteStarterSearchTokens","word","words","split","tokens","one","filter","Boolean","slice","token","siteStarterSearchLimit","limit","value","Math","floor","Number","isFinite","min","siteStarterSummaryOf","listingId","listing","authorName","price","priceUsd","displayName","description","official","previewImageUrl","facets","officialStartersFirst","rows","row"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,aAAa,EAAEC,eAAe,EAAEC,kBAAkB,QAAQ,qCAAoC;AACvG,SAASC,kBAAkB,QAAQ,4CAA2C;AAC9E,SACEC,gBAAgB,EAChBC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AAUA,QAAQ,IAAIA,QAAQ;QACxDK,iBACE,OAAOP,QAAQO,eAAe,KAAK,YAAYP,QAAQO,eAAe,GAClEP,QAAQO,eAAe,GACvB;QACNC,QAAQvC,oBAAoB+B;IAC9B;AACF;AAEA;;;CAGC,GACD,OAAO,SAASS,sBAAuDC,IAAkB;IACvF,OAAO;WAAIA,KAAKxB,MAAM,CAAC,CAACyB,MAAQA,IAAIL,QAAQ;WAAMI,KAAKxB,MAAM,CAAC,CAACyB,MAAQ,CAACA,IAAIL,QAAQ;KAAE;AACxF"}
@@ -17,6 +17,8 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
17
17
  */ // The leaf module, not the server barrel: the list keys every artifact
18
18
  // create stamps (AGL-3321), which the install specs' closed-world barrel
19
19
  // mocks have no reason to stage.
20
+ import { holdsStampedSiteKey } from "@aglyn/aglyn/app-utils/host-permissions";
21
+ import { MARKETPLACE_SITE_ROLE_PRESET, marketplaceSitePermissionRefusal } from "../model/marketplace-site-permissions.js";
20
22
  import { artifactCreateListKeys } from "@aglyn/aglyn/app-utils/artifact-list-keys";
21
23
  import { createResourceUid, isPluginRevoked } from "@aglyn/aglyn/server";
22
24
  import { firebaseAdmin } from "@aglyn/tenant-data-admin";
@@ -93,7 +95,7 @@ import { isPublisherSecurityLocked } from "./sale-risk.js";
93
95
  error: 'Unauthenticated'
94
96
  });
95
97
  try {
96
- var _hostSnapshot_get, _listing_priceUsd, _membership_orgId, _versionSnapshot_get, _versionSnapshot_get1, _versionSnapshot_get2, _listing_displayName;
98
+ var _listing_priceUsd, _membership_orgId, _versionSnapshot_get, _versionSnapshot_get1, _versionSnapshot_get2, _listing_displayName;
97
99
  const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken);
98
100
  const membership = await resolveOrgPermissions(decoded.uid, {
99
101
  hostId
@@ -111,10 +113,11 @@ import { isPublisherSecurityLocked } from "./sale-risk.js";
111
113
  error: 'Unknown site'
112
114
  });
113
115
  }
114
- const memberRole = ((_hostSnapshot_get = hostSnapshot.get('memberRoles')) != null ? _hostSnapshot_get : {})[decoded.uid];
115
- if (memberRole !== 'admin' && memberRole !== 'editor') {
116
+ // "Install marketplace items into a site" (AGL-4047): the site's stamp, else
117
+ // the preset of the member's site role, the Admin and Editor this asked for.
118
+ if (!holdsStampedSiteKey(hostSnapshot, decoded.uid, 'marketplace.siteInstall', MARKETPLACE_SITE_ROLE_PRESET)) {
116
119
  return res.status(403).json({
117
- error: 'Not a site admin or editor'
120
+ error: marketplaceSitePermissionRefusal('marketplace.siteInstall')
118
121
  });
119
122
  }
120
123
  const listingRef = firestore.collection('marketplaceListings').doc(listingId);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/marketplace/src/lib/server/install-email-starter.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// The leaf module, not the server barrel: the list keys every artifact\n// create stamps (AGL-3321), which the install specs' closed-world barrel\n// mocks have no reason to stage.\nimport { artifactCreateListKeys } from '@aglyn/aglyn/app-utils/artifact-list-keys'\nimport { createResourceUid, isPluginRevoked } from '@aglyn/aglyn/server'\nimport { type PluginApiHandler } from '@aglyn/aglyn/server'\nimport type { PluginRevocation } from '@aglyn/aglyn/server'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { resolveOrgPermissions } from '@aglyn/tenant-runtime/org-permissions'\nimport {\n emailStarterRefusal,\n inspectEmailStarter,\n isPrivateListing,\n listingArtifactType,\n resolveEmailStarterAssurance,\n} from '../model'\nimport { canActAsPublisher } from './publisher-profile'\nimport { requirePurchase } from './purchase-entitlement'\nimport { recordInstallProvenance } from './provenance'\nimport { recordVersionMove } from './version-stats'\nimport { isPublisherSecurityLocked } from './sale-risk'\n\n/**\n * Installs a marketplace email starter as a new email on a site.\n *\n * ## The install is a COPY, and that is the versioning answer\n *\n * The published tree is written into a screen document of the tenant's own —\n * `hosts/{h}/screens/{newId}` with `kind: 'email'`, plus its first version —\n * in exactly the shape `createEmailScreen` writes, so it appears in the site's\n * Email templates list beside every email they designed themselves and opens\n * in the same besigner. From that write on, nothing reads the listing again.\n *\n * That is deliberate, and it is the property a live reference could not have:\n * a publisher pushing version 4 must not rewrite the email a tenant is\n * mailing from this afternoon. A newer version surfaces as an offer — the\n * shared `resolveUpdateState` comparison every other artifact type uses — and\n * is taken through `update-artifact`, which three-way-merges against the base\n * snapshot recorded here so the tenant's own edits survive it.\n *\n * The one thing a copy does NOT sever is a `media:` reference, which still\n * resolves against the publisher's media. Reported by the inspection rather\n * than refused: our own CDN serves it, so no third party learns who opened the\n * mail, but the bytes behind it can still change.\n *\n * ## Three refusals that are not in the other install routes\n *\n * **The kill switch, at install.** Every other copied artifact treats\n * `revocations` as a plugin concern. An installed email is mailed from the\n * shared sending domain, so a stopped version must not be handed out — and,\n * separately, must stop being sent by tenants who already have it, which is\n * `emailStarterSendBlock` on the send path.\n *\n * **A rejected version, for everybody including its publisher.** Review is not\n * a precondition for installing an email starter — they are auto-listed like\n * every other copied artifact — so most versions are honestly `unreviewed` and\n * install fine. A verdict of `rejected` is different: somebody looked and said\n * no, and the publisher's own site is on the same sending domain as everyone\n * else's.\n *\n * **The policy, re-run over the listing's own bytes.** The publish route\n * already refused a violating design. Re-running it here is not belt and\n * braces about that route — it is the gate for content that never went through\n * it: a version published before this policy existed, a document written by a\n * staff tool, an import. A tracking pixel is only refused if the refusal sits\n * where the content is HANDED OVER, which is the lesson `install-email-template`\n * records about takedown.\n */\nexport const installEmailStarterHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n const listingId = String(req.body?.listingId ?? '')\n const hostId = String(req.body?.hostId ?? '')\n if (!listingId || !hostId) {\n return res.status(400).json({ error: 'Missing listingId or hostId' })\n }\n const authorization = String(req.headers.authorization ?? '')\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken) return res.status(401).json({ error: 'Unauthenticated' })\n\n try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n const membership = await resolveOrgPermissions(decoded.uid, { hostId })\n if (!membership.permissions.installPlugins) {\n return res.status(403).json({\n error:\n 'Your organization role does not allow installing from the marketplace',\n })\n }\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const hostSnapshot = await hostRef.get()\n if (!hostSnapshot.exists) {\n return res.status(404).json({ error: 'Unknown site' })\n }\n const memberRole = (hostSnapshot.get('memberRoles') ?? {})[decoded.uid]\n if (memberRole !== 'admin' && memberRole !== 'editor') {\n return res.status(403).json({ error: 'Not a site admin or editor' })\n }\n\n const listingRef = firestore.collection('marketplaceListings').doc(listingId)\n const listingSnapshot = await listingRef.get()\n const listing = listingSnapshot.data() as any\n if (\n !listing ||\n listing.deletedAt ||\n listing.hiddenAt ||\n // A publisher under a SECURITY lock hands nothing over (AGL-3365).\n (await isPublisherSecurityLocked(firestore, listing.profileId)) ||\n listingArtifactType(listing) !== 'emailStarter'\n ) {\n return res.status(404).json({ error: 'Unknown email starter' })\n }\n\n const ownsListing = await canActAsPublisher(\n firestore,\n decoded.uid,\n listing.profileId,\n )\n if (isPrivateListing(listing) && !ownsListing) {\n return res.status(404).json({ error: 'Unknown listing' })\n }\n const priceUsd = Number(listing.priceUsd ?? 0)\n const unpaid = await requirePurchase({\n firestore,\n buyerUid: decoded.uid,\n buyerOrgId: membership.orgId ?? '',\n listingId,\n priceUsd,\n ownsListing,\n })\n if (unpaid) return res.status(402).json(unpaid)\n\n const version = listing.latestVersion\n const revocation = (\n await firestore.collection('revocations').doc(listingId).get()\n ).data() as PluginRevocation | undefined\n if (isPluginRevoked(revocation, String(version ?? ''))) {\n return res\n .status(409)\n .json({ error: 'This email design has been stopped by Aglyn' })\n }\n\n const versionSnapshot = await listingRef\n .collection('versions')\n .doc(String(version))\n .get()\n if (!versionSnapshot.exists) {\n return res.status(500).json({ error: 'Email starter version missing' })\n }\n /**\n * The assurance of THIS version, from THIS version's document.\n *\n * Read here rather than off the listing, and stamped rather than\n * recomputed later, because the listing's own review fields answer a\n * different question. `reviewStatus: 'verified'` is a claim about the\n * publisher; `latestVersionReviewState` describes whatever is newest. A\n * reader that consulted either would report version 7 as reviewed on the\n * strength of version 3, which is how \"reviewed\" stops meaning anything.\n */\n const assurance = resolveEmailStarterAssurance({\n reviewState: versionSnapshot.get('reviewState'),\n })\n if (assurance === 'rejected') {\n return res.status(409).json({\n error: 'This email design was turned down in review and cannot be installed',\n })\n }\n\n const inspection = inspectEmailStarter(versionSnapshot.get('nodes'), {\n hostId,\n })\n const violation = emailStarterRefusal(inspection)\n if (violation) {\n return res\n .status(422)\n .json({ error: violation, violations: inspection.violations })\n }\n const nodes = inspection.nodes\n if (!nodes || !Object.keys(nodes).length) {\n return res.status(500).json({ error: 'Email starter version missing' })\n }\n\n const subject = String(versionSnapshot.get('subject') ?? '')\n const preheader = String(versionSnapshot.get('preheader') ?? '')\n const rootId = versionSnapshot.get('rootId') ?? null\n const provenance = await recordInstallProvenance({\n firestore,\n listingId,\n listing,\n version,\n artifactType: 'emailStarter',\n content: { rootId, nodes, subject, preheader },\n })\n const installedFrom = { ...provenance.installedFrom, assurance }\n\n const screenId = createResourceUid()\n const versionId = createResourceUid()\n const now = firebaseAdmin.firestore.FieldValue.serverTimestamp()\n const displayName = String(listing.displayName ?? 'Installed email').slice(\n 0,\n 120,\n )\n const batch = firestore.batch()\n const screenRef = hostRef.collection('screens').doc(screenId)\n /**\n * The same document shape `createEmailScreen` writes, so the Email\n * templates list, the screen besigner and the campaign composer all find\n * it without knowing it came from anywhere.\n *\n * NOT routed, and `kind: 'email'`, which is what keeps it out of\n * `countBillableScreens` — an installed email spends the same allowance a\n * hand-made one does, which is none.\n *\n * `nodes` is written as a plain map here, exactly as the first version\n * from `/api/hosts/versions` is. The besigner's converter compresses on\n * the first save, and `decodeStoredNodes` is what every reader on this\n * path already goes through, so both forms are handled from the start.\n */\n batch.set(screenRef, {\n displayName,\n // The keys the email templates list finds it by (AGL-3321).\n ...artifactCreateListKeys('screens', { displayName }),\n kind: 'email',\n versionId,\n ...(subject && { emailSubject: subject }),\n ...(preheader && { emailPreheader: preheader }),\n installedFrom,\n createdAt: now,\n updatedAt: now,\n })\n batch.set(screenRef.collection('versions').doc(versionId), {\n screenId,\n ...(rootId ? { rootId } : {}),\n nodes,\n // Stamped on the VERSION as well as the screen, because the version is\n // what the send path renders and the send path is where the kill switch\n // has to bite. A stamp only on the parent would be one document away\n // from the bytes it describes.\n installedFrom,\n createdAt: now,\n updatedAt: now,\n })\n await batch.commit()\n\n await recordVersionMove({\n firestore,\n listingRef,\n artifactType: 'emailStarter',\n to: version,\n })\n await listingRef\n .update({\n installCount: firebaseAdmin.firestore.FieldValue.increment(1),\n })\n .catch(() => undefined)\n\n return res.status(200).json({\n installed: true,\n screenId,\n versionId,\n version: version ?? null,\n assurance,\n linkHosts: inspection.linkHosts,\n foreignMediaScopes: inspection.foreignMediaScopes,\n baseStored: provenance.baseStored,\n })\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Email starter install failed' })\n }\n}\n\nexport default installEmailStarterHandler\n"],"names":["artifactCreateListKeys","createResourceUid","isPluginRevoked","firebaseAdmin","resolveOrgPermissions","emailStarterRefusal","inspectEmailStarter","isPrivateListing","listingArtifactType","resolveEmailStarterAssurance","canActAsPublisher","requirePurchase","recordInstallProvenance","recordVersionMove","isPublisherSecurityLocked","installEmailStarterHandler","req","res","method","status","json","error","listingId","String","body","hostId","authorization","headers","idToken","startsWith","slice","length","undefined","hostSnapshot","listing","membership","versionSnapshot","decoded","app","auth","verifyIdToken","uid","permissions","installPlugins","firestore","hostRef","collection","doc","get","exists","memberRole","listingRef","listingSnapshot","data","deletedAt","hiddenAt","profileId","ownsListing","priceUsd","Number","unpaid","buyerUid","buyerOrgId","orgId","version","latestVersion","revocation","assurance","reviewState","inspection","violation","violations","nodes","Object","keys","subject","preheader","rootId","provenance","artifactType","content","installedFrom","screenId","versionId","now","FieldValue","serverTimestamp","displayName","batch","screenRef","set","kind","emailSubject","emailPreheader","createdAt","updatedAt","commit","to","update","installCount","increment","catch","installed","linkHosts","foreignMediaScopes","baseStored","console"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,uEAAuE;AACvE,yEAAyE;AACzE,iCAAiC;AACjC,SAASA,sBAAsB,QAAQ,4CAA2C;AAClF,SAASC,iBAAiB,EAAEC,eAAe,QAAQ,sBAAqB;AAGxE,SAASC,aAAa,QAAQ,2BAA0B;AACxD,SAASC,qBAAqB,QAAQ,wCAAuC;AAC7E,SACEC,mBAAmB,EACnBC,mBAAmB,EACnBC,gBAAgB,EAChBC,mBAAmB,EACnBC,4BAA4B,QACvB,oBAAU;AACjB,SAASC,iBAAiB,QAAQ,yBAAqB;AACvD,SAASC,eAAe,QAAQ,4BAAwB;AACxD,SAASC,uBAAuB,QAAQ,kBAAc;AACtD,SAASC,iBAAiB,QAAQ,qBAAiB;AACnD,SAASC,yBAAyB,QAAQ,iBAAa;AAEvD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA6CC,GACD,OAAO,MAAMC,6BAA+C,OAAOC,KAAKC;qBASzCD;QALJA,WACHA;IAJtB,IAAIA,IAAIE,MAAM,KAAK,QAAQ;QACzB,OAAOD,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAqB;IAC5D;IACA,MAAMC,YAAYC,gBAAOP,YAAAA,IAAIQ,IAAI,qBAARR,UAAUM,SAAS,mBAAI;IAChD,MAAMG,SAASF,iBAAOP,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AQrF,KAAK,CAACA;QACd,OAAOJ,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAA+B;IACtE;AACF,EAAC;AAED,eAAeN,2BAA0B"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/marketplace/src/lib/server/install-email-starter.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// The leaf module, not the server barrel: the list keys every artifact\n// create stamps (AGL-3321), which the install specs' closed-world barrel\n// mocks have no reason to stage.\nimport { holdsStampedSiteKey } from '@aglyn/aglyn/app-utils/host-permissions'\nimport { MARKETPLACE_SITE_ROLE_PRESET, marketplaceSitePermissionRefusal } from '../model/marketplace-site-permissions'\nimport { artifactCreateListKeys } from '@aglyn/aglyn/app-utils/artifact-list-keys'\nimport { createResourceUid, isPluginRevoked } from '@aglyn/aglyn/server'\nimport { type PluginApiHandler } from '@aglyn/aglyn/server'\nimport type { PluginRevocation } from '@aglyn/aglyn/server'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { resolveOrgPermissions } from '@aglyn/tenant-runtime/org-permissions'\nimport {\n emailStarterRefusal,\n inspectEmailStarter,\n isPrivateListing,\n listingArtifactType,\n resolveEmailStarterAssurance,\n} from '../model'\nimport { canActAsPublisher } from './publisher-profile'\nimport { requirePurchase } from './purchase-entitlement'\nimport { recordInstallProvenance } from './provenance'\nimport { recordVersionMove } from './version-stats'\nimport { isPublisherSecurityLocked } from './sale-risk'\n\n/**\n * Installs a marketplace email starter as a new email on a site.\n *\n * ## The install is a COPY, and that is the versioning answer\n *\n * The published tree is written into a screen document of the tenant's own —\n * `hosts/{h}/screens/{newId}` with `kind: 'email'`, plus its first version —\n * in exactly the shape `createEmailScreen` writes, so it appears in the site's\n * Email templates list beside every email they designed themselves and opens\n * in the same besigner. From that write on, nothing reads the listing again.\n *\n * That is deliberate, and it is the property a live reference could not have:\n * a publisher pushing version 4 must not rewrite the email a tenant is\n * mailing from this afternoon. A newer version surfaces as an offer — the\n * shared `resolveUpdateState` comparison every other artifact type uses — and\n * is taken through `update-artifact`, which three-way-merges against the base\n * snapshot recorded here so the tenant's own edits survive it.\n *\n * The one thing a copy does NOT sever is a `media:` reference, which still\n * resolves against the publisher's media. Reported by the inspection rather\n * than refused: our own CDN serves it, so no third party learns who opened the\n * mail, but the bytes behind it can still change.\n *\n * ## Three refusals that are not in the other install routes\n *\n * **The kill switch, at install.** Every other copied artifact treats\n * `revocations` as a plugin concern. An installed email is mailed from the\n * shared sending domain, so a stopped version must not be handed out — and,\n * separately, must stop being sent by tenants who already have it, which is\n * `emailStarterSendBlock` on the send path.\n *\n * **A rejected version, for everybody including its publisher.** Review is not\n * a precondition for installing an email starter — they are auto-listed like\n * every other copied artifact — so most versions are honestly `unreviewed` and\n * install fine. A verdict of `rejected` is different: somebody looked and said\n * no, and the publisher's own site is on the same sending domain as everyone\n * else's.\n *\n * **The policy, re-run over the listing's own bytes.** The publish route\n * already refused a violating design. Re-running it here is not belt and\n * braces about that route — it is the gate for content that never went through\n * it: a version published before this policy existed, a document written by a\n * staff tool, an import. A tracking pixel is only refused if the refusal sits\n * where the content is HANDED OVER, which is the lesson `install-email-template`\n * records about takedown.\n */\nexport const installEmailStarterHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n const listingId = String(req.body?.listingId ?? '')\n const hostId = String(req.body?.hostId ?? '')\n if (!listingId || !hostId) {\n return res.status(400).json({ error: 'Missing listingId or hostId' })\n }\n const authorization = String(req.headers.authorization ?? '')\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken) return res.status(401).json({ error: 'Unauthenticated' })\n\n try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n const membership = await resolveOrgPermissions(decoded.uid, { hostId })\n if (!membership.permissions.installPlugins) {\n return res.status(403).json({\n error:\n 'Your organization role does not allow installing from the marketplace',\n })\n }\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const hostSnapshot = await hostRef.get()\n if (!hostSnapshot.exists) {\n return res.status(404).json({ error: 'Unknown site' })\n }\n // \"Install marketplace items into a site\" (AGL-4047): the site's stamp, else\n // the preset of the member's site role, the Admin and Editor this asked for.\n if (!holdsStampedSiteKey(hostSnapshot, decoded.uid, 'marketplace.siteInstall', MARKETPLACE_SITE_ROLE_PRESET)) {\n return res.status(403).json({ error: marketplaceSitePermissionRefusal('marketplace.siteInstall') })\n }\n\n const listingRef = firestore.collection('marketplaceListings').doc(listingId)\n const listingSnapshot = await listingRef.get()\n const listing = listingSnapshot.data() as any\n if (\n !listing ||\n listing.deletedAt ||\n listing.hiddenAt ||\n // A publisher under a SECURITY lock hands nothing over (AGL-3365).\n (await isPublisherSecurityLocked(firestore, listing.profileId)) ||\n listingArtifactType(listing) !== 'emailStarter'\n ) {\n return res.status(404).json({ error: 'Unknown email starter' })\n }\n\n const ownsListing = await canActAsPublisher(\n firestore,\n decoded.uid,\n listing.profileId,\n )\n if (isPrivateListing(listing) && !ownsListing) {\n return res.status(404).json({ error: 'Unknown listing' })\n }\n const priceUsd = Number(listing.priceUsd ?? 0)\n const unpaid = await requirePurchase({\n firestore,\n buyerUid: decoded.uid,\n buyerOrgId: membership.orgId ?? '',\n listingId,\n priceUsd,\n ownsListing,\n })\n if (unpaid) return res.status(402).json(unpaid)\n\n const version = listing.latestVersion\n const revocation = (\n await firestore.collection('revocations').doc(listingId).get()\n ).data() as PluginRevocation | undefined\n if (isPluginRevoked(revocation, String(version ?? ''))) {\n return res\n .status(409)\n .json({ error: 'This email design has been stopped by Aglyn' })\n }\n\n const versionSnapshot = await listingRef\n .collection('versions')\n .doc(String(version))\n .get()\n if (!versionSnapshot.exists) {\n return res.status(500).json({ error: 'Email starter version missing' })\n }\n /**\n * The assurance of THIS version, from THIS version's document.\n *\n * Read here rather than off the listing, and stamped rather than\n * recomputed later, because the listing's own review fields answer a\n * different question. `reviewStatus: 'verified'` is a claim about the\n * publisher; `latestVersionReviewState` describes whatever is newest. A\n * reader that consulted either would report version 7 as reviewed on the\n * strength of version 3, which is how \"reviewed\" stops meaning anything.\n */\n const assurance = resolveEmailStarterAssurance({\n reviewState: versionSnapshot.get('reviewState'),\n })\n if (assurance === 'rejected') {\n return res.status(409).json({\n error: 'This email design was turned down in review and cannot be installed',\n })\n }\n\n const inspection = inspectEmailStarter(versionSnapshot.get('nodes'), {\n hostId,\n })\n const violation = emailStarterRefusal(inspection)\n if (violation) {\n return res\n .status(422)\n .json({ error: violation, violations: inspection.violations })\n }\n const nodes = inspection.nodes\n if (!nodes || !Object.keys(nodes).length) {\n return res.status(500).json({ error: 'Email starter version missing' })\n }\n\n const subject = String(versionSnapshot.get('subject') ?? '')\n const preheader = String(versionSnapshot.get('preheader') ?? '')\n const rootId = versionSnapshot.get('rootId') ?? null\n const provenance = await recordInstallProvenance({\n firestore,\n listingId,\n listing,\n version,\n artifactType: 'emailStarter',\n content: { rootId, nodes, subject, preheader },\n })\n const installedFrom = { ...provenance.installedFrom, assurance }\n\n const screenId = createResourceUid()\n const versionId = createResourceUid()\n const now = firebaseAdmin.firestore.FieldValue.serverTimestamp()\n const displayName = String(listing.displayName ?? 'Installed email').slice(\n 0,\n 120,\n )\n const batch = firestore.batch()\n const screenRef = hostRef.collection('screens').doc(screenId)\n /**\n * The same document shape `createEmailScreen` writes, so the Email\n * templates list, the screen besigner and the campaign composer all find\n * it without knowing it came from anywhere.\n *\n * NOT routed, and `kind: 'email'`, which is what keeps it out of\n * `countBillableScreens` — an installed email spends the same allowance a\n * hand-made one does, which is none.\n *\n * `nodes` is written as a plain map here, exactly as the first version\n * from `/api/hosts/versions` is. The besigner's converter compresses on\n * the first save, and `decodeStoredNodes` is what every reader on this\n * path already goes through, so both forms are handled from the start.\n */\n batch.set(screenRef, {\n displayName,\n // The keys the email templates list finds it by (AGL-3321).\n ...artifactCreateListKeys('screens', { displayName }),\n kind: 'email',\n versionId,\n ...(subject && { emailSubject: subject }),\n ...(preheader && { emailPreheader: preheader }),\n installedFrom,\n createdAt: now,\n updatedAt: now,\n })\n batch.set(screenRef.collection('versions').doc(versionId), {\n screenId,\n ...(rootId ? { rootId } : {}),\n nodes,\n // Stamped on the VERSION as well as the screen, because the version is\n // what the send path renders and the send path is where the kill switch\n // has to bite. A stamp only on the parent would be one document away\n // from the bytes it describes.\n installedFrom,\n createdAt: now,\n updatedAt: now,\n })\n await batch.commit()\n\n await recordVersionMove({\n firestore,\n listingRef,\n artifactType: 'emailStarter',\n to: version,\n })\n await listingRef\n .update({\n installCount: firebaseAdmin.firestore.FieldValue.increment(1),\n })\n .catch(() => undefined)\n\n return res.status(200).json({\n installed: true,\n screenId,\n versionId,\n version: version ?? null,\n assurance,\n linkHosts: inspection.linkHosts,\n foreignMediaScopes: inspection.foreignMediaScopes,\n baseStored: provenance.baseStored,\n })\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Email starter install failed' })\n }\n}\n\nexport default installEmailStarterHandler\n"],"names":["holdsStampedSiteKey","MARKETPLACE_SITE_ROLE_PRESET","marketplaceSitePermissionRefusal","artifactCreateListKeys","createResourceUid","isPluginRevoked","firebaseAdmin","resolveOrgPermissions","emailStarterRefusal","inspectEmailStarter","isPrivateListing","listingArtifactType","resolveEmailStarterAssurance","canActAsPublisher","requirePurchase","recordInstallProvenance","recordVersionMove","isPublisherSecurityLocked","installEmailStarterHandler","req","res","method","status","json","error","listingId","String","body","hostId","authorization","headers","idToken","startsWith","slice","length","undefined","listing","membership","versionSnapshot","decoded","app","auth","verifyIdToken","uid","permissions","installPlugins","firestore","hostRef","collection","doc","hostSnapshot","get","exists","listingRef","listingSnapshot","data","deletedAt","hiddenAt","profileId","ownsListing","priceUsd","Number","unpaid","buyerUid","buyerOrgId","orgId","version","latestVersion","revocation","assurance","reviewState","inspection","violation","violations","nodes","Object","keys","subject","preheader","rootId","provenance","artifactType","content","installedFrom","screenId","versionId","now","FieldValue","serverTimestamp","displayName","batch","screenRef","set","kind","emailSubject","emailPreheader","createdAt","updatedAt","commit","to","update","installCount","increment","catch","installed","linkHosts","foreignMediaScopes","baseStored","console"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,uEAAuE;AACvE,yEAAyE;AACzE,iCAAiC;AACjC,SAASA,mBAAmB,QAAQ,0CAAyC;AAC7E,SAASC,4BAA4B,EAAEC,gCAAgC,QAAQ,2CAAuC;AACtH,SAASC,sBAAsB,QAAQ,4CAA2C;AAClF,SAASC,iBAAiB,EAAEC,eAAe,QAAQ,sBAAqB;AAGxE,SAASC,aAAa,QAAQ,2BAA0B;AACxD,SAASC,qBAAqB,QAAQ,wCAAuC;AAC7E,SACEC,mBAAmB,EACnBC,mBAAmB,EACnBC,gBAAgB,EAChBC,mBAAmB,EACnBC,4BAA4B,QACvB,oBAAU;AACjB,SAASC,iBAAiB,QAAQ,yBAAqB;AACvD,SAASC,eAAe,QAAQ,4BAAwB;AACxD,SAASC,uBAAuB,QAAQ,kBAAc;AACtD,SAASC,iBAAiB,QAAQ,qBAAiB;AACnD,SAASC,yBAAyB,QAAQ,iBAAa;AAEvD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA6CC,GACD,OAAO,MAAMC,6BAA+C,OAAOC,KAAKC;qBASzCD;QALJA,WACHA;IAJtB,IAAIA,IAAIE,MAAM,KAAK,QAAQ;QACzB,OAAOD,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAqB;IAC5D;IACA,MAAMC,YAAYC,gB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