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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/package.json +14 -14
  2. package/src/lib/declarations.d.ts +26 -0
  3. package/src/lib/declarations.js +37 -0
  4. package/src/lib/declarations.js.map +1 -0
  5. package/src/lib/declarations.server.d.ts +2 -1
  6. package/src/lib/declarations.server.js +18 -1
  7. package/src/lib/declarations.server.js.map +1 -1
  8. package/src/lib/model/marketplace-site-permissions.d.ts +26 -0
  9. package/src/lib/model/marketplace-site-permissions.js +62 -0
  10. package/src/lib/model/marketplace-site-permissions.js.map +1 -0
  11. package/src/lib/model/marketplace.d.ts +24 -0
  12. package/src/lib/model/marketplace.js.map +1 -1
  13. package/src/lib/model/site-starter-listing.d.ts +49 -0
  14. package/src/lib/model/site-starter-listing.js +75 -0
  15. package/src/lib/model/site-starter-listing.js.map +1 -0
  16. package/src/lib/server/install-email-starter.js +7 -4
  17. package/src/lib/server/install-email-starter.js.map +1 -1
  18. package/src/lib/server/install-email-template.js +8 -5
  19. package/src/lib/server/install-email-template.js.map +1 -1
  20. package/src/lib/server/install-layout.js +7 -4
  21. package/src/lib/server/install-layout.js.map +1 -1
  22. package/src/lib/server/install-plugin.js +8 -8
  23. package/src/lib/server/install-plugin.js.map +1 -1
  24. package/src/lib/server/install-template.js +7 -4
  25. package/src/lib/server/install-template.js.map +1 -1
  26. package/src/lib/server/install-theme.js +10 -7
  27. package/src/lib/server/install-theme.js.map +1 -1
  28. package/src/lib/server/install.js +7 -4
  29. package/src/lib/server/install.js.map +1 -1
  30. package/src/lib/server/publish-email-starter.js +8 -5
  31. package/src/lib/server/publish-email-starter.js.map +1 -1
  32. package/src/lib/server/publish-email-template.js +8 -5
  33. package/src/lib/server/publish-email-template.js.map +1 -1
  34. package/src/lib/server/publish-layout.js +8 -5
  35. package/src/lib/server/publish-layout.js.map +1 -1
  36. package/src/lib/server/publish-starter.d.ts +37 -0
  37. package/src/lib/server/publish-starter.js +501 -0
  38. package/src/lib/server/publish-starter.js.map +1 -0
  39. package/src/lib/server/publish-template.js +9 -6
  40. package/src/lib/server/publish-template.js.map +1 -1
  41. package/src/lib/server/publish-theme.js +8 -5
  42. package/src/lib/server/publish-theme.js.map +1 -1
  43. package/src/lib/server/publish.js +8 -5
  44. package/src/lib/server/publish.js.map +1 -1
  45. package/src/lib/server/site-starter-source.d.ts +19 -0
  46. package/src/lib/server/site-starter-source.js +189 -0
  47. package/src/lib/server/site-starter-source.js.map +1 -0
  48. package/src/lib/server.js +3 -0
  49. package/src/lib/server.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/marketplace/src/lib/server/publish-email-starter.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { displayNameSearchFields } from '@aglyn/aglyn/app-utils/name-search'\nimport {\n CANVAS_ROOT_ELEMENT_ID,\n checkEntitlement,\n createResourceUid,\n} from '@aglyn/aglyn/server'\nimport { type PluginApiHandler } from '@aglyn/aglyn/server'\nimport { decodeStoredNodes } from '@aglyn/aglyn/app-utils/stored-nodes'\nimport { inlineReusableBlocks } from './publish-email-blocks'\nimport { firebaseAdmin, getOrgForHost } from '@aglyn/tenant-data-admin'\nimport { resolveOrgPermissions } from '@aglyn/tenant-runtime/org-permissions'\nimport {\n emailStarterRefusal,\n inspectEmailStarter,\n MARKETPLACE_EMAIL_STARTER_COMPONENT_ID_ALLOWLIST,\n marketplacePriceRefusal,\n sanitizeMarketplaceDefinition,\n} from '../model'\nimport { resolvePublisherProfile } from './publisher-profile'\nimport { publishPreconditionRefusal } from './publish-preconditions'\nimport { listingSubmissionRefusal } from './listing-screen'\nimport { refreshListingQueryFields } from './listing-query-fields'\n\n/**\n * Publishes a site's campaign email design as a marketplace starter.\n *\n * The source is a `kind: 'email'` SCREEN — the document `createEmailScreen`\n * writes and the screen besigner edits — not an entry in the transactional\n * catalog. That is the whole difference from `publish-email-template`, and it\n * is why the two exist separately: a transactional design is a design FOR a\n * fixed key and installs onto that same key; a starter belongs to no key and\n * installs as a new email of the buyer's own.\n *\n * ## Two things this reads that the transactional publisher does not\n *\n * **The nodes are compressed.** A screen version is written through\n * `screenVersionConverter`, so `nodes` comes back from the Admin SDK as a\n * msgpack `Buffer`. `publish-email-template.ts` reads its `nodes` raw and says\n * why — its besigner saves with a bare `setDoc` and no converter — and copying\n * that line here would publish a Buffer: truthy, non-empty by `Object.keys`\n * (those are byte indices), and scanning as a design with no blocks in it.\n *\n * **The tree is inspected, not just sanitized.** `sanitizeMarketplaceDefinition`\n * DROPS an unsafe URL and publishes what is left, which is right for a page.\n * Here the URL rules are the product: a remote image in an email is a read\n * receipt for whoever hosts it, and quietly removing one teaches the publisher\n * nothing. So `inspectEmailStarter` runs first and REFUSES.\n */\nexport const publishEmailStarterHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n const hostId = String(req.body?.hostId ?? '')\n const screenId = String(req.body?.screenId ?? '')\n const displayName = String(req.body?.displayName ?? '').slice(0, 80)\n const description = String(req.body?.description ?? '').slice(0, 500)\n const category = String(req.body?.category ?? '').slice(0, 40)\n const priceUsd = Math.round(Number(req.body?.priceUsd ?? 0)) || 0\n const priceRefusal = marketplacePriceRefusal(priceUsd)\n if (priceRefusal) return res.status(400).json({ error: priceRefusal })\n if (!hostId || !screenId || !displayName.trim()) {\n return res\n .status(400)\n .json({ error: 'Missing hostId, screenId, or displayName' })\n }\n\n const authorization = String(req.headers.authorization ?? '')\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken) return res.status(401).json({ error: 'Unauthenticated' })\n\n try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n const membership = await resolveOrgPermissions(decoded.uid, { hostId })\n if (!membership.permissions.publishToMarketplace) {\n return res.status(403).json({\n error:\n 'Your organization role does not allow publishing to the marketplace',\n })\n }\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const hostSnapshot = await hostRef.get()\n if (!hostSnapshot.exists) {\n return res.status(404).json({ error: 'Unknown site' })\n }\n const memberRole = (hostSnapshot.get('memberRoles') ?? {})[decoded.uid]\n if (memberRole !== 'admin' && memberRole !== 'editor') {\n return res.status(403).json({ error: 'Not a site admin or editor' })\n }\n\n const orgForHost = await getOrgForHost(hostId)\n if (!checkEntitlement(orgForHost?.org ?? {}, 'marketplaceSelling')) {\n return res\n .status(403)\n .json({ error: 'Publishing to the marketplace requires a Pro plan' })\n }\n if (!orgForHost?.orgId) {\n return res.status(409).json({ error: 'Site has no owning organization' })\n }\n const publisher = await resolvePublisherProfile(firestore, orgForHost.orgId)\n const refusal = publishPreconditionRefusal(publisher, {\n priceUsd,\n sells: 'templates',\n })\n if (refusal) return res.status(refusal.status).json(refusal.body)\n\n const screenRef = hostRef.collection('screens').doc(screenId)\n const screenSnapshot = await screenRef.get()\n const screen = screenSnapshot.data() as Record<string, unknown> | undefined\n if (!screen || screen['deletedAt']) {\n return res.status(404).json({ error: 'Unknown email' })\n }\n if (screen['kind'] !== 'email') {\n return res\n .status(422)\n .json({ error: 'That design is not an email' })\n }\n const activeVersionId = screen['versionId']\n if (!activeVersionId) {\n return res\n .status(404)\n .json({ error: 'This email has no saved design yet — design and save it first' })\n }\n const versionSnapshot = await screenRef\n .collection('versions')\n .doc(String(activeVersionId))\n .get()\n\n /*\n * The site's reusable blocks INLINED before anything is judged (AGL-3287).\n * A buyer's org has none of this site's components, so a placement has to\n * travel as the blocks it renders — and inlining first is what puts a\n * shared footer's links and images in front of the inspection below, as\n * the send path would mail them. An undecodable payload is left as stored,\n * so the inspection still refuses it by name.\n */\n const stored = versionSnapshot.get('nodes')\n const readable = decodeStoredNodes<Record<string, unknown>>(stored)\n let design: unknown = stored\n if (readable && typeof readable === 'object' && !Array.isArray(readable)) {\n const inlined = await inlineReusableBlocks(readable, {\n firestore,\n hostId,\n rootId: CANVAS_ROOT_ELEMENT_ID,\n })\n if (inlined.ok === false) {\n return res.status(422).json({ error: inlined.error })\n }\n design = inlined.nodes\n }\n // The inspection decodes, so it is also the guard against publishing a\n // node map nothing could read — it refuses rather than reporting a\n // compressed payload as a clean design.\n const inspection = inspectEmailStarter(design)\n const violation = emailStarterRefusal(inspection)\n if (violation) {\n return res.status(422).json({\n error: violation,\n violations: inspection.violations,\n })\n }\n if (!inspection.nodes || !Object.keys(inspection.nodes).length) {\n return res.status(404).json({ error: 'This email design is empty' })\n }\n // Runs after the inspection and over the same decoded map. It enforces the\n // component-id allowlist and trims node keys; the URL rules it also carries\n // can no longer fire, because a design that would have tripped them was\n // refused above rather than silently trimmed.\n const sanitized = sanitizeMarketplaceDefinition(\n { rootId: CANVAS_ROOT_ELEMENT_ID, nodes: inspection.nodes },\n { componentIds: MARKETPLACE_EMAIL_STARTER_COMPONENT_ID_ALLOWLIST },\n )\n if (sanitized.ok === false) {\n return res.status(422).json({ error: sanitized.error })\n }\n\n // One listing per (publisher org, source screen). Re-publishing the same\n // email bumps its version rather than minting a second listing, which is\n // what makes \"update available\" mean anything to everyone who installed it.\n const existing = await firestore\n .collection('marketplaceListings')\n .where('profileId', '==', publisher.orgId)\n .where('sourceHostId', '==', hostId)\n .where('sourceScreenId', '==', screenId)\n .limit(1)\n .get()\n const listingRef = existing.empty\n ? firestore.collection('marketplaceListings').doc(createResourceUid())\n : existing.docs[0].ref\n const version = existing.empty\n ? 1\n : Number(existing.docs[0].get('latestVersion') ?? 0) + 1\n const now = firebaseAdmin.firestore.FieldValue.serverTimestamp()\n\n // The phishing screen, before anything is listed (AGL-3365).\n const screened = await listingSubmissionRefusal({\n publisherOrgId: publisher.orgId,\n content: {\n displayName,\n publisherName: publisher.displayName,\n description,\n emailNodes: sanitized.nodes,\n },\n official: decoded['staff'] === true,\n org: orgForHost.org ?? null,\n })\n if (screened) return res.status(screened.status).json(screened.body)\n\n await listingRef.set(\n {\n profileId: publisher.orgId,\n artifactType: 'emailStarter',\n sourceHostId: hostId,\n sourceScreenId: screenId,\n displayName: displayName.trim(),\n // The keys a listing is searched by (AGL-3321): the template gallery's\n // marketplace shelf asks `nameTokens` on its query.\n ...displayNameSearchFields(displayName.trim()),\n ...(description.trim() && { description: description.trim() }),\n ...(category.trim() && { category: category.trim() }),\n priceUsd,\n latestVersion: version,\n deletedAt: null,\n ...(existing.empty && { createdAt: now }),\n updatedAt: now,\n versionHistory: firebaseAdmin.firestore.FieldValue.arrayUnion({\n version,\n publishedAt: firebaseAdmin.firestore.Timestamp.now(),\n }),\n },\n { merge: true },\n )\n // The lists this listing appears in query by fields derived from it (AGL-3321).\n await refreshListingQueryFields(listingRef)\n await listingRef\n .collection('versions')\n .doc(String(version))\n .set({\n rootId: sanitized.rootId,\n nodes: sanitized.nodes,\n // Copy is part of the design and travels with it.\n subject: String(screen['emailSubject'] ?? ''),\n preheader: String(screen['emailPreheader'] ?? ''),\n // The hosts this design would send a recipient to, recorded at publish\n // so the listing page can show them BEFORE somebody installs. A tenant\n // about to mail their own customers under their own name is entitled to\n // see the domains a stranger's template points them at, and no\n // allowlist can make that judgment for them.\n linkHosts: inspection.linkHosts,\n // Absent `reviewState` is the un-reviewed default, and it is written\n // NOWHERE here on purpose: a publisher who could stamp their own\n // version approved would make the field decorative. Staff write it.\n publishedAt: now,\n })\n\n return res\n .status(200)\n .json({ listingId: listingRef.id, version, linkHosts: inspection.linkHosts })\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Email starter publish failed' })\n }\n}\n\nexport default publishEmailStarterHandler\n"],"names":["displayNameSearchFields","CANVAS_ROOT_ELEMENT_ID","checkEntitlement","createResourceUid","decodeStoredNodes","inlineReusableBlocks","firebaseAdmin","getOrgForHost","resolveOrgPermissions","emailStarterRefusal","inspectEmailStarter","MARKETPLACE_EMAIL_STARTER_COMPONENT_ID_ALLOWLIST","marketplacePriceRefusal","sanitizeMarketplaceDefinition","resolvePublisherProfile","publishPreconditionRefusal","listingSubmissionRefusal","refreshListingQueryFields","publishEmailStarterHandler","req","res","method","status","json","error","hostId","String","body","screenId","displayName","slice","description","category","priceUsd","Math","round","Number","priceRefusal","trim","authorization","headers","idToken","startsWith","length","undefined","hostSnapshot","existing","orgForHost","screen","decoded","app","auth","verifyIdToken","membership","uid","permissions","publishToMarketplace","firestore","hostRef","collection","doc","get","exists","memberRole","org","orgId","publisher","refusal","sells","screenRef","screenSnapshot","data","activeVersionId","versionSnapshot","stored","readable","design","Array","isArray","inlined","rootId","ok","nodes","inspection","violation","violations","Object","keys","sanitized","componentIds","where","limit","listingRef","empty","docs","ref","version","now","FieldValue","serverTimestamp","screened","publisherOrgId","content","publisherName","emailNodes","official","set","profileId","artifactType","sourceHostId","sourceScreenId","latestVersion","deletedAt","createdAt","updatedAt","versionHistory","arrayUnion","publishedAt","Timestamp","merge","subject","preheader","linkHosts","listingId","id","console"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,uBAAuB,QAAQ,qCAAoC;AAC5E,SACEC,sBAAsB,EACtBC,gBAAgB,EAChBC,iBAAiB,QACZ,sBAAqB;AAE5B,SAASC,iBAAiB,QAAQ,sCAAqC;AACvE,SAASC,oBAAoB,QAAQ,4BAAwB;AAC7D,SAASC,aAAa,EAAEC,aAAa,QAAQ,2BAA0B;AACvE,SAASC,qBAAqB,QAAQ,wCAAuC;AAC7E,SACEC,mBAAmB,EACnBC,mBAAmB,EACnBC,gDAAgD,EAChDC,uBAAuB,EACvBC,6BAA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,SAAS,CAAC6D,SAAS,CAACrB,GAAG;YACpD;YAEF;YAAEsB,OAAO;QAAK;QAEhB,gFAAgF;QAChF,MAAMtG,0BAA0B2E;QAChC,MAAMA,WACHjC,UAAU,CAAC,YACXC,GAAG,CAAClC,OAAOsE,UACXU,GAAG,CAAC;YACH1B,QAAQQ,UAAUR,MAAM;YACxBE,OAAOM,UAAUN,KAAK;YACtB,kDAAkD;YAClDsC,SAAS9F,QAAOsB,uBAAAA,MAAM,CAAC,eAAe,YAAtBA,uBAA0B;YAC1CyE,WAAW/F,QAAOsB,yBAAAA,MAAM,CAAC,iBAAiB,YAAxBA,yBAA4B;YAC9C,uEAAuE;YACvE,uEAAuE;YACvE,wEAAwE;YACxE,+DAA+D;YAC/D,6CAA6C;YAC7C0E,WAAWvC,WAAWuC,SAAS;YAC/B,qEAAqE;YACrE,iEAAiE;YACjE,oEAAoE;YACpEL,aAAapB;QACf;QAEF,OAAO7E,IACJE,MAAM,CAAC,KACPC,IAAI,CAAC;YAAEoG,WAAW/B,WAAWgC,EAAE;YAAE5B;YAAS0B,WAAWvC,WAAWuC,SAAS;QAAC;IAC/E,EAAE,OAAOlG,OAAO;QACdqG,QAAQrG,KAAK,CAACA;QACd,OAAOJ,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAA+B;IACtE;AACF,EAAC;AAED,eAAeN,2BAA0B"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/marketplace/src/lib/server/publish-email-starter.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { holdsStampedSiteKey } from '@aglyn/aglyn/app-utils/host-permissions'\nimport { MARKETPLACE_SITE_ROLE_PRESET, marketplaceSitePermissionRefusal } from '../model/marketplace-site-permissions'\nimport { displayNameSearchFields } from '@aglyn/aglyn/app-utils/name-search'\nimport {\n CANVAS_ROOT_ELEMENT_ID,\n checkEntitlement,\n createResourceUid,\n} from '@aglyn/aglyn/server'\nimport { type PluginApiHandler } from '@aglyn/aglyn/server'\nimport { decodeStoredNodes } from '@aglyn/aglyn/app-utils/stored-nodes'\nimport { inlineReusableBlocks } from './publish-email-blocks'\nimport { firebaseAdmin, getOrgForHost } from '@aglyn/tenant-data-admin'\nimport { resolveOrgPermissions } from '@aglyn/tenant-runtime/org-permissions'\nimport {\n emailStarterRefusal,\n inspectEmailStarter,\n MARKETPLACE_EMAIL_STARTER_COMPONENT_ID_ALLOWLIST,\n marketplacePriceRefusal,\n sanitizeMarketplaceDefinition,\n} from '../model'\nimport { resolvePublisherProfile } from './publisher-profile'\nimport { publishPreconditionRefusal } from './publish-preconditions'\nimport { listingSubmissionRefusal } from './listing-screen'\nimport { refreshListingQueryFields } from './listing-query-fields'\n\n/**\n * Publishes a site's campaign email design as a marketplace starter.\n *\n * The source is a `kind: 'email'` SCREEN — the document `createEmailScreen`\n * writes and the screen besigner edits — not an entry in the transactional\n * catalog. That is the whole difference from `publish-email-template`, and it\n * is why the two exist separately: a transactional design is a design FOR a\n * fixed key and installs onto that same key; a starter belongs to no key and\n * installs as a new email of the buyer's own.\n *\n * ## Two things this reads that the transactional publisher does not\n *\n * **The nodes are compressed.** A screen version is written through\n * `screenVersionConverter`, so `nodes` comes back from the Admin SDK as a\n * msgpack `Buffer`. `publish-email-template.ts` reads its `nodes` raw and says\n * why — its besigner saves with a bare `setDoc` and no converter — and copying\n * that line here would publish a Buffer: truthy, non-empty by `Object.keys`\n * (those are byte indices), and scanning as a design with no blocks in it.\n *\n * **The tree is inspected, not just sanitized.** `sanitizeMarketplaceDefinition`\n * DROPS an unsafe URL and publishes what is left, which is right for a page.\n * Here the URL rules are the product: a remote image in an email is a read\n * receipt for whoever hosts it, and quietly removing one teaches the publisher\n * nothing. So `inspectEmailStarter` runs first and REFUSES.\n */\nexport const publishEmailStarterHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n const hostId = String(req.body?.hostId ?? '')\n const screenId = String(req.body?.screenId ?? '')\n const displayName = String(req.body?.displayName ?? '').slice(0, 80)\n const description = String(req.body?.description ?? '').slice(0, 500)\n const category = String(req.body?.category ?? '').slice(0, 40)\n const priceUsd = Math.round(Number(req.body?.priceUsd ?? 0)) || 0\n const priceRefusal = marketplacePriceRefusal(priceUsd)\n if (priceRefusal) return res.status(400).json({ error: priceRefusal })\n if (!hostId || !screenId || !displayName.trim()) {\n return res\n .status(400)\n .json({ error: 'Missing hostId, screenId, or displayName' })\n }\n\n const authorization = String(req.headers.authorization ?? '')\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken) return res.status(401).json({ error: 'Unauthenticated' })\n\n try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n const membership = await resolveOrgPermissions(decoded.uid, { hostId })\n if (!membership.permissions.publishToMarketplace) {\n return res.status(403).json({\n error:\n 'Your organization role does not allow publishing to the marketplace',\n })\n }\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const hostSnapshot = await hostRef.get()\n if (!hostSnapshot.exists) {\n return res.status(404).json({ error: 'Unknown site' })\n }\n // \"Publish a site’s items to the marketplace\" (AGL-4047): the site's stamp, else\n // the preset of the member's site role, the Admin and Editor this asked for.\n if (!holdsStampedSiteKey(hostSnapshot, decoded.uid, 'marketplace.sitePublish', MARKETPLACE_SITE_ROLE_PRESET)) {\n return res.status(403).json({ error: marketplaceSitePermissionRefusal('marketplace.sitePublish') })\n }\n\n const orgForHost = await getOrgForHost(hostId)\n if (!checkEntitlement(orgForHost?.org ?? {}, 'marketplaceSelling')) {\n return res\n .status(403)\n .json({ error: 'Publishing to the marketplace requires a Pro plan' })\n }\n if (!orgForHost?.orgId) {\n return res.status(409).json({ error: 'Site has no owning organization' })\n }\n const publisher = await resolvePublisherProfile(firestore, orgForHost.orgId)\n const refusal = publishPreconditionRefusal(publisher, {\n priceUsd,\n sells: 'templates',\n })\n if (refusal) return res.status(refusal.status).json(refusal.body)\n\n const screenRef = hostRef.collection('screens').doc(screenId)\n const screenSnapshot = await screenRef.get()\n const screen = screenSnapshot.data() as Record<string, unknown> | undefined\n if (!screen || screen['deletedAt']) {\n return res.status(404).json({ error: 'Unknown email' })\n }\n if (screen['kind'] !== 'email') {\n return res\n .status(422)\n .json({ error: 'That design is not an email' })\n }\n const activeVersionId = screen['versionId']\n if (!activeVersionId) {\n return res\n .status(404)\n .json({ error: 'This email has no saved design yet — design and save it first' })\n }\n const versionSnapshot = await screenRef\n .collection('versions')\n .doc(String(activeVersionId))\n .get()\n\n /*\n * The site's reusable blocks INLINED before anything is judged (AGL-3287).\n * A buyer's org has none of this site's components, so a placement has to\n * travel as the blocks it renders — and inlining first is what puts a\n * shared footer's links and images in front of the inspection below, as\n * the send path would mail them. An undecodable payload is left as stored,\n * so the inspection still refuses it by name.\n */\n const stored = versionSnapshot.get('nodes')\n const readable = decodeStoredNodes<Record<string, unknown>>(stored)\n let design: unknown = stored\n if (readable && typeof readable === 'object' && !Array.isArray(readable)) {\n const inlined = await inlineReusableBlocks(readable, {\n firestore,\n hostId,\n rootId: CANVAS_ROOT_ELEMENT_ID,\n })\n if (inlined.ok === false) {\n return res.status(422).json({ error: inlined.error })\n }\n design = inlined.nodes\n }\n // The inspection decodes, so it is also the guard against publishing a\n // node map nothing could read — it refuses rather than reporting a\n // compressed payload as a clean design.\n const inspection = inspectEmailStarter(design)\n const violation = emailStarterRefusal(inspection)\n if (violation) {\n return res.status(422).json({\n error: violation,\n violations: inspection.violations,\n })\n }\n if (!inspection.nodes || !Object.keys(inspection.nodes).length) {\n return res.status(404).json({ error: 'This email design is empty' })\n }\n // Runs after the inspection and over the same decoded map. It enforces the\n // component-id allowlist and trims node keys; the URL rules it also carries\n // can no longer fire, because a design that would have tripped them was\n // refused above rather than silently trimmed.\n const sanitized = sanitizeMarketplaceDefinition(\n { rootId: CANVAS_ROOT_ELEMENT_ID, nodes: inspection.nodes },\n { componentIds: MARKETPLACE_EMAIL_STARTER_COMPONENT_ID_ALLOWLIST },\n )\n if (sanitized.ok === false) {\n return res.status(422).json({ error: sanitized.error })\n }\n\n // One listing per (publisher org, source screen). Re-publishing the same\n // email bumps its version rather than minting a second listing, which is\n // what makes \"update available\" mean anything to everyone who installed it.\n const existing = await firestore\n .collection('marketplaceListings')\n .where('profileId', '==', publisher.orgId)\n .where('sourceHostId', '==', hostId)\n .where('sourceScreenId', '==', screenId)\n .limit(1)\n .get()\n const listingRef = existing.empty\n ? firestore.collection('marketplaceListings').doc(createResourceUid())\n : existing.docs[0].ref\n const version = existing.empty\n ? 1\n : Number(existing.docs[0].get('latestVersion') ?? 0) + 1\n const now = firebaseAdmin.firestore.FieldValue.serverTimestamp()\n\n // The phishing screen, before anything is listed (AGL-3365).\n const screened = await listingSubmissionRefusal({\n publisherOrgId: publisher.orgId,\n content: {\n displayName,\n publisherName: publisher.displayName,\n description,\n emailNodes: sanitized.nodes,\n },\n official: decoded['staff'] === true,\n org: orgForHost.org ?? null,\n })\n if (screened) return res.status(screened.status).json(screened.body)\n\n await listingRef.set(\n {\n profileId: publisher.orgId,\n artifactType: 'emailStarter',\n sourceHostId: hostId,\n sourceScreenId: screenId,\n displayName: displayName.trim(),\n // The keys a listing is searched by (AGL-3321): the template gallery's\n // marketplace shelf asks `nameTokens` on its query.\n ...displayNameSearchFields(displayName.trim()),\n ...(description.trim() && { description: description.trim() }),\n ...(category.trim() && { category: category.trim() }),\n priceUsd,\n latestVersion: version,\n deletedAt: null,\n ...(existing.empty && { createdAt: now }),\n updatedAt: now,\n versionHistory: firebaseAdmin.firestore.FieldValue.arrayUnion({\n version,\n publishedAt: firebaseAdmin.firestore.Timestamp.now(),\n }),\n },\n { merge: true },\n )\n // The lists this listing appears in query by fields derived from it (AGL-3321).\n await refreshListingQueryFields(listingRef)\n await listingRef\n .collection('versions')\n .doc(String(version))\n .set({\n rootId: sanitized.rootId,\n nodes: sanitized.nodes,\n // Copy is part of the design and travels with it.\n subject: String(screen['emailSubject'] ?? ''),\n preheader: String(screen['emailPreheader'] ?? ''),\n // The hosts this design would send a recipient to, recorded at publish\n // so the listing page can show them BEFORE somebody installs. A tenant\n // about to mail their own customers under their own name is entitled to\n // see the domains a stranger's template points them at, and no\n // allowlist can make that judgment for them.\n linkHosts: inspection.linkHosts,\n // Absent `reviewState` is the un-reviewed default, and it is written\n // NOWHERE here on purpose: a publisher who could stamp their own\n // version approved would make the field decorative. Staff write it.\n publishedAt: now,\n })\n\n return res\n .status(200)\n .json({ listingId: listingRef.id, version, linkHosts: inspection.linkHosts })\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Email starter publish failed' })\n }\n}\n\nexport default publishEmailStarterHandler\n"],"names":["holdsStampedSiteKey","MARKETPLACE_SITE_ROLE_PRESET","marketplaceSitePermissionRefusal","displayNameSearchFields","CANVAS_ROOT_ELEMENT_ID","checkEntitlement","createResourceUid","decodeStoredNodes","inlineReusableBlocks","firebaseAdmin","getOrgForHost","resolveOrgPermissions","emailStarterRefusal","inspectEmailStarter","MARKETPLACE_EMAIL_STARTER_COMPONENT_ID_ALLOWLIST","marketplacePriceRefusal","sanitizeMarketplaceDefinition","resolvePublisherProfile","publishPreconditionRefusal","listingSubmissionRefusal","refreshListingQueryFields","publishEmailStarterHandler","req","res","method","status","json","error","hostId","String","body","screenId","displayName","slice","description","category","priceUsd","Math","round","Number","priceRefusal","trim","authorization","headers","idToken","startsWith","length","undefined","existing","orgForHost","screen","decoded","app","auth","verifyIdToken","membership","uid","permissions","publishToMarketplace","firestore","hostRef","collection","doc","hostSnapshot","get","exists","org","orgId","publisher","refusal","sells","screenRef","screenSnapshot","data","activeVersionId","versionSnapshot","stored","readable","design","Array","isArray","inlined","rootId","ok","nodes","inspection","violation","violations","Object","keys","sanitized","componentIds","where","limit","listingRef","empty","docs","ref","version","now","FieldValue","serverTimestamp","screened","publisherOrgId","content","publisherName","emailNodes","official","set","profileId","artifactType","sourceHostId","sourceScreenId","latestVersion","deletedAt","createdAt","updatedAt","versionHistory","arrayUnion","publishedAt","Timestamp","merge","subject","preheader","linkHosts","listingId","id","console"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,mBAAmB,QAAQ,0CAAyC;AAC7E,SAASC,4BAA4B,EAAEC,gCAAgC,QAAQ,2CAAuC;AACtH,SAASC,uBAAuB,QAAQ,qCAAoC;AAC5E,SACEC,sBAAsB,EACtBC,gBAAgB,EAChBC,iBAAiB,QACZ,sBAAqB;AAE5B,SAASC,iBAAiB,QAAQ,sCAAqC;AACvE,SAASC,oBAAoB,QAAQ,4BAAwB;AAC7D,SAASC,aAAa,EAAEC,aAAa,QAAQ,2BAA0B;AACvE,SAASC,qBAAqB,QAAQ,wCAAuC;AAC7E,SACEC,mBAAmB,EACnBC,mBAAmB,EACnBC,gDAAgD,EAChDC,uBAAuB,EACvBC,6BAA6B,QACxB,oBAAU;AACjB,SAASC,uBAAuB,QAAQ,yBAAqB;AAC7D,SAASC,0BAA0B,QAAQ,6BAAyB;AACpE,SAASC,wBAAwB,QAAQ,sBAAkB;AAC3D,SAASC,yBAAyB,QAAQ,4BAAwB;AAElE;;;;;;;;;;;;;;;;;;;;;;;;CAwBC,GACD,OAAO,MAAMC,6BAA+C,OAAOC,KAAKC;iDAkBzCD;QAdPA,WACEA,YACGA,YACAA,YACHA,YACWA;IARnC,IAAIA,IAAIE,MAAM,KAAK,QAAQ;QACzB,OAAOD,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAqB;IAC5D;IACA,MAAMC,SAASC,gBAA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7C0E,WAAWvC,WAAWuC,SAAS;YAC/B,qEAAqE;YACrE,iEAAiE;YACjE,oEAAoE;YACpEL,aAAapB;QACf;QAEF,OAAO5E,IACJE,MAAM,CAAC,KACPC,IAAI,CAAC;YAAEmG,WAAW/B,WAAWgC,EAAE;YAAE5B;YAAS0B,WAAWvC,WAAWuC,SAAS;QAAC;IAC/E,EAAE,OAAOjG,OAAO;QACdoG,QAAQpG,KAAK,CAACA;QACd,OAAOJ,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAA+B;IACtE;AACF,EAAC;AAED,eAAeN,2BAA0B"}
