@decocms/apps-shopify 7.71.6 → 8.0.0-next.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/package.json +4 -4
- package/src/index.ts +10 -1
- package/src/utils/graphqlOperationName.ts +2 -67
- package/src/utils/operationRouter.ts +1 -1
- package/src/v8/client.test.ts +136 -0
- package/src/v8/client.ts +125 -0
- package/src/v8/graphqlOperationName.test.ts +80 -0
- package/src/v8/graphqlOperationName.ts +67 -0
- package/src/utils/__tests__/graphqlOperationName.test.ts +0 -80
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@decocms/apps-shopify",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "8.0.0-next.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Deco commerce app: Shopify integration",
|
|
6
6
|
"repository": {
|
|
@@ -31,9 +31,9 @@
|
|
|
31
31
|
"lint:unused": "knip"
|
|
32
32
|
},
|
|
33
33
|
"dependencies": {
|
|
34
|
-
"@decocms/blocks": "
|
|
35
|
-
"@decocms/apps-commerce": "
|
|
36
|
-
"@decocms/tanstack": "
|
|
34
|
+
"@decocms/blocks": "8.0.0-next.0",
|
|
35
|
+
"@decocms/apps-commerce": "8.0.0-next.0",
|
|
36
|
+
"@decocms/tanstack": "8.0.0-next.0"
|
|
37
37
|
},
|
|
38
38
|
"peerDependencies": {
|
|
39
39
|
"react": "^19.0.0",
|
package/src/index.ts
CHANGED
|
@@ -34,10 +34,19 @@ export { default as userLoader } from "./loaders/user";
|
|
|
34
34
|
export { getCartCookie, setCartCookie } from "./utils/cart";
|
|
35
35
|
// Cookie utils
|
|
36
36
|
export { getCookies, setCookie } from "./utils/cookies";
|
|
37
|
-
export { extractGraphqlOperationName } from "./
|
|
37
|
+
export { extractGraphqlOperationName } from "./v8/graphqlOperationName";
|
|
38
38
|
export {
|
|
39
39
|
type CreateShopifyFetchOptions,
|
|
40
40
|
createShopifyFetch,
|
|
41
41
|
} from "./utils/instrumentedFetch";
|
|
42
42
|
export { shopifyOperationRouter } from "./utils/operationRouter";
|
|
43
43
|
export { getUserCookie, setUserCookie } from "./utils/user";
|
|
44
|
+
|
|
45
|
+
// The next-major upstream client (/next/upstream-clients). Everything above is
|
|
46
|
+
// the v7 surface, kept for v7 consumers until v7 is dropped.
|
|
47
|
+
export {
|
|
48
|
+
createShopifyClient,
|
|
49
|
+
type ShopifyClient,
|
|
50
|
+
type ShopifyClientConfig,
|
|
51
|
+
ShopifyError,
|
|
52
|
+
} from "./v8/client";
|
|
@@ -1,67 +1,2 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
*
|
|
4
|
-
* Used at the Shopify GraphQL client layer to stamp `init.operation`
|
|
5
|
-
* on the outbound fetch. The framework then suffixes the integration
|
|
6
|
-
* name (`shopify.<operation>`) onto the span and uses the same string
|
|
7
|
-
* as the `fetch.operation` attribute + histogram label.
|
|
8
|
-
*
|
|
9
|
-
* Resolution order:
|
|
10
|
-
*
|
|
11
|
-
* 1. An explicit `operationName` argument (e.g. when the client
|
|
12
|
-
* received one alongside a multi-operation document) wins.
|
|
13
|
-
* 2. If the document has exactly one named operation, that name
|
|
14
|
-
* is used.
|
|
15
|
-
* 3. If the document has zero or many anonymous operations, we
|
|
16
|
-
* return `undefined` so the caller can fall back (typically to
|
|
17
|
-
* the URL-derived `storefront.graphql` / `admin.graphql`).
|
|
18
|
-
*
|
|
19
|
-
* The parser is deliberately a small regex pass, not a full GraphQL
|
|
20
|
-
* tokenizer:
|
|
21
|
-
*
|
|
22
|
-
* - GraphQL operation definitions live at the top level of the
|
|
23
|
-
* document, never nested inside other operations, fragments, or
|
|
24
|
-
* selection sets, so positional context isn't required to find
|
|
25
|
-
* them — only to not match the literal words `query` /
|
|
26
|
-
* `mutation` / `subscription` inside string values.
|
|
27
|
-
* - We strip block strings (`""" … """`), string literals
|
|
28
|
-
* (`"…"`), and `# …` comments before matching, which is enough
|
|
29
|
-
* to make false-positive matches inside comments / docs vanish.
|
|
30
|
-
*
|
|
31
|
-
* If a Shopify operation is ever sufficiently mis-named to break
|
|
32
|
-
* this (unlikely, since the storefront SDK names them deliberately),
|
|
33
|
-
* the caller can always set `init.operation` explicitly.
|
|
34
|
-
*/
|
|
35
|
-
|
|
36
|
-
const OPERATION_RE = /\b(?:query|mutation|subscription)\s+([A-Za-z_][A-Za-z0-9_]*)/g;
|
|
37
|
-
|
|
38
|
-
const stripCommentsAndStrings = (doc: string): string =>
|
|
39
|
-
doc
|
|
40
|
-
.replace(/"""[\s\S]*?"""/g, '""')
|
|
41
|
-
.replace(/"(?:\\.|[^"\\])*"/g, '""')
|
|
42
|
-
.replace(/#[^\n]*/g, "");
|
|
43
|
-
|
|
44
|
-
export function extractGraphqlOperationName(
|
|
45
|
-
document: string,
|
|
46
|
-
explicit?: string,
|
|
47
|
-
): string | undefined {
|
|
48
|
-
if (explicit) return explicit;
|
|
49
|
-
if (!document) return undefined;
|
|
50
|
-
|
|
51
|
-
const stripped = stripCommentsAndStrings(document);
|
|
52
|
-
const names: string[] = [];
|
|
53
|
-
|
|
54
|
-
OPERATION_RE.lastIndex = 0;
|
|
55
|
-
for (
|
|
56
|
-
let match = OPERATION_RE.exec(stripped);
|
|
57
|
-
match !== null;
|
|
58
|
-
match = OPERATION_RE.exec(stripped)
|
|
59
|
-
) {
|
|
60
|
-
const [, name] = match;
|
|
61
|
-
if (name) names.push(name);
|
|
62
|
-
if (names.length > 1) break;
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
if (names.length === 1) return names[0];
|
|
66
|
-
return undefined;
|
|
67
|
-
}
|
|
1
|
+
// Moved to the v8 client tree; re-exported here for the v7 modules.
|
|
2
|
+
export { extractGraphqlOperationName } from "../v8/graphqlOperationName";
|
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
* hitting, not what the call actually does. The semantic operation
|
|
12
12
|
* name lives in the GraphQL document itself (`query Foo { ... }`),
|
|
13
13
|
* and is extracted by `extractGraphqlOperationName` (see
|
|
14
|
-
*
|
|
14
|
+
* `../v8/graphqlOperationName.ts`) at the client layer and stamped as
|
|
15
15
|
* `init.operation`, which always wins over this router.
|
|
16
16
|
*
|
|
17
17
|
* So this router exists for:
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
// @vitest-environment node
|
|
2
|
+
/**
|
|
3
|
+
* createShopifyClient (/next/upstream-clients#write-a-client): every request
|
|
4
|
+
* goes through the instrumented fetch as provider "shopify", labeled with the
|
|
5
|
+
* GraphQL operation name, and errors carry no bodies or tokens.
|
|
6
|
+
*/
|
|
7
|
+
import { beforeEach, describe, expect, it, vi } from "vitest";
|
|
8
|
+
|
|
9
|
+
const seen = vi.hoisted(() => ({
|
|
10
|
+
options: [] as unknown[],
|
|
11
|
+
operations: [] as (string | undefined)[],
|
|
12
|
+
}));
|
|
13
|
+
|
|
14
|
+
vi.mock("@decocms/blocks/fetch", async (importOriginal) => {
|
|
15
|
+
const real = await importOriginal<typeof import("@decocms/blocks/fetch")>();
|
|
16
|
+
return {
|
|
17
|
+
createInstrumentedFetch: (options: Parameters<typeof real.createInstrumentedFetch>[0]) => {
|
|
18
|
+
seen.options.push(options);
|
|
19
|
+
const request = real.createInstrumentedFetch(options);
|
|
20
|
+
return (input: string | URL | Request, init?: RequestInit & { operation?: string }) => {
|
|
21
|
+
seen.operations.push(init?.operation);
|
|
22
|
+
return request(input, init);
|
|
23
|
+
};
|
|
24
|
+
},
|
|
25
|
+
};
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
import { createShopifyClient, ShopifyError } from "./client";
|
|
29
|
+
|
|
30
|
+
function upstream(body: unknown, status = 200) {
|
|
31
|
+
return vi.fn(
|
|
32
|
+
async (_input: string | URL | Request, _init?: RequestInit) =>
|
|
33
|
+
new Response(JSON.stringify(body), { status }),
|
|
34
|
+
);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const config = { storeName: "acme", storefrontAccessToken: "sf-token", apiVersion: "2026-07" };
|
|
38
|
+
|
|
39
|
+
beforeEach(() => {
|
|
40
|
+
seen.options.length = 0;
|
|
41
|
+
seen.operations.length = 0;
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
describe("createShopifyClient", () => {
|
|
45
|
+
it("posts to the Storefront API through the instrumented fetch, with no retries or circuit breaker", async () => {
|
|
46
|
+
const fetch = upstream({ data: { product: { id: "1" } } });
|
|
47
|
+
const shopify = createShopifyClient(config, { fetch });
|
|
48
|
+
|
|
49
|
+
const data = await shopify.storefront.query<{ product: { id: string } }>(
|
|
50
|
+
"query ProductByHandle($handle: String!) { product(handle: $handle) { id } }",
|
|
51
|
+
{ handle: "linen-shirt" },
|
|
52
|
+
{ headers: { "Shopify-Storefront-Buyer-IP": "203.0.113.7" } },
|
|
53
|
+
);
|
|
54
|
+
|
|
55
|
+
expect(data).toEqual({ product: { id: "1" } });
|
|
56
|
+
expect(seen.options).toEqual([{ provider: "shopify", fetch }]);
|
|
57
|
+
expect(seen.operations).toEqual(["ProductByHandle"]);
|
|
58
|
+
const [url, init] = fetch.mock.calls[0] ?? [];
|
|
59
|
+
expect(url).toBe("https://acme.myshopify.com/api/2026-07/graphql.json");
|
|
60
|
+
expect(init?.method).toBe("POST");
|
|
61
|
+
expect(init?.headers).toMatchObject({
|
|
62
|
+
"x-shopify-storefront-access-token": "sf-token",
|
|
63
|
+
"Shopify-Storefront-Buyer-IP": "203.0.113.7",
|
|
64
|
+
});
|
|
65
|
+
expect(JSON.parse(String(init?.body))).toEqual({
|
|
66
|
+
query: "query ProductByHandle($handle: String!) { product(handle: $handle) { id } }",
|
|
67
|
+
variables: { handle: "linen-shirt" },
|
|
68
|
+
});
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
it("labels an unnamed document by its API surface", async () => {
|
|
72
|
+
const fetch = upstream({ data: { shop: { name: "Acme" } } });
|
|
73
|
+
const shopify = createShopifyClient(
|
|
74
|
+
{ ...config, adminAccessToken: "admin-token", apiVersion: "2025-07" },
|
|
75
|
+
{ fetch },
|
|
76
|
+
);
|
|
77
|
+
await shopify.storefront.query("{ shop { name } }");
|
|
78
|
+
await shopify.admin.query("{ shop { name } }");
|
|
79
|
+
|
|
80
|
+
expect(seen.operations).toEqual(["storefront.graphql", "admin.graphql"]);
|
|
81
|
+
expect(fetch.mock.calls[1]?.[0]).toBe(
|
|
82
|
+
"https://acme.myshopify.com/admin/api/2025-07/graphql.json",
|
|
83
|
+
);
|
|
84
|
+
expect(fetch.mock.calls[1]?.[1]?.headers).toMatchObject({
|
|
85
|
+
"x-shopify-access-token": "admin-token",
|
|
86
|
+
});
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
it("refuses admin calls without an admin token, without sending anything", async () => {
|
|
90
|
+
const fetch = upstream({ data: {} });
|
|
91
|
+
const shopify = createShopifyClient(config, { fetch });
|
|
92
|
+
await expect(shopify.admin.query("{ shop { name } }")).rejects.toThrow(/adminAccessToken/);
|
|
93
|
+
expect(fetch).not.toHaveBeenCalled();
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
it("reports HTTP failures by operation and status, never the body or token", async () => {
|
|
97
|
+
const fetch = upstream({ errors: "secret upstream detail sf-token" }, 401);
|
|
98
|
+
const shopify = createShopifyClient(config, { fetch });
|
|
99
|
+
const error = (await shopify.storefront
|
|
100
|
+
.query("query Cart { cart { id } }")
|
|
101
|
+
.catch((e: unknown) => e)) as ShopifyError;
|
|
102
|
+
|
|
103
|
+
expect(error).toBeInstanceOf(ShopifyError);
|
|
104
|
+
expect(error).toMatchObject({ operation: "Cart", status: 401, codes: [] });
|
|
105
|
+
expect(error.message).toBe("shopify Cart failed with HTTP 401");
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
it("reports a non-JSON body as INVALID_JSON, never quoting the body", async () => {
|
|
109
|
+
const fetch = vi.fn(async () => new Response("<html>sf-token</html>", { status: 200 }));
|
|
110
|
+
const shopify = createShopifyClient(config, { fetch });
|
|
111
|
+
const error = (await shopify.storefront
|
|
112
|
+
.query("query Cart { cart { id } }")
|
|
113
|
+
.catch((e: unknown) => e)) as ShopifyError;
|
|
114
|
+
|
|
115
|
+
expect(error).toBeInstanceOf(ShopifyError);
|
|
116
|
+
expect(error).toMatchObject({ operation: "Cart", status: 200, codes: ["INVALID_JSON"] });
|
|
117
|
+
expect(error.message).not.toContain("sf-token");
|
|
118
|
+
expect(error.message).not.toContain("<html");
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
it("reports GraphQL errors by their codes, not their messages", async () => {
|
|
122
|
+
const fetch = upstream({
|
|
123
|
+
errors: [
|
|
124
|
+
{ message: "Throttled for customer@example.com", extensions: { code: "THROTTLED" } },
|
|
125
|
+
{ message: "again", extensions: { code: "THROTTLED" } },
|
|
126
|
+
],
|
|
127
|
+
});
|
|
128
|
+
const shopify = createShopifyClient(config, { fetch });
|
|
129
|
+
const error = (await shopify.storefront
|
|
130
|
+
.query("query Cart { cart { id } }")
|
|
131
|
+
.catch((e: unknown) => e)) as ShopifyError;
|
|
132
|
+
|
|
133
|
+
expect(error).toMatchObject({ operation: "Cart", status: 200, codes: ["THROTTLED"] });
|
|
134
|
+
expect(error.message).not.toContain("customer@example.com");
|
|
135
|
+
});
|
|
136
|
+
});
|
package/src/v8/client.ts
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Shopify upstream client (/next/upstream-clients): the Storefront and
|
|
3
|
+
* Admin GraphQL APIs over the framework's instrumented fetch, and nothing
|
|
4
|
+
* else. Converters to commerce types, cart and customer flows, hooks and
|
|
5
|
+
* loaders live in the Shopify platform template and site code.
|
|
6
|
+
*
|
|
7
|
+
* Every request is measured as provider "shopify", labeled with the GraphQL
|
|
8
|
+
* operation's own name (`query ProductByHandle { … }` → "ProductByHandle"),
|
|
9
|
+
* or "storefront.graphql" / "admin.graphql" for an unnamed document. Retries
|
|
10
|
+
* and the circuit breaker stay off, as for every client but VTEX's; caching
|
|
11
|
+
* is the framework binding's job.
|
|
12
|
+
*/
|
|
13
|
+
import { createInstrumentedFetch } from "@decocms/blocks/fetch";
|
|
14
|
+
import { extractGraphqlOperationName } from "./graphqlOperationName";
|
|
15
|
+
|
|
16
|
+
export interface ShopifyClientConfig {
|
|
17
|
+
/** The store's subdomain: "acme" for acme.myshopify.com. */
|
|
18
|
+
storeName: string;
|
|
19
|
+
/** Storefront API access token. */
|
|
20
|
+
storefrontAccessToken: string;
|
|
21
|
+
/** Admin API access token; `admin` is only available when it's set. */
|
|
22
|
+
adminAccessToken?: string;
|
|
23
|
+
/** The Shopify API version, e.g. "2026-07". The site owns it, so there is no default to go stale. */
|
|
24
|
+
apiVersion: string;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
interface ShopifyRequestOptions {
|
|
28
|
+
/** Extra request headers, e.g. `Shopify-Storefront-Buyer-IP`. */
|
|
29
|
+
headers?: Record<string, string>;
|
|
30
|
+
signal?: AbortSignal;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** One GraphQL endpoint: send a document, get its `data` back. */
|
|
34
|
+
interface ShopifyGraphQL {
|
|
35
|
+
query<T, V extends Record<string, unknown> = Record<string, unknown>>(
|
|
36
|
+
document: string,
|
|
37
|
+
variables?: V,
|
|
38
|
+
options?: ShopifyRequestOptions,
|
|
39
|
+
): Promise<T>;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export interface ShopifyClient {
|
|
43
|
+
storefront: ShopifyGraphQL;
|
|
44
|
+
/** Throws when called without `adminAccessToken` in the config. */
|
|
45
|
+
admin: ShopifyGraphQL;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** A failed request. Carries the operation, the HTTP status and Shopify's error codes; never bodies or tokens. */
|
|
49
|
+
export class ShopifyError extends Error {
|
|
50
|
+
constructor(
|
|
51
|
+
readonly operation: string,
|
|
52
|
+
readonly status: number,
|
|
53
|
+
readonly codes: string[] = [],
|
|
54
|
+
) {
|
|
55
|
+
super(
|
|
56
|
+
codes.length > 0
|
|
57
|
+
? `shopify ${operation} returned GraphQL errors (${codes.join(", ")})`
|
|
58
|
+
: `shopify ${operation} failed with HTTP ${status}`,
|
|
59
|
+
);
|
|
60
|
+
this.name = "ShopifyError";
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export function createShopifyClient(
|
|
65
|
+
config: ShopifyClientConfig,
|
|
66
|
+
options: { fetch?: typeof globalThis.fetch } = {},
|
|
67
|
+
): ShopifyClient {
|
|
68
|
+
const request = createInstrumentedFetch({ provider: "shopify", fetch: options.fetch });
|
|
69
|
+
const origin = `https://${config.storeName}.myshopify.com`;
|
|
70
|
+
const version = config.apiVersion;
|
|
71
|
+
|
|
72
|
+
const endpoint = (surface: "storefront" | "admin", url: string, auth: Record<string, string>) =>
|
|
73
|
+
({
|
|
74
|
+
async query(document, variables, { headers, signal } = {}) {
|
|
75
|
+
const operation = extractGraphqlOperationName(document) ?? `${surface}.graphql`;
|
|
76
|
+
const response = await request(url, {
|
|
77
|
+
operation,
|
|
78
|
+
method: "POST",
|
|
79
|
+
headers: { "content-type": "application/json", ...headers, ...auth },
|
|
80
|
+
body: JSON.stringify({ query: document, variables }),
|
|
81
|
+
signal,
|
|
82
|
+
});
|
|
83
|
+
if (!response.ok) {
|
|
84
|
+
void response.body?.cancel().catch(() => {});
|
|
85
|
+
throw new ShopifyError(operation, response.status);
|
|
86
|
+
}
|
|
87
|
+
// A non-JSON body (an HTML error page) must not reach the error: the
|
|
88
|
+
// SyntaxError's message quotes the start of the body.
|
|
89
|
+
let body: { data?: unknown; errors?: { extensions?: { code?: unknown } }[] };
|
|
90
|
+
try {
|
|
91
|
+
body = await response.json();
|
|
92
|
+
} catch {
|
|
93
|
+
throw new ShopifyError(operation, response.status, ["INVALID_JSON"]);
|
|
94
|
+
}
|
|
95
|
+
// Partial data alongside errors is rejected as a whole, deliberately:
|
|
96
|
+
// a thin client doesn't guess which fields are still trustworthy.
|
|
97
|
+
if (body.errors?.length || body.data == null) {
|
|
98
|
+
const codes = body.errors?.length
|
|
99
|
+
? body.errors.map((e) =>
|
|
100
|
+
typeof e.extensions?.code === "string" ? e.extensions.code : "UNKNOWN",
|
|
101
|
+
)
|
|
102
|
+
: ["MISSING_DATA"];
|
|
103
|
+
throw new ShopifyError(operation, response.status, [...new Set(codes)]);
|
|
104
|
+
}
|
|
105
|
+
return body.data as never;
|
|
106
|
+
},
|
|
107
|
+
}) satisfies ShopifyGraphQL;
|
|
108
|
+
|
|
109
|
+
const adminToken = config.adminAccessToken;
|
|
110
|
+
return {
|
|
111
|
+
storefront: endpoint("storefront", `${origin}/api/${version}/graphql.json`, {
|
|
112
|
+
"x-shopify-storefront-access-token": config.storefrontAccessToken,
|
|
113
|
+
}),
|
|
114
|
+
admin: adminToken
|
|
115
|
+
? endpoint("admin", `${origin}/admin/api/${version}/graphql.json`, {
|
|
116
|
+
"x-shopify-access-token": adminToken,
|
|
117
|
+
})
|
|
118
|
+
: {
|
|
119
|
+
query: () =>
|
|
120
|
+
Promise.reject(
|
|
121
|
+
new Error("shopify admin: pass adminAccessToken to createShopifyClient"),
|
|
122
|
+
),
|
|
123
|
+
},
|
|
124
|
+
};
|
|
125
|
+
}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { describe, expect, it } from "vitest";
|
|
2
|
+
import { extractGraphqlOperationName } from "./graphqlOperationName";
|
|
3
|
+
|
|
4
|
+
describe("extractGraphqlOperationName", () => {
|
|
5
|
+
it("returns the explicit name when provided, regardless of body content", () => {
|
|
6
|
+
expect(extractGraphqlOperationName("query Whatever { x }", "ForcedName")).toBe("ForcedName");
|
|
7
|
+
expect(extractGraphqlOperationName("", "Override")).toBe("Override");
|
|
8
|
+
});
|
|
9
|
+
|
|
10
|
+
it("extracts a single named query", () => {
|
|
11
|
+
expect(
|
|
12
|
+
extractGraphqlOperationName("query ProductBySlug($slug: String!) { product { id } }"),
|
|
13
|
+
).toBe("ProductBySlug");
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
it("extracts a single named mutation", () => {
|
|
17
|
+
expect(
|
|
18
|
+
extractGraphqlOperationName("mutation CartLinesAdd($cartId: ID!) { cartLinesAdd { } }"),
|
|
19
|
+
).toBe("CartLinesAdd");
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
it("extracts a single named subscription", () => {
|
|
23
|
+
expect(extractGraphqlOperationName("subscription OrderEvents { orderUpdated { id } }")).toBe(
|
|
24
|
+
"OrderEvents",
|
|
25
|
+
);
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
it("returns undefined for anonymous operations", () => {
|
|
29
|
+
expect(extractGraphqlOperationName("{ product { id } }")).toBeUndefined();
|
|
30
|
+
expect(extractGraphqlOperationName("query { product { id } }")).toBeUndefined();
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
it("returns undefined when document has more than one named operation (caller must disambiguate)", () => {
|
|
34
|
+
const multi = `
|
|
35
|
+
query OpA { a }
|
|
36
|
+
query OpB { b }
|
|
37
|
+
`;
|
|
38
|
+
expect(extractGraphqlOperationName(multi)).toBeUndefined();
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
it("ignores the words query/mutation/subscription inside string literals", () => {
|
|
42
|
+
const docWithStringy = `query RealName { thing(arg: "this query mutation subscription is a string") }`;
|
|
43
|
+
expect(extractGraphqlOperationName(docWithStringy)).toBe("RealName");
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
it("ignores the words inside block strings (triple-quoted)", () => {
|
|
47
|
+
const doc = `
|
|
48
|
+
"""
|
|
49
|
+
This block string mentions query Inner and mutation Inner2.
|
|
50
|
+
"""
|
|
51
|
+
query OuterReal { x }
|
|
52
|
+
`;
|
|
53
|
+
expect(extractGraphqlOperationName(doc)).toBe("OuterReal");
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
it("ignores the words inside # comments", () => {
|
|
57
|
+
const doc = `
|
|
58
|
+
# query CommentedOut { x }
|
|
59
|
+
query Active { y }
|
|
60
|
+
`;
|
|
61
|
+
expect(extractGraphqlOperationName(doc)).toBe("Active");
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
it("returns undefined on an empty / nullish body", () => {
|
|
65
|
+
expect(extractGraphqlOperationName("")).toBeUndefined();
|
|
66
|
+
expect(extractGraphqlOperationName(" \n\t ")).toBeUndefined();
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
it("handles a real-world Shopify storefront query shape", () => {
|
|
70
|
+
const doc = `
|
|
71
|
+
query ProductDetails($handle: String!, $country: CountryCode!) @inContext(country: $country) {
|
|
72
|
+
product(handle: $handle) {
|
|
73
|
+
id
|
|
74
|
+
title
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
`;
|
|
78
|
+
expect(extractGraphqlOperationName(doc)).toBe("ProductDetails");
|
|
79
|
+
});
|
|
80
|
+
});
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Extract a semantic operation name from a GraphQL document.
|
|
3
|
+
*
|
|
4
|
+
* Used at the Shopify GraphQL client layer to stamp `init.operation`
|
|
5
|
+
* on the outbound fetch. The framework then suffixes the integration
|
|
6
|
+
* name (`shopify.<operation>`) onto the span and uses the same string
|
|
7
|
+
* as the `fetch.operation` attribute + histogram label.
|
|
8
|
+
*
|
|
9
|
+
* Resolution order:
|
|
10
|
+
*
|
|
11
|
+
* 1. An explicit `operationName` argument (e.g. when the client
|
|
12
|
+
* received one alongside a multi-operation document) wins.
|
|
13
|
+
* 2. If the document has exactly one named operation, that name
|
|
14
|
+
* is used.
|
|
15
|
+
* 3. If the document has zero or many anonymous operations, we
|
|
16
|
+
* return `undefined` so the caller can fall back (typically to
|
|
17
|
+
* the URL-derived `storefront.graphql` / `admin.graphql`).
|
|
18
|
+
*
|
|
19
|
+
* The parser is deliberately a small regex pass, not a full GraphQL
|
|
20
|
+
* tokenizer:
|
|
21
|
+
*
|
|
22
|
+
* - GraphQL operation definitions live at the top level of the
|
|
23
|
+
* document, never nested inside other operations, fragments, or
|
|
24
|
+
* selection sets, so positional context isn't required to find
|
|
25
|
+
* them — only to not match the literal words `query` /
|
|
26
|
+
* `mutation` / `subscription` inside string values.
|
|
27
|
+
* - We strip block strings (`""" … """`), string literals
|
|
28
|
+
* (`"…"`), and `# …` comments before matching, which is enough
|
|
29
|
+
* to make false-positive matches inside comments / docs vanish.
|
|
30
|
+
*
|
|
31
|
+
* If a Shopify operation is ever sufficiently mis-named to break
|
|
32
|
+
* this (unlikely, since the storefront SDK names them deliberately),
|
|
33
|
+
* the caller can always set `init.operation` explicitly.
|
|
34
|
+
*/
|
|
35
|
+
|
|
36
|
+
const OPERATION_RE = /\b(?:query|mutation|subscription)\s+([A-Za-z_][A-Za-z0-9_]*)/g;
|
|
37
|
+
|
|
38
|
+
const stripCommentsAndStrings = (doc: string): string =>
|
|
39
|
+
doc
|
|
40
|
+
.replace(/"""[\s\S]*?"""/g, '""')
|
|
41
|
+
.replace(/"(?:\\.|[^"\\])*"/g, '""')
|
|
42
|
+
.replace(/#[^\n]*/g, "");
|
|
43
|
+
|
|
44
|
+
export function extractGraphqlOperationName(
|
|
45
|
+
document: string,
|
|
46
|
+
explicit?: string,
|
|
47
|
+
): string | undefined {
|
|
48
|
+
if (explicit) return explicit;
|
|
49
|
+
if (!document) return undefined;
|
|
50
|
+
|
|
51
|
+
const stripped = stripCommentsAndStrings(document);
|
|
52
|
+
const names: string[] = [];
|
|
53
|
+
|
|
54
|
+
OPERATION_RE.lastIndex = 0;
|
|
55
|
+
for (
|
|
56
|
+
let match = OPERATION_RE.exec(stripped);
|
|
57
|
+
match !== null;
|
|
58
|
+
match = OPERATION_RE.exec(stripped)
|
|
59
|
+
) {
|
|
60
|
+
const [, name] = match;
|
|
61
|
+
if (name) names.push(name);
|
|
62
|
+
if (names.length > 1) break;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
if (names.length === 1) return names[0];
|
|
66
|
+
return undefined;
|
|
67
|
+
}
|
|
@@ -1,80 +0,0 @@
|
|
|
1
|
-
import { describe, expect, it } from "vitest";
|
|
2
|
-
import { extractGraphqlOperationName } from "../graphqlOperationName";
|
|
3
|
-
|
|
4
|
-
describe("extractGraphqlOperationName", () => {
|
|
5
|
-
it("returns the explicit name when provided, regardless of body content", () => {
|
|
6
|
-
expect(extractGraphqlOperationName("query Whatever { x }", "ForcedName")).toBe("ForcedName");
|
|
7
|
-
expect(extractGraphqlOperationName("", "Override")).toBe("Override");
|
|
8
|
-
});
|
|
9
|
-
|
|
10
|
-
it("extracts a single named query", () => {
|
|
11
|
-
expect(
|
|
12
|
-
extractGraphqlOperationName("query ProductBySlug($slug: String!) { product { id } }"),
|
|
13
|
-
).toBe("ProductBySlug");
|
|
14
|
-
});
|
|
15
|
-
|
|
16
|
-
it("extracts a single named mutation", () => {
|
|
17
|
-
expect(
|
|
18
|
-
extractGraphqlOperationName("mutation CartLinesAdd($cartId: ID!) { cartLinesAdd { } }"),
|
|
19
|
-
).toBe("CartLinesAdd");
|
|
20
|
-
});
|
|
21
|
-
|
|
22
|
-
it("extracts a single named subscription", () => {
|
|
23
|
-
expect(extractGraphqlOperationName("subscription OrderEvents { orderUpdated { id } }")).toBe(
|
|
24
|
-
"OrderEvents",
|
|
25
|
-
);
|
|
26
|
-
});
|
|
27
|
-
|
|
28
|
-
it("returns undefined for anonymous operations", () => {
|
|
29
|
-
expect(extractGraphqlOperationName("{ product { id } }")).toBeUndefined();
|
|
30
|
-
expect(extractGraphqlOperationName("query { product { id } }")).toBeUndefined();
|
|
31
|
-
});
|
|
32
|
-
|
|
33
|
-
it("returns undefined when document has more than one named operation (caller must disambiguate)", () => {
|
|
34
|
-
const multi = `
|
|
35
|
-
query OpA { a }
|
|
36
|
-
query OpB { b }
|
|
37
|
-
`;
|
|
38
|
-
expect(extractGraphqlOperationName(multi)).toBeUndefined();
|
|
39
|
-
});
|
|
40
|
-
|
|
41
|
-
it("ignores the words query/mutation/subscription inside string literals", () => {
|
|
42
|
-
const docWithStringy = `query RealName { thing(arg: "this query mutation subscription is a string") }`;
|
|
43
|
-
expect(extractGraphqlOperationName(docWithStringy)).toBe("RealName");
|
|
44
|
-
});
|
|
45
|
-
|
|
46
|
-
it("ignores the words inside block strings (triple-quoted)", () => {
|
|
47
|
-
const doc = `
|
|
48
|
-
"""
|
|
49
|
-
This block string mentions query Inner and mutation Inner2.
|
|
50
|
-
"""
|
|
51
|
-
query OuterReal { x }
|
|
52
|
-
`;
|
|
53
|
-
expect(extractGraphqlOperationName(doc)).toBe("OuterReal");
|
|
54
|
-
});
|
|
55
|
-
|
|
56
|
-
it("ignores the words inside # comments", () => {
|
|
57
|
-
const doc = `
|
|
58
|
-
# query CommentedOut { x }
|
|
59
|
-
query Active { y }
|
|
60
|
-
`;
|
|
61
|
-
expect(extractGraphqlOperationName(doc)).toBe("Active");
|
|
62
|
-
});
|
|
63
|
-
|
|
64
|
-
it("returns undefined on an empty / nullish body", () => {
|
|
65
|
-
expect(extractGraphqlOperationName("")).toBeUndefined();
|
|
66
|
-
expect(extractGraphqlOperationName(" \n\t ")).toBeUndefined();
|
|
67
|
-
});
|
|
68
|
-
|
|
69
|
-
it("handles a real-world Shopify storefront query shape", () => {
|
|
70
|
-
const doc = `
|
|
71
|
-
query ProductDetails($handle: String!, $country: CountryCode!) @inContext(country: $country) {
|
|
72
|
-
product(handle: $handle) {
|
|
73
|
-
id
|
|
74
|
-
title
|
|
75
|
-
}
|
|
76
|
-
}
|
|
77
|
-
`;
|
|
78
|
-
expect(extractGraphqlOperationName(doc)).toBe("ProductDetails");
|
|
79
|
-
});
|
|
80
|
-
});
|