@base44-preview/sdk 0.8.58-beta.0-pr.363.6724db0 → 0.8.58-beta.0-pr.366.dccfb00

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.d.ts CHANGED
@@ -14,7 +14,7 @@ export type { AppLogsModule } from "./modules/app-logs.types.js";
14
14
  export type { AppModule, AppPublicSettings, AppPublicSettingsResponse, } from "./modules/app.types.js";
15
15
  export type { ActorsModule, ActorClient, ActorRef, Connection, ActorSubscription, ActorConnectOptions, ActorNameRegistry, ActorRegistry, } from "./modules/actors.types.js";
16
16
  export type { SsoModule, SsoAccessTokenResponse } from "./modules/sso.types.js";
17
- export type { PaymentsModule, ServiceRolePaymentsModule, PaymentsErrorCode, PaymentsRecurringFrequency, CheckoutBuyer, CheckoutFreeTrial, CheckoutItem, CheckoutItemRecurring, CheckoutPresentation, CheckoutShipping, CheckoutElement, CheckoutMount, MountableCheckout, CreateCheckoutParams, CreateCheckoutResult, CompleteCheckoutResult, EmbeddedCheckout, PayPalEmbeddedCheckout, StripeEmbeddedCheckout, MountCheckoutOptions, ListPurchasesParams, ServiceRoleListPurchasesParams, ListPurchasesResult, Purchase, PurchaseItem, PurchaseStatus, RefundParams, ShippingAddress, RefundResult, CancelSubscriptionOptions, SubscriptionResult, } from "./modules/payments.types.js";
17
+ export type { PaymentsModule, ServiceRolePaymentsModule, PaymentsErrorCode, PaymentsRecurringFrequency, CheckoutBuyer, CheckoutFreeTrial, CheckoutItem, CheckoutItemRecurring, CheckoutPresentation, CheckoutShipping, CheckoutElement, CheckoutMount, MountableCheckout, CreateCheckoutParams, CreateCheckoutResult, CompleteCheckoutResult, EmbeddedCheckout, PayPalCheckoutOnClick, PayPalEmbeddedCheckout, StripeEmbeddedCheckout, MountCheckoutOptions, ListPurchasesParams, ServiceRoleListPurchasesParams, ListPurchasesResult, Purchase, PurchaseItem, PurchaseStatus, RefundParams, ShippingAddress, RefundResult, CancelSubscriptionOptions, SubscriptionResult, } from "./modules/payments.types.js";
18
18
  export type { BrowserModule, BrowserSession, BrowserSessionOptions, } from "./modules/browser.types.js";
19
19
  export { Actor, type Conn } from "./actor.js";
20
20
  export type { ConnectorsModule, UserConnectorsModule, ConnectorApiRequest, ConnectorApiResponse, ConnectorApiResponsePhase, } from "./modules/connectors.types.js";
@@ -6,9 +6,6 @@ export declare const ANALYTICS_INITIALIZATION_EVENT_NAME = "__initialization_eve
6
6
  export declare const ANALYTICS_SESSION_DURATION_EVENT_NAME = "__session_duration_event__";
7
7
  export declare const ANALYTICS_CONFIG_ENABLE_URL_PARAM_KEY = "analytics-enable";
8
8
  export declare const ANALYTICS_SESSION_ID_LOCAL_STORAGE_KEY = "base44_analytics_session_id";
9
- export declare const ANALYTICS_DENIED_LOCAL_STORAGE_KEY = "base44_analytics_denied";
10
- /** Whether a page in this mode may track before any consent signal. */
11
- export declare function initialConsentGranted(mode: string | null): boolean;
12
9
  export declare const ANALYTICS_MODE_META_NAME = "base44-analytics";
13
10
  /** Whether analytics may run and store the session id on this page. */
14
11
  export declare function isAnalyticsAllowed(): boolean;
@@ -5,37 +5,6 @@ export const ANALYTICS_INITIALIZATION_EVENT_NAME = "__initialization_event__";
5
5
  export const ANALYTICS_SESSION_DURATION_EVENT_NAME = "__session_duration_event__";
6
6
  export const ANALYTICS_CONFIG_ENABLE_URL_PARAM_KEY = "analytics-enable";
7
7
  export const ANALYTICS_SESSION_ID_LOCAL_STORAGE_KEY = "base44_analytics_session_id";