@@ -14,7 +14,9 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
14
14
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
15
  * See the License for the specific language governing permissions and
16
16
  * limitations under the License.
17
- */ import { displayNameSearchFields } from "@aglyn/aglyn/app-utils/name-search";
17
+ */ import { holdsStampedSiteKey } from "@aglyn/aglyn/app-utils/host-permissions";
18
+ import { MARKETPLACE_SITE_ROLE_PRESET, marketplaceSitePermissionRefusal } from "../model/marketplace-site-permissions.js";
19
+ import { displayNameSearchFields } from "@aglyn/aglyn/app-utils/name-search";
18
20
  import { checkEntitlement, createResourceUid, decodeStoredNodes } from "@aglyn/aglyn/server";
19
21
  import { inlineReusableBlocks } from "./publish-email-blocks.js";
20
22
  import { firebaseAdmin, getOrgForHost } from "@aglyn/tenant-data-admin";
@@ -80,7 +82,7 @@ import { refreshListingQueryFields } from "./listing-query-fields.js";
80
82
  error: 'Unauthenticated'
81
83
  });
82
84
  try {
83
- var _hostSnapshot_get, _ref6, _versionSnapshot_get, _existing_docs__get, _orgForHost_org, _templateSnapshot_get, _templateSnapshot_get1;
85
+ var _ref6, _versionSnapshot_get, _existing_docs__get, _orgForHost_org, _templateSnapshot_get, _templateSnapshot_get1;
84
86
  const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken);
