@aglyn/plugins-marketplace 1.0.0-beta.199 → 1.0.0-beta.201
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +14 -14
- package/src/lib/components/marketplace-browse.component.js +104 -169
- package/src/lib/components/marketplace-browse.component.js.map +1 -1
- package/src/lib/components/marketplace-reports-page.component.js +9 -0
- package/src/lib/components/marketplace-reports-page.component.js.map +1 -1
- package/src/lib/components/org-licences-panel.component.js +212 -170
- package/src/lib/components/org-licences-panel.component.js.map +1 -1
- package/src/lib/components/org-seller-panel.component.js +23 -5
- package/src/lib/components/org-seller-panel.component.js.map +1 -1
- package/src/lib/components/plugin-reviews-queue.component.d.ts +9 -0
- package/src/lib/components/plugin-reviews-queue.component.js +190 -114
- package/src/lib/components/plugin-reviews-queue.component.js.map +1 -1
- package/src/lib/hooks/use-listing-name-lookup.d.ts +34 -0
- package/src/lib/hooks/use-listing-name-lookup.js +131 -0
- package/src/lib/hooks/use-listing-name-lookup.js.map +1 -0
- package/src/lib/model/listing-query.d.ts +140 -0
- package/src/lib/model/listing-query.js +393 -0
- package/src/lib/model/listing-query.js.map +1 -0
- package/src/lib/model/marketplace.d.ts +11 -0
- package/src/lib/model/marketplace.js.map +1 -1
- package/src/lib/server/admin-reports.js +30 -12
- package/src/lib/server/admin-reports.js.map +1 -1
- package/src/lib/server/admin-reviews.js +180 -128
- package/src/lib/server/admin-reviews.js.map +1 -1
- package/src/lib/server/admin-trust.js +2 -1
- package/src/lib/server/admin-trust.js.map +1 -1
- package/src/lib/server/billing-webhook.js +13 -1
- package/src/lib/server/billing-webhook.js.map +1 -1
- package/src/lib/server/checkout.js +3 -1
- package/src/lib/server/checkout.js.map +1 -1
- package/src/lib/server/install-email-starter.js +9 -2
- package/src/lib/server/install-email-starter.js.map +1 -1
- package/src/lib/server/install-layout.js +17 -5
- package/src/lib/server/install-layout.js.map +1 -1
- package/src/lib/server/install-template.js +15 -5
- package/src/lib/server/install-template.js.map +1 -1
- package/src/lib/server/install.js +10 -2
- package/src/lib/server/install.js.map +1 -1
- package/src/lib/server/listing-query-fields.d.ts +38 -0
- package/src/lib/server/listing-query-fields.js +50 -0
- package/src/lib/server/listing-query-fields.js.map +1 -0
- package/src/lib/server/publish-dataset-schema.js +6 -2
- package/src/lib/server/publish-dataset-schema.js.map +1 -1
- package/src/lib/server/publish-email-starter.js +6 -2
- package/src/lib/server/publish-email-starter.js.map +1 -1
- package/src/lib/server/publish-email-template.js +6 -2
- package/src/lib/server/publish-email-template.js.map +1 -1
- package/src/lib/server/publish-layout.js +6 -2
- package/src/lib/server/publish-layout.js.map +1 -1
- package/src/lib/server/publish-plugin.js +75 -7
- package/src/lib/server/publish-plugin.js.map +1 -1
- package/src/lib/server/publish-template.js +6 -2
- package/src/lib/server/publish-template.js.map +1 -1
- package/src/lib/server/publish-theme.js +6 -2
- package/src/lib/server/publish-theme.js.map +1 -1
- package/src/lib/server/publish.js +6 -2
- package/src/lib/server/publish.js.map +1 -1
- package/src/lib/server/update-artifact.js +18 -4
- package/src/lib/server/update-artifact.js.map +1 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/marketplace/src/lib/model/listing-query.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n displayNameSearchFields,\n scopedSearch,\n scopedSearchTokens,\n} from '@aglyn/aglyn/app-utils/name-search'\nimport {\n isListingBrowsable,\n isListingDeleted,\n isPrivateListing,\n} from '@aglyn/aglyn/app-utils/marketplace-listing-visibility'\nimport type { ListFilterField } from '@aglyn/shared-ui-jsx/const/list-filter'\nimport type { ListFilterClause } from '@aglyn/shared-ui-jsx/const/list-grid-filter'\nimport {\n LIST_QUERY_ID_PATH,\n type ListQueryDeclaration,\n type ListQueryFilter,\n type ListQuerySort,\n} from '@aglyn/shared-ui-jsx/const/list-query-plan'\n\n/*\n * EVERY MARKETPLACE LIST ON ITS QUERY (AGL-3321).\n *\n * Browse, the licenses tab, the staff review queue and the abuse-report queue\n * each matched their filters and search over the rows they had loaded — a\n * window of ninety listings, two hundred reports, a hundred plugins. A match\n * on the next page was answered \"no match\". Each list now declares what its\n * query can hold, and the fields below are what the listing writers stamp so\n * the query has something to ask.\n *\n * ## What a listing carries for its lists\n *\n * - `nameLower`/`nameTokens`/`nameReversed` — the display name's search\n * keys (`displayNameSearchFields`), for the staff queue's search and for\n * the licenses tab's listing-name lookup.\n * - `browseAudience` — who browse shows the listing to, as scope tokens:\n * `*` for everyone, the publisher's org id for the owner's own view of a\n * listing still in review or taken down, and each again joined to the\n * publisher (`*|<org>`) so a publisher page asks the same question\n * narrowed to one publisher without a second equality. Empty for a\n * deleted or private listing, which browse never shows anyone.\n * - `browseTokens` — the name tokens under each audience scope\n * (`scopedSearchTokens`), so browse's search folds into its audience\n * clause: one `array-contains-any` answers both.\n * - `takenDown` — `hiddenAt` as a boolean, for the staff queue's Taken down\n * status by equality rather than by a range that would lead the order.\n *\n * All five follow from fields other writers own (`displayName`, `deletedAt`,\n * `visibility`, `hiddenAt`, `reviewStatus`, the artifact discriminators,\n * `profileId`), so no writer computes them from its own patch: each calls\n * `refreshListingQueryFields` after it writes, which re-derives them from the\n * document as stored. `tools/scripts/lib/listing-query-fields.mjs`\n * restates the derivation for the seeds and the backfill, held to\n * `listing-query-fields.fixtures.json` beside it by both sides.\n */\n\n/** Everyone, as a browse audience scope. */\nexport const BROWSE_EVERYONE = '*'\n/** Joins an audience scope to the publisher it is narrowed to. */\nexport const BROWSE_PUBLISHER_JOIN = '|'\n\nexport const LISTING_BROWSE_AUDIENCE = 'browseAudience'\nexport const LISTING_BROWSE_TOKENS = 'browseTokens'\nexport const LISTING_NAME_TOKENS = 'nameTokens'\nexport const LISTING_TAKEN_DOWN = 'takenDown'\n\n/** The fields a listing's lists query by, all derived. */\nexport interface ListingQueryFields {\n nameLower: string\n nameTokens: string[]\n nameReversed: string\n browseAudience: string[]\n browseTokens: string[]\n takenDown: boolean\n}\n\n/** What the derivation reads off a listing. */\nexport interface ListingQuerySource {\n displayName?: unknown\n profileId?: unknown\n deletedAt?: unknown\n hiddenAt?: unknown\n visibility?: string\n reviewStatus?: string\n artifactType?: string\n type?: string\n kind?: string\n}\n\n/**\n * Who browse shows a listing to — the same rule the grid applied in memory:\n * never a deleted or private listing; a browsable one to everyone; one that\n * is not browsable (in review, rejected, taken down) to its own publisher\n * only, so a publisher can watch a submission move through review.\n */\nexport function listingBrowseAudience(listing: ListingQuerySource): string[] {\n if (isListingDeleted(listing) || isPrivateListing(listing)) return []\n const publisher = typeof listing.profileId === 'string' ? listing.profileId : ''\n const scope = isListingBrowsable(listing) ? BROWSE_EVERYONE : publisher\n if (!scope) return []\n return publisher\n ? [scope, `${scope}${BROWSE_PUBLISHER_JOIN}${publisher}`]\n : [scope]\n}\n\n/** Every derived field, from the listing as stored. */\nexport function listingQueryFields(listing: ListingQuerySource): ListingQueryFields {\n const name = displayNameSearchFields(listing.displayName)\n const browseAudience = listingBrowseAudience(listing)\n return {\n ...name,\n browseAudience,\n browseTokens: scopedSearchTokens(browseAudience, name.nameTokens),\n takenDown: Boolean(listing.hiddenAt),\n }\n}\n\nconst same = (left: unknown, right: unknown): boolean =>\n JSON.stringify(left ?? null) === JSON.stringify(right ?? null)\n\n/**\n * What a listing that never had one holds in each field browse ORDERS by. An\n * `orderBy` drops a document missing its field, so a listing nobody has\n * installed or rated would vanish from Most installed and Highest rated\n * rather than sort last. `null` sorts after every number in a descending\n * order, which is where \"not yet rated\" belongs; the reviews route writes a\n * number over it on the first rating. Only ever stamped where the field is\n * ABSENT — the install and review routes own the values.\n */\nexport const LISTING_SORT_DEFAULTS: Readonly<Record<string, number | null>> = {\n installCount: 0,\n ratingAverage: null,\n}\n\n/**\n * The derived fields a stored listing is missing or holds stale, plus any\n * sort field it lacks, or null when it is current — what a writer's refresh\n * and the backfill write.\n */\nexport function listingQueryFieldsPatch(\n listing: ListingQuerySource & Record<string, unknown>,\n): Record<string, unknown> | null {\n const computed = listingQueryFields(listing)\n const patch: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(computed)) {\n if (!same(listing[key], value)) patch[key] = value\n }\n for (const [key, value] of Object.entries(LISTING_SORT_DEFAULTS)) {\n if (listing[key] === undefined) patch[key] = value\n }\n return Object.keys(patch).length ? patch : null\n}\n\n/*==========================================\n * Browse (public, web SDK).\n *=========================================*/\n\nexport type BrowseSort = 'newest' | 'installed' | 'rated'\n\nexport const BROWSE_SORTS: Readonly<Record<BrowseSort, ListQuerySort>> = {\n newest: { path: 'createdAt', direction: 'desc' },\n installed: { path: 'installCount', direction: 'desc' },\n rated: { path: 'ratingAverage', direction: 'desc' },\n}\n\n/**\n * The browse shelf: a category chip, the search box and three orders, every\n * one on the query. The audience clause is its base (`browseBase`), and the\n * search folds into it.\n */\nexport const MARKETPLACE_BROWSE_QUERY: ListQueryDeclaration = {\n fields: [\n { column: 'category', kind: 'exact', path: 'category', operators: ['equals'] },\n ] satisfies ListFilterField[],\n sorts: [BROWSE_SORTS.newest, BROWSE_SORTS.installed, BROWSE_SORTS.rated],\n search: {\n tokensPath: LISTING_BROWSE_TOKENS,\n scoped: scopedSearch(LISTING_BROWSE_TOKENS),\n },\n}\n\n/** The base clause's path, for the index enumeration. */\nexport const MARKETPLACE_BROWSE_BASE_PATHS = [\n { path: LISTING_BROWSE_AUDIENCE, array: true },\n] as const\n\n/**\n * What a reader may see on browse: everything public, plus their own org's\n * listings still in review — narrowed to one publisher on a publisher page.\n */\nexport function browseBase(\n viewerOrgId: string | null | undefined,\n publisherId?: string | null,\n): ListQueryFilter[] {\n const scopes = [BROWSE_EVERYONE, ...(viewerOrgId ? [viewerOrgId] : [])]\n return [\n {\n path: LISTING_BROWSE_AUDIENCE,\n op: 'array-contains-any',\n value: publisherId\n ? scopes.map((scope) => `${scope}${BROWSE_PUBLISHER_JOIN}${publisherId}`)\n : scopes,\n },\n ]\n}\n\n/*==========================================\n * Licenses (`marketplacePurchases`, web SDK, buyer/org-gated).\n *=========================================*/\n\n/**\n * Both license tables keep the order they always had — Firestore's, by\n * document id — which index merging serves with no composite at all.\n */\nconst BY_ID: ListQuerySort = { path: LIST_QUERY_ID_PATH, direction: 'asc' }\n\n/** \"This workspace\": who on the team bought it. */\nexport const HELD_LICENCE_QUERY: ListQueryDeclaration = {\n fields: [\n { column: 'buyerUid', kind: 'exact', path: 'buyerUid', operators: ['equals'] },\n ] satisfies ListFilterField[],\n sorts: [BY_ID],\n}\n\n/**\n * \"Bought by you\": which workspace a license landed in. A purchase that\n * names none (before AGL-2331) is stored with `buyerOrgId: null` and is\n * asked for as empty.\n */\nexport const MINE_LICENCE_QUERY: ListQueryDeclaration = {\n fields: [\n {\n column: 'buyerOrgId',\n kind: 'exact',\n path: 'buyerOrgId',\n presence: 'nullable',\n operators: ['equals', 'isEmpty'],\n },\n ] satisfies ListFilterField[],\n sorts: [BY_ID],\n}\n\n/** The picked value that means \"every workspace\" — a purchase naming none. */\nexport const EVERY_WORKSPACE = 'every'\n\n/**\n * The Licensed-to select's \"every workspace\" as the query reads it: a\n * purchase whose `buyerOrgId` is null.\n */\nexport function mineLicenceClauses(\n clauses: readonly ListFilterClause[],\n): ListFilterClause[] {\n return clauses.map((clause) =>\n clause.field === 'buyerOrgId' && clause.op === 'equals' && clause.value === EVERY_WORKSPACE\n ? { ...clause, op: 'isEmpty', value: '' }\n : clause,\n )\n}\n\n/**\n * At most this many listings are named by one license search: they go on the\n * purchases query as `listingId in [...]`, which Firestore caps at thirty.\n */\nexport const LICENCE_LISTING_MATCH_CAP = 30\n\n/**\n * The listing-name lookup a license search runs first: the listings whose\n * name has the typed word, by the same token array the staff queue searches.\n */\nexport const LISTING_NAME_LOOKUP: ListQueryDeclaration = {\n fields: [],\n sorts: [BY_ID],\n search: { tokensPath: LISTING_NAME_TOKENS },\n}\n\n/**\n * A license table's scope: its owner clause, live purchases only (a refunded\n * purchase is not a license, AGL-1546), and the listings a search named.\n */\nexport function licenceBase(\n owner: { path: 'buyerOrgId' | 'buyerUid'; value: string },\n listingIds: readonly string[] | null,\n): ListQueryFilter[] {\n return [\n { path: owner.path, op: '==', value: owner.value },\n { path: 'refundedAt', op: '==', value: null },\n ...(listingIds ? [{ path: 'listingId', op: 'in' as const, value: [...listingIds] }] : []),\n ]\n}\n\n/*==========================================\n * The staff review queue (Admin SDK, staff route).\n *=========================================*/\n\n/** The queue's Status select, as clauses the query serves. */\nexport const REVIEW_QUEUE_QUERY: ListQueryDeclaration = {\n fields: [\n { column: 'reviewStatus', kind: 'exact', path: 'reviewStatus', operators: ['equals'] },\n { column: LISTING_TAKEN_DOWN, kind: 'boolean', path: LISTING_TAKEN_DOWN },\n ] satisfies ListFilterField[],\n sorts: [BY_ID],\n search: { tokensPath: LISTING_NAME_TOKENS },\n}\n\n/** The three sections the queue reads, each its own query. */\nexport type ReviewQueueSection = 'queue' | 'listed' | 'verification'\n\n/** A listing's newest bytes have no approval: the `latestVersionReviewState` values that mean it. */\nexport const AWAITING_REVIEW_STATES = ['pending', 'rejected'] as const\nexport const LISTED_REVIEW_STATUSES = ['listed', 'verified'] as const\n\n/**\n * One section's scope: live plugin listings, narrowed to the section. The\n * Listed section's own `reviewStatus in [...]` steps aside for a Status\n * clause that names one of its two values, and a clause naming any other\n * value leaves the section empty by definition — `null`, never queried.\n */\nexport function reviewQueueBase(\n section: ReviewQueueSection,\n clauses: readonly ListFilterClause[],\n): ListQueryFilter[] | null {\n const base: ListQueryFilter[] = [\n { path: 'type', op: '==', value: 'plugin' },\n { path: 'deletedAt', op: '==', value: null },\n ]\n if (section === 'queue') {\n base.push({\n path: 'latestVersionReviewState',\n op: 'in',\n value: [...AWAITING_REVIEW_STATES],\n })\n } else if (section === 'verification') {\n base.push({ path: 'verificationRequest.state', op: '==', value: 'pending' })\n } else {\n const status = clauses.find(\n (clause) => clause.field === 'reviewStatus' && clause.op === 'equals' && clause.value,\n )\n if (status) {\n if (!(LISTED_REVIEW_STATUSES as readonly string[]).includes(status.value)) return null\n } else {\n base.push({ path: 'reviewStatus', op: 'in', value: [...LISTED_REVIEW_STATUSES] })\n }\n }\n return base\n}\n\n/** The queue's Status select as the clause it asks for, or none for \"All\". */\nexport function reviewQueueStatusClauses(status: string): ListFilterClause[] {\n if (!status || status === 'all') return []\n if (status === 'hidden') return [{ field: LISTING_TAKEN_DOWN, op: 'is', value: 'true' }]\n return [{ field: 'reviewStatus', op: 'equals', value: status }]\n}\n\n/*==========================================\n * The abuse-report queue (Admin SDK, staff route).\n *=========================================*/\n\nexport const MARKETPLACE_REPORTS_QUERY: ListQueryDeclaration = {\n fields: [\n { column: 'status', kind: 'exact', path: 'status', operators: ['equals'] },\n ] satisfies ListFilterField[],\n sorts: [{ path: 'updatedAt', direction: 'desc' }],\n}\n"],"names":["displayNameSearchFields","scopedSearch","scopedSearchTokens","isListingBrowsable","isListingDeleted","isPrivateListing","LIST_QUERY_ID_PATH","BROWSE_EVERYONE","BROWSE_PUBLISHER_JOIN","LISTING_BROWSE_AUDIENCE","LISTING_BROWSE_TOKENS","LISTING_NAME_TOKENS","LISTING_TAKEN_DOWN","listingBrowseAudience","listing","publisher","profileId","scope","listingQueryFields","name","displayName","browseAudience","browseTokens","nameTokens","takenDown","Boolean","hiddenAt","same","left","right","JSON","stringify","LISTING_SORT_DEFAULTS","installCount","ratingAverage","listingQueryFieldsPatch","computed","patch","key","value","Object","entries","undefined","keys","length","BROWSE_SORTS","newest","path","direction","installed","rated","MARKETPLACE_BROWSE_QUERY","fields","column","kind","operators","sorts","search","tokensPath","scoped","MARKETPLACE_BROWSE_BASE_PATHS","array","browseBase","viewerOrgId","publisherId","scopes","op","map","BY_ID","HELD_LICENCE_QUERY","MINE_LICENCE_QUERY","presence","EVERY_WORKSPACE","mineLicenceClauses","clauses","clause","field","LICENCE_LISTING_MATCH_CAP","LISTING_NAME_LOOKUP","licenceBase","owner","listingIds","REVIEW_QUEUE_QUERY","AWAITING_REVIEW_STATES","LISTED_REVIEW_STATUSES","reviewQueueBase","section","base","push","status","find","includes","reviewQueueStatusClauses","MARKETPLACE_REPORTS_QUERY"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,uBAAuB,EACvBC,YAAY,EACZC,kBAAkB,QACb,qCAAoC;AAC3C,SACEC,kBAAkB,EAClBC,gBAAgB,EAChBC,gBAAgB,QACX,wDAAuD;AAG9D,SACEC,kBAAkB,QAIb,6CAA4C;AAEnD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAkCC,GAED,0CAA0C,GAC1C,OAAO,MAAMC,kBAAkB,IAAG;AAClC,gEAAgE,GAChE,OAAO,MAAMC,wBAAwB,IAAG;AAExC,OAAO,MAAMC,0BAA0B,iBAAgB;AACvD,OAAO,MAAMC,wBAAwB,eAAc;AACnD,OAAO,MAAMC,sBAAsB,aAAY;AAC/C,OAAO,MAAMC,qBAAqB,YAAW;AAyB7C;;;;;CAKC,GACD,OAAO,SAASC,sBAAsBC,OAA2B;IAC/D,IAAIV,iBAAiBU,YAAYT,iBAAiBS,UAAU,OAAO,EAAE;IACrE,MAAMC,YAAY,OAAOD,QAAQE,SAAS,KAAK,WAAWF,QAAQE,SAAS,GAAG;IAC9E,MAAMC,QAAQd,mBAAmBW,WAAWP,kBAAkBQ;IAC9D,IAAI,CAACE,OAAO,OAAO,EAAE;IACrB,OAAOF,YACH;QAACE;QAAO,GAAGA,QAAQT,wBAAwBO,WAAW;KAAC,GACvD;QAACE;KAAM;AACb;AAEA,qDAAqD,GACrD,OAAO,SAASC,mBAAmBJ,OAA2B;IAC5D,MAAMK,OAA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I4C;aAAuB;QACpC;IACF,OAAO,IAAIG,YAAY,gBAAgB;QACrCC,KAAKC,IAAI,CAAC;YAAEzC,MAAM;YAA6BmB,IAAI;YAAM3B,OAAO;QAAU;IAC5E,OAAO;QACL,MAAMkD,SAASf,QAAQgB,IAAI,CACzB,CAACf,SAAWA,OAAOC,KAAK,KAAK,kBAAkBD,OAAOT,EAAE,KAAK,YAAYS,OAAOpC,KAAK;QAEvF,IAAIkD,QAAQ;YACV,IAAI,CAAC,AAACL,uBAA6CO,QAAQ,CAACF,OAAOlD,KAAK,GAAG,OAAO;QACpF,OAAO;YACLgD,KAAKC,IAAI,CAAC;gBAAEzC,MAAM;gBAAgBmB,IAAI;gBAAM3B,OAAO;uBAAI6C;iBAAuB;YAAC;QACjF;IACF;IACA,OAAOG;AACT;AAEA,4EAA4E,GAC5E,OAAO,SAASK,yBAAyBH,MAAc;IACrD,IAAI,CAACA,UAAUA,WAAW,OAAO,OAAO,EAAE;IAC1C,IAAIA,WAAW,UAAU,OAAO;QAAC;YAAEb,OAAOhE;YAAoBsD,IAAI;YAAM3B,OAAO;QAAO;KAAE;IACxF,OAAO;QAAC;YAAEqC,OAAO;YAAgBV,IAAI;YAAU3B,OAAOkD;QAAO;KAAE;AACjE;AAEA;;2CAE2C,GAE3C,OAAO,MAAMI,4BAAkD;IAC7DzC,QAAQ;QACN;YAAEC,QAAQ;YAAUC,MAAM;YAASP,MAAM;YAAUQ,WAAW;gBAAC;aAAS;QAAC;KAC1E;IACDC,OAAO;QAAC;YAAET,MAAM;YAAaC,WAAW;QAAO;KAAE;AACnD,EAAC"}
|
|
@@ -191,6 +191,17 @@ export interface MarketplaceListing {
|
|
|
191
191
|
reviewedBy?: string;
|
|
192
192
|
reviewedAt?: unknown;
|
|
193
193
|
rejectionReason?: string;
|
|
194
|
+
/**
|
|
195
|
+
* What the marketplace lists query by (AGL-3321), derived by the server
|
|
196
|
+
* from the fields above after every write (`listingQueryFields`,
|
|
197
|
+
* `refreshListingQueryFields`) and denied to clients.
|
|
198
|
+
*/
|
|
199
|
+
nameLower?: string;
|
|
200
|
+
nameTokens?: string[];
|
|
201
|
+
nameReversed?: string;
|
|
202
|
+
browseAudience?: string[];
|
|
203
|
+
browseTokens?: string[];
|
|
204
|
+
takenDown?: boolean;
|
|
194
205
|
}
|
|
195
206
|
/**
|
|
196
207
|
* Everything an org can publish to the marketplace (AGL-654).
|
|
@@ -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 '@aglyn/aglyn/app-utils/plan-entitlements'\nimport type { MarketplaceArtifactType } from '@aglyn/aglyn/app-utils/marketplace-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 '@aglyn/aglyn/app-utils/marketplace-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\n/**\n * Everything an org can publish to the marketplace (AGL-654).\n *\n * Defined in core and re-exported here (AGL-1016): the console needs it to\n * render update state for installed artifacts, and an app may not depend on an\n * addon lib. Publishing code keeps importing it from this model unchanged.\n */\nexport type { MarketplaceArtifactType }\n\n/**\n * Human-readable label for each artifact type (AGL-864).\n *\n * Shared by browse cards, the listing detail page, and the seller panel so\n * \"what kind of thing is this\" reads the same everywhere. Resolve a listing's\n * label through {@link listingArtifactLabel}, which tolerates the legacy\n * `type`/`kind` shape the way {@link listingArtifactType} does.\n */\nexport const ARTIFACT_TYPE_LABELS: Record<MarketplaceArtifactType, string> = {\n plugin: 'Plugin',\n component: 'Component',\n template: 'Site template',\n layout: 'Layout',\n datasetSchema: 'Dataset schema',\n emailTemplate: 'Email template',\n emailStarter: 'Email starter',\n theme: 'Theme',\n}\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/** Where an installed artifact lives. */\nexport type InstallTarget = 'org' | 'host'\n\n/**\n * Install targets each artifact type actually supports (AGL-656).\n *\n * This is not a policy choice — it is where the install routes physically\n * write. Only plugins have an org-scoped pin\n * (`orgs/{orgId}/installs/{listingId}`, applying to every site, shadowed by\n * a host pin). Components land in `hosts/{h}/components`, templates and\n * layouts in `hosts/{h}/templates`: all host-scoped by nature, because a\n * screen tree belongs to a site.\n *\n * Exported so the UI can ask rather than assume — an install picker that\n * offers \"this whole organization\" for a template would be lying.\n */\nexport const INSTALL_TARGETS: Record<\n MarketplaceArtifactType,\n readonly InstallTarget[]\n> = {\n plugin: ['org', 'host'],\n component: ['host'],\n template: ['host'],\n layout: ['host'],\n // Dataset schemas are org-shared data (AGL-237), so they install at org\n // scope — as a new empty dataset, not a pin (AGL-657).\n datasetSchema: ['org'],\n emailTemplate: ['host'],\n // A campaign email is a screen, and a screen belongs to a site.\n emailStarter: ['host'],\n // A theme is one site's visual identity, written to `hosts/{h}.theme`\n // (AGL-1020). Applying one org-wide would repaint every site at once from a\n // control that says \"install\".\n theme: ['host'],\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/** A plugin install pin — the version-pinned doc the install API writes. */\nexport interface InstallPin {\n version?: number | string\n}\n\n/**\n * The install state of a plugin listing for one site, told honestly (AGL-656).\n *\n * A plugin can be pinned at two scopes: the org pin\n * (`orgs/{orgId}/installs/{listingId}`) applies to every site, and a host pin\n * (`hosts/{hostId}/installs/{listingId}`) applies to just this one AND shadows\n * the org pin. Detecting installs from `hosts/{h}/components` — the COMPONENT\n * collection — never sees either pin, so an installed plugin used to read as\n * \"not installed\" on both the browse grid and the detail page. This resolves\n * the effective state from the two pins the way the loader does.\n */\nexport interface PluginInstallState {\n /** Effective pin scope for this site — host wins over org — or null. */\n scope: InstallTarget | null\n /** Version pinned at the effective scope, or null when not installed. */\n installedVersion: string | null\n /** Both pins exist: the host pin takes precedence, shadowing the org one. */\n shadowed: boolean\n /** Installed, but the pinned version is behind the listing's latest. */\n updateAvailable: boolean\n}\n\n/**\n * Resolves a plugin listing's install state for a site from its two pins\n * (AGL-656). The host pin shadows the org pin, mirroring the loader, so the\n * effective version and update prompt always describe what actually runs here.\n */\nexport function resolvePluginInstallState(\n latestVersion: number | string | undefined,\n hostPin: InstallPin | null | undefined,\n orgPin: InstallPin | null | undefined,\n): PluginInstallState {\n const effective = hostPin ?? orgPin ?? null\n const installedVersion =\n effective?.version != null ? String(effective.version) : null\n return {\n scope: hostPin ? 'host' : orgPin ? 'org' : null,\n installedVersion,\n shadowed: Boolean(hostPin && orgPin),\n // Any difference is an upgrade prompt, matching the installed-plugins card\n // — pins only ever move forward, so \"different\" means \"behind\".\n updateAvailable:\n installedVersion != null &&\n latestVersion != null &&\n String(latestVersion) !== installedVersion,\n }\n}\n\n/** One site's slice of an org-scope install picture (AGL-997). */\nexport interface OrgInstallSite {\n hostId: string\n label: string\n /** The version that actually runs here, from the effective pin. */\n version: string | null\n /** Where that pin lives — a host pin shadows the org one, as the loader does. */\n pinnedBy: InstallTarget\n /** This site has its OWN pin on top of an org pin. */\n shadowed: boolean\n}\n\n/**\n * The whole org's install picture for one listing (AGL-997).\n *\n * At org scope, \"installed\" is a SET, not a boolean. The detail page used to\n * resolve state against the single acting host, so a plugin installed on one\n * of five sites reported \"Installed on this site\" — describing one arbitrary\n * site and staying silent about the other four — and offered an Uninstall\n * that was all-or-nothing.\n *\n * `orgWide` and per-site pins are not exclusive: an org pin covers every\n * site including ones created later, and a host pin on top of it shadows it\n * for that one site. Both facts have to survive into the UI, which is why\n * this returns the sites AND the pins rather than a single scope.\n */\nexport interface OrgInstallSummary {\n /** An org pin exists: every site is covered, including future ones. */\n orgWide: boolean\n /** Version of the org pin, when there is one. */\n orgVersion: string | null\n /** Every site the listing effectively runs on. */\n sites: OrgInstallSite[]\n /** Sites carrying their own removable host pin. */\n hostPinnedIds: string[]\n /** Sites with no pin of their own and no org pin covering them. */\n availableHostIds: string[]\n installedAnywhere: boolean\n}\n\nexport function resolveOrgInstallSummary(\n hosts: ReadonlyArray<{ id: string; label: string }>,\n hostPins: Readonly<Record<string, InstallPin | null | undefined>>,\n orgPin: InstallPin | null | undefined,\n): OrgInstallSummary {\n const orgWide = Boolean(orgPin)\n const orgVersion = orgPin?.version != null ? String(orgPin.version) : null\n const sites: OrgInstallSite[] = []\n const hostPinnedIds: string[] = []\n const availableHostIds: string[] = []\n for (const host of hosts) {\n const hostPin = hostPins[host.id]\n if (hostPin) hostPinnedIds.push(host.id)\n if (!hostPin && !orgPin) {\n availableHostIds.push(host.id)\n continue\n }\n sites.push({\n hostId: host.id,\n label: host.label,\n version:\n hostPin?.version != null ? String(hostPin.version) : orgVersion,\n pinnedBy: hostPin ? 'host' : 'org',\n shadowed: Boolean(hostPin && orgPin),\n })\n }\n return {\n orgWide,\n orgVersion,\n sites,\n hostPinnedIds,\n availableHostIds,\n installedAnywhere: orgWide || hostPinnedIds.length > 0,\n }\n}\n\n/** One site an uninstall would touch, and whether it really loses the plugin. */\nexport interface UninstallTarget {\n hostId: string\n label: string\n /**\n * The plugin keeps running here. Removing a HOST pin while an org pin still\n * covers the site, or the ORG pin while the site holds its own host pin,\n * changes which pointer is in use and nothing a visitor can see.\n */\n stillCovered: boolean\n}\n\n/**\n * Which sites an uninstall actually affects (AGL-1027).\n *\n * The shadowing case is the whole reason this is a function rather than a\n * filter at the call site. A pin is not a boolean per site: an org pin covers\n * everything, a host pin names one site, and where both exist the host pin\n * wins. So \"remove\" means three different things depending on which pointer is\n * being dropped and what is left underneath — and the one thing the dialog must\n * never do is tell someone a plugin will stop working when it will not.\n *\n * Returns every site the operation touches, including the ones that keep the\n * plugin, so the dialog can say so explicitly instead of omitting them and\n * leaving the count unexplained.\n */\nexport function resolveUninstallTargets(\n orgInstall: OrgInstallSummary,\n scope: 'org' | 'host',\n hostId?: string,\n): UninstallTarget[] {\n if (scope === 'host') {\n const site = orgInstall.sites.find((entry) => entry.hostId === hostId)\n if (!site) return []\n // Its own pin goes; the org pin, if there is one, still covers it.\n return [\n { hostId: site.hostId, label: site.label, stillCovered: orgInstall.orgWide },\n ]\n }\n // Dropping the org pin: every site loses it EXCEPT those holding a host pin\n // of their own, which were already shadowing the org pin anyway.\n return orgInstall.sites.map((site) => ({\n hostId: site.hostId,\n label: site.label,\n stillCovered: site.pinnedBy === '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/** Fixed category taxonomy for marketplace listings (AGL-430). */\nexport const LISTING_CATEGORIES: readonly string[] = [\n 'analytics',\n 'automation',\n 'commerce',\n 'communication',\n 'content',\n 'design',\n 'forms',\n 'integrations',\n 'marketing',\n 'productivity',\n 'seo',\n 'security',\n] as const\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 allowlists and the sanitizer live in core since AGL-2939 — see\n * `@aglyn/aglyn/app-utils/node-definition-sanitizer` — and keep their\n * marketplace names here for the publishers that import them.\n */\nimport {\n MARKETPLACE_COMPONENT_ID_ALLOWLIST,\n MARKETPLACE_EMAIL_COMPONENT_ID_ALLOWLIST,\n MARKETPLACE_EMAIL_STARTER_COMPONENT_ID_ALLOWLIST,\n MARKETPLACE_DEFINITION_MAX_BYTES,\n sanitizeMarketplaceDefinition,\n marketplaceDefinitionToNested,\n MARKETPLACE_DATASET_FIELD_TYPES,\n} from '@aglyn/aglyn/app-utils/node-definition-sanitizer'\n\nexport {\n MARKETPLACE_COMPONENT_ID_ALLOWLIST,\n MARKETPLACE_EMAIL_COMPONENT_ID_ALLOWLIST,\n MARKETPLACE_EMAIL_STARTER_COMPONENT_ID_ALLOWLIST,\n MARKETPLACE_DEFINITION_MAX_BYTES,\n sanitizeMarketplaceDefinition,\n marketplaceDefinitionToNested,\n MARKETPLACE_DATASET_FIELD_TYPES,\n}\nexport {\n MARKETPLACE_SAFE_HREF,\n MARKETPLACE_SAFE_SRC,\n} from '@aglyn/aglyn/app-utils/node-definition-sanitizer'\nexport type {\n MarketplaceDefinitionNodes,\n} from '@aglyn/aglyn/app-utils/node-definition-sanitizer'\n\n/** Field cap on a published schema — mirrors the console's create limit. */\nexport const MARKETPLACE_DATASET_MAX_FIELDS = 100\n\n/** A published dataset schema: the model, with no records. */\nexport interface MarketplaceDatasetSchema {\n fields: Record<string, MarketplaceDatasetField>\n order: string[]\n}\n\nexport interface MarketplaceDatasetField {\n name: string\n type: string\n customType?: string\n description?: string\n required?: boolean\n default?: unknown\n validation?: Record<string, unknown>\n /**\n * Kept so an install into an org that HAS the referenced dataset can relink\n * it. `datasetId` is the publisher's id and is meaningless in another org,\n * so `datasetLabel` carries the human name the installer matches on.\n */\n reference?: {\n datasetId?: string\n datasetLabel?: string\n displayFieldId?: string\n multiple?: boolean\n onDelete?: string\n }\n}\n\nconst KEPT_VALIDATION_KEYS = ['required', 'regex', 'min', 'max', 'options']\n\n/**\n * Validates and strips a `DatasetModel` for publishing as a marketplace\n * dataset schema (AGL-657).\n *\n * Publishes STRUCTURE ONLY — records never travel. That is the whole safety\n * story for this artifact type: a dataset's rows are the org's customer data,\n * so the publish path reads the model and nothing else, and there is no code\n * path here that can reach the `records` subcollection.\n *\n * Two cross-org hazards the issue called out, handled by carrying enough\n * context for the INSTALLER to decide rather than by rejecting at publish:\n * - `reference` FKs point at a dataset id that only exists in the publisher's\n * org. The id is kept alongside the referenced dataset's label so the\n * installer can relink by name and degrade the field when it can't (see\n * `resolveInstalledDatasetSchema`).\n * - `customType` names a plugin-declared field type (AGL-434) whose plugin the\n * installing org may not have. Unknown custom types already degrade to their\n * base type at render, so the name rides along untouched.\n */\nexport function sanitizeDatasetSchema(model: {\n fields?: Record<string, any>\n order?: unknown\n}):\n | { ok: true; schema: MarketplaceDatasetSchema }\n | { ok: false; error: string } {\n const fields = model?.fields\n if (!fields || typeof fields !== 'object') {\n return { ok: false, error: 'Dataset has no field model to publish' }\n }\n // Order is the display contract; fall back to key order for models written\n // before `order` was required so older datasets stay publishable.\n const order = Array.isArray(model.order)\n ? model.order.map(String)\n : Object.keys(fields)\n const kept = order.filter((id) => fields[id])\n if (!kept.length) {\n return { ok: false, error: 'Dataset has no fields to publish' }\n }\n if (kept.length > MARKETPLACE_DATASET_MAX_FIELDS) {\n return {\n ok: false,\n error: `Dataset schemas are limited to ${MARKETPLACE_DATASET_MAX_FIELDS} fields`,\n }\n }\n const schema: MarketplaceDatasetSchema = { fields: {}, order: kept }\n for (const id of kept) {\n const field = fields[id] ?? {}\n const type = String(field.type ?? 'text')\n if (!MARKETPLACE_DATASET_FIELD_TYPES.includes(type)) {\n return { ok: false, error: `Field \"${id}\" has an unsupported type` }\n }\n const safe: MarketplaceDatasetField = {\n name: String(field.name ?? id).slice(0, 120),\n type,\n }\n if (field.customType) safe.customType = String(field.customType).slice(0, 60)\n if (field.description) {\n safe.description = String(field.description).slice(0, 500)\n }\n if (field.required === true) safe.required = true\n // Defaults are publisher-authored values, not data — keep only primitives\n // so a default can't smuggle a nested object into the installing org.\n if (\n field.default !== undefined &&\n (typeof field.default === 'string' ||\n typeof field.default === 'number' ||\n typeof field.default === 'boolean')\n ) {\n safe.default = field.default\n }\n if (field.validation && typeof field.validation === 'object') {\n const validation: Record<string, unknown> = {}\n for (const key of KEPT_VALIDATION_KEYS) {\n if (field.validation[key] !== undefined) {\n validation[key] = field.validation[key]\n }\n }\n if (Object.keys(validation).length) safe.validation = validation\n }\n if (field.reference && typeof field.reference === 'object') {\n safe.reference = {\n ...(field.reference.datasetId && {\n datasetId: String(field.reference.datasetId),\n }),\n ...(field.reference.datasetLabel && {\n datasetLabel: String(field.reference.datasetLabel).slice(0, 120),\n }),\n ...(field.reference.displayFieldId && {\n displayFieldId: String(field.reference.displayFieldId),\n }),\n ...(field.reference.multiple === true && { multiple: true }),\n ...(field.reference.onDelete && {\n onDelete: String(field.reference.onDelete),\n }),\n }\n }\n schema.fields[id] = safe\n }\n const serialized = JSON.stringify(schema)\n if (serialized.length > MARKETPLACE_DEFINITION_MAX_BYTES) {\n return { ok: false, error: 'Dataset schema is too large to publish' }\n }\n return { ok: true, schema }\n}\n\n/**\n * Rewrites a published schema for the installing org (AGL-657).\n *\n * `reference` fields are the only part of a schema that can't cross an org\n * boundary as-is: they name a dataset id in the PUBLISHER's org. Relink by the\n * referenced dataset's label when the installing org has one by that name;\n * otherwise degrade the field to plain `text` and report it, because a\n * reference field pointing at a dataset that doesn't exist renders as a broken\n * picker — silently keeping the dead id would install something visibly\n * broken and blame the installer for it.\n *\n * `existingDatasets` maps lowercased display name → dataset id in the target.\n */\nexport function resolveInstalledDatasetSchema(\n schema: MarketplaceDatasetSchema,\n existingDatasets: Readonly<Record<string, string>>,\n): { schema: MarketplaceDatasetSchema; degradedFieldIds: string[] } {\n const degradedFieldIds: string[] = []\n const fields: Record<string, MarketplaceDatasetField> = {}\n for (const id of schema.order) {\n const field = schema.fields[id]\n if (!field) continue\n if (field.type !== 'reference' && !field.reference) {\n fields[id] = field\n continue\n }\n const label = String(field.reference?.datasetLabel ?? '').toLowerCase()\n const relinked = label ? existingDatasets[label] : undefined\n if (relinked) {\n fields[id] = {\n ...field,\n reference: { ...field.reference, datasetId: relinked },\n }\n continue\n }\n const { reference: _dropped, ...rest } = field\n fields[id] = { ...rest, type: 'text' }\n degradedFieldIds.push(id)\n }\n return { schema: { fields, order: schema.order }, degradedFieldIds }\n}\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 screen',\n template: 'Editable screens you can rework in Besigner',\n layout: 'An editable layout you can apply to any screen',\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}\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","plugin","component","template","layout","datasetSchema","emailTemplate","emailStarter","theme","listingArtifactLabel","listing","INSTALL_TARGETS","installTargetsFor","resolvePluginInstallState","latestVersion","hostPin","orgPin","effective","installedVersion","version","String","scope","shadowed","Boolean","updateAvailable","resolveOrgInstallSummary","hosts","hostPins","orgWide","orgVersion","sites","hostPinnedIds","availableHostIds","host","id","push","hostId","label","pinnedBy","installedAnywhere","length","resolveUninstallTargets","orgInstall","site","find","entry","stillCovered","map","resolveInstallPlan","targeting","targets","canOrgPin","includes","canHostPin","allHostIds","selectedHostIds","VERIFICATION_BLOCK_MESSAGES","VERIFICATION_DECLINE_COOLDOWN_DAYS","timestampMs","verificationRequestBlock","isVersionApproved","reviewState","installsUnreviewedFallback","viewerOrgId","revocation","profileId","newestApprovedVersion","versions","approved","filter","reduce","best","publishedAt","toMillis","missingPublicListingContent","missing","description","trim","readme","license","LISTING_CATEGORIES","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","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","MARKETPLACE_COMPONENT_ID_ALLOWLIST","MARKETPLACE_EMAIL_COMPONENT_ID_ALLOWLIST","MARKETPLACE_EMAIL_STARTER_COMPONENT_ID_ALLOWLIST","MARKETPLACE_DEFINITION_MAX_BYTES","sanitizeMarketplaceDefinition","marketplaceDefinitionToNested","MARKETPLACE_DATASET_FIELD_TYPES","MARKETPLACE_SAFE_HREF","MARKETPLACE_SAFE_SRC","MARKETPLACE_DATASET_MAX_FIELDS","KEPT_VALIDATION_KEYS","sanitizeDatasetSchema","model","fields","order","Object","keys","kept","schema","field","type","safe","name","slice","customType","required","default","validation","reference","datasetId","datasetLabel","displayFieldId","multiple","onDelete","serialized","JSON","stringify","resolveInstalledDatasetSchema","existingDatasets","degradedFieldIds","relinked","_dropped","rest","ARTIFACT_INSTALL_RESULT","listingInclusions","options","rows","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,2CAA0C;AAGjF,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,wDAAuD;AAE9D,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,yBAAyBG,IAAI,CAACD;AACvC;AA6HA;;;;;;;CAOC,GACD,OAAO,MAAME,uBAAgE;IAC3EC,QAAQ;IACRC,WAAW;IACXC,UAAU;IACVC,QAAQ;IACRC,eAAe;IACfC,eAAe;IACfC,cAAc;IACdC,OAAO;AACT,EAAC;AAED,8DAA8D,GAC9D,OAAO,SAASC,qBAAqBC,OAIpC;QACQV;IAAP,QAAOA,4CAAAA,oBAAoB,CAACL,oBAAoBe,SAAS,YAAlDV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E,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,KAAK7I,QAAQ,CAACwI,QAAQ;YAC/DK,KAAK9J,IAAI,CAACyJ;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 '@aglyn/aglyn/app-utils/plan-entitlements'\nimport type { MarketplaceArtifactType } from '@aglyn/aglyn/app-utils/marketplace-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 '@aglyn/aglyn/app-utils/marketplace-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\n/**\n * Everything an org can publish to the marketplace (AGL-654).\n *\n * Defined in core and re-exported here (AGL-1016): the console needs it to\n * render update state for installed artifacts, and an app may not depend on an\n * addon lib. Publishing code keeps importing it from this model unchanged.\n */\nexport type { MarketplaceArtifactType }\n\n/**\n * Human-readable label for each artifact type (AGL-864).\n *\n * Shared by browse cards, the listing detail page, and the seller panel so\n * \"what kind of thing is this\" reads the same everywhere. Resolve a listing's\n * label through {@link listingArtifactLabel}, which tolerates the legacy\n * `type`/`kind` shape the way {@link listingArtifactType} does.\n */\nexport const ARTIFACT_TYPE_LABELS: Record<MarketplaceArtifactType, string> = {\n plugin: 'Plugin',\n component: 'Component',\n template: 'Site template',\n layout: 'Layout',\n datasetSchema: 'Dataset schema',\n emailTemplate: 'Email template',\n emailStarter: 'Email starter',\n theme: 'Theme',\n}\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/** Where an installed artifact lives. */\nexport type InstallTarget = 'org' | 'host'\n\n/**\n * Install targets each artifact type actually supports (AGL-656).\n *\n * This is not a policy choice — it is where the install routes physically\n * write. Only plugins have an org-scoped pin\n * (`orgs/{orgId}/installs/{listingId}`, applying to every site, shadowed by\n * a host pin). Components land in `hosts/{h}/components`, templates and\n * layouts in `hosts/{h}/templates`: all host-scoped by nature, because a\n * screen tree belongs to a site.\n *\n * Exported so the UI can ask rather than assume — an install picker that\n * offers \"this whole organization\" for a template would be lying.\n */\nexport const INSTALL_TARGETS: Record<\n MarketplaceArtifactType,\n readonly InstallTarget[]\n> = {\n plugin: ['org', 'host'],\n component: ['host'],\n template: ['host'],\n layout: ['host'],\n // Dataset schemas are org-shared data (AGL-237), so they install at org\n // scope — as a new empty dataset, not a pin (AGL-657).\n datasetSchema: ['org'],\n emailTemplate: ['host'],\n // A campaign email is a screen, and a screen belongs to a site.\n emailStarter: ['host'],\n // A theme is one site's visual identity, written to `hosts/{h}.theme`\n // (AGL-1020). Applying one org-wide would repaint every site at once from a\n // control that says \"install\".\n theme: ['host'],\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/** A plugin install pin — the version-pinned doc the install API writes. */\nexport interface InstallPin {\n version?: number | string\n}\n\n/**\n * The install state of a plugin listing for one site, told honestly (AGL-656).\n *\n * A plugin can be pinned at two scopes: the org pin\n * (`orgs/{orgId}/installs/{listingId}`) applies to every site, and a host pin\n * (`hosts/{hostId}/installs/{listingId}`) applies to just this one AND shadows\n * the org pin. Detecting installs from `hosts/{h}/components` — the COMPONENT\n * collection — never sees either pin, so an installed plugin used to read as\n * \"not installed\" on both the browse grid and the detail page. This resolves\n * the effective state from the two pins the way the loader does.\n */\nexport interface PluginInstallState {\n /** Effective pin scope for this site — host wins over org — or null. */\n scope: InstallTarget | null\n /** Version pinned at the effective scope, or null when not installed. */\n installedVersion: string | null\n /** Both pins exist: the host pin takes precedence, shadowing the org one. */\n shadowed: boolean\n /** Installed, but the pinned version is behind the listing's latest. */\n updateAvailable: boolean\n}\n\n/**\n * Resolves a plugin listing's install state for a site from its two pins\n * (AGL-656). The host pin shadows the org pin, mirroring the loader, so the\n * effective version and update prompt always describe what actually runs here.\n */\nexport function resolvePluginInstallState(\n latestVersion: number | string | undefined,\n hostPin: InstallPin | null | undefined,\n orgPin: InstallPin | null | undefined,\n): PluginInstallState {\n const effective = hostPin ?? orgPin ?? null\n const installedVersion =\n effective?.version != null ? String(effective.version) : null\n return {\n scope: hostPin ? 'host' : orgPin ? 'org' : null,\n installedVersion,\n shadowed: Boolean(hostPin && orgPin),\n // Any difference is an upgrade prompt, matching the installed-plugins card\n // — pins only ever move forward, so \"different\" means \"behind\".\n updateAvailable:\n installedVersion != null &&\n latestVersion != null &&\n String(latestVersion) !== installedVersion,\n }\n}\n\n/** One site's slice of an org-scope install picture (AGL-997). */\nexport interface OrgInstallSite {\n hostId: string\n label: string\n /** The version that actually runs here, from the effective pin. */\n version: string | null\n /** Where that pin lives — a host pin shadows the org one, as the loader does. */\n pinnedBy: InstallTarget\n /** This site has its OWN pin on top of an org pin. */\n shadowed: boolean\n}\n\n/**\n * The whole org's install picture for one listing (AGL-997).\n *\n * At org scope, \"installed\" is a SET, not a boolean. The detail page used to\n * resolve state against the single acting host, so a plugin installed on one\n * of five sites reported \"Installed on this site\" — describing one arbitrary\n * site and staying silent about the other four — and offered an Uninstall\n * that was all-or-nothing.\n *\n * `orgWide` and per-site pins are not exclusive: an org pin covers every\n * site including ones created later, and a host pin on top of it shadows it\n * for that one site. Both facts have to survive into the UI, which is why\n * this returns the sites AND the pins rather than a single scope.\n */\nexport interface OrgInstallSummary {\n /** An org pin exists: every site is covered, including future ones. */\n orgWide: boolean\n /** Version of the org pin, when there is one. */\n orgVersion: string | null\n /** Every site the listing effectively runs on. */\n sites: OrgInstallSite[]\n /** Sites carrying their own removable host pin. */\n hostPinnedIds: string[]\n /** Sites with no pin of their own and no org pin covering them. */\n availableHostIds: string[]\n installedAnywhere: boolean\n}\n\nexport function resolveOrgInstallSummary(\n hosts: ReadonlyArray<{ id: string; label: string }>,\n hostPins: Readonly<Record<string, InstallPin | null | undefined>>,\n orgPin: InstallPin | null | undefined,\n): OrgInstallSummary {\n const orgWide = Boolean(orgPin)\n const orgVersion = orgPin?.version != null ? String(orgPin.version) : null\n const sites: OrgInstallSite[] = []\n const hostPinnedIds: string[] = []\n const availableHostIds: string[] = []\n for (const host of hosts) {\n const hostPin = hostPins[host.id]\n if (hostPin) hostPinnedIds.push(host.id)\n if (!hostPin && !orgPin) {\n availableHostIds.push(host.id)\n continue\n }\n sites.push({\n hostId: host.id,\n label: host.label,\n version:\n hostPin?.version != null ? String(hostPin.version) : orgVersion,\n pinnedBy: hostPin ? 'host' : 'org',\n shadowed: Boolean(hostPin && orgPin),\n })\n }\n return {\n orgWide,\n orgVersion,\n sites,\n hostPinnedIds,\n availableHostIds,\n installedAnywhere: orgWide || hostPinnedIds.length > 0,\n }\n}\n\n/** One site an uninstall would touch, and whether it really loses the plugin. */\nexport interface UninstallTarget {\n hostId: string\n label: string\n /**\n * The plugin keeps running here. Removing a HOST pin while an org pin still\n * covers the site, or the ORG pin while the site holds its own host pin,\n * changes which pointer is in use and nothing a visitor can see.\n */\n stillCovered: boolean\n}\n\n/**\n * Which sites an uninstall actually affects (AGL-1027).\n *\n * The shadowing case is the whole reason this is a function rather than a\n * filter at the call site. A pin is not a boolean per site: an org pin covers\n * everything, a host pin names one site, and where both exist the host pin\n * wins. So \"remove\" means three different things depending on which pointer is\n * being dropped and what is left underneath — and the one thing the dialog must\n * never do is tell someone a plugin will stop working when it will not.\n *\n * Returns every site the operation touches, including the ones that keep the\n * plugin, so the dialog can say so explicitly instead of omitting them and\n * leaving the count unexplained.\n */\nexport function resolveUninstallTargets(\n orgInstall: OrgInstallSummary,\n scope: 'org' | 'host',\n hostId?: string,\n): UninstallTarget[] {\n if (scope === 'host') {\n const site = orgInstall.sites.find((entry) => entry.hostId === hostId)\n if (!site) return []\n // Its own pin goes; the org pin, if there is one, still covers it.\n return [\n { hostId: site.hostId, label: site.label, stillCovered: orgInstall.orgWide },\n ]\n }\n // Dropping the org pin: every site loses it EXCEPT those holding a host pin\n // of their own, which were already shadowing the org pin anyway.\n return orgInstall.sites.map((site) => ({\n hostId: site.hostId,\n label: site.label,\n stillCovered: site.pinnedBy === '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/** Fixed category taxonomy for marketplace listings (AGL-430). */\nexport const LISTING_CATEGORIES: readonly string[] = [\n 'analytics',\n 'automation',\n 'commerce',\n 'communication',\n 'content',\n 'design',\n 'forms',\n 'integrations',\n 'marketing',\n 'productivity',\n 'seo',\n 'security',\n] as const\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 allowlists and the sanitizer live in core since AGL-2939 — see\n * `@aglyn/aglyn/app-utils/node-definition-sanitizer` — and keep their\n * marketplace names here for the publishers that import them.\n */\nimport {\n MARKETPLACE_COMPONENT_ID_ALLOWLIST,\n MARKETPLACE_EMAIL_COMPONENT_ID_ALLOWLIST,\n MARKETPLACE_EMAIL_STARTER_COMPONENT_ID_ALLOWLIST,\n MARKETPLACE_DEFINITION_MAX_BYTES,\n sanitizeMarketplaceDefinition,\n marketplaceDefinitionToNested,\n MARKETPLACE_DATASET_FIELD_TYPES,\n} from '@aglyn/aglyn/app-utils/node-definition-sanitizer'\n\nexport {\n MARKETPLACE_COMPONENT_ID_ALLOWLIST,\n MARKETPLACE_EMAIL_COMPONENT_ID_ALLOWLIST,\n MARKETPLACE_EMAIL_STARTER_COMPONENT_ID_ALLOWLIST,\n MARKETPLACE_DEFINITION_MAX_BYTES,\n sanitizeMarketplaceDefinition,\n marketplaceDefinitionToNested,\n MARKETPLACE_DATASET_FIELD_TYPES,\n}\nexport {\n MARKETPLACE_SAFE_HREF,\n MARKETPLACE_SAFE_SRC,\n} from '@aglyn/aglyn/app-utils/node-definition-sanitizer'\nexport type {\n MarketplaceDefinitionNodes,\n} from '@aglyn/aglyn/app-utils/node-definition-sanitizer'\n\n/** Field cap on a published schema — mirrors the console's create limit. */\nexport const MARKETPLACE_DATASET_MAX_FIELDS = 100\n\n/** A published dataset schema: the model, with no records. */\nexport interface MarketplaceDatasetSchema {\n fields: Record<string, MarketplaceDatasetField>\n order: string[]\n}\n\nexport interface MarketplaceDatasetField {\n name: string\n type: string\n customType?: string\n description?: string\n required?: boolean\n default?: unknown\n validation?: Record<string, unknown>\n /**\n * Kept so an install into an org that HAS the referenced dataset can relink\n * it. `datasetId` is the publisher's id and is meaningless in another org,\n * so `datasetLabel` carries the human name the installer matches on.\n */\n reference?: {\n datasetId?: string\n datasetLabel?: string\n displayFieldId?: string\n multiple?: boolean\n onDelete?: string\n }\n}\n\nconst KEPT_VALIDATION_KEYS = ['required', 'regex', 'min', 'max', 'options']\n\n/**\n * Validates and strips a `DatasetModel` for publishing as a marketplace\n * dataset schema (AGL-657).\n *\n * Publishes STRUCTURE ONLY — records never travel. That is the whole safety\n * story for this artifact type: a dataset's rows are the org's customer data,\n * so the publish path reads the model and nothing else, and there is no code\n * path here that can reach the `records` subcollection.\n *\n * Two cross-org hazards the issue called out, handled by carrying enough\n * context for the INSTALLER to decide rather than by rejecting at publish:\n * - `reference` FKs point at a dataset id that only exists in the publisher's\n * org. The id is kept alongside the referenced dataset's label so the\n * installer can relink by name and degrade the field when it can't (see\n * `resolveInstalledDatasetSchema`).\n * - `customType` names a plugin-declared field type (AGL-434) whose plugin the\n * installing org may not have. Unknown custom types already degrade to their\n * base type at render, so the name rides along untouched.\n */\nexport function sanitizeDatasetSchema(model: {\n fields?: Record<string, any>\n order?: unknown\n}):\n | { ok: true; schema: MarketplaceDatasetSchema }\n | { ok: false; error: string } {\n const fields = model?.fields\n if (!fields || typeof fields !== 'object') {\n return { ok: false, error: 'Dataset has no field model to publish' }\n }\n // Order is the display contract; fall back to key order for models written\n // before `order` was required so older datasets stay publishable.\n const order = Array.isArray(model.order)\n ? model.order.map(String)\n : Object.keys(fields)\n const kept = order.filter((id) => fields[id])\n if (!kept.length) {\n return { ok: false, error: 'Dataset has no fields to publish' }\n }\n if (kept.length > MARKETPLACE_DATASET_MAX_FIELDS) {\n return {\n ok: false,\n error: `Dataset schemas are limited to ${MARKETPLACE_DATASET_MAX_FIELDS} fields`,\n }\n }\n const schema: MarketplaceDatasetSchema = { fields: {}, order: kept }\n for (const id of kept) {\n const field = fields[id] ?? {}\n const type = String(field.type ?? 'text')\n if (!MARKETPLACE_DATASET_FIELD_TYPES.includes(type)) {\n return { ok: false, error: `Field \"${id}\" has an unsupported type` }\n }\n const safe: MarketplaceDatasetField = {\n name: String(field.name ?? id).slice(0, 120),\n type,\n }\n if (field.customType) safe.customType = String(field.customType).slice(0, 60)\n if (field.description) {\n safe.description = String(field.description).slice(0, 500)\n }\n if (field.required === true) safe.required = true\n // Defaults are publisher-authored values, not data — keep only primitives\n // so a default can't smuggle a nested object into the installing org.\n if (\n field.default !== undefined &&\n (typeof field.default === 'string' ||\n typeof field.default === 'number' ||\n typeof field.default === 'boolean')\n ) {\n safe.default = field.default\n }\n if (field.validation && typeof field.validation === 'object') {\n const validation: Record<string, unknown> = {}\n for (const key of KEPT_VALIDATION_KEYS) {\n if (field.validation[key] !== undefined) {\n validation[key] = field.validation[key]\n }\n }\n if (Object.keys(validation).length) safe.validation = validation\n }\n if (field.reference && typeof field.reference === 'object') {\n safe.reference = {\n ...(field.reference.datasetId && {\n datasetId: String(field.reference.datasetId),\n }),\n ...(field.reference.datasetLabel && {\n datasetLabel: String(field.reference.datasetLabel).slice(0, 120),\n }),\n ...(field.reference.displayFieldId && {\n displayFieldId: String(field.reference.displayFieldId),\n }),\n ...(field.reference.multiple === true && { multiple: true }),\n ...(field.reference.onDelete && {\n onDelete: String(field.reference.onDelete),\n }),\n }\n }\n schema.fields[id] = safe\n }\n const serialized = JSON.stringify(schema)\n if (serialized.length > MARKETPLACE_DEFINITION_MAX_BYTES) {\n return { ok: false, error: 'Dataset schema is too large to publish' }\n }\n return { ok: true, schema }\n}\n\n/**\n * Rewrites a published schema for the installing org (AGL-657).\n *\n * `reference` fields are the only part of a schema that can't cross an org\n * boundary as-is: they name a dataset id in the PUBLISHER's org. Relink by the\n * referenced dataset's label when the installing org has one by that name;\n * otherwise degrade the field to plain `text` and report it, because a\n * reference field pointing at a dataset that doesn't exist renders as a broken\n * picker — silently keeping the dead id would install something visibly\n * broken and blame the installer for it.\n *\n * `existingDatasets` maps lowercased display name → dataset id in the target.\n */\nexport function resolveInstalledDatasetSchema(\n schema: MarketplaceDatasetSchema,\n existingDatasets: Readonly<Record<string, string>>,\n): { schema: MarketplaceDatasetSchema; degradedFieldIds: string[] } {\n const degradedFieldIds: string[] = []\n const fields: Record<string, MarketplaceDatasetField> = {}\n for (const id of schema.order) {\n const field = schema.fields[id]\n if (!field) continue\n if (field.type !== 'reference' && !field.reference) {\n fields[id] = field\n continue\n }\n const label = String(field.reference?.datasetLabel ?? '').toLowerCase()\n const relinked = label ? existingDatasets[label] : undefined\n if (relinked) {\n fields[id] = {\n ...field,\n reference: { ...field.reference, datasetId: relinked },\n }\n continue\n }\n const { reference: _dropped, ...rest } = field\n fields[id] = { ...rest, type: 'text' }\n degradedFieldIds.push(id)\n }\n return { schema: { fields, order: schema.order }, degradedFieldIds }\n}\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 screen',\n template: 'Editable screens you can rework in Besigner',\n layout: 'An editable layout you can apply to any screen',\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}\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","plugin","component","template","layout","datasetSchema","emailTemplate","emailStarter","theme","listingArtifactLabel","listing","INSTALL_TARGETS","installTargetsFor","resolvePluginInstallState","latestVersion","hostPin","orgPin","effective","installedVersion","version","String","scope","shadowed","Boolean","updateAvailable","resolveOrgInstallSummary","hosts","hostPins","orgWide","orgVersion","sites","hostPinnedIds","availableHostIds","host","id","push","hostId","label","pinnedBy","installedAnywhere","length","resolveUninstallTargets","orgInstall","site","find","entry","stillCovered","map","resolveInstallPlan","targeting","targets","canOrgPin","includes","canHostPin","allHostIds","selectedHostIds","VERIFICATION_BLOCK_MESSAGES","VERIFICATION_DECLINE_COOLDOWN_DAYS","timestampMs","verificationRequestBlock","isVersionApproved","reviewState","installsUnreviewedFallback","viewerOrgId","revocation","profileId","newestApprovedVersion","versions","approved","filter","reduce","best","publishedAt","toMillis","missingPublicListingContent","missing","description","trim","readme","license","LISTING_CATEGORIES","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","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","MARKETPLACE_COMPONENT_ID_ALLOWLIST","MARKETPLACE_EMAIL_COMPONENT_ID_ALLOWLIST","MARKETPLACE_EMAIL_STARTER_COMPONENT_ID_ALLOWLIST","MARKETPLACE_DEFINITION_MAX_BYTES","sanitizeMarketplaceDefinition","marketplaceDefinitionToNested","MARKETPLACE_DATASET_FIELD_TYPES","MARKETPLACE_SAFE_HREF","MARKETPLACE_SAFE_SRC","MARKETPLACE_DATASET_MAX_FIELDS","KEPT_VALIDATION_KEYS","sanitizeDatasetSchema","model","fields","order","Object","keys","kept","schema","field","type","safe","name","slice","customType","required","default","validation","reference","datasetId","datasetLabel","displayFieldId","multiple","onDelete","serialized","JSON","stringify","resolveInstalledDatasetSchema","existingDatasets","degradedFieldIds","relinked","_dropped","rest","ARTIFACT_INSTALL_RESULT","listingInclusions","options","rows","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,2CAA0C;AAGjF,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,wDAAuD;AAE9D,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,yBAAyBG,IAAI,CAACD;AACvC;AAwIA;;;;;;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A8E,EAC9EC,SAAiB,EACjBE,KAAqD;IAErD,IAAI,CAACF,WAAW,OAAO;IACvB,OAAO,CAACD,oBAAAA,YAAa,EAAE,EAAEjF,IAAI,CAC3B,CAAC8E,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,KAAK7I,QAAQ,CAACwI,QAAQ;YAC/DK,KAAK9J,IAAI,CAACyJ;QACZ;IACF;IACA,OAAOK;AACT"}
|
|
@@ -18,6 +18,11 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
|
18
18
|
import * as Aglyn from "@aglyn/aglyn/server";
|
|
19
19
|
import { emailUnverifiedResponse, firebaseAdmin, isImpersonationSession } from "@aglyn/tenant-data-admin";
|
|
20
20
|
import { invalidIdTokenResponse } from "@aglyn/tenant-data-admin/server/id-token-refusal";
|
|
21
|
+
import { applyListQuery } from "@aglyn/tenant-data-admin/server/list-query";
|
|
22
|
+
import { nameSearchNormalizers } from "@aglyn/aglyn/app-utils/name-search";
|
|
23
|
+
import { planListQuery } from "@aglyn/shared-ui-jsx/const/list-query-plan";
|
|
24
|
+
import { MARKETPLACE_REPORTS_QUERY } from "../model/listing-query.js";
|
|
25
|
+
import { addAdminAudit } from "@aglyn/tenant-data-admin/server/admin-audit-write";
|
|
21
26
|
/**
|
|
22
27
|
* The staff end of the marketplace report button (AGL-2310), served at
|
|
23
28
|
* `/api/marketplace/admin/reports` for this plugin's Marketplace reports
|
|
@@ -56,6 +61,7 @@ import { invalidIdTokenResponse } from "@aglyn/tenant-data-admin/server/id-token
|
|
|
56
61
|
* and the document the route actually mutates cannot drift apart.
|
|
57
62
|
*/ const REPORTS_COLLECTION = 'marketplaceReports';
|
|
58
63
|
const REPORT_ID = /^[a-f0-9]{40}$/;
|
|
64
|
+
/** How many reports one read of the queue returns. */ const REPORTS_WINDOW = 200;
|
|
59
65
|
const asString = (value)=>typeof value === 'string' && value ? value : null;
|
|
60
66
|
const asMillis = (value)=>{
|
|
61
67
|
const candidate = value;
|
|
@@ -105,18 +111,29 @@ async function handler(request) {
|
|
|
105
111
|
if (method === 'GET') {
|
|
106
112
|
var _ref3;
|
|
107
113
|
/**
|
|
108
|
-
*
|
|
114
|
+
* Status on the QUERY, newest activity first (AGL-3321).
|
|
109
115
|
*
|
|
110
|
-
*
|
|
111
|
-
*
|
|
112
|
-
*
|
|
113
|
-
*
|
|
114
|
-
*
|
|
116
|
+
* It was matched in JS over the newest two hundred reports, so an open
|
|
117
|
+
* report older than two hundred newer ones of any status was not in the
|
|
118
|
+
* Open queue at all — the one list whose job is not to lose a report.
|
|
119
|
+
* `MARKETPLACE_REPORTS_QUERY` puts it on the query, served by the
|
|
120
|
+
* `(status, updatedAt DESC)` composite its spec pins. `report.ts` has
|
|
121
|
+
* written `status` and `updatedAt` on every report since the button
|
|
122
|
+
* shipped, so the order drops none. A queue longer than its window says
|
|
123
|
+
* so (`more`) instead of reading as complete.
|
|
115
124
|
*/ const requested = String((_ref3 = query == null ? void 0 : query['status']) != null ? _ref3 : '');
|
|
116
|
-
const
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
125
|
+
const plan = planListQuery(MARKETPLACE_REPORTS_QUERY, {
|
|
126
|
+
clauses: requested ? [
|
|
127
|
+
{
|
|
128
|
+
field: 'status',
|
|
129
|
+
op: 'equals',
|
|
130
|
+
value: requested
|
|
131
|
+
}
|
|
132
|
+
] : []
|
|
133
|
+
}, nameSearchNormalizers);
|
|
134
|
+
const snapshot = await applyListQuery(collection, plan).limit(REPORTS_WINDOW + 1).get();
|
|
135
|
+
const more = snapshot.docs.length > REPORTS_WINDOW;
|
|
136
|
+
const reports = snapshot.docs.slice(0, REPORTS_WINDOW).map((doc)=>{
|
|
120
137
|
var _asString, _asString1;
|
|
121
138
|
const data = doc.data();
|
|
122
139
|
return {
|
|
@@ -139,9 +156,10 @@ async function handler(request) {
|
|
|
139
156
|
createdAtMs: asMillis(data['createdAt']),
|
|
140
157
|
updatedAtMs: asMillis(data['updatedAt'])
|
|
141
158
|
};
|
|
142
|
-
})
|
|
159
|
+
});
|
|
143
160
|
return Response.json({
|
|
144
161
|
reports,
|
|
162
|
+
more,
|
|
145
163
|
actorRole: showIdentity ? 'super' : 'support',
|
|
146
164
|
identityVisible: showIdentity,
|
|
147
165
|
statuses: Aglyn.ABUSE_REPORT_STATUSES
|
|
@@ -232,7 +250,7 @@ async function handler(request) {
|
|
|
232
250
|
* read either, and `targetType` here said `marketplaceReport` while
|
|
233
251
|
* `targetType` on the report document says `listing` or `review` — the
|
|
234
252
|
* same key naming two different things one hop apart.
|
|
235
|
-
*/ await firestore
|
|
253
|
+
*/ await addAdminAudit(firestore, _extends({
|
|
236
254
|
action: 'marketplace-report-status',
|
|
237
255
|
actorUid: decoded.uid,
|
|
238
256
|
actorEmail: decoded.email ? String(decoded.email) : null,
|