8
- // Remembers a visitor's Decline across pages. On "on" pages the SDK starts
9
- // before the app's banner replays the saved choice, so without it each new
10
- // page would store the id and send one batch before the denial arrives.
11
- export const ANALYTICS_DENIED_LOCAL_STORAGE_KEY = "base44_analytics_denied";
12
- function readAnalyticsDenied() {
13
- try {
14
- return localStorage.getItem(ANALYTICS_DENIED_LOCAL_STORAGE_KEY) === "1";
15
- }
16
- catch (_a) {
17
- return false;
18
- }
19
- }
20
- function writeAnalyticsDenied(denied) {
21
- try {
22
- if (denied)
23
- localStorage.setItem(ANALYTICS_DENIED_LOCAL_STORAGE_KEY, "1");
24
- else
25
- localStorage.removeItem(ANALYTICS_DENIED_LOCAL_STORAGE_KEY);
26
- }
27
- catch (_a) {
28
- // storage unavailable: the banner's replay still stops tracking
29
- }
30
- }
31
- /** Whether a page in this mode may track before any consent signal. */
32
- export function initialConsentGranted(mode) {
33
- if (mode === "consent")
34
- return false;
35
- if (mode === "on")
36
- return !readAnalyticsDenied();
37
- return true;
38
- }
39
8
  // Set by the Base44 server from the app owner's choice: "off" never tracks,
40
9
  // "consent" waits for the page's Google Consent Mode `analytics_storage` grant,
41
10
  // "on" tracks until that consent is denied. Absent: track as before.
