@c1m-public/channel-client 0.10.0 → 0.12.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,18 +12,24 @@ 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
18
20
  identifiers.
19
21
 
22
+ Managed C1M sites need one deployment secret: `C1M_CHANNEL_TOKEN`. The client
23
+ uses `https://api.saasdash.app` by default. Pass `baseUrl` directly only for
24
+ local development or private C1M infrastructure; it is not part of the normal
25
+ deployment contract.
26
+
20
27
  ### Next.js
21
28
 
22
29
  ```ts
23
30
  import { createNextChannelClient } from "@c1m-public/channel-client/next";
24
31
 
25
32
  const channel = createNextChannelClient({
26
- baseUrl: process.env.C1M_API_URL!,
27
33
  token: process.env.C1M_CHANNEL_TOKEN!,
28
34
  cache: { revalidate: 60 },
29
35
  });
@@ -49,7 +55,6 @@ const checkout = await channel.checkout.pay(
49
55
  import { createChannelClient } from "@c1m-public/channel-client";
50
56
 
51
57
  const channel = createChannelClient({
52
- baseUrl: process.env.C1M_API_URL!,
53
58
  token: process.env.C1M_CHANNEL_TOKEN!,
54
59
  });
55
60
 
@@ -65,6 +70,38 @@ const directory = await channel.dash.directory.list({ region: "london" });
65
70
  const account = channel.withCustomer(customerAccessToken);
66
71
  const addresses = await account.addresses.list();
67
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);
68
105
  ```
69
106
 
70
107
  ### Headless customer OTP
@@ -122,7 +159,6 @@ other runtimes must enforce their own server-module boundary.
122
159
 
123
160
  ```ts
124
161
  const channel = createChannelClient({
125
- baseUrl: process.env.C1M_API_URL!,
126
162
  token: process.env.C1M_CHANNEL_TOKEN!,
127
163
  observe(event) {
128
164
  console.info("c1m.channel", event);
@@ -191,7 +227,6 @@ price and a stale one at checkout.
191
227
  ```ts
192
228
  // A client whose reads are filed under the catalog tag the webhook route busts.
193
229
  const catalog = createNextChannelClient({
194
- baseUrl: process.env.C1M_API_URL!,
195
230
  token: process.env.C1M_CHANNEL_TOKEN!,
196
231
  cache: { revalidate: 3600, tags: [CHANNEL_CATALOG_CACHE_TAG] },
197
232
  });
package/dist/index.d.ts CHANGED
@@ -1,12 +1,14 @@
1
1
  export * from "./webhooks.js";
2
2
  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";
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, 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
+ export declare const DEFAULT_CHANNEL_API_URL = "https://api.saasdash.app";
4
5
  export interface ChannelRetryPolicy {
5
6
  attempts?: number;
6
7
  maxDelayMs?: number;
7
8
  }
