@c1m-public/channel-client 0.11.0 → 0.14.0

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
@@ -12,6 +12,8 @@ transport core.
12
12
  policy layered over the same client.
13
13
  - `@c1m-public/channel-client/webhooks` — framework-neutral webhook events and
14
14
  signature verification.
15
+ - `@c1m-public/channel-client/renderer` — framework-neutral canonical document
16
+ traversal, responsive CSS safety, and injected block registries.
15
17
 
16
18
  Channel credentials resolve the tenant and scope at the API door (plus the
17
19
  workspace for workspace-scoped channels), so site URLs never carry those
@@ -68,6 +70,38 @@ const directory = await channel.dash.directory.list({ region: "london" });
68
70
  const account = channel.withCustomer(customerAccessToken);
69
71
  const addresses = await account.addresses.list();
70
72
  const subscriptions = await account.subscriptions.list({ status: "active" });
73
+ const sessions = await account.sessions.list();
74
+ const activity = await account.securityActivity();
75
+ ```
76
+
77
+ ### Trusted visitor context
78
+
79
+ Server-rendered sites may pass edge-provided visitor metadata without trusting
80
+ browser-supplied forwarding headers. `withVisitor()` signs the bounded IP,
81
+ country, user-agent hash, method, and exact Channel API URI with the channel
82
+ token. C1M verifies it before geo or rate-limit use.
83
+
84
+ ```ts
85
+ const visitorChannel = channel.withVisitor({
86
+ ip: trustedEdgeIP,
87
+ country: trustedEdgeCountry,
88
+ userAgent: request.headers.get("user-agent") ?? "",
89
+ });
90
+ const geo = await visitorChannel.geo.detect();
91
+ ```
92
+
93
+ ### Canonical document renderer
94
+
95
+ The renderer owns safe mechanics, not presentation. A site supplies a registry
96
+ whose values can be React nodes, strings, or any other output type.
97
+
98
+ ```ts
99
+ import { collectResponsiveCSS, renderSiteDocument } from "@c1m-public/channel-client/renderer";
100
+
101
+ const blocks = renderSiteDocument(document, {
102
+ registry: { text: ({ node }) => String(node.props?.text ?? "") },
103
+ });
104
+ const css = collectResponsiveCSS(document);
71
105
  ```
72
106
 
73
107
  ### Headless customer OTP
@@ -166,6 +200,10 @@ Publishing runs through npm Trusted Publishing and GitHub OIDC. Push a protected
166
200
  packs, and publishes without a stored npm token. Published versions are
167
201
  immutable, so increment the package version for every release.
168
202
 
203
+ The release workflow also accepts a manual dispatch with an existing release
204
+ tag. This is only a safe retry mechanism: it checks out that immutable tag and
205
+ verifies the package version before publishing.
206
+
169
207
  ## The `/next` kits
170
208
 
171
209
  The ~600 lines of plumbing every headless site was copy-pasting, shipped once.
@@ -185,20 +223,32 @@ export const POST = createChannelWebhookRoute({
185
223
 
186
224
  Out of the box that route keeps your cache honest with no configuration:
187
225
  `page.published` revalidates the published path plus `CHANNEL_SITE_CACHE_TAG`,
188
- and every `product.*` event revalidates `CHANNEL_CATALOG_CACHE_TAG`. Tag your
189
- catalog reads with it and a merchant's price edit reaches the storefront on the
190
- next request instead of at the end of a TTL — the difference between a correct
191
- price and a stale one at checkout.
226
+ and every `product.*` event revalidates `CHANNEL_CATALOG_CACHE_TAG`. Since
227
+ 0.14.0 the Next adapter files reads under those tags for you: product,
228
+ category, collection and brand reads carry `channel:catalog`, every other
229
+ anonymous read carries `channel:site` — so a merchant's price edit reaches the
230
+ storefront on the next request instead of at the end of a TTL. Pass
231
+ `cache.tags` to add your own on top, or `cache.tagsFor(pathname)` to replace
232
+ the classifier (`defaultChannelCacheTags` is exported to compose with).
192
233
 
193
234
  ```ts
