@mesub/node 0.1.0 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/README.md +10 -5
  2. package/dist/{chunk-ELK7IBLO.js → chunk-35MOUS4W.js} +2 -2
  3. package/dist/{chunk-XDLLXY7Y.js → chunk-6HGYY2KN.js} +2 -2
  4. package/dist/{chunk-SGSYQJYT.cjs → chunk-BP5D5I66.cjs} +31 -22
  5. package/dist/chunk-BP5D5I66.cjs.map +1 -0
  6. package/dist/{chunk-KMPBFNJE.js → chunk-JCDJZDEJ.js} +16 -7
  7. package/dist/chunk-JCDJZDEJ.js.map +1 -0
  8. package/dist/{chunk-PCDZI7B4.cjs → chunk-RSN2QQUR.cjs} +7 -7
  9. package/dist/{chunk-PCDZI7B4.cjs.map → chunk-RSN2QQUR.cjs.map} +1 -1
  10. package/dist/{chunk-VMKI4VVA.cjs → chunk-WNHLTJ6F.cjs} +4 -4
  11. package/dist/{chunk-VMKI4VVA.cjs.map → chunk-WNHLTJ6F.cjs.map} +1 -1
  12. package/dist/{client-Dm1jamju.d.cts → client-BZB6KIGd.d.cts} +10 -3
  13. package/dist/{client-BQuRYSdB.d.ts → client-Q5QhXphp.d.ts} +10 -3
  14. package/dist/{errors-DqW3DMBS.d.ts → errors-BN4ZWUfM.d.ts} +1 -1
  15. package/dist/{errors-CtPucyOh.d.cts → errors-DcLfunS-.d.cts} +1 -1
  16. package/dist/express.cjs +21 -21
  17. package/dist/express.d.cts +7 -7
  18. package/dist/express.d.ts +7 -7
  19. package/dist/express.js +3 -3
  20. package/dist/{guard-DKb6iU1z.d.ts → guard-CaXiHMVF.d.ts} +1 -1
  21. package/dist/{guard-Dhy4fI6n.d.cts → guard-D4AB5HtN.d.cts} +1 -1
  22. package/dist/index.cjs +2 -2
  23. package/dist/index.d.cts +5 -5
  24. package/dist/index.d.ts +5 -5
  25. package/dist/index.js +1 -1
  26. package/dist/nest.cjs +13 -13
  27. package/dist/nest.d.cts +5 -5
  28. package/dist/nest.d.ts +5 -5
  29. package/dist/nest.js +2 -2
  30. package/dist/next.cjs +20 -20
  31. package/dist/next.d.cts +7 -7
  32. package/dist/next.d.ts +7 -7
  33. package/dist/next.js +3 -3
  34. package/dist/{routes-DWkRFOP0.d.cts → routes-DT8EFWSl.d.cts} +2 -2
  35. package/dist/{routes-CLtZnUzl.d.ts → routes-KoaD1Xsk.d.ts} +2 -2
  36. package/dist/situations.d.cts +1 -1
  37. package/dist/situations.d.ts +1 -1
  38. package/dist/{subscriptions-D1hE7MUc.d.ts → subscriptions-B6Lin6i_.d.cts} +7 -0
  39. package/dist/{subscriptions-D1hE7MUc.d.cts → subscriptions-B6Lin6i_.d.ts} +7 -0
  40. package/dist/testing.cjs +20 -18
  41. package/dist/testing.cjs.map +1 -1
  42. package/dist/testing.d.cts +2 -2
  43. package/dist/testing.d.ts +2 -2
  44. package/dist/testing.js +8 -6
  45. package/dist/testing.js.map +1 -1
  46. package/package.json +1 -1
  47. package/dist/chunk-KMPBFNJE.js.map +0 -1
  48. package/dist/chunk-SGSYQJYT.cjs.map +0 -1
  49. /package/dist/{chunk-ELK7IBLO.js.map → chunk-35MOUS4W.js.map} +0 -0
  50. /package/dist/{chunk-XDLLXY7Y.js.map → chunk-6HGYY2KN.js.map} +0 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["/home/runner/work/node-sdk/node-sdk/dist/chunk-PCDZI7B4.cjs","../src/routes.ts"],"names":["id","subscription","action"],"mappings":"AAAA;AACE;AACA;AACF,wDAA6B;AAC7B;AACA;AC6DO,IAAM,eAAA,EAAiB,GAAA,EAAK,IAAA;AAEnC,IAAM,QAAA,EAAU,CAAC,QAAA,EAAU,QAAA,EAAU,OAAO,CAAA;AAI5C,IAAM,GAAA,EAAK,uBAAA;AAEX,IAAM,KAAA,EAAO,uCAAA;AAMb,IAAM,iBAAA,EAAmB,GAAA;AAOzB,SAAS,OAAA,CAAA,EAAuB;AAC5B,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oC,EAAA;AACZ,IAAA;AACxB,EAAA;AACJ;ADrXmC;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/node-sdk/node-sdk/dist/chunk-PCDZI7B4.cjs","sourcesContent":[null,"import type { Customer, ServedAttempt } from './answer.js';\nimport type { Mesub } from './client.js';\nimport { type Asked, customerOf } from './customer.js';\nimport { MesubError } from './errors.js';\nimport type { Plan } from './plans.js';\nimport type { ServerSubscription, SubscriptionAttempt } from './subscriptions.js';\nimport type { CallOptions } from './transport.js';\n\n/**\n * The routes `@mesub/react` calls on your own server, so the browser never\n * talks to Mesub nor holds a key: a plan to show, the customer's\n * subscriptions, one of them with its payments, and each step of\n * subscribing (a fresh transaction to sign included), cancelling, resuming,\n * closing and paying a late payment now. One function, `handleWidget`; the\n * Express and Next entries only carry a request to it.\n *\n * Who is asking comes from `customer`, your own verified auth, as on the\n * guards. A subscription that is not that customer's is answered 404, the\n * same as one that does not exist.\n */\n\n/** Who is asking, from your own auth. Null when nobody is signed in, a 401. */\nexport type WidgetCustomer<Req> = (\n request: Req,\n) => Customer | string | null | undefined | Promise<Customer | string | null | undefined>;\n\nexport interface WidgetRoutesOptions<Req> {\n /** Defaults to one client built from MESUB_API_KEY. */\n client?: Mesub;\n /**\n * Who is asking, from a session you verified, never from the request\n * itself: `(req) => ({ external_id: req.user.id })`, a wallet or an email.\n * Every subscription created is tied to it, and only its own are reached.\n */\n customer: WidgetCustomer<Req>;\n /**\n * Where that customer's notices go, when `customer` is not an email:\n * `(req) => req.user.email`. Not verified by Mesub.\n */\n email?: (request: Req) => string | null | undefined | Promise<string | null | undefined>;\n /**\n * The plans the widget may subscribe to. Any plan of your project by\n * default; name them to keep one off your site.\n */\n plans?: readonly string[];\n}\n\n/** A request as the core reads it, whatever the framework. */\nexport interface WidgetRequest {\n method: string;\n /** After the mount point: `/subscriptions/sub_1/cancel`. */\n path: string;\n /** Parsed JSON, or undefined when there was none. */\n body: unknown;\n /** The request's `Content-Type`, to refuse a POST a plain form could send. */\n contentType: string | null;\n}\n\n/** What the core answers: a status and a JSON body. */\nexport interface WidgetResponse {\n status: number;\n body: unknown;\n headers?: Record<string, string>;\n}\n\n/** The most a widget request's body may weigh: a signed transaction is under 2 kB. */\nexport const MAX_BODY_BYTES = 64 * 1024;\n\nconst ACTIONS = ['cancel', 'resume', 'close'] as const;\ntype Action = (typeof ACTIONS)[number];\n\n/** An id as Mesub writes them: nothing that could rewrite the path. */\nconst ID = /^[A-Za-z0-9_-]{1,64}$/;\n/** A plan slug as Mesub writes them: with at least one letter, never a number. */\nconst SLUG = /^(?=.*[a-z])[a-z0-9]+(?:-[a-z0-9]+)*$/;\n\n/**\n * How long one widget request gives Mesub for all its reads, in milliseconds:\n * a browser is waiting, and a detail or a list makes several calls.\n */\nconst WIDGET_READ_TIME = 10_000;\n\n/**\n * How every read of one request is made, as a guard's: cut at one deadline,\n * and a 429 handed on at once, never waited out. The client's methods pass\n * their options to the transport whole, which is how these reach it.\n */\nfunction bounded(): CallOptions {\n return { deadline: Date.now() + WIDGET_READ_TIME, retryRateLimited: false };\n}\n\nfunction refusal(status: number, code: string, message: string): WidgetResponse {\n return { status, body: { error: { code, message } } };\n}\n\nconst NOT_FOUND = () => refusal(404, 'not_found', 'Nothing here.');\nconst NO_SUBSCRIPTION = () => refusal(404, 'subscription_not_found', 'No such subscription.');\n\n/** Said to the browser for an error Mesub did not word itself. */\nconst NO_ANSWER = 'Mesub could not answer this request.';\n\n/** Mesub's own words only: the transport's may name `baseUrl` or a network error. */\nfunction said(error: MesubError): string {\n return error.apiCode === null ? NO_ANSWER : error.message;\n}\n\n/**\n * Whether Mesub refused your server, not what the customer did: any 401,\n * which Mesub answers only to an API key missing, never issued or rotated\n * since (`missing_api_key`, `invalid_api_key`), or a 403 that names none of\n * Mesub's own codes, from something in front of Mesub turning your server\n * away. Handed on, a 401 reads to `@mesub/react` as \"nobody is signed in\",\n * and every visitor gets the sign-in screen: thrown instead, a broken\n * integration, for the framework to log and answer 500.\n */\nfunction brokenIntegration(error: MesubError): boolean {\n if (error.status === 401) return true;\n\n return error.status === 403 && (error.apiCode === null || error.apiCode === 'forbidden');\n}\n\n/** A Mesub refusal, handed on with its own status and code, and nothing of the key. */\nfunction fromMesub(error: MesubError): WidgetResponse {\n // No answer from Mesub, or a 2xx this SDK cannot read: a 502 of yours.\n const status = error.status === null || error.status < 400 ? 502 : error.status;\n const retry =\n error.retryAfter === null\n ? undefined\n : { 'Retry-After': String(Math.ceil(error.retryAfter / 1000)) };\n\n return {\n status,\n body: { error: { code: error.apiCode ?? error.code, message: said(error) } },\n ...(retry && { headers: retry }),\n };\n}\n\nfunction isString(value: unknown): value is string {\n return typeof value === 'string' && value !== '';\n}\n\nfunction fieldsOf(body: unknown): Record<string, unknown> | null {\n return typeof body === 'object' && body !== null && !Array.isArray(body)\n ? (body as Record<string, unknown>)\n : null;\n}\n\n/** Whether that subscription is the customer's: by the same identifier it was asked with. */\nfunction isTheirs(subscription: ServerSubscription, asked: Asked): boolean {\n if (asked.kind === 'wallet') return subscription.wallet === asked.value;\n if (asked.kind === 'external_id') return subscription.external_id === asked.value;\n\n return subscription.email === asked.value;\n}\n\n/** What a browser gets of a subscription: the merchant's own id and email stay on the server. */\nfunction shown(subscription: ServerSubscription) {\n const { email: _email, external_id: _externalId, ...rest } = subscription;\n\n return rest;\n}\n\n/** `GET /subscriptions` reads pages of 100, Mesub's largest, and 5 at most. */\nconst LIST_PAGE = 100;\nconst LIST_MAX_PAGES = 5;\n\n/** What `GET /subscriptions` answers. */\nexport interface WidgetSubscriptionList {\n /** Newest first, expired checkouts included: the 500 newest at most. */\n subscriptions: Array<Omit<ServerSubscription, 'email' | 'external_id'>>;\n /** True when the customer has more than those, which are not read. */\n has_more: boolean;\n}\n\n/** One pull attempt as the browser gets it: the fields Mesub serves, and no other. */\nexport interface WidgetPayment {\n attempted_at: string;\n /** `paid`, `skipped`, `rejected` or `blocked` today; a newer one is handed on as is. */\n outcome: string;\n /** What was asked for, in the mint's smallest unit; on a paid one, what was paid. */\n amount: string;\n /**\n * That amount in dollars when it was attempted, a decimal string. Null\n * until Mesub priced it, and from a Mesub that does not say.\n */\n amount_usd: string | null;\n /**\n * Mesub's short reason, null on a paid one, as on `ServedAttempt`: snake\n * case, an open string with the `program_${number}` and\n * `solana_${number}` families.\n */\n reason: string | null;\n /** The transaction that paid. Null on every outcome but `paid`. */\n signature: string | null;\n /** A retry of a missed charge. Null from a Mesub that does not say. */\n retry: boolean | null;\n /**\n * Which retry and out of how many, as Mesub recorded them when it ran:\n * 2 and 3 for \"retry 2 / 3\". Null when it is no retry of the plan's, or\n * Mesub does not say.\n */\n retry_number: number | null;\n retries_allowed: number | null;\n /** The start of the period it was for. Null when Mesub recorded none or does not say. */\n period_start: string | null;\n}\n\n/** What `GET /subscriptions/:id` answers. */\nexport interface WidgetSubscriptionDetail {\n subscription: Omit<ServerSubscription, 'email' | 'external_id'>;\n /** What Mesub pulls next, soonest first: one entry at most, none when nothing is due. */\n upcoming: WidgetUpcoming[];\n /**\n * This subscription's own pull attempts, newest first: the first page,\n * twenty at most, so not always its full history. Null when they could\n * not be read: `payments_error` says why.\n */\n payments: WidgetPayment[] | null;\n /**\n * What it paid since it began, counted by Mesub over all its attempts,\n * not over `payments`: how many were paid, and their sum in the mint's\n * smallest unit. Null when the read failed, and from a Mesub that does\n * not serve it: never summed here.\n */\n paid: { count: number; amount: string } | null;\n /** Why `payments` is null; null otherwise. */\n payments_error: { code: string; message: string } | null;\n}\n\n/** The one pull Mesub announces next for a subscription. */\nexport interface WidgetUpcoming {\n /** `charge` at the due date of a running one, `retry` of a missed one. */\n kind: 'charge' | 'retry';\n due_at: string;\n /**\n * The plan's price in the mint's smallest unit, and as a person counts\n * it. Null when the plan could not be read, never guessed.\n */\n amount: string | null;\n amount_display: string | null;\n /**\n * The plan's amount in dollars at the latest price Mesub knows, a decimal\n * string such as `\"9.99\"`: an estimate to show beside the amount, never\n * what is charged. Null when Mesub knows no price, and when the plan could\n * not be read.\n */\n amount_usd: string | null;\n /**\n * On a `retry`, which one it will be and out of how many: 2 and 3 for\n * \"next try 2 / 3\". Null on a `charge`, and when Mesub does not say.\n */\n retry_number: number | null;\n retries_allowed: number | null;\n}\n\n/** How long the plan list read for the widget is kept. */\nconst PLAN_TTL_MS = 60_000;\n\ninterface PlanList {\n /** Shared while the request is out. */\n plans: Promise<Plan[]>;\n /** Infinity until Mesub answered. */\n until: number;\n}\n\n// Per client, so two projects never share a plan.\nconst planLists = new WeakMap<Mesub, PlanList>();\n\n/**\n * A plan for the widget routes, from the project's list: public reads must\n * not spend the API key's rate limit, so one call per TTL whatever the slugs,\n * and null with no call for a slug that is not in it. A failed read is\n * forgotten at once.\n */\nasync function planOf(client: Mesub, slug: string, read: CallOptions): Promise<Plan | null> {\n let list = planLists.get(client);\n\n if (!list || list.until <= Date.now()) {\n // Shared while in flight: bound by the first asker's deadline, as a guard's flight.\n const fresh: PlanList = { plans: client.plans.list(read), until: Infinity };\n\n list = fresh;\n planLists.set(client, fresh);\n fresh.plans.then(\n () => {\n fresh.until = Date.now() + PLAN_TTL_MS;\n },\n () => {\n if (planLists.get(client) === fresh) planLists.delete(client);\n },\n );\n }\n\n return (await list.plans).find((plan) => plan.slug === slug) ?? null;\n}\n\n/**\n * What Mesub will pull next: the next charge of a running subscription, the\n * next retry of a late one, and nothing for any other, a parked seat\n * included. One event at most: later periods are not served, so not computed.\n * On Free a late one has no retry of Mesub's, only `retry_deadline`.\n */\nasync function upcomingOf(\n client: Mesub,\n subscription: ServerSubscription,\n read: CallOptions,\n): Promise<WidgetUpcoming[]> {\n const { status, plan } = subscription;\n const next =\n status === 'active'\n ? { kind: 'charge' as const, due_at: subscription.next_charge_at }\n : status === 'unpaid'\n ? { kind: 'retry' as const, due_at: subscription.next_retry_at }\n : null;\n\n // A date on any other status is no pull Mesub will run.\n if (!next || next.due_at === null || subscription.paused) return [];\n\n let price: Pick<Plan, 'amount' | 'amount_display' | 'amount_usd'> | null = null;\n\n if (plan !== null && SLUG.test(plan)) {\n try {\n price = await planOf(client, plan, read);\n } catch (error) {\n if (!(error instanceof MesubError) || brokenIntegration(error)) throw error;\n }\n }\n\n const retry = next.kind === 'retry';\n\n return [\n {\n kind: next.kind,\n due_at: next.due_at,\n amount: price?.amount ?? null,\n amount_display: price?.amount_display ?? null,\n amount_usd: price?.amount_usd ?? null,\n // Mesub's own, never counted here; `?? null` for a subscription cached by an older SDK.\n retry_number: retry ? (subscription.next_retry_number ?? null) : null,\n retries_allowed: retry ? (subscription.retries_allowed ?? null) : null,\n },\n ];\n}\n\n/** The statuses nothing is ever pulled in: a checkout that never started. */\nconst NEVER_STARTED = ['pending', 'expired', 'failed'];\n\nfunction payment(attempt: SubscriptionAttempt): WidgetPayment {\n return {\n attempted_at: attempt.attempted_at,\n outcome: attempt.outcome,\n amount: attempt.amount,\n // `?? null` for an attempt handed by a client that predates the field.\n amount_usd: attempt.amount_usd ?? null,\n reason: attempt.reason,\n signature: attempt.signature,\n retry: attempt.retry,\n retry_number: attempt.retry_number,\n retries_allowed: attempt.retries_allowed,\n period_start: attempt.period_start,\n };\n}\n\n/** An attempt of `/v1/access`, which says nothing of retries nor periods. */\nfunction olderPayment(attempt: ServedAttempt): WidgetPayment {\n return {\n attempted_at: attempt.attempted_at,\n outcome: attempt.outcome,\n amount: attempt.amount,\n amount_usd: null,\n reason: attempt.reason,\n signature: attempt.signature,\n retry: null,\n retry_number: null,\n retries_allowed: null,\n period_start: null,\n };\n}\n\ntype Payments = Omit<WidgetSubscriptionDetail, 'subscription' | 'upcoming'>;\n\nfunction unlisted(code: string, message: string): Payments {\n return { payments: null, paid: null, payments_error: { code, message } };\n}\n\n/**\n * A subscription's own pull attempts and what it paid, from\n * `GET /v1/subscriptions/:id/attempts`. A Mesub that predates the route\n * (Mesub-io/backend#289) answers a 404 that names no code for it: its payments are then\n * read the older way, without a total.\n */\nasync function paymentsOf(\n client: Mesub,\n subscription: ServerSubscription,\n read: CallOptions,\n): Promise<Payments> {\n try {\n const page = await client.subscriptions.attempts(subscription.id, {}, read);\n\n return { payments: page.data.map(payment), paid: page.paid, payments_error: null };\n } catch (error) {\n if (!(error instanceof MesubError) || brokenIntegration(error)) throw error;\n // No such route, not no such subscription: that one names its code.\n if (error.status === 404 && error.apiCode === null) {\n return olderPaymentsOf(client, subscription, read);\n }\n\n // The subscription was read: it is answered without them, so the dialog still opens.\n return unlisted(error.apiCode ?? error.code, said(error));\n }\n}\n\n/**\n * The last pull attempts as a Mesub without the attempts route serves them:\n * through `/v1/access` only, five at most, for the subscription in force on\n * that wallet and plan, naming no id. They are this one's only when the\n * answer started when this one did. No total: five attempts are not one.\n */\nasync function olderPaymentsOf(\n client: Mesub,\n subscription: ServerSubscription,\n read: CallOptions,\n): Promise<Payments> {\n const { plan, wallet, confirmed_at: confirmedAt } = subscription;\n const listed = (payments: WidgetPayment[]): Payments => ({\n payments,\n paid: null,\n payments_error: null,\n });\n\n // Never started, so never pulled: nothing to ask.\n if (confirmedAt === null && NEVER_STARTED.includes(subscription.status)) return listed([]);\n if (plan === null || !SLUG.test(plan)) {\n return unlisted('plan_without_slug', 'Its plan has no slug to read payments by.');\n }\n\n try {\n const answer = await client.access({ wallet }, plan, { attempts: true, ...read });\n const same =\n confirmedAt !== null &&\n answer.subscribed_since !== null &&\n Date.parse(answer.subscribed_since) === Date.parse(confirmedAt);\n\n if (!same) {\n return unlisted(\n 'not_the_current_subscription',\n 'This Mesub serves payments for the current subscription of a wallet on a plan only.',\n );\n }\n\n return listed(\n (answer.attempts ?? [])\n .map(olderPayment)\n .sort((a, b) => Date.parse(b.attempted_at) - Date.parse(a.attempted_at)),\n );\n } catch (error) {\n if (!(error instanceof MesubError) || brokenIntegration(error)) throw error;\n\n return unlisted(error.apiCode ?? error.code, said(error));\n }\n}\n\n/**\n * Answers one request of the widget. `asked` is who your auth says is asking,\n * already normalised, or null for nobody; `email` their notices' address.\n *\n * Never throws for what the caller sent or what Mesub refused of the\n * customer's request: both are answered. An integration error is thrown to\n * the framework, which logs it and answers 500: Mesub refusing your API key\n * (its 401, never handed on as the customer's own) or something in front of\n * Mesub refusing your server (a 403 without Mesub's code), and anything that\n * is not a MesubError. The 401 answered here means nobody is signed in, only.\n */\nexport async function handleWidget(\n client: Mesub,\n request: WidgetRequest,\n asked: Asked | null,\n options: { email?: string | null | undefined; plans?: readonly string[] } = {},\n): Promise<WidgetResponse> {\n const segments = request.path.split('?')[0]!.split('/').filter(Boolean);\n const method = request.method.toUpperCase();\n const read = bounded();\n\n try {\n // A plan is public: the page shows its price before anybody signs in.\n if (method === 'GET' && segments.length === 2 && segments[0] === 'plans') {\n const slug = segments[1]!;\n\n if (!SLUG.test(slug) || (options.plans && !options.plans.includes(slug))) {\n return refusal(404, 'plan_not_found', 'No such plan.');\n }\n\n const plan = await planOf(client, slug, read);\n\n return plan\n ? { status: 200, body: plan }\n : refusal(404, 'plan_not_found', 'No such plan.');\n }\n\n if (segments[0] !== 'subscriptions') return NOT_FOUND();\n if (method !== 'GET' && method !== 'POST') {\n return refusal(405, 'method_not_allowed', 'GET or POST.');\n }\n if (!asked) return refusal(401, 'unauthenticated', 'Sign in first.');\n\n if (method === 'GET' && segments.length === 2) {\n const id = segments[1]!;\n\n if (!ID.test(id)) return NO_SUBSCRIPTION();\n\n // Theirs first: another customer's is not read any further.\n const subscription = await client.subscriptions.retrieve(id, read);\n if (!isTheirs(subscription, asked)) return NO_SUBSCRIPTION();\n\n const [upcoming, payments] = await Promise.all([\n upcomingOf(client, subscription, read),\n paymentsOf(client, subscription, read),\n ]);\n const detail: WidgetSubscriptionDetail = {\n subscription: shown(subscription),\n upcoming,\n ...payments,\n };\n\n return { status: 200, body: detail };\n }\n\n if (method === 'GET') {\n if (segments.length !== 1) return NOT_FOUND();\n\n const params = { ...customerParam(asked), limit: LIST_PAGE };\n let page = await client.subscriptions.list(params, read);\n const subscriptions = [...page.data];\n\n const more = () => page.has_more && page.data.length > 0;\n\n // One browser request is LIST_MAX_PAGES calls to Mesub at most.\n for (let pages = 1; more() && pages < LIST_MAX_PAGES; pages++) {\n page = await client.subscriptions.list(\n { ...params, starting_after: page.data.at(-1)!.id },\n read,\n );\n subscriptions.push(...page.data);\n }\n\n const list: WidgetSubscriptionList = {\n subscriptions: subscriptions.map(shown),\n has_more: more(),\n };\n\n return { status: 200, body: list };\n }\n\n // A JSON body cannot be sent by a plain form from another site.\n if (!request.contentType?.toLowerCase().startsWith('application/json')) {\n return refusal(415, 'unsupported_media_type', 'Send JSON.');\n }\n\n const body = fieldsOf(request.body) ?? {};\n\n if (segments.length === 1) {\n const { plan, wallet } = body;\n\n if (!isString(plan) || !SLUG.test(plan) || !isString(wallet)) {\n return refusal(400, 'invalid_request', 'A plan and a wallet are needed.');\n }\n if (options.plans && !options.plans.includes(plan)) {\n return refusal(404, 'plan_not_found', 'No such plan.');\n }\n // Named by wallet, the customer is that wallet: no other may be subscribed for them.\n if (asked.kind === 'wallet' && asked.value !== wallet) {\n return refusal(403, 'wallet_mismatch', 'Connect the wallet you signed in with.');\n }\n\n const email = asked.kind === 'email' ? asked.value : options.email;\n const created = await client.subscriptions.create({\n plan,\n wallet,\n ...(asked.kind === 'external_id' && { external_id: asked.value }),\n ...(isString(email) && { email }),\n });\n\n return { status: 201, body: created };\n }\n\n const id = segments[1]!;\n const step = segments.slice(2).join('/');\n\n if (!ID.test(id)) return NO_SUBSCRIPTION();\n\n const known = [\n 'submit',\n 'transaction',\n 'retry',\n ...ACTIONS,\n ...ACTIONS.map((action) => `${action}/confirm`),\n ];\n if (!known.includes(step)) return NOT_FOUND();\n\n // Before anything is built or confirmed: is it theirs at all.\n const subscription = await client.subscriptions.retrieve(id, read);\n if (!isTheirs(subscription, asked)) return NO_SUBSCRIPTION();\n\n if (step === 'submit') {\n const { transaction, terms_signature: termsSignature } = body;\n\n if (!isString(transaction) || !isString(termsSignature)) {\n return refusal(\n 400,\n 'invalid_request',\n 'The signed transaction and the terms signature are needed.',\n );\n }\n\n const settled = await client.subscriptions.submit(id, {\n transaction,\n terms_signature: termsSignature,\n });\n\n return { status: 201, body: { ...settled, subscription: shown(settled.subscription) } };\n }\n\n // A fresh transaction for a pending one (Mesub-io/backend#427): answered as subscribing is.\n if (step === 'transaction') {\n return { status: 201, body: await client.subscriptions.transaction(id) };\n }\n\n // Pay now (Mesub-io/backend#354): nothing to sign, the outcome comes with the pull.\n if (step === 'retry') {\n const retried = await client.subscriptions.retry(id);\n\n return { status: 202, body: { subscription: shown(retried) } };\n }\n\n const [action, confirm] = step.split('/') as [Action, 'confirm' | undefined];\n\n if (!confirm) {\n return { status: 201, body: await client.subscriptions[action](id) };\n }\n\n const { signature } = body;\n if (!isString(signature)) {\n return refusal(400, 'invalid_request', 'The signature of the transaction is needed.');\n }\n\n const confirmed = await client.subscriptions[CONFIRM[action]](id, { signature });\n\n return {\n status: 201,\n body: { ...confirmed, subscription: shown(confirmed.subscription) },\n };\n } catch (error) {\n if (!(error instanceof MesubError) || brokenIntegration(error)) throw error;\n // An unknown id is Mesub's 404, answered as ours: nothing tells the two apart.\n if (error.apiCode === 'subscription_not_found') return NO_SUBSCRIPTION();\n\n return fromMesub(error);\n }\n}\n\nconst CONFIRM = {\n cancel: 'confirmCancel',\n resume: 'confirmResume',\n close: 'confirmClose',\n} as const satisfies Record<Action, string>;\n\nfunction customerParam(asked: Asked): Customer {\n if (asked.kind === 'wallet') return { wallet: asked.value };\n\n return asked.kind === 'email' ? { email: asked.value } : { external_id: asked.value };\n}\n\n/**\n * Who your auth says is asking, normalised as Mesub reads it. Null for\n * nobody; a value Mesub cannot be asked about is a broken integration, thrown.\n */\nexport async function widgetCustomer<Req>(\n request: Req,\n customer: WidgetCustomer<Req>,\n): Promise<Asked | null> {\n const named = await customer(request);\n\n if (named === null || named === undefined) return null;\n\n const asked = customerOf(named);\n\n if (asked.value === '') {\n throw new TypeError(\n '`customer` returned an empty value: return null when nobody is signed in.',\n );\n }\n\n return asked;\n}\n\n/** Checked when the routes are built: without `customer` they would serve anybody. */\nexport function checkWidgetOptions<Req>(options: WidgetRoutesOptions<Req>): void {\n if (typeof options?.customer !== 'function') {\n throw new TypeError(\n 'The widget routes need `customer`: a function of the request returning who is signed in.',\n );\n }\n if (options.plans !== undefined && !options.plans.every((plan) => SLUG.test(plan))) {\n throw new TypeError('`plans` is a list of plan slugs.');\n }\n}\n"]}
