@shopkit/data-layer 1.3.0 → 1.4.1

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/dist/index.mjs CHANGED
@@ -1,652 +1,5 @@
1
- // ../../node_modules/.bun/@shopify+graphql-client@1.4.2/node_modules/@shopify/graphql-client/dist/graphql-client/constants.mjs
2
- var CLIENT = "GraphQL Client";
3
- var MIN_RETRIES = 0;
4
- var MAX_RETRIES = 3;
5
- var GQL_API_ERROR = "An error occurred while fetching from the API. Review 'graphQLErrors' for details.";
6
- var UNEXPECTED_CONTENT_TYPE_ERROR = "Response returned unexpected Content-Type:";
7
- var NO_DATA_OR_ERRORS_ERROR = "An unknown error has occurred. The API did not return a data object or any errors in its response.";
8
- var CONTENT_TYPES = {
9
- json: "application/json",
10
- multipart: "multipart/mixed"
11
- };
12
- var SDK_VARIANT_HEADER = "X-SDK-Variant";
13
- var SDK_VERSION_HEADER = "X-SDK-Version";
14
- var DEFAULT_SDK_VARIANT = "shopify-graphql-client";
15
- var DEFAULT_CLIENT_VERSION = "1.4.2";
16
- var RETRY_WAIT_TIME = 1e3;
17
- var RETRIABLE_STATUS_CODES = [429, 503];
18
- var DEFER_OPERATION_REGEX = /@(defer)\b/i;
19
- var NEWLINE_SEPARATOR = "\r\n";
20
- var BOUNDARY_HEADER_REGEX = /boundary="?([^=";]+)"?/i;
21
- var HEADER_SEPARATOR = NEWLINE_SEPARATOR + NEWLINE_SEPARATOR;
22
-
23
- // ../../node_modules/.bun/@shopify+graphql-client@1.4.2/node_modules/@shopify/graphql-client/dist/graphql-client/utilities.mjs
24
- function formatErrorMessage(message, client = CLIENT) {
25
- return message.startsWith(`${client}`) ? message : `${client}: ${message}`;
26
- }
27
- function getErrorMessage(error) {
28
- return error instanceof Error ? error.message : JSON.stringify(error);
29
- }
30
- function getErrorCause(error) {
31
- return error instanceof Error && error.cause ? error.cause : void 0;
32
- }
33
- function combineErrors(dataArray) {
34
- return dataArray.flatMap(({ errors }) => {
35
- return errors ?? [];
36
- });
37
- }
38
- function validateRetries({ client, retries }) {
39
- if (retries !== void 0 && (typeof retries !== "number" || retries < MIN_RETRIES || retries > MAX_RETRIES)) {
40
- throw new Error(`${client}: The provided "retries" value (${retries}) is invalid - it cannot be less than ${MIN_RETRIES} or greater than ${MAX_RETRIES}`);
41
- }
42
- }
43
- function getKeyValueIfValid(key, value) {
44
- return value && (typeof value !== "object" || Array.isArray(value) || typeof value === "object" && Object.keys(value).length > 0) ? { [key]: value } : {};
45
- }
46
- function buildDataObjectByPath(path, data) {
47
- if (path.length === 0) {
48
- return data;
49
- }
50
- const key = path.pop();
51
- const newData = {
52
- [key]: data
53
- };
54
- if (path.length === 0) {
55
- return newData;
56
- }
57
- return buildDataObjectByPath(path, newData);
58
- }
59
- function combineObjects(baseObject, newObject) {
60
- return Object.keys(newObject || {}).reduce((acc, key) => {
61
- if ((typeof newObject[key] === "object" || Array.isArray(newObject[key])) && baseObject[key]) {
62
- acc[key] = combineObjects(baseObject[key], newObject[key]);
63
- return acc;
64
- }
65
- acc[key] = newObject[key];
66
- return acc;
67
- }, Array.isArray(baseObject) ? [...baseObject] : { ...baseObject });
68
- }
69
- function buildCombinedDataObject([initialDatum, ...remainingData]) {
70
- return remainingData.reduce(combineObjects, { ...initialDatum });
71
- }
72
-
73
- // ../../node_modules/.bun/@shopify+graphql-client@1.4.2/node_modules/@shopify/graphql-client/dist/graphql-client/http-fetch.mjs
74
- function generateHttpFetch({ clientLogger, customFetchApi = fetch, client = CLIENT, defaultRetryWaitTime = RETRY_WAIT_TIME, retriableCodes = RETRIABLE_STATUS_CODES }) {
75
- const httpFetch = async (requestParams, count, maxRetries) => {
76
- const nextCount = count + 1;
77
- const maxTries = maxRetries + 1;
78
- let response;
79
- try {
80
- response = await customFetchApi(...requestParams);
81
- clientLogger({
82
- type: "HTTP-Response",
83
- content: {
84
- requestParams,
85
- response
86
- }
87
- });
88
- if (!response.ok && retriableCodes.includes(response.status) && nextCount <= maxTries) {
89
- throw new Error();
90
- }
91
- const deprecationNotice = response?.headers.get("X-Shopify-API-Deprecated-Reason") || "";
92
- if (deprecationNotice) {
93
- clientLogger({
94
- type: "HTTP-Response-GraphQL-Deprecation-Notice",
95
- content: {
96
- requestParams,
97
- deprecationNotice
98
- }
99
- });
100
- }
101
- return response;
102
- } catch (error) {
103
- if (nextCount <= maxTries) {
104
- const retryAfter = response?.headers.get("Retry-After");
105
- await sleep(retryAfter ? parseInt(retryAfter, 10) : defaultRetryWaitTime);
106
- clientLogger({
107
- type: "HTTP-Retry",
108
- content: {
109
- requestParams,
110
- lastResponse: response,
111
- retryAttempt: count,
112
- maxRetries
113
- }
114
- });
115
- return httpFetch(requestParams, nextCount, maxRetries);
116
- }
117
- throw new Error(formatErrorMessage(`${maxRetries > 0 ? `Attempted maximum number of ${maxRetries} network retries. Last message - ` : ""}${getErrorMessage(error)}`, client));
118
- }
119
- };
120
- return httpFetch;
121
- }
122
- async function sleep(waitTime) {
123
- return new Promise((resolve) => setTimeout(resolve, waitTime));
124
- }
125
-
126
- // ../../node_modules/.bun/@shopify+graphql-client@1.4.2/node_modules/@shopify/graphql-client/dist/graphql-client/graphql-client.mjs
127
- function createGraphQLClient({ headers, url, customFetchApi = fetch, retries = 0, logger: logger2 }) {
128
- validateRetries({ client: CLIENT, retries });
129
- const config = {
130
- headers,
131
- url,
132
- retries
133
- };
134
- const clientLogger = generateClientLogger(logger2);
135
- const httpFetch = generateHttpFetch({
136
- customFetchApi,
137
- clientLogger,
138
- defaultRetryWaitTime: RETRY_WAIT_TIME
139
- });
140
- const fetchFn = generateFetch(httpFetch, config);
141
- const request = generateRequest(fetchFn);
142
- const requestStream = generateRequestStream(fetchFn);
143
- return {
144
- config,
145
- fetch: fetchFn,
146
- request,
147
- requestStream
148
- };
149
- }
150
- function generateClientLogger(logger2) {
151
- return (logContent) => {
152
- if (logger2) {
153
- logger2(logContent);
154
- }
155
- };
156
- }
157
- async function processJSONResponse(response) {
158
- const { errors, data, extensions } = await response.json();
159
- return {
160
- ...getKeyValueIfValid("data", data),
161
- ...getKeyValueIfValid("extensions", extensions),
162
- headers: response.headers,
163
- ...errors || !data ? {
164
- errors: {
165
- networkStatusCode: response.status,
166
- message: formatErrorMessage(errors ? GQL_API_ERROR : NO_DATA_OR_ERRORS_ERROR),
167
- ...getKeyValueIfValid("graphQLErrors", errors),
168
- response
169
- }
170
- } : {}
171
- };
172
- }
173
- function generateFetch(httpFetch, { url, headers, retries }) {
174
- return async (operation, options = {}) => {
175
- const { variables, headers: overrideHeaders, url: overrideUrl, retries: overrideRetries, keepalive, signal } = options;
176
- const body = JSON.stringify({
177
- query: operation,
178
- variables
179
- });
180
- validateRetries({ client: CLIENT, retries: overrideRetries });
181
- const flatHeaders = Object.entries({
182
- ...headers,
183
- ...overrideHeaders
184
- }).reduce((headers2, [key, value]) => {
185
- headers2[key] = Array.isArray(value) ? value.join(", ") : value.toString();
186
- return headers2;
187
- }, {});
188
- if (!flatHeaders[SDK_VARIANT_HEADER] && !flatHeaders[SDK_VERSION_HEADER]) {
189
- flatHeaders[SDK_VARIANT_HEADER] = DEFAULT_SDK_VARIANT;
190
- flatHeaders[SDK_VERSION_HEADER] = DEFAULT_CLIENT_VERSION;
191
- }
192
- const fetchParams = [
193
- overrideUrl ?? url,
194
- {
195
- method: "POST",
196
- headers: flatHeaders,
197
- body,
198
- signal,
199
- keepalive
200
- }
201
- ];
202
- return httpFetch(fetchParams, 1, overrideRetries ?? retries);
203
- };
204
- }
205
- function generateRequest(fetchFn) {
206
- return async (...props) => {
207
- if (DEFER_OPERATION_REGEX.test(props[0])) {
208
- throw new Error(formatErrorMessage("This operation will result in a streamable response - use requestStream() instead."));
209
- }
210
- let response = null;
211
- try {
212
- response = await fetchFn(...props);
213
- const { status, statusText } = response;
214
- const contentType = response.headers.get("content-type") || "";
215
- if (!response.ok) {
216
- return {
217
- errors: {
218
- networkStatusCode: status,
219
- message: formatErrorMessage(statusText),
220
- response
221
- }
222
- };
223
- }
224
- if (!contentType.includes(CONTENT_TYPES.json)) {
225
- return {
226
- errors: {
227
- networkStatusCode: status,
228
- message: formatErrorMessage(`${UNEXPECTED_CONTENT_TYPE_ERROR} ${contentType}`),
229
- response
230
- }
231
- };
232
- }
233
- return await processJSONResponse(response);
234
- } catch (error) {
235
- return {
236
- errors: {
237
- message: getErrorMessage(error),
238
- ...response == null ? {} : {
239
- networkStatusCode: response.status,
240
- response
241
- }
242
- }
243
- };
244
- }
245
- };
246
- }
247
- async function* getStreamBodyIterator(response) {
248
- const decoder = new TextDecoder();
249
- if (response.body[Symbol.asyncIterator]) {
250
- for await (const chunk of response.body) {
251
- yield decoder.decode(chunk);
252
- }
253
- } else {
254
- const reader = response.body.getReader();
255
- let readResult;
256
- try {
257
- while (!(readResult = await reader.read()).done) {
258
- yield decoder.decode(readResult.value);
259
- }
260
- } finally {
261
- reader.cancel();
262
- }
263
- }
264
- }
265
- function readStreamChunk(streamBodyIterator, boundary) {
266
- return {
267
- async *[Symbol.asyncIterator]() {
268
- try {
269
- let buffer = "";
270
- for await (const textChunk of streamBodyIterator) {
271
- buffer += textChunk;
272
- if (buffer.indexOf(boundary) > -1) {
273
- const lastBoundaryIndex = buffer.lastIndexOf(boundary);
274
- const fullResponses = buffer.slice(0, lastBoundaryIndex);
275
- const chunkBodies = fullResponses.split(boundary).filter((chunk) => chunk.trim().length > 0).map((chunk) => {
276
- const body = chunk.slice(chunk.indexOf(HEADER_SEPARATOR) + HEADER_SEPARATOR.length).trim();
277
- return body;
278
- });
279
- if (chunkBodies.length > 0) {
280
- yield chunkBodies;
281
- }
282
- buffer = buffer.slice(lastBoundaryIndex + boundary.length);
283
- if (buffer.trim() === `--`) {
284
- buffer = "";
285
- }
286
- }
287
- }
288
- } catch (error) {
289
- throw new Error(`Error occured while processing stream payload - ${getErrorMessage(error)}`);
290
- }
291
- }
292
- };
293
- }
294
- function createJsonResponseAsyncIterator(response) {
295
- return {
296
- async *[Symbol.asyncIterator]() {
297
- try {
298
- const processedResponse = await processJSONResponse(response);
299
- yield {
300
- ...processedResponse,
301
- hasNext: false
302
- };
303
- } catch (error) {
304
- yield {
305
- errors: {
306
- message: formatErrorMessage(getErrorMessage(error)),
307
- networkStatusCode: response.status,
308
- response
309
- },
310
- hasNext: false
311
- };
312
- }
313
- }
314
- };
315
- }
316
- function getResponseDataFromChunkBodies(chunkBodies) {
317
- return chunkBodies.map((value) => {
318
- try {
319
- return JSON.parse(value);
320
- } catch (error) {
321
- throw new Error(`Error in parsing multipart response - ${getErrorMessage(error)}`);
322
- }
323
- }).map((payload) => {
324
- const { data, incremental, hasNext, extensions, errors } = payload;
325
- if (!incremental) {
326
- return {
327
- data: data || {},
328
- ...getKeyValueIfValid("errors", errors),
329
- ...getKeyValueIfValid("extensions", extensions),
330
- hasNext
331
- };
332
- }
333
- const incrementalArray = incremental.map(({ data: data2, path, errors: errors2 }) => {
334
- return {
335
- data: data2 && path ? buildDataObjectByPath(path, data2) : {},
336
- ...getKeyValueIfValid("errors", errors2)
337
- };
338
- });
339
- return {
340
- data: incrementalArray.length === 1 ? incrementalArray[0].data : buildCombinedDataObject([
341
- ...incrementalArray.map(({ data: data2 }) => data2)
342
- ]),
343
- ...getKeyValueIfValid("errors", combineErrors(incrementalArray)),
344
- hasNext
345
- };
346
- });
347
- }
348
- function validateResponseData(responseErrors, combinedData) {
349
- if (responseErrors.length > 0) {
350
- throw new Error(GQL_API_ERROR, {
351
- cause: {
352
- graphQLErrors: responseErrors
353
- }
354
- });
355
- }
356
- if (Object.keys(combinedData).length === 0) {
357
- throw new Error(NO_DATA_OR_ERRORS_ERROR);
358
- }
359
- }
360
- function createMultipartResponseAsyncInterator(response, responseContentType) {
361
- const boundaryHeader = (responseContentType ?? "").match(BOUNDARY_HEADER_REGEX);
362
- const boundary = `--${boundaryHeader ? boundaryHeader[1] : "-"}`;
363
- if (!response.body?.getReader && !response.body?.[Symbol.asyncIterator]) {
364
- throw new Error("API multipart response did not return an iterable body", {
365
- cause: response
366
- });
367
- }
368
- const streamBodyIterator = getStreamBodyIterator(response);
369
- let combinedData = {};
370
- let responseExtensions;
371
- return {
372
- async *[Symbol.asyncIterator]() {
373
- try {
374
- let streamHasNext = true;
375
- for await (const chunkBodies of readStreamChunk(streamBodyIterator, boundary)) {
376
- const responseData = getResponseDataFromChunkBodies(chunkBodies);
377
- responseExtensions = responseData.find((datum) => datum.extensions)?.extensions ?? responseExtensions;
378
- const responseErrors = combineErrors(responseData);
379
- combinedData = buildCombinedDataObject([
380
- combinedData,
381
- ...responseData.map(({ data }) => data)
382
- ]);
383
- streamHasNext = responseData.slice(-1)[0].hasNext;
384
- validateResponseData(responseErrors, combinedData);
385
- yield {
386
- ...getKeyValueIfValid("data", combinedData),
387
- ...getKeyValueIfValid("extensions", responseExtensions),
388
- hasNext: streamHasNext
389
- };
390
- }
391
- if (streamHasNext) {
392
- throw new Error(`Response stream terminated unexpectedly`);
393
- }
394
- } catch (error) {
395
- const cause = getErrorCause(error);
396
- yield {
397
- ...getKeyValueIfValid("data", combinedData),
398
- ...getKeyValueIfValid("extensions", responseExtensions),
399
- errors: {
400
- message: formatErrorMessage(getErrorMessage(error)),
401
- networkStatusCode: response.status,
402
- ...getKeyValueIfValid("graphQLErrors", cause?.graphQLErrors),
403
- response
404
- },
405
- hasNext: false
406
- };
407
- }
408
- }
409
- };
410
- }
411
- function generateRequestStream(fetchFn) {
412
- return async (...props) => {
413
- if (!DEFER_OPERATION_REGEX.test(props[0])) {
414
- throw new Error(formatErrorMessage("This operation does not result in a streamable response - use request() instead."));
415
- }
416
- try {
417
- const response = await fetchFn(...props);
418
- const { statusText } = response;
419
- if (!response.ok) {
420
- throw new Error(statusText, { cause: response });
421
- }
422
- const responseContentType = response.headers.get("content-type") || "";
423
- switch (true) {
424
- case responseContentType.includes(CONTENT_TYPES.json):
425
- return createJsonResponseAsyncIterator(response);
426
- case responseContentType.includes(CONTENT_TYPES.multipart):
427
- return createMultipartResponseAsyncInterator(response, responseContentType);
428
- default:
429
- throw new Error(`${UNEXPECTED_CONTENT_TYPE_ERROR} ${responseContentType}`, { cause: response });
430
- }
431
- } catch (error) {
432
- return {
433
- async *[Symbol.asyncIterator]() {
434
- const response = getErrorCause(error);
435
- yield {
436
- errors: {
437
- message: formatErrorMessage(getErrorMessage(error)),
438
- ...getKeyValueIfValid("networkStatusCode", response?.status),
439
- ...getKeyValueIfValid("response", response)
440
- },
441
- hasNext: false
442
- };
443
- }
444
- };
445
- }
446
- };
447
- }
448
-
449
- // ../../node_modules/.bun/@shopify+graphql-client@1.4.2/node_modules/@shopify/graphql-client/dist/api-client-utilities/validations.mjs
450
- function validateDomainAndGetStoreUrl({ client, storeDomain }) {
451
- try {
452
- if (!storeDomain || typeof storeDomain !== "string") {
453
- throw new Error();
454
- }
455
- const trimmedDomain = storeDomain.trim();
456
- const protocolUrl = trimmedDomain.match(/^https?:/) ? trimmedDomain : `https://${trimmedDomain}`;
457
- const url = new URL(protocolUrl);
458
- url.protocol = "https";
459
- return url.origin;
460
- } catch (error) {
461
- throw new Error(`${client}: a valid store domain ("${storeDomain}") must be provided`, { cause: error });
462
- }
463
- }
464
- function validateApiVersion({ client, currentSupportedApiVersions, apiVersion, logger: logger2 }) {
465
- const versionError = `${client}: the provided apiVersion ("${apiVersion}")`;
466
- const supportedVersion = `Currently supported API versions: ${currentSupportedApiVersions.join(", ")}`;
467
- if (!apiVersion || typeof apiVersion !== "string") {
468
- throw new Error(`${versionError} is invalid. ${supportedVersion}`);
469
- }
470
- const trimmedApiVersion = apiVersion.trim();
471
- if (!currentSupportedApiVersions.includes(trimmedApiVersion)) {
472
- if (logger2) {
473
- logger2({
474
- type: "Unsupported_Api_Version",
475
- content: {
476
- apiVersion,
477
- supportedApiVersions: currentSupportedApiVersions
478
- }
479
- });
480
- } else {
481
- console.warn(`${versionError} is likely deprecated or not supported. ${supportedVersion}`);
482
- }
483
- }
484
- }
485
-
486
- // ../../node_modules/.bun/@shopify+graphql-client@1.4.2/node_modules/@shopify/graphql-client/dist/api-client-utilities/api-versions.mjs
487
- function getQuarterMonth(quarter) {
488
- const month = quarter * 3 - 2;
489
- return month === 10 ? month : `0${month}`;
490
- }
491
- function getPrevousVersion(year, quarter, nQuarter) {
492
- const versionQuarter = quarter - nQuarter;
493
- if (versionQuarter <= 0) {
494
- return `${year - 1}-${getQuarterMonth(versionQuarter + 4)}`;
495
- }
496
- return `${year}-${getQuarterMonth(versionQuarter)}`;
497
- }
498
- function getCurrentApiVersion() {
499
- const date = /* @__PURE__ */ new Date();
500
- const month = date.getUTCMonth();
501
- const year = date.getUTCFullYear();
502
- const quarter = Math.floor(month / 3 + 1);
503
- return {
504
- year,
505
- quarter,
506
- version: `${year}-${getQuarterMonth(quarter)}`
507
- };
508
- }
509
- function getCurrentSupportedApiVersions() {
510
- const { year, quarter, version: currentVersion } = getCurrentApiVersion();
511
- const nextVersion = quarter === 4 ? `${year + 1}-01` : `${year}-${getQuarterMonth(quarter + 1)}`;
512
- return [
513
- getPrevousVersion(year, quarter, 3),
514
- getPrevousVersion(year, quarter, 2),
515
- getPrevousVersion(year, quarter, 1),
516
- currentVersion,
517
- nextVersion,
518
- "unstable"
519
- ];
520
- }
521
-
522
- // ../../node_modules/.bun/@shopify+graphql-client@1.4.2/node_modules/@shopify/graphql-client/dist/api-client-utilities/utilities.mjs
523
- function generateGetHeaders(config) {
524
- return (customHeaders) => {
525
- return { ...customHeaders ?? {}, ...config.headers };
526
- };
527
- }
528
- function generateGetGQLClientParams({ getHeaders, getApiUrl }) {
529
- return (operation, options) => {
530
- const props = [operation];
531
- if (options && Object.keys(options).length > 0) {
532
- const { variables, apiVersion: propApiVersion, headers, retries, signal } = options;
533
- props.push({
534
- ...variables ? { variables } : {},
535
- ...headers ? { headers: getHeaders(headers) } : {},
536
- ...propApiVersion ? { url: getApiUrl(propApiVersion) } : {},
537
- ...retries ? { retries } : {},
538
- ...signal ? { signal } : {}
539
- });
540
- }
541
- return props;
542
- };
543
- }
544
-
545
- // ../../node_modules/.bun/@shopify+storefront-api-client@1.0.10/node_modules/@shopify/storefront-api-client/dist/constants.mjs
546
- var DEFAULT_CONTENT_TYPE = "application/json";
547
- var DEFAULT_SDK_VARIANT2 = "storefront-api-client";
548
- var DEFAULT_CLIENT_VERSION2 = "1.0.10";
549
- var PUBLIC_ACCESS_TOKEN_HEADER = "X-Shopify-Storefront-Access-Token";
550
- var PRIVATE_ACCESS_TOKEN_HEADER = "Shopify-Storefront-Private-Token";
551
- var SDK_VARIANT_HEADER2 = "X-SDK-Variant";
552
- var SDK_VERSION_HEADER2 = "X-SDK-Version";
553
- var SDK_VARIANT_SOURCE_HEADER = "X-SDK-Variant-Source";
554
- var CLIENT2 = "Storefront API Client";
555
-
556
- // ../../node_modules/.bun/@shopify+storefront-api-client@1.0.10/node_modules/@shopify/storefront-api-client/dist/validations.mjs
557
- function validatePrivateAccessTokenUsage(privateAccessToken) {
558
- if (privateAccessToken && typeof window !== "undefined") {
559
- throw new Error(`${CLIENT2}: private access tokens and headers should only be used in a server-to-server implementation. Use the public API access token in nonserver environments.`);
560
- }
561
- }
562
- function validateRequiredAccessTokens(publicAccessToken, privateAccessToken) {
563
- if (!publicAccessToken && !privateAccessToken) {
564
- throw new Error(`${CLIENT2}: a public or private access token must be provided`);
565
- }
566
- if (publicAccessToken && privateAccessToken) {
567
- throw new Error(`${CLIENT2}: only provide either a public or private access token`);
568
- }
569
- }
570
-
571
- // ../../node_modules/.bun/@shopify+storefront-api-client@1.0.10/node_modules/@shopify/storefront-api-client/dist/storefront-api-client.mjs
572
- function createStorefrontApiClient({ storeDomain, apiVersion, publicAccessToken, privateAccessToken, clientName, retries = 0, customFetchApi, logger: logger2 }) {
573
- const currentSupportedApiVersions = getCurrentSupportedApiVersions();
574
- const storeUrl = validateDomainAndGetStoreUrl({
575
- client: CLIENT2,
576
- storeDomain
577
- });
578
- const baseApiVersionValidationParams = {
579
- client: CLIENT2,
580
- currentSupportedApiVersions,
581
- logger: logger2
582
- };
583
- validateApiVersion({ ...baseApiVersionValidationParams, apiVersion });
584
- validateRequiredAccessTokens(publicAccessToken, privateAccessToken);
585
- validatePrivateAccessTokenUsage(privateAccessToken);
586
- const apiUrlFormatter = generateApiUrlFormatter(storeUrl, apiVersion, baseApiVersionValidationParams);
587
- const config = {
588
- storeDomain: storeUrl,
589
- apiVersion,
590
- ...publicAccessToken ? { publicAccessToken } : {
591
- privateAccessToken
592
- },
593
- headers: {
594
- "Content-Type": DEFAULT_CONTENT_TYPE,
595
- Accept: DEFAULT_CONTENT_TYPE,
596
- [SDK_VARIANT_HEADER2]: DEFAULT_SDK_VARIANT2,
597
- [SDK_VERSION_HEADER2]: DEFAULT_CLIENT_VERSION2,
598
- ...clientName ? { [SDK_VARIANT_SOURCE_HEADER]: clientName } : {},
599
- ...publicAccessToken ? { [PUBLIC_ACCESS_TOKEN_HEADER]: publicAccessToken } : { [PRIVATE_ACCESS_TOKEN_HEADER]: privateAccessToken }
600
- },
601
- apiUrl: apiUrlFormatter(),
602
- clientName
603
- };
604
- const graphqlClient = createGraphQLClient({
605
- headers: config.headers,
606
- url: config.apiUrl,
607
- retries,
608
- customFetchApi,
609
- logger: logger2
610
- });
611
- const getHeaders = generateGetHeaders(config);
612
- const getApiUrl = generateGetApiUrl(config, apiUrlFormatter);
613
- const getGQLClientParams = generateGetGQLClientParams({
614
- getHeaders,
615
- getApiUrl
616
- });
617
- const client = {
618
- config,
619
- getHeaders,
620
- getApiUrl,
621
- fetch: (...props) => {
622
- return graphqlClient.fetch(...getGQLClientParams(...props));
623
- },
624
- request: (...props) => {
625
- return graphqlClient.request(...getGQLClientParams(...props));
626
- },
627
- requestStream: (...props) => {
628
- return graphqlClient.requestStream(...getGQLClientParams(...props));
629
- }
630
- };
631
- return Object.freeze(client);
632
- }
633
- function generateApiUrlFormatter(storeUrl, defaultApiVersion, baseApiVersionValidationParams) {
634
- return (apiVersion) => {
635
- if (apiVersion) {
636
- validateApiVersion({
637
- ...baseApiVersionValidationParams,
638
- apiVersion
639
- });
640
- }
641
- const urlApiVersion = (apiVersion ?? defaultApiVersion).trim();
642
- return `${storeUrl}/api/${urlApiVersion}/graphql.json`;
643
- };
644
- }
645
- function generateGetApiUrl(config, apiUrlFormatter) {
646
- return (propApiVersion) => {
647
- return propApiVersion ? apiUrlFormatter(propApiVersion) : config.apiUrl;
648
- };
649
- }
1
+ import { createStorefrontApiClient } from '@shopify/storefront-api-client';
2
+ import { CacheTags } from '@shopkit/core/cache-tags';
650
3
 
