@c1m-public/channel-client 0.5.0 → 0.6.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
@@ -29,13 +29,16 @@ const channel = createNextChannelClient({
29
29
 
30
30
  const { page } = await channel.pages.get("home");
31
31
 
32
- const { order: cart } = await channel.cart.addItem(
33
- { product_id: "product-id", quantity: 1 },
34
- { idempotencyKey: crypto.randomUUID() },
35
- );
32
+ const { order: cart } = await channel.cart.addItem({ product_id: "product-id", quantity: 1 });
33
+
34
+ // Checkout is addressed by the ORDER the cart became (every cart call returns
35
+ // its order.id). The idempotency key is DETERMINISTIC on purpose: a fresh
36
+ // random key per retry is the exact duplicate-charge hazard idempotency exists
37
+ // to prevent.
36
38
  const checkout = await channel.checkout.pay(
39
+ cart.id,
37
40
  { cart_token: cart.cart_token!, return_url: "https://example.com/checkout/complete" },
38
- { idempotencyKey: crypto.randomUUID() },
41
+ { idempotencyKey: `pay:${cart.id}` },
39
42
  );
40
43
  ```
41
44
 
@@ -115,3 +118,38 @@ Publishing runs through npm Trusted Publishing and GitHub OIDC. Push a protected
115
118
  `channel-client-vX.Y.Z` tag matching `package.json`; the workflow verifies,
116
119
  packs, and publishes without a stored npm token. Published versions are
117
120
  immutable, so increment the package version for every release.
121
+
122
+ ## The `/next` kits
123
+
124
+ The ~600 lines of plumbing every headless site was copy-pasting, shipped once.
125
+ No `next` imports — apps inject `next/cache` and apply cookies where Next allows
126
+ writes (a Server Component cannot write cookies; proxy.ts and Server Actions can).
127
+
128
+ ```ts
129
+ // app/api/webhooks/c1m/route.ts — the whole file
130
+ import { revalidatePath, revalidateTag } from "next/cache";
131
+ import { createChannelWebhookRoute } from "@c1m-public/channel-client/next";
132
+
133
+ export const POST = createChannelWebhookRoute({
134
+ secret: () => process.env.C1M_CHANNEL_WEBHOOK_SECRET!,
135
+ invalidate: { revalidatePath, revalidateTag },
136
+ });
137
+ ```
138
+
139
+ ```ts
140
+ // session: cookie codec + the contested-vs-expired refresh decision
141
+ const session = createCustomerSession({ client: getChannelClient });
142
+ const result = await session.refresh(rawCookie); // keep | write | clear
143
+ // `keep` on refresh_contested is the load-bearing case: the customer's other
144
+ // tab already stored a fresh token — clearing would log out a live session.
145
+ ```
146
+
147
+ ```ts
148
+ // cart: server-side cart, client-held token, hosted checkout
149
+ const cart = createCart({ client: getChannelClient });
150
+ await cart.addItem({ cart_token, product_id, quantity: 1 });
151
+ const { redirect_url } = await cart.checkout.pay(orderId, {
152
+ cart_token,
153
+ return_url: "https://your-site.example/thanks", // must be on the channel's registered site
154
+ });
155
+ ```
package/dist/index.d.ts CHANGED
@@ -101,12 +101,12 @@ export declare function createChannelClient(options: CreateChannelClientOptions)
101
101
  readonly merge: (input: MergeCartInput, mutation?: ChannelMutationOptions) => Promise<CartResponse>;
102
102
  };
103
103
  readonly checkout: {
104
- readonly options: (cartToken: string) => Promise<CheckoutOptions>;
105
- readonly status: (params?: ChannelCheckoutStatusParams) => Promise<CheckoutStatusResponse>;
106
- readonly setCustomer: (input: CheckoutCustomerInput, mutation?: ChannelMutationOptions) => Promise<CartResponse>;
107
- readonly setAddresses: (input: CheckoutAddressesInput, mutation?: ChannelMutationOptions) => Promise<CartResponse>;
108
- readonly setFulfillment: (input: CheckoutFulfillmentInput, mutation?: ChannelMutationOptions) => Promise<CartResponse>;
109
- readonly pay: (input: CheckoutPayInput, mutation?: ChannelMutationOptions) => Promise<CheckoutPayResponse>;
104
+ readonly options: (orderId: string, cartToken: string) => Promise<CheckoutOptions>;
105
+ readonly status: (orderId: string, params?: ChannelCheckoutStatusParams) => Promise<CheckoutStatusResponse>;
106
+ readonly setCustomer: (orderId: string, input: CheckoutCustomerInput, mutation?: ChannelMutationOptions) => Promise<CartResponse>;
107
+ readonly setAddresses: (orderId: string, input: CheckoutAddressesInput, mutation?: ChannelMutationOptions) => Promise<CartResponse>;
108
+ readonly setFulfillment: (orderId: string, input: CheckoutFulfillmentInput, mutation?: ChannelMutationOptions) => Promise<CartResponse>;
109
+ readonly pay: (orderId: string, input: CheckoutPayInput, mutation?: ChannelMutationOptions) => Promise<CheckoutPayResponse>;
110
110
  };
111
111
  readonly reviews: {
112
112
  readonly list: (params?: ChannelListParams) => Promise<ListResponse<Review>>;
package/dist/index.js CHANGED
@@ -193,24 +193,29 @@ export function createChannelClient(options) {
193
193
  method: "POST", headers: mutationHeaders(mutation), body: JSON.stringify(input),
194
194
  }),
195
195
  },
196
+ // Checkout is addressed by the ORDER the cart became: the server mounts
197
+ // /checkout/{order_id}/... (the cart is an orders row, and every cart call
198
+ // returns its order.id). 0.5.0 shipped these without the order_id segment,
199
+ // so every checkout call 404'd — the signature change is safe because the
200
+ // old shape never worked.
196
201
  checkout: {
197
- options: (cartToken) => request("channel.checkout.options", appendQuery("/checkout/options", {
202
+ options: (orderId, cartToken) => request("channel.checkout.options", appendQuery(`/checkout/${encodePath(orderId)}/options`, {
198
203
  cart_token: required(cartToken, "cartToken"),
199
204
  })),
200
- status: (params = {}) => request("channel.checkout.status", appendQuery("/checkout/status", {
205
+ status: (orderId, params = {}) => request("channel.checkout.status", appendQuery(`/checkout/${encodePath(orderId)}/status`, {
201
206
  cart_token: params.cartToken,
202
207
  checkout_session_id: params.checkoutSessionId,
203
208
  })),
204
- setCustomer: (input, mutation) => request("channel.checkout.customer", "/checkout/customer", {
209
+ setCustomer: (orderId, input, mutation) => request("channel.checkout.customer", `/checkout/${encodePath(orderId)}/customer`, {
205
210
  method: "PUT", headers: mutationHeaders(mutation), body: JSON.stringify(input),
206
211
  }),
207
- setAddresses: (input, mutation) => request("channel.checkout.addresses", "/checkout/addresses", {
212
+ setAddresses: (orderId, input, mutation) => request("channel.checkout.addresses", `/checkout/${encodePath(orderId)}/addresses`, {
208
213
  method: "PUT", headers: mutationHeaders(mutation), body: JSON.stringify(input),
209
214
  }),
210
- setFulfillment: (input, mutation) => request("channel.checkout.fulfillment", "/checkout/fulfillment", {
215
+ setFulfillment: (orderId, input, mutation) => request("channel.checkout.fulfillment", `/checkout/${encodePath(orderId)}/fulfillment`, {
211
216
  method: "PUT", headers: mutationHeaders(mutation), body: JSON.stringify(input),
212
217
  }),
213
- pay: (input, mutation) => request("channel.checkout.pay", "/checkout/pay", {
218
+ pay: (orderId, input, mutation) => request("channel.checkout.pay", `/checkout/${encodePath(orderId)}/pay`, {
214
219
  method: "POST", headers: mutationHeaders(mutation), body: JSON.stringify(input),
215
220
  }),
216
221
  },
@@ -0,0 +1,74 @@
1
+ import "server-only";
2
+ import { createChannelClient, type ChannelCheckoutStatusParams } from "./index.js";
3
+ import type { AddCartItemInput, CartResponse, CheckoutAddressesInput, CheckoutCustomerInput, CheckoutFulfillmentInput, CheckoutOptions, CheckoutPayInput, CheckoutPayResponse, CheckoutStatusResponse, Order } from "./types.js";
4
+ export interface CartCookieAttributes {
5
+ httpOnly: true;
6
+ secure: boolean;
7
+ sameSite: "lax";
8
+ path: "/";
9
+ maxAge: number;
10
+ }
11
+ export declare const cartCookie: {
12
+ readonly name: "cart_token";
13
+ readonly attributes: (isProduction?: boolean) => CartCookieAttributes;
14
+ /**
15
+ * The client mints the token (the server accepts any sufficiently-random
16
+ * bearer key and creates the cart row on first use).
17
+ */
18
+ readonly mint: () => string;
19
+ /** Tolerant read: an absent or garbage cookie means "no cart yet". */
20
+ readonly parse: (raw: string | undefined) => string | null;
21
+ };
22
+ type CartClient = Pick<ReturnType<typeof createChannelClient>, "cart" | "checkout">;
23
+ export interface CreateCartOptions {
24
+ /** The channel client, or a lazy resolver (the singleton pattern). */
25
+ client: CartClient | (() => CartClient);
26
+ }
27
+ /**
28
+ * Cart + checkout, with the token threading done for you. Every method returns
29
+ * the cart's underlying ORDER — checkout steps are addressed by its id.
30
+ */
31
+ export declare function createCart(options: CreateCartOptions): {
32
+ readonly cookie: {
33
+ readonly name: "cart_token";
34
+ readonly attributes: (isProduction?: boolean) => CartCookieAttributes;
35
+ /**
36
+ * The client mints the token (the server accepts any sufficiently-random
37
+ * bearer key and creates the cart row on first use).
38
+ */
39
+ readonly mint: () => string;
40
+ /** Tolerant read: an absent or garbage cookie means "no cart yet". */
41
+ readonly parse: (raw: string | undefined) => string | null;
42
+ };
43
+ /** Null when the token has no cart yet — a new visitor, not an error. */
44
+ readonly get: (cartToken: string) => Promise<Order | null>;
45
+ readonly addItem: (input: AddCartItemInput) => Promise<CartResponse>;
46
+ readonly updateItem: (itemId: string, cartToken: string, quantity: number) => Promise<CartResponse>;
47
+ readonly removeItem: (itemId: string, cartToken: string) => Promise<CartResponse>;
48
+ readonly clear: (cartToken: string) => Promise<CartResponse>;
49
+ /**
50
+ * Call in the same Server Action that sets the session cookie: the guest's
51
+ * cart follows the customer into their account instead of evaporating at
52
+ * the sign-in door.
53
+ */
54
+ readonly mergeOnSignIn: (guestCartToken: string, customerCartToken: string) => Promise<CartResponse>;
55
+ /** Checkout steps, addressed by the order the cart became. */
56
+ readonly checkout: {
57
+ readonly options: (orderId: string, cartToken: string) => Promise<CheckoutOptions>;
58
+ readonly status: (orderId: string, params?: ChannelCheckoutStatusParams) => Promise<CheckoutStatusResponse>;
59
+ readonly setCustomer: (orderId: string, input: CheckoutCustomerInput) => Promise<CartResponse>;
60
+ readonly setAddresses: (orderId: string, input: CheckoutAddressesInput) => Promise<CartResponse>;
61
+ readonly setFulfillment: (orderId: string, input: CheckoutFulfillmentInput) => Promise<CartResponse>;
62
+ /**
63
+ * Returns the Stripe-hosted redirect URL. `return_url` is REQUIRED for a
64
+ * channel checkout (our API's host means nothing to your shopper) and
65
+ * must be on the channel's registered site_url — the server refuses
66
+ * anything else, because an unchecked return URL is an open redirect.
67
+ */
68
+ readonly pay: (orderId: string, input: CheckoutPayInput & {
69
+ return_url: string;
70
+ }) => Promise<CheckoutPayResponse>;
71
+ };
72
+ };
73
+ export type CartKit = ReturnType<typeof createCart>;
74
+ export {};
@@ -0,0 +1,85 @@
1
+ import "server-only";
2
+ import { createChannelClient } from "./index.js";
3
+ function inProduction() {
4
+ return typeof process !== "undefined" && process?.env?.NODE_ENV === "production";
5
+ }
6
+ /** Carts live as long as sessions do; an abandoned cart is cleaned server-side. */
7
+ const CART_MAX_AGE_SECONDS = 60 * 60 * 24 * 30;
8
+ export const cartCookie = {
9
+ name: "cart_token",
10
+ attributes(isProduction = inProduction()) {
11
+ return { httpOnly: true, secure: isProduction, sameSite: "lax", path: "/", maxAge: CART_MAX_AGE_SECONDS };
12
+ },
13
+ /**
14
+ * The client mints the token (the server accepts any sufficiently-random
15
+ * bearer key and creates the cart row on first use).
16
+ */
17
+ mint() {
18
+ return globalThis.crypto.randomUUID();
19
+ },
20
+ /** Tolerant read: an absent or garbage cookie means "no cart yet". */
21
+ parse(raw) {
22
+ const trimmed = raw?.trim() ?? "";
23
+ if (!trimmed || trimmed.length > 120)
24
+ return null;
25
+ return trimmed;
26
+ },
27
+ };
28
+ /**
29
+ * Cart + checkout, with the token threading done for you. Every method returns
30
+ * the cart's underlying ORDER — checkout steps are addressed by its id.
31
+ */
32
+ export function createCart(options) {
33
+ const resolve = typeof options.client === "function" ? options.client : () => options.client;
34
+ return {
35
+ cookie: cartCookie,
36
+ /** Null when the token has no cart yet — a new visitor, not an error. */
37
+ async get(cartToken) {
38
+ try {
39
+ const { order } = await resolve().cart.get(cartToken);
40
+ return order ?? null;
41
+ }
42
+ catch {
43
+ return null;
44
+ }
45
+ },
46
+ async addItem(input) {
47
+ return resolve().cart.addItem(input);
48
+ },
49
+ async updateItem(itemId, cartToken, quantity) {
50
+ return resolve().cart.updateItem(itemId, { cart_token: cartToken, quantity });
51
+ },
52
+ async removeItem(itemId, cartToken) {
53
+ return resolve().cart.removeItem(itemId, cartToken);
54
+ },
55
+ async clear(cartToken) {
56
+ return resolve().cart.clear(cartToken);
57
+ },
58
+ /**
59
+ * Call in the same Server Action that sets the session cookie: the guest's
60
+ * cart follows the customer into their account instead of evaporating at
61
+ * the sign-in door.
62
+ */
63
+ async mergeOnSignIn(guestCartToken, customerCartToken) {
64
+ return resolve().cart.merge({
65
+ source_cart_token: guestCartToken,
66
+ target_cart_token: customerCartToken,
67
+ });
68
+ },
69
+ /** Checkout steps, addressed by the order the cart became. */
70
+ checkout: {
71
+ options: (orderId, cartToken) => resolve().checkout.options(orderId, cartToken),
72
+ status: (orderId, params) => resolve().checkout.status(orderId, params),
73
+ setCustomer: (orderId, input) => resolve().checkout.setCustomer(orderId, input),
74
+ setAddresses: (orderId, input) => resolve().checkout.setAddresses(orderId, input),
75
+ setFulfillment: (orderId, input) => resolve().checkout.setFulfillment(orderId, input),
76
+ /**
77
+ * Returns the Stripe-hosted redirect URL. `return_url` is REQUIRED for a
78
+ * channel checkout (our API's host means nothing to your shopper) and
79
+ * must be on the channel's registered site_url — the server refuses
80
+ * anything else, because an unchecked return URL is an open redirect.
81
+ */
82
+ pay: (orderId, input) => resolve().checkout.pay(orderId, input, { idempotencyKey: `pay:${orderId}` }),
83
+ },
84
+ };
85
+ }
@@ -0,0 +1,109 @@
1
+ import "server-only";
2
+ import { createChannelClient } from "./index.js";
3
+ /** What the session cookie holds. `expiresAt` is the ACCESS token's expiry. */
4
+ export interface SessionTokens {
5
+ accessToken: string;
6
+ refreshToken: string;
7
+ expiresAt: string;
8
+ }
9
+ /** A signed-in customer, normalized for rendering. */
10
+ export interface SessionCustomer {
11
+ id: string;
12
+ email: string;
13
+ name: string;
14
+ }
15
+ export interface SessionCookieAttributes {
16
+ httpOnly: true;
17
+ secure: boolean;
18
+ sameSite: "lax";
19
+ path: "/";
20
+ maxAge: number;
21
+ }
22
+ /**
23
+ * The one definition of the session cookie. A second definition is how a cookie
24
+ * ends up readable on one path and not another.
25
+ */
26
+ export declare const sessionCookie: {
27
+ readonly name: "c1m_session";
28
+ readonly attributes: (isProduction?: boolean) => SessionCookieAttributes;
29
+ readonly serialize: (tokens: SessionTokens) => string;
30
+ /**
31
+ * A cookie is attacker-controlled input: truncated, stale-shaped, or
32
+ * hand-written. Anything unreadable is "not signed in", never a crash.
33
+ */
34
+ readonly parse: (raw: string | undefined) => SessionTokens | null;
35
+ readonly needsRefresh: (tokens: SessionTokens, now?: number) => boolean;
36
+ };
37
+ export type RequestCodeOutcome = {
38
+ state: "sent";
39
+ } | {
40
+ state: "failed";
41
+ };
42
+ export type SignInOutcome = {
43
+ state: "signed-in";
44
+ customer: SessionCustomer;
45
+ tokens: SessionTokens;
46
+ /** Ready to hand to cookies().set(...) — name, value, attributes. */
47
+ cookie: {
48
+ name: string;
49
+ value: string;
50
+ attributes: SessionCookieAttributes;
51
+ };
52
+ } | {
53
+ state: "invalid-code";
54
+ } | {
55
+ state: "failed";
56
+ };
57
+ /**
58
+ * What to do with the session cookie after a refresh attempt.
59
+ *
60
+ * `keep` and `clear` are NOT interchangeable. Clearing when the customer merely
61
+ * lost a race with their own second tab discards the fresh token that tab just
62
+ * stored — logging them out of a live session. The server keeps the token
63
+ * family alive for a short rotation grace window and reports the loser as
64
+ * `refresh_contested` precisely so clients can tell the two apart.
65
+ */
66
+ export type SessionRefreshResult = {
67
+ action: "keep";
68
+ } | {
69
+ action: "write";
70
+ value: string;
71
+ attributes: SessionCookieAttributes;
72
+ } | {
73
+ action: "clear";
74
+ };
75
+ type SessionClient = Pick<ReturnType<typeof createChannelClient>, "auth" | "withCustomer">;
76
+ export interface CreateCustomerSessionOptions {
77
+ /** The channel client, or a lazy resolver (the singleton pattern). */
78
+ client: SessionClient | (() => SessionClient);
79
+ }
80
+ /**
81
+ * The session surface a site actually needs, mapped to intentional outcomes —
82
+ * a route renders "that code was wrong" without ever seeing an HTTP status.
83
+ */
84
+ export declare function createCustomerSession(options: CreateCustomerSessionOptions): {
85
+ readonly cookie: {
86
+ readonly name: "c1m_session";
87
+ readonly attributes: (isProduction?: boolean) => SessionCookieAttributes;
88
+ readonly serialize: (tokens: SessionTokens) => string;
89
+ /**
90
+ * A cookie is attacker-controlled input: truncated, stale-shaped, or
91
+ * hand-written. Anything unreadable is "not signed in", never a crash.
92
+ */
93
+ readonly parse: (raw: string | undefined) => SessionTokens | null;
94
+ readonly needsRefresh: (tokens: SessionTokens, now?: number) => boolean;
95
+ };
96
+ readonly requestCode: (email: string) => Promise<RequestCodeOutcome>;
97
+ readonly signIn: (email: string, code: string) => Promise<SignInOutcome>;
98
+ /**
99
+ * Decide what this request should do to the session cookie. Designed to be
100
+ * the whole body of proxy.ts.
101
+ */
102
+ readonly refresh: (raw: string | undefined) => Promise<SessionRefreshResult>;
103
+ /** Who is signed in, or null. Never throws — a broken cookie is "signed out". */
104
+ readonly getCustomer: (raw: string | undefined) => Promise<SessionCustomer | null>;
105
+ /** Best-effort server logout; the caller clears the cookie REGARDLESS. */
106
+ readonly signOut: (raw: string | undefined) => Promise<void>;
107
+ };
108
+ export type CustomerSessionKit = ReturnType<typeof createCustomerSession>;
109
+ export {};
@@ -0,0 +1,197 @@
1
+ import "server-only";
2
+ import { ChannelAPIError, createChannelClient } from "./index.js";
3
+ function inProduction() {
4
+ return typeof process !== "undefined" && process?.env?.NODE_ENV === "production";
5
+ }
6
+ /** Match the refresh token's life (~30 days), not the access token's (~15 min). */
7
+ const MAX_AGE_SECONDS = 60 * 60 * 24 * 30;
8
+ /** Refresh slightly BEFORE expiry: a token that dies mid-render fails the request it was meant to serve. */
9
+ const REFRESH_SKEW_MS = 60_000;
10
+ /**
11
+ * The one definition of the session cookie. A second definition is how a cookie
12
+ * ends up readable on one path and not another.
13
+ */
14
+ export const sessionCookie = {
15
+ name: "c1m_session",
16
+ attributes(isProduction = inProduction()) {
17
+ return {
18
+ // Never readable from JavaScript: an XSS bug must not become a stolen session.
19
+ httpOnly: true,
20
+ secure: isProduction,
21
+ // Lax, not Strict: the session must survive a customer arriving from an
22
+ // emailed link. Not None — that would ship the cookie cross-site.
23
+ sameSite: "lax",
24
+ path: "/",
25
+ maxAge: MAX_AGE_SECONDS,
26
+ };
27
+ },
28
+ serialize(tokens) {
29
+ return JSON.stringify(tokens);
30
+ },
31
+ /**
32
+ * A cookie is attacker-controlled input: truncated, stale-shaped, or
33
+ * hand-written. Anything unreadable is "not signed in", never a crash.
34
+ */
35
+ parse(raw) {
36
+ if (!raw)
37
+ return null;
38
+ try {
39
+ const parsed = JSON.parse(raw);
40
+ if (!parsed || typeof parsed !== "object")
41
+ return null;
42
+ const { accessToken, refreshToken, expiresAt } = parsed;
43
+ if (typeof accessToken !== "string" || !accessToken)
44
+ return null;
45
+ if (typeof refreshToken !== "string" || !refreshToken)
46
+ return null;
47
+ if (typeof expiresAt !== "string" || !expiresAt)
48
+ return null;
49
+ return { accessToken, refreshToken, expiresAt };
50
+ }
51
+ catch {
52
+ return null;
53
+ }
54
+ },
55
+ needsRefresh(tokens, now = Date.now()) {
56
+ const expiresAt = Date.parse(tokens.expiresAt);
57
+ // Unparseable expiry: refresh and find out, rather than trusting it forever.
58
+ if (Number.isNaN(expiresAt))
59
+ return true;
60
+ return expiresAt - now <= REFRESH_SKEW_MS;
61
+ },
62
+ };
63
+ /** The server's code for "another request rotated this token moments ago". */
64
+ const CONTESTED = "refresh_contested";
65
+ /**
66
+ * Structural, not instanceof: a published package can be instantiated twice in
67
+ * one process (pnpm strictness, bundler duplication, test transforms), and
68
+ * `instanceof` across instances silently fails — which here would misclassify a
69
+ * DEAD session as a transient wobble and keep a corpse cookie forever.
70
+ */
71
+ function asChannelAPIError(error) {
72
+ if (error instanceof ChannelAPIError)
73
+ return error;
74
+ if (typeof error === "object" && error !== null &&
75
+ error.name === "ChannelAPIError" &&
76
+ typeof error.status === "number" &&
77
+ typeof error.code === "string") {
78
+ return error;
79
+ }
80
+ return null;
81
+ }
82
+ function normalizeCustomer(customer) {
83
+ return {
84
+ id: customer.id,
85
+ email: customer.email,
86
+ name: customer.name?.trim() || customer.email,
87
+ };
88
+ }
89
+ function toTokens(session) {
90
+ return {
91
+ accessToken: session.access_token,
92
+ refreshToken: session.refresh_token,
93
+ expiresAt: session.expires_at,
94
+ };
95
+ }
96
+ /**
97
+ * The session surface a site actually needs, mapped to intentional outcomes —
98
+ * a route renders "that code was wrong" without ever seeing an HTTP status.
99
+ */
100
+ export function createCustomerSession(options) {
101
+ const resolve = typeof options.client === "function" ? options.client : () => options.client;
102
+ return {
103
+ cookie: sessionCookie,
104
+ async requestCode(email) {
105
+ try {
106
+ await resolve().auth.sendCode(email);
107
+ return { state: "sent" };
108
+ }
109
+ catch {
110
+ return { state: "failed" };
111
+ }
112
+ },
113
+ async signIn(email, code) {
114
+ try {
115
+ const session = await resolve().auth.verifyCode({ email, code });
116
+ const tokens = toTokens(session);
117
+ return {
118
+ state: "signed-in",
119
+ customer: normalizeCustomer(session.end_user),
120
+ tokens,
121
+ cookie: {
122
+ name: sessionCookie.name,
123
+ value: sessionCookie.serialize(tokens),
124
+ attributes: sessionCookie.attributes(),
125
+ },
126
+ };
127
+ }
128
+ catch (error) {
129
+ // A wrong code is an ordinary thing a person does, not a failure.
130
+ const api = asChannelAPIError(error);
131
+ if (api && (api.status === 401 || api.status === 400)) {
132
+ return { state: "invalid-code" };
133
+ }
134
+ return { state: "failed" };
135
+ }
136
+ },
137
+ /**
138
+ * Decide what this request should do to the session cookie. Designed to be
139
+ * the whole body of proxy.ts.
140
+ */
141
+ async refresh(raw) {
142
+ const session = sessionCookie.parse(raw);
143
+ if (!session)
144
+ return { action: "keep" };
145
+ if (!sessionCookie.needsRefresh(session))
146
+ return { action: "keep" };
147
+ try {
148
+ const rotated = await resolve().auth.refresh(session.refreshToken);
149
+ return {
150
+ action: "write",
151
+ value: sessionCookie.serialize(toTokens(rotated)),
152
+ attributes: sessionCookie.attributes(),
153
+ };
154
+ }
155
+ catch (error) {
156
+ const api = asChannelAPIError(error);
157
+ if (api) {
158
+ // Lost a race with the customer's own other tab: the session is alive
159
+ // and that tab already stored a good token. KEEP the cookie.
160
+ if (api.code === CONTESTED)
161
+ return { action: "keep" };
162
+ // Genuinely dead — logged out, revoked, or aged out. Clear it.
163
+ if (api.status === 401)
164
+ return { action: "clear" };
165
+ }
166
+ // An upstream wobble is not evidence anyone's session is dead.
167
+ return { action: "keep" };
168
+ }
169
+ },
170
+ /** Who is signed in, or null. Never throws — a broken cookie is "signed out". */
171
+ async getCustomer(raw) {
172
+ const session = sessionCookie.parse(raw);
173
+ if (!session)
174
+ return null;
175
+ try {
176
+ const { end_user } = await resolve().withCustomer(session.accessToken).me();
177
+ return normalizeCustomer(end_user);
178
+ }
179
+ catch {
180
+ return null;
181
+ }
182
+ },
183
+ /** Best-effort server logout; the caller clears the cookie REGARDLESS. */
184
+ async signOut(raw) {
185
+ const session = sessionCookie.parse(raw);
186
+ if (!session)
187
+ return;
188
+ try {
189
+ await resolve().withCustomer(session.accessToken).logout();
190
+ }
191
+ catch {
192
+ // A customer who clicks "sign out" must end up signed out of this
193
+ // browser even if the API is down.
194
+ }
195
+ },
196
+ };
197
+ }
@@ -0,0 +1,52 @@
1
+ import "server-only";
2
+ import { type ChannelWebhookEvent, type ChannelWebhookEventDataMap } from "./webhooks.js";
3
+ /**
4
+ * Webhook route factory: the whole app/api/webhooks/c1m/route.ts in one call.
5
+ *
6
+ * import { revalidatePath, revalidateTag } from "next/cache";
7
+ * export const POST = createChannelWebhookRoute({
8
+ * secret: () => process.env.C1M_CHANNEL_WEBHOOK_SECRET!,
9
+ * invalidate: { revalidatePath, revalidateTag },
10
+ * });
11
+ *
12
+ * The invalidator is injected rather than imported here on purpose: it keeps
13
+ * this module free of `next` (bundler-safe, unit-testable with a fake), and it
14
+ * is the app's two-line import — not eighty lines of verification, dispatch,
15
+ * path-safety and error-mapping boilerplate.
16
+ */
17
+ /** The cache tag every anonymous site read is filed under. */
18
+ export declare const CHANNEL_SITE_CACHE_TAG = "channel:site";
19
+ export interface ChannelCacheInvalidator {
20
+ revalidatePath(path: string): void;
21
+ revalidateTag(tag: string): void;
22
+ }
23
+ export interface ChannelWebhookRouteLogger {
24
+ info(message: string, context?: Record<string, unknown>): void;
25
+ warn(message: string, context?: Record<string, unknown>): void;
26
+ error(message: string, context?: Record<string, unknown>): void;
27
+ }
28
+ export type ChannelWebhookHandlers = {
29
+ [T in keyof ChannelWebhookEventDataMap]?: (event: ChannelWebhookEvent<T>, invalidate: ChannelCacheInvalidator) => void | Promise<void>;
30
+ };
31
+ export interface CreateChannelWebhookRouteOptions {
32
+ /** The whsec_ signing secret, or a lazy resolver (resolved per request so builds without env pass). */
33
+ secret: string | (() => string);
34
+ /** Next's cache invalidation, injected: `{ revalidatePath, revalidateTag }` from next/cache. */
35
+ invalidate: ChannelCacheInvalidator;
36
+ /**
37
+ * Per-event handlers. A handler REPLACES the built-in behavior for that type;
38
+ * types without a handler get the default (page.published revalidates the
39
+ * site tag + the published path; everything else is acknowledged and ignored
40
+ * — delivery is at-least-once, so an unhandled event must still 204 or the
41
+ * server will retry it for hours).
42
+ */
43
+ onEvent?: ChannelWebhookHandlers;
44
+ logger?: ChannelWebhookRouteLogger;
45
+ }
46
+ /**
47
+ * A route_pattern arrives from the network; it is input, not truth. Reject
48
+ * anything that is not a plain absolute path before handing it to the cache.
49
+ */
50
+ export declare function safePublishedPath(path: string): string | undefined;
51
+ /** Build the POST handler for the channel webhook endpoint. */
52
+ export declare function createChannelWebhookRoute(options: CreateChannelWebhookRouteOptions): (request: Request) => Promise<Response>;
@@ -0,0 +1,92 @@
1
+ import "server-only";
2
+ import { ChannelWebhookVerificationError, parseChannelWebhookEvent, } from "./webhooks.js";
3
+ /**
4
+ * Webhook route factory: the whole app/api/webhooks/c1m/route.ts in one call.
5
+ *
6
+ * import { revalidatePath, revalidateTag } from "next/cache";
7
+ * export const POST = createChannelWebhookRoute({
8
+ * secret: () => process.env.C1M_CHANNEL_WEBHOOK_SECRET!,
9
+ * invalidate: { revalidatePath, revalidateTag },
10
+ * });
11
+ *
12
+ * The invalidator is injected rather than imported here on purpose: it keeps
13
+ * this module free of `next` (bundler-safe, unit-testable with a fake), and it
14
+ * is the app's two-line import — not eighty lines of verification, dispatch,
15
+ * path-safety and error-mapping boilerplate.
16
+ */
17
+ /** The cache tag every anonymous site read is filed under. */
18
+ export const CHANNEL_SITE_CACHE_TAG = "channel:site";
19
+ /**
20
+ * A route_pattern arrives from the network; it is input, not truth. Reject
21
+ * anything that is not a plain absolute path before handing it to the cache.
22
+ */
23
+ export function safePublishedPath(path) {
24
+ const normalized = path.trim();
25
+ if (!normalized.startsWith("/") || normalized.startsWith("//") || normalized.length > 1024) {
26
+ return undefined;
27
+ }
28
+ return normalized;
29
+ }
30
+ /** Structural, not instanceof — see the session kit for why. */
31
+ function isVerificationError(error) {
32
+ if (error instanceof ChannelWebhookVerificationError)
33
+ return true;
34
+ return (typeof error === "object" && error !== null &&
35
+ error.name === "ChannelWebhookVerificationError" &&
36
+ typeof error.code === "string");
37
+ }
38
+ function defaultBehavior(event, invalidate) {
39
+ if (event.type !== "page.published")
40
+ return undefined;
41
+ const path = safePublishedPath(event.data.route_pattern);
42
+ if (!path)
43
+ throw new Error("page.published contains an invalid route_pattern");
44
+ invalidate.revalidateTag(CHANNEL_SITE_CACHE_TAG);
45
+ invalidate.revalidatePath(path);
46
+ return path;
47
+ }
48
+ /** Build the POST handler for the channel webhook endpoint. */
49
+ export function createChannelWebhookRoute(options) {
50
+ const logger = options.logger ?? console;
51
+ const resolveSecret = typeof options.secret === "function" ? options.secret : () => options.secret;
52
+ return async (request) => {
53
+ let event;
54
+ try {
55
+ event = await parseChannelWebhookEvent(request, { secret: resolveSecret() });
56
+ }
57
+ catch (error) {
58
+ if (isVerificationError(error)) {
59
+ // An unverifiable request is noise or an attack; log the code, say
60
+ // nothing useful back.
61
+ logger.warn("channel_webhook_rejected", { code: error.code });
62
+ return Response.json({ code: "invalid_channel_webhook" }, { status: 401 });
63
+ }
64
+ logger.error("channel_webhook_failed", { error });
65
+ return Response.json({ code: "channel_webhook_failed" }, { status: 500 });
66
+ }
67
+ try {
68
+ const handler = options.onEvent?.[event.type];
69
+ let revalidatedPath;
70
+ if (handler) {
71
+ await handler(event, options.invalidate);
72
+ }
73
+ else {
74
+ revalidatedPath = defaultBehavior(event, options.invalidate);
75
+ }
76
+ logger.info("channel_webhook_processed", {
77
+ eventId: event.id,
78
+ eventType: event.type,
79
+ ...(revalidatedPath ? { revalidatedPath } : {}),
80
+ });
81
+ return new Response(null, { status: 204 });
82
+ }
83
+ catch (error) {
84
+ // A handler failure is OURS: the signature verified, the event is real.
85
+ // A 500 makes the server retry on its ladder — which is what you want
86
+ // when the failure is transient, and visible in delivery history when
87
+ // it is not.
88
+ logger.error("channel_webhook_failed", { eventId: event.id, eventType: event.type, error });
89
+ return Response.json({ code: "channel_webhook_failed" }, { status: 500 });
90
+ }
91
+ };
92
+ }
package/dist/next.d.ts CHANGED
@@ -46,12 +46,12 @@ export declare function createNextChannelClient(options: CreateNextChannelClient
46
46
  readonly merge: (input: import("./types.js").MergeCartInput, mutation?: import("./index.js").ChannelMutationOptions) => Promise<import("./types.js").CartResponse>;
47
47
  };
48
48
  readonly checkout: {
49
- readonly options: (cartToken: string) => Promise<import("./types.js").CheckoutOptions>;
50
- readonly status: (params?: import("./index.js").ChannelCheckoutStatusParams) => Promise<import("./types.js").CheckoutStatusResponse>;
51
- readonly setCustomer: (input: import("./types.js").CheckoutCustomerInput, mutation?: import("./index.js").ChannelMutationOptions) => Promise<import("./types.js").CartResponse>;
52
- readonly setAddresses: (input: import("./types.js").CheckoutAddressesInput, mutation?: import("./index.js").ChannelMutationOptions) => Promise<import("./types.js").CartResponse>;
53
- readonly setFulfillment: (input: import("./types.js").CheckoutFulfillmentInput, mutation?: import("./index.js").ChannelMutationOptions) => Promise<import("./types.js").CartResponse>;
54
- readonly pay: (input: import("./types.js").CheckoutPayInput, mutation?: import("./index.js").ChannelMutationOptions) => Promise<import("./types.js").CheckoutPayResponse>;
49
+ readonly options: (orderId: string, cartToken: string) => Promise<import("./types.js").CheckoutOptions>;
50
+ readonly status: (orderId: string, params?: import("./index.js").ChannelCheckoutStatusParams) => Promise<import("./types.js").CheckoutStatusResponse>;
51
+ readonly setCustomer: (orderId: string, input: import("./types.js").CheckoutCustomerInput, mutation?: import("./index.js").ChannelMutationOptions) => Promise<import("./types.js").CartResponse>;
52
+ readonly setAddresses: (orderId: string, input: import("./types.js").CheckoutAddressesInput, mutation?: import("./index.js").ChannelMutationOptions) => Promise<import("./types.js").CartResponse>;
53
+ readonly setFulfillment: (orderId: string, input: import("./types.js").CheckoutFulfillmentInput, mutation?: import("./index.js").ChannelMutationOptions) => Promise<import("./types.js").CartResponse>;
54
+ readonly pay: (orderId: string, input: import("./types.js").CheckoutPayInput, mutation?: import("./index.js").ChannelMutationOptions) => Promise<import("./types.js").CheckoutPayResponse>;
55
55
  };
56
56
  readonly reviews: {
57
57
  readonly list: (params?: import("./index.js").ChannelListParams) => Promise<import("./types.js").ListResponse<import("./types.js").Review>>;
@@ -110,3 +110,6 @@ export declare function createNextChannelClient(options: CreateNextChannelClient
110
110
  }>;
111
111
  };
112
112
  };
113
+ export * from "./next-session.js";
114
+ export * from "./next-webhooks.js";
115
+ export * from "./next-cart.js";
package/dist/next.js CHANGED
@@ -38,3 +38,10 @@ export function createNextChannelClient(options) {
38
38
  };
39
39
  return createChannelClient({ ...coreOptions, fetch: nextFetch });
40
40
  }
41
+ // The kits: the ~600 lines of plumbing every headless site was copy-pasting —
42
+ // session cookie + refresh decision, the webhook route, the cart's token
43
+ // threading — shipped once, injection-shaped, framework-honest (no `next`
44
+ // imports; apps pass next/cache + apply cookies where Next allows writes).
45
+ export * from "./next-session.js";
46
+ export * from "./next-webhooks.js";
47
+ export * from "./next-cart.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@c1m-public/channel-client",
3
- "version": "0.5.0",
3
+ "version": "0.6.0",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "description": "Typed server-side client for the MML headless Channel API",