1
+ {"version":3,"sources":["/home/runner/work/node-sdk/node-sdk/dist/chunk-RSN2QQUR.cjs","../src/routes.ts"],"names":["id","subscription","action"],"mappings":"AAAA;AACE;AACA;AACF,wDAA6B;AAC7B;AACA;AC6DO,IAAM,eAAA,EAAiB,GAAA,EAAK,IAAA;AAEnC,IAAM,QAAA,EAAU,CAAC,QAAA,EAAU,QAAA,EAAU,OAAO,CAAA;AAI5C,IAAM,GAAA,EAAK,uBAAA;AAEX,IAAM,KAAA,EAAO,uCAAA;AAMb,IAAM,iBAAA,EAAmB,GAAA;AAOzB,SAAS,OAAA,CAAA,EAAuB;AAC5B,EAAA,OAAO,EAAE,QAAA,EAAU,IAAA,CAAK,GAAA,CAAI,EAAA,EAAI,gBAAA,EAAkB,gBAAA,EAAkB,MAAM,CAAA;AAC9E;AAEA,SAAS,OAAA,CAAQ,MAAA,EAAgB,IAAA,EAAc,OAAA,EAAiC;AAC5E,EAAA,OAAO,EAAE,MAAA,EAAQ,IAAA,EAAM,EAAE,KAAA,EAAO,EAAE,IAAA,EAAM,QAAQ,EAAE,EAAE,CAAA;AACxD;AAEA,IAAM,UAAA,EAAY,CAAA,EAAA,GAAM,OAAA,CAAQ,GAAA,EAAK,WAAA,EAAa,eAAe,CAAA;AACjE,IAAM,gBAAA,EAAkB,CAAA,EAAA,GAAM,OAAA,CAAQ,GAAA,EAAK,wBAAA,EAA0B,uBAAuB,CAAA;AAG5F,IAAM,UAAA,EAAY,sCAAA;AAGlB,SAAS,IAAA,CAAK,KAAA,EAA2B;AACrC,EAAA,OAAO,KAAA,CAAM,QAAA,IAAY,KAAA,EAAO,UAAA,EAAY,KAAA,CAAM,OAAA;AACtD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A;AAChC,IAAA;AAG4B,IAAA;AACI,MAAA;AAChC,IAAA;AAGsB,IAAA;AACW,MAAA;AAED,MAAA;AAChC,IAAA;AAE+B,IAAA;AAEjB,IAAA;AACkB,MAAA;AAChC,IAAA;AAEsB,IAAA;AACI,IAAA;AACF,MAAA;AACxB,IAAA;AAE+B,IAAA;AAExB,IAAA;AACK,MAAA;AACc,MAAA;AAC1B,IAAA;AACY,EAAA;AACW,IAAA;AAED,IAAA;AAEA,IAAA;AAC1B,EAAA;AACJ;AAEgB;AACJ,EAAA;AACA,EAAA;AACD,EAAA;AACX;AAE+C;AACd,EAAA;AAEG,EAAA;AACpC;AAOI;AAG6B,EAAA;AAEG,EAAA;AAEF,EAAA;AAEN,EAAA;AACV,IAAA;AACN,MAAA;AACJ,IAAA;AACJ,EAAA;AAEO,EAAA;AACX;AAGwC;AACH,EAAA;AACnB,IAAA;AACN,MAAA;AACJ,IAAA;AACJ,EAAA;AACoC,EAAA;AACZ,IAAA;AACxB,EAAA;AACJ;ADrXmC;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/node-sdk/node-sdk/dist/chunk-RSN2QQUR.cjs","sourcesContent":[null,"import type { Customer, ServedAttempt } from './answer.js';\nimport type { Mesub } from './client.js';\nimport { type Asked, customerOf } from './customer.js';\nimport { MesubError } from './errors.js';\nimport type { Plan } from './plans.js';\nimport type { ServerSubscription, SubscriptionAttempt } from './subscriptions.js';\nimport type { CallOptions } from './transport.js';\n\n/**\n * The routes `@mesub/react` calls on your own server, so the browser never\n * talks to Mesub nor holds a key: a plan to show, the customer's\n * subscriptions, one of them with its payments, and each step of\n * subscribing (a fresh transaction to sign included), cancelling, resuming,\n * closing and paying a late payment now. One function, `handleWidget`; the\n * Express and Next entries only carry a request to it.\n *\n * Who is asking comes from `customer`, your own verified auth, as on the\n * guards. A subscription that is not that customer's is answered 404, the\n * same as one that does not exist.\n */\n\n/** Who is asking, from your own auth. Null when nobody is signed in, a 401. */\nexport type WidgetCustomer<Req> = (\n request: Req,\n) => Customer | string | null | undefined | Promise<Customer | string | null | undefined>;\n\nexport interface WidgetRoutesOptions<Req> {\n /** Defaults to one client built from MESUB_API_KEY. */\n client?: Mesub;\n /**\n * Who is asking, from a session you verified, never from the request\n * itself: `(req) => ({ external_id: req.user.id })`, a wallet or an email.\n * Every subscription created is tied to it, and only its own are reached.\n */\n customer: WidgetCustomer<Req>;\n /**\n * Where that customer's notices go, when `customer` is not an email:\n * `(req) => req.user.email`. Not verified by Mesub.\n */\n email?: (request: Req) => string | null | undefined | Promise<string | null | undefined>;\n /**\n * The plans the widget may subscribe to. Any plan of your project by\n * default; name them to keep one off your site.\n */\n plans?: readonly string[];\n}\n\n/** A request as the core reads it, whatever the framework. */\nexport interface WidgetRequest {\n method: string;\n /** After the mount point: `/subscriptions/sub_1/cancel`. */\n path: string;\n /** Parsed JSON, or undefined when there was none. */\n body: unknown;\n /** The request's `Content-Type`, to refuse a POST a plain form could send. */\n contentType: string | null;\n}\n\n/** What the core answers: a status and a JSON body. */\nexport interface WidgetResponse {\n status: number;\n body: unknown;\n headers?: Record<string, string>;\n}\n\n/** The most a widget request's body may weigh: a signed transaction is under 2 kB. */\nexport const MAX_BODY_BYTES = 64 * 1024;\n\nconst ACTIONS = ['cancel', 'resume', 'close'] as const;\ntype Action = (typeof ACTIONS)[number];\n\n/** An id as Mesub writes them: nothing that could rewrite the path. */\nconst ID = /^[A-Za-z0-9_-]{1,64}$/;\n/** A plan slug as Mesub writes them: with at least one letter, never a number. */\nconst SLUG = /^(?=.*[a-z])[a-z0-9]+(?:-[a-z0-9]+)*$/;\n\n/**\n * How long one widget request gives Mesub for all its reads, in milliseconds:\n * a browser is waiting, and a detail or a list makes several calls.\n */\nconst WIDGET_READ_TIME = 10_000;\n\n/**\n * How every read of one request is made, as a guard's: cut at one deadline,\n * and a 429 handed on at once, never waited out. The client's methods pass\n * their options to the transport whole, which is how these reach it.\n */\nfunction bounded(): CallOptions {\n return { deadline: Date.now() + WIDGET_READ_TIME, retryRateLimited: false };\n}\n\nfunction refusal(status: number, code: string, message: string): WidgetResponse {\n return { status, body: { error: { code, message } } };\n}\n\nconst NOT_FOUND = () => refusal(404, 'not_found', 'Nothing here.');\nconst NO_SUBSCRIPTION = () => refusal(404, 'subscription_not_found', 'No such subscription.');\n\n/** Said to the browser for an error Mesub did not word itself. */\nconst NO_ANSWER = 'Mesub could not answer this request.';\n\n/** Mesub's own words only: the transport's may name `baseUrl` or a network error. */\nfunction said(error: MesubError): string {\n return error.apiCode === null ? NO_ANSWER : error.message;\n}\n\n/**\n * Whether Mesub refused your server, not what the customer did: any 401,\n * which Mesub answers only to an API key missing, never issued or rotated\n * since (`missing_api_key`, `invalid_api_key`), or a 403 that names none of\n * Mesub's own codes, from something in front of Mesub turning your server\n * away. Handed on, a 401 reads to `@mesub/react` as \"nobody is signed in\",\n * and every visitor gets the sign-in screen: thrown instead, a broken\n * integration, for the framework to log and answer 500.\n */\nfunction brokenIntegration(error: MesubError): boolean {\n if (error.status === 401) return true;\n\n return error.status === 403 && (error.apiCode === null || error.apiCode === 'forbidden');\n}\n\n/** A Mesub refusal, handed on with its own status and code, and nothing of the key. */\nfunction fromMesub(error: MesubError): WidgetResponse {\n // No answer from Mesub, or a 2xx this SDK cannot read: a 502 of yours.\n const status = error.status === null || error.status < 400 ? 502 : error.status;\n const retry =\n error.retryAfter === null\n ? undefined\n : { 'Retry-After': String(Math.ceil(error.retryAfter / 1000)) };\n\n return {\n status,\n body: { error: { code: error.apiCode ?? error.code, message: said(error) } },\n ...(retry && { headers: retry }),\n };\n}\n\nfunction isString(value: unknown): value is string {\n return typeof value === 'string' && value !== '';\n}\n\nfunction fieldsOf(body: unknown): Record<string, unknown> | null {\n return typeof body === 'object' && body !== null && !Array.isArray(body)\n ? (body as Record<string, unknown>)\n : null;\n}\n\n/** Whether that subscription is the customer's: by the same identifier it was asked with. */\nfunction isTheirs(subscription: ServerSubscription, asked: Asked): boolean {\n if (asked.kind === 'wallet') return subscription.wallet === asked.value;\n if (asked.kind === 'external_id') return subscription.external_id === asked.value;\n\n return subscription.email === asked.value;\n}\n\n/** What a browser gets of a subscription: the merchant's own id and email stay on the server. */\nfunction shown(subscription: ServerSubscription) {\n const { email: _email, external_id: _externalId, ...rest } = subscription;\n\n return rest;\n}\n\n/** `GET /subscriptions` reads pages of 100, Mesub's largest, and 5 at most. */\nconst LIST_PAGE = 100;\nconst LIST_MAX_PAGES = 5;\n\n/** What `GET /subscriptions` answers. */\nexport interface WidgetSubscriptionList {\n /** Newest first, expired checkouts included: the 500 newest at most. */\n subscriptions: Array<Omit<ServerSubscription, 'email' | 'external_id'>>;\n /** True when the customer has more than those, which are not read. */\n has_more: boolean;\n}\n\n/** One pull attempt as the browser gets it: the fields Mesub serves, and no other. */\nexport interface WidgetPayment {\n attempted_at: string;\n /** `paid`, `skipped`, `rejected` or `blocked` today; a newer one is handed on as is. */\n outcome: string;\n /** What was asked for, in the mint's smallest unit; on a paid one, what was paid. */\n amount: string;\n /**\n * That amount in dollars when it was attempted, a decimal string. Null\n * until Mesub priced it, and from a Mesub that does not say.\n */\n amount_usd: string | null;\n /**\n * Mesub's short reason, null on a paid one, as on `ServedAttempt`: snake\n * case, an open string with the `program_${number}` and\n * `solana_${number}` families.\n */\n reason: string | null;\n /** The transaction that paid. Null on every outcome but `paid`. */\n signature: string | null;\n /** A retry of a missed charge. Null from a Mesub that does not say. */\n retry: boolean | null;\n /**\n * Which retry and out of how many, as Mesub recorded them when it ran:\n * 2 and 3 for \"retry 2 / 3\". Null when it is no retry of the plan's, or\n * Mesub does not say.\n */\n retry_number: number | null;\n retries_allowed: number | null;\n /** The start of the period it was for. Null when Mesub recorded none or does not say. */\n period_start: string | null;\n}\n\n/** What `GET /subscriptions/:id` answers. */\nexport interface WidgetSubscriptionDetail {\n subscription: Omit<ServerSubscription, 'email' | 'external_id'>;\n /** What Mesub pulls next, soonest first: one entry at most, none when nothing is due. */\n upcoming: WidgetUpcoming[];\n /**\n * This subscription's own pull attempts, newest first: the first page,\n * twenty at most, so not always its full history. Null when they could\n * not be read: `payments_error` says why.\n */\n payments: WidgetPayment[] | null;\n /**\n * What it paid since it began, counted by Mesub over all its attempts,\n * not over `payments`: how many were paid, and their sum in the mint's\n * smallest unit. Null when the read failed, and from a Mesub that does\n * not serve it: never summed here.\n */\n paid: { count: number; amount: string } | null;\n /** Why `payments` is null; null otherwise. */\n payments_error: { code: string; message: string } | null;\n}\n\n/** The one pull Mesub announces next for a subscription. */\nexport interface WidgetUpcoming {\n /** `charge` at the due date of a running one, `retry` of a missed one. */\n kind: 'charge' | 'retry';\n due_at: string;\n /**\n * The plan's price in the mint's smallest unit, and as a person counts\n * it. Null when the plan could not be read, never guessed.\n */\n amount: string | null;\n amount_display: string | null;\n /**\n * The plan's amount in dollars at the latest price Mesub knows, a decimal\n * string such as `\"9.99\"`: an estimate to show beside the amount, never\n * what is charged. Null when Mesub knows no price, and when the plan could\n * not be read.\n */\n amount_usd: string | null;\n /**\n * On a `retry`, which one it will be and out of how many: 2 and 3 for\n * \"next try 2 / 3\". Null on a `charge`, and when Mesub does not say.\n */\n retry_number: number | null;\n retries_allowed: number | null;\n}\n\n/** How long the plan list read for the widget is kept. */\nconst PLAN_TTL_MS = 60_000;\n\ninterface PlanList {\n /** Shared while the request is out. */\n plans: Promise<Plan[]>;\n /** Infinity until Mesub answered. */\n until: number;\n}\n\n// Per client, so two projects never share a plan.\nconst planLists = new WeakMap<Mesub, PlanList>();\n\n/**\n * A plan for the widget routes, from the project's list: public reads must\n * not spend the API key's rate limit, so one call per TTL whatever the slugs,\n * and null with no call for a slug that is not in it. A failed read is\n * forgotten at once.\n */\nasync function planOf(client: Mesub, slug: string, read: CallOptions): Promise<Plan | null> {\n let list = planLists.get(client);\n\n if (!list || list.until <= Date.now()) {\n // Shared while in flight: bound by the first asker's deadline, as a guard's flight.\n const fresh: PlanList = { plans: client.plans.list(read), until: Infinity };\n\n list = fresh;\n planLists.set(client, fresh);\n fresh.plans.then(\n () => {\n fresh.until = Date.now() + PLAN_TTL_MS;\n },\n () => {\n if (planLists.get(client) === fresh) planLists.delete(client);\n },\n );\n }\n\n return (await list.plans).find((plan) => plan.slug === slug) ?? null;\n}\n\n/**\n * What Mesub will pull next: the next charge of a running subscription, the\n * next retry of a late one, and nothing for any other, a parked seat\n * included. One event at most: later periods are not served, so not computed.\n * On Free a late one has no retry of Mesub's, only `retry_deadline`.\n */\nasync function upcomingOf(\n client: Mesub,\n subscription: ServerSubscription,\n read: CallOptions,\n): Promise<WidgetUpcoming[]> {\n const { status, plan } = subscription;\n const next =\n status === 'active'\n ? { kind: 'charge' as const, due_at: subscription.next_charge_at }\n : status === 'unpaid'\n ? { kind: 'retry' as const, due_at: subscription.next_retry_at }\n : null;\n\n // A date on any other status is no pull Mesub will run.\n if (!next || next.due_at === null || subscription.paused) return [];\n\n let price: Pick<Plan, 'amount' | 'amount_display' | 'amount_usd'> | null = null;\n\n if (plan !== null && SLUG.test(plan)) {\n try {\n price = await planOf(client, plan, read);\n } catch (error) {\n if (!(error instanceof MesubError) || brokenIntegration(error)) throw error;\n }\n }\n\n const retry = next.kind === 'retry';\n\n return [\n {\n kind: next.kind,\n due_at: next.due_at,\n amount: price?.amount ?? null,\n amount_display: price?.amount_display ?? null,\n amount_usd: price?.amount_usd ?? null,\n // Mesub's own, never counted here; `?? null` for a subscription cached by an older SDK.\n retry_number: retry ? (subscription.next_retry_number ?? null) : null,\n retries_allowed: retry ? (subscription.retries_allowed ?? null) : null,\n },\n ];\n}\n\n/** The statuses nothing is ever pulled in: a checkout that never started. */\nconst NEVER_STARTED = ['pending', 'expired', 'failed'];\n\nfunction payment(attempt: SubscriptionAttempt): WidgetPayment {\n return {\n attempted_at: attempt.attempted_at,\n outcome: attempt.outcome,\n amount: attempt.amount,\n // `?? null` for an attempt handed by a client that predates the field.\n amount_usd: attempt.amount_usd ?? null,\n reason: attempt.reason,\n signature: attempt.signature,\n retry: attempt.retry,\n retry_number: attempt.retry_number,\n retries_allowed: attempt.retries_allowed,\n period_start: attempt.period_start,\n };\n}\n\n/** An attempt of `/v1/access`, which says nothing of retries nor periods. */\nfunction olderPayment(attempt: ServedAttempt): WidgetPayment {\n return {\n attempted_at: attempt.attempted_at,\n outcome: attempt.outcome,\n amount: attempt.amount,\n amount_usd: null,\n reason: attempt.reason,\n signature: attempt.signature,\n retry: null,\n retry_number: null,\n retries_allowed: null,\n period_start: null,\n };\n}\n\ntype Payments = Omit<WidgetSubscriptionDetail, 'subscription' | 'upcoming'>;\n\nfunction unlisted(code: string, message: string): Payments {\n return { payments: null, paid: null, payments_error: { code, message } };\n}\n\n/**\n * A subscription's own pull attempts and what it paid, from\n * `GET /v1/subscriptions/:id/attempts`. A Mesub that predates the route\n * (Mesub-io/backend#289) answers a 404 that names no code for it: its payments are then\n * read the older way, without a total.\n */\nasync function paymentsOf(\n client: Mesub,\n subscription: ServerSubscription,\n read: CallOptions,\n): Promise<Payments> {\n try {\n const page = await client.subscriptions.attempts(subscription.id, {}, read);\n\n return { payments: page.data.map(payment), paid: page.paid, payments_error: null };\n } catch (error) {\n if (!(error instanceof MesubError) || brokenIntegration(error)) throw error;\n // No such route, not no such subscription: that one names its code.\n if (error.status === 404 && error.apiCode === null) {\n return olderPaymentsOf(client, subscription, read);\n }\n\n // The subscription was read: it is answered without them, so the dialog still opens.\n return unlisted(error.apiCode ?? error.code, said(error));\n }\n}\n\n/**\n * The last pull attempts as a Mesub without the attempts route serves them:\n * through `/v1/access` only, five at most, for the subscription in force on\n * that wallet and plan, naming no id. They are this one's only when the\n * answer started when this one did. No total: five attempts are not one.\n */\nasync function olderPaymentsOf(\n client: Mesub,\n subscription: ServerSubscription,\n read: CallOptions,\n): Promise<Payments> {\n const { plan, wallet, confirmed_at: confirmedAt } = subscription;\n const listed = (payments: WidgetPayment[]): Payments => ({\n payments,\n paid: null,\n payments_error: null,\n });\n\n // Never started, so never pulled: nothing to ask.\n if (confirmedAt === null && NEVER_STARTED.includes(subscription.status)) return listed([]);\n if (plan === null || !SLUG.test(plan)) {\n return unlisted('plan_without_slug', 'Its plan has no slug to read payments by.');\n }\n\n try {\n const answer = await client.access({ wallet }, plan, { attempts: true, ...read });\n const same =\n confirmedAt !== null &&\n answer.subscribed_since !== null &&\n Date.parse(answer.subscribed_since) === Date.parse(confirmedAt);\n\n if (!same) {\n return unlisted(\n 'not_the_current_subscription',\n 'This Mesub serves payments for the current subscription of a wallet on a plan only.',\n );\n }\n\n return listed(\n (answer.attempts ?? [])\n .map(olderPayment)\n .sort((a, b) => Date.parse(b.attempted_at) - Date.parse(a.attempted_at)),\n );\n } catch (error) {\n if (!(error instanceof MesubError) || brokenIntegration(error)) throw error;\n\n return unlisted(error.apiCode ?? error.code, said(error));\n }\n}\n\n/**\n * Answers one request of the widget. `asked` is who your auth says is asking,\n * already normalised, or null for nobody; `email` their notices' address.\n *\n * Never throws for what the caller sent or what Mesub refused of the\n * customer's request: both are answered. An integration error is thrown to\n * the framework, which logs it and answers 500: Mesub refusing your API key\n * (its 401, never handed on as the customer's own) or something in front of\n * Mesub refusing your server (a 403 without Mesub's code), and anything that\n * is not a MesubError. The 401 answered here means nobody is signed in, only.\n */\nexport async function handleWidget(\n client: Mesub,\n request: WidgetRequest,\n asked: Asked | null,\n options: { email?: string | null | undefined; plans?: readonly string[] } = {},\n): Promise<WidgetResponse> {\n const segments = request.path.split('?')[0]!.split('/').filter(Boolean);\n const method = request.method.toUpperCase();\n const read = bounded();\n\n try {\n // A plan is public: the page shows its price before anybody signs in.\n if (method === 'GET' && segments.length === 2 && segments[0] === 'plans') {\n const slug = segments[1]!;\n\n if (!SLUG.test(slug) || (options.plans && !options.plans.includes(slug))) {\n return refusal(404, 'plan_not_found', 'No such plan.');\n }\n\n const plan = await planOf(client, slug, read);\n\n return plan\n ? { status: 200, body: plan }\n : refusal(404, 'plan_not_found', 'No such plan.');\n }\n\n if (segments[0] !== 'subscriptions') return NOT_FOUND();\n if (method !== 'GET' && method !== 'POST') {\n return refusal(405, 'method_not_allowed', 'GET or POST.');\n }\n if (!asked) return refusal(401, 'unauthenticated', 'Sign in first.');\n\n if (method === 'GET' && segments.length === 2) {\n const id = segments[1]!;\n\n if (!ID.test(id)) return NO_SUBSCRIPTION();\n\n // Theirs first: another customer's is not read any further.\n const subscription = await client.subscriptions.retrieve(id, read);\n if (!isTheirs(subscription, asked)) return NO_SUBSCRIPTION();\n\n const [upcoming, payments] = await Promise.all([\n upcomingOf(client, subscription, read),\n paymentsOf(client, subscription, read),\n ]);\n const detail: WidgetSubscriptionDetail = {\n subscription: shown(subscription),\n upcoming,\n ...payments,\n };\n\n return { status: 200, body: detail };\n }\n\n if (method === 'GET') {\n if (segments.length !== 1) return NOT_FOUND();\n\n const params = { ...customerParam(asked), limit: LIST_PAGE };\n let page = await client.subscriptions.list(params, read);\n const subscriptions = [...page.data];\n\n const more = () => page.has_more && page.data.length > 0;\n\n // One browser request is LIST_MAX_PAGES calls to Mesub at most.\n for (let pages = 1; more() && pages < LIST_MAX_PAGES; pages++) {\n page = await client.subscriptions.list(\n { ...params, starting_after: page.data.at(-1)!.id },\n read,\n );\n subscriptions.push(...page.data);\n }\n\n const list: WidgetSubscriptionList = {\n subscriptions: subscriptions.map(shown),\n has_more: more(),\n };\n\n return { status: 200, body: list };\n }\n\n // A JSON body cannot be sent by a plain form from another site.\n if (!request.contentType?.toLowerCase().startsWith('application/json')) {\n return refusal(415, 'unsupported_media_type', 'Send JSON.');\n }\n\n const body = fieldsOf(request.body) ?? {};\n\n if (segments.length === 1) {\n const { plan, wallet } = body;\n\n if (!isString(plan) || !SLUG.test(plan) || !isString(wallet)) {\n return refusal(400, 'invalid_request', 'A plan and a wallet are needed.');\n }\n if (options.plans && !options.plans.includes(plan)) {\n return refusal(404, 'plan_not_found', 'No such plan.');\n }\n // Named by wallet, the customer is that wallet: no other may be subscribed for them.\n if (asked.kind === 'wallet' && asked.value !== wallet) {\n return refusal(403, 'wallet_mismatch', 'Connect the wallet you signed in with.');\n }\n\n const email = asked.kind === 'email' ? asked.value : options.email;\n const created = await client.subscriptions.create({\n plan,\n wallet,\n ...(asked.kind === 'external_id' && { external_id: asked.value }),\n ...(isString(email) && { email }),\n });\n\n return { status: 201, body: created };\n }\n\n const id = segments[1]!;\n const step = segments.slice(2).join('/');\n\n if (!ID.test(id)) return NO_SUBSCRIPTION();\n\n const known = [\n 'submit',\n 'transaction',\n 'retry',\n ...ACTIONS,\n ...ACTIONS.map((action) => `${action}/confirm`),\n ];\n if (!known.includes(step)) return NOT_FOUND();\n\n // Before anything is built or confirmed: is it theirs at all.\n const subscription = await client.subscriptions.retrieve(id, read);\n if (!isTheirs(subscription, asked)) return NO_SUBSCRIPTION();\n\n if (step === 'submit') {\n const { transaction, terms_signature: termsSignature } = body;\n\n if (!isString(transaction) || !isString(termsSignature)) {\n return refusal(\n 400,\n 'invalid_request',\n 'The signed transaction and the terms signature are needed.',\n );\n }\n\n const settled = await client.subscriptions.submit(id, {\n transaction,\n terms_signature: termsSignature,\n });\n\n return { status: 201, body: { ...settled, subscription: shown(settled.subscription) } };\n }\n\n // A fresh transaction for a pending one (Mesub-io/backend#427): answered as subscribing is.\n if (step === 'transaction') {\n return { status: 201, body: await client.subscriptions.transaction(id) };\n }\n\n // Pay now (Mesub-io/backend#354): nothing to sign, the outcome comes with the pull.\n if (step === 'retry') {\n const retried = await client.subscriptions.retry(id);\n\n return { status: 202, body: { subscription: shown(retried) } };\n }\n\n const [action, confirm] = step.split('/') as [Action, 'confirm' | undefined];\n\n if (!confirm) {\n return { status: 201, body: await client.subscriptions[action](id) };\n }\n\n const { signature } = body;\n if (!isString(signature)) {\n return refusal(400, 'invalid_request', 'The signature of the transaction is needed.');\n }\n\n const confirmed = await client.subscriptions[CONFIRM[action]](id, { signature });\n\n return {\n status: 201,\n body: { ...confirmed, subscription: shown(confirmed.subscription) },\n };\n } catch (error) {\n if (!(error instanceof MesubError) || brokenIntegration(error)) throw error;\n // An unknown id is Mesub's 404, answered as ours: nothing tells the two apart.\n if (error.apiCode === 'subscription_not_found') return NO_SUBSCRIPTION();\n\n return fromMesub(error);\n }\n}\n\nconst CONFIRM = {\n cancel: 'confirmCancel',\n resume: 'confirmResume',\n close: 'confirmClose',\n} as const satisfies Record<Action, string>;\n\nfunction customerParam(asked: Asked): Customer {\n if (asked.kind === 'wallet') return { wallet: asked.value };\n\n return asked.kind === 'email' ? { email: asked.value } : { external_id: asked.value };\n}\n\n/**\n * Who your auth says is asking, normalised as Mesub reads it. Null for\n * nobody; a value Mesub cannot be asked about is a broken integration, thrown.\n */\nexport async function widgetCustomer<Req>(\n request: Req,\n customer: WidgetCustomer<Req>,\n): Promise<Asked | null> {\n const named = await customer(request);\n\n if (named === null || named === undefined) return null;\n\n const asked = customerOf(named);\n\n if (asked.value === '') {\n throw new TypeError(\n '`customer` returned an empty value: return null when nobody is signed in.',\n );\n }\n\n return asked;\n}\n\n/** Checked when the routes are built: without `customer` they would serve anybody. */\nexport function checkWidgetOptions<Req>(options: WidgetRoutesOptions<Req>): void {\n if (typeof options?.customer !== 'function') {\n throw new TypeError(\n 'The widget routes need `customer`: a function of the request returning who is signed in.',\n );\n }\n if (options.plans !== undefined && !options.plans.every((plan) => SLUG.test(plan))) {\n throw new TypeError('`plans` is a list of plan slugs.');\n }\n}\n"]}
@@ -1,7 +1,7 @@
1
1
  "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
