@extenshi/pay 0.11.0 → 0.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +11 -1
- package/dist/core/extenshi-pay.d.ts +1 -1
- package/dist/core/extenshi-pay.d.ts.map +1 -1
- package/dist/core.d.mts +6 -3
- package/dist/core.d.ts +6 -3
- package/dist/core.js +26 -8
- package/dist/core.js.map +1 -1
- package/dist/core.mjs +26 -9
- package/dist/core.mjs.map +1 -1
- package/dist/extenshi-pay-lite.js +25 -8
- package/dist/extenshi-pay-lite.js.map +1 -1
- package/dist/extenshi-pay-lite.min.js +3 -3
- package/dist/extenshi-pay-lite.min.js.map +1 -1
- package/dist/extenshi-pay-lite.mjs +25 -8
- package/dist/extenshi-pay-lite.mjs.map +1 -1
- package/dist/extenshi-pay.cjs.js +28 -8
- package/dist/extenshi-pay.cjs.js.map +1 -1
- package/dist/extenshi-pay.d.ts.map +1 -1
- package/dist/extenshi-pay.js +28 -8
- package/dist/extenshi-pay.js.map +1 -1
- package/dist/extenshi-pay.min.js +3 -3
- package/dist/extenshi-pay.min.js.map +1 -1
- package/dist/extenshi-pay.min.mjs +3 -3
- package/dist/extenshi-pay.min.mjs.map +1 -1
- package/dist/extenshi-pay.mjs +28 -9
- package/dist/extenshi-pay.mjs.map +1 -1
- package/dist/index.d.mts +6 -3
- package/dist/index.d.ts +6 -3
- package/dist/lite.d.mts +4 -2
- package/dist/lite.d.ts +4 -2
- package/dist/payment/entitlement.d.ts.map +1 -1
- package/dist/paywall.js +2 -2
- package/dist/paywall.js.map +1 -1
- package/dist/paywall.mjs +2 -2
- package/dist/paywall.mjs.map +1 -1
- package/dist/types/contract.d.ts +1 -0
- package/dist/types/contract.d.ts.map +1 -1
- package/dist/types/entitlement.d.ts +2 -0
- package/dist/types/entitlement.d.ts.map +1 -1
- package/dist/version.d.ts +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"extenshi-pay.min.mjs","sources":["../src/types/contract.ts","../src/types/errors.ts","../src/core/identity.ts","../src/api/mock.ts","../src/api/pay-api.ts","../src/utils/logger.ts","../src/api/transport.ts","../src/payment/checkout.ts","../src/payment/cloud-backup.ts","../src/payment/features.ts","../src/payment/signature.ts","../src/payment/trial.ts","../src/payment/entitlement.ts","../src/core/storage.ts","../src/payment/recovery.ts","../src/types/config.ts","../src/version.ts","../src/core/locale.ts","../src/core/config.ts","../src/core/event-emitter.ts","../src/paywall/i18n.ts","../src/payment/withdrawal-waiver.ts","../src/core/extenshi-pay.ts","../src/paywall/seller-details.ts","../src/paywall/license-panel.ts","../src/paywall/billing-profile-picker.ts","../src/paywall/icon.ts","../src/paywall/format.ts","../src/paywall/strings.ts","../../extension_templates/paywall-templates/fullscreen/template.html","../src/paywall/templates.ts","../../extension_templates/paywall-templates/modal/template.html","../../extension_templates/paywall-templates/inline/template.html","../../extension_templates/paywall-templates/sidebar/template.html","../../extension_templates/paywall-templates/minimal/template.html","../src/paywall/renderer.ts","../src/extenshi-pay.ts"],"sourcesContent":["/**\n * Wire contract between the SDK and catalog-bff `pay.*`.\n *\n * SOURCE OF TRUTH: `shared-types/pay.ts` in the extenshi.io monorepo. The SDK\n * ships with zero runtime dependencies and must not import that workspace, so\n * the types and constants it needs are copied here under identical names.\n * `canonicalJson` is copied VERBATIM: the BFF signs its output and the SDK\n * verifies it, so both sides must produce byte-identical strings\n * (pinned by tests/unit/canonical-json.test.ts). When `shared-types/pay.ts`\n * changes, mirror the change here.\n */\n\n/** Bumped only when an older SDK could misread the response. */\nexport const PAY_CONTRACT_VERSION = 1\n\nexport const PAY_GATEWAYS = ['stripe', 'paddle', 'lemonsqueezy'] as const\nexport type PayGatewayId = (typeof PAY_GATEWAYS)[number]\n\n// ─── Publishable key ────────────────────────────────────────────────────────\n\n/**\n * The only credential an extension bundle carries. It is public by\n * construction (anyone can unzip the .crx), so it must grant nothing beyond\n * \"read this project's offer\" and \"start a checkout for this project\".\n */\nexport const PAY_PUBLISHABLE_KEY_PREFIX = 'pk_ext_'\nexport const PAY_PUBLISHABLE_KEY_HEX_LENGTH = 32\nconst PUBLISHABLE_KEY_RE = new RegExp(\n\t`^${PAY_PUBLISHABLE_KEY_PREFIX}[0-9a-f]{${PAY_PUBLISHABLE_KEY_HEX_LENGTH}}$`,\n)\n\nexport function isPayPublishableKey(value: unknown): value is string {\n\treturn typeof value === 'string' && PUBLISHABLE_KEY_RE.test(value)\n}\n\n// ─── Offers ─────────────────────────────────────────────────────────────────\n\nexport const PAY_OFFER_KINDS = ['one_time', 'subscription', 'lifetime'] as const\nexport type PayOfferKind = (typeof PAY_OFFER_KINDS)[number]\n\nexport const PAY_OFFER_INTERVALS = ['month', 'year'] as const\nexport type PayOfferInterval = (typeof PAY_OFFER_INTERVALS)[number]\n\n/** ISO-4217 lowercase, matching what every gateway returns. */\nexport const PAY_CURRENCIES = ['usd', 'eur', 'gbp'] as const\nexport type PayCurrency = (typeof PAY_CURRENCIES)[number]\n\n/** `sku` is author-chosen and stable; it is what `requireFeature()` keys on. */\nexport const PAY_SKU_RE = /^[a-z0-9][a-z0-9_-]{1,39}$/\n\n// ─── Projection ─────────────────────────────────────────────────────────────\n\n/**\n * active — paid and not expired\n * grace — subscription past_due: keep access for a short window so a card\n * hiccup does not lock a paying user out mid-session\n * expired — was active, no longer is\n * none — never had it\n */\nexport const PAY_ENTITLEMENT_STATUSES = ['active', 'grace', 'expired', 'none'] as const\nexport type PayEntitlementStatus = (typeof PAY_ENTITLEMENT_STATUSES)[number]\n\n// ─── SDK-facing DTOs (the `pay.*` tRPC contract) ────────────────────────────\n\nexport interface PayOfferDto {\n\tsku: string\n\tkind: PayOfferKind\n\tinterval: PayOfferInterval | null\n\tamountMinor: number\n\tcurrency: PayCurrency\n\ttitle: string\n\tdescription: string | null\n\tfeatures: string[]\n}\n\nexport interface PayOfferResponse {\n\t/** Optional during rolling upgrades; never infer this from the project name. */\n\tseller?: PaySellerPublic | null\n\n\tv: typeof PAY_CONTRACT_VERSION\n\tprojectName: string\n\tprovider: PayGatewayId\n\t/** False while the seller cannot take money; the SDK renders the offer read-only. */\n\tcheckoutEnabled: boolean\n\t/** Optional for older servers; show recovery only when explicitly enabled. */\n\trecoveryEnabled?: boolean\n\toffers: PayOfferDto[]\n\t/** Base64 Ed25519 public key for `SignedEntitlement.signature`; null when unsigned. */\n\tentitlementPublicKey: string | null\n\t/**\n\t * The language the offers' text is in when the seller translated them\n\t * (it. 13 T10 L2); absent from older servers and for single-language offers.\n\t */\n\tlocale?: string\n\t/**\n\t * Set when the paywall must show an unticked withdrawal-waiver checkbox and\n\t * send the accepted `version` with `createCheckout`. Null when the seller\n\t * attested the extension is not distributed in the EEA/UK; absent from\n\t * older servers (the SDK then shows no checkbox).\n\t */\n\twithdrawalWaiver?: PayWithdrawalWaiver | null\n}\n\n/**\n * Version of the buyer-facing withdrawal waiver text the paywall shows (EU/EEA\n * digital content, Directive 2011/83/EU art. 16(m); UK CCR 2013 reg. 37). The\n * text itself lives in the SDK dictionary under the same version; bump both\n * together so a recorded consent always names the words the buyer saw.\n */\nexport const PAY_WITHDRAWAL_WAIVER_VERSION = '2026-10-v1'\n\nexport interface PayWithdrawalWaiver {\n\tversion: string\n}\n\nexport interface PayEntitlementItem {\n\t/** Optional for old signed caches and older servers. */\n\ttitle?: string\n\tkind?: PayOfferKind\n\tsubscriptions?: Array<{\n\t\tstatus: string\n\t\tcancelAtPeriodEnd: boolean\n\t\tcurrentPeriodEnd: string | null\n\t}>\n\n\tsku: string\n\tstatus: PayEntitlementStatus\n\t/** ISO timestamp; null for lifetime / one-time grants. */\n\texpiresAt: string | null\n\tfeatures: string[]\n}\n\n/**\n * The installation's free trial on the server clock: one per installation per application,\n * started at its first license read. Absent when the application has no trial.\n */\nexport interface PayTrial {\n\t/** ISO time of the first license read while the application had a trial. */\n\tstartedAt: string\n\t/** ISO `startedAt` plus the application's current trial length. */\n\tendsAt: string\n}\n\nexport interface PayEntitlementPayload {\n\tv: typeof PAY_CONTRACT_VERSION\n\t/** Signed application scope; prevents moving a grant to another application. */\n\tpublishableKey: string\n\tendUserRef: string\n\tentitlements: PayEntitlementItem[]\n\t/** ISO timestamp the projection was computed at; the SDK uses it for cache age. */\n\tissuedAt: string\n\t/** Optional: only for an application with a trial, and absent from older servers. */\n\ttrial?: PayTrial\n\t/** Optional: seconds of offline access after `issuedAt`; absent from older servers (48 hours). */\n\tofflineSeconds?: number\n}\n\nexport interface SignedEntitlement {\n\tpayload: PayEntitlementPayload\n\t/** Base64 Ed25519 signature over the canonical JSON of `payload`; null when the server has no key. */\n\tsignature: string | null\n\talg: 'ed25519' | null\n}\n\nexport type PayCheckoutClaim =\n\t| { state: 'pending' }\n\t| { state: 'complete'; entitlement: SignedEntitlement }\n\t| { state: 'expired' }\n\t| { state: 'canceled' }\n\nexport interface PayCheckoutSession {\n\turl: string\n\tsessionId: string\n\t/** ISO timestamp. */\n\texpiresAt: string\n}\n\n/**\n * The `endUserRef` an SDK mints on first run and keeps in `chrome.storage`.\n * Opaque, random, never derived from anything identifying.\n */\nexport const PAY_END_USER_REF_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i\n\n/** Typed error codes the BFF throws; dojo and the SDK match on `cause.code`. */\nexport const PAY_ERRORS = {\n\tSELLER_NOT_CONNECTED: 'PAY_SELLER_NOT_CONNECTED',\n\tSELLER_NOT_ACTIVE: 'PAY_SELLER_NOT_ACTIVE',\n\tAGREEMENT_REQUIRED: 'PAY_AGREEMENT_REQUIRED',\n\tOFFER_NOT_FOUND: 'PAY_OFFER_NOT_FOUND',\n\tOFFER_LIMIT: 'PAY_OFFER_LIMIT',\n\tPRICE_TOO_LOW: 'PAY_PRICE_TOO_LOW',\n\tGATEWAY_UNAVAILABLE: 'PAY_GATEWAY_UNAVAILABLE',\n\tRATE_LIMITED: 'PAY_RATE_LIMITED',\n\tINVALID_KEY: 'PAY_INVALID_KEY',\n\tWITHDRAWAL_WAIVER_REQUIRED: 'PAY_WITHDRAWAL_WAIVER_REQUIRED',\n} as const\nexport type PayErrorCode = (typeof PAY_ERRORS)[keyof typeof PAY_ERRORS]\n\n/**\n * Canonical JSON for signing: keys sorted recursively, no whitespace. Both\n * the BFF (sign) and the SDK (verify) must produce byte-identical output for\n * the same payload, so the rule lives in the shared contract.\n */\nexport function canonicalJson(value: unknown): string {\n\tif (value === null || typeof value !== 'object') return JSON.stringify(value)\n\tif (Array.isArray(value)) return `[${value.map((item) => canonicalJson(item)).join(',')}]`\n\tconst entries = Object.entries(value as Record<string, unknown>)\n\t\t.filter(([, v]) => v !== undefined)\n\t\t.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n\treturn `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonicalJson(v)}`).join(',')}}`\n}\n\nexport interface PayRestoreSessionResponse {\n\tsessionId: string\n\texpiresAt: string\n\turl: string\n}\n/**\n * `storage`: the buyer turns on the cloud copy of the extension's settings. The\n * hosted page shows the storage disclosure; the claim records consent. Additive:\n * a session without a purpose is a plain restore.\n */\nexport const PAY_RESTORE_PURPOSES = ['restore', 'storage'] as const\nexport type PayRestorePurpose = (typeof PAY_RESTORE_PURPOSES)[number]\n\n/**\n * Outcome for the cloud copy of settings, present in a complete claim only when\n * the application offers it. A token is returned once; a retried claim rotates it.\n */\nexport type PayStorageGrant =\n\t| { state: 'granted'; token: string }\n\t| { state: 'unavailable'; reason: 'NO_CONSENT' | 'LICENSE_REQUIRED' }\n\n/** From `shared-types/storage.ts`: `est_` + 32 random bytes, base64url. */\nexport const STORAGE_TOKEN_RE = /^est_[A-Za-z0-9_-]{43}$/\n\nexport type PayRestoreClaimResponse =\n\t| { state: 'pending' }\n\t| { state: 'complete'; endUserRef: string; entitlement: SignedEntitlement; storage?: PayStorageGrant }\n\n/** A project-scoped billing profile; provider identifiers are never exposed. */\nexport interface PayPortalAccount {\n\tid: string\n\tlabel: string\n\tcreatedAt: string\n\tsubscriptions: Array<{\n\t\ttitle: string\n\t\tstatus: string\n\t\tcancelAtPeriodEnd: boolean\n\t\tcurrentPeriodEnd: string | null\n\t}>\n}\n\nexport interface PayPortalResponse {\n\turl: string | null\n\t/** Present when the buyer must choose among multiple billing profiles. */\n\taccounts?: PayPortalAccount[]\n}\n\n/** Public author-provided contact details. Not a claim of identity verification. */\nexport interface PaySellerPublic {\n\tdisplayName: string\n\t/** HTTPS support page or plain email address. */\n\tsupportUrl: string\n\ttermsUrl: string | null\n\t/** Optional for older servers: refunds section of the license terms. */\n\trefundPolicyUrl?: string | null\n}\n","export const ERROR_CODES = {\n\tINVALID_CONFIG: 'INVALID_CONFIG',\n\tINVALID_REQUEST: 'INVALID_REQUEST',\n\tNETWORK_ERROR: 'NETWORK_ERROR',\n\tTIMEOUT: 'TIMEOUT',\n\tVERIFICATION_UNAVAILABLE: 'VERIFICATION_UNAVAILABLE',\n\tINVALID_RESPONSE: 'INVALID_RESPONSE',\n\tRATE_LIMITED: 'RATE_LIMITED',\n\tINVALID_KEY: 'INVALID_KEY',\n\tSELLER_NOT_ACTIVE: 'SELLER_NOT_ACTIVE',\n\tOFFER_NOT_FOUND: 'OFFER_NOT_FOUND',\n\tGATEWAY_UNAVAILABLE: 'GATEWAY_UNAVAILABLE',\n\tCHECKOUT_UNAVAILABLE: 'CHECKOUT_UNAVAILABLE',\n\tPAYWALL_UNAVAILABLE: 'PAYWALL_UNAVAILABLE',\n\tWITHDRAWAL_WAIVER_REQUIRED: 'WITHDRAWAL_WAIVER_REQUIRED',\n\tUNKNOWN: 'UNKNOWN',\n} as const\n\nexport type ErrorCode = (typeof ERROR_CODES)[keyof typeof ERROR_CODES]\n\nexport interface ExtenshiPayErrorOptions {\n\tretryAfterSec?: number\n\thttpStatus?: number\n\tcause?: unknown\n}\n\nexport class ExtenshiPayError extends Error {\n\treadonly code: ErrorCode\n\treadonly retryAfterSec: number | undefined\n\treadonly httpStatus: number | undefined\n\treadonly cause: unknown\n\n\tconstructor(code: ErrorCode, message: string, options: ExtenshiPayErrorOptions = {}) {\n\t\tsuper(message)\n\t\tthis.name = 'ExtenshiPayError'\n\t\tthis.code = code\n\t\tthis.retryAfterSec = options.retryAfterSec\n\t\tthis.httpStatus = options.httpStatus\n\t\tthis.cause = options.cause\n\t}\n\n\tstatic from(error: unknown, fallback: ErrorCode = ERROR_CODES.UNKNOWN): ExtenshiPayError {\n\t\tif (error instanceof ExtenshiPayError) return error\n\t\tconst message = error instanceof Error ? error.message : String(error)\n\t\treturn new ExtenshiPayError(fallback, message, { cause: error })\n\t}\n}\n","/**\n * `endUserRef` — the only identity the SDK has.\n *\n * A random UUID minted on first run and kept in the SDK's storage namespace.\n * It is never derived from anything identifying (no fingerprint, no e-mail,\n * no extension-supplied user id) and remains the installation identifier. Explicit recovery also sends a\n * random session ID and proof; it never derives identity from an email locally.\n */\n\nimport { PAY_END_USER_REF_RE } from '../types/contract.js'\nimport { ERROR_CODES, ExtenshiPayError } from '../types/errors.js'\nimport type { StorageAdapter } from './storage.js'\n\nexport const END_USER_REF_STORAGE_KEY = 'extenshi-pay:endUserRef'\n\nexport function mintEndUserRef(): string {\n\tconst cryptoApi = (globalThis as { crypto?: Crypto }).crypto\n\tif (!cryptoApi) {\n\t\tthrow new ExtenshiPayError(ERROR_CODES.UNKNOWN, 'Web Crypto is not available in this context')\n\t}\n\tif (typeof cryptoApi.randomUUID === 'function') return cryptoApi.randomUUID()\n\tconst bytes = cryptoApi.getRandomValues(new Uint8Array(16))\n\tbytes[6] = (bytes[6] & 0x0f) | 0x40\n\tbytes[8] = (bytes[8] & 0x3f) | 0x80\n\tconst hex = Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('')\n\treturn `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`\n}\n\nexport async function getOrCreateEndUserRef(storage: StorageAdapter): Promise<string> {\n\tconst existing = await storage.get(END_USER_REF_STORAGE_KEY)\n\tif (typeof existing === 'string' && PAY_END_USER_REF_RE.test(existing)) return existing\n\tconst ref = mintEndUserRef()\n\tawait storage.set(END_USER_REF_STORAGE_KEY, ref)\n\treturn ref\n}\n","/**\n * In-memory stand-in for the BFF, used when `mock: true`. Lets an extension be\n * developed with no backend: offers and entitlements come from `mockData`, a\n * mock checkout completes after `claimAfterPolls` polls and grants the SKU.\n */\n\nimport { mintEndUserRef } from '../core/identity.js'\nimport type { MockData } from '../types/config.js'\nimport {\n\tPAY_CONTRACT_VERSION,\n\tPAY_WITHDRAWAL_WAIVER_VERSION,\n\ttype PayCheckoutClaim,\n\ttype PayEntitlementItem,\n\ttype PayOfferDto,\n\ttype PayOfferResponse,\n\ttype PaySellerPublic,\n\ttype PayTrial,\n\ttype PayWithdrawalWaiver,\n\ttype SignedEntitlement,\n} from '../types/contract.js'\nimport type { WithdrawalWaiverConsent } from '../types/entitlement.js'\nimport { ERROR_CODES, ExtenshiPayError } from '../types/errors.js'\nimport type { ProcedureKind, Transport } from './transport.js'\n\ntype SessionState = 'open' | 'complete' | 'canceled' | 'expired'\n\ninterface MockSession {\n\tsku: string\n\tpolls: number\n\tstate: SessionState\n\t/** What `createCheckout` received, for inspecting the consent in dev/tests. */\n\twithdrawalWaiver: WithdrawalWaiverConsent | null\n}\n\nconst DAY_MS = 24 * 60 * 60 * 1000\n\n/** Accepts the same optional `withdrawalWaiver` input as the BFF; anything else is no consent. */\nfunction mockConsent(value: unknown): WithdrawalWaiverConsent | null {\n\tconst consent = value as Partial<WithdrawalWaiverConsent> | null | undefined\n\treturn consent && typeof consent.version === 'string' && consent.accepted === true\n\t\t? { version: consent.version, accepted: true }\n\t\t: null\n}\n\nexport class MockTransport implements Transport {\n\tprivate entitlements: PayEntitlementItem[]\n\tprivate readonly offers: PayOfferDto[]\n\tprivate readonly projectName: string\n\tprivate readonly checkoutEnabled: boolean\n\tprivate readonly claimAfterPolls: number\n\tprivate readonly withdrawalWaiver: PayWithdrawalWaiver | null\n\tprivate readonly seller: PaySellerPublic | null | undefined\n\tprivate trial: PayTrial | null\n\treadonly sessions = new Map<string, MockSession>()\n\n\tconstructor(data: MockData = {}) {\n\t\tthis.entitlements = [...(data.entitlements ?? [])]\n\t\tthis.offers = [...(data.offers ?? [])]\n\t\tthis.projectName = data.projectName ?? 'Mock project'\n\t\tthis.checkoutEnabled = data.checkoutEnabled ?? true\n\t\tthis.claimAfterPolls = data.claimAfterPolls ?? 1\n\t\tthis.withdrawalWaiver =\n\t\t\tdata.withdrawalWaiver === undefined ? { version: PAY_WITHDRAWAL_WAIVER_VERSION } : data.withdrawalWaiver\n\t\tthis.seller = data.seller\n\t\tthis.trial = null\n\t\tif (data.trial) this.setTrial(data.trial.days, data.trial.startedAt)\n\t}\n\n\tasync call<T>(procedure: string, _kind: ProcedureKind, input: Record<string, unknown>): Promise<T> {\n\t\tswitch (procedure) {\n\t\t\tcase 'pay.getOffer':\n\t\t\t\treturn this.offerResponse() as T\n\t\t\tcase 'pay.createCheckout':\n\t\t\t\treturn this.createCheckout(String(input.sku), mockConsent(input.withdrawalWaiver)) as T\n\t\t\tcase 'pay.claimSession':\n\t\t\t\treturn this.claim(\n\t\t\t\t\tString(input.sessionId),\n\t\t\t\t\tString(input.endUserRef),\n\t\t\t\t\tString(input.publishableKey),\n\t\t\t\t) as T\n\t\t\tcase 'pay.getEntitlement':\n\t\t\t\treturn this.envelope(String(input.endUserRef), String(input.publishableKey)) as T\n\t\t\tcase 'pay.getPortalUrl':\n\t\t\t\treturn { url: this.entitlements.length > 0 ? 'https://mock.extenshi.io/portal' : null } as T\n\t\t\tdefault:\n\t\t\t\tthrow new ExtenshiPayError(ERROR_CODES.INVALID_REQUEST, `Unknown procedure ${procedure}`)\n\t\t}\n\t}\n\n\t/** Test/dev helpers. */\n\tsetEntitlements(items: PayEntitlementItem[]): void {\n\t\tthis.entitlements = [...items]\n\t}\n\n\t/** Previews a server trial of `days` from `startedAt` (default now); `null` removes it. */\n\tsetTrial(days: number | null, startedAt: string = new Date().toISOString()): void {\n\t\tconst start = Date.parse(startedAt)\n\t\tthis.trial =\n\t\t\tdays === null || !Number.isFinite(start)\n\t\t\t\t? null\n\t\t\t\t: { startedAt: new Date(start).toISOString(), endsAt: new Date(start + days * DAY_MS).toISOString() }\n\t}\n\n\tcancelSession(sessionId: string): void {\n\t\tconst session = this.sessions.get(sessionId)\n\t\tif (session) session.state = 'canceled'\n\t}\n\n\texpireSession(sessionId: string): void {\n\t\tconst session = this.sessions.get(sessionId)\n\t\tif (session) session.state = 'expired'\n\t}\n\n\tprivate offerResponse(): PayOfferResponse {\n\t\treturn {\n\t\t\tv: PAY_CONTRACT_VERSION,\n\t\t\tprojectName: this.projectName,\n\t\t\tprovider: 'stripe',\n\t\t\tcheckoutEnabled: this.checkoutEnabled && this.offers.length > 0,\n\t\t\toffers: [...this.offers],\n\t\t\tentitlementPublicKey: null,\n\t\t\twithdrawalWaiver: this.withdrawalWaiver ? { ...this.withdrawalWaiver } : null,\n\t\t\t...(this.seller !== undefined && { seller: this.seller ? { ...this.seller } : null }),\n\t\t}\n\t}\n\n\tprivate createCheckout(sku: string, withdrawalWaiver: WithdrawalWaiverConsent | null) {\n\t\tif (!this.checkoutEnabled) {\n\t\t\tthrow new ExtenshiPayError(ERROR_CODES.SELLER_NOT_ACTIVE, 'Mock seller cannot take payments')\n\t\t}\n\t\tif (!this.offers.some((offer) => offer.sku === sku)) {\n\t\t\tthrow new ExtenshiPayError(ERROR_CODES.OFFER_NOT_FOUND, `Unknown mock offer ${sku}`)\n\t\t}\n\t\tconst sessionId = mintEndUserRef()\n\t\tthis.sessions.set(sessionId, { sku, polls: 0, state: 'open', withdrawalWaiver })\n\t\treturn {\n\t\t\turl: `https://mock.extenshi.io/checkout/${sessionId}`,\n\t\t\tsessionId,\n\t\t\texpiresAt: new Date(Date.now() + 30 * 60 * 1000).toISOString(),\n\t\t}\n\t}\n\n\tprivate claim(sessionId: string, endUserRef: string, publishableKey: string): PayCheckoutClaim {\n\t\tconst session = this.sessions.get(sessionId)\n\t\tif (!session) throw new ExtenshiPayError(ERROR_CODES.CHECKOUT_UNAVAILABLE, 'Unknown checkout session')\n\t\tif (session.state === 'canceled') return { state: 'canceled' }\n\t\tif (session.state === 'expired') return { state: 'expired' }\n\t\tif (session.state === 'open') {\n\t\t\tsession.polls += 1\n\t\t\tif (session.polls <= this.claimAfterPolls) return { state: 'pending' }\n\t\t\tsession.state = 'complete'\n\t\t\tthis.grant(session.sku)\n\t\t}\n\t\treturn { state: 'complete', entitlement: this.envelope(endUserRef, publishableKey) }\n\t}\n\n\tprivate grant(sku: string): void {\n\t\tconst offer = this.offers.find((o) => o.sku === sku)\n\t\tconst expiresAt =\n\t\t\toffer?.kind === 'subscription'\n\t\t\t\t? new Date(Date.now() + (offer.interval === 'year' ? 365 : 30) * DAY_MS).toISOString()\n\t\t\t\t: null\n\t\tthis.entitlements = [\n\t\t\t...this.entitlements.filter((item) => item.sku !== sku),\n\t\t\t{\n\t\t\t\tsku,\n\t\t\t\ttitle: offer?.title,\n\t\t\t\tkind: offer?.kind,\n\t\t\t\tstatus: 'active',\n\t\t\t\texpiresAt,\n\t\t\t\tfeatures: offer?.features ?? [],\n\t\t\t},\n\t\t]\n\t}\n\n\tprivate envelope(endUserRef: string, publishableKey: string): SignedEntitlement {\n\t\treturn {\n\t\t\tpayload: {\n\t\t\t\tv: PAY_CONTRACT_VERSION,\n\t\t\t\tpublishableKey,\n\t\t\t\tendUserRef,\n\t\t\t\tentitlements: [...this.entitlements],\n\t\t\t\tissuedAt: new Date().toISOString(),\n\t\t\t\t...(this.trial ? { trial: { ...this.trial } } : {}),\n\t\t\t},\n\t\t\tsignature: null,\n\t\t\talg: null,\n\t\t}\n\t}\n}\n","/** Typed wrapper over the SDK-facing `pay.*` procedures. Nothing else is ever called. */\n\nimport type {\n\tPayCheckoutClaim,\n\tPayCheckoutSession,\n\tPayOfferResponse,\n\tPayPortalResponse,\n\tPayRestoreClaimResponse,\n\tPayRestorePurpose,\n\tPayRestoreSessionResponse,\n\tSignedEntitlement,\n} from '../types/contract.js'\nimport type { WithdrawalWaiverConsent } from '../types/entitlement.js'\nimport type { Transport } from './transport.js'\n\nexport class PayApi {\n\tconstructor(\n\t\tprivate readonly transport: Transport,\n\t\tprivate readonly publishableKey: string,\n\t) {}\n\n\t/**\n\t * `locale` opens the hosted recovery page (and its email) in the user's language.\n\t * `purpose` is sent only for `storage`: a plain restore keeps the request older\n\t * BFFs know, and their non-strict zod input strips the key anyway.\n\t */\n\tcreateRestoreSession(\n\t\tclaimChallenge: string,\n\t\tlocale?: string | null,\n\t\tpurpose?: PayRestorePurpose,\n\t): Promise<PayRestoreSessionResponse> {\n\t\treturn this.transport.call('pay.createRestoreSession', 'mutation', {\n\t\t\tpublishableKey: this.publishableKey,\n\t\t\tclaimChallenge,\n\t\t\t...(locale ? { locale } : {}),\n\t\t\t...(purpose === 'storage' ? { purpose } : {}),\n\t\t})\n\t}\n\n\tclaimRestoreSession(sessionId: string, claimSecret: string): Promise<PayRestoreClaimResponse> {\n\t\treturn this.transport.call('pay.claimRestoreSession', 'mutation', {\n\t\t\tpublishableKey: this.publishableKey,\n\t\t\tsessionId,\n\t\t\tclaimSecret,\n\t\t})\n\t}\n\n\tgetOffer(locale?: string | null): Promise<PayOfferResponse> {\n\t\treturn this.transport.call('pay.getOffer', 'query', {\n\t\t\tpublishableKey: this.publishableKey,\n\t\t\tlocale: locale ?? undefined,\n\t\t})\n\t}\n\n\t/**\n\t * `withdrawalWaiver` is sent only when given. Older BFFs parse the input with\n\t * a non-strict zod object, which strips the unknown key, so it is safe there.\n\t * Plain-JS callers passing anything but `accepted: true` send no consent.\n\t */\n\tcreateCheckout(\n\t\tsku: string,\n\t\tendUserRef: string,\n\t\tlocale?: string | null,\n\t\twithdrawalWaiver?: WithdrawalWaiverConsent,\n\t): Promise<PayCheckoutSession> {\n\t\treturn this.transport.call('pay.createCheckout', 'mutation', {\n\t\t\tpublishableKey: this.publishableKey,\n\t\t\tsku,\n\t\t\tendUserRef,\n\t\t\tlocale: locale ?? undefined,\n\t\t\t...(withdrawalWaiver?.accepted === true && typeof withdrawalWaiver.version === 'string'\n\t\t\t\t? { withdrawalWaiver: { version: withdrawalWaiver.version, accepted: true } }\n\t\t\t\t: {}),\n\t\t})\n\t}\n\n\tclaimSession(sessionId: string, endUserRef: string): Promise<PayCheckoutClaim> {\n\t\treturn this.transport.call('pay.claimSession', 'query', {\n\t\t\tpublishableKey: this.publishableKey,\n\t\t\tsessionId,\n\t\t\tendUserRef,\n\t\t})\n\t}\n\n\t/** `trialStartedHint`: the trial start kept in storage.sync; the server only lets it move a start earlier. */\n\tgetEntitlement(endUserRef: string, trialStartedHint?: string | null): Promise<SignedEntitlement> {\n\t\treturn this.transport.call('pay.getEntitlement', 'query', {\n\t\t\tpublishableKey: this.publishableKey,\n\t\t\tendUserRef,\n\t\t\t...(trialStartedHint ? { trialStartedHint } : {}),\n\t\t})\n\t}\n\n\tgetPortalUrl(endUserRef: string, customerId?: string, locale?: string | null): Promise<PayPortalResponse> {\n\t\treturn this.transport.call('pay.getPortalUrl', 'mutation', {\n\t\t\tpublishableKey: this.publishableKey,\n\t\t\tendUserRef,\n\t\t\t...(customerId ? { customerId } : {}),\n\t\t\t...(locale ? { locale } : {}),\n\t\t})\n\t}\n}\n","import type { LogLevel } from '../types/config.js'\n\nconst ORDER: Record<LogLevel, number> = { silent: 0, error: 1, warn: 2, info: 3, debug: 4 }\n\nexport class Logger {\n\tprivate level: LogLevel = 'warn'\n\tprivate readonly prefix = '[ExtenshiPay]'\n\n\tconfigure(options: { logLevel?: LogLevel; debug?: boolean }): void {\n\t\tif (options.logLevel) this.level = options.logLevel\n\t\tif (options.debug) this.level = 'debug'\n\t}\n\n\terror(message: string, ...args: unknown[]): void {\n\t\tif (this.enabled('error')) console.error(this.prefix, message, ...args)\n\t}\n\n\twarn(message: string, ...args: unknown[]): void {\n\t\tif (this.enabled('warn')) console.warn(this.prefix, message, ...args)\n\t}\n\n\tinfo(message: string, ...args: unknown[]): void {\n\t\tif (this.enabled('info')) console.info(this.prefix, message, ...args)\n\t}\n\n\tdebug(message: string, ...args: unknown[]): void {\n\t\tif (this.enabled('debug')) console.debug(this.prefix, message, ...args)\n\t}\n\n\tprivate enabled(level: LogLevel): boolean {\n\t\treturn ORDER[level] <= ORDER[this.level]\n\t}\n}\n\nexport const logger = new Logger()\n","/**\n * HTTP transport for the BFF's tRPC endpoint (`/api/trpc/<procedure>`).\n *\n * Queries are header-less GETs with `?input=<json>` (a CORS \"simple request\",\n * so no preflight); mutations POST a JSON body. The only things that leave the\n * extension are payment inputs and optional recovery session/proof inputs\n * and the browser's standard headers — `credentials: 'omit'` keeps cookies out.\n * Queries are retried on network / 5xx errors; mutations never are.\n */\n\nimport { PAY_ERRORS } from '../types/contract.js'\nimport { ERROR_CODES, type ErrorCode, ExtenshiPayError } from '../types/errors.js'\nimport { logger } from '../utils/logger.js'\n\nexport type ProcedureKind = 'query' | 'mutation'\n\nexport interface Transport {\n\tcall<T>(procedure: string, kind: ProcedureKind, input: Record<string, unknown>): Promise<T>\n}\n\nexport interface HttpTransportOptions {\n\tapiUrl: string\n\t/** Per-attempt timeout (default 10 s). */\n\ttimeoutMs?: number\n\t/** Extra attempts for queries (default 1). */\n\tretries?: number\n\tfetchImpl?: typeof fetch\n}\n\nexport const TRPC_PATH = '/api/trpc'\nconst DEFAULT_TIMEOUT_MS = 10_000\nconst DEFAULT_RETRIES = 1\nconst RETRY_BASE_MS = 500\n\ninterface TrpcErrorShape {\n\tmessage?: string\n\tcode?: number\n\tdata?: {\n\t\tcode?: string\n\t\thttpStatus?: number\n\t\tcause?: { code?: string; retryAfterSec?: number }\n\t}\n}\n\ninterface TrpcEnvelope<T> {\n\tresult?: { data?: T }\n\terror?: TrpcErrorShape\n}\n\nconst RETRYABLE: ReadonlySet<ErrorCode> = new Set([\n\tERROR_CODES.NETWORK_ERROR,\n\tERROR_CODES.TIMEOUT,\n\tERROR_CODES.GATEWAY_UNAVAILABLE,\n])\n\n/** `PAY_*` cause codes, when the BFF forwards them, map 1:1. */\nconst CAUSE_TO_CODE: Record<string, ErrorCode> = {\n\t[PAY_ERRORS.RATE_LIMITED]: ERROR_CODES.RATE_LIMITED,\n\t[PAY_ERRORS.INVALID_KEY]: ERROR_CODES.INVALID_KEY,\n\t[PAY_ERRORS.SELLER_NOT_CONNECTED]: ERROR_CODES.SELLER_NOT_ACTIVE,\n\t[PAY_ERRORS.SELLER_NOT_ACTIVE]: ERROR_CODES.SELLER_NOT_ACTIVE,\n\t[PAY_ERRORS.AGREEMENT_REQUIRED]: ERROR_CODES.SELLER_NOT_ACTIVE,\n\t[PAY_ERRORS.OFFER_NOT_FOUND]: ERROR_CODES.OFFER_NOT_FOUND,\n\t[PAY_ERRORS.GATEWAY_UNAVAILABLE]: ERROR_CODES.GATEWAY_UNAVAILABLE,\n\t[PAY_ERRORS.WITHDRAWAL_WAIVER_REQUIRED]: ERROR_CODES.WITHDRAWAL_WAIVER_REQUIRED,\n}\n\nfunction parseRetryAfter(message: string): number | undefined {\n\tconst match = /retry in (\\d+)s/i.exec(message)\n\treturn match ? Number(match[1]) : undefined\n}\n\n/**\n * The BFF's error formatter does not forward `cause` for `pay.*` errors, so the\n * tRPC code + message is the primary signal; `data.cause.code` is honoured when\n * present so a future BFF that forwards it needs no SDK change.\n */\nexport function trpcErrorToPayError(error: TrpcErrorShape, httpStatus?: number): ExtenshiPayError {\n\tconst message = error.message ?? 'Request failed'\n\tconst trpcCode = error.data?.code ?? ''\n\tconst causeCode = error.data?.cause?.code\n\tconst retryAfterSec = error.data?.cause?.retryAfterSec ?? parseRetryAfter(message)\n\tconst options = { retryAfterSec, httpStatus: error.data?.httpStatus ?? httpStatus }\n\n\tconst mapped = causeCode ? CAUSE_TO_CODE[causeCode] : undefined\n\tif (mapped) return new ExtenshiPayError(mapped, message, options)\n\n\tswitch (trpcCode) {\n\t\tcase 'TOO_MANY_REQUESTS':\n\t\t\treturn new ExtenshiPayError(ERROR_CODES.RATE_LIMITED, message, options)\n\t\tcase 'NOT_FOUND':\n\t\t\tif (/publishable key/i.test(message))\n\t\t\t\treturn new ExtenshiPayError(ERROR_CODES.INVALID_KEY, message, options)\n\t\t\tif (/session/i.test(message))\n\t\t\t\treturn new ExtenshiPayError(ERROR_CODES.CHECKOUT_UNAVAILABLE, message, options)\n\t\t\treturn new ExtenshiPayError(ERROR_CODES.OFFER_NOT_FOUND, message, options)\n\t\tcase 'PRECONDITION_FAILED':\n\t\t\tif (/withdrawal/i.test(message))\n\t\t\t\treturn new ExtenshiPayError(ERROR_CODES.WITHDRAWAL_WAIVER_REQUIRED, message, options)\n\t\t\treturn new ExtenshiPayError(ERROR_CODES.SELLER_NOT_ACTIVE, message, options)\n\t\tcase 'BAD_REQUEST':\n\t\t\treturn new ExtenshiPayError(ERROR_CODES.INVALID_REQUEST, message, options)\n\t\tcase 'INTERNAL_SERVER_ERROR':\n\t\t\treturn new ExtenshiPayError(ERROR_CODES.GATEWAY_UNAVAILABLE, message, options)\n\t\tdefault:\n\t\t\treturn new ExtenshiPayError(ERROR_CODES.UNKNOWN, message, options)\n\t}\n}\n\nfunction sleep(ms: number): Promise<void> {\n\treturn new Promise((resolve) => setTimeout(resolve, ms))\n}\n\nexport class HttpTransport implements Transport {\n\tprivate readonly apiUrl: string\n\tprivate readonly timeoutMs: number\n\tprivate readonly retries: number\n\tprivate readonly fetchImpl: typeof fetch\n\n\tconstructor(options: HttpTransportOptions) {\n\t\tthis.apiUrl = options.apiUrl.replace(/\\/+$/, '')\n\t\tthis.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS\n\t\tthis.retries = options.retries ?? DEFAULT_RETRIES\n\t\tthis.fetchImpl = options.fetchImpl ?? ((input, init) => fetch(input, init))\n\t}\n\n\tasync call<T>(procedure: string, kind: ProcedureKind, input: Record<string, unknown>): Promise<T> {\n\t\tconst base = `${this.apiUrl}${TRPC_PATH}/${procedure}`\n\t\tconst url = kind === 'query' ? `${base}?input=${encodeURIComponent(JSON.stringify(input))}` : base\n\t\tconst attempts = kind === 'query' ? this.retries + 1 : 1\n\t\tlet lastError: ExtenshiPayError | null = null\n\t\tfor (let attempt = 0; attempt < attempts; attempt++) {\n\t\t\ttry {\n\t\t\t\treturn await this.request<T>(url, kind, input)\n\t\t\t} catch (error) {\n\t\t\t\tconst err = ExtenshiPayError.from(error)\n\t\t\t\tif (!RETRYABLE.has(err.code) || attempt === attempts - 1) throw err\n\t\t\t\tlastError = err\n\t\t\t\tlogger.debug(`${procedure} failed (${err.code}), retrying`)\n\t\t\t\tawait sleep(RETRY_BASE_MS * 2 ** attempt)\n\t\t\t}\n\t\t}\n\t\tthrow lastError ?? new ExtenshiPayError(ERROR_CODES.UNKNOWN, `${procedure} failed`)\n\t}\n\n\tprivate async request<T>(url: string, kind: ProcedureKind, input: Record<string, unknown>): Promise<T> {\n\t\tconst controller = typeof AbortController === 'function' ? new AbortController() : null\n\t\tconst timer = controller ? setTimeout(() => controller.abort(), this.timeoutMs) : null\n\t\tlet response: Response\n\t\ttry {\n\t\t\tresponse = await this.fetchImpl(url, {\n\t\t\t\tmethod: kind === 'query' ? 'GET' : 'POST',\n\t\t\t\theaders: kind === 'mutation' ? { 'Content-Type': 'application/json' } : undefined,\n\t\t\t\tbody: kind === 'mutation' ? JSON.stringify(input) : undefined,\n\t\t\t\tsignal: controller?.signal,\n\t\t\t\tcredentials: 'omit',\n\t\t\t})\n\t\t} catch (error) {\n\t\t\tif (controller?.signal.aborted) {\n\t\t\t\tthrow new ExtenshiPayError(ERROR_CODES.TIMEOUT, `Request timed out after ${this.timeoutMs}ms`)\n\t\t\t}\n\t\t\tthrow new ExtenshiPayError(ERROR_CODES.NETWORK_ERROR, 'Network request failed', { cause: error })\n\t\t} finally {\n\t\t\tif (timer !== null) clearTimeout(timer)\n\t\t}\n\n\t\tlet body: TrpcEnvelope<T> | null = null\n\t\ttry {\n\t\t\tbody = (await response.json()) as TrpcEnvelope<T>\n\t\t} catch {\n\t\t\tbody = null\n\t\t}\n\t\tif (body?.error) throw trpcErrorToPayError(body.error, response.status)\n\t\tif (!response.ok) {\n\t\t\tconst code = response.status >= 500 ? ERROR_CODES.GATEWAY_UNAVAILABLE : ERROR_CODES.INVALID_RESPONSE\n\t\t\tthrow new ExtenshiPayError(code, `HTTP ${response.status}`, { httpStatus: response.status })\n\t\t}\n\t\tif (!body?.result || !('data' in body.result)) {\n\t\t\tthrow new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Malformed response from the payment backend')\n\t\t}\n\t\treturn body.result.data as T\n\t}\n}\n","/**\n * Hosted checkout flow.\n *\n * `pay.createCheckout` returns a URL on the seller's provider; the SDK opens\n * it in a new tab (`chrome.tabs.create`, falling back to `window.open`) and\n * polls `pay.claimSession` every 2 s for up to 10 min — and immediately when\n * the extension regains focus — until the webhook has landed. A pending\n * session is persisted so a restarted service worker / reopened popup can\n * finish the claim on the next `initialize()`.\n */\n\nimport type { PayApi } from '../api/pay-api.js'\nimport type { StorageAdapter } from '../core/storage.js'\nimport type { PayCheckoutClaim, SignedEntitlement } from '../types/contract.js'\nimport type { CheckoutOptions, CheckoutResult, Entitlement } from '../types/entitlement.js'\nimport { ERROR_CODES, ExtenshiPayError } from '../types/errors.js'\nimport type { ExtenshiPayEvents } from '../types/events.js'\nimport { logger } from '../utils/logger.js'\n\nexport const CHECKOUT_POLL_INTERVAL_MS = 2_000\nexport const CHECKOUT_TIMEOUT_MS = 10 * 60 * 1000\nconst MAX_ERROR_BACKOFF_MS = 30_000\n/** How long after `expiresAt` a persisted session is still worth one claim (webhook lag). */\nconst PENDING_GRACE_MS = 60 * 60 * 1000\n\ninterface PendingCheckout {\n\tsessionId: string\n\tsku: string\n\texpiresAt: string\n}\n\ntype OpenUrl = (url: string) => void | Promise<void>\ntype Emit = <K extends keyof ExtenshiPayEvents>(event: K, payload: ExtenshiPayEvents[K]) => void\n\nexport interface CheckoutManagerOptions {\n\tapi: PayApi\n\tstorage: StorageAdapter\n\tpublishableKey: string\n\tlocale: string | null\n\tgetEndUserRef: () => Promise<string>\n\t/** Verifies + stores the envelope from a completed session. */\n\tonComplete: (envelope: SignedEntitlement) => Promise<Entitlement>\n\temit: Emit\n\topenUrl?: OpenUrl\n\tnow?: () => number\n}\n\ninterface TabsApi {\n\tcreate(properties: { url: string }): unknown\n}\n\ninterface FocusGlobals {\n\tchrome?: { tabs?: TabsApi; windows?: { onFocusChanged?: FocusEvent } }\n\tbrowser?: { tabs?: TabsApi }\n\topen?: (url: string, target: string, features: string) => unknown\n\taddEventListener?: (type: string, listener: () => void) => void\n\tremoveEventListener?: (type: string, listener: () => void) => void\n\tdocument?: Document\n}\n\ninterface FocusEvent {\n\taddListener(listener: (windowId: number) => void): void\n\tremoveListener(listener: (windowId: number) => void): void\n}\n\nexport async function openInNewTab(url: string): Promise<void> {\n\tconst g = globalThis as FocusGlobals\n\tconst tabs = g.chrome?.tabs ?? g.browser?.tabs\n\tif (tabs && typeof tabs.create === 'function') {\n\t\tconst result = tabs.create({ url })\n\t\tif (result && typeof (result as Promise<unknown>).then === 'function') await result\n\t\treturn\n\t}\n\tif (typeof g.open === 'function') {\n\t\tg.open(url, '_blank', 'noopener,noreferrer')\n\t\treturn\n\t}\n\tthrow new ExtenshiPayError(ERROR_CODES.CHECKOUT_UNAVAILABLE, 'Cannot open a checkout tab from this context')\n}\n\n/** Calls `onFocus` whenever the extension window/tab regains focus; returns a disposer. */\nfunction onFocusRegained(onFocus: () => void): () => void {\n\tconst g = globalThis as FocusGlobals\n\tconst disposers: Array<() => void> = []\n\tif (typeof g.addEventListener === 'function' && typeof g.removeEventListener === 'function') {\n\t\tg.addEventListener('focus', onFocus)\n\t\tdisposers.push(() => g.removeEventListener?.('focus', onFocus))\n\t}\n\tconst doc = g.document\n\tif (doc && typeof doc.addEventListener === 'function') {\n\t\tconst onVisible = () => {\n\t\t\tif (doc.visibilityState === 'visible') onFocus()\n\t\t}\n\t\tdoc.addEventListener('visibilitychange', onVisible)\n\t\tdisposers.push(() => doc.removeEventListener('visibilitychange', onVisible))\n\t}\n\tconst windows = g.chrome?.windows?.onFocusChanged\n\tif (windows && typeof windows.addListener === 'function') {\n\t\tconst onWindow = (windowId: number) => {\n\t\t\tif (windowId !== -1) onFocus()\n\t\t}\n\t\twindows.addListener(onWindow)\n\t\tdisposers.push(() => windows.removeListener(onWindow))\n\t}\n\treturn () => {\n\t\tfor (const dispose of disposers) dispose()\n\t}\n}\n\n/** A sleep that can be cut short by `wake()`. */\nfunction interruptibleSleep() {\n\tlet wake: (() => void) | null = null\n\treturn {\n\t\tsleep(ms: number): Promise<void> {\n\t\t\treturn new Promise<void>((resolve) => {\n\t\t\t\tconst timer = setTimeout(() => {\n\t\t\t\t\twake = null\n\t\t\t\t\tresolve()\n\t\t\t\t}, ms)\n\t\t\t\twake = () => {\n\t\t\t\t\tclearTimeout(timer)\n\t\t\t\t\twake = null\n\t\t\t\t\tresolve()\n\t\t\t\t}\n\t\t\t})\n\t\t},\n\t\twake(): void {\n\t\t\twake?.()\n\t\t},\n\t}\n}\n\nexport class CheckoutManager {\n\tprivate active: string | null = null\n\tprivate readonly now: () => number\n\n\tconstructor(private readonly options: CheckoutManagerOptions) {\n\t\tthis.now = options.now ?? (() => Date.now())\n\t}\n\n\tget pendingKey(): string {\n\t\treturn `extenshi-pay:${this.options.publishableKey}:pendingCheckout`\n\t}\n\n\tisActive(): boolean {\n\t\treturn this.active !== null\n\t}\n\n\tasync open(sku: string, options: CheckoutOptions = {}): Promise<CheckoutResult> {\n\t\tif (this.active) {\n\t\t\tthrow new ExtenshiPayError(ERROR_CODES.CHECKOUT_UNAVAILABLE, 'A checkout is already in progress')\n\t\t}\n\t\tconst endUserRef = await this.options.getEndUserRef()\n\t\tconst session = await this.options.api.createCheckout(\n\t\t\tsku,\n\t\t\tendUserRef,\n\t\t\toptions.locale ?? this.options.locale,\n\t\t\toptions.withdrawalWaiver,\n\t\t)\n\t\tthis.active = session.sessionId\n\t\ttry {\n\t\t\tconst pending: PendingCheckout = { sessionId: session.sessionId, sku, expiresAt: session.expiresAt }\n\t\t\tawait this.options.storage.set(this.pendingKey, pending)\n\t\t\tthis.options.emit('checkout:started', { sku, sessionId: session.sessionId, url: session.url })\n\t\t\tawait (options.openUrl ?? this.options.openUrl ?? openInNewTab)(session.url)\n\t\t\treturn await this.poll(sku, session.sessionId, endUserRef, options)\n\t\t} finally {\n\t\t\tthis.active = null\n\t\t}\n\t}\n\n\t/** Finishes a checkout that was started before a restart; null when there is nothing to resume. */\n\tasync resumePending(): Promise<CheckoutResult | null> {\n\t\tconst raw = (await this.options.storage.get(this.pendingKey)) as Partial<PendingCheckout> | undefined\n\t\tif (!raw || typeof raw.sessionId !== 'string' || typeof raw.sku !== 'string') return null\n\t\tconst expires = Date.parse(raw.expiresAt ?? '')\n\t\tif (!Number.isFinite(expires) || expires + PENDING_GRACE_MS < this.now()) {\n\t\t\tawait this.options.storage.remove(this.pendingKey)\n\t\t\treturn null\n\t\t}\n\t\tconst endUserRef = await this.options.getEndUserRef()\n\t\tlet claim: PayCheckoutClaim\n\t\ttry {\n\t\t\tclaim = await this.options.api.claimSession(raw.sessionId, endUserRef)\n\t\t} catch (error) {\n\t\t\tlogger.debug('could not resume pending checkout', error)\n\t\t\treturn null\n\t\t}\n\t\treturn this.settle(claim, raw.sku, raw.sessionId)\n\t}\n\n\tprivate async poll(\n\t\tsku: string,\n\t\tsessionId: string,\n\t\tendUserRef: string,\n\t\toptions: CheckoutOptions,\n\t): Promise<CheckoutResult> {\n\t\tconst interval = options.pollIntervalMs ?? CHECKOUT_POLL_INTERVAL_MS\n\t\tconst deadline = this.now() + (options.timeoutMs ?? CHECKOUT_TIMEOUT_MS)\n\t\tconst sleeper = interruptibleSleep()\n\t\tconst stopFocus = onFocusRegained(() => sleeper.wake())\n\t\tlet delay = interval\n\t\tlet errorBackoff = 0\n\t\ttry {\n\t\t\tfor (;;) {\n\t\t\t\tawait sleeper.sleep(delay)\n\t\t\t\tif (this.now() >= deadline) return { state: 'timeout', sku, sessionId }\n\t\t\t\tlet claim: PayCheckoutClaim\n\t\t\t\ttry {\n\t\t\t\t\tclaim = await this.options.api.claimSession(sessionId, endUserRef)\n\t\t\t\t} catch (error) {\n\t\t\t\t\tconst err = ExtenshiPayError.from(error)\n\t\t\t\t\tif (err.code === ERROR_CODES.RATE_LIMITED) {\n\t\t\t\t\t\tdelay = (err.retryAfterSec ?? 5) * 1000\n\t\t\t\t\t} else if (\n\t\t\t\t\t\terr.code === ERROR_CODES.NETWORK_ERROR ||\n\t\t\t\t\t\terr.code === ERROR_CODES.TIMEOUT ||\n\t\t\t\t\t\terr.code === ERROR_CODES.GATEWAY_UNAVAILABLE\n\t\t\t\t\t) {\n\t\t\t\t\t\terrorBackoff = Math.min(errorBackoff ? errorBackoff * 2 : interval, MAX_ERROR_BACKOFF_MS)\n\t\t\t\t\t\tdelay = errorBackoff\n\t\t\t\t\t} else {\n\t\t\t\t\t\tawait this.options.storage.remove(this.pendingKey)\n\t\t\t\t\t\tthrow err\n\t\t\t\t\t}\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\terrorBackoff = 0\n\t\t\t\tdelay = interval\n\t\t\t\tconst result = await this.settle(claim, sku, sessionId)\n\t\t\t\tif (result) return result\n\t\t\t}\n\t\t} finally {\n\t\t\tstopFocus()\n\t\t}\n\t}\n\n\tprivate async settle(\n\t\tclaim: PayCheckoutClaim,\n\t\tsku: string,\n\t\tsessionId: string,\n\t): Promise<CheckoutResult | null> {\n\t\tswitch (claim.state) {\n\t\t\tcase 'pending':\n\t\t\t\treturn null\n\t\t\tcase 'complete': {\n\t\t\t\tconst entitlement = await this.options.onComplete(claim.entitlement)\n\t\t\t\tawait this.options.storage.remove(this.pendingKey)\n\t\t\t\tthis.options.emit('checkout:completed', { sku, sessionId, entitlement })\n\t\t\t\treturn { state: 'complete', sku, sessionId, entitlement }\n\t\t\t}\n\t\t\tcase 'canceled':\n\t\t\t\tawait this.options.storage.remove(this.pendingKey)\n\t\t\t\tthis.options.emit('checkout:canceled', { sku, sessionId })\n\t\t\t\treturn { state: 'canceled', sku, sessionId }\n\t\t\tcase 'expired':\n\t\t\t\tawait this.options.storage.remove(this.pendingKey)\n\t\t\t\tthis.options.emit('checkout:expired', { sku, sessionId })\n\t\t\t\treturn { state: 'expired', sku, sessionId }\n\t\t\tdefault:\n\t\t\t\tthrow new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Unknown checkout claim state')\n\t\t}\n\t}\n}\n","/**\n * Cloud copy of the extension's settings (`@extenshi/storage`). Pay owns the\n * token: only a verified restore claim issues it; this module keeps it in the\n * SDK's storage (`storage.local`) and revokes it. `@extenshi/storage` reads it\n * through `cloudBackupToken()`. The token is never logged and never answered to\n * a content script: route those calls to the background.\n */\n\nimport type { StorageAdapter } from '../core/storage.js'\nimport { type PayStorageGrant, STORAGE_TOKEN_RE } from '../types/contract.js'\nimport type { CloudBackupState } from '../types/entitlement.js'\nimport { ERROR_CODES, ExtenshiPayError } from '../types/errors.js'\nimport { logger } from '../utils/logger.js'\n\nconst REQUEST_TIMEOUT_MS = 10_000\n\nexport interface CloudBackupOptions {\n\tstorage: StorageAdapter\n\tpublishableKey: string\n\tapiUrl: string\n\tfetch?: typeof fetch\n\t/** Mock mode: forget the token locally, never call the network. */\n\tmock?: boolean\n}\n\n/** True in a content script, where the token must not be handed out. */\nfunction inContentScript(): boolean {\n\tconst g = globalThis as {\n\t\tchrome?: { runtime?: { id?: string }; tabs?: unknown }\n\t\tbrowser?: { runtime?: { id?: string }; tabs?: unknown }\n\t}\n\treturn !!(g.chrome?.runtime?.id || g.browser?.runtime?.id) && !(g.chrome?.tabs || g.browser?.tabs)\n}\n\nexport class CloudBackup {\n\tprivate readonly fetchImpl: typeof fetch\n\n\tconstructor(private readonly options: CloudBackupOptions) {\n\t\tthis.fetchImpl = options.fetch ?? ((input, init) => fetch(input, init))\n\t}\n\n\tget storageKey(): string {\n\t\treturn `extenshi-pay:${this.options.publishableKey}:storageToken`\n\t}\n\n\t/** Stores or clears the token from a verified claim. Never throws: the licence is already restored. */\n\tasync accept(grant: PayStorageGrant | undefined): Promise<CloudBackupState | undefined> {\n\t\tif (!grant || typeof grant !== 'object') return undefined\n\t\ttry {\n\t\t\tif (grant.state === 'granted') {\n\t\t\t\tif (typeof grant.token !== 'string' || !STORAGE_TOKEN_RE.test(grant.token)) return undefined\n\t\t\t\tawait this.options.storage.set(this.storageKey, grant.token)\n\t\t\t\treturn 'on'\n\t\t\t}\n\t\t\tif (grant.state === 'unavailable') {\n\t\t\t\tawait this.options.storage.remove(this.storageKey)\n\t\t\t\treturn grant.reason === 'LICENSE_REQUIRED' ? 'license_required' : 'no_consent'\n\t\t\t}\n\t\t} catch {\n\t\t\tlogger.warn('cloud backup state could not be saved')\n\t\t}\n\t\treturn undefined\n\t}\n\n\tasync token(): Promise<string | null> {\n\t\tthis.assertTrustedContext()\n\t\tconst value = await this.options.storage.get(this.storageKey)\n\t\treturn typeof value === 'string' && STORAGE_TOKEN_RE.test(value) ? value : null\n\t}\n\n\t/** Revokes this installation's token. A token the server no longer knows (401) is forgotten too. */\n\tasync disable(): Promise<void> {\n\t\tconst token = await this.token()\n\t\tif (!token) return\n\t\tif (!this.options.mock) {\n\t\t\tconst status = await this.request('/v1/storage/grant', token)\n\t\t\tif (status !== 401) this.throwUnlessOk(status)\n\t\t}\n\t\tawait this.options.storage.remove(this.storageKey)\n\t}\n\n\t/** Deletes the buyer's cloud copy and turns the backup off on every device. */\n\tasync delete(): Promise<void> {\n\t\tconst token = await this.token()\n\t\tif (!token)\n\t\t\tthrow new ExtenshiPayError(\n\t\t\t\tERROR_CODES.INVALID_REQUEST,\n\t\t\t\t'Cloud backup is off on this installation; turn it on to delete the cloud copy',\n\t\t\t)\n\t\tif (!this.options.mock) {\n\t\t\tconst status = await this.request('/v1/storage/data', token)\n\t\t\tif (status === 401) {\n\t\t\t\t// The server no longer accepts this token, so it is useless here; the copy was not deleted.\n\t\t\t\tawait this.options.storage.remove(this.storageKey)\n\t\t\t\tthrow new ExtenshiPayError(\n\t\t\t\t\tERROR_CODES.INVALID_REQUEST,\n\t\t\t\t\t'Cloud backup is off on the server; turn it on again to delete the cloud copy',\n\t\t\t\t\t{ httpStatus: 401 },\n\t\t\t\t)\n\t\t\t}\n\t\t\tthis.throwUnlessOk(status)\n\t\t}\n\t\tawait this.options.storage.remove(this.storageKey)\n\t}\n\n\tprivate assertTrustedContext(): void {\n\t\tif (inContentScript())\n\t\t\tthrow new ExtenshiPayError(\n\t\t\t\tERROR_CODES.INVALID_REQUEST,\n\t\t\t\t'Use cloud backup from an extension page or background context',\n\t\t\t)\n\t}\n\n\tprivate throwUnlessOk(status: number): void {\n\t\tif (status >= 200 && status < 300) return\n\t\tif (status === 429)\n\t\t\tthrow new ExtenshiPayError(ERROR_CODES.RATE_LIMITED, 'Too many requests', { httpStatus: status })\n\t\tif (status >= 500)\n\t\t\tthrow new ExtenshiPayError(ERROR_CODES.GATEWAY_UNAVAILABLE, `HTTP ${status}`, { httpStatus: status })\n\t\tthrow new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, `HTTP ${status}`, { httpStatus: status })\n\t}\n\n\tprivate async request(path: string, token: string): Promise<number> {\n\t\tconst controller = typeof AbortController === 'function' ? new AbortController() : null\n\t\tconst timer = controller ? setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS) : null\n\t\ttry {\n\t\t\tconst response = await this.fetchImpl(`${this.options.apiUrl}${path}`, {\n\t\t\t\tmethod: 'DELETE',\n\t\t\t\theaders: { Authorization: `Bearer ${token}` },\n\t\t\t\tcredentials: 'omit',\n\t\t\t\tsignal: controller?.signal,\n\t\t\t})\n\t\t\treturn response.status\n\t\t} catch (error) {\n\t\t\tif (controller?.signal.aborted)\n\t\t\t\tthrow new ExtenshiPayError(ERROR_CODES.TIMEOUT, `Request timed out after ${REQUEST_TIMEOUT_MS}ms`)\n\t\t\tthrow new ExtenshiPayError(ERROR_CODES.NETWORK_ERROR, 'Network request failed', { cause: error })\n\t\t} finally {\n\t\t\tif (timer !== null) clearTimeout(timer)\n\t\t}\n\t}\n}\n","/** Pure helpers over the entitlement projection. Features come from the items' `features[]`. */\n\nimport type { PayEntitlementItem } from '../types/contract.js'\nimport type { Entitlement } from '../types/entitlement.js'\n\nconst LIVE_STATUSES: ReadonlySet<string> = new Set(['active', 'grace'])\n\nexport function isLive(item: PayEntitlementItem): boolean {\n\treturn LIVE_STATUSES.has(item.status)\n}\n\n/** An item past its `expiresAt` reads as expired without a network round-trip. */\nexport function applyLocalExpiry(\n\titems: PayEntitlementItem[],\n\tnow: number = Date.now(),\n): PayEntitlementItem[] {\n\treturn items.map((item) => {\n\t\tif (!isLive(item) || !item.expiresAt) return item\n\t\tconst expires = Date.parse(item.expiresAt)\n\t\treturn Number.isFinite(expires) && expires <= now ? { ...item, status: 'expired' } : item\n\t})\n}\n\nexport function collectFeatures(items: PayEntitlementItem[]): string[] {\n\tconst features = new Set<string>()\n\tfor (const item of items) {\n\t\tif (!isLive(item)) continue\n\t\tfor (const feature of item.features) features.add(feature)\n\t}\n\treturn [...features]\n}\n\nexport function isEntitled(entitlement: Entitlement, sku?: string): boolean {\n\treturn (\n\t\t!entitlement.requiresOnlineCheck &&\n\t\tentitlement.items.some((item) => isLive(item) && (sku === undefined || item.sku === sku))\n\t)\n}\n\nexport function hasFeature(entitlement: Entitlement, feature: string): boolean {\n\treturn entitlement.features.includes(feature)\n}\n\nexport function checkFeatures(entitlement: Entitlement, features: string[]): Record<string, boolean> {\n\tconst result: Record<string, boolean> = {}\n\tfor (const feature of features) result[feature] = hasFeature(entitlement, feature)\n\treturn result\n}\n\nexport const EMPTY_ENTITLEMENT: Entitlement = Object.freeze({\n\titems: [],\n\tfeatures: [],\n\tverified: false,\n\tissuedAt: null,\n\tfetchedAt: null,\n\tsource: 'none',\n\trequiresOnlineCheck: false,\n\tofflineUntil: null,\n}) as Entitlement\n\n// Frozen empty arrays prevent consumers from changing the shared denied state.\nObject.freeze(EMPTY_ENTITLEMENT.items)\nObject.freeze(EMPTY_ENTITLEMENT.features)\n","/**\n * Ed25519 verification of the entitlement projection.\n *\n * Tamper resistance, not DRM. Callers must deny access for both invalid and\n * unverified envelopes outside explicit mocks.\n *\n * Which keys are trusted, in order (`PublicKeySource`, built in core/extenshi-pay.ts):\n * 1. the key the server returned over HTTPS in this session;\n * 2. the bundled `entitlementPublicKey`, when the developer configured one. It pins\n * verification without a round-trip: a key read from extension storage is then never used;\n * 3. without a bundled key, the server key saved in `storage.local` next to the\n * license cache, so a restart with no network can still verify the cache.\n * When none of them verifies an envelope the server is asked for its current key once\n * (a rotated key), and that answer decides.\n */\n\nimport { canonicalJson, type SignedEntitlement } from '../types/contract.js'\n\nexport type SignatureVerdict = 'valid' | 'invalid' | 'unverified'\n\nexport function base64ToBytes(base64: string): Uint8Array<ArrayBuffer> {\n\tconst binary = atob(base64)\n\tconst bytes = new Uint8Array(binary.length)\n\tfor (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i)\n\treturn bytes\n}\n\nexport async function verifyEntitlementSignature(\n\tenvelope: SignedEntitlement,\n\tpublicKeyBase64: string | null,\n): Promise<SignatureVerdict> {\n\tif (!envelope.signature || envelope.alg !== 'ed25519') return 'invalid'\n\tif (!publicKeyBase64) return 'unverified'\n\tconst subtle = (globalThis as { crypto?: Crypto }).crypto?.subtle\n\tif (!subtle) return 'unverified'\n\n\tlet key: CryptoKey\n\ttry {\n\t\tkey = await subtle.importKey('raw', base64ToBytes(publicKeyBase64), { name: 'Ed25519' }, false, [\n\t\t\t'verify',\n\t\t])\n\t} catch {\n\t\treturn 'unverified'\n\t}\n\n\ttry {\n\t\tconst data = new TextEncoder().encode(canonicalJson(envelope.payload))\n\t\tconst ok = await subtle.verify('Ed25519', key, base64ToBytes(envelope.signature), data)\n\t\treturn ok ? 'valid' : 'invalid'\n\t} catch {\n\t\treturn 'invalid'\n\t}\n}\n\nexport const PUBLIC_KEY_RE = /^[A-Za-z0-9+/]{43}=$/\n\nexport interface PublicKeySource {\n\t/** Keys trusted without a round-trip, in the order above. */\n\tknown(): Promise<string[]>\n\t/** The server's current key, fetched now; null when the server signs nothing. Rejects when unreachable. */\n\tfetchCurrent(): Promise<string | null>\n}\n\nexport interface KeyedVerdict {\n\tverdict: SignatureVerdict\n\t/** The key that verified the envelope; null unless `verdict` is `valid`. */\n\tkey: string | null\n}\n\n/**\n * `invalid` only when the server's current key was checked too (or the envelope carries no\n * signature at all). A mismatch against known keys while the server is unreachable is\n * `unverified`: it may be a rotated key, and no paid access is granted either way.\n */\nexport async function verifyWithKeys(\n\tenvelope: SignedEntitlement,\n\tsource: PublicKeySource,\n): Promise<KeyedVerdict> {\n\tif (!envelope.signature || envelope.alg !== 'ed25519') return { verdict: 'invalid', key: null }\n\tlet known: string[] = []\n\ttry {\n\t\tknown = await source.known()\n\t} catch {\n\t\tknown = []\n\t}\n\tlet mismatch = false\n\tfor (const key of known) {\n\t\tconst verdict = await verifyEntitlementSignature(envelope, key)\n\t\tif (verdict === 'valid') return { verdict, key }\n\t\tif (verdict === 'invalid') mismatch = true\n\t}\n\tlet current: string | null\n\ttry {\n\t\tcurrent = await source.fetchCurrent()\n\t} catch {\n\t\treturn { verdict: 'unverified', key: null }\n\t}\n\tif (current && !known.includes(current)) {\n\t\tconst verdict = await verifyEntitlementSignature(envelope, current)\n\t\treturn { verdict, key: verdict === 'valid' ? current : null }\n\t}\n\treturn { verdict: mismatch ? 'invalid' : 'unverified', key: null }\n}\n","/**\n * The free trial an application configures on the server (`trialDays`).\n *\n * The server starts one clock per installation at its first license read and\n * signs `{ startedAt, endsAt }` into the entitlement, so the trial comes from\n * the verified license like paid access does: no start date in extension\n * storage, nothing a device clock or a storage edit can move. Offline, the\n * cached license answers for up to 48 hours.\n *\n * `trial:ending` / `trial:ended` fire once per installation and trial (the\n * marker is kept in the SDK's storage), and not while the user has paid\n * access. Render state from `getTrial()`; the events are one-time notices.\n */\n\nimport type { StorageAdapter } from '../core/storage.js'\nimport type { PayTrial } from '../types/contract.js'\nimport type { TrialState } from '../types/entitlement.js'\nimport { logger } from '../utils/logger.js'\n\nexport const DAY_MS = 24 * 60 * 60 * 1000\n/** Re-check at least daily: long timers are clamped by browsers and lost when a service worker sleeps. */\nconst MAX_TIMER_MS = DAY_MS\n\nexport interface TrialClock {\n\t/** Device time. */\n\tnow: number\n\t/** The signed issue time of the license; a floor for `now`. */\n\tissuedAt: number\n\t/** Whether the license was checked recently enough to grant access (48 h, as for paid access). */\n\tchecked: boolean\n}\n\n/** The trial as of `clock`, or null when the license carries none (or a malformed one). */\nexport function trialState(trial: PayTrial | undefined, clock: TrialClock): TrialState | null {\n\tif (!trial) return null\n\tconst startedAt = Date.parse(trial.startedAt)\n\tconst endsAt = Date.parse(trial.endsAt)\n\tif (!Number.isFinite(startedAt) || !Number.isFinite(endsAt)) return null\n\t// The server's signed time is a floor: a clock turned back cannot reopen an ended trial.\n\tconst now = Number.isFinite(clock.issuedAt) ? Math.max(clock.now, clock.issuedAt) : clock.now\n\tconst left = endsAt - now\n\treturn {\n\t\tactive: left > 0 && clock.checked,\n\t\tstartedAt: trial.startedAt,\n\t\tendsAt: trial.endsAt,\n\t\tdaysLeft: left > 0 ? Math.ceil(left / DAY_MS) : 0,\n\t\trequiresOnlineCheck: left > 0 && !clock.checked,\n\t}\n}\n\n/** The feedback form address with `src=trial_end`; null unless it is a plain HTTPS URL. No installation id is added. */\nexport function trialFeedbackUrl(raw: string | undefined): string | null {\n\tif (!raw) return null\n\tlet url: URL\n\ttry {\n\t\turl = new URL(raw)\n\t} catch {\n\t\treturn null\n\t}\n\tif (url.protocol !== 'https:' || url.username || url.password) return null\n\turl.searchParams.set('src', 'trial_end')\n\treturn url.toString()\n}\n\nexport type TrialEvent = 'trial:ending' | 'trial:ended'\n\nexport interface TrialNotifierOptions {\n\tstorage: StorageAdapter\n\tstorageKey: string\n\t/** `trial:ending` fires this many days before the end; 0 never. */\n\tendingDays: number\n\tgetTrial: () => TrialState | null\n\thasPaidAccess: () => boolean\n\temit: (event: TrialEvent, trial: TrialState) => void\n\tnow: () => number\n}\n\n/** Which trial each event was last sent for, as `startedAt|endsAt`. */\ninterface SentRecord {\n\tending?: string\n\tended?: string\n}\n\nexport class TrialNotifier {\n\tprivate timer: ReturnType<typeof setTimeout> | null = null\n\tprivate running = false\n\tprivate pending: Promise<void> = Promise.resolve()\n\n\tconstructor(private readonly options: TrialNotifierOptions) {}\n\n\tstart(): void {\n\t\tthis.running = true\n\t\tvoid this.evaluate()\n\t}\n\n\tstop(): void {\n\t\tthis.running = false\n\t\tthis.clearTimer()\n\t}\n\n\t/** Checks the held license; serialized, so two refreshes never send one event twice. */\n\tevaluate(): Promise<void> {\n\t\tthis.pending = this.pending.then(() => this.check()).catch((error) => logger.debug('trial check', error))\n\t\treturn this.pending\n\t}\n\n\tprivate async check(): Promise<void> {\n\t\tif (!this.running) return\n\t\tthis.clearTimer()\n\t\tconst trial = this.options.getTrial()\n\t\tif (!trial) return\n\t\tconst now = this.options.now()\n\t\tconst endsAt = Date.parse(trial.endsAt)\n\t\tconst endingAt = endsAt - this.options.endingDays * DAY_MS\n\t\tconst event: TrialEvent | null =\n\t\t\ttrial.daysLeft === 0\n\t\t\t\t? 'trial:ended'\n\t\t\t\t: trial.active && this.options.endingDays > 0 && now >= endingAt\n\t\t\t\t\t? 'trial:ending'\n\t\t\t\t\t: null\n\t\tif (event && !this.options.hasPaidAccess()) await this.send(event, trial)\n\t\tif (!this.running || trial.daysLeft === 0) return\n\t\tconst next = [endingAt, endsAt].find((at) => at > now) ?? endsAt\n\t\tthis.timer = setTimeout(\n\t\t\t() => {\n\t\t\t\tthis.timer = null\n\t\t\t\tvoid this.evaluate()\n\t\t\t},\n\t\t\tMath.max(1000, Math.min(next - now, MAX_TIMER_MS)),\n\t\t)\n\t}\n\n\tprivate async send(event: TrialEvent, trial: TrialState): Promise<void> {\n\t\tconst id = `${trial.startedAt}|${trial.endsAt}`\n\t\tconst field = event === 'trial:ended' ? 'ended' : 'ending'\n\t\tconst stored = (await this.options.storage.get(this.options.storageKey)) as SentRecord | undefined\n\t\tconst sent: SentRecord = stored && typeof stored === 'object' ? stored : {}\n\t\tif (sent[field] === id || !this.running) return\n\t\tawait this.options.storage.set(this.options.storageKey, { ...sent, [field]: id })\n\t\tthis.options.emit(event, trial)\n\t}\n\n\tprivate clearTimer(): void {\n\t\tif (this.timer !== null) clearTimeout(this.timer)\n\t\tthis.timer = null\n\t}\n}\n","/**\n * Entitlement cache + refresh.\n *\n * The cached envelope is a cache OF the server projection, never a second\n * source of truth: it is verified when stored and re-verified on load (once\n * the project's public key is known), served without a round-trip while the\n * TTL holds, served after signed issuance for the signed `offlineSeconds` (48 hours when absent) when the network is down, and expired\n * locally by `expiresAt`. Background refresh polls at most every 15 minutes\n * and backs off exponentially on errors.\n */\n\nimport type { PayApi } from '../api/pay-api.js'\nimport type { StorageAdapter } from '../core/storage.js'\nimport { canonicalJson, type SignedEntitlement } from '../types/contract.js'\nimport type { ClockSkew, Entitlement, EntitlementSource, TrialState } from '../types/entitlement.js'\nimport { ERROR_CODES, ExtenshiPayError } from '../types/errors.js'\nimport { logger } from '../utils/logger.js'\nimport { applyLocalExpiry, collectFeatures, EMPTY_ENTITLEMENT } from './features.js'\nimport { type PublicKeySource, verifyWithKeys } from './signature.js'\nimport { trialState } from './trial.js'\n\nexport const MIN_REFRESH_INTERVAL_MS = 15 * 60 * 1000\nexport const MAX_REFRESH_BACKOFF_MS = 6 * 60 * 60 * 1000\n/** Offline allowance when the signed license names none (older servers and caches). */\nexport const MAX_OFFLINE_AGE_MS = 48 * 60 * 60 * 1000\n/** Ceiling for a signed `offlineSeconds`. */\nexport const MAX_SIGNED_OFFLINE_AGE_MS = 366 * 24 * 60 * 60 * 1000\n/** `setTimeout` fires at once past this delay. */\nconst MAX_TIMER_MS = 2 ** 31 - 1\n// Allow small server/client clock skew without granting more than the signed age limit.\nexport const MAX_CLOCK_SKEW_MS = 5 * 60 * 1000\nconst CACHE_VERSION = 1\n\ninterface CacheRecord {\n\tv: typeof CACHE_VERSION\n\tenvelope: SignedEntitlement\n\tfetchedAt: number\n}\n\ninterface Held {\n\tenvelope: SignedEntitlement\n\tfetchedAt: number\n\tverified: boolean\n\t/** The key that verified the envelope; null while unverified and in mock mode. */\n\tkey: string | null\n\tsource: EntitlementSource\n}\n\nexport interface EntitlementManagerOptions {\n\tapi: PayApi\n\tstorage: StorageAdapter\n\tpublishableKey: string\n\tcacheTtlMs: number\n\tsource?: EntitlementSource\n\tgetEndUserRef: () => Promise<string>\n\t/** The trusted Ed25519 keys, in order, and how to ask the server for its current one. */\n\tkeys: PublicKeySource\n\tonChange?: (entitlement: Entitlement) => void\n\t/** After every accepted envelope, changed or not (the trial is not part of `onChange`). */\n\tonAccepted?: () => void\n\t/** The synced trial start to send with a refresh; null when there is none. */\n\tgetTrialStartHint?: () => Promise<string | null>\n\tonError?: (error: ExtenshiPayError) => void\n\tnow?: () => number\n}\n\nfunction isEnvelope(value: unknown): value is SignedEntitlement {\n\tif (!value || typeof value !== 'object') return false\n\tconst env = value as SignedEntitlement\n\treturn (\n\t\t!!env.payload &&\n\t\ttypeof env.payload === 'object' &&\n\t\ttypeof env.payload.endUserRef === 'string' &&\n\t\tArray.isArray(env.payload.entitlements) &&\n\t\ttypeof env.payload.issuedAt === 'string'\n\t)\n}\n\nexport class EntitlementManager {\n\tprivate held: Held | null = null\n\tprivate inflight: Promise<Entitlement> | null = null\n\t/** Device clock against the server's at the last license check; null within 5 minutes. */\n\tprivate clockSkew: ClockSkew | null = null\n\tprivate timer: ReturnType<typeof setTimeout> | null = null\n\tprivate refreshGeneration = 0\n\tprivate deadlineTimer: ReturnType<typeof setTimeout> | null = null\n\tprivate refreshIntervalMs = MIN_REFRESH_INTERVAL_MS\n\tprivate backoffMs = 0\n\tprivate autoRefresh = false\n\tprivate readonly online = () => {\n\t\tvoid this.get({ force: true }).then(() => this.notifyIfChanged())\n\t}\n\t// Starts at the empty projection: a first load that finds nothing is not a\n\t// change, a first load that finds a paid entitlement is.\n\tprivate lastFingerprint: string | null = canonicalJson({ items: [], requiresOnlineCheck: false })\n\tprivate readonly now: () => number\n\tprivate readonly source: EntitlementSource\n\n\tconstructor(private readonly options: EntitlementManagerOptions) {\n\t\tthis.now = options.now ?? (() => Date.now())\n\t\tthis.source = options.source ?? 'network'\n\t}\n\n\tget storageKey(): string {\n\t\t// Keep the real cache key stable for upgrades. Simulated grants must\n\t\t// neither consume nor overwrite that cache when developers switch modes.\n\t\treturn `extenshi-pay:${this.options.publishableKey}:entitlement${this.source === 'mock' ? ':mock' : ''}`\n\t}\n\n\t/** Loads the persisted envelope (unverified until `reverify()`); no network. */\n\tasync load(): Promise<Entitlement | null> {\n\t\tconst raw = await this.options.storage.get(this.storageKey)\n\t\tconst record = raw as Partial<CacheRecord> | undefined\n\t\tif (\n\t\t\t!record ||\n\t\t\trecord.v !== CACHE_VERSION ||\n\t\t\t!isEnvelope(record.envelope) ||\n\t\t\ttypeof record.fetchedAt !== 'number' ||\n\t\t\t!Number.isFinite(record.fetchedAt)\n\t\t) {\n\t\t\treturn null\n\t\t}\n\t\tconst endUserRef = await this.options.getEndUserRef()\n\t\tif (\n\t\t\trecord.envelope.payload.endUserRef !== endUserRef ||\n\t\t\t(this.source !== 'mock' && record.envelope.payload.publishableKey !== this.options.publishableKey)\n\t\t) {\n\t\t\tawait this.options.storage.remove(this.storageKey)\n\t\t\treturn null\n\t\t}\n\t\tthis.held = {\n\t\t\tenvelope: JSON.parse(JSON.stringify(record.envelope)),\n\t\t\tfetchedAt: record.fetchedAt,\n\t\t\tverified: false,\n\t\t\tkey: null,\n\t\t\tsource: this.source === 'mock' ? 'mock' : 'cache',\n\t\t}\n\t\tthis.measureClockSkew(record.fetchedAt, Date.parse(record.envelope.payload.issuedAt))\n\t\tthis.lastFingerprint = this.fingerprint()\n\t\treturn this.snapshot()\n\t}\n\n\t/** Re-checks the loaded envelope against the project's key; discards it when the signature is invalid. */\n\tasync reverify(): Promise<void> {\n\t\tif (!this.held) return\n\t\tif (this.source === 'mock') return\n\t\tconst held = this.held\n\t\tconst { verdict, key } = await verifyWithKeys(held.envelope, this.options.keys)\n\t\tif (held !== this.held) return\n\t\tif (verdict === 'invalid') {\n\t\t\tlogger.warn('cached entitlement failed signature verification; discarding')\n\t\t\tawait this.discard()\n\t\t\tthrow new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Cached entitlement signature is invalid')\n\t\t}\n\t\theld.verified = verdict === 'valid'\n\t\theld.key = key\n\t\tif (!held.verified) {\n\t\t\tthrow new ExtenshiPayError(\n\t\t\t\tERROR_CODES.VERIFICATION_UNAVAILABLE,\n\t\t\t\t'Entitlement verification requires a trusted key and Ed25519 WebCrypto support',\n\t\t\t)\n\t\t}\n\t\tthis.scheduleDeadline()\n\t}\n\n\t/** The key the held license was verified with; null when there is none or it is unverified. */\n\tget verifiedKey(): string | null {\n\t\treturn this.held?.verified ? this.held.key : null\n\t}\n\n\tgetCached(): Entitlement | null {\n\t\treturn this.held ? this.snapshot() : null\n\t}\n\n\t/** The server trial in the held license; null without one, or while the license is unverified. */\n\tgetTrial(): TrialState | null {\n\t\tconst held = this.held\n\t\tif (!held || (this.source !== 'mock' && !held.verified)) return null\n\t\tconst now = this.now()\n\t\tconst issuedAt = Date.parse(held.envelope.payload.issuedAt)\n\t\treturn trialState(held.envelope.payload.trial, {\n\t\t\tnow,\n\t\t\tissuedAt,\n\t\t\t// The same offline rule as paid access (snapshot): the allowance from the signed issue, no clock turned back.\n\t\t\tchecked:\n\t\t\t\tthis.source === 'mock' ||\n\t\t\t\t(now >= held.fetchedAt && now < this.offlineDeadline() && now + MAX_CLOCK_SKEW_MS >= issuedAt),\n\t\t})\n\t}\n\n\tisFresh(): boolean {\n\t\treturn (\n\t\t\tthis.held !== null &&\n\t\t\t(this.source === 'mock' || (this.held.verified && !this.snapshot().requiresOnlineCheck)) &&\n\t\t\tthis.now() >= this.held.fetchedAt &&\n\t\t\tthis.now() - this.held.fetchedAt < Math.min(this.options.cacheTtlMs, this.offlineAgeMs())\n\t\t)\n\t}\n\n\tasync get(options: { force?: boolean } = {}): Promise<Entitlement> {\n\t\tif (!options.force && this.isFresh()) return this.snapshot()\n\t\ttry {\n\t\t\treturn await this.refresh()\n\t\t} catch (error) {\n\t\t\tconst err = ExtenshiPayError.from(error)\n\t\t\tthis.options.onError?.(err)\n\t\t\tif (this.held) {\n\t\t\t\tlogger.debug('serving cached entitlement after refresh failure', err.code)\n\t\t\t\treturn this.snapshot()\n\t\t\t}\n\t\t\treturn this.snapshot()\n\t\t}\n\t}\n\n\t/** Fetches the projection from the backend, verifies and stores it. */\n\trefresh(): Promise<Entitlement> {\n\t\tif (!this.inflight) {\n\t\t\tthis.inflight = (async () => {\n\t\t\t\tconst endUserRef = await this.options.getEndUserRef()\n\t\t\t\tconst hint = this.options.getTrialStartHint ? await this.options.getTrialStartHint() : null\n\t\t\t\tconst envelope = await this.options.api.getEntitlement(endUserRef, hint)\n\t\t\t\treturn this.accept(envelope, this.source)\n\t\t\t})().finally(() => {\n\t\t\t\tthis.inflight = null\n\t\t\t})\n\t\t}\n\t\treturn this.inflight\n\t}\n\n\t/** Verifies and stores an envelope obtained elsewhere (e.g. from `claimSession`). */\n\tasync accept(envelope: SignedEntitlement, source: EntitlementSource = this.source): Promise<Entitlement> {\n\t\tif (!isEnvelope(envelope)) {\n\t\t\tthrow new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Malformed entitlement envelope')\n\t\t}\n\t\t// Detach from callers/storage: later mutation must not alter verified state.\n\t\tenvelope = JSON.parse(JSON.stringify(envelope)) as SignedEntitlement\n\t\tif (this.source !== 'mock' && envelope.payload.publishableKey !== this.options.publishableKey) {\n\t\t\tthrow new ExtenshiPayError(\n\t\t\t\tERROR_CODES.INVALID_RESPONSE,\n\t\t\t\t'Entitlement belongs to a different application or lacks a signed application scope',\n\t\t\t)\n\t\t}\n\t\tconst endUserRef = await this.options.getEndUserRef()\n\t\tif (envelope.payload.endUserRef !== endUserRef) {\n\t\t\tthrow new ExtenshiPayError(\n\t\t\t\tERROR_CODES.INVALID_RESPONSE,\n\t\t\t\t'Entitlement issued for a different endUserRef',\n\t\t\t)\n\t\t}\n\t\tconst { verdict, key } =\n\t\t\tthis.source === 'mock'\n\t\t\t\t? { verdict: 'unverified' as const, key: null }\n\t\t\t\t: await verifyWithKeys(envelope, this.options.keys)\n\t\tif (verdict === 'invalid') {\n\t\t\tawait this.discard()\n\t\t\tthrow new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Entitlement signature is invalid')\n\t\t}\n\t\tif (verdict !== 'valid' && this.source !== 'mock') {\n\t\t\tthrow new ExtenshiPayError(\n\t\t\t\tERROR_CODES.VERIFICATION_UNAVAILABLE,\n\t\t\t\t'Entitlement verification requires a trusted key and Ed25519 WebCrypto support',\n\t\t\t)\n\t\t}\n\t\tconst fetchedAt = this.now()\n\t\tconst issuedAt = Date.parse(envelope.payload.issuedAt)\n\t\t// A verified envelope was signed moments ago: its `issuedAt` is the server's clock.\n\t\tif (this.source !== 'mock') this.measureClockSkew(fetchedAt, issuedAt)\n\t\tif (this.source !== 'mock' && (!Number.isFinite(issuedAt) || issuedAt > fetchedAt + MAX_CLOCK_SKEW_MS)) {\n\t\t\tthrow new ExtenshiPayError(\n\t\t\t\tERROR_CODES.INVALID_RESPONSE,\n\t\t\t\t'Entitlement issuedAt is invalid or in the future',\n\t\t\t)\n\t\t}\n\t\tthis.held = { envelope, fetchedAt, verified: verdict === 'valid', key, source }\n\t\tconst record: CacheRecord = { v: CACHE_VERSION, envelope, fetchedAt }\n\t\tawait this.options.storage.set(this.storageKey, JSON.parse(JSON.stringify(record)))\n\t\tthis.backoffMs = 0\n\t\tthis.scheduleDeadline()\n\t\tthis.notifyIfChanged()\n\t\tthis.options.onAccepted?.()\n\t\treturn this.snapshot()\n\t}\n\n\t/** Drain an older installation refresh before changing identity. */\n\tasync settleRefresh(): Promise<void> {\n\t\tawait this.inflight?.catch(() => undefined)\n\t}\n\n\tasync clear(): Promise<void> {\n\t\tthis.held = null\n\t\tthis.scheduleDeadline()\n\t\tthis.lastFingerprint = null\n\t\tawait this.options.storage.remove(this.storageKey)\n\t}\n\n\tstartAutoRefresh(intervalMs: number = Math.max(this.options.cacheTtlMs, MIN_REFRESH_INTERVAL_MS)): void {\n\t\tthis.stopAutoRefresh()\n\t\tthis.autoRefresh = true\n\t\tglobalThis.addEventListener?.('online', this.online)\n\t\tthis.refreshIntervalMs = Math.max(intervalMs, MIN_REFRESH_INTERVAL_MS)\n\t\tthis.schedule(this.refreshIntervalMs)\n\t\tthis.scheduleDeadline()\n\t}\n\n\tstopAutoRefresh(): void {\n\t\tthis.autoRefresh = false\n\t\tglobalThis.removeEventListener?.('online', this.online)\n\t\tthis.refreshGeneration++\n\t\tif (this.deadlineTimer !== null) clearTimeout(this.deadlineTimer)\n\t\tthis.deadlineTimer = null\n\t\tif (this.timer !== null) clearTimeout(this.timer)\n\t\tthis.timer = null\n\t}\n\n\tprivate scheduleDeadline(): void {\n\t\tif (this.deadlineTimer !== null) clearTimeout(this.deadlineTimer)\n\t\tthis.deadlineTimer = null\n\t\tif (!this.autoRefresh || !this.held || !this.held.verified || this.source === 'mock') return\n\t\tconst now = this.now()\n\t\tif (now >= this.offlineDeadline()) return\n\t\tconst deadlines = [\n\t\t\tthis.offlineDeadline(),\n\t\t\t...this.held.envelope.payload.entitlements\n\t\t\t\t.filter((item) => item.status === 'active' || item.status === 'grace')\n\t\t\t\t.map((item) => (item.expiresAt ? Date.parse(item.expiresAt) : NaN)),\n\t\t]\n\t\tconst remaining = Math.min(...deadlines.filter((deadline) => deadline > now)) - now\n\t\tif (!Number.isFinite(remaining) || remaining <= 0) return\n\t\tthis.deadlineTimer = setTimeout(\n\t\t\t() => {\n\t\t\t\tthis.deadlineTimer = null\n\t\t\t\tthis.notifyIfChanged()\n\t\t\t\tthis.scheduleDeadline()\n\t\t\t},\n\t\t\tMath.min(remaining, MAX_TIMER_MS),\n\t\t)\n\t}\n\n\tprivate schedule(delayMs: number): void {\n\t\tconst generation = this.refreshGeneration\n\t\tthis.timer = setTimeout(async () => {\n\t\t\tthis.timer = null\n\t\t\ttry {\n\t\t\t\tawait this.refresh()\n\t\t\t\tif (generation !== this.refreshGeneration) return\n\t\t\t\tthis.schedule(this.refreshIntervalMs)\n\t\t\t} catch (error) {\n\t\t\t\tif (generation !== this.refreshGeneration) return\n\t\t\t\tthis.options.onError?.(ExtenshiPayError.from(error))\n\t\t\t\tthis.backoffMs = Math.min(\n\t\t\t\t\tthis.backoffMs ? this.backoffMs * 2 : this.refreshIntervalMs,\n\t\t\t\t\tMAX_REFRESH_BACKOFF_MS,\n\t\t\t\t)\n\t\t\t\tthis.schedule(this.backoffMs)\n\t\t\t}\n\t\t}, delayMs)\n\t}\n\n\tprivate measureClockSkew(local: number, server: number): void {\n\t\tconst ms = local - server\n\t\tthis.clockSkew =\n\t\t\tNumber.isFinite(ms) && Math.abs(ms) > MAX_CLOCK_SKEW_MS\n\t\t\t\t? { direction: ms > 0 ? 'ahead' : 'behind', ms: Math.abs(ms) }\n\t\t\t\t: null\n\t}\n\n\tprivate async discard(): Promise<void> {\n\t\tthis.held = null\n\t\tthis.scheduleDeadline()\n\t\tawait this.options.storage.remove(this.storageKey)\n\t\tthis.notifyIfChanged()\n\t}\n\n\tprivate fingerprint(): string {\n\t\tconst state = this.snapshot()\n\t\treturn canonicalJson({ items: state.items, requiresOnlineCheck: state.requiresOnlineCheck })\n\t}\n\n\tprivate notifyIfChanged(): void {\n\t\tconst fingerprint = this.fingerprint()\n\t\tif (fingerprint === this.lastFingerprint) return\n\t\tthis.lastFingerprint = fingerprint\n\t\tthis.options.onChange?.(this.snapshot())\n\t}\n\n\tprivate offlineDeadline(): number {\n\t\tif (!this.held) return NaN\n\t\t// fetchedAt is untrusted bookkeeping; it may shorten, never extend, a grant.\n\t\treturn (\n\t\t\tMath.min(this.held.fetchedAt, Date.parse(this.held.envelope.payload.issuedAt)) + this.offlineAgeMs()\n\t\t)\n\t}\n\n\t/** The signed allowance of the held license, or 48 hours when it names none. */\n\tprivate offlineAgeMs(): number {\n\t\tconst seconds = this.held?.envelope.payload.offlineSeconds\n\t\tif (typeof seconds !== 'number' || !Number.isFinite(seconds) || seconds <= 0) return MAX_OFFLINE_AGE_MS\n\t\treturn Math.min(seconds * 1000, MAX_SIGNED_OFFLINE_AGE_MS)\n\t}\n\n\tprivate snapshot(): Entitlement {\n\t\tif (!this.held)\n\t\t\treturn this.clockSkew ? { ...EMPTY_ENTITLEMENT, clockSkew: this.clockSkew } : EMPTY_ENTITLEMENT\n\t\tif (this.source !== 'mock' && !this.held.verified) {\n\t\t\treturn {\n\t\t\t\t...EMPTY_ENTITLEMENT,\n\t\t\t\trequiresOnlineCheck: true,\n\t\t\t\tclockSkew: this.clockSkew,\n\t\t\t\tsource: this.held.source,\n\t\t\t}\n\t\t}\n\t\tconst items = applyLocalExpiry(\n\t\t\tJSON.parse(JSON.stringify(this.held.envelope.payload.entitlements)),\n\t\t\tthis.now(),\n\t\t)\n\t\tconst hasPaidAccess =\n\t\t\tcollectFeatures(items).length > 0 ||\n\t\t\titems.some((item) => item.status === 'active' || item.status === 'grace')\n\t\tconst offlineUntil = this.source === 'mock' || !hasPaidAccess ? null : this.offlineDeadline()\n\t\tconst requiresOnlineCheck =\n\t\t\tofflineUntil !== null &&\n\t\t\t(!Number.isFinite(offlineUntil) ||\n\t\t\t\tthis.now() >= offlineUntil ||\n\t\t\t\tthis.now() < this.held.fetchedAt ||\n\t\t\t\tthis.now() + MAX_CLOCK_SKEW_MS < Date.parse(this.held.envelope.payload.issuedAt))\n\t\treturn {\n\t\t\titems,\n\t\t\tfeatures: requiresOnlineCheck ? [] : collectFeatures(items),\n\t\t\trequiresOnlineCheck,\n\t\t\tofflineUntil,\n\t\t\tclockSkew: this.clockSkew,\n\t\t\tverified: this.held.verified,\n\t\t\tissuedAt: this.held.envelope.payload.issuedAt,\n\t\t\tfetchedAt: this.held.fetchedAt,\n\t\t\tsource: this.held.source,\n\t\t}\n\t}\n}\n","/**\n * Persistent key/value storage for the SDK's own namespace.\n *\n * Preference order: `chrome.storage.local` (Chrome/Edge), `browser.storage.local`\n * (Firefox), `localStorage` (non-extension contexts such as a dev page), then\n * memory. Both promise-returning (MV3, Firefox) and callback-only (MV2) storage\n * APIs are supported.\n */\n\nexport interface StorageAdapter {\n\tget(key: string): Promise<unknown>\n\tset(key: string, value: unknown): Promise<void>\n\tremove(key: string): Promise<void>\n}\n\ntype Items = Record<string, unknown>\n\ninterface StorageArea {\n\tget(keys: string, callback?: (items: Items) => void): unknown\n\tset(items: Items, callback?: () => void): unknown\n\tremove(keys: string, callback?: () => void): unknown\n}\n\ninterface ExtensionGlobals {\n\tchrome?: {\n\t\tstorage?: { local?: StorageArea; sync?: StorageArea }\n\t\truntime?: { lastError?: { message?: string } }\n\t}\n\tbrowser?: { storage?: { local?: StorageArea; sync?: StorageArea } }\n}\n\nfunction extensionGlobals(): ExtensionGlobals {\n\treturn globalThis as ExtensionGlobals\n}\n\nfunction isThenable<T>(value: unknown): value is Promise<T> {\n\treturn !!value && typeof (value as Promise<T>).then === 'function'\n}\n\n/** Runs a storage-area call that may either return a promise or expect a callback. */\nfunction areaCall<T>(\n\tdirect: () => unknown,\n\twithCallback: (callback: (value: T) => void) => void,\n): Promise<T> {\n\tconst result = direct()\n\tif (isThenable<T>(result)) return result\n\treturn new Promise<T>((resolve, reject) => {\n\t\twithCallback((value) => {\n\t\t\tconst lastError = extensionGlobals().chrome?.runtime?.lastError\n\t\t\tif (lastError) reject(new Error(lastError.message ?? 'storage error'))\n\t\t\telse resolve(value)\n\t\t})\n\t})\n}\n\nexport class ExtensionStorage implements StorageAdapter {\n\tconstructor(private readonly area: StorageArea) {}\n\n\tasync get(key: string): Promise<unknown> {\n\t\tconst items = await areaCall<Items>(\n\t\t\t() => this.area.get(key),\n\t\t\t(cb) => this.area.get(key, cb),\n\t\t)\n\t\treturn items?.[key]\n\t}\n\n\tasync set(key: string, value: unknown): Promise<void> {\n\t\tawait areaCall<void>(\n\t\t\t() => this.area.set({ [key]: value }),\n\t\t\t(cb) => this.area.set({ [key]: value }, cb),\n\t\t)\n\t}\n\n\tasync remove(key: string): Promise<void> {\n\t\tawait areaCall<void>(\n\t\t\t() => this.area.remove(key),\n\t\t\t(cb) => this.area.remove(key, cb),\n\t\t)\n\t}\n}\n\nexport class LocalStorageAdapter implements StorageAdapter {\n\tconstructor(private readonly store: Storage) {}\n\n\tasync get(key: string): Promise<unknown> {\n\t\tconst raw = this.store.getItem(key)\n\t\tif (raw === null) return undefined\n\t\ttry {\n\t\t\treturn JSON.parse(raw)\n\t\t} catch {\n\t\t\treturn undefined\n\t\t}\n\t}\n\n\tasync set(key: string, value: unknown): Promise<void> {\n\t\tthis.store.setItem(key, JSON.stringify(value))\n\t}\n\n\tasync remove(key: string): Promise<void> {\n\t\tthis.store.removeItem(key)\n\t}\n}\n\nexport class MemoryStorage implements StorageAdapter {\n\tprivate readonly map = new Map<string, unknown>()\n\n\tasync get(key: string): Promise<unknown> {\n\t\treturn this.map.get(key)\n\t}\n\n\tasync set(key: string, value: unknown): Promise<void> {\n\t\tthis.map.set(key, value)\n\t}\n\n\tasync remove(key: string): Promise<void> {\n\t\tthis.map.delete(key)\n\t}\n}\n\n/**\n * The browser's synced storage (`storage.sync`), or null outside an extension. The SDK keeps\n * only the trial start there (never `endUserRef`), so devices on one synced account share the\n * trial. Uninstalling clears it from the account, so it does not survive a reinstall.\n */\nexport function createSyncStorage(): StorageAdapter | null {\n\tconst g = extensionGlobals()\n\tconst area = g.chrome?.storage?.sync ?? g.browser?.storage?.sync\n\treturn area ? new ExtensionStorage(area) : null\n}\n\nexport function createStorage(): StorageAdapter {\n\tconst g = extensionGlobals()\n\tconst area = g.chrome?.storage?.local ?? g.browser?.storage?.local\n\tif (area) return new ExtensionStorage(area)\n\ttry {\n\t\tconst store = (globalThis as { localStorage?: Storage }).localStorage\n\t\tif (store && typeof store.getItem === 'function') return new LocalStorageAdapter(store)\n\t} catch {\n\t\t// Access to localStorage can throw in sandboxed frames.\n\t}\n\treturn new MemoryStorage()\n}\n","/** Email stays on the hosted page. Only this extension context holds the claim secret. */\nimport type { PayApi } from '../api/pay-api.js'\nimport type { StorageAdapter } from '../core/storage.js'\nimport { ExtensionStorage, MemoryStorage } from '../core/storage.js'\nimport type { PayStorageGrant, SignedEntitlement } from '../types/contract.js'\nimport type { CloudBackupState, Entitlement, RestoreOptions, RestoreResult } from '../types/entitlement.js'\nimport { ERROR_CODES, ExtenshiPayError } from '../types/errors.js'\nimport { openInNewTab } from './checkout.js'\n\ntype SessionArea = ConstructorParameters<typeof ExtensionStorage>[0]\n\n/** storage.local is exposed to content scripts by default. Never put a recovery proof there. */\nexport function createRecoveryStorage(): StorageAdapter {\n\tconst g = globalThis as {\n\t\tchrome?: { storage?: { session?: SessionArea }; tabs?: unknown }\n\t\tbrowser?: { storage?: { session?: SessionArea }; tabs?: unknown }\n\t}\n\tconst extension = g.chrome?.tabs ? g.chrome : g.browser?.tabs ? g.browser : null\n\treturn extension?.storage?.session ? new ExtensionStorage(extension.storage.session) : new MemoryStorage()\n}\n\ninterface PendingRestore {\n\tsessionId: string\n\tclaimSecret: string\n\texpiresAt: string\n}\nexport interface RecoveryManagerOptions {\n\tapi: PayApi\n\t/** The user's language, for the hosted recovery page and its email. */\n\tlocale?: string | null\n\tstorage: StorageAdapter\n\tpublishableKey: string\n\tonComplete: (endUserRef: string, envelope: SignedEntitlement) => Promise<Entitlement>\n\t/** Runs after `onComplete` accepted the entitlement, with the claim's storage grant (if any). */\n\tonStorageGrant?: (grant: PayStorageGrant | undefined) => Promise<CloudBackupState | undefined>\n\topenUrl?: (url: string) => void | Promise<void>\n\tnow?: () => number\n}\n\nexport class RecoveryManager {\n\tprivate active = false\n\tprivate stopped = false\n\tprivate wake: (() => void) | null = null\n\tconstructor(private readonly options: RecoveryManagerOptions) {}\n\tget pendingKey(): string {\n\t\treturn `extenshi-pay:${this.options.publishableKey}:pendingRestore`\n\t}\n\tisActive(): boolean {\n\t\treturn this.active\n\t}\n\tstop(): void {\n\t\tthis.stopped = true\n\t\tthis.wake?.()\n\t}\n\n\tasync open(options: RestoreOptions = {}): Promise<RestoreResult> {\n\t\tif (this.active)\n\t\t\tthrow new ExtenshiPayError(ERROR_CODES.INVALID_REQUEST, 'Recovery is already in progress')\n\t\tthis.active = true\n\t\tthis.stopped = false\n\t\ttry {\n\t\t\t// A caller from a content script must route the action to its own background;\n\t\t\t// never return this manager's internal state through that message bridge.\n\t\t\tconst g = globalThis as {\n\t\t\t\tchrome?: { runtime?: { id?: string }; tabs?: unknown }\n\t\t\t\tbrowser?: { runtime?: { id?: string }; tabs?: unknown }\n\t\t\t}\n\t\t\tif ((g.chrome?.runtime?.id || g.browser?.runtime?.id) && !(g.chrome?.tabs || g.browser?.tabs))\n\t\t\t\tthrow new ExtenshiPayError(\n\t\t\t\t\tERROR_CODES.INVALID_REQUEST,\n\t\t\t\t\t'Start recovery in an extension page or background context',\n\t\t\t\t)\n\t\t\tconst cryptoApi = globalThis.crypto\n\t\t\tif (!cryptoApi?.subtle)\n\t\t\t\tthrow new ExtenshiPayError(\n\t\t\t\t\tERROR_CODES.INVALID_REQUEST,\n\t\t\t\t\t'Secure recovery is unavailable in this browser',\n\t\t\t\t)\n\t\t\tconst secret = Array.from(cryptoApi.getRandomValues(new Uint8Array(32)), (b) =>\n\t\t\t\tb.toString(16).padStart(2, '0'),\n\t\t\t).join('')\n\t\t\tconst hash = await cryptoApi.subtle.digest('SHA-256', new TextEncoder().encode(secret))\n\t\t\tconst challenge = Array.from(new Uint8Array(hash), (b) => b.toString(16).padStart(2, '0')).join('')\n\t\t\tconst created = await this.options.api.createRestoreSession(\n\t\t\t\tchallenge,\n\t\t\t\tthis.options.locale,\n\t\t\t\toptions.purpose,\n\t\t\t)\n\t\t\tif (!Number.isFinite(Date.parse(created.expiresAt)))\n\t\t\t\tthrow new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Invalid recovery expiry')\n\t\t\tconst pending = { sessionId: created.sessionId, expiresAt: created.expiresAt, claimSecret: secret }\n\t\t\tawait this.options.storage.set(this.pendingKey, pending)\n\t\t\tawait (options.openUrl ?? this.options.openUrl ?? openInNewTab)(created.url)\n\t\t\treturn await this.poll(pending, options)\n\t\t} finally {\n\t\t\tthis.active = false\n\t\t}\n\t}\n\n\tasync resumePending(): Promise<RestoreResult | null> {\n\t\tif (this.active || this.stopped) return null\n\t\tconst raw = (await this.options.storage.get(this.pendingKey)) as Partial<PendingRestore> | undefined\n\t\tif (!raw || this.active || this.stopped) return null\n\t\tif (\n\t\t\ttypeof raw.sessionId !== 'string' ||\n\t\t\ttypeof raw.claimSecret !== 'string' ||\n\t\t\t!/^[a-f0-9]{64}$/.test(raw.claimSecret) ||\n\t\t\t!Number.isFinite(Date.parse(raw.expiresAt ?? ''))\n\t\t) {\n\t\t\tawait this.options.storage.remove(this.pendingKey)\n\t\t\treturn null\n\t\t}\n\t\tthis.active = true\n\t\tthis.stopped = false\n\t\ttry {\n\t\t\treturn await this.poll(raw as PendingRestore, {})\n\t\t} finally {\n\t\t\tthis.active = false\n\t\t}\n\t}\n\n\tprivate async poll(pending: PendingRestore, options: RestoreOptions): Promise<RestoreResult> {\n\t\tconst now = this.options.now ?? Date.now\n\t\tconst expires = Date.parse(pending.expiresAt)\n\t\tconst deadline = Math.min(expires, now() + (options.timeoutMs ?? 10 * 60 * 1000))\n\t\tlet delay = 0\n\t\twhile (!this.stopped && !options.signal?.aborted && now() < deadline) {\n\t\t\tif (delay)\n\t\t\t\tawait new Promise<void>((resolve) => {\n\t\t\t\t\tconst done = () => {\n\t\t\t\t\t\tclearTimeout(timer)\n\t\t\t\t\t\toptions.signal?.removeEventListener('abort', done)\n\t\t\t\t\t\tthis.wake = null\n\t\t\t\t\t\tresolve()\n\t\t\t\t\t}\n\t\t\t\t\tconst timer = setTimeout(done, Math.min(delay, Math.max(0, deadline - now())))\n\t\t\t\t\tthis.wake = done\n\t\t\t\t\toptions.signal?.addEventListener('abort', done, { once: true })\n\t\t\t\t})\n\t\t\tif (this.stopped || options.signal?.aborted || now() >= deadline) break\n\t\t\ttry {\n\t\t\t\tconst claim = await this.options.api.claimRestoreSession(pending.sessionId, pending.claimSecret)\n\t\t\t\tif (this.stopped || options.signal?.aborted) break\n\t\t\t\tif (claim.state === 'complete') {\n\t\t\t\t\tconst entitlement = await this.options.onComplete(claim.endUserRef, claim.entitlement)\n\t\t\t\t\tconst cloudBackup = await this.options.onStorageGrant?.(claim.storage)\n\t\t\t\t\tawait this.options.storage.remove(this.pendingKey)\n\t\t\t\t\treturn { state: 'complete', entitlement, ...(cloudBackup ? { cloudBackup } : {}) }\n\t\t\t\t}\n\t\t\t\tif (claim.state !== 'pending')\n\t\t\t\t\tthrow new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Invalid recovery response')\n\t\t\t\tdelay = Math.max(100, options.pollIntervalMs ?? 2_000)\n\t\t\t} catch (error) {\n\t\t\t\tconst err = ExtenshiPayError.from(error)\n\t\t\t\tif (\n\t\t\t\t\t![\n\t\t\t\t\t\tERROR_CODES.NETWORK_ERROR,\n\t\t\t\t\t\tERROR_CODES.TIMEOUT,\n\t\t\t\t\t\tERROR_CODES.GATEWAY_UNAVAILABLE,\n\t\t\t\t\t\tERROR_CODES.RATE_LIMITED,\n\t\t\t\t\t].some((code) => code === err.code)\n\t\t\t\t)\n\t\t\t\t\tthrow err\n\t\t\t\tdelay = Math.max(2_000, (err.retryAfterSec ?? 5) * 1000)\n\t\t\t}\n\t\t}\n\t\tif (now() >= expires) await this.options.storage.remove(this.pendingKey)\n\t\treturn {\n\t\t\tstate: this.stopped || options.signal?.aborted ? 'canceled' : now() >= expires ? 'expired' : 'timeout',\n\t\t}\n\t}\n}\n","import type { PayEntitlementItem, PayOfferDto, PaySellerPublic, PayWithdrawalWaiver } from './contract.js'\nimport type { ExtenshiPayError } from './errors.js'\n\nexport type LogLevel = 'silent' | 'error' | 'warn' | 'info' | 'debug'\n\n/** Reserved for future routing; today every environment talks to the same BFF. */\nexport type Environment = 'production' | 'sandbox' | 'development'\n\nexport interface ThemeConfig {\n\t/** `auto` follows `prefers-color-scheme`. */\n\tmode?: 'light' | 'dark' | 'auto'\n\tprimaryColor?: string\n\tfontFamily?: string\n\tborderRadius?: string\n\t/** Appended verbatim inside the paywall's shadow root. */\n\tcustomCss?: string\n}\n\n/** Offline development data used when `mock: true`. */\nexport interface MockData {\n\tentitlements?: PayEntitlementItem[]\n\toffers?: PayOfferDto[]\n\tprojectName?: string\n\t/** Defaults to true. */\n\tcheckoutEnabled?: boolean\n\t/** How many `claimSession` polls answer `pending` before a mock checkout completes (default 1). */\n\tclaimAfterPolls?: number\n\t/**\n\t * Offer's withdrawal waiver (default: required, current version, so the\n\t * paywall previews the checkbox). `null` previews a seller outside the EEA/UK.\n\t */\n\twithdrawalWaiver?: PayWithdrawalWaiver | null\n\t/**\n\t * Seller details for the paywall, the license panel and the waiver text.\n\t * Omitted, the offer carries none (as from an older server); `null`\n\t * previews a seller without public details, so the paywall disables purchase.\n\t */\n\tseller?: PaySellerPublic | null\n\t/**\n\t * Previews a server trial: `days` long, started at `startedAt` (default: when the mock is\n\t * created). Omitted, the mock application has no trial.\n\t */\n\ttrial?: { days: number; startedAt?: string }\n}\n\nexport interface ExtenshiPayConfig {\n\t/** `pk_ext_` + 32 hex characters, from the project's Monetization tab. */\n\tpublishableKey: string\n\t/** Defaults to `https://bff.extenshi.io`. */\n\tapiUrl?: string\n\t/** Bundled raw Ed25519 public key (base64). Enables verified cache use after an offline restart. */\n\tentitlementPublicKey?: string\n\tenvironment?: Environment\n\t/** Shorthand for `logLevel: 'debug'`. */\n\tdebug?: boolean\n\tlogLevel?: LogLevel\n\t/** How long a fetched entitlement is served without a network round-trip (default 1 hour). */\n\tcacheTtlMs?: number\n\t/** BCP-47 tag such as `en` or `de-DE`; sent to the backend for checkout/offer copy and used for price formatting. */\n\tlocale?: string\n\tmock?: boolean\n\tmockData?: MockData\n\tonReady?: () => void\n\tonError?: (error: ExtenshiPayError) => void\n\ttheme?: ThemeConfig\n\t/** Days before the trial's end that `trial:ending` fires (default 2; 0 turns it off). */\n\ttrialEndingDays?: number\n\t/**\n\t * Keep the trial's start date in `storage.sync` and send it back on license checks, so\n\t * other devices on the same synced browser account share the trial (default true).\n\t * Only the date is synced, never the installation id. A reinstall still restarts the\n\t * trial: uninstalling clears `storage.sync`.\n\t */\n\tsyncTrialStart?: boolean\n}\n\nexport interface ResolvedConfig {\n\tpublishableKey: string\n\tapiUrl: string\n\tentitlementPublicKey: string | null\n\tenvironment: Environment\n\tdebug: boolean\n\tlogLevel: LogLevel\n\tcacheTtlMs: number\n\tlocale: string | null\n\tmock: boolean\n\tmockData: MockData | null\n\ttheme: ThemeConfig\n\ttrialEndingDays: number\n\tsyncTrialStart: boolean\n}\n\nexport const DEFAULT_API_URL = 'https://bff.extenshi.io'\nexport const DEFAULT_CACHE_TTL_MS = 60 * 60 * 1000\nexport const MAX_CACHE_TTL_MS = 7 * 24 * 60 * 60 * 1000\nexport const DEFAULT_TRIAL_ENDING_DAYS = 2\n","/** Kept in sync with package.json by tests/unit/version.test.ts. */\nexport const VERSION = '0.11.0'\n","/**\n * The user's language as the SDK sends it. Kept apart from the paywall\n * dictionary (../paywall/i18n.ts) so the Lite and core bundles, which never\n * render UI, do not carry the translations.\n */\n\n/** What the backend (and older backends) accept as a locale: `de`, `pt-BR`, `zh-CN`. */\nconst WIRE_LOCALE_RE = /^[a-z]{2}(-[A-Za-z]{2,4})?$/\n\n/**\n * A browser tag as the SDK sends it: `pt_BR` → `pt-BR`, `es-419` → `es`,\n * `zh-Hant-TW` → `zh-TW`; null for anything that is not a language tag.\n */\nexport function wireLocale(raw: unknown): string | null {\n\tif (typeof raw !== 'string') return null\n\tconst parts = raw.trim().replace(/_/g, '-').split('-').filter(Boolean)\n\tconst lang = parts[0]?.toLowerCase()\n\tif (!lang || !/^[a-z]{2}$/.test(lang)) return null\n\tconst script = parts\n\t\t.slice(1)\n\t\t.find((p) => /^[A-Za-z]{4}$/.test(p))\n\t\t?.toLowerCase()\n\t// zh-Hant without a region is Traditional Chinese: keep that, never let it read as zh-CN.\n\tconst region =\n\t\tparts.slice(1).find((p) => /^[A-Za-z]{2}$/.test(p)) ??\n\t\t(lang === 'zh' && script === 'hant' ? 'TW' : undefined)\n\tconst tag = region ? `${lang}-${region.toUpperCase()}` : lang\n\treturn WIRE_LOCALE_RE.test(tag) ? tag : lang\n}\n\n/** The browser UI language (`chrome.i18n.getUILanguage()`, else `navigator.language`), or null. */\nexport function browserLocale(): string | null {\n\tconst g = globalThis as {\n\t\tchrome?: { i18n?: { getUILanguage?: () => string } }\n\t\tbrowser?: { i18n?: { getUILanguage?: () => string } }\n\t\tnavigator?: { language?: string }\n\t}\n\ttry {\n\t\tconst ui = g.chrome?.i18n?.getUILanguage?.() ?? g.browser?.i18n?.getUILanguage?.()\n\t\tif (ui) return wireLocale(ui)\n\t} catch {\n\t\t/* Not an extension context. */\n\t}\n\treturn wireLocale(g.navigator?.language)\n}\n","import { PUBLIC_KEY_RE } from '../payment/signature.js'\nimport {\n\tDEFAULT_API_URL,\n\tDEFAULT_CACHE_TTL_MS,\n\tDEFAULT_TRIAL_ENDING_DAYS,\n\ttype ExtenshiPayConfig,\n\tMAX_CACHE_TTL_MS,\n\ttype ResolvedConfig,\n} from '../types/config.js'\nimport { isPayPublishableKey } from '../types/contract.js'\nimport { ERROR_CODES, ExtenshiPayError } from '../types/errors.js'\nimport { browserLocale } from './locale.js'\n\nconst ENVIRONMENTS = new Set(['production', 'sandbox', 'development'])\nconst LOG_LEVELS = new Set(['silent', 'error', 'warn', 'info', 'debug'])\nconst THEME_MODES = new Set(['light', 'dark', 'auto'])\n/** Same shape the BFF accepts (`en`, `de-DE`, `zh-Hant`). */\nexport const LOCALE_RE = /^[a-z]{2}(-[A-Za-z]{2,4})?$/\n\nfunction isHttpUrl(value: string): boolean {\n\ttry {\n\t\tconst url = new URL(value)\n\t\treturn url.protocol === 'https:' || url.protocol === 'http:'\n\t} catch {\n\t\treturn false\n\t}\n}\n\nexport function resolveConfig(input: ExtenshiPayConfig): ResolvedConfig {\n\tconst errors: string[] = []\n\tif (!input || typeof input !== 'object') {\n\t\tthrow new ExtenshiPayError(ERROR_CODES.INVALID_CONFIG, 'ExtenshiPay config must be an object')\n\t}\n\n\tif (!isPayPublishableKey(input.publishableKey)) {\n\t\terrors.push('publishableKey must look like pk_ext_<32 hex characters>')\n\t}\n\n\tconst apiUrl = (input.apiUrl ?? DEFAULT_API_URL).replace(/\\/+$/, '')\n\tif (!isHttpUrl(apiUrl)) errors.push('apiUrl must be an http(s) URL')\n\n\tconst entitlementPublicKey = input.entitlementPublicKey ?? null\n\tif (entitlementPublicKey !== null && !PUBLIC_KEY_RE.test(entitlementPublicKey)) {\n\t\terrors.push('entitlementPublicKey must be a base64-encoded 32-byte Ed25519 public key')\n\t}\n\n\tconst environment = input.environment ?? 'production'\n\tif (!ENVIRONMENTS.has(environment)) errors.push('environment must be production, sandbox or development')\n\n\tconst logLevel = input.logLevel ?? 'warn'\n\tif (!LOG_LEVELS.has(logLevel)) errors.push('logLevel must be silent, error, warn, info or debug')\n\n\tconst cacheTtlMs = input.cacheTtlMs ?? DEFAULT_CACHE_TTL_MS\n\tif (!Number.isFinite(cacheTtlMs) || cacheTtlMs < 0 || cacheTtlMs > MAX_CACHE_TTL_MS) {\n\t\terrors.push(`cacheTtlMs must be between 0 and ${MAX_CACHE_TTL_MS}`)\n\t}\n\n\t// Default: the browser UI language, as README promises (it. 13 T10 L2).\n\t// `null` still opts out explicitly: prices then use the runtime default\n\t// and the paywall reads English.\n\tconst locale = input.locale === undefined ? browserLocale() : input.locale\n\tif (locale !== null && !LOCALE_RE.test(locale))\n\t\terrors.push('locale must be a BCP-47 tag such as en or de-DE')\n\n\tconst theme = input.theme ?? {}\n\tif (theme.mode !== undefined && !THEME_MODES.has(theme.mode))\n\t\terrors.push('theme.mode must be light, dark or auto')\n\n\tconst trialEndingDays = input.trialEndingDays ?? DEFAULT_TRIAL_ENDING_DAYS\n\tif (!Number.isInteger(trialEndingDays) || trialEndingDays < 0 || trialEndingDays > 365)\n\t\terrors.push('trialEndingDays must be a whole number of days between 0 and 365')\n\n\tif (\n\t\tinput.mock &&\n\t\tinput.mockData !== undefined &&\n\t\t(typeof input.mockData !== 'object' || input.mockData === null)\n\t) {\n\t\terrors.push('mockData must be an object')\n\t}\n\n\tif (errors.length > 0) {\n\t\tthrow new ExtenshiPayError(ERROR_CODES.INVALID_CONFIG, `Invalid ExtenshiPay config: ${errors.join('; ')}`)\n\t}\n\n\treturn {\n\t\tpublishableKey: input.publishableKey,\n\t\tapiUrl,\n\t\tentitlementPublicKey,\n\t\tenvironment,\n\t\tdebug: input.debug === true,\n\t\tlogLevel,\n\t\tcacheTtlMs,\n\t\tlocale,\n\t\tmock: input.mock === true,\n\t\tmockData: input.mock ? (input.mockData ?? {}) : null,\n\t\ttheme,\n\t\ttrialEndingDays,\n\t\tsyncTrialStart: input.syncTrialStart !== false,\n\t}\n}\n","import { logger } from '../utils/logger.js'\n\nexport type Listener<T> = (payload: T) => void\ntype AnyListener = (payload: never) => void\n\nexport class EventEmitter<Events extends object> {\n\tprivate readonly listeners = new Map<keyof Events, Set<AnyListener>>()\n\n\ton<K extends keyof Events>(event: K, listener: Listener<Events[K]>): () => void {\n\t\tlet set = this.listeners.get(event)\n\t\tif (!set) {\n\t\t\tset = new Set()\n\t\t\tthis.listeners.set(event, set)\n\t\t}\n\t\tset.add(listener as AnyListener)\n\t\treturn () => this.off(event, listener)\n\t}\n\n\tonce<K extends keyof Events>(event: K, listener: Listener<Events[K]>): () => void {\n\t\tconst off = this.on(event, (payload) => {\n\t\t\toff()\n\t\t\tlistener(payload)\n\t\t})\n\t\treturn off\n\t}\n\n\toff<K extends keyof Events>(event: K, listener: Listener<Events[K]>): void {\n\t\tthis.listeners.get(event)?.delete(listener as AnyListener)\n\t}\n\n\temit<K extends keyof Events>(event: K, payload: Events[K]): void {\n\t\tconst set = this.listeners.get(event)\n\t\tif (!set) return\n\t\tfor (const listener of [...set]) {\n\t\t\tconst fn = listener as Listener<Events[K]>\n\t\t\ttry {\n\t\t\t\tfn(payload)\n\t\t\t} catch (error) {\n\t\t\t\tlogger.error(`listener for \"${String(event)}\" threw`, error)\n\t\t\t}\n\t\t}\n\t}\n\n\tremoveAll(): void {\n\t\tthis.listeners.clear()\n\t}\n}\n","/**\n * Every string the SDK shows to the USER of an extension — paywall, license\n * dialog, billing-profile picker, seller details — in the end-user languages\n * (ROADMAP it. 13 T10, stage L2; closes it. 12 T9). Developer-facing error\n * messages stay English.\n *\n * Self-contained on purpose: the SDK ships inside third-party extensions with\n * no runtime dependencies and no remote code, so the dictionary is compiled\n * in. Placeholders are `{name}`, `{date}`, `{status}`. A missing\n * translation falls back to English, never to an empty string. The same\n * languages as the hosted pages (shared-types END_USER_LOCALES); keep the\n * lists in sync.\n */\n\nexport { browserLocale, wireLocale } from '../core/locale.js'\n\nimport { wireLocale } from '../core/locale.js'\n\nexport const SDK_LOCALES = ['en', 'es', 'pt-BR', 'fr', 'de', 'it', 'ru', 'ja', 'ko', 'zh-CN', 'ar'] as const\nexport type SdkLocale = (typeof SDK_LOCALES)[number]\n\nexport const SDK_STRINGS_EN = {\n\ttitle: 'Unlock premium features',\n\tdescription: 'Upgrade to get full access to this extension.',\n\tupgrade: 'Upgrade',\n\tcancel: 'Not now',\n\tdismiss: 'Dismiss',\n\tremindLater: 'Remind me later',\n\tcontinueFree: 'Continue with the free version',\n\tcheckoutUnavailable: 'Purchases are temporarily unavailable',\n\tperiodMonth: '/month',\n\tperiodYear: '/year',\n\tperiodOnce: 'one-time',\n\tfooter: 'Secure checkout opens in a new tab.',\n\trestorePurchase: 'Restore purchase',\n\tfeaturesHeading: 'Premium Features',\n\tplansHeading: 'Choose Your Plan',\n\tfreePlanName: 'Free',\n\tpremiumPlanName: 'Premium',\n\tpopularBadge: 'Most Popular',\n\tunlockHeading: 'Unlock Premium Features',\n\tsimulatePurchase: 'Simulate purchase',\n\tmockNotice: 'Development preview: licenses and payments are simulated. No payment will be taken.',\n\tsellerProvidedBy: 'License provided by {name}',\n\tsellerUnavailable: 'License provider details are unavailable.',\n\tsellerSupport: 'Extension support',\n\tsellerTerms: 'License terms',\n\tsellerRefunds: 'Refund policy',\n\tsellerRole:\n\t\t'The author handles extension functionality and license commitments. Extenshi provides payment and license recovery tools.',\n\tlicenseTitle: 'Your license',\n\tlicenseFallbackName: 'Extension license',\n\tlicenseNone: 'No license found on this installation.',\n\tkindOneTime: 'One-time purchase',\n\tkindLifetime: 'Lifetime',\n\tkindSubscription: 'Subscription',\n\tkindLicense: 'License',\n\tstatusLine: 'Status: {status}',\n\tstatusActive: 'active',\n\tstatusGrace: 'grace period',\n\tstatusExpired: 'expired',\n\tstatusNone: 'no access',\n\taccessEnded: 'Access ended {date}',\n\taccessUntil: 'Access until {date}',\n\taccessRecordedEnd: 'Recorded end date {date}',\n\tsubscriptionLine: 'Subscription: {status}',\n\trenewalCanceled: 'Renewal canceled',\n\tperiodEnds: 'Period ends {date}',\n\tsubActive: 'active',\n\tsubTrialing: 'trial',\n\tsubPastDue: 'payment overdue',\n\tsubCanceled: 'canceled',\n\tsubUnpaid: 'unpaid',\n\tsubIncomplete: 'incomplete',\n\tsubIncompleteExpired: 'payment not completed',\n\tsubPaused: 'paused',\n\tlicenseOffline:\n\t\t'Connect to the internet to verify your license. Paid features are paused after 48 hours without a successful check. Your purchase has not expired.',\n\tlicenseCached: 'Showing saved license information.',\n\tlicenseFresh: 'Subscription information reflects the latest processed payment update.',\n\tactionFailed: 'Unable to complete the request. Please try again or contact extension support.',\n\tmanageBilling: 'Manage billing',\n\tnoPortal: 'No billing portal opened. You can retry or contact extension support.',\n\tclose: 'Close',\n\tpickerTitle: 'Choose a billing profile',\n\tpickerDescription:\n\t\t'Separate purchases can have separate billing profiles. Choose one to manage its subscriptions and payment details.',\n\tpickerFirstRecorded: 'First recorded {date}',\n\tpickerCancel: 'Cancel',\n\ttrialEndedTitle: 'Your free trial has ended',\n\ttrialEndedDescription:\n\t\t'The extension’s tools are paused. Your settings are kept and will be there when you upgrade.',\n\ttrialEndedFeedback: 'Share feedback',\n}\n\nexport type SdkStringKey = keyof typeof SDK_STRINGS_EN\nexport type SdkStrings = Record<SdkStringKey, string>\n\n// BEGIN GENERATED TRANSLATIONS\nconst TRANSLATIONS: Partial<Record<Exclude<SdkLocale, 'en'>, SdkStrings>> = {\n\tes: {\n\t\ttitle: 'Desbloquea las funciones premium',\n\t\tdescription: 'Mejora tu plan para obtener acceso completo a esta extensión.',\n\t\tupgrade: 'Mejorar plan',\n\t\tcancel: 'Ahora no',\n\t\tdismiss: 'Descartar',\n\t\tremindLater: 'Recordármelo más tarde',\n\t\tcontinueFree: 'Seguir con la versión gratuita',\n\t\tcheckoutUnavailable: 'Compras no disponibles temporalmente',\n\t\tperiodMonth: '/mes',\n\t\tperiodYear: '/año',\n\t\tperiodOnce: 'pago único',\n\t\tfooter: 'El pago seguro se abre en una pestaña nueva.',\n\t\trestorePurchase: 'Restaurar compra',\n\t\tfeaturesHeading: 'Funciones premium',\n\t\tplansHeading: 'Elige tu plan',\n\t\tfreePlanName: 'Gratis',\n\t\tpremiumPlanName: 'Premium',\n\t\tpopularBadge: 'Más popular',\n\t\tunlockHeading: 'Desbloquea las funciones premium',\n\t\tsimulatePurchase: 'Simular compra',\n\t\tmockNotice:\n\t\t\t'Vista previa de desarrollo: las licencias y los pagos son simulados. No se realizará ningún cobro.',\n\t\tsellerProvidedBy: 'Licencia proporcionada por {name}',\n\t\tsellerUnavailable: 'Los datos del proveedor de la licencia no están disponibles.',\n\t\tsellerSupport: 'Asistencia de la extensión',\n\t\tsellerTerms: 'Condiciones de licencia',\n\t\tsellerRefunds: 'Política de reembolsos',\n\t\tsellerRole:\n\t\t\t'El autor se encarga de las funciones de la extensión y de los compromisos de la licencia. Extenshi proporciona las herramientas de pago y de recuperación de licencias.',\n\t\tlicenseTitle: 'Tu licencia',\n\t\tlicenseFallbackName: 'Licencia de la extensión',\n\t\tlicenseNone: 'No se ha encontrado ninguna licencia en esta instalación.',\n\t\tkindOneTime: 'Compra única',\n\t\tkindLifetime: 'Licencia vitalicia',\n\t\tkindSubscription: 'Suscripción',\n\t\tkindLicense: 'Licencia',\n\t\tstatusLine: 'Estado: {status}',\n\t\tstatusActive: 'activo',\n\t\tstatusGrace: 'período de gracia',\n\t\tstatusExpired: 'caducado',\n\t\tstatusNone: 'sin acceso',\n\t\taccessEnded: 'Acceso finalizado el {date}',\n\t\taccessUntil: 'Acceso hasta el {date}',\n\t\taccessRecordedEnd: 'Fecha de finalización registrada: {date}',\n\t\tsubscriptionLine: 'Suscripción: {status}',\n\t\trenewalCanceled: 'Renovación cancelada',\n\t\tperiodEnds: 'El período finaliza el {date}',\n\t\tsubActive: 'activa',\n\t\tsubTrialing: 'en período de prueba',\n\t\tsubPastDue: 'pago vencido',\n\t\tsubCanceled: 'cancelada',\n\t\tsubUnpaid: 'sin pagar',\n\t\tsubIncomplete: 'incompleta',\n\t\tsubIncompleteExpired: 'pago no completado',\n\t\tsubPaused: 'en pausa',\n\t\tlicenseOffline:\n\t\t\t'Conéctate a internet para verificar tu licencia. Las funciones de pago se suspenden si pasan 48 horas sin una verificación correcta. Tu compra no ha caducado.',\n\t\tlicenseCached: 'Se muestra la información de licencia guardada.',\n\t\tlicenseFresh: 'La información de la suscripción refleja la última actualización de pago procesada.',\n\t\tactionFailed:\n\t\t\t'No se pudo completar la solicitud. Inténtalo de nuevo o ponte en contacto con la asistencia de la extensión.',\n\t\tmanageBilling: 'Gestionar facturación',\n\t\tnoPortal:\n\t\t\t'No se abrió ningún portal de facturación. Puedes volver a intentarlo o ponerte en contacto con la asistencia de la extensión.',\n\t\tclose: 'Cerrar',\n\t\tpickerTitle: 'Elige un perfil de facturación',\n\t\tpickerDescription:\n\t\t\t'Las compras independientes pueden tener perfiles de facturación distintos. Elige uno para gestionar sus suscripciones y datos de pago.',\n\t\tpickerFirstRecorded: 'Registrado por primera vez el {date}',\n\t\tpickerCancel: 'Cancelar',\n\t\ttrialEndedTitle: 'Tu prueba gratuita ha terminado',\n\t\ttrialEndedDescription:\n\t\t\t'Las herramientas de la extensión están en pausa. Tu configuración se conserva y la encontrarás igual cuando mejores tu plan.',\n\t\ttrialEndedFeedback: 'Enviar comentarios',\n\t},\n\t'pt-BR': {\n\t\ttitle: 'Desbloqueie os recursos premium',\n\t\tdescription: 'Faça o upgrade para ter acesso completo a esta extensão.',\n\t\tupgrade: 'Fazer upgrade',\n\t\tcancel: 'Agora não',\n\t\tdismiss: 'Dispensar',\n\t\tremindLater: 'Lembrar mais tarde',\n\t\tcontinueFree: 'Continuar com a versão gratuita',\n\t\tcheckoutUnavailable: 'Compras temporariamente indisponíveis',\n\t\tperiodMonth: '/mês',\n\t\tperiodYear: '/ano',\n\t\tperiodOnce: 'pagamento único',\n\t\tfooter: 'O checkout seguro abre em uma nova guia.',\n\t\trestorePurchase: 'Restaurar compra',\n\t\tfeaturesHeading: 'Recursos premium',\n\t\tplansHeading: 'Escolha seu plano',\n\t\tfreePlanName: 'Gratuito',\n\t\tpremiumPlanName: 'Premium',\n\t\tpopularBadge: 'Mais popular',\n\t\tunlockHeading: 'Desbloqueie os recursos premium',\n\t\tsimulatePurchase: 'Simular compra',\n\t\tmockNotice: 'Prévia de desenvolvimento: licenças e pagamentos são simulados. Nenhum valor será cobrado.',\n\t\tsellerProvidedBy: 'Licença fornecida por {name}',\n\t\tsellerUnavailable: 'Os dados do fornecedor da licença não estão disponíveis.',\n\t\tsellerSupport: 'Suporte da extensão',\n\t\tsellerTerms: 'Termos de licença',\n\t\tsellerRefunds: 'Política de reembolso',\n\t\tsellerRole:\n\t\t\t'O autor é responsável pelo funcionamento da extensão e pelos compromissos da licença. A Extenshi fornece as ferramentas de pagamento e de recuperação de licenças.',\n\t\tlicenseTitle: 'Sua licença',\n\t\tlicenseFallbackName: 'Licença da extensão',\n\t\tlicenseNone: 'Nenhuma licença encontrada nesta instalação.',\n\t\tkindOneTime: 'Compra única',\n\t\tkindLifetime: 'Licença vitalícia',\n\t\tkindSubscription: 'Assinatura',\n\t\tkindLicense: 'Licença',\n\t\tstatusLine: 'Status: {status}',\n\t\tstatusActive: 'ativo',\n\t\tstatusGrace: 'período de carência',\n\t\tstatusExpired: 'expirado',\n\t\tstatusNone: 'sem acesso',\n\t\taccessEnded: 'Acesso encerrado em {date}',\n\t\taccessUntil: 'Acesso até {date}',\n\t\taccessRecordedEnd: 'Data de término registrada: {date}',\n\t\tsubscriptionLine: 'Assinatura: {status}',\n\t\trenewalCanceled: 'Renovação cancelada',\n\t\tperiodEnds: 'Período termina em {date}',\n\t\tsubActive: 'ativa',\n\t\tsubTrialing: 'em período de teste',\n\t\tsubPastDue: 'pagamento em atraso',\n\t\tsubCanceled: 'cancelada',\n\t\tsubUnpaid: 'não paga',\n\t\tsubIncomplete: 'incompleta',\n\t\tsubIncompleteExpired: 'pagamento não concluído',\n\t\tsubPaused: 'pausada',\n\t\tlicenseOffline:\n\t\t\t'Conecte-se à internet para verificar sua licença. Os recursos pagos são pausados após 48 horas sem uma verificação bem-sucedida. Sua compra não expirou.',\n\t\tlicenseCached: 'Exibindo as informações de licença salvas.',\n\t\tlicenseFresh: 'As informações da assinatura refletem a atualização de pagamento processada mais recente.',\n\t\tactionFailed:\n\t\t\t'Não foi possível concluir a solicitação. Tente novamente ou entre em contato com o suporte da extensão.',\n\t\tmanageBilling: 'Gerenciar cobrança',\n\t\tnoPortal:\n\t\t\t'O portal de cobrança não foi aberto. Você pode tentar novamente ou entrar em contato com o suporte da extensão.',\n\t\tclose: 'Fechar',\n\t\tpickerTitle: 'Escolha um perfil de cobrança',\n\t\tpickerDescription:\n\t\t\t'Compras diferentes podem ter perfis de cobrança diferentes. Escolha um perfil para gerenciar as assinaturas e os dados de pagamento vinculados a ele.',\n\t\tpickerFirstRecorded: 'Registrado pela primeira vez em {date}',\n\t\tpickerCancel: 'Cancelar',\n\t\ttrialEndedTitle: 'Seu teste gratuito terminou',\n\t\ttrialEndedDescription:\n\t\t\t'As ferramentas da extensão estão pausadas. Suas configurações foram mantidas e estarão lá quando você fizer o upgrade.',\n\t\ttrialEndedFeedback: 'Enviar feedback',\n\t},\n\tfr: {\n\t\ttitle: 'Débloquez les fonctionnalités premium',\n\t\tdescription: 'Passez à la version supérieure pour obtenir un accès complet à cette extension.',\n\t\tupgrade: 'Mettre à niveau',\n\t\tcancel: 'Pas maintenant',\n\t\tdismiss: 'Ignorer',\n\t\tremindLater: 'Me le rappeler plus tard',\n\t\tcontinueFree: 'Continuer avec la version gratuite',\n\t\tcheckoutUnavailable: 'Les achats sont temporairement indisponibles',\n\t\tperiodMonth: '/mois',\n\t\tperiodYear: '/an',\n\t\tperiodOnce: 'paiement unique',\n\t\tfooter: 'Le paiement sécurisé s’ouvre dans un nouvel onglet.',\n\t\trestorePurchase: 'Restaurer l’achat',\n\t\tfeaturesHeading: 'Fonctionnalités premium',\n\t\tplansHeading: 'Choisissez votre formule',\n\t\tfreePlanName: 'Gratuit',\n\t\tpremiumPlanName: 'Premium',\n\t\tpopularBadge: 'Le plus populaire',\n\t\tunlockHeading: 'Débloquez les fonctionnalités premium',\n\t\tsimulatePurchase: 'Simuler l’achat',\n\t\tmockNotice:\n\t\t\t'Aperçu de développement : les licences et les paiements sont simulés. Aucun paiement ne sera prélevé.',\n\t\tsellerProvidedBy: 'Licence fournie par {name}',\n\t\tsellerUnavailable: 'Les informations sur le fournisseur de la licence ne sont pas disponibles.',\n\t\tsellerSupport: 'Assistance pour l’extension',\n\t\tsellerTerms: 'Conditions de licence',\n\t\tsellerRefunds: 'Politique de remboursement',\n\t\tsellerRole:\n\t\t\t'L’auteur est responsable des fonctionnalités de l’extension et des engagements liés à la licence. Extenshi fournit les outils de paiement et de restauration des licences.',\n\t\tlicenseTitle: 'Votre licence',\n\t\tlicenseFallbackName: 'Licence de l’extension',\n\t\tlicenseNone: 'Aucune licence n’a été trouvée pour cette installation.',\n\t\tkindOneTime: 'Achat unique',\n\t\tkindLifetime: 'Licence à vie',\n\t\tkindSubscription: 'Abonnement',\n\t\tkindLicense: 'Licence',\n\t\tstatusLine: 'Statut : {status}',\n\t\tstatusActive: 'actif',\n\t\tstatusGrace: 'période de grâce',\n\t\tstatusExpired: 'expiré',\n\t\tstatusNone: 'aucun accès',\n\t\taccessEnded: 'Accès terminé le {date}',\n\t\taccessUntil: 'Accès jusqu’au {date}',\n\t\taccessRecordedEnd: 'Date de fin enregistrée : {date}',\n\t\tsubscriptionLine: 'Abonnement : {status}',\n\t\trenewalCanceled: 'Renouvellement annulé',\n\t\tperiodEnds: 'Fin de la période le {date}',\n\t\tsubActive: 'actif',\n\t\tsubTrialing: 'en période d’essai',\n\t\tsubPastDue: 'paiement en retard',\n\t\tsubCanceled: 'résilié',\n\t\tsubUnpaid: 'impayé',\n\t\tsubIncomplete: 'incomplet',\n\t\tsubIncompleteExpired: 'paiement non finalisé',\n\t\tsubPaused: 'en pause',\n\t\tlicenseOffline:\n\t\t\t'Connectez-vous à Internet pour vérifier votre licence. Les fonctionnalités payantes sont suspendues après 48 heures sans vérification réussie. Votre achat n’a pas expiré.',\n\t\tlicenseCached: 'Affichage des informations de licence enregistrées.',\n\t\tlicenseFresh: 'Les informations d’abonnement reflètent la dernière mise à jour de paiement traitée.',\n\t\tactionFailed:\n\t\t\t'Impossible de traiter la demande. Veuillez réessayer ou contacter l’assistance de l’extension.',\n\t\tmanageBilling: 'Gérer la facturation',\n\t\tnoPortal:\n\t\t\t'Le portail de facturation ne s’est pas ouvert. Vous pouvez réessayer ou contacter l’assistance de l’extension.',\n\t\tclose: 'Fermer',\n\t\tpickerTitle: 'Choisissez un profil de facturation',\n\t\tpickerDescription:\n\t\t\t'Des achats distincts peuvent avoir des profils de facturation distincts. Choisissez-en un pour gérer ses abonnements et ses informations de paiement.',\n\t\tpickerFirstRecorded: 'Enregistré pour la première fois le {date}',\n\t\tpickerCancel: 'Annuler',\n\t\ttrialEndedTitle: 'Votre essai gratuit est terminé',\n\t\ttrialEndedDescription:\n\t\t\t'Les outils de l’extension sont en pause. Vos paramètres sont conservés et vous les retrouverez après la mise à niveau.',\n\t\ttrialEndedFeedback: 'Donner votre avis',\n\t},\n\tde: {\n\t\ttitle: 'Premium-Funktionen freischalten',\n\t\tdescription: 'Hol dir mit einem Upgrade vollen Zugriff auf diese Erweiterung.',\n\t\tupgrade: 'Upgraden',\n\t\tcancel: 'Jetzt nicht',\n\t\tdismiss: 'Ausblenden',\n\t\tremindLater: 'Später erinnern',\n\t\tcontinueFree: 'Mit der kostenlosen Version fortfahren',\n\t\tcheckoutUnavailable: 'Käufe sind vorübergehend nicht möglich',\n\t\tperiodMonth: '/Monat',\n\t\tperiodYear: '/Jahr',\n\t\tperiodOnce: 'einmalig',\n\t\tfooter: 'Der sichere Bezahlvorgang öffnet sich in einem neuen Tab.',\n\t\trestorePurchase: 'Kauf wiederherstellen',\n\t\tfeaturesHeading: 'Premium-Funktionen',\n\t\tplansHeading: 'Wähle deinen Tarif',\n\t\tfreePlanName: 'Kostenlos',\n\t\tpremiumPlanName: 'Premium',\n\t\tpopularBadge: 'Am beliebtesten',\n\t\tunlockHeading: 'Premium-Funktionen freischalten',\n\t\tsimulatePurchase: 'Kauf simulieren',\n\t\tmockNotice:\n\t\t\t'Entwicklungsvorschau: Lizenzen und Zahlungen werden simuliert. Es wird keine Zahlung eingezogen.',\n\t\tsellerProvidedBy: 'Lizenz bereitgestellt von {name}',\n\t\tsellerUnavailable: 'Angaben zum Lizenzgeber sind nicht verfügbar.',\n\t\tsellerSupport: 'Support für die Erweiterung',\n\t\tsellerTerms: 'Lizenzbedingungen',\n\t\tsellerRefunds: 'Rückerstattungen',\n\t\tsellerRole:\n\t\t\t'Der Autor ist für die Funktionen der Erweiterung und die Lizenzzusagen verantwortlich. Extenshi stellt die Werkzeuge für Zahlung und Lizenzwiederherstellung bereit.',\n\t\tlicenseTitle: 'Deine Lizenz',\n\t\tlicenseFallbackName: 'Erweiterungslizenz',\n\t\tlicenseNone: 'Für diese Installation wurde keine Lizenz gefunden.',\n\t\tkindOneTime: 'Einmalkauf',\n\t\tkindLifetime: 'Lebenslange Lizenz',\n\t\tkindSubscription: 'Abonnement',\n\t\tkindLicense: 'Lizenz',\n\t\tstatusLine: 'Status: {status}',\n\t\tstatusActive: 'aktiv',\n\t\tstatusGrace: 'Kulanzfrist',\n\t\tstatusExpired: 'abgelaufen',\n\t\tstatusNone: 'kein Zugriff',\n\t\taccessEnded: 'Zugriff endete am {date}',\n\t\taccessUntil: 'Zugriff bis {date}',\n\t\taccessRecordedEnd: 'Erfasstes Enddatum: {date}',\n\t\tsubscriptionLine: 'Abonnement: {status}',\n\t\trenewalCanceled: 'Wird nicht verlängert',\n\t\tperiodEnds: 'Zeitraum endet am {date}',\n\t\tsubActive: 'aktiv',\n\t\tsubTrialing: 'Testphase',\n\t\tsubPastDue: 'Zahlung überfällig',\n\t\tsubCanceled: 'gekündigt',\n\t\tsubUnpaid: 'unbezahlt',\n\t\tsubIncomplete: 'unvollständig',\n\t\tsubIncompleteExpired: 'Zahlung nicht abgeschlossen',\n\t\tsubPaused: 'pausiert',\n\t\tlicenseOffline:\n\t\t\t'Stelle eine Internetverbindung her, um deine Lizenz zu prüfen. Kostenpflichtige Funktionen werden nach 48 Stunden ohne erfolgreiche Prüfung pausiert. Dein Kauf ist nicht abgelaufen.',\n\t\tlicenseCached: 'Gespeicherte Lizenzinformationen werden angezeigt.',\n\t\tlicenseFresh: 'Die Abonnementangaben entsprechen dem zuletzt verarbeiteten Zahlungsstand.',\n\t\tactionFailed:\n\t\t\t'Die Anfrage konnte nicht abgeschlossen werden. Bitte versuche es erneut oder wende dich an den Support für die Erweiterung.',\n\t\tmanageBilling: 'Abrechnung verwalten',\n\t\tnoPortal:\n\t\t\t'Das Abrechnungsportal wurde nicht geöffnet. Du kannst es erneut versuchen oder dich an den Support für die Erweiterung wenden.',\n\t\tclose: 'Schließen',\n\t\tpickerTitle: 'Abrechnungsprofil auswählen',\n\t\tpickerDescription:\n\t\t\t'Verschiedene Käufe können eigene Abrechnungsprofile haben. Wähle eines aus, um seine Abonnements und Zahlungsdaten zu verwalten.',\n\t\tpickerFirstRecorded: 'Erstmals erfasst am {date}',\n\t\tpickerCancel: 'Abbrechen',\n\t\ttrialEndedTitle: 'Dein kostenloser Testzeitraum ist abgelaufen',\n\t\ttrialEndedDescription:\n\t\t\t'Die Funktionen der Erweiterung sind pausiert. Deine Einstellungen bleiben erhalten und sind nach dem Upgrade wieder da.',\n\t\ttrialEndedFeedback: 'Feedback geben',\n\t},\n\tit: {\n\t\ttitle: 'Sblocca le funzionalità premium',\n\t\tdescription: 'Effettua l’upgrade per ottenere l’accesso completo a questa estensione.',\n\t\tupgrade: 'Effettua l’upgrade',\n\t\tcancel: 'Non ora',\n\t\tdismiss: 'Ignora',\n\t\tremindLater: 'Ricordamelo più tardi',\n\t\tcontinueFree: 'Continua con la versione gratuita',\n\t\tcheckoutUnavailable: 'Gli acquisti sono temporaneamente non disponibili',\n\t\tperiodMonth: '/mese',\n\t\tperiodYear: '/anno',\n\t\tperiodOnce: 'una tantum',\n\t\tfooter: 'Il checkout sicuro si apre in una nuova scheda.',\n\t\trestorePurchase: 'Ripristina acquisto',\n\t\tfeaturesHeading: 'Funzionalità premium',\n\t\tplansHeading: 'Scegli il tuo piano',\n\t\tfreePlanName: 'Gratuito',\n\t\tpremiumPlanName: 'Premium',\n\t\tpopularBadge: 'Il più scelto',\n\t\tunlockHeading: 'Sblocca le funzionalità premium',\n\t\tsimulatePurchase: 'Simula acquisto',\n\t\tmockNotice:\n\t\t\t'Anteprima di sviluppo: licenze e pagamenti sono simulati. Non verrà addebitato alcun pagamento.',\n\t\tsellerProvidedBy: 'Licenza fornita da {name}',\n\t\tsellerUnavailable: 'I dettagli del fornitore della licenza non sono disponibili.',\n\t\tsellerSupport: 'Assistenza per l’estensione',\n\t\tsellerTerms: 'Termini di licenza',\n\t\tsellerRefunds: 'Politica di rimborso',\n\t\tsellerRole:\n\t\t\t'L’autore è responsabile delle funzionalità dell’estensione e degli impegni relativi alla licenza. Extenshi fornisce gli strumenti di pagamento e di recupero della licenza.',\n\t\tlicenseTitle: 'La tua licenza',\n\t\tlicenseFallbackName: 'Licenza dell’estensione',\n\t\tlicenseNone: 'Nessuna licenza trovata in questa installazione.',\n\t\tkindOneTime: 'Acquisto una tantum',\n\t\tkindLifetime: 'Licenza a vita',\n\t\tkindSubscription: 'Abbonamento',\n\t\tkindLicense: 'Licenza',\n\t\tstatusLine: 'Stato: {status}',\n\t\tstatusActive: 'attivo',\n\t\tstatusGrace: 'periodo di tolleranza',\n\t\tstatusExpired: 'scaduto',\n\t\tstatusNone: 'nessun accesso',\n\t\taccessEnded: 'Accesso terminato il {date}',\n\t\taccessUntil: 'Accesso fino al {date}',\n\t\taccessRecordedEnd: 'Data di fine registrata: {date}',\n\t\tsubscriptionLine: 'Abbonamento: {status}',\n\t\trenewalCanceled: 'Rinnovo annullato',\n\t\tperiodEnds: 'Il periodo termina il {date}',\n\t\tsubActive: 'attivo',\n\t\tsubTrialing: 'in prova',\n\t\tsubPastDue: 'pagamento in ritardo',\n\t\tsubCanceled: 'disdetto',\n\t\tsubUnpaid: 'non pagato',\n\t\tsubIncomplete: 'incompleto',\n\t\tsubIncompleteExpired: 'pagamento non completato',\n\t\tsubPaused: 'in pausa',\n\t\tlicenseOffline:\n\t\t\t'Connettiti a internet per verificare la tua licenza. Le funzionalità a pagamento vengono sospese dopo 48 ore senza una verifica riuscita. Il tuo acquisto non è scaduto.',\n\t\tlicenseCached: 'Vengono mostrate le informazioni salvate sulla licenza.',\n\t\tlicenseFresh:\n\t\t\t'Le informazioni sull’abbonamento riflettono l’ultimo aggiornamento di pagamento elaborato.',\n\t\tactionFailed: 'Impossibile completare la richiesta. Riprova o contatta l’assistenza per l’estensione.',\n\t\tmanageBilling: 'Gestisci fatturazione',\n\t\tnoPortal:\n\t\t\t'Il portale di fatturazione non è stato aperto. Puoi riprovare o contattare l’assistenza per l’estensione.',\n\t\tclose: 'Chiudi',\n\t\tpickerTitle: 'Scegli un profilo di fatturazione',\n\t\tpickerDescription:\n\t\t\t'Acquisti diversi possono avere profili di fatturazione diversi. Scegline uno per gestirne gli abbonamenti e i dati di pagamento.',\n\t\tpickerFirstRecorded: 'Registrato per la prima volta il {date}',\n\t\tpickerCancel: 'Annulla',\n\t\ttrialEndedTitle: 'La tua prova gratuita è terminata',\n\t\ttrialEndedDescription:\n\t\t\t'Gli strumenti dell’estensione sono in pausa. Le tue impostazioni sono conservate e le ritroverai dopo l’upgrade.',\n\t\ttrialEndedFeedback: 'Invia un feedback',\n\t},\n\tru: {\n\t\ttitle: 'Откройте доступ к премиум-функциям',\n\t\tdescription: 'Перейдите на премиум, чтобы получить полный доступ к этому расширению.',\n\t\tupgrade: 'Перейти на премиум',\n\t\tcancel: 'Не сейчас',\n\t\tdismiss: 'Скрыть',\n\t\tremindLater: 'Напомнить позже',\n\t\tcontinueFree: 'Продолжить в бесплатной версии',\n\t\tcheckoutUnavailable: 'Покупки временно недоступны',\n\t\tperiodMonth: '/мес.',\n\t\tperiodYear: '/год',\n\t\tperiodOnce: 'разово',\n\t\tfooter: 'Защищённая страница оплаты откроется в новой вкладке.',\n\t\trestorePurchase: 'Восстановить покупку',\n\t\tfeaturesHeading: 'Премиум-функции',\n\t\tplansHeading: 'Выберите тарифный план',\n\t\tfreePlanName: 'Бесплатный',\n\t\tpremiumPlanName: 'Премиум',\n\t\tpopularBadge: 'Самый популярный',\n\t\tunlockHeading: 'Откройте доступ к премиум-функциям',\n\t\tsimulatePurchase: 'Имитировать покупку',\n\t\tmockNotice: 'Режим разработки: лицензии и платежи имитируются. Деньги не будут списаны.',\n\t\tsellerProvidedBy: 'Лицензию предоставляет {name}',\n\t\tsellerUnavailable: 'Сведения о поставщике лицензии недоступны.',\n\t\tsellerSupport: 'Поддержка расширения',\n\t\tsellerTerms: 'Условия лицензии',\n\t\tsellerRefunds: 'Возврат средств',\n\t\tsellerRole:\n\t\t\t'Автор отвечает за работу расширения и обязательства по лицензии. Extenshi предоставляет инструменты для оплаты и восстановления лицензий.',\n\t\tlicenseTitle: 'Ваша лицензия',\n\t\tlicenseFallbackName: 'Лицензия на расширение',\n\t\tlicenseNone: 'Для этой установки лицензия не найдена.',\n\t\tkindOneTime: 'Разовая покупка',\n\t\tkindLifetime: 'Бессрочная лицензия',\n\t\tkindSubscription: 'Подписка',\n\t\tkindLicense: 'Лицензия',\n\t\tstatusLine: 'Статус: {status}',\n\t\tstatusActive: 'действует',\n\t\tstatusGrace: 'льготный период',\n\t\tstatusExpired: 'срок истёк',\n\t\tstatusNone: 'нет доступа',\n\t\taccessEnded: 'Доступ закончился: {date}',\n\t\taccessUntil: 'Доступ до {date}',\n\t\taccessRecordedEnd: 'Зафиксированная дата окончания: {date}',\n\t\tsubscriptionLine: 'Подписка: {status}',\n\t\trenewalCanceled: 'Продление отменено',\n\t\tperiodEnds: 'Период заканчивается: {date}',\n\t\tsubActive: 'активна',\n\t\tsubTrialing: 'пробный период',\n\t\tsubPastDue: 'платёж просрочен',\n\t\tsubCanceled: 'отменена',\n\t\tsubUnpaid: 'не оплачена',\n\t\tsubIncomplete: 'ожидает первого платежа',\n\t\tsubIncompleteExpired: 'платёж не завершён',\n\t\tsubPaused: 'приостановлена',\n\t\tlicenseOffline:\n\t\t\t'Подключитесь к интернету, чтобы проверить лицензию. Если успешной проверки не было 48 часов, платные функции приостанавливаются. Срок действия вашей покупки не истёк.',\n\t\tlicenseCached: 'Показаны сохранённые сведения о лицензии.',\n\t\tlicenseFresh: 'Сведения о подписке соответствуют последнему обработанному обновлению платежа.',\n\t\tactionFailed: 'Не удалось выполнить запрос. Попробуйте ещё раз или обратитесь в поддержку расширения.',\n\t\tmanageBilling: 'Управление оплатой',\n\t\tnoPortal: 'Портал оплаты не открылся. Можно повторить попытку или обратиться в поддержку расширения.',\n\t\tclose: 'Закрыть',\n\t\tpickerTitle: 'Выберите платёжный профиль',\n\t\tpickerDescription:\n\t\t\t'У разных покупок могут быть разные платёжные профили. Выберите профиль, чтобы управлять его подписками и платёжными данными.',\n\t\tpickerFirstRecorded: 'Впервые зафиксирован: {date}',\n\t\tpickerCancel: 'Отмена',\n\t\ttrialEndedTitle: 'Бесплатный пробный период закончился',\n\t\ttrialEndedDescription:\n\t\t\t'Инструменты расширения приостановлены. Ваши настройки сохранены и будут на месте после перехода на премиум.',\n\t\ttrialEndedFeedback: 'Оставить отзыв',\n\t},\n\tja: {\n\t\ttitle: 'プレミアム機能をアンロック',\n\t\tdescription: 'アップグレードすると、この拡張機能のすべての機能をご利用いただけます。',\n\t\tupgrade: 'アップグレード',\n\t\tcancel: '今はしない',\n\t\tdismiss: '非表示にする',\n\t\tremindLater: 'あとで通知する',\n\t\tcontinueFree: '無料版のまま使い続ける',\n\t\tcheckoutUnavailable: '一時的に購入できません',\n\t\tperiodMonth: '/月',\n\t\tperiodYear: '/年',\n\t\tperiodOnce: '買い切り',\n\t\tfooter: '安全なチェックアウト画面が新しいタブで開きます。',\n\t\trestorePurchase: '購入を復元',\n\t\tfeaturesHeading: 'プレミアム機能',\n\t\tplansHeading: 'プランを選択',\n\t\tfreePlanName: '無料',\n\t\tpremiumPlanName: 'プレミアム',\n\t\tpopularBadge: '一番人気',\n\t\tunlockHeading: 'プレミアム機能をアンロック',\n\t\tsimulatePurchase: '購入をシミュレート',\n\t\tmockNotice: '開発用プレビュー:ライセンスと支払いはシミュレーションです。実際の請求は発生しません。',\n\t\tsellerProvidedBy: 'ライセンス提供者:{name}',\n\t\tsellerUnavailable: 'ライセンス提供者の情報を取得できません。',\n\t\tsellerSupport: '拡張機能のサポート',\n\t\tsellerTerms: 'ライセンス条件',\n\t\tsellerRefunds: '返金ポリシー',\n\t\tsellerRole:\n\t\t\t'拡張機能の機能とライセンス上の約束については、開発者が責任を負います。Extenshiは、お支払いとライセンス復元のためのツールを提供します。',\n\t\tlicenseTitle: 'ご利用のライセンス',\n\t\tlicenseFallbackName: '拡張機能のライセンス',\n\t\tlicenseNone: 'このインストール環境ではライセンスが見つかりませんでした。',\n\t\tkindOneTime: '買い切り',\n\t\tkindLifetime: 'ライフタイムライセンス',\n\t\tkindSubscription: 'サブスクリプション',\n\t\tkindLicense: 'ライセンス',\n\t\tstatusLine: 'ステータス:{status}',\n\t\tstatusActive: '有効',\n\t\tstatusGrace: '猶予期間中',\n\t\tstatusExpired: '期限切れ',\n\t\tstatusNone: '利用不可',\n\t\taccessEnded: '利用終了日時:{date}',\n\t\taccessUntil: '利用期限:{date}',\n\t\taccessRecordedEnd: '記録上の終了日時:{date}',\n\t\tsubscriptionLine: 'サブスクリプション:{status}',\n\t\trenewalCanceled: '更新停止済み',\n\t\tperiodEnds: '期間終了日:{date}',\n\t\tsubActive: '有効',\n\t\tsubTrialing: 'トライアル中',\n\t\tsubPastDue: '支払い期限超過',\n\t\tsubCanceled: '解約済み',\n\t\tsubUnpaid: '未払い',\n\t\tsubIncomplete: '手続き未完了',\n\t\tsubIncompleteExpired: '支払い未完了',\n\t\tsubPaused: '一時停止中',\n\t\tlicenseOffline:\n\t\t\t'ライセンスを確認するには、インターネットに接続してください。確認に成功しないまま48時間が経過すると、有料機能は一時停止されます。ご購入が失効したわけではありません。',\n\t\tlicenseCached: '保存済みのライセンス情報を表示しています。',\n\t\tlicenseFresh: 'サブスクリプション情報には、処理済みの最新の支払い情報が反映されています。',\n\t\tactionFailed:\n\t\t\t'リクエストを完了できませんでした。もう一度お試しいただくか、拡張機能のサポートにお問い合わせください。',\n\t\tmanageBilling: '請求情報を管理',\n\t\tnoPortal: '請求ポータルを開けませんでした。再試行するか、拡張機能のサポートにお問い合わせください。',\n\t\tclose: '閉じる',\n\t\tpickerTitle: '請求プロファイルを選択',\n\t\tpickerDescription:\n\t\t\t'購入ごとに別々の請求プロファイルがある場合があります。サブスクリプションと支払い情報を管理するプロファイルを1つ選択してください。',\n\t\tpickerFirstRecorded: '初回記録日:{date}',\n\t\tpickerCancel: 'キャンセル',\n\t\ttrialEndedTitle: '無料トライアルが終了しました',\n\t\ttrialEndedDescription:\n\t\t\t'拡張機能のツールは一時停止しています。設定は保存されており、アップグレード後もそのままご利用いただけます。',\n\t\ttrialEndedFeedback: 'フィードバックを送信',\n\t},\n\tko: {\n\t\ttitle: '프리미엄 기능 잠금 해제',\n\t\tdescription: '업그레이드하면 이 확장 프로그램의 모든 기능을 이용할 수 있습니다.',\n\t\tupgrade: '업그레이드',\n\t\tcancel: '나중에',\n\t\tdismiss: '닫기',\n\t\tremindLater: '나중에 다시 알림',\n\t\tcontinueFree: '무료 버전으로 계속하기',\n\t\tcheckoutUnavailable: '일시적으로 구매할 수 없습니다',\n\t\tperiodMonth: '/월',\n\t\tperiodYear: '/년',\n\t\tperiodOnce: '일회성',\n\t\tfooter: '안전한 결제 페이지가 새 탭에서 열립니다.',\n\t\trestorePurchase: '구매 복원',\n\t\tfeaturesHeading: '프리미엄 기능',\n\t\tplansHeading: '요금제 선택',\n\t\tfreePlanName: '무료',\n\t\tpremiumPlanName: '프리미엄',\n\t\tpopularBadge: '가장 인기',\n\t\tunlockHeading: '프리미엄 기능 잠금 해제',\n\t\tsimulatePurchase: '구매 시뮬레이션',\n\t\tmockNotice: '개발용 미리보기: 라이선스와 결제는 시뮬레이션됩니다. 실제로 결제되지 않습니다.',\n\t\tsellerProvidedBy: '라이선스 제공자: {name}',\n\t\tsellerUnavailable: '라이선스 제공자 정보를 확인할 수 없습니다.',\n\t\tsellerSupport: '확장 프로그램 지원',\n\t\tsellerTerms: '라이선스 약관',\n\t\tsellerRefunds: '환불 정책',\n\t\tsellerRole:\n\t\t\t'확장 프로그램의 기능과 라이선스 관련 약속은 개발자가 책임집니다. Extenshi는 결제 및 라이선스 복구 도구를 제공합니다.',\n\t\tlicenseTitle: '내 라이선스',\n\t\tlicenseFallbackName: '확장 프로그램 라이선스',\n\t\tlicenseNone: '이 설치 환경에서 라이선스를 찾지 못했습니다.',\n\t\tkindOneTime: '일회성 구매',\n\t\tkindLifetime: '평생 라이선스',\n\t\tkindSubscription: '구독',\n\t\tkindLicense: '라이선스',\n\t\tstatusLine: '상태: {status}',\n\t\tstatusActive: '활성',\n\t\tstatusGrace: '유예 기간 중',\n\t\tstatusExpired: '만료됨',\n\t\tstatusNone: '이용 권한 없음',\n\t\taccessEnded: '이용 종료 일시: {date}',\n\t\taccessUntil: '이용 기한: {date}',\n\t\taccessRecordedEnd: '기록된 종료 일시: {date}',\n\t\tsubscriptionLine: '구독: {status}',\n\t\trenewalCanceled: '갱신 취소됨',\n\t\tperiodEnds: '기간 종료일: {date}',\n\t\tsubActive: '활성',\n\t\tsubTrialing: '체험 중',\n\t\tsubPastDue: '결제 연체',\n\t\tsubCanceled: '해지됨',\n\t\tsubUnpaid: '미결제',\n\t\tsubIncomplete: '미완료',\n\t\tsubIncompleteExpired: '결제 미완료',\n\t\tsubPaused: '일시 중지됨',\n\t\tlicenseOffline:\n\t\t\t'라이선스를 확인하려면 인터넷에 연결해 주세요. 확인에 성공하지 못한 채 48시간이 지나면 유료 기능이 일시 중지됩니다. 구매가 만료된 것은 아닙니다.',\n\t\tlicenseCached: '저장된 라이선스 정보를 표시하고 있습니다.',\n\t\tlicenseFresh: '구독 정보에는 가장 최근에 처리된 결제 내역이 반영되어 있습니다.',\n\t\tactionFailed: '요청을 완료할 수 없습니다. 다시 시도하거나 확장 프로그램 지원 창구에 문의해 주세요.',\n\t\tmanageBilling: '결제 관리',\n\t\tnoPortal: '결제 포털이 열리지 않았습니다. 다시 시도하거나 확장 프로그램 지원 창구에 문의해 주세요.',\n\t\tclose: '닫기',\n\t\tpickerTitle: '결제 프로필 선택',\n\t\tpickerDescription:\n\t\t\t'구매마다 결제 프로필이 다를 수 있습니다. 구독과 결제 정보를 관리할 프로필을 하나 선택해 주세요.',\n\t\tpickerFirstRecorded: '최초 기록일: {date}',\n\t\tpickerCancel: '취소',\n\t\ttrialEndedTitle: '무료 체험 기간이 종료되었습니다',\n\t\ttrialEndedDescription:\n\t\t\t'확장 프로그램의 도구가 일시 중지되었습니다. 설정은 그대로 저장되어 있으며 업그레이드하면 다시 사용할 수 있습니다.',\n\t\ttrialEndedFeedback: '의견 보내기',\n\t},\n\t'zh-CN': {\n\t\ttitle: '解锁高级功能',\n\t\tdescription: '升级即可完整使用此扩展程序。',\n\t\tupgrade: '升级',\n\t\tcancel: '以后再说',\n\t\tdismiss: '忽略',\n\t\tremindLater: '稍后提醒我',\n\t\tcontinueFree: '继续使用免费版',\n\t\tcheckoutUnavailable: '暂时无法购买',\n\t\tperiodMonth: '/月',\n\t\tperiodYear: '/年',\n\t\tperiodOnce: '一次性',\n\t\tfooter: '安全结账页面将在新标签页中打开。',\n\t\trestorePurchase: '恢复购买',\n\t\tfeaturesHeading: '高级功能',\n\t\tplansHeading: '选择您的方案',\n\t\tfreePlanName: '免费版',\n\t\tpremiumPlanName: '高级版',\n\t\tpopularBadge: '最受欢迎',\n\t\tunlockHeading: '解锁高级功能',\n\t\tsimulatePurchase: '模拟购买',\n\t\tmockNotice: '开发预览:许可证和付款均为模拟,不会实际扣款。',\n\t\tsellerProvidedBy: '许可证由 {name} 提供',\n\t\tsellerUnavailable: '无法获取许可证提供方的详细信息。',\n\t\tsellerSupport: '扩展程序支持',\n\t\tsellerTerms: '许可条款',\n\t\tsellerRefunds: '退款政策',\n\t\tsellerRole: '作者负责扩展程序的功能及许可证相关承诺。Extenshi 提供支付及许可证恢复工具。',\n\t\tlicenseTitle: '您的许可证',\n\t\tlicenseFallbackName: '扩展程序许可证',\n\t\tlicenseNone: '此安装中未找到许可证。',\n\t\tkindOneTime: '一次性购买',\n\t\tkindLifetime: '终身许可证',\n\t\tkindSubscription: '订阅',\n\t\tkindLicense: '许可证',\n\t\tstatusLine: '状态:{status}',\n\t\tstatusActive: '有效',\n\t\tstatusGrace: '宽限期',\n\t\tstatusExpired: '已过期',\n\t\tstatusNone: '无使用权限',\n\t\taccessEnded: '使用权限已于 {date} 结束',\n\t\taccessUntil: '可使用至 {date}',\n\t\taccessRecordedEnd: '记录的结束日期:{date}',\n\t\tsubscriptionLine: '订阅:{status}',\n\t\trenewalCanceled: '已取消续订',\n\t\tperiodEnds: '当前计费周期于 {date} 结束',\n\t\tsubActive: '有效',\n\t\tsubTrialing: '试用中',\n\t\tsubPastDue: '付款逾期',\n\t\tsubCanceled: '已取消',\n\t\tsubUnpaid: '未付款',\n\t\tsubIncomplete: '未完成',\n\t\tsubIncompleteExpired: '付款未完成',\n\t\tsubPaused: '已暂停',\n\t\tlicenseOffline:\n\t\t\t'请连接互联网以验证您的许可证。如果连续48小时未能成功验证,付费功能将暂停。您的购买仍然有效。',\n\t\tlicenseCached: '正在显示已保存的许可证信息。',\n\t\tlicenseFresh: '订阅信息反映的是最近一次已处理的付款更新。',\n\t\tactionFailed: '无法完成请求。请重试或联系扩展程序支持。',\n\t\tmanageBilling: '管理账单',\n\t\tnoPortal: '未能打开账单门户。您可以重试或联系扩展程序支持。',\n\t\tclose: '关闭',\n\t\tpickerTitle: '选择账单资料',\n\t\tpickerDescription: '不同的购买可以有各自的账单资料。请选择一个,以管理其订阅和付款信息。',\n\t\tpickerFirstRecorded: '首次记录于 {date}',\n\t\tpickerCancel: '取消',\n\t\ttrialEndedTitle: '免费试用已结束',\n\t\ttrialEndedDescription: '扩展程序的工具已暂停。您的设置已保留,升级后即可继续使用。',\n\t\ttrialEndedFeedback: '提交反馈',\n\t},\n\tar: {\n\t\ttitle: 'احصل على الميزات المميزة',\n\t\tdescription: 'قم بالترقية للوصول الكامل إلى هذه الإضافة.',\n\t\tupgrade: 'ترقية',\n\t\tcancel: 'ليس الآن',\n\t\tdismiss: 'تجاهل',\n\t\tremindLater: 'ذكّرني لاحقًا',\n\t\tcontinueFree: 'المتابعة بالإصدار المجاني',\n\t\tcheckoutUnavailable: 'عمليات الشراء غير متاحة مؤقتًا',\n\t\tperiodMonth: '/شهر',\n\t\tperiodYear: '/سنة',\n\t\tperiodOnce: 'لمرة واحدة',\n\t\tfooter: 'تُفتح صفحة الدفع الآمن في علامة تبويب جديدة.',\n\t\trestorePurchase: 'استعادة الشراء',\n\t\tfeaturesHeading: 'الميزات المميزة',\n\t\tplansHeading: 'اختر خطتك',\n\t\tfreePlanName: 'مجاني',\n\t\tpremiumPlanName: 'مميز',\n\t\tpopularBadge: 'الأكثر رواجًا',\n\t\tunlockHeading: 'احصل على الميزات المميزة',\n\t\tsimulatePurchase: 'محاكاة الشراء',\n\t\tmockNotice: 'معاينة التطوير: تجري محاكاة التراخيص والمدفوعات، ولن يُحصَّل أي مبلغ.',\n\t\tsellerProvidedBy: 'الترخيص مقدَّم من البائع {name}',\n\t\tsellerUnavailable: 'بيانات مانح الترخيص غير متاحة.',\n\t\tsellerSupport: 'دعم الإضافة',\n\t\tsellerTerms: 'شروط الترخيص',\n\t\tsellerRefunds: 'سياسة استرداد المبالغ',\n\t\tsellerRole:\n\t\t\t'يتحمّل مطوّر الإضافة المسؤولية عن وظائفها وعن التزامات الترخيص، وتوفّر Extenshi أدوات الدفع واستعادة التراخيص.',\n\t\tlicenseTitle: 'ترخيصك',\n\t\tlicenseFallbackName: 'ترخيص الإضافة',\n\t\tlicenseNone: 'لم يُعثر على أي ترخيص في هذا التثبيت.',\n\t\tkindOneTime: 'شراء لمرة واحدة',\n\t\tkindLifetime: 'ترخيص مدى الحياة',\n\t\tkindSubscription: 'اشتراك',\n\t\tkindLicense: 'ترخيص',\n\t\tstatusLine: 'الحالة: {status}',\n\t\tstatusActive: 'نشطة',\n\t\tstatusGrace: 'في فترة السماح',\n\t\tstatusExpired: 'منتهية الصلاحية',\n\t\tstatusNone: 'بلا وصول',\n\t\taccessEnded: 'انتهى الوصول في {date}',\n\t\taccessUntil: 'الوصول متاح حتى {date}',\n\t\taccessRecordedEnd: 'تاريخ الانتهاء المسجَّل: {date}',\n\t\tsubscriptionLine: 'الاشتراك: {status}',\n\t\trenewalCanceled: 'أُلغي التجديد',\n\t\tperiodEnds: 'تنتهي الفترة الحالية في {date}',\n\t\tsubActive: 'نشط',\n\t\tsubTrialing: 'فترة تجريبية',\n\t\tsubPastDue: 'متأخر السداد',\n\t\tsubCanceled: 'ملغى',\n\t\tsubUnpaid: 'غير مدفوع',\n\t\tsubIncomplete: 'غير مكتمل',\n\t\tsubIncompleteExpired: 'لم يكتمل الدفع',\n\t\tsubPaused: 'متوقف مؤقتًا',\n\t\tlicenseOffline:\n\t\t\t'اتصل بالإنترنت للتحقق من ترخيصك. تتوقف الميزات المدفوعة مؤقتًا إذا مرّت 48 ساعة دون تحقق ناجح. لم تنتهِ صلاحية عملية الشراء.',\n\t\tlicenseCached: 'تُعرض معلومات الترخيص المحفوظة.',\n\t\tlicenseFresh: 'تعكس معلومات الاشتراك آخر تحديث للدفع تمت معالجته.',\n\t\tactionFailed: 'تعذّر إكمال الطلب. يُرجى المحاولة مرة أخرى أو التواصل مع دعم الإضافة.',\n\t\tmanageBilling: 'إدارة الفوترة',\n\t\tnoPortal: 'لم تُفتح بوابة الفوترة. يمكنك المحاولة مرة أخرى أو التواصل مع دعم الإضافة.',\n\t\tclose: 'إغلاق',\n\t\tpickerTitle: 'اختر ملف فوترة',\n\t\tpickerDescription:\n\t\t\t'يمكن أن تكون لعمليات الشراء المنفصلة ملفات فوترة منفصلة. اختر ملفًا منها لإدارة اشتراكاته وتفاصيل الدفع الخاصة به.',\n\t\tpickerFirstRecorded: 'سُجِّل لأول مرة في {date}',\n\t\tpickerCancel: 'إلغاء',\n\t\ttrialEndedTitle: 'انتهت فترتك التجريبية المجانية',\n\t\ttrialEndedDescription: 'أدوات الإضافة متوقفة مؤقتًا. إعداداتك محفوظة وستجدها كما هي بعد الترقية.',\n\t\ttrialEndedFeedback: 'إرسال ملاحظات',\n\t},\n}\n// END GENERATED TRANSLATIONS\n\n/** Our dictionary language for a tag: exact, then pt → pt-BR, zh(-CN/SG/Hans) → zh-CN, then the bare language. */\nexport function sdkLocale(locale: string | null | undefined): SdkLocale {\n\tconst tag = wireLocale(locale)\n\tif (!tag) return 'en'\n\tconst exact = SDK_LOCALES.find((l) => l.toLowerCase() === tag.toLowerCase())\n\tif (exact) return exact\n\tconst [lang, region] = tag.split('-')\n\tif (lang === 'pt') return 'pt-BR'\n\t// Traditional-script regions read English rather than Simplified characters.\n\tif (lang === 'zh') return region && ['TW', 'HK', 'MO'].includes(region) ? 'en' : 'zh-CN'\n\treturn SDK_LOCALES.find((l) => l === lang) ?? 'en'\n}\n\nexport function sdkDir(locale: string | null | undefined): 'ltr' | 'rtl' {\n\tconst lang = wireLocale(locale)?.split('-')[0]\n\treturn lang && ['ar', 'he', 'fa', 'ur'].includes(lang) ? 'rtl' : 'ltr'\n}\n\n/** English merged with the translation for `locale`. */\nexport function sdkStrings(locale: string | null | undefined): SdkStrings {\n\tconst tag = sdkLocale(locale)\n\treturn tag === 'en' ? SDK_STRINGS_EN : { ...SDK_STRINGS_EN, ...TRANSLATIONS[tag] }\n}\n\n/** Fill `{placeholders}` once; a value containing braces is inserted literally. */\nexport function fill(message: string, values: Record<string, string>): string {\n\treturn message.replace(/\\{([a-z]+)\\}/g, (whole, key: string) => values[key] ?? whole)\n}\n\n/** The raw translation block, for completeness tests. */\nexport function sdkTranslations(locale: Exclude<SdkLocale, 'en'>): SdkStrings | undefined {\n\treturn TRANSLATIONS[locale]\n}\n","/**\n * Buyer-facing withdrawal-waiver text (EU/EEA digital content, Directive\n * 2011/83/EU art. 16(m); UK CCR 2013 reg. 37), per text version and SDK\n * language. Its own module, not part of the paywall dictionary, so Lite can\n * show it without bundling every paywall string.\n *\n * The recorded consent names the version, so a version's words never change:\n * new wording is a new version here and a new PAY_WITHDRAWAL_WAIVER_VERSION.\n *\n * MIRRORED in shared-types/pay-withdrawal-waiver.ts, which the purchase\n * confirmation email quotes; shared-types/pay-withdrawal-waiver.test.ts fails\n * unless both copies are byte-identical. Change them together.\n */\n\nimport { fill, type SdkLocale, sdkLocale } from '../paywall/i18n.js'\nimport { PAY_WITHDRAWAL_WAIVER_VERSION } from '../types/contract.js'\n\nexport const WITHDRAWAL_WAIVER_TEXTS: Readonly<Record<string, Readonly<Record<SdkLocale, string>>>> = {\n\t[PAY_WITHDRAWAL_WAIVER_VERSION]: {\n\t\ten: 'I agree that {seller} starts supplying the digital content immediately, and I acknowledge that I lose my right of withdrawal once supply has begun.',\n\t\tes: 'Acepto que {seller} comience a suministrar el contenido digital de inmediato y reconozco que pierdo mi derecho de desistimiento una vez iniciado el suministro.',\n\t\t'pt-BR':\n\t\t\t'Concordo que {seller} comece a fornecer o conteúdo digital imediatamente e reconheço que perco meu direito de arrependimento assim que o fornecimento tiver início.',\n\t\tfr: 'J’accepte que {seller} commence immédiatement la fourniture du contenu numérique et je reconnais perdre mon droit de rétractation dès le début de la fourniture.',\n\t\tde: 'Ich stimme zu, dass {seller} sofort mit der Bereitstellung der digitalen Inhalte beginnt, und ich nehme zur Kenntnis, dass ich mit Beginn der Bereitstellung mein Widerrufsrecht verliere.',\n\t\tit: 'Accetto che {seller} inizi immediatamente la fornitura del contenuto digitale e riconosco di perdere il mio diritto di recesso una volta iniziata la fornitura.',\n\t\tru: 'Я соглашаюсь с тем, что {seller} немедленно начнёт предоставление цифрового контента, и подтверждаю, что утрачиваю право на отказ от договора с момента начала предоставления.',\n\t\tja: '{seller}がデジタルコンテンツの提供を直ちに開始することに同意し、提供の開始後は撤回権を失うことを了承します。',\n\t\tko: '{seller}의 디지털 콘텐츠 제공이 즉시 시작되는 것에 동의하며, 제공이 시작되면 청약철회권을 상실한다는 점을 확인합니다.',\n\t\t'zh-CN': '我同意 {seller} 立即开始提供数字内容,并确认一旦开始提供,我将失去撤回权。',\n\t\tar: 'أوافق على أن يبدأ {seller} فورًا في تقديم المحتوى الرقمي، وأُقرّ بأنني أفقد حقي في العدول عن العقد بمجرد بدء التقديم.',\n\t},\n}\n\n/**\n * The waiver text to show for `serverVersion`, and the version to send with\n * the consent. A version this SDK does not know (a newer server) shows this\n * SDK's current text and sends its version: the consent always names the words\n * actually shown.\n */\nexport function withdrawalWaiverText(\n\tserverVersion: string,\n\tlocale: string | null | undefined,\n\tseller: string,\n): { version: string; text: string } {\n\t// Own keys only: `toString` / `__proto__` from a server are just unknown versions.\n\tconst known = Object.keys(WITHDRAWAL_WAIVER_TEXTS).includes(serverVersion)\n\tconst version = known ? serverVersion : PAY_WITHDRAWAL_WAIVER_VERSION\n\treturn { version, text: fill(WITHDRAWAL_WAIVER_TEXTS[version][sdkLocale(locale)], { seller }) }\n}\n","/**\n * `ExtenshiPayLite` — entitlement, feature gating and hosted checkout, without\n * the paywall UI. This is what the `lite` bundle exports; the full `ExtenshiPay`\n * extends it with `getOffer()` / `showPaywall()`.\n *\n * Data that leaves the extension: `publishableKey`, `endUserRef`, `sku`,\n * `locale`, checkout session IDs and, with a server trial, the trial start date\n * the server issued (`trialStartedHint`, kept in storage.sync). Explicit recovery also sends its session ID,\n * challenge and claim secret (POST body). Email stays on the hosted page. With cloud backup, the\n * storage token goes only to `/v1/storage` (as a bearer), never in a message to a content script.\n */\n\nimport { MockTransport } from '../api/mock.js'\nimport { PayApi } from '../api/pay-api.js'\nimport { HttpTransport, type Transport } from '../api/transport.js'\nimport { CheckoutManager } from '../payment/checkout.js'\nimport { CloudBackup } from '../payment/cloud-backup.js'\nimport { EntitlementManager, MAX_CLOCK_SKEW_MS } from '../payment/entitlement.js'\nimport { checkFeatures, hasFeature, isEntitled, isLive } from '../payment/features.js'\nimport { createRecoveryStorage, RecoveryManager } from '../payment/recovery.js'\nimport { PUBLIC_KEY_RE, type PublicKeySource, verifyWithKeys } from '../payment/signature.js'\nimport { TrialNotifier } from '../payment/trial.js'\nimport { withdrawalWaiverText } from '../payment/withdrawal-waiver.js'\nimport type { ExtenshiPayConfig, ResolvedConfig } from '../types/config.js'\nimport type { PayOfferResponse } from '../types/contract.js'\nimport { PAY_END_USER_REF_RE } from '../types/contract.js'\nimport type {\n\tCheckoutOptions,\n\tCheckoutResult,\n\tCustomerPortalOptions,\n\tEntitlement,\n\tGetEntitlementOptions,\n\tLicenseSummary,\n\tRequireFeatureOptions,\n\tRestoreOptions,\n\tRestoreResult,\n\tTrialState,\n} from '../types/entitlement.js'\nimport { ERROR_CODES, ExtenshiPayError } from '../types/errors.js'\nimport type { ExtenshiPayEvents } from '../types/events.js'\nimport { logger } from '../utils/logger.js'\nimport { VERSION } from '../version.js'\nimport { resolveConfig } from './config.js'\nimport { EventEmitter, type Listener } from './event-emitter.js'\nimport { END_USER_REF_STORAGE_KEY, getOrCreateEndUserRef } from './identity.js'\nimport { createStorage, createSyncStorage, type StorageAdapter } from './storage.js'\n\n/** Server-side offer cache is 5 min; mirror it in memory. */\nconst OFFER_TTL_MS = 5 * 60 * 1000\n\n/** Injection points for tests and unusual hosts. */\nexport interface ExtenshiPayDeps {\n\tstorage?: StorageAdapter\n\t/** Where the trial start is synced (default `storage.sync`); null turns syncing off. */\n\tsyncStorage?: StorageAdapter | null\n\t/** Trusted extension-only storage; never share this adapter with content scripts. */\n\trecoveryStorage?: StorageAdapter\n\ttransport?: Transport\n\tfetch?: typeof fetch\n\topenUrl?: (url: string) => void | Promise<void>\n\tnow?: () => number\n}\n\nexport class ExtenshiPayLite {\n\tstatic readonly version = VERSION\n\n\tprotected readonly config: ResolvedConfig\n\tprotected readonly emitter = new EventEmitter<ExtenshiPayEvents>()\n\tprotected readonly storage: StorageAdapter\n\tprotected readonly api: PayApi\n\tprotected readonly entitlements: EntitlementManager\n\tprotected readonly checkout: CheckoutManager\n\tprotected readonly recovery: RecoveryManager\n\tprivate readonly backup: CloudBackup\n\t/** `deps.openUrl`, for tabs the full SDK opens outside checkout and recovery. */\n\tprotected readonly openUrl: ((url: string) => void | Promise<void>) | undefined\n\tprivate readonly trial: TrialNotifier\n\t/** storage.sync for the trial start; null when off, in mock mode, or outside an extension. */\n\tprivate readonly syncStorage: StorageAdapter | null\n\tprivate readonly now: () => number\n\tprivate endUserRef: string | null = null\n\tprivate endUserRefPromise: Promise<string> | null = null\n\tprivate offer: { value: PayOfferResponse; fetchedAt: number } | null = null\n\tprivate offerInflight: Promise<PayOfferResponse> | null = null\n\t/** The signing key the server returned in this session; never one read from storage. */\n\tprivate serverKey: string | null = null\n\t/** Trust order for license signatures; see payment/signature.ts. */\n\tprivate readonly keys: PublicKeySource = {\n\t\tknown: async () => {\n\t\t\tconst pinned = this.config.entitlementPublicKey\n\t\t\tconst offline = pinned ?? (await this.readSavedServerKey())\n\t\t\treturn [...new Set([this.serverKey, offline].filter((key): key is string => !!key))]\n\t\t},\n\t\tfetchCurrent: async () => (await this.fetchOffer(true)).entitlementPublicKey,\n\t}\n\tprivate readyPromise: Promise<void> | null = null\n\tprivate destroyed = false\n\n\tconstructor(config: ExtenshiPayConfig, deps: ExtenshiPayDeps = {}) {\n\t\tthis.config = resolveConfig(config)\n\t\tlogger.configure({ logLevel: this.config.logLevel, debug: this.config.debug })\n\t\tthis.now = deps.now ?? (() => Date.now())\n\t\tthis.storage = deps.storage ?? createStorage()\n\t\tthis.openUrl = deps.openUrl\n\t\tthis.syncStorage =\n\t\t\t!this.config.syncTrialStart || this.config.mock\n\t\t\t\t? null\n\t\t\t\t: deps.syncStorage === undefined\n\t\t\t\t\t? createSyncStorage()\n\t\t\t\t\t: deps.syncStorage\n\n\t\tconst transport =\n\t\t\tdeps.transport ??\n\t\t\t(this.config.mock\n\t\t\t\t? new MockTransport(this.config.mockData ?? {})\n\t\t\t\t: new HttpTransport({ apiUrl: this.config.apiUrl, fetchImpl: deps.fetch }))\n\t\tthis.api = new PayApi(transport, this.config.publishableKey)\n\n\t\tthis.entitlements = new EntitlementManager({\n\t\t\tapi: this.api,\n\t\t\tstorage: this.storage,\n\t\t\tpublishableKey: this.config.publishableKey,\n\t\t\tcacheTtlMs: this.config.cacheTtlMs,\n\t\t\tsource: this.config.mock ? 'mock' : 'network',\n\t\t\tgetEndUserRef: () => this.getEndUserRef(),\n\t\t\tkeys: this.keys,\n\t\t\tonChange: (entitlement) => this.emitter.emit('entitlement:changed', entitlement),\n\t\t\tonAccepted: () => {\n\t\t\t\tvoid this.trial.evaluate()\n\t\t\t\tvoid this.rememberTrialStart()\n\t\t\t},\n\t\t\tgetTrialStartHint: () => this.readTrialStartHint(),\n\t\t\tonError: (error) => this.reportError(error),\n\t\t\tnow: this.now,\n\t\t})\n\n\t\tthis.trial = new TrialNotifier({\n\t\t\tstorage: this.storage,\n\t\t\tstorageKey: `extenshi-pay:${this.config.publishableKey}:trial-events${this.config.mock ? ':mock' : ''}`,\n\t\t\tendingDays: this.config.trialEndingDays,\n\t\t\tgetTrial: () => this.entitlements.getTrial(),\n\t\t\t// A paid license still counts while it waits for an online check: no \"trial ended\" to a buyer.\n\t\t\thasPaidAccess: () => (this.entitlements.getCached()?.items ?? []).some(isLive),\n\t\t\temit: (event, trial) => this.emitter.emit(event, trial),\n\t\t\tnow: this.now,\n\t\t})\n\n\t\tthis.checkout = new CheckoutManager({\n\t\t\tapi: this.api,\n\t\t\tstorage: this.storage,\n\t\t\tpublishableKey: this.config.publishableKey,\n\t\t\tlocale: this.config.locale,\n\t\t\tgetEndUserRef: () => this.getEndUserRef(),\n\t\t\tonComplete: (envelope) => this.entitlements.accept(envelope),\n\t\t\temit: (event, payload) => this.emitter.emit(event, payload),\n\t\t\t// Mock checkouts complete on their own; never open a tab to a mock URL.\n\t\t\topenUrl:\n\t\t\t\tdeps.openUrl ??\n\t\t\t\t(this.config.mock ? (url) => logger.info('mock checkout (no tab opened)', url) : undefined),\n\t\t\tnow: this.now,\n\t\t})\n\n\t\tthis.backup = new CloudBackup({\n\t\t\tstorage: this.storage,\n\t\t\tpublishableKey: this.config.publishableKey,\n\t\t\tapiUrl: this.config.apiUrl,\n\t\t\tfetch: deps.fetch,\n\t\t\tmock: this.config.mock,\n\t\t})\n\n\t\tthis.recovery = new RecoveryManager({\n\t\t\tapi: this.api,\n\t\t\tlocale: this.config.locale,\n\t\t\tpublishableKey: this.config.publishableKey,\n\t\t\tstorage: deps.recoveryStorage ?? createRecoveryStorage(),\n\t\t\topenUrl: deps.openUrl,\n\t\t\tnow: this.now,\n\t\t\tonComplete: async (ref, envelope) => {\n\t\t\t\tif (\n\t\t\t\t\t!PAY_END_USER_REF_RE.test(ref) ||\n\t\t\t\t\tenvelope?.payload?.endUserRef !== ref ||\n\t\t\t\t\tenvelope.payload.publishableKey !== this.config.publishableKey ||\n\t\t\t\t\t!Number.isFinite(Date.parse(envelope.payload.issuedAt)) ||\n\t\t\t\t\tDate.parse(envelope.payload.issuedAt) > this.now() + MAX_CLOCK_SKEW_MS ||\n\t\t\t\t\t(await verifyWithKeys(envelope, this.keys)).verdict !== 'valid'\n\t\t\t\t)\n\t\t\t\t\tthrow new ExtenshiPayError(\n\t\t\t\t\t\tERROR_CODES.INVALID_RESPONSE,\n\t\t\t\t\t\t'Recovery requires a verified entitlement for this installation',\n\t\t\t\t\t)\n\t\t\t\tthis.entitlements.stopAutoRefresh()\n\t\t\t\ttry {\n\t\t\t\t\tawait this.entitlements.settleRefresh()\n\t\t\t\t\tif (this.destroyed) throw new ExtenshiPayError(ERROR_CODES.INVALID_REQUEST, 'Recovery was stopped')\n\t\t\t\t\tawait this.storage.set(END_USER_REF_STORAGE_KEY, ref)\n\t\t\t\t\tthis.endUserRef = ref\n\t\t\t\t\tthis.endUserRefPromise = null\n\t\t\t\t\tawait this.entitlements.clear()\n\t\t\t\t\treturn await this.entitlements.accept(envelope)\n\t\t\t\t} finally {\n\t\t\t\t\tif (!this.destroyed) this.entitlements.startAutoRefresh()\n\t\t\t\t}\n\t\t\t},\n\t\t\tonStorageGrant: (grant) => this.backup.accept(grant),\n\t\t})\n\n\t\tif (config.onError) this.emitter.on('error', config.onError)\n\t\tif (config.onReady) this.emitter.once('ready', config.onReady)\n\t}\n\n\tget version(): string {\n\t\treturn VERSION\n\t}\n\n\t/**\n\t * Mints/loads `endUserRef`, loads the cached entitlement, re-verifies it and\n\t * refreshes it when stale. Resolves once `isPaid()` can answer; network\n\t * failures fall back to the cache and are reported through `error`.\n\t */\n\tinitialize(): Promise<void> {\n\t\tif (!this.readyPromise) this.readyPromise = this.doInitialize()\n\t\treturn this.readyPromise\n\t}\n\n\tprivate async doInitialize(): Promise<void> {\n\t\tconst endUserRef = await this.getEndUserRef()\n\t\tawait this.entitlements.load()\n\t\ttry {\n\t\t\tawait this.entitlements.reverify()\n\t\t} catch (error) {\n\t\t\tthis.reportError(error)\n\t\t}\n\t\tif (!this.entitlements.isFresh()) await this.entitlements.get({ force: true })\n\t\tthis.emitter.emit('ready', { endUserRef })\n\t\tvoid this.afterReady()\n\t}\n\n\tprivate async afterReady(): Promise<void> {\n\t\tif (this.destroyed) return\n\t\ttry {\n\t\t\tawait this.checkout.resumePending()\n\t\t\tif (this.destroyed) return\n\t\t\tawait this.recovery.resumePending()\n\t\t} catch (error) {\n\t\t\tthis.reportError(error)\n\t\t}\n\t\tvoid this.confirmSavedServerKey()\n\t\tif (!this.destroyed) {\n\t\t\tthis.entitlements.startAutoRefresh()\n\t\t\tthis.trial.start()\n\t\t}\n\t}\n\n\t/** The anonymous, random id this install is known by. */\n\tgetEndUserRef(): Promise<string> {\n\t\tif (this.endUserRef) return Promise.resolve(this.endUserRef)\n\t\tif (!this.endUserRefPromise) {\n\t\t\tthis.endUserRefPromise = getOrCreateEndUserRef(this.storage).then((ref) => {\n\t\t\t\tthis.endUserRef = ref\n\t\t\t\treturn ref\n\t\t\t})\n\t\t}\n\t\treturn this.endUserRefPromise\n\t}\n\n\tgetCachedEntitlement(): Entitlement | null {\n\t\treturn this.entitlements.getCached()\n\t}\n\n\tasync getEntitlement(options: GetEntitlementOptions = {}): Promise<Entitlement> {\n\t\tawait this.initialize()\n\t\treturn this.entitlements.get(options)\n\t}\n\n\t/**\n\t * The free trial the application set on the server, from the verified license, or null when\n\t * there is none (or the license could not be verified yet). Answers offline from the cached\n\t * license; like paid access, `active` needs a license check within 48 hours. `isPaid()` and\n\t * `hasFeature()` do not include the trial: grant trial access with `(await getTrial())?.active`.\n\t */\n\tasync getTrial(options: GetEntitlementOptions = {}): Promise<TrialState | null> {\n\t\tawait this.getEntitlement(options)\n\t\treturn this.entitlements.getTrial()\n\t}\n\n\t/** True when any active/grace entitlement exists, or the given `sku` is active/grace. */\n\tasync isPaid(sku?: string): Promise<boolean> {\n\t\treturn isEntitled(await this.getEntitlement(), sku)\n\t}\n\n\tasync hasFeature(feature: string): Promise<boolean> {\n\t\treturn hasFeature(await this.getEntitlement(), feature)\n\t}\n\n\tasync checkFeatures(features: string[]): Promise<Record<string, boolean>> {\n\t\treturn checkFeatures(await this.getEntitlement(), features)\n\t}\n\n\t/** Resolves true when the feature is (or becomes) unlocked. */\n\tasync requireFeature(feature: string, options: RequireFeatureOptions = {}): Promise<boolean> {\n\t\tif (await this.hasFeature(feature)) {\n\t\t\toptions.onUnlock?.()\n\t\t\treturn true\n\t\t}\n\t\tconst unlocked = await this.onFeatureLocked(feature, options)\n\t\tif (unlocked) options.onUnlock?.()\n\t\telse options.onCancel?.()\n\t\treturn unlocked\n\t}\n\n\t/** Lite has no UI: a locked feature stays locked. The full SDK shows the paywall here. */\n\tprotected async onFeatureLocked(_feature: string, _options: RequireFeatureOptions): Promise<boolean> {\n\t\treturn false\n\t}\n\n\t/**\n\t * The withdrawal waiver this offer asks for, with the exact text to show\n\t * next to an unticked checkbox (buyer's language, seller's name filled in),\n\t * or null when the seller attested the extension is not distributed in the\n\t * EEA/UK. For UIs that call `openCheckout()` themselves — Lite, or a custom\n\t * paywall; the full SDK's paywall does this for you.\n\t */\n\tasync getWithdrawalWaiver(): Promise<{ version: string; text: string } | null> {\n\t\tawait this.initialize()\n\t\ttry {\n\t\t\tconst offer = await this.fetchOffer()\n\t\t\tif (!offer.withdrawalWaiver) return null\n\t\t\tconst seller = offer.seller?.displayName?.trim() || offer.projectName\n\t\t\treturn withdrawalWaiverText(offer.withdrawalWaiver.version, this.config.locale, seller)\n\t\t} catch (error) {\n\t\t\tthrow this.reportError(error)\n\t\t}\n\t}\n\n\t/**\n\t * Opens hosted checkout for `sku` in a new tab and resolves when the session settles.\n\t *\n\t * Called directly (not from the paywall), this does NOT collect the EU/UK\n\t * withdrawal waiver. If `getWithdrawalWaiver()` returns one, your UI must\n\t * collect the buyer's consent and pass it as `options.withdrawalWaiver`;\n\t * without it this rejects with `WITHDRAWAL_WAIVER_REQUIRED` (the server\n\t * refuses such a checkout too).\n\t */\n\tasync openCheckout(sku: string, options: CheckoutOptions = {}): Promise<CheckoutResult> {\n\t\tawait this.initialize()\n\t\ttry {\n\t\t\tif (this.recovery.isActive())\n\t\t\t\tthrow new ExtenshiPayError(ERROR_CODES.INVALID_REQUEST, 'Recovery is in progress')\n\t\t\t// A cold cache is filled here; if the offer cannot be read, the server decides.\n\t\t\tconst offer = await this.fetchOffer().catch(() => null)\n\t\t\tif (offer?.withdrawalWaiver && options.withdrawalWaiver?.accepted !== true)\n\t\t\t\tthrow new ExtenshiPayError(\n\t\t\t\t\tERROR_CODES.WITHDRAWAL_WAIVER_REQUIRED,\n\t\t\t\t\t'This offer needs the buyer to accept the withdrawal waiver; pass options.withdrawalWaiver',\n\t\t\t\t)\n\t\t\treturn await this.checkout.open(sku, options)\n\t\t} catch (error) {\n\t\t\tthrow this.reportError(error)\n\t\t}\n\t}\n\n\t/** Opens email verification on the hosted page. No email is collected inside the extension. */\n\tasync restorePurchase(options: RestoreOptions = {}): Promise<RestoreResult> {\n\t\tawait this.initialize()\n\t\ttry {\n\t\t\tif (this.checkout.isActive())\n\t\t\t\tthrow new ExtenshiPayError(ERROR_CODES.INVALID_REQUEST, 'Checkout is in progress')\n\t\t\treturn await this.recovery.open(options)\n\t\t} catch (error) {\n\t\t\tthrow this.reportError(error)\n\t\t}\n\t}\n\n\t/**\n\t * Turns on the cloud copy of the extension's settings (`@extenshi/storage`): the\n\t * hosted restore page shows the storage disclosure and the buyer confirms with\n\t * the code from the purchase email. `cloudBackup` in the result says whether it is\n\t * on. Buyers only; consent is recorded by the server.\n\t */\n\tenableCloudBackup(options: Omit<RestoreOptions, 'purpose'> = {}): Promise<RestoreResult> {\n\t\treturn this.restorePurchase({ ...options, purpose: 'storage' })\n\t}\n\n\t/**\n\t * The storage token for `ExtenshiStorage.create({ cloud: { getToken } })`, or null\n\t * while cloud backup is off on this installation. Extension pages and background\n\t * only: it rejects in a content script, and must never be sent to one.\n\t */\n\tasync cloudBackupToken(): Promise<string | null> {\n\t\treturn this.backup.token()\n\t}\n\n\t/** Turns cloud backup off on this installation: revokes its token. The cloud copy stays. */\n\tasync disableCloudBackup(): Promise<void> {\n\t\ttry {\n\t\t\tawait this.backup.disable()\n\t\t} catch (error) {\n\t\t\tthrow this.reportError(error)\n\t\t}\n\t}\n\n\t/** Deletes the buyer's cloud copy and turns cloud backup off on every installation. */\n\tasync deleteCloudBackup(): Promise<void> {\n\t\ttry {\n\t\t\tawait this.backup.delete()\n\t\t} catch (error) {\n\t\t\tthrow this.reportError(error)\n\t\t}\n\t}\n\n\t/** Read-only license view. Entitlements retain cache/signature/offline semantics. */\n\tasync getLicenseSummary(options: GetEntitlementOptions = {}): Promise<LicenseSummary> {\n\t\tawait this.initialize()\n\t\tlet offer: PayOfferResponse | null = null\n\t\ttry {\n\t\t\toffer = await this.fetchOffer(options.force)\n\t\t} catch {\n\t\t\t/* Offline: do not invent seller details. */\n\t\t}\n\t\treturn {\n\t\t\tprojectName: offer?.projectName ?? null,\n\t\t\tseller: offer?.seller ?? null,\n\t\t\tentitlement: await this.getEntitlement(options),\n\t\t\trecoveryEnabled: offer?.recoveryEnabled === true,\n\t\t}\n\t}\n\n\t/** Opens the provider's self-service portal; resolves null when the provider has none. */\n\tasync openCustomerPortal(options: CustomerPortalOptions = {}): Promise<string | null> {\n\t\tawait this.initialize()\n\t\ttry {\n\t\t\tconst endUserRef = await this.getEndUserRef()\n\t\t\tlet result = await this.api.getPortalUrl(endUserRef, undefined, this.config.locale)\n\t\t\tif (this.destroyed) return null\n\t\t\tif (result.accounts?.length) {\n\t\t\t\tif (!options.selectAccount)\n\t\t\t\t\tthrow new ExtenshiPayError(\n\t\t\t\t\t\tERROR_CODES.INVALID_REQUEST,\n\t\t\t\t\t\t'Choose a billing profile using selectAccount',\n\t\t\t\t\t)\n\t\t\t\tconst customerId = await options.selectAccount(result.accounts)\n\t\t\t\tif (customerId === null || this.destroyed) return null\n\t\t\t\tif (!result.accounts.some((a) => a.id === customerId))\n\t\t\t\t\tthrow new ExtenshiPayError(ERROR_CODES.INVALID_REQUEST, 'Invalid billing profile')\n\t\t\t\t// Recovery may replace this installation while the selector is open.\n\t\t\t\tif (endUserRef !== (await this.getEndUserRef()))\n\t\t\t\t\tthrow new ExtenshiPayError(\n\t\t\t\t\t\tERROR_CODES.INVALID_REQUEST,\n\t\t\t\t\t\t'Installation changed; open the portal again',\n\t\t\t\t\t)\n\t\t\t\tresult = await this.api.getPortalUrl(endUserRef, customerId, this.config.locale)\n\t\t\t}\n\t\t\tif (this.destroyed) return null\n\t\t\tconst { url } = result\n\t\t\tif (url) await (options.openUrl ?? (await import('../payment/checkout.js')).openInNewTab)(url)\n\t\t\treturn url\n\t\t} catch (error) {\n\t\t\tthrow this.reportError(error)\n\t\t}\n\t}\n\n\ton<K extends keyof ExtenshiPayEvents>(event: K, listener: Listener<ExtenshiPayEvents[K]>): () => void {\n\t\treturn this.emitter.on(event, listener)\n\t}\n\n\tonce<K extends keyof ExtenshiPayEvents>(event: K, listener: Listener<ExtenshiPayEvents[K]>): () => void {\n\t\treturn this.emitter.once(event, listener)\n\t}\n\n\toff<K extends keyof ExtenshiPayEvents>(event: K, listener: Listener<ExtenshiPayEvents[K]>): void {\n\t\tthis.emitter.off(event, listener)\n\t}\n\n\tonEntitlementChange(listener: Listener<Entitlement>): () => void {\n\t\treturn this.emitter.on('entitlement:changed', listener)\n\t}\n\n\tasync clearCache(): Promise<void> {\n\t\tthis.offer = null\n\t\tawait this.entitlements.clear()\n\t}\n\n\t/** Stops background refresh and drops listeners. */\n\tdestroy(): void {\n\t\tthis.destroyed = true\n\t\tthis.recovery.stop()\n\t\tthis.trial.stop()\n\t\tthis.entitlements.stopAutoRefresh()\n\t\tthis.emitter.removeAll()\n\t}\n\n\t/** Offer + signing key. Public in the full SDK (`getOffer`), internal here. */\n\tprotected fetchOffer(force = false): Promise<PayOfferResponse> {\n\t\tif (!force && this.offer && this.now() - this.offer.fetchedAt < OFFER_TTL_MS) {\n\t\t\treturn Promise.resolve(this.offer.value)\n\t\t}\n\t\tif (!this.offerInflight) {\n\t\t\tthis.offerInflight = this.api\n\t\t\t\t.getOffer(this.config.locale)\n\t\t\t\t.then(async (value) => {\n\t\t\t\t\tthis.offer = { value, fetchedAt: this.now() }\n\t\t\t\t\tawait this.rememberServerKey(value.entitlementPublicKey)\n\t\t\t\t\treturn value\n\t\t\t\t})\n\t\t\t\t.finally(() => {\n\t\t\t\t\tthis.offerInflight = null\n\t\t\t\t})\n\t\t}\n\t\treturn this.offerInflight\n\t}\n\n\tprivate get serverKeyStorageKey(): string {\n\t\treturn `extenshi-pay:${this.config.publishableKey}:entitlementPublicKey`\n\t}\n\n\tprivate async readSavedServerKey(): Promise<string | null> {\n\t\ttry {\n\t\t\tconst value = await this.storage.get(this.serverKeyStorageKey)\n\t\t\treturn typeof value === 'string' && PUBLIC_KEY_RE.test(value) ? value : null\n\t\t} catch {\n\t\t\treturn null\n\t\t}\n\t}\n\n\t/**\n\t * Keeps the server's key next to the license cache so a restart with no network can verify it.\n\t * Not with a bundled key: that one already covers the restart, and storage stays untrusted.\n\t */\n\tprivate async rememberServerKey(key: string | null | undefined): Promise<void> {\n\t\tif (typeof key !== 'string' || !PUBLIC_KEY_RE.test(key)) return\n\t\tthis.serverKey = key\n\t\tif (this.config.entitlementPublicKey || this.config.mock) return\n\t\ttry {\n\t\t\tif ((await this.readSavedServerKey()) !== key) await this.storage.set(this.serverKeyStorageKey, key)\n\t\t} catch (error) {\n\t\t\tlogger.debug('signing key not saved', error)\n\t\t}\n\t}\n\n\t/**\n\t * A license verified with the saved key alone is checked against the server once per start:\n\t * when the server's key differs (rotation, or an edited storage) the license is fetched again,\n\t * and dropped if it does not verify. Offline, the saved key stands until `offlineUntil`.\n\t */\n\tprivate async confirmSavedServerKey(): Promise<void> {\n\t\tconst used = this.entitlements.verifiedKey\n\t\tif (this.destroyed || !used || used === this.serverKey || used === this.config.entitlementPublicKey)\n\t\t\treturn\n\t\ttry {\n\t\t\tif ((await this.fetchOffer()).entitlementPublicKey === used || this.destroyed) return\n\t\t} catch {\n\t\t\treturn\n\t\t}\n\t\ttry {\n\t\t\tawait this.entitlements.refresh()\n\t\t} catch {\n\t\t\tawait this.entitlements.reverify().catch((error) => this.reportError(error))\n\t\t}\n\t}\n\n\tprivate get trialStartKey(): string {\n\t\treturn `extenshi-pay:${this.config.publishableKey}:trialStartedAt`\n\t}\n\n\t/** The synced trial start, or null (none, malformed, or storage.sync unavailable). */\n\tprivate async readTrialStartHint(): Promise<string | null> {\n\t\tif (!this.syncStorage) return null\n\t\ttry {\n\t\t\tconst value = await this.syncStorage.get(this.trialStartKey)\n\t\t\treturn typeof value === 'string' && Number.isFinite(Date.parse(value)) ? value : null\n\t\t} catch {\n\t\t\treturn null\n\t\t}\n\t}\n\n\t/** Syncs the verified trial start, keeping the earliest one seen. Never the installation id. */\n\tprivate async rememberTrialStart(): Promise<void> {\n\t\tconst trial = this.entitlements.getTrial()\n\t\tif (!this.syncStorage || !trial) return\n\t\ttry {\n\t\t\tconst synced = await this.readTrialStartHint()\n\t\t\tif (synced && Date.parse(synced) <= Date.parse(trial.startedAt)) return\n\t\t\tawait this.syncStorage.set(this.trialStartKey, trial.startedAt)\n\t\t} catch (error) {\n\t\t\tlogger.debug('trial start not synced', error)\n\t\t}\n\t}\n\n\tprotected reportError(error: unknown): ExtenshiPayError {\n\t\tconst err = ExtenshiPayError.from(error)\n\t\tlogger.warn(`${err.code}: ${err.message}`)\n\t\tthis.emitter.emit('error', err)\n\t\treturn err\n\t}\n}\n","import type { PaySellerPublic } from '../types/contract.js'\nimport { fill, SDK_STRINGS_EN, type SdkStrings } from './i18n.js'\n\n/** Treat even server-provided links as untrusted; never render executable protocols. */\nexport function publicContactUrl(value: string): string | null {\n\ttry {\n\t\tconst url = new URL(value)\n\t\tif (url.protocol === 'https:' && !url.username && !url.password) return url.href\n\t} catch {\n\t\t/* A plain email address is allowed below. */\n\t}\n\tif (/^[^\\s@?&#:]+@[^\\s@?&#:]+\\.[^\\s@?&#:]+$/.test(value)) return `mailto:${encodeURIComponent(value)}`\n\treturn null\n}\n\nexport function sellerDetails(seller: PaySellerPublic | null, t: SdkStrings = SDK_STRINGS_EN): HTMLElement {\n\tconst section = document.createElement('section')\n\tsection.className = 'extenshi-seller-details'\n\tconst name = document.createElement('p')\n\tname.textContent = seller ? fill(t.sellerProvidedBy, { name: seller.displayName }) : t.sellerUnavailable\n\tsection.append(name)\n\tconst link = (label: string, value: string | null) => {\n\t\tconst href = value ? publicContactUrl(value) : null\n\t\tif (!href) return\n\t\tconst a = document.createElement('a')\n\t\ta.textContent = label\n\t\ta.href = href\n\t\ta.target = '_blank'\n\t\ta.rel = 'noopener noreferrer'\n\t\ta.style.marginInlineEnd = '12px'\n\t\tsection.append(a)\n\t}\n\tif (seller) {\n\t\tlink(t.sellerSupport, seller.supportUrl)\n\t\tlink(t.sellerTerms, seller.termsUrl)\n\t\tlink(t.sellerRefunds, seller.refundPolicyUrl ?? null)\n\t}\n\tconst role = document.createElement('p')\n\trole.textContent = t.sellerRole\n\tsection.append(role)\n\treturn section\n}\n","import type { LicenseSummary } from '../types/entitlement.js'\nimport { ERROR_CODES, ExtenshiPayError } from '../types/errors.js'\nimport { fill, type SdkStrings, sdkDir, sdkLocale, sdkStrings } from './i18n.js'\nimport { sellerDetails } from './seller-details.js'\n\n/** A status label in the language, or the raw value for one we do not know. */\nfunction statusLabel(t: SdkStrings, status: string): string {\n\tconst map: Record<string, string> = {\n\t\tactive: t.statusActive,\n\t\tgrace: t.statusGrace,\n\t\texpired: t.statusExpired,\n\t\tnone: t.statusNone,\n\t}\n\treturn map[status] ?? status.replace(/_/g, ' ')\n}\n\n/** A provider subscription status (Stripe vocabulary) in the language. */\nexport function subscriptionStatusLabel(t: SdkStrings, status: string): string {\n\tconst map: Record<string, string> = {\n\t\tactive: t.subActive,\n\t\ttrialing: t.subTrialing,\n\t\tpast_due: t.subPastDue,\n\t\tcanceled: t.subCanceled,\n\t\tunpaid: t.subUnpaid,\n\t\tincomplete: t.subIncomplete,\n\t\tincomplete_expired: t.subIncompleteExpired,\n\t\tpaused: t.subPaused,\n\t}\n\treturn map[status] ?? status.replace(/_/g, ' ')\n}\n\nexport class LicensePanel {\n\tprivate dismiss: (() => void) | null = null\n\thide(): void {\n\t\tthis.dismiss?.()\n\t}\n\tshow(\n\t\tsummary: LicenseSummary,\n\t\tactions: {\n\t\t\trestore: () => Promise<LicenseSummary>\n\t\t\tmanage: () => Promise<string | null>\n\t\t},\n\t\tlocale: string | null = null,\n\t): Promise<void> {\n\t\tthis.hide()\n\t\tif (typeof document === 'undefined')\n\t\t\tthrow new ExtenshiPayError(\n\t\t\t\tERROR_CODES.INVALID_REQUEST,\n\t\t\t\t'Use getLicenseSummary outside an extension page',\n\t\t\t)\n\t\tconst t = sdkStrings(locale)\n\t\tconst lang = sdkLocale(locale)\n\t\tconst host = document.createElement('div')\n\t\thost.className = 'extenshi-license-host'\n\t\thost.setAttribute('lang', lang)\n\t\thost.setAttribute('dir', sdkDir(lang))\n\t\tconst root = host.attachShadow({ mode: 'open' })\n\t\tconst style = document.createElement('style')\n\t\tstyle.textContent = `dialog{font:15px/1.5 system-ui,sans-serif;color:#172033;background:#fff;border:1px solid #dce1e8;border-radius:16px;padding:24px;width:min(460px,calc(100vw - 64px));max-height:80vh}dialog::backdrop{background:#10182880}h2{margin:0}h3{font-size:16px;margin:0}article{border-block-end:1px solid #ddd;padding:16px 0}p{margin:8px 0}button{font:inherit;padding:10px 14px;margin:12px 8px 0 0;border:1px solid #cbd5e1;border-radius:8px;cursor:pointer;background:#fff;color:inherit}button:disabled{opacity:.5;cursor:wait}button:focus-visible,a:focus-visible{outline:3px solid #0ea5e9}a{color:#0369a1}.extenshi-seller-details{font-size:13px;margin-top:20px}`\n\t\tconst dialog = document.createElement('dialog')\n\t\tdialog.setAttribute('aria-label', t.licenseTitle)\n\t\tconst title = document.createElement('h2')\n\t\ttitle.textContent = t.licenseTitle\n\t\tconst content = document.createElement('div')\n\t\tconst feedback = document.createElement('p')\n\t\tfeedback.setAttribute('role', 'status')\n\t\tconst render = (state: LicenseSummary) => {\n\t\t\tcontent.replaceChildren()\n\t\t\tconst note = document.createElement('p')\n\t\t\tnote.textContent = state.projectName ?? t.licenseFallbackName\n\t\t\tcontent.append(note)\n\t\t\tif (!state.entitlement.items.length) {\n\t\t\t\tconst empty = document.createElement('p')\n\t\t\t\tempty.textContent = t.licenseNone\n\t\t\t\tcontent.append(empty)\n\t\t\t}\n\t\t\tfor (const item of state.entitlement.items) {\n\t\t\t\tconst article = document.createElement('article')\n\t\t\t\tconst heading = document.createElement('h3')\n\t\t\t\theading.textContent = item.title ?? item.sku\n\t\t\t\tconst status = document.createElement('p')\n\t\t\t\tconst kind =\n\t\t\t\t\titem.kind === 'one_time'\n\t\t\t\t\t\t? item.expiresAt\n\t\t\t\t\t\t\t? t.kindOneTime\n\t\t\t\t\t\t\t: t.kindLifetime\n\t\t\t\t\t\t: item.kind === 'subscription'\n\t\t\t\t\t\t\t? t.kindSubscription\n\t\t\t\t\t\t\t: t.kindLicense\n\t\t\t\tstatus.textContent = `${kind} · ${fill(t.statusLine, { status: statusLabel(t, item.status) })}`\n\t\t\t\tarticle.append(heading, status)\n\t\t\t\tif (item.expiresAt) {\n\t\t\t\t\tconst date = new Date(item.expiresAt)\n\t\t\t\t\tif (!Number.isNaN(date.getTime())) {\n\t\t\t\t\t\tconst expiry = document.createElement('p')\n\t\t\t\t\t\tconst when = date.toLocaleString(lang)\n\t\t\t\t\t\texpiry.textContent = fill(\n\t\t\t\t\t\t\titem.status === 'expired'\n\t\t\t\t\t\t\t\t? t.accessEnded\n\t\t\t\t\t\t\t\t: item.status === 'active' || item.status === 'grace'\n\t\t\t\t\t\t\t\t\t? t.accessUntil\n\t\t\t\t\t\t\t\t\t: t.accessRecordedEnd,\n\t\t\t\t\t\t\t{ date: when },\n\t\t\t\t\t\t)\n\t\t\t\t\t\tarticle.append(expiry)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfor (const sub of item.subscriptions ?? []) {\n\t\t\t\t\tconst row = document.createElement('p')\n\t\t\t\t\trow.textContent = `${fill(t.subscriptionLine, { status: subscriptionStatusLabel(t, sub.status) })}${sub.cancelAtPeriodEnd ? ` · ${t.renewalCanceled}` : ''}`\n\t\t\t\t\tarticle.append(row)\n\t\t\t\t}\n\t\t\t\tcontent.append(article)\n\t\t\t}\n\t\t\tconst freshness = document.createElement('p')\n\t\t\tfreshness.textContent = state.entitlement.requiresOnlineCheck\n\t\t\t\t? t.licenseOffline\n\t\t\t\t: state.entitlement.source === 'mock'\n\t\t\t\t\t? t.mockNotice\n\t\t\t\t\t: state.entitlement.source === 'cache'\n\t\t\t\t\t\t? t.licenseCached\n\t\t\t\t\t\t: t.licenseFresh\n\t\t\tcontent.append(freshness, sellerDetails(state.seller, t))\n\t\t}\n\t\trender(summary)\n\t\tdialog.append(title, content, feedback)\n\t\troot.append(style, dialog)\n\t\tdocument.body.append(host)\n\t\tif (typeof dialog.showModal !== 'function') {\n\t\t\thost.remove()\n\t\t\tthrow new ExtenshiPayError(\n\t\t\t\tERROR_CODES.INVALID_REQUEST,\n\t\t\t\t'This browser needs a custom license screen using getLicenseSummary',\n\t\t\t)\n\t\t}\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tlet closed = false\n\t\t\tconst close = () => {\n\t\t\t\tclosed = true\n\t\t\t\tthis.dismiss = null\n\t\t\t\tdialog.close()\n\t\t\t\thost.remove()\n\t\t\t\tresolve()\n\t\t\t}\n\t\t\tthis.dismiss = close\n\t\t\tdialog.addEventListener('cancel', (event) => {\n\t\t\t\tevent.preventDefault()\n\t\t\t\tclose()\n\t\t\t})\n\t\t\tconst buttons: HTMLButtonElement[] = []\n\t\t\tconst action = (label: string, run: () => Promise<void>) => {\n\t\t\t\tconst button = document.createElement('button')\n\t\t\t\tbutton.type = 'button'\n\t\t\t\tbutton.textContent = label\n\t\t\t\tbutton.addEventListener('click', async () => {\n\t\t\t\t\tbuttons.forEach((b) => {\n\t\t\t\t\t\tb.disabled = true\n\t\t\t\t\t})\n\t\t\t\t\tfeedback.textContent = ''\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait run()\n\t\t\t\t\t} catch {\n\t\t\t\t\t\tif (!closed) feedback.textContent = t.actionFailed\n\t\t\t\t\t} finally {\n\t\t\t\t\t\tif (!closed)\n\t\t\t\t\t\t\tbuttons.forEach((b) => {\n\t\t\t\t\t\t\t\tb.disabled = false\n\t\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t\tbuttons.push(button)\n\t\t\t\tdialog.append(button)\n\t\t\t}\n\t\t\tif (summary.recoveryEnabled)\n\t\t\t\taction(t.restorePurchase, async () => {\n\t\t\t\t\tconst updated = await actions.restore()\n\t\t\t\t\tif (!closed) render(updated)\n\t\t\t\t})\n\t\t\tif (summary.entitlement.source !== 'mock')\n\t\t\t\taction(t.manageBilling, async () => {\n\t\t\t\t\tconst url = await actions.manage()\n\t\t\t\t\tif (!url && !closed) feedback.textContent = t.noPortal\n\t\t\t\t})\n\t\t\tconst done = document.createElement('button')\n\t\t\tdone.type = 'button'\n\t\t\tdone.textContent = t.close\n\t\t\tdone.addEventListener('click', close)\n\t\t\tdialog.append(done)\n\t\t\ttry {\n\t\t\t\tdialog.showModal()\n\t\t\t} catch (error) {\n\t\t\t\tthis.dismiss = null\n\t\t\t\thost.remove()\n\t\t\t\treject(error)\n\t\t\t}\n\t\t})\n\t}\n}\n","import type { PayPortalAccount } from '../types/contract.js'\nimport { ERROR_CODES, ExtenshiPayError } from '../types/errors.js'\nimport { fill, sdkDir, sdkLocale, sdkStrings } from './i18n.js'\nimport { subscriptionStatusLabel } from './license-panel.js'\n\n/** Bundled UI only. Native dialog provides modal focus containment and Escape. */\nexport class BillingProfilePicker {\n\tprivate dismiss: (() => void) | null = null\n\n\thide(): void {\n\t\tthis.dismiss?.()\n\t}\n\n\tshow(accounts: PayPortalAccount[], locale: string | null = null): Promise<string | null> {\n\t\tthis.hide()\n\t\tif (typeof document === 'undefined')\n\t\t\tthrow new ExtenshiPayError(\n\t\t\t\tERROR_CODES.INVALID_REQUEST,\n\t\t\t\t'Provide selectAccount outside an extension page',\n\t\t\t)\n\t\tconst t = sdkStrings(locale)\n\t\tconst lang = sdkLocale(locale)\n\t\tconst host = document.createElement('div')\n\t\thost.className = 'extenshi-billing-profile-host'\n\t\thost.setAttribute('lang', lang)\n\t\thost.setAttribute('dir', sdkDir(lang))\n\t\tconst root = host.attachShadow({ mode: 'open' })\n\t\tconst style = document.createElement('style')\n\t\tstyle.textContent = `\n\t\t\tdialog{font:15px/1.5 system-ui,sans-serif;color:#172033;background:#fff;border:1px solid #dce1e8;border-radius:16px;padding:24px;width:min(440px,calc(100vw - 64px));max-height:80vh;box-shadow:0 20px 60px #0003}\n\t\t\tdialog::backdrop{background:#10182880}h2{margin:0 0 8px;font-size:22px}p{margin:0 0 16px;color:#526078}\n\t\t\tbutton{font:inherit;cursor:pointer;border:1px solid #dce1e8;border-radius:8px;background:#fff;color:inherit;padding:12px;text-align:left;width:100%;margin-top:10px}\n\t\t\tbutton:hover{background:#f3f6fa}button:focus-visible{outline:3px solid #0ea5e9;outline-offset:2px}strong,small{display:block}small{color:#526078;margin-top:4px}\n\t\t`\n\t\tconst dialog = document.createElement('dialog')\n\t\tdialog.setAttribute('aria-labelledby', 'billing-title')\n\t\tdialog.setAttribute('aria-describedby', 'billing-description')\n\t\tconst title = document.createElement('h2')\n\t\ttitle.id = 'billing-title'\n\t\ttitle.textContent = t.pickerTitle\n\t\tconst description = document.createElement('p')\n\t\tdescription.id = 'billing-description'\n\t\tdescription.textContent = t.pickerDescription\n\t\tdialog.append(title, description)\n\t\troot.append(style, dialog)\n\t\tdocument.body.append(host)\n\t\tif (typeof dialog.showModal !== 'function') {\n\t\t\thost.remove()\n\t\t\tthrow new ExtenshiPayError(\n\t\t\t\tERROR_CODES.INVALID_REQUEST,\n\t\t\t\t'This browser needs a custom selectAccount callback',\n\t\t\t)\n\t\t}\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst finish = (id: string | null) => {\n\t\t\t\tthis.dismiss = null\n\t\t\t\tdialog.close()\n\t\t\t\thost.remove()\n\t\t\t\tresolve(id)\n\t\t\t}\n\t\t\tthis.dismiss = () => finish(null)\n\t\t\tdialog.addEventListener('cancel', (event) => {\n\t\t\t\tevent.preventDefault()\n\t\t\t\tfinish(null)\n\t\t\t})\n\t\t\tfor (const account of accounts) {\n\t\t\t\tconst button = document.createElement('button')\n\t\t\t\tbutton.type = 'button'\n\t\t\t\tconst label = document.createElement('strong')\n\t\t\t\tlabel.textContent = account.label\n\t\t\t\tconst detail = document.createElement('small')\n\t\t\t\tconst recorded = new Date(account.createdAt)\n\t\t\t\tdetail.textContent = Number.isNaN(recorded.getTime())\n\t\t\t\t\t? ''\n\t\t\t\t\t: fill(t.pickerFirstRecorded, { date: recorded.toLocaleDateString(lang) })\n\t\t\t\tbutton.append(label, detail)\n\t\t\t\tfor (const subscription of account.subscriptions) {\n\t\t\t\t\tconst line = document.createElement('small')\n\t\t\t\t\tconst end = subscription.currentPeriodEnd ? new Date(subscription.currentPeriodEnd) : null\n\t\t\t\t\tconst cancellation = subscription.cancelAtPeriodEnd\n\t\t\t\t\t\t? ` · ${t.renewalCanceled}${end && !Number.isNaN(end.getTime()) ? ` · ${fill(t.periodEnds, { date: end.toLocaleDateString(lang) })}` : ''}`\n\t\t\t\t\t\t: ''\n\t\t\t\t\tline.textContent = `${subscription.title} · ${subscriptionStatusLabel(t, subscription.status)}${cancellation}`\n\t\t\t\t\tbutton.append(line)\n\t\t\t\t}\n\t\t\t\tbutton.addEventListener('click', () => finish(account.id))\n\t\t\t\tdialog.append(button)\n\t\t\t}\n\t\t\tconst cancel = document.createElement('button')\n\t\t\tcancel.type = 'button'\n\t\t\tcancel.textContent = t.pickerCancel\n\t\t\tcancel.addEventListener('click', () => finish(null))\n\t\t\tdialog.append(cancel)\n\t\t\ttry {\n\t\t\t\tdialog.showModal()\n\t\t\t} catch (error) {\n\t\t\t\tthis.dismiss = null\n\t\t\t\thost.remove()\n\t\t\t\treject(error)\n\t\t\t}\n\t\t})\n\t}\n}\n","/**\n * The paywall's header image: the extension's own icon in place of the\n * templates' generic glyph (lock, layers).\n *\n * Only images from the extension package or `data:image/` URLs: a remote\n * image would be a request to a third party on every paywall view. The\n * manifest icon is the default on the extension's own pages (popup, options)\n * only. A content script runs on the site's origin, where the package's files\n * load only when `web_accessible_resources` lists them, and the SDK never asks\n * for that.\n */\n\ninterface ExtensionRuntime {\n\tgetURL?: (path: string) => string\n\tgetManifest?: () => { icons?: Record<string, string> }\n}\n\nconst DATA_IMAGE_RE = /^data:image\\/[\\w.+-]+[;,]/i\n/** `chrome-extension://<id>/`, `moz-extension://<uuid>/`, `safari-web-extension://<id>/`. */\nconst PACKAGE_BASE_RE = /^[a-z-]+-extension:\\/\\/[^/]+\\/$/\n\nfunction extensionRuntime(): ExtensionRuntime | undefined {\n\tconst g = globalThis as {\n\t\tchrome?: { runtime?: ExtensionRuntime }\n\t\tbrowser?: { runtime?: ExtensionRuntime }\n\t}\n\treturn g.chrome?.runtime ?? g.browser?.runtime\n}\n\nfunction packageBase(runtime: ExtensionRuntime | undefined): string | null {\n\ttry {\n\t\tconst base = runtime?.getURL?.('')\n\t\treturn typeof base === 'string' && PACKAGE_BASE_RE.test(base) ? base : null\n\t} catch {\n\t\treturn null\n\t}\n}\n\nfunction onExtensionPage(base: string): boolean {\n\tconst href = (globalThis as { location?: { href?: string } }).location?.href\n\treturn typeof href === 'string' && href.startsWith(base)\n}\n\nfunction largestIcon(runtime: ExtensionRuntime | undefined): string {\n\tlet best: [size: number, path: string] | null = null\n\ttry {\n\t\tfor (const [size, path] of Object.entries(runtime?.getManifest?.().icons ?? {})) {\n\t\t\tconst n = Number(size)\n\t\t\tif (typeof path === 'string' && path && Number.isFinite(n) && (!best || n > best[0])) best = [n, path]\n\t\t}\n\t} catch {\n\t\t/* No manifest to read. */\n\t}\n\treturn best?.[1] ?? ''\n}\n\n/**\n * The header image for `PaywallOptions.icon`, or null to keep the template's\n * glyph: `false` opts out, a `data:image/` URL is used anywhere, a package path\n * (or the manifest's largest icon by default) only on the extension's pages.\n */\nexport function paywallIconUrl(option?: string | false): string | null {\n\tif (option === false) return null\n\tconst explicit = typeof option === 'string' ? option.trim() : ''\n\tif (DATA_IMAGE_RE.test(explicit)) return explicit\n\tconst runtime = extensionRuntime()\n\tconst base = packageBase(runtime)\n\tif (!base || !onExtensionPage(base)) return null\n\tconst path = explicit || largestIcon(runtime)\n\tif (!path) return null\n\ttry {\n\t\tconst url = new URL(path, base).href\n\t\treturn url.startsWith(base) ? url : null\n\t} catch {\n\t\treturn null\n\t}\n}\n","import type { PayOfferDto } from '../types/contract.js'\nimport type { PaywallStrings } from '../types/paywall.js'\n\nexport interface FormattedPrice {\n\t/** Currency symbol/code as the locale renders it (`$`, `€`, `US$`). */\n\tcurrency: string\n\t/** Numeric part (`9.99`, `9,99`). */\n\tamount: string\n\t/** The whole formatted price (`$9.99`). */\n\tfull: string\n}\n\nexport function formatPrice(amountMinor: number, currency: string, locale?: string | null): FormattedPrice {\n\tconst value = amountMinor / 100\n\tconst code = currency.toUpperCase()\n\ttry {\n\t\tconst formatter = new Intl.NumberFormat(locale ?? undefined, { style: 'currency', currency: code })\n\t\tconst parts = formatter.formatToParts(value)\n\t\treturn {\n\t\t\tcurrency: parts\n\t\t\t\t.filter((part) => part.type === 'currency')\n\t\t\t\t.map((part) => part.value)\n\t\t\t\t.join(''),\n\t\t\tamount: parts\n\t\t\t\t.filter((part) => part.type !== 'currency' && part.type !== 'literal')\n\t\t\t\t.map((part) => part.value)\n\t\t\t\t.join(''),\n\t\t\tfull: formatter.format(value),\n\t\t}\n\t} catch {\n\t\tconst amount = value.toFixed(2)\n\t\treturn { currency: code, amount, full: `${amount} ${code}` }\n\t}\n}\n\nexport function periodLabel(offer: PayOfferDto, strings: PaywallStrings): string {\n\tif (offer.kind !== 'subscription') return strings.periodOnce\n\treturn offer.interval === 'year' ? strings.periodYear : strings.periodMonth\n}\n","/**\n * The paywall's strings in a locale, from the SDK dictionary (./i18n.ts).\n * Do not add promotional claims without marketing/legal review (see\n * .claude/modules/paywall-templates.md).\n */\n\nimport type { PaywallStrings } from '../types/paywall.js'\nimport { SDK_STRINGS_EN, type SdkStrings, sdkStrings } from './i18n.js'\n\nfunction paywallStrings(t: SdkStrings): PaywallStrings {\n\treturn {\n\t\ttitle: t.title,\n\t\tdescription: t.description,\n\t\tupgrade: t.upgrade,\n\t\tcancel: t.cancel,\n\t\tdismiss: t.dismiss,\n\t\tremindLater: t.remindLater,\n\t\tcontinueFree: t.continueFree,\n\t\tcheckoutUnavailable: t.checkoutUnavailable,\n\t\tperiodMonth: t.periodMonth,\n\t\tperiodYear: t.periodYear,\n\t\tperiodOnce: t.periodOnce,\n\t\tfooter: t.footer,\n\t\trestorePurchase: t.restorePurchase,\n\t\tfeaturesHeading: t.featuresHeading,\n\t\tplansHeading: t.plansHeading,\n\t\tfreePlanName: t.freePlanName,\n\t\tpremiumPlanName: t.premiumPlanName,\n\t\tpopularBadge: t.popularBadge,\n\t\tunlockHeading: t.unlockHeading,\n\t}\n}\n\n/** English (the default and the fallback). */\nexport const DEFAULT_STRINGS: PaywallStrings = paywallStrings(SDK_STRINGS_EN)\n\nexport const MOCK_PAYMENT_NOTICE = SDK_STRINGS_EN.mockNotice\n\n/** The paywall strings for `locale` (English when we have no translation). */\nexport function stringsFor(locale: string | null | undefined): PaywallStrings {\n\treturn paywallStrings(sdkStrings(locale))\n}\n","export const html = \"<div class=\\\"ep-fullscreen-paywall\\\" id=\\\"fullscreenPaywall\\\" role=\\\"dialog\\\" aria-labelledby=\\\"fullscreen-title\\\"><div class=\\\"ep-fullscreen-background\\\"><div class=\\\"ep-background-pattern\\\"></div></div><div class=\\\"ep-fullscreen-header\\\"><div class=\\\"ep-fullscreen-logo\\\"><svg width=\\\"40\\\" height=\\\"40\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><path d=\\\"M12 2L2 7l10 5 10-5-10-5z\\\"></path><path d=\\\"M2 17l10 5 10-5\\\"></path><path d=\\\"M2 12l10 5 10-5\\\"></path></svg><span class=\\\"ep-fullscreen-logo-text\\\">{{brandName}}</span></div><button class=\\\"ep-fullscreen-close\\\" aria-label=\\\"Close paywall\\\" data-ep-action=\\\"closeFullscreen\\\"><svg width=\\\"24\\\" height=\\\"24\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><line x1=\\\"18\\\" y1=\\\"6\\\" x2=\\\"6\\\" y2=\\\"18\\\"></line><line x1=\\\"6\\\" y1=\\\"6\\\" x2=\\\"18\\\" y2=\\\"18\\\"></line></svg></button></div><div class=\\\"ep-fullscreen-content\\\"><div class=\\\"ep-fullscreen-container\\\"><div class=\\\"ep-fullscreen-hero\\\"><div class=\\\"ep-hero-icon\\\"><svg width=\\\"80\\\" height=\\\"80\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><path d=\\\"M12 2L2 7l10 5 10-5-10-5z\\\"></path><path d=\\\"M2 17l10 5 10-5\\\"></path><path d=\\\"M2 12l10 5 10-5\\\"></path></svg></div><h1 class=\\\"ep-heading-1\\\" id=\\\"fullscreen-title\\\">{{title}}</h1><p class=\\\"ep-hero-description\\\">{{description}}</p></div><div class=\\\"ep-fullscreen-features\\\"><div class=\\\"ep-features-grid\\\"><div class=\\\"ep-feature-card\\\"><div class=\\\"ep-feature-card-icon\\\"><svg width=\\\"32\\\" height=\\\"32\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><path d=\\\"M22 12h-4l-3 9L9 3l-3 9H2\\\"></path></svg></div><h3 class=\\\"ep-feature-card-title\\\">{{feature1Title}}</h3><p class=\\\"ep-feature-card-description\\\">{{feature1Description}}</p></div><div class=\\\"ep-feature-card\\\"><div class=\\\"ep-feature-card-icon\\\"><svg width=\\\"32\\\" height=\\\"32\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><path d=\\\"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z\\\"></path></svg></div><h3 class=\\\"ep-feature-card-title\\\">{{feature2Title}}</h3><p class=\\\"ep-feature-card-description\\\">{{feature2Description}}</p></div><div class=\\\"ep-feature-card\\\"><div class=\\\"ep-feature-card-icon\\\"><svg width=\\\"32\\\" height=\\\"32\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><path d=\\\"M13 2L3 14h9l-1 8 10-12h-9l1-8z\\\"></path></svg></div><h3 class=\\\"ep-feature-card-title\\\">{{feature3Title}}</h3><p class=\\\"ep-feature-card-description\\\">{{feature3Description}}</p></div><div class=\\\"ep-feature-card\\\"><div class=\\\"ep-feature-card-icon\\\"><svg width=\\\"32\\\" height=\\\"32\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><path d=\\\"M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z\\\"></path><polyline points=\\\"7.5,4.21 12,6.81 16.5,4.21\\\"></polyline><polyline points=\\\"7.5,19.79 7.5,14.6 3,12\\\"></polyline><polyline points=\\\"21,12 16.5,14.6 16.5,19.79\\\"></polyline></svg></div><h3 class=\\\"ep-feature-card-title\\\">{{feature4Title}}</h3><p class=\\\"ep-feature-card-description\\\">{{feature4Description}}</p></div></div></div><div class=\\\"ep-fullscreen-pricing\\\"><div class=\\\"ep-pricing-header\\\"><h2 class=\\\"ep-heading-2\\\">{{plansHeading}}</h2><p class=\\\"ep-pricing-subtitle\\\">{{pricingSubtitle}}</p></div><div class=\\\"ep-pricing-plans\\\"><div class=\\\"ep-pricing-plan\\\"><div class=\\\"ep-pricing-plan-header\\\"><h3 class=\\\"ep-pricing-plan-title\\\">{{freePlanName}}</h3><div class=\\\"ep-pricing-plan-price\\\"><span class=\\\"ep-pricing-currency\\\">{{currency}}</span><span class=\\\"ep-pricing-amount\\\">0</span></div><p class=\\\"ep-pricing-plan-description\\\">{{freeDescription}}</p></div><ul class=\\\"ep-pricing-plan-features\\\"><li class=\\\"ep-pricing-feature\\\"><svg class=\\\"ep-pricing-feature-icon\\\" width=\\\"20\\\" height=\\\"20\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><polyline points=\\\"20,6 9,17 4,12\\\"></polyline></svg> {{freeFeature1}} </li><li class=\\\"ep-pricing-feature\\\"><svg class=\\\"ep-pricing-feature-icon\\\" width=\\\"20\\\" height=\\\"20\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><polyline points=\\\"20,6 9,17 4,12\\\"></polyline></svg> {{freeFeature2}} </li><li class=\\\"ep-pricing-feature ep-pricing-feature-disabled\\\"><svg class=\\\"ep-pricing-feature-icon\\\" width=\\\"20\\\" height=\\\"20\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><line x1=\\\"18\\\" y1=\\\"6\\\" x2=\\\"6\\\" y2=\\\"18\\\"></line><line x1=\\\"6\\\" y1=\\\"6\\\" x2=\\\"18\\\" y2=\\\"18\\\"></line></svg> {{freeFeature3}} </li></ul><button class=\\\"ep-btn ep-btn-secondary ep-btn-full\\\" data-ep-action=\\\"continueFree\\\"> {{continueButtonText}} </button></div><div class=\\\"ep-pricing-plan ep-pricing-plan-premium\\\"><div class=\\\"ep-pricing-plan-badge\\\">{{premiumBadge}}</div><div class=\\\"ep-pricing-plan-header\\\"><h3 class=\\\"ep-pricing-plan-title\\\">{{premiumPlanName}}</h3><div class=\\\"ep-pricing-plan-price\\\"><span class=\\\"ep-pricing-currency\\\">{{currency}}</span><span class=\\\"ep-pricing-amount\\\">{{price}}</span><span class=\\\"ep-pricing-period\\\">{{period}}</span></div><p class=\\\"ep-pricing-plan-description\\\">{{premiumDescription}}</p></div><ul class=\\\"ep-pricing-plan-features\\\"><li class=\\\"ep-pricing-feature\\\"><svg class=\\\"ep-pricing-feature-icon\\\" width=\\\"20\\\" height=\\\"20\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><polyline points=\\\"20,6 9,17 4,12\\\"></polyline></svg> {{premiumFeature1}} </li><li class=\\\"ep-pricing-feature\\\"><svg class=\\\"ep-pricing-feature-icon\\\" width=\\\"20\\\" height=\\\"20\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><polyline points=\\\"20,6 9,17 4,12\\\"></polyline></svg> {{premiumFeature2}} </li><li class=\\\"ep-pricing-feature\\\"><svg class=\\\"ep-pricing-feature-icon\\\" width=\\\"20\\\" height=\\\"20\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><polyline points=\\\"20,6 9,17 4,12\\\"></polyline></svg> {{premiumFeature3}} </li><li class=\\\"ep-pricing-feature\\\"><svg class=\\\"ep-pricing-feature-icon\\\" width=\\\"20\\\" height=\\\"20\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><polyline points=\\\"20,6 9,17 4,12\\\"></polyline></svg> {{premiumFeature4}} </li></ul><button class=\\\"ep-btn ep-btn-primary ep-btn-lg ep-btn-full\\\" data-ep-action=\\\"upgradeNow\\\"> {{upgradeButtonText}} </button></div></div></div><div class=\\\"ep-fullscreen-trial\\\"><div class=\\\"ep-trial-card\\\"><div class=\\\"ep-trial-icon\\\"><svg width=\\\"32\\\" height=\\\"32\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><path d=\\\"M22 11.08V12a10 10 0 1 1-5.93-9.14\\\"></path><polyline points=\\\"22,4 12,14.01 9,11.01\\\"></polyline></svg></div><h3 class=\\\"ep-trial-title\\\">{{trialTitle}}</h3><p class=\\\"ep-trial-description\\\">{{trialDescription}}</p><button class=\\\"ep-btn ep-btn-secondary ep-btn-lg\\\" data-ep-action=\\\"startTrial\\\"> {{trialButtonText}} </button></div></div></div></div></div>\";\nexport const css = \".ep-fullscreen-paywall{position:fixed;top:0;left:0;right:0;bottom:0;background-color:var(--ep-bg-primary);z-index:var(--ep-z-modal);display:flex;flex-direction:column;animation:ep-fullscreen-in var(--ep-transition-slow);overflow-y:auto}.ep-fullscreen-paywall.ep-fullscreen-closing{animation:ep-fullscreen-out var(--ep-transition-slow)}.ep-fullscreen-background{position:absolute;top:0;left:0;right:0;bottom:0;overflow:hidden;z-index:-1}.ep-background-pattern{position:absolute;top:-50%;left:-50%;width:200%;height:200%;background:linear-gradient(45deg,transparent 30%,rgba(14,165,233,0.03) 50%,transparent 70%);background-size:60px 60px;animation:ep-background-pattern var(--ep-transition-slow) infinite linear}:host([data-theme=\\\"dark\\\"]) .ep-background-pattern{background:linear-gradient(45deg,transparent 30%,rgba(14,165,233,0.05) 50%,transparent 70%)}.ep-fullscreen-header{display:flex;justify-content:space-between;align-items:center;padding:var(--ep-space-6) var(--ep-space-8);border-bottom:1px solid var(--ep-border-primary);background-color:var(--ep-bg-secondary);backdrop-filter:blur(10px);z-index:1}.ep-fullscreen-logo{display:flex;align-items:center;gap:var(--ep-space-3);color:var(--ep-primary-600)}.ep-fullscreen-logo-text{font-size:var(--ep-font-size-xl);font-weight:var(--ep-font-weight-bold);color:var(--ep-text-primary)}.ep-fullscreen-close{background:none;border:none;color:var(--ep-text-tertiary);cursor:pointer;padding:var(--ep-space-2);border-radius:var(--ep-radius-md);transition:all var(--ep-transition-fast)}.ep-fullscreen-close:hover{color:var(--ep-text-primary);background-color:var(--ep-bg-tertiary)}.ep-fullscreen-content{flex:1;padding:var(--ep-space-8);display:flex;align-items:center;justify-content:center}.ep-fullscreen-container{max-width:1200px;width:100%;margin:0 auto}.ep-fullscreen-hero{text-align:center;margin-bottom:var(--ep-space-16)}.ep-hero-icon{width:120px;height:120px;margin:0 auto var(--ep-space-6);background:linear-gradient(135deg,var(--ep-primary-500),var(--ep-primary-600));border-radius:var(--ep-radius-2xl);display:flex;align-items:center;justify-content:center;color:white;box-shadow:var(--ep-shadow-lg);animation:ep-hero-icon-in var(--ep-transition-slow) 0.2s both}.ep-fullscreen-hero .ep-heading-1{font-size:var(--ep-font-size-5xl);margin-bottom:var(--ep-space-6);background:linear-gradient(135deg,var(--ep-primary-600),var(--ep-primary-700));-webkit-background-clip:text;-webkit-text-fill-color:transparent;background-clip:text;animation:ep-hero-title-in var(--ep-transition-slow) 0.3s both}.ep-hero-description{font-size:var(--ep-font-size-xl);color:var(--ep-text-secondary);max-width:600px;margin:0 auto;line-height:var(--ep-line-height-relaxed);animation:ep-hero-description-in var(--ep-transition-slow) 0.4s both}.ep-fullscreen-features{margin-bottom:var(--ep-space-16)}.ep-features-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(280px,1fr));gap:var(--ep-space-6)}.ep-feature-card{background-color:var(--ep-bg-secondary);border:1px solid var(--ep-border-primary);border-radius:var(--ep-radius-xl);padding:var(--ep-space-8);text-align:center;box-shadow:var(--ep-shadow-sm);transition:all var(--ep-transition-normal);opacity:0;transform:translateY(20px);animation:ep-feature-card-in var(--ep-transition-slow) both}.ep-feature-card:hover{transform:translateY(-4px);box-shadow:var(--ep-shadow-lg)}.ep-feature-card-icon{width:80px;height:80px;margin:0 auto var(--ep-space-4);background:linear-gradient(135deg,var(--ep-primary-500),var(--ep-primary-600));border-radius:var(--ep-radius-xl);display:flex;align-items:center;justify-content:center;color:white}.ep-feature-card-title{font-size:var(--ep-font-size-xl);font-weight:var(--ep-font-weight-semibold);color:var(--ep-text-primary);margin-bottom:var(--ep-space-3)}.ep-feature-card-description{color:var(--ep-text-secondary);line-height:var(--ep-line-height-relaxed);margin:0}.ep-fullscreen-pricing{margin-bottom:var(--ep-space-16)}.ep-pricing-header{text-align:center;margin-bottom:var(--ep-space-10)}.ep-pricing-header .ep-heading-2{font-size:var(--ep-font-size-4xl);margin-bottom:var(--ep-space-4)}.ep-pricing-subtitle{font-size:var(--ep-font-size-lg);color:var(--ep-text-secondary);margin:0}.ep-pricing-plans{display:grid;grid-template-columns:repeat(auto-fit,minmax(320px,1fr));gap:var(--ep-space-8);max-width:800px;margin:0 auto}.ep-pricing-plan{position:relative;background-color:var(--ep-bg-secondary);border:1px solid var(--ep-border-primary);border-radius:var(--ep-radius-xl);padding:var(--ep-space-8);box-shadow:var(--ep-shadow-md);transition:all var(--ep-transition-normal);opacity:0;transform:translateY(20px);animation:ep-pricing-plan-in var(--ep-transition-slow) both}.ep-pricing-plan:hover{transform:translateY(-4px);box-shadow:var(--ep-shadow-lg)}.ep-pricing-plan-premium{border-color:var(--ep-primary-300);box-shadow:var(--ep-shadow-xl);transform:scale(1.05)}.ep-pricing-plan-premium:hover{transform:scale(1.05) translateY(-4px)}.ep-pricing-plan-badge{position:absolute;top:-16px;left:50%;transform:translateX(-50%);background:linear-gradient(135deg,var(--ep-primary-500),var(--ep-primary-600));color:white;padding:var(--ep-space-2) var(--ep-space-6);border-radius:var(--ep-radius-full);font-size:var(--ep-font-size-sm);font-weight:var(--ep-font-weight-semibold);white-space:nowrap}.ep-pricing-plan-header{text-align:center;margin-bottom:var(--ep-space-8)}.ep-pricing-plan-title{font-size:var(--ep-font-size-2xl);font-weight:var(--ep-font-weight-bold);color:var(--ep-text-primary);margin-bottom:var(--ep-space-4)}.ep-pricing-plan-price{display:flex;align-items:baseline;justify-content:center;gap:var(--ep-space-2);margin-bottom:var(--ep-space-3)}.ep-pricing-currency{font-size:var(--ep-font-size-xl);font-weight:var(--ep-font-weight-medium);color:var(--ep-text-secondary)}.ep-pricing-amount{font-size:var(--ep-font-size-5xl);font-weight:var(--ep-font-weight-bold);color:var(--ep-text-primary)}.ep-pricing-period{font-size:var(--ep-font-size-xl);color:var(--ep-text-secondary)}.ep-pricing-plan-description{color:var(--ep-text-secondary);margin:0}.ep-pricing-plan-features{list-style:none;padding:0;margin:0 0 var(--ep-space-8) 0}.ep-pricing-feature{display:flex;align-items:center;gap:var(--ep-space-3);padding:var(--ep-space-3) 0;color:var(--ep-text-primary);font-size:var(--ep-font-size-base)}.ep-pricing-feature-disabled{color:var(--ep-text-tertiary)}.ep-pricing-feature-icon{color:var(--ep-success-500);flex-shrink:0}.ep-pricing-feature-disabled .ep-pricing-feature-icon{color:var(--ep-text-tertiary)}.ep-fullscreen-trial{text-align:center}.ep-trial-card{background:linear-gradient(135deg,var(--ep-success-50),var(--ep-success-100));border:1px solid var(--ep-success-200);border-radius:var(--ep-radius-xl);padding:var(--ep-space-8);max-width:600px;margin:0 auto;box-shadow:var(--ep-shadow-md)}:host([data-theme=\\\"dark\\\"]) .ep-trial-card{background:linear-gradient(135deg,rgba(16,185,129,0.1),rgba(16,185,129,0.15));border-color:rgba(16,185,129,0.3)}.ep-trial-icon{width:80px;height:80px;margin:0 auto var(--ep-space-4);background:linear-gradient(135deg,var(--ep-success-500),var(--ep-success-600));border-radius:var(--ep-radius-xl);display:flex;align-items:center;justify-content:center;color:white}.ep-trial-title{font-size:var(--ep-font-size-2xl);font-weight:var(--ep-font-weight-bold);color:var(--ep-success-700);margin-bottom:var(--ep-space-3)}:host([data-theme=\\\"dark\\\"]) .ep-trial-title{color:var(--ep-success-400)}.ep-trial-description{color:var(--ep-success-600);font-size:var(--ep-font-size-lg);line-height:var(--ep-line-height-relaxed);margin-bottom:var(--ep-space-6)}:host([data-theme=\\\"dark\\\"]) .ep-trial-description{color:var(--ep-success-300)}.ep-theme-toggle{position:fixed;top:var(--ep-space-4);right:var(--ep-space-4);z-index:var(--ep-z-tooltip)}@keyframes ep-fullscreen-in{from{opacity:0;transform:scale(0.98)}to{opacity:1;transform:scale(1)}}@keyframes ep-fullscreen-out{from{opacity:1;transform:scale(1)}to{opacity:0;transform:scale(0.98)}}@keyframes ep-background-pattern{from{transform:translateX(0) translateY(0)}to{transform:translateX(-60px) translateY(-60px)}}@keyframes ep-hero-icon-in{from{opacity:0;transform:scale(0.8)}to{opacity:1;transform:scale(1)}}@keyframes ep-hero-title-in{from{opacity:0;transform:translateY(20px)}to{opacity:1;transform:translateY(0)}}@keyframes ep-hero-description-in{from{opacity:0;transform:translateY(20px)}to{opacity:1;transform:translateY(0)}}@keyframes ep-feature-card-in{from{opacity:0;transform:translateY(20px)}to{opacity:1;transform:translateY(0)}}@keyframes ep-pricing-plan-in{from{opacity:0;transform:translateY(20px)}to{opacity:1;transform:translateY(0)}}@media (max-width:1024px){.ep-fullscreen-content{padding:var(--ep-space-6)}.ep-fullscreen-hero{margin-bottom:var(--ep-space-12)}.ep-fullscreen-features{margin-bottom:var(--ep-space-12)}.ep-fullscreen-pricing{margin-bottom:var(--ep-space-12)}.ep-features-grid{grid-template-columns:repeat(auto-fit,minmax(250px,1fr));gap:var(--ep-space-4)}.ep-pricing-plans{gap:var(--ep-space-6)}}@media (max-width:768px){.ep-fullscreen-header{padding:var(--ep-space-4) var(--ep-space-6)}.ep-fullscreen-content{padding:var(--ep-space-4)}.ep-fullscreen-hero .ep-heading-1{font-size:var(--ep-font-size-3xl)}.ep-hero-description{font-size:var(--ep-font-size-lg)}.ep-hero-icon{width:80px;height:80px}.ep-features-grid{grid-template-columns:1fr}.ep-pricing-plans{grid-template-columns:1fr}.ep-pricing-plan-premium{transform:none}.ep-pricing-plan-premium:hover{transform:translateY(-4px)}.ep-feature-card{padding:var(--ep-space-6)}.ep-feature-card-icon{width:60px;height:60px}.ep-pricing-plan{padding:var(--ep-space-6)}.ep-pricing-amount{font-size:var(--ep-font-size-4xl)}}@media (max-width:480px){.ep-fullscreen-header{padding:var(--ep-space-3) var(--ep-space-4)}.ep-fullscreen-logo-text{font-size:var(--ep-font-size-lg)}.ep-fullscreen-content{padding:var(--ep-space-3)}.ep-fullscreen-hero .ep-heading-1{font-size:var(--ep-font-size-2xl)}.ep-hero-description{font-size:var(--ep-font-size-base)}.ep-hero-icon{width:60px;height:60px}.ep-pricing-header .ep-heading-2{font-size:var(--ep-font-size-2xl)}.ep-pricing-amount{font-size:var(--ep-font-size-3xl)}.ep-feature-card-icon{width:48px;height:48px}.ep-trial-icon{width:60px;height:60px}}@media (prefers-contrast:high){.ep-fullscreen-paywall{background-color:var(--ep-bg-primary)}.ep-feature-card{border:2px solid var(--ep-border-secondary)}.ep-pricing-plan{border:2px solid var(--ep-border-secondary)}.ep-pricing-plan-premium{border:2px solid var(--ep-primary-500)}.ep-trial-card{border:2px solid var(--ep-success-500)}}@media (prefers-reduced-motion:reduce){.ep-fullscreen-paywall{animation:none}.ep-background-pattern{animation:none}.ep-hero-icon{animation:none}.ep-fullscreen-hero .ep-heading-1{animation:none}.ep-hero-description{animation:none}.ep-feature-card{animation:none;opacity:1;transform:none}.ep-pricing-plan{animation:none;opacity:1;transform:none}.ep-pricing-plan-premium{transform:none}.ep-feature-card:hover{transform:none}.ep-pricing-plan:hover{transform:none}}\";\nexport default { html, css };","/**\n * The five templates from `@extenshi/paywall-templates`, inlined at build\n * time by build/paywall-templates-plugin.mjs. No runtime fetch, no\n * `web_accessible_resources`, no remote code.\n */\n\nimport sharedCss from 'virtual:extenshi-paywall-shared-css'\nimport * as fullscreen from '@extenshi/paywall-templates/fullscreen'\nimport * as inline from '@extenshi/paywall-templates/inline'\nimport * as minimal from '@extenshi/paywall-templates/minimal'\nimport * as modal from '@extenshi/paywall-templates/modal'\nimport * as sidebar from '@extenshi/paywall-templates/sidebar'\nimport type { PaywallMode } from '../types/paywall.js'\n\nexport interface PaywallTemplate {\n\thtml: string\n\tcss: string\n}\n\nexport const PAYWALL_SHARED_CSS: string = sharedCss\n\nexport const PAYWALL_TEMPLATES: Record<PaywallMode, PaywallTemplate> = {\n\tmodal: { html: modal.html, css: modal.css },\n\tinline: { html: inline.html, css: inline.css },\n\tsidebar: { html: sidebar.html, css: sidebar.css },\n\tfullscreen: { html: fullscreen.html, css: fullscreen.css },\n\tminimal: { html: minimal.html, css: minimal.css },\n}\n\nexport const PAYWALL_MODES = Object.keys(PAYWALL_TEMPLATES) as PaywallMode[]\n","export const html = \"<div class=\\\"ep-modal-backdrop\\\" id=\\\"paywallModal\\\" role=\\\"dialog\\\" aria-labelledby=\\\"paywall-title\\\" aria-describedby=\\\"paywall-description\\\"><div class=\\\"ep-modal-container\\\"><button class=\\\"ep-modal-close\\\" aria-label=\\\"Close paywall\\\" data-ep-action=\\\"closePaywall\\\"><svg width=\\\"24\\\" height=\\\"24\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><line x1=\\\"18\\\" y1=\\\"6\\\" x2=\\\"6\\\" y2=\\\"18\\\"></line><line x1=\\\"6\\\" y1=\\\"6\\\" x2=\\\"18\\\" y2=\\\"18\\\"></line></svg></button><div class=\\\"ep-modal-content\\\"><div class=\\\"ep-modal-header\\\"><div class=\\\"ep-modal-icon\\\"><svg width=\\\"48\\\" height=\\\"48\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><rect x=\\\"3\\\" y=\\\"11\\\" width=\\\"18\\\" height=\\\"11\\\" rx=\\\"2\\\" ry=\\\"2\\\"></rect><path d=\\\"m7 11V7a5 5 0 0 1 10 0v4\\\"></path></svg></div><h2 class=\\\"ep-heading-2\\\" id=\\\"paywall-title\\\">{{title}}</h2><p class=\\\"ep-text-body\\\" id=\\\"paywall-description\\\">{{description}}</p></div><div class=\\\"ep-modal-features\\\"><h3 class=\\\"ep-heading-3\\\">{{featuresHeading}}</h3><ul class=\\\"ep-feature-list\\\"><li class=\\\"ep-feature-item\\\"><svg class=\\\"ep-feature-icon\\\" width=\\\"20\\\" height=\\\"20\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><polyline points=\\\"20,6 9,17 4,12\\\"></polyline></svg><span>{{feature1}}</span></li><li class=\\\"ep-feature-item\\\"><svg class=\\\"ep-feature-icon\\\" width=\\\"20\\\" height=\\\"20\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><polyline points=\\\"20,6 9,17 4,12\\\"></polyline></svg><span>{{feature2}}</span></li><li class=\\\"ep-feature-item\\\"><svg class=\\\"ep-feature-icon\\\" width=\\\"20\\\" height=\\\"20\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><polyline points=\\\"20,6 9,17 4,12\\\"></polyline></svg><span>{{feature3}}</span></li><li class=\\\"ep-feature-item\\\"><svg class=\\\"ep-feature-icon\\\" width=\\\"20\\\" height=\\\"20\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><polyline points=\\\"20,6 9,17 4,12\\\"></polyline></svg><span>{{feature4}}</span></li><li class=\\\"ep-feature-item\\\"><svg class=\\\"ep-feature-icon\\\" width=\\\"20\\\" height=\\\"20\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><polyline points=\\\"20,6 9,17 4,12\\\"></polyline></svg><span>{{feature5}}</span></li><li class=\\\"ep-feature-item\\\"><svg class=\\\"ep-feature-icon\\\" width=\\\"20\\\" height=\\\"20\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><polyline points=\\\"20,6 9,17 4,12\\\"></polyline></svg><span>{{feature6}}</span></li></ul></div><div class=\\\"ep-modal-pricing\\\"><div class=\\\"ep-pricing-card\\\"><div class=\\\"ep-pricing-header\\\"><div class=\\\"ep-pricing-price\\\"><span class=\\\"ep-pricing-currency\\\">{{currency}}</span><span class=\\\"ep-pricing-amount\\\">{{price}}</span><span class=\\\"ep-pricing-period\\\">{{period}}</span></div><p class=\\\"ep-pricing-description\\\">{{pricingDescription}}</p></div><div class=\\\"ep-trial-info\\\"><p class=\\\"ep-text-sm\\\">{{trialInfo}}</p></div></div></div><div class=\\\"ep-modal-actions\\\"><button class=\\\"ep-btn ep-btn-primary ep-btn-lg ep-btn-full\\\" data-ep-action=\\\"upgradeNow\\\"> {{upgradeButtonText}} </button><button class=\\\"ep-btn ep-btn-ghost ep-btn-sm\\\" data-ep-action=\\\"closePaywall\\\"> {{cancelButtonText}} </button></div><div class=\\\"ep-modal-footer\\\"><p class=\\\"ep-text-sm\\\">{{footerText}}</p></div></div></div></div>\";\nexport const css = \".ep-modal-backdrop{position:fixed;top:0;left:0;right:0;bottom:0;background-color:rgba(0,0,0,0.75);backdrop-filter:blur(4px);z-index:var(--ep-z-modal);display:flex;align-items:center;justify-content:center;padding:var(--ep-space-4);animation:ep-modal-backdrop-in var(--ep-transition-normal)}.ep-modal-backdrop.ep-modal-closing{animation:ep-modal-backdrop-out var(--ep-transition-normal)}.ep-modal-container{position:relative;background-color:var(--ep-bg-secondary);border-radius:var(--ep-radius-xl);box-shadow:var(--ep-shadow-xl);max-width:480px;width:100%;max-height:90vh;overflow-y:auto;animation:ep-modal-container-in var(--ep-transition-normal)}.ep-modal-backdrop.ep-modal-closing .ep-modal-container{animation:ep-modal-container-out var(--ep-transition-normal)}.ep-modal-close{position:absolute;top:var(--ep-space-4);right:var(--ep-space-4);background:none;border:none;color:var(--ep-text-tertiary);cursor:pointer;padding:var(--ep-space-2);border-radius:var(--ep-radius-md);transition:all var(--ep-transition-fast);z-index:1}.ep-modal-close:hover{color:var(--ep-text-primary);background-color:var(--ep-bg-tertiary)}.ep-modal-close:focus{outline:2px solid var(--ep-primary-500);outline-offset:2px}.ep-modal-content{padding:var(--ep-space-8);padding-top:var(--ep-space-12)}.ep-modal-header{text-align:center;margin-bottom:var(--ep-space-8)}.ep-modal-icon{width:80px;height:80px;margin:0 auto var(--ep-space-4);background:linear-gradient(135deg,var(--ep-primary-500),var(--ep-primary-600));border-radius:var(--ep-radius-2xl);display:flex;align-items:center;justify-content:center;color:white}.ep-modal-header .ep-heading-2{margin-bottom:var(--ep-space-3)}.ep-modal-header .ep-text-body{margin-bottom:0;font-size:var(--ep-font-size-lg)}.ep-modal-features{margin-bottom:var(--ep-space-8)}.ep-modal-features .ep-heading-3{margin-bottom:var(--ep-space-4);text-align:center}.ep-feature-list{list-style:none;padding:0;margin:0}.ep-feature-item{display:flex;align-items:center;gap:var(--ep-space-3);padding:var(--ep-space-3) 0;border-bottom:1px solid var(--ep-border-primary)}.ep-feature-item:last-child{border-bottom:none}.ep-feature-icon{color:var(--ep-success-500);flex-shrink:0}.ep-feature-item span{color:var(--ep-text-primary);font-weight:var(--ep-font-weight-medium)}.ep-modal-pricing{margin-bottom:var(--ep-space-8)}.ep-pricing-card{background:linear-gradient(135deg,var(--ep-primary-50),var(--ep-primary-100));border:1px solid var(--ep-primary-200);border-radius:var(--ep-radius-lg);padding:var(--ep-space-6);text-align:center}:host([data-theme=\\\"dark\\\"]) .ep-pricing-card{background:linear-gradient(135deg,var(--ep-primary-900),var(--ep-primary-800));border-color:var(--ep-primary-700)}.ep-pricing-header{margin-bottom:var(--ep-space-4)}.ep-pricing-price{display:flex;align-items:baseline;justify-content:center;gap:var(--ep-space-1);margin-bottom:var(--ep-space-2)}.ep-pricing-currency{font-size:var(--ep-font-size-lg);font-weight:var(--ep-font-weight-medium);color:var(--ep-text-secondary)}.ep-pricing-amount{font-size:var(--ep-font-size-4xl);font-weight:var(--ep-font-weight-bold);color:var(--ep-text-primary)}.ep-pricing-period{font-size:var(--ep-font-size-lg);color:var(--ep-text-secondary)}.ep-pricing-description{color:var(--ep-text-secondary);margin:0}.ep-pricing-header:last-child,.ep-pricing-price:last-child{margin-bottom:0}.ep-trial-info{background-color:var(--ep-success-50);border:1px solid var(--ep-success-200);border-radius:var(--ep-radius-md);padding:var(--ep-space-3);margin-top:var(--ep-space-4)}:host([data-theme=\\\"dark\\\"]) .ep-trial-info{background-color:rgba(16,185,129,0.1);border-color:rgba(16,185,129,0.3)}.ep-trial-info .ep-text-sm{color:var(--ep-success-700);margin:0;font-weight:var(--ep-font-weight-medium)}:host([data-theme=\\\"dark\\\"]) .ep-trial-info .ep-text-sm{color:var(--ep-success-400)}.ep-modal-actions{display:flex;flex-direction:column;gap:var(--ep-space-3);margin-bottom:var(--ep-space-6)}.ep-modal-footer{text-align:center;padding-top:var(--ep-space-6);border-top:1px solid var(--ep-border-primary)}.ep-modal-footer .ep-text-sm{margin:0}.ep-theme-toggle{position:fixed;top:var(--ep-space-4);left:var(--ep-space-4);z-index:var(--ep-z-tooltip)}@keyframes ep-modal-backdrop-in{from{opacity:0}to{opacity:1}}@keyframes ep-modal-backdrop-out{from{opacity:1}to{opacity:0}}@keyframes ep-modal-container-in{from{opacity:0;transform:scale(0.95) translateY(-10px)}to{opacity:1;transform:scale(1) translateY(0)}}@keyframes ep-modal-container-out{from{opacity:1;transform:scale(1) translateY(0)}to{opacity:0;transform:scale(0.95) translateY(-10px)}}@media (max-width:640px){.ep-modal-backdrop{padding:var(--ep-space-2)}.ep-modal-container{max-width:100%;border-radius:var(--ep-radius-lg)}.ep-modal-content{padding:var(--ep-space-6);padding-top:var(--ep-space-10)}.ep-modal-icon{width:60px;height:60px}.ep-modal-header .ep-heading-2{font-size:var(--ep-font-size-xl)}.ep-pricing-amount{font-size:var(--ep-font-size-3xl)}}@media (max-width:480px){.ep-modal-content{padding:var(--ep-space-4);padding-top:var(--ep-space-8)}.ep-modal-close{top:var(--ep-space-3);right:var(--ep-space-3)}}@media (prefers-contrast:high){.ep-modal-backdrop{background-color:rgba(0,0,0,0.9);backdrop-filter:none}.ep-modal-container{border:2px solid var(--ep-border-secondary)}.ep-pricing-card{background:var(--ep-bg-secondary);border:2px solid var(--ep-primary-500)}}@media (prefers-reduced-motion:reduce){.ep-modal-backdrop{animation:none}.ep-modal-container{animation:none}.ep-modal-backdrop.ep-modal-closing{animation:none}.ep-modal-backdrop.ep-modal-closing .ep-modal-container{animation:none}}\";\nexport default { html, css };","export const html = \"<div class=\\\"ep-inline-paywall\\\" id=\\\"inlinePaywall\\\" role=\\\"region\\\" aria-labelledby=\\\"paywall-title\\\"><div class=\\\"ep-inline-header\\\"><div class=\\\"ep-inline-icon\\\"><svg width=\\\"32\\\" height=\\\"32\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><path d=\\\"M9 12l2 2 4-4\\\"></path><path d=\\\"M21 12c-1 0-3-1-3-3s2-3 3-3 3 1 3 3-2 3-3 3\\\"></path><path d=\\\"M3 12c1 0 3-1 3-3s-2-3-3-3-3 1-3 3 2 3 3 3\\\"></path></svg></div><div class=\\\"ep-inline-header-content\\\"><h3 class=\\\"ep-heading-3\\\" id=\\\"paywall-title\\\">{{title}}</h3><p class=\\\"ep-text-body\\\">{{description}}</p></div></div><div class=\\\"ep-inline-content\\\"><div class=\\\"ep-inline-features\\\"><div class=\\\"ep-feature-grid\\\"><div class=\\\"ep-feature-card\\\"><div class=\\\"ep-feature-card-icon\\\"><svg width=\\\"24\\\" height=\\\"24\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><path d=\\\"M22 12h-4l-3 9L9 3l-3 9H2\\\"></path></svg></div><h4 class=\\\"ep-feature-card-title\\\">{{feature1Title}}</h4><p class=\\\"ep-feature-card-description\\\">{{feature1Description}}</p></div><div class=\\\"ep-feature-card\\\"><div class=\\\"ep-feature-card-icon\\\"><svg width=\\\"24\\\" height=\\\"24\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><path d=\\\"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z\\\"></path></svg></div><h4 class=\\\"ep-feature-card-title\\\">{{feature2Title}}</h4><p class=\\\"ep-feature-card-description\\\">{{feature2Description}}</p></div><div class=\\\"ep-feature-card\\\"><div class=\\\"ep-feature-card-icon\\\"><svg width=\\\"24\\\" height=\\\"24\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><path d=\\\"M13 2L3 14h9l-1 8 10-12h-9l1-8z\\\"></path></svg></div><h4 class=\\\"ep-feature-card-title\\\">{{feature3Title}}</h4><p class=\\\"ep-feature-card-description\\\">{{feature3Description}}</p></div></div></div><div class=\\\"ep-inline-pricing\\\"><div class=\\\"ep-pricing-comparison\\\"><div class=\\\"ep-pricing-plan\\\"><div class=\\\"ep-pricing-plan-header\\\"><h4 class=\\\"ep-pricing-plan-title\\\">{{freePlanName}}</h4><div class=\\\"ep-pricing-plan-price\\\"><span class=\\\"ep-pricing-currency\\\">{{currency}}</span><span class=\\\"ep-pricing-amount\\\">0</span></div></div><ul class=\\\"ep-pricing-plan-features\\\"><li class=\\\"ep-pricing-feature\\\"><svg class=\\\"ep-pricing-feature-icon\\\" width=\\\"16\\\" height=\\\"16\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><polyline points=\\\"20,6 9,17 4,12\\\"></polyline></svg> {{freeFeature1}} </li><li class=\\\"ep-pricing-feature\\\"><svg class=\\\"ep-pricing-feature-icon\\\" width=\\\"16\\\" height=\\\"16\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><polyline points=\\\"20,6 9,17 4,12\\\"></polyline></svg> {{freeFeature2}} </li><li class=\\\"ep-pricing-feature ep-pricing-feature-disabled\\\"><svg class=\\\"ep-pricing-feature-icon\\\" width=\\\"16\\\" height=\\\"16\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><line x1=\\\"18\\\" y1=\\\"6\\\" x2=\\\"6\\\" y2=\\\"18\\\"></line><line x1=\\\"6\\\" y1=\\\"6\\\" x2=\\\"18\\\" y2=\\\"18\\\"></line></svg> {{freeFeature3}} </li></ul></div><div class=\\\"ep-pricing-plan ep-pricing-plan-premium\\\"><div class=\\\"ep-pricing-plan-badge\\\">{{popularBadge}}</div><div class=\\\"ep-pricing-plan-header\\\"><h4 class=\\\"ep-pricing-plan-title\\\">{{premiumPlanName}}</h4><div class=\\\"ep-pricing-plan-price\\\"><span class=\\\"ep-pricing-currency\\\">{{currency}}</span><span class=\\\"ep-pricing-amount\\\">{{price}}</span><span class=\\\"ep-pricing-period\\\">{{period}}</span></div></div><ul class=\\\"ep-pricing-plan-features\\\"><li class=\\\"ep-pricing-feature\\\"><svg class=\\\"ep-pricing-feature-icon\\\" width=\\\"16\\\" height=\\\"16\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><polyline points=\\\"20,6 9,17 4,12\\\"></polyline></svg> {{premiumFeature1}} </li><li class=\\\"ep-pricing-feature\\\"><svg class=\\\"ep-pricing-feature-icon\\\" width=\\\"16\\\" height=\\\"16\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><polyline points=\\\"20,6 9,17 4,12\\\"></polyline></svg> {{premiumFeature2}} </li><li class=\\\"ep-pricing-feature\\\"><svg class=\\\"ep-pricing-feature-icon\\\" width=\\\"16\\\" height=\\\"16\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><polyline points=\\\"20,6 9,17 4,12\\\"></polyline></svg> {{premiumFeature3}} </li></ul><button class=\\\"ep-btn ep-btn-primary ep-btn-full\\\" data-ep-action=\\\"upgradeNow\\\"> {{upgradeButtonText}} </button></div></div></div><div class=\\\"ep-inline-trial\\\"><div class=\\\"ep-trial-content\\\"><p class=\\\"ep-trial-text\\\">{{trialText}}</p><div class=\\\"ep-trial-actions\\\"><button class=\\\"ep-btn ep-btn-secondary\\\" data-ep-action=\\\"startTrial\\\"> {{trialButtonText}} </button><button class=\\\"ep-btn ep-btn-ghost ep-btn-sm\\\" data-ep-action=\\\"dismissPaywall\\\"> {{dismissButtonText}} </button></div></div></div></div></div>\";\nexport const css = \".ep-inline-paywall{max-width:800px;margin:0 auto;background-color:var(--ep-bg-secondary);border:1px solid var(--ep-border-primary);border-radius:var(--ep-radius-lg);box-shadow:var(--ep-shadow-md);overflow:hidden;opacity:0;transform:translateY(20px);transition:all var(--ep-transition-slow)}.ep-inline-paywall.ep-inline-visible{opacity:1;transform:translateY(0)}.ep-inline-paywall.ep-inline-dismissing{opacity:0;transform:translateY(-20px);transition:all var(--ep-transition-normal)}.ep-inline-header{display:flex;align-items:center;gap:var(--ep-space-4);padding:var(--ep-space-6);background:linear-gradient(135deg,var(--ep-primary-50),var(--ep-primary-100));border-bottom:1px solid var(--ep-border-primary)}:host([data-theme=\\\"dark\\\"]) .ep-inline-header{background:linear-gradient(135deg,var(--ep-primary-900),var(--ep-primary-800))}.ep-inline-icon{width:64px;height:64px;background:linear-gradient(135deg,var(--ep-primary-500),var(--ep-primary-600));border-radius:var(--ep-radius-xl);display:flex;align-items:center;justify-content:center;color:white;flex-shrink:0}.ep-inline-header-content{flex:1;min-width:0}.ep-inline-header-content .ep-heading-3{margin-bottom:var(--ep-space-2);color:var(--ep-text-primary)}.ep-inline-header-content .ep-text-body{margin-bottom:0;color:var(--ep-text-secondary)}.ep-inline-content{padding:var(--ep-space-8)}.ep-inline-features{margin-bottom:var(--ep-space-8)}.ep-feature-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(240px,1fr));gap:var(--ep-space-4)}.ep-feature-card{background-color:var(--ep-bg-tertiary);border:1px solid var(--ep-border-primary);border-radius:var(--ep-radius-md);padding:var(--ep-space-4);text-align:center;transition:all var(--ep-transition-normal);opacity:0;transform:translateY(10px);animation:ep-feature-card-in var(--ep-transition-slow) forwards}.ep-feature-card:hover{transform:translateY(-2px);box-shadow:var(--ep-shadow-md)}.ep-feature-card-icon{width:48px;height:48px;margin:0 auto var(--ep-space-3);background:linear-gradient(135deg,var(--ep-primary-500),var(--ep-primary-600));border-radius:var(--ep-radius-lg);display:flex;align-items:center;justify-content:center;color:white}.ep-feature-card-title{font-size:var(--ep-font-size-lg);font-weight:var(--ep-font-weight-semibold);color:var(--ep-text-primary);margin-bottom:var(--ep-space-2)}.ep-feature-card-description{color:var(--ep-text-secondary);font-size:var(--ep-font-size-sm);line-height:var(--ep-line-height-relaxed);margin:0}.ep-inline-pricing{margin-bottom:var(--ep-space-8)}.ep-pricing-comparison{display:grid;grid-template-columns:repeat(auto-fit,minmax(280px,1fr));gap:var(--ep-space-4);max-width:600px;margin:0 auto}.ep-pricing-plan{position:relative;background-color:var(--ep-bg-secondary);border:1px solid var(--ep-border-primary);border-radius:var(--ep-radius-lg);padding:var(--ep-space-6);transition:all var(--ep-transition-normal)}.ep-pricing-plan:hover{transform:translateY(-2px);box-shadow:var(--ep-shadow-md)}.ep-pricing-plan-premium{border-color:var(--ep-primary-300);box-shadow:var(--ep-shadow-lg)}.ep-pricing-plan-badge{position:absolute;top:-12px;left:50%;transform:translateX(-50%);background:linear-gradient(135deg,var(--ep-primary-500),var(--ep-primary-600));color:white;padding:var(--ep-space-1) var(--ep-space-4);border-radius:var(--ep-radius-full);font-size:var(--ep-font-size-sm);font-weight:var(--ep-font-weight-medium);white-space:nowrap}.ep-pricing-plan-header{text-align:center;margin-bottom:var(--ep-space-6)}.ep-pricing-plan-title{font-size:var(--ep-font-size-xl);font-weight:var(--ep-font-weight-semibold);color:var(--ep-text-primary);margin-bottom:var(--ep-space-3)}.ep-pricing-plan-price{display:flex;align-items:baseline;justify-content:center;gap:var(--ep-space-1)}.ep-pricing-currency{font-size:var(--ep-font-size-lg);font-weight:var(--ep-font-weight-medium);color:var(--ep-text-secondary)}.ep-pricing-amount{font-size:var(--ep-font-size-3xl);font-weight:var(--ep-font-weight-bold);color:var(--ep-text-primary)}.ep-pricing-period{font-size:var(--ep-font-size-lg);color:var(--ep-text-secondary)}.ep-pricing-plan-features{list-style:none;padding:0;margin:0 0 var(--ep-space-6) 0}.ep-pricing-feature{display:flex;align-items:center;gap:var(--ep-space-3);padding:var(--ep-space-2) 0;color:var(--ep-text-primary);font-size:var(--ep-font-size-sm)}.ep-pricing-feature-disabled{color:var(--ep-text-tertiary)}.ep-pricing-feature-icon{color:var(--ep-success-500);flex-shrink:0}.ep-pricing-feature-disabled .ep-pricing-feature-icon{color:var(--ep-text-tertiary)}.ep-inline-trial{background:linear-gradient(135deg,var(--ep-gray-50),var(--ep-gray-100));border:1px solid var(--ep-border-primary);border-radius:var(--ep-radius-md);padding:var(--ep-space-6);text-align:center}:host([data-theme=\\\"dark\\\"]) .ep-inline-trial{background:linear-gradient(135deg,var(--ep-gray-800),var(--ep-gray-700))}.ep-trial-content{max-width:400px;margin:0 auto}.ep-trial-text{color:var(--ep-text-primary);font-size:var(--ep-font-size-lg);font-weight:var(--ep-font-weight-medium);margin-bottom:var(--ep-space-6)}.ep-trial-actions{display:flex;flex-direction:column;gap:var(--ep-space-3);align-items:center}.ep-theme-toggle{position:fixed;top:var(--ep-space-4);right:var(--ep-space-4);z-index:var(--ep-z-tooltip)}@keyframes ep-feature-card-in{from{opacity:0;transform:translateY(10px)}to{opacity:1;transform:translateY(0)}}@media (max-width:768px){.ep-inline-paywall{margin:var(--ep-space-4)}.ep-inline-header{flex-direction:column;text-align:center;gap:var(--ep-space-3)}.ep-inline-content{padding:var(--ep-space-6)}.ep-feature-grid{grid-template-columns:1fr}.ep-pricing-comparison{grid-template-columns:1fr}.ep-pricing-plan{padding:var(--ep-space-4)}.ep-trial-actions{flex-direction:column;width:100%}.ep-trial-actions .ep-btn{width:100%}}@media (max-width:640px){.ep-inline-paywall{margin:var(--ep-space-2);border-radius:var(--ep-radius-md)}.ep-inline-header{padding:var(--ep-space-4)}.ep-inline-content{padding:var(--ep-space-4)}.ep-inline-icon{width:48px;height:48px}.ep-feature-card-icon{width:40px;height:40px}.ep-pricing-plan{padding:var(--ep-space-3)}.ep-pricing-amount{font-size:var(--ep-font-size-2xl)}}@media (prefers-contrast:high){.ep-inline-paywall{border:2px solid var(--ep-border-secondary)}.ep-feature-card{border:2px solid var(--ep-border-secondary)}.ep-pricing-plan{border:2px solid var(--ep-border-secondary)}.ep-pricing-plan-premium{border:2px solid var(--ep-primary-500)}}@media (prefers-reduced-motion:reduce){.ep-inline-paywall{transition:none;opacity:1;transform:none}.ep-feature-card{transition:none;animation:none;opacity:1;transform:none}.ep-feature-card:hover{transform:none}.ep-pricing-plan:hover{transform:none}}\";\nexport default { html, css };","export const html = \"<div class=\\\"ep-sidebar-backdrop\\\" id=\\\"sidebarBackdrop\\\"></div><div class=\\\"ep-sidebar-paywall\\\" id=\\\"sidebarPaywall\\\" role=\\\"dialog\\\" aria-labelledby=\\\"sidebar-title\\\" aria-describedby=\\\"sidebar-description\\\"><div class=\\\"ep-sidebar-header\\\"><button class=\\\"ep-sidebar-close\\\" aria-label=\\\"Close paywall\\\" data-ep-action=\\\"closeSidebar\\\"><svg width=\\\"24\\\" height=\\\"24\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><line x1=\\\"18\\\" y1=\\\"6\\\" x2=\\\"6\\\" y2=\\\"18\\\"></line><line x1=\\\"6\\\" y1=\\\"6\\\" x2=\\\"18\\\" y2=\\\"18\\\"></line></svg></button><div class=\\\"ep-sidebar-logo\\\"><svg width=\\\"32\\\" height=\\\"32\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><path d=\\\"M12 2L2 7l10 5 10-5-10-5z\\\"></path><path d=\\\"M2 17l10 5 10-5\\\"></path><path d=\\\"M2 12l10 5 10-5\\\"></path></svg><span class=\\\"ep-sidebar-logo-text\\\">{{brandName}}</span></div></div><div class=\\\"ep-sidebar-content\\\"><div class=\\\"ep-sidebar-title-section\\\"><h2 class=\\\"ep-heading-2\\\" id=\\\"sidebar-title\\\">{{title}}</h2><p class=\\\"ep-text-body\\\" id=\\\"sidebar-description\\\">{{description}}</p></div><div class=\\\"ep-sidebar-progress\\\"><div class=\\\"ep-progress-header\\\"><span class=\\\"ep-progress-label\\\">{{progressLabel}}</span><span class=\\\"ep-progress-value\\\">{{usageCount}}/{{usageLimit}}</span></div><div class=\\\"ep-progress-bar\\\"><div class=\\\"ep-progress-fill\\\" style=\\\"width: {{progressPercentage}}%\\\"></div></div><p class=\\\"ep-progress-text\\\">{{progressText}}</p></div><div class=\\\"ep-sidebar-features\\\"><h3 class=\\\"ep-heading-3\\\">{{unlockHeading}}</h3><div class=\\\"ep-feature-list\\\"><div class=\\\"ep-feature-item\\\"><div class=\\\"ep-feature-icon\\\"><svg width=\\\"20\\\" height=\\\"20\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><path d=\\\"M12 2L2 7l10 5 10-5-10-5z\\\"></path><path d=\\\"M2 17l10 5 10-5\\\"></path><path d=\\\"M2 12l10 5 10-5\\\"></path></svg></div><div class=\\\"ep-feature-content\\\"><h4 class=\\\"ep-feature-title\\\">{{feature1Title}}</h4><p class=\\\"ep-feature-description\\\">{{feature1Description}}</p></div></div><div class=\\\"ep-feature-item\\\"><div class=\\\"ep-feature-icon\\\"><svg width=\\\"20\\\" height=\\\"20\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><path d=\\\"M22 12h-4l-3 9L9 3l-3 9H2\\\"></path></svg></div><div class=\\\"ep-feature-content\\\"><h4 class=\\\"ep-feature-title\\\">{{feature2Title}}</h4><p class=\\\"ep-feature-description\\\">{{feature2Description}}</p></div></div><div class=\\\"ep-feature-item\\\"><div class=\\\"ep-feature-icon\\\"><svg width=\\\"20\\\" height=\\\"20\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><path d=\\\"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z\\\"></path></svg></div><div class=\\\"ep-feature-content\\\"><h4 class=\\\"ep-feature-title\\\">{{feature3Title}}</h4><p class=\\\"ep-feature-description\\\">{{feature3Description}}</p></div></div></div></div><div class=\\\"ep-sidebar-pricing\\\"><div class=\\\"ep-pricing-card\\\"><div class=\\\"ep-pricing-header\\\"><div class=\\\"ep-pricing-badge\\\">{{pricingBadge}}</div><div class=\\\"ep-pricing-price\\\"><span class=\\\"ep-pricing-currency\\\">{{currency}}</span><span class=\\\"ep-pricing-amount\\\">{{price}}</span><span class=\\\"ep-pricing-period\\\">{{period}}</span></div><p class=\\\"ep-pricing-description\\\">{{pricingDescription}}</p></div></div></div><div class=\\\"ep-sidebar-trial\\\"><div class=\\\"ep-trial-info\\\"><div class=\\\"ep-trial-icon\\\"><svg width=\\\"20\\\" height=\\\"20\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><path d=\\\"M22 11.08V12a10 10 0 1 1-5.93-9.14\\\"></path><polyline points=\\\"22,4 12,14.01 9,11.01\\\"></polyline></svg></div><div class=\\\"ep-trial-content\\\"><h4 class=\\\"ep-trial-title\\\">{{trialTitle}}</h4><p class=\\\"ep-trial-description\\\">{{trialDescription}}</p></div></div></div></div><div class=\\\"ep-sidebar-footer\\\"><button class=\\\"ep-btn ep-btn-primary ep-btn-lg ep-btn-full\\\" data-ep-action=\\\"startUpgrade\\\"> {{upgradeButtonText}} </button><button class=\\\"ep-btn ep-btn-secondary ep-btn-full\\\" data-ep-action=\\\"startTrial\\\"> {{trialButtonText}} </button><button class=\\\"ep-btn ep-btn-ghost ep-btn-sm\\\" data-ep-action=\\\"remindLater\\\"> {{remindLaterText}} </button></div></div>\";\nexport const css = \".ep-sidebar-backdrop{position:fixed;top:0;left:0;right:0;bottom:0;background-color:rgba(0,0,0,0.5);backdrop-filter:blur(2px);z-index:var(--ep-z-backdrop);opacity:0;visibility:hidden;transition:all var(--ep-transition-normal)}.ep-sidebar-backdrop.ep-sidebar-backdrop-visible{opacity:1;visibility:visible}.ep-sidebar-paywall{position:fixed;top:0;right:0;bottom:0;width:400px;max-width:90vw;background-color:var(--ep-bg-secondary);border-left:1px solid var(--ep-border-primary);box-shadow:var(--ep-shadow-xl);z-index:var(--ep-z-modal);display:flex;flex-direction:column;transform:translateX(100%);transition:transform var(--ep-transition-normal)}.ep-sidebar-paywall.ep-sidebar-visible{transform:translateX(0)}.ep-sidebar-header{display:flex;align-items:center;justify-content:space-between;padding:var(--ep-space-4) var(--ep-space-6);border-bottom:1px solid var(--ep-border-primary);background:linear-gradient(135deg,var(--ep-primary-50),var(--ep-primary-100))}:host([data-theme=\\\"dark\\\"]) .ep-sidebar-header{background:linear-gradient(135deg,var(--ep-primary-900),var(--ep-primary-800))}.ep-sidebar-close{background:none;border:none;color:var(--ep-text-tertiary);cursor:pointer;padding:var(--ep-space-2);border-radius:var(--ep-radius-md);transition:all var(--ep-transition-fast)}.ep-sidebar-close:hover{color:var(--ep-text-primary);background-color:var(--ep-bg-tertiary)}.ep-sidebar-logo{display:flex;align-items:center;gap:var(--ep-space-2);color:var(--ep-primary-600)}.ep-sidebar-logo-text{font-size:var(--ep-font-size-lg);font-weight:var(--ep-font-weight-semibold);color:var(--ep-text-primary)}.ep-sidebar-content{flex:1;padding:var(--ep-space-6);overflow-y:auto;display:flex;flex-direction:column;gap:var(--ep-space-6)}.ep-sidebar-title-section{text-align:center}.ep-sidebar-title-section .ep-heading-2{margin-bottom:var(--ep-space-3);color:var(--ep-text-primary)}.ep-sidebar-title-section .ep-text-body{margin-bottom:0;color:var(--ep-text-secondary)}.ep-sidebar-progress{background-color:var(--ep-bg-tertiary);border:1px solid var(--ep-border-primary);border-radius:var(--ep-radius-md);padding:var(--ep-space-4)}.ep-progress-header{display:flex;justify-content:space-between;align-items:center;margin-bottom:var(--ep-space-3)}.ep-progress-label{font-size:var(--ep-font-size-sm);font-weight:var(--ep-font-weight-medium);color:var(--ep-text-primary)}.ep-progress-value{font-size:var(--ep-font-size-sm);font-weight:var(--ep-font-weight-semibold);color:var(--ep-primary-600)}.ep-progress-bar{height:8px;background-color:var(--ep-bg-primary);border-radius:var(--ep-radius-full);overflow:hidden;margin-bottom:var(--ep-space-2)}.ep-progress-fill{height:100%;background:linear-gradient(90deg,var(--ep-primary-500),var(--ep-primary-600));border-radius:var(--ep-radius-full);transition:width var(--ep-transition-normal)}.ep-progress-text{font-size:var(--ep-font-size-xs);color:var(--ep-text-tertiary);margin:0}.ep-sidebar-features .ep-heading-3{margin-bottom:var(--ep-space-4);text-align:center}.ep-feature-list{display:flex;flex-direction:column;gap:var(--ep-space-4)}.ep-feature-item{display:flex;align-items:flex-start;gap:var(--ep-space-3);padding:var(--ep-space-3);background-color:var(--ep-bg-tertiary);border:1px solid var(--ep-border-primary);border-radius:var(--ep-radius-md);opacity:0;transform:translateX(20px);transition:all var(--ep-transition-normal)}.ep-feature-item.ep-feature-item-visible{opacity:1;transform:translateX(0)}.ep-feature-icon{width:40px;height:40px;background:linear-gradient(135deg,var(--ep-primary-500),var(--ep-primary-600));border-radius:var(--ep-radius-lg);display:flex;align-items:center;justify-content:center;color:white;flex-shrink:0}.ep-feature-content{flex:1;min-width:0}.ep-feature-title{font-size:var(--ep-font-size-base);font-weight:var(--ep-font-weight-semibold);color:var(--ep-text-primary);margin-bottom:var(--ep-space-1)}.ep-feature-description{font-size:var(--ep-font-size-sm);color:var(--ep-text-secondary);line-height:var(--ep-line-height-relaxed);margin:0}.ep-sidebar-pricing{background:linear-gradient(135deg,var(--ep-primary-50),var(--ep-primary-100));border:1px solid var(--ep-primary-200);border-radius:var(--ep-radius-lg);padding:var(--ep-space-4)}:host([data-theme=\\\"dark\\\"]) .ep-sidebar-pricing{background:linear-gradient(135deg,var(--ep-primary-900),var(--ep-primary-800));border-color:var(--ep-primary-700)}.ep-pricing-card{text-align:center}.ep-pricing-header{margin-bottom:var(--ep-space-4)}.ep-pricing-badge{background:linear-gradient(135deg,var(--ep-primary-500),var(--ep-primary-600));color:white;padding:var(--ep-space-1) var(--ep-space-3);border-radius:var(--ep-radius-full);font-size:var(--ep-font-size-xs);font-weight:var(--ep-font-weight-medium);display:inline-block;margin-bottom:var(--ep-space-3)}.ep-pricing-price{display:flex;align-items:baseline;justify-content:center;gap:var(--ep-space-1);margin-bottom:var(--ep-space-2)}.ep-pricing-currency{font-size:var(--ep-font-size-base);font-weight:var(--ep-font-weight-medium);color:var(--ep-text-secondary)}.ep-pricing-amount{font-size:var(--ep-font-size-2xl);font-weight:var(--ep-font-weight-bold);color:var(--ep-text-primary)}.ep-pricing-period{font-size:var(--ep-font-size-base);color:var(--ep-text-secondary)}.ep-pricing-description{font-size:var(--ep-font-size-sm);color:var(--ep-text-secondary);margin:0}.ep-pricing-header:last-child,.ep-pricing-price:last-child{margin-bottom:0}.ep-sidebar-trial{background-color:var(--ep-success-50);border:1px solid var(--ep-success-200);border-radius:var(--ep-radius-md);padding:var(--ep-space-4)}:host([data-theme=\\\"dark\\\"]) .ep-sidebar-trial{background-color:rgba(16,185,129,0.1);border-color:rgba(16,185,129,0.3)}.ep-trial-info{display:flex;align-items:flex-start;gap:var(--ep-space-3)}.ep-trial-icon{width:32px;height:32px;background:linear-gradient(135deg,var(--ep-success-500),var(--ep-success-600));border-radius:var(--ep-radius-lg);display:flex;align-items:center;justify-content:center;color:white;flex-shrink:0}.ep-trial-content{flex:1;min-width:0}.ep-trial-title{font-size:var(--ep-font-size-base);font-weight:var(--ep-font-weight-semibold);color:var(--ep-success-700);margin-bottom:var(--ep-space-1)}:host([data-theme=\\\"dark\\\"]) .ep-trial-title{color:var(--ep-success-400)}.ep-trial-description{font-size:var(--ep-font-size-sm);color:var(--ep-success-600);line-height:var(--ep-line-height-relaxed);margin:0}:host([data-theme=\\\"dark\\\"]) .ep-trial-description{color:var(--ep-success-300)}.ep-sidebar-footer{padding:var(--ep-space-6);border-top:1px solid var(--ep-border-primary);background-color:var(--ep-bg-tertiary);display:flex;flex-direction:column;gap:var(--ep-space-3)}.ep-theme-toggle{position:fixed;top:var(--ep-space-4);left:var(--ep-space-4);z-index:var(--ep-z-tooltip);display:flex;flex-direction:column;gap:var(--ep-space-2)}@media (max-width:768px){.ep-sidebar-paywall{width:100%;max-width:100%;border-left:none}.ep-sidebar-content{padding:var(--ep-space-4)}.ep-sidebar-footer{padding:var(--ep-space-4)}}@media (max-width:480px){.ep-sidebar-header{padding:var(--ep-space-3) var(--ep-space-4)}.ep-sidebar-content{padding:var(--ep-space-3);gap:var(--ep-space-4)}.ep-sidebar-footer{padding:var(--ep-space-3)}.ep-feature-item{padding:var(--ep-space-2)}.ep-feature-icon{width:32px;height:32px}.ep-pricing-amount{font-size:var(--ep-font-size-xl)}}@media (prefers-contrast:high){.ep-sidebar-paywall{border-left:2px solid var(--ep-border-secondary)}.ep-feature-item{border:2px solid var(--ep-border-secondary)}.ep-sidebar-pricing{border:2px solid var(--ep-primary-500)}.ep-sidebar-trial{border:2px solid var(--ep-success-500)}}@media (prefers-reduced-motion:reduce){.ep-sidebar-backdrop{transition:none}.ep-sidebar-paywall{transition:none}.ep-feature-item{transition:none;opacity:1;transform:none}.ep-progress-fill{transition:none}}\";\nexport default { html, css };","export const html = \"<div class=\\\"ep-minimal-paywall\\\" id=\\\"minimalPaywall\\\" role=\\\"dialog\\\" aria-labelledby=\\\"minimal-title\\\"><button class=\\\"ep-minimal-close\\\" aria-label=\\\"Close paywall\\\" data-ep-action=\\\"closeMinimal\\\"><svg width=\\\"20\\\" height=\\\"20\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><line x1=\\\"18\\\" y1=\\\"6\\\" x2=\\\"6\\\" y2=\\\"18\\\"></line><line x1=\\\"6\\\" y1=\\\"6\\\" x2=\\\"18\\\" y2=\\\"18\\\"></line></svg></button><div class=\\\"ep-minimal-content\\\"><div class=\\\"ep-minimal-header\\\"><div class=\\\"ep-minimal-icon\\\"><svg width=\\\"24\\\" height=\\\"24\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><path d=\\\"M9 12l2 2 4-4\\\"></path><path d=\\\"M21 12c-1 0-3-1-3-3s2-3 3-3 3 1 3 3-2 3-3 3\\\"></path><path d=\\\"M3 12c1 0 3-1 3-3s-2-3-3-3-3 1-3 3 2 3 3 3\\\"></path></svg></div><h3 class=\\\"ep-minimal-title\\\" id=\\\"minimal-title\\\">{{title}}</h3><p class=\\\"ep-minimal-description\\\">{{description}}</p></div><div class=\\\"ep-minimal-pricing\\\"><div class=\\\"ep-minimal-price\\\"><span class=\\\"ep-minimal-currency\\\">{{currency}}</span><span class=\\\"ep-minimal-amount\\\">{{price}}</span><span class=\\\"ep-minimal-period\\\">{{period}}</span></div><p class=\\\"ep-minimal-price-description\\\">{{priceDescription}}</p></div><div class=\\\"ep-minimal-features\\\"><ul class=\\\"ep-minimal-feature-list\\\"><li class=\\\"ep-minimal-feature\\\"><svg class=\\\"ep-minimal-feature-icon\\\" width=\\\"16\\\" height=\\\"16\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><polyline points=\\\"20,6 9,17 4,12\\\"></polyline></svg><span>{{feature1}}</span></li><li class=\\\"ep-minimal-feature\\\"><svg class=\\\"ep-minimal-feature-icon\\\" width=\\\"16\\\" height=\\\"16\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><polyline points=\\\"20,6 9,17 4,12\\\"></polyline></svg><span>{{feature2}}</span></li><li class=\\\"ep-minimal-feature\\\"><svg class=\\\"ep-minimal-feature-icon\\\" width=\\\"16\\\" height=\\\"16\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><polyline points=\\\"20,6 9,17 4,12\\\"></polyline></svg><span>{{feature3}}</span></li></ul></div><div class=\\\"ep-minimal-actions\\\"><button class=\\\"ep-btn ep-btn-primary ep-btn-full\\\" data-ep-action=\\\"upgradeNow\\\"> {{upgradeButtonText}} </button><button class=\\\"ep-btn ep-btn-ghost ep-btn-sm\\\" data-ep-action=\\\"closeMinimal\\\"> {{dismissButtonText}} </button></div><div class=\\\"ep-minimal-trial\\\"><p class=\\\"ep-minimal-trial-text\\\">{{trialText}}</p></div></div></div><div class=\\\"ep-minimal-backdrop\\\" id=\\\"minimalBackdrop\\\"></div>\";\nexport const css = \".ep-minimal-backdrop{position:fixed;top:0;left:0;right:0;bottom:0;background-color:rgba(0,0,0,0.4);z-index:var(--ep-z-backdrop);opacity:0;visibility:hidden;transition:all var(--ep-transition-fast)}.ep-minimal-backdrop.ep-minimal-backdrop-visible{opacity:1;visibility:visible}.ep-minimal-paywall{position:fixed;top:50%;left:50%;transform:translate(-50%,-50%) scale(0.95);background-color:var(--ep-bg-secondary);border:1px solid var(--ep-border-primary);border-radius:var(--ep-radius-lg);box-shadow:var(--ep-shadow-xl);z-index:var(--ep-z-modal);max-width:400px;width:90vw;max-height:90vh;overflow-y:auto;opacity:0;visibility:hidden;transition:all var(--ep-transition-fast)}.ep-minimal-paywall.ep-minimal-visible{opacity:1;visibility:visible;transform:translate(-50%,-50%) scale(1)}.ep-minimal-close{position:absolute;top:var(--ep-space-3);right:var(--ep-space-3);background:none;border:none;color:var(--ep-text-tertiary);cursor:pointer;padding:var(--ep-space-2);border-radius:var(--ep-radius-sm);transition:all var(--ep-transition-fast);z-index:1}.ep-minimal-close:hover{color:var(--ep-text-primary);background-color:var(--ep-bg-tertiary)}.ep-minimal-content{padding:var(--ep-space-6);padding-top:var(--ep-space-8)}.ep-minimal-header{text-align:center;margin-bottom:var(--ep-space-6)}.ep-minimal-icon{width:48px;height:48px;margin:0 auto var(--ep-space-3);background:linear-gradient(135deg,var(--ep-primary-500),var(--ep-primary-600));border-radius:var(--ep-radius-lg);display:flex;align-items:center;justify-content:center;color:white}.ep-minimal-title{font-size:var(--ep-font-size-xl);font-weight:var(--ep-font-weight-semibold);color:var(--ep-text-primary);margin-bottom:var(--ep-space-2)}.ep-minimal-description{color:var(--ep-text-secondary);font-size:var(--ep-font-size-sm);line-height:var(--ep-line-height-relaxed);margin:0}.ep-minimal-pricing{text-align:center;margin-bottom:var(--ep-space-6);padding:var(--ep-space-4);background:linear-gradient(135deg,var(--ep-primary-50),var(--ep-primary-100));border:1px solid var(--ep-primary-200);border-radius:var(--ep-radius-md)}:host([data-theme=\\\"dark\\\"]) .ep-minimal-pricing{background:linear-gradient(135deg,var(--ep-primary-900),var(--ep-primary-800));border-color:var(--ep-primary-700)}.ep-minimal-price{display:flex;align-items:baseline;justify-content:center;gap:var(--ep-space-1);margin-bottom:var(--ep-space-2)}.ep-minimal-currency{font-size:var(--ep-font-size-base);font-weight:var(--ep-font-weight-medium);color:var(--ep-text-secondary)}.ep-minimal-amount{font-size:var(--ep-font-size-2xl);font-weight:var(--ep-font-weight-bold);color:var(--ep-text-primary)}.ep-minimal-period{font-size:var(--ep-font-size-base);color:var(--ep-text-secondary)}.ep-minimal-price-description{color:var(--ep-text-secondary);font-size:var(--ep-font-size-xs);margin:0}.ep-minimal-features{margin-bottom:var(--ep-space-6)}.ep-minimal-feature-list{list-style:none;padding:0;margin:0}.ep-minimal-feature{display:flex;align-items:center;gap:var(--ep-space-2);padding:var(--ep-space-2) 0;color:var(--ep-text-primary);font-size:var(--ep-font-size-sm);border-bottom:1px solid var(--ep-border-primary)}.ep-minimal-feature:last-child{border-bottom:none}.ep-minimal-feature-icon{color:var(--ep-success-500);flex-shrink:0}.ep-minimal-feature span{font-weight:var(--ep-font-weight-medium)}.ep-minimal-actions{display:flex;flex-direction:column;gap:var(--ep-space-2);margin-bottom:var(--ep-space-4)}.ep-minimal-trial{text-align:center;padding-top:var(--ep-space-4);border-top:1px solid var(--ep-border-primary)}.ep-minimal-trial-text{color:var(--ep-text-tertiary);font-size:var(--ep-font-size-xs);margin:0}.ep-theme-toggle{position:fixed;top:var(--ep-space-4);left:var(--ep-space-4);z-index:var(--ep-z-tooltip);display:flex;flex-direction:column;gap:var(--ep-space-2)}@media (max-width:480px){.ep-minimal-paywall{width:95vw;max-width:none}.ep-minimal-content{padding:var(--ep-space-4);padding-top:var(--ep-space-6)}.ep-minimal-close{top:var(--ep-space-2);right:var(--ep-space-2)}.ep-minimal-icon{width:40px;height:40px}.ep-minimal-title{font-size:var(--ep-font-size-lg)}.ep-minimal-amount{font-size:var(--ep-font-size-xl)}.ep-minimal-pricing{padding:var(--ep-space-3)}}@media (prefers-contrast:high){.ep-minimal-paywall{border:2px solid var(--ep-border-secondary)}.ep-minimal-pricing{border:2px solid var(--ep-primary-500)}.ep-minimal-backdrop{background-color:rgba(0,0,0,0.8)}}@media (prefers-reduced-motion:reduce){.ep-minimal-backdrop{transition:none}.ep-minimal-paywall{transition:none;transform:translate(-50%,-50%)}.ep-minimal-paywall.ep-minimal-visible{transform:translate(-50%,-50%)}}@media print{.ep-minimal-backdrop{display:none}.ep-minimal-paywall{position:static;transform:none;box-shadow:none;border:1px solid black;opacity:1;visibility:visible}.ep-minimal-close{display:none}}.ep-minimal-paywall *:focus{outline:2px solid var(--ep-primary-500);outline-offset:2px}.ep-minimal-paywall *:focus:not(:focus-visible){outline:none}.ep-minimal-paywall{animation:ep-minimal-entrance var(--ep-transition-normal) ease-out}@keyframes ep-minimal-entrance{from{opacity:0;transform:translate(-50%,-50%) scale(0.9)}to{opacity:1;transform:translate(-50%,-50%) scale(1)}}.ep-minimal-feature:hover{background-color:var(--ep-bg-tertiary);border-radius:var(--ep-radius-sm);margin:0 calc(-1 * var(--ep-space-2));padding:var(--ep-space-2)}.ep-minimal-pricing:hover{background:linear-gradient(135deg,var(--ep-primary-100),var(--ep-primary-200));border-color:var(--ep-primary-300)}:host([data-theme=\\\"dark\\\"]) .ep-minimal-pricing:hover{background:linear-gradient(135deg,var(--ep-primary-800),var(--ep-primary-700));border-color:var(--ep-primary-600)}\";\nexport default { html, css };","/**\n * The one paywall renderer.\n *\n * Renders a template from `@extenshi/paywall-templates` into a Shadow DOM\n * host so the templates' resets never leak into the extension page (and vice\n * versa). Placeholders (`{{title}}`, `{{price}}` …) are filled from the offer\n * and the strings dictionary, every value HTML-escaped; buttons are bound with\n * `addEventListener` on `data-ep-action` (no inline handlers, no scripts).\n */\n\nimport { withdrawalWaiverText } from '../payment/withdrawal-waiver.js'\nimport type { ThemeConfig } from '../types/config.js'\nimport type { PayOfferDto, PaySellerPublic, PayWithdrawalWaiver } from '../types/contract.js'\nimport type { UpgradeConsent } from '../types/entitlement.js'\nimport { ERROR_CODES, ExtenshiPayError } from '../types/errors.js'\nimport type { PaywallMode, PaywallStrings } from '../types/paywall.js'\nimport { formatPrice, periodLabel } from './format.js'\nimport { sdkDir, sdkLocale, sdkStrings } from './i18n.js'\nimport { sellerDetails } from './seller-details.js'\nimport { stringsFor } from './strings.js'\nimport { PAYWALL_SHARED_CSS, PAYWALL_TEMPLATES } from './templates.js'\n\nexport interface PaywallView {\n\tmode: PaywallMode\n\ttitle: string\n\tdescription: string\n\tfeatures: string[]\n\tfreeFeatures: string[]\n\t/** Header image URL (./icon.ts) in place of the template's glyph; absent or null keeps the glyph. */\n\ticon?: string | null\n\tbrandName: string\n\toffer: PayOfferDto | null\n\tcheckoutEnabled: boolean\n\tmock?: boolean\n\trecoveryEnabled?: boolean\n\tseller?: PaySellerPublic | null\n\t/**\n\t * From `PayOfferResponse.withdrawalWaiver`: when set (and the offer is\n\t * purchasable) an unticked waiver checkbox gates every upgrade button.\n\t * The waiver text is not overridable through `strings`: it is versioned.\n\t */\n\twithdrawalWaiver?: PayWithdrawalWaiver | null\n\t/** A link-styled button under the plans (trial-ended screen); clicking it calls `onFeedback`. */\n\tfeedback?: { label: string } | null\n\tlocale: string | null\n\ttheme: ThemeConfig\n\tstrings: Partial<PaywallStrings>\n\tcontainer?: HTMLElement\n}\n\nexport interface PaywallRendererCallbacks {\n\t/** `consent` is passed only when the paywall showed the withdrawal waiver (and it was ticked). */\n\tonUpgrade: (sku: string, consent?: UpgradeConsent) => void\n\tonClose: () => void\n\tonRestore?: () => void\n\tonFeedback?: () => void\n}\n\nexport const PAYWALL_HOST_CLASS = 'extenshi-paywall-host'\n\nconst UPGRADE_ACTIONS: ReadonlySet<string> = new Set(['upgradeNow', 'startUpgrade'])\nconst UPGRADE_SELECTOR = '[data-ep-action=\"upgradeNow\"], [data-ep-action=\"startUpgrade\"]'\nexport const WITHDRAWAL_WAIVER_CLASS = 'extenshi-withdrawal-waiver'\nconst CLOSE_ACTIONS: ReadonlySet<string> = new Set([\n\t'closePaywall',\n\t'closeSidebar',\n\t'closeFullscreen',\n\t'closeMinimal',\n\t'dismissPaywall',\n\t'remindLater',\n\t'continueFree',\n])\n\nconst ROOT_SELECTOR: Record<PaywallMode, string> = {\n\tmodal: '.ep-modal-backdrop',\n\tinline: '.ep-inline-paywall',\n\tsidebar: '.ep-sidebar-paywall',\n\tfullscreen: '.ep-fullscreen-paywall',\n\tminimal: '.ep-minimal-paywall',\n}\n\nconst BACKDROP_SELECTOR: Partial<Record<PaywallMode, string>> = {\n\tmodal: '.ep-modal-backdrop',\n\tsidebar: '.ep-sidebar-backdrop',\n\tminimal: '.ep-minimal-backdrop',\n}\n\nconst VISIBLE_CLASSES: Partial<Record<PaywallMode, Array<[selector: string, className: string]>>> = {\n\tinline: [['.ep-inline-paywall', 'ep-inline-visible']],\n\tsidebar: [\n\t\t['.ep-sidebar-paywall', 'ep-sidebar-visible'],\n\t\t['.ep-sidebar-backdrop', 'ep-sidebar-backdrop-visible'],\n\t],\n\tminimal: [\n\t\t['.ep-minimal-paywall', 'ep-minimal-visible'],\n\t\t['.ep-minimal-backdrop', 'ep-minimal-backdrop-visible'],\n\t],\n}\n\n/** Template blocks the contract has no data for (trials, usage meters). */\nconst PRUNE_SELECTOR = '[class*=\"-trial\"], .ep-sidebar-progress'\n/** Glyphs that stand for the product: on a gradient tile, or next to the brand name. */\nconst ICON_TILE_SELECTOR = '.ep-modal-icon, .ep-inline-icon, .ep-minimal-icon, .ep-hero-icon'\nconst ICON_LOGO_SELECTOR = '.ep-fullscreen-logo, .ep-sidebar-logo'\n/**\n * Templates stagger their feature rows in with this class from their demo\n * script (sidebar, fullscreen); without it the rows sit at opacity 0.\n */\nconst FEATURE_ITEM_VISIBLE = ['.ep-feature-item', 'ep-feature-item-visible'] as const\n/** Containers of a single feature slot; dropped when the slot's placeholder is empty. */\nconst FEATURE_SLOT_SELECTOR = 'li, .ep-feature-card, .ep-feature-item, .ep-pricing-feature, .ep-feature'\n/** Feature sections and lists (with their headings); dropped once no slot is left in them. */\nconst FEATURE_BLOCK_SELECTOR = '[class*=\"-features\"]'\nconst EMPTY_SLOT_MARK = 'data-ep-empty'\n/** Placeholders whose element is dropped when empty: feature slots and the price card's copy. */\nconst OPTIONAL_KEY_RE =\n\t/^(feature\\d+(Title)?|premiumFeature\\d+|freeFeature\\d+|pricingDescription|priceDescription|premiumDescription)$/\n\nexport function escapeHtml(value: string): string {\n\treturn value\n\t\t.replace(/&/g, '&')\n\t\t.replace(/</g, '<')\n\t\t.replace(/>/g, '>')\n\t\t.replace(/\"/g, '"')\n\t\t.replace(/'/g, ''')\n}\n\nexport function substitute(html: string, content: Record<string, string>): string {\n\treturn html.replace(/\\{\\{(\\w+)\\}\\}/g, (_match, key: string) => {\n\t\tconst value = content[key] ?? ''\n\t\tif (value === '' && OPTIONAL_KEY_RE.test(key)) return `<i ${EMPTY_SLOT_MARK}></i>`\n\t\treturn escapeHtml(value)\n\t})\n}\n\nexport function buildContent(view: PaywallView, strings: PaywallStrings): Record<string, string> {\n\tconst offer = view.offer\n\tconst price = offer ? formatPrice(offer.amountMinor, offer.currency, view.locale) : null\n\t// Without a `description` option the header already shows the offer's\n\t// description (ExtenshiPay.showPaywall); the price card must not repeat it.\n\tconst offerDescription = offer?.description?.trim() ?? ''\n\tconst priceCopy = offerDescription === view.description.trim() ? '' : offerDescription\n\tconst content: Record<string, string> = {\n\t\ttitle: view.title,\n\t\tdescription: view.description,\n\t\tbrandName: view.brandName,\n\t\tcurrency: price?.currency ?? '',\n\t\tprice: price?.amount ?? '',\n\t\tperiod: offer ? periodLabel(offer, strings) : '',\n\t\tpricingDescription: priceCopy,\n\t\tpriceDescription: priceCopy,\n\t\tpremiumDescription: priceCopy,\n\t\tupgradeButtonText: view.checkoutEnabled && offer ? strings.upgrade : strings.checkoutUnavailable,\n\t\tcancelButtonText: strings.cancel,\n\t\tdismissButtonText: strings.dismiss,\n\t\tremindLaterText: strings.remindLater,\n\t\tcontinueButtonText: strings.continueFree,\n\t\tfooterText: strings.footer,\n\t\tfeaturesHeading: strings.featuresHeading,\n\t\tplansHeading: strings.plansHeading,\n\t\tfreePlanName: strings.freePlanName,\n\t\tpremiumPlanName: strings.premiumPlanName,\n\t\tpopularBadge: strings.popularBadge,\n\t\tunlockHeading: strings.unlockHeading,\n\t}\n\tview.features.forEach((feature, index) => {\n\t\tconst n = index + 1\n\t\tcontent[`feature${n}`] = feature\n\t\tcontent[`feature${n}Title`] = feature\n\t\tcontent[`premiumFeature${n}`] = feature\n\t})\n\tview.freeFeatures.forEach((feature, index) => {\n\t\tcontent[`freeFeature${index + 1}`] = feature\n\t})\n\treturn content\n}\n\n/** Who supplies the content: the seller's public name, else the project/brand name. */\nfunction waiverSellerName(view: PaywallView): string {\n\treturn view.seller?.displayName?.trim() || view.brandName.trim() || view.title\n}\n\nconst CSS_VALUE_UNSAFE = /[;{}<>]/g\n/**\n * The rest of the primary scale, as the share of `primaryColor` mixed with\n * white (tints) or black (shades). Price cards and links use these steps; left\n * at the defaults they stay sky blue next to a button in the author's colour.\n */\nconst PRIMARY_TINTS: ReadonlyArray<[step: number, percent: number]> = [\n\t[50, 8],\n\t[100, 16],\n\t[200, 32],\n\t[300, 52],\n\t[400, 76],\n]\nconst PRIMARY_SHADES: ReadonlyArray<[step: number, percent: number]> = [\n\t[800, 72],\n\t[900, 52],\n]\n\nexport function themeCss(theme: ThemeConfig): string {\n\tconst declarations: string[] = []\n\tconst safe = (value: string) => value.replace(CSS_VALUE_UNSAFE, '')\n\tif (theme.primaryColor) {\n\t\tconst color = safe(theme.primaryColor)\n\t\tdeclarations.push(`--ep-primary-500:${color}`, `--ep-primary-600:${color}`, `--ep-primary-700:${color}`)\n\t\tfor (const [step, percent] of PRIMARY_TINTS)\n\t\t\tdeclarations.push(`--ep-primary-${step}:color-mix(in srgb,${color} ${percent}%,white)`)\n\t\tfor (const [step, percent] of PRIMARY_SHADES)\n\t\t\tdeclarations.push(`--ep-primary-${step}:color-mix(in srgb,${color} ${percent}%,black)`)\n\t}\n\tif (theme.fontFamily) declarations.push(`--ep-font-family-sans:${safe(theme.fontFamily)}`)\n\tif (theme.borderRadius) {\n\t\tconst radius = safe(theme.borderRadius)\n\t\tdeclarations.push(`--ep-radius-md:${radius}`, `--ep-radius-lg:${radius}`, `--ep-radius-xl:${radius}`)\n\t}\n\tconst host = declarations.length > 0 ? `:host{${declarations.join(';')}}` : ''\n\treturn host + (theme.customCss ?? '')\n}\n\nexport function resolveThemeMode(theme: ThemeConfig): 'light' | 'dark' {\n\tconst mode = theme.mode ?? 'auto'\n\tif (mode !== 'auto') return mode\n\tconst matchMedia = (globalThis as { matchMedia?: (query: string) => { matches: boolean } }).matchMedia\n\treturn typeof matchMedia === 'function' &&\n\t\tmatchMedia.call(globalThis, '(prefers-color-scheme: dark)').matches\n\t\t? 'dark'\n\t\t: 'light'\n}\n\nexport class PaywallRenderer {\n\tprivate host: HTMLElement | null = null\n\tprivate keyHandler: ((event: KeyboardEvent) => void) | null = null\n\n\tconstructor(private readonly callbacks: PaywallRendererCallbacks) {}\n\n\tisVisible(): boolean {\n\t\treturn this.host !== null\n\t}\n\n\t/** Returns the host element; its shadow root holds the rendered template. */\n\tshow(view: PaywallView): HTMLElement {\n\t\tthis.hide()\n\t\tconst doc = (globalThis as { document?: Document }).document\n\t\tif (!doc || typeof doc.createElement !== 'function' || !doc.body) {\n\t\t\tthrow new ExtenshiPayError(\n\t\t\t\tERROR_CODES.PAYWALL_UNAVAILABLE,\n\t\t\t\t'The paywall needs a DOM; call showPaywall() from a popup, options page or content script',\n\t\t\t)\n\t\t}\n\t\tconst template = PAYWALL_TEMPLATES[view.mode]\n\t\tif (!template)\n\t\t\tthrow new ExtenshiPayError(ERROR_CODES.INVALID_REQUEST, `Unknown paywall mode \"${view.mode}\"`)\n\n\t\tconst t = sdkStrings(view.locale)\n\t\tconst strings: PaywallStrings = { ...stringsFor(view.locale), ...view.strings }\n\t\tif (view.mock) {\n\t\t\tstrings.upgrade = t.simulatePurchase\n\t\t\tstrings.footer = t.mockNotice\n\t\t}\n\t\tconst host = doc.createElement('div')\n\t\thost.className = PAYWALL_HOST_CLASS\n\t\thost.setAttribute('data-theme', resolveThemeMode(view.theme))\n\t\t// The shadow tree inherits the host's language: screen readers and\n\t\t// hyphenation read the strings in the language they are written in.\n\t\thost.setAttribute('lang', sdkLocale(view.locale))\n\t\thost.setAttribute('dir', sdkDir(sdkLocale(view.locale)))\n\t\tconst root: ShadowRoot | HTMLElement =\n\t\t\ttypeof host.attachShadow === 'function' ? host.attachShadow({ mode: 'open' }) : host\n\t\troot.innerHTML =\n\t\t\t`<style>${PAYWALL_SHARED_CSS}${template.css}${themeCss(view.theme)}</style>` +\n\t\t\tsubstitute(template.html, buildContent(view, strings))\n\n\t\tthis.prune(root)\n\t\tif (view.icon) this.placeIcon(root, doc, view.icon)\n\t\tconst waiver =\n\t\t\tview.offer && view.checkoutEnabled && view.withdrawalWaiver\n\t\t\t\t? withdrawalWaiverText(view.withdrawalWaiver.version, view.locale, waiverSellerName(view))\n\t\t\t\t: null\n\t\tconst waiverBox = waiver ? doc.createElement('input') : null\n\t\t// undefined: no waiver asked → onUpgrade(sku) exactly as before; null: not ticked yet.\n\t\tconst consent = (): UpgradeConsent | null | undefined => {\n\t\t\tif (!waiver) return undefined\n\t\t\treturn waiverBox?.checked ? { withdrawalWaiver: { version: waiver.version, accepted: true } } : null\n\t\t}\n\t\tthis.bind(root, view, doc, consent)\n\t\tconst sellerMount = root.querySelector(\n\t\t\t'[class*=\"-footer\"], .ep-minimal-actions, .ep-inline-content, .ep-fullscreen-content',\n\t\t)\n\t\tif (sellerMount) {\n\t\t\tconst details = sellerDetails(view.seller ?? null, t)\n\t\t\tdetails.style.cssText =\n\t\t\t\t'font-size:12px;line-height:1.5;margin-top:12px;text-align:start;white-space:normal;color:var(--ep-text-secondary)'\n\t\t\t// In the modal, disclose the provider before the purchase action,\n\t\t\t// instead of below it in the scrollable footer.\n\t\t\tconst modalActions = root.querySelector('.ep-modal-actions')\n\t\t\tif (modalActions) modalActions.before(details)\n\t\t\telse sellerMount.append(details)\n\t\t}\n\t\tif (view.mock) {\n\t\t\tconst upgrade = root.querySelector(UPGRADE_SELECTOR)\n\t\t\tif (upgrade) {\n\t\t\t\tconst notice = doc.createElement('p')\n\t\t\t\tnotice.className = 'extenshi-payment-preview'\n\t\t\t\tnotice.textContent = t.mockNotice\n\t\t\t\tnotice.style.cssText = 'font-size:13px;line-height:1.5;margin:12px 0;white-space:normal'\n\t\t\t\tupgrade.before(notice)\n\t\t\t}\n\t\t}\n\t\tif (waiver && waiverBox) this.mountWaiver(root, doc, waiver.text, waiverBox)\n\t\tconst onRestore = this.callbacks.onRestore\n\t\tif (view.recoveryEnabled && onRestore) this.footerLink(root, doc, strings.restorePurchase, onRestore)\n\t\tconst onFeedback = this.callbacks.onFeedback\n\t\tif (view.feedback && onFeedback) this.footerLink(root, doc, view.feedback.label, onFeedback)\n\t\tconst mount = view.mode === 'inline' ? (view.container ?? doc.body) : doc.body\n\t\tmount.appendChild(host)\n\t\tthis.host = host\n\t\tthis.reveal(root, view.mode)\n\t\treturn host\n\t}\n\n\thide(): void {\n\t\tif (!this.host) return\n\t\tif (this.keyHandler) {\n\t\t\tthis.host.ownerDocument.removeEventListener('keydown', this.keyHandler)\n\t\t\tthis.keyHandler = null\n\t\t}\n\t\tthis.host.remove()\n\t\tthis.host = null\n\t}\n\n\t/** A text button at the end of the footer (no `href`: the SDK opens URLs itself). */\n\tprivate footerLink(root: ParentNode, doc: Document, label: string, onClick: () => void): void {\n\t\tconst footer = root.querySelector(\n\t\t\t'[class*=\"-footer\"], .ep-minimal-actions, .ep-inline-content, .ep-fullscreen-content',\n\t\t)\n\t\tif (!footer) return\n\t\tconst button = doc.createElement('button')\n\t\tbutton.type = 'button'\n\t\tbutton.textContent = label\n\t\tbutton.style.cssText =\n\t\t\t'display:block;margin:12px auto 0;background:none;border:0;color:inherit;font:inherit;text-decoration:underline;cursor:pointer'\n\t\tbutton.addEventListener('click', () => onClick())\n\t\tfooter.appendChild(button)\n\t}\n\n\tprivate prune(root: ParentNode): void {\n\t\tfor (const element of root.querySelectorAll(PRUNE_SELECTOR)) element.remove()\n\t\tfor (const mark of root.querySelectorAll(`[${EMPTY_SLOT_MARK}]`)) {\n\t\t\tconst slot = mark.parentElement?.closest(FEATURE_SLOT_SELECTOR) ?? mark.parentElement\n\t\t\t;(slot ?? mark).remove()\n\t\t}\n\t\t// Every slot empty (no `features` passed): drop the section with its\n\t\t// heading, so no \"Premium Features\" title sits over nothing.\n\t\tfor (const block of root.querySelectorAll(FEATURE_BLOCK_SELECTOR)) {\n\t\t\tif (!block.querySelector(FEATURE_SLOT_SELECTOR)) block.remove()\n\t\t}\n\t\t// A button whose label placeholder the contract does not fill (trial\n\t\t// CTAs on sidebar/fullscreen) would render as an empty pill; icon-only\n\t\t// buttons (close) keep their SVG and stay.\n\t\tfor (const button of root.querySelectorAll('button')) {\n\t\t\tif (!button.textContent?.trim() && !button.querySelector('svg')) button.remove()\n\t\t}\n\t}\n\n\t/**\n\t * Swaps the templates' product glyphs for the extension's icon. A tile's\n\t * gradient only backs the white glyph, so it goes too; an image that fails\n\t * to load puts the glyph (and the gradient) back.\n\t */\n\tprivate placeIcon(root: ParentNode, doc: Document, url: string): void {\n\t\tfor (const slot of root.querySelectorAll<HTMLElement>(`${ICON_TILE_SELECTOR}, ${ICON_LOGO_SELECTOR}`)) {\n\t\t\tconst glyph = Array.from(slot.children).find((child) => child.localName === 'svg')\n\t\t\tif (!glyph) continue\n\t\t\tconst tile = slot.matches(ICON_TILE_SELECTOR)\n\t\t\tconst size = Number(glyph.getAttribute('width')) || 32\n\t\t\tconst img = doc.createElement('img')\n\t\t\timg.alt = ''\n\t\t\timg.style.cssText = tile\n\t\t\t\t? 'width:100%;height:100%;object-fit:contain'\n\t\t\t\t: `width:${size}px;height:${size}px;object-fit:contain`\n\t\t\timg.addEventListener('error', () => {\n\t\t\t\timg.replaceWith(glyph)\n\t\t\t\tif (tile) slot.style.removeProperty('background')\n\t\t\t})\n\t\t\timg.src = url\n\t\t\tif (tile) slot.style.background = 'none'\n\t\t\tglyph.replaceWith(img)\n\t\t}\n\t}\n\n\t/**\n\t * Inserts the unticked waiver checkbox right before the first upgrade\n\t * button and keeps every upgrade button disabled until it is ticked.\n\t */\n\tprivate mountWaiver(root: ParentNode, doc: Document, text: string, input: HTMLInputElement): void {\n\t\tconst buttons = Array.from(root.querySelectorAll<HTMLElement>(UPGRADE_SELECTOR))\n\t\tconst first = buttons[0]\n\t\tif (!first) return\n\t\tconst label = doc.createElement('label')\n\t\tlabel.className = WITHDRAWAL_WAIVER_CLASS\n\t\tlabel.style.cssText =\n\t\t\t'display:flex;align-items:flex-start;gap:8px;margin:12px 0;font-size:13px;line-height:1.5;text-align:start;white-space:normal;color:inherit;cursor:pointer'\n\t\tinput.type = 'checkbox'\n\t\tinput.checked = false\n\t\tinput.style.cssText = 'flex:none;width:16px;height:16px;margin:2px 0 0;cursor:pointer'\n\t\tconst span = doc.createElement('span')\n\t\tspan.textContent = text\n\t\tlabel.append(input, span)\n\t\tfirst.before(label)\n\t\tconst sync = () => {\n\t\t\tfor (const button of buttons) {\n\t\t\t\tif (input.checked) {\n\t\t\t\t\tbutton.removeAttribute('disabled')\n\t\t\t\t\tbutton.removeAttribute('aria-disabled')\n\t\t\t\t} else {\n\t\t\t\t\tbutton.setAttribute('disabled', '')\n\t\t\t\t\tbutton.setAttribute('aria-disabled', 'true')\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tinput.addEventListener('change', sync)\n\t\tsync()\n\t}\n\n\tprivate bind(\n\t\troot: ParentNode,\n\t\tview: PaywallView,\n\t\tdoc: Document,\n\t\tconsent: () => UpgradeConsent | null | undefined,\n\t): void {\n\t\tfor (const element of root.querySelectorAll<HTMLElement>('[data-ep-action]')) {\n\t\t\tconst action = element.getAttribute('data-ep-action') ?? ''\n\t\t\tif (UPGRADE_ACTIONS.has(action)) {\n\t\t\t\tif (view.offer && view.checkoutEnabled) {\n\t\t\t\t\tconst sku = view.offer.sku\n\t\t\t\t\telement.addEventListener('click', (event) => {\n\t\t\t\t\t\tevent.preventDefault()\n\t\t\t\t\t\tconst given = consent()\n\t\t\t\t\t\t// Waiver shown but not ticked: a disabled button cannot be\n\t\t\t\t\t\t// clicked, but never start checkout without consent anyway.\n\t\t\t\t\t\tif (given === null) return\n\t\t\t\t\t\tif (given) this.callbacks.onUpgrade(sku, given)\n\t\t\t\t\t\telse this.callbacks.onUpgrade(sku)\n\t\t\t\t\t})\n\t\t\t\t} else {\n\t\t\t\t\telement.setAttribute('disabled', '')\n\t\t\t\t\telement.setAttribute('aria-disabled', 'true')\n\t\t\t\t}\n\t\t\t} else if (CLOSE_ACTIONS.has(action)) {\n\t\t\t\telement.addEventListener('click', (event) => {\n\t\t\t\t\tevent.preventDefault()\n\t\t\t\t\tthis.close()\n\t\t\t\t})\n\t\t\t} else {\n\t\t\t\telement.remove()\n\t\t\t}\n\t\t}\n\t\tconst backdropSelector = BACKDROP_SELECTOR[view.mode]\n\t\tif (backdropSelector) {\n\t\t\troot.querySelector(backdropSelector)?.addEventListener('click', (event) => {\n\t\t\t\tif (event.target === event.currentTarget) this.close()\n\t\t\t})\n\t\t}\n\t\tif (view.mode !== 'inline') {\n\t\t\tthis.keyHandler = (event) => {\n\t\t\t\tif (event.key === 'Escape') this.close()\n\t\t\t}\n\t\t\tdoc.addEventListener('keydown', this.keyHandler)\n\t\t}\n\t}\n\n\tprivate reveal(root: ParentNode, mode: PaywallMode): void {\n\t\tconst rootElement = root.querySelector<HTMLElement>(ROOT_SELECTOR[mode])\n\t\tif (rootElement && (mode === 'modal' || mode === 'fullscreen')) rootElement.style.display = 'flex'\n\t\tfor (const [selector, className] of VISIBLE_CLASSES[mode] ?? []) {\n\t\t\troot.querySelector(selector)?.classList.add(className)\n\t\t}\n\t\tfor (const item of root.querySelectorAll(FEATURE_ITEM_VISIBLE[0]))\n\t\t\titem.classList.add(FEATURE_ITEM_VISIBLE[1])\n\t}\n\n\tprivate close(): void {\n\t\tthis.hide()\n\t\tthis.callbacks.onClose()\n\t}\n}\n","/** Full SDK: everything in `ExtenshiPayLite` plus the offer and the paywall UI. */\n\nimport { ExtenshiPayLite } from './core/extenshi-pay.js'\nimport { openInNewTab } from './payment/checkout.js'\nimport { isEntitled } from './payment/features.js'\nimport { trialFeedbackUrl } from './payment/trial.js'\nimport { BillingProfilePicker } from './paywall/billing-profile-picker.js'\nimport { sdkStrings } from './paywall/i18n.js'\nimport { paywallIconUrl } from './paywall/icon.js'\nimport { LicensePanel } from './paywall/license-panel.js'\nimport { PaywallRenderer, type PaywallView } from './paywall/renderer.js'\nimport { stringsFor } from './paywall/strings.js'\nimport type { PayOfferDto, PayOfferResponse } from './types/contract.js'\nimport type { CustomerPortalOptions, RequireFeatureOptions, UpgradeConsent } from './types/entitlement.js'\nimport { ERROR_CODES, ExtenshiPayError } from './types/errors.js'\nimport type { PaywallOptions, TrialEndedOptions } from './types/paywall.js'\n\ninterface PaywallSession {\n\toptions: PaywallOptions\n\tresolve: (unlocked: boolean) => void\n\t/** The trial-ended screen's feedback form, with `src=trial_end`. */\n\tfeedbackUrl: string | null\n}\n\nfunction pickOffer(offer: PayOfferResponse | null, sku: string | undefined): PayOfferDto | null {\n\tif (!offer) return null\n\treturn offer.offers.find((candidate) => candidate.sku === sku) ?? offer.offers[0] ?? null\n}\n\nexport class ExtenshiPay extends ExtenshiPayLite {\n\tprivate disposed = false\n\tprivate licensePanel = new LicensePanel()\n\tprivate billingProfiles = new BillingProfilePicker()\n\tprivate paywall: PaywallRenderer | null = null\n\tprivate paywallSession: PaywallSession | null = null\n\n\toverride async openCustomerPortal(options: CustomerPortalOptions = {}): Promise<string | null> {\n\t\treturn super.openCustomerPortal({\n\t\t\t...options,\n\t\t\tselectAccount:\n\t\t\t\toptions.selectAccount ?? ((accounts) => this.billingProfiles.show(accounts, this.config.locale)),\n\t\t})\n\t}\n\n\toverride destroy(): void {\n\t\tthis.disposed = true\n\t\tthis.licensePanel.hide()\n\t\tthis.billingProfiles.hide()\n\t\tthis.hidePaywall()\n\t\tsuper.destroy()\n\t}\n\n\tasync showLicense(): Promise<void> {\n\t\t// An explicit status check should see refunds/cancellations immediately.\n\t\t// The entitlement manager still falls back to the verified cache offline.\n\t\tconst summary = await this.getLicenseSummary({ force: !this.config.mock })\n\t\tif (this.disposed) return\n\t\treturn this.licensePanel.show(\n\t\t\tsummary,\n\t\t\t{\n\t\t\t\trestore: async () => {\n\t\t\t\t\tawait this.restorePurchase()\n\t\t\t\t\treturn this.getLicenseSummary({ force: true })\n\t\t\t\t},\n\t\t\t\tmanage: () => this.openCustomerPortal(),\n\t\t\t},\n\t\t\tthis.config.locale,\n\t\t)\n\t}\n\n\tasync getOffer(options: { force?: boolean } = {}): Promise<PayOfferResponse> {\n\t\tawait this.initialize()\n\t\ttry {\n\t\t\treturn await this.fetchOffer(options.force)\n\t\t} catch (error) {\n\t\t\tthrow this.reportError(error)\n\t\t}\n\t}\n\n\t/**\n\t * Renders the paywall and resolves `true` when a checkout started from it\n\t * completes, `false` when the user closes it. The offer is fetched via\n\t * `getOffer()`; if that fails the paywall still renders with checkout disabled.\n\t */\n\tasync showPaywall(options: PaywallOptions = {}): Promise<boolean> {\n\t\treturn this.present(options, null)\n\t}\n\n\t/**\n\t * The paywall for a user whose free trial ended, e.g. on `trial:ended`. In the user's\n\t * language it says the trial has ended, the tools are paused and the settings are kept,\n\t * then shows the plans, \"Restore purchase\" when recovery is on, and with `feedbackFormUrl`\n\t * a feedback button. Resolves like `showPaywall()`. The default text promises the settings\n\t * are kept: pass `description` if your extension does not keep them.\n\t */\n\tasync showTrialEnded(options: TrialEndedOptions = {}): Promise<boolean> {\n\t\tconst t = sdkStrings(this.config.locale)\n\t\tconst feedbackUrl = trialFeedbackUrl(options.feedbackFormUrl)\n\t\tif (options.feedbackFormUrl !== undefined && !feedbackUrl)\n\t\t\tthis.reportError(\n\t\t\t\tnew ExtenshiPayError(\n\t\t\t\t\tERROR_CODES.INVALID_REQUEST,\n\t\t\t\t\t'feedbackFormUrl must be an https URL without credentials; the feedback button is left out',\n\t\t\t\t),\n\t\t\t)\n\t\tconst { feedbackFormUrl: _url, feedbackLabel, ...paywall } = options\n\t\treturn this.present(\n\t\t\t{\n\t\t\t\t...paywall,\n\t\t\t\ttitle: options.title ?? t.trialEndedTitle,\n\t\t\t\tdescription: options.description ?? t.trialEndedDescription,\n\t\t\t},\n\t\t\tfeedbackUrl ? { label: feedbackLabel ?? t.trialEndedFeedback, url: feedbackUrl } : null,\n\t\t)\n\t}\n\n\tprivate async present(\n\t\toptions: PaywallOptions,\n\t\tfeedback: { label: string; url: string } | null,\n\t): Promise<boolean> {\n\t\tawait this.initialize()\n\t\tlet offer: PayOfferResponse | null = null\n\t\ttry {\n\t\t\toffer = await this.fetchOffer()\n\t\t} catch (error) {\n\t\t\tthis.reportError(error)\n\t\t}\n\t\tconst selected = pickOffer(offer, options.sku)\n\t\tconst defaults = stringsFor(this.config.locale)\n\t\tconst view: PaywallView = {\n\t\t\tmode: options.mode ?? 'modal',\n\t\t\ttitle: options.title ?? selected?.title ?? defaults.title,\n\t\t\tdescription: options.description ?? selected?.description ?? defaults.description,\n\t\t\t// The offer's `features` are entitlement keys ('full'), not display\n\t\t\t// text: bullets come from the caller only, or the block is dropped.\n\t\t\tfeatures: options.features ?? [],\n\t\t\tfreeFeatures: options.freeFeatures ?? [],\n\t\t\ticon: paywallIconUrl(options.icon),\n\t\t\tbrandName: offer?.projectName ?? '',\n\t\t\toffer: selected,\n\t\t\tcheckoutEnabled: offer?.checkoutEnabled === true && selected !== null && offer.seller !== null,\n\t\t\tmock: this.config.mock,\n\t\t\trecoveryEnabled: offer?.recoveryEnabled === true,\n\t\t\tseller: offer?.seller ?? null,\n\t\t\twithdrawalWaiver: offer?.withdrawalWaiver ?? null,\n\t\t\tfeedback: feedback ? { label: feedback.label } : null,\n\t\t\tlocale: this.config.locale,\n\t\t\ttheme: { ...this.config.theme, ...options.theme },\n\t\t\tstrings: options.strings ?? {},\n\t\t\tcontainer: options.container,\n\t\t}\n\t\tthis.hidePaywall()\n\t\treturn new Promise<boolean>((resolve) => {\n\t\t\tthis.paywallSession = { options, resolve, feedbackUrl: feedback?.url ?? null }\n\t\t\ttry {\n\t\t\t\tthis.renderer().show(view)\n\t\t\t} catch (error) {\n\t\t\t\tthis.paywallSession = null\n\t\t\t\tthis.reportError(error)\n\t\t\t\tresolve(false)\n\t\t\t}\n\t\t})\n\t}\n\n\thidePaywall(): void {\n\t\tthis.paywall?.hide()\n\t\tthis.settlePaywall(false)\n\t}\n\n\tisPaywallVisible(): boolean {\n\t\treturn this.paywall?.isVisible() === true\n\t}\n\n\tprotected override async onFeatureLocked(\n\t\t_feature: string,\n\t\toptions: RequireFeatureOptions,\n\t): Promise<boolean> {\n\t\tif (options.showPaywall === false) return false\n\t\tif ((await this.getEntitlement()).requiresOnlineCheck) {\n\t\t\tawait this.showLicense()\n\t\t\treturn false\n\t\t}\n\t\treturn this.showPaywall(options.paywall ?? {})\n\t}\n\n\tprivate renderer(): PaywallRenderer {\n\t\tif (!this.paywall) {\n\t\t\tthis.paywall = new PaywallRenderer({\n\t\t\t\tonUpgrade: (sku, consent) => void this.handleUpgrade(sku, consent),\n\t\t\t\tonClose: () => this.settlePaywall(false),\n\t\t\t\tonRestore: () => void this.handleRestore(),\n\t\t\t\tonFeedback: () => void this.handleFeedback(),\n\t\t\t})\n\t\t}\n\t\treturn this.paywall\n\t}\n\n\tprivate async handleRestore(): Promise<void> {\n\t\ttry {\n\t\t\tconst result = await this.restorePurchase()\n\t\t\tif (result.state === 'complete' && isEntitled(result.entitlement)) {\n\t\t\t\tthis.paywall?.hide()\n\t\t\t\tthis.settlePaywall(true)\n\t\t\t}\n\t\t} catch {\n\t\t\t/* Reported through the error event; leave the paywall open for retry. */\n\t\t}\n\t}\n\n\tprivate async handleFeedback(): Promise<void> {\n\t\tconst url = this.paywallSession?.feedbackUrl\n\t\tif (!url) return\n\t\ttry {\n\t\t\tawait (this.openUrl ?? openInNewTab)(url)\n\t\t} catch (error) {\n\t\t\tthis.reportError(error)\n\t\t}\n\t}\n\n\tprivate async handleUpgrade(sku: string, consent?: UpgradeConsent): Promise<void> {\n\t\tif (consent) this.paywallSession?.options.onUpgrade?.(sku, consent)\n\t\telse this.paywallSession?.options.onUpgrade?.(sku)\n\t\ttry {\n\t\t\tconst result = await this.openCheckout(\n\t\t\t\tsku,\n\t\t\t\tconsent?.withdrawalWaiver ? { withdrawalWaiver: consent.withdrawalWaiver } : {},\n\t\t\t)\n\t\t\tif (result.state === 'complete') {\n\t\t\t\tthis.paywall?.hide()\n\t\t\t\tthis.settlePaywall(true)\n\t\t\t}\n\t\t} catch {\n\t\t\t// Reported through the `error` event by openCheckout(); the paywall stays open for a retry.\n\t\t}\n\t}\n\n\tprivate settlePaywall(unlocked: boolean): void {\n\t\tconst session = this.paywallSession\n\t\tif (!session) return\n\t\tthis.paywallSession = null\n\t\tif (!unlocked) session.options.onClose?.()\n\t\tsession.resolve(unlocked)\n\t}\n}\n"],"names":["PAY_CONTRACT_VERSION","PAY_GATEWAYS","PAY_PUBLISHABLE_KEY_PREFIX","PAY_PUBLISHABLE_KEY_HEX_LENGTH","PUBLISHABLE_KEY_RE","RegExp","isPayPublishableKey","value","test","PAY_OFFER_KINDS","PAY_OFFER_INTERVALS","PAY_CURRENCIES","PAY_SKU_RE","PAY_ENTITLEMENT_STATUSES","PAY_WITHDRAWAL_WAIVER_VERSION","PAY_END_USER_REF_RE","PAY_ERRORS","SELLER_NOT_CONNECTED","SELLER_NOT_ACTIVE","AGREEMENT_REQUIRED","OFFER_NOT_FOUND","OFFER_LIMIT","PRICE_TOO_LOW","GATEWAY_UNAVAILABLE","RATE_LIMITED","INVALID_KEY","WITHDRAWAL_WAIVER_REQUIRED","canonicalJson","JSON","stringify","Array","isArray","map","item","join","Object","entries","filter","v","undefined","sort","a","b","k","PAY_RESTORE_PURPOSES","STORAGE_TOKEN_RE","ERROR_CODES","INVALID_CONFIG","INVALID_REQUEST","NETWORK_ERROR","TIMEOUT","VERIFICATION_UNAVAILABLE","INVALID_RESPONSE","CHECKOUT_UNAVAILABLE","PAYWALL_UNAVAILABLE","UNKNOWN","ExtenshiPayError","Error","constructor","code","message","options","super","this","name","retryAfterSec","httpStatus","cause","from","error","fallback","String","END_USER_REF_STORAGE_KEY","mintEndUserRef","cryptoApi","globalThis","crypto","randomUUID","bytes","getRandomValues","Uint8Array","hex","toString","padStart","slice","async","getOrCreateEndUserRef","storage","existing","get","ref","set","DAY_MS","MockTransport","data","sessions","Map","entitlements","offers","projectName","checkoutEnabled","claimAfterPolls","withdrawalWaiver","version","seller","trial","setTrial","days","startedAt","call","procedure","_kind","input","offerResponse","createCheckout","sku","consent","accepted","mockConsent","claim","sessionId","endUserRef","publishableKey","envelope","url","length","setEntitlements","items","Date","toISOString","start","parse","Number","isFinite","endsAt","cancelSession","session","state","expireSession","provider","entitlementPublicKey","some","offer","polls","expiresAt","now","grant","entitlement","find","o","kind","interval","title","status","features","payload","issuedAt","signature","alg","PayApi","transport","createRestoreSession","claimChallenge","locale","purpose","claimRestoreSession","claimSecret","getOffer","claimSession","getEntitlement","trialStartedHint","getPortalUrl","customerId","ORDER","silent","warn","info","debug","Logger","level","prefix","configure","logLevel","args","enabled","console","logger","TRPC_PATH","RETRYABLE","Set","CAUSE_TO_CODE","trpcErrorToPayError","trpcCode","causeCode","match","exec","parseRetryAfter","mapped","sleep","ms","Promise","resolve","setTimeout","HttpTransport","apiUrl","replace","timeoutMs","retries","fetchImpl","init","fetch","base","encodeURIComponent","attempts","lastError","attempt","request","err","has","controller","AbortController","timer","abort","response","method","headers","body","signal","credentials","aborted","clearTimeout","json","ok","result","CHECKOUT_POLL_INTERVAL_MS","CHECKOUT_TIMEOUT_MS","openInNewTab","g","tabs","chrome","browser","create","then","open","CheckoutManager","active","pendingKey","isActive","getEndUserRef","api","pending","emit","openUrl","poll","resumePending","raw","expires","remove","settle","pollIntervalMs","deadline","sleeper","wake","interruptibleSleep","stopFocus","onFocus","disposers","addEventListener","removeEventListener","push","doc","document","onVisible","visibilityState","windows","onFocusChanged","addListener","onWindow","windowId","removeListener","dispose","onFocusRegained","delay","errorBackoff","Math","min","onComplete","CloudBackup","storageKey","accept","token","reason","assertTrustedContext","disable","mock","throwUnlessOk","runtime","id","inContentScript","path","Authorization","LIVE_STATUSES","isLive","applyLocalExpiry","collectFeatures","feature","add","isEntitled","requiresOnlineCheck","hasFeature","includes","checkFeatures","EMPTY_ENTITLEMENT","freeze","verified","fetchedAt","source","offlineUntil","base64ToBytes","base64","binary","atob","i","charCodeAt","verifyEntitlementSignature","publicKeyBase64","subtle","key","importKey","TextEncoder","encode","verify","PUBLIC_KEY_RE","verifyWithKeys","verdict","known","current","mismatch","fetchCurrent","MAX_TIMER_MS","TrialNotifier","running","evaluate","stop","clearTimer","check","catch","getTrial","endingAt","endingDays","event","daysLeft","hasPaidAccess","send","next","at","max","field","stored","sent","MIN_REFRESH_INTERVAL_MS","MAX_REFRESH_BACKOFF_MS","MAX_CLOCK_SKEW_MS","isEnvelope","env","EntitlementManager","held","inflight","clockSkew","refreshGeneration","deadlineTimer","refreshIntervalMs","backoffMs","autoRefresh","online","force","notifyIfChanged","lastFingerprint","load","record","measureClockSkew","fingerprint","snapshot","reverify","keys","discard","scheduleDeadline","verifiedKey","getCached","clock","left","checked","ceil","trialState","offlineDeadline","isFresh","cacheTtlMs","offlineAgeMs","refresh","onError","hint","getTrialStartHint","finally","onAccepted","settleRefresh","clear","startAutoRefresh","intervalMs","stopAutoRefresh","schedule","deadlines","NaN","remaining","delayMs","generation","local","server","abs","direction","onChange","seconds","offlineSeconds","extensionGlobals","areaCall","direct","withCallback","reject","ExtensionStorage","area","cb","LocalStorageAdapter","store","getItem","setItem","removeItem","MemoryStorage","delete","createSyncStorage","sync","createStorage","localStorage","createRecoveryStorage","extension","RecoveryManager","stopped","secret","hash","digest","challenge","created","done","once","cloudBackup","onStorageGrant","DEFAULT_API_URL","DEFAULT_CACHE_TTL_MS","MAX_CACHE_TTL_MS","DEFAULT_TRIAL_ENDING_DAYS","VERSION","WIRE_LOCALE_RE","wireLocale","parts","trim","split","Boolean","lang","toLowerCase","script","p","region","tag","toUpperCase","ENVIRONMENTS","LOG_LEVELS","THEME_MODES","LOCALE_RE","resolveConfig","errors","URL","protocol","isHttpUrl","environment","ui","i18n","getUILanguage","navigator","language","browserLocale","theme","mode","trialEndingDays","isInteger","mockData","syncTrialStart","EventEmitter","listeners","on","listener","off","fn","removeAll","SDK_LOCALES","SDK_STRINGS_EN","description","upgrade","cancel","dismiss","remindLater","continueFree","checkoutUnavailable","periodMonth","periodYear","periodOnce","footer","restorePurchase","featuresHeading","plansHeading","freePlanName","premiumPlanName","popularBadge","unlockHeading","simulatePurchase","mockNotice","sellerProvidedBy","sellerUnavailable","sellerSupport","sellerTerms","sellerRefunds","sellerRole","licenseTitle","licenseFallbackName","licenseNone","kindOneTime","kindLifetime","kindSubscription","kindLicense","statusLine","statusActive","statusGrace","statusExpired","statusNone","accessEnded","accessUntil","accessRecordedEnd","subscriptionLine","renewalCanceled","periodEnds","subActive","subTrialing","subPastDue","subCanceled","subUnpaid","subIncomplete","subIncompleteExpired","subPaused","licenseOffline","licenseCached","licenseFresh","actionFailed","manageBilling","noPortal","close","pickerTitle","pickerDescription","pickerFirstRecorded","pickerCancel","trialEndedTitle","trialEndedDescription","trialEndedFeedback","TRANSLATIONS","es","fr","de","it","ru","ja","ko","ar","sdkLocale","exact","l","sdkDir","sdkStrings","fill","values","whole","WITHDRAWAL_WAIVER_TEXTS","en","withdrawalWaiverText","serverVersion","text","ExtenshiPayLite","config","deps","emitter","endUserRefPromise","offerInflight","serverKey","offline","readSavedServerKey","fetchOffer","readyPromise","destroyed","syncStorage","rememberTrialStart","readTrialStartHint","reportError","checkout","backup","recovery","recoveryStorage","onReady","initialize","doInitialize","afterReady","confirmSavedServerKey","getCachedEntitlement","isPaid","requireFeature","onUnlock","unlocked","onFeatureLocked","onCancel","_feature","_options","getWithdrawalWaiver","displayName","openCheckout","enableCloudBackup","cloudBackupToken","disableCloudBackup","deleteCloudBackup","getLicenseSummary","recoveryEnabled","openCustomerPortal","accounts","selectAccount","onEntitlementChange","clearCache","destroy","rememberServerKey","serverKeyStorageKey","used","trialStartKey","synced","sellerDetails","t","section","createElement","className","textContent","append","link","label","href","username","password","publicContactUrl","target","rel","style","marginInlineEnd","supportUrl","termsUrl","refundPolicyUrl","role","statusLabel","grace","expired","none","subscriptionStatusLabel","trialing","past_due","canceled","unpaid","incomplete","incomplete_expired","paused","LicensePanel","hide","show","summary","actions","host","setAttribute","root","attachShadow","dialog","content","feedback","render","replaceChildren","note","empty","article","heading","date","isNaN","getTime","expiry","when","toLocaleString","sub","subscriptions","row","cancelAtPeriodEnd","freshness","showModal","closed","preventDefault","buttons","action","run","button","type","forEach","disabled","updated","restore","manage","BillingProfilePicker","finish","account","detail","recorded","createdAt","toLocaleDateString","subscription","line","end","currentPeriodEnd","cancellation","DATA_IMAGE_RE","PACKAGE_BASE_RE","paywallIconUrl","option","explicit","extensionRuntime","getURL","packageBase","location","startsWith","onExtensionPage","best","size","getManifest","icons","n","largestIcon","formatPrice","amountMinor","currency","formatter","Intl","NumberFormat","formatToParts","part","amount","full","format","toFixed","periodLabel","strings","paywallStrings","DEFAULT_STRINGS","stringsFor","PAYWALL_SHARED_CSS","PAYWALL_TEMPLATES","modal","html","css","inline","sidebar","fullscreen","minimal","PAYWALL_MODES","PAYWALL_HOST_CLASS","UPGRADE_ACTIONS","UPGRADE_SELECTOR","WITHDRAWAL_WAIVER_CLASS","CLOSE_ACTIONS","ROOT_SELECTOR","BACKDROP_SELECTOR","VISIBLE_CLASSES","ICON_TILE_SELECTOR","FEATURE_ITEM_VISIBLE","FEATURE_SLOT_SELECTOR","EMPTY_SLOT_MARK","OPTIONAL_KEY_RE","escapeHtml","substitute","_match","buildContent","view","price","offerDescription","priceCopy","brandName","period","pricingDescription","priceDescription","premiumDescription","upgradeButtonText","cancelButtonText","dismissButtonText","remindLaterText","continueButtonText","footerText","index","freeFeatures","CSS_VALUE_UNSAFE","PRIMARY_TINTS","PRIMARY_SHADES","themeCss","declarations","safe","primaryColor","color","step","percent","fontFamily","borderRadius","radius","customCss","resolveThemeMode","matchMedia","matches","PaywallRenderer","callbacks","keyHandler","isVisible","template","innerHTML","prune","icon","placeIcon","waiver","waiverSellerName","waiverBox","bind","sellerMount","querySelector","details","cssText","modalActions","before","notice","mountWaiver","onRestore","footerLink","onFeedback","container","appendChild","reveal","ownerDocument","onClick","element","querySelectorAll","mark","parentElement","closest","block","slot","glyph","children","child","localName","tile","getAttribute","img","alt","replaceWith","removeProperty","src","background","first","span","removeAttribute","given","onUpgrade","backdropSelector","currentTarget","rootElement","display","selector","classList","onClose","ExtenshiPay","disposed","licensePanel","billingProfiles","paywall","paywallSession","hidePaywall","showLicense","showPaywall","present","showTrialEnded","feedbackUrl","searchParams","trialFeedbackUrl","feedbackFormUrl","_url","feedbackLabel","selected","candidate","pickOffer","defaults","renderer","settlePaywall","isPaywallVisible","handleUpgrade","handleRestore","handleFeedback"],"mappings":";;;;;;AAaO,MAAMA,EAAuB,EAEvBC,EAAe,CAAC,SAAU,SAAU,gBAUpC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Q,mBAAMqB,GACb,IACC,MAAMvqB,QAAe1K,KAAKmc,kBACL,aAAjBzR,EAAOhG,OAAwB0K,EAAW1E,EAAOtF,eACpDpF,KAAK4zB,SAASpN,OACdxmB,KAAK80B,eAAc,GAErB,CAAE,MAEF,CACD,CAEQ,oBAAMI,GACb,MAAMrxB,EAAM7D,KAAK6zB,gBAAgBM,YACjC,GAAKtwB,EACL,UACQ7D,KAAK6L,SAAWhB,GAAchH,EACtC,CAAE,MAAOvD,GACRN,KAAK+hB,YAAYzhB,EAClB,CACD,CAEQ,mBAAM00B,CAAc5xB,EAAaC,GACpCA,EAASrD,KAAK6zB,gBAAgB/zB,QAAQkzB,YAAY5vB,EAAKC,GACtDrD,KAAK6zB,gBAAgB/zB,QAAQkzB,YAAY5vB,GAC9C,IAKsB,oBAJApD,KAAKojB,aACzBhgB,EACAC,GAASd,iBAAmB,CAAEA,iBAAkBc,EAAQd,kBAAqB,CAAA,IAEnEmC,QACV1E,KAAK4zB,SAASpN,OACdxmB,KAAK80B,eAAc,GAErB,CAAE,MAEF,CACD,CAEQ,aAAAA,CAAcjS,GACrB,MAAMpe,EAAUzE,KAAK6zB,eAChBpvB,IACLzE,KAAK6zB,eAAiB,KACjBhR,GAAUpe,EAAQ3E,QAAQyzB,YAC/B9uB,EAAQiE,QAAQma,GACjB"}
|
|
1
|
+
{"version":3,"file":"extenshi-pay.min.mjs","sources":["../src/types/contract.ts","../src/types/errors.ts","../src/core/identity.ts","../src/api/mock.ts","../src/api/pay-api.ts","../src/utils/logger.ts","../src/api/transport.ts","../src/payment/checkout.ts","../src/payment/cloud-backup.ts","../src/payment/features.ts","../src/payment/signature.ts","../src/payment/trial.ts","../src/payment/entitlement.ts","../src/core/storage.ts","../src/payment/recovery.ts","../src/types/config.ts","../src/version.ts","../src/core/locale.ts","../src/core/config.ts","../src/core/event-emitter.ts","../src/paywall/i18n.ts","../src/payment/withdrawal-waiver.ts","../src/core/extenshi-pay.ts","../src/paywall/seller-details.ts","../src/paywall/license-panel.ts","../src/paywall/billing-profile-picker.ts","../src/paywall/icon.ts","../src/paywall/format.ts","../src/paywall/strings.ts","../../extension_templates/paywall-templates/fullscreen/template.html","../src/paywall/templates.ts","../../extension_templates/paywall-templates/modal/template.html","../../extension_templates/paywall-templates/inline/template.html","../../extension_templates/paywall-templates/sidebar/template.html","../../extension_templates/paywall-templates/minimal/template.html","../src/paywall/renderer.ts","../src/extenshi-pay.ts"],"sourcesContent":["/**\n * Wire contract between the SDK and catalog-bff `pay.*`.\n *\n * SOURCE OF TRUTH: `shared-types/pay.ts` in the extenshi.io monorepo. The SDK\n * ships with zero runtime dependencies and must not import that workspace, so\n * the types and constants it needs are copied here under identical names.\n * `canonicalJson` is copied VERBATIM: the BFF signs its output and the SDK\n * verifies it, so both sides must produce byte-identical strings\n * (pinned by tests/unit/canonical-json.test.ts). When `shared-types/pay.ts`\n * changes, mirror the change here.\n */\n\n/** Bumped only when an older SDK could misread the response. */\nexport const PAY_CONTRACT_VERSION = 1\n\nexport const PAY_GATEWAYS = ['stripe', 'paddle', 'lemonsqueezy'] as const\nexport type PayGatewayId = (typeof PAY_GATEWAYS)[number]\n\n// ─── Publishable key ────────────────────────────────────────────────────────\n\n/**\n * The only credential an extension bundle carries. It is public by\n * construction (anyone can unzip the .crx), so it must grant nothing beyond\n * \"read this project's offer\" and \"start a checkout for this project\".\n */\nexport const PAY_PUBLISHABLE_KEY_PREFIX = 'pk_ext_'\nexport const PAY_PUBLISHABLE_KEY_HEX_LENGTH = 32\nconst PUBLISHABLE_KEY_RE = new RegExp(\n\t`^${PAY_PUBLISHABLE_KEY_PREFIX}[0-9a-f]{${PAY_PUBLISHABLE_KEY_HEX_LENGTH}}$`,\n)\n\nexport function isPayPublishableKey(value: unknown): value is string {\n\treturn typeof value === 'string' && PUBLISHABLE_KEY_RE.test(value)\n}\n\n// ─── Offers ─────────────────────────────────────────────────────────────────\n\nexport const PAY_OFFER_KINDS = ['one_time', 'subscription', 'lifetime'] as const\nexport type PayOfferKind = (typeof PAY_OFFER_KINDS)[number]\n\nexport const PAY_OFFER_INTERVALS = ['month', 'year'] as const\nexport type PayOfferInterval = (typeof PAY_OFFER_INTERVALS)[number]\n\n/** ISO-4217 lowercase, matching what every gateway returns. */\nexport const PAY_CURRENCIES = ['usd', 'eur', 'gbp'] as const\nexport type PayCurrency = (typeof PAY_CURRENCIES)[number]\n\n/** `sku` is author-chosen and stable; it is what `requireFeature()` keys on. */\nexport const PAY_SKU_RE = /^[a-z0-9][a-z0-9_-]{1,39}$/\n\n// ─── Projection ─────────────────────────────────────────────────────────────\n\n/**\n * active — paid and not expired\n * grace — subscription past_due: keep access for a short window so a card\n * hiccup does not lock a paying user out mid-session\n * expired — was active, no longer is\n * none — never had it\n */\nexport const PAY_ENTITLEMENT_STATUSES = ['active', 'grace', 'expired', 'none'] as const\nexport type PayEntitlementStatus = (typeof PAY_ENTITLEMENT_STATUSES)[number]\n\n// ─── SDK-facing DTOs (the `pay.*` tRPC contract) ────────────────────────────\n\nexport interface PayOfferDto {\n\tsku: string\n\tkind: PayOfferKind\n\tinterval: PayOfferInterval | null\n\tamountMinor: number\n\tcurrency: PayCurrency\n\ttitle: string\n\tdescription: string | null\n\tfeatures: string[]\n}\n\n// Outside the seller SKU grammar. Issued only in a signed projection, never in the sales ledger.\nexport const PAY_REGIONAL_ACCESS_SKU = '@regional-free'\n\nexport interface PayOfferResponse {\n\t/** Optional during rolling upgrades; never infer this from the project name. */\n\tseller?: PaySellerPublic | null\n\n\tv: typeof PAY_CONTRACT_VERSION\n\tprojectName: string\n\tprovider: PayGatewayId\n\t/** False while the seller cannot take money; the SDK renders the offer read-only. */\n\tcheckoutEnabled: boolean\n\t/** Optional for older servers; show recovery only when explicitly enabled. */\n\trecoveryEnabled?: boolean\n\toffers: PayOfferDto[]\n\t/** Base64 Ed25519 public key for `SignedEntitlement.signature`; null when unsigned. */\n\tentitlementPublicKey: string | null\n\t/**\n\t * The language the offers' text is in when the seller translated them\n\t * (it. 13 T10 L2); absent from older servers and for single-language offers.\n\t */\n\tlocale?: string\n\t/**\n\t * Set when the paywall must show an unticked withdrawal-waiver checkbox and\n\t * send the accepted `version` with `createCheckout`. Null when the seller\n\t * attested the extension is not distributed in the EEA/UK; absent from\n\t * older servers (the SDK then shows no checkbox).\n\t */\n\twithdrawalWaiver?: PayWithdrawalWaiver | null\n}\n\n/**\n * Version of the buyer-facing withdrawal waiver text the paywall shows (EU/EEA\n * digital content, Directive 2011/83/EU art. 16(m); UK CCR 2013 reg. 37). The\n * text itself lives in the SDK dictionary under the same version; bump both\n * together so a recorded consent always names the words the buyer saw.\n */\nexport const PAY_WITHDRAWAL_WAIVER_VERSION = '2026-10-v1'\n\nexport interface PayWithdrawalWaiver {\n\tversion: string\n}\n\nexport interface PayEntitlementItem {\n\t/** Optional for old signed caches and older servers. */\n\ttitle?: string\n\tkind?: PayOfferKind\n\tsubscriptions?: Array<{\n\t\tstatus: string\n\t\tcancelAtPeriodEnd: boolean\n\t\tcurrentPeriodEnd: string | null\n\t}>\n\n\tsku: string\n\tstatus: PayEntitlementStatus\n\t/** ISO timestamp; null for lifetime / one-time grants. */\n\texpiresAt: string | null\n\tfeatures: string[]\n}\n\n/**\n * The installation's free trial on the server clock: one per installation per application,\n * started at its first license read. Absent when the application has no trial.\n */\nexport interface PayTrial {\n\t/** ISO time of the first license read while the application had a trial. */\n\tstartedAt: string\n\t/** ISO `startedAt` plus the application's current trial length. */\n\tendsAt: string\n}\n\nexport interface PayEntitlementPayload {\n\tv: typeof PAY_CONTRACT_VERSION\n\t/** Signed application scope; prevents moving a grant to another application. */\n\tpublishableKey: string\n\tendUserRef: string\n\tentitlements: PayEntitlementItem[]\n\t/** ISO timestamp the projection was computed at; the SDK uses it for cache age. */\n\tissuedAt: string\n\t/** Optional: only for an application with a trial, and absent from older servers. */\n\ttrial?: PayTrial\n\t/** Optional: seconds of offline access after `issuedAt`; absent from older servers (48 hours). */\n\tofflineSeconds?: number\n}\n\nexport interface SignedEntitlement {\n\tpayload: PayEntitlementPayload\n\t/** Base64 Ed25519 signature over the canonical JSON of `payload`; null when the server has no key. */\n\tsignature: string | null\n\talg: 'ed25519' | null\n}\n\nexport type PayCheckoutClaim =\n\t| { state: 'pending' }\n\t| { state: 'complete'; entitlement: SignedEntitlement }\n\t| { state: 'expired' }\n\t| { state: 'canceled' }\n\nexport interface PayCheckoutSession {\n\turl: string\n\tsessionId: string\n\t/** ISO timestamp. */\n\texpiresAt: string\n}\n\n/**\n * The `endUserRef` an SDK mints on first run and keeps in `chrome.storage`.\n * Opaque, random, never derived from anything identifying.\n */\nexport const PAY_END_USER_REF_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i\n\n/** Typed error codes the BFF throws; dojo and the SDK match on `cause.code`. */\nexport const PAY_ERRORS = {\n\tSELLER_NOT_CONNECTED: 'PAY_SELLER_NOT_CONNECTED',\n\tSELLER_NOT_ACTIVE: 'PAY_SELLER_NOT_ACTIVE',\n\tAGREEMENT_REQUIRED: 'PAY_AGREEMENT_REQUIRED',\n\tOFFER_NOT_FOUND: 'PAY_OFFER_NOT_FOUND',\n\tOFFER_LIMIT: 'PAY_OFFER_LIMIT',\n\tPRICE_TOO_LOW: 'PAY_PRICE_TOO_LOW',\n\tGATEWAY_UNAVAILABLE: 'PAY_GATEWAY_UNAVAILABLE',\n\tRATE_LIMITED: 'PAY_RATE_LIMITED',\n\tINVALID_KEY: 'PAY_INVALID_KEY',\n\tWITHDRAWAL_WAIVER_REQUIRED: 'PAY_WITHDRAWAL_WAIVER_REQUIRED',\n} as const\nexport type PayErrorCode = (typeof PAY_ERRORS)[keyof typeof PAY_ERRORS]\n\n/**\n * Canonical JSON for signing: keys sorted recursively, no whitespace. Both\n * the BFF (sign) and the SDK (verify) must produce byte-identical output for\n * the same payload, so the rule lives in the shared contract.\n */\nexport function canonicalJson(value: unknown): string {\n\tif (value === null || typeof value !== 'object') return JSON.stringify(value)\n\tif (Array.isArray(value)) return `[${value.map((item) => canonicalJson(item)).join(',')}]`\n\tconst entries = Object.entries(value as Record<string, unknown>)\n\t\t.filter(([, v]) => v !== undefined)\n\t\t.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n\treturn `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonicalJson(v)}`).join(',')}}`\n}\n\nexport interface PayRestoreSessionResponse {\n\tsessionId: string\n\texpiresAt: string\n\turl: string\n}\n/**\n * `storage`: the buyer turns on the cloud copy of the extension's settings. The\n * hosted page shows the storage disclosure; the claim records consent. Additive:\n * a session without a purpose is a plain restore.\n */\nexport const PAY_RESTORE_PURPOSES = ['restore', 'storage'] as const\nexport type PayRestorePurpose = (typeof PAY_RESTORE_PURPOSES)[number]\n\n/**\n * Outcome for the cloud copy of settings, present in a complete claim only when\n * the application offers it. A token is returned once; a retried claim rotates it.\n */\nexport type PayStorageGrant =\n\t| { state: 'granted'; token: string }\n\t| { state: 'unavailable'; reason: 'NO_CONSENT' | 'LICENSE_REQUIRED' }\n\n/** From `shared-types/storage.ts`: `est_` + 32 random bytes, base64url. */\nexport const STORAGE_TOKEN_RE = /^est_[A-Za-z0-9_-]{43}$/\n\nexport type PayRestoreClaimResponse =\n\t| { state: 'pending' }\n\t| { state: 'complete'; endUserRef: string; entitlement: SignedEntitlement; storage?: PayStorageGrant }\n\n/** A project-scoped billing profile; provider identifiers are never exposed. */\nexport interface PayPortalAccount {\n\tid: string\n\tlabel: string\n\tcreatedAt: string\n\tsubscriptions: Array<{\n\t\ttitle: string\n\t\tstatus: string\n\t\tcancelAtPeriodEnd: boolean\n\t\tcurrentPeriodEnd: string | null\n\t}>\n}\n\nexport interface PayPortalResponse {\n\turl: string | null\n\t/** Present when the buyer must choose among multiple billing profiles. */\n\taccounts?: PayPortalAccount[]\n}\n\n/** Public author-provided contact details. Not a claim of identity verification. */\nexport interface PaySellerPublic {\n\tdisplayName: string\n\t/** HTTPS support page or plain email address. */\n\tsupportUrl: string\n\ttermsUrl: string | null\n\t/** Optional for older servers: refunds section of the license terms. */\n\trefundPolicyUrl?: string | null\n}\n","export const ERROR_CODES = {\n\tINVALID_CONFIG: 'INVALID_CONFIG',\n\tINVALID_REQUEST: 'INVALID_REQUEST',\n\tNETWORK_ERROR: 'NETWORK_ERROR',\n\tTIMEOUT: 'TIMEOUT',\n\tVERIFICATION_UNAVAILABLE: 'VERIFICATION_UNAVAILABLE',\n\tINVALID_RESPONSE: 'INVALID_RESPONSE',\n\tRATE_LIMITED: 'RATE_LIMITED',\n\tINVALID_KEY: 'INVALID_KEY',\n\tSELLER_NOT_ACTIVE: 'SELLER_NOT_ACTIVE',\n\tOFFER_NOT_FOUND: 'OFFER_NOT_FOUND',\n\tGATEWAY_UNAVAILABLE: 'GATEWAY_UNAVAILABLE',\n\tCHECKOUT_UNAVAILABLE: 'CHECKOUT_UNAVAILABLE',\n\tPAYWALL_UNAVAILABLE: 'PAYWALL_UNAVAILABLE',\n\tWITHDRAWAL_WAIVER_REQUIRED: 'WITHDRAWAL_WAIVER_REQUIRED',\n\tUNKNOWN: 'UNKNOWN',\n} as const\n\nexport type ErrorCode = (typeof ERROR_CODES)[keyof typeof ERROR_CODES]\n\nexport interface ExtenshiPayErrorOptions {\n\tretryAfterSec?: number\n\thttpStatus?: number\n\tcause?: unknown\n}\n\nexport class ExtenshiPayError extends Error {\n\treadonly code: ErrorCode\n\treadonly retryAfterSec: number | undefined\n\treadonly httpStatus: number | undefined\n\treadonly cause: unknown\n\n\tconstructor(code: ErrorCode, message: string, options: ExtenshiPayErrorOptions = {}) {\n\t\tsuper(message)\n\t\tthis.name = 'ExtenshiPayError'\n\t\tthis.code = code\n\t\tthis.retryAfterSec = options.retryAfterSec\n\t\tthis.httpStatus = options.httpStatus\n\t\tthis.cause = options.cause\n\t}\n\n\tstatic from(error: unknown, fallback: ErrorCode = ERROR_CODES.UNKNOWN): ExtenshiPayError {\n\t\tif (error instanceof ExtenshiPayError) return error\n\t\tconst message = error instanceof Error ? error.message : String(error)\n\t\treturn new ExtenshiPayError(fallback, message, { cause: error })\n\t}\n}\n","/**\n * `endUserRef` — the only identity the SDK has.\n *\n * A random UUID minted on first run and kept in the SDK's storage namespace.\n * It is never derived from anything identifying (no fingerprint, no e-mail,\n * no extension-supplied user id) and remains the installation identifier. Explicit recovery also sends a\n * random session ID and proof; it never derives identity from an email locally.\n */\n\nimport { PAY_END_USER_REF_RE } from '../types/contract.js'\nimport { ERROR_CODES, ExtenshiPayError } from '../types/errors.js'\nimport type { StorageAdapter } from './storage.js'\n\nexport const END_USER_REF_STORAGE_KEY = 'extenshi-pay:endUserRef'\n\nexport function mintEndUserRef(): string {\n\tconst cryptoApi = (globalThis as { crypto?: Crypto }).crypto\n\tif (!cryptoApi) {\n\t\tthrow new ExtenshiPayError(ERROR_CODES.UNKNOWN, 'Web Crypto is not available in this context')\n\t}\n\tif (typeof cryptoApi.randomUUID === 'function') return cryptoApi.randomUUID()\n\tconst bytes = cryptoApi.getRandomValues(new Uint8Array(16))\n\tbytes[6] = (bytes[6] & 0x0f) | 0x40\n\tbytes[8] = (bytes[8] & 0x3f) | 0x80\n\tconst hex = Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('')\n\treturn `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`\n}\n\nexport async function getOrCreateEndUserRef(storage: StorageAdapter): Promise<string> {\n\tconst existing = await storage.get(END_USER_REF_STORAGE_KEY)\n\tif (typeof existing === 'string' && PAY_END_USER_REF_RE.test(existing)) return existing\n\tconst ref = mintEndUserRef()\n\tawait storage.set(END_USER_REF_STORAGE_KEY, ref)\n\treturn ref\n}\n","/**\n * In-memory stand-in for the BFF, used when `mock: true`. Lets an extension be\n * developed with no backend: offers and entitlements come from `mockData`, a\n * mock checkout completes after `claimAfterPolls` polls and grants the SKU.\n */\n\nimport { mintEndUserRef } from '../core/identity.js'\nimport type { MockData } from '../types/config.js'\nimport {\n\tPAY_CONTRACT_VERSION,\n\tPAY_WITHDRAWAL_WAIVER_VERSION,\n\ttype PayCheckoutClaim,\n\ttype PayEntitlementItem,\n\ttype PayOfferDto,\n\ttype PayOfferResponse,\n\ttype PaySellerPublic,\n\ttype PayTrial,\n\ttype PayWithdrawalWaiver,\n\ttype SignedEntitlement,\n} from '../types/contract.js'\nimport type { WithdrawalWaiverConsent } from '../types/entitlement.js'\nimport { ERROR_CODES, ExtenshiPayError } from '../types/errors.js'\nimport type { ProcedureKind, Transport } from './transport.js'\n\ntype SessionState = 'open' | 'complete' | 'canceled' | 'expired'\n\ninterface MockSession {\n\tsku: string\n\tpolls: number\n\tstate: SessionState\n\t/** What `createCheckout` received, for inspecting the consent in dev/tests. */\n\twithdrawalWaiver: WithdrawalWaiverConsent | null\n}\n\nconst DAY_MS = 24 * 60 * 60 * 1000\n\n/** Accepts the same optional `withdrawalWaiver` input as the BFF; anything else is no consent. */\nfunction mockConsent(value: unknown): WithdrawalWaiverConsent | null {\n\tconst consent = value as Partial<WithdrawalWaiverConsent> | null | undefined\n\treturn consent && typeof consent.version === 'string' && consent.accepted === true\n\t\t? { version: consent.version, accepted: true }\n\t\t: null\n}\n\nexport class MockTransport implements Transport {\n\tprivate entitlements: PayEntitlementItem[]\n\tprivate readonly offers: PayOfferDto[]\n\tprivate readonly projectName: string\n\tprivate readonly checkoutEnabled: boolean\n\tprivate readonly claimAfterPolls: number\n\tprivate readonly withdrawalWaiver: PayWithdrawalWaiver | null\n\tprivate readonly seller: PaySellerPublic | null | undefined\n\tprivate trial: PayTrial | null\n\treadonly sessions = new Map<string, MockSession>()\n\n\tconstructor(data: MockData = {}) {\n\t\tthis.entitlements = [...(data.entitlements ?? [])]\n\t\tthis.offers = [...(data.offers ?? [])]\n\t\tthis.projectName = data.projectName ?? 'Mock project'\n\t\tthis.checkoutEnabled = data.checkoutEnabled ?? true\n\t\tthis.claimAfterPolls = data.claimAfterPolls ?? 1\n\t\tthis.withdrawalWaiver =\n\t\t\tdata.withdrawalWaiver === undefined ? { version: PAY_WITHDRAWAL_WAIVER_VERSION } : data.withdrawalWaiver\n\t\tthis.seller = data.seller\n\t\tthis.trial = null\n\t\tif (data.trial) this.setTrial(data.trial.days, data.trial.startedAt)\n\t}\n\n\tasync call<T>(procedure: string, _kind: ProcedureKind, input: Record<string, unknown>): Promise<T> {\n\t\tswitch (procedure) {\n\t\t\tcase 'pay.getOffer':\n\t\t\t\treturn this.offerResponse() as T\n\t\t\tcase 'pay.createCheckout':\n\t\t\t\treturn this.createCheckout(String(input.sku), mockConsent(input.withdrawalWaiver)) as T\n\t\t\tcase 'pay.claimSession':\n\t\t\t\treturn this.claim(\n\t\t\t\t\tString(input.sessionId),\n\t\t\t\t\tString(input.endUserRef),\n\t\t\t\t\tString(input.publishableKey),\n\t\t\t\t) as T\n\t\t\tcase 'pay.getEntitlement':\n\t\t\t\treturn this.envelope(String(input.endUserRef), String(input.publishableKey)) as T\n\t\t\tcase 'pay.getPortalUrl':\n\t\t\t\treturn { url: this.entitlements.length > 0 ? 'https://mock.extenshi.io/portal' : null } as T\n\t\t\tdefault:\n\t\t\t\tthrow new ExtenshiPayError(ERROR_CODES.INVALID_REQUEST, `Unknown procedure ${procedure}`)\n\t\t}\n\t}\n\n\t/** Test/dev helpers. */\n\tsetEntitlements(items: PayEntitlementItem[]): void {\n\t\tthis.entitlements = [...items]\n\t}\n\n\t/** Previews a server trial of `days` from `startedAt` (default now); `null` removes it. */\n\tsetTrial(days: number | null, startedAt: string = new Date().toISOString()): void {\n\t\tconst start = Date.parse(startedAt)\n\t\tthis.trial =\n\t\t\tdays === null || !Number.isFinite(start)\n\t\t\t\t? null\n\t\t\t\t: { startedAt: new Date(start).toISOString(), endsAt: new Date(start + days * DAY_MS).toISOString() }\n\t}\n\n\tcancelSession(sessionId: string): void {\n\t\tconst session = this.sessions.get(sessionId)\n\t\tif (session) session.state = 'canceled'\n\t}\n\n\texpireSession(sessionId: string): void {\n\t\tconst session = this.sessions.get(sessionId)\n\t\tif (session) session.state = 'expired'\n\t}\n\n\tprivate offerResponse(): PayOfferResponse {\n\t\treturn {\n\t\t\tv: PAY_CONTRACT_VERSION,\n\t\t\tprojectName: this.projectName,\n\t\t\tprovider: 'stripe',\n\t\t\tcheckoutEnabled: this.checkoutEnabled && this.offers.length > 0,\n\t\t\toffers: [...this.offers],\n\t\t\tentitlementPublicKey: null,\n\t\t\twithdrawalWaiver: this.withdrawalWaiver ? { ...this.withdrawalWaiver } : null,\n\t\t\t...(this.seller !== undefined && { seller: this.seller ? { ...this.seller } : null }),\n\t\t}\n\t}\n\n\tprivate createCheckout(sku: string, withdrawalWaiver: WithdrawalWaiverConsent | null) {\n\t\tif (!this.checkoutEnabled) {\n\t\t\tthrow new ExtenshiPayError(ERROR_CODES.SELLER_NOT_ACTIVE, 'Mock seller cannot take payments')\n\t\t}\n\t\tif (!this.offers.some((offer) => offer.sku === sku)) {\n\t\t\tthrow new ExtenshiPayError(ERROR_CODES.OFFER_NOT_FOUND, `Unknown mock offer ${sku}`)\n\t\t}\n\t\tconst sessionId = mintEndUserRef()\n\t\tthis.sessions.set(sessionId, { sku, polls: 0, state: 'open', withdrawalWaiver })\n\t\treturn {\n\t\t\turl: `https://mock.extenshi.io/checkout/${sessionId}`,\n\t\t\tsessionId,\n\t\t\texpiresAt: new Date(Date.now() + 30 * 60 * 1000).toISOString(),\n\t\t}\n\t}\n\n\tprivate claim(sessionId: string, endUserRef: string, publishableKey: string): PayCheckoutClaim {\n\t\tconst session = this.sessions.get(sessionId)\n\t\tif (!session) throw new ExtenshiPayError(ERROR_CODES.CHECKOUT_UNAVAILABLE, 'Unknown checkout session')\n\t\tif (session.state === 'canceled') return { state: 'canceled' }\n\t\tif (session.state === 'expired') return { state: 'expired' }\n\t\tif (session.state === 'open') {\n\t\t\tsession.polls += 1\n\t\t\tif (session.polls <= this.claimAfterPolls) return { state: 'pending' }\n\t\t\tsession.state = 'complete'\n\t\t\tthis.grant(session.sku)\n\t\t}\n\t\treturn { state: 'complete', entitlement: this.envelope(endUserRef, publishableKey) }\n\t}\n\n\tprivate grant(sku: string): void {\n\t\tconst offer = this.offers.find((o) => o.sku === sku)\n\t\tconst expiresAt =\n\t\t\toffer?.kind === 'subscription'\n\t\t\t\t? new Date(Date.now() + (offer.interval === 'year' ? 365 : 30) * DAY_MS).toISOString()\n\t\t\t\t: null\n\t\tthis.entitlements = [\n\t\t\t...this.entitlements.filter((item) => item.sku !== sku),\n\t\t\t{\n\t\t\t\tsku,\n\t\t\t\ttitle: offer?.title,\n\t\t\t\tkind: offer?.kind,\n\t\t\t\tstatus: 'active',\n\t\t\t\texpiresAt,\n\t\t\t\tfeatures: offer?.features ?? [],\n\t\t\t},\n\t\t]\n\t}\n\n\tprivate envelope(endUserRef: string, publishableKey: string): SignedEntitlement {\n\t\treturn {\n\t\t\tpayload: {\n\t\t\t\tv: PAY_CONTRACT_VERSION,\n\t\t\t\tpublishableKey,\n\t\t\t\tendUserRef,\n\t\t\t\tentitlements: [...this.entitlements],\n\t\t\t\tissuedAt: new Date().toISOString(),\n\t\t\t\t...(this.trial ? { trial: { ...this.trial } } : {}),\n\t\t\t},\n\t\t\tsignature: null,\n\t\t\talg: null,\n\t\t}\n\t}\n}\n","/** Typed wrapper over the SDK-facing `pay.*` procedures. Nothing else is ever called. */\n\nimport type {\n\tPayCheckoutClaim,\n\tPayCheckoutSession,\n\tPayOfferResponse,\n\tPayPortalResponse,\n\tPayRestoreClaimResponse,\n\tPayRestorePurpose,\n\tPayRestoreSessionResponse,\n\tSignedEntitlement,\n} from '../types/contract.js'\nimport type { WithdrawalWaiverConsent } from '../types/entitlement.js'\nimport type { Transport } from './transport.js'\n\nexport class PayApi {\n\tconstructor(\n\t\tprivate readonly transport: Transport,\n\t\tprivate readonly publishableKey: string,\n\t) {}\n\n\t/**\n\t * `locale` opens the hosted recovery page (and its email) in the user's language.\n\t * `purpose` is sent only for `storage`: a plain restore keeps the request older\n\t * BFFs know, and their non-strict zod input strips the key anyway.\n\t */\n\tcreateRestoreSession(\n\t\tclaimChallenge: string,\n\t\tlocale?: string | null,\n\t\tpurpose?: PayRestorePurpose,\n\t): Promise<PayRestoreSessionResponse> {\n\t\treturn this.transport.call('pay.createRestoreSession', 'mutation', {\n\t\t\tpublishableKey: this.publishableKey,\n\t\t\tclaimChallenge,\n\t\t\t...(locale ? { locale } : {}),\n\t\t\t...(purpose === 'storage' ? { purpose } : {}),\n\t\t})\n\t}\n\n\tclaimRestoreSession(sessionId: string, claimSecret: string): Promise<PayRestoreClaimResponse> {\n\t\treturn this.transport.call('pay.claimRestoreSession', 'mutation', {\n\t\t\tpublishableKey: this.publishableKey,\n\t\t\tsessionId,\n\t\t\tclaimSecret,\n\t\t})\n\t}\n\n\tgetOffer(locale?: string | null): Promise<PayOfferResponse> {\n\t\treturn this.transport.call('pay.getOffer', 'query', {\n\t\t\tpublishableKey: this.publishableKey,\n\t\t\tlocale: locale ?? undefined,\n\t\t})\n\t}\n\n\t/**\n\t * `withdrawalWaiver` is sent only when given. Older BFFs parse the input with\n\t * a non-strict zod object, which strips the unknown key, so it is safe there.\n\t * Plain-JS callers passing anything but `accepted: true` send no consent.\n\t */\n\tcreateCheckout(\n\t\tsku: string,\n\t\tendUserRef: string,\n\t\tlocale?: string | null,\n\t\twithdrawalWaiver?: WithdrawalWaiverConsent,\n\t): Promise<PayCheckoutSession> {\n\t\treturn this.transport.call('pay.createCheckout', 'mutation', {\n\t\t\tpublishableKey: this.publishableKey,\n\t\t\tsku,\n\t\t\tendUserRef,\n\t\t\tlocale: locale ?? undefined,\n\t\t\t...(withdrawalWaiver?.accepted === true && typeof withdrawalWaiver.version === 'string'\n\t\t\t\t? { withdrawalWaiver: { version: withdrawalWaiver.version, accepted: true } }\n\t\t\t\t: {}),\n\t\t})\n\t}\n\n\tclaimSession(sessionId: string, endUserRef: string): Promise<PayCheckoutClaim> {\n\t\treturn this.transport.call('pay.claimSession', 'query', {\n\t\t\tpublishableKey: this.publishableKey,\n\t\t\tsessionId,\n\t\t\tendUserRef,\n\t\t})\n\t}\n\n\t/** `trialStartedHint`: the trial start kept in storage.sync; the server only lets it move a start earlier. */\n\tgetEntitlement(endUserRef: string, trialStartedHint?: string | null): Promise<SignedEntitlement> {\n\t\treturn this.transport.call('pay.getEntitlement', 'query', {\n\t\t\tpublishableKey: this.publishableKey,\n\t\t\tendUserRef,\n\t\t\t...(trialStartedHint ? { trialStartedHint } : {}),\n\t\t})\n\t}\n\n\tgetPortalUrl(endUserRef: string, customerId?: string, locale?: string | null): Promise<PayPortalResponse> {\n\t\treturn this.transport.call('pay.getPortalUrl', 'mutation', {\n\t\t\tpublishableKey: this.publishableKey,\n\t\t\tendUserRef,\n\t\t\t...(customerId ? { customerId } : {}),\n\t\t\t...(locale ? { locale } : {}),\n\t\t})\n\t}\n}\n","import type { LogLevel } from '../types/config.js'\n\nconst ORDER: Record<LogLevel, number> = { silent: 0, error: 1, warn: 2, info: 3, debug: 4 }\n\nexport class Logger {\n\tprivate level: LogLevel = 'warn'\n\tprivate readonly prefix = '[ExtenshiPay]'\n\n\tconfigure(options: { logLevel?: LogLevel; debug?: boolean }): void {\n\t\tif (options.logLevel) this.level = options.logLevel\n\t\tif (options.debug) this.level = 'debug'\n\t}\n\n\terror(message: string, ...args: unknown[]): void {\n\t\tif (this.enabled('error')) console.error(this.prefix, message, ...args)\n\t}\n\n\twarn(message: string, ...args: unknown[]): void {\n\t\tif (this.enabled('warn')) console.warn(this.prefix, message, ...args)\n\t}\n\n\tinfo(message: string, ...args: unknown[]): void {\n\t\tif (this.enabled('info')) console.info(this.prefix, message, ...args)\n\t}\n\n\tdebug(message: string, ...args: unknown[]): void {\n\t\tif (this.enabled('debug')) console.debug(this.prefix, message, ...args)\n\t}\n\n\tprivate enabled(level: LogLevel): boolean {\n\t\treturn ORDER[level] <= ORDER[this.level]\n\t}\n}\n\nexport const logger = new Logger()\n","/**\n * HTTP transport for the BFF's tRPC endpoint (`/api/trpc/<procedure>`).\n *\n * Queries are header-less GETs with `?input=<json>` (a CORS \"simple request\",\n * so no preflight); mutations POST a JSON body. The only things that leave the\n * extension are payment inputs and optional recovery session/proof inputs\n * and the browser's standard headers — `credentials: 'omit'` keeps cookies out.\n * Queries are retried on network / 5xx errors; mutations never are.\n */\n\nimport { PAY_ERRORS } from '../types/contract.js'\nimport { ERROR_CODES, type ErrorCode, ExtenshiPayError } from '../types/errors.js'\nimport { logger } from '../utils/logger.js'\n\nexport type ProcedureKind = 'query' | 'mutation'\n\nexport interface Transport {\n\tcall<T>(procedure: string, kind: ProcedureKind, input: Record<string, unknown>): Promise<T>\n}\n\nexport interface HttpTransportOptions {\n\tapiUrl: string\n\t/** Per-attempt timeout (default 10 s). */\n\ttimeoutMs?: number\n\t/** Extra attempts for queries (default 1). */\n\tretries?: number\n\tfetchImpl?: typeof fetch\n}\n\nexport const TRPC_PATH = '/api/trpc'\nconst DEFAULT_TIMEOUT_MS = 10_000\nconst DEFAULT_RETRIES = 1\nconst RETRY_BASE_MS = 500\n\ninterface TrpcErrorShape {\n\tmessage?: string\n\tcode?: number\n\tdata?: {\n\t\tcode?: string\n\t\thttpStatus?: number\n\t\tcause?: { code?: string; retryAfterSec?: number }\n\t}\n}\n\ninterface TrpcEnvelope<T> {\n\tresult?: { data?: T }\n\terror?: TrpcErrorShape\n}\n\nconst RETRYABLE: ReadonlySet<ErrorCode> = new Set([\n\tERROR_CODES.NETWORK_ERROR,\n\tERROR_CODES.TIMEOUT,\n\tERROR_CODES.GATEWAY_UNAVAILABLE,\n])\n\n/** `PAY_*` cause codes, when the BFF forwards them, map 1:1. */\nconst CAUSE_TO_CODE: Record<string, ErrorCode> = {\n\t[PAY_ERRORS.RATE_LIMITED]: ERROR_CODES.RATE_LIMITED,\n\t[PAY_ERRORS.INVALID_KEY]: ERROR_CODES.INVALID_KEY,\n\t[PAY_ERRORS.SELLER_NOT_CONNECTED]: ERROR_CODES.SELLER_NOT_ACTIVE,\n\t[PAY_ERRORS.SELLER_NOT_ACTIVE]: ERROR_CODES.SELLER_NOT_ACTIVE,\n\t[PAY_ERRORS.AGREEMENT_REQUIRED]: ERROR_CODES.SELLER_NOT_ACTIVE,\n\t[PAY_ERRORS.OFFER_NOT_FOUND]: ERROR_CODES.OFFER_NOT_FOUND,\n\t[PAY_ERRORS.GATEWAY_UNAVAILABLE]: ERROR_CODES.GATEWAY_UNAVAILABLE,\n\t[PAY_ERRORS.WITHDRAWAL_WAIVER_REQUIRED]: ERROR_CODES.WITHDRAWAL_WAIVER_REQUIRED,\n}\n\nfunction parseRetryAfter(message: string): number | undefined {\n\tconst match = /retry in (\\d+)s/i.exec(message)\n\treturn match ? Number(match[1]) : undefined\n}\n\n/**\n * The BFF's error formatter does not forward `cause` for `pay.*` errors, so the\n * tRPC code + message is the primary signal; `data.cause.code` is honoured when\n * present so a future BFF that forwards it needs no SDK change.\n */\nexport function trpcErrorToPayError(error: TrpcErrorShape, httpStatus?: number): ExtenshiPayError {\n\tconst message = error.message ?? 'Request failed'\n\tconst trpcCode = error.data?.code ?? ''\n\tconst causeCode = error.data?.cause?.code\n\tconst retryAfterSec = error.data?.cause?.retryAfterSec ?? parseRetryAfter(message)\n\tconst options = { retryAfterSec, httpStatus: error.data?.httpStatus ?? httpStatus }\n\n\tconst mapped = causeCode ? CAUSE_TO_CODE[causeCode] : undefined\n\tif (mapped) return new ExtenshiPayError(mapped, message, options)\n\n\tswitch (trpcCode) {\n\t\tcase 'TOO_MANY_REQUESTS':\n\t\t\treturn new ExtenshiPayError(ERROR_CODES.RATE_LIMITED, message, options)\n\t\tcase 'NOT_FOUND':\n\t\t\tif (/publishable key/i.test(message))\n\t\t\t\treturn new ExtenshiPayError(ERROR_CODES.INVALID_KEY, message, options)\n\t\t\tif (/session/i.test(message))\n\t\t\t\treturn new ExtenshiPayError(ERROR_CODES.CHECKOUT_UNAVAILABLE, message, options)\n\t\t\treturn new ExtenshiPayError(ERROR_CODES.OFFER_NOT_FOUND, message, options)\n\t\tcase 'PRECONDITION_FAILED':\n\t\t\tif (/withdrawal/i.test(message))\n\t\t\t\treturn new ExtenshiPayError(ERROR_CODES.WITHDRAWAL_WAIVER_REQUIRED, message, options)\n\t\t\treturn new ExtenshiPayError(ERROR_CODES.SELLER_NOT_ACTIVE, message, options)\n\t\tcase 'BAD_REQUEST':\n\t\t\treturn new ExtenshiPayError(ERROR_CODES.INVALID_REQUEST, message, options)\n\t\tcase 'INTERNAL_SERVER_ERROR':\n\t\t\treturn new ExtenshiPayError(ERROR_CODES.GATEWAY_UNAVAILABLE, message, options)\n\t\tdefault:\n\t\t\treturn new ExtenshiPayError(ERROR_CODES.UNKNOWN, message, options)\n\t}\n}\n\nfunction sleep(ms: number): Promise<void> {\n\treturn new Promise((resolve) => setTimeout(resolve, ms))\n}\n\nexport class HttpTransport implements Transport {\n\tprivate readonly apiUrl: string\n\tprivate readonly timeoutMs: number\n\tprivate readonly retries: number\n\tprivate readonly fetchImpl: typeof fetch\n\n\tconstructor(options: HttpTransportOptions) {\n\t\tthis.apiUrl = options.apiUrl.replace(/\\/+$/, '')\n\t\tthis.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS\n\t\tthis.retries = options.retries ?? DEFAULT_RETRIES\n\t\tthis.fetchImpl = options.fetchImpl ?? ((input, init) => fetch(input, init))\n\t}\n\n\tasync call<T>(procedure: string, kind: ProcedureKind, input: Record<string, unknown>): Promise<T> {\n\t\tconst base = `${this.apiUrl}${TRPC_PATH}/${procedure}`\n\t\tconst url = kind === 'query' ? `${base}?input=${encodeURIComponent(JSON.stringify(input))}` : base\n\t\tconst attempts = kind === 'query' ? this.retries + 1 : 1\n\t\tlet lastError: ExtenshiPayError | null = null\n\t\tfor (let attempt = 0; attempt < attempts; attempt++) {\n\t\t\ttry {\n\t\t\t\treturn await this.request<T>(url, kind, input)\n\t\t\t} catch (error) {\n\t\t\t\tconst err = ExtenshiPayError.from(error)\n\t\t\t\tif (!RETRYABLE.has(err.code) || attempt === attempts - 1) throw err\n\t\t\t\tlastError = err\n\t\t\t\tlogger.debug(`${procedure} failed (${err.code}), retrying`)\n\t\t\t\tawait sleep(RETRY_BASE_MS * 2 ** attempt)\n\t\t\t}\n\t\t}\n\t\tthrow lastError ?? new ExtenshiPayError(ERROR_CODES.UNKNOWN, `${procedure} failed`)\n\t}\n\n\tprivate async request<T>(url: string, kind: ProcedureKind, input: Record<string, unknown>): Promise<T> {\n\t\tconst controller = typeof AbortController === 'function' ? new AbortController() : null\n\t\tconst timer = controller ? setTimeout(() => controller.abort(), this.timeoutMs) : null\n\t\tlet response: Response\n\t\ttry {\n\t\t\tresponse = await this.fetchImpl(url, {\n\t\t\t\tmethod: kind === 'query' ? 'GET' : 'POST',\n\t\t\t\theaders: kind === 'mutation' ? { 'Content-Type': 'application/json' } : undefined,\n\t\t\t\tbody: kind === 'mutation' ? JSON.stringify(input) : undefined,\n\t\t\t\tsignal: controller?.signal,\n\t\t\t\tcredentials: 'omit',\n\t\t\t})\n\t\t} catch (error) {\n\t\t\tif (controller?.signal.aborted) {\n\t\t\t\tthrow new ExtenshiPayError(ERROR_CODES.TIMEOUT, `Request timed out after ${this.timeoutMs}ms`)\n\t\t\t}\n\t\t\tthrow new ExtenshiPayError(ERROR_CODES.NETWORK_ERROR, 'Network request failed', { cause: error })\n\t\t} finally {\n\t\t\tif (timer !== null) clearTimeout(timer)\n\t\t}\n\n\t\tlet body: TrpcEnvelope<T> | null = null\n\t\ttry {\n\t\t\tbody = (await response.json()) as TrpcEnvelope<T>\n\t\t} catch {\n\t\t\tbody = null\n\t\t}\n\t\tif (body?.error) throw trpcErrorToPayError(body.error, response.status)\n\t\tif (!response.ok) {\n\t\t\tconst code = response.status >= 500 ? ERROR_CODES.GATEWAY_UNAVAILABLE : ERROR_CODES.INVALID_RESPONSE\n\t\t\tthrow new ExtenshiPayError(code, `HTTP ${response.status}`, { httpStatus: response.status })\n\t\t}\n\t\tif (!body?.result || !('data' in body.result)) {\n\t\t\tthrow new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Malformed response from the payment backend')\n\t\t}\n\t\treturn body.result.data as T\n\t}\n}\n","/**\n * Hosted checkout flow.\n *\n * `pay.createCheckout` returns a URL on the seller's provider; the SDK opens\n * it in a new tab (`chrome.tabs.create`, falling back to `window.open`) and\n * polls `pay.claimSession` every 2 s for up to 10 min — and immediately when\n * the extension regains focus — until the webhook has landed. A pending\n * session is persisted so a restarted service worker / reopened popup can\n * finish the claim on the next `initialize()`.\n */\n\nimport type { PayApi } from '../api/pay-api.js'\nimport type { StorageAdapter } from '../core/storage.js'\nimport type { PayCheckoutClaim, SignedEntitlement } from '../types/contract.js'\nimport type { CheckoutOptions, CheckoutResult, Entitlement } from '../types/entitlement.js'\nimport { ERROR_CODES, ExtenshiPayError } from '../types/errors.js'\nimport type { ExtenshiPayEvents } from '../types/events.js'\nimport { logger } from '../utils/logger.js'\n\nexport const CHECKOUT_POLL_INTERVAL_MS = 2_000\nexport const CHECKOUT_TIMEOUT_MS = 10 * 60 * 1000\nconst MAX_ERROR_BACKOFF_MS = 30_000\n/** How long after `expiresAt` a persisted session is still worth one claim (webhook lag). */\nconst PENDING_GRACE_MS = 60 * 60 * 1000\n\ninterface PendingCheckout {\n\tsessionId: string\n\tsku: string\n\texpiresAt: string\n}\n\ntype OpenUrl = (url: string) => void | Promise<void>\ntype Emit = <K extends keyof ExtenshiPayEvents>(event: K, payload: ExtenshiPayEvents[K]) => void\n\nexport interface CheckoutManagerOptions {\n\tapi: PayApi\n\tstorage: StorageAdapter\n\tpublishableKey: string\n\tlocale: string | null\n\tgetEndUserRef: () => Promise<string>\n\t/** Verifies + stores the envelope from a completed session. */\n\tonComplete: (envelope: SignedEntitlement) => Promise<Entitlement>\n\temit: Emit\n\topenUrl?: OpenUrl\n\tnow?: () => number\n}\n\ninterface TabsApi {\n\tcreate(properties: { url: string }): unknown\n}\n\ninterface FocusGlobals {\n\tchrome?: { tabs?: TabsApi; windows?: { onFocusChanged?: FocusEvent } }\n\tbrowser?: { tabs?: TabsApi }\n\topen?: (url: string, target: string, features: string) => unknown\n\taddEventListener?: (type: string, listener: () => void) => void\n\tremoveEventListener?: (type: string, listener: () => void) => void\n\tdocument?: Document\n}\n\ninterface FocusEvent {\n\taddListener(listener: (windowId: number) => void): void\n\tremoveListener(listener: (windowId: number) => void): void\n}\n\nexport async function openInNewTab(url: string): Promise<void> {\n\tconst g = globalThis as FocusGlobals\n\tconst tabs = g.chrome?.tabs ?? g.browser?.tabs\n\tif (tabs && typeof tabs.create === 'function') {\n\t\tconst result = tabs.create({ url })\n\t\tif (result && typeof (result as Promise<unknown>).then === 'function') await result\n\t\treturn\n\t}\n\tif (typeof g.open === 'function') {\n\t\tg.open(url, '_blank', 'noopener,noreferrer')\n\t\treturn\n\t}\n\tthrow new ExtenshiPayError(ERROR_CODES.CHECKOUT_UNAVAILABLE, 'Cannot open a checkout tab from this context')\n}\n\n/** Calls `onFocus` whenever the extension window/tab regains focus; returns a disposer. */\nfunction onFocusRegained(onFocus: () => void): () => void {\n\tconst g = globalThis as FocusGlobals\n\tconst disposers: Array<() => void> = []\n\tif (typeof g.addEventListener === 'function' && typeof g.removeEventListener === 'function') {\n\t\tg.addEventListener('focus', onFocus)\n\t\tdisposers.push(() => g.removeEventListener?.('focus', onFocus))\n\t}\n\tconst doc = g.document\n\tif (doc && typeof doc.addEventListener === 'function') {\n\t\tconst onVisible = () => {\n\t\t\tif (doc.visibilityState === 'visible') onFocus()\n\t\t}\n\t\tdoc.addEventListener('visibilitychange', onVisible)\n\t\tdisposers.push(() => doc.removeEventListener('visibilitychange', onVisible))\n\t}\n\tconst windows = g.chrome?.windows?.onFocusChanged\n\tif (windows && typeof windows.addListener === 'function') {\n\t\tconst onWindow = (windowId: number) => {\n\t\t\tif (windowId !== -1) onFocus()\n\t\t}\n\t\twindows.addListener(onWindow)\n\t\tdisposers.push(() => windows.removeListener(onWindow))\n\t}\n\treturn () => {\n\t\tfor (const dispose of disposers) dispose()\n\t}\n}\n\n/** A sleep that can be cut short by `wake()`. */\nfunction interruptibleSleep() {\n\tlet wake: (() => void) | null = null\n\treturn {\n\t\tsleep(ms: number): Promise<void> {\n\t\t\treturn new Promise<void>((resolve) => {\n\t\t\t\tconst timer = setTimeout(() => {\n\t\t\t\t\twake = null\n\t\t\t\t\tresolve()\n\t\t\t\t}, ms)\n\t\t\t\twake = () => {\n\t\t\t\t\tclearTimeout(timer)\n\t\t\t\t\twake = null\n\t\t\t\t\tresolve()\n\t\t\t\t}\n\t\t\t})\n\t\t},\n\t\twake(): void {\n\t\t\twake?.()\n\t\t},\n\t}\n}\n\nexport class CheckoutManager {\n\tprivate active: string | null = null\n\tprivate readonly now: () => number\n\n\tconstructor(private readonly options: CheckoutManagerOptions) {\n\t\tthis.now = options.now ?? (() => Date.now())\n\t}\n\n\tget pendingKey(): string {\n\t\treturn `extenshi-pay:${this.options.publishableKey}:pendingCheckout`\n\t}\n\n\tisActive(): boolean {\n\t\treturn this.active !== null\n\t}\n\n\tasync open(sku: string, options: CheckoutOptions = {}): Promise<CheckoutResult> {\n\t\tif (this.active) {\n\t\t\tthrow new ExtenshiPayError(ERROR_CODES.CHECKOUT_UNAVAILABLE, 'A checkout is already in progress')\n\t\t}\n\t\tconst endUserRef = await this.options.getEndUserRef()\n\t\tconst session = await this.options.api.createCheckout(\n\t\t\tsku,\n\t\t\tendUserRef,\n\t\t\toptions.locale ?? this.options.locale,\n\t\t\toptions.withdrawalWaiver,\n\t\t)\n\t\tthis.active = session.sessionId\n\t\ttry {\n\t\t\tconst pending: PendingCheckout = { sessionId: session.sessionId, sku, expiresAt: session.expiresAt }\n\t\t\tawait this.options.storage.set(this.pendingKey, pending)\n\t\t\tthis.options.emit('checkout:started', { sku, sessionId: session.sessionId, url: session.url })\n\t\t\tawait (options.openUrl ?? this.options.openUrl ?? openInNewTab)(session.url)\n\t\t\treturn await this.poll(sku, session.sessionId, endUserRef, options)\n\t\t} finally {\n\t\t\tthis.active = null\n\t\t}\n\t}\n\n\t/** Finishes a checkout that was started before a restart; null when there is nothing to resume. */\n\tasync resumePending(): Promise<CheckoutResult | null> {\n\t\tconst raw = (await this.options.storage.get(this.pendingKey)) as Partial<PendingCheckout> | undefined\n\t\tif (!raw || typeof raw.sessionId !== 'string' || typeof raw.sku !== 'string') return null\n\t\tconst expires = Date.parse(raw.expiresAt ?? '')\n\t\tif (!Number.isFinite(expires) || expires + PENDING_GRACE_MS < this.now()) {\n\t\t\tawait this.options.storage.remove(this.pendingKey)\n\t\t\treturn null\n\t\t}\n\t\tconst endUserRef = await this.options.getEndUserRef()\n\t\tlet claim: PayCheckoutClaim\n\t\ttry {\n\t\t\tclaim = await this.options.api.claimSession(raw.sessionId, endUserRef)\n\t\t} catch (error) {\n\t\t\tlogger.debug('could not resume pending checkout', error)\n\t\t\treturn null\n\t\t}\n\t\treturn this.settle(claim, raw.sku, raw.sessionId)\n\t}\n\n\tprivate async poll(\n\t\tsku: string,\n\t\tsessionId: string,\n\t\tendUserRef: string,\n\t\toptions: CheckoutOptions,\n\t): Promise<CheckoutResult> {\n\t\tconst interval = options.pollIntervalMs ?? CHECKOUT_POLL_INTERVAL_MS\n\t\tconst deadline = this.now() + (options.timeoutMs ?? CHECKOUT_TIMEOUT_MS)\n\t\tconst sleeper = interruptibleSleep()\n\t\tconst stopFocus = onFocusRegained(() => sleeper.wake())\n\t\tlet delay = interval\n\t\tlet errorBackoff = 0\n\t\ttry {\n\t\t\tfor (;;) {\n\t\t\t\tawait sleeper.sleep(delay)\n\t\t\t\tif (this.now() >= deadline) return { state: 'timeout', sku, sessionId }\n\t\t\t\tlet claim: PayCheckoutClaim\n\t\t\t\ttry {\n\t\t\t\t\tclaim = await this.options.api.claimSession(sessionId, endUserRef)\n\t\t\t\t} catch (error) {\n\t\t\t\t\tconst err = ExtenshiPayError.from(error)\n\t\t\t\t\tif (err.code === ERROR_CODES.RATE_LIMITED) {\n\t\t\t\t\t\tdelay = (err.retryAfterSec ?? 5) * 1000\n\t\t\t\t\t} else if (\n\t\t\t\t\t\terr.code === ERROR_CODES.NETWORK_ERROR ||\n\t\t\t\t\t\terr.code === ERROR_CODES.TIMEOUT ||\n\t\t\t\t\t\terr.code === ERROR_CODES.GATEWAY_UNAVAILABLE\n\t\t\t\t\t) {\n\t\t\t\t\t\terrorBackoff = Math.min(errorBackoff ? errorBackoff * 2 : interval, MAX_ERROR_BACKOFF_MS)\n\t\t\t\t\t\tdelay = errorBackoff\n\t\t\t\t\t} else {\n\t\t\t\t\t\tawait this.options.storage.remove(this.pendingKey)\n\t\t\t\t\t\tthrow err\n\t\t\t\t\t}\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\terrorBackoff = 0\n\t\t\t\tdelay = interval\n\t\t\t\tconst result = await this.settle(claim, sku, sessionId)\n\t\t\t\tif (result) return result\n\t\t\t}\n\t\t} finally {\n\t\t\tstopFocus()\n\t\t}\n\t}\n\n\tprivate async settle(\n\t\tclaim: PayCheckoutClaim,\n\t\tsku: string,\n\t\tsessionId: string,\n\t): Promise<CheckoutResult | null> {\n\t\tswitch (claim.state) {\n\t\t\tcase 'pending':\n\t\t\t\treturn null\n\t\t\tcase 'complete': {\n\t\t\t\tconst entitlement = await this.options.onComplete(claim.entitlement)\n\t\t\t\tawait this.options.storage.remove(this.pendingKey)\n\t\t\t\tthis.options.emit('checkout:completed', { sku, sessionId, entitlement })\n\t\t\t\treturn { state: 'complete', sku, sessionId, entitlement }\n\t\t\t}\n\t\t\tcase 'canceled':\n\t\t\t\tawait this.options.storage.remove(this.pendingKey)\n\t\t\t\tthis.options.emit('checkout:canceled', { sku, sessionId })\n\t\t\t\treturn { state: 'canceled', sku, sessionId }\n\t\t\tcase 'expired':\n\t\t\t\tawait this.options.storage.remove(this.pendingKey)\n\t\t\t\tthis.options.emit('checkout:expired', { sku, sessionId })\n\t\t\t\treturn { state: 'expired', sku, sessionId }\n\t\t\tdefault:\n\t\t\t\tthrow new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Unknown checkout claim state')\n\t\t}\n\t}\n}\n","/**\n * Cloud copy of the extension's settings (`@extenshi/storage`). Pay owns the\n * token: only a verified restore claim issues it; this module keeps it in the\n * SDK's storage (`storage.local`) and revokes it. `@extenshi/storage` reads it\n * through `cloudBackupToken()`. The token is never logged and never answered to\n * a content script: route those calls to the background.\n */\n\nimport type { StorageAdapter } from '../core/storage.js'\nimport { type PayStorageGrant, STORAGE_TOKEN_RE } from '../types/contract.js'\nimport type { CloudBackupState } from '../types/entitlement.js'\nimport { ERROR_CODES, ExtenshiPayError } from '../types/errors.js'\nimport { logger } from '../utils/logger.js'\n\nconst REQUEST_TIMEOUT_MS = 10_000\n\nexport interface CloudBackupOptions {\n\tstorage: StorageAdapter\n\tpublishableKey: string\n\tapiUrl: string\n\tfetch?: typeof fetch\n\t/** Mock mode: forget the token locally, never call the network. */\n\tmock?: boolean\n}\n\n/** True in a content script, where the token must not be handed out. */\nfunction inContentScript(): boolean {\n\tconst g = globalThis as {\n\t\tchrome?: { runtime?: { id?: string }; tabs?: unknown }\n\t\tbrowser?: { runtime?: { id?: string }; tabs?: unknown }\n\t}\n\treturn !!(g.chrome?.runtime?.id || g.browser?.runtime?.id) && !(g.chrome?.tabs || g.browser?.tabs)\n}\n\nexport class CloudBackup {\n\tprivate readonly fetchImpl: typeof fetch\n\n\tconstructor(private readonly options: CloudBackupOptions) {\n\t\tthis.fetchImpl = options.fetch ?? ((input, init) => fetch(input, init))\n\t}\n\n\tget storageKey(): string {\n\t\treturn `extenshi-pay:${this.options.publishableKey}:storageToken`\n\t}\n\n\t/** Stores or clears the token from a verified claim. Never throws: the licence is already restored. */\n\tasync accept(grant: PayStorageGrant | undefined): Promise<CloudBackupState | undefined> {\n\t\tif (!grant || typeof grant !== 'object') return undefined\n\t\ttry {\n\t\t\tif (grant.state === 'granted') {\n\t\t\t\tif (typeof grant.token !== 'string' || !STORAGE_TOKEN_RE.test(grant.token)) return undefined\n\t\t\t\tawait this.options.storage.set(this.storageKey, grant.token)\n\t\t\t\treturn 'on'\n\t\t\t}\n\t\t\tif (grant.state === 'unavailable') {\n\t\t\t\tawait this.options.storage.remove(this.storageKey)\n\t\t\t\treturn grant.reason === 'LICENSE_REQUIRED' ? 'license_required' : 'no_consent'\n\t\t\t}\n\t\t} catch {\n\t\t\tlogger.warn('cloud backup state could not be saved')\n\t\t}\n\t\treturn undefined\n\t}\n\n\tasync token(): Promise<string | null> {\n\t\tthis.assertTrustedContext()\n\t\tconst value = await this.options.storage.get(this.storageKey)\n\t\treturn typeof value === 'string' && STORAGE_TOKEN_RE.test(value) ? value : null\n\t}\n\n\t/** Revokes this installation's token. A token the server no longer knows (401) is forgotten too. */\n\tasync disable(): Promise<void> {\n\t\tconst token = await this.token()\n\t\tif (!token) return\n\t\tif (!this.options.mock) {\n\t\t\tconst status = await this.request('/v1/storage/grant', token)\n\t\t\tif (status !== 401) this.throwUnlessOk(status)\n\t\t}\n\t\tawait this.options.storage.remove(this.storageKey)\n\t}\n\n\t/** Deletes the buyer's cloud copy and turns the backup off on every device. */\n\tasync delete(): Promise<void> {\n\t\tconst token = await this.token()\n\t\tif (!token)\n\t\t\tthrow new ExtenshiPayError(\n\t\t\t\tERROR_CODES.INVALID_REQUEST,\n\t\t\t\t'Cloud backup is off on this installation; turn it on to delete the cloud copy',\n\t\t\t)\n\t\tif (!this.options.mock) {\n\t\t\tconst status = await this.request('/v1/storage/data', token)\n\t\t\tif (status === 401) {\n\t\t\t\t// The server no longer accepts this token, so it is useless here; the copy was not deleted.\n\t\t\t\tawait this.options.storage.remove(this.storageKey)\n\t\t\t\tthrow new ExtenshiPayError(\n\t\t\t\t\tERROR_CODES.INVALID_REQUEST,\n\t\t\t\t\t'Cloud backup is off on the server; turn it on again to delete the cloud copy',\n\t\t\t\t\t{ httpStatus: 401 },\n\t\t\t\t)\n\t\t\t}\n\t\t\tthis.throwUnlessOk(status)\n\t\t}\n\t\tawait this.options.storage.remove(this.storageKey)\n\t}\n\n\tprivate assertTrustedContext(): void {\n\t\tif (inContentScript())\n\t\t\tthrow new ExtenshiPayError(\n\t\t\t\tERROR_CODES.INVALID_REQUEST,\n\t\t\t\t'Use cloud backup from an extension page or background context',\n\t\t\t)\n\t}\n\n\tprivate throwUnlessOk(status: number): void {\n\t\tif (status >= 200 && status < 300) return\n\t\tif (status === 429)\n\t\t\tthrow new ExtenshiPayError(ERROR_CODES.RATE_LIMITED, 'Too many requests', { httpStatus: status })\n\t\tif (status >= 500)\n\t\t\tthrow new ExtenshiPayError(ERROR_CODES.GATEWAY_UNAVAILABLE, `HTTP ${status}`, { httpStatus: status })\n\t\tthrow new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, `HTTP ${status}`, { httpStatus: status })\n\t}\n\n\tprivate async request(path: string, token: string): Promise<number> {\n\t\tconst controller = typeof AbortController === 'function' ? new AbortController() : null\n\t\tconst timer = controller ? setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS) : null\n\t\ttry {\n\t\t\tconst response = await this.fetchImpl(`${this.options.apiUrl}${path}`, {\n\t\t\t\tmethod: 'DELETE',\n\t\t\t\theaders: { Authorization: `Bearer ${token}` },\n\t\t\t\tcredentials: 'omit',\n\t\t\t\tsignal: controller?.signal,\n\t\t\t})\n\t\t\treturn response.status\n\t\t} catch (error) {\n\t\t\tif (controller?.signal.aborted)\n\t\t\t\tthrow new ExtenshiPayError(ERROR_CODES.TIMEOUT, `Request timed out after ${REQUEST_TIMEOUT_MS}ms`)\n\t\t\tthrow new ExtenshiPayError(ERROR_CODES.NETWORK_ERROR, 'Network request failed', { cause: error })\n\t\t} finally {\n\t\t\tif (timer !== null) clearTimeout(timer)\n\t\t}\n\t}\n}\n","/** Pure helpers over the entitlement projection. Features come from the items' `features[]`. */\n\nimport type { PayEntitlementItem } from '../types/contract.js'\nimport type { Entitlement } from '../types/entitlement.js'\n\nconst LIVE_STATUSES: ReadonlySet<string> = new Set(['active', 'grace'])\n\nexport function isLive(item: PayEntitlementItem): boolean {\n\treturn LIVE_STATUSES.has(item.status)\n}\n\n/** An item past its `expiresAt` reads as expired without a network round-trip. */\nexport function applyLocalExpiry(\n\titems: PayEntitlementItem[],\n\tnow: number = Date.now(),\n): PayEntitlementItem[] {\n\treturn items.map((item) => {\n\t\tif (!isLive(item) || !item.expiresAt) return item\n\t\tconst expires = Date.parse(item.expiresAt)\n\t\treturn Number.isFinite(expires) && expires <= now ? { ...item, status: 'expired' } : item\n\t})\n}\n\nexport function collectFeatures(items: PayEntitlementItem[]): string[] {\n\tconst features = new Set<string>()\n\tfor (const item of items) {\n\t\tif (!isLive(item)) continue\n\t\tfor (const feature of item.features) features.add(feature)\n\t}\n\treturn [...features]\n}\n\nexport function isEntitled(entitlement: Entitlement, sku?: string): boolean {\n\treturn (\n\t\t!entitlement.requiresOnlineCheck &&\n\t\tentitlement.items.some((item) => isLive(item) && (sku === undefined || item.sku === sku))\n\t)\n}\n\nexport function hasFeature(entitlement: Entitlement, feature: string): boolean {\n\treturn entitlement.features.includes(feature)\n}\n\nexport function checkFeatures(entitlement: Entitlement, features: string[]): Record<string, boolean> {\n\tconst result: Record<string, boolean> = {}\n\tfor (const feature of features) result[feature] = hasFeature(entitlement, feature)\n\treturn result\n}\n\nexport const EMPTY_ENTITLEMENT: Entitlement = Object.freeze({\n\titems: [],\n\tfeatures: [],\n\tverified: false,\n\tissuedAt: null,\n\tfetchedAt: null,\n\tsource: 'none',\n\trequiresOnlineCheck: false,\n\tofflineUntil: null,\n}) as Entitlement\n\n// Frozen empty arrays prevent consumers from changing the shared denied state.\nObject.freeze(EMPTY_ENTITLEMENT.items)\nObject.freeze(EMPTY_ENTITLEMENT.features)\n","/**\n * Ed25519 verification of the entitlement projection.\n *\n * Tamper resistance, not DRM. Callers must deny access for both invalid and\n * unverified envelopes outside explicit mocks.\n *\n * Which keys are trusted, in order (`PublicKeySource`, built in core/extenshi-pay.ts):\n * 1. the key the server returned over HTTPS in this session;\n * 2. the bundled `entitlementPublicKey`, when the developer configured one. It pins\n * verification without a round-trip: a key read from extension storage is then never used;\n * 3. without a bundled key, the server key saved in `storage.local` next to the\n * license cache, so a restart with no network can still verify the cache.\n * When none of them verifies an envelope the server is asked for its current key once\n * (a rotated key), and that answer decides.\n */\n\nimport { canonicalJson, type SignedEntitlement } from '../types/contract.js'\n\nexport type SignatureVerdict = 'valid' | 'invalid' | 'unverified'\n\nexport function base64ToBytes(base64: string): Uint8Array<ArrayBuffer> {\n\tconst binary = atob(base64)\n\tconst bytes = new Uint8Array(binary.length)\n\tfor (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i)\n\treturn bytes\n}\n\nexport async function verifyEntitlementSignature(\n\tenvelope: SignedEntitlement,\n\tpublicKeyBase64: string | null,\n): Promise<SignatureVerdict> {\n\tif (!envelope.signature || envelope.alg !== 'ed25519') return 'invalid'\n\tif (!publicKeyBase64) return 'unverified'\n\tconst subtle = (globalThis as { crypto?: Crypto }).crypto?.subtle\n\tif (!subtle) return 'unverified'\n\n\tlet key: CryptoKey\n\ttry {\n\t\tkey = await subtle.importKey('raw', base64ToBytes(publicKeyBase64), { name: 'Ed25519' }, false, [\n\t\t\t'verify',\n\t\t])\n\t} catch {\n\t\treturn 'unverified'\n\t}\n\n\ttry {\n\t\tconst data = new TextEncoder().encode(canonicalJson(envelope.payload))\n\t\tconst ok = await subtle.verify('Ed25519', key, base64ToBytes(envelope.signature), data)\n\t\treturn ok ? 'valid' : 'invalid'\n\t} catch {\n\t\treturn 'invalid'\n\t}\n}\n\nexport const PUBLIC_KEY_RE = /^[A-Za-z0-9+/]{43}=$/\n\nexport interface PublicKeySource {\n\t/** Keys trusted without a round-trip, in the order above. */\n\tknown(): Promise<string[]>\n\t/** The server's current key, fetched now; null when the server signs nothing. Rejects when unreachable. */\n\tfetchCurrent(): Promise<string | null>\n}\n\nexport interface KeyedVerdict {\n\tverdict: SignatureVerdict\n\t/** The key that verified the envelope; null unless `verdict` is `valid`. */\n\tkey: string | null\n}\n\n/**\n * `invalid` only when the server's current key was checked too (or the envelope carries no\n * signature at all). A mismatch against known keys while the server is unreachable is\n * `unverified`: it may be a rotated key, and no paid access is granted either way.\n */\nexport async function verifyWithKeys(\n\tenvelope: SignedEntitlement,\n\tsource: PublicKeySource,\n): Promise<KeyedVerdict> {\n\tif (!envelope.signature || envelope.alg !== 'ed25519') return { verdict: 'invalid', key: null }\n\tlet known: string[] = []\n\ttry {\n\t\tknown = await source.known()\n\t} catch {\n\t\tknown = []\n\t}\n\tlet mismatch = false\n\tfor (const key of known) {\n\t\tconst verdict = await verifyEntitlementSignature(envelope, key)\n\t\tif (verdict === 'valid') return { verdict, key }\n\t\tif (verdict === 'invalid') mismatch = true\n\t}\n\tlet current: string | null\n\ttry {\n\t\tcurrent = await source.fetchCurrent()\n\t} catch {\n\t\treturn { verdict: 'unverified', key: null }\n\t}\n\tif (current && !known.includes(current)) {\n\t\tconst verdict = await verifyEntitlementSignature(envelope, current)\n\t\treturn { verdict, key: verdict === 'valid' ? current : null }\n\t}\n\treturn { verdict: mismatch ? 'invalid' : 'unverified', key: null }\n}\n","/**\n * The free trial an application configures on the server (`trialDays`).\n *\n * The server starts one clock per installation at its first license read and\n * signs `{ startedAt, endsAt }` into the entitlement, so the trial comes from\n * the verified license like paid access does: no start date in extension\n * storage, nothing a device clock or a storage edit can move. Offline, the\n * cached license answers for up to 48 hours.\n *\n * `trial:ending` / `trial:ended` fire once per installation and trial (the\n * marker is kept in the SDK's storage), and not while the user has paid\n * access. Render state from `getTrial()`; the events are one-time notices.\n */\n\nimport type { StorageAdapter } from '../core/storage.js'\nimport type { PayTrial } from '../types/contract.js'\nimport type { TrialState } from '../types/entitlement.js'\nimport { logger } from '../utils/logger.js'\n\nexport const DAY_MS = 24 * 60 * 60 * 1000\n/** Re-check at least daily: long timers are clamped by browsers and lost when a service worker sleeps. */\nconst MAX_TIMER_MS = DAY_MS\n\nexport interface TrialClock {\n\t/** Device time. */\n\tnow: number\n\t/** The signed issue time of the license; a floor for `now`. */\n\tissuedAt: number\n\t/** Whether the license was checked recently enough to grant access (48 h, as for paid access). */\n\tchecked: boolean\n}\n\n/** The trial as of `clock`, or null when the license carries none (or a malformed one). */\nexport function trialState(trial: PayTrial | undefined, clock: TrialClock): TrialState | null {\n\tif (!trial) return null\n\tconst startedAt = Date.parse(trial.startedAt)\n\tconst endsAt = Date.parse(trial.endsAt)\n\tif (!Number.isFinite(startedAt) || !Number.isFinite(endsAt)) return null\n\t// The server's signed time is a floor: a clock turned back cannot reopen an ended trial.\n\tconst now = Number.isFinite(clock.issuedAt) ? Math.max(clock.now, clock.issuedAt) : clock.now\n\tconst left = endsAt - now\n\treturn {\n\t\tactive: left > 0 && clock.checked,\n\t\tstartedAt: trial.startedAt,\n\t\tendsAt: trial.endsAt,\n\t\tdaysLeft: left > 0 ? Math.ceil(left / DAY_MS) : 0,\n\t\trequiresOnlineCheck: left > 0 && !clock.checked,\n\t}\n}\n\n/** The feedback form address with `src=trial_end`; null unless it is a plain HTTPS URL. No installation id is added. */\nexport function trialFeedbackUrl(raw: string | undefined): string | null {\n\tif (!raw) return null\n\tlet url: URL\n\ttry {\n\t\turl = new URL(raw)\n\t} catch {\n\t\treturn null\n\t}\n\tif (url.protocol !== 'https:' || url.username || url.password) return null\n\turl.searchParams.set('src', 'trial_end')\n\treturn url.toString()\n}\n\nexport type TrialEvent = 'trial:ending' | 'trial:ended'\n\nexport interface TrialNotifierOptions {\n\tstorage: StorageAdapter\n\tstorageKey: string\n\t/** `trial:ending` fires this many days before the end; 0 never. */\n\tendingDays: number\n\tgetTrial: () => TrialState | null\n\thasPaidAccess: () => boolean\n\temit: (event: TrialEvent, trial: TrialState) => void\n\tnow: () => number\n}\n\n/** Which trial each event was last sent for, as `startedAt|endsAt`. */\ninterface SentRecord {\n\tending?: string\n\tended?: string\n}\n\nexport class TrialNotifier {\n\tprivate timer: ReturnType<typeof setTimeout> | null = null\n\tprivate running = false\n\tprivate pending: Promise<void> = Promise.resolve()\n\n\tconstructor(private readonly options: TrialNotifierOptions) {}\n\n\tstart(): void {\n\t\tthis.running = true\n\t\tvoid this.evaluate()\n\t}\n\n\tstop(): void {\n\t\tthis.running = false\n\t\tthis.clearTimer()\n\t}\n\n\t/** Checks the held license; serialized, so two refreshes never send one event twice. */\n\tevaluate(): Promise<void> {\n\t\tthis.pending = this.pending.then(() => this.check()).catch((error) => logger.debug('trial check', error))\n\t\treturn this.pending\n\t}\n\n\tprivate async check(): Promise<void> {\n\t\tif (!this.running) return\n\t\tthis.clearTimer()\n\t\tconst trial = this.options.getTrial()\n\t\tif (!trial) return\n\t\tconst now = this.options.now()\n\t\tconst endsAt = Date.parse(trial.endsAt)\n\t\tconst endingAt = endsAt - this.options.endingDays * DAY_MS\n\t\tconst event: TrialEvent | null =\n\t\t\ttrial.daysLeft === 0\n\t\t\t\t? 'trial:ended'\n\t\t\t\t: trial.active && this.options.endingDays > 0 && now >= endingAt\n\t\t\t\t\t? 'trial:ending'\n\t\t\t\t\t: null\n\t\tif (event && !this.options.hasPaidAccess()) await this.send(event, trial)\n\t\tif (!this.running || trial.daysLeft === 0) return\n\t\tconst next = [endingAt, endsAt].find((at) => at > now) ?? endsAt\n\t\tthis.timer = setTimeout(\n\t\t\t() => {\n\t\t\t\tthis.timer = null\n\t\t\t\tvoid this.evaluate()\n\t\t\t},\n\t\t\tMath.max(1000, Math.min(next - now, MAX_TIMER_MS)),\n\t\t)\n\t}\n\n\tprivate async send(event: TrialEvent, trial: TrialState): Promise<void> {\n\t\tconst id = `${trial.startedAt}|${trial.endsAt}`\n\t\tconst field = event === 'trial:ended' ? 'ended' : 'ending'\n\t\tconst stored = (await this.options.storage.get(this.options.storageKey)) as SentRecord | undefined\n\t\tconst sent: SentRecord = stored && typeof stored === 'object' ? stored : {}\n\t\tif (sent[field] === id || !this.running) return\n\t\tawait this.options.storage.set(this.options.storageKey, { ...sent, [field]: id })\n\t\tthis.options.emit(event, trial)\n\t}\n\n\tprivate clearTimer(): void {\n\t\tif (this.timer !== null) clearTimeout(this.timer)\n\t\tthis.timer = null\n\t}\n}\n","/**\n * Entitlement cache + refresh.\n *\n * The cached envelope is a cache OF the server projection, never a second\n * source of truth: it is verified when stored and re-verified on load (once\n * the project's public key is known), served without a round-trip while the\n * TTL holds, served after signed issuance for the signed `offlineSeconds` (48 hours when absent) when the network is down, and expired\n * locally by `expiresAt`. Background refresh polls at most every 15 minutes\n * and backs off exponentially on errors.\n */\n\nimport type { PayApi } from '../api/pay-api.js'\nimport type { StorageAdapter } from '../core/storage.js'\nimport { canonicalJson, PAY_REGIONAL_ACCESS_SKU, type SignedEntitlement } from '../types/contract.js'\nimport type { ClockSkew, Entitlement, EntitlementSource, TrialState } from '../types/entitlement.js'\nimport { ERROR_CODES, ExtenshiPayError } from '../types/errors.js'\nimport { logger } from '../utils/logger.js'\nimport { applyLocalExpiry, collectFeatures, EMPTY_ENTITLEMENT } from './features.js'\nimport { type PublicKeySource, verifyWithKeys } from './signature.js'\nimport { trialState } from './trial.js'\n\nexport const MIN_REFRESH_INTERVAL_MS = 15 * 60 * 1000\nexport const MAX_REFRESH_BACKOFF_MS = 6 * 60 * 60 * 1000\n/** Offline allowance when the signed license names none (older servers and caches). */\nexport const MAX_OFFLINE_AGE_MS = 48 * 60 * 60 * 1000\n/** Ceiling for a signed `offlineSeconds`. */\nexport const MAX_SIGNED_OFFLINE_AGE_MS = 366 * 24 * 60 * 60 * 1000\n/** `setTimeout` fires at once past this delay. */\nconst MAX_TIMER_MS = 2 ** 31 - 1\n// Allow small server/client clock skew without granting more than the signed age limit.\nexport const MAX_CLOCK_SKEW_MS = 5 * 60 * 1000\nconst CACHE_VERSION = 1\n\ninterface CacheRecord {\n\tv: typeof CACHE_VERSION\n\tenvelope: SignedEntitlement\n\tfetchedAt: number\n}\n\ninterface Held {\n\tenvelope: SignedEntitlement\n\tfetchedAt: number\n\tverified: boolean\n\t/** The key that verified the envelope; null while unverified and in mock mode. */\n\tkey: string | null\n\tsource: EntitlementSource\n}\n\nexport interface EntitlementManagerOptions {\n\tapi: PayApi\n\tstorage: StorageAdapter\n\tpublishableKey: string\n\tcacheTtlMs: number\n\tsource?: EntitlementSource\n\tgetEndUserRef: () => Promise<string>\n\t/** The trusted Ed25519 keys, in order, and how to ask the server for its current one. */\n\tkeys: PublicKeySource\n\tonChange?: (entitlement: Entitlement) => void\n\t/** After every accepted envelope, changed or not (the trial is not part of `onChange`). */\n\tonAccepted?: () => void\n\t/** The synced trial start to send with a refresh; null when there is none. */\n\tgetTrialStartHint?: () => Promise<string | null>\n\tonError?: (error: ExtenshiPayError) => void\n\tnow?: () => number\n}\n\nfunction isEnvelope(value: unknown): value is SignedEntitlement {\n\tif (!value || typeof value !== 'object') return false\n\tconst env = value as SignedEntitlement\n\treturn (\n\t\t!!env.payload &&\n\t\ttypeof env.payload === 'object' &&\n\t\ttypeof env.payload.endUserRef === 'string' &&\n\t\tArray.isArray(env.payload.entitlements) &&\n\t\ttypeof env.payload.issuedAt === 'string'\n\t)\n}\n\nexport class EntitlementManager {\n\tprivate held: Held | null = null\n\tprivate inflight: Promise<Entitlement> | null = null\n\t/** Device clock against the server's at the last license check; null within 5 minutes. */\n\tprivate clockSkew: ClockSkew | null = null\n\tprivate timer: ReturnType<typeof setTimeout> | null = null\n\tprivate refreshGeneration = 0\n\tprivate deadlineTimer: ReturnType<typeof setTimeout> | null = null\n\tprivate refreshIntervalMs = MIN_REFRESH_INTERVAL_MS\n\tprivate backoffMs = 0\n\tprivate autoRefresh = false\n\tprivate readonly online = () => {\n\t\tvoid this.get({ force: true }).then(() => this.notifyIfChanged())\n\t}\n\t// Starts at the empty projection: a first load that finds nothing is not a\n\t// change, a first load that finds a paid entitlement is.\n\tprivate lastFingerprint: string | null = canonicalJson({ items: [], requiresOnlineCheck: false })\n\tprivate readonly now: () => number\n\tprivate readonly source: EntitlementSource\n\n\tconstructor(private readonly options: EntitlementManagerOptions) {\n\t\tthis.now = options.now ?? (() => Date.now())\n\t\tthis.source = options.source ?? 'network'\n\t}\n\n\tget storageKey(): string {\n\t\t// Keep the real cache key stable for upgrades. Simulated grants must\n\t\t// neither consume nor overwrite that cache when developers switch modes.\n\t\treturn `extenshi-pay:${this.options.publishableKey}:entitlement${this.source === 'mock' ? ':mock' : ''}`\n\t}\n\n\t/** Loads the persisted envelope (unverified until `reverify()`); no network. */\n\tasync load(): Promise<Entitlement | null> {\n\t\tconst raw = await this.options.storage.get(this.storageKey)\n\t\tconst record = raw as Partial<CacheRecord> | undefined\n\t\tif (\n\t\t\t!record ||\n\t\t\trecord.v !== CACHE_VERSION ||\n\t\t\t!isEnvelope(record.envelope) ||\n\t\t\ttypeof record.fetchedAt !== 'number' ||\n\t\t\t!Number.isFinite(record.fetchedAt)\n\t\t) {\n\t\t\treturn null\n\t\t}\n\t\tconst endUserRef = await this.options.getEndUserRef()\n\t\tif (\n\t\t\trecord.envelope.payload.endUserRef !== endUserRef ||\n\t\t\t(this.source !== 'mock' && record.envelope.payload.publishableKey !== this.options.publishableKey)\n\t\t) {\n\t\t\tawait this.options.storage.remove(this.storageKey)\n\t\t\treturn null\n\t\t}\n\t\tthis.held = {\n\t\t\tenvelope: JSON.parse(JSON.stringify(record.envelope)),\n\t\t\tfetchedAt: record.fetchedAt,\n\t\t\tverified: false,\n\t\t\tkey: null,\n\t\t\tsource: this.source === 'mock' ? 'mock' : 'cache',\n\t\t}\n\t\tthis.measureClockSkew(record.fetchedAt, Date.parse(record.envelope.payload.issuedAt))\n\t\tthis.lastFingerprint = this.fingerprint()\n\t\treturn this.snapshot()\n\t}\n\n\t/** Re-checks the loaded envelope against the project's key; discards it when the signature is invalid. */\n\tasync reverify(): Promise<void> {\n\t\tif (!this.held) return\n\t\tif (this.source === 'mock') return\n\t\tconst held = this.held\n\t\tconst { verdict, key } = await verifyWithKeys(held.envelope, this.options.keys)\n\t\tif (held !== this.held) return\n\t\tif (verdict === 'invalid') {\n\t\t\tlogger.warn('cached entitlement failed signature verification; discarding')\n\t\t\tawait this.discard()\n\t\t\tthrow new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Cached entitlement signature is invalid')\n\t\t}\n\t\theld.verified = verdict === 'valid'\n\t\theld.key = key\n\t\tif (!held.verified) {\n\t\t\tthrow new ExtenshiPayError(\n\t\t\t\tERROR_CODES.VERIFICATION_UNAVAILABLE,\n\t\t\t\t'Entitlement verification requires a trusted key and Ed25519 WebCrypto support',\n\t\t\t)\n\t\t}\n\t\tthis.scheduleDeadline()\n\t}\n\n\t/** The key the held license was verified with; null when there is none or it is unverified. */\n\tget verifiedKey(): string | null {\n\t\treturn this.held?.verified ? this.held.key : null\n\t}\n\n\tgetCached(): Entitlement | null {\n\t\treturn this.held ? this.snapshot() : null\n\t}\n\n\t/** The server trial in the held license; null without one, or while the license is unverified. */\n\tgetTrial(): TrialState | null {\n\t\tconst held = this.held\n\t\tif (!held || (this.source !== 'mock' && !held.verified)) return null\n\t\tconst now = this.now()\n\t\tconst issuedAt = Date.parse(held.envelope.payload.issuedAt)\n\t\treturn trialState(held.envelope.payload.trial, {\n\t\t\tnow,\n\t\t\tissuedAt,\n\t\t\t// The same offline rule as paid access (snapshot): the allowance from the signed issue, no clock turned back.\n\t\t\tchecked:\n\t\t\t\tthis.source === 'mock' ||\n\t\t\t\t(now >= held.fetchedAt && now < this.offlineDeadline() && now + MAX_CLOCK_SKEW_MS >= issuedAt),\n\t\t})\n\t}\n\n\tisFresh(): boolean {\n\t\treturn (\n\t\t\tthis.held !== null &&\n\t\t\t(this.source === 'mock' || (this.held.verified && !this.snapshot().requiresOnlineCheck)) &&\n\t\t\tthis.now() >= this.held.fetchedAt &&\n\t\t\tthis.now() - this.held.fetchedAt < Math.min(this.options.cacheTtlMs, this.offlineAgeMs())\n\t\t)\n\t}\n\n\tasync get(options: { force?: boolean } = {}): Promise<Entitlement> {\n\t\tif (!options.force && this.isFresh()) return this.snapshot()\n\t\ttry {\n\t\t\treturn await this.refresh()\n\t\t} catch (error) {\n\t\t\tconst err = ExtenshiPayError.from(error)\n\t\t\tthis.options.onError?.(err)\n\t\t\tif (this.held) {\n\t\t\t\tlogger.debug('serving cached entitlement after refresh failure', err.code)\n\t\t\t\treturn this.snapshot()\n\t\t\t}\n\t\t\treturn this.snapshot()\n\t\t}\n\t}\n\n\t/** Fetches the projection from the backend, verifies and stores it. */\n\trefresh(): Promise<Entitlement> {\n\t\tif (!this.inflight) {\n\t\t\tthis.inflight = (async () => {\n\t\t\t\tconst endUserRef = await this.options.getEndUserRef()\n\t\t\t\tconst hint = this.options.getTrialStartHint ? await this.options.getTrialStartHint() : null\n\t\t\t\tconst envelope = await this.options.api.getEntitlement(endUserRef, hint)\n\t\t\t\treturn this.accept(envelope, this.source)\n\t\t\t})().finally(() => {\n\t\t\t\tthis.inflight = null\n\t\t\t})\n\t\t}\n\t\treturn this.inflight\n\t}\n\n\t/** Verifies and stores an envelope obtained elsewhere (e.g. from `claimSession`). */\n\tasync accept(envelope: SignedEntitlement, source: EntitlementSource = this.source): Promise<Entitlement> {\n\t\tif (!isEnvelope(envelope)) {\n\t\t\tthrow new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Malformed entitlement envelope')\n\t\t}\n\t\t// Detach from callers/storage: later mutation must not alter verified state.\n\t\tenvelope = JSON.parse(JSON.stringify(envelope)) as SignedEntitlement\n\t\tif (this.source !== 'mock' && envelope.payload.publishableKey !== this.options.publishableKey) {\n\t\t\tthrow new ExtenshiPayError(\n\t\t\t\tERROR_CODES.INVALID_RESPONSE,\n\t\t\t\t'Entitlement belongs to a different application or lacks a signed application scope',\n\t\t\t)\n\t\t}\n\t\tconst endUserRef = await this.options.getEndUserRef()\n\t\tif (envelope.payload.endUserRef !== endUserRef) {\n\t\t\tthrow new ExtenshiPayError(\n\t\t\t\tERROR_CODES.INVALID_RESPONSE,\n\t\t\t\t'Entitlement issued for a different endUserRef',\n\t\t\t)\n\t\t}\n\t\tconst { verdict, key } =\n\t\t\tthis.source === 'mock'\n\t\t\t\t? { verdict: 'unverified' as const, key: null }\n\t\t\t\t: await verifyWithKeys(envelope, this.options.keys)\n\t\tif (verdict === 'invalid') {\n\t\t\tawait this.discard()\n\t\t\tthrow new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Entitlement signature is invalid')\n\t\t}\n\t\tif (verdict !== 'valid' && this.source !== 'mock') {\n\t\t\tthrow new ExtenshiPayError(\n\t\t\t\tERROR_CODES.VERIFICATION_UNAVAILABLE,\n\t\t\t\t'Entitlement verification requires a trusted key and Ed25519 WebCrypto support',\n\t\t\t)\n\t\t}\n\t\tconst fetchedAt = this.now()\n\t\tconst issuedAt = Date.parse(envelope.payload.issuedAt)\n\t\t// A verified envelope was signed moments ago: its `issuedAt` is the server's clock.\n\t\tif (this.source !== 'mock') this.measureClockSkew(fetchedAt, issuedAt)\n\t\tif (this.source !== 'mock' && (!Number.isFinite(issuedAt) || issuedAt > fetchedAt + MAX_CLOCK_SKEW_MS)) {\n\t\t\tthrow new ExtenshiPayError(\n\t\t\t\tERROR_CODES.INVALID_RESPONSE,\n\t\t\t\t'Entitlement issuedAt is invalid or in the future',\n\t\t\t)\n\t\t}\n\t\tthis.held = { envelope, fetchedAt, verified: verdict === 'valid', key, source }\n\t\tconst record: CacheRecord = { v: CACHE_VERSION, envelope, fetchedAt }\n\t\tawait this.options.storage.set(this.storageKey, JSON.parse(JSON.stringify(record)))\n\t\tthis.backoffMs = 0\n\t\tthis.scheduleDeadline()\n\t\tthis.notifyIfChanged()\n\t\tthis.options.onAccepted?.()\n\t\treturn this.snapshot()\n\t}\n\n\t/** Drain an older installation refresh before changing identity. */\n\tasync settleRefresh(): Promise<void> {\n\t\tawait this.inflight?.catch(() => undefined)\n\t}\n\n\tasync clear(): Promise<void> {\n\t\tthis.held = null\n\t\tthis.scheduleDeadline()\n\t\tthis.lastFingerprint = null\n\t\tawait this.options.storage.remove(this.storageKey)\n\t}\n\n\tstartAutoRefresh(intervalMs: number = Math.max(this.options.cacheTtlMs, MIN_REFRESH_INTERVAL_MS)): void {\n\t\tthis.stopAutoRefresh()\n\t\tthis.autoRefresh = true\n\t\tglobalThis.addEventListener?.('online', this.online)\n\t\tthis.refreshIntervalMs = Math.max(intervalMs, MIN_REFRESH_INTERVAL_MS)\n\t\tthis.schedule(this.refreshIntervalMs)\n\t\tthis.scheduleDeadline()\n\t}\n\n\tstopAutoRefresh(): void {\n\t\tthis.autoRefresh = false\n\t\tglobalThis.removeEventListener?.('online', this.online)\n\t\tthis.refreshGeneration++\n\t\tif (this.deadlineTimer !== null) clearTimeout(this.deadlineTimer)\n\t\tthis.deadlineTimer = null\n\t\tif (this.timer !== null) clearTimeout(this.timer)\n\t\tthis.timer = null\n\t}\n\n\tprivate scheduleDeadline(): void {\n\t\tif (this.deadlineTimer !== null) clearTimeout(this.deadlineTimer)\n\t\tthis.deadlineTimer = null\n\t\tif (!this.autoRefresh || !this.held || !this.held.verified || this.source === 'mock') return\n\t\tconst now = this.now()\n\t\tif (now >= this.offlineDeadline()) return\n\t\tconst deadlines = [\n\t\t\tthis.offlineDeadline(),\n\t\t\t...this.held.envelope.payload.entitlements\n\t\t\t\t.filter((item) => item.status === 'active' || item.status === 'grace')\n\t\t\t\t.map((item) => (item.expiresAt ? Date.parse(item.expiresAt) : NaN)),\n\t\t]\n\t\tconst remaining = Math.min(...deadlines.filter((deadline) => deadline > now)) - now\n\t\tif (!Number.isFinite(remaining) || remaining <= 0) return\n\t\tthis.deadlineTimer = setTimeout(\n\t\t\t() => {\n\t\t\t\tthis.deadlineTimer = null\n\t\t\t\tthis.notifyIfChanged()\n\t\t\t\tthis.scheduleDeadline()\n\t\t\t},\n\t\t\tMath.min(remaining, MAX_TIMER_MS),\n\t\t)\n\t}\n\n\tprivate schedule(delayMs: number): void {\n\t\tconst generation = this.refreshGeneration\n\t\tthis.timer = setTimeout(async () => {\n\t\t\tthis.timer = null\n\t\t\ttry {\n\t\t\t\tawait this.refresh()\n\t\t\t\tif (generation !== this.refreshGeneration) return\n\t\t\t\tthis.schedule(this.refreshIntervalMs)\n\t\t\t} catch (error) {\n\t\t\t\tif (generation !== this.refreshGeneration) return\n\t\t\t\tthis.options.onError?.(ExtenshiPayError.from(error))\n\t\t\t\tthis.backoffMs = Math.min(\n\t\t\t\t\tthis.backoffMs ? this.backoffMs * 2 : this.refreshIntervalMs,\n\t\t\t\t\tMAX_REFRESH_BACKOFF_MS,\n\t\t\t\t)\n\t\t\t\tthis.schedule(this.backoffMs)\n\t\t\t}\n\t\t}, delayMs)\n\t}\n\n\tprivate measureClockSkew(local: number, server: number): void {\n\t\tconst ms = local - server\n\t\tthis.clockSkew =\n\t\t\tNumber.isFinite(ms) && Math.abs(ms) > MAX_CLOCK_SKEW_MS\n\t\t\t\t? { direction: ms > 0 ? 'ahead' : 'behind', ms: Math.abs(ms) }\n\t\t\t\t: null\n\t}\n\n\tprivate async discard(): Promise<void> {\n\t\tthis.held = null\n\t\tthis.scheduleDeadline()\n\t\tawait this.options.storage.remove(this.storageKey)\n\t\tthis.notifyIfChanged()\n\t}\n\n\tprivate fingerprint(): string {\n\t\tconst state = this.snapshot()\n\t\treturn canonicalJson({\n\t\t\titems: state.items,\n\t\t\trequiresOnlineCheck: state.requiresOnlineCheck,\n\t\t\t...(state.regionalFreeUntil\n\t\t\t\t? { regionalFreeUntil: state.regionalFreeUntil, features: state.features }\n\t\t\t\t: {}),\n\t\t})\n\t}\n\n\tprivate notifyIfChanged(): void {\n\t\tconst fingerprint = this.fingerprint()\n\t\tif (fingerprint === this.lastFingerprint) return\n\t\tthis.lastFingerprint = fingerprint\n\t\tthis.options.onChange?.(this.snapshot())\n\t}\n\n\tprivate offlineDeadline(): number {\n\t\tif (!this.held) return NaN\n\t\t// fetchedAt is untrusted bookkeeping; it may shorten, never extend, a grant.\n\t\treturn (\n\t\t\tMath.min(this.held.fetchedAt, Date.parse(this.held.envelope.payload.issuedAt)) + this.offlineAgeMs()\n\t\t)\n\t}\n\n\t/** The signed allowance of the held license, or 48 hours when it names none. */\n\tprivate offlineAgeMs(): number {\n\t\tconst seconds = this.held?.envelope.payload.offlineSeconds\n\t\tif (typeof seconds !== 'number' || !Number.isFinite(seconds) || seconds <= 0) return MAX_OFFLINE_AGE_MS\n\t\treturn Math.min(seconds * 1000, MAX_SIGNED_OFFLINE_AGE_MS)\n\t}\n\n\tprivate snapshot(): Entitlement {\n\t\tif (!this.held)\n\t\t\treturn this.clockSkew ? { ...EMPTY_ENTITLEMENT, clockSkew: this.clockSkew } : EMPTY_ENTITLEMENT\n\t\tif (this.source !== 'mock' && !this.held.verified) {\n\t\t\treturn {\n\t\t\t\t...EMPTY_ENTITLEMENT,\n\t\t\t\trequiresOnlineCheck: true,\n\t\t\t\tclockSkew: this.clockSkew,\n\t\t\t\tsource: this.held.source,\n\t\t\t}\n\t\t}\n\t\tconst grants = applyLocalExpiry(\n\t\t\tJSON.parse(JSON.stringify(this.held.envelope.payload.entitlements)),\n\t\t\tthis.now(),\n\t\t)\n\t\tconst regional = grants.find(\n\t\t\t(grant) => grant.sku === PAY_REGIONAL_ACCESS_SKU && grant.status === 'active',\n\t\t)\n\t\tconst items = grants.filter((grant) => grant.sku !== PAY_REGIONAL_ACCESS_SKU)\n\t\tconst hasPaidAccess =\n\t\t\tgrants.some((grant) => grant.sku === PAY_REGIONAL_ACCESS_SKU) ||\n\t\t\tcollectFeatures(items).length > 0 ||\n\t\t\titems.some((item) => item.status === 'active' || item.status === 'grace')\n\t\tconst offlineUntil = this.source === 'mock' || !hasPaidAccess ? null : this.offlineDeadline()\n\t\tconst requiresOnlineCheck =\n\t\t\tofflineUntil !== null &&\n\t\t\t(!Number.isFinite(offlineUntil) ||\n\t\t\t\tthis.now() >= offlineUntil ||\n\t\t\t\tthis.now() < this.held.fetchedAt ||\n\t\t\t\tthis.now() + MAX_CLOCK_SKEW_MS < Date.parse(this.held.envelope.payload.issuedAt))\n\t\treturn {\n\t\t\titems,\n\t\t\tfeatures: requiresOnlineCheck ? [] : collectFeatures(grants),\n\t\t\t...(regional?.expiresAt && !requiresOnlineCheck\n\t\t\t\t? { regionalFreeUntil: Date.parse(regional.expiresAt) }\n\t\t\t\t: {}),\n\t\t\trequiresOnlineCheck,\n\t\t\tofflineUntil,\n\t\t\tclockSkew: this.clockSkew,\n\t\t\tverified: this.held.verified,\n\t\t\tissuedAt: this.held.envelope.payload.issuedAt,\n\t\t\tfetchedAt: this.held.fetchedAt,\n\t\t\tsource: this.held.source,\n\t\t}\n\t}\n}\n","/**\n * Persistent key/value storage for the SDK's own namespace.\n *\n * Preference order: `chrome.storage.local` (Chrome/Edge), `browser.storage.local`\n * (Firefox), `localStorage` (non-extension contexts such as a dev page), then\n * memory. Both promise-returning (MV3, Firefox) and callback-only (MV2) storage\n * APIs are supported.\n */\n\nexport interface StorageAdapter {\n\tget(key: string): Promise<unknown>\n\tset(key: string, value: unknown): Promise<void>\n\tremove(key: string): Promise<void>\n}\n\ntype Items = Record<string, unknown>\n\ninterface StorageArea {\n\tget(keys: string, callback?: (items: Items) => void): unknown\n\tset(items: Items, callback?: () => void): unknown\n\tremove(keys: string, callback?: () => void): unknown\n}\n\ninterface ExtensionGlobals {\n\tchrome?: {\n\t\tstorage?: { local?: StorageArea; sync?: StorageArea }\n\t\truntime?: { lastError?: { message?: string } }\n\t}\n\tbrowser?: { storage?: { local?: StorageArea; sync?: StorageArea } }\n}\n\nfunction extensionGlobals(): ExtensionGlobals {\n\treturn globalThis as ExtensionGlobals\n}\n\nfunction isThenable<T>(value: unknown): value is Promise<T> {\n\treturn !!value && typeof (value as Promise<T>).then === 'function'\n}\n\n/** Runs a storage-area call that may either return a promise or expect a callback. */\nfunction areaCall<T>(\n\tdirect: () => unknown,\n\twithCallback: (callback: (value: T) => void) => void,\n): Promise<T> {\n\tconst result = direct()\n\tif (isThenable<T>(result)) return result\n\treturn new Promise<T>((resolve, reject) => {\n\t\twithCallback((value) => {\n\t\t\tconst lastError = extensionGlobals().chrome?.runtime?.lastError\n\t\t\tif (lastError) reject(new Error(lastError.message ?? 'storage error'))\n\t\t\telse resolve(value)\n\t\t})\n\t})\n}\n\nexport class ExtensionStorage implements StorageAdapter {\n\tconstructor(private readonly area: StorageArea) {}\n\n\tasync get(key: string): Promise<unknown> {\n\t\tconst items = await areaCall<Items>(\n\t\t\t() => this.area.get(key),\n\t\t\t(cb) => this.area.get(key, cb),\n\t\t)\n\t\treturn items?.[key]\n\t}\n\n\tasync set(key: string, value: unknown): Promise<void> {\n\t\tawait areaCall<void>(\n\t\t\t() => this.area.set({ [key]: value }),\n\t\t\t(cb) => this.area.set({ [key]: value }, cb),\n\t\t)\n\t}\n\n\tasync remove(key: string): Promise<void> {\n\t\tawait areaCall<void>(\n\t\t\t() => this.area.remove(key),\n\t\t\t(cb) => this.area.remove(key, cb),\n\t\t)\n\t}\n}\n\nexport class LocalStorageAdapter implements StorageAdapter {\n\tconstructor(private readonly store: Storage) {}\n\n\tasync get(key: string): Promise<unknown> {\n\t\tconst raw = this.store.getItem(key)\n\t\tif (raw === null) return undefined\n\t\ttry {\n\t\t\treturn JSON.parse(raw)\n\t\t} catch {\n\t\t\treturn undefined\n\t\t}\n\t}\n\n\tasync set(key: string, value: unknown): Promise<void> {\n\t\tthis.store.setItem(key, JSON.stringify(value))\n\t}\n\n\tasync remove(key: string): Promise<void> {\n\t\tthis.store.removeItem(key)\n\t}\n}\n\nexport class MemoryStorage implements StorageAdapter {\n\tprivate readonly map = new Map<string, unknown>()\n\n\tasync get(key: string): Promise<unknown> {\n\t\treturn this.map.get(key)\n\t}\n\n\tasync set(key: string, value: unknown): Promise<void> {\n\t\tthis.map.set(key, value)\n\t}\n\n\tasync remove(key: string): Promise<void> {\n\t\tthis.map.delete(key)\n\t}\n}\n\n/**\n * The browser's synced storage (`storage.sync`), or null outside an extension. The SDK keeps\n * only the trial start there (never `endUserRef`), so devices on one synced account share the\n * trial. Uninstalling clears it from the account, so it does not survive a reinstall.\n */\nexport function createSyncStorage(): StorageAdapter | null {\n\tconst g = extensionGlobals()\n\tconst area = g.chrome?.storage?.sync ?? g.browser?.storage?.sync\n\treturn area ? new ExtensionStorage(area) : null\n}\n\nexport function createStorage(): StorageAdapter {\n\tconst g = extensionGlobals()\n\tconst area = g.chrome?.storage?.local ?? g.browser?.storage?.local\n\tif (area) return new ExtensionStorage(area)\n\ttry {\n\t\tconst store = (globalThis as { localStorage?: Storage }).localStorage\n\t\tif (store && typeof store.getItem === 'function') return new LocalStorageAdapter(store)\n\t} catch {\n\t\t// Access to localStorage can throw in sandboxed frames.\n\t}\n\treturn new MemoryStorage()\n}\n","/** Email stays on the hosted page. Only this extension context holds the claim secret. */\nimport type { PayApi } from '../api/pay-api.js'\nimport type { StorageAdapter } from '../core/storage.js'\nimport { ExtensionStorage, MemoryStorage } from '../core/storage.js'\nimport type { PayStorageGrant, SignedEntitlement } from '../types/contract.js'\nimport type { CloudBackupState, Entitlement, RestoreOptions, RestoreResult } from '../types/entitlement.js'\nimport { ERROR_CODES, ExtenshiPayError } from '../types/errors.js'\nimport { openInNewTab } from './checkout.js'\n\ntype SessionArea = ConstructorParameters<typeof ExtensionStorage>[0]\n\n/** storage.local is exposed to content scripts by default. Never put a recovery proof there. */\nexport function createRecoveryStorage(): StorageAdapter {\n\tconst g = globalThis as {\n\t\tchrome?: { storage?: { session?: SessionArea }; tabs?: unknown }\n\t\tbrowser?: { storage?: { session?: SessionArea }; tabs?: unknown }\n\t}\n\tconst extension = g.chrome?.tabs ? g.chrome : g.browser?.tabs ? g.browser : null\n\treturn extension?.storage?.session ? new ExtensionStorage(extension.storage.session) : new MemoryStorage()\n}\n\ninterface PendingRestore {\n\tsessionId: string\n\tclaimSecret: string\n\texpiresAt: string\n}\nexport interface RecoveryManagerOptions {\n\tapi: PayApi\n\t/** The user's language, for the hosted recovery page and its email. */\n\tlocale?: string | null\n\tstorage: StorageAdapter\n\tpublishableKey: string\n\tonComplete: (endUserRef: string, envelope: SignedEntitlement) => Promise<Entitlement>\n\t/** Runs after `onComplete` accepted the entitlement, with the claim's storage grant (if any). */\n\tonStorageGrant?: (grant: PayStorageGrant | undefined) => Promise<CloudBackupState | undefined>\n\topenUrl?: (url: string) => void | Promise<void>\n\tnow?: () => number\n}\n\nexport class RecoveryManager {\n\tprivate active = false\n\tprivate stopped = false\n\tprivate wake: (() => void) | null = null\n\tconstructor(private readonly options: RecoveryManagerOptions) {}\n\tget pendingKey(): string {\n\t\treturn `extenshi-pay:${this.options.publishableKey}:pendingRestore`\n\t}\n\tisActive(): boolean {\n\t\treturn this.active\n\t}\n\tstop(): void {\n\t\tthis.stopped = true\n\t\tthis.wake?.()\n\t}\n\n\tasync open(options: RestoreOptions = {}): Promise<RestoreResult> {\n\t\tif (this.active)\n\t\t\tthrow new ExtenshiPayError(ERROR_CODES.INVALID_REQUEST, 'Recovery is already in progress')\n\t\tthis.active = true\n\t\tthis.stopped = false\n\t\ttry {\n\t\t\t// A caller from a content script must route the action to its own background;\n\t\t\t// never return this manager's internal state through that message bridge.\n\t\t\tconst g = globalThis as {\n\t\t\t\tchrome?: { runtime?: { id?: string }; tabs?: unknown }\n\t\t\t\tbrowser?: { runtime?: { id?: string }; tabs?: unknown }\n\t\t\t}\n\t\t\tif ((g.chrome?.runtime?.id || g.browser?.runtime?.id) && !(g.chrome?.tabs || g.browser?.tabs))\n\t\t\t\tthrow new ExtenshiPayError(\n\t\t\t\t\tERROR_CODES.INVALID_REQUEST,\n\t\t\t\t\t'Start recovery in an extension page or background context',\n\t\t\t\t)\n\t\t\tconst cryptoApi = globalThis.crypto\n\t\t\tif (!cryptoApi?.subtle)\n\t\t\t\tthrow new ExtenshiPayError(\n\t\t\t\t\tERROR_CODES.INVALID_REQUEST,\n\t\t\t\t\t'Secure recovery is unavailable in this browser',\n\t\t\t\t)\n\t\t\tconst secret = Array.from(cryptoApi.getRandomValues(new Uint8Array(32)), (b) =>\n\t\t\t\tb.toString(16).padStart(2, '0'),\n\t\t\t).join('')\n\t\t\tconst hash = await cryptoApi.subtle.digest('SHA-256', new TextEncoder().encode(secret))\n\t\t\tconst challenge = Array.from(new Uint8Array(hash), (b) => b.toString(16).padStart(2, '0')).join('')\n\t\t\tconst created = await this.options.api.createRestoreSession(\n\t\t\t\tchallenge,\n\t\t\t\tthis.options.locale,\n\t\t\t\toptions.purpose,\n\t\t\t)\n\t\t\tif (!Number.isFinite(Date.parse(created.expiresAt)))\n\t\t\t\tthrow new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Invalid recovery expiry')\n\t\t\tconst pending = { sessionId: created.sessionId, expiresAt: created.expiresAt, claimSecret: secret }\n\t\t\tawait this.options.storage.set(this.pendingKey, pending)\n\t\t\tawait (options.openUrl ?? this.options.openUrl ?? openInNewTab)(created.url)\n\t\t\treturn await this.poll(pending, options)\n\t\t} finally {\n\t\t\tthis.active = false\n\t\t}\n\t}\n\n\tasync resumePending(): Promise<RestoreResult | null> {\n\t\tif (this.active || this.stopped) return null\n\t\tconst raw = (await this.options.storage.get(this.pendingKey)) as Partial<PendingRestore> | undefined\n\t\tif (!raw || this.active || this.stopped) return null\n\t\tif (\n\t\t\ttypeof raw.sessionId !== 'string' ||\n\t\t\ttypeof raw.claimSecret !== 'string' ||\n\t\t\t!/^[a-f0-9]{64}$/.test(raw.claimSecret) ||\n\t\t\t!Number.isFinite(Date.parse(raw.expiresAt ?? ''))\n\t\t) {\n\t\t\tawait this.options.storage.remove(this.pendingKey)\n\t\t\treturn null\n\t\t}\n\t\tthis.active = true\n\t\tthis.stopped = false\n\t\ttry {\n\t\t\treturn await this.poll(raw as PendingRestore, {})\n\t\t} finally {\n\t\t\tthis.active = false\n\t\t}\n\t}\n\n\tprivate async poll(pending: PendingRestore, options: RestoreOptions): Promise<RestoreResult> {\n\t\tconst now = this.options.now ?? Date.now\n\t\tconst expires = Date.parse(pending.expiresAt)\n\t\tconst deadline = Math.min(expires, now() + (options.timeoutMs ?? 10 * 60 * 1000))\n\t\tlet delay = 0\n\t\twhile (!this.stopped && !options.signal?.aborted && now() < deadline) {\n\t\t\tif (delay)\n\t\t\t\tawait new Promise<void>((resolve) => {\n\t\t\t\t\tconst done = () => {\n\t\t\t\t\t\tclearTimeout(timer)\n\t\t\t\t\t\toptions.signal?.removeEventListener('abort', done)\n\t\t\t\t\t\tthis.wake = null\n\t\t\t\t\t\tresolve()\n\t\t\t\t\t}\n\t\t\t\t\tconst timer = setTimeout(done, Math.min(delay, Math.max(0, deadline - now())))\n\t\t\t\t\tthis.wake = done\n\t\t\t\t\toptions.signal?.addEventListener('abort', done, { once: true })\n\t\t\t\t})\n\t\t\tif (this.stopped || options.signal?.aborted || now() >= deadline) break\n\t\t\ttry {\n\t\t\t\tconst claim = await this.options.api.claimRestoreSession(pending.sessionId, pending.claimSecret)\n\t\t\t\tif (this.stopped || options.signal?.aborted) break\n\t\t\t\tif (claim.state === 'complete') {\n\t\t\t\t\tconst entitlement = await this.options.onComplete(claim.endUserRef, claim.entitlement)\n\t\t\t\t\tconst cloudBackup = await this.options.onStorageGrant?.(claim.storage)\n\t\t\t\t\tawait this.options.storage.remove(this.pendingKey)\n\t\t\t\t\treturn { state: 'complete', entitlement, ...(cloudBackup ? { cloudBackup } : {}) }\n\t\t\t\t}\n\t\t\t\tif (claim.state !== 'pending')\n\t\t\t\t\tthrow new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Invalid recovery response')\n\t\t\t\tdelay = Math.max(100, options.pollIntervalMs ?? 2_000)\n\t\t\t} catch (error) {\n\t\t\t\tconst err = ExtenshiPayError.from(error)\n\t\t\t\tif (\n\t\t\t\t\t![\n\t\t\t\t\t\tERROR_CODES.NETWORK_ERROR,\n\t\t\t\t\t\tERROR_CODES.TIMEOUT,\n\t\t\t\t\t\tERROR_CODES.GATEWAY_UNAVAILABLE,\n\t\t\t\t\t\tERROR_CODES.RATE_LIMITED,\n\t\t\t\t\t].some((code) => code === err.code)\n\t\t\t\t)\n\t\t\t\t\tthrow err\n\t\t\t\tdelay = Math.max(2_000, (err.retryAfterSec ?? 5) * 1000)\n\t\t\t}\n\t\t}\n\t\tif (now() >= expires) await this.options.storage.remove(this.pendingKey)\n\t\treturn {\n\t\t\tstate: this.stopped || options.signal?.aborted ? 'canceled' : now() >= expires ? 'expired' : 'timeout',\n\t\t}\n\t}\n}\n","import type { PayEntitlementItem, PayOfferDto, PaySellerPublic, PayWithdrawalWaiver } from './contract.js'\nimport type { ExtenshiPayError } from './errors.js'\n\nexport type LogLevel = 'silent' | 'error' | 'warn' | 'info' | 'debug'\n\n/** Reserved for future routing; today every environment talks to the same BFF. */\nexport type Environment = 'production' | 'sandbox' | 'development'\n\nexport interface ThemeConfig {\n\t/** `auto` follows `prefers-color-scheme`. */\n\tmode?: 'light' | 'dark' | 'auto'\n\tprimaryColor?: string\n\tfontFamily?: string\n\tborderRadius?: string\n\t/** Appended verbatim inside the paywall's shadow root. */\n\tcustomCss?: string\n}\n\n/** Offline development data used when `mock: true`. */\nexport interface MockData {\n\tentitlements?: PayEntitlementItem[]\n\toffers?: PayOfferDto[]\n\tprojectName?: string\n\t/** Defaults to true. */\n\tcheckoutEnabled?: boolean\n\t/** How many `claimSession` polls answer `pending` before a mock checkout completes (default 1). */\n\tclaimAfterPolls?: number\n\t/**\n\t * Offer's withdrawal waiver (default: required, current version, so the\n\t * paywall previews the checkbox). `null` previews a seller outside the EEA/UK.\n\t */\n\twithdrawalWaiver?: PayWithdrawalWaiver | null\n\t/**\n\t * Seller details for the paywall, the license panel and the waiver text.\n\t * Omitted, the offer carries none (as from an older server); `null`\n\t * previews a seller without public details, so the paywall disables purchase.\n\t */\n\tseller?: PaySellerPublic | null\n\t/**\n\t * Previews a server trial: `days` long, started at `startedAt` (default: when the mock is\n\t * created). Omitted, the mock application has no trial.\n\t */\n\ttrial?: { days: number; startedAt?: string }\n}\n\nexport interface ExtenshiPayConfig {\n\t/** `pk_ext_` + 32 hex characters, from the project's Monetization tab. */\n\tpublishableKey: string\n\t/** Defaults to `https://bff.extenshi.io`. */\n\tapiUrl?: string\n\t/** Bundled raw Ed25519 public key (base64). Enables verified cache use after an offline restart. */\n\tentitlementPublicKey?: string\n\tenvironment?: Environment\n\t/** Shorthand for `logLevel: 'debug'`. */\n\tdebug?: boolean\n\tlogLevel?: LogLevel\n\t/** How long a fetched entitlement is served without a network round-trip (default 1 hour). */\n\tcacheTtlMs?: number\n\t/** BCP-47 tag such as `en` or `de-DE`; sent to the backend for checkout/offer copy and used for price formatting. */\n\tlocale?: string\n\tmock?: boolean\n\tmockData?: MockData\n\tonReady?: () => void\n\tonError?: (error: ExtenshiPayError) => void\n\ttheme?: ThemeConfig\n\t/** Days before the trial's end that `trial:ending` fires (default 2; 0 turns it off). */\n\ttrialEndingDays?: number\n\t/**\n\t * Keep the trial's start date in `storage.sync` and send it back on license checks, so\n\t * other devices on the same synced browser account share the trial (default true).\n\t * Only the date is synced, never the installation id. A reinstall still restarts the\n\t * trial: uninstalling clears `storage.sync`.\n\t */\n\tsyncTrialStart?: boolean\n}\n\nexport interface ResolvedConfig {\n\tpublishableKey: string\n\tapiUrl: string\n\tentitlementPublicKey: string | null\n\tenvironment: Environment\n\tdebug: boolean\n\tlogLevel: LogLevel\n\tcacheTtlMs: number\n\tlocale: string | null\n\tmock: boolean\n\tmockData: MockData | null\n\ttheme: ThemeConfig\n\ttrialEndingDays: number\n\tsyncTrialStart: boolean\n}\n\nexport const DEFAULT_API_URL = 'https://bff.extenshi.io'\nexport const DEFAULT_CACHE_TTL_MS = 60 * 60 * 1000\nexport const MAX_CACHE_TTL_MS = 7 * 24 * 60 * 60 * 1000\nexport const DEFAULT_TRIAL_ENDING_DAYS = 2\n","/** Kept in sync with package.json by tests/unit/version.test.ts. */\nexport const VERSION = '0.12.0'\n","/**\n * The user's language as the SDK sends it. Kept apart from the paywall\n * dictionary (../paywall/i18n.ts) so the Lite and core bundles, which never\n * render UI, do not carry the translations.\n */\n\n/** What the backend (and older backends) accept as a locale: `de`, `pt-BR`, `zh-CN`. */\nconst WIRE_LOCALE_RE = /^[a-z]{2}(-[A-Za-z]{2,4})?$/\n\n/**\n * A browser tag as the SDK sends it: `pt_BR` → `pt-BR`, `es-419` → `es`,\n * `zh-Hant-TW` → `zh-TW`; null for anything that is not a language tag.\n */\nexport function wireLocale(raw: unknown): string | null {\n\tif (typeof raw !== 'string') return null\n\tconst parts = raw.trim().replace(/_/g, '-').split('-').filter(Boolean)\n\tconst lang = parts[0]?.toLowerCase()\n\tif (!lang || !/^[a-z]{2}$/.test(lang)) return null\n\tconst script = parts\n\t\t.slice(1)\n\t\t.find((p) => /^[A-Za-z]{4}$/.test(p))\n\t\t?.toLowerCase()\n\t// zh-Hant without a region is Traditional Chinese: keep that, never let it read as zh-CN.\n\tconst region =\n\t\tparts.slice(1).find((p) => /^[A-Za-z]{2}$/.test(p)) ??\n\t\t(lang === 'zh' && script === 'hant' ? 'TW' : undefined)\n\tconst tag = region ? `${lang}-${region.toUpperCase()}` : lang\n\treturn WIRE_LOCALE_RE.test(tag) ? tag : lang\n}\n\n/** The browser UI language (`chrome.i18n.getUILanguage()`, else `navigator.language`), or null. */\nexport function browserLocale(): string | null {\n\tconst g = globalThis as {\n\t\tchrome?: { i18n?: { getUILanguage?: () => string } }\n\t\tbrowser?: { i18n?: { getUILanguage?: () => string } }\n\t\tnavigator?: { language?: string }\n\t}\n\ttry {\n\t\tconst ui = g.chrome?.i18n?.getUILanguage?.() ?? g.browser?.i18n?.getUILanguage?.()\n\t\tif (ui) return wireLocale(ui)\n\t} catch {\n\t\t/* Not an extension context. */\n\t}\n\treturn wireLocale(g.navigator?.language)\n}\n","import { PUBLIC_KEY_RE } from '../payment/signature.js'\nimport {\n\tDEFAULT_API_URL,\n\tDEFAULT_CACHE_TTL_MS,\n\tDEFAULT_TRIAL_ENDING_DAYS,\n\ttype ExtenshiPayConfig,\n\tMAX_CACHE_TTL_MS,\n\ttype ResolvedConfig,\n} from '../types/config.js'\nimport { isPayPublishableKey } from '../types/contract.js'\nimport { ERROR_CODES, ExtenshiPayError } from '../types/errors.js'\nimport { browserLocale } from './locale.js'\n\nconst ENVIRONMENTS = new Set(['production', 'sandbox', 'development'])\nconst LOG_LEVELS = new Set(['silent', 'error', 'warn', 'info', 'debug'])\nconst THEME_MODES = new Set(['light', 'dark', 'auto'])\n/** Same shape the BFF accepts (`en`, `de-DE`, `zh-Hant`). */\nexport const LOCALE_RE = /^[a-z]{2}(-[A-Za-z]{2,4})?$/\n\nfunction isHttpUrl(value: string): boolean {\n\ttry {\n\t\tconst url = new URL(value)\n\t\treturn url.protocol === 'https:' || url.protocol === 'http:'\n\t} catch {\n\t\treturn false\n\t}\n}\n\nexport function resolveConfig(input: ExtenshiPayConfig): ResolvedConfig {\n\tconst errors: string[] = []\n\tif (!input || typeof input !== 'object') {\n\t\tthrow new ExtenshiPayError(ERROR_CODES.INVALID_CONFIG, 'ExtenshiPay config must be an object')\n\t}\n\n\tif (!isPayPublishableKey(input.publishableKey)) {\n\t\terrors.push('publishableKey must look like pk_ext_<32 hex characters>')\n\t}\n\n\tconst apiUrl = (input.apiUrl ?? DEFAULT_API_URL).replace(/\\/+$/, '')\n\tif (!isHttpUrl(apiUrl)) errors.push('apiUrl must be an http(s) URL')\n\n\tconst entitlementPublicKey = input.entitlementPublicKey ?? null\n\tif (entitlementPublicKey !== null && !PUBLIC_KEY_RE.test(entitlementPublicKey)) {\n\t\terrors.push('entitlementPublicKey must be a base64-encoded 32-byte Ed25519 public key')\n\t}\n\n\tconst environment = input.environment ?? 'production'\n\tif (!ENVIRONMENTS.has(environment)) errors.push('environment must be production, sandbox or development')\n\n\tconst logLevel = input.logLevel ?? 'warn'\n\tif (!LOG_LEVELS.has(logLevel)) errors.push('logLevel must be silent, error, warn, info or debug')\n\n\tconst cacheTtlMs = input.cacheTtlMs ?? DEFAULT_CACHE_TTL_MS\n\tif (!Number.isFinite(cacheTtlMs) || cacheTtlMs < 0 || cacheTtlMs > MAX_CACHE_TTL_MS) {\n\t\terrors.push(`cacheTtlMs must be between 0 and ${MAX_CACHE_TTL_MS}`)\n\t}\n\n\t// Default: the browser UI language, as README promises (it. 13 T10 L2).\n\t// `null` still opts out explicitly: prices then use the runtime default\n\t// and the paywall reads English.\n\tconst locale = input.locale === undefined ? browserLocale() : input.locale\n\tif (locale !== null && !LOCALE_RE.test(locale))\n\t\terrors.push('locale must be a BCP-47 tag such as en or de-DE')\n\n\tconst theme = input.theme ?? {}\n\tif (theme.mode !== undefined && !THEME_MODES.has(theme.mode))\n\t\terrors.push('theme.mode must be light, dark or auto')\n\n\tconst trialEndingDays = input.trialEndingDays ?? DEFAULT_TRIAL_ENDING_DAYS\n\tif (!Number.isInteger(trialEndingDays) || trialEndingDays < 0 || trialEndingDays > 365)\n\t\terrors.push('trialEndingDays must be a whole number of days between 0 and 365')\n\n\tif (\n\t\tinput.mock &&\n\t\tinput.mockData !== undefined &&\n\t\t(typeof input.mockData !== 'object' || input.mockData === null)\n\t) {\n\t\terrors.push('mockData must be an object')\n\t}\n\n\tif (errors.length > 0) {\n\t\tthrow new ExtenshiPayError(ERROR_CODES.INVALID_CONFIG, `Invalid ExtenshiPay config: ${errors.join('; ')}`)\n\t}\n\n\treturn {\n\t\tpublishableKey: input.publishableKey,\n\t\tapiUrl,\n\t\tentitlementPublicKey,\n\t\tenvironment,\n\t\tdebug: input.debug === true,\n\t\tlogLevel,\n\t\tcacheTtlMs,\n\t\tlocale,\n\t\tmock: input.mock === true,\n\t\tmockData: input.mock ? (input.mockData ?? {}) : null,\n\t\ttheme,\n\t\ttrialEndingDays,\n\t\tsyncTrialStart: input.syncTrialStart !== false,\n\t}\n}\n","import { logger } from '../utils/logger.js'\n\nexport type Listener<T> = (payload: T) => void\ntype AnyListener = (payload: never) => void\n\nexport class EventEmitter<Events extends object> {\n\tprivate readonly listeners = new Map<keyof Events, Set<AnyListener>>()\n\n\ton<K extends keyof Events>(event: K, listener: Listener<Events[K]>): () => void {\n\t\tlet set = this.listeners.get(event)\n\t\tif (!set) {\n\t\t\tset = new Set()\n\t\t\tthis.listeners.set(event, set)\n\t\t}\n\t\tset.add(listener as AnyListener)\n\t\treturn () => this.off(event, listener)\n\t}\n\n\tonce<K extends keyof Events>(event: K, listener: Listener<Events[K]>): () => void {\n\t\tconst off = this.on(event, (payload) => {\n\t\t\toff()\n\t\t\tlistener(payload)\n\t\t})\n\t\treturn off\n\t}\n\n\toff<K extends keyof Events>(event: K, listener: Listener<Events[K]>): void {\n\t\tthis.listeners.get(event)?.delete(listener as AnyListener)\n\t}\n\n\temit<K extends keyof Events>(event: K, payload: Events[K]): void {\n\t\tconst set = this.listeners.get(event)\n\t\tif (!set) return\n\t\tfor (const listener of [...set]) {\n\t\t\tconst fn = listener as Listener<Events[K]>\n\t\t\ttry {\n\t\t\t\tfn(payload)\n\t\t\t} catch (error) {\n\t\t\t\tlogger.error(`listener for \"${String(event)}\" threw`, error)\n\t\t\t}\n\t\t}\n\t}\n\n\tremoveAll(): void {\n\t\tthis.listeners.clear()\n\t}\n}\n","/**\n * Every string the SDK shows to the USER of an extension — paywall, license\n * dialog, billing-profile picker, seller details — in the end-user languages\n * (ROADMAP it. 13 T10, stage L2; closes it. 12 T9). Developer-facing error\n * messages stay English.\n *\n * Self-contained on purpose: the SDK ships inside third-party extensions with\n * no runtime dependencies and no remote code, so the dictionary is compiled\n * in. Placeholders are `{name}`, `{date}`, `{status}`. A missing\n * translation falls back to English, never to an empty string. The same\n * languages as the hosted pages (shared-types END_USER_LOCALES); keep the\n * lists in sync.\n */\n\nexport { browserLocale, wireLocale } from '../core/locale.js'\n\nimport { wireLocale } from '../core/locale.js'\n\nexport const SDK_LOCALES = ['en', 'es', 'pt-BR', 'fr', 'de', 'it', 'ru', 'ja', 'ko', 'zh-CN', 'ar'] as const\nexport type SdkLocale = (typeof SDK_LOCALES)[number]\n\nexport const SDK_STRINGS_EN = {\n\ttitle: 'Unlock premium features',\n\tdescription: 'Upgrade to get full access to this extension.',\n\tupgrade: 'Upgrade',\n\tcancel: 'Not now',\n\tdismiss: 'Dismiss',\n\tremindLater: 'Remind me later',\n\tcontinueFree: 'Continue with the free version',\n\tcheckoutUnavailable: 'Purchases are temporarily unavailable',\n\tperiodMonth: '/month',\n\tperiodYear: '/year',\n\tperiodOnce: 'one-time',\n\tfooter: 'Secure checkout opens in a new tab.',\n\trestorePurchase: 'Restore purchase',\n\tfeaturesHeading: 'Premium Features',\n\tplansHeading: 'Choose Your Plan',\n\tfreePlanName: 'Free',\n\tpremiumPlanName: 'Premium',\n\tpopularBadge: 'Most Popular',\n\tunlockHeading: 'Unlock Premium Features',\n\tsimulatePurchase: 'Simulate purchase',\n\tmockNotice: 'Development preview: licenses and payments are simulated. No payment will be taken.',\n\tsellerProvidedBy: 'License provided by {name}',\n\tsellerUnavailable: 'License provider details are unavailable.',\n\tsellerSupport: 'Extension support',\n\tsellerTerms: 'License terms',\n\tsellerRefunds: 'Refund policy',\n\tsellerRole:\n\t\t'The author handles extension functionality and license commitments. Extenshi provides payment and license recovery tools.',\n\tlicenseTitle: 'Your license',\n\tlicenseFallbackName: 'Extension license',\n\tlicenseNone: 'No license found on this installation.',\n\tkindOneTime: 'One-time purchase',\n\tkindLifetime: 'Lifetime',\n\tkindSubscription: 'Subscription',\n\tkindLicense: 'License',\n\tstatusLine: 'Status: {status}',\n\tstatusActive: 'active',\n\tstatusGrace: 'grace period',\n\tstatusExpired: 'expired',\n\tstatusNone: 'no access',\n\taccessEnded: 'Access ended {date}',\n\taccessUntil: 'Access until {date}',\n\taccessRecordedEnd: 'Recorded end date {date}',\n\tsubscriptionLine: 'Subscription: {status}',\n\trenewalCanceled: 'Renewal canceled',\n\tperiodEnds: 'Period ends {date}',\n\tsubActive: 'active',\n\tsubTrialing: 'trial',\n\tsubPastDue: 'payment overdue',\n\tsubCanceled: 'canceled',\n\tsubUnpaid: 'unpaid',\n\tsubIncomplete: 'incomplete',\n\tsubIncompleteExpired: 'payment not completed',\n\tsubPaused: 'paused',\n\tlicenseOffline:\n\t\t'Connect to the internet to verify your license. Paid features are paused after 48 hours without a successful check. Your purchase has not expired.',\n\tlicenseCached: 'Showing saved license information.',\n\tlicenseFresh: 'Subscription information reflects the latest processed payment update.',\n\tactionFailed: 'Unable to complete the request. Please try again or contact extension support.',\n\tmanageBilling: 'Manage billing',\n\tnoPortal: 'No billing portal opened. You can retry or contact extension support.',\n\tclose: 'Close',\n\tpickerTitle: 'Choose a billing profile',\n\tpickerDescription:\n\t\t'Separate purchases can have separate billing profiles. Choose one to manage its subscriptions and payment details.',\n\tpickerFirstRecorded: 'First recorded {date}',\n\tpickerCancel: 'Cancel',\n\ttrialEndedTitle: 'Your free trial has ended',\n\ttrialEndedDescription:\n\t\t'The extension’s tools are paused. Your settings are kept and will be there when you upgrade.',\n\ttrialEndedFeedback: 'Share feedback',\n}\n\nexport type SdkStringKey = keyof typeof SDK_STRINGS_EN\nexport type SdkStrings = Record<SdkStringKey, string>\n\n// BEGIN GENERATED TRANSLATIONS\nconst TRANSLATIONS: Partial<Record<Exclude<SdkLocale, 'en'>, SdkStrings>> = {\n\tes: {\n\t\ttitle: 'Desbloquea las funciones premium',\n\t\tdescription: 'Mejora tu plan para obtener acceso completo a esta extensión.',\n\t\tupgrade: 'Mejorar plan',\n\t\tcancel: 'Ahora no',\n\t\tdismiss: 'Descartar',\n\t\tremindLater: 'Recordármelo más tarde',\n\t\tcontinueFree: 'Seguir con la versión gratuita',\n\t\tcheckoutUnavailable: 'Compras no disponibles temporalmente',\n\t\tperiodMonth: '/mes',\n\t\tperiodYear: '/año',\n\t\tperiodOnce: 'pago único',\n\t\tfooter: 'El pago seguro se abre en una pestaña nueva.',\n\t\trestorePurchase: 'Restaurar compra',\n\t\tfeaturesHeading: 'Funciones premium',\n\t\tplansHeading: 'Elige tu plan',\n\t\tfreePlanName: 'Gratis',\n\t\tpremiumPlanName: 'Premium',\n\t\tpopularBadge: 'Más popular',\n\t\tunlockHeading: 'Desbloquea las funciones premium',\n\t\tsimulatePurchase: 'Simular compra',\n\t\tmockNotice:\n\t\t\t'Vista previa de desarrollo: las licencias y los pagos son simulados. No se realizará ningún cobro.',\n\t\tsellerProvidedBy: 'Licencia proporcionada por {name}',\n\t\tsellerUnavailable: 'Los datos del proveedor de la licencia no están disponibles.',\n\t\tsellerSupport: 'Asistencia de la extensión',\n\t\tsellerTerms: 'Condiciones de licencia',\n\t\tsellerRefunds: 'Política de reembolsos',\n\t\tsellerRole:\n\t\t\t'El autor se encarga de las funciones de la extensión y de los compromisos de la licencia. Extenshi proporciona las herramientas de pago y de recuperación de licencias.',\n\t\tlicenseTitle: 'Tu licencia',\n\t\tlicenseFallbackName: 'Licencia de la extensión',\n\t\tlicenseNone: 'No se ha encontrado ninguna licencia en esta instalación.',\n\t\tkindOneTime: 'Compra única',\n\t\tkindLifetime: 'Licencia vitalicia',\n\t\tkindSubscription: 'Suscripción',\n\t\tkindLicense: 'Licencia',\n\t\tstatusLine: 'Estado: {status}',\n\t\tstatusActive: 'activo',\n\t\tstatusGrace: 'período de gracia',\n\t\tstatusExpired: 'caducado',\n\t\tstatusNone: 'sin acceso',\n\t\taccessEnded: 'Acceso finalizado el {date}',\n\t\taccessUntil: 'Acceso hasta el {date}',\n\t\taccessRecordedEnd: 'Fecha de finalización registrada: {date}',\n\t\tsubscriptionLine: 'Suscripción: {status}',\n\t\trenewalCanceled: 'Renovación cancelada',\n\t\tperiodEnds: 'El período finaliza el {date}',\n\t\tsubActive: 'activa',\n\t\tsubTrialing: 'en período de prueba',\n\t\tsubPastDue: 'pago vencido',\n\t\tsubCanceled: 'cancelada',\n\t\tsubUnpaid: 'sin pagar',\n\t\tsubIncomplete: 'incompleta',\n\t\tsubIncompleteExpired: 'pago no completado',\n\t\tsubPaused: 'en pausa',\n\t\tlicenseOffline:\n\t\t\t'Conéctate a internet para verificar tu licencia. Las funciones de pago se suspenden si pasan 48 horas sin una verificación correcta. Tu compra no ha caducado.',\n\t\tlicenseCached: 'Se muestra la información de licencia guardada.',\n\t\tlicenseFresh: 'La información de la suscripción refleja la última actualización de pago procesada.',\n\t\tactionFailed:\n\t\t\t'No se pudo completar la solicitud. Inténtalo de nuevo o ponte en contacto con la asistencia de la extensión.',\n\t\tmanageBilling: 'Gestionar facturación',\n\t\tnoPortal:\n\t\t\t'No se abrió ningún portal de facturación. Puedes volver a intentarlo o ponerte en contacto con la asistencia de la extensión.',\n\t\tclose: 'Cerrar',\n\t\tpickerTitle: 'Elige un perfil de facturación',\n\t\tpickerDescription:\n\t\t\t'Las compras independientes pueden tener perfiles de facturación distintos. Elige uno para gestionar sus suscripciones y datos de pago.',\n\t\tpickerFirstRecorded: 'Registrado por primera vez el {date}',\n\t\tpickerCancel: 'Cancelar',\n\t\ttrialEndedTitle: 'Tu prueba gratuita ha terminado',\n\t\ttrialEndedDescription:\n\t\t\t'Las herramientas de la extensión están en pausa. Tu configuración se conserva y la encontrarás igual cuando mejores tu plan.',\n\t\ttrialEndedFeedback: 'Enviar comentarios',\n\t},\n\t'pt-BR': {\n\t\ttitle: 'Desbloqueie os recursos premium',\n\t\tdescription: 'Faça o upgrade para ter acesso completo a esta extensão.',\n\t\tupgrade: 'Fazer upgrade',\n\t\tcancel: 'Agora não',\n\t\tdismiss: 'Dispensar',\n\t\tremindLater: 'Lembrar mais tarde',\n\t\tcontinueFree: 'Continuar com a versão gratuita',\n\t\tcheckoutUnavailable: 'Compras temporariamente indisponíveis',\n\t\tperiodMonth: '/mês',\n\t\tperiodYear: '/ano',\n\t\tperiodOnce: 'pagamento único',\n\t\tfooter: 'O checkout seguro abre em uma nova guia.',\n\t\trestorePurchase: 'Restaurar compra',\n\t\tfeaturesHeading: 'Recursos premium',\n\t\tplansHeading: 'Escolha seu plano',\n\t\tfreePlanName: 'Gratuito',\n\t\tpremiumPlanName: 'Premium',\n\t\tpopularBadge: 'Mais popular',\n\t\tunlockHeading: 'Desbloqueie os recursos premium',\n\t\tsimulatePurchase: 'Simular compra',\n\t\tmockNotice: 'Prévia de desenvolvimento: licenças e pagamentos são simulados. Nenhum valor será cobrado.',\n\t\tsellerProvidedBy: 'Licença fornecida por {name}',\n\t\tsellerUnavailable: 'Os dados do fornecedor da licença não estão disponíveis.',\n\t\tsellerSupport: 'Suporte da extensão',\n\t\tsellerTerms: 'Termos de licença',\n\t\tsellerRefunds: 'Política de reembolso',\n\t\tsellerRole:\n\t\t\t'O autor é responsável pelo funcionamento da extensão e pelos compromissos da licença. A Extenshi fornece as ferramentas de pagamento e de recuperação de licenças.',\n\t\tlicenseTitle: 'Sua licença',\n\t\tlicenseFallbackName: 'Licença da extensão',\n\t\tlicenseNone: 'Nenhuma licença encontrada nesta instalação.',\n\t\tkindOneTime: 'Compra única',\n\t\tkindLifetime: 'Licença vitalícia',\n\t\tkindSubscription: 'Assinatura',\n\t\tkindLicense: 'Licença',\n\t\tstatusLine: 'Status: {status}',\n\t\tstatusActive: 'ativo',\n\t\tstatusGrace: 'período de carência',\n\t\tstatusExpired: 'expirado',\n\t\tstatusNone: 'sem acesso',\n\t\taccessEnded: 'Acesso encerrado em {date}',\n\t\taccessUntil: 'Acesso até {date}',\n\t\taccessRecordedEnd: 'Data de término registrada: {date}',\n\t\tsubscriptionLine: 'Assinatura: {status}',\n\t\trenewalCanceled: 'Renovação cancelada',\n\t\tperiodEnds: 'Período termina em {date}',\n\t\tsubActive: 'ativa',\n\t\tsubTrialing: 'em período de teste',\n\t\tsubPastDue: 'pagamento em atraso',\n\t\tsubCanceled: 'cancelada',\n\t\tsubUnpaid: 'não paga',\n\t\tsubIncomplete: 'incompleta',\n\t\tsubIncompleteExpired: 'pagamento não concluído',\n\t\tsubPaused: 'pausada',\n\t\tlicenseOffline:\n\t\t\t'Conecte-se à internet para verificar sua licença. Os recursos pagos são pausados após 48 horas sem uma verificação bem-sucedida. Sua compra não expirou.',\n\t\tlicenseCached: 'Exibindo as informações de licença salvas.',\n\t\tlicenseFresh: 'As informações da assinatura refletem a atualização de pagamento processada mais recente.',\n\t\tactionFailed:\n\t\t\t'Não foi possível concluir a solicitação. Tente novamente ou entre em contato com o suporte da extensão.',\n\t\tmanageBilling: 'Gerenciar cobrança',\n\t\tnoPortal:\n\t\t\t'O portal de cobrança não foi aberto. Você pode tentar novamente ou entrar em contato com o suporte da extensão.',\n\t\tclose: 'Fechar',\n\t\tpickerTitle: 'Escolha um perfil de cobrança',\n\t\tpickerDescription:\n\t\t\t'Compras diferentes podem ter perfis de cobrança diferentes. Escolha um perfil para gerenciar as assinaturas e os dados de pagamento vinculados a ele.',\n\t\tpickerFirstRecorded: 'Registrado pela primeira vez em {date}',\n\t\tpickerCancel: 'Cancelar',\n\t\ttrialEndedTitle: 'Seu teste gratuito terminou',\n\t\ttrialEndedDescription:\n\t\t\t'As ferramentas da extensão estão pausadas. Suas configurações foram mantidas e estarão lá quando você fizer o upgrade.',\n\t\ttrialEndedFeedback: 'Enviar feedback',\n\t},\n\tfr: {\n\t\ttitle: 'Débloquez les fonctionnalités premium',\n\t\tdescription: 'Passez à la version supérieure pour obtenir un accès complet à cette extension.',\n\t\tupgrade: 'Mettre à niveau',\n\t\tcancel: 'Pas maintenant',\n\t\tdismiss: 'Ignorer',\n\t\tremindLater: 'Me le rappeler plus tard',\n\t\tcontinueFree: 'Continuer avec la version gratuite',\n\t\tcheckoutUnavailable: 'Les achats sont temporairement indisponibles',\n\t\tperiodMonth: '/mois',\n\t\tperiodYear: '/an',\n\t\tperiodOnce: 'paiement unique',\n\t\tfooter: 'Le paiement sécurisé s’ouvre dans un nouvel onglet.',\n\t\trestorePurchase: 'Restaurer l’achat',\n\t\tfeaturesHeading: 'Fonctionnalités premium',\n\t\tplansHeading: 'Choisissez votre formule',\n\t\tfreePlanName: 'Gratuit',\n\t\tpremiumPlanName: 'Premium',\n\t\tpopularBadge: 'Le plus populaire',\n\t\tunlockHeading: 'Débloquez les fonctionnalités premium',\n\t\tsimulatePurchase: 'Simuler l’achat',\n\t\tmockNotice:\n\t\t\t'Aperçu de développement : les licences et les paiements sont simulés. Aucun paiement ne sera prélevé.',\n\t\tsellerProvidedBy: 'Licence fournie par {name}',\n\t\tsellerUnavailable: 'Les informations sur le fournisseur de la licence ne sont pas disponibles.',\n\t\tsellerSupport: 'Assistance pour l’extension',\n\t\tsellerTerms: 'Conditions de licence',\n\t\tsellerRefunds: 'Politique de remboursement',\n\t\tsellerRole:\n\t\t\t'L’auteur est responsable des fonctionnalités de l’extension et des engagements liés à la licence. Extenshi fournit les outils de paiement et de restauration des licences.',\n\t\tlicenseTitle: 'Votre licence',\n\t\tlicenseFallbackName: 'Licence de l’extension',\n\t\tlicenseNone: 'Aucune licence n’a été trouvée pour cette installation.',\n\t\tkindOneTime: 'Achat unique',\n\t\tkindLifetime: 'Licence à vie',\n\t\tkindSubscription: 'Abonnement',\n\t\tkindLicense: 'Licence',\n\t\tstatusLine: 'Statut : {status}',\n\t\tstatusActive: 'actif',\n\t\tstatusGrace: 'période de grâce',\n\t\tstatusExpired: 'expiré',\n\t\tstatusNone: 'aucun accès',\n\t\taccessEnded: 'Accès terminé le {date}',\n\t\taccessUntil: 'Accès jusqu’au {date}',\n\t\taccessRecordedEnd: 'Date de fin enregistrée : {date}',\n\t\tsubscriptionLine: 'Abonnement : {status}',\n\t\trenewalCanceled: 'Renouvellement annulé',\n\t\tperiodEnds: 'Fin de la période le {date}',\n\t\tsubActive: 'actif',\n\t\tsubTrialing: 'en période d’essai',\n\t\tsubPastDue: 'paiement en retard',\n\t\tsubCanceled: 'résilié',\n\t\tsubUnpaid: 'impayé',\n\t\tsubIncomplete: 'incomplet',\n\t\tsubIncompleteExpired: 'paiement non finalisé',\n\t\tsubPaused: 'en pause',\n\t\tlicenseOffline:\n\t\t\t'Connectez-vous à Internet pour vérifier votre licence. Les fonctionnalités payantes sont suspendues après 48 heures sans vérification réussie. Votre achat n’a pas expiré.',\n\t\tlicenseCached: 'Affichage des informations de licence enregistrées.',\n\t\tlicenseFresh: 'Les informations d’abonnement reflètent la dernière mise à jour de paiement traitée.',\n\t\tactionFailed:\n\t\t\t'Impossible de traiter la demande. Veuillez réessayer ou contacter l’assistance de l’extension.',\n\t\tmanageBilling: 'Gérer la facturation',\n\t\tnoPortal:\n\t\t\t'Le portail de facturation ne s’est pas ouvert. Vous pouvez réessayer ou contacter l’assistance de l’extension.',\n\t\tclose: 'Fermer',\n\t\tpickerTitle: 'Choisissez un profil de facturation',\n\t\tpickerDescription:\n\t\t\t'Des achats distincts peuvent avoir des profils de facturation distincts. Choisissez-en un pour gérer ses abonnements et ses informations de paiement.',\n\t\tpickerFirstRecorded: 'Enregistré pour la première fois le {date}',\n\t\tpickerCancel: 'Annuler',\n\t\ttrialEndedTitle: 'Votre essai gratuit est terminé',\n\t\ttrialEndedDescription:\n\t\t\t'Les outils de l’extension sont en pause. Vos paramètres sont conservés et vous les retrouverez après la mise à niveau.',\n\t\ttrialEndedFeedback: 'Donner votre avis',\n\t},\n\tde: {\n\t\ttitle: 'Premium-Funktionen freischalten',\n\t\tdescription: 'Hol dir mit einem Upgrade vollen Zugriff auf diese Erweiterung.',\n\t\tupgrade: 'Upgraden',\n\t\tcancel: 'Jetzt nicht',\n\t\tdismiss: 'Ausblenden',\n\t\tremindLater: 'Später erinnern',\n\t\tcontinueFree: 'Mit der kostenlosen Version fortfahren',\n\t\tcheckoutUnavailable: 'Käufe sind vorübergehend nicht möglich',\n\t\tperiodMonth: '/Monat',\n\t\tperiodYear: '/Jahr',\n\t\tperiodOnce: 'einmalig',\n\t\tfooter: 'Der sichere Bezahlvorgang öffnet sich in einem neuen Tab.',\n\t\trestorePurchase: 'Kauf wiederherstellen',\n\t\tfeaturesHeading: 'Premium-Funktionen',\n\t\tplansHeading: 'Wähle deinen Tarif',\n\t\tfreePlanName: 'Kostenlos',\n\t\tpremiumPlanName: 'Premium',\n\t\tpopularBadge: 'Am beliebtesten',\n\t\tunlockHeading: 'Premium-Funktionen freischalten',\n\t\tsimulatePurchase: 'Kauf simulieren',\n\t\tmockNotice:\n\t\t\t'Entwicklungsvorschau: Lizenzen und Zahlungen werden simuliert. Es wird keine Zahlung eingezogen.',\n\t\tsellerProvidedBy: 'Lizenz bereitgestellt von {name}',\n\t\tsellerUnavailable: 'Angaben zum Lizenzgeber sind nicht verfügbar.',\n\t\tsellerSupport: 'Support für die Erweiterung',\n\t\tsellerTerms: 'Lizenzbedingungen',\n\t\tsellerRefunds: 'Rückerstattungen',\n\t\tsellerRole:\n\t\t\t'Der Autor ist für die Funktionen der Erweiterung und die Lizenzzusagen verantwortlich. Extenshi stellt die Werkzeuge für Zahlung und Lizenzwiederherstellung bereit.',\n\t\tlicenseTitle: 'Deine Lizenz',\n\t\tlicenseFallbackName: 'Erweiterungslizenz',\n\t\tlicenseNone: 'Für diese Installation wurde keine Lizenz gefunden.',\n\t\tkindOneTime: 'Einmalkauf',\n\t\tkindLifetime: 'Lebenslange Lizenz',\n\t\tkindSubscription: 'Abonnement',\n\t\tkindLicense: 'Lizenz',\n\t\tstatusLine: 'Status: {status}',\n\t\tstatusActive: 'aktiv',\n\t\tstatusGrace: 'Kulanzfrist',\n\t\tstatusExpired: 'abgelaufen',\n\t\tstatusNone: 'kein Zugriff',\n\t\taccessEnded: 'Zugriff endete am {date}',\n\t\taccessUntil: 'Zugriff bis {date}',\n\t\taccessRecordedEnd: 'Erfasstes Enddatum: {date}',\n\t\tsubscriptionLine: 'Abonnement: {status}',\n\t\trenewalCanceled: 'Wird nicht verlängert',\n\t\tperiodEnds: 'Zeitraum endet am {date}',\n\t\tsubActive: 'aktiv',\n\t\tsubTrialing: 'Testphase',\n\t\tsubPastDue: 'Zahlung überfällig',\n\t\tsubCanceled: 'gekündigt',\n\t\tsubUnpaid: 'unbezahlt',\n\t\tsubIncomplete: 'unvollständig',\n\t\tsubIncompleteExpired: 'Zahlung nicht abgeschlossen',\n\t\tsubPaused: 'pausiert',\n\t\tlicenseOffline:\n\t\t\t'Stelle eine Internetverbindung her, um deine Lizenz zu prüfen. Kostenpflichtige Funktionen werden nach 48 Stunden ohne erfolgreiche Prüfung pausiert. Dein Kauf ist nicht abgelaufen.',\n\t\tlicenseCached: 'Gespeicherte Lizenzinformationen werden angezeigt.',\n\t\tlicenseFresh: 'Die Abonnementangaben entsprechen dem zuletzt verarbeiteten Zahlungsstand.',\n\t\tactionFailed:\n\t\t\t'Die Anfrage konnte nicht abgeschlossen werden. Bitte versuche es erneut oder wende dich an den Support für die Erweiterung.',\n\t\tmanageBilling: 'Abrechnung verwalten',\n\t\tnoPortal:\n\t\t\t'Das Abrechnungsportal wurde nicht geöffnet. Du kannst es erneut versuchen oder dich an den Support für die Erweiterung wenden.',\n\t\tclose: 'Schließen',\n\t\tpickerTitle: 'Abrechnungsprofil auswählen',\n\t\tpickerDescription:\n\t\t\t'Verschiedene Käufe können eigene Abrechnungsprofile haben. Wähle eines aus, um seine Abonnements und Zahlungsdaten zu verwalten.',\n\t\tpickerFirstRecorded: 'Erstmals erfasst am {date}',\n\t\tpickerCancel: 'Abbrechen',\n\t\ttrialEndedTitle: 'Dein kostenloser Testzeitraum ist abgelaufen',\n\t\ttrialEndedDescription:\n\t\t\t'Die Funktionen der Erweiterung sind pausiert. Deine Einstellungen bleiben erhalten und sind nach dem Upgrade wieder da.',\n\t\ttrialEndedFeedback: 'Feedback geben',\n\t},\n\tit: {\n\t\ttitle: 'Sblocca le funzionalità premium',\n\t\tdescription: 'Effettua l’upgrade per ottenere l’accesso completo a questa estensione.',\n\t\tupgrade: 'Effettua l’upgrade',\n\t\tcancel: 'Non ora',\n\t\tdismiss: 'Ignora',\n\t\tremindLater: 'Ricordamelo più tardi',\n\t\tcontinueFree: 'Continua con la versione gratuita',\n\t\tcheckoutUnavailable: 'Gli acquisti sono temporaneamente non disponibili',\n\t\tperiodMonth: '/mese',\n\t\tperiodYear: '/anno',\n\t\tperiodOnce: 'una tantum',\n\t\tfooter: 'Il checkout sicuro si apre in una nuova scheda.',\n\t\trestorePurchase: 'Ripristina acquisto',\n\t\tfeaturesHeading: 'Funzionalità premium',\n\t\tplansHeading: 'Scegli il tuo piano',\n\t\tfreePlanName: 'Gratuito',\n\t\tpremiumPlanName: 'Premium',\n\t\tpopularBadge: 'Il più scelto',\n\t\tunlockHeading: 'Sblocca le funzionalità premium',\n\t\tsimulatePurchase: 'Simula acquisto',\n\t\tmockNotice:\n\t\t\t'Anteprima di sviluppo: licenze e pagamenti sono simulati. Non verrà addebitato alcun pagamento.',\n\t\tsellerProvidedBy: 'Licenza fornita da {name}',\n\t\tsellerUnavailable: 'I dettagli del fornitore della licenza non sono disponibili.',\n\t\tsellerSupport: 'Assistenza per l’estensione',\n\t\tsellerTerms: 'Termini di licenza',\n\t\tsellerRefunds: 'Politica di rimborso',\n\t\tsellerRole:\n\t\t\t'L’autore è responsabile delle funzionalità dell’estensione e degli impegni relativi alla licenza. Extenshi fornisce gli strumenti di pagamento e di recupero della licenza.',\n\t\tlicenseTitle: 'La tua licenza',\n\t\tlicenseFallbackName: 'Licenza dell’estensione',\n\t\tlicenseNone: 'Nessuna licenza trovata in questa installazione.',\n\t\tkindOneTime: 'Acquisto una tantum',\n\t\tkindLifetime: 'Licenza a vita',\n\t\tkindSubscription: 'Abbonamento',\n\t\tkindLicense: 'Licenza',\n\t\tstatusLine: 'Stato: {status}',\n\t\tstatusActive: 'attivo',\n\t\tstatusGrace: 'periodo di tolleranza',\n\t\tstatusExpired: 'scaduto',\n\t\tstatusNone: 'nessun accesso',\n\t\taccessEnded: 'Accesso terminato il {date}',\n\t\taccessUntil: 'Accesso fino al {date}',\n\t\taccessRecordedEnd: 'Data di fine registrata: {date}',\n\t\tsubscriptionLine: 'Abbonamento: {status}',\n\t\trenewalCanceled: 'Rinnovo annullato',\n\t\tperiodEnds: 'Il periodo termina il {date}',\n\t\tsubActive: 'attivo',\n\t\tsubTrialing: 'in prova',\n\t\tsubPastDue: 'pagamento in ritardo',\n\t\tsubCanceled: 'disdetto',\n\t\tsubUnpaid: 'non pagato',\n\t\tsubIncomplete: 'incompleto',\n\t\tsubIncompleteExpired: 'pagamento non completato',\n\t\tsubPaused: 'in pausa',\n\t\tlicenseOffline:\n\t\t\t'Connettiti a internet per verificare la tua licenza. Le funzionalità a pagamento vengono sospese dopo 48 ore senza una verifica riuscita. Il tuo acquisto non è scaduto.',\n\t\tlicenseCached: 'Vengono mostrate le informazioni salvate sulla licenza.',\n\t\tlicenseFresh:\n\t\t\t'Le informazioni sull’abbonamento riflettono l’ultimo aggiornamento di pagamento elaborato.',\n\t\tactionFailed: 'Impossibile completare la richiesta. Riprova o contatta l’assistenza per l’estensione.',\n\t\tmanageBilling: 'Gestisci fatturazione',\n\t\tnoPortal:\n\t\t\t'Il portale di fatturazione non è stato aperto. Puoi riprovare o contattare l’assistenza per l’estensione.',\n\t\tclose: 'Chiudi',\n\t\tpickerTitle: 'Scegli un profilo di fatturazione',\n\t\tpickerDescription:\n\t\t\t'Acquisti diversi possono avere profili di fatturazione diversi. Scegline uno per gestirne gli abbonamenti e i dati di pagamento.',\n\t\tpickerFirstRecorded: 'Registrato per la prima volta il {date}',\n\t\tpickerCancel: 'Annulla',\n\t\ttrialEndedTitle: 'La tua prova gratuita è terminata',\n\t\ttrialEndedDescription:\n\t\t\t'Gli strumenti dell’estensione sono in pausa. Le tue impostazioni sono conservate e le ritroverai dopo l’upgrade.',\n\t\ttrialEndedFeedback: 'Invia un feedback',\n\t},\n\tru: {\n\t\ttitle: 'Откройте доступ к премиум-функциям',\n\t\tdescription: 'Перейдите на премиум, чтобы получить полный доступ к этому расширению.',\n\t\tupgrade: 'Перейти на премиум',\n\t\tcancel: 'Не сейчас',\n\t\tdismiss: 'Скрыть',\n\t\tremindLater: 'Напомнить позже',\n\t\tcontinueFree: 'Продолжить в бесплатной версии',\n\t\tcheckoutUnavailable: 'Покупки временно недоступны',\n\t\tperiodMonth: '/мес.',\n\t\tperiodYear: '/год',\n\t\tperiodOnce: 'разово',\n\t\tfooter: 'Защищённая страница оплаты откроется в новой вкладке.',\n\t\trestorePurchase: 'Восстановить покупку',\n\t\tfeaturesHeading: 'Премиум-функции',\n\t\tplansHeading: 'Выберите тарифный план',\n\t\tfreePlanName: 'Бесплатный',\n\t\tpremiumPlanName: 'Премиум',\n\t\tpopularBadge: 'Самый популярный',\n\t\tunlockHeading: 'Откройте доступ к премиум-функциям',\n\t\tsimulatePurchase: 'Имитировать покупку',\n\t\tmockNotice: 'Режим разработки: лицензии и платежи имитируются. Деньги не будут списаны.',\n\t\tsellerProvidedBy: 'Лицензию предоставляет {name}',\n\t\tsellerUnavailable: 'Сведения о поставщике лицензии недоступны.',\n\t\tsellerSupport: 'Поддержка расширения',\n\t\tsellerTerms: 'Условия лицензии',\n\t\tsellerRefunds: 'Возврат средств',\n\t\tsellerRole:\n\t\t\t'Автор отвечает за работу расширения и обязательства по лицензии. Extenshi предоставляет инструменты для оплаты и восстановления лицензий.',\n\t\tlicenseTitle: 'Ваша лицензия',\n\t\tlicenseFallbackName: 'Лицензия на расширение',\n\t\tlicenseNone: 'Для этой установки лицензия не найдена.',\n\t\tkindOneTime: 'Разовая покупка',\n\t\tkindLifetime: 'Бессрочная лицензия',\n\t\tkindSubscription: 'Подписка',\n\t\tkindLicense: 'Лицензия',\n\t\tstatusLine: 'Статус: {status}',\n\t\tstatusActive: 'действует',\n\t\tstatusGrace: 'льготный период',\n\t\tstatusExpired: 'срок истёк',\n\t\tstatusNone: 'нет доступа',\n\t\taccessEnded: 'Доступ закончился: {date}',\n\t\taccessUntil: 'Доступ до {date}',\n\t\taccessRecordedEnd: 'Зафиксированная дата окончания: {date}',\n\t\tsubscriptionLine: 'Подписка: {status}',\n\t\trenewalCanceled: 'Продление отменено',\n\t\tperiodEnds: 'Период заканчивается: {date}',\n\t\tsubActive: 'активна',\n\t\tsubTrialing: 'пробный период',\n\t\tsubPastDue: 'платёж просрочен',\n\t\tsubCanceled: 'отменена',\n\t\tsubUnpaid: 'не оплачена',\n\t\tsubIncomplete: 'ожидает первого платежа',\n\t\tsubIncompleteExpired: 'платёж не завершён',\n\t\tsubPaused: 'приостановлена',\n\t\tlicenseOffline:\n\t\t\t'Подключитесь к интернету, чтобы проверить лицензию. Если успешной проверки не было 48 часов, платные функции приостанавливаются. Срок действия вашей покупки не истёк.',\n\t\tlicenseCached: 'Показаны сохранённые сведения о лицензии.',\n\t\tlicenseFresh: 'Сведения о подписке соответствуют последнему обработанному обновлению платежа.',\n\t\tactionFailed: 'Не удалось выполнить запрос. Попробуйте ещё раз или обратитесь в поддержку расширения.',\n\t\tmanageBilling: 'Управление оплатой',\n\t\tnoPortal: 'Портал оплаты не открылся. Можно повторить попытку или обратиться в поддержку расширения.',\n\t\tclose: 'Закрыть',\n\t\tpickerTitle: 'Выберите платёжный профиль',\n\t\tpickerDescription:\n\t\t\t'У разных покупок могут быть разные платёжные профили. Выберите профиль, чтобы управлять его подписками и платёжными данными.',\n\t\tpickerFirstRecorded: 'Впервые зафиксирован: {date}',\n\t\tpickerCancel: 'Отмена',\n\t\ttrialEndedTitle: 'Бесплатный пробный период закончился',\n\t\ttrialEndedDescription:\n\t\t\t'Инструменты расширения приостановлены. Ваши настройки сохранены и будут на месте после перехода на премиум.',\n\t\ttrialEndedFeedback: 'Оставить отзыв',\n\t},\n\tja: {\n\t\ttitle: 'プレミアム機能をアンロック',\n\t\tdescription: 'アップグレードすると、この拡張機能のすべての機能をご利用いただけます。',\n\t\tupgrade: 'アップグレード',\n\t\tcancel: '今はしない',\n\t\tdismiss: '非表示にする',\n\t\tremindLater: 'あとで通知する',\n\t\tcontinueFree: '無料版のまま使い続ける',\n\t\tcheckoutUnavailable: '一時的に購入できません',\n\t\tperiodMonth: '/月',\n\t\tperiodYear: '/年',\n\t\tperiodOnce: '買い切り',\n\t\tfooter: '安全なチェックアウト画面が新しいタブで開きます。',\n\t\trestorePurchase: '購入を復元',\n\t\tfeaturesHeading: 'プレミアム機能',\n\t\tplansHeading: 'プランを選択',\n\t\tfreePlanName: '無料',\n\t\tpremiumPlanName: 'プレミアム',\n\t\tpopularBadge: '一番人気',\n\t\tunlockHeading: 'プレミアム機能をアンロック',\n\t\tsimulatePurchase: '購入をシミュレート',\n\t\tmockNotice: '開発用プレビュー:ライセンスと支払いはシミュレーションです。実際の請求は発生しません。',\n\t\tsellerProvidedBy: 'ライセンス提供者:{name}',\n\t\tsellerUnavailable: 'ライセンス提供者の情報を取得できません。',\n\t\tsellerSupport: '拡張機能のサポート',\n\t\tsellerTerms: 'ライセンス条件',\n\t\tsellerRefunds: '返金ポリシー',\n\t\tsellerRole:\n\t\t\t'拡張機能の機能とライセンス上の約束については、開発者が責任を負います。Extenshiは、お支払いとライセンス復元のためのツールを提供します。',\n\t\tlicenseTitle: 'ご利用のライセンス',\n\t\tlicenseFallbackName: '拡張機能のライセンス',\n\t\tlicenseNone: 'このインストール環境ではライセンスが見つかりませんでした。',\n\t\tkindOneTime: '買い切り',\n\t\tkindLifetime: 'ライフタイムライセンス',\n\t\tkindSubscription: 'サブスクリプション',\n\t\tkindLicense: 'ライセンス',\n\t\tstatusLine: 'ステータス:{status}',\n\t\tstatusActive: '有効',\n\t\tstatusGrace: '猶予期間中',\n\t\tstatusExpired: '期限切れ',\n\t\tstatusNone: '利用不可',\n\t\taccessEnded: '利用終了日時:{date}',\n\t\taccessUntil: '利用期限:{date}',\n\t\taccessRecordedEnd: '記録上の終了日時:{date}',\n\t\tsubscriptionLine: 'サブスクリプション:{status}',\n\t\trenewalCanceled: '更新停止済み',\n\t\tperiodEnds: '期間終了日:{date}',\n\t\tsubActive: '有効',\n\t\tsubTrialing: 'トライアル中',\n\t\tsubPastDue: '支払い期限超過',\n\t\tsubCanceled: '解約済み',\n\t\tsubUnpaid: '未払い',\n\t\tsubIncomplete: '手続き未完了',\n\t\tsubIncompleteExpired: '支払い未完了',\n\t\tsubPaused: '一時停止中',\n\t\tlicenseOffline:\n\t\t\t'ライセンスを確認するには、インターネットに接続してください。確認に成功しないまま48時間が経過すると、有料機能は一時停止されます。ご購入が失効したわけではありません。',\n\t\tlicenseCached: '保存済みのライセンス情報を表示しています。',\n\t\tlicenseFresh: 'サブスクリプション情報には、処理済みの最新の支払い情報が反映されています。',\n\t\tactionFailed:\n\t\t\t'リクエストを完了できませんでした。もう一度お試しいただくか、拡張機能のサポートにお問い合わせください。',\n\t\tmanageBilling: '請求情報を管理',\n\t\tnoPortal: '請求ポータルを開けませんでした。再試行するか、拡張機能のサポートにお問い合わせください。',\n\t\tclose: '閉じる',\n\t\tpickerTitle: '請求プロファイルを選択',\n\t\tpickerDescription:\n\t\t\t'購入ごとに別々の請求プロファイルがある場合があります。サブスクリプションと支払い情報を管理するプロファイルを1つ選択してください。',\n\t\tpickerFirstRecorded: '初回記録日:{date}',\n\t\tpickerCancel: 'キャンセル',\n\t\ttrialEndedTitle: '無料トライアルが終了しました',\n\t\ttrialEndedDescription:\n\t\t\t'拡張機能のツールは一時停止しています。設定は保存されており、アップグレード後もそのままご利用いただけます。',\n\t\ttrialEndedFeedback: 'フィードバックを送信',\n\t},\n\tko: {\n\t\ttitle: '프리미엄 기능 잠금 해제',\n\t\tdescription: '업그레이드하면 이 확장 프로그램의 모든 기능을 이용할 수 있습니다.',\n\t\tupgrade: '업그레이드',\n\t\tcancel: '나중에',\n\t\tdismiss: '닫기',\n\t\tremindLater: '나중에 다시 알림',\n\t\tcontinueFree: '무료 버전으로 계속하기',\n\t\tcheckoutUnavailable: '일시적으로 구매할 수 없습니다',\n\t\tperiodMonth: '/월',\n\t\tperiodYear: '/년',\n\t\tperiodOnce: '일회성',\n\t\tfooter: '안전한 결제 페이지가 새 탭에서 열립니다.',\n\t\trestorePurchase: '구매 복원',\n\t\tfeaturesHeading: '프리미엄 기능',\n\t\tplansHeading: '요금제 선택',\n\t\tfreePlanName: '무료',\n\t\tpremiumPlanName: '프리미엄',\n\t\tpopularBadge: '가장 인기',\n\t\tunlockHeading: '프리미엄 기능 잠금 해제',\n\t\tsimulatePurchase: '구매 시뮬레이션',\n\t\tmockNotice: '개발용 미리보기: 라이선스와 결제는 시뮬레이션됩니다. 실제로 결제되지 않습니다.',\n\t\tsellerProvidedBy: '라이선스 제공자: {name}',\n\t\tsellerUnavailable: '라이선스 제공자 정보를 확인할 수 없습니다.',\n\t\tsellerSupport: '확장 프로그램 지원',\n\t\tsellerTerms: '라이선스 약관',\n\t\tsellerRefunds: '환불 정책',\n\t\tsellerRole:\n\t\t\t'확장 프로그램의 기능과 라이선스 관련 약속은 개발자가 책임집니다. Extenshi는 결제 및 라이선스 복구 도구를 제공합니다.',\n\t\tlicenseTitle: '내 라이선스',\n\t\tlicenseFallbackName: '확장 프로그램 라이선스',\n\t\tlicenseNone: '이 설치 환경에서 라이선스를 찾지 못했습니다.',\n\t\tkindOneTime: '일회성 구매',\n\t\tkindLifetime: '평생 라이선스',\n\t\tkindSubscription: '구독',\n\t\tkindLicense: '라이선스',\n\t\tstatusLine: '상태: {status}',\n\t\tstatusActive: '활성',\n\t\tstatusGrace: '유예 기간 중',\n\t\tstatusExpired: '만료됨',\n\t\tstatusNone: '이용 권한 없음',\n\t\taccessEnded: '이용 종료 일시: {date}',\n\t\taccessUntil: '이용 기한: {date}',\n\t\taccessRecordedEnd: '기록된 종료 일시: {date}',\n\t\tsubscriptionLine: '구독: {status}',\n\t\trenewalCanceled: '갱신 취소됨',\n\t\tperiodEnds: '기간 종료일: {date}',\n\t\tsubActive: '활성',\n\t\tsubTrialing: '체험 중',\n\t\tsubPastDue: '결제 연체',\n\t\tsubCanceled: '해지됨',\n\t\tsubUnpaid: '미결제',\n\t\tsubIncomplete: '미완료',\n\t\tsubIncompleteExpired: '결제 미완료',\n\t\tsubPaused: '일시 중지됨',\n\t\tlicenseOffline:\n\t\t\t'라이선스를 확인하려면 인터넷에 연결해 주세요. 확인에 성공하지 못한 채 48시간이 지나면 유료 기능이 일시 중지됩니다. 구매가 만료된 것은 아닙니다.',\n\t\tlicenseCached: '저장된 라이선스 정보를 표시하고 있습니다.',\n\t\tlicenseFresh: '구독 정보에는 가장 최근에 처리된 결제 내역이 반영되어 있습니다.',\n\t\tactionFailed: '요청을 완료할 수 없습니다. 다시 시도하거나 확장 프로그램 지원 창구에 문의해 주세요.',\n\t\tmanageBilling: '결제 관리',\n\t\tnoPortal: '결제 포털이 열리지 않았습니다. 다시 시도하거나 확장 프로그램 지원 창구에 문의해 주세요.',\n\t\tclose: '닫기',\n\t\tpickerTitle: '결제 프로필 선택',\n\t\tpickerDescription:\n\t\t\t'구매마다 결제 프로필이 다를 수 있습니다. 구독과 결제 정보를 관리할 프로필을 하나 선택해 주세요.',\n\t\tpickerFirstRecorded: '최초 기록일: {date}',\n\t\tpickerCancel: '취소',\n\t\ttrialEndedTitle: '무료 체험 기간이 종료되었습니다',\n\t\ttrialEndedDescription:\n\t\t\t'확장 프로그램의 도구가 일시 중지되었습니다. 설정은 그대로 저장되어 있으며 업그레이드하면 다시 사용할 수 있습니다.',\n\t\ttrialEndedFeedback: '의견 보내기',\n\t},\n\t'zh-CN': {\n\t\ttitle: '解锁高级功能',\n\t\tdescription: '升级即可完整使用此扩展程序。',\n\t\tupgrade: '升级',\n\t\tcancel: '以后再说',\n\t\tdismiss: '忽略',\n\t\tremindLater: '稍后提醒我',\n\t\tcontinueFree: '继续使用免费版',\n\t\tcheckoutUnavailable: '暂时无法购买',\n\t\tperiodMonth: '/月',\n\t\tperiodYear: '/年',\n\t\tperiodOnce: '一次性',\n\t\tfooter: '安全结账页面将在新标签页中打开。',\n\t\trestorePurchase: '恢复购买',\n\t\tfeaturesHeading: '高级功能',\n\t\tplansHeading: '选择您的方案',\n\t\tfreePlanName: '免费版',\n\t\tpremiumPlanName: '高级版',\n\t\tpopularBadge: '最受欢迎',\n\t\tunlockHeading: '解锁高级功能',\n\t\tsimulatePurchase: '模拟购买',\n\t\tmockNotice: '开发预览:许可证和付款均为模拟,不会实际扣款。',\n\t\tsellerProvidedBy: '许可证由 {name} 提供',\n\t\tsellerUnavailable: '无法获取许可证提供方的详细信息。',\n\t\tsellerSupport: '扩展程序支持',\n\t\tsellerTerms: '许可条款',\n\t\tsellerRefunds: '退款政策',\n\t\tsellerRole: '作者负责扩展程序的功能及许可证相关承诺。Extenshi 提供支付及许可证恢复工具。',\n\t\tlicenseTitle: '您的许可证',\n\t\tlicenseFallbackName: '扩展程序许可证',\n\t\tlicenseNone: '此安装中未找到许可证。',\n\t\tkindOneTime: '一次性购买',\n\t\tkindLifetime: '终身许可证',\n\t\tkindSubscription: '订阅',\n\t\tkindLicense: '许可证',\n\t\tstatusLine: '状态:{status}',\n\t\tstatusActive: '有效',\n\t\tstatusGrace: '宽限期',\n\t\tstatusExpired: '已过期',\n\t\tstatusNone: '无使用权限',\n\t\taccessEnded: '使用权限已于 {date} 结束',\n\t\taccessUntil: '可使用至 {date}',\n\t\taccessRecordedEnd: '记录的结束日期:{date}',\n\t\tsubscriptionLine: '订阅:{status}',\n\t\trenewalCanceled: '已取消续订',\n\t\tperiodEnds: '当前计费周期于 {date} 结束',\n\t\tsubActive: '有效',\n\t\tsubTrialing: '试用中',\n\t\tsubPastDue: '付款逾期',\n\t\tsubCanceled: '已取消',\n\t\tsubUnpaid: '未付款',\n\t\tsubIncomplete: '未完成',\n\t\tsubIncompleteExpired: '付款未完成',\n\t\tsubPaused: '已暂停',\n\t\tlicenseOffline:\n\t\t\t'请连接互联网以验证您的许可证。如果连续48小时未能成功验证,付费功能将暂停。您的购买仍然有效。',\n\t\tlicenseCached: '正在显示已保存的许可证信息。',\n\t\tlicenseFresh: '订阅信息反映的是最近一次已处理的付款更新。',\n\t\tactionFailed: '无法完成请求。请重试或联系扩展程序支持。',\n\t\tmanageBilling: '管理账单',\n\t\tnoPortal: '未能打开账单门户。您可以重试或联系扩展程序支持。',\n\t\tclose: '关闭',\n\t\tpickerTitle: '选择账单资料',\n\t\tpickerDescription: '不同的购买可以有各自的账单资料。请选择一个,以管理其订阅和付款信息。',\n\t\tpickerFirstRecorded: '首次记录于 {date}',\n\t\tpickerCancel: '取消',\n\t\ttrialEndedTitle: '免费试用已结束',\n\t\ttrialEndedDescription: '扩展程序的工具已暂停。您的设置已保留,升级后即可继续使用。',\n\t\ttrialEndedFeedback: '提交反馈',\n\t},\n\tar: {\n\t\ttitle: 'احصل على الميزات المميزة',\n\t\tdescription: 'قم بالترقية للوصول الكامل إلى هذه الإضافة.',\n\t\tupgrade: 'ترقية',\n\t\tcancel: 'ليس الآن',\n\t\tdismiss: 'تجاهل',\n\t\tremindLater: 'ذكّرني لاحقًا',\n\t\tcontinueFree: 'المتابعة بالإصدار المجاني',\n\t\tcheckoutUnavailable: 'عمليات الشراء غير متاحة مؤقتًا',\n\t\tperiodMonth: '/شهر',\n\t\tperiodYear: '/سنة',\n\t\tperiodOnce: 'لمرة واحدة',\n\t\tfooter: 'تُفتح صفحة الدفع الآمن في علامة تبويب جديدة.',\n\t\trestorePurchase: 'استعادة الشراء',\n\t\tfeaturesHeading: 'الميزات المميزة',\n\t\tplansHeading: 'اختر خطتك',\n\t\tfreePlanName: 'مجاني',\n\t\tpremiumPlanName: 'مميز',\n\t\tpopularBadge: 'الأكثر رواجًا',\n\t\tunlockHeading: 'احصل على الميزات المميزة',\n\t\tsimulatePurchase: 'محاكاة الشراء',\n\t\tmockNotice: 'معاينة التطوير: تجري محاكاة التراخيص والمدفوعات، ولن يُحصَّل أي مبلغ.',\n\t\tsellerProvidedBy: 'الترخيص مقدَّم من البائع {name}',\n\t\tsellerUnavailable: 'بيانات مانح الترخيص غير متاحة.',\n\t\tsellerSupport: 'دعم الإضافة',\n\t\tsellerTerms: 'شروط الترخيص',\n\t\tsellerRefunds: 'سياسة استرداد المبالغ',\n\t\tsellerRole:\n\t\t\t'يتحمّل مطوّر الإضافة المسؤولية عن وظائفها وعن التزامات الترخيص، وتوفّر Extenshi أدوات الدفع واستعادة التراخيص.',\n\t\tlicenseTitle: 'ترخيصك',\n\t\tlicenseFallbackName: 'ترخيص الإضافة',\n\t\tlicenseNone: 'لم يُعثر على أي ترخيص في هذا التثبيت.',\n\t\tkindOneTime: 'شراء لمرة واحدة',\n\t\tkindLifetime: 'ترخيص مدى الحياة',\n\t\tkindSubscription: 'اشتراك',\n\t\tkindLicense: 'ترخيص',\n\t\tstatusLine: 'الحالة: {status}',\n\t\tstatusActive: 'نشطة',\n\t\tstatusGrace: 'في فترة السماح',\n\t\tstatusExpired: 'منتهية الصلاحية',\n\t\tstatusNone: 'بلا وصول',\n\t\taccessEnded: 'انتهى الوصول في {date}',\n\t\taccessUntil: 'الوصول متاح حتى {date}',\n\t\taccessRecordedEnd: 'تاريخ الانتهاء المسجَّل: {date}',\n\t\tsubscriptionLine: 'الاشتراك: {status}',\n\t\trenewalCanceled: 'أُلغي التجديد',\n\t\tperiodEnds: 'تنتهي الفترة الحالية في {date}',\n\t\tsubActive: 'نشط',\n\t\tsubTrialing: 'فترة تجريبية',\n\t\tsubPastDue: 'متأخر السداد',\n\t\tsubCanceled: 'ملغى',\n\t\tsubUnpaid: 'غير مدفوع',\n\t\tsubIncomplete: 'غير مكتمل',\n\t\tsubIncompleteExpired: 'لم يكتمل الدفع',\n\t\tsubPaused: 'متوقف مؤقتًا',\n\t\tlicenseOffline:\n\t\t\t'اتصل بالإنترنت للتحقق من ترخيصك. تتوقف الميزات المدفوعة مؤقتًا إذا مرّت 48 ساعة دون تحقق ناجح. لم تنتهِ صلاحية عملية الشراء.',\n\t\tlicenseCached: 'تُعرض معلومات الترخيص المحفوظة.',\n\t\tlicenseFresh: 'تعكس معلومات الاشتراك آخر تحديث للدفع تمت معالجته.',\n\t\tactionFailed: 'تعذّر إكمال الطلب. يُرجى المحاولة مرة أخرى أو التواصل مع دعم الإضافة.',\n\t\tmanageBilling: 'إدارة الفوترة',\n\t\tnoPortal: 'لم تُفتح بوابة الفوترة. يمكنك المحاولة مرة أخرى أو التواصل مع دعم الإضافة.',\n\t\tclose: 'إغلاق',\n\t\tpickerTitle: 'اختر ملف فوترة',\n\t\tpickerDescription:\n\t\t\t'يمكن أن تكون لعمليات الشراء المنفصلة ملفات فوترة منفصلة. اختر ملفًا منها لإدارة اشتراكاته وتفاصيل الدفع الخاصة به.',\n\t\tpickerFirstRecorded: 'سُجِّل لأول مرة في {date}',\n\t\tpickerCancel: 'إلغاء',\n\t\ttrialEndedTitle: 'انتهت فترتك التجريبية المجانية',\n\t\ttrialEndedDescription: 'أدوات الإضافة متوقفة مؤقتًا. إعداداتك محفوظة وستجدها كما هي بعد الترقية.',\n\t\ttrialEndedFeedback: 'إرسال ملاحظات',\n\t},\n}\n// END GENERATED TRANSLATIONS\n\n/** Our dictionary language for a tag: exact, then pt → pt-BR, zh(-CN/SG/Hans) → zh-CN, then the bare language. */\nexport function sdkLocale(locale: string | null | undefined): SdkLocale {\n\tconst tag = wireLocale(locale)\n\tif (!tag) return 'en'\n\tconst exact = SDK_LOCALES.find((l) => l.toLowerCase() === tag.toLowerCase())\n\tif (exact) return exact\n\tconst [lang, region] = tag.split('-')\n\tif (lang === 'pt') return 'pt-BR'\n\t// Traditional-script regions read English rather than Simplified characters.\n\tif (lang === 'zh') return region && ['TW', 'HK', 'MO'].includes(region) ? 'en' : 'zh-CN'\n\treturn SDK_LOCALES.find((l) => l === lang) ?? 'en'\n}\n\nexport function sdkDir(locale: string | null | undefined): 'ltr' | 'rtl' {\n\tconst lang = wireLocale(locale)?.split('-')[0]\n\treturn lang && ['ar', 'he', 'fa', 'ur'].includes(lang) ? 'rtl' : 'ltr'\n}\n\n/** English merged with the translation for `locale`. */\nexport function sdkStrings(locale: string | null | undefined): SdkStrings {\n\tconst tag = sdkLocale(locale)\n\treturn tag === 'en' ? SDK_STRINGS_EN : { ...SDK_STRINGS_EN, ...TRANSLATIONS[tag] }\n}\n\n/** Fill `{placeholders}` once; a value containing braces is inserted literally. */\nexport function fill(message: string, values: Record<string, string>): string {\n\treturn message.replace(/\\{([a-z]+)\\}/g, (whole, key: string) => values[key] ?? whole)\n}\n\n/** The raw translation block, for completeness tests. */\nexport function sdkTranslations(locale: Exclude<SdkLocale, 'en'>): SdkStrings | undefined {\n\treturn TRANSLATIONS[locale]\n}\n","/**\n * Buyer-facing withdrawal-waiver text (EU/EEA digital content, Directive\n * 2011/83/EU art. 16(m); UK CCR 2013 reg. 37), per text version and SDK\n * language. Its own module, not part of the paywall dictionary, so Lite can\n * show it without bundling every paywall string.\n *\n * The recorded consent names the version, so a version's words never change:\n * new wording is a new version here and a new PAY_WITHDRAWAL_WAIVER_VERSION.\n *\n * MIRRORED in shared-types/pay-withdrawal-waiver.ts, which the purchase\n * confirmation email quotes; shared-types/pay-withdrawal-waiver.test.ts fails\n * unless both copies are byte-identical. Change them together.\n */\n\nimport { fill, type SdkLocale, sdkLocale } from '../paywall/i18n.js'\nimport { PAY_WITHDRAWAL_WAIVER_VERSION } from '../types/contract.js'\n\nexport const WITHDRAWAL_WAIVER_TEXTS: Readonly<Record<string, Readonly<Record<SdkLocale, string>>>> = {\n\t[PAY_WITHDRAWAL_WAIVER_VERSION]: {\n\t\ten: 'I agree that {seller} starts supplying the digital content immediately, and I acknowledge that I lose my right of withdrawal once supply has begun.',\n\t\tes: 'Acepto que {seller} comience a suministrar el contenido digital de inmediato y reconozco que pierdo mi derecho de desistimiento una vez iniciado el suministro.',\n\t\t'pt-BR':\n\t\t\t'Concordo que {seller} comece a fornecer o conteúdo digital imediatamente e reconheço que perco meu direito de arrependimento assim que o fornecimento tiver início.',\n\t\tfr: 'J’accepte que {seller} commence immédiatement la fourniture du contenu numérique et je reconnais perdre mon droit de rétractation dès le début de la fourniture.',\n\t\tde: 'Ich stimme zu, dass {seller} sofort mit der Bereitstellung der digitalen Inhalte beginnt, und ich nehme zur Kenntnis, dass ich mit Beginn der Bereitstellung mein Widerrufsrecht verliere.',\n\t\tit: 'Accetto che {seller} inizi immediatamente la fornitura del contenuto digitale e riconosco di perdere il mio diritto di recesso una volta iniziata la fornitura.',\n\t\tru: 'Я соглашаюсь с тем, что {seller} немедленно начнёт предоставление цифрового контента, и подтверждаю, что утрачиваю право на отказ от договора с момента начала предоставления.',\n\t\tja: '{seller}がデジタルコンテンツの提供を直ちに開始することに同意し、提供の開始後は撤回権を失うことを了承します。',\n\t\tko: '{seller}의 디지털 콘텐츠 제공이 즉시 시작되는 것에 동의하며, 제공이 시작되면 청약철회권을 상실한다는 점을 확인합니다.',\n\t\t'zh-CN': '我同意 {seller} 立即开始提供数字内容,并确认一旦开始提供,我将失去撤回权。',\n\t\tar: 'أوافق على أن يبدأ {seller} فورًا في تقديم المحتوى الرقمي، وأُقرّ بأنني أفقد حقي في العدول عن العقد بمجرد بدء التقديم.',\n\t},\n}\n\n/**\n * The waiver text to show for `serverVersion`, and the version to send with\n * the consent. A version this SDK does not know (a newer server) shows this\n * SDK's current text and sends its version: the consent always names the words\n * actually shown.\n */\nexport function withdrawalWaiverText(\n\tserverVersion: string,\n\tlocale: string | null | undefined,\n\tseller: string,\n): { version: string; text: string } {\n\t// Own keys only: `toString` / `__proto__` from a server are just unknown versions.\n\tconst known = Object.keys(WITHDRAWAL_WAIVER_TEXTS).includes(serverVersion)\n\tconst version = known ? serverVersion : PAY_WITHDRAWAL_WAIVER_VERSION\n\treturn { version, text: fill(WITHDRAWAL_WAIVER_TEXTS[version][sdkLocale(locale)], { seller }) }\n}\n","/**\n * `ExtenshiPayLite` — entitlement, feature gating and hosted checkout, without\n * the paywall UI. This is what the `lite` bundle exports; the full `ExtenshiPay`\n * extends it with `getOffer()` / `showPaywall()`.\n *\n * Data that leaves the extension: `publishableKey`, `endUserRef`, `sku`,\n * `locale`, checkout session IDs and, with a server trial, the trial start date\n * the server issued (`trialStartedHint`, kept in storage.sync). Explicit recovery also sends its session ID,\n * challenge and claim secret (POST body). Email stays on the hosted page. With cloud backup, the\n * storage token goes only to `/v1/storage` (as a bearer), never in a message to a content script.\n */\n\nimport { MockTransport } from '../api/mock.js'\nimport { PayApi } from '../api/pay-api.js'\nimport { HttpTransport, type Transport } from '../api/transport.js'\nimport { CheckoutManager } from '../payment/checkout.js'\nimport { CloudBackup } from '../payment/cloud-backup.js'\nimport { EntitlementManager, MAX_CLOCK_SKEW_MS } from '../payment/entitlement.js'\nimport { checkFeatures, hasFeature, isEntitled, isLive } from '../payment/features.js'\nimport { createRecoveryStorage, RecoveryManager } from '../payment/recovery.js'\nimport { PUBLIC_KEY_RE, type PublicKeySource, verifyWithKeys } from '../payment/signature.js'\nimport { TrialNotifier } from '../payment/trial.js'\nimport { withdrawalWaiverText } from '../payment/withdrawal-waiver.js'\nimport type { ExtenshiPayConfig, ResolvedConfig } from '../types/config.js'\nimport type { PayOfferResponse } from '../types/contract.js'\nimport { PAY_END_USER_REF_RE } from '../types/contract.js'\nimport type {\n\tCheckoutOptions,\n\tCheckoutResult,\n\tCustomerPortalOptions,\n\tEntitlement,\n\tGetEntitlementOptions,\n\tLicenseSummary,\n\tRequireFeatureOptions,\n\tRestoreOptions,\n\tRestoreResult,\n\tTrialState,\n} from '../types/entitlement.js'\nimport { ERROR_CODES, ExtenshiPayError } from '../types/errors.js'\nimport type { ExtenshiPayEvents } from '../types/events.js'\nimport { logger } from '../utils/logger.js'\nimport { VERSION } from '../version.js'\nimport { resolveConfig } from './config.js'\nimport { EventEmitter, type Listener } from './event-emitter.js'\nimport { END_USER_REF_STORAGE_KEY, getOrCreateEndUserRef } from './identity.js'\nimport { createStorage, createSyncStorage, type StorageAdapter } from './storage.js'\n\n/** Server-side offer cache is 5 min; mirror it in memory. */\nconst OFFER_TTL_MS = 5 * 60 * 1000\n\n/** Injection points for tests and unusual hosts. */\nexport interface ExtenshiPayDeps {\n\tstorage?: StorageAdapter\n\t/** Where the trial start is synced (default `storage.sync`); null turns syncing off. */\n\tsyncStorage?: StorageAdapter | null\n\t/** Trusted extension-only storage; never share this adapter with content scripts. */\n\trecoveryStorage?: StorageAdapter\n\ttransport?: Transport\n\tfetch?: typeof fetch\n\topenUrl?: (url: string) => void | Promise<void>\n\tnow?: () => number\n}\n\nexport class ExtenshiPayLite {\n\tstatic readonly version = VERSION\n\n\tprotected readonly config: ResolvedConfig\n\tprotected readonly emitter = new EventEmitter<ExtenshiPayEvents>()\n\tprotected readonly storage: StorageAdapter\n\tprotected readonly api: PayApi\n\tprotected readonly entitlements: EntitlementManager\n\tprotected readonly checkout: CheckoutManager\n\tprotected readonly recovery: RecoveryManager\n\tprivate readonly backup: CloudBackup\n\t/** `deps.openUrl`, for tabs the full SDK opens outside checkout and recovery. */\n\tprotected readonly openUrl: ((url: string) => void | Promise<void>) | undefined\n\tprivate readonly trial: TrialNotifier\n\t/** storage.sync for the trial start; null when off, in mock mode, or outside an extension. */\n\tprivate readonly syncStorage: StorageAdapter | null\n\tprivate readonly now: () => number\n\tprivate endUserRef: string | null = null\n\tprivate endUserRefPromise: Promise<string> | null = null\n\tprivate offer: { value: PayOfferResponse; fetchedAt: number } | null = null\n\tprivate offerInflight: Promise<PayOfferResponse> | null = null\n\t/** The signing key the server returned in this session; never one read from storage. */\n\tprivate serverKey: string | null = null\n\t/** Trust order for license signatures; see payment/signature.ts. */\n\tprivate readonly keys: PublicKeySource = {\n\t\tknown: async () => {\n\t\t\tconst pinned = this.config.entitlementPublicKey\n\t\t\tconst offline = pinned ?? (await this.readSavedServerKey())\n\t\t\treturn [...new Set([this.serverKey, offline].filter((key): key is string => !!key))]\n\t\t},\n\t\tfetchCurrent: async () => (await this.fetchOffer(true)).entitlementPublicKey,\n\t}\n\tprivate readyPromise: Promise<void> | null = null\n\tprivate destroyed = false\n\n\tconstructor(config: ExtenshiPayConfig, deps: ExtenshiPayDeps = {}) {\n\t\tthis.config = resolveConfig(config)\n\t\tlogger.configure({ logLevel: this.config.logLevel, debug: this.config.debug })\n\t\tthis.now = deps.now ?? (() => Date.now())\n\t\tthis.storage = deps.storage ?? createStorage()\n\t\tthis.openUrl = deps.openUrl\n\t\tthis.syncStorage =\n\t\t\t!this.config.syncTrialStart || this.config.mock\n\t\t\t\t? null\n\t\t\t\t: deps.syncStorage === undefined\n\t\t\t\t\t? createSyncStorage()\n\t\t\t\t\t: deps.syncStorage\n\n\t\tconst transport =\n\t\t\tdeps.transport ??\n\t\t\t(this.config.mock\n\t\t\t\t? new MockTransport(this.config.mockData ?? {})\n\t\t\t\t: new HttpTransport({ apiUrl: this.config.apiUrl, fetchImpl: deps.fetch }))\n\t\tthis.api = new PayApi(transport, this.config.publishableKey)\n\n\t\tthis.entitlements = new EntitlementManager({\n\t\t\tapi: this.api,\n\t\t\tstorage: this.storage,\n\t\t\tpublishableKey: this.config.publishableKey,\n\t\t\tcacheTtlMs: this.config.cacheTtlMs,\n\t\t\tsource: this.config.mock ? 'mock' : 'network',\n\t\t\tgetEndUserRef: () => this.getEndUserRef(),\n\t\t\tkeys: this.keys,\n\t\t\tonChange: (entitlement) => this.emitter.emit('entitlement:changed', entitlement),\n\t\t\tonAccepted: () => {\n\t\t\t\tvoid this.trial.evaluate()\n\t\t\t\tvoid this.rememberTrialStart()\n\t\t\t},\n\t\t\tgetTrialStartHint: () => this.readTrialStartHint(),\n\t\t\tonError: (error) => this.reportError(error),\n\t\t\tnow: this.now,\n\t\t})\n\n\t\tthis.trial = new TrialNotifier({\n\t\t\tstorage: this.storage,\n\t\t\tstorageKey: `extenshi-pay:${this.config.publishableKey}:trial-events${this.config.mock ? ':mock' : ''}`,\n\t\t\tendingDays: this.config.trialEndingDays,\n\t\t\tgetTrial: () => this.entitlements.getTrial(),\n\t\t\t// A paid license still counts while it waits for an online check: no \"trial ended\" to a buyer.\n\t\t\thasPaidAccess: () => {\n\t\t\t\tconst license = this.entitlements.getCached()\n\t\t\t\treturn Boolean(license?.regionalFreeUntil || license?.items.some(isLive))\n\t\t\t},\n\t\t\temit: (event, trial) => this.emitter.emit(event, trial),\n\t\t\tnow: this.now,\n\t\t})\n\n\t\tthis.checkout = new CheckoutManager({\n\t\t\tapi: this.api,\n\t\t\tstorage: this.storage,\n\t\t\tpublishableKey: this.config.publishableKey,\n\t\t\tlocale: this.config.locale,\n\t\t\tgetEndUserRef: () => this.getEndUserRef(),\n\t\t\tonComplete: (envelope) => this.entitlements.accept(envelope),\n\t\t\temit: (event, payload) => this.emitter.emit(event, payload),\n\t\t\t// Mock checkouts complete on their own; never open a tab to a mock URL.\n\t\t\topenUrl:\n\t\t\t\tdeps.openUrl ??\n\t\t\t\t(this.config.mock ? (url) => logger.info('mock checkout (no tab opened)', url) : undefined),\n\t\t\tnow: this.now,\n\t\t})\n\n\t\tthis.backup = new CloudBackup({\n\t\t\tstorage: this.storage,\n\t\t\tpublishableKey: this.config.publishableKey,\n\t\t\tapiUrl: this.config.apiUrl,\n\t\t\tfetch: deps.fetch,\n\t\t\tmock: this.config.mock,\n\t\t})\n\n\t\tthis.recovery = new RecoveryManager({\n\t\t\tapi: this.api,\n\t\t\tlocale: this.config.locale,\n\t\t\tpublishableKey: this.config.publishableKey,\n\t\t\tstorage: deps.recoveryStorage ?? createRecoveryStorage(),\n\t\t\topenUrl: deps.openUrl,\n\t\t\tnow: this.now,\n\t\t\tonComplete: async (ref, envelope) => {\n\t\t\t\tif (\n\t\t\t\t\t!PAY_END_USER_REF_RE.test(ref) ||\n\t\t\t\t\tenvelope?.payload?.endUserRef !== ref ||\n\t\t\t\t\tenvelope.payload.publishableKey !== this.config.publishableKey ||\n\t\t\t\t\t!Number.isFinite(Date.parse(envelope.payload.issuedAt)) ||\n\t\t\t\t\tDate.parse(envelope.payload.issuedAt) > this.now() + MAX_CLOCK_SKEW_MS ||\n\t\t\t\t\t(await verifyWithKeys(envelope, this.keys)).verdict !== 'valid'\n\t\t\t\t)\n\t\t\t\t\tthrow new ExtenshiPayError(\n\t\t\t\t\t\tERROR_CODES.INVALID_RESPONSE,\n\t\t\t\t\t\t'Recovery requires a verified entitlement for this installation',\n\t\t\t\t\t)\n\t\t\t\tthis.entitlements.stopAutoRefresh()\n\t\t\t\ttry {\n\t\t\t\t\tawait this.entitlements.settleRefresh()\n\t\t\t\t\tif (this.destroyed) throw new ExtenshiPayError(ERROR_CODES.INVALID_REQUEST, 'Recovery was stopped')\n\t\t\t\t\tawait this.storage.set(END_USER_REF_STORAGE_KEY, ref)\n\t\t\t\t\tthis.endUserRef = ref\n\t\t\t\t\tthis.endUserRefPromise = null\n\t\t\t\t\tawait this.entitlements.clear()\n\t\t\t\t\treturn await this.entitlements.accept(envelope)\n\t\t\t\t} finally {\n\t\t\t\t\tif (!this.destroyed) this.entitlements.startAutoRefresh()\n\t\t\t\t}\n\t\t\t},\n\t\t\tonStorageGrant: (grant) => this.backup.accept(grant),\n\t\t})\n\n\t\tif (config.onError) this.emitter.on('error', config.onError)\n\t\tif (config.onReady) this.emitter.once('ready', config.onReady)\n\t}\n\n\tget version(): string {\n\t\treturn VERSION\n\t}\n\n\t/**\n\t * Mints/loads `endUserRef`, loads the cached entitlement, re-verifies it and\n\t * refreshes it when stale. Resolves once `isPaid()` can answer; network\n\t * failures fall back to the cache and are reported through `error`.\n\t */\n\tinitialize(): Promise<void> {\n\t\tif (!this.readyPromise) this.readyPromise = this.doInitialize()\n\t\treturn this.readyPromise\n\t}\n\n\tprivate async doInitialize(): Promise<void> {\n\t\tconst endUserRef = await this.getEndUserRef()\n\t\tawait this.entitlements.load()\n\t\ttry {\n\t\t\tawait this.entitlements.reverify()\n\t\t} catch (error) {\n\t\t\tthis.reportError(error)\n\t\t}\n\t\tif (!this.entitlements.isFresh()) await this.entitlements.get({ force: true })\n\t\tthis.emitter.emit('ready', { endUserRef })\n\t\tvoid this.afterReady()\n\t}\n\n\tprivate async afterReady(): Promise<void> {\n\t\tif (this.destroyed) return\n\t\ttry {\n\t\t\tawait this.checkout.resumePending()\n\t\t\tif (this.destroyed) return\n\t\t\tawait this.recovery.resumePending()\n\t\t} catch (error) {\n\t\t\tthis.reportError(error)\n\t\t}\n\t\tvoid this.confirmSavedServerKey()\n\t\tif (!this.destroyed) {\n\t\t\tthis.entitlements.startAutoRefresh()\n\t\t\tthis.trial.start()\n\t\t}\n\t}\n\n\t/** The anonymous, random id this install is known by. */\n\tgetEndUserRef(): Promise<string> {\n\t\tif (this.endUserRef) return Promise.resolve(this.endUserRef)\n\t\tif (!this.endUserRefPromise) {\n\t\t\tthis.endUserRefPromise = getOrCreateEndUserRef(this.storage).then((ref) => {\n\t\t\t\tthis.endUserRef = ref\n\t\t\t\treturn ref\n\t\t\t})\n\t\t}\n\t\treturn this.endUserRefPromise\n\t}\n\n\tgetCachedEntitlement(): Entitlement | null {\n\t\treturn this.entitlements.getCached()\n\t}\n\n\tasync getEntitlement(options: GetEntitlementOptions = {}): Promise<Entitlement> {\n\t\tawait this.initialize()\n\t\treturn this.entitlements.get(options)\n\t}\n\n\t/**\n\t * The free trial the application set on the server, from the verified license, or null when\n\t * there is none (or the license could not be verified yet). Answers offline from the cached\n\t * license; like paid access, `active` needs a license check within 48 hours. `isPaid()` and\n\t * `hasFeature()` do not include the trial: grant trial access with `(await getTrial())?.active`.\n\t */\n\tasync getTrial(options: GetEntitlementOptions = {}): Promise<TrialState | null> {\n\t\tawait this.getEntitlement(options)\n\t\treturn this.entitlements.getTrial()\n\t}\n\n\t/** True when any active/grace entitlement exists, or the given `sku` is active/grace. */\n\tasync isPaid(sku?: string): Promise<boolean> {\n\t\treturn isEntitled(await this.getEntitlement(), sku)\n\t}\n\n\tasync hasFeature(feature: string): Promise<boolean> {\n\t\treturn hasFeature(await this.getEntitlement(), feature)\n\t}\n\n\tasync checkFeatures(features: string[]): Promise<Record<string, boolean>> {\n\t\treturn checkFeatures(await this.getEntitlement(), features)\n\t}\n\n\t/** Resolves true when the feature is (or becomes) unlocked. */\n\tasync requireFeature(feature: string, options: RequireFeatureOptions = {}): Promise<boolean> {\n\t\tif (await this.hasFeature(feature)) {\n\t\t\toptions.onUnlock?.()\n\t\t\treturn true\n\t\t}\n\t\tconst unlocked = await this.onFeatureLocked(feature, options)\n\t\tif (unlocked) options.onUnlock?.()\n\t\telse options.onCancel?.()\n\t\treturn unlocked\n\t}\n\n\t/** Lite has no UI: a locked feature stays locked. The full SDK shows the paywall here. */\n\tprotected async onFeatureLocked(_feature: string, _options: RequireFeatureOptions): Promise<boolean> {\n\t\treturn false\n\t}\n\n\t/**\n\t * The withdrawal waiver this offer asks for, with the exact text to show\n\t * next to an unticked checkbox (buyer's language, seller's name filled in),\n\t * or null when the seller attested the extension is not distributed in the\n\t * EEA/UK. For UIs that call `openCheckout()` themselves — Lite, or a custom\n\t * paywall; the full SDK's paywall does this for you.\n\t */\n\tasync getWithdrawalWaiver(): Promise<{ version: string; text: string } | null> {\n\t\tawait this.initialize()\n\t\ttry {\n\t\t\tconst offer = await this.fetchOffer()\n\t\t\tif (!offer.withdrawalWaiver) return null\n\t\t\tconst seller = offer.seller?.displayName?.trim() || offer.projectName\n\t\t\treturn withdrawalWaiverText(offer.withdrawalWaiver.version, this.config.locale, seller)\n\t\t} catch (error) {\n\t\t\tthrow this.reportError(error)\n\t\t}\n\t}\n\n\t/**\n\t * Opens hosted checkout for `sku` in a new tab and resolves when the session settles.\n\t *\n\t * Called directly (not from the paywall), this does NOT collect the EU/UK\n\t * withdrawal waiver. If `getWithdrawalWaiver()` returns one, your UI must\n\t * collect the buyer's consent and pass it as `options.withdrawalWaiver`;\n\t * without it this rejects with `WITHDRAWAL_WAIVER_REQUIRED` (the server\n\t * refuses such a checkout too).\n\t */\n\tasync openCheckout(sku: string, options: CheckoutOptions = {}): Promise<CheckoutResult> {\n\t\tawait this.initialize()\n\t\ttry {\n\t\t\tif (this.recovery.isActive())\n\t\t\t\tthrow new ExtenshiPayError(ERROR_CODES.INVALID_REQUEST, 'Recovery is in progress')\n\t\t\t// A cold cache is filled here; if the offer cannot be read, the server decides.\n\t\t\tconst offer = await this.fetchOffer().catch(() => null)\n\t\t\tif (offer?.withdrawalWaiver && options.withdrawalWaiver?.accepted !== true)\n\t\t\t\tthrow new ExtenshiPayError(\n\t\t\t\t\tERROR_CODES.WITHDRAWAL_WAIVER_REQUIRED,\n\t\t\t\t\t'This offer needs the buyer to accept the withdrawal waiver; pass options.withdrawalWaiver',\n\t\t\t\t)\n\t\t\treturn await this.checkout.open(sku, options)\n\t\t} catch (error) {\n\t\t\tthrow this.reportError(error)\n\t\t}\n\t}\n\n\t/** Opens email verification on the hosted page. No email is collected inside the extension. */\n\tasync restorePurchase(options: RestoreOptions = {}): Promise<RestoreResult> {\n\t\tawait this.initialize()\n\t\ttry {\n\t\t\tif (this.checkout.isActive())\n\t\t\t\tthrow new ExtenshiPayError(ERROR_CODES.INVALID_REQUEST, 'Checkout is in progress')\n\t\t\treturn await this.recovery.open(options)\n\t\t} catch (error) {\n\t\t\tthrow this.reportError(error)\n\t\t}\n\t}\n\n\t/**\n\t * Turns on the cloud copy of the extension's settings (`@extenshi/storage`): the\n\t * hosted restore page shows the storage disclosure and the buyer confirms with\n\t * the code from the purchase email. `cloudBackup` in the result says whether it is\n\t * on. Buyers only; consent is recorded by the server.\n\t */\n\tenableCloudBackup(options: Omit<RestoreOptions, 'purpose'> = {}): Promise<RestoreResult> {\n\t\treturn this.restorePurchase({ ...options, purpose: 'storage' })\n\t}\n\n\t/**\n\t * The storage token for `ExtenshiStorage.create({ cloud: { getToken } })`, or null\n\t * while cloud backup is off on this installation. Extension pages and background\n\t * only: it rejects in a content script, and must never be sent to one.\n\t */\n\tasync cloudBackupToken(): Promise<string | null> {\n\t\treturn this.backup.token()\n\t}\n\n\t/** Turns cloud backup off on this installation: revokes its token. The cloud copy stays. */\n\tasync disableCloudBackup(): Promise<void> {\n\t\ttry {\n\t\t\tawait this.backup.disable()\n\t\t} catch (error) {\n\t\t\tthrow this.reportError(error)\n\t\t}\n\t}\n\n\t/** Deletes the buyer's cloud copy and turns cloud backup off on every installation. */\n\tasync deleteCloudBackup(): Promise<void> {\n\t\ttry {\n\t\t\tawait this.backup.delete()\n\t\t} catch (error) {\n\t\t\tthrow this.reportError(error)\n\t\t}\n\t}\n\n\t/** Read-only license view. Entitlements retain cache/signature/offline semantics. */\n\tasync getLicenseSummary(options: GetEntitlementOptions = {}): Promise<LicenseSummary> {\n\t\tawait this.initialize()\n\t\tlet offer: PayOfferResponse | null = null\n\t\ttry {\n\t\t\toffer = await this.fetchOffer(options.force)\n\t\t} catch {\n\t\t\t/* Offline: do not invent seller details. */\n\t\t}\n\t\treturn {\n\t\t\tprojectName: offer?.projectName ?? null,\n\t\t\tseller: offer?.seller ?? null,\n\t\t\tentitlement: await this.getEntitlement(options),\n\t\t\trecoveryEnabled: offer?.recoveryEnabled === true,\n\t\t}\n\t}\n\n\t/** Opens the provider's self-service portal; resolves null when the provider has none. */\n\tasync openCustomerPortal(options: CustomerPortalOptions = {}): Promise<string | null> {\n\t\tawait this.initialize()\n\t\ttry {\n\t\t\tconst endUserRef = await this.getEndUserRef()\n\t\t\tlet result = await this.api.getPortalUrl(endUserRef, undefined, this.config.locale)\n\t\t\tif (this.destroyed) return null\n\t\t\tif (result.accounts?.length) {\n\t\t\t\tif (!options.selectAccount)\n\t\t\t\t\tthrow new ExtenshiPayError(\n\t\t\t\t\t\tERROR_CODES.INVALID_REQUEST,\n\t\t\t\t\t\t'Choose a billing profile using selectAccount',\n\t\t\t\t\t)\n\t\t\t\tconst customerId = await options.selectAccount(result.accounts)\n\t\t\t\tif (customerId === null || this.destroyed) return null\n\t\t\t\tif (!result.accounts.some((a) => a.id === customerId))\n\t\t\t\t\tthrow new ExtenshiPayError(ERROR_CODES.INVALID_REQUEST, 'Invalid billing profile')\n\t\t\t\t// Recovery may replace this installation while the selector is open.\n\t\t\t\tif (endUserRef !== (await this.getEndUserRef()))\n\t\t\t\t\tthrow new ExtenshiPayError(\n\t\t\t\t\t\tERROR_CODES.INVALID_REQUEST,\n\t\t\t\t\t\t'Installation changed; open the portal again',\n\t\t\t\t\t)\n\t\t\t\tresult = await this.api.getPortalUrl(endUserRef, customerId, this.config.locale)\n\t\t\t}\n\t\t\tif (this.destroyed) return null\n\t\t\tconst { url } = result\n\t\t\tif (url) await (options.openUrl ?? (await import('../payment/checkout.js')).openInNewTab)(url)\n\t\t\treturn url\n\t\t} catch (error) {\n\t\t\tthrow this.reportError(error)\n\t\t}\n\t}\n\n\ton<K extends keyof ExtenshiPayEvents>(event: K, listener: Listener<ExtenshiPayEvents[K]>): () => void {\n\t\treturn this.emitter.on(event, listener)\n\t}\n\n\tonce<K extends keyof ExtenshiPayEvents>(event: K, listener: Listener<ExtenshiPayEvents[K]>): () => void {\n\t\treturn this.emitter.once(event, listener)\n\t}\n\n\toff<K extends keyof ExtenshiPayEvents>(event: K, listener: Listener<ExtenshiPayEvents[K]>): void {\n\t\tthis.emitter.off(event, listener)\n\t}\n\n\tonEntitlementChange(listener: Listener<Entitlement>): () => void {\n\t\treturn this.emitter.on('entitlement:changed', listener)\n\t}\n\n\tasync clearCache(): Promise<void> {\n\t\tthis.offer = null\n\t\tawait this.entitlements.clear()\n\t}\n\n\t/** Stops background refresh and drops listeners. */\n\tdestroy(): void {\n\t\tthis.destroyed = true\n\t\tthis.recovery.stop()\n\t\tthis.trial.stop()\n\t\tthis.entitlements.stopAutoRefresh()\n\t\tthis.emitter.removeAll()\n\t}\n\n\t/** Offer + signing key. Public in the full SDK (`getOffer`), internal here. */\n\tprotected fetchOffer(force = false): Promise<PayOfferResponse> {\n\t\tif (!force && this.offer && this.now() - this.offer.fetchedAt < OFFER_TTL_MS) {\n\t\t\treturn Promise.resolve(this.offer.value)\n\t\t}\n\t\tif (!this.offerInflight) {\n\t\t\tthis.offerInflight = this.api\n\t\t\t\t.getOffer(this.config.locale)\n\t\t\t\t.then(async (value) => {\n\t\t\t\t\tthis.offer = { value, fetchedAt: this.now() }\n\t\t\t\t\tawait this.rememberServerKey(value.entitlementPublicKey)\n\t\t\t\t\treturn value\n\t\t\t\t})\n\t\t\t\t.finally(() => {\n\t\t\t\t\tthis.offerInflight = null\n\t\t\t\t})\n\t\t}\n\t\treturn this.offerInflight\n\t}\n\n\tprivate get serverKeyStorageKey(): string {\n\t\treturn `extenshi-pay:${this.config.publishableKey}:entitlementPublicKey`\n\t}\n\n\tprivate async readSavedServerKey(): Promise<string | null> {\n\t\ttry {\n\t\t\tconst value = await this.storage.get(this.serverKeyStorageKey)\n\t\t\treturn typeof value === 'string' && PUBLIC_KEY_RE.test(value) ? value : null\n\t\t} catch {\n\t\t\treturn null\n\t\t}\n\t}\n\n\t/**\n\t * Keeps the server's key next to the license cache so a restart with no network can verify it.\n\t * Not with a bundled key: that one already covers the restart, and storage stays untrusted.\n\t */\n\tprivate async rememberServerKey(key: string | null | undefined): Promise<void> {\n\t\tif (typeof key !== 'string' || !PUBLIC_KEY_RE.test(key)) return\n\t\tthis.serverKey = key\n\t\tif (this.config.entitlementPublicKey || this.config.mock) return\n\t\ttry {\n\t\t\tif ((await this.readSavedServerKey()) !== key) await this.storage.set(this.serverKeyStorageKey, key)\n\t\t} catch (error) {\n\t\t\tlogger.debug('signing key not saved', error)\n\t\t}\n\t}\n\n\t/**\n\t * A license verified with the saved key alone is checked against the server once per start:\n\t * when the server's key differs (rotation, or an edited storage) the license is fetched again,\n\t * and dropped if it does not verify. Offline, the saved key stands until `offlineUntil`.\n\t */\n\tprivate async confirmSavedServerKey(): Promise<void> {\n\t\tconst used = this.entitlements.verifiedKey\n\t\tif (this.destroyed || !used || used === this.serverKey || used === this.config.entitlementPublicKey)\n\t\t\treturn\n\t\ttry {\n\t\t\tif ((await this.fetchOffer()).entitlementPublicKey === used || this.destroyed) return\n\t\t} catch {\n\t\t\treturn\n\t\t}\n\t\ttry {\n\t\t\tawait this.entitlements.refresh()\n\t\t} catch {\n\t\t\tawait this.entitlements.reverify().catch((error) => this.reportError(error))\n\t\t}\n\t}\n\n\tprivate get trialStartKey(): string {\n\t\treturn `extenshi-pay:${this.config.publishableKey}:trialStartedAt`\n\t}\n\n\t/** The synced trial start, or null (none, malformed, or storage.sync unavailable). */\n\tprivate async readTrialStartHint(): Promise<string | null> {\n\t\tif (!this.syncStorage) return null\n\t\ttry {\n\t\t\tconst value = await this.syncStorage.get(this.trialStartKey)\n\t\t\treturn typeof value === 'string' && Number.isFinite(Date.parse(value)) ? value : null\n\t\t} catch {\n\t\t\treturn null\n\t\t}\n\t}\n\n\t/** Syncs the verified trial start, keeping the earliest one seen. Never the installation id. */\n\tprivate async rememberTrialStart(): Promise<void> {\n\t\tconst trial = this.entitlements.getTrial()\n\t\tif (!this.syncStorage || !trial) return\n\t\ttry {\n\t\t\tconst synced = await this.readTrialStartHint()\n\t\t\tif (synced && Date.parse(synced) <= Date.parse(trial.startedAt)) return\n\t\t\tawait this.syncStorage.set(this.trialStartKey, trial.startedAt)\n\t\t} catch (error) {\n\t\t\tlogger.debug('trial start not synced', error)\n\t\t}\n\t}\n\n\tprotected reportError(error: unknown): ExtenshiPayError {\n\t\tconst err = ExtenshiPayError.from(error)\n\t\tlogger.warn(`${err.code}: ${err.message}`)\n\t\tthis.emitter.emit('error', err)\n\t\treturn err\n\t}\n}\n","import type { PaySellerPublic } from '../types/contract.js'\nimport { fill, SDK_STRINGS_EN, type SdkStrings } from './i18n.js'\n\n/** Treat even server-provided links as untrusted; never render executable protocols. */\nexport function publicContactUrl(value: string): string | null {\n\ttry {\n\t\tconst url = new URL(value)\n\t\tif (url.protocol === 'https:' && !url.username && !url.password) return url.href\n\t} catch {\n\t\t/* A plain email address is allowed below. */\n\t}\n\tif (/^[^\\s@?&#:]+@[^\\s@?&#:]+\\.[^\\s@?&#:]+$/.test(value)) return `mailto:${encodeURIComponent(value)}`\n\treturn null\n}\n\nexport function sellerDetails(seller: PaySellerPublic | null, t: SdkStrings = SDK_STRINGS_EN): HTMLElement {\n\tconst section = document.createElement('section')\n\tsection.className = 'extenshi-seller-details'\n\tconst name = document.createElement('p')\n\tname.textContent = seller ? fill(t.sellerProvidedBy, { name: seller.displayName }) : t.sellerUnavailable\n\tsection.append(name)\n\tconst link = (label: string, value: string | null) => {\n\t\tconst href = value ? publicContactUrl(value) : null\n\t\tif (!href) return\n\t\tconst a = document.createElement('a')\n\t\ta.textContent = label\n\t\ta.href = href\n\t\ta.target = '_blank'\n\t\ta.rel = 'noopener noreferrer'\n\t\ta.style.marginInlineEnd = '12px'\n\t\tsection.append(a)\n\t}\n\tif (seller) {\n\t\tlink(t.sellerSupport, seller.supportUrl)\n\t\tlink(t.sellerTerms, seller.termsUrl)\n\t\tlink(t.sellerRefunds, seller.refundPolicyUrl ?? null)\n\t}\n\tconst role = document.createElement('p')\n\trole.textContent = t.sellerRole\n\tsection.append(role)\n\treturn section\n}\n","import type { LicenseSummary } from '../types/entitlement.js'\nimport { ERROR_CODES, ExtenshiPayError } from '../types/errors.js'\nimport { fill, type SdkStrings, sdkDir, sdkLocale, sdkStrings } from './i18n.js'\nimport { sellerDetails } from './seller-details.js'\n\n/** A status label in the language, or the raw value for one we do not know. */\nfunction statusLabel(t: SdkStrings, status: string): string {\n\tconst map: Record<string, string> = {\n\t\tactive: t.statusActive,\n\t\tgrace: t.statusGrace,\n\t\texpired: t.statusExpired,\n\t\tnone: t.statusNone,\n\t}\n\treturn map[status] ?? status.replace(/_/g, ' ')\n}\n\n/** A provider subscription status (Stripe vocabulary) in the language. */\nexport function subscriptionStatusLabel(t: SdkStrings, status: string): string {\n\tconst map: Record<string, string> = {\n\t\tactive: t.subActive,\n\t\ttrialing: t.subTrialing,\n\t\tpast_due: t.subPastDue,\n\t\tcanceled: t.subCanceled,\n\t\tunpaid: t.subUnpaid,\n\t\tincomplete: t.subIncomplete,\n\t\tincomplete_expired: t.subIncompleteExpired,\n\t\tpaused: t.subPaused,\n\t}\n\treturn map[status] ?? status.replace(/_/g, ' ')\n}\n\nexport class LicensePanel {\n\tprivate dismiss: (() => void) | null = null\n\thide(): void {\n\t\tthis.dismiss?.()\n\t}\n\tshow(\n\t\tsummary: LicenseSummary,\n\t\tactions: {\n\t\t\trestore: () => Promise<LicenseSummary>\n\t\t\tmanage: () => Promise<string | null>\n\t\t},\n\t\tlocale: string | null = null,\n\t): Promise<void> {\n\t\tthis.hide()\n\t\tif (typeof document === 'undefined')\n\t\t\tthrow new ExtenshiPayError(\n\t\t\t\tERROR_CODES.INVALID_REQUEST,\n\t\t\t\t'Use getLicenseSummary outside an extension page',\n\t\t\t)\n\t\tconst t = sdkStrings(locale)\n\t\tconst lang = sdkLocale(locale)\n\t\tconst host = document.createElement('div')\n\t\thost.className = 'extenshi-license-host'\n\t\thost.setAttribute('lang', lang)\n\t\thost.setAttribute('dir', sdkDir(lang))\n\t\tconst root = host.attachShadow({ mode: 'open' })\n\t\tconst style = document.createElement('style')\n\t\tstyle.textContent = `dialog{font:15px/1.5 system-ui,sans-serif;color:#172033;background:#fff;border:1px solid #dce1e8;border-radius:16px;padding:24px;width:min(460px,calc(100vw - 64px));max-height:80vh}dialog::backdrop{background:#10182880}h2{margin:0}h3{font-size:16px;margin:0}article{border-block-end:1px solid #ddd;padding:16px 0}p{margin:8px 0}button{font:inherit;padding:10px 14px;margin:12px 8px 0 0;border:1px solid #cbd5e1;border-radius:8px;cursor:pointer;background:#fff;color:inherit}button:disabled{opacity:.5;cursor:wait}button:focus-visible,a:focus-visible{outline:3px solid #0ea5e9}a{color:#0369a1}.extenshi-seller-details{font-size:13px;margin-top:20px}`\n\t\tconst dialog = document.createElement('dialog')\n\t\tdialog.setAttribute('aria-label', t.licenseTitle)\n\t\tconst title = document.createElement('h2')\n\t\ttitle.textContent = t.licenseTitle\n\t\tconst content = document.createElement('div')\n\t\tconst feedback = document.createElement('p')\n\t\tfeedback.setAttribute('role', 'status')\n\t\tconst render = (state: LicenseSummary) => {\n\t\t\tcontent.replaceChildren()\n\t\t\tconst note = document.createElement('p')\n\t\t\tnote.textContent = state.projectName ?? t.licenseFallbackName\n\t\t\tcontent.append(note)\n\t\t\tif (!state.entitlement.items.length) {\n\t\t\t\tconst empty = document.createElement('p')\n\t\t\t\tempty.textContent = t.licenseNone\n\t\t\t\tcontent.append(empty)\n\t\t\t}\n\t\t\tfor (const item of state.entitlement.items) {\n\t\t\t\tconst article = document.createElement('article')\n\t\t\t\tconst heading = document.createElement('h3')\n\t\t\t\theading.textContent = item.title ?? item.sku\n\t\t\t\tconst status = document.createElement('p')\n\t\t\t\tconst kind =\n\t\t\t\t\titem.kind === 'one_time'\n\t\t\t\t\t\t? item.expiresAt\n\t\t\t\t\t\t\t? t.kindOneTime\n\t\t\t\t\t\t\t: t.kindLifetime\n\t\t\t\t\t\t: item.kind === 'subscription'\n\t\t\t\t\t\t\t? t.kindSubscription\n\t\t\t\t\t\t\t: t.kindLicense\n\t\t\t\tstatus.textContent = `${kind} · ${fill(t.statusLine, { status: statusLabel(t, item.status) })}`\n\t\t\t\tarticle.append(heading, status)\n\t\t\t\tif (item.expiresAt) {\n\t\t\t\t\tconst date = new Date(item.expiresAt)\n\t\t\t\t\tif (!Number.isNaN(date.getTime())) {\n\t\t\t\t\t\tconst expiry = document.createElement('p')\n\t\t\t\t\t\tconst when = date.toLocaleString(lang)\n\t\t\t\t\t\texpiry.textContent = fill(\n\t\t\t\t\t\t\titem.status === 'expired'\n\t\t\t\t\t\t\t\t? t.accessEnded\n\t\t\t\t\t\t\t\t: item.status === 'active' || item.status === 'grace'\n\t\t\t\t\t\t\t\t\t? t.accessUntil\n\t\t\t\t\t\t\t\t\t: t.accessRecordedEnd,\n\t\t\t\t\t\t\t{ date: when },\n\t\t\t\t\t\t)\n\t\t\t\t\t\tarticle.append(expiry)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfor (const sub of item.subscriptions ?? []) {\n\t\t\t\t\tconst row = document.createElement('p')\n\t\t\t\t\trow.textContent = `${fill(t.subscriptionLine, { status: subscriptionStatusLabel(t, sub.status) })}${sub.cancelAtPeriodEnd ? ` · ${t.renewalCanceled}` : ''}`\n\t\t\t\t\tarticle.append(row)\n\t\t\t\t}\n\t\t\t\tcontent.append(article)\n\t\t\t}\n\t\t\tconst freshness = document.createElement('p')\n\t\t\tfreshness.textContent = state.entitlement.requiresOnlineCheck\n\t\t\t\t? t.licenseOffline\n\t\t\t\t: state.entitlement.source === 'mock'\n\t\t\t\t\t? t.mockNotice\n\t\t\t\t\t: state.entitlement.source === 'cache'\n\t\t\t\t\t\t? t.licenseCached\n\t\t\t\t\t\t: t.licenseFresh\n\t\t\tcontent.append(freshness, sellerDetails(state.seller, t))\n\t\t}\n\t\trender(summary)\n\t\tdialog.append(title, content, feedback)\n\t\troot.append(style, dialog)\n\t\tdocument.body.append(host)\n\t\tif (typeof dialog.showModal !== 'function') {\n\t\t\thost.remove()\n\t\t\tthrow new ExtenshiPayError(\n\t\t\t\tERROR_CODES.INVALID_REQUEST,\n\t\t\t\t'This browser needs a custom license screen using getLicenseSummary',\n\t\t\t)\n\t\t}\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tlet closed = false\n\t\t\tconst close = () => {\n\t\t\t\tclosed = true\n\t\t\t\tthis.dismiss = null\n\t\t\t\tdialog.close()\n\t\t\t\thost.remove()\n\t\t\t\tresolve()\n\t\t\t}\n\t\t\tthis.dismiss = close\n\t\t\tdialog.addEventListener('cancel', (event) => {\n\t\t\t\tevent.preventDefault()\n\t\t\t\tclose()\n\t\t\t})\n\t\t\tconst buttons: HTMLButtonElement[] = []\n\t\t\tconst action = (label: string, run: () => Promise<void>) => {\n\t\t\t\tconst button = document.createElement('button')\n\t\t\t\tbutton.type = 'button'\n\t\t\t\tbutton.textContent = label\n\t\t\t\tbutton.addEventListener('click', async () => {\n\t\t\t\t\tbuttons.forEach((b) => {\n\t\t\t\t\t\tb.disabled = true\n\t\t\t\t\t})\n\t\t\t\t\tfeedback.textContent = ''\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait run()\n\t\t\t\t\t} catch {\n\t\t\t\t\t\tif (!closed) feedback.textContent = t.actionFailed\n\t\t\t\t\t} finally {\n\t\t\t\t\t\tif (!closed)\n\t\t\t\t\t\t\tbuttons.forEach((b) => {\n\t\t\t\t\t\t\t\tb.disabled = false\n\t\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t\tbuttons.push(button)\n\t\t\t\tdialog.append(button)\n\t\t\t}\n\t\t\tif (summary.recoveryEnabled)\n\t\t\t\taction(t.restorePurchase, async () => {\n\t\t\t\t\tconst updated = await actions.restore()\n\t\t\t\t\tif (!closed) render(updated)\n\t\t\t\t})\n\t\t\tif (summary.entitlement.source !== 'mock')\n\t\t\t\taction(t.manageBilling, async () => {\n\t\t\t\t\tconst url = await actions.manage()\n\t\t\t\t\tif (!url && !closed) feedback.textContent = t.noPortal\n\t\t\t\t})\n\t\t\tconst done = document.createElement('button')\n\t\t\tdone.type = 'button'\n\t\t\tdone.textContent = t.close\n\t\t\tdone.addEventListener('click', close)\n\t\t\tdialog.append(done)\n\t\t\ttry {\n\t\t\t\tdialog.showModal()\n\t\t\t} catch (error) {\n\t\t\t\tthis.dismiss = null\n\t\t\t\thost.remove()\n\t\t\t\treject(error)\n\t\t\t}\n\t\t})\n\t}\n}\n","import type { PayPortalAccount } from '../types/contract.js'\nimport { ERROR_CODES, ExtenshiPayError } from '../types/errors.js'\nimport { fill, sdkDir, sdkLocale, sdkStrings } from './i18n.js'\nimport { subscriptionStatusLabel } from './license-panel.js'\n\n/** Bundled UI only. Native dialog provides modal focus containment and Escape. */\nexport class BillingProfilePicker {\n\tprivate dismiss: (() => void) | null = null\n\n\thide(): void {\n\t\tthis.dismiss?.()\n\t}\n\n\tshow(accounts: PayPortalAccount[], locale: string | null = null): Promise<string | null> {\n\t\tthis.hide()\n\t\tif (typeof document === 'undefined')\n\t\t\tthrow new ExtenshiPayError(\n\t\t\t\tERROR_CODES.INVALID_REQUEST,\n\t\t\t\t'Provide selectAccount outside an extension page',\n\t\t\t)\n\t\tconst t = sdkStrings(locale)\n\t\tconst lang = sdkLocale(locale)\n\t\tconst host = document.createElement('div')\n\t\thost.className = 'extenshi-billing-profile-host'\n\t\thost.setAttribute('lang', lang)\n\t\thost.setAttribute('dir', sdkDir(lang))\n\t\tconst root = host.attachShadow({ mode: 'open' })\n\t\tconst style = document.createElement('style')\n\t\tstyle.textContent = `\n\t\t\tdialog{font:15px/1.5 system-ui,sans-serif;color:#172033;background:#fff;border:1px solid #dce1e8;border-radius:16px;padding:24px;width:min(440px,calc(100vw - 64px));max-height:80vh;box-shadow:0 20px 60px #0003}\n\t\t\tdialog::backdrop{background:#10182880}h2{margin:0 0 8px;font-size:22px}p{margin:0 0 16px;color:#526078}\n\t\t\tbutton{font:inherit;cursor:pointer;border:1px solid #dce1e8;border-radius:8px;background:#fff;color:inherit;padding:12px;text-align:left;width:100%;margin-top:10px}\n\t\t\tbutton:hover{background:#f3f6fa}button:focus-visible{outline:3px solid #0ea5e9;outline-offset:2px}strong,small{display:block}small{color:#526078;margin-top:4px}\n\t\t`\n\t\tconst dialog = document.createElement('dialog')\n\t\tdialog.setAttribute('aria-labelledby', 'billing-title')\n\t\tdialog.setAttribute('aria-describedby', 'billing-description')\n\t\tconst title = document.createElement('h2')\n\t\ttitle.id = 'billing-title'\n\t\ttitle.textContent = t.pickerTitle\n\t\tconst description = document.createElement('p')\n\t\tdescription.id = 'billing-description'\n\t\tdescription.textContent = t.pickerDescription\n\t\tdialog.append(title, description)\n\t\troot.append(style, dialog)\n\t\tdocument.body.append(host)\n\t\tif (typeof dialog.showModal !== 'function') {\n\t\t\thost.remove()\n\t\t\tthrow new ExtenshiPayError(\n\t\t\t\tERROR_CODES.INVALID_REQUEST,\n\t\t\t\t'This browser needs a custom selectAccount callback',\n\t\t\t)\n\t\t}\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst finish = (id: string | null) => {\n\t\t\t\tthis.dismiss = null\n\t\t\t\tdialog.close()\n\t\t\t\thost.remove()\n\t\t\t\tresolve(id)\n\t\t\t}\n\t\t\tthis.dismiss = () => finish(null)\n\t\t\tdialog.addEventListener('cancel', (event) => {\n\t\t\t\tevent.preventDefault()\n\t\t\t\tfinish(null)\n\t\t\t})\n\t\t\tfor (const account of accounts) {\n\t\t\t\tconst button = document.createElement('button')\n\t\t\t\tbutton.type = 'button'\n\t\t\t\tconst label = document.createElement('strong')\n\t\t\t\tlabel.textContent = account.label\n\t\t\t\tconst detail = document.createElement('small')\n\t\t\t\tconst recorded = new Date(account.createdAt)\n\t\t\t\tdetail.textContent = Number.isNaN(recorded.getTime())\n\t\t\t\t\t? ''\n\t\t\t\t\t: fill(t.pickerFirstRecorded, { date: recorded.toLocaleDateString(lang) })\n\t\t\t\tbutton.append(label, detail)\n\t\t\t\tfor (const subscription of account.subscriptions) {\n\t\t\t\t\tconst line = document.createElement('small')\n\t\t\t\t\tconst end = subscription.currentPeriodEnd ? new Date(subscription.currentPeriodEnd) : null\n\t\t\t\t\tconst cancellation = subscription.cancelAtPeriodEnd\n\t\t\t\t\t\t? ` · ${t.renewalCanceled}${end && !Number.isNaN(end.getTime()) ? ` · ${fill(t.periodEnds, { date: end.toLocaleDateString(lang) })}` : ''}`\n\t\t\t\t\t\t: ''\n\t\t\t\t\tline.textContent = `${subscription.title} · ${subscriptionStatusLabel(t, subscription.status)}${cancellation}`\n\t\t\t\t\tbutton.append(line)\n\t\t\t\t}\n\t\t\t\tbutton.addEventListener('click', () => finish(account.id))\n\t\t\t\tdialog.append(button)\n\t\t\t}\n\t\t\tconst cancel = document.createElement('button')\n\t\t\tcancel.type = 'button'\n\t\t\tcancel.textContent = t.pickerCancel\n\t\t\tcancel.addEventListener('click', () => finish(null))\n\t\t\tdialog.append(cancel)\n\t\t\ttry {\n\t\t\t\tdialog.showModal()\n\t\t\t} catch (error) {\n\t\t\t\tthis.dismiss = null\n\t\t\t\thost.remove()\n\t\t\t\treject(error)\n\t\t\t}\n\t\t})\n\t}\n}\n","/**\n * The paywall's header image: the extension's own icon in place of the\n * templates' generic glyph (lock, layers).\n *\n * Only images from the extension package or `data:image/` URLs: a remote\n * image would be a request to a third party on every paywall view. The\n * manifest icon is the default on the extension's own pages (popup, options)\n * only. A content script runs on the site's origin, where the package's files\n * load only when `web_accessible_resources` lists them, and the SDK never asks\n * for that.\n */\n\ninterface ExtensionRuntime {\n\tgetURL?: (path: string) => string\n\tgetManifest?: () => { icons?: Record<string, string> }\n}\n\nconst DATA_IMAGE_RE = /^data:image\\/[\\w.+-]+[;,]/i\n/** `chrome-extension://<id>/`, `moz-extension://<uuid>/`, `safari-web-extension://<id>/`. */\nconst PACKAGE_BASE_RE = /^[a-z-]+-extension:\\/\\/[^/]+\\/$/\n\nfunction extensionRuntime(): ExtensionRuntime | undefined {\n\tconst g = globalThis as {\n\t\tchrome?: { runtime?: ExtensionRuntime }\n\t\tbrowser?: { runtime?: ExtensionRuntime }\n\t}\n\treturn g.chrome?.runtime ?? g.browser?.runtime\n}\n\nfunction packageBase(runtime: ExtensionRuntime | undefined): string | null {\n\ttry {\n\t\tconst base = runtime?.getURL?.('')\n\t\treturn typeof base === 'string' && PACKAGE_BASE_RE.test(base) ? base : null\n\t} catch {\n\t\treturn null\n\t}\n}\n\nfunction onExtensionPage(base: string): boolean {\n\tconst href = (globalThis as { location?: { href?: string } }).location?.href\n\treturn typeof href === 'string' && href.startsWith(base)\n}\n\nfunction largestIcon(runtime: ExtensionRuntime | undefined): string {\n\tlet best: [size: number, path: string] | null = null\n\ttry {\n\t\tfor (const [size, path] of Object.entries(runtime?.getManifest?.().icons ?? {})) {\n\t\t\tconst n = Number(size)\n\t\t\tif (typeof path === 'string' && path && Number.isFinite(n) && (!best || n > best[0])) best = [n, path]\n\t\t}\n\t} catch {\n\t\t/* No manifest to read. */\n\t}\n\treturn best?.[1] ?? ''\n}\n\n/**\n * The header image for `PaywallOptions.icon`, or null to keep the template's\n * glyph: `false` opts out, a `data:image/` URL is used anywhere, a package path\n * (or the manifest's largest icon by default) only on the extension's pages.\n */\nexport function paywallIconUrl(option?: string | false): string | null {\n\tif (option === false) return null\n\tconst explicit = typeof option === 'string' ? option.trim() : ''\n\tif (DATA_IMAGE_RE.test(explicit)) return explicit\n\tconst runtime = extensionRuntime()\n\tconst base = packageBase(runtime)\n\tif (!base || !onExtensionPage(base)) return null\n\tconst path = explicit || largestIcon(runtime)\n\tif (!path) return null\n\ttry {\n\t\tconst url = new URL(path, base).href\n\t\treturn url.startsWith(base) ? url : null\n\t} catch {\n\t\treturn null\n\t}\n}\n","import type { PayOfferDto } from '../types/contract.js'\nimport type { PaywallStrings } from '../types/paywall.js'\n\nexport interface FormattedPrice {\n\t/** Currency symbol/code as the locale renders it (`$`, `€`, `US$`). */\n\tcurrency: string\n\t/** Numeric part (`9.99`, `9,99`). */\n\tamount: string\n\t/** The whole formatted price (`$9.99`). */\n\tfull: string\n}\n\nexport function formatPrice(amountMinor: number, currency: string, locale?: string | null): FormattedPrice {\n\tconst value = amountMinor / 100\n\tconst code = currency.toUpperCase()\n\ttry {\n\t\tconst formatter = new Intl.NumberFormat(locale ?? undefined, { style: 'currency', currency: code })\n\t\tconst parts = formatter.formatToParts(value)\n\t\treturn {\n\t\t\tcurrency: parts\n\t\t\t\t.filter((part) => part.type === 'currency')\n\t\t\t\t.map((part) => part.value)\n\t\t\t\t.join(''),\n\t\t\tamount: parts\n\t\t\t\t.filter((part) => part.type !== 'currency' && part.type !== 'literal')\n\t\t\t\t.map((part) => part.value)\n\t\t\t\t.join(''),\n\t\t\tfull: formatter.format(value),\n\t\t}\n\t} catch {\n\t\tconst amount = value.toFixed(2)\n\t\treturn { currency: code, amount, full: `${amount} ${code}` }\n\t}\n}\n\nexport function periodLabel(offer: PayOfferDto, strings: PaywallStrings): string {\n\tif (offer.kind !== 'subscription') return strings.periodOnce\n\treturn offer.interval === 'year' ? strings.periodYear : strings.periodMonth\n}\n","/**\n * The paywall's strings in a locale, from the SDK dictionary (./i18n.ts).\n * Do not add promotional claims without marketing/legal review (see\n * .claude/modules/paywall-templates.md).\n */\n\nimport type { PaywallStrings } from '../types/paywall.js'\nimport { SDK_STRINGS_EN, type SdkStrings, sdkStrings } from './i18n.js'\n\nfunction paywallStrings(t: SdkStrings): PaywallStrings {\n\treturn {\n\t\ttitle: t.title,\n\t\tdescription: t.description,\n\t\tupgrade: t.upgrade,\n\t\tcancel: t.cancel,\n\t\tdismiss: t.dismiss,\n\t\tremindLater: t.remindLater,\n\t\tcontinueFree: t.continueFree,\n\t\tcheckoutUnavailable: t.checkoutUnavailable,\n\t\tperiodMonth: t.periodMonth,\n\t\tperiodYear: t.periodYear,\n\t\tperiodOnce: t.periodOnce,\n\t\tfooter: t.footer,\n\t\trestorePurchase: t.restorePurchase,\n\t\tfeaturesHeading: t.featuresHeading,\n\t\tplansHeading: t.plansHeading,\n\t\tfreePlanName: t.freePlanName,\n\t\tpremiumPlanName: t.premiumPlanName,\n\t\tpopularBadge: t.popularBadge,\n\t\tunlockHeading: t.unlockHeading,\n\t}\n}\n\n/** English (the default and the fallback). */\nexport const DEFAULT_STRINGS: PaywallStrings = paywallStrings(SDK_STRINGS_EN)\n\nexport const MOCK_PAYMENT_NOTICE = SDK_STRINGS_EN.mockNotice\n\n/** The paywall strings for `locale` (English when we have no translation). */\nexport function stringsFor(locale: string | null | undefined): PaywallStrings {\n\treturn paywallStrings(sdkStrings(locale))\n}\n","export const html = \"<div class=\\\"ep-fullscreen-paywall\\\" id=\\\"fullscreenPaywall\\\" role=\\\"dialog\\\" aria-labelledby=\\\"fullscreen-title\\\"><div class=\\\"ep-fullscreen-background\\\"><div class=\\\"ep-background-pattern\\\"></div></div><div class=\\\"ep-fullscreen-header\\\"><div class=\\\"ep-fullscreen-logo\\\"><svg width=\\\"40\\\" height=\\\"40\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><path d=\\\"M12 2L2 7l10 5 10-5-10-5z\\\"></path><path d=\\\"M2 17l10 5 10-5\\\"></path><path d=\\\"M2 12l10 5 10-5\\\"></path></svg><span class=\\\"ep-fullscreen-logo-text\\\">{{brandName}}</span></div><button class=\\\"ep-fullscreen-close\\\" aria-label=\\\"Close paywall\\\" data-ep-action=\\\"closeFullscreen\\\"><svg width=\\\"24\\\" height=\\\"24\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><line x1=\\\"18\\\" y1=\\\"6\\\" x2=\\\"6\\\" y2=\\\"18\\\"></line><line x1=\\\"6\\\" y1=\\\"6\\\" x2=\\\"18\\\" y2=\\\"18\\\"></line></svg></button></div><div class=\\\"ep-fullscreen-content\\\"><div class=\\\"ep-fullscreen-container\\\"><div class=\\\"ep-fullscreen-hero\\\"><div class=\\\"ep-hero-icon\\\"><svg width=\\\"80\\\" height=\\\"80\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><path d=\\\"M12 2L2 7l10 5 10-5-10-5z\\\"></path><path d=\\\"M2 17l10 5 10-5\\\"></path><path d=\\\"M2 12l10 5 10-5\\\"></path></svg></div><h1 class=\\\"ep-heading-1\\\" id=\\\"fullscreen-title\\\">{{title}}</h1><p class=\\\"ep-hero-description\\\">{{description}}</p></div><div class=\\\"ep-fullscreen-features\\\"><div class=\\\"ep-features-grid\\\"><div class=\\\"ep-feature-card\\\"><div class=\\\"ep-feature-card-icon\\\"><svg width=\\\"32\\\" height=\\\"32\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><path d=\\\"M22 12h-4l-3 9L9 3l-3 9H2\\\"></path></svg></div><h3 class=\\\"ep-feature-card-title\\\">{{feature1Title}}</h3><p class=\\\"ep-feature-card-description\\\">{{feature1Description}}</p></div><div class=\\\"ep-feature-card\\\"><div class=\\\"ep-feature-card-icon\\\"><svg width=\\\"32\\\" height=\\\"32\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><path d=\\\"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z\\\"></path></svg></div><h3 class=\\\"ep-feature-card-title\\\">{{feature2Title}}</h3><p class=\\\"ep-feature-card-description\\\">{{feature2Description}}</p></div><div class=\\\"ep-feature-card\\\"><div class=\\\"ep-feature-card-icon\\\"><svg width=\\\"32\\\" height=\\\"32\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><path d=\\\"M13 2L3 14h9l-1 8 10-12h-9l1-8z\\\"></path></svg></div><h3 class=\\\"ep-feature-card-title\\\">{{feature3Title}}</h3><p class=\\\"ep-feature-card-description\\\">{{feature3Description}}</p></div><div class=\\\"ep-feature-card\\\"><div class=\\\"ep-feature-card-icon\\\"><svg width=\\\"32\\\" height=\\\"32\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><path d=\\\"M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z\\\"></path><polyline points=\\\"7.5,4.21 12,6.81 16.5,4.21\\\"></polyline><polyline points=\\\"7.5,19.79 7.5,14.6 3,12\\\"></polyline><polyline points=\\\"21,12 16.5,14.6 16.5,19.79\\\"></polyline></svg></div><h3 class=\\\"ep-feature-card-title\\\">{{feature4Title}}</h3><p class=\\\"ep-feature-card-description\\\">{{feature4Description}}</p></div></div></div><div class=\\\"ep-fullscreen-pricing\\\"><div class=\\\"ep-pricing-header\\\"><h2 class=\\\"ep-heading-2\\\">{{plansHeading}}</h2><p class=\\\"ep-pricing-subtitle\\\">{{pricingSubtitle}}</p></div><div class=\\\"ep-pricing-plans\\\"><div class=\\\"ep-pricing-plan\\\"><div class=\\\"ep-pricing-plan-header\\\"><h3 class=\\\"ep-pricing-plan-title\\\">{{freePlanName}}</h3><div class=\\\"ep-pricing-plan-price\\\"><span class=\\\"ep-pricing-currency\\\">{{currency}}</span><span class=\\\"ep-pricing-amount\\\">0</span></div><p class=\\\"ep-pricing-plan-description\\\">{{freeDescription}}</p></div><ul class=\\\"ep-pricing-plan-features\\\"><li class=\\\"ep-pricing-feature\\\"><svg class=\\\"ep-pricing-feature-icon\\\" width=\\\"20\\\" height=\\\"20\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><polyline points=\\\"20,6 9,17 4,12\\\"></polyline></svg> {{freeFeature1}} </li><li class=\\\"ep-pricing-feature\\\"><svg class=\\\"ep-pricing-feature-icon\\\" width=\\\"20\\\" height=\\\"20\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><polyline points=\\\"20,6 9,17 4,12\\\"></polyline></svg> {{freeFeature2}} </li><li class=\\\"ep-pricing-feature ep-pricing-feature-disabled\\\"><svg class=\\\"ep-pricing-feature-icon\\\" width=\\\"20\\\" height=\\\"20\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><line x1=\\\"18\\\" y1=\\\"6\\\" x2=\\\"6\\\" y2=\\\"18\\\"></line><line x1=\\\"6\\\" y1=\\\"6\\\" x2=\\\"18\\\" y2=\\\"18\\\"></line></svg> {{freeFeature3}} </li></ul><button class=\\\"ep-btn ep-btn-secondary ep-btn-full\\\" data-ep-action=\\\"continueFree\\\"> {{continueButtonText}} </button></div><div class=\\\"ep-pricing-plan ep-pricing-plan-premium\\\"><div class=\\\"ep-pricing-plan-badge\\\">{{premiumBadge}}</div><div class=\\\"ep-pricing-plan-header\\\"><h3 class=\\\"ep-pricing-plan-title\\\">{{premiumPlanName}}</h3><div class=\\\"ep-pricing-plan-price\\\"><span class=\\\"ep-pricing-currency\\\">{{currency}}</span><span class=\\\"ep-pricing-amount\\\">{{price}}</span><span class=\\\"ep-pricing-period\\\">{{period}}</span></div><p class=\\\"ep-pricing-plan-description\\\">{{premiumDescription}}</p></div><ul class=\\\"ep-pricing-plan-features\\\"><li class=\\\"ep-pricing-feature\\\"><svg class=\\\"ep-pricing-feature-icon\\\" width=\\\"20\\\" height=\\\"20\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><polyline points=\\\"20,6 9,17 4,12\\\"></polyline></svg> {{premiumFeature1}} </li><li class=\\\"ep-pricing-feature\\\"><svg class=\\\"ep-pricing-feature-icon\\\" width=\\\"20\\\" height=\\\"20\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><polyline points=\\\"20,6 9,17 4,12\\\"></polyline></svg> {{premiumFeature2}} </li><li class=\\\"ep-pricing-feature\\\"><svg class=\\\"ep-pricing-feature-icon\\\" width=\\\"20\\\" height=\\\"20\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><polyline points=\\\"20,6 9,17 4,12\\\"></polyline></svg> {{premiumFeature3}} </li><li class=\\\"ep-pricing-feature\\\"><svg class=\\\"ep-pricing-feature-icon\\\" width=\\\"20\\\" height=\\\"20\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><polyline points=\\\"20,6 9,17 4,12\\\"></polyline></svg> {{premiumFeature4}} </li></ul><button class=\\\"ep-btn ep-btn-primary ep-btn-lg ep-btn-full\\\" data-ep-action=\\\"upgradeNow\\\"> {{upgradeButtonText}} </button></div></div></div><div class=\\\"ep-fullscreen-trial\\\"><div class=\\\"ep-trial-card\\\"><div class=\\\"ep-trial-icon\\\"><svg width=\\\"32\\\" height=\\\"32\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><path d=\\\"M22 11.08V12a10 10 0 1 1-5.93-9.14\\\"></path><polyline points=\\\"22,4 12,14.01 9,11.01\\\"></polyline></svg></div><h3 class=\\\"ep-trial-title\\\">{{trialTitle}}</h3><p class=\\\"ep-trial-description\\\">{{trialDescription}}</p><button class=\\\"ep-btn ep-btn-secondary ep-btn-lg\\\" data-ep-action=\\\"startTrial\\\"> {{trialButtonText}} </button></div></div></div></div></div>\";\nexport const css = \".ep-fullscreen-paywall{position:fixed;top:0;left:0;right:0;bottom:0;background-color:var(--ep-bg-primary);z-index:var(--ep-z-modal);display:flex;flex-direction:column;animation:ep-fullscreen-in var(--ep-transition-slow);overflow-y:auto}.ep-fullscreen-paywall.ep-fullscreen-closing{animation:ep-fullscreen-out var(--ep-transition-slow)}.ep-fullscreen-background{position:absolute;top:0;left:0;right:0;bottom:0;overflow:hidden;z-index:-1}.ep-background-pattern{position:absolute;top:-50%;left:-50%;width:200%;height:200%;background:linear-gradient(45deg,transparent 30%,rgba(14,165,233,0.03) 50%,transparent 70%);background-size:60px 60px;animation:ep-background-pattern var(--ep-transition-slow) infinite linear}:host([data-theme=\\\"dark\\\"]) .ep-background-pattern{background:linear-gradient(45deg,transparent 30%,rgba(14,165,233,0.05) 50%,transparent 70%)}.ep-fullscreen-header{display:flex;justify-content:space-between;align-items:center;padding:var(--ep-space-6) var(--ep-space-8);border-bottom:1px solid var(--ep-border-primary);background-color:var(--ep-bg-secondary);backdrop-filter:blur(10px);z-index:1}.ep-fullscreen-logo{display:flex;align-items:center;gap:var(--ep-space-3);color:var(--ep-primary-600)}.ep-fullscreen-logo-text{font-size:var(--ep-font-size-xl);font-weight:var(--ep-font-weight-bold);color:var(--ep-text-primary)}.ep-fullscreen-close{background:none;border:none;color:var(--ep-text-tertiary);cursor:pointer;padding:var(--ep-space-2);border-radius:var(--ep-radius-md);transition:all var(--ep-transition-fast)}.ep-fullscreen-close:hover{color:var(--ep-text-primary);background-color:var(--ep-bg-tertiary)}.ep-fullscreen-content{flex:1;padding:var(--ep-space-8);display:flex;align-items:center;justify-content:center}.ep-fullscreen-container{max-width:1200px;width:100%;margin:0 auto}.ep-fullscreen-hero{text-align:center;margin-bottom:var(--ep-space-16)}.ep-hero-icon{width:120px;height:120px;margin:0 auto var(--ep-space-6);background:linear-gradient(135deg,var(--ep-primary-500),var(--ep-primary-600));border-radius:var(--ep-radius-2xl);display:flex;align-items:center;justify-content:center;color:white;box-shadow:var(--ep-shadow-lg);animation:ep-hero-icon-in var(--ep-transition-slow) 0.2s both}.ep-fullscreen-hero .ep-heading-1{font-size:var(--ep-font-size-5xl);margin-bottom:var(--ep-space-6);background:linear-gradient(135deg,var(--ep-primary-600),var(--ep-primary-700));-webkit-background-clip:text;-webkit-text-fill-color:transparent;background-clip:text;animation:ep-hero-title-in var(--ep-transition-slow) 0.3s both}.ep-hero-description{font-size:var(--ep-font-size-xl);color:var(--ep-text-secondary);max-width:600px;margin:0 auto;line-height:var(--ep-line-height-relaxed);animation:ep-hero-description-in var(--ep-transition-slow) 0.4s both}.ep-fullscreen-features{margin-bottom:var(--ep-space-16)}.ep-features-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(280px,1fr));gap:var(--ep-space-6)}.ep-feature-card{background-color:var(--ep-bg-secondary);border:1px solid var(--ep-border-primary);border-radius:var(--ep-radius-xl);padding:var(--ep-space-8);text-align:center;box-shadow:var(--ep-shadow-sm);transition:all var(--ep-transition-normal);opacity:0;transform:translateY(20px);animation:ep-feature-card-in var(--ep-transition-slow) both}.ep-feature-card:hover{transform:translateY(-4px);box-shadow:var(--ep-shadow-lg)}.ep-feature-card-icon{width:80px;height:80px;margin:0 auto var(--ep-space-4);background:linear-gradient(135deg,var(--ep-primary-500),var(--ep-primary-600));border-radius:var(--ep-radius-xl);display:flex;align-items:center;justify-content:center;color:white}.ep-feature-card-title{font-size:var(--ep-font-size-xl);font-weight:var(--ep-font-weight-semibold);color:var(--ep-text-primary);margin-bottom:var(--ep-space-3)}.ep-feature-card-description{color:var(--ep-text-secondary);line-height:var(--ep-line-height-relaxed);margin:0}.ep-fullscreen-pricing{margin-bottom:var(--ep-space-16)}.ep-pricing-header{text-align:center;margin-bottom:var(--ep-space-10)}.ep-pricing-header .ep-heading-2{font-size:var(--ep-font-size-4xl);margin-bottom:var(--ep-space-4)}.ep-pricing-subtitle{font-size:var(--ep-font-size-lg);color:var(--ep-text-secondary);margin:0}.ep-pricing-plans{display:grid;grid-template-columns:repeat(auto-fit,minmax(320px,1fr));gap:var(--ep-space-8);max-width:800px;margin:0 auto}.ep-pricing-plan{position:relative;background-color:var(--ep-bg-secondary);border:1px solid var(--ep-border-primary);border-radius:var(--ep-radius-xl);padding:var(--ep-space-8);box-shadow:var(--ep-shadow-md);transition:all var(--ep-transition-normal);opacity:0;transform:translateY(20px);animation:ep-pricing-plan-in var(--ep-transition-slow) both}.ep-pricing-plan:hover{transform:translateY(-4px);box-shadow:var(--ep-shadow-lg)}.ep-pricing-plan-premium{border-color:var(--ep-primary-300);box-shadow:var(--ep-shadow-xl);transform:scale(1.05)}.ep-pricing-plan-premium:hover{transform:scale(1.05) translateY(-4px)}.ep-pricing-plan-badge{position:absolute;top:-16px;left:50%;transform:translateX(-50%);background:linear-gradient(135deg,var(--ep-primary-500),var(--ep-primary-600));color:white;padding:var(--ep-space-2) var(--ep-space-6);border-radius:var(--ep-radius-full);font-size:var(--ep-font-size-sm);font-weight:var(--ep-font-weight-semibold);white-space:nowrap}.ep-pricing-plan-header{text-align:center;margin-bottom:var(--ep-space-8)}.ep-pricing-plan-title{font-size:var(--ep-font-size-2xl);font-weight:var(--ep-font-weight-bold);color:var(--ep-text-primary);margin-bottom:var(--ep-space-4)}.ep-pricing-plan-price{display:flex;align-items:baseline;justify-content:center;gap:var(--ep-space-2);margin-bottom:var(--ep-space-3)}.ep-pricing-currency{font-size:var(--ep-font-size-xl);font-weight:var(--ep-font-weight-medium);color:var(--ep-text-secondary)}.ep-pricing-amount{font-size:var(--ep-font-size-5xl);font-weight:var(--ep-font-weight-bold);color:var(--ep-text-primary)}.ep-pricing-period{font-size:var(--ep-font-size-xl);color:var(--ep-text-secondary)}.ep-pricing-plan-description{color:var(--ep-text-secondary);margin:0}.ep-pricing-plan-features{list-style:none;padding:0;margin:0 0 var(--ep-space-8) 0}.ep-pricing-feature{display:flex;align-items:center;gap:var(--ep-space-3);padding:var(--ep-space-3) 0;color:var(--ep-text-primary);font-size:var(--ep-font-size-base)}.ep-pricing-feature-disabled{color:var(--ep-text-tertiary)}.ep-pricing-feature-icon{color:var(--ep-success-500);flex-shrink:0}.ep-pricing-feature-disabled .ep-pricing-feature-icon{color:var(--ep-text-tertiary)}.ep-fullscreen-trial{text-align:center}.ep-trial-card{background:linear-gradient(135deg,var(--ep-success-50),var(--ep-success-100));border:1px solid var(--ep-success-200);border-radius:var(--ep-radius-xl);padding:var(--ep-space-8);max-width:600px;margin:0 auto;box-shadow:var(--ep-shadow-md)}:host([data-theme=\\\"dark\\\"]) .ep-trial-card{background:linear-gradient(135deg,rgba(16,185,129,0.1),rgba(16,185,129,0.15));border-color:rgba(16,185,129,0.3)}.ep-trial-icon{width:80px;height:80px;margin:0 auto var(--ep-space-4);background:linear-gradient(135deg,var(--ep-success-500),var(--ep-success-600));border-radius:var(--ep-radius-xl);display:flex;align-items:center;justify-content:center;color:white}.ep-trial-title{font-size:var(--ep-font-size-2xl);font-weight:var(--ep-font-weight-bold);color:var(--ep-success-700);margin-bottom:var(--ep-space-3)}:host([data-theme=\\\"dark\\\"]) .ep-trial-title{color:var(--ep-success-400)}.ep-trial-description{color:var(--ep-success-600);font-size:var(--ep-font-size-lg);line-height:var(--ep-line-height-relaxed);margin-bottom:var(--ep-space-6)}:host([data-theme=\\\"dark\\\"]) .ep-trial-description{color:var(--ep-success-300)}.ep-theme-toggle{position:fixed;top:var(--ep-space-4);right:var(--ep-space-4);z-index:var(--ep-z-tooltip)}@keyframes ep-fullscreen-in{from{opacity:0;transform:scale(0.98)}to{opacity:1;transform:scale(1)}}@keyframes ep-fullscreen-out{from{opacity:1;transform:scale(1)}to{opacity:0;transform:scale(0.98)}}@keyframes ep-background-pattern{from{transform:translateX(0) translateY(0)}to{transform:translateX(-60px) translateY(-60px)}}@keyframes ep-hero-icon-in{from{opacity:0;transform:scale(0.8)}to{opacity:1;transform:scale(1)}}@keyframes ep-hero-title-in{from{opacity:0;transform:translateY(20px)}to{opacity:1;transform:translateY(0)}}@keyframes ep-hero-description-in{from{opacity:0;transform:translateY(20px)}to{opacity:1;transform:translateY(0)}}@keyframes ep-feature-card-in{from{opacity:0;transform:translateY(20px)}to{opacity:1;transform:translateY(0)}}@keyframes ep-pricing-plan-in{from{opacity:0;transform:translateY(20px)}to{opacity:1;transform:translateY(0)}}@media (max-width:1024px){.ep-fullscreen-content{padding:var(--ep-space-6)}.ep-fullscreen-hero{margin-bottom:var(--ep-space-12)}.ep-fullscreen-features{margin-bottom:var(--ep-space-12)}.ep-fullscreen-pricing{margin-bottom:var(--ep-space-12)}.ep-features-grid{grid-template-columns:repeat(auto-fit,minmax(250px,1fr));gap:var(--ep-space-4)}.ep-pricing-plans{gap:var(--ep-space-6)}}@media (max-width:768px){.ep-fullscreen-header{padding:var(--ep-space-4) var(--ep-space-6)}.ep-fullscreen-content{padding:var(--ep-space-4)}.ep-fullscreen-hero .ep-heading-1{font-size:var(--ep-font-size-3xl)}.ep-hero-description{font-size:var(--ep-font-size-lg)}.ep-hero-icon{width:80px;height:80px}.ep-features-grid{grid-template-columns:1fr}.ep-pricing-plans{grid-template-columns:1fr}.ep-pricing-plan-premium{transform:none}.ep-pricing-plan-premium:hover{transform:translateY(-4px)}.ep-feature-card{padding:var(--ep-space-6)}.ep-feature-card-icon{width:60px;height:60px}.ep-pricing-plan{padding:var(--ep-space-6)}.ep-pricing-amount{font-size:var(--ep-font-size-4xl)}}@media (max-width:480px){.ep-fullscreen-header{padding:var(--ep-space-3) var(--ep-space-4)}.ep-fullscreen-logo-text{font-size:var(--ep-font-size-lg)}.ep-fullscreen-content{padding:var(--ep-space-3)}.ep-fullscreen-hero .ep-heading-1{font-size:var(--ep-font-size-2xl)}.ep-hero-description{font-size:var(--ep-font-size-base)}.ep-hero-icon{width:60px;height:60px}.ep-pricing-header .ep-heading-2{font-size:var(--ep-font-size-2xl)}.ep-pricing-amount{font-size:var(--ep-font-size-3xl)}.ep-feature-card-icon{width:48px;height:48px}.ep-trial-icon{width:60px;height:60px}}@media (prefers-contrast:high){.ep-fullscreen-paywall{background-color:var(--ep-bg-primary)}.ep-feature-card{border:2px solid var(--ep-border-secondary)}.ep-pricing-plan{border:2px solid var(--ep-border-secondary)}.ep-pricing-plan-premium{border:2px solid var(--ep-primary-500)}.ep-trial-card{border:2px solid var(--ep-success-500)}}@media (prefers-reduced-motion:reduce){.ep-fullscreen-paywall{animation:none}.ep-background-pattern{animation:none}.ep-hero-icon{animation:none}.ep-fullscreen-hero .ep-heading-1{animation:none}.ep-hero-description{animation:none}.ep-feature-card{animation:none;opacity:1;transform:none}.ep-pricing-plan{animation:none;opacity:1;transform:none}.ep-pricing-plan-premium{transform:none}.ep-feature-card:hover{transform:none}.ep-pricing-plan:hover{transform:none}}\";\nexport default { html, css };","/**\n * The five templates from `@extenshi/paywall-templates`, inlined at build\n * time by build/paywall-templates-plugin.mjs. No runtime fetch, no\n * `web_accessible_resources`, no remote code.\n */\n\nimport sharedCss from 'virtual:extenshi-paywall-shared-css'\nimport * as fullscreen from '@extenshi/paywall-templates/fullscreen'\nimport * as inline from '@extenshi/paywall-templates/inline'\nimport * as minimal from '@extenshi/paywall-templates/minimal'\nimport * as modal from '@extenshi/paywall-templates/modal'\nimport * as sidebar from '@extenshi/paywall-templates/sidebar'\nimport type { PaywallMode } from '../types/paywall.js'\n\nexport interface PaywallTemplate {\n\thtml: string\n\tcss: string\n}\n\nexport const PAYWALL_SHARED_CSS: string = sharedCss\n\nexport const PAYWALL_TEMPLATES: Record<PaywallMode, PaywallTemplate> = {\n\tmodal: { html: modal.html, css: modal.css },\n\tinline: { html: inline.html, css: inline.css },\n\tsidebar: { html: sidebar.html, css: sidebar.css },\n\tfullscreen: { html: fullscreen.html, css: fullscreen.css },\n\tminimal: { html: minimal.html, css: minimal.css },\n}\n\nexport const PAYWALL_MODES = Object.keys(PAYWALL_TEMPLATES) as PaywallMode[]\n","export const html = \"<div class=\\\"ep-modal-backdrop\\\" id=\\\"paywallModal\\\" role=\\\"dialog\\\" aria-labelledby=\\\"paywall-title\\\" aria-describedby=\\\"paywall-description\\\"><div class=\\\"ep-modal-container\\\"><button class=\\\"ep-modal-close\\\" aria-label=\\\"Close paywall\\\" data-ep-action=\\\"closePaywall\\\"><svg width=\\\"24\\\" height=\\\"24\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><line x1=\\\"18\\\" y1=\\\"6\\\" x2=\\\"6\\\" y2=\\\"18\\\"></line><line x1=\\\"6\\\" y1=\\\"6\\\" x2=\\\"18\\\" y2=\\\"18\\\"></line></svg></button><div class=\\\"ep-modal-content\\\"><div class=\\\"ep-modal-header\\\"><div class=\\\"ep-modal-icon\\\"><svg width=\\\"48\\\" height=\\\"48\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><rect x=\\\"3\\\" y=\\\"11\\\" width=\\\"18\\\" height=\\\"11\\\" rx=\\\"2\\\" ry=\\\"2\\\"></rect><path d=\\\"m7 11V7a5 5 0 0 1 10 0v4\\\"></path></svg></div><h2 class=\\\"ep-heading-2\\\" id=\\\"paywall-title\\\">{{title}}</h2><p class=\\\"ep-text-body\\\" id=\\\"paywall-description\\\">{{description}}</p></div><div class=\\\"ep-modal-features\\\"><h3 class=\\\"ep-heading-3\\\">{{featuresHeading}}</h3><ul class=\\\"ep-feature-list\\\"><li class=\\\"ep-feature-item\\\"><svg class=\\\"ep-feature-icon\\\" width=\\\"20\\\" height=\\\"20\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><polyline points=\\\"20,6 9,17 4,12\\\"></polyline></svg><span>{{feature1}}</span></li><li class=\\\"ep-feature-item\\\"><svg class=\\\"ep-feature-icon\\\" width=\\\"20\\\" height=\\\"20\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><polyline points=\\\"20,6 9,17 4,12\\\"></polyline></svg><span>{{feature2}}</span></li><li class=\\\"ep-feature-item\\\"><svg class=\\\"ep-feature-icon\\\" width=\\\"20\\\" height=\\\"20\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><polyline points=\\\"20,6 9,17 4,12\\\"></polyline></svg><span>{{feature3}}</span></li><li class=\\\"ep-feature-item\\\"><svg class=\\\"ep-feature-icon\\\" width=\\\"20\\\" height=\\\"20\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><polyline points=\\\"20,6 9,17 4,12\\\"></polyline></svg><span>{{feature4}}</span></li><li class=\\\"ep-feature-item\\\"><svg class=\\\"ep-feature-icon\\\" width=\\\"20\\\" height=\\\"20\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><polyline points=\\\"20,6 9,17 4,12\\\"></polyline></svg><span>{{feature5}}</span></li><li class=\\\"ep-feature-item\\\"><svg class=\\\"ep-feature-icon\\\" width=\\\"20\\\" height=\\\"20\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><polyline points=\\\"20,6 9,17 4,12\\\"></polyline></svg><span>{{feature6}}</span></li></ul></div><div class=\\\"ep-modal-pricing\\\"><div class=\\\"ep-pricing-card\\\"><div class=\\\"ep-pricing-header\\\"><div class=\\\"ep-pricing-price\\\"><span class=\\\"ep-pricing-currency\\\">{{currency}}</span><span class=\\\"ep-pricing-amount\\\">{{price}}</span><span class=\\\"ep-pricing-period\\\">{{period}}</span></div><p class=\\\"ep-pricing-description\\\">{{pricingDescription}}</p></div><div class=\\\"ep-trial-info\\\"><p class=\\\"ep-text-sm\\\">{{trialInfo}}</p></div></div></div><div class=\\\"ep-modal-actions\\\"><button class=\\\"ep-btn ep-btn-primary ep-btn-lg ep-btn-full\\\" data-ep-action=\\\"upgradeNow\\\"> {{upgradeButtonText}} </button><button class=\\\"ep-btn ep-btn-ghost ep-btn-sm\\\" data-ep-action=\\\"closePaywall\\\"> {{cancelButtonText}} </button></div><div class=\\\"ep-modal-footer\\\"><p class=\\\"ep-text-sm\\\">{{footerText}}</p></div></div></div></div>\";\nexport const css = \".ep-modal-backdrop{position:fixed;top:0;left:0;right:0;bottom:0;background-color:rgba(0,0,0,0.75);backdrop-filter:blur(4px);z-index:var(--ep-z-modal);display:flex;align-items:center;justify-content:center;padding:var(--ep-space-4);animation:ep-modal-backdrop-in var(--ep-transition-normal)}.ep-modal-backdrop.ep-modal-closing{animation:ep-modal-backdrop-out var(--ep-transition-normal)}.ep-modal-container{position:relative;background-color:var(--ep-bg-secondary);border-radius:var(--ep-radius-xl);box-shadow:var(--ep-shadow-xl);max-width:480px;width:100%;max-height:90vh;overflow-y:auto;animation:ep-modal-container-in var(--ep-transition-normal)}.ep-modal-backdrop.ep-modal-closing .ep-modal-container{animation:ep-modal-container-out var(--ep-transition-normal)}.ep-modal-close{position:absolute;top:var(--ep-space-4);right:var(--ep-space-4);background:none;border:none;color:var(--ep-text-tertiary);cursor:pointer;padding:var(--ep-space-2);border-radius:var(--ep-radius-md);transition:all var(--ep-transition-fast);z-index:1}.ep-modal-close:hover{color:var(--ep-text-primary);background-color:var(--ep-bg-tertiary)}.ep-modal-close:focus{outline:2px solid var(--ep-primary-500);outline-offset:2px}.ep-modal-content{padding:var(--ep-space-8);padding-top:var(--ep-space-12)}.ep-modal-header{text-align:center;margin-bottom:var(--ep-space-8)}.ep-modal-icon{width:80px;height:80px;margin:0 auto var(--ep-space-4);background:linear-gradient(135deg,var(--ep-primary-500),var(--ep-primary-600));border-radius:var(--ep-radius-2xl);display:flex;align-items:center;justify-content:center;color:white}.ep-modal-header .ep-heading-2{margin-bottom:var(--ep-space-3)}.ep-modal-header .ep-text-body{margin-bottom:0;font-size:var(--ep-font-size-lg)}.ep-modal-features{margin-bottom:var(--ep-space-8)}.ep-modal-features .ep-heading-3{margin-bottom:var(--ep-space-4);text-align:center}.ep-feature-list{list-style:none;padding:0;margin:0}.ep-feature-item{display:flex;align-items:center;gap:var(--ep-space-3);padding:var(--ep-space-3) 0;border-bottom:1px solid var(--ep-border-primary)}.ep-feature-item:last-child{border-bottom:none}.ep-feature-icon{color:var(--ep-success-500);flex-shrink:0}.ep-feature-item span{color:var(--ep-text-primary);font-weight:var(--ep-font-weight-medium)}.ep-modal-pricing{margin-bottom:var(--ep-space-8)}.ep-pricing-card{background:linear-gradient(135deg,var(--ep-primary-50),var(--ep-primary-100));border:1px solid var(--ep-primary-200);border-radius:var(--ep-radius-lg);padding:var(--ep-space-6);text-align:center}:host([data-theme=\\\"dark\\\"]) .ep-pricing-card{background:linear-gradient(135deg,var(--ep-primary-900),var(--ep-primary-800));border-color:var(--ep-primary-700)}.ep-pricing-header{margin-bottom:var(--ep-space-4)}.ep-pricing-price{display:flex;align-items:baseline;justify-content:center;gap:var(--ep-space-1);margin-bottom:var(--ep-space-2)}.ep-pricing-currency{font-size:var(--ep-font-size-lg);font-weight:var(--ep-font-weight-medium);color:var(--ep-text-secondary)}.ep-pricing-amount{font-size:var(--ep-font-size-4xl);font-weight:var(--ep-font-weight-bold);color:var(--ep-text-primary)}.ep-pricing-period{font-size:var(--ep-font-size-lg);color:var(--ep-text-secondary)}.ep-pricing-description{color:var(--ep-text-secondary);margin:0}.ep-pricing-header:last-child,.ep-pricing-price:last-child{margin-bottom:0}.ep-trial-info{background-color:var(--ep-success-50);border:1px solid var(--ep-success-200);border-radius:var(--ep-radius-md);padding:var(--ep-space-3);margin-top:var(--ep-space-4)}:host([data-theme=\\\"dark\\\"]) .ep-trial-info{background-color:rgba(16,185,129,0.1);border-color:rgba(16,185,129,0.3)}.ep-trial-info .ep-text-sm{color:var(--ep-success-700);margin:0;font-weight:var(--ep-font-weight-medium)}:host([data-theme=\\\"dark\\\"]) .ep-trial-info .ep-text-sm{color:var(--ep-success-400)}.ep-modal-actions{display:flex;flex-direction:column;gap:var(--ep-space-3);margin-bottom:var(--ep-space-6)}.ep-modal-footer{text-align:center;padding-top:var(--ep-space-6);border-top:1px solid var(--ep-border-primary)}.ep-modal-footer .ep-text-sm{margin:0}.ep-theme-toggle{position:fixed;top:var(--ep-space-4);left:var(--ep-space-4);z-index:var(--ep-z-tooltip)}@keyframes ep-modal-backdrop-in{from{opacity:0}to{opacity:1}}@keyframes ep-modal-backdrop-out{from{opacity:1}to{opacity:0}}@keyframes ep-modal-container-in{from{opacity:0;transform:scale(0.95) translateY(-10px)}to{opacity:1;transform:scale(1) translateY(0)}}@keyframes ep-modal-container-out{from{opacity:1;transform:scale(1) translateY(0)}to{opacity:0;transform:scale(0.95) translateY(-10px)}}@media (max-width:640px){.ep-modal-backdrop{padding:var(--ep-space-2)}.ep-modal-container{max-width:100%;border-radius:var(--ep-radius-lg)}.ep-modal-content{padding:var(--ep-space-6);padding-top:var(--ep-space-10)}.ep-modal-icon{width:60px;height:60px}.ep-modal-header .ep-heading-2{font-size:var(--ep-font-size-xl)}.ep-pricing-amount{font-size:var(--ep-font-size-3xl)}}@media (max-width:480px){.ep-modal-content{padding:var(--ep-space-4);padding-top:var(--ep-space-8)}.ep-modal-close{top:var(--ep-space-3);right:var(--ep-space-3)}}@media (prefers-contrast:high){.ep-modal-backdrop{background-color:rgba(0,0,0,0.9);backdrop-filter:none}.ep-modal-container{border:2px solid var(--ep-border-secondary)}.ep-pricing-card{background:var(--ep-bg-secondary);border:2px solid var(--ep-primary-500)}}@media (prefers-reduced-motion:reduce){.ep-modal-backdrop{animation:none}.ep-modal-container{animation:none}.ep-modal-backdrop.ep-modal-closing{animation:none}.ep-modal-backdrop.ep-modal-closing .ep-modal-container{animation:none}}\";\nexport default { html, css };","export const html = \"<div class=\\\"ep-inline-paywall\\\" id=\\\"inlinePaywall\\\" role=\\\"region\\\" aria-labelledby=\\\"paywall-title\\\"><div class=\\\"ep-inline-header\\\"><div class=\\\"ep-inline-icon\\\"><svg width=\\\"32\\\" height=\\\"32\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><path d=\\\"M9 12l2 2 4-4\\\"></path><path d=\\\"M21 12c-1 0-3-1-3-3s2-3 3-3 3 1 3 3-2 3-3 3\\\"></path><path d=\\\"M3 12c1 0 3-1 3-3s-2-3-3-3-3 1-3 3 2 3 3 3\\\"></path></svg></div><div class=\\\"ep-inline-header-content\\\"><h3 class=\\\"ep-heading-3\\\" id=\\\"paywall-title\\\">{{title}}</h3><p class=\\\"ep-text-body\\\">{{description}}</p></div></div><div class=\\\"ep-inline-content\\\"><div class=\\\"ep-inline-features\\\"><div class=\\\"ep-feature-grid\\\"><div class=\\\"ep-feature-card\\\"><div class=\\\"ep-feature-card-icon\\\"><svg width=\\\"24\\\" height=\\\"24\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><path d=\\\"M22 12h-4l-3 9L9 3l-3 9H2\\\"></path></svg></div><h4 class=\\\"ep-feature-card-title\\\">{{feature1Title}}</h4><p class=\\\"ep-feature-card-description\\\">{{feature1Description}}</p></div><div class=\\\"ep-feature-card\\\"><div class=\\\"ep-feature-card-icon\\\"><svg width=\\\"24\\\" height=\\\"24\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><path d=\\\"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z\\\"></path></svg></div><h4 class=\\\"ep-feature-card-title\\\">{{feature2Title}}</h4><p class=\\\"ep-feature-card-description\\\">{{feature2Description}}</p></div><div class=\\\"ep-feature-card\\\"><div class=\\\"ep-feature-card-icon\\\"><svg width=\\\"24\\\" height=\\\"24\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><path d=\\\"M13 2L3 14h9l-1 8 10-12h-9l1-8z\\\"></path></svg></div><h4 class=\\\"ep-feature-card-title\\\">{{feature3Title}}</h4><p class=\\\"ep-feature-card-description\\\">{{feature3Description}}</p></div></div></div><div class=\\\"ep-inline-pricing\\\"><div class=\\\"ep-pricing-comparison\\\"><div class=\\\"ep-pricing-plan\\\"><div class=\\\"ep-pricing-plan-header\\\"><h4 class=\\\"ep-pricing-plan-title\\\">{{freePlanName}}</h4><div class=\\\"ep-pricing-plan-price\\\"><span class=\\\"ep-pricing-currency\\\">{{currency}}</span><span class=\\\"ep-pricing-amount\\\">0</span></div></div><ul class=\\\"ep-pricing-plan-features\\\"><li class=\\\"ep-pricing-feature\\\"><svg class=\\\"ep-pricing-feature-icon\\\" width=\\\"16\\\" height=\\\"16\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><polyline points=\\\"20,6 9,17 4,12\\\"></polyline></svg> {{freeFeature1}} </li><li class=\\\"ep-pricing-feature\\\"><svg class=\\\"ep-pricing-feature-icon\\\" width=\\\"16\\\" height=\\\"16\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><polyline points=\\\"20,6 9,17 4,12\\\"></polyline></svg> {{freeFeature2}} </li><li class=\\\"ep-pricing-feature ep-pricing-feature-disabled\\\"><svg class=\\\"ep-pricing-feature-icon\\\" width=\\\"16\\\" height=\\\"16\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><line x1=\\\"18\\\" y1=\\\"6\\\" x2=\\\"6\\\" y2=\\\"18\\\"></line><line x1=\\\"6\\\" y1=\\\"6\\\" x2=\\\"18\\\" y2=\\\"18\\\"></line></svg> {{freeFeature3}} </li></ul></div><div class=\\\"ep-pricing-plan ep-pricing-plan-premium\\\"><div class=\\\"ep-pricing-plan-badge\\\">{{popularBadge}}</div><div class=\\\"ep-pricing-plan-header\\\"><h4 class=\\\"ep-pricing-plan-title\\\">{{premiumPlanName}}</h4><div class=\\\"ep-pricing-plan-price\\\"><span class=\\\"ep-pricing-currency\\\">{{currency}}</span><span class=\\\"ep-pricing-amount\\\">{{price}}</span><span class=\\\"ep-pricing-period\\\">{{period}}</span></div></div><ul class=\\\"ep-pricing-plan-features\\\"><li class=\\\"ep-pricing-feature\\\"><svg class=\\\"ep-pricing-feature-icon\\\" width=\\\"16\\\" height=\\\"16\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><polyline points=\\\"20,6 9,17 4,12\\\"></polyline></svg> {{premiumFeature1}} </li><li class=\\\"ep-pricing-feature\\\"><svg class=\\\"ep-pricing-feature-icon\\\" width=\\\"16\\\" height=\\\"16\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><polyline points=\\\"20,6 9,17 4,12\\\"></polyline></svg> {{premiumFeature2}} </li><li class=\\\"ep-pricing-feature\\\"><svg class=\\\"ep-pricing-feature-icon\\\" width=\\\"16\\\" height=\\\"16\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><polyline points=\\\"20,6 9,17 4,12\\\"></polyline></svg> {{premiumFeature3}} </li></ul><button class=\\\"ep-btn ep-btn-primary ep-btn-full\\\" data-ep-action=\\\"upgradeNow\\\"> {{upgradeButtonText}} </button></div></div></div><div class=\\\"ep-inline-trial\\\"><div class=\\\"ep-trial-content\\\"><p class=\\\"ep-trial-text\\\">{{trialText}}</p><div class=\\\"ep-trial-actions\\\"><button class=\\\"ep-btn ep-btn-secondary\\\" data-ep-action=\\\"startTrial\\\"> {{trialButtonText}} </button><button class=\\\"ep-btn ep-btn-ghost ep-btn-sm\\\" data-ep-action=\\\"dismissPaywall\\\"> {{dismissButtonText}} </button></div></div></div></div></div>\";\nexport const css = \".ep-inline-paywall{max-width:800px;margin:0 auto;background-color:var(--ep-bg-secondary);border:1px solid var(--ep-border-primary);border-radius:var(--ep-radius-lg);box-shadow:var(--ep-shadow-md);overflow:hidden;opacity:0;transform:translateY(20px);transition:all var(--ep-transition-slow)}.ep-inline-paywall.ep-inline-visible{opacity:1;transform:translateY(0)}.ep-inline-paywall.ep-inline-dismissing{opacity:0;transform:translateY(-20px);transition:all var(--ep-transition-normal)}.ep-inline-header{display:flex;align-items:center;gap:var(--ep-space-4);padding:var(--ep-space-6);background:linear-gradient(135deg,var(--ep-primary-50),var(--ep-primary-100));border-bottom:1px solid var(--ep-border-primary)}:host([data-theme=\\\"dark\\\"]) .ep-inline-header{background:linear-gradient(135deg,var(--ep-primary-900),var(--ep-primary-800))}.ep-inline-icon{width:64px;height:64px;background:linear-gradient(135deg,var(--ep-primary-500),var(--ep-primary-600));border-radius:var(--ep-radius-xl);display:flex;align-items:center;justify-content:center;color:white;flex-shrink:0}.ep-inline-header-content{flex:1;min-width:0}.ep-inline-header-content .ep-heading-3{margin-bottom:var(--ep-space-2);color:var(--ep-text-primary)}.ep-inline-header-content .ep-text-body{margin-bottom:0;color:var(--ep-text-secondary)}.ep-inline-content{padding:var(--ep-space-8)}.ep-inline-features{margin-bottom:var(--ep-space-8)}.ep-feature-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(240px,1fr));gap:var(--ep-space-4)}.ep-feature-card{background-color:var(--ep-bg-tertiary);border:1px solid var(--ep-border-primary);border-radius:var(--ep-radius-md);padding:var(--ep-space-4);text-align:center;transition:all var(--ep-transition-normal);opacity:0;transform:translateY(10px);animation:ep-feature-card-in var(--ep-transition-slow) forwards}.ep-feature-card:hover{transform:translateY(-2px);box-shadow:var(--ep-shadow-md)}.ep-feature-card-icon{width:48px;height:48px;margin:0 auto var(--ep-space-3);background:linear-gradient(135deg,var(--ep-primary-500),var(--ep-primary-600));border-radius:var(--ep-radius-lg);display:flex;align-items:center;justify-content:center;color:white}.ep-feature-card-title{font-size:var(--ep-font-size-lg);font-weight:var(--ep-font-weight-semibold);color:var(--ep-text-primary);margin-bottom:var(--ep-space-2)}.ep-feature-card-description{color:var(--ep-text-secondary);font-size:var(--ep-font-size-sm);line-height:var(--ep-line-height-relaxed);margin:0}.ep-inline-pricing{margin-bottom:var(--ep-space-8)}.ep-pricing-comparison{display:grid;grid-template-columns:repeat(auto-fit,minmax(280px,1fr));gap:var(--ep-space-4);max-width:600px;margin:0 auto}.ep-pricing-plan{position:relative;background-color:var(--ep-bg-secondary);border:1px solid var(--ep-border-primary);border-radius:var(--ep-radius-lg);padding:var(--ep-space-6);transition:all var(--ep-transition-normal)}.ep-pricing-plan:hover{transform:translateY(-2px);box-shadow:var(--ep-shadow-md)}.ep-pricing-plan-premium{border-color:var(--ep-primary-300);box-shadow:var(--ep-shadow-lg)}.ep-pricing-plan-badge{position:absolute;top:-12px;left:50%;transform:translateX(-50%);background:linear-gradient(135deg,var(--ep-primary-500),var(--ep-primary-600));color:white;padding:var(--ep-space-1) var(--ep-space-4);border-radius:var(--ep-radius-full);font-size:var(--ep-font-size-sm);font-weight:var(--ep-font-weight-medium);white-space:nowrap}.ep-pricing-plan-header{text-align:center;margin-bottom:var(--ep-space-6)}.ep-pricing-plan-title{font-size:var(--ep-font-size-xl);font-weight:var(--ep-font-weight-semibold);color:var(--ep-text-primary);margin-bottom:var(--ep-space-3)}.ep-pricing-plan-price{display:flex;align-items:baseline;justify-content:center;gap:var(--ep-space-1)}.ep-pricing-currency{font-size:var(--ep-font-size-lg);font-weight:var(--ep-font-weight-medium);color:var(--ep-text-secondary)}.ep-pricing-amount{font-size:var(--ep-font-size-3xl);font-weight:var(--ep-font-weight-bold);color:var(--ep-text-primary)}.ep-pricing-period{font-size:var(--ep-font-size-lg);color:var(--ep-text-secondary)}.ep-pricing-plan-features{list-style:none;padding:0;margin:0 0 var(--ep-space-6) 0}.ep-pricing-feature{display:flex;align-items:center;gap:var(--ep-space-3);padding:var(--ep-space-2) 0;color:var(--ep-text-primary);font-size:var(--ep-font-size-sm)}.ep-pricing-feature-disabled{color:var(--ep-text-tertiary)}.ep-pricing-feature-icon{color:var(--ep-success-500);flex-shrink:0}.ep-pricing-feature-disabled .ep-pricing-feature-icon{color:var(--ep-text-tertiary)}.ep-inline-trial{background:linear-gradient(135deg,var(--ep-gray-50),var(--ep-gray-100));border:1px solid var(--ep-border-primary);border-radius:var(--ep-radius-md);padding:var(--ep-space-6);text-align:center}:host([data-theme=\\\"dark\\\"]) .ep-inline-trial{background:linear-gradient(135deg,var(--ep-gray-800),var(--ep-gray-700))}.ep-trial-content{max-width:400px;margin:0 auto}.ep-trial-text{color:var(--ep-text-primary);font-size:var(--ep-font-size-lg);font-weight:var(--ep-font-weight-medium);margin-bottom:var(--ep-space-6)}.ep-trial-actions{display:flex;flex-direction:column;gap:var(--ep-space-3);align-items:center}.ep-theme-toggle{position:fixed;top:var(--ep-space-4);right:var(--ep-space-4);z-index:var(--ep-z-tooltip)}@keyframes ep-feature-card-in{from{opacity:0;transform:translateY(10px)}to{opacity:1;transform:translateY(0)}}@media (max-width:768px){.ep-inline-paywall{margin:var(--ep-space-4)}.ep-inline-header{flex-direction:column;text-align:center;gap:var(--ep-space-3)}.ep-inline-content{padding:var(--ep-space-6)}.ep-feature-grid{grid-template-columns:1fr}.ep-pricing-comparison{grid-template-columns:1fr}.ep-pricing-plan{padding:var(--ep-space-4)}.ep-trial-actions{flex-direction:column;width:100%}.ep-trial-actions .ep-btn{width:100%}}@media (max-width:640px){.ep-inline-paywall{margin:var(--ep-space-2);border-radius:var(--ep-radius-md)}.ep-inline-header{padding:var(--ep-space-4)}.ep-inline-content{padding:var(--ep-space-4)}.ep-inline-icon{width:48px;height:48px}.ep-feature-card-icon{width:40px;height:40px}.ep-pricing-plan{padding:var(--ep-space-3)}.ep-pricing-amount{font-size:var(--ep-font-size-2xl)}}@media (prefers-contrast:high){.ep-inline-paywall{border:2px solid var(--ep-border-secondary)}.ep-feature-card{border:2px solid var(--ep-border-secondary)}.ep-pricing-plan{border:2px solid var(--ep-border-secondary)}.ep-pricing-plan-premium{border:2px solid var(--ep-primary-500)}}@media (prefers-reduced-motion:reduce){.ep-inline-paywall{transition:none;opacity:1;transform:none}.ep-feature-card{transition:none;animation:none;opacity:1;transform:none}.ep-feature-card:hover{transform:none}.ep-pricing-plan:hover{transform:none}}\";\nexport default { html, css };","export const html = \"<div class=\\\"ep-sidebar-backdrop\\\" id=\\\"sidebarBackdrop\\\"></div><div class=\\\"ep-sidebar-paywall\\\" id=\\\"sidebarPaywall\\\" role=\\\"dialog\\\" aria-labelledby=\\\"sidebar-title\\\" aria-describedby=\\\"sidebar-description\\\"><div class=\\\"ep-sidebar-header\\\"><button class=\\\"ep-sidebar-close\\\" aria-label=\\\"Close paywall\\\" data-ep-action=\\\"closeSidebar\\\"><svg width=\\\"24\\\" height=\\\"24\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><line x1=\\\"18\\\" y1=\\\"6\\\" x2=\\\"6\\\" y2=\\\"18\\\"></line><line x1=\\\"6\\\" y1=\\\"6\\\" x2=\\\"18\\\" y2=\\\"18\\\"></line></svg></button><div class=\\\"ep-sidebar-logo\\\"><svg width=\\\"32\\\" height=\\\"32\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><path d=\\\"M12 2L2 7l10 5 10-5-10-5z\\\"></path><path d=\\\"M2 17l10 5 10-5\\\"></path><path d=\\\"M2 12l10 5 10-5\\\"></path></svg><span class=\\\"ep-sidebar-logo-text\\\">{{brandName}}</span></div></div><div class=\\\"ep-sidebar-content\\\"><div class=\\\"ep-sidebar-title-section\\\"><h2 class=\\\"ep-heading-2\\\" id=\\\"sidebar-title\\\">{{title}}</h2><p class=\\\"ep-text-body\\\" id=\\\"sidebar-description\\\">{{description}}</p></div><div class=\\\"ep-sidebar-progress\\\"><div class=\\\"ep-progress-header\\\"><span class=\\\"ep-progress-label\\\">{{progressLabel}}</span><span class=\\\"ep-progress-value\\\">{{usageCount}}/{{usageLimit}}</span></div><div class=\\\"ep-progress-bar\\\"><div class=\\\"ep-progress-fill\\\" style=\\\"width: {{progressPercentage}}%\\\"></div></div><p class=\\\"ep-progress-text\\\">{{progressText}}</p></div><div class=\\\"ep-sidebar-features\\\"><h3 class=\\\"ep-heading-3\\\">{{unlockHeading}}</h3><div class=\\\"ep-feature-list\\\"><div class=\\\"ep-feature-item\\\"><div class=\\\"ep-feature-icon\\\"><svg width=\\\"20\\\" height=\\\"20\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><path d=\\\"M12 2L2 7l10 5 10-5-10-5z\\\"></path><path d=\\\"M2 17l10 5 10-5\\\"></path><path d=\\\"M2 12l10 5 10-5\\\"></path></svg></div><div class=\\\"ep-feature-content\\\"><h4 class=\\\"ep-feature-title\\\">{{feature1Title}}</h4><p class=\\\"ep-feature-description\\\">{{feature1Description}}</p></div></div><div class=\\\"ep-feature-item\\\"><div class=\\\"ep-feature-icon\\\"><svg width=\\\"20\\\" height=\\\"20\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><path d=\\\"M22 12h-4l-3 9L9 3l-3 9H2\\\"></path></svg></div><div class=\\\"ep-feature-content\\\"><h4 class=\\\"ep-feature-title\\\">{{feature2Title}}</h4><p class=\\\"ep-feature-description\\\">{{feature2Description}}</p></div></div><div class=\\\"ep-feature-item\\\"><div class=\\\"ep-feature-icon\\\"><svg width=\\\"20\\\" height=\\\"20\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><path d=\\\"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z\\\"></path></svg></div><div class=\\\"ep-feature-content\\\"><h4 class=\\\"ep-feature-title\\\">{{feature3Title}}</h4><p class=\\\"ep-feature-description\\\">{{feature3Description}}</p></div></div></div></div><div class=\\\"ep-sidebar-pricing\\\"><div class=\\\"ep-pricing-card\\\"><div class=\\\"ep-pricing-header\\\"><div class=\\\"ep-pricing-badge\\\">{{pricingBadge}}</div><div class=\\\"ep-pricing-price\\\"><span class=\\\"ep-pricing-currency\\\">{{currency}}</span><span class=\\\"ep-pricing-amount\\\">{{price}}</span><span class=\\\"ep-pricing-period\\\">{{period}}</span></div><p class=\\\"ep-pricing-description\\\">{{pricingDescription}}</p></div></div></div><div class=\\\"ep-sidebar-trial\\\"><div class=\\\"ep-trial-info\\\"><div class=\\\"ep-trial-icon\\\"><svg width=\\\"20\\\" height=\\\"20\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><path d=\\\"M22 11.08V12a10 10 0 1 1-5.93-9.14\\\"></path><polyline points=\\\"22,4 12,14.01 9,11.01\\\"></polyline></svg></div><div class=\\\"ep-trial-content\\\"><h4 class=\\\"ep-trial-title\\\">{{trialTitle}}</h4><p class=\\\"ep-trial-description\\\">{{trialDescription}}</p></div></div></div></div><div class=\\\"ep-sidebar-footer\\\"><button class=\\\"ep-btn ep-btn-primary ep-btn-lg ep-btn-full\\\" data-ep-action=\\\"startUpgrade\\\"> {{upgradeButtonText}} </button><button class=\\\"ep-btn ep-btn-secondary ep-btn-full\\\" data-ep-action=\\\"startTrial\\\"> {{trialButtonText}} </button><button class=\\\"ep-btn ep-btn-ghost ep-btn-sm\\\" data-ep-action=\\\"remindLater\\\"> {{remindLaterText}} </button></div></div>\";\nexport const css = \".ep-sidebar-backdrop{position:fixed;top:0;left:0;right:0;bottom:0;background-color:rgba(0,0,0,0.5);backdrop-filter:blur(2px);z-index:var(--ep-z-backdrop);opacity:0;visibility:hidden;transition:all var(--ep-transition-normal)}.ep-sidebar-backdrop.ep-sidebar-backdrop-visible{opacity:1;visibility:visible}.ep-sidebar-paywall{position:fixed;top:0;right:0;bottom:0;width:400px;max-width:90vw;background-color:var(--ep-bg-secondary);border-left:1px solid var(--ep-border-primary);box-shadow:var(--ep-shadow-xl);z-index:var(--ep-z-modal);display:flex;flex-direction:column;transform:translateX(100%);transition:transform var(--ep-transition-normal)}.ep-sidebar-paywall.ep-sidebar-visible{transform:translateX(0)}.ep-sidebar-header{display:flex;align-items:center;justify-content:space-between;padding:var(--ep-space-4) var(--ep-space-6);border-bottom:1px solid var(--ep-border-primary);background:linear-gradient(135deg,var(--ep-primary-50),var(--ep-primary-100))}:host([data-theme=\\\"dark\\\"]) .ep-sidebar-header{background:linear-gradient(135deg,var(--ep-primary-900),var(--ep-primary-800))}.ep-sidebar-close{background:none;border:none;color:var(--ep-text-tertiary);cursor:pointer;padding:var(--ep-space-2);border-radius:var(--ep-radius-md);transition:all var(--ep-transition-fast)}.ep-sidebar-close:hover{color:var(--ep-text-primary);background-color:var(--ep-bg-tertiary)}.ep-sidebar-logo{display:flex;align-items:center;gap:var(--ep-space-2);color:var(--ep-primary-600)}.ep-sidebar-logo-text{font-size:var(--ep-font-size-lg);font-weight:var(--ep-font-weight-semibold);color:var(--ep-text-primary)}.ep-sidebar-content{flex:1;padding:var(--ep-space-6);overflow-y:auto;display:flex;flex-direction:column;gap:var(--ep-space-6)}.ep-sidebar-title-section{text-align:center}.ep-sidebar-title-section .ep-heading-2{margin-bottom:var(--ep-space-3);color:var(--ep-text-primary)}.ep-sidebar-title-section .ep-text-body{margin-bottom:0;color:var(--ep-text-secondary)}.ep-sidebar-progress{background-color:var(--ep-bg-tertiary);border:1px solid var(--ep-border-primary);border-radius:var(--ep-radius-md);padding:var(--ep-space-4)}.ep-progress-header{display:flex;justify-content:space-between;align-items:center;margin-bottom:var(--ep-space-3)}.ep-progress-label{font-size:var(--ep-font-size-sm);font-weight:var(--ep-font-weight-medium);color:var(--ep-text-primary)}.ep-progress-value{font-size:var(--ep-font-size-sm);font-weight:var(--ep-font-weight-semibold);color:var(--ep-primary-600)}.ep-progress-bar{height:8px;background-color:var(--ep-bg-primary);border-radius:var(--ep-radius-full);overflow:hidden;margin-bottom:var(--ep-space-2)}.ep-progress-fill{height:100%;background:linear-gradient(90deg,var(--ep-primary-500),var(--ep-primary-600));border-radius:var(--ep-radius-full);transition:width var(--ep-transition-normal)}.ep-progress-text{font-size:var(--ep-font-size-xs);color:var(--ep-text-tertiary);margin:0}.ep-sidebar-features .ep-heading-3{margin-bottom:var(--ep-space-4);text-align:center}.ep-feature-list{display:flex;flex-direction:column;gap:var(--ep-space-4)}.ep-feature-item{display:flex;align-items:flex-start;gap:var(--ep-space-3);padding:var(--ep-space-3);background-color:var(--ep-bg-tertiary);border:1px solid var(--ep-border-primary);border-radius:var(--ep-radius-md);opacity:0;transform:translateX(20px);transition:all var(--ep-transition-normal)}.ep-feature-item.ep-feature-item-visible{opacity:1;transform:translateX(0)}.ep-feature-icon{width:40px;height:40px;background:linear-gradient(135deg,var(--ep-primary-500),var(--ep-primary-600));border-radius:var(--ep-radius-lg);display:flex;align-items:center;justify-content:center;color:white;flex-shrink:0}.ep-feature-content{flex:1;min-width:0}.ep-feature-title{font-size:var(--ep-font-size-base);font-weight:var(--ep-font-weight-semibold);color:var(--ep-text-primary);margin-bottom:var(--ep-space-1)}.ep-feature-description{font-size:var(--ep-font-size-sm);color:var(--ep-text-secondary);line-height:var(--ep-line-height-relaxed);margin:0}.ep-sidebar-pricing{background:linear-gradient(135deg,var(--ep-primary-50),var(--ep-primary-100));border:1px solid var(--ep-primary-200);border-radius:var(--ep-radius-lg);padding:var(--ep-space-4)}:host([data-theme=\\\"dark\\\"]) .ep-sidebar-pricing{background:linear-gradient(135deg,var(--ep-primary-900),var(--ep-primary-800));border-color:var(--ep-primary-700)}.ep-pricing-card{text-align:center}.ep-pricing-header{margin-bottom:var(--ep-space-4)}.ep-pricing-badge{background:linear-gradient(135deg,var(--ep-primary-500),var(--ep-primary-600));color:white;padding:var(--ep-space-1) var(--ep-space-3);border-radius:var(--ep-radius-full);font-size:var(--ep-font-size-xs);font-weight:var(--ep-font-weight-medium);display:inline-block;margin-bottom:var(--ep-space-3)}.ep-pricing-price{display:flex;align-items:baseline;justify-content:center;gap:var(--ep-space-1);margin-bottom:var(--ep-space-2)}.ep-pricing-currency{font-size:var(--ep-font-size-base);font-weight:var(--ep-font-weight-medium);color:var(--ep-text-secondary)}.ep-pricing-amount{font-size:var(--ep-font-size-2xl);font-weight:var(--ep-font-weight-bold);color:var(--ep-text-primary)}.ep-pricing-period{font-size:var(--ep-font-size-base);color:var(--ep-text-secondary)}.ep-pricing-description{font-size:var(--ep-font-size-sm);color:var(--ep-text-secondary);margin:0}.ep-pricing-header:last-child,.ep-pricing-price:last-child{margin-bottom:0}.ep-sidebar-trial{background-color:var(--ep-success-50);border:1px solid var(--ep-success-200);border-radius:var(--ep-radius-md);padding:var(--ep-space-4)}:host([data-theme=\\\"dark\\\"]) .ep-sidebar-trial{background-color:rgba(16,185,129,0.1);border-color:rgba(16,185,129,0.3)}.ep-trial-info{display:flex;align-items:flex-start;gap:var(--ep-space-3)}.ep-trial-icon{width:32px;height:32px;background:linear-gradient(135deg,var(--ep-success-500),var(--ep-success-600));border-radius:var(--ep-radius-lg);display:flex;align-items:center;justify-content:center;color:white;flex-shrink:0}.ep-trial-content{flex:1;min-width:0}.ep-trial-title{font-size:var(--ep-font-size-base);font-weight:var(--ep-font-weight-semibold);color:var(--ep-success-700);margin-bottom:var(--ep-space-1)}:host([data-theme=\\\"dark\\\"]) .ep-trial-title{color:var(--ep-success-400)}.ep-trial-description{font-size:var(--ep-font-size-sm);color:var(--ep-success-600);line-height:var(--ep-line-height-relaxed);margin:0}:host([data-theme=\\\"dark\\\"]) .ep-trial-description{color:var(--ep-success-300)}.ep-sidebar-footer{padding:var(--ep-space-6);border-top:1px solid var(--ep-border-primary);background-color:var(--ep-bg-tertiary);display:flex;flex-direction:column;gap:var(--ep-space-3)}.ep-theme-toggle{position:fixed;top:var(--ep-space-4);left:var(--ep-space-4);z-index:var(--ep-z-tooltip);display:flex;flex-direction:column;gap:var(--ep-space-2)}@media (max-width:768px){.ep-sidebar-paywall{width:100%;max-width:100%;border-left:none}.ep-sidebar-content{padding:var(--ep-space-4)}.ep-sidebar-footer{padding:var(--ep-space-4)}}@media (max-width:480px){.ep-sidebar-header{padding:var(--ep-space-3) var(--ep-space-4)}.ep-sidebar-content{padding:var(--ep-space-3);gap:var(--ep-space-4)}.ep-sidebar-footer{padding:var(--ep-space-3)}.ep-feature-item{padding:var(--ep-space-2)}.ep-feature-icon{width:32px;height:32px}.ep-pricing-amount{font-size:var(--ep-font-size-xl)}}@media (prefers-contrast:high){.ep-sidebar-paywall{border-left:2px solid var(--ep-border-secondary)}.ep-feature-item{border:2px solid var(--ep-border-secondary)}.ep-sidebar-pricing{border:2px solid var(--ep-primary-500)}.ep-sidebar-trial{border:2px solid var(--ep-success-500)}}@media (prefers-reduced-motion:reduce){.ep-sidebar-backdrop{transition:none}.ep-sidebar-paywall{transition:none}.ep-feature-item{transition:none;opacity:1;transform:none}.ep-progress-fill{transition:none}}\";\nexport default { html, css };","export const html = \"<div class=\\\"ep-minimal-paywall\\\" id=\\\"minimalPaywall\\\" role=\\\"dialog\\\" aria-labelledby=\\\"minimal-title\\\"><button class=\\\"ep-minimal-close\\\" aria-label=\\\"Close paywall\\\" data-ep-action=\\\"closeMinimal\\\"><svg width=\\\"20\\\" height=\\\"20\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><line x1=\\\"18\\\" y1=\\\"6\\\" x2=\\\"6\\\" y2=\\\"18\\\"></line><line x1=\\\"6\\\" y1=\\\"6\\\" x2=\\\"18\\\" y2=\\\"18\\\"></line></svg></button><div class=\\\"ep-minimal-content\\\"><div class=\\\"ep-minimal-header\\\"><div class=\\\"ep-minimal-icon\\\"><svg width=\\\"24\\\" height=\\\"24\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><path d=\\\"M9 12l2 2 4-4\\\"></path><path d=\\\"M21 12c-1 0-3-1-3-3s2-3 3-3 3 1 3 3-2 3-3 3\\\"></path><path d=\\\"M3 12c1 0 3-1 3-3s-2-3-3-3-3 1-3 3 2 3 3 3\\\"></path></svg></div><h3 class=\\\"ep-minimal-title\\\" id=\\\"minimal-title\\\">{{title}}</h3><p class=\\\"ep-minimal-description\\\">{{description}}</p></div><div class=\\\"ep-minimal-pricing\\\"><div class=\\\"ep-minimal-price\\\"><span class=\\\"ep-minimal-currency\\\">{{currency}}</span><span class=\\\"ep-minimal-amount\\\">{{price}}</span><span class=\\\"ep-minimal-period\\\">{{period}}</span></div><p class=\\\"ep-minimal-price-description\\\">{{priceDescription}}</p></div><div class=\\\"ep-minimal-features\\\"><ul class=\\\"ep-minimal-feature-list\\\"><li class=\\\"ep-minimal-feature\\\"><svg class=\\\"ep-minimal-feature-icon\\\" width=\\\"16\\\" height=\\\"16\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><polyline points=\\\"20,6 9,17 4,12\\\"></polyline></svg><span>{{feature1}}</span></li><li class=\\\"ep-minimal-feature\\\"><svg class=\\\"ep-minimal-feature-icon\\\" width=\\\"16\\\" height=\\\"16\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><polyline points=\\\"20,6 9,17 4,12\\\"></polyline></svg><span>{{feature2}}</span></li><li class=\\\"ep-minimal-feature\\\"><svg class=\\\"ep-minimal-feature-icon\\\" width=\\\"16\\\" height=\\\"16\\\" viewBox=\\\"0 0 24 24\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\"><polyline points=\\\"20,6 9,17 4,12\\\"></polyline></svg><span>{{feature3}}</span></li></ul></div><div class=\\\"ep-minimal-actions\\\"><button class=\\\"ep-btn ep-btn-primary ep-btn-full\\\" data-ep-action=\\\"upgradeNow\\\"> {{upgradeButtonText}} </button><button class=\\\"ep-btn ep-btn-ghost ep-btn-sm\\\" data-ep-action=\\\"closeMinimal\\\"> {{dismissButtonText}} </button></div><div class=\\\"ep-minimal-trial\\\"><p class=\\\"ep-minimal-trial-text\\\">{{trialText}}</p></div></div></div><div class=\\\"ep-minimal-backdrop\\\" id=\\\"minimalBackdrop\\\"></div>\";\nexport const css = \".ep-minimal-backdrop{position:fixed;top:0;left:0;right:0;bottom:0;background-color:rgba(0,0,0,0.4);z-index:var(--ep-z-backdrop);opacity:0;visibility:hidden;transition:all var(--ep-transition-fast)}.ep-minimal-backdrop.ep-minimal-backdrop-visible{opacity:1;visibility:visible}.ep-minimal-paywall{position:fixed;top:50%;left:50%;transform:translate(-50%,-50%) scale(0.95);background-color:var(--ep-bg-secondary);border:1px solid var(--ep-border-primary);border-radius:var(--ep-radius-lg);box-shadow:var(--ep-shadow-xl);z-index:var(--ep-z-modal);max-width:400px;width:90vw;max-height:90vh;overflow-y:auto;opacity:0;visibility:hidden;transition:all var(--ep-transition-fast)}.ep-minimal-paywall.ep-minimal-visible{opacity:1;visibility:visible;transform:translate(-50%,-50%) scale(1)}.ep-minimal-close{position:absolute;top:var(--ep-space-3);right:var(--ep-space-3);background:none;border:none;color:var(--ep-text-tertiary);cursor:pointer;padding:var(--ep-space-2);border-radius:var(--ep-radius-sm);transition:all var(--ep-transition-fast);z-index:1}.ep-minimal-close:hover{color:var(--ep-text-primary);background-color:var(--ep-bg-tertiary)}.ep-minimal-content{padding:var(--ep-space-6);padding-top:var(--ep-space-8)}.ep-minimal-header{text-align:center;margin-bottom:var(--ep-space-6)}.ep-minimal-icon{width:48px;height:48px;margin:0 auto var(--ep-space-3);background:linear-gradient(135deg,var(--ep-primary-500),var(--ep-primary-600));border-radius:var(--ep-radius-lg);display:flex;align-items:center;justify-content:center;color:white}.ep-minimal-title{font-size:var(--ep-font-size-xl);font-weight:var(--ep-font-weight-semibold);color:var(--ep-text-primary);margin-bottom:var(--ep-space-2)}.ep-minimal-description{color:var(--ep-text-secondary);font-size:var(--ep-font-size-sm);line-height:var(--ep-line-height-relaxed);margin:0}.ep-minimal-pricing{text-align:center;margin-bottom:var(--ep-space-6);padding:var(--ep-space-4);background:linear-gradient(135deg,var(--ep-primary-50),var(--ep-primary-100));border:1px solid var(--ep-primary-200);border-radius:var(--ep-radius-md)}:host([data-theme=\\\"dark\\\"]) .ep-minimal-pricing{background:linear-gradient(135deg,var(--ep-primary-900),var(--ep-primary-800));border-color:var(--ep-primary-700)}.ep-minimal-price{display:flex;align-items:baseline;justify-content:center;gap:var(--ep-space-1);margin-bottom:var(--ep-space-2)}.ep-minimal-currency{font-size:var(--ep-font-size-base);font-weight:var(--ep-font-weight-medium);color:var(--ep-text-secondary)}.ep-minimal-amount{font-size:var(--ep-font-size-2xl);font-weight:var(--ep-font-weight-bold);color:var(--ep-text-primary)}.ep-minimal-period{font-size:var(--ep-font-size-base);color:var(--ep-text-secondary)}.ep-minimal-price-description{color:var(--ep-text-secondary);font-size:var(--ep-font-size-xs);margin:0}.ep-minimal-features{margin-bottom:var(--ep-space-6)}.ep-minimal-feature-list{list-style:none;padding:0;margin:0}.ep-minimal-feature{display:flex;align-items:center;gap:var(--ep-space-2);padding:var(--ep-space-2) 0;color:var(--ep-text-primary);font-size:var(--ep-font-size-sm);border-bottom:1px solid var(--ep-border-primary)}.ep-minimal-feature:last-child{border-bottom:none}.ep-minimal-feature-icon{color:var(--ep-success-500);flex-shrink:0}.ep-minimal-feature span{font-weight:var(--ep-font-weight-medium)}.ep-minimal-actions{display:flex;flex-direction:column;gap:var(--ep-space-2);margin-bottom:var(--ep-space-4)}.ep-minimal-trial{text-align:center;padding-top:var(--ep-space-4);border-top:1px solid var(--ep-border-primary)}.ep-minimal-trial-text{color:var(--ep-text-tertiary);font-size:var(--ep-font-size-xs);margin:0}.ep-theme-toggle{position:fixed;top:var(--ep-space-4);left:var(--ep-space-4);z-index:var(--ep-z-tooltip);display:flex;flex-direction:column;gap:var(--ep-space-2)}@media (max-width:480px){.ep-minimal-paywall{width:95vw;max-width:none}.ep-minimal-content{padding:var(--ep-space-4);padding-top:var(--ep-space-6)}.ep-minimal-close{top:var(--ep-space-2);right:var(--ep-space-2)}.ep-minimal-icon{width:40px;height:40px}.ep-minimal-title{font-size:var(--ep-font-size-lg)}.ep-minimal-amount{font-size:var(--ep-font-size-xl)}.ep-minimal-pricing{padding:var(--ep-space-3)}}@media (prefers-contrast:high){.ep-minimal-paywall{border:2px solid var(--ep-border-secondary)}.ep-minimal-pricing{border:2px solid var(--ep-primary-500)}.ep-minimal-backdrop{background-color:rgba(0,0,0,0.8)}}@media (prefers-reduced-motion:reduce){.ep-minimal-backdrop{transition:none}.ep-minimal-paywall{transition:none;transform:translate(-50%,-50%)}.ep-minimal-paywall.ep-minimal-visible{transform:translate(-50%,-50%)}}@media print{.ep-minimal-backdrop{display:none}.ep-minimal-paywall{position:static;transform:none;box-shadow:none;border:1px solid black;opacity:1;visibility:visible}.ep-minimal-close{display:none}}.ep-minimal-paywall *:focus{outline:2px solid var(--ep-primary-500);outline-offset:2px}.ep-minimal-paywall *:focus:not(:focus-visible){outline:none}.ep-minimal-paywall{animation:ep-minimal-entrance var(--ep-transition-normal) ease-out}@keyframes ep-minimal-entrance{from{opacity:0;transform:translate(-50%,-50%) scale(0.9)}to{opacity:1;transform:translate(-50%,-50%) scale(1)}}.ep-minimal-feature:hover{background-color:var(--ep-bg-tertiary);border-radius:var(--ep-radius-sm);margin:0 calc(-1 * var(--ep-space-2));padding:var(--ep-space-2)}.ep-minimal-pricing:hover{background:linear-gradient(135deg,var(--ep-primary-100),var(--ep-primary-200));border-color:var(--ep-primary-300)}:host([data-theme=\\\"dark\\\"]) .ep-minimal-pricing:hover{background:linear-gradient(135deg,var(--ep-primary-800),var(--ep-primary-700));border-color:var(--ep-primary-600)}\";\nexport default { html, css };","/**\n * The one paywall renderer.\n *\n * Renders a template from `@extenshi/paywall-templates` into a Shadow DOM\n * host so the templates' resets never leak into the extension page (and vice\n * versa). Placeholders (`{{title}}`, `{{price}}` …) are filled from the offer\n * and the strings dictionary, every value HTML-escaped; buttons are bound with\n * `addEventListener` on `data-ep-action` (no inline handlers, no scripts).\n */\n\nimport { withdrawalWaiverText } from '../payment/withdrawal-waiver.js'\nimport type { ThemeConfig } from '../types/config.js'\nimport type { PayOfferDto, PaySellerPublic, PayWithdrawalWaiver } from '../types/contract.js'\nimport type { UpgradeConsent } from '../types/entitlement.js'\nimport { ERROR_CODES, ExtenshiPayError } from '../types/errors.js'\nimport type { PaywallMode, PaywallStrings } from '../types/paywall.js'\nimport { formatPrice, periodLabel } from './format.js'\nimport { sdkDir, sdkLocale, sdkStrings } from './i18n.js'\nimport { sellerDetails } from './seller-details.js'\nimport { stringsFor } from './strings.js'\nimport { PAYWALL_SHARED_CSS, PAYWALL_TEMPLATES } from './templates.js'\n\nexport interface PaywallView {\n\tmode: PaywallMode\n\ttitle: string\n\tdescription: string\n\tfeatures: string[]\n\tfreeFeatures: string[]\n\t/** Header image URL (./icon.ts) in place of the template's glyph; absent or null keeps the glyph. */\n\ticon?: string | null\n\tbrandName: string\n\toffer: PayOfferDto | null\n\tcheckoutEnabled: boolean\n\tmock?: boolean\n\trecoveryEnabled?: boolean\n\tseller?: PaySellerPublic | null\n\t/**\n\t * From `PayOfferResponse.withdrawalWaiver`: when set (and the offer is\n\t * purchasable) an unticked waiver checkbox gates every upgrade button.\n\t * The waiver text is not overridable through `strings`: it is versioned.\n\t */\n\twithdrawalWaiver?: PayWithdrawalWaiver | null\n\t/** A link-styled button under the plans (trial-ended screen); clicking it calls `onFeedback`. */\n\tfeedback?: { label: string } | null\n\tlocale: string | null\n\ttheme: ThemeConfig\n\tstrings: Partial<PaywallStrings>\n\tcontainer?: HTMLElement\n}\n\nexport interface PaywallRendererCallbacks {\n\t/** `consent` is passed only when the paywall showed the withdrawal waiver (and it was ticked). */\n\tonUpgrade: (sku: string, consent?: UpgradeConsent) => void\n\tonClose: () => void\n\tonRestore?: () => void\n\tonFeedback?: () => void\n}\n\nexport const PAYWALL_HOST_CLASS = 'extenshi-paywall-host'\n\nconst UPGRADE_ACTIONS: ReadonlySet<string> = new Set(['upgradeNow', 'startUpgrade'])\nconst UPGRADE_SELECTOR = '[data-ep-action=\"upgradeNow\"], [data-ep-action=\"startUpgrade\"]'\nexport const WITHDRAWAL_WAIVER_CLASS = 'extenshi-withdrawal-waiver'\nconst CLOSE_ACTIONS: ReadonlySet<string> = new Set([\n\t'closePaywall',\n\t'closeSidebar',\n\t'closeFullscreen',\n\t'closeMinimal',\n\t'dismissPaywall',\n\t'remindLater',\n\t'continueFree',\n])\n\nconst ROOT_SELECTOR: Record<PaywallMode, string> = {\n\tmodal: '.ep-modal-backdrop',\n\tinline: '.ep-inline-paywall',\n\tsidebar: '.ep-sidebar-paywall',\n\tfullscreen: '.ep-fullscreen-paywall',\n\tminimal: '.ep-minimal-paywall',\n}\n\nconst BACKDROP_SELECTOR: Partial<Record<PaywallMode, string>> = {\n\tmodal: '.ep-modal-backdrop',\n\tsidebar: '.ep-sidebar-backdrop',\n\tminimal: '.ep-minimal-backdrop',\n}\n\nconst VISIBLE_CLASSES: Partial<Record<PaywallMode, Array<[selector: string, className: string]>>> = {\n\tinline: [['.ep-inline-paywall', 'ep-inline-visible']],\n\tsidebar: [\n\t\t['.ep-sidebar-paywall', 'ep-sidebar-visible'],\n\t\t['.ep-sidebar-backdrop', 'ep-sidebar-backdrop-visible'],\n\t],\n\tminimal: [\n\t\t['.ep-minimal-paywall', 'ep-minimal-visible'],\n\t\t['.ep-minimal-backdrop', 'ep-minimal-backdrop-visible'],\n\t],\n}\n\n/** Template blocks the contract has no data for (trials, usage meters). */\nconst PRUNE_SELECTOR = '[class*=\"-trial\"], .ep-sidebar-progress'\n/** Glyphs that stand for the product: on a gradient tile, or next to the brand name. */\nconst ICON_TILE_SELECTOR = '.ep-modal-icon, .ep-inline-icon, .ep-minimal-icon, .ep-hero-icon'\nconst ICON_LOGO_SELECTOR = '.ep-fullscreen-logo, .ep-sidebar-logo'\n/**\n * Templates stagger their feature rows in with this class from their demo\n * script (sidebar, fullscreen); without it the rows sit at opacity 0.\n */\nconst FEATURE_ITEM_VISIBLE = ['.ep-feature-item', 'ep-feature-item-visible'] as const\n/** Containers of a single feature slot; dropped when the slot's placeholder is empty. */\nconst FEATURE_SLOT_SELECTOR = 'li, .ep-feature-card, .ep-feature-item, .ep-pricing-feature, .ep-feature'\n/** Feature sections and lists (with their headings); dropped once no slot is left in them. */\nconst FEATURE_BLOCK_SELECTOR = '[class*=\"-features\"]'\nconst EMPTY_SLOT_MARK = 'data-ep-empty'\n/** Placeholders whose element is dropped when empty: feature slots and the price card's copy. */\nconst OPTIONAL_KEY_RE =\n\t/^(feature\\d+(Title)?|premiumFeature\\d+|freeFeature\\d+|pricingDescription|priceDescription|premiumDescription)$/\n\nexport function escapeHtml(value: string): string {\n\treturn value\n\t\t.replace(/&/g, '&')\n\t\t.replace(/</g, '<')\n\t\t.replace(/>/g, '>')\n\t\t.replace(/\"/g, '"')\n\t\t.replace(/'/g, ''')\n}\n\nexport function substitute(html: string, content: Record<string, string>): string {\n\treturn html.replace(/\\{\\{(\\w+)\\}\\}/g, (_match, key: string) => {\n\t\tconst value = content[key] ?? ''\n\t\tif (value === '' && OPTIONAL_KEY_RE.test(key)) return `<i ${EMPTY_SLOT_MARK}></i>`\n\t\treturn escapeHtml(value)\n\t})\n}\n\nexport function buildContent(view: PaywallView, strings: PaywallStrings): Record<string, string> {\n\tconst offer = view.offer\n\tconst price = offer ? formatPrice(offer.amountMinor, offer.currency, view.locale) : null\n\t// Without a `description` option the header already shows the offer's\n\t// description (ExtenshiPay.showPaywall); the price card must not repeat it.\n\tconst offerDescription = offer?.description?.trim() ?? ''\n\tconst priceCopy = offerDescription === view.description.trim() ? '' : offerDescription\n\tconst content: Record<string, string> = {\n\t\ttitle: view.title,\n\t\tdescription: view.description,\n\t\tbrandName: view.brandName,\n\t\tcurrency: price?.currency ?? '',\n\t\tprice: price?.amount ?? '',\n\t\tperiod: offer ? periodLabel(offer, strings) : '',\n\t\tpricingDescription: priceCopy,\n\t\tpriceDescription: priceCopy,\n\t\tpremiumDescription: priceCopy,\n\t\tupgradeButtonText: view.checkoutEnabled && offer ? strings.upgrade : strings.checkoutUnavailable,\n\t\tcancelButtonText: strings.cancel,\n\t\tdismissButtonText: strings.dismiss,\n\t\tremindLaterText: strings.remindLater,\n\t\tcontinueButtonText: strings.continueFree,\n\t\tfooterText: strings.footer,\n\t\tfeaturesHeading: strings.featuresHeading,\n\t\tplansHeading: strings.plansHeading,\n\t\tfreePlanName: strings.freePlanName,\n\t\tpremiumPlanName: strings.premiumPlanName,\n\t\tpopularBadge: strings.popularBadge,\n\t\tunlockHeading: strings.unlockHeading,\n\t}\n\tview.features.forEach((feature, index) => {\n\t\tconst n = index + 1\n\t\tcontent[`feature${n}`] = feature\n\t\tcontent[`feature${n}Title`] = feature\n\t\tcontent[`premiumFeature${n}`] = feature\n\t})\n\tview.freeFeatures.forEach((feature, index) => {\n\t\tcontent[`freeFeature${index + 1}`] = feature\n\t})\n\treturn content\n}\n\n/** Who supplies the content: the seller's public name, else the project/brand name. */\nfunction waiverSellerName(view: PaywallView): string {\n\treturn view.seller?.displayName?.trim() || view.brandName.trim() || view.title\n}\n\nconst CSS_VALUE_UNSAFE = /[;{}<>]/g\n/**\n * The rest of the primary scale, as the share of `primaryColor` mixed with\n * white (tints) or black (shades). Price cards and links use these steps; left\n * at the defaults they stay sky blue next to a button in the author's colour.\n */\nconst PRIMARY_TINTS: ReadonlyArray<[step: number, percent: number]> = [\n\t[50, 8],\n\t[100, 16],\n\t[200, 32],\n\t[300, 52],\n\t[400, 76],\n]\nconst PRIMARY_SHADES: ReadonlyArray<[step: number, percent: number]> = [\n\t[800, 72],\n\t[900, 52],\n]\n\nexport function themeCss(theme: ThemeConfig): string {\n\tconst declarations: string[] = []\n\tconst safe = (value: string) => value.replace(CSS_VALUE_UNSAFE, '')\n\tif (theme.primaryColor) {\n\t\tconst color = safe(theme.primaryColor)\n\t\tdeclarations.push(`--ep-primary-500:${color}`, `--ep-primary-600:${color}`, `--ep-primary-700:${color}`)\n\t\tfor (const [step, percent] of PRIMARY_TINTS)\n\t\t\tdeclarations.push(`--ep-primary-${step}:color-mix(in srgb,${color} ${percent}%,white)`)\n\t\tfor (const [step, percent] of PRIMARY_SHADES)\n\t\t\tdeclarations.push(`--ep-primary-${step}:color-mix(in srgb,${color} ${percent}%,black)`)\n\t}\n\tif (theme.fontFamily) declarations.push(`--ep-font-family-sans:${safe(theme.fontFamily)}`)\n\tif (theme.borderRadius) {\n\t\tconst radius = safe(theme.borderRadius)\n\t\tdeclarations.push(`--ep-radius-md:${radius}`, `--ep-radius-lg:${radius}`, `--ep-radius-xl:${radius}`)\n\t}\n\tconst host = declarations.length > 0 ? `:host{${declarations.join(';')}}` : ''\n\treturn host + (theme.customCss ?? '')\n}\n\nexport function resolveThemeMode(theme: ThemeConfig): 'light' | 'dark' {\n\tconst mode = theme.mode ?? 'auto'\n\tif (mode !== 'auto') return mode\n\tconst matchMedia = (globalThis as { matchMedia?: (query: string) => { matches: boolean } }).matchMedia\n\treturn typeof matchMedia === 'function' &&\n\t\tmatchMedia.call(globalThis, '(prefers-color-scheme: dark)').matches\n\t\t? 'dark'\n\t\t: 'light'\n}\n\nexport class PaywallRenderer {\n\tprivate host: HTMLElement | null = null\n\tprivate keyHandler: ((event: KeyboardEvent) => void) | null = null\n\n\tconstructor(private readonly callbacks: PaywallRendererCallbacks) {}\n\n\tisVisible(): boolean {\n\t\treturn this.host !== null\n\t}\n\n\t/** Returns the host element; its shadow root holds the rendered template. */\n\tshow(view: PaywallView): HTMLElement {\n\t\tthis.hide()\n\t\tconst doc = (globalThis as { document?: Document }).document\n\t\tif (!doc || typeof doc.createElement !== 'function' || !doc.body) {\n\t\t\tthrow new ExtenshiPayError(\n\t\t\t\tERROR_CODES.PAYWALL_UNAVAILABLE,\n\t\t\t\t'The paywall needs a DOM; call showPaywall() from a popup, options page or content script',\n\t\t\t)\n\t\t}\n\t\tconst template = PAYWALL_TEMPLATES[view.mode]\n\t\tif (!template)\n\t\t\tthrow new ExtenshiPayError(ERROR_CODES.INVALID_REQUEST, `Unknown paywall mode \"${view.mode}\"`)\n\n\t\tconst t = sdkStrings(view.locale)\n\t\tconst strings: PaywallStrings = { ...stringsFor(view.locale), ...view.strings }\n\t\tif (view.mock) {\n\t\t\tstrings.upgrade = t.simulatePurchase\n\t\t\tstrings.footer = t.mockNotice\n\t\t}\n\t\tconst host = doc.createElement('div')\n\t\thost.className = PAYWALL_HOST_CLASS\n\t\thost.setAttribute('data-theme', resolveThemeMode(view.theme))\n\t\t// The shadow tree inherits the host's language: screen readers and\n\t\t// hyphenation read the strings in the language they are written in.\n\t\thost.setAttribute('lang', sdkLocale(view.locale))\n\t\thost.setAttribute('dir', sdkDir(sdkLocale(view.locale)))\n\t\tconst root: ShadowRoot | HTMLElement =\n\t\t\ttypeof host.attachShadow === 'function' ? host.attachShadow({ mode: 'open' }) : host\n\t\troot.innerHTML =\n\t\t\t`<style>${PAYWALL_SHARED_CSS}${template.css}${themeCss(view.theme)}</style>` +\n\t\t\tsubstitute(template.html, buildContent(view, strings))\n\n\t\tthis.prune(root)\n\t\tif (view.icon) this.placeIcon(root, doc, view.icon)\n\t\tconst waiver =\n\t\t\tview.offer && view.checkoutEnabled && view.withdrawalWaiver\n\t\t\t\t? withdrawalWaiverText(view.withdrawalWaiver.version, view.locale, waiverSellerName(view))\n\t\t\t\t: null\n\t\tconst waiverBox = waiver ? doc.createElement('input') : null\n\t\t// undefined: no waiver asked → onUpgrade(sku) exactly as before; null: not ticked yet.\n\t\tconst consent = (): UpgradeConsent | null | undefined => {\n\t\t\tif (!waiver) return undefined\n\t\t\treturn waiverBox?.checked ? { withdrawalWaiver: { version: waiver.version, accepted: true } } : null\n\t\t}\n\t\tthis.bind(root, view, doc, consent)\n\t\tconst sellerMount = root.querySelector(\n\t\t\t'[class*=\"-footer\"], .ep-minimal-actions, .ep-inline-content, .ep-fullscreen-content',\n\t\t)\n\t\tif (sellerMount) {\n\t\t\tconst details = sellerDetails(view.seller ?? null, t)\n\t\t\tdetails.style.cssText =\n\t\t\t\t'font-size:12px;line-height:1.5;margin-top:12px;text-align:start;white-space:normal;color:var(--ep-text-secondary)'\n\t\t\t// In the modal, disclose the provider before the purchase action,\n\t\t\t// instead of below it in the scrollable footer.\n\t\t\tconst modalActions = root.querySelector('.ep-modal-actions')\n\t\t\tif (modalActions) modalActions.before(details)\n\t\t\telse sellerMount.append(details)\n\t\t}\n\t\tif (view.mock) {\n\t\t\tconst upgrade = root.querySelector(UPGRADE_SELECTOR)\n\t\t\tif (upgrade) {\n\t\t\t\tconst notice = doc.createElement('p')\n\t\t\t\tnotice.className = 'extenshi-payment-preview'\n\t\t\t\tnotice.textContent = t.mockNotice\n\t\t\t\tnotice.style.cssText = 'font-size:13px;line-height:1.5;margin:12px 0;white-space:normal'\n\t\t\t\tupgrade.before(notice)\n\t\t\t}\n\t\t}\n\t\tif (waiver && waiverBox) this.mountWaiver(root, doc, waiver.text, waiverBox)\n\t\tconst onRestore = this.callbacks.onRestore\n\t\tif (view.recoveryEnabled && onRestore) this.footerLink(root, doc, strings.restorePurchase, onRestore)\n\t\tconst onFeedback = this.callbacks.onFeedback\n\t\tif (view.feedback && onFeedback) this.footerLink(root, doc, view.feedback.label, onFeedback)\n\t\tconst mount = view.mode === 'inline' ? (view.container ?? doc.body) : doc.body\n\t\tmount.appendChild(host)\n\t\tthis.host = host\n\t\tthis.reveal(root, view.mode)\n\t\treturn host\n\t}\n\n\thide(): void {\n\t\tif (!this.host) return\n\t\tif (this.keyHandler) {\n\t\t\tthis.host.ownerDocument.removeEventListener('keydown', this.keyHandler)\n\t\t\tthis.keyHandler = null\n\t\t}\n\t\tthis.host.remove()\n\t\tthis.host = null\n\t}\n\n\t/** A text button at the end of the footer (no `href`: the SDK opens URLs itself). */\n\tprivate footerLink(root: ParentNode, doc: Document, label: string, onClick: () => void): void {\n\t\tconst footer = root.querySelector(\n\t\t\t'[class*=\"-footer\"], .ep-minimal-actions, .ep-inline-content, .ep-fullscreen-content',\n\t\t)\n\t\tif (!footer) return\n\t\tconst button = doc.createElement('button')\n\t\tbutton.type = 'button'\n\t\tbutton.textContent = label\n\t\tbutton.style.cssText =\n\t\t\t'display:block;margin:12px auto 0;background:none;border:0;color:inherit;font:inherit;text-decoration:underline;cursor:pointer'\n\t\tbutton.addEventListener('click', () => onClick())\n\t\tfooter.appendChild(button)\n\t}\n\n\tprivate prune(root: ParentNode): void {\n\t\tfor (const element of root.querySelectorAll(PRUNE_SELECTOR)) element.remove()\n\t\tfor (const mark of root.querySelectorAll(`[${EMPTY_SLOT_MARK}]`)) {\n\t\t\tconst slot = mark.parentElement?.closest(FEATURE_SLOT_SELECTOR) ?? mark.parentElement\n\t\t\t;(slot ?? mark).remove()\n\t\t}\n\t\t// Every slot empty (no `features` passed): drop the section with its\n\t\t// heading, so no \"Premium Features\" title sits over nothing.\n\t\tfor (const block of root.querySelectorAll(FEATURE_BLOCK_SELECTOR)) {\n\t\t\tif (!block.querySelector(FEATURE_SLOT_SELECTOR)) block.remove()\n\t\t}\n\t\t// A button whose label placeholder the contract does not fill (trial\n\t\t// CTAs on sidebar/fullscreen) would render as an empty pill; icon-only\n\t\t// buttons (close) keep their SVG and stay.\n\t\tfor (const button of root.querySelectorAll('button')) {\n\t\t\tif (!button.textContent?.trim() && !button.querySelector('svg')) button.remove()\n\t\t}\n\t}\n\n\t/**\n\t * Swaps the templates' product glyphs for the extension's icon. A tile's\n\t * gradient only backs the white glyph, so it goes too; an image that fails\n\t * to load puts the glyph (and the gradient) back.\n\t */\n\tprivate placeIcon(root: ParentNode, doc: Document, url: string): void {\n\t\tfor (const slot of root.querySelectorAll<HTMLElement>(`${ICON_TILE_SELECTOR}, ${ICON_LOGO_SELECTOR}`)) {\n\t\t\tconst glyph = Array.from(slot.children).find((child) => child.localName === 'svg')\n\t\t\tif (!glyph) continue\n\t\t\tconst tile = slot.matches(ICON_TILE_SELECTOR)\n\t\t\tconst size = Number(glyph.getAttribute('width')) || 32\n\t\t\tconst img = doc.createElement('img')\n\t\t\timg.alt = ''\n\t\t\timg.style.cssText = tile\n\t\t\t\t? 'width:100%;height:100%;object-fit:contain'\n\t\t\t\t: `width:${size}px;height:${size}px;object-fit:contain`\n\t\t\timg.addEventListener('error', () => {\n\t\t\t\timg.replaceWith(glyph)\n\t\t\t\tif (tile) slot.style.removeProperty('background')\n\t\t\t})\n\t\t\timg.src = url\n\t\t\tif (tile) slot.style.background = 'none'\n\t\t\tglyph.replaceWith(img)\n\t\t}\n\t}\n\n\t/**\n\t * Inserts the unticked waiver checkbox right before the first upgrade\n\t * button and keeps every upgrade button disabled until it is ticked.\n\t */\n\tprivate mountWaiver(root: ParentNode, doc: Document, text: string, input: HTMLInputElement): void {\n\t\tconst buttons = Array.from(root.querySelectorAll<HTMLElement>(UPGRADE_SELECTOR))\n\t\tconst first = buttons[0]\n\t\tif (!first) return\n\t\tconst label = doc.createElement('label')\n\t\tlabel.className = WITHDRAWAL_WAIVER_CLASS\n\t\tlabel.style.cssText =\n\t\t\t'display:flex;align-items:flex-start;gap:8px;margin:12px 0;font-size:13px;line-height:1.5;text-align:start;white-space:normal;color:inherit;cursor:pointer'\n\t\tinput.type = 'checkbox'\n\t\tinput.checked = false\n\t\tinput.style.cssText = 'flex:none;width:16px;height:16px;margin:2px 0 0;cursor:pointer'\n\t\tconst span = doc.createElement('span')\n\t\tspan.textContent = text\n\t\tlabel.append(input, span)\n\t\tfirst.before(label)\n\t\tconst sync = () => {\n\t\t\tfor (const button of buttons) {\n\t\t\t\tif (input.checked) {\n\t\t\t\t\tbutton.removeAttribute('disabled')\n\t\t\t\t\tbutton.removeAttribute('aria-disabled')\n\t\t\t\t} else {\n\t\t\t\t\tbutton.setAttribute('disabled', '')\n\t\t\t\t\tbutton.setAttribute('aria-disabled', 'true')\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tinput.addEventListener('change', sync)\n\t\tsync()\n\t}\n\n\tprivate bind(\n\t\troot: ParentNode,\n\t\tview: PaywallView,\n\t\tdoc: Document,\n\t\tconsent: () => UpgradeConsent | null | undefined,\n\t): void {\n\t\tfor (const element of root.querySelectorAll<HTMLElement>('[data-ep-action]')) {\n\t\t\tconst action = element.getAttribute('data-ep-action') ?? ''\n\t\t\tif (UPGRADE_ACTIONS.has(action)) {\n\t\t\t\tif (view.offer && view.checkoutEnabled) {\n\t\t\t\t\tconst sku = view.offer.sku\n\t\t\t\t\telement.addEventListener('click', (event) => {\n\t\t\t\t\t\tevent.preventDefault()\n\t\t\t\t\t\tconst given = consent()\n\t\t\t\t\t\t// Waiver shown but not ticked: a disabled button cannot be\n\t\t\t\t\t\t// clicked, but never start checkout without consent anyway.\n\t\t\t\t\t\tif (given === null) return\n\t\t\t\t\t\tif (given) this.callbacks.onUpgrade(sku, given)\n\t\t\t\t\t\telse this.callbacks.onUpgrade(sku)\n\t\t\t\t\t})\n\t\t\t\t} else {\n\t\t\t\t\telement.setAttribute('disabled', '')\n\t\t\t\t\telement.setAttribute('aria-disabled', 'true')\n\t\t\t\t}\n\t\t\t} else if (CLOSE_ACTIONS.has(action)) {\n\t\t\t\telement.addEventListener('click', (event) => {\n\t\t\t\t\tevent.preventDefault()\n\t\t\t\t\tthis.close()\n\t\t\t\t})\n\t\t\t} else {\n\t\t\t\telement.remove()\n\t\t\t}\n\t\t}\n\t\tconst backdropSelector = BACKDROP_SELECTOR[view.mode]\n\t\tif (backdropSelector) {\n\t\t\troot.querySelector(backdropSelector)?.addEventListener('click', (event) => {\n\t\t\t\tif (event.target === event.currentTarget) this.close()\n\t\t\t})\n\t\t}\n\t\tif (view.mode !== 'inline') {\n\t\t\tthis.keyHandler = (event) => {\n\t\t\t\tif (event.key === 'Escape') this.close()\n\t\t\t}\n\t\t\tdoc.addEventListener('keydown', this.keyHandler)\n\t\t}\n\t}\n\n\tprivate reveal(root: ParentNode, mode: PaywallMode): void {\n\t\tconst rootElement = root.querySelector<HTMLElement>(ROOT_SELECTOR[mode])\n\t\tif (rootElement && (mode === 'modal' || mode === 'fullscreen')) rootElement.style.display = 'flex'\n\t\tfor (const [selector, className] of VISIBLE_CLASSES[mode] ?? []) {\n\t\t\troot.querySelector(selector)?.classList.add(className)\n\t\t}\n\t\tfor (const item of root.querySelectorAll(FEATURE_ITEM_VISIBLE[0]))\n\t\t\titem.classList.add(FEATURE_ITEM_VISIBLE[1])\n\t}\n\n\tprivate close(): void {\n\t\tthis.hide()\n\t\tthis.callbacks.onClose()\n\t}\n}\n","/** Full SDK: everything in `ExtenshiPayLite` plus the offer and the paywall UI. */\n\nimport { ExtenshiPayLite } from './core/extenshi-pay.js'\nimport { openInNewTab } from './payment/checkout.js'\nimport { isEntitled } from './payment/features.js'\nimport { trialFeedbackUrl } from './payment/trial.js'\nimport { BillingProfilePicker } from './paywall/billing-profile-picker.js'\nimport { sdkStrings } from './paywall/i18n.js'\nimport { paywallIconUrl } from './paywall/icon.js'\nimport { LicensePanel } from './paywall/license-panel.js'\nimport { PaywallRenderer, type PaywallView } from './paywall/renderer.js'\nimport { stringsFor } from './paywall/strings.js'\nimport type { PayOfferDto, PayOfferResponse } from './types/contract.js'\nimport type { CustomerPortalOptions, RequireFeatureOptions, UpgradeConsent } from './types/entitlement.js'\nimport { ERROR_CODES, ExtenshiPayError } from './types/errors.js'\nimport type { PaywallOptions, TrialEndedOptions } from './types/paywall.js'\n\ninterface PaywallSession {\n\toptions: PaywallOptions\n\tresolve: (unlocked: boolean) => void\n\t/** The trial-ended screen's feedback form, with `src=trial_end`. */\n\tfeedbackUrl: string | null\n}\n\nfunction pickOffer(offer: PayOfferResponse | null, sku: string | undefined): PayOfferDto | null {\n\tif (!offer) return null\n\treturn offer.offers.find((candidate) => candidate.sku === sku) ?? offer.offers[0] ?? null\n}\n\nexport class ExtenshiPay extends ExtenshiPayLite {\n\tprivate disposed = false\n\tprivate licensePanel = new LicensePanel()\n\tprivate billingProfiles = new BillingProfilePicker()\n\tprivate paywall: PaywallRenderer | null = null\n\tprivate paywallSession: PaywallSession | null = null\n\n\toverride async openCustomerPortal(options: CustomerPortalOptions = {}): Promise<string | null> {\n\t\treturn super.openCustomerPortal({\n\t\t\t...options,\n\t\t\tselectAccount:\n\t\t\t\toptions.selectAccount ?? ((accounts) => this.billingProfiles.show(accounts, this.config.locale)),\n\t\t})\n\t}\n\n\toverride destroy(): void {\n\t\tthis.disposed = true\n\t\tthis.licensePanel.hide()\n\t\tthis.billingProfiles.hide()\n\t\tthis.hidePaywall()\n\t\tsuper.destroy()\n\t}\n\n\tasync showLicense(): Promise<void> {\n\t\t// An explicit status check should see refunds/cancellations immediately.\n\t\t// The entitlement manager still falls back to the verified cache offline.\n\t\tconst summary = await this.getLicenseSummary({ force: !this.config.mock })\n\t\tif (this.disposed) return\n\t\treturn this.licensePanel.show(\n\t\t\tsummary,\n\t\t\t{\n\t\t\t\trestore: async () => {\n\t\t\t\t\tawait this.restorePurchase()\n\t\t\t\t\treturn this.getLicenseSummary({ force: true })\n\t\t\t\t},\n\t\t\t\tmanage: () => this.openCustomerPortal(),\n\t\t\t},\n\t\t\tthis.config.locale,\n\t\t)\n\t}\n\n\tasync getOffer(options: { force?: boolean } = {}): Promise<PayOfferResponse> {\n\t\tawait this.initialize()\n\t\ttry {\n\t\t\treturn await this.fetchOffer(options.force)\n\t\t} catch (error) {\n\t\t\tthrow this.reportError(error)\n\t\t}\n\t}\n\n\t/**\n\t * Renders the paywall and resolves `true` when a checkout started from it\n\t * completes, `false` when the user closes it. The offer is fetched via\n\t * `getOffer()`; if that fails the paywall still renders with checkout disabled.\n\t */\n\tasync showPaywall(options: PaywallOptions = {}): Promise<boolean> {\n\t\treturn this.present(options, null)\n\t}\n\n\t/**\n\t * The paywall for a user whose free trial ended, e.g. on `trial:ended`. In the user's\n\t * language it says the trial has ended, the tools are paused and the settings are kept,\n\t * then shows the plans, \"Restore purchase\" when recovery is on, and with `feedbackFormUrl`\n\t * a feedback button. Resolves like `showPaywall()`. The default text promises the settings\n\t * are kept: pass `description` if your extension does not keep them.\n\t */\n\tasync showTrialEnded(options: TrialEndedOptions = {}): Promise<boolean> {\n\t\tconst t = sdkStrings(this.config.locale)\n\t\tconst feedbackUrl = trialFeedbackUrl(options.feedbackFormUrl)\n\t\tif (options.feedbackFormUrl !== undefined && !feedbackUrl)\n\t\t\tthis.reportError(\n\t\t\t\tnew ExtenshiPayError(\n\t\t\t\t\tERROR_CODES.INVALID_REQUEST,\n\t\t\t\t\t'feedbackFormUrl must be an https URL without credentials; the feedback button is left out',\n\t\t\t\t),\n\t\t\t)\n\t\tconst { feedbackFormUrl: _url, feedbackLabel, ...paywall } = options\n\t\treturn this.present(\n\t\t\t{\n\t\t\t\t...paywall,\n\t\t\t\ttitle: options.title ?? t.trialEndedTitle,\n\t\t\t\tdescription: options.description ?? t.trialEndedDescription,\n\t\t\t},\n\t\t\tfeedbackUrl ? { label: feedbackLabel ?? t.trialEndedFeedback, url: feedbackUrl } : null,\n\t\t)\n\t}\n\n\tprivate async present(\n\t\toptions: PaywallOptions,\n\t\tfeedback: { label: string; url: string } | null,\n\t): Promise<boolean> {\n\t\tawait this.initialize()\n\t\tif (this.entitlements.getCached()?.regionalFreeUntil) return false\n\t\tlet offer: PayOfferResponse | null = null\n\t\ttry {\n\t\t\toffer = await this.fetchOffer()\n\t\t} catch (error) {\n\t\t\tthis.reportError(error)\n\t\t}\n\t\tconst selected = pickOffer(offer, options.sku)\n\t\tconst defaults = stringsFor(this.config.locale)\n\t\tconst view: PaywallView = {\n\t\t\tmode: options.mode ?? 'modal',\n\t\t\ttitle: options.title ?? selected?.title ?? defaults.title,\n\t\t\tdescription: options.description ?? selected?.description ?? defaults.description,\n\t\t\t// The offer's `features` are entitlement keys ('full'), not display\n\t\t\t// text: bullets come from the caller only, or the block is dropped.\n\t\t\tfeatures: options.features ?? [],\n\t\t\tfreeFeatures: options.freeFeatures ?? [],\n\t\t\ticon: paywallIconUrl(options.icon),\n\t\t\tbrandName: offer?.projectName ?? '',\n\t\t\toffer: selected,\n\t\t\tcheckoutEnabled: offer?.checkoutEnabled === true && selected !== null && offer.seller !== null,\n\t\t\tmock: this.config.mock,\n\t\t\trecoveryEnabled: offer?.recoveryEnabled === true,\n\t\t\tseller: offer?.seller ?? null,\n\t\t\twithdrawalWaiver: offer?.withdrawalWaiver ?? null,\n\t\t\tfeedback: feedback ? { label: feedback.label } : null,\n\t\t\tlocale: this.config.locale,\n\t\t\ttheme: { ...this.config.theme, ...options.theme },\n\t\t\tstrings: options.strings ?? {},\n\t\t\tcontainer: options.container,\n\t\t}\n\t\tthis.hidePaywall()\n\t\treturn new Promise<boolean>((resolve) => {\n\t\t\tthis.paywallSession = { options, resolve, feedbackUrl: feedback?.url ?? null }\n\t\t\ttry {\n\t\t\t\tthis.renderer().show(view)\n\t\t\t} catch (error) {\n\t\t\t\tthis.paywallSession = null\n\t\t\t\tthis.reportError(error)\n\t\t\t\tresolve(false)\n\t\t\t}\n\t\t})\n\t}\n\n\thidePaywall(): void {\n\t\tthis.paywall?.hide()\n\t\tthis.settlePaywall(false)\n\t}\n\n\tisPaywallVisible(): boolean {\n\t\treturn this.paywall?.isVisible() === true\n\t}\n\n\tprotected override async onFeatureLocked(\n\t\t_feature: string,\n\t\toptions: RequireFeatureOptions,\n\t): Promise<boolean> {\n\t\tif (options.showPaywall === false) return false\n\t\tif ((await this.getEntitlement()).requiresOnlineCheck) {\n\t\t\tawait this.showLicense()\n\t\t\treturn false\n\t\t}\n\t\treturn this.showPaywall(options.paywall ?? {})\n\t}\n\n\tprivate renderer(): PaywallRenderer {\n\t\tif (!this.paywall) {\n\t\t\tthis.paywall = new PaywallRenderer({\n\t\t\t\tonUpgrade: (sku, consent) => void this.handleUpgrade(sku, consent),\n\t\t\t\tonClose: () => this.settlePaywall(false),\n\t\t\t\tonRestore: () => void this.handleRestore(),\n\t\t\t\tonFeedback: () => void this.handleFeedback(),\n\t\t\t})\n\t\t}\n\t\treturn this.paywall\n\t}\n\n\tprivate async handleRestore(): Promise<void> {\n\t\ttry {\n\t\t\tconst result = await this.restorePurchase()\n\t\t\tif (result.state === 'complete' && isEntitled(result.entitlement)) {\n\t\t\t\tthis.paywall?.hide()\n\t\t\t\tthis.settlePaywall(true)\n\t\t\t}\n\t\t} catch {\n\t\t\t/* Reported through the error event; leave the paywall open for retry. */\n\t\t}\n\t}\n\n\tprivate async handleFeedback(): Promise<void> {\n\t\tconst url = this.paywallSession?.feedbackUrl\n\t\tif (!url) return\n\t\ttry {\n\t\t\tawait (this.openUrl ?? openInNewTab)(url)\n\t\t} catch (error) {\n\t\t\tthis.reportError(error)\n\t\t}\n\t}\n\n\tprivate async handleUpgrade(sku: string, consent?: UpgradeConsent): Promise<void> {\n\t\tif (consent) this.paywallSession?.options.onUpgrade?.(sku, consent)\n\t\telse this.paywallSession?.options.onUpgrade?.(sku)\n\t\ttry {\n\t\t\tconst result = await this.openCheckout(\n\t\t\t\tsku,\n\t\t\t\tconsent?.withdrawalWaiver ? { withdrawalWaiver: consent.withdrawalWaiver } : {},\n\t\t\t)\n\t\t\tif (result.state === 'complete') {\n\t\t\t\tthis.paywall?.hide()\n\t\t\t\tthis.settlePaywall(true)\n\t\t\t}\n\t\t} catch {\n\t\t\t// Reported through the `error` event by openCheckout(); the paywall stays open for a retry.\n\t\t}\n\t}\n\n\tprivate settlePaywall(unlocked: boolean): void {\n\t\tconst session = this.paywallSession\n\t\tif (!session) return\n\t\tthis.paywallSession = null\n\t\tif (!unlocked) session.options.onClose?.()\n\t\tsession.resolve(unlocked)\n\t}\n}\n"],"names":["PAY_CONTRACT_VERSION","PAY_GATEWAYS","PAY_PUBLISHABLE_KEY_PREFIX","PAY_PUBLISHABLE_KEY_HEX_LENGTH","PUBLISHABLE_KEY_RE","RegExp","isPayPublishableKey","value","test","PAY_OFFER_KINDS","PAY_OFFER_INTERVALS","PAY_CURRENCIES","PAY_SKU_RE","PAY_ENTITLEMENT_STATUSES","PAY_REGIONAL_ACCESS_SKU","PAY_WITHDRAWAL_WAIVER_VERSION","PAY_END_USER_REF_RE","PAY_ERRORS","SELLER_NOT_CONNECTED","SELLER_NOT_ACTIVE","AGREEMENT_REQUIRED","OFFER_NOT_FOUND","OFFER_LIMIT","PRICE_TOO_LOW","GATEWAY_UNAVAILABLE","RATE_LIMITED","INVALID_KEY","WITHDRAWAL_WAIVER_REQUIRED","canonicalJson","JSON","stringify","Array","isArray","map","item","join","Object","entries","filter","v","undefined","sort","a","b","k","PAY_RESTORE_PURPOSES","STORAGE_TOKEN_RE","ERROR_CODES","INVALID_CONFIG","INVALID_REQUEST","NETWORK_ERROR","TIMEOUT","VERIFICATION_UNAVAILABLE","INVALID_RESPONSE","CHECKOUT_UNAVAILABLE","PAYWALL_UNAVAILABLE","UNKNOWN","ExtenshiPayError","Error","constructor","code","message","options","super","this","name","retryAfterSec","httpStatus","cause","from","error","fallback","String","END_USER_REF_STORAGE_KEY","mintEndUserRef","cryptoApi","globalThis","crypto","randomUUID","bytes","getRandomValues","Uint8Array","hex","toString","padStart","slice","async","getOrCreateEndUserRef","storage","existing","get","ref","set","DAY_MS","MockTransport","data","sessions","Map","entitlements","offers","projectName","checkoutEnabled","claimAfterPolls","withdrawalWaiver","version","seller","trial","setTrial","days","startedAt","call","procedure","_kind","input","offerResponse","createCheckout","sku","consent","accepted","mockConsent","claim","sessionId","endUserRef","publishableKey","envelope","url","length","setEntitlements","items","Date","toISOString","start","parse","Number","isFinite","endsAt","cancelSession","session","state","expireSession","provider","entitlementPublicKey","some","offer","polls","expiresAt","now","grant","entitlement","find","o","kind","interval","title","status","features","payload","issuedAt","signature","alg","PayApi","transport","createRestoreSession","claimChallenge","locale","purpose","claimRestoreSession","claimSecret","getOffer","claimSession","getEntitlement","trialStartedHint","getPortalUrl","customerId","ORDER","silent","warn","info","debug","Logger","level","prefix","configure","logLevel","args","enabled","console","logger","TRPC_PATH","RETRYABLE","Set","CAUSE_TO_CODE","trpcErrorToPayError","trpcCode","causeCode","match","exec","parseRetryAfter","mapped","sleep","ms","Promise","resolve","setTimeout","HttpTransport","apiUrl","replace","timeoutMs","retries","fetchImpl","init","fetch","base","encodeURIComponent","attempts","lastError","attempt","request","err","has","controller","AbortController","timer","abort","response","method","headers","body","signal","credentials","aborted","clearTimeout","json","ok","result","CHECKOUT_POLL_INTERVAL_MS","CHECKOUT_TIMEOUT_MS","openInNewTab","g","tabs","chrome","browser","create","then","open","CheckoutManager","active","pendingKey","isActive","getEndUserRef","api","pending","emit","openUrl","poll","resumePending","raw","expires","remove","settle","pollIntervalMs","deadline","sleeper","wake","interruptibleSleep","stopFocus","onFocus","disposers","addEventListener","removeEventListener","push","doc","document","onVisible","visibilityState","windows","onFocusChanged","addListener","onWindow","windowId","removeListener","dispose","onFocusRegained","delay","errorBackoff","Math","min","onComplete","CloudBackup","storageKey","accept","token","reason","assertTrustedContext","disable","mock","throwUnlessOk","runtime","id","inContentScript","path","Authorization","LIVE_STATUSES","isLive","applyLocalExpiry","collectFeatures","feature","add","isEntitled","requiresOnlineCheck","hasFeature","includes","checkFeatures","EMPTY_ENTITLEMENT","freeze","verified","fetchedAt","source","offlineUntil","base64ToBytes","base64","binary","atob","i","charCodeAt","verifyEntitlementSignature","publicKeyBase64","subtle","key","importKey","TextEncoder","encode","verify","PUBLIC_KEY_RE","verifyWithKeys","verdict","known","current","mismatch","fetchCurrent","MAX_TIMER_MS","TrialNotifier","running","evaluate","stop","clearTimer","check","catch","getTrial","endingAt","endingDays","event","daysLeft","hasPaidAccess","send","next","at","max","field","stored","sent","MIN_REFRESH_INTERVAL_MS","MAX_REFRESH_BACKOFF_MS","MAX_CLOCK_SKEW_MS","isEnvelope","env","EntitlementManager","held","inflight","clockSkew","refreshGeneration","deadlineTimer","refreshIntervalMs","backoffMs","autoRefresh","online","force","notifyIfChanged","lastFingerprint","load","record","measureClockSkew","fingerprint","snapshot","reverify","keys","discard","scheduleDeadline","verifiedKey","getCached","clock","left","checked","ceil","trialState","offlineDeadline","isFresh","cacheTtlMs","offlineAgeMs","refresh","onError","hint","getTrialStartHint","finally","onAccepted","settleRefresh","clear","startAutoRefresh","intervalMs","stopAutoRefresh","schedule","deadlines","NaN","remaining","delayMs","generation","local","server","abs","direction","regionalFreeUntil","onChange","seconds","offlineSeconds","grants","regional","extensionGlobals","areaCall","direct","withCallback","reject","ExtensionStorage","area","cb","LocalStorageAdapter","store","getItem","setItem","removeItem","MemoryStorage","delete","createSyncStorage","sync","createStorage","localStorage","createRecoveryStorage","extension","RecoveryManager","stopped","secret","hash","digest","challenge","created","done","once","cloudBackup","onStorageGrant","DEFAULT_API_URL","DEFAULT_CACHE_TTL_MS","MAX_CACHE_TTL_MS","DEFAULT_TRIAL_ENDING_DAYS","VERSION","WIRE_LOCALE_RE","wireLocale","parts","trim","split","Boolean","lang","toLowerCase","script","p","region","tag","toUpperCase","ENVIRONMENTS","LOG_LEVELS","THEME_MODES","LOCALE_RE","resolveConfig","errors","URL","protocol","isHttpUrl","environment","ui","i18n","getUILanguage","navigator","language","browserLocale","theme","mode","trialEndingDays","isInteger","mockData","syncTrialStart","EventEmitter","listeners","on","listener","off","fn","removeAll","SDK_LOCALES","SDK_STRINGS_EN","description","upgrade","cancel","dismiss","remindLater","continueFree","checkoutUnavailable","periodMonth","periodYear","periodOnce","footer","restorePurchase","featuresHeading","plansHeading","freePlanName","premiumPlanName","popularBadge","unlockHeading","simulatePurchase","mockNotice","sellerProvidedBy","sellerUnavailable","sellerSupport","sellerTerms","sellerRefunds","sellerRole","licenseTitle","licenseFallbackName","licenseNone","kindOneTime","kindLifetime","kindSubscription","kindLicense","statusLine","statusActive","statusGrace","statusExpired","statusNone","accessEnded","accessUntil","accessRecordedEnd","subscriptionLine","renewalCanceled","periodEnds","subActive","subTrialing","subPastDue","subCanceled","subUnpaid","subIncomplete","subIncompleteExpired","subPaused","licenseOffline","licenseCached","licenseFresh","actionFailed","manageBilling","noPortal","close","pickerTitle","pickerDescription","pickerFirstRecorded","pickerCancel","trialEndedTitle","trialEndedDescription","trialEndedFeedback","TRANSLATIONS","es","fr","de","it","ru","ja","ko","ar","sdkLocale","exact","l","sdkDir","sdkStrings","fill","values","whole","WITHDRAWAL_WAIVER_TEXTS","en","withdrawalWaiverText","serverVersion","text","ExtenshiPayLite","config","deps","emitter","endUserRefPromise","offerInflight","serverKey","offline","readSavedServerKey","fetchOffer","readyPromise","destroyed","syncStorage","rememberTrialStart","readTrialStartHint","reportError","license","checkout","backup","recovery","recoveryStorage","onReady","initialize","doInitialize","afterReady","confirmSavedServerKey","getCachedEntitlement","isPaid","requireFeature","onUnlock","unlocked","onFeatureLocked","onCancel","_feature","_options","getWithdrawalWaiver","displayName","openCheckout","enableCloudBackup","cloudBackupToken","disableCloudBackup","deleteCloudBackup","getLicenseSummary","recoveryEnabled","openCustomerPortal","accounts","selectAccount","onEntitlementChange","clearCache","destroy","rememberServerKey","serverKeyStorageKey","used","trialStartKey","synced","sellerDetails","t","section","createElement","className","textContent","append","link","label","href","username","password","publicContactUrl","target","rel","style","marginInlineEnd","supportUrl","termsUrl","refundPolicyUrl","role","statusLabel","grace","expired","none","subscriptionStatusLabel","trialing","past_due","canceled","unpaid","incomplete","incomplete_expired","paused","LicensePanel","hide","show","summary","actions","host","setAttribute","root","attachShadow","dialog","content","feedback","render","replaceChildren","note","empty","article","heading","date","isNaN","getTime","expiry","when","toLocaleString","sub","subscriptions","row","cancelAtPeriodEnd","freshness","showModal","closed","preventDefault","buttons","action","run","button","type","forEach","disabled","updated","restore","manage","BillingProfilePicker","finish","account","detail","recorded","createdAt","toLocaleDateString","subscription","line","end","currentPeriodEnd","cancellation","DATA_IMAGE_RE","PACKAGE_BASE_RE","paywallIconUrl","option","explicit","extensionRuntime","getURL","packageBase","location","startsWith","onExtensionPage","best","size","getManifest","icons","n","largestIcon","formatPrice","amountMinor","currency","formatter","Intl","NumberFormat","formatToParts","part","amount","full","format","toFixed","periodLabel","strings","paywallStrings","DEFAULT_STRINGS","stringsFor","PAYWALL_SHARED_CSS","PAYWALL_TEMPLATES","modal","html","css","inline","sidebar","fullscreen","minimal","PAYWALL_MODES","PAYWALL_HOST_CLASS","UPGRADE_ACTIONS","UPGRADE_SELECTOR","WITHDRAWAL_WAIVER_CLASS","CLOSE_ACTIONS","ROOT_SELECTOR","BACKDROP_SELECTOR","VISIBLE_CLASSES","ICON_TILE_SELECTOR","FEATURE_ITEM_VISIBLE","FEATURE_SLOT_SELECTOR","EMPTY_SLOT_MARK","OPTIONAL_KEY_RE","escapeHtml","substitute","_match","buildContent","view","price","offerDescription","priceCopy","brandName","period","pricingDescription","priceDescription","premiumDescription","upgradeButtonText","cancelButtonText","dismissButtonText","remindLaterText","continueButtonText","footerText","index","freeFeatures","CSS_VALUE_UNSAFE","PRIMARY_TINTS","PRIMARY_SHADES","themeCss","declarations","safe","primaryColor","color","step","percent","fontFamily","borderRadius","radius","customCss","resolveThemeMode","matchMedia","matches","PaywallRenderer","callbacks","keyHandler","isVisible","template","innerHTML","prune","icon","placeIcon","waiver","waiverSellerName","waiverBox","bind","sellerMount","querySelector","details","cssText","modalActions","before","notice","mountWaiver","onRestore","footerLink","onFeedback","container","appendChild","reveal","ownerDocument","onClick","element","querySelectorAll","mark","parentElement","closest","block","slot","glyph","children","child","localName","tile","getAttribute","img","alt","replaceWith","removeProperty","src","background","first","span","removeAttribute","given","onUpgrade","backdropSelector","currentTarget","rootElement","display","selector","classList","onClose","ExtenshiPay","disposed","licensePanel","billingProfiles","paywall","paywallSession","hidePaywall","showLicense","showPaywall","present","showTrialEnded","feedbackUrl","searchParams","trialFeedbackUrl","feedbackFormUrl","_url","feedbackLabel","selected","candidate","pickOffer","defaults","renderer","settlePaywall","isPaywallVisible","handleUpgrade","handleRestore","handleFeedback"],"mappings":";;;;;;AAaO,MAAMA,EAAuB,EAEvBC,EAAe,CAAC,SAAU,SAAU,gBAUpCC,EAA6B,UAC7BC,EAAiC,GACxCC,EAAqB,IAAIC,OAC9B,IAAIH,kBAGC,SAAUI,EAAoBC,GACnC,MAAwB,iBAAVA,GAAsBH,EAAmBI,KAAKD,EAC7D,CAIO,MAAME,EAAkB,CAAC,WAAY,eAAgB,YAG/CC,EAAsB,CAAC,QAAS,QAIhCC,EAAiB,CAAC,MAAO,MAAO,OAIhCC,EAAa,6BAWbC,EAA2B,CAAC,SAAU,QAAS,UAAW,QAiB1DC,EAA0B,iBAoC1BC,EAAgC,aAwEhCC,EAAsB,kEAGtBC,EAAa,CACzBC,qBAAsB,2BACtBC,kBAAmB,wBACnBC,mBAAoB,yBACpBC,gBAAiB,sBACjBC,YAAa,kBACbC,cAAe,oBACfC,oBAAqB,0BACrBC,aAAc,mBACdC,YAAa,kBACbC,2BAA4B,kCASvB,SAAUC,EAAcrB,GAC7B,GAAc,OAAVA,GAAmC,iBAAVA,EAAoB,OAAOsB,KAAKC,UAAUvB,GACvE,GAAIwB,MAAMC,QAAQzB,GAAQ,MAAO,IAAIA,EAAM0B,IAAKC,GAASN,EAAcM,IAAOC,KAAK,QAInF,MAAO,IAHSC,OAAOC,QAAQ9B,GAC7B+B,OAAO,EAAC,CAAGC,UAAaC,IAAND,GAClBE,KAAK,EAAEC,IAAKC,KAAQD,EAAIC,GAAI,EAAKD,EAAIC,EAAI,EAAI,GAC5BV,IAAI,EAAEW,EAAGL,KAAO,GAAGV,KAAKC,UAAUc,MAAMhB,EAAcW,MAAMJ,KAAK,OACrF,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