@sanity/client 7.26.2 → 8.0.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.
Files changed (130) hide show
  1. package/README.md +5 -377
  2. package/dist/browserUpload-CQgx9YYo.js +86 -0
  3. package/dist/browserUpload-CQgx9YYo.js.map +1 -0
  4. package/dist/browserUpload-icWlVP15.js +86 -0
  5. package/dist/browserUpload-icWlVP15.js.map +1 -0
  6. package/dist/config-a8VajuEY.js +126 -0
  7. package/dist/config-a8VajuEY.js.map +1 -0
  8. package/dist/csm.d.ts +122 -335
  9. package/dist/csm.js +79 -91
  10. package/dist/csm.js.map +1 -1
  11. package/dist/dist-C9ExSk2R.js +73 -0
  12. package/dist/dist-C9ExSk2R.js.map +1 -0
  13. package/dist/dist-Z8cIRxoB.js +69 -0
  14. package/dist/dist-Z8cIRxoB.js.map +1 -0
  15. package/dist/index.d.ts +107 -6723
  16. package/dist/index.js +2822 -2847
  17. package/dist/index.js.map +1 -1
  18. package/dist/{index.d.cts → index.node.d.ts} +4291 -5328
  19. package/dist/index.node.js +3131 -0
  20. package/dist/index.node.js.map +1 -0
  21. package/dist/isRecord-Kfmt-nk-.js +7 -0
  22. package/dist/isRecord-Kfmt-nk-.js.map +1 -0
  23. package/dist/media-library.d.ts +9 -100
  24. package/dist/media-library.js +36 -14
  25. package/dist/media-library.js.map +1 -1
  26. package/dist/request-CJxcN16k.js +372 -0
  27. package/dist/request-CJxcN16k.js.map +1 -0
  28. package/dist/request-k7VS_NnC.js +354 -0
  29. package/dist/request-k7VS_NnC.js.map +1 -0
  30. package/dist/resolveEditInfo-sq7yF78q.js +325 -0
  31. package/dist/resolveEditInfo-sq7yF78q.js.map +1 -0
  32. package/dist/rolldown-runtime-vyAXikos.js +9 -0
  33. package/dist/stega.d.ts +78 -7137
  34. package/dist/stega.js +27 -20
  35. package/dist/stega.js.map +1 -1
  36. package/dist/stegaClean-C18wLWau.js +21 -0
  37. package/dist/stegaClean-C18wLWau.js.map +1 -0
  38. package/dist/stegaEncodeSourceMap-B2fGArSf.js +163 -0
  39. package/dist/stegaEncodeSourceMap-B2fGArSf.js.map +1 -0
  40. package/dist/stegaEncodeSourceMap-DkoIlutY.js +367 -0
  41. package/dist/stegaEncodeSourceMap-DkoIlutY.js.map +1 -0
  42. package/dist/{index.browser.d.cts → types-CUxZSgB2.d.ts} +3956 -5256
  43. package/dist/types-CfGzbXrl.d.ts +108 -0
  44. package/package.json +64 -141
  45. package/src/SanityClient.ts +82 -117
  46. package/src/agent/actions/AgentActionsClient.ts +12 -12
  47. package/src/agent/actions/commonTypes.ts +2 -1
  48. package/src/agent/actions/generate.ts +26 -6
  49. package/src/agent/actions/patch.ts +27 -7
  50. package/src/agent/actions/prompt.ts +19 -5
  51. package/src/agent/actions/transform.ts +23 -5
  52. package/src/agent/actions/translate.ts +23 -5
  53. package/src/assets/AssetsClient.ts +71 -23
  54. package/src/csm/applySourceDocuments.ts +3 -1
  55. package/src/csm/createEditUrl.ts +1 -1
  56. package/src/csm/draftUtils.ts +0 -1
  57. package/src/csm/index.ts +2 -2
  58. package/src/csm/studioPath.ts +2 -1
  59. package/src/csm/types.ts +8 -2
  60. package/src/data/dataMethods.ts +801 -349
  61. package/src/data/eventsource.ts +13 -10
  62. package/src/data/listen.ts +18 -23
  63. package/src/data/live.ts +44 -27
  64. package/src/data/resolveEventSourceFetch.ts +96 -0
  65. package/src/datasets/DatasetsClient.ts +58 -41
  66. package/src/defineCreateClient.ts +35 -23
  67. package/src/http/browserMiddleware.ts +7 -1
  68. package/src/http/browserUpload.ts +162 -0
  69. package/src/http/errors.ts +60 -6
  70. package/src/http/nodeMiddleware.ts +94 -30
  71. package/src/http/request.ts +310 -87
  72. package/src/http/requestOptions.ts +131 -15
  73. package/src/{index.browser.ts → index.node.ts} +9 -4
  74. package/src/index.ts +4 -3
  75. package/src/mediaLibrary/MediaLibraryVideoClient.ts +26 -11
  76. package/src/projects/ProjectsClient.ts +18 -16
  77. package/src/releases/ReleasesClient.ts +38 -33
  78. package/src/stega/index.ts +1 -2
  79. package/src/stega/stegaEncodeSourceMap.ts +5 -0
  80. package/src/stega/types.ts +2 -2
  81. package/src/types.ts +148 -105
  82. package/src/users/UsersClient.ts +10 -14
  83. package/src/util/shareReplayLatest.ts +1 -1
  84. package/src/warnings.ts +6 -1
  85. package/dist/_chunks-cjs/config.cjs +0 -206
  86. package/dist/_chunks-cjs/config.cjs.map +0 -1
  87. package/dist/_chunks-cjs/isRecord.cjs +0 -6
  88. package/dist/_chunks-cjs/isRecord.cjs.map +0 -1
  89. package/dist/_chunks-cjs/resolveEditInfo.cjs +0 -334
  90. package/dist/_chunks-cjs/resolveEditInfo.cjs.map +0 -1
  91. package/dist/_chunks-cjs/stegaClean.cjs +0 -46
  92. package/dist/_chunks-cjs/stegaClean.cjs.map +0 -1
  93. package/dist/_chunks-cjs/stegaEncodeSourceMap.cjs +0 -388
  94. package/dist/_chunks-cjs/stegaEncodeSourceMap.cjs.map +0 -1
  95. package/dist/_chunks-es/config.js +0 -207
  96. package/dist/_chunks-es/config.js.map +0 -1
  97. package/dist/_chunks-es/isRecord.js +0 -7
  98. package/dist/_chunks-es/isRecord.js.map +0 -1
  99. package/dist/_chunks-es/resolveEditInfo.js +0 -335
  100. package/dist/_chunks-es/resolveEditInfo.js.map +0 -1
  101. package/dist/_chunks-es/stegaClean.js +0 -47
  102. package/dist/_chunks-es/stegaClean.js.map +0 -1
  103. package/dist/_chunks-es/stegaEncodeSourceMap.js +0 -389
  104. package/dist/_chunks-es/stegaEncodeSourceMap.js.map +0 -1
  105. package/dist/csm.cjs +0 -99
  106. package/dist/csm.cjs.map +0 -1
  107. package/dist/csm.d.cts +0 -391
  108. package/dist/index.browser.cjs +0 -3106
  109. package/dist/index.browser.cjs.map +0 -1
  110. package/dist/index.browser.d.ts +0 -6802
  111. package/dist/index.browser.js +0 -3082
  112. package/dist/index.browser.js.map +0 -1
  113. package/dist/index.cjs +0 -2946
  114. package/dist/index.cjs.map +0 -1
  115. package/dist/media-library.cjs +0 -20
  116. package/dist/media-library.cjs.map +0 -1
  117. package/dist/media-library.d.cts +0 -117
  118. package/dist/stega.browser.cjs +0 -29
  119. package/dist/stega.browser.cjs.map +0 -1
  120. package/dist/stega.browser.d.cts +0 -7200
  121. package/dist/stega.browser.d.ts +0 -7200
  122. package/dist/stega.browser.js +0 -24
  123. package/dist/stega.browser.js.map +0 -1
  124. package/dist/stega.cjs +0 -29
  125. package/dist/stega.cjs.map +0 -1
  126. package/dist/stega.d.cts +0 -7200
  127. package/src/data/eventsourcePolyfill.ts +0 -7
  128. package/umd/.gitkeep +0 -1
  129. package/umd/sanityClient.js +0 -6543
  130. package/umd/sanityClient.min.js +0 -6