651
4
  // src/adapters/shopify/client.ts
652
5
  function createShopifyStorefrontClient(config) {
@@ -4342,8 +3695,12 @@ var BaseCustomService = class {
4342
3695
  headers,
4343
3696
  // Bound the upstream wait — see core/request-timeout.ts for the policy and
4344
3697
  // rationale (Bblunt prod memory-leak postmortem, Jun 2026).
4345
- signal: resolveRequestSignal(options, this.timeout)
3698
+ signal: resolveRequestSignal(options, this.timeout),
3699
+ ...options?.cache ? { cache: options.cache } : {}
4346
3700
  };
3701
+ if (options?.next) {
3702
+ requestOptions.next = options.next;
3703
+ }
4347
3704
  if (data && method !== "GET") {
4348
3705
  requestOptions.body = JSON.stringify(data);
4349
3706
  }
@@ -4611,7 +3968,15 @@ var ProductService2 = class extends BaseCustomService {
4611
3968
  PRODUCT_ENDPOINTS.getCollections(options?.version),
4612
3969
  "GET",
4613
3970
  void 0,
4614
- { params: queryParams, ...options || {} }
3971
+ {
3972
+ params: queryParams,
3973
+ ...options || {},
3974
+ // Broad collections tag so a catalog-wide change can revalidate the list.
3975
+ next: {
3976
+ ...options?.next || {},
3977
+ tags: [CacheTags.collections(), ...options?.next?.tags || []]
3978
+ }
3979
+ }
4615
3980
  );
4616
3981
  if (!result || !result.collections) {
4617
3982
  return formatResponse({
@@ -4661,7 +4026,18 @@ var ProductService2 = class extends BaseCustomService {
4661
4026
  const apiUrl = handle ? PRODUCT_ENDPOINTS.getCollectionByHandle(options?.version, handle) : PRODUCT_ENDPOINTS.getCollectionById(options?.version, id);
4662
4027
  const result = await this.request(apiUrl, "GET", void 0, {
4663
4028
  params: queryParams,
4664
- ...options || {}
4029
+ ...options || {},
4030
+ // Tag the collection read so a webhook can revalidateTag() it, refreshing
4031
+ // the collection page AND every grid built from it. GET only — Next caches
4032
+ // GET; the handle keys the entity. See @shopkit/core/cache-tags.
4033
+ next: {
4034
+ ...options?.next || {},
4035
+ tags: [
4036
+ CacheTags.collections(),
4037
+ ...handle ? [CacheTags.collection(handle)] : [],
4038
+ ...options?.next?.tags || []
4039
+ ]
4040
+ }
4665
4041
  });
4666
4042
  if (!result) {
4667
4043
  return formatResponse({