@porulle/adapter-shopify 0.86.0 → 0.88.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/src/oauth.ts CHANGED
@@ -4,29 +4,54 @@ import type { ChannelConnectorError, Result } from "@porulle/core";
4
4
  import { z } from "zod";
5
5
 
6
6
  /**
7
- * Shopify's OAuth for a standalone (non-embedded) app: the authorization code grant, asking for an
8
- * EXPIRING offline token. Shopify requires expiring offline tokens of every new public app calling the
9
- * GraphQL Admin API: a one-hour access token and a 90-day refresh token that rotates on every refresh.
10
- * https://shopify.dev/docs/apps/build/authentication-authorization/access-tokens
7
+ * Shopify's two grants an app connects a store with.
8
+ *
9
+ * - The authorization code grant, for an app the merchant installs from us (public or custom
10
+ * distribution), asking for an EXPIRING offline token: Shopify requires them of every new public
11
+ * app calling the GraphQL Admin API — a one-hour access token and a 90-day refresh token that
12
+ * rotates on every refresh.
13
+ * https://shopify.dev/docs/apps/build/authentication-authorization/access-tokens
14
+ * - The client credentials grant, for an app that belongs to the SAME Shopify organization as the
15
+ * store: a merchant's own Dev Dashboard app, whose client id and secret the merchant hands over.
16
+ * The token lives 24 hours and there is no refresh token; a new one is minted with the same client
17
+ * id and secret. Shopify refuses it with `shop_not_permitted` across organizations.
18
+ * https://shopify.dev/docs/apps/build/authentication-authorization/client-credentials-grant
19
+ * - The token exchange grant, for an app Shopify installs itself (managed installation) and loads
20
+ * inside the admin: App Bridge hands the page a one-minute ID token, and the app trades it for the
21
+ * same expiring offline token. Shopify keeps ONE current offline token per app and store, so a
22
+ * successful exchange retires the refresh tokens an earlier grant of that app issued.
23
+ * https://shopify.dev/docs/apps/build/authentication-authorization/implement-token-exchange
11
24
  */
12
25
 
13
26
  /**
14
- * The scopes the connector's live paths need, and nothing else.
27
+ * The scopes the connector's live paths need, and nothing else. Nothing about a product is ever
28
+ * pushed to a merchant's Shopify — only orders reach it — so there is no `write_products` here.
15
29
  *
16
- * - `read_products`, `write_products`: the catalogue import, and the Loom metafield write-back.
30
+ * - `read_products`: the catalogue import.
17
31
  * - `read_inventory`: variant stock and the inventory item behind a stock webhook.
18
32
  * - `write_orders`: a paid platform order is created in the store (`orderCreate`). A write scope
19
33
  * includes its read scope, which `orders/fulfilled` and `orders/cancelled` need.
20
34
  * - `read_returns`, `write_returns`: a shopper's return is asked of the store (`returnRequest`) and
21
35
  * its `returns/*` webhooks say how the store answered.
22
36
  */
23
- export const REQUIRED_SCOPES = ["read_products", "write_products", "read_inventory", "write_orders", "read_returns", "write_returns"] as const;
37
+ export const REQUIRED_SCOPES = ["read_products", "read_inventory", "write_orders", "read_returns", "write_returns"] as const;
24
38
 
25
39
  /** Refresh this long before Shopify's stated expiry, so a call never starts on a token about to lapse. */
26
40
  export const ACCESS_TOKEN_REFRESH_MARGIN_MS = 5 * 60 * 1000;
27
41
 
28
42
  /** What the store row holds. Read back with {@link parseShopifyCredentials}; never cast. */
