@bestcheckout/dynamic-component-cli 0.1.0 → 0.1.2
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 +525 -12
- package/package.json +14 -10
- package/skills/checkout-theme-dynamic-development/SKILL.md +14 -0
- package/skills/checkout-theme-dynamic-development/agents/openai.yaml +3 -0
- package/skills/checkout-theme-dynamic-development/references/behaviors.json +1214 -0
- package/skills/checkout-theme-dynamic-development/references/cli-development.md +43 -0
- package/skills/checkout-theme-dynamic-development/references/component-catalog.json +5172 -0
- package/skills/checkout-theme-dynamic-development/references/workflow.md +114 -0
- package/src/core/build.mjs +62 -46
- package/src/core/doctor.mjs +14 -2
- package/src/core/project.mjs +10 -7
- package/src/core/server.mjs +16 -3
- package/src/core/source-bundle.mjs +135 -0
- package/src/protocol/validation.mjs +57 -1
- package/templates/starter/README.md +6 -0
- package/types/index.d.ts +182 -9
package/README.md
CHANGED
|
@@ -2,16 +2,50 @@
|
|
|
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
|
+
- [AI skill for local development](#ai-skill-for-local-development)
|
|
9
|
+
- [Quick start and Editor preview](#quick-start)
|
|
10
|
+
- [Global installation](#optional-global-installation)
|
|
11
|
+
- [Archive installation](#install-from-a-supplied-tgz)
|
|
12
|
+
- [Project files and additional components](#project-files-and-additional-components)
|
|
13
|
+
- [Component contract and schema](#component-development)
|
|
14
|
+
- [Complete Checkout example](#complete-checkout-example)
|
|
15
|
+
- [Runtime API](#runtime-usage)
|
|
16
|
+
- [Common capabilities](#common-runtime-capabilities)
|
|
17
|
+
- [Checkout](#checkout-runtime)
|
|
18
|
+
- [Upsell and Downsell](#upsell-and-downsell-runtime)
|
|
19
|
+
- [Thank You](#thank-you-runtime)
|
|
20
|
+
- [Styles and imports](#styles-imports-and-runtime-limits)
|
|
21
|
+
- [Save, Publish and shared components](#local-preview-save-and-publish)
|
|
22
|
+
- [Validation checklist](#validation-checklist)
|
|
23
|
+
- [CLI commands](#commands)
|
|
24
|
+
- [Troubleshooting](#troubleshooting)
|
|
25
|
+
- [Upgrade](#upgrade)
|
|
26
|
+
|
|
5
27
|
## Requirements
|
|
6
28
|
|
|
7
29
|
- 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.
|
|
8
30
|
- Internet access to install public npm dependencies.
|
|
9
|
-
-
|
|
31
|
+
- For integrated page preview, Save and Publish: access to a BestCheckout theme editor with custom components and the corresponding template permissions. Local source editing and builds do not require an active Editor session or MCP connection.
|
|
10
32
|
- 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.
|
|
11
33
|
|
|
34
|
+
## AI skill for local development
|
|
35
|
+
|
|
36
|
+
The package includes `skills/checkout-theme-dynamic-development/`, an optional skill for AI assistants editing local dynamic-component projects. It guides requirement analysis, public Runtime usage, local validation/builds and Editor integration. Neither BestCheckout MCP nor the shop-visual source repository is required. Manual CLI development works without a Skill.
|
|
37
|
+
|
|
38
|
+
Copy the complete directory from the installed `node_modules/@bestcheckout/dynamic-component-cli/skills/checkout-theme-dynamic-development/` into your AI client's supported skill location, or extract a supplied versioned Skill ZIP there. Keep `SKILL.md`, `references/` and `agents/` together. Package installation alone does not register the Skill. The client also needs local file/terminal capabilities to perform development; browser/image capabilities determine which visual checks it can run.
|
|
39
|
+
|
|
40
|
+
The Skill reads the project's installed CLI README, public types and generated component/behavior catalogs. These catalogs ship with the Skill and record the CLI version and public-type hash; prefer the installed project's copies to a separately downloaded Skill's copies. Do not use newer reference material to assume an older project or deployed Host supports a capability. Generated catalogs describe platform behavior and supported settings, not the store's current page configuration.
|
|
41
|
+
|
|
42
|
+
MCP-only users receive the shared development principles and MCP operations from the service and do not need to install this Skill or CLI. If MCP is also connected during local development, it can supply relevant page context without changing the local source, Save or Publish path. Missing Editor/Host access leaves integration unverified; local source implementation and available checks can still proceed.
|
|
43
|
+
|
|
44
|
+
Local edits, builds, Editor previews, saved page changes and publication are separate states. Use the Editor's existing Save/Publish flow; the Skill does not add authentication, remote persistence or publication capabilities to the CLI.
|
|
45
|
+
|
|
12
46
|
## Quick start
|
|
13
47
|
|
|
14
|
-
|
|
48
|
+
The public package is available from npm. Run:
|
|
15
49
|
|
|
16
50
|
```bash
|
|
17
51
|
npx @bestcheckout/dynamic-component-cli@latest init my-components --component-id checkout-card --page-type checkout
|
|
@@ -21,7 +55,7 @@ npx playwright install chromium
|
|
|
21
55
|
npm run dev
|
|
22
56
|
```
|
|
23
57
|
|
|
24
|
-
Use a new or empty project directory. No global CLI installation is required.
|
|
58
|
+
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
59
|
|
|
26
60
|
The terminal prints each component's Local URL. For the example above on the default port, it is:
|
|
27
61
|
|
|
@@ -42,6 +76,20 @@ Use the exact URL printed by your server. The source URL is a module for the Edi
|
|
|
42
76
|
|
|
43
77
|
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
78
|
|
|
79
|
+
### Optional global installation
|
|
80
|
+
|
|
81
|
+
```bash
|
|
82
|
+
npm install --global @bestcheckout/dynamic-component-cli@latest --registry=https://registry.npmjs.org/
|
|
83
|
+
dynamic-component --version
|
|
84
|
+
dynamic-component init my-components --component-id checkout-card --page-type checkout
|
|
85
|
+
cd my-components
|
|
86
|
+
npm install
|
|
87
|
+
npx playwright install chromium
|
|
88
|
+
npm run dev
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
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.
|
|
92
|
+
|
|
45
93
|
## Install from a supplied .tgz
|
|
46
94
|
|
|
47
95
|
No source checkout is needed. Replace both archive paths with the actual downloaded file:
|
|
@@ -54,7 +102,7 @@ npx playwright install chromium
|
|
|
54
102
|
npm run dev
|
|
55
103
|
```
|
|
56
104
|
|
|
57
|
-
`--cli-package` copies the archive into `vendor/` and installs that copy instead of fetching
|
|
105
|
+
`--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
106
|
|
|
59
107
|
## Project files and additional components
|
|
60
108
|
|
|
@@ -81,24 +129,439 @@ Restart `npm run dev` after adding a component or changing `dynamic.config.json`
|
|
|
81
129
|
- Page types are exactly `checkout`, `upsell`, `downsell`, `thankYou` (case-sensitive).
|
|
82
130
|
- Component IDs use 1–64 lowercase letters, numbers, underscores or hyphens and must be unique within the project.
|
|
83
131
|
- `dynamic.config.json` registers local entry files. Keep its component ID and page type consistent with each exported `manifest`; mismatches fail validation.
|
|
84
|
-
-
|
|
132
|
+
- All starters are ordinary components without recommendation-rule capabilities. Add `capabilities.offerRecommendation: true` only when the component is intended to own the Upsell/Downsell page's recommendation rules; then configure those rules in the Editor.
|
|
133
|
+
|
|
134
|
+
## Component development
|
|
135
|
+
|
|
136
|
+
### Supported pages and component contract
|
|
137
|
+
|
|
138
|
+
The CLI supports four page types:
|
|
139
|
+
|
|
140
|
+
| Page type | Runtime entry | Typical capabilities |
|
|
141
|
+
| --- | --- | --- |
|
|
142
|
+
| `checkout` | `runtime.checkout` | Contact, address, delivery, discounts, payment and checkout submission |
|
|
143
|
+
| `upsell` | `runtime.offer` | Recommendations, repricing, accepting an offer and continuing the flow |
|
|
144
|
+
| `downsell` | `runtime.offer` | The same offer contract with the downsell page context |
|
|
145
|
+
| `thankYou` | `runtime.order` | Read-only order data, refresh and order navigation |
|
|
146
|
+
|
|
147
|
+
A component exports a default definition containing `manifest`, `schema`, `defaultSettings`, `Component` and optional `styles`. The complete example below shows a usable definition.
|
|
148
|
+
|
|
149
|
+
- `manifest.componentId` is 1–64 lowercase letters, numbers, `_` or `-`. It identifies shared code within a theme.
|
|
150
|
+
- `manifest.name` is the non-empty display name shown in the Editor, up to 128 Unicode characters.
|
|
151
|
+
- `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.
|
|
152
|
+
- `manifest.capabilities.offerRecommendation` is opt-in: set it to `true` only for an Upsell/Downsell component that owns the page's product recommendation rule. Ordinary content or interaction components omit it. Being placed on an offer page or reading `runtime.offer` recommendations does not require this declaration. The Editor uses the first rule provider in template order, including hidden sections.
|
|
153
|
+
- `schema` is an array of Editor fields. Use `[]` when there are no settings.
|
|
154
|
+
- `defaultSettings` supplies values for new instances. It does not overwrite values already configured by a merchant.
|
|
155
|
+
- `Component` receives `{ settings, runtime, context }`.
|
|
156
|
+
- `styles` is an optional CSS string. Use component-owned class names; the platform scopes styles per instance.
|
|
157
|
+
|
|
158
|
+
`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.
|
|
159
|
+
|
|
160
|
+
### Editor schema and settings
|
|
161
|
+
|
|
162
|
+
Before writing code, inspect the current page and built-in settings. Prefer existing components, then configuration/layout changes, and use dynamic code for remaining requirements or an explicit custom-code choice. Clarify missing appearance, interaction or flow choices only when they affect the result; infer ordinary business behavior from the current contract instead of asking the merchant to enumerate it. “New” and “fully replace” describe outcomes, not a required replacement mechanism.
|
|
163
|
+
|
|
164
|
+
Every Section, including a built-in/core Section, supports deletion and hiding. Replacing an instance means removing the old instance once its replacement covers the requested behavior and configuration. Hiding retains the instance and is for an explicit hide/keep request, not the default substitute for replacement. Editing an existing instance in place needs no second instance. Keep page/global ownership and supported placement rules separate from deletion permission.
|
|
165
|
+
|
|
166
|
+
Check page tasks, business functions and component responsibilities together. A custom component can combine functions from several behavior profiles; dependencies may remain elsewhere on the page. For example, contact/address/shipping needs their applicable individual behaviors plus address-to-rates-to-totals/submission checks. Preserve the page's necessary flow, authoritative Host state, editable configuration and single transaction ownership. Component visibility or build success alone does not establish completeness.
|
|
167
|
+
|
|
168
|
+
The generated behavior catalog covers all registered Checkout-family components. Read every relevant profile when functions are combined, and use the existing Checkout example, page starters and Runtime examples as references. Custom controls need documented public Runtime capabilities and their own behavior checks. Reuse existing business APIs and configuration/resource save and publish operations. Build, structural validation, preview or publication success does not establish complete behavioral equivalence; report unverified behavior explicitly.
|
|
169
|
+
|
|
170
|
+
Before implementing, check the smallest proposed change against the user's intended difference, applicable behaviors and public capability limits below. Missing behavior guides in an older contract do not imply that there are no behaviors to preserve.
|
|
85
171
|
|
|
86
|
-
|
|
172
|
+
Schema fields use the same field types as the Editor configuration panel:
|
|
87
173
|
|
|
88
|
-
|
|
174
|
+
```ts
|
|
175
|
+
const schema = [
|
|
176
|
+
{ key: "title", type: "text", label: "Title", required: true },
|
|
177
|
+
{
|
|
178
|
+
key: "layout",
|
|
179
|
+
type: "select",
|
|
180
|
+
label: "Layout",
|
|
181
|
+
options: [
|
|
182
|
+
{ label: "Horizontal", value: "horizontal" },
|
|
183
|
+
{ label: "Stacked", value: "stacked" },
|
|
184
|
+
],
|
|
185
|
+
},
|
|
186
|
+
{ key: "showBadge", type: "toggle", label: "Show badge" },
|
|
187
|
+
];
|
|
188
|
+
|
|
189
|
+
const defaultSettings = {
|
|
190
|
+
title: "Recommended products",
|
|
191
|
+
layout: "horizontal",
|
|
192
|
+
showBadge: true,
|
|
193
|
+
};
|
|
194
|
+
```
|
|
195
|
+
|
|
196
|
+
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.
|
|
197
|
+
|
|
198
|
+
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.
|
|
199
|
+
|
|
200
|
+
### Complete Checkout example
|
|
201
|
+
|
|
202
|
+
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.
|
|
203
|
+
|
|
204
|
+
```tsx
|
|
205
|
+
import { useCallback, useSyncExternalStore } from "react";
|
|
206
|
+
import type {
|
|
207
|
+
DynamicComponentDefinition,
|
|
208
|
+
DynamicComponentProps,
|
|
209
|
+
} from "@bestcheckout/dynamic-component-cli/types";
|
|
210
|
+
|
|
211
|
+
function Component({ settings, runtime }: DynamicComponentProps) {
|
|
212
|
+
const checkout = runtime.checkout;
|
|
213
|
+
const subscribe = useCallback(
|
|
214
|
+
(notify: () => void) => checkout?.subscribe(() => notify()) ?? (() => {}),
|
|
215
|
+
[checkout],
|
|
216
|
+
);
|
|
217
|
+
const getSnapshot = useCallback(() => checkout?.getSnapshot(), [checkout]);
|
|
218
|
+
const snapshot = useSyncExternalStore(subscribe, getSnapshot);
|
|
219
|
+
|
|
220
|
+
return (
|
|
221
|
+
<section className="checkout-card">
|
|
222
|
+
<h2>{String(settings.title ?? "")}</h2>
|
|
223
|
+
{!snapshot ? (
|
|
224
|
+
<p>Checkout data is unavailable on this page.</p>
|
|
225
|
+
) : snapshot.status.dataStatus !== "ready" ? (
|
|
226
|
+
<p role="status">Checkout data is not ready. Please try again.</p>
|
|
227
|
+
) : (
|
|
228
|
+
<p>Contact email: {snapshot.contact.email || "Not provided"}</p>
|
|
229
|
+
)}
|
|
230
|
+
</section>
|
|
231
|
+
);
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
export default {
|
|
235
|
+
manifest: {
|
|
236
|
+
componentId: "checkout-card",
|
|
237
|
+
name: "Checkout information",
|
|
238
|
+
supportedPageTypes: ["checkout"],
|
|
239
|
+
},
|
|
240
|
+
schema: [{ key: "title", type: "text", label: "Title", required: true }],
|
|
241
|
+
defaultSettings: { title: "Confirm your checkout details" },
|
|
242
|
+
styles: `
|
|
243
|
+
.checkout-card { padding: 20px; border: 1px solid #ddd; border-radius: 8px; }
|
|
244
|
+
.checkout-card h2 { margin: 0 0 12px; font-size: 20px; }
|
|
245
|
+
.checkout-card p { margin: 0; overflow-wrap: anywhere; }
|
|
246
|
+
@media (max-width: 600px) { .checkout-card { padding: 16px; } }
|
|
247
|
+
`,
|
|
248
|
+
Component,
|
|
249
|
+
} satisfies DynamicComponentDefinition;
|
|
250
|
+
```
|
|
251
|
+
|
|
252
|
+
### Runtime usage
|
|
253
|
+
|
|
254
|
+
Import public types from the installed package:
|
|
89
255
|
|
|
90
256
|
```ts
|
|
91
|
-
import type {
|
|
257
|
+
import type {
|
|
258
|
+
DynamicComponentProps,
|
|
259
|
+
DynamicRuntime,
|
|
260
|
+
} from "@bestcheckout/dynamic-component-cli/types";
|
|
92
261
|
```
|
|
93
262
|
|
|
94
|
-
|
|
263
|
+
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.
|
|
264
|
+
|
|
265
|
+
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.
|
|
266
|
+
|
|
267
|
+
- Common actions, Order actions and Checkout business actions return `ok`; handle `code`, `message` and applicable `errors` on failure.
|
|
268
|
+
- Checkout validation returns `valid`; synchronous setters remain synchronous.
|
|
269
|
+
- Catch exceptions from payment mounts and Offer asynchronous actions. Offer actions use `status`, not `ok`.
|
|
270
|
+
- Disable duplicate operations while pending, ignore stale responses after selection changes/unmount, and clean up subscriptions, timers and mounts.
|
|
271
|
+
|
|
272
|
+
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.
|
|
273
|
+
|
|
274
|
+
#### Common runtime capabilities
|
|
275
|
+
|
|
276
|
+
| Capability | Methods |
|
|
277
|
+
| --- | --- |
|
|
278
|
+
| `runtime.page` | Read-only page context |
|
|
279
|
+
| `runtime.brand?` | `name`, `logoUrl`, `logoAlt` |
|
|
280
|
+
| `runtime.navigation?` | `navigate({ url, target? })`; destination starts with `/` or is an absolute HTTP(S) URL; target is `_self` or `_blank` |
|
|
281
|
+
| `runtime.account?` | `getSnapshot()`, `subscribe(listener)`, optional `open()`, `login()`, `logout()`; status is `loading / signed_out / signed_in / error` |
|
|
282
|
+
| `runtime.cart?` | `getSnapshot()`, `subscribe(listener)`, optional `addItem({ productId, variantId?, quantity })`, `open()`; snapshot includes quantity, amount, currency, `isLoading` and `error` |
|
|
283
|
+
|
|
284
|
+
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.
|
|
285
|
+
|
|
286
|
+
`runtime.account?.login` invokes the existing platform login flow when the actual page Host supplies it. It does not accept credentials or expose OTP verification, registration or session-management operations for a custom authentication form. An `ok` result only describes the action call; wait for the account snapshot to become `signed_in` before presenting an authenticated state. Handle cancellation, failure and missing capabilities without changing account state locally. Preview login is simulated and does not prove that a Live page has a working login integration.
|
|
287
|
+
|
|
288
|
+
#### Checkout runtime
|
|
289
|
+
|
|
290
|
+
`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:
|
|
291
|
+
|
|
292
|
+
| Area | Methods |
|
|
293
|
+
| --- | --- |
|
|
294
|
+
| Contact | `contact.getState()`, `contact.setEmail(email)`, `contact.validate()` |
|
|
295
|
+
| Current-instance add-ons | `upsell.getProduct(productId)`, `getSelections()`, `setSelection({ productId, variantId?, quantity })`, `remove(productId)` |
|
|
296
|
+
| Delivery address | `delivery.getState()`, `setField({ field, value })`, `validateField(field)`, `setCountry(id)`, `setState(id)`, `setCity(id)` |
|
|
297
|
+
| Saved addresses | `delivery.selectSavedAddress(id)`, `useNewAddress()`, `openNewAddress?()`, `editSavedAddress(id)`, `deleteSavedAddress(id)` |
|
|
298
|
+
| Billing address | `billing.getState()`, `setField({ field, value })`, `validateField(field)`, `setCountry(id)`, `setState(id)`, `setCity(id)`, `setSameAsShipping(boolean)` |
|
|
299
|
+
| Address autocomplete (optional) | `delivery.autocomplete?` and `billing.autocomplete?`: `search(query)`, `apply(suggestionId)`, `cancel()` |
|
|
300
|
+
| Shipping | `shipping.getState()`, `shipping.selectRate(id)` |
|
|
301
|
+
| Discounts | `coupon.getState()`, `coupon.apply(code)`, `coupon.remove(code)` |
|
|
302
|
+
| Payment | `payment.getState()`, `selectMethod(method)`, `mountSecureElement({ element, method })`, `mountAction({ element, method })` |
|
|
303
|
+
| Express payment | `express.mount({ element })` |
|
|
304
|
+
| Validation and submit | `validation.validateAll()`, `submit()` |
|
|
305
|
+
|
|
306
|
+
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.
|
|
307
|
+
|
|
308
|
+
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.
|
|
309
|
+
|
|
310
|
+
`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.
|
|
311
|
+
|
|
312
|
+
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.
|
|
313
|
+
|
|
314
|
+
A coupon action can be wrapped in `src/actions.ts` and called from a button handler:
|
|
315
|
+
|
|
316
|
+
```ts
|
|
317
|
+
import type { DynamicRuntime } from "@bestcheckout/dynamic-component-cli/types";
|
|
318
|
+
|
|
319
|
+
export async function applyCoupon(runtime: DynamicRuntime, code: string): Promise<string> {
|
|
320
|
+
if (!runtime.checkout) return "Discount codes are unavailable on this page.";
|
|
321
|
+
try {
|
|
322
|
+
const result = await runtime.checkout.coupon.apply(code);
|
|
323
|
+
if (!result.ok) return result.message || "Could not apply this code. Please retry.";
|
|
324
|
+
return result.outcome === "kept_better"
|
|
325
|
+
? "The better discount was kept."
|
|
326
|
+
: "Discount updated.";
|
|
327
|
+
} catch {
|
|
328
|
+
return "The action is unavailable. Please retry.";
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
```
|
|
332
|
+
|
|
333
|
+
Payment method IDs come from `snapshot.payment.methods`. Render only the methods actually provided by the Host:
|
|
334
|
+
|
|
335
|
+
| Method | Integration |
|
|
336
|
+
| --- | --- |
|
|
337
|
+
| Card | `payment.mountSecureElement` for the form, then `checkout.submit()` |
|
|
338
|
+
| Klarna | `payment.mountSecureElement` with `payment.mountAction`, or a supported custom submit button |
|
|
339
|
+
| PayPal | `payment.mountAction` for the native authorization button; do not use `checkout.submit()` |
|
|
340
|
+
| Express | `checkout.express.mount` for the native express controls |
|
|
341
|
+
|
|
342
|
+
Check the result of `payment.selectMethod(method)` before mounting. Secure-element handles also expose `validate()`. Mount only a supported method using the integration in the table above; do not guess secure/action support from a regular expression over the method label. Keep mount containers stable across input, address and quote updates. Components must not read or persist card numbers, CVV or payment tokens.
|
|
343
|
+
|
|
344
|
+
##### Payment mount lifecycle
|
|
345
|
+
|
|
346
|
+
Runtime capability objects and their methods may receive new references on ordinary Host updates. A new `checkout` reference is not a new checkout session. Do not make payment mount effects depend on `runtime`, `checkout`, `snapshot`, inline option objects or mount-function references: mounting/releasing can itself notify the Host, creating an update → cleanup → remount loop. Subscription effects may depend on the current API object; payment resource ownership must use a separate lifecycle.
|
|
347
|
+
|
|
348
|
+
The wrapper below updates a ref after commit and mounts by component instance, checkout presence, mount kind and payment method. The current Renderer remounts the enclosing dynamic component when its template/Section identity or Host session changes. Keep this wrapper inside that component; do not hoist it into a persistent global root. A custom Host must provide a session key that changes with the business session and remount the component on session replacement. `runtime.page` is not an order/session identifier; do not invent one from an email, amount or snapshot. Runtime refs are not a substitute for Host session isolation.
|
|
349
|
+
|
|
350
|
+
Use this wrapper as `src/NativePaymentControl.tsx`. `kind="secure"` mounts a secure form, `kind="action"` mounts a native authorization button, and `kind="express"` mounts native express controls (omit `method` for Express). Render one owner for each payment surface; do not mount a duplicate alongside an enabled built-in Payment/Express section.
|
|
351
|
+
|
|
352
|
+
```tsx
|
|
353
|
+
import { useEffect, useLayoutEffect, useRef, useState } from "react";
|
|
354
|
+
import type { DynamicCheckoutRuntime } from "@bestcheckout/dynamic-component-cli/types";
|
|
355
|
+
|
|
356
|
+
export function NativePaymentControl({ checkout, kind, method = "" }: {
|
|
357
|
+
checkout?: DynamicCheckoutRuntime;
|
|
358
|
+
kind: "secure" | "action" | "express";
|
|
359
|
+
method?: string;
|
|
360
|
+
}) {
|
|
361
|
+
const container = useRef<HTMLDivElement>(null);
|
|
362
|
+
const latestCheckout = useRef(checkout);
|
|
363
|
+
const [error, setError] = useState("");
|
|
364
|
+
const hasCheckout = Boolean(checkout);
|
|
365
|
+
|
|
366
|
+
// Keep the API current without making its reference a mount identity.
|
|
367
|
+
useLayoutEffect(() => {
|
|
368
|
+
latestCheckout.current = checkout;
|
|
369
|
+
}, [checkout]);
|
|
370
|
+
|
|
371
|
+
useEffect(() => {
|
|
372
|
+
const api = latestCheckout.current;
|
|
373
|
+
const element = container.current;
|
|
374
|
+
if (!hasCheckout || !api || !element || (kind !== "express" && !method)) {
|
|
375
|
+
setError("Payment controls are unavailable. Please refresh the page.");
|
|
376
|
+
return;
|
|
377
|
+
}
|
|
378
|
+
let cancelled = false;
|
|
379
|
+
let unmount: (() => void) | undefined;
|
|
380
|
+
setError("");
|
|
381
|
+
const mount = async () => {
|
|
382
|
+
try {
|
|
383
|
+
const handle = await (kind === "express"
|
|
384
|
+
? api.express.mount({ element })
|
|
385
|
+
: kind === "action"
|
|
386
|
+
? api.payment.mountAction({ element, method })
|
|
387
|
+
: api.payment.mountSecureElement({ element, method }));
|
|
388
|
+
if (cancelled) handle.unmount();
|
|
389
|
+
else unmount = () => handle.unmount();
|
|
390
|
+
} catch {
|
|
391
|
+
if (!cancelled) setError("Payment controls failed to load. Please refresh the page.");
|
|
392
|
+
}
|
|
393
|
+
};
|
|
394
|
+
// Run after React commits; cleanup of the previous owner is queued first.
|
|
395
|
+
queueMicrotask(() => { if (!cancelled) void mount(); });
|
|
396
|
+
return () => {
|
|
397
|
+
cancelled = true;
|
|
398
|
+
queueMicrotask(() => unmount?.());
|
|
399
|
+
};
|
|
400
|
+
}, [hasCheckout, kind, method]);
|
|
401
|
+
|
|
402
|
+
return (
|
|
403
|
+
<div>
|
|
404
|
+
<div ref={container} />
|
|
405
|
+
{error && <p role="alert">{error}</p>}
|
|
406
|
+
</div>
|
|
407
|
+
);
|
|
408
|
+
}
|
|
409
|
+
```
|
|
410
|
+
|
|
411
|
+
This manages control ownership only; mounting does not submit or prove successful payment. Host updates refresh an existing mounted control through the runtime adapter. If a mount resolves after cleanup, its handle is immediately released. Failure remains an unavailable state across ordinary snapshot updates; do not automatically retry on errors or new Runtime references.
|
|
412
|
+
|
|
413
|
+
The recovery policy in this example is a visible instruction to refresh the page manually, with no automatic retry or reload. After a mounted control becomes unavailable or throws during rendering, the Adapter removes the provider subtree, releases its Host reservation once and keeps a refresh message inside its owned container until disposal. Ordinary Host updates do not recover that failed mount; a page refresh creates a new instance. `hasCheckout` only detects that the checkout API exists, not that the payment SDK is ready. Errors handled internally by a payment SDK, including asynchronous network failures, remain the responsibility of that SDK/Host UI; a React error boundary does not catch every asynchronous error.
|
|
414
|
+
|
|
415
|
+
Mount calls and cleanup are queued after the React commit so nested payment roots are not synchronously unmounted while React is rendering; cancelled setups are skipped. React StrictMode may run setup/cleanup again in development; cleanup must tolerate it. Do not keep the first Runtime forever in a ref, remove all effect dependencies, or suppress dependency lint rules as a workaround.
|
|
416
|
+
|
|
417
|
+
##### Patterns to avoid in dynamic components
|
|
418
|
+
|
|
419
|
+
| Risky pattern | Failure mode | Supported approach |
|
|
420
|
+
| --- | --- | --- |
|
|
421
|
+
| Payment mount effect depends on an API/snapshot object; random, timestamp or serialized-snapshot React keys | Repeated SDK initialization, requests and lost input | Use the lifecycle wrapper above; stable component types, keys and container nodes within a session |
|
|
422
|
+
| `innerHTML`, `replaceChildren`, manual removal, or another `createRoot` inside a payment container | React/SDK DOM ownership conflicts and `removeChild` errors | Leave the empty ref container to the mount handle; release with `unmount()` |
|
|
423
|
+
| Calling setters, coupon actions, repricing or payment actions during render or in every subscription callback | Update/request feedback loops and duplicate writes | Render reads only; invoke writes from user intent or narrowly keyed, guarded effects |
|
|
424
|
+
| `getSnapshot: () => ({ ...checkout.getSnapshot() })`, allocating arrays with `map/filter`, or a new fallback object on every read | Unstable external-store snapshots and repeated renders | Return the existing snapshot; derive display values after reading it; always unsubscribe |
|
|
425
|
+
| Defining a component function inside another render, or keying the whole form by field values | React sees a new component identity; focus and payment state reset | Define components at module scope and use stable resource/instance keys |
|
|
426
|
+
| Applying an async result after its selection/session changed | Stale products, address options or quotes overwrite current state | Track request identity or cancellation; ignore stale completions and release late mount handles |
|
|
427
|
+
| Only using `setBusy(true)` to prevent same-tick duplicate actions; unbounded retry/polling | Duplicate submissions or request storms | Use an immediate ref lock plus visible busy state, unlock in `finally`; use bounded/manual recovery and existing payment status reads |
|
|
428
|
+
| Guessing payment capabilities by label, swallowing mount errors, or treating fulfilled Promises as payment success | Wrong control, silent failure or false success | Follow supported method integration and result contracts; show errors; keep unknown/processing explicit |
|
|
429
|
+
| Calling Hooks conditionally after an early return or inside a list/callback | Hook order changes when data or capabilities appear | Call Hooks unconditionally at component top level; put availability checks inside callbacks/effects or split a module-scope child component |
|
|
430
|
+
| Mutating settings/snapshots or computing authoritative totals, defaulting missing amount/currency to zero/USD | Corrupt shared data or show false prices/readiness | Keep snapshots/settings read-only; use local UI state and server amounts; render missing/unknown explicitly |
|
|
431
|
+
| Global DOM queries, duplicate hard-coded input IDs, global listeners/timers without cleanup | One instance changes another, leaked callbacks and duplicate actions | Use instance refs/IDs and scoped styles; remove listeners, clear timers, unsubscribe and release handles on cleanup |
|
|
432
|
+
| Automatically submitting/accepting/retrying a charge when data becomes ready or a request times out | Unintended or duplicate transactions | Require user intent; keep unknown/processing states; reconcile the existing attempt instead of creating another payment |
|
|
433
|
+
| Reading browser globals at module evaluation, storing business state in module globals/local storage, or private API/SDK fallbacks | Build failure, stale/cross-session data and bypassed Host controls | Browser work in cleaned-up effects; state per instance; use documented optional Runtime capabilities |
|
|
434
|
+
|
|
435
|
+
For asynchronous writes, acquire a ref lock before the first `await`; a disabled button/state update alone is not a synchronous lock. Release the lock in `finally` and discard stale UI results using the request/selection identity. A local lock does not replace the Host/server transaction guard or idempotency, and a timeout is not evidence that a payment failed. Avoid reporting a second global toast for errors the Host already displays; show a local unavailable/recovery state when needed.
|
|
436
|
+
|
|
437
|
+
For payment examples, validate ordinary Host reference changes, input/quote updates, method/kind switches, session remount, capability withdrawal, delayed resolution after cleanup, failed mounts and StrictMode. Assert both stable DOM/input and bounded mount/request counts. A successful build or Editor preview alone does not verify these properties or a real payment.
|
|
438
|
+
|
|
439
|
+
#### Current capability limits
|
|
440
|
+
|
|
441
|
+
Behavior profiles describe the built-in component's responsibilities, not a promise that each one can be reimplemented through the public Runtime. For every requested business function, check the current contract and actual Host for required authoritative data, operations/parameters, observable result/error/pending states, applicable page/configuration/access conditions, and ownership/persistence/dependencies. Check only affected functions; providers elsewhere on the page may fulfill dependencies.
|
|
442
|
+
|
|
443
|
+
Apply this to all domains, not just login or payment. Product selection is not catalog/inventory editing; applying a coupon is not creating promotion rules; selecting a shipping rate is not creating a shipping service; order/tracking reads are not refunds or cancellations. New points, subscription, notification, upload or other integration behavior needs its own supported capabilities. These are distinctions to verify, not a permanent denylist. Pure presentation and local UI state do not require a business API, but cannot substitute for a saved business result.
|
|
444
|
+
|
|
445
|
+
When an operation is confirmed unsupported, decline that part before creating dependent code: explain the unmet business result, the actual limitation, and a verified alternative if one exists. Preserve supported independent work and existing providers; do not claim full completion, silently deliver a mock, invent an enablement setting or bypass the boundary with private APIs. Distinguish missing support from unknown availability and temporary failure. A separate platform change requires its own scope; it is not implied by merchant customization.
|
|
446
|
+
|
|
447
|
+
- The public Checkout API has no input/mount entry for the platform's additional payment/order information. Some destinations require these fields during payment preparation. Keep the built-in Payment path when these fields apply or their applicability is unknown; a custom payment form cannot claim full coverage. An enabled built-in Payment also owns the native payment surface, so adding a second custom mount is not a supported workaround.
|
|
448
|
+
- Shipping insurance and VIP selections use their original Section identity and dedicated Host billing behavior. `checkout.upsell.setSelection` handles products under the dynamic instance's identity; it cannot substitute for those paid selections or adopt an existing section's selections. Retain the existing providers and configuration for those functions.
|
|
449
|
+
- Required data or actions that are absent from the public API remain unsupported, not inapplicable. Explain the specific unmet requirement and use a supported configuration/layout. Do not invent a private API, charge locally, or expand platform infrastructure as part of a merchant customization.
|
|
450
|
+
|
|
451
|
+
#### Upsell and Downsell runtime
|
|
452
|
+
|
|
453
|
+
`runtime.offer.getSnapshot()` provides recommendations, currency, order confirmation and optional transaction/continuation state. The primary methods are:
|
|
454
|
+
|
|
455
|
+
- `reprice?(input)` obtains the current server quote for a recommendation, variant, quantity and optional purchase option.
|
|
456
|
+
- `accept?(input)` accepts the currently quoted offer. A successful Promise does not by itself mean payment succeeded; inspect the returned status.
|
|
457
|
+
- `getPaymentStatus?(recommendationId)` reads an existing payment status without creating a new charge.
|
|
458
|
+
- `getPaymentAttempt?(recommendationId)` reads an existing payment attempt when available.
|
|
459
|
+
- `leaveAndContinue?()` continues the host-controlled post-purchase flow, resolving to `void` on success and rejecting on failure or when blocked.
|
|
460
|
+
|
|
461
|
+
`reprice` and `accept` use this input shape; IDs and purchase options come from the recommendation snapshot:
|
|
462
|
+
|
|
463
|
+
```ts
|
|
464
|
+
type OfferInput = {
|
|
465
|
+
recommendationId: number;
|
|
466
|
+
variantId: number;
|
|
467
|
+
quantity: number;
|
|
468
|
+
purchaseOptionId?: string;
|
|
469
|
+
};
|
|
470
|
+
```
|
|
471
|
+
|
|
472
|
+
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.
|
|
473
|
+
|
|
474
|
+
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.
|
|
475
|
+
|
|
476
|
+
Offer pages require a recommendation rule for the offer flow, but each component does not need to own one. All CLI starters omit `manifest.capabilities.offerRecommendation`. Ordinary components, including consumers of existing recommendations through `runtime.offer`, leave it omitted. Declare it as `true` only when intentionally providing the page's rules; the Editor then supplies the Product recommendation section. Do not duplicate the platform recommendation fields in your custom schema.
|
|
477
|
+
|
|
478
|
+
When replacing the current rule provider, copy its existing recommendation settings into the replacement instance's `props`, unless the user requested a rule change, and remove the old instance after the replacement is ready. The first provider in template order applies to the page, including hidden sections: hiding the old Offer can leave its rules active and is not a completed replacement. Read back the final page and verify which provider owns the rules. An ordinary component can replace other presentation content without becoming a rule provider. If removing the last provider leaves a required flow unconfigured, explain that specific missing configuration and arrange its intended replacement; do not prohibit deletion because the component is built-in.
|
|
479
|
+
|
|
480
|
+
#### Thank You runtime
|
|
481
|
+
|
|
482
|
+
`runtime.order` is read-only:
|
|
483
|
+
|
|
484
|
+
- `getSnapshot()` and `subscribe(listener)` read the authenticated order state.
|
|
485
|
+
- `refresh?({ target?: "main" | "addOn" | "all" })` refreshes order data without modifying the order.
|
|
486
|
+
- `continueShopping?()` and `viewOrder?()` navigate through host-provided destinations.
|
|
487
|
+
|
|
488
|
+
The snapshot may include order number, status, customer, address, payment summary, lines, totals, currency and `additionalInformation` (read-only `{ title, value }` entries). Display supplied additional information with non-empty titles and values alongside order details; do not invent missing values or expose checkout editing controls. Missing data should be omitted or shown as unavailable until loaded. `getSnapshot()` can be `undefined`. `reads.main` and `reads.addOn` independently describe read state:
|
|
489
|
+
|
|
490
|
+
| Field | Meaning |
|
|
491
|
+
| --- | --- |
|
|
492
|
+
| `status` | `unknown / loading / success / empty / error` |
|
|
493
|
+
| `refreshing`, `stale` | Whether a refresh is in flight and whether existing data is stale |
|
|
494
|
+
| `data` | Last successfully read data; may remain visible after a refresh fails |
|
|
495
|
+
| `error` | Read failure information; a read failure is not a payment failure |
|
|
496
|
+
|
|
497
|
+
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.
|
|
498
|
+
|
|
499
|
+
### Styles, imports and runtime limits
|
|
500
|
+
|
|
501
|
+
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.
|
|
502
|
+
|
|
503
|
+
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.
|
|
504
|
+
|
|
505
|
+
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.
|
|
506
|
+
|
|
507
|
+
### Local preview, Save and Publish
|
|
508
|
+
|
|
509
|
+
| Source | When to use it | How to submit |
|
|
510
|
+
| --- | --- | --- |
|
|
511
|
+
| **Local Dev Server source URL** | Source development and HMR | Save requests a production build and uploads it |
|
|
512
|
+
| **Upload component** | Delivery or replacement of production code | Build and upload `dist/<componentId>.js`; valid `.mjs` artifacts are also supported |
|
|
513
|
+
| **Existing component** | Reuse a component already uploaded to this theme | Select it and configure the current instance |
|
|
514
|
+
|
|
515
|
+
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.
|
|
516
|
+
|
|
517
|
+
| Operation | Effect |
|
|
518
|
+
| --- | --- |
|
|
519
|
+
| Local/HMR or file selection | Updates pending code in the Editor; does not change the storefront |
|
|
520
|
+
| **Save** | Validates and saves shared component draft and current template configuration |
|
|
521
|
+
| **Publish** | Saves if necessary, publishes referenced component artifacts, then publishes template configuration |
|
|
522
|
+
| **Discard** | Restores the latest saved template configuration and clears pending sources; does not roll back shared resources already written |
|
|
523
|
+
|
|
524
|
+
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.
|
|
525
|
+
|
|
526
|
+
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.
|
|
527
|
+
|
|
528
|
+
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.
|
|
529
|
+
|
|
530
|
+
To update an existing component:
|
|
531
|
+
|
|
532
|
+
1. Check the source manifest’s `componentId`. Keep it for a shared update; choose a new ID for independent code.
|
|
533
|
+
2. Connect its Local URL or use **Replace** with a new build. The last successfully loaded source is used.
|
|
534
|
+
3. Verify settings compatibility in other referencing instances. Existing configured values take precedence over changed defaults.
|
|
535
|
+
4. Save and reopen the template to verify the saved draft. Reconnect Local URL after an Editor reload if continuing development.
|
|
536
|
+
5. Publish and refresh the storefront and other referencing templates. After publication, stop Dev Server to verify resource independence.
|
|
537
|
+
|
|
538
|
+
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.
|
|
539
|
+
|
|
540
|
+
### Validation checklist
|
|
541
|
+
|
|
542
|
+
Scale checks to the change. Existing text/color/configuration edits need result and readback checks. For custom code, review the stable final source against the requested behavior and public Runtime, and inspect desktop/mobile rendering. Changed transaction or cross-function behavior warrants a focused independent adversarial review when available; otherwise explicitly self-review and report that limitation. Compare visual work to the reference or agreed theme, including usable controls and relevant error/loading states. Run code review alongside browser checks when practical and repeat only affected checks after fixes; do not add approval stages or fixed review rounds. Unavailable browser/business checks remain unverified.
|
|
543
|
+
|
|
544
|
+
Before publishing, verify:
|
|
545
|
+
|
|
546
|
+
- `npm run build` passes and the artifact is the current source.
|
|
547
|
+
- Manifest page support, schema and defaults match the target template.
|
|
548
|
+
- Preview works on desktop and mobile; HMR does not lose settings or create duplicate subscriptions.
|
|
549
|
+
- Loading, empty, unavailable, validation, network error and duplicate-action states are handled.
|
|
550
|
+
- Review the Runtime guide’s “Patterns to avoid in dynamic components”; test two instances, late/failed responses, session replacement and unmount cleanup.
|
|
551
|
+
- Payment mount/request counts settle after initialization and do not grow on ordinary API/snapshot updates; SDK containers and input values remain stable.
|
|
552
|
+
- Runtime actions check `ok`/status and never assume a Promise means payment success.
|
|
553
|
+
- Save and reopen preserve the component identity and settings.
|
|
554
|
+
- Publish succeeds, the local server can stop, and a refreshed storefront renders the published artifact.
|
|
555
|
+
- Shared component IDs are reviewed across all templates before replacement.
|
|
95
556
|
|
|
96
557
|
## Commands
|
|
97
558
|
|
|
98
|
-
Run project commands inside the generated project:
|
|
559
|
+
Run project commands inside the generated project; `init` creates a new project and is run outside it:
|
|
99
560
|
|
|
100
561
|
| Command | Purpose |
|
|
101
562
|
| --- | --- |
|
|
563
|
+
| `init` | Create the project and first component; see Quick start |
|
|
564
|
+
| `npx dynamic-component create <id> --page-type <type>` | Add a component; restart Dev Server afterward |
|
|
102
565
|
| `npm run dev` | Start the local server; Ctrl+C stops it |
|
|
103
566
|
| `npm run build` | Type-check, validate in a browser and write `dist/<componentId>.js` |
|
|
104
567
|
| `npm run validate` | Run validation without writing production artifacts |
|
|
@@ -108,6 +571,19 @@ Run project commands inside the generated project:
|
|
|
108
571
|
|
|
109
572
|
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
573
|
|
|
574
|
+
`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.
|
|
575
|
+
|
|
576
|
+
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:
|
|
577
|
+
|
|
578
|
+
```bash
|
|
579
|
+
npm run dev -- --port 5189
|
|
580
|
+
npm run build -- --component-id checkout-card
|
|
581
|
+
npm run validate -- --browser-executable /absolute/path/to/browser
|
|
582
|
+
npx dynamic-component doctor --project /absolute/path/to/my-components
|
|
583
|
+
```
|
|
584
|
+
|
|
585
|
+
`--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.
|
|
586
|
+
|
|
111
587
|
## Troubleshooting
|
|
112
588
|
|
|
113
589
|
| Problem | Action |
|
|
@@ -121,10 +597,17 @@ For a manual upload, run `npm run build`, then upload the generated `.js` in the
|
|
|
121
597
|
| 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
598
|
| Build is busy or times out | Wait for the active build to finish, reduce excessive source work if needed, then explicitly retry Save |
|
|
123
599
|
| New component URL is missing | Restart the server after `create` or configuration changes |
|
|
600
|
+
| HMR is `error` or `disconnected` | Fix compilation errors, check the port, restart/reconnect if configuration changed |
|
|
601
|
+
| Dev Server does not support build sessions | Upgrade the project-local CLI and restart; alternatively build in the terminal and upload the artifact |
|
|
602
|
+
| 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 |
|
|
603
|
+
| Resource version conflict | Reload the component/template, review others’ changes, then submit the intended version |
|
|
604
|
+
| Published page still shows old content | Confirm both component and template publication succeeded and that the page uses the intended theme/template; refresh |
|
|
605
|
+
| Runtime capability missing | Check page/shop configuration, handle `undefined` or `unavailable` and do not call absent methods |
|
|
606
|
+
| 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
607
|
|
|
125
|
-
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.
|
|
608
|
+
Builds support up to 500 source files, 1000 source-tree entries, 16 MiB of source and a 1 MiB artifact. Local Save builds also return a deterministic draft-only source ZIP (up to 16 MiB) containing the selected component entry, local dependencies and declarations. The ZIP is created from the same source snapshot as the JavaScript artifact; ordinary `dist` output remains a single JavaScript file. 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
609
|
|
|
127
|
-
Windows/Linux, Safari/Firefox and production HTTPS Editor access remain outside the completed compatibility checks. `doctor` cannot change browser permissions.
|
|
610
|
+
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
611
|
|
|
129
612
|
## Upgrade
|
|
130
613
|
|
|
@@ -146,3 +629,33 @@ Source lives in `shop-visual/packages/dynamic-component-cli`. Types and validati
|
|
|
146
629
|
## License
|
|
147
630
|
|
|
148
631
|
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.
|
|
632
|
+
|
|
633
|
+
## Draft source archives
|
|
634
|
+
|
|
635
|
+
When saving from a Local URL, the Editor uploads the compiled JavaScript and the
|
|
636
|
+
source ZIP together. Source-only changes (including types and declarations) make
|
|
637
|
+
the component pending again. A missing source ZIP requires upgrading the local
|
|
638
|
+
CLI; Local Save does not silently fall back to JavaScript-only upload.
|
|
639
|
+
|
|
640
|
+
The archive contains `dynamic.config.json` with one registration and
|
|
641
|
+
`sourceBuild.cliVersion`, the entry and its local dependencies under `src/`.
|
|
642
|
+
Source bytes and relative paths are preserved. Ambient `src/**/*.d.ts` files are
|
|
643
|
+
included because the standard Starter includes them globally. The archive omits
|
|
644
|
+
package manifests, lockfiles, credentials and installed dependencies. Restore it
|
|
645
|
+
into a clean Starter using the recorded CLI version; validate archive paths,
|
|
646
|
+
entry count and expanded size before extracting, then run `npm run validate` and
|
|
647
|
+
`npm run build`. Normal Save does not download or rebuild the archive.
|
|
648
|
+
|
|
649
|
+
The exported `buildArtifact` / `buildSingleDynamicArtifact` helpers return an
|
|
650
|
+
additional `sourceBundle` (`fileName`, `format: "zip"`, `base64`, `sha256`, `size`).
|
|
651
|
+
MCP callers can reuse this contract; the CLI does not manage platform credentials
|
|
652
|
+
or make backend save requests. The archive is a draft development asset; Publish
|
|
653
|
+
continues to use JavaScript and manifest only. Direct JavaScript upload remains
|
|
654
|
+
supported without source.
|
|
655
|
+
|
|
656
|
+
MCP source persistence uses the same ZIP directory layout. MCP-built archives
|
|
657
|
+
record `sourceBuild.toolVersion`; CLI-built archives record `sourceBuild.cliVersion`.
|
|
658
|
+
The StationSign transport carries ZIP bytes as `source_file_base64` with
|
|
659
|
+
`source_sha256`, `source_file_size`, and `source_format: "zip"`; Admin uses multipart
|
|
660
|
+
`source_file`. Both store source metadata only on the draft. A saved source archive
|
|
661
|
+
must be verified against the authoritative resource response.
|