194
- // A client whose reads are filed under the catalog tag the webhook route busts.
195
- const catalog = createNextChannelClient({
235
+ const channel = createNextChannelClient({
196
236
  token: process.env.C1M_CHANNEL_TOKEN!,
197
- cache: { revalidate: 3600, tags: [CHANNEL_CATALOG_CACHE_TAG] },
237
+ cache: { revalidate: 3600 }, // products.list() → tags ["channel:catalog"]
198
238
  });
199
- const products = await catalog.products.list();
200
239
  ```
201
240
 
241
+ ### One-call bootstrap
242
+
243
+ `init.light()` is the shell payload: identity, branding, features,
244
+ `preferences{currency,locale,timezone}`, `seo{title,description}` and
245
+ `site{url,source,channel_id}` — the workspace's public origin resolved
246
+ server-side (verified hostname › channel site URL › managed host). Use
247
+ `site.url` for `metadataBase`, canonical/OG URLs, robots and sitemaps instead
248
+ of a hardcoded base URL. Navigation (`menus.get`) and theme (`theme.get`) stay
249
+ separate, parallel reads. `dash.init()` is the same shape for dash sites
250
+ (`branding`, `locale`, `seo`, `site`).
251
+
202
252
  The core also exposes the complete current channel door: public category,
203
253
  collection and brand navigation; published blog and giving reads; cart and
204
254
  checkout; Quick Print settings, quotes and multipart intake; assembled dining
@@ -0,0 +1,11 @@
1
+ import "server-only";
2
+ import { type DashChannelClient } from "./dash.js";
3
+ import { type CreateNextChannelClientOptions } from "./next.js";
4
+ /**
5
+ * Dash-scoped client with Next.js Data Cache semantics — the factory a
6
+ * dash-site base should use. Anonymous dash GETs may receive `next.revalidate`;
7
+ * visitor-signed calls (geo, lead capture) should go through a `no-store`
8
+ * client so per-visitor answers are never cached under a shared tag.
9
+ */
10
+ export declare function createNextDashChannelClient(options: CreateNextChannelClientOptions): DashChannelClient;
11
+ export type { DashChannelClient } from "./dash.js";
@@ -0,0 +1,12 @@
1
+ import "server-only";
2
+ import { narrowToDash } from "./dash.js";
3
+ import { createNextChannelClient } from "./next.js";
4
+ /**
5
+ * Dash-scoped client with Next.js Data Cache semantics — the factory a
6
+ * dash-site base should use. Anonymous dash GETs may receive `next.revalidate`;
7
+ * visitor-signed calls (geo, lead capture) should go through a `no-store`
8
+ * client so per-visitor answers are never cached under a shared tag.
9
+ */
10
+ export function createNextDashChannelClient(options) {
11
+ return narrowToDash(createNextChannelClient(options));
12
+ }
package/dist/dash.d.ts ADDED
@@ -0,0 +1,23 @@
1
+ import "server-only";
2
+ import { createChannelClient, type ChannelVisitor, type CreateChannelClientOptions } from "./index.js";
3
+ /**
4
+ * The dash-scoped surface of the Channel API: what a dash marketing site
5
+ * (localprint.app, greatremovals…) is allowed to call. It is a TYPE PROJECTION
6
+ * of the full client — same transport, same retries, same visitor signing,
7
+ * same release train — narrowed so dash-site code cannot express a workspace
8
+ * call (cart, checkout, account, products…). The server enforces scope on
9
+ * every request regardless (a dash token gets a uniform 404 on the workspace
10
+ * surface); this narrows the *authoring* surface so the mistake never compiles.
11
+ *
12
+ * `ping` and `geo` are deliberately included: both are scope-agnostic on the
13
+ * door (the credential self-check must answer for either scope, and geo lets
14
+ * a dash site localise pricing).
15
+ */
16
+ export type DashChannelClient = Pick<ReturnType<typeof createChannelClient>, "ping" | "geo" | "dash" | "assetUrl"> & {
17
+ /** Request-scoped clone carrying signed visitor metadata (see ChannelVisitor). */
18
+ withVisitor(visitor: ChannelVisitor): DashChannelClient;
19
+ };
20
+ declare function narrow(client: ReturnType<typeof createChannelClient>): DashChannelClient;
21
+ /** Dash-scoped client over plain fetch (no framework cache semantics). */
22
+ export declare function createDashChannelClient(options: CreateChannelClientOptions): DashChannelClient;
23
+ export { narrow as narrowToDash };
package/dist/dash.js ADDED
@@ -0,0 +1,16 @@
1
+ import "server-only";
2
+ import { createChannelClient } from "./index.js";
3
+ function narrow(client) {
4
+ return {
5
+ ping: client.ping,
6
+ geo: client.geo,
7
+ dash: client.dash,
8
+ assetUrl: client.assetUrl,
9
+ withVisitor: (visitor) => narrow(client.withVisitor(visitor)),
10
+ };
11
+ }
12
+ /** Dash-scoped client over plain fetch (no framework cache semantics). */
13
+ export function createDashChannelClient(options) {
14
+ return narrow(createChannelClient(options));
15
+ }
16
+ export { narrow as narrowToDash };
@@ -0,0 +1,12 @@
1
+ /**
2
+ * ChannelConfigurationError is thrown for a misconfigured client — missing or
3
+ * malformed token, invalid retry/timeout/cache options, missing fetch, missing
4
+ * webhook secret — as opposed to ChannelAPIError, which describes what the
5
+ * network or the API did. Callers can branch on this without string-matching
6
+ * messages; both starters previously invented a local equivalent.
7
+ */
8
+ export declare class ChannelConfigurationError extends Error {
9
+ constructor(message: string);
10
+ }
11
+ /** Works across duplicate package instances and transformed test bundles. */
12
+ export declare function isChannelConfigurationError(error: unknown): error is ChannelConfigurationError;
package/dist/errors.js ADDED
@@ -0,0 +1,19 @@
1
+ /**
2
+ * ChannelConfigurationError is thrown for a misconfigured client — missing or
3
+ * malformed token, invalid retry/timeout/cache options, missing fetch, missing
4
+ * webhook secret — as opposed to ChannelAPIError, which describes what the
5
+ * network or the API did. Callers can branch on this without string-matching
6
+ * messages; both starters previously invented a local equivalent.
7
+ */
8
+ export class ChannelConfigurationError extends Error {
9
+ constructor(message) {
10
+ super(message);
11
+ this.name = "ChannelConfigurationError";
12
+ }
13
+ }
14
+ /** Works across duplicate package instances and transformed test bundles. */
15
+ export function isChannelConfigurationError(error) {
16
+ return (error instanceof ChannelConfigurationError ||
17
+ (typeof error === "object" && error !== null &&
18
+ error.name === "ChannelConfigurationError"));
19
+ }
package/dist/index.d.ts CHANGED
@@ -1,6 +1,8 @@
1
+ import "server-only";
1
2
  export * from "./webhooks.js";
3
+ export * from "./errors.js";
2
4
  export type * from "./types.js";
3
- import type { CatalogBrand, CatalogCategory, CatalogCollection, CatalogProductsResponse, BlogPostResponse, DiningMenu, DashDirectoryEntry, DashDirectoryProfileResponse, DashDirectoryRegion, DashInitResponse, DashLead, DashPlansResponse, DashProfileResponse, GivingEntry, GivingIntentListResponse, AddCartItemInput, CartResponse, CheckoutAddressesInput, CheckoutCustomerInput, CheckoutFulfillmentInput, CheckoutOptions, CheckoutPayInput, CheckoutPayResponse, CheckoutStatusResponse, ChannelPing, CustomerResponse, CustomerSession, CustomerSignupResponse, LeadResponse, LightInitResponse, ListResponse, Order, OrderSummary, MergeCartInput, SendCodeResponse, Product, ProductAsset, PrintIntakeInput, PrintJob, PrintOptionsSelection, PrintQuoteResponse, PrintSettingsResponse, PublicPage, PublicPageSummary, PublicSubmitReviewInput, PublicWorkspaceInit, MenuResponse, Review, ReviewSummaryResponse, SavedAddress, SavedAddressDefaultKind, SavedAddressInput, SavedAddressResponse, SavedAddressUpdateInput, SavedPaymentMethod, SiteDocument, StartGivingInput, StartGivingResponse, PaymentMethodConfirmInput, PaymentMethodMutationResponse, PaymentMethodSetupInput, PaymentMethodSetupResult, SubscriptionAgreementResponse, SubscriptionInvoiceListResponse, SubscriptionInvoiceResponse, SubscriptionListResponse, SubscriptionSourceResponse, ThemeResponse, UpdateCartItemInput } from "./types.js";
5
+ import type { CatalogBrand, CatalogCategory, CatalogCollection, CatalogProductsResponse, BlogPostResponse, DiningMenu, DashDirectoryEntry, DashDirectoryProfileResponse, DashDirectoryRegion, DashInitResponse, DashLead, DashPlansResponse, DashProfileResponse, GivingEntry, GivingIntentListResponse, AddCartItemInput, CartResponse, CheckoutAddressesInput, CheckoutCustomerInput, CheckoutFulfillmentInput, CheckoutOptions, CheckoutPayInput, CheckoutPayResponse, CheckoutStatusResponse, ChannelPing, CustomerResponse, CustomerAuthSession, CustomerSecurityActivityPage, ChannelGeo, CustomerSession, CustomerSignupResponse, LeadResponse, LightInitResponse, ListResponse, Order, OrderSummary, MergeCartInput, SendCodeResponse, Product, ProductAsset, PrintIntakeInput, PrintJob, PrintOptionsSelection, PrintQuoteResponse, PrintSettingsResponse, PublicPage, PublicPageSummary, PublicSubmitReviewInput, PublicWorkspaceInit, MenuResponse, Review, ReviewSummaryResponse, SavedAddress, SavedAddressDefaultKind, SavedAddressInput, SavedAddressResponse, SavedAddressUpdateInput, SavedPaymentMethod, SiteDocument, StartGivingInput, StartGivingResponse, PaymentMethodConfirmInput, PaymentMethodMutationResponse, PaymentMethodSetupInput, PaymentMethodSetupResult, SubscriptionAgreementResponse, SubscriptionInvoiceListResponse, SubscriptionInvoiceResponse, SubscriptionListResponse, SubscriptionSourceResponse, ThemeResponse, UpdateCartItemInput } from "./types.js";
4
6
  export declare const DEFAULT_CHANNEL_API_URL = "https://api.saasdash.app";
5
7
  export interface ChannelRetryPolicy {
6
8
  attempts?: number;
@@ -11,14 +13,33 @@ export interface CreateChannelClientOptions {
11
13
  baseUrl?: string;
12
14
  token: string;
13
15
  fetch?: typeof globalThis.fetch;
16
+ /**
17
+ * Per-ATTEMPT timeout (default 10 000 ms), not a whole-call budget: with
18
+ * `retry.attempts` retries the worst-case wall clock is roughly
19
+ * `(attempts + 1) × timeoutMs` plus backoff. Pass `signal` to bound the
20
+ * whole call to the caller's own deadline.
21
+ */
14
22
  timeoutMs?: number;
23
+ /**
24
+ * GET-only retries on 429/502/503/504 and network errors (mutations are
25
+ * retried only by the caller, under an Idempotency-Key). Backoff honours
26
+ * Retry-After when present; otherwise it grows exponentially from 250 ms
27
+ * with jitter, capped at `maxDelayMs` (default 2 000).
28
+ */
15
29
  retry?: ChannelRetryPolicy | false;
16
30
  observe?: ChannelRequestObserver;
17
31
  /** Optional request-scope cancellation signal, combined with the timeout. */
18
32
  signal?: AbortSignal;
33
+ /** Verified visitor metadata from the hosting edge. Never accept these values from an untrusted caller. */
34
+ visitor?: ChannelVisitor;
35
+ }
36
+ export interface ChannelVisitor {
37
+ ip?: string;
38
+ country?: string;
39
+ userAgent?: string;
19
40
  }
20
41
  export type ChannelRequestOutcome = "success" | "api_error" | "network_error" | "timeout" | "invalid_response" | "cancelled";
21
- export type ChannelOperation = "channel.ping" | "channel.site.resolve" | "channel.init.get" | "channel.init.light" | "content.pages.public.list.channel" | "content.pages.public.get.channel" | "shop.public.products.list.channel" | "shop.public.products.get.channel" | "shop.public.products.media.channel" | "reviews.public.list.channel" | "reviews.public.summary.channel" | "reviews.public.submit.channel" | "channel.theme.get" | "channel.menus.get" | "channel.blog.get" | "channel.blog.list" | "channel.giving.entries.list" | "channel.giving.entries.get" | "channel.giving.start" | "channel.print.settings" | "channel.print.quote" | "channel.print.intake" | "dining.public.board_menu.channel" | "channel.auth.check" | "channel.auth.signup" | "channel.auth.send_code" | "channel.auth.verify_code" | "channel.auth.refresh" | "channel.auth.me" | "channel.auth.me.update" | "channel.auth.logout" | "channel.account.addresses.list" | "channel.account.addresses.create" | "channel.account.addresses.get" | "channel.account.addresses.update" | "channel.account.addresses.delete" | "channel.account.addresses.set_default" | "channel.account.giving.list" | "channel.account.orders.list" | "channel.account.orders.summary" | "channel.account.orders.get" | "channel.account.payment_methods.list" | "channel.account.payment_methods.setup" | "channel.account.payment_methods.confirm" | "channel.account.payment_methods.default" | "channel.account.payment_methods.delete" | "channel.account.subscriptions.list" | "channel.account.subscriptions.get" | "channel.account.subscriptions.source" | "channel.account.subscriptions.cancel" | "channel.account.subscriptions.pause" | "channel.account.subscriptions.resume" | "channel.account.subscriptions.invoices.list" | "channel.account.subscriptions.invoices.get" | "channel.account.subscriptions.invoices.pay_now" | "channel.catalog.brands.list" | "channel.catalog.categories.list" | "channel.catalog.categories.products" | "channel.catalog.collections.list" | "channel.catalog.collections.products" | "channel.cart.get" | "channel.cart.items.add" | "channel.cart.items.update" | "channel.cart.items.remove" | "channel.cart.clear" | "channel.cart.merge" | "channel.checkout.options" | "channel.checkout.status" | "channel.checkout.customer.set" | "channel.checkout.addresses.set" | "channel.checkout.fulfillment.set" | "channel.checkout.pay" | "channel.dash.profile" | "channel.dash.init" | "channel.dash.plans" | "channel.dash.directory.regions" | "channel.dash.directory.browse" | "channel.dash.directory.get" | "channel.dash.leads.capture" | "growth.public_workspace.leads.capture.channel";
42
+ export type ChannelOperation = "channel.ping" | "channel.geo.detect" | "channel.site.resolve" | "channel.init.get" | "channel.init.light" | "content.pages.public.list.channel" | "content.pages.public.get.channel" | "shop.public.products.list.channel" | "shop.public.products.get.channel" | "shop.public.products.media.channel" | "reviews.public.list.channel" | "reviews.public.summary.channel" | "reviews.public.submit.channel" | "channel.theme.get" | "channel.menus.get" | "channel.blog.get" | "channel.blog.list" | "channel.giving.entries.list" | "channel.giving.entries.get" | "channel.giving.start" | "channel.print.settings" | "channel.print.quote" | "channel.print.intake" | "dining.public.board_menu.channel" | "channel.auth.check" | "channel.auth.signup" | "channel.auth.send_code" | "channel.auth.verify_code" | "channel.auth.refresh" | "channel.auth.me" | "channel.auth.me.update" | "channel.auth.logout" | "channel.auth.sessions.list" | "channel.auth.sessions.revoke" | "channel.auth.sessions.revoke_others" | "channel.auth.sessions.revoke_all" | "channel.auth.security_activity.list" | "channel.account.addresses.list" | "channel.account.addresses.create" | "channel.account.addresses.get" | "channel.account.addresses.update" | "channel.account.addresses.delete" | "channel.account.addresses.set_default" | "channel.account.giving.list" | "channel.account.orders.list" | "channel.account.orders.summary" | "channel.account.orders.get" | "channel.account.payment_methods.list" | "channel.account.payment_methods.setup" | "channel.account.payment_methods.confirm" | "channel.account.payment_methods.default" | "channel.account.payment_methods.delete" | "channel.account.subscriptions.list" | "channel.account.subscriptions.get" | "channel.account.subscriptions.source" | "channel.account.subscriptions.cancel" | "channel.account.subscriptions.pause" | "channel.account.subscriptions.resume" | "channel.account.subscriptions.invoices.list" | "channel.account.subscriptions.invoices.get" | "channel.account.subscriptions.invoices.pay_now" | "channel.catalog.brands.list" | "channel.catalog.categories.list" | "channel.catalog.categories.products" | "channel.catalog.collections.list" | "channel.catalog.collections.products" | "channel.cart.get" | "channel.cart.items.add" | "channel.cart.items.update" | "channel.cart.items.remove" | "channel.cart.clear" | "channel.cart.merge" | "channel.checkout.options" | "channel.checkout.status" | "channel.checkout.customer.set" | "channel.checkout.addresses.set" | "channel.checkout.fulfillment.set" | "channel.checkout.pay" | "channel.dash.profile" | "channel.dash.init" | "channel.dash.plans" | "channel.dash.directory.regions" | "channel.dash.directory.browse" | "channel.dash.directory.get" | "channel.dash.leads.capture" | "growth.public_workspace.leads.capture.channel";
22
43
  export interface ChannelRequestObservation {
23
44
  operation: ChannelOperation;
24
45
  method: string;
@@ -72,8 +93,7 @@ export interface ChannelSubscriptionListParams extends ChannelListParams {
72
93
  export interface ChannelSubscriptionCancelParams {
73
94
  immediate?: boolean;
74
95
  }
75
- export interface ChannelInvoiceListParams {
76
- limit?: number;
96
+ export interface ChannelInvoiceListParams extends ChannelListParams {
77
97
  }
78
98
  export declare class ChannelAPIError extends Error {
79
99
  readonly status: number;
@@ -93,7 +113,12 @@ export declare function createChannelClient(options: CreateChannelClientOptions)
93
113
  * the token is bad, revoked, or the channel is disabled (the door will not
94
114
  * say which). A 503 means C1M is unavailable — NOT that your token is wrong.
95
115
  */
96
- readonly ping: () => Promise<ChannelPing>;
116
+ readonly ping: (challenge?: string) => Promise<ChannelPing>;
117
+ /** Return a request-scoped client that signs trusted edge visitor metadata. */
118
+ readonly withVisitor: (visitor: ChannelVisitor) => /*elided*/ any;
119
+ readonly geo: {
120
+ readonly detect: () => Promise<ChannelGeo>;
121
+ };
97
122
  /** Tenant-level data exposed only to a dash-scoped channel token. */
98
123
  readonly dash: {
99
124
  readonly profile: () => Promise<DashProfileResponse>;
@@ -188,7 +213,7 @@ export declare function createChannelClient(options: CreateChannelClientOptions)
188
213
  };
189
214
  readonly print: {
190
215
  readonly settings: () => Promise<PrintSettingsResponse>;
191
- readonly quote: (input: PrintOptionsSelection) => Promise<PrintQuoteResponse>;
216
+ readonly quote: (input: PrintOptionsSelection, mutation?: ChannelMutationOptions) => Promise<PrintQuoteResponse>;
192
217
  readonly intake: (input: PrintIntakeInput, mutation?: ChannelMutationOptions) => Promise<{
193
218
  job: PrintJob;
194
219
  }>;
@@ -232,6 +257,24 @@ export declare function createChannelClient(options: CreateChannelClientOptions)
232
257
  readonly logout: () => Promise<{
233
258
  status?: string;
234
259
  }>;
260
+ readonly sessions: {
261
+ readonly list: () => Promise<{
262
+ items: CustomerAuthSession[];
263
+ }>;
264
+ readonly revoke: (sessionId: string) => Promise<{
265
+ status?: string;
266
+ }>;
267
+ readonly revokeOthers: () => Promise<{
268
+ revoked: number;
269
+ }>;
270
+ readonly revokeAll: () => Promise<{
271
+ revoked: number;
272
+ }>;
273
+ };
274
+ readonly securityActivity: (params?: {
275
+ category?: string;
276
+ cursor?: string;
277
+ }) => Promise<CustomerSecurityActivityPage>;
235
278
  readonly orders: {
236
279
  readonly list: (params?: ChannelListParams) => Promise<ListResponse<Order>>;
237
280
  readonly summary: () => Promise<{
package/dist/index.js CHANGED
@@ -1,4 +1,7 @@
1
+ import "server-only";
1
2
  export * from "./webhooks.js";
3
+ export * from "./errors.js";
4
+ import { ChannelConfigurationError } from "./errors.js";
2
5
  const CHANNEL_TOKEN_PREFIX = "sk_chan_";
3
6
  export const DEFAULT_CHANNEL_API_URL = "https://api.saasdash.app";
4
7
  const RETRYABLE_STATUSES = new Set([429, 502, 503, 504]);
@@ -26,12 +29,12 @@ export function isChannelAPIError(error) {
26
29
  function required(value, label) {
27
30
  const normalized = value.trim();
28
31
  if (!normalized)
29
- throw new Error(`${label} is required`);
32
+ throw new ChannelConfigurationError(`${label} is required`);
30
33
  return normalized;
31
34
  }
32
35
  function positiveNumber(value, label) {
33
36
  if (!Number.isFinite(value) || value <= 0)
34
- throw new Error(`${label} must be a positive finite number`);
37
+ throw new ChannelConfigurationError(`${label} must be a positive finite number`);
35
38
  return value;
36
39
  }
37
40
  function encodePath(value) {
@@ -46,15 +49,23 @@ function appendQuery(path, values) {
46
49
  const encoded = query.toString();
47
50
  return encoded ? `${path}?${encoded}` : path;
48
51
  }
49
- function retryDelay(response, maxDelayMs) {
52
+ // backoffDelay is the no-Retry-After default: exponential from 250 ms with
53
+ // full jitter, capped. A flat 250 ms with no jitter (the previous behaviour)
54
+ // turns `attempts: 5` on a 429 into five requests a quarter-second apart into
55
+ // the very limiter that just refused you — a thundering herd in miniature.
56
+ function backoffDelay(attempt, maxDelayMs) {
57
+ const base = Math.min(250 * 2 ** Math.max(attempt, 0), maxDelayMs);
58
+ return Math.floor(Math.random() * base);
59
+ }
60
+ function retryDelay(response, attempt, maxDelayMs) {
50
61
  const value = response.headers.get("Retry-After");
51
62
  if (!value)
52
- return Math.min(250, maxDelayMs);
63
+ return backoffDelay(attempt, maxDelayMs);
53
64
  const seconds = Number(value);
54
65
  if (Number.isFinite(seconds))
55
66
  return Math.min(Math.max(seconds * 1_000, 0), maxDelayMs);
56
67
  const date = Date.parse(value);
57
- return Number.isNaN(date) ? Math.min(250, maxDelayMs) : Math.min(Math.max(date - Date.now(), 0), maxDelayMs);
68
+ return Number.isNaN(date) ? backoffDelay(attempt, maxDelayMs) : Math.min(Math.max(date - Date.now(), 0), maxDelayMs);
58
69
  }
59
70
  function wait(ms) {
60
71
  return ms <= 0 ? Promise.resolve() : new Promise((resolve) => setTimeout(resolve, ms));
@@ -70,20 +81,43 @@ function combineSignals(...signals) {
70
81
  function isFormDataBody(body) {
71
82
  return typeof FormData !== "undefined" && body instanceof FormData;
72
83
  }
84
+ async function visitorHeaders(token, method, path, visitor) {
85
+ if (!visitor)
86
+ return undefined;
87
+ const ip = visitor.ip?.trim() ?? "";
88
+ const country = visitor.country?.trim().toUpperCase() ?? "";
89
+ const userAgent = visitor.userAgent?.trim() ?? "";
90
+ if (!ip && !country && !userAgent)
91
+ return undefined;
92
+ const timestamp = Math.floor(Date.now() / 1_000).toString();
93
+ const encoder = new TextEncoder();
94
+ const uaHash = await crypto.subtle.digest("SHA-256", encoder.encode(userAgent));
95
+ const hex = (bytes) => Array.from(new Uint8Array(bytes), (value) => value.toString(16).padStart(2, "0")).join("");
96
+ const canonical = ["v1", timestamp, method, `/api/v1/channel${path}`, ip, country, hex(uaHash)].join("\n");
97
+ const key = await crypto.subtle.importKey("raw", encoder.encode(token), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
98
+ const signature = hex(await crypto.subtle.sign("HMAC", key, encoder.encode(canonical)));
99
+ return {
100
+ "X-C1M-Visitor-IP": ip,
101
+ "X-C1M-Visitor-Country": country,
102
+ "X-C1M-Visitor-User-Agent": userAgent,
103
+ "X-C1M-Visitor-Timestamp": timestamp,
104
+ "X-C1M-Visitor-Signature": signature,
105
+ };
106
+ }
73
107
  export function createChannelClient(options) {
74
108
  const baseUrl = (options.baseUrl === undefined
75
109
  ? DEFAULT_CHANNEL_API_URL
76
110
  : required(options.baseUrl, "baseUrl")).replace(/\/+$/, "");
77
111
  const token = required(options.token, "token");
78
112
  if (!token.startsWith(CHANNEL_TOKEN_PREFIX))
79
- throw new Error("token must start with sk_chan_");
113
+ throw new ChannelConfigurationError("token must start with sk_chan_");
80
114
  const fetcher = options.fetch ?? globalThis.fetch;
81
115
  if (!fetcher)
82
- throw new Error("fetch implementation is required");
116
+ throw new ChannelConfigurationError("fetch implementation is required");
83
117
  const timeoutMs = positiveNumber(options.timeoutMs ?? 10_000, "timeoutMs");
84
118
  const configuredRetryAttempts = options.retry === false ? 0 : options.retry?.attempts ?? 1;
85
119
  if (!Number.isSafeInteger(configuredRetryAttempts) || configuredRetryAttempts < 0) {
86
- throw new Error("retry.attempts must be a non-negative safe integer");
120
+ throw new ChannelConfigurationError("retry.attempts must be a non-negative safe integer");
87
121
  }
88
122
  const retryAttempts = configuredRetryAttempts;
89
123
  const maxRetryDelayMs = positiveNumber(options.retry === false ? 2_000 : options.retry?.maxDelayMs ?? 2_000, "retry.maxDelayMs");
@@ -100,6 +134,11 @@ export function createChannelClient(options) {
100
134
  // separate credential — Authorization is already spoken for, so the
101
135
  // customer's session rides in its own header.
102
136
  headers.set("Authorization", `Bearer ${token}`);
137
+ const signedVisitor = await visitorHeaders(token, method, path, options.visitor);
138
+ if (signedVisitor) {
139
+ for (const [key, value] of Object.entries(signedVisitor))
140
+ headers.set(key, value);
141
+ }
103
142
  if (session)
104
143
  headers.set("X-End-User-Token", session);
105
144
  if (init.body !== undefined && !isFormDataBody(init.body) && !headers.has("Content-Type")) {
@@ -134,7 +173,7 @@ export function createChannelClient(options) {
134
173
  }
135
174
  outcome = "network_error";
136
175
  if (method === "GET" && attempt < retryAttempts) {
137
- await wait(Math.min(250, maxRetryDelayMs));
176
+ await wait(backoffDelay(attempt, maxRetryDelayMs));
138
177
  continue;
139
178
  }
140
179
  throw new ChannelAPIError("Channel API request failed", 0, "channel_network_error", "");
@@ -144,7 +183,7 @@ export function createChannelClient(options) {
144
183
  }
145
184
  if (method !== "GET" || !RETRYABLE_STATUSES.has(response.status) || attempt === retryAttempts)
146
185
  break;
147
- await wait(retryDelay(response, maxRetryDelayMs));
186
+ await wait(retryDelay(response, attempt, maxRetryDelayMs));
148
187
  }
149
188
  if (!response)
150
189
  throw new ChannelAPIError("Channel API request failed", 0, "channel_network_error", "");
@@ -195,7 +234,12 @@ export function createChannelClient(options) {
195
234
  * the token is bad, revoked, or the channel is disabled (the door will not
196
235
  * say which). A 503 means C1M is unavailable — NOT that your token is wrong.
197
236
  */
198
- ping: () => request("channel.ping", "/ping"),
237
+ ping: (challenge) => request("channel.ping", appendQuery("/ping", { challenge })),
238
+ /** Return a request-scoped client that signs trusted edge visitor metadata. */
239
+ withVisitor: (visitor) => createChannelClient({ ...options, visitor }),
240
+ geo: {
241
+ detect: () => request("channel.geo.detect", "/geo/detect"),
242
+ },
199
243
  /** Tenant-level data exposed only to a dash-scoped channel token. */
200
244
  dash: {
201
245
  profile: () => request("channel.dash.profile", "/dash/profile"),
@@ -314,8 +358,8 @@ export function createChannelClient(options) {
314
358
  },
315
359
  print: {
316
360
  settings: () => request("channel.print.settings", "/print/settings"),
317
- quote: (input) => request("channel.print.quote", "/print/quote", {
318
- method: "POST", body: JSON.stringify(input),
361
+ quote: (input, mutation) => request("channel.print.quote", "/print/quote", {
362
+ method: "POST", headers: mutationHeaders(mutation), body: JSON.stringify(input),
319
363
  }),
320
364
  intake: (input, mutation) => {
321
365
  const form = new FormData();
@@ -362,6 +406,13 @@ export function createChannelClient(options) {
362
406
  me: () => request("channel.auth.me", "/auth/me", {}, customerSession),
363
407
  updateProfile: (input) => request("channel.auth.me.update", "/auth/me", { method: "PUT", body: JSON.stringify(input) }, customerSession),
364
408
  logout: () => request("channel.auth.logout", "/auth/logout", { method: "POST" }, customerSession),
409
+ sessions: {
410
+ list: () => request("channel.auth.sessions.list", "/auth/me/sessions", {}, customerSession),
411
+ revoke: (sessionId) => request("channel.auth.sessions.revoke", `/auth/me/sessions/${encodePath(sessionId)}`, { method: "DELETE" }, customerSession),
412
+ revokeOthers: () => request("channel.auth.sessions.revoke_others", "/auth/me/sessions/revoke-others", { method: "POST" }, customerSession),
413
+ revokeAll: () => request("channel.auth.sessions.revoke_all", "/auth/me/sessions/revoke-all", { method: "POST" }, customerSession),
414
+ },
415
+ securityActivity: (params = {}) => request("channel.auth.security_activity.list", appendQuery("/auth/me/security-activity", params), {}, customerSession),
365
416
  orders: {
366
417
  list: (params = {}) => request("channel.account.orders.list", appendQuery("/account/orders", params), {}, customerSession),
367
418
  summary: () => request("channel.account.orders.summary", "/account/orders/summary", {}, customerSession),
@@ -1,5 +1,5 @@
1
1
  import "server-only";
2
- import { ChannelWebhookVerificationError, isChannelWebhookEventType, parseChannelWebhookEvent, } from "./webhooks.js";
2
+ import { isChannelWebhookVerificationError, isChannelWebhookEventType, parseChannelWebhookEvent, } from "./webhooks.js";
3
3
  /**
4
4
  * Webhook route factory: the whole app/api/webhooks/c1m/route.ts in one call.
5
5
  *
@@ -33,13 +33,8 @@ export function safePublishedPath(path) {
33
33
  }
34
34
  return normalized;
35
35
  }
36
- /** Structural, not instanceof — see the session kit for why. */
37
- function isVerificationError(error) {
38
- if (error instanceof ChannelWebhookVerificationError)
39
- return true;
40
- return (typeof error === "object" && error !== null &&
41
- error.name === "ChannelWebhookVerificationError" &&
42
- typeof error.code === "string");
36
+ function errorMessage(error) {
37
+ return error instanceof Error ? error.message : String(error);
43
38
  }
44
39
  function defaultBehavior(event, invalidate) {
45
40
  if (event.type === "page.published") {
@@ -70,13 +65,15 @@ export function createChannelWebhookRoute(options) {
70
65
  event = await parseChannelWebhookEvent(request, { secret: resolveSecret() });
71
66
  }
72
67
  catch (error) {
73
- if (isVerificationError(error)) {
68
+ if (isChannelWebhookVerificationError(error)) {
74
69
  // An unverifiable request is noise or an attack; log the code, say
75
70
  // nothing useful back.
76
71
  logger.warn("channel_webhook_rejected", { code: error.code });
77
72
  return Response.json({ code: "invalid_channel_webhook" }, { status: 401 });
78
73
  }
79
- logger.error("channel_webhook_failed", { error });
74
+ // Log a message, never the raw error object: a thrown value could carry
75
+ // configuration (a secret in a message string) into the log verbatim.
76
+ logger.error("channel_webhook_failed", { message: errorMessage(error) });
80
77
  return Response.json({ code: "channel_webhook_failed" }, { status: 500 });
81
78
  }
82
79
  try {
@@ -105,7 +102,7 @@ export function createChannelWebhookRoute(options) {
105
102
  // A 500 makes the server retry on its ladder — which is what you want
106
103
  // when the failure is transient, and visible in delivery history when
107
104
  // it is not.
108
- logger.error("channel_webhook_failed", { eventId: event.id, eventType: event.type, error });
105
+ logger.error("channel_webhook_failed", { eventId: event.id, eventType: event.type, message: errorMessage(error) });
109
106
  return Response.json({ code: "channel_webhook_failed" }, { status: 500 });
110
107
  }
111
108
  };
package/dist/next.d.ts CHANGED
@@ -1,13 +1,27 @@
1
1
  import "server-only";
2
2
  import { type CreateChannelClientOptions } from "./index.js";
3
+ /**
4
+ * Cache policy for anonymous GETs. `tags` are applied to every cached read;
5
+ * `tagsFor` (or the default classifier) adds per-request tags so a webhook
6
+ * can bust one family of reads without the whole site: catalog reads carry
7
+ * `channel:catalog` (busted by `product.*` events), everything else carries
8
+ * `channel:site` (busted by `page.published`). Without this the kit's default
9
+ * `product.*` handler invalidates a tag no fetch carries.
10
+ */
3
11
  export type NextChannelCachePolicy = "no-store" | {
4
12
  revalidate: number;
5
13
  tags?: string[];
14
+ tagsFor?: (pathname: string) => string[];
6
15
  };
7
16
  export interface CreateNextChannelClientOptions extends Omit<CreateChannelClientOptions, "fetch"> {
8
17
  fetch?: typeof globalThis.fetch;
9
18
  cache?: NextChannelCachePolicy;
10
19
  }
20
+ /**
21
+ * Default classifier: catalog reads → `channel:catalog`, all other anonymous
22
+ * reads → `channel:site`. Exported so a site can compose it with its own tags.
23
+ */
24
+ export declare function defaultChannelCacheTags(pathname: string): string[];
11
25
  /**
12
26
  * Build the Channel API client with Next.js Data Cache semantics.
13
27
  *
@@ -15,7 +29,11 @@ export interface CreateNextChannelClientOptions extends Omit<CreateChannelClient
15
29
  * mutations are forced to `no-store` by both this adapter and the core client.
16
30
  */
17
31
  export declare function createNextChannelClient(options: CreateNextChannelClientOptions): {
18
- readonly ping: () => Promise<import("./types.js").ChannelPing>;
32
+ readonly ping: (challenge?: string) => Promise<import("./types.js").ChannelPing>;
33
+ readonly withVisitor: (visitor: import("./index.js").ChannelVisitor) => /*elided*/ any;
34
+ readonly geo: {
35
+ readonly detect: () => Promise<import("./types.js").ChannelGeo>;
36
+ };
19
37
  readonly dash: {
20
38
  readonly profile: () => Promise<import("./types.js").DashProfileResponse>;
21
39
  readonly init: () => Promise<import("./types.js").DashInitResponse>;
@@ -109,7 +127,7 @@ export declare function createNextChannelClient(options: CreateNextChannelClient
109
127
  };
110
128
  readonly print: {
111
129
  readonly settings: () => Promise<import("./types.js").PrintSettingsResponse>;
112
- readonly quote: (input: import("./types.js").PrintOptionsSelection) => Promise<import("./types.js").PrintQuoteResponse>;
130
+ readonly quote: (input: import("./types.js").PrintOptionsSelection, mutation?: import("./index.js").ChannelMutationOptions) => Promise<import("./types.js").PrintQuoteResponse>;
113
131
  readonly intake: (input: import("./types.js").PrintIntakeInput, mutation?: import("./index.js").ChannelMutationOptions) => Promise<{
114
132
  job: import("./types.js").PrintJob;
115
133
  }>;
@@ -142,6 +160,24 @@ export declare function createNextChannelClient(options: CreateNextChannelClient
142
160
  readonly logout: () => Promise<{
143
161
  status?: string;
144
162
  }>;
163
+ readonly sessions: {
164
+ readonly list: () => Promise<{
165
+ items: import("./types.js").CustomerAuthSession[];
166
+ }>;
167
+ readonly revoke: (sessionId: string) => Promise<{
168
+ status?: string;
169
+ }>;
170
+ readonly revokeOthers: () => Promise<{
171
+ revoked: number;
172
+ }>;
173
+ readonly revokeAll: () => Promise<{
174
+ revoked: number;
175
+ }>;
176
+ };
177
+ readonly securityActivity: (params?: {
178
+ category?: string;
179
+ cursor?: string;
180
+ }) => Promise<import("./types.js").CustomerSecurityActivityPage>;
145
181
  readonly orders: {
146
182
  readonly list: (params?: import("./index.js").ChannelListParams) => Promise<import("./types.js").ListResponse<import("./types.js").Order>>;
147
183
  readonly summary: () => Promise<{
package/dist/next.js CHANGED
@@ -1,10 +1,30 @@
1
1
  import "server-only";
2
- import { createChannelClient } from "./index.js";
2
+ import { ChannelConfigurationError, createChannelClient } from "./index.js";
3
+ /** Cache tags — mirrored from next-webhooks so the two files agree by name. */
4
+ const SITE_TAG = "channel:site";
5
+ const CATALOG_TAG = "channel:catalog";
6
+ const CATALOG_PATH = /^\/api\/v1\/channel\/(products|categories|collections|brands)(\/|$|\?)/;
7
+ /**
8
+ * Default classifier: catalog reads → `channel:catalog`, all other anonymous
9
+ * reads → `channel:site`. Exported so a site can compose it with its own tags.
10
+ */
11
+ export function defaultChannelCacheTags(pathname) {
12
+ return CATALOG_PATH.test(pathname) ? [CATALOG_TAG] : [SITE_TAG];
13
+ }
14
+ function pathnameOf(input) {
15
+ try {
16
+ const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
17
+ return new URL(url, "http://placeholder.invalid").pathname;
18
+ }
19
+ catch {
20
+ return "";
21
+ }
22
+ }
3
23
  function validateCachePolicy(policy) {
4
24
  if (policy === "no-store")
5
25
  return;
6
26
  if (!Number.isFinite(policy.revalidate) || policy.revalidate < 0) {
7
- throw new Error("cache.revalidate must be a non-negative finite number");
27
+ throw new ChannelConfigurationError("cache.revalidate must be a non-negative finite number");
8
28
  }
9
29
  }
10
30
  /**
@@ -18,16 +38,18 @@ export function createNextChannelClient(options) {
18
38
  validateCachePolicy(cache);
19
39
  const fetcher = suppliedFetch ?? globalThis.fetch;
20
40
  if (!fetcher)
21
- throw new Error("fetch implementation is required");
41
+ throw new ChannelConfigurationError("fetch implementation is required");
22
42
  const nextFetch = (input, init = {}) => {
23
43
  const request = { ...init };
24
44
  const method = (request.method ?? "GET").toUpperCase();
25
45
  const customerScoped = new Headers(request.headers).has("X-End-User-Token");
26
46
  if (method === "GET" && !customerScoped && cache !== "no-store") {
27
47
  delete request.cache;
48
+ const classify = cache.tagsFor ?? defaultChannelCacheTags;
49
+ const tags = Array.from(new Set([...(cache.tags ?? []), ...classify(pathnameOf(input))]));
28
50
  request.next = {
29
51
  revalidate: cache.revalidate,
30
- ...(cache.tags ? { tags: cache.tags } : {}),
52
+ ...(tags.length ? { tags } : {}),
31
53
  };
32
54
  }
33
55
  else {
@@ -0,0 +1,46 @@
1
+ /** Framework-neutral canonical site-document traversal. UI packages provide
2
+ * the block registry; this package owns document validation, responsive CSS
3
+ * safety and deterministic tree traversal shared by hosted and headless sites. */
4
+ export interface SiteBuilderNode {
5
+ id: string;
6
+ kind: string;
7
+ props?: Record<string, unknown>;
8
+ style?: Record<string, unknown> & {
9
+ tablet?: Record<string, unknown>;
10
+ mobile?: Record<string, unknown>;
11
+ hover?: Record<string, unknown>;
12
+ focus?: Record<string, unknown>;
13
+ };
14
+ children?: SiteBuilderNode[];
15
+ }
16
+ export interface SiteBuilderDocument {
17
+ zones: Array<{
18
+ id: string;
19
+ kind?: string;
20
+ nodes: SiteBuilderNode[];
21
+ }>;
22
+ }
23
+ export interface RenderBlockInput<T> {
24
+ node: SiteBuilderNode;
25
+ children: T[];
26
+ index: number;
27
+ siblingCount: number;
28
+ data?: unknown;
29
+ }
30
+ export type SiteBlockRegistry<T> = Record<string, (input: RenderBlockInput<T>) => T>;
31
+ export interface RenderSiteOptions<T> {
32
+ registry: SiteBlockRegistry<T>;
33
+ dataByNodeId?: Record<string, unknown>;
34
+ /** Exact node replacements for application-owned slots such as cart or
35
+ * account panels. Replacements still obey the node's hidden flag. */
36
+ nodeOverrides?: Record<string, T>;
37
+ onUnknownBlock?: (node: SiteBuilderNode) => void;
38
+ zone?: string;
39
+ }
40
+ export declare function isSiteBuilderDocument(value: unknown): value is SiteBuilderDocument;
41
+ export declare function renderSiteDocument<T>(document: unknown, options: RenderSiteOptions<T>): T[];
42
+ export declare function safeStyleRule(properties: Record<string, unknown>): string;
43
+ export declare function collectResponsiveCSS(document: unknown, widths?: {
44
+ mobile?: number;
45
+ tablet?: number;
46
+ }): string;
@@ -0,0 +1,101 @@
1
+ /** Framework-neutral canonical site-document traversal. UI packages provide
2
+ * the block registry; this package owns document validation, responsive CSS
3
+ * safety and deterministic tree traversal shared by hosted and headless sites. */
4
+ export function isSiteBuilderDocument(value) {
5
+ if (typeof value !== "object" || value === null)
6
+ return false;
7
+ const zones = value.zones;
8
+ return Array.isArray(zones) && zones.every((zone) => typeof zone === "object" && zone !== null && typeof zone.id === "string" && Array.isArray(zone.nodes));
9
+ }
10
+ export function renderSiteDocument(document, options) {
11
+ if (!isSiteBuilderDocument(document))
12
+ return [];
13
+ const zone = document.zones.find((item) => item.kind === options.zone || item.id === options.zone)
14
+ ?? document.zones.find((item) => item.kind === "body")
15
+ ?? document.zones.find((item) => item.id === "body");
16
+ if (!zone)
17
+ return [];
18
+ const renderNodes = (nodes) => nodes.flatMap((node, index) => {
19
+ if (node.props?.hidden === true)
20
+ return [];
21
+ if (options.nodeOverrides && Object.prototype.hasOwnProperty.call(options.nodeOverrides, node.id)) {
22
+ return [options.nodeOverrides[node.id]];
23
+ }
24
+ const renderer = options.registry[node.kind];
25
+ if (!renderer) {
26
+ options.onUnknownBlock?.(node);
27
+ return [];
28
+ }
29
+ return [renderer({
30
+ node,
31
+ children: renderNodes(Array.isArray(node.children) ? node.children : []),
32
+ index,
33
+ siblingCount: nodes.length,
34
+ data: options.dataByNodeId?.[node.id],
35
+ })];
36
+ });
37
+ return renderNodes(zone.nodes);
38
+ }
39
+ const propertyPattern = /^(--[a-z0-9-]+|[a-z][a-z0-9-]*)$/;
40
+ // Node styles are emitted inside a raw <style> element. Reject declaration and
41
+ // rule breakout, CSS escapes and every resource-loading function. Builder
42
+ // styles do not need external resources; assets belong in typed block props.
43
+ const unsafeValuePattern = /[<>{};@\\]|(?:url|image-set|image|cross-fade)[\s\u00a0]*\(|expression[\s\u00a0]*\(|javascript[\s\u00a0]*:/i;
44
+ export function safeStyleRule(properties) {
45
+ return Object.entries(properties).flatMap(([property, value]) => {
46
+ const cssProperty = property.replace(/[A-Z]/g, (character) => `-${character.toLowerCase()}`);
47
+ if (!propertyPattern.test(cssProperty) || value === undefined || value === null || typeof value === "object")
48
+ return [];
49
+ const cssValue = String(value).trim();
50
+ if (!cssValue || unsafeValuePattern.test(cssValue))
51
+ return [];
52
+ return [`${cssProperty}:${cssValue} !important`];
53
+ }).join(";");
54
+ }
55
+ export function collectResponsiveCSS(document, widths = {}) {
56
+ if (!isSiteBuilderDocument(document))
57
+ return "";
58
+ const mobile = widths.mobile ?? 390;
59
+ const tablet = widths.tablet ?? 768;
60
+ const rules = [];
61
+ const walk = (nodes) => {
62
+ for (const node of nodes) {
63
+ const escapedID = node.id.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/[\r\n]/g, "");
64
+ const selector = `[data-mml-nid="${escapedID}"]`;
65
+ const visibility = normalizeResponsiveVisibility(node.props?.responsiveVisibility);
66
+ const tabletRule = safeStyleRule(node.style?.tablet ?? {});
67
+ const mobileRule = safeStyleRule(node.style?.mobile ?? {});
68
+ const hoverRule = safeStyleRule(node.style?.hover ?? {});
69
+ const focusRule = safeStyleRule(node.style?.focus ?? {});
70
+ if (visibility.desktop === false)
71
+ rules.push(`@media (min-width:${tablet + 1}px){${selector}{display:none !important}}`);
72
+ if (visibility.tablet === false)
73
+ rules.push(`@media (min-width:${mobile + 1}px) and (max-width:${tablet}px){${selector}{display:none !important}}`);
74
+ if (visibility.mobile === false)
75
+ rules.push(`@media (max-width:${mobile}px){${selector}{display:none !important}}`);
76
+ if (tabletRule)
77
+ rules.push(`@media (max-width:${tablet}px){${selector}{${tabletRule}}}`);
78
+ if (mobileRule)
79
+ rules.push(`@media (max-width:${mobile}px){${selector}{${mobileRule}}}`);
80
+ if (hoverRule)
81
+ rules.push(`${selector}:hover{${hoverRule}}`);
82
+ if (focusRule)
83
+ rules.push(`${selector}:focus{${focusRule}}`);
84
+ walk(Array.isArray(node.children) ? node.children : []);
85
+ }
86
+ };
87
+ for (const zone of document.zones)
88
+ walk(zone.nodes);
89
+ return rules.join("");
90
+ }
91
+ function normalizeResponsiveVisibility(value) {
92
+ if (typeof value !== "object" || value === null || Array.isArray(value))
93
+ return {};
94
+ const source = value;
95
+ const result = {};
96
+ for (const device of ["desktop", "tablet", "mobile"]) {
97
+ if (typeof source[device] === "boolean")
98
+ result[device] = source[device];
99
+ }
100
+ return result;
101
+ }
package/dist/types.d.ts CHANGED
@@ -29,15 +29,44 @@ export interface PublicWorkspaceInit {
29
29
  max_age?: number;
30
30
  };
31
31
  }
32
+ /**
33
+ * The public origin of a dash or workspace, resolved server-side once:
34
+ * verified hostname (external → the channel bound to it) > active channel
35
+ * site_url > hosted managed host. Use it for `metadataBase`, canonical/OG
36
+ * URLs, robots and sitemaps instead of a hardcoded base URL.
37
+ */
38
+ export interface SiteRef {
39
+ /** Absolute https origin, no trailing slash. */
40
+ url: string;
41
+ source: "hostname" | "channel" | "hosted";
42
+ /** The external channel that renders the site, when one does. */
43
+ channel_id?: string;
44
+ }
45
+ /**
46
+ * The headless bootstrap payload — one cached call carries identity,
47
+ * branding, features, locale, SEO defaults and the public origin. Navigation
48
+ * (`menus.get`) and theme (`theme.get`) stay separate, parallel reads.
49
+ */
32
50
  export interface LightInitResponse {
33
51
  workspace_id: string;
34
52
  workspace_name: string;
53
+ workspace_slug?: string;
35
54
  primary_color: string;
36
55
  logo_url?: string;
37
56
  logo_light_url?: string;
38
57
  logo_dark_url?: string;
39
58
  logo_square_url?: string;
40
59
  enabled_features: string[];
60
+ preferences?: {
61
+ currency?: string;
62
+ locale?: string;
63
+ timezone?: string;
64
+ };
65
+ site?: SiteRef;
66
+ seo?: {
67
+ title?: string;
68
+ description?: string;
69
+ };
41
70
  etag?: string;
42
71
  }
43
72
  export interface DashTenantInfo {
@@ -56,9 +85,34 @@ export interface DashPublicProfileInfo {
56
85
  header_media_url?: string;
57
86
  pricing_summary?: string;
58
87
  }
88
+ export interface DashBrandingInfo {
89
+ primary_color?: string;
90
+ logo_url?: string;
91
+ logo_square_url?: string;
92
+ favicon_url?: string;
93
+ cover_url?: string;
94
+ }
95
+ export interface DashLocaleInfo {
96
+ region?: string;
97
+ currency?: string;
98
+ locale?: string;
99
+ timezone?: string;
100
+ }
101
+ /**
102
+ * The dash bootstrap — one call for a marketing site's shell: identity,
103
+ * public profile, branding, locale, SEO defaults and the public origin.
104
+ * `dash.profile()` remains for the full profile page (gallery, about template).
105
+ */
59
106
  export interface DashInitResponse {
60
107
  tenant: DashTenantInfo;
61
108
  public_profile: DashPublicProfileInfo;
109
+ branding?: DashBrandingInfo;
110
+ locale?: DashLocaleInfo;
111
+ seo?: {
112
+ title?: string;
113
+ description?: string;
114
+ };
115
+ site?: SiteRef;
62
116
  }
63
117
  export interface DashPublicPage {
64
118
  profile: DashPublicProfileInfo & {
@@ -922,6 +976,53 @@ export interface SendCodeResponse {
922
976
  export interface CustomerResponse {
923
977
  end_user: Customer;
924
978
  }
979
+ export interface CustomerAuthSession {
980
+ id: string;
981
+ auth_method: string;
982
+ device_type: string;
983
+ browser_name: string;
984
+ os_name: string;
985
+ country_code?: string;
986
+ created_at: string;
987
+ last_seen_at: string;
988
+ expires_at: string;
989
+ revoked_at?: string;
990
+ current: boolean;
991
+ }
992
+ export interface CustomerSecurityActivity {
993
+ id: string;
994
+ event_type: string;
995
+ category: string;
996
+ severity: string;
997
+ outcome: string;
998
+ country_code?: string;
999
+ session_id?: string;
1000
+ metadata?: Record<string, unknown>;
1001
+ occurred_at: string;
1002
+ }
1003
+ export interface CustomerSecurityActivityPage {
1004
+ items: CustomerSecurityActivity[];
1005
+ next_cursor?: string;
1006
+ has_more: boolean;
1007
+ }
1008
+ export interface ChannelGeo {
1009
+ country: string;
1010
+ countryName: string;
1011
+ currency: {
1012
+ code: string;
1013
+ symbol: string;
1014
+ };
1015
+ region: {
1016
+ code: string;
1017
+ name: string;
1018
+ currency: string;
1019
+ currencySymbol: string;
1020
+ locale: string;
1021
+ timezone: string;
1022
+ };
1023
+ ip: string;
1024
+ source: string;
1025
+ }
925
1026
  export interface Order {
926
1027
  id: string;
927
1028
  workspace_id?: string;
@@ -1072,4 +1173,5 @@ export interface ChannelPing {
1072
1173
  saas_app: string;
1073
1174
  scope: "workspace" | "dash";
1074
1175
  api_version: string;
1176
+ attestation?: string;
1075
1177
  }
@@ -108,6 +108,12 @@ export declare class ChannelWebhookVerificationError extends Error {
108
108
  readonly code: ChannelWebhookVerificationCode;
109
109
  constructor(message: string, code: ChannelWebhookVerificationCode);
110
110
  }
111
+ /**
112
+ * Structural, not instanceof — works across duplicate package instances and
113
+ * transformed test bundles. Exported so any consumer writing its own route
114
+ * handler can branch on "unverifiable request" without re-deriving this.
115
+ */
116
+ export declare function isChannelWebhookVerificationError(error: unknown): error is ChannelWebhookVerificationError;
111
117
  export declare const CHANNEL_WEBHOOK_SIGNATURE_HEADER = "X-C1M-Signature";
112
118
  export declare const CHANNEL_WEBHOOK_TIMESTAMP_HEADER = "X-C1M-Timestamp";
113
119
  export declare const CHANNEL_WEBHOOK_EVENT_ID_HEADER = "X-C1M-Event-ID";
package/dist/webhooks.js CHANGED
@@ -9,6 +9,7 @@
9
9
  * PII-free fields; fetch the detail back through the channel client. Data POSTed
10
10
  * to your server can never be reached by a GDPR erasure on ours.
11
11
  */
12
+ import { ChannelConfigurationError } from "./errors.js";
12
13
  export const CHANNEL_WEBHOOK_EVENT_TYPES = [
13
14
  "order.created",
14
15
  "order.paid",
@@ -37,6 +38,17 @@ export class ChannelWebhookVerificationError extends Error {
37
38
  this.name = "ChannelWebhookVerificationError";
38
39
  }
39
40
  }
41
+ /**
42
+ * Structural, not instanceof — works across duplicate package instances and
43
+ * transformed test bundles. Exported so any consumer writing its own route
44
+ * handler can branch on "unverifiable request" without re-deriving this.
45
+ */
46
+ export function isChannelWebhookVerificationError(error) {
47
+ return (error instanceof ChannelWebhookVerificationError ||
48
+ (typeof error === "object" && error !== null &&
49
+ error.name === "ChannelWebhookVerificationError" &&
50
+ typeof error.code === "string"));
51
+ }
40
52
  export const CHANNEL_WEBHOOK_SIGNATURE_HEADER = "X-C1M-Signature";
41
53
  export const CHANNEL_WEBHOOK_TIMESTAMP_HEADER = "X-C1M-Timestamp";
42
54
  export const CHANNEL_WEBHOOK_EVENT_ID_HEADER = "X-C1M-Event-ID";
@@ -87,7 +99,7 @@ export async function verifyChannelWebhookSignature(options) {
87
99
  const tolerance = options.toleranceSeconds ?? DEFAULT_TOLERANCE_SECONDS;
88
100
  const now = options.now ?? Date.now;
89
101
  if (!secret)
90
- throw new Error("secret is required");
102
+ throw new ChannelConfigurationError("secret is required");
91
103
  if (!signature) {
92
104
  throw new ChannelWebhookVerificationError(`missing ${CHANNEL_WEBHOOK_SIGNATURE_HEADER} header`, "missing_signature");
93
105
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@c1m-public/channel-client",
3
- "version": "0.11.0",
3
+ "version": "0.14.0",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "description": "Typed server-side client for the MML headless Channel API",
@@ -27,6 +27,18 @@
27
27
  "./webhooks": {
28
28
  "types": "./dist/webhooks.d.ts",
29
29
  "default": "./dist/webhooks.js"
30
+ },
31
+ "./renderer": {
32
+ "types": "./dist/renderer.d.ts",
33
+ "default": "./dist/renderer.js"
34
+ },
35
+ "./dash": {
36
+ "types": "./dist/dash.d.ts",
37
+ "default": "./dist/dash.js"
38
+ },
39
+ "./dash/next": {
40
+ "types": "./dist/dash-next.d.ts",
41
+ "default": "./dist/dash-next.js"
30
42
  }
31
43
  },
32
44
  "files": [
@@ -39,6 +51,13 @@
39
51
  "publishConfig": {
40
52
  "access": "public"
41
53
  },
54
+ "dependencies": {
55
+ "server-only": "0.0.1"
56
+ },
57
+ "devDependencies": {
58
+ "typescript": "5.9.3",
59
+ "vitest": "^4.1.4"
60
+ },
42
61
  "scripts": {
43
62
  "clean": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\"",
44
63
  "build": "pnpm clean && tsc -p tsconfig.build.json",
@@ -46,12 +65,5 @@
46
65
  "test": "vitest",
47
66
  "test:run": "vitest run",
48
67
  "type-check": "tsc -p tsconfig.json --noEmit"
49
- },
50
- "dependencies": {
51
- "server-only": "0.0.1"
52
- },
53
- "devDependencies": {
54
- "typescript": "5.9.3",
55
- "vitest": "^4.1.4"
56
68
  }
57
- }
69
+ }