@bestcheckout/dynamic-component-cli 0.1.1 → 0.1.5

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 CHANGED
@@ -511,7 +511,7 @@ npx dynamic-component doctor --project /absolute/path/to/my-components
511
511
  | Runtime capability missing | Check page/shop configuration, handle `undefined` or `unavailable` and do not call absent methods |
512
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
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.
514
+ 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.
515
515
 
516
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
517
 
@@ -535,3 +535,33 @@ Source lives in `shop-visual/packages/dynamic-component-cli`. Types and validati
535
535
  ## License
536
536
 
537
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.
538
+
539
+ ## Draft source archives
540
+
541
+ When saving from a Local URL, the Editor uploads the compiled JavaScript and the
542
+ source ZIP together. Source-only changes (including types and declarations) make
543
+ the component pending again. A missing source ZIP requires upgrading the local
544
+ CLI; Local Save does not silently fall back to JavaScript-only upload.
545
+
546
+ The archive contains `dynamic.config.json` with one registration and
547
+ `sourceBuild.cliVersion`, the entry and its local dependencies under `src/`.
548
+ Source bytes and relative paths are preserved. Ambient `src/**/*.d.ts` files are
549
+ included because the standard Starter includes them globally. The archive omits
550
+ package manifests, lockfiles, credentials and installed dependencies. Restore it
551
+ into a clean Starter using the recorded CLI version; validate archive paths,
552
+ entry count and expanded size before extracting, then run `npm run validate` and
553
+ `npm run build`. Normal Save does not download or rebuild the archive.
554
+
555
+ The exported `buildArtifact` / `buildSingleDynamicArtifact` helpers return an
556
+ additional `sourceBundle` (`fileName`, `format: "zip"`, `base64`, `sha256`, `size`).
557
+ MCP callers can reuse this contract; the CLI does not manage platform credentials
558
+ or make backend save requests. The archive is a draft development asset; Publish
559
+ continues to use JavaScript and manifest only. Direct JavaScript upload remains
560
+ supported without source.
561
+
562
+ MCP source persistence uses the same ZIP directory layout. MCP-built archives
563
+ record `sourceBuild.toolVersion`; CLI-built archives record `sourceBuild.cliVersion`.
564
+ The StationSign transport carries ZIP bytes as `source_file_base64` with
565
+ `source_sha256`, `source_file_size`, and `source_format: "zip"`; Admin uses multipart
566
+ `source_file`. Both store source metadata only on the draft. A saved source archive
567
+ must be verified against the authoritative resource response.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bestcheckout/dynamic-component-cli",
3
- "version": "0.1.1",
3
+ "version": "0.1.5",
4
4
  "description": "CLI and starter project generator for BestCheckout dynamic components",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -14,14 +14,6 @@
14
14
  "README.md",
15
15
  "LICENSE"
16
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
17
  "engines": {
26
18
  "node": ">=20.10.0"
27
19
  },
@@ -37,6 +29,7 @@
37
29
  "dependencies": {
38
30
  "acorn": "8.15.0",
39
31
  "esbuild": "0.21.5",
32
+ "fflate": "0.8.2",
40
33
  "playwright": "1.56.1",
41
34
  "react": "18.3.1",
42
35
  "react-dom": "18.3.1",
@@ -49,5 +42,13 @@
49
42
  },
50
43
  "devDependencies": {
51
44
  "dts-bundle-generator": "9.5.1"
45
+ },
46
+ "scripts": {
47
+ "test": "node --test tests/*.test.mjs",
48
+ "pack:check": "npm pack --dry-run",
49
+ "test:integration": "node tests/standalone.integration.mjs",
50
+ "test:editor": "node scripts/test-editor.mjs",
51
+ "sync:protocol": "node scripts/sync-protocol.mjs",
52
+ "check:protocol": "node scripts/sync-protocol.mjs --check"
52
53
  }
