@c1m-public/channel-client 0.2.1 → 0.3.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
@@ -13,7 +13,7 @@ const channel = createChannelClient({
13
13
  cache: { revalidate: 60 },
14
14
  });
15
15
 
16
- const document = await channel.site.resolve({ route: "/" });
16
+ const { page } = await channel.pages.get("home");
17
17
  ```
18
18
 
19
19
  The package must only be imported from server modules. Never expose the token in
@@ -28,6 +28,19 @@ asset requests.
28
28
  - Requests time out after 10 seconds by default.
29
29
  - API failures throw `ChannelAPIError` with safe status, code, and request ID.
30
30
  - Assets remain tokenless and are normalized with `assetUrl()`.
31
+ - `observe` can receive one bounded telemetry event per logical request. Events
32
+ contain operation, outcome, status, request ID, duration and attempt count;
33
+ they never contain URLs, credentials, headers, bodies or customer data.
34
+
35
+ ```ts
36
+ const channel = createChannelClient({
37
+ baseUrl: process.env.C1M_API_URL!,
38
+ token: process.env.C1M_CHANNEL_TOKEN!,
39
+ observe(event) {
40
+ console.info("c1m.channel", event);
41
+ },
42
+ });
43
+ ```
31
44
 
32
45
  ## Webhooks
33
46
 
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import "server-only";
2
2
  export * from "./webhooks.js";
3
- export type { BlogPost, BlogPostResponse, Customer, CustomerResponse, CustomerSession, CustomerSignupResponse, LeadResponse, Order, OrderSummary, SendCodeResponse, LightInitResponse, ListResponse, Product, ProductAsset, PublicPage, PublicPageSummary, PublicSubmitReviewInput, PublicWorkspaceInit, Menu, MenuItem, MenuResponse, Review, ReviewSummaryResponse, SiteDocument, SiteGatedDocument, SiteResolvedDocument, ThemeResponse, } from "./types";
4
- import type { BlogPostResponse, CustomerResponse, CustomerSession, CustomerSignupResponse, LeadResponse, LightInitResponse, ListResponse, Order, OrderSummary, SendCodeResponse, Product, ProductAsset, PublicPage, PublicPageSummary, PublicSubmitReviewInput, PublicWorkspaceInit, MenuResponse, Review, ReviewSummaryResponse, SiteDocument, ThemeResponse } from "./types";
3
+ export type { BlogPost, BlogPostResponse, ChannelPing, Customer, CustomerResponse, CustomerSession, CustomerSignupResponse, LeadResponse, Order, OrderSummary, SendCodeResponse, LightInitResponse, ListResponse, Product, ProductAsset, PublicPage, PublicPageSummary, PublicSubmitReviewInput, PublicWorkspaceInit, Menu, MenuItem, MenuResponse, Review, ReviewSummaryResponse, SiteDocument, SiteGatedDocument, SiteResolvedDocument, ThemeResponse, } from "./types";
4
+ import type { BlogPostResponse, ChannelPing, CustomerResponse, CustomerSession, CustomerSignupResponse, LeadResponse, LightInitResponse, ListResponse, Order, OrderSummary, SendCodeResponse, Product, ProductAsset, PublicPage, PublicPageSummary, PublicSubmitReviewInput, PublicWorkspaceInit, MenuResponse, Review, ReviewSummaryResponse, SiteDocument, ThemeResponse } from "./types";
5
5
  export type ChannelCachePolicy = "no-store" | {
6
6
  revalidate: number;
7
7
  tags?: string[];
@@ -17,7 +17,24 @@ export interface CreateChannelClientOptions {
17
17
  cache?: ChannelCachePolicy;
18
18
  timeoutMs?: number;
19
19
  retry?: ChannelRetryPolicy | false;
20
+ observe?: ChannelRequestObserver;
20
21
  }
22
+ export type ChannelRequestOutcome = "success" | "api_error" | "network_error" | "timeout" | "invalid_response";
23
+ 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.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.orders.list" | "channel.account.orders.summary" | "channel.account.orders.get" | "growth.public_workspace.leads.capture.channel";
24
+ export interface ChannelRequestObservation {
25
+ operation: ChannelOperation;
26
+ method: string;
27
+ outcome: ChannelRequestOutcome;
28
+ status: number;
29
+ requestId: string;
30
+ durationMs: number;
31
+ attempts: number;
32
+ }
33
+ /**
34
+ * Receives bounded request telemetry. Observations deliberately exclude URLs,
35
+ * headers, credentials, request bodies, response bodies and customer data.
36
+ */
37
+ export type ChannelRequestObserver = (observation: ChannelRequestObservation) => void;
21
38
  export interface ChannelListParams {
22
39
  cursor?: string;
23
40
  limit?: number;
@@ -46,6 +63,16 @@ export declare class ChannelAPIError extends Error {
46
63
  constructor(message: string, status: number, code: string, requestId: string);
47
64
  }
48
65
  export declare function createChannelClient(options: CreateChannelClientOptions): {
66
+ /**
67
+ * Verify the channel token and see what it points at.
68
+ *
69
+ * The cheapest call on the door — it does no database work server-side. Use
70
+ * it as a deployment health check: a 200 means C1M_CHANNEL_TOKEN is right and
71
+ * aimed at the workspace you expect. A ChannelAPIError with status 401 means
72
+ * the token is bad, revoked, or the channel is disabled (the door will not
73
+ * say which). A 503 means C1M is unavailable — NOT that your token is wrong.
74
+ */
75
+ readonly ping: () => Promise<ChannelPing>;
49
76
  readonly assetUrl: (pathOrUrl: string) => string;
50
77
  readonly site: {
51
78
  readonly resolve: (params?: ChannelSiteResolveParams) => Promise<SiteDocument>;
package/dist/index.js CHANGED
@@ -69,8 +69,14 @@ export function createChannelClient(options) {
69
69
  }
70
70
  const retryAttempts = configuredRetryAttempts;
71
71
  const maxRetryDelayMs = positiveNumber(options.retry === false ? 2_000 : options.retry?.maxDelayMs ?? 2_000, "retry.maxDelayMs");
72
- async function request(path, init = {}, session) {
72
+ const observe = options.observe;
73
+ async function request(operation, path, init = {}, session) {
73
74
  const method = (init.method ?? "GET").toUpperCase();
75
+ const startedAt = Date.now();
76
+ let attempts = 0;
77
+ let status = 0;
78
+ let requestId = "";
79
+ let outcome = "network_error";
74
80
  const headers = new Headers(init.headers);
75
81
  // The channel token authenticates the APP. A customer is a SECOND,
76
82
  // separate credential — Authorization is already spoken for, so the
@@ -92,89 +98,115 @@ export function createChannelClient(options) {
92
98
  else {
93
99
  requestInit.cache = "no-store";
94
100
  }
95
- let response;
96
- for (let attempt = 0; attempt <= retryAttempts; attempt += 1) {
97
- const controller = new AbortController();
98
- const timeout = setTimeout(() => controller.abort(), timeoutMs);
99
- const abort = () => controller.abort();
100
- init.signal?.addEventListener("abort", abort, { once: true });
101
- if (init.signal?.aborted)
102
- controller.abort();
103
- try {
104
- response = await fetcher(`${baseUrl}/api/v1/channel${path}`, { ...requestInit, signal: controller.signal });
105
- }
106
- catch (error) {
107
- if (controller.signal.aborted) {
108
- const code = init.signal?.aborted ? "channel_request_aborted" : "channel_request_timeout";
109
- throw new ChannelAPIError(code === "channel_request_timeout" ? "Channel API request timed out" : "Channel API request aborted", 0, code, "");
101
+ try {
102
+ let response;
103
+ for (let attempt = 0; attempt <= retryAttempts; attempt += 1) {
104
+ attempts = attempt + 1;
105
+ const controller = new AbortController();
106
+ const timeout = setTimeout(() => controller.abort(), timeoutMs);
107
+ try {
108
+ response = await fetcher(`${baseUrl}/api/v1/channel${path}`, { ...requestInit, signal: controller.signal });
109
+ }
110
+ catch (error) {
111
+ if (controller.signal.aborted) {
112
+ outcome = "timeout";
113
+ throw new ChannelAPIError("Channel API request timed out", 0, "channel_request_timeout", "");
114
+ }
115
+ outcome = "network_error";
116
+ throw new ChannelAPIError("Channel API request failed", 0, "channel_network_error", "");
117
+ }
118
+ finally {
119
+ clearTimeout(timeout);
110
120
  }
121
+ if (method !== "GET" || !RETRYABLE_STATUSES.has(response.status) || attempt === retryAttempts)
122
+ break;
123
+ await wait(retryDelay(response, maxRetryDelayMs));
124
+ }
125
+ if (!response)
111
126
  throw new ChannelAPIError("Channel API request failed", 0, "channel_network_error", "");
127
+ status = response.status;
128
+ requestId = response.headers.get("X-Request-ID") ?? "";
129
+ if (!response.ok) {
130
+ const payload = (await response.json().catch(() => ({})));
131
+ requestId = typeof payload.request_id === "string" ? payload.request_id : requestId;
132
+ outcome = "api_error";
133
+ throw new ChannelAPIError(typeof payload.message === "string" ? payload.message : "Channel API request failed", response.status, typeof payload.code === "string" ? payload.code : "channel_request_failed", requestId);
112
134
  }
113
- finally {
114
- clearTimeout(timeout);
115
- init.signal?.removeEventListener("abort", abort);
135
+ try {
136
+ const payload = (await response.json());
137
+ outcome = "success";
138
+ return payload;
139
+ }
140
+ catch {
141
+ outcome = "invalid_response";
142
+ throw new ChannelAPIError("Channel API response was not valid JSON", response.status, "invalid_channel_response", requestId);
116
143
  }
117
- if (method !== "GET" || !RETRYABLE_STATUSES.has(response.status) || attempt === retryAttempts)
118
- break;
119
- await wait(retryDelay(response, maxRetryDelayMs));
120
- }
121
- if (!response)
122
- throw new ChannelAPIError("Channel API request failed", 0, "channel_network_error", "");
123
- if (!response.ok) {
124
- const payload = (await response.json().catch(() => ({})));
125
- throw new ChannelAPIError(typeof payload.message === "string" ? payload.message : "Channel API request failed", response.status, typeof payload.code === "string" ? payload.code : "channel_request_failed", typeof payload.request_id === "string" ? payload.request_id : response.headers.get("X-Request-ID") ?? "");
126
- }
127
- try {
128
- return (await response.json());
129
144
  }
130
- catch {
131
- throw new ChannelAPIError("Channel API response was not valid JSON", response.status, "invalid_channel_response", response.headers.get("X-Request-ID") ?? "");
145
+ finally {
146
+ if (observe) {
147
+ try {
148
+ observe({ operation, method, outcome, status, requestId, durationMs: Math.max(0, Date.now() - startedAt), attempts });
149
+ }
150
+ catch {
151
+ // Telemetry must never become part of the request's availability path.
152
+ }
153
+ }
132
154
  }
133
155
  }
134
156
  function mutationHeaders(mutation) {
135
157
  return mutation?.idempotencyKey ? { "Idempotency-Key": mutation.idempotencyKey } : undefined;
136
158
  }
137
159
  return {
160
+ /**
161
+ * Verify the channel token and see what it points at.
162
+ *
163
+ * The cheapest call on the door — it does no database work server-side. Use
164
+ * it as a deployment health check: a 200 means C1M_CHANNEL_TOKEN is right and
165
+ * aimed at the workspace you expect. A ChannelAPIError with status 401 means
166
+ * the token is bad, revoked, or the channel is disabled (the door will not
167
+ * say which). A 503 means C1M is unavailable — NOT that your token is wrong.
168
+ */
169
+ ping: () => request("channel.ping", "/ping"),
138
170
  assetUrl: (pathOrUrl) => new URL(required(pathOrUrl, "asset URL"), `${baseUrl}/`).toString(),
139
171
  site: {
140
- resolve: (params = {}) => request(appendQuery("/site/resolve", params)),
172
+ resolve: (params = {}) => request("channel.site.resolve", appendQuery("/site/resolve", params)),
141
173
  },
142
174
  init: {
143
- get: () => request("/init"),
144
- light: () => request("/init/light"),
175
+ get: () => request("channel.init.get", "/init"),
176
+ light: () => request("channel.init.light", "/init/light"),
145
177
  },
146
178
  pages: {
147
- list: (params = {}) => request(appendQuery("/pages", params)),
148
- get: (slug) => request(`/pages/${encodePath(slug)}`),
179
+ list: (params = {}) => request("content.pages.public.list.channel", appendQuery("/pages", params)),
180
+ get: (slug) => request("content.pages.public.get.channel", `/pages/${encodePath(slug)}`),
149
181
  },
150
182
  products: {
151
- list: (params = {}) => request(appendQuery("/products", params)),
152
- get: (slug) => request(`/products/${encodePath(slug)}`),
153
- media: (slug) => request(`/products/${encodePath(slug)}/media`),
183
+ list: (params = {}) => request("shop.public.products.list.channel", appendQuery("/products", params)),
184
+ get: (slug) => request("shop.public.products.get.channel", `/products/${encodePath(slug)}`),
185
+ media: (slug) => request("shop.public.products.media.channel", `/products/${encodePath(slug)}/media`),
154
186
  },
155
187
  reviews: {
156
- list: (params = {}) => request(appendQuery("/reviews", params)),
157
- summary: () => request("/reviews/summary"),
158
- submit: (input, mutation) => request("/reviews", {
188
+ list: (params = {}) => request("reviews.public.list.channel", appendQuery("/reviews", params)),
189
+ summary: () => request("reviews.public.summary.channel", "/reviews/summary"),
190
+ submit: (input, mutation) => request("reviews.public.submit.channel", "/reviews", {
159
191
  method: "POST", headers: mutationHeaders(mutation), body: JSON.stringify(input),
160
192
  }),
161
193
  },
162
194
  theme: {
163
- get: () => request("/theme"),
195
+ get: () => request("channel.theme.get", "/theme"),
164
196
  },
165
197
  menus: {
166
- get: (handle) => request(`/menus/${encodePath(handle)}`),
198
+ get: (handle) => request("channel.menus.get", `/menus/${encodePath(handle)}`),
167
199
  },
168
200
  blog: {
169
- get: (slug) => request(`/blog/posts/${encodePath(slug)}`),
201
+ get: (slug) => request("channel.blog.get", `/blog/posts/${encodePath(slug)}`),
170
202
  },
171
203
  // Customer sign-in. These are anonymous calls — they CREATE a session.
172
204
  auth: {
173
- check: (email) => request("/auth/check", { method: "POST", body: JSON.stringify({ email }) }),
174
- signup: (input) => request("/auth/signup", { method: "POST", body: JSON.stringify(input) }),
175
- sendCode: (email) => request("/auth/send-code", { method: "POST", body: JSON.stringify({ email }) }),
176
- verifyCode: (input) => request("/auth/verify-code", { method: "POST", body: JSON.stringify(input) }),
177
- refresh: (refreshToken) => request("/auth/refresh", { method: "POST", body: JSON.stringify({ refresh_token: refreshToken }) }),
205
+ check: (email) => request("channel.auth.check", "/auth/check", { method: "POST", body: JSON.stringify({ email }) }),
206
+ signup: (input) => request("channel.auth.signup", "/auth/signup", { method: "POST", body: JSON.stringify(input) }),
207
+ sendCode: (email) => request("channel.auth.send_code", "/auth/send-code", { method: "POST", body: JSON.stringify({ email }) }),
208
+ verifyCode: (input) => request("channel.auth.verify_code", "/auth/verify-code", { method: "POST", body: JSON.stringify(input) }),
209
+ refresh: (refreshToken) => request("channel.auth.refresh", "/auth/refresh", { method: "POST", body: JSON.stringify({ refresh_token: refreshToken }) }),
178
210
  },
179
211
  /**
180
212
  * Scope calls to a signed-in customer.
@@ -190,18 +222,18 @@ export function createChannelClient(options) {
190
222
  withCustomer(session) {
191
223
  const customerSession = required(session, "session");
192
224
  return {
193
- me: () => request("/auth/me", {}, customerSession),
194
- updateProfile: (input) => request("/auth/me", { method: "PUT", body: JSON.stringify(input) }, customerSession),
195
- logout: () => request("/auth/logout", { method: "POST" }, customerSession),
225
+ me: () => request("channel.auth.me", "/auth/me", {}, customerSession),
226
+ updateProfile: (input) => request("channel.auth.me.update", "/auth/me", { method: "PUT", body: JSON.stringify(input) }, customerSession),
227
+ logout: () => request("channel.auth.logout", "/auth/logout", { method: "POST" }, customerSession),
196
228
  orders: {
197
- list: (params = {}) => request(appendQuery("/account/orders", params), {}, customerSession),
198
- summary: () => request("/account/orders/summary", {}, customerSession),
199
- get: (orderId) => request(`/account/orders/${encodePath(orderId)}`, {}, customerSession),
229
+ list: (params = {}) => request("channel.account.orders.list", appendQuery("/account/orders", params), {}, customerSession),
230
+ summary: () => request("channel.account.orders.summary", "/account/orders/summary", {}, customerSession),
231
+ get: (orderId) => request("channel.account.orders.get", `/account/orders/${encodePath(orderId)}`, {}, customerSession),
200
232
  },
201
233
  };
202
234
  },
203
235
  leads: {
204
- create: (input, mutation) => request("/leads", {
236
+ create: (input, mutation) => request("growth.public_workspace.leads.capture.channel", "/leads", {
205
237
  method: "POST", headers: mutationHeaders(mutation), body: JSON.stringify(input),
206
238
  }),
207
239
  },
package/dist/types.d.ts CHANGED
@@ -41,21 +41,36 @@ export interface LightInitResponse {
41
41
  etag?: string;
42
42
  }
43
43
  export interface PublicPageSummary {
44
- page_key?: string;
45
- page_type: "system" | "custom";
46
- is_builder_editable: boolean;
44
+ id: string;
45
+ saas_app: string;
46
+ workspace_id: string;
47
+ source: string;
48
+ route_kind: string;
49
+ route_pattern: string;
47
50
  slug: string;
48
51
  title: string;
52
+ status: string;
53
+ status_reason: string;
49
54
  visibility: "hidden" | "visible";
55
+ edit_mode: string;
56
+ draft_revision: number;
57
+ created_at: string;
58
+ updated_at: string;
50
59
  }
51
60
  export interface PublicPage extends PublicPageSummary {
52
- id: string;
53
- workspace_id: string;
61
+ owner_app?: string;
62
+ required_apps?: string[];
63
+ required_features?: string[];
54
64
  seo_title?: string;
55
65
  seo_description?: string;
56
- content?: unknown;
57
- created_at?: string;
58
- updated_at?: string;
66
+ draft_state?: unknown;
67
+ layout_state?: unknown;
68
+ published_at?: string;
69
+ manifest_key?: string;
70
+ manifest_version?: number;
71
+ template_key?: string;
72
+ theme_id?: string;
73
+ default_shell_template_id?: string;
59
74
  }
60
75
  export interface Product {
61
76
  id: string;
@@ -265,3 +280,10 @@ export interface OrderSummary {
265
280
  total_orders: number;
266
281
  [key: string]: unknown;
267
282
  }
283
+ /** What the door reports about the token you just used. */
284
+ export interface ChannelPing {
285
+ channel_id: string;
286
+ workspace_id: string;
287
+ saas_app: string;
288
+ api_version: string;
289
+ }
package/package.json CHANGED
@@ -1,9 +1,18 @@
1
1
  {
2
2
  "name": "@c1m-public/channel-client",
3
- "version": "0.2.1",
3
+ "version": "0.3.0",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "description": "Server-only TypeScript client for the MML headless Channel API",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://github.com/cloud1mediaLtd/mml-js.git",
10
+ "directory": "packages/channel-client"
11
+ },
12
+ "homepage": "https://github.com/cloud1mediaLtd/mml-js/tree/main/packages/channel-client",
13
+ "bugs": {
14
+ "url": "https://github.com/cloud1mediaLtd/mml-js/issues"
15
+ },
7
16
  "main": "./dist/index.js",
8
17
  "types": "./dist/index.d.ts",
9
18
  "exports": {