@bestcheckout/dynamic-component-cli 0.1.0 → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +398 -9
- package/package.json +1 -1
- package/templates/starter/README.md +2 -0
package/README.md
CHANGED
|
@@ -2,6 +2,27 @@
|
|
|
2
2
|
|
|
3
3
|
Create and develop custom React components for BestCheckout's Checkout, Upsell, Downsell and Thank You pages. The CLI includes project generation, a local Dev Server with HMR, validation and single-file production builds. It works without the Admin, Shop Visual or old Dev Server source repositories.
|
|
4
4
|
|
|
5
|
+
This README is the public development guide for the CLI and dynamic components. The Editor links here from **Component source → Guide**.
|
|
6
|
+
|
|
7
|
+
- [Requirements](#requirements)
|
|
8
|
+
- [Quick start and Editor preview](#quick-start)
|
|
9
|
+
- [Global installation](#optional-global-installation)
|
|
10
|
+
- [Archive installation](#install-from-a-supplied-tgz)
|
|
11
|
+
- [Project files and additional components](#project-files-and-additional-components)
|
|
12
|
+
- [Component contract and schema](#component-development)
|
|
13
|
+
- [Complete Checkout example](#complete-checkout-example)
|
|
14
|
+
- [Runtime API](#runtime-usage)
|
|
15
|
+
- [Common capabilities](#common-runtime-capabilities)
|
|
16
|
+
- [Checkout](#checkout-runtime)
|
|
17
|
+
- [Upsell and Downsell](#upsell-and-downsell-runtime)
|
|
18
|
+
- [Thank You](#thank-you-runtime)
|
|
19
|
+
- [Styles and imports](#styles-imports-and-runtime-limits)
|
|
20
|
+
- [Save, Publish and shared components](#local-preview-save-and-publish)
|
|
21
|
+
- [Validation checklist](#validation-checklist)
|
|
22
|
+
- [CLI commands](#commands)
|
|
23
|
+
- [Troubleshooting](#troubleshooting)
|
|
24
|
+
- [Upgrade](#upgrade)
|
|
25
|
+
|
|
5
26
|
## Requirements
|
|
6
27
|
|
|
7
28
|
- Node.js >=20.10 and npm. The package has been tested on macOS with Node 22.22.1 and 24.14.1; the minimum Node version, Windows and Linux have not yet been verified.
|
|
@@ -11,7 +32,7 @@ Create and develop custom React components for BestCheckout's Checkout, Upsell,
|
|
|
11
32
|
|
|
12
33
|
## Quick start
|
|
13
34
|
|
|
14
|
-
|
|
35
|
+
The public package is available from npm. Run:
|
|
15
36
|
|
|
16
37
|
```bash
|
|
17
38
|
npx @bestcheckout/dynamic-component-cli@latest init my-components --component-id checkout-card --page-type checkout
|
|
@@ -21,7 +42,7 @@ npx playwright install chromium
|
|
|
21
42
|
npm run dev
|
|
22
43
|
```
|
|
23
44
|
|
|
24
|
-
Use a new or empty project directory. No global CLI installation is required.
|
|
45
|
+
Use a new or empty project directory. No global CLI installation is required. Replace `@latest` with a specific published version when your team needs a reproducible starter.
|
|
25
46
|
|
|
26
47
|
The terminal prints each component's Local URL. For the example above on the default port, it is:
|
|
27
48
|
|
|
@@ -42,6 +63,20 @@ Use the exact URL printed by your server. The source URL is a module for the Edi
|
|
|
42
63
|
|
|
43
64
|
The CLI does not log in to Admin, call resource CRUD APIs or publish templates. These actions remain in the Editor. Local URLs are development inputs and are not the production component source.
|
|
44
65
|
|
|
66
|
+
### Optional global installation
|
|
67
|
+
|
|
68
|
+
```bash
|
|
69
|
+
npm install --global @bestcheckout/dynamic-component-cli@latest --registry=https://registry.npmjs.org/
|
|
70
|
+
dynamic-component --version
|
|
71
|
+
dynamic-component init my-components --component-id checkout-card --page-type checkout
|
|
72
|
+
cd my-components
|
|
73
|
+
npm install
|
|
74
|
+
npx playwright install chromium
|
|
75
|
+
npm run dev
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
Use either this flow or the `npx` quick start. Both generate a project with its own pinned CLI dependency; upgrading the global CLI does not upgrade an existing project.
|
|
79
|
+
|
|
45
80
|
## Install from a supplied .tgz
|
|
46
81
|
|
|
47
82
|
No source checkout is needed. Replace both archive paths with the actual downloaded file:
|
|
@@ -54,7 +89,7 @@ npx playwright install chromium
|
|
|
54
89
|
npm run dev
|
|
55
90
|
```
|
|
56
91
|
|
|
57
|
-
`--cli-package` copies the archive into `vendor/` and installs that copy instead of fetching
|
|
92
|
+
`--cli-package` copies the archive into `vendor/` and installs that copy instead of fetching the CLI from npm. Keep `vendor/` with this project. Installed third-party dependencies still require registry access; a `.tgz` is not a fully offline dependency bundle.
|
|
58
93
|
|
|
59
94
|
## Project files and additional components
|
|
60
95
|
|
|
@@ -83,22 +118,356 @@ Restart `npm run dev` after adding a component or changing `dynamic.config.json`
|
|
|
83
118
|
- `dynamic.config.json` registers local entry files. Keep its component ID and page type consistent with each exported `manifest`; mismatches fail validation.
|
|
84
119
|
- Upsell/Downsell starters declare `capabilities.offerRecommendation`. Configure their recommendation rules in the Editor before saving/publishing the offer template.
|
|
85
120
|
|
|
86
|
-
## Component
|
|
121
|
+
## Component development
|
|
122
|
+
|
|
123
|
+
### Supported pages and component contract
|
|
124
|
+
|
|
125
|
+
The CLI supports four page types:
|
|
87
126
|
|
|
88
|
-
|
|
127
|
+
| Page type | Runtime entry | Typical capabilities |
|
|
128
|
+
| --- | --- | --- |
|
|
129
|
+
| `checkout` | `runtime.checkout` | Contact, address, delivery, discounts, payment and checkout submission |
|
|
130
|
+
| `upsell` | `runtime.offer` | Recommendations, repricing, accepting an offer and continuing the flow |
|
|
131
|
+
| `downsell` | `runtime.offer` | The same offer contract with the downsell page context |
|
|
132
|
+
| `thankYou` | `runtime.order` | Read-only order data, refresh and order navigation |
|
|
133
|
+
|
|
134
|
+
A component exports a default definition containing `manifest`, `schema`, `defaultSettings`, `Component` and optional `styles`. The complete example below shows a usable definition.
|
|
135
|
+
|
|
136
|
+
- `manifest.componentId` is 1–64 lowercase letters, numbers, `_` or `-`. It identifies shared code within a theme.
|
|
137
|
+
- `manifest.name` is the non-empty display name shown in the Editor, up to 128 Unicode characters.
|
|
138
|
+
- `manifest.supportedPageTypes` limits where the component can be selected. Omission means all four pages; an empty array means none. It does not grant runtime capabilities.
|
|
139
|
+
- `manifest.capabilities.offerRecommendation` must be `true` for an Upsell/Downsell component that provides the page's product recommendation rule. The Editor uses the first rule provider in template order, including hidden sections.
|
|
140
|
+
- `schema` is an array of Editor fields. Use `[]` when there are no settings.
|
|
141
|
+
- `defaultSettings` supplies values for new instances. It does not overwrite values already configured by a merchant.
|
|
142
|
+
- `Component` receives `{ settings, runtime, context }`.
|
|
143
|
+
- `styles` is an optional CSS string. Use component-owned class names; the platform scopes styles per instance.
|
|
144
|
+
|
|
145
|
+
`context` provides `themeId`, `pageType`, `sectionId`, optional `handle` and `shopId`, plus mode and device. Use the injected identity rather than constructing your own. `context.mode` is `editor`, `preview`, `live` or `storefront`; `context.device` is `desktop` or `mobile`. Components run in the browser. They do not provide their own SSR HTML.
|
|
146
|
+
|
|
147
|
+
### Editor schema and settings
|
|
148
|
+
|
|
149
|
+
Schema fields use the same field types as the Editor configuration panel:
|
|
89
150
|
|
|
90
151
|
```ts
|
|
91
|
-
|
|
152
|
+
const schema = [
|
|
153
|
+
{ key: "title", type: "text", label: "Title", required: true },
|
|
154
|
+
{
|
|
155
|
+
key: "layout",
|
|
156
|
+
type: "select",
|
|
157
|
+
label: "Layout",
|
|
158
|
+
options: [
|
|
159
|
+
{ label: "Horizontal", value: "horizontal" },
|
|
160
|
+
{ label: "Stacked", value: "stacked" },
|
|
161
|
+
],
|
|
162
|
+
},
|
|
163
|
+
{ key: "showBadge", type: "toggle", label: "Show badge" },
|
|
164
|
+
];
|
|
165
|
+
|
|
166
|
+
const defaultSettings = {
|
|
167
|
+
title: "Recommended products",
|
|
168
|
+
layout: "horizontal",
|
|
169
|
+
showBadge: true,
|
|
170
|
+
};
|
|
92
171
|
```
|
|
93
172
|
|
|
94
|
-
Supported
|
|
173
|
+
Supported field families include `text`, `textarea`, `url`, `date`, `number`, `range`, `select`, `radio`, `segmented`, `toggle`, `color`, `image`, `video`, `product`, `collection`, `menu`, `blog` and `page`. Resource fields save stable references; handle an unselected value and do not treat a reference as complete product, collection or order data. Number/range fields can use `min`, `max` and `step`; choice fields use `options`. Custom Editor controls, nested arrays and `richtext`, `html` or `css` fields are not supported.
|
|
174
|
+
|
|
175
|
+
Read settings defensively. A schema change must remain compatible with instances already saved in templates: add fields with defaults, and review every template before removing a field, changing its type or narrowing its options. Do not store hydrated business data, picker labels, Editor selection state or transient loading state in settings.
|
|
176
|
+
|
|
177
|
+
### Complete Checkout example
|
|
178
|
+
|
|
179
|
+
Replace `src/checkout-card/component.tsx` with this definition. The manifest ID and page must match `dynamic.config.json`. This example reads checkout data and updates when the Host publishes a new snapshot.
|
|
180
|
+
|
|
181
|
+
```tsx
|
|
182
|
+
import { useCallback, useSyncExternalStore } from "react";
|
|
183
|
+
import type {
|
|
184
|
+
DynamicComponentDefinition,
|
|
185
|
+
DynamicComponentProps,
|
|
186
|
+
} from "@bestcheckout/dynamic-component-cli/types";
|
|
187
|
+
|
|
188
|
+
function Component({ settings, runtime }: DynamicComponentProps) {
|
|
189
|
+
const checkout = runtime.checkout;
|
|
190
|
+
const subscribe = useCallback(
|
|
191
|
+
(notify: () => void) => checkout?.subscribe(() => notify()) ?? (() => {}),
|
|
192
|
+
[checkout],
|
|
193
|
+
);
|
|
194
|
+
const getSnapshot = useCallback(() => checkout?.getSnapshot(), [checkout]);
|
|
195
|
+
const snapshot = useSyncExternalStore(subscribe, getSnapshot);
|
|
196
|
+
|
|
197
|
+
return (
|
|
198
|
+
<section className="checkout-card">
|
|
199
|
+
<h2>{String(settings.title ?? "")}</h2>
|
|
200
|
+
{!snapshot ? (
|
|
201
|
+
<p>Checkout data is unavailable on this page.</p>
|
|
202
|
+
) : snapshot.status.dataStatus !== "ready" ? (
|
|
203
|
+
<p role="status">Checkout data is not ready. Please try again.</p>
|
|
204
|
+
) : (
|
|
205
|
+
<p>Contact email: {snapshot.contact.email || "Not provided"}</p>
|
|
206
|
+
)}
|
|
207
|
+
</section>
|
|
208
|
+
);
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
export default {
|
|
212
|
+
manifest: {
|
|
213
|
+
componentId: "checkout-card",
|
|
214
|
+
name: "Checkout information",
|
|
215
|
+
supportedPageTypes: ["checkout"],
|
|
216
|
+
},
|
|
217
|
+
schema: [{ key: "title", type: "text", label: "Title", required: true }],
|
|
218
|
+
defaultSettings: { title: "Confirm your checkout details" },
|
|
219
|
+
styles: `
|
|
220
|
+
.checkout-card { padding: 20px; border: 1px solid #ddd; border-radius: 8px; }
|
|
221
|
+
.checkout-card h2 { margin: 0 0 12px; font-size: 20px; }
|
|
222
|
+
.checkout-card p { margin: 0; overflow-wrap: anywhere; }
|
|
223
|
+
@media (max-width: 600px) { .checkout-card { padding: 16px; } }
|
|
224
|
+
`,
|
|
225
|
+
Component,
|
|
226
|
+
} satisfies DynamicComponentDefinition;
|
|
227
|
+
```
|
|
228
|
+
|
|
229
|
+
### Runtime usage
|
|
230
|
+
|
|
231
|
+
Import public types from the installed package:
|
|
232
|
+
|
|
233
|
+
```ts
|
|
234
|
+
import type {
|
|
235
|
+
DynamicComponentProps,
|
|
236
|
+
DynamicRuntime,
|
|
237
|
+
} from "@bestcheckout/dynamic-component-cli/types";
|
|
238
|
+
```
|
|
239
|
+
|
|
240
|
+
Runtime capabilities are optional. Check the page capability and handle `undefined` or `unavailable` states. Snapshots are read-only. Use `getSnapshot()` for the current value and `subscribe(listener)` for updates; always return the unsubscribe function and clean it up when the component unmounts. In React, `useSyncExternalStore` is the recommended subscription pattern; return the existing snapshot rather than allocating a new object on every read. Components share page business state while keeping their own settings and UI state. Preview uses simulated business data and cannot prove a real payment flow; Storefront uses actual Host data. There is no component `dataRequirements` contract or component SSR step.
|
|
241
|
+
|
|
242
|
+
Do not access Admin APIs, private Storefront clients, payment SDK internals, platform Stores or local storage. Do not pass prices, payment tokens, order IDs or credentials back through component settings. Server responses are authoritative for prices, inventory, discounts, order status and payment outcomes. Never replace missing amounts/currency with zero/USD or infer payment success from missing data.
|
|
243
|
+
|
|
244
|
+
- Common actions, Order actions and Checkout business actions return `ok`; handle `code`, `message` and applicable `errors` on failure.
|
|
245
|
+
- Checkout validation returns `valid`; synchronous setters remain synchronous.
|
|
246
|
+
- Catch exceptions from payment mounts and Offer asynchronous actions. Offer actions use `status`, not `ok`.
|
|
247
|
+
- Disable duplicate operations while pending, ignore stale responses after selection changes/unmount, and clean up subscriptions, timers and mounts.
|
|
248
|
+
|
|
249
|
+
The types shipped with your installed CLI are the reference for full parameter and result shapes; use IDE autocomplete rather than copying private Host types.
|
|
250
|
+
|
|
251
|
+
#### Common runtime capabilities
|
|
252
|
+
|
|
253
|
+
| Capability | Methods |
|
|
254
|
+
| --- | --- |
|
|
255
|
+
| `runtime.page` | Read-only page context |
|
|
256
|
+
| `runtime.brand?` | `name`, `logoUrl`, `logoAlt` |
|
|
257
|
+
| `runtime.navigation?` | `navigate({ url, target? })`; destination starts with `/` or is an absolute HTTP(S) URL; target is `_self` or `_blank` |
|
|
258
|
+
| `runtime.account?` | `getSnapshot()`, `subscribe(listener)`, optional `open()`, `login()`, `logout()`; status is `loading / signed_out / signed_in / error` |
|
|
259
|
+
| `runtime.cart?` | `getSnapshot()`, `subscribe(listener)`, optional `addItem({ productId, variantId?, quantity })`, `open()`; snapshot includes quantity, amount, currency, `isLoading` and `error` |
|
|
260
|
+
|
|
261
|
+
Common actions return `{ ok: true }` or `{ ok: false, code, message? }`, with `code` of `unavailable / invalid_destination / blocked / failed`. Cart data is not order data; checkout add-ons use `checkout.upsell`. The platform may omit a capability because of page type or shop configuration. Do not create a private fallback client. There is no public `runtime.currency`; read currency from the page snapshot that owns the amount.
|
|
262
|
+
|
|
263
|
+
#### Checkout runtime
|
|
264
|
+
|
|
265
|
+
`runtime.checkout.getSnapshot()` includes `contact`, read-only `lines`, optional `summary`, `currency`, `delivery`, `billing`, `shipping`, `coupon`, `payment` and `status`. `status.dataStatus` is `loading / ready / error / unknown`; `canSubmit` allows an attempt, while `blockedReasons` explains why it is blocked. The Host still revalidates on submission. Available actions:
|
|
266
|
+
|
|
267
|
+
| Area | Methods |
|
|
268
|
+
| --- | --- |
|
|
269
|
+
| Contact | `contact.getState()`, `contact.setEmail(email)`, `contact.validate()` |
|
|
270
|
+
| Current-instance add-ons | `upsell.getProduct(productId)`, `getSelections()`, `setSelection({ productId, variantId?, quantity })`, `remove(productId)` |
|
|
271
|
+
| Delivery address | `delivery.getState()`, `setField({ field, value })`, `validateField(field)`, `setCountry(id)`, `setState(id)`, `setCity(id)` |
|
|
272
|
+
| Saved addresses | `delivery.selectSavedAddress(id)`, `useNewAddress()`, `openNewAddress?()`, `editSavedAddress(id)`, `deleteSavedAddress(id)` |
|
|
273
|
+
| Billing address | `billing.getState()`, `setField({ field, value })`, `validateField(field)`, `setCountry(id)`, `setState(id)`, `setCity(id)`, `setSameAsShipping(boolean)` |
|
|
274
|
+
| Address autocomplete (optional) | `delivery.autocomplete?` and `billing.autocomplete?`: `search(query)`, `apply(suggestionId)`, `cancel()` |
|
|
275
|
+
| Shipping | `shipping.getState()`, `shipping.selectRate(id)` |
|
|
276
|
+
| Discounts | `coupon.getState()`, `coupon.apply(code)`, `coupon.remove(code)` |
|
|
277
|
+
| Payment | `payment.getState()`, `selectMethod(method)`, `mountSecureElement({ element, method })`, `mountAction({ element, method })` |
|
|
278
|
+
| Express payment | `express.mount({ element })` |
|
|
279
|
+
| Validation and submit | `validation.validateAll()`, `submit()` |
|
|
280
|
+
|
|
281
|
+
Methods without a prefix belong to the object at the beginning of the row. Address fields are `country / firstName / lastName / address / apartment / state / stateInput / city / cityInput / zip / phone`. Region IDs come from the current snapshot options. A successful address-dialog action means the dialog opened, not that an address was saved.
|
|
282
|
+
|
|
283
|
+
The add-on `quantity` is the target quantity for that component instance, not an increment. `lines` does not expose a way to mutate original checkout lines. IDs and options must come from the current snapshot or resource configuration; never submit a price or amount from the component.
|
|
284
|
+
|
|
285
|
+
`validation.validateAll()` returns `{ valid, errors }`, with `field / path / message` errors. It only validates and never charges. `submit()` returns an `{ ok: true }` or `{ ok: false, code, errors, message?, blockedReasons? }` result. Payment mounts return an `unmount()` handle; call it during cleanup. Do not mount a second secure form for the same payment method while the built-in payment UI is active.
|
|
286
|
+
|
|
287
|
+
Shipping state can be `waiting_address`, `loading`, `available`, `empty` or `error`. Successful coupon outcomes are `applied / replaced_better / kept_better / removed`; use each entry’s `removable` flag in `coupon.applied` to decide whether to show Remove. Treat errors as user-visible states and prevent duplicate submissions while an action is pending.
|
|
288
|
+
|
|
289
|
+
A coupon action can be wrapped in `src/actions.ts` and called from a button handler:
|
|
290
|
+
|
|
291
|
+
```ts
|
|
292
|
+
import type { DynamicRuntime } from "@bestcheckout/dynamic-component-cli/types";
|
|
293
|
+
|
|
294
|
+
export async function applyCoupon(runtime: DynamicRuntime, code: string): Promise<string> {
|
|
295
|
+
if (!runtime.checkout) return "Discount codes are unavailable on this page.";
|
|
296
|
+
try {
|
|
297
|
+
const result = await runtime.checkout.coupon.apply(code);
|
|
298
|
+
if (!result.ok) return result.message || "Could not apply this code. Please retry.";
|
|
299
|
+
return result.outcome === "kept_better"
|
|
300
|
+
? "The better discount was kept."
|
|
301
|
+
: "Discount updated.";
|
|
302
|
+
} catch {
|
|
303
|
+
return "The action is unavailable. Please retry.";
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
```
|
|
307
|
+
|
|
308
|
+
Payment method IDs come from `snapshot.payment.methods`. Render only the methods actually provided by the Host:
|
|
309
|
+
|
|
310
|
+
| Method | Integration |
|
|
311
|
+
| --- | --- |
|
|
312
|
+
| Card | `payment.mountSecureElement` for the form, then `checkout.submit()` |
|
|
313
|
+
| Klarna | `payment.mountSecureElement` with `payment.mountAction`, or a supported custom submit button |
|
|
314
|
+
| PayPal | `payment.mountAction` for the native authorization button; do not use `checkout.submit()` |
|
|
315
|
+
| Express | `checkout.express.mount` for the native express controls |
|
|
316
|
+
|
|
317
|
+
Check the result of `payment.selectMethod(method)` before mounting. Secure-element handles also expose `validate()`. Keep mount containers stable across input, address and quote updates. Catch mount failures and show an unavailable state without an automatic retry loop. Components must not read or persist card numbers, CVV or payment tokens. Use this wrapper as `src/SecurePaymentForm.tsx`, passing a currently supported secure-form method:
|
|
318
|
+
|
|
319
|
+
```tsx
|
|
320
|
+
import { useEffect, useRef, useState } from "react";
|
|
321
|
+
import type { DynamicCheckoutRuntime } from "@bestcheckout/dynamic-component-cli/types";
|
|
322
|
+
|
|
323
|
+
export function SecurePaymentForm({ checkout, method }: {
|
|
324
|
+
checkout?: DynamicCheckoutRuntime;
|
|
325
|
+
method: string;
|
|
326
|
+
}) {
|
|
327
|
+
const container = useRef<HTMLDivElement>(null);
|
|
328
|
+
const [error, setError] = useState("");
|
|
329
|
+
|
|
330
|
+
useEffect(() => {
|
|
331
|
+
const element = container.current;
|
|
332
|
+
if (!checkout || !element || !method) {
|
|
333
|
+
setError("Payment form is unavailable.");
|
|
334
|
+
return;
|
|
335
|
+
}
|
|
336
|
+
let cancelled = false;
|
|
337
|
+
let unmount: (() => void) | undefined;
|
|
338
|
+
setError("");
|
|
339
|
+
void checkout.payment.mountSecureElement({ element, method }).then(
|
|
340
|
+
(handle) => {
|
|
341
|
+
if (cancelled) handle.unmount();
|
|
342
|
+
else unmount = () => handle.unmount();
|
|
343
|
+
},
|
|
344
|
+
() => { if (!cancelled) setError("Payment form failed to load."); },
|
|
345
|
+
);
|
|
346
|
+
return () => {
|
|
347
|
+
cancelled = true;
|
|
348
|
+
unmount?.();
|
|
349
|
+
};
|
|
350
|
+
}, [checkout, method]);
|
|
351
|
+
|
|
352
|
+
return (
|
|
353
|
+
<div>
|
|
354
|
+
<div ref={container} />
|
|
355
|
+
{error && <p role="alert">{error}</p>}
|
|
356
|
+
</div>
|
|
357
|
+
);
|
|
358
|
+
}
|
|
359
|
+
```
|
|
360
|
+
|
|
361
|
+
This only manages the form lifecycle. It does not submit or indicate successful payment. If a mount resolves after cleanup, the returned handle is immediately released. Do not remount on each snapshot update.
|
|
362
|
+
|
|
363
|
+
#### Upsell and Downsell runtime
|
|
364
|
+
|
|
365
|
+
`runtime.offer.getSnapshot()` provides recommendations, currency, order confirmation and optional transaction/continuation state. The primary methods are:
|
|
366
|
+
|
|
367
|
+
- `reprice?(input)` obtains the current server quote for a recommendation, variant, quantity and optional purchase option.
|
|
368
|
+
- `accept?(input)` accepts the currently quoted offer. A successful Promise does not by itself mean payment succeeded; inspect the returned status.
|
|
369
|
+
- `getPaymentStatus?(recommendationId)` reads an existing payment status without creating a new charge.
|
|
370
|
+
- `getPaymentAttempt?(recommendationId)` reads an existing payment attempt when available.
|
|
371
|
+
- `leaveAndContinue?()` continues the host-controlled post-purchase flow, resolving to `void` on success and rejecting on failure or when blocked.
|
|
372
|
+
|
|
373
|
+
`reprice` and `accept` use this input shape; IDs and purchase options come from the recommendation snapshot:
|
|
374
|
+
|
|
375
|
+
```ts
|
|
376
|
+
type OfferInput = {
|
|
377
|
+
recommendationId: number;
|
|
378
|
+
variantId: number;
|
|
379
|
+
quantity: number;
|
|
380
|
+
purchaseOptionId?: string;
|
|
381
|
+
};
|
|
382
|
+
```
|
|
383
|
+
|
|
384
|
+
Reprice returns `unitPrice / amount / currency` and the matching selection. Payment status is `not_started / processing / requires_action / succeeded / succeeded_pending_order / failed`; shared transactions can also be `unknown / submitting`. Do not repurchase an accepted recommendation.
|
|
385
|
+
|
|
386
|
+
Use the latest matching quote and server-returned amount. Do not call `accept` again while a transaction is processing or unknown; query the existing payment status instead. Disable repeated actions while repricing, accepting or reconciling.
|
|
387
|
+
|
|
388
|
+
Offer pages require a recommendation rule. The CLI's Upsell and Downsell starters declare `manifest.capabilities.offerRecommendation: true`; configure the rule in the Editor's Product recommendation section. A dynamic component can provide the rule through this manifest capability. The first provider in template order applies to the page, including hidden sections. Do not duplicate the platform recommendation fields in your custom schema.
|
|
389
|
+
|
|
390
|
+
#### Thank You runtime
|
|
391
|
+
|
|
392
|
+
`runtime.order` is read-only:
|
|
393
|
+
|
|
394
|
+
- `getSnapshot()` and `subscribe(listener)` read the authenticated order state.
|
|
395
|
+
- `refresh?({ target?: "main" | "addOn" | "all" })` refreshes order data without modifying the order.
|
|
396
|
+
- `continueShopping?()` and `viewOrder?()` navigate through host-provided destinations.
|
|
397
|
+
|
|
398
|
+
The snapshot may include order number, status, customer, address, payment summary, lines, totals and currency. Missing data should be omitted or shown as unavailable until loaded. `getSnapshot()` can be `undefined`. `reads.main` and `reads.addOn` independently describe read state:
|
|
399
|
+
|
|
400
|
+
| Field | Meaning |
|
|
401
|
+
| --- | --- |
|
|
402
|
+
| `status` | `unknown / loading / success / empty / error` |
|
|
403
|
+
| `refreshing`, `stale` | Whether a refresh is in flight and whether existing data is stale |
|
|
404
|
+
| `data` | Last successfully read data; may remain visible after a refresh fails |
|
|
405
|
+
| `error` | Read failure information; a read failure is not a payment failure |
|
|
406
|
+
|
|
407
|
+
Refresh defaults to `all`. Refresh/navigation actions return `ok` results. When a valid navigation destination is unavailable, the method may be absent; hide or disable the corresponding button. Thank You components cannot modify an order, create an order or charge a payment again.
|
|
408
|
+
|
|
409
|
+
### Styles, imports and runtime limits
|
|
410
|
+
|
|
411
|
+
Put component CSS in the exported `styles` string and scope selectors under a component-owned class. Do not add global resets, `html`/`body` rules or a second CSS loading path. Use hosted asset URLs or configured media resources instead of importing CSS, images or video files.
|
|
412
|
+
|
|
413
|
+
Allowed runtime imports are the platform React bridge (`react`, `react-dom`, `react-dom/client`, `react/jsx-runtime`, `react/jsx-dev-runtime`) and relative modules inside `src`. Node APIs, source symlinks, imports outside `src`, arbitrary runtime dependencies and a second copy of React are unsupported.
|
|
414
|
+
|
|
415
|
+
Production output is one UTF-8 ESM JavaScript file, at most 1 MiB, with no extra chunks or HMR code. Components execute in the browser and the CLI is not a security sandbox for untrusted code. Do not put platform credentials in source or configuration.
|
|
416
|
+
|
|
417
|
+
### Local preview, Save and Publish
|
|
418
|
+
|
|
419
|
+
| Source | When to use it | How to submit |
|
|
420
|
+
| --- | --- | --- |
|
|
421
|
+
| **Local Dev Server source URL** | Source development and HMR | Save requests a production build and uploads it |
|
|
422
|
+
| **Upload component** | Delivery or replacement of production code | Build and upload `dist/<componentId>.js`; valid `.mjs` artifacts are also supported |
|
|
423
|
+
| **Existing component** | Reuse a component already uploaded to this theme | Select it and configure the current instance |
|
|
424
|
+
|
|
425
|
+
Raw `.tsx/.jsx` is for Local URL development, not file upload. A successful file selection or preview still needs Save. To hand off a component, provide the built artifact, page support and setup instructions. For further development also share source, project config, lockfile and the `vendor` archive if you used archive installation.
|
|
426
|
+
|
|
427
|
+
| Operation | Effect |
|
|
428
|
+
| --- | --- |
|
|
429
|
+
| Local/HMR or file selection | Updates pending code in the Editor; does not change the storefront |
|
|
430
|
+
| **Save** | Validates and saves shared component draft and current template configuration |
|
|
431
|
+
| **Publish** | Saves if necessary, publishes referenced component artifacts, then publishes template configuration |
|
|
432
|
+
| **Discard** | Restores the latest saved template configuration and clears pending sources; does not roll back shared resources already written |
|
|
433
|
+
|
|
434
|
+
A component ID identifies shared code within a theme; each instance has independent settings. Replacing a component with the same ID updates every template that references that ID after the new artifact is published. Use a new component ID when code must evolve independently. Hidden/disabled references are included in Save/Publish validation. Within one Save, a shared component ID is built/uploaded at most once when needed. Updating code does not migrate other templates’ settings automatically.
|
|
435
|
+
|
|
436
|
+
Save and Publish are separate: Save updates the saved draft, while Publish makes the saved artifact/template available to the storefront. If shared resource publication succeeds but template publication fails, the resource is not automatically rolled back; retry the failed operation or explicitly restore and publish an older artifact.
|
|
437
|
+
|
|
438
|
+
Removing a Section or clearing its selection only unbinds that instance. **Delete component** in the component picker removes the theme’s shared resource and can leave all referencing instances without usable code.
|
|
439
|
+
|
|
440
|
+
To update an existing component:
|
|
441
|
+
|
|
442
|
+
1. Check the source manifest’s `componentId`. Keep it for a shared update; choose a new ID for independent code.
|
|
443
|
+
2. Connect its Local URL or use **Replace** with a new build. The last successfully loaded source is used.
|
|
444
|
+
3. Verify settings compatibility in other referencing instances. Existing configured values take precedence over changed defaults.
|
|
445
|
+
4. Save and reopen the template to verify the saved draft. Reconnect Local URL after an Editor reload if continuing development.
|
|
446
|
+
5. Publish and refresh the storefront and other referencing templates. After publication, stop Dev Server to verify resource independence.
|
|
447
|
+
|
|
448
|
+
For settings-only changes such as a title or color, use Save/Publish without uploading code again. To restore older shared code, upload and publish a retained old artifact; restoring template settings alone does not restore old code.
|
|
449
|
+
|
|
450
|
+
### Validation checklist
|
|
451
|
+
|
|
452
|
+
Before publishing, verify:
|
|
453
|
+
|
|
454
|
+
- `npm run build` passes and the artifact is the current source.
|
|
455
|
+
- Manifest page support, schema and defaults match the target template.
|
|
456
|
+
- Preview works on desktop and mobile; HMR does not lose settings or create duplicate subscriptions.
|
|
457
|
+
- Loading, empty, unavailable, validation, network error and duplicate-action states are handled.
|
|
458
|
+
- Runtime actions check `ok`/status and never assume a Promise means payment success.
|
|
459
|
+
- Save and reopen preserve the component identity and settings.
|
|
460
|
+
- Publish succeeds, the local server can stop, and a refreshed storefront renders the published artifact.
|
|
461
|
+
- Shared component IDs are reviewed across all templates before replacement.
|
|
95
462
|
|
|
96
463
|
## Commands
|
|
97
464
|
|
|
98
|
-
Run project commands inside the generated project:
|
|
465
|
+
Run project commands inside the generated project; `init` creates a new project and is run outside it:
|
|
99
466
|
|
|
100
467
|
| Command | Purpose |
|
|
101
468
|
| --- | --- |
|
|
469
|
+
| `init` | Create the project and first component; see Quick start |
|
|
470
|
+
| `npx dynamic-component create <id> --page-type <type>` | Add a component; restart Dev Server afterward |
|
|
102
471
|
| `npm run dev` | Start the local server; Ctrl+C stops it |
|
|
103
472
|
| `npm run build` | Type-check, validate in a browser and write `dist/<componentId>.js` |
|
|
104
473
|
| `npm run validate` | Run validation without writing production artifacts |
|
|
@@ -108,6 +477,19 @@ Run project commands inside the generated project:
|
|
|
108
477
|
|
|
109
478
|
For a manual upload, run `npm run build`, then upload the generated `.js` in the Editor and Save/Publish there. When using Local Save, the Editor requests the build automatically; you do not need to run `build` first. Failed builds do not replace existing output files.
|
|
110
479
|
|
|
480
|
+
`build` already includes type checking, source boundary checks, compilation and browser definition validation; do not run `validate` first unless you specifically want a check without artifacts. `doctor` is optional for setup or troubleshooting.
|
|
481
|
+
|
|
482
|
+
The server defaults to loopback port `5173`. No Editor origin registration is required. To persist a custom port, merge `"server": { "port": 5189 }` into `dynamic.config.json`, or override it per command:
|
|
483
|
+
|
|
484
|
+
```bash
|
|
485
|
+
npm run dev -- --port 5189
|
|
486
|
+
npm run build -- --component-id checkout-card
|
|
487
|
+
npm run validate -- --browser-executable /absolute/path/to/browser
|
|
488
|
+
npx dynamic-component doctor --project /absolute/path/to/my-components
|
|
489
|
+
```
|
|
490
|
+
|
|
491
|
+
`--project` supports `create / dev / validate / build / doctor`; `--port` supports `dev / doctor`; `--browser-executable` supports `validate / build / doctor` (or use `DYNAMIC_COMPONENT_BROWSER`). `validate` checks all components and does not accept `--component-id`. A selected component build still type-checks the project.
|
|
492
|
+
|
|
111
493
|
## Troubleshooting
|
|
112
494
|
|
|
113
495
|
| Problem | Action |
|
|
@@ -121,10 +503,17 @@ For a manual upload, run `npm run build`, then upload the generated `.js` in the
|
|
|
121
503
|
| Save fails while preview works | Review the error and run `npm run build`; production type checks and browser validation also apply to Local Save |
|
|
122
504
|
| Build is busy or times out | Wait for the active build to finish, reduce excessive source work if needed, then explicitly retry Save |
|
|
123
505
|
| New component URL is missing | Restart the server after `create` or configuration changes |
|
|
506
|
+
| HMR is `error` or `disconnected` | Fix compilation errors, check the port, restart/reconnect if configuration changed |
|
|
507
|
+
| Dev Server does not support build sessions | Upgrade the project-local CLI and restart; alternatively build in the terminal and upload the artifact |
|
|
508
|
+
| Build source changed or result is stale | Wait for the active build to finish, confirm current source, then explicitly Save again; do not substitute an old artifact |
|
|
509
|
+
| Resource version conflict | Reload the component/template, review others’ changes, then submit the intended version |
|
|
510
|
+
| Published page still shows old content | Confirm both component and template publication succeeded and that the page uses the intended theme/template; refresh |
|
|
511
|
+
| Runtime capability missing | Check page/shop configuration, handle `undefined` or `unavailable` and do not call absent methods |
|
|
512
|
+
| Component load or render failure | Check exports, schema, imports and browser console; fix and trigger HMR or rebuild/upload. Platform error UI does not handle your action errors |
|
|
124
513
|
|
|
125
514
|
Builds support up to 500 source files, 1000 source-tree entries, 16 MiB of source and a 1 MiB artifact. Editor-requested builds run one at a time and time out after 45 seconds. Components run in the browser during preview/validation; this is not a sandbox for untrusted code. No platform credentials are stored by the CLI.
|
|
126
515
|
|
|
127
|
-
Windows/Linux, Safari/Firefox and production HTTPS Editor access remain outside the completed compatibility checks. `doctor` cannot change browser permissions.
|
|
516
|
+
Windows/Linux, Safari/Firefox and production HTTPS Editor access remain outside the completed compatibility checks. `doctor` cannot change browser permissions. HTTPS Editor access to local HTTP services may also depend on browser local-network permissions.
|
|
128
517
|
|
|
129
518
|
## Upgrade
|
|
130
519
|
|
package/package.json
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
# Dynamic component project
|
|
2
2
|
|
|
3
|
+
Full component protocol, Runtime API, examples and publishing guidance: [Development guide](https://www.npmjs.com/package/@bestcheckout/dynamic-component-cli).
|
|
4
|
+
|
|
3
5
|
## Start development
|
|
4
6
|
|
|
5
7
|
Use Node.js >=20.10 and npm. From this project directory:
|