29
43
  export interface ShopifyCredentials {
44
+ /**
45
+ * The client id of the app that issued this grant. A token renews only with the app that issued
46
+ * it, and which app that is cannot be inferred from the shop: it is stored with the grant. Absent on
47
+ * a grant stored before this field existed, which the next renewal fills in.
48
+ */
49
+ clientId?: string;
50
+ /**
51
+ * How the token was granted. `client_credentials` has no refresh token: it is renewed by minting
52
+ * again with the app's client id and secret. Absent: the authorization code grant.
53
+ */
54
+ grant?: "client_credentials";
30
55
  accessToken: string;
31
56
  /** Absent for a non-expiring token (an admin-created custom app); such a token is never refreshed. */
32
57
  refreshToken?: string;
@@ -36,6 +61,8 @@ export interface ShopifyCredentials {
36
61
  }
37
62
 
38
63
  const credentialsSchema = z.object({
64
+ clientId: z.string().min(1).optional(),
65
+ grant: z.literal("client_credentials").optional(),
39
66
  accessToken: z.string().min(1),
40
67
  refreshToken: z.string().min(1).optional(),
41
68
  accessTokenExpiresAt: z.string().optional(),
@@ -46,9 +73,11 @@ const credentialsSchema = z.object({
46
73
  export function parseShopifyCredentials(value: Record<string, unknown>): ShopifyCredentials | undefined {
47
74
  const parsed = credentialsSchema.safeParse(value);
48
75
  if (!parsed.success) return undefined;
49
- const { refreshToken, accessTokenExpiresAt, refreshTokenExpiresAt, ...rest } = parsed.data;
76
+ const { clientId, grant, refreshToken, accessTokenExpiresAt, refreshTokenExpiresAt, ...rest } = parsed.data;
50
77
  return {
51
78
  ...rest,
79
+ ...(clientId !== undefined ? { clientId } : {}),
80
+ ...(grant !== undefined ? { grant } : {}),
52
81
  ...(refreshToken !== undefined ? { refreshToken } : {}),
53
82
  ...(accessTokenExpiresAt !== undefined ? { accessTokenExpiresAt } : {}),
54
83
  ...(refreshTokenExpiresAt !== undefined ? { refreshTokenExpiresAt } : {}),
@@ -108,8 +137,9 @@ export function missingScopes(granted: readonly string[], required: readonly str
108
137
  return required.filter((scope) => !have.has(scope) && !(scope.startsWith("read_") && have.has(`write_${scope.slice(5)}`)));
109
138
  }
110
139
 
111
- function credentialsFrom(body: z.infer<typeof tokenResponseSchema>, now: number): ShopifyCredentials {
140
+ function credentialsFrom(body: z.infer<typeof tokenResponseSchema>, now: number, clientId: string): ShopifyCredentials {
112
141
  return {
142
+ clientId,
113
143
  accessToken: body.access_token,
114
144
  grantedScopes: body.scope.split(",").map((scope) => scope.trim()).filter(Boolean),
115
145
  ...(body.refresh_token !== undefined ? { refreshToken: body.refresh_token } : {}),
@@ -118,7 +148,27 @@ function credentialsFrom(body: z.infer<typeof tokenResponseSchema>, now: number)
118
148
  };
119
149
  }
120
150
 
121
- async function postTokenEndpoint(fetchImpl: typeof fetch, origin: string, form: Record<string, string>): Promise<Result<z.infer<typeof tokenResponseSchema>, ChannelConnectorError>> {
151
+ /**
152
+ * Why the token endpoint refused a grant, from the body Shopify answered with. Live Shopify
153
+ * (measured 2026-11-24) answers 400 JSON (`invalid_request`, `application_cannot_be_found`,
154
+ * `app_not_installed`) and `shop_not_permitted` for cross-org client credentials; the refusal name is
155
+ * matched wherever it appears rather than parsed from one assumed shape.
156
+ */
157
+ function tokenRefusal(status: number, body: string): ChannelConnectorError {
158
+ if (body.includes("shop_not_permitted")) {
159
+ return { code: "SHOPIFY_SHOP_NOT_PERMITTED", message: "Shopify refused the client credentials grant for this store: the app and the store are in different Shopify organizations.", retriable: false };
160
+ }
161
+ if (body.includes("app_not_installed")) {
162
+ return { code: "SHOPIFY_APP_NOT_INSTALLED", message: "Shopify says the app is not installed on this store.", retriable: false };
163
+ }
164
+ return { code: "SHOPIFY_REAUTHORIZATION_REQUIRED", message: `Shopify refused the grant (${status}); the store must be reconnected.`, retriable: false };
165
+ }
166
+
167
+ /**
168
+ * `badRequest` is what a 400 means to this grant when it is not the generic refusal: for the token
169
+ * exchange it is a stale or invalid ID token, which a fresh one fixes.
170
+ */
171
+ async function postTokenEndpoint(fetchImpl: typeof fetch, origin: string, form: Record<string, string>, badRequest?: ChannelConnectorError): Promise<Result<z.infer<typeof tokenResponseSchema>, ChannelConnectorError>> {
122
172
  let response: Response;
123
173
  try {
124
174
  response = await fetchImpl(`${origin}/admin/oauth/access_token`, {
@@ -130,8 +180,12 @@ async function postTokenEndpoint(fetchImpl: typeof fetch, origin: string, form:
130
180
  } catch (error) {
131
181
  return oauthError("SHOPIFY_TOKEN_REQUEST_FAILED", error instanceof Error ? error.message : "Shopify token request failed.", true);
132
182
  }
183
+ if (response.status === 400 && badRequest !== undefined) return Err(badRequest);
133
184
  if (response.status === 400 || response.status === 401) {
134
- return oauthError("SHOPIFY_REAUTHORIZATION_REQUIRED", `Shopify refused the grant (${response.status}); the store must be reconnected.`);
185
+ return Err(tokenRefusal(response.status, await response.text().catch(() => "")));
186
+ }
187
+ if (response.status === 404) {
188
+ return oauthError("SHOPIFY_SHOP_NOT_FOUND", "Shopify has no store at that address.");
135
189
  }
136
190
  if (!response.ok) return oauthError("SHOPIFY_TOKEN_REQUEST_FAILED", `Shopify token request failed (${response.status}).`, response.status >= 500);
137
191
  const parsed = tokenResponseSchema.safeParse(await response.json().catch(() => undefined));
@@ -164,7 +218,7 @@ export async function exchangeCallback(params: {
164
218
  if (!code) return oauthError("SHOPIFY_OAUTH_CODE_REQUIRED", "Shopify OAuth callback code is required.");
165
219
  const token = await postTokenEndpoint(params.fetchImpl, params.origin, { client_id: params.clientId, client_secret: params.clientSecret, code, expiring: "1" });
166
220
  if (!token.ok) return token;
167
- const credentials = credentialsFrom(token.value, params.now);
221
+ const credentials = credentialsFrom(token.value, params.now, params.clientId);
168
222
  // Merchants can untick scopes on the grant screen; a token missing one fails later in a way that
169
223
  // looks like a product problem, so it is refused here, where the cause is still nameable.
170
224
  const missing = missingScopes(credentials.grantedScopes, params.requiredScopes);
@@ -172,9 +226,131 @@ export async function exchangeCallback(params: {
172
226
  return Ok(credentials);
173
227
  }
174
228
 
229
+ /** Shopify's ID tokens are signed with this; anything else (`none`, RS256) is refused before it is read. */
230
+ const ID_TOKEN_ALGORITHM = "HS256";
231
+ /** How far a token's `nbf` may sit in the future before it is refused: clocks differ by seconds. */
232
+ const ID_TOKEN_SKEW_MS = 10_000;
233
+
234
+ const idTokenHeaderSchema = z.object({ alg: z.string() });
235
+ const idTokenPayloadSchema = z.object({
236
+ iss: z.string(),
237
+ dest: z.string(),
238
+ aud: z.string(),
239
+ sub: z.string(),
240
+ exp: z.number(),
241
+ nbf: z.number(),
242
+ });
243
+
244
+ const ID_TOKEN_INVALID: ChannelConnectorError = { code: "SHOPIFY_ID_TOKEN_INVALID", message: "The Shopify ID token is invalid or expired.", retriable: false };
245
+
246
+ function jwtPart(encoded: string): unknown {
247
+ try {
248
+ return JSON.parse(Buffer.from(encoded, "base64url").toString("utf8"));
249
+ } catch {
250
+ return undefined;
251
+ }
252
+ }
253
+
254
+ function hostOf(url: string): string | undefined {
255
+ try {
256
+ return new URL(url).hostname.toLowerCase();
257
+ } catch {
258
+ return undefined;
259
+ }
260
+ }
261
+
262
+ /**
263
+ * Check an ID token the way Shopify documents: HS256 over `header.payload` under the client secret
264
+ * (compared in constant time), `exp` in the future, `nbf` in the past, `aud` equal to the client id,
265
+ * and the hostnames of `iss` and `dest` equal and a `*.myshopify.com` shop. Returns the shop the
266
+ * token was issued for and the staff member (`sub`). Every failure is `SHOPIFY_ID_TOKEN_INVALID`:
267
+ * the caller's answer is the same (a fresh token fixes it), and the cause is not the caller's to learn.
268
+ * https://shopify.dev/docs/apps/build/authentication-authorization/id-tokens
269
+ */
270
+ export function verifyShopifyIdToken(params: { token: string; clientId: string; clientSecret: string; now: number }): Result<{ shop: string; userId: string }, ChannelConnectorError> {
271
+ const parts = params.token.split(".");
272
+ const [encodedHeader, encodedPayload, encodedSignature] = parts;
273
+ if (parts.length !== 3 || !encodedHeader || !encodedPayload || !encodedSignature) return Err(ID_TOKEN_INVALID);
274
+ const header = idTokenHeaderSchema.safeParse(jwtPart(encodedHeader));
275
+ if (!header.success || header.data.alg !== ID_TOKEN_ALGORITHM) return Err(ID_TOKEN_INVALID);
276
+ const expected = createHmac("sha256", params.clientSecret).update(`${encodedHeader}.${encodedPayload}`).digest();
277
+ const actual = Buffer.from(encodedSignature, "base64url");
278
+ if (actual.length !== expected.length || !timingSafeEqual(actual, expected)) return Err(ID_TOKEN_INVALID);
279
+ const payload = idTokenPayloadSchema.safeParse(jwtPart(encodedPayload));
280
+ if (!payload.success) return Err(ID_TOKEN_INVALID);
281
+ const claims = payload.data;
282
+ const issuerHost = hostOf(claims.iss);
283
+ const destHost = hostOf(claims.dest);
284
+ if (
285
+ claims.exp * 1000 <= params.now
286
+ || claims.nbf * 1000 > params.now + ID_TOKEN_SKEW_MS
287
+ || claims.aud !== params.clientId
288
+ || issuerHost === undefined
289
+ || issuerHost !== destHost
290
+ || !validShopDomain(destHost)
291
+ ) return Err(ID_TOKEN_INVALID);
292
+ return Ok({ shop: destHost, userId: claims.sub });
293
+ }
294
+
295
+ /**
296
+ * Trade a verified ID token for an expiring offline token (the token exchange grant). Shopify answers
297
+ * a stale or invalid ID token with 400, a routine condition a fresh token fixes: it is
298
+ * `SHOPIFY_ID_TOKEN_INVALID` here, not a refusal of the app. Scopes the store did not grant are refused
299
+ * exactly as the code grant refuses them.
300
+ */
301
+ export async function exchangeIdToken(params: {
302
+ fetchImpl: typeof fetch;
303
+ origin: string;
304
+ clientId: string;
305
+ clientSecret: string;
306
+ idToken: string;
307
+ requiredScopes: readonly string[];
308
+ now: number;
309
+ }): Promise<Result<ShopifyCredentials, ChannelConnectorError>> {
310
+ const token = await postTokenEndpoint(params.fetchImpl, params.origin, {
311
+ client_id: params.clientId,
312
+ client_secret: params.clientSecret,
313
+ grant_type: "urn:ietf:params:oauth:grant-type:token-exchange",
314
+ subject_token: params.idToken,
315
+ subject_token_type: "urn:ietf:params:oauth:token-type:id_token",
316
+ requested_token_type: "urn:shopify:params:oauth:token-type:offline-access-token",
317
+ expiring: "1",
318
+ }, ID_TOKEN_INVALID);
319
+ if (!token.ok) return token;
320
+ const credentials = credentialsFrom(token.value, params.now, params.clientId);
321
+ const missing = missingScopes(credentials.grantedScopes, params.requiredScopes);
322
+ if (missing.length > 0) return oauthError("SHOPIFY_SCOPES_NOT_GRANTED", `The store did not grant: ${missing.join(", ")}.`);
323
+ return Ok(credentials);
324
+ }
325
+
326
+ /**
327
+ * A token from the client credentials grant: the app's own client id and secret, no code and no
328
+ * scope (Shopify ignores one). The token carries the scopes the store granted the app's installation.
329
+ * A refusal names its cause: `SHOPIFY_SHOP_NOT_PERMITTED` (another organization's app),
330
+ * `SHOPIFY_APP_NOT_INSTALLED`, or `SHOPIFY_REAUTHORIZATION_REQUIRED` for a client id or secret
331
+ * Shopify does not accept.
332
+ */
333
+ export async function mintClientCredentials(params: {
334
+ fetchImpl: typeof fetch;
335
+ origin: string;
336
+ clientId: string;
337
+ clientSecret: string;
338
+ now: number;
339
+ }): Promise<Result<ShopifyCredentials, ChannelConnectorError>> {
340
+ const token = await postTokenEndpoint(params.fetchImpl, params.origin, {
341
+ grant_type: "client_credentials",
342
+ client_id: params.clientId,
343
+ client_secret: params.clientSecret,
344
+ });
345
+ if (!token.ok) return token;
346
+ return Ok({ grant: "client_credentials", ...credentialsFrom(token.value, params.now, params.clientId) });
347
+ }
348
+
175
349
  /**
176
350
  * New credentials when the access token is within the refresh margin of expiry, `null` when the
177
- * current ones are good. A refresh token Shopify refuses means the merchant must reconnect.
351
+ * current ones are good. A client-credentials token is minted again; an authorization-code token is
352
+ * refreshed with its refresh token, and a refresh token Shopify refuses means the merchant must
353
+ * reconnect.
178
354
  */
179
355
  export async function refreshIfExpiring(params: {
180
356
  fetchImpl: typeof fetch;
@@ -192,6 +368,7 @@ export async function refreshIfExpiring(params: {
192
368
  const expiresAt = Date.parse(credentials.accessTokenExpiresAt);
193
369
  if (Number.isFinite(expiresAt) && expiresAt - params.now > ACCESS_TOKEN_REFRESH_MARGIN_MS) return Ok(null);
194
370
  }
371
+ if (credentials.grant === "client_credentials") return mintClientCredentials(params);
195
372
  if (credentials.refreshToken === undefined) return oauthError("SHOPIFY_REAUTHORIZATION_REQUIRED", "The store's access token expired and no refresh token is held; the store must be reconnected.");
196
373
  const token = await postTokenEndpoint(params.fetchImpl, params.origin, {
197
374
  client_id: params.clientId,
@@ -200,7 +377,7 @@ export async function refreshIfExpiring(params: {
200
377
  refresh_token: credentials.refreshToken,
201
378
  });
202
379
  if (!token.ok) return token;
203
- const refreshed = credentialsFrom(token.value, params.now);
380
+ const refreshed = credentialsFrom(token.value, params.now, params.clientId);
204
381
  // A refresh answer may omit the scope list; the grant did not change, so keep the one we hold.
205
382
  return Ok(refreshed.grantedScopes.length > 0 ? refreshed : { ...refreshed, grantedScopes: credentials.grantedScopes });
206
383
  }
package/src/webhooks.ts CHANGED
@@ -76,6 +76,194 @@ const COMPLIANCE: Record<string, Extract<ChannelEvent, { kind: "compliance.reque
76
76
  "shop/redact": "shop_redact",
77
77
  };
78
78
 
79
+ /** The topics whose payload names the shop that sent it, signed: `shop_domain`. */
80
+ export function isComplianceTopic(topic: string): boolean {
81
+ return topic in COMPLIANCE;
82
+ }
83
+
84
+ /** The topics `decodeShopifyWebhook` answers with a read of the shop's Admin API; every other decodes from its body. */
85
+ const READS_THE_STORE: ReadonlySet<string> = new Set(["inventory_levels/update"]);
86
+
87
+ export function decodeReadsTheStore(topic: string): boolean {
88
+ return READS_THE_STORE.has(topic);
89
+ }
90
+
91
+ function isPlainRecord(value: unknown): value is Record<string, unknown> {
92
+ return typeof value === "object" && value !== null && !Array.isArray(value);
93
+ }
94
+
95
+ /** Keeps an identifier/scalar field if present; replaces non-scalar malformed values with `false` so validation still rejects them without retaining PII. */
96
+ function keepId(value: unknown): string | number | boolean | null | undefined {
97
+ if (value === undefined || value === null) return value;
98
+ return typeof value === "string" || typeof value === "number" ? value : false;
99
+ }
100
+
101
+ function keepIdList(value: unknown): unknown {
102
+ if (value === undefined) return undefined;
103
+ if (!Array.isArray(value)) return false;
104
+ return value.map((entry) => (typeof entry === "string" || typeof entry === "number" ? entry : false));
105
+ }
106
+
107
+ function keepString(value: unknown): string | boolean | null | undefined {
108
+ if (value === undefined || value === null) return value;
109
+ return typeof value === "string" ? value : false;
110
+ }
111
+
112
+ /**
113
+ * Keeps only the fields `decodeShopifyWebhook` and compliance handlers read before a delivery is
114
+ * persisted in `commerce_jobs.input` — stripping shopper names, shipping/billing addresses, phone
115
+ * numbers and any other extra webhook fields while preserving malformed-shape failures.
116
+ */
117
+ export function minimizeShopifyWebhookPayload(topic: string, data: unknown): unknown {
118
+ if (topic === "app/uninstalled") return {};
119
+ if (!isPlainRecord(data)) return null;
120
+
121
+ if (topic === "shop/redact") {
122
+ const out: Record<string, unknown> = {};
123
+ if ("shop_id" in data) out.shop_id = keepId(data.shop_id);
124
+ if ("shop_domain" in data) out.shop_domain = keepString(data.shop_domain);
125
+ return out;
126
+ }
127
+
128
+ if (topic === "customers/redact" || topic === "customers/data_request") {
129
+ const out: Record<string, unknown> = {};
130
+ if ("shop_id" in data) out.shop_id = keepId(data.shop_id);
131
+ if ("shop_domain" in data) out.shop_domain = keepString(data.shop_domain);
132
+ if ("email" in data) out.email = keepString(data.email);
133
+ if ("customer_id" in data) out.customer_id = keepId(data.customer_id);
134
+ if ("customer" in data) {
135
+ if (data.customer === null) out.customer = null;
136
+ else if (isPlainRecord(data.customer)) {
137
+ const customer: Record<string, unknown> = {};
138
+ if ("id" in data.customer) customer.id = keepId(data.customer.id);
139
+ if ("email" in data.customer) customer.email = keepString(data.customer.email);
140
+ out.customer = customer;
141
+ } else {
142
+ out.customer = false;
143
+ }
144
+ }
145
+ if ("orders_to_redact" in data) out.orders_to_redact = keepIdList(data.orders_to_redact);
146
+ if ("orders_requested" in data) out.orders_requested = keepIdList(data.orders_requested);
147
+ if ("data_request" in data) {
148
+ if (data.data_request === null) out.data_request = null;
149
+ else if (isPlainRecord(data.data_request)) {
150
+ out.data_request = "id" in data.data_request ? { id: keepId(data.data_request.id) } : {};
151
+ } else {
152
+ out.data_request = false;
153
+ }
154
+ }
155
+ return out;
156
+ }
157
+
158
+ if (topic === "orders/cancelled") {
159
+ return "id" in data ? { id: keepId(data.id) } : {};
160
+ }
161
+
162
+ if (topic === "orders/fulfilled" || topic === "orders/partially_fulfilled") {
163
+ const out: Record<string, unknown> = {};
164
+ if ("id" in data) out.id = keepId(data.id);
165
+ if ("fulfillments" in data) {
166
+ if (!Array.isArray(data.fulfillments)) {
167
+ out.fulfillments = false;
168
+ } else {
169
+ out.fulfillments = data.fulfillments.map((parcel) => {
170
+ if (!isPlainRecord(parcel)) return false;
171
+ const minimal: Record<string, unknown> = {};
172
+ if ("id" in parcel) minimal.id = keepId(parcel.id);
173
+ if ("status" in parcel) minimal.status = keepString(parcel.status);
174
+ if ("tracking_company" in parcel) minimal.tracking_company = keepString(parcel.tracking_company);
175
+ if ("tracking_number" in parcel) minimal.tracking_number = keepString(parcel.tracking_number);
176
+ if ("tracking_url" in parcel) minimal.tracking_url = keepString(parcel.tracking_url);
177
+ if ("line_items" in parcel) {
178
+ minimal.line_items = Array.isArray(parcel.line_items)
179
+ ? parcel.line_items.map((line) => (isPlainRecord(line)
180
+ ? {
181
+ ...("variant_id" in line ? { variant_id: keepId(line.variant_id) } : {}),
182
+ ...("quantity" in line ? { quantity: typeof line.quantity === "number" ? line.quantity : false } : {}),
183
+ }
184
+ : false))
185
+ : false;
186
+ }
187
+ return minimal;
188
+ });
189
+ }
190
+ }
191
+ return out;
192
+ }
193
+
194
+ if (topic === "refunds/create") {
195
+ const out: Record<string, unknown> = {};
196
+ if ("id" in data) out.id = keepId(data.id);
197
+ if ("order_id" in data) out.order_id = keepId(data.order_id);
198
+ if ("refund_line_items" in data) {
199
+ out.refund_line_items = Array.isArray(data.refund_line_items)
200
+ ? data.refund_line_items.map((entry) => {
201
+ if (!isPlainRecord(entry)) return false;
202
+ const minimal: Record<string, unknown> = {};
203
+ if ("quantity" in entry) minimal.quantity = typeof entry.quantity === "number" ? entry.quantity : false;
204
+ if ("line_item" in entry) {
205
+ minimal.line_item = isPlainRecord(entry.line_item)
206
+ ? {
207
+ ...("variant_id" in entry.line_item ? { variant_id: keepId(entry.line_item.variant_id) } : {}),
208
+ ...("product_id" in entry.line_item ? { product_id: keepId(entry.line_item.product_id) } : {}),
209
+ }
210
+ : false;
211
+ }
212
+ return minimal;
213
+ })
214
+ : false;
215
+ }
216
+ if ("transactions" in data) {
217
+ out.transactions = Array.isArray(data.transactions)
218
+ ? data.transactions.map((tx) => (isPlainRecord(tx)
219
+ ? {
220
+ ...("kind" in tx ? { kind: keepString(tx.kind) } : {}),
221
+ ...("status" in tx ? { status: keepString(tx.status) } : {}),
222
+ ...("amount" in tx ? { amount: keepId(tx.amount) } : {}),
223
+ ...("currency" in tx ? { currency: keepString(tx.currency) } : {}),
224
+ }
225
+ : false))
226
+ : false;
227
+ }
228
+ if ("refund_shipping_lines" in data) {
229
+ out.refund_shipping_lines = Array.isArray(data.refund_shipping_lines)
230
+ ? data.refund_shipping_lines.map((line) => {
231
+ if (!isPlainRecord(line)) return false;
232
+ const set = isPlainRecord(line.subtotal_amount_set) ? line.subtotal_amount_set : null;
233
+ const shopMoney = set && isPlainRecord(set.shop_money) ? set.shop_money : null;
234
+ return shopMoney
235
+ ? {
236
+ subtotal_amount_set: {
237
+ shop_money: {
238
+ ...("amount" in shopMoney ? { amount: keepId(shopMoney.amount) } : {}),
239
+ ...("currency_code" in shopMoney ? { currency_code: keepString(shopMoney.currency_code) } : {}),
240
+ },
241
+ },
242
+ }
243
+ : false;
244
+ })
245
+ : false;
246
+ }
247
+ return out;
248
+ }
249
+
250
+ if (topic === "inventory_levels/update") {
251
+ return "inventory_item_id" in data ? { inventory_item_id: keepId(data.inventory_item_id) } : {};
252
+ }
253
+
254
+ if (
255
+ topic === "products/create"
256
+ || topic === "products/update"
257
+ || topic === "products/delete"
258
+ || topic in RETURN_STATUS
259
+ || topic.startsWith("orders/")
260
+ ) {
261
+ return "id" in data ? { id: keepId(data.id) } : {};
262
+ }
263
+
264
+ return {};
265
+ }
266
+
79
267
  function malformed(topic: string, error: z.ZodError): Result<never, ChannelConnectorError> {
80
268
  return Err({ code: "SHOPIFY_WEBHOOK_MALFORMED", message: `A Shopify ${topic} delivery did not parse: ${error.message}`, retriable: false });
81
269
  }