@@ -92,7 +61,7 @@ const consentSharedState = getSharedInstance("analytics-consent", () => {
92
61
  return {
93
62
  analyticsMode,
94
63
  // Whether the visitor may be tracked and the session id stored.
95
- consentGranted: initialConsentGranted(analyticsMode),
64
+ consentGranted: analyticsMode !== "consent",
96
65
  isWatchingConsent: false,
97
66
  listeners: [],
98
67
  };
@@ -104,7 +73,6 @@ export function isAnalyticsAllowed() {
104
73
  }
105
74
  function setConsentGranted(granted) {
106
75
  var _a;
107
- writeAnalyticsDenied(!granted);
108
76
  if (consentSharedState.consentGranted === granted)
109
77
  return;
110
78
  consentSharedState.consentGranted = granted;
@@ -1,4 +1,4 @@
1
- import type { CheckoutElement, CheckoutMount, CompleteCheckoutResult, MountableCheckout, MountCheckoutOptions } from "./payments.types.js";
1
+ import type { CheckoutElement, CheckoutMount, CompleteCheckoutResult, MountableCheckout, MountCheckoutOptions, PayPalCheckoutOnClick, PayPalEmbeddedCheckout } from "./payments.types.js";
2
2
  /** @internal */
3
3
  export type LoadScript = (src: string) => Promise<void>;
4
4
  /**
@@ -8,11 +8,13 @@ export type LoadScript = (src: string) => Promise<void>;
8
8
  export interface PaymentsCheckoutConfig {
9
9
  paypal?: {
10
10
  script_url?: string;
11
+ button?: PayPalButtonConfig | null;
11
12
  };
12
13
  stripe?: {
13
14
  script_url?: string;
14
15
  };
15
16
  }
17
+ type PayPalButtonConfig = Pick<PayPalEmbeddedCheckout, "client_id" | "merchant_id" | "partner_attribution_id">;
16
18
  /** @internal */
17
19
  export interface MountCheckoutDeps {
18
20
  completeCheckout: (checkoutId: string) => Promise<CompleteCheckoutResult>;
@@ -33,4 +35,5 @@ export declare function preloadCheckout(provider: "paypal" | "stripe", deps: Pic
33
35
  * Mounts the embedded checkout that createCheckout() returned.
34
36
  * @internal
35
37
  */
36
- export declare function mountCheckout(element: CheckoutElement, checkout: MountableCheckout, options: MountCheckoutOptions, deps: MountCheckoutDeps): Promise<CheckoutMount>;
38
+ export declare function mountCheckout(element: CheckoutElement, checkout: MountableCheckout | PayPalCheckoutOnClick, options: MountCheckoutOptions, deps: MountCheckoutDeps): Promise<CheckoutMount>;
39
+ export {};
@@ -103,6 +103,8 @@ function mountStripe(element, scriptUrl, embedded, deps) {
103
103
  activeStripeCheckout = null;
104
104
  checkout.destroy();
105
105
  },
106
+ // Stripe's own form has no single button to disable.
107
+ setDisabled: () => undefined,
106
108
  };
107
109
  activeStripeCheckout = handle;
108
110
  return handle;
@@ -110,7 +112,9 @@ function mountStripe(element, scriptUrl, embedded, deps) {
110
112
  stripeQueue = mount.catch(() => undefined);
111
113
  return mount;
112
114
  }
113
- async function mountPayPal(element, scriptUrl, checkoutId, currency, embedded, options, deps) {
115
+ async function mountPayPal(element, scriptUrl, currency, embedded,
116
+ // A created checkout's id, or what an on-click checkout calls inside the click to create one.
117
+ checkout, options, deps) {
114
118
  var _a;
115
119
  const paypal = await loadGlobal(scriptUrl, () => browserGlobals().paypal, deps.loadScript);
116
120
  if (typeof paypal.createInstance !== "function") {
@@ -142,6 +146,10 @@ async function mountPayPal(element, scriptUrl, checkoutId, currency, embedded, o
142
146
  }
143
147
  let destroyed = false;
144
148
  let completing = false;
149
+ // Set once a payment goes through: another click would create and charge a second order.
150
+ let paid = false;
151
+ let starting = false;
152
+ let checkoutId = typeof checkout === "string" ? checkout : undefined;
145
153
  // App callbacks run only while mounted, and their own errors never reach PayPal or onError.
146
154
  const notify = (callback) => {
147
155
  if (destroyed)
@@ -161,6 +169,8 @@ async function mountPayPal(element, scriptUrl, checkoutId, currency, embedded, o
161
169
  button.disabled = true;
162
170
  let result;
163
171
  try {
172
+ if (!checkoutId)
173
+ throw new Error("PayPal approved a checkout that wasn't created");
164
174
  // Runs even after destroy(), so an approved payment is still captured.
165
175
  result = await deps.completeCheckout(checkoutId);
166
176
  }
@@ -172,6 +182,7 @@ async function mountPayPal(element, scriptUrl, checkoutId, currency, embedded, o
172
182
  return;
173
183
  }
174
184
  completing = false;
185
+ paid = true;
175
186
  notify(() => { var _a; return (_a = options.onComplete) === null || _a === void 0 ? void 0 : _a.call(options, result); });
176
187
  },
177
188
  onCancel() {
@@ -183,15 +194,26 @@ async function mountPayPal(element, scriptUrl, checkoutId, currency, embedded, o
183
194
  });
184
195
  button.setAttribute("type", subscription ? "subscribe" : "pay");
185
196
  const onClick = () => {
186
- if (completing)
197
+ if (paid || completing || starting || button.disabled)
187
198
  return;
199
+ starting = true;
188
200
  // Not awaited before start(), which must run inside the click to open PayPal's popup.
189
- const id = Promise.resolve(subscription ? { subscriptionId: checkoutId } : { orderId: checkoutId });
201
+ const id = Promise.resolve()
202
+ .then(typeof checkout === "string" ? () => checkout : checkout)
203
+ .then((resolved) => {
204
+ checkoutId = resolved;
205
+ return subscription ? { subscriptionId: resolved } : { orderId: resolved };
206
+ });
190
207
  const report = (error) => notify(() => { var _a; return (_a = options.onError) === null || _a === void 0 ? void 0 : _a.call(options, error); });
191
208
  try {
192
- Promise.resolve(session.start({ presentationMode: "auto" }, id)).catch(report);
209
+ Promise.resolve(session.start({ presentationMode: "auto" }, id))
210
+ .catch(report)
211
+ .finally(() => {
212
+ starting = false;
213
+ });
193
214
  }
194
215
  catch (error) {
216
+ starting = false;
195
217
  report(error);
196
218
  }
197
219
  };
@@ -207,6 +229,26 @@ async function mountPayPal(element, scriptUrl, checkoutId, currency, embedded, o
207
229
  button.remove();
208
230
  (_a = session.destroy) === null || _a === void 0 ? void 0 : _a.call(session);
209
231
  },
232
+ setDisabled(disabled) {
233
+ // A payment being completed, or already made, keeps the button off whatever the app asks.
234
+ if (!completing && !paid)
235
+ button.disabled = disabled;
236
+ },
237
+ };
238
+ }
239
+ /** The new checkout's id, refused unless it is the checkout the button was drawn for. */
240
+ function onClickCheckoutId(spec, button) {
241
+ return async () => {
242
+ var _a;
243
+ const checkout = await spec.createCheckout();
244
+ const embedded = checkout === null || checkout === void 0 ? void 0 : checkout.embedded;
245
+ if ((embedded === null || embedded === void 0 ? void 0 : embedded.provider) !== "paypal" ||
246
+ embedded.intent !== spec.intent ||
247
+ embedded.merchant_id !== button.merchant_id ||
248
+ ((_a = checkout.currency) === null || _a === void 0 ? void 0 : _a.toLowerCase()) !== spec.currency.toLowerCase()) {
249
+ throw new Error("createCheckout() returned a checkout that doesn't match the PayPal button. Check its provider, intent and currency.");
250
+ }
251
+ return checkout.checkout_id;
210
252
  };
211
253
  }
212
254
  /**
@@ -237,6 +279,9 @@ export async function mountCheckout(element, checkout, options, deps) {
237
279
  if (!element) {
238
280
  throw new Error("mountCheckout() requires an element to render in");
239
281
  }
282
+ if ("createCheckout" in checkout) {
283
+ return mountPayPalOnClick(element, checkout, options, deps);
284
+ }
240
285
  const embedded = checkout === null || checkout === void 0 ? void 0 : checkout.embedded;
241
286
  if (!embedded) {
242
287
  throw new Error("This checkout isn't embedded. Create it with presentation: 'embedded', or send the buyer to its redirect_url.");
@@ -245,8 +290,21 @@ export async function mountCheckout(element, checkout, options, deps) {
245
290
  case "stripe":
246
291
  return mountStripe(element, await scriptUrlFor("stripe", deps), embedded, deps);
247
292
  case "paypal":
248
- return mountPayPal(element, await scriptUrlFor("paypal", deps), checkout.checkout_id, checkout.currency, embedded, options, deps);
293
+ return mountPayPal(element, await scriptUrlFor("paypal", deps), checkout.currency, embedded, checkout.checkout_id, options, deps);
249
294
  default:
250
295
  throw new Error(`Embedded checkout isn't supported for provider ${embedded.provider}`);
251
296
  }
252
297
  }
298
+ async function mountPayPalOnClick(element, spec, options, deps) {
299
+ var _a, _b;
300
+ if (spec.provider !== "paypal" || typeof spec.createCheckout !== "function") {
301
+ throw new Error("Only PayPal can create its checkout on click");
302
+ }
303
+ const scriptUrl = await scriptUrlFor("paypal", deps);
304
+ const button = (_b = (_a = (await deps.getConfig())) === null || _a === void 0 ? void 0 : _a.paypal) === null || _b === void 0 ? void 0 : _b.button;
305
+ if (!(button === null || button === void 0 ? void 0 : button.client_id) || !button.merchant_id) {
306
+ throw new Error("PayPal isn't ready to take payments in this app yet");
307
+ }
308
+ const embedded = { provider: "paypal", ...button, intent: spec.intent };
309
+ return mountPayPal(element, scriptUrl, spec.currency, embedded, onClickCheckoutId(spec, button), options, deps);
310
+ }
@@ -350,12 +350,29 @@ export interface MountableCheckout {
350
350
  /** Data for the embedded checkout. Mounting rejects when it's `null`. */
351
351
  embedded: EmbeddedCheckout | null;
352
352
  }
353
+ /**
354
+ * A PayPal checkout that [`mountCheckout()`](#mountcheckout) creates when the buyer clicks PayPal's button. The button shows as soon as the page loads, the buyer clicks once, and no order is created until they do.
355
+ */
356
+ export interface PayPalCheckoutOnClick {
357
+ /** Payment provider. Only PayPal can create its checkout on click. */
358
+ provider: "paypal";
359
+ /** Three-letter ISO currency code the checkout uses, such as `'usd'`. */
360
+ currency: string;
361
+ /** Whether the checkout is a one-time payment or a subscription. */
362
+ intent: "capture" | "subscription";
363
+ /**
364
+ * Creates the checkout when the buyer clicks, usually by calling the backend function that calls {@linkcode ServiceRolePaymentsModule.createCheckout | createCheckout()}. Resolve with its result. Reject to stop, for example when a required form field is empty: PayPal's window closes and `onError` receives the error.
365
+ */
366
+ createCheckout: () => Promise<MountableCheckout>;
367
+ }
353
368
  /**
354
369
  * A mounted embedded checkout.
355
370
  */
356
371
  export interface CheckoutMount {
357
372
  /** Removes the checkout from the page. Call it when the component that holds it unmounts. For Stripe, mounting another checkout destroys this one for you. */
358
373
  destroy: () => void;
374
+ /** PayPal: greys out the button and ignores clicks, for example until a required form is filled in. After a payment completes the button stays off, so `setDisabled(false)` can't start a second payment. Stripe ignores it. */
375
+ setDisabled: (disabled: boolean) => void;
359
376
  }
360
377
  /**
361
378
  * Payments module for accepting one-time payments and subscriptions in your app through its connected payment provider.
@@ -416,12 +433,14 @@ export interface PaymentsModule {
416
433
  *
417
434
  * To make the checkout appear faster, load the library ahead of time with [`preloadCheckout()`](#preloadcheckout) when the page opens.
418
435
  *
419
- * Requires a browser environment and can't be used in the backend. Rejects when the checkout isn't embedded, when the payments config can't be fetched or has no valid script URL for the provider, when the provider's library fails to load, or when PayPal isn't available for the checkout's currency.
436
+ * For PayPal, pass a {@linkcode PayPalCheckoutOnClick} instead of a created checkout to show PayPal's button right away and create the checkout only when the buyer clicks it. The buyer clicks once, and page views create no orders.
437
+ *
438
+ * Requires a browser environment and can't be used in the backend. Rejects when the checkout isn't embedded, when an on-click PayPal checkout is mounted before the app's PayPal can take payments, when the payments config can't be fetched or has no valid script URL for the provider, when the provider's library fails to load, or when PayPal isn't available for the checkout's currency.
420
439
  *
421
440
  * The checkout's callbacks run in the buyer's browser, where they can be faked. Grant access to what the buyer paid for only after your backend confirms the purchase, for example with [`listPurchases()`](#service-role-methods) in a backend function.
422
441
  *
423
442
  * @param element - Element to render the checkout in. It should be empty.
424
- * @param checkout - The result of {@linkcode ServiceRolePaymentsModule.createCheckout | createCheckout()}.
443
+ * @param checkout - The result of {@linkcode ServiceRolePaymentsModule.createCheckout | createCheckout()}, or for PayPal a {@linkcode PayPalCheckoutOnClick} that creates it when the buyer clicks.
425
444
  * @param options - Callbacks for the checkout's outcome.
426
445
  * @returns Promise resolving to the mounted checkout once it renders.
427
446
  *
@@ -445,6 +464,25 @@ export interface PaymentsModule {
445
464
  * ```
446
465
  *
447
466
  * @example
467
+ * ```typescript
468
+ * // PayPal: show the button on page load and create the checkout on click
469
+ * const mount = await base44.payments.mountCheckout(
470
+ * document.getElementById('paypal')!,
471
+ * {
472
+ * provider: 'paypal',
473
+ * currency: 'usd',
474
+ * intent: 'capture',
475
+ * createCheckout: async () =>
476
+ * (await base44.functions.invoke('createCheckout', { productId })).data,
477
+ * },
478
+ * { onComplete: ({ checkout_id }) => confirmPurchase(checkout_id) }
479
+ * );
480
+ *
481
+ * // Grey out the button until the shipping form is valid
482
+ * mount.setDisabled(!formIsValid);
483
+ * ```
484
+ *
485
+ * @example
448
486
  * ```tsx
449
487
  * // React component
450
488
  * function Checkout({ checkout }: { checkout: CreateCheckoutResult }) {
@@ -467,7 +505,7 @@ export interface PaymentsModule {
467
505
  * }
468
506
  * ```
469
507
  */
470
- mountCheckout(element: CheckoutElement, checkout: MountableCheckout, options?: MountCheckoutOptions): Promise<CheckoutMount>;
508
+ mountCheckout(element: CheckoutElement, checkout: MountableCheckout | PayPalCheckoutOnClick, options?: MountCheckoutOptions): Promise<CheckoutMount>;
471
509
  /**
472
510
  * Completes a PayPal checkout after the buyer approves it.
473
511
  *
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@base44-preview/sdk",
3
- "version": "0.8.58-beta.0-pr.363.6724db0",
3
+ "version": "0.8.58-beta.0-pr.366.dccfb00",
4
4
  "description": "JavaScript SDK for Base44 API",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",