53
- }
54
+ }
@@ -1,65 +1,81 @@
1
- import { createHash } from 'node:crypto';
2
- import { readFile, stat } from 'node:fs/promises';
3
- import { resolve, relative } from 'node:path';
4
- import { build } from 'esbuild';
5
- import { assertId, inside, safeFile, sourceFiles } from './config.mjs';
6
- import { buildBoundary } from './source-boundary.mjs';
7
- import { validateDynamicArtifactSource } from '../protocol/artifact.mjs';
1
+ import { createHash } from "node:crypto";
2
+ import { readFile, stat, mkdtemp, rm } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import { captureSource, createSourceBundle } from "./source-bundle.mjs";
5
+ import { resolve, relative } from "node:path";
6
+ import { build } from "esbuild";
7
+ import { assertId, safeFile, sourceFiles } from "./config.mjs";
8
+ import { buildBoundary } from "./source-boundary.mjs";
9
+ import { validateDynamicArtifactSource } from "../protocol/artifact.mjs";
8
10
  export async function sourceFingerprint(src) {
9
- const hash = createHash('sha256');
11
+ const hash = createHash("sha256");
10
12
  let size = 0;
11
13
  const files = await sourceFiles(src);
12
- if (files.length > 500) throw new Error('Source tree exceeds 500 files');
14
+ if (files.length > 500) throw new Error("Source tree exceeds 500 files");
13
15
  for (const file of files) {
14
16
  size += (await stat(file)).size;
15
- if (size > 16 * 1024 * 1024) throw new Error('Source tree exceeds 16 MiB');
17
+ if (size > 16 * 1024 * 1024) throw new Error("Source tree exceeds 16 MiB");
16
18
  const bytes = await readFile(file);
17
- if (bytes.length > 16 * 1024 * 1024) throw new Error('Source file exceeds 16 MiB');
18
- hash.update(relative(src, file)).update('\0').update(bytes).update('\0');
19
+ if (bytes.length > 16 * 1024 * 1024)
20
+ throw new Error("Source file exceeds 16 MiB");
21
+ hash.update(relative(src, file)).update("\0").update(bytes).update("\0");
19
22
  }
20
- return hash.digest('hex');
23
+ return hash.digest("hex");
21
24
  }
22
25
  // Shared by CLI build and Editor Local Save. Transform only; no Node import of merchant source.