@@ -0,0 +1,354 @@
1
+ import { t as isRecord } from "./isRecord-Kfmt-nk-.js";
2
+ import { HttpError, createRequester } from "get-it";
3
+ import { isRetryableRequest, retry } from "get-it/middleware";
4
+ import { Observable, from } from "rxjs";
5
+ /**
6
+ * RegExp to test for newlines.
7
+ */
8
+ const NEWLINE = /\r\n|[\n\r\u2028\u2029]/;
9
+ /**
10
+ * Highlight a code frame with the given location and message.
11
+ *
12
+ * @param query - The query to be highlighted.
13
+ * @param location - The location of the error in the code/query.
14
+ * @param message - Message to be displayed inline (if possible) next to the highlighted
15
+ * location in the code. If it can't be positioned inline, it will be placed above the
16
+ * code frame.
17
+ * @returns The highlighted code frame.
18
+ */
19
+ function codeFrame(query, location, message) {
20
+ let lines = query.split(NEWLINE), { start, end, markerLines } = getMarkerLines({
21
+ start: columnToLine(location.start, lines),
22
+ end: location.end ? columnToLine(location.end, lines) : void 0
23
+ }, lines), numberMaxWidth = `${end}`.length;
24
+ return query.split(NEWLINE, end).slice(start, end).map((line, index) => {
25
+ let number = start + 1 + index, gutter = ` ${` ${number}`.slice(-numberMaxWidth)} |`, hasMarker = markerLines[number], lastMarkerLine = !markerLines[number + 1];
26
+ if (!hasMarker) return ` ${gutter}${line.length > 0 ? ` ${line}` : ""}`;
27
+ let markerLine = "";
28
+ if (Array.isArray(hasMarker)) {
29
+ let markerSpacing = line.slice(0, Math.max(hasMarker[0] - 1, 0)).replace(/[^\t]/g, " "), numberOfMarkers = hasMarker[1] || 1;
30
+ markerLine = [
31
+ "\n ",
32
+ gutter.replace(/\d/g, " "),
33
+ " ",
34
+ markerSpacing,
35
+ "^".repeat(numberOfMarkers)
36
+ ].join(""), lastMarkerLine && message && (markerLine += " " + message);
37
+ }
38
+ return [
39
+ ">",
40
+ gutter,
41
+ line.length > 0 ? ` ${line}` : "",
42
+ markerLine
43
+ ].join("");
44
+ }).join("\n");
45
+ }
46
+ function getMarkerLines(loc, source) {
47
+ let startLoc = { ...loc.start }, endLoc = {
48
+ ...startLoc,
49
+ ...loc.end
50
+ }, startLine = startLoc.line ?? -1, startColumn = startLoc.column ?? 0, endLine = endLoc.line, endColumn = endLoc.column, start = Math.max(startLine - 3, 0), end = Math.min(source.length, endLine + 3);
51
+ startLine === -1 && (start = 0), endLine === -1 && (end = source.length);
52
+ let lineDiff = endLine - startLine, markerLines = {};
53
+ if (lineDiff) for (let i = 0; i <= lineDiff; i++) {
54
+ let lineNumber = i + startLine;
55
+ markerLines[lineNumber] = startColumn ? i === 0 ? [startColumn, source[lineNumber - 1].length - startColumn + 1] : i === lineDiff ? [0, endColumn] : [0, source[lineNumber - i].length] : !0;
56
+ }
57
+ else markerLines[startLine] = startColumn === endColumn ? !startColumn || [startColumn, 0] : [startColumn, endColumn - startColumn];
58
+ return {
59
+ start,
60
+ end,
61
+ markerLines
62
+ };
63
+ }
64
+ function columnToLine(column, lines) {
65
+ let offset = 0;
66
+ for (let i = 0; i < lines.length; i++) {
67
+ let lineLength = lines[i].length + 1;
68
+ if (offset + lineLength > column) return {
69
+ line: i + 1,
70
+ column: column - offset
71
+ };
72
+ offset += lineLength;
73
+ }
74
+ return {
75
+ line: lines.length,
76
+ column: lines[lines.length - 1]?.length ?? 0
77
+ };
78
+ }
79
+ /**
80
+ * Adapter for buffered responses from get-it v9 (`BufferedResponse`-shaped).
81
+ *
82
+ * The URL and method aren't on the response itself in v9, so the request
83
+ * options must be passed alongside.
84
+ *
85
+ * @internal
86
+ */
87
+ function httpResponseFromFetch(res, reqUrl, reqMethod) {
88
+ return {
89
+ statusCode: res.status,
90
+ statusMessage: res.statusText || null,
91
+ headers: headersToRecord$1(res.headers),
92
+ body: res.body,
93
+ url: reqUrl,
94
+ method: reqMethod
95
+ };
96
+ }
97
+ function headersToRecord$1(headers) {
98
+ let out = {};
99
+ return headers.forEach((value, key) => {
100
+ out[key] = value;
101
+ }), out;
102
+ }
103
+ /**
104
+ * Checks if the provided error is an HTTP error.
105
+ *
106
+ * @param error - The error to check.
107
+ * @returns `true` if the error is an HTTP error, `false` otherwise.
108
+ * @public
109
+ */
110
+ function isHttpError(error) {
111
+ if (!isRecord(error)) return !1;
112
+ let response = error.response;
113
+ return !(typeof error.statusCode != "number" || typeof error.message != "string" || !isRecord(response) || response.body === void 0 || typeof response.url != "string" || typeof response.method != "string" || typeof response.headers != "object" || typeof response.statusCode != "number");
114
+ }
115
+ /** @public */
116
+ var ClientError = class extends Error {
117
+ response;
118
+ statusCode = 400;
119
+ responseBody;
120
+ traceId;
121
+ details;
122
+ constructor(res, tag) {
123
+ let props = extractErrorProps(res, tag);
124
+ super(props.message), Object.assign(this, props);
125
+ }
126
+ }, ServerError = class extends Error {
127
+ response;
128
+ statusCode = 500;
129
+ responseBody;
130
+ traceId;
131
+ details;
132
+ constructor(res) {
133
+ let props = extractErrorProps(res);
134
+ super(props.message), Object.assign(this, props);
135
+ }
136
+ };
137
+ function extractErrorProps(res, tag) {
138
+ let body = res.body, props = {
139
+ response: res,
140
+ statusCode: res.statusCode,
141
+ responseBody: stringifyBody(body, res),
142
+ traceId: extractTraceId(res),
143
+ message: "",
144
+ details: void 0
145
+ };
146
+ if (!isRecord(body)) return props.message = `${httpErrorMessage(res, body)}${formatTraceId(props.traceId)}`, props;
147
+ let error = body.error;
148
+ if (typeof error == "string" && typeof body.message == "string") return props.message = `${error} - ${body.message}${formatTraceId(props.traceId)}`, props;
149
+ if (typeof error != "object" || !error) return props.message = typeof error == "string" ? `${error}${formatTraceId(props.traceId)}` : typeof body.message == "string" ? `${body.message}${formatTraceId(props.traceId)}` : `${httpErrorMessage(res, body)}${formatTraceId(props.traceId)}`, props;
150
+ if (isMutationError(error) || isActionError(error)) {
151
+ let allItems = error.items || [], items = allItems.slice(0, 5).map((item) => item.error?.description).filter(Boolean), itemsStr = items.length ? `:\n- ${items.join("\n- ")}` : "";
152
+ return allItems.length > 5 && (itemsStr += `\n...and ${allItems.length - 5} more`), props.message = `${error.description}${formatTraceId(props.traceId)}${itemsStr}`, props.details = body.error, props;
153
+ }
154
+ return isQueryParseError(error) ? (props.message = formatQueryParseError(error, tag, props.traceId), props.details = body.error, props) : "description" in error && typeof error.description == "string" ? (props.message = `${error.description}${formatTraceId(props.traceId)}`, props.details = error, props) : (props.message = `${httpErrorMessage(res, body)}${formatTraceId(props.traceId)}`, props);
155
+ }
156
+ function isMutationError(error) {
157
+ return "type" in error && error.type === "mutationError" && "description" in error && typeof error.description == "string";
158
+ }
159
+ function isActionError(error) {
160
+ return "type" in error && error.type === "actionError" && "description" in error && typeof error.description == "string";
161
+ }
162
+ /** @internal */
163
+ function isQueryParseError(error) {
164
+ return isRecord(error) && error.type === "queryParseError" && typeof error.query == "string" && typeof error.start == "number" && typeof error.end == "number";
165
+ }
166
+ /**
167
+ * Formats a GROQ query parse error into a human-readable string.
168
+ *
169
+ * @param error - The error object containing details about the parse error.
170
+ * @param tag - An optional tag to include in the error message.
171
+ * @returns A formatted error message string.
172
+ * @public
173
+ */
174
+ function formatQueryParseError(error, tag, traceId) {
175
+ let { query, start, end, description } = error, withTraceId = traceId ? `\n(traceId: ${traceId})` : "";
176
+ if (!query || start === void 0) return `GROQ query parse error: ${description}${withTraceId}`;
177
+ let withTag = tag ? `\n\nTag: ${tag}` : "";
178
+ return `GROQ query parse error:\n${codeFrame(query, {
179
+ start,
180
+ end
181
+ }, description)}${withTag}${withTraceId}`;
182
+ }
183
+ function httpErrorMessage(res, body) {
184
+ let details = typeof body == "string" ? ` (${sliceWithEllipsis(body, 100)})` : "", statusMessage = res.statusMessage ? ` ${res.statusMessage}` : "";
185
+ return `${res.method}-request to ${res.url} resulted in HTTP ${res.statusCode}${statusMessage}${details}`;
186
+ }
187
+ /**
188
+ * Extract the traceId from the traceparent header on the response.
189
+ *
190
+ * The traceparent is on the format [version]-[traceId]-[parentId]-[traceFlags], but
191
+ * when debugging end-user issues it's the traceId we need to be able to get hold of
192
+ * the relevant traces.
193
+ *
194
+ * @see https://www.w3.org/TR/trace-context/
195
+ * @returns The traceId for HTTP response
196
+ */
197
+ function extractTraceId(res) {
198
+ let traceparent = res?.headers?.traceparent;
199
+ if (traceparent) return traceparent.split("-")[1];
200
+ }
201
+ function stringifyBody(body, res) {
202
+ return (res.headers["content-type"] || "").toLowerCase().indexOf("application/json") === -1 ? body : JSON.stringify(body, null, 2);
203
+ }
204
+ function formatTraceId(traceId) {
205
+ return traceId ? ` (traceId: ${traceId})` : "";
206
+ }
207
+ function sliceWithEllipsis(str, max) {
208
+ return str.length > max ? `${str.slice(0, max)}…` : str;
209
+ }
210
+ /** @public */
211
+ var CorsOriginError = class extends Error {
212
+ projectId;
213
+ addOriginUrl;
214
+ constructor({ projectId, credentials } = {}) {
215
+ if (super("CorsOriginError"), this.name = "CorsOriginError", this.projectId = projectId, projectId && typeof location < "u") {
216
+ let url = new URL(`https://sanity.io/manage/project/${projectId}/api`), { origin } = location;
217
+ url.searchParams.set("cors", "add"), url.searchParams.set("origin", origin), credentials && url.searchParams.set("credentials", ""), this.addOriginUrl = url, this.message = `The current origin is not allowed to connect to the Live Content API. Add it here: ${url}`;
218
+ } else this.message = projectId ? `The current origin is not allowed to connect to the Live Content API. Change your configuration here: https://sanity.io/manage/project/${projectId}/api` : "The current origin is not allowed to connect to the Live Content API.";
219
+ }
220
+ };
221
+ /**
222
+ * Build both the observable and promise transport forms from a single get-it
223
+ * requester. The promise form is the primitive (`executeRequest` is already
224
+ * promise-based); the observable form wraps it lazily so each subscription
225
+ * starts its own request (cold), and unsubscribing aborts the in-flight
226
+ * fetch — the same contract as the get-it v8 observable adapter.
227
+ *
228
+ * @internal
229
+ */
230
+ function defineRequester(envOptions, config = {}) {
231
+ let applyFetchInit = (opts, next) => {
232
+ let fetchInit = opts.meta?.fetchInit;
233
+ if (typeof fetchInit != "object" || !fetchInit) return next(opts);
234
+ let baseFetch = opts.fetch ?? envOptions.fetch ?? globalThis.fetch, fetchWithInit = (input, init) => baseFetch(input, {
235
+ ...fetchInit,
236
+ ...init
237
+ });
238
+ return next({
239
+ ...opts,
240
+ fetch: fetchWithInit
241
+ });
242
+ }, requester = createRequester({
243
+ ...envOptions.fetch ? { fetch: envOptions.fetch } : {},
244
+ headers: envOptions.headers,
245
+ httpErrors: !0,
246
+ middleware: [
247
+ retry({
248
+ shouldRetry: shouldRetryRequest,
249
+ maxRetries: config.maxRetries ?? 5,
250
+ ...config.retryDelay ? { retryDelay: config.retryDelay } : {}
251
+ }),
252
+ ...envOptions.middleware,
253
+ applyFetchInit,
254
+ printWarnings(config)
255
+ ]
256
+ }), promise = (options) => {
257
+ if (typeof options.url != "string") throw TypeError("Request options must include a `url`");
258
+ return executeRequest(requester, options);
259
+ }, observable = (options) => new Observable((subscriber) => {
260
+ let controller = new AbortController(), userSignal = options.signal, signal = userSignal ? AbortSignal.any([userSignal, controller.signal]) : controller.signal, subscription = from(promise({
261
+ ...options,
262
+ signal
263
+ })).subscribe(subscriber);
264
+ return () => {
265
+ subscription.unsubscribe(), controller.abort();
266
+ };
267
+ });
268
+ return {
269
+ promise,
270
+ observable
271
+ };
272
+ }
273
+ async function executeRequest(requester, fetchOptions) {
274
+ let url = fetchOptions.url, method = (fetchOptions.method ?? "GET").toUpperCase(), response;
275
+ try {
276
+ response = await requester(fetchOptions);
277
+ } catch (err) {
278
+ if (err instanceof HttpError) {
279
+ let errBody = parseJsonText(typeof err.body == "string" ? err.body : "", err.headers), canonical = httpResponseFromFetch({
280
+ status: err.status,
281
+ statusText: err.statusText,
282
+ headers: err.headers,
283
+ body: errBody
284
+ }, url, method), tag = extractRequestTag(fetchOptions.query);
285
+ throw canonical.statusCode >= 500 ? new ServerError(canonical) : new ClientError(canonical, tag);
286
+ }
287
+ throw err;
288
+ }
289
+ return {
290
+ type: "response",
291
+ body: parseJsonBody(response),
292
+ statusCode: response.status,
293
+ statusMessage: response.statusText || null,
294
+ headers: headersToRecord(response.headers),
295
+ url,
296
+ method
297
+ };
298
+ }
299
+ /**
300
+ * Extract the GROQ request tag (used for error messages) from the query.
301
+ */
302
+ function extractRequestTag(query) {
303
+ if (!query) return;
304
+ if (query instanceof URLSearchParams) return query.get("tag") ?? void 0;
305
+ let tag = query.tag;
306
+ return typeof tag == "string" ? tag : void 0;
307
+ }
308
+ function parseJsonBody(response) {
309
+ return parseJsonText(response.text(), response.headers);
310
+ }
311
+ /**
312
+ * Parse a response body according to its `content-type`: JSON when the header
313
+ * says so (falling back to the raw text on malformed JSON), text otherwise.
314
+ * Shared with the browser XHR upload path so error bodies parse identically
315
+ * on both transports.
316
+ *
317
+ * @internal
318
+ */
319
+ function parseJsonText(text, headers) {
320
+ let contentType = (headers.get("content-type") ?? "").toLowerCase();
321
+ if (text) {
322
+ if (contentType.includes("application/json")) try {
323
+ return JSON.parse(text);
324
+ } catch {
325
+ return text;
326
+ }
327
+ return text;
328
+ }
329
+ }
330
+ function headersToRecord(headers) {
331
+ let out = {};
332
+ return headers.forEach((value, key) => {
333
+ out[key] = value;
334
+ }), out;
335
+ }
336
+ function shouldRetryRequest(err, attempt, options) {
337
+ if (err instanceof HttpError) {
338
+ let isSafe = (options.method ?? "GET") === "GET" || options.method === "HEAD", isQuery = (options.url ?? "").includes("/data/query"), status = err.status;
339
+ return !!((isSafe || isQuery) && (status === 429 || status === 502 || status === 503));
340
+ }
341
+ return isRetryableRequest(err, attempt, options);
342
+ }
343
+ function printWarnings(config) {
344
+ let seen = {}, shouldIgnore = (message) => config.ignoreWarnings !== void 0 && (Array.isArray(config.ignoreWarnings) ? config.ignoreWarnings : [config.ignoreWarnings]).some((pattern) => typeof pattern == "string" ? message.includes(pattern) : pattern.test(message));
345
+ return { afterResponse(response) {
346
+ let header = response.headers.get("x-sanity-warning");
347
+ if (!header) return response;
348
+ for (let msg of header.split(",").map((m) => m.trim())) !msg || seen[msg] || shouldIgnore(msg) || (seen[msg] = !0, console.warn(msg));
349
+ return response;
350
+ } };
351
+ }
352
+ export { ServerError as a, isHttpError as c, CorsOriginError as i, isQueryParseError as l, parseJsonText as n, formatQueryParseError as o, ClientError as r, httpResponseFromFetch as s, defineRequester as t };
353
+
354
+ //# sourceMappingURL=request-k7VS_NnC.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"request-k7VS_NnC.js","names":["headersToRecord","GetItHttpError"],"sources":["../src/util/codeFrame.ts","../src/http/errors.ts","../src/http/request.ts"],"sourcesContent":["/**\n * Inlined, modified version of the `codeFrameColumns` function from `@babel/code-frame`.\n * MIT-licensed - https://github.com/babel/babel/blob/main/LICENSE\n * Copyright (c) 2014-present Sebastian McKenzie and other contributors.\n */\ntype Location = {\n column: number\n line: number\n}\n\ntype NodeLocation = {\n start: Location\n end?: Location\n}\n\ntype GroqLocation = {\n start: number\n end?: number\n}\n\n/**\n * RegExp to test for newlines.\n */\n\nconst NEWLINE = /\\r\\n|[\\n\\r\\u2028\\u2029]/\n\n/**\n * Extract what lines should be marked and highlighted.\n */\n\ntype MarkerLines = Record<number, true | [number, number]>\n\n/**\n * Highlight a code frame with the given location and message.\n *\n * @param query - The query to be highlighted.\n * @param location - The location of the error in the code/query.\n * @param message - Message to be displayed inline (if possible) next to the highlighted\n * location in the code. If it can't be positioned inline, it will be placed above the\n * code frame.\n * @returns The highlighted code frame.\n */\nexport function codeFrame(query: string, location: GroqLocation, message?: string): string {\n const lines = query.split(NEWLINE)\n const loc = {\n start: columnToLine(location.start, lines),\n end: location.end ? columnToLine(location.end, lines) : undefined,\n }\n\n const {start, end, markerLines} = getMarkerLines(loc, lines)\n\n const numberMaxWidth = `${end}`.length\n\n return query\n .split(NEWLINE, end)\n .slice(start, end)\n .map((line, index) => {\n const number = start + 1 + index\n const paddedNumber = ` ${number}`.slice(-numberMaxWidth)\n const gutter = ` ${paddedNumber} |`\n const hasMarker = markerLines[number]\n const lastMarkerLine = !markerLines[number + 1]\n if (!hasMarker) {\n return ` ${gutter}${line.length > 0 ? ` ${line}` : ''}`\n }\n\n let markerLine = ''\n if (Array.isArray(hasMarker)) {\n const markerSpacing = line.slice(0, Math.max(hasMarker[0] - 1, 0)).replace(/[^\\t]/g, ' ')\n const numberOfMarkers = hasMarker[1] || 1\n\n markerLine = [\n '\\n ',\n gutter.replace(/\\d/g, ' '),\n ' ',\n markerSpacing,\n '^'.repeat(numberOfMarkers),\n ].join('')\n\n if (lastMarkerLine && message) {\n markerLine += ' ' + message\n }\n }\n return ['>', gutter, line.length > 0 ? ` ${line}` : '', markerLine].join('')\n })\n .join('\\n')\n}\n\nfunction getMarkerLines(\n loc: NodeLocation,\n source: Array<string>,\n): {\n start: number\n end: number\n markerLines: MarkerLines\n} {\n const startLoc: Location = {...loc.start}\n const endLoc: Location = {...startLoc, ...loc.end}\n const linesAbove = 2\n const linesBelow = 3\n const startLine = startLoc.line ?? -1\n const startColumn = startLoc.column ?? 0\n const endLine = endLoc.line\n const endColumn = endLoc.column\n\n let start = Math.max(startLine - (linesAbove + 1), 0)\n let end = Math.min(source.length, endLine + linesBelow)\n\n if (startLine === -1) {\n start = 0\n }\n\n if (endLine === -1) {\n end = source.length\n }\n\n const lineDiff = endLine - startLine\n const markerLines: MarkerLines = {}\n\n if (lineDiff) {\n for (let i = 0; i <= lineDiff; i++) {\n const lineNumber = i + startLine\n\n if (!startColumn) {\n markerLines[lineNumber] = true\n } else if (i === 0) {\n const sourceLength = source[lineNumber - 1].length\n\n markerLines[lineNumber] = [startColumn, sourceLength - startColumn + 1]\n } else if (i === lineDiff) {\n markerLines[lineNumber] = [0, endColumn]\n } else {\n const sourceLength = source[lineNumber - i].length\n\n markerLines[lineNumber] = [0, sourceLength]\n }\n }\n } else {\n if (startColumn === endColumn) {\n if (startColumn) {\n markerLines[startLine] = [startColumn, 0]\n } else {\n markerLines[startLine] = true\n }\n } else {\n markerLines[startLine] = [startColumn, endColumn - startColumn]\n }\n }\n\n return {start, end, markerLines}\n}\n\nfunction columnToLine(column: number, lines: string[]): Location {\n let offset = 0\n\n for (let i = 0; i < lines.length; i++) {\n const lineLength = lines[i].length + 1 // assume '\\n' after each line\n\n if (offset + lineLength > column) {\n return {\n line: i + 1, // 1-based line\n column: column - offset, // 0-based column\n }\n }\n\n offset += lineLength\n }\n\n // Fallback: beyond last line\n return {\n line: lines.length,\n column: lines[lines.length - 1]?.length ?? 0,\n }\n}\n","import type {ActionError, Any, ErrorProps, MutationError, QueryParseError} from '../types'\nimport {codeFrame} from '../util/codeFrame'\nimport {isRecord} from '../util/isRecord'\n\nconst MAX_ITEMS_IN_ERROR_MESSAGE = 5\n\n/**\n * Canonical HTTP response shape used internally to build {@link ClientError}\n * and {@link ServerError}. Decouples the error layer from any particular\n * transport library — adapters in the HTTP layer (e.g. `httpResponseFromGetIt`)\n * project transport-specific response shapes into this stable form before\n * constructing errors.\n *\n * Matches the public {@link HttpError.response} shape so consumers see no\n * difference in error properties when the underlying transport changes.\n *\n * @internal\n */\nexport interface CanonicalHttpResponse {\n statusCode: number\n statusMessage: string | null\n headers: Record<string, string>\n body: unknown\n url: string\n method: string\n}\n\n/**\n * Adapter for buffered responses from get-it v9 (`BufferedResponse`-shaped).\n *\n * The URL and method aren't on the response itself in v9, so the request\n * options must be passed alongside.\n *\n * @internal\n */\nexport function httpResponseFromFetch(\n res: {\n status: number\n statusText: string\n headers: Headers\n body: unknown\n },\n reqUrl: string,\n reqMethod: string,\n): CanonicalHttpResponse {\n return {\n statusCode: res.status,\n statusMessage: res.statusText || null,\n headers: headersToRecord(res.headers),\n body: res.body,\n url: reqUrl,\n method: reqMethod,\n }\n}\n\nfunction headersToRecord(headers: Headers): Record<string, string> {\n const out: Record<string, string> = {}\n headers.forEach((value, key) => {\n out[key] = value\n })\n return out\n}\n\n/**\n * Shared properties for HTTP errors (eg both ClientError and ServerError)\n * Use `isHttpError` for type narrowing and accessing response properties.\n *\n * @public\n */\nexport interface HttpError {\n statusCode: number\n message: string\n response: {\n body: unknown\n url: string\n method: string\n headers: Record<string, string>\n statusCode: number\n statusMessage: string | null\n }\n}\n\n/**\n * Checks if the provided error is an HTTP error.\n *\n * @param error - The error to check.\n * @returns `true` if the error is an HTTP error, `false` otherwise.\n * @public\n */\nexport function isHttpError(error: unknown): error is HttpError {\n if (!isRecord(error)) {\n return false\n }\n\n const response = error.response\n if (\n typeof error.statusCode !== 'number' ||\n typeof error.message !== 'string' ||\n !isRecord(response)\n ) {\n return false\n }\n\n if (\n typeof response.body === 'undefined' ||\n typeof response.url !== 'string' ||\n typeof response.method !== 'string' ||\n typeof response.headers !== 'object' ||\n typeof response.statusCode !== 'number'\n ) {\n return false\n }\n\n return true\n}\n\n/** @public */\nexport class ClientError extends Error {\n response: ErrorProps['response']\n statusCode: ErrorProps['statusCode'] = 400\n responseBody: ErrorProps['responseBody']\n traceId: ErrorProps['traceId']\n details: ErrorProps['details']\n\n constructor(res: Any, tag?: string) {\n const props = extractErrorProps(res, tag)\n super(props.message)\n Object.assign(this, props)\n }\n}\n\n/** @public */\nexport class ServerError extends Error {\n response: ErrorProps['response']\n statusCode: ErrorProps['statusCode'] = 500\n responseBody: ErrorProps['responseBody']\n traceId: ErrorProps['traceId']\n details: ErrorProps['details']\n\n constructor(res: Any) {\n const props = extractErrorProps(res)\n super(props.message)\n Object.assign(this, props)\n }\n}\n\nfunction extractErrorProps(res: Any, tag?: string): ErrorProps {\n const body = res.body\n const props = {\n response: res,\n statusCode: res.statusCode,\n responseBody: stringifyBody(body, res),\n traceId: extractTraceId(res),\n message: '',\n details: undefined as Any,\n }\n\n // Fall back early if we didn't get a JSON object returned as expected\n if (!isRecord(body)) {\n props.message = `${httpErrorMessage(res, body)}${formatTraceId(props.traceId)}`\n return props\n }\n\n const error = body.error\n\n // API/Boom style errors ({statusCode, error, message})\n if (typeof error === 'string' && typeof body.message === 'string') {\n props.message = `${error} - ${body.message}${formatTraceId(props.traceId)}`\n return props\n }\n\n // Content Lake errors with a `error` prop being an object\n if (typeof error !== 'object' || error === null) {\n if (typeof error === 'string') {\n props.message = `${error}${formatTraceId(props.traceId)}`\n } else if (typeof body.message === 'string') {\n props.message = `${body.message}${formatTraceId(props.traceId)}`\n } else {\n props.message = `${httpErrorMessage(res, body)}${formatTraceId(props.traceId)}`\n }\n return props\n }\n\n // Mutation errors (specifically)\n if (isMutationError(error) || isActionError(error)) {\n const allItems = error.items || []\n const items = allItems\n .slice(0, MAX_ITEMS_IN_ERROR_MESSAGE)\n .map((item) => item.error?.description)\n .filter(Boolean)\n let itemsStr = items.length ? `:\\n- ${items.join('\\n- ')}` : ''\n if (allItems.length > MAX_ITEMS_IN_ERROR_MESSAGE) {\n itemsStr += `\\n...and ${allItems.length - MAX_ITEMS_IN_ERROR_MESSAGE} more`\n }\n props.message = `${error.description}${formatTraceId(props.traceId)}${itemsStr}`\n props.details = body.error\n return props\n }\n\n // Query parse errors\n if (isQueryParseError(error)) {\n props.message = formatQueryParseError(error, tag, props.traceId)\n props.details = body.error\n return props\n }\n\n if ('description' in error && typeof error.description === 'string') {\n // Query/database errors ({error: {description, other, arb, props}})\n props.message = `${error.description}${formatTraceId(props.traceId)}`\n props.details = error\n return props\n }\n\n // Other, more arbitrary errors\n props.message = `${httpErrorMessage(res, body)}${formatTraceId(props.traceId)}`\n return props\n}\n\nfunction isMutationError(error: object): error is MutationError {\n return (\n 'type' in error &&\n error.type === 'mutationError' &&\n 'description' in error &&\n typeof error.description === 'string'\n )\n}\n\nfunction isActionError(error: object): error is ActionError {\n return (\n 'type' in error &&\n error.type === 'actionError' &&\n 'description' in error &&\n typeof error.description === 'string'\n )\n}\n\n/** @internal */\nexport function isQueryParseError(error: object): error is QueryParseError {\n return (\n isRecord(error) &&\n error.type === 'queryParseError' &&\n typeof error.query === 'string' &&\n typeof error.start === 'number' &&\n typeof error.end === 'number'\n )\n}\n\n/**\n * Formats a GROQ query parse error into a human-readable string.\n *\n * @param error - The error object containing details about the parse error.\n * @param tag - An optional tag to include in the error message.\n * @returns A formatted error message string.\n * @public\n */\nexport function formatQueryParseError(\n error: QueryParseError,\n tag?: string | null,\n traceId?: string,\n) {\n const {query, start, end, description} = error\n const withTraceId = traceId ? `\\n(traceId: ${traceId})` : ''\n\n if (!query || typeof start === 'undefined') {\n return `GROQ query parse error: ${description}${withTraceId}`\n }\n\n const withTag = tag ? `\\n\\nTag: ${tag}` : ''\n const framed = codeFrame(query, {start, end}, description)\n\n return `GROQ query parse error:\\n${framed}${withTag}${withTraceId}`\n}\n\nfunction httpErrorMessage(res: Any, body: unknown) {\n const details = typeof body === 'string' ? ` (${sliceWithEllipsis(body, 100)})` : ''\n const statusMessage = res.statusMessage ? ` ${res.statusMessage}` : ''\n return `${res.method}-request to ${res.url} resulted in HTTP ${res.statusCode}${statusMessage}${details}`\n}\n\n/**\n * Extract the traceId from the traceparent header on the response.\n *\n * The traceparent is on the format [version]-[traceId]-[parentId]-[traceFlags], but\n * when debugging end-user issues it's the traceId we need to be able to get hold of\n * the relevant traces.\n *\n * @see https://www.w3.org/TR/trace-context/\n * @returns The traceId for HTTP response\n */\nfunction extractTraceId(res: Any): string | undefined {\n const traceparent = res?.headers?.['traceparent']\n if (!traceparent) return\n\n return traceparent.split('-')[1]\n}\n\nfunction stringifyBody(body: Any, res: Any) {\n const contentType = (res.headers['content-type'] || '').toLowerCase()\n const isJson = contentType.indexOf('application/json') !== -1\n return isJson ? JSON.stringify(body, null, 2) : body\n}\n\nfunction formatTraceId(traceId: string | undefined): string {\n return traceId ? ` (traceId: ${traceId})` : ''\n}\n\nfunction sliceWithEllipsis(str: string, max: number) {\n return str.length > max ? `${str.slice(0, max)}…` : str\n}\n\n/** @public */\nexport class CorsOriginError extends Error {\n projectId?: string\n addOriginUrl?: URL\n\n constructor({projectId, credentials}: {projectId?: string; credentials?: boolean} = {}) {\n super('CorsOriginError')\n this.name = 'CorsOriginError'\n this.projectId = projectId\n\n // Only build a deep-link when we know which project the user needs to\n // configure - without `projectId` the management URL can't actually route\n // them anywhere useful.\n if (projectId && typeof location !== 'undefined') {\n const url = new URL(`https://sanity.io/manage/project/${projectId}/api`)\n const {origin} = location\n url.searchParams.set('cors', 'add')\n url.searchParams.set('origin', origin)\n if (credentials) {\n // Pre-selects the \"Allow credentials (token-based auth)\" toggle in\n // the Sanity management CORS form.\n url.searchParams.set('credentials', '')\n }\n this.addOriginUrl = url\n this.message = `The current origin is not allowed to connect to the Live Content API. Add it here: ${url}`\n } else if (projectId) {\n this.message = `The current origin is not allowed to connect to the Live Content API. Change your configuration here: https://sanity.io/manage/project/${projectId}/api`\n } else {\n this.message = `The current origin is not allowed to connect to the Live Content API.`\n }\n }\n}\n","import {\n createRequester,\n type FetchFunction,\n HttpError as GetItHttpError,\n type RequestOptions as FetchRequestOptions,\n type TransformMiddleware,\n type WrappingMiddleware,\n} from 'get-it'\nimport {isRetryableRequest, retry} from 'get-it/middleware'\nimport {from, Observable} from 'rxjs'\n\nimport type {Any} from '../types'\nimport {ClientError, httpResponseFromFetch, ServerError} from './errors'\n\n/**\n * Middleware accepted by the internal HTTP layer. Two flavors per get-it v9:\n * a flat-pipeline transform (`beforeRequest`/`afterResponse`) or a wrapping\n * middleware that surrounds the fetch chain.\n *\n * @internal\n */\nexport type LegacyMiddleware = TransformMiddleware | WrappingMiddleware\n\n/**\n * The shape this client's internal pipeline produces. Mirrors the historical\n * `ResponseEvent` from the get-it v8 multi-event observable, so all the existing\n * downstream code (`_requestObservable`, `_uploadObservable`,\n * `defineCreateClient`) keeps working without churn.\n *\n * @internal\n */\nexport interface ResponseEvent {\n type: 'response'\n body: unknown\n statusCode: number\n statusMessage: string | null\n headers: Record<string, string>\n url: string\n method: string\n}\n\n/**\n * Legacy \"requester\" type — the result of `defineHttpRequest`. Returns a\n * single-event Observable for compatibility with the rest of the codebase.\n *\n * @internal\n */\nexport type LegacyRequester = (options: Any) => Observable<ResponseEvent>\n\n/**\n * Promise-based sibling of {@link LegacyRequester}. Resolves directly to the\n * single `ResponseEvent` the transport produces, skipping the RxJS wrapper.\n * Used by the promise-based client surface so it never constructs an\n * Observable.\n *\n * @internal\n */\nexport type PromiseRequester = (options: Any) => Promise<ResponseEvent>\n\n/**\n * Both forms of the transport, sharing a single underlying get-it requester\n * (so retry state and the one-shot warning de-duplication are shared between\n * the observable and promise paths).\n *\n * @internal\n */\nexport interface DualRequester {\n observable: LegacyRequester\n promise: PromiseRequester\n}\n\n/**\n * Options for tuning the HTTP request pipeline per-client.\n *\n * @internal\n */\nexport interface HttpRequestConfig {\n ignoreWarnings?: string | RegExp | Array<string | RegExp>\n maxRetries?: number\n retryDelay?: (attemptNumber: number) => number\n}\n\n/**\n * Build both the observable and promise transport forms from a single get-it\n * requester. The promise form is the primitive (`executeRequest` is already\n * promise-based); the observable form wraps it lazily so each subscription\n * starts its own request (cold), and unsubscribing aborts the in-flight\n * fetch — the same contract as the get-it v8 observable adapter.\n *\n * @internal\n */\nexport function defineRequester(\n envOptions: EnvironmentOptions,\n config: HttpRequestConfig = {},\n): DualRequester {\n // Framework-patched fetch implementations read extra `RequestInit` fields\n // for caching semantics — Next.js App Router's `cache` and `next` options in\n // particular. Legacy callers pass those via an object-valued `fetch` request\n // option (see `adaptToFetchOptions`, which stashes it in `meta.fetchInit`\n // since get-it v9's own `fetch` option only accepts a function). Merge them\n // into the init of whichever fetch implementation is effective for the\n // request: per-request/test-override fetch, the environment default, or the\n // global fetch.\n const applyFetchInit: WrappingMiddleware = (opts, next) => {\n const fetchInit = opts.meta?.fetchInit\n if (typeof fetchInit !== 'object' || fetchInit === null) return next(opts)\n const baseFetch: NonNullable<FetchRequestOptions['fetch']> =\n opts.fetch ?? envOptions.fetch ?? globalThis.fetch\n const fetchWithInit: typeof baseFetch = (input, init) =>\n baseFetch(input, {...fetchInit, ...init})\n return next({...opts, fetch: fetchWithInit})\n }\n\n const requester = createRequester({\n ...(envOptions.fetch ? {fetch: envOptions.fetch} : {}),\n headers: envOptions.headers,\n // Keep get-it's built-in 4xx/5xx → HttpError so the retry middleware can\n // see them; we translate to ClientError/ServerError after the retry loop\n // has exhausted in `executeRequest`.\n httpErrors: true,\n middleware: [\n retry({\n shouldRetry: shouldRetryRequest,\n maxRetries: config.maxRetries ?? 5,\n ...(config.retryDelay ? {retryDelay: config.retryDelay} : {}),\n }),\n ...envOptions.middleware,\n applyFetchInit,\n printWarnings(config),\n ],\n })\n\n const promise: PromiseRequester = (options: Any) => {\n // Options arrive fetch-shaped from `requestOptions` — the single\n // translation boundary between public option names and the transport.\n if (typeof options.url !== 'string') {\n throw new TypeError('Request options must include a `url`')\n }\n return executeRequest(requester, options)\n }\n\n // Same per-subscription AbortController pattern as `_observe` in\n // dataMethods: a caller-supplied signal is combined in via\n // `AbortSignal.any`, so the request aborts both on the caller's signal and\n // on unsubscribe. `AbortSignal.any` (rather than `addEventListener`)\n // because the caller's signal can be long-lived and reused — a manually\n // added listener would accumulate there once per subscription, since\n // `{once: true}` only cleans up if the signal actually fires.\n const observable: LegacyRequester = (options: Any) =>\n new Observable<ResponseEvent>((subscriber) => {\n const controller = new AbortController()\n const userSignal: AbortSignal | undefined = options.signal\n const signal = userSignal\n ? AbortSignal.any([userSignal, controller.signal])\n : controller.signal\n const subscription = from(promise({...options, signal})).subscribe(subscriber)\n return () => {\n subscription.unsubscribe()\n controller.abort()\n }\n })\n\n return {promise, observable}\n}\n\n/** @internal */\nexport function defineHttpRequest(\n envOptions: EnvironmentOptions,\n config: HttpRequestConfig = {},\n): LegacyRequester {\n return defineRequester(envOptions, config).observable\n}\n\n/**\n * Options describing the environment-specific defaults (Node vs. browser).\n *\n * @internal\n */\nexport interface EnvironmentOptions {\n fetch?: FetchRequestOptions['fetch']\n headers?: Record<string, string>\n middleware: LegacyMiddleware[]\n /**\n * Resolves the environment's fetch implementation — the same transport\n * regular requests use (custom fetch variants, undici configuration,\n * env-proxy support and all), optionally configured for an explicit proxy\n * URL. Lets consumers of the resolved config (the EventSource fetch\n * resolver) avoid falling back to whatever `globalThis.fetch` happens to\n * be. The Node environment supplies get-it's undici-backed fetch; the\n * browser environment leaves it unset (the global fetch IS the\n * environment's fetch there).\n *\n * Looked up via the env rather than imported directly so that the Node-only\n * `get-it/node` (which transitively pulls in `undici`) never ends up in the\n * browser bundle, even via rollup's inlined dynamic imports.\n */\n resolveFetch?: (proxyUrl?: string) => FetchFunction\n}\n\nasync function executeRequest(\n requester: ReturnType<typeof createRequester>,\n fetchOptions: FetchRequestOptions,\n): Promise<ResponseEvent> {\n const url = fetchOptions.url\n const method = (fetchOptions.method ?? 'GET').toUpperCase()\n\n let response\n try {\n response = await requester(fetchOptions)\n } catch (err) {\n if (err instanceof GetItHttpError) {\n // `err.body` is the response body as a string (get-it v9 stores the\n // already-decoded text), regardless of which response variant\n // `err.response` is.\n const errBodyText = typeof err.body === 'string' ? err.body : ''\n const errBody = parseJsonText(errBodyText, err.headers)\n const canonical = httpResponseFromFetch(\n {\n status: err.status,\n statusText: err.statusText,\n headers: err.headers,\n body: errBody,\n },\n url,\n method,\n )\n const tag = extractRequestTag(fetchOptions.query)\n if (canonical.statusCode >= 500) {\n throw new ServerError(canonical)\n }\n throw new ClientError(canonical, tag)\n }\n throw err\n }\n\n const body = parseJsonBody(response)\n return {\n type: 'response',\n body,\n statusCode: response.status,\n statusMessage: response.statusText || null,\n headers: headersToRecord(response.headers),\n url,\n method,\n }\n}\n\n/**\n * Extract the GROQ request tag (used for error messages) from the query.\n */\nfunction extractRequestTag(query: FetchRequestOptions['query']): string | undefined {\n if (!query) return undefined\n if (query instanceof URLSearchParams) return query.get('tag') ?? undefined\n const tag = query.tag\n return typeof tag === 'string' ? tag : undefined\n}\n\nfunction parseJsonBody(response: {headers: Headers; text(): string}): unknown {\n return parseJsonText(response.text(), response.headers)\n}\n\n/**\n * Parse a response body according to its `content-type`: JSON when the header\n * says so (falling back to the raw text on malformed JSON), text otherwise.\n * Shared with the browser XHR upload path so error bodies parse identically\n * on both transports.\n *\n * @internal\n */\nexport function parseJsonText(text: string, headers: Headers): unknown {\n const contentType = (headers.get('content-type') ?? '').toLowerCase()\n if (!text) return undefined\n if (contentType.includes('application/json')) {\n try {\n return JSON.parse(text)\n } catch {\n return text\n }\n }\n return text\n}\n\nfunction headersToRecord(headers: Headers): Record<string, string> {\n const out: Record<string, string> = {}\n headers.forEach((value, key) => {\n out[key] = value\n })\n return out\n}\n\nfunction shouldRetryRequest(err: unknown, attempt: number, options: FetchRequestOptions): boolean {\n // HTTP errors aren't usually retryable, but Content Lake gives us a few\n // status codes where retrying *is* the right move.\n if (err instanceof GetItHttpError) {\n const isSafe = (options.method ?? 'GET') === 'GET' || options.method === 'HEAD'\n const isQuery = (options.url ?? '').includes('/data/query')\n const status = err.status\n const retryableStatus = status === 429 || status === 502 || status === 503\n if ((isSafe || isQuery) && retryableStatus) return true\n return false\n }\n\n return isRetryableRequest(err, attempt, options)\n}\n\nfunction printWarnings(config: HttpRequestConfig): TransformMiddleware {\n const seen: Record<string, boolean> = {}\n\n const shouldIgnore = (message: string): boolean => {\n if (config.ignoreWarnings === undefined) return false\n const patterns = Array.isArray(config.ignoreWarnings)\n ? config.ignoreWarnings\n : [config.ignoreWarnings]\n return patterns.some((pattern) =>\n typeof pattern === 'string' ? message.includes(pattern) : pattern.test(message),\n )\n }\n\n return {\n afterResponse(response) {\n const header = response.headers.get('x-sanity-warning')\n if (!header) return response\n // Multiple warnings can be comma-separated per HTTP header semantics.\n for (const msg of header.split(',').map((m) => m.trim())) {\n if (!msg || seen[msg] || shouldIgnore(msg)) continue\n seen[msg] = true\n // oxlint-disable-next-line no-console\n console.warn(msg)\n }\n return response\n },\n }\n}\n"],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