85
87
  const membership = await resolveOrgPermissions(decoded.uid, {
86
88
  hostId
@@ -98,10 +100,11 @@ import { refreshListingQueryFields } from "./listing-query-fields.js";
98
100
  error: 'Unknown site'
99
101
  });
100
102
  }
101
- const memberRole = ((_hostSnapshot_get = hostSnapshot.get('memberRoles')) != null ? _hostSnapshot_get : {})[decoded.uid];
102
- if (memberRole !== 'admin' && memberRole !== 'editor') {
103
+ // "Publish a site’s items to the marketplace" (AGL-4047): the site's stamp, else
104
+ // the preset of the member's site role, the Admin and Editor this asked for.
105
+ if (!holdsStampedSiteKey(hostSnapshot, decoded.uid, 'marketplace.sitePublish', MARKETPLACE_SITE_ROLE_PRESET)) {
103
106
  return res.status(403).json({
104
- error: 'Not a site admin or editor'
107
+ error: marketplaceSitePermissionRefusal('marketplace.sitePublish')
105
108
  });
106
109
  }
107
110
  const orgForHost = await getOrgForHost(hostId);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/marketplace/src/lib/server/publish-email-template.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 { displayNameSearchFields } from '@aglyn/aglyn/app-utils/name-search'\nimport {\n checkEntitlement,\n createResourceUid,\n decodeStoredNodes,\n} from '@aglyn/aglyn/server'\nimport { type PluginApiHandler } from '@aglyn/aglyn/server'\nimport { inlineReusableBlocks } from './publish-email-blocks'\nimport { firebaseAdmin, getOrgForHost } from '@aglyn/tenant-data-admin'\nimport { resolveOrgPermissions } from '@aglyn/tenant-runtime/org-permissions'\nimport {\n EMAIL_NODE_ROOT_ID,\n getTenantEmail,\n isTenantEmailEditable,\n TENANT_EMAIL_COLLECTION,\n} from '@aglyn/shared-util-email'\nimport {\n MARKETPLACE_EMAIL_COMPONENT_ID_ALLOWLIST,\n marketplacePriceRefusal,\n sanitizeMarketplaceDefinition,\n} from '../model'\nimport { resolvePublisherProfile } from './publisher-profile'\nimport { publishPreconditionRefusal } from './publish-preconditions'\nimport { listingSubmissionRefusal } from './listing-screen'\nimport { refreshListingQueryFields } from './listing-query-fields'\n\n/**\n * Publishes a site's designed transactional email to the marketplace\n * (AGL-657).\n *\n * An email design is a node tree like any other artifact, but it does NOT live\n * in the host's screen routing map — which is exactly why `publish-template`\n * could never capture one (it only sees `hostSnapshot.get('screens')`). The\n * tree lives at `hosts/{h}/emailTemplates/{key}/versions/{versionId}`, so this\n * reads it directly.\n *\n * `templateKey` is a fixed catalog key ('booking-confirmed', …), not a free\n * id: a published email means \"a design FOR this transactional email\", so the\n * key travels with the listing and the installer lands on the same key.\n */\nexport const publishEmailTemplateHandler: PluginApiHandler = async (\n req,\n res,\n) => {\n if (req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n const hostId = String(req.body?.hostId ?? '')\n const templateKey = String(req.body?.templateKey ?? '')\n const displayName = String(req.body?.displayName ?? '').slice(0, 80)\n const description = String(req.body?.description ?? '').slice(0, 500)\n const category = String(req.body?.category ?? '').slice(0, 40)\n const priceUsd = Math.round(Number(req.body?.priceUsd ?? 0)) || 0\n // The price floor and ceiling, from ONE validator (AGL-2343): a paid listing\n // under `MARKETPLACE_MIN_PRICE_USD` loses money on every sale, because\n // marketplace checkout is a destination charge whose Stripe fee is debited\n // from the platform's balance. Also enforced in `publishPreconditionRefusal`\n // below, so a door that drops this line is still covered.\n const priceRefusal = marketplacePriceRefusal(priceUsd)\n if (priceRefusal) {\n return res.status(400).json({ error: priceRefusal })\n }\n if (!hostId || !templateKey || !displayName.trim()) {\n return res\n .status(400)\n .json({ error: 'Missing hostId, templateKey, or displayName' })\n }\n const entry = getTenantEmail(templateKey)\n if (!entry || !isTenantEmailEditable(entry)) {\n return res.status(400).json({ error: 'Not a designable email template' })\n }\n\n const authorization = String(req.headers.authorization ?? '')\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken) return res.status(401).json({ error: 'Unauthenticated' })\n\n try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n const membership = await resolveOrgPermissions(decoded.uid, { hostId })\n if (!membership.permissions.publishToMarketplace) {\n return res.status(403).json({\n error:\n 'Your organization role does not allow publishing to the marketplace',\n })\n }\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const hostSnapshot = await hostRef.get()\n if (!hostSnapshot.exists) {\n return res.status(404).json({ error: 'Unknown site' })\n }\n const memberRole = (hostSnapshot.get('memberRoles') ?? {})[decoded.uid]\n if (memberRole !== 'admin' && memberRole !== 'editor') {\n return res.status(403).json({ error: 'Not a site admin or editor' })\n }\n\n const orgForHost = await getOrgForHost(hostId)\n if (!checkEntitlement(orgForHost?.org ?? {}, 'marketplaceSelling')) {\n return res\n .status(403)\n .json({ error: 'Publishing to the marketplace requires a Pro plan' })\n }\n if (!orgForHost?.orgId) {\n return res.status(409).json({ error: 'Site has no owning organization' })\n }\n\n const publisher = await resolvePublisherProfile(firestore, orgForHost.orgId)\n // Profile, payouts AND the publisher agreement, in one gate\n // (AGL-2282) — see `publishPreconditionRefusal`.\n const refusal = publishPreconditionRefusal(publisher, {\n priceUsd,\n sells: 'templates',\n })\n if (refusal) return res.status(refusal.status).json(refusal.body)\n\n const templateRef = hostRef\n .collection(TENANT_EMAIL_COLLECTION)\n .doc(templateKey)\n const templateSnapshot = await templateRef.get()\n const activeVersionId = templateSnapshot.get('versionId')\n if (!templateSnapshot.exists || !activeVersionId) {\n return res.status(404).json({\n error: 'This email has no published design yet — design and save it first',\n })\n }\n const versionSnapshot = await templateRef\n .collection('versions')\n .doc(String(activeVersionId))\n .get()\n // Decoded, like the screen and layout publish paths (AGL-1395): the email\n // besigner now compresses through a converter as those do, and versions\n // written before it did are still plain maps, which come back unchanged.\n //\n // `sanitizeMarketplaceDefinition` below would refuse an undecoded tree\n // rather than publish garbage, so this is the difference between the\n // feature working and a publish that always says the design is invalid.\n const stored = decodeStoredNodes<Record<string, any>>(\n versionSnapshot.get('nodes'),\n )\n if (!stored || !Object.keys(stored).length) {\n return res.status(404).json({ error: 'This email design is empty' })\n }\n const rootId = versionSnapshot.get('rootId') ?? EMAIL_NODE_ROOT_ID\n // The site's reusable blocks INLINED (AGL-3287): a listing is installed\n // into another org, which has none of this site's components, and the\n // sanitizer below refuses a component reference outright.\n const inlined = await inlineReusableBlocks(stored, {\n firestore,\n hostId,\n rootId,\n })\n if (inlined.ok === false) {\n return res.status(422).json({ error: inlined.error })\n }\n const nodes = inlined.nodes\n // Emails are built from `plugins-email` blocks only, so the page allowlist\n // is REPLACED rather than extended — see MARKETPLACE_EMAIL_COMPONENT_ID_ALLOWLIST\n // for why `emailHtml` is not on the list.\n const sanitized = sanitizeMarketplaceDefinition(\n { rootId, nodes },\n { componentIds: MARKETPLACE_EMAIL_COMPONENT_ID_ALLOWLIST },\n )\n if (sanitized.ok === false) {\n return res.status(422).json({ error: sanitized.error })\n }\n\n // One listing per (source site, template key).\n const existing = await firestore\n .collection('marketplaceListings')\n .where('profileId', '==', publisher.orgId)\n .where('sourceHostId', '==', hostId)\n .where('emailTemplateKey', '==', templateKey)\n .limit(1)\n .get()\n const listingRef = existing.empty\n ? firestore.collection('marketplaceListings').doc(createResourceUid())\n : existing.docs[0].ref\n const version = existing.empty\n ? 1\n : Number(existing.docs[0].get('latestVersion') ?? 0) + 1\n const now = firebaseAdmin.firestore.FieldValue.serverTimestamp()\n\n // The phishing screen, before anything is listed (AGL-3365).\n const screened = await listingSubmissionRefusal({\n publisherOrgId: publisher.orgId,\n content: {\n displayName,\n publisherName: publisher.displayName,\n description,\n emailNodes: sanitized.nodes,\n },\n official: decoded['staff'] === true,\n org: orgForHost.org ?? null,\n })\n if (screened) return res.status(screened.status).json(screened.body)\n\n await listingRef.set(\n {\n profileId: publisher.orgId,\n artifactType: 'emailTemplate',\n sourceHostId: hostId,\n emailTemplateKey: templateKey,\n displayName: displayName.trim(),\n // The keys a listing is searched by (AGL-3321): the template gallery's\n // marketplace shelf asks `nameTokens` on its query.\n ...displayNameSearchFields(displayName.trim()),\n ...(description.trim() && { description: description.trim() }),\n ...(category.trim() && { category: category.trim() }),\n priceUsd,\n latestVersion: version,\n deletedAt: null,\n ...(existing.empty && { createdAt: now }),\n updatedAt: now,\n versionHistory: firebaseAdmin.firestore.FieldValue.arrayUnion({\n version,\n publishedAt: firebaseAdmin.firestore.Timestamp.now(),\n }),\n },\n { merge: true },\n )\n // The lists this listing appears in query by fields derived from it (AGL-3321).\n await refreshListingQueryFields(listingRef)\n await listingRef\n .collection('versions')\n .doc(String(version))\n .set({\n rootId: sanitized.rootId,\n nodes: sanitized.nodes,\n emailTemplateKey: templateKey,\n // The copy fields are part of the design, not the tree.\n subject: String(templateSnapshot.get('subject') ?? ''),\n preheader: String(templateSnapshot.get('preheader') ?? ''),\n publishedAt: now,\n })\n\n return res.status(200).json({ listingId: listingRef.id, version })\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Publish failed' })\n }\n}\n\nexport default publishEmailTemplateHandler\n"],"names":["displayNameSearchFields","checkEntitlement","createResourceUid","decodeStoredNodes","inlineReusableBlocks","firebaseAdmin","getOrgForHost","resolveOrgPermissions","EMAIL_NODE_ROOT_ID","getTenantEmail","isTenantEmailEditable","TENANT_EMAIL_COLLECTION","MARKETPLACE_EMAIL_COMPONENT_ID_ALLOWLIST","marketplacePriceRefusal","sanitizeMarketplaceDefinition","resolvePublisherProfile","publishPreconditionRefusal","listingSubmissionRefusal","refreshListingQueryFields","publishEmailTemplateHandler","req","res","method","status","json","error","hostId","String","body","templateKey","displayName","slice","description","category","priceUsd","Math","round","Number","priceRefusal","trim","entry","authorization","headers","idToken","startsWith","length","undefined","hostSnapshot","versionSnapshot","existing","orgForHost","templateSnapshot","decoded","app","auth","verifyIdToken","membership","uid","permissions","publishToMarketplace","firestore","hostRef","collection","doc","get","exists","memberRole","org","orgId","publisher","refusal","sells","templateRef","activeVersionId","stored","Object","keys","rootId","inlined","ok","nodes","sanitized","componentIds","where","limit","listingRef","empty","docs","ref","version","now","FieldValue","serverTimestamp","screened","publisherOrgId","content","publisherName","emailNodes","official","set","profileId","artifactType","sourceHostId","emailTemplateKey","latestVersion","deletedAt","createdAt","updatedAt","versionHistory","arrayUnion","publishedAt","Timestamp","merge","subject","preheader","listingId","id","console"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,uBAAuB,QAAQ,qCAAoC;AAC5E,SACEC,gBAAgB,EAChBC,iBAAiB,EACjBC,iBAAiB,QACZ,sBAAqB;AAE5B,SAASC,oBAAoB,QAAQ,4BAAwB;AAC7D,SAASC,aAAa,EAAEC,aAAa,QAAQ,2BAA0B;AACvE,SAASC,qBAAqB,QAAQ,wCAAuC;AAC7E,SACEC,kBAAkB,EAClBC,cAAc,EACdC,qBAAqB,EACrBC,uBAAuB,QAClB,2BAA0B;AACjC,SACEC,wCAAwC,EACxCC,uBAAuB,EACvBC,6BAA6B,QACxB,oBAAU;AACjB,SAASC,uBAAuB,QAAQ,yBAAqB;AAC7D,SAASC,0BAA0B,QAAQ,6BAAyB;AACpE,SAASC,wBAAwB,QAAQ,sBAAkB;AAC3D,SAASC,yBAAyB,QAAQ,4BAAwB;AAElE;;;;;;;;;;;;;CAaC,GACD,OAAO,MAAMC,8BAAgD,OAC3DC,KACAC;iDA8B6BD;QAzBPA,WACKA,YACAA,YACAA,YACHA,YACWA;IARnC,IAAIA,IAAIE,MAAM,KAAK,QAAQ;QACzB,OAAOD,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAqB;IAC5D;IACA,MAAMC,SAASC,gBAAOP,YAAAA,IAAIQ,IAAI,qBAARR,UAAUM,MAAM,mB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../../../../../../../libs/plugins/marketplace/src/lib/server/publish-email-template.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 { holdsStampedSiteKey } from '@aglyn/aglyn/app-utils/host-permissions'\nimport { MARKETPLACE_SITE_ROLE_PRESET, marketplaceSitePermissionRefusal } from '../model/marketplace-site-permissions'\nimport { displayNameSearchFields } from '@aglyn/aglyn/app-utils/name-search'\nimport {\n checkEntitlement,\n createResourceUid,\n decodeStoredNodes,\n} from '@aglyn/aglyn/server'\nimport { type PluginApiHandler } from '@aglyn/aglyn/server'\nimport { inlineReusableBlocks } from './publish-email-blocks'\nimport { firebaseAdmin, getOrgForHost } from '@aglyn/tenant-data-admin'\nimport { resolveOrgPermissions } from '@aglyn/tenant-runtime/org-permissions'\nimport {\n EMAIL_NODE_ROOT_ID,\n getTenantEmail,\n isTenantEmailEditable,\n TENANT_EMAIL_COLLECTION,\n} from '@aglyn/shared-util-email'\nimport {\n MARKETPLACE_EMAIL_COMPONENT_ID_ALLOWLIST,\n marketplacePriceRefusal,\n sanitizeMarketplaceDefinition,\n} from '../model'\nimport { resolvePublisherProfile } from './publisher-profile'\nimport { publishPreconditionRefusal } from './publish-preconditions'\nimport { listingSubmissionRefusal } from './listing-screen'\nimport { refreshListingQueryFields } from './listing-query-fields'\n\n/**\n * Publishes a site's designed transactional email to the marketplace\n * (AGL-657).\n *\n * An email design is a node tree like any other artifact, but it does NOT live\n * in the host's screen routing map — which is exactly why `publish-template`\n * could never capture one (it only sees `hostSnapshot.get('screens')`). The\n * tree lives at `hosts/{h}/emailTemplates/{key}/versions/{versionId}`, so this\n * reads it directly.\n *\n * `templateKey` is a fixed catalog key ('booking-confirmed', …), not a free\n * id: a published email means \"a design FOR this transactional email\", so the\n * key travels with the listing and the installer lands on the same key.\n */\nexport const publishEmailTemplateHandler: PluginApiHandler = async (\n req,\n res,\n) => {\n if (req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n const hostId = String(req.body?.hostId ?? '')\n const templateKey = String(req.body?.templateKey ?? '')\n const displayName = String(req.body?.displayName ?? '').slice(0, 80)\n const description = String(req.body?.description ?? '').slice(0, 500)\n const category = String(req.body?.category ?? '').slice(0, 40)\n const priceUsd = Math.round(Number(req.body?.priceUsd ?? 0)) || 0\n // The price floor and ceiling, from ONE validator (AGL-2343): a paid listing\n // under `MARKETPLACE_MIN_PRICE_USD` loses money on every sale, because\n // marketplace checkout is a destination charge whose Stripe fee is debited\n // from the platform's balance. Also enforced in `publishPreconditionRefusal`\n // below, so a door that drops this line is still covered.\n const priceRefusal = marketplacePriceRefusal(priceUsd)\n if (priceRefusal) {\n return res.status(400).json({ error: priceRefusal })\n }\n if (!hostId || !templateKey || !displayName.trim()) {\n return res\n .status(400)\n .json({ error: 'Missing hostId, templateKey, or displayName' })\n }\n const entry = getTenantEmail(templateKey)\n if (!entry || !isTenantEmailEditable(entry)) {\n return res.status(400).json({ error: 'Not a designable email template' })\n }\n\n const authorization = String(req.headers.authorization ?? '')\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken) return res.status(401).json({ error: 'Unauthenticated' })\n\n try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n const membership = await resolveOrgPermissions(decoded.uid, { hostId })\n if (!membership.permissions.publishToMarketplace) {\n return res.status(403).json({\n error:\n 'Your organization role does not allow publishing to the marketplace',\n })\n }\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const hostSnapshot = await hostRef.get()\n if (!hostSnapshot.exists) {\n return res.status(404).json({ error: 'Unknown site' })\n }\n // \"Publish a site’s items to the marketplace\" (AGL-4047): the site's stamp, else\n // the preset of the member's site role, the Admin and Editor this asked for.\n if (!holdsStampedSiteKey(hostSnapshot, decoded.uid, 'marketplace.sitePublish', MARKETPLACE_SITE_ROLE_PRESET)) {\n return res.status(403).json({ error: marketplaceSitePermissionRefusal('marketplace.sitePublish') })\n }\n\n const orgForHost = await getOrgForHost(hostId)\n if (!checkEntitlement(orgForHost?.org ?? {}, 'marketplaceSelling')) {\n return res\n .status(403)\n .json({ error: 'Publishing to the marketplace requires a Pro plan' })\n }\n if (!orgForHost?.orgId) {\n return res.status(409).json({ error: 'Site has no owning organization' })\n }\n\n const publisher = await resolvePublisherProfile(firestore, orgForHost.orgId)\n // Profile, payouts AND the publisher agreement, in one gate\n // (AGL-2282) — see `publishPreconditionRefusal`.\n const refusal = publishPreconditionRefusal(publisher, {\n priceUsd,\n sells: 'templates',\n })\n if (refusal) return res.status(refusal.status).json(refusal.body)\n\n const templateRef = hostRef\n .collection(TENANT_EMAIL_COLLECTION)\n .doc(templateKey)\n const templateSnapshot = await templateRef.get()\n const activeVersionId = templateSnapshot.get('versionId')\n if (!templateSnapshot.exists || !activeVersionId) {\n return res.status(404).json({\n error: 'This email has no published design yet — design and save it first',\n })\n }\n const versionSnapshot = await templateRef\n .collection('versions')\n .doc(String(activeVersionId))\n .get()\n // Decoded, like the screen and layout publish paths (AGL-1395): the email\n // besigner now compresses through a converter as those do, and versions\n // written before it did are still plain maps, which come back unchanged.\n //\n // `sanitizeMarketplaceDefinition` below would refuse an undecoded tree\n // rather than publish garbage, so this is the difference between the\n // feature working and a publish that always says the design is invalid.\n const stored = decodeStoredNodes<Record<string, any>>(\n versionSnapshot.get('nodes'),\n )\n if (!stored || !Object.keys(stored).length) {\n return res.status(404).json({ error: 'This email design is empty' })\n }\n const rootId = versionSnapshot.get('rootId') ?? EMAIL_NODE_ROOT_ID\n // The site's reusable blocks INLINED (AGL-3287): a listing is installed\n // into another org, which has none of this site's components, and the\n // sanitizer below refuses a component reference outright.\n const inlined = await inlineReusableBlocks(stored, {\n firestore,\n hostId,\n rootId,\n })\n if (inlined.ok === false) {\n return res.status(422).json({ error: inlined.error })\n }\n const nodes = inlined.nodes\n // Emails are built from `plugins-email` blocks only, so the page allowlist\n // is REPLACED rather than extended — see MARKETPLACE_EMAIL_COMPONENT_ID_ALLOWLIST\n // for why `emailHtml` is not on the list.\n const sanitized = sanitizeMarketplaceDefinition(\n { rootId, nodes },\n { componentIds: MARKETPLACE_EMAIL_COMPONENT_ID_ALLOWLIST },\n )\n if (sanitized.ok === false) {\n return res.status(422).json({ error: sanitized.error })\n }\n\n // One listing per (source site, template key).\n const existing = await firestore\n .collection('marketplaceListings')\n .where('profileId', '==', publisher.orgId)\n .where('sourceHostId', '==', hostId)\n .where('emailTemplateKey', '==', templateKey)\n .limit(1)\n .get()\n const listingRef = existing.empty\n ? firestore.collection('marketplaceListings').doc(createResourceUid())\n : existing.docs[0].ref\n const version = existing.empty\n ? 1\n : Number(existing.docs[0].get('latestVersion') ?? 0) + 1\n const now = firebaseAdmin.firestore.FieldValue.serverTimestamp()\n\n // The phishing screen, before anything is listed (AGL-3365).\n const screened = await listingSubmissionRefusal({\n publisherOrgId: publisher.orgId,\n content: {\n displayName,\n publisherName: publisher.displayName,\n description,\n emailNodes: sanitized.nodes,\n },\n official: decoded['staff'] === true,\n org: orgForHost.org ?? null,\n })\n if (screened) return res.status(screened.status).json(screened.body)\n\n await listingRef.set(\n {\n profileId: publisher.orgId,\n artifactType: 'emailTemplate',\n sourceHostId: hostId,\n emailTemplateKey: templateKey,\n displayName: displayName.trim(),\n // The keys a listing is searched by (AGL-3321): the template gallery's\n // marketplace shelf asks `nameTokens` on its query.\n ...displayNameSearchFields(displayName.trim()),\n ...(description.trim() && { description: description.trim() }),\n ...(category.trim() && { category: category.trim() }),\n priceUsd,\n latestVersion: version,\n deletedAt: null,\n ...(existing.empty && { createdAt: now }),\n updatedAt: now,\n versionHistory: firebaseAdmin.firestore.FieldValue.arrayUnion({\n version,\n publishedAt: firebaseAdmin.firestore.Timestamp.now(),\n }),\n },\n { merge: true },\n )\n // The lists this listing appears in query by fields derived from it (AGL-3321).\n await refreshListingQueryFields(listingRef)\n await listingRef\n .collection('versions')\n .doc(String(version))\n .set({\n rootId: sanitized.rootId,\n nodes: sanitized.nodes,\n emailTemplateKey: templateKey,\n // The copy fields are part of the design, not the tree.\n subject: String(templateSnapshot.get('subject') ?? ''),\n preheader: String(templateSnapshot.get('preheader') ?? ''),\n publishedAt: now,\n })\n\n return res.status(200).json({ listingId: listingRef.id, version })\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Publish failed' })\n }\n}\n\nexport default publishEmailTemplateHandler\n"],"names":["holdsStampedSiteKey","MARKETPLACE_SITE_ROLE_PRESET","marketplaceSitePermissionRefusal","displayNameSearchFields","checkEntitlement","createResourceUid","decodeStoredNodes","inlineReusableBlocks","firebaseAdmin","getOrgForHost","resolveOrgPermissions","EMAIL_NODE_ROOT_ID","getTenantEmail","isTenantEmailEditable","TENANT_EMAIL_COLLECTION","MARKETPLACE_EMAIL_COMPONENT_ID_ALLOWLIST","marketplacePriceRefusal","sanitizeMarketplaceDefinition","resolvePublisherProfile","publishPreconditionRefusal","listingSubmissionRefusal","refreshListingQueryFields","publishEmailTemplateHandler","req","res","method","status","json","error","hostId","String","body","templateKey","displayName","slice","description","category","priceUsd","Math","round","Number","priceRefusal","trim","entry","authorization","headers","idToken","startsWith","length","undefined","versionSnapshot","existing","orgForHost","templateSnapshot","decoded","app","auth","verifyIdToken","membership","uid","permissions","publishToMarketplace","firestore","hostRef","collection","doc","hostSnapshot","get","exists","org","orgId","publisher","refusal","sells","templateRef","activeVersionId","stored","Object","keys","rootId","inlined","ok","nodes","sanitized","componentIds","where","limit","listingRef","empty","docs","ref","version","now","FieldValue","serverTimestamp","screened","publisherOrgId","content","publisherName","emailNodes","official","set","profileId","artifactType","sourceHostId","emailTemplateKey","latestVersion","deletedAt","createdAt","updatedAt","versionHistory","arrayUnion","publishedAt","Timestamp","merge","subject","preheader","listingId","id","console"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,mBAAmB,QAAQ,0CAAyC;AAC7E,SAASC,4BAA4B,EAAEC,gCAAgC,QAAQ,2CAAuC;AACtH,SAASC,uBAAuB,QAAQ,qCAAoC;AAC5E,SACEC,gBAAgB,EAChBC,iBAAiB,EACjBC,iBAAiB,QACZ,sBAAqB;AAE5B,SAASC,oBAAoB,QAAQ,4BAAwB;AAC7D,SAASC,aAAa,EAAEC,aAAa,QAAQ,2BAA0B;AACvE,SAASC,qBAAqB,QAAQ,wCAAuC;AAC7E,SACEC,kBAAkB,EAClBC,cAAc,EACdC,qBAAqB,EACrBC,uBAAuB,QAClB,2BAA0B;AACjC,SACEC,wCAAwC,EACxCC,uBAAuB,EACvBC,6BAA6B,QACxB,oBAAU;AACjB,SAASC,uBAAuB,QAAQ,yBAAqB;AAC7D,SAASC,0BAA0B,QAAQ,6BAAyB;AACpE,SAASC,wBAAwB,QAAQ,sBAAkB;AAC3D,SAASC,yBAAyB,QAAQ,4BAAwB;AAElE;;;;;;;;;;;;;CAaC,GACD,OAAO,MAAMC,8BAAgD,OAC3DC,KACAC;iDA8B6BD;QAzBPA,WACKA,YACAA,YACAA,YACHA,YACWA;IARnC,IAAIA,IAAIE,MAAM,KAAK,QAAQ;QACzB,OAAOD,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAqB;IAC5D;IACA,MAAMC,SAASC,gBAAOP,YAAAA,IAAIQ,IAAI,qBAARR,UAAUM,MAAM,mBAAI;IAC1C,MAAMG,cAAcF,iBAAOP,aAAAA,IAAIQ,IAAI,qBAARR,WAAUS,WAAW,oBAAI;IACpD,MAAMC,cAAcH,iBAAOP,aAAAA,IAAIQ,IAAI,qBAARR,WAAUU,WAAW,oBAAI,IAAIC,KAAK,CAAC,GAAG;I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A,YAAYO,IAAI;QAAG,GACxDN,SAASM,IAAI,MAAM;YAAEN,UAAUA,SAASM,IAAI;QAAG;YACnDL;YACAqE,eAAef;YACfgB,WAAW;WACPxD,SAASqC,KAAK,IAAI;YAAEoB,WAAWhB;QAAI;YACvCiB,WAAWjB;YACXkB,gBAAgBtG,cAAcsD,SAAS,CAAC+B,UAAU,CAACkB,UAAU,CAAC;gBAC5DpB;gBACAqB,aAAaxG,cAAcsD,SAAS,CAACmD,SAAS,CAACrB,GAAG;YACpD;YAEF;YAAEsB,OAAO;QAAK;QAEhB,gFAAgF;QAChF,MAAM7F,0BAA0BkE;QAChC,MAAMA,WACHvB,UAAU,CAAC,YACXC,GAAG,CAACnC,OAAO6D,UACXU,GAAG,CAAC;YACHtB,QAAQI,UAAUJ,MAAM;YACxBG,OAAOC,UAAUD,KAAK;YACtBuB,kBAAkBzE;YAClB,wDAAwD;YACxDmF,SAASrF,QAAOuB,wBAAAA,iBAAiBc,GAAG,CAAC,sBAArBd,wBAAmC;YACnD+D,WAAWtF,QAAOuB,yBAAAA,iBAAiBc,GAAG,CAAC,wBAArBd,yBAAqC;YACvD2D,aAAapB;QACf;QAEF,OAAOpE,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAE0F,WAAW9B,WAAW+B,EAAE;YAAE3B;QAAQ;IAClE,EAAE,OAAO/D,OAAO;QACd2F,QAAQ3F,KAAK,CAACA;QACd,OAAOJ,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAiB;IACxD;AACF,EAAC;AAED,eAAeN,4BAA2B"}
@@ -14,7 +14,9 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
14
14
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
15
  * See the License for the specific language governing permissions and
16
16
  * limitations under the License.
17
- */ import { displayNameSearchFields } from "@aglyn/aglyn/app-utils/name-search";
17
+ */ import { holdsStampedSiteKey } from "@aglyn/aglyn/app-utils/host-permissions";
18
+ import { MARKETPLACE_SITE_ROLE_PRESET, marketplaceSitePermissionRefusal } from "../model/marketplace-site-permissions.js";
19
+ import { displayNameSearchFields } from "@aglyn/aglyn/app-utils/name-search";
18
20
  import { CANVAS_ROOT_ELEMENT_ID, checkEntitlement, createResourceUid, decodeStoredNodes } from "@aglyn/aglyn/server";
19
21
  import { firebaseAdmin, getOrgForHost } from "@aglyn/tenant-data-admin";
20
22
  import { resolveOrgPermissions } from "@aglyn/tenant-runtime/org-permissions";
@@ -73,7 +75,7 @@ import { refreshListingQueryFields } from "./listing-query-fields.js";
73
75
  error: 'Unauthenticated'
74
76
  });
75
77
  try {
76
- var _hostSnapshot_get, _ref6, _existing_docs__get, _orgForHost_org;
78
+ var _ref6, _existing_docs__get, _orgForHost_org;
77
79
  const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken);
78
80
  const membership = await resolveOrgPermissions(decoded.uid, {
79
81
  hostId
@@ -91,10 +93,11 @@ import { refreshListingQueryFields } from "./listing-query-fields.js";
91
93
  error: 'Unknown site'
92
94
  });
93
95
  }