23
26
  export async function buildArtifact(config, component) {
24
27
  assertId(component.componentId);
25
28
  const entry = await safeFile(
26
29
  config.src,
27
- resolve(config.root, component.entry),
30
+ resolve(config.root, component.entry)
28
31
  );
29
32
  const before = await sourceFingerprint(config.src);
30
- const result = await build({
31
- absWorkingDir: config.root,
32
- entryPoints: [entry],
33
- bundle: true,
34
- write: false,
35
- format: 'esm',
36
- platform: 'browser',
37
- target: 'es2020',
38
- jsx: 'automatic',
39
- logLevel: 'silent',
40
- tsconfigRaw: { compilerOptions: { jsx: 'react-jsx' } },
41
- plugins: [buildBoundary(config.src)],
42
- metafile: true,
43
- });
44
- if (result.outputFiles.length !== 1)
45
- throw new Error(
46
- 'Build must produce one JavaScript file without assets or chunks',
33
+ const snapshotRoot = await mkdtemp(resolve(tmpdir(), "dynamic-source-"));
34
+ try {
35
+ const snapshot = await captureSource(config, snapshotRoot);
36
+ const result = await build({
37
+ absWorkingDir: snapshotRoot,
38
+ entryPoints: [resolve(snapshotRoot, relative(config.root, entry))],
39
+ bundle: true,
40
+ write: false,
41
+ format: "esm",
42
+ platform: "browser",
43
+ target: "es2020",
44
+ jsx: "automatic",
45
+ logLevel: "silent",
46
+ tsconfigRaw: { compilerOptions: { jsx: "react-jsx" } },
47
+ plugins: [buildBoundary(resolve(snapshotRoot, "src"))],
48
+ metafile: true,
49
+ });
50
+ if (result.outputFiles.length !== 1)
51
+ throw new Error(
52
+ "Build must produce one JavaScript file without assets or chunks"
53
+ );
54
+ if (before !== (await sourceFingerprint(config.src)))
55
+ throw new Error("Source changed during build. Review and retry.");
56
+ const sourceText = result.outputFiles[0].text;
57
+ validateDynamicArtifactSource(sourceText);
58
+ const sourceBundle = await createSourceBundle(
59
+ snapshotRoot,
60
+ snapshot,
61
+ component,
62
+ Object.keys(result.metafile.inputs)
47
63
  );
48
- if (before !== (await sourceFingerprint(config.src)))
49
- throw new Error('Source changed during build. Review and retry.');
50
- const sourceText = result.outputFiles[0].text;
51
- validateDynamicArtifactSource(sourceText);
52
- return {
53
- componentId: component.componentId,
54
- fileName: component.componentId + '.js',
55
- sourceText,
56
- sourceHash: createHash('sha256').update(sourceText).digest('hex'),
57
- };
64
+ return {
65
+ sourceBundle,
66
+ componentId: component.componentId,
67
+ fileName: component.componentId + ".js",
68
+ sourceText,
69
+ sourceHash: createHash("sha256").update(sourceText).digest("hex"),
70
+ };
71
+ } finally {
72
+ await rm(snapshotRoot, { recursive: true, force: true });
73
+ }
58
74
  }
59
75
  export async function buildSingleDynamicArtifact(
60
76
  sourceUrl,
61
77
  componentId,
62
- options,
78
+ options
63
79
  ) {
64
80
  assertId(componentId);
65
81
  const config = options.config;
@@ -70,16 +86,16 @@ export async function buildSingleDynamicArtifact(
70
86
  url.password ||
71
87
  url.hash ||
72
88
  url.search ||
73
- !url.pathname.startsWith('/src/')
89
+ !url.pathname.startsWith("/src/")
74
90
  )
75
91
  throw new Error(
76
- 'sourceUrl must point to a registered entry on this Dev Server',
92
+ "sourceUrl must point to a registered entry on this Dev Server"
77
93
  );
78
94
  const entry = decodeURIComponent(url.pathname.slice(1));
79
95
  const component = config.components.find(
80
- (item) => item.componentId === componentId && item.entry === entry,
96
+ (item) => item.componentId === componentId && item.entry === entry
81
97
  );
82
98
  if (!component)
83
- throw new Error('componentId/sourceUrl does not match dynamic.config.json');
99
+ throw new Error("componentId/sourceUrl does not match dynamic.config.json");
84
100
  return buildArtifact(config, component);
85
101
  }
@@ -3,6 +3,7 @@ import { execFile } from 'node:child_process';
3
3
  import { promisify } from 'node:util';
4
4
  import { createRequire } from 'node:module';
5
5
  import { readFile } from 'node:fs/promises';
6
+ import { dirname, join } from 'node:path';
6
7
  import { readConfig } from './config.mjs';
7
8
  import { launchBrowser } from './browser.mjs';
8
9
  const require = createRequire(import.meta.url);
@@ -38,7 +39,17 @@ export async function diagnose(root, options = {}) {
38
39
  await readFile(new URL('../../package.json', import.meta.url), 'utf8'),
39
40
  );
40
41
  for (const [name, expected] of Object.entries(pkg.dependencies)) {
41
- const actual = require(`${name}/package.json`).version;
42
+ const entry = require.resolve(name);
43
+ let directory = dirname(entry);
44
+ let actual;
45
+ for (let index = 0; index < 5 && !actual; index++) {
46
+ try {
47
+ const metadata = JSON.parse(await readFile(join(directory, 'package.json'), 'utf8'));
48
+ if (metadata.name === name) actual = metadata.version;
49
+ } catch (error) { if (error.code !== 'ENOENT') throw error; }
50
+ directory = dirname(directory);
51
+ }
52
+ if (!actual) throw new Error(`${name}: package metadata unavailable`);
42
53
  if (actual !== expected)
43
54
  throw new Error(
44
55
  `${name}: expected ${expected}, found ${actual}. Reinstall the CLI package.`,
@@ -83,7 +94,8 @@ export async function diagnose(root, options = {}) {
83
94
  }
84
95
  if (
85
96
  meta.protocolVersion !== 1 ||
86
- meta.build?.url !== origin + '/.well-known/dynamic-build' ||
97
+ typeof meta.build?.url !== 'string' ||
98
+ new URL(meta.build.url, origin).href !== origin + '/.well-known/dynamic-build' ||
87
99
  meta.hmr?.transport !== 'websocket'
88
100
  )
89
101
  throw new Error(
@@ -15,6 +15,7 @@ function json(response, status, body) {
15
15
  }
16
16
  export async function serveProject(root, options = {}) {
17
17
  const config = await readConfig(root, options);
18
+ root = config.root;
18
19
  const port = config.server.port;
19
20
  const origin = `http://127.0.0.1:${port}`;
20
21
  const canonicalBuildInput = (input) => {
@@ -35,6 +36,12 @@ export async function serveProject(root, options = {}) {
35
36
  enforce: 'pre',
36
37
  configureServer(server) {
37
38
  let busy = false;
39
+ const changed = (_event, path) => {
40
+ if (inside(config.src, resolve(path)) || resolve(path) === resolve(root, 'dynamic.config.json'))
41
+ server.ws.send({ type: 'custom', event: 'dynamic-source-changed', data: {} });
42
+ };
43
+ server.watcher.on('all', changed);
44
+ server.httpServer?.once('close', () => server.watcher.off('all', changed));
38
45
  const buildSessions = createBuildSessions();
39
46
  server.httpServer?.once('close', () => buildSessions.close());
40
47
  server.middlewares.use(async (request, response, next) => {
@@ -44,6 +51,9 @@ export async function serveProject(root, options = {}) {
44
51
  response.setHeader('Access-Control-Allow-Origin', '*');
45
52
  response.setHeader('Access-Control-Allow-Methods', 'GET,POST,OPTIONS');
46
53
  response.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
54
+ if (request.headers['access-control-request-private-network'] === 'true') {
55
+ response.setHeader('Access-Control-Allow-Private-Network', 'true');
56
+ }
47
57
  if (request.method === 'OPTIONS') {
48
58
  response.statusCode = 204;
49
59
  response.end();
@@ -59,11 +69,11 @@ export async function serveProject(root, options = {}) {
59
69
  return json(response, 405, { message: 'GET is required' });
60
70
  return json(response, 200, {
61
71
  protocolVersion: 1,
62
- build: { url: origin + '/.well-known/dynamic-build' },
63
- buildSession: { url: origin + '/.well-known/dynamic-build-session' },
72
+ build: { url: '/.well-known/dynamic-build' },
73
+ buildSession: { url: '/.well-known/dynamic-build-session' },
64
74
  hmr: {
65
75
  transport: 'websocket',
66
- url: `ws://127.0.0.1:${port}/`,
76
+ url: `ws://${host}/`,
67
77
  protocol: 'vite-hmr',
68
78
  token: server.config.webSocketToken,
69
79
  },
@@ -91,6 +101,9 @@ export async function serveProject(root, options = {}) {
91
101
  if (busy) return json(response, 409, { message: 'A local build is already running. Save again after it completes.' });
92
102
  busy = true;
93
103
  try {
104
+ const currentConfig = await readConfig(root, options);
105
+ if (JSON.stringify(currentConfig) !== JSON.stringify(config))
106
+ throw new Error('Project configuration changed. Restart the CLI and review before saving.');
94
107
  return json(response, 200, await runBuildWorker(new URL('./build-worker.mjs', import.meta.url), {
95
108
  ...input, options: { config, origin: new URL(input.sourceUrl).origin },
96
109
  }));
@@ -0,0 +1,135 @@
1
+ import { readFile, mkdir, writeFile } from "node:fs/promises";
2
+ import { resolve, relative, dirname } from "node:path";
3
+ import { createHash } from "node:crypto";
4
+ import ts from "typescript";
5
+ import { zipSync } from "fflate";
6
+ import { inside, sourceFiles } from "./config.mjs";
7
+ import { assertPublicImport } from "./source-boundary.mjs";
8
+
9
+ const limit = 16 * 1024 * 1024;
10
+ export async function captureSource(config, root) {
11
+ let size = 0;
12
+ const snapshot = new Map();
13
+ for (const file of await sourceFiles(config.src)) {
14
+ const bytes = await readFile(file);
15
+ size += bytes.length;
16
+ if (size > limit) throw new Error("Source tree exceeds 16 MiB");
17
+ const path = relative(config.root, file).split("\\").join("/");
18
+ snapshot.set(path, bytes);
19
+ const target = resolve(root, path);
20
+ await mkdir(dirname(target), { recursive: true });
21
+ await writeFile(target, bytes);
22
+ }
23
+ return snapshot;
24
+ }
25
+
26
+ /** Resolve from the captured tree, including imports erased by the JS compiler. */
27
+ export async function createSourceBundle(
28
+ root,
29
+ snapshot,
30
+ component,
31
+ runtimeInputs
32
+ ) {
33
+ const selected = new Set();
34
+ const compilerOptions = {
35
+ moduleResolution: ts.ModuleResolutionKind.Bundler,
36
+ allowJs: true,
37
+ resolveJsonModule: true,
38
+ };
39
+ const visit = (path) => {
40
+ path = path.split("\\").join("/");
41
+ if (selected.has(path)) return;
42
+ if (
43
+ !inside(resolve(root, "src"), resolve(root, path)) ||
44
+ // Keep the archive boundary aligned with the extensions TypeScript and
45
+ // esbuild can resolve from a component project, including ESM/CJS
46
+ // module variants.
47
+ !/\.(?:[cm]?[jt]sx?|json)$/.test(path) ||
48
+ /(?:^|[/\\])\./.test(path)
49
+ )
50
+ throw new Error(`Unsupported source path: ${path}`);
51
+ const bytes = snapshot.get(path);
52
+ if (!bytes) throw new Error(`Cannot collect source dependency: ${path}`);
53
+ selected.add(path);
54
+ if (path.endsWith(".json")) return;
55
+ const info = ts.preProcessFile(bytes.toString("utf8"), true, true);
56
+ for (const item of info.importedFiles) {
57
+ if (!item.fileName.startsWith(".")) {
58
+ if (item.fileName !== "@bestcheckout/dynamic-component-cli/types")
59
+ assertPublicImport(item.fileName);
60
+ continue;
61
+ }
62
+ assertPublicImport(item.fileName);
63
+ const resolved = ts.resolveModuleName(
64
+ item.fileName,
65
+ resolve(root, path),
66
+ compilerOptions,
67
+ ts.sys
68
+ ).resolvedModule;
69
+ if (!resolved)
70
+ throw new Error(
71
+ `Cannot collect source dependency: ${item.fileName} from ${path}`
72
+ );
73
+ visit(relative(root, resolved.resolvedFileName));
74
+ }
75
+ for (const item of info.referencedFiles)
76
+ visit(relative(root, resolve(root, dirname(path), item.fileName)));
77
+ for (const item of info.typeReferenceDirectives) {
78
+ if (
79
+ ![
80
+ "react",
81
+ "react-dom",
82
+ "@bestcheckout/dynamic-component-cli/types",
83
+ ].includes(item.fileName)
84
+ )
85
+ throw new Error(`Unsupported type dependency: ${item.fileName}`);
86
+ }
87
+ if (info.libReferenceDirectives.length)
88
+ throw new Error("Custom reference lib directives are not supported");
89
+ };
90
+ visit(component.entry);
91
+ for (const input of runtimeInputs)
92
+ visit(relative(root, resolve(root, input)));
93
+ // Standard tsconfig includes src declarations globally, even without an import.
94
+ for (const path of snapshot.keys()) if (path.endsWith(".d.ts")) visit(path);
95
+ const { version } = JSON.parse(
96
+ await readFile(new URL("../../package.json", import.meta.url), "utf8")
97
+ );
98
+ const files = Object.create(null);
99
+ const options = { level: 6, mtime: new Date(1980, 0, 1) };
100
+ files["dynamic.config.json"] = [
101
+ Buffer.from(
102
+ JSON.stringify(
103
+ {
104
+ protocolVersion: 1,
105
+ components: [
106
+ {
107
+ componentId: component.componentId,
108
+ pageType: component.pageType,
109
+ entry: component.entry,
110
+ },
111
+ ],
112
+ sourceBuild: { cliVersion: version },
113
+ },
114
+ null,
115
+ 2
116
+ ) + "\n"
117
+ ),
118
+ options,
119
+ ];
120
+ for (const path of [...selected].sort())
121
+ files[path] = [snapshot.get(path), options];
122
+ if (
123
+ Object.values(files).reduce((sum, [bytes]) => sum + bytes.length, 0) > limit
124
+ )
125
+ throw new Error("Uncompressed source ZIP exceeds 16 MiB");
126
+ const bytes = Buffer.from(zipSync(files));
127
+ if (bytes.length > limit) throw new Error("Source ZIP exceeds 16 MiB");
128
+ return {
129
+ fileName: `${component.componentId}-source.zip`,
130
+ format: "zip",
131
+ size: bytes.length,
132
+ sha256: createHash("sha256").update(bytes).digest("hex"),
133
+ base64: bytes.toString("base64"),
134
+ };
135
+ }
@@ -15,6 +15,55 @@ function isRecord(value) {
15
15
  function isPageType(value) {
16
16
  return value === "checkout" || value === "upsell" || value === "downsell" || value === "thankYou";
17
17
  }
18
+ function describeType(value) {
19
+ if (Array.isArray(value)) return "array";
20
+ if (value === null) return "null";
21
+ return typeof value;
22
+ }
23
+ function validateDynamicSettingTypes(schema, defaults) {
24
+ const fields = Array.isArray(schema) ? schema : isRecord(schema) && Array.isArray(schema.fields) ? schema.fields : [];
25
+ const errors = [];
26
+ for (const field of fields) {
27
+ if (!isRecord(field) || typeof field.key !== "string") continue;
28
+ const value = field.key.split(".").reduce(
29
+ (current, key) => isRecord(current) && Object.prototype.hasOwnProperty.call(current, key) ? current[key] : void 0,
30
+ defaults
31
+ );
32
+ if (value == null) continue;
33
+ const type = field.type;
34
+ const text = ["text", "textarea", "richtext", "url", "color", "html", "css", "date"].includes(String(type));
35
+ const choice = ["select", "radio", "segmented"].includes(String(type));
36
+ const expected = text ? "string" : type === "toggle" ? "boolean" : type === "number" || type === "range" ? "finite number" : type === "array" ? "array" : choice ? field.multiple ? "string[]" : "string" : void 0;
37
+ const valid = expected === void 0 || (expected === "string" ? typeof value === "string" : expected === "boolean" ? typeof value === "boolean" : expected === "finite number" ? typeof value === "number" && Number.isFinite(value) : expected === "string[]" ? Array.isArray(value) && value.every((item) => typeof item === "string") : Array.isArray(value));
38
+ if (!valid && expected) {
39
+ let preview;
40
+ try {
41
+ preview = JSON.stringify(value) ?? String(value);
42
+ } catch {
43
+ preview = "[unserializable]";
44
+ }
45
+ preview = preview.slice(0, 160);
46
+ const actual = describeType(value);
47
+ errors.push({
48
+ field: field.key,
49
+ expected,
50
+ actual,
51
+ value: preview,
52
+ message: `invalid ${field.key}: expected ${expected}, received ${actual} (${preview})`
53
+ });
54
+ }
55
+ if (type === "array" && Array.isArray(value) && Array.isArray(field.itemFields)) {
56
+ value.forEach((item, index) => {
57
+ if (!isRecord(item)) return;
58
+ for (const issue of validateDynamicSettingTypes(field.itemFields, item)) {
59
+ const path = `${field.key}[${index}].${issue.field}`;
60
+ errors.push({ ...issue, field: path, message: `invalid ${path}: expected ${issue.expected}, received ${issue.actual} (${issue.value})` });
61
+ }
62
+ });
63
+ }
64
+ }
65
+ return errors;
66
+ }
18
67
  function validateDynamicManifest(value) {
19
68
  if (!isRecord(value))
20
69
  return { ok: false, error: "manifest must be an object" };
@@ -55,12 +104,19 @@ function validateDynamicComponentDefinition(value) {
55
104
  return { ok: false, error: "definition must be an object" };
56
105
  const manifestResult = validateDynamicManifest(value.manifest);
57
106
  if (!manifestResult.ok) return manifestResult;
58
- if (!isRecord(value.defaultSettings)) {
107
+ if (!isRecord(value.defaultSettings) || Array.isArray(value.defaultSettings)) {
59
108
  return { ok: false, error: "defaultSettings must be an object" };
60
109
  }
61
110
  if (!isRecord(value.schema) && !Array.isArray(value.schema)) {
62
111
  return { ok: false, error: "schema must be an object or array" };
63
112
  }
113
+ const typeErrors = validateDynamicSettingTypes(value.schema, value.defaultSettings);
114
+ if (typeErrors.length) {
115
+ return {
116
+ ok: false,
117
+ error: `defaultSettings type mismatch: ${typeErrors.map((issue) => issue.message).join("; ")}`
118
+ };
119
+ }
64
120
  if (manifestResult.manifest.capabilities?.offerRecommendation) {
65
121
  const fields = Array.isArray(value.schema) ? value.schema : value.schema.fields;
66
122
  if (Array.isArray(fields) && fields.some(
package/types/index.d.ts CHANGED
@@ -186,7 +186,7 @@ type CheckoutDynamicHost = {
186
186
  /** Change the selected secure/payment method through the Host guard. */
187
187
  selectPaymentMethod?(method: string): CheckoutActionResult;
188
188
  /** Reserve a secure form before React/SDK creation. The adapter owns release. */
189
- acquirePaymentMount?(identity: CheckoutInstanceIdentity, method: string): {
189
+ acquirePaymentMount?(identity: CheckoutInstanceIdentity, method: string, kind?: "secure" | "action" | "express"): {
190
190
  render(): ReactNode;
191
191
  validate(): Promise<CheckoutValidationResult>;
192
192
  release(): void;
@@ -330,6 +330,8 @@ type CheckoutExpressPaymentMethod = {
330
330
  appearance?: "shop-pay" | "paypal" | "google-pay" | "apple-pay";
331
331
  };
332
332
  type CheckoutPaymentMethod = {
333
+ /** Secure methods use Host submit; native methods use their mounted SDK action button. */
334
+ submission?: "secure" | "native";
333
335
  id: string;
334
336
  title: string;
335
337
  description?: string;
@@ -354,8 +356,11 @@ type CheckoutPaymentActionRenderProps = {
354
356
  method: CheckoutPaymentMethod;
355
357
  isSubmitting: boolean;
356
358
  };
357
- type CheckoutDeliveryField = "firstName" | "lastName" | "address" | "apartment" | "state" | "stateInput" | "city" | "cityInput" | "zip" | "phone";
358
- type CheckoutDeliveryValues = Record<CheckoutDeliveryField, string> & {
359
+ type CheckoutDeliveryField = "streetName" | "buildingNumber" | "district" | "firstName" | "lastName" | "address" | "apartment" | "state" | "stateInput" | "city" | "cityInput" | "zip" | "phone";
360
+ type CheckoutDeliveryValues = Record<Exclude<CheckoutDeliveryField, "streetName" | "buildingNumber" | "district">, string> & {
361
+ streetName?: string;
362
+ buildingNumber?: string;
363
+ district?: string;
359
364
  country: string;
360
365
  };
361
366
  type CheckoutDeliveryOption = {
@@ -397,11 +402,30 @@ type CheckoutAccount = {
397
402
  email: string;
398
403
  avatar?: string;
399
404
  };
405
+ type CheckoutAddressSchema = Record<"state" | "city" | "zip", {
406
+ visible: boolean;
407
+ required: boolean;
408
+ label: string;
409
+ order: number;
410
+ }>;
400
411
  type CheckoutDeliveryState = {
401
412
  values: CheckoutDeliveryValues;
413
+ locationStatus?: string;
414
+ retryLocations?: () => void;
402
415
  countryOptions: CheckoutDeliveryOption[];
403
416
  stateOptions: CheckoutDeliveryOption[];
404
417
  cityOptions: CheckoutDeliveryOption[];
418
+ lastNameFirst?: boolean;
419
+ addressLayout?: {
420
+ field: CheckoutDeliveryField;
421
+ label: string;
422
+ required: boolean;
423
+ span?: number;
424
+ placeholder?: string;
425
+ widget?: "select" | "text" | "combobox";
426
+ }[][];
427
+ addressSchema?: CheckoutAddressSchema;
428
+ isAddressComplete?: boolean;
405
429
  useStateSelect: boolean;
406
430
  useCitySelect: boolean;
407
431
  phoneCode?: string;
@@ -416,9 +440,22 @@ type CheckoutDeliveryState = {
416
440
  };
417
441
  type CheckoutBillingState = {
418
442
  values: CheckoutDeliveryValues;
443
+ locationStatus?: string;
444
+ retryLocations?: () => void;
419
445
  countryOptions: CheckoutDeliveryOption[];
420
446
  stateOptions: CheckoutDeliveryOption[];
421
447
  cityOptions: CheckoutDeliveryOption[];
448
+ lastNameFirst?: boolean;
449
+ addressLayout?: {
450
+ field: CheckoutDeliveryField;
451
+ label: string;
452
+ required: boolean;
453
+ span?: number;
454
+ placeholder?: string;
455
+ widget?: "select" | "text" | "combobox";
456
+ }[][];
457
+ addressSchema?: CheckoutAddressSchema;
458
+ isAddressComplete?: boolean;
422
459
  useStateSelect: boolean;
423
460
  useCitySelect: boolean;
424
461
  phoneCode?: string;
@@ -499,6 +536,7 @@ type CheckoutRuntime = {
499
536
  startExpressCheckout?: (method: string) => void;
500
537
  renderExpressCheckout?: (props: CheckoutExpressCheckoutRenderProps) => ReactNode;
501
538
  renderPaymentDetails?: (props: CheckoutPaymentDetailsRenderProps) => ReactNode;
539
+ renderAdditionalInformation?: () => ReactNode;
502
540
  renderPaymentAction?: (props: CheckoutPaymentActionRenderProps) => ReactNode;
503
541
  setContactEmail?: (email: string) => void;
504
542
  openSignIn?: () => void;
@@ -515,6 +553,12 @@ type CheckoutRuntime = {
515
553
  editSavedAddress?: (addressId: string) => void;
516
554
  deleteSavedAddress?: (addressId: string) => void;
517
555
  applyGoogleDeliveryAddress?: (address: CheckoutGoogleAddress) => void;
556
+ renderBillingPhoneInput?: (props: {
557
+ placeholder: string;
558
+ }) => ReactNode;
559
+ renderDeliveryPhoneInput?: (props: {
560
+ placeholder: string;
561
+ }) => ReactNode;
518
562
  renderDeliveryAddressInput?: (props: CheckoutAddressInputRenderProps) => ReactNode;
519
563
  billing?: CheckoutBillingState;
520
564
  setBillingSameAsShipping?: (sameAsShipping: boolean) => void;
@@ -604,6 +648,11 @@ type CheckoutThankYouSnapshot = {
604
648
  billingAddress?: CheckoutAddress;
605
649
  billingSameAsShipping?: boolean;
606
650
  shippingMethod?: string;
651
+ /** Read-only order-level tax and identity fields supplied by the Storefront. */
652
+ additionalInformation?: Array<{
653
+ title: string;
654
+ value: string;
655
+ }>;
607
656
  payment?: {
608
657
  brand?: string;
609
658
  last4?: string;
@@ -832,6 +881,9 @@ declare function toCheckoutSnapshot(host: CheckoutRuntime, preview?: boolean): {
832
881
  useStateSelect: boolean;
833
882
  useCitySelect: boolean;
834
883
  phoneCode?: string;
884
+ locationStatus?: string | undefined;
885
+ lastNameFirst?: boolean | undefined;
886
+ isAddressComplete?: boolean | undefined;
835
887
  savedAddressCount?: number | undefined;
836
888
  selectedSavedAddressId?: string | undefined;
837
889
  isSavedAddressListExpanded?: boolean | undefined;
@@ -847,6 +899,9 @@ declare function toCheckoutSnapshot(host: CheckoutRuntime, preview?: boolean): {
847
899
  useStateSelect: boolean;
848
900
  useCitySelect: boolean;
849
901
  phoneCode?: string;
902
+ locationStatus?: string | undefined;
903
+ lastNameFirst?: boolean | undefined;
904
+ isAddressComplete?: boolean | undefined;
850
905
  googlePlacesApiKey?: string | undefined;
851
906
  sameAsShipping: boolean;
852
907
  hasShippingAddress: boolean;
@@ -871,7 +926,7 @@ declare function toCheckoutSnapshot(host: CheckoutRuntime, preview?: boolean): {
871
926
  isApplying: boolean | undefined;
872
927
  };
873
928
  payment: {
874
- methods: Pick<CheckoutPaymentMethod, "description" | "title" | "id" | "showCardBrandIcons">[];
929
+ methods: Pick<CheckoutPaymentMethod, "description" | "title" | "id" | "showCardBrandIcons" | "submission">[];
875
930
  selectedMethod: string;
876
931
  isSubmitting: boolean | undefined;
877
932
  expressMethods: Pick<CheckoutExpressPaymentMethod, "label" | "id" | "appearance">[];
@@ -897,6 +952,9 @@ declare function createDynamicCheckoutAdapter(context: DynamicComponentContext,
897
952
  useStateSelect: boolean;
898
953
  useCitySelect: boolean;
899
954
  phoneCode?: string;
955
+ locationStatus?: string | undefined;
956
+ lastNameFirst?: boolean | undefined;
957
+ isAddressComplete?: boolean | undefined;
900
958
  savedAddressCount?: number | undefined;
901
959
  selectedSavedAddressId?: string | undefined;
902
960
  isSavedAddressListExpanded?: boolean | undefined;
@@ -912,6 +970,9 @@ declare function createDynamicCheckoutAdapter(context: DynamicComponentContext,
912
970
  useStateSelect: boolean;
913
971
  useCitySelect: boolean;
914
972
  phoneCode?: string;
973
+ locationStatus?: string | undefined;
974
+ lastNameFirst?: boolean | undefined;
975
+ isAddressComplete?: boolean | undefined;
915
976
  googlePlacesApiKey?: string | undefined;
916
977
  sameAsShipping: boolean;
917
978
  hasShippingAddress: boolean;
@@ -936,7 +997,7 @@ declare function createDynamicCheckoutAdapter(context: DynamicComponentContext,
936
997
  isApplying: boolean | undefined;
937
998
  };
938
999
  payment: {
939
- methods: Pick<CheckoutPaymentMethod, "description" | "title" | "id" | "showCardBrandIcons">[];
1000
+ methods: Pick<CheckoutPaymentMethod, "description" | "title" | "id" | "showCardBrandIcons" | "submission">[];
940
1001
  selectedMethod: string;
941
1002
  isSubmitting: boolean | undefined;
942
1003
  expressMethods: Pick<CheckoutExpressPaymentMethod, "label" | "id" | "appearance">[];
@@ -986,6 +1047,9 @@ declare function createDynamicCheckoutAdapter(context: DynamicComponentContext,
986
1047
  useStateSelect: boolean;
987
1048
  useCitySelect: boolean;
988
1049
  phoneCode?: string;
1050
+ locationStatus?: string | undefined;
1051
+ lastNameFirst?: boolean | undefined;
1052
+ isAddressComplete?: boolean | undefined;
989
1053
  savedAddressCount?: number | undefined;
990
1054
  selectedSavedAddressId?: string | undefined;
991
1055
  isSavedAddressListExpanded?: boolean | undefined;
@@ -1053,6 +1117,9 @@ declare function createDynamicCheckoutAdapter(context: DynamicComponentContext,
1053
1117
  useStateSelect: boolean;
1054
1118
  useCitySelect: boolean;
1055
1119
  phoneCode?: string;
1120
+ locationStatus?: string | undefined;
1121
+ lastNameFirst?: boolean | undefined;
1122
+ isAddressComplete?: boolean | undefined;
1056
1123
  googlePlacesApiKey?: string | undefined;
1057
1124
  sameAsShipping: boolean;
1058
1125
  hasShippingAddress: boolean;
@@ -1123,7 +1190,7 @@ declare function createDynamicCheckoutAdapter(context: DynamicComponentContext,
1123
1190
  };
1124
1191
  payment: {
1125
1192
  getState: () => {
1126
- methods: Pick<CheckoutPaymentMethod, "description" | "title" | "id" | "showCardBrandIcons">[];
1193
+ methods: Pick<CheckoutPaymentMethod, "description" | "title" | "id" | "showCardBrandIcons" | "submission">[];
1127
1194
  selectedMethod: string;
1128
1195
  isSubmitting: boolean | undefined;
1129
1196
  expressMethods: Pick<CheckoutExpressPaymentMethod, "label" | "id" | "appearance">[];