@c1m-public/channel-client 0.5.0 → 0.8.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 +67 -5
- package/dist/index.d.ts +44 -10
- package/dist/index.js +92 -10
- package/dist/next-cart.d.ts +76 -0
- package/dist/next-cart.js +87 -0
- package/dist/next-session.d.ts +109 -0
- package/dist/next-session.js +178 -0
- package/dist/next-webhooks.d.ts +58 -0
- package/dist/next-webhooks.js +112 -0
- package/dist/next.d.ts +34 -6
- package/dist/next.js +7 -0
- package/dist/types.d.ts +314 -0
- package/dist/webhooks.d.ts +42 -2
- package/dist/webhooks.js +61 -2
- package/package.json +1 -1
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
|
-
|
|
34
|
-
|
|
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). One key belongs to one logical payment attempt. Keep it stable
|
|
36
|
+
// while retrying that attempt; mint a new key after a correctable checkout
|
|
37
|
+
// failure so the server does not replay the old 4xx response.
|
|
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:
|
|
41
|
+
{ idempotencyKey: paymentAttemptId },
|
|
39
42
|
);
|
|
40
43
|
```
|
|
41
44
|
|
|
@@ -66,6 +69,8 @@ other runtimes must enforce their own server-module boundary.
|
|
|
66
69
|
continues to resolve tenant and workspace identity at the API door.
|
|
67
70
|
- Requests time out after 10 seconds by default.
|
|
68
71
|
- API failures throw `ChannelAPIError` with safe status, code, and request ID.
|
|
72
|
+
- Use `isChannelAPIError(error)` instead of `instanceof`; it remains correct
|
|
73
|
+
when a server bundle contains more than one package instance.
|
|
69
74
|
- Assets remain tokenless and are normalized with `assetUrl()`.
|
|
70
75
|
- `observe` can receive one bounded telemetry event per logical request. Events
|
|
71
76
|
contain operation, outcome, status, request ID, duration and attempt count;
|
|
@@ -115,3 +120,60 @@ Publishing runs through npm Trusted Publishing and GitHub OIDC. Push a protected
|
|
|
115
120
|
`channel-client-vX.Y.Z` tag matching `package.json`; the workflow verifies,
|
|
116
121
|
packs, and publishes without a stored npm token. Published versions are
|
|
117
122
|
immutable, so increment the package version for every release.
|
|
123
|
+
|
|
124
|
+
## The `/next` kits
|
|
125
|
+
|
|
126
|
+
The ~600 lines of plumbing every headless site was copy-pasting, shipped once.
|
|
127
|
+
No `next` imports — apps inject `next/cache` and apply cookies where Next allows
|
|
128
|
+
writes (a Server Component cannot write cookies; proxy.ts and Server Actions can).
|
|
129
|
+
|
|
130
|
+
```ts
|
|
131
|
+
// app/api/webhooks/c1m/route.ts — the whole file
|
|
132
|
+
import { revalidatePath, revalidateTag } from "next/cache";
|
|
133
|
+
import { createChannelWebhookRoute } from "@c1m-public/channel-client/next";
|
|
134
|
+
|
|
135
|
+
export const POST = createChannelWebhookRoute({
|
|
136
|
+
secret: () => process.env.C1M_CHANNEL_WEBHOOK_SECRET!,
|
|
137
|
+
invalidate: { revalidatePath, revalidateTag },
|
|
138
|
+
});
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
Out of the box that route keeps your cache honest with no configuration:
|
|
142
|
+
`page.published` revalidates the published path plus `CHANNEL_SITE_CACHE_TAG`,
|
|
143
|
+
and every `product.*` event revalidates `CHANNEL_CATALOG_CACHE_TAG`. Tag your
|
|
144
|
+
catalog reads with it and a merchant's price edit reaches the storefront on the
|
|
145
|
+
next request instead of at the end of a TTL — the difference between a correct
|
|
146
|
+
price and a stale one at checkout.
|
|
147
|
+
|
|
148
|
+
```ts
|
|
149
|
+
// A client whose reads are filed under the catalog tag the webhook route busts.
|
|
150
|
+
const catalog = createNextChannelClient({
|
|
151
|
+
baseUrl: process.env.C1M_API_URL!,
|
|
152
|
+
token: process.env.C1M_CHANNEL_TOKEN!,
|
|
153
|
+
cache: { revalidate: 3600, tags: [CHANNEL_CATALOG_CACHE_TAG] },
|
|
154
|
+
});
|
|
155
|
+
const products = await catalog.products.list();
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
The core also exposes the complete current channel door: published blog lists,
|
|
159
|
+
giving entries and checkout start, Quick Print settings/quotes/multipart intake,
|
|
160
|
+
and assembled dining menus. `pnpm contract:check` compares the client inventory
|
|
161
|
+
with the canonical server OpenAPI document when both repositories are present.
|
|
162
|
+
|
|
163
|
+
```ts
|
|
164
|
+
// session: cookie codec + the contested-vs-expired refresh decision
|
|
165
|
+
const session = createCustomerSession({ client: getChannelClient });
|
|
166
|
+
const result = await session.refresh(rawCookie); // keep | write | clear
|
|
167
|
+
// `keep` on refresh_contested is the load-bearing case: the customer's other
|
|
168
|
+
// tab already stored a fresh token — clearing would log out a live session.
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
```ts
|
|
172
|
+
// cart: server-side cart, client-held token, hosted checkout
|
|
173
|
+
const cart = createCart({ client: getChannelClient });
|
|
174
|
+
await cart.addItem({ cart_token, product_id, quantity: 1 });
|
|
175
|
+
const { redirect_url } = await cart.checkout.pay(orderId, {
|
|
176
|
+
cart_token,
|
|
177
|
+
return_url: "https://your-site.example/thanks", // must be on the channel's registered site
|
|
178
|
+
}, { idempotencyKey: paymentAttemptId });
|
|
179
|
+
```
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
export * from "./webhooks.js";
|
|
2
|
-
export type
|
|
3
|
-
|
|
2
|
+
export type * from "./types.js";
|
|
3
|
+
export type { BlogPost, BlogPostResponse, DiningMenu, GivingEntry, GivingIntent, AddCartItemInput, CartResponse, CheckoutAddress, CheckoutAddressesInput, CheckoutCustomerInput, CheckoutFulfillmentInput, CheckoutOptions, CheckoutPayInput, CheckoutPayResponse, CheckoutStatus, CheckoutStatusResponse, ChannelPing, Customer, CustomerResponse, CustomerSession, CustomerSignupResponse, LeadResponse, Order, OrderItem, OrderSummary, MergeCartInput, SendCodeResponse, LightInitResponse, ListResponse, Product, ProductAsset, PrintIntakeInput, PrintJob, PrintOptionsSelection, PrintQuoteResponse, PrintSettingsResponse, PublicPage, PublicPageSummary, PublicSubmitReviewInput, PublicWorkspaceInit, Menu, MenuItem, MenuResponse, Review, ReviewSummaryResponse, PaymentMethodOption, PaymentReadiness, ShippingMethodOption, SiteDocument, SiteGatedDocument, SiteResolvedDocument, StartGivingInput, StartGivingResponse, ThemeResponse, UpdateCartItemInput, } from "./types";
|
|
4
|
+
import type { BlogPostResponse, DiningMenu, GivingEntry, 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, SiteDocument, StartGivingInput, StartGivingResponse, ThemeResponse, UpdateCartItemInput } from "./types";
|
|
4
5
|
export interface ChannelRetryPolicy {
|
|
5
6
|
attempts?: number;
|
|
6
7
|
maxDelayMs?: number;
|
|
@@ -12,9 +13,11 @@ export interface CreateChannelClientOptions {
|
|
|
12
13
|
timeoutMs?: number;
|
|
13
14
|
retry?: ChannelRetryPolicy | false;
|
|
14
15
|
observe?: ChannelRequestObserver;
|
|
16
|
+
/** Optional request-scope cancellation signal, combined with the timeout. */
|
|
17
|
+
signal?: AbortSignal;
|
|
15
18
|
}
|
|
16
|
-
export type ChannelRequestOutcome = "success" | "api_error" | "network_error" | "timeout" | "invalid_response";
|
|
17
|
-
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" | "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" | "channel.checkout.addresses" | "channel.checkout.fulfillment" | "channel.checkout.pay" | "growth.public_workspace.leads.capture.channel";
|
|
19
|
+
export type ChannelRequestOutcome = "success" | "api_error" | "network_error" | "timeout" | "invalid_response" | "cancelled";
|
|
20
|
+
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.orders.list" | "channel.account.orders.summary" | "channel.account.orders.get" | "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" | "growth.public_workspace.leads.capture.channel";
|
|
18
21
|
export interface ChannelRequestObservation {
|
|
19
22
|
operation: ChannelOperation;
|
|
20
23
|
method: string;
|
|
@@ -35,6 +38,10 @@ export interface ChannelListParams {
|
|
|
35
38
|
}
|
|
36
39
|
export interface ChannelProductListParams extends ChannelListParams {
|
|
37
40
|
currency?: string;
|
|
41
|
+
search?: string;
|
|
42
|
+
category_id?: string;
|
|
43
|
+
brand_id?: string;
|
|
44
|
+
type_id?: string;
|
|
38
45
|
}
|
|
39
46
|
export interface ChannelSiteResolveParams {
|
|
40
47
|
route?: string;
|
|
@@ -60,6 +67,8 @@ export declare class ChannelAPIError extends Error {
|
|
|
60
67
|
readonly requestId: string;
|
|
61
68
|
constructor(message: string, status: number, code: string, requestId: string);
|
|
62
69
|
}
|
|
70
|
+
/** Works across duplicate package instances and transformed test bundles. */
|
|
71
|
+
export declare function isChannelAPIError(error: unknown): error is ChannelAPIError;
|
|
63
72
|
export declare function createChannelClient(options: CreateChannelClientOptions): {
|
|
64
73
|
/**
|
|
65
74
|
* Verify the channel token and see what it points at.
|
|
@@ -101,12 +110,12 @@ export declare function createChannelClient(options: CreateChannelClientOptions)
|
|
|
101
110
|
readonly merge: (input: MergeCartInput, mutation?: ChannelMutationOptions) => Promise<CartResponse>;
|
|
102
111
|
};
|
|
103
112
|
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>;
|
|
113
|
+
readonly options: (orderId: string, cartToken: string) => Promise<CheckoutOptions>;
|
|
114
|
+
readonly status: (orderId: string, params?: ChannelCheckoutStatusParams) => Promise<CheckoutStatusResponse>;
|
|
115
|
+
readonly setCustomer: (orderId: string, input: CheckoutCustomerInput, mutation?: ChannelMutationOptions) => Promise<CartResponse>;
|
|
116
|
+
readonly setAddresses: (orderId: string, input: CheckoutAddressesInput, mutation?: ChannelMutationOptions) => Promise<CartResponse>;
|
|
117
|
+
readonly setFulfillment: (orderId: string, input: CheckoutFulfillmentInput, mutation?: ChannelMutationOptions) => Promise<CartResponse>;
|
|
118
|
+
readonly pay: (orderId: string, input: CheckoutPayInput, mutation?: ChannelMutationOptions) => Promise<CheckoutPayResponse>;
|
|
110
119
|
};
|
|
111
120
|
readonly reviews: {
|
|
112
121
|
readonly list: (params?: ChannelListParams) => Promise<ListResponse<Review>>;
|
|
@@ -122,8 +131,30 @@ export declare function createChannelClient(options: CreateChannelClientOptions)
|
|
|
122
131
|
readonly get: (handle: string) => Promise<MenuResponse>;
|
|
123
132
|
};
|
|
124
133
|
readonly blog: {
|
|
134
|
+
readonly list: (params?: ChannelListParams) => Promise<ListResponse<import("./types.js").BlogPost>>;
|
|
125
135
|
readonly get: (slug: string) => Promise<BlogPostResponse>;
|
|
126
136
|
};
|
|
137
|
+
readonly giving: {
|
|
138
|
+
readonly entries: {
|
|
139
|
+
readonly list: () => Promise<{
|
|
140
|
+
items: GivingEntry[];
|
|
141
|
+
}>;
|
|
142
|
+
readonly get: (slug: string) => Promise<{
|
|
143
|
+
entry: GivingEntry;
|
|
144
|
+
}>;
|
|
145
|
+
};
|
|
146
|
+
readonly start: (input: StartGivingInput, mutation?: ChannelMutationOptions) => Promise<StartGivingResponse>;
|
|
147
|
+
};
|
|
148
|
+
readonly print: {
|
|
149
|
+
readonly settings: () => Promise<PrintSettingsResponse>;
|
|
150
|
+
readonly quote: (input: PrintOptionsSelection) => Promise<PrintQuoteResponse>;
|
|
151
|
+
readonly intake: (input: PrintIntakeInput, mutation?: ChannelMutationOptions) => Promise<{
|
|
152
|
+
job: PrintJob;
|
|
153
|
+
}>;
|
|
154
|
+
};
|
|
155
|
+
readonly dining: {
|
|
156
|
+
readonly menu: (boardSlug: string) => Promise<DiningMenu>;
|
|
157
|
+
};
|
|
127
158
|
readonly auth: {
|
|
128
159
|
readonly check: (email: string) => Promise<{
|
|
129
160
|
exists: boolean;
|
|
@@ -169,6 +200,9 @@ export declare function createChannelClient(options: CreateChannelClientOptions)
|
|
|
169
200
|
order: Order;
|
|
170
201
|
}>;
|
|
171
202
|
};
|
|
203
|
+
readonly giving: {
|
|
204
|
+
readonly start: (input: StartGivingInput, mutation?: ChannelMutationOptions) => Promise<StartGivingResponse>;
|
|
205
|
+
};
|
|
172
206
|
};
|
|
173
207
|
readonly leads: {
|
|
174
208
|
readonly create: (input: ChannelLeadInput, mutation?: ChannelMutationOptions) => Promise<{
|
package/dist/index.js
CHANGED
|
@@ -13,6 +13,15 @@ export class ChannelAPIError extends Error {
|
|
|
13
13
|
this.name = "ChannelAPIError";
|
|
14
14
|
}
|
|
15
15
|
}
|
|
16
|
+
/** Works across duplicate package instances and transformed test bundles. */
|
|
17
|
+
export function isChannelAPIError(error) {
|
|
18
|
+
return (error instanceof ChannelAPIError ||
|
|
19
|
+
(typeof error === "object" && error !== null &&
|
|
20
|
+
error.name === "ChannelAPIError" &&
|
|
21
|
+
typeof error.status === "number" &&
|
|
22
|
+
typeof error.code === "string" &&
|
|
23
|
+
typeof error.requestId === "string"));
|
|
24
|
+
}
|
|
16
25
|
function required(value, label) {
|
|
17
26
|
const normalized = value.trim();
|
|
18
27
|
if (!normalized)
|
|
@@ -49,6 +58,17 @@ function retryDelay(response, maxDelayMs) {
|
|
|
49
58
|
function wait(ms) {
|
|
50
59
|
return ms <= 0 ? Promise.resolve() : new Promise((resolve) => setTimeout(resolve, ms));
|
|
51
60
|
}
|
|
61
|
+
function combineSignals(...signals) {
|
|
62
|
+
const active = signals.filter((signal) => Boolean(signal));
|
|
63
|
+
if (active.length === 0)
|
|
64
|
+
return undefined;
|
|
65
|
+
if (active.length === 1)
|
|
66
|
+
return active[0];
|
|
67
|
+
return AbortSignal.any(active);
|
|
68
|
+
}
|
|
69
|
+
function isFormDataBody(body) {
|
|
70
|
+
return typeof FormData !== "undefined" && body instanceof FormData;
|
|
71
|
+
}
|
|
52
72
|
export function createChannelClient(options) {
|
|
53
73
|
const baseUrl = required(options.baseUrl, "baseUrl").replace(/\/+$/, "");
|
|
54
74
|
const token = required(options.token, "token");
|
|
@@ -79,8 +99,9 @@ export function createChannelClient(options) {
|
|
|
79
99
|
headers.set("Authorization", `Bearer ${token}`);
|
|
80
100
|
if (session)
|
|
81
101
|
headers.set("X-End-User-Token", session);
|
|
82
|
-
if (init.body !== undefined && !headers.has("Content-Type"))
|
|
102
|
+
if (init.body !== undefined && !isFormDataBody(init.body) && !headers.has("Content-Type")) {
|
|
83
103
|
headers.set("Content-Type", "application/json");
|
|
104
|
+
}
|
|
84
105
|
const requestInit = { ...init, method, headers };
|
|
85
106
|
// Private reads and every mutation are non-cacheable in every runtime. An
|
|
86
107
|
// adapter may add framework caching only to anonymous GET requests.
|
|
@@ -94,14 +115,25 @@ export function createChannelClient(options) {
|
|
|
94
115
|
const controller = new AbortController();
|
|
95
116
|
const timeout = setTimeout(() => controller.abort(), timeoutMs);
|
|
96
117
|
try {
|
|
97
|
-
response = await fetcher(`${baseUrl}/api/v1/channel${path}`, {
|
|
118
|
+
response = await fetcher(`${baseUrl}/api/v1/channel${path}`, {
|
|
119
|
+
...requestInit,
|
|
120
|
+
signal: combineSignals(options.signal, requestInit.signal, controller.signal),
|
|
121
|
+
});
|
|
98
122
|
}
|
|
99
|
-
catch
|
|
123
|
+
catch {
|
|
100
124
|
if (controller.signal.aborted) {
|
|
101
125
|
outcome = "timeout";
|
|
102
126
|
throw new ChannelAPIError("Channel API request timed out", 0, "channel_request_timeout", "");
|
|
103
127
|
}
|
|
128
|
+
if (options.signal?.aborted || requestInit.signal?.aborted) {
|
|
129
|
+
outcome = "cancelled";
|
|
130
|
+
throw new ChannelAPIError("Channel API request was cancelled", 0, "channel_request_cancelled", "");
|
|
131
|
+
}
|
|
104
132
|
outcome = "network_error";
|
|
133
|
+
if (method === "GET" && attempt < retryAttempts) {
|
|
134
|
+
await wait(Math.min(250, maxRetryDelayMs));
|
|
135
|
+
continue;
|
|
136
|
+
}
|
|
105
137
|
throw new ChannelAPIError("Channel API request failed", 0, "channel_network_error", "");
|
|
106
138
|
}
|
|
107
139
|
finally {
|
|
@@ -122,8 +154,13 @@ export function createChannelClient(options) {
|
|
|
122
154
|
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);
|
|
123
155
|
}
|
|
124
156
|
try {
|
|
125
|
-
const payload = (await response.json());
|
|
126
157
|
outcome = "success";
|
|
158
|
+
if (response.status === 204)
|
|
159
|
+
return undefined;
|
|
160
|
+
const text = await response.text();
|
|
161
|
+
if (!text)
|
|
162
|
+
return undefined;
|
|
163
|
+
const payload = JSON.parse(text);
|
|
127
164
|
return payload;
|
|
128
165
|
}
|
|
129
166
|
catch {
|
|
@@ -193,24 +230,29 @@ export function createChannelClient(options) {
|
|
|
193
230
|
method: "POST", headers: mutationHeaders(mutation), body: JSON.stringify(input),
|
|
194
231
|
}),
|
|
195
232
|
},
|
|
233
|
+
// Checkout is addressed by the ORDER the cart became: the server mounts
|
|
234
|
+
// /checkout/{order_id}/... (the cart is an orders row, and every cart call
|
|
235
|
+
// returns its order.id). 0.5.0 shipped these without the order_id segment,
|
|
236
|
+
// so every checkout call 404'd — the signature change is safe because the
|
|
237
|
+
// old shape never worked.
|
|
196
238
|
checkout: {
|
|
197
|
-
options: (cartToken) => request("channel.checkout.options", appendQuery(
|
|
239
|
+
options: (orderId, cartToken) => request("channel.checkout.options", appendQuery(`/checkout/${encodePath(orderId)}/options`, {
|
|
198
240
|
cart_token: required(cartToken, "cartToken"),
|
|
199
241
|
})),
|
|
200
|
-
status: (params = {}) => request("channel.checkout.status", appendQuery(
|
|
242
|
+
status: (orderId, params = {}) => request("channel.checkout.status", appendQuery(`/checkout/${encodePath(orderId)}/status`, {
|
|
201
243
|
cart_token: params.cartToken,
|
|
202
244
|
checkout_session_id: params.checkoutSessionId,
|
|
203
245
|
})),
|
|
204
|
-
setCustomer: (input, mutation) => request("channel.checkout.customer",
|
|
246
|
+
setCustomer: (orderId, input, mutation) => request("channel.checkout.customer.set", `/checkout/${encodePath(orderId)}/customer`, {
|
|
205
247
|
method: "PUT", headers: mutationHeaders(mutation), body: JSON.stringify(input),
|
|
206
248
|
}),
|
|
207
|
-
setAddresses: (input, mutation) => request("channel.checkout.addresses",
|
|
249
|
+
setAddresses: (orderId, input, mutation) => request("channel.checkout.addresses.set", `/checkout/${encodePath(orderId)}/addresses`, {
|
|
208
250
|
method: "PUT", headers: mutationHeaders(mutation), body: JSON.stringify(input),
|
|
209
251
|
}),
|
|
210
|
-
setFulfillment: (input, mutation) => request("channel.checkout.fulfillment",
|
|
252
|
+
setFulfillment: (orderId, input, mutation) => request("channel.checkout.fulfillment.set", `/checkout/${encodePath(orderId)}/fulfillment`, {
|
|
211
253
|
method: "PUT", headers: mutationHeaders(mutation), body: JSON.stringify(input),
|
|
212
254
|
}),
|
|
213
|
-
pay: (input, mutation) => request("channel.checkout.pay",
|
|
255
|
+
pay: (orderId, input, mutation) => request("channel.checkout.pay", `/checkout/${encodePath(orderId)}/pay`, {
|
|
214
256
|
method: "POST", headers: mutationHeaders(mutation), body: JSON.stringify(input),
|
|
215
257
|
}),
|
|
216
258
|
},
|
|
@@ -228,8 +270,43 @@ export function createChannelClient(options) {
|
|
|
228
270
|
get: (handle) => request("channel.menus.get", `/menus/${encodePath(handle)}`),
|
|
229
271
|
},
|
|
230
272
|
blog: {
|
|
273
|
+
list: (params = {}) => request("channel.blog.list", appendQuery("/blog/posts", params)),
|
|
231
274
|
get: (slug) => request("channel.blog.get", `/blog/posts/${encodePath(slug)}`),
|
|
232
275
|
},
|
|
276
|
+
giving: {
|
|
277
|
+
entries: {
|
|
278
|
+
list: () => request("channel.giving.entries.list", "/giving/entries"),
|
|
279
|
+
get: (slug) => request("channel.giving.entries.get", `/giving/entries/${encodePath(slug)}`),
|
|
280
|
+
},
|
|
281
|
+
start: (input, mutation) => request("channel.giving.start", "/give/start", {
|
|
282
|
+
method: "POST", headers: mutationHeaders(mutation), body: JSON.stringify(input),
|
|
283
|
+
}),
|
|
284
|
+
},
|
|
285
|
+
print: {
|
|
286
|
+
settings: () => request("channel.print.settings", "/print/settings"),
|
|
287
|
+
quote: (input) => request("channel.print.quote", "/print/quote", {
|
|
288
|
+
method: "POST", body: JSON.stringify(input),
|
|
289
|
+
}),
|
|
290
|
+
intake: (input, mutation) => {
|
|
291
|
+
const form = new FormData();
|
|
292
|
+
form.set("name", input.name);
|
|
293
|
+
if (input.email)
|
|
294
|
+
form.set("email", input.email);
|
|
295
|
+
if (input.phone)
|
|
296
|
+
form.set("phone", input.phone);
|
|
297
|
+
if (input.notes)
|
|
298
|
+
form.set("notes", input.notes);
|
|
299
|
+
form.set("options", JSON.stringify(input.options));
|
|
300
|
+
for (const file of input.files)
|
|
301
|
+
form.append("files", file.blob, file.filename);
|
|
302
|
+
return request("channel.print.intake", "/print/intake", {
|
|
303
|
+
method: "POST", headers: mutationHeaders(mutation), body: form,
|
|
304
|
+
});
|
|
305
|
+
},
|
|
306
|
+
},
|
|
307
|
+
dining: {
|
|
308
|
+
menu: (boardSlug) => request("dining.public.board_menu.channel", `/dining/boards/${encodePath(boardSlug)}/menu`),
|
|
309
|
+
},
|
|
233
310
|
// Customer sign-in. These are anonymous calls — they CREATE a session.
|
|
234
311
|
auth: {
|
|
235
312
|
check: (email) => request("channel.auth.check", "/auth/check", { method: "POST", body: JSON.stringify({ email }) }),
|
|
@@ -260,6 +337,11 @@ export function createChannelClient(options) {
|
|
|
260
337
|
summary: () => request("channel.account.orders.summary", "/account/orders/summary", {}, customerSession),
|
|
261
338
|
get: (orderId) => request("channel.account.orders.get", `/account/orders/${encodePath(orderId)}`, {}, customerSession),
|
|
262
339
|
},
|
|
340
|
+
giving: {
|
|
341
|
+
start: (input, mutation) => request("channel.giving.start", "/give/start", {
|
|
342
|
+
method: "POST", headers: mutationHeaders(mutation), body: JSON.stringify(input),
|
|
343
|
+
}, customerSession),
|
|
344
|
+
},
|
|
263
345
|
};
|
|
264
346
|
},
|
|
265
347
|
leads: {
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import "server-only";
|
|
2
|
+
import { createChannelClient, type ChannelCheckoutStatusParams, type ChannelMutationOptions } 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
|
+
}, attempt: ChannelMutationOptions & {
|
|
71
|
+
idempotencyKey: string;
|
|
72
|
+
}) => Promise<CheckoutPayResponse>;
|
|
73
|
+
};
|
|
74
|
+
};
|
|
75
|
+
export type CartKit = ReturnType<typeof createCart>;
|
|
76
|
+
export {};
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import "server-only";
|
|
2
|
+
import { createChannelClient, isChannelAPIError, } 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 (error) {
|
|
43
|
+
if (isChannelAPIError(error) && error.status === 404)
|
|
44
|
+
return null;
|
|
45
|
+
throw error;
|
|
46
|
+
}
|
|
47
|
+
},
|
|
48
|
+
async addItem(input) {
|
|
49
|
+
return resolve().cart.addItem(input);
|
|
50
|
+
},
|
|
51
|
+
async updateItem(itemId, cartToken, quantity) {
|
|
52
|
+
return resolve().cart.updateItem(itemId, { cart_token: cartToken, quantity });
|
|
53
|
+
},
|
|
54
|
+
async removeItem(itemId, cartToken) {
|
|
55
|
+
return resolve().cart.removeItem(itemId, cartToken);
|
|
56
|
+
},
|
|
57
|
+
async clear(cartToken) {
|
|
58
|
+
return resolve().cart.clear(cartToken);
|
|
59
|
+
},
|
|
60
|
+
/**
|
|
61
|
+
* Call in the same Server Action that sets the session cookie: the guest's
|
|
62
|
+
* cart follows the customer into their account instead of evaporating at
|
|
63
|
+
* the sign-in door.
|
|
64
|
+
*/
|
|
65
|
+
async mergeOnSignIn(guestCartToken, customerCartToken) {
|
|
66
|
+
return resolve().cart.merge({
|
|
67
|
+
source_cart_token: guestCartToken,
|
|
68
|
+
target_cart_token: customerCartToken,
|
|
69
|
+
});
|
|
70
|
+
},
|
|
71
|
+
/** Checkout steps, addressed by the order the cart became. */
|
|
72
|
+
checkout: {
|
|
73
|
+
options: (orderId, cartToken) => resolve().checkout.options(orderId, cartToken),
|
|
74
|
+
status: (orderId, params) => resolve().checkout.status(orderId, params),
|
|
75
|
+
setCustomer: (orderId, input) => resolve().checkout.setCustomer(orderId, input),
|
|
76
|
+
setAddresses: (orderId, input) => resolve().checkout.setAddresses(orderId, input),
|
|
77
|
+
setFulfillment: (orderId, input) => resolve().checkout.setFulfillment(orderId, input),
|
|
78
|
+
/**
|
|
79
|
+
* Returns the Stripe-hosted redirect URL. `return_url` is REQUIRED for a
|
|
80
|
+
* channel checkout (our API's host means nothing to your shopper) and
|
|
81
|
+
* must be on the channel's registered site_url — the server refuses
|
|
82
|
+
* anything else, because an unchecked return URL is an open redirect.
|
|
83
|
+
*/
|
|
84
|
+
pay: (orderId, input, attempt) => resolve().checkout.pay(orderId, input, attempt),
|
|
85
|
+
},
|
|
86
|
+
};
|
|
87
|
+
}
|
|
@@ -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 {};
|