94
- const memberRole = ((_hostSnapshot_get = hostSnapshot.get('memberRoles')) != null ? _hostSnapshot_get : {})[decoded.uid];
95
- if (memberRole !== 'admin' && memberRole !== 'editor') {
96
+ // "Publish a site’s items to the marketplace" (AGL-4047): the site's stamp, else
97
+ // the preset of the member's site role, the Admin and Editor this asked for.
98
+ if (!holdsStampedSiteKey(hostSnapshot, decoded.uid, 'marketplace.sitePublish', MARKETPLACE_SITE_ROLE_PRESET)) {
96
99
  return res.status(403).json({
97
- error: 'Not a site admin or editor'
100
+ error: marketplaceSitePermissionRefusal('marketplace.sitePublish')
98
101
  });
99
102
  }
100
103
  const orgForHost = await getOrgForHost(hostId);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/marketplace/src/lib/server/publish-layout.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 { displayNameSearchFields } from '@aglyn/aglyn/app-utils/name-search'\nimport {\n CANVAS_ROOT_ELEMENT_ID,\n checkEntitlement,\n createResourceUid,\n decodeStoredNodes,\n} from '@aglyn/aglyn/server'\nimport { type PluginApiHandler } from '@aglyn/aglyn/server'\nimport { firebaseAdmin, getOrgForHost } from '@aglyn/tenant-data-admin'\nimport { resolveOrgPermissions } from '@aglyn/tenant-runtime/org-permissions'\nimport {\n marketplacePriceRefusal,\n sanitizeMarketplaceDefinition,\n} from '../model/marketplace'\nimport { sanitizeMarketplaceProps } from '../model/marketplace-props'\nimport { resolvePublisherProfile } from './publisher-profile'\nimport { publishPreconditionRefusal } from './publish-preconditions'\nimport { listingSubmissionRefusal } from './listing-screen'\nimport { refreshListingQueryFields } from './listing-query-fields'\n\n/** The node marking where a bound screen's content grafts in. */\nconst LAYOUT_SLOT_COMPONENT_ID = 'layoutSlot'\n\n/**\n * Publishes a shared layout to the marketplace (AGL-671).\n *\n * Layouts were the one design asset that could not be shared at all:\n * `publish-template` captures screens and theme only, and `layoutSlot` is\n * excluded from the marketplace allowlist as \"layout chrome\". Both are\n * addressed here — the slot is permitted for this artifact type\n * specifically, since a layout without one is chrome with nowhere to put\n * the page.\n *\n * Gates mirror template publishing exactly: org permission, host role,\n * `marketplaceSelling`, an org publisher profile, and payouts configured\n * before anything can be sold.\n */\nexport const publishLayoutHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n const hostId = String(req.body?.hostId ?? '')\n const layoutId = String(req.body?.layoutId ?? '')\n const displayName = String(req.body?.displayName ?? '')\n const description = String(req.body?.description ?? '')\n const category = String(req.body?.category ?? '')\n const priceUsd = Math.max(0, Math.round(Number(req.body?.priceUsd ?? 0)))\n if (!hostId || !layoutId || !displayName.trim()) {\n return res\n .status(400)\n .json({ error: 'Missing hostId, layoutId or displayName' })\n }\n // The price floor and ceiling, from ONE validator (AGL-2343). This door had\n // NO price validation at all: it clamped to zero and stored whatever came in,\n // so both a $1 listing that loses money on every sale and a $250,000 one were\n // publishable here. Also enforced in `publishPreconditionRefusal` below.\n const priceRefusal = marketplacePriceRefusal(priceUsd)\n if (priceRefusal) {\n return res.status(400).json({ error: priceRefusal })\n }\n const authorization = String(req.headers.authorization ?? '')\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken) return res.status(401).json({ error: 'Unauthenticated' })\n\n try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n const membership = await resolveOrgPermissions(decoded.uid, { hostId })\n if (!membership.permissions.publishToMarketplace) {\n return res.status(403).json({\n error:\n 'Your organization role does not allow publishing to the marketplace',\n })\n }\n const firestore = firebaseAdmin.app().firestore()\n\n const hostRef = firestore.collection('hosts').doc(hostId)\n const hostSnapshot = await hostRef.get()\n if (!hostSnapshot.exists) {\n return res.status(404).json({ error: 'Unknown site' })\n }\n const memberRole = (hostSnapshot.get('memberRoles') ?? {})[decoded.uid]\n if (memberRole !== 'admin' && memberRole !== 'editor') {\n return res.status(403).json({ error: 'Not a site admin or editor' })\n }\n\n const orgForHost = await getOrgForHost(hostId)\n const org = orgForHost?.org ?? {}\n if (!checkEntitlement(org as any, 'marketplaceSelling')) {\n return res.status(403).json({\n error: 'Publishing to the marketplace requires a Pro plan',\n })\n }\n if (!orgForHost?.orgId) {\n return res.status(409).json({ error: 'Site has no owning organization' })\n }\n\n const publisher = await resolvePublisherProfile(firestore, orgForHost.orgId)\n // Profile, payouts AND the publisher agreement, in one gate\n // (AGL-2282) — see `publishPreconditionRefusal`.\n const refusal = publishPreconditionRefusal(publisher, {\n priceUsd,\n sells: 'layouts',\n })\n if (refusal) return res.status(refusal.status).json(refusal.body)\n\n const layoutRef = hostRef.collection('layouts').doc(layoutId)\n const layoutSnapshot = await layoutRef.get()\n if (!layoutSnapshot.exists) {\n return res.status(404).json({ error: 'Unknown layout' })\n }\n const versionId = layoutSnapshot.get('versionId')\n if (!versionId) {\n return res.status(422).json({\n error: 'Publish this layout on your site first — there is no ' +\n 'published version to share',\n })\n }\n const versionSnapshot = await layoutRef\n .collection('versions')\n .doc(String(versionId))\n .get()\n // `nodes` is stored in more than one form and the besigner writes the\n // COMPRESSED one, which the Admin SDK materialises as a Node `Buffer`\n // (AGL-1395). Read raw, this was worse than the template path: the length\n // check passed on the BYTE COUNT, and the root search below walked byte\n // INDICES — byte 0 is a number, a number has no `parentId`, so `rootId`\n // resolved to `'0'` and the sanitizer built a wrapper around nothing.\n // Every besigner-edited layout was refused as empty or slotless.\n const nodes = decodeStoredNodes<Record<string, any>>(\n versionSnapshot.get('nodes'),\n )\n if (!nodes || !Object.keys(nodes).length) {\n return res.status(422).json({ error: 'Layout version has no content' })\n }\n\n // The layout properties its tree binds to (AGL-2933), from the same\n // version. A default the sanitizer refuses is cleared and its property\n // kept — see `sanitizeMarketplaceProps`.\n const props = sanitizeMarketplaceProps(versionSnapshot.get('props'))\n if (props.ok === false) {\n return res.status(422).json({ error: props.error })\n }\n\n // Layout versions have no explicit rootId. The besigner canvas roots them\n // at the same wrapper screens use, so prefer it outright; the parentless\n // search stays as the fallback for anything authored before that, and\n // matches how the renderer walks them. Preferring the wrapper also means a\n // top-level node that relies on child arrays alone — legal, see\n // `compose-layout-nodes` — can no longer win the search over the real root.\n const rootId: string =\n (nodes[CANVAS_ROOT_ELEMENT_ID] && CANVAS_ROOT_ELEMENT_ID) ||\n Object.keys(nodes).find((id) => !nodes[id]?.parentId) ||\n Object.keys(nodes)[0] ||\n ''\n const sanitized = sanitizeMarketplaceDefinition(\n { rootId, nodes },\n {\n extraComponentIds: [LAYOUT_SLOT_COMPONENT_ID],\n // A link or image bound whole to a Link or Image property travels\n // bound (AGL-2933).\n declaredProps: props.props,\n },\n )\n // `=== false` rather than `!sanitized.ok`: the compiler does not narrow\n // the union on the negated form here, and publish-template hit the same\n // thing first.\n if (sanitized.ok === false) {\n return res.status(400).json({ error: sanitized.error })\n }\n // A layout whose slot did not survive would render as chrome with the\n // page content missing — better to refuse than to publish that.\n const hasSlot = Object.values(sanitized.nodes).some(\n (node: any) => node.componentId === LAYOUT_SLOT_COMPONENT_ID,\n )\n if (!hasSlot) {\n return res.status(422).json({\n error:\n 'This layout has no content slot, so pages using it would have ' +\n 'nowhere to render',\n })\n }\n\n // One listing per source layout; re-publish bumps the version.\n const existing = await firestore\n .collection('marketplaceListings')\n .where('profileId', '==', publisher.orgId)\n .where('sourceLayoutId', '==', layoutId)\n .limit(1)\n .get()\n const listingRef = existing.empty\n ? firestore.collection('marketplaceListings').doc(createResourceUid())\n : existing.docs[0].ref\n const version = existing.empty\n ? 1\n : Number(existing.docs[0].get('latestVersion') ?? 0) + 1\n const now = firebaseAdmin.firestore.FieldValue.serverTimestamp()\n\n // The phishing screen, before anything is listed (AGL-3365).\n const screened = await listingSubmissionRefusal({\n publisherOrgId: publisher.orgId,\n content: {\n displayName,\n publisherName: publisher.displayName,\n description,\n pageNodes: sanitized.nodes,\n },\n official: decoded['staff'] === true,\n org: orgForHost.org ?? null,\n })\n if (screened) return res.status(screened.status).json(screened.body)\n\n await listingRef.set(\n {\n artifactType: 'layout',\n profileId: publisher.orgId,\n sourceHostId: hostId,\n sourceLayoutId: layoutId,\n displayName: displayName.trim(),\n // The keys a listing is searched by (AGL-3321): the template gallery's\n // marketplace shelf asks `nameTokens` on its query.\n ...displayNameSearchFields(displayName.trim()),\n ...(description.trim() && { description: description.trim() }),\n ...(category.trim() && { category: category.trim() }),\n priceUsd,\n latestVersion: version,\n deletedAt: null,\n ...(existing.empty && { createdAt: now }),\n updatedAt: now,\n versionHistory: firebaseAdmin.firestore.FieldValue.arrayUnion({\n version,\n publishedAt: firebaseAdmin.firestore.Timestamp.now(),\n }),\n },\n { merge: true },\n )\n // The lists this listing appears in query by fields derived from it (AGL-3321).\n await refreshListingQueryFields(listingRef)\n await listingRef.collection('versions').doc(String(version)).set({\n // `props` is always a list, even an empty one: install and update read a\n // version with none as one published before properties were carried.\n layout: {\n rootId: sanitized.rootId,\n nodes: sanitized.nodes,\n props: props.props,\n },\n publishedAt: now,\n })\n\n return res.status(200).json({ listingId: listingRef.id, version })\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Layout publish failed' })\n }\n}\n\nexport default publishLayoutHandler\n"],"names":["displayNameSearchFields","CANVAS_ROOT_ELEMENT_ID","checkEntitlement","createResourceUid","decodeStoredNodes","firebaseAdmin","getOrgForHost","resolveOrgPermissions","marketplacePriceRefusal","sanitizeMarketplaceDefinition","sanitizeMarketplaceProps","resolvePublisherProfile","publishPreconditionRefusal","listingSubmissionRefusal","refreshListingQueryFields","LAYOUT_SLOT_COMPONENT_ID","publishLayoutHandler","req","res","method","status","json","error","hostId","String","body","layoutId","displayName","description","category","priceUsd","Math","max","round","Number","trim","priceRefusal","authorization","headers","idToken","startsWith","slice","length","undefined","hostSnapshot","existing","orgForHost","decoded","app","auth","verifyIdToken","membership","uid","permissions","publishToMarketplace","firestore","hostRef","collection","doc","get","exists","memberRole","org","orgId","publisher","refusal","sells","layoutRef","layoutSnapshot","versionId","versionSnapshot","nodes","Object","keys","props","ok","rootId","find","id","parentId","sanitized","extraComponentIds","declaredProps","hasSlot","values","some","node","componentId","where","limit","listingRef","empty","docs","ref","version","now","FieldValue","serverTimestamp","screened","publisherOrgId","content","publisherName","pageNodes","official","set","artifactType","profileId","sourceHostId","sourceLayoutId","latestVersion","deletedAt","createdAt","updatedAt","versionHistory","arrayUnion","publishedAt","Timestamp","merge","layout","listingId","console"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,uBAAuB,QAAQ,qCAAoC;AAC5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WAG1BnC,wBAAwB2B,YAAYQ,IAAI,KACvCP,YAAYO,IAAI,MAAM;YAAEP,aAAaA,YAAYO,IAAI;QAAG,GACxDN,SAASM,IAAI,MAAM;YAAEN,UAAUA,SAASM,IAAI;QAAG;YACnDL;YACA+E,eAAef;YACfgB,WAAW;WACPjE,SAAS8C,KAAK,IAAI;YAAEoB,WAAWhB;QAAI;YACvCiB,WAAWjB;YACXkB,gBAAgB5G,cAAckD,SAAS,CAACyC,UAAU,CAACkB,UAAU,CAAC;gBAC5DpB;gBACAqB,aAAa9G,cAAckD,SAAS,CAAC6D,SAAS,CAACrB,GAAG;YACpD;YAEF;YAAEsB,OAAO;QAAK;QAEhB,gFAAgF;QAChF,MAAMvG,0BAA0B4E;QAChC,MAAMA,WAAWjC,UAAU,CAAC,YAAYC,GAAG,CAAClC,OAAOsE,UAAUU,GAAG,CAAC;YAC/D,yEAAyE;YACzE,qEAAqE;YACrEc,QAAQ;gBACN1C,QAAQI,UAAUJ,MAAM;gBACxBL,OAAOS,UAAUT,KAAK;gBACtBG,OAAOA,MAAMA,KAAK;YACpB;YACAyC,aAAapB;QACf;QAEA,OAAO7E,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEkG,WAAW7B,WAAWZ,EAAE;YAAEgB;QAAQ;IAClE,EAAE,OAAOxE,OAAO;QACdkG,QAAQlG,KAAK,CAACA;QACd,OAAOJ,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAwB;IAC/D;AACF,EAAC;AAED,eAAeN,qBAAoB"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/marketplace/src/lib/server/publish-layout.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 { holdsStampedSiteKey } from '@aglyn/aglyn/app-utils/host-permissions'\nimport { MARKETPLACE_SITE_ROLE_PRESET, marketplaceSitePermissionRefusal } from '../model/marketplace-site-permissions'\nimport { displayNameSearchFields } from '@aglyn/aglyn/app-utils/name-search'\nimport {\n CANVAS_ROOT_ELEMENT_ID,\n checkEntitlement,\n createResourceUid,\n decodeStoredNodes,\n} from '@aglyn/aglyn/server'\nimport { type PluginApiHandler } from '@aglyn/aglyn/server'\nimport { firebaseAdmin, getOrgForHost } from '@aglyn/tenant-data-admin'\nimport { resolveOrgPermissions } from '@aglyn/tenant-runtime/org-permissions'\nimport {\n marketplacePriceRefusal,\n sanitizeMarketplaceDefinition,\n} from '../model/marketplace'\nimport { sanitizeMarketplaceProps } from '../model/marketplace-props'\nimport { resolvePublisherProfile } from './publisher-profile'\nimport { publishPreconditionRefusal } from './publish-preconditions'\nimport { listingSubmissionRefusal } from './listing-screen'\nimport { refreshListingQueryFields } from './listing-query-fields'\n\n/** The node marking where a bound screen's content grafts in. */\nconst LAYOUT_SLOT_COMPONENT_ID = 'layoutSlot'\n\n/**\n * Publishes a shared layout to the marketplace (AGL-671).\n *\n * Layouts were the one design asset that could not be shared at all:\n * `publish-template` captures screens and theme only, and `layoutSlot` is\n * excluded from the marketplace allowlist as \"layout chrome\". Both are\n * addressed here — the slot is permitted for this artifact type\n * specifically, since a layout without one is chrome with nowhere to put\n * the page.\n *\n * Gates mirror template publishing exactly: org permission, host role,\n * `marketplaceSelling`, an org publisher profile, and payouts configured\n * before anything can be sold.\n */\nexport const publishLayoutHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n const hostId = String(req.body?.hostId ?? '')\n const layoutId = String(req.body?.layoutId ?? '')\n const displayName = String(req.body?.displayName ?? '')\n const description = String(req.body?.description ?? '')\n const category = String(req.body?.category ?? '')\n const priceUsd = Math.max(0, Math.round(Number(req.body?.priceUsd ?? 0)))\n if (!hostId || !layoutId || !displayName.trim()) {\n return res\n .status(400)\n .json({ error: 'Missing hostId, layoutId or displayName' })\n }\n // The price floor and ceiling, from ONE validator (AGL-2343). This door had\n // NO price validation at all: it clamped to zero and stored whatever came in,\n // so both a $1 listing that loses money on every sale and a $250,000 one were\n // publishable here. Also enforced in `publishPreconditionRefusal` below.\n const priceRefusal = marketplacePriceRefusal(priceUsd)\n if (priceRefusal) {\n return res.status(400).json({ error: priceRefusal })\n }\n const authorization = String(req.headers.authorization ?? '')\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken) return res.status(401).json({ error: 'Unauthenticated' })\n\n try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n const membership = await resolveOrgPermissions(decoded.uid, { hostId })\n if (!membership.permissions.publishToMarketplace) {\n return res.status(403).json({\n error:\n 'Your organization role does not allow publishing to the marketplace',\n })\n }\n const firestore = firebaseAdmin.app().firestore()\n\n const hostRef = firestore.collection('hosts').doc(hostId)\n const hostSnapshot = await hostRef.get()\n if (!hostSnapshot.exists) {\n return res.status(404).json({ error: 'Unknown site' })\n }\n // \"Publish a site’s items to the marketplace\" (AGL-4047): the site's stamp, else\n // the preset of the member's site role, the Admin and Editor this asked for.\n if (!holdsStampedSiteKey(hostSnapshot, decoded.uid, 'marketplace.sitePublish', MARKETPLACE_SITE_ROLE_PRESET)) {\n return res.status(403).json({ error: marketplaceSitePermissionRefusal('marketplace.sitePublish') })\n }\n\n const orgForHost = await getOrgForHost(hostId)\n const org = orgForHost?.org ?? {}\n if (!checkEntitlement(org as any, 'marketplaceSelling')) {\n return res.status(403).json({\n error: 'Publishing to the marketplace requires a Pro plan',\n })\n }\n if (!orgForHost?.orgId) {\n return res.status(409).json({ error: 'Site has no owning organization' })\n }\n\n const publisher = await resolvePublisherProfile(firestore, orgForHost.orgId)\n // Profile, payouts AND the publisher agreement, in one gate\n // (AGL-2282) — see `publishPreconditionRefusal`.\n const refusal = publishPreconditionRefusal(publisher, {\n priceUsd,\n sells: 'layouts',\n })\n if (refusal) return res.status(refusal.status).json(refusal.body)\n\n const layoutRef = hostRef.collection('layouts').doc(layoutId)\n const layoutSnapshot = await layoutRef.get()\n if (!layoutSnapshot.exists) {\n return res.status(404).json({ error: 'Unknown layout' })\n }\n const versionId = layoutSnapshot.get('versionId')\n if (!versionId) {\n return res.status(422).json({\n error: 'Publish this layout on your site first — there is no ' +\n 'published version to share',\n })\n }\n const versionSnapshot = await layoutRef\n .collection('versions')\n .doc(String(versionId))\n .get()\n // `nodes` is stored in more than one form and the besigner writes the\n // COMPRESSED one, which the Admin SDK materialises as a Node `Buffer`\n // (AGL-1395). Read raw, this was worse than the template path: the length\n // check passed on the BYTE COUNT, and the root search below walked byte\n // INDICES — byte 0 is a number, a number has no `parentId`, so `rootId`\n // resolved to `'0'` and the sanitizer built a wrapper around nothing.\n // Every besigner-edited layout was refused as empty or slotless.\n const nodes = decodeStoredNodes<Record<string, any>>(\n versionSnapshot.get('nodes'),\n )\n if (!nodes || !Object.keys(nodes).length) {\n return res.status(422).json({ error: 'Layout version has no content' })\n }\n\n // The layout properties its tree binds to (AGL-2933), from the same\n // version. A default the sanitizer refuses is cleared and its property\n // kept — see `sanitizeMarketplaceProps`.\n const props = sanitizeMarketplaceProps(versionSnapshot.get('props'))\n if (props.ok === false) {\n return res.status(422).json({ error: props.error })\n }\n\n // Layout versions have no explicit rootId. The besigner canvas roots them\n // at the same wrapper screens use, so prefer it outright; the parentless\n // search stays as the fallback for anything authored before that, and\n // matches how the renderer walks them. Preferring the wrapper also means a\n // top-level node that relies on child arrays alone — legal, see\n // `compose-layout-nodes` — can no longer win the search over the real root.\n const rootId: string =\n (nodes[CANVAS_ROOT_ELEMENT_ID] && CANVAS_ROOT_ELEMENT_ID) ||\n Object.keys(nodes).find((id) => !nodes[id]?.parentId) ||\n Object.keys(nodes)[0] ||\n ''\n const sanitized = sanitizeMarketplaceDefinition(\n { rootId, nodes },\n {\n extraComponentIds: [LAYOUT_SLOT_COMPONENT_ID],\n // A link or image bound whole to a Link or Image property travels\n // bound (AGL-2933).\n declaredProps: props.props,\n },\n )\n // `=== false` rather than `!sanitized.ok`: the compiler does not narrow\n // the union on the negated form here, and publish-template hit the same\n // thing first.\n if (sanitized.ok === false) {\n return res.status(400).json({ error: sanitized.error })\n }\n // A layout whose slot did not survive would render as chrome with the\n // page content missing — better to refuse than to publish that.\n const hasSlot = Object.values(sanitized.nodes).some(\n (node: any) => node.componentId === LAYOUT_SLOT_COMPONENT_ID,\n )\n if (!hasSlot) {\n return res.status(422).json({\n error:\n 'This layout has no content slot, so pages using it would have ' +\n 'nowhere to render',\n })\n }\n\n // One listing per source layout; re-publish bumps the version.\n const existing = await firestore\n .collection('marketplaceListings')\n .where('profileId', '==', publisher.orgId)\n .where('sourceLayoutId', '==', layoutId)\n .limit(1)\n .get()\n const listingRef = existing.empty\n ? firestore.collection('marketplaceListings').doc(createResourceUid())\n : existing.docs[0].ref\n const version = existing.empty\n ? 1\n : Number(existing.docs[0].get('latestVersion') ?? 0) + 1\n const now = firebaseAdmin.firestore.FieldValue.serverTimestamp()\n\n // The phishing screen, before anything is listed (AGL-3365).\n const screened = await listingSubmissionRefusal({\n publisherOrgId: publisher.orgId,\n content: {\n displayName,\n publisherName: publisher.displayName,\n description,\n pageNodes: sanitized.nodes,\n },\n official: decoded['staff'] === true,\n org: orgForHost.org ?? null,\n })\n if (screened) return res.status(screened.status).json(screened.body)\n\n await listingRef.set(\n {\n artifactType: 'layout',\n profileId: publisher.orgId,\n sourceHostId: hostId,\n sourceLayoutId: layoutId,\n displayName: displayName.trim(),\n // The keys a listing is searched by (AGL-3321): the template gallery's\n // marketplace shelf asks `nameTokens` on its query.\n ...displayNameSearchFields(displayName.trim()),\n ...(description.trim() && { description: description.trim() }),\n ...(category.trim() && { category: category.trim() }),\n priceUsd,\n latestVersion: version,\n deletedAt: null,\n ...(existing.empty && { createdAt: now }),\n updatedAt: now,\n versionHistory: firebaseAdmin.firestore.FieldValue.arrayUnion({\n version,\n publishedAt: firebaseAdmin.firestore.Timestamp.now(),\n }),\n },\n { merge: true },\n )\n // The lists this listing appears in query by fields derived from it (AGL-3321).\n await refreshListingQueryFields(listingRef)\n await listingRef.collection('versions').doc(String(version)).set({\n // `props` is always a list, even an empty one: install and update read a\n // version with none as one published before properties were carried.\n layout: {\n rootId: sanitized.rootId,\n nodes: sanitized.nodes,\n props: props.props,\n },\n publishedAt: now,\n })\n\n return res.status(200).json({ listingId: listingRef.id, version })\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Layout publish failed' })\n }\n}\n\nexport default publishLayoutHandler\n"],"names":["holdsStampedSiteKey","MARKETPLACE_SITE_ROLE_PRESET","marketplaceSitePermissionRefusal","displayNameSearchFields","CANVAS_ROOT_ELEMENT_ID","checkEntitlement","createResourceUid","decodeStoredNodes","firebaseAdmin","getOrgForHost","resolveOrgPermissions","marketplacePriceRefusal","sanitizeMarketplaceDefinition","sanitizeMarketplaceProps","resolvePublisherProfile","publishPreconditionRefusal","listingSubmissionRefusal","refreshListingQueryFields","LAYOUT_SLOT_COMPONENT_ID","publishLayoutHandler","req","res","method","status","json","error","hostId","String","body","layoutId","displayName","description","category","priceUsd","Math","max","round","Number","trim","priceRefusal","authorization","headers","idToken","startsWith","slice","length","undefined","existing","orgForHost","decoded","app","auth","verifyIdToken","membership","uid","permissions","publishToMarketplace","firestore","hostRef","collection","doc","hostSnapshot","get","exists","org","orgId","publisher","refusal","sells","layoutRef","layoutSnapshot","versionId","versionSnapshot","nodes","Object","keys","props","ok","rootId","find","id","parentId","sanitized","extraComponentIds","declaredProps","hasSlot","values","some","node","componentId","where","limit","listingRef","empty","docs","ref","version","now","FieldValue","serverTimestamp","screened","publisherOrgId","content","publisherName","pageNodes","official","set","artifactType","profileId","sourceHostId","sourceLayoutId","latestVersion","deletedAt","createdAt","updatedAt","versionHistory","arrayUnion","publishedAt","Timestamp","merge","layout","listingId","console"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,mBAAmB,QAAQ,0CAAyC;AAC7E,SAASC,4BAA4B,EAAEC,gCAAgC,QAAQ,2CAAuC;AACtH,SAASC,uBAAuB,QAAQ,qCAAoC;AAC5E,SACEC,sBAAsB,EACtBC,gBAAgB,EAChBC,iBAAiB,EACjBC,iBAAiB,QACZ,sBAAqB;AAE5B,SAASC,aAAa,EAAEC,aAAa,QAAQ,2BAA0B;AACvE,SAASC,qBAAqB,QAAQ,wCAAuC;AAC7E,SACEC,uBAAuB,EACvBC,6BAA6B,QACxB,0BAAsB;AAC7B,SAASC,wBAAwB,QAAQ,gCAA4B;AACrE,SAASC,uBAAuB,QAAQ,yBAAqB;AAC7D,SAASC,0BAA0B,QAAQ,6BAAyB;AACpE,SAASC,wBAAwB,QAAQ,sBAAkB;AAC3D,SAASC,yBAAyB,QAAQ,4BAAwB;AAElE,+DAA+D,GAC/D,MAAMC,2BAA2B;AAEjC;;;;;;;;;;;;;CAaC,GACD,OAAO,MAAMC,uBAAyC,OAAOC,KAAKC;iDAuBnCD;QAnBPA,WACEA,YACGA,YACAA,YACHA,YACuBA;IAR/C,IAAIA,IAAIE,MAAM,KAAK,QAAQ;QACzB,OAAOD,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAqB;IAC5D;IACA,MAAMC,SAASC,gBAAOP,YAAAA,IAAIQ,IAAI,qBAARR,UAAUM,MAAM,mBAAI;IAC1C,MAAMG,WAAWF,iBAAOP,aAAAA,IAAIQ,IAAI,qBAARR,WAAUS,QAAQ,oBAAI;IAC9C,MAAMC,cAAcH,iBAAOP,aAAAA,IAAIQ,IAAI,qBAARR,WAAUU,WAAW,oBAAI;IACpD,MAAMC,cAAcJ,iBAAOP,aAAAA,IAAIQ,IAAI,qBAARR,WAAUW,WAAW,oBAAI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LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ import { type PluginApiHandler } from '@aglyn/aglyn/server';
18
+ /**
19
+ * Publishes a site as a site starter (AGL-4049): a whole site a person picks
20
+ * in "Create site" before it exists. Captures every published page with its
21
+ * published version, the shared layout the Home page sits in — both through
22
+ * `sanitizeSiteStarterNodes`, the starter's own rule, which keeps what a real
23
+ * site is made of (its grids, cards, styles and safe interactions) where the
24
+ * portable rule the other doors use would refuse it — and the theme
25
+ * in one of its two shapes — a built-in theme with brand colors and fonts
26
+ * over it, named in the body, or the site's own full theme — into a
27
+ * `siteStarter` listing that waits for review before anyone else sees it.
28
+ *
29
+ * Gates mirror the template door exactly: the price, org permission, site
30
+ * role, `marketplaceSelling`, a publisher profile with payouts and the current
31
+ * agreement, then the phishing screen before anything is listed. One listing
32
+ * per source site, keyed on `sourceStarterHostId` (never `sourceHostId`, which
33
+ * the template, layout and theme doors share); re-publishing bumps the
34
+ * version and keeps the review verdict, as a plugin's does.
35
+ */
36
+ export declare const publishStarterHandler: PluginApiHandler;
37
+ export default publishStarterHandler;