@nozle-js/react 0.8.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -9,9 +9,712 @@ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
9
9
 
10
10
  var React__default = /*#__PURE__*/_interopDefault(React);
11
11
 
12
- // src/provider.tsx
12
+ // src/components/portal/BillingPortal.tsx
13
+
14
+ // src/components/portal/client.ts
15
+ var BillingPortalError = class extends Error {
16
+ constructor(code) {
17
+ super(
18
+ code === "changed" ? "Your subscription changed. Review its latest details before confirming again." : code === "unauthorized" ? "Your billing session has expired. Reconnect to continue." : code === "session" ? "Could not start your billing session. Please try again." : "Could not complete this billing request. Please try again."
19
+ );
20
+ this.code = code;
21
+ this.name = "BillingPortalError";
22
+ }
23
+ code;
24
+ };
25
+ function portalClient(session) {
26
+ let endpoint;
27
+ try {
28
+ endpoint = new URL(
29
+ `${(session.apiUrl ?? "https://api.nozle.app/core").replace(/\/$/, "")}/graphql`
30
+ );
31
+ if (endpoint.username || endpoint.password || endpoint.search || endpoint.hash || endpoint.protocol !== "https:" && !(endpoint.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(endpoint.hostname)) || !session.token?.trim() || /^(sk_|pk_)/.test(session.token) || /[\r\n]/.test(session.token)) {
32
+ throw new Error();
33
+ }
34
+ } catch {
35
+ throw new BillingPortalError("session");
36
+ }
37
+ return {
38
+ async request(query, variables = {}, signal) {
39
+ const controller = new AbortController();
40
+ const abort = () => controller.abort();
41
+ if (signal?.aborted) abort();
42
+ signal?.addEventListener("abort", abort, { once: true });
43
+ const timeout = setTimeout(abort, 2e4);
44
+ try {
45
+ const response = await fetch(endpoint.href, {
46
+ method: "POST",
47
+ headers: {
48
+ "Content-Type": "application/json",
49
+ "customer-portal-token": session.token
50
+ },
51
+ body: JSON.stringify({ query, variables }),
52
+ credentials: "omit",
53
+ cache: "no-store",
54
+ redirect: "error",
55
+ referrerPolicy: "no-referrer",
56
+ signal: controller.signal
57
+ });
58
+ if ([401, 403].includes(response.status))
59
+ throw new BillingPortalError("unauthorized");
60
+ if (!response.ok) throw new BillingPortalError("request");
61
+ const body = await response.json();
62
+ if (body.errors?.length) {
63
+ const unauthorized = body.errors.some(
64
+ (error) => error.extensions?.code === "unauthorized" || error.extensions?.status === "unauthorized"
65
+ );
66
+ throw new BillingPortalError(
67
+ unauthorized ? "unauthorized" : "request"
68
+ );
69
+ }
70
+ if (!body.data || typeof body.data !== "object")
71
+ throw new BillingPortalError("request");
72
+ return body.data;
73
+ } catch (error) {
74
+ if (signal?.aborted) throw new DOMException("Aborted", "AbortError");
75
+ throw error instanceof BillingPortalError ? error : new BillingPortalError("request");
76
+ } finally {
77
+ clearTimeout(timeout);
78
+ signal?.removeEventListener("abort", abort);
79
+ }
80
+ }
81
+ };
82
+ }
83
+ function invoiceDownloadUrl(value) {
84
+ try {
85
+ const url = new URL(value);
86
+ if (url.protocol !== "https:" || url.username || url.password)
87
+ throw new Error();
88
+ url.pathname = url.pathname.replace(
89
+ "/rails/active_storage/blobs/redirect/",
90
+ "/rails/active_storage/blobs/proxy/"
91
+ );
92
+ return url.href;
93
+ } catch {
94
+ throw new BillingPortalError("request");
95
+ }
96
+ }
97
+
98
+ // src/components/portal/operations.ts
99
+ var identityQuery = `query SdkPortalIdentity {
100
+ customerPortalUser { id name firstname lastname customerType email legalName
101
+ taxIdentificationNumber currency applicableTimezone
102
+ addressLine1 addressLine2 city state zipcode country
103
+ shippingAddress { addressLine1 addressLine2 city state zipcode country }
104
+ }
105
+ customerPortalOrganization { id name }
106
+ }`;
107
+ var subscriptionsQuery = `query SdkPortalSubscriptions($page: Int) {
108
+ customerPortalSubscriptions(status: [active], limit: 20, page: $page) {
109
+ metadata { currentPage totalPages }
110
+ collection { id externalId status endingAt name currentBillingPeriodEndingAt
111
+ nextSubscription { id status plan { name } }
112
+ plan { id name invoiceDisplayName code amountCents amountCurrency interval }
113
+ }
114
+ }
115
+ }`;
116
+ var subscriptionQuery = `query SdkPortalSubscription($id: ID!) {
117
+ customerPortalSubscription(id: $id) {
118
+ id externalId status endingAt name currentBillingPeriodEndingAt
119
+ nextSubscription { id status plan { name } }
120
+ plan { id name invoiceDisplayName code amountCents amountCurrency interval }
121
+ }
122
+ }`;
123
+ var usageQuery = `query SdkPortalUsage($subscriptionId: ID!) {
124
+ customerPortalCustomerUsage(subscriptionId: $subscriptionId) {
125
+ amountCents currency fromDatetime toDatetime
126
+ chargesUsage { id units amountCents charge { id invoiceDisplayName } feature { id code name } }
127
+ }
128
+ }`;
129
+ var invoicesQuery = `query SdkPortalInvoices($page: Int, $searchTerm: String) {
130
+ customerPortalInvoices(status: [finalized], limit: 8, page: $page, searchTerm: $searchTerm) {
131
+ metadata { currentPage totalPages totalCount }
132
+ collection { id number issuingDate totalAmountCents totalDueAmountCents currency
133
+ paymentStatus paymentOverdue paymentDisputeLostAt }
134
+ }
135
+ }`;
136
+ var walletsQuery = `query SdkPortalWallets($page: Int) {
137
+ customerPortalWallets(status: active, limit: 10, page: $page) {
138
+ metadata { currentPage totalPages }
139
+ collection { id name currency balanceCents creditsBalance consumedCredits expirationAt rateAmount
140
+ paidTopUpMinAmountCents paidTopUpMaxAmountCents }
141
+ }
142
+ }`;
143
+ var updateCustomerMutation = `mutation SdkPortalUpdateCustomer($input: UpdateCustomerPortalCustomerInput!) {
144
+ updateCustomerPortalCustomer(input: $input) { id }
145
+ }`;
146
+ var downloadInvoiceMutation = `mutation SdkPortalDownloadInvoice($input: DownloadCustomerPortalInvoiceInput!) {
147
+ downloadCustomerPortalInvoice(input: $input) { id fileUrl }
148
+ }`;
149
+ var topUpMutation = `mutation SdkPortalTopUp($input: CreateCustomerPortalWalletTransactionInput!) {
150
+ createCustomerPortalWalletTransaction(input: $input) { collection { id } }
151
+ }`;
152
+
153
+ // src/components/portal/styles.ts
154
+ var portalStyles = `
155
+ .nozle-billing-portal{color:var(--nozle-portal-text,#202922);background:var(--nozle-portal-background,#fff);font:14px/1.55 system-ui,sans-serif;box-sizing:border-box;width:100%;min-width:0;padding:clamp(18px,4vw,40px);border-radius:12px}
156
+ .nozle-billing-portal *{box-sizing:border-box}
157
+ .nozle-billing-portal h2,.nozle-billing-portal h3,.nozle-billing-portal p{margin:0}
158
+ .nozle-billing-portal h2{font-size:24px;letter-spacing:-.6px;line-height:1.3}
159
+ .nozle-billing-portal h3{font-size:16px;line-height:1.4}
160
+ .nozle-billing-portal header{margin-bottom:30px}
161
+ .nozle-billing-portal section{margin-top:28px;padding-top:24px;border-top:1px solid var(--nozle-portal-border,#e6e9e5)}
162
+ .nozle-billing-portal button,.nozle-billing-portal .nzp-link{appearance:none;display:inline-flex;align-items:center;justify-content:center;font:inherit;font-weight:550;line-height:1.4;border:1px solid var(--nozle-portal-border,#dce2d9);border-radius:7px;background:var(--nozle-portal-background,#fff);color:var(--nozle-portal-text,#202922);padding:9px 14px;cursor:pointer;text-decoration:none;white-space:normal}
163
+ .nozle-billing-portal button:hover,.nozle-billing-portal .nzp-link:hover{background:var(--nozle-portal-muted-background,#f4f6f2)}
164
+ .nozle-billing-portal button:disabled{opacity:.55;cursor:wait}
165
+ .nozle-billing-portal :focus-visible{outline:2px solid var(--nozle-portal-accent,#526949);outline-offset:3px}
166
+ .nozle-billing-portal .nzp-primary{background:var(--nozle-portal-accent,#526949);border-color:var(--nozle-portal-accent,#526949);color:#fff}
167
+ .nozle-billing-portal .nzp-primary:hover{filter:brightness(.92);background:var(--nozle-portal-accent,#526949)}
168
+ .nozle-billing-portal .nzp-muted{color:var(--nozle-portal-muted,#687166);font-size:13px}
169
+ .nozle-billing-portal .nzp-row{display:flex;align-items:center;justify-content:space-between;gap:14px;flex-wrap:wrap}
170
+ .nozle-billing-portal .nzp-stack{display:grid;gap:12px;margin-top:16px}
171
+ .nozle-billing-portal .nzp-card{border:1px solid var(--nozle-portal-border,#e0e6dc);border-radius:10px;padding:20px;min-width:0}
172
+ .nozle-billing-portal .nzp-price{font-size:26px;letter-spacing:-.5px;margin:12px 0 4px}
173
+ .nozle-billing-portal .nzp-badge{display:inline-block;font-size:11px;font-weight:600;letter-spacing:.3px;border-radius:5px;background:var(--nozle-portal-muted-background,#edf3e8);padding:3px 7px}
174
+ .nozle-billing-portal .nzp-empty{border:1px dashed var(--nozle-portal-border,#dce2d9);border-radius:8px;padding:22px;text-align:center;color:var(--nozle-portal-muted,#687166);margin-top:16px}
175
+ .nozle-billing-portal .nzp-error{color:#922e25;background:#fff4f2;border:1px solid #f2d2ce;border-radius:8px;padding:14px;margin:16px 0;display:flex;gap:12px;align-items:center;flex-wrap:wrap}
176
+ .nozle-billing-portal .nzp-table{overflow-x:auto;margin-top:16px}
177
+ .nozle-billing-portal table{width:100%;border-collapse:collapse;text-align:left;font-size:13px}
178
+ .nozle-billing-portal th{font-weight:500;color:var(--nozle-portal-muted,#687166);background:var(--nozle-portal-muted-background,#f7f8f5)}
179
+ .nozle-billing-portal th,.nozle-billing-portal td{padding:12px 10px;border-bottom:1px solid var(--nozle-portal-border,#e6e9e5);white-space:nowrap}
180
+ .nozle-billing-portal label{display:grid;gap:6px;font-size:13px;font-weight:500;min-width:0}
181
+ .nozle-billing-portal input,.nozle-billing-portal select{width:100%;min-width:0;font:inherit;color:inherit;background:var(--nozle-portal-background,#fff);border:1px solid var(--nozle-portal-border,#dce2d9);border-radius:6px;padding:9px 10px}
182
+ .nozle-billing-portal .nzp-fields{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,220px),1fr));gap:16px;margin:20px 0}
183
+ .nozle-billing-portal .nzp-actions{display:flex;align-items:flex-end;gap:10px;flex-wrap:wrap;margin-top:20px}
184
+ .nozle-billing-portal dl{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,210px),1fr));gap:18px;margin:16px 0 0}
185
+ .nozle-billing-portal dt{font-size:12px;color:var(--nozle-portal-muted,#687166)}
186
+ .nozle-billing-portal dd{margin:3px 0 0;overflow-wrap:anywhere}
187
+ .nozle-billing-portal footer{margin-top:30px;text-align:center;color:var(--nozle-portal-muted,#687166);font-size:12px}
188
+ `;
189
+
190
+ // src/components/portal/timezones.ts
191
+ var portalTimezones = {
192
+ TZ_AFRICA_ALGIERS: "Africa/Algiers",
193
+ TZ_AFRICA_CAIRO: "Africa/Cairo",
194
+ TZ_AFRICA_CASABLANCA: "Africa/Casablanca",
195
+ TZ_AFRICA_HARARE: "Africa/Harare",
196
+ TZ_AFRICA_JOHANNESBURG: "Africa/Johannesburg",
197
+ TZ_AFRICA_MONROVIA: "Africa/Monrovia",
198
+ TZ_AFRICA_NAIROBI: "Africa/Nairobi",
199
+ TZ_AMERICA_ARGENTINA_BUENOS_AIRES: "America/Argentina/Buenos_Aires",
200
+ TZ_AMERICA_BOGOTA: "America/Bogota",
201
+ TZ_AMERICA_CARACAS: "America/Caracas",
202
+ TZ_AMERICA_CHICAGO: "America/Chicago",
203
+ TZ_AMERICA_CHIHUAHUA: "America/Chihuahua",
204
+ TZ_AMERICA_DENVER: "America/Denver",
205
+ TZ_AMERICA_NUUK: "America/Nuuk",
206
+ TZ_AMERICA_GUATEMALA: "America/Guatemala",
207
+ TZ_AMERICA_GUYANA: "America/Guyana",
208
+ TZ_AMERICA_HALIFAX: "America/Halifax",
209
+ TZ_AMERICA_INDIANA_INDIANAPOLIS: "America/Indiana/Indianapolis",
210
+ TZ_AMERICA_JUNEAU: "America/Juneau",
211
+ TZ_AMERICA_LA_PAZ: "America/La_Paz",
212
+ TZ_AMERICA_LIMA: "America/Lima",
213
+ TZ_AMERICA_LOS_ANGELES: "America/Los_Angeles",
214
+ TZ_AMERICA_MAZATLAN: "America/Mazatlan",
215
+ TZ_AMERICA_MEXICO_CITY: "America/Mexico_City",
216
+ TZ_AMERICA_MONTERREY: "America/Monterrey",
217
+ TZ_AMERICA_MONTEVIDEO: "America/Montevideo",
218
+ TZ_AMERICA_NEW_YORK: "America/New_York",
219
+ TZ_AMERICA_PHOENIX: "America/Phoenix",
220
+ TZ_AMERICA_PUERTO_RICO: "America/Puerto_Rico",
221
+ TZ_AMERICA_REGINA: "America/Regina",
222
+ TZ_AMERICA_SANTIAGO: "America/Santiago",
223
+ TZ_AMERICA_SAO_PAULO: "America/Sao_Paulo",
224
+ TZ_AMERICA_ST_JOHNS: "America/St_Johns",
225
+ TZ_AMERICA_TIJUANA: "America/Tijuana",
226
+ TZ_ASIA_ALMATY: "Asia/Almaty",
227
+ TZ_ASIA_BAGHDAD: "Asia/Baghdad",
228
+ TZ_ASIA_BAKU: "Asia/Baku",
229
+ TZ_ASIA_BANGKOK: "Asia/Bangkok",
230
+ TZ_ASIA_CHONGQING: "Asia/Chongqing",
231
+ TZ_ASIA_COLOMBO: "Asia/Colombo",
232
+ TZ_ASIA_DHAKA: "Asia/Dhaka",
233
+ TZ_ASIA_HONG_KONG: "Asia/Hong_Kong",
234
+ TZ_ASIA_IRKUTSK: "Asia/Irkutsk",
235
+ TZ_ASIA_JAKARTA: "Asia/Jakarta",
236
+ TZ_ASIA_JERUSALEM: "Asia/Jerusalem",
237
+ TZ_ASIA_KABUL: "Asia/Kabul",
238
+ TZ_ASIA_KAMCHATKA: "Asia/Kamchatka",
239
+ TZ_ASIA_KARACHI: "Asia/Karachi",
240
+ TZ_ASIA_KATHMANDU: "Asia/Kathmandu",
241
+ TZ_ASIA_KOLKATA: "Asia/Kolkata",
242
+ TZ_ASIA_KRASNOYARSK: "Asia/Krasnoyarsk",
243
+ TZ_ASIA_KUALA_LUMPUR: "Asia/Kuala_Lumpur",
244
+ TZ_ASIA_KUWAIT: "Asia/Kuwait",
245
+ TZ_ASIA_MAGADAN: "Asia/Magadan",
246
+ TZ_ASIA_MUSCAT: "Asia/Muscat",
247
+ TZ_ASIA_NOVOSIBIRSK: "Asia/Novosibirsk",
248
+ TZ_ASIA_YANGON: "Asia/Yangon",
249
+ TZ_ASIA_RIYADH: "Asia/Riyadh",
250
+ TZ_ASIA_SEOUL: "Asia/Seoul",
251
+ TZ_ASIA_SHANGHAI: "Asia/Shanghai",
252
+ TZ_ASIA_SINGAPORE: "Asia/Singapore",
253
+ TZ_ASIA_SREDNEKOLYMSK: "Asia/Srednekolymsk",
254
+ TZ_ASIA_TAIPEI: "Asia/Taipei",
255
+ TZ_ASIA_TASHKENT: "Asia/Tashkent",
256
+ TZ_ASIA_TBILISI: "Asia/Tbilisi",
257
+ TZ_ASIA_TEHRAN: "Asia/Tehran",
258
+ TZ_ASIA_TOKYO: "Asia/Tokyo",
259
+ TZ_ASIA_ULAANBAATAR: "Asia/Ulaanbaatar",
260
+ TZ_ASIA_URUMQI: "Asia/Urumqi",
261
+ TZ_ASIA_VLADIVOSTOK: "Asia/Vladivostok",
262
+ TZ_ASIA_YAKUTSK: "Asia/Yakutsk",
263
+ TZ_ASIA_YEKATERINBURG: "Asia/Yekaterinburg",
264
+ TZ_ASIA_YEREVAN: "Asia/Yerevan",
265
+ TZ_ATLANTIC_AZORES: "Atlantic/Azores",
266
+ TZ_ATLANTIC_CAPE_VERDE: "Atlantic/Cape_Verde",
267
+ TZ_ATLANTIC_SOUTH_GEORGIA: "Atlantic/South_Georgia",
268
+ TZ_AUSTRALIA_ADELAIDE: "Australia/Adelaide",
269
+ TZ_AUSTRALIA_BRISBANE: "Australia/Brisbane",
270
+ TZ_AUSTRALIA_CANBERRA: "Australia/Canberra",
271
+ TZ_AUSTRALIA_DARWIN: "Australia/Darwin",
272
+ TZ_AUSTRALIA_HOBART: "Australia/Hobart",
273
+ TZ_AUSTRALIA_MELBOURNE: "Australia/Melbourne",
274
+ TZ_AUSTRALIA_PERTH: "Australia/Perth",
275
+ TZ_AUSTRALIA_SYDNEY: "Australia/Sydney",
276
+ TZ_EUROPE_AMSTERDAM: "Europe/Amsterdam",
277
+ TZ_EUROPE_ATHENS: "Europe/Athens",
278
+ TZ_EUROPE_BELGRADE: "Europe/Belgrade",
279
+ TZ_EUROPE_BERLIN: "Europe/Berlin",
280
+ TZ_EUROPE_BRATISLAVA: "Europe/Bratislava",
281
+ TZ_EUROPE_BRUSSELS: "Europe/Brussels",
282
+ TZ_EUROPE_BUCHAREST: "Europe/Bucharest",
283
+ TZ_EUROPE_BUDAPEST: "Europe/Budapest",
284
+ TZ_EUROPE_COPENHAGEN: "Europe/Copenhagen",
285
+ TZ_EUROPE_DUBLIN: "Europe/Dublin",
286
+ TZ_EUROPE_HELSINKI: "Europe/Helsinki",
287
+ TZ_EUROPE_ISTANBUL: "Europe/Istanbul",
288
+ TZ_EUROPE_KALININGRAD: "Europe/Kaliningrad",
289
+ TZ_EUROPE_KYIV: "Europe/Kyiv",
290
+ TZ_EUROPE_LISBON: "Europe/Lisbon",
291
+ TZ_EUROPE_LJUBLJANA: "Europe/Ljubljana",
292
+ TZ_EUROPE_LONDON: "Europe/London",
293
+ TZ_EUROPE_MADRID: "Europe/Madrid",
294
+ TZ_EUROPE_MINSK: "Europe/Minsk",
295
+ TZ_EUROPE_MOSCOW: "Europe/Moscow",
296
+ TZ_EUROPE_PARIS: "Europe/Paris",
297
+ TZ_EUROPE_PRAGUE: "Europe/Prague",
298
+ TZ_EUROPE_RIGA: "Europe/Riga",
299
+ TZ_EUROPE_ROME: "Europe/Rome",
300
+ TZ_EUROPE_SAMARA: "Europe/Samara",
301
+ TZ_EUROPE_SARAJEVO: "Europe/Sarajevo",
302
+ TZ_EUROPE_SKOPJE: "Europe/Skopje",
303
+ TZ_EUROPE_SOFIA: "Europe/Sofia",
304
+ TZ_EUROPE_STOCKHOLM: "Europe/Stockholm",
305
+ TZ_EUROPE_TALLINN: "Europe/Tallinn",
306
+ TZ_EUROPE_VIENNA: "Europe/Vienna",
307
+ TZ_EUROPE_VILNIUS: "Europe/Vilnius",
308
+ TZ_EUROPE_VOLGOGRAD: "Europe/Volgograd",
309
+ TZ_EUROPE_WARSAW: "Europe/Warsaw",
310
+ TZ_EUROPE_ZAGREB: "Europe/Zagreb",
311
+ TZ_EUROPE_ZURICH: "Europe/Zurich",
312
+ TZ_ETC_GMT_12: "Etc/GMT+12",
313
+ TZ_PACIFIC_APIA: "Pacific/Apia",
314
+ TZ_PACIFIC_AUCKLAND: "Pacific/Auckland",
315
+ TZ_PACIFIC_CHATHAM: "Pacific/Chatham",
316
+ TZ_PACIFIC_FAKAOFO: "Pacific/Fakaofo",
317
+ TZ_PACIFIC_FIJI: "Pacific/Fiji",
318
+ TZ_PACIFIC_GUADALCANAL: "Pacific/Guadalcanal",
319
+ TZ_PACIFIC_GUAM: "Pacific/Guam",
320
+ TZ_PACIFIC_HONOLULU: "Pacific/Honolulu",
321
+ TZ_PACIFIC_MAJURO: "Pacific/Majuro",
322
+ TZ_PACIFIC_MIDWAY: "Pacific/Midway",
323
+ TZ_PACIFIC_NOUMEA: "Pacific/Noumea",
324
+ TZ_PACIFIC_PAGO_PAGO: "Pacific/Pago_Pago",
325
+ TZ_PACIFIC_PORT_MORESBY: "Pacific/Port_Moresby",
326
+ TZ_PACIFIC_TONGATAPU: "Pacific/Tongatapu",
327
+ TZ_UTC: "UTC"
328
+ };
329
+
330
+ // src/core/decimal.ts
331
+ function parseDecimal(value) {
332
+ const match = value.trim().match(/^([+-]?)(\d+)(?:\.(\d+))?$/);
333
+ if (!match) return null;
334
+ const rawInteger = match[2] ?? "0";
335
+ let firstIntegerDigit = 0;
336
+ while (firstIntegerDigit < rawInteger.length - 1 && rawInteger[firstIntegerDigit] === "0") {
337
+ firstIntegerDigit += 1;
338
+ }
339
+ const integer = rawInteger.slice(firstIntegerDigit);
340
+ const rawFraction = match[3] ?? "";
341
+ let fractionEnd = rawFraction.length;
342
+ while (fractionEnd > 0 && rawFraction[fractionEnd - 1] === "0") {
343
+ fractionEnd -= 1;
344
+ }
345
+ const fraction = rawFraction.slice(0, fractionEnd);
346
+ const zero = integer === "0" && fraction === "";
347
+ return {
348
+ sign: !zero && match[1] === "-" ? -1 : 1,
349
+ integer,
350
+ fraction
351
+ };
352
+ }
353
+ function compareDecimalStrings(left, right) {
354
+ const a = parseDecimal(left);
355
+ const b = parseDecimal(right);
356
+ if (!a || !b) throw new Error("invalid decimal value");
357
+ if (a.sign !== b.sign) return a.sign > b.sign ? 1 : -1;
358
+ let magnitude = 0;
359
+ if (a.integer.length !== b.integer.length) {
360
+ magnitude = a.integer.length > b.integer.length ? 1 : -1;
361
+ } else if (a.integer !== b.integer) {
362
+ magnitude = a.integer > b.integer ? 1 : -1;
363
+ } else {
364
+ const width = Math.max(a.fraction.length, b.fraction.length);
365
+ const aFraction = a.fraction.padEnd(width, "0");
366
+ const bFraction = b.fraction.padEnd(width, "0");
367
+ if (aFraction !== bFraction) magnitude = aFraction > bFraction ? 1 : -1;
368
+ }
369
+ return magnitude * a.sign;
370
+ }
371
+
372
+ // src/components/portal/amounts.ts
373
+ function walletAmountCents(credits, rate, currencyDigits) {
374
+ if (!/^\d{1,30}(\.\d{1,5})?$/.test(credits) || !Number.isFinite(rate) || rate <= 0)
375
+ return null;
376
+ const decimal = (value) => {
377
+ const match = /^(\d+)(?:\.(\d+))?(?:e([+-]?\d+))?$/i.exec(value);
378
+ return {
379
+ value: BigInt(match[1] + (match[2] ?? "")),
380
+ scale: (match[2]?.length ?? 0) - Number(match[3] ?? 0)
381
+ };
382
+ };
383
+ const left = decimal(credits), right = decimal(String(rate));
384
+ const coefficient = left.value * right.value;
385
+ const scale = left.scale + right.scale - currencyDigits;
386
+ if (scale <= 0) return String(coefficient * 10n ** BigInt(-scale));
387
+ const padded = String(coefficient).padStart(scale + 1, "0");
388
+ return `${padded.slice(0, -scale)}.${padded.slice(-scale)}`;
389
+ }
390
+ var styles = `
391
+ .nozle-cancellation{font:inherit;color:var(--nozle-portal-text,#202922)}
392
+ .nozle-cancellation button{font:inherit;padding:9px 14px;border:1px solid var(--nozle-portal-border,#dce2d9);border-radius:7px;background:var(--nozle-portal-background,#fff);color:inherit;cursor:pointer}
393
+ .nozle-cancellation button:disabled{opacity:.55;cursor:wait}
394
+ .nozle-cancellation :focus-visible{outline:2px solid var(--nozle-portal-accent,#526949);outline-offset:3px}
395
+ .nozle-cancellation .nzc-backdrop{position:fixed;inset:0;background:#0006;z-index:1000;display:flex;align-items:center;justify-content:center;padding:20px}
396
+ .nozle-cancellation .nzc-dialog{box-sizing:border-box;background:var(--nozle-portal-background,#fff);border:1px solid var(--nozle-portal-border,#dce2d9);border-radius:12px;padding:24px;width:100%;max-width:440px;max-height:90dvh;overflow:auto;box-shadow:0 12px 48px #0003}
397
+ .nozle-cancellation .nzc-dialog h3{margin:0 0 16px;font-size:20px}
398
+ .nozle-cancellation .nzc-dialog p{margin:12px 0;line-height:1.55}
399
+ .nozle-cancellation .nzc-buttons{display:flex;flex-wrap:wrap;justify-content:flex-end;gap:10px;margin-top:20px}
400
+ .nozle-cancellation [role=alert]{color:#922e25}
401
+ `;
402
+ function formatDate(value, locale, timezone) {
403
+ const timeZone = timezone.startsWith("TZ_") ? portalTimezones[timezone] ?? "UTC" : timezone;
404
+ return new Intl.DateTimeFormat(locale, {
405
+ dateStyle: "long",
406
+ timeZone
407
+ }).format(new Date(value));
408
+ }
409
+ function completed(operation, state) {
410
+ if (!state) return false;
411
+ return operation === "cancel" ? Boolean(state.endingAt) || ["terminated", "canceled"].includes(state.status) : state.status === "active" && !state.endingAt;
412
+ }
413
+ function CancellationControl(props) {
414
+ return /* @__PURE__ */ jsxRuntime.jsx(
415
+ CancellationFlow,
416
+ {
417
+ ...props
418
+ },
419
+ `${props.subscription.id}:${props.subscription.externalId}`
420
+ );
421
+ }
422
+ function CancellationFlow({
423
+ subscription,
424
+ actions,
425
+ refresh,
426
+ onChanged,
427
+ onError,
428
+ locale = "en-US",
429
+ timezone = "UTC",
430
+ nonce
431
+ }) {
432
+ const [open, setOpen] = React.useState(false);
433
+ const [busy, setBusy] = React.useState(false);
434
+ const [preview, setPreview] = React.useState();
435
+ const [failure, setFailure] = React.useState();
436
+ const [notice, setNotice] = React.useState("");
437
+ const [observed, setObserved] = React.useState(
438
+ subscription
439
+ );
440
+ const request = React.useRef(void 0);
441
+ const inFlight = React.useRef(null);
442
+ const trigger = React.useRef(null);
443
+ const dialog = React.useRef(null);
444
+ const titleId = React.useId();
445
+ const descriptionId = React.useId();
446
+ const active = observed?.status === "active";
447
+ const ending = observed?.endingAt;
448
+ const expired = Boolean(ending && Date.parse(ending) <= Date.now());
449
+ const operation = ending ? "uncancel" : "cancel";
450
+ React.useEffect(
451
+ () => setObserved(subscription),
452
+ [
453
+ subscription.id,
454
+ subscription.externalId,
455
+ subscription.status,
456
+ subscription.endingAt,
457
+ subscription.name,
458
+ subscription.pendingPlanName
459
+ ]
460
+ );
461
+ React.useEffect(() => () => inFlight.current?.abort(), []);
462
+ React.useEffect(() => {
463
+ if (!open) return;
464
+ dialog.current?.focus();
465
+ return () => trigger.current?.focus();
466
+ }, [open]);
467
+ function report(cause, message) {
468
+ const error = cause instanceof BillingPortalError ? cause : new BillingPortalError("request");
469
+ setFailure(error.code === "unauthorized" ? error.message : message);
470
+ onError?.(error);
471
+ }
472
+ async function run(task) {
473
+ if (inFlight.current) return;
474
+ const controller = new AbortController();
475
+ inFlight.current = controller;
476
+ setBusy(true);
477
+ let timedOut = false;
478
+ let rejectAborted = () => {
479
+ };
480
+ const aborted = new Promise((_resolve, reject) => {
481
+ rejectAborted = () => reject(new DOMException("Aborted", "AbortError"));
482
+ controller.signal.addEventListener("abort", rejectAborted, {
483
+ once: true
484
+ });
485
+ });
486
+ const timeout = setTimeout(() => {
487
+ timedOut = true;
488
+ controller.abort();
489
+ }, 3e4);
490
+ try {
491
+ await Promise.race([task(controller.signal), aborted]);
492
+ } catch (cause) {
493
+ if (timedOut)
494
+ report(
495
+ cause,
496
+ "This request timed out. Check its status before trying again."
497
+ );
498
+ } finally {
499
+ clearTimeout(timeout);
500
+ controller.signal.removeEventListener("abort", rejectAborted);
501
+ if (!controller.signal.aborted || timedOut) setBusy(false);
502
+ if (inFlight.current === controller) inFlight.current = null;
503
+ }
504
+ }
505
+ function finish(state, op) {
506
+ setObserved(state);
507
+ request.current = void 0;
508
+ setOpen(false);
509
+ setPreview(void 0);
510
+ setFailure(void 0);
511
+ setNotice(
512
+ op === "cancel" ? "Cancellation scheduled." : "Your subscription will continue to renew."
513
+ );
514
+ onChanged?.();
515
+ }
516
+ async function loadPreview() {
517
+ setOpen(true);
518
+ setFailure(void 0);
519
+ if (request.current) return;
520
+ setPreview(void 0);
521
+ await run(async (signal) => {
522
+ try {
523
+ const state = await refresh(signal);
524
+ if (signal.aborted) return;
525
+ setObserved(state);
526
+ if (!state || state.status !== "active" || Boolean(state.endingAt) !== Boolean(ending)) {
527
+ setFailure(
528
+ "Your subscription changed. Close this dialog and refresh your billing details."
529
+ );
530
+ return;
531
+ }
532
+ const result = await actions.preview({
533
+ subscriptionId: subscription.externalId,
534
+ operation,
535
+ signal
536
+ });
537
+ if (signal.aborted) return;
538
+ if (result.operation !== operation || !Number.isFinite(Date.parse(result.effectiveAt)) || result.renewalAt !== null && !Number.isFinite(Date.parse(result.renewalAt)))
539
+ throw new Error();
540
+ setPreview(result);
541
+ } catch (cause) {
542
+ if (!signal.aborted)
543
+ report(cause, "Could not load this change. Please try again.");
544
+ }
545
+ });
546
+ }
547
+ async function confirm() {
548
+ if (!preview || inFlight.current) return;
549
+ if (!request.current) {
550
+ request.current = {
551
+ operation: preview.operation,
552
+ idempotencyKey: crypto.randomUUID(),
553
+ ...preview.operation === "cancel" ? { expectedEffectiveAt: preview.effectiveAt } : {},
554
+ attempted: false,
555
+ accepted: false
556
+ };
557
+ }
558
+ setFailure(void 0);
559
+ await run(async (signal) => {
560
+ const current = request.current;
561
+ let cause;
562
+ try {
563
+ if (current.attempted) {
564
+ const state = await refresh(signal);
565
+ if (signal.aborted) return;
566
+ if (completed(current.operation, state)) {
567
+ finish(state, current.operation);
568
+ return;
569
+ }
570
+ }
571
+ if (!current.accepted) {
572
+ current.attempted = true;
573
+ await actions.apply({
574
+ subscriptionId: subscription.externalId,
575
+ operation: current.operation,
576
+ idempotencyKey: current.idempotencyKey,
577
+ expectedEffectiveAt: current.expectedEffectiveAt,
578
+ signal
579
+ });
580
+ current.accepted = true;
581
+ }
582
+ } catch (error) {
583
+ cause = error;
584
+ if (!signal.aborted && error instanceof BillingPortalError && error.code === "changed") {
585
+ request.current = void 0;
586
+ setPreview(void 0);
587
+ try {
588
+ const state = await refresh(signal);
589
+ if (signal.aborted) return;
590
+ setObserved(state);
591
+ } catch {
592
+ if (signal.aborted) return;
593
+ }
594
+ setFailure(error.message);
595
+ onError?.(error);
596
+ return;
597
+ }
598
+ }
599
+ if (signal.aborted) return;
600
+ try {
601
+ const state = await refresh(signal);
602
+ if (signal.aborted) return;
603
+ setObserved(state);
604
+ if (completed(current.operation, state)) {
605
+ finish(state, current.operation);
606
+ return;
607
+ }
608
+ } catch (error) {
609
+ cause ??= error;
610
+ }
611
+ if (!signal.aborted)
612
+ report(
613
+ cause,
614
+ "We could not confirm this change. Check its status before trying again."
615
+ );
616
+ });
617
+ }
618
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "nozle-cancellation", children: [
619
+ /* @__PURE__ */ jsxRuntime.jsx("style", { nonce, children: styles }),
620
+ notice && /* @__PURE__ */ jsxRuntime.jsx("p", { role: "status", children: notice }),
621
+ active && !expired && /* @__PURE__ */ jsxRuntime.jsx("button", { ref: trigger, type: "button", onClick: () => void loadPreview(), children: ending ? "Keep my subscription" : "Cancel subscription" }),
622
+ open && /* @__PURE__ */ jsxRuntime.jsx("div", { className: "nzc-backdrop", children: /* @__PURE__ */ jsxRuntime.jsxs(
623
+ "div",
624
+ {
625
+ className: "nzc-dialog",
626
+ ref: dialog,
627
+ role: "dialog",
628
+ "aria-modal": "true",
629
+ "aria-labelledby": titleId,
630
+ "aria-describedby": descriptionId,
631
+ tabIndex: -1,
632
+ onKeyDown: (event) => {
633
+ if (event.key === "Escape" && !busy) {
634
+ event.preventDefault();
635
+ setOpen(false);
636
+ }
637
+ if (event.key === "Tab") {
638
+ const buttons = Array.from(
639
+ dialog.current?.querySelectorAll(
640
+ "button:not(:disabled)"
641
+ ) ?? []
642
+ );
643
+ const first = buttons[0], last = buttons[buttons.length - 1];
644
+ if (!first) {
645
+ event.preventDefault();
646
+ return;
647
+ }
648
+ if (event.shiftKey && (document.activeElement === first || document.activeElement === dialog.current)) {
649
+ event.preventDefault();
650
+ last.focus();
651
+ } else if (!event.shiftKey && (document.activeElement === last || document.activeElement === dialog.current)) {
652
+ event.preventDefault();
653
+ first.focus();
654
+ }
655
+ }
656
+ },
657
+ children: [
658
+ /* @__PURE__ */ jsxRuntime.jsx("h3", { id: titleId, children: (preview?.operation ?? operation) === "cancel" ? "Cancel subscription?" : "Keep your subscription?" }),
659
+ /* @__PURE__ */ jsxRuntime.jsx("p", { id: descriptionId, children: subscription.name }),
660
+ preview && (preview.operation === "cancel" ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
661
+ /* @__PURE__ */ jsxRuntime.jsxs("p", { children: [
662
+ "If you confirm, your subscription will end on",
663
+ " ",
664
+ /* @__PURE__ */ jsxRuntime.jsx("strong", { children: formatDate(preview.effectiveAt, locale, timezone) }),
665
+ "."
666
+ ] }),
667
+ /* @__PURE__ */ jsxRuntime.jsx("p", { children: "You can keep your subscription before cancellation takes effect. Outstanding invoices and usage charges still apply." }),
668
+ observed?.pendingPlanName && /* @__PURE__ */ jsxRuntime.jsxs("p", { children: [
669
+ "Your scheduled change to ",
670
+ observed.pendingPlanName,
671
+ " will be removed. Keeping your subscription later will not restore that change."
672
+ ] })
673
+ ] }) : /* @__PURE__ */ jsxRuntime.jsxs("p", { children: [
674
+ "Your current plan will continue to renew",
675
+ preview.renewalAt ? ` on ${formatDate(preview.renewalAt, locale, timezone)}` : "",
676
+ "."
677
+ ] })),
678
+ busy && /* @__PURE__ */ jsxRuntime.jsx("p", { role: "status", children: request.current ? "Confirming subscription status\u2026" : "Loading subscription details\u2026" }),
679
+ failure && /* @__PURE__ */ jsxRuntime.jsx("p", { role: "alert", children: failure }),
680
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "nzc-buttons", children: [
681
+ /* @__PURE__ */ jsxRuntime.jsx(
682
+ "button",
683
+ {
684
+ type: "button",
685
+ disabled: busy,
686
+ onClick: () => setOpen(false),
687
+ children: "Close"
688
+ }
689
+ ),
690
+ !preview && failure && /* @__PURE__ */ jsxRuntime.jsx(
691
+ "button",
692
+ {
693
+ type: "button",
694
+ disabled: busy,
695
+ onClick: () => void loadPreview(),
696
+ children: "Try again"
697
+ }
698
+ ),
699
+ preview && /* @__PURE__ */ jsxRuntime.jsx(
700
+ "button",
701
+ {
702
+ type: "button",
703
+ disabled: busy,
704
+ onClick: () => void confirm(),
705
+ children: request.current ? "Check status / retry" : preview.operation === "cancel" ? "Confirm cancellation" : "Confirm keep subscription"
706
+ }
707
+ )
708
+ ] })
709
+ ]
710
+ }
711
+ ) })
712
+ ] });
713
+ }
13
714
  function createClient(publishableKey, baseUrl) {
14
- const base = baseUrl.replace(/\/+$/, "");
715
+ let end = baseUrl.length;
716
+ while (end > 0 && baseUrl[end - 1] === "/") end--;
717
+ const base = baseUrl.slice(0, end);
15
718
  return {
16
719
  publishableKey,
17
720
  baseUrl: base,
@@ -31,21 +734,29 @@ var BillingContext = React.createContext(null);
31
734
  function BillingProvider({
32
735
  publishableKey,
33
736
  createCheckout,
737
+ verifyCheckout,
738
+ getCheckoutStatus,
34
739
  baseUrl = "https://api.nozle.app/engine",
35
740
  children
36
741
  }) {
37
742
  if (!publishableKey.startsWith("pk_")) {
38
- throw new Error("BillingProvider publishableKey must be a publishable key (pk_)");
743
+ throw new Error(
744
+ "BillingProvider publishableKey must be a publishable key (pk_)"
745
+ );
39
746
  }
40
747
  const client = React.useMemo(
41
748
  () => createClient(publishableKey, baseUrl),
42
749
  [publishableKey, baseUrl]
43
750
  );
44
751
  const contextValue = React.useMemo(
45
- () => ({ client, createCheckout }),
46
- [client, createCheckout]
752
+ () => ({ client, createCheckout, verifyCheckout, getCheckoutStatus }),
753
+ [client, createCheckout, verifyCheckout, getCheckoutStatus]
754
+ );
755
+ return React__default.default.createElement(
756
+ BillingContext.Provider,
757
+ { value: contextValue },
758
+ children
47
759
  );
48
- return React__default.default.createElement(BillingContext.Provider, { value: contextValue }, children);
49
760
  }
50
761
  function useOptionalBillingContext() {
51
762
  return React.useContext(BillingContext);
@@ -60,91 +771,165 @@ function useBillingContext() {
60
771
  function useNozleClient() {
61
772
  return useBillingContext().client;
62
773
  }
63
- function usePlans() {
64
- const { client } = useBillingContext();
65
- const [plans, setPlans] = React.useState([]);
66
- const [isLoading, setIsLoading] = React.useState(true);
67
- React.useEffect(() => {
68
- let cancelled = false;
69
- if (!client) {
70
- setIsLoading(false);
71
- return;
774
+
775
+ // src/components/billing/razorpay-checkout.ts
776
+ var loadingScript;
777
+ function loadRazorpayScript() {
778
+ if (typeof window === "undefined")
779
+ return Promise.reject(new Error("Razorpay checkout requires a browser"));
780
+ if (window.Razorpay) return Promise.resolve();
781
+ if (loadingScript) return loadingScript;
782
+ loadingScript = new Promise((resolve, reject) => {
783
+ const existing = document.querySelector(
784
+ 'script[src="https://checkout.razorpay.com/v1/checkout.js"]'
785
+ );
786
+ const script = existing || document.createElement("script");
787
+ const finish = (error) => {
788
+ clearTimeout(timer);
789
+ script.removeEventListener("load", onLoad);
790
+ script.removeEventListener("error", onError);
791
+ if (error) {
792
+ script.remove();
793
+ reject(error);
794
+ } else {
795
+ resolve();
796
+ }
797
+ };
798
+ const onLoad = () => finish(
799
+ window.Razorpay ? void 0 : new Error("Razorpay checkout did not initialize")
800
+ );
801
+ const onError = () => finish(new Error("Failed to load Razorpay checkout"));
802
+ const timer = setTimeout(
803
+ () => finish(new Error("Razorpay checkout timed out while loading")),
804
+ 15e3
805
+ );
806
+ script.addEventListener("load", onLoad);
807
+ script.addEventListener("error", onError);
808
+ if (!existing) {
809
+ script.id = "razorpay-js";
810
+ script.src = "https://checkout.razorpay.com/v1/checkout.js";
811
+ document.body.appendChild(script);
72
812
  }
73
- void client.catalogFetch("/api/v1/plans").then(async (response) => {
74
- if (!response.ok) throw new Error(`HTTP ${response.status}`);
75
- const data = await response.json();
76
- if (!cancelled) setPlans(data.plans ?? []);
77
- }).finally(() => {
78
- if (!cancelled) setIsLoading(false);
813
+ }).catch((error) => {
814
+ loadingScript = void 0;
815
+ throw error;
816
+ });
817
+ return loadingScript;
818
+ }
819
+ function checkStatus(status, id) {
820
+ if (status.checkout_id !== id || status.provider !== "razorpay")
821
+ throw new Error("Checkout status did not match this checkout");
822
+ if (["failed", "expired", "needs_review"].includes(status.status))
823
+ throw new Error(`Checkout ${status.status.replaceAll("_", " ")}`);
824
+ }
825
+ async function waitForCheckout(id, actions, initial, phase = "confirm") {
826
+ let status = initial;
827
+ if (!status && !actions.getCheckoutStatus)
828
+ throw new Error("BillingProvider getCheckoutStatus callback is required");
829
+ for (let attempt = 0; attempt < 30; attempt++) {
830
+ status = status || await actions.getCheckoutStatus(id);
831
+ checkStatus(status, id);
832
+ if (status.status === "succeeded" && status.fulfillment_status === "succeeded" || phase === "prepare" && status.status === "awaiting_payment")
833
+ return status;
834
+ actions.onProcessing?.(status);
835
+ if (!actions.getCheckoutStatus) return status;
836
+ if (attempt < 29) {
837
+ await new Promise((resolve) => setTimeout(resolve, 1e3));
838
+ status = void 0;
839
+ }
840
+ }
841
+ return status;
842
+ }
843
+ async function openRazorpayCheckout(result, actions) {
844
+ if (!result.checkout_id || !result.key_id || !result.order_id)
845
+ throw new Error(
846
+ "Razorpay checkout requires server-issued checkout_id, key_id and order_id"
847
+ );
848
+ if (!actions.verifyCheckout)
849
+ throw new Error(
850
+ "BillingProvider verifyCheckout callback is required for Razorpay checkout"
851
+ );
852
+ await loadRazorpayScript();
853
+ await new Promise((resolve, reject) => {
854
+ let finishing = false;
855
+ const checkout = new window.Razorpay({
856
+ key: result.key_id,
857
+ order_id: result.order_id,
858
+ amount: result.amount_cents,
859
+ currency: result.currency,
860
+ ...result.recurring && {
861
+ customer_id: result.customer_id,
862
+ recurring: "1"
863
+ },
864
+ handler: (response) => {
865
+ if (finishing) return;
866
+ finishing = true;
867
+ void (async () => {
868
+ const verified = await actions.verifyCheckout(
869
+ result.checkout_id,
870
+ response
871
+ );
872
+ const status = await waitForCheckout(
873
+ result.checkout_id,
874
+ actions,
875
+ verified
876
+ );
877
+ if (status.status === "succeeded" && status.fulfillment_status === "succeeded")
878
+ actions.onSuccess?.(response.razorpay_payment_id);
879
+ else actions.onProcessing?.(status);
880
+ resolve();
881
+ })().catch(reject);
882
+ },
883
+ modal: {
884
+ ondismiss: () => {
885
+ if (!finishing) {
886
+ finishing = true;
887
+ actions.onDismiss?.();
888
+ resolve();
889
+ }
890
+ }
891
+ }
79
892
  });
80
- return () => {
81
- cancelled = true;
893
+ checkout.on("payment.failed", () => {
894
+ if (finishing) return;
895
+ finishing = true;
896
+ checkout.close();
897
+ reject(new Error("Payment failed. You can retry checkout."));
898
+ });
899
+ checkout.open();
900
+ });
901
+ }
902
+ async function resumeCheckout(result, actions) {
903
+ const status = await waitForCheckout(
904
+ result.checkout_id,
905
+ actions,
906
+ void 0,
907
+ "prepare"
908
+ );
909
+ if (status.status === "awaiting_payment") return status.checkout;
910
+ if (status.status === "succeeded" && status.fulfillment_status === "succeeded")
911
+ return {
912
+ type: "completed",
913
+ status: "succeeded",
914
+ invoice_id: status.invoice_id || void 0
82
915
  };
83
- }, [client]);
84
- return { plans, isLoading };
916
+ actions.onProcessing?.(status);
917
+ return void 0;
85
918
  }
86
919
 
87
920
  // src/components/billing/checkout-navigation.ts
88
921
  function navigateToCheckout(url, location = window.location) {
89
- location.assign(url);
90
- }
91
-
92
- // src/hooks/use-checkout.ts
93
- function useCheckout() {
94
- const { createCheckout } = useBillingContext();
95
- const [isLoading, setIsLoading] = React.useState(false);
96
- const [error, setError] = React.useState(null);
97
- const [checkout, setCheckout] = React.useState(null);
98
- const fetchClientSecret = React.useCallback(
99
- async (planCode, returnUrl) => {
100
- setIsLoading(true);
101
- setError(null);
102
- try {
103
- if (!createCheckout) {
104
- throw new Error("BillingProvider createCheckout callback is required for checkout");
105
- }
106
- const result = await createCheckout({
107
- planCode,
108
- returnUrl: returnUrl ?? window.location.href
109
- });
110
- setCheckout(result);
111
- if ("client_secret" in result || "clientSecret" in result) {
112
- const clientSecret = result.client_secret ?? result.clientSecret;
113
- if (clientSecret) return clientSecret;
114
- }
115
- if ("url" in result && result.url) {
116
- navigateToCheckout(result.url);
117
- return null;
118
- }
119
- if ("type" in result && (result.type === "completed" || result.type === "scheduled")) {
120
- return null;
121
- }
122
- throw new Error("Checkout response did not include a supported result type");
123
- } catch (cause) {
124
- const checkoutError = cause instanceof Error ? cause : new Error(String(cause));
125
- setError(checkoutError);
126
- throw checkoutError;
127
- } finally {
128
- setIsLoading(false);
129
- }
130
- },
131
- [createCheckout]
922
+ const parsed = new URL(
923
+ url,
924
+ typeof window !== "undefined" ? window.location.href : void 0
132
925
  );
133
- return { fetchClientSecret, checkout, isLoading, error };
134
- }
135
- function loadRazorpayScript() {
136
- return new Promise((resolve, reject) => {
137
- if (document.getElementById("razorpay-js")) {
138
- resolve();
139
- return;
140
- }
141
- const script = document.createElement("script");
142
- script.id = "razorpay-js";
143
- script.src = "https://checkout.razorpay.com/v1/checkout.js";
144
- script.onload = () => resolve();
145
- script.onerror = () => reject(new Error("Failed to load Razorpay.js"));
146
- document.body.appendChild(script);
147
- });
926
+ const local = ["localhost", "127.0.0.1", "[::1]"].includes(parsed.hostname);
927
+ if (parsed.protocol !== "https:" && !(parsed.protocol === "http:" && local)) {
928
+ throw new Error("Checkout URL must use HTTPS");
929
+ }
930
+ if (parsed.username || parsed.password)
931
+ throw new Error("Checkout URL must not contain credentials");
932
+ location.assign(url);
148
933
  }
149
934
  async function handleCheckoutResult(result, options) {
150
935
  if ("type" in result && result.type === "scheduled") {
@@ -156,18 +941,20 @@ async function handleCheckoutResult(result, options) {
156
941
  return;
157
942
  }
158
943
  if ("type" in result && result.type === "razorpay") {
159
- if (!options.razorpayKeyId) throw new Error("razorpayKeyId is required for Razorpay checkout");
160
- await loadRazorpayScript();
161
- const checkout = new window.Razorpay({
162
- key: options.razorpayKeyId,
163
- order_id: result.orderId,
164
- handler: (response) => options.onSuccess?.(response.razorpay_payment_id)
165
- });
166
- checkout.open();
944
+ await openRazorpayCheckout(result, options);
945
+ return;
946
+ }
947
+ if ("type" in result && result.type === "processing") {
948
+ const next = await resumeCheckout(result, options);
949
+ if (next) await handleCheckoutResult(next, options);
950
+ return;
951
+ }
952
+ if ("type" in result && result.type === "hosted") {
953
+ navigateToCheckout(result.payment_url);
167
954
  return;
168
955
  }
169
956
  if ("url" in result && result.url) {
170
- window.location.assign(result.url);
957
+ navigateToCheckout(result.url);
171
958
  return;
172
959
  }
173
960
  if ("type" in result && result.type === "stripe") {
@@ -176,7 +963,10 @@ async function handleCheckoutResult(result, options) {
176
963
  options.onStripeClientSecret(clientSecret);
177
964
  return;
178
965
  }
179
- if (clientSecret) throw new Error("onStripeClientSecret is required for embedded Stripe checkout");
966
+ if (clientSecret)
967
+ throw new Error(
968
+ "onStripeClientSecret is required for embedded Stripe checkout"
969
+ );
180
970
  throw new Error("Stripe checkout did not include a URL or client secret");
181
971
  }
182
972
  throw new Error("Unknown checkout response format");
@@ -189,30 +979,58 @@ function CheckoutButton({
189
979
  style,
190
980
  onError,
191
981
  razorpayKeyId,
982
+ registerMandate,
983
+ onProcessing,
984
+ onDismiss,
192
985
  onStripeClientSecret,
193
986
  onSuccess,
194
987
  onComplete,
195
988
  onScheduled
196
989
  }) {
197
- const { createCheckout } = useBillingContext();
990
+ const { createCheckout, verifyCheckout, getCheckoutStatus } = useBillingContext();
991
+ const attempt = React.useRef(void 0);
992
+ const inFlight = React.useRef(false);
993
+ const [processing, setProcessing] = React.useState(false);
198
994
  const [loading, setLoading] = React.useState(false);
199
995
  const [error, setError] = React.useState(null);
200
996
  async function handleClick() {
997
+ if (inFlight.current) return;
998
+ inFlight.current = true;
201
999
  setLoading(true);
1000
+ setProcessing(false);
202
1001
  setError(null);
203
1002
  try {
204
1003
  if (!createCheckout) {
205
- throw new Error("BillingProvider createCheckout callback is required for checkout");
1004
+ throw new Error(
1005
+ "BillingProvider createCheckout callback is required for checkout"
1006
+ );
206
1007
  }
1008
+ if (attempt.current?.plan !== planCode)
1009
+ attempt.current = { plan: planCode, key: crypto.randomUUID() };
207
1010
  const result = await createCheckout({
1011
+ idempotencyKey: attempt.current.key,
1012
+ ...registerMandate !== void 0 && { registerMandate },
208
1013
  planCode,
209
1014
  returnUrl: returnUrl ?? window.location.href
210
1015
  });
211
1016
  await handleCheckoutResult(result, {
212
1017
  razorpayKeyId,
1018
+ verifyCheckout,
1019
+ getCheckoutStatus,
1020
+ onProcessing: (status) => {
1021
+ setProcessing(true);
1022
+ onProcessing?.(status);
1023
+ },
1024
+ onDismiss,
213
1025
  onStripeClientSecret,
214
- onSuccess,
215
- onComplete,
1026
+ onSuccess: (id) => {
1027
+ setProcessing(false);
1028
+ onSuccess?.(id);
1029
+ },
1030
+ onComplete: (completed2) => {
1031
+ setProcessing(false);
1032
+ onComplete?.(completed2);
1033
+ },
216
1034
  onScheduled
217
1035
  });
218
1036
  } catch (cause) {
@@ -220,6 +1038,7 @@ function CheckoutButton({
220
1038
  setError(checkoutError);
221
1039
  onError?.(checkoutError);
222
1040
  } finally {
1041
+ inFlight.current = false;
223
1042
  setLoading(false);
224
1043
  }
225
1044
  }
@@ -245,9 +1064,1878 @@ function CheckoutButton({
245
1064
  "aria-busy": loading,
246
1065
  children: loading ? "Loading..." : label
247
1066
  }
248
- ),
249
- error && /* @__PURE__ */ jsxRuntime.jsx("span", { role: "alert", children: error.message })
250
- ] });
1067
+ ),
1068
+ processing && /* @__PURE__ */ jsxRuntime.jsx("span", { role: "status", children: "Payment is processing. Confirmation may take a little while." }),
1069
+ error && /* @__PURE__ */ jsxRuntime.jsx("span", { role: "alert", children: error.message })
1070
+ ] });
1071
+ }
1072
+ var CheckoutContext = React.createContext(null);
1073
+ function useCheckout() {
1074
+ const ctx = React.useContext(CheckoutContext);
1075
+ if (ctx === null) {
1076
+ throw new Error("useCheckout must be used inside a <Checkout> component");
1077
+ }
1078
+ return ctx;
1079
+ }
1080
+ function buildStripeAppearance() {
1081
+ if (typeof document === "undefined") {
1082
+ return { theme: "stripe" };
1083
+ }
1084
+ const style = getComputedStyle(document.documentElement);
1085
+ const get = (prop, fallback) => style.getPropertyValue(prop).trim() || fallback;
1086
+ return {
1087
+ theme: "stripe",
1088
+ variables: {
1089
+ colorPrimary: get("--nozle-primary", "#16a34a"),
1090
+ colorBackground: get("--nozle-background", "#f8fafc"),
1091
+ colorText: get("--nozle-foreground", "#1e293b"),
1092
+ colorDanger: get("--nozle-destructive", "#dc2626"),
1093
+ borderRadius: get("--nozle-radius", "0.5rem"),
1094
+ fontFamily: "inherit"
1095
+ }
1096
+ };
1097
+ }
1098
+ function CheckoutInner({
1099
+ submitLabel,
1100
+ onSuccess,
1101
+ onError,
1102
+ onReady,
1103
+ className,
1104
+ style,
1105
+ returnUrl,
1106
+ children
1107
+ }) {
1108
+ const stripe = reactStripeJs.useStripe();
1109
+ const elements = reactStripeJs.useElements();
1110
+ const [isProcessing, setIsProcessing] = React.useState(false);
1111
+ const [error, setError] = React.useState(null);
1112
+ const [isReady, setIsReady] = React.useState(false);
1113
+ const inFlight = React.useRef(false);
1114
+ async function confirmPayment() {
1115
+ if (!stripe || !elements || inFlight.current) return;
1116
+ inFlight.current = true;
1117
+ setIsProcessing(true);
1118
+ setError(null);
1119
+ try {
1120
+ const result = await stripe.confirmPayment({
1121
+ elements,
1122
+ confirmParams: { return_url: returnUrl ?? window.location.href },
1123
+ redirect: "if_required"
1124
+ });
1125
+ if (result.error) {
1126
+ const err = new Error(result.error.message ?? "Payment failed");
1127
+ setError(err);
1128
+ onError?.(err);
1129
+ } else if (result.paymentIntent?.status === "succeeded") {
1130
+ onSuccess?.(result.paymentIntent.id);
1131
+ }
1132
+ } catch {
1133
+ const failure = new Error(
1134
+ "Payment could not be confirmed. Check its status before retrying."
1135
+ );
1136
+ setError(failure);
1137
+ onError?.(failure);
1138
+ } finally {
1139
+ inFlight.current = false;
1140
+ setIsProcessing(false);
1141
+ }
1142
+ }
1143
+ return /* @__PURE__ */ jsxRuntime.jsx(CheckoutContext.Provider, { value: { confirmPayment, isProcessing, error }, children: /* @__PURE__ */ jsxRuntime.jsxs("div", { className, style, children: [
1144
+ /* @__PURE__ */ jsxRuntime.jsx("style", { children: `@keyframes nozle-skeleton-pulse { 0%{background-position:200% 0} 100%{background-position:-200% 0} }` }),
1145
+ !isReady && /* @__PURE__ */ jsxRuntime.jsx(
1146
+ "div",
1147
+ {
1148
+ "data-testid": "checkout-skeleton",
1149
+ style: {
1150
+ height: "200px",
1151
+ borderRadius: "var(--nozle-radius, 0.5rem)",
1152
+ background: "linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%)",
1153
+ backgroundSize: "200% 100%",
1154
+ animation: "nozle-skeleton-pulse 1.5s ease-in-out infinite"
1155
+ }
1156
+ }
1157
+ ),
1158
+ /* @__PURE__ */ jsxRuntime.jsx(
1159
+ reactStripeJs.PaymentElement,
1160
+ {
1161
+ onReady: () => {
1162
+ setIsReady(true);
1163
+ onReady?.();
1164
+ }
1165
+ }
1166
+ ),
1167
+ error !== null && /* @__PURE__ */ jsxRuntime.jsx(
1168
+ "p",
1169
+ {
1170
+ style: {
1171
+ color: "var(--nozle-destructive, #dc2626)",
1172
+ margin: "0.5rem 0 0"
1173
+ },
1174
+ children: error.message
1175
+ }
1176
+ ),
1177
+ children ?? /* @__PURE__ */ jsxRuntime.jsx(
1178
+ "button",
1179
+ {
1180
+ type: "button",
1181
+ onClick: () => void confirmPayment(),
1182
+ disabled: isProcessing || !stripe,
1183
+ "aria-busy": isProcessing,
1184
+ style: {
1185
+ padding: "0.75rem 1.5rem",
1186
+ borderRadius: "var(--nozle-radius, 0.5rem)",
1187
+ border: "none",
1188
+ background: "var(--nozle-primary, var(--primary))",
1189
+ color: "var(--nozle-primary-foreground, var(--primary-foreground))",
1190
+ cursor: isProcessing ? "not-allowed" : "pointer",
1191
+ fontWeight: 500,
1192
+ opacity: isProcessing ? 0.7 : 1,
1193
+ marginTop: "1rem",
1194
+ width: "100%"
1195
+ },
1196
+ children: isProcessing ? "Processing..." : submitLabel ?? "Pay now"
1197
+ }
1198
+ )
1199
+ ] }) });
1200
+ }
1201
+ function StripeCheckout({
1202
+ clientSecret,
1203
+ publishableKey,
1204
+ stripeAccount,
1205
+ returnUrl,
1206
+ submitLabel,
1207
+ onSuccess,
1208
+ onComplete,
1209
+ onError,
1210
+ onReady,
1211
+ className,
1212
+ style,
1213
+ children
1214
+ }) {
1215
+ const stripePromise = React.useMemo(
1216
+ () => stripeJs.loadStripe(publishableKey, stripeAccount ? { stripeAccount } : void 0),
1217
+ [publishableKey, stripeAccount]
1218
+ );
1219
+ const appearance = React.useMemo(() => buildStripeAppearance(), []);
1220
+ const embeddedOptions = React.useMemo(
1221
+ () => ({ clientSecret, onComplete }),
1222
+ [clientSecret, onComplete]
1223
+ );
1224
+ if (clientSecret.startsWith("cs_")) {
1225
+ return /* @__PURE__ */ jsxRuntime.jsx("div", { className, style, children: /* @__PURE__ */ jsxRuntime.jsx(
1226
+ reactStripeJs.EmbeddedCheckoutProvider,
1227
+ {
1228
+ stripe: stripePromise,
1229
+ options: embeddedOptions,
1230
+ children: /* @__PURE__ */ jsxRuntime.jsx(reactStripeJs.EmbeddedCheckout, {})
1231
+ }
1232
+ ) });
1233
+ }
1234
+ const options = { clientSecret, appearance };
1235
+ return /* @__PURE__ */ jsxRuntime.jsx(reactStripeJs.Elements, { stripe: stripePromise, options, children: /* @__PURE__ */ jsxRuntime.jsx(
1236
+ CheckoutInner,
1237
+ {
1238
+ submitLabel,
1239
+ onSuccess,
1240
+ onError,
1241
+ onReady,
1242
+ className,
1243
+ style,
1244
+ returnUrl,
1245
+ children
1246
+ }
1247
+ ) }, clientSecret);
1248
+ }
1249
+ function ProviderCheckout(props) {
1250
+ const billing = useOptionalBillingContext();
1251
+ const [busy, setBusy] = React.useState(false);
1252
+ const [error, setError] = React.useState(null);
1253
+ const [processing, setProcessing] = React.useState(false);
1254
+ const pay = async () => {
1255
+ if (busy) return;
1256
+ setBusy(true);
1257
+ setError(null);
1258
+ try {
1259
+ await handleCheckoutResult(props.checkout, {
1260
+ verifyCheckout: props.verifyCheckout ?? billing?.verifyCheckout,
1261
+ getCheckoutStatus: props.getCheckoutStatus ?? billing?.getCheckoutStatus,
1262
+ onDismiss: props.onDismiss,
1263
+ onSuccess: (id) => {
1264
+ setProcessing(false);
1265
+ props.onSuccess?.(id);
1266
+ props.onComplete?.();
1267
+ },
1268
+ onComplete: () => {
1269
+ setProcessing(false);
1270
+ props.onComplete?.();
1271
+ },
1272
+ onScheduled: () => props.onComplete?.(),
1273
+ onProcessing: (status) => {
1274
+ setProcessing(true);
1275
+ props.onProcessing?.(status);
1276
+ }
1277
+ });
1278
+ } catch (cause) {
1279
+ const failure = cause instanceof Error ? cause : new Error("Checkout failed");
1280
+ setError(failure);
1281
+ props.onError?.(failure);
1282
+ } finally {
1283
+ setBusy(false);
1284
+ }
1285
+ };
1286
+ if ("type" in props.checkout && props.checkout.type === "stripe" && !props.checkout.url) {
1287
+ const result = props.checkout;
1288
+ const clientSecret = result.clientSecret ?? result.client_secret;
1289
+ if (clientSecret && result.publishable_key) {
1290
+ return /* @__PURE__ */ jsxRuntime.jsx(
1291
+ StripeCheckout,
1292
+ {
1293
+ clientSecret,
1294
+ publishableKey: result.publishable_key,
1295
+ stripeAccount: result.stripe_account,
1296
+ returnUrl: props.returnUrl,
1297
+ submitLabel: props.submitLabel,
1298
+ onSuccess: props.onSuccess,
1299
+ onComplete: props.onComplete,
1300
+ onError: props.onError
1301
+ }
1302
+ );
1303
+ }
1304
+ return /* @__PURE__ */ jsxRuntime.jsx("p", { role: "alert", children: "Payment setup is incomplete. Contact support to continue." });
1305
+ }
1306
+ return /* @__PURE__ */ jsxRuntime.jsx(
1307
+ CheckoutContext.Provider,
1308
+ {
1309
+ value: { confirmPayment: pay, isProcessing: busy, error },
1310
+ children: /* @__PURE__ */ jsxRuntime.jsxs("div", { className: props.className, children: [
1311
+ /* @__PURE__ */ jsxRuntime.jsx(
1312
+ "button",
1313
+ {
1314
+ type: "button",
1315
+ disabled: busy,
1316
+ "aria-busy": busy,
1317
+ onClick: () => void pay(),
1318
+ children: busy ? "Processing\u2026" : props.submitLabel || "Pay now"
1319
+ }
1320
+ ),
1321
+ processing && /* @__PURE__ */ jsxRuntime.jsx("p", { role: "status", children: "Payment is processing. Confirmation may take a little while." }),
1322
+ error && /* @__PURE__ */ jsxRuntime.jsx("p", { role: "alert", children: error.message })
1323
+ ] })
1324
+ }
1325
+ );
1326
+ }
1327
+ function Checkout(props) {
1328
+ return "checkout" in props ? /* @__PURE__ */ jsxRuntime.jsx(ProviderCheckout, { ...props }) : /* @__PURE__ */ jsxRuntime.jsx(StripeCheckout, { ...props });
1329
+ }
1330
+ var styles2 = `
1331
+ .nozle-upgrade-modal{position:fixed;inset:0;background:#0006;display:flex;align-items:center;justify-content:center;z-index:1000;padding:20px;color:var(--nozle-portal-text,#202922);font:inherit}
1332
+ .nozle-upgrade-modal .nzu-dialog{box-sizing:border-box;background:var(--nozle-portal-background,#fff);border:1px solid var(--nozle-portal-border,#dce2d9);border-radius:12px;padding:24px;max-width:480px;width:100%;max-height:90dvh;overflow:auto;box-shadow:0 12px 48px #0003}
1333
+ .nozle-upgrade-modal h2{font-size:20px;margin:0 0 16px}
1334
+ .nozle-upgrade-modal p{line-height:1.55}
1335
+ .nozle-upgrade-modal button{font:inherit;padding:9px 14px;border:1px solid var(--nozle-portal-border,#dce2d9);border-radius:7px;background:var(--nozle-portal-background,#fff);color:inherit;cursor:pointer}
1336
+ .nozle-upgrade-modal button:disabled{opacity:.55;cursor:wait}
1337
+ .nozle-upgrade-modal :focus-visible{outline:2px solid var(--nozle-portal-accent,#526949);outline-offset:3px}
1338
+ .nozle-upgrade-modal .nzu-buttons{display:flex;flex-wrap:wrap;gap:10px;justify-content:flex-end;margin-top:20px}
1339
+ .nozle-upgrade-modal [role=alert]{color:#922e25}
1340
+ `;
1341
+ function UpgradeModal(props) {
1342
+ const billing = useOptionalBillingContext();
1343
+ const [processing, setProcessing] = React.useState(false);
1344
+ const [error, setError] = React.useState(null);
1345
+ const [confirming, setConfirming] = React.useState(false);
1346
+ const inFlight = React.useRef(false);
1347
+ const dialog = React.useRef(null);
1348
+ const titleId = React.useId();
1349
+ const busy = Boolean(props.busy || confirming);
1350
+ React.useEffect(() => {
1351
+ if (!props.isOpen) return;
1352
+ const previous = document.activeElement;
1353
+ setError(null);
1354
+ dialog.current?.focus();
1355
+ return () => {
1356
+ if (previous?.isConnected) previous.focus();
1357
+ };
1358
+ }, [props.isOpen]);
1359
+ async function handleConfirm() {
1360
+ if (inFlight.current || props.confirmDisabled || busy) return;
1361
+ inFlight.current = true;
1362
+ setConfirming(true);
1363
+ setError(null);
1364
+ try {
1365
+ if (props.onSubmit) {
1366
+ await props.onSubmit();
1367
+ } else {
1368
+ if (!billing?.createCheckout)
1369
+ throw new Error(
1370
+ "BillingProvider createCheckout callback is required for checkout"
1371
+ );
1372
+ const result = await billing.createCheckout({
1373
+ planCode: props.planCode,
1374
+ returnUrl: props.returnUrl ?? window.location.href,
1375
+ ...props.subscriptionId && { subscriptionId: props.subscriptionId },
1376
+ ...props.quoteId && { quoteId: props.quoteId },
1377
+ ...props.idempotencyKey && { idempotencyKey: props.idempotencyKey }
1378
+ });
1379
+ await handleCheckoutResult(result, {
1380
+ verifyCheckout: billing.verifyCheckout,
1381
+ getCheckoutStatus: billing.getCheckoutStatus,
1382
+ onSuccess: () => {
1383
+ setProcessing(false);
1384
+ props.onCompleted?.();
1385
+ },
1386
+ onProcessing: () => setProcessing(true),
1387
+ onStripeClientSecret: (secret) => {
1388
+ props.onStripeClientSecret?.(secret);
1389
+ props.onCheckoutStarted?.();
1390
+ },
1391
+ onComplete: () => {
1392
+ setProcessing(false);
1393
+ props.onCompleted?.();
1394
+ },
1395
+ onScheduled: () => props.onScheduled?.()
1396
+ });
1397
+ }
1398
+ props.onConfirm?.();
1399
+ } catch (cause) {
1400
+ const failure = cause instanceof Error ? cause : new Error("Checkout failed");
1401
+ setError(failure.message);
1402
+ props.onError?.(failure);
1403
+ } finally {
1404
+ inFlight.current = false;
1405
+ setConfirming(false);
1406
+ }
1407
+ }
1408
+ if (!props.isOpen) return null;
1409
+ const money2 = (value) => new Intl.NumberFormat(props.locale ?? "en-US", {
1410
+ style: "currency",
1411
+ currency: props.preview?.currency ?? "USD"
1412
+ }).format(value);
1413
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "nozle-upgrade-modal", children: [
1414
+ /* @__PURE__ */ jsxRuntime.jsx("style", { nonce: props.nonce, children: styles2 }),
1415
+ /* @__PURE__ */ jsxRuntime.jsxs(
1416
+ "div",
1417
+ {
1418
+ ref: dialog,
1419
+ className: "nzu-dialog",
1420
+ role: "dialog",
1421
+ "aria-modal": "true",
1422
+ "aria-labelledby": titleId,
1423
+ tabIndex: -1,
1424
+ "aria-busy": busy,
1425
+ onKeyDown: (event) => {
1426
+ if (event.key === "Escape" && !busy) {
1427
+ event.preventDefault();
1428
+ props.onCancel?.();
1429
+ }
1430
+ if (event.key !== "Tab") return;
1431
+ const nodes = Array.from(
1432
+ dialog.current?.querySelectorAll(
1433
+ 'button:not(:disabled),input:not(:disabled),select:not(:disabled),a[href],[tabindex="0"]'
1434
+ ) ?? []
1435
+ );
1436
+ const first = nodes[0], last = nodes[nodes.length - 1];
1437
+ if (!first) {
1438
+ event.preventDefault();
1439
+ return;
1440
+ }
1441
+ if (event.shiftKey && (document.activeElement === first || document.activeElement === dialog.current)) {
1442
+ event.preventDefault();
1443
+ last.focus();
1444
+ }
1445
+ if (!event.shiftKey && (document.activeElement === last || document.activeElement === dialog.current)) {
1446
+ event.preventDefault();
1447
+ first.focus();
1448
+ }
1449
+ },
1450
+ children: [
1451
+ /* @__PURE__ */ jsxRuntime.jsx("h2", { id: titleId, children: props.title ?? "Confirm plan change" }),
1452
+ processing && /* @__PURE__ */ jsxRuntime.jsx("p", { role: "status", children: "Payment is processing. Confirmation may take a little while." }),
1453
+ error && /* @__PURE__ */ jsxRuntime.jsx("p", { role: "alert", children: error }),
1454
+ props.preview && /* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
1455
+ props.preview.credit > 0 && /* @__PURE__ */ jsxRuntime.jsxs("p", { children: [
1456
+ "Credits applied: ",
1457
+ money2(-props.preview.credit)
1458
+ ] }),
1459
+ /* @__PURE__ */ jsxRuntime.jsxs("p", { children: [
1460
+ "New plan charge: ",
1461
+ money2(props.preview.debit)
1462
+ ] }),
1463
+ /* @__PURE__ */ jsxRuntime.jsx("p", { children: /* @__PURE__ */ jsxRuntime.jsxs("strong", { children: [
1464
+ "Due today: ",
1465
+ money2(props.preview.net)
1466
+ ] }) }),
1467
+ /* @__PURE__ */ jsxRuntime.jsxs("p", { children: [
1468
+ "Next billing date:",
1469
+ " ",
1470
+ new Date(props.preview.nextBillingDate).toLocaleDateString(
1471
+ props.locale
1472
+ ),
1473
+ "."
1474
+ ] })
1475
+ ] }),
1476
+ props.children,
1477
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "nzu-buttons", children: [
1478
+ /* @__PURE__ */ jsxRuntime.jsx("button", { type: "button", onClick: props.onCancel, disabled: busy, children: "Close" }),
1479
+ /* @__PURE__ */ jsxRuntime.jsx(
1480
+ "button",
1481
+ {
1482
+ type: "button",
1483
+ onClick: () => void handleConfirm(),
1484
+ disabled: busy || props.confirmDisabled,
1485
+ children: busy ? "Checking subscription\u2026" : props.confirmLabel ?? "Confirm"
1486
+ }
1487
+ )
1488
+ ] })
1489
+ ]
1490
+ }
1491
+ )
1492
+ ] });
1493
+ }
1494
+
1495
+ // src/components/billing/amounts.ts
1496
+ function formatMinorAmount(value, currency, locale = "en-US") {
1497
+ const raw = String(value);
1498
+ if (!/^-?\d+$/.test(raw) || typeof value === "number" && !Number.isSafeInteger(value)) {
1499
+ return "Amount unavailable";
1500
+ }
1501
+ try {
1502
+ const formatter = new Intl.NumberFormat(locale, {
1503
+ style: "currency",
1504
+ currency
1505
+ });
1506
+ const digits = formatter.resolvedOptions().maximumFractionDigits ?? 2;
1507
+ const minor = BigInt(raw);
1508
+ const absolute = minor < 0n ? -minor : minor;
1509
+ const scale = 10n ** BigInt(digits);
1510
+ const whole = absolute / scale;
1511
+ const signed = minor < 0n ? whole === 0n ? -0 : -whole : whole;
1512
+ const decimal = String(absolute % scale).padStart(digits, "0");
1513
+ const digitFormatter = new Intl.NumberFormat(locale, {
1514
+ useGrouping: false
1515
+ });
1516
+ const fraction = [...decimal].map((digit) => digitFormatter.format(Number(digit))).join("");
1517
+ return formatter.formatToParts(signed).map((part) => part.type === "fraction" ? fraction : part.value).join("");
1518
+ } catch {
1519
+ return "Amount unavailable";
1520
+ }
1521
+ }
1522
+ function formatBillingDate(value, locale = "en-US", timezone) {
1523
+ if (!value || !Number.isFinite(Date.parse(value))) return "Not available";
1524
+ try {
1525
+ return new Intl.DateTimeFormat(locale, {
1526
+ dateStyle: "medium",
1527
+ timeZone: timezone?.startsWith("TZ_") ? portalTimezones[timezone] ?? "UTC" : timezone ?? "UTC"
1528
+ }).format(new Date(value));
1529
+ } catch {
1530
+ return new Intl.DateTimeFormat(locale, {
1531
+ dateStyle: "medium",
1532
+ timeZone: "UTC"
1533
+ }).format(new Date(value));
1534
+ }
1535
+ }
1536
+ var styles3 = `
1537
+ .nozle-plan-change{font:inherit;color:var(--nozle-portal-text,#202922);margin-top:12px}
1538
+ .nozle-plan-change button{font:inherit;padding:9px 14px;border:1px solid var(--nozle-portal-border,#dce2d9);border-radius:7px;background:var(--nozle-portal-background,#fff);color:inherit;cursor:pointer}
1539
+ .nozle-plan-change button:disabled{opacity:.55;cursor:wait}
1540
+ .nozle-plan-change :focus-visible{outline:2px solid var(--nozle-portal-accent,#526949);outline-offset:3px}
1541
+ .nozle-plan-change [role=alert]{color:#922e25}
1542
+ .nozle-plan-change .nzpc-actions{display:flex;gap:10px;flex-wrap:wrap}
1543
+ .nozle-upgrade-modal select{box-sizing:border-box;width:100%;font:inherit;color:inherit;padding:10px;margin:8px 0;border:1px solid #dce2d9;border-radius:7px;background:var(--nozle-portal-background,#fff)}
1544
+ .nozle-upgrade-modal dl{display:block;margin:16px 0;padding:0}
1545
+ .nozle-upgrade-modal dl div{display:flex;justify-content:space-between;gap:16px;margin:12px 0}
1546
+ .nozle-upgrade-modal dd{margin:0;text-align:right}
1547
+ `;
1548
+ var paymentPending = (state) => ["awaiting_payment", "processing", "needs_review"].includes(
1549
+ state.checkoutStatus
1550
+ );
1551
+ function paymentMessage(state) {
1552
+ if (state.checkoutStatus === "needs_review")
1553
+ return "Payment needs review. Contact support before trying another payment.";
1554
+ return state.checkoutStatus === "awaiting_payment" ? "Complete payment to change your plan." : "Your change is processing. Your current plan remains active until confirmation.";
1555
+ }
1556
+ function done(attempt, state) {
1557
+ if (attempt.operation === "withdraw")
1558
+ return !state.pendingChange && state.status === "active" && state.currentPlan.code === attempt.fromPlan;
1559
+ return state.currentPlan.code === attempt.target && state.status === "active" || state.pendingChange?.plan.code === attempt.target;
1560
+ }
1561
+ function PlanChangeControl(props) {
1562
+ return /* @__PURE__ */ jsxRuntime.jsx(PlanChangeFlow, { ...props }, props.subscriptionId);
1563
+ }
1564
+ function PlanChangeFlow({
1565
+ subscriptionId,
1566
+ refreshKey,
1567
+ actions,
1568
+ onChanged,
1569
+ onError,
1570
+ returnUrl,
1571
+ locale = "en-US",
1572
+ timezone = "UTC",
1573
+ nonce
1574
+ }) {
1575
+ const owner = React.useMemo(
1576
+ () => ({ controller: new AbortController() }),
1577
+ [subscriptionId, actions]
1578
+ );
1579
+ const latest = React.useRef(owner);
1580
+ latest.current = owner;
1581
+ const [loaded, setLoaded] = React.useState();
1582
+ const [busy, setBusy] = React.useState(false);
1583
+ const [failure, setFailure] = React.useState();
1584
+ const [notice, setNotice] = React.useState("");
1585
+ const [mode, setMode] = React.useState(
1586
+ null
1587
+ );
1588
+ const [target, setTarget] = React.useState("");
1589
+ const [quote, setQuote] = React.useState();
1590
+ const [checkout, setCheckout] = React.useState(null);
1591
+ const [withdrawTarget, setWithdrawTarget] = React.useState();
1592
+ const pending = React.useRef(void 0);
1593
+ const previousRefresh = React.useRef(refreshKey);
1594
+ const inFlight = React.useRef(null);
1595
+ const state = loaded?.owner === owner ? loaded.value : void 0;
1596
+ const errorCallback = React.useRef(onError), changedCallback = React.useRef(onChanged);
1597
+ errorCallback.current = onError;
1598
+ changedCallback.current = onChanged;
1599
+ async function run(task) {
1600
+ if (latest.current !== owner || inFlight.current) return;
1601
+ const controller = new AbortController();
1602
+ inFlight.current = controller;
1603
+ setBusy(true);
1604
+ setFailure(void 0);
1605
+ let timedOut = false;
1606
+ let rejectAbort = () => {
1607
+ };
1608
+ const aborted = new Promise((_, reject) => {
1609
+ rejectAbort = () => reject(new Error("aborted"));
1610
+ controller.signal.addEventListener("abort", rejectAbort, { once: true });
1611
+ });
1612
+ const timer = setTimeout(() => {
1613
+ timedOut = true;
1614
+ controller.abort();
1615
+ }, 3e4);
1616
+ try {
1617
+ await Promise.race([task(controller.signal), aborted]);
1618
+ } catch (error) {
1619
+ if (latest.current !== owner || controller.signal.aborted && !timedOut)
1620
+ return;
1621
+ const safe = error instanceof BillingPortalError ? error : new BillingPortalError("request");
1622
+ if (safe.code === "changed") {
1623
+ pending.current = void 0;
1624
+ setQuote(void 0);
1625
+ setTarget("");
1626
+ setMode("choose");
1627
+ setFailure(
1628
+ "Your subscription or price changed. Check the latest details and confirm again."
1629
+ );
1630
+ } else
1631
+ setFailure(
1632
+ timedOut ? "This request timed out. Check subscription status before retrying." : safe.code === "unauthorized" ? "Your session expired. Reconnect to manage your subscription." : "We could not confirm this change. Check subscription status before retrying."
1633
+ );
1634
+ errorCallback.current?.(safe);
1635
+ } finally {
1636
+ clearTimeout(timer);
1637
+ controller.signal.removeEventListener("abort", rejectAbort);
1638
+ if (inFlight.current === controller) inFlight.current = null;
1639
+ if (latest.current === owner) setBusy(false);
1640
+ }
1641
+ }
1642
+ async function read(signal, initial = false) {
1643
+ const value = await (initial ? actions.load : actions.status)({
1644
+ subscriptionId,
1645
+ signal
1646
+ });
1647
+ if (signal.aborted || latest.current !== owner) return null;
1648
+ if (value.subscriptionId !== subscriptionId)
1649
+ throw new BillingPortalError("request");
1650
+ setLoaded({ owner, value });
1651
+ setCheckout(paymentPending(value) ? value.checkout : null);
1652
+ return value;
1653
+ }
1654
+ function finish(attempt, value) {
1655
+ pending.current = void 0;
1656
+ setMode(null);
1657
+ setQuote(void 0);
1658
+ setCheckout(null);
1659
+ setNotice(
1660
+ attempt.operation === "withdraw" ? "Scheduled change removed. Your current plan will continue to renew." : value.pendingChange ? `Plan change scheduled for ${formatBillingDate(value.pendingChange.effectiveAt, locale, timezone)}.` : `Your ${value.currentPlan.name} plan is active.`
1661
+ );
1662
+ changedCallback.current?.();
1663
+ }
1664
+ async function reconcile(signal) {
1665
+ const value = await read(signal);
1666
+ if (!value) return null;
1667
+ const attempt = pending.current;
1668
+ if (attempt && done(attempt, value)) finish(attempt, value);
1669
+ else if (!attempt && state && (value.currentPlan.code !== state.currentPlan.code || value.pendingChange?.id !== state.pendingChange?.id)) {
1670
+ setNotice(
1671
+ value.pendingChange ? `Plan change scheduled for ${formatBillingDate(value.pendingChange.effectiveAt, locale, timezone)}.` : `Your ${value.currentPlan.name} plan is active.`
1672
+ );
1673
+ changedCallback.current?.();
1674
+ } else if (["failed", "expired"].includes(value.checkoutStatus)) {
1675
+ pending.current = void 0;
1676
+ setCheckout(null);
1677
+ setMode(null);
1678
+ setNotice(
1679
+ "Payment did not complete. Your current plan is unchanged. You can choose a plan again."
1680
+ );
1681
+ } else if (paymentPending(value) || attempt?.accepted) {
1682
+ setNotice(paymentMessage(value));
1683
+ }
1684
+ return value;
1685
+ }
1686
+ React.useEffect(() => {
1687
+ inFlight.current?.abort();
1688
+ inFlight.current = null;
1689
+ if (owner.controller.signal.aborted)
1690
+ owner.controller = new AbortController();
1691
+ pending.current = void 0;
1692
+ setMode(null);
1693
+ setQuote(void 0);
1694
+ setCheckout(null);
1695
+ setNotice("");
1696
+ void run(async (signal) => {
1697
+ await read(signal, true);
1698
+ });
1699
+ return () => {
1700
+ inFlight.current?.abort();
1701
+ owner.controller.abort();
1702
+ };
1703
+ }, [owner]);
1704
+ React.useEffect(() => {
1705
+ if (previousRefresh.current === refreshKey) return;
1706
+ previousRefresh.current = refreshKey;
1707
+ let stopped = false;
1708
+ let timer;
1709
+ const refresh = () => {
1710
+ if (stopped) return;
1711
+ if (inFlight.current) {
1712
+ timer = setTimeout(refresh, 100);
1713
+ return;
1714
+ }
1715
+ void run(async (signal) => {
1716
+ await reconcile(signal);
1717
+ });
1718
+ };
1719
+ refresh();
1720
+ return () => {
1721
+ stopped = true;
1722
+ clearTimeout(timer);
1723
+ };
1724
+ }, [refreshKey, owner]);
1725
+ React.useEffect(() => {
1726
+ if (!state || state.checkoutStatus === "needs_review" || !paymentPending(state) && !pending.current?.accepted)
1727
+ return;
1728
+ const timer = setInterval(() => {
1729
+ if (!document.hidden)
1730
+ void run(async (signal) => {
1731
+ await reconcile(signal);
1732
+ });
1733
+ }, 5e3);
1734
+ return () => clearInterval(timer);
1735
+ }, [state, owner]);
1736
+ function openChange() {
1737
+ if (pending.current) {
1738
+ setMode(
1739
+ pending.current.operation === "withdraw" ? "withdraw" : "confirm"
1740
+ );
1741
+ return;
1742
+ }
1743
+ setTarget("");
1744
+ setQuote(void 0);
1745
+ setMode("choose");
1746
+ setFailure(void 0);
1747
+ void run(async (signal) => {
1748
+ await read(signal);
1749
+ });
1750
+ }
1751
+ async function prepare() {
1752
+ await run(async (signal) => {
1753
+ const value = await read(signal);
1754
+ if (!value) return;
1755
+ if (value.endingAt || value.pendingChange || paymentPending(value) || !value.eligiblePlans.some((plan2) => plan2.code === target))
1756
+ throw new BillingPortalError("changed");
1757
+ const result = await actions.preview({
1758
+ subscriptionId,
1759
+ targetPlanCode: target,
1760
+ signal
1761
+ });
1762
+ if (signal.aborted) return;
1763
+ const plan = value.eligiblePlans.find((plan2) => plan2.code === target);
1764
+ if (result.operation !== plan.operation || !result.quoteToken || !Number.isFinite(Date.parse(result.effectiveAt)) || result.operation === "downgrade" && result.timing !== "end_of_period")
1765
+ throw new BillingPortalError("request");
1766
+ const amounts = [
1767
+ result.creditAmountCents,
1768
+ result.debitAmountCents,
1769
+ result.netAmountCents,
1770
+ result.amountDueNowCents,
1771
+ result.amountDueAtEffectiveCents
1772
+ ];
1773
+ if (!/^[A-Z]{3}$/.test(result.currency) || amounts.some(
1774
+ (amount) => formatMinorAmount(amount, result.currency, locale) === "Amount unavailable"
1775
+ ) || !["immediate", "end_of_period"].includes(result.timing) || result.renewalAt !== null && !Number.isFinite(Date.parse(result.renewalAt)))
1776
+ throw new BillingPortalError("request");
1777
+ setQuote(result);
1778
+ setMode("confirm");
1779
+ });
1780
+ }
1781
+ async function confirm() {
1782
+ if (mode === "choose") return prepare();
1783
+ await run(async (signal) => {
1784
+ let attempt = pending.current;
1785
+ if (!attempt) {
1786
+ if (mode === "withdraw") {
1787
+ if (!withdrawTarget) throw new BillingPortalError("changed");
1788
+ attempt = {
1789
+ key: crypto.randomUUID(),
1790
+ operation: "withdraw",
1791
+ pendingId: withdrawTarget.id,
1792
+ fromPlan: withdrawTarget.fromPlan,
1793
+ accepted: false,
1794
+ attempted: false
1795
+ };
1796
+ } else {
1797
+ if (!quote) throw new BillingPortalError("changed");
1798
+ attempt = {
1799
+ key: crypto.randomUUID(),
1800
+ operation: quote.operation,
1801
+ target,
1802
+ quote,
1803
+ accepted: false,
1804
+ attempted: false
1805
+ };
1806
+ }
1807
+ pending.current = attempt;
1808
+ }
1809
+ if (attempt.attempted) {
1810
+ await reconcile(signal);
1811
+ if (signal.aborted || pending.current !== attempt || attempt.accepted)
1812
+ return;
1813
+ }
1814
+ attempt.attempted = true;
1815
+ let result;
1816
+ try {
1817
+ if (attempt.operation === "withdraw")
1818
+ await actions.withdraw({
1819
+ subscriptionId,
1820
+ pendingChangeId: attempt.pendingId,
1821
+ idempotencyKey: attempt.key,
1822
+ signal
1823
+ });
1824
+ else
1825
+ result = await actions.apply({
1826
+ subscriptionId,
1827
+ targetPlanCode: attempt.target,
1828
+ quoteToken: attempt.quote.quoteToken,
1829
+ idempotencyKey: attempt.key,
1830
+ returnUrl: returnUrl ?? window.location.origin + window.location.pathname,
1831
+ signal
1832
+ });
1833
+ if (signal.aborted) return;
1834
+ attempt.accepted = true;
1835
+ setMode(null);
1836
+ } catch (error) {
1837
+ if (!signal.aborted) {
1838
+ await reconcile(signal).catch(() => null);
1839
+ if (pending.current !== attempt && !(error instanceof BillingPortalError && error.code === "changed"))
1840
+ return;
1841
+ }
1842
+ throw error;
1843
+ }
1844
+ const value = await reconcile(signal);
1845
+ if (!value || signal.aborted || pending.current !== attempt) return;
1846
+ if (result && !["completed", "scheduled"].includes(
1847
+ "type" in result ? result.type : ""
1848
+ ))
1849
+ setCheckout(result);
1850
+ });
1851
+ }
1852
+ const check = () => void run(async (signal) => {
1853
+ await reconcile(signal);
1854
+ });
1855
+ const selected = state?.eligiblePlans.find((plan) => plan.code === target);
1856
+ const money2 = (amount) => formatMinorAmount(
1857
+ amount,
1858
+ quote?.currency ?? state?.currentPlan.currency ?? "USD",
1859
+ locale
1860
+ );
1861
+ const blocked = Boolean(
1862
+ state?.endingAt || state?.pendingChange || state && paymentPending(state) || state?.blockedReason || pending.current?.accepted
1863
+ );
1864
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "nozle-plan-change", children: [
1865
+ /* @__PURE__ */ jsxRuntime.jsx("style", { nonce, children: styles3 }),
1866
+ !state ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
1867
+ /* @__PURE__ */ jsxRuntime.jsx("p", { role: "status", children: "Loading plan changes\u2026" }),
1868
+ failure && /* @__PURE__ */ jsxRuntime.jsx("p", { role: "alert", children: failure }),
1869
+ /* @__PURE__ */ jsxRuntime.jsx("button", { type: "button", onClick: check, disabled: busy, children: "Check subscription status" })
1870
+ ] }) : /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
1871
+ state.pendingChange && /* @__PURE__ */ jsxRuntime.jsxs("p", { children: [
1872
+ "Current plan until",
1873
+ " ",
1874
+ formatBillingDate(
1875
+ state.pendingChange.effectiveAt,
1876
+ locale,
1877
+ timezone
1878
+ ),
1879
+ ", then ",
1880
+ state.pendingChange.plan.name,
1881
+ " at",
1882
+ " ",
1883
+ formatMinorAmount(
1884
+ state.pendingChange.plan.amountCents,
1885
+ state.pendingChange.plan.currency,
1886
+ locale
1887
+ ),
1888
+ " ",
1889
+ "/ ",
1890
+ state.pendingChange.plan.interval,
1891
+ "."
1892
+ ] }),
1893
+ state.endingAt && /* @__PURE__ */ jsxRuntime.jsx("p", { children: "Keep your subscription before choosing another plan." }),
1894
+ state.blockedReason && !state.endingAt && !state.pendingChange && !paymentPending(state) && /* @__PURE__ */ jsxRuntime.jsx("p", { children: "Plan changes are currently unavailable. Contact support for your options." }),
1895
+ !state.blockedReason && !state.endingAt && !state.pendingChange && !paymentPending(state) && state.eligiblePlans.length === 0 && /* @__PURE__ */ jsxRuntime.jsx("p", { children: "No other plans are available for this subscription." }),
1896
+ ["failed", "expired"].includes(state.checkoutStatus) && !notice && /* @__PURE__ */ jsxRuntime.jsx("p", { children: "Payment did not complete. Your current plan is unchanged." }),
1897
+ paymentPending(state) && !notice && /* @__PURE__ */ jsxRuntime.jsx("p", { role: "status", children: paymentMessage(state) }),
1898
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "nzpc-actions", children: [
1899
+ !blocked && state.status === "active" && state.eligiblePlans.length > 0 && /* @__PURE__ */ jsxRuntime.jsx("button", { type: "button", disabled: busy, onClick: openChange, children: "Change plan" }),
1900
+ state.pendingChange && state.status === "active" && !paymentPending(state) && /* @__PURE__ */ jsxRuntime.jsx(
1901
+ "button",
1902
+ {
1903
+ type: "button",
1904
+ disabled: busy,
1905
+ onClick: () => {
1906
+ setWithdrawTarget({
1907
+ id: state.pendingChange.id,
1908
+ name: state.pendingChange.plan.name,
1909
+ fromPlan: state.currentPlan.code,
1910
+ currentName: state.currentPlan.name
1911
+ });
1912
+ setMode("withdraw");
1913
+ setFailure(void 0);
1914
+ },
1915
+ children: "Keep current plan"
1916
+ }
1917
+ ),
1918
+ (paymentPending(state) || pending.current || failure) && /* @__PURE__ */ jsxRuntime.jsx("button", { type: "button", disabled: busy, onClick: check, children: "Check subscription status" }),
1919
+ pending.current?.attempted && !pending.current.accepted && /* @__PURE__ */ jsxRuntime.jsx("button", { type: "button", disabled: busy, onClick: openChange, children: "Review and retry change" })
1920
+ ] }),
1921
+ failure && !mode && /* @__PURE__ */ jsxRuntime.jsx("p", { role: "alert", children: failure }),
1922
+ notice && /* @__PURE__ */ jsxRuntime.jsx("p", { role: "status", children: notice }),
1923
+ checkout && /* @__PURE__ */ jsxRuntime.jsx(
1924
+ Checkout,
1925
+ {
1926
+ checkout,
1927
+ returnUrl,
1928
+ verifyCheckout: actions.verifyCheckout ? (checkoutId, verification) => actions.verifyCheckout({
1929
+ subscriptionId,
1930
+ checkoutId,
1931
+ verification,
1932
+ signal: owner.controller.signal
1933
+ }) : void 0,
1934
+ getCheckoutStatus: actions.getCheckoutStatus ? (checkoutId) => actions.getCheckoutStatus({
1935
+ subscriptionId,
1936
+ checkoutId,
1937
+ signal: owner.controller.signal
1938
+ }) : void 0,
1939
+ onSuccess: check,
1940
+ onComplete: check,
1941
+ onProcessing: check,
1942
+ onDismiss: () => {
1943
+ if (owner.controller.signal.aborted) return;
1944
+ setNotice(
1945
+ "Payment was closed. Your plan changes only after payment is confirmed."
1946
+ );
1947
+ check();
1948
+ },
1949
+ onError: () => {
1950
+ if (owner.controller.signal.aborted) return;
1951
+ setFailure(
1952
+ "Payment could not be completed. Check subscription status to continue."
1953
+ );
1954
+ check();
1955
+ }
1956
+ },
1957
+ "checkout_id" in checkout ? checkout.checkout_id : "payment"
1958
+ ),
1959
+ /* @__PURE__ */ jsxRuntime.jsxs(
1960
+ UpgradeModal,
1961
+ {
1962
+ isOpen: mode !== null,
1963
+ planCode: target,
1964
+ title: mode === "withdraw" ? "Keep your current plan?" : mode === "choose" ? "Change plan" : `Confirm ${quote?.operation ?? "plan change"}`,
1965
+ nonce,
1966
+ busy,
1967
+ confirmDisabled: mode === "choose" && (!target || blocked) || mode === "confirm" && !quote,
1968
+ confirmLabel: pending.current?.attempted ? "Check status / retry" : mode === "choose" ? "Review change" : mode === "withdraw" ? "Confirm keep current plan" : quote?.operation === "downgrade" ? "Confirm downgrade" : "Confirm upgrade",
1969
+ onCancel: () => setMode(null),
1970
+ onSubmit: confirm,
1971
+ children: [
1972
+ failure && /* @__PURE__ */ jsxRuntime.jsx("p", { role: "alert", children: failure }),
1973
+ mode === "choose" && /* @__PURE__ */ jsxRuntime.jsxs("label", { children: [
1974
+ "Choose a plan",
1975
+ /* @__PURE__ */ jsxRuntime.jsxs(
1976
+ "select",
1977
+ {
1978
+ value: target,
1979
+ onChange: (event) => {
1980
+ setTarget(event.target.value);
1981
+ setQuote(void 0);
1982
+ },
1983
+ disabled: busy,
1984
+ children: [
1985
+ /* @__PURE__ */ jsxRuntime.jsx("option", { value: "", children: "Select a plan" }),
1986
+ state.eligiblePlans.map((plan) => /* @__PURE__ */ jsxRuntime.jsxs("option", { value: plan.code, children: [
1987
+ plan.name,
1988
+ " \u2014",
1989
+ " ",
1990
+ formatMinorAmount(
1991
+ plan.amountCents,
1992
+ plan.currency,
1993
+ locale
1994
+ ),
1995
+ " ",
1996
+ "/ ",
1997
+ plan.interval,
1998
+ " (",
1999
+ plan.operation,
2000
+ ")"
2001
+ ] }, plan.code))
2002
+ ]
2003
+ }
2004
+ )
2005
+ ] }),
2006
+ mode === "withdraw" && /* @__PURE__ */ jsxRuntime.jsxs("p", { children: [
2007
+ "Remove the scheduled change to ",
2008
+ withdrawTarget?.name,
2009
+ ". Your",
2010
+ " ",
2011
+ withdrawTarget?.currentName,
2012
+ " plan will continue to renew."
2013
+ ] }),
2014
+ mode === "confirm" && quote && /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
2015
+ /* @__PURE__ */ jsxRuntime.jsxs("p", { children: [
2016
+ state.currentPlan.name,
2017
+ " \u2192 ",
2018
+ selected?.name ?? target
2019
+ ] }),
2020
+ selected && /* @__PURE__ */ jsxRuntime.jsxs("p", { children: [
2021
+ formatMinorAmount(
2022
+ selected.amountCents,
2023
+ selected.currency,
2024
+ locale
2025
+ ),
2026
+ " ",
2027
+ "/ ",
2028
+ selected.interval,
2029
+ ". Base price, excluding tax and usage."
2030
+ ] }),
2031
+ /* @__PURE__ */ jsxRuntime.jsxs("dl", { children: [
2032
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
2033
+ /* @__PURE__ */ jsxRuntime.jsx("dt", { children: "New plan charge" }),
2034
+ /* @__PURE__ */ jsxRuntime.jsx("dd", { children: money2(quote.debitAmountCents) })
2035
+ ] }),
2036
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
2037
+ /* @__PURE__ */ jsxRuntime.jsx("dt", { children: "Credits applied" }),
2038
+ /* @__PURE__ */ jsxRuntime.jsx("dd", { children: money2(quote.creditAmountCents) })
2039
+ ] }),
2040
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
2041
+ /* @__PURE__ */ jsxRuntime.jsx("dt", { children: "Due now" }),
2042
+ /* @__PURE__ */ jsxRuntime.jsx("dd", { children: money2(quote.amountDueNowCents) })
2043
+ ] }),
2044
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
2045
+ /* @__PURE__ */ jsxRuntime.jsx("dt", { children: "Due at effective date" }),
2046
+ /* @__PURE__ */ jsxRuntime.jsx("dd", { children: money2(quote.amountDueAtEffectiveCents) })
2047
+ ] })
2048
+ ] }),
2049
+ /* @__PURE__ */ jsxRuntime.jsxs("p", { children: [
2050
+ "Effective",
2051
+ " ",
2052
+ formatBillingDate(quote.effectiveAt, locale, timezone),
2053
+ ".",
2054
+ " ",
2055
+ quote.renewalAt && `Next renewal ${formatBillingDate(quote.renewalAt, locale, timezone)}.`
2056
+ ] }),
2057
+ quote.timing === "end_of_period" ? /* @__PURE__ */ jsxRuntime.jsx("p", { children: "Your current plan and access continue until the effective date." }) : BigInt(quote.amountDueNowCents) === 0n ? /* @__PURE__ */ jsxRuntime.jsx("p", { children: "No payment is due now for this change." }) : /* @__PURE__ */ jsxRuntime.jsx("p", { children: "Your plan changes after the required payment is confirmed." })
2058
+ ] })
2059
+ ]
2060
+ }
2061
+ )
2062
+ ] })
2063
+ ] });
2064
+ }
2065
+ function asError(error) {
2066
+ return error instanceof BillingPortalError ? error : new BillingPortalError("request");
2067
+ }
2068
+ function BillingPortal({
2069
+ createSession,
2070
+ cancellationActions,
2071
+ planChangeActions,
2072
+ locale = "en-US",
2073
+ className = "",
2074
+ style,
2075
+ nonce,
2076
+ onError
2077
+ }) {
2078
+ const [attempt, setAttempt] = React.useState(0);
2079
+ const [state, setState] = React.useState();
2080
+ const errorCallback = React.useRef(onError);
2081
+ errorCallback.current = onError;
2082
+ React.useEffect(() => {
2083
+ const controller = new AbortController();
2084
+ let active = true;
2085
+ const timer = setTimeout(() => {
2086
+ active = false;
2087
+ controller.abort();
2088
+ const error = new BillingPortalError("session");
2089
+ setState({ source: createSession, attempt, error });
2090
+ errorCallback.current?.(error);
2091
+ }, 2e4);
2092
+ Promise.resolve().then(() => createSession({ signal: controller.signal })).then((session) => {
2093
+ if (active)
2094
+ setState({
2095
+ source: createSession,
2096
+ attempt,
2097
+ client: portalClient(session)
2098
+ });
2099
+ }).catch(() => {
2100
+ if (active) {
2101
+ const error = new BillingPortalError("session");
2102
+ setState({ source: createSession, attempt, error });
2103
+ errorCallback.current?.(error);
2104
+ }
2105
+ }).finally(() => clearTimeout(timer));
2106
+ return () => {
2107
+ active = false;
2108
+ clearTimeout(timer);
2109
+ controller.abort();
2110
+ };
2111
+ }, [createSession, attempt]);
2112
+ const current = state?.source === createSession && state.attempt === attempt ? state : void 0;
2113
+ const reconnect = () => setAttempt((value) => value + 1);
2114
+ return /* @__PURE__ */ jsxRuntime.jsxs(
2115
+ "div",
2116
+ {
2117
+ className: `nozle-billing-portal ${className}`,
2118
+ style,
2119
+ "aria-label": "Nozle billing portal",
2120
+ children: [
2121
+ /* @__PURE__ */ jsxRuntime.jsx("style", { nonce, children: portalStyles }),
2122
+ current?.client ? /* @__PURE__ */ jsxRuntime.jsx(
2123
+ Portal,
2124
+ {
2125
+ client: current.client,
2126
+ locale,
2127
+ reconnect,
2128
+ onError,
2129
+ cancellationActions,
2130
+ planChangeActions,
2131
+ nonce
2132
+ },
2133
+ attempt
2134
+ ) : current?.error ? /* @__PURE__ */ jsxRuntime.jsx(Failure, { error: current.error, retry: reconnect }) : /* @__PURE__ */ jsxRuntime.jsx(Loading, { label: "Starting billing session\u2026" })
2135
+ ]
2136
+ }
2137
+ );
2138
+ }
2139
+ function useQuery(client, query, variables, onError, retainDuringRefresh = false) {
2140
+ const [attempt, setAttempt] = React.useState(0);
2141
+ const key = JSON.stringify(variables);
2142
+ const [state, setState] = React.useState();
2143
+ const callback = React.useRef(onError);
2144
+ callback.current = onError;
2145
+ React.useEffect(() => {
2146
+ const controller = new AbortController();
2147
+ client.request(query, JSON.parse(key), controller.signal).then((data) => {
2148
+ if (!controller.signal.aborted)
2149
+ setState({ client, key, attempt, data });
2150
+ }).catch((cause) => {
2151
+ if (!controller.signal.aborted) {
2152
+ const error = asError(cause);
2153
+ setState({ client, key, attempt, error });
2154
+ callback.current?.(error);
2155
+ }
2156
+ });
2157
+ return () => controller.abort();
2158
+ }, [client, query, key, attempt]);
2159
+ const current = state?.client === client && state.key === key && state.attempt === attempt ? state : void 0;
2160
+ return {
2161
+ data: current?.data ?? (retainDuringRefresh && !current && state?.client === client && state.key === key ? state.data : void 0),
2162
+ error: current?.error,
2163
+ retry: () => setAttempt((n) => n + 1)
2164
+ };
2165
+ }
2166
+ function useAction(onError) {
2167
+ const [pending, setPending] = React.useState(false);
2168
+ const [error, setError] = React.useState();
2169
+ const controller = React.useRef(null);
2170
+ React.useEffect(() => () => controller.current?.abort(), []);
2171
+ return {
2172
+ pending,
2173
+ error,
2174
+ run: async (action) => {
2175
+ if (controller.current) return;
2176
+ const next = new AbortController();
2177
+ controller.current = next;
2178
+ setPending(true);
2179
+ setError(void 0);
2180
+ try {
2181
+ await action(next.signal);
2182
+ } catch (cause) {
2183
+ if (!next.signal.aborted) {
2184
+ const failure = asError(cause);
2185
+ setError(failure);
2186
+ onError?.(failure);
2187
+ }
2188
+ } finally {
2189
+ if (!next.signal.aborted) setPending(false);
2190
+ if (controller.current === next) controller.current = null;
2191
+ }
2192
+ }
2193
+ };
2194
+ }
2195
+ function Loading({ label = "Loading billing data\u2026" }) {
2196
+ return /* @__PURE__ */ jsxRuntime.jsx("p", { className: "nzp-empty", role: "status", children: label });
2197
+ }
2198
+ function Failure({
2199
+ error,
2200
+ retry,
2201
+ reconnect
2202
+ }) {
2203
+ const action = error.code === "unauthorized" ? reconnect ?? retry : retry;
2204
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { role: "alert", className: "nzp-error", children: [
2205
+ /* @__PURE__ */ jsxRuntime.jsx("span", { children: error.message }),
2206
+ action && /* @__PURE__ */ jsxRuntime.jsx("button", { type: "button", onClick: action, children: error.code === "unauthorized" ? "Reconnect" : "Try again" })
2207
+ ] });
2208
+ }
2209
+ function money(cents, currency, locale) {
2210
+ const formatter = new Intl.NumberFormat(locale, {
2211
+ style: "currency",
2212
+ currency
2213
+ });
2214
+ const digits = formatter.resolvedOptions().maximumFractionDigits ?? 2;
2215
+ return formatter.format(Number(cents) / 10 ** digits);
2216
+ }
2217
+ function date(value, locale, timeZone) {
2218
+ if (!value) return "\u2014";
2219
+ const dateOnly = /^\d{4}-\d{2}-\d{2}$/.test(value);
2220
+ const zone = timeZone?.startsWith("TZ_") ? portalTimezones[timeZone] ?? "UTC" : timeZone ?? "UTC";
2221
+ return new Intl.DateTimeFormat(locale, {
2222
+ dateStyle: "medium",
2223
+ timeZone: dateOnly ? "UTC" : zone
2224
+ }).format(new Date(value));
2225
+ }
2226
+ var planName = (subscription) => subscription.name || subscription.plan.invoiceDisplayName || subscription.plan.name;
2227
+ var intervals = {
2228
+ weekly: "week",
2229
+ monthly: "month",
2230
+ quarterly: "quarter",
2231
+ semiannual: "six months",
2232
+ yearly: "year"
2233
+ };
2234
+ function Portal(props) {
2235
+ const { client, locale, reconnect, onError } = props;
2236
+ const { data, error, retry } = useQuery(
2237
+ client,
2238
+ identityQuery,
2239
+ {},
2240
+ onError
2241
+ );
2242
+ const [view, setView] = React.useState({ kind: "overview" });
2243
+ const [notice, setNotice] = React.useState("");
2244
+ const back = () => setView({ kind: "overview" });
2245
+ if (error)
2246
+ return /* @__PURE__ */ jsxRuntime.jsx(Failure, { error, retry, reconnect });
2247
+ if (!data) return /* @__PURE__ */ jsxRuntime.jsx(Loading, {});
2248
+ const customer = data.customerPortalUser;
2249
+ return /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
2250
+ /* @__PURE__ */ jsxRuntime.jsxs("header", { children: [
2251
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "nzp-row", children: [
2252
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "nzp-muted", children: data.customerPortalOrganization.name }),
2253
+ /* @__PURE__ */ jsxRuntime.jsx("button", { type: "button", onClick: reconnect, children: "Refresh portal" })
2254
+ ] }),
2255
+ /* @__PURE__ */ jsxRuntime.jsx("h2", { children: "Billing portal" }),
2256
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "nzp-muted", children: customer.name || [customer.firstname, customer.lastname].filter(Boolean).join(" ") || customer.email || "Your account" })
2257
+ ] }),
2258
+ notice && /* @__PURE__ */ jsxRuntime.jsx("p", { role: "status", children: notice }),
2259
+ view.kind !== "overview" && /* @__PURE__ */ jsxRuntime.jsx("button", { type: "button", onClick: back, children: "\u2190 Back to overview" }),
2260
+ view.kind === "overview" && /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
2261
+ /* @__PURE__ */ jsxRuntime.jsx(
2262
+ Subscriptions,
2263
+ {
2264
+ ...props,
2265
+ timezone: customer.applicableTimezone,
2266
+ onUsage: (subscription) => setView({ kind: "usage", subscription })
2267
+ }
2268
+ ),
2269
+ /* @__PURE__ */ jsxRuntime.jsx(
2270
+ Wallets,
2271
+ {
2272
+ ...props,
2273
+ onWallet: (wallet) => setView({ kind: "wallet", wallet })
2274
+ }
2275
+ ),
2276
+ /* @__PURE__ */ jsxRuntime.jsxs("section", { "aria-label": "Billing information", children: [
2277
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "nzp-row", children: [
2278
+ /* @__PURE__ */ jsxRuntime.jsx("h3", { children: "Billing information" }),
2279
+ /* @__PURE__ */ jsxRuntime.jsx("button", { type: "button", onClick: () => setView({ kind: "edit" }), children: "Edit billing information" })
2280
+ ] }),
2281
+ /* @__PURE__ */ jsxRuntime.jsxs("dl", { children: [
2282
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
2283
+ /* @__PURE__ */ jsxRuntime.jsx("dt", { children: "Account name" }),
2284
+ /* @__PURE__ */ jsxRuntime.jsx("dd", { children: customer.name || "Not provided" })
2285
+ ] }),
2286
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
2287
+ /* @__PURE__ */ jsxRuntime.jsx("dt", { children: "Email" }),
2288
+ /* @__PURE__ */ jsxRuntime.jsx("dd", { children: customer.email || "Not provided" })
2289
+ ] }),
2290
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
2291
+ /* @__PURE__ */ jsxRuntime.jsx("dt", { children: "Legal name" }),
2292
+ /* @__PURE__ */ jsxRuntime.jsx("dd", { children: customer.legalName || "Not provided" })
2293
+ ] }),
2294
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
2295
+ /* @__PURE__ */ jsxRuntime.jsx("dt", { children: "Tax ID" }),
2296
+ /* @__PURE__ */ jsxRuntime.jsx("dd", { children: customer.taxIdentificationNumber || "Not provided" })
2297
+ ] }),
2298
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
2299
+ /* @__PURE__ */ jsxRuntime.jsx("dt", { children: "Billing address" }),
2300
+ /* @__PURE__ */ jsxRuntime.jsx("dd", { children: [
2301
+ customer.addressLine1,
2302
+ customer.addressLine2,
2303
+ customer.city,
2304
+ customer.state,
2305
+ customer.zipcode,
2306
+ customer.country
2307
+ ].filter(Boolean).join(", ") || "Not provided" })
2308
+ ] })
2309
+ ] })
2310
+ ] }),
2311
+ /* @__PURE__ */ jsxRuntime.jsx(Invoices, { ...props })
2312
+ ] }),
2313
+ view.kind === "usage" && /* @__PURE__ */ jsxRuntime.jsx(
2314
+ UsageDetails,
2315
+ {
2316
+ ...props,
2317
+ subscription: view.subscription,
2318
+ timezone: customer.applicableTimezone
2319
+ }
2320
+ ),
2321
+ view.kind === "edit" && /* @__PURE__ */ jsxRuntime.jsx(
2322
+ CustomerForm,
2323
+ {
2324
+ ...props,
2325
+ customer,
2326
+ onSaved: () => {
2327
+ setNotice("Billing information saved.");
2328
+ back();
2329
+ retry();
2330
+ },
2331
+ onCancel: back
2332
+ }
2333
+ ),
2334
+ view.kind === "wallet" && /* @__PURE__ */ jsxRuntime.jsx(
2335
+ WalletTopUp,
2336
+ {
2337
+ ...props,
2338
+ wallet: view.wallet,
2339
+ onCreated: () => {
2340
+ setNotice(
2341
+ "Top-up requested. Your balance updates after payment is processed."
2342
+ );
2343
+ back();
2344
+ }
2345
+ }
2346
+ ),
2347
+ /* @__PURE__ */ jsxRuntime.jsx("footer", { children: "Powered by Nozle" })
2348
+ ] });
2349
+ }
2350
+ function Pager({
2351
+ page,
2352
+ total,
2353
+ setPage
2354
+ }) {
2355
+ if (total <= 1) return null;
2356
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "nzp-actions", "aria-label": "Pagination", children: [
2357
+ /* @__PURE__ */ jsxRuntime.jsx(
2358
+ "button",
2359
+ {
2360
+ type: "button",
2361
+ disabled: page <= 1,
2362
+ onClick: () => setPage(page - 1),
2363
+ children: "Previous"
2364
+ }
2365
+ ),
2366
+ /* @__PURE__ */ jsxRuntime.jsxs("span", { children: [
2367
+ "Page ",
2368
+ page,
2369
+ " of ",
2370
+ total
2371
+ ] }),
2372
+ /* @__PURE__ */ jsxRuntime.jsx(
2373
+ "button",
2374
+ {
2375
+ type: "button",
2376
+ disabled: page >= total,
2377
+ onClick: () => setPage(page + 1),
2378
+ children: "Next"
2379
+ }
2380
+ )
2381
+ ] });
2382
+ }
2383
+ function Subscriptions({
2384
+ client,
2385
+ locale,
2386
+ timezone,
2387
+ reconnect,
2388
+ onError,
2389
+ onUsage,
2390
+ cancellationActions,
2391
+ planChangeActions,
2392
+ nonce
2393
+ }) {
2394
+ const [page, setPage] = React.useState(1);
2395
+ const [updated, setUpdated] = React.useState({});
2396
+ const { data, error, retry } = useQuery(client, subscriptionsQuery, { page }, onError, true);
2397
+ const result = data?.customerPortalSubscriptions;
2398
+ React.useEffect(() => setUpdated({}), [result]);
2399
+ return /* @__PURE__ */ jsxRuntime.jsxs("section", { "aria-label": "Subscriptions", children: [
2400
+ /* @__PURE__ */ jsxRuntime.jsx("h3", { children: "Subscriptions" }),
2401
+ error ? /* @__PURE__ */ jsxRuntime.jsx(Failure, { error, retry, reconnect }) : !result ? /* @__PURE__ */ jsxRuntime.jsx(Loading, {}) : /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
2402
+ result.collection.length === 0 ? /* @__PURE__ */ jsxRuntime.jsx("p", { className: "nzp-empty", children: "No active subscriptions." }) : /* @__PURE__ */ jsxRuntime.jsx("div", { className: "nzp-stack", children: result.collection.map((item) => updated[item.id] ?? item).map((subscription) => /* @__PURE__ */ jsxRuntime.jsxs(
2403
+ "article",
2404
+ {
2405
+ className: "nzp-card",
2406
+ "data-subscription-id": subscription.externalId,
2407
+ children: [
2408
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "nzp-row", children: [
2409
+ /* @__PURE__ */ jsxRuntime.jsx("h3", { children: planName(subscription) }),
2410
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "nzp-badge", children: subscription.endingAt ? "Scheduled to end" : "Active" })
2411
+ ] }),
2412
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "nzp-price", children: [
2413
+ money(
2414
+ subscription.plan.amountCents,
2415
+ subscription.plan.amountCurrency,
2416
+ locale
2417
+ ),
2418
+ " ",
2419
+ /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "nzp-muted", children: [
2420
+ "/",
2421
+ " ",
2422
+ intervals[subscription.plan.interval] || subscription.plan.interval
2423
+ ] })
2424
+ ] }),
2425
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "nzp-row", children: [
2426
+ /* @__PURE__ */ jsxRuntime.jsxs("p", { className: "nzp-muted", children: [
2427
+ "Base price, excluding tax and usage",
2428
+ /* @__PURE__ */ jsxRuntime.jsx("br", {}),
2429
+ "Current period ends",
2430
+ " ",
2431
+ date(
2432
+ subscription.currentBillingPeriodEndingAt,
2433
+ locale,
2434
+ timezone
2435
+ )
2436
+ ] }),
2437
+ /* @__PURE__ */ jsxRuntime.jsx(
2438
+ "button",
2439
+ {
2440
+ type: "button",
2441
+ onClick: () => onUsage(subscription),
2442
+ children: "View usage"
2443
+ }
2444
+ )
2445
+ ] }),
2446
+ subscription.endingAt && /* @__PURE__ */ jsxRuntime.jsxs("p", { children: [
2447
+ "Cancels on",
2448
+ " ",
2449
+ date(subscription.endingAt, locale, timezone)
2450
+ ] }),
2451
+ subscription.nextSubscription?.status === "pending" && /* @__PURE__ */ jsxRuntime.jsxs("p", { children: [
2452
+ "Scheduled plan:",
2453
+ " ",
2454
+ subscription.nextSubscription.plan.name
2455
+ ] }),
2456
+ cancellationActions && subscription.externalId && /* @__PURE__ */ jsxRuntime.jsx(
2457
+ CancellationControl,
2458
+ {
2459
+ subscription: cancellationState(subscription),
2460
+ actions: cancellationActions,
2461
+ locale,
2462
+ timezone,
2463
+ nonce,
2464
+ onError,
2465
+ onChanged: retry,
2466
+ refresh: async (signal) => {
2467
+ const result2 = await client.request(
2468
+ subscriptionQuery,
2469
+ { id: subscription.id },
2470
+ signal
2471
+ );
2472
+ if (!signal.aborted && result2.customerPortalSubscription) {
2473
+ const fresh = result2.customerPortalSubscription;
2474
+ setUpdated((previous) => ({
2475
+ ...previous,
2476
+ [fresh.id]: fresh
2477
+ }));
2478
+ }
2479
+ return result2.customerPortalSubscription ? cancellationState(
2480
+ result2.customerPortalSubscription
2481
+ ) : null;
2482
+ }
2483
+ }
2484
+ ),
2485
+ planChangeActions && subscription.externalId && /* @__PURE__ */ jsxRuntime.jsx(
2486
+ PlanChangeControl,
2487
+ {
2488
+ subscriptionId: subscription.externalId,
2489
+ refreshKey: `${subscription.id}:${subscription.endingAt ?? ""}:${subscription.nextSubscription?.id ?? ""}:${subscription.plan.code}`,
2490
+ actions: planChangeActions,
2491
+ locale,
2492
+ timezone,
2493
+ nonce,
2494
+ onError,
2495
+ onChanged: retry
2496
+ }
2497
+ )
2498
+ ]
2499
+ },
2500
+ subscription.externalId || subscription.id
2501
+ )) }),
2502
+ /* @__PURE__ */ jsxRuntime.jsx(
2503
+ Pager,
2504
+ {
2505
+ page,
2506
+ total: result.metadata.totalPages,
2507
+ setPage
2508
+ }
2509
+ )
2510
+ ] })
2511
+ ] });
2512
+ }
2513
+ function cancellationState(subscription) {
2514
+ return {
2515
+ id: subscription.id,
2516
+ externalId: subscription.externalId,
2517
+ name: planName(subscription),
2518
+ status: subscription.status,
2519
+ endingAt: subscription.endingAt,
2520
+ pendingPlanName: subscription.nextSubscription?.status === "pending" ? subscription.nextSubscription.plan.name : null
2521
+ };
2522
+ }
2523
+ function UsageDetails({
2524
+ client,
2525
+ locale,
2526
+ reconnect,
2527
+ onError,
2528
+ subscription,
2529
+ timezone
2530
+ }) {
2531
+ const { data, error, retry } = useQuery(client, usageQuery, { subscriptionId: subscription.id }, onError);
2532
+ const usage = data?.customerPortalCustomerUsage;
2533
+ return /* @__PURE__ */ jsxRuntime.jsxs("section", { "aria-label": "Subscription usage", children: [
2534
+ /* @__PURE__ */ jsxRuntime.jsxs("h3", { children: [
2535
+ planName(subscription),
2536
+ " \xB7 Usage"
2537
+ ] }),
2538
+ error ? /* @__PURE__ */ jsxRuntime.jsx(Failure, { error, retry, reconnect }) : !usage ? /* @__PURE__ */ jsxRuntime.jsx(Loading, {}) : /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
2539
+ /* @__PURE__ */ jsxRuntime.jsxs("p", { className: "nzp-muted", children: [
2540
+ date(usage.fromDatetime, locale, timezone),
2541
+ " \u2013",
2542
+ " ",
2543
+ date(usage.toDatetime, locale, timezone)
2544
+ ] }),
2545
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "nzp-price", children: money(usage.amountCents, usage.currency, locale) }),
2546
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "nzp-muted", children: "Current usage, excluding tax" }),
2547
+ usage.chargesUsage.length ? /* @__PURE__ */ jsxRuntime.jsx("div", { className: "nzp-table", children: /* @__PURE__ */ jsxRuntime.jsxs("table", { children: [
2548
+ /* @__PURE__ */ jsxRuntime.jsx("thead", { children: /* @__PURE__ */ jsxRuntime.jsxs("tr", { children: [
2549
+ /* @__PURE__ */ jsxRuntime.jsx("th", { children: "Feature" }),
2550
+ /* @__PURE__ */ jsxRuntime.jsx("th", { children: "Units" }),
2551
+ /* @__PURE__ */ jsxRuntime.jsx("th", { children: "Amount" })
2552
+ ] }) }),
2553
+ /* @__PURE__ */ jsxRuntime.jsx("tbody", { children: usage.chargesUsage.map((charge, index) => /* @__PURE__ */ jsxRuntime.jsxs("tr", { children: [
2554
+ /* @__PURE__ */ jsxRuntime.jsx("td", { children: charge.charge?.invoiceDisplayName || charge.feature?.name || charge.feature?.code || "Usage" }),
2555
+ /* @__PURE__ */ jsxRuntime.jsx("td", { children: charge.units }),
2556
+ /* @__PURE__ */ jsxRuntime.jsx("td", { children: money(charge.amountCents, usage.currency, locale) })
2557
+ ] }, `${charge.id}-${index}`)) })
2558
+ ] }) }) : /* @__PURE__ */ jsxRuntime.jsx("p", { className: "nzp-empty", children: "No usage recorded for this billing period." })
2559
+ ] })
2560
+ ] });
2561
+ }
2562
+ function Invoices(props) {
2563
+ const { client, locale, reconnect, onError } = props;
2564
+ const [search, setSearch] = React.useState("");
2565
+ const [filter, setFilter] = React.useState({ page: 1, searchTerm: "" });
2566
+ const { data, error, retry } = useQuery(client, invoicesQuery, filter, onError);
2567
+ const result = data?.customerPortalInvoices;
2568
+ return /* @__PURE__ */ jsxRuntime.jsxs("section", { "aria-label": "Invoice history", children: [
2569
+ /* @__PURE__ */ jsxRuntime.jsx("h3", { children: "Invoice history" }),
2570
+ /* @__PURE__ */ jsxRuntime.jsxs(
2571
+ "form",
2572
+ {
2573
+ className: "nzp-actions",
2574
+ onSubmit: (event) => {
2575
+ event.preventDefault();
2576
+ setFilter({ page: 1, searchTerm: search.trim() });
2577
+ },
2578
+ children: [
2579
+ /* @__PURE__ */ jsxRuntime.jsxs("label", { children: [
2580
+ "Search invoices",
2581
+ /* @__PURE__ */ jsxRuntime.jsx(
2582
+ "input",
2583
+ {
2584
+ type: "search",
2585
+ value: search,
2586
+ onChange: (event) => setSearch(event.target.value)
2587
+ }
2588
+ )
2589
+ ] }),
2590
+ /* @__PURE__ */ jsxRuntime.jsx("button", { type: "submit", children: "Search" })
2591
+ ]
2592
+ }
2593
+ ),
2594
+ error ? /* @__PURE__ */ jsxRuntime.jsx(Failure, { error, retry, reconnect }) : !result ? /* @__PURE__ */ jsxRuntime.jsx(Loading, {}) : /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
2595
+ !result.collection.length ? /* @__PURE__ */ jsxRuntime.jsx("p", { className: "nzp-empty", children: filter.searchTerm ? "No invoices match your search." : "No invoices yet." }) : /* @__PURE__ */ jsxRuntime.jsx("div", { className: "nzp-table", children: /* @__PURE__ */ jsxRuntime.jsxs("table", { children: [
2596
+ /* @__PURE__ */ jsxRuntime.jsx("thead", { children: /* @__PURE__ */ jsxRuntime.jsxs("tr", { children: [
2597
+ /* @__PURE__ */ jsxRuntime.jsx("th", { children: "Invoice" }),
2598
+ /* @__PURE__ */ jsxRuntime.jsx("th", { children: "Date" }),
2599
+ /* @__PURE__ */ jsxRuntime.jsx("th", { children: "Amount" }),
2600
+ /* @__PURE__ */ jsxRuntime.jsx("th", { children: "Status" }),
2601
+ /* @__PURE__ */ jsxRuntime.jsx("th", { children: "PDF" })
2602
+ ] }) }),
2603
+ /* @__PURE__ */ jsxRuntime.jsx("tbody", { children: result.collection.map((invoice) => /* @__PURE__ */ jsxRuntime.jsxs("tr", { children: [
2604
+ /* @__PURE__ */ jsxRuntime.jsx("td", { children: invoice.number }),
2605
+ /* @__PURE__ */ jsxRuntime.jsx("td", { children: date(invoice.issuingDate, locale) }),
2606
+ /* @__PURE__ */ jsxRuntime.jsx("td", { children: money(
2607
+ invoice.totalAmountCents,
2608
+ invoice.currency,
2609
+ locale
2610
+ ) }),
2611
+ /* @__PURE__ */ jsxRuntime.jsx("td", { children: invoice.paymentOverdue ? "Overdue" : invoice.paymentStatus === "succeeded" ? "Paid" : invoice.paymentDisputeLostAt ? "Disputed" : "To pay" }),
2612
+ /* @__PURE__ */ jsxRuntime.jsx("td", { children: /* @__PURE__ */ jsxRuntime.jsx(InvoiceDownload, { ...props, invoice }) })
2613
+ ] }, invoice.id)) })
2614
+ ] }) }),
2615
+ /* @__PURE__ */ jsxRuntime.jsx(
2616
+ Pager,
2617
+ {
2618
+ page: filter.page,
2619
+ total: result.metadata.totalPages,
2620
+ setPage: (page) => setFilter({ ...filter, page })
2621
+ }
2622
+ )
2623
+ ] })
2624
+ ] });
2625
+ }
2626
+ function InvoiceDownload({
2627
+ client,
2628
+ invoice,
2629
+ onError,
2630
+ reconnect
2631
+ }) {
2632
+ const [url, setUrl] = React.useState("");
2633
+ const [generating, setGenerating] = React.useState(false);
2634
+ const action = useAction(onError);
2635
+ const download = () => action.run(async (signal) => {
2636
+ const data = await client.request(downloadInvoiceMutation, { input: { id: invoice.id } }, signal);
2637
+ if (signal.aborted) return;
2638
+ const file = data.downloadCustomerPortalInvoice.fileUrl;
2639
+ if (file) {
2640
+ setUrl(invoiceDownloadUrl(file));
2641
+ setGenerating(false);
2642
+ } else setGenerating(true);
2643
+ });
2644
+ return /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
2645
+ url ? /* @__PURE__ */ jsxRuntime.jsx(
2646
+ "a",
2647
+ {
2648
+ className: "nzp-link",
2649
+ href: url,
2650
+ target: "_blank",
2651
+ rel: "noopener noreferrer",
2652
+ referrerPolicy: "no-referrer",
2653
+ children: "Open PDF"
2654
+ }
2655
+ ) : /* @__PURE__ */ jsxRuntime.jsx(
2656
+ "button",
2657
+ {
2658
+ type: "button",
2659
+ disabled: action.pending,
2660
+ "aria-label": `Download invoice ${invoice.number}`,
2661
+ onClick: download,
2662
+ children: action.pending ? "Preparing\u2026" : generating ? "Check PDF" : "Download"
2663
+ }
2664
+ ),
2665
+ generating && /* @__PURE__ */ jsxRuntime.jsx("p", { className: "nzp-muted", role: "status", children: "PDF is being generated. Check again shortly." }),
2666
+ action.error && /* @__PURE__ */ jsxRuntime.jsx(Failure, { error: action.error, reconnect })
2667
+ ] });
2668
+ }
2669
+ var customerFields = [
2670
+ ["name", "Account name"],
2671
+ ["firstname", "First name"],
2672
+ ["lastname", "Last name"],
2673
+ ["email", "Email"],
2674
+ ["legalName", "Legal name"],
2675
+ ["taxIdentificationNumber", "Tax ID"],
2676
+ ["addressLine1", "Address line 1"],
2677
+ ["addressLine2", "Address line 2"],
2678
+ ["city", "City"],
2679
+ ["state", "State / province"],
2680
+ ["zipcode", "Postal code"],
2681
+ ["country", "Country code"]
2682
+ ];
2683
+ function CustomerForm({
2684
+ client,
2685
+ customer,
2686
+ reconnect,
2687
+ onError,
2688
+ onSaved,
2689
+ onCancel
2690
+ }) {
2691
+ const [values, setValues] = React.useState(
2692
+ () => Object.fromEntries(
2693
+ customerFields.map(([key]) => [key, customer[key] ?? ""])
2694
+ )
2695
+ );
2696
+ const action = useAction(onError);
2697
+ const submit = (event) => {
2698
+ event.preventDefault();
2699
+ const input = Object.fromEntries(
2700
+ customerFields.filter(([key]) => values[key] !== (customer[key] ?? "")).map(([key]) => [
2701
+ key,
2702
+ key === "country" ? values[key].toUpperCase() || null : values[key]
2703
+ ])
2704
+ );
2705
+ void action.run(async (signal) => {
2706
+ await client.request(updateCustomerMutation, { input }, signal);
2707
+ if (!signal.aborted) onSaved();
2708
+ });
2709
+ };
2710
+ return /* @__PURE__ */ jsxRuntime.jsxs("section", { "aria-label": "Edit billing information", children: [
2711
+ /* @__PURE__ */ jsxRuntime.jsx("h3", { children: "Edit billing information" }),
2712
+ /* @__PURE__ */ jsxRuntime.jsxs("form", { onSubmit: submit, children: [
2713
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "nzp-fields", children: customerFields.map(([key, label]) => /* @__PURE__ */ jsxRuntime.jsxs("label", { children: [
2714
+ label,
2715
+ /* @__PURE__ */ jsxRuntime.jsx(
2716
+ "input",
2717
+ {
2718
+ type: key === "email" ? "email" : "text",
2719
+ value: values[key],
2720
+ disabled: action.pending,
2721
+ pattern: key === "country" ? "[A-Za-z]{2}" : void 0,
2722
+ maxLength: key === "country" ? 2 : 255,
2723
+ placeholder: key === "country" ? "US" : void 0,
2724
+ onChange: (event) => setValues({ ...values, [key]: event.target.value })
2725
+ }
2726
+ )
2727
+ ] }, key)) }),
2728
+ action.error && /* @__PURE__ */ jsxRuntime.jsx(Failure, { error: action.error, reconnect }),
2729
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "nzp-actions", children: [
2730
+ /* @__PURE__ */ jsxRuntime.jsx(
2731
+ "button",
2732
+ {
2733
+ type: "submit",
2734
+ className: "nzp-primary",
2735
+ disabled: action.pending,
2736
+ children: action.pending ? "Saving\u2026" : "Save billing information"
2737
+ }
2738
+ ),
2739
+ /* @__PURE__ */ jsxRuntime.jsx("button", { type: "button", disabled: action.pending, onClick: onCancel, children: "Cancel" })
2740
+ ] })
2741
+ ] })
2742
+ ] });
2743
+ }
2744
+ function Wallets({
2745
+ client,
2746
+ locale,
2747
+ reconnect,
2748
+ onError,
2749
+ onWallet
2750
+ }) {
2751
+ const [page, setPage] = React.useState(1);
2752
+ const { data, error, retry } = useQuery(client, walletsQuery, { page }, onError);
2753
+ const result = data?.customerPortalWallets;
2754
+ if (result && !result.collection.length) return null;
2755
+ return /* @__PURE__ */ jsxRuntime.jsxs("section", { "aria-label": "Wallets", children: [
2756
+ /* @__PURE__ */ jsxRuntime.jsx("h3", { children: "Wallets" }),
2757
+ error ? /* @__PURE__ */ jsxRuntime.jsx(Failure, { error, retry, reconnect }) : !result ? /* @__PURE__ */ jsxRuntime.jsx(Loading, {}) : /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
2758
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "nzp-stack", children: result.collection.map((wallet) => /* @__PURE__ */ jsxRuntime.jsxs("article", { className: "nzp-card", children: [
2759
+ /* @__PURE__ */ jsxRuntime.jsx("h3", { children: wallet.name || "Prepaid credits" }),
2760
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "nzp-price", children: money(wallet.balanceCents, wallet.currency, locale) }),
2761
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "nzp-row", children: [
2762
+ /* @__PURE__ */ jsxRuntime.jsxs("p", { className: "nzp-muted", children: [
2763
+ wallet.creditsBalance,
2764
+ " credits available \xB7",
2765
+ " ",
2766
+ wallet.consumedCredits,
2767
+ " consumed"
2768
+ ] }),
2769
+ /* @__PURE__ */ jsxRuntime.jsx("button", { type: "button", onClick: () => onWallet(wallet), children: "Add credits" })
2770
+ ] })
2771
+ ] }, wallet.id)) }),
2772
+ /* @__PURE__ */ jsxRuntime.jsx(
2773
+ Pager,
2774
+ {
2775
+ page,
2776
+ total: result.metadata.totalPages,
2777
+ setPage
2778
+ }
2779
+ )
2780
+ ] })
2781
+ ] });
2782
+ }
2783
+ function WalletTopUp({
2784
+ client,
2785
+ locale,
2786
+ wallet,
2787
+ reconnect,
2788
+ onError,
2789
+ onCreated
2790
+ }) {
2791
+ const [credits, setCredits] = React.useState("");
2792
+ const action = useAction(onError);
2793
+ const digits = new Intl.NumberFormat(locale, {
2794
+ style: "currency",
2795
+ currency: wallet.currency
2796
+ }).resolvedOptions().maximumFractionDigits ?? 2;
2797
+ const amountCents = walletAmountCents(credits, wallet.rateAmount, digits);
2798
+ const valid = amountCents !== null && compareDecimalStrings(credits, "0") > 0 && (wallet.paidTopUpMinAmountCents == null || compareDecimalStrings(
2799
+ amountCents,
2800
+ String(wallet.paidTopUpMinAmountCents)
2801
+ ) >= 0) && (wallet.paidTopUpMaxAmountCents == null || compareDecimalStrings(
2802
+ amountCents,
2803
+ String(wallet.paidTopUpMaxAmountCents)
2804
+ ) <= 0);
2805
+ return /* @__PURE__ */ jsxRuntime.jsxs("section", { "aria-label": "Add credits", children: [
2806
+ /* @__PURE__ */ jsxRuntime.jsxs("h3", { children: [
2807
+ "Add credits \xB7 ",
2808
+ wallet.name || "Wallet"
2809
+ ] }),
2810
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "nzp-muted", children: "A paid top-up creates a billing transaction. Credits become available after payment is processed." }),
2811
+ /* @__PURE__ */ jsxRuntime.jsxs(
2812
+ "form",
2813
+ {
2814
+ onSubmit: (event) => {
2815
+ event.preventDefault();
2816
+ if (valid)
2817
+ void action.run(async (signal) => {
2818
+ await client.request(
2819
+ topUpMutation,
2820
+ { input: { walletId: wallet.id, paidCredits: credits } },
2821
+ signal
2822
+ );
2823
+ if (!signal.aborted) onCreated();
2824
+ });
2825
+ },
2826
+ children: [
2827
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "nzp-fields", children: /* @__PURE__ */ jsxRuntime.jsxs("label", { children: [
2828
+ "Credits to add",
2829
+ /* @__PURE__ */ jsxRuntime.jsx(
2830
+ "input",
2831
+ {
2832
+ inputMode: "decimal",
2833
+ maxLength: 36,
2834
+ required: true,
2835
+ value: credits,
2836
+ disabled: action.pending,
2837
+ onChange: (event) => setCredits(event.target.value)
2838
+ }
2839
+ )
2840
+ ] }) }),
2841
+ /* @__PURE__ */ jsxRuntime.jsxs("p", { children: [
2842
+ amountCents !== null ? money(amountCents, wallet.currency, locale) : "\u2014",
2843
+ " ",
2844
+ "excluding tax"
2845
+ ] }),
2846
+ wallet.paidTopUpMinAmountCents != null && /* @__PURE__ */ jsxRuntime.jsxs("p", { className: "nzp-muted", children: [
2847
+ "Minimum",
2848
+ " ",
2849
+ money(wallet.paidTopUpMinAmountCents, wallet.currency, locale)
2850
+ ] }),
2851
+ wallet.paidTopUpMaxAmountCents != null && /* @__PURE__ */ jsxRuntime.jsxs("p", { className: "nzp-muted", children: [
2852
+ "Maximum",
2853
+ " ",
2854
+ money(wallet.paidTopUpMaxAmountCents, wallet.currency, locale)
2855
+ ] }),
2856
+ action.error && /* @__PURE__ */ jsxRuntime.jsx(Failure, { error: action.error, reconnect }),
2857
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "nzp-actions", children: /* @__PURE__ */ jsxRuntime.jsx(
2858
+ "button",
2859
+ {
2860
+ type: "submit",
2861
+ className: "nzp-primary",
2862
+ disabled: !valid || action.pending,
2863
+ children: action.pending ? "Requesting\u2026" : "Confirm paid top-up"
2864
+ }
2865
+ ) })
2866
+ ]
2867
+ }
2868
+ )
2869
+ ] });
2870
+ }
2871
+ function usePlans() {
2872
+ const { client } = useBillingContext();
2873
+ const [plans, setPlans] = React.useState([]);
2874
+ const [isLoading, setIsLoading] = React.useState(true);
2875
+ React.useEffect(() => {
2876
+ let cancelled = false;
2877
+ if (!client) {
2878
+ setIsLoading(false);
2879
+ return;
2880
+ }
2881
+ void client.catalogFetch("/api/v1/plans").then(async (response) => {
2882
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
2883
+ const data = await response.json();
2884
+ if (!cancelled) setPlans(data.plans ?? []);
2885
+ }).finally(() => {
2886
+ if (!cancelled) setIsLoading(false);
2887
+ });
2888
+ return () => {
2889
+ cancelled = true;
2890
+ };
2891
+ }, [client]);
2892
+ return { plans, isLoading };
2893
+ }
2894
+ function useCheckout2() {
2895
+ const { createCheckout } = useBillingContext();
2896
+ const [isLoading, setIsLoading] = React.useState(false);
2897
+ const [error, setError] = React.useState(null);
2898
+ const [checkout, setCheckout] = React.useState(null);
2899
+ const fetchClientSecret = React.useCallback(
2900
+ async (planCode, returnUrl) => {
2901
+ setIsLoading(true);
2902
+ setError(null);
2903
+ try {
2904
+ if (!createCheckout) {
2905
+ throw new Error("BillingProvider createCheckout callback is required for checkout");
2906
+ }
2907
+ const result = await createCheckout({
2908
+ planCode,
2909
+ returnUrl: returnUrl ?? window.location.href
2910
+ });
2911
+ setCheckout(result);
2912
+ if ("client_secret" in result || "clientSecret" in result) {
2913
+ const clientSecret = result.client_secret ?? result.clientSecret;
2914
+ if (clientSecret) return clientSecret;
2915
+ }
2916
+ if ("url" in result && result.url) {
2917
+ navigateToCheckout(result.url);
2918
+ return null;
2919
+ }
2920
+ if ("type" in result && result.type === "hosted") {
2921
+ navigateToCheckout(result.payment_url);
2922
+ return null;
2923
+ }
2924
+ if ("type" in result && ["completed", "scheduled", "razorpay", "processing"].includes(result.type)) {
2925
+ return null;
2926
+ }
2927
+ throw new Error("Checkout response did not include a supported result type");
2928
+ } catch (cause) {
2929
+ const checkoutError = cause instanceof Error ? cause : new Error(String(cause));
2930
+ setError(checkoutError);
2931
+ throw checkoutError;
2932
+ } finally {
2933
+ setIsLoading(false);
2934
+ }
2935
+ },
2936
+ [createCheckout]
2937
+ );
2938
+ return { fetchClientSecret, checkout, isLoading, error };
251
2939
  }