2
2
 
3
3
 
4
- var _chunkSGSYQJYTcjs = require('./chunk-SGSYQJYT.cjs');
4
+ var _chunkBP5D5I66cjs = require('./chunk-BP5D5I66.cjs');
5
5
 
6
6
  // src/guard.ts
7
7
  var DENIAL_STATUS = {
@@ -16,7 +16,7 @@ function retryAfterOf(outcome) {
16
16
  }
17
17
  var shared;
18
18
  function defaultClient() {
19
- shared ??= new (0, _chunkSGSYQJYTcjs.Mesub)();
19
+ shared ??= new (0, _chunkBP5D5I66cjs.Mesub)();
20
20
  return shared;
21
21
  }
22
22
  function plansOf(plan, request) {
@@ -49,7 +49,7 @@ function checkCustomer(options) {
49
49
  async function askerOf(request, customer) {
50
50
  const named = await customer(request);
51
51
  if (named === null || named === void 0) return null;
52
- const asked = _chunkSGSYQJYTcjs.customerOf.call(void 0, named);
52
+ const asked = _chunkBP5D5I66cjs.customerOf.call(void 0, named);
53
53
  if (asked.value === "") {
54
54
  throw new TypeError(
55
55
  "`customer` returned an empty value: return null when nobody is signed in."
@@ -117,4 +117,4 @@ function denialOf(outcome) {
117
117
 
118
118
 
119
119
  exports.retryAfterOf = retryAfterOf; exports.defaultClient = defaultClient; exports.plansOf = plansOf; exports.checkPlan = checkPlan; exports.checkCustomer = checkCustomer; exports.askerOf = askerOf; exports.guard = guard; exports.denialBody = denialBody; exports.accessOf = accessOf; exports.denialOf = denialOf;
120
- //# sourceMappingURL=chunk-VMKI4VVA.cjs.map
120
+ //# sourceMappingURL=chunk-WNHLTJ6F.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["/home/runner/work/node-sdk/node-sdk/dist/chunk-VMKI4VVA.cjs","../src/guard.ts"],"names":[],"mappings":"AAAA;AACE;AACA;AACF,wDAA6B;AAC7B;AACA;ACiCO,IAAM,cAAA,EAA8C;AAAA,EACvD,eAAA,EAAiB,GAAA;AAAA,EACjB,SAAA,EAAW,GAAA;AAAA,EACX,WAAA,EAAa;AACjB,CAAA;AAMO,IAAM,0BAAA,EAA4B,EAAA;AAMlC,SAAS,YAAA,CAAa,OAAA,EAA4D;AACrF,EAAA,MAAM,MAAA,kBAAQ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,MAAA,EAAQ,OAAA,CAAQ,QAAA,CAAS,MAAA,CAAO,OAAO,EAAA,EAAI,CAAC;AAAA,EACjF,CAAA;AACJ;AAEO,SAAS,QAAA,CAAS,OAAA,EAAgE;AACrF,EAAA,MAAM,EAAE,SAAS,EAAA,EAAI,OAAA;AAErB,EAAA,OAAO;AAAA,IACH,MAAA,EACI,QAAA,CAAS,KAAA,IAAS,SAAA,EAAW,QAAA,CAAS,MAAA,mCAAS,OAAA,qBAAQ,QAAA,qBAAS,MAAA,6BAAQ,QAAA,UAAU,MAAA;AAAA,IACtF,QAAA;AAAA,IACA,IAAA,EAAM,OAAA,CAAQ,IAAA;AAAA,IACd,MAAA,EAAQ,OAAA,CAAQ,QAAA,CAAS,MAAA;AAAA,IACzB,KAAA,EAAO,OAAA,CAAQ,QAAA,CAAS;AAAA,EAC5B,CAAA;AACJ;AAEO,SAAS,QAAA,CAAS,OAAA,EAA4D;AACjF,EAAA,OAAO;AAAA,IACH,MAAA,EAAQ,OAAA,CAAQ,MAAA;AAAA,IAChB,MAAA,EAAQ,aAAA,CAAc,OAAA,CAAQ,MAAM,CAAA;AAAA,IACpC,MAAA,mCAAQ,OAAA,qBAAQ,QAAA,+BAAU,QAAA,UAAU;AAAA,EACxC,CAAA;AACJ;ADxJA;AACA;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,yTAAC","file":"/home/runner/work/node-sdk/node-sdk/dist/chunk-VMKI4VVA.cjs","sourcesContent":[null,"import type { AccessAnswer, Customer } from './answer.js';\nimport { type Decision, Mesub } from './client.js';\nimport { type Asked, customerOf } from './customer.js';\n\n/** Why a request was turned away, and what it answers by default. */\nexport type DenialReason = 'unauthenticated' | 'no_access' | 'unavailable';\n\nexport type GuardOutcome =\n | { allowed: true; customer: Asked; plan: string; decision: Decision }\n | { allowed: false; reason: DenialReason; decision?: Decision };\n\n/** Who is asking and what Mesub answered, as a guarded route receives it. */\nexport interface MesubAccess {\n /**\n * The wallet that pays. Asked by external id or email, the one Mesub\n * answered with; null when the answer is the outage fallback's and holds none.\n */\n wallet: string | null;\n /** Who Mesub was asked about: a wallet, your own id for them, or their email. */\n customer: Asked;\n /** The plan that let the request through: the first of the list that did. */\n plan: string;\n /** Mesub's answer for that plan. */\n answer: AccessAnswer | null;\n /** The answer came from the outage fallback. */\n stale: boolean;\n}\n\n/** A refusal, as `onDenied` receives it. */\nexport interface Denial {\n reason: DenialReason;\n /** 401, 402 or 503: what would be answered without `onDenied`. */\n status: number;\n /** Mesub's answer, for the first plan asked when there are several. */\n answer: AccessAnswer | null;\n}\n\n/** What a guard answers by default for each refusal. */\nexport const DENIAL_STATUS: Record<DenialReason, number> = {\n unauthenticated: 401,\n no_access: 402,\n unavailable: 503,\n};\n\n/**\n * Seconds a client should wait before asking again when Mesub is unreachable\n * and did not say how long itself.\n */\nexport const UNAVAILABLE_RETRY_AFTER_S = 30;\n\n/**\n * The `Retry-After` of a guard's 503, in seconds: the one Mesub sent with its\n * 429 or 503 when it sent one, `UNAVAILABLE_RETRY_AFTER_S` otherwise (#132).\n */\nexport function retryAfterOf(outcome: Extract<GuardOutcome, { allowed: false }>): string {\n const asked = outcome.decision?.retryAfter;\n\n return String(asked === undefined ? UNAVAILABLE_RETRY_AFTER_S : Math.ceil(asked / 1000));\n}\n\nlet shared: Mesub | undefined;\n\n/** The client a middleware uses when given none: built once, from MESUB_API_KEY. */\nexport function defaultClient(): Mesub {\n shared ??= new Mesub();\n\n return shared;\n}\n\n/**\n * The plan a guard asks about: one, any one of several (the first that grants\n * lets the request through), or either of those worked out per request.\n */\nexport type PlanOption<Req> =\n string | readonly string[] | ((request: Req) => string | readonly string[]);\n\n/**\n * The plans a guard asks about for that request, in order, each once. A\n * plan that is not a non-empty string, or no plan at all, is a broken\n * integration: thrown, never read as a refusal.\n */\nexport function plansOf<Req>(plan: PlanOption<Req>, request: Req): string[] {\n return checkedPlans(typeof plan === 'function' ? plan(request) : plan);\n}\n\n/**\n * Checks a fixed plan when the guard is built, so a typo fails at start-up\n * rather than on the first request. One worked out per request is checked\n * then, by `plansOf`.\n */\nexport function checkPlan<Req>(plan: PlanOption<Req>): void {\n if (typeof plan !== 'function') checkedPlans(plan);\n}\n\n/**\n * Each plan a guard asks about is one call to `/v1/access`, made for every\n * request, against the key's 1000 calls a minute. Three is what a Dev\n * project can hold; a list longer than that is more likely built from the\n * request than written by hand.\n */\nconst MAX_PLANS = 3;\n\nfunction checkedPlans(value: unknown): string[] {\n const plans: unknown[] =\n typeof value === 'string' ? [value] : Array.isArray(value) ? value : [];\n\n if (plans.length === 0 || !plans.every((plan) => typeof plan === 'string' && plan !== '')) {\n throw new TypeError('A guard needs a plan, or a list of plans, as non-empty strings.');\n }\n\n const unique = [...new Set(plans as string[])];\n\n if (unique.length > MAX_PLANS) {\n throw new TypeError(\n `A guard asks about ${MAX_PLANS} plans at most: each one is a call to Mesub on every request.`,\n );\n }\n\n return unique;\n}\n\n/**\n * Who is asking, from your own auth: `(req) => ({ external_id: req.user.id })`,\n * a wallet, or an email. Null or undefined when nobody is signed in, a 401.\n * May be async.\n *\n * It must come from a session you verified, never from the request itself (a\n * query, a body, a header the caller writes): whoever names a subscriber\n * would get their access.\n */\nexport type CustomerOption<Req> = (\n request: Req,\n) => Customer | string | null | undefined | Promise<Customer | string | null | undefined>;\n\n/** Checked when the guard is built: without `customer` it could not tell who is asking. */\nexport function checkCustomer<Req>(options: { customer: CustomerOption<Req> }): void {\n if (typeof options?.customer !== 'function') {\n throw new TypeError(\n 'A guard needs `customer`: a function of the request returning who is signed in, ' +\n 'e.g. `(req) => ({ external_id: req.user.id })`.',\n );\n }\n}\n\n/**\n * Who is asking, as `customer` names them, or null for nobody.\n *\n * A `customer` that returns something Mesub cannot be asked about (two\n * identifiers, an empty one, not a string) is a broken integration: thrown.\n */\nexport async function askerOf<Req>(\n request: Req,\n customer: CustomerOption<Req>,\n): Promise<Asked | null> {\n const named = await customer(request);\n\n if (named === null || named === undefined) return null;\n\n const asked = customerOf(named);\n\n if (asked.value === '') {\n throw new TypeError(\n '`customer` returned an empty value: return null when nobody is signed in.',\n );\n }\n\n return asked;\n}\n\n/** The customer as `decide` takes it. */\nfunction asCustomer(asked: Asked): Customer | string {\n if (asked.kind === 'wallet') return asked.value;\n\n return asked.kind === 'email' ? { email: asked.value } : { external_id: asked.value };\n}\n\n/**\n * The one decision the middlewares make: who is asking, from `askerOf`, then\n * whether they have access to one of the plans.\n *\n * - nobody is asking (`customer` returned null): `unauthenticated`\n * - the fallback of `hasAccess` otherwise, per plan, through `decide`,\n * within the client's `guardTimeout`. The plans are asked at once, so\n * several fit the same budget, and read in order: the first that grants\n * lets the request through, without waiting for the ones after it.\n * `unavailable` when none grants and Mesub failed (outage, rate limit) or\n * the budget ran out on one with nothing cached: 402 only ever means\n * Mesub said no, for every plan\n *\n * An integration error (a bad API key, an unknown plan) is thrown, unless a\n * plan before it in the list already granted.\n *\n * `plansFor` runs only once somebody is identified: a plan worked out from\n * the request never runs, nor throws, for an anonymous one.\n */\nexport async function guard(\n client: Mesub,\n asked: Asked | null,\n plansFor: () => readonly string[],\n): Promise<GuardOutcome> {\n if (!asked) return { allowed: false, reason: 'unauthenticated' };\n\n const plans = plansFor();\n const customer = asCustomer(asked);\n const pending = plans.map((plan) => client.decide(customer, plan));\n\n // The ones not read, once a plan before them grants, must not reject unhandled.\n for (const decision of pending) decision.catch(() => undefined);\n\n let first: Decision | undefined;\n let unavailable: Decision | undefined;\n\n for (const [index, next] of pending.entries()) {\n const decision = await next;\n\n if (decision.access) {\n return { allowed: true, customer: asked, plan: plans[index]!, decision };\n }\n\n first ??= decision;\n // Mesub failed or did not answer within the budget, and nothing was\n // cached for that customer and plan: not a no, an outage.\n if (decision.unavailable) unavailable ??= decision;\n }\n\n if (unavailable) return { allowed: false, reason: 'unavailable', decision: unavailable };\n\n return { allowed: false, reason: 'no_access', ...(first ? { decision: first } : {}) };\n}\n\n/** The body a refusal answers with. `status` only when there is an answer to read it from. */\nexport function denialBody(outcome: Extract<GuardOutcome, { allowed: false }>) {\n return {\n access: false,\n reason: outcome.reason,\n ...(outcome.decision?.answer ? { status: outcome.decision.answer.status } : {}),\n };\n}\n\nexport function accessOf(outcome: Extract<GuardOutcome, { allowed: true }>): MesubAccess {\n const { customer } = outcome;\n\n return {\n wallet:\n customer.kind === 'wallet' ? customer.value : (outcome.decision.answer?.wallet ?? null),\n customer,\n plan: outcome.plan,\n answer: outcome.decision.answer,\n stale: outcome.decision.stale,\n };\n}\n\nexport function denialOf(outcome: Extract<GuardOutcome, { allowed: false }>): Denial {\n return {\n reason: outcome.reason,\n status: DENIAL_STATUS[outcome.reason],\n answer: outcome.decision?.answer ?? null,\n };\n}\n"]}
1
+ {"version":3,"sources":["/home/runner/work/node-sdk/node-sdk/dist/chunk-WNHLTJ6F.cjs","../src/guard.ts"],"names":[],"mappings":"AAAA;AACE;AACA;AACF,wDAA6B;AAC7B;AACA;ACiCO,IAAM,cAAA,EAA8C;AAAA,EACvD,eAAA,EAAiB,GAAA;AAAA,EACjB,SAAA,EAAW,GAAA;AAAA,EACX,WAAA,EAAa;AACjB,CAAA;AAMO,IAAM,0BAAA,EAA4B,EAAA;AAMlC,SAAS,YAAA,CAAa,OAAA,EAA4D;AACrF,EAAA,MAAM,MAAA,kBAAQ,OAAA,mBAAQ,QAAA,6BAAU,YAAA;AAEhC,EAAA,OAAO,MAAA,CAAO,MAAA,IAAU,KAAA,EAAA,EAAY,0BAAA,EAA4B,IAAA,CAAK,IAAA,CAAK,MAAA,EAAQ,GAAI,CAAC,CAAA;AAC3F;AAEA,IAAI,MAAA;AAGG,SAAS,aAAA,CAAA,EAAuB;AACnC,EAAA,OAAA,IAAW,IAAI,4BAAA,CAAM,CAAA;AAErB,EAAA,OAAO,MAAA;AACX;AAcO,SAAS,OAAA,CAAa,IAAA,EAAuB,OAAA,EAAwB;AACxE,EAAA,OAAO,YAAA,CAAa,OAAO,KAAA,IAAS,WAAA,EAAa,IAAA,CAAK,OAAO,EAAA,EAAI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,QAAA,CAAS,MAAA;AAAA,IACzB,KAAA,EAAO,OAAA,CAAQ,QAAA,CAAS;AAAA,EAC5B,CAAA;AACJ;AAEO,SAAS,QAAA,CAAS,OAAA,EAA4D;AACjF,EAAA,OAAO;AAAA,IACH,MAAA,EAAQ,OAAA,CAAQ,MAAA;AAAA,IAChB,MAAA,EAAQ,aAAA,CAAc,OAAA,CAAQ,MAAM,CAAA;AAAA,IACpC,MAAA,mCAAQ,OAAA,qBAAQ,QAAA,+BAAU,QAAA,UAAU;AAAA,EACxC,CAAA;AACJ;ADxJA;AACA;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,yTAAC","file":"/home/runner/work/node-sdk/node-sdk/dist/chunk-WNHLTJ6F.cjs","sourcesContent":[null,"import type { AccessAnswer, Customer } from './answer.js';\nimport { type Decision, Mesub } from './client.js';\nimport { type Asked, customerOf } from './customer.js';\n\n/** Why a request was turned away, and what it answers by default. */\nexport type DenialReason = 'unauthenticated' | 'no_access' | 'unavailable';\n\nexport type GuardOutcome =\n | { allowed: true; customer: Asked; plan: string; decision: Decision }\n | { allowed: false; reason: DenialReason; decision?: Decision };\n\n/** Who is asking and what Mesub answered, as a guarded route receives it. */\nexport interface MesubAccess {\n /**\n * The wallet that pays. Asked by external id or email, the one Mesub\n * answered with; null when the answer is the outage fallback's and holds none.\n */\n wallet: string | null;\n /** Who Mesub was asked about: a wallet, your own id for them, or their email. */\n customer: Asked;\n /** The plan that let the request through: the first of the list that did. */\n plan: string;\n /** Mesub's answer for that plan. */\n answer: AccessAnswer | null;\n /** The answer came from the outage fallback. */\n stale: boolean;\n}\n\n/** A refusal, as `onDenied` receives it. */\nexport interface Denial {\n reason: DenialReason;\n /** 401, 402 or 503: what would be answered without `onDenied`. */\n status: number;\n /** Mesub's answer, for the first plan asked when there are several. */\n answer: AccessAnswer | null;\n}\n\n/** What a guard answers by default for each refusal. */\nexport const DENIAL_STATUS: Record<DenialReason, number> = {\n unauthenticated: 401,\n no_access: 402,\n unavailable: 503,\n};\n\n/**\n * Seconds a client should wait before asking again when Mesub is unreachable\n * and did not say how long itself.\n */\nexport const UNAVAILABLE_RETRY_AFTER_S = 30;\n\n/**\n * The `Retry-After` of a guard's 503, in seconds: the one Mesub sent with its\n * 429 or 503 when it sent one, `UNAVAILABLE_RETRY_AFTER_S` otherwise (#132).\n */\nexport function retryAfterOf(outcome: Extract<GuardOutcome, { allowed: false }>): string {\n const asked = outcome.decision?.retryAfter;\n\n return String(asked === undefined ? UNAVAILABLE_RETRY_AFTER_S : Math.ceil(asked / 1000));\n}\n\nlet shared: Mesub | undefined;\n\n/** The client a middleware uses when given none: built once, from MESUB_API_KEY. */\nexport function defaultClient(): Mesub {\n shared ??= new Mesub();\n\n return shared;\n}\n\n/**\n * The plan a guard asks about: one, any one of several (the first that grants\n * lets the request through), or either of those worked out per request.\n */\nexport type PlanOption<Req> =\n string | readonly string[] | ((request: Req) => string | readonly string[]);\n\n/**\n * The plans a guard asks about for that request, in order, each once. A\n * plan that is not a non-empty string, or no plan at all, is a broken\n * integration: thrown, never read as a refusal.\n */\nexport function plansOf<Req>(plan: PlanOption<Req>, request: Req): string[] {\n return checkedPlans(typeof plan === 'function' ? plan(request) : plan);\n}\n\n/**\n * Checks a fixed plan when the guard is built, so a typo fails at start-up\n * rather than on the first request. One worked out per request is checked\n * then, by `plansOf`.\n */\nexport function checkPlan<Req>(plan: PlanOption<Req>): void {\n if (typeof plan !== 'function') checkedPlans(plan);\n}\n\n/**\n * Each plan a guard asks about is one call to `/v1/access`, made for every\n * request, against the key's 1000 calls a minute. Three is what a Dev\n * project can hold; a list longer than that is more likely built from the\n * request than written by hand.\n */\nconst MAX_PLANS = 3;\n\nfunction checkedPlans(value: unknown): string[] {\n const plans: unknown[] =\n typeof value === 'string' ? [value] : Array.isArray(value) ? value : [];\n\n if (plans.length === 0 || !plans.every((plan) => typeof plan === 'string' && plan !== '')) {\n throw new TypeError('A guard needs a plan, or a list of plans, as non-empty strings.');\n }\n\n const unique = [...new Set(plans as string[])];\n\n if (unique.length > MAX_PLANS) {\n throw new TypeError(\n `A guard asks about ${MAX_PLANS} plans at most: each one is a call to Mesub on every request.`,\n );\n }\n\n return unique;\n}\n\n/**\n * Who is asking, from your own auth: `(req) => ({ external_id: req.user.id })`,\n * a wallet, or an email. Null or undefined when nobody is signed in, a 401.\n * May be async.\n *\n * It must come from a session you verified, never from the request itself (a\n * query, a body, a header the caller writes): whoever names a subscriber\n * would get their access.\n */\nexport type CustomerOption<Req> = (\n request: Req,\n) => Customer | string | null | undefined | Promise<Customer | string | null | undefined>;\n\n/** Checked when the guard is built: without `customer` it could not tell who is asking. */\nexport function checkCustomer<Req>(options: { customer: CustomerOption<Req> }): void {\n if (typeof options?.customer !== 'function') {\n throw new TypeError(\n 'A guard needs `customer`: a function of the request returning who is signed in, ' +\n 'e.g. `(req) => ({ external_id: req.user.id })`.',\n );\n }\n}\n\n/**\n * Who is asking, as `customer` names them, or null for nobody.\n *\n * A `customer` that returns something Mesub cannot be asked about (two\n * identifiers, an empty one, not a string) is a broken integration: thrown.\n */\nexport async function askerOf<Req>(\n request: Req,\n customer: CustomerOption<Req>,\n): Promise<Asked | null> {\n const named = await customer(request);\n\n if (named === null || named === undefined) return null;\n\n const asked = customerOf(named);\n\n if (asked.value === '') {\n throw new TypeError(\n '`customer` returned an empty value: return null when nobody is signed in.',\n );\n }\n\n return asked;\n}\n\n/** The customer as `decide` takes it. */\nfunction asCustomer(asked: Asked): Customer | string {\n if (asked.kind === 'wallet') return asked.value;\n\n return asked.kind === 'email' ? { email: asked.value } : { external_id: asked.value };\n}\n\n/**\n * The one decision the middlewares make: who is asking, from `askerOf`, then\n * whether they have access to one of the plans.\n *\n * - nobody is asking (`customer` returned null): `unauthenticated`\n * - the fallback of `hasAccess` otherwise, per plan, through `decide`,\n * within the client's `guardTimeout`. The plans are asked at once, so\n * several fit the same budget, and read in order: the first that grants\n * lets the request through, without waiting for the ones after it.\n * `unavailable` when none grants and Mesub failed (outage, rate limit) or\n * the budget ran out on one with nothing cached: 402 only ever means\n * Mesub said no, for every plan\n *\n * An integration error (a bad API key, an unknown plan) is thrown, unless a\n * plan before it in the list already granted.\n *\n * `plansFor` runs only once somebody is identified: a plan worked out from\n * the request never runs, nor throws, for an anonymous one.\n */\nexport async function guard(\n client: Mesub,\n asked: Asked | null,\n plansFor: () => readonly string[],\n): Promise<GuardOutcome> {\n if (!asked) return { allowed: false, reason: 'unauthenticated' };\n\n const plans = plansFor();\n const customer = asCustomer(asked);\n const pending = plans.map((plan) => client.decide(customer, plan));\n\n // The ones not read, once a plan before them grants, must not reject unhandled.\n for (const decision of pending) decision.catch(() => undefined);\n\n let first: Decision | undefined;\n let unavailable: Decision | undefined;\n\n for (const [index, next] of pending.entries()) {\n const decision = await next;\n\n if (decision.access) {\n return { allowed: true, customer: asked, plan: plans[index]!, decision };\n }\n\n first ??= decision;\n // Mesub failed or did not answer within the budget, and nothing was\n // cached for that customer and plan: not a no, an outage.\n if (decision.unavailable) unavailable ??= decision;\n }\n\n if (unavailable) return { allowed: false, reason: 'unavailable', decision: unavailable };\n\n return { allowed: false, reason: 'no_access', ...(first ? { decision: first } : {}) };\n}\n\n/** The body a refusal answers with. `status` only when there is an answer to read it from. */\nexport function denialBody(outcome: Extract<GuardOutcome, { allowed: false }>) {\n return {\n access: false,\n reason: outcome.reason,\n ...(outcome.decision?.answer ? { status: outcome.decision.answer.status } : {}),\n };\n}\n\nexport function accessOf(outcome: Extract<GuardOutcome, { allowed: true }>): MesubAccess {\n const { customer } = outcome;\n\n return {\n wallet:\n customer.kind === 'wallet' ? customer.value : (outcome.decision.answer?.wallet ?? null),\n customer,\n plan: outcome.plan,\n answer: outcome.decision.answer,\n stale: outcome.decision.stale,\n };\n}\n\nexport function denialOf(outcome: Extract<GuardOutcome, { allowed: false }>): Denial {\n return {\n reason: outcome.reason,\n status: DENIAL_STATUS[outcome.reason],\n answer: outcome.decision?.answer ?? null,\n };\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { j as ServerSubscription, B as BlockedReason, T as Transport, R as RequestOptions, w as Subscriptions, A as AccessAnswer, a as AccessList, C as Customer, b as AccessOptions } from './subscriptions-D1hE7MUc.cjs';
1
+ import { j as ServerSubscription, B as BlockedReason, T as Transport, R as RequestOptions, w as Subscriptions, A as AccessAnswer, a as AccessList, C as Customer, b as AccessOptions } from './subscriptions-B6Lin6i_.cjs';
2
2
 
3
3
  /** One cached answer, with the two moments that decide what it is still good for. */
4
4
  interface CacheEntry<T> {
@@ -198,6 +198,12 @@ interface FirstPayment {
198
198
  mint: string | null;
199
199
  /** The transaction that paid it. */
200
200
  signature: string | null;
201
+ /**
202
+ * What the receiver's account got of it: `amount` less the fee a
203
+ * Token-2022 mint withholds. Null when not known, absent from a Mesub that
204
+ * predates it.
205
+ */
206
+ amount_received?: string | null;
201
207
  }
202
208
  /**
203
209
  * `subscription.ended`: `changed_at` only on a cancellation that reached its
@@ -593,8 +599,9 @@ interface MesubOptions {
593
599
  /** API key. Defaults to `process.env.MESUB_API_KEY`. */
594
600
  apiKey?: string;
595
601
  /**
596
- * Defaults to `https://api.mesub.io`. May carry a path, e.g. behind a
597
- * proxy at `https://proxy.example.com/mesub`: every call is made under it.
602
+ * Defaults to `process.env.MESUB_BASE_URL`, then `https://api.mesub.io`.
603
+ * May carry a path, e.g. behind a proxy at
604
+ * `https://proxy.example.com/mesub`: every call is made under it.
598
605
  */
599
606
  baseUrl?: string;
600
607
  /**
@@ -1,4 +1,4 @@
1
- import { j as ServerSubscription, B as BlockedReason, T as Transport, R as RequestOptions, w as Subscriptions, A as AccessAnswer, a as AccessList, C as Customer, b as AccessOptions } from './subscriptions-D1hE7MUc.js';
1
+ import { j as ServerSubscription, B as BlockedReason, T as Transport, R as RequestOptions, w as Subscriptions, A as AccessAnswer, a as AccessList, C as Customer, b as AccessOptions } from './subscriptions-B6Lin6i_.js';
2
2
 
3
3
  /** One cached answer, with the two moments that decide what it is still good for. */
4
4
  interface CacheEntry<T> {
@@ -198,6 +198,12 @@ interface FirstPayment {
198
198
  mint: string | null;
199
199
  /** The transaction that paid it. */
200
200
  signature: string | null;
201
+ /**
202
+ * What the receiver's account got of it: `amount` less the fee a
203
+ * Token-2022 mint withholds. Null when not known, absent from a Mesub that
204
+ * predates it.
205
+ */
206
+ amount_received?: string | null;
201
207
  }
202
208
  /**
203
209
  * `subscription.ended`: `changed_at` only on a cancellation that reached its
@@ -593,8 +599,9 @@ interface MesubOptions {
593
599
  /** API key. Defaults to `process.env.MESUB_API_KEY`. */
594
600
  apiKey?: string;
595
601
  /**
596
- * Defaults to `https://api.mesub.io`. May carry a path, e.g. behind a
597
- * proxy at `https://proxy.example.com/mesub`: every call is made under it.
602
+ * Defaults to `process.env.MESUB_BASE_URL`, then `https://api.mesub.io`.
603
+ * May carry a path, e.g. behind a proxy at
604
+ * `https://proxy.example.com/mesub`: every call is made under it.
598
605
  */
599
606
  baseUrl?: string;
600
607
  /**
@@ -1,4 +1,4 @@
1
- import { j as ServerSubscription } from './subscriptions-D1hE7MUc.js';
1
+ import { j as ServerSubscription } from './subscriptions-B6Lin6i_.js';
2
2
 
3
3
  /**
4
4
  * Stable codes to branch on, one per kind of failure; `apiCode` tells the
@@ -1,4 +1,4 @@
1
- import { j as ServerSubscription } from './subscriptions-D1hE7MUc.cjs';
1
+ import { j as ServerSubscription } from './subscriptions-B6Lin6i_.cjs';
2
2
 
3
3
  /**
4
4
  * Stable codes to branch on, one per kind of failure; `apiCode` tells the
package/dist/express.cjs CHANGED
@@ -3,7 +3,7 @@
3
3
 
4
4
 
5
5
 
6
- var _chunkPCDZI7B4cjs = require('./chunk-PCDZI7B4.cjs');
6
+ var _chunkRSN2QQURcjs = require('./chunk-RSN2QQUR.cjs');
7
7
 
8
8
 
9
9
 
@@ -15,16 +15,16 @@ var _chunkPCDZI7B4cjs = require('./chunk-PCDZI7B4.cjs');
15
15
 
16
16
 
17
17
 
18
- var _chunkVMKI4VVAcjs = require('./chunk-VMKI4VVA.cjs');
18
+ var _chunkWNHLTJ6Fcjs = require('./chunk-WNHLTJ6F.cjs');
19
19
 
20
20
 
21
- var _chunkSGSYQJYTcjs = require('./chunk-SGSYQJYT.cjs');
21
+ var _chunkBP5D5I66cjs = require('./chunk-BP5D5I66.cjs');
22
22
 
23
23
  // src/express.ts
24
24
  function forNext(error) {
25
- if (!(error instanceof _chunkSGSYQJYTcjs.MesubError) || error.status === null) return error;
25
+ if (!(error instanceof _chunkBP5D5I66cjs.MesubError) || error.status === null) return error;
26
26
  if (error.status < 400 || error.status >= 500) return error;
27
- return new (0, _chunkSGSYQJYTcjs.MesubError)(error.message, {
27
+ return new (0, _chunkBP5D5I66cjs.MesubError)(error.message, {
28
28
  status: 500,
29
29
  code: error.code,
30
30
  apiCode: error.apiCode,
@@ -36,30 +36,30 @@ function forNext(error) {
36
36
  });
37
37
  }
38
38
  function requirePlan(plan, options) {
39
- _chunkVMKI4VVAcjs.checkPlan.call(void 0, plan);
40
- _chunkVMKI4VVAcjs.checkCustomer.call(void 0, options);
39
+ _chunkWNHLTJ6Fcjs.checkPlan.call(void 0, plan);
40
+ _chunkWNHLTJ6Fcjs.checkCustomer.call(void 0, options);
41
41
  return async (req, res, next) => {
42
42
  try {
43
- const client = _nullishCoalesce(options.client, () => ( _chunkVMKI4VVAcjs.defaultClient.call(void 0, )));
44
- const outcome = await _chunkVMKI4VVAcjs.guard.call(void 0,
43
+ const client = _nullishCoalesce(options.client, () => ( _chunkWNHLTJ6Fcjs.defaultClient.call(void 0, )));
44
+ const outcome = await _chunkWNHLTJ6Fcjs.guard.call(void 0,
45
45
  client,
46
- await _chunkVMKI4VVAcjs.askerOf.call(void 0, req, options.customer),
47
- () => _chunkVMKI4VVAcjs.plansOf.call(void 0, plan, req)
46
+ await _chunkWNHLTJ6Fcjs.askerOf.call(void 0, req, options.customer),
47
+ () => _chunkWNHLTJ6Fcjs.plansOf.call(void 0, plan, req)
48
48
  );
49
49
  if (outcome.allowed) {
50
- const locals = _chunkVMKI4VVAcjs.accessOf.call(void 0, outcome);
50
+ const locals = _chunkWNHLTJ6Fcjs.accessOf.call(void 0, outcome);
51
51
  res.locals["mesub"] = locals;
52
52
  return next();
53
53
  }
54
- const denial = _chunkVMKI4VVAcjs.denialOf.call(void 0, outcome);
54
+ const denial = _chunkWNHLTJ6Fcjs.denialOf.call(void 0, outcome);
55
55
  if (options.onDenied) {
56
56
  await options.onDenied(denial, req, res, next);
57
57
  return;
58
58
  }
59
59
  if (outcome.reason === "unavailable") {
60
- res.setHeader("Retry-After", _chunkVMKI4VVAcjs.retryAfterOf.call(void 0, outcome));
60
+ res.setHeader("Retry-After", _chunkWNHLTJ6Fcjs.retryAfterOf.call(void 0, outcome));
61
61
  }
62
- res.status(denial.status).json(_chunkVMKI4VVAcjs.denialBody.call(void 0, outcome));
62
+ res.status(denial.status).json(_chunkWNHLTJ6Fcjs.denialBody.call(void 0, outcome));
63
63
  } catch (error) {
64
64
  next(forNext(error));
65
65
  }
@@ -74,14 +74,14 @@ async function jsonBody(req) {
74
74
  for await (const chunk of req) {
75
75
  const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk));
76
76
  size += bytes.length;
77
- if (size > _chunkPCDZI7B4cjs.MAX_BODY_BYTES) throw new RangeError("The body is too large.");
77
+ if (size > _chunkRSN2QQURcjs.MAX_BODY_BYTES) throw new RangeError("The body is too large.");
78
78
  chunks.push(bytes);
79
79
  }
80
80
  if (size === 0) return void 0;
81
81
  return JSON.parse(Buffer.concat(chunks).toString("utf8"));
82
82
  }
83
83
  function mesubRoutes(options) {
84
- _chunkPCDZI7B4cjs.checkWidgetOptions.call(void 0, options);
84
+ _chunkRSN2QQURcjs.checkWidgetOptions.call(void 0, options);
85
85
  return async (req, res, next) => {
86
86
  try {
87
87
  let body;
@@ -98,10 +98,10 @@ function mesubRoutes(options) {
98
98
  return;
99
99
  }
100
100
  const publicRead = req.method === "GET" && req.path.startsWith("/plans/");
101
- const asked = publicRead ? null : await _chunkPCDZI7B4cjs.widgetCustomer.call(void 0, req, options.customer);
101
+ const asked = publicRead ? null : await _chunkRSN2QQURcjs.widgetCustomer.call(void 0, req, options.customer);
102
102
  const email = asked && options.email ? await options.email(req) : void 0;
103
- const answer = await _chunkPCDZI7B4cjs.handleWidget.call(void 0,
104
- _nullishCoalesce(options.client, () => ( _chunkVMKI4VVAcjs.defaultClient.call(void 0, ))),
103
+ const answer = await _chunkRSN2QQURcjs.handleWidget.call(void 0,
104
+ _nullishCoalesce(options.client, () => ( _chunkWNHLTJ6Fcjs.defaultClient.call(void 0, ))),
105
105
  {
106
106
  method: req.method,
107
107
  path: req.path,
@@ -125,5 +125,5 @@ function mesubRoutes(options) {
125
125
 
126
126
 
127
127
 
128
- exports.MesubError = _chunkSGSYQJYTcjs.MesubError; exports.mesubRoutes = mesubRoutes; exports.requirePlan = requirePlan;
128
+ exports.MesubError = _chunkBP5D5I66cjs.MesubError; exports.mesubRoutes = mesubRoutes; exports.requirePlan = requirePlan;
129
129
  //# sourceMappingURL=express.cjs.map
@@ -1,11 +1,11 @@
1
1
  import { Request, Response, NextFunction, RequestHandler } from 'express';
2
- import { M as Mesub } from './client-Dm1jamju.cjs';
3
- import { M as MesubAccess, C as CustomerOption, D as Denial, P as PlanOption } from './guard-Dhy4fI6n.cjs';
4
- export { A as Asked, a as DenialReason } from './guard-Dhy4fI6n.cjs';
5
- import { W as WidgetRoutesOptions } from './routes-DWkRFOP0.cjs';
6
- export { a as WidgetPayment, b as WidgetSubscriptionDetail, c as WidgetSubscriptionList } from './routes-DWkRFOP0.cjs';
7
- export { M as MesubError } from './errors-CtPucyOh.cjs';
8
- export { C as Customer } from './subscriptions-D1hE7MUc.cjs';
2
+ import { M as Mesub } from './client-BZB6KIGd.cjs';
3
+ import { M as MesubAccess, C as CustomerOption, D as Denial, P as PlanOption } from './guard-D4AB5HtN.cjs';
4
+ export { A as Asked, a as DenialReason } from './guard-D4AB5HtN.cjs';
5
+ import { W as WidgetRoutesOptions } from './routes-DT8EFWSl.cjs';
6
+ export { a as WidgetPayment, b as WidgetSubscriptionDetail, c as WidgetSubscriptionList } from './routes-DT8EFWSl.cjs';
7
+ export { M as MesubError } from './errors-DcLfunS-.cjs';
8
+ export { C as Customer } from './subscriptions-B6Lin6i_.cjs';
9
9
 
10
10
  /** `@mesub/node/express`: `requirePlan()`. */
11
11
 
package/dist/express.d.ts CHANGED
@@ -1,11 +1,11 @@
1
1
  import { Request, Response, NextFunction, RequestHandler } from 'express';
2
- import { M as Mesub } from './client-BQuRYSdB.js';
3
- import { M as MesubAccess, C as CustomerOption, D as Denial, P as PlanOption } from './guard-DKb6iU1z.js';
4
- export { A as Asked, a as DenialReason } from './guard-DKb6iU1z.js';
5
- import { W as WidgetRoutesOptions } from './routes-CLtZnUzl.js';
6
- export { a as WidgetPayment, b as WidgetSubscriptionDetail, c as WidgetSubscriptionList } from './routes-CLtZnUzl.js';
7
- export { M as MesubError } from './errors-DqW3DMBS.js';
8
- export { C as Customer } from './subscriptions-D1hE7MUc.js';
2
+ import { M as Mesub } from './client-Q5QhXphp.js';
3
+ import { M as MesubAccess, C as CustomerOption, D as Denial, P as PlanOption } from './guard-CaXiHMVF.js';
4
+ export { A as Asked, a as DenialReason } from './guard-CaXiHMVF.js';
5
+ import { W as WidgetRoutesOptions } from './routes-KoaD1Xsk.js';
6
+ export { a as WidgetPayment, b as WidgetSubscriptionDetail, c as WidgetSubscriptionList } from './routes-KoaD1Xsk.js';
7
+ export { M as MesubError } from './errors-BN4ZWUfM.js';
8
+ export { C as Customer } from './subscriptions-B6Lin6i_.js';
9
9
 
10
10
  /** `@mesub/node/express`: `requirePlan()`. */
11
11
 
package/dist/express.js CHANGED
@@ -3,7 +3,7 @@ import {
3
3
  checkWidgetOptions,
4
4
  handleWidget,
5
5
  widgetCustomer
6
- } from "./chunk-ELK7IBLO.js";
6
+ } from "./chunk-35MOUS4W.js";
7
7
  import {
8
8
  accessOf,
9
9
  askerOf,
@@ -15,10 +15,10 @@ import {
15
15
  guard,
16
16
  plansOf,
17
17
  retryAfterOf
18
- } from "./chunk-XDLLXY7Y.js";
18
+ } from "./chunk-6HGYY2KN.js";
19
19
  import {
20
20
  MesubError
21
- } from "./chunk-KMPBFNJE.js";
21
+ } from "./chunk-JCDJZDEJ.js";
22
22
 
23
23
  // src/express.ts
24
24
  function forNext(error) {
@@ -1,4 +1,4 @@
1
- import { C as Customer, A as AccessAnswer } from './subscriptions-D1hE7MUc.js';
1
+ import { C as Customer, A as AccessAnswer } from './subscriptions-B6Lin6i_.js';
2
2
 
3
3
  /** Who a call is about, normalised as Mesub reads it. */
4
4
  interface Asked {
@@ -1,4 +1,4 @@
1
- import { C as Customer, A as AccessAnswer } from './subscriptions-D1hE7MUc.cjs';
1
+ import { C as Customer, A as AccessAnswer } from './subscriptions-B6Lin6i_.cjs';
2
2
 
3
3
  /** Who a call is about, normalised as Mesub reads it. */
4
4
  interface Asked {
package/dist/index.cjs CHANGED
@@ -10,7 +10,7 @@
10
10
 
11
11
 
12
12
 
13
- var _chunkSGSYQJYTcjs = require('./chunk-SGSYQJYT.cjs');
13
+ var _chunkBP5D5I66cjs = require('./chunk-BP5D5I66.cjs');
14
14
 
15
15
 
16
16
 
@@ -35,5 +35,5 @@ var _chunk43Q4PNF7cjs = require('./chunk-43Q4PNF7.cjs');
35
35
 
36
36
 
37
37
 
38
- exports.ACCESS_LINE = _chunk43Q4PNF7cjs.ACCESS_LINE; exports.API_VERSION = _chunkSGSYQJYTcjs.API_VERSION; exports.API_VERSION_HEADER = _chunkSGSYQJYTcjs.API_VERSION_HEADER; exports.AccessCache = _chunkSGSYQJYTcjs.AccessCache; exports.CONFIRMATIONS = _chunk43Q4PNF7cjs.CONFIRMATIONS; exports.DEFAULT_MAX_ENTRIES = _chunkSGSYQJYTcjs.DEFAULT_MAX_ENTRIES; exports.DEFAULT_MAX_STALE_MS = _chunkSGSYQJYTcjs.DEFAULT_MAX_STALE_MS; exports.MemoryStore = _chunkSGSYQJYTcjs.MemoryStore; exports.Mesub = _chunkSGSYQJYTcjs.Mesub; exports.MesubError = _chunkSGSYQJYTcjs.MesubError; exports.MesubSubmitError = _chunkSGSYQJYTcjs.MesubSubmitError; exports.SITUATIONS = _chunk43Q4PNF7cjs.SITUATIONS; exports.VERSION = _chunkSGSYQJYTcjs.VERSION; exports.explain = _chunk43Q4PNF7cjs.explain; exports.situationOf = _chunk43Q4PNF7cjs.situationOf; exports.verifyWebhook = _chunkSGSYQJYTcjs.verifyWebhook;
38
+ exports.ACCESS_LINE = _chunk43Q4PNF7cjs.ACCESS_LINE; exports.API_VERSION = _chunkBP5D5I66cjs.API_VERSION; exports.API_VERSION_HEADER = _chunkBP5D5I66cjs.API_VERSION_HEADER; exports.AccessCache = _chunkBP5D5I66cjs.AccessCache; exports.CONFIRMATIONS = _chunk43Q4PNF7cjs.CONFIRMATIONS; exports.DEFAULT_MAX_ENTRIES = _chunkBP5D5I66cjs.DEFAULT_MAX_ENTRIES; exports.DEFAULT_MAX_STALE_MS = _chunkBP5D5I66cjs.DEFAULT_MAX_STALE_MS; exports.MemoryStore = _chunkBP5D5I66cjs.MemoryStore; exports.Mesub = _chunkBP5D5I66cjs.Mesub; exports.MesubError = _chunkBP5D5I66cjs.MesubError; exports.MesubSubmitError = _chunkBP5D5I66cjs.MesubSubmitError; exports.SITUATIONS = _chunk43Q4PNF7cjs.SITUATIONS; exports.VERSION = _chunkBP5D5I66cjs.VERSION; exports.explain = _chunk43Q4PNF7cjs.explain; exports.situationOf = _chunk43Q4PNF7cjs.situationOf; exports.verifyWebhook = _chunkBP5D5I66cjs.verifyWebhook;
39
39
  //# sourceMappingURL=index.cjs.map
package/dist/index.d.cts CHANGED
@@ -1,11 +1,11 @@
1
- import { C as CacheStore, a as CacheEntry } from './client-Dm1jamju.cjs';
2
- export { A as AccessCache, b as AccessCacheOptions, c as AccessChangedDetail, d as CachedAnswer, e as CreatedDetail, D as DEFAULT_MAX_STALE_MS, f as Decision, E as EndedDetail, g as EventList, h as EventListParams, i as EventNetwork, j as EventType, k as Events, F as FirstPayment, H as HeaderSource, M as Mesub, l as MesubEvent, m as MesubOptions, N as NoDetail, P as PaymentFailedDetail, n as Plan, o as PlanStatus, p as PlanToken, q as Plans, R as RenewalIssue, r as RenewalUpcomingDetail, s as RenewedDetail, t as Revalidating, S as StoppedDetail, u as SubscriptionAccessGrantedEvent, v as SubscriptionAccessRevokedEvent, w as SubscriptionCancelledEvent, x as SubscriptionCreatedEvent, y as SubscriptionEndedEvent, z as SubscriptionExpiredEvent, B as SubscriptionPausedEvent, G as SubscriptionPaymentFailedEvent, I as SubscriptionRenewalUpcomingEvent, J as SubscriptionRenewedEvent, K as SubscriptionResumedEvent, L as SubscriptionStoppedEvent, O as SubscriptionUnpausedEvent, T as TestEvent, V as VerifyWebhookOptions, W as WebhookBody, Q as WebhookEvent, U as WebhookEventType, X as Webhooks, Y as verifyWebhook } from './client-Dm1jamju.cjs';
3
- export { M as MesubError, a as MesubErrorCode, b as MesubErrorOptions, c as MesubSubmitError, d as MesubSubmitErrorOptions } from './errors-CtPucyOh.cjs';
4
- export { A as AccessAnswer, a as AccessList, b as AccessOptions, c as AttemptsParams, B as BlockedReason, d as ConfirmOptions, e as ConfirmParams, f as ConfirmReasonCode, g as ConfirmResult, C as Customer, E as EndReason, L as LateReason, h as ListParams, P as PaymentStatus, i as PullOutcome, R as RequestOptions, S as ServedAttempt, j as ServerSubscription, k as ServerSubscriptionList, l as ServerSubscriptionStatus, m as StopReason, n as SubmitOptions, o as SubmitParams, p as SubmitResult, q as SubscribeCosts, r as SubscribeParams, s as SubscribeTransaction, t as SubscriptionAttempt, u as SubscriptionAttemptList, v as SubscriptionStatus, w as Subscriptions, W as WalletTransaction } from './subscriptions-D1hE7MUc.cjs';
1
+ import { C as CacheStore, a as CacheEntry } from './client-BZB6KIGd.cjs';
2
+ export { A as AccessCache, b as AccessCacheOptions, c as AccessChangedDetail, d as CachedAnswer, e as CreatedDetail, D as DEFAULT_MAX_STALE_MS, f as Decision, E as EndedDetail, g as EventList, h as EventListParams, i as EventNetwork, j as EventType, k as Events, F as FirstPayment, H as HeaderSource, M as Mesub, l as MesubEvent, m as MesubOptions, N as NoDetail, P as PaymentFailedDetail, n as Plan, o as PlanStatus, p as PlanToken, q as Plans, R as RenewalIssue, r as RenewalUpcomingDetail, s as RenewedDetail, t as Revalidating, S as StoppedDetail, u as SubscriptionAccessGrantedEvent, v as SubscriptionAccessRevokedEvent, w as SubscriptionCancelledEvent, x as SubscriptionCreatedEvent, y as SubscriptionEndedEvent, z as SubscriptionExpiredEvent, B as SubscriptionPausedEvent, G as SubscriptionPaymentFailedEvent, I as SubscriptionRenewalUpcomingEvent, J as SubscriptionRenewedEvent, K as SubscriptionResumedEvent, L as SubscriptionStoppedEvent, O as SubscriptionUnpausedEvent, T as TestEvent, V as VerifyWebhookOptions, W as WebhookBody, Q as WebhookEvent, U as WebhookEventType, X as Webhooks, Y as verifyWebhook } from './client-BZB6KIGd.cjs';
3
+ export { M as MesubError, a as MesubErrorCode, b as MesubErrorOptions, c as MesubSubmitError, d as MesubSubmitErrorOptions } from './errors-DcLfunS-.cjs';
4
+ export { A as AccessAnswer, a as AccessList, b as AccessOptions, c as AttemptsParams, B as BlockedReason, d as ConfirmOptions, e as ConfirmParams, f as ConfirmReasonCode, g as ConfirmResult, C as Customer, E as EndReason, L as LateReason, h as ListParams, P as PaymentStatus, i as PullOutcome, R as RequestOptions, S as ServedAttempt, j as ServerSubscription, k as ServerSubscriptionList, l as ServerSubscriptionStatus, m as StopReason, n as SubmitOptions, o as SubmitParams, p as SubmitResult, q as SubscribeCosts, r as SubscribeParams, s as SubscribeTransaction, t as SubscriptionAttempt, u as SubscriptionAttemptList, v as SubscriptionStatus, w as Subscriptions, W as WalletTransaction } from './subscriptions-B6Lin6i_.cjs';
5
5
  export { ACCESS_LINE, CONFIRMATIONS, ConfirmationKey, ExplainOptions, Explainable, ExplainedAction, Explanation, SITUATIONS, Situation, SituationActionId, SituationActionTemplate, SituationActor, SituationKey, SituationText, explain, situationOf } from './situations.cjs';
6
6
 
7
7
  /** Kept in step with package.json by `test/version.spec.ts`. */
8
- declare const VERSION = "0.1.0";
8
+ declare const VERSION = "0.1.3";
9
9
  /**
10
10
  * The version of the Mesub API this release was written against, sent in
11
11
  * the `Mesub-Version` header of every call, so the API can change its