8
9
  export interface CreateChannelClientOptions {
9
- baseUrl: string;
10
+ /** Override only for local development or private C1M infrastructure. */
11
+ baseUrl?: string;
10
12
  token: string;
11
13
  fetch?: typeof globalThis.fetch;
12
14
  timeoutMs?: number;
@@ -14,9 +16,16 @@ export interface CreateChannelClientOptions {
14
16
  observe?: ChannelRequestObserver;
15
17
  /** Optional request-scope cancellation signal, combined with the timeout. */
16
18
  signal?: AbortSignal;
19
+ /** Verified visitor metadata from the hosting edge. Never accept these values from an untrusted caller. */
20
+ visitor?: ChannelVisitor;
21
+ }
22
+ export interface ChannelVisitor {
23
+ ip?: string;
24
+ country?: string;
25
+ userAgent?: string;
17
26
  }
18
27
  export type ChannelRequestOutcome = "success" | "api_error" | "network_error" | "timeout" | "invalid_response" | "cancelled";
19
- 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";
28
+ 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";
20
29
  export interface ChannelRequestObservation {
21
30
  operation: ChannelOperation;
22
31
  method: string;
@@ -91,7 +100,12 @@ export declare function createChannelClient(options: CreateChannelClientOptions)
91
100
  * the token is bad, revoked, or the channel is disabled (the door will not
92
101
  * say which). A 503 means C1M is unavailable — NOT that your token is wrong.
93
102
  */
94
- readonly ping: () => Promise<ChannelPing>;
103
+ readonly ping: (challenge?: string) => Promise<ChannelPing>;
104
+ /** Return a request-scoped client that signs trusted edge visitor metadata. */
105
+ readonly withVisitor: (visitor: ChannelVisitor) => /*elided*/ any;
106
+ readonly geo: {
107
+ readonly detect: () => Promise<ChannelGeo>;
108
+ };
95
109
  /** Tenant-level data exposed only to a dash-scoped channel token. */
96
110
  readonly dash: {
97
111
  readonly profile: () => Promise<DashProfileResponse>;
@@ -230,6 +244,24 @@ export declare function createChannelClient(options: CreateChannelClientOptions)
230
244
  readonly logout: () => Promise<{
231
245
  status?: string;
232
246
  }>;
247
+ readonly sessions: {
248
+ readonly list: () => Promise<{
249
+ items: CustomerAuthSession[];
250
+ }>;
251
+ readonly revoke: (sessionId: string) => Promise<{
252
+ status?: string;
253
+ }>;
254
+ readonly revokeOthers: () => Promise<{
255
+ revoked: number;
256
+ }>;
257
+ readonly revokeAll: () => Promise<{
258
+ revoked: number;
259
+ }>;
260
+ };
261
+ readonly securityActivity: (params?: {
262
+ category?: string;
263
+ cursor?: string;
264
+ }) => Promise<CustomerSecurityActivityPage>;
233
265
  readonly orders: {
234
266
  readonly list: (params?: ChannelListParams) => Promise<ListResponse<Order>>;
235
267
  readonly summary: () => Promise<{
package/dist/index.js CHANGED
@@ -1,5 +1,6 @@
1
1
  export * from "./webhooks.js";
2
2
  const CHANNEL_TOKEN_PREFIX = "sk_chan_";
3
+ export const DEFAULT_CHANNEL_API_URL = "https://api.saasdash.app";
3
4
  const RETRYABLE_STATUSES = new Set([429, 502, 503, 504]);
4
5
  export class ChannelAPIError extends Error {
5
6
  status;
@@ -69,8 +70,33 @@ function combineSignals(...signals) {
69
70
  function isFormDataBody(body) {
70
71
  return typeof FormData !== "undefined" && body instanceof FormData;
71
72
  }
73
+ async function visitorHeaders(token, method, path, visitor) {
74
+ if (!visitor)
75
+ return undefined;
76
+ const ip = visitor.ip?.trim() ?? "";
77
+ const country = visitor.country?.trim().toUpperCase() ?? "";
78
+ const userAgent = visitor.userAgent?.trim() ?? "";
79
+ if (!ip && !country && !userAgent)
80
+ return undefined;
81
+ const timestamp = Math.floor(Date.now() / 1_000).toString();
82
+ const encoder = new TextEncoder();
83
+ const uaHash = await crypto.subtle.digest("SHA-256", encoder.encode(userAgent));
84
+ const hex = (bytes) => Array.from(new Uint8Array(bytes), (value) => value.toString(16).padStart(2, "0")).join("");
85
+ const canonical = ["v1", timestamp, method, `/api/v1/channel${path}`, ip, country, hex(uaHash)].join("\n");
86
+ const key = await crypto.subtle.importKey("raw", encoder.encode(token), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
87
+ const signature = hex(await crypto.subtle.sign("HMAC", key, encoder.encode(canonical)));
88
+ return {
89
+ "X-C1M-Visitor-IP": ip,
90
+ "X-C1M-Visitor-Country": country,
91
+ "X-C1M-Visitor-User-Agent": userAgent,
92
+ "X-C1M-Visitor-Timestamp": timestamp,
93
+ "X-C1M-Visitor-Signature": signature,
94
+ };
95
+ }
72
96
  export function createChannelClient(options) {
73
- const baseUrl = required(options.baseUrl, "baseUrl").replace(/\/+$/, "");
97
+ const baseUrl = (options.baseUrl === undefined
98
+ ? DEFAULT_CHANNEL_API_URL
99
+ : required(options.baseUrl, "baseUrl")).replace(/\/+$/, "");
74
100
  const token = required(options.token, "token");
75
101
  if (!token.startsWith(CHANNEL_TOKEN_PREFIX))
76
102
  throw new Error("token must start with sk_chan_");
@@ -97,6 +123,11 @@ export function createChannelClient(options) {
97
123
  // separate credential — Authorization is already spoken for, so the
98
124
  // customer's session rides in its own header.
99
125
  headers.set("Authorization", `Bearer ${token}`);
126
+ const signedVisitor = await visitorHeaders(token, method, path, options.visitor);
127
+ if (signedVisitor) {
128
+ for (const [key, value] of Object.entries(signedVisitor))
129
+ headers.set(key, value);
130
+ }
100
131
  if (session)
101
132
  headers.set("X-End-User-Token", session);
102
133
  if (init.body !== undefined && !isFormDataBody(init.body) && !headers.has("Content-Type")) {
@@ -192,7 +223,12 @@ export function createChannelClient(options) {
192
223
  * the token is bad, revoked, or the channel is disabled (the door will not
193
224
  * say which). A 503 means C1M is unavailable — NOT that your token is wrong.
194
225
  */
195
- ping: () => request("channel.ping", "/ping"),
226
+ ping: (challenge) => request("channel.ping", appendQuery("/ping", { challenge })),
227
+ /** Return a request-scoped client that signs trusted edge visitor metadata. */
228
+ withVisitor: (visitor) => createChannelClient({ ...options, visitor }),
229
+ geo: {
230
+ detect: () => request("channel.geo.detect", "/geo/detect"),
231
+ },
196
232
  /** Tenant-level data exposed only to a dash-scoped channel token. */
197
233
  dash: {
198
234
  profile: () => request("channel.dash.profile", "/dash/profile"),
@@ -359,6 +395,13 @@ export function createChannelClient(options) {
359
395
  me: () => request("channel.auth.me", "/auth/me", {}, customerSession),
360
396
  updateProfile: (input) => request("channel.auth.me.update", "/auth/me", { method: "PUT", body: JSON.stringify(input) }, customerSession),
361
397
  logout: () => request("channel.auth.logout", "/auth/logout", { method: "POST" }, customerSession),
398
+ sessions: {
399
+ list: () => request("channel.auth.sessions.list", "/auth/me/sessions", {}, customerSession),
400
+ revoke: (sessionId) => request("channel.auth.sessions.revoke", `/auth/me/sessions/${encodePath(sessionId)}`, { method: "DELETE" }, customerSession),
401
+ revokeOthers: () => request("channel.auth.sessions.revoke_others", "/auth/me/sessions/revoke-others", { method: "POST" }, customerSession),
402
+ revokeAll: () => request("channel.auth.sessions.revoke_all", "/auth/me/sessions/revoke-all", { method: "POST" }, customerSession),
403
+ },
404
+ securityActivity: (params = {}) => request("channel.auth.security_activity.list", appendQuery("/auth/me/security-activity", params), {}, customerSession),
362
405
  orders: {
363
406
  list: (params = {}) => request("channel.account.orders.list", appendQuery("/account/orders", params), {}, customerSession),
364
407
  summary: () => request("channel.account.orders.summary", "/account/orders/summary", {}, customerSession),
package/dist/next.d.ts CHANGED
@@ -15,7 +15,11 @@ export interface CreateNextChannelClientOptions extends Omit<CreateChannelClient
15
15
  * mutations are forced to `no-store` by both this adapter and the core client.
16
16
  */
17
17
  export declare function createNextChannelClient(options: CreateNextChannelClientOptions): {
18
- readonly ping: () => Promise<import("./types.js").ChannelPing>;
18
+ readonly ping: (challenge?: string) => Promise<import("./types.js").ChannelPing>;
19
+ readonly withVisitor: (visitor: import("./index.js").ChannelVisitor) => /*elided*/ any;
20
+ readonly geo: {
21
+ readonly detect: () => Promise<import("./types.js").ChannelGeo>;
22
+ };
19
23
  readonly dash: {
20
24
  readonly profile: () => Promise<import("./types.js").DashProfileResponse>;
21
25
  readonly init: () => Promise<import("./types.js").DashInitResponse>;
@@ -142,6 +146,24 @@ export declare function createNextChannelClient(options: CreateNextChannelClient
142
146
  readonly logout: () => Promise<{
143
147
  status?: string;
144
148
  }>;
149
+ readonly sessions: {
150
+ readonly list: () => Promise<{
151
+ items: import("./types.js").CustomerAuthSession[];
152
+ }>;
153
+ readonly revoke: (sessionId: string) => Promise<{
154
+ status?: string;
155
+ }>;
156
+ readonly revokeOthers: () => Promise<{
157
+ revoked: number;
158
+ }>;
159
+ readonly revokeAll: () => Promise<{
160
+ revoked: number;
161
+ }>;
162
+ };
163
+ readonly securityActivity: (params?: {
164
+ category?: string;
165
+ cursor?: string;
166
+ }) => Promise<import("./types.js").CustomerSecurityActivityPage>;
145
167
  readonly orders: {
146
168
  readonly list: (params?: import("./index.js").ChannelListParams) => Promise<import("./types.js").ListResponse<import("./types.js").Order>>;
147
169
  readonly summary: () => Promise<{
@@ -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
@@ -922,6 +922,53 @@ export interface SendCodeResponse {
922
922
  export interface CustomerResponse {
923
923
  end_user: Customer;
924
924
  }
925
+ export interface CustomerAuthSession {
926
+ id: string;
927
+ auth_method: string;
928
+ device_type: string;
929
+ browser_name: string;
930
+ os_name: string;
931
+ country_code?: string;
932
+ created_at: string;
933
+ last_seen_at: string;
934
+ expires_at: string;
935
+ revoked_at?: string;
936
+ current: boolean;
937
+ }
938
+ export interface CustomerSecurityActivity {
939
+ id: string;
940
+ event_type: string;
941
+ category: string;
942
+ severity: string;
943
+ outcome: string;
944
+ country_code?: string;
945
+ session_id?: string;
946
+ metadata?: Record<string, unknown>;
947
+ occurred_at: string;
948
+ }
949
+ export interface CustomerSecurityActivityPage {
950
+ items: CustomerSecurityActivity[];
951
+ next_cursor?: string;
952
+ has_more: boolean;
953
+ }
954
+ export interface ChannelGeo {
955
+ country: string;
956
+ countryName: string;
957
+ currency: {
958
+ code: string;
959
+ symbol: string;
960
+ };
961
+ region: {
962
+ code: string;
963
+ name: string;
964
+ currency: string;
965
+ currencySymbol: string;
966
+ locale: string;
967
+ timezone: string;
968
+ };
969
+ ip: string;
970
+ source: string;
971
+ }
925
972
  export interface Order {
926
973
  id: string;
927
974
  workspace_id?: string;
@@ -1072,4 +1119,5 @@ export interface ChannelPing {
1072
1119
  saas_app: string;
1073
1120
  scope: "workspace" | "dash";
1074
1121
  api_version: string;
1122
+ attestation?: string;
1075
1123
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@c1m-public/channel-client",
3
- "version": "0.10.0",
3
+ "version": "0.12.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,10 @@
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"
30
34
  }
31
35
  },
32
36
  "files": [