@bestcheckout/dynamic-component-cli 0.0.0-stage → 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/LICENSE +21 -0
- package/README.md +536 -2
- package/package.json +51 -4
- package/src/cli.mjs +87 -0
- package/src/core/browser.mjs +23 -0
- package/src/core/build-runner.mjs +18 -0
- package/src/core/build-session.mjs +69 -0
- package/src/core/build-worker.mjs +8 -0
- package/src/core/build.mjs +85 -0
- package/src/core/config.mjs +115 -0
- package/src/core/doctor.mjs +102 -0
- package/src/core/project.mjs +143 -0
- package/src/core/react-bridge.mjs +65 -0
- package/src/core/server.mjs +191 -0
- package/src/core/source-boundary.mjs +69 -0
- package/src/core/validate.mjs +247 -0
- package/src/protocol/artifact.mjs +88 -0
- package/src/protocol/validation.mjs +96 -0
- package/templates/starter/README.md +58 -0
- package/templates/starter/tsconfig.json +14 -0
- package/types/index.d.ts +1230 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 BestCheckout contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,537 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @bestcheckout/dynamic-component-cli
|
|
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
|
+
|
|
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
|
+
|
|
26
|
+
## Requirements
|
|
27
|
+
|
|
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.
|
|
29
|
+
- Internet access to install public npm dependencies.
|
|
30
|
+
- Access to a BestCheckout theme editor with custom components and permission to save/publish your target template.
|
|
31
|
+
- Chromium for build validation, including builds requested by Editor Save. Install it as shown below. On macOS, an existing Google Chrome installation can also be detected automatically.
|
|
32
|
+
|
|
33
|
+
## Quick start
|
|
34
|
+
|
|
35
|
+
The public package is available from npm. Run:
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
npx @bestcheckout/dynamic-component-cli@latest init my-components --component-id checkout-card --page-type checkout
|
|
39
|
+
cd my-components
|
|
40
|
+
npm install
|
|
41
|
+
npx playwright install chromium
|
|
42
|
+
npm run dev
|
|
43
|
+
```
|
|
44
|
+
|
|
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.
|
|
46
|
+
|
|
47
|
+
The terminal prints each component's Local URL. For the example above on the default port, it is:
|
|
48
|
+
|
|
49
|
+
```text
|
|
50
|
+
http://localhost:5173/src/checkout-card/component.tsx
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
Use the exact URL printed by your server. The source URL is a module for the Editor to load, not a standalone checkout webpage; the Editor supplies React and business data.
|
|
54
|
+
|
|
55
|
+
### Connect to the Editor
|
|
56
|
+
|
|
57
|
+
1. Open the target theme's Checkout template and add or select a custom component.
|
|
58
|
+
2. Under **Component source**, paste the source URL into **Local Dev Server source URL** and finish editing the field to connect.
|
|
59
|
+
3. Edit `src/checkout-card/component.tsx`. Change `Component` JSX or the exported `styles` string to see HMR updates in the preview. Edit the right-panel settings to test configuration separately.
|
|
60
|
+
4. Keep the Dev Server running and click **Save** in the Editor. It requests a production build, validates/uploads it and saves the template. Fix build errors and explicitly retry Save when needed.
|
|
61
|
+
5. Click **Publish** to make the saved component/template changes available to the storefront. A local preview alone does not update the storefront.
|
|
62
|
+
6. After a successful publish, stop the Dev Server and refresh the storefront to verify it uses the uploaded artifact.
|
|
63
|
+
|
|
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.
|
|
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
|
+
|
|
80
|
+
## Install from a supplied .tgz
|
|
81
|
+
|
|
82
|
+
No source checkout is needed. Replace both archive paths with the actual downloaded file:
|
|
83
|
+
|
|
84
|
+
```bash
|
|
85
|
+
npx --yes --package /absolute/path/dynamic-component-cli.tgz dynamic-component init my-components --component-id checkout-card --page-type checkout --cli-package /absolute/path/dynamic-component-cli.tgz
|
|
86
|
+
cd my-components
|
|
87
|
+
npm install
|
|
88
|
+
npx playwright install chromium
|
|
89
|
+
npm run dev
|
|
90
|
+
```
|
|
91
|
+
|
|
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.
|
|
93
|
+
|
|
94
|
+
## Project files and additional components
|
|
95
|
+
|
|
96
|
+
```text
|
|
97
|
+
my-components/
|
|
98
|
+
src/checkout-card/component.tsx
|
|
99
|
+
dynamic.config.json
|
|
100
|
+
package.json
|
|
101
|
+
tsconfig.json
|
|
102
|
+
README.md
|
|
103
|
+
dist/checkout-card.js # generated by npm run build
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
Run these commands inside the generated project, after `npm install`:
|
|
107
|
+
|
|
108
|
+
```bash
|
|
109
|
+
npx dynamic-component create offer-card --page-type upsell
|
|
110
|
+
npx dynamic-component create downsell-card --page-type downsell
|
|
111
|
+
npx dynamic-component create order-card --page-type thankYou
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
Restart `npm run dev` after adding a component or changing `dynamic.config.json`. Ordinary source edits use HMR.
|
|
115
|
+
|
|
116
|
+
- Page types are exactly `checkout`, `upsell`, `downsell`, `thankYou` (case-sensitive).
|
|
117
|
+
- Component IDs use 1–64 lowercase letters, numbers, underscores or hyphens and must be unique within the project.
|
|
118
|
+
- `dynamic.config.json` registers local entry files. Keep its component ID and page type consistent with each exported `manifest`; mismatches fail validation.
|
|
119
|
+
- Upsell/Downsell starters declare `capabilities.offerRecommendation`. Configure their recommendation rules in the Editor before saving/publishing the offer template.
|
|
120
|
+
|
|
121
|
+
## Component development
|
|
122
|
+
|
|
123
|
+
### Supported pages and component contract
|
|
124
|
+
|
|
125
|
+
The CLI supports four page types:
|
|
126
|
+
|
|
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:
|
|
150
|
+
|
|
151
|
+
```ts
|
|
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
|
+
};
|
|
171
|
+
```
|
|
172
|
+
|
|
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.
|
|
462
|
+
|
|
463
|
+
## Commands
|
|
464
|
+
|
|
465
|
+
Run project commands inside the generated project; `init` creates a new project and is run outside it:
|
|
466
|
+
|
|
467
|
+
| Command | Purpose |
|
|
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 |
|
|
471
|
+
| `npm run dev` | Start the local server; Ctrl+C stops it |
|
|
472
|
+
| `npm run build` | Type-check, validate in a browser and write `dist/<componentId>.js` |
|
|
473
|
+
| `npm run validate` | Run validation without writing production artifacts |
|
|
474
|
+
| `npm run doctor` | Diagnose config, port and browser availability |
|
|
475
|
+
| `npx dynamic-component --help` | Show command options |
|
|
476
|
+
| `npx dynamic-component --version` | Show the installed CLI version |
|
|
477
|
+
|
|
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.
|
|
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
|
+
|
|
493
|
+
## Troubleshooting
|
|
494
|
+
|
|
495
|
+
| Problem | Action |
|
|
496
|
+
| --- | --- |
|
|
497
|
+
| Port 5173 is occupied | Run `npm run dev -- --port 5180` and reconnect using the new printed URL |
|
|
498
|
+
| Editor cannot connect | Keep the server running on the same computer as the browser; check the URL and any browser local-network access prompt |
|
|
499
|
+
| Browser validation is unavailable | Run `npx playwright install chromium` inside the project, then retry |
|
|
500
|
+
| Use an existing browser | For manual builds, use `npm run build -- --browser-executable "/absolute/path/to/browser"`; for Editor-triggered builds, set `DYNAMIC_COMPONENT_BROWSER` in the shell that starts the Dev Server |
|
|
501
|
+
| Unsupported dependency or CSS import | Keep code imports inside `src`, use platform React imports, exported `styles` and hosted asset URLs |
|
|
502
|
+
| Component ID or page type mismatch | Match `dynamic.config.json` with the exported manifest; use a compatible Editor page type |
|
|
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 |
|
|
504
|
+
| Build is busy or times out | Wait for the active build to finish, reduce excessive source work if needed, then explicitly retry Save |
|
|
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 |
|
|
513
|
+
|
|
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.
|
|
515
|
+
|
|
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.
|
|
517
|
+
|
|
518
|
+
## Upgrade
|
|
519
|
+
|
|
520
|
+
Projects pin the CLI version used to create them. After a newer version is published, stop the Dev Server and run:
|
|
521
|
+
|
|
522
|
+
```bash
|
|
523
|
+
npm install --save-dev --save-exact @bestcheckout/dynamic-component-cli@latest
|
|
524
|
+
npx playwright install chromium
|
|
525
|
+
npm run build
|
|
526
|
+
npm run dev
|
|
527
|
+
```
|
|
528
|
+
|
|
529
|
+
Review release changes before upgrading. Installing a new CLI does not overwrite your existing component source or regenerate the Starter. Update the project-local dependency even if you also installed the CLI globally.
|
|
530
|
+
|
|
531
|
+
## Maintainers
|
|
532
|
+
|
|
533
|
+
Source lives in `shop-visual/packages/dynamic-component-cli`. Types and validation are generated from the adjacent Renderer package; installed users do not need to run this synchronization. Tests, protocol synchronization and release steps are documented in `docs/dynamic-component-cli-publishing.md` in the source repository. These maintainer scripts are not shipped in the npm archive.
|
|
534
|
+
|
|
535
|
+
## License
|
|
536
|
+
|
|
537
|
+
MIT. See [LICENSE](./LICENSE). This license applies to this CLI package; it does not change the licenses of other platform packages or third-party dependencies.
|
package/package.json
CHANGED
|
@@ -1,6 +1,53 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@bestcheckout/dynamic-component-cli",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "CLI and starter project generator for BestCheckout dynamic components",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"bin": {
|
|
8
|
+
"dynamic-component": "src/cli.mjs"
|
|
9
|
+
},
|
|
10
|
+
"files": [
|
|
11
|
+
"src",
|
|
12
|
+
"types",
|
|
13
|
+
"templates",
|
|
14
|
+
"README.md",
|
|
15
|
+
"LICENSE"
|
|
16
|
+
],
|
|
17
|
+
"scripts": {
|
|
18
|
+
"test": "node --test tests/*.test.mjs",
|
|
19
|
+
"pack:check": "npm pack --dry-run",
|
|
20
|
+
"test:integration": "node tests/standalone.integration.mjs",
|
|
21
|
+
"test:editor": "node scripts/test-editor.mjs",
|
|
22
|
+
"sync:protocol": "node scripts/sync-protocol.mjs",
|
|
23
|
+
"check:protocol": "node scripts/sync-protocol.mjs --check"
|
|
24
|
+
},
|
|
25
|
+
"engines": {
|
|
26
|
+
"node": ">=20.10.0"
|
|
27
|
+
},
|
|
28
|
+
"private": false,
|
|
29
|
+
"exports": {
|
|
30
|
+
"./types": {
|
|
31
|
+
"types": "./types/index.d.ts"
|
|
32
|
+
},
|
|
33
|
+
"./build": "./src/core/build.mjs",
|
|
34
|
+
"./react-bridge": "./src/core/react-bridge.mjs",
|
|
35
|
+
"./source-boundary": "./src/core/source-boundary.mjs"
|
|
36
|
+
},
|
|
37
|
+
"dependencies": {
|
|
38
|
+
"acorn": "8.15.0",
|
|
39
|
+
"esbuild": "0.21.5",
|
|
40
|
+
"playwright": "1.56.1",
|
|
41
|
+
"react": "18.3.1",
|
|
42
|
+
"react-dom": "18.3.1",
|
|
43
|
+
"typescript": "5.6.3",
|
|
44
|
+
"vite": "5.4.21"
|
|
45
|
+
},
|
|
46
|
+
"publishConfig": {
|
|
47
|
+
"access": "public",
|
|
48
|
+
"registry": "https://registry.npmjs.org/"
|
|
49
|
+
},
|
|
50
|
+
"devDependencies": {
|
|
51
|
+
"dts-bundle-generator": "9.5.1"
|
|
52
|
+
}
|
|
53
|
+
}
|