@aglyn/plugins-marketplace 1.20.1 → 1.20.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +15 -15
- package/src/lib/components/listing-content.component.d.ts +8 -1
- package/src/lib/components/listing-content.component.js +52 -12
- package/src/lib/components/listing-content.component.js.map +1 -1
- package/src/lib/components/listing-detail-page.component.d.ts +6 -0
- package/src/lib/components/listing-detail-page.component.js +24 -4
- package/src/lib/components/listing-detail-page.component.js.map +1 -1
- package/src/lib/components/marketplace-hub.component.js +2 -0
- package/src/lib/components/marketplace-hub.component.js.map +1 -1
- package/src/lib/components/org-plugin-installs-card.component.js +67 -9
- package/src/lib/components/org-plugin-installs-card.component.js.map +1 -1
- package/src/lib/components/org-seller-panel.component.js +14 -4
- package/src/lib/components/org-seller-panel.component.js.map +1 -1
- package/src/lib/components/plugin-reviews-surface.component.js +17 -6
- package/src/lib/components/plugin-reviews-surface.component.js.map +1 -1
- package/src/lib/components/plugin-site-set-panel.component.d.ts +11 -0
- package/src/lib/components/plugin-site-set-panel.component.js +52 -9
- package/src/lib/components/plugin-site-set-panel.component.js.map +1 -1
- package/src/lib/hooks/use-starter-publish-facts.js +5 -1
- package/src/lib/hooks/use-starter-publish-facts.js.map +1 -1
- package/src/lib/model/marketplace-catalog.d.ts +40 -1
- package/src/lib/model/marketplace-catalog.js +46 -2
- package/src/lib/model/marketplace-catalog.js.map +1 -1
- package/src/lib/model/marketplace.d.ts +1 -1
- package/src/lib/model/marketplace.js +1 -1
- package/src/lib/model/marketplace.js.map +1 -1
- package/src/lib/model/starter-publish.d.ts +12 -5
- package/src/lib/model/starter-publish.js +18 -6
- package/src/lib/model/starter-publish.js.map +1 -1
- package/src/lib/server/connect.js +45 -13
- package/src/lib/server/connect.js.map +1 -1
- package/src/lib/server/starter-publish-facts.js +4 -0
- package/src/lib/server/starter-publish-facts.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/marketplace/src/lib/server/connect.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 { firebaseAdmin, getOrgForUser } from '@aglyn/tenant-data-admin'\nimport { paymentProvider } from '@aglyn/tenant-data-admin/server/payment-provider'\nimport { buildRoute, Route, type PluginApiHandler } from '@aglyn/aglyn/server'\nimport { orgAgeDays } from '@aglyn/tenant-data-admin/server/org-age'\nimport {\n MARKETPLACE_PAYOUTS_PERMISSION,\n marketplacePublisherPermissionRefusal,\n} from '../model/marketplace-publisher-permissions'\nimport { publisherPermissionVerdict } from './publisher-permissions'\nimport { applyPublisherPayoutPolicy } from './sale-risk'\n\nasync function stripe(path: string, params?: URLSearchParams) {\n const response = await fetch(`https://api.stripe.com/v1/${path}`, {\n method: params ? 'POST' : 'GET',\n headers: {\n Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,\n ...(params && {\n 'Content-Type': 'application/x-www-form-urlencoded',\n }),\n },\n ...(params && { body: params.toString() }),\n })\n const payload = await response.json()\n if (!response.ok) {\n throw new Error(payload?.error?.message ?? `Stripe ${path} failed`)\n }\n return payload\n}\n\n/**\n * Stripe Connect onboarding for marketplace publishers (AGL-46): creates an\n * Express account on first call (id stored on the profile via Admin SDK),\n * refreshes `stripeChargesEnabled` on every call, and returns an\n * account-link URL while onboarding is incomplete. 501 without Stripe env.\n */\nexport const connectHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n if (!process.env.STRIPE_SECRET_KEY) {\n return res\n .status(501)\n .json({ error: 'Payouts are not configured (STRIPE_SECRET_KEY).' })\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 firestore = firebaseAdmin.app().firestore()\n // Payouts belong to the publishing ORG (AGL-652) — the marketplace pays\n // the organization that published, not whoever set the account up.\n // Binding the payout destination asks \"Manage marketplace payouts\"\n // (`marketplace.payouts`, AGL-4047), whose default is the owner and admins\n // this asked for by role before, so nobody's access moved.\n //\n // The acting org comes from the client (AGL-861): the URL is the source of\n // truth for which workspace the seller is in, and a member can belong to\n // several. Guessing with `getOrgForUser(uid)` returned the FIRST org from\n // the reverse index, so the profile check ran against the wrong org and\n // 412'd even when the acting org's profile was fully set up. Passing the\n // requested org resolves membership for that specific org; falling back to\n // the first only when the client omits it keeps older callers working.\n const requestedOrgId =\n String((req.body as { orgId?: string } | undefined)?.orgId ?? '').trim() ||\n undefined\n const orgForUser = await getOrgForUser(decoded.uid, requestedOrgId)\n const orgId = orgForUser?.orgId\n const verdict = await publisherPermissionVerdict(\n decoded.uid,\n orgId,\n MARKETPLACE_PAYOUTS_PERMISSION,\n )\n if (!orgId || verdict !== 'granted') {\n return res.status(403).json({\n error: marketplacePublisherPermissionRefusal(\n MARKETPLACE_PAYOUTS_PERMISSION,\n ),\n reason: 'permission',\n permission: MARKETPLACE_PAYOUTS_PERMISSION,\n })\n }\n const profileRef = firestore.collection('publisherProfiles').doc(orgId)\n const profileSnapshot = await profileRef.get()\n if (!profileSnapshot.exists) {\n return res.status(412).json({\n error:\n 'Set up your publisher profile first — Marketplace → Profile.',\n })\n }\n\n let accountId = profileSnapshot.get('stripeAccountId') as\n | string\n | undefined\n if (!accountId) {\n const account = await stripe(\n 'accounts',\n new URLSearchParams({\n type: 'express',\n // Explicit capabilities (AGL-1547): without them the account's\n // abilities depend on unverified dashboard platform-profile\n // defaults, and a destination charge (`transfer_data`) requires\n // the destination to hold `transfers` — an account onboarded\n // without it takes money that can never pay out.\n 'capabilities[card_payments][requested]': 'true',\n 'capabilities[transfers][requested]': 'true',\n 'metadata[publisherOrgId]': orgId,\n ...(decoded.email ? { email: decoded.email } : {}),\n }),\n )\n accountId = account.id\n await profileRef.set(\n { stripeAccountId: accountId, stripeChargesEnabled: false },\n { merge: true },\n )\n }\n\n const account = await stripe(`accounts/${accountId}`)\n const chargesEnabled = Boolean(account?.charges_enabled)\n // Which Stripe world this account lives in (AGL-2471) — two of the three\n // poisoned production linkages were publisherProfiles, written by this\n // very route from a localhost session holding the test key. See the\n // commerce twin and `payment-provider-stripe-connect.ts` for why the retrieve above\n // is the proof and the `acct_…` string is not.\n const platformMode = await paymentProvider().resolvePlatformMode()\n // Payout readiness rides along (AGL-1547): the gate stays on\n // charges_enabled, but the profile records whether the money can\n // actually LEAVE Stripe — the live drill (AGL-1548) reads it, and a\n // seller panel can warn before the first sale strands funds.\n const payoutsEnabled = Boolean(account?.payouts_enabled)\n await profileRef.set(\n {\n stripeChargesEnabled: chargesEnabled,\n stripePayoutsEnabled: payoutsEnabled,\n // ALWAYS written, and `null` when Stripe would not say (AGL-2471).\n // Writing unconditionally is what makes re-onboarding safe: a fresh\n // `stripeAccountId` on a document that still carried the PREVIOUS\n // account's verdict would otherwise inherit it. `null` is not a\n // boolean, so the gate reads it as `mode-unverified` and refuses —\n // never a fabricated `true`.\n stripeAccountLivemode: platformMode ? platformMode === 'live' : null,\n },\n { merge: true },\n )\n const origin = req.headers.origin ?? `https://${req.headers.host}`\n const orgSnapshot = await firestore.collection('orgs').doc(orgId).get()\n const orgSlug = orgSnapshot.get('slug') as string | undefined\n // A young publisher's payouts are held (AGL-3365) — see\n // `model/publisher-risk.ts`. Here, where the account is created and\n // where the publisher comes back to it; the sale webhook applies the\n // same policy, so a publisher who never returns still ages out of it.\n // Never throws, and writes to Stripe only when the answer changes.\n await applyPublisherPayoutPolicy({\n firestore,\n publisherOrgId: orgId,\n ageDays: orgAgeDays(orgSnapshot.get('createdAt')),\n stripeKey: process.env.STRIPE_SECRET_KEY,\n })\n // Return people to the Marketplace page (AGL-861), not the retired\n // `/[orgSlug]/marketplace` surface. Stripe bakes these URLs into the\n // onboarding link, so an extra redirect hop mid-onboarding is avoidable.\n const payoutsPath = orgSlug\n ? buildRoute(Route.ORG_MARKETPLACE, { orgSlug })\n : Route.ORG_MARKETPLACE\n // A CONNECTED PUBLISHER STILL NEEDS A DOOR INTO STRIPE. The\n // commerce twin carries the full note; the shape and the reasoning are the\n // same, and the seller panel's \"Finish payout setup in Stripe\" button was\n // the surface that named a problem it could not act on.\n if (chargesEnabled) {\n if (!payoutsEnabled) {\n const fix = await stripe(\n 'account_links',\n new URLSearchParams({\n account: accountId as string,\n type: 'account_onboarding',\n refresh_url: `${origin}${payoutsPath}?connect=refresh`,\n return_url: `${origin}${payoutsPath}?connect=done`,\n }),\n )\n return res.status(200).json({\n accountId,\n chargesEnabled: true,\n payoutsEnabled,\n url: fix.url,\n })\n }\n // Best-effort, for the same reason as the twin: a missing convenience\n // link must never turn a working status check into an error.\n let dashboardUrl: string | undefined\n try {\n const login = await stripe(\n `accounts/${accountId}/login_links`,\n new URLSearchParams(),\n )\n dashboardUrl = typeof login?.url === 'string' ? login.url : undefined\n } catch (error) {\n console.error('Stripe Express dashboard link failed', error)\n }\n return res.status(200).json({\n accountId,\n chargesEnabled: true,\n payoutsEnabled,\n ...(dashboardUrl ? { dashboardUrl } : {}),\n })\n }\n\n const link = await stripe(\n 'account_links',\n new URLSearchParams({\n account: accountId as string,\n type: 'account_onboarding',\n refresh_url: `${origin}${payoutsPath}?connect=refresh`,\n return_url: `${origin}${payoutsPath}?connect=done`,\n }),\n )\n return res\n .status(200)\n .json({ accountId, chargesEnabled: false, url: link.url })\n } catch (error) {\n console.error(error)\n return res.status(502).json({ error: 'Payout setup failed' })\n }\n}\n"],"names":["firebaseAdmin","getOrgForUser","paymentProvider","buildRoute","Route","orgAgeDays","MARKETPLACE_PAYOUTS_PERMISSION","marketplacePublisherPermissionRefusal","publisherPermissionVerdict","applyPublisherPayoutPolicy","stripe","path","params","response","fetch","method","headers","Authorization","process","env","STRIPE_SECRET_KEY","body","toString","payload","json","ok","Error","error","message","connectHandler","req","res","status","authorization","String","idToken","startsWith","slice","length","undefined","decoded","app","auth","verifyIdToken","firestore","requestedOrgId","orgId","trim","orgForUser","uid","verdict","reason","permission","profileRef","collection","doc","profileSnapshot","get","exists","accountId","account","URLSearchParams","type","email","id","set","stripeAccountId","stripeChargesEnabled","merge","chargesEnabled","Boolean","charges_enabled","platformMode","resolvePlatformMode","payoutsEnabled","payouts_enabled","stripePayoutsEnabled","stripeAccountLivemode","origin","host","orgSnapshot","orgSlug","publisherOrgId","ageDays","stripeKey","payoutsPath","ORG_MARKETPLACE","fix","refresh_url","return_url","url","dashboardUrl","login","console","link"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,aAAa,EAAEC,aAAa,QAAQ,2BAA0B;AACvE,SAASC,eAAe,QAAQ,mDAAkD;AAClF,SAASC,UAAU,EAAEC,KAAK,QAA+B,sBAAqB;AAC9E,SAASC,UAAU,QAAQ,0CAAyC;AACpE,SACEC,8BAA8B,EAC9BC,qCAAqC,QAChC,gDAA4C;AACnD,SAASC,0BAA0B,QAAQ,6BAAyB;AACpE,SAASC,0BAA0B,QAAQ,iBAAa;AAExD,eAAeC,OAAOC,IAAY,EAAEC,MAAwB;IAC1D,MAAMC,WAAW,MAAMC,MAAM,CAAC,0BAA0B,EAAEH,MAAM,EAAE;QAChEI,QAAQH,SAAS,SAAS;QAC1BI,SAAS;YACPC,eAAe,CAAC,OAAO,EAAEC,QAAQC,GAAG,CAACC,iBAAiB,EAAE;WACpDR,UAAU;YACZ,gBAAgB;QAClB;OAEEA,UAAU;QAAES,MAAMT,OAAOU,QAAQ;IAAG;IAE1C,MAAMC,UAAU,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AAY,GAAGX,SAASO,YAAY,aAAa,CAAC;gBACpD;gBAEF,OAAOtD,IAAIC,MAAM,CAAC,KAAKR,IAAI,CAAC;oBAC1BmC;oBACAU,gBAAgB;oBAChBK;oBACAgB,KAAKH,IAAIG,GAAG;gBACd;YACF;YACA,sEAAsE;YACtE,6DAA6D;YAC7D,IAAIC;YACJ,IAAI;gBACF,MAAMC,QAAQ,MAAMlF,OAClB,CAAC,SAAS,EAAEiD,UAAU,YAAY,CAAC,EACnC,IAAIE;gBAEN8B,eAAe,QAAOC,yBAAAA,MAAOF,GAAG,MAAK,WAAWE,MAAMF,GAAG,GAAGnD;YAC9D,EAAE,OAAOZ,OAAO;gBACdkE,QAAQlE,KAAK,CAAC,wCAAwCA;YACxD;YACA,OAAOI,IAAIC,MAAM,CAAC,KAAKR,IAAI,CAAC;gBAC1BmC;gBACAU,gBAAgB;gBAChBK;eACIiB,eAAe;gBAAEA;YAAa,IAAI,CAAC;QAE3C;QAEA,MAAMG,OAAO,MAAMpF,OACjB,iBACA,IAAImD,gBAAgB;YAClBD,SAASD;YACTG,MAAM;YACN0B,aAAa,GAAGV,SAASO,YAAY,gBAAgB,CAAC;YACtDI,YAAY,GAAGX,SAASO,YAAY,aAAa,CAAC;QACpD;QAEF,OAAOtD,IACJC,MAAM,CAAC,KACPR,IAAI,CAAC;YAAEmC;YAAWU,gBAAgB;YAAOqB,KAAKI,KAAKJ,GAAG;QAAC;IAC5D,EAAE,OAAO/D,OAAO;QACdkE,QAAQlE,KAAK,CAACA;QACd,OAAOI,IAAIC,MAAM,CAAC,KAAKR,IAAI,CAAC;YAAEG,OAAO;QAAsB;IAC7D;AACF,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/marketplace/src/lib/server/connect.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 { firebaseAdmin, getOrgForUser } from '@aglyn/tenant-data-admin'\nimport {\n merchantAccountInOtherMode,\n merchantAccountReplacement,\n paymentProvider,\n PREVIOUS_MERCHANT_ACCOUNTS_FIELD,\n} from '@aglyn/tenant-data-admin/server/payment-provider'\nimport { buildRoute, Route, type PluginApiHandler } from '@aglyn/aglyn/server'\nimport { orgAgeDays } from '@aglyn/tenant-data-admin/server/org-age'\nimport {\n MARKETPLACE_PAYOUTS_PERMISSION,\n marketplacePublisherPermissionRefusal,\n} from '../model/marketplace-publisher-permissions'\nimport { publisherPermissionVerdict } from './publisher-permissions'\nimport { applyPublisherPayoutPolicy } from './sale-risk'\n\nasync function stripe(path: string, params?: URLSearchParams) {\n const response = await fetch(`https://api.stripe.com/v1/${path}`, {\n method: params ? 'POST' : 'GET',\n headers: {\n Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,\n ...(params && {\n 'Content-Type': 'application/x-www-form-urlencoded',\n }),\n },\n ...(params && { body: params.toString() }),\n })\n const payload = await response.json()\n if (!response.ok) {\n throw new Error(payload?.error?.message ?? `Stripe ${path} failed`)\n }\n return payload\n}\n\n/**\n * Stripe Connect onboarding for marketplace publishers (AGL-46): creates an\n * Express account on first call (id stored on the profile via Admin SDK),\n * refreshes `stripeChargesEnabled` on every call, and returns an\n * account-link URL while onboarding is incomplete. 501 without Stripe env.\n */\nexport const connectHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n if (!process.env.STRIPE_SECRET_KEY) {\n return res\n .status(501)\n .json({ error: 'Payouts are not configured (STRIPE_SECRET_KEY).' })\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 firestore = firebaseAdmin.app().firestore()\n // Payouts belong to the publishing ORG (AGL-652) — the marketplace pays\n // the organization that published, not whoever set the account up.\n // Binding the payout destination asks \"Manage marketplace payouts\"\n // (`marketplace.payouts`, AGL-4047), whose default is the owner and admins\n // this asked for by role before, so nobody's access moved.\n //\n // The acting org comes from the client (AGL-861): the URL is the source of\n // truth for which workspace the seller is in, and a member can belong to\n // several. Guessing with `getOrgForUser(uid)` returned the FIRST org from\n // the reverse index, so the profile check ran against the wrong org and\n // 412'd even when the acting org's profile was fully set up. Passing the\n // requested org resolves membership for that specific org; falling back to\n // the first only when the client omits it keeps older callers working.\n const requestedOrgId =\n String((req.body as { orgId?: string } | undefined)?.orgId ?? '').trim() ||\n undefined\n const orgForUser = await getOrgForUser(decoded.uid, requestedOrgId)\n const orgId = orgForUser?.orgId\n const verdict = await publisherPermissionVerdict(\n decoded.uid,\n orgId,\n MARKETPLACE_PAYOUTS_PERMISSION,\n )\n if (!orgId || verdict !== 'granted') {\n return res.status(403).json({\n error: marketplacePublisherPermissionRefusal(\n MARKETPLACE_PAYOUTS_PERMISSION,\n ),\n reason: 'permission',\n permission: MARKETPLACE_PAYOUTS_PERMISSION,\n })\n }\n const profileRef = firestore.collection('publisherProfiles').doc(orgId)\n const profileSnapshot = await profileRef.get()\n if (!profileSnapshot.exists) {\n return res.status(412).json({\n error:\n 'Set up your publisher profile first — Marketplace → Profile.',\n })\n }\n\n // This deployment's Stripe mode, asked first: whether the stored account\n // can be used here at all depends on it (AGL-2471).\n const platformMode = await paymentProvider().resolvePlatformMode()\n let accountId = profileSnapshot.get('stripeAccountId') as\n | string\n | undefined\n // An account from the other Stripe mode is REPLACED, never resumed: a\n // live key cannot read a test account, so resuming it failed every time.\n // The commerce twin carries the full note.\n let account: any\n let replacedAccountId: string | undefined\n if (\n accountId &&\n merchantAccountInOtherMode(\n profileSnapshot.get('stripeAccountLivemode'),\n platformMode,\n )\n ) {\n replacedAccountId = accountId\n } else if (accountId) {\n try {\n account = await stripe(`accounts/${accountId}`)\n } catch (error) {\n if (!paymentProvider().refusedAsOtherMode((error as Error)?.message)) {\n throw error\n }\n replacedAccountId = accountId\n }\n }\n if (!accountId || replacedAccountId) {\n const created = await stripe(\n 'accounts',\n new URLSearchParams({\n type: 'express',\n // Explicit capabilities (AGL-1547): without them the account's\n // abilities depend on unverified dashboard platform-profile\n // defaults, and a destination charge (`transfer_data`) requires\n // the destination to hold `transfers` — an account onboarded\n // without it takes money that can never pay out.\n 'capabilities[card_payments][requested]': 'true',\n 'capabilities[transfers][requested]': 'true',\n 'metadata[publisherOrgId]': orgId,\n ...(replacedAccountId\n ? { 'metadata[replacesAccount]': replacedAccountId }\n : {}),\n ...(decoded.email ? { email: decoded.email } : {}),\n }),\n )\n accountId = String(created.id)\n if (replacedAccountId) {\n console.warn(\n `[AGL-2471] Replacing Stripe account ${replacedAccountId} on ` +\n `publisherProfiles/${orgId}: it belongs to the other Stripe mode ` +\n `from this ${platformMode ?? 'unknown'}-mode deployment. New ` +\n `account ${accountId}.`,\n )\n await profileRef.set(\n merchantAccountReplacement({\n previousAccountIds: profileSnapshot.get(\n PREVIOUS_MERCHANT_ACCOUNTS_FIELD,\n ),\n replacedAccountId,\n newAccountId: accountId,\n }),\n { merge: true },\n )\n } else {\n await profileRef.set(\n { stripeAccountId: accountId, stripeChargesEnabled: false },\n { merge: true },\n )\n }\n account = await stripe(`accounts/${accountId}`)\n }\n\n const chargesEnabled = Boolean(account?.charges_enabled)\n // Which Stripe world this account lives in (AGL-2471) — two of the three\n // poisoned production linkages were publisherProfiles, written by this\n // very route from a localhost session holding the test key. See the\n // commerce twin and `payment-provider-stripe-connect.ts` for why the retrieve above\n // is the proof and the `acct_…` string is not.\n // Payout readiness rides along (AGL-1547): the gate stays on\n // charges_enabled, but the profile records whether the money can\n // actually LEAVE Stripe — the live drill (AGL-1548) reads it, and a\n // seller panel can warn before the first sale strands funds.\n const payoutsEnabled = Boolean(account?.payouts_enabled)\n await profileRef.set(\n {\n stripeChargesEnabled: chargesEnabled,\n stripePayoutsEnabled: payoutsEnabled,\n // ALWAYS written, and `null` when Stripe would not say (AGL-2471).\n // Writing unconditionally is what makes re-onboarding safe: a fresh\n // `stripeAccountId` on a document that still carried the PREVIOUS\n // account's verdict would otherwise inherit it. `null` is not a\n // boolean, so the gate reads it as `mode-unverified` and refuses —\n // never a fabricated `true`.\n stripeAccountLivemode: platformMode ? platformMode === 'live' : null,\n },\n { merge: true },\n )\n const origin = req.headers.origin ?? `https://${req.headers.host}`\n const orgSnapshot = await firestore.collection('orgs').doc(orgId).get()\n const orgSlug = orgSnapshot.get('slug') as string | undefined\n // A young publisher's payouts are held (AGL-3365) — see\n // `model/publisher-risk.ts`. Here, where the account is created and\n // where the publisher comes back to it; the sale webhook applies the\n // same policy, so a publisher who never returns still ages out of it.\n // Never throws, and writes to Stripe only when the answer changes.\n await applyPublisherPayoutPolicy({\n firestore,\n publisherOrgId: orgId,\n ageDays: orgAgeDays(orgSnapshot.get('createdAt')),\n stripeKey: process.env.STRIPE_SECRET_KEY,\n })\n // Return people to the Marketplace page (AGL-861), not the retired\n // `/[orgSlug]/marketplace` surface. Stripe bakes these URLs into the\n // onboarding link, so an extra redirect hop mid-onboarding is avoidable.\n const payoutsPath = orgSlug\n ? buildRoute(Route.ORG_MARKETPLACE, { orgSlug })\n : Route.ORG_MARKETPLACE\n // A CONNECTED PUBLISHER STILL NEEDS A DOOR INTO STRIPE. The\n // commerce twin carries the full note; the shape and the reasoning are the\n // same, and the seller panel's \"Finish payout setup in Stripe\" button was\n // the surface that named a problem it could not act on.\n if (chargesEnabled) {\n if (!payoutsEnabled) {\n const fix = await stripe(\n 'account_links',\n new URLSearchParams({\n account: accountId as string,\n type: 'account_onboarding',\n refresh_url: `${origin}${payoutsPath}?connect=refresh`,\n return_url: `${origin}${payoutsPath}?connect=done`,\n }),\n )\n return res.status(200).json({\n accountId,\n chargesEnabled: true,\n payoutsEnabled,\n url: fix.url,\n })\n }\n // Best-effort, for the same reason as the twin: a missing convenience\n // link must never turn a working status check into an error.\n let dashboardUrl: string | undefined\n try {\n const login = await stripe(\n `accounts/${accountId}/login_links`,\n new URLSearchParams(),\n )\n dashboardUrl = typeof login?.url === 'string' ? login.url : undefined\n } catch (error) {\n console.error('Stripe Express dashboard link failed', error)\n }\n return res.status(200).json({\n accountId,\n chargesEnabled: true,\n payoutsEnabled,\n ...(dashboardUrl ? { dashboardUrl } : {}),\n })\n }\n\n const link = await stripe(\n 'account_links',\n new URLSearchParams({\n account: accountId as string,\n type: 'account_onboarding',\n refresh_url: `${origin}${payoutsPath}?connect=refresh`,\n return_url: `${origin}${payoutsPath}?connect=done`,\n }),\n )\n return res\n .status(200)\n .json({ accountId, chargesEnabled: false, url: link.url })\n } catch (error) {\n console.error(error)\n return res.status(502).json({ error: 'Payout setup failed' })\n }\n}\n"],"names":["firebaseAdmin","getOrgForUser","merchantAccountInOtherMode","merchantAccountReplacement","paymentProvider","PREVIOUS_MERCHANT_ACCOUNTS_FIELD","buildRoute","Route","orgAgeDays","MARKETPLACE_PAYOUTS_PERMISSION","marketplacePublisherPermissionRefusal","publisherPermissionVerdict","applyPublisherPayoutPolicy","stripe","path","params","response","fetch","method","headers","Authorization","process","env","STRIPE_SECRET_KEY","body","toString","payload","json","ok","Error","error","message","connectHandler","req","res","status","authorization","String","idToken","startsWith","slice","length","undefined","decoded","app","auth","verifyIdToken","firestore","requestedOrgId","orgId","trim","orgForUser","uid","verdict","reason","permission","profileRef","collection","doc","profileSnapshot","get","exists","platformMode","resolvePlatformMode","accountId","account","replacedAccountId","refusedAsOtherMode","created","URLSearchParams","type","email","id","console","warn","set","previousAccountIds","newAccountId","merge","stripeAccountId","stripeChargesEnabled","chargesEnabled","Boolean","charges_enabled","payoutsEnabled","payouts_enabled","stripePayoutsEnabled","stripeAccountLivemode","origin","host","orgSnapshot","orgSlug","publisherOrgId","ageDays","stripeKey","payoutsPath","ORG_MARKETPLACE","fix","refresh_url","return_url","url","dashboardUrl","login","link"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,aAAa,EAAEC,aAAa,QAAQ,2BAA0B;AACvE,SACEC,0BAA0B,EAC1BC,0BAA0B,EAC1BC,eAAe,EACfC,gCAAgC,QAC3B,mDAAkD;AACzD,SAASC,UAAU,EAAEC,KAAK,QAA+B,sBAAqB;AAC9E,SAASC,UAAU,QAAQ,0CAAyC;AACpE,SACEC,8BAA8B,EAC9BC,qCAAqC,QAChC,gDAA4C;AACnD,SAASC,0BAA0B,QAAQ,6BAAyB;AACpE,SAASC,0BAA0B,QAAQ,iBAAa;AAExD,eAAeC,OAAOC,IAAY,EAAEC,MAAwB;IAC1D,MAAMC,WAAW,MAAMC,MAAM,CAAC,0BAA0B,EAAEH,MAAM,EAAE;QAChEI,QAAQH,SAAS,SAAS;QAC1BI,SAAS;YACPC,eAAe,CAAC,OAAO,EAAEC,QAAQC,GAAG,CAACC,iBAAiB,EAAE;WACpDR,UAAU;YACZ,gBAAgB;QAClB;OAEEA,UAAU;QAAES,MAAMT,OAAOU,QAAQ;IAAG;IAE1C,MAAMC,UAAU,MAAMV,SAASW,IAAI;IACnC,IAAI,CAACX,SAASY,EAAE,EAAE;;YACAF;QAAhB,MAAM,IAAIG,cAAMH,4BAAAA,iBAAAA,QAASI,KAAK,qBAAdJ,eAAgBK,OAAO,mBAAI,CAAC,OAAO,EAAEjB,KAAK,OAAO,CAAC;IACpE;IACA,OAAOY;AACT;AAEA;;;;;CAKC,GACD,OAAO,MAAMM,iBAAmC,OAAOC,KAAKC;QAS7BD;IAR7B,IAAIA,IAAIf,MAAM,KAAK,QAAQ;QACzB,OAAOgB,IAAIC,MAAM,CAAC,KAAKR,IAAI,CAAC;YAAEG,OAAO;QAAqB;IAC5D;IACA,IAAI,CAACT,Q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YAAY,GAAGX,SAASO,YAAY,aAAa,CAAC;QACpD;QAEF,OAAO7D,IACJC,MAAM,CAAC,KACPR,IAAI,CAAC;YAAEqC;YAAWiB,gBAAgB;YAAOmB,KAAKG,KAAKH,GAAG;QAAC;IAC5D,EAAE,OAAOtE,OAAO;QACd2C,QAAQ3C,KAAK,CAACA;QACd,OAAOI,IAAIC,MAAM,CAAC,KAAKR,IAAI,CAAC;YAAEG,OAAO;QAAsB;IAC7D;AACF,EAAC"}
|
|
@@ -21,6 +21,7 @@ import { siteStarterBuiltinThemeOf } from "@aglyn/aglyn/app-utils/site-starter-t
|
|
|
21
21
|
import { checkEntitlement } from "@aglyn/aglyn/server";
|
|
22
22
|
import { firebaseAdmin, getOrgForHost, isServerReleaseFlagOnForOrg } from "@aglyn/tenant-data-admin";
|
|
23
23
|
import { isRefusedIdToken } from "@aglyn/tenant-data-admin/server/id-token-refusal";
|
|
24
|
+
import { paymentProvider } from "@aglyn/tenant-data-admin/server/payment-provider";
|
|
24
25
|
import { resolveOrgPermissions } from "@aglyn/tenant-runtime/org-permissions";
|
|
25
26
|
import { starterPublishFactsAnswer, starterPublishPages } from "../model/starter-publish.js";
|
|
26
27
|
import { PUBLISHER_PROFILES, resolvePublisherProfile } from "./publisher-profile.js";
|
|
@@ -116,6 +117,9 @@ import { SITE_STARTERS_UNRELEASED } from "./starters.js";
|
|
|
116
117
|
profile: profile.exists ? profile.data() : null,
|
|
117
118
|
pages,
|
|
118
119
|
sellsAsPlatform: (publisher == null ? void 0 : publisher.sellsAsPlatform) === true,
|
|
120
|
+
// The door's own mode, so a payout account in the other Stripe mode
|
|
121
|
+
// is named as the step in the way (AGL-2471).
|
|
122
|
+
platformMode: paymentProvider().platformMode(),
|
|
119
123
|
// The apps fix each step on a screen of their own.
|
|
120
124
|
marketplacePath: null,
|
|
121
125
|
pagesPath: null
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/marketplace/src/lib/server/starter-publish-facts.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 { permissionRefusalText } from '@aglyn/aglyn/app-utils/org-permissions'\nimport { planLabelGrantingFeature } from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport { SITE_STARTER_MAX_SCREENS } from '@aglyn/aglyn/app-utils/site-starter'\nimport { siteStarterBuiltinThemeOf } from '@aglyn/aglyn/app-utils/site-starter-theme'\nimport { checkEntitlement, type PluginApiHandler } from '@aglyn/aglyn/server'\nimport { firebaseAdmin, getOrgForHost, isServerReleaseFlagOnForOrg } from '@aglyn/tenant-data-admin'\nimport { isRefusedIdToken } from '@aglyn/tenant-data-admin/server/id-token-refusal'\nimport { resolveOrgPermissions } from '@aglyn/tenant-runtime/org-permissions'\nimport type { DecodedIdToken } from 'firebase-admin/auth'\nimport { starterPublishFactsAnswer, starterPublishPages } from '../model/starter-publish'\nimport { PUBLISHER_PROFILES, resolvePublisherProfile } from './publisher-profile'\nimport { SITE_STARTERS_UNRELEASED } from './starters'\n\n/**\n * WHAT \"PUBLISH AS A STARTER\" READS BEFORE THE CLICK, ASKED OF THE SERVER\n * (AGL-4049).\n *\n * `GET /api/marketplace/starter-publish-facts?hostId=` answers\n * `StarterPublishFactsAnswer`: what the publish would capture, the built-in\n * theme the site wears as the publish body carries it, and each setup step\n * still in the way.\n *\n * The console's form works these out in the browser; the native apps ask\n * here, so what a site's built-in theme is stays one function in core\n * (`siteStarterBuiltinThemeOf`) rather than a port on each platform. It reads\n * for the same person the door would take: the workspace's \"Publish to the\n * marketplace\" (`marketplace.publish`), and the release flag, which staff\n * pass. A refusal is also how an app knows to offer nothing. The door still\n * decides: these are what it would say, read early.\n */\nexport const starterPublishFactsHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'GET') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n const hostId = String(req.query?.['hostId'] ?? '').trim()\n if (!hostId) return res.status(400).json({ error: 'Missing hostId' })\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 let decoded: DecodedIdToken\n try {\n decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n } catch (error) {\n // Only a refused credential is the caller's 401; failing to check it is\n // ours and keeps the dispatcher's 5xx.\n if (!isRefusedIdToken(error)) throw error\n return res.status(401).json({ error: 'Unauthenticated' })\n }\n try {\n const membership = await resolveOrgPermissions(decoded.uid, { hostId })\n if (!membership.orgId || !membership.permissions.publishToMarketplace) {\n return res.status(403).json({ error: permissionRefusalText('marketplace.publish') })\n }\n const orgId = membership.orgId\n if (\n decoded['staff'] !== true &&\n !(await isServerReleaseFlagOnForOrg('release_site_starters', orgId))\n ) {\n return res.status(403).json({ error: SITE_STARTERS_UNRELEASED })\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) return res.status(404).json({ error: 'Unknown site' })\n const host = hostSnapshot.data() as Record<string, unknown>\n\n // The routed pages, at most one past the most a starter may have: the\n // window the door walks, enough to say a site is past the limit.\n const routing = host['screens']\n const routedIds =\n routing && typeof routing === 'object' && !Array.isArray(routing)\n ? Object.keys(routing).slice(0, SITE_STARTER_MAX_SCREENS + 1)\n : []\n const screens = routedIds.length\n ? await firestore.getAll(...routedIds.map((id) => hostRef.collection('screens').doc(id)))\n : []\n const pages = starterPublishPages(\n routing,\n screens\n .filter((screen) => screen.exists)\n .map((screen) => ({ ...(screen.data() as Record<string, unknown>), $id: screen.id })),\n )\n\n const [orgForHost, profile, publisher] = await Promise.all([\n getOrgForHost(hostId),\n firestore.collection(PUBLISHER_PROFILES).doc(orgId).get(),\n resolvePublisherProfile(firestore, orgId),\n ])\n const answer = starterPublishFactsAnswer({\n facts: {\n plan: {\n ready: true,\n locked: !checkEntitlement((orgForHost?.org ?? {}) as any, 'marketplaceSelling'),\n ...(planLabelGrantingFeature('marketplaceSelling')\n ? { planLabel: planLabelGrantingFeature('marketplaceSelling') }\n : {}),\n },\n profile: profile.exists ? (profile.data() as Record<string, unknown>) : null,\n pages,\n sellsAsPlatform: publisher?.sellsAsPlatform === true,\n // The apps fix each step on a screen of their own.\n marketplacePath: null,\n pagesPath: null,\n },\n builtin: siteStarterBuiltinThemeOf(host),\n })\n return res.status(200).json(answer)\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Could not read this site' })\n }\n}\n\nexport default starterPublishFactsHandler\n"],"names":["permissionRefusalText","planLabelGrantingFeature","SITE_STARTER_MAX_SCREENS","siteStarterBuiltinThemeOf","checkEntitlement","firebaseAdmin","getOrgForHost","isServerReleaseFlagOnForOrg","isRefusedIdToken","resolveOrgPermissions","starterPublishFactsAnswer","starterPublishPages","PUBLISHER_PROFILES","resolvePublisherProfile","SITE_STARTERS_UNRELEASED","starterPublishFactsHandler","req","res","method","status","json","error","hostId","String","query","trim","authorization","headers","idToken","startsWith","slice","length","undefined","decoded","app","auth","verifyIdToken","membership","uid","orgId","permissions","publishToMarketplace","firestore","hostRef","collection","doc","hostSnapshot","get","exists","host","data","routing","routedIds","Array","isArray","Object","keys","screens","getAll","map","id","pages","filter","screen","$id","orgForHost","profile","publisher","Promise","all","answer","facts","plan","ready","locked","org","planLabel","sellsAsPlatform","marketplacePath","pagesPath","builtin","console"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,qBAAqB,QAAQ,yCAAwC;AAC9E,SAASC,wBAAwB,QAAQ,2CAA0C;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,CAAC,CAACC,SAAWA,OAAOf,MAAM,EAChCW,GAAG,CAAC,CAACI,SAAY,aAAMA,OAAOb,IAAI;gBAAgCc,KAAKD,OAAOH,EAAE;;QAGrF,MAAM,CAACK,YAAYC,SAASC,UAAU,GAAG,MAAMC,QAAQC,GAAG,CAAC;YACzD/D,cAAcgB;YACdoB,UAAUE,UAAU,CAAChC,oBAAoBiC,GAAG,CAACN,OAAOQ,GAAG;YACvDlC,wBAAwB6B,WAAWH;SACpC;QACD,MAAM+B,SAAS5D,0BAA0B;YACvC6D,OAAO;gBACLC,MAAM;oBACJC,OAAO;oBACPC,QAAQ,CAACtE,0BAAkB6D,8BAAAA,WAAYU,GAAG,oBAAI,CAAC,GAAW;mBACtD1E,yBAAyB,wBACzB;oBAAE2E,WAAW3E,yBAAyB;gBAAsB,IAC5D,CAAC;gBAEPiE,SAASA,QAAQlB,MAAM,GAAIkB,QAAQhB,IAAI,KAAiC;gBACxEW;gBACAgB,iBAAiBV,CAAAA,6BAAAA,UAAWU,eAAe,MAAK;gBAChD,mDAAmD;gBACnDC,iBAAiB;gBACjBC,WAAW;YACb;YACAC,SAAS7E,0BAA0B8C;QACrC;QACA,OAAOhC,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAACkD;IAC9B,EAAE,OAAOjD,OAAO;QACd4D,QAAQ5D,KAAK,CAACA;QACd,OAAOJ,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAA2B;IAClE;AACF,EAAC;AAED,eAAeN,2BAA0B"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/marketplace/src/lib/server/starter-publish-facts.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 { permissionRefusalText } from '@aglyn/aglyn/app-utils/org-permissions'\nimport { planLabelGrantingFeature } from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport { SITE_STARTER_MAX_SCREENS } from '@aglyn/aglyn/app-utils/site-starter'\nimport { siteStarterBuiltinThemeOf } from '@aglyn/aglyn/app-utils/site-starter-theme'\nimport { checkEntitlement, type PluginApiHandler } from '@aglyn/aglyn/server'\nimport { firebaseAdmin, getOrgForHost, isServerReleaseFlagOnForOrg } from '@aglyn/tenant-data-admin'\nimport { isRefusedIdToken } from '@aglyn/tenant-data-admin/server/id-token-refusal'\nimport { paymentProvider } from '@aglyn/tenant-data-admin/server/payment-provider'\nimport { resolveOrgPermissions } from '@aglyn/tenant-runtime/org-permissions'\nimport type { DecodedIdToken } from 'firebase-admin/auth'\nimport { starterPublishFactsAnswer, starterPublishPages } from '../model/starter-publish'\nimport { PUBLISHER_PROFILES, resolvePublisherProfile } from './publisher-profile'\nimport { SITE_STARTERS_UNRELEASED } from './starters'\n\n/**\n * WHAT \"PUBLISH AS A STARTER\" READS BEFORE THE CLICK, ASKED OF THE SERVER\n * (AGL-4049).\n *\n * `GET /api/marketplace/starter-publish-facts?hostId=` answers\n * `StarterPublishFactsAnswer`: what the publish would capture, the built-in\n * theme the site wears as the publish body carries it, and each setup step\n * still in the way.\n *\n * The console's form works these out in the browser; the native apps ask\n * here, so what a site's built-in theme is stays one function in core\n * (`siteStarterBuiltinThemeOf`) rather than a port on each platform. It reads\n * for the same person the door would take: the workspace's \"Publish to the\n * marketplace\" (`marketplace.publish`), and the release flag, which staff\n * pass. A refusal is also how an app knows to offer nothing. The door still\n * decides: these are what it would say, read early.\n */\nexport const starterPublishFactsHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'GET') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n const hostId = String(req.query?.['hostId'] ?? '').trim()\n if (!hostId) return res.status(400).json({ error: 'Missing hostId' })\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 let decoded: DecodedIdToken\n try {\n decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n } catch (error) {\n // Only a refused credential is the caller's 401; failing to check it is\n // ours and keeps the dispatcher's 5xx.\n if (!isRefusedIdToken(error)) throw error\n return res.status(401).json({ error: 'Unauthenticated' })\n }\n try {\n const membership = await resolveOrgPermissions(decoded.uid, { hostId })\n if (!membership.orgId || !membership.permissions.publishToMarketplace) {\n return res.status(403).json({ error: permissionRefusalText('marketplace.publish') })\n }\n const orgId = membership.orgId\n if (\n decoded['staff'] !== true &&\n !(await isServerReleaseFlagOnForOrg('release_site_starters', orgId))\n ) {\n return res.status(403).json({ error: SITE_STARTERS_UNRELEASED })\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) return res.status(404).json({ error: 'Unknown site' })\n const host = hostSnapshot.data() as Record<string, unknown>\n\n // The routed pages, at most one past the most a starter may have: the\n // window the door walks, enough to say a site is past the limit.\n const routing = host['screens']\n const routedIds =\n routing && typeof routing === 'object' && !Array.isArray(routing)\n ? Object.keys(routing).slice(0, SITE_STARTER_MAX_SCREENS + 1)\n : []\n const screens = routedIds.length\n ? await firestore.getAll(...routedIds.map((id) => hostRef.collection('screens').doc(id)))\n : []\n const pages = starterPublishPages(\n routing,\n screens\n .filter((screen) => screen.exists)\n .map((screen) => ({ ...(screen.data() as Record<string, unknown>), $id: screen.id })),\n )\n\n const [orgForHost, profile, publisher] = await Promise.all([\n getOrgForHost(hostId),\n firestore.collection(PUBLISHER_PROFILES).doc(orgId).get(),\n resolvePublisherProfile(firestore, orgId),\n ])\n const answer = starterPublishFactsAnswer({\n facts: {\n plan: {\n ready: true,\n locked: !checkEntitlement((orgForHost?.org ?? {}) as any, 'marketplaceSelling'),\n ...(planLabelGrantingFeature('marketplaceSelling')\n ? { planLabel: planLabelGrantingFeature('marketplaceSelling') }\n : {}),\n },\n profile: profile.exists ? (profile.data() as Record<string, unknown>) : null,\n pages,\n sellsAsPlatform: publisher?.sellsAsPlatform === true,\n // The door's own mode, so a payout account in the other Stripe mode\n // is named as the step in the way (AGL-2471).\n platformMode: paymentProvider().platformMode(),\n // The apps fix each step on a screen of their own.\n marketplacePath: null,\n pagesPath: null,\n },\n builtin: siteStarterBuiltinThemeOf(host),\n })\n return res.status(200).json(answer)\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Could not read this site' })\n }\n}\n\nexport default starterPublishFactsHandler\n"],"names":["permissionRefusalText","planLabelGrantingFeature","SITE_STARTER_MAX_SCREENS","siteStarterBuiltinThemeOf","checkEntitlement","firebaseAdmin","getOrgForHost","isServerReleaseFlagOnForOrg","isRefusedIdToken","paymentProvider","resolveOrgPermissions","starterPublishFactsAnswer","starterPublishPages","PUBLISHER_PROFILES","resolvePublisherProfile","SITE_STARTERS_UNRELEASED","starterPublishFactsHandler","req","res","method","status","json","error","hostId","String","query","trim","authorization","headers","idToken","startsWith","slice","length","undefined","decoded","app","auth","verifyIdToken","membership","uid","orgId","permissions","publishToMarketplace","firestore","hostRef","collection","doc","hostSnapshot","get","exists","host","data","routing","routedIds","Array","isArray","Object","keys","screens","getAll","map","id","pages","filter","screen","$id","orgForHost","profile","publisher","Promise","all","answer","facts","plan","ready","locked","org","planLabel","sellsAsPlatform","platformMode","marketplacePath","pagesPath","builtin","console"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,qBAAqB,QAAQ,yCAAwC;AAC9E,SAASC,wBAAwB,QAAQ,2CAA0C;AACnF,SAASC,wBAAwB,QAAQ,sCAAqC;AAC9E,SAASC,yBAAyB,QAAQ,4CAA2C;AACrF,SAASC,gBA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