252
2940
  var SYMBOLS = { USD: "$", EUR: "\u20AC", GBP: "\xA3", JPY: "\xA5" };
253
2941
  function fmtPrice(cents, cur) {
@@ -518,6 +3206,7 @@ function PricingTable({
518
3206
  const [currentPlan, setCurrentPlan] = React.useState(currentPlanCode ?? null);
519
3207
  const [isAnnual, setIsAnnual] = React.useState(false);
520
3208
  const [loading, setLoading] = React.useState(!propPlans);
3209
+ const [processing, setProcessing] = React.useState(false);
521
3210
  const [checkoutError, setCheckoutError] = React.useState(null);
522
3211
  React.useEffect(() => {
523
3212
  if (propPlans) {
@@ -560,7 +3249,14 @@ function PricingTable({
560
3249
  returnUrl: returnUrl ?? window.location.href
561
3250
  });
562
3251
  onCheckoutResult?.(result);
563
- await handleCheckoutResult(result, { onStripeClientSecret });
3252
+ await handleCheckoutResult(result, {
3253
+ onStripeClientSecret,
3254
+ verifyCheckout: billing?.verifyCheckout,
3255
+ getCheckoutStatus: billing?.getCheckoutStatus,
3256
+ onProcessing: () => setProcessing(true),
3257
+ onSuccess: () => setProcessing(false),
3258
+ onComplete: () => setProcessing(false)
3259
+ });
564
3260
  } catch (cause) {
565
3261
  const error = cause instanceof Error ? cause : new Error("Checkout failed");
566
3262
  setCheckoutError(error.message);
@@ -576,6 +3272,7 @@ function PricingTable({
576
3272
  background: C.bg
577
3273
  }, children: [
578
3274
  showToggle && hasAnnual && /* @__PURE__ */ jsxRuntime.jsx(Toggle, { isAnnual, onChange: setIsAnnual }),
3275
+ processing && /* @__PURE__ */ jsxRuntime.jsx("p", { role: "status", children: "Payment is processing. Confirmation may take a little while." }),
579
3276
  checkoutError && /* @__PURE__ */ jsxRuntime.jsx("p", { role: "alert", children: checkoutError }),
580
3277
  /* @__PURE__ */ jsxRuntime.jsx("div", { style: {
581
3278
  display: "grid",
@@ -846,278 +3543,12 @@ function PlanComparison({
846
3543
  }
847
3544
  );
848
3545
  }
849
- var CheckoutContext = React.createContext(null);
850
- function useCheckout2() {
851
- const ctx = React.useContext(CheckoutContext);
852
- if (ctx === null) {
853
- throw new Error("useCheckout must be used inside a <Checkout> component");
854
- }
855
- return ctx;
856
- }
857
- function buildStripeAppearance() {
858
- if (typeof document === "undefined") {
859
- return { theme: "stripe" };
860
- }
861
- const style = getComputedStyle(document.documentElement);
862
- const get = (prop, fallback) => style.getPropertyValue(prop).trim() || fallback;
863
- return {
864
- theme: "stripe",
865
- variables: {
866
- colorPrimary: get("--nozle-primary", "#16a34a"),
867
- colorBackground: get("--nozle-background", "#f8fafc"),
868
- colorText: get("--nozle-foreground", "#1e293b"),
869
- colorDanger: get("--nozle-destructive", "#dc2626"),
870
- borderRadius: get("--nozle-radius", "0.5rem"),
871
- fontFamily: "inherit"
872
- }
873
- };
874
- }
875
- function CheckoutInner({
876
- submitLabel,
877
- onSuccess,
878
- onError,
879
- onReady,
880
- className,
881
- style,
882
- returnUrl,
883
- children
884
- }) {
885
- const stripe = reactStripeJs.useStripe();
886
- const elements = reactStripeJs.useElements();
887
- const [isProcessing, setIsProcessing] = React.useState(false);
888
- const [error, setError] = React.useState(null);
889
- const [isReady, setIsReady] = React.useState(false);
890
- async function confirmPayment() {
891
- if (!stripe || !elements) return;
892
- setIsProcessing(true);
893
- setError(null);
894
- const result = await stripe.confirmPayment({
895
- elements,
896
- confirmParams: { return_url: returnUrl ?? window.location.href },
897
- redirect: "if_required"
898
- });
899
- setIsProcessing(false);
900
- if (result.error) {
901
- const err = new Error(result.error.message ?? "Payment failed");
902
- setError(err);
903
- onError?.(err);
904
- } else if (result.paymentIntent?.status === "succeeded") {
905
- onSuccess?.(result.paymentIntent.id);
906
- }
907
- }
908
- return /* @__PURE__ */ jsxRuntime.jsx(CheckoutContext.Provider, { value: { confirmPayment, isProcessing, error }, children: /* @__PURE__ */ jsxRuntime.jsxs("div", { className, style, children: [
909
- /* @__PURE__ */ jsxRuntime.jsx("style", { children: `@keyframes nozle-skeleton-pulse { 0%{background-position:200% 0} 100%{background-position:-200% 0} }` }),
910
- !isReady && /* @__PURE__ */ jsxRuntime.jsx(
911
- "div",
912
- {
913
- "data-testid": "checkout-skeleton",
914
- style: {
915
- height: "200px",
916
- borderRadius: "var(--nozle-radius, 0.5rem)",
917
- background: "linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%)",
918
- backgroundSize: "200% 100%",
919
- animation: "nozle-skeleton-pulse 1.5s ease-in-out infinite"
920
- }
921
- }
922
- ),
923
- /* @__PURE__ */ jsxRuntime.jsx(
924
- reactStripeJs.PaymentElement,
925
- {
926
- onReady: () => {
927
- setIsReady(true);
928
- onReady?.();
929
- }
930
- }
931
- ),
932
- error !== null && /* @__PURE__ */ jsxRuntime.jsx("p", { style: { color: "var(--nozle-destructive, #dc2626)", margin: "0.5rem 0 0" }, children: error.message }),
933
- children ?? /* @__PURE__ */ jsxRuntime.jsx(
934
- "button",
935
- {
936
- type: "button",
937
- onClick: () => void confirmPayment(),
938
- disabled: isProcessing || !stripe,
939
- "aria-busy": isProcessing,
940
- style: {
941
- padding: "0.75rem 1.5rem",
942
- borderRadius: "var(--nozle-radius, 0.5rem)",
943
- border: "none",
944
- background: "var(--nozle-primary, var(--primary))",
945
- color: "var(--nozle-primary-foreground, var(--primary-foreground))",
946
- cursor: isProcessing ? "not-allowed" : "pointer",
947
- fontWeight: 500,
948
- opacity: isProcessing ? 0.7 : 1,
949
- marginTop: "1rem",
950
- width: "100%"
951
- },
952
- children: isProcessing ? "Processing..." : submitLabel ?? "Pay now"
953
- }
954
- )
955
- ] }) });
956
- }
957
- function Checkout({
958
- clientSecret,
959
- publishableKey,
960
- stripeAccount,
961
- returnUrl,
962
- submitLabel,
963
- onSuccess,
964
- onComplete,
965
- onError,
966
- onReady,
967
- className,
968
- style,
969
- children
970
- }) {
971
- const stripePromise = React.useMemo(
972
- () => stripeJs.loadStripe(publishableKey, stripeAccount ? { stripeAccount } : void 0),
973
- [publishableKey, stripeAccount]
974
- );
975
- const appearance = React.useMemo(() => buildStripeAppearance(), []);
976
- const embeddedOptions = React.useMemo(
977
- () => ({ clientSecret, onComplete }),
978
- [clientSecret, onComplete]
979
- );
980
- if (clientSecret.startsWith("cs_")) {
981
- return /* @__PURE__ */ jsxRuntime.jsx("div", { className, style, children: /* @__PURE__ */ jsxRuntime.jsx(reactStripeJs.EmbeddedCheckoutProvider, { stripe: stripePromise, options: embeddedOptions, children: /* @__PURE__ */ jsxRuntime.jsx(reactStripeJs.EmbeddedCheckout, {}) }) });
982
- }
983
- const options = { clientSecret, appearance };
984
- return /* @__PURE__ */ jsxRuntime.jsx(reactStripeJs.Elements, { stripe: stripePromise, options, children: /* @__PURE__ */ jsxRuntime.jsx(
985
- CheckoutInner,
986
- {
987
- submitLabel,
988
- onSuccess,
989
- onError,
990
- onReady,
991
- className,
992
- style,
993
- returnUrl,
994
- children
995
- }
996
- ) }, clientSecret);
997
- }
998
- function UpgradeModal({
999
- isOpen,
1000
- planCode,
1001
- returnUrl,
1002
- preview,
1003
- onStripeClientSecret,
1004
- onCheckoutStarted,
1005
- onCompleted,
1006
- onScheduled,
1007
- onConfirm,
1008
- onCancel,
1009
- onError
1010
- }) {
1011
- const { createCheckout } = useBillingContext();
1012
- const [error, setError] = React.useState(null);
1013
- const [confirming, setConfirming] = React.useState(false);
1014
- async function handleConfirm() {
1015
- setConfirming(true);
1016
- setError(null);
1017
- try {
1018
- if (!createCheckout) {
1019
- throw new Error("BillingProvider createCheckout callback is required for checkout");
1020
- }
1021
- const result = await createCheckout({
1022
- planCode,
1023
- returnUrl: returnUrl ?? window.location.href
1024
- });
1025
- await handleCheckoutResult(result, {
1026
- onStripeClientSecret: (clientSecret) => {
1027
- onStripeClientSecret?.(clientSecret);
1028
- onCheckoutStarted?.();
1029
- },
1030
- onComplete: () => onCompleted?.(),
1031
- onScheduled: () => onScheduled?.()
1032
- });
1033
- onConfirm?.();
1034
- } catch (cause) {
1035
- const checkoutError = cause instanceof Error ? cause : new Error("Checkout failed");
1036
- setError(checkoutError.message);
1037
- onError?.(checkoutError);
1038
- } finally {
1039
- setConfirming(false);
1040
- }
1041
- }
1042
- if (!isOpen) return null;
1043
- return /* @__PURE__ */ jsxRuntime.jsx(
1044
- "div",
1045
- {
1046
- style: {
1047
- position: "fixed",
1048
- inset: 0,
1049
- background: "oklch(0 0 0 / 0.5)",
1050
- display: "flex",
1051
- alignItems: "center",
1052
- justifyContent: "center",
1053
- zIndex: 1e3
1054
- },
1055
- role: "dialog",
1056
- "aria-modal": "true",
1057
- "aria-label": "Change plan",
1058
- children: /* @__PURE__ */ jsxRuntime.jsxs(
1059
- "div",
1060
- {
1061
- style: {
1062
- background: "var(--nozle-background, var(--background))",
1063
- color: "var(--nozle-foreground, var(--foreground))",
1064
- border: "1px solid var(--nozle-border, var(--border))",
1065
- borderRadius: "var(--nozle-radius, 0.5rem)",
1066
- padding: "2rem",
1067
- maxWidth: "28rem",
1068
- width: "100%",
1069
- boxShadow: "var(--nozle-shadow, 0 4px 6px -1px rgb(0 0 0 / 0.1))"
1070
- },
1071
- children: [
1072
- /* @__PURE__ */ jsxRuntime.jsx("h2", { style: { fontSize: "1.25rem", fontWeight: 600, margin: "0 0 1rem" }, children: "Confirm plan change" }),
1073
- error && /* @__PURE__ */ jsxRuntime.jsx("p", { role: "alert", style: { color: "oklch(0.6 0.2 25)" }, children: error }),
1074
- preview && /* @__PURE__ */ jsxRuntime.jsxs("div", { style: { marginBottom: "1.5rem" }, children: [
1075
- /* @__PURE__ */ jsxRuntime.jsxs(
1076
- "div",
1077
- {
1078
- style: {
1079
- background: "var(--nozle-muted, var(--muted))",
1080
- borderRadius: "var(--nozle-radius, 0.5rem)",
1081
- padding: "1rem",
1082
- display: "flex",
1083
- flexDirection: "column",
1084
- gap: "0.5rem"
1085
- },
1086
- children: [
1087
- preview.credit > 0 && /* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
1088
- "Credits applied: -$",
1089
- preview.credit.toFixed(2)
1090
- ] }),
1091
- /* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
1092
- "New plan charge: $",
1093
- preview.debit.toFixed(2)
1094
- ] }),
1095
- /* @__PURE__ */ jsxRuntime.jsxs("strong", { children: [
1096
- "Due today: $",
1097
- preview.net.toFixed(2)
1098
- ] })
1099
- ]
1100
- }
1101
- ),
1102
- /* @__PURE__ */ jsxRuntime.jsxs("p", { style: { fontSize: "0.875rem" }, children: [
1103
- "Next billing date: ",
1104
- new Date(preview.nextBillingDate).toLocaleDateString(),
1105
- "."
1106
- ] })
1107
- ] }),
1108
- /* @__PURE__ */ jsxRuntime.jsxs("div", { style: { display: "flex", gap: "0.75rem", justifyContent: "flex-end" }, children: [
1109
- /* @__PURE__ */ jsxRuntime.jsx("button", { type: "button", onClick: onCancel, disabled: confirming, children: "Cancel" }),
1110
- /* @__PURE__ */ jsxRuntime.jsx("button", { type: "button", onClick: () => void handleConfirm(), disabled: confirming, children: confirming ? "Starting checkout..." : "Confirm" })
1111
- ] })
1112
- ]
1113
- }
1114
- )
1115
- }
1116
- );
1117
- }
1118
3546
  function UpgradeButton({
1119
3547
  planCode,
1120
3548
  returnUrl,
3549
+ subscriptionId,
3550
+ quoteId,
3551
+ idempotencyKey,
1121
3552
  preview,
1122
3553
  label = "Upgrade",
1123
3554
  className,
@@ -1155,6 +3586,9 @@ function UpgradeButton({
1155
3586
  isOpen,
1156
3587
  planCode,
1157
3588
  returnUrl,
3589
+ subscriptionId,
3590
+ quoteId,
3591
+ idempotencyKey,
1158
3592
  preview,
1159
3593
  onStripeClientSecret,
1160
3594
  onCheckoutStarted: () => {
@@ -1209,10 +3643,10 @@ function PlanGate({
1209
3643
  }
1210
3644
  function UpgradePrompt({
1211
3645
  text = "Upgrade to access this feature",
1212
- planName,
3646
+ planName: planName2,
1213
3647
  onUpgrade
1214
3648
  }) {
1215
- const displayText = planName ? `Upgrade to ${planName} to access this feature` : text;
3649
+ const displayText = planName2 ? `Upgrade to ${planName2} to access this feature` : text;
1216
3650
  function handleUpgrade() {
1217
3651
  if (onUpgrade) {
1218
3652
  onUpgrade();
@@ -1594,7 +4028,10 @@ function PaymentMethodDisplay({
1594
4028
  }
1595
4029
 
1596
4030
  exports.BillingContext = BillingContext;
4031
+ exports.BillingPortal = BillingPortal;
4032
+ exports.BillingPortalError = BillingPortalError;
1597
4033
  exports.BillingProvider = BillingProvider;
4034
+ exports.CancellationControl = CancellationControl;
1598
4035
  exports.Checkout = Checkout;
1599
4036
  exports.CheckoutButton = CheckoutButton;
1600
4037
  exports.FeatureGate = FeatureGate;
@@ -1602,6 +4039,7 @@ exports.LockedOverlay = LockedOverlay;
1602
4039
  exports.PaymentMethodDisplay = PaymentMethodDisplay;
1603
4040
  exports.PlanBadge = PlanBadge;
1604
4041
  exports.PlanCard = PlanCard;
4042
+ exports.PlanChangeControl = PlanChangeControl;
1605
4043
  exports.PlanComparison = PlanComparison;
1606
4044
  exports.PlanGate = PlanGate;
1607
4045
  exports.PricingTable = PricingTable;
@@ -1614,8 +4052,8 @@ exports.UsageGate = UsageGate;
1614
4052
  exports.UsageMeter = UsageMeter;
1615
4053
  exports.getUsageMeterColor = getUsageMeterColor;
1616
4054
  exports.useBillingContext = useBillingContext;
1617
- exports.useCheckout = useCheckout2;
1618
- exports.useCheckoutSession = useCheckout;
4055
+ exports.useCheckout = useCheckout;
4056
+ exports.useCheckoutSession = useCheckout2;
1619
4057
  exports.useNozleClient = useNozleClient;
1620
4058
  exports.useOptionalBillingContext = useOptionalBillingContext;
1621
4059
  exports.usePlans = usePlans;