@c1m-public/channel-client 0.19.0 → 0.20.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 +16 -5
- package/dist/chunk-ATGQYDRM.js +334 -0
- package/dist/chunk-AX6L2XH3.js +599 -0
- package/dist/chunk-JDERR7M5.js +17 -0
- package/dist/chunk-RJQ4YEZV.js +180 -0
- package/dist/dash-next.d.ts +8 -5
- package/dist/dash-next.js +10 -11
- package/dist/dash.d.ts +7 -5
- package/dist/dash.js +3 -16
- package/dist/index.d.ts +1325 -27
- package/dist/index.js +2 -513
- package/dist/moving-lead-model/index.d.ts +417 -3
- package/dist/moving-lead-model/index.js +288 -2
- package/dist/next.d.ts +352 -103
- package/dist/next.js +3 -69
- package/dist/renderer.d.ts +11 -9
- package/dist/renderer.js +75 -95
- package/dist/webhooks.d.ts +28 -26
- package/dist/webhooks.js +1 -228
- package/package.json +5 -3
- package/dist/errors.d.ts +0 -12
- package/dist/errors.js +0 -19
- package/dist/moving-lead-model/address-model.d.ts +0 -12
- package/dist/moving-lead-model/address-model.js +0 -43
- package/dist/moving-lead-model/address-types.d.ts +0 -55
- package/dist/moving-lead-model/address-types.js +0 -12
- package/dist/moving-lead-model/quote-model.d.ts +0 -348
- package/dist/moving-lead-model/quote-model.js +0 -267
- package/dist/next-cart.d.ts +0 -76
- package/dist/next-cart.js +0 -87
- package/dist/next-session.d.ts +0 -121
- package/dist/next-session.js +0 -177
- package/dist/next-webhooks.d.ts +0 -58
- package/dist/next-webhooks.js +0 -109
- package/dist/types.d.ts +0 -1273
- package/dist/types.js +0 -1
package/dist/next-cart.js
DELETED
|
@@ -1,87 +0,0 @@
|
|
|
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
|
-
}
|
package/dist/next-session.d.ts
DELETED
|
@@ -1,121 +0,0 @@
|
|
|
1
|
-
import "server-only";
|
|
2
|
-
import { createChannelClient } from "./index.js";
|
|
3
|
-
/**
|
|
4
|
-
* Customer-session kit for Next.js sites.
|
|
5
|
-
*
|
|
6
|
-
* Every headless C1M site needs the same ~250 lines: an httpOnly cookie codec,
|
|
7
|
-
* a refresh-skew decision, and — the part nobody gets right twice — the
|
|
8
|
-
* contested-vs-expired distinction. This kit ships them once.
|
|
9
|
-
*
|
|
10
|
-
* Framework-honest: no `next` imports. The codec returns names, values and
|
|
11
|
-
* attribute objects; the app applies them with `next/headers` or `NextResponse`
|
|
12
|
-
* (a Server Component cannot write cookies, so WHERE they are applied is
|
|
13
|
-
* necessarily the app's decision: proxy.ts or a Server Action).
|
|
14
|
-
*/
|
|
15
|
-
/** What the session cookie holds. `expiresAt` is the ACCESS token's expiry. */
|
|
16
|
-
export interface SessionTokens {
|
|
17
|
-
accessToken: string;
|
|
18
|
-
refreshToken: string;
|
|
19
|
-
expiresAt: string;
|
|
20
|
-
}
|
|
21
|
-
/** A signed-in customer, normalized for rendering. */
|
|
22
|
-
export interface SessionCustomer {
|
|
23
|
-
id: string;
|
|
24
|
-
email: string;
|
|
25
|
-
name: string;
|
|
26
|
-
}
|
|
27
|
-
export interface SessionCookieAttributes {
|
|
28
|
-
httpOnly: true;
|
|
29
|
-
secure: true;
|
|
30
|
-
sameSite: "lax";
|
|
31
|
-
path: "/";
|
|
32
|
-
maxAge: number;
|
|
33
|
-
}
|
|
34
|
-
/**
|
|
35
|
-
* The one definition of the session cookie. A second definition is how a cookie
|
|
36
|
-
* ends up readable on one path and not another.
|
|
37
|
-
*/
|
|
38
|
-
export declare const sessionCookie: {
|
|
39
|
-
readonly name: "__Host-c1m_session";
|
|
40
|
-
readonly attributes: (_isProduction?: boolean) => SessionCookieAttributes;
|
|
41
|
-
readonly serialize: (tokens: SessionTokens) => string;
|
|
42
|
-
/**
|
|
43
|
-
* A cookie is attacker-controlled input: truncated, stale-shaped, or
|
|
44
|
-
* hand-written. Anything unreadable is "not signed in", never a crash.
|
|
45
|
-
*/
|
|
46
|
-
readonly parse: (raw: string | undefined) => SessionTokens | null;
|
|
47
|
-
readonly needsRefresh: (tokens: SessionTokens, now?: number) => boolean;
|
|
48
|
-
};
|
|
49
|
-
export type RequestCodeOutcome = {
|
|
50
|
-
state: "sent";
|
|
51
|
-
} | {
|
|
52
|
-
state: "failed";
|
|
53
|
-
};
|
|
54
|
-
export type SignInOutcome = {
|
|
55
|
-
state: "signed-in";
|
|
56
|
-
customer: SessionCustomer;
|
|
57
|
-
tokens: SessionTokens;
|
|
58
|
-
/** Ready to hand to cookies().set(...) — name, value, attributes. */
|
|
59
|
-
cookie: {
|
|
60
|
-
name: string;
|
|
61
|
-
value: string;
|
|
62
|
-
attributes: SessionCookieAttributes;
|
|
63
|
-
};
|
|
64
|
-
} | {
|
|
65
|
-
state: "invalid-code";
|
|
66
|
-
} | {
|
|
67
|
-
state: "failed";
|
|
68
|
-
};
|
|
69
|
-
/**
|
|
70
|
-
* What to do with the session cookie after a refresh attempt.
|
|
71
|
-
*
|
|
72
|
-
* `keep` and `clear` are NOT interchangeable. Clearing when the customer merely
|
|
73
|
-
* lost a race with their own second tab discards the fresh token that tab just
|
|
74
|
-
* stored — logging them out of a live session. The server keeps the token
|
|
75
|
-
* family alive for a short rotation grace window and reports the loser as
|
|
76
|
-
* `refresh_contested` precisely so clients can tell the two apart.
|
|
77
|
-
*/
|
|
78
|
-
export type SessionRefreshResult = {
|
|
79
|
-
action: "keep";
|
|
80
|
-
} | {
|
|
81
|
-
action: "write";
|
|
82
|
-
value: string;
|
|
83
|
-
attributes: SessionCookieAttributes;
|
|
84
|
-
} | {
|
|
85
|
-
action: "clear";
|
|
86
|
-
};
|
|
87
|
-
type SessionClient = Pick<ReturnType<typeof createChannelClient>, "auth" | "withCustomer">;
|
|
88
|
-
export interface CreateCustomerSessionOptions {
|
|
89
|
-
/** The channel client, or a lazy resolver (the singleton pattern). */
|
|
90
|
-
client: SessionClient | (() => SessionClient);
|
|
91
|
-
}
|
|
92
|
-
/**
|
|
93
|
-
* The session surface a site actually needs, mapped to intentional outcomes —
|
|
94
|
-
* a route renders "that code was wrong" without ever seeing an HTTP status.
|
|
95
|
-
*/
|
|
96
|
-
export declare function createCustomerSession(options: CreateCustomerSessionOptions): {
|
|
97
|
-
readonly cookie: {
|
|
98
|
-
readonly name: "__Host-c1m_session";
|
|
99
|
-
readonly attributes: (_isProduction?: boolean) => SessionCookieAttributes;
|
|
100
|
-
readonly serialize: (tokens: SessionTokens) => string;
|
|
101
|
-
/**
|
|
102
|
-
* A cookie is attacker-controlled input: truncated, stale-shaped, or
|
|
103
|
-
* hand-written. Anything unreadable is "not signed in", never a crash.
|
|
104
|
-
*/
|
|
105
|
-
readonly parse: (raw: string | undefined) => SessionTokens | null;
|
|
106
|
-
readonly needsRefresh: (tokens: SessionTokens, now?: number) => boolean;
|
|
107
|
-
};
|
|
108
|
-
readonly requestCode: (email: string) => Promise<RequestCodeOutcome>;
|
|
109
|
-
readonly signIn: (email: string, code: string) => Promise<SignInOutcome>;
|
|
110
|
-
/**
|
|
111
|
-
* Decide what this request should do to the session cookie. Designed to be
|
|
112
|
-
* the whole body of proxy.ts.
|
|
113
|
-
*/
|
|
114
|
-
readonly refresh: (raw: string | undefined) => Promise<SessionRefreshResult>;
|
|
115
|
-
/** Who is signed in, or null. Never throws — a broken cookie is "signed out". */
|
|
116
|
-
readonly getCustomer: (raw: string | undefined) => Promise<SessionCustomer | null>;
|
|
117
|
-
/** Best-effort server logout; the caller clears the cookie REGARDLESS. */
|
|
118
|
-
readonly signOut: (raw: string | undefined) => Promise<void>;
|
|
119
|
-
};
|
|
120
|
-
export type CustomerSessionKit = ReturnType<typeof createCustomerSession>;
|
|
121
|
-
export {};
|
package/dist/next-session.js
DELETED
|
@@ -1,177 +0,0 @@
|
|
|
1
|
-
import "server-only";
|
|
2
|
-
import { createChannelClient, isChannelAPIError } from "./index.js";
|
|
3
|
-
/** Match the refresh token's life (~30 days), not the access token's (~15 min). */
|
|
4
|
-
const MAX_AGE_SECONDS = 60 * 60 * 24 * 30;
|
|
5
|
-
/** Refresh slightly BEFORE expiry: a token that dies mid-render fails the request it was meant to serve. */
|
|
6
|
-
const REFRESH_SKEW_MS = 60_000;
|
|
7
|
-
/**
|
|
8
|
-
* The one definition of the session cookie. A second definition is how a cookie
|
|
9
|
-
* ends up readable on one path and not another.
|
|
10
|
-
*/
|
|
11
|
-
export const sessionCookie = {
|
|
12
|
-
name: "__Host-c1m_session",
|
|
13
|
-
// The optional argument remains source-compatible with 0.14 callers. A
|
|
14
|
-
// __Host- cookie is Secure in every environment, including local HTTPS.
|
|
15
|
-
attributes(_isProduction) {
|
|
16
|
-
return {
|
|
17
|
-
// Never readable from JavaScript: an XSS bug must not become a stolen session.
|
|
18
|
-
httpOnly: true,
|
|
19
|
-
secure: true,
|
|
20
|
-
// Lax, not Strict: the session must survive a customer arriving from an
|
|
21
|
-
// emailed link. Not None — that would ship the cookie cross-site.
|
|
22
|
-
sameSite: "lax",
|
|
23
|
-
path: "/",
|
|
24
|
-
maxAge: MAX_AGE_SECONDS,
|
|
25
|
-
};
|
|
26
|
-
},
|
|
27
|
-
serialize(tokens) {
|
|
28
|
-
return JSON.stringify(tokens);
|
|
29
|
-
},
|
|
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
|
-
parse(raw) {
|
|
35
|
-
if (!raw)
|
|
36
|
-
return null;
|
|
37
|
-
try {
|
|
38
|
-
const parsed = JSON.parse(raw);
|
|
39
|
-
if (!parsed || typeof parsed !== "object")
|
|
40
|
-
return null;
|
|
41
|
-
const { accessToken, refreshToken, expiresAt } = parsed;
|
|
42
|
-
if (typeof accessToken !== "string" || !accessToken)
|
|
43
|
-
return null;
|
|
44
|
-
if (typeof refreshToken !== "string" || !refreshToken)
|
|
45
|
-
return null;
|
|
46
|
-
if (typeof expiresAt !== "string" || !expiresAt)
|
|
47
|
-
return null;
|
|
48
|
-
return { accessToken, refreshToken, expiresAt };
|
|
49
|
-
}
|
|
50
|
-
catch {
|
|
51
|
-
return null;
|
|
52
|
-
}
|
|
53
|
-
},
|
|
54
|
-
needsRefresh(tokens, now = Date.now()) {
|
|
55
|
-
const expiresAt = Date.parse(tokens.expiresAt);
|
|
56
|
-
// Unparseable expiry: refresh and find out, rather than trusting it forever.
|
|
57
|
-
if (Number.isNaN(expiresAt))
|
|
58
|
-
return true;
|
|
59
|
-
return expiresAt - now <= REFRESH_SKEW_MS;
|
|
60
|
-
},
|
|
61
|
-
};
|
|
62
|
-
/** The server's code for "another request rotated this token moments ago". */
|
|
63
|
-
const CONTESTED = "refresh_contested";
|
|
64
|
-
function normalizeCustomer(customer) {
|
|
65
|
-
return {
|
|
66
|
-
id: customer.id,
|
|
67
|
-
email: customer.email,
|
|
68
|
-
name: customer.name?.trim() || customer.email,
|
|
69
|
-
};
|
|
70
|
-
}
|
|
71
|
-
function toTokens(session) {
|
|
72
|
-
return {
|
|
73
|
-
accessToken: session.access_token,
|
|
74
|
-
refreshToken: session.refresh_token,
|
|
75
|
-
expiresAt: session.expires_at,
|
|
76
|
-
};
|
|
77
|
-
}
|
|
78
|
-
/**
|
|
79
|
-
* The session surface a site actually needs, mapped to intentional outcomes —
|
|
80
|
-
* a route renders "that code was wrong" without ever seeing an HTTP status.
|
|
81
|
-
*/
|
|
82
|
-
export function createCustomerSession(options) {
|
|
83
|
-
const resolve = typeof options.client === "function" ? options.client : () => options.client;
|
|
84
|
-
return {
|
|
85
|
-
cookie: sessionCookie,
|
|
86
|
-
async requestCode(email) {
|
|
87
|
-
try {
|
|
88
|
-
await resolve().auth.sendCode(email);
|
|
89
|
-
return { state: "sent" };
|
|
90
|
-
}
|
|
91
|
-
catch {
|
|
92
|
-
return { state: "failed" };
|
|
93
|
-
}
|
|
94
|
-
},
|
|
95
|
-
async signIn(email, code) {
|
|
96
|
-
try {
|
|
97
|
-
const session = await resolve().auth.verifyCode({ email, code });
|
|
98
|
-
const tokens = toTokens(session);
|
|
99
|
-
return {
|
|
100
|
-
state: "signed-in",
|
|
101
|
-
customer: normalizeCustomer(session.end_user),
|
|
102
|
-
tokens,
|
|
103
|
-
cookie: {
|
|
104
|
-
name: sessionCookie.name,
|
|
105
|
-
value: sessionCookie.serialize(tokens),
|
|
106
|
-
attributes: sessionCookie.attributes(),
|
|
107
|
-
},
|
|
108
|
-
};
|
|
109
|
-
}
|
|
110
|
-
catch (error) {
|
|
111
|
-
// A wrong code is an ordinary thing a person does, not a failure.
|
|
112
|
-
if (isChannelAPIError(error) && error.code === "invalid_code") {
|
|
113
|
-
return { state: "invalid-code" };
|
|
114
|
-
}
|
|
115
|
-
return { state: "failed" };
|
|
116
|
-
}
|
|
117
|
-
},
|
|
118
|
-
/**
|
|
119
|
-
* Decide what this request should do to the session cookie. Designed to be
|
|
120
|
-
* the whole body of proxy.ts.
|
|
121
|
-
*/
|
|
122
|
-
async refresh(raw) {
|
|
123
|
-
const session = sessionCookie.parse(raw);
|
|
124
|
-
if (!session)
|
|
125
|
-
return { action: "keep" };
|
|
126
|
-
if (!sessionCookie.needsRefresh(session))
|
|
127
|
-
return { action: "keep" };
|
|
128
|
-
try {
|
|
129
|
-
const rotated = await resolve().auth.refresh(session.refreshToken);
|
|
130
|
-
return {
|
|
131
|
-
action: "write",
|
|
132
|
-
value: sessionCookie.serialize(toTokens(rotated)),
|
|
133
|
-
attributes: sessionCookie.attributes(),
|
|
134
|
-
};
|
|
135
|
-
}
|
|
136
|
-
catch (error) {
|
|
137
|
-
if (isChannelAPIError(error)) {
|
|
138
|
-
// Lost a race with the customer's own other tab: the session is alive
|
|
139
|
-
// and that tab already stored a good token. KEEP the cookie.
|
|
140
|
-
if (error.code === CONTESTED)
|
|
141
|
-
return { action: "keep" };
|
|
142
|
-
// Genuinely dead — logged out, revoked, or aged out. Clear it.
|
|
143
|
-
if (error.status === 401)
|
|
144
|
-
return { action: "clear" };
|
|
145
|
-
}
|
|
146
|
-
// An upstream wobble is not evidence anyone's session is dead.
|
|
147
|
-
return { action: "keep" };
|
|
148
|
-
}
|
|
149
|
-
},
|
|
150
|
-
/** Who is signed in, or null. Never throws — a broken cookie is "signed out". */
|
|
151
|
-
async getCustomer(raw) {
|
|
152
|
-
const session = sessionCookie.parse(raw);
|
|
153
|
-
if (!session)
|
|
154
|
-
return null;
|
|
155
|
-
try {
|
|
156
|
-
const { end_user } = await resolve().withCustomer(session.accessToken).me();
|
|
157
|
-
return normalizeCustomer(end_user);
|
|
158
|
-
}
|
|
159
|
-
catch {
|
|
160
|
-
return null;
|
|
161
|
-
}
|
|
162
|
-
},
|
|
163
|
-
/** Best-effort server logout; the caller clears the cookie REGARDLESS. */
|
|
164
|
-
async signOut(raw) {
|
|
165
|
-
const session = sessionCookie.parse(raw);
|
|
166
|
-
if (!session)
|
|
167
|
-
return;
|
|
168
|
-
try {
|
|
169
|
-
await resolve().withCustomer(session.accessToken).logout();
|
|
170
|
-
}
|
|
171
|
-
catch {
|
|
172
|
-
// A customer who clicks "sign out" must end up signed out of this
|
|
173
|
-
// browser even if the API is down.
|
|
174
|
-
}
|
|
175
|
-
},
|
|
176
|
-
};
|
|
177
|
-
}
|
package/dist/next-webhooks.d.ts
DELETED
|
@@ -1,58 +0,0 @@
|
|
|
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
|
-
/**
|
|
20
|
-
* The cache tag catalog reads (product list, product detail) are filed under.
|
|
21
|
-
* `product.*` events bust this tag by default, so a merchant's price edit
|
|
22
|
-
* reaches the storefront on the next request instead of at the end of a TTL.
|
|
23
|
-
*/
|
|
24
|
-
export declare const CHANNEL_CATALOG_CACHE_TAG = "channel:catalog";
|
|
25
|
-
export interface ChannelCacheInvalidator {
|
|
26
|
-
revalidatePath(path: string): void;
|
|
27
|
-
revalidateTag(tag: string): void;
|
|
28
|
-
}
|
|
29
|
-
export interface ChannelWebhookRouteLogger {
|
|
30
|
-
info(message: string, context?: Record<string, unknown>): void;
|
|
31
|
-
warn(message: string, context?: Record<string, unknown>): void;
|
|
32
|
-
error(message: string, context?: Record<string, unknown>): void;
|
|
33
|
-
}
|
|
34
|
-
export type ChannelWebhookHandlers = {
|
|
35
|
-
[T in keyof ChannelWebhookEventDataMap]?: (event: ChannelWebhookEvent<T>, invalidate: ChannelCacheInvalidator) => void | Promise<void>;
|
|
36
|
-
};
|
|
37
|
-
export interface CreateChannelWebhookRouteOptions {
|
|
38
|
-
/** The whsec_ signing secret, or a lazy resolver (resolved per request so builds without env pass). */
|
|
39
|
-
secret: string | (() => string);
|
|
40
|
-
/** Next's cache invalidation, injected: `{ revalidatePath, revalidateTag }` from next/cache. */
|
|
41
|
-
invalidate: ChannelCacheInvalidator;
|
|
42
|
-
/**
|
|
43
|
-
* Per-event handlers. A handler REPLACES the built-in behavior for that type;
|
|
44
|
-
* types without a handler get the default (page.published revalidates the
|
|
45
|
-
* site tag + the published path; everything else is acknowledged and ignored
|
|
46
|
-
* — delivery is at-least-once, so an unhandled event must still 204 or the
|
|
47
|
-
* server will retry it for hours).
|
|
48
|
-
*/
|
|
49
|
-
onEvent?: ChannelWebhookHandlers;
|
|
50
|
-
logger?: ChannelWebhookRouteLogger;
|
|
51
|
-
}
|
|
52
|
-
/**
|
|
53
|
-
* A route_pattern arrives from the network; it is input, not truth. Reject
|
|
54
|
-
* anything that is not a plain absolute path before handing it to the cache.
|
|
55
|
-
*/
|
|
56
|
-
export declare function safePublishedPath(path: string): string | undefined;
|
|
57
|
-
/** Build the POST handler for the channel webhook endpoint. */
|
|
58
|
-
export declare function createChannelWebhookRoute(options: CreateChannelWebhookRouteOptions): (request: Request) => Promise<Response>;
|
package/dist/next-webhooks.js
DELETED
|
@@ -1,109 +0,0 @@
|
|
|
1
|
-
import "server-only";
|
|
2
|
-
import { isChannelWebhookVerificationError, isChannelWebhookEventType, 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
|
-
* The cache tag catalog reads (product list, product detail) are filed under.
|
|
21
|
-
* `product.*` events bust this tag by default, so a merchant's price edit
|
|
22
|
-
* reaches the storefront on the next request instead of at the end of a TTL.
|
|
23
|
-
*/
|
|
24
|
-
export const CHANNEL_CATALOG_CACHE_TAG = "channel:catalog";
|
|
25
|
-
/**
|
|
26
|
-
* A route_pattern arrives from the network; it is input, not truth. Reject
|
|
27
|
-
* anything that is not a plain absolute path before handing it to the cache.
|
|
28
|
-
*/
|
|
29
|
-
export function safePublishedPath(path) {
|
|
30
|
-
const normalized = path.trim();
|
|
31
|
-
if (!normalized.startsWith("/") || normalized.startsWith("//") || normalized.length > 1024) {
|
|
32
|
-
return undefined;
|
|
33
|
-
}
|
|
34
|
-
return normalized;
|
|
35
|
-
}
|
|
36
|
-
function errorMessage(error) {
|
|
37
|
-
return error instanceof Error ? error.message : String(error);
|
|
38
|
-
}
|
|
39
|
-
function defaultBehavior(event, invalidate) {
|
|
40
|
-
if (event.type === "page.published") {
|
|
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
|
-
// A catalog edit with no cache bust means the site serves the old price
|
|
49
|
-
// until its TTL expires — so product.* busts the catalog tag by default,
|
|
50
|
-
// with no configuration. Tag your product reads with
|
|
51
|
-
// CHANNEL_CATALOG_CACHE_TAG and a price change lands on the next request.
|
|
52
|
-
if (event.type === "product.created" || event.type === "product.updated" || event.type === "product.deleted") {
|
|
53
|
-
invalidate.revalidateTag(CHANNEL_CATALOG_CACHE_TAG);
|
|
54
|
-
return undefined;
|
|
55
|
-
}
|
|
56
|
-
return undefined;
|
|
57
|
-
}
|
|
58
|
-
/** Build the POST handler for the channel webhook endpoint. */
|
|
59
|
-
export function createChannelWebhookRoute(options) {
|
|
60
|
-
const logger = options.logger ?? console;
|
|
61
|
-
const resolveSecret = typeof options.secret === "function" ? options.secret : () => options.secret;
|
|
62
|
-
return async (request) => {
|
|
63
|
-
let event;
|
|
64
|
-
try {
|
|
65
|
-
event = await parseChannelWebhookEvent(request, { secret: resolveSecret() });
|
|
66
|
-
}
|
|
67
|
-
catch (error) {
|
|
68
|
-
if (isChannelWebhookVerificationError(error)) {
|
|
69
|
-
// An unverifiable request is noise or an attack; log the code, say
|
|
70
|
-
// nothing useful back.
|
|
71
|
-
logger.warn("channel_webhook_rejected", { code: error.code });
|
|
72
|
-
return Response.json({ code: "invalid_channel_webhook" }, { status: 401 });
|
|
73
|
-
}
|
|
74
|
-
// Log a message, never the raw error object: a thrown value could carry
|
|
75
|
-
// configuration (a secret in a message string) into the log verbatim.
|
|
76
|
-
logger.error("channel_webhook_failed", { message: errorMessage(error) });
|
|
77
|
-
return Response.json({ code: "channel_webhook_failed" }, { status: 500 });
|
|
78
|
-
}
|
|
79
|
-
try {
|
|
80
|
-
if (!isChannelWebhookEventType(event.type)) {
|
|
81
|
-
logger.info("channel_webhook_ignored", { eventId: event.id, eventType: event.type });
|
|
82
|
-
return new Response(null, { status: 204 });
|
|
83
|
-
}
|
|
84
|
-
const knownEvent = event;
|
|
85
|
-
const handler = options.onEvent?.[knownEvent.type];
|
|
86
|
-
let revalidatedPath;
|
|
87
|
-
if (handler) {
|
|
88
|
-
await handler(knownEvent, options.invalidate);
|
|
89
|
-
}
|
|
90
|
-
else {
|
|
91
|
-
revalidatedPath = defaultBehavior(knownEvent, options.invalidate);
|
|
92
|
-
}
|
|
93
|
-
logger.info("channel_webhook_processed", {
|
|
94
|
-
eventId: event.id,
|
|
95
|
-
eventType: knownEvent.type,
|
|
96
|
-
...(revalidatedPath ? { revalidatedPath } : {}),
|
|
97
|
-
});
|
|
98
|
-
return new Response(null, { status: 204 });
|
|
99
|
-
}
|
|
100
|
-
catch (error) {
|
|
101
|
-
// A handler failure is OURS: the signature verified, the event is real.
|
|
102
|
-
// A 500 makes the server retry on its ladder — which is what you want
|
|
103
|
-
// when the failure is transient, and visible in delivery history when
|
|
104
|
-
// it is not.
|
|
105
|
-
logger.error("channel_webhook_failed", { eventId: event.id, eventType: event.type, message: errorMessage(error) });
|
|
106
|
-
return Response.json({ code: "channel_webhook_failed" }, { status: 500 });
|
|
107
|
-
}
|
|
108
|
-
};
|
|
109
|
-
}
|