@sanity/client 8.0.0 → 8.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +265 -0
- package/dist/{browserUpload-CQgx9YYo.js → browserUpload-2tz6Sdqp.js} +4 -3
- package/dist/browserUpload-2tz6Sdqp.js.map +1 -0
- package/dist/{browserUpload-icWlVP15.js → browserUpload-CwpNx7Vl.js} +4 -3
- package/dist/browserUpload-CwpNx7Vl.js.map +1 -0
- package/dist/{config-a8VajuEY.js → config-3wiPP-sZ.js} +2 -2
- package/dist/config-3wiPP-sZ.js.map +1 -0
- package/dist/csm.js +2 -2
- package/dist/csm.js.map +1 -1
- package/dist/index.d.ts +17 -11
- package/dist/index.js +610 -136
- package/dist/index.js.map +1 -1
- package/dist/index.node.d.ts +918 -26
- package/dist/index.node.js +559 -66
- package/dist/index.node.js.map +1 -1
- package/dist/media-library.d.ts +1 -1
- package/dist/{request-CJxcN16k.js → request-BhMuKj0D.js} +10 -9
- package/dist/request-BhMuKj0D.js.map +1 -0
- package/dist/{request-k7VS_NnC.js → request-SnMg7nUX.js} +10 -9
- package/dist/request-SnMg7nUX.js.map +1 -0
- package/dist/{resolveEditInfo-sq7yF78q.js → resolveEditInfo-Cz-smq3a.js} +17 -3
- package/dist/resolveEditInfo-Cz-smq3a.js.map +1 -0
- package/dist/stega.js +1 -1
- package/dist/{stegaEncodeSourceMap-DkoIlutY.js → stegaEncodeSourceMap-DbM2fTN4.js} +8 -2
- package/dist/stegaEncodeSourceMap-DbM2fTN4.js.map +1 -0
- package/dist/{stegaEncodeSourceMap-B2fGArSf.js → stegaEncodeSourceMap-YR3NQ3iz.js} +2 -2
- package/dist/{stegaEncodeSourceMap-B2fGArSf.js.map → stegaEncodeSourceMap-YR3NQ3iz.js.map} +1 -1
- package/dist/{types-CUxZSgB2.d.ts → types-nJhm5Nyq.d.ts} +910 -24
- package/package.json +26 -11
- package/src/SanityClient.ts +39 -20
- package/src/assets/AssetsClient.ts +54 -5
- package/src/collaboration/CollaborationCommentsClient.ts +387 -0
- package/src/collaboration/comments.ts +313 -0
- package/src/collaboration/types.ts +252 -0
- package/src/csm/applySourceDocuments.ts +2 -4
- package/src/csm/draftUtils.ts +23 -4
- package/src/data/dataMethods.ts +9 -20
- package/src/data/eventsource.ts +71 -41
- package/src/data/listen.ts +20 -5
- package/src/data/live.ts +17 -9
- package/src/data/resolveEventSourceFetch.ts +9 -1
- package/src/defineCreateClient.ts +5 -1
- package/src/functions/FunctionsClient.ts +66 -0
- package/src/functions/invoke.ts +176 -0
- package/src/http/browserUpload.ts +1 -0
- package/src/http/errors.ts +2 -1
- package/src/http/request.ts +8 -14
- package/src/mediaLibrary/MediaLibraryVideoClient.ts +1 -1
- package/src/types.ts +420 -4
- package/src/validators.ts +1 -1
- package/src/warnings.ts +7 -1
- package/dist/browserUpload-CQgx9YYo.js.map +0 -1
- package/dist/browserUpload-icWlVP15.js.map +0 -1
- package/dist/config-a8VajuEY.js.map +0 -1
- package/dist/request-CJxcN16k.js.map +0 -1
- package/dist/request-k7VS_NnC.js.map +0 -1
- package/dist/resolveEditInfo-sq7yF78q.js.map +0 -1
- package/dist/stegaEncodeSourceMap-DkoIlutY.js.map +0 -1
package/dist/media-library.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { _r as VideoSubtitleInfoPublic, dr as VideoPlaybackInfoSigned, fr as VideoPlaybackTokens, gr as VideoSubtitleInfo, hr as VideoRenditionInfoSigned, mr as VideoRenditionInfoPublic, or as VideoPlaybackInfo, pr as VideoRenditionInfo, vr as VideoSubtitleInfoSigned } from "./types-nJhm5Nyq.js";
|
|
2
2
|
/**
|
|
3
3
|
* Check if the entire playback info response requires signed URLs
|
|
4
4
|
* @public
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { t as isRecord } from "./isRecord-Kfmt-nk-.js";
|
|
2
|
-
import {
|
|
2
|
+
import { createRequester, isHttpError } from "get-it";
|
|
3
3
|
import { isRetryableRequest, retry } from "get-it/middleware";
|
|
4
4
|
import { Observable, from } from "rxjs";
|
|
5
5
|
/**
|
|
@@ -120,7 +120,7 @@ function httpResponseFromFetch(res, reqUrl, reqMethod) {
|
|
|
120
120
|
statusMessage: res.statusText || null,
|
|
121
121
|
headers: headersToRecord$1(res.headers),
|
|
122
122
|
body: res.body,
|
|
123
|
-
url: reqUrl,
|
|
123
|
+
url: res.url || reqUrl,
|
|
124
124
|
method: reqMethod
|
|
125
125
|
};
|
|
126
126
|
}
|
|
@@ -137,7 +137,7 @@ function headersToRecord$1(headers) {
|
|
|
137
137
|
* @returns `true` if the error is an HTTP error, `false` otherwise.
|
|
138
138
|
* @public
|
|
139
139
|
*/
|
|
140
|
-
function isHttpError(error) {
|
|
140
|
+
function isHttpError$1(error) {
|
|
141
141
|
if (!isRecord(error)) return !1;
|
|
142
142
|
let response = error.response;
|
|
143
143
|
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");
|
|
@@ -293,12 +293,13 @@ async function executeRequest(requester, fetchOptions) {
|
|
|
293
293
|
try {
|
|
294
294
|
response = await requester(fetchOptions);
|
|
295
295
|
} catch (err) {
|
|
296
|
-
if (err
|
|
296
|
+
if (isHttpError(err)) {
|
|
297
297
|
let errBody = parseJsonText(typeof err.body == "string" ? err.body : "", err.headers), canonical = httpResponseFromFetch({
|
|
298
298
|
status: err.status,
|
|
299
299
|
statusText: err.statusText,
|
|
300
300
|
headers: err.headers,
|
|
301
|
-
body: errBody
|
|
301
|
+
body: errBody,
|
|
302
|
+
url: err.response.url ?? err.url
|
|
302
303
|
}, url, method), tag = extractRequestTag(fetchOptions.query);
|
|
303
304
|
throw canonical.statusCode >= 500 ? new ServerError(canonical) : new ClientError(canonical, tag);
|
|
304
305
|
}
|
|
@@ -310,7 +311,7 @@ async function executeRequest(requester, fetchOptions) {
|
|
|
310
311
|
statusCode: response.status,
|
|
311
312
|
statusMessage: response.statusText || null,
|
|
312
313
|
headers: headersToRecord(response.headers),
|
|
313
|
-
url,
|
|
314
|
+
url: response.url || url,
|
|
314
315
|
method
|
|
315
316
|
};
|
|
316
317
|
}
|
|
@@ -352,7 +353,7 @@ function headersToRecord(headers) {
|
|
|
352
353
|
}), out;
|
|
353
354
|
}
|
|
354
355
|
function shouldRetryRequest(err, attempt, options) {
|
|
355
|
-
if (err
|
|
356
|
+
if (isHttpError(err)) {
|
|
356
357
|
let isSafe = (options.method ?? "GET") === "GET" || options.method === "HEAD", isQuery = (options.url ?? "").includes("/data/query"), status = err.status;
|
|
357
358
|
return !!((isSafe || isQuery) && (status === 429 || status === 502 || status === 503));
|
|
358
359
|
}
|
|
@@ -367,6 +368,6 @@ function printWarnings(config) {
|
|
|
367
368
|
return response;
|
|
368
369
|
} };
|
|
369
370
|
}
|
|
370
|
-
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, _defineProperty as u };
|
|
371
|
+
export { ServerError as a, isHttpError$1 as c, CorsOriginError as i, isQueryParseError as l, parseJsonText as n, formatQueryParseError as o, ClientError as r, httpResponseFromFetch as s, defineRequester as t, _defineProperty as u };
|
|
371
372
|
|
|
372
|
-
//# sourceMappingURL=request-
|
|
373
|
+
//# sourceMappingURL=request-BhMuKj0D.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"request-BhMuKj0D.js","names":["headersToRecord","isHttpError","isGetItHttpError"],"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 url: string\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: res.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 isHttpError as isGetItHttpError,\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 observable half of `defineRequester`'s\n * result. Returns a single-event Observable for compatibility with the rest\n * 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/**\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 (isGetItHttpError(err)) {\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 url: err.response.url ?? err.url,\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: response.url || 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 (isGetItHttpError(err)) {\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"],"mappings":";;;;;;;AAwBA,MAAM,UAAU;;;;;;;;;;;AAkBhB,SAAgB,UAAU,OAAe,UAAwB,SAA0B;CACzF,IAAM,QAAQ,MAAM,MAAM,OAAO,GAM3B,EAAC,OAAO,KAAK,gBAAe,eAAe;EAJ/C,OAAO,aAAa,SAAS,OAAO,KAAK;EACzC,KAAK,SAAS,MAAM,aAAa,SAAS,KAAK,KAAK,IAAI,KAAA;CAGP,GAAG,KAAK,GAErD,iBAAiB,GAAG,MAAM;CAEhC,OAAO,MACJ,MAAM,SAAS,GAAG,CAAC,CACnB,MAAM,OAAO,GAAG,CAAC,CACjB,KAAK,MAAM,UAAU;EACpB,IAAM,SAAS,QAAQ,IAAI,OAErB,SAAS,IADM,IAAI,SAAS,MAAM,CAAC,cACX,EAAE,KAC1B,YAAY,YAAY,SACxB,iBAAiB,CAAC,YAAY,SAAS;EAC7C,IAAI,CAAC,WACH,OAAO,IAAI,SAAS,KAAK,SAAS,IAAI,IAAI,SAAS;EAGrD,IAAI,aAAa;EACjB,IAAI,MAAM,QAAQ,SAAS,GAAG;GAC5B,IAAM,gBAAgB,KAAK,MAAM,GAAG,KAAK,IAAI,UAAU,KAAK,GAAG,CAAC,CAAC,CAAC,CAAC,QAAQ,UAAU,GAAG,GAClF,kBAAkB,UAAU,MAAM;GAUxC,AARA,aAAa;IACX;IACA,OAAO,QAA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AAc,SAAiB,SAAuC;CAGhG,IAAIA,YAAiB,GAAG,GAAG;EACzB,IAAM,UAAU,QAAQ,UAAU,WAAW,SAAS,QAAQ,WAAW,QACnE,WAAW,QAAQ,OAAO,GAAA,CAAI,SAAS,aAAa,GACpD,SAAS,IAAI;EAGnB,OADA,IAAK,UAAU,aADS,WAAW,OAAO,WAAW,OAAO,WAAW;CAGzE;CAEA,OAAO,mBAAmB,KAAK,SAAS,OAAO;AACjD;AAEA,SAAS,cAAc,QAAgD;CACrE,IAAM,OAAgC,CAAC,GAEjC,gBAAgB,YAChB,OAAO,mBAAmB,KAAA,MACb,MAAM,QAAQ,OAAO,cAAc,IAChD,OAAO,iBACP,CAAC,OAAO,cAAc,EAAA,CACV,MAAM,YACpB,OAAO,WAAY,WAAW,QAAQ,SAAS,OAAO,IAAI,QAAQ,KAAK,OAAO,CAChF;CAGF,OAAO,EACL,cAAc,UAAU;EACtB,IAAM,SAAS,SAAS,QAAQ,IAAI,kBAAkB;EACtD,IAAI,CAAC,QAAQ,OAAO;EAEpB,KAAK,IAAM,OAAO,OAAO,MAAM,GAAG,CAAC,CAAC,KAAK,MAAM,EAAE,KAAK,CAAC,GACjD,CAAC,OAAO,KAAK,QAAQ,aAAa,GAAG,MACzC,KAAK,OAAO,IAEZ,QAAQ,KAAK,GAAG;EAElB,OAAO;CACT,EACF;AACF"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { t as isRecord } from "./isRecord-Kfmt-nk-.js";
|
|
2
|
-
import {
|
|
2
|
+
import { createRequester, isHttpError } from "get-it";
|
|
3
3
|
import { isRetryableRequest, retry } from "get-it/middleware";
|
|
4
4
|
import { Observable, from } from "rxjs";
|
|
5
5
|
/**
|
|
@@ -90,7 +90,7 @@ function httpResponseFromFetch(res, reqUrl, reqMethod) {
|
|
|
90
90
|
statusMessage: res.statusText || null,
|
|
91
91
|
headers: headersToRecord$1(res.headers),
|
|
92
92
|
body: res.body,
|
|
93
|
-
url: reqUrl,
|
|
93
|
+
url: res.url || reqUrl,
|
|
94
94
|
method: reqMethod
|
|
95
95
|
};
|
|
96
96
|
}
|
|
@@ -107,7 +107,7 @@ function headersToRecord$1(headers) {
|
|
|
107
107
|
* @returns `true` if the error is an HTTP error, `false` otherwise.
|
|
108
108
|
* @public
|
|
109
109
|
*/
|
|
110
|
-
function isHttpError(error) {
|
|
110
|
+
function isHttpError$1(error) {
|
|
111
111
|
if (!isRecord(error)) return !1;
|
|
112
112
|
let response = error.response;
|
|
113
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");
|
|
@@ -275,12 +275,13 @@ async function executeRequest(requester, fetchOptions) {
|
|
|
275
275
|
try {
|
|
276
276
|
response = await requester(fetchOptions);
|
|
277
277
|
} catch (err) {
|
|
278
|
-
if (err
|
|
278
|
+
if (isHttpError(err)) {
|
|
279
279
|
let errBody = parseJsonText(typeof err.body == "string" ? err.body : "", err.headers), canonical = httpResponseFromFetch({
|
|
280
280
|
status: err.status,
|
|
281
281
|
statusText: err.statusText,
|
|
282
282
|
headers: err.headers,
|
|
283
|
-
body: errBody
|
|
283
|
+
body: errBody,
|
|
284
|
+
url: err.response.url ?? err.url
|
|
284
285
|
}, url, method), tag = extractRequestTag(fetchOptions.query);
|
|
285
286
|
throw canonical.statusCode >= 500 ? new ServerError(canonical) : new ClientError(canonical, tag);
|
|
286
287
|
}
|
|
@@ -292,7 +293,7 @@ async function executeRequest(requester, fetchOptions) {
|
|
|
292
293
|
statusCode: response.status,
|
|
293
294
|
statusMessage: response.statusText || null,
|
|
294
295
|
headers: headersToRecord(response.headers),
|
|
295
|
-
url,
|
|
296
|
+
url: response.url || url,
|
|
296
297
|
method
|
|
297
298
|
};
|
|
298
299
|
}
|
|
@@ -334,7 +335,7 @@ function headersToRecord(headers) {
|
|
|
334
335
|
}), out;
|
|
335
336
|
}
|
|
336
337
|
function shouldRetryRequest(err, attempt, options) {
|
|
337
|
-
if (err
|
|
338
|
+
if (isHttpError(err)) {
|
|
338
339
|
let isSafe = (options.method ?? "GET") === "GET" || options.method === "HEAD", isQuery = (options.url ?? "").includes("/data/query"), status = err.status;
|
|
339
340
|
return !!((isSafe || isQuery) && (status === 429 || status === 502 || status === 503));
|
|
340
341
|
}
|
|
@@ -349,6 +350,6 @@ function printWarnings(config) {
|
|
|
349
350
|
return response;
|
|
350
351
|
} };
|
|
351
352
|
}
|
|
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
|
+
export { ServerError as a, isHttpError$1 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
|
|
|
354
|
-
//# sourceMappingURL=request-
|
|
355
|
+
//# sourceMappingURL=request-SnMg7nUX.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"request-SnMg7nUX.js","names":["headersToRecord","isHttpError","isGetItHttpError"],"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 url: string\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: res.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 isHttpError as isGetItHttpError,\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 observable half of `defineRequester`'s\n * result. Returns a single-event Observable for compatibility with the rest\n * 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/**\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 (isGetItHttpError(err)) {\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 url: err.response.url ?? err.url,\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: response.url || 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 (isGetItHttpError(err)) {\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"],"mappings":";;;;;;;AAwBA,MAAM,UAAU;;;;;;;;;;;AAkBhB,SAAgB,UAAU,OAAe,UAAwB,SAA0B;CACzF,IAAM,QAAQ,MAAM,MAAM,OAAO,GAM3B,EAAC,OAAO,KAAK,gBAAe,eAAe;EAJ/C,OAAO,aAAa,SAAS,OAAO,KAAK;EACzC,KAAK,SAAS,MAAM,aAAa,SAAS,KAAK,KAAK,IAAI,KAAA;CAGP,GAAG,KAAK,GAErD,iBAAiB,GAAG,MAAM;CAEhC,OAAO,MACJ,MAAM,SAAS,GAAG,CAAC,CACnB,MAAM,OAAO,GAAG,CAAC,CACjB,KAAK,MAAM,UAAU;EACpB,IAAM,SAAS,QAAQ,IAAI,OAErB,SAAS,IADM,IAAI,SAAS,MAAM,CAAC,cACX,EAAE,KAC1B,YAAY,YAAY,SACxB,iBAAiB,CAAC,YAAY,SAAS;EAC7C,IAAI,CAAC,WACH,OAAO,IAAI,SAAS,KAAK,SAAS,IAAI,IAAI,SAAS;EAGrD,IAAI,aAAa;EACjB,IAAI,MAAM,QAAQ,SAAS,GAAG;GAC5B,IAAM,gBAAgB,KAAK,MAAM,GAAG,KAAK,IAAI,UAAU,KAAK,GAAG,CAAC,CAAC,CAAC,CAAC,QAAQ,UAAU,GAAG,GAClF,kBAAkB,UAAU,MAAM;GAUxC,AARA,aAAa;IACX;IACA,OAAO,QAAQ,OAAO,GAAG;IACzB;IACA;IACA,IAAI,OAAO,eAAe;GAC5B,CAAC,CAAC,KAAK,EAAE,GAEL,kBAAkB,YACpB,cAAc,MAAM;EAExB;EACA,OAAO;GAAC;GAAK;GAAQ,KAAK,SAAS,IAAI,IAAI,SAAS;GAAI;EAAU,CAAC,CAAC,KAAK,EAAE;CAC7E,CAAC,CAAC,CACD,KAAK,IAAI;AACd;AAEA,SAAS,eACP,KACA,QAKA;CACA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AG,CAAC,CAAC,KAAK,MAAM,EAAE,KAAK,CAAC,GACjD,CAAC,OAAO,KAAK,QAAQ,aAAa,GAAG,MACzC,KAAK,OAAO,IAEZ,QAAQ,KAAK,GAAG;EAElB,OAAO;CACT,EACF;AACF"}
|
|
@@ -93,11 +93,22 @@ function isVersionId(id) {
|
|
|
93
93
|
function isPublishedId(id) {
|
|
94
94
|
return !isDraftId(id) && !isVersionId(id);
|
|
95
95
|
}
|
|
96
|
+
/**
|
|
97
|
+
* A phantom brand like `DraftId` has no runtime representation, so it can never be produced
|
|
98
|
+
* by narrowing a string - there's nothing to check. These two functions are the only places
|
|
99
|
+
* allowed to assert a plain string into a branded id.
|
|
100
|
+
*/
|
|
101
|
+
function asDraftId(value) {
|
|
102
|
+
return value;
|
|
103
|
+
}
|
|
104
|
+
function asPublishedId(value) {
|
|
105
|
+
return value;
|
|
106
|
+
}
|
|
96
107
|
/** @internal */
|
|
97
108
|
function getDraftId(id) {
|
|
98
109
|
if (isVersionId(id)) {
|
|
99
110
|
let publishedId = getPublishedId(id);
|
|
100
|
-
return DRAFTS_PREFIX + publishedId;
|
|
111
|
+
return asDraftId(DRAFTS_PREFIX + publishedId);
|
|
101
112
|
}
|
|
102
113
|
return isDraftId(id) ? id : DRAFTS_PREFIX + id;
|
|
103
114
|
}
|
|
@@ -120,7 +131,10 @@ function getVersionFromId(id) {
|
|
|
120
131
|
}
|
|
121
132
|
/** @internal */
|
|
122
133
|
function getPublishedId(id) {
|
|
123
|
-
|
|
134
|
+
if (isVersionId(id)) return asPublishedId(id.split(".").slice(2).join("."));
|
|
135
|
+
if (isDraftId(id)) return asPublishedId(id.slice(DRAFTS_PREFIX.length));
|
|
136
|
+
if (isPublishedId(id)) return id;
|
|
137
|
+
throw Error(`Unable to resolve a published id from "${id}"`);
|
|
124
138
|
}
|
|
125
139
|
const ESCAPE = {
|
|
126
140
|
"\f": "\\f",
|
|
@@ -322,4 +336,4 @@ function resolveStudioBaseRoute(studioUrl) {
|
|
|
322
336
|
}
|
|
323
337
|
export { toString as S, isPublishedId as _, resolveMapping as a, reKeySegment as b, parseJsonPath as c, VERSION_FOLDER as d, getDraftId as f, isDraftId as g, getVersionId as h, walkMap as i, studioPathToJsonPath as l, getVersionFromId as m, resolveStudioBaseRoute as n, jsonPath as o, getPublishedId as p, createEditUrl as r, jsonPathToStudioPath as s, resolveEditInfo as t, DRAFTS_FOLDER as u, isVersionId as v, studioPath_exports as x, get as y };
|
|
324
338
|
|
|
325
|
-
//# sourceMappingURL=resolveEditInfo-
|
|
339
|
+
//# sourceMappingURL=resolveEditInfo-Cz-smq3a.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"resolveEditInfo-Cz-smq3a.js","names":["studioPath.fromString","studioPath.toString"],"sources":["../src/csm/studioPath.ts","../src/csm/draftUtils.ts","../src/csm/jsonPath.ts","../src/csm/resolveMapping.ts","../src/csm/isArray.ts","../src/csm/walkMap.ts","../src/csm/createEditUrl.ts","../src/csm/resolveEditInfo.ts"],"sourcesContent":["/** @alpha */\nexport type KeyedSegment = {_key: string}\n\n/** @alpha */\nexport type IndexTuple = [number | '', number | '']\n\n/** @alpha */\nexport type PathSegment = string | number | KeyedSegment | IndexTuple\n\n/** @alpha */\nexport type Path = PathSegment[]\n\nconst rePropName =\n /[^.[\\]]+|\\[(?:(-?\\d+(?:\\.\\d+)?)|([\"'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2)\\]|(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))/g\n/** @internal */\nexport const reKeySegment = /_key\\s*==\\s*['\"](.*)['\"]/\nconst reIndexTuple = /^\\d*:\\d*$/\n\n/** @internal */\nexport function isIndexSegment(segment: PathSegment): segment is number {\n return typeof segment === 'number' || (typeof segment === 'string' && /^\\[\\d+\\]$/.test(segment))\n}\n\n/** @internal */\nexport function isKeySegment(segment: PathSegment): segment is KeyedSegment {\n if (typeof segment === 'string') {\n return reKeySegment.test(segment.trim())\n }\n\n return typeof segment === 'object' && '_key' in segment\n}\n\n/** @internal */\nexport function isIndexTuple(segment: PathSegment): segment is IndexTuple {\n if (typeof segment === 'string' && reIndexTuple.test(segment)) {\n return true\n }\n\n if (!Array.isArray(segment) || segment.length !== 2) {\n return false\n }\n\n const [from, to] = segment\n return (typeof from === 'number' || from === '') && (typeof to === 'number' || to === '')\n}\n\n/** @internal */\n// oxlint-disable-next-line typescript/no-unnecessary-type-parameters -- caller-supplied return type; removing it breaks `get<Result>(...)` call sites\nexport function get<Result = unknown, Fallback = unknown>(\n obj: unknown,\n path: Path | string,\n defaultVal?: Fallback,\n): Result | typeof defaultVal {\n const select = typeof path === 'string' ? fromString(path) : path\n if (!Array.isArray(select)) {\n throw new Error('Path must be an array or a string')\n }\n\n let acc: unknown = obj\n for (let i = 0; i < select.length; i++) {\n const segment = select[i]\n if (isIndexSegment(segment)) {\n if (!Array.isArray(acc)) {\n return defaultVal\n }\n\n acc = acc[segment]\n }\n\n if (isKeySegment(segment)) {\n if (!Array.isArray(acc)) {\n return defaultVal\n }\n\n acc = acc.find((item) => item._key === segment._key)\n }\n\n if (typeof segment === 'string') {\n acc =\n typeof acc === 'object' && acc !== null\n ? ((acc as Record<string, unknown>)[segment] as Result)\n : undefined\n }\n\n if (typeof acc === 'undefined') {\n return defaultVal\n }\n }\n\n return acc as Result\n}\n\n/** @alpha */\nexport function toString(path: Path): string {\n if (!Array.isArray(path)) {\n throw new Error('Path is not an array')\n }\n\n return path.reduce<string>((target, segment, i) => {\n const segmentType = typeof segment\n if (segmentType === 'number') {\n return `${target}[${segment}]`\n }\n\n if (segmentType === 'string') {\n const separator = i === 0 ? '' : '.'\n return `${target}${separator}${segment}`\n }\n\n if (isKeySegment(segment) && segment._key) {\n return `${target}[_key==\"${segment._key}\"]`\n }\n\n if (Array.isArray(segment)) {\n const [from, to] = segment\n return `${target}[${from}:${to}]`\n }\n\n throw new Error(`Unsupported path segment \\`${JSON.stringify(segment)}\\``)\n }, '')\n}\n\n/** @alpha */\nexport function fromString(path: string): Path {\n if (typeof path !== 'string') {\n throw new Error('Path is not a string')\n }\n\n const segments = path.match(rePropName)\n if (!segments) {\n throw new Error('Invalid path string')\n }\n\n return segments.map(parsePathSegment)\n}\n\nfunction parsePathSegment(segment: string): PathSegment {\n if (isIndexSegment(segment)) {\n return parseIndexSegment(segment)\n }\n\n if (isKeySegment(segment)) {\n return parseKeySegment(segment)\n }\n\n if (isIndexTuple(segment)) {\n return parseIndexTupleSegment(segment)\n }\n\n return segment\n}\n\nfunction parseIndexSegment(segment: string): PathSegment {\n return Number(segment.replace(/[^\\d]/g, ''))\n}\n\nfunction parseKeySegment(segment: string): KeyedSegment {\n const segments = segment.match(reKeySegment)\n return {_key: segments![1]}\n}\n\nfunction parseIndexTupleSegment(segment: string): IndexTuple {\n const [from, to] = segment.split(':').map((seg) => (seg === '' ? seg : Number(seg)))\n return [from, to]\n}\n","// nominal/opaque type hack\ntype Opaque<T, K> = T & {__opaqueId__: K}\n\n/** @internal */\nexport type DraftId = Opaque<string, 'draftId'>\n\n/** @internal */\nexport type PublishedId = Opaque<string, 'publishedId'>\n\n/** @internal */\nexport const DRAFTS_FOLDER = 'drafts'\n\n/** @internal */\nexport const VERSION_FOLDER = 'versions'\n\nconst PATH_SEPARATOR = '.'\nconst DRAFTS_PREFIX = `${DRAFTS_FOLDER}${PATH_SEPARATOR}`\nconst VERSION_PREFIX = `${VERSION_FOLDER}${PATH_SEPARATOR}`\n\n/** @internal */\nexport function isDraftId(id: string): id is DraftId {\n return id.startsWith(DRAFTS_PREFIX)\n}\n\n/** @internal */\nexport function isVersionId(id: string): boolean {\n return id.startsWith(VERSION_PREFIX)\n}\n\n/** @internal */\nexport function isPublishedId(id: string): id is PublishedId {\n return !isDraftId(id) && !isVersionId(id)\n}\n\n/**\n * A phantom brand like `DraftId` has no runtime representation, so it can never be produced\n * by narrowing a string - there's nothing to check. These two functions are the only places\n * allowed to assert a plain string into a branded id.\n */\nfunction asDraftId(value: string): DraftId {\n return value as DraftId\n}\n\nfunction asPublishedId(value: string): PublishedId {\n return value as PublishedId\n}\n\n/** @internal */\nexport function getDraftId(id: string): DraftId {\n if (isVersionId(id)) {\n const publishedId = getPublishedId(id)\n return asDraftId(DRAFTS_PREFIX + publishedId)\n }\n\n return isDraftId(id) ? id : ((DRAFTS_PREFIX + id) as DraftId)\n}\n\n/** @internal */\nexport function getVersionId(id: string, version: string): string {\n if (version === 'drafts' || version === 'published') {\n throw new Error('Version can not be \"published\" or \"drafts\"')\n }\n\n return `${VERSION_PREFIX}${version}${PATH_SEPARATOR}${getPublishedId(id)}`\n}\n\n/**\n * @internal\n * Given an id, returns the versionId if it exists.\n * e.g. `versions.summer-drop.foo` = `summer-drop`\n * e.g. `drafts.foo` = `undefined`\n * e.g. `foo` = `undefined`\n */\nexport function getVersionFromId(id: string): string | undefined {\n if (!isVersionId(id)) return undefined\n const [_versionPrefix, versionId, ..._publishedId] = id.split(PATH_SEPARATOR)\n\n return versionId\n}\n\n/** @internal */\nexport function getPublishedId(id: string): PublishedId {\n if (isVersionId(id)) {\n // make sure to only remove the versions prefix and the bundle name\n return asPublishedId(id.split(PATH_SEPARATOR).slice(2).join(PATH_SEPARATOR))\n }\n\n if (isDraftId(id)) {\n return asPublishedId(id.slice(DRAFTS_PREFIX.length))\n }\n\n if (isPublishedId(id)) {\n return id\n }\n\n // Unreachable: `isPublishedId` is defined as `!isDraftId(id) && !isVersionId(id)`, both of\n // which were already checked (and found false) above, so this can never execute.\n throw new Error(`Unable to resolve a published id from \"${id}\"`)\n}\n","import * as studioPath from './studioPath'\nimport type {\n ContentSourceMapParsedPath,\n ContentSourceMapParsedPathKeyedSegment,\n ContentSourceMapPaths,\n Path,\n} from './types'\n\nconst ESCAPE: Record<string, string> = {\n '\\f': '\\\\f',\n '\\n': '\\\\n',\n '\\r': '\\\\r',\n '\\t': '\\\\t',\n \"'\": \"\\\\'\",\n '\\\\': '\\\\\\\\',\n}\n\nconst UNESCAPE: Record<string, string> = {\n '\\\\f': '\\f',\n '\\\\n': '\\n',\n '\\\\r': '\\r',\n '\\\\t': '\\t',\n \"\\\\'\": \"'\",\n '\\\\\\\\': '\\\\',\n}\n\n/**\n * @internal\n */\nexport function jsonPath(path: ContentSourceMapParsedPath): ContentSourceMapPaths[number] {\n return `$${path\n .map((segment) => {\n if (typeof segment === 'string') {\n const escapedKey = segment.replace(/[\\f\\n\\r\\t'\\\\]/g, (match) => {\n return ESCAPE[match]\n })\n return `['${escapedKey}']`\n }\n\n if (typeof segment === 'number') {\n return `[${segment}]`\n }\n\n if (segment._key !== '') {\n const escapedKey = segment._key.replace(/['\\\\]/g, (match) => {\n return ESCAPE[match]\n })\n return `[?(@._key=='${escapedKey}')]`\n }\n\n return `[${segment._index}]`\n })\n .join('')}`\n}\n/**\n * @internal\n */\nexport function jsonPathArray(path: ContentSourceMapParsedPath): string[] {\n return path.map((segment) => {\n if (typeof segment === 'string') {\n const escapedKey = segment.replace(/[\\f\\n\\r\\t'\\\\]/g, (match) => {\n return ESCAPE[match]\n })\n return `['${escapedKey}']`\n }\n\n if (typeof segment === 'number') {\n return `[${segment}]`\n }\n\n if (segment._key !== '') {\n const escapedKey = segment._key.replace(/['\\\\]/g, (match) => {\n return ESCAPE[match]\n })\n return `[?(@._key=='${escapedKey}')]`\n }\n\n return `[${segment._index}]`\n })\n}\n\n/**\n * @internal\n */\nexport function parseJsonPath(path: ContentSourceMapPaths[number]): ContentSourceMapParsedPath {\n const parsed: ContentSourceMapParsedPath = []\n\n const parseRe = /\\['(.*?)'\\]|\\[(\\d+)\\]|\\[\\?\\(@\\._key=='(.*?)'\\)\\]/g\n let match: RegExpExecArray | null\n\n while ((match = parseRe.exec(path)) !== null) {\n if (match[1] !== undefined) {\n const key = match[1].replace(/\\\\(\\\\|f|n|r|t|')/g, (m) => {\n return UNESCAPE[m]\n })\n\n parsed.push(key)\n continue\n }\n\n if (match[2] !== undefined) {\n parsed.push(parseInt(match[2], 10))\n continue\n }\n\n if (match[3] !== undefined) {\n const _key = match[3].replace(/\\\\(\\\\')/g, (m) => {\n return UNESCAPE[m]\n })\n\n parsed.push({\n _key,\n _index: -1,\n })\n continue\n }\n }\n\n return parsed\n}\n\n/**\n * @internal\n */\nexport function jsonPathToStudioPath(path: ContentSourceMapParsedPath): Path {\n return path.map((segment) => {\n if (typeof segment === 'string') {\n return segment\n }\n\n if (typeof segment === 'number') {\n return segment\n }\n\n if (segment._key !== '') {\n return {_key: segment._key}\n }\n\n if (segment._index !== -1) {\n return segment._index\n }\n\n throw new Error(`invalid segment:${JSON.stringify(segment)}`)\n })\n}\n\n/**\n * @internal\n */\nexport function studioPathToJsonPath(path: Path | string): ContentSourceMapParsedPath {\n const parsedPath = typeof path === 'string' ? studioPath.fromString(path) : path\n\n return parsedPath.map((segment) => {\n if (typeof segment === 'string') {\n return segment\n }\n\n if (typeof segment === 'number') {\n return segment\n }\n\n if (Array.isArray(segment)) {\n throw new Error(`IndexTuple segments aren't supported:${JSON.stringify(segment)}`)\n }\n\n if (isContentSourceMapParsedPathKeyedSegment(segment)) {\n return segment\n }\n\n if (segment._key) {\n return {_key: segment._key, _index: -1}\n }\n\n throw new Error(`invalid segment:${JSON.stringify(segment)}`)\n })\n}\n\nfunction isContentSourceMapParsedPathKeyedSegment(\n segment: studioPath.PathSegment | ContentSourceMapParsedPath[number],\n): segment is ContentSourceMapParsedPathKeyedSegment {\n return typeof segment === 'object' && '_key' in segment && '_index' in segment\n}\n\n/**\n * @internal\n */\nexport function jsonPathToMappingPath(path: ContentSourceMapParsedPath): (string | number)[] {\n return path.map((segment) => {\n if (typeof segment === 'string') {\n return segment\n }\n\n if (typeof segment === 'number') {\n return segment\n }\n\n if (segment._index !== -1) {\n return segment._index\n }\n\n throw new Error(`invalid segment:${JSON.stringify(segment)}`)\n })\n}\n","import {jsonPath, jsonPathArray, jsonPathToMappingPath} from './jsonPath'\nimport type {ContentSourceMap, ContentSourceMapMapping, ContentSourceMapParsedPath} from './types'\n\n/**\n * @internal\n */\nexport function resolveMapping(\n resultPath: ContentSourceMapParsedPath,\n csm?: ContentSourceMap,\n):\n | {\n mapping: ContentSourceMapMapping\n matchedPath: string\n pathSuffix: string\n }\n | undefined {\n if (!csm?.mappings) {\n return undefined\n }\n const resultMappingPath = jsonPath(jsonPathToMappingPath(resultPath))\n\n if (csm.mappings[resultMappingPath] !== undefined) {\n return {\n mapping: csm.mappings[resultMappingPath],\n matchedPath: resultMappingPath,\n pathSuffix: '',\n }\n }\n\n const resultMappingPathArray = jsonPathArray(jsonPathToMappingPath(resultPath))\n for (let i = resultMappingPathArray.length - 1; i >= 0; i--) {\n const key = `$${resultMappingPathArray.slice(0, i).join('')}`\n const mappingFound = csm.mappings[key]\n if (mappingFound) {\n const pathSuffix = resultMappingPath.substring(key.length)\n return {mapping: mappingFound, matchedPath: key, pathSuffix}\n }\n }\n\n return undefined\n}\n","/** @internal */\nexport function isArray(value: unknown): value is Array<unknown> {\n return value !== null && Array.isArray(value)\n}\n","import {isRecord} from '../util/isRecord'\nimport {isArray} from './isArray'\nimport type {ContentSourceMapParsedPath, WalkMapFn} from './types'\n\n/**\n * generic way to walk a nested object or array and apply a mapping function to each value\n * @internal\n */\nexport function walkMap(\n value: unknown,\n mappingFn: WalkMapFn,\n path: ContentSourceMapParsedPath = [],\n): unknown {\n if (isArray(value)) {\n return value.map((v, idx) => {\n if (isRecord(v)) {\n const _key = v['_key']\n if (typeof _key === 'string') {\n return walkMap(v, mappingFn, path.concat({_key, _index: idx}))\n }\n }\n\n return walkMap(v, mappingFn, path.concat(idx))\n })\n }\n\n if (isRecord(value)) {\n // Handle Portable Text in a faster way\n if (value._type === 'block' || value._type === 'span') {\n const result = {...value}\n if (value._type === 'block') {\n result.children = walkMap(value.children, mappingFn, path.concat('children'))\n } else if (value._type === 'span') {\n result.text = walkMap(value.text, mappingFn, path.concat('text'))\n }\n return result\n }\n\n return Object.fromEntries(\n Object.entries(value).map(([k, v]) => [k, walkMap(v, mappingFn, path.concat(k))]),\n )\n }\n\n return mappingFn(value, path)\n}\n","import {getPublishedId, getVersionFromId, isPublishedId, isVersionId} from './draftUtils'\nimport {jsonPathToStudioPath} from './jsonPath'\nimport * as studioPath from './studioPath'\nimport type {CreateEditUrlOptions, EditIntentUrl, StudioBaseUrl} from './types'\n\n/** @internal */\nexport function createEditUrl(options: CreateEditUrlOptions): `${StudioBaseUrl}${EditIntentUrl}` {\n const {\n baseUrl,\n workspace: _workspace = 'default',\n tool: _tool = 'default',\n id: _id,\n type,\n path,\n projectId,\n dataset,\n } = options\n\n if (!baseUrl) {\n throw new Error('baseUrl is required')\n }\n if (!path) {\n throw new Error('path is required')\n }\n if (!_id) {\n throw new Error('id is required')\n }\n if (baseUrl !== '/' && baseUrl.endsWith('/')) {\n throw new Error('baseUrl must not end with a slash')\n }\n\n const workspace = _workspace === 'default' ? undefined : _workspace\n const tool = _tool === 'default' ? undefined : _tool\n const id = getPublishedId(_id)\n const stringifiedPath = Array.isArray(path)\n ? studioPath.toString(jsonPathToStudioPath(path))\n : path\n\n // oxlint-disable-next-line no-warning-comments\n // @TODO Using searchParams as a temporary workaround until `@sanity/overlays` can decode state from the path reliably\n const searchParams = new URLSearchParams({\n baseUrl,\n id,\n type,\n path: stringifiedPath,\n })\n if (workspace) {\n searchParams.set('workspace', workspace)\n }\n if (tool) {\n searchParams.set('tool', tool)\n }\n if (projectId) {\n searchParams.set('projectId', projectId)\n }\n if (dataset) {\n searchParams.set('dataset', dataset)\n }\n if (isPublishedId(_id)) {\n searchParams.set('perspective', 'published')\n } else if (isVersionId(_id)) {\n const versionId = getVersionFromId(_id)!\n searchParams.set('perspective', versionId)\n }\n\n const segments = [baseUrl === '/' ? '' : baseUrl]\n if (workspace) {\n segments.push(workspace)\n }\n const routerParams = [\n 'mode=presentation',\n `id=${id}`,\n `type=${type}`,\n `path=${encodeURIComponent(stringifiedPath)}`,\n ]\n if (tool) {\n routerParams.push(`tool=${tool}`)\n }\n segments.push('intent', 'edit', `${routerParams.join(';')}?${searchParams}`)\n return segments.join('/') as unknown as `${StudioBaseUrl}${EditIntentUrl}`\n}\n","import {parseJsonPath} from './jsonPath'\nimport {resolveMapping} from './resolveMapping'\nimport type {\n CreateEditUrlOptions,\n ResolveEditInfoOptions,\n StudioBaseRoute,\n StudioBaseUrl,\n StudioUrl,\n} from './types'\n\n/** @internal */\nexport function resolveEditInfo(options: ResolveEditInfoOptions): CreateEditUrlOptions | undefined {\n const {resultSourceMap: csm, resultPath} = options\n const {mapping, pathSuffix} = resolveMapping(resultPath, csm) || {}\n\n if (!mapping) {\n // console.warn('no mapping for path', { path: resultPath, sourceMap: csm })\n return undefined\n }\n\n if (mapping.source.type === 'literal') {\n return undefined\n }\n\n if (mapping.source.type === 'unknown') {\n return undefined\n }\n\n const sourceDoc = csm.documents[mapping.source.document]\n const sourcePath = csm.paths[mapping.source.path]\n\n if (sourceDoc && sourcePath) {\n const {baseUrl, workspace, tool} = resolveStudioBaseRoute(\n typeof options.studioUrl === 'function' ? options.studioUrl(sourceDoc) : options.studioUrl,\n )\n if (!baseUrl) return undefined\n const {_id, _type, _projectId, _dataset} = sourceDoc\n return {\n baseUrl,\n workspace,\n tool,\n id: _id,\n type: _type,\n path: parseJsonPath(sourcePath + pathSuffix),\n projectId: _projectId,\n dataset: _dataset,\n } satisfies CreateEditUrlOptions\n }\n\n return undefined\n}\n\n/** @internal */\nexport function resolveStudioBaseRoute(studioUrl: StudioUrl): StudioBaseRoute {\n let baseUrl: StudioBaseUrl = typeof studioUrl === 'string' ? studioUrl : studioUrl.baseUrl\n if (baseUrl !== '/') {\n baseUrl = baseUrl.replace(/\\/$/, '')\n }\n if (typeof studioUrl === 'string') {\n return {baseUrl}\n }\n return {...studioUrl, baseUrl}\n}\n"],"mappings":";;;;;;;;;;;AAYA,MAAM,aACJ,oGAEW,eAAe,4BACtB,eAAe;;AAGrB,SAAgB,eAAe,SAAyC;CACtE,OAAO,OAAO,WAAY,YAAa,OAAO,WAAY,YAAY,YAAY,KAAK,OAAO;AAChG;;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KD,QAAQ,OAAO,SAAS,aAIxB,QAAQ,OAAO,SAAS,WAC1B;CAGF,IAAM,YAAY,IAAI,UAAU,QAAQ,OAAO,WACzC,aAAa,IAAI,MAAM,QAAQ,OAAO;CAE5C,IAAI,aAAa,YAAY;EAC3B,IAAM,EAAC,SAAS,WAAW,SAAQ,uBACjC,OAAO,QAAQ,aAAc,aAAa,QAAQ,UAAU,SAAS,IAAI,QAAQ,SACnF;EACA,IAAI,CAAC,SAAS;EACd,IAAM,EAAC,KAAK,OAAO,YAAY,aAAY;EAC3C,OAAO;GACL;GACA;GACA;GACA,IAAI;GACJ,MAAM;GACN,MAAM,cAAc,aAAa,UAAU;GAC3C,WAAW;GACX,SAAS;EACX;CACF;AAGF;;AAGA,SAAgB,uBAAuB,WAAuC;CAC5E,IAAI,UAAyB,OAAO,aAAc,WAAW,YAAY,UAAU;CAOnF,OANI,YAAY,QACd,UAAU,QAAQ,QAAQ,OAAO,EAAE,IAEjC,OAAO,aAAc,WAChB,EAAC,QAAO,IAEV;EAAC,GAAG;EAAW;CAAO;AAC/B"}
|
package/dist/stega.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { n as vercelStegaCleanAll, t as stegaClean } from "./stegaClean-C18wLWau.js";
|
|
2
|
-
import { r as encodeIntoResult, t as stegaEncodeSourceMap } from "./stegaEncodeSourceMap-
|
|
2
|
+
import { r as encodeIntoResult, t as stegaEncodeSourceMap } from "./stegaEncodeSourceMap-YR3NQ3iz.js";
|
|
3
3
|
import { ObservableSanityClient, SanityClient, createClient as createClient$1, requester as requester$1 } from "@sanity/client";
|
|
4
4
|
export * from "@sanity/client";
|
|
5
5
|
/**
|
|
@@ -13,6 +13,9 @@ function isVersionId(id) {
|
|
|
13
13
|
function isPublishedId(id) {
|
|
14
14
|
return !isDraftId(id) && !isVersionId(id);
|
|
15
15
|
}
|
|
16
|
+
function asPublishedId(value) {
|
|
17
|
+
return value;
|
|
18
|
+
}
|
|
16
19
|
/**
|
|
17
20
|
* @internal
|
|
18
21
|
* Given an id, returns the versionId if it exists.
|
|
@@ -27,7 +30,10 @@ function getVersionFromId(id) {
|
|
|
27
30
|
}
|
|
28
31
|
/** @internal */
|
|
29
32
|
function getPublishedId(id) {
|
|
30
|
-
|
|
33
|
+
if (isVersionId(id)) return asPublishedId(id.split(".").slice(2).join("."));
|
|
34
|
+
if (isDraftId(id)) return asPublishedId(id.slice(7));
|
|
35
|
+
if (isPublishedId(id)) return id;
|
|
36
|
+
throw Error(`Unable to resolve a published id from "${id}"`);
|
|
31
37
|
}
|
|
32
38
|
/** @internal */
|
|
33
39
|
const reKeySegment = /_key\s*==\s*['"](.*)['"]/;
|
|
@@ -364,4 +370,4 @@ function prettyPathForLogging(path) {
|
|
|
364
370
|
}
|
|
365
371
|
export { encodeIntoResult, stegaEncodeSourceMap };
|
|
366
372
|
|
|
367
|
-
//# sourceMappingURL=stegaEncodeSourceMap-
|
|
373
|
+
//# sourceMappingURL=stegaEncodeSourceMap-DbM2fTN4.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"stegaEncodeSourceMap-DbM2fTN4.js","names":["studioPath.toString","vercelStegaCombine","studioPathToString"],"sources":["../src/csm/draftUtils.ts","../src/csm/studioPath.ts","../src/csm/jsonPath.ts","../src/csm/createEditUrl.ts","../src/csm/resolveMapping.ts","../src/csm/resolveEditInfo.ts","../src/csm/isArray.ts","../src/csm/walkMap.ts","../src/stega/encodeIntoResult.ts","../src/stega/filterDefault.ts","../src/stega/stegaEncodeSourceMap.ts"],"sourcesContent":["// nominal/opaque type hack\ntype Opaque<T, K> = T & {__opaqueId__: K}\n\n/** @internal */\nexport type DraftId = Opaque<string, 'draftId'>\n\n/** @internal */\nexport type PublishedId = Opaque<string, 'publishedId'>\n\n/** @internal */\nexport const DRAFTS_FOLDER = 'drafts'\n\n/** @internal */\nexport const VERSION_FOLDER = 'versions'\n\nconst PATH_SEPARATOR = '.'\nconst DRAFTS_PREFIX = `${DRAFTS_FOLDER}${PATH_SEPARATOR}`\nconst VERSION_PREFIX = `${VERSION_FOLDER}${PATH_SEPARATOR}`\n\n/** @internal */\nexport function isDraftId(id: string): id is DraftId {\n return id.startsWith(DRAFTS_PREFIX)\n}\n\n/** @internal */\nexport function isVersionId(id: string): boolean {\n return id.startsWith(VERSION_PREFIX)\n}\n\n/** @internal */\nexport function isPublishedId(id: string): id is PublishedId {\n return !isDraftId(id) && !isVersionId(id)\n}\n\n/**\n * A phantom brand like `DraftId` has no runtime representation, so it can never be produced\n * by narrowing a string - there's nothing to check. These two functions are the only places\n * allowed to assert a plain string into a branded id.\n */\nfunction asDraftId(value: string): DraftId {\n return value as DraftId\n}\n\nfunction asPublishedId(value: string): PublishedId {\n return value as PublishedId\n}\n\n/** @internal */\nexport function getDraftId(id: string): DraftId {\n if (isVersionId(id)) {\n const publishedId = getPublishedId(id)\n return asDraftId(DRAFTS_PREFIX + publishedId)\n }\n\n return isDraftId(id) ? id : ((DRAFTS_PREFIX + id) as DraftId)\n}\n\n/** @internal */\nexport function getVersionId(id: string, version: string): string {\n if (version === 'drafts' || version === 'published') {\n throw new Error('Version can not be \"published\" or \"drafts\"')\n }\n\n return `${VERSION_PREFIX}${version}${PATH_SEPARATOR}${getPublishedId(id)}`\n}\n\n/**\n * @internal\n * Given an id, returns the versionId if it exists.\n * e.g. `versions.summer-drop.foo` = `summer-drop`\n * e.g. `drafts.foo` = `undefined`\n * e.g. `foo` = `undefined`\n */\nexport function getVersionFromId(id: string): string | undefined {\n if (!isVersionId(id)) return undefined\n const [_versionPrefix, versionId, ..._publishedId] = id.split(PATH_SEPARATOR)\n\n return versionId\n}\n\n/** @internal */\nexport function getPublishedId(id: string): PublishedId {\n if (isVersionId(id)) {\n // make sure to only remove the versions prefix and the bundle name\n return asPublishedId(id.split(PATH_SEPARATOR).slice(2).join(PATH_SEPARATOR))\n }\n\n if (isDraftId(id)) {\n return asPublishedId(id.slice(DRAFTS_PREFIX.length))\n }\n\n if (isPublishedId(id)) {\n return id\n }\n\n // Unreachable: `isPublishedId` is defined as `!isDraftId(id) && !isVersionId(id)`, both of\n // which were already checked (and found false) above, so this can never execute.\n throw new Error(`Unable to resolve a published id from \"${id}\"`)\n}\n","/** @alpha */\nexport type KeyedSegment = {_key: string}\n\n/** @alpha */\nexport type IndexTuple = [number | '', number | '']\n\n/** @alpha */\nexport type PathSegment = string | number | KeyedSegment | IndexTuple\n\n/** @alpha */\nexport type Path = PathSegment[]\n\nconst rePropName =\n /[^.[\\]]+|\\[(?:(-?\\d+(?:\\.\\d+)?)|([\"'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2)\\]|(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))/g\n/** @internal */\nexport const reKeySegment = /_key\\s*==\\s*['\"](.*)['\"]/\nconst reIndexTuple = /^\\d*:\\d*$/\n\n/** @internal */\nexport function isIndexSegment(segment: PathSegment): segment is number {\n return typeof segment === 'number' || (typeof segment === 'string' && /^\\[\\d+\\]$/.test(segment))\n}\n\n/** @internal */\nexport function isKeySegment(segment: PathSegment): segment is KeyedSegment {\n if (typeof segment === 'string') {\n return reKeySegment.test(segment.trim())\n }\n\n return typeof segment === 'object' && '_key' in segment\n}\n\n/** @internal */\nexport function isIndexTuple(segment: PathSegment): segment is IndexTuple {\n if (typeof segment === 'string' && reIndexTuple.test(segment)) {\n return true\n }\n\n if (!Array.isArray(segment) || segment.length !== 2) {\n return false\n }\n\n const [from, to] = segment\n return (typeof from === 'number' || from === '') && (typeof to === 'number' || to === '')\n}\n\n/** @internal */\n// oxlint-disable-next-line typescript/no-unnecessary-type-parameters -- caller-supplied return type; removing it breaks `get<Result>(...)` call sites\nexport function get<Result = unknown, Fallback = unknown>(\n obj: unknown,\n path: Path | string,\n defaultVal?: Fallback,\n): Result | typeof defaultVal {\n const select = typeof path === 'string' ? fromString(path) : path\n if (!Array.isArray(select)) {\n throw new Error('Path must be an array or a string')\n }\n\n let acc: unknown = obj\n for (let i = 0; i < select.length; i++) {\n const segment = select[i]\n if (isIndexSegment(segment)) {\n if (!Array.isArray(acc)) {\n return defaultVal\n }\n\n acc = acc[segment]\n }\n\n if (isKeySegment(segment)) {\n if (!Array.isArray(acc)) {\n return defaultVal\n }\n\n acc = acc.find((item) => item._key === segment._key)\n }\n\n if (typeof segment === 'string') {\n acc =\n typeof acc === 'object' && acc !== null\n ? ((acc as Record<string, unknown>)[segment] as Result)\n : undefined\n }\n\n if (typeof acc === 'undefined') {\n return defaultVal\n }\n }\n\n return acc as Result\n}\n\n/** @alpha */\nexport function toString(path: Path): string {\n if (!Array.isArray(path)) {\n throw new Error('Path is not an array')\n }\n\n return path.reduce<string>((target, segment, i) => {\n const segmentType = typeof segment\n if (segmentType === 'number') {\n return `${target}[${segment}]`\n }\n\n if (segmentType === 'string') {\n const separator = i === 0 ? '' : '.'\n return `${target}${separator}${segment}`\n }\n\n if (isKeySegment(segment) && segment._key) {\n return `${target}[_key==\"${segment._key}\"]`\n }\n\n if (Array.isArray(segment)) {\n const [from, to] = segment\n return `${target}[${from}:${to}]`\n }\n\n throw new Error(`Unsupported path segment \\`${JSON.stringify(segment)}\\``)\n }, '')\n}\n\n/** @alpha */\nexport function fromString(path: string): Path {\n if (typeof path !== 'string') {\n throw new Error('Path is not a string')\n }\n\n const segments = path.match(rePropName)\n if (!segments) {\n throw new Error('Invalid path string')\n }\n\n return segments.map(parsePathSegment)\n}\n\nfunction parsePathSegment(segment: string): PathSegment {\n if (isIndexSegment(segment)) {\n return parseIndexSegment(segment)\n }\n\n if (isKeySegment(segment)) {\n return parseKeySegment(segment)\n }\n\n if (isIndexTuple(segment)) {\n return parseIndexTupleSegment(segment)\n }\n\n return segment\n}\n\nfunction parseIndexSegment(segment: string): PathSegment {\n return Number(segment.replace(/[^\\d]/g, ''))\n}\n\nfunction parseKeySegment(segment: string): KeyedSegment {\n const segments = segment.match(reKeySegment)\n return {_key: segments![1]}\n}\n\nfunction parseIndexTupleSegment(segment: string): IndexTuple {\n const [from, to] = segment.split(':').map((seg) => (seg === '' ? seg : Number(seg)))\n return [from, to]\n}\n","import * as studioPath from './studioPath'\nimport type {\n ContentSourceMapParsedPath,\n ContentSourceMapParsedPathKeyedSegment,\n ContentSourceMapPaths,\n Path,\n} from './types'\n\nconst ESCAPE: Record<string, string> = {\n '\\f': '\\\\f',\n '\\n': '\\\\n',\n '\\r': '\\\\r',\n '\\t': '\\\\t',\n \"'\": \"\\\\'\",\n '\\\\': '\\\\\\\\',\n}\n\nconst UNESCAPE: Record<string, string> = {\n '\\\\f': '\\f',\n '\\\\n': '\\n',\n '\\\\r': '\\r',\n '\\\\t': '\\t',\n \"\\\\'\": \"'\",\n '\\\\\\\\': '\\\\',\n}\n\n/**\n * @internal\n */\nexport function jsonPath(path: ContentSourceMapParsedPath): ContentSourceMapPaths[number] {\n return `$${path\n .map((segment) => {\n if (typeof segment === 'string') {\n const escapedKey = segment.replace(/[\\f\\n\\r\\t'\\\\]/g, (match) => {\n return ESCAPE[match]\n })\n return `['${escapedKey}']`\n }\n\n if (typeof segment === 'number') {\n return `[${segment}]`\n }\n\n if (segment._key !== '') {\n const escapedKey = segment._key.replace(/['\\\\]/g, (match) => {\n return ESCAPE[match]\n })\n return `[?(@._key=='${escapedKey}')]`\n }\n\n return `[${segment._index}]`\n })\n .join('')}`\n}\n/**\n * @internal\n */\nexport function jsonPathArray(path: ContentSourceMapParsedPath): string[] {\n return path.map((segment) => {\n if (typeof segment === 'string') {\n const escapedKey = segment.replace(/[\\f\\n\\r\\t'\\\\]/g, (match) => {\n return ESCAPE[match]\n })\n return `['${escapedKey}']`\n }\n\n if (typeof segment === 'number') {\n return `[${segment}]`\n }\n\n if (segment._key !== '') {\n const escapedKey = segment._key.replace(/['\\\\]/g, (match) => {\n return ESCAPE[match]\n })\n return `[?(@._key=='${escapedKey}')]`\n }\n\n return `[${segment._index}]`\n })\n}\n\n/**\n * @internal\n */\nexport function parseJsonPath(path: ContentSourceMapPaths[number]): ContentSourceMapParsedPath {\n const parsed: ContentSourceMapParsedPath = []\n\n const parseRe = /\\['(.*?)'\\]|\\[(\\d+)\\]|\\[\\?\\(@\\._key=='(.*?)'\\)\\]/g\n let match: RegExpExecArray | null\n\n while ((match = parseRe.exec(path)) !== null) {\n if (match[1] !== undefined) {\n const key = match[1].replace(/\\\\(\\\\|f|n|r|t|')/g, (m) => {\n return UNESCAPE[m]\n })\n\n parsed.push(key)\n continue\n }\n\n if (match[2] !== undefined) {\n parsed.push(parseInt(match[2], 10))\n continue\n }\n\n if (match[3] !== undefined) {\n const _key = match[3].replace(/\\\\(\\\\')/g, (m) => {\n return UNESCAPE[m]\n })\n\n parsed.push({\n _key,\n _index: -1,\n })\n continue\n }\n }\n\n return parsed\n}\n\n/**\n * @internal\n */\nexport function jsonPathToStudioPath(path: ContentSourceMapParsedPath): Path {\n return path.map((segment) => {\n if (typeof segment === 'string') {\n return segment\n }\n\n if (typeof segment === 'number') {\n return segment\n }\n\n if (segment._key !== '') {\n return {_key: segment._key}\n }\n\n if (segment._index !== -1) {\n return segment._index\n }\n\n throw new Error(`invalid segment:${JSON.stringify(segment)}`)\n })\n}\n\n/**\n * @internal\n */\nexport function studioPathToJsonPath(path: Path | string): ContentSourceMapParsedPath {\n const parsedPath = typeof path === 'string' ? studioPath.fromString(path) : path\n\n return parsedPath.map((segment) => {\n if (typeof segment === 'string') {\n return segment\n }\n\n if (typeof segment === 'number') {\n return segment\n }\n\n if (Array.isArray(segment)) {\n throw new Error(`IndexTuple segments aren't supported:${JSON.stringify(segment)}`)\n }\n\n if (isContentSourceMapParsedPathKeyedSegment(segment)) {\n return segment\n }\n\n if (segment._key) {\n return {_key: segment._key, _index: -1}\n }\n\n throw new Error(`invalid segment:${JSON.stringify(segment)}`)\n })\n}\n\nfunction isContentSourceMapParsedPathKeyedSegment(\n segment: studioPath.PathSegment | ContentSourceMapParsedPath[number],\n): segment is ContentSourceMapParsedPathKeyedSegment {\n return typeof segment === 'object' && '_key' in segment && '_index' in segment\n}\n\n/**\n * @internal\n */\nexport function jsonPathToMappingPath(path: ContentSourceMapParsedPath): (string | number)[] {\n return path.map((segment) => {\n if (typeof segment === 'string') {\n return segment\n }\n\n if (typeof segment === 'number') {\n return segment\n }\n\n if (segment._index !== -1) {\n return segment._index\n }\n\n throw new Error(`invalid segment:${JSON.stringify(segment)}`)\n })\n}\n","import {getPublishedId, getVersionFromId, isPublishedId, isVersionId} from './draftUtils'\nimport {jsonPathToStudioPath} from './jsonPath'\nimport * as studioPath from './studioPath'\nimport type {CreateEditUrlOptions, EditIntentUrl, StudioBaseUrl} from './types'\n\n/** @internal */\nexport function createEditUrl(options: CreateEditUrlOptions): `${StudioBaseUrl}${EditIntentUrl}` {\n const {\n baseUrl,\n workspace: _workspace = 'default',\n tool: _tool = 'default',\n id: _id,\n type,\n path,\n projectId,\n dataset,\n } = options\n\n if (!baseUrl) {\n throw new Error('baseUrl is required')\n }\n if (!path) {\n throw new Error('path is required')\n }\n if (!_id) {\n throw new Error('id is required')\n }\n if (baseUrl !== '/' && baseUrl.endsWith('/')) {\n throw new Error('baseUrl must not end with a slash')\n }\n\n const workspace = _workspace === 'default' ? undefined : _workspace\n const tool = _tool === 'default' ? undefined : _tool\n const id = getPublishedId(_id)\n const stringifiedPath = Array.isArray(path)\n ? studioPath.toString(jsonPathToStudioPath(path))\n : path\n\n // oxlint-disable-next-line no-warning-comments\n // @TODO Using searchParams as a temporary workaround until `@sanity/overlays` can decode state from the path reliably\n const searchParams = new URLSearchParams({\n baseUrl,\n id,\n type,\n path: stringifiedPath,\n })\n if (workspace) {\n searchParams.set('workspace', workspace)\n }\n if (tool) {\n searchParams.set('tool', tool)\n }\n if (projectId) {\n searchParams.set('projectId', projectId)\n }\n if (dataset) {\n searchParams.set('dataset', dataset)\n }\n if (isPublishedId(_id)) {\n searchParams.set('perspective', 'published')\n } else if (isVersionId(_id)) {\n const versionId = getVersionFromId(_id)!\n searchParams.set('perspective', versionId)\n }\n\n const segments = [baseUrl === '/' ? '' : baseUrl]\n if (workspace) {\n segments.push(workspace)\n }\n const routerParams = [\n 'mode=presentation',\n `id=${id}`,\n `type=${type}`,\n `path=${encodeURIComponent(stringifiedPath)}`,\n ]\n if (tool) {\n routerParams.push(`tool=${tool}`)\n }\n segments.push('intent', 'edit', `${routerParams.join(';')}?${searchParams}`)\n return segments.join('/') as unknown as `${StudioBaseUrl}${EditIntentUrl}`\n}\n","import {jsonPath, jsonPathArray, jsonPathToMappingPath} from './jsonPath'\nimport type {ContentSourceMap, ContentSourceMapMapping, ContentSourceMapParsedPath} from './types'\n\n/**\n * @internal\n */\nexport function resolveMapping(\n resultPath: ContentSourceMapParsedPath,\n csm?: ContentSourceMap,\n):\n | {\n mapping: ContentSourceMapMapping\n matchedPath: string\n pathSuffix: string\n }\n | undefined {\n if (!csm?.mappings) {\n return undefined\n }\n const resultMappingPath = jsonPath(jsonPathToMappingPath(resultPath))\n\n if (csm.mappings[resultMappingPath] !== undefined) {\n return {\n mapping: csm.mappings[resultMappingPath],\n matchedPath: resultMappingPath,\n pathSuffix: '',\n }\n }\n\n const resultMappingPathArray = jsonPathArray(jsonPathToMappingPath(resultPath))\n for (let i = resultMappingPathArray.length - 1; i >= 0; i--) {\n const key = `$${resultMappingPathArray.slice(0, i).join('')}`\n const mappingFound = csm.mappings[key]\n if (mappingFound) {\n const pathSuffix = resultMappingPath.substring(key.length)\n return {mapping: mappingFound, matchedPath: key, pathSuffix}\n }\n }\n\n return undefined\n}\n","import {parseJsonPath} from './jsonPath'\nimport {resolveMapping} from './resolveMapping'\nimport type {\n CreateEditUrlOptions,\n ResolveEditInfoOptions,\n StudioBaseRoute,\n StudioBaseUrl,\n StudioUrl,\n} from './types'\n\n/** @internal */\nexport function resolveEditInfo(options: ResolveEditInfoOptions): CreateEditUrlOptions | undefined {\n const {resultSourceMap: csm, resultPath} = options\n const {mapping, pathSuffix} = resolveMapping(resultPath, csm) || {}\n\n if (!mapping) {\n // console.warn('no mapping for path', { path: resultPath, sourceMap: csm })\n return undefined\n }\n\n if (mapping.source.type === 'literal') {\n return undefined\n }\n\n if (mapping.source.type === 'unknown') {\n return undefined\n }\n\n const sourceDoc = csm.documents[mapping.source.document]\n const sourcePath = csm.paths[mapping.source.path]\n\n if (sourceDoc && sourcePath) {\n const {baseUrl, workspace, tool} = resolveStudioBaseRoute(\n typeof options.studioUrl === 'function' ? options.studioUrl(sourceDoc) : options.studioUrl,\n )\n if (!baseUrl) return undefined\n const {_id, _type, _projectId, _dataset} = sourceDoc\n return {\n baseUrl,\n workspace,\n tool,\n id: _id,\n type: _type,\n path: parseJsonPath(sourcePath + pathSuffix),\n projectId: _projectId,\n dataset: _dataset,\n } satisfies CreateEditUrlOptions\n }\n\n return undefined\n}\n\n/** @internal */\nexport function resolveStudioBaseRoute(studioUrl: StudioUrl): StudioBaseRoute {\n let baseUrl: StudioBaseUrl = typeof studioUrl === 'string' ? studioUrl : studioUrl.baseUrl\n if (baseUrl !== '/') {\n baseUrl = baseUrl.replace(/\\/$/, '')\n }\n if (typeof studioUrl === 'string') {\n return {baseUrl}\n }\n return {...studioUrl, baseUrl}\n}\n","/** @internal */\nexport function isArray(value: unknown): value is Array<unknown> {\n return value !== null && Array.isArray(value)\n}\n","import {isRecord} from '../util/isRecord'\nimport {isArray} from './isArray'\nimport type {ContentSourceMapParsedPath, WalkMapFn} from './types'\n\n/**\n * generic way to walk a nested object or array and apply a mapping function to each value\n * @internal\n */\nexport function walkMap(\n value: unknown,\n mappingFn: WalkMapFn,\n path: ContentSourceMapParsedPath = [],\n): unknown {\n if (isArray(value)) {\n return value.map((v, idx) => {\n if (isRecord(v)) {\n const _key = v['_key']\n if (typeof _key === 'string') {\n return walkMap(v, mappingFn, path.concat({_key, _index: idx}))\n }\n }\n\n return walkMap(v, mappingFn, path.concat(idx))\n })\n }\n\n if (isRecord(value)) {\n // Handle Portable Text in a faster way\n if (value._type === 'block' || value._type === 'span') {\n const result = {...value}\n if (value._type === 'block') {\n result.children = walkMap(value.children, mappingFn, path.concat('children'))\n } else if (value._type === 'span') {\n result.text = walkMap(value.text, mappingFn, path.concat('text'))\n }\n return result\n }\n\n return Object.fromEntries(\n Object.entries(value).map(([k, v]) => [k, walkMap(v, mappingFn, path.concat(k))]),\n )\n }\n\n return mappingFn(value, path)\n}\n","import type {ContentSourceMap} from '@sanity/client/csm'\n\nimport {parseJsonPath} from '../csm/jsonPath'\nimport {resolveMapping} from '../csm/resolveMapping'\nimport {walkMap} from '../csm/walkMap'\nimport type {Encoder} from './types'\n\n/**\n * @internal\n */\nexport function encodeIntoResult<Result>(\n result: Result,\n csm: ContentSourceMap,\n encoder: Encoder,\n): Result {\n return walkMap(result, (value, path) => {\n // Only map strings, we could extend this in the future to support other types like integers...\n if (typeof value !== 'string') {\n return value\n }\n\n const resolveMappingResult = resolveMapping(path, csm)\n if (!resolveMappingResult) {\n return value\n }\n\n const {mapping, matchedPath} = resolveMappingResult\n if (mapping.type !== 'value') {\n return value\n }\n\n if (mapping.source.type !== 'documentValue') {\n return value\n }\n\n const sourceDocument = csm.documents[mapping.source.document!]\n const sourcePath = csm.paths[mapping.source.path]\n\n const matchPathSegments = parseJsonPath(matchedPath)\n const sourcePathSegments = parseJsonPath(sourcePath)\n const fullSourceSegments = sourcePathSegments.concat(path.slice(matchPathSegments.length))\n\n return encoder({\n sourcePath: fullSourceSegments,\n sourceDocument,\n resultPath: path,\n value,\n })\n }) as Result\n}\n","import type {ContentSourceMapParsedPath, FilterDefault} from './types'\n\nexport const filterDefault: FilterDefault = ({sourcePath, resultPath, value}) => {\n // Skips encoding on URL or Date strings, similar to the `skip: 'auto'` parameter in vercelStegaCombine()\n if (isValidDate(value) || isValidURL(value)) {\n return false\n }\n\n const endPath = sourcePath.at(-1)\n // Never encode slugs\n if (sourcePath.at(-2) === 'slug' && endPath === 'current') {\n return false\n }\n\n // Skip underscored keys, and strings that end with `Id`, needs better heuristics but it works for now\n if (typeof endPath === 'string' && (endPath.startsWith('_') || endPath.endsWith('Id'))) {\n return false\n }\n\n // Don't encode into anything that is suggested it'll render for SEO in meta tags\n if (\n sourcePath.some(\n (path) => path === 'meta' || path === 'metadata' || path === 'openGraph' || path === 'seo',\n )\n ) {\n return false\n }\n\n // If the sourcePath or resultPath contains something that sounds like a type, like iconType, we skip encoding, as it's most\n // of the time used for logic that breaks if it contains stega characters\n if (hasTypeLike(sourcePath) || hasTypeLike(resultPath)) {\n return false\n }\n\n // Finally, we ignore a bunch of paths that are typically used for page building\n if (typeof endPath === 'string' && denylist.has(endPath)) {\n return false\n }\n\n return true\n}\n\nconst denylist = new Set([\n 'color',\n 'colour',\n 'currency',\n 'email',\n 'format',\n 'gid',\n 'hex',\n 'href',\n 'hsl',\n 'hsla',\n 'icon',\n 'id',\n 'index',\n 'key',\n 'language',\n 'layout',\n 'link',\n 'linkAction',\n 'locale',\n 'lqip',\n 'page',\n 'path',\n 'ref',\n 'rgb',\n 'rgba',\n 'route',\n 'secret',\n 'slug',\n 'status',\n 'tag',\n 'template',\n 'theme',\n 'type',\n 'textTheme',\n 'unit',\n 'url',\n 'username',\n 'variant',\n 'website',\n])\n\nfunction isValidDate(dateString: string) {\n return /^\\d{4}-\\d{2}-\\d{2}/.test(dateString) ? Boolean(Date.parse(dateString)) : false\n}\n\nconst allowedProtocols = new Set([\n 'app:',\n 'data:',\n 'discord:',\n 'file:',\n 'ftp:',\n 'ftps:',\n 'geo:',\n 'http:',\n 'https:',\n 'imap:',\n 'javascript:',\n 'magnet:',\n 'mailto:',\n 'maps:',\n 'ms-excel:',\n 'ms-powerpoint:',\n 'ms-word:',\n 'slack:',\n 'sms:',\n 'spotify:',\n 'steam:',\n 'teams:',\n 'tel:',\n 'vscode:',\n 'zoom:',\n])\n\nfunction isValidURL(url: string) {\n try {\n const {protocol} = new URL(url, url.startsWith('/') ? 'https://acme.com' : undefined)\n return allowedProtocols.has(protocol) || protocol.startsWith('web+')\n } catch {\n return false\n }\n}\n\nfunction hasTypeLike(path: ContentSourceMapParsedPath): boolean {\n return path.some((segment) => typeof segment === 'string' && segment.match(/type/i) !== null)\n}\n","import {vercelStegaCombine} from '@vercel/stega'\n\nimport {createEditUrl} from '../csm/createEditUrl'\nimport {jsonPathToStudioPath} from '../csm/jsonPath'\nimport {resolveStudioBaseRoute} from '../csm/resolveEditInfo'\nimport {reKeySegment, toString as studioPathToString} from '../csm/studioPath'\nimport {encodeIntoResult} from './encodeIntoResult'\n// Re-export so `encodeIntoResult` is a genuine export of this module - which\n// forms its own output chunk via the dynamic import in `dataMethods`. Without\n// this, rolldown absorbs `encodeIntoResult` into the chunk but omits it from\n// the chunk's exports, breaking `@sanity/client/stega`'s re-export of it.\nexport {encodeIntoResult} from './encodeIntoResult'\nimport {filterDefault} from './filterDefault'\nimport {\n type ContentSourceMap,\n type ContentSourceMapParsedPath,\n type InitializedStegaConfig,\n} from './types'\n\nconst TRUNCATE_LENGTH = 20\n\n/**\n * Uses `@vercel/stega` to embed edit info JSON into strings in your query result.\n * The JSON payloads are added using invisible characters so they don't show up visually.\n * The edit info is generated from the Content Source Map (CSM) that is returned from Sanity for the query.\n * @public\n */\nexport function stegaEncodeSourceMap<Result = unknown>(\n result: Result,\n resultSourceMap: ContentSourceMap | undefined,\n config: InitializedStegaConfig,\n): Result {\n const {filter, logger, enabled} = config\n if (!enabled) {\n const msg = \"config.enabled must be true, don't call this function otherwise\"\n logger?.error?.(`[@sanity/client]: ${msg}`, {result, resultSourceMap, config})\n throw new TypeError(msg)\n }\n\n if (!resultSourceMap) {\n logger?.error?.('[@sanity/client]: Missing Content Source Map from response body', {\n result,\n resultSourceMap,\n config,\n })\n return result\n }\n\n if (!config.studioUrl) {\n const msg = 'config.studioUrl must be defined'\n logger?.error?.(`[@sanity/client]: ${msg}`, {result, resultSourceMap, config})\n throw new TypeError(msg)\n }\n\n const report: Record<'encoded' | 'skipped', {path: string; length: number; value: string}[]> = {\n encoded: [],\n skipped: [],\n }\n\n const resultWithStega = encodeIntoResult(\n result,\n resultSourceMap,\n ({sourcePath, sourceDocument, resultPath, value}) => {\n // Allow userland to control when to opt-out of encoding\n if (\n (typeof filter === 'function'\n ? filter({sourcePath, resultPath, filterDefault, sourceDocument, value})\n : filterDefault({sourcePath, resultPath, filterDefault, sourceDocument, value})) === false\n ) {\n if (logger) {\n report.skipped.push({\n path: prettyPathForLogging(sourcePath),\n value: `${value.slice(0, TRUNCATE_LENGTH)}${\n value.length > TRUNCATE_LENGTH ? '...' : ''\n }`,\n length: value.length,\n })\n }\n return value\n }\n\n if (logger) {\n report.encoded.push({\n path: prettyPathForLogging(sourcePath),\n value: `${value.slice(0, TRUNCATE_LENGTH)}${value.length > TRUNCATE_LENGTH ? '...' : ''}`,\n length: value.length,\n })\n }\n\n const {baseUrl, workspace, tool} = resolveStudioBaseRoute(\n typeof config.studioUrl === 'function'\n ? config.studioUrl(sourceDocument)\n : config.studioUrl!,\n )\n if (!baseUrl) return value\n const {_id: id, _type: type, _projectId: projectId, _dataset: dataset} = sourceDocument\n\n return vercelStegaCombine(\n value,\n {\n origin: 'sanity.io',\n href: createEditUrl({\n baseUrl,\n workspace,\n tool,\n id,\n type,\n path: sourcePath,\n ...(!config.omitCrossDatasetReferenceData && {dataset, projectId}),\n }),\n },\n // We use custom logic to determine if we should skip encoding\n false,\n )\n },\n )\n\n if (logger) {\n const isSkipping = report.skipped.length\n const isEncoding = report.encoded.length\n if (isSkipping || isEncoding) {\n ;(logger?.groupCollapsed || logger.log)?.('[@sanity/client]: Encoding source map into result')\n logger.log?.(\n `[@sanity/client]: Paths encoded: ${report.encoded.length}, skipped: ${report.skipped.length}`,\n )\n }\n if (report.encoded.length > 0) {\n logger?.log?.(`[@sanity/client]: Table of encoded paths`)\n ;(logger?.table || logger.log)?.(report.encoded)\n }\n if (report.skipped.length > 0) {\n const skipped = new Set<string>()\n for (const {path} of report.skipped) {\n skipped.add(path.replace(reKeySegment, '0').replace(/\\[\\d+\\]/g, '[]'))\n }\n logger?.log?.(`[@sanity/client]: List of skipped paths`, [...skipped.values()])\n }\n\n if (isSkipping || isEncoding) {\n logger?.groupEnd?.()\n }\n }\n\n return resultWithStega\n}\n\nfunction prettyPathForLogging(path: ContentSourceMapParsedPath): string {\n return studioPathToString(jsonPathToStudioPath(path))\n}\n"],"mappings":";;;;AAoBA,SAAgB,UAAU,IAA2B;CACnD,OAAO,GAAG,WAAW,SAAa;AACpC;;AAGA,SAAgB,YAAY,IAAqB;CAC/C,OAAO,GAAG,WAAW,WAAc;AACrC;;AAGA,SAAgB,cAAc,IAA+B;CAC3D,OAAO,CAAC,UAAU,EAAE,KAAK,CAAC,YAAY,EAAE;AAC1C;AAWA,SAAS,cAAc,OAA4B;CACjD,OAAO;AACT;;;;;;;;AA4BA,SAAgB,iBAAiB,IAAgC;CAC/D,IAAI,CAAC,YAAY,EAAE,GAAG;CACtB,IAAM,CAAC,gBAAgB,WAAW,GAAG,gBAAgB,GAAG,MAAM,GAAc;CAE5E,OAAO;AACT;;AAGA,SAAgB,eAAe,IAAyB;CACtD,IAAI,YAAY,EAAE,GAEhB,OAAO,cAAc,GAAG,MAAM,GAAc,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,KAAK,GAAc,CAAC;CAG7E,IAAI,UAAU,EAAE,GACd,OAAO,cAAc,GAAG,MAAM,CAAoB,CAAC;CAGrD,IAAI,cAAc,EAAE,GAClB,OAAO;CAKT,MAAU,MAAM,0CAA0C,GAAG,EAAE;AACjE;;ACnFA,MAAa,eAAe;;AAS5B,SAAgB,aAAa,SAA+C;CAK1E,OAJI,OAAO,WAAY,WACd,aAAa,KAAK,QAAQ,KAAK,CAAC,IAGlC,OAAO,WAAY,YAAY,UAAU;AAClD;;AA+DA,SAAgB,SAAS,MAAoB;CAC3C,IAAI,CAAC,MAAM,QAAQ,IAAI,GACrB,MAAU,MAAM,sBAAsB;CAGxC,OAAO,KAAK,QAAgB,QAAQ,SAAS,MAAM;EACjD,IAAM,cAAc,OAAO;EAC3B,IAAI,gBAAgB,UAClB,OAAO,GAAG,OAAO,GAAG,QAAQ;EAG9B,IAAI,gBAAgB,UA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AC,GAAG,QAAQ,OAAO,CAAC,CAAC;EAChF;EAEA,CAAI,cAAc,eAChB,QAAQ,WAAW;CAEvB;CAEA,OAAO;AACT;AAEA,SAAS,qBAAqB,MAA0C;CACtE,OAAOC,SAAmB,qBAAqB,IAAI,CAAC;AACtD"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { t as __exportAll } from "./rolldown-runtime-vyAXikos.js";
|
|
2
2
|
import { n as y } from "./dist-Z8cIRxoB.js";
|
|
3
|
-
import { S as toString, a as resolveMapping, b as reKeySegment, c as parseJsonPath, i as walkMap, n as resolveStudioBaseRoute, r as createEditUrl, s as jsonPathToStudioPath } from "./resolveEditInfo-
|
|
3
|
+
import { S as toString, a as resolveMapping, b as reKeySegment, c as parseJsonPath, i as walkMap, n as resolveStudioBaseRoute, r as createEditUrl, s as jsonPathToStudioPath } from "./resolveEditInfo-Cz-smq3a.js";
|
|
4
4
|
/**
|
|
5
5
|
* @internal
|
|
6
6
|
*/
|
|
@@ -160,4 +160,4 @@ function prettyPathForLogging(path) {
|
|
|
160
160
|
}
|
|
161
161
|
export { stegaEncodeSourceMap_exports as n, encodeIntoResult as r, stegaEncodeSourceMap as t };
|
|
162
162
|
|
|
163
|
-
//# sourceMappingURL=stegaEncodeSourceMap-
|
|
163
|
+
//# sourceMappingURL=stegaEncodeSourceMap-YR3NQ3iz.js.map
|