@sanity/sdk-react 0.0.0-alpha.26 → 0.0.0-alpha.28
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/_chunks-es/index.js +43 -25
- package/dist/_chunks-es/index.js.map +1 -1
- package/dist/index.d.ts +16 -11
- package/package.json +6 -5
- package/src/context/ResourceProvider.tsx +2 -2
- package/src/hooks/context/useSanityInstance.ts +2 -2
- package/src/hooks/dashboard/useNavigateToStudioDocument.test.ts +120 -4
- package/src/hooks/dashboard/useNavigateToStudioDocument.ts +51 -16
- package/src/hooks/dashboard/useStudioWorkspacesByProjectIdDataset.test.tsx +103 -90
- package/src/hooks/dashboard/useStudioWorkspacesByProjectIdDataset.ts +21 -13
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../../src/context/SanityInstanceContext.ts","../../src/hooks/context/useSanityInstance.ts","../../src/hooks/helpers/createStateSourceHook.tsx","../../src/hooks/auth/useAuthState.tsx","../../src/hooks/auth/useLoginUrl.tsx","../../src/components/utils.ts","../../src/components/auth/AuthError.ts","../../src/hooks/helpers/createCallbackHook.tsx","../../src/hooks/auth/useHandleAuthCallback.tsx","../../src/components/auth/LoginCallback.tsx","../../../../node_modules/.pnpm/get-it@8.6.7/node_modules/get-it/dist/_chunks-es/defaultOptionsValidator.js","../../../../node_modules/.pnpm/get-it@8.6.7/node_modules/get-it/dist/_chunks-es/createRequester.js","../../../../node_modules/.pnpm/mimic-response@3.1.0/node_modules/mimic-response/index.js","../../../../node_modules/.pnpm/decompress-response@7.0.0/node_modules/decompress-response/index.js","../../../../node_modules/.pnpm/ms@2.1.3/node_modules/ms/index.js","../../../../node_modules/.pnpm/debug@4.4.0/node_modules/debug/src/common.js","../../../../node_modules/.pnpm/debug@4.4.0/node_modules/debug/src/browser.js","../../../../node_modules/.pnpm/has-flag@4.0.0/node_modules/has-flag/index.js","../../../../node_modules/.pnpm/supports-color@7.2.0/node_modules/supports-color/index.js","../../../../node_modules/.pnpm/debug@4.4.0/node_modules/debug/src/node.js","../../../../node_modules/.pnpm/debug@4.4.0/node_modules/debug/src/index.js","../../../../node_modules/.pnpm/follow-redirects@1.15.9/node_modules/follow-redirects/debug.js","../../../../node_modules/.pnpm/follow-redirects@1.15.9/node_modules/follow-redirects/index.js","../../../../node_modules/.pnpm/process-nextick-args@2.0.1/node_modules/process-nextick-args/index.js","../../../../node_modules/.pnpm/isarray@1.0.0/node_modules/isarray/index.js","../../../../node_modules/.pnpm/readable-stream@2.3.8/node_modules/readable-stream/lib/internal/streams/stream.js","../../../../node_modules/.pnpm/safe-buffer@5.1.2/node_modules/safe-buffer/index.js","../../../../node_modules/.pnpm/core-util-is@1.0.3/node_modules/core-util-is/lib/util.js","../../../../node_modules/.pnpm/inherits@2.0.4/node_modules/inherits/inherits_browser.js","../../../../node_modules/.pnpm/inherits@2.0.4/node_modules/inherits/inherits.js","../../../../node_modules/.pnpm/readable-stream@2.3.8/node_modules/readable-stream/lib/internal/streams/BufferList.js","../../../../node_modules/.pnpm/readable-stream@2.3.8/node_modules/readable-stream/lib/internal/streams/destroy.js","../../../../node_modules/.pnpm/util-deprecate@1.0.2/node_modules/util-deprecate/node.js","../../../../node_modules/.pnpm/readable-stream@2.3.8/node_modules/readable-stream/lib/_stream_writable.js","../../../../node_modules/.pnpm/readable-stream@2.3.8/node_modules/readable-stream/lib/_stream_duplex.js","../../../../node_modules/.pnpm/string_decoder@1.1.1/node_modules/string_decoder/lib/string_decoder.js","../../../../node_modules/.pnpm/readable-stream@2.3.8/node_modules/readable-stream/lib/_stream_readable.js","../../../../node_modules/.pnpm/readable-stream@2.3.8/node_modules/readable-stream/lib/_stream_transform.js","../../../../node_modules/.pnpm/readable-stream@2.3.8/node_modules/readable-stream/lib/_stream_passthrough.js","../../../../node_modules/.pnpm/readable-stream@2.3.8/node_modules/readable-stream/readable.js","../../../../node_modules/.pnpm/xtend@4.0.2/node_modules/xtend/immutable.js","../../../../node_modules/.pnpm/through2@2.0.5/node_modules/through2/through2.js","../../../../node_modules/.pnpm/speedometer@1.0.0/node_modules/speedometer/index.js","../../../../node_modules/.pnpm/progress-stream@2.0.0/node_modules/progress-stream/index.js","../../../../node_modules/.pnpm/safe-buffer@5.2.1/node_modules/safe-buffer/index.js","../../../../node_modules/.pnpm/tunnel-agent@0.6.0/node_modules/tunnel-agent/index.js","../../../../node_modules/.pnpm/get-it@8.6.7/node_modules/get-it/dist/_chunks-es/node-request.js","../../../../node_modules/.pnpm/get-it@8.6.7/node_modules/get-it/dist/index.js","../../../../node_modules/.pnpm/is-retry-allowed@2.2.0/node_modules/is-retry-allowed/index.js","../../../../node_modules/.pnpm/get-it@8.6.7/node_modules/get-it/dist/middleware.js","../../../../node_modules/.pnpm/@sanity+client@6.29.0/node_modules/@sanity/client/dist/_chunks-es/stegaClean.js","../../../../node_modules/.pnpm/@sanity+client@6.29.0/node_modules/@sanity/client/dist/_chunks-es/config.js","../../../../node_modules/.pnpm/@sanity+client@6.29.0/node_modules/@sanity/client/dist/index.js","../../src/hooks/auth/useLogOut.tsx","../../src/components/auth/LoginError.tsx","../../src/components/auth/AuthBoundary.tsx","../../src/context/ResourceProvider.tsx","../../src/components/SDKProvider.tsx","../../src/components/SanityApp.tsx","../../src/hooks/auth/useAuthToken.tsx","../../src/hooks/auth/useCurrentUser.tsx","../../src/hooks/auth/useDashboardOrganizationId.tsx","../../src/hooks/client/useClient.ts","../../src/hooks/comlink/useFrameConnection.ts","../../src/hooks/comlink/useWindowConnection.ts","../../src/hooks/comlink/useManageFavorite.ts","../../src/hooks/comlink/useRecordDocumentHistoryEvent.ts","../../src/hooks/dashboard/useStudioWorkspacesByProjectIdDataset.ts","../../src/hooks/dashboard/useNavigateToStudioDocument.ts","../../src/hooks/datasets/useDatasets.ts","../../src/hooks/document/useApplyDocumentActions.ts","../../src/hooks/document/useDocument.ts","../../src/hooks/document/useDocumentEvent.ts","../../src/hooks/document/useDocumentPermissions.ts","../../src/hooks/document/useDocumentSyncStatus.ts","../../src/hooks/document/useEditDocument.ts","../../src/hooks/query/useQuery.ts","../../src/hooks/documents/useDocuments.ts","../../src/hooks/paginatedDocuments/usePaginatedDocuments.ts","../../src/hooks/preview/usePreview.tsx","../../src/hooks/projection/useProjection.ts","../../src/hooks/projects/useProject.ts","../../src/hooks/projects/useProjects.ts","../../src/hooks/users/useUsers.ts","../../src/utils/getEnv.ts","../../src/version.ts"],"sourcesContent":["import {type SanityInstance} from '@sanity/sdk'\nimport {createContext} from 'react'\n\nexport const SanityInstanceContext = createContext<SanityInstance | null>(null)\n","import {type SanityConfig, type SanityInstance} from '@sanity/sdk'\nimport {use} from 'react'\n\nimport {SanityInstanceContext} from '../../context/SanityInstanceContext'\n\n/**\n * Retrieves the current Sanity instance or finds a matching instance from the hierarchy\n *\n * @public\n *\n * @category Platform\n * @param config - Optional configuration to match against when finding an instance\n * @returns The current or matching Sanity instance\n *\n * @remarks\n * This hook accesses the nearest Sanity instance from the React context. When provided with\n * a configuration object, it traverses up the instance hierarchy to find the closest instance\n * that matches the specified configuration using shallow comparison of properties.\n *\n * The hook must be used within a component wrapped by a `ResourceProvider` or `SanityApp`.\n *\n * Use this hook when you need to:\n * - Access the current SanityInstance from context\n * - Find a specific instance with matching project/dataset configuration\n * - Access a parent instance with specific configuration values\n *\n * @example Get the current instance\n * ```tsx\n * // Get the current instance from context\n * const instance = useSanityInstance()\n * console.log(instance.config.projectId)\n * ```\n *\n * @example Find an instance with specific configuration\n * ```tsx\n * // Find an instance matching the given project and dataset\n * const instance = useSanityInstance({\n * projectId: 'abc123',\n * dataset: 'production'\n * })\n *\n * // Use instance for API calls\n * const fetchDocument = (docId) => {\n * // Instance is guaranteed to have the matching config\n * return client.fetch(`*[_id == $id][0]`, { id: docId })\n * }\n * ```\n *\n * @example Match partial configuration\n * ```tsx\n * // Find an instance with specific auth configuration\n * const instance = useSanityInstance({\n * auth: { requireLogin: true }\n * })\n * ```\n *\n * @throws Error if no SanityInstance is found in context\n * @throws Error if no matching instance is found for the provided config\n */\nexport const useSanityInstance = (config?: SanityConfig): SanityInstance => {\n const instance = use(SanityInstanceContext)\n\n if (!instance) {\n throw new Error(\n `SanityInstance context not found. ${config ? `Requested config: ${JSON.stringify(config, null, 2)}. ` : ''}Please ensure that your component is wrapped in a <ResourceProvider> or a <SanityApp>.`,\n )\n }\n\n if (!config) return instance\n\n const match = instance.match(config)\n if (!match) {\n throw new Error(\n `Could not find a matching Sanity instance for the requested configuration: ${JSON.stringify(config, null, 2)}.\nPlease ensure there is a <ResourceProvider> with a matching configuration in the component hierarchy.`,\n )\n }\n\n return match\n}\n","import {type SanityConfig, type SanityInstance, type StateSource} from '@sanity/sdk'\nimport {useSyncExternalStore} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\ntype StateSourceFactory<TParams extends unknown[], TState> = (\n instance: SanityInstance,\n ...params: TParams\n) => StateSource<TState>\n\ninterface CreateStateSourceHookOptions<TParams extends unknown[], TState> {\n getState: StateSourceFactory<TParams, TState>\n shouldSuspend?: (instance: SanityInstance, ...params: TParams) => boolean\n suspender?: (instance: SanityInstance, ...params: TParams) => Promise<unknown>\n getConfig?: (...params: TParams) => SanityConfig | undefined\n}\n\nexport function createStateSourceHook<TParams extends unknown[], TState>(\n options: StateSourceFactory<TParams, TState> | CreateStateSourceHookOptions<TParams, TState>,\n): (...params: TParams) => TState {\n const getState = typeof options === 'function' ? options : options.getState\n const getConfig = 'getConfig' in options ? options.getConfig : undefined\n const suspense = 'shouldSuspend' in options && 'suspender' in options ? options : undefined\n\n function useHook(...params: TParams) {\n const instance = useSanityInstance(getConfig?.(...params))\n\n if (suspense?.suspender && suspense?.shouldSuspend?.(instance, ...params)) {\n throw suspense.suspender(instance, ...params)\n }\n\n const state = getState(instance, ...params)\n return useSyncExternalStore(state.subscribe, state.getCurrent)\n }\n\n return useHook\n}\n","import {type AuthState, getAuthState} from '@sanity/sdk'\n\nimport {createStateSourceHook} from '../helpers/createStateSourceHook'\n\n/**\n * @internal\n * A React hook that subscribes to authentication state changes.\n *\n * This hook provides access to the current authentication state type from the Sanity auth store.\n * It automatically re-renders when the authentication state changes.\n *\n * @remarks\n * The hook uses `useSyncExternalStore` to safely subscribe to auth state changes\n * and ensure consistency between server and client rendering.\n *\n * @returns The current authentication state type\n *\n * @example\n * ```tsx\n * function AuthStatus() {\n * const authState = useAuthState()\n * return <div>Current auth state: {authState}</div>\n * }\n * ```\n */\nexport const useAuthState: () => AuthState = createStateSourceHook(getAuthState)\n","import {getLoginUrlState} from '@sanity/sdk'\nimport {useMemo, useSyncExternalStore} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\n/**\n * @internal\n */\nexport function useLoginUrl(): string {\n const instance = useSanityInstance()\n const {subscribe, getCurrent} = useMemo(() => getLoginUrlState(instance), [instance])\n\n return useSyncExternalStore(subscribe, getCurrent as () => string)\n}\n","export function isInIframe(): boolean {\n return typeof window !== 'undefined' && window.self !== window.top\n}\n\n/**\n * @internal\n *\n * Checks if the current URL is a local URL.\n *\n * @param window - The window object\n * @returns True if the current URL is a local URL, false otherwise\n */\nexport function isLocalUrl(window: Window): boolean {\n const url = typeof window !== 'undefined' ? window.location.href : ''\n\n return (\n url.startsWith('http://localhost') ||\n url.startsWith('https://localhost') ||\n url.startsWith('http://127.0.0.1') ||\n url.startsWith('https://127.0.0.1')\n )\n}\n","/**\n * Error class for authentication-related errors. Wraps errors thrown during the\n * authentication flow.\n *\n * @remarks\n * This class provides a consistent error type for authentication failures while\n * preserving the original error as the cause. If the original error has a\n * message property, it will be used as the error message.\n *\n * @alpha\n */\nexport class AuthError extends Error {\n constructor(error: unknown) {\n if (\n typeof error === 'object' &&\n !!error &&\n 'message' in error &&\n typeof error.message === 'string'\n ) {\n super(error.message)\n } else {\n super()\n }\n\n this.cause = error\n }\n}\n","import {type SanityInstance} from '@sanity/sdk'\nimport {useCallback} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\nexport function createCallbackHook<TParams extends unknown[], TReturn>(\n callback: (instance: SanityInstance, ...params: TParams) => TReturn,\n): () => (...params: TParams) => TReturn {\n function useHook() {\n const instance = useSanityInstance()\n return useCallback((...params: TParams) => callback(instance, ...params), [instance])\n }\n\n return useHook\n}\n","import {handleAuthCallback} from '@sanity/sdk'\n\nimport {createCallbackHook} from '../helpers/createCallbackHook'\n\n/**\n * @internal\n * A React hook that returns a function for handling authentication callbacks.\n *\n * @remarks\n * This hook provides access to the authentication store's callback handler,\n * which processes auth redirects by extracting the session ID and fetching the\n * authentication token. If fetching the long-lived token is successful,\n * `handleAuthCallback` will return a Promise that resolves a new location that\n * removes the short-lived token from the URL. Use this in combination with\n * `history.replaceState` or your own router's `replace` function to update the\n * current location without triggering a reload.\n *\n * @example\n * ```tsx\n * function AuthCallback() {\n * const handleAuthCallback = useHandleAuthCallback()\n * const router = useRouter() // Example router\n *\n * useEffect(() => {\n * async function processCallback() {\n * // Handle the callback and get the cleaned URL\n * const newUrl = await handleAuthCallback(window.location.href)\n *\n * if (newUrl) {\n * // Replace URL without triggering navigation\n * router.replace(newUrl, {shallow: true})\n * }\n * }\n *\n * processCallback().catch(console.error)\n * }, [handleAuthCallback, router])\n *\n * return <div>Completing login...</div>\n * }\n * ```\n *\n * @returns A callback handler function that processes OAuth redirects\n * @public\n */\nexport const useHandleAuthCallback = createCallbackHook(handleAuthCallback)\n","import {useEffect} from 'react'\n\nimport {useHandleAuthCallback} from '../../hooks/auth/useHandleAuthCallback'\n\n/**\n * Component shown during auth callback processing that handles login completion.\n * Automatically processes the auth callback when mounted and updates the URL\n * to remove callback parameters without triggering a page reload.\n *\n * @alpha\n */\nexport function LoginCallback(): React.ReactNode {\n const handleAuthCallback = useHandleAuthCallback()\n\n useEffect(() => {\n const url = new URL(location.href)\n handleAuthCallback(url.toString()).then((replacementLocation) => {\n if (replacementLocation) {\n // history API with `replaceState` is used to prevent a reload but still\n // remove the short-lived token from the URL\n history.replaceState(null, '', replacementLocation)\n }\n })\n }, [handleAuthCallback])\n\n return null\n}\n","const e=!(typeof navigator>\"u\")&&\"ReactNative\"===navigator.product,t={timeout:e?6e4:12e4},r=function(r){const a={...t,...\"string\"==typeof r?{url:r}:r};if(a.timeout=o(a.timeout),a.query){const{url:t,searchParams:r}=function(t){const r=t.indexOf(\"?\");if(-1===r)return{url:t,searchParams:new URLSearchParams};const o=t.slice(0,r),a=t.slice(r+1);if(!e)return{url:o,searchParams:new URLSearchParams(a)};if(\"function\"!=typeof decodeURIComponent)throw new Error(\"Broken `URLSearchParams` implementation, and `decodeURIComponent` is not defined\");const s=new URLSearchParams;for(const e of a.split(\"&\")){const[t,r]=e.split(\"=\");t&&s.append(n(t),n(r||\"\"))}return{url:o,searchParams:s}}(a.url);for(const[e,n]of Object.entries(a.query)){if(void 0!==n)if(Array.isArray(n))for(const t of n)r.append(e,t);else r.append(e,n);const o=r.toString();o&&(a.url=`${t}?${o}`)}}return a.method=a.body&&!a.method?\"POST\":(a.method||\"GET\").toUpperCase(),a};function n(e){return decodeURIComponent(e.replace(/\\+/g,\" \"))}function o(e){if(!1===e||0===e)return!1;if(e.connect||e.socket)return e;const r=Number(e);return isNaN(r)?o(t.timeout):{connect:r,socket:r}}const a=/^https?:\\/\\//i,s=function(e){if(!a.test(e.url))throw new Error(`\"${e.url}\" is not a valid URL`)};export{r as p,s as v};//# sourceMappingURL=defaultOptionsValidator.js.map\n","import{p as e,v as t}from\"./defaultOptionsValidator.js\";const r=[\"request\",\"response\",\"progress\",\"error\",\"abort\"],o=[\"processOptions\",\"validateOptions\",\"interceptRequest\",\"finalizeOptions\",\"onRequest\",\"onResponse\",\"onError\",\"onReturn\",\"onHeaders\"];function n(s,i){const u=[],a=o.reduce(((e,t)=>(e[t]=e[t]||[],e)),{processOptions:[e],validateOptions:[t]});function c(e){const t=r.reduce(((e,t)=>(e[t]=function(){const e=/* @__PURE__ */Object.create(null);let t=0;return{publish:function(t){for(const r in e)e[r](t)},subscribe:function(r){const o=t++;return e[o]=r,function(){delete e[o]}}}}(),e)),{}),o=(e=>function(t,r,...o){const n=\"onError\"===t;let s=r;for(let r=0;r<e[t].length&&(s=(0,e[t][r])(s,...o),!n||s);r++);return s})(a),n=o(\"processOptions\",e);o(\"validateOptions\",n);const s={options:n,channels:t,applyMiddleware:o};let u;const c=t.request.subscribe((e=>{u=i(e,((r,n)=>((e,r,n)=>{let s=e,i=r;if(!s)try{i=o(\"onResponse\",r,n)}catch(e){i=null,s=e}s=s&&o(\"onError\",s,n),s?t.error.publish(s):i&&t.response.publish(i)})(r,n,e)))}));t.abort.subscribe((()=>{c(),u&&u.abort()}));const l=o(\"onReturn\",t,s);return l===t&&t.request.publish(s),l}return c.use=function(e){if(!e)throw new Error(\"Tried to add middleware that resolved to falsey value\");if(\"function\"==typeof e)throw new Error(\"Tried to add middleware that was a function. It probably expects you to pass options to it.\");if(e.onReturn&&a.onReturn.length>0)throw new Error(\"Tried to add new middleware with `onReturn` handler, but another handler has already been registered for this event\");return o.forEach((t=>{e[t]&&a[t].push(e[t])})),u.push(e),c},c.clone=()=>n(u,i),s.forEach(c.use),c}export{n as c};//# sourceMappingURL=createRequester.js.map\n","'use strict';\n\n// We define these manually to ensure they're always copied\n// even if they would move up the prototype chain\n// https://nodejs.org/api/http.html#http_class_http_incomingmessage\nconst knownProperties = [\n\t'aborted',\n\t'complete',\n\t'headers',\n\t'httpVersion',\n\t'httpVersionMinor',\n\t'httpVersionMajor',\n\t'method',\n\t'rawHeaders',\n\t'rawTrailers',\n\t'setTimeout',\n\t'socket',\n\t'statusCode',\n\t'statusMessage',\n\t'trailers',\n\t'url'\n];\n\nmodule.exports = (fromStream, toStream) => {\n\tif (toStream._readableState.autoDestroy) {\n\t\tthrow new Error('The second stream must have the `autoDestroy` option set to `false`');\n\t}\n\n\tconst fromProperties = new Set(Object.keys(fromStream).concat(knownProperties));\n\n\tconst properties = {};\n\n\tfor (const property of fromProperties) {\n\t\t// Don't overwrite existing properties.\n\t\tif (property in toStream) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tproperties[property] = {\n\t\t\tget() {\n\t\t\t\tconst value = fromStream[property];\n\t\t\t\tconst isFunction = typeof value === 'function';\n\n\t\t\t\treturn isFunction ? value.bind(fromStream) : value;\n\t\t\t},\n\t\t\tset(value) {\n\t\t\t\tfromStream[property] = value;\n\t\t\t},\n\t\t\tenumerable: true,\n\t\t\tconfigurable: false\n\t\t};\n\t}\n\n\tObject.defineProperties(toStream, properties);\n\n\tfromStream.once('aborted', () => {\n\t\ttoStream.destroy();\n\n\t\ttoStream.emit('aborted');\n\t});\n\n\tfromStream.once('close', () => {\n\t\tif (fromStream.complete) {\n\t\t\tif (toStream.readable) {\n\t\t\t\ttoStream.once('end', () => {\n\t\t\t\t\ttoStream.emit('close');\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\ttoStream.emit('close');\n\t\t\t}\n\t\t} else {\n\t\t\ttoStream.emit('close');\n\t\t}\n\t});\n\n\treturn toStream;\n};\n","'use strict';\nconst {Transform, PassThrough} = require('stream');\nconst zlib = require('zlib');\nconst mimicResponse = require('mimic-response');\n\nmodule.exports = response => {\n\tconst contentEncoding = (response.headers['content-encoding'] || '').toLowerCase();\n\tdelete response.headers['content-encoding'];\n\n\tif (!['gzip', 'deflate', 'br'].includes(contentEncoding)) {\n\t\treturn response;\n\t}\n\n\t// TODO: Remove this when targeting Node.js 12.\n\tconst isBrotli = contentEncoding === 'br';\n\tif (isBrotli && typeof zlib.createBrotliDecompress !== 'function') {\n\t\tresponse.destroy(new Error('Brotli is not supported on Node.js < 12'));\n\t\treturn response;\n\t}\n\n\tlet isEmpty = true;\n\n\tconst checker = new Transform({\n\t\ttransform(data, _encoding, callback) {\n\t\t\tisEmpty = false;\n\n\t\t\tcallback(null, data);\n\t\t},\n\n\t\tflush(callback) {\n\t\t\tcallback();\n\t\t}\n\t});\n\n\tconst finalStream = new PassThrough({\n\t\tautoDestroy: false,\n\t\tdestroy(error, callback) {\n\t\t\tresponse.destroy();\n\n\t\t\tcallback(error);\n\t\t}\n\t});\n\n\tconst decompressStream = isBrotli ? zlib.createBrotliDecompress() : zlib.createUnzip();\n\n\tdecompressStream.once('error', error => {\n\t\tif (isEmpty && !response.readable) {\n\t\t\tfinalStream.end();\n\t\t\treturn;\n\t\t}\n\n\t\tfinalStream.destroy(error);\n\t});\n\n\tmimicResponse(response, finalStream);\n\tresponse.pipe(checker).pipe(decompressStream).pipe(finalStream);\n\n\treturn finalStream;\n};\n","/**\n * Helpers.\n */\n\nvar s = 1000;\nvar m = s * 60;\nvar h = m * 60;\nvar d = h * 24;\nvar w = d * 7;\nvar y = d * 365.25;\n\n/**\n * Parse or format the given `val`.\n *\n * Options:\n *\n * - `long` verbose formatting [false]\n *\n * @param {String|Number} val\n * @param {Object} [options]\n * @throws {Error} throw an error if val is not a non-empty string or a number\n * @return {String|Number}\n * @api public\n */\n\nmodule.exports = function (val, options) {\n options = options || {};\n var type = typeof val;\n if (type === 'string' && val.length > 0) {\n return parse(val);\n } else if (type === 'number' && isFinite(val)) {\n return options.long ? fmtLong(val) : fmtShort(val);\n }\n throw new Error(\n 'val is not a non-empty string or a valid number. val=' +\n JSON.stringify(val)\n );\n};\n\n/**\n * Parse the given `str` and return milliseconds.\n *\n * @param {String} str\n * @return {Number}\n * @api private\n */\n\nfunction parse(str) {\n str = String(str);\n if (str.length > 100) {\n return;\n }\n var match = /^(-?(?:\\d+)?\\.?\\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(\n str\n );\n if (!match) {\n return;\n }\n var n = parseFloat(match[1]);\n var type = (match[2] || 'ms').toLowerCase();\n switch (type) {\n case 'years':\n case 'year':\n case 'yrs':\n case 'yr':\n case 'y':\n return n * y;\n case 'weeks':\n case 'week':\n case 'w':\n return n * w;\n case 'days':\n case 'day':\n case 'd':\n return n * d;\n case 'hours':\n case 'hour':\n case 'hrs':\n case 'hr':\n case 'h':\n return n * h;\n case 'minutes':\n case 'minute':\n case 'mins':\n case 'min':\n case 'm':\n return n * m;\n case 'seconds':\n case 'second':\n case 'secs':\n case 'sec':\n case 's':\n return n * s;\n case 'milliseconds':\n case 'millisecond':\n case 'msecs':\n case 'msec':\n case 'ms':\n return n;\n default:\n return undefined;\n }\n}\n\n/**\n * Short format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtShort(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return Math.round(ms / d) + 'd';\n }\n if (msAbs >= h) {\n return Math.round(ms / h) + 'h';\n }\n if (msAbs >= m) {\n return Math.round(ms / m) + 'm';\n }\n if (msAbs >= s) {\n return Math.round(ms / s) + 's';\n }\n return ms + 'ms';\n}\n\n/**\n * Long format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtLong(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return plural(ms, msAbs, d, 'day');\n }\n if (msAbs >= h) {\n return plural(ms, msAbs, h, 'hour');\n }\n if (msAbs >= m) {\n return plural(ms, msAbs, m, 'minute');\n }\n if (msAbs >= s) {\n return plural(ms, msAbs, s, 'second');\n }\n return ms + ' ms';\n}\n\n/**\n * Pluralization helper.\n */\n\nfunction plural(ms, msAbs, n, name) {\n var isPlural = msAbs >= n * 1.5;\n return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');\n}\n","\n/**\n * This is the common logic for both the Node.js and web browser\n * implementations of `debug()`.\n */\n\nfunction setup(env) {\n\tcreateDebug.debug = createDebug;\n\tcreateDebug.default = createDebug;\n\tcreateDebug.coerce = coerce;\n\tcreateDebug.disable = disable;\n\tcreateDebug.enable = enable;\n\tcreateDebug.enabled = enabled;\n\tcreateDebug.humanize = require('ms');\n\tcreateDebug.destroy = destroy;\n\n\tObject.keys(env).forEach(key => {\n\t\tcreateDebug[key] = env[key];\n\t});\n\n\t/**\n\t* The currently active debug mode names, and names to skip.\n\t*/\n\n\tcreateDebug.names = [];\n\tcreateDebug.skips = [];\n\n\t/**\n\t* Map of special \"%n\" handling functions, for the debug \"format\" argument.\n\t*\n\t* Valid key names are a single, lower or upper-case letter, i.e. \"n\" and \"N\".\n\t*/\n\tcreateDebug.formatters = {};\n\n\t/**\n\t* Selects a color for a debug namespace\n\t* @param {String} namespace The namespace string for the debug instance to be colored\n\t* @return {Number|String} An ANSI color code for the given namespace\n\t* @api private\n\t*/\n\tfunction selectColor(namespace) {\n\t\tlet hash = 0;\n\n\t\tfor (let i = 0; i < namespace.length; i++) {\n\t\t\thash = ((hash << 5) - hash) + namespace.charCodeAt(i);\n\t\t\thash |= 0; // Convert to 32bit integer\n\t\t}\n\n\t\treturn createDebug.colors[Math.abs(hash) % createDebug.colors.length];\n\t}\n\tcreateDebug.selectColor = selectColor;\n\n\t/**\n\t* Create a debugger with the given `namespace`.\n\t*\n\t* @param {String} namespace\n\t* @return {Function}\n\t* @api public\n\t*/\n\tfunction createDebug(namespace) {\n\t\tlet prevTime;\n\t\tlet enableOverride = null;\n\t\tlet namespacesCache;\n\t\tlet enabledCache;\n\n\t\tfunction debug(...args) {\n\t\t\t// Disabled?\n\t\t\tif (!debug.enabled) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst self = debug;\n\n\t\t\t// Set `diff` timestamp\n\t\t\tconst curr = Number(new Date());\n\t\t\tconst ms = curr - (prevTime || curr);\n\t\t\tself.diff = ms;\n\t\t\tself.prev = prevTime;\n\t\t\tself.curr = curr;\n\t\t\tprevTime = curr;\n\n\t\t\targs[0] = createDebug.coerce(args[0]);\n\n\t\t\tif (typeof args[0] !== 'string') {\n\t\t\t\t// Anything else let's inspect with %O\n\t\t\t\targs.unshift('%O');\n\t\t\t}\n\n\t\t\t// Apply any `formatters` transformations\n\t\t\tlet index = 0;\n\t\t\targs[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {\n\t\t\t\t// If we encounter an escaped % then don't increase the array index\n\t\t\t\tif (match === '%%') {\n\t\t\t\t\treturn '%';\n\t\t\t\t}\n\t\t\t\tindex++;\n\t\t\t\tconst formatter = createDebug.formatters[format];\n\t\t\t\tif (typeof formatter === 'function') {\n\t\t\t\t\tconst val = args[index];\n\t\t\t\t\tmatch = formatter.call(self, val);\n\n\t\t\t\t\t// Now we need to remove `args[index]` since it's inlined in the `format`\n\t\t\t\t\targs.splice(index, 1);\n\t\t\t\t\tindex--;\n\t\t\t\t}\n\t\t\t\treturn match;\n\t\t\t});\n\n\t\t\t// Apply env-specific formatting (colors, etc.)\n\t\t\tcreateDebug.formatArgs.call(self, args);\n\n\t\t\tconst logFn = self.log || createDebug.log;\n\t\t\tlogFn.apply(self, args);\n\t\t}\n\n\t\tdebug.namespace = namespace;\n\t\tdebug.useColors = createDebug.useColors();\n\t\tdebug.color = createDebug.selectColor(namespace);\n\t\tdebug.extend = extend;\n\t\tdebug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.\n\n\t\tObject.defineProperty(debug, 'enabled', {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: false,\n\t\t\tget: () => {\n\t\t\t\tif (enableOverride !== null) {\n\t\t\t\t\treturn enableOverride;\n\t\t\t\t}\n\t\t\t\tif (namespacesCache !== createDebug.namespaces) {\n\t\t\t\t\tnamespacesCache = createDebug.namespaces;\n\t\t\t\t\tenabledCache = createDebug.enabled(namespace);\n\t\t\t\t}\n\n\t\t\t\treturn enabledCache;\n\t\t\t},\n\t\t\tset: v => {\n\t\t\t\tenableOverride = v;\n\t\t\t}\n\t\t});\n\n\t\t// Env-specific initialization logic for debug instances\n\t\tif (typeof createDebug.init === 'function') {\n\t\t\tcreateDebug.init(debug);\n\t\t}\n\n\t\treturn debug;\n\t}\n\n\tfunction extend(namespace, delimiter) {\n\t\tconst newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);\n\t\tnewDebug.log = this.log;\n\t\treturn newDebug;\n\t}\n\n\t/**\n\t* Enables a debug mode by namespaces. This can include modes\n\t* separated by a colon and wildcards.\n\t*\n\t* @param {String} namespaces\n\t* @api public\n\t*/\n\tfunction enable(namespaces) {\n\t\tcreateDebug.save(namespaces);\n\t\tcreateDebug.namespaces = namespaces;\n\n\t\tcreateDebug.names = [];\n\t\tcreateDebug.skips = [];\n\n\t\tconst split = (typeof namespaces === 'string' ? namespaces : '')\n\t\t\t.trim()\n\t\t\t.replace(' ', ',')\n\t\t\t.split(',')\n\t\t\t.filter(Boolean);\n\n\t\tfor (const ns of split) {\n\t\t\tif (ns[0] === '-') {\n\t\t\t\tcreateDebug.skips.push(ns.slice(1));\n\t\t\t} else {\n\t\t\t\tcreateDebug.names.push(ns);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Checks if the given string matches a namespace template, honoring\n\t * asterisks as wildcards.\n\t *\n\t * @param {String} search\n\t * @param {String} template\n\t * @return {Boolean}\n\t */\n\tfunction matchesTemplate(search, template) {\n\t\tlet searchIndex = 0;\n\t\tlet templateIndex = 0;\n\t\tlet starIndex = -1;\n\t\tlet matchIndex = 0;\n\n\t\twhile (searchIndex < search.length) {\n\t\t\tif (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === '*')) {\n\t\t\t\t// Match character or proceed with wildcard\n\t\t\t\tif (template[templateIndex] === '*') {\n\t\t\t\t\tstarIndex = templateIndex;\n\t\t\t\t\tmatchIndex = searchIndex;\n\t\t\t\t\ttemplateIndex++; // Skip the '*'\n\t\t\t\t} else {\n\t\t\t\t\tsearchIndex++;\n\t\t\t\t\ttemplateIndex++;\n\t\t\t\t}\n\t\t\t} else if (starIndex !== -1) { // eslint-disable-line no-negated-condition\n\t\t\t\t// Backtrack to the last '*' and try to match more characters\n\t\t\t\ttemplateIndex = starIndex + 1;\n\t\t\t\tmatchIndex++;\n\t\t\t\tsearchIndex = matchIndex;\n\t\t\t} else {\n\t\t\t\treturn false; // No match\n\t\t\t}\n\t\t}\n\n\t\t// Handle trailing '*' in template\n\t\twhile (templateIndex < template.length && template[templateIndex] === '*') {\n\t\t\ttemplateIndex++;\n\t\t}\n\n\t\treturn templateIndex === template.length;\n\t}\n\n\t/**\n\t* Disable debug output.\n\t*\n\t* @return {String} namespaces\n\t* @api public\n\t*/\n\tfunction disable() {\n\t\tconst namespaces = [\n\t\t\t...createDebug.names,\n\t\t\t...createDebug.skips.map(namespace => '-' + namespace)\n\t\t].join(',');\n\t\tcreateDebug.enable('');\n\t\treturn namespaces;\n\t}\n\n\t/**\n\t* Returns true if the given mode name is enabled, false otherwise.\n\t*\n\t* @param {String} name\n\t* @return {Boolean}\n\t* @api public\n\t*/\n\tfunction enabled(name) {\n\t\tfor (const skip of createDebug.skips) {\n\t\t\tif (matchesTemplate(name, skip)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\tfor (const ns of createDebug.names) {\n\t\t\tif (matchesTemplate(name, ns)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/**\n\t* Coerce `val`.\n\t*\n\t* @param {Mixed} val\n\t* @return {Mixed}\n\t* @api private\n\t*/\n\tfunction coerce(val) {\n\t\tif (val instanceof Error) {\n\t\t\treturn val.stack || val.message;\n\t\t}\n\t\treturn val;\n\t}\n\n\t/**\n\t* XXX DO NOT USE. This is a temporary stub function.\n\t* XXX It WILL be removed in the next major release.\n\t*/\n\tfunction destroy() {\n\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t}\n\n\tcreateDebug.enable(createDebug.load());\n\n\treturn createDebug;\n}\n\nmodule.exports = setup;\n","/* eslint-env browser */\n\n/**\n * This is the web browser implementation of `debug()`.\n */\n\nexports.formatArgs = formatArgs;\nexports.save = save;\nexports.load = load;\nexports.useColors = useColors;\nexports.storage = localstorage();\nexports.destroy = (() => {\n\tlet warned = false;\n\n\treturn () => {\n\t\tif (!warned) {\n\t\t\twarned = true;\n\t\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t\t}\n\t};\n})();\n\n/**\n * Colors.\n */\n\nexports.colors = [\n\t'#0000CC',\n\t'#0000FF',\n\t'#0033CC',\n\t'#0033FF',\n\t'#0066CC',\n\t'#0066FF',\n\t'#0099CC',\n\t'#0099FF',\n\t'#00CC00',\n\t'#00CC33',\n\t'#00CC66',\n\t'#00CC99',\n\t'#00CCCC',\n\t'#00CCFF',\n\t'#3300CC',\n\t'#3300FF',\n\t'#3333CC',\n\t'#3333FF',\n\t'#3366CC',\n\t'#3366FF',\n\t'#3399CC',\n\t'#3399FF',\n\t'#33CC00',\n\t'#33CC33',\n\t'#33CC66',\n\t'#33CC99',\n\t'#33CCCC',\n\t'#33CCFF',\n\t'#6600CC',\n\t'#6600FF',\n\t'#6633CC',\n\t'#6633FF',\n\t'#66CC00',\n\t'#66CC33',\n\t'#9900CC',\n\t'#9900FF',\n\t'#9933CC',\n\t'#9933FF',\n\t'#99CC00',\n\t'#99CC33',\n\t'#CC0000',\n\t'#CC0033',\n\t'#CC0066',\n\t'#CC0099',\n\t'#CC00CC',\n\t'#CC00FF',\n\t'#CC3300',\n\t'#CC3333',\n\t'#CC3366',\n\t'#CC3399',\n\t'#CC33CC',\n\t'#CC33FF',\n\t'#CC6600',\n\t'#CC6633',\n\t'#CC9900',\n\t'#CC9933',\n\t'#CCCC00',\n\t'#CCCC33',\n\t'#FF0000',\n\t'#FF0033',\n\t'#FF0066',\n\t'#FF0099',\n\t'#FF00CC',\n\t'#FF00FF',\n\t'#FF3300',\n\t'#FF3333',\n\t'#FF3366',\n\t'#FF3399',\n\t'#FF33CC',\n\t'#FF33FF',\n\t'#FF6600',\n\t'#FF6633',\n\t'#FF9900',\n\t'#FF9933',\n\t'#FFCC00',\n\t'#FFCC33'\n];\n\n/**\n * Currently only WebKit-based Web Inspectors, Firefox >= v31,\n * and the Firebug extension (any Firefox version) are known\n * to support \"%c\" CSS customizations.\n *\n * TODO: add a `localStorage` variable to explicitly enable/disable colors\n */\n\n// eslint-disable-next-line complexity\nfunction useColors() {\n\t// NB: In an Electron preload script, document will be defined but not fully\n\t// initialized. Since we know we're in Chrome, we'll just detect this case\n\t// explicitly\n\tif (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {\n\t\treturn true;\n\t}\n\n\t// Internet Explorer and Edge do not support colors.\n\tif (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\\/(\\d+)/)) {\n\t\treturn false;\n\t}\n\n\tlet m;\n\n\t// Is webkit? http://stackoverflow.com/a/16459606/376773\n\t// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632\n\t// eslint-disable-next-line no-return-assign\n\treturn (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||\n\t\t// Is firebug? http://stackoverflow.com/a/398120/376773\n\t\t(typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||\n\t\t// Is firefox >= v31?\n\t\t// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages\n\t\t(typeof navigator !== 'undefined' && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\\/(\\d+)/)) && parseInt(m[1], 10) >= 31) ||\n\t\t// Double check webkit in userAgent just in case we are in a worker\n\t\t(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\\/(\\d+)/));\n}\n\n/**\n * Colorize log arguments if enabled.\n *\n * @api public\n */\n\nfunction formatArgs(args) {\n\targs[0] = (this.useColors ? '%c' : '') +\n\t\tthis.namespace +\n\t\t(this.useColors ? ' %c' : ' ') +\n\t\targs[0] +\n\t\t(this.useColors ? '%c ' : ' ') +\n\t\t'+' + module.exports.humanize(this.diff);\n\n\tif (!this.useColors) {\n\t\treturn;\n\t}\n\n\tconst c = 'color: ' + this.color;\n\targs.splice(1, 0, c, 'color: inherit');\n\n\t// The final \"%c\" is somewhat tricky, because there could be other\n\t// arguments passed either before or after the %c, so we need to\n\t// figure out the correct index to insert the CSS into\n\tlet index = 0;\n\tlet lastC = 0;\n\targs[0].replace(/%[a-zA-Z%]/g, match => {\n\t\tif (match === '%%') {\n\t\t\treturn;\n\t\t}\n\t\tindex++;\n\t\tif (match === '%c') {\n\t\t\t// We only are interested in the *last* %c\n\t\t\t// (the user may have provided their own)\n\t\t\tlastC = index;\n\t\t}\n\t});\n\n\targs.splice(lastC, 0, c);\n}\n\n/**\n * Invokes `console.debug()` when available.\n * No-op when `console.debug` is not a \"function\".\n * If `console.debug` is not available, falls back\n * to `console.log`.\n *\n * @api public\n */\nexports.log = console.debug || console.log || (() => {});\n\n/**\n * Save `namespaces`.\n *\n * @param {String} namespaces\n * @api private\n */\nfunction save(namespaces) {\n\ttry {\n\t\tif (namespaces) {\n\t\t\texports.storage.setItem('debug', namespaces);\n\t\t} else {\n\t\t\texports.storage.removeItem('debug');\n\t\t}\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n}\n\n/**\n * Load `namespaces`.\n *\n * @return {String} returns the previously persisted debug modes\n * @api private\n */\nfunction load() {\n\tlet r;\n\ttry {\n\t\tr = exports.storage.getItem('debug');\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n\n\t// If debug isn't set in LS, and we're in Electron, try to load $DEBUG\n\tif (!r && typeof process !== 'undefined' && 'env' in process) {\n\t\tr = process.env.DEBUG;\n\t}\n\n\treturn r;\n}\n\n/**\n * Localstorage attempts to return the localstorage.\n *\n * This is necessary because safari throws\n * when a user disables cookies/localstorage\n * and you attempt to access it.\n *\n * @return {LocalStorage}\n * @api private\n */\n\nfunction localstorage() {\n\ttry {\n\t\t// TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context\n\t\t// The Browser also has localStorage in the global context.\n\t\treturn localStorage;\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n}\n\nmodule.exports = require('./common')(exports);\n\nconst {formatters} = module.exports;\n\n/**\n * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.\n */\n\nformatters.j = function (v) {\n\ttry {\n\t\treturn JSON.stringify(v);\n\t} catch (error) {\n\t\treturn '[UnexpectedJSONParseError]: ' + error.message;\n\t}\n};\n","'use strict';\n\nmodule.exports = (flag, argv = process.argv) => {\n\tconst prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--');\n\tconst position = argv.indexOf(prefix + flag);\n\tconst terminatorPosition = argv.indexOf('--');\n\treturn position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);\n};\n","'use strict';\nconst os = require('os');\nconst tty = require('tty');\nconst hasFlag = require('has-flag');\n\nconst {env} = process;\n\nlet forceColor;\nif (hasFlag('no-color') ||\n\thasFlag('no-colors') ||\n\thasFlag('color=false') ||\n\thasFlag('color=never')) {\n\tforceColor = 0;\n} else if (hasFlag('color') ||\n\thasFlag('colors') ||\n\thasFlag('color=true') ||\n\thasFlag('color=always')) {\n\tforceColor = 1;\n}\n\nif ('FORCE_COLOR' in env) {\n\tif (env.FORCE_COLOR === 'true') {\n\t\tforceColor = 1;\n\t} else if (env.FORCE_COLOR === 'false') {\n\t\tforceColor = 0;\n\t} else {\n\t\tforceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3);\n\t}\n}\n\nfunction translateLevel(level) {\n\tif (level === 0) {\n\t\treturn false;\n\t}\n\n\treturn {\n\t\tlevel,\n\t\thasBasic: true,\n\t\thas256: level >= 2,\n\t\thas16m: level >= 3\n\t};\n}\n\nfunction supportsColor(haveStream, streamIsTTY) {\n\tif (forceColor === 0) {\n\t\treturn 0;\n\t}\n\n\tif (hasFlag('color=16m') ||\n\t\thasFlag('color=full') ||\n\t\thasFlag('color=truecolor')) {\n\t\treturn 3;\n\t}\n\n\tif (hasFlag('color=256')) {\n\t\treturn 2;\n\t}\n\n\tif (haveStream && !streamIsTTY && forceColor === undefined) {\n\t\treturn 0;\n\t}\n\n\tconst min = forceColor || 0;\n\n\tif (env.TERM === 'dumb') {\n\t\treturn min;\n\t}\n\n\tif (process.platform === 'win32') {\n\t\t// Windows 10 build 10586 is the first Windows release that supports 256 colors.\n\t\t// Windows 10 build 14931 is the first release that supports 16m/TrueColor.\n\t\tconst osRelease = os.release().split('.');\n\t\tif (\n\t\t\tNumber(osRelease[0]) >= 10 &&\n\t\t\tNumber(osRelease[2]) >= 10586\n\t\t) {\n\t\t\treturn Number(osRelease[2]) >= 14931 ? 3 : 2;\n\t\t}\n\n\t\treturn 1;\n\t}\n\n\tif ('CI' in env) {\n\t\tif (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'GITHUB_ACTIONS', 'BUILDKITE'].some(sign => sign in env) || env.CI_NAME === 'codeship') {\n\t\t\treturn 1;\n\t\t}\n\n\t\treturn min;\n\t}\n\n\tif ('TEAMCITY_VERSION' in env) {\n\t\treturn /^(9\\.(0*[1-9]\\d*)\\.|\\d{2,}\\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;\n\t}\n\n\tif (env.COLORTERM === 'truecolor') {\n\t\treturn 3;\n\t}\n\n\tif ('TERM_PROGRAM' in env) {\n\t\tconst version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10);\n\n\t\tswitch (env.TERM_PROGRAM) {\n\t\t\tcase 'iTerm.app':\n\t\t\t\treturn version >= 3 ? 3 : 2;\n\t\t\tcase 'Apple_Terminal':\n\t\t\t\treturn 2;\n\t\t\t// No default\n\t\t}\n\t}\n\n\tif (/-256(color)?$/i.test(env.TERM)) {\n\t\treturn 2;\n\t}\n\n\tif (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {\n\t\treturn 1;\n\t}\n\n\tif ('COLORTERM' in env) {\n\t\treturn 1;\n\t}\n\n\treturn min;\n}\n\nfunction getSupportLevel(stream) {\n\tconst level = supportsColor(stream, stream && stream.isTTY);\n\treturn translateLevel(level);\n}\n\nmodule.exports = {\n\tsupportsColor: getSupportLevel,\n\tstdout: translateLevel(supportsColor(true, tty.isatty(1))),\n\tstderr: translateLevel(supportsColor(true, tty.isatty(2)))\n};\n","/**\n * Module dependencies.\n */\n\nconst tty = require('tty');\nconst util = require('util');\n\n/**\n * This is the Node.js implementation of `debug()`.\n */\n\nexports.init = init;\nexports.log = log;\nexports.formatArgs = formatArgs;\nexports.save = save;\nexports.load = load;\nexports.useColors = useColors;\nexports.destroy = util.deprecate(\n\t() => {},\n\t'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'\n);\n\n/**\n * Colors.\n */\n\nexports.colors = [6, 2, 3, 4, 5, 1];\n\ntry {\n\t// Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json)\n\t// eslint-disable-next-line import/no-extraneous-dependencies\n\tconst supportsColor = require('supports-color');\n\n\tif (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) {\n\t\texports.colors = [\n\t\t\t20,\n\t\t\t21,\n\t\t\t26,\n\t\t\t27,\n\t\t\t32,\n\t\t\t33,\n\t\t\t38,\n\t\t\t39,\n\t\t\t40,\n\t\t\t41,\n\t\t\t42,\n\t\t\t43,\n\t\t\t44,\n\t\t\t45,\n\t\t\t56,\n\t\t\t57,\n\t\t\t62,\n\t\t\t63,\n\t\t\t68,\n\t\t\t69,\n\t\t\t74,\n\t\t\t75,\n\t\t\t76,\n\t\t\t77,\n\t\t\t78,\n\t\t\t79,\n\t\t\t80,\n\t\t\t81,\n\t\t\t92,\n\t\t\t93,\n\t\t\t98,\n\t\t\t99,\n\t\t\t112,\n\t\t\t113,\n\t\t\t128,\n\t\t\t129,\n\t\t\t134,\n\t\t\t135,\n\t\t\t148,\n\t\t\t149,\n\t\t\t160,\n\t\t\t161,\n\t\t\t162,\n\t\t\t163,\n\t\t\t164,\n\t\t\t165,\n\t\t\t166,\n\t\t\t167,\n\t\t\t168,\n\t\t\t169,\n\t\t\t170,\n\t\t\t171,\n\t\t\t172,\n\t\t\t173,\n\t\t\t178,\n\t\t\t179,\n\t\t\t184,\n\t\t\t185,\n\t\t\t196,\n\t\t\t197,\n\t\t\t198,\n\t\t\t199,\n\t\t\t200,\n\t\t\t201,\n\t\t\t202,\n\t\t\t203,\n\t\t\t204,\n\t\t\t205,\n\t\t\t206,\n\t\t\t207,\n\t\t\t208,\n\t\t\t209,\n\t\t\t214,\n\t\t\t215,\n\t\t\t220,\n\t\t\t221\n\t\t];\n\t}\n} catch (error) {\n\t// Swallow - we only care if `supports-color` is available; it doesn't have to be.\n}\n\n/**\n * Build up the default `inspectOpts` object from the environment variables.\n *\n * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js\n */\n\nexports.inspectOpts = Object.keys(process.env).filter(key => {\n\treturn /^debug_/i.test(key);\n}).reduce((obj, key) => {\n\t// Camel-case\n\tconst prop = key\n\t\t.substring(6)\n\t\t.toLowerCase()\n\t\t.replace(/_([a-z])/g, (_, k) => {\n\t\t\treturn k.toUpperCase();\n\t\t});\n\n\t// Coerce string value into JS value\n\tlet val = process.env[key];\n\tif (/^(yes|on|true|enabled)$/i.test(val)) {\n\t\tval = true;\n\t} else if (/^(no|off|false|disabled)$/i.test(val)) {\n\t\tval = false;\n\t} else if (val === 'null') {\n\t\tval = null;\n\t} else {\n\t\tval = Number(val);\n\t}\n\n\tobj[prop] = val;\n\treturn obj;\n}, {});\n\n/**\n * Is stdout a TTY? Colored output is enabled when `true`.\n */\n\nfunction useColors() {\n\treturn 'colors' in exports.inspectOpts ?\n\t\tBoolean(exports.inspectOpts.colors) :\n\t\ttty.isatty(process.stderr.fd);\n}\n\n/**\n * Adds ANSI color escape codes if enabled.\n *\n * @api public\n */\n\nfunction formatArgs(args) {\n\tconst {namespace: name, useColors} = this;\n\n\tif (useColors) {\n\t\tconst c = this.color;\n\t\tconst colorCode = '\\u001B[3' + (c < 8 ? c : '8;5;' + c);\n\t\tconst prefix = ` ${colorCode};1m${name} \\u001B[0m`;\n\n\t\targs[0] = prefix + args[0].split('\\n').join('\\n' + prefix);\n\t\targs.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\\u001B[0m');\n\t} else {\n\t\targs[0] = getDate() + name + ' ' + args[0];\n\t}\n}\n\nfunction getDate() {\n\tif (exports.inspectOpts.hideDate) {\n\t\treturn '';\n\t}\n\treturn new Date().toISOString() + ' ';\n}\n\n/**\n * Invokes `util.formatWithOptions()` with the specified arguments and writes to stderr.\n */\n\nfunction log(...args) {\n\treturn process.stderr.write(util.formatWithOptions(exports.inspectOpts, ...args) + '\\n');\n}\n\n/**\n * Save `namespaces`.\n *\n * @param {String} namespaces\n * @api private\n */\nfunction save(namespaces) {\n\tif (namespaces) {\n\t\tprocess.env.DEBUG = namespaces;\n\t} else {\n\t\t// If you set a process.env field to null or undefined, it gets cast to the\n\t\t// string 'null' or 'undefined'. Just delete instead.\n\t\tdelete process.env.DEBUG;\n\t}\n}\n\n/**\n * Load `namespaces`.\n *\n * @return {String} returns the previously persisted debug modes\n * @api private\n */\n\nfunction load() {\n\treturn process.env.DEBUG;\n}\n\n/**\n * Init logic for `debug` instances.\n *\n * Create a new `inspectOpts` object in case `useColors` is set\n * differently for a particular `debug` instance.\n */\n\nfunction init(debug) {\n\tdebug.inspectOpts = {};\n\n\tconst keys = Object.keys(exports.inspectOpts);\n\tfor (let i = 0; i < keys.length; i++) {\n\t\tdebug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];\n\t}\n}\n\nmodule.exports = require('./common')(exports);\n\nconst {formatters} = module.exports;\n\n/**\n * Map %o to `util.inspect()`, all on a single line.\n */\n\nformatters.o = function (v) {\n\tthis.inspectOpts.colors = this.useColors;\n\treturn util.inspect(v, this.inspectOpts)\n\t\t.split('\\n')\n\t\t.map(str => str.trim())\n\t\t.join(' ');\n};\n\n/**\n * Map %O to `util.inspect()`, allowing multiple lines if needed.\n */\n\nformatters.O = function (v) {\n\tthis.inspectOpts.colors = this.useColors;\n\treturn util.inspect(v, this.inspectOpts);\n};\n","/**\n * Detect Electron renderer / nwjs process, which is node, but we should\n * treat as a browser.\n */\n\nif (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) {\n\tmodule.exports = require('./browser.js');\n} else {\n\tmodule.exports = require('./node.js');\n}\n","var debug;\n\nmodule.exports = function () {\n if (!debug) {\n try {\n /* eslint global-require: off */\n debug = require(\"debug\")(\"follow-redirects\");\n }\n catch (error) { /* */ }\n if (typeof debug !== \"function\") {\n debug = function () { /* */ };\n }\n }\n debug.apply(null, arguments);\n};\n","var url = require(\"url\");\nvar URL = url.URL;\nvar http = require(\"http\");\nvar https = require(\"https\");\nvar Writable = require(\"stream\").Writable;\nvar assert = require(\"assert\");\nvar debug = require(\"./debug\");\n\n// Preventive platform detection\n// istanbul ignore next\n(function detectUnsupportedEnvironment() {\n var looksLikeNode = typeof process !== \"undefined\";\n var looksLikeBrowser = typeof window !== \"undefined\" && typeof document !== \"undefined\";\n var looksLikeV8 = isFunction(Error.captureStackTrace);\n if (!looksLikeNode && (looksLikeBrowser || !looksLikeV8)) {\n console.warn(\"The follow-redirects package should be excluded from browser builds.\");\n }\n}());\n\n// Whether to use the native URL object or the legacy url module\nvar useNativeURL = false;\ntry {\n assert(new URL(\"\"));\n}\ncatch (error) {\n useNativeURL = error.code === \"ERR_INVALID_URL\";\n}\n\n// URL fields to preserve in copy operations\nvar preservedUrlFields = [\n \"auth\",\n \"host\",\n \"hostname\",\n \"href\",\n \"path\",\n \"pathname\",\n \"port\",\n \"protocol\",\n \"query\",\n \"search\",\n \"hash\",\n];\n\n// Create handlers that pass events from native requests\nvar events = [\"abort\", \"aborted\", \"connect\", \"error\", \"socket\", \"timeout\"];\nvar eventHandlers = Object.create(null);\nevents.forEach(function (event) {\n eventHandlers[event] = function (arg1, arg2, arg3) {\n this._redirectable.emit(event, arg1, arg2, arg3);\n };\n});\n\n// Error types with codes\nvar InvalidUrlError = createErrorType(\n \"ERR_INVALID_URL\",\n \"Invalid URL\",\n TypeError\n);\nvar RedirectionError = createErrorType(\n \"ERR_FR_REDIRECTION_FAILURE\",\n \"Redirected request failed\"\n);\nvar TooManyRedirectsError = createErrorType(\n \"ERR_FR_TOO_MANY_REDIRECTS\",\n \"Maximum number of redirects exceeded\",\n RedirectionError\n);\nvar MaxBodyLengthExceededError = createErrorType(\n \"ERR_FR_MAX_BODY_LENGTH_EXCEEDED\",\n \"Request body larger than maxBodyLength limit\"\n);\nvar WriteAfterEndError = createErrorType(\n \"ERR_STREAM_WRITE_AFTER_END\",\n \"write after end\"\n);\n\n// istanbul ignore next\nvar destroy = Writable.prototype.destroy || noop;\n\n// An HTTP(S) request that can be redirected\nfunction RedirectableRequest(options, responseCallback) {\n // Initialize the request\n Writable.call(this);\n this._sanitizeOptions(options);\n this._options = options;\n this._ended = false;\n this._ending = false;\n this._redirectCount = 0;\n this._redirects = [];\n this._requestBodyLength = 0;\n this._requestBodyBuffers = [];\n\n // Attach a callback if passed\n if (responseCallback) {\n this.on(\"response\", responseCallback);\n }\n\n // React to responses of native requests\n var self = this;\n this._onNativeResponse = function (response) {\n try {\n self._processResponse(response);\n }\n catch (cause) {\n self.emit(\"error\", cause instanceof RedirectionError ?\n cause : new RedirectionError({ cause: cause }));\n }\n };\n\n // Perform the first request\n this._performRequest();\n}\nRedirectableRequest.prototype = Object.create(Writable.prototype);\n\nRedirectableRequest.prototype.abort = function () {\n destroyRequest(this._currentRequest);\n this._currentRequest.abort();\n this.emit(\"abort\");\n};\n\nRedirectableRequest.prototype.destroy = function (error) {\n destroyRequest(this._currentRequest, error);\n destroy.call(this, error);\n return this;\n};\n\n// Writes buffered data to the current native request\nRedirectableRequest.prototype.write = function (data, encoding, callback) {\n // Writing is not allowed if end has been called\n if (this._ending) {\n throw new WriteAfterEndError();\n }\n\n // Validate input and shift parameters if necessary\n if (!isString(data) && !isBuffer(data)) {\n throw new TypeError(\"data should be a string, Buffer or Uint8Array\");\n }\n if (isFunction(encoding)) {\n callback = encoding;\n encoding = null;\n }\n\n // Ignore empty buffers, since writing them doesn't invoke the callback\n // https://github.com/nodejs/node/issues/22066\n if (data.length === 0) {\n if (callback) {\n callback();\n }\n return;\n }\n // Only write when we don't exceed the maximum body length\n if (this._requestBodyLength + data.length <= this._options.maxBodyLength) {\n this._requestBodyLength += data.length;\n this._requestBodyBuffers.push({ data: data, encoding: encoding });\n this._currentRequest.write(data, encoding, callback);\n }\n // Error when we exceed the maximum body length\n else {\n this.emit(\"error\", new MaxBodyLengthExceededError());\n this.abort();\n }\n};\n\n// Ends the current native request\nRedirectableRequest.prototype.end = function (data, encoding, callback) {\n // Shift parameters if necessary\n if (isFunction(data)) {\n callback = data;\n data = encoding = null;\n }\n else if (isFunction(encoding)) {\n callback = encoding;\n encoding = null;\n }\n\n // Write data if needed and end\n if (!data) {\n this._ended = this._ending = true;\n this._currentRequest.end(null, null, callback);\n }\n else {\n var self = this;\n var currentRequest = this._currentRequest;\n this.write(data, encoding, function () {\n self._ended = true;\n currentRequest.end(null, null, callback);\n });\n this._ending = true;\n }\n};\n\n// Sets a header value on the current native request\nRedirectableRequest.prototype.setHeader = function (name, value) {\n this._options.headers[name] = value;\n this._currentRequest.setHeader(name, value);\n};\n\n// Clears a header value on the current native request\nRedirectableRequest.prototype.removeHeader = function (name) {\n delete this._options.headers[name];\n this._currentRequest.removeHeader(name);\n};\n\n// Global timeout for all underlying requests\nRedirectableRequest.prototype.setTimeout = function (msecs, callback) {\n var self = this;\n\n // Destroys the socket on timeout\n function destroyOnTimeout(socket) {\n socket.setTimeout(msecs);\n socket.removeListener(\"timeout\", socket.destroy);\n socket.addListener(\"timeout\", socket.destroy);\n }\n\n // Sets up a timer to trigger a timeout event\n function startTimer(socket) {\n if (self._timeout) {\n clearTimeout(self._timeout);\n }\n self._timeout = setTimeout(function () {\n self.emit(\"timeout\");\n clearTimer();\n }, msecs);\n destroyOnTimeout(socket);\n }\n\n // Stops a timeout from triggering\n function clearTimer() {\n // Clear the timeout\n if (self._timeout) {\n clearTimeout(self._timeout);\n self._timeout = null;\n }\n\n // Clean up all attached listeners\n self.removeListener(\"abort\", clearTimer);\n self.removeListener(\"error\", clearTimer);\n self.removeListener(\"response\", clearTimer);\n self.removeListener(\"close\", clearTimer);\n if (callback) {\n self.removeListener(\"timeout\", callback);\n }\n if (!self.socket) {\n self._currentRequest.removeListener(\"socket\", startTimer);\n }\n }\n\n // Attach callback if passed\n if (callback) {\n this.on(\"timeout\", callback);\n }\n\n // Start the timer if or when the socket is opened\n if (this.socket) {\n startTimer(this.socket);\n }\n else {\n this._currentRequest.once(\"socket\", startTimer);\n }\n\n // Clean up on events\n this.on(\"socket\", destroyOnTimeout);\n this.on(\"abort\", clearTimer);\n this.on(\"error\", clearTimer);\n this.on(\"response\", clearTimer);\n this.on(\"close\", clearTimer);\n\n return this;\n};\n\n// Proxy all other public ClientRequest methods\n[\n \"flushHeaders\", \"getHeader\",\n \"setNoDelay\", \"setSocketKeepAlive\",\n].forEach(function (method) {\n RedirectableRequest.prototype[method] = function (a, b) {\n return this._currentRequest[method](a, b);\n };\n});\n\n// Proxy all public ClientRequest properties\n[\"aborted\", \"connection\", \"socket\"].forEach(function (property) {\n Object.defineProperty(RedirectableRequest.prototype, property, {\n get: function () { return this._currentRequest[property]; },\n });\n});\n\nRedirectableRequest.prototype._sanitizeOptions = function (options) {\n // Ensure headers are always present\n if (!options.headers) {\n options.headers = {};\n }\n\n // Since http.request treats host as an alias of hostname,\n // but the url module interprets host as hostname plus port,\n // eliminate the host property to avoid confusion.\n if (options.host) {\n // Use hostname if set, because it has precedence\n if (!options.hostname) {\n options.hostname = options.host;\n }\n delete options.host;\n }\n\n // Complete the URL object when necessary\n if (!options.pathname && options.path) {\n var searchPos = options.path.indexOf(\"?\");\n if (searchPos < 0) {\n options.pathname = options.path;\n }\n else {\n options.pathname = options.path.substring(0, searchPos);\n options.search = options.path.substring(searchPos);\n }\n }\n};\n\n\n// Executes the next native request (initial or redirect)\nRedirectableRequest.prototype._performRequest = function () {\n // Load the native protocol\n var protocol = this._options.protocol;\n var nativeProtocol = this._options.nativeProtocols[protocol];\n if (!nativeProtocol) {\n throw new TypeError(\"Unsupported protocol \" + protocol);\n }\n\n // If specified, use the agent corresponding to the protocol\n // (HTTP and HTTPS use different types of agents)\n if (this._options.agents) {\n var scheme = protocol.slice(0, -1);\n this._options.agent = this._options.agents[scheme];\n }\n\n // Create the native request and set up its event handlers\n var request = this._currentRequest =\n nativeProtocol.request(this._options, this._onNativeResponse);\n request._redirectable = this;\n for (var event of events) {\n request.on(event, eventHandlers[event]);\n }\n\n // RFC7230§5.3.1: When making a request directly to an origin server, […]\n // a client MUST send only the absolute path […] as the request-target.\n this._currentUrl = /^\\//.test(this._options.path) ?\n url.format(this._options) :\n // When making a request to a proxy, […]\n // a client MUST send the target URI in absolute-form […].\n this._options.path;\n\n // End a redirected request\n // (The first request must be ended explicitly with RedirectableRequest#end)\n if (this._isRedirect) {\n // Write the request entity and end\n var i = 0;\n var self = this;\n var buffers = this._requestBodyBuffers;\n (function writeNext(error) {\n // Only write if this request has not been redirected yet\n // istanbul ignore else\n if (request === self._currentRequest) {\n // Report any write errors\n // istanbul ignore if\n if (error) {\n self.emit(\"error\", error);\n }\n // Write the next buffer if there are still left\n else if (i < buffers.length) {\n var buffer = buffers[i++];\n // istanbul ignore else\n if (!request.finished) {\n request.write(buffer.data, buffer.encoding, writeNext);\n }\n }\n // End the request if `end` has been called on us\n else if (self._ended) {\n request.end();\n }\n }\n }());\n }\n};\n\n// Processes a response from the current native request\nRedirectableRequest.prototype._processResponse = function (response) {\n // Store the redirected response\n var statusCode = response.statusCode;\n if (this._options.trackRedirects) {\n this._redirects.push({\n url: this._currentUrl,\n headers: response.headers,\n statusCode: statusCode,\n });\n }\n\n // RFC7231§6.4: The 3xx (Redirection) class of status code indicates\n // that further action needs to be taken by the user agent in order to\n // fulfill the request. If a Location header field is provided,\n // the user agent MAY automatically redirect its request to the URI\n // referenced by the Location field value,\n // even if the specific status code is not understood.\n\n // If the response is not a redirect; return it as-is\n var location = response.headers.location;\n if (!location || this._options.followRedirects === false ||\n statusCode < 300 || statusCode >= 400) {\n response.responseUrl = this._currentUrl;\n response.redirects = this._redirects;\n this.emit(\"response\", response);\n\n // Clean up\n this._requestBodyBuffers = [];\n return;\n }\n\n // The response is a redirect, so abort the current request\n destroyRequest(this._currentRequest);\n // Discard the remainder of the response to avoid waiting for data\n response.destroy();\n\n // RFC7231§6.4: A client SHOULD detect and intervene\n // in cyclical redirections (i.e., \"infinite\" redirection loops).\n if (++this._redirectCount > this._options.maxRedirects) {\n throw new TooManyRedirectsError();\n }\n\n // Store the request headers if applicable\n var requestHeaders;\n var beforeRedirect = this._options.beforeRedirect;\n if (beforeRedirect) {\n requestHeaders = Object.assign({\n // The Host header was set by nativeProtocol.request\n Host: response.req.getHeader(\"host\"),\n }, this._options.headers);\n }\n\n // RFC7231§6.4: Automatic redirection needs to done with\n // care for methods not known to be safe, […]\n // RFC7231§6.4.2–3: For historical reasons, a user agent MAY change\n // the request method from POST to GET for the subsequent request.\n var method = this._options.method;\n if ((statusCode === 301 || statusCode === 302) && this._options.method === \"POST\" ||\n // RFC7231§6.4.4: The 303 (See Other) status code indicates that\n // the server is redirecting the user agent to a different resource […]\n // A user agent can perform a retrieval request targeting that URI\n // (a GET or HEAD request if using HTTP) […]\n (statusCode === 303) && !/^(?:GET|HEAD)$/.test(this._options.method)) {\n this._options.method = \"GET\";\n // Drop a possible entity and headers related to it\n this._requestBodyBuffers = [];\n removeMatchingHeaders(/^content-/i, this._options.headers);\n }\n\n // Drop the Host header, as the redirect might lead to a different host\n var currentHostHeader = removeMatchingHeaders(/^host$/i, this._options.headers);\n\n // If the redirect is relative, carry over the host of the last request\n var currentUrlParts = parseUrl(this._currentUrl);\n var currentHost = currentHostHeader || currentUrlParts.host;\n var currentUrl = /^\\w+:/.test(location) ? this._currentUrl :\n url.format(Object.assign(currentUrlParts, { host: currentHost }));\n\n // Create the redirected request\n var redirectUrl = resolveUrl(location, currentUrl);\n debug(\"redirecting to\", redirectUrl.href);\n this._isRedirect = true;\n spreadUrlObject(redirectUrl, this._options);\n\n // Drop confidential headers when redirecting to a less secure protocol\n // or to a different domain that is not a superdomain\n if (redirectUrl.protocol !== currentUrlParts.protocol &&\n redirectUrl.protocol !== \"https:\" ||\n redirectUrl.host !== currentHost &&\n !isSubdomain(redirectUrl.host, currentHost)) {\n removeMatchingHeaders(/^(?:(?:proxy-)?authorization|cookie)$/i, this._options.headers);\n }\n\n // Evaluate the beforeRedirect callback\n if (isFunction(beforeRedirect)) {\n var responseDetails = {\n headers: response.headers,\n statusCode: statusCode,\n };\n var requestDetails = {\n url: currentUrl,\n method: method,\n headers: requestHeaders,\n };\n beforeRedirect(this._options, responseDetails, requestDetails);\n this._sanitizeOptions(this._options);\n }\n\n // Perform the redirected request\n this._performRequest();\n};\n\n// Wraps the key/value object of protocols with redirect functionality\nfunction wrap(protocols) {\n // Default settings\n var exports = {\n maxRedirects: 21,\n maxBodyLength: 10 * 1024 * 1024,\n };\n\n // Wrap each protocol\n var nativeProtocols = {};\n Object.keys(protocols).forEach(function (scheme) {\n var protocol = scheme + \":\";\n var nativeProtocol = nativeProtocols[protocol] = protocols[scheme];\n var wrappedProtocol = exports[scheme] = Object.create(nativeProtocol);\n\n // Executes a request, following redirects\n function request(input, options, callback) {\n // Parse parameters, ensuring that input is an object\n if (isURL(input)) {\n input = spreadUrlObject(input);\n }\n else if (isString(input)) {\n input = spreadUrlObject(parseUrl(input));\n }\n else {\n callback = options;\n options = validateUrl(input);\n input = { protocol: protocol };\n }\n if (isFunction(options)) {\n callback = options;\n options = null;\n }\n\n // Set defaults\n options = Object.assign({\n maxRedirects: exports.maxRedirects,\n maxBodyLength: exports.maxBodyLength,\n }, input, options);\n options.nativeProtocols = nativeProtocols;\n if (!isString(options.host) && !isString(options.hostname)) {\n options.hostname = \"::1\";\n }\n\n assert.equal(options.protocol, protocol, \"protocol mismatch\");\n debug(\"options\", options);\n return new RedirectableRequest(options, callback);\n }\n\n // Executes a GET request, following redirects\n function get(input, options, callback) {\n var wrappedRequest = wrappedProtocol.request(input, options, callback);\n wrappedRequest.end();\n return wrappedRequest;\n }\n\n // Expose the properties on the wrapped protocol\n Object.defineProperties(wrappedProtocol, {\n request: { value: request, configurable: true, enumerable: true, writable: true },\n get: { value: get, configurable: true, enumerable: true, writable: true },\n });\n });\n return exports;\n}\n\nfunction noop() { /* empty */ }\n\nfunction parseUrl(input) {\n var parsed;\n // istanbul ignore else\n if (useNativeURL) {\n parsed = new URL(input);\n }\n else {\n // Ensure the URL is valid and absolute\n parsed = validateUrl(url.parse(input));\n if (!isString(parsed.protocol)) {\n throw new InvalidUrlError({ input });\n }\n }\n return parsed;\n}\n\nfunction resolveUrl(relative, base) {\n // istanbul ignore next\n return useNativeURL ? new URL(relative, base) : parseUrl(url.resolve(base, relative));\n}\n\nfunction validateUrl(input) {\n if (/^\\[/.test(input.hostname) && !/^\\[[:0-9a-f]+\\]$/i.test(input.hostname)) {\n throw new InvalidUrlError({ input: input.href || input });\n }\n if (/^\\[/.test(input.host) && !/^\\[[:0-9a-f]+\\](:\\d+)?$/i.test(input.host)) {\n throw new InvalidUrlError({ input: input.href || input });\n }\n return input;\n}\n\nfunction spreadUrlObject(urlObject, target) {\n var spread = target || {};\n for (var key of preservedUrlFields) {\n spread[key] = urlObject[key];\n }\n\n // Fix IPv6 hostname\n if (spread.hostname.startsWith(\"[\")) {\n spread.hostname = spread.hostname.slice(1, -1);\n }\n // Ensure port is a number\n if (spread.port !== \"\") {\n spread.port = Number(spread.port);\n }\n // Concatenate path\n spread.path = spread.search ? spread.pathname + spread.search : spread.pathname;\n\n return spread;\n}\n\nfunction removeMatchingHeaders(regex, headers) {\n var lastValue;\n for (var header in headers) {\n if (regex.test(header)) {\n lastValue = headers[header];\n delete headers[header];\n }\n }\n return (lastValue === null || typeof lastValue === \"undefined\") ?\n undefined : String(lastValue).trim();\n}\n\nfunction createErrorType(code, message, baseClass) {\n // Create constructor\n function CustomError(properties) {\n // istanbul ignore else\n if (isFunction(Error.captureStackTrace)) {\n Error.captureStackTrace(this, this.constructor);\n }\n Object.assign(this, properties || {});\n this.code = code;\n this.message = this.cause ? message + \": \" + this.cause.message : message;\n }\n\n // Attach constructor and set default properties\n CustomError.prototype = new (baseClass || Error)();\n Object.defineProperties(CustomError.prototype, {\n constructor: {\n value: CustomError,\n enumerable: false,\n },\n name: {\n value: \"Error [\" + code + \"]\",\n enumerable: false,\n },\n });\n return CustomError;\n}\n\nfunction destroyRequest(request, error) {\n for (var event of events) {\n request.removeListener(event, eventHandlers[event]);\n }\n request.on(\"error\", noop);\n request.destroy(error);\n}\n\nfunction isSubdomain(subdomain, domain) {\n assert(isString(subdomain) && isString(domain));\n var dot = subdomain.length - domain.length - 1;\n return dot > 0 && subdomain[dot] === \".\" && subdomain.endsWith(domain);\n}\n\nfunction isString(value) {\n return typeof value === \"string\" || value instanceof String;\n}\n\nfunction isFunction(value) {\n return typeof value === \"function\";\n}\n\nfunction isBuffer(value) {\n return typeof value === \"object\" && (\"length\" in value);\n}\n\nfunction isURL(value) {\n return URL && value instanceof URL;\n}\n\n// Exports\nmodule.exports = wrap({ http: http, https: https });\nmodule.exports.wrap = wrap;\n","'use strict';\n\nif (typeof process === 'undefined' ||\n !process.version ||\n process.version.indexOf('v0.') === 0 ||\n process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {\n module.exports = { nextTick: nextTick };\n} else {\n module.exports = process\n}\n\nfunction nextTick(fn, arg1, arg2, arg3) {\n if (typeof fn !== 'function') {\n throw new TypeError('\"callback\" argument must be a function');\n }\n var len = arguments.length;\n var args, i;\n switch (len) {\n case 0:\n case 1:\n return process.nextTick(fn);\n case 2:\n return process.nextTick(function afterTickOne() {\n fn.call(null, arg1);\n });\n case 3:\n return process.nextTick(function afterTickTwo() {\n fn.call(null, arg1, arg2);\n });\n case 4:\n return process.nextTick(function afterTickThree() {\n fn.call(null, arg1, arg2, arg3);\n });\n default:\n args = new Array(len - 1);\n i = 0;\n while (i < args.length) {\n args[i++] = arguments[i];\n }\n return process.nextTick(function afterTick() {\n fn.apply(null, args);\n });\n }\n}\n\n","var toString = {}.toString;\n\nmodule.exports = Array.isArray || function (arr) {\n return toString.call(arr) == '[object Array]';\n};\n","module.exports = require('stream');\n","/* eslint-disable node/no-deprecated-api */\nvar buffer = require('buffer')\nvar Buffer = buffer.Buffer\n\n// alternative to using Object.keys for old browsers\nfunction copyProps (src, dst) {\n for (var key in src) {\n dst[key] = src[key]\n }\n}\nif (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {\n module.exports = buffer\n} else {\n // Copy properties from require('buffer')\n copyProps(buffer, exports)\n exports.Buffer = SafeBuffer\n}\n\nfunction SafeBuffer (arg, encodingOrOffset, length) {\n return Buffer(arg, encodingOrOffset, length)\n}\n\n// Copy static methods from Buffer\ncopyProps(Buffer, SafeBuffer)\n\nSafeBuffer.from = function (arg, encodingOrOffset, length) {\n if (typeof arg === 'number') {\n throw new TypeError('Argument must not be a number')\n }\n return Buffer(arg, encodingOrOffset, length)\n}\n\nSafeBuffer.alloc = function (size, fill, encoding) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n var buf = Buffer(size)\n if (fill !== undefined) {\n if (typeof encoding === 'string') {\n buf.fill(fill, encoding)\n } else {\n buf.fill(fill)\n }\n } else {\n buf.fill(0)\n }\n return buf\n}\n\nSafeBuffer.allocUnsafe = function (size) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n return Buffer(size)\n}\n\nSafeBuffer.allocUnsafeSlow = function (size) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n return buffer.SlowBuffer(size)\n}\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// NOTE: These type checking functions intentionally don't use `instanceof`\n// because it is fragile and can be easily faked with `Object.create()`.\n\nfunction isArray(arg) {\n if (Array.isArray) {\n return Array.isArray(arg);\n }\n return objectToString(arg) === '[object Array]';\n}\nexports.isArray = isArray;\n\nfunction isBoolean(arg) {\n return typeof arg === 'boolean';\n}\nexports.isBoolean = isBoolean;\n\nfunction isNull(arg) {\n return arg === null;\n}\nexports.isNull = isNull;\n\nfunction isNullOrUndefined(arg) {\n return arg == null;\n}\nexports.isNullOrUndefined = isNullOrUndefined;\n\nfunction isNumber(arg) {\n return typeof arg === 'number';\n}\nexports.isNumber = isNumber;\n\nfunction isString(arg) {\n return typeof arg === 'string';\n}\nexports.isString = isString;\n\nfunction isSymbol(arg) {\n return typeof arg === 'symbol';\n}\nexports.isSymbol = isSymbol;\n\nfunction isUndefined(arg) {\n return arg === void 0;\n}\nexports.isUndefined = isUndefined;\n\nfunction isRegExp(re) {\n return objectToString(re) === '[object RegExp]';\n}\nexports.isRegExp = isRegExp;\n\nfunction isObject(arg) {\n return typeof arg === 'object' && arg !== null;\n}\nexports.isObject = isObject;\n\nfunction isDate(d) {\n return objectToString(d) === '[object Date]';\n}\nexports.isDate = isDate;\n\nfunction isError(e) {\n return (objectToString(e) === '[object Error]' || e instanceof Error);\n}\nexports.isError = isError;\n\nfunction isFunction(arg) {\n return typeof arg === 'function';\n}\nexports.isFunction = isFunction;\n\nfunction isPrimitive(arg) {\n return arg === null ||\n typeof arg === 'boolean' ||\n typeof arg === 'number' ||\n typeof arg === 'string' ||\n typeof arg === 'symbol' || // ES6 symbol\n typeof arg === 'undefined';\n}\nexports.isPrimitive = isPrimitive;\n\nexports.isBuffer = require('buffer').Buffer.isBuffer;\n\nfunction objectToString(o) {\n return Object.prototype.toString.call(o);\n}\n","if (typeof Object.create === 'function') {\n // implementation from standard node.js 'util' module\n module.exports = function inherits(ctor, superCtor) {\n if (superCtor) {\n ctor.super_ = superCtor\n ctor.prototype = Object.create(superCtor.prototype, {\n constructor: {\n value: ctor,\n enumerable: false,\n writable: true,\n configurable: true\n }\n })\n }\n };\n} else {\n // old school shim for old browsers\n module.exports = function inherits(ctor, superCtor) {\n if (superCtor) {\n ctor.super_ = superCtor\n var TempCtor = function () {}\n TempCtor.prototype = superCtor.prototype\n ctor.prototype = new TempCtor()\n ctor.prototype.constructor = ctor\n }\n }\n}\n","try {\n var util = require('util');\n /* istanbul ignore next */\n if (typeof util.inherits !== 'function') throw '';\n module.exports = util.inherits;\n} catch (e) {\n /* istanbul ignore next */\n module.exports = require('./inherits_browser.js');\n}\n","'use strict';\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nvar Buffer = require('safe-buffer').Buffer;\nvar util = require('util');\n\nfunction copyBuffer(src, target, offset) {\n src.copy(target, offset);\n}\n\nmodule.exports = function () {\n function BufferList() {\n _classCallCheck(this, BufferList);\n\n this.head = null;\n this.tail = null;\n this.length = 0;\n }\n\n BufferList.prototype.push = function push(v) {\n var entry = { data: v, next: null };\n if (this.length > 0) this.tail.next = entry;else this.head = entry;\n this.tail = entry;\n ++this.length;\n };\n\n BufferList.prototype.unshift = function unshift(v) {\n var entry = { data: v, next: this.head };\n if (this.length === 0) this.tail = entry;\n this.head = entry;\n ++this.length;\n };\n\n BufferList.prototype.shift = function shift() {\n if (this.length === 0) return;\n var ret = this.head.data;\n if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;\n --this.length;\n return ret;\n };\n\n BufferList.prototype.clear = function clear() {\n this.head = this.tail = null;\n this.length = 0;\n };\n\n BufferList.prototype.join = function join(s) {\n if (this.length === 0) return '';\n var p = this.head;\n var ret = '' + p.data;\n while (p = p.next) {\n ret += s + p.data;\n }return ret;\n };\n\n BufferList.prototype.concat = function concat(n) {\n if (this.length === 0) return Buffer.alloc(0);\n var ret = Buffer.allocUnsafe(n >>> 0);\n var p = this.head;\n var i = 0;\n while (p) {\n copyBuffer(p.data, ret, i);\n i += p.data.length;\n p = p.next;\n }\n return ret;\n };\n\n return BufferList;\n}();\n\nif (util && util.inspect && util.inspect.custom) {\n module.exports.prototype[util.inspect.custom] = function () {\n var obj = util.inspect({ length: this.length });\n return this.constructor.name + ' ' + obj;\n };\n}","'use strict';\n\n/*<replacement>*/\n\nvar pna = require('process-nextick-args');\n/*</replacement>*/\n\n// undocumented cb() API, needed for core, not for public API\nfunction destroy(err, cb) {\n var _this = this;\n\n var readableDestroyed = this._readableState && this._readableState.destroyed;\n var writableDestroyed = this._writableState && this._writableState.destroyed;\n\n if (readableDestroyed || writableDestroyed) {\n if (cb) {\n cb(err);\n } else if (err) {\n if (!this._writableState) {\n pna.nextTick(emitErrorNT, this, err);\n } else if (!this._writableState.errorEmitted) {\n this._writableState.errorEmitted = true;\n pna.nextTick(emitErrorNT, this, err);\n }\n }\n\n return this;\n }\n\n // we set destroyed to true before firing error callbacks in order\n // to make it re-entrance safe in case destroy() is called within callbacks\n\n if (this._readableState) {\n this._readableState.destroyed = true;\n }\n\n // if this is a duplex stream mark the writable part as destroyed as well\n if (this._writableState) {\n this._writableState.destroyed = true;\n }\n\n this._destroy(err || null, function (err) {\n if (!cb && err) {\n if (!_this._writableState) {\n pna.nextTick(emitErrorNT, _this, err);\n } else if (!_this._writableState.errorEmitted) {\n _this._writableState.errorEmitted = true;\n pna.nextTick(emitErrorNT, _this, err);\n }\n } else if (cb) {\n cb(err);\n }\n });\n\n return this;\n}\n\nfunction undestroy() {\n if (this._readableState) {\n this._readableState.destroyed = false;\n this._readableState.reading = false;\n this._readableState.ended = false;\n this._readableState.endEmitted = false;\n }\n\n if (this._writableState) {\n this._writableState.destroyed = false;\n this._writableState.ended = false;\n this._writableState.ending = false;\n this._writableState.finalCalled = false;\n this._writableState.prefinished = false;\n this._writableState.finished = false;\n this._writableState.errorEmitted = false;\n }\n}\n\nfunction emitErrorNT(self, err) {\n self.emit('error', err);\n}\n\nmodule.exports = {\n destroy: destroy,\n undestroy: undestroy\n};","\n/**\n * For Node.js, simply re-export the core `util.deprecate` function.\n */\n\nmodule.exports = require('util').deprecate;\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// A bit simpler than readable streams.\n// Implement an async ._write(chunk, encoding, cb), and it'll handle all\n// the drain event emission and buffering.\n\n'use strict';\n\n/*<replacement>*/\n\nvar pna = require('process-nextick-args');\n/*</replacement>*/\n\nmodule.exports = Writable;\n\n/* <replacement> */\nfunction WriteReq(chunk, encoding, cb) {\n this.chunk = chunk;\n this.encoding = encoding;\n this.callback = cb;\n this.next = null;\n}\n\n// It seems a linked list but it is not\n// there will be only 2 of these for each stream\nfunction CorkedRequest(state) {\n var _this = this;\n\n this.next = null;\n this.entry = null;\n this.finish = function () {\n onCorkedFinish(_this, state);\n };\n}\n/* </replacement> */\n\n/*<replacement>*/\nvar asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick;\n/*</replacement>*/\n\n/*<replacement>*/\nvar Duplex;\n/*</replacement>*/\n\nWritable.WritableState = WritableState;\n\n/*<replacement>*/\nvar util = Object.create(require('core-util-is'));\nutil.inherits = require('inherits');\n/*</replacement>*/\n\n/*<replacement>*/\nvar internalUtil = {\n deprecate: require('util-deprecate')\n};\n/*</replacement>*/\n\n/*<replacement>*/\nvar Stream = require('./internal/streams/stream');\n/*</replacement>*/\n\n/*<replacement>*/\n\nvar Buffer = require('safe-buffer').Buffer;\nvar OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {};\nfunction _uint8ArrayToBuffer(chunk) {\n return Buffer.from(chunk);\n}\nfunction _isUint8Array(obj) {\n return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;\n}\n\n/*</replacement>*/\n\nvar destroyImpl = require('./internal/streams/destroy');\n\nutil.inherits(Writable, Stream);\n\nfunction nop() {}\n\nfunction WritableState(options, stream) {\n Duplex = Duplex || require('./_stream_duplex');\n\n options = options || {};\n\n // Duplex streams are both readable and writable, but share\n // the same options object.\n // However, some cases require setting options to different\n // values for the readable and the writable sides of the duplex stream.\n // These options can be provided separately as readableXXX and writableXXX.\n var isDuplex = stream instanceof Duplex;\n\n // object stream flag to indicate whether or not this stream\n // contains buffers or objects.\n this.objectMode = !!options.objectMode;\n\n if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode;\n\n // the point at which write() starts returning false\n // Note: 0 is a valid value, means that we always return false if\n // the entire buffer is not flushed immediately on write()\n var hwm = options.highWaterMark;\n var writableHwm = options.writableHighWaterMark;\n var defaultHwm = this.objectMode ? 16 : 16 * 1024;\n\n if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm;\n\n // cast to ints.\n this.highWaterMark = Math.floor(this.highWaterMark);\n\n // if _final has been called\n this.finalCalled = false;\n\n // drain event flag.\n this.needDrain = false;\n // at the start of calling end()\n this.ending = false;\n // when end() has been called, and returned\n this.ended = false;\n // when 'finish' is emitted\n this.finished = false;\n\n // has it been destroyed\n this.destroyed = false;\n\n // should we decode strings into buffers before passing to _write?\n // this is here so that some node-core streams can optimize string\n // handling at a lower level.\n var noDecode = options.decodeStrings === false;\n this.decodeStrings = !noDecode;\n\n // Crypto is kind of old and crusty. Historically, its default string\n // encoding is 'binary' so we have to make this configurable.\n // Everything else in the universe uses 'utf8', though.\n this.defaultEncoding = options.defaultEncoding || 'utf8';\n\n // not an actual buffer we keep track of, but a measurement\n // of how much we're waiting to get pushed to some underlying\n // socket or file.\n this.length = 0;\n\n // a flag to see when we're in the middle of a write.\n this.writing = false;\n\n // when true all writes will be buffered until .uncork() call\n this.corked = 0;\n\n // a flag to be able to tell if the onwrite cb is called immediately,\n // or on a later tick. We set this to true at first, because any\n // actions that shouldn't happen until \"later\" should generally also\n // not happen before the first write call.\n this.sync = true;\n\n // a flag to know if we're processing previously buffered items, which\n // may call the _write() callback in the same tick, so that we don't\n // end up in an overlapped onwrite situation.\n this.bufferProcessing = false;\n\n // the callback that's passed to _write(chunk,cb)\n this.onwrite = function (er) {\n onwrite(stream, er);\n };\n\n // the callback that the user supplies to write(chunk,encoding,cb)\n this.writecb = null;\n\n // the amount that is being written when _write is called.\n this.writelen = 0;\n\n this.bufferedRequest = null;\n this.lastBufferedRequest = null;\n\n // number of pending user-supplied write callbacks\n // this must be 0 before 'finish' can be emitted\n this.pendingcb = 0;\n\n // emit prefinish if the only thing we're waiting for is _write cbs\n // This is relevant for synchronous Transform streams\n this.prefinished = false;\n\n // True if the error was already emitted and should not be thrown again\n this.errorEmitted = false;\n\n // count buffered requests\n this.bufferedRequestCount = 0;\n\n // allocate the first CorkedRequest, there is always\n // one allocated and free to use, and we maintain at most two\n this.corkedRequestsFree = new CorkedRequest(this);\n}\n\nWritableState.prototype.getBuffer = function getBuffer() {\n var current = this.bufferedRequest;\n var out = [];\n while (current) {\n out.push(current);\n current = current.next;\n }\n return out;\n};\n\n(function () {\n try {\n Object.defineProperty(WritableState.prototype, 'buffer', {\n get: internalUtil.deprecate(function () {\n return this.getBuffer();\n }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')\n });\n } catch (_) {}\n})();\n\n// Test _writableState for inheritance to account for Duplex streams,\n// whose prototype chain only points to Readable.\nvar realHasInstance;\nif (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {\n realHasInstance = Function.prototype[Symbol.hasInstance];\n Object.defineProperty(Writable, Symbol.hasInstance, {\n value: function (object) {\n if (realHasInstance.call(this, object)) return true;\n if (this !== Writable) return false;\n\n return object && object._writableState instanceof WritableState;\n }\n });\n} else {\n realHasInstance = function (object) {\n return object instanceof this;\n };\n}\n\nfunction Writable(options) {\n Duplex = Duplex || require('./_stream_duplex');\n\n // Writable ctor is applied to Duplexes, too.\n // `realHasInstance` is necessary because using plain `instanceof`\n // would return false, as no `_writableState` property is attached.\n\n // Trying to use the custom `instanceof` for Writable here will also break the\n // Node.js LazyTransform implementation, which has a non-trivial getter for\n // `_writableState` that would lead to infinite recursion.\n if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {\n return new Writable(options);\n }\n\n this._writableState = new WritableState(options, this);\n\n // legacy.\n this.writable = true;\n\n if (options) {\n if (typeof options.write === 'function') this._write = options.write;\n\n if (typeof options.writev === 'function') this._writev = options.writev;\n\n if (typeof options.destroy === 'function') this._destroy = options.destroy;\n\n if (typeof options.final === 'function') this._final = options.final;\n }\n\n Stream.call(this);\n}\n\n// Otherwise people can pipe Writable streams, which is just wrong.\nWritable.prototype.pipe = function () {\n this.emit('error', new Error('Cannot pipe, not readable'));\n};\n\nfunction writeAfterEnd(stream, cb) {\n var er = new Error('write after end');\n // TODO: defer error events consistently everywhere, not just the cb\n stream.emit('error', er);\n pna.nextTick(cb, er);\n}\n\n// Checks that a user-supplied chunk is valid, especially for the particular\n// mode the stream is in. Currently this means that `null` is never accepted\n// and undefined/non-string values are only allowed in object mode.\nfunction validChunk(stream, state, chunk, cb) {\n var valid = true;\n var er = false;\n\n if (chunk === null) {\n er = new TypeError('May not write null values to stream');\n } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {\n er = new TypeError('Invalid non-string/buffer chunk');\n }\n if (er) {\n stream.emit('error', er);\n pna.nextTick(cb, er);\n valid = false;\n }\n return valid;\n}\n\nWritable.prototype.write = function (chunk, encoding, cb) {\n var state = this._writableState;\n var ret = false;\n var isBuf = !state.objectMode && _isUint8Array(chunk);\n\n if (isBuf && !Buffer.isBuffer(chunk)) {\n chunk = _uint8ArrayToBuffer(chunk);\n }\n\n if (typeof encoding === 'function') {\n cb = encoding;\n encoding = null;\n }\n\n if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;\n\n if (typeof cb !== 'function') cb = nop;\n\n if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {\n state.pendingcb++;\n ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);\n }\n\n return ret;\n};\n\nWritable.prototype.cork = function () {\n var state = this._writableState;\n\n state.corked++;\n};\n\nWritable.prototype.uncork = function () {\n var state = this._writableState;\n\n if (state.corked) {\n state.corked--;\n\n if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);\n }\n};\n\nWritable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {\n // node::ParseEncoding() requires lower case.\n if (typeof encoding === 'string') encoding = encoding.toLowerCase();\n if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding);\n this._writableState.defaultEncoding = encoding;\n return this;\n};\n\nfunction decodeChunk(state, chunk, encoding) {\n if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {\n chunk = Buffer.from(chunk, encoding);\n }\n return chunk;\n}\n\nObject.defineProperty(Writable.prototype, 'writableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function () {\n return this._writableState.highWaterMark;\n }\n});\n\n// if we're already writing something, then just put this\n// in the queue, and wait our turn. Otherwise, call _write\n// If we return false, then we need a drain event, so set that flag.\nfunction writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {\n if (!isBuf) {\n var newChunk = decodeChunk(state, chunk, encoding);\n if (chunk !== newChunk) {\n isBuf = true;\n encoding = 'buffer';\n chunk = newChunk;\n }\n }\n var len = state.objectMode ? 1 : chunk.length;\n\n state.length += len;\n\n var ret = state.length < state.highWaterMark;\n // we must ensure that previous needDrain will not be reset to false.\n if (!ret) state.needDrain = true;\n\n if (state.writing || state.corked) {\n var last = state.lastBufferedRequest;\n state.lastBufferedRequest = {\n chunk: chunk,\n encoding: encoding,\n isBuf: isBuf,\n callback: cb,\n next: null\n };\n if (last) {\n last.next = state.lastBufferedRequest;\n } else {\n state.bufferedRequest = state.lastBufferedRequest;\n }\n state.bufferedRequestCount += 1;\n } else {\n doWrite(stream, state, false, len, chunk, encoding, cb);\n }\n\n return ret;\n}\n\nfunction doWrite(stream, state, writev, len, chunk, encoding, cb) {\n state.writelen = len;\n state.writecb = cb;\n state.writing = true;\n state.sync = true;\n if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);\n state.sync = false;\n}\n\nfunction onwriteError(stream, state, sync, er, cb) {\n --state.pendingcb;\n\n if (sync) {\n // defer the callback if we are being called synchronously\n // to avoid piling up things on the stack\n pna.nextTick(cb, er);\n // this can emit finish, and it will always happen\n // after error\n pna.nextTick(finishMaybe, stream, state);\n stream._writableState.errorEmitted = true;\n stream.emit('error', er);\n } else {\n // the caller expect this to happen before if\n // it is async\n cb(er);\n stream._writableState.errorEmitted = true;\n stream.emit('error', er);\n // this can emit finish, but finish must\n // always follow error\n finishMaybe(stream, state);\n }\n}\n\nfunction onwriteStateUpdate(state) {\n state.writing = false;\n state.writecb = null;\n state.length -= state.writelen;\n state.writelen = 0;\n}\n\nfunction onwrite(stream, er) {\n var state = stream._writableState;\n var sync = state.sync;\n var cb = state.writecb;\n\n onwriteStateUpdate(state);\n\n if (er) onwriteError(stream, state, sync, er, cb);else {\n // Check if we're actually ready to finish, but don't emit yet\n var finished = needFinish(state);\n\n if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {\n clearBuffer(stream, state);\n }\n\n if (sync) {\n /*<replacement>*/\n asyncWrite(afterWrite, stream, state, finished, cb);\n /*</replacement>*/\n } else {\n afterWrite(stream, state, finished, cb);\n }\n }\n}\n\nfunction afterWrite(stream, state, finished, cb) {\n if (!finished) onwriteDrain(stream, state);\n state.pendingcb--;\n cb();\n finishMaybe(stream, state);\n}\n\n// Must force callback to be called on nextTick, so that we don't\n// emit 'drain' before the write() consumer gets the 'false' return\n// value, and has a chance to attach a 'drain' listener.\nfunction onwriteDrain(stream, state) {\n if (state.length === 0 && state.needDrain) {\n state.needDrain = false;\n stream.emit('drain');\n }\n}\n\n// if there's something in the buffer waiting, then process it\nfunction clearBuffer(stream, state) {\n state.bufferProcessing = true;\n var entry = state.bufferedRequest;\n\n if (stream._writev && entry && entry.next) {\n // Fast case, write everything using _writev()\n var l = state.bufferedRequestCount;\n var buffer = new Array(l);\n var holder = state.corkedRequestsFree;\n holder.entry = entry;\n\n var count = 0;\n var allBuffers = true;\n while (entry) {\n buffer[count] = entry;\n if (!entry.isBuf) allBuffers = false;\n entry = entry.next;\n count += 1;\n }\n buffer.allBuffers = allBuffers;\n\n doWrite(stream, state, true, state.length, buffer, '', holder.finish);\n\n // doWrite is almost always async, defer these to save a bit of time\n // as the hot path ends with doWrite\n state.pendingcb++;\n state.lastBufferedRequest = null;\n if (holder.next) {\n state.corkedRequestsFree = holder.next;\n holder.next = null;\n } else {\n state.corkedRequestsFree = new CorkedRequest(state);\n }\n state.bufferedRequestCount = 0;\n } else {\n // Slow case, write chunks one-by-one\n while (entry) {\n var chunk = entry.chunk;\n var encoding = entry.encoding;\n var cb = entry.callback;\n var len = state.objectMode ? 1 : chunk.length;\n\n doWrite(stream, state, false, len, chunk, encoding, cb);\n entry = entry.next;\n state.bufferedRequestCount--;\n // if we didn't call the onwrite immediately, then\n // it means that we need to wait until it does.\n // also, that means that the chunk and cb are currently\n // being processed, so move the buffer counter past them.\n if (state.writing) {\n break;\n }\n }\n\n if (entry === null) state.lastBufferedRequest = null;\n }\n\n state.bufferedRequest = entry;\n state.bufferProcessing = false;\n}\n\nWritable.prototype._write = function (chunk, encoding, cb) {\n cb(new Error('_write() is not implemented'));\n};\n\nWritable.prototype._writev = null;\n\nWritable.prototype.end = function (chunk, encoding, cb) {\n var state = this._writableState;\n\n if (typeof chunk === 'function') {\n cb = chunk;\n chunk = null;\n encoding = null;\n } else if (typeof encoding === 'function') {\n cb = encoding;\n encoding = null;\n }\n\n if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);\n\n // .end() fully uncorks\n if (state.corked) {\n state.corked = 1;\n this.uncork();\n }\n\n // ignore unnecessary end() calls.\n if (!state.ending) endWritable(this, state, cb);\n};\n\nfunction needFinish(state) {\n return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;\n}\nfunction callFinal(stream, state) {\n stream._final(function (err) {\n state.pendingcb--;\n if (err) {\n stream.emit('error', err);\n }\n state.prefinished = true;\n stream.emit('prefinish');\n finishMaybe(stream, state);\n });\n}\nfunction prefinish(stream, state) {\n if (!state.prefinished && !state.finalCalled) {\n if (typeof stream._final === 'function') {\n state.pendingcb++;\n state.finalCalled = true;\n pna.nextTick(callFinal, stream, state);\n } else {\n state.prefinished = true;\n stream.emit('prefinish');\n }\n }\n}\n\nfunction finishMaybe(stream, state) {\n var need = needFinish(state);\n if (need) {\n prefinish(stream, state);\n if (state.pendingcb === 0) {\n state.finished = true;\n stream.emit('finish');\n }\n }\n return need;\n}\n\nfunction endWritable(stream, state, cb) {\n state.ending = true;\n finishMaybe(stream, state);\n if (cb) {\n if (state.finished) pna.nextTick(cb);else stream.once('finish', cb);\n }\n state.ended = true;\n stream.writable = false;\n}\n\nfunction onCorkedFinish(corkReq, state, err) {\n var entry = corkReq.entry;\n corkReq.entry = null;\n while (entry) {\n var cb = entry.callback;\n state.pendingcb--;\n cb(err);\n entry = entry.next;\n }\n\n // reuse the free corkReq.\n state.corkedRequestsFree.next = corkReq;\n}\n\nObject.defineProperty(Writable.prototype, 'destroyed', {\n get: function () {\n if (this._writableState === undefined) {\n return false;\n }\n return this._writableState.destroyed;\n },\n set: function (value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (!this._writableState) {\n return;\n }\n\n // backward compatibility, the user is explicitly\n // managing destroyed\n this._writableState.destroyed = value;\n }\n});\n\nWritable.prototype.destroy = destroyImpl.destroy;\nWritable.prototype._undestroy = destroyImpl.undestroy;\nWritable.prototype._destroy = function (err, cb) {\n this.end();\n cb(err);\n};","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// a duplex stream is just a stream that is both readable and writable.\n// Since JS doesn't have multiple prototypal inheritance, this class\n// prototypally inherits from Readable, and then parasitically from\n// Writable.\n\n'use strict';\n\n/*<replacement>*/\n\nvar pna = require('process-nextick-args');\n/*</replacement>*/\n\n/*<replacement>*/\nvar objectKeys = Object.keys || function (obj) {\n var keys = [];\n for (var key in obj) {\n keys.push(key);\n }return keys;\n};\n/*</replacement>*/\n\nmodule.exports = Duplex;\n\n/*<replacement>*/\nvar util = Object.create(require('core-util-is'));\nutil.inherits = require('inherits');\n/*</replacement>*/\n\nvar Readable = require('./_stream_readable');\nvar Writable = require('./_stream_writable');\n\nutil.inherits(Duplex, Readable);\n\n{\n // avoid scope creep, the keys array can then be collected\n var keys = objectKeys(Writable.prototype);\n for (var v = 0; v < keys.length; v++) {\n var method = keys[v];\n if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];\n }\n}\n\nfunction Duplex(options) {\n if (!(this instanceof Duplex)) return new Duplex(options);\n\n Readable.call(this, options);\n Writable.call(this, options);\n\n if (options && options.readable === false) this.readable = false;\n\n if (options && options.writable === false) this.writable = false;\n\n this.allowHalfOpen = true;\n if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;\n\n this.once('end', onend);\n}\n\nObject.defineProperty(Duplex.prototype, 'writableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function () {\n return this._writableState.highWaterMark;\n }\n});\n\n// the no-half-open enforcer\nfunction onend() {\n // if we allow half-open state, or if the writable side ended,\n // then we're ok.\n if (this.allowHalfOpen || this._writableState.ended) return;\n\n // no more data can be written.\n // But allow more writes to happen in this tick.\n pna.nextTick(onEndNT, this);\n}\n\nfunction onEndNT(self) {\n self.end();\n}\n\nObject.defineProperty(Duplex.prototype, 'destroyed', {\n get: function () {\n if (this._readableState === undefined || this._writableState === undefined) {\n return false;\n }\n return this._readableState.destroyed && this._writableState.destroyed;\n },\n set: function (value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (this._readableState === undefined || this._writableState === undefined) {\n return;\n }\n\n // backward compatibility, the user is explicitly\n // managing destroyed\n this._readableState.destroyed = value;\n this._writableState.destroyed = value;\n }\n});\n\nDuplex.prototype._destroy = function (err, cb) {\n this.push(null);\n this.end();\n\n pna.nextTick(cb, err);\n};","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\n/*<replacement>*/\n\nvar Buffer = require('safe-buffer').Buffer;\n/*</replacement>*/\n\nvar isEncoding = Buffer.isEncoding || function (encoding) {\n encoding = '' + encoding;\n switch (encoding && encoding.toLowerCase()) {\n case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw':\n return true;\n default:\n return false;\n }\n};\n\nfunction _normalizeEncoding(enc) {\n if (!enc) return 'utf8';\n var retried;\n while (true) {\n switch (enc) {\n case 'utf8':\n case 'utf-8':\n return 'utf8';\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return 'utf16le';\n case 'latin1':\n case 'binary':\n return 'latin1';\n case 'base64':\n case 'ascii':\n case 'hex':\n return enc;\n default:\n if (retried) return; // undefined\n enc = ('' + enc).toLowerCase();\n retried = true;\n }\n }\n};\n\n// Do not cache `Buffer.isEncoding` when checking encoding names as some\n// modules monkey-patch it to support additional encodings\nfunction normalizeEncoding(enc) {\n var nenc = _normalizeEncoding(enc);\n if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);\n return nenc || enc;\n}\n\n// StringDecoder provides an interface for efficiently splitting a series of\n// buffers into a series of JS strings without breaking apart multi-byte\n// characters.\nexports.StringDecoder = StringDecoder;\nfunction StringDecoder(encoding) {\n this.encoding = normalizeEncoding(encoding);\n var nb;\n switch (this.encoding) {\n case 'utf16le':\n this.text = utf16Text;\n this.end = utf16End;\n nb = 4;\n break;\n case 'utf8':\n this.fillLast = utf8FillLast;\n nb = 4;\n break;\n case 'base64':\n this.text = base64Text;\n this.end = base64End;\n nb = 3;\n break;\n default:\n this.write = simpleWrite;\n this.end = simpleEnd;\n return;\n }\n this.lastNeed = 0;\n this.lastTotal = 0;\n this.lastChar = Buffer.allocUnsafe(nb);\n}\n\nStringDecoder.prototype.write = function (buf) {\n if (buf.length === 0) return '';\n var r;\n var i;\n if (this.lastNeed) {\n r = this.fillLast(buf);\n if (r === undefined) return '';\n i = this.lastNeed;\n this.lastNeed = 0;\n } else {\n i = 0;\n }\n if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);\n return r || '';\n};\n\nStringDecoder.prototype.end = utf8End;\n\n// Returns only complete characters in a Buffer\nStringDecoder.prototype.text = utf8Text;\n\n// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer\nStringDecoder.prototype.fillLast = function (buf) {\n if (this.lastNeed <= buf.length) {\n buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);\n return this.lastChar.toString(this.encoding, 0, this.lastTotal);\n }\n buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);\n this.lastNeed -= buf.length;\n};\n\n// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a\n// continuation byte. If an invalid byte is detected, -2 is returned.\nfunction utf8CheckByte(byte) {\n if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4;\n return byte >> 6 === 0x02 ? -1 : -2;\n}\n\n// Checks at most 3 bytes at the end of a Buffer in order to detect an\n// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)\n// needed to complete the UTF-8 character (if applicable) are returned.\nfunction utf8CheckIncomplete(self, buf, i) {\n var j = buf.length - 1;\n if (j < i) return 0;\n var nb = utf8CheckByte(buf[j]);\n if (nb >= 0) {\n if (nb > 0) self.lastNeed = nb - 1;\n return nb;\n }\n if (--j < i || nb === -2) return 0;\n nb = utf8CheckByte(buf[j]);\n if (nb >= 0) {\n if (nb > 0) self.lastNeed = nb - 2;\n return nb;\n }\n if (--j < i || nb === -2) return 0;\n nb = utf8CheckByte(buf[j]);\n if (nb >= 0) {\n if (nb > 0) {\n if (nb === 2) nb = 0;else self.lastNeed = nb - 3;\n }\n return nb;\n }\n return 0;\n}\n\n// Validates as many continuation bytes for a multi-byte UTF-8 character as\n// needed or are available. If we see a non-continuation byte where we expect\n// one, we \"replace\" the validated continuation bytes we've seen so far with\n// a single UTF-8 replacement character ('\\ufffd'), to match v8's UTF-8 decoding\n// behavior. The continuation byte check is included three times in the case\n// where all of the continuation bytes for a character exist in the same buffer.\n// It is also done this way as a slight performance increase instead of using a\n// loop.\nfunction utf8CheckExtraBytes(self, buf, p) {\n if ((buf[0] & 0xC0) !== 0x80) {\n self.lastNeed = 0;\n return '\\ufffd';\n }\n if (self.lastNeed > 1 && buf.length > 1) {\n if ((buf[1] & 0xC0) !== 0x80) {\n self.lastNeed = 1;\n return '\\ufffd';\n }\n if (self.lastNeed > 2 && buf.length > 2) {\n if ((buf[2] & 0xC0) !== 0x80) {\n self.lastNeed = 2;\n return '\\ufffd';\n }\n }\n }\n}\n\n// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.\nfunction utf8FillLast(buf) {\n var p = this.lastTotal - this.lastNeed;\n var r = utf8CheckExtraBytes(this, buf, p);\n if (r !== undefined) return r;\n if (this.lastNeed <= buf.length) {\n buf.copy(this.lastChar, p, 0, this.lastNeed);\n return this.lastChar.toString(this.encoding, 0, this.lastTotal);\n }\n buf.copy(this.lastChar, p, 0, buf.length);\n this.lastNeed -= buf.length;\n}\n\n// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a\n// partial character, the character's bytes are buffered until the required\n// number of bytes are available.\nfunction utf8Text(buf, i) {\n var total = utf8CheckIncomplete(this, buf, i);\n if (!this.lastNeed) return buf.toString('utf8', i);\n this.lastTotal = total;\n var end = buf.length - (total - this.lastNeed);\n buf.copy(this.lastChar, 0, end);\n return buf.toString('utf8', i, end);\n}\n\n// For UTF-8, a replacement character is added when ending on a partial\n// character.\nfunction utf8End(buf) {\n var r = buf && buf.length ? this.write(buf) : '';\n if (this.lastNeed) return r + '\\ufffd';\n return r;\n}\n\n// UTF-16LE typically needs two bytes per character, but even if we have an even\n// number of bytes available, we need to check if we end on a leading/high\n// surrogate. In that case, we need to wait for the next two bytes in order to\n// decode the last character properly.\nfunction utf16Text(buf, i) {\n if ((buf.length - i) % 2 === 0) {\n var r = buf.toString('utf16le', i);\n if (r) {\n var c = r.charCodeAt(r.length - 1);\n if (c >= 0xD800 && c <= 0xDBFF) {\n this.lastNeed = 2;\n this.lastTotal = 4;\n this.lastChar[0] = buf[buf.length - 2];\n this.lastChar[1] = buf[buf.length - 1];\n return r.slice(0, -1);\n }\n }\n return r;\n }\n this.lastNeed = 1;\n this.lastTotal = 2;\n this.lastChar[0] = buf[buf.length - 1];\n return buf.toString('utf16le', i, buf.length - 1);\n}\n\n// For UTF-16LE we do not explicitly append special replacement characters if we\n// end on a partial character, we simply let v8 handle that.\nfunction utf16End(buf) {\n var r = buf && buf.length ? this.write(buf) : '';\n if (this.lastNeed) {\n var end = this.lastTotal - this.lastNeed;\n return r + this.lastChar.toString('utf16le', 0, end);\n }\n return r;\n}\n\nfunction base64Text(buf, i) {\n var n = (buf.length - i) % 3;\n if (n === 0) return buf.toString('base64', i);\n this.lastNeed = 3 - n;\n this.lastTotal = 3;\n if (n === 1) {\n this.lastChar[0] = buf[buf.length - 1];\n } else {\n this.lastChar[0] = buf[buf.length - 2];\n this.lastChar[1] = buf[buf.length - 1];\n }\n return buf.toString('base64', i, buf.length - n);\n}\n\nfunction base64End(buf) {\n var r = buf && buf.length ? this.write(buf) : '';\n if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);\n return r;\n}\n\n// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)\nfunction simpleWrite(buf) {\n return buf.toString(this.encoding);\n}\n\nfunction simpleEnd(buf) {\n return buf && buf.length ? this.write(buf) : '';\n}","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\n/*<replacement>*/\n\nvar pna = require('process-nextick-args');\n/*</replacement>*/\n\nmodule.exports = Readable;\n\n/*<replacement>*/\nvar isArray = require('isarray');\n/*</replacement>*/\n\n/*<replacement>*/\nvar Duplex;\n/*</replacement>*/\n\nReadable.ReadableState = ReadableState;\n\n/*<replacement>*/\nvar EE = require('events').EventEmitter;\n\nvar EElistenerCount = function (emitter, type) {\n return emitter.listeners(type).length;\n};\n/*</replacement>*/\n\n/*<replacement>*/\nvar Stream = require('./internal/streams/stream');\n/*</replacement>*/\n\n/*<replacement>*/\n\nvar Buffer = require('safe-buffer').Buffer;\nvar OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {};\nfunction _uint8ArrayToBuffer(chunk) {\n return Buffer.from(chunk);\n}\nfunction _isUint8Array(obj) {\n return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;\n}\n\n/*</replacement>*/\n\n/*<replacement>*/\nvar util = Object.create(require('core-util-is'));\nutil.inherits = require('inherits');\n/*</replacement>*/\n\n/*<replacement>*/\nvar debugUtil = require('util');\nvar debug = void 0;\nif (debugUtil && debugUtil.debuglog) {\n debug = debugUtil.debuglog('stream');\n} else {\n debug = function () {};\n}\n/*</replacement>*/\n\nvar BufferList = require('./internal/streams/BufferList');\nvar destroyImpl = require('./internal/streams/destroy');\nvar StringDecoder;\n\nutil.inherits(Readable, Stream);\n\nvar kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];\n\nfunction prependListener(emitter, event, fn) {\n // Sadly this is not cacheable as some libraries bundle their own\n // event emitter implementation with them.\n if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn);\n\n // This is a hack to make sure that our error handler is attached before any\n // userland ones. NEVER DO THIS. This is here only because this code needs\n // to continue to work with older versions of Node.js that do not include\n // the prependListener() method. The goal is to eventually remove this hack.\n if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];\n}\n\nfunction ReadableState(options, stream) {\n Duplex = Duplex || require('./_stream_duplex');\n\n options = options || {};\n\n // Duplex streams are both readable and writable, but share\n // the same options object.\n // However, some cases require setting options to different\n // values for the readable and the writable sides of the duplex stream.\n // These options can be provided separately as readableXXX and writableXXX.\n var isDuplex = stream instanceof Duplex;\n\n // object stream flag. Used to make read(n) ignore n and to\n // make all the buffer merging and length checks go away\n this.objectMode = !!options.objectMode;\n\n if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode;\n\n // the point at which it stops calling _read() to fill the buffer\n // Note: 0 is a valid value, means \"don't call _read preemptively ever\"\n var hwm = options.highWaterMark;\n var readableHwm = options.readableHighWaterMark;\n var defaultHwm = this.objectMode ? 16 : 16 * 1024;\n\n if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm;\n\n // cast to ints.\n this.highWaterMark = Math.floor(this.highWaterMark);\n\n // A linked list is used to store data chunks instead of an array because the\n // linked list can remove elements from the beginning faster than\n // array.shift()\n this.buffer = new BufferList();\n this.length = 0;\n this.pipes = null;\n this.pipesCount = 0;\n this.flowing = null;\n this.ended = false;\n this.endEmitted = false;\n this.reading = false;\n\n // a flag to be able to tell if the event 'readable'/'data' is emitted\n // immediately, or on a later tick. We set this to true at first, because\n // any actions that shouldn't happen until \"later\" should generally also\n // not happen before the first read call.\n this.sync = true;\n\n // whenever we return null, then we set a flag to say\n // that we're awaiting a 'readable' event emission.\n this.needReadable = false;\n this.emittedReadable = false;\n this.readableListening = false;\n this.resumeScheduled = false;\n\n // has it been destroyed\n this.destroyed = false;\n\n // Crypto is kind of old and crusty. Historically, its default string\n // encoding is 'binary' so we have to make this configurable.\n // Everything else in the universe uses 'utf8', though.\n this.defaultEncoding = options.defaultEncoding || 'utf8';\n\n // the number of writers that are awaiting a drain event in .pipe()s\n this.awaitDrain = 0;\n\n // if true, a maybeReadMore has been scheduled\n this.readingMore = false;\n\n this.decoder = null;\n this.encoding = null;\n if (options.encoding) {\n if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;\n this.decoder = new StringDecoder(options.encoding);\n this.encoding = options.encoding;\n }\n}\n\nfunction Readable(options) {\n Duplex = Duplex || require('./_stream_duplex');\n\n if (!(this instanceof Readable)) return new Readable(options);\n\n this._readableState = new ReadableState(options, this);\n\n // legacy\n this.readable = true;\n\n if (options) {\n if (typeof options.read === 'function') this._read = options.read;\n\n if (typeof options.destroy === 'function') this._destroy = options.destroy;\n }\n\n Stream.call(this);\n}\n\nObject.defineProperty(Readable.prototype, 'destroyed', {\n get: function () {\n if (this._readableState === undefined) {\n return false;\n }\n return this._readableState.destroyed;\n },\n set: function (value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (!this._readableState) {\n return;\n }\n\n // backward compatibility, the user is explicitly\n // managing destroyed\n this._readableState.destroyed = value;\n }\n});\n\nReadable.prototype.destroy = destroyImpl.destroy;\nReadable.prototype._undestroy = destroyImpl.undestroy;\nReadable.prototype._destroy = function (err, cb) {\n this.push(null);\n cb(err);\n};\n\n// Manually shove something into the read() buffer.\n// This returns true if the highWaterMark has not been hit yet,\n// similar to how Writable.write() returns true if you should\n// write() some more.\nReadable.prototype.push = function (chunk, encoding) {\n var state = this._readableState;\n var skipChunkCheck;\n\n if (!state.objectMode) {\n if (typeof chunk === 'string') {\n encoding = encoding || state.defaultEncoding;\n if (encoding !== state.encoding) {\n chunk = Buffer.from(chunk, encoding);\n encoding = '';\n }\n skipChunkCheck = true;\n }\n } else {\n skipChunkCheck = true;\n }\n\n return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);\n};\n\n// Unshift should *always* be something directly out of read()\nReadable.prototype.unshift = function (chunk) {\n return readableAddChunk(this, chunk, null, true, false);\n};\n\nfunction readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {\n var state = stream._readableState;\n if (chunk === null) {\n state.reading = false;\n onEofChunk(stream, state);\n } else {\n var er;\n if (!skipChunkCheck) er = chunkInvalid(state, chunk);\n if (er) {\n stream.emit('error', er);\n } else if (state.objectMode || chunk && chunk.length > 0) {\n if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {\n chunk = _uint8ArrayToBuffer(chunk);\n }\n\n if (addToFront) {\n if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true);\n } else if (state.ended) {\n stream.emit('error', new Error('stream.push() after EOF'));\n } else {\n state.reading = false;\n if (state.decoder && !encoding) {\n chunk = state.decoder.write(chunk);\n if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);\n } else {\n addChunk(stream, state, chunk, false);\n }\n }\n } else if (!addToFront) {\n state.reading = false;\n }\n }\n\n return needMoreData(state);\n}\n\nfunction addChunk(stream, state, chunk, addToFront) {\n if (state.flowing && state.length === 0 && !state.sync) {\n stream.emit('data', chunk);\n stream.read(0);\n } else {\n // update the buffer info.\n state.length += state.objectMode ? 1 : chunk.length;\n if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);\n\n if (state.needReadable) emitReadable(stream);\n }\n maybeReadMore(stream, state);\n}\n\nfunction chunkInvalid(state, chunk) {\n var er;\n if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {\n er = new TypeError('Invalid non-string/buffer chunk');\n }\n return er;\n}\n\n// if it's past the high water mark, we can push in some more.\n// Also, if we have no data yet, we can stand some\n// more bytes. This is to work around cases where hwm=0,\n// such as the repl. Also, if the push() triggered a\n// readable event, and the user called read(largeNumber) such that\n// needReadable was set, then we ought to push more, so that another\n// 'readable' event will be triggered.\nfunction needMoreData(state) {\n return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);\n}\n\nReadable.prototype.isPaused = function () {\n return this._readableState.flowing === false;\n};\n\n// backwards compatibility.\nReadable.prototype.setEncoding = function (enc) {\n if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;\n this._readableState.decoder = new StringDecoder(enc);\n this._readableState.encoding = enc;\n return this;\n};\n\n// Don't raise the hwm > 8MB\nvar MAX_HWM = 0x800000;\nfunction computeNewHighWaterMark(n) {\n if (n >= MAX_HWM) {\n n = MAX_HWM;\n } else {\n // Get the next highest power of 2 to prevent increasing hwm excessively in\n // tiny amounts\n n--;\n n |= n >>> 1;\n n |= n >>> 2;\n n |= n >>> 4;\n n |= n >>> 8;\n n |= n >>> 16;\n n++;\n }\n return n;\n}\n\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction howMuchToRead(n, state) {\n if (n <= 0 || state.length === 0 && state.ended) return 0;\n if (state.objectMode) return 1;\n if (n !== n) {\n // Only flow one buffer at a time\n if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;\n }\n // If we're asking for more than the current hwm, then raise the hwm.\n if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);\n if (n <= state.length) return n;\n // Don't have enough\n if (!state.ended) {\n state.needReadable = true;\n return 0;\n }\n return state.length;\n}\n\n// you can override either this method, or the async _read(n) below.\nReadable.prototype.read = function (n) {\n debug('read', n);\n n = parseInt(n, 10);\n var state = this._readableState;\n var nOrig = n;\n\n if (n !== 0) state.emittedReadable = false;\n\n // if we're doing read(0) to trigger a readable event, but we\n // already have a bunch of data in the buffer, then just trigger\n // the 'readable' event and move on.\n if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {\n debug('read: emitReadable', state.length, state.ended);\n if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);\n return null;\n }\n\n n = howMuchToRead(n, state);\n\n // if we've ended, and we're now clear, then finish it up.\n if (n === 0 && state.ended) {\n if (state.length === 0) endReadable(this);\n return null;\n }\n\n // All the actual chunk generation logic needs to be\n // *below* the call to _read. The reason is that in certain\n // synthetic stream cases, such as passthrough streams, _read\n // may be a completely synchronous operation which may change\n // the state of the read buffer, providing enough data when\n // before there was *not* enough.\n //\n // So, the steps are:\n // 1. Figure out what the state of things will be after we do\n // a read from the buffer.\n //\n // 2. If that resulting state will trigger a _read, then call _read.\n // Note that this may be asynchronous, or synchronous. Yes, it is\n // deeply ugly to write APIs this way, but that still doesn't mean\n // that the Readable class should behave improperly, as streams are\n // designed to be sync/async agnostic.\n // Take note if the _read call is sync or async (ie, if the read call\n // has returned yet), so that we know whether or not it's safe to emit\n // 'readable' etc.\n //\n // 3. Actually pull the requested chunks out of the buffer and return.\n\n // if we need a readable event, then we need to do some reading.\n var doRead = state.needReadable;\n debug('need readable', doRead);\n\n // if we currently have less than the highWaterMark, then also read some\n if (state.length === 0 || state.length - n < state.highWaterMark) {\n doRead = true;\n debug('length less than watermark', doRead);\n }\n\n // however, if we've ended, then there's no point, and if we're already\n // reading, then it's unnecessary.\n if (state.ended || state.reading) {\n doRead = false;\n debug('reading or ended', doRead);\n } else if (doRead) {\n debug('do read');\n state.reading = true;\n state.sync = true;\n // if the length is currently zero, then we *need* a readable event.\n if (state.length === 0) state.needReadable = true;\n // call internal read method\n this._read(state.highWaterMark);\n state.sync = false;\n // If _read pushed data synchronously, then `reading` will be false,\n // and we need to re-evaluate how much data we can return to the user.\n if (!state.reading) n = howMuchToRead(nOrig, state);\n }\n\n var ret;\n if (n > 0) ret = fromList(n, state);else ret = null;\n\n if (ret === null) {\n state.needReadable = true;\n n = 0;\n } else {\n state.length -= n;\n }\n\n if (state.length === 0) {\n // If we have nothing in the buffer, then we want to know\n // as soon as we *do* get something into the buffer.\n if (!state.ended) state.needReadable = true;\n\n // If we tried to read() past the EOF, then emit end on the next tick.\n if (nOrig !== n && state.ended) endReadable(this);\n }\n\n if (ret !== null) this.emit('data', ret);\n\n return ret;\n};\n\nfunction onEofChunk(stream, state) {\n if (state.ended) return;\n if (state.decoder) {\n var chunk = state.decoder.end();\n if (chunk && chunk.length) {\n state.buffer.push(chunk);\n state.length += state.objectMode ? 1 : chunk.length;\n }\n }\n state.ended = true;\n\n // emit 'readable' now to make sure it gets picked up.\n emitReadable(stream);\n}\n\n// Don't emit readable right away in sync mode, because this can trigger\n// another read() call => stack overflow. This way, it might trigger\n// a nextTick recursion warning, but that's not so bad.\nfunction emitReadable(stream) {\n var state = stream._readableState;\n state.needReadable = false;\n if (!state.emittedReadable) {\n debug('emitReadable', state.flowing);\n state.emittedReadable = true;\n if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream);\n }\n}\n\nfunction emitReadable_(stream) {\n debug('emit readable');\n stream.emit('readable');\n flow(stream);\n}\n\n// at this point, the user has presumably seen the 'readable' event,\n// and called read() to consume some data. that may have triggered\n// in turn another _read(n) call, in which case reading = true if\n// it's in progress.\n// However, if we're not ended, or reading, and the length < hwm,\n// then go ahead and try to read some more preemptively.\nfunction maybeReadMore(stream, state) {\n if (!state.readingMore) {\n state.readingMore = true;\n pna.nextTick(maybeReadMore_, stream, state);\n }\n}\n\nfunction maybeReadMore_(stream, state) {\n var len = state.length;\n while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {\n debug('maybeReadMore read 0');\n stream.read(0);\n if (len === state.length)\n // didn't get any data, stop spinning.\n break;else len = state.length;\n }\n state.readingMore = false;\n}\n\n// abstract method. to be overridden in specific implementation classes.\n// call cb(er, data) where data is <= n in length.\n// for virtual (non-string, non-buffer) streams, \"length\" is somewhat\n// arbitrary, and perhaps not very meaningful.\nReadable.prototype._read = function (n) {\n this.emit('error', new Error('_read() is not implemented'));\n};\n\nReadable.prototype.pipe = function (dest, pipeOpts) {\n var src = this;\n var state = this._readableState;\n\n switch (state.pipesCount) {\n case 0:\n state.pipes = dest;\n break;\n case 1:\n state.pipes = [state.pipes, dest];\n break;\n default:\n state.pipes.push(dest);\n break;\n }\n state.pipesCount += 1;\n debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);\n\n var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;\n\n var endFn = doEnd ? onend : unpipe;\n if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn);\n\n dest.on('unpipe', onunpipe);\n function onunpipe(readable, unpipeInfo) {\n debug('onunpipe');\n if (readable === src) {\n if (unpipeInfo && unpipeInfo.hasUnpiped === false) {\n unpipeInfo.hasUnpiped = true;\n cleanup();\n }\n }\n }\n\n function onend() {\n debug('onend');\n dest.end();\n }\n\n // when the dest drains, it reduces the awaitDrain counter\n // on the source. This would be more elegant with a .once()\n // handler in flow(), but adding and removing repeatedly is\n // too slow.\n var ondrain = pipeOnDrain(src);\n dest.on('drain', ondrain);\n\n var cleanedUp = false;\n function cleanup() {\n debug('cleanup');\n // cleanup event handlers once the pipe is broken\n dest.removeListener('close', onclose);\n dest.removeListener('finish', onfinish);\n dest.removeListener('drain', ondrain);\n dest.removeListener('error', onerror);\n dest.removeListener('unpipe', onunpipe);\n src.removeListener('end', onend);\n src.removeListener('end', unpipe);\n src.removeListener('data', ondata);\n\n cleanedUp = true;\n\n // if the reader is waiting for a drain event from this\n // specific writer, then it would cause it to never start\n // flowing again.\n // So, if this is awaiting a drain, then we just call it now.\n // If we don't know, then assume that we are waiting for one.\n if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();\n }\n\n // If the user pushes more data while we're writing to dest then we'll end up\n // in ondata again. However, we only want to increase awaitDrain once because\n // dest will only emit one 'drain' event for the multiple writes.\n // => Introduce a guard on increasing awaitDrain.\n var increasedAwaitDrain = false;\n src.on('data', ondata);\n function ondata(chunk) {\n debug('ondata');\n increasedAwaitDrain = false;\n var ret = dest.write(chunk);\n if (false === ret && !increasedAwaitDrain) {\n // If the user unpiped during `dest.write()`, it is possible\n // to get stuck in a permanently paused state if that write\n // also returned false.\n // => Check whether `dest` is still a piping destination.\n if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {\n debug('false write response, pause', state.awaitDrain);\n state.awaitDrain++;\n increasedAwaitDrain = true;\n }\n src.pause();\n }\n }\n\n // if the dest has an error, then stop piping into it.\n // however, don't suppress the throwing behavior for this.\n function onerror(er) {\n debug('onerror', er);\n unpipe();\n dest.removeListener('error', onerror);\n if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);\n }\n\n // Make sure our error handler is attached before userland ones.\n prependListener(dest, 'error', onerror);\n\n // Both close and finish should trigger unpipe, but only once.\n function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }\n dest.once('close', onclose);\n function onfinish() {\n debug('onfinish');\n dest.removeListener('close', onclose);\n unpipe();\n }\n dest.once('finish', onfinish);\n\n function unpipe() {\n debug('unpipe');\n src.unpipe(dest);\n }\n\n // tell the dest that it's being piped to\n dest.emit('pipe', src);\n\n // start the flow if it hasn't been started already.\n if (!state.flowing) {\n debug('pipe resume');\n src.resume();\n }\n\n return dest;\n};\n\nfunction pipeOnDrain(src) {\n return function () {\n var state = src._readableState;\n debug('pipeOnDrain', state.awaitDrain);\n if (state.awaitDrain) state.awaitDrain--;\n if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {\n state.flowing = true;\n flow(src);\n }\n };\n}\n\nReadable.prototype.unpipe = function (dest) {\n var state = this._readableState;\n var unpipeInfo = { hasUnpiped: false };\n\n // if we're not piping anywhere, then do nothing.\n if (state.pipesCount === 0) return this;\n\n // just one destination. most common case.\n if (state.pipesCount === 1) {\n // passed in one, but it's not the right one.\n if (dest && dest !== state.pipes) return this;\n\n if (!dest) dest = state.pipes;\n\n // got a match.\n state.pipes = null;\n state.pipesCount = 0;\n state.flowing = false;\n if (dest) dest.emit('unpipe', this, unpipeInfo);\n return this;\n }\n\n // slow case. multiple pipe destinations.\n\n if (!dest) {\n // remove all.\n var dests = state.pipes;\n var len = state.pipesCount;\n state.pipes = null;\n state.pipesCount = 0;\n state.flowing = false;\n\n for (var i = 0; i < len; i++) {\n dests[i].emit('unpipe', this, { hasUnpiped: false });\n }return this;\n }\n\n // try to find the right one.\n var index = indexOf(state.pipes, dest);\n if (index === -1) return this;\n\n state.pipes.splice(index, 1);\n state.pipesCount -= 1;\n if (state.pipesCount === 1) state.pipes = state.pipes[0];\n\n dest.emit('unpipe', this, unpipeInfo);\n\n return this;\n};\n\n// set up data events if they are asked for\n// Ensure readable listeners eventually get something\nReadable.prototype.on = function (ev, fn) {\n var res = Stream.prototype.on.call(this, ev, fn);\n\n if (ev === 'data') {\n // Start flowing on next tick if stream isn't explicitly paused\n if (this._readableState.flowing !== false) this.resume();\n } else if (ev === 'readable') {\n var state = this._readableState;\n if (!state.endEmitted && !state.readableListening) {\n state.readableListening = state.needReadable = true;\n state.emittedReadable = false;\n if (!state.reading) {\n pna.nextTick(nReadingNextTick, this);\n } else if (state.length) {\n emitReadable(this);\n }\n }\n }\n\n return res;\n};\nReadable.prototype.addListener = Readable.prototype.on;\n\nfunction nReadingNextTick(self) {\n debug('readable nexttick read 0');\n self.read(0);\n}\n\n// pause() and resume() are remnants of the legacy readable stream API\n// If the user uses them, then switch into old mode.\nReadable.prototype.resume = function () {\n var state = this._readableState;\n if (!state.flowing) {\n debug('resume');\n state.flowing = true;\n resume(this, state);\n }\n return this;\n};\n\nfunction resume(stream, state) {\n if (!state.resumeScheduled) {\n state.resumeScheduled = true;\n pna.nextTick(resume_, stream, state);\n }\n}\n\nfunction resume_(stream, state) {\n if (!state.reading) {\n debug('resume read 0');\n stream.read(0);\n }\n\n state.resumeScheduled = false;\n state.awaitDrain = 0;\n stream.emit('resume');\n flow(stream);\n if (state.flowing && !state.reading) stream.read(0);\n}\n\nReadable.prototype.pause = function () {\n debug('call pause flowing=%j', this._readableState.flowing);\n if (false !== this._readableState.flowing) {\n debug('pause');\n this._readableState.flowing = false;\n this.emit('pause');\n }\n return this;\n};\n\nfunction flow(stream) {\n var state = stream._readableState;\n debug('flow', state.flowing);\n while (state.flowing && stream.read() !== null) {}\n}\n\n// wrap an old-style stream as the async data source.\n// This is *not* part of the readable stream interface.\n// It is an ugly unfortunate mess of history.\nReadable.prototype.wrap = function (stream) {\n var _this = this;\n\n var state = this._readableState;\n var paused = false;\n\n stream.on('end', function () {\n debug('wrapped end');\n if (state.decoder && !state.ended) {\n var chunk = state.decoder.end();\n if (chunk && chunk.length) _this.push(chunk);\n }\n\n _this.push(null);\n });\n\n stream.on('data', function (chunk) {\n debug('wrapped data');\n if (state.decoder) chunk = state.decoder.write(chunk);\n\n // don't skip over falsy values in objectMode\n if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;\n\n var ret = _this.push(chunk);\n if (!ret) {\n paused = true;\n stream.pause();\n }\n });\n\n // proxy all the other methods.\n // important when wrapping filters and duplexes.\n for (var i in stream) {\n if (this[i] === undefined && typeof stream[i] === 'function') {\n this[i] = function (method) {\n return function () {\n return stream[method].apply(stream, arguments);\n };\n }(i);\n }\n }\n\n // proxy certain important events.\n for (var n = 0; n < kProxyEvents.length; n++) {\n stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));\n }\n\n // when we try to consume some more bytes, simply unpause the\n // underlying stream.\n this._read = function (n) {\n debug('wrapped _read', n);\n if (paused) {\n paused = false;\n stream.resume();\n }\n };\n\n return this;\n};\n\nObject.defineProperty(Readable.prototype, 'readableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function () {\n return this._readableState.highWaterMark;\n }\n});\n\n// exposed for testing purposes only.\nReadable._fromList = fromList;\n\n// Pluck off n bytes from an array of buffers.\n// Length is the combined lengths of all the buffers in the list.\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction fromList(n, state) {\n // nothing buffered\n if (state.length === 0) return null;\n\n var ret;\n if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {\n // read it all, truncate the list\n if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length);\n state.buffer.clear();\n } else {\n // read part of list\n ret = fromListPartial(n, state.buffer, state.decoder);\n }\n\n return ret;\n}\n\n// Extracts only enough buffered data to satisfy the amount requested.\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction fromListPartial(n, list, hasStrings) {\n var ret;\n if (n < list.head.data.length) {\n // slice is the same for buffers and strings\n ret = list.head.data.slice(0, n);\n list.head.data = list.head.data.slice(n);\n } else if (n === list.head.data.length) {\n // first chunk is a perfect match\n ret = list.shift();\n } else {\n // result spans more than one buffer\n ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);\n }\n return ret;\n}\n\n// Copies a specified amount of characters from the list of buffered data\n// chunks.\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction copyFromBufferString(n, list) {\n var p = list.head;\n var c = 1;\n var ret = p.data;\n n -= ret.length;\n while (p = p.next) {\n var str = p.data;\n var nb = n > str.length ? str.length : n;\n if (nb === str.length) ret += str;else ret += str.slice(0, n);\n n -= nb;\n if (n === 0) {\n if (nb === str.length) {\n ++c;\n if (p.next) list.head = p.next;else list.head = list.tail = null;\n } else {\n list.head = p;\n p.data = str.slice(nb);\n }\n break;\n }\n ++c;\n }\n list.length -= c;\n return ret;\n}\n\n// Copies a specified amount of bytes from the list of buffered data chunks.\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction copyFromBuffer(n, list) {\n var ret = Buffer.allocUnsafe(n);\n var p = list.head;\n var c = 1;\n p.data.copy(ret);\n n -= p.data.length;\n while (p = p.next) {\n var buf = p.data;\n var nb = n > buf.length ? buf.length : n;\n buf.copy(ret, ret.length - n, 0, nb);\n n -= nb;\n if (n === 0) {\n if (nb === buf.length) {\n ++c;\n if (p.next) list.head = p.next;else list.head = list.tail = null;\n } else {\n list.head = p;\n p.data = buf.slice(nb);\n }\n break;\n }\n ++c;\n }\n list.length -= c;\n return ret;\n}\n\nfunction endReadable(stream) {\n var state = stream._readableState;\n\n // If we get here before consuming all the bytes, then that is a\n // bug in node. Should never happen.\n if (state.length > 0) throw new Error('\"endReadable()\" called on non-empty stream');\n\n if (!state.endEmitted) {\n state.ended = true;\n pna.nextTick(endReadableNT, state, stream);\n }\n}\n\nfunction endReadableNT(state, stream) {\n // Check that we didn't get one last unshift.\n if (!state.endEmitted && state.length === 0) {\n state.endEmitted = true;\n stream.readable = false;\n stream.emit('end');\n }\n}\n\nfunction indexOf(xs, x) {\n for (var i = 0, l = xs.length; i < l; i++) {\n if (xs[i] === x) return i;\n }\n return -1;\n}","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// a transform stream is a readable/writable stream where you do\n// something with the data. Sometimes it's called a \"filter\",\n// but that's not a great name for it, since that implies a thing where\n// some bits pass through, and others are simply ignored. (That would\n// be a valid example of a transform, of course.)\n//\n// While the output is causally related to the input, it's not a\n// necessarily symmetric or synchronous transformation. For example,\n// a zlib stream might take multiple plain-text writes(), and then\n// emit a single compressed chunk some time in the future.\n//\n// Here's how this works:\n//\n// The Transform stream has all the aspects of the readable and writable\n// stream classes. When you write(chunk), that calls _write(chunk,cb)\n// internally, and returns false if there's a lot of pending writes\n// buffered up. When you call read(), that calls _read(n) until\n// there's enough pending readable data buffered up.\n//\n// In a transform stream, the written data is placed in a buffer. When\n// _read(n) is called, it transforms the queued up data, calling the\n// buffered _write cb's as it consumes chunks. If consuming a single\n// written chunk would result in multiple output chunks, then the first\n// outputted bit calls the readcb, and subsequent chunks just go into\n// the read buffer, and will cause it to emit 'readable' if necessary.\n//\n// This way, back-pressure is actually determined by the reading side,\n// since _read has to be called to start processing a new chunk. However,\n// a pathological inflate type of transform can cause excessive buffering\n// here. For example, imagine a stream where every byte of input is\n// interpreted as an integer from 0-255, and then results in that many\n// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in\n// 1kb of data being output. In this case, you could write a very small\n// amount of input, and end up with a very large amount of output. In\n// such a pathological inflating mechanism, there'd be no way to tell\n// the system to stop doing the transform. A single 4MB write could\n// cause the system to run out of memory.\n//\n// However, even in such a pathological case, only a single written chunk\n// would be consumed, and then the rest would wait (un-transformed) until\n// the results of the previous transformed chunk were consumed.\n\n'use strict';\n\nmodule.exports = Transform;\n\nvar Duplex = require('./_stream_duplex');\n\n/*<replacement>*/\nvar util = Object.create(require('core-util-is'));\nutil.inherits = require('inherits');\n/*</replacement>*/\n\nutil.inherits(Transform, Duplex);\n\nfunction afterTransform(er, data) {\n var ts = this._transformState;\n ts.transforming = false;\n\n var cb = ts.writecb;\n\n if (!cb) {\n return this.emit('error', new Error('write callback called multiple times'));\n }\n\n ts.writechunk = null;\n ts.writecb = null;\n\n if (data != null) // single equals check for both `null` and `undefined`\n this.push(data);\n\n cb(er);\n\n var rs = this._readableState;\n rs.reading = false;\n if (rs.needReadable || rs.length < rs.highWaterMark) {\n this._read(rs.highWaterMark);\n }\n}\n\nfunction Transform(options) {\n if (!(this instanceof Transform)) return new Transform(options);\n\n Duplex.call(this, options);\n\n this._transformState = {\n afterTransform: afterTransform.bind(this),\n needTransform: false,\n transforming: false,\n writecb: null,\n writechunk: null,\n writeencoding: null\n };\n\n // start out asking for a readable event once data is transformed.\n this._readableState.needReadable = true;\n\n // we have implemented the _read method, and done the other things\n // that Readable wants before the first _read call, so unset the\n // sync guard flag.\n this._readableState.sync = false;\n\n if (options) {\n if (typeof options.transform === 'function') this._transform = options.transform;\n\n if (typeof options.flush === 'function') this._flush = options.flush;\n }\n\n // When the writable side finishes, then flush out anything remaining.\n this.on('prefinish', prefinish);\n}\n\nfunction prefinish() {\n var _this = this;\n\n if (typeof this._flush === 'function') {\n this._flush(function (er, data) {\n done(_this, er, data);\n });\n } else {\n done(this, null, null);\n }\n}\n\nTransform.prototype.push = function (chunk, encoding) {\n this._transformState.needTransform = false;\n return Duplex.prototype.push.call(this, chunk, encoding);\n};\n\n// This is the part where you do stuff!\n// override this function in implementation classes.\n// 'chunk' is an input chunk.\n//\n// Call `push(newChunk)` to pass along transformed output\n// to the readable side. You may call 'push' zero or more times.\n//\n// Call `cb(err)` when you are done with this chunk. If you pass\n// an error, then that'll put the hurt on the whole operation. If you\n// never call cb(), then you'll never get another chunk.\nTransform.prototype._transform = function (chunk, encoding, cb) {\n throw new Error('_transform() is not implemented');\n};\n\nTransform.prototype._write = function (chunk, encoding, cb) {\n var ts = this._transformState;\n ts.writecb = cb;\n ts.writechunk = chunk;\n ts.writeencoding = encoding;\n if (!ts.transforming) {\n var rs = this._readableState;\n if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);\n }\n};\n\n// Doesn't matter what the args are here.\n// _transform does all the work.\n// That we got here means that the readable side wants more data.\nTransform.prototype._read = function (n) {\n var ts = this._transformState;\n\n if (ts.writechunk !== null && ts.writecb && !ts.transforming) {\n ts.transforming = true;\n this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);\n } else {\n // mark that we need a transform, so that any data that comes in\n // will get processed, now that we've asked for it.\n ts.needTransform = true;\n }\n};\n\nTransform.prototype._destroy = function (err, cb) {\n var _this2 = this;\n\n Duplex.prototype._destroy.call(this, err, function (err2) {\n cb(err2);\n _this2.emit('close');\n });\n};\n\nfunction done(stream, er, data) {\n if (er) return stream.emit('error', er);\n\n if (data != null) // single equals check for both `null` and `undefined`\n stream.push(data);\n\n // if there's nothing in the write buffer, then that means\n // that nothing more will ever be provided\n if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0');\n\n if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming');\n\n return stream.push(null);\n}","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// a passthrough stream.\n// basically just the most minimal sort of Transform stream.\n// Every written chunk gets output as-is.\n\n'use strict';\n\nmodule.exports = PassThrough;\n\nvar Transform = require('./_stream_transform');\n\n/*<replacement>*/\nvar util = Object.create(require('core-util-is'));\nutil.inherits = require('inherits');\n/*</replacement>*/\n\nutil.inherits(PassThrough, Transform);\n\nfunction PassThrough(options) {\n if (!(this instanceof PassThrough)) return new PassThrough(options);\n\n Transform.call(this, options);\n}\n\nPassThrough.prototype._transform = function (chunk, encoding, cb) {\n cb(null, chunk);\n};","var Stream = require('stream');\nif (process.env.READABLE_STREAM === 'disable' && Stream) {\n module.exports = Stream;\n exports = module.exports = Stream.Readable;\n exports.Readable = Stream.Readable;\n exports.Writable = Stream.Writable;\n exports.Duplex = Stream.Duplex;\n exports.Transform = Stream.Transform;\n exports.PassThrough = Stream.PassThrough;\n exports.Stream = Stream;\n} else {\n exports = module.exports = require('./lib/_stream_readable.js');\n exports.Stream = Stream || exports;\n exports.Readable = exports;\n exports.Writable = require('./lib/_stream_writable.js');\n exports.Duplex = require('./lib/_stream_duplex.js');\n exports.Transform = require('./lib/_stream_transform.js');\n exports.PassThrough = require('./lib/_stream_passthrough.js');\n}\n","module.exports = extend\n\nvar hasOwnProperty = Object.prototype.hasOwnProperty;\n\nfunction extend() {\n var target = {}\n\n for (var i = 0; i < arguments.length; i++) {\n var source = arguments[i]\n\n for (var key in source) {\n if (hasOwnProperty.call(source, key)) {\n target[key] = source[key]\n }\n }\n }\n\n return target\n}\n","var Transform = require('readable-stream').Transform\n , inherits = require('util').inherits\n , xtend = require('xtend')\n\nfunction DestroyableTransform(opts) {\n Transform.call(this, opts)\n this._destroyed = false\n}\n\ninherits(DestroyableTransform, Transform)\n\nDestroyableTransform.prototype.destroy = function(err) {\n if (this._destroyed) return\n this._destroyed = true\n \n var self = this\n process.nextTick(function() {\n if (err)\n self.emit('error', err)\n self.emit('close')\n })\n}\n\n// a noop _transform function\nfunction noop (chunk, enc, callback) {\n callback(null, chunk)\n}\n\n\n// create a new export function, used by both the main export and\n// the .ctor export, contains common logic for dealing with arguments\nfunction through2 (construct) {\n return function (options, transform, flush) {\n if (typeof options == 'function') {\n flush = transform\n transform = options\n options = {}\n }\n\n if (typeof transform != 'function')\n transform = noop\n\n if (typeof flush != 'function')\n flush = null\n\n return construct(options, transform, flush)\n }\n}\n\n\n// main export, just make me a transform stream!\nmodule.exports = through2(function (options, transform, flush) {\n var t2 = new DestroyableTransform(options)\n\n t2._transform = transform\n\n if (flush)\n t2._flush = flush\n\n return t2\n})\n\n\n// make me a reusable prototype that I can `new`, or implicitly `new`\n// with a constructor call\nmodule.exports.ctor = through2(function (options, transform, flush) {\n function Through2 (override) {\n if (!(this instanceof Through2))\n return new Through2(override)\n\n this.options = xtend(options, override)\n\n DestroyableTransform.call(this, this.options)\n }\n\n inherits(Through2, DestroyableTransform)\n\n Through2.prototype._transform = transform\n\n if (flush)\n Through2.prototype._flush = flush\n\n return Through2\n})\n\n\nmodule.exports.obj = through2(function (options, transform, flush) {\n var t2 = new DestroyableTransform(xtend({ objectMode: true, highWaterMark: 16 }, options))\n\n t2._transform = transform\n\n if (flush)\n t2._flush = flush\n\n return t2\n})\n","var tick = 1\nvar maxTick = 65535\nvar resolution = 4\nvar inc = function () {\n tick = (tick + 1) & maxTick\n}\n\nvar timer = setInterval(inc, (1000 / resolution) | 0)\nif (timer.unref) timer.unref()\n\nmodule.exports = function (seconds) {\n var size = resolution * (seconds || 5)\n var buffer = [0]\n var pointer = 1\n var last = (tick - 1) & maxTick\n\n return function (delta) {\n var dist = (tick - last) & maxTick\n if (dist > size) dist = size\n last = tick\n\n while (dist--) {\n if (pointer === size) pointer = 0\n buffer[pointer] = buffer[pointer === 0 ? size - 1 : pointer - 1]\n pointer++\n }\n\n if (delta) buffer[pointer - 1] += delta\n\n var top = buffer[pointer - 1]\n var btm = buffer.length < size ? 0 : buffer[pointer === size ? 0 : pointer]\n\n return buffer.length < resolution ? top : (top - btm) * resolution / buffer.length\n }\n}\n","var through = require('through2');\nvar speedometer = require('speedometer');\n\nmodule.exports = function(options, onprogress) {\n\tif (typeof options === 'function') return module.exports(null, options);\n\toptions = options || {};\n\n\tvar length = options.length || 0;\n\tvar time = options.time || 0;\n\tvar drain = options.drain || false;\n\tvar transferred = options.transferred || 0;\n\tvar nextUpdate = Date.now()+time;\n\tvar delta = 0;\n\tvar speed = speedometer(options.speed || 5000);\n\tvar startTime = Date.now();\n\n\tvar update = {\n\t\tpercentage: 0,\n\t\ttransferred: transferred,\n\t\tlength: length,\n\t\tremaining: length,\n\t\teta: 0,\n\t\truntime: 0\n\t};\n\n\tvar emit = function(ended) {\n\t\tupdate.delta = delta;\n\t\tupdate.percentage = ended ? 100 : (length ? transferred/length*100 : 0);\n\t\tupdate.speed = speed(delta);\n\t\tupdate.eta = Math.round(update.remaining / update.speed);\n\t\tupdate.runtime = parseInt((Date.now() - startTime)/1000);\n\t\tnextUpdate = Date.now()+time;\n\n\t\tdelta = 0;\n\n\t\ttr.emit('progress', update);\n\t};\n\tvar write = function(chunk, enc, callback) {\n\t\tvar len = options.objectMode ? 1 : chunk.length;\n\t\ttransferred += len;\n\t\tdelta += len;\n\t\tupdate.transferred = transferred;\n\t\tupdate.remaining = length >= transferred ? length - transferred : 0;\n\n\t\tif (Date.now() >= nextUpdate) emit(false);\n\t\tcallback(null, chunk);\n\t};\n\tvar end = function(callback) {\n\t\temit(true);\n\t\tcallback();\n\t};\n\n\tvar tr = through(options.objectMode ? {objectMode:true, highWaterMark:16} : {}, write, end);\n\tvar onlength = function(newLength) {\n\t\tlength = newLength;\n\t\tupdate.length = length;\n\t\tupdate.remaining = length - update.transferred;\n\t\ttr.emit('length', length);\n\t};\n\t\n\t// Expose `onlength()` handler as `setLength()` to support custom use cases where length\n\t// is not known until after a few chunks have already been pumped, or is\n\t// calculated on the fly.\n\ttr.setLength = onlength;\n\t\n\ttr.on('pipe', function(stream) {\n\t\tif (typeof length === 'number') return;\n\t\t// Support http module\n\t\tif (stream.readable && !stream.writable && stream.headers) {\n\t\t\treturn onlength(parseInt(stream.headers['content-length'] || 0));\n\t\t}\n\n\t\t// Support streams with a length property\n\t\tif (typeof stream.length === 'number') {\n\t\t\treturn onlength(stream.length);\n\t\t}\n\n\t\t// Support request module\n\t\tstream.on('response', function(res) {\n\t\t\tif (!res || !res.headers) return;\n\t\t\tif (res.headers['content-encoding'] === 'gzip') return;\n\t\t\tif (res.headers['content-length']) {\n\t\t\t\treturn onlength(parseInt(res.headers['content-length']));\n\t\t\t}\n\t\t});\n\t});\n\n\tif (drain) tr.resume();\n\tif (onprogress) tr.on('progress', onprogress);\n\n\ttr.progress = function() {\n\t\tupdate.speed = speed(0);\n\t\tupdate.eta = Math.round(update.remaining / update.speed);\n\n\t\treturn update;\n\t};\n\treturn tr;\n};\n","/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */\n/* eslint-disable node/no-deprecated-api */\nvar buffer = require('buffer')\nvar Buffer = buffer.Buffer\n\n// alternative to using Object.keys for old browsers\nfunction copyProps (src, dst) {\n for (var key in src) {\n dst[key] = src[key]\n }\n}\nif (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {\n module.exports = buffer\n} else {\n // Copy properties from require('buffer')\n copyProps(buffer, exports)\n exports.Buffer = SafeBuffer\n}\n\nfunction SafeBuffer (arg, encodingOrOffset, length) {\n return Buffer(arg, encodingOrOffset, length)\n}\n\nSafeBuffer.prototype = Object.create(Buffer.prototype)\n\n// Copy static methods from Buffer\ncopyProps(Buffer, SafeBuffer)\n\nSafeBuffer.from = function (arg, encodingOrOffset, length) {\n if (typeof arg === 'number') {\n throw new TypeError('Argument must not be a number')\n }\n return Buffer(arg, encodingOrOffset, length)\n}\n\nSafeBuffer.alloc = function (size, fill, encoding) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n var buf = Buffer(size)\n if (fill !== undefined) {\n if (typeof encoding === 'string') {\n buf.fill(fill, encoding)\n } else {\n buf.fill(fill)\n }\n } else {\n buf.fill(0)\n }\n return buf\n}\n\nSafeBuffer.allocUnsafe = function (size) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n return Buffer(size)\n}\n\nSafeBuffer.allocUnsafeSlow = function (size) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n return buffer.SlowBuffer(size)\n}\n","'use strict'\n\nvar net = require('net')\n , tls = require('tls')\n , http = require('http')\n , https = require('https')\n , events = require('events')\n , assert = require('assert')\n , util = require('util')\n , Buffer = require('safe-buffer').Buffer\n ;\n\nexports.httpOverHttp = httpOverHttp\nexports.httpsOverHttp = httpsOverHttp\nexports.httpOverHttps = httpOverHttps\nexports.httpsOverHttps = httpsOverHttps\n\n\nfunction httpOverHttp(options) {\n var agent = new TunnelingAgent(options)\n agent.request = http.request\n return agent\n}\n\nfunction httpsOverHttp(options) {\n var agent = new TunnelingAgent(options)\n agent.request = http.request\n agent.createSocket = createSecureSocket\n agent.defaultPort = 443\n return agent\n}\n\nfunction httpOverHttps(options) {\n var agent = new TunnelingAgent(options)\n agent.request = https.request\n return agent\n}\n\nfunction httpsOverHttps(options) {\n var agent = new TunnelingAgent(options)\n agent.request = https.request\n agent.createSocket = createSecureSocket\n agent.defaultPort = 443\n return agent\n}\n\n\nfunction TunnelingAgent(options) {\n var self = this\n self.options = options || {}\n self.proxyOptions = self.options.proxy || {}\n self.maxSockets = self.options.maxSockets || http.Agent.defaultMaxSockets\n self.requests = []\n self.sockets = []\n\n self.on('free', function onFree(socket, host, port) {\n for (var i = 0, len = self.requests.length; i < len; ++i) {\n var pending = self.requests[i]\n if (pending.host === host && pending.port === port) {\n // Detect the request to connect same origin server,\n // reuse the connection.\n self.requests.splice(i, 1)\n pending.request.onSocket(socket)\n return\n }\n }\n socket.destroy()\n self.removeSocket(socket)\n })\n}\nutil.inherits(TunnelingAgent, events.EventEmitter)\n\nTunnelingAgent.prototype.addRequest = function addRequest(req, options) {\n var self = this\n\n // Legacy API: addRequest(req, host, port, path)\n if (typeof options === 'string') {\n options = {\n host: options,\n port: arguments[2],\n path: arguments[3]\n };\n }\n\n if (self.sockets.length >= this.maxSockets) {\n // We are over limit so we'll add it to the queue.\n self.requests.push({host: options.host, port: options.port, request: req})\n return\n }\n\n // If we are under maxSockets create a new one.\n self.createConnection({host: options.host, port: options.port, request: req})\n}\n\nTunnelingAgent.prototype.createConnection = function createConnection(pending) {\n var self = this\n\n self.createSocket(pending, function(socket) {\n socket.on('free', onFree)\n socket.on('close', onCloseOrRemove)\n socket.on('agentRemove', onCloseOrRemove)\n pending.request.onSocket(socket)\n\n function onFree() {\n self.emit('free', socket, pending.host, pending.port)\n }\n\n function onCloseOrRemove(err) {\n self.removeSocket(socket)\n socket.removeListener('free', onFree)\n socket.removeListener('close', onCloseOrRemove)\n socket.removeListener('agentRemove', onCloseOrRemove)\n }\n })\n}\n\nTunnelingAgent.prototype.createSocket = function createSocket(options, cb) {\n var self = this\n var placeholder = {}\n self.sockets.push(placeholder)\n\n var connectOptions = mergeOptions({}, self.proxyOptions,\n { method: 'CONNECT'\n , path: options.host + ':' + options.port\n , agent: false\n }\n )\n if (connectOptions.proxyAuth) {\n connectOptions.headers = connectOptions.headers || {}\n connectOptions.headers['Proxy-Authorization'] = 'Basic ' +\n Buffer.from(connectOptions.proxyAuth).toString('base64')\n }\n\n debug('making CONNECT request')\n var connectReq = self.request(connectOptions)\n connectReq.useChunkedEncodingByDefault = false // for v0.6\n connectReq.once('response', onResponse) // for v0.6\n connectReq.once('upgrade', onUpgrade) // for v0.6\n connectReq.once('connect', onConnect) // for v0.7 or later\n connectReq.once('error', onError)\n connectReq.end()\n\n function onResponse(res) {\n // Very hacky. This is necessary to avoid http-parser leaks.\n res.upgrade = true\n }\n\n function onUpgrade(res, socket, head) {\n // Hacky.\n process.nextTick(function() {\n onConnect(res, socket, head)\n })\n }\n\n function onConnect(res, socket, head) {\n connectReq.removeAllListeners()\n socket.removeAllListeners()\n\n if (res.statusCode === 200) {\n assert.equal(head.length, 0)\n debug('tunneling connection has established')\n self.sockets[self.sockets.indexOf(placeholder)] = socket\n cb(socket)\n } else {\n debug('tunneling socket could not be established, statusCode=%d', res.statusCode)\n var error = new Error('tunneling socket could not be established, ' + 'statusCode=' + res.statusCode)\n error.code = 'ECONNRESET'\n options.request.emit('error', error)\n self.removeSocket(placeholder)\n }\n }\n\n function onError(cause) {\n connectReq.removeAllListeners()\n\n debug('tunneling socket could not be established, cause=%s\\n', cause.message, cause.stack)\n var error = new Error('tunneling socket could not be established, ' + 'cause=' + cause.message)\n error.code = 'ECONNRESET'\n options.request.emit('error', error)\n self.removeSocket(placeholder)\n }\n}\n\nTunnelingAgent.prototype.removeSocket = function removeSocket(socket) {\n var pos = this.sockets.indexOf(socket)\n if (pos === -1) return\n\n this.sockets.splice(pos, 1)\n\n var pending = this.requests.shift()\n if (pending) {\n // If we have pending requests and a socket gets closed a new one\n // needs to be created to take over in the pool for the one that closed.\n this.createConnection(pending)\n }\n}\n\nfunction createSecureSocket(options, cb) {\n var self = this\n TunnelingAgent.prototype.createSocket.call(self, options, function(socket) {\n // 0 is dummy port for v0.6\n var secureSocket = tls.connect(0, mergeOptions({}, self.options,\n { servername: options.host\n , socket: socket\n }\n ))\n self.sockets[self.sockets.indexOf(socket)] = secureSocket\n cb(secureSocket)\n })\n}\n\n\nfunction mergeOptions(target) {\n for (var i = 1, len = arguments.length; i < len; ++i) {\n var overrides = arguments[i]\n if (typeof overrides === 'object') {\n var keys = Object.keys(overrides)\n for (var j = 0, keyLen = keys.length; j < keyLen; ++j) {\n var k = keys[j]\n if (overrides[k] !== undefined) {\n target[k] = overrides[k]\n }\n }\n }\n }\n return target\n}\n\n\nvar debug\nif (process.env.NODE_DEBUG && /\\btunnel\\b/.test(process.env.NODE_DEBUG)) {\n debug = function() {\n var args = Array.prototype.slice.call(arguments)\n if (typeof args[0] === 'string') {\n args[0] = 'TUNNEL: ' + args[0]\n } else {\n args.unshift('TUNNEL:')\n }\n console.error.apply(console, args)\n }\n} else {\n debug = function() {}\n}\nexports.debug = debug // for test\n","import t from\"decompress-response\";import e from\"follow-redirects\";import o from\"http\";import r from\"https\";import n from\"progress-stream\";import s from\"querystring\";import{Readable as c}from\"stream\";import a from\"url\";import*as p from\"tunnel-agent\";function i(t){return Object.keys(t||{}).reduce(((e,o)=>(e[o.toLowerCase()]=t[o],e)),{})}function u(t){return t.replace(/^\\.*/,\".\").toLowerCase()}function d(t){const e=t.trim().toLowerCase(),o=e.split(\":\",2);return{hostname:u(o[0]),port:o[1],hasPort:e.indexOf(\":\")>-1}}const h=[\"protocol\",\"slashes\",\"auth\",\"host\",\"port\",\"hostname\",\"hash\",\"search\",\"query\",\"pathname\",\"path\",\"href\"],l=[\"accept\",\"accept-charset\",\"accept-encoding\",\"accept-language\",\"accept-ranges\",\"cache-control\",\"content-encoding\",\"content-language\",\"content-location\",\"content-md5\",\"content-range\",\"content-type\",\"connection\",\"date\",\"expect\",\"max-forwards\",\"pragma\",\"referer\",\"te\",\"user-agent\",\"via\"],m=[\"proxy-authorization\"],f=t=>null!==t&&\"object\"==typeof t&&\"function\"==typeof t.pipe,y=\"node\";class b extends Error{request;code;constructor(t,e){super(t.message),this.request=e,this.code=t.code}}const g=(t,e,o,r)=>({body:r,url:e,method:o,headers:t.headers,statusCode:t.statusCode,statusMessage:t.statusMessage}),x=(x,w)=>{const{options:O}=x,T=Object.assign({},a.parse(O.url));if(\"function\"==typeof fetch&&O.fetch){const t=new AbortController,e=x.applyMiddleware(\"finalizeOptions\",{...T,method:O.method,headers:{...\"object\"==typeof O.fetch&&O.fetch.headers?i(O.fetch.headers):{},...i(O.headers)},maxRedirects:O.maxRedirects}),o={credentials:O.withCredentials?\"include\":\"omit\",...\"object\"==typeof O.fetch?O.fetch:{},method:e.method,headers:e.headers,body:O.body,signal:t.signal},r=x.applyMiddleware(\"interceptRequest\",void 0,{adapter:y,context:x});if(r){const t=setTimeout(w,0,null,r);return{abort:()=>clearTimeout(t)}}const n=fetch(O.url,o);return x.applyMiddleware(\"onRequest\",{options:O,adapter:y,request:n,context:x}),n.then((async t=>{const e=O.rawBody?t.body:await t.text(),o={};t.headers.forEach(((t,e)=>{o[e]=t})),w(null,{body:e,url:t.url,method:O.method,headers:o,statusCode:t.status,statusMessage:t.statusText})})).catch((t=>{\"AbortError\"!=t.name&&w(t)})),{abort:()=>t.abort()}}const v=f(O.body)?\"stream\":typeof O.body;if(\"undefined\"!==v&&\"stream\"!==v&&\"string\"!==v&&!Buffer.isBuffer(O.body))throw new Error(`Request body must be a string, buffer or stream, got ${v}`);const R={};O.bodySize?R[\"content-length\"]=O.bodySize:O.body&&\"stream\"!==v&&(R[\"content-length\"]=Buffer.byteLength(O.body));let j=!1;const q=(t,e)=>!j&&w(t,e);x.channels.abort.subscribe((()=>{j=!0}));let C=Object.assign({},T,{method:O.method,headers:Object.assign({},i(O.headers),R),maxRedirects:O.maxRedirects});const $=function(t){let e;return e=t.hasOwnProperty(\"proxy\")?t.proxy:function(t){const e=process.env.NO_PROXY||process.env.no_proxy||\"\";return\"*\"===e||\"\"!==e&&function(t,e){const o=t.port||(\"https:\"===t.protocol?\"443\":\"80\"),r=u(t.hostname);return e.split(\",\").map(d).some((t=>{const e=r.indexOf(t.hostname),n=e>-1&&e===r.length-t.hostname.length;return t.hasPort?o===t.port&&n:n}))}(t,e)?null:\"http:\"===t.protocol?process.env.HTTP_PROXY||process.env.http_proxy||null:\"https:\"===t.protocol&&(process.env.HTTPS_PROXY||process.env.https_proxy||process.env.HTTP_PROXY||process.env.http_proxy)||null}(a.parse(t.url)),\"string\"==typeof e?a.parse(e):e}(O),E=$&&function(t){return typeof t.tunnel<\"u\"?!!t.tunnel:\"https:\"===a.parse(t.url).protocol}(O),L=x.applyMiddleware(\"interceptRequest\",void 0,{adapter:y,context:x});if(L){const t=setImmediate(q,null,L);return{abort:()=>clearImmediate(t)}}if(0!==O.maxRedirects&&(C.maxRedirects=O.maxRedirects||5),$&&E?C=function(t={},e){const o=Object.assign({},t),r=l.concat(o.proxyHeaderWhiteList||[]).map((t=>t.toLowerCase())),n=m.concat(o.proxyHeaderExclusiveList||[]).map((t=>t.toLowerCase())),s=(c=o.headers,a=r,Object.keys(c).filter((t=>-1!==a.indexOf(t.toLowerCase()))).reduce(((t,e)=>(t[e]=c[e],t)),{}));var c,a;s.host=function(t){const e=t.port,o=t.protocol;let r=`${t.hostname}:`;return r+=e||(\"https:\"===o?\"443\":\"80\"),r}(o),o.headers=Object.keys(o.headers||{}).reduce(((t,e)=>(-1===n.indexOf(e.toLowerCase())&&(t[e]=o.headers[e]),t)),{});const i=function(t,e){const o=function(t){return h.reduce(((e,o)=>(e[o]=t[o],e)),{})}(t),r=function(t,e){return`${\"https:\"===t.protocol?\"https\":\"http\"}Over${\"https:\"===e.protocol?\"Https\":\"Http\"}`}(o,e);return p[r]}(o,e),u=function(t,e,o){return{proxy:{host:e.hostname,port:+e.port,proxyAuth:e.auth,headers:o},headers:t.headers,ca:t.ca,cert:t.cert,key:t.key,passphrase:t.passphrase,pfx:t.pfx,ciphers:t.ciphers,rejectUnauthorized:t.rejectUnauthorized,secureOptions:t.secureOptions,secureProtocol:t.secureProtocol}}(o,e,s);return o.agent=i(u),o}(C,$):$&&!E&&(C=function(t,e,o){const r=t.headers||{},n=Object.assign({},t,{headers:r});return r.host=r.host||function(t){const e=t.port||(\"https:\"===t.protocol?\"443\":\"80\");return`${t.hostname}:${e}`}(e),n.protocol=o.protocol||n.protocol,n.hostname=o.host.replace(/:\\d+/,\"\"),n.port=o.port,n.host=function(t){let e=t.host;return t.port&&(\"80\"===t.port&&\"http:\"===t.protocol||\"443\"===t.port&&\"https:\"===t.protocol)&&(e=t.hostname),e}(Object.assign({},e,o)),n.href=`${n.protocol}//${n.host}${n.path}`,n.path=a.format(e),n}(C,T,$)),!E&&$&&$.auth&&!C.headers[\"proxy-authorization\"]){const[t,e]=$.auth.username?[$.auth.username,$.auth.password]:$.auth.split(\":\").map((t=>s.unescape(t))),o=Buffer.from(`${t}:${e}`,\"utf8\").toString(\"base64\");C.headers[\"proxy-authorization\"]=`Basic ${o}`}const P=function(t,n,s){const c=\"https:\"===t.protocol,a=0===t.maxRedirects?{http:o,https:r}:{http:e.http,https:e.https};if(!n||s)return c?a.https:a.http;let p=443===n.port;return n.protocol&&(p=/^https:?/.test(n.protocol)),p?a.https:a.http}(C,$,E);\"function\"==typeof O.debug&&$&&O.debug(\"Proxying using %s\",C.agent?\"tunnel agent\":`${C.host}:${C.port}`);const z=\"HEAD\"!==C.method;let M;z&&!C.headers[\"accept-encoding\"]&&!1!==O.compress&&(C.headers[\"accept-encoding\"]=typeof Bun<\"u\"?\"gzip, deflate\":\"br, gzip, deflate\");const k=x.applyMiddleware(\"finalizeOptions\",C),S=P.request(k,(e=>{const o=z?t(e):e;M=o;const r=x.applyMiddleware(\"onHeaders\",o,{headers:e.headers,adapter:y,context:x}),n=\"responseUrl\"in e?e.responseUrl:O.url;O.stream?q(null,g(o,n,C.method,r)):function(t,e){const o=[];t.on(\"data\",(function(t){o.push(t)})),t.once(\"end\",(function(){e&&e(null,Buffer.concat(o)),e=null})),t.once(\"error\",(function(t){e&&e(t),e=null}))}(r,((t,e)=>{if(t)return q(t);const r=O.rawBody?e:e.toString(),s=g(o,n,C.method,r);return q(null,s)}))}));function B(t){M&&M.destroy(t),S.destroy(t)}S.once(\"socket\",(t=>{t.once(\"error\",B),S.once(\"response\",(e=>{e.once(\"end\",(()=>{t.removeListener(\"error\",B)}))}))})),S.once(\"error\",(t=>{M||q(new b(t,S))})),O.timeout&&function(t,e){if(t.timeoutTimer)return t;const o=isNaN(e)?e:{socket:e,connect:e},r=t.getHeader(\"host\"),n=r?\" to \"+r:\"\";function s(){t.timeoutTimer&&(clearTimeout(t.timeoutTimer),t.timeoutTimer=null)}function c(e){if(s(),void 0!==o.socket){const r=()=>{const t=new Error(\"Socket timed out on request\"+n);t.code=\"ESOCKETTIMEDOUT\",e.destroy(t)};e.setTimeout(o.socket,r),t.once(\"response\",(t=>{t.once(\"end\",(()=>{e.removeListener(\"timeout\",r)}))}))}}void 0!==o.connect&&(t.timeoutTimer=setTimeout((function(){const e=new Error(\"Connection timed out on request\"+n);e.code=\"ETIMEDOUT\",t.destroy(e)}),o.connect)),t.on(\"socket\",(function(t){t.connecting?t.once(\"connect\",(()=>c(t))):c(t)})),t.on(\"error\",s)}(S,O.timeout);const{bodyStream:H,progress:_}=function(t){if(!t.body)return{};const e=f(t.body),o=t.bodySize||(e?null:Buffer.byteLength(t.body));if(!o)return e?{bodyStream:t.body}:{};const r=n({time:16,length:o});return{bodyStream:(e?t.body:c.from(t.body)).pipe(r),progress:r}}(O);return x.applyMiddleware(\"onRequest\",{options:O,adapter:y,request:S,context:x,progress:_}),H?H.pipe(S):S.end(O.body),{abort:()=>S.abort()}};export{b as N,y as a,x as h};//# sourceMappingURL=node-request.js.map\n","import{c as e}from\"./_chunks-es/createRequester.js\";import{h as s}from\"./_chunks-es/node-request.js\";import{a as r}from\"./_chunks-es/node-request.js\";const o=(r=[],o=s)=>e(r,o),t=\"node\";export{r as adapter,t as environment,o as getIt};//# sourceMappingURL=index.js.map\n","'use strict';\n\nconst denyList = new Set([\n\t'ENOTFOUND',\n\t'ENETUNREACH',\n\n\t// SSL errors from https://github.com/nodejs/node/blob/fc8e3e2cdc521978351de257030db0076d79e0ab/src/crypto/crypto_common.cc#L301-L328\n\t'UNABLE_TO_GET_ISSUER_CERT',\n\t'UNABLE_TO_GET_CRL',\n\t'UNABLE_TO_DECRYPT_CERT_SIGNATURE',\n\t'UNABLE_TO_DECRYPT_CRL_SIGNATURE',\n\t'UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY',\n\t'CERT_SIGNATURE_FAILURE',\n\t'CRL_SIGNATURE_FAILURE',\n\t'CERT_NOT_YET_VALID',\n\t'CERT_HAS_EXPIRED',\n\t'CRL_NOT_YET_VALID',\n\t'CRL_HAS_EXPIRED',\n\t'ERROR_IN_CERT_NOT_BEFORE_FIELD',\n\t'ERROR_IN_CERT_NOT_AFTER_FIELD',\n\t'ERROR_IN_CRL_LAST_UPDATE_FIELD',\n\t'ERROR_IN_CRL_NEXT_UPDATE_FIELD',\n\t'OUT_OF_MEM',\n\t'DEPTH_ZERO_SELF_SIGNED_CERT',\n\t'SELF_SIGNED_CERT_IN_CHAIN',\n\t'UNABLE_TO_GET_ISSUER_CERT_LOCALLY',\n\t'UNABLE_TO_VERIFY_LEAF_SIGNATURE',\n\t'CERT_CHAIN_TOO_LONG',\n\t'CERT_REVOKED',\n\t'INVALID_CA',\n\t'PATH_LENGTH_EXCEEDED',\n\t'INVALID_PURPOSE',\n\t'CERT_UNTRUSTED',\n\t'CERT_REJECTED',\n\t'HOSTNAME_MISMATCH'\n]);\n\n// TODO: Use `error?.code` when targeting Node.js 14\nmodule.exports = error => !denyList.has(error && error.code);\n","import{Agent as e}from\"http\";import{Agent as t}from\"https\";import{g as s}from\"./_chunks-es/_commonjsHelpers.js\";import r from\"tty\";import n from\"util\";import{p as o,v as i}from\"./_chunks-es/defaultOptionsValidator.js\";import c from\"progress-stream\";import a from\"is-retry-allowed\";import{N as u}from\"./_chunks-es/node-request.js\";const p=/^https:/i;function l(s){const r=new e(s),n=new t(s),o={http:r,https:n};return{finalizeOptions:e=>{if(e.agent)return e;if(e.maxRedirects>0)return{...e,agents:o};const t=p.test(e.href||e.protocol);return{...e,agent:t?n:r}}}}const d=/^\\//,f=/\\/$/;function m(e){const t=e.replace(f,\"\");return{processOptions:e=>{if(/^https?:\\/\\//i.test(e.url))return e;const s=[t,e.url.replace(d,\"\")].join(\"/\");return Object.assign({},e,{url:s})}}}var h,C,g,b,y,w={exports:{}},O={exports:{}};function F(){return b?g:(b=1,g=function(e){function t(e){let r,n,o,i=null;function c(...e){if(!c.enabled)return;const s=c,n=Number(/* @__PURE__ */new Date),o=n-(r||n);s.diff=o,s.prev=r,s.curr=n,r=n,e[0]=t.coerce(e[0]),\"string\"!=typeof e[0]&&e.unshift(\"%O\");let i=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((r,n)=>{if(\"%%\"===r)return\"%\";i++;const o=t.formatters[n];if(\"function\"==typeof o){const t=e[i];r=o.call(s,t),e.splice(i,1),i--}return r})),t.formatArgs.call(s,e),(s.log||t.log).apply(s,e)}return c.namespace=e,c.useColors=t.useColors(),c.color=t.selectColor(e),c.extend=s,c.destroy=t.destroy,Object.defineProperty(c,\"enabled\",{enumerable:!0,configurable:!1,get:()=>null!==i?i:(n!==t.namespaces&&(n=t.namespaces,o=t.enabled(e)),o),set:e=>{i=e}}),\"function\"==typeof t.init&&t.init(c),c}function s(e,s){const r=t(this.namespace+(typeof s>\"u\"?\":\":s)+e);return r.log=this.log,r}function r(e,t){let s=0,r=0,n=-1,o=0;for(;s<e.length;)if(r<t.length&&(t[r]===e[s]||\"*\"===t[r]))\"*\"===t[r]?(n=r,o=s,r++):(s++,r++);else{if(-1===n)return!1;r=n+1,o++,s=o}for(;r<t.length&&\"*\"===t[r];)r++;return r===t.length}return t.debug=t,t.default=t,t.coerce=function(e){return e instanceof Error?e.stack||e.message:e},t.disable=function(){const e=[...t.names,...t.skips.map((e=>\"-\"+e))].join(\",\");return t.enable(\"\"),e},t.enable=function(e){t.save(e),t.namespaces=e,t.names=[],t.skips=[];const s=(\"string\"==typeof e?e:\"\").trim().replace(\" \",\",\").split(\",\").filter(Boolean);for(const e of s)\"-\"===e[0]?t.skips.push(e.slice(1)):t.names.push(e)},t.enabled=function(e){for(const s of t.skips)if(r(e,s))return!1;for(const s of t.names)if(r(e,s))return!0;return!1},t.humanize=function(){if(C)return h;C=1;var e=1e3,t=60*e,s=60*t,r=24*s,n=7*r;function o(e,t,s,r){var n=t>=1.5*s;return Math.round(e/s)+\" \"+r+(n?\"s\":\"\")}return h=function(i,c){c=c||{};var a,u,p=typeof i;if(\"string\"===p&&i.length>0)return function(o){if(!((o=String(o)).length>100)){var i=/^(-?(?:\\d+)?\\.?\\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(o);if(i){var c=parseFloat(i[1]);switch((i[2]||\"ms\").toLowerCase()){case\"years\":case\"year\":case\"yrs\":case\"yr\":case\"y\":return 315576e5*c;case\"weeks\":case\"week\":case\"w\":return c*n;case\"days\":case\"day\":case\"d\":return c*r;case\"hours\":case\"hour\":case\"hrs\":case\"hr\":case\"h\":return c*s;case\"minutes\":case\"minute\":case\"mins\":case\"min\":case\"m\":return c*t;case\"seconds\":case\"second\":case\"secs\":case\"sec\":case\"s\":return c*e;case\"milliseconds\":case\"millisecond\":case\"msecs\":case\"msec\":case\"ms\":return c;default:return}}}}(i);if(\"number\"===p&&isFinite(i))return c.long?(a=i,(u=Math.abs(a))>=r?o(a,u,r,\"day\"):u>=s?o(a,u,s,\"hour\"):u>=t?o(a,u,t,\"minute\"):u>=e?o(a,u,e,\"second\"):a+\" ms\"):function(n){var o=Math.abs(n);return o>=r?Math.round(n/r)+\"d\":o>=s?Math.round(n/s)+\"h\":o>=t?Math.round(n/t)+\"m\":o>=e?Math.round(n/e)+\"s\":n+\"ms\"}(i);throw new Error(\"val is not a non-empty string or a valid number. val=\"+JSON.stringify(i))}}(),t.destroy=function(){console.warn(\"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.\")},Object.keys(e).forEach((s=>{t[s]=e[s]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let s=0;for(let t=0;t<e.length;t++)s=(s<<5)-s+e.charCodeAt(t),s|=0;return t.colors[Math.abs(s)%t.colors.length]},t.enable(t.load()),t})}var v,j,x,E,k={exports:{}},R=/* @__PURE__ */s((E||(E=1,typeof process>\"u\"||\"renderer\"===process.type||!0===process.browser||process.__nwjs?w.exports=(y||(y=1,function(e,t){t.formatArgs=function(t){if(t[0]=(this.useColors?\"%c\":\"\")+this.namespace+(this.useColors?\" %c\":\" \")+t[0]+(this.useColors?\"%c \":\" \")+\"+\"+e.exports.humanize(this.diff),!this.useColors)return;const s=\"color: \"+this.color;t.splice(1,0,s,\"color: inherit\");let r=0,n=0;t[0].replace(/%[a-zA-Z%]/g,(e=>{\"%%\"!==e&&(r++,\"%c\"===e&&(n=r))})),t.splice(n,0,s)},t.save=function(e){try{e?t.storage.setItem(\"debug\",e):t.storage.removeItem(\"debug\")}catch{}},t.load=function(){let e;try{e=t.storage.getItem(\"debug\")}catch{}return!e&&typeof process<\"u\"&&\"env\"in process&&(e=process.env.DEBUG),e},t.useColors=function(){if(typeof window<\"u\"&&window.process&&(\"renderer\"===window.process.type||window.process.__nwjs))return!0;if(typeof navigator<\"u\"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\\/(\\d+)/))return!1;let e;return typeof document<\"u\"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<\"u\"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<\"u\"&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\\/(\\d+)/))&&parseInt(e[1],10)>=31||typeof navigator<\"u\"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\\/(\\d+)/)},t.storage=function(){try{return localStorage}catch{}}(),t.destroy=/* @__PURE__ */(()=>{let e=!1;return()=>{e||(e=!0,console.warn(\"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.\"))}})(),t.colors=[\"#0000CC\",\"#0000FF\",\"#0033CC\",\"#0033FF\",\"#0066CC\",\"#0066FF\",\"#0099CC\",\"#0099FF\",\"#00CC00\",\"#00CC33\",\"#00CC66\",\"#00CC99\",\"#00CCCC\",\"#00CCFF\",\"#3300CC\",\"#3300FF\",\"#3333CC\",\"#3333FF\",\"#3366CC\",\"#3366FF\",\"#3399CC\",\"#3399FF\",\"#33CC00\",\"#33CC33\",\"#33CC66\",\"#33CC99\",\"#33CCCC\",\"#33CCFF\",\"#6600CC\",\"#6600FF\",\"#6633CC\",\"#6633FF\",\"#66CC00\",\"#66CC33\",\"#9900CC\",\"#9900FF\",\"#9933CC\",\"#9933FF\",\"#99CC00\",\"#99CC33\",\"#CC0000\",\"#CC0033\",\"#CC0066\",\"#CC0099\",\"#CC00CC\",\"#CC00FF\",\"#CC3300\",\"#CC3333\",\"#CC3366\",\"#CC3399\",\"#CC33CC\",\"#CC33FF\",\"#CC6600\",\"#CC6633\",\"#CC9900\",\"#CC9933\",\"#CCCC00\",\"#CCCC33\",\"#FF0000\",\"#FF0033\",\"#FF0066\",\"#FF0099\",\"#FF00CC\",\"#FF00FF\",\"#FF3300\",\"#FF3333\",\"#FF3366\",\"#FF3399\",\"#FF33CC\",\"#FF33FF\",\"#FF6600\",\"#FF6633\",\"#FF9900\",\"#FF9933\",\"#FFCC00\",\"#FFCC33\"],t.log=console.debug||console.log||(()=>{}),e.exports=F()(t);const{formatters:s}=e.exports;s.j=function(e){try{return JSON.stringify(e)}catch(e){return\"[UnexpectedJSONParseError]: \"+e.message}}}(O,O.exports)),O.exports):w.exports=(x||(x=1,function(e,t){const s=r,o=n;t.init=function(e){e.inspectOpts={};const s=Object.keys(t.inspectOpts);for(let r=0;r<s.length;r++)e.inspectOpts[s[r]]=t.inspectOpts[s[r]]},t.log=function(...e){return process.stderr.write(o.formatWithOptions(t.inspectOpts,...e)+\"\\n\")},t.formatArgs=function(s){const{namespace:r,useColors:n}=this;if(n){const t=this.color,n=\"\u001b[3\"+(t<8?t:\"8;5;\"+t),o=` ${n};1m${r} \u001b[0m`;s[0]=o+s[0].split(\"\\n\").join(\"\\n\"+o),s.push(n+\"m+\"+e.exports.humanize(this.diff)+\"\u001b[0m\")}else s[0]=(t.inspectOpts.hideDate?\"\":/* @__PURE__ */(new Date).toISOString()+\" \")+r+\" \"+s[0]},t.save=function(e){e?process.env.DEBUG=e:delete process.env.DEBUG},t.load=function(){return process.env.DEBUG},t.useColors=function(){return\"colors\"in t.inspectOpts?!!t.inspectOpts.colors:s.isatty(process.stderr.fd)},t.destroy=o.deprecate((()=>{}),\"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.\"),t.colors=[6,2,3,4,5,1];try{const e=function(){if(j)return v;j=1;const e=function(){const e=/(Chrome|Chromium)\\/(?<chromeVersion>\\d+)\\./.exec(navigator.userAgent);if(e)return Number.parseInt(e.groups.chromeVersion,10)}()>=69&&{level:1,hasBasic:!0,has256:!1,has16m:!1};return v={stdout:e,stderr:e}}();e&&(e.stderr||e).level>=2&&(t.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}t.inspectOpts=Object.keys(process.env).filter((e=>/^debug_/i.test(e))).reduce(((e,t)=>{const s=t.substring(6).toLowerCase().replace(/_([a-z])/g,((e,t)=>t.toUpperCase()));let r=process.env[t];return r=!!/^(yes|on|true|enabled)$/i.test(r)||!/^(no|off|false|disabled)$/i.test(r)&&(\"null\"===r?null:Number(r)),e[s]=r,e}),{}),e.exports=F()(t);const{formatters:i}=e.exports;i.o=function(e){return this.inspectOpts.colors=this.useColors,o.inspect(e,this.inspectOpts).split(\"\\n\").map((e=>e.trim())).join(\" \")},i.O=function(e){return this.inspectOpts.colors=this.useColors,o.inspect(e,this.inspectOpts)}}(k,k.exports)),k.exports)),w.exports));const A=[\"cookie\",\"authorization\"],q=Object.prototype.hasOwnProperty;function N(e={}){const t=e.verbose,s=e.namespace||\"get-it\",r=R(s),n=e.log||r,o=n===r&&!R.enabled(s);let i=0;return{processOptions:e=>(e.debug=n,e.requestId=e.requestId||++i,e),onRequest:s=>{if(o||!s)return s;const r=s.options;if(n(\"[%s] HTTP %s %s\",r.requestId,r.method,r.url),t&&r.body&&\"string\"==typeof r.body&&n(\"[%s] Request body: %s\",r.requestId,r.body),t&&r.headers){const t=!1===e.redactSensitiveHeaders?r.headers:((e,t)=>{const s={};for(const r in e)q.call(e,r)&&(s[r]=t.indexOf(r.toLowerCase())>-1?\"<redacted>\":e[r]);return s})(r.headers,A);n(\"[%s] Request headers: %s\",r.requestId,JSON.stringify(t,null,2))}return s},onResponse:(e,s)=>{if(o||!e)return e;const r=s.options.requestId;return n(\"[%s] Response code: %s %s\",r,e.statusCode,e.statusMessage),t&&e.body&&n(\"[%s] Response body: %s\",r,function(e){return-1!==(e.headers[\"content-type\"]||\"\").toLowerCase().indexOf(\"application/json\")?function(e){try{const t=\"string\"==typeof e?JSON.parse(e):e;return JSON.stringify(t,null,2)}catch{return e}}(e.body):e.body}(e)),e},onError:(e,t)=>{const s=t.options.requestId;return e?(n(\"[%s] ERROR: %s\",s,e.message),e):(n(\"[%s] Error encountered, but handled by an earlier middleware\",s),e)}}}function S(e,t={}){return{processOptions:s=>{const r=s.headers||{};return s.headers=t.override?Object.assign({},r,e):Object.assign({},e,r),s}}}class I extends Error{response;request;constructor(e,t){super();const s=e.url.length>400?`${e.url.slice(0,399)}…`:e.url;let r=`${e.method}-request to ${s} resulted in `;r+=`HTTP ${e.statusCode} ${e.statusMessage}`,this.message=r.trim(),this.response=e,this.request=t.options}}function $(){return{onResponse:(e,t)=>{if(!(e.statusCode>=400))return e;throw new I(e,t)}}}function _(e={}){if(\"function\"!=typeof e.inject)throw new Error(\"`injectResponse` middleware requires a `inject` function\");return{interceptRequest:function(t,s){const r=e.inject(s,t);if(!r)return t;const n=s.context.options;return{body:\"\",url:n.url,method:n.method,headers:{},statusCode:200,statusMessage:\"OK\",...r}}}}const T=typeof Buffer>\"u\"?()=>!1:e=>Buffer.isBuffer(e);function M(e){return\"[object Object]\"===Object.prototype.toString.call(e)}function P(e){if(!1===M(e))return!1;const t=e.constructor;if(void 0===t)return!0;const s=t.prototype;return!(!1===M(s)||!1===s.hasOwnProperty(\"isPrototypeOf\"))}const z=[\"boolean\",\"string\",\"number\"];function L(){return{processOptions:e=>{const t=e.body;return!t||\"function\"==typeof t.pipe||T(t)||-1===z.indexOf(typeof t)&&!Array.isArray(t)&&!P(t)?e:Object.assign({},e,{body:JSON.stringify(e.body),headers:Object.assign({},e.headers,{\"Content-Type\":\"application/json\"})})}}}function B(e){return{onResponse:s=>{const r=s.headers[\"content-type\"]||\"\",n=e&&e.force||-1!==r.indexOf(\"application/json\");return s.body&&r&&n?Object.assign({},s,{body:t(s.body)}):s},processOptions:e=>Object.assign({},e,{headers:Object.assign({Accept:\"application/json\"},e.headers)})};function t(e){try{return JSON.parse(e)}catch(e){throw e.message=`Failed to parsed response body as JSON: ${e.message}`,e}}}function D(e={}){if(!e.ca)throw new Error('Required mtls option \"ca\" is missing');if(!e.cert)throw new Error('Required mtls option \"cert\" is missing');if(!e.key)throw new Error('Required mtls option \"key\" is missing');return{finalizeOptions:t=>{if(function(e){return\"object\"==typeof e&&null!==e&&!(\"protocol\"in e)}(t))return t;const s={cert:e.cert,key:e.key,ca:e.ca};return Object.assign({},t,s)}}}let J={};typeof globalThis<\"u\"?J=globalThis:typeof window<\"u\"?J=window:typeof global<\"u\"?J=global:typeof self<\"u\"&&(J=self);var U=J;function G(e={}){const t=e.implementation||U.Observable;if(!t)throw new Error(\"`Observable` is not available in global scope, and no implementation was passed\");return{onReturn:(e,s)=>new t((t=>(e.error.subscribe((e=>t.error(e))),e.progress.subscribe((e=>t.next(Object.assign({type:\"progress\"},e)))),e.response.subscribe((e=>{t.next(Object.assign({type:\"response\"},e)),t.complete()})),e.request.publish(s),()=>e.abort.publish())))}}function H(e){return t=>({stage:e,percent:t.percentage,total:t.length,loaded:t.transferred,lengthComputable:!(0===t.length&&0===t.percentage)})}function V(){return{onHeaders:(e,t)=>{const s=c({time:16}),r=H(\"download\"),n=e.headers[\"content-length\"],o=n?Number(n):0;return!isNaN(o)&&o>0&&s.setLength(o),s.on(\"progress\",(e=>t.context.channels.progress.publish(r(e)))),e.pipe(s)},onRequest:e=>{if(!e.progress)return;const t=H(\"upload\");e.progress.on(\"progress\",(s=>e.context.channels.progress.publish(t(s))))}}}const W=(e={})=>{const t=e.implementation||Promise;if(!t)throw new Error(\"`Promise` is not available in global scope, and no implementation was passed\");return{onReturn:(s,r)=>new t(((t,n)=>{const o=r.options.cancelToken;o&&o.promise.then((e=>{s.abort.publish(e),n(e)})),s.error.subscribe(n),s.response.subscribe((s=>{t(e.onlyBody?s.body:s)})),setTimeout((()=>{try{s.request.publish(r)}catch(e){n(e)}}),0)}))}};class Z{__CANCEL__=!0;message;constructor(e){this.message=e}toString(){return\"Cancel\"+(this.message?`: ${this.message}`:\"\")}}class K{promise;reason;constructor(e){if(\"function\"!=typeof e)throw new TypeError(\"executor must be a function.\");let t=null;this.promise=new Promise((e=>{t=e})),e((e=>{this.reason||(this.reason=new Z(e),t(this.reason))}))}static source=()=>{let e;return{token:new K((t=>{e=t})),cancel:e}}}function Q(e){if(!(!1===e||e&&e.host))throw new Error(\"Proxy middleware takes an object of host, port and auth properties\");return{processOptions:t=>Object.assign({proxy:e},t)}}W.Cancel=Z,W.CancelToken=K,W.isCancel=e=>!(!e||!e?.__CANCEL__);var X=(e,t,s)=>!(\"GET\"!==s.method&&\"HEAD\"!==s.method||e.response&&e.response.statusCode)&&a(e);function Y(e){return 100*Math.pow(2,e)+100*Math.random()}const ee=(e={})=>(e=>{const t=e.maxRetries||5,s=e.retryDelay||Y,r=e.shouldRetry;return{onError:(e,n)=>{const o=n.options,i=o.maxRetries||t,c=o.retryDelay||s,a=o.shouldRetry||r,u=o.attemptNumber||0;if(null!==(p=o.body)&&\"object\"==typeof p&&\"function\"==typeof p.pipe||!a(e,u,o)||u>=i)return e;var p;const l=Object.assign({},n,{options:Object.assign({},o,{attemptNumber:u+1})});return setTimeout((()=>n.channels.request.publish(l)),c(u)),null}}})({shouldRetry:X,...e});function te(e){const t=new URLSearchParams,s=(e,r)=>{const n=r instanceof Set?Array.from(r):r;if(Array.isArray(n))if(n.length)for(const t in n)s(`${e}[${t}]`,n[t]);else t.append(`${e}[]`,\"\");else if(\"object\"==typeof n&&null!==n)for(const[t,r]of Object.entries(n))s(`${e}[${t}]`,r);else t.append(e,n)};for(const[t,r]of Object.entries(e))s(t,r);return t.toString()}function se(){return{processOptions:e=>{const t=e.body;return t&&\"function\"!=typeof t.pipe&&!T(t)&&P(t)?{...e,body:te(e.body),headers:{...e.headers,\"Content-Type\":\"application/x-www-form-urlencoded\"}}:e}}}ee.shouldRetry=X;const re=(ne=l,function(e={}){const{maxRetries:t=3,ms:s=1e3,maxFree:r=256}=e,{finalizeOptions:n}=ne({keepAlive:!0,keepAliveMsecs:s,maxFreeSockets:r});return{finalizeOptions:n,onError:(e,s)=>{if((\"GET\"===s.options.method||\"POST\"===s.options.method)&&e instanceof u&&\"ECONNRESET\"===e.code&&e.request.reusedSocket){const e=s.options.attemptNumber||0;if(e<t){const t=Object.assign({},s,{options:Object.assign({},s.options,{attemptNumber:e+1})});return setImmediate((()=>s.channels.request.publish(t))),null}}return e}}});var ne;export{Z as Cancel,K as CancelToken,l as agent,m as base,N as debug,S as headers,$ as httpErrors,_ as injectResponse,L as jsonRequest,B as jsonResponse,re as keepAlive,D as mtls,G as observable,o as processOptions,V as progress,W as promise,Q as proxy,ee as retry,se as urlEncoded,i as validateOptions};//# sourceMappingURL=middleware.js.map\n","var s = { 0: 8203, 1: 8204, 2: 8205, 3: 8290, 4: 8291, 5: 8288, 6: 65279, 7: 8289, 8: 119155, 9: 119156, a: 119157, b: 119158, c: 119159, d: 119160, e: 119161, f: 119162 }, c = { 0: 8203, 1: 8204, 2: 8205, 3: 65279 }, u = new Array(4).fill(String.fromCodePoint(c[0])).join(\"\");\nfunction E(t) {\n let e = JSON.stringify(t);\n return `${u}${Array.from(e).map((r) => {\n let n = r.charCodeAt(0);\n if (n > 255) throw new Error(`Only ASCII edit info can be encoded. Error attempting to encode ${e} on character ${r} (${n})`);\n return Array.from(n.toString(4).padStart(4, \"0\")).map((o) => String.fromCodePoint(c[o])).join(\"\");\n }).join(\"\")}`;\n}\nfunction I(t) {\n return !Number.isNaN(Number(t)) || /[a-z]/i.test(t) && !/\\d+(?:[-:\\/]\\d+){2}(?:T\\d+(?:[-:\\/]\\d+){1,2}(\\.\\d+)?Z?)?/.test(t) ? !1 : !!Date.parse(t);\n}\nfunction T(t) {\n try {\n new URL(t, t.startsWith(\"/\") ? \"https://acme.com\" : void 0);\n } catch {\n return !1;\n }\n return !0;\n}\nfunction C(t, e, r = \"auto\") {\n return r === !0 || r === \"auto\" && (I(t) || T(t)) ? t : `${t}${E(e)}`;\n}\nObject.fromEntries(Object.entries(c).map((t) => t.reverse()));\nObject.fromEntries(Object.entries(s).map((t) => t.reverse()));\nvar S = `${Object.values(s).map((t) => `\\\\u{${t.toString(16)}}`).join(\"\")}`, f = new RegExp(`[${S}]{4,}`, \"gu\");\nfunction _(t) {\n var e;\n return { cleaned: t.replace(f, \"\"), encoded: ((e = t.match(f)) == null ? void 0 : e[0]) || \"\" };\n}\nfunction O(t) {\n return t && JSON.parse(_(JSON.stringify(t)).cleaned);\n}\nfunction stegaClean(result) {\n return O(result);\n}\nconst vercelStegaCleanAll = stegaClean;\nexport {\n C,\n stegaClean,\n vercelStegaCleanAll\n};\n//# sourceMappingURL=stegaClean.js.map\n","const BASE_URL = \"https://www.sanity.io/help/\";\nfunction generateHelpUrl(slug) {\n return BASE_URL + slug;\n}\nconst VALID_ASSET_TYPES = [\"image\", \"file\"], VALID_INSERT_LOCATIONS = [\"before\", \"after\", \"replace\"], dataset = (name) => {\n if (!/^(~[a-z0-9]{1}[-\\w]{0,63}|[a-z0-9]{1}[-\\w]{0,63})$/.test(name))\n throw new Error(\n \"Datasets can only contain lowercase characters, numbers, underscores and dashes, and start with tilde, and be maximum 64 characters\"\n );\n}, projectId = (id) => {\n if (!/^[-a-z0-9]+$/i.test(id))\n throw new Error(\"`projectId` can only contain only a-z, 0-9 and dashes\");\n}, validateAssetType = (type) => {\n if (VALID_ASSET_TYPES.indexOf(type) === -1)\n throw new Error(`Invalid asset type: ${type}. Must be one of ${VALID_ASSET_TYPES.join(\", \")}`);\n}, validateObject = (op, val) => {\n if (val === null || typeof val != \"object\" || Array.isArray(val))\n throw new Error(`${op}() takes an object of properties`);\n}, validateDocumentId = (op, id) => {\n if (typeof id != \"string\" || !/^[a-z0-9_][a-z0-9_.-]{0,127}$/i.test(id) || id.includes(\"..\"))\n throw new Error(`${op}(): \"${id}\" is not a valid document ID`);\n}, requireDocumentId = (op, doc) => {\n if (!doc._id)\n throw new Error(`${op}() requires that the document contains an ID (\"_id\" property)`);\n validateDocumentId(op, doc._id);\n}, validateInsert = (at, selector, items) => {\n const signature = \"insert(at, selector, items)\";\n if (VALID_INSERT_LOCATIONS.indexOf(at) === -1) {\n const valid = VALID_INSERT_LOCATIONS.map((loc) => `\"${loc}\"`).join(\", \");\n throw new Error(`${signature} takes an \"at\"-argument which is one of: ${valid}`);\n }\n if (typeof selector != \"string\")\n throw new Error(`${signature} takes a \"selector\"-argument which must be a string`);\n if (!Array.isArray(items))\n throw new Error(`${signature} takes an \"items\"-argument which must be an array`);\n}, hasDataset = (config) => {\n if (!config.dataset)\n throw new Error(\"`dataset` must be provided to perform queries\");\n return config.dataset || \"\";\n}, requestTag = (tag) => {\n if (typeof tag != \"string\" || !/^[a-z0-9._-]{1,75}$/i.test(tag))\n throw new Error(\n \"Tag can only contain alphanumeric characters, underscores, dashes and dots, and be between one and 75 characters long.\"\n );\n return tag;\n}, resourceConfig = (config) => {\n if (!config[\"~experimental_resource\"])\n throw new Error(\"`resource` must be provided to perform resource queries\");\n const { type, id } = config[\"~experimental_resource\"];\n switch (type) {\n case \"dataset\": {\n if (id.split(\".\").length !== 2)\n throw new Error('Dataset resource ID must be in the format \"project.dataset\"');\n return;\n }\n case \"dashboard\":\n case \"media-library\":\n case \"canvas\":\n return;\n default:\n throw new Error(`Unsupported resource type: ${type.toString()}`);\n }\n}, resourceGuard = (service, config) => {\n if (config[\"~experimental_resource\"])\n throw new Error(`\\`${service}\\` does not support resource-based operations`);\n};\nfunction once(fn) {\n let didCall = !1, returnValue;\n return (...args) => (didCall || (returnValue = fn(...args), didCall = !0), returnValue);\n}\nconst createWarningPrinter = (message) => (\n // eslint-disable-next-line no-console\n once((...args) => console.warn(message.join(\" \"), ...args))\n), printCdnAndWithCredentialsWarning = createWarningPrinter([\n \"Because you set `withCredentials` to true, we will override your `useCdn`\",\n \"setting to be false since (cookie-based) credentials are never set on the CDN\"\n]), printCdnWarning = createWarningPrinter([\n \"Since you haven't set a value for `useCdn`, we will deliver content using our\",\n \"global, edge-cached API-CDN. If you wish to have content delivered faster, set\",\n \"`useCdn: false` to use the Live API. Note: You may incur higher costs using the live API.\"\n]), printCdnPreviewDraftsWarning = createWarningPrinter([\n \"The Sanity client is configured with the `perspective` set to `drafts` or `previewDrafts`, which doesn't support the API-CDN.\",\n \"The Live API will be used instead. Set `useCdn: false` in your configuration to hide this warning.\"\n]), printPreviewDraftsDeprecationWarning = createWarningPrinter([\n \"The `previewDrafts` perspective has been renamed to `drafts` and will be removed in a future API version\"\n]), printBrowserTokenWarning = createWarningPrinter([\n \"You have configured Sanity client to use a token in the browser. This may cause unintentional security issues.\",\n `See ${generateHelpUrl(\n \"js-client-browser-token\"\n )} for more information and how to hide this warning.`\n]), printCredentialedTokenWarning = createWarningPrinter([\n \"You have configured Sanity client to use a token, but also provided `withCredentials: true`.\",\n \"This is no longer supported - only token will be used - remove `withCredentials: true`.\"\n]), printNoApiVersionSpecifiedWarning = createWarningPrinter([\n \"Using the Sanity client without specifying an API version is deprecated.\",\n `See ${generateHelpUrl(\"js-client-api-version\")}`\n]), printNoDefaultExport = createWarningPrinter([\n \"The default export of @sanity/client has been deprecated. Use the named export `createClient` instead.\"\n]), defaultCdnHost = \"apicdn.sanity.io\", defaultConfig = {\n apiHost: \"https://api.sanity.io\",\n apiVersion: \"1\",\n useProjectHostname: !0,\n stega: { enabled: !1 }\n}, LOCALHOSTS = [\"localhost\", \"127.0.0.1\", \"0.0.0.0\"], isLocal = (host) => LOCALHOSTS.indexOf(host) !== -1;\nfunction validateApiVersion(apiVersion) {\n if (apiVersion === \"1\" || apiVersion === \"X\")\n return;\n const apiDate = new Date(apiVersion);\n if (!(/^\\d{4}-\\d{2}-\\d{2}$/.test(apiVersion) && apiDate instanceof Date && apiDate.getTime() > 0))\n throw new Error(\"Invalid API version string, expected `1` or date in format `YYYY-MM-DD`\");\n}\nfunction validateApiPerspective(perspective) {\n if (Array.isArray(perspective) && perspective.length > 1 && perspective.includes(\"raw\"))\n throw new TypeError(\n 'Invalid API perspective value: \"raw\". The raw-perspective can not be combined with other perspectives'\n );\n}\nconst initConfig = (config, prevConfig) => {\n const specifiedConfig = {\n ...prevConfig,\n ...config,\n stega: {\n ...typeof prevConfig.stega == \"boolean\" ? { enabled: prevConfig.stega } : prevConfig.stega || defaultConfig.stega,\n ...typeof config.stega == \"boolean\" ? { enabled: config.stega } : config.stega || {}\n }\n };\n specifiedConfig.apiVersion || printNoApiVersionSpecifiedWarning();\n const newConfig = {\n ...defaultConfig,\n ...specifiedConfig\n }, projectBased = newConfig.useProjectHostname && !newConfig[\"~experimental_resource\"];\n if (typeof Promise > \"u\") {\n const helpUrl = generateHelpUrl(\"js-client-promise-polyfill\");\n throw new Error(`No native Promise-implementation found, polyfill needed - see ${helpUrl}`);\n }\n if (projectBased && !newConfig.projectId)\n throw new Error(\"Configuration must contain `projectId`\");\n if (newConfig[\"~experimental_resource\"] && resourceConfig(newConfig), typeof newConfig.perspective < \"u\" && validateApiPerspective(newConfig.perspective), \"encodeSourceMap\" in newConfig)\n throw new Error(\n \"It looks like you're using options meant for '@sanity/preview-kit/client'. 'encodeSourceMap' is not supported in '@sanity/client'. Did you mean 'stega.enabled'?\"\n );\n if (\"encodeSourceMapAtPath\" in newConfig)\n throw new Error(\n \"It looks like you're using options meant for '@sanity/preview-kit/client'. 'encodeSourceMapAtPath' is not supported in '@sanity/client'. Did you mean 'stega.filter'?\"\n );\n if (typeof newConfig.stega.enabled != \"boolean\")\n throw new Error(`stega.enabled must be a boolean, received ${newConfig.stega.enabled}`);\n if (newConfig.stega.enabled && newConfig.stega.studioUrl === void 0)\n throw new Error(\"stega.studioUrl must be defined when stega.enabled is true\");\n if (newConfig.stega.enabled && typeof newConfig.stega.studioUrl != \"string\" && typeof newConfig.stega.studioUrl != \"function\")\n throw new Error(\n `stega.studioUrl must be a string or a function, received ${newConfig.stega.studioUrl}`\n );\n const isBrowser = typeof window < \"u\" && window.location && window.location.hostname, isLocalhost = isBrowser && isLocal(window.location.hostname), hasToken = !!newConfig.token;\n newConfig.withCredentials && hasToken && (printCredentialedTokenWarning(), newConfig.withCredentials = !1), isBrowser && isLocalhost && hasToken && newConfig.ignoreBrowserTokenWarning !== !0 ? printBrowserTokenWarning() : typeof newConfig.useCdn > \"u\" && printCdnWarning(), projectBased && projectId(newConfig.projectId), newConfig.dataset && dataset(newConfig.dataset), \"requestTagPrefix\" in newConfig && (newConfig.requestTagPrefix = newConfig.requestTagPrefix ? requestTag(newConfig.requestTagPrefix).replace(/\\.+$/, \"\") : void 0), newConfig.apiVersion = `${newConfig.apiVersion}`.replace(/^v/, \"\"), newConfig.isDefaultApi = newConfig.apiHost === defaultConfig.apiHost, newConfig.useCdn === !0 && newConfig.withCredentials && printCdnAndWithCredentialsWarning(), newConfig.useCdn = newConfig.useCdn !== !1 && !newConfig.withCredentials, validateApiVersion(newConfig.apiVersion);\n const hostParts = newConfig.apiHost.split(\"://\", 2), protocol = hostParts[0], host = hostParts[1], cdnHost = newConfig.isDefaultApi ? defaultCdnHost : host;\n return projectBased ? (newConfig.url = `${protocol}://${newConfig.projectId}.${host}/v${newConfig.apiVersion}`, newConfig.cdnUrl = `${protocol}://${newConfig.projectId}.${cdnHost}/v${newConfig.apiVersion}`) : (newConfig.url = `${newConfig.apiHost}/v${newConfig.apiVersion}`, newConfig.cdnUrl = newConfig.url), newConfig;\n};\nexport {\n dataset,\n defaultConfig,\n hasDataset,\n initConfig,\n printCdnPreviewDraftsWarning,\n printNoDefaultExport,\n printPreviewDraftsDeprecationWarning,\n requestTag,\n requireDocumentId,\n resourceConfig,\n resourceGuard,\n validateApiPerspective,\n validateAssetType,\n validateDocumentId,\n validateInsert,\n validateObject\n};\n//# sourceMappingURL=config.js.map\n","import { getIt } from \"get-it\";\nimport { adapter, environment } from \"get-it\";\nimport { retry, jsonRequest, jsonResponse, progress, observable, debug, headers, agent } from \"get-it/middleware\";\nimport { Observable, defer, of, isObservable, mergeMap, from, lastValueFrom, shareReplay, catchError, concat, throwError, timer, tap, finalize, share, merge, EMPTY } from \"rxjs\";\nimport { stegaClean } from \"./_chunks-es/stegaClean.js\";\nimport { combineLatestWith, map, filter, finalize as finalize$1 } from \"rxjs/operators\";\nimport { validateObject, validateInsert, requireDocumentId, validateDocumentId, resourceConfig, hasDataset, requestTag, printPreviewDraftsDeprecationWarning, validateApiPerspective, printCdnPreviewDraftsWarning, validateAssetType, resourceGuard, dataset, defaultConfig, initConfig, printNoDefaultExport } from \"./_chunks-es/config.js\";\nclass ClientError extends Error {\n response;\n statusCode = 400;\n responseBody;\n details;\n constructor(res) {\n const props = extractErrorProps(res);\n super(props.message), Object.assign(this, props);\n }\n}\nclass ServerError extends Error {\n response;\n statusCode = 500;\n responseBody;\n details;\n constructor(res) {\n const props = extractErrorProps(res);\n super(props.message), Object.assign(this, props);\n }\n}\nfunction extractErrorProps(res) {\n const body = res.body, props = {\n response: res,\n statusCode: res.statusCode,\n responseBody: stringifyBody(body, res),\n message: \"\",\n details: void 0\n };\n if (body.error && body.message)\n return props.message = `${body.error} - ${body.message}`, props;\n if (isMutationError(body) || isActionError(body)) {\n const allItems = body.error.items || [], items = allItems.slice(0, 5).map((item) => item.error?.description).filter(Boolean);\n let itemsStr = items.length ? `:\n- ${items.join(`\n- `)}` : \"\";\n return allItems.length > 5 && (itemsStr += `\n...and ${allItems.length - 5} more`), props.message = `${body.error.description}${itemsStr}`, props.details = body.error, props;\n }\n return body.error && body.error.description ? (props.message = body.error.description, props.details = body.error, props) : (props.message = body.error || body.message || httpErrorMessage(res), props);\n}\nfunction isMutationError(body) {\n return isPlainObject(body) && isPlainObject(body.error) && body.error.type === \"mutationError\" && typeof body.error.description == \"string\";\n}\nfunction isActionError(body) {\n return isPlainObject(body) && isPlainObject(body.error) && body.error.type === \"actionError\" && typeof body.error.description == \"string\";\n}\nfunction isPlainObject(obj) {\n return typeof obj == \"object\" && obj !== null && !Array.isArray(obj);\n}\nfunction httpErrorMessage(res) {\n const statusMessage = res.statusMessage ? ` ${res.statusMessage}` : \"\";\n return `${res.method}-request to ${res.url} resulted in HTTP ${res.statusCode}${statusMessage}`;\n}\nfunction stringifyBody(body, res) {\n return (res.headers[\"content-type\"] || \"\").toLowerCase().indexOf(\"application/json\") !== -1 ? JSON.stringify(body, null, 2) : body;\n}\nclass CorsOriginError extends Error {\n projectId;\n addOriginUrl;\n constructor({ projectId }) {\n super(\"CorsOriginError\"), this.name = \"CorsOriginError\", this.projectId = projectId;\n const url = new URL(`https://sanity.io/manage/project/${projectId}/api`);\n if (typeof location < \"u\") {\n const { origin } = location;\n url.searchParams.set(\"cors\", \"add\"), url.searchParams.set(\"origin\", origin), this.addOriginUrl = url, this.message = `The current origin is not allowed to connect to the Live Content API. Add it here: ${url}`;\n } else\n this.message = `The current origin is not allowed to connect to the Live Content API. Change your configuration here: ${url}`;\n }\n}\nconst httpError = {\n onResponse: (res) => {\n if (res.statusCode >= 500)\n throw new ServerError(res);\n if (res.statusCode >= 400)\n throw new ClientError(res);\n return res;\n }\n};\nfunction printWarnings() {\n const seen = {};\n return {\n onResponse: (res) => {\n const warn = res.headers[\"x-sanity-warning\"], warnings = Array.isArray(warn) ? warn : [warn];\n for (const msg of warnings)\n !msg || seen[msg] || (seen[msg] = !0, console.warn(msg));\n return res;\n }\n };\n}\nfunction defineHttpRequest(envMiddleware) {\n return getIt([\n retry({ shouldRetry }),\n ...envMiddleware,\n printWarnings(),\n jsonRequest(),\n jsonResponse(),\n progress(),\n httpError,\n observable({ implementation: Observable })\n ]);\n}\nfunction shouldRetry(err, attempt, options) {\n if (options.maxRetries === 0) return !1;\n const isSafe = options.method === \"GET\" || options.method === \"HEAD\", isQuery2 = (options.uri || options.url).startsWith(\"/data/query\"), isRetriableResponse = err.response && (err.response.statusCode === 429 || err.response.statusCode === 502 || err.response.statusCode === 503);\n return (isSafe || isQuery2) && isRetriableResponse ? !0 : retry.shouldRetry(err, attempt, options);\n}\nclass ConnectionFailedError extends Error {\n name = \"ConnectionFailedError\";\n}\nclass DisconnectError extends Error {\n name = \"DisconnectError\";\n reason;\n constructor(message, reason, options = {}) {\n super(message, options), this.reason = reason;\n }\n}\nclass ChannelError extends Error {\n name = \"ChannelError\";\n data;\n constructor(message, data) {\n super(message), this.data = data;\n }\n}\nclass MessageError extends Error {\n name = \"MessageError\";\n data;\n constructor(message, data, options = {}) {\n super(message, options), this.data = data;\n }\n}\nclass MessageParseError extends Error {\n name = \"MessageParseError\";\n}\nconst REQUIRED_EVENTS = [\"channelError\", \"disconnect\"];\nfunction connectEventSource(initEventSource, events) {\n return defer(() => {\n const es = initEventSource();\n return isObservable(es) ? es : of(es);\n }).pipe(mergeMap((es) => connectWithESInstance(es, events)));\n}\nfunction connectWithESInstance(es, events) {\n return new Observable((observer) => {\n const emitOpen = events.includes(\"open\"), emitReconnect = events.includes(\"reconnect\");\n function onError(evt) {\n if (\"data\" in evt) {\n const [parseError, event] = parseEvent(evt);\n observer.error(\n parseError ? new MessageParseError(\"Unable to parse EventSource error message\", { cause: event }) : new MessageError((event?.data).message, event)\n );\n return;\n }\n es.readyState === es.CLOSED ? observer.error(new ConnectionFailedError(\"EventSource connection failed\")) : emitReconnect && observer.next({ type: \"reconnect\" });\n }\n function onOpen() {\n observer.next({ type: \"open\" });\n }\n function onMessage(message) {\n const [parseError, event] = parseEvent(message);\n if (parseError) {\n observer.error(\n new MessageParseError(\"Unable to parse EventSource message\", { cause: parseError })\n );\n return;\n }\n if (message.type === \"channelError\") {\n observer.error(new ChannelError(extractErrorMessage(event?.data), event.data));\n return;\n }\n if (message.type === \"disconnect\") {\n observer.error(\n new DisconnectError(\n `Server disconnected client: ${event.data?.reason || \"unknown error\"}`\n )\n );\n return;\n }\n observer.next({\n type: message.type,\n id: message.lastEventId,\n ...event.data ? { data: event.data } : {}\n });\n }\n es.addEventListener(\"error\", onError), emitOpen && es.addEventListener(\"open\", onOpen);\n const cleanedEvents = [.../* @__PURE__ */ new Set([...REQUIRED_EVENTS, ...events])].filter((type) => type !== \"error\" && type !== \"open\" && type !== \"reconnect\");\n return cleanedEvents.forEach((type) => es.addEventListener(type, onMessage)), () => {\n es.removeEventListener(\"error\", onError), emitOpen && es.removeEventListener(\"open\", onOpen), cleanedEvents.forEach((type) => es.removeEventListener(type, onMessage)), es.close();\n };\n });\n}\nfunction parseEvent(message) {\n try {\n const data = typeof message.data == \"string\" && JSON.parse(message.data);\n return [\n null,\n {\n type: message.type,\n id: message.lastEventId,\n ...isEmptyObject(data) ? {} : { data }\n }\n ];\n } catch (err) {\n return [err, null];\n }\n}\nfunction extractErrorMessage(err) {\n return err.error ? err.error.description ? err.error.description : typeof err.error == \"string\" ? err.error : JSON.stringify(err.error, null, 2) : err.message || \"Unknown listener error\";\n}\nfunction isEmptyObject(data) {\n for (const _ in data)\n return !1;\n return !0;\n}\nfunction getSelection(sel) {\n if (typeof sel == \"string\")\n return { id: sel };\n if (Array.isArray(sel))\n return { query: \"*[_id in $ids]\", params: { ids: sel } };\n if (typeof sel == \"object\" && sel !== null && \"query\" in sel && typeof sel.query == \"string\")\n return \"params\" in sel && typeof sel.params == \"object\" && sel.params !== null ? { query: sel.query, params: sel.params } : { query: sel.query };\n const selectionOpts = [\n \"* Document ID (<docId>)\",\n \"* Array of document IDs\",\n \"* Object containing `query`\"\n ].join(`\n`);\n throw new Error(`Unknown selection - must be one of:\n\n${selectionOpts}`);\n}\nclass BasePatch {\n selection;\n operations;\n constructor(selection, operations = {}) {\n this.selection = selection, this.operations = operations;\n }\n /**\n * Sets the given attributes to the document. Does NOT merge objects.\n * The operation is added to the current patch, ready to be commited by `commit()`\n *\n * @param attrs - Attributes to set. To set a deep attribute, use JSONMatch, eg: \\{\"nested.prop\": \"value\"\\}\n */\n set(attrs) {\n return this._assign(\"set\", attrs);\n }\n /**\n * Sets the given attributes to the document if they are not currently set. Does NOT merge objects.\n * The operation is added to the current patch, ready to be commited by `commit()`\n *\n * @param attrs - Attributes to set. To set a deep attribute, use JSONMatch, eg: \\{\"nested.prop\": \"value\"\\}\n */\n setIfMissing(attrs) {\n return this._assign(\"setIfMissing\", attrs);\n }\n /**\n * Performs a \"diff-match-patch\" operation on the string attributes provided.\n * The operation is added to the current patch, ready to be commited by `commit()`\n *\n * @param attrs - Attributes to perform operation on. To set a deep attribute, use JSONMatch, eg: \\{\"nested.prop\": \"dmp\"\\}\n */\n diffMatchPatch(attrs) {\n return validateObject(\"diffMatchPatch\", attrs), this._assign(\"diffMatchPatch\", attrs);\n }\n /**\n * Unsets the attribute paths provided.\n * The operation is added to the current patch, ready to be commited by `commit()`\n *\n * @param attrs - Attribute paths to unset.\n */\n unset(attrs) {\n if (!Array.isArray(attrs))\n throw new Error(\"unset(attrs) takes an array of attributes to unset, non-array given\");\n return this.operations = Object.assign({}, this.operations, { unset: attrs }), this;\n }\n /**\n * Increment a numeric value. Each entry in the argument is either an attribute or a JSON path. The value may be a positive or negative integer or floating-point value. The operation will fail if target value is not a numeric value, or doesn't exist.\n *\n * @param attrs - Object of attribute paths to increment, values representing the number to increment by.\n */\n inc(attrs) {\n return this._assign(\"inc\", attrs);\n }\n /**\n * Decrement a numeric value. Each entry in the argument is either an attribute or a JSON path. The value may be a positive or negative integer or floating-point value. The operation will fail if target value is not a numeric value, or doesn't exist.\n *\n * @param attrs - Object of attribute paths to decrement, values representing the number to decrement by.\n */\n dec(attrs) {\n return this._assign(\"dec\", attrs);\n }\n /**\n * Provides methods for modifying arrays, by inserting, appending and replacing elements via a JSONPath expression.\n *\n * @param at - Location to insert at, relative to the given selector, or 'replace' the matched path\n * @param selector - JSONPath expression, eg `comments[-1]` or `blocks[_key==\"abc123\"]`\n * @param items - Array of items to insert/replace\n */\n insert(at, selector, items) {\n return validateInsert(at, selector, items), this._assign(\"insert\", { [at]: selector, items });\n }\n /**\n * Append the given items to the array at the given JSONPath\n *\n * @param selector - Attribute/path to append to, eg `comments` or `person.hobbies`\n * @param items - Array of items to append to the array\n */\n append(selector, items) {\n return this.insert(\"after\", `${selector}[-1]`, items);\n }\n /**\n * Prepend the given items to the array at the given JSONPath\n *\n * @param selector - Attribute/path to prepend to, eg `comments` or `person.hobbies`\n * @param items - Array of items to prepend to the array\n */\n prepend(selector, items) {\n return this.insert(\"before\", `${selector}[0]`, items);\n }\n /**\n * Change the contents of an array by removing existing elements and/or adding new elements.\n *\n * @param selector - Attribute or JSONPath expression for array\n * @param start - Index at which to start changing the array (with origin 0). If greater than the length of the array, actual starting index will be set to the length of the array. If negative, will begin that many elements from the end of the array (with origin -1) and will be set to 0 if absolute value is greater than the length of the array.x\n * @param deleteCount - An integer indicating the number of old array elements to remove.\n * @param items - The elements to add to the array, beginning at the start index. If you don't specify any elements, splice() will only remove elements from the array.\n */\n splice(selector, start, deleteCount, items) {\n const delAll = typeof deleteCount > \"u\" || deleteCount === -1, startIndex = start < 0 ? start - 1 : start, delCount = delAll ? -1 : Math.max(0, start + deleteCount), delRange = startIndex < 0 && delCount >= 0 ? \"\" : delCount, rangeSelector = `${selector}[${startIndex}:${delRange}]`;\n return this.insert(\"replace\", rangeSelector, items || []);\n }\n /**\n * Adds a revision clause, preventing the document from being patched if the `_rev` property does not match the given value\n *\n * @param rev - Revision to lock the patch to\n */\n ifRevisionId(rev) {\n return this.operations.ifRevisionID = rev, this;\n }\n /**\n * Return a plain JSON representation of the patch\n */\n serialize() {\n return { ...getSelection(this.selection), ...this.operations };\n }\n /**\n * Return a plain JSON representation of the patch\n */\n toJSON() {\n return this.serialize();\n }\n /**\n * Clears the patch of all operations\n */\n reset() {\n return this.operations = {}, this;\n }\n _assign(op, props, merge2 = !0) {\n return validateObject(op, props), this.operations = Object.assign({}, this.operations, {\n [op]: Object.assign({}, merge2 && this.operations[op] || {}, props)\n }), this;\n }\n _set(op, props) {\n return this._assign(op, props, !1);\n }\n}\nclass ObservablePatch extends BasePatch {\n #client;\n constructor(selection, operations, client) {\n super(selection, operations), this.#client = client;\n }\n /**\n * Clones the patch\n */\n clone() {\n return new ObservablePatch(this.selection, { ...this.operations }, this.#client);\n }\n commit(options) {\n if (!this.#client)\n throw new Error(\n \"No `client` passed to patch, either provide one or pass the patch to a clients `mutate()` method\"\n );\n const returnFirst = typeof this.selection == \"string\", opts = Object.assign({ returnFirst, returnDocuments: !0 }, options);\n return this.#client.mutate({ patch: this.serialize() }, opts);\n }\n}\nclass Patch extends BasePatch {\n #client;\n constructor(selection, operations, client) {\n super(selection, operations), this.#client = client;\n }\n /**\n * Clones the patch\n */\n clone() {\n return new Patch(this.selection, { ...this.operations }, this.#client);\n }\n commit(options) {\n if (!this.#client)\n throw new Error(\n \"No `client` passed to patch, either provide one or pass the patch to a clients `mutate()` method\"\n );\n const returnFirst = typeof this.selection == \"string\", opts = Object.assign({ returnFirst, returnDocuments: !0 }, options);\n return this.#client.mutate({ patch: this.serialize() }, opts);\n }\n}\nconst defaultMutateOptions = { returnDocuments: !1 };\nclass BaseTransaction {\n operations;\n trxId;\n constructor(operations = [], transactionId) {\n this.operations = operations, this.trxId = transactionId;\n }\n /**\n * Creates a new Sanity document. If `_id` is provided and already exists, the mutation will fail. If no `_id` is given, one will automatically be generated by the database.\n * The operation is added to the current transaction, ready to be commited by `commit()`\n *\n * @param doc - Document to create. Requires a `_type` property.\n */\n create(doc) {\n return validateObject(\"create\", doc), this._add({ create: doc });\n }\n /**\n * Creates a new Sanity document. If a document with the same `_id` already exists, the create operation will be ignored.\n * The operation is added to the current transaction, ready to be commited by `commit()`\n *\n * @param doc - Document to create if it does not already exist. Requires `_id` and `_type` properties.\n */\n createIfNotExists(doc) {\n const op = \"createIfNotExists\";\n return validateObject(op, doc), requireDocumentId(op, doc), this._add({ [op]: doc });\n }\n /**\n * Creates a new Sanity document, or replaces an existing one if the same `_id` is already used.\n * The operation is added to the current transaction, ready to be commited by `commit()`\n *\n * @param doc - Document to create or replace. Requires `_id` and `_type` properties.\n */\n createOrReplace(doc) {\n const op = \"createOrReplace\";\n return validateObject(op, doc), requireDocumentId(op, doc), this._add({ [op]: doc });\n }\n /**\n * Deletes the document with the given document ID\n * The operation is added to the current transaction, ready to be commited by `commit()`\n *\n * @param documentId - Document ID to delete\n */\n delete(documentId) {\n return validateDocumentId(\"delete\", documentId), this._add({ delete: { id: documentId } });\n }\n transactionId(id) {\n return id ? (this.trxId = id, this) : this.trxId;\n }\n /**\n * Return a plain JSON representation of the transaction\n */\n serialize() {\n return [...this.operations];\n }\n /**\n * Return a plain JSON representation of the transaction\n */\n toJSON() {\n return this.serialize();\n }\n /**\n * Clears the transaction of all operations\n */\n reset() {\n return this.operations = [], this;\n }\n _add(mut) {\n return this.operations.push(mut), this;\n }\n}\nclass Transaction extends BaseTransaction {\n #client;\n constructor(operations, client, transactionId) {\n super(operations, transactionId), this.#client = client;\n }\n /**\n * Clones the transaction\n */\n clone() {\n return new Transaction([...this.operations], this.#client, this.trxId);\n }\n commit(options) {\n if (!this.#client)\n throw new Error(\n \"No `client` passed to transaction, either provide one or pass the transaction to a clients `mutate()` method\"\n );\n return this.#client.mutate(\n this.serialize(),\n Object.assign({ transactionId: this.trxId }, defaultMutateOptions, options || {})\n );\n }\n patch(patchOrDocumentId, patchOps) {\n const isBuilder = typeof patchOps == \"function\", isPatch = typeof patchOrDocumentId != \"string\" && patchOrDocumentId instanceof Patch, isMutationSelection = typeof patchOrDocumentId == \"object\" && (\"query\" in patchOrDocumentId || \"id\" in patchOrDocumentId);\n if (isPatch)\n return this._add({ patch: patchOrDocumentId.serialize() });\n if (isBuilder) {\n const patch = patchOps(new Patch(patchOrDocumentId, {}, this.#client));\n if (!(patch instanceof Patch))\n throw new Error(\"function passed to `patch()` must return the patch\");\n return this._add({ patch: patch.serialize() });\n }\n if (isMutationSelection) {\n const patch = new Patch(patchOrDocumentId, patchOps || {}, this.#client);\n return this._add({ patch: patch.serialize() });\n }\n return this._add({ patch: { id: patchOrDocumentId, ...patchOps } });\n }\n}\nclass ObservableTransaction extends BaseTransaction {\n #client;\n constructor(operations, client, transactionId) {\n super(operations, transactionId), this.#client = client;\n }\n /**\n * Clones the transaction\n */\n clone() {\n return new ObservableTransaction([...this.operations], this.#client, this.trxId);\n }\n commit(options) {\n if (!this.#client)\n throw new Error(\n \"No `client` passed to transaction, either provide one or pass the transaction to a clients `mutate()` method\"\n );\n return this.#client.mutate(\n this.serialize(),\n Object.assign({ transactionId: this.trxId }, defaultMutateOptions, options || {})\n );\n }\n patch(patchOrDocumentId, patchOps) {\n const isBuilder = typeof patchOps == \"function\";\n if (typeof patchOrDocumentId != \"string\" && patchOrDocumentId instanceof ObservablePatch)\n return this._add({ patch: patchOrDocumentId.serialize() });\n if (isBuilder) {\n const patch = patchOps(new ObservablePatch(patchOrDocumentId, {}, this.#client));\n if (!(patch instanceof ObservablePatch))\n throw new Error(\"function passed to `patch()` must return the patch\");\n return this._add({ patch: patch.serialize() });\n }\n return this._add({ patch: { id: patchOrDocumentId, ...patchOps } });\n }\n}\nconst projectHeader = \"X-Sanity-Project-ID\";\nfunction requestOptions(config, overrides = {}) {\n const headers2 = {}, token = overrides.token || config.token;\n token && (headers2.Authorization = `Bearer ${token}`), !overrides.useGlobalApi && !config.useProjectHostname && config.projectId && (headers2[projectHeader] = config.projectId);\n const withCredentials = !!(typeof overrides.withCredentials > \"u\" ? config.withCredentials : overrides.withCredentials), timeout = typeof overrides.timeout > \"u\" ? config.timeout : overrides.timeout;\n return Object.assign({}, overrides, {\n headers: Object.assign({}, headers2, overrides.headers || {}),\n timeout: typeof timeout > \"u\" ? 5 * 60 * 1e3 : timeout,\n proxy: overrides.proxy || config.proxy,\n json: !0,\n withCredentials,\n fetch: typeof overrides.fetch == \"object\" && typeof config.fetch == \"object\" ? { ...config.fetch, ...overrides.fetch } : overrides.fetch || config.fetch\n });\n}\nconst encodeQueryString = ({\n query,\n params = {},\n options = {}\n}) => {\n const searchParams = new URLSearchParams(), { tag, includeMutations, returnQuery, ...opts } = options;\n tag && searchParams.append(\"tag\", tag), searchParams.append(\"query\", query);\n for (const [key, value] of Object.entries(params))\n searchParams.append(`$${key}`, JSON.stringify(value));\n for (const [key, value] of Object.entries(opts))\n value && searchParams.append(key, `${value}`);\n return returnQuery === !1 && searchParams.append(\"returnQuery\", \"false\"), includeMutations === !1 && searchParams.append(\"includeMutations\", \"false\"), `?${searchParams}`;\n}, excludeFalsey = (param, defValue) => param === !1 ? void 0 : typeof param > \"u\" ? defValue : param, getMutationQuery = (options = {}) => ({\n dryRun: options.dryRun,\n returnIds: !0,\n returnDocuments: excludeFalsey(options.returnDocuments, !0),\n visibility: options.visibility || \"sync\",\n autoGenerateArrayKeys: options.autoGenerateArrayKeys,\n skipCrossDatasetReferenceValidation: options.skipCrossDatasetReferenceValidation\n}), isResponse = (event) => event.type === \"response\", getBody = (event) => event.body, indexBy = (docs, attr) => docs.reduce((indexed, doc) => (indexed[attr(doc)] = doc, indexed), /* @__PURE__ */ Object.create(null)), getQuerySizeLimit = 11264;\nfunction _fetch(client, httpRequest, _stega, query, _params = {}, options = {}) {\n const stega = \"stega\" in options ? {\n ..._stega || {},\n ...typeof options.stega == \"boolean\" ? { enabled: options.stega } : options.stega || {}\n } : _stega, params = stega.enabled ? stegaClean(_params) : _params, mapResponse = options.filterResponse === !1 ? (res) => res : (res) => res.result, { cache, next, ...opts } = {\n // Opt out of setting a `signal` on an internal `fetch` if one isn't provided.\n // This is necessary in React Server Components to avoid opting out of Request Memoization.\n useAbortSignal: typeof options.signal < \"u\",\n // Set `resultSourceMap' when stega is enabled, as it's required for encoding.\n resultSourceMap: stega.enabled ? \"withKeyArraySelector\" : options.resultSourceMap,\n ...options,\n // Default to not returning the query, unless `filterResponse` is `false`,\n // or `returnQuery` is explicitly set. `true` is the default in Content Lake, so skip if truthy\n returnQuery: options.filterResponse === !1 && options.returnQuery !== !1\n }, reqOpts = typeof cache < \"u\" || typeof next < \"u\" ? { ...opts, fetch: { cache, next } } : opts, $request = _dataRequest(client, httpRequest, \"query\", { query, params }, reqOpts);\n return stega.enabled ? $request.pipe(\n combineLatestWith(\n from(\n import(\"./_chunks-es/stegaEncodeSourceMap.js\").then(function(n) {\n return n.stegaEncodeSourceMap$1;\n }).then(\n ({ stegaEncodeSourceMap }) => stegaEncodeSourceMap\n )\n )\n ),\n map(\n ([res, stegaEncodeSourceMap]) => {\n const result = stegaEncodeSourceMap(res.result, res.resultSourceMap, stega);\n return mapResponse({ ...res, result });\n }\n )\n ) : $request.pipe(map(mapResponse));\n}\nfunction _getDocument(client, httpRequest, id, opts = {}) {\n const options = {\n uri: _getDataUrl(client, \"doc\", id),\n json: !0,\n tag: opts.tag,\n signal: opts.signal\n };\n return _requestObservable(client, httpRequest, options).pipe(\n filter(isResponse),\n map((event) => event.body.documents && event.body.documents[0])\n );\n}\nfunction _getDocuments(client, httpRequest, ids, opts = {}) {\n const options = {\n uri: _getDataUrl(client, \"doc\", ids.join(\",\")),\n json: !0,\n tag: opts.tag,\n signal: opts.signal\n };\n return _requestObservable(client, httpRequest, options).pipe(\n filter(isResponse),\n map((event) => {\n const indexed = indexBy(event.body.documents || [], (doc) => doc._id);\n return ids.map((id) => indexed[id] || null);\n })\n );\n}\nfunction _createIfNotExists(client, httpRequest, doc, options) {\n return requireDocumentId(\"createIfNotExists\", doc), _create(client, httpRequest, doc, \"createIfNotExists\", options);\n}\nfunction _createOrReplace(client, httpRequest, doc, options) {\n return requireDocumentId(\"createOrReplace\", doc), _create(client, httpRequest, doc, \"createOrReplace\", options);\n}\nfunction _delete(client, httpRequest, selection, options) {\n return _dataRequest(\n client,\n httpRequest,\n \"mutate\",\n { mutations: [{ delete: getSelection(selection) }] },\n options\n );\n}\nfunction _mutate(client, httpRequest, mutations, options) {\n let mut;\n mutations instanceof Patch || mutations instanceof ObservablePatch ? mut = { patch: mutations.serialize() } : mutations instanceof Transaction || mutations instanceof ObservableTransaction ? mut = mutations.serialize() : mut = mutations;\n const muts = Array.isArray(mut) ? mut : [mut], transactionId = options && options.transactionId || void 0;\n return _dataRequest(client, httpRequest, \"mutate\", { mutations: muts, transactionId }, options);\n}\nfunction _action(client, httpRequest, actions, options) {\n const acts = Array.isArray(actions) ? actions : [actions], transactionId = options && options.transactionId || void 0, skipCrossDatasetReferenceValidation = options && options.skipCrossDatasetReferenceValidation || void 0, dryRun = options && options.dryRun || void 0;\n return _dataRequest(\n client,\n httpRequest,\n \"actions\",\n { actions: acts, transactionId, skipCrossDatasetReferenceValidation, dryRun },\n options\n );\n}\nfunction _dataRequest(client, httpRequest, endpoint, body, options = {}) {\n const isMutation = endpoint === \"mutate\", isAction = endpoint === \"actions\", isQuery2 = endpoint === \"query\", strQuery = isMutation || isAction ? \"\" : encodeQueryString(body), useGet = !isMutation && !isAction && strQuery.length < getQuerySizeLimit, stringQuery = useGet ? strQuery : \"\", returnFirst = options.returnFirst, { timeout, token, tag, headers: headers2, returnQuery, lastLiveEventId, cacheMode } = options, uri = _getDataUrl(client, endpoint, stringQuery), reqOptions = {\n method: useGet ? \"GET\" : \"POST\",\n uri,\n json: !0,\n body: useGet ? void 0 : body,\n query: isMutation && getMutationQuery(options),\n timeout,\n headers: headers2,\n token,\n tag,\n returnQuery,\n perspective: options.perspective,\n resultSourceMap: options.resultSourceMap,\n lastLiveEventId: Array.isArray(lastLiveEventId) ? lastLiveEventId[0] : lastLiveEventId,\n cacheMode,\n canUseCdn: isQuery2,\n signal: options.signal,\n fetch: options.fetch,\n useAbortSignal: options.useAbortSignal,\n useCdn: options.useCdn\n };\n return _requestObservable(client, httpRequest, reqOptions).pipe(\n filter(isResponse),\n map(getBody),\n map((res) => {\n if (!isMutation)\n return res;\n const results = res.results || [];\n if (options.returnDocuments)\n return returnFirst ? results[0] && results[0].document : results.map((mut) => mut.document);\n const key = returnFirst ? \"documentId\" : \"documentIds\", ids = returnFirst ? results[0] && results[0].id : results.map((mut) => mut.id);\n return {\n transactionId: res.transactionId,\n results,\n [key]: ids\n };\n })\n );\n}\nfunction _create(client, httpRequest, doc, op, options = {}) {\n const mutation = { [op]: doc }, opts = Object.assign({ returnFirst: !0, returnDocuments: !0 }, options);\n return _dataRequest(client, httpRequest, \"mutate\", { mutations: [mutation] }, opts);\n}\nconst hasDataConfig = (client) => client.config().dataset !== void 0 && client.config().projectId !== void 0 || client.config()[\"~experimental_resource\"] !== void 0, isQuery = (client, uri) => hasDataConfig(client) && uri.startsWith(_getDataUrl(client, \"query\")), isMutate = (client, uri) => hasDataConfig(client) && uri.startsWith(_getDataUrl(client, \"mutate\")), isDoc = (client, uri) => hasDataConfig(client) && uri.startsWith(_getDataUrl(client, \"doc\", \"\")), isListener = (client, uri) => hasDataConfig(client) && uri.startsWith(_getDataUrl(client, \"listen\")), isHistory = (client, uri) => hasDataConfig(client) && uri.startsWith(_getDataUrl(client, \"history\", \"\")), isData = (client, uri) => uri.startsWith(\"/data/\") || isQuery(client, uri) || isMutate(client, uri) || isDoc(client, uri) || isListener(client, uri) || isHistory(client, uri);\nfunction _requestObservable(client, httpRequest, options) {\n const uri = options.url || options.uri, config = client.config(), canUseCdn = typeof options.canUseCdn > \"u\" ? [\"GET\", \"HEAD\"].indexOf(options.method || \"GET\") >= 0 && isData(client, uri) : options.canUseCdn;\n let useCdn = (options.useCdn ?? config.useCdn) && canUseCdn;\n const tag = options.tag && config.requestTagPrefix ? [config.requestTagPrefix, options.tag].join(\".\") : options.tag || config.requestTagPrefix;\n if (tag && options.tag !== null && (options.query = { tag: requestTag(tag), ...options.query }), [\"GET\", \"HEAD\", \"POST\"].indexOf(options.method || \"GET\") >= 0 && isQuery(client, uri)) {\n const resultSourceMap = options.resultSourceMap ?? config.resultSourceMap;\n resultSourceMap !== void 0 && resultSourceMap !== !1 && (options.query = { resultSourceMap, ...options.query });\n const perspectiveOption = options.perspective || config.perspective;\n typeof perspectiveOption < \"u\" && (perspectiveOption === \"previewDrafts\" && printPreviewDraftsDeprecationWarning(), validateApiPerspective(perspectiveOption), options.query = {\n perspective: Array.isArray(perspectiveOption) ? perspectiveOption.join(\",\") : perspectiveOption,\n ...options.query\n }, (Array.isArray(perspectiveOption) && perspectiveOption.length > 0 || // previewDrafts was renamed to drafts, but keep for backwards compat\n perspectiveOption === \"previewDrafts\" || perspectiveOption === \"drafts\") && useCdn && (useCdn = !1, printCdnPreviewDraftsWarning())), options.lastLiveEventId && (options.query = { ...options.query, lastLiveEventId: options.lastLiveEventId }), options.returnQuery === !1 && (options.query = { returnQuery: \"false\", ...options.query }), useCdn && options.cacheMode == \"noStale\" && (options.query = { cacheMode: \"noStale\", ...options.query });\n }\n const reqOptions = requestOptions(\n config,\n Object.assign({}, options, {\n url: _getUrl(client, uri, useCdn)\n })\n ), request = new Observable(\n (subscriber) => httpRequest(reqOptions, config.requester).subscribe(subscriber)\n );\n return options.signal ? request.pipe(_withAbortSignal(options.signal)) : request;\n}\nfunction _request(client, httpRequest, options) {\n return _requestObservable(client, httpRequest, options).pipe(\n filter((event) => event.type === \"response\"),\n map((event) => event.body)\n );\n}\nfunction _getDataUrl(client, operation, path) {\n const config = client.config();\n if (config[\"~experimental_resource\"]) {\n resourceConfig(config);\n const resourceBase = resourceDataBase(config), uri2 = path !== void 0 ? `${operation}/${path}` : operation;\n return `${resourceBase}/${uri2}`.replace(/\\/($|\\?)/, \"$1\");\n }\n const catalog = hasDataset(config), baseUri = `/${operation}/${catalog}`;\n return `/data${path !== void 0 ? `${baseUri}/${path}` : baseUri}`.replace(/\\/($|\\?)/, \"$1\");\n}\nfunction _getUrl(client, uri, canUseCdn = !1) {\n const { url, cdnUrl } = client.config();\n return `${canUseCdn ? cdnUrl : url}/${uri.replace(/^\\//, \"\")}`;\n}\nfunction _withAbortSignal(signal) {\n return (input) => new Observable((observer) => {\n const abort = () => observer.error(_createAbortError(signal));\n if (signal && signal.aborted) {\n abort();\n return;\n }\n const subscription = input.subscribe(observer);\n return signal.addEventListener(\"abort\", abort), () => {\n signal.removeEventListener(\"abort\", abort), subscription.unsubscribe();\n };\n });\n}\nconst isDomExceptionSupported = !!globalThis.DOMException;\nfunction _createAbortError(signal) {\n if (isDomExceptionSupported)\n return new DOMException(signal?.reason ?? \"The operation was aborted.\", \"AbortError\");\n const error = new Error(signal?.reason ?? \"The operation was aborted.\");\n return error.name = \"AbortError\", error;\n}\nconst resourceDataBase = (config) => {\n if (!config[\"~experimental_resource\"])\n throw new Error(\"`resource` must be provided to perform resource queries\");\n const { type, id } = config[\"~experimental_resource\"];\n switch (type) {\n case \"dataset\": {\n const segments = id.split(\".\");\n if (segments.length !== 2)\n throw new Error('Dataset ID must be in the format \"project.dataset\"');\n return `/projects/${segments[0]}/datasets/${segments[1]}`;\n }\n case \"canvas\":\n return `/canvases/${id}`;\n case \"media-library\":\n return `/media-libraries/${id}`;\n case \"dashboard\":\n return `/dashboards/${id}`;\n default:\n throw new Error(`Unsupported resource type: ${type.toString()}`);\n }\n};\nclass ObservableAssetsClient {\n #client;\n #httpRequest;\n constructor(client, httpRequest) {\n this.#client = client, this.#httpRequest = httpRequest;\n }\n upload(assetType, body, options) {\n return _upload(this.#client, this.#httpRequest, assetType, body, options);\n }\n}\nclass AssetsClient {\n #client;\n #httpRequest;\n constructor(client, httpRequest) {\n this.#client = client, this.#httpRequest = httpRequest;\n }\n upload(assetType, body, options) {\n const observable2 = _upload(this.#client, this.#httpRequest, assetType, body, options);\n return lastValueFrom(\n observable2.pipe(\n filter((event) => event.type === \"response\"),\n map(\n (event) => event.body.document\n )\n )\n );\n }\n}\nfunction _upload(client, httpRequest, assetType, body, opts = {}) {\n validateAssetType(assetType);\n let meta = opts.extract || void 0;\n meta && !meta.length && (meta = [\"none\"]);\n const config = client.config(), options = optionsFromFile(opts, body), { tag, label, title, description, creditLine, filename, source } = options, query = {\n label,\n title,\n description,\n filename,\n meta,\n creditLine\n };\n return source && (query.sourceId = source.id, query.sourceName = source.name, query.sourceUrl = source.url), _requestObservable(client, httpRequest, {\n tag,\n method: \"POST\",\n timeout: options.timeout || 0,\n uri: buildAssetUploadUrl(config, assetType),\n headers: options.contentType ? { \"Content-Type\": options.contentType } : {},\n query,\n body\n });\n}\nfunction buildAssetUploadUrl(config, assetType) {\n const assetTypeEndpoint = assetType === \"image\" ? \"images\" : \"files\";\n if (config[\"~experimental_resource\"]) {\n const { type, id } = config[\"~experimental_resource\"];\n switch (type) {\n case \"dataset\":\n throw new Error(\n \"Assets are not supported for dataset resources, yet. Configure the client with `{projectId: <projectId>, dataset: <datasetId>}` instead.\"\n );\n case \"canvas\":\n return `/canvases/${id}/assets/${assetTypeEndpoint}`;\n case \"media-library\":\n return `/media-libraries/${id}/upload`;\n case \"dashboard\":\n return `/dashboards/${id}/assets/${assetTypeEndpoint}`;\n default:\n throw new Error(`Unsupported resource type: ${type.toString()}`);\n }\n }\n const dataset2 = hasDataset(config);\n return `assets/${assetTypeEndpoint}/${dataset2}`;\n}\nfunction optionsFromFile(opts, file) {\n return typeof File > \"u\" || !(file instanceof File) ? opts : Object.assign(\n {\n filename: opts.preserveFilename === !1 ? void 0 : file.name,\n contentType: file.type\n },\n opts\n );\n}\nvar defaults = (obj, defaults2) => Object.keys(defaults2).concat(Object.keys(obj)).reduce((target, prop) => (target[prop] = typeof obj[prop] > \"u\" ? defaults2[prop] : obj[prop], target), {});\nconst pick = (obj, props) => props.reduce((selection, prop) => (typeof obj[prop] > \"u\" || (selection[prop] = obj[prop]), selection), {}), eventSourcePolyfill = defer(() => import(\"@sanity/eventsource\")).pipe(\n map(({ default: EventSource2 }) => EventSource2),\n shareReplay(1)\n);\nfunction reconnectOnConnectionFailure() {\n return function(source) {\n return source.pipe(\n catchError((err, caught) => err instanceof ConnectionFailedError ? concat(of({ type: \"reconnect\" }), timer(1e3).pipe(mergeMap(() => caught))) : throwError(() => err))\n );\n };\n}\nconst MAX_URL_LENGTH = 14800, possibleOptions = [\n \"includePreviousRevision\",\n \"includeResult\",\n \"includeMutations\",\n \"includeAllVersions\",\n \"visibility\",\n \"effectFormat\",\n \"tag\"\n], defaultOptions = {\n includeResult: !0\n};\nfunction _listen(query, params, opts = {}) {\n const { url, token, withCredentials, requestTagPrefix } = this.config(), tag = opts.tag && requestTagPrefix ? [requestTagPrefix, opts.tag].join(\".\") : opts.tag, options = { ...defaults(opts, defaultOptions), tag }, listenOpts = pick(options, possibleOptions), qs = encodeQueryString({ query, params, options: { tag, ...listenOpts } }), uri = `${url}${_getDataUrl(this, \"listen\", qs)}`;\n if (uri.length > MAX_URL_LENGTH)\n return throwError(() => new Error(\"Query too large for listener\"));\n const listenFor = options.events ? options.events : [\"mutation\"], esOptions = {};\n return withCredentials && (esOptions.withCredentials = !0), token && (esOptions.headers = {\n Authorization: `Bearer ${token}`\n }), connectEventSource(() => (\n // use polyfill if there is no global EventSource or if we need to set headers\n (typeof EventSource > \"u\" || esOptions.headers ? eventSourcePolyfill : of(EventSource)).pipe(map((EventSource2) => new EventSource2(uri, esOptions)))\n ), listenFor).pipe(\n reconnectOnConnectionFailure(),\n filter((event) => listenFor.includes(event.type)),\n map(\n (event) => ({\n type: event.type,\n ...\"data\" in event ? event.data : {}\n })\n )\n );\n}\nfunction shareReplayLatest(configOrPredicate, config) {\n return _shareReplayLatest(\n typeof configOrPredicate == \"function\" ? { predicate: configOrPredicate, ...config } : configOrPredicate\n );\n}\nfunction _shareReplayLatest(config) {\n return (source) => {\n let latest, emitted = !1;\n const { predicate, ...shareConfig } = config, wrapped = source.pipe(\n tap((value) => {\n config.predicate(value) && (emitted = !0, latest = value);\n }),\n finalize(() => {\n emitted = !1, latest = void 0;\n }),\n share(shareConfig)\n ), emitLatest = new Observable((subscriber) => {\n emitted && subscriber.next(\n // this cast is safe because of the emitted check which asserts that we got T from the source\n latest\n ), subscriber.complete();\n });\n return merge(wrapped, emitLatest);\n };\n}\nconst requiredApiVersion = \"2021-03-25\";\nclass LiveClient {\n #client;\n constructor(client) {\n this.#client = client;\n }\n /**\n * Requires `apiVersion` to be `2021-03-25` or later.\n */\n events({\n includeDrafts = !1,\n tag: _tag\n } = {}) {\n resourceGuard(\"live\", this.#client.config());\n const {\n projectId,\n apiVersion: _apiVersion,\n token,\n withCredentials,\n requestTagPrefix\n } = this.#client.config(), apiVersion = _apiVersion.replace(/^v/, \"\");\n if (apiVersion !== \"X\" && apiVersion < requiredApiVersion)\n throw new Error(\n `The live events API requires API version ${requiredApiVersion} or later. The current API version is ${apiVersion}. Please update your API version to use this feature.`\n );\n if (includeDrafts && !token && !withCredentials)\n throw new Error(\n \"The live events API requires a token or withCredentials when 'includeDrafts: true'. Please update your client configuration. The token should have the lowest possible access role.\"\n );\n const path = _getDataUrl(this.#client, \"live/events\"), url = new URL(this.#client.getUrl(path, !1)), tag = _tag && requestTagPrefix ? [requestTagPrefix, _tag].join(\".\") : _tag;\n tag && url.searchParams.set(\"tag\", tag), includeDrafts && url.searchParams.set(\"includeDrafts\", \"true\");\n const esOptions = {};\n includeDrafts && token && (esOptions.headers = {\n Authorization: `Bearer ${token}`\n }), includeDrafts && withCredentials && (esOptions.withCredentials = !0);\n const key = `${url.href}::${JSON.stringify(esOptions)}`, existing = eventsCache.get(key);\n if (existing)\n return existing;\n const events = connectEventSource(() => (\n // use polyfill if there is no global EventSource or if we need to set headers\n (typeof EventSource > \"u\" || esOptions.headers ? eventSourcePolyfill : of(EventSource)).pipe(map((EventSource2) => new EventSource2(url.href, esOptions)))\n ), [\n \"message\",\n \"restart\",\n \"welcome\",\n \"reconnect\",\n \"goaway\"\n ]).pipe(\n reconnectOnConnectionFailure(),\n map((event) => {\n if (event.type === \"message\") {\n const { data, ...rest } = event;\n return { ...rest, tags: data.tags };\n }\n return event;\n })\n ), checkCors = fetchObservable(url, {\n method: \"OPTIONS\",\n mode: \"cors\",\n credentials: esOptions.withCredentials ? \"include\" : \"omit\",\n headers: esOptions.headers\n }).pipe(\n mergeMap(() => EMPTY),\n catchError(() => {\n throw new CorsOriginError({ projectId });\n })\n ), observable2 = concat(checkCors, events).pipe(\n finalize$1(() => eventsCache.delete(key)),\n shareReplayLatest({\n predicate: (event) => event.type === \"welcome\"\n })\n );\n return eventsCache.set(key, observable2), observable2;\n }\n}\nfunction fetchObservable(url, init) {\n return new Observable((observer) => {\n const controller = new AbortController(), signal = controller.signal;\n return fetch(url, { ...init, signal: controller.signal }).then(\n (response) => {\n observer.next(response), observer.complete();\n },\n (err) => {\n signal.aborted || observer.error(err);\n }\n ), () => controller.abort();\n });\n}\nconst eventsCache = /* @__PURE__ */ new Map();\nclass ObservableDatasetsClient {\n #client;\n #httpRequest;\n constructor(client, httpRequest) {\n this.#client = client, this.#httpRequest = httpRequest;\n }\n /**\n * Create a new dataset with the given name\n *\n * @param name - Name of the dataset to create\n * @param options - Options for the dataset\n */\n create(name2, options) {\n return _modify(this.#client, this.#httpRequest, \"PUT\", name2, options);\n }\n /**\n * Edit a dataset with the given name\n *\n * @param name - Name of the dataset to edit\n * @param options - New options for the dataset\n */\n edit(name2, options) {\n return _modify(this.#client, this.#httpRequest, \"PATCH\", name2, options);\n }\n /**\n * Delete a dataset with the given name\n *\n * @param name - Name of the dataset to delete\n */\n delete(name2) {\n return _modify(this.#client, this.#httpRequest, \"DELETE\", name2);\n }\n /**\n * Fetch a list of datasets for the configured project\n */\n list() {\n return _request(this.#client, this.#httpRequest, {\n uri: \"/datasets\",\n tag: null\n });\n }\n}\nclass DatasetsClient {\n #client;\n #httpRequest;\n constructor(client, httpRequest) {\n this.#client = client, this.#httpRequest = httpRequest;\n }\n /**\n * Create a new dataset with the given name\n *\n * @param name - Name of the dataset to create\n * @param options - Options for the dataset\n */\n create(name2, options) {\n return resourceGuard(\"dataset\", this.#client.config()), lastValueFrom(\n _modify(this.#client, this.#httpRequest, \"PUT\", name2, options)\n );\n }\n /**\n * Edit a dataset with the given name\n *\n * @param name - Name of the dataset to edit\n * @param options - New options for the dataset\n */\n edit(name2, options) {\n return resourceGuard(\"dataset\", this.#client.config()), lastValueFrom(\n _modify(this.#client, this.#httpRequest, \"PATCH\", name2, options)\n );\n }\n /**\n * Delete a dataset with the given name\n *\n * @param name - Name of the dataset to delete\n */\n delete(name2) {\n return resourceGuard(\"dataset\", this.#client.config()), lastValueFrom(_modify(this.#client, this.#httpRequest, \"DELETE\", name2));\n }\n /**\n * Fetch a list of datasets for the configured project\n */\n list() {\n return resourceGuard(\"dataset\", this.#client.config()), lastValueFrom(\n _request(this.#client, this.#httpRequest, { uri: \"/datasets\", tag: null })\n );\n }\n}\nfunction _modify(client, httpRequest, method, name2, options) {\n return resourceGuard(\"dataset\", client.config()), dataset(name2), _request(client, httpRequest, {\n method,\n uri: `/datasets/${name2}`,\n body: options,\n tag: null\n });\n}\nclass ObservableProjectsClient {\n #client;\n #httpRequest;\n constructor(client, httpRequest) {\n this.#client = client, this.#httpRequest = httpRequest;\n }\n list(options) {\n resourceGuard(\"projects\", this.#client.config());\n const uri = options?.includeMembers === !1 ? \"/projects?includeMembers=false\" : \"/projects\";\n return _request(this.#client, this.#httpRequest, { uri });\n }\n /**\n * Fetch a project by project ID\n *\n * @param projectId - ID of the project to fetch\n */\n getById(projectId) {\n return resourceGuard(\"projects\", this.#client.config()), _request(this.#client, this.#httpRequest, { uri: `/projects/${projectId}` });\n }\n}\nclass ProjectsClient {\n #client;\n #httpRequest;\n constructor(client, httpRequest) {\n this.#client = client, this.#httpRequest = httpRequest;\n }\n list(options) {\n resourceGuard(\"projects\", this.#client.config());\n const uri = options?.includeMembers === !1 ? \"/projects?includeMembers=false\" : \"/projects\";\n return lastValueFrom(_request(this.#client, this.#httpRequest, { uri }));\n }\n /**\n * Fetch a project by project ID\n *\n * @param projectId - ID of the project to fetch\n */\n getById(projectId) {\n return resourceGuard(\"projects\", this.#client.config()), lastValueFrom(\n _request(this.#client, this.#httpRequest, { uri: `/projects/${projectId}` })\n );\n }\n}\nclass ObservableUsersClient {\n #client;\n #httpRequest;\n constructor(client, httpRequest) {\n this.#client = client, this.#httpRequest = httpRequest;\n }\n /**\n * Fetch a user by user ID\n *\n * @param id - User ID of the user to fetch. If `me` is provided, a minimal response including the users role is returned.\n */\n getById(id) {\n return _request(\n this.#client,\n this.#httpRequest,\n { uri: `/users/${id}` }\n );\n }\n}\nclass UsersClient {\n #client;\n #httpRequest;\n constructor(client, httpRequest) {\n this.#client = client, this.#httpRequest = httpRequest;\n }\n /**\n * Fetch a user by user ID\n *\n * @param id - User ID of the user to fetch. If `me` is provided, a minimal response including the users role is returned.\n */\n getById(id) {\n return lastValueFrom(\n _request(this.#client, this.#httpRequest, {\n uri: `/users/${id}`\n })\n );\n }\n}\nclass ObservableSanityClient {\n assets;\n datasets;\n live;\n projects;\n users;\n /**\n * Private properties\n */\n #clientConfig;\n #httpRequest;\n /**\n * Instance properties\n */\n listen = _listen;\n constructor(httpRequest, config = defaultConfig) {\n this.config(config), this.#httpRequest = httpRequest, this.assets = new ObservableAssetsClient(this, this.#httpRequest), this.datasets = new ObservableDatasetsClient(this, this.#httpRequest), this.live = new LiveClient(this), this.projects = new ObservableProjectsClient(this, this.#httpRequest), this.users = new ObservableUsersClient(this, this.#httpRequest);\n }\n /**\n * Clone the client - returns a new instance\n */\n clone() {\n return new ObservableSanityClient(this.#httpRequest, this.config());\n }\n config(newConfig) {\n if (newConfig === void 0)\n return { ...this.#clientConfig };\n if (this.#clientConfig && this.#clientConfig.allowReconfigure === !1)\n throw new Error(\n \"Existing client instance cannot be reconfigured - use `withConfig(newConfig)` to return a new client\"\n );\n return this.#clientConfig = initConfig(newConfig, this.#clientConfig || {}), this;\n }\n /**\n * Clone the client with a new (partial) configuration.\n *\n * @param newConfig - New client configuration properties, shallowly merged with existing configuration\n */\n withConfig(newConfig) {\n const thisConfig = this.config();\n return new ObservableSanityClient(this.#httpRequest, {\n ...thisConfig,\n ...newConfig,\n stega: {\n ...thisConfig.stega || {},\n ...typeof newConfig?.stega == \"boolean\" ? { enabled: newConfig.stega } : newConfig?.stega || {}\n }\n });\n }\n fetch(query, params, options) {\n return _fetch(\n this,\n this.#httpRequest,\n this.#clientConfig.stega,\n query,\n params,\n options\n );\n }\n /**\n * Fetch a single document with the given ID.\n *\n * @param id - Document ID to fetch\n * @param options - Request options\n */\n getDocument(id, options) {\n return _getDocument(this, this.#httpRequest, id, options);\n }\n /**\n * Fetch multiple documents in one request.\n * Should be used sparingly - performing a query is usually a better option.\n * The order/position of documents is preserved based on the original array of IDs.\n * If any of the documents are missing, they will be replaced by a `null` entry in the returned array\n *\n * @param ids - Document IDs to fetch\n * @param options - Request options\n */\n getDocuments(ids, options) {\n return _getDocuments(this, this.#httpRequest, ids, options);\n }\n create(document, options) {\n return _create(this, this.#httpRequest, document, \"create\", options);\n }\n createIfNotExists(document, options) {\n return _createIfNotExists(this, this.#httpRequest, document, options);\n }\n createOrReplace(document, options) {\n return _createOrReplace(this, this.#httpRequest, document, options);\n }\n delete(selection, options) {\n return _delete(this, this.#httpRequest, selection, options);\n }\n mutate(operations, options) {\n return _mutate(this, this.#httpRequest, operations, options);\n }\n /**\n * Create a new buildable patch of operations to perform\n *\n * @param selection - Document ID, an array of document IDs, or an object with `query` and optional `params`, defining which document(s) to patch\n * @param operations - Optional object of patch operations to initialize the patch instance with\n * @returns Patch instance - call `.commit()` to perform the operations defined\n */\n patch(selection, operations) {\n return new ObservablePatch(selection, operations, this);\n }\n /**\n * Create a new transaction of mutations\n *\n * @param operations - Optional array of mutation operations to initialize the transaction instance with\n */\n transaction(operations) {\n return new ObservableTransaction(operations, this);\n }\n /**\n * Perform action operations against the configured dataset\n *\n * @param operations - Action operation(s) to execute\n * @param options - Action options\n */\n action(operations, options) {\n return _action(this, this.#httpRequest, operations, options);\n }\n /**\n * Perform an HTTP request against the Sanity API\n *\n * @param options - Request options\n */\n request(options) {\n return _request(this, this.#httpRequest, options);\n }\n /**\n * Get a Sanity API URL for the URI provided\n *\n * @param uri - URI/path to build URL for\n * @param canUseCdn - Whether or not to allow using the API CDN for this route\n */\n getUrl(uri, canUseCdn) {\n return _getUrl(this, uri, canUseCdn);\n }\n /**\n * Get a Sanity API URL for the data operation and path provided\n *\n * @param operation - Data operation (eg `query`, `mutate`, `listen` or similar)\n * @param path - Path to append after the operation\n */\n getDataUrl(operation, path) {\n return _getDataUrl(this, operation, path);\n }\n}\nclass SanityClient {\n assets;\n datasets;\n live;\n projects;\n users;\n /**\n * Observable version of the Sanity client, with the same configuration as the promise-based one\n */\n observable;\n /**\n * Private properties\n */\n #clientConfig;\n #httpRequest;\n /**\n * Instance properties\n */\n listen = _listen;\n constructor(httpRequest, config = defaultConfig) {\n this.config(config), this.#httpRequest = httpRequest, this.assets = new AssetsClient(this, this.#httpRequest), this.datasets = new DatasetsClient(this, this.#httpRequest), this.live = new LiveClient(this), this.projects = new ProjectsClient(this, this.#httpRequest), this.users = new UsersClient(this, this.#httpRequest), this.observable = new ObservableSanityClient(httpRequest, config);\n }\n /**\n * Clone the client - returns a new instance\n */\n clone() {\n return new SanityClient(this.#httpRequest, this.config());\n }\n config(newConfig) {\n if (newConfig === void 0)\n return { ...this.#clientConfig };\n if (this.#clientConfig && this.#clientConfig.allowReconfigure === !1)\n throw new Error(\n \"Existing client instance cannot be reconfigured - use `withConfig(newConfig)` to return a new client\"\n );\n return this.observable && this.observable.config(newConfig), this.#clientConfig = initConfig(newConfig, this.#clientConfig || {}), this;\n }\n /**\n * Clone the client with a new (partial) configuration.\n *\n * @param newConfig - New client configuration properties, shallowly merged with existing configuration\n */\n withConfig(newConfig) {\n const thisConfig = this.config();\n return new SanityClient(this.#httpRequest, {\n ...thisConfig,\n ...newConfig,\n stega: {\n ...thisConfig.stega || {},\n ...typeof newConfig?.stega == \"boolean\" ? { enabled: newConfig.stega } : newConfig?.stega || {}\n }\n });\n }\n fetch(query, params, options) {\n return lastValueFrom(\n _fetch(\n this,\n this.#httpRequest,\n this.#clientConfig.stega,\n query,\n params,\n options\n )\n );\n }\n /**\n * Fetch a single document with the given ID.\n *\n * @param id - Document ID to fetch\n * @param options - Request options\n */\n getDocument(id, options) {\n return lastValueFrom(_getDocument(this, this.#httpRequest, id, options));\n }\n /**\n * Fetch multiple documents in one request.\n * Should be used sparingly - performing a query is usually a better option.\n * The order/position of documents is preserved based on the original array of IDs.\n * If any of the documents are missing, they will be replaced by a `null` entry in the returned array\n *\n * @param ids - Document IDs to fetch\n * @param options - Request options\n */\n getDocuments(ids, options) {\n return lastValueFrom(_getDocuments(this, this.#httpRequest, ids, options));\n }\n create(document, options) {\n return lastValueFrom(\n _create(this, this.#httpRequest, document, \"create\", options)\n );\n }\n createIfNotExists(document, options) {\n return lastValueFrom(\n _createIfNotExists(this, this.#httpRequest, document, options)\n );\n }\n createOrReplace(document, options) {\n return lastValueFrom(\n _createOrReplace(this, this.#httpRequest, document, options)\n );\n }\n delete(selection, options) {\n return lastValueFrom(_delete(this, this.#httpRequest, selection, options));\n }\n mutate(operations, options) {\n return lastValueFrom(_mutate(this, this.#httpRequest, operations, options));\n }\n /**\n * Create a new buildable patch of operations to perform\n *\n * @param selection - Document ID, an array of document IDs, or an object with `query` and optional `params`, defining which document(s) to patch\n * @param operations - Optional object of patch operations to initialize the patch instance with\n * @returns Patch instance - call `.commit()` to perform the operations defined\n */\n patch(documentId, operations) {\n return new Patch(documentId, operations, this);\n }\n /**\n * Create a new transaction of mutations\n *\n * @param operations - Optional array of mutation operations to initialize the transaction instance with\n */\n transaction(operations) {\n return new Transaction(operations, this);\n }\n /**\n * Perform action operations against the configured dataset\n * Returns a promise that resolves to the transaction result\n *\n * @param operations - Action operation(s) to execute\n * @param options - Action options\n */\n action(operations, options) {\n return lastValueFrom(_action(this, this.#httpRequest, operations, options));\n }\n /**\n * Perform a request against the Sanity API\n * NOTE: Only use this for Sanity API endpoints, not for your own APIs!\n *\n * @param options - Request options\n * @returns Promise resolving to the response body\n */\n request(options) {\n return lastValueFrom(_request(this, this.#httpRequest, options));\n }\n /**\n * Perform an HTTP request a `/data` sub-endpoint\n * NOTE: Considered internal, thus marked as deprecated. Use `request` instead.\n *\n * @deprecated - Use `request()` or your own HTTP library instead\n * @param endpoint - Endpoint to hit (mutate, query etc)\n * @param body - Request body\n * @param options - Request options\n * @internal\n */\n dataRequest(endpoint, body, options) {\n return lastValueFrom(_dataRequest(this, this.#httpRequest, endpoint, body, options));\n }\n /**\n * Get a Sanity API URL for the URI provided\n *\n * @param uri - URI/path to build URL for\n * @param canUseCdn - Whether or not to allow using the API CDN for this route\n */\n getUrl(uri, canUseCdn) {\n return _getUrl(this, uri, canUseCdn);\n }\n /**\n * Get a Sanity API URL for the data operation and path provided\n *\n * @param operation - Data operation (eg `query`, `mutate`, `listen` or similar)\n * @param path - Path to append after the operation\n */\n getDataUrl(operation, path) {\n return _getDataUrl(this, operation, path);\n }\n}\nfunction defineCreateClientExports(envMiddleware, ClassConstructor) {\n return { requester: defineHttpRequest(envMiddleware), createClient: (config) => {\n const clientRequester = defineHttpRequest(envMiddleware);\n return new ClassConstructor(\n (options, requester2) => (requester2 || clientRequester)({\n maxRedirects: 0,\n maxRetries: config.maxRetries,\n retryDelay: config.retryDelay,\n ...options\n }),\n config\n );\n } };\n}\nfunction defineDeprecatedCreateClient(createClient2) {\n return function(config) {\n return printNoDefaultExport(), createClient2(config);\n };\n}\nvar name = \"@sanity/client\", version = \"6.29.0\";\nconst middleware = [\n debug({ verbose: !0, namespace: \"sanity:client\" }),\n headers({ \"User-Agent\": `${name} ${version}` }),\n // Enable keep-alive, and in addition limit the number of sockets that can be opened.\n // This avoids opening too many connections to the server if someone tries to execute\n // a bunch of requests in parallel. It's recommended to have a concurrency limit\n // at a \"higher limit\" (i.e. you shouldn't actually execute hundreds of requests in parallel),\n // and this is mainly to minimize the impact for the network and server.\n //\n // We're currently matching the same defaults as browsers:\n // https://stackoverflow.com/questions/26003756/is-there-a-limit-practical-or-otherwise-to-the-number-of-web-sockets-a-page-op\n agent({\n keepAlive: !0,\n maxSockets: 30,\n maxTotalSockets: 256\n })\n], exp = defineCreateClientExports(middleware, SanityClient), requester = exp.requester, createClient = exp.createClient, deprecatedCreateClient = defineDeprecatedCreateClient(createClient);\nexport {\n BasePatch,\n BaseTransaction,\n ChannelError,\n ClientError,\n ConnectionFailedError,\n CorsOriginError,\n DisconnectError,\n MessageError,\n MessageParseError,\n ObservablePatch,\n ObservableSanityClient,\n ObservableTransaction,\n Patch,\n SanityClient,\n ServerError,\n Transaction,\n connectEventSource,\n createClient,\n deprecatedCreateClient as default,\n requester,\n adapter as unstable__adapter,\n environment as unstable__environment,\n validateApiPerspective\n};\n//# sourceMappingURL=index.js.map\n","import {logout} from '@sanity/sdk'\n\nimport {createCallbackHook} from '../helpers/createCallbackHook'\n\n/**\n * Hook to log out of the current session\n * @internal\n * @returns A function to log out of the current session\n */\nexport const useLogOut = createCallbackHook(logout)\n","import {ClientError} from '@sanity/client'\nimport {AuthStateType} from '@sanity/sdk'\nimport {useCallback, useEffect, useState} from 'react'\nimport {type FallbackProps} from 'react-error-boundary'\n\nimport {useAuthState} from '../../hooks/auth/useAuthState'\nimport {useLogOut} from '../../hooks/auth/useLogOut'\nimport {AuthError} from './AuthError'\n/**\n * @alpha\n */\nexport type LoginErrorProps = FallbackProps\n\n/**\n * Displays authentication error details and provides retry functionality.\n * Only handles {@link AuthError} instances - rethrows other error types.\n *\n * @alpha\n */\nexport function LoginError({error, resetErrorBoundary}: LoginErrorProps): React.ReactNode {\n if (!(error instanceof AuthError)) throw error\n const logout = useLogOut()\n const authState = useAuthState()\n\n const [authErrorMessage, setAuthErrorMessage] = useState(\n 'Please try again or contact support if the problem persists.',\n )\n\n const handleRetry = useCallback(async () => {\n await logout()\n resetErrorBoundary()\n }, [logout, resetErrorBoundary])\n\n useEffect(() => {\n if (authState.type === AuthStateType.ERROR && authState.error instanceof ClientError) {\n if (authState.error.statusCode === 401) {\n handleRetry()\n } else if (authState.error.statusCode === 404) {\n const errorMessage = authState.error.response.body.message || ''\n if (errorMessage.startsWith('Session with sid') && errorMessage.endsWith('not found')) {\n setAuthErrorMessage('The session ID is invalid or expired.')\n } else {\n setAuthErrorMessage('The login link is invalid or expired. Please try again.')\n }\n }\n }\n }, [authState, handleRetry])\n\n return (\n <div className=\"sc-login-error\">\n <div className=\"sc-login-error__content\">\n <h2 className=\"sc-login-error__title\">Authentication Error</h2>\n <p className=\"sc-login-error__description\">{authErrorMessage}</p>\n </div>\n\n <button className=\"sc-login-error__button\" onClick={handleRetry}>\n Retry\n </button>\n </div>\n )\n}\n","import {AuthStateType} from '@sanity/sdk'\nimport {useEffect, useMemo} from 'react'\nimport {ErrorBoundary, type FallbackProps} from 'react-error-boundary'\n\nimport {useAuthState} from '../../hooks/auth/useAuthState'\nimport {useLoginUrl} from '../../hooks/auth/useLoginUrl'\nimport {isInIframe} from '../utils'\nimport {AuthError} from './AuthError'\nimport {LoginCallback} from './LoginCallback'\nimport {LoginError, type LoginErrorProps} from './LoginError'\n\n// Only import bridge if we're in an iframe. This assumes that the app is\n// running within SanityOS if it is in an iframe and that the bridge hasn't already been loaded\nif (isInIframe() && !document.querySelector('[data-sanity-core]')) {\n const parsedUrl = new URL(window.location.href)\n const mode = new URLSearchParams(parsedUrl.hash.slice(1)).get('mode')\n const script = document.createElement('script')\n script.src =\n mode === 'core-ui--staging'\n ? 'https://core.sanity-cdn.work/bridge.js'\n : 'https://core.sanity-cdn.com/bridge.js'\n script.type = 'module'\n script.async = true\n document.head.appendChild(script)\n}\n\n/**\n * @public\n */\nexport interface AuthBoundaryProps {\n /**\n * Custom component to render the login screen.\n * Receives all props. Defaults to {@link Login}.\n */\n LoginComponent?: React.ComponentType<{\n header?: React.ReactNode\n footer?: React.ReactNode\n }>\n\n /**\n * Custom component to render during OAuth callback processing.\n * Receives all props. Defaults to {@link LoginCallback}.\n */\n CallbackComponent?: React.ComponentType<{\n header?: React.ReactNode\n footer?: React.ReactNode\n }>\n\n /**\n * Custom component to render when authentication errors occur.\n * Receives error boundary props and layout props. Defaults to\n * {@link LoginError}\n */\n LoginErrorComponent?: React.ComponentType<LoginErrorProps>\n\n /** Header content to display */\n header?: React.ReactNode\n\n /** Footer content to display */\n footer?: React.ReactNode\n\n /** Protected content to render when authenticated */\n children?: React.ReactNode\n}\n\n/**\n * A component that handles authentication flow and error boundaries for a\n * protected section of the application.\n *\n * @remarks\n * This component manages different authentication states and renders the\n * appropriate components based on that state.\n *\n * @example\n * ```tsx\n * function App() {\n * return (\n * <AuthBoundary header={<MyLogo />}>\n * <ProtectedContent />\n * </AuthBoundary>\n * )\n * }\n * ```\n *\n * @internal\n */\nexport function AuthBoundary({\n LoginErrorComponent = LoginError,\n ...props\n}: AuthBoundaryProps): React.ReactNode {\n const FallbackComponent = useMemo(() => {\n return function LoginComponentWithLayoutProps(fallbackProps: FallbackProps) {\n return <LoginErrorComponent {...fallbackProps} />\n }\n }, [LoginErrorComponent])\n\n return (\n <ErrorBoundary FallbackComponent={FallbackComponent}>\n <AuthSwitch {...props} />\n </ErrorBoundary>\n )\n}\n\ninterface AuthSwitchProps {\n LoginComponent?: React.ComponentType<{\n header?: React.ReactNode\n footer?: React.ReactNode\n }>\n CallbackComponent?: React.ComponentType<{\n header?: React.ReactNode\n footer?: React.ReactNode\n }>\n header?: React.ReactNode\n footer?: React.ReactNode\n children?: React.ReactNode\n}\n\nfunction AuthSwitch({CallbackComponent = LoginCallback, children, ...props}: AuthSwitchProps) {\n const authState = useAuthState()\n\n const isLoggedOut = authState.type === AuthStateType.LOGGED_OUT && !authState.isDestroyingSession\n const loginUrl = useLoginUrl()\n\n useEffect(() => {\n if (isLoggedOut && !isInIframe()) {\n // We don't want to redirect to login if we're in the Dashboard\n window.location.href = loginUrl\n }\n }, [isLoggedOut, loginUrl])\n\n switch (authState.type) {\n case AuthStateType.ERROR: {\n throw new AuthError(authState.error)\n }\n case AuthStateType.LOGGING_IN: {\n return <CallbackComponent {...props} />\n }\n case AuthStateType.LOGGED_IN: {\n return children\n }\n case AuthStateType.LOGGED_OUT: {\n return null\n }\n default: {\n // @ts-expect-error - This state should never happen\n throw new Error(`Invalid auth state: ${authState.type}`)\n }\n }\n}\n","import {createSanityInstance, type SanityConfig, type SanityInstance} from '@sanity/sdk'\nimport {Suspense, use, useEffect, useMemo, useRef} from 'react'\n\nimport {SanityInstanceContext} from './SanityInstanceContext'\n\nconst DEFAULT_FALLBACK = (\n <>\n Warning: No fallback provided. Please supply a fallback prop to ensure proper Suspense handling.\n </>\n)\n\n/**\n * Props for the ResourceProvider component\n * @internal\n */\nexport interface ResourceProviderProps extends SanityConfig {\n /**\n * React node to show while content is loading\n * Used as the fallback for the internal Suspense boundary\n */\n fallback: React.ReactNode\n children: React.ReactNode\n}\n\n/**\n * Provides a Sanity instance to child components through React Context\n *\n * @internal\n *\n * @remarks\n * The ResourceProvider creates a hierarchical structure of Sanity instances:\n * - When used as a root provider, it creates a new Sanity instance with the given config\n * - When nested inside another ResourceProvider, it creates a child instance that\n * inherits and extends the parent's configuration\n *\n * Features:\n * - Automatically manages the lifecycle of Sanity instances\n * - Disposes instances when the component unmounts\n * - Includes a Suspense boundary for data loading\n * - Enables hierarchical configuration inheritance\n *\n * Use this component to:\n * - Set up project/dataset configuration for an application\n * - Override specific configuration values in a section of your app\n * - Create isolated instance hierarchies for different features\n *\n * @example Creating a root provider\n * ```tsx\n * <ResourceProvider\n * projectId=\"your-project-id\"\n * dataset=\"production\"\n * fallback={<LoadingSpinner />}\n * >\n * <YourApp />\n * </ResourceProvider>\n * ```\n *\n * @example Creating nested providers with configuration inheritance\n * ```tsx\n * // Root provider with production config with nested provider for preview features with custom dataset\n * <ResourceProvider projectId=\"abc123\" dataset=\"production\" fallback={<Loading />}>\n * <div>...Main app content</div>\n * <Dashboard />\n * <ResourceProvider dataset=\"preview\" fallback={<Loading />}>\n * <PreviewFeatures />\n * </ResourceProvider>\n * </ResourceProvider>\n * ```\n */\nexport function ResourceProvider({\n children,\n fallback,\n ...config\n}: ResourceProviderProps): React.ReactNode {\n const parent = use(SanityInstanceContext)\n const instance = useMemo(\n () => (parent ? parent.createChild(config) : createSanityInstance(config)),\n [config, parent],\n )\n\n // Ref to hold the scheduled disposal timer.\n const disposal = useRef<{\n instance: SanityInstance\n timeoutId: ReturnType<typeof setTimeout>\n } | null>(null)\n\n useEffect(() => {\n // If the component remounts quickly (as in Strict Mode), cancel any pending disposal.\n if (disposal.current !== null && instance === disposal.current.instance) {\n clearTimeout(disposal.current.timeoutId)\n disposal.current = null\n }\n\n return () => {\n disposal.current = {\n instance,\n timeoutId: setTimeout(() => {\n if (!instance.isDisposed()) {\n instance.dispose()\n }\n }, 0),\n }\n }\n }, [instance])\n\n return (\n <SanityInstanceContext.Provider value={instance}>\n <Suspense fallback={fallback ?? DEFAULT_FALLBACK}>{children}</Suspense>\n </SanityInstanceContext.Provider>\n )\n}\n","import {type SanityConfig} from '@sanity/sdk'\nimport {type ReactElement, type ReactNode} from 'react'\n\nimport {ResourceProvider} from '../context/ResourceProvider'\nimport {AuthBoundary, type AuthBoundaryProps} from './auth/AuthBoundary'\n\n/**\n * @internal\n */\nexport interface SDKProviderProps extends AuthBoundaryProps {\n children: ReactNode\n config: SanityConfig | SanityConfig[]\n fallback: ReactNode\n}\n\n/**\n * @internal\n *\n * Top-level context provider that provides access to the Sanity SDK.\n * Creates a hierarchy of ResourceProviders, each providing a SanityInstance that can be\n * accessed by hooks. The first configuration in the array becomes the default instance.\n */\nexport function SDKProvider({\n children,\n config,\n fallback,\n ...props\n}: SDKProviderProps): ReactElement {\n // reverse because we want the first config to be the default, but the\n // ResourceProvider nesting makes the last one the default\n const configs = (Array.isArray(config) ? config : [config]).slice().reverse()\n\n // Create a nested structure of ResourceProviders for each config\n const createNestedProviders = (index: number): ReactElement => {\n if (index >= configs.length) {\n return <AuthBoundary {...props}>{children}</AuthBoundary>\n }\n\n return (\n <ResourceProvider {...configs[index]} fallback={fallback}>\n {createNestedProviders(index + 1)}\n </ResourceProvider>\n )\n }\n\n return createNestedProviders(0)\n}\n","import {type SanityConfig} from '@sanity/sdk'\nimport {type ReactElement, useEffect} from 'react'\n\nimport {SDKProvider} from './SDKProvider'\nimport {isInIframe, isLocalUrl} from './utils'\n\n/**\n * @public\n * @category Types\n */\nexport interface SanityAppProps {\n /* One or more SanityConfig objects providing a project ID and dataset name */\n config: SanityConfig | SanityConfig[]\n /** @deprecated use the `config` prop instead. */\n sanityConfigs?: SanityConfig[]\n children: React.ReactNode\n /* Fallback content to show when child components are suspending. Same as the `fallback` prop for React Suspense. */\n fallback: React.ReactNode\n}\n\nconst REDIRECT_URL = 'https://sanity.io/welcome'\n\n/**\n * @public\n *\n * The SanityApp component provides your Sanity application with access to your Sanity configuration,\n * as well as application context and state which is used by the Sanity React hooks. Your application\n * must be wrapped with the SanityApp component to function properly.\n *\n * SanityApp creates a hierarchy of ResourceProviders, each providing a SanityInstance that can be\n * accessed by hooks. The first configuration in the array becomes the default instance.\n *\n * @category Components\n * @param props - Your Sanity configuration and the React children to render\n * @returns Your Sanity application, integrated with your Sanity configuration and application context\n *\n * @example\n * ```tsx\n * import { SanityApp } from '@sanity/sdk-react'\n *\n * import MyAppRoot from './Root'\n *\n * // Single project configuration\n * const mySanityConfig = {\n * projectId: 'my-project-id',\n * dataset: 'production',\n * }\n *\n * // Or multiple project configurations\n * const multipleConfigs = [\n * // Configuration for your main project. This will be used as the default project for hooks.\n * {\n * projectId: 'marketing-website-project',\n * dataset: 'production',\n * },\n * // Configuration for a separate blog project\n * {\n * projectId: 'blog-project',\n * dataset: 'production',\n * },\n * // Configuration for a separate ecommerce project\n * {\n * projectId: 'ecommerce-project',\n * dataset: 'production',\n * }\n * ]\n *\n * export default function MyApp() {\n * return (\n * <SanityApp config={mySanityConfig} fallback={<LoadingSpinner />}>\n * <MyAppRoot />\n * </SanityApp>\n * )\n * }\n * ```\n */\nexport function SanityApp({\n children,\n fallback,\n config,\n sanityConfigs,\n ...props\n}: SanityAppProps): ReactElement {\n const configs = config ?? sanityConfigs ?? []\n\n useEffect(() => {\n let timeout: NodeJS.Timeout | undefined\n\n if (!isInIframe() && !isLocalUrl(window)) {\n // If the app is not running in an iframe and is not a local url, redirect to core.\n timeout = setTimeout(() => {\n // eslint-disable-next-line no-console\n console.warn('Redirecting to core', REDIRECT_URL)\n window.location.replace(REDIRECT_URL)\n }, 1000)\n }\n return () => clearTimeout(timeout)\n }, [])\n\n return (\n <SDKProvider {...props} fallback={fallback} config={configs}>\n {children}\n </SDKProvider>\n )\n}\n","import {getTokenState} from '@sanity/sdk'\n\nimport {createStateSourceHook} from '../helpers/createStateSourceHook'\n\n/**\n * Hook to get the currently logged in user\n * @internal\n * @returns The current user or null if not authenticated\n */\nexport const useAuthToken = createStateSourceHook(getTokenState)\n","import {type CurrentUser, getCurrentUserState} from '@sanity/sdk'\n\nimport {createStateSourceHook} from '../helpers/createStateSourceHook'\n\ntype UseCurrentUser = {\n /**\n * @public\n *\n * Provides the currently authenticated user’s profile information.\n *\n * @category Users\n * @returns The current user data\n *\n * @example Rendering a basic user profile\n * ```\n * const user = useCurrentUser()\n *\n * return (\n * <figure>\n * <img src={user?.profileImage} alt=`Profile image for ${user?.name}` />\n * <h2>{user?.name}</h2>\n * </figure>\n * )\n * ```\n */\n (): CurrentUser | null\n}\n\n/**\n * @public\n * @function\n * @TODO This should not return null — users of a custom app will always be authenticated via Core\n */\nexport const useCurrentUser: UseCurrentUser = createStateSourceHook(getCurrentUserState)\n","import {getDashboardOrganizationId} from '@sanity/sdk'\nimport {useMemo, useSyncExternalStore} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\n/**\n * @public\n *\n * A React hook that retrieves the dashboard organization ID that is currently selected in the Sanity Dashboard.\n *\n * @example\n * ```tsx\n * function DashboardComponent() {\n * const orgId = useDashboardOrganizationId()\n *\n * if (!orgId) return null\n *\n * return <div>Organization ID: {String(orgId)}</div>\n * }\n * ```\n *\n * @category Dashboard\n * @returns The dashboard organization ID (string | undefined)\n */\nexport function useDashboardOrganizationId(): string | undefined {\n const instance = useSanityInstance()\n const {subscribe, getCurrent} = useMemo(() => getDashboardOrganizationId(instance), [instance])\n\n return useSyncExternalStore(subscribe, getCurrent)\n}\n","import {getClientState} from '@sanity/sdk'\nimport {identity} from 'rxjs'\n\nimport {createStateSourceHook} from '../helpers/createStateSourceHook'\n\n/**\n * A React hook that provides a client that subscribes to changes in your application,\n * such as user authentication changes.\n *\n * @remarks\n * The hook uses `useSyncExternalStore` to safely subscribe to changes\n * and ensure consistency between server and client rendering.\n *\n * @category Platform\n * @returns A Sanity client\n *\n * @example\n * ```tsx\n * function MyComponent() {\n * const client = useClient({apiVersion: '2024-11-12'})\n * const [document, setDocument] = useState(null)\n * useEffect(async () => {\n * const doc = client.fetch('*[_id == \"myDocumentId\"]')\n * setDocument(doc)\n * }, [])\n * return <div>{JSON.stringify(document) ?? 'Loading...'}</div>\n * }\n * ```\n *\n * @public\n * @function\n */\nexport const useClient = createStateSourceHook({\n getState: getClientState,\n getConfig: identity,\n})\n","import {type ChannelInstance, type Controller, type Status} from '@sanity/comlink'\nimport {\n type FrameMessage,\n getOrCreateChannel,\n getOrCreateController,\n releaseChannel,\n type WindowMessage,\n} from '@sanity/sdk'\nimport {useCallback, useEffect, useRef} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\n/**\n * @internal\n */\nexport type FrameMessageHandler<TWindowMessage extends WindowMessage> = (\n event: TWindowMessage['data'],\n) => TWindowMessage['response'] | Promise<TWindowMessage['response']>\n\n/**\n * @internal\n */\nexport interface UseFrameConnectionOptions<TWindowMessage extends WindowMessage> {\n name: string\n connectTo: string\n targetOrigin: string\n onMessage?: {\n [K in TWindowMessage['type']]: (data: Extract<TWindowMessage, {type: K}>['data']) => void\n }\n heartbeat?: boolean\n onStatus?: (status: Status) => void\n}\n\n/**\n * @internal\n */\nexport interface FrameConnection<TFrameMessage extends FrameMessage> {\n connect: (frameWindow: Window) => () => void // Return cleanup function\n sendMessage: <T extends TFrameMessage['type']>(\n ...params: Extract<TFrameMessage, {type: T}>['data'] extends undefined\n ? [type: T]\n : [type: T, data: Extract<TFrameMessage, {type: T}>['data']]\n ) => void\n}\n\n/**\n * @internal\n */\nexport function useFrameConnection<\n TFrameMessage extends FrameMessage,\n TWindowMessage extends WindowMessage,\n>(options: UseFrameConnectionOptions<TWindowMessage>): FrameConnection<TFrameMessage> {\n const {onMessage, targetOrigin, name, connectTo, heartbeat, onStatus} = options\n const instance = useSanityInstance()\n const controllerRef = useRef<Controller | null>(null)\n const channelRef = useRef<ChannelInstance<TFrameMessage, TWindowMessage> | null>(null)\n\n useEffect(() => {\n const controller = getOrCreateController(instance, targetOrigin)\n const channel = getOrCreateChannel(instance, {name, connectTo, heartbeat})\n controllerRef.current = controller\n channelRef.current = channel\n\n channel.onStatus((event) => {\n onStatus?.(event.status)\n })\n\n const messageUnsubscribers: Array<() => void> = []\n\n if (onMessage) {\n Object.entries(onMessage).forEach(([type, handler]) => {\n const unsubscribe = channel.on(type, handler as FrameMessageHandler<TWindowMessage>)\n messageUnsubscribers.push(unsubscribe)\n })\n }\n\n return () => {\n // Clean up all subscriptions and stop controller/channel\n messageUnsubscribers.forEach((unsub) => unsub())\n releaseChannel(instance, name)\n channelRef.current = null\n controllerRef.current = null\n }\n }, [targetOrigin, name, connectTo, heartbeat, onMessage, instance, onStatus])\n\n const connect = useCallback((frameWindow: Window) => {\n const removeTarget = controllerRef.current?.addTarget(frameWindow)\n return () => {\n removeTarget?.()\n }\n }, [])\n\n const sendMessage = useCallback(\n <T extends TFrameMessage['type']>(\n type: T,\n data?: Extract<TFrameMessage, {type: T}>['data'],\n ) => {\n channelRef.current?.post(type, data)\n },\n [],\n )\n\n return {\n connect,\n sendMessage,\n }\n}\n","import {type MessageData, type Node, type Status} from '@sanity/comlink'\nimport {type FrameMessage, getOrCreateNode, releaseNode, type WindowMessage} from '@sanity/sdk'\nimport {useCallback, useEffect, useRef} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\n/**\n * @internal\n */\nexport type WindowMessageHandler<TFrameMessage extends FrameMessage> = (\n event: TFrameMessage['data'],\n) => TFrameMessage['response']\n\n/**\n * @internal\n */\nexport interface UseWindowConnectionOptions<TMessage extends FrameMessage> {\n name: string\n connectTo: string\n onMessage?: Record<TMessage['type'], WindowMessageHandler<TMessage>>\n onStatus?: (status: Status) => void\n}\n\n/**\n * @internal\n */\nexport interface WindowConnection<TMessage extends WindowMessage> {\n sendMessage: <TType extends TMessage['type']>(\n type: TType,\n data?: Extract<TMessage, {type: TType}>['data'],\n ) => void\n fetch: <TResponse>(\n type: string,\n data?: MessageData,\n options?: {\n signal?: AbortSignal\n suppressWarnings?: boolean\n responseTimeout?: number\n },\n ) => Promise<TResponse>\n}\n\n/**\n * @internal\n * Hook to wrap a Comlink node in a React hook.\n * Our store functionality takes care of the lifecycle of the node,\n * as well as sharing a single node between invocations if they share the same name.\n *\n * Generally not to be used directly, but to be used as a dependency of\n * Comlink-powered hooks like `useManageFavorite`.\n */\nexport function useWindowConnection<\n TWindowMessage extends WindowMessage,\n TFrameMessage extends FrameMessage,\n>({\n name,\n connectTo,\n onMessage,\n onStatus,\n}: UseWindowConnectionOptions<TFrameMessage>): WindowConnection<TWindowMessage> {\n const nodeRef = useRef<Node<TWindowMessage, TFrameMessage> | null>(null)\n const messageUnsubscribers = useRef<(() => void)[]>([])\n const instance = useSanityInstance()\n\n useEffect(() => {\n // the type cast is unfortunate, but the generic type of the node is not known here.\n // We know that the node is a WindowMessage node, but not the generic types.\n const node = getOrCreateNode(instance, {\n name,\n connectTo,\n }) as unknown as Node<TWindowMessage, TFrameMessage>\n nodeRef.current = node\n\n const statusUnsubscribe = node.onStatus((eventStatus) => {\n onStatus?.(eventStatus)\n })\n\n if (onMessage) {\n Object.entries(onMessage).forEach(([type, handler]) => {\n const messageUnsubscribe = node.on(type, handler as WindowMessageHandler<TFrameMessage>)\n messageUnsubscribers.current.push(messageUnsubscribe)\n })\n }\n\n return () => {\n statusUnsubscribe()\n messageUnsubscribers.current.forEach((unsubscribe) => unsubscribe())\n messageUnsubscribers.current = []\n releaseNode(instance, name)\n nodeRef.current = null\n }\n }, [instance, name, connectTo, onMessage, onStatus])\n\n const sendMessage = useCallback(\n (type: TWindowMessage['type'], data?: Extract<TWindowMessage, {type: typeof type}>['data']) => {\n if (!nodeRef.current) {\n throw new Error('Cannot send message before connection is established')\n }\n nodeRef.current.post(type, data)\n },\n [],\n )\n\n const fetch = useCallback(\n <TResponse>(\n type: string,\n data?: MessageData,\n fetchOptions?: {\n responseTimeout?: number\n signal?: AbortSignal\n suppressWarnings?: boolean\n },\n ): Promise<TResponse> => {\n return nodeRef.current?.fetch(type, data, fetchOptions ?? {}) as Promise<TResponse>\n },\n [],\n )\n return {\n sendMessage,\n fetch,\n }\n}\n","import {type Status} from '@sanity/comlink'\nimport {\n type CanvasResource,\n type Events,\n type MediaResource,\n SDK_CHANNEL_NAME,\n SDK_NODE_NAME,\n type StudioResource,\n} from '@sanity/message-protocol'\nimport {type DocumentHandle, type FrameMessage} from '@sanity/sdk'\nimport {useCallback, useEffect, useState} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\nimport {useWindowConnection} from './useWindowConnection'\n\n// should we import this whole type from the message protocol?\n\ninterface ManageFavorite {\n favorite: () => void\n unfavorite: () => void\n isFavorited: boolean\n isConnected: boolean\n}\n\ninterface UseManageFavoriteProps extends DocumentHandle {\n resourceId?: string\n resourceType: StudioResource['type'] | MediaResource['type'] | CanvasResource['type']\n /**\n * The name of the schema collection this document belongs to.\n * Typically is the name of the workspace when used in the context of a studio.\n */\n schemaName?: string\n}\n\n/**\n * @internal\n *\n * This hook provides functionality to add and remove documents from favorites,\n * and tracks the current favorite status of the document.\n * @param documentHandle - The document handle containing document ID and type, like `{_id: '123', _type: 'book'}`\n * @returns An object containing:\n * - `favorite` - Function to add document to favorites\n * - `unfavorite` - Function to remove document from favorites\n * - `isFavorited` - Boolean indicating if document is currently favorited\n * - `isConnected` - Boolean indicating if connection to Dashboard UI is established\n *\n * @example\n * ```tsx\n * function MyDocumentAction(props: DocumentActionProps) {\n * const {documentId, documentType} = props\n * const {favorite, unfavorite, isFavorited, isConnected} = useManageFavorite({\n * documentId,\n * documentType\n * })\n *\n * return (\n * <Button\n * disabled={!isConnected}\n * onClick={() => isFavorited ? unfavorite() : favorite()}\n * text={isFavorited ? 'Remove from favorites' : 'Add to favorites'}\n * />\n * )\n * }\n * ```\n */\nexport function useManageFavorite({\n documentId,\n documentType,\n projectId: paramProjectId,\n dataset: paramDataset,\n resourceId: paramResourceId,\n resourceType,\n schemaName,\n}: UseManageFavoriteProps): ManageFavorite {\n const [isFavorited, setIsFavorited] = useState(false) // should load this from a comlink fetch\n const [status, setStatus] = useState<Status>('idle')\n const [resourceId, setResourceId] = useState<string>(paramResourceId || '')\n const {sendMessage} = useWindowConnection<Events.FavoriteMessage, FrameMessage>({\n name: SDK_NODE_NAME,\n connectTo: SDK_CHANNEL_NAME,\n onStatus: setStatus,\n })\n const instance = useSanityInstance()\n const {config} = instance\n const instanceProjectId = config?.projectId\n const instanceDataset = config?.dataset\n const projectId = paramProjectId ?? instanceProjectId\n const dataset = paramDataset ?? instanceDataset\n\n if (resourceType === 'studio' && (!projectId || !dataset)) {\n throw new Error('projectId and dataset are required for studio resources')\n }\n\n useEffect(() => {\n // If resourceType is studio and the resourceId is not provided,\n // use the projectId and dataset to generate a resourceId\n if (resourceType === 'studio' && !paramResourceId) {\n setResourceId(`${projectId}.${dataset}`)\n } else if (paramResourceId) {\n setResourceId(paramResourceId)\n } else {\n // For other resource types, resourceId is required\n throw new Error('resourceId is required for media-library and canvas resources')\n }\n }, [resourceType, paramResourceId, projectId, dataset])\n\n const handleFavoriteAction = useCallback(\n (action: 'added' | 'removed', setFavoriteState: boolean) => {\n if (!documentId || !documentType || !resourceType) return\n\n try {\n const message: Events.FavoriteMessage = {\n type: 'dashboard/v1/events/favorite/mutate',\n data: {\n eventType: action,\n document: {\n id: documentId,\n type: documentType,\n resource: {\n id: resourceId,\n type: resourceType,\n schemaName,\n },\n },\n },\n response: {\n success: true,\n },\n }\n\n sendMessage(message.type, message.data)\n setIsFavorited(setFavoriteState)\n } catch (err) {\n const error = err instanceof Error ? err : new Error('Failed to update favorite status')\n // eslint-disable-next-line no-console\n console.error(\n `Failed to ${action === 'added' ? 'favorite' : 'unfavorite'} document:`,\n error,\n )\n throw error\n }\n },\n [documentId, documentType, resourceId, resourceType, sendMessage, schemaName],\n )\n\n const favorite = useCallback(() => handleFavoriteAction('added', true), [handleFavoriteAction])\n\n const unfavorite = useCallback(\n () => handleFavoriteAction('removed', false),\n [handleFavoriteAction],\n )\n\n return {\n favorite,\n unfavorite,\n isFavorited,\n isConnected: status === 'connected',\n }\n}\n","import {type Status} from '@sanity/comlink'\nimport {\n type CanvasResource,\n type Events,\n type MediaResource,\n SDK_CHANNEL_NAME,\n SDK_NODE_NAME,\n type StudioResource,\n} from '@sanity/message-protocol'\nimport {type DocumentHandle, type FrameMessage} from '@sanity/sdk'\nimport {useCallback, useState} from 'react'\n\nimport {useWindowConnection} from './useWindowConnection'\n\ninterface DocumentInteractionHistory {\n recordEvent: (eventType: 'viewed' | 'edited' | 'created' | 'deleted') => void\n isConnected: boolean\n}\n\n/**\n * @internal\n */\ninterface UseRecordDocumentHistoryEventProps extends DocumentHandle {\n resourceType: StudioResource['type'] | MediaResource['type'] | CanvasResource['type']\n resourceId?: string\n /**\n * The name of the schema collection this document belongs to.\n * Typically is the name of the workspace when used in the context of a studio.\n */\n schemaName?: string\n}\n\n/**\n * @internal\n * Hook for managing document interaction history in Sanity Studio.\n * This hook provides functionality to record document interactions.\n * @category History\n * @param documentHandle - The document handle containing document ID and type, like `{_id: '123', _type: 'book'}`\n * @returns An object containing:\n * - `recordEvent` - Function to record document interactions\n * - `isConnected` - Boolean indicating if connection to Studio is established\n *\n * @example\n * ```tsx\n * function MyDocumentAction(props: DocumentActionProps) {\n * const {documentId, documentType, resourceType, resourceId} = props\n * const {recordEvent, isConnected} = useRecordDocumentHistoryEvent({\n * documentId,\n * documentType,\n * resourceType,\n * resourceId,\n * })\n *\n * return (\n * <Button\n * disabled={!isConnected}\n * onClick={() => recordEvent('viewed')}\n * text={'Viewed'}\n * />\n * )\n * }\n * ```\n */\nexport function useRecordDocumentHistoryEvent({\n documentId,\n documentType,\n resourceType,\n resourceId,\n schemaName,\n}: UseRecordDocumentHistoryEventProps): DocumentInteractionHistory {\n const [status, setStatus] = useState<Status>('idle')\n const {sendMessage} = useWindowConnection<Events.HistoryMessage, FrameMessage>({\n name: SDK_NODE_NAME,\n connectTo: SDK_CHANNEL_NAME,\n onStatus: setStatus,\n })\n\n if (resourceType !== 'studio' && !resourceId) {\n throw new Error('resourceId is required for media-library and canvas resources')\n }\n\n const recordEvent = useCallback(\n (eventType: 'viewed' | 'edited' | 'created' | 'deleted') => {\n try {\n const message: Events.HistoryMessage = {\n type: 'dashboard/v1/events/history',\n data: {\n eventType,\n document: {\n id: documentId,\n type: documentType,\n resource: {\n id: resourceId!,\n type: resourceType,\n schemaName,\n },\n },\n },\n }\n\n sendMessage(message.type, message.data)\n } catch (error) {\n // eslint-disable-next-line no-console\n console.error('Failed to record history event:', error)\n throw error\n }\n },\n [documentId, documentType, resourceId, resourceType, sendMessage, schemaName],\n )\n\n return {\n recordEvent,\n isConnected: status === 'connected',\n }\n}\n","import {type Status} from '@sanity/comlink'\nimport {SDK_CHANNEL_NAME, SDK_NODE_NAME} from '@sanity/message-protocol'\nimport {useEffect, useState} from 'react'\n\nimport {useWindowConnection} from '../comlink/useWindowConnection'\n\ninterface Workspace {\n name: string\n title: string\n basePath: string\n dataset: string\n userApplicationId: string\n url: string\n _ref: string\n}\n\ninterface WorkspacesByProjectIdDataset {\n [key: `${string}:${string}`]: Workspace[] // key format: `${projectId}:${dataset}`\n}\n\ninterface StudioWorkspacesResult {\n workspacesByProjectIdAndDataset: WorkspacesByProjectIdDataset\n error: string | null\n isConnected: boolean\n}\n\n/**\n * Hook that fetches studio workspaces and organizes them by projectId:dataset\n * @internal\n */\nexport function useStudioWorkspacesByProjectIdDataset(): StudioWorkspacesResult {\n const [workspacesByProjectIdAndDataset, setWorkspacesByProjectIdAndDataset] =\n useState<WorkspacesByProjectIdDataset>({})\n const [status, setStatus] = useState<Status>('idle')\n const [error, setError] = useState<string | null>(null)\n\n const {fetch} = useWindowConnection({\n name: SDK_NODE_NAME,\n connectTo: SDK_CHANNEL_NAME,\n onStatus: setStatus,\n })\n\n // Once computed, this should probably be in a store and poll for changes\n // However, our stores are currently being refactored\n useEffect(() => {\n if (!fetch || status !== 'connected') return\n\n async function fetchWorkspaces(signal: AbortSignal) {\n try {\n const data = await fetch<{\n context: {availableResources: Array<{projectId: string; workspaces: Workspace[]}>}\n }>('dashboard/v1/bridge/context', undefined, {signal})\n\n const workspaceMap: WorkspacesByProjectIdDataset = {}\n\n data.context.availableResources.forEach((resource) => {\n if (!resource.projectId || !resource.workspaces?.length) return\n\n resource.workspaces.forEach((workspace) => {\n const key = `${resource.projectId}:${workspace.dataset}` as const\n if (!workspaceMap[key]) {\n workspaceMap[key] = []\n }\n workspaceMap[key].push(workspace)\n })\n })\n\n setWorkspacesByProjectIdAndDataset(workspaceMap)\n setError(null)\n } catch (err: unknown) {\n if (err instanceof Error) {\n if (err.name === 'AbortError') {\n return\n }\n setError('Failed to fetch workspaces')\n }\n }\n }\n\n const controller = new AbortController()\n fetchWorkspaces(controller.signal)\n\n return () => {\n controller.abort()\n }\n }, [fetch, status])\n\n return {\n workspacesByProjectIdAndDataset,\n error,\n isConnected: status === 'connected',\n }\n}\n","import {type Status} from '@sanity/comlink'\nimport {type Bridge, SDK_CHANNEL_NAME, SDK_NODE_NAME} from '@sanity/message-protocol'\nimport {type DocumentHandle} from '@sanity/sdk'\nimport {useCallback, useState} from 'react'\n\nimport {useWindowConnection} from '../comlink/useWindowConnection'\nimport {useStudioWorkspacesByProjectIdDataset} from './useStudioWorkspacesByProjectIdDataset'\n\n/**\n * @public\n * @category Types\n */\nexport interface NavigateToStudioResult {\n navigateToStudioDocument: () => void\n isConnected: boolean\n}\n\n/**\n * @public\n *\n * Hook that provides a function to navigate to a given document in its parent Studio.\n *\n * Uses the `projectId` and `dataset` properties of the {@link DocumentHandle} you provide to resolve the correct Studio.\n * This will only work if you have deployed a studio with a workspace with this `projectId` / `dataset` combination.\n *\n * @remarks If you write your own Document Handle to pass to this hook (as opposed to a Document Handle generated by another hook),\n * it must include values for `documentId`, `documentType`, `projectId`, and `dataset`.\n *\n * @category Documents\n * @param documentHandle - The document handle for the document to navigate to\n * @returns An object containing:\n * - `navigateToStudioDocument` - Function that when called will navigate to the studio document\n * - `isConnected` - Boolean indicating if connection to Dashboard is established\n *\n * @example\n * ```ts\n * import {useNavigateToStudioDocument, type DocumentHandle} from '@sanity/sdk-react'\n *\n * function MyComponent({documentHandle}: {documentHandle: DocumentHandle}) {\n * const {navigateToStudioDocument, isConnected} = useNavigateToStudioDocument(documentHandle)\n *\n * return (\n * <button onClick={navigateToStudioDocument} disabled={!isConnected}>\n * Navigate to Studio Document\n * </button>\n * )\n * }\n * ```\n */\nexport function useNavigateToStudioDocument(\n documentHandle: DocumentHandle,\n): NavigateToStudioResult {\n const {workspacesByProjectIdAndDataset, isConnected: workspacesConnected} =\n useStudioWorkspacesByProjectIdDataset()\n const [status, setStatus] = useState<Status>('idle')\n const {sendMessage} = useWindowConnection<Bridge.Navigation.NavigateToResourceMessage, never>({\n name: SDK_NODE_NAME,\n connectTo: SDK_CHANNEL_NAME,\n onStatus: setStatus,\n })\n\n const navigateToStudioDocument = useCallback(() => {\n const {projectId, dataset} = documentHandle\n\n if (!workspacesConnected || status !== 'connected' || !projectId || !dataset) {\n return\n }\n\n // Find the workspace for this document\n const workspaces = workspacesByProjectIdAndDataset[`${projectId}:${dataset}`]\n if (!workspaces?.length) {\n // eslint-disable-next-line no-console\n console.warn(\n `No workspace found for document with projectId: ${projectId} and dataset: ${dataset}`,\n )\n return\n }\n\n if (workspaces.length > 1) {\n // eslint-disable-next-line no-console\n console.warn('Multiple workspaces found for document', documentHandle)\n // eslint-disable-next-line no-console\n console.warn('Using the first one', workspaces[0])\n }\n\n const workspace = workspaces[0]\n\n const message: Bridge.Navigation.NavigateToResourceMessage = {\n type: 'dashboard/v1/bridge/navigate-to-resource',\n data: {\n resourceId: workspace._ref,\n resourceType: 'studio',\n path: `/intent/edit/id=${documentHandle.documentId};type=${documentHandle.documentType}`,\n },\n }\n\n sendMessage(message.type, message.data)\n }, [documentHandle, workspacesConnected, status, workspacesByProjectIdAndDataset, sendMessage])\n\n return {\n navigateToStudioDocument,\n isConnected: workspacesConnected && status === 'connected',\n }\n}\n","import {type DatasetsResponse} from '@sanity/client'\nimport {\n getDatasetsState,\n type ProjectHandle,\n resolveDatasets,\n type SanityInstance,\n type StateSource,\n} from '@sanity/sdk'\n\nimport {createStateSourceHook} from '../helpers/createStateSourceHook'\n\ntype UseDatasets = {\n /**\n *\n * Returns metadata for each dataset the current user has access to.\n *\n * @category Datasets\n * @returns The metadata for your the datasets\n *\n * @example\n * ```tsx\n * const datasets = useDatasets()\n *\n * return (\n * <select>\n * {datasets.map((dataset) => (\n * <option key={dataset.name}>{dataset.name}</option>\n * ))}\n * </select>\n * )\n * ```\n *\n */\n (): DatasetsResponse\n}\n\n/**\n * @public\n * @function\n */\nexport const useDatasets: UseDatasets = createStateSourceHook({\n getState: getDatasetsState as (\n instance: SanityInstance,\n projectHandle?: ProjectHandle,\n ) => StateSource<DatasetsResponse>,\n shouldSuspend: (instance, projectHandle?: ProjectHandle) =>\n // remove `undefined` since we're suspending when that is the case\n getDatasetsState(instance, projectHandle).getCurrent() === undefined,\n suspender: resolveDatasets,\n getConfig: (projectHandle?: ProjectHandle) => projectHandle,\n})\n","import {applyDocumentActions} from '@sanity/sdk'\n\nimport {createCallbackHook} from '../helpers/createCallbackHook'\n\n/**\n *\n * @beta\n *\n * Provides a callback for applying one or more actions to a document.\n *\n * @category Documents\n * @param dataset - An optional dataset handle with projectId and dataset. If not provided, the nearest SanityInstance from context will be used.\n * @returns A function that takes one more more {@link DocumentAction}s and returns a promise that resolves to an {@link ActionsResult}.\n * @example Publish or unpublish a document\n * ```\n * import { publishDocument, unpublishDocument } from '@sanity/sdk'\n * import { useApplyDocumentActions } from '@sanity/sdk-react'\n *\n * const apply = useApplyDocumentActions()\n * const myDocument = { documentId: 'my-document-id', documentType: 'my-document-type' }\n *\n * return (\n * <button onClick={() => apply(publishDocument(myDocument))}>Publish</button>\n * <button onClick={() => apply(unpublishDocument(myDocument))}>Unpublish</button>\n * )\n * ```\n *\n * @example Create and publish a new document\n * ```\n * import { createDocument, publishDocument } from '@sanity/sdk'\n * import { useApplyDocumentActions } from '@sanity/sdk-react'\n *\n * const apply = useApplyDocumentActions()\n *\n * const handleCreateAndPublish = () => {\n * const handle = { documentId: window.crypto.randomUUID(), documentType: 'my-document-type' }\n * apply([\n * createDocument(handle),\n * publishDocument(handle),\n * ])\n * }\n *\n * return (\n * <button onClick={handleCreateAndPublish}>\n * I'm feeling lucky\n * </button>\n * )\n * ```\n */\nexport const useApplyDocumentActions = createCallbackHook(applyDocumentActions)\n","import {\n type DocumentHandle,\n getDocumentState,\n type JsonMatch,\n type JsonMatchPath,\n resolveDocument,\n} from '@sanity/sdk'\nimport {type SanityDocument} from '@sanity/types'\nimport {identity} from 'rxjs'\n\nimport {createStateSourceHook} from '../helpers/createStateSourceHook'\n\n/**\n * @beta\n *\n * ## useDocument(doc, path)\n * Read and subscribe to nested values in a document\n * @category Documents\n * @param doc - The document to read state from, specified as a DocumentHandle\n * @param path - The path to the nested value to read from\n * @returns The value at the specified path\n * @example\n * ```tsx\n * import {useDocument} from '@sanity/sdk-react'\n *\n * const documentHandle = {\n * documentId: 'order-123',\n * documentType: 'order',\n * projectId: 'abc123',\n * dataset: 'production'\n * }\n *\n * function OrderLink() {\n * const title = useDocument(documentHandle, 'title')\n * const id = useDocument(documentHandle, '_id')\n *\n * return (\n * <a href={`/order/${id}`}>Order {title} today!</a>\n * )\n * }\n * ```\n *\n */\nexport function useDocument<\n TDocument extends SanityDocument,\n TPath extends JsonMatchPath<TDocument>,\n>(doc: DocumentHandle<TDocument>, path: TPath): JsonMatch<TDocument, TPath> | undefined\n\n/**\n * @beta\n * ## useDocument(doc)\n * Read and subscribe to an entire document\n * @param doc - The document to read state from, specified as a DocumentHandle\n * @returns The document state as an object\n * @example\n * ```tsx\n * import {type SanityDocument, useDocument} from '@sanity/sdk-react'\n *\n * interface Book extends SanityDocument {\n * title: string\n * author: string\n * summary: string\n * }\n *\n * const documentHandle = {\n * documentId: 'book-123',\n * documentType: 'book',\n * projectId: 'abc123',\n * dataset: 'production'\n * }\n *\n * function DocumentView() {\n * const book = useDocument<Book>(documentHandle)\n *\n * if (!book) {\n * return <div>Loading...</div>\n * }\n *\n * return (\n * <article>\n * <h1>{book.title}</h1>\n * <address>By {book.author}</address>\n *\n * <h2>Summary</h2>\n * {book.summary}\n *\n * <h2>Order</h2>\n * <a href={`/order/${book._id}`}>Order {book.title} today!</a>\n * </article>\n * )\n * }\n * ```\n *\n */\nexport function useDocument<TDocument extends SanityDocument>(\n doc: DocumentHandle<TDocument>,\n): TDocument | null\n\n/**\n * @beta\n * Reads and subscribes to a document's realtime state, incorporating both local and remote changes.\n * When called with a `path` argument, the hook will return the nested value's state.\n * When called without a `path` argument, the entire document's state will be returned.\n *\n * @remarks\n * `useDocument` is designed to be used within a realtime context in which local updates to documents\n * need to be displayed before they are persisted to the remote copy. This can be useful within a collaborative\n * or realtime editing interface where local changes need to be reflected immediately.\n *\n * The hook automatically uses the correct Sanity instance based on the project and dataset\n * specified in the DocumentHandle. This makes it easy to work with documents from different\n * projects or datasets in the same component.\n *\n * However, this hook can be too resource intensive for applications where static document values simply\n * need to be displayed (or when changes to documents don't need to be reflected immediately);\n * consider using `usePreview` or `useQuery` for these use cases instead. These hooks leverage the Sanity\n * Live Content API to provide a more efficient way to read and subscribe to document state.\n */\nexport function useDocument(doc: DocumentHandle, path?: string): unknown {\n return _useDocument(doc, path)\n}\n\nconst _useDocument = createStateSourceHook<[doc: DocumentHandle, path?: string], unknown>({\n getState: getDocumentState,\n shouldSuspend: (instance, doc) => getDocumentState(instance, doc).getCurrent() === undefined,\n suspender: resolveDocument,\n getConfig: identity,\n})\n","import {type DatasetHandle, type DocumentEvent, subscribeDocumentEvents} from '@sanity/sdk'\nimport {useCallback, useEffect, useInsertionEffect, useRef} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\n/**\n *\n * @beta\n *\n * Subscribes an event handler to events in your application's document store, such as document\n * creation, deletion, and updates.\n *\n * @category Documents\n * @param handler - The event handler to register.\n * @param doc - The document to subscribe to events for. If you pass a `DocumentHandle` with specified `projectId` and `dataset`,\n * the document will be read from the specified Sanity project and dataset that is included in the handle. If no `projectId` or `dataset` is provided,\n * the document will use the nearest instance from context.\n * @example\n * ```\n * import {useDocumentEvent} from '@sanity/sdk-react'\n * import {type DocumentEvent} from '@sanity/sdk'\n *\n * useDocumentEvent((event) => {\n * if (event.type === DocumentEvent.DocumentDeletedEvent) {\n * alert(`Document with ID ${event.documentId} deleted!`)\n * } else {\n * console.log(event)\n * }\n * })\n * ```\n */\nexport function useDocumentEvent(\n handler: (documentEvent: DocumentEvent) => void,\n dataset: DatasetHandle,\n): void {\n const ref = useRef(handler)\n\n useInsertionEffect(() => {\n ref.current = handler\n })\n\n const stableHandler = useCallback((documentEvent: DocumentEvent) => {\n return ref.current(documentEvent)\n }, [])\n\n const instance = useSanityInstance(dataset)\n useEffect(() => {\n return subscribeDocumentEvents(instance, stableHandler)\n }, [instance, stableHandler])\n}\n","import {type DocumentAction, type DocumentPermissionsResult, getPermissionsState} from '@sanity/sdk'\nimport {useCallback, useMemo, useSyncExternalStore} from 'react'\nimport {filter, firstValueFrom} from 'rxjs'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\n/**\n *\n * @beta\n *\n * Check if the current user has the specified permissions for the given document actions.\n *\n * @category Permissions\n * @param actionOrActions - One more more calls to a particular document action function for a given document\n * @returns An object that specifies whether the action is allowed; if the action is not allowed, an explanatory message and list of reasons is also provided.\n *\n * @example Checking for permission to publish a document\n * ```ts\n * import {useDocumentPermissions, useApplyDocumentActions} from '@sanity/sdk-react'\n * import {publishDocument} from '@sanity/sdk'\n *\n * export function PublishButton({doc}: {doc: DocumentHandle}) {\n * const publishPermissions = useDocumentPermissions(publishDocument(doc))\n * const applyAction = useApplyDocumentActions()\n *\n * return (\n * <>\n * <button\n * disabled={!publishPermissions.allowed}\n * onClick={() => applyAction(publishDocument(doc))}\n * popoverTarget={`${publishPermissions.allowed ? undefined : 'publishButtonPopover'}`}\n * >\n * Publish\n * </button>\n * {!publishPermissions.allowed && (\n * <div popover id=\"publishButtonPopover\">\n * {publishPermissions.message}\n * </div>\n * )}\n * </>\n * )\n * }\n * ```\n */\nexport function useDocumentPermissions(\n actionOrActions: DocumentAction | DocumentAction[],\n): DocumentPermissionsResult {\n const actions = Array.isArray(actionOrActions) ? actionOrActions : [actionOrActions]\n // if actions is an array, we need to check that all actions belong to the same project and dataset\n let projectId\n let dataset\n\n for (const action of actions) {\n if (action.projectId) {\n if (!projectId) projectId = action.projectId\n if (action.projectId !== projectId) {\n throw new Error(\n `Mismatched project IDs found in actions. All actions must belong to the same project. Found \"${action.projectId}\" but expected \"${projectId}\".`,\n )\n }\n\n if (action.dataset) {\n if (!dataset) dataset = action.dataset\n if (action.dataset !== dataset) {\n throw new Error(\n `Mismatched datasets found in actions. All actions must belong to the same dataset. Found \"${action.dataset}\" but expected \"${dataset}\".`,\n )\n }\n }\n }\n }\n\n const instance = useSanityInstance({projectId, dataset})\n const isDocumentReady = useCallback(\n () => getPermissionsState(instance, actionOrActions).getCurrent() !== undefined,\n [actionOrActions, instance],\n )\n if (!isDocumentReady()) {\n throw firstValueFrom(\n getPermissionsState(instance, actionOrActions).observable.pipe(\n filter((result) => result !== undefined),\n ),\n )\n }\n\n const {subscribe, getCurrent} = useMemo(\n () => getPermissionsState(instance, actionOrActions),\n [actionOrActions, instance],\n )\n\n return useSyncExternalStore(subscribe, getCurrent) as DocumentPermissionsResult\n}\n","import {type DocumentHandle, getDocumentSyncStatus} from '@sanity/sdk'\n\nimport {createStateSourceHook} from '../helpers/createStateSourceHook'\n\ntype UseDocumentSyncStatus = {\n /**\n * Exposes the document's sync status between local and remote document states.\n *\n * @category Documents\n * @param doc - The document handle to get sync status for. If you pass a `DocumentHandle` with specified `projectId` and `dataset`,\n * the document will be read from the specified Sanity project and dataset that is included in the handle. If no `projectId` or `dataset` is provided,\n * the document will use the nearest instance from context.\n * @returns `true` if local changes are synced with remote, `false` if the changes are not synced, and `undefined` if the document is not found\n * @example Disable a Save button when there are no changes to sync\n * ```\n * const myDocumentHandle = { documentId: 'documentId', documentType: 'documentType', projectId: 'projectId', dataset: 'dataset' }\n * const documentSynced = useDocumentSyncStatus(myDocumentHandle)\n *\n * return (\n * <button disabled={documentSynced}>\n * Save Changes\n * </button>\n * )\n * ```\n */\n (doc: DocumentHandle): boolean | undefined\n}\n\n/**\n * @beta\n * @function\n */\nexport const useDocumentSyncStatus: UseDocumentSyncStatus =\n createStateSourceHook(getDocumentSyncStatus)\n","import {\n type ActionsResult,\n type DocumentHandle,\n editDocument,\n getDocumentState,\n type JsonMatch,\n type JsonMatchPath,\n resolveDocument,\n} from '@sanity/sdk'\nimport {type SanityDocument} from '@sanity/types'\nimport {useCallback} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\nimport {useApplyDocumentActions} from './useApplyDocumentActions'\n\nconst ignoredKeys = ['_id', '_type', '_createdAt', '_updatedAt', '_rev']\n\ntype Updater<TValue> = TValue | ((nextValue: TValue) => TValue)\n\n/**\n *\n * @beta\n *\n * ## useEditDocument(doc, path)\n * Edit a nested value within a document\n *\n * @category Documents\n * @param docHandle - The document to be edited, specified as a DocumentHandle\n * @param path - The path to the nested value to be edited\n * @returns A function to update the nested value. Accepts either a new value, or an updater function that exposes the previous value and returns a new value.\n * @example Update a document's name by providing the new value directly\n * ```tsx\n * const handle = {\n * documentId: 'movie-123',\n * documentType: 'movie',\n * projectId: 'abc123',\n * dataset: 'production'\n * }\n *\n * const name = useDocument(handle, 'name')\n * const editName = useEditDocument(handle, 'name')\n *\n * function handleNameChange(event: React.ChangeEvent<HTMLInputElement>) {\n * editName(event.target.value)\n * }\n *\n * return (\n * <input type='text' value={name} onChange={handleNameChange} />\n * )\n * ```\n *\n * @example Update a count on a document by providing an updater function\n * ```tsx\n * const handle = {\n * documentId: 'counter-123',\n * documentType: 'counter',\n * projectId: 'abc123',\n * dataset: 'production'\n * }\n *\n * const count = useDocument(handle, 'count')\n * const editCount = useEditDocument(handle, 'count')\n *\n * function incrementCount() {\n * editCount(previousCount => previousCount + 1)\n * }\n *\n * return (\n * <>\n * <button onClick={incrementCount}>\n * Increment\n * </button>\n * Current count: {count}\n * </>\n * )\n * ```\n */\nexport function useEditDocument<\n TDocument extends SanityDocument,\n TPath extends JsonMatchPath<TDocument>,\n>(\n docHandle: DocumentHandle<TDocument>,\n path: TPath,\n): (nextValue: Updater<JsonMatch<TDocument, TPath>>) => Promise<ActionsResult<TDocument>>\n\n/**\n *\n * @beta\n *\n * ## useEditDocument(doc)\n * Edit an entire document\n * @param docHandle - The document to be edited, specified as a DocumentHandle.\n * The hook will automatically use the Sanity instance that matches the project and dataset specified in the handle.\n * @returns A function to update the document state. Accepts either a new document state, or an updater function that exposes the previous document state and returns the new document state.\n * @example\n * ```tsx\n * const myDocumentHandle = {\n * documentId: 'product-123',\n * documentType: 'product',\n * projectId: 'abc123',\n * dataset: 'production'\n * }\n *\n * const myDocument = useDocument(myDocumentHandle)\n * const { title, price } = myDocument ?? {}\n *\n * const editMyDocument = useEditDocument(myDocumentHandle)\n *\n * function handleFieldChange(e: React.ChangeEvent<HTMLInputElement>) {\n * const {name, value} = e.currentTarget\n * // Use an updater function to update the document state based on the previous state\n * editMyDocument(previousDocument => ({\n * ...previousDocument,\n * [name]: value\n * }))\n * }\n *\n * function handleSaleChange(e: React.ChangeEvent<HTMLInputElement>) {\n * const { checked } = e.currentTarget\n * if (checked) {\n * // Use an updater function to add a new salePrice field;\n * // set it at a 20% discount off the normal price\n * editMyDocument(previousDocument => ({\n * ...previousDocument,\n * salePrice: previousDocument.price * 0.8,\n * }))\n * } else {\n * // Get the document state without the salePrice field\n * const { salePrice, ...rest } = myDocument\n * // Update the document state to remove the salePrice field\n * editMyDocument(rest)\n * }\n * }\n *\n * return (\n * <>\n * <form onSubmit={e => e.preventDefault()}>\n * <input name='title' type='text' value={title} onChange={handleFieldChange} />\n * <input name='price' type='number' value={price} onChange={handleFieldChange} />\n * <input\n * name='salePrice'\n * type='checkbox'\n * checked={myDocument && 'salePrice' in myDocument}\n * onChange={handleSaleChange}\n * />\n * </form>\n * <pre><code>\n * {JSON.stringify(myDocument, null, 2)}\n * </code></pre>\n * </>\n * )\n * ```\n */\nexport function useEditDocument<TDocument extends SanityDocument>(\n docHandle: DocumentHandle<TDocument>,\n): (nextValue: Updater<TDocument>) => Promise<ActionsResult<TDocument>>\n\n/**\n *\n * @beta\n *\n * Enables editing of a document’s state.\n * When called with a `path` argument, the hook will return a function for updating a nested value.\n * When called without a `path` argument, the hook will return a function for updating the entire document.\n */\nexport function useEditDocument(\n docHandle: DocumentHandle,\n path?: string,\n): (updater: Updater<unknown>) => Promise<ActionsResult> {\n const instance = useSanityInstance(docHandle)\n const apply = useApplyDocumentActions()\n const isDocumentReady = useCallback(\n () => getDocumentState(instance, docHandle).getCurrent() !== undefined,\n [instance, docHandle],\n )\n if (!isDocumentReady()) throw resolveDocument(instance, docHandle)\n\n return (updater: Updater<unknown>) => {\n if (path) {\n const nextValue =\n typeof updater === 'function'\n ? updater(getDocumentState(instance, docHandle, path).getCurrent())\n : updater\n\n return apply(editDocument(docHandle, {set: {[path]: nextValue}}))\n }\n\n const current = getDocumentState(instance, docHandle).getCurrent() as object | null | undefined\n const nextValue = typeof updater === 'function' ? updater(current) : updater\n\n if (typeof nextValue !== 'object' || !nextValue) {\n throw new Error(\n `No path was provided to \\`useEditDocument\\` and the value provided was not a document object.`,\n )\n }\n\n const allKeys = Object.keys({...current, ...nextValue})\n const editActions = allKeys\n .filter((key) => !ignoredKeys.includes(key))\n .filter((key) => current?.[key as keyof typeof current] !== nextValue[key])\n .map((key) =>\n key in nextValue\n ? editDocument(docHandle, {set: {[key]: nextValue[key]}})\n : editDocument(docHandle, {unset: [key]}),\n )\n\n return apply(editActions)\n }\n}\n","import {\n getQueryKey,\n getQueryState,\n parseQueryKey,\n type QueryOptions,\n resolveQuery,\n} from '@sanity/sdk'\nimport {useEffect, useMemo, useRef, useState, useSyncExternalStore, useTransition} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\n/**\n * Executes GROQ queries against a Sanity dataset.\n *\n * This hook provides a convenient way to fetch and subscribe to real-time updates\n * for your Sanity content. Changes made to the dataset's content will trigger\n * automatic updates.\n *\n * @remarks\n * The returned `isPending` flag indicates when a React transition is in progress,\n * which can be used to show loading states for query changes.\n *\n * @beta\n * @category GROQ\n * @param query - GROQ query string to execute\n * @param options - Optional configuration for the query, including projectId and dataset\n * @returns Object containing the query result and a pending state flag\n *\n * @example Basic usage\n * ```tsx\n * const {data, isPending} = useQuery<Movie[]>('*[_type == \"movie\"]')\n * ```\n *\n * @example Using parameters\n * ```tsx\n * // With parameters\n * const {data} = useQuery<Movie>('*[_type == \"movie\" && _id == $id][0]', {\n * params: { id: 'movie-123' }\n * })\n * ```\n *\n * @example Query from a specific project/dataset\n * ```tsx\n * // Specify which project and dataset to query\n * const {data} = useQuery<Movie[]>('*[_type == \"movie\"]', {\n * projectId: 'abc123',\n * dataset: 'production'\n * })\n * ```\n *\n * @example With a loading state for transitions\n * ```tsx\n * const {data, isPending} = useQuery<Movie[]>('*[_type == \"movie\"]')\n * return (\n * <div>\n * {isPending && <div>Updating...</div>}\n * <ul>\n * {data.map(movie => <li key={movie._id}>{movie.title}</li>)}\n * </ul>\n * </div>\n * )\n * ```\n *\n */\nexport function useQuery<T>(query: string, options?: QueryOptions): {data: T; isPending: boolean} {\n const instance = useSanityInstance(options)\n\n // Use React's useTransition to avoid UI jank when queries change\n const [isPending, startTransition] = useTransition()\n\n // Get the unique key for this query and its options\n const queryKey = getQueryKey(query, options)\n // Use a deferred state to avoid immediate re-renders when the query changes\n const [deferredQueryKey, setDeferredQueryKey] = useState(queryKey)\n // Parse the deferred query key back into a query and options\n const deferred = useMemo(() => parseQueryKey(deferredQueryKey), [deferredQueryKey])\n\n // Create an AbortController to cancel in-flight requests when needed\n const ref = useRef<AbortController>(new AbortController())\n\n // When the query or options change, start a transition to update the query\n useEffect(() => {\n if (queryKey === deferredQueryKey) return\n\n startTransition(() => {\n // Abort any in-flight requests for the previous query\n if (ref && !ref.current.signal.aborted) {\n ref.current.abort()\n ref.current = new AbortController()\n }\n\n setDeferredQueryKey(queryKey)\n })\n }, [deferredQueryKey, queryKey])\n\n // Get the state source for this query from the query store\n const {getCurrent, subscribe} = useMemo(\n () => getQueryState(instance, deferred.query, deferred.options),\n [instance, deferred],\n )\n\n // If data isn't available yet, suspend rendering\n if (getCurrent() === undefined) {\n // Normally, reading from a mutable ref during render can be risky in concurrent mode.\n // However, it is safe here because:\n // 1. React guarantees that while the component is suspended (via throwing a promise),\n // no effects or state updates occur during that render pass.\n // 2. We immediately capture the current abort signal in a local variable (currentSignal).\n // 3. Even if a background render updates ref.current (for example, due to a query change),\n // the captured signal remains unchanged for this suspended render.\n // Thus, the promise thrown here uses a stable abort signal, ensuring correct behavior.\n const currentSignal = ref.current.signal\n // eslint-disable-next-line react-compiler/react-compiler\n throw resolveQuery(instance, deferred.query, {...deferred.options, signal: currentSignal})\n }\n\n // Subscribe to updates and get the current data\n // useSyncExternalStore ensures the component re-renders when the data changes\n const data = useSyncExternalStore(subscribe, getCurrent) as T\n return useMemo(() => ({data, isPending}), [data, isPending])\n}\n","import {createGroqSearchFilter, type DocumentHandle, type QueryOptions} from '@sanity/sdk'\nimport {type SortOrderingItem} from '@sanity/types'\nimport {pick} from 'lodash-es'\nimport {useCallback, useEffect, useMemo, useState} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\nimport {useQuery} from '../query/useQuery'\n\nconst DEFAULT_BATCH_SIZE = 25\nconst DEFAULT_PERSPECTIVE = 'drafts'\n\n/**\n * Result structure returned from the infinite list query\n * @internal\n */\ninterface UseDocumentsQueryResult {\n count: number\n data: DocumentHandle[]\n}\n\n/**\n * Configuration options for the useDocuments hook\n *\n * @beta\n * @category Types\n */\nexport interface DocumentsOptions extends QueryOptions {\n /**\n * GROQ filter expression to apply to the query\n */\n filter?: string\n /**\n * Number of items to load per batch (defaults to 25)\n */\n batchSize?: number\n /**\n * Sorting configuration for the results\n */\n orderings?: SortOrderingItem[]\n /**\n * Text search query to filter results\n */\n search?: string\n}\n\n/**\n * Return value from the useDocuments hook\n *\n * @beta\n * @category Types\n */\nexport interface DocumentsResponse {\n /**\n * Array of document handles for the current batch\n */\n data: DocumentHandle[]\n /**\n * Whether there are more items available to load\n */\n hasMore: boolean\n /**\n * Total count of items matching the query\n */\n count: number\n /**\n * Whether a query is currently in progress\n */\n isPending: boolean\n /**\n * Function to load the next batch of results\n */\n loadMore: () => void\n}\n\n/**\n * Retrieves batches of {@link DocumentHandle}s, narrowed by optional filters, text searches, and custom ordering,\n * with infinite scrolling support. The number of document handles returned per batch is customizable,\n * and additional batches can be loaded using the supplied `loadMore` function.\n *\n * @beta\n * @category Documents\n * @param options - Configuration options for the infinite list\n * @returns An object containing the list of document handles, the loading state, the total count of retrieved document handles, and a function to load more\n *\n * @remarks\n * - The returned document handles include projectId and dataset information from the current Sanity instance\n * - This makes them ready to use with document operations and other document hooks\n * - The hook automatically uses the correct Sanity instance based on the projectId and dataset in the options\n *\n * @example Basic infinite list with loading more\n * ```tsx\n * const { data, hasMore, isPending, loadMore, count } = useDocuments({\n * filter: '_type == \"post\"',\n * search: searchTerm,\n * batchSize: 10,\n * orderings: [{field: '_createdAt', direction: 'desc'}]\n * })\n *\n * return (\n * <div>\n * Total documents: {count}\n * <ol>\n * {data.map((doc) => (\n * <li key={doc.documentId}>\n * <MyDocumentComponent doc={doc} />\n * </li>\n * ))}\n * </ol>\n * {hasMore && <button onClick={loadMore} disabled={isPending}>\n * {isPending ? 'Loading...' : 'Load More'}\n * </button>}\n * </div>\n * )\n * ```\n */\nexport function useDocuments({\n batchSize = DEFAULT_BATCH_SIZE,\n params,\n search,\n filter,\n orderings,\n ...options\n}: DocumentsOptions): DocumentsResponse {\n const instance = useSanityInstance(options)\n const perspective = options.perspective ?? DEFAULT_PERSPECTIVE\n const [limit, setLimit] = useState(batchSize)\n\n // Reset the limit to the current batchSize whenever any query parameters\n // (filter, search, params, orderings) or batchSize changes\n const key = JSON.stringify({filter, search, params, orderings, batchSize})\n useEffect(() => {\n setLimit(batchSize)\n }, [key, batchSize])\n\n const filterClause = useMemo(() => {\n const conditions: string[] = []\n const trimmedSearch = search?.trim()\n\n // Add search query filter if specified\n if (trimmedSearch) {\n const searchFilter = createGroqSearchFilter(trimmedSearch)\n if (searchFilter) {\n conditions.push(searchFilter)\n }\n }\n\n // Add additional filter if specified\n if (filter) {\n conditions.push(`(${filter})`)\n }\n\n return conditions.length ? `[${conditions.join(' && ')}]` : ''\n }, [filter, search])\n\n const orderClause = orderings\n ? `| order(${orderings\n .map((ordering) =>\n [ordering.field, ordering.direction.toLowerCase()]\n .map((str) => str.trim())\n .filter(Boolean)\n .join(' '),\n )\n .join(',')})`\n : ''\n\n const dataQuery = `*${filterClause}${orderClause}[0...${limit}]{\"documentId\":_id,\"documentType\":_type,...$__dataset}`\n const countQuery = `count(*${filterClause})`\n\n const {\n data: {count, data},\n isPending,\n } = useQuery<UseDocumentsQueryResult>(`{\"count\":${countQuery},\"data\":${dataQuery}}`, {\n ...options,\n params: {\n ...params,\n __dataset: pick(instance.config, 'projectId', 'dataset'),\n },\n perspective,\n })\n\n const hasMore = data.length < count\n\n const loadMore = useCallback(() => {\n setLimit((prev) => Math.min(prev + batchSize, count))\n }, [count, batchSize])\n\n return useMemo(\n () => ({data, hasMore, count, isPending, loadMore}),\n [data, hasMore, count, isPending, loadMore],\n )\n}\n","import {createGroqSearchFilter, type DocumentHandle, type QueryOptions} from '@sanity/sdk'\nimport {type SortOrderingItem} from '@sanity/types'\nimport {pick} from 'lodash-es'\nimport {useCallback, useEffect, useMemo, useState} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\nimport {useQuery} from '../query/useQuery'\n\nconst DEFAULT_PERSPECTIVE = 'drafts'\n\n/**\n * Configuration options for the usePaginatedDocuments hook\n *\n * @beta\n * @category Types\n */\nexport interface PaginatedDocumentsOptions extends QueryOptions {\n /**\n * GROQ filter expression to apply to the query\n */\n filter?: string\n /**\n * Number of items to display per page (defaults to 25)\n */\n pageSize?: number\n /**\n * Sorting configuration for the results\n */\n orderings?: SortOrderingItem[]\n /**\n * Text search query to filter results\n */\n search?: string\n}\n\n/**\n * Return value from the usePaginatedDocuments hook\n *\n * @beta\n * @category Types\n */\nexport interface PaginatedDocumentsResponse {\n /**\n * Array of document handles for the current page\n */\n data: DocumentHandle[]\n /**\n * Whether a query is currently in progress\n */\n isPending: boolean\n\n /**\n * Number of items displayed per page\n */\n pageSize: number\n /**\n * Current page number (1-indexed)\n */\n currentPage: number\n /**\n * Total number of pages available\n */\n totalPages: number\n\n /**\n * Starting index of the current page (0-indexed)\n */\n startIndex: number\n /**\n * Ending index of the current page (exclusive, 0-indexed)\n */\n endIndex: number\n /**\n * Total count of items matching the query\n */\n count: number\n\n /**\n * Navigate to the first page\n */\n firstPage: () => void\n /**\n * Whether there is a first page available to navigate to\n */\n hasFirstPage: boolean\n\n /**\n * Navigate to the previous page\n */\n previousPage: () => void\n /**\n * Whether there is a previous page available to navigate to\n */\n hasPreviousPage: boolean\n\n /**\n * Navigate to the next page\n */\n nextPage: () => void\n /**\n * Whether there is a next page available to navigate to\n */\n hasNextPage: boolean\n\n /**\n * Navigate to the last page\n */\n lastPage: () => void\n /**\n * Whether there is a last page available to navigate to\n */\n hasLastPage: boolean\n\n /**\n * Navigate to a specific page number\n * @param pageNumber - The page number to navigate to (1-indexed)\n */\n goToPage: (pageNumber: number) => void\n}\n\n/**\n * Retrieves pages of {@link DocumentHandle}s, narrowed by optional filters, text searches, and custom ordering,\n * with support for traditional paginated interfaces. The number of document handles returned per page is customizable,\n * while page navigation is handled via the included navigation functions.\n *\n * @beta\n * @category Documents\n * @param options - Configuration options for the paginated list\n * @returns An object containing the current page of document handles, the loading and pagination state, and navigation functions\n *\n * @remarks\n * - The returned document handles include projectId and dataset information from the current Sanity instance\n * - This makes them ready to use with document operations and other document hooks\n * - The hook automatically uses the correct Sanity instance based on the projectId and dataset in the options\n *\n * @example Basic usage\n * ```tsx\n * const {\n * data,\n * isPending,\n * currentPage,\n * totalPages,\n * nextPage,\n * previousPage,\n * hasNextPage,\n * hasPreviousPage\n * } = usePaginatedDocuments({\n * filter: '_type == \"post\"',\n * search: searchTerm,\n * pageSize: 10,\n * orderings: [{field: '_createdAt', direction: 'desc'}]\n * })\n *\n * return (\n * <>\n * <table>\n * {data.map(doc => (\n * <MyTableRowComponent key={doc.documentId} doc={doc} />\n * ))}\n * </table>\n * {hasPreviousPage && <button onClick={previousPage}>Previous</button>}\n * {currentPage} / {totalPages}\n * {hasNextPage && <button onClick={nextPage}>Next</button>}\n * </>\n * )\n * ```\n *\n */\nexport function usePaginatedDocuments({\n filter = '',\n pageSize = 25,\n params = {},\n orderings,\n search,\n ...options\n}: PaginatedDocumentsOptions): PaginatedDocumentsResponse {\n const instance = useSanityInstance(options)\n const [pageIndex, setPageIndex] = useState(0)\n const key = JSON.stringify({filter, search, params, orderings, pageSize})\n // Reset the pageIndex to 0 whenever any query parameters (filter, search,\n // params, orderings) or pageSize changes\n useEffect(() => {\n setPageIndex(0)\n }, [key])\n\n const startIndex = pageIndex * pageSize\n const endIndex = (pageIndex + 1) * pageSize\n const perspective = options.perspective ?? DEFAULT_PERSPECTIVE\n\n const filterClause = useMemo(() => {\n const conditions: string[] = []\n const trimmedSearch = search?.trim()\n\n // Add search query filter if specified\n if (trimmedSearch) {\n const searchFilter = createGroqSearchFilter(trimmedSearch)\n if (searchFilter) {\n conditions.push(searchFilter)\n }\n }\n\n // Add additional filter if specified\n if (filter) {\n conditions.push(`(${filter})`)\n }\n\n return conditions.length ? `[${conditions.join(' && ')}]` : ''\n }, [filter, search])\n\n const orderClause = orderings\n ? `| order(${orderings\n .map((ordering) =>\n [ordering.field, ordering.direction.toLowerCase()]\n .map((str) => str.trim())\n .filter(Boolean)\n .join(' '),\n )\n .join(',')})`\n : ''\n\n const dataQuery = `*${filterClause}${orderClause}[${startIndex}...${endIndex}]{\"documentId\":_id,\"documentType\":_type,...$__dataset}`\n const countQuery = `count(*${filterClause})`\n\n const {\n data: {data, count},\n isPending,\n } = useQuery<{data: DocumentHandle[]; count: number}>(\n `{\"data\":${dataQuery},\"count\":${countQuery}}`,\n {\n ...options,\n perspective,\n params: {...params, __dataset: pick(instance.config, 'projectId', 'dataset')},\n },\n )\n\n const totalPages = Math.ceil(count / pageSize)\n const currentPage = pageIndex + 1\n\n // Navigation methods\n const firstPage = useCallback(() => setPageIndex(0), [])\n const previousPage = useCallback(() => setPageIndex((prev) => Math.max(prev - 1, 0)), [])\n const nextPage = useCallback(\n () => setPageIndex((prev) => Math.min(prev + 1, totalPages - 1)),\n [totalPages],\n )\n const lastPage = useCallback(() => setPageIndex(totalPages - 1), [totalPages])\n const goToPage = useCallback(\n (pageNumber: number) => {\n if (pageNumber < 1 || pageNumber > totalPages) return\n setPageIndex(pageNumber - 1)\n },\n [totalPages],\n )\n\n // Boolean flags for page availability\n const hasFirstPage = pageIndex > 0\n const hasPreviousPage = pageIndex > 0\n const hasNextPage = pageIndex < totalPages - 1\n const hasLastPage = pageIndex < totalPages - 1\n\n return {\n data,\n isPending,\n pageSize,\n currentPage,\n totalPages,\n startIndex,\n endIndex,\n count,\n firstPage,\n hasFirstPage,\n previousPage,\n hasPreviousPage,\n nextPage,\n hasNextPage,\n lastPage,\n hasLastPage,\n goToPage,\n }\n}\n","import {type DocumentHandle, getPreviewState, type PreviewValue, resolvePreview} from '@sanity/sdk'\nimport {useCallback, useSyncExternalStore} from 'react'\nimport {distinctUntilChanged, EMPTY, Observable, startWith, switchMap} from 'rxjs'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\n/**\n * @beta\n * @category Types\n */\nexport interface UsePreviewOptions extends DocumentHandle {\n /**\n * Optional ref object to track visibility. When provided, preview resolution\n * only occurs when the referenced element is visible in the viewport.\n */\n ref?: React.RefObject<unknown>\n}\n\n/**\n * @beta\n * @category Types\n */\nexport interface UsePreviewResults {\n /** The results of resolving the document’s preview values */\n data: PreviewValue\n /** True when preview values are being refreshed */\n isPending: boolean\n}\n\n/**\n * @beta\n *\n * Returns the preview values of a document (specified via a `DocumentHandle`),\n * including the document’s `title`, `subtitle`, `media`, and `status`. These values are live and will update in realtime.\n * To reduce unnecessary network requests for resolving the preview values, an optional `ref` can be passed to the hook so that preview\n * resolution will only occur if the `ref` is intersecting the current viewport.\n *\n * @category Documents\n * @param options - The document handle for the document you want to resolve preview values for, and an optional ref\n * @returns The preview values for the given document and a boolean to indicate whether the resolution is pending\n *\n * @example Combining with useDocuments to render a collection of document previews\n * ```\n * // PreviewComponent.jsx\n * export default function PreviewComponent({ document }) {\n * const { data: { title, subtitle, media }, isPending } = usePreview({ document })\n * return (\n * <article style={{ opacity: isPending ? 0.5 : 1}}>\n * {media?.type === 'image-asset' ? <img src={media.url} alt='' /> : ''}\n * <h2>{title}</h2>\n * <p>{subtitle}</p>\n * </article>\n * )\n * }\n *\n * // DocumentList.jsx\n * const { data } = useDocuments({ filter: '_type == \"movie\"' })\n * return (\n * <div>\n * <h1>Movies</h1>\n * <ul>\n * {data.map(movie => (\n * <li key={movie._id}>\n * <Suspense fallback='Loading…'>\n * <PreviewComponent document={movie} />\n * </Suspense>\n * </li>\n * ))}\n * </ul>\n * </div>\n * )\n * ```\n */\nexport function usePreview({ref, ...docHandle}: UsePreviewOptions): UsePreviewResults {\n const instance = useSanityInstance()\n const stateSource = getPreviewState(instance, docHandle)\n\n // Create subscribe function for useSyncExternalStore\n const subscribe = useCallback(\n (onStoreChanged: () => void) => {\n const subscription = new Observable<boolean>((observer) => {\n // For environments that don't have an intersection observer (e.g. server-side),\n // we pass true to always subscribe since we can't detect visibility\n if (typeof IntersectionObserver === 'undefined' || typeof HTMLElement === 'undefined') {\n observer.next(true)\n return\n }\n\n const intersectionObserver = new IntersectionObserver(\n ([entry]) => observer.next(entry.isIntersecting),\n {rootMargin: '0px', threshold: 0},\n )\n if (ref?.current && ref.current instanceof HTMLElement) {\n intersectionObserver.observe(ref.current)\n } else {\n // If no ref is provided or ref.current isn't an HTML element,\n // pass true to always subscribe since we can't track visibility\n observer.next(true)\n }\n return () => intersectionObserver.disconnect()\n })\n .pipe(\n startWith(false),\n distinctUntilChanged(),\n switchMap((isVisible) =>\n isVisible\n ? new Observable<void>((obs) => {\n return stateSource.subscribe(() => obs.next())\n })\n : EMPTY,\n ),\n )\n .subscribe({next: onStoreChanged})\n\n return () => subscription.unsubscribe()\n },\n [stateSource, ref],\n )\n\n // Create getSnapshot function to return current state\n const getSnapshot = useCallback(() => {\n const currentState = stateSource.getCurrent()\n if (currentState.data === null) throw resolvePreview(instance, docHandle)\n return currentState as UsePreviewResults\n }, [docHandle, instance, stateSource])\n\n return useSyncExternalStore(subscribe, getSnapshot)\n}\n","import {\n type DocumentHandle,\n getProjectionState,\n resolveProjection,\n type ValidProjection,\n} from '@sanity/sdk'\nimport {useCallback, useSyncExternalStore} from 'react'\nimport {distinctUntilChanged, EMPTY, Observable, startWith, switchMap} from 'rxjs'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\n/**\n * @public\n * @category Types\n */\nexport interface UseProjectionOptions extends DocumentHandle {\n ref?: React.RefObject<unknown>\n projection: ValidProjection\n}\n\n/**\n * @public\n * @category Types\n */\nexport interface UseProjectionResults<TData extends object> {\n data: TData\n isPending: boolean\n}\n\n/**\n * @beta\n *\n * Returns the projection values of a document (specified via a `DocumentHandle`),\n * based on the provided projection string. These values are live and will update in realtime.\n * To reduce unnecessary network requests for resolving the projection values, an optional `ref` can be passed to the hook so that projection\n * resolution will only occur if the `ref` is intersecting the current viewport.\n *\n * @category Documents\n * @param options - The document handle for the document you want to project values from, the projection string, and an optional ref\n * @returns The projection values for the given document and a boolean to indicate whether the resolution is pending\n *\n * @example Using a projection to render a preview of document\n * ```\n * // ProjectionComponent.jsx\n * export default function ProjectionComponent({ document }) {\n * const ref = useRef(null)\n * const { results: { title, coverImage, authors }, isPending } = useProjection({\n * document,\n * ref,\n * projection: `{\n * title,\n * 'coverImage': cover.asset->url,\n * 'authors': array::join(authors[]->{'name': firstName + ' ' + lastName + ' '}.name, ', ')\n * }`,\n * })\n *\n * return (\n * <article ref={ref} style={{ opacity: isPending ? 0.5 : 1}}>\n * <h2>{title}</h2>\n * <img src={coverImage} alt={title} />\n * <p>{authors}</p>\n * </article>\n * )\n * }\n * ```\n *\n * @example Combining with useDocuments to render a collection with specific fields\n * ```\n * // DocumentList.jsx\n * const { data } = useDocuments({ filter: '_type == \"article\"' })\n * return (\n * <div>\n * <h1>Books</h1>\n * <ul>\n * {data.map(book => (\n * <li key={book._id}>\n * <Suspense fallback='Loading…'>\n * <ProjectionComponent\n * document={book}\n * />\n * </Suspense>\n * </li>\n * ))}\n * </ul>\n * </div>\n * )\n * ```\n */\nexport function useProjection<TData extends object>({\n ref,\n projection,\n ...docHandle\n}: UseProjectionOptions): UseProjectionResults<TData> {\n const instance = useSanityInstance()\n const stateSource = getProjectionState<TData>(instance, {...docHandle, projection})\n\n if (stateSource.getCurrent().data === null) {\n throw resolveProjection(instance, {...docHandle, projection})\n }\n\n // Create subscribe function for useSyncExternalStore\n const subscribe = useCallback(\n (onStoreChanged: () => void) => {\n const subscription = new Observable<boolean>((observer) => {\n // For environments that don't have an intersection observer (e.g. server-side),\n // we pass true to always subscribe since we can't detect visibility\n if (typeof IntersectionObserver === 'undefined' || typeof HTMLElement === 'undefined') {\n observer.next(true)\n return\n }\n\n const intersectionObserver = new IntersectionObserver(\n ([entry]) => observer.next(entry.isIntersecting),\n {rootMargin: '0px', threshold: 0},\n )\n if (ref?.current && ref.current instanceof HTMLElement) {\n intersectionObserver.observe(ref.current)\n } else {\n // If no ref is provided or ref.current isn't an HTML element,\n // pass true to always subscribe since we can't track visibility\n observer.next(true)\n }\n return () => intersectionObserver.disconnect()\n })\n .pipe(\n startWith(false),\n distinctUntilChanged(),\n switchMap((isVisible) =>\n isVisible\n ? new Observable<void>((obs) => {\n return stateSource.subscribe(() => obs.next())\n })\n : EMPTY,\n ),\n )\n .subscribe({next: onStoreChanged})\n\n return () => subscription.unsubscribe()\n },\n [stateSource, ref],\n )\n\n return useSyncExternalStore(subscribe, stateSource.getCurrent) as UseProjectionResults<TData>\n}\n","import {\n getProjectState,\n type ProjectHandle,\n resolveProject,\n type SanityInstance,\n type SanityProject,\n type StateSource,\n} from '@sanity/sdk'\nimport {identity} from 'rxjs'\n\nimport {createStateSourceHook} from '../helpers/createStateSourceHook'\n\ntype UseProject = {\n /**\n *\n * Returns metadata for a given project\n *\n * @category Projects\n * @param projectId - The ID of the project to retrieve metadata for\n * @returns The metadata for the project\n * @example\n * ```tsx\n * function ProjectMetadata({ projectId }: { projectId: string }) {\n * const project = useProject(projectId)\n *\n * return (\n * <figure style={{ backgroundColor: project.metadata.color || 'lavender'}}>\n * <h1>{project.displayName}</h1>\n * </figure>\n * )\n * }\n * ```\n */\n (projectHandle?: ProjectHandle): SanityProject\n}\n\n/**\n * @public\n * @function\n */\nexport const useProject: UseProject = createStateSourceHook({\n // remove `undefined` since we're suspending when that is the case\n getState: getProjectState as (\n instance: SanityInstance,\n projectHandle?: ProjectHandle,\n ) => StateSource<SanityProject>,\n shouldSuspend: (instance, projectHandle) =>\n getProjectState(instance, projectHandle).getCurrent() === undefined,\n suspender: resolveProject,\n getConfig: identity,\n})\n","import {type SanityProject} from '@sanity/client'\nimport {getProjectsState, resolveProjects, type SanityInstance, type StateSource} from '@sanity/sdk'\n\nimport {createStateSourceHook} from '../helpers/createStateSourceHook'\n\n/**\n * @public\n * @category Types\n * @interface\n */\nexport type ProjectWithoutMembers = Omit<SanityProject, 'members'>\n\ntype UseProjects = {\n /**\n *\n * Returns metadata for each project you have access to.\n *\n * @category Projects\n * @returns An array of metadata (minus the projects’ members) for each project\n * @example\n * ```tsx\n * const projects = useProjects()\n *\n * return (\n * <select>\n * {projects.map((project) => (\n * <option key={project.id}>{project.displayName}</option>\n * ))}\n * </select>\n * )\n * ```\n */\n (): ProjectWithoutMembers[]\n}\n\n/**\n * @public\n * @function\n */\nexport const useProjects: UseProjects = createStateSourceHook({\n // remove `undefined` since we're suspending when that is the case\n getState: getProjectsState as (instance: SanityInstance) => StateSource<ProjectWithoutMembers[]>,\n shouldSuspend: (instance) => getProjectsState(instance).getCurrent() === undefined,\n suspender: resolveProjects,\n})\n","import {\n getUsersKey,\n type GetUsersOptions,\n getUsersState,\n loadMoreUsers,\n parseUsersKey,\n resolveUsers,\n type SanityUser,\n} from '@sanity/sdk'\nimport {useCallback, useEffect, useMemo, useState, useSyncExternalStore, useTransition} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\n/**\n * @public\n * @category Types\n */\nexport interface UsersResult {\n /**\n * The users fetched.\n */\n data: SanityUser[]\n /**\n * Whether there are more users to fetch.\n */\n hasMore: boolean\n\n /**\n * Whether a users request is currently in progress\n */\n isPending: boolean\n /**\n * Load more users.\n */\n loadMore: () => void\n}\n\n/**\n *\n * @public\n *\n * Retrieves the users for a given resource (either a project or an organization).\n *\n * @category Users\n * @param params - The resource type, project ID, and the limit of users to fetch\n * @returns A list of users, a boolean indicating whether there are more users to fetch, and a function to load more users\n *\n * @example\n * ```\n * const { data, hasMore, loadMore, isPending } = useUsers({\n * resourceType: 'organization',\n * organizationId: 'my-org-id',\n * batchSize: 10,\n * })\n *\n * return (\n * <div>\n * {data.map(user => (\n * <figure key={user.sanityUserId}>\n * <img src={user.profile.imageUrl} alt='' />\n * <figcaption>{user.profile.displayName}</figcaption>\n * <address>{user.profile.email}</address>\n * </figure>\n * ))}\n * {hasMore && <button onClick={loadMore}>{isPending ? 'Loading...' : 'Load More'</button>}\n * </div>\n * )\n * ```\n */\nexport function useUsers(options?: GetUsersOptions): UsersResult {\n const instance = useSanityInstance(options)\n // Use React's useTransition to avoid UI jank when user options change\n const [isPending, startTransition] = useTransition()\n\n // Get the unique key for this users request and its options\n const key = getUsersKey(instance, options)\n // Use a deferred state to avoid immediate re-renders when the users request changes\n const [deferredKey, setDeferredKey] = useState(key)\n // Parse the deferred users key back into users options\n const deferred = useMemo(() => parseUsersKey(deferredKey), [deferredKey])\n\n // Create an AbortController to cancel in-flight requests when needed\n const [ref, setRef] = useState<AbortController>(new AbortController())\n\n // When the users request or options change, start a transition to update the request\n useEffect(() => {\n if (key === deferredKey) return\n\n startTransition(() => {\n if (!ref.signal.aborted) {\n ref.abort()\n setRef(new AbortController())\n }\n\n setDeferredKey(key)\n })\n }, [deferredKey, key, ref])\n\n // Get the state source for this users request from the users store\n const {getCurrent, subscribe} = useMemo(() => {\n return getUsersState(instance, deferred)\n }, [instance, deferred])\n\n // If data isn't available yet, suspend rendering until it is\n // This is the React Suspense integration - throwing a promise\n // will cause React to show the nearest Suspense fallback\n if (getCurrent() === undefined) {\n throw resolveUsers(instance, {...deferred, signal: ref.signal})\n }\n\n // Subscribe to updates and get the current data\n // useSyncExternalStore ensures the component re-renders when the data changes\n const {data, hasMore} = useSyncExternalStore(subscribe, getCurrent)!\n\n const loadMore = useCallback(() => {\n loadMoreUsers(instance, options)\n }, [instance, options])\n\n return {data, hasMore, isPending, loadMore}\n}\n","// Local type declaration for Remix\ntype WindowWithEnv = Window &\n typeof globalThis & {\n ENV?: Record<string, unknown>\n }\n\ntype KnownEnvVar = 'DEV' | 'PKG_VERSION'\n\nexport function getEnv(key: KnownEnvVar): unknown {\n if (typeof import.meta !== 'undefined' && import.meta.env) {\n // Vite environment variables\n return (import.meta.env as unknown as Record<string, unknown>)[key]\n } else if (typeof process !== 'undefined' && process.env) {\n // Node.js or server-side environment variables\n return process.env[key]\n } else if (typeof window !== 'undefined' && (window as WindowWithEnv).ENV) {\n // Remix-style client-side environment variables\n return (window as WindowWithEnv).ENV?.[key]\n }\n return undefined\n}\n","import {version} from '../package.json'\nimport {getEnv} from './utils/getEnv'\n\n/**\n * This version is provided by pkg-utils at build time\n * @internal\n */\nexport const REACT_SDK_VERSION = getEnv('PKG_VERSION') || `${version}-development`\n"],"names":["SanityInstanceContext","createContext","useSanityInstance","config","instance","use","Error","JSON","stringify","match","createStateSourceHook","options","getState","getConfig","undefined","suspense","useHook","t0","$","_c","params","t1","suspender","shouldSuspend","t2","state","useSyncExternalStore","subscribe","getCurrent","useAuthState","getAuthState","useLoginUrl","getLoginUrlState","isInIframe","window","self","top","isLocalUrl","url","location","href","startsWith","AuthError","constructor","error","message","cause","createCallbackHook","callback","useHandleAuthCallback","handleAuthCallback","LoginCallback","URL","toString","then","_temp","useEffect","replacementLocation","history","replaceState","e","navigator","product","t","timeout","r","a","o","query","searchParams","indexOf","URLSearchParams","slice","decodeURIComponent","s","split","append","n","Object","entries","Array","isArray","method","body","toUpperCase","replace","connect","socket","Number","isNaN","length","knownProperties","mimicResponse","fromStream","toStream","_readableState","autoDestroy","fromProperties","Set","keys","concat","properties","property","get","value","bind","set","enumerable","configurable","defineProperties","once","destroy","emit","complete","readable","Transform","PassThrough","require$$0","zlib","require$$1","require$$2","decompressResponse","response","contentEncoding","headers","toLowerCase","includes","isBrotli","createBrotliDecompress","isEmpty","checker","transform","data","_encoding","flush","finalStream","decompressStream","createUnzip","end","pipe","m","h","d","w","y","ms","val","type","parse","isFinite","long","fmtLong","fmtShort","str","String","exec","parseFloat","msAbs","Math","abs","round","plural","name","isPlural","setup","env","createDebug","debug","default","coerce","disable","enable","enabled","humanize","forEach","key","names","skips","formatters","selectColor","namespace","hash","i","charCodeAt","colors","prevTime","enableOverride","namespacesCache","enabledCache","args","curr","Date","diff","prev","unshift","index","format","formatter","call","splice","formatArgs","log","apply","useColors","color","extend","defineProperty","namespaces","v","init","delimiter","newDebug","save","trim","filter","Boolean","ns","push","matchesTemplate","search","template","searchIndex","templateIndex","starIndex","matchIndex","map","join","skip","stack","console","warn","load","common","exports","storage","localstorage","warned","process","__nwjs","userAgent","document","documentElement","style","WebkitAppearance","firebug","exception","table","parseInt","module","c","lastC","setItem","removeItem","getItem","DEBUG","localStorage","j","hasFlag","flag","argv","prefix","position","terminatorPosition","os","tty","forceColor","FORCE_COLOR","min","translateLevel","level","hasBasic","has256","has16m","supportsColor","haveStream","streamIsTTY","TERM","platform","osRelease","release","some","sign","CI_NAME","test","TEAMCITY_VERSION","COLORTERM","version","TERM_PROGRAM_VERSION","TERM_PROGRAM","getSupportLevel","stream","isTTY","supportsColor_1","stdout","isatty","stderr","util","deprecate","inspectOpts","reduce","obj","prop","substring","_","k","fd","colorCode","getDate","hideDate","toISOString","write","formatWithOptions","require$$3","inspect","O","browser","srcModule","debug_1","arguments","http","https","Writable","assert","require$$4","require$$5","detectUnsupportedEnvironment","looksLikeNode","looksLikeBrowser","looksLikeV8","isFunction","captureStackTrace","useNativeURL","code","preservedUrlFields","events","eventHandlers","create","event","arg1","arg2","arg3","_redirectable","InvalidUrlError","createErrorType","TypeError","RedirectionError","TooManyRedirectsError","MaxBodyLengthExceededError","WriteAfterEndError","prototype","noop","RedirectableRequest","responseCallback","_sanitizeOptions","_options","_ended","_ending","_redirectCount","_redirects","_requestBodyLength","_requestBodyBuffers","on","_onNativeResponse","_processResponse","_performRequest","abort","destroyRequest","_currentRequest","encoding","isString","isBuffer","maxBodyLength","currentRequest","setHeader","removeHeader","setTimeout","msecs","destroyOnTimeout","removeListener","addListener","startTimer","_timeout","clearTimeout","clearTimer","b","host","hostname","pathname","path","searchPos","protocol","nativeProtocol","nativeProtocols","agents","scheme","agent","request","_currentUrl","_isRedirect","buffers","writeNext","buffer","finished","statusCode","trackRedirects","followRedirects","responseUrl","redirects","maxRedirects","requestHeaders","beforeRedirect","assign","Host","req","getHeader","removeMatchingHeaders","currentHostHeader","currentUrlParts","parseUrl","currentHost","currentUrl","redirectUrl","resolveUrl","spreadUrlObject","isSubdomain","responseDetails","requestDetails","wrap","protocols","wrappedProtocol","input","isURL","validateUrl","equal","wrappedRequest","writable","parsed","relative","base","resolve","urlObject","target","spread","port","regex","lastValue","header","baseClass","CustomError","subdomain","domain","dot","endsWith","followRedirectsModule","processNextickArgsModule","nextTick","fn","len","isarray","arr","Buffer","copyProps","src","dst","from","alloc","allocUnsafe","allocUnsafeSlow","SafeBuffer","arg","encodingOrOffset","size","fill","buf","SlowBuffer","objectToString","isBoolean","isNull","isNullOrUndefined","isNumber","isSymbol","isUndefined","isRegExp","re","isObject","isDate","isError","isPrimitive","inherits_browserModule","ctor","superCtor","super_","TempCtor","require","inherits","inheritsModule","_classCallCheck","Constructor","copyBuffer","offset","copy","BufferList","head","tail","entry","next","shift","ret","clear","p","custom","pna","err","cb","_this","readableDestroyed","destroyed","writableDestroyed","_writableState","errorEmitted","emitErrorNT","_destroy","undestroy","reading","ended","endEmitted","ending","finalCalled","prefinished","destroy_1","node","_stream_writable","CorkedRequest","finish","onCorkedFinish","asyncWrite","setImmediate","Duplex","WritableState","internalUtil","Stream","OurUint8Array","global","Uint8Array","_uint8ArrayToBuffer","chunk","_isUint8Array","destroyImpl","require$$6","nop","require$$7","isDuplex","objectMode","writableObjectMode","hwm","highWaterMark","writableHwm","writableHighWaterMark","defaultHwm","floor","needDrain","noDecode","decodeStrings","defaultEncoding","writing","corked","sync","bufferProcessing","onwrite","er","writecb","writelen","bufferedRequest","lastBufferedRequest","pendingcb","bufferedRequestCount","corkedRequestsFree","getBuffer","current","out","realHasInstance","Symbol","hasInstance","Function","object","_write","writev","_writev","final","_final","writeAfterEnd","validChunk","valid","isBuf","writeOrBuffer","cork","uncork","clearBuffer","setDefaultEncoding","decodeChunk","newChunk","last","doWrite","onwriteError","finishMaybe","onwriteStateUpdate","needFinish","afterWrite","onwriteDrain","l","holder","count","allBuffers","endWritable","callFinal","prefinish","need","corkReq","_undestroy","objectKeys","_stream_duplex","Readable","allowHalfOpen","onend","onEndNT","isEncoding","_normalizeEncoding","enc","retried","normalizeEncoding","nenc","string_decoder","StringDecoder","nb","text","utf16Text","utf16End","fillLast","utf8FillLast","base64Text","base64End","simpleWrite","simpleEnd","lastNeed","lastTotal","lastChar","utf8End","utf8Text","utf8CheckByte","byte","utf8CheckIncomplete","utf8CheckExtraBytes","total","_stream_readable","ReadableState","EElistenerCount","emitter","listeners","debugUtil","debuglog","require$$8","require$$9","kProxyEvents","prependListener","_events","require$$10","readableObjectMode","readableHwm","readableHighWaterMark","pipes","pipesCount","flowing","needReadable","emittedReadable","readableListening","resumeScheduled","awaitDrain","readingMore","decoder","require$$11","read","_read","skipChunkCheck","readableAddChunk","addToFront","onEofChunk","chunkInvalid","getPrototypeOf","addChunk","maybeReadMore","needMoreData","emitReadable","isPaused","setEncoding","MAX_HWM","computeNewHighWaterMark","howMuchToRead","nOrig","endReadable","doRead","fromList","emitReadable_","flow","maybeReadMore_","dest","pipeOpts","doEnd","endFn","unpipe","onunpipe","unpipeInfo","hasUnpiped","cleanup","ondrain","pipeOnDrain","cleanedUp","onclose","onfinish","onerror","ondata","increasedAwaitDrain","pause","resume","dests","ev","res","nReadingNextTick","resume_","paused","_fromList","fromListPartial","list","hasStrings","copyFromBufferString","copyFromBuffer","endReadableNT","xs","x","_stream_transform","afterTransform","ts","_transformState","transforming","writechunk","rs","needTransform","writeencoding","_transform","_flush","done","_this2","err2","_stream_passthrough","READABLE_STREAM","immutable","hasOwnProperty","source","xtend","DestroyableTransform","opts","_destroyed","through2","construct","through2Module","Through2","override","tick","maxTick","resolution","inc","timer","setInterval","unref","speedometer","seconds","pointer","delta","dist","btm","through","onprogress","time","drain","transferred","nextUpdate","now","speed","startTime","update","percentage","remaining","eta","runtime","tr","onlength","newLength","setLength","progress","net","tls","tunnelAgent","httpOverHttp","httpsOverHttp","httpOverHttps","httpsOverHttps","TunnelingAgent","createSocket","createSecureSocket","defaultPort","proxyOptions","proxy","maxSockets","Agent","defaultMaxSockets","requests","sockets","pending","onSocket","removeSocket","EventEmitter","addRequest","createConnection","onFree","onCloseOrRemove","placeholder","connectOptions","mergeOptions","proxyAuth","connectReq","useChunkedEncodingByDefault","onResponse","onUpgrade","onConnect","onError","upgrade","removeAllListeners","pos","secureSocket","servername","overrides","keyLen","NODE_DEBUG","getIt","denyList","isRetryAllowed","has","finalizeOptions","f","u","fromCodePoint","E","padStart","I","T","C","fromEntries","reverse","S","values","RegExp","cleaned","encoded","BASE_URL","generateHelpUrl","slug","ClientError","responseBody","details","props","extractErrorProps","ServerError","stringifyBody","isMutationError","isActionError","allItems","items","item","description","itemsStr","httpErrorMessage","isPlainObject","statusMessage","CorsOriginError","projectId","addOriginUrl","origin","useLogOut","logout","LoginError","resetErrorBoundary","authState","authErrorMessage","setAuthErrorMessage","useState","handleRetry","AuthStateType","ERROR","errorMessage","t3","t4","for","t5","t6","t7","querySelector","parsedUrl","mode","script","createElement","async","appendChild","AuthBoundary","LoginErrorComponent","fallbackProps","FallbackComponent","AuthSwitch","children","CallbackComponent","isLoggedOut","LOGGED_OUT","isDestroyingSession","loginUrl","LOGGING_IN","LOGGED_IN","DEFAULT_FALLBACK","ResourceProvider","fallback","parent","createChild","createSanityInstance","disposal","useRef","timeoutId","isDisposed","dispose","SDKProvider","configs","createNestedProviders","REDIRECT_URL","SanityApp","sanityConfigs","_temp2","useAuthToken","getTokenState","useCurrentUser","getCurrentUserState","useDashboardOrganizationId","getDashboardOrganizationId","useClient","getClientState","identity","useFrameConnection","onMessage","targetOrigin","connectTo","heartbeat","onStatus","controllerRef","channelRef","controller","getOrCreateController","channel","getOrCreateChannel","status","messageUnsubscribers","handler","unsubscribe","releaseChannel","frameWindow","removeTarget","addTarget","type_0","post","sendMessage","unsub","useWindowConnection","nodeRef","getOrCreateNode","statusUnsubscribe","eventStatus","messageUnsubscribe","releaseNode","type_1","data_0","fetchOptions","fetch","useManageFavorite","documentId","documentType","paramProjectId","dataset","paramDataset","resourceId","paramResourceId","resourceType","schemaName","isFavorited","setIsFavorited","setStatus","setResourceId","SDK_NODE_NAME","SDK_CHANNEL_NAME","instanceProjectId","instanceDataset","action","setFavoriteState","eventType","id","resource","success","handleFavoriteAction","favorite","unfavorite","t8","isConnected","useRecordDocumentHistoryEvent","recordEvent","useStudioWorkspacesByProjectIdDataset","workspacesByProjectIdAndDataset","setWorkspacesByProjectIdAndDataset","setError","fetchWorkspaces","signal","workspaceMap","context","availableResources","workspaces","workspace","AbortController","useNavigateToStudioDocument","documentHandle","workspacesConnected","_ref","navigateToStudioDocument","useDatasets","getDatasetsState","projectHandle","resolveDatasets","useApplyDocumentActions","applyDocumentActions","useDocument","doc","_useDocument","getDocumentState","resolveDocument","useDocumentEvent","ref","useInsertionEffect","documentEvent","stableHandler","subscribeDocumentEvents","useDocumentPermissions","actionOrActions","actions","getPermissionsState","firstValueFrom","observable","result","useDocumentSyncStatus","getDocumentSyncStatus","ignoredKeys","useEditDocument","docHandle","updater","nextValue","editDocument","nextValue_0","editActions","key_0","key_1","unset","useQuery","isPending","startTransition","useTransition","queryKey","getQueryKey","deferredQueryKey","setDeferredQueryKey","deferred","useMemo","parseQueryKey","aborted","getQueryState","currentSignal","resolveQuery","DEFAULT_BATCH_SIZE","DEFAULT_PERSPECTIVE","useDocuments","orderings","batchSize","perspective","limit","setLimit","conditions","trimmedSearch","searchFilter","createGroqSearchFilter","filterClause","orderClause","dataQuery","countQuery","pick","__dataset","t9","hasMore","t10","loadMore","t11","t12","ordering","field","direction","usePaginatedDocuments","pageSize","pageIndex","setPageIndex","startIndex","endIndex","totalPages","ceil","currentPage","t13","firstPage","t14","_temp3","previousPage","t15","prev_0","nextPage","t16","lastPage","t17","pageNumber","goToPage","hasFirstPage","hasPreviousPage","hasNextPage","hasLastPage","t18","max","usePreview","getPreviewState","stateSource","onStoreChanged","subscription","Observable","observer","IntersectionObserver","HTMLElement","intersectionObserver","isIntersecting","rootMargin","threshold","observe","disconnect","startWith","distinctUntilChanged","switchMap","isVisible","obs","EMPTY","currentState","resolvePreview","useProjection","projection","getProjectionState","resolveProjection","useProject","getProjectState","resolveProject","useProjects","getProjectsState","resolveProjects","useUsers","getUsersKey","deferredKey","setDeferredKey","parseUsersKey","setRef","getUsersState","resolveUsers","useCallback","loadMoreUsers","getEnv","import","ENV","REACT_SDK_VERSION"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAGaA,MAAAA,wBAAwBC,cAAqC,IAAI,GCwDjEC,oBAAqBC,CAA0C,WAAA;AACpEC,QAAAA,WAAWC,IAAIL,qBAAqB;AAE1C,MAAI,CAACI;AACH,UAAM,IAAIE,MACR,qCAAqCH,SAAS,qBAAqBI,KAAKC,UAAUL,QAAQ,MAAM,CAAC,CAAC,OAAO,EAAE,wFAC7G;AAGE,MAAA,CAACA,OAAeC,QAAAA;AAEdK,QAAAA,QAAQL,SAASK,MAAMN,MAAM;AACnC,MAAI,CAACM;AACG,UAAA,IAAIH,MACR,8EAA8EC,KAAKC,UAAUL,QAAQ,MAAM,CAAC,CAAC;AAAA,sGAE/G;AAGKM,SAAAA;AACT;AC9DO,SAASC,sBACdC,SACgC;AAChC,QAAMC,WAAW,OAAOD,WAAY,aAAaA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y+B,aAAaz+B,KAAKu2B,GAAG,CAAC;AAGpB,QAAA;AAAA,IAAC1/B;AAAAA,IAAYD;AAAAA,EAAAA,IAAa6hC,QAAQ,MAC/BoG,cAAcxpC,UAAUmjC,QAAQ,GACtC,CAACnjC,UAAUmjC,QAAQ,CAAC;AAKvB,MAAI3hC,WAAiBd,MAAAA;AACnB,UAAM+oC,aAAazpC,UAAU;AAAA,MAAC,GAAGmjC;AAAAA,MAAUzD,QAAQwB,IAAIxB;AAAAA,IAAAA,CAAO;AAK1D,QAAA;AAAA,IAAC13B;AAAAA,IAAM68B;AAAAA,EAAAA,IAAWvjC,qBAAqBC,WAAWC,UAAU,GAE5DujC,WAAW2E,YAAY,MAAM;AACjCC,kBAAc3pC,UAAUO,OAAO;AAAA,EAAA,GAC9B,CAACP,UAAUO,OAAO,CAAC;AAEf,SAAA;AAAA,IAACyH;AAAAA,IAAM68B;AAAAA,IAASjC;AAAAA,IAAWmC;AAAAA,EAAQ;AAC5C;;AC/GO,SAAS6E,OAAOj/B,KAA2B;AAC5C,MAAA,OAAOk/B,cAAgB,OAAeA,YAAY5/B;AAE5C4/B,WAAAA,YAAY5/B,IAA2CU,GAAG;AACzD,MAAA,OAAO8D,UAAY,OAAeA,QAAQxE;AAE5CwE,WAAAA,QAAQxE,IAAIU,GAAG;AACb,MAAA,OAAO7I,SAAW,OAAgBA,OAAyBgoC;AAE5DhoC,WAAAA,OAAyBgoC,MAAMn/B,GAAG;AAG9C;ACbO,MAAMo/B,oBAAoBH,OAAO,aAAa,KAAK,GAAGl4B,OAAO;","x_google_ignoreList":[10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52]}
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../../src/context/SanityInstanceContext.ts","../../src/hooks/context/useSanityInstance.ts","../../src/hooks/helpers/createStateSourceHook.tsx","../../src/hooks/auth/useAuthState.tsx","../../src/hooks/auth/useLoginUrl.tsx","../../src/components/utils.ts","../../src/components/auth/AuthError.ts","../../src/hooks/helpers/createCallbackHook.tsx","../../src/hooks/auth/useHandleAuthCallback.tsx","../../src/components/auth/LoginCallback.tsx","../../../../node_modules/.pnpm/get-it@8.6.7/node_modules/get-it/dist/_chunks-es/defaultOptionsValidator.js","../../../../node_modules/.pnpm/get-it@8.6.7/node_modules/get-it/dist/_chunks-es/createRequester.js","../../../../node_modules/.pnpm/mimic-response@3.1.0/node_modules/mimic-response/index.js","../../../../node_modules/.pnpm/decompress-response@7.0.0/node_modules/decompress-response/index.js","../../../../node_modules/.pnpm/ms@2.1.3/node_modules/ms/index.js","../../../../node_modules/.pnpm/debug@4.4.0/node_modules/debug/src/common.js","../../../../node_modules/.pnpm/debug@4.4.0/node_modules/debug/src/browser.js","../../../../node_modules/.pnpm/has-flag@4.0.0/node_modules/has-flag/index.js","../../../../node_modules/.pnpm/supports-color@7.2.0/node_modules/supports-color/index.js","../../../../node_modules/.pnpm/debug@4.4.0/node_modules/debug/src/node.js","../../../../node_modules/.pnpm/debug@4.4.0/node_modules/debug/src/index.js","../../../../node_modules/.pnpm/follow-redirects@1.15.9/node_modules/follow-redirects/debug.js","../../../../node_modules/.pnpm/follow-redirects@1.15.9/node_modules/follow-redirects/index.js","../../../../node_modules/.pnpm/process-nextick-args@2.0.1/node_modules/process-nextick-args/index.js","../../../../node_modules/.pnpm/isarray@1.0.0/node_modules/isarray/index.js","../../../../node_modules/.pnpm/readable-stream@2.3.8/node_modules/readable-stream/lib/internal/streams/stream.js","../../../../node_modules/.pnpm/safe-buffer@5.1.2/node_modules/safe-buffer/index.js","../../../../node_modules/.pnpm/core-util-is@1.0.3/node_modules/core-util-is/lib/util.js","../../../../node_modules/.pnpm/inherits@2.0.4/node_modules/inherits/inherits_browser.js","../../../../node_modules/.pnpm/inherits@2.0.4/node_modules/inherits/inherits.js","../../../../node_modules/.pnpm/readable-stream@2.3.8/node_modules/readable-stream/lib/internal/streams/BufferList.js","../../../../node_modules/.pnpm/readable-stream@2.3.8/node_modules/readable-stream/lib/internal/streams/destroy.js","../../../../node_modules/.pnpm/util-deprecate@1.0.2/node_modules/util-deprecate/node.js","../../../../node_modules/.pnpm/readable-stream@2.3.8/node_modules/readable-stream/lib/_stream_writable.js","../../../../node_modules/.pnpm/readable-stream@2.3.8/node_modules/readable-stream/lib/_stream_duplex.js","../../../../node_modules/.pnpm/string_decoder@1.1.1/node_modules/string_decoder/lib/string_decoder.js","../../../../node_modules/.pnpm/readable-stream@2.3.8/node_modules/readable-stream/lib/_stream_readable.js","../../../../node_modules/.pnpm/readable-stream@2.3.8/node_modules/readable-stream/lib/_stream_transform.js","../../../../node_modules/.pnpm/readable-stream@2.3.8/node_modules/readable-stream/lib/_stream_passthrough.js","../../../../node_modules/.pnpm/readable-stream@2.3.8/node_modules/readable-stream/readable.js","../../../../node_modules/.pnpm/xtend@4.0.2/node_modules/xtend/immutable.js","../../../../node_modules/.pnpm/through2@2.0.5/node_modules/through2/through2.js","../../../../node_modules/.pnpm/speedometer@1.0.0/node_modules/speedometer/index.js","../../../../node_modules/.pnpm/progress-stream@2.0.0/node_modules/progress-stream/index.js","../../../../node_modules/.pnpm/safe-buffer@5.2.1/node_modules/safe-buffer/index.js","../../../../node_modules/.pnpm/tunnel-agent@0.6.0/node_modules/tunnel-agent/index.js","../../../../node_modules/.pnpm/get-it@8.6.7/node_modules/get-it/dist/_chunks-es/node-request.js","../../../../node_modules/.pnpm/get-it@8.6.7/node_modules/get-it/dist/index.js","../../../../node_modules/.pnpm/is-retry-allowed@2.2.0/node_modules/is-retry-allowed/index.js","../../../../node_modules/.pnpm/get-it@8.6.7/node_modules/get-it/dist/middleware.js","../../../../node_modules/.pnpm/@sanity+client@6.29.0/node_modules/@sanity/client/dist/_chunks-es/stegaClean.js","../../../../node_modules/.pnpm/@sanity+client@6.29.0/node_modules/@sanity/client/dist/_chunks-es/config.js","../../../../node_modules/.pnpm/@sanity+client@6.29.0/node_modules/@sanity/client/dist/index.js","../../src/hooks/auth/useLogOut.tsx","../../src/components/auth/LoginError.tsx","../../src/components/auth/AuthBoundary.tsx","../../src/context/ResourceProvider.tsx","../../src/components/SDKProvider.tsx","../../src/components/SanityApp.tsx","../../src/hooks/auth/useAuthToken.tsx","../../src/hooks/auth/useCurrentUser.tsx","../../src/hooks/auth/useDashboardOrganizationId.tsx","../../src/hooks/client/useClient.ts","../../src/hooks/comlink/useFrameConnection.ts","../../src/hooks/comlink/useWindowConnection.ts","../../src/hooks/comlink/useManageFavorite.ts","../../src/hooks/comlink/useRecordDocumentHistoryEvent.ts","../../src/hooks/dashboard/useStudioWorkspacesByProjectIdDataset.ts","../../src/hooks/dashboard/useNavigateToStudioDocument.ts","../../src/hooks/datasets/useDatasets.ts","../../src/hooks/document/useApplyDocumentActions.ts","../../src/hooks/document/useDocument.ts","../../src/hooks/document/useDocumentEvent.ts","../../src/hooks/document/useDocumentPermissions.ts","../../src/hooks/document/useDocumentSyncStatus.ts","../../src/hooks/document/useEditDocument.ts","../../src/hooks/query/useQuery.ts","../../src/hooks/documents/useDocuments.ts","../../src/hooks/paginatedDocuments/usePaginatedDocuments.ts","../../src/hooks/preview/usePreview.tsx","../../src/hooks/projection/useProjection.ts","../../src/hooks/projects/useProject.ts","../../src/hooks/projects/useProjects.ts","../../src/hooks/users/useUsers.ts","../../src/utils/getEnv.ts","../../src/version.ts"],"sourcesContent":["import {type SanityInstance} from '@sanity/sdk'\nimport {createContext} from 'react'\n\nexport const SanityInstanceContext = createContext<SanityInstance | null>(null)\n","import {type SanityConfig, type SanityInstance} from '@sanity/sdk'\nimport {useContext} from 'react'\n\nimport {SanityInstanceContext} from '../../context/SanityInstanceContext'\n\n/**\n * Retrieves the current Sanity instance or finds a matching instance from the hierarchy\n *\n * @public\n *\n * @category Platform\n * @param config - Optional configuration to match against when finding an instance\n * @returns The current or matching Sanity instance\n *\n * @remarks\n * This hook accesses the nearest Sanity instance from the React context. When provided with\n * a configuration object, it traverses up the instance hierarchy to find the closest instance\n * that matches the specified configuration using shallow comparison of properties.\n *\n * The hook must be used within a component wrapped by a `ResourceProvider` or `SanityApp`.\n *\n * Use this hook when you need to:\n * - Access the current SanityInstance from context\n * - Find a specific instance with matching project/dataset configuration\n * - Access a parent instance with specific configuration values\n *\n * @example Get the current instance\n * ```tsx\n * // Get the current instance from context\n * const instance = useSanityInstance()\n * console.log(instance.config.projectId)\n * ```\n *\n * @example Find an instance with specific configuration\n * ```tsx\n * // Find an instance matching the given project and dataset\n * const instance = useSanityInstance({\n * projectId: 'abc123',\n * dataset: 'production'\n * })\n *\n * // Use instance for API calls\n * const fetchDocument = (docId) => {\n * // Instance is guaranteed to have the matching config\n * return client.fetch(`*[_id == $id][0]`, { id: docId })\n * }\n * ```\n *\n * @example Match partial configuration\n * ```tsx\n * // Find an instance with specific auth configuration\n * const instance = useSanityInstance({\n * auth: { requireLogin: true }\n * })\n * ```\n *\n * @throws Error if no SanityInstance is found in context\n * @throws Error if no matching instance is found for the provided config\n */\nexport const useSanityInstance = (config?: SanityConfig): SanityInstance => {\n const instance = useContext(SanityInstanceContext)\n\n if (!instance) {\n throw new Error(\n `SanityInstance context not found. ${config ? `Requested config: ${JSON.stringify(config, null, 2)}. ` : ''}Please ensure that your component is wrapped in a <ResourceProvider> or a <SanityApp>.`,\n )\n }\n\n if (!config) return instance\n\n const match = instance.match(config)\n if (!match) {\n throw new Error(\n `Could not find a matching Sanity instance for the requested configuration: ${JSON.stringify(config, null, 2)}.\nPlease ensure there is a <ResourceProvider> with a matching configuration in the component hierarchy.`,\n )\n }\n\n return match\n}\n","import {type SanityConfig, type SanityInstance, type StateSource} from '@sanity/sdk'\nimport {useSyncExternalStore} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\ntype StateSourceFactory<TParams extends unknown[], TState> = (\n instance: SanityInstance,\n ...params: TParams\n) => StateSource<TState>\n\ninterface CreateStateSourceHookOptions<TParams extends unknown[], TState> {\n getState: StateSourceFactory<TParams, TState>\n shouldSuspend?: (instance: SanityInstance, ...params: TParams) => boolean\n suspender?: (instance: SanityInstance, ...params: TParams) => Promise<unknown>\n getConfig?: (...params: TParams) => SanityConfig | undefined\n}\n\nexport function createStateSourceHook<TParams extends unknown[], TState>(\n options: StateSourceFactory<TParams, TState> | CreateStateSourceHookOptions<TParams, TState>,\n): (...params: TParams) => TState {\n const getState = typeof options === 'function' ? options : options.getState\n const getConfig = 'getConfig' in options ? options.getConfig : undefined\n const suspense = 'shouldSuspend' in options && 'suspender' in options ? options : undefined\n\n function useHook(...params: TParams) {\n const instance = useSanityInstance(getConfig?.(...params))\n\n if (suspense?.suspender && suspense?.shouldSuspend?.(instance, ...params)) {\n throw suspense.suspender(instance, ...params)\n }\n\n const state = getState(instance, ...params)\n return useSyncExternalStore(state.subscribe, state.getCurrent)\n }\n\n return useHook\n}\n","import {type AuthState, getAuthState} from '@sanity/sdk'\n\nimport {createStateSourceHook} from '../helpers/createStateSourceHook'\n\n/**\n * @internal\n * A React hook that subscribes to authentication state changes.\n *\n * This hook provides access to the current authentication state type from the Sanity auth store.\n * It automatically re-renders when the authentication state changes.\n *\n * @remarks\n * The hook uses `useSyncExternalStore` to safely subscribe to auth state changes\n * and ensure consistency between server and client rendering.\n *\n * @returns The current authentication state type\n *\n * @example\n * ```tsx\n * function AuthStatus() {\n * const authState = useAuthState()\n * return <div>Current auth state: {authState}</div>\n * }\n * ```\n */\nexport const useAuthState: () => AuthState = createStateSourceHook(getAuthState)\n","import {getLoginUrlState} from '@sanity/sdk'\nimport {useMemo, useSyncExternalStore} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\n/**\n * @internal\n */\nexport function useLoginUrl(): string {\n const instance = useSanityInstance()\n const {subscribe, getCurrent} = useMemo(() => getLoginUrlState(instance), [instance])\n\n return useSyncExternalStore(subscribe, getCurrent as () => string)\n}\n","export function isInIframe(): boolean {\n return typeof window !== 'undefined' && window.self !== window.top\n}\n\n/**\n * @internal\n *\n * Checks if the current URL is a local URL.\n *\n * @param window - The window object\n * @returns True if the current URL is a local URL, false otherwise\n */\nexport function isLocalUrl(window: Window): boolean {\n const url = typeof window !== 'undefined' ? window.location.href : ''\n\n return (\n url.startsWith('http://localhost') ||\n url.startsWith('https://localhost') ||\n url.startsWith('http://127.0.0.1') ||\n url.startsWith('https://127.0.0.1')\n )\n}\n","/**\n * Error class for authentication-related errors. Wraps errors thrown during the\n * authentication flow.\n *\n * @remarks\n * This class provides a consistent error type for authentication failures while\n * preserving the original error as the cause. If the original error has a\n * message property, it will be used as the error message.\n *\n * @alpha\n */\nexport class AuthError extends Error {\n constructor(error: unknown) {\n if (\n typeof error === 'object' &&\n !!error &&\n 'message' in error &&\n typeof error.message === 'string'\n ) {\n super(error.message)\n } else {\n super()\n }\n\n this.cause = error\n }\n}\n","import {type SanityInstance} from '@sanity/sdk'\nimport {useCallback} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\nexport function createCallbackHook<TParams extends unknown[], TReturn>(\n callback: (instance: SanityInstance, ...params: TParams) => TReturn,\n): () => (...params: TParams) => TReturn {\n function useHook() {\n const instance = useSanityInstance()\n return useCallback((...params: TParams) => callback(instance, ...params), [instance])\n }\n\n return useHook\n}\n","import {handleAuthCallback} from '@sanity/sdk'\n\nimport {createCallbackHook} from '../helpers/createCallbackHook'\n\n/**\n * @internal\n * A React hook that returns a function for handling authentication callbacks.\n *\n * @remarks\n * This hook provides access to the authentication store's callback handler,\n * which processes auth redirects by extracting the session ID and fetching the\n * authentication token. If fetching the long-lived token is successful,\n * `handleAuthCallback` will return a Promise that resolves a new location that\n * removes the short-lived token from the URL. Use this in combination with\n * `history.replaceState` or your own router's `replace` function to update the\n * current location without triggering a reload.\n *\n * @example\n * ```tsx\n * function AuthCallback() {\n * const handleAuthCallback = useHandleAuthCallback()\n * const router = useRouter() // Example router\n *\n * useEffect(() => {\n * async function processCallback() {\n * // Handle the callback and get the cleaned URL\n * const newUrl = await handleAuthCallback(window.location.href)\n *\n * if (newUrl) {\n * // Replace URL without triggering navigation\n * router.replace(newUrl, {shallow: true})\n * }\n * }\n *\n * processCallback().catch(console.error)\n * }, [handleAuthCallback, router])\n *\n * return <div>Completing login...</div>\n * }\n * ```\n *\n * @returns A callback handler function that processes OAuth redirects\n * @public\n */\nexport const useHandleAuthCallback = createCallbackHook(handleAuthCallback)\n","import {useEffect} from 'react'\n\nimport {useHandleAuthCallback} from '../../hooks/auth/useHandleAuthCallback'\n\n/**\n * Component shown during auth callback processing that handles login completion.\n * Automatically processes the auth callback when mounted and updates the URL\n * to remove callback parameters without triggering a page reload.\n *\n * @alpha\n */\nexport function LoginCallback(): React.ReactNode {\n const handleAuthCallback = useHandleAuthCallback()\n\n useEffect(() => {\n const url = new URL(location.href)\n handleAuthCallback(url.toString()).then((replacementLocation) => {\n if (replacementLocation) {\n // history API with `replaceState` is used to prevent a reload but still\n // remove the short-lived token from the URL\n history.replaceState(null, '', replacementLocation)\n }\n })\n }, [handleAuthCallback])\n\n return null\n}\n","const e=!(typeof navigator>\"u\")&&\"ReactNative\"===navigator.product,t={timeout:e?6e4:12e4},r=function(r){const a={...t,...\"string\"==typeof r?{url:r}:r};if(a.timeout=o(a.timeout),a.query){const{url:t,searchParams:r}=function(t){const r=t.indexOf(\"?\");if(-1===r)return{url:t,searchParams:new URLSearchParams};const o=t.slice(0,r),a=t.slice(r+1);if(!e)return{url:o,searchParams:new URLSearchParams(a)};if(\"function\"!=typeof decodeURIComponent)throw new Error(\"Broken `URLSearchParams` implementation, and `decodeURIComponent` is not defined\");const s=new URLSearchParams;for(const e of a.split(\"&\")){const[t,r]=e.split(\"=\");t&&s.append(n(t),n(r||\"\"))}return{url:o,searchParams:s}}(a.url);for(const[e,n]of Object.entries(a.query)){if(void 0!==n)if(Array.isArray(n))for(const t of n)r.append(e,t);else r.append(e,n);const o=r.toString();o&&(a.url=`${t}?${o}`)}}return a.method=a.body&&!a.method?\"POST\":(a.method||\"GET\").toUpperCase(),a};function n(e){return decodeURIComponent(e.replace(/\\+/g,\" \"))}function o(e){if(!1===e||0===e)return!1;if(e.connect||e.socket)return e;const r=Number(e);return isNaN(r)?o(t.timeout):{connect:r,socket:r}}const a=/^https?:\\/\\//i,s=function(e){if(!a.test(e.url))throw new Error(`\"${e.url}\" is not a valid URL`)};export{r as p,s as v};//# sourceMappingURL=defaultOptionsValidator.js.map\n","import{p as e,v as t}from\"./defaultOptionsValidator.js\";const r=[\"request\",\"response\",\"progress\",\"error\",\"abort\"],o=[\"processOptions\",\"validateOptions\",\"interceptRequest\",\"finalizeOptions\",\"onRequest\",\"onResponse\",\"onError\",\"onReturn\",\"onHeaders\"];function n(s,i){const u=[],a=o.reduce(((e,t)=>(e[t]=e[t]||[],e)),{processOptions:[e],validateOptions:[t]});function c(e){const t=r.reduce(((e,t)=>(e[t]=function(){const e=/* @__PURE__ */Object.create(null);let t=0;return{publish:function(t){for(const r in e)e[r](t)},subscribe:function(r){const o=t++;return e[o]=r,function(){delete e[o]}}}}(),e)),{}),o=(e=>function(t,r,...o){const n=\"onError\"===t;let s=r;for(let r=0;r<e[t].length&&(s=(0,e[t][r])(s,...o),!n||s);r++);return s})(a),n=o(\"processOptions\",e);o(\"validateOptions\",n);const s={options:n,channels:t,applyMiddleware:o};let u;const c=t.request.subscribe((e=>{u=i(e,((r,n)=>((e,r,n)=>{let s=e,i=r;if(!s)try{i=o(\"onResponse\",r,n)}catch(e){i=null,s=e}s=s&&o(\"onError\",s,n),s?t.error.publish(s):i&&t.response.publish(i)})(r,n,e)))}));t.abort.subscribe((()=>{c(),u&&u.abort()}));const l=o(\"onReturn\",t,s);return l===t&&t.request.publish(s),l}return c.use=function(e){if(!e)throw new Error(\"Tried to add middleware that resolved to falsey value\");if(\"function\"==typeof e)throw new Error(\"Tried to add middleware that was a function. It probably expects you to pass options to it.\");if(e.onReturn&&a.onReturn.length>0)throw new Error(\"Tried to add new middleware with `onReturn` handler, but another handler has already been registered for this event\");return o.forEach((t=>{e[t]&&a[t].push(e[t])})),u.push(e),c},c.clone=()=>n(u,i),s.forEach(c.use),c}export{n as c};//# sourceMappingURL=createRequester.js.map\n","'use strict';\n\n// We define these manually to ensure they're always copied\n// even if they would move up the prototype chain\n// https://nodejs.org/api/http.html#http_class_http_incomingmessage\nconst knownProperties = [\n\t'aborted',\n\t'complete',\n\t'headers',\n\t'httpVersion',\n\t'httpVersionMinor',\n\t'httpVersionMajor',\n\t'method',\n\t'rawHeaders',\n\t'rawTrailers',\n\t'setTimeout',\n\t'socket',\n\t'statusCode',\n\t'statusMessage',\n\t'trailers',\n\t'url'\n];\n\nmodule.exports = (fromStream, toStream) => {\n\tif (toStream._readableState.autoDestroy) {\n\t\tthrow new Error('The second stream must have the `autoDestroy` option set to `false`');\n\t}\n\n\tconst fromProperties = new Set(Object.keys(fromStream).concat(knownProperties));\n\n\tconst properties = {};\n\n\tfor (const property of fromProperties) {\n\t\t// Don't overwrite existing properties.\n\t\tif (property in toStream) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tproperties[property] = {\n\t\t\tget() {\n\t\t\t\tconst value = fromStream[property];\n\t\t\t\tconst isFunction = typeof value === 'function';\n\n\t\t\t\treturn isFunction ? value.bind(fromStream) : value;\n\t\t\t},\n\t\t\tset(value) {\n\t\t\t\tfromStream[property] = value;\n\t\t\t},\n\t\t\tenumerable: true,\n\t\t\tconfigurable: false\n\t\t};\n\t}\n\n\tObject.defineProperties(toStream, properties);\n\n\tfromStream.once('aborted', () => {\n\t\ttoStream.destroy();\n\n\t\ttoStream.emit('aborted');\n\t});\n\n\tfromStream.once('close', () => {\n\t\tif (fromStream.complete) {\n\t\t\tif (toStream.readable) {\n\t\t\t\ttoStream.once('end', () => {\n\t\t\t\t\ttoStream.emit('close');\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\ttoStream.emit('close');\n\t\t\t}\n\t\t} else {\n\t\t\ttoStream.emit('close');\n\t\t}\n\t});\n\n\treturn toStream;\n};\n","'use strict';\nconst {Transform, PassThrough} = require('stream');\nconst zlib = require('zlib');\nconst mimicResponse = require('mimic-response');\n\nmodule.exports = response => {\n\tconst contentEncoding = (response.headers['content-encoding'] || '').toLowerCase();\n\tdelete response.headers['content-encoding'];\n\n\tif (!['gzip', 'deflate', 'br'].includes(contentEncoding)) {\n\t\treturn response;\n\t}\n\n\t// TODO: Remove this when targeting Node.js 12.\n\tconst isBrotli = contentEncoding === 'br';\n\tif (isBrotli && typeof zlib.createBrotliDecompress !== 'function') {\n\t\tresponse.destroy(new Error('Brotli is not supported on Node.js < 12'));\n\t\treturn response;\n\t}\n\n\tlet isEmpty = true;\n\n\tconst checker = new Transform({\n\t\ttransform(data, _encoding, callback) {\n\t\t\tisEmpty = false;\n\n\t\t\tcallback(null, data);\n\t\t},\n\n\t\tflush(callback) {\n\t\t\tcallback();\n\t\t}\n\t});\n\n\tconst finalStream = new PassThrough({\n\t\tautoDestroy: false,\n\t\tdestroy(error, callback) {\n\t\t\tresponse.destroy();\n\n\t\t\tcallback(error);\n\t\t}\n\t});\n\n\tconst decompressStream = isBrotli ? zlib.createBrotliDecompress() : zlib.createUnzip();\n\n\tdecompressStream.once('error', error => {\n\t\tif (isEmpty && !response.readable) {\n\t\t\tfinalStream.end();\n\t\t\treturn;\n\t\t}\n\n\t\tfinalStream.destroy(error);\n\t});\n\n\tmimicResponse(response, finalStream);\n\tresponse.pipe(checker).pipe(decompressStream).pipe(finalStream);\n\n\treturn finalStream;\n};\n","/**\n * Helpers.\n */\n\nvar s = 1000;\nvar m = s * 60;\nvar h = m * 60;\nvar d = h * 24;\nvar w = d * 7;\nvar y = d * 365.25;\n\n/**\n * Parse or format the given `val`.\n *\n * Options:\n *\n * - `long` verbose formatting [false]\n *\n * @param {String|Number} val\n * @param {Object} [options]\n * @throws {Error} throw an error if val is not a non-empty string or a number\n * @return {String|Number}\n * @api public\n */\n\nmodule.exports = function (val, options) {\n options = options || {};\n var type = typeof val;\n if (type === 'string' && val.length > 0) {\n return parse(val);\n } else if (type === 'number' && isFinite(val)) {\n return options.long ? fmtLong(val) : fmtShort(val);\n }\n throw new Error(\n 'val is not a non-empty string or a valid number. val=' +\n JSON.stringify(val)\n );\n};\n\n/**\n * Parse the given `str` and return milliseconds.\n *\n * @param {String} str\n * @return {Number}\n * @api private\n */\n\nfunction parse(str) {\n str = String(str);\n if (str.length > 100) {\n return;\n }\n var match = /^(-?(?:\\d+)?\\.?\\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(\n str\n );\n if (!match) {\n return;\n }\n var n = parseFloat(match[1]);\n var type = (match[2] || 'ms').toLowerCase();\n switch (type) {\n case 'years':\n case 'year':\n case 'yrs':\n case 'yr':\n case 'y':\n return n * y;\n case 'weeks':\n case 'week':\n case 'w':\n return n * w;\n case 'days':\n case 'day':\n case 'd':\n return n * d;\n case 'hours':\n case 'hour':\n case 'hrs':\n case 'hr':\n case 'h':\n return n * h;\n case 'minutes':\n case 'minute':\n case 'mins':\n case 'min':\n case 'm':\n return n * m;\n case 'seconds':\n case 'second':\n case 'secs':\n case 'sec':\n case 's':\n return n * s;\n case 'milliseconds':\n case 'millisecond':\n case 'msecs':\n case 'msec':\n case 'ms':\n return n;\n default:\n return undefined;\n }\n}\n\n/**\n * Short format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtShort(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return Math.round(ms / d) + 'd';\n }\n if (msAbs >= h) {\n return Math.round(ms / h) + 'h';\n }\n if (msAbs >= m) {\n return Math.round(ms / m) + 'm';\n }\n if (msAbs >= s) {\n return Math.round(ms / s) + 's';\n }\n return ms + 'ms';\n}\n\n/**\n * Long format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtLong(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return plural(ms, msAbs, d, 'day');\n }\n if (msAbs >= h) {\n return plural(ms, msAbs, h, 'hour');\n }\n if (msAbs >= m) {\n return plural(ms, msAbs, m, 'minute');\n }\n if (msAbs >= s) {\n return plural(ms, msAbs, s, 'second');\n }\n return ms + ' ms';\n}\n\n/**\n * Pluralization helper.\n */\n\nfunction plural(ms, msAbs, n, name) {\n var isPlural = msAbs >= n * 1.5;\n return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');\n}\n","\n/**\n * This is the common logic for both the Node.js and web browser\n * implementations of `debug()`.\n */\n\nfunction setup(env) {\n\tcreateDebug.debug = createDebug;\n\tcreateDebug.default = createDebug;\n\tcreateDebug.coerce = coerce;\n\tcreateDebug.disable = disable;\n\tcreateDebug.enable = enable;\n\tcreateDebug.enabled = enabled;\n\tcreateDebug.humanize = require('ms');\n\tcreateDebug.destroy = destroy;\n\n\tObject.keys(env).forEach(key => {\n\t\tcreateDebug[key] = env[key];\n\t});\n\n\t/**\n\t* The currently active debug mode names, and names to skip.\n\t*/\n\n\tcreateDebug.names = [];\n\tcreateDebug.skips = [];\n\n\t/**\n\t* Map of special \"%n\" handling functions, for the debug \"format\" argument.\n\t*\n\t* Valid key names are a single, lower or upper-case letter, i.e. \"n\" and \"N\".\n\t*/\n\tcreateDebug.formatters = {};\n\n\t/**\n\t* Selects a color for a debug namespace\n\t* @param {String} namespace The namespace string for the debug instance to be colored\n\t* @return {Number|String} An ANSI color code for the given namespace\n\t* @api private\n\t*/\n\tfunction selectColor(namespace) {\n\t\tlet hash = 0;\n\n\t\tfor (let i = 0; i < namespace.length; i++) {\n\t\t\thash = ((hash << 5) - hash) + namespace.charCodeAt(i);\n\t\t\thash |= 0; // Convert to 32bit integer\n\t\t}\n\n\t\treturn createDebug.colors[Math.abs(hash) % createDebug.colors.length];\n\t}\n\tcreateDebug.selectColor = selectColor;\n\n\t/**\n\t* Create a debugger with the given `namespace`.\n\t*\n\t* @param {String} namespace\n\t* @return {Function}\n\t* @api public\n\t*/\n\tfunction createDebug(namespace) {\n\t\tlet prevTime;\n\t\tlet enableOverride = null;\n\t\tlet namespacesCache;\n\t\tlet enabledCache;\n\n\t\tfunction debug(...args) {\n\t\t\t// Disabled?\n\t\t\tif (!debug.enabled) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst self = debug;\n\n\t\t\t// Set `diff` timestamp\n\t\t\tconst curr = Number(new Date());\n\t\t\tconst ms = curr - (prevTime || curr);\n\t\t\tself.diff = ms;\n\t\t\tself.prev = prevTime;\n\t\t\tself.curr = curr;\n\t\t\tprevTime = curr;\n\n\t\t\targs[0] = createDebug.coerce(args[0]);\n\n\t\t\tif (typeof args[0] !== 'string') {\n\t\t\t\t// Anything else let's inspect with %O\n\t\t\t\targs.unshift('%O');\n\t\t\t}\n\n\t\t\t// Apply any `formatters` transformations\n\t\t\tlet index = 0;\n\t\t\targs[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {\n\t\t\t\t// If we encounter an escaped % then don't increase the array index\n\t\t\t\tif (match === '%%') {\n\t\t\t\t\treturn '%';\n\t\t\t\t}\n\t\t\t\tindex++;\n\t\t\t\tconst formatter = createDebug.formatters[format];\n\t\t\t\tif (typeof formatter === 'function') {\n\t\t\t\t\tconst val = args[index];\n\t\t\t\t\tmatch = formatter.call(self, val);\n\n\t\t\t\t\t// Now we need to remove `args[index]` since it's inlined in the `format`\n\t\t\t\t\targs.splice(index, 1);\n\t\t\t\t\tindex--;\n\t\t\t\t}\n\t\t\t\treturn match;\n\t\t\t});\n\n\t\t\t// Apply env-specific formatting (colors, etc.)\n\t\t\tcreateDebug.formatArgs.call(self, args);\n\n\t\t\tconst logFn = self.log || createDebug.log;\n\t\t\tlogFn.apply(self, args);\n\t\t}\n\n\t\tdebug.namespace = namespace;\n\t\tdebug.useColors = createDebug.useColors();\n\t\tdebug.color = createDebug.selectColor(namespace);\n\t\tdebug.extend = extend;\n\t\tdebug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.\n\n\t\tObject.defineProperty(debug, 'enabled', {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: false,\n\t\t\tget: () => {\n\t\t\t\tif (enableOverride !== null) {\n\t\t\t\t\treturn enableOverride;\n\t\t\t\t}\n\t\t\t\tif (namespacesCache !== createDebug.namespaces) {\n\t\t\t\t\tnamespacesCache = createDebug.namespaces;\n\t\t\t\t\tenabledCache = createDebug.enabled(namespace);\n\t\t\t\t}\n\n\t\t\t\treturn enabledCache;\n\t\t\t},\n\t\t\tset: v => {\n\t\t\t\tenableOverride = v;\n\t\t\t}\n\t\t});\n\n\t\t// Env-specific initialization logic for debug instances\n\t\tif (typeof createDebug.init === 'function') {\n\t\t\tcreateDebug.init(debug);\n\t\t}\n\n\t\treturn debug;\n\t}\n\n\tfunction extend(namespace, delimiter) {\n\t\tconst newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);\n\t\tnewDebug.log = this.log;\n\t\treturn newDebug;\n\t}\n\n\t/**\n\t* Enables a debug mode by namespaces. This can include modes\n\t* separated by a colon and wildcards.\n\t*\n\t* @param {String} namespaces\n\t* @api public\n\t*/\n\tfunction enable(namespaces) {\n\t\tcreateDebug.save(namespaces);\n\t\tcreateDebug.namespaces = namespaces;\n\n\t\tcreateDebug.names = [];\n\t\tcreateDebug.skips = [];\n\n\t\tconst split = (typeof namespaces === 'string' ? namespaces : '')\n\t\t\t.trim()\n\t\t\t.replace(' ', ',')\n\t\t\t.split(',')\n\t\t\t.filter(Boolean);\n\n\t\tfor (const ns of split) {\n\t\t\tif (ns[0] === '-') {\n\t\t\t\tcreateDebug.skips.push(ns.slice(1));\n\t\t\t} else {\n\t\t\t\tcreateDebug.names.push(ns);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Checks if the given string matches a namespace template, honoring\n\t * asterisks as wildcards.\n\t *\n\t * @param {String} search\n\t * @param {String} template\n\t * @return {Boolean}\n\t */\n\tfunction matchesTemplate(search, template) {\n\t\tlet searchIndex = 0;\n\t\tlet templateIndex = 0;\n\t\tlet starIndex = -1;\n\t\tlet matchIndex = 0;\n\n\t\twhile (searchIndex < search.length) {\n\t\t\tif (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === '*')) {\n\t\t\t\t// Match character or proceed with wildcard\n\t\t\t\tif (template[templateIndex] === '*') {\n\t\t\t\t\tstarIndex = templateIndex;\n\t\t\t\t\tmatchIndex = searchIndex;\n\t\t\t\t\ttemplateIndex++; // Skip the '*'\n\t\t\t\t} else {\n\t\t\t\t\tsearchIndex++;\n\t\t\t\t\ttemplateIndex++;\n\t\t\t\t}\n\t\t\t} else if (starIndex !== -1) { // eslint-disable-line no-negated-condition\n\t\t\t\t// Backtrack to the last '*' and try to match more characters\n\t\t\t\ttemplateIndex = starIndex + 1;\n\t\t\t\tmatchIndex++;\n\t\t\t\tsearchIndex = matchIndex;\n\t\t\t} else {\n\t\t\t\treturn false; // No match\n\t\t\t}\n\t\t}\n\n\t\t// Handle trailing '*' in template\n\t\twhile (templateIndex < template.length && template[templateIndex] === '*') {\n\t\t\ttemplateIndex++;\n\t\t}\n\n\t\treturn templateIndex === template.length;\n\t}\n\n\t/**\n\t* Disable debug output.\n\t*\n\t* @return {String} namespaces\n\t* @api public\n\t*/\n\tfunction disable() {\n\t\tconst namespaces = [\n\t\t\t...createDebug.names,\n\t\t\t...createDebug.skips.map(namespace => '-' + namespace)\n\t\t].join(',');\n\t\tcreateDebug.enable('');\n\t\treturn namespaces;\n\t}\n\n\t/**\n\t* Returns true if the given mode name is enabled, false otherwise.\n\t*\n\t* @param {String} name\n\t* @return {Boolean}\n\t* @api public\n\t*/\n\tfunction enabled(name) {\n\t\tfor (const skip of createDebug.skips) {\n\t\t\tif (matchesTemplate(name, skip)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\tfor (const ns of createDebug.names) {\n\t\t\tif (matchesTemplate(name, ns)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/**\n\t* Coerce `val`.\n\t*\n\t* @param {Mixed} val\n\t* @return {Mixed}\n\t* @api private\n\t*/\n\tfunction coerce(val) {\n\t\tif (val instanceof Error) {\n\t\t\treturn val.stack || val.message;\n\t\t}\n\t\treturn val;\n\t}\n\n\t/**\n\t* XXX DO NOT USE. This is a temporary stub function.\n\t* XXX It WILL be removed in the next major release.\n\t*/\n\tfunction destroy() {\n\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t}\n\n\tcreateDebug.enable(createDebug.load());\n\n\treturn createDebug;\n}\n\nmodule.exports = setup;\n","/* eslint-env browser */\n\n/**\n * This is the web browser implementation of `debug()`.\n */\n\nexports.formatArgs = formatArgs;\nexports.save = save;\nexports.load = load;\nexports.useColors = useColors;\nexports.storage = localstorage();\nexports.destroy = (() => {\n\tlet warned = false;\n\n\treturn () => {\n\t\tif (!warned) {\n\t\t\twarned = true;\n\t\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t\t}\n\t};\n})();\n\n/**\n * Colors.\n */\n\nexports.colors = [\n\t'#0000CC',\n\t'#0000FF',\n\t'#0033CC',\n\t'#0033FF',\n\t'#0066CC',\n\t'#0066FF',\n\t'#0099CC',\n\t'#0099FF',\n\t'#00CC00',\n\t'#00CC33',\n\t'#00CC66',\n\t'#00CC99',\n\t'#00CCCC',\n\t'#00CCFF',\n\t'#3300CC',\n\t'#3300FF',\n\t'#3333CC',\n\t'#3333FF',\n\t'#3366CC',\n\t'#3366FF',\n\t'#3399CC',\n\t'#3399FF',\n\t'#33CC00',\n\t'#33CC33',\n\t'#33CC66',\n\t'#33CC99',\n\t'#33CCCC',\n\t'#33CCFF',\n\t'#6600CC',\n\t'#6600FF',\n\t'#6633CC',\n\t'#6633FF',\n\t'#66CC00',\n\t'#66CC33',\n\t'#9900CC',\n\t'#9900FF',\n\t'#9933CC',\n\t'#9933FF',\n\t'#99CC00',\n\t'#99CC33',\n\t'#CC0000',\n\t'#CC0033',\n\t'#CC0066',\n\t'#CC0099',\n\t'#CC00CC',\n\t'#CC00FF',\n\t'#CC3300',\n\t'#CC3333',\n\t'#CC3366',\n\t'#CC3399',\n\t'#CC33CC',\n\t'#CC33FF',\n\t'#CC6600',\n\t'#CC6633',\n\t'#CC9900',\n\t'#CC9933',\n\t'#CCCC00',\n\t'#CCCC33',\n\t'#FF0000',\n\t'#FF0033',\n\t'#FF0066',\n\t'#FF0099',\n\t'#FF00CC',\n\t'#FF00FF',\n\t'#FF3300',\n\t'#FF3333',\n\t'#FF3366',\n\t'#FF3399',\n\t'#FF33CC',\n\t'#FF33FF',\n\t'#FF6600',\n\t'#FF6633',\n\t'#FF9900',\n\t'#FF9933',\n\t'#FFCC00',\n\t'#FFCC33'\n];\n\n/**\n * Currently only WebKit-based Web Inspectors, Firefox >= v31,\n * and the Firebug extension (any Firefox version) are known\n * to support \"%c\" CSS customizations.\n *\n * TODO: add a `localStorage` variable to explicitly enable/disable colors\n */\n\n// eslint-disable-next-line complexity\nfunction useColors() {\n\t// NB: In an Electron preload script, document will be defined but not fully\n\t// initialized. Since we know we're in Chrome, we'll just detect this case\n\t// explicitly\n\tif (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {\n\t\treturn true;\n\t}\n\n\t// Internet Explorer and Edge do not support colors.\n\tif (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\\/(\\d+)/)) {\n\t\treturn false;\n\t}\n\n\tlet m;\n\n\t// Is webkit? http://stackoverflow.com/a/16459606/376773\n\t// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632\n\t// eslint-disable-next-line no-return-assign\n\treturn (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||\n\t\t// Is firebug? http://stackoverflow.com/a/398120/376773\n\t\t(typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||\n\t\t// Is firefox >= v31?\n\t\t// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages\n\t\t(typeof navigator !== 'undefined' && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\\/(\\d+)/)) && parseInt(m[1], 10) >= 31) ||\n\t\t// Double check webkit in userAgent just in case we are in a worker\n\t\t(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\\/(\\d+)/));\n}\n\n/**\n * Colorize log arguments if enabled.\n *\n * @api public\n */\n\nfunction formatArgs(args) {\n\targs[0] = (this.useColors ? '%c' : '') +\n\t\tthis.namespace +\n\t\t(this.useColors ? ' %c' : ' ') +\n\t\targs[0] +\n\t\t(this.useColors ? '%c ' : ' ') +\n\t\t'+' + module.exports.humanize(this.diff);\n\n\tif (!this.useColors) {\n\t\treturn;\n\t}\n\n\tconst c = 'color: ' + this.color;\n\targs.splice(1, 0, c, 'color: inherit');\n\n\t// The final \"%c\" is somewhat tricky, because there could be other\n\t// arguments passed either before or after the %c, so we need to\n\t// figure out the correct index to insert the CSS into\n\tlet index = 0;\n\tlet lastC = 0;\n\targs[0].replace(/%[a-zA-Z%]/g, match => {\n\t\tif (match === '%%') {\n\t\t\treturn;\n\t\t}\n\t\tindex++;\n\t\tif (match === '%c') {\n\t\t\t// We only are interested in the *last* %c\n\t\t\t// (the user may have provided their own)\n\t\t\tlastC = index;\n\t\t}\n\t});\n\n\targs.splice(lastC, 0, c);\n}\n\n/**\n * Invokes `console.debug()` when available.\n * No-op when `console.debug` is not a \"function\".\n * If `console.debug` is not available, falls back\n * to `console.log`.\n *\n * @api public\n */\nexports.log = console.debug || console.log || (() => {});\n\n/**\n * Save `namespaces`.\n *\n * @param {String} namespaces\n * @api private\n */\nfunction save(namespaces) {\n\ttry {\n\t\tif (namespaces) {\n\t\t\texports.storage.setItem('debug', namespaces);\n\t\t} else {\n\t\t\texports.storage.removeItem('debug');\n\t\t}\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n}\n\n/**\n * Load `namespaces`.\n *\n * @return {String} returns the previously persisted debug modes\n * @api private\n */\nfunction load() {\n\tlet r;\n\ttry {\n\t\tr = exports.storage.getItem('debug');\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n\n\t// If debug isn't set in LS, and we're in Electron, try to load $DEBUG\n\tif (!r && typeof process !== 'undefined' && 'env' in process) {\n\t\tr = process.env.DEBUG;\n\t}\n\n\treturn r;\n}\n\n/**\n * Localstorage attempts to return the localstorage.\n *\n * This is necessary because safari throws\n * when a user disables cookies/localstorage\n * and you attempt to access it.\n *\n * @return {LocalStorage}\n * @api private\n */\n\nfunction localstorage() {\n\ttry {\n\t\t// TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context\n\t\t// The Browser also has localStorage in the global context.\n\t\treturn localStorage;\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n}\n\nmodule.exports = require('./common')(exports);\n\nconst {formatters} = module.exports;\n\n/**\n * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.\n */\n\nformatters.j = function (v) {\n\ttry {\n\t\treturn JSON.stringify(v);\n\t} catch (error) {\n\t\treturn '[UnexpectedJSONParseError]: ' + error.message;\n\t}\n};\n","'use strict';\n\nmodule.exports = (flag, argv = process.argv) => {\n\tconst prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--');\n\tconst position = argv.indexOf(prefix + flag);\n\tconst terminatorPosition = argv.indexOf('--');\n\treturn position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);\n};\n","'use strict';\nconst os = require('os');\nconst tty = require('tty');\nconst hasFlag = require('has-flag');\n\nconst {env} = process;\n\nlet forceColor;\nif (hasFlag('no-color') ||\n\thasFlag('no-colors') ||\n\thasFlag('color=false') ||\n\thasFlag('color=never')) {\n\tforceColor = 0;\n} else if (hasFlag('color') ||\n\thasFlag('colors') ||\n\thasFlag('color=true') ||\n\thasFlag('color=always')) {\n\tforceColor = 1;\n}\n\nif ('FORCE_COLOR' in env) {\n\tif (env.FORCE_COLOR === 'true') {\n\t\tforceColor = 1;\n\t} else if (env.FORCE_COLOR === 'false') {\n\t\tforceColor = 0;\n\t} else {\n\t\tforceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3);\n\t}\n}\n\nfunction translateLevel(level) {\n\tif (level === 0) {\n\t\treturn false;\n\t}\n\n\treturn {\n\t\tlevel,\n\t\thasBasic: true,\n\t\thas256: level >= 2,\n\t\thas16m: level >= 3\n\t};\n}\n\nfunction supportsColor(haveStream, streamIsTTY) {\n\tif (forceColor === 0) {\n\t\treturn 0;\n\t}\n\n\tif (hasFlag('color=16m') ||\n\t\thasFlag('color=full') ||\n\t\thasFlag('color=truecolor')) {\n\t\treturn 3;\n\t}\n\n\tif (hasFlag('color=256')) {\n\t\treturn 2;\n\t}\n\n\tif (haveStream && !streamIsTTY && forceColor === undefined) {\n\t\treturn 0;\n\t}\n\n\tconst min = forceColor || 0;\n\n\tif (env.TERM === 'dumb') {\n\t\treturn min;\n\t}\n\n\tif (process.platform === 'win32') {\n\t\t// Windows 10 build 10586 is the first Windows release that supports 256 colors.\n\t\t// Windows 10 build 14931 is the first release that supports 16m/TrueColor.\n\t\tconst osRelease = os.release().split('.');\n\t\tif (\n\t\t\tNumber(osRelease[0]) >= 10 &&\n\t\t\tNumber(osRelease[2]) >= 10586\n\t\t) {\n\t\t\treturn Number(osRelease[2]) >= 14931 ? 3 : 2;\n\t\t}\n\n\t\treturn 1;\n\t}\n\n\tif ('CI' in env) {\n\t\tif (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'GITHUB_ACTIONS', 'BUILDKITE'].some(sign => sign in env) || env.CI_NAME === 'codeship') {\n\t\t\treturn 1;\n\t\t}\n\n\t\treturn min;\n\t}\n\n\tif ('TEAMCITY_VERSION' in env) {\n\t\treturn /^(9\\.(0*[1-9]\\d*)\\.|\\d{2,}\\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;\n\t}\n\n\tif (env.COLORTERM === 'truecolor') {\n\t\treturn 3;\n\t}\n\n\tif ('TERM_PROGRAM' in env) {\n\t\tconst version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10);\n\n\t\tswitch (env.TERM_PROGRAM) {\n\t\t\tcase 'iTerm.app':\n\t\t\t\treturn version >= 3 ? 3 : 2;\n\t\t\tcase 'Apple_Terminal':\n\t\t\t\treturn 2;\n\t\t\t// No default\n\t\t}\n\t}\n\n\tif (/-256(color)?$/i.test(env.TERM)) {\n\t\treturn 2;\n\t}\n\n\tif (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {\n\t\treturn 1;\n\t}\n\n\tif ('COLORTERM' in env) {\n\t\treturn 1;\n\t}\n\n\treturn min;\n}\n\nfunction getSupportLevel(stream) {\n\tconst level = supportsColor(stream, stream && stream.isTTY);\n\treturn translateLevel(level);\n}\n\nmodule.exports = {\n\tsupportsColor: getSupportLevel,\n\tstdout: translateLevel(supportsColor(true, tty.isatty(1))),\n\tstderr: translateLevel(supportsColor(true, tty.isatty(2)))\n};\n","/**\n * Module dependencies.\n */\n\nconst tty = require('tty');\nconst util = require('util');\n\n/**\n * This is the Node.js implementation of `debug()`.\n */\n\nexports.init = init;\nexports.log = log;\nexports.formatArgs = formatArgs;\nexports.save = save;\nexports.load = load;\nexports.useColors = useColors;\nexports.destroy = util.deprecate(\n\t() => {},\n\t'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'\n);\n\n/**\n * Colors.\n */\n\nexports.colors = [6, 2, 3, 4, 5, 1];\n\ntry {\n\t// Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json)\n\t// eslint-disable-next-line import/no-extraneous-dependencies\n\tconst supportsColor = require('supports-color');\n\n\tif (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) {\n\t\texports.colors = [\n\t\t\t20,\n\t\t\t21,\n\t\t\t26,\n\t\t\t27,\n\t\t\t32,\n\t\t\t33,\n\t\t\t38,\n\t\t\t39,\n\t\t\t40,\n\t\t\t41,\n\t\t\t42,\n\t\t\t43,\n\t\t\t44,\n\t\t\t45,\n\t\t\t56,\n\t\t\t57,\n\t\t\t62,\n\t\t\t63,\n\t\t\t68,\n\t\t\t69,\n\t\t\t74,\n\t\t\t75,\n\t\t\t76,\n\t\t\t77,\n\t\t\t78,\n\t\t\t79,\n\t\t\t80,\n\t\t\t81,\n\t\t\t92,\n\t\t\t93,\n\t\t\t98,\n\t\t\t99,\n\t\t\t112,\n\t\t\t113,\n\t\t\t128,\n\t\t\t129,\n\t\t\t134,\n\t\t\t135,\n\t\t\t148,\n\t\t\t149,\n\t\t\t160,\n\t\t\t161,\n\t\t\t162,\n\t\t\t163,\n\t\t\t164,\n\t\t\t165,\n\t\t\t166,\n\t\t\t167,\n\t\t\t168,\n\t\t\t169,\n\t\t\t170,\n\t\t\t171,\n\t\t\t172,\n\t\t\t173,\n\t\t\t178,\n\t\t\t179,\n\t\t\t184,\n\t\t\t185,\n\t\t\t196,\n\t\t\t197,\n\t\t\t198,\n\t\t\t199,\n\t\t\t200,\n\t\t\t201,\n\t\t\t202,\n\t\t\t203,\n\t\t\t204,\n\t\t\t205,\n\t\t\t206,\n\t\t\t207,\n\t\t\t208,\n\t\t\t209,\n\t\t\t214,\n\t\t\t215,\n\t\t\t220,\n\t\t\t221\n\t\t];\n\t}\n} catch (error) {\n\t// Swallow - we only care if `supports-color` is available; it doesn't have to be.\n}\n\n/**\n * Build up the default `inspectOpts` object from the environment variables.\n *\n * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js\n */\n\nexports.inspectOpts = Object.keys(process.env).filter(key => {\n\treturn /^debug_/i.test(key);\n}).reduce((obj, key) => {\n\t// Camel-case\n\tconst prop = key\n\t\t.substring(6)\n\t\t.toLowerCase()\n\t\t.replace(/_([a-z])/g, (_, k) => {\n\t\t\treturn k.toUpperCase();\n\t\t});\n\n\t// Coerce string value into JS value\n\tlet val = process.env[key];\n\tif (/^(yes|on|true|enabled)$/i.test(val)) {\n\t\tval = true;\n\t} else if (/^(no|off|false|disabled)$/i.test(val)) {\n\t\tval = false;\n\t} else if (val === 'null') {\n\t\tval = null;\n\t} else {\n\t\tval = Number(val);\n\t}\n\n\tobj[prop] = val;\n\treturn obj;\n}, {});\n\n/**\n * Is stdout a TTY? Colored output is enabled when `true`.\n */\n\nfunction useColors() {\n\treturn 'colors' in exports.inspectOpts ?\n\t\tBoolean(exports.inspectOpts.colors) :\n\t\ttty.isatty(process.stderr.fd);\n}\n\n/**\n * Adds ANSI color escape codes if enabled.\n *\n * @api public\n */\n\nfunction formatArgs(args) {\n\tconst {namespace: name, useColors} = this;\n\n\tif (useColors) {\n\t\tconst c = this.color;\n\t\tconst colorCode = '\\u001B[3' + (c < 8 ? c : '8;5;' + c);\n\t\tconst prefix = ` ${colorCode};1m${name} \\u001B[0m`;\n\n\t\targs[0] = prefix + args[0].split('\\n').join('\\n' + prefix);\n\t\targs.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\\u001B[0m');\n\t} else {\n\t\targs[0] = getDate() + name + ' ' + args[0];\n\t}\n}\n\nfunction getDate() {\n\tif (exports.inspectOpts.hideDate) {\n\t\treturn '';\n\t}\n\treturn new Date().toISOString() + ' ';\n}\n\n/**\n * Invokes `util.formatWithOptions()` with the specified arguments and writes to stderr.\n */\n\nfunction log(...args) {\n\treturn process.stderr.write(util.formatWithOptions(exports.inspectOpts, ...args) + '\\n');\n}\n\n/**\n * Save `namespaces`.\n *\n * @param {String} namespaces\n * @api private\n */\nfunction save(namespaces) {\n\tif (namespaces) {\n\t\tprocess.env.DEBUG = namespaces;\n\t} else {\n\t\t// If you set a process.env field to null or undefined, it gets cast to the\n\t\t// string 'null' or 'undefined'. Just delete instead.\n\t\tdelete process.env.DEBUG;\n\t}\n}\n\n/**\n * Load `namespaces`.\n *\n * @return {String} returns the previously persisted debug modes\n * @api private\n */\n\nfunction load() {\n\treturn process.env.DEBUG;\n}\n\n/**\n * Init logic for `debug` instances.\n *\n * Create a new `inspectOpts` object in case `useColors` is set\n * differently for a particular `debug` instance.\n */\n\nfunction init(debug) {\n\tdebug.inspectOpts = {};\n\n\tconst keys = Object.keys(exports.inspectOpts);\n\tfor (let i = 0; i < keys.length; i++) {\n\t\tdebug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];\n\t}\n}\n\nmodule.exports = require('./common')(exports);\n\nconst {formatters} = module.exports;\n\n/**\n * Map %o to `util.inspect()`, all on a single line.\n */\n\nformatters.o = function (v) {\n\tthis.inspectOpts.colors = this.useColors;\n\treturn util.inspect(v, this.inspectOpts)\n\t\t.split('\\n')\n\t\t.map(str => str.trim())\n\t\t.join(' ');\n};\n\n/**\n * Map %O to `util.inspect()`, allowing multiple lines if needed.\n */\n\nformatters.O = function (v) {\n\tthis.inspectOpts.colors = this.useColors;\n\treturn util.inspect(v, this.inspectOpts);\n};\n","/**\n * Detect Electron renderer / nwjs process, which is node, but we should\n * treat as a browser.\n */\n\nif (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) {\n\tmodule.exports = require('./browser.js');\n} else {\n\tmodule.exports = require('./node.js');\n}\n","var debug;\n\nmodule.exports = function () {\n if (!debug) {\n try {\n /* eslint global-require: off */\n debug = require(\"debug\")(\"follow-redirects\");\n }\n catch (error) { /* */ }\n if (typeof debug !== \"function\") {\n debug = function () { /* */ };\n }\n }\n debug.apply(null, arguments);\n};\n","var url = require(\"url\");\nvar URL = url.URL;\nvar http = require(\"http\");\nvar https = require(\"https\");\nvar Writable = require(\"stream\").Writable;\nvar assert = require(\"assert\");\nvar debug = require(\"./debug\");\n\n// Preventive platform detection\n// istanbul ignore next\n(function detectUnsupportedEnvironment() {\n var looksLikeNode = typeof process !== \"undefined\";\n var looksLikeBrowser = typeof window !== \"undefined\" && typeof document !== \"undefined\";\n var looksLikeV8 = isFunction(Error.captureStackTrace);\n if (!looksLikeNode && (looksLikeBrowser || !looksLikeV8)) {\n console.warn(\"The follow-redirects package should be excluded from browser builds.\");\n }\n}());\n\n// Whether to use the native URL object or the legacy url module\nvar useNativeURL = false;\ntry {\n assert(new URL(\"\"));\n}\ncatch (error) {\n useNativeURL = error.code === \"ERR_INVALID_URL\";\n}\n\n// URL fields to preserve in copy operations\nvar preservedUrlFields = [\n \"auth\",\n \"host\",\n \"hostname\",\n \"href\",\n \"path\",\n \"pathname\",\n \"port\",\n \"protocol\",\n \"query\",\n \"search\",\n \"hash\",\n];\n\n// Create handlers that pass events from native requests\nvar events = [\"abort\", \"aborted\", \"connect\", \"error\", \"socket\", \"timeout\"];\nvar eventHandlers = Object.create(null);\nevents.forEach(function (event) {\n eventHandlers[event] = function (arg1, arg2, arg3) {\n this._redirectable.emit(event, arg1, arg2, arg3);\n };\n});\n\n// Error types with codes\nvar InvalidUrlError = createErrorType(\n \"ERR_INVALID_URL\",\n \"Invalid URL\",\n TypeError\n);\nvar RedirectionError = createErrorType(\n \"ERR_FR_REDIRECTION_FAILURE\",\n \"Redirected request failed\"\n);\nvar TooManyRedirectsError = createErrorType(\n \"ERR_FR_TOO_MANY_REDIRECTS\",\n \"Maximum number of redirects exceeded\",\n RedirectionError\n);\nvar MaxBodyLengthExceededError = createErrorType(\n \"ERR_FR_MAX_BODY_LENGTH_EXCEEDED\",\n \"Request body larger than maxBodyLength limit\"\n);\nvar WriteAfterEndError = createErrorType(\n \"ERR_STREAM_WRITE_AFTER_END\",\n \"write after end\"\n);\n\n// istanbul ignore next\nvar destroy = Writable.prototype.destroy || noop;\n\n// An HTTP(S) request that can be redirected\nfunction RedirectableRequest(options, responseCallback) {\n // Initialize the request\n Writable.call(this);\n this._sanitizeOptions(options);\n this._options = options;\n this._ended = false;\n this._ending = false;\n this._redirectCount = 0;\n this._redirects = [];\n this._requestBodyLength = 0;\n this._requestBodyBuffers = [];\n\n // Attach a callback if passed\n if (responseCallback) {\n this.on(\"response\", responseCallback);\n }\n\n // React to responses of native requests\n var self = this;\n this._onNativeResponse = function (response) {\n try {\n self._processResponse(response);\n }\n catch (cause) {\n self.emit(\"error\", cause instanceof RedirectionError ?\n cause : new RedirectionError({ cause: cause }));\n }\n };\n\n // Perform the first request\n this._performRequest();\n}\nRedirectableRequest.prototype = Object.create(Writable.prototype);\n\nRedirectableRequest.prototype.abort = function () {\n destroyRequest(this._currentRequest);\n this._currentRequest.abort();\n this.emit(\"abort\");\n};\n\nRedirectableRequest.prototype.destroy = function (error) {\n destroyRequest(this._currentRequest, error);\n destroy.call(this, error);\n return this;\n};\n\n// Writes buffered data to the current native request\nRedirectableRequest.prototype.write = function (data, encoding, callback) {\n // Writing is not allowed if end has been called\n if (this._ending) {\n throw new WriteAfterEndError();\n }\n\n // Validate input and shift parameters if necessary\n if (!isString(data) && !isBuffer(data)) {\n throw new TypeError(\"data should be a string, Buffer or Uint8Array\");\n }\n if (isFunction(encoding)) {\n callback = encoding;\n encoding = null;\n }\n\n // Ignore empty buffers, since writing them doesn't invoke the callback\n // https://github.com/nodejs/node/issues/22066\n if (data.length === 0) {\n if (callback) {\n callback();\n }\n return;\n }\n // Only write when we don't exceed the maximum body length\n if (this._requestBodyLength + data.length <= this._options.maxBodyLength) {\n this._requestBodyLength += data.length;\n this._requestBodyBuffers.push({ data: data, encoding: encoding });\n this._currentRequest.write(data, encoding, callback);\n }\n // Error when we exceed the maximum body length\n else {\n this.emit(\"error\", new MaxBodyLengthExceededError());\n this.abort();\n }\n};\n\n// Ends the current native request\nRedirectableRequest.prototype.end = function (data, encoding, callback) {\n // Shift parameters if necessary\n if (isFunction(data)) {\n callback = data;\n data = encoding = null;\n }\n else if (isFunction(encoding)) {\n callback = encoding;\n encoding = null;\n }\n\n // Write data if needed and end\n if (!data) {\n this._ended = this._ending = true;\n this._currentRequest.end(null, null, callback);\n }\n else {\n var self = this;\n var currentRequest = this._currentRequest;\n this.write(data, encoding, function () {\n self._ended = true;\n currentRequest.end(null, null, callback);\n });\n this._ending = true;\n }\n};\n\n// Sets a header value on the current native request\nRedirectableRequest.prototype.setHeader = function (name, value) {\n this._options.headers[name] = value;\n this._currentRequest.setHeader(name, value);\n};\n\n// Clears a header value on the current native request\nRedirectableRequest.prototype.removeHeader = function (name) {\n delete this._options.headers[name];\n this._currentRequest.removeHeader(name);\n};\n\n// Global timeout for all underlying requests\nRedirectableRequest.prototype.setTimeout = function (msecs, callback) {\n var self = this;\n\n // Destroys the socket on timeout\n function destroyOnTimeout(socket) {\n socket.setTimeout(msecs);\n socket.removeListener(\"timeout\", socket.destroy);\n socket.addListener(\"timeout\", socket.destroy);\n }\n\n // Sets up a timer to trigger a timeout event\n function startTimer(socket) {\n if (self._timeout) {\n clearTimeout(self._timeout);\n }\n self._timeout = setTimeout(function () {\n self.emit(\"timeout\");\n clearTimer();\n }, msecs);\n destroyOnTimeout(socket);\n }\n\n // Stops a timeout from triggering\n function clearTimer() {\n // Clear the timeout\n if (self._timeout) {\n clearTimeout(self._timeout);\n self._timeout = null;\n }\n\n // Clean up all attached listeners\n self.removeListener(\"abort\", clearTimer);\n self.removeListener(\"error\", clearTimer);\n self.removeListener(\"response\", clearTimer);\n self.removeListener(\"close\", clearTimer);\n if (callback) {\n self.removeListener(\"timeout\", callback);\n }\n if (!self.socket) {\n self._currentRequest.removeListener(\"socket\", startTimer);\n }\n }\n\n // Attach callback if passed\n if (callback) {\n this.on(\"timeout\", callback);\n }\n\n // Start the timer if or when the socket is opened\n if (this.socket) {\n startTimer(this.socket);\n }\n else {\n this._currentRequest.once(\"socket\", startTimer);\n }\n\n // Clean up on events\n this.on(\"socket\", destroyOnTimeout);\n this.on(\"abort\", clearTimer);\n this.on(\"error\", clearTimer);\n this.on(\"response\", clearTimer);\n this.on(\"close\", clearTimer);\n\n return this;\n};\n\n// Proxy all other public ClientRequest methods\n[\n \"flushHeaders\", \"getHeader\",\n \"setNoDelay\", \"setSocketKeepAlive\",\n].forEach(function (method) {\n RedirectableRequest.prototype[method] = function (a, b) {\n return this._currentRequest[method](a, b);\n };\n});\n\n// Proxy all public ClientRequest properties\n[\"aborted\", \"connection\", \"socket\"].forEach(function (property) {\n Object.defineProperty(RedirectableRequest.prototype, property, {\n get: function () { return this._currentRequest[property]; },\n });\n});\n\nRedirectableRequest.prototype._sanitizeOptions = function (options) {\n // Ensure headers are always present\n if (!options.headers) {\n options.headers = {};\n }\n\n // Since http.request treats host as an alias of hostname,\n // but the url module interprets host as hostname plus port,\n // eliminate the host property to avoid confusion.\n if (options.host) {\n // Use hostname if set, because it has precedence\n if (!options.hostname) {\n options.hostname = options.host;\n }\n delete options.host;\n }\n\n // Complete the URL object when necessary\n if (!options.pathname && options.path) {\n var searchPos = options.path.indexOf(\"?\");\n if (searchPos < 0) {\n options.pathname = options.path;\n }\n else {\n options.pathname = options.path.substring(0, searchPos);\n options.search = options.path.substring(searchPos);\n }\n }\n};\n\n\n// Executes the next native request (initial or redirect)\nRedirectableRequest.prototype._performRequest = function () {\n // Load the native protocol\n var protocol = this._options.protocol;\n var nativeProtocol = this._options.nativeProtocols[protocol];\n if (!nativeProtocol) {\n throw new TypeError(\"Unsupported protocol \" + protocol);\n }\n\n // If specified, use the agent corresponding to the protocol\n // (HTTP and HTTPS use different types of agents)\n if (this._options.agents) {\n var scheme = protocol.slice(0, -1);\n this._options.agent = this._options.agents[scheme];\n }\n\n // Create the native request and set up its event handlers\n var request = this._currentRequest =\n nativeProtocol.request(this._options, this._onNativeResponse);\n request._redirectable = this;\n for (var event of events) {\n request.on(event, eventHandlers[event]);\n }\n\n // RFC7230§5.3.1: When making a request directly to an origin server, […]\n // a client MUST send only the absolute path […] as the request-target.\n this._currentUrl = /^\\//.test(this._options.path) ?\n url.format(this._options) :\n // When making a request to a proxy, […]\n // a client MUST send the target URI in absolute-form […].\n this._options.path;\n\n // End a redirected request\n // (The first request must be ended explicitly with RedirectableRequest#end)\n if (this._isRedirect) {\n // Write the request entity and end\n var i = 0;\n var self = this;\n var buffers = this._requestBodyBuffers;\n (function writeNext(error) {\n // Only write if this request has not been redirected yet\n // istanbul ignore else\n if (request === self._currentRequest) {\n // Report any write errors\n // istanbul ignore if\n if (error) {\n self.emit(\"error\", error);\n }\n // Write the next buffer if there are still left\n else if (i < buffers.length) {\n var buffer = buffers[i++];\n // istanbul ignore else\n if (!request.finished) {\n request.write(buffer.data, buffer.encoding, writeNext);\n }\n }\n // End the request if `end` has been called on us\n else if (self._ended) {\n request.end();\n }\n }\n }());\n }\n};\n\n// Processes a response from the current native request\nRedirectableRequest.prototype._processResponse = function (response) {\n // Store the redirected response\n var statusCode = response.statusCode;\n if (this._options.trackRedirects) {\n this._redirects.push({\n url: this._currentUrl,\n headers: response.headers,\n statusCode: statusCode,\n });\n }\n\n // RFC7231§6.4: The 3xx (Redirection) class of status code indicates\n // that further action needs to be taken by the user agent in order to\n // fulfill the request. If a Location header field is provided,\n // the user agent MAY automatically redirect its request to the URI\n // referenced by the Location field value,\n // even if the specific status code is not understood.\n\n // If the response is not a redirect; return it as-is\n var location = response.headers.location;\n if (!location || this._options.followRedirects === false ||\n statusCode < 300 || statusCode >= 400) {\n response.responseUrl = this._currentUrl;\n response.redirects = this._redirects;\n this.emit(\"response\", response);\n\n // Clean up\n this._requestBodyBuffers = [];\n return;\n }\n\n // The response is a redirect, so abort the current request\n destroyRequest(this._currentRequest);\n // Discard the remainder of the response to avoid waiting for data\n response.destroy();\n\n // RFC7231§6.4: A client SHOULD detect and intervene\n // in cyclical redirections (i.e., \"infinite\" redirection loops).\n if (++this._redirectCount > this._options.maxRedirects) {\n throw new TooManyRedirectsError();\n }\n\n // Store the request headers if applicable\n var requestHeaders;\n var beforeRedirect = this._options.beforeRedirect;\n if (beforeRedirect) {\n requestHeaders = Object.assign({\n // The Host header was set by nativeProtocol.request\n Host: response.req.getHeader(\"host\"),\n }, this._options.headers);\n }\n\n // RFC7231§6.4: Automatic redirection needs to done with\n // care for methods not known to be safe, […]\n // RFC7231§6.4.2–3: For historical reasons, a user agent MAY change\n // the request method from POST to GET for the subsequent request.\n var method = this._options.method;\n if ((statusCode === 301 || statusCode === 302) && this._options.method === \"POST\" ||\n // RFC7231§6.4.4: The 303 (See Other) status code indicates that\n // the server is redirecting the user agent to a different resource […]\n // A user agent can perform a retrieval request targeting that URI\n // (a GET or HEAD request if using HTTP) […]\n (statusCode === 303) && !/^(?:GET|HEAD)$/.test(this._options.method)) {\n this._options.method = \"GET\";\n // Drop a possible entity and headers related to it\n this._requestBodyBuffers = [];\n removeMatchingHeaders(/^content-/i, this._options.headers);\n }\n\n // Drop the Host header, as the redirect might lead to a different host\n var currentHostHeader = removeMatchingHeaders(/^host$/i, this._options.headers);\n\n // If the redirect is relative, carry over the host of the last request\n var currentUrlParts = parseUrl(this._currentUrl);\n var currentHost = currentHostHeader || currentUrlParts.host;\n var currentUrl = /^\\w+:/.test(location) ? this._currentUrl :\n url.format(Object.assign(currentUrlParts, { host: currentHost }));\n\n // Create the redirected request\n var redirectUrl = resolveUrl(location, currentUrl);\n debug(\"redirecting to\", redirectUrl.href);\n this._isRedirect = true;\n spreadUrlObject(redirectUrl, this._options);\n\n // Drop confidential headers when redirecting to a less secure protocol\n // or to a different domain that is not a superdomain\n if (redirectUrl.protocol !== currentUrlParts.protocol &&\n redirectUrl.protocol !== \"https:\" ||\n redirectUrl.host !== currentHost &&\n !isSubdomain(redirectUrl.host, currentHost)) {\n removeMatchingHeaders(/^(?:(?:proxy-)?authorization|cookie)$/i, this._options.headers);\n }\n\n // Evaluate the beforeRedirect callback\n if (isFunction(beforeRedirect)) {\n var responseDetails = {\n headers: response.headers,\n statusCode: statusCode,\n };\n var requestDetails = {\n url: currentUrl,\n method: method,\n headers: requestHeaders,\n };\n beforeRedirect(this._options, responseDetails, requestDetails);\n this._sanitizeOptions(this._options);\n }\n\n // Perform the redirected request\n this._performRequest();\n};\n\n// Wraps the key/value object of protocols with redirect functionality\nfunction wrap(protocols) {\n // Default settings\n var exports = {\n maxRedirects: 21,\n maxBodyLength: 10 * 1024 * 1024,\n };\n\n // Wrap each protocol\n var nativeProtocols = {};\n Object.keys(protocols).forEach(function (scheme) {\n var protocol = scheme + \":\";\n var nativeProtocol = nativeProtocols[protocol] = protocols[scheme];\n var wrappedProtocol = exports[scheme] = Object.create(nativeProtocol);\n\n // Executes a request, following redirects\n function request(input, options, callback) {\n // Parse parameters, ensuring that input is an object\n if (isURL(input)) {\n input = spreadUrlObject(input);\n }\n else if (isString(input)) {\n input = spreadUrlObject(parseUrl(input));\n }\n else {\n callback = options;\n options = validateUrl(input);\n input = { protocol: protocol };\n }\n if (isFunction(options)) {\n callback = options;\n options = null;\n }\n\n // Set defaults\n options = Object.assign({\n maxRedirects: exports.maxRedirects,\n maxBodyLength: exports.maxBodyLength,\n }, input, options);\n options.nativeProtocols = nativeProtocols;\n if (!isString(options.host) && !isString(options.hostname)) {\n options.hostname = \"::1\";\n }\n\n assert.equal(options.protocol, protocol, \"protocol mismatch\");\n debug(\"options\", options);\n return new RedirectableRequest(options, callback);\n }\n\n // Executes a GET request, following redirects\n function get(input, options, callback) {\n var wrappedRequest = wrappedProtocol.request(input, options, callback);\n wrappedRequest.end();\n return wrappedRequest;\n }\n\n // Expose the properties on the wrapped protocol\n Object.defineProperties(wrappedProtocol, {\n request: { value: request, configurable: true, enumerable: true, writable: true },\n get: { value: get, configurable: true, enumerable: true, writable: true },\n });\n });\n return exports;\n}\n\nfunction noop() { /* empty */ }\n\nfunction parseUrl(input) {\n var parsed;\n // istanbul ignore else\n if (useNativeURL) {\n parsed = new URL(input);\n }\n else {\n // Ensure the URL is valid and absolute\n parsed = validateUrl(url.parse(input));\n if (!isString(parsed.protocol)) {\n throw new InvalidUrlError({ input });\n }\n }\n return parsed;\n}\n\nfunction resolveUrl(relative, base) {\n // istanbul ignore next\n return useNativeURL ? new URL(relative, base) : parseUrl(url.resolve(base, relative));\n}\n\nfunction validateUrl(input) {\n if (/^\\[/.test(input.hostname) && !/^\\[[:0-9a-f]+\\]$/i.test(input.hostname)) {\n throw new InvalidUrlError({ input: input.href || input });\n }\n if (/^\\[/.test(input.host) && !/^\\[[:0-9a-f]+\\](:\\d+)?$/i.test(input.host)) {\n throw new InvalidUrlError({ input: input.href || input });\n }\n return input;\n}\n\nfunction spreadUrlObject(urlObject, target) {\n var spread = target || {};\n for (var key of preservedUrlFields) {\n spread[key] = urlObject[key];\n }\n\n // Fix IPv6 hostname\n if (spread.hostname.startsWith(\"[\")) {\n spread.hostname = spread.hostname.slice(1, -1);\n }\n // Ensure port is a number\n if (spread.port !== \"\") {\n spread.port = Number(spread.port);\n }\n // Concatenate path\n spread.path = spread.search ? spread.pathname + spread.search : spread.pathname;\n\n return spread;\n}\n\nfunction removeMatchingHeaders(regex, headers) {\n var lastValue;\n for (var header in headers) {\n if (regex.test(header)) {\n lastValue = headers[header];\n delete headers[header];\n }\n }\n return (lastValue === null || typeof lastValue === \"undefined\") ?\n undefined : String(lastValue).trim();\n}\n\nfunction createErrorType(code, message, baseClass) {\n // Create constructor\n function CustomError(properties) {\n // istanbul ignore else\n if (isFunction(Error.captureStackTrace)) {\n Error.captureStackTrace(this, this.constructor);\n }\n Object.assign(this, properties || {});\n this.code = code;\n this.message = this.cause ? message + \": \" + this.cause.message : message;\n }\n\n // Attach constructor and set default properties\n CustomError.prototype = new (baseClass || Error)();\n Object.defineProperties(CustomError.prototype, {\n constructor: {\n value: CustomError,\n enumerable: false,\n },\n name: {\n value: \"Error [\" + code + \"]\",\n enumerable: false,\n },\n });\n return CustomError;\n}\n\nfunction destroyRequest(request, error) {\n for (var event of events) {\n request.removeListener(event, eventHandlers[event]);\n }\n request.on(\"error\", noop);\n request.destroy(error);\n}\n\nfunction isSubdomain(subdomain, domain) {\n assert(isString(subdomain) && isString(domain));\n var dot = subdomain.length - domain.length - 1;\n return dot > 0 && subdomain[dot] === \".\" && subdomain.endsWith(domain);\n}\n\nfunction isString(value) {\n return typeof value === \"string\" || value instanceof String;\n}\n\nfunction isFunction(value) {\n return typeof value === \"function\";\n}\n\nfunction isBuffer(value) {\n return typeof value === \"object\" && (\"length\" in value);\n}\n\nfunction isURL(value) {\n return URL && value instanceof URL;\n}\n\n// Exports\nmodule.exports = wrap({ http: http, https: https });\nmodule.exports.wrap = wrap;\n","'use strict';\n\nif (typeof process === 'undefined' ||\n !process.version ||\n process.version.indexOf('v0.') === 0 ||\n process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {\n module.exports = { nextTick: nextTick };\n} else {\n module.exports = process\n}\n\nfunction nextTick(fn, arg1, arg2, arg3) {\n if (typeof fn !== 'function') {\n throw new TypeError('\"callback\" argument must be a function');\n }\n var len = arguments.length;\n var args, i;\n switch (len) {\n case 0:\n case 1:\n return process.nextTick(fn);\n case 2:\n return process.nextTick(function afterTickOne() {\n fn.call(null, arg1);\n });\n case 3:\n return process.nextTick(function afterTickTwo() {\n fn.call(null, arg1, arg2);\n });\n case 4:\n return process.nextTick(function afterTickThree() {\n fn.call(null, arg1, arg2, arg3);\n });\n default:\n args = new Array(len - 1);\n i = 0;\n while (i < args.length) {\n args[i++] = arguments[i];\n }\n return process.nextTick(function afterTick() {\n fn.apply(null, args);\n });\n }\n}\n\n","var toString = {}.toString;\n\nmodule.exports = Array.isArray || function (arr) {\n return toString.call(arr) == '[object Array]';\n};\n","module.exports = require('stream');\n","/* eslint-disable node/no-deprecated-api */\nvar buffer = require('buffer')\nvar Buffer = buffer.Buffer\n\n// alternative to using Object.keys for old browsers\nfunction copyProps (src, dst) {\n for (var key in src) {\n dst[key] = src[key]\n }\n}\nif (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {\n module.exports = buffer\n} else {\n // Copy properties from require('buffer')\n copyProps(buffer, exports)\n exports.Buffer = SafeBuffer\n}\n\nfunction SafeBuffer (arg, encodingOrOffset, length) {\n return Buffer(arg, encodingOrOffset, length)\n}\n\n// Copy static methods from Buffer\ncopyProps(Buffer, SafeBuffer)\n\nSafeBuffer.from = function (arg, encodingOrOffset, length) {\n if (typeof arg === 'number') {\n throw new TypeError('Argument must not be a number')\n }\n return Buffer(arg, encodingOrOffset, length)\n}\n\nSafeBuffer.alloc = function (size, fill, encoding) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n var buf = Buffer(size)\n if (fill !== undefined) {\n if (typeof encoding === 'string') {\n buf.fill(fill, encoding)\n } else {\n buf.fill(fill)\n }\n } else {\n buf.fill(0)\n }\n return buf\n}\n\nSafeBuffer.allocUnsafe = function (size) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n return Buffer(size)\n}\n\nSafeBuffer.allocUnsafeSlow = function (size) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n return buffer.SlowBuffer(size)\n}\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// NOTE: These type checking functions intentionally don't use `instanceof`\n// because it is fragile and can be easily faked with `Object.create()`.\n\nfunction isArray(arg) {\n if (Array.isArray) {\n return Array.isArray(arg);\n }\n return objectToString(arg) === '[object Array]';\n}\nexports.isArray = isArray;\n\nfunction isBoolean(arg) {\n return typeof arg === 'boolean';\n}\nexports.isBoolean = isBoolean;\n\nfunction isNull(arg) {\n return arg === null;\n}\nexports.isNull = isNull;\n\nfunction isNullOrUndefined(arg) {\n return arg == null;\n}\nexports.isNullOrUndefined = isNullOrUndefined;\n\nfunction isNumber(arg) {\n return typeof arg === 'number';\n}\nexports.isNumber = isNumber;\n\nfunction isString(arg) {\n return typeof arg === 'string';\n}\nexports.isString = isString;\n\nfunction isSymbol(arg) {\n return typeof arg === 'symbol';\n}\nexports.isSymbol = isSymbol;\n\nfunction isUndefined(arg) {\n return arg === void 0;\n}\nexports.isUndefined = isUndefined;\n\nfunction isRegExp(re) {\n return objectToString(re) === '[object RegExp]';\n}\nexports.isRegExp = isRegExp;\n\nfunction isObject(arg) {\n return typeof arg === 'object' && arg !== null;\n}\nexports.isObject = isObject;\n\nfunction isDate(d) {\n return objectToString(d) === '[object Date]';\n}\nexports.isDate = isDate;\n\nfunction isError(e) {\n return (objectToString(e) === '[object Error]' || e instanceof Error);\n}\nexports.isError = isError;\n\nfunction isFunction(arg) {\n return typeof arg === 'function';\n}\nexports.isFunction = isFunction;\n\nfunction isPrimitive(arg) {\n return arg === null ||\n typeof arg === 'boolean' ||\n typeof arg === 'number' ||\n typeof arg === 'string' ||\n typeof arg === 'symbol' || // ES6 symbol\n typeof arg === 'undefined';\n}\nexports.isPrimitive = isPrimitive;\n\nexports.isBuffer = require('buffer').Buffer.isBuffer;\n\nfunction objectToString(o) {\n return Object.prototype.toString.call(o);\n}\n","if (typeof Object.create === 'function') {\n // implementation from standard node.js 'util' module\n module.exports = function inherits(ctor, superCtor) {\n if (superCtor) {\n ctor.super_ = superCtor\n ctor.prototype = Object.create(superCtor.prototype, {\n constructor: {\n value: ctor,\n enumerable: false,\n writable: true,\n configurable: true\n }\n })\n }\n };\n} else {\n // old school shim for old browsers\n module.exports = function inherits(ctor, superCtor) {\n if (superCtor) {\n ctor.super_ = superCtor\n var TempCtor = function () {}\n TempCtor.prototype = superCtor.prototype\n ctor.prototype = new TempCtor()\n ctor.prototype.constructor = ctor\n }\n }\n}\n","try {\n var util = require('util');\n /* istanbul ignore next */\n if (typeof util.inherits !== 'function') throw '';\n module.exports = util.inherits;\n} catch (e) {\n /* istanbul ignore next */\n module.exports = require('./inherits_browser.js');\n}\n","'use strict';\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nvar Buffer = require('safe-buffer').Buffer;\nvar util = require('util');\n\nfunction copyBuffer(src, target, offset) {\n src.copy(target, offset);\n}\n\nmodule.exports = function () {\n function BufferList() {\n _classCallCheck(this, BufferList);\n\n this.head = null;\n this.tail = null;\n this.length = 0;\n }\n\n BufferList.prototype.push = function push(v) {\n var entry = { data: v, next: null };\n if (this.length > 0) this.tail.next = entry;else this.head = entry;\n this.tail = entry;\n ++this.length;\n };\n\n BufferList.prototype.unshift = function unshift(v) {\n var entry = { data: v, next: this.head };\n if (this.length === 0) this.tail = entry;\n this.head = entry;\n ++this.length;\n };\n\n BufferList.prototype.shift = function shift() {\n if (this.length === 0) return;\n var ret = this.head.data;\n if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;\n --this.length;\n return ret;\n };\n\n BufferList.prototype.clear = function clear() {\n this.head = this.tail = null;\n this.length = 0;\n };\n\n BufferList.prototype.join = function join(s) {\n if (this.length === 0) return '';\n var p = this.head;\n var ret = '' + p.data;\n while (p = p.next) {\n ret += s + p.data;\n }return ret;\n };\n\n BufferList.prototype.concat = function concat(n) {\n if (this.length === 0) return Buffer.alloc(0);\n var ret = Buffer.allocUnsafe(n >>> 0);\n var p = this.head;\n var i = 0;\n while (p) {\n copyBuffer(p.data, ret, i);\n i += p.data.length;\n p = p.next;\n }\n return ret;\n };\n\n return BufferList;\n}();\n\nif (util && util.inspect && util.inspect.custom) {\n module.exports.prototype[util.inspect.custom] = function () {\n var obj = util.inspect({ length: this.length });\n return this.constructor.name + ' ' + obj;\n };\n}","'use strict';\n\n/*<replacement>*/\n\nvar pna = require('process-nextick-args');\n/*</replacement>*/\n\n// undocumented cb() API, needed for core, not for public API\nfunction destroy(err, cb) {\n var _this = this;\n\n var readableDestroyed = this._readableState && this._readableState.destroyed;\n var writableDestroyed = this._writableState && this._writableState.destroyed;\n\n if (readableDestroyed || writableDestroyed) {\n if (cb) {\n cb(err);\n } else if (err) {\n if (!this._writableState) {\n pna.nextTick(emitErrorNT, this, err);\n } else if (!this._writableState.errorEmitted) {\n this._writableState.errorEmitted = true;\n pna.nextTick(emitErrorNT, this, err);\n }\n }\n\n return this;\n }\n\n // we set destroyed to true before firing error callbacks in order\n // to make it re-entrance safe in case destroy() is called within callbacks\n\n if (this._readableState) {\n this._readableState.destroyed = true;\n }\n\n // if this is a duplex stream mark the writable part as destroyed as well\n if (this._writableState) {\n this._writableState.destroyed = true;\n }\n\n this._destroy(err || null, function (err) {\n if (!cb && err) {\n if (!_this._writableState) {\n pna.nextTick(emitErrorNT, _this, err);\n } else if (!_this._writableState.errorEmitted) {\n _this._writableState.errorEmitted = true;\n pna.nextTick(emitErrorNT, _this, err);\n }\n } else if (cb) {\n cb(err);\n }\n });\n\n return this;\n}\n\nfunction undestroy() {\n if (this._readableState) {\n this._readableState.destroyed = false;\n this._readableState.reading = false;\n this._readableState.ended = false;\n this._readableState.endEmitted = false;\n }\n\n if (this._writableState) {\n this._writableState.destroyed = false;\n this._writableState.ended = false;\n this._writableState.ending = false;\n this._writableState.finalCalled = false;\n this._writableState.prefinished = false;\n this._writableState.finished = false;\n this._writableState.errorEmitted = false;\n }\n}\n\nfunction emitErrorNT(self, err) {\n self.emit('error', err);\n}\n\nmodule.exports = {\n destroy: destroy,\n undestroy: undestroy\n};","\n/**\n * For Node.js, simply re-export the core `util.deprecate` function.\n */\n\nmodule.exports = require('util').deprecate;\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// A bit simpler than readable streams.\n// Implement an async ._write(chunk, encoding, cb), and it'll handle all\n// the drain event emission and buffering.\n\n'use strict';\n\n/*<replacement>*/\n\nvar pna = require('process-nextick-args');\n/*</replacement>*/\n\nmodule.exports = Writable;\n\n/* <replacement> */\nfunction WriteReq(chunk, encoding, cb) {\n this.chunk = chunk;\n this.encoding = encoding;\n this.callback = cb;\n this.next = null;\n}\n\n// It seems a linked list but it is not\n// there will be only 2 of these for each stream\nfunction CorkedRequest(state) {\n var _this = this;\n\n this.next = null;\n this.entry = null;\n this.finish = function () {\n onCorkedFinish(_this, state);\n };\n}\n/* </replacement> */\n\n/*<replacement>*/\nvar asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick;\n/*</replacement>*/\n\n/*<replacement>*/\nvar Duplex;\n/*</replacement>*/\n\nWritable.WritableState = WritableState;\n\n/*<replacement>*/\nvar util = Object.create(require('core-util-is'));\nutil.inherits = require('inherits');\n/*</replacement>*/\n\n/*<replacement>*/\nvar internalUtil = {\n deprecate: require('util-deprecate')\n};\n/*</replacement>*/\n\n/*<replacement>*/\nvar Stream = require('./internal/streams/stream');\n/*</replacement>*/\n\n/*<replacement>*/\n\nvar Buffer = require('safe-buffer').Buffer;\nvar OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {};\nfunction _uint8ArrayToBuffer(chunk) {\n return Buffer.from(chunk);\n}\nfunction _isUint8Array(obj) {\n return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;\n}\n\n/*</replacement>*/\n\nvar destroyImpl = require('./internal/streams/destroy');\n\nutil.inherits(Writable, Stream);\n\nfunction nop() {}\n\nfunction WritableState(options, stream) {\n Duplex = Duplex || require('./_stream_duplex');\n\n options = options || {};\n\n // Duplex streams are both readable and writable, but share\n // the same options object.\n // However, some cases require setting options to different\n // values for the readable and the writable sides of the duplex stream.\n // These options can be provided separately as readableXXX and writableXXX.\n var isDuplex = stream instanceof Duplex;\n\n // object stream flag to indicate whether or not this stream\n // contains buffers or objects.\n this.objectMode = !!options.objectMode;\n\n if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode;\n\n // the point at which write() starts returning false\n // Note: 0 is a valid value, means that we always return false if\n // the entire buffer is not flushed immediately on write()\n var hwm = options.highWaterMark;\n var writableHwm = options.writableHighWaterMark;\n var defaultHwm = this.objectMode ? 16 : 16 * 1024;\n\n if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm;\n\n // cast to ints.\n this.highWaterMark = Math.floor(this.highWaterMark);\n\n // if _final has been called\n this.finalCalled = false;\n\n // drain event flag.\n this.needDrain = false;\n // at the start of calling end()\n this.ending = false;\n // when end() has been called, and returned\n this.ended = false;\n // when 'finish' is emitted\n this.finished = false;\n\n // has it been destroyed\n this.destroyed = false;\n\n // should we decode strings into buffers before passing to _write?\n // this is here so that some node-core streams can optimize string\n // handling at a lower level.\n var noDecode = options.decodeStrings === false;\n this.decodeStrings = !noDecode;\n\n // Crypto is kind of old and crusty. Historically, its default string\n // encoding is 'binary' so we have to make this configurable.\n // Everything else in the universe uses 'utf8', though.\n this.defaultEncoding = options.defaultEncoding || 'utf8';\n\n // not an actual buffer we keep track of, but a measurement\n // of how much we're waiting to get pushed to some underlying\n // socket or file.\n this.length = 0;\n\n // a flag to see when we're in the middle of a write.\n this.writing = false;\n\n // when true all writes will be buffered until .uncork() call\n this.corked = 0;\n\n // a flag to be able to tell if the onwrite cb is called immediately,\n // or on a later tick. We set this to true at first, because any\n // actions that shouldn't happen until \"later\" should generally also\n // not happen before the first write call.\n this.sync = true;\n\n // a flag to know if we're processing previously buffered items, which\n // may call the _write() callback in the same tick, so that we don't\n // end up in an overlapped onwrite situation.\n this.bufferProcessing = false;\n\n // the callback that's passed to _write(chunk,cb)\n this.onwrite = function (er) {\n onwrite(stream, er);\n };\n\n // the callback that the user supplies to write(chunk,encoding,cb)\n this.writecb = null;\n\n // the amount that is being written when _write is called.\n this.writelen = 0;\n\n this.bufferedRequest = null;\n this.lastBufferedRequest = null;\n\n // number of pending user-supplied write callbacks\n // this must be 0 before 'finish' can be emitted\n this.pendingcb = 0;\n\n // emit prefinish if the only thing we're waiting for is _write cbs\n // This is relevant for synchronous Transform streams\n this.prefinished = false;\n\n // True if the error was already emitted and should not be thrown again\n this.errorEmitted = false;\n\n // count buffered requests\n this.bufferedRequestCount = 0;\n\n // allocate the first CorkedRequest, there is always\n // one allocated and free to use, and we maintain at most two\n this.corkedRequestsFree = new CorkedRequest(this);\n}\n\nWritableState.prototype.getBuffer = function getBuffer() {\n var current = this.bufferedRequest;\n var out = [];\n while (current) {\n out.push(current);\n current = current.next;\n }\n return out;\n};\n\n(function () {\n try {\n Object.defineProperty(WritableState.prototype, 'buffer', {\n get: internalUtil.deprecate(function () {\n return this.getBuffer();\n }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')\n });\n } catch (_) {}\n})();\n\n// Test _writableState for inheritance to account for Duplex streams,\n// whose prototype chain only points to Readable.\nvar realHasInstance;\nif (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {\n realHasInstance = Function.prototype[Symbol.hasInstance];\n Object.defineProperty(Writable, Symbol.hasInstance, {\n value: function (object) {\n if (realHasInstance.call(this, object)) return true;\n if (this !== Writable) return false;\n\n return object && object._writableState instanceof WritableState;\n }\n });\n} else {\n realHasInstance = function (object) {\n return object instanceof this;\n };\n}\n\nfunction Writable(options) {\n Duplex = Duplex || require('./_stream_duplex');\n\n // Writable ctor is applied to Duplexes, too.\n // `realHasInstance` is necessary because using plain `instanceof`\n // would return false, as no `_writableState` property is attached.\n\n // Trying to use the custom `instanceof` for Writable here will also break the\n // Node.js LazyTransform implementation, which has a non-trivial getter for\n // `_writableState` that would lead to infinite recursion.\n if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {\n return new Writable(options);\n }\n\n this._writableState = new WritableState(options, this);\n\n // legacy.\n this.writable = true;\n\n if (options) {\n if (typeof options.write === 'function') this._write = options.write;\n\n if (typeof options.writev === 'function') this._writev = options.writev;\n\n if (typeof options.destroy === 'function') this._destroy = options.destroy;\n\n if (typeof options.final === 'function') this._final = options.final;\n }\n\n Stream.call(this);\n}\n\n// Otherwise people can pipe Writable streams, which is just wrong.\nWritable.prototype.pipe = function () {\n this.emit('error', new Error('Cannot pipe, not readable'));\n};\n\nfunction writeAfterEnd(stream, cb) {\n var er = new Error('write after end');\n // TODO: defer error events consistently everywhere, not just the cb\n stream.emit('error', er);\n pna.nextTick(cb, er);\n}\n\n// Checks that a user-supplied chunk is valid, especially for the particular\n// mode the stream is in. Currently this means that `null` is never accepted\n// and undefined/non-string values are only allowed in object mode.\nfunction validChunk(stream, state, chunk, cb) {\n var valid = true;\n var er = false;\n\n if (chunk === null) {\n er = new TypeError('May not write null values to stream');\n } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {\n er = new TypeError('Invalid non-string/buffer chunk');\n }\n if (er) {\n stream.emit('error', er);\n pna.nextTick(cb, er);\n valid = false;\n }\n return valid;\n}\n\nWritable.prototype.write = function (chunk, encoding, cb) {\n var state = this._writableState;\n var ret = false;\n var isBuf = !state.objectMode && _isUint8Array(chunk);\n\n if (isBuf && !Buffer.isBuffer(chunk)) {\n chunk = _uint8ArrayToBuffer(chunk);\n }\n\n if (typeof encoding === 'function') {\n cb = encoding;\n encoding = null;\n }\n\n if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;\n\n if (typeof cb !== 'function') cb = nop;\n\n if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {\n state.pendingcb++;\n ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);\n }\n\n return ret;\n};\n\nWritable.prototype.cork = function () {\n var state = this._writableState;\n\n state.corked++;\n};\n\nWritable.prototype.uncork = function () {\n var state = this._writableState;\n\n if (state.corked) {\n state.corked--;\n\n if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);\n }\n};\n\nWritable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {\n // node::ParseEncoding() requires lower case.\n if (typeof encoding === 'string') encoding = encoding.toLowerCase();\n if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding);\n this._writableState.defaultEncoding = encoding;\n return this;\n};\n\nfunction decodeChunk(state, chunk, encoding) {\n if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {\n chunk = Buffer.from(chunk, encoding);\n }\n return chunk;\n}\n\nObject.defineProperty(Writable.prototype, 'writableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function () {\n return this._writableState.highWaterMark;\n }\n});\n\n// if we're already writing something, then just put this\n// in the queue, and wait our turn. Otherwise, call _write\n// If we return false, then we need a drain event, so set that flag.\nfunction writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {\n if (!isBuf) {\n var newChunk = decodeChunk(state, chunk, encoding);\n if (chunk !== newChunk) {\n isBuf = true;\n encoding = 'buffer';\n chunk = newChunk;\n }\n }\n var len = state.objectMode ? 1 : chunk.length;\n\n state.length += len;\n\n var ret = state.length < state.highWaterMark;\n // we must ensure that previous needDrain will not be reset to false.\n if (!ret) state.needDrain = true;\n\n if (state.writing || state.corked) {\n var last = state.lastBufferedRequest;\n state.lastBufferedRequest = {\n chunk: chunk,\n encoding: encoding,\n isBuf: isBuf,\n callback: cb,\n next: null\n };\n if (last) {\n last.next = state.lastBufferedRequest;\n } else {\n state.bufferedRequest = state.lastBufferedRequest;\n }\n state.bufferedRequestCount += 1;\n } else {\n doWrite(stream, state, false, len, chunk, encoding, cb);\n }\n\n return ret;\n}\n\nfunction doWrite(stream, state, writev, len, chunk, encoding, cb) {\n state.writelen = len;\n state.writecb = cb;\n state.writing = true;\n state.sync = true;\n if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);\n state.sync = false;\n}\n\nfunction onwriteError(stream, state, sync, er, cb) {\n --state.pendingcb;\n\n if (sync) {\n // defer the callback if we are being called synchronously\n // to avoid piling up things on the stack\n pna.nextTick(cb, er);\n // this can emit finish, and it will always happen\n // after error\n pna.nextTick(finishMaybe, stream, state);\n stream._writableState.errorEmitted = true;\n stream.emit('error', er);\n } else {\n // the caller expect this to happen before if\n // it is async\n cb(er);\n stream._writableState.errorEmitted = true;\n stream.emit('error', er);\n // this can emit finish, but finish must\n // always follow error\n finishMaybe(stream, state);\n }\n}\n\nfunction onwriteStateUpdate(state) {\n state.writing = false;\n state.writecb = null;\n state.length -= state.writelen;\n state.writelen = 0;\n}\n\nfunction onwrite(stream, er) {\n var state = stream._writableState;\n var sync = state.sync;\n var cb = state.writecb;\n\n onwriteStateUpdate(state);\n\n if (er) onwriteError(stream, state, sync, er, cb);else {\n // Check if we're actually ready to finish, but don't emit yet\n var finished = needFinish(state);\n\n if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {\n clearBuffer(stream, state);\n }\n\n if (sync) {\n /*<replacement>*/\n asyncWrite(afterWrite, stream, state, finished, cb);\n /*</replacement>*/\n } else {\n afterWrite(stream, state, finished, cb);\n }\n }\n}\n\nfunction afterWrite(stream, state, finished, cb) {\n if (!finished) onwriteDrain(stream, state);\n state.pendingcb--;\n cb();\n finishMaybe(stream, state);\n}\n\n// Must force callback to be called on nextTick, so that we don't\n// emit 'drain' before the write() consumer gets the 'false' return\n// value, and has a chance to attach a 'drain' listener.\nfunction onwriteDrain(stream, state) {\n if (state.length === 0 && state.needDrain) {\n state.needDrain = false;\n stream.emit('drain');\n }\n}\n\n// if there's something in the buffer waiting, then process it\nfunction clearBuffer(stream, state) {\n state.bufferProcessing = true;\n var entry = state.bufferedRequest;\n\n if (stream._writev && entry && entry.next) {\n // Fast case, write everything using _writev()\n var l = state.bufferedRequestCount;\n var buffer = new Array(l);\n var holder = state.corkedRequestsFree;\n holder.entry = entry;\n\n var count = 0;\n var allBuffers = true;\n while (entry) {\n buffer[count] = entry;\n if (!entry.isBuf) allBuffers = false;\n entry = entry.next;\n count += 1;\n }\n buffer.allBuffers = allBuffers;\n\n doWrite(stream, state, true, state.length, buffer, '', holder.finish);\n\n // doWrite is almost always async, defer these to save a bit of time\n // as the hot path ends with doWrite\n state.pendingcb++;\n state.lastBufferedRequest = null;\n if (holder.next) {\n state.corkedRequestsFree = holder.next;\n holder.next = null;\n } else {\n state.corkedRequestsFree = new CorkedRequest(state);\n }\n state.bufferedRequestCount = 0;\n } else {\n // Slow case, write chunks one-by-one\n while (entry) {\n var chunk = entry.chunk;\n var encoding = entry.encoding;\n var cb = entry.callback;\n var len = state.objectMode ? 1 : chunk.length;\n\n doWrite(stream, state, false, len, chunk, encoding, cb);\n entry = entry.next;\n state.bufferedRequestCount--;\n // if we didn't call the onwrite immediately, then\n // it means that we need to wait until it does.\n // also, that means that the chunk and cb are currently\n // being processed, so move the buffer counter past them.\n if (state.writing) {\n break;\n }\n }\n\n if (entry === null) state.lastBufferedRequest = null;\n }\n\n state.bufferedRequest = entry;\n state.bufferProcessing = false;\n}\n\nWritable.prototype._write = function (chunk, encoding, cb) {\n cb(new Error('_write() is not implemented'));\n};\n\nWritable.prototype._writev = null;\n\nWritable.prototype.end = function (chunk, encoding, cb) {\n var state = this._writableState;\n\n if (typeof chunk === 'function') {\n cb = chunk;\n chunk = null;\n encoding = null;\n } else if (typeof encoding === 'function') {\n cb = encoding;\n encoding = null;\n }\n\n if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);\n\n // .end() fully uncorks\n if (state.corked) {\n state.corked = 1;\n this.uncork();\n }\n\n // ignore unnecessary end() calls.\n if (!state.ending) endWritable(this, state, cb);\n};\n\nfunction needFinish(state) {\n return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;\n}\nfunction callFinal(stream, state) {\n stream._final(function (err) {\n state.pendingcb--;\n if (err) {\n stream.emit('error', err);\n }\n state.prefinished = true;\n stream.emit('prefinish');\n finishMaybe(stream, state);\n });\n}\nfunction prefinish(stream, state) {\n if (!state.prefinished && !state.finalCalled) {\n if (typeof stream._final === 'function') {\n state.pendingcb++;\n state.finalCalled = true;\n pna.nextTick(callFinal, stream, state);\n } else {\n state.prefinished = true;\n stream.emit('prefinish');\n }\n }\n}\n\nfunction finishMaybe(stream, state) {\n var need = needFinish(state);\n if (need) {\n prefinish(stream, state);\n if (state.pendingcb === 0) {\n state.finished = true;\n stream.emit('finish');\n }\n }\n return need;\n}\n\nfunction endWritable(stream, state, cb) {\n state.ending = true;\n finishMaybe(stream, state);\n if (cb) {\n if (state.finished) pna.nextTick(cb);else stream.once('finish', cb);\n }\n state.ended = true;\n stream.writable = false;\n}\n\nfunction onCorkedFinish(corkReq, state, err) {\n var entry = corkReq.entry;\n corkReq.entry = null;\n while (entry) {\n var cb = entry.callback;\n state.pendingcb--;\n cb(err);\n entry = entry.next;\n }\n\n // reuse the free corkReq.\n state.corkedRequestsFree.next = corkReq;\n}\n\nObject.defineProperty(Writable.prototype, 'destroyed', {\n get: function () {\n if (this._writableState === undefined) {\n return false;\n }\n return this._writableState.destroyed;\n },\n set: function (value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (!this._writableState) {\n return;\n }\n\n // backward compatibility, the user is explicitly\n // managing destroyed\n this._writableState.destroyed = value;\n }\n});\n\nWritable.prototype.destroy = destroyImpl.destroy;\nWritable.prototype._undestroy = destroyImpl.undestroy;\nWritable.prototype._destroy = function (err, cb) {\n this.end();\n cb(err);\n};","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// a duplex stream is just a stream that is both readable and writable.\n// Since JS doesn't have multiple prototypal inheritance, this class\n// prototypally inherits from Readable, and then parasitically from\n// Writable.\n\n'use strict';\n\n/*<replacement>*/\n\nvar pna = require('process-nextick-args');\n/*</replacement>*/\n\n/*<replacement>*/\nvar objectKeys = Object.keys || function (obj) {\n var keys = [];\n for (var key in obj) {\n keys.push(key);\n }return keys;\n};\n/*</replacement>*/\n\nmodule.exports = Duplex;\n\n/*<replacement>*/\nvar util = Object.create(require('core-util-is'));\nutil.inherits = require('inherits');\n/*</replacement>*/\n\nvar Readable = require('./_stream_readable');\nvar Writable = require('./_stream_writable');\n\nutil.inherits(Duplex, Readable);\n\n{\n // avoid scope creep, the keys array can then be collected\n var keys = objectKeys(Writable.prototype);\n for (var v = 0; v < keys.length; v++) {\n var method = keys[v];\n if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];\n }\n}\n\nfunction Duplex(options) {\n if (!(this instanceof Duplex)) return new Duplex(options);\n\n Readable.call(this, options);\n Writable.call(this, options);\n\n if (options && options.readable === false) this.readable = false;\n\n if (options && options.writable === false) this.writable = false;\n\n this.allowHalfOpen = true;\n if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;\n\n this.once('end', onend);\n}\n\nObject.defineProperty(Duplex.prototype, 'writableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function () {\n return this._writableState.highWaterMark;\n }\n});\n\n// the no-half-open enforcer\nfunction onend() {\n // if we allow half-open state, or if the writable side ended,\n // then we're ok.\n if (this.allowHalfOpen || this._writableState.ended) return;\n\n // no more data can be written.\n // But allow more writes to happen in this tick.\n pna.nextTick(onEndNT, this);\n}\n\nfunction onEndNT(self) {\n self.end();\n}\n\nObject.defineProperty(Duplex.prototype, 'destroyed', {\n get: function () {\n if (this._readableState === undefined || this._writableState === undefined) {\n return false;\n }\n return this._readableState.destroyed && this._writableState.destroyed;\n },\n set: function (value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (this._readableState === undefined || this._writableState === undefined) {\n return;\n }\n\n // backward compatibility, the user is explicitly\n // managing destroyed\n this._readableState.destroyed = value;\n this._writableState.destroyed = value;\n }\n});\n\nDuplex.prototype._destroy = function (err, cb) {\n this.push(null);\n this.end();\n\n pna.nextTick(cb, err);\n};","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\n/*<replacement>*/\n\nvar Buffer = require('safe-buffer').Buffer;\n/*</replacement>*/\n\nvar isEncoding = Buffer.isEncoding || function (encoding) {\n encoding = '' + encoding;\n switch (encoding && encoding.toLowerCase()) {\n case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw':\n return true;\n default:\n return false;\n }\n};\n\nfunction _normalizeEncoding(enc) {\n if (!enc) return 'utf8';\n var retried;\n while (true) {\n switch (enc) {\n case 'utf8':\n case 'utf-8':\n return 'utf8';\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return 'utf16le';\n case 'latin1':\n case 'binary':\n return 'latin1';\n case 'base64':\n case 'ascii':\n case 'hex':\n return enc;\n default:\n if (retried) return; // undefined\n enc = ('' + enc).toLowerCase();\n retried = true;\n }\n }\n};\n\n// Do not cache `Buffer.isEncoding` when checking encoding names as some\n// modules monkey-patch it to support additional encodings\nfunction normalizeEncoding(enc) {\n var nenc = _normalizeEncoding(enc);\n if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);\n return nenc || enc;\n}\n\n// StringDecoder provides an interface for efficiently splitting a series of\n// buffers into a series of JS strings without breaking apart multi-byte\n// characters.\nexports.StringDecoder = StringDecoder;\nfunction StringDecoder(encoding) {\n this.encoding = normalizeEncoding(encoding);\n var nb;\n switch (this.encoding) {\n case 'utf16le':\n this.text = utf16Text;\n this.end = utf16End;\n nb = 4;\n break;\n case 'utf8':\n this.fillLast = utf8FillLast;\n nb = 4;\n break;\n case 'base64':\n this.text = base64Text;\n this.end = base64End;\n nb = 3;\n break;\n default:\n this.write = simpleWrite;\n this.end = simpleEnd;\n return;\n }\n this.lastNeed = 0;\n this.lastTotal = 0;\n this.lastChar = Buffer.allocUnsafe(nb);\n}\n\nStringDecoder.prototype.write = function (buf) {\n if (buf.length === 0) return '';\n var r;\n var i;\n if (this.lastNeed) {\n r = this.fillLast(buf);\n if (r === undefined) return '';\n i = this.lastNeed;\n this.lastNeed = 0;\n } else {\n i = 0;\n }\n if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);\n return r || '';\n};\n\nStringDecoder.prototype.end = utf8End;\n\n// Returns only complete characters in a Buffer\nStringDecoder.prototype.text = utf8Text;\n\n// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer\nStringDecoder.prototype.fillLast = function (buf) {\n if (this.lastNeed <= buf.length) {\n buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);\n return this.lastChar.toString(this.encoding, 0, this.lastTotal);\n }\n buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);\n this.lastNeed -= buf.length;\n};\n\n// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a\n// continuation byte. If an invalid byte is detected, -2 is returned.\nfunction utf8CheckByte(byte) {\n if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4;\n return byte >> 6 === 0x02 ? -1 : -2;\n}\n\n// Checks at most 3 bytes at the end of a Buffer in order to detect an\n// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)\n// needed to complete the UTF-8 character (if applicable) are returned.\nfunction utf8CheckIncomplete(self, buf, i) {\n var j = buf.length - 1;\n if (j < i) return 0;\n var nb = utf8CheckByte(buf[j]);\n if (nb >= 0) {\n if (nb > 0) self.lastNeed = nb - 1;\n return nb;\n }\n if (--j < i || nb === -2) return 0;\n nb = utf8CheckByte(buf[j]);\n if (nb >= 0) {\n if (nb > 0) self.lastNeed = nb - 2;\n return nb;\n }\n if (--j < i || nb === -2) return 0;\n nb = utf8CheckByte(buf[j]);\n if (nb >= 0) {\n if (nb > 0) {\n if (nb === 2) nb = 0;else self.lastNeed = nb - 3;\n }\n return nb;\n }\n return 0;\n}\n\n// Validates as many continuation bytes for a multi-byte UTF-8 character as\n// needed or are available. If we see a non-continuation byte where we expect\n// one, we \"replace\" the validated continuation bytes we've seen so far with\n// a single UTF-8 replacement character ('\\ufffd'), to match v8's UTF-8 decoding\n// behavior. The continuation byte check is included three times in the case\n// where all of the continuation bytes for a character exist in the same buffer.\n// It is also done this way as a slight performance increase instead of using a\n// loop.\nfunction utf8CheckExtraBytes(self, buf, p) {\n if ((buf[0] & 0xC0) !== 0x80) {\n self.lastNeed = 0;\n return '\\ufffd';\n }\n if (self.lastNeed > 1 && buf.length > 1) {\n if ((buf[1] & 0xC0) !== 0x80) {\n self.lastNeed = 1;\n return '\\ufffd';\n }\n if (self.lastNeed > 2 && buf.length > 2) {\n if ((buf[2] & 0xC0) !== 0x80) {\n self.lastNeed = 2;\n return '\\ufffd';\n }\n }\n }\n}\n\n// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.\nfunction utf8FillLast(buf) {\n var p = this.lastTotal - this.lastNeed;\n var r = utf8CheckExtraBytes(this, buf, p);\n if (r !== undefined) return r;\n if (this.lastNeed <= buf.length) {\n buf.copy(this.lastChar, p, 0, this.lastNeed);\n return this.lastChar.toString(this.encoding, 0, this.lastTotal);\n }\n buf.copy(this.lastChar, p, 0, buf.length);\n this.lastNeed -= buf.length;\n}\n\n// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a\n// partial character, the character's bytes are buffered until the required\n// number of bytes are available.\nfunction utf8Text(buf, i) {\n var total = utf8CheckIncomplete(this, buf, i);\n if (!this.lastNeed) return buf.toString('utf8', i);\n this.lastTotal = total;\n var end = buf.length - (total - this.lastNeed);\n buf.copy(this.lastChar, 0, end);\n return buf.toString('utf8', i, end);\n}\n\n// For UTF-8, a replacement character is added when ending on a partial\n// character.\nfunction utf8End(buf) {\n var r = buf && buf.length ? this.write(buf) : '';\n if (this.lastNeed) return r + '\\ufffd';\n return r;\n}\n\n// UTF-16LE typically needs two bytes per character, but even if we have an even\n// number of bytes available, we need to check if we end on a leading/high\n// surrogate. In that case, we need to wait for the next two bytes in order to\n// decode the last character properly.\nfunction utf16Text(buf, i) {\n if ((buf.length - i) % 2 === 0) {\n var r = buf.toString('utf16le', i);\n if (r) {\n var c = r.charCodeAt(r.length - 1);\n if (c >= 0xD800 && c <= 0xDBFF) {\n this.lastNeed = 2;\n this.lastTotal = 4;\n this.lastChar[0] = buf[buf.length - 2];\n this.lastChar[1] = buf[buf.length - 1];\n return r.slice(0, -1);\n }\n }\n return r;\n }\n this.lastNeed = 1;\n this.lastTotal = 2;\n this.lastChar[0] = buf[buf.length - 1];\n return buf.toString('utf16le', i, buf.length - 1);\n}\n\n// For UTF-16LE we do not explicitly append special replacement characters if we\n// end on a partial character, we simply let v8 handle that.\nfunction utf16End(buf) {\n var r = buf && buf.length ? this.write(buf) : '';\n if (this.lastNeed) {\n var end = this.lastTotal - this.lastNeed;\n return r + this.lastChar.toString('utf16le', 0, end);\n }\n return r;\n}\n\nfunction base64Text(buf, i) {\n var n = (buf.length - i) % 3;\n if (n === 0) return buf.toString('base64', i);\n this.lastNeed = 3 - n;\n this.lastTotal = 3;\n if (n === 1) {\n this.lastChar[0] = buf[buf.length - 1];\n } else {\n this.lastChar[0] = buf[buf.length - 2];\n this.lastChar[1] = buf[buf.length - 1];\n }\n return buf.toString('base64', i, buf.length - n);\n}\n\nfunction base64End(buf) {\n var r = buf && buf.length ? this.write(buf) : '';\n if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);\n return r;\n}\n\n// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)\nfunction simpleWrite(buf) {\n return buf.toString(this.encoding);\n}\n\nfunction simpleEnd(buf) {\n return buf && buf.length ? this.write(buf) : '';\n}","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\n/*<replacement>*/\n\nvar pna = require('process-nextick-args');\n/*</replacement>*/\n\nmodule.exports = Readable;\n\n/*<replacement>*/\nvar isArray = require('isarray');\n/*</replacement>*/\n\n/*<replacement>*/\nvar Duplex;\n/*</replacement>*/\n\nReadable.ReadableState = ReadableState;\n\n/*<replacement>*/\nvar EE = require('events').EventEmitter;\n\nvar EElistenerCount = function (emitter, type) {\n return emitter.listeners(type).length;\n};\n/*</replacement>*/\n\n/*<replacement>*/\nvar Stream = require('./internal/streams/stream');\n/*</replacement>*/\n\n/*<replacement>*/\n\nvar Buffer = require('safe-buffer').Buffer;\nvar OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {};\nfunction _uint8ArrayToBuffer(chunk) {\n return Buffer.from(chunk);\n}\nfunction _isUint8Array(obj) {\n return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;\n}\n\n/*</replacement>*/\n\n/*<replacement>*/\nvar util = Object.create(require('core-util-is'));\nutil.inherits = require('inherits');\n/*</replacement>*/\n\n/*<replacement>*/\nvar debugUtil = require('util');\nvar debug = void 0;\nif (debugUtil && debugUtil.debuglog) {\n debug = debugUtil.debuglog('stream');\n} else {\n debug = function () {};\n}\n/*</replacement>*/\n\nvar BufferList = require('./internal/streams/BufferList');\nvar destroyImpl = require('./internal/streams/destroy');\nvar StringDecoder;\n\nutil.inherits(Readable, Stream);\n\nvar kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];\n\nfunction prependListener(emitter, event, fn) {\n // Sadly this is not cacheable as some libraries bundle their own\n // event emitter implementation with them.\n if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn);\n\n // This is a hack to make sure that our error handler is attached before any\n // userland ones. NEVER DO THIS. This is here only because this code needs\n // to continue to work with older versions of Node.js that do not include\n // the prependListener() method. The goal is to eventually remove this hack.\n if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];\n}\n\nfunction ReadableState(options, stream) {\n Duplex = Duplex || require('./_stream_duplex');\n\n options = options || {};\n\n // Duplex streams are both readable and writable, but share\n // the same options object.\n // However, some cases require setting options to different\n // values for the readable and the writable sides of the duplex stream.\n // These options can be provided separately as readableXXX and writableXXX.\n var isDuplex = stream instanceof Duplex;\n\n // object stream flag. Used to make read(n) ignore n and to\n // make all the buffer merging and length checks go away\n this.objectMode = !!options.objectMode;\n\n if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode;\n\n // the point at which it stops calling _read() to fill the buffer\n // Note: 0 is a valid value, means \"don't call _read preemptively ever\"\n var hwm = options.highWaterMark;\n var readableHwm = options.readableHighWaterMark;\n var defaultHwm = this.objectMode ? 16 : 16 * 1024;\n\n if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm;\n\n // cast to ints.\n this.highWaterMark = Math.floor(this.highWaterMark);\n\n // A linked list is used to store data chunks instead of an array because the\n // linked list can remove elements from the beginning faster than\n // array.shift()\n this.buffer = new BufferList();\n this.length = 0;\n this.pipes = null;\n this.pipesCount = 0;\n this.flowing = null;\n this.ended = false;\n this.endEmitted = false;\n this.reading = false;\n\n // a flag to be able to tell if the event 'readable'/'data' is emitted\n // immediately, or on a later tick. We set this to true at first, because\n // any actions that shouldn't happen until \"later\" should generally also\n // not happen before the first read call.\n this.sync = true;\n\n // whenever we return null, then we set a flag to say\n // that we're awaiting a 'readable' event emission.\n this.needReadable = false;\n this.emittedReadable = false;\n this.readableListening = false;\n this.resumeScheduled = false;\n\n // has it been destroyed\n this.destroyed = false;\n\n // Crypto is kind of old and crusty. Historically, its default string\n // encoding is 'binary' so we have to make this configurable.\n // Everything else in the universe uses 'utf8', though.\n this.defaultEncoding = options.defaultEncoding || 'utf8';\n\n // the number of writers that are awaiting a drain event in .pipe()s\n this.awaitDrain = 0;\n\n // if true, a maybeReadMore has been scheduled\n this.readingMore = false;\n\n this.decoder = null;\n this.encoding = null;\n if (options.encoding) {\n if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;\n this.decoder = new StringDecoder(options.encoding);\n this.encoding = options.encoding;\n }\n}\n\nfunction Readable(options) {\n Duplex = Duplex || require('./_stream_duplex');\n\n if (!(this instanceof Readable)) return new Readable(options);\n\n this._readableState = new ReadableState(options, this);\n\n // legacy\n this.readable = true;\n\n if (options) {\n if (typeof options.read === 'function') this._read = options.read;\n\n if (typeof options.destroy === 'function') this._destroy = options.destroy;\n }\n\n Stream.call(this);\n}\n\nObject.defineProperty(Readable.prototype, 'destroyed', {\n get: function () {\n if (this._readableState === undefined) {\n return false;\n }\n return this._readableState.destroyed;\n },\n set: function (value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (!this._readableState) {\n return;\n }\n\n // backward compatibility, the user is explicitly\n // managing destroyed\n this._readableState.destroyed = value;\n }\n});\n\nReadable.prototype.destroy = destroyImpl.destroy;\nReadable.prototype._undestroy = destroyImpl.undestroy;\nReadable.prototype._destroy = function (err, cb) {\n this.push(null);\n cb(err);\n};\n\n// Manually shove something into the read() buffer.\n// This returns true if the highWaterMark has not been hit yet,\n// similar to how Writable.write() returns true if you should\n// write() some more.\nReadable.prototype.push = function (chunk, encoding) {\n var state = this._readableState;\n var skipChunkCheck;\n\n if (!state.objectMode) {\n if (typeof chunk === 'string') {\n encoding = encoding || state.defaultEncoding;\n if (encoding !== state.encoding) {\n chunk = Buffer.from(chunk, encoding);\n encoding = '';\n }\n skipChunkCheck = true;\n }\n } else {\n skipChunkCheck = true;\n }\n\n return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);\n};\n\n// Unshift should *always* be something directly out of read()\nReadable.prototype.unshift = function (chunk) {\n return readableAddChunk(this, chunk, null, true, false);\n};\n\nfunction readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {\n var state = stream._readableState;\n if (chunk === null) {\n state.reading = false;\n onEofChunk(stream, state);\n } else {\n var er;\n if (!skipChunkCheck) er = chunkInvalid(state, chunk);\n if (er) {\n stream.emit('error', er);\n } else if (state.objectMode || chunk && chunk.length > 0) {\n if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {\n chunk = _uint8ArrayToBuffer(chunk);\n }\n\n if (addToFront) {\n if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true);\n } else if (state.ended) {\n stream.emit('error', new Error('stream.push() after EOF'));\n } else {\n state.reading = false;\n if (state.decoder && !encoding) {\n chunk = state.decoder.write(chunk);\n if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);\n } else {\n addChunk(stream, state, chunk, false);\n }\n }\n } else if (!addToFront) {\n state.reading = false;\n }\n }\n\n return needMoreData(state);\n}\n\nfunction addChunk(stream, state, chunk, addToFront) {\n if (state.flowing && state.length === 0 && !state.sync) {\n stream.emit('data', chunk);\n stream.read(0);\n } else {\n // update the buffer info.\n state.length += state.objectMode ? 1 : chunk.length;\n if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);\n\n if (state.needReadable) emitReadable(stream);\n }\n maybeReadMore(stream, state);\n}\n\nfunction chunkInvalid(state, chunk) {\n var er;\n if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {\n er = new TypeError('Invalid non-string/buffer chunk');\n }\n return er;\n}\n\n// if it's past the high water mark, we can push in some more.\n// Also, if we have no data yet, we can stand some\n// more bytes. This is to work around cases where hwm=0,\n// such as the repl. Also, if the push() triggered a\n// readable event, and the user called read(largeNumber) such that\n// needReadable was set, then we ought to push more, so that another\n// 'readable' event will be triggered.\nfunction needMoreData(state) {\n return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);\n}\n\nReadable.prototype.isPaused = function () {\n return this._readableState.flowing === false;\n};\n\n// backwards compatibility.\nReadable.prototype.setEncoding = function (enc) {\n if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;\n this._readableState.decoder = new StringDecoder(enc);\n this._readableState.encoding = enc;\n return this;\n};\n\n// Don't raise the hwm > 8MB\nvar MAX_HWM = 0x800000;\nfunction computeNewHighWaterMark(n) {\n if (n >= MAX_HWM) {\n n = MAX_HWM;\n } else {\n // Get the next highest power of 2 to prevent increasing hwm excessively in\n // tiny amounts\n n--;\n n |= n >>> 1;\n n |= n >>> 2;\n n |= n >>> 4;\n n |= n >>> 8;\n n |= n >>> 16;\n n++;\n }\n return n;\n}\n\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction howMuchToRead(n, state) {\n if (n <= 0 || state.length === 0 && state.ended) return 0;\n if (state.objectMode) return 1;\n if (n !== n) {\n // Only flow one buffer at a time\n if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;\n }\n // If we're asking for more than the current hwm, then raise the hwm.\n if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);\n if (n <= state.length) return n;\n // Don't have enough\n if (!state.ended) {\n state.needReadable = true;\n return 0;\n }\n return state.length;\n}\n\n// you can override either this method, or the async _read(n) below.\nReadable.prototype.read = function (n) {\n debug('read', n);\n n = parseInt(n, 10);\n var state = this._readableState;\n var nOrig = n;\n\n if (n !== 0) state.emittedReadable = false;\n\n // if we're doing read(0) to trigger a readable event, but we\n // already have a bunch of data in the buffer, then just trigger\n // the 'readable' event and move on.\n if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {\n debug('read: emitReadable', state.length, state.ended);\n if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);\n return null;\n }\n\n n = howMuchToRead(n, state);\n\n // if we've ended, and we're now clear, then finish it up.\n if (n === 0 && state.ended) {\n if (state.length === 0) endReadable(this);\n return null;\n }\n\n // All the actual chunk generation logic needs to be\n // *below* the call to _read. The reason is that in certain\n // synthetic stream cases, such as passthrough streams, _read\n // may be a completely synchronous operation which may change\n // the state of the read buffer, providing enough data when\n // before there was *not* enough.\n //\n // So, the steps are:\n // 1. Figure out what the state of things will be after we do\n // a read from the buffer.\n //\n // 2. If that resulting state will trigger a _read, then call _read.\n // Note that this may be asynchronous, or synchronous. Yes, it is\n // deeply ugly to write APIs this way, but that still doesn't mean\n // that the Readable class should behave improperly, as streams are\n // designed to be sync/async agnostic.\n // Take note if the _read call is sync or async (ie, if the read call\n // has returned yet), so that we know whether or not it's safe to emit\n // 'readable' etc.\n //\n // 3. Actually pull the requested chunks out of the buffer and return.\n\n // if we need a readable event, then we need to do some reading.\n var doRead = state.needReadable;\n debug('need readable', doRead);\n\n // if we currently have less than the highWaterMark, then also read some\n if (state.length === 0 || state.length - n < state.highWaterMark) {\n doRead = true;\n debug('length less than watermark', doRead);\n }\n\n // however, if we've ended, then there's no point, and if we're already\n // reading, then it's unnecessary.\n if (state.ended || state.reading) {\n doRead = false;\n debug('reading or ended', doRead);\n } else if (doRead) {\n debug('do read');\n state.reading = true;\n state.sync = true;\n // if the length is currently zero, then we *need* a readable event.\n if (state.length === 0) state.needReadable = true;\n // call internal read method\n this._read(state.highWaterMark);\n state.sync = false;\n // If _read pushed data synchronously, then `reading` will be false,\n // and we need to re-evaluate how much data we can return to the user.\n if (!state.reading) n = howMuchToRead(nOrig, state);\n }\n\n var ret;\n if (n > 0) ret = fromList(n, state);else ret = null;\n\n if (ret === null) {\n state.needReadable = true;\n n = 0;\n } else {\n state.length -= n;\n }\n\n if (state.length === 0) {\n // If we have nothing in the buffer, then we want to know\n // as soon as we *do* get something into the buffer.\n if (!state.ended) state.needReadable = true;\n\n // If we tried to read() past the EOF, then emit end on the next tick.\n if (nOrig !== n && state.ended) endReadable(this);\n }\n\n if (ret !== null) this.emit('data', ret);\n\n return ret;\n};\n\nfunction onEofChunk(stream, state) {\n if (state.ended) return;\n if (state.decoder) {\n var chunk = state.decoder.end();\n if (chunk && chunk.length) {\n state.buffer.push(chunk);\n state.length += state.objectMode ? 1 : chunk.length;\n }\n }\n state.ended = true;\n\n // emit 'readable' now to make sure it gets picked up.\n emitReadable(stream);\n}\n\n// Don't emit readable right away in sync mode, because this can trigger\n// another read() call => stack overflow. This way, it might trigger\n// a nextTick recursion warning, but that's not so bad.\nfunction emitReadable(stream) {\n var state = stream._readableState;\n state.needReadable = false;\n if (!state.emittedReadable) {\n debug('emitReadable', state.flowing);\n state.emittedReadable = true;\n if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream);\n }\n}\n\nfunction emitReadable_(stream) {\n debug('emit readable');\n stream.emit('readable');\n flow(stream);\n}\n\n// at this point, the user has presumably seen the 'readable' event,\n// and called read() to consume some data. that may have triggered\n// in turn another _read(n) call, in which case reading = true if\n// it's in progress.\n// However, if we're not ended, or reading, and the length < hwm,\n// then go ahead and try to read some more preemptively.\nfunction maybeReadMore(stream, state) {\n if (!state.readingMore) {\n state.readingMore = true;\n pna.nextTick(maybeReadMore_, stream, state);\n }\n}\n\nfunction maybeReadMore_(stream, state) {\n var len = state.length;\n while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {\n debug('maybeReadMore read 0');\n stream.read(0);\n if (len === state.length)\n // didn't get any data, stop spinning.\n break;else len = state.length;\n }\n state.readingMore = false;\n}\n\n// abstract method. to be overridden in specific implementation classes.\n// call cb(er, data) where data is <= n in length.\n// for virtual (non-string, non-buffer) streams, \"length\" is somewhat\n// arbitrary, and perhaps not very meaningful.\nReadable.prototype._read = function (n) {\n this.emit('error', new Error('_read() is not implemented'));\n};\n\nReadable.prototype.pipe = function (dest, pipeOpts) {\n var src = this;\n var state = this._readableState;\n\n switch (state.pipesCount) {\n case 0:\n state.pipes = dest;\n break;\n case 1:\n state.pipes = [state.pipes, dest];\n break;\n default:\n state.pipes.push(dest);\n break;\n }\n state.pipesCount += 1;\n debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);\n\n var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;\n\n var endFn = doEnd ? onend : unpipe;\n if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn);\n\n dest.on('unpipe', onunpipe);\n function onunpipe(readable, unpipeInfo) {\n debug('onunpipe');\n if (readable === src) {\n if (unpipeInfo && unpipeInfo.hasUnpiped === false) {\n unpipeInfo.hasUnpiped = true;\n cleanup();\n }\n }\n }\n\n function onend() {\n debug('onend');\n dest.end();\n }\n\n // when the dest drains, it reduces the awaitDrain counter\n // on the source. This would be more elegant with a .once()\n // handler in flow(), but adding and removing repeatedly is\n // too slow.\n var ondrain = pipeOnDrain(src);\n dest.on('drain', ondrain);\n\n var cleanedUp = false;\n function cleanup() {\n debug('cleanup');\n // cleanup event handlers once the pipe is broken\n dest.removeListener('close', onclose);\n dest.removeListener('finish', onfinish);\n dest.removeListener('drain', ondrain);\n dest.removeListener('error', onerror);\n dest.removeListener('unpipe', onunpipe);\n src.removeListener('end', onend);\n src.removeListener('end', unpipe);\n src.removeListener('data', ondata);\n\n cleanedUp = true;\n\n // if the reader is waiting for a drain event from this\n // specific writer, then it would cause it to never start\n // flowing again.\n // So, if this is awaiting a drain, then we just call it now.\n // If we don't know, then assume that we are waiting for one.\n if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();\n }\n\n // If the user pushes more data while we're writing to dest then we'll end up\n // in ondata again. However, we only want to increase awaitDrain once because\n // dest will only emit one 'drain' event for the multiple writes.\n // => Introduce a guard on increasing awaitDrain.\n var increasedAwaitDrain = false;\n src.on('data', ondata);\n function ondata(chunk) {\n debug('ondata');\n increasedAwaitDrain = false;\n var ret = dest.write(chunk);\n if (false === ret && !increasedAwaitDrain) {\n // If the user unpiped during `dest.write()`, it is possible\n // to get stuck in a permanently paused state if that write\n // also returned false.\n // => Check whether `dest` is still a piping destination.\n if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {\n debug('false write response, pause', state.awaitDrain);\n state.awaitDrain++;\n increasedAwaitDrain = true;\n }\n src.pause();\n }\n }\n\n // if the dest has an error, then stop piping into it.\n // however, don't suppress the throwing behavior for this.\n function onerror(er) {\n debug('onerror', er);\n unpipe();\n dest.removeListener('error', onerror);\n if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);\n }\n\n // Make sure our error handler is attached before userland ones.\n prependListener(dest, 'error', onerror);\n\n // Both close and finish should trigger unpipe, but only once.\n function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }\n dest.once('close', onclose);\n function onfinish() {\n debug('onfinish');\n dest.removeListener('close', onclose);\n unpipe();\n }\n dest.once('finish', onfinish);\n\n function unpipe() {\n debug('unpipe');\n src.unpipe(dest);\n }\n\n // tell the dest that it's being piped to\n dest.emit('pipe', src);\n\n // start the flow if it hasn't been started already.\n if (!state.flowing) {\n debug('pipe resume');\n src.resume();\n }\n\n return dest;\n};\n\nfunction pipeOnDrain(src) {\n return function () {\n var state = src._readableState;\n debug('pipeOnDrain', state.awaitDrain);\n if (state.awaitDrain) state.awaitDrain--;\n if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {\n state.flowing = true;\n flow(src);\n }\n };\n}\n\nReadable.prototype.unpipe = function (dest) {\n var state = this._readableState;\n var unpipeInfo = { hasUnpiped: false };\n\n // if we're not piping anywhere, then do nothing.\n if (state.pipesCount === 0) return this;\n\n // just one destination. most common case.\n if (state.pipesCount === 1) {\n // passed in one, but it's not the right one.\n if (dest && dest !== state.pipes) return this;\n\n if (!dest) dest = state.pipes;\n\n // got a match.\n state.pipes = null;\n state.pipesCount = 0;\n state.flowing = false;\n if (dest) dest.emit('unpipe', this, unpipeInfo);\n return this;\n }\n\n // slow case. multiple pipe destinations.\n\n if (!dest) {\n // remove all.\n var dests = state.pipes;\n var len = state.pipesCount;\n state.pipes = null;\n state.pipesCount = 0;\n state.flowing = false;\n\n for (var i = 0; i < len; i++) {\n dests[i].emit('unpipe', this, { hasUnpiped: false });\n }return this;\n }\n\n // try to find the right one.\n var index = indexOf(state.pipes, dest);\n if (index === -1) return this;\n\n state.pipes.splice(index, 1);\n state.pipesCount -= 1;\n if (state.pipesCount === 1) state.pipes = state.pipes[0];\n\n dest.emit('unpipe', this, unpipeInfo);\n\n return this;\n};\n\n// set up data events if they are asked for\n// Ensure readable listeners eventually get something\nReadable.prototype.on = function (ev, fn) {\n var res = Stream.prototype.on.call(this, ev, fn);\n\n if (ev === 'data') {\n // Start flowing on next tick if stream isn't explicitly paused\n if (this._readableState.flowing !== false) this.resume();\n } else if (ev === 'readable') {\n var state = this._readableState;\n if (!state.endEmitted && !state.readableListening) {\n state.readableListening = state.needReadable = true;\n state.emittedReadable = false;\n if (!state.reading) {\n pna.nextTick(nReadingNextTick, this);\n } else if (state.length) {\n emitReadable(this);\n }\n }\n }\n\n return res;\n};\nReadable.prototype.addListener = Readable.prototype.on;\n\nfunction nReadingNextTick(self) {\n debug('readable nexttick read 0');\n self.read(0);\n}\n\n// pause() and resume() are remnants of the legacy readable stream API\n// If the user uses them, then switch into old mode.\nReadable.prototype.resume = function () {\n var state = this._readableState;\n if (!state.flowing) {\n debug('resume');\n state.flowing = true;\n resume(this, state);\n }\n return this;\n};\n\nfunction resume(stream, state) {\n if (!state.resumeScheduled) {\n state.resumeScheduled = true;\n pna.nextTick(resume_, stream, state);\n }\n}\n\nfunction resume_(stream, state) {\n if (!state.reading) {\n debug('resume read 0');\n stream.read(0);\n }\n\n state.resumeScheduled = false;\n state.awaitDrain = 0;\n stream.emit('resume');\n flow(stream);\n if (state.flowing && !state.reading) stream.read(0);\n}\n\nReadable.prototype.pause = function () {\n debug('call pause flowing=%j', this._readableState.flowing);\n if (false !== this._readableState.flowing) {\n debug('pause');\n this._readableState.flowing = false;\n this.emit('pause');\n }\n return this;\n};\n\nfunction flow(stream) {\n var state = stream._readableState;\n debug('flow', state.flowing);\n while (state.flowing && stream.read() !== null) {}\n}\n\n// wrap an old-style stream as the async data source.\n// This is *not* part of the readable stream interface.\n// It is an ugly unfortunate mess of history.\nReadable.prototype.wrap = function (stream) {\n var _this = this;\n\n var state = this._readableState;\n var paused = false;\n\n stream.on('end', function () {\n debug('wrapped end');\n if (state.decoder && !state.ended) {\n var chunk = state.decoder.end();\n if (chunk && chunk.length) _this.push(chunk);\n }\n\n _this.push(null);\n });\n\n stream.on('data', function (chunk) {\n debug('wrapped data');\n if (state.decoder) chunk = state.decoder.write(chunk);\n\n // don't skip over falsy values in objectMode\n if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;\n\n var ret = _this.push(chunk);\n if (!ret) {\n paused = true;\n stream.pause();\n }\n });\n\n // proxy all the other methods.\n // important when wrapping filters and duplexes.\n for (var i in stream) {\n if (this[i] === undefined && typeof stream[i] === 'function') {\n this[i] = function (method) {\n return function () {\n return stream[method].apply(stream, arguments);\n };\n }(i);\n }\n }\n\n // proxy certain important events.\n for (var n = 0; n < kProxyEvents.length; n++) {\n stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));\n }\n\n // when we try to consume some more bytes, simply unpause the\n // underlying stream.\n this._read = function (n) {\n debug('wrapped _read', n);\n if (paused) {\n paused = false;\n stream.resume();\n }\n };\n\n return this;\n};\n\nObject.defineProperty(Readable.prototype, 'readableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function () {\n return this._readableState.highWaterMark;\n }\n});\n\n// exposed for testing purposes only.\nReadable._fromList = fromList;\n\n// Pluck off n bytes from an array of buffers.\n// Length is the combined lengths of all the buffers in the list.\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction fromList(n, state) {\n // nothing buffered\n if (state.length === 0) return null;\n\n var ret;\n if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {\n // read it all, truncate the list\n if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length);\n state.buffer.clear();\n } else {\n // read part of list\n ret = fromListPartial(n, state.buffer, state.decoder);\n }\n\n return ret;\n}\n\n// Extracts only enough buffered data to satisfy the amount requested.\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction fromListPartial(n, list, hasStrings) {\n var ret;\n if (n < list.head.data.length) {\n // slice is the same for buffers and strings\n ret = list.head.data.slice(0, n);\n list.head.data = list.head.data.slice(n);\n } else if (n === list.head.data.length) {\n // first chunk is a perfect match\n ret = list.shift();\n } else {\n // result spans more than one buffer\n ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);\n }\n return ret;\n}\n\n// Copies a specified amount of characters from the list of buffered data\n// chunks.\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction copyFromBufferString(n, list) {\n var p = list.head;\n var c = 1;\n var ret = p.data;\n n -= ret.length;\n while (p = p.next) {\n var str = p.data;\n var nb = n > str.length ? str.length : n;\n if (nb === str.length) ret += str;else ret += str.slice(0, n);\n n -= nb;\n if (n === 0) {\n if (nb === str.length) {\n ++c;\n if (p.next) list.head = p.next;else list.head = list.tail = null;\n } else {\n list.head = p;\n p.data = str.slice(nb);\n }\n break;\n }\n ++c;\n }\n list.length -= c;\n return ret;\n}\n\n// Copies a specified amount of bytes from the list of buffered data chunks.\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction copyFromBuffer(n, list) {\n var ret = Buffer.allocUnsafe(n);\n var p = list.head;\n var c = 1;\n p.data.copy(ret);\n n -= p.data.length;\n while (p = p.next) {\n var buf = p.data;\n var nb = n > buf.length ? buf.length : n;\n buf.copy(ret, ret.length - n, 0, nb);\n n -= nb;\n if (n === 0) {\n if (nb === buf.length) {\n ++c;\n if (p.next) list.head = p.next;else list.head = list.tail = null;\n } else {\n list.head = p;\n p.data = buf.slice(nb);\n }\n break;\n }\n ++c;\n }\n list.length -= c;\n return ret;\n}\n\nfunction endReadable(stream) {\n var state = stream._readableState;\n\n // If we get here before consuming all the bytes, then that is a\n // bug in node. Should never happen.\n if (state.length > 0) throw new Error('\"endReadable()\" called on non-empty stream');\n\n if (!state.endEmitted) {\n state.ended = true;\n pna.nextTick(endReadableNT, state, stream);\n }\n}\n\nfunction endReadableNT(state, stream) {\n // Check that we didn't get one last unshift.\n if (!state.endEmitted && state.length === 0) {\n state.endEmitted = true;\n stream.readable = false;\n stream.emit('end');\n }\n}\n\nfunction indexOf(xs, x) {\n for (var i = 0, l = xs.length; i < l; i++) {\n if (xs[i] === x) return i;\n }\n return -1;\n}","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// a transform stream is a readable/writable stream where you do\n// something with the data. Sometimes it's called a \"filter\",\n// but that's not a great name for it, since that implies a thing where\n// some bits pass through, and others are simply ignored. (That would\n// be a valid example of a transform, of course.)\n//\n// While the output is causally related to the input, it's not a\n// necessarily symmetric or synchronous transformation. For example,\n// a zlib stream might take multiple plain-text writes(), and then\n// emit a single compressed chunk some time in the future.\n//\n// Here's how this works:\n//\n// The Transform stream has all the aspects of the readable and writable\n// stream classes. When you write(chunk), that calls _write(chunk,cb)\n// internally, and returns false if there's a lot of pending writes\n// buffered up. When you call read(), that calls _read(n) until\n// there's enough pending readable data buffered up.\n//\n// In a transform stream, the written data is placed in a buffer. When\n// _read(n) is called, it transforms the queued up data, calling the\n// buffered _write cb's as it consumes chunks. If consuming a single\n// written chunk would result in multiple output chunks, then the first\n// outputted bit calls the readcb, and subsequent chunks just go into\n// the read buffer, and will cause it to emit 'readable' if necessary.\n//\n// This way, back-pressure is actually determined by the reading side,\n// since _read has to be called to start processing a new chunk. However,\n// a pathological inflate type of transform can cause excessive buffering\n// here. For example, imagine a stream where every byte of input is\n// interpreted as an integer from 0-255, and then results in that many\n// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in\n// 1kb of data being output. In this case, you could write a very small\n// amount of input, and end up with a very large amount of output. In\n// such a pathological inflating mechanism, there'd be no way to tell\n// the system to stop doing the transform. A single 4MB write could\n// cause the system to run out of memory.\n//\n// However, even in such a pathological case, only a single written chunk\n// would be consumed, and then the rest would wait (un-transformed) until\n// the results of the previous transformed chunk were consumed.\n\n'use strict';\n\nmodule.exports = Transform;\n\nvar Duplex = require('./_stream_duplex');\n\n/*<replacement>*/\nvar util = Object.create(require('core-util-is'));\nutil.inherits = require('inherits');\n/*</replacement>*/\n\nutil.inherits(Transform, Duplex);\n\nfunction afterTransform(er, data) {\n var ts = this._transformState;\n ts.transforming = false;\n\n var cb = ts.writecb;\n\n if (!cb) {\n return this.emit('error', new Error('write callback called multiple times'));\n }\n\n ts.writechunk = null;\n ts.writecb = null;\n\n if (data != null) // single equals check for both `null` and `undefined`\n this.push(data);\n\n cb(er);\n\n var rs = this._readableState;\n rs.reading = false;\n if (rs.needReadable || rs.length < rs.highWaterMark) {\n this._read(rs.highWaterMark);\n }\n}\n\nfunction Transform(options) {\n if (!(this instanceof Transform)) return new Transform(options);\n\n Duplex.call(this, options);\n\n this._transformState = {\n afterTransform: afterTransform.bind(this),\n needTransform: false,\n transforming: false,\n writecb: null,\n writechunk: null,\n writeencoding: null\n };\n\n // start out asking for a readable event once data is transformed.\n this._readableState.needReadable = true;\n\n // we have implemented the _read method, and done the other things\n // that Readable wants before the first _read call, so unset the\n // sync guard flag.\n this._readableState.sync = false;\n\n if (options) {\n if (typeof options.transform === 'function') this._transform = options.transform;\n\n if (typeof options.flush === 'function') this._flush = options.flush;\n }\n\n // When the writable side finishes, then flush out anything remaining.\n this.on('prefinish', prefinish);\n}\n\nfunction prefinish() {\n var _this = this;\n\n if (typeof this._flush === 'function') {\n this._flush(function (er, data) {\n done(_this, er, data);\n });\n } else {\n done(this, null, null);\n }\n}\n\nTransform.prototype.push = function (chunk, encoding) {\n this._transformState.needTransform = false;\n return Duplex.prototype.push.call(this, chunk, encoding);\n};\n\n// This is the part where you do stuff!\n// override this function in implementation classes.\n// 'chunk' is an input chunk.\n//\n// Call `push(newChunk)` to pass along transformed output\n// to the readable side. You may call 'push' zero or more times.\n//\n// Call `cb(err)` when you are done with this chunk. If you pass\n// an error, then that'll put the hurt on the whole operation. If you\n// never call cb(), then you'll never get another chunk.\nTransform.prototype._transform = function (chunk, encoding, cb) {\n throw new Error('_transform() is not implemented');\n};\n\nTransform.prototype._write = function (chunk, encoding, cb) {\n var ts = this._transformState;\n ts.writecb = cb;\n ts.writechunk = chunk;\n ts.writeencoding = encoding;\n if (!ts.transforming) {\n var rs = this._readableState;\n if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);\n }\n};\n\n// Doesn't matter what the args are here.\n// _transform does all the work.\n// That we got here means that the readable side wants more data.\nTransform.prototype._read = function (n) {\n var ts = this._transformState;\n\n if (ts.writechunk !== null && ts.writecb && !ts.transforming) {\n ts.transforming = true;\n this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);\n } else {\n // mark that we need a transform, so that any data that comes in\n // will get processed, now that we've asked for it.\n ts.needTransform = true;\n }\n};\n\nTransform.prototype._destroy = function (err, cb) {\n var _this2 = this;\n\n Duplex.prototype._destroy.call(this, err, function (err2) {\n cb(err2);\n _this2.emit('close');\n });\n};\n\nfunction done(stream, er, data) {\n if (er) return stream.emit('error', er);\n\n if (data != null) // single equals check for both `null` and `undefined`\n stream.push(data);\n\n // if there's nothing in the write buffer, then that means\n // that nothing more will ever be provided\n if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0');\n\n if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming');\n\n return stream.push(null);\n}","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// a passthrough stream.\n// basically just the most minimal sort of Transform stream.\n// Every written chunk gets output as-is.\n\n'use strict';\n\nmodule.exports = PassThrough;\n\nvar Transform = require('./_stream_transform');\n\n/*<replacement>*/\nvar util = Object.create(require('core-util-is'));\nutil.inherits = require('inherits');\n/*</replacement>*/\n\nutil.inherits(PassThrough, Transform);\n\nfunction PassThrough(options) {\n if (!(this instanceof PassThrough)) return new PassThrough(options);\n\n Transform.call(this, options);\n}\n\nPassThrough.prototype._transform = function (chunk, encoding, cb) {\n cb(null, chunk);\n};","var Stream = require('stream');\nif (process.env.READABLE_STREAM === 'disable' && Stream) {\n module.exports = Stream;\n exports = module.exports = Stream.Readable;\n exports.Readable = Stream.Readable;\n exports.Writable = Stream.Writable;\n exports.Duplex = Stream.Duplex;\n exports.Transform = Stream.Transform;\n exports.PassThrough = Stream.PassThrough;\n exports.Stream = Stream;\n} else {\n exports = module.exports = require('./lib/_stream_readable.js');\n exports.Stream = Stream || exports;\n exports.Readable = exports;\n exports.Writable = require('./lib/_stream_writable.js');\n exports.Duplex = require('./lib/_stream_duplex.js');\n exports.Transform = require('./lib/_stream_transform.js');\n exports.PassThrough = require('./lib/_stream_passthrough.js');\n}\n","module.exports = extend\n\nvar hasOwnProperty = Object.prototype.hasOwnProperty;\n\nfunction extend() {\n var target = {}\n\n for (var i = 0; i < arguments.length; i++) {\n var source = arguments[i]\n\n for (var key in source) {\n if (hasOwnProperty.call(source, key)) {\n target[key] = source[key]\n }\n }\n }\n\n return target\n}\n","var Transform = require('readable-stream').Transform\n , inherits = require('util').inherits\n , xtend = require('xtend')\n\nfunction DestroyableTransform(opts) {\n Transform.call(this, opts)\n this._destroyed = false\n}\n\ninherits(DestroyableTransform, Transform)\n\nDestroyableTransform.prototype.destroy = function(err) {\n if (this._destroyed) return\n this._destroyed = true\n \n var self = this\n process.nextTick(function() {\n if (err)\n self.emit('error', err)\n self.emit('close')\n })\n}\n\n// a noop _transform function\nfunction noop (chunk, enc, callback) {\n callback(null, chunk)\n}\n\n\n// create a new export function, used by both the main export and\n// the .ctor export, contains common logic for dealing with arguments\nfunction through2 (construct) {\n return function (options, transform, flush) {\n if (typeof options == 'function') {\n flush = transform\n transform = options\n options = {}\n }\n\n if (typeof transform != 'function')\n transform = noop\n\n if (typeof flush != 'function')\n flush = null\n\n return construct(options, transform, flush)\n }\n}\n\n\n// main export, just make me a transform stream!\nmodule.exports = through2(function (options, transform, flush) {\n var t2 = new DestroyableTransform(options)\n\n t2._transform = transform\n\n if (flush)\n t2._flush = flush\n\n return t2\n})\n\n\n// make me a reusable prototype that I can `new`, or implicitly `new`\n// with a constructor call\nmodule.exports.ctor = through2(function (options, transform, flush) {\n function Through2 (override) {\n if (!(this instanceof Through2))\n return new Through2(override)\n\n this.options = xtend(options, override)\n\n DestroyableTransform.call(this, this.options)\n }\n\n inherits(Through2, DestroyableTransform)\n\n Through2.prototype._transform = transform\n\n if (flush)\n Through2.prototype._flush = flush\n\n return Through2\n})\n\n\nmodule.exports.obj = through2(function (options, transform, flush) {\n var t2 = new DestroyableTransform(xtend({ objectMode: true, highWaterMark: 16 }, options))\n\n t2._transform = transform\n\n if (flush)\n t2._flush = flush\n\n return t2\n})\n","var tick = 1\nvar maxTick = 65535\nvar resolution = 4\nvar inc = function () {\n tick = (tick + 1) & maxTick\n}\n\nvar timer = setInterval(inc, (1000 / resolution) | 0)\nif (timer.unref) timer.unref()\n\nmodule.exports = function (seconds) {\n var size = resolution * (seconds || 5)\n var buffer = [0]\n var pointer = 1\n var last = (tick - 1) & maxTick\n\n return function (delta) {\n var dist = (tick - last) & maxTick\n if (dist > size) dist = size\n last = tick\n\n while (dist--) {\n if (pointer === size) pointer = 0\n buffer[pointer] = buffer[pointer === 0 ? size - 1 : pointer - 1]\n pointer++\n }\n\n if (delta) buffer[pointer - 1] += delta\n\n var top = buffer[pointer - 1]\n var btm = buffer.length < size ? 0 : buffer[pointer === size ? 0 : pointer]\n\n return buffer.length < resolution ? top : (top - btm) * resolution / buffer.length\n }\n}\n","var through = require('through2');\nvar speedometer = require('speedometer');\n\nmodule.exports = function(options, onprogress) {\n\tif (typeof options === 'function') return module.exports(null, options);\n\toptions = options || {};\n\n\tvar length = options.length || 0;\n\tvar time = options.time || 0;\n\tvar drain = options.drain || false;\n\tvar transferred = options.transferred || 0;\n\tvar nextUpdate = Date.now()+time;\n\tvar delta = 0;\n\tvar speed = speedometer(options.speed || 5000);\n\tvar startTime = Date.now();\n\n\tvar update = {\n\t\tpercentage: 0,\n\t\ttransferred: transferred,\n\t\tlength: length,\n\t\tremaining: length,\n\t\teta: 0,\n\t\truntime: 0\n\t};\n\n\tvar emit = function(ended) {\n\t\tupdate.delta = delta;\n\t\tupdate.percentage = ended ? 100 : (length ? transferred/length*100 : 0);\n\t\tupdate.speed = speed(delta);\n\t\tupdate.eta = Math.round(update.remaining / update.speed);\n\t\tupdate.runtime = parseInt((Date.now() - startTime)/1000);\n\t\tnextUpdate = Date.now()+time;\n\n\t\tdelta = 0;\n\n\t\ttr.emit('progress', update);\n\t};\n\tvar write = function(chunk, enc, callback) {\n\t\tvar len = options.objectMode ? 1 : chunk.length;\n\t\ttransferred += len;\n\t\tdelta += len;\n\t\tupdate.transferred = transferred;\n\t\tupdate.remaining = length >= transferred ? length - transferred : 0;\n\n\t\tif (Date.now() >= nextUpdate) emit(false);\n\t\tcallback(null, chunk);\n\t};\n\tvar end = function(callback) {\n\t\temit(true);\n\t\tcallback();\n\t};\n\n\tvar tr = through(options.objectMode ? {objectMode:true, highWaterMark:16} : {}, write, end);\n\tvar onlength = function(newLength) {\n\t\tlength = newLength;\n\t\tupdate.length = length;\n\t\tupdate.remaining = length - update.transferred;\n\t\ttr.emit('length', length);\n\t};\n\t\n\t// Expose `onlength()` handler as `setLength()` to support custom use cases where length\n\t// is not known until after a few chunks have already been pumped, or is\n\t// calculated on the fly.\n\ttr.setLength = onlength;\n\t\n\ttr.on('pipe', function(stream) {\n\t\tif (typeof length === 'number') return;\n\t\t// Support http module\n\t\tif (stream.readable && !stream.writable && stream.headers) {\n\t\t\treturn onlength(parseInt(stream.headers['content-length'] || 0));\n\t\t}\n\n\t\t// Support streams with a length property\n\t\tif (typeof stream.length === 'number') {\n\t\t\treturn onlength(stream.length);\n\t\t}\n\n\t\t// Support request module\n\t\tstream.on('response', function(res) {\n\t\t\tif (!res || !res.headers) return;\n\t\t\tif (res.headers['content-encoding'] === 'gzip') return;\n\t\t\tif (res.headers['content-length']) {\n\t\t\t\treturn onlength(parseInt(res.headers['content-length']));\n\t\t\t}\n\t\t});\n\t});\n\n\tif (drain) tr.resume();\n\tif (onprogress) tr.on('progress', onprogress);\n\n\ttr.progress = function() {\n\t\tupdate.speed = speed(0);\n\t\tupdate.eta = Math.round(update.remaining / update.speed);\n\n\t\treturn update;\n\t};\n\treturn tr;\n};\n","/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */\n/* eslint-disable node/no-deprecated-api */\nvar buffer = require('buffer')\nvar Buffer = buffer.Buffer\n\n// alternative to using Object.keys for old browsers\nfunction copyProps (src, dst) {\n for (var key in src) {\n dst[key] = src[key]\n }\n}\nif (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {\n module.exports = buffer\n} else {\n // Copy properties from require('buffer')\n copyProps(buffer, exports)\n exports.Buffer = SafeBuffer\n}\n\nfunction SafeBuffer (arg, encodingOrOffset, length) {\n return Buffer(arg, encodingOrOffset, length)\n}\n\nSafeBuffer.prototype = Object.create(Buffer.prototype)\n\n// Copy static methods from Buffer\ncopyProps(Buffer, SafeBuffer)\n\nSafeBuffer.from = function (arg, encodingOrOffset, length) {\n if (typeof arg === 'number') {\n throw new TypeError('Argument must not be a number')\n }\n return Buffer(arg, encodingOrOffset, length)\n}\n\nSafeBuffer.alloc = function (size, fill, encoding) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n var buf = Buffer(size)\n if (fill !== undefined) {\n if (typeof encoding === 'string') {\n buf.fill(fill, encoding)\n } else {\n buf.fill(fill)\n }\n } else {\n buf.fill(0)\n }\n return buf\n}\n\nSafeBuffer.allocUnsafe = function (size) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n return Buffer(size)\n}\n\nSafeBuffer.allocUnsafeSlow = function (size) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n return buffer.SlowBuffer(size)\n}\n","'use strict'\n\nvar net = require('net')\n , tls = require('tls')\n , http = require('http')\n , https = require('https')\n , events = require('events')\n , assert = require('assert')\n , util = require('util')\n , Buffer = require('safe-buffer').Buffer\n ;\n\nexports.httpOverHttp = httpOverHttp\nexports.httpsOverHttp = httpsOverHttp\nexports.httpOverHttps = httpOverHttps\nexports.httpsOverHttps = httpsOverHttps\n\n\nfunction httpOverHttp(options) {\n var agent = new TunnelingAgent(options)\n agent.request = http.request\n return agent\n}\n\nfunction httpsOverHttp(options) {\n var agent = new TunnelingAgent(options)\n agent.request = http.request\n agent.createSocket = createSecureSocket\n agent.defaultPort = 443\n return agent\n}\n\nfunction httpOverHttps(options) {\n var agent = new TunnelingAgent(options)\n agent.request = https.request\n return agent\n}\n\nfunction httpsOverHttps(options) {\n var agent = new TunnelingAgent(options)\n agent.request = https.request\n agent.createSocket = createSecureSocket\n agent.defaultPort = 443\n return agent\n}\n\n\nfunction TunnelingAgent(options) {\n var self = this\n self.options = options || {}\n self.proxyOptions = self.options.proxy || {}\n self.maxSockets = self.options.maxSockets || http.Agent.defaultMaxSockets\n self.requests = []\n self.sockets = []\n\n self.on('free', function onFree(socket, host, port) {\n for (var i = 0, len = self.requests.length; i < len; ++i) {\n var pending = self.requests[i]\n if (pending.host === host && pending.port === port) {\n // Detect the request to connect same origin server,\n // reuse the connection.\n self.requests.splice(i, 1)\n pending.request.onSocket(socket)\n return\n }\n }\n socket.destroy()\n self.removeSocket(socket)\n })\n}\nutil.inherits(TunnelingAgent, events.EventEmitter)\n\nTunnelingAgent.prototype.addRequest = function addRequest(req, options) {\n var self = this\n\n // Legacy API: addRequest(req, host, port, path)\n if (typeof options === 'string') {\n options = {\n host: options,\n port: arguments[2],\n path: arguments[3]\n };\n }\n\n if (self.sockets.length >= this.maxSockets) {\n // We are over limit so we'll add it to the queue.\n self.requests.push({host: options.host, port: options.port, request: req})\n return\n }\n\n // If we are under maxSockets create a new one.\n self.createConnection({host: options.host, port: options.port, request: req})\n}\n\nTunnelingAgent.prototype.createConnection = function createConnection(pending) {\n var self = this\n\n self.createSocket(pending, function(socket) {\n socket.on('free', onFree)\n socket.on('close', onCloseOrRemove)\n socket.on('agentRemove', onCloseOrRemove)\n pending.request.onSocket(socket)\n\n function onFree() {\n self.emit('free', socket, pending.host, pending.port)\n }\n\n function onCloseOrRemove(err) {\n self.removeSocket(socket)\n socket.removeListener('free', onFree)\n socket.removeListener('close', onCloseOrRemove)\n socket.removeListener('agentRemove', onCloseOrRemove)\n }\n })\n}\n\nTunnelingAgent.prototype.createSocket = function createSocket(options, cb) {\n var self = this\n var placeholder = {}\n self.sockets.push(placeholder)\n\n var connectOptions = mergeOptions({}, self.proxyOptions,\n { method: 'CONNECT'\n , path: options.host + ':' + options.port\n , agent: false\n }\n )\n if (connectOptions.proxyAuth) {\n connectOptions.headers = connectOptions.headers || {}\n connectOptions.headers['Proxy-Authorization'] = 'Basic ' +\n Buffer.from(connectOptions.proxyAuth).toString('base64')\n }\n\n debug('making CONNECT request')\n var connectReq = self.request(connectOptions)\n connectReq.useChunkedEncodingByDefault = false // for v0.6\n connectReq.once('response', onResponse) // for v0.6\n connectReq.once('upgrade', onUpgrade) // for v0.6\n connectReq.once('connect', onConnect) // for v0.7 or later\n connectReq.once('error', onError)\n connectReq.end()\n\n function onResponse(res) {\n // Very hacky. This is necessary to avoid http-parser leaks.\n res.upgrade = true\n }\n\n function onUpgrade(res, socket, head) {\n // Hacky.\n process.nextTick(function() {\n onConnect(res, socket, head)\n })\n }\n\n function onConnect(res, socket, head) {\n connectReq.removeAllListeners()\n socket.removeAllListeners()\n\n if (res.statusCode === 200) {\n assert.equal(head.length, 0)\n debug('tunneling connection has established')\n self.sockets[self.sockets.indexOf(placeholder)] = socket\n cb(socket)\n } else {\n debug('tunneling socket could not be established, statusCode=%d', res.statusCode)\n var error = new Error('tunneling socket could not be established, ' + 'statusCode=' + res.statusCode)\n error.code = 'ECONNRESET'\n options.request.emit('error', error)\n self.removeSocket(placeholder)\n }\n }\n\n function onError(cause) {\n connectReq.removeAllListeners()\n\n debug('tunneling socket could not be established, cause=%s\\n', cause.message, cause.stack)\n var error = new Error('tunneling socket could not be established, ' + 'cause=' + cause.message)\n error.code = 'ECONNRESET'\n options.request.emit('error', error)\n self.removeSocket(placeholder)\n }\n}\n\nTunnelingAgent.prototype.removeSocket = function removeSocket(socket) {\n var pos = this.sockets.indexOf(socket)\n if (pos === -1) return\n\n this.sockets.splice(pos, 1)\n\n var pending = this.requests.shift()\n if (pending) {\n // If we have pending requests and a socket gets closed a new one\n // needs to be created to take over in the pool for the one that closed.\n this.createConnection(pending)\n }\n}\n\nfunction createSecureSocket(options, cb) {\n var self = this\n TunnelingAgent.prototype.createSocket.call(self, options, function(socket) {\n // 0 is dummy port for v0.6\n var secureSocket = tls.connect(0, mergeOptions({}, self.options,\n { servername: options.host\n , socket: socket\n }\n ))\n self.sockets[self.sockets.indexOf(socket)] = secureSocket\n cb(secureSocket)\n })\n}\n\n\nfunction mergeOptions(target) {\n for (var i = 1, len = arguments.length; i < len; ++i) {\n var overrides = arguments[i]\n if (typeof overrides === 'object') {\n var keys = Object.keys(overrides)\n for (var j = 0, keyLen = keys.length; j < keyLen; ++j) {\n var k = keys[j]\n if (overrides[k] !== undefined) {\n target[k] = overrides[k]\n }\n }\n }\n }\n return target\n}\n\n\nvar debug\nif (process.env.NODE_DEBUG && /\\btunnel\\b/.test(process.env.NODE_DEBUG)) {\n debug = function() {\n var args = Array.prototype.slice.call(arguments)\n if (typeof args[0] === 'string') {\n args[0] = 'TUNNEL: ' + args[0]\n } else {\n args.unshift('TUNNEL:')\n }\n console.error.apply(console, args)\n }\n} else {\n debug = function() {}\n}\nexports.debug = debug // for test\n","import t from\"decompress-response\";import e from\"follow-redirects\";import o from\"http\";import r from\"https\";import n from\"progress-stream\";import s from\"querystring\";import{Readable as c}from\"stream\";import a from\"url\";import*as p from\"tunnel-agent\";function i(t){return Object.keys(t||{}).reduce(((e,o)=>(e[o.toLowerCase()]=t[o],e)),{})}function u(t){return t.replace(/^\\.*/,\".\").toLowerCase()}function d(t){const e=t.trim().toLowerCase(),o=e.split(\":\",2);return{hostname:u(o[0]),port:o[1],hasPort:e.indexOf(\":\")>-1}}const h=[\"protocol\",\"slashes\",\"auth\",\"host\",\"port\",\"hostname\",\"hash\",\"search\",\"query\",\"pathname\",\"path\",\"href\"],l=[\"accept\",\"accept-charset\",\"accept-encoding\",\"accept-language\",\"accept-ranges\",\"cache-control\",\"content-encoding\",\"content-language\",\"content-location\",\"content-md5\",\"content-range\",\"content-type\",\"connection\",\"date\",\"expect\",\"max-forwards\",\"pragma\",\"referer\",\"te\",\"user-agent\",\"via\"],m=[\"proxy-authorization\"],f=t=>null!==t&&\"object\"==typeof t&&\"function\"==typeof t.pipe,y=\"node\";class b extends Error{request;code;constructor(t,e){super(t.message),this.request=e,this.code=t.code}}const g=(t,e,o,r)=>({body:r,url:e,method:o,headers:t.headers,statusCode:t.statusCode,statusMessage:t.statusMessage}),x=(x,w)=>{const{options:O}=x,T=Object.assign({},a.parse(O.url));if(\"function\"==typeof fetch&&O.fetch){const t=new AbortController,e=x.applyMiddleware(\"finalizeOptions\",{...T,method:O.method,headers:{...\"object\"==typeof O.fetch&&O.fetch.headers?i(O.fetch.headers):{},...i(O.headers)},maxRedirects:O.maxRedirects}),o={credentials:O.withCredentials?\"include\":\"omit\",...\"object\"==typeof O.fetch?O.fetch:{},method:e.method,headers:e.headers,body:O.body,signal:t.signal},r=x.applyMiddleware(\"interceptRequest\",void 0,{adapter:y,context:x});if(r){const t=setTimeout(w,0,null,r);return{abort:()=>clearTimeout(t)}}const n=fetch(O.url,o);return x.applyMiddleware(\"onRequest\",{options:O,adapter:y,request:n,context:x}),n.then((async t=>{const e=O.rawBody?t.body:await t.text(),o={};t.headers.forEach(((t,e)=>{o[e]=t})),w(null,{body:e,url:t.url,method:O.method,headers:o,statusCode:t.status,statusMessage:t.statusText})})).catch((t=>{\"AbortError\"!=t.name&&w(t)})),{abort:()=>t.abort()}}const v=f(O.body)?\"stream\":typeof O.body;if(\"undefined\"!==v&&\"stream\"!==v&&\"string\"!==v&&!Buffer.isBuffer(O.body))throw new Error(`Request body must be a string, buffer or stream, got ${v}`);const R={};O.bodySize?R[\"content-length\"]=O.bodySize:O.body&&\"stream\"!==v&&(R[\"content-length\"]=Buffer.byteLength(O.body));let j=!1;const q=(t,e)=>!j&&w(t,e);x.channels.abort.subscribe((()=>{j=!0}));let C=Object.assign({},T,{method:O.method,headers:Object.assign({},i(O.headers),R),maxRedirects:O.maxRedirects});const $=function(t){let e;return e=t.hasOwnProperty(\"proxy\")?t.proxy:function(t){const e=process.env.NO_PROXY||process.env.no_proxy||\"\";return\"*\"===e||\"\"!==e&&function(t,e){const o=t.port||(\"https:\"===t.protocol?\"443\":\"80\"),r=u(t.hostname);return e.split(\",\").map(d).some((t=>{const e=r.indexOf(t.hostname),n=e>-1&&e===r.length-t.hostname.length;return t.hasPort?o===t.port&&n:n}))}(t,e)?null:\"http:\"===t.protocol?process.env.HTTP_PROXY||process.env.http_proxy||null:\"https:\"===t.protocol&&(process.env.HTTPS_PROXY||process.env.https_proxy||process.env.HTTP_PROXY||process.env.http_proxy)||null}(a.parse(t.url)),\"string\"==typeof e?a.parse(e):e}(O),E=$&&function(t){return typeof t.tunnel<\"u\"?!!t.tunnel:\"https:\"===a.parse(t.url).protocol}(O),L=x.applyMiddleware(\"interceptRequest\",void 0,{adapter:y,context:x});if(L){const t=setImmediate(q,null,L);return{abort:()=>clearImmediate(t)}}if(0!==O.maxRedirects&&(C.maxRedirects=O.maxRedirects||5),$&&E?C=function(t={},e){const o=Object.assign({},t),r=l.concat(o.proxyHeaderWhiteList||[]).map((t=>t.toLowerCase())),n=m.concat(o.proxyHeaderExclusiveList||[]).map((t=>t.toLowerCase())),s=(c=o.headers,a=r,Object.keys(c).filter((t=>-1!==a.indexOf(t.toLowerCase()))).reduce(((t,e)=>(t[e]=c[e],t)),{}));var c,a;s.host=function(t){const e=t.port,o=t.protocol;let r=`${t.hostname}:`;return r+=e||(\"https:\"===o?\"443\":\"80\"),r}(o),o.headers=Object.keys(o.headers||{}).reduce(((t,e)=>(-1===n.indexOf(e.toLowerCase())&&(t[e]=o.headers[e]),t)),{});const i=function(t,e){const o=function(t){return h.reduce(((e,o)=>(e[o]=t[o],e)),{})}(t),r=function(t,e){return`${\"https:\"===t.protocol?\"https\":\"http\"}Over${\"https:\"===e.protocol?\"Https\":\"Http\"}`}(o,e);return p[r]}(o,e),u=function(t,e,o){return{proxy:{host:e.hostname,port:+e.port,proxyAuth:e.auth,headers:o},headers:t.headers,ca:t.ca,cert:t.cert,key:t.key,passphrase:t.passphrase,pfx:t.pfx,ciphers:t.ciphers,rejectUnauthorized:t.rejectUnauthorized,secureOptions:t.secureOptions,secureProtocol:t.secureProtocol}}(o,e,s);return o.agent=i(u),o}(C,$):$&&!E&&(C=function(t,e,o){const r=t.headers||{},n=Object.assign({},t,{headers:r});return r.host=r.host||function(t){const e=t.port||(\"https:\"===t.protocol?\"443\":\"80\");return`${t.hostname}:${e}`}(e),n.protocol=o.protocol||n.protocol,n.hostname=o.host.replace(/:\\d+/,\"\"),n.port=o.port,n.host=function(t){let e=t.host;return t.port&&(\"80\"===t.port&&\"http:\"===t.protocol||\"443\"===t.port&&\"https:\"===t.protocol)&&(e=t.hostname),e}(Object.assign({},e,o)),n.href=`${n.protocol}//${n.host}${n.path}`,n.path=a.format(e),n}(C,T,$)),!E&&$&&$.auth&&!C.headers[\"proxy-authorization\"]){const[t,e]=$.auth.username?[$.auth.username,$.auth.password]:$.auth.split(\":\").map((t=>s.unescape(t))),o=Buffer.from(`${t}:${e}`,\"utf8\").toString(\"base64\");C.headers[\"proxy-authorization\"]=`Basic ${o}`}const P=function(t,n,s){const c=\"https:\"===t.protocol,a=0===t.maxRedirects?{http:o,https:r}:{http:e.http,https:e.https};if(!n||s)return c?a.https:a.http;let p=443===n.port;return n.protocol&&(p=/^https:?/.test(n.protocol)),p?a.https:a.http}(C,$,E);\"function\"==typeof O.debug&&$&&O.debug(\"Proxying using %s\",C.agent?\"tunnel agent\":`${C.host}:${C.port}`);const z=\"HEAD\"!==C.method;let M;z&&!C.headers[\"accept-encoding\"]&&!1!==O.compress&&(C.headers[\"accept-encoding\"]=typeof Bun<\"u\"?\"gzip, deflate\":\"br, gzip, deflate\");const k=x.applyMiddleware(\"finalizeOptions\",C),S=P.request(k,(e=>{const o=z?t(e):e;M=o;const r=x.applyMiddleware(\"onHeaders\",o,{headers:e.headers,adapter:y,context:x}),n=\"responseUrl\"in e?e.responseUrl:O.url;O.stream?q(null,g(o,n,C.method,r)):function(t,e){const o=[];t.on(\"data\",(function(t){o.push(t)})),t.once(\"end\",(function(){e&&e(null,Buffer.concat(o)),e=null})),t.once(\"error\",(function(t){e&&e(t),e=null}))}(r,((t,e)=>{if(t)return q(t);const r=O.rawBody?e:e.toString(),s=g(o,n,C.method,r);return q(null,s)}))}));function B(t){M&&M.destroy(t),S.destroy(t)}S.once(\"socket\",(t=>{t.once(\"error\",B),S.once(\"response\",(e=>{e.once(\"end\",(()=>{t.removeListener(\"error\",B)}))}))})),S.once(\"error\",(t=>{M||q(new b(t,S))})),O.timeout&&function(t,e){if(t.timeoutTimer)return t;const o=isNaN(e)?e:{socket:e,connect:e},r=t.getHeader(\"host\"),n=r?\" to \"+r:\"\";function s(){t.timeoutTimer&&(clearTimeout(t.timeoutTimer),t.timeoutTimer=null)}function c(e){if(s(),void 0!==o.socket){const r=()=>{const t=new Error(\"Socket timed out on request\"+n);t.code=\"ESOCKETTIMEDOUT\",e.destroy(t)};e.setTimeout(o.socket,r),t.once(\"response\",(t=>{t.once(\"end\",(()=>{e.removeListener(\"timeout\",r)}))}))}}void 0!==o.connect&&(t.timeoutTimer=setTimeout((function(){const e=new Error(\"Connection timed out on request\"+n);e.code=\"ETIMEDOUT\",t.destroy(e)}),o.connect)),t.on(\"socket\",(function(t){t.connecting?t.once(\"connect\",(()=>c(t))):c(t)})),t.on(\"error\",s)}(S,O.timeout);const{bodyStream:H,progress:_}=function(t){if(!t.body)return{};const e=f(t.body),o=t.bodySize||(e?null:Buffer.byteLength(t.body));if(!o)return e?{bodyStream:t.body}:{};const r=n({time:16,length:o});return{bodyStream:(e?t.body:c.from(t.body)).pipe(r),progress:r}}(O);return x.applyMiddleware(\"onRequest\",{options:O,adapter:y,request:S,context:x,progress:_}),H?H.pipe(S):S.end(O.body),{abort:()=>S.abort()}};export{b as N,y as a,x as h};//# sourceMappingURL=node-request.js.map\n","import{c as e}from\"./_chunks-es/createRequester.js\";import{h as s}from\"./_chunks-es/node-request.js\";import{a as r}from\"./_chunks-es/node-request.js\";const o=(r=[],o=s)=>e(r,o),t=\"node\";export{r as adapter,t as environment,o as getIt};//# sourceMappingURL=index.js.map\n","'use strict';\n\nconst denyList = new Set([\n\t'ENOTFOUND',\n\t'ENETUNREACH',\n\n\t// SSL errors from https://github.com/nodejs/node/blob/fc8e3e2cdc521978351de257030db0076d79e0ab/src/crypto/crypto_common.cc#L301-L328\n\t'UNABLE_TO_GET_ISSUER_CERT',\n\t'UNABLE_TO_GET_CRL',\n\t'UNABLE_TO_DECRYPT_CERT_SIGNATURE',\n\t'UNABLE_TO_DECRYPT_CRL_SIGNATURE',\n\t'UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY',\n\t'CERT_SIGNATURE_FAILURE',\n\t'CRL_SIGNATURE_FAILURE',\n\t'CERT_NOT_YET_VALID',\n\t'CERT_HAS_EXPIRED',\n\t'CRL_NOT_YET_VALID',\n\t'CRL_HAS_EXPIRED',\n\t'ERROR_IN_CERT_NOT_BEFORE_FIELD',\n\t'ERROR_IN_CERT_NOT_AFTER_FIELD',\n\t'ERROR_IN_CRL_LAST_UPDATE_FIELD',\n\t'ERROR_IN_CRL_NEXT_UPDATE_FIELD',\n\t'OUT_OF_MEM',\n\t'DEPTH_ZERO_SELF_SIGNED_CERT',\n\t'SELF_SIGNED_CERT_IN_CHAIN',\n\t'UNABLE_TO_GET_ISSUER_CERT_LOCALLY',\n\t'UNABLE_TO_VERIFY_LEAF_SIGNATURE',\n\t'CERT_CHAIN_TOO_LONG',\n\t'CERT_REVOKED',\n\t'INVALID_CA',\n\t'PATH_LENGTH_EXCEEDED',\n\t'INVALID_PURPOSE',\n\t'CERT_UNTRUSTED',\n\t'CERT_REJECTED',\n\t'HOSTNAME_MISMATCH'\n]);\n\n// TODO: Use `error?.code` when targeting Node.js 14\nmodule.exports = error => !denyList.has(error && error.code);\n","import{Agent as e}from\"http\";import{Agent as t}from\"https\";import{g as s}from\"./_chunks-es/_commonjsHelpers.js\";import r from\"tty\";import n from\"util\";import{p as o,v as i}from\"./_chunks-es/defaultOptionsValidator.js\";import c from\"progress-stream\";import a from\"is-retry-allowed\";import{N as u}from\"./_chunks-es/node-request.js\";const p=/^https:/i;function l(s){const r=new e(s),n=new t(s),o={http:r,https:n};return{finalizeOptions:e=>{if(e.agent)return e;if(e.maxRedirects>0)return{...e,agents:o};const t=p.test(e.href||e.protocol);return{...e,agent:t?n:r}}}}const d=/^\\//,f=/\\/$/;function m(e){const t=e.replace(f,\"\");return{processOptions:e=>{if(/^https?:\\/\\//i.test(e.url))return e;const s=[t,e.url.replace(d,\"\")].join(\"/\");return Object.assign({},e,{url:s})}}}var h,C,g,b,y,w={exports:{}},O={exports:{}};function F(){return b?g:(b=1,g=function(e){function t(e){let r,n,o,i=null;function c(...e){if(!c.enabled)return;const s=c,n=Number(/* @__PURE__ */new Date),o=n-(r||n);s.diff=o,s.prev=r,s.curr=n,r=n,e[0]=t.coerce(e[0]),\"string\"!=typeof e[0]&&e.unshift(\"%O\");let i=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((r,n)=>{if(\"%%\"===r)return\"%\";i++;const o=t.formatters[n];if(\"function\"==typeof o){const t=e[i];r=o.call(s,t),e.splice(i,1),i--}return r})),t.formatArgs.call(s,e),(s.log||t.log).apply(s,e)}return c.namespace=e,c.useColors=t.useColors(),c.color=t.selectColor(e),c.extend=s,c.destroy=t.destroy,Object.defineProperty(c,\"enabled\",{enumerable:!0,configurable:!1,get:()=>null!==i?i:(n!==t.namespaces&&(n=t.namespaces,o=t.enabled(e)),o),set:e=>{i=e}}),\"function\"==typeof t.init&&t.init(c),c}function s(e,s){const r=t(this.namespace+(typeof s>\"u\"?\":\":s)+e);return r.log=this.log,r}function r(e,t){let s=0,r=0,n=-1,o=0;for(;s<e.length;)if(r<t.length&&(t[r]===e[s]||\"*\"===t[r]))\"*\"===t[r]?(n=r,o=s,r++):(s++,r++);else{if(-1===n)return!1;r=n+1,o++,s=o}for(;r<t.length&&\"*\"===t[r];)r++;return r===t.length}return t.debug=t,t.default=t,t.coerce=function(e){return e instanceof Error?e.stack||e.message:e},t.disable=function(){const e=[...t.names,...t.skips.map((e=>\"-\"+e))].join(\",\");return t.enable(\"\"),e},t.enable=function(e){t.save(e),t.namespaces=e,t.names=[],t.skips=[];const s=(\"string\"==typeof e?e:\"\").trim().replace(\" \",\",\").split(\",\").filter(Boolean);for(const e of s)\"-\"===e[0]?t.skips.push(e.slice(1)):t.names.push(e)},t.enabled=function(e){for(const s of t.skips)if(r(e,s))return!1;for(const s of t.names)if(r(e,s))return!0;return!1},t.humanize=function(){if(C)return h;C=1;var e=1e3,t=60*e,s=60*t,r=24*s,n=7*r;function o(e,t,s,r){var n=t>=1.5*s;return Math.round(e/s)+\" \"+r+(n?\"s\":\"\")}return h=function(i,c){c=c||{};var a,u,p=typeof i;if(\"string\"===p&&i.length>0)return function(o){if(!((o=String(o)).length>100)){var i=/^(-?(?:\\d+)?\\.?\\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(o);if(i){var c=parseFloat(i[1]);switch((i[2]||\"ms\").toLowerCase()){case\"years\":case\"year\":case\"yrs\":case\"yr\":case\"y\":return 315576e5*c;case\"weeks\":case\"week\":case\"w\":return c*n;case\"days\":case\"day\":case\"d\":return c*r;case\"hours\":case\"hour\":case\"hrs\":case\"hr\":case\"h\":return c*s;case\"minutes\":case\"minute\":case\"mins\":case\"min\":case\"m\":return c*t;case\"seconds\":case\"second\":case\"secs\":case\"sec\":case\"s\":return c*e;case\"milliseconds\":case\"millisecond\":case\"msecs\":case\"msec\":case\"ms\":return c;default:return}}}}(i);if(\"number\"===p&&isFinite(i))return c.long?(a=i,(u=Math.abs(a))>=r?o(a,u,r,\"day\"):u>=s?o(a,u,s,\"hour\"):u>=t?o(a,u,t,\"minute\"):u>=e?o(a,u,e,\"second\"):a+\" ms\"):function(n){var o=Math.abs(n);return o>=r?Math.round(n/r)+\"d\":o>=s?Math.round(n/s)+\"h\":o>=t?Math.round(n/t)+\"m\":o>=e?Math.round(n/e)+\"s\":n+\"ms\"}(i);throw new Error(\"val is not a non-empty string or a valid number. val=\"+JSON.stringify(i))}}(),t.destroy=function(){console.warn(\"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.\")},Object.keys(e).forEach((s=>{t[s]=e[s]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let s=0;for(let t=0;t<e.length;t++)s=(s<<5)-s+e.charCodeAt(t),s|=0;return t.colors[Math.abs(s)%t.colors.length]},t.enable(t.load()),t})}var v,j,x,E,k={exports:{}},R=/* @__PURE__ */s((E||(E=1,typeof process>\"u\"||\"renderer\"===process.type||!0===process.browser||process.__nwjs?w.exports=(y||(y=1,function(e,t){t.formatArgs=function(t){if(t[0]=(this.useColors?\"%c\":\"\")+this.namespace+(this.useColors?\" %c\":\" \")+t[0]+(this.useColors?\"%c \":\" \")+\"+\"+e.exports.humanize(this.diff),!this.useColors)return;const s=\"color: \"+this.color;t.splice(1,0,s,\"color: inherit\");let r=0,n=0;t[0].replace(/%[a-zA-Z%]/g,(e=>{\"%%\"!==e&&(r++,\"%c\"===e&&(n=r))})),t.splice(n,0,s)},t.save=function(e){try{e?t.storage.setItem(\"debug\",e):t.storage.removeItem(\"debug\")}catch{}},t.load=function(){let e;try{e=t.storage.getItem(\"debug\")}catch{}return!e&&typeof process<\"u\"&&\"env\"in process&&(e=process.env.DEBUG),e},t.useColors=function(){if(typeof window<\"u\"&&window.process&&(\"renderer\"===window.process.type||window.process.__nwjs))return!0;if(typeof navigator<\"u\"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\\/(\\d+)/))return!1;let e;return typeof document<\"u\"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<\"u\"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<\"u\"&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\\/(\\d+)/))&&parseInt(e[1],10)>=31||typeof navigator<\"u\"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\\/(\\d+)/)},t.storage=function(){try{return localStorage}catch{}}(),t.destroy=/* @__PURE__ */(()=>{let e=!1;return()=>{e||(e=!0,console.warn(\"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.\"))}})(),t.colors=[\"#0000CC\",\"#0000FF\",\"#0033CC\",\"#0033FF\",\"#0066CC\",\"#0066FF\",\"#0099CC\",\"#0099FF\",\"#00CC00\",\"#00CC33\",\"#00CC66\",\"#00CC99\",\"#00CCCC\",\"#00CCFF\",\"#3300CC\",\"#3300FF\",\"#3333CC\",\"#3333FF\",\"#3366CC\",\"#3366FF\",\"#3399CC\",\"#3399FF\",\"#33CC00\",\"#33CC33\",\"#33CC66\",\"#33CC99\",\"#33CCCC\",\"#33CCFF\",\"#6600CC\",\"#6600FF\",\"#6633CC\",\"#6633FF\",\"#66CC00\",\"#66CC33\",\"#9900CC\",\"#9900FF\",\"#9933CC\",\"#9933FF\",\"#99CC00\",\"#99CC33\",\"#CC0000\",\"#CC0033\",\"#CC0066\",\"#CC0099\",\"#CC00CC\",\"#CC00FF\",\"#CC3300\",\"#CC3333\",\"#CC3366\",\"#CC3399\",\"#CC33CC\",\"#CC33FF\",\"#CC6600\",\"#CC6633\",\"#CC9900\",\"#CC9933\",\"#CCCC00\",\"#CCCC33\",\"#FF0000\",\"#FF0033\",\"#FF0066\",\"#FF0099\",\"#FF00CC\",\"#FF00FF\",\"#FF3300\",\"#FF3333\",\"#FF3366\",\"#FF3399\",\"#FF33CC\",\"#FF33FF\",\"#FF6600\",\"#FF6633\",\"#FF9900\",\"#FF9933\",\"#FFCC00\",\"#FFCC33\"],t.log=console.debug||console.log||(()=>{}),e.exports=F()(t);const{formatters:s}=e.exports;s.j=function(e){try{return JSON.stringify(e)}catch(e){return\"[UnexpectedJSONParseError]: \"+e.message}}}(O,O.exports)),O.exports):w.exports=(x||(x=1,function(e,t){const s=r,o=n;t.init=function(e){e.inspectOpts={};const s=Object.keys(t.inspectOpts);for(let r=0;r<s.length;r++)e.inspectOpts[s[r]]=t.inspectOpts[s[r]]},t.log=function(...e){return process.stderr.write(o.formatWithOptions(t.inspectOpts,...e)+\"\\n\")},t.formatArgs=function(s){const{namespace:r,useColors:n}=this;if(n){const t=this.color,n=\"\u001b[3\"+(t<8?t:\"8;5;\"+t),o=` ${n};1m${r} \u001b[0m`;s[0]=o+s[0].split(\"\\n\").join(\"\\n\"+o),s.push(n+\"m+\"+e.exports.humanize(this.diff)+\"\u001b[0m\")}else s[0]=(t.inspectOpts.hideDate?\"\":/* @__PURE__ */(new Date).toISOString()+\" \")+r+\" \"+s[0]},t.save=function(e){e?process.env.DEBUG=e:delete process.env.DEBUG},t.load=function(){return process.env.DEBUG},t.useColors=function(){return\"colors\"in t.inspectOpts?!!t.inspectOpts.colors:s.isatty(process.stderr.fd)},t.destroy=o.deprecate((()=>{}),\"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.\"),t.colors=[6,2,3,4,5,1];try{const e=function(){if(j)return v;j=1;const e=function(){const e=/(Chrome|Chromium)\\/(?<chromeVersion>\\d+)\\./.exec(navigator.userAgent);if(e)return Number.parseInt(e.groups.chromeVersion,10)}()>=69&&{level:1,hasBasic:!0,has256:!1,has16m:!1};return v={stdout:e,stderr:e}}();e&&(e.stderr||e).level>=2&&(t.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}t.inspectOpts=Object.keys(process.env).filter((e=>/^debug_/i.test(e))).reduce(((e,t)=>{const s=t.substring(6).toLowerCase().replace(/_([a-z])/g,((e,t)=>t.toUpperCase()));let r=process.env[t];return r=!!/^(yes|on|true|enabled)$/i.test(r)||!/^(no|off|false|disabled)$/i.test(r)&&(\"null\"===r?null:Number(r)),e[s]=r,e}),{}),e.exports=F()(t);const{formatters:i}=e.exports;i.o=function(e){return this.inspectOpts.colors=this.useColors,o.inspect(e,this.inspectOpts).split(\"\\n\").map((e=>e.trim())).join(\" \")},i.O=function(e){return this.inspectOpts.colors=this.useColors,o.inspect(e,this.inspectOpts)}}(k,k.exports)),k.exports)),w.exports));const A=[\"cookie\",\"authorization\"],q=Object.prototype.hasOwnProperty;function N(e={}){const t=e.verbose,s=e.namespace||\"get-it\",r=R(s),n=e.log||r,o=n===r&&!R.enabled(s);let i=0;return{processOptions:e=>(e.debug=n,e.requestId=e.requestId||++i,e),onRequest:s=>{if(o||!s)return s;const r=s.options;if(n(\"[%s] HTTP %s %s\",r.requestId,r.method,r.url),t&&r.body&&\"string\"==typeof r.body&&n(\"[%s] Request body: %s\",r.requestId,r.body),t&&r.headers){const t=!1===e.redactSensitiveHeaders?r.headers:((e,t)=>{const s={};for(const r in e)q.call(e,r)&&(s[r]=t.indexOf(r.toLowerCase())>-1?\"<redacted>\":e[r]);return s})(r.headers,A);n(\"[%s] Request headers: %s\",r.requestId,JSON.stringify(t,null,2))}return s},onResponse:(e,s)=>{if(o||!e)return e;const r=s.options.requestId;return n(\"[%s] Response code: %s %s\",r,e.statusCode,e.statusMessage),t&&e.body&&n(\"[%s] Response body: %s\",r,function(e){return-1!==(e.headers[\"content-type\"]||\"\").toLowerCase().indexOf(\"application/json\")?function(e){try{const t=\"string\"==typeof e?JSON.parse(e):e;return JSON.stringify(t,null,2)}catch{return e}}(e.body):e.body}(e)),e},onError:(e,t)=>{const s=t.options.requestId;return e?(n(\"[%s] ERROR: %s\",s,e.message),e):(n(\"[%s] Error encountered, but handled by an earlier middleware\",s),e)}}}function S(e,t={}){return{processOptions:s=>{const r=s.headers||{};return s.headers=t.override?Object.assign({},r,e):Object.assign({},e,r),s}}}class I extends Error{response;request;constructor(e,t){super();const s=e.url.length>400?`${e.url.slice(0,399)}…`:e.url;let r=`${e.method}-request to ${s} resulted in `;r+=`HTTP ${e.statusCode} ${e.statusMessage}`,this.message=r.trim(),this.response=e,this.request=t.options}}function $(){return{onResponse:(e,t)=>{if(!(e.statusCode>=400))return e;throw new I(e,t)}}}function _(e={}){if(\"function\"!=typeof e.inject)throw new Error(\"`injectResponse` middleware requires a `inject` function\");return{interceptRequest:function(t,s){const r=e.inject(s,t);if(!r)return t;const n=s.context.options;return{body:\"\",url:n.url,method:n.method,headers:{},statusCode:200,statusMessage:\"OK\",...r}}}}const T=typeof Buffer>\"u\"?()=>!1:e=>Buffer.isBuffer(e);function M(e){return\"[object Object]\"===Object.prototype.toString.call(e)}function P(e){if(!1===M(e))return!1;const t=e.constructor;if(void 0===t)return!0;const s=t.prototype;return!(!1===M(s)||!1===s.hasOwnProperty(\"isPrototypeOf\"))}const z=[\"boolean\",\"string\",\"number\"];function L(){return{processOptions:e=>{const t=e.body;return!t||\"function\"==typeof t.pipe||T(t)||-1===z.indexOf(typeof t)&&!Array.isArray(t)&&!P(t)?e:Object.assign({},e,{body:JSON.stringify(e.body),headers:Object.assign({},e.headers,{\"Content-Type\":\"application/json\"})})}}}function B(e){return{onResponse:s=>{const r=s.headers[\"content-type\"]||\"\",n=e&&e.force||-1!==r.indexOf(\"application/json\");return s.body&&r&&n?Object.assign({},s,{body:t(s.body)}):s},processOptions:e=>Object.assign({},e,{headers:Object.assign({Accept:\"application/json\"},e.headers)})};function t(e){try{return JSON.parse(e)}catch(e){throw e.message=`Failed to parsed response body as JSON: ${e.message}`,e}}}function D(e={}){if(!e.ca)throw new Error('Required mtls option \"ca\" is missing');if(!e.cert)throw new Error('Required mtls option \"cert\" is missing');if(!e.key)throw new Error('Required mtls option \"key\" is missing');return{finalizeOptions:t=>{if(function(e){return\"object\"==typeof e&&null!==e&&!(\"protocol\"in e)}(t))return t;const s={cert:e.cert,key:e.key,ca:e.ca};return Object.assign({},t,s)}}}let J={};typeof globalThis<\"u\"?J=globalThis:typeof window<\"u\"?J=window:typeof global<\"u\"?J=global:typeof self<\"u\"&&(J=self);var U=J;function G(e={}){const t=e.implementation||U.Observable;if(!t)throw new Error(\"`Observable` is not available in global scope, and no implementation was passed\");return{onReturn:(e,s)=>new t((t=>(e.error.subscribe((e=>t.error(e))),e.progress.subscribe((e=>t.next(Object.assign({type:\"progress\"},e)))),e.response.subscribe((e=>{t.next(Object.assign({type:\"response\"},e)),t.complete()})),e.request.publish(s),()=>e.abort.publish())))}}function H(e){return t=>({stage:e,percent:t.percentage,total:t.length,loaded:t.transferred,lengthComputable:!(0===t.length&&0===t.percentage)})}function V(){return{onHeaders:(e,t)=>{const s=c({time:16}),r=H(\"download\"),n=e.headers[\"content-length\"],o=n?Number(n):0;return!isNaN(o)&&o>0&&s.setLength(o),s.on(\"progress\",(e=>t.context.channels.progress.publish(r(e)))),e.pipe(s)},onRequest:e=>{if(!e.progress)return;const t=H(\"upload\");e.progress.on(\"progress\",(s=>e.context.channels.progress.publish(t(s))))}}}const W=(e={})=>{const t=e.implementation||Promise;if(!t)throw new Error(\"`Promise` is not available in global scope, and no implementation was passed\");return{onReturn:(s,r)=>new t(((t,n)=>{const o=r.options.cancelToken;o&&o.promise.then((e=>{s.abort.publish(e),n(e)})),s.error.subscribe(n),s.response.subscribe((s=>{t(e.onlyBody?s.body:s)})),setTimeout((()=>{try{s.request.publish(r)}catch(e){n(e)}}),0)}))}};class Z{__CANCEL__=!0;message;constructor(e){this.message=e}toString(){return\"Cancel\"+(this.message?`: ${this.message}`:\"\")}}class K{promise;reason;constructor(e){if(\"function\"!=typeof e)throw new TypeError(\"executor must be a function.\");let t=null;this.promise=new Promise((e=>{t=e})),e((e=>{this.reason||(this.reason=new Z(e),t(this.reason))}))}static source=()=>{let e;return{token:new K((t=>{e=t})),cancel:e}}}function Q(e){if(!(!1===e||e&&e.host))throw new Error(\"Proxy middleware takes an object of host, port and auth properties\");return{processOptions:t=>Object.assign({proxy:e},t)}}W.Cancel=Z,W.CancelToken=K,W.isCancel=e=>!(!e||!e?.__CANCEL__);var X=(e,t,s)=>!(\"GET\"!==s.method&&\"HEAD\"!==s.method||e.response&&e.response.statusCode)&&a(e);function Y(e){return 100*Math.pow(2,e)+100*Math.random()}const ee=(e={})=>(e=>{const t=e.maxRetries||5,s=e.retryDelay||Y,r=e.shouldRetry;return{onError:(e,n)=>{const o=n.options,i=o.maxRetries||t,c=o.retryDelay||s,a=o.shouldRetry||r,u=o.attemptNumber||0;if(null!==(p=o.body)&&\"object\"==typeof p&&\"function\"==typeof p.pipe||!a(e,u,o)||u>=i)return e;var p;const l=Object.assign({},n,{options:Object.assign({},o,{attemptNumber:u+1})});return setTimeout((()=>n.channels.request.publish(l)),c(u)),null}}})({shouldRetry:X,...e});function te(e){const t=new URLSearchParams,s=(e,r)=>{const n=r instanceof Set?Array.from(r):r;if(Array.isArray(n))if(n.length)for(const t in n)s(`${e}[${t}]`,n[t]);else t.append(`${e}[]`,\"\");else if(\"object\"==typeof n&&null!==n)for(const[t,r]of Object.entries(n))s(`${e}[${t}]`,r);else t.append(e,n)};for(const[t,r]of Object.entries(e))s(t,r);return t.toString()}function se(){return{processOptions:e=>{const t=e.body;return t&&\"function\"!=typeof t.pipe&&!T(t)&&P(t)?{...e,body:te(e.body),headers:{...e.headers,\"Content-Type\":\"application/x-www-form-urlencoded\"}}:e}}}ee.shouldRetry=X;const re=(ne=l,function(e={}){const{maxRetries:t=3,ms:s=1e3,maxFree:r=256}=e,{finalizeOptions:n}=ne({keepAlive:!0,keepAliveMsecs:s,maxFreeSockets:r});return{finalizeOptions:n,onError:(e,s)=>{if((\"GET\"===s.options.method||\"POST\"===s.options.method)&&e instanceof u&&\"ECONNRESET\"===e.code&&e.request.reusedSocket){const e=s.options.attemptNumber||0;if(e<t){const t=Object.assign({},s,{options:Object.assign({},s.options,{attemptNumber:e+1})});return setImmediate((()=>s.channels.request.publish(t))),null}}return e}}});var ne;export{Z as Cancel,K as CancelToken,l as agent,m as base,N as debug,S as headers,$ as httpErrors,_ as injectResponse,L as jsonRequest,B as jsonResponse,re as keepAlive,D as mtls,G as observable,o as processOptions,V as progress,W as promise,Q as proxy,ee as retry,se as urlEncoded,i as validateOptions};//# sourceMappingURL=middleware.js.map\n","var s = { 0: 8203, 1: 8204, 2: 8205, 3: 8290, 4: 8291, 5: 8288, 6: 65279, 7: 8289, 8: 119155, 9: 119156, a: 119157, b: 119158, c: 119159, d: 119160, e: 119161, f: 119162 }, c = { 0: 8203, 1: 8204, 2: 8205, 3: 65279 }, u = new Array(4).fill(String.fromCodePoint(c[0])).join(\"\");\nfunction E(t) {\n let e = JSON.stringify(t);\n return `${u}${Array.from(e).map((r) => {\n let n = r.charCodeAt(0);\n if (n > 255) throw new Error(`Only ASCII edit info can be encoded. Error attempting to encode ${e} on character ${r} (${n})`);\n return Array.from(n.toString(4).padStart(4, \"0\")).map((o) => String.fromCodePoint(c[o])).join(\"\");\n }).join(\"\")}`;\n}\nfunction I(t) {\n return !Number.isNaN(Number(t)) || /[a-z]/i.test(t) && !/\\d+(?:[-:\\/]\\d+){2}(?:T\\d+(?:[-:\\/]\\d+){1,2}(\\.\\d+)?Z?)?/.test(t) ? !1 : !!Date.parse(t);\n}\nfunction T(t) {\n try {\n new URL(t, t.startsWith(\"/\") ? \"https://acme.com\" : void 0);\n } catch {\n return !1;\n }\n return !0;\n}\nfunction C(t, e, r = \"auto\") {\n return r === !0 || r === \"auto\" && (I(t) || T(t)) ? t : `${t}${E(e)}`;\n}\nObject.fromEntries(Object.entries(c).map((t) => t.reverse()));\nObject.fromEntries(Object.entries(s).map((t) => t.reverse()));\nvar S = `${Object.values(s).map((t) => `\\\\u{${t.toString(16)}}`).join(\"\")}`, f = new RegExp(`[${S}]{4,}`, \"gu\");\nfunction _(t) {\n var e;\n return { cleaned: t.replace(f, \"\"), encoded: ((e = t.match(f)) == null ? void 0 : e[0]) || \"\" };\n}\nfunction O(t) {\n return t && JSON.parse(_(JSON.stringify(t)).cleaned);\n}\nfunction stegaClean(result) {\n return O(result);\n}\nconst vercelStegaCleanAll = stegaClean;\nexport {\n C,\n stegaClean,\n vercelStegaCleanAll\n};\n//# sourceMappingURL=stegaClean.js.map\n","const BASE_URL = \"https://www.sanity.io/help/\";\nfunction generateHelpUrl(slug) {\n return BASE_URL + slug;\n}\nconst VALID_ASSET_TYPES = [\"image\", \"file\"], VALID_INSERT_LOCATIONS = [\"before\", \"after\", \"replace\"], dataset = (name) => {\n if (!/^(~[a-z0-9]{1}[-\\w]{0,63}|[a-z0-9]{1}[-\\w]{0,63})$/.test(name))\n throw new Error(\n \"Datasets can only contain lowercase characters, numbers, underscores and dashes, and start with tilde, and be maximum 64 characters\"\n );\n}, projectId = (id) => {\n if (!/^[-a-z0-9]+$/i.test(id))\n throw new Error(\"`projectId` can only contain only a-z, 0-9 and dashes\");\n}, validateAssetType = (type) => {\n if (VALID_ASSET_TYPES.indexOf(type) === -1)\n throw new Error(`Invalid asset type: ${type}. Must be one of ${VALID_ASSET_TYPES.join(\", \")}`);\n}, validateObject = (op, val) => {\n if (val === null || typeof val != \"object\" || Array.isArray(val))\n throw new Error(`${op}() takes an object of properties`);\n}, validateDocumentId = (op, id) => {\n if (typeof id != \"string\" || !/^[a-z0-9_][a-z0-9_.-]{0,127}$/i.test(id) || id.includes(\"..\"))\n throw new Error(`${op}(): \"${id}\" is not a valid document ID`);\n}, requireDocumentId = (op, doc) => {\n if (!doc._id)\n throw new Error(`${op}() requires that the document contains an ID (\"_id\" property)`);\n validateDocumentId(op, doc._id);\n}, validateInsert = (at, selector, items) => {\n const signature = \"insert(at, selector, items)\";\n if (VALID_INSERT_LOCATIONS.indexOf(at) === -1) {\n const valid = VALID_INSERT_LOCATIONS.map((loc) => `\"${loc}\"`).join(\", \");\n throw new Error(`${signature} takes an \"at\"-argument which is one of: ${valid}`);\n }\n if (typeof selector != \"string\")\n throw new Error(`${signature} takes a \"selector\"-argument which must be a string`);\n if (!Array.isArray(items))\n throw new Error(`${signature} takes an \"items\"-argument which must be an array`);\n}, hasDataset = (config) => {\n if (!config.dataset)\n throw new Error(\"`dataset` must be provided to perform queries\");\n return config.dataset || \"\";\n}, requestTag = (tag) => {\n if (typeof tag != \"string\" || !/^[a-z0-9._-]{1,75}$/i.test(tag))\n throw new Error(\n \"Tag can only contain alphanumeric characters, underscores, dashes and dots, and be between one and 75 characters long.\"\n );\n return tag;\n}, resourceConfig = (config) => {\n if (!config[\"~experimental_resource\"])\n throw new Error(\"`resource` must be provided to perform resource queries\");\n const { type, id } = config[\"~experimental_resource\"];\n switch (type) {\n case \"dataset\": {\n if (id.split(\".\").length !== 2)\n throw new Error('Dataset resource ID must be in the format \"project.dataset\"');\n return;\n }\n case \"dashboard\":\n case \"media-library\":\n case \"canvas\":\n return;\n default:\n throw new Error(`Unsupported resource type: ${type.toString()}`);\n }\n}, resourceGuard = (service, config) => {\n if (config[\"~experimental_resource\"])\n throw new Error(`\\`${service}\\` does not support resource-based operations`);\n};\nfunction once(fn) {\n let didCall = !1, returnValue;\n return (...args) => (didCall || (returnValue = fn(...args), didCall = !0), returnValue);\n}\nconst createWarningPrinter = (message) => (\n // eslint-disable-next-line no-console\n once((...args) => console.warn(message.join(\" \"), ...args))\n), printCdnAndWithCredentialsWarning = createWarningPrinter([\n \"Because you set `withCredentials` to true, we will override your `useCdn`\",\n \"setting to be false since (cookie-based) credentials are never set on the CDN\"\n]), printCdnWarning = createWarningPrinter([\n \"Since you haven't set a value for `useCdn`, we will deliver content using our\",\n \"global, edge-cached API-CDN. If you wish to have content delivered faster, set\",\n \"`useCdn: false` to use the Live API. Note: You may incur higher costs using the live API.\"\n]), printCdnPreviewDraftsWarning = createWarningPrinter([\n \"The Sanity client is configured with the `perspective` set to `drafts` or `previewDrafts`, which doesn't support the API-CDN.\",\n \"The Live API will be used instead. Set `useCdn: false` in your configuration to hide this warning.\"\n]), printPreviewDraftsDeprecationWarning = createWarningPrinter([\n \"The `previewDrafts` perspective has been renamed to `drafts` and will be removed in a future API version\"\n]), printBrowserTokenWarning = createWarningPrinter([\n \"You have configured Sanity client to use a token in the browser. This may cause unintentional security issues.\",\n `See ${generateHelpUrl(\n \"js-client-browser-token\"\n )} for more information and how to hide this warning.`\n]), printCredentialedTokenWarning = createWarningPrinter([\n \"You have configured Sanity client to use a token, but also provided `withCredentials: true`.\",\n \"This is no longer supported - only token will be used - remove `withCredentials: true`.\"\n]), printNoApiVersionSpecifiedWarning = createWarningPrinter([\n \"Using the Sanity client without specifying an API version is deprecated.\",\n `See ${generateHelpUrl(\"js-client-api-version\")}`\n]), printNoDefaultExport = createWarningPrinter([\n \"The default export of @sanity/client has been deprecated. Use the named export `createClient` instead.\"\n]), defaultCdnHost = \"apicdn.sanity.io\", defaultConfig = {\n apiHost: \"https://api.sanity.io\",\n apiVersion: \"1\",\n useProjectHostname: !0,\n stega: { enabled: !1 }\n}, LOCALHOSTS = [\"localhost\", \"127.0.0.1\", \"0.0.0.0\"], isLocal = (host) => LOCALHOSTS.indexOf(host) !== -1;\nfunction validateApiVersion(apiVersion) {\n if (apiVersion === \"1\" || apiVersion === \"X\")\n return;\n const apiDate = new Date(apiVersion);\n if (!(/^\\d{4}-\\d{2}-\\d{2}$/.test(apiVersion) && apiDate instanceof Date && apiDate.getTime() > 0))\n throw new Error(\"Invalid API version string, expected `1` or date in format `YYYY-MM-DD`\");\n}\nfunction validateApiPerspective(perspective) {\n if (Array.isArray(perspective) && perspective.length > 1 && perspective.includes(\"raw\"))\n throw new TypeError(\n 'Invalid API perspective value: \"raw\". The raw-perspective can not be combined with other perspectives'\n );\n}\nconst initConfig = (config, prevConfig) => {\n const specifiedConfig = {\n ...prevConfig,\n ...config,\n stega: {\n ...typeof prevConfig.stega == \"boolean\" ? { enabled: prevConfig.stega } : prevConfig.stega || defaultConfig.stega,\n ...typeof config.stega == \"boolean\" ? { enabled: config.stega } : config.stega || {}\n }\n };\n specifiedConfig.apiVersion || printNoApiVersionSpecifiedWarning();\n const newConfig = {\n ...defaultConfig,\n ...specifiedConfig\n }, projectBased = newConfig.useProjectHostname && !newConfig[\"~experimental_resource\"];\n if (typeof Promise > \"u\") {\n const helpUrl = generateHelpUrl(\"js-client-promise-polyfill\");\n throw new Error(`No native Promise-implementation found, polyfill needed - see ${helpUrl}`);\n }\n if (projectBased && !newConfig.projectId)\n throw new Error(\"Configuration must contain `projectId`\");\n if (newConfig[\"~experimental_resource\"] && resourceConfig(newConfig), typeof newConfig.perspective < \"u\" && validateApiPerspective(newConfig.perspective), \"encodeSourceMap\" in newConfig)\n throw new Error(\n \"It looks like you're using options meant for '@sanity/preview-kit/client'. 'encodeSourceMap' is not supported in '@sanity/client'. Did you mean 'stega.enabled'?\"\n );\n if (\"encodeSourceMapAtPath\" in newConfig)\n throw new Error(\n \"It looks like you're using options meant for '@sanity/preview-kit/client'. 'encodeSourceMapAtPath' is not supported in '@sanity/client'. Did you mean 'stega.filter'?\"\n );\n if (typeof newConfig.stega.enabled != \"boolean\")\n throw new Error(`stega.enabled must be a boolean, received ${newConfig.stega.enabled}`);\n if (newConfig.stega.enabled && newConfig.stega.studioUrl === void 0)\n throw new Error(\"stega.studioUrl must be defined when stega.enabled is true\");\n if (newConfig.stega.enabled && typeof newConfig.stega.studioUrl != \"string\" && typeof newConfig.stega.studioUrl != \"function\")\n throw new Error(\n `stega.studioUrl must be a string or a function, received ${newConfig.stega.studioUrl}`\n );\n const isBrowser = typeof window < \"u\" && window.location && window.location.hostname, isLocalhost = isBrowser && isLocal(window.location.hostname), hasToken = !!newConfig.token;\n newConfig.withCredentials && hasToken && (printCredentialedTokenWarning(), newConfig.withCredentials = !1), isBrowser && isLocalhost && hasToken && newConfig.ignoreBrowserTokenWarning !== !0 ? printBrowserTokenWarning() : typeof newConfig.useCdn > \"u\" && printCdnWarning(), projectBased && projectId(newConfig.projectId), newConfig.dataset && dataset(newConfig.dataset), \"requestTagPrefix\" in newConfig && (newConfig.requestTagPrefix = newConfig.requestTagPrefix ? requestTag(newConfig.requestTagPrefix).replace(/\\.+$/, \"\") : void 0), newConfig.apiVersion = `${newConfig.apiVersion}`.replace(/^v/, \"\"), newConfig.isDefaultApi = newConfig.apiHost === defaultConfig.apiHost, newConfig.useCdn === !0 && newConfig.withCredentials && printCdnAndWithCredentialsWarning(), newConfig.useCdn = newConfig.useCdn !== !1 && !newConfig.withCredentials, validateApiVersion(newConfig.apiVersion);\n const hostParts = newConfig.apiHost.split(\"://\", 2), protocol = hostParts[0], host = hostParts[1], cdnHost = newConfig.isDefaultApi ? defaultCdnHost : host;\n return projectBased ? (newConfig.url = `${protocol}://${newConfig.projectId}.${host}/v${newConfig.apiVersion}`, newConfig.cdnUrl = `${protocol}://${newConfig.projectId}.${cdnHost}/v${newConfig.apiVersion}`) : (newConfig.url = `${newConfig.apiHost}/v${newConfig.apiVersion}`, newConfig.cdnUrl = newConfig.url), newConfig;\n};\nexport {\n dataset,\n defaultConfig,\n hasDataset,\n initConfig,\n printCdnPreviewDraftsWarning,\n printNoDefaultExport,\n printPreviewDraftsDeprecationWarning,\n requestTag,\n requireDocumentId,\n resourceConfig,\n resourceGuard,\n validateApiPerspective,\n validateAssetType,\n validateDocumentId,\n validateInsert,\n validateObject\n};\n//# sourceMappingURL=config.js.map\n","import { getIt } from \"get-it\";\nimport { adapter, environment } from \"get-it\";\nimport { retry, jsonRequest, jsonResponse, progress, observable, debug, headers, agent } from \"get-it/middleware\";\nimport { Observable, defer, of, isObservable, mergeMap, from, lastValueFrom, shareReplay, catchError, concat, throwError, timer, tap, finalize, share, merge, EMPTY } from \"rxjs\";\nimport { stegaClean } from \"./_chunks-es/stegaClean.js\";\nimport { combineLatestWith, map, filter, finalize as finalize$1 } from \"rxjs/operators\";\nimport { validateObject, validateInsert, requireDocumentId, validateDocumentId, resourceConfig, hasDataset, requestTag, printPreviewDraftsDeprecationWarning, validateApiPerspective, printCdnPreviewDraftsWarning, validateAssetType, resourceGuard, dataset, defaultConfig, initConfig, printNoDefaultExport } from \"./_chunks-es/config.js\";\nclass ClientError extends Error {\n response;\n statusCode = 400;\n responseBody;\n details;\n constructor(res) {\n const props = extractErrorProps(res);\n super(props.message), Object.assign(this, props);\n }\n}\nclass ServerError extends Error {\n response;\n statusCode = 500;\n responseBody;\n details;\n constructor(res) {\n const props = extractErrorProps(res);\n super(props.message), Object.assign(this, props);\n }\n}\nfunction extractErrorProps(res) {\n const body = res.body, props = {\n response: res,\n statusCode: res.statusCode,\n responseBody: stringifyBody(body, res),\n message: \"\",\n details: void 0\n };\n if (body.error && body.message)\n return props.message = `${body.error} - ${body.message}`, props;\n if (isMutationError(body) || isActionError(body)) {\n const allItems = body.error.items || [], items = allItems.slice(0, 5).map((item) => item.error?.description).filter(Boolean);\n let itemsStr = items.length ? `:\n- ${items.join(`\n- `)}` : \"\";\n return allItems.length > 5 && (itemsStr += `\n...and ${allItems.length - 5} more`), props.message = `${body.error.description}${itemsStr}`, props.details = body.error, props;\n }\n return body.error && body.error.description ? (props.message = body.error.description, props.details = body.error, props) : (props.message = body.error || body.message || httpErrorMessage(res), props);\n}\nfunction isMutationError(body) {\n return isPlainObject(body) && isPlainObject(body.error) && body.error.type === \"mutationError\" && typeof body.error.description == \"string\";\n}\nfunction isActionError(body) {\n return isPlainObject(body) && isPlainObject(body.error) && body.error.type === \"actionError\" && typeof body.error.description == \"string\";\n}\nfunction isPlainObject(obj) {\n return typeof obj == \"object\" && obj !== null && !Array.isArray(obj);\n}\nfunction httpErrorMessage(res) {\n const statusMessage = res.statusMessage ? ` ${res.statusMessage}` : \"\";\n return `${res.method}-request to ${res.url} resulted in HTTP ${res.statusCode}${statusMessage}`;\n}\nfunction stringifyBody(body, res) {\n return (res.headers[\"content-type\"] || \"\").toLowerCase().indexOf(\"application/json\") !== -1 ? JSON.stringify(body, null, 2) : body;\n}\nclass CorsOriginError extends Error {\n projectId;\n addOriginUrl;\n constructor({ projectId }) {\n super(\"CorsOriginError\"), this.name = \"CorsOriginError\", this.projectId = projectId;\n const url = new URL(`https://sanity.io/manage/project/${projectId}/api`);\n if (typeof location < \"u\") {\n const { origin } = location;\n url.searchParams.set(\"cors\", \"add\"), url.searchParams.set(\"origin\", origin), this.addOriginUrl = url, this.message = `The current origin is not allowed to connect to the Live Content API. Add it here: ${url}`;\n } else\n this.message = `The current origin is not allowed to connect to the Live Content API. Change your configuration here: ${url}`;\n }\n}\nconst httpError = {\n onResponse: (res) => {\n if (res.statusCode >= 500)\n throw new ServerError(res);\n if (res.statusCode >= 400)\n throw new ClientError(res);\n return res;\n }\n};\nfunction printWarnings() {\n const seen = {};\n return {\n onResponse: (res) => {\n const warn = res.headers[\"x-sanity-warning\"], warnings = Array.isArray(warn) ? warn : [warn];\n for (const msg of warnings)\n !msg || seen[msg] || (seen[msg] = !0, console.warn(msg));\n return res;\n }\n };\n}\nfunction defineHttpRequest(envMiddleware) {\n return getIt([\n retry({ shouldRetry }),\n ...envMiddleware,\n printWarnings(),\n jsonRequest(),\n jsonResponse(),\n progress(),\n httpError,\n observable({ implementation: Observable })\n ]);\n}\nfunction shouldRetry(err, attempt, options) {\n if (options.maxRetries === 0) return !1;\n const isSafe = options.method === \"GET\" || options.method === \"HEAD\", isQuery2 = (options.uri || options.url).startsWith(\"/data/query\"), isRetriableResponse = err.response && (err.response.statusCode === 429 || err.response.statusCode === 502 || err.response.statusCode === 503);\n return (isSafe || isQuery2) && isRetriableResponse ? !0 : retry.shouldRetry(err, attempt, options);\n}\nclass ConnectionFailedError extends Error {\n name = \"ConnectionFailedError\";\n}\nclass DisconnectError extends Error {\n name = \"DisconnectError\";\n reason;\n constructor(message, reason, options = {}) {\n super(message, options), this.reason = reason;\n }\n}\nclass ChannelError extends Error {\n name = \"ChannelError\";\n data;\n constructor(message, data) {\n super(message), this.data = data;\n }\n}\nclass MessageError extends Error {\n name = \"MessageError\";\n data;\n constructor(message, data, options = {}) {\n super(message, options), this.data = data;\n }\n}\nclass MessageParseError extends Error {\n name = \"MessageParseError\";\n}\nconst REQUIRED_EVENTS = [\"channelError\", \"disconnect\"];\nfunction connectEventSource(initEventSource, events) {\n return defer(() => {\n const es = initEventSource();\n return isObservable(es) ? es : of(es);\n }).pipe(mergeMap((es) => connectWithESInstance(es, events)));\n}\nfunction connectWithESInstance(es, events) {\n return new Observable((observer) => {\n const emitOpen = events.includes(\"open\"), emitReconnect = events.includes(\"reconnect\");\n function onError(evt) {\n if (\"data\" in evt) {\n const [parseError, event] = parseEvent(evt);\n observer.error(\n parseError ? new MessageParseError(\"Unable to parse EventSource error message\", { cause: event }) : new MessageError((event?.data).message, event)\n );\n return;\n }\n es.readyState === es.CLOSED ? observer.error(new ConnectionFailedError(\"EventSource connection failed\")) : emitReconnect && observer.next({ type: \"reconnect\" });\n }\n function onOpen() {\n observer.next({ type: \"open\" });\n }\n function onMessage(message) {\n const [parseError, event] = parseEvent(message);\n if (parseError) {\n observer.error(\n new MessageParseError(\"Unable to parse EventSource message\", { cause: parseError })\n );\n return;\n }\n if (message.type === \"channelError\") {\n observer.error(new ChannelError(extractErrorMessage(event?.data), event.data));\n return;\n }\n if (message.type === \"disconnect\") {\n observer.error(\n new DisconnectError(\n `Server disconnected client: ${event.data?.reason || \"unknown error\"}`\n )\n );\n return;\n }\n observer.next({\n type: message.type,\n id: message.lastEventId,\n ...event.data ? { data: event.data } : {}\n });\n }\n es.addEventListener(\"error\", onError), emitOpen && es.addEventListener(\"open\", onOpen);\n const cleanedEvents = [.../* @__PURE__ */ new Set([...REQUIRED_EVENTS, ...events])].filter((type) => type !== \"error\" && type !== \"open\" && type !== \"reconnect\");\n return cleanedEvents.forEach((type) => es.addEventListener(type, onMessage)), () => {\n es.removeEventListener(\"error\", onError), emitOpen && es.removeEventListener(\"open\", onOpen), cleanedEvents.forEach((type) => es.removeEventListener(type, onMessage)), es.close();\n };\n });\n}\nfunction parseEvent(message) {\n try {\n const data = typeof message.data == \"string\" && JSON.parse(message.data);\n return [\n null,\n {\n type: message.type,\n id: message.lastEventId,\n ...isEmptyObject(data) ? {} : { data }\n }\n ];\n } catch (err) {\n return [err, null];\n }\n}\nfunction extractErrorMessage(err) {\n return err.error ? err.error.description ? err.error.description : typeof err.error == \"string\" ? err.error : JSON.stringify(err.error, null, 2) : err.message || \"Unknown listener error\";\n}\nfunction isEmptyObject(data) {\n for (const _ in data)\n return !1;\n return !0;\n}\nfunction getSelection(sel) {\n if (typeof sel == \"string\")\n return { id: sel };\n if (Array.isArray(sel))\n return { query: \"*[_id in $ids]\", params: { ids: sel } };\n if (typeof sel == \"object\" && sel !== null && \"query\" in sel && typeof sel.query == \"string\")\n return \"params\" in sel && typeof sel.params == \"object\" && sel.params !== null ? { query: sel.query, params: sel.params } : { query: sel.query };\n const selectionOpts = [\n \"* Document ID (<docId>)\",\n \"* Array of document IDs\",\n \"* Object containing `query`\"\n ].join(`\n`);\n throw new Error(`Unknown selection - must be one of:\n\n${selectionOpts}`);\n}\nclass BasePatch {\n selection;\n operations;\n constructor(selection, operations = {}) {\n this.selection = selection, this.operations = operations;\n }\n /**\n * Sets the given attributes to the document. Does NOT merge objects.\n * The operation is added to the current patch, ready to be commited by `commit()`\n *\n * @param attrs - Attributes to set. To set a deep attribute, use JSONMatch, eg: \\{\"nested.prop\": \"value\"\\}\n */\n set(attrs) {\n return this._assign(\"set\", attrs);\n }\n /**\n * Sets the given attributes to the document if they are not currently set. Does NOT merge objects.\n * The operation is added to the current patch, ready to be commited by `commit()`\n *\n * @param attrs - Attributes to set. To set a deep attribute, use JSONMatch, eg: \\{\"nested.prop\": \"value\"\\}\n */\n setIfMissing(attrs) {\n return this._assign(\"setIfMissing\", attrs);\n }\n /**\n * Performs a \"diff-match-patch\" operation on the string attributes provided.\n * The operation is added to the current patch, ready to be commited by `commit()`\n *\n * @param attrs - Attributes to perform operation on. To set a deep attribute, use JSONMatch, eg: \\{\"nested.prop\": \"dmp\"\\}\n */\n diffMatchPatch(attrs) {\n return validateObject(\"diffMatchPatch\", attrs), this._assign(\"diffMatchPatch\", attrs);\n }\n /**\n * Unsets the attribute paths provided.\n * The operation is added to the current patch, ready to be commited by `commit()`\n *\n * @param attrs - Attribute paths to unset.\n */\n unset(attrs) {\n if (!Array.isArray(attrs))\n throw new Error(\"unset(attrs) takes an array of attributes to unset, non-array given\");\n return this.operations = Object.assign({}, this.operations, { unset: attrs }), this;\n }\n /**\n * Increment a numeric value. Each entry in the argument is either an attribute or a JSON path. The value may be a positive or negative integer or floating-point value. The operation will fail if target value is not a numeric value, or doesn't exist.\n *\n * @param attrs - Object of attribute paths to increment, values representing the number to increment by.\n */\n inc(attrs) {\n return this._assign(\"inc\", attrs);\n }\n /**\n * Decrement a numeric value. Each entry in the argument is either an attribute or a JSON path. The value may be a positive or negative integer or floating-point value. The operation will fail if target value is not a numeric value, or doesn't exist.\n *\n * @param attrs - Object of attribute paths to decrement, values representing the number to decrement by.\n */\n dec(attrs) {\n return this._assign(\"dec\", attrs);\n }\n /**\n * Provides methods for modifying arrays, by inserting, appending and replacing elements via a JSONPath expression.\n *\n * @param at - Location to insert at, relative to the given selector, or 'replace' the matched path\n * @param selector - JSONPath expression, eg `comments[-1]` or `blocks[_key==\"abc123\"]`\n * @param items - Array of items to insert/replace\n */\n insert(at, selector, items) {\n return validateInsert(at, selector, items), this._assign(\"insert\", { [at]: selector, items });\n }\n /**\n * Append the given items to the array at the given JSONPath\n *\n * @param selector - Attribute/path to append to, eg `comments` or `person.hobbies`\n * @param items - Array of items to append to the array\n */\n append(selector, items) {\n return this.insert(\"after\", `${selector}[-1]`, items);\n }\n /**\n * Prepend the given items to the array at the given JSONPath\n *\n * @param selector - Attribute/path to prepend to, eg `comments` or `person.hobbies`\n * @param items - Array of items to prepend to the array\n */\n prepend(selector, items) {\n return this.insert(\"before\", `${selector}[0]`, items);\n }\n /**\n * Change the contents of an array by removing existing elements and/or adding new elements.\n *\n * @param selector - Attribute or JSONPath expression for array\n * @param start - Index at which to start changing the array (with origin 0). If greater than the length of the array, actual starting index will be set to the length of the array. If negative, will begin that many elements from the end of the array (with origin -1) and will be set to 0 if absolute value is greater than the length of the array.x\n * @param deleteCount - An integer indicating the number of old array elements to remove.\n * @param items - The elements to add to the array, beginning at the start index. If you don't specify any elements, splice() will only remove elements from the array.\n */\n splice(selector, start, deleteCount, items) {\n const delAll = typeof deleteCount > \"u\" || deleteCount === -1, startIndex = start < 0 ? start - 1 : start, delCount = delAll ? -1 : Math.max(0, start + deleteCount), delRange = startIndex < 0 && delCount >= 0 ? \"\" : delCount, rangeSelector = `${selector}[${startIndex}:${delRange}]`;\n return this.insert(\"replace\", rangeSelector, items || []);\n }\n /**\n * Adds a revision clause, preventing the document from being patched if the `_rev` property does not match the given value\n *\n * @param rev - Revision to lock the patch to\n */\n ifRevisionId(rev) {\n return this.operations.ifRevisionID = rev, this;\n }\n /**\n * Return a plain JSON representation of the patch\n */\n serialize() {\n return { ...getSelection(this.selection), ...this.operations };\n }\n /**\n * Return a plain JSON representation of the patch\n */\n toJSON() {\n return this.serialize();\n }\n /**\n * Clears the patch of all operations\n */\n reset() {\n return this.operations = {}, this;\n }\n _assign(op, props, merge2 = !0) {\n return validateObject(op, props), this.operations = Object.assign({}, this.operations, {\n [op]: Object.assign({}, merge2 && this.operations[op] || {}, props)\n }), this;\n }\n _set(op, props) {\n return this._assign(op, props, !1);\n }\n}\nclass ObservablePatch extends BasePatch {\n #client;\n constructor(selection, operations, client) {\n super(selection, operations), this.#client = client;\n }\n /**\n * Clones the patch\n */\n clone() {\n return new ObservablePatch(this.selection, { ...this.operations }, this.#client);\n }\n commit(options) {\n if (!this.#client)\n throw new Error(\n \"No `client` passed to patch, either provide one or pass the patch to a clients `mutate()` method\"\n );\n const returnFirst = typeof this.selection == \"string\", opts = Object.assign({ returnFirst, returnDocuments: !0 }, options);\n return this.#client.mutate({ patch: this.serialize() }, opts);\n }\n}\nclass Patch extends BasePatch {\n #client;\n constructor(selection, operations, client) {\n super(selection, operations), this.#client = client;\n }\n /**\n * Clones the patch\n */\n clone() {\n return new Patch(this.selection, { ...this.operations }, this.#client);\n }\n commit(options) {\n if (!this.#client)\n throw new Error(\n \"No `client` passed to patch, either provide one or pass the patch to a clients `mutate()` method\"\n );\n const returnFirst = typeof this.selection == \"string\", opts = Object.assign({ returnFirst, returnDocuments: !0 }, options);\n return this.#client.mutate({ patch: this.serialize() }, opts);\n }\n}\nconst defaultMutateOptions = { returnDocuments: !1 };\nclass BaseTransaction {\n operations;\n trxId;\n constructor(operations = [], transactionId) {\n this.operations = operations, this.trxId = transactionId;\n }\n /**\n * Creates a new Sanity document. If `_id` is provided and already exists, the mutation will fail. If no `_id` is given, one will automatically be generated by the database.\n * The operation is added to the current transaction, ready to be commited by `commit()`\n *\n * @param doc - Document to create. Requires a `_type` property.\n */\n create(doc) {\n return validateObject(\"create\", doc), this._add({ create: doc });\n }\n /**\n * Creates a new Sanity document. If a document with the same `_id` already exists, the create operation will be ignored.\n * The operation is added to the current transaction, ready to be commited by `commit()`\n *\n * @param doc - Document to create if it does not already exist. Requires `_id` and `_type` properties.\n */\n createIfNotExists(doc) {\n const op = \"createIfNotExists\";\n return validateObject(op, doc), requireDocumentId(op, doc), this._add({ [op]: doc });\n }\n /**\n * Creates a new Sanity document, or replaces an existing one if the same `_id` is already used.\n * The operation is added to the current transaction, ready to be commited by `commit()`\n *\n * @param doc - Document to create or replace. Requires `_id` and `_type` properties.\n */\n createOrReplace(doc) {\n const op = \"createOrReplace\";\n return validateObject(op, doc), requireDocumentId(op, doc), this._add({ [op]: doc });\n }\n /**\n * Deletes the document with the given document ID\n * The operation is added to the current transaction, ready to be commited by `commit()`\n *\n * @param documentId - Document ID to delete\n */\n delete(documentId) {\n return validateDocumentId(\"delete\", documentId), this._add({ delete: { id: documentId } });\n }\n transactionId(id) {\n return id ? (this.trxId = id, this) : this.trxId;\n }\n /**\n * Return a plain JSON representation of the transaction\n */\n serialize() {\n return [...this.operations];\n }\n /**\n * Return a plain JSON representation of the transaction\n */\n toJSON() {\n return this.serialize();\n }\n /**\n * Clears the transaction of all operations\n */\n reset() {\n return this.operations = [], this;\n }\n _add(mut) {\n return this.operations.push(mut), this;\n }\n}\nclass Transaction extends BaseTransaction {\n #client;\n constructor(operations, client, transactionId) {\n super(operations, transactionId), this.#client = client;\n }\n /**\n * Clones the transaction\n */\n clone() {\n return new Transaction([...this.operations], this.#client, this.trxId);\n }\n commit(options) {\n if (!this.#client)\n throw new Error(\n \"No `client` passed to transaction, either provide one or pass the transaction to a clients `mutate()` method\"\n );\n return this.#client.mutate(\n this.serialize(),\n Object.assign({ transactionId: this.trxId }, defaultMutateOptions, options || {})\n );\n }\n patch(patchOrDocumentId, patchOps) {\n const isBuilder = typeof patchOps == \"function\", isPatch = typeof patchOrDocumentId != \"string\" && patchOrDocumentId instanceof Patch, isMutationSelection = typeof patchOrDocumentId == \"object\" && (\"query\" in patchOrDocumentId || \"id\" in patchOrDocumentId);\n if (isPatch)\n return this._add({ patch: patchOrDocumentId.serialize() });\n if (isBuilder) {\n const patch = patchOps(new Patch(patchOrDocumentId, {}, this.#client));\n if (!(patch instanceof Patch))\n throw new Error(\"function passed to `patch()` must return the patch\");\n return this._add({ patch: patch.serialize() });\n }\n if (isMutationSelection) {\n const patch = new Patch(patchOrDocumentId, patchOps || {}, this.#client);\n return this._add({ patch: patch.serialize() });\n }\n return this._add({ patch: { id: patchOrDocumentId, ...patchOps } });\n }\n}\nclass ObservableTransaction extends BaseTransaction {\n #client;\n constructor(operations, client, transactionId) {\n super(operations, transactionId), this.#client = client;\n }\n /**\n * Clones the transaction\n */\n clone() {\n return new ObservableTransaction([...this.operations], this.#client, this.trxId);\n }\n commit(options) {\n if (!this.#client)\n throw new Error(\n \"No `client` passed to transaction, either provide one or pass the transaction to a clients `mutate()` method\"\n );\n return this.#client.mutate(\n this.serialize(),\n Object.assign({ transactionId: this.trxId }, defaultMutateOptions, options || {})\n );\n }\n patch(patchOrDocumentId, patchOps) {\n const isBuilder = typeof patchOps == \"function\";\n if (typeof patchOrDocumentId != \"string\" && patchOrDocumentId instanceof ObservablePatch)\n return this._add({ patch: patchOrDocumentId.serialize() });\n if (isBuilder) {\n const patch = patchOps(new ObservablePatch(patchOrDocumentId, {}, this.#client));\n if (!(patch instanceof ObservablePatch))\n throw new Error(\"function passed to `patch()` must return the patch\");\n return this._add({ patch: patch.serialize() });\n }\n return this._add({ patch: { id: patchOrDocumentId, ...patchOps } });\n }\n}\nconst projectHeader = \"X-Sanity-Project-ID\";\nfunction requestOptions(config, overrides = {}) {\n const headers2 = {}, token = overrides.token || config.token;\n token && (headers2.Authorization = `Bearer ${token}`), !overrides.useGlobalApi && !config.useProjectHostname && config.projectId && (headers2[projectHeader] = config.projectId);\n const withCredentials = !!(typeof overrides.withCredentials > \"u\" ? config.withCredentials : overrides.withCredentials), timeout = typeof overrides.timeout > \"u\" ? config.timeout : overrides.timeout;\n return Object.assign({}, overrides, {\n headers: Object.assign({}, headers2, overrides.headers || {}),\n timeout: typeof timeout > \"u\" ? 5 * 60 * 1e3 : timeout,\n proxy: overrides.proxy || config.proxy,\n json: !0,\n withCredentials,\n fetch: typeof overrides.fetch == \"object\" && typeof config.fetch == \"object\" ? { ...config.fetch, ...overrides.fetch } : overrides.fetch || config.fetch\n });\n}\nconst encodeQueryString = ({\n query,\n params = {},\n options = {}\n}) => {\n const searchParams = new URLSearchParams(), { tag, includeMutations, returnQuery, ...opts } = options;\n tag && searchParams.append(\"tag\", tag), searchParams.append(\"query\", query);\n for (const [key, value] of Object.entries(params))\n searchParams.append(`$${key}`, JSON.stringify(value));\n for (const [key, value] of Object.entries(opts))\n value && searchParams.append(key, `${value}`);\n return returnQuery === !1 && searchParams.append(\"returnQuery\", \"false\"), includeMutations === !1 && searchParams.append(\"includeMutations\", \"false\"), `?${searchParams}`;\n}, excludeFalsey = (param, defValue) => param === !1 ? void 0 : typeof param > \"u\" ? defValue : param, getMutationQuery = (options = {}) => ({\n dryRun: options.dryRun,\n returnIds: !0,\n returnDocuments: excludeFalsey(options.returnDocuments, !0),\n visibility: options.visibility || \"sync\",\n autoGenerateArrayKeys: options.autoGenerateArrayKeys,\n skipCrossDatasetReferenceValidation: options.skipCrossDatasetReferenceValidation\n}), isResponse = (event) => event.type === \"response\", getBody = (event) => event.body, indexBy = (docs, attr) => docs.reduce((indexed, doc) => (indexed[attr(doc)] = doc, indexed), /* @__PURE__ */ Object.create(null)), getQuerySizeLimit = 11264;\nfunction _fetch(client, httpRequest, _stega, query, _params = {}, options = {}) {\n const stega = \"stega\" in options ? {\n ..._stega || {},\n ...typeof options.stega == \"boolean\" ? { enabled: options.stega } : options.stega || {}\n } : _stega, params = stega.enabled ? stegaClean(_params) : _params, mapResponse = options.filterResponse === !1 ? (res) => res : (res) => res.result, { cache, next, ...opts } = {\n // Opt out of setting a `signal` on an internal `fetch` if one isn't provided.\n // This is necessary in React Server Components to avoid opting out of Request Memoization.\n useAbortSignal: typeof options.signal < \"u\",\n // Set `resultSourceMap' when stega is enabled, as it's required for encoding.\n resultSourceMap: stega.enabled ? \"withKeyArraySelector\" : options.resultSourceMap,\n ...options,\n // Default to not returning the query, unless `filterResponse` is `false`,\n // or `returnQuery` is explicitly set. `true` is the default in Content Lake, so skip if truthy\n returnQuery: options.filterResponse === !1 && options.returnQuery !== !1\n }, reqOpts = typeof cache < \"u\" || typeof next < \"u\" ? { ...opts, fetch: { cache, next } } : opts, $request = _dataRequest(client, httpRequest, \"query\", { query, params }, reqOpts);\n return stega.enabled ? $request.pipe(\n combineLatestWith(\n from(\n import(\"./_chunks-es/stegaEncodeSourceMap.js\").then(function(n) {\n return n.stegaEncodeSourceMap$1;\n }).then(\n ({ stegaEncodeSourceMap }) => stegaEncodeSourceMap\n )\n )\n ),\n map(\n ([res, stegaEncodeSourceMap]) => {\n const result = stegaEncodeSourceMap(res.result, res.resultSourceMap, stega);\n return mapResponse({ ...res, result });\n }\n )\n ) : $request.pipe(map(mapResponse));\n}\nfunction _getDocument(client, httpRequest, id, opts = {}) {\n const options = {\n uri: _getDataUrl(client, \"doc\", id),\n json: !0,\n tag: opts.tag,\n signal: opts.signal\n };\n return _requestObservable(client, httpRequest, options).pipe(\n filter(isResponse),\n map((event) => event.body.documents && event.body.documents[0])\n );\n}\nfunction _getDocuments(client, httpRequest, ids, opts = {}) {\n const options = {\n uri: _getDataUrl(client, \"doc\", ids.join(\",\")),\n json: !0,\n tag: opts.tag,\n signal: opts.signal\n };\n return _requestObservable(client, httpRequest, options).pipe(\n filter(isResponse),\n map((event) => {\n const indexed = indexBy(event.body.documents || [], (doc) => doc._id);\n return ids.map((id) => indexed[id] || null);\n })\n );\n}\nfunction _createIfNotExists(client, httpRequest, doc, options) {\n return requireDocumentId(\"createIfNotExists\", doc), _create(client, httpRequest, doc, \"createIfNotExists\", options);\n}\nfunction _createOrReplace(client, httpRequest, doc, options) {\n return requireDocumentId(\"createOrReplace\", doc), _create(client, httpRequest, doc, \"createOrReplace\", options);\n}\nfunction _delete(client, httpRequest, selection, options) {\n return _dataRequest(\n client,\n httpRequest,\n \"mutate\",\n { mutations: [{ delete: getSelection(selection) }] },\n options\n );\n}\nfunction _mutate(client, httpRequest, mutations, options) {\n let mut;\n mutations instanceof Patch || mutations instanceof ObservablePatch ? mut = { patch: mutations.serialize() } : mutations instanceof Transaction || mutations instanceof ObservableTransaction ? mut = mutations.serialize() : mut = mutations;\n const muts = Array.isArray(mut) ? mut : [mut], transactionId = options && options.transactionId || void 0;\n return _dataRequest(client, httpRequest, \"mutate\", { mutations: muts, transactionId }, options);\n}\nfunction _action(client, httpRequest, actions, options) {\n const acts = Array.isArray(actions) ? actions : [actions], transactionId = options && options.transactionId || void 0, skipCrossDatasetReferenceValidation = options && options.skipCrossDatasetReferenceValidation || void 0, dryRun = options && options.dryRun || void 0;\n return _dataRequest(\n client,\n httpRequest,\n \"actions\",\n { actions: acts, transactionId, skipCrossDatasetReferenceValidation, dryRun },\n options\n );\n}\nfunction _dataRequest(client, httpRequest, endpoint, body, options = {}) {\n const isMutation = endpoint === \"mutate\", isAction = endpoint === \"actions\", isQuery2 = endpoint === \"query\", strQuery = isMutation || isAction ? \"\" : encodeQueryString(body), useGet = !isMutation && !isAction && strQuery.length < getQuerySizeLimit, stringQuery = useGet ? strQuery : \"\", returnFirst = options.returnFirst, { timeout, token, tag, headers: headers2, returnQuery, lastLiveEventId, cacheMode } = options, uri = _getDataUrl(client, endpoint, stringQuery), reqOptions = {\n method: useGet ? \"GET\" : \"POST\",\n uri,\n json: !0,\n body: useGet ? void 0 : body,\n query: isMutation && getMutationQuery(options),\n timeout,\n headers: headers2,\n token,\n tag,\n returnQuery,\n perspective: options.perspective,\n resultSourceMap: options.resultSourceMap,\n lastLiveEventId: Array.isArray(lastLiveEventId) ? lastLiveEventId[0] : lastLiveEventId,\n cacheMode,\n canUseCdn: isQuery2,\n signal: options.signal,\n fetch: options.fetch,\n useAbortSignal: options.useAbortSignal,\n useCdn: options.useCdn\n };\n return _requestObservable(client, httpRequest, reqOptions).pipe(\n filter(isResponse),\n map(getBody),\n map((res) => {\n if (!isMutation)\n return res;\n const results = res.results || [];\n if (options.returnDocuments)\n return returnFirst ? results[0] && results[0].document : results.map((mut) => mut.document);\n const key = returnFirst ? \"documentId\" : \"documentIds\", ids = returnFirst ? results[0] && results[0].id : results.map((mut) => mut.id);\n return {\n transactionId: res.transactionId,\n results,\n [key]: ids\n };\n })\n );\n}\nfunction _create(client, httpRequest, doc, op, options = {}) {\n const mutation = { [op]: doc }, opts = Object.assign({ returnFirst: !0, returnDocuments: !0 }, options);\n return _dataRequest(client, httpRequest, \"mutate\", { mutations: [mutation] }, opts);\n}\nconst hasDataConfig = (client) => client.config().dataset !== void 0 && client.config().projectId !== void 0 || client.config()[\"~experimental_resource\"] !== void 0, isQuery = (client, uri) => hasDataConfig(client) && uri.startsWith(_getDataUrl(client, \"query\")), isMutate = (client, uri) => hasDataConfig(client) && uri.startsWith(_getDataUrl(client, \"mutate\")), isDoc = (client, uri) => hasDataConfig(client) && uri.startsWith(_getDataUrl(client, \"doc\", \"\")), isListener = (client, uri) => hasDataConfig(client) && uri.startsWith(_getDataUrl(client, \"listen\")), isHistory = (client, uri) => hasDataConfig(client) && uri.startsWith(_getDataUrl(client, \"history\", \"\")), isData = (client, uri) => uri.startsWith(\"/data/\") || isQuery(client, uri) || isMutate(client, uri) || isDoc(client, uri) || isListener(client, uri) || isHistory(client, uri);\nfunction _requestObservable(client, httpRequest, options) {\n const uri = options.url || options.uri, config = client.config(), canUseCdn = typeof options.canUseCdn > \"u\" ? [\"GET\", \"HEAD\"].indexOf(options.method || \"GET\") >= 0 && isData(client, uri) : options.canUseCdn;\n let useCdn = (options.useCdn ?? config.useCdn) && canUseCdn;\n const tag = options.tag && config.requestTagPrefix ? [config.requestTagPrefix, options.tag].join(\".\") : options.tag || config.requestTagPrefix;\n if (tag && options.tag !== null && (options.query = { tag: requestTag(tag), ...options.query }), [\"GET\", \"HEAD\", \"POST\"].indexOf(options.method || \"GET\") >= 0 && isQuery(client, uri)) {\n const resultSourceMap = options.resultSourceMap ?? config.resultSourceMap;\n resultSourceMap !== void 0 && resultSourceMap !== !1 && (options.query = { resultSourceMap, ...options.query });\n const perspectiveOption = options.perspective || config.perspective;\n typeof perspectiveOption < \"u\" && (perspectiveOption === \"previewDrafts\" && printPreviewDraftsDeprecationWarning(), validateApiPerspective(perspectiveOption), options.query = {\n perspective: Array.isArray(perspectiveOption) ? perspectiveOption.join(\",\") : perspectiveOption,\n ...options.query\n }, (Array.isArray(perspectiveOption) && perspectiveOption.length > 0 || // previewDrafts was renamed to drafts, but keep for backwards compat\n perspectiveOption === \"previewDrafts\" || perspectiveOption === \"drafts\") && useCdn && (useCdn = !1, printCdnPreviewDraftsWarning())), options.lastLiveEventId && (options.query = { ...options.query, lastLiveEventId: options.lastLiveEventId }), options.returnQuery === !1 && (options.query = { returnQuery: \"false\", ...options.query }), useCdn && options.cacheMode == \"noStale\" && (options.query = { cacheMode: \"noStale\", ...options.query });\n }\n const reqOptions = requestOptions(\n config,\n Object.assign({}, options, {\n url: _getUrl(client, uri, useCdn)\n })\n ), request = new Observable(\n (subscriber) => httpRequest(reqOptions, config.requester).subscribe(subscriber)\n );\n return options.signal ? request.pipe(_withAbortSignal(options.signal)) : request;\n}\nfunction _request(client, httpRequest, options) {\n return _requestObservable(client, httpRequest, options).pipe(\n filter((event) => event.type === \"response\"),\n map((event) => event.body)\n );\n}\nfunction _getDataUrl(client, operation, path) {\n const config = client.config();\n if (config[\"~experimental_resource\"]) {\n resourceConfig(config);\n const resourceBase = resourceDataBase(config), uri2 = path !== void 0 ? `${operation}/${path}` : operation;\n return `${resourceBase}/${uri2}`.replace(/\\/($|\\?)/, \"$1\");\n }\n const catalog = hasDataset(config), baseUri = `/${operation}/${catalog}`;\n return `/data${path !== void 0 ? `${baseUri}/${path}` : baseUri}`.replace(/\\/($|\\?)/, \"$1\");\n}\nfunction _getUrl(client, uri, canUseCdn = !1) {\n const { url, cdnUrl } = client.config();\n return `${canUseCdn ? cdnUrl : url}/${uri.replace(/^\\//, \"\")}`;\n}\nfunction _withAbortSignal(signal) {\n return (input) => new Observable((observer) => {\n const abort = () => observer.error(_createAbortError(signal));\n if (signal && signal.aborted) {\n abort();\n return;\n }\n const subscription = input.subscribe(observer);\n return signal.addEventListener(\"abort\", abort), () => {\n signal.removeEventListener(\"abort\", abort), subscription.unsubscribe();\n };\n });\n}\nconst isDomExceptionSupported = !!globalThis.DOMException;\nfunction _createAbortError(signal) {\n if (isDomExceptionSupported)\n return new DOMException(signal?.reason ?? \"The operation was aborted.\", \"AbortError\");\n const error = new Error(signal?.reason ?? \"The operation was aborted.\");\n return error.name = \"AbortError\", error;\n}\nconst resourceDataBase = (config) => {\n if (!config[\"~experimental_resource\"])\n throw new Error(\"`resource` must be provided to perform resource queries\");\n const { type, id } = config[\"~experimental_resource\"];\n switch (type) {\n case \"dataset\": {\n const segments = id.split(\".\");\n if (segments.length !== 2)\n throw new Error('Dataset ID must be in the format \"project.dataset\"');\n return `/projects/${segments[0]}/datasets/${segments[1]}`;\n }\n case \"canvas\":\n return `/canvases/${id}`;\n case \"media-library\":\n return `/media-libraries/${id}`;\n case \"dashboard\":\n return `/dashboards/${id}`;\n default:\n throw new Error(`Unsupported resource type: ${type.toString()}`);\n }\n};\nclass ObservableAssetsClient {\n #client;\n #httpRequest;\n constructor(client, httpRequest) {\n this.#client = client, this.#httpRequest = httpRequest;\n }\n upload(assetType, body, options) {\n return _upload(this.#client, this.#httpRequest, assetType, body, options);\n }\n}\nclass AssetsClient {\n #client;\n #httpRequest;\n constructor(client, httpRequest) {\n this.#client = client, this.#httpRequest = httpRequest;\n }\n upload(assetType, body, options) {\n const observable2 = _upload(this.#client, this.#httpRequest, assetType, body, options);\n return lastValueFrom(\n observable2.pipe(\n filter((event) => event.type === \"response\"),\n map(\n (event) => event.body.document\n )\n )\n );\n }\n}\nfunction _upload(client, httpRequest, assetType, body, opts = {}) {\n validateAssetType(assetType);\n let meta = opts.extract || void 0;\n meta && !meta.length && (meta = [\"none\"]);\n const config = client.config(), options = optionsFromFile(opts, body), { tag, label, title, description, creditLine, filename, source } = options, query = {\n label,\n title,\n description,\n filename,\n meta,\n creditLine\n };\n return source && (query.sourceId = source.id, query.sourceName = source.name, query.sourceUrl = source.url), _requestObservable(client, httpRequest, {\n tag,\n method: \"POST\",\n timeout: options.timeout || 0,\n uri: buildAssetUploadUrl(config, assetType),\n headers: options.contentType ? { \"Content-Type\": options.contentType } : {},\n query,\n body\n });\n}\nfunction buildAssetUploadUrl(config, assetType) {\n const assetTypeEndpoint = assetType === \"image\" ? \"images\" : \"files\";\n if (config[\"~experimental_resource\"]) {\n const { type, id } = config[\"~experimental_resource\"];\n switch (type) {\n case \"dataset\":\n throw new Error(\n \"Assets are not supported for dataset resources, yet. Configure the client with `{projectId: <projectId>, dataset: <datasetId>}` instead.\"\n );\n case \"canvas\":\n return `/canvases/${id}/assets/${assetTypeEndpoint}`;\n case \"media-library\":\n return `/media-libraries/${id}/upload`;\n case \"dashboard\":\n return `/dashboards/${id}/assets/${assetTypeEndpoint}`;\n default:\n throw new Error(`Unsupported resource type: ${type.toString()}`);\n }\n }\n const dataset2 = hasDataset(config);\n return `assets/${assetTypeEndpoint}/${dataset2}`;\n}\nfunction optionsFromFile(opts, file) {\n return typeof File > \"u\" || !(file instanceof File) ? opts : Object.assign(\n {\n filename: opts.preserveFilename === !1 ? void 0 : file.name,\n contentType: file.type\n },\n opts\n );\n}\nvar defaults = (obj, defaults2) => Object.keys(defaults2).concat(Object.keys(obj)).reduce((target, prop) => (target[prop] = typeof obj[prop] > \"u\" ? defaults2[prop] : obj[prop], target), {});\nconst pick = (obj, props) => props.reduce((selection, prop) => (typeof obj[prop] > \"u\" || (selection[prop] = obj[prop]), selection), {}), eventSourcePolyfill = defer(() => import(\"@sanity/eventsource\")).pipe(\n map(({ default: EventSource2 }) => EventSource2),\n shareReplay(1)\n);\nfunction reconnectOnConnectionFailure() {\n return function(source) {\n return source.pipe(\n catchError((err, caught) => err instanceof ConnectionFailedError ? concat(of({ type: \"reconnect\" }), timer(1e3).pipe(mergeMap(() => caught))) : throwError(() => err))\n );\n };\n}\nconst MAX_URL_LENGTH = 14800, possibleOptions = [\n \"includePreviousRevision\",\n \"includeResult\",\n \"includeMutations\",\n \"includeAllVersions\",\n \"visibility\",\n \"effectFormat\",\n \"tag\"\n], defaultOptions = {\n includeResult: !0\n};\nfunction _listen(query, params, opts = {}) {\n const { url, token, withCredentials, requestTagPrefix } = this.config(), tag = opts.tag && requestTagPrefix ? [requestTagPrefix, opts.tag].join(\".\") : opts.tag, options = { ...defaults(opts, defaultOptions), tag }, listenOpts = pick(options, possibleOptions), qs = encodeQueryString({ query, params, options: { tag, ...listenOpts } }), uri = `${url}${_getDataUrl(this, \"listen\", qs)}`;\n if (uri.length > MAX_URL_LENGTH)\n return throwError(() => new Error(\"Query too large for listener\"));\n const listenFor = options.events ? options.events : [\"mutation\"], esOptions = {};\n return withCredentials && (esOptions.withCredentials = !0), token && (esOptions.headers = {\n Authorization: `Bearer ${token}`\n }), connectEventSource(() => (\n // use polyfill if there is no global EventSource or if we need to set headers\n (typeof EventSource > \"u\" || esOptions.headers ? eventSourcePolyfill : of(EventSource)).pipe(map((EventSource2) => new EventSource2(uri, esOptions)))\n ), listenFor).pipe(\n reconnectOnConnectionFailure(),\n filter((event) => listenFor.includes(event.type)),\n map(\n (event) => ({\n type: event.type,\n ...\"data\" in event ? event.data : {}\n })\n )\n );\n}\nfunction shareReplayLatest(configOrPredicate, config) {\n return _shareReplayLatest(\n typeof configOrPredicate == \"function\" ? { predicate: configOrPredicate, ...config } : configOrPredicate\n );\n}\nfunction _shareReplayLatest(config) {\n return (source) => {\n let latest, emitted = !1;\n const { predicate, ...shareConfig } = config, wrapped = source.pipe(\n tap((value) => {\n config.predicate(value) && (emitted = !0, latest = value);\n }),\n finalize(() => {\n emitted = !1, latest = void 0;\n }),\n share(shareConfig)\n ), emitLatest = new Observable((subscriber) => {\n emitted && subscriber.next(\n // this cast is safe because of the emitted check which asserts that we got T from the source\n latest\n ), subscriber.complete();\n });\n return merge(wrapped, emitLatest);\n };\n}\nconst requiredApiVersion = \"2021-03-25\";\nclass LiveClient {\n #client;\n constructor(client) {\n this.#client = client;\n }\n /**\n * Requires `apiVersion` to be `2021-03-25` or later.\n */\n events({\n includeDrafts = !1,\n tag: _tag\n } = {}) {\n resourceGuard(\"live\", this.#client.config());\n const {\n projectId,\n apiVersion: _apiVersion,\n token,\n withCredentials,\n requestTagPrefix\n } = this.#client.config(), apiVersion = _apiVersion.replace(/^v/, \"\");\n if (apiVersion !== \"X\" && apiVersion < requiredApiVersion)\n throw new Error(\n `The live events API requires API version ${requiredApiVersion} or later. The current API version is ${apiVersion}. Please update your API version to use this feature.`\n );\n if (includeDrafts && !token && !withCredentials)\n throw new Error(\n \"The live events API requires a token or withCredentials when 'includeDrafts: true'. Please update your client configuration. The token should have the lowest possible access role.\"\n );\n const path = _getDataUrl(this.#client, \"live/events\"), url = new URL(this.#client.getUrl(path, !1)), tag = _tag && requestTagPrefix ? [requestTagPrefix, _tag].join(\".\") : _tag;\n tag && url.searchParams.set(\"tag\", tag), includeDrafts && url.searchParams.set(\"includeDrafts\", \"true\");\n const esOptions = {};\n includeDrafts && token && (esOptions.headers = {\n Authorization: `Bearer ${token}`\n }), includeDrafts && withCredentials && (esOptions.withCredentials = !0);\n const key = `${url.href}::${JSON.stringify(esOptions)}`, existing = eventsCache.get(key);\n if (existing)\n return existing;\n const events = connectEventSource(() => (\n // use polyfill if there is no global EventSource or if we need to set headers\n (typeof EventSource > \"u\" || esOptions.headers ? eventSourcePolyfill : of(EventSource)).pipe(map((EventSource2) => new EventSource2(url.href, esOptions)))\n ), [\n \"message\",\n \"restart\",\n \"welcome\",\n \"reconnect\",\n \"goaway\"\n ]).pipe(\n reconnectOnConnectionFailure(),\n map((event) => {\n if (event.type === \"message\") {\n const { data, ...rest } = event;\n return { ...rest, tags: data.tags };\n }\n return event;\n })\n ), checkCors = fetchObservable(url, {\n method: \"OPTIONS\",\n mode: \"cors\",\n credentials: esOptions.withCredentials ? \"include\" : \"omit\",\n headers: esOptions.headers\n }).pipe(\n mergeMap(() => EMPTY),\n catchError(() => {\n throw new CorsOriginError({ projectId });\n })\n ), observable2 = concat(checkCors, events).pipe(\n finalize$1(() => eventsCache.delete(key)),\n shareReplayLatest({\n predicate: (event) => event.type === \"welcome\"\n })\n );\n return eventsCache.set(key, observable2), observable2;\n }\n}\nfunction fetchObservable(url, init) {\n return new Observable((observer) => {\n const controller = new AbortController(), signal = controller.signal;\n return fetch(url, { ...init, signal: controller.signal }).then(\n (response) => {\n observer.next(response), observer.complete();\n },\n (err) => {\n signal.aborted || observer.error(err);\n }\n ), () => controller.abort();\n });\n}\nconst eventsCache = /* @__PURE__ */ new Map();\nclass ObservableDatasetsClient {\n #client;\n #httpRequest;\n constructor(client, httpRequest) {\n this.#client = client, this.#httpRequest = httpRequest;\n }\n /**\n * Create a new dataset with the given name\n *\n * @param name - Name of the dataset to create\n * @param options - Options for the dataset\n */\n create(name2, options) {\n return _modify(this.#client, this.#httpRequest, \"PUT\", name2, options);\n }\n /**\n * Edit a dataset with the given name\n *\n * @param name - Name of the dataset to edit\n * @param options - New options for the dataset\n */\n edit(name2, options) {\n return _modify(this.#client, this.#httpRequest, \"PATCH\", name2, options);\n }\n /**\n * Delete a dataset with the given name\n *\n * @param name - Name of the dataset to delete\n */\n delete(name2) {\n return _modify(this.#client, this.#httpRequest, \"DELETE\", name2);\n }\n /**\n * Fetch a list of datasets for the configured project\n */\n list() {\n return _request(this.#client, this.#httpRequest, {\n uri: \"/datasets\",\n tag: null\n });\n }\n}\nclass DatasetsClient {\n #client;\n #httpRequest;\n constructor(client, httpRequest) {\n this.#client = client, this.#httpRequest = httpRequest;\n }\n /**\n * Create a new dataset with the given name\n *\n * @param name - Name of the dataset to create\n * @param options - Options for the dataset\n */\n create(name2, options) {\n return resourceGuard(\"dataset\", this.#client.config()), lastValueFrom(\n _modify(this.#client, this.#httpRequest, \"PUT\", name2, options)\n );\n }\n /**\n * Edit a dataset with the given name\n *\n * @param name - Name of the dataset to edit\n * @param options - New options for the dataset\n */\n edit(name2, options) {\n return resourceGuard(\"dataset\", this.#client.config()), lastValueFrom(\n _modify(this.#client, this.#httpRequest, \"PATCH\", name2, options)\n );\n }\n /**\n * Delete a dataset with the given name\n *\n * @param name - Name of the dataset to delete\n */\n delete(name2) {\n return resourceGuard(\"dataset\", this.#client.config()), lastValueFrom(_modify(this.#client, this.#httpRequest, \"DELETE\", name2));\n }\n /**\n * Fetch a list of datasets for the configured project\n */\n list() {\n return resourceGuard(\"dataset\", this.#client.config()), lastValueFrom(\n _request(this.#client, this.#httpRequest, { uri: \"/datasets\", tag: null })\n );\n }\n}\nfunction _modify(client, httpRequest, method, name2, options) {\n return resourceGuard(\"dataset\", client.config()), dataset(name2), _request(client, httpRequest, {\n method,\n uri: `/datasets/${name2}`,\n body: options,\n tag: null\n });\n}\nclass ObservableProjectsClient {\n #client;\n #httpRequest;\n constructor(client, httpRequest) {\n this.#client = client, this.#httpRequest = httpRequest;\n }\n list(options) {\n resourceGuard(\"projects\", this.#client.config());\n const uri = options?.includeMembers === !1 ? \"/projects?includeMembers=false\" : \"/projects\";\n return _request(this.#client, this.#httpRequest, { uri });\n }\n /**\n * Fetch a project by project ID\n *\n * @param projectId - ID of the project to fetch\n */\n getById(projectId) {\n return resourceGuard(\"projects\", this.#client.config()), _request(this.#client, this.#httpRequest, { uri: `/projects/${projectId}` });\n }\n}\nclass ProjectsClient {\n #client;\n #httpRequest;\n constructor(client, httpRequest) {\n this.#client = client, this.#httpRequest = httpRequest;\n }\n list(options) {\n resourceGuard(\"projects\", this.#client.config());\n const uri = options?.includeMembers === !1 ? \"/projects?includeMembers=false\" : \"/projects\";\n return lastValueFrom(_request(this.#client, this.#httpRequest, { uri }));\n }\n /**\n * Fetch a project by project ID\n *\n * @param projectId - ID of the project to fetch\n */\n getById(projectId) {\n return resourceGuard(\"projects\", this.#client.config()), lastValueFrom(\n _request(this.#client, this.#httpRequest, { uri: `/projects/${projectId}` })\n );\n }\n}\nclass ObservableUsersClient {\n #client;\n #httpRequest;\n constructor(client, httpRequest) {\n this.#client = client, this.#httpRequest = httpRequest;\n }\n /**\n * Fetch a user by user ID\n *\n * @param id - User ID of the user to fetch. If `me` is provided, a minimal response including the users role is returned.\n */\n getById(id) {\n return _request(\n this.#client,\n this.#httpRequest,\n { uri: `/users/${id}` }\n );\n }\n}\nclass UsersClient {\n #client;\n #httpRequest;\n constructor(client, httpRequest) {\n this.#client = client, this.#httpRequest = httpRequest;\n }\n /**\n * Fetch a user by user ID\n *\n * @param id - User ID of the user to fetch. If `me` is provided, a minimal response including the users role is returned.\n */\n getById(id) {\n return lastValueFrom(\n _request(this.#client, this.#httpRequest, {\n uri: `/users/${id}`\n })\n );\n }\n}\nclass ObservableSanityClient {\n assets;\n datasets;\n live;\n projects;\n users;\n /**\n * Private properties\n */\n #clientConfig;\n #httpRequest;\n /**\n * Instance properties\n */\n listen = _listen;\n constructor(httpRequest, config = defaultConfig) {\n this.config(config), this.#httpRequest = httpRequest, this.assets = new ObservableAssetsClient(this, this.#httpRequest), this.datasets = new ObservableDatasetsClient(this, this.#httpRequest), this.live = new LiveClient(this), this.projects = new ObservableProjectsClient(this, this.#httpRequest), this.users = new ObservableUsersClient(this, this.#httpRequest);\n }\n /**\n * Clone the client - returns a new instance\n */\n clone() {\n return new ObservableSanityClient(this.#httpRequest, this.config());\n }\n config(newConfig) {\n if (newConfig === void 0)\n return { ...this.#clientConfig };\n if (this.#clientConfig && this.#clientConfig.allowReconfigure === !1)\n throw new Error(\n \"Existing client instance cannot be reconfigured - use `withConfig(newConfig)` to return a new client\"\n );\n return this.#clientConfig = initConfig(newConfig, this.#clientConfig || {}), this;\n }\n /**\n * Clone the client with a new (partial) configuration.\n *\n * @param newConfig - New client configuration properties, shallowly merged with existing configuration\n */\n withConfig(newConfig) {\n const thisConfig = this.config();\n return new ObservableSanityClient(this.#httpRequest, {\n ...thisConfig,\n ...newConfig,\n stega: {\n ...thisConfig.stega || {},\n ...typeof newConfig?.stega == \"boolean\" ? { enabled: newConfig.stega } : newConfig?.stega || {}\n }\n });\n }\n fetch(query, params, options) {\n return _fetch(\n this,\n this.#httpRequest,\n this.#clientConfig.stega,\n query,\n params,\n options\n );\n }\n /**\n * Fetch a single document with the given ID.\n *\n * @param id - Document ID to fetch\n * @param options - Request options\n */\n getDocument(id, options) {\n return _getDocument(this, this.#httpRequest, id, options);\n }\n /**\n * Fetch multiple documents in one request.\n * Should be used sparingly - performing a query is usually a better option.\n * The order/position of documents is preserved based on the original array of IDs.\n * If any of the documents are missing, they will be replaced by a `null` entry in the returned array\n *\n * @param ids - Document IDs to fetch\n * @param options - Request options\n */\n getDocuments(ids, options) {\n return _getDocuments(this, this.#httpRequest, ids, options);\n }\n create(document, options) {\n return _create(this, this.#httpRequest, document, \"create\", options);\n }\n createIfNotExists(document, options) {\n return _createIfNotExists(this, this.#httpRequest, document, options);\n }\n createOrReplace(document, options) {\n return _createOrReplace(this, this.#httpRequest, document, options);\n }\n delete(selection, options) {\n return _delete(this, this.#httpRequest, selection, options);\n }\n mutate(operations, options) {\n return _mutate(this, this.#httpRequest, operations, options);\n }\n /**\n * Create a new buildable patch of operations to perform\n *\n * @param selection - Document ID, an array of document IDs, or an object with `query` and optional `params`, defining which document(s) to patch\n * @param operations - Optional object of patch operations to initialize the patch instance with\n * @returns Patch instance - call `.commit()` to perform the operations defined\n */\n patch(selection, operations) {\n return new ObservablePatch(selection, operations, this);\n }\n /**\n * Create a new transaction of mutations\n *\n * @param operations - Optional array of mutation operations to initialize the transaction instance with\n */\n transaction(operations) {\n return new ObservableTransaction(operations, this);\n }\n /**\n * Perform action operations against the configured dataset\n *\n * @param operations - Action operation(s) to execute\n * @param options - Action options\n */\n action(operations, options) {\n return _action(this, this.#httpRequest, operations, options);\n }\n /**\n * Perform an HTTP request against the Sanity API\n *\n * @param options - Request options\n */\n request(options) {\n return _request(this, this.#httpRequest, options);\n }\n /**\n * Get a Sanity API URL for the URI provided\n *\n * @param uri - URI/path to build URL for\n * @param canUseCdn - Whether or not to allow using the API CDN for this route\n */\n getUrl(uri, canUseCdn) {\n return _getUrl(this, uri, canUseCdn);\n }\n /**\n * Get a Sanity API URL for the data operation and path provided\n *\n * @param operation - Data operation (eg `query`, `mutate`, `listen` or similar)\n * @param path - Path to append after the operation\n */\n getDataUrl(operation, path) {\n return _getDataUrl(this, operation, path);\n }\n}\nclass SanityClient {\n assets;\n datasets;\n live;\n projects;\n users;\n /**\n * Observable version of the Sanity client, with the same configuration as the promise-based one\n */\n observable;\n /**\n * Private properties\n */\n #clientConfig;\n #httpRequest;\n /**\n * Instance properties\n */\n listen = _listen;\n constructor(httpRequest, config = defaultConfig) {\n this.config(config), this.#httpRequest = httpRequest, this.assets = new AssetsClient(this, this.#httpRequest), this.datasets = new DatasetsClient(this, this.#httpRequest), this.live = new LiveClient(this), this.projects = new ProjectsClient(this, this.#httpRequest), this.users = new UsersClient(this, this.#httpRequest), this.observable = new ObservableSanityClient(httpRequest, config);\n }\n /**\n * Clone the client - returns a new instance\n */\n clone() {\n return new SanityClient(this.#httpRequest, this.config());\n }\n config(newConfig) {\n if (newConfig === void 0)\n return { ...this.#clientConfig };\n if (this.#clientConfig && this.#clientConfig.allowReconfigure === !1)\n throw new Error(\n \"Existing client instance cannot be reconfigured - use `withConfig(newConfig)` to return a new client\"\n );\n return this.observable && this.observable.config(newConfig), this.#clientConfig = initConfig(newConfig, this.#clientConfig || {}), this;\n }\n /**\n * Clone the client with a new (partial) configuration.\n *\n * @param newConfig - New client configuration properties, shallowly merged with existing configuration\n */\n withConfig(newConfig) {\n const thisConfig = this.config();\n return new SanityClient(this.#httpRequest, {\n ...thisConfig,\n ...newConfig,\n stega: {\n ...thisConfig.stega || {},\n ...typeof newConfig?.stega == \"boolean\" ? { enabled: newConfig.stega } : newConfig?.stega || {}\n }\n });\n }\n fetch(query, params, options) {\n return lastValueFrom(\n _fetch(\n this,\n this.#httpRequest,\n this.#clientConfig.stega,\n query,\n params,\n options\n )\n );\n }\n /**\n * Fetch a single document with the given ID.\n *\n * @param id - Document ID to fetch\n * @param options - Request options\n */\n getDocument(id, options) {\n return lastValueFrom(_getDocument(this, this.#httpRequest, id, options));\n }\n /**\n * Fetch multiple documents in one request.\n * Should be used sparingly - performing a query is usually a better option.\n * The order/position of documents is preserved based on the original array of IDs.\n * If any of the documents are missing, they will be replaced by a `null` entry in the returned array\n *\n * @param ids - Document IDs to fetch\n * @param options - Request options\n */\n getDocuments(ids, options) {\n return lastValueFrom(_getDocuments(this, this.#httpRequest, ids, options));\n }\n create(document, options) {\n return lastValueFrom(\n _create(this, this.#httpRequest, document, \"create\", options)\n );\n }\n createIfNotExists(document, options) {\n return lastValueFrom(\n _createIfNotExists(this, this.#httpRequest, document, options)\n );\n }\n createOrReplace(document, options) {\n return lastValueFrom(\n _createOrReplace(this, this.#httpRequest, document, options)\n );\n }\n delete(selection, options) {\n return lastValueFrom(_delete(this, this.#httpRequest, selection, options));\n }\n mutate(operations, options) {\n return lastValueFrom(_mutate(this, this.#httpRequest, operations, options));\n }\n /**\n * Create a new buildable patch of operations to perform\n *\n * @param selection - Document ID, an array of document IDs, or an object with `query` and optional `params`, defining which document(s) to patch\n * @param operations - Optional object of patch operations to initialize the patch instance with\n * @returns Patch instance - call `.commit()` to perform the operations defined\n */\n patch(documentId, operations) {\n return new Patch(documentId, operations, this);\n }\n /**\n * Create a new transaction of mutations\n *\n * @param operations - Optional array of mutation operations to initialize the transaction instance with\n */\n transaction(operations) {\n return new Transaction(operations, this);\n }\n /**\n * Perform action operations against the configured dataset\n * Returns a promise that resolves to the transaction result\n *\n * @param operations - Action operation(s) to execute\n * @param options - Action options\n */\n action(operations, options) {\n return lastValueFrom(_action(this, this.#httpRequest, operations, options));\n }\n /**\n * Perform a request against the Sanity API\n * NOTE: Only use this for Sanity API endpoints, not for your own APIs!\n *\n * @param options - Request options\n * @returns Promise resolving to the response body\n */\n request(options) {\n return lastValueFrom(_request(this, this.#httpRequest, options));\n }\n /**\n * Perform an HTTP request a `/data` sub-endpoint\n * NOTE: Considered internal, thus marked as deprecated. Use `request` instead.\n *\n * @deprecated - Use `request()` or your own HTTP library instead\n * @param endpoint - Endpoint to hit (mutate, query etc)\n * @param body - Request body\n * @param options - Request options\n * @internal\n */\n dataRequest(endpoint, body, options) {\n return lastValueFrom(_dataRequest(this, this.#httpRequest, endpoint, body, options));\n }\n /**\n * Get a Sanity API URL for the URI provided\n *\n * @param uri - URI/path to build URL for\n * @param canUseCdn - Whether or not to allow using the API CDN for this route\n */\n getUrl(uri, canUseCdn) {\n return _getUrl(this, uri, canUseCdn);\n }\n /**\n * Get a Sanity API URL for the data operation and path provided\n *\n * @param operation - Data operation (eg `query`, `mutate`, `listen` or similar)\n * @param path - Path to append after the operation\n */\n getDataUrl(operation, path) {\n return _getDataUrl(this, operation, path);\n }\n}\nfunction defineCreateClientExports(envMiddleware, ClassConstructor) {\n return { requester: defineHttpRequest(envMiddleware), createClient: (config) => {\n const clientRequester = defineHttpRequest(envMiddleware);\n return new ClassConstructor(\n (options, requester2) => (requester2 || clientRequester)({\n maxRedirects: 0,\n maxRetries: config.maxRetries,\n retryDelay: config.retryDelay,\n ...options\n }),\n config\n );\n } };\n}\nfunction defineDeprecatedCreateClient(createClient2) {\n return function(config) {\n return printNoDefaultExport(), createClient2(config);\n };\n}\nvar name = \"@sanity/client\", version = \"6.29.0\";\nconst middleware = [\n debug({ verbose: !0, namespace: \"sanity:client\" }),\n headers({ \"User-Agent\": `${name} ${version}` }),\n // Enable keep-alive, and in addition limit the number of sockets that can be opened.\n // This avoids opening too many connections to the server if someone tries to execute\n // a bunch of requests in parallel. It's recommended to have a concurrency limit\n // at a \"higher limit\" (i.e. you shouldn't actually execute hundreds of requests in parallel),\n // and this is mainly to minimize the impact for the network and server.\n //\n // We're currently matching the same defaults as browsers:\n // https://stackoverflow.com/questions/26003756/is-there-a-limit-practical-or-otherwise-to-the-number-of-web-sockets-a-page-op\n agent({\n keepAlive: !0,\n maxSockets: 30,\n maxTotalSockets: 256\n })\n], exp = defineCreateClientExports(middleware, SanityClient), requester = exp.requester, createClient = exp.createClient, deprecatedCreateClient = defineDeprecatedCreateClient(createClient);\nexport {\n BasePatch,\n BaseTransaction,\n ChannelError,\n ClientError,\n ConnectionFailedError,\n CorsOriginError,\n DisconnectError,\n MessageError,\n MessageParseError,\n ObservablePatch,\n ObservableSanityClient,\n ObservableTransaction,\n Patch,\n SanityClient,\n ServerError,\n Transaction,\n connectEventSource,\n createClient,\n deprecatedCreateClient as default,\n requester,\n adapter as unstable__adapter,\n environment as unstable__environment,\n validateApiPerspective\n};\n//# sourceMappingURL=index.js.map\n","import {logout} from '@sanity/sdk'\n\nimport {createCallbackHook} from '../helpers/createCallbackHook'\n\n/**\n * Hook to log out of the current session\n * @internal\n * @returns A function to log out of the current session\n */\nexport const useLogOut = createCallbackHook(logout)\n","import {ClientError} from '@sanity/client'\nimport {AuthStateType} from '@sanity/sdk'\nimport {useCallback, useEffect, useState} from 'react'\nimport {type FallbackProps} from 'react-error-boundary'\n\nimport {useAuthState} from '../../hooks/auth/useAuthState'\nimport {useLogOut} from '../../hooks/auth/useLogOut'\nimport {AuthError} from './AuthError'\n/**\n * @alpha\n */\nexport type LoginErrorProps = FallbackProps\n\n/**\n * Displays authentication error details and provides retry functionality.\n * Only handles {@link AuthError} instances - rethrows other error types.\n *\n * @alpha\n */\nexport function LoginError({error, resetErrorBoundary}: LoginErrorProps): React.ReactNode {\n if (!(error instanceof AuthError)) throw error\n const logout = useLogOut()\n const authState = useAuthState()\n\n const [authErrorMessage, setAuthErrorMessage] = useState(\n 'Please try again or contact support if the problem persists.',\n )\n\n const handleRetry = useCallback(async () => {\n await logout()\n resetErrorBoundary()\n }, [logout, resetErrorBoundary])\n\n useEffect(() => {\n if (authState.type === AuthStateType.ERROR && authState.error instanceof ClientError) {\n if (authState.error.statusCode === 401) {\n handleRetry()\n } else if (authState.error.statusCode === 404) {\n const errorMessage = authState.error.response.body.message || ''\n if (errorMessage.startsWith('Session with sid') && errorMessage.endsWith('not found')) {\n setAuthErrorMessage('The session ID is invalid or expired.')\n } else {\n setAuthErrorMessage('The login link is invalid or expired. Please try again.')\n }\n }\n }\n }, [authState, handleRetry])\n\n return (\n <div className=\"sc-login-error\">\n <div className=\"sc-login-error__content\">\n <h2 className=\"sc-login-error__title\">Authentication Error</h2>\n <p className=\"sc-login-error__description\">{authErrorMessage}</p>\n </div>\n\n <button className=\"sc-login-error__button\" onClick={handleRetry}>\n Retry\n </button>\n </div>\n )\n}\n","import {AuthStateType} from '@sanity/sdk'\nimport {useEffect, useMemo} from 'react'\nimport {ErrorBoundary, type FallbackProps} from 'react-error-boundary'\n\nimport {useAuthState} from '../../hooks/auth/useAuthState'\nimport {useLoginUrl} from '../../hooks/auth/useLoginUrl'\nimport {isInIframe} from '../utils'\nimport {AuthError} from './AuthError'\nimport {LoginCallback} from './LoginCallback'\nimport {LoginError, type LoginErrorProps} from './LoginError'\n\n// Only import bridge if we're in an iframe. This assumes that the app is\n// running within SanityOS if it is in an iframe and that the bridge hasn't already been loaded\nif (isInIframe() && !document.querySelector('[data-sanity-core]')) {\n const parsedUrl = new URL(window.location.href)\n const mode = new URLSearchParams(parsedUrl.hash.slice(1)).get('mode')\n const script = document.createElement('script')\n script.src =\n mode === 'core-ui--staging'\n ? 'https://core.sanity-cdn.work/bridge.js'\n : 'https://core.sanity-cdn.com/bridge.js'\n script.type = 'module'\n script.async = true\n document.head.appendChild(script)\n}\n\n/**\n * @public\n */\nexport interface AuthBoundaryProps {\n /**\n * Custom component to render the login screen.\n * Receives all props. Defaults to {@link Login}.\n */\n LoginComponent?: React.ComponentType<{\n header?: React.ReactNode\n footer?: React.ReactNode\n }>\n\n /**\n * Custom component to render during OAuth callback processing.\n * Receives all props. Defaults to {@link LoginCallback}.\n */\n CallbackComponent?: React.ComponentType<{\n header?: React.ReactNode\n footer?: React.ReactNode\n }>\n\n /**\n * Custom component to render when authentication errors occur.\n * Receives error boundary props and layout props. Defaults to\n * {@link LoginError}\n */\n LoginErrorComponent?: React.ComponentType<LoginErrorProps>\n\n /** Header content to display */\n header?: React.ReactNode\n\n /** Footer content to display */\n footer?: React.ReactNode\n\n /** Protected content to render when authenticated */\n children?: React.ReactNode\n}\n\n/**\n * A component that handles authentication flow and error boundaries for a\n * protected section of the application.\n *\n * @remarks\n * This component manages different authentication states and renders the\n * appropriate components based on that state.\n *\n * @example\n * ```tsx\n * function App() {\n * return (\n * <AuthBoundary header={<MyLogo />}>\n * <ProtectedContent />\n * </AuthBoundary>\n * )\n * }\n * ```\n *\n * @internal\n */\nexport function AuthBoundary({\n LoginErrorComponent = LoginError,\n ...props\n}: AuthBoundaryProps): React.ReactNode {\n const FallbackComponent = useMemo(() => {\n return function LoginComponentWithLayoutProps(fallbackProps: FallbackProps) {\n return <LoginErrorComponent {...fallbackProps} />\n }\n }, [LoginErrorComponent])\n\n return (\n <ErrorBoundary FallbackComponent={FallbackComponent}>\n <AuthSwitch {...props} />\n </ErrorBoundary>\n )\n}\n\ninterface AuthSwitchProps {\n LoginComponent?: React.ComponentType<{\n header?: React.ReactNode\n footer?: React.ReactNode\n }>\n CallbackComponent?: React.ComponentType<{\n header?: React.ReactNode\n footer?: React.ReactNode\n }>\n header?: React.ReactNode\n footer?: React.ReactNode\n children?: React.ReactNode\n}\n\nfunction AuthSwitch({CallbackComponent = LoginCallback, children, ...props}: AuthSwitchProps) {\n const authState = useAuthState()\n\n const isLoggedOut = authState.type === AuthStateType.LOGGED_OUT && !authState.isDestroyingSession\n const loginUrl = useLoginUrl()\n\n useEffect(() => {\n if (isLoggedOut && !isInIframe()) {\n // We don't want to redirect to login if we're in the Dashboard\n window.location.href = loginUrl\n }\n }, [isLoggedOut, loginUrl])\n\n switch (authState.type) {\n case AuthStateType.ERROR: {\n throw new AuthError(authState.error)\n }\n case AuthStateType.LOGGING_IN: {\n return <CallbackComponent {...props} />\n }\n case AuthStateType.LOGGED_IN: {\n return children\n }\n case AuthStateType.LOGGED_OUT: {\n return null\n }\n default: {\n // @ts-expect-error - This state should never happen\n throw new Error(`Invalid auth state: ${authState.type}`)\n }\n }\n}\n","import {createSanityInstance, type SanityConfig, type SanityInstance} from '@sanity/sdk'\nimport {Suspense, useContext, useEffect, useMemo, useRef} from 'react'\n\nimport {SanityInstanceContext} from './SanityInstanceContext'\n\nconst DEFAULT_FALLBACK = (\n <>\n Warning: No fallback provided. Please supply a fallback prop to ensure proper Suspense handling.\n </>\n)\n\n/**\n * Props for the ResourceProvider component\n * @internal\n */\nexport interface ResourceProviderProps extends SanityConfig {\n /**\n * React node to show while content is loading\n * Used as the fallback for the internal Suspense boundary\n */\n fallback: React.ReactNode\n children: React.ReactNode\n}\n\n/**\n * Provides a Sanity instance to child components through React Context\n *\n * @internal\n *\n * @remarks\n * The ResourceProvider creates a hierarchical structure of Sanity instances:\n * - When used as a root provider, it creates a new Sanity instance with the given config\n * - When nested inside another ResourceProvider, it creates a child instance that\n * inherits and extends the parent's configuration\n *\n * Features:\n * - Automatically manages the lifecycle of Sanity instances\n * - Disposes instances when the component unmounts\n * - Includes a Suspense boundary for data loading\n * - Enables hierarchical configuration inheritance\n *\n * Use this component to:\n * - Set up project/dataset configuration for an application\n * - Override specific configuration values in a section of your app\n * - Create isolated instance hierarchies for different features\n *\n * @example Creating a root provider\n * ```tsx\n * <ResourceProvider\n * projectId=\"your-project-id\"\n * dataset=\"production\"\n * fallback={<LoadingSpinner />}\n * >\n * <YourApp />\n * </ResourceProvider>\n * ```\n *\n * @example Creating nested providers with configuration inheritance\n * ```tsx\n * // Root provider with production config with nested provider for preview features with custom dataset\n * <ResourceProvider projectId=\"abc123\" dataset=\"production\" fallback={<Loading />}>\n * <div>...Main app content</div>\n * <Dashboard />\n * <ResourceProvider dataset=\"preview\" fallback={<Loading />}>\n * <PreviewFeatures />\n * </ResourceProvider>\n * </ResourceProvider>\n * ```\n */\nexport function ResourceProvider({\n children,\n fallback,\n ...config\n}: ResourceProviderProps): React.ReactNode {\n const parent = useContext(SanityInstanceContext)\n const instance = useMemo(\n () => (parent ? parent.createChild(config) : createSanityInstance(config)),\n [config, parent],\n )\n\n // Ref to hold the scheduled disposal timer.\n const disposal = useRef<{\n instance: SanityInstance\n timeoutId: ReturnType<typeof setTimeout>\n } | null>(null)\n\n useEffect(() => {\n // If the component remounts quickly (as in Strict Mode), cancel any pending disposal.\n if (disposal.current !== null && instance === disposal.current.instance) {\n clearTimeout(disposal.current.timeoutId)\n disposal.current = null\n }\n\n return () => {\n disposal.current = {\n instance,\n timeoutId: setTimeout(() => {\n if (!instance.isDisposed()) {\n instance.dispose()\n }\n }, 0),\n }\n }\n }, [instance])\n\n return (\n <SanityInstanceContext.Provider value={instance}>\n <Suspense fallback={fallback ?? DEFAULT_FALLBACK}>{children}</Suspense>\n </SanityInstanceContext.Provider>\n )\n}\n","import {type SanityConfig} from '@sanity/sdk'\nimport {type ReactElement, type ReactNode} from 'react'\n\nimport {ResourceProvider} from '../context/ResourceProvider'\nimport {AuthBoundary, type AuthBoundaryProps} from './auth/AuthBoundary'\n\n/**\n * @internal\n */\nexport interface SDKProviderProps extends AuthBoundaryProps {\n children: ReactNode\n config: SanityConfig | SanityConfig[]\n fallback: ReactNode\n}\n\n/**\n * @internal\n *\n * Top-level context provider that provides access to the Sanity SDK.\n * Creates a hierarchy of ResourceProviders, each providing a SanityInstance that can be\n * accessed by hooks. The first configuration in the array becomes the default instance.\n */\nexport function SDKProvider({\n children,\n config,\n fallback,\n ...props\n}: SDKProviderProps): ReactElement {\n // reverse because we want the first config to be the default, but the\n // ResourceProvider nesting makes the last one the default\n const configs = (Array.isArray(config) ? config : [config]).slice().reverse()\n\n // Create a nested structure of ResourceProviders for each config\n const createNestedProviders = (index: number): ReactElement => {\n if (index >= configs.length) {\n return <AuthBoundary {...props}>{children}</AuthBoundary>\n }\n\n return (\n <ResourceProvider {...configs[index]} fallback={fallback}>\n {createNestedProviders(index + 1)}\n </ResourceProvider>\n )\n }\n\n return createNestedProviders(0)\n}\n","import {type SanityConfig} from '@sanity/sdk'\nimport {type ReactElement, useEffect} from 'react'\n\nimport {SDKProvider} from './SDKProvider'\nimport {isInIframe, isLocalUrl} from './utils'\n\n/**\n * @public\n * @category Types\n */\nexport interface SanityAppProps {\n /* One or more SanityConfig objects providing a project ID and dataset name */\n config: SanityConfig | SanityConfig[]\n /** @deprecated use the `config` prop instead. */\n sanityConfigs?: SanityConfig[]\n children: React.ReactNode\n /* Fallback content to show when child components are suspending. Same as the `fallback` prop for React Suspense. */\n fallback: React.ReactNode\n}\n\nconst REDIRECT_URL = 'https://sanity.io/welcome'\n\n/**\n * @public\n *\n * The SanityApp component provides your Sanity application with access to your Sanity configuration,\n * as well as application context and state which is used by the Sanity React hooks. Your application\n * must be wrapped with the SanityApp component to function properly.\n *\n * SanityApp creates a hierarchy of ResourceProviders, each providing a SanityInstance that can be\n * accessed by hooks. The first configuration in the array becomes the default instance.\n *\n * @category Components\n * @param props - Your Sanity configuration and the React children to render\n * @returns Your Sanity application, integrated with your Sanity configuration and application context\n *\n * @example\n * ```tsx\n * import { SanityApp } from '@sanity/sdk-react'\n *\n * import MyAppRoot from './Root'\n *\n * // Single project configuration\n * const mySanityConfig = {\n * projectId: 'my-project-id',\n * dataset: 'production',\n * }\n *\n * // Or multiple project configurations\n * const multipleConfigs = [\n * // Configuration for your main project. This will be used as the default project for hooks.\n * {\n * projectId: 'marketing-website-project',\n * dataset: 'production',\n * },\n * // Configuration for a separate blog project\n * {\n * projectId: 'blog-project',\n * dataset: 'production',\n * },\n * // Configuration for a separate ecommerce project\n * {\n * projectId: 'ecommerce-project',\n * dataset: 'production',\n * }\n * ]\n *\n * export default function MyApp() {\n * return (\n * <SanityApp config={mySanityConfig} fallback={<LoadingSpinner />}>\n * <MyAppRoot />\n * </SanityApp>\n * )\n * }\n * ```\n */\nexport function SanityApp({\n children,\n fallback,\n config,\n sanityConfigs,\n ...props\n}: SanityAppProps): ReactElement {\n const configs = config ?? sanityConfigs ?? []\n\n useEffect(() => {\n let timeout: NodeJS.Timeout | undefined\n\n if (!isInIframe() && !isLocalUrl(window)) {\n // If the app is not running in an iframe and is not a local url, redirect to core.\n timeout = setTimeout(() => {\n // eslint-disable-next-line no-console\n console.warn('Redirecting to core', REDIRECT_URL)\n window.location.replace(REDIRECT_URL)\n }, 1000)\n }\n return () => clearTimeout(timeout)\n }, [])\n\n return (\n <SDKProvider {...props} fallback={fallback} config={configs}>\n {children}\n </SDKProvider>\n )\n}\n","import {getTokenState} from '@sanity/sdk'\n\nimport {createStateSourceHook} from '../helpers/createStateSourceHook'\n\n/**\n * Hook to get the currently logged in user\n * @internal\n * @returns The current user or null if not authenticated\n */\nexport const useAuthToken = createStateSourceHook(getTokenState)\n","import {type CurrentUser, getCurrentUserState} from '@sanity/sdk'\n\nimport {createStateSourceHook} from '../helpers/createStateSourceHook'\n\ntype UseCurrentUser = {\n /**\n * @public\n *\n * Provides the currently authenticated user’s profile information.\n *\n * @category Users\n * @returns The current user data\n *\n * @example Rendering a basic user profile\n * ```\n * const user = useCurrentUser()\n *\n * return (\n * <figure>\n * <img src={user?.profileImage} alt=`Profile image for ${user?.name}` />\n * <h2>{user?.name}</h2>\n * </figure>\n * )\n * ```\n */\n (): CurrentUser | null\n}\n\n/**\n * @public\n * @function\n * @TODO This should not return null — users of a custom app will always be authenticated via Core\n */\nexport const useCurrentUser: UseCurrentUser = createStateSourceHook(getCurrentUserState)\n","import {getDashboardOrganizationId} from '@sanity/sdk'\nimport {useMemo, useSyncExternalStore} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\n/**\n * @public\n *\n * A React hook that retrieves the dashboard organization ID that is currently selected in the Sanity Dashboard.\n *\n * @example\n * ```tsx\n * function DashboardComponent() {\n * const orgId = useDashboardOrganizationId()\n *\n * if (!orgId) return null\n *\n * return <div>Organization ID: {String(orgId)}</div>\n * }\n * ```\n *\n * @category Dashboard\n * @returns The dashboard organization ID (string | undefined)\n */\nexport function useDashboardOrganizationId(): string | undefined {\n const instance = useSanityInstance()\n const {subscribe, getCurrent} = useMemo(() => getDashboardOrganizationId(instance), [instance])\n\n return useSyncExternalStore(subscribe, getCurrent)\n}\n","import {getClientState} from '@sanity/sdk'\nimport {identity} from 'rxjs'\n\nimport {createStateSourceHook} from '../helpers/createStateSourceHook'\n\n/**\n * A React hook that provides a client that subscribes to changes in your application,\n * such as user authentication changes.\n *\n * @remarks\n * The hook uses `useSyncExternalStore` to safely subscribe to changes\n * and ensure consistency between server and client rendering.\n *\n * @category Platform\n * @returns A Sanity client\n *\n * @example\n * ```tsx\n * function MyComponent() {\n * const client = useClient({apiVersion: '2024-11-12'})\n * const [document, setDocument] = useState(null)\n * useEffect(async () => {\n * const doc = client.fetch('*[_id == \"myDocumentId\"]')\n * setDocument(doc)\n * }, [])\n * return <div>{JSON.stringify(document) ?? 'Loading...'}</div>\n * }\n * ```\n *\n * @public\n * @function\n */\nexport const useClient = createStateSourceHook({\n getState: getClientState,\n getConfig: identity,\n})\n","import {type ChannelInstance, type Controller, type Status} from '@sanity/comlink'\nimport {\n type FrameMessage,\n getOrCreateChannel,\n getOrCreateController,\n releaseChannel,\n type WindowMessage,\n} from '@sanity/sdk'\nimport {useCallback, useEffect, useRef} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\n/**\n * @internal\n */\nexport type FrameMessageHandler<TWindowMessage extends WindowMessage> = (\n event: TWindowMessage['data'],\n) => TWindowMessage['response'] | Promise<TWindowMessage['response']>\n\n/**\n * @internal\n */\nexport interface UseFrameConnectionOptions<TWindowMessage extends WindowMessage> {\n name: string\n connectTo: string\n targetOrigin: string\n onMessage?: {\n [K in TWindowMessage['type']]: (data: Extract<TWindowMessage, {type: K}>['data']) => void\n }\n heartbeat?: boolean\n onStatus?: (status: Status) => void\n}\n\n/**\n * @internal\n */\nexport interface FrameConnection<TFrameMessage extends FrameMessage> {\n connect: (frameWindow: Window) => () => void // Return cleanup function\n sendMessage: <T extends TFrameMessage['type']>(\n ...params: Extract<TFrameMessage, {type: T}>['data'] extends undefined\n ? [type: T]\n : [type: T, data: Extract<TFrameMessage, {type: T}>['data']]\n ) => void\n}\n\n/**\n * @internal\n */\nexport function useFrameConnection<\n TFrameMessage extends FrameMessage,\n TWindowMessage extends WindowMessage,\n>(options: UseFrameConnectionOptions<TWindowMessage>): FrameConnection<TFrameMessage> {\n const {onMessage, targetOrigin, name, connectTo, heartbeat, onStatus} = options\n const instance = useSanityInstance()\n const controllerRef = useRef<Controller | null>(null)\n const channelRef = useRef<ChannelInstance<TFrameMessage, TWindowMessage> | null>(null)\n\n useEffect(() => {\n const controller = getOrCreateController(instance, targetOrigin)\n const channel = getOrCreateChannel(instance, {name, connectTo, heartbeat})\n controllerRef.current = controller\n channelRef.current = channel\n\n channel.onStatus((event) => {\n onStatus?.(event.status)\n })\n\n const messageUnsubscribers: Array<() => void> = []\n\n if (onMessage) {\n Object.entries(onMessage).forEach(([type, handler]) => {\n const unsubscribe = channel.on(type, handler as FrameMessageHandler<TWindowMessage>)\n messageUnsubscribers.push(unsubscribe)\n })\n }\n\n return () => {\n // Clean up all subscriptions and stop controller/channel\n messageUnsubscribers.forEach((unsub) => unsub())\n releaseChannel(instance, name)\n channelRef.current = null\n controllerRef.current = null\n }\n }, [targetOrigin, name, connectTo, heartbeat, onMessage, instance, onStatus])\n\n const connect = useCallback((frameWindow: Window) => {\n const removeTarget = controllerRef.current?.addTarget(frameWindow)\n return () => {\n removeTarget?.()\n }\n }, [])\n\n const sendMessage = useCallback(\n <T extends TFrameMessage['type']>(\n type: T,\n data?: Extract<TFrameMessage, {type: T}>['data'],\n ) => {\n channelRef.current?.post(type, data)\n },\n [],\n )\n\n return {\n connect,\n sendMessage,\n }\n}\n","import {type MessageData, type Node, type Status} from '@sanity/comlink'\nimport {type FrameMessage, getOrCreateNode, releaseNode, type WindowMessage} from '@sanity/sdk'\nimport {useCallback, useEffect, useRef} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\n/**\n * @internal\n */\nexport type WindowMessageHandler<TFrameMessage extends FrameMessage> = (\n event: TFrameMessage['data'],\n) => TFrameMessage['response']\n\n/**\n * @internal\n */\nexport interface UseWindowConnectionOptions<TMessage extends FrameMessage> {\n name: string\n connectTo: string\n onMessage?: Record<TMessage['type'], WindowMessageHandler<TMessage>>\n onStatus?: (status: Status) => void\n}\n\n/**\n * @internal\n */\nexport interface WindowConnection<TMessage extends WindowMessage> {\n sendMessage: <TType extends TMessage['type']>(\n type: TType,\n data?: Extract<TMessage, {type: TType}>['data'],\n ) => void\n fetch: <TResponse>(\n type: string,\n data?: MessageData,\n options?: {\n signal?: AbortSignal\n suppressWarnings?: boolean\n responseTimeout?: number\n },\n ) => Promise<TResponse>\n}\n\n/**\n * @internal\n * Hook to wrap a Comlink node in a React hook.\n * Our store functionality takes care of the lifecycle of the node,\n * as well as sharing a single node between invocations if they share the same name.\n *\n * Generally not to be used directly, but to be used as a dependency of\n * Comlink-powered hooks like `useManageFavorite`.\n */\nexport function useWindowConnection<\n TWindowMessage extends WindowMessage,\n TFrameMessage extends FrameMessage,\n>({\n name,\n connectTo,\n onMessage,\n onStatus,\n}: UseWindowConnectionOptions<TFrameMessage>): WindowConnection<TWindowMessage> {\n const nodeRef = useRef<Node<TWindowMessage, TFrameMessage> | null>(null)\n const messageUnsubscribers = useRef<(() => void)[]>([])\n const instance = useSanityInstance()\n\n useEffect(() => {\n // the type cast is unfortunate, but the generic type of the node is not known here.\n // We know that the node is a WindowMessage node, but not the generic types.\n const node = getOrCreateNode(instance, {\n name,\n connectTo,\n }) as unknown as Node<TWindowMessage, TFrameMessage>\n nodeRef.current = node\n\n const statusUnsubscribe = node.onStatus((eventStatus) => {\n onStatus?.(eventStatus)\n })\n\n if (onMessage) {\n Object.entries(onMessage).forEach(([type, handler]) => {\n const messageUnsubscribe = node.on(type, handler as WindowMessageHandler<TFrameMessage>)\n messageUnsubscribers.current.push(messageUnsubscribe)\n })\n }\n\n return () => {\n statusUnsubscribe()\n messageUnsubscribers.current.forEach((unsubscribe) => unsubscribe())\n messageUnsubscribers.current = []\n releaseNode(instance, name)\n nodeRef.current = null\n }\n }, [instance, name, connectTo, onMessage, onStatus])\n\n const sendMessage = useCallback(\n (type: TWindowMessage['type'], data?: Extract<TWindowMessage, {type: typeof type}>['data']) => {\n if (!nodeRef.current) {\n throw new Error('Cannot send message before connection is established')\n }\n nodeRef.current.post(type, data)\n },\n [],\n )\n\n const fetch = useCallback(\n <TResponse>(\n type: string,\n data?: MessageData,\n fetchOptions?: {\n responseTimeout?: number\n signal?: AbortSignal\n suppressWarnings?: boolean\n },\n ): Promise<TResponse> => {\n return nodeRef.current?.fetch(type, data, fetchOptions ?? {}) as Promise<TResponse>\n },\n [],\n )\n return {\n sendMessage,\n fetch,\n }\n}\n","import {type Status} from '@sanity/comlink'\nimport {\n type CanvasResource,\n type Events,\n type MediaResource,\n SDK_CHANNEL_NAME,\n SDK_NODE_NAME,\n type StudioResource,\n} from '@sanity/message-protocol'\nimport {type DocumentHandle, type FrameMessage} from '@sanity/sdk'\nimport {useCallback, useEffect, useState} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\nimport {useWindowConnection} from './useWindowConnection'\n\n// should we import this whole type from the message protocol?\n\ninterface ManageFavorite {\n favorite: () => void\n unfavorite: () => void\n isFavorited: boolean\n isConnected: boolean\n}\n\ninterface UseManageFavoriteProps extends DocumentHandle {\n resourceId?: string\n resourceType: StudioResource['type'] | MediaResource['type'] | CanvasResource['type']\n /**\n * The name of the schema collection this document belongs to.\n * Typically is the name of the workspace when used in the context of a studio.\n */\n schemaName?: string\n}\n\n/**\n * @internal\n *\n * This hook provides functionality to add and remove documents from favorites,\n * and tracks the current favorite status of the document.\n * @param documentHandle - The document handle containing document ID and type, like `{_id: '123', _type: 'book'}`\n * @returns An object containing:\n * - `favorite` - Function to add document to favorites\n * - `unfavorite` - Function to remove document from favorites\n * - `isFavorited` - Boolean indicating if document is currently favorited\n * - `isConnected` - Boolean indicating if connection to Dashboard UI is established\n *\n * @example\n * ```tsx\n * function MyDocumentAction(props: DocumentActionProps) {\n * const {documentId, documentType} = props\n * const {favorite, unfavorite, isFavorited, isConnected} = useManageFavorite({\n * documentId,\n * documentType\n * })\n *\n * return (\n * <Button\n * disabled={!isConnected}\n * onClick={() => isFavorited ? unfavorite() : favorite()}\n * text={isFavorited ? 'Remove from favorites' : 'Add to favorites'}\n * />\n * )\n * }\n * ```\n */\nexport function useManageFavorite({\n documentId,\n documentType,\n projectId: paramProjectId,\n dataset: paramDataset,\n resourceId: paramResourceId,\n resourceType,\n schemaName,\n}: UseManageFavoriteProps): ManageFavorite {\n const [isFavorited, setIsFavorited] = useState(false) // should load this from a comlink fetch\n const [status, setStatus] = useState<Status>('idle')\n const [resourceId, setResourceId] = useState<string>(paramResourceId || '')\n const {sendMessage} = useWindowConnection<Events.FavoriteMessage, FrameMessage>({\n name: SDK_NODE_NAME,\n connectTo: SDK_CHANNEL_NAME,\n onStatus: setStatus,\n })\n const instance = useSanityInstance()\n const {config} = instance\n const instanceProjectId = config?.projectId\n const instanceDataset = config?.dataset\n const projectId = paramProjectId ?? instanceProjectId\n const dataset = paramDataset ?? instanceDataset\n\n if (resourceType === 'studio' && (!projectId || !dataset)) {\n throw new Error('projectId and dataset are required for studio resources')\n }\n\n useEffect(() => {\n // If resourceType is studio and the resourceId is not provided,\n // use the projectId and dataset to generate a resourceId\n if (resourceType === 'studio' && !paramResourceId) {\n setResourceId(`${projectId}.${dataset}`)\n } else if (paramResourceId) {\n setResourceId(paramResourceId)\n } else {\n // For other resource types, resourceId is required\n throw new Error('resourceId is required for media-library and canvas resources')\n }\n }, [resourceType, paramResourceId, projectId, dataset])\n\n const handleFavoriteAction = useCallback(\n (action: 'added' | 'removed', setFavoriteState: boolean) => {\n if (!documentId || !documentType || !resourceType) return\n\n try {\n const message: Events.FavoriteMessage = {\n type: 'dashboard/v1/events/favorite/mutate',\n data: {\n eventType: action,\n document: {\n id: documentId,\n type: documentType,\n resource: {\n id: resourceId,\n type: resourceType,\n schemaName,\n },\n },\n },\n response: {\n success: true,\n },\n }\n\n sendMessage(message.type, message.data)\n setIsFavorited(setFavoriteState)\n } catch (err) {\n const error = err instanceof Error ? err : new Error('Failed to update favorite status')\n // eslint-disable-next-line no-console\n console.error(\n `Failed to ${action === 'added' ? 'favorite' : 'unfavorite'} document:`,\n error,\n )\n throw error\n }\n },\n [documentId, documentType, resourceId, resourceType, sendMessage, schemaName],\n )\n\n const favorite = useCallback(() => handleFavoriteAction('added', true), [handleFavoriteAction])\n\n const unfavorite = useCallback(\n () => handleFavoriteAction('removed', false),\n [handleFavoriteAction],\n )\n\n return {\n favorite,\n unfavorite,\n isFavorited,\n isConnected: status === 'connected',\n }\n}\n","import {type Status} from '@sanity/comlink'\nimport {\n type CanvasResource,\n type Events,\n type MediaResource,\n SDK_CHANNEL_NAME,\n SDK_NODE_NAME,\n type StudioResource,\n} from '@sanity/message-protocol'\nimport {type DocumentHandle, type FrameMessage} from '@sanity/sdk'\nimport {useCallback, useState} from 'react'\n\nimport {useWindowConnection} from './useWindowConnection'\n\ninterface DocumentInteractionHistory {\n recordEvent: (eventType: 'viewed' | 'edited' | 'created' | 'deleted') => void\n isConnected: boolean\n}\n\n/**\n * @internal\n */\ninterface UseRecordDocumentHistoryEventProps extends DocumentHandle {\n resourceType: StudioResource['type'] | MediaResource['type'] | CanvasResource['type']\n resourceId?: string\n /**\n * The name of the schema collection this document belongs to.\n * Typically is the name of the workspace when used in the context of a studio.\n */\n schemaName?: string\n}\n\n/**\n * @internal\n * Hook for managing document interaction history in Sanity Studio.\n * This hook provides functionality to record document interactions.\n * @category History\n * @param documentHandle - The document handle containing document ID and type, like `{_id: '123', _type: 'book'}`\n * @returns An object containing:\n * - `recordEvent` - Function to record document interactions\n * - `isConnected` - Boolean indicating if connection to Studio is established\n *\n * @example\n * ```tsx\n * function MyDocumentAction(props: DocumentActionProps) {\n * const {documentId, documentType, resourceType, resourceId} = props\n * const {recordEvent, isConnected} = useRecordDocumentHistoryEvent({\n * documentId,\n * documentType,\n * resourceType,\n * resourceId,\n * })\n *\n * return (\n * <Button\n * disabled={!isConnected}\n * onClick={() => recordEvent('viewed')}\n * text={'Viewed'}\n * />\n * )\n * }\n * ```\n */\nexport function useRecordDocumentHistoryEvent({\n documentId,\n documentType,\n resourceType,\n resourceId,\n schemaName,\n}: UseRecordDocumentHistoryEventProps): DocumentInteractionHistory {\n const [status, setStatus] = useState<Status>('idle')\n const {sendMessage} = useWindowConnection<Events.HistoryMessage, FrameMessage>({\n name: SDK_NODE_NAME,\n connectTo: SDK_CHANNEL_NAME,\n onStatus: setStatus,\n })\n\n if (resourceType !== 'studio' && !resourceId) {\n throw new Error('resourceId is required for media-library and canvas resources')\n }\n\n const recordEvent = useCallback(\n (eventType: 'viewed' | 'edited' | 'created' | 'deleted') => {\n try {\n const message: Events.HistoryMessage = {\n type: 'dashboard/v1/events/history',\n data: {\n eventType,\n document: {\n id: documentId,\n type: documentType,\n resource: {\n id: resourceId!,\n type: resourceType,\n schemaName,\n },\n },\n },\n }\n\n sendMessage(message.type, message.data)\n } catch (error) {\n // eslint-disable-next-line no-console\n console.error('Failed to record history event:', error)\n throw error\n }\n },\n [documentId, documentType, resourceId, resourceType, sendMessage, schemaName],\n )\n\n return {\n recordEvent,\n isConnected: status === 'connected',\n }\n}\n","import {type Status} from '@sanity/comlink'\nimport {SDK_CHANNEL_NAME, SDK_NODE_NAME} from '@sanity/message-protocol'\nimport {useEffect, useState} from 'react'\n\nimport {useWindowConnection} from '../comlink/useWindowConnection'\n\nexport interface DashboardResource {\n id: string\n name: string\n title: string\n basePath: string\n projectId: string\n dataset: string\n type: string\n userApplicationId: string\n url: string\n}\n\ninterface WorkspacesByProjectIdDataset {\n [key: `${string}:${string}`]: DashboardResource[] // key format: `${projectId}:${dataset}`\n}\n\ninterface StudioWorkspacesResult {\n workspacesByProjectIdAndDataset: WorkspacesByProjectIdDataset\n error: string | null\n isConnected: boolean\n}\n\n/**\n * Hook that fetches studio workspaces and organizes them by projectId:dataset\n * @internal\n */\nexport function useStudioWorkspacesByProjectIdDataset(): StudioWorkspacesResult {\n const [workspacesByProjectIdAndDataset, setWorkspacesByProjectIdAndDataset] =\n useState<WorkspacesByProjectIdDataset>({})\n const [status, setStatus] = useState<Status>('idle')\n const [error, setError] = useState<string | null>(null)\n\n const {fetch} = useWindowConnection({\n name: SDK_NODE_NAME,\n connectTo: SDK_CHANNEL_NAME,\n onStatus: setStatus,\n })\n\n // Once computed, this should probably be in a store and poll for changes\n // However, our stores are currently being refactored\n useEffect(() => {\n if (!fetch || status !== 'connected') return\n\n async function fetchWorkspaces(signal: AbortSignal) {\n try {\n const data = await fetch<{\n context: {availableResources: Array<DashboardResource>}\n }>('dashboard/v1/bridge/context', undefined, {signal})\n\n const workspaceMap: WorkspacesByProjectIdDataset = {}\n const noProjectIdAndDataset: DashboardResource[] = []\n\n data.context.availableResources.forEach((resource) => {\n if (resource.type !== 'studio') return\n if (!resource.projectId || !resource.dataset) {\n noProjectIdAndDataset.push(resource)\n return\n }\n const key = `${resource.projectId}:${resource.dataset}` as const\n if (!workspaceMap[key]) {\n workspaceMap[key] = []\n }\n workspaceMap[key].push(resource)\n })\n\n if (noProjectIdAndDataset.length > 0) {\n workspaceMap['NO_PROJECT_ID:NO_DATASET'] = noProjectIdAndDataset\n }\n\n setWorkspacesByProjectIdAndDataset(workspaceMap)\n setError(null)\n } catch (err: unknown) {\n if (err instanceof Error) {\n if (err.name === 'AbortError') {\n return\n }\n setError('Failed to fetch workspaces')\n }\n }\n }\n\n const controller = new AbortController()\n fetchWorkspaces(controller.signal)\n\n return () => {\n controller.abort()\n }\n }, [fetch, status])\n\n return {\n workspacesByProjectIdAndDataset,\n error,\n isConnected: status === 'connected',\n }\n}\n","import {type Status} from '@sanity/comlink'\nimport {type Bridge, SDK_CHANNEL_NAME, SDK_NODE_NAME} from '@sanity/message-protocol'\nimport {type DocumentHandle} from '@sanity/sdk'\nimport {useCallback, useState} from 'react'\n\nimport {useWindowConnection} from '../comlink/useWindowConnection'\nimport {\n type DashboardResource,\n useStudioWorkspacesByProjectIdDataset,\n} from './useStudioWorkspacesByProjectIdDataset'\n\n/**\n * @public\n * @category Types\n */\nexport interface NavigateToStudioResult {\n navigateToStudioDocument: () => void\n isConnected: boolean\n}\n\n/**\n * @public\n *\n * Hook that provides a function to navigate to a given document in its parent Studio.\n *\n * Uses the `projectId` and `dataset` properties of the {@link DocumentHandle} you provide to resolve the correct Studio.\n * This will only work if you have deployed a studio with a workspace with this `projectId` / `dataset` combination.\n *\n * @remarks If you write your own Document Handle to pass to this hook (as opposed to a Document Handle generated by another hook),\n * it must include values for `documentId`, `documentType`, `projectId`, and `dataset`.\n *\n * @category Documents\n * @param documentHandle - The document handle for the document to navigate to\n * @param preferredStudioUrl - The preferred studio url to navigate to if you have multiple\n * studios with the same projectId and dataset\n * @returns An object containing:\n * - `navigateToStudioDocument` - Function that when called will navigate to the studio document\n * - `isConnected` - Boolean indicating if connection to Dashboard is established\n *\n * @example\n * ```ts\n * import {useNavigateToStudioDocument, type DocumentHandle} from '@sanity/sdk-react'\n *\n * function MyComponent({documentHandle}: {documentHandle: DocumentHandle}) {\n * const {navigateToStudioDocument, isConnected} = useNavigateToStudioDocument(documentHandle)\n *\n * return (\n * <button onClick={navigateToStudioDocument} disabled={!isConnected}>\n * Navigate to Studio Document\n * </button>\n * )\n * }\n * ```\n */\nexport function useNavigateToStudioDocument(\n documentHandle: DocumentHandle,\n preferredStudioUrl?: string,\n): NavigateToStudioResult {\n const {workspacesByProjectIdAndDataset, isConnected: workspacesConnected} =\n useStudioWorkspacesByProjectIdDataset()\n const [status, setStatus] = useState<Status>('idle')\n const {sendMessage} = useWindowConnection<Bridge.Navigation.NavigateToResourceMessage, never>({\n name: SDK_NODE_NAME,\n connectTo: SDK_CHANNEL_NAME,\n onStatus: setStatus,\n })\n\n const navigateToStudioDocument = useCallback(() => {\n const {projectId, dataset} = documentHandle\n\n if (!workspacesConnected || status !== 'connected') {\n // eslint-disable-next-line no-console\n console.warn('Not connected to Dashboard')\n return\n }\n\n if (!projectId || !dataset) {\n // eslint-disable-next-line no-console\n console.warn('Project ID and dataset are required to navigate to a studio document')\n return\n }\n\n let workspace: DashboardResource | undefined\n\n if (preferredStudioUrl) {\n // Get workspaces matching the projectId:dataset and any workspaces without projectId/dataset,\n // in case there hasn't been a manifest loaded yet\n const allWorkspaces = [\n ...(workspacesByProjectIdAndDataset[`${projectId}:${dataset}`] || []),\n ...(workspacesByProjectIdAndDataset['NO_PROJECT_ID:NO_DATASET'] || []),\n ]\n workspace = allWorkspaces.find((w) => w.url === preferredStudioUrl)\n } else {\n const workspaces = workspacesByProjectIdAndDataset[`${projectId}:${dataset}`]\n if (workspaces?.length > 1) {\n // eslint-disable-next-line no-console\n console.warn(\n 'Multiple workspaces found for document and no preferred studio url',\n documentHandle,\n )\n // eslint-disable-next-line no-console\n console.warn('Using the first one', workspaces[0])\n }\n\n workspace = workspaces?.[0]\n }\n\n if (!workspace) {\n // eslint-disable-next-line no-console\n console.warn(\n `No workspace found for document with projectId: ${projectId} and dataset: ${dataset}${preferredStudioUrl ? ` or with preferred studio url: ${preferredStudioUrl}` : ''}`,\n )\n return\n }\n\n const message: Bridge.Navigation.NavigateToResourceMessage = {\n type: 'dashboard/v1/bridge/navigate-to-resource',\n data: {\n resourceId: workspace.id,\n resourceType: 'studio',\n path: `/intent/edit/id=${documentHandle.documentId};type=${documentHandle.documentType}`,\n },\n }\n\n sendMessage(message.type, message.data)\n }, [\n documentHandle,\n workspacesConnected,\n status,\n workspacesByProjectIdAndDataset,\n sendMessage,\n preferredStudioUrl,\n ])\n\n return {\n navigateToStudioDocument,\n isConnected: workspacesConnected && status === 'connected',\n }\n}\n","import {type DatasetsResponse} from '@sanity/client'\nimport {\n getDatasetsState,\n type ProjectHandle,\n resolveDatasets,\n type SanityInstance,\n type StateSource,\n} from '@sanity/sdk'\n\nimport {createStateSourceHook} from '../helpers/createStateSourceHook'\n\ntype UseDatasets = {\n /**\n *\n * Returns metadata for each dataset the current user has access to.\n *\n * @category Datasets\n * @returns The metadata for your the datasets\n *\n * @example\n * ```tsx\n * const datasets = useDatasets()\n *\n * return (\n * <select>\n * {datasets.map((dataset) => (\n * <option key={dataset.name}>{dataset.name}</option>\n * ))}\n * </select>\n * )\n * ```\n *\n */\n (): DatasetsResponse\n}\n\n/**\n * @public\n * @function\n */\nexport const useDatasets: UseDatasets = createStateSourceHook({\n getState: getDatasetsState as (\n instance: SanityInstance,\n projectHandle?: ProjectHandle,\n ) => StateSource<DatasetsResponse>,\n shouldSuspend: (instance, projectHandle?: ProjectHandle) =>\n // remove `undefined` since we're suspending when that is the case\n getDatasetsState(instance, projectHandle).getCurrent() === undefined,\n suspender: resolveDatasets,\n getConfig: (projectHandle?: ProjectHandle) => projectHandle,\n})\n","import {applyDocumentActions} from '@sanity/sdk'\n\nimport {createCallbackHook} from '../helpers/createCallbackHook'\n\n/**\n *\n * @beta\n *\n * Provides a callback for applying one or more actions to a document.\n *\n * @category Documents\n * @param dataset - An optional dataset handle with projectId and dataset. If not provided, the nearest SanityInstance from context will be used.\n * @returns A function that takes one more more {@link DocumentAction}s and returns a promise that resolves to an {@link ActionsResult}.\n * @example Publish or unpublish a document\n * ```\n * import { publishDocument, unpublishDocument } from '@sanity/sdk'\n * import { useApplyDocumentActions } from '@sanity/sdk-react'\n *\n * const apply = useApplyDocumentActions()\n * const myDocument = { documentId: 'my-document-id', documentType: 'my-document-type' }\n *\n * return (\n * <button onClick={() => apply(publishDocument(myDocument))}>Publish</button>\n * <button onClick={() => apply(unpublishDocument(myDocument))}>Unpublish</button>\n * )\n * ```\n *\n * @example Create and publish a new document\n * ```\n * import { createDocument, publishDocument } from '@sanity/sdk'\n * import { useApplyDocumentActions } from '@sanity/sdk-react'\n *\n * const apply = useApplyDocumentActions()\n *\n * const handleCreateAndPublish = () => {\n * const handle = { documentId: window.crypto.randomUUID(), documentType: 'my-document-type' }\n * apply([\n * createDocument(handle),\n * publishDocument(handle),\n * ])\n * }\n *\n * return (\n * <button onClick={handleCreateAndPublish}>\n * I'm feeling lucky\n * </button>\n * )\n * ```\n */\nexport const useApplyDocumentActions = createCallbackHook(applyDocumentActions)\n","import {\n type DocumentHandle,\n getDocumentState,\n type JsonMatch,\n type JsonMatchPath,\n resolveDocument,\n} from '@sanity/sdk'\nimport {type SanityDocument} from '@sanity/types'\nimport {identity} from 'rxjs'\n\nimport {createStateSourceHook} from '../helpers/createStateSourceHook'\n\n/**\n * @beta\n *\n * ## useDocument(doc, path)\n * Read and subscribe to nested values in a document\n * @category Documents\n * @param doc - The document to read state from, specified as a DocumentHandle\n * @param path - The path to the nested value to read from\n * @returns The value at the specified path\n * @example\n * ```tsx\n * import {useDocument} from '@sanity/sdk-react'\n *\n * const documentHandle = {\n * documentId: 'order-123',\n * documentType: 'order',\n * projectId: 'abc123',\n * dataset: 'production'\n * }\n *\n * function OrderLink() {\n * const title = useDocument(documentHandle, 'title')\n * const id = useDocument(documentHandle, '_id')\n *\n * return (\n * <a href={`/order/${id}`}>Order {title} today!</a>\n * )\n * }\n * ```\n *\n */\nexport function useDocument<\n TDocument extends SanityDocument,\n TPath extends JsonMatchPath<TDocument>,\n>(doc: DocumentHandle<TDocument>, path: TPath): JsonMatch<TDocument, TPath> | undefined\n\n/**\n * @beta\n * ## useDocument(doc)\n * Read and subscribe to an entire document\n * @param doc - The document to read state from, specified as a DocumentHandle\n * @returns The document state as an object\n * @example\n * ```tsx\n * import {type SanityDocument, useDocument} from '@sanity/sdk-react'\n *\n * interface Book extends SanityDocument {\n * title: string\n * author: string\n * summary: string\n * }\n *\n * const documentHandle = {\n * documentId: 'book-123',\n * documentType: 'book',\n * projectId: 'abc123',\n * dataset: 'production'\n * }\n *\n * function DocumentView() {\n * const book = useDocument<Book>(documentHandle)\n *\n * if (!book) {\n * return <div>Loading...</div>\n * }\n *\n * return (\n * <article>\n * <h1>{book.title}</h1>\n * <address>By {book.author}</address>\n *\n * <h2>Summary</h2>\n * {book.summary}\n *\n * <h2>Order</h2>\n * <a href={`/order/${book._id}`}>Order {book.title} today!</a>\n * </article>\n * )\n * }\n * ```\n *\n */\nexport function useDocument<TDocument extends SanityDocument>(\n doc: DocumentHandle<TDocument>,\n): TDocument | null\n\n/**\n * @beta\n * Reads and subscribes to a document's realtime state, incorporating both local and remote changes.\n * When called with a `path` argument, the hook will return the nested value's state.\n * When called without a `path` argument, the entire document's state will be returned.\n *\n * @remarks\n * `useDocument` is designed to be used within a realtime context in which local updates to documents\n * need to be displayed before they are persisted to the remote copy. This can be useful within a collaborative\n * or realtime editing interface where local changes need to be reflected immediately.\n *\n * The hook automatically uses the correct Sanity instance based on the project and dataset\n * specified in the DocumentHandle. This makes it easy to work with documents from different\n * projects or datasets in the same component.\n *\n * However, this hook can be too resource intensive for applications where static document values simply\n * need to be displayed (or when changes to documents don't need to be reflected immediately);\n * consider using `usePreview` or `useQuery` for these use cases instead. These hooks leverage the Sanity\n * Live Content API to provide a more efficient way to read and subscribe to document state.\n */\nexport function useDocument(doc: DocumentHandle, path?: string): unknown {\n return _useDocument(doc, path)\n}\n\nconst _useDocument = createStateSourceHook<[doc: DocumentHandle, path?: string], unknown>({\n getState: getDocumentState,\n shouldSuspend: (instance, doc) => getDocumentState(instance, doc).getCurrent() === undefined,\n suspender: resolveDocument,\n getConfig: identity,\n})\n","import {type DatasetHandle, type DocumentEvent, subscribeDocumentEvents} from '@sanity/sdk'\nimport {useCallback, useEffect, useInsertionEffect, useRef} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\n/**\n *\n * @beta\n *\n * Subscribes an event handler to events in your application's document store, such as document\n * creation, deletion, and updates.\n *\n * @category Documents\n * @param handler - The event handler to register.\n * @param doc - The document to subscribe to events for. If you pass a `DocumentHandle` with specified `projectId` and `dataset`,\n * the document will be read from the specified Sanity project and dataset that is included in the handle. If no `projectId` or `dataset` is provided,\n * the document will use the nearest instance from context.\n * @example\n * ```\n * import {useDocumentEvent} from '@sanity/sdk-react'\n * import {type DocumentEvent} from '@sanity/sdk'\n *\n * useDocumentEvent((event) => {\n * if (event.type === DocumentEvent.DocumentDeletedEvent) {\n * alert(`Document with ID ${event.documentId} deleted!`)\n * } else {\n * console.log(event)\n * }\n * })\n * ```\n */\nexport function useDocumentEvent(\n handler: (documentEvent: DocumentEvent) => void,\n dataset: DatasetHandle,\n): void {\n const ref = useRef(handler)\n\n useInsertionEffect(() => {\n ref.current = handler\n })\n\n const stableHandler = useCallback((documentEvent: DocumentEvent) => {\n return ref.current(documentEvent)\n }, [])\n\n const instance = useSanityInstance(dataset)\n useEffect(() => {\n return subscribeDocumentEvents(instance, stableHandler)\n }, [instance, stableHandler])\n}\n","import {type DocumentAction, type DocumentPermissionsResult, getPermissionsState} from '@sanity/sdk'\nimport {useCallback, useMemo, useSyncExternalStore} from 'react'\nimport {filter, firstValueFrom} from 'rxjs'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\n/**\n *\n * @beta\n *\n * Check if the current user has the specified permissions for the given document actions.\n *\n * @category Permissions\n * @param actionOrActions - One more more calls to a particular document action function for a given document\n * @returns An object that specifies whether the action is allowed; if the action is not allowed, an explanatory message and list of reasons is also provided.\n *\n * @example Checking for permission to publish a document\n * ```ts\n * import {useDocumentPermissions, useApplyDocumentActions} from '@sanity/sdk-react'\n * import {publishDocument} from '@sanity/sdk'\n *\n * export function PublishButton({doc}: {doc: DocumentHandle}) {\n * const publishPermissions = useDocumentPermissions(publishDocument(doc))\n * const applyAction = useApplyDocumentActions()\n *\n * return (\n * <>\n * <button\n * disabled={!publishPermissions.allowed}\n * onClick={() => applyAction(publishDocument(doc))}\n * popoverTarget={`${publishPermissions.allowed ? undefined : 'publishButtonPopover'}`}\n * >\n * Publish\n * </button>\n * {!publishPermissions.allowed && (\n * <div popover id=\"publishButtonPopover\">\n * {publishPermissions.message}\n * </div>\n * )}\n * </>\n * )\n * }\n * ```\n */\nexport function useDocumentPermissions(\n actionOrActions: DocumentAction | DocumentAction[],\n): DocumentPermissionsResult {\n const actions = Array.isArray(actionOrActions) ? actionOrActions : [actionOrActions]\n // if actions is an array, we need to check that all actions belong to the same project and dataset\n let projectId\n let dataset\n\n for (const action of actions) {\n if (action.projectId) {\n if (!projectId) projectId = action.projectId\n if (action.projectId !== projectId) {\n throw new Error(\n `Mismatched project IDs found in actions. All actions must belong to the same project. Found \"${action.projectId}\" but expected \"${projectId}\".`,\n )\n }\n\n if (action.dataset) {\n if (!dataset) dataset = action.dataset\n if (action.dataset !== dataset) {\n throw new Error(\n `Mismatched datasets found in actions. All actions must belong to the same dataset. Found \"${action.dataset}\" but expected \"${dataset}\".`,\n )\n }\n }\n }\n }\n\n const instance = useSanityInstance({projectId, dataset})\n const isDocumentReady = useCallback(\n () => getPermissionsState(instance, actionOrActions).getCurrent() !== undefined,\n [actionOrActions, instance],\n )\n if (!isDocumentReady()) {\n throw firstValueFrom(\n getPermissionsState(instance, actionOrActions).observable.pipe(\n filter((result) => result !== undefined),\n ),\n )\n }\n\n const {subscribe, getCurrent} = useMemo(\n () => getPermissionsState(instance, actionOrActions),\n [actionOrActions, instance],\n )\n\n return useSyncExternalStore(subscribe, getCurrent) as DocumentPermissionsResult\n}\n","import {type DocumentHandle, getDocumentSyncStatus} from '@sanity/sdk'\n\nimport {createStateSourceHook} from '../helpers/createStateSourceHook'\n\ntype UseDocumentSyncStatus = {\n /**\n * Exposes the document's sync status between local and remote document states.\n *\n * @category Documents\n * @param doc - The document handle to get sync status for. If you pass a `DocumentHandle` with specified `projectId` and `dataset`,\n * the document will be read from the specified Sanity project and dataset that is included in the handle. If no `projectId` or `dataset` is provided,\n * the document will use the nearest instance from context.\n * @returns `true` if local changes are synced with remote, `false` if the changes are not synced, and `undefined` if the document is not found\n * @example Disable a Save button when there are no changes to sync\n * ```\n * const myDocumentHandle = { documentId: 'documentId', documentType: 'documentType', projectId: 'projectId', dataset: 'dataset' }\n * const documentSynced = useDocumentSyncStatus(myDocumentHandle)\n *\n * return (\n * <button disabled={documentSynced}>\n * Save Changes\n * </button>\n * )\n * ```\n */\n (doc: DocumentHandle): boolean | undefined\n}\n\n/**\n * @beta\n * @function\n */\nexport const useDocumentSyncStatus: UseDocumentSyncStatus =\n createStateSourceHook(getDocumentSyncStatus)\n","import {\n type ActionsResult,\n type DocumentHandle,\n editDocument,\n getDocumentState,\n type JsonMatch,\n type JsonMatchPath,\n resolveDocument,\n} from '@sanity/sdk'\nimport {type SanityDocument} from '@sanity/types'\nimport {useCallback} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\nimport {useApplyDocumentActions} from './useApplyDocumentActions'\n\nconst ignoredKeys = ['_id', '_type', '_createdAt', '_updatedAt', '_rev']\n\ntype Updater<TValue> = TValue | ((nextValue: TValue) => TValue)\n\n/**\n *\n * @beta\n *\n * ## useEditDocument(doc, path)\n * Edit a nested value within a document\n *\n * @category Documents\n * @param docHandle - The document to be edited, specified as a DocumentHandle\n * @param path - The path to the nested value to be edited\n * @returns A function to update the nested value. Accepts either a new value, or an updater function that exposes the previous value and returns a new value.\n * @example Update a document's name by providing the new value directly\n * ```tsx\n * const handle = {\n * documentId: 'movie-123',\n * documentType: 'movie',\n * projectId: 'abc123',\n * dataset: 'production'\n * }\n *\n * const name = useDocument(handle, 'name')\n * const editName = useEditDocument(handle, 'name')\n *\n * function handleNameChange(event: React.ChangeEvent<HTMLInputElement>) {\n * editName(event.target.value)\n * }\n *\n * return (\n * <input type='text' value={name} onChange={handleNameChange} />\n * )\n * ```\n *\n * @example Update a count on a document by providing an updater function\n * ```tsx\n * const handle = {\n * documentId: 'counter-123',\n * documentType: 'counter',\n * projectId: 'abc123',\n * dataset: 'production'\n * }\n *\n * const count = useDocument(handle, 'count')\n * const editCount = useEditDocument(handle, 'count')\n *\n * function incrementCount() {\n * editCount(previousCount => previousCount + 1)\n * }\n *\n * return (\n * <>\n * <button onClick={incrementCount}>\n * Increment\n * </button>\n * Current count: {count}\n * </>\n * )\n * ```\n */\nexport function useEditDocument<\n TDocument extends SanityDocument,\n TPath extends JsonMatchPath<TDocument>,\n>(\n docHandle: DocumentHandle<TDocument>,\n path: TPath,\n): (nextValue: Updater<JsonMatch<TDocument, TPath>>) => Promise<ActionsResult<TDocument>>\n\n/**\n *\n * @beta\n *\n * ## useEditDocument(doc)\n * Edit an entire document\n * @param docHandle - The document to be edited, specified as a DocumentHandle.\n * The hook will automatically use the Sanity instance that matches the project and dataset specified in the handle.\n * @returns A function to update the document state. Accepts either a new document state, or an updater function that exposes the previous document state and returns the new document state.\n * @example\n * ```tsx\n * const myDocumentHandle = {\n * documentId: 'product-123',\n * documentType: 'product',\n * projectId: 'abc123',\n * dataset: 'production'\n * }\n *\n * const myDocument = useDocument(myDocumentHandle)\n * const { title, price } = myDocument ?? {}\n *\n * const editMyDocument = useEditDocument(myDocumentHandle)\n *\n * function handleFieldChange(e: React.ChangeEvent<HTMLInputElement>) {\n * const {name, value} = e.currentTarget\n * // Use an updater function to update the document state based on the previous state\n * editMyDocument(previousDocument => ({\n * ...previousDocument,\n * [name]: value\n * }))\n * }\n *\n * function handleSaleChange(e: React.ChangeEvent<HTMLInputElement>) {\n * const { checked } = e.currentTarget\n * if (checked) {\n * // Use an updater function to add a new salePrice field;\n * // set it at a 20% discount off the normal price\n * editMyDocument(previousDocument => ({\n * ...previousDocument,\n * salePrice: previousDocument.price * 0.8,\n * }))\n * } else {\n * // Get the document state without the salePrice field\n * const { salePrice, ...rest } = myDocument\n * // Update the document state to remove the salePrice field\n * editMyDocument(rest)\n * }\n * }\n *\n * return (\n * <>\n * <form onSubmit={e => e.preventDefault()}>\n * <input name='title' type='text' value={title} onChange={handleFieldChange} />\n * <input name='price' type='number' value={price} onChange={handleFieldChange} />\n * <input\n * name='salePrice'\n * type='checkbox'\n * checked={myDocument && 'salePrice' in myDocument}\n * onChange={handleSaleChange}\n * />\n * </form>\n * <pre><code>\n * {JSON.stringify(myDocument, null, 2)}\n * </code></pre>\n * </>\n * )\n * ```\n */\nexport function useEditDocument<TDocument extends SanityDocument>(\n docHandle: DocumentHandle<TDocument>,\n): (nextValue: Updater<TDocument>) => Promise<ActionsResult<TDocument>>\n\n/**\n *\n * @beta\n *\n * Enables editing of a document’s state.\n * When called with a `path` argument, the hook will return a function for updating a nested value.\n * When called without a `path` argument, the hook will return a function for updating the entire document.\n */\nexport function useEditDocument(\n docHandle: DocumentHandle,\n path?: string,\n): (updater: Updater<unknown>) => Promise<ActionsResult> {\n const instance = useSanityInstance(docHandle)\n const apply = useApplyDocumentActions()\n const isDocumentReady = useCallback(\n () => getDocumentState(instance, docHandle).getCurrent() !== undefined,\n [instance, docHandle],\n )\n if (!isDocumentReady()) throw resolveDocument(instance, docHandle)\n\n return (updater: Updater<unknown>) => {\n if (path) {\n const nextValue =\n typeof updater === 'function'\n ? updater(getDocumentState(instance, docHandle, path).getCurrent())\n : updater\n\n return apply(editDocument(docHandle, {set: {[path]: nextValue}}))\n }\n\n const current = getDocumentState(instance, docHandle).getCurrent() as object | null | undefined\n const nextValue = typeof updater === 'function' ? updater(current) : updater\n\n if (typeof nextValue !== 'object' || !nextValue) {\n throw new Error(\n `No path was provided to \\`useEditDocument\\` and the value provided was not a document object.`,\n )\n }\n\n const allKeys = Object.keys({...current, ...nextValue})\n const editActions = allKeys\n .filter((key) => !ignoredKeys.includes(key))\n .filter((key) => current?.[key as keyof typeof current] !== nextValue[key])\n .map((key) =>\n key in nextValue\n ? editDocument(docHandle, {set: {[key]: nextValue[key]}})\n : editDocument(docHandle, {unset: [key]}),\n )\n\n return apply(editActions)\n }\n}\n","import {\n getQueryKey,\n getQueryState,\n parseQueryKey,\n type QueryOptions,\n resolveQuery,\n} from '@sanity/sdk'\nimport {useEffect, useMemo, useRef, useState, useSyncExternalStore, useTransition} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\n/**\n * Executes GROQ queries against a Sanity dataset.\n *\n * This hook provides a convenient way to fetch and subscribe to real-time updates\n * for your Sanity content. Changes made to the dataset's content will trigger\n * automatic updates.\n *\n * @remarks\n * The returned `isPending` flag indicates when a React transition is in progress,\n * which can be used to show loading states for query changes.\n *\n * @beta\n * @category GROQ\n * @param query - GROQ query string to execute\n * @param options - Optional configuration for the query, including projectId and dataset\n * @returns Object containing the query result and a pending state flag\n *\n * @example Basic usage\n * ```tsx\n * const {data, isPending} = useQuery<Movie[]>('*[_type == \"movie\"]')\n * ```\n *\n * @example Using parameters\n * ```tsx\n * // With parameters\n * const {data} = useQuery<Movie>('*[_type == \"movie\" && _id == $id][0]', {\n * params: { id: 'movie-123' }\n * })\n * ```\n *\n * @example Query from a specific project/dataset\n * ```tsx\n * // Specify which project and dataset to query\n * const {data} = useQuery<Movie[]>('*[_type == \"movie\"]', {\n * projectId: 'abc123',\n * dataset: 'production'\n * })\n * ```\n *\n * @example With a loading state for transitions\n * ```tsx\n * const {data, isPending} = useQuery<Movie[]>('*[_type == \"movie\"]')\n * return (\n * <div>\n * {isPending && <div>Updating...</div>}\n * <ul>\n * {data.map(movie => <li key={movie._id}>{movie.title}</li>)}\n * </ul>\n * </div>\n * )\n * ```\n *\n */\nexport function useQuery<T>(query: string, options?: QueryOptions): {data: T; isPending: boolean} {\n const instance = useSanityInstance(options)\n\n // Use React's useTransition to avoid UI jank when queries change\n const [isPending, startTransition] = useTransition()\n\n // Get the unique key for this query and its options\n const queryKey = getQueryKey(query, options)\n // Use a deferred state to avoid immediate re-renders when the query changes\n const [deferredQueryKey, setDeferredQueryKey] = useState(queryKey)\n // Parse the deferred query key back into a query and options\n const deferred = useMemo(() => parseQueryKey(deferredQueryKey), [deferredQueryKey])\n\n // Create an AbortController to cancel in-flight requests when needed\n const ref = useRef<AbortController>(new AbortController())\n\n // When the query or options change, start a transition to update the query\n useEffect(() => {\n if (queryKey === deferredQueryKey) return\n\n startTransition(() => {\n // Abort any in-flight requests for the previous query\n if (ref && !ref.current.signal.aborted) {\n ref.current.abort()\n ref.current = new AbortController()\n }\n\n setDeferredQueryKey(queryKey)\n })\n }, [deferredQueryKey, queryKey])\n\n // Get the state source for this query from the query store\n const {getCurrent, subscribe} = useMemo(\n () => getQueryState(instance, deferred.query, deferred.options),\n [instance, deferred],\n )\n\n // If data isn't available yet, suspend rendering\n if (getCurrent() === undefined) {\n // Normally, reading from a mutable ref during render can be risky in concurrent mode.\n // However, it is safe here because:\n // 1. React guarantees that while the component is suspended (via throwing a promise),\n // no effects or state updates occur during that render pass.\n // 2. We immediately capture the current abort signal in a local variable (currentSignal).\n // 3. Even if a background render updates ref.current (for example, due to a query change),\n // the captured signal remains unchanged for this suspended render.\n // Thus, the promise thrown here uses a stable abort signal, ensuring correct behavior.\n const currentSignal = ref.current.signal\n // eslint-disable-next-line react-compiler/react-compiler\n throw resolveQuery(instance, deferred.query, {...deferred.options, signal: currentSignal})\n }\n\n // Subscribe to updates and get the current data\n // useSyncExternalStore ensures the component re-renders when the data changes\n const data = useSyncExternalStore(subscribe, getCurrent) as T\n return useMemo(() => ({data, isPending}), [data, isPending])\n}\n","import {createGroqSearchFilter, type DocumentHandle, type QueryOptions} from '@sanity/sdk'\nimport {type SortOrderingItem} from '@sanity/types'\nimport {pick} from 'lodash-es'\nimport {useCallback, useEffect, useMemo, useState} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\nimport {useQuery} from '../query/useQuery'\n\nconst DEFAULT_BATCH_SIZE = 25\nconst DEFAULT_PERSPECTIVE = 'drafts'\n\n/**\n * Result structure returned from the infinite list query\n * @internal\n */\ninterface UseDocumentsQueryResult {\n count: number\n data: DocumentHandle[]\n}\n\n/**\n * Configuration options for the useDocuments hook\n *\n * @beta\n * @category Types\n */\nexport interface DocumentsOptions extends QueryOptions {\n /**\n * GROQ filter expression to apply to the query\n */\n filter?: string\n /**\n * Number of items to load per batch (defaults to 25)\n */\n batchSize?: number\n /**\n * Sorting configuration for the results\n */\n orderings?: SortOrderingItem[]\n /**\n * Text search query to filter results\n */\n search?: string\n}\n\n/**\n * Return value from the useDocuments hook\n *\n * @beta\n * @category Types\n */\nexport interface DocumentsResponse {\n /**\n * Array of document handles for the current batch\n */\n data: DocumentHandle[]\n /**\n * Whether there are more items available to load\n */\n hasMore: boolean\n /**\n * Total count of items matching the query\n */\n count: number\n /**\n * Whether a query is currently in progress\n */\n isPending: boolean\n /**\n * Function to load the next batch of results\n */\n loadMore: () => void\n}\n\n/**\n * Retrieves batches of {@link DocumentHandle}s, narrowed by optional filters, text searches, and custom ordering,\n * with infinite scrolling support. The number of document handles returned per batch is customizable,\n * and additional batches can be loaded using the supplied `loadMore` function.\n *\n * @beta\n * @category Documents\n * @param options - Configuration options for the infinite list\n * @returns An object containing the list of document handles, the loading state, the total count of retrieved document handles, and a function to load more\n *\n * @remarks\n * - The returned document handles include projectId and dataset information from the current Sanity instance\n * - This makes them ready to use with document operations and other document hooks\n * - The hook automatically uses the correct Sanity instance based on the projectId and dataset in the options\n *\n * @example Basic infinite list with loading more\n * ```tsx\n * const { data, hasMore, isPending, loadMore, count } = useDocuments({\n * filter: '_type == \"post\"',\n * search: searchTerm,\n * batchSize: 10,\n * orderings: [{field: '_createdAt', direction: 'desc'}]\n * })\n *\n * return (\n * <div>\n * Total documents: {count}\n * <ol>\n * {data.map((doc) => (\n * <li key={doc.documentId}>\n * <MyDocumentComponent doc={doc} />\n * </li>\n * ))}\n * </ol>\n * {hasMore && <button onClick={loadMore} disabled={isPending}>\n * {isPending ? 'Loading...' : 'Load More'}\n * </button>}\n * </div>\n * )\n * ```\n */\nexport function useDocuments({\n batchSize = DEFAULT_BATCH_SIZE,\n params,\n search,\n filter,\n orderings,\n ...options\n}: DocumentsOptions): DocumentsResponse {\n const instance = useSanityInstance(options)\n const perspective = options.perspective ?? DEFAULT_PERSPECTIVE\n const [limit, setLimit] = useState(batchSize)\n\n // Reset the limit to the current batchSize whenever any query parameters\n // (filter, search, params, orderings) or batchSize changes\n const key = JSON.stringify({filter, search, params, orderings, batchSize})\n useEffect(() => {\n setLimit(batchSize)\n }, [key, batchSize])\n\n const filterClause = useMemo(() => {\n const conditions: string[] = []\n const trimmedSearch = search?.trim()\n\n // Add search query filter if specified\n if (trimmedSearch) {\n const searchFilter = createGroqSearchFilter(trimmedSearch)\n if (searchFilter) {\n conditions.push(searchFilter)\n }\n }\n\n // Add additional filter if specified\n if (filter) {\n conditions.push(`(${filter})`)\n }\n\n return conditions.length ? `[${conditions.join(' && ')}]` : ''\n }, [filter, search])\n\n const orderClause = orderings\n ? `| order(${orderings\n .map((ordering) =>\n [ordering.field, ordering.direction.toLowerCase()]\n .map((str) => str.trim())\n .filter(Boolean)\n .join(' '),\n )\n .join(',')})`\n : ''\n\n const dataQuery = `*${filterClause}${orderClause}[0...${limit}]{\"documentId\":_id,\"documentType\":_type,...$__dataset}`\n const countQuery = `count(*${filterClause})`\n\n const {\n data: {count, data},\n isPending,\n } = useQuery<UseDocumentsQueryResult>(`{\"count\":${countQuery},\"data\":${dataQuery}}`, {\n ...options,\n params: {\n ...params,\n __dataset: pick(instance.config, 'projectId', 'dataset'),\n },\n perspective,\n })\n\n const hasMore = data.length < count\n\n const loadMore = useCallback(() => {\n setLimit((prev) => Math.min(prev + batchSize, count))\n }, [count, batchSize])\n\n return useMemo(\n () => ({data, hasMore, count, isPending, loadMore}),\n [data, hasMore, count, isPending, loadMore],\n )\n}\n","import {createGroqSearchFilter, type DocumentHandle, type QueryOptions} from '@sanity/sdk'\nimport {type SortOrderingItem} from '@sanity/types'\nimport {pick} from 'lodash-es'\nimport {useCallback, useEffect, useMemo, useState} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\nimport {useQuery} from '../query/useQuery'\n\nconst DEFAULT_PERSPECTIVE = 'drafts'\n\n/**\n * Configuration options for the usePaginatedDocuments hook\n *\n * @beta\n * @category Types\n */\nexport interface PaginatedDocumentsOptions extends QueryOptions {\n /**\n * GROQ filter expression to apply to the query\n */\n filter?: string\n /**\n * Number of items to display per page (defaults to 25)\n */\n pageSize?: number\n /**\n * Sorting configuration for the results\n */\n orderings?: SortOrderingItem[]\n /**\n * Text search query to filter results\n */\n search?: string\n}\n\n/**\n * Return value from the usePaginatedDocuments hook\n *\n * @beta\n * @category Types\n */\nexport interface PaginatedDocumentsResponse {\n /**\n * Array of document handles for the current page\n */\n data: DocumentHandle[]\n /**\n * Whether a query is currently in progress\n */\n isPending: boolean\n\n /**\n * Number of items displayed per page\n */\n pageSize: number\n /**\n * Current page number (1-indexed)\n */\n currentPage: number\n /**\n * Total number of pages available\n */\n totalPages: number\n\n /**\n * Starting index of the current page (0-indexed)\n */\n startIndex: number\n /**\n * Ending index of the current page (exclusive, 0-indexed)\n */\n endIndex: number\n /**\n * Total count of items matching the query\n */\n count: number\n\n /**\n * Navigate to the first page\n */\n firstPage: () => void\n /**\n * Whether there is a first page available to navigate to\n */\n hasFirstPage: boolean\n\n /**\n * Navigate to the previous page\n */\n previousPage: () => void\n /**\n * Whether there is a previous page available to navigate to\n */\n hasPreviousPage: boolean\n\n /**\n * Navigate to the next page\n */\n nextPage: () => void\n /**\n * Whether there is a next page available to navigate to\n */\n hasNextPage: boolean\n\n /**\n * Navigate to the last page\n */\n lastPage: () => void\n /**\n * Whether there is a last page available to navigate to\n */\n hasLastPage: boolean\n\n /**\n * Navigate to a specific page number\n * @param pageNumber - The page number to navigate to (1-indexed)\n */\n goToPage: (pageNumber: number) => void\n}\n\n/**\n * Retrieves pages of {@link DocumentHandle}s, narrowed by optional filters, text searches, and custom ordering,\n * with support for traditional paginated interfaces. The number of document handles returned per page is customizable,\n * while page navigation is handled via the included navigation functions.\n *\n * @beta\n * @category Documents\n * @param options - Configuration options for the paginated list\n * @returns An object containing the current page of document handles, the loading and pagination state, and navigation functions\n *\n * @remarks\n * - The returned document handles include projectId and dataset information from the current Sanity instance\n * - This makes them ready to use with document operations and other document hooks\n * - The hook automatically uses the correct Sanity instance based on the projectId and dataset in the options\n *\n * @example Basic usage\n * ```tsx\n * const {\n * data,\n * isPending,\n * currentPage,\n * totalPages,\n * nextPage,\n * previousPage,\n * hasNextPage,\n * hasPreviousPage\n * } = usePaginatedDocuments({\n * filter: '_type == \"post\"',\n * search: searchTerm,\n * pageSize: 10,\n * orderings: [{field: '_createdAt', direction: 'desc'}]\n * })\n *\n * return (\n * <>\n * <table>\n * {data.map(doc => (\n * <MyTableRowComponent key={doc.documentId} doc={doc} />\n * ))}\n * </table>\n * {hasPreviousPage && <button onClick={previousPage}>Previous</button>}\n * {currentPage} / {totalPages}\n * {hasNextPage && <button onClick={nextPage}>Next</button>}\n * </>\n * )\n * ```\n *\n */\nexport function usePaginatedDocuments({\n filter = '',\n pageSize = 25,\n params = {},\n orderings,\n search,\n ...options\n}: PaginatedDocumentsOptions): PaginatedDocumentsResponse {\n const instance = useSanityInstance(options)\n const [pageIndex, setPageIndex] = useState(0)\n const key = JSON.stringify({filter, search, params, orderings, pageSize})\n // Reset the pageIndex to 0 whenever any query parameters (filter, search,\n // params, orderings) or pageSize changes\n useEffect(() => {\n setPageIndex(0)\n }, [key])\n\n const startIndex = pageIndex * pageSize\n const endIndex = (pageIndex + 1) * pageSize\n const perspective = options.perspective ?? DEFAULT_PERSPECTIVE\n\n const filterClause = useMemo(() => {\n const conditions: string[] = []\n const trimmedSearch = search?.trim()\n\n // Add search query filter if specified\n if (trimmedSearch) {\n const searchFilter = createGroqSearchFilter(trimmedSearch)\n if (searchFilter) {\n conditions.push(searchFilter)\n }\n }\n\n // Add additional filter if specified\n if (filter) {\n conditions.push(`(${filter})`)\n }\n\n return conditions.length ? `[${conditions.join(' && ')}]` : ''\n }, [filter, search])\n\n const orderClause = orderings\n ? `| order(${orderings\n .map((ordering) =>\n [ordering.field, ordering.direction.toLowerCase()]\n .map((str) => str.trim())\n .filter(Boolean)\n .join(' '),\n )\n .join(',')})`\n : ''\n\n const dataQuery = `*${filterClause}${orderClause}[${startIndex}...${endIndex}]{\"documentId\":_id,\"documentType\":_type,...$__dataset}`\n const countQuery = `count(*${filterClause})`\n\n const {\n data: {data, count},\n isPending,\n } = useQuery<{data: DocumentHandle[]; count: number}>(\n `{\"data\":${dataQuery},\"count\":${countQuery}}`,\n {\n ...options,\n perspective,\n params: {...params, __dataset: pick(instance.config, 'projectId', 'dataset')},\n },\n )\n\n const totalPages = Math.ceil(count / pageSize)\n const currentPage = pageIndex + 1\n\n // Navigation methods\n const firstPage = useCallback(() => setPageIndex(0), [])\n const previousPage = useCallback(() => setPageIndex((prev) => Math.max(prev - 1, 0)), [])\n const nextPage = useCallback(\n () => setPageIndex((prev) => Math.min(prev + 1, totalPages - 1)),\n [totalPages],\n )\n const lastPage = useCallback(() => setPageIndex(totalPages - 1), [totalPages])\n const goToPage = useCallback(\n (pageNumber: number) => {\n if (pageNumber < 1 || pageNumber > totalPages) return\n setPageIndex(pageNumber - 1)\n },\n [totalPages],\n )\n\n // Boolean flags for page availability\n const hasFirstPage = pageIndex > 0\n const hasPreviousPage = pageIndex > 0\n const hasNextPage = pageIndex < totalPages - 1\n const hasLastPage = pageIndex < totalPages - 1\n\n return {\n data,\n isPending,\n pageSize,\n currentPage,\n totalPages,\n startIndex,\n endIndex,\n count,\n firstPage,\n hasFirstPage,\n previousPage,\n hasPreviousPage,\n nextPage,\n hasNextPage,\n lastPage,\n hasLastPage,\n goToPage,\n }\n}\n","import {type DocumentHandle, getPreviewState, type PreviewValue, resolvePreview} from '@sanity/sdk'\nimport {useCallback, useSyncExternalStore} from 'react'\nimport {distinctUntilChanged, EMPTY, Observable, startWith, switchMap} from 'rxjs'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\n/**\n * @beta\n * @category Types\n */\nexport interface UsePreviewOptions extends DocumentHandle {\n /**\n * Optional ref object to track visibility. When provided, preview resolution\n * only occurs when the referenced element is visible in the viewport.\n */\n ref?: React.RefObject<unknown>\n}\n\n/**\n * @beta\n * @category Types\n */\nexport interface UsePreviewResults {\n /** The results of resolving the document’s preview values */\n data: PreviewValue\n /** True when preview values are being refreshed */\n isPending: boolean\n}\n\n/**\n * @beta\n *\n * Returns the preview values of a document (specified via a `DocumentHandle`),\n * including the document’s `title`, `subtitle`, `media`, and `status`. These values are live and will update in realtime.\n * To reduce unnecessary network requests for resolving the preview values, an optional `ref` can be passed to the hook so that preview\n * resolution will only occur if the `ref` is intersecting the current viewport.\n *\n * @category Documents\n * @param options - The document handle for the document you want to resolve preview values for, and an optional ref\n * @returns The preview values for the given document and a boolean to indicate whether the resolution is pending\n *\n * @example Combining with useDocuments to render a collection of document previews\n * ```\n * // PreviewComponent.jsx\n * export default function PreviewComponent({ document }) {\n * const { data: { title, subtitle, media }, isPending } = usePreview({ document })\n * return (\n * <article style={{ opacity: isPending ? 0.5 : 1}}>\n * {media?.type === 'image-asset' ? <img src={media.url} alt='' /> : ''}\n * <h2>{title}</h2>\n * <p>{subtitle}</p>\n * </article>\n * )\n * }\n *\n * // DocumentList.jsx\n * const { data } = useDocuments({ filter: '_type == \"movie\"' })\n * return (\n * <div>\n * <h1>Movies</h1>\n * <ul>\n * {data.map(movie => (\n * <li key={movie._id}>\n * <Suspense fallback='Loading…'>\n * <PreviewComponent document={movie} />\n * </Suspense>\n * </li>\n * ))}\n * </ul>\n * </div>\n * )\n * ```\n */\nexport function usePreview({ref, ...docHandle}: UsePreviewOptions): UsePreviewResults {\n const instance = useSanityInstance()\n const stateSource = getPreviewState(instance, docHandle)\n\n // Create subscribe function for useSyncExternalStore\n const subscribe = useCallback(\n (onStoreChanged: () => void) => {\n const subscription = new Observable<boolean>((observer) => {\n // For environments that don't have an intersection observer (e.g. server-side),\n // we pass true to always subscribe since we can't detect visibility\n if (typeof IntersectionObserver === 'undefined' || typeof HTMLElement === 'undefined') {\n observer.next(true)\n return\n }\n\n const intersectionObserver = new IntersectionObserver(\n ([entry]) => observer.next(entry.isIntersecting),\n {rootMargin: '0px', threshold: 0},\n )\n if (ref?.current && ref.current instanceof HTMLElement) {\n intersectionObserver.observe(ref.current)\n } else {\n // If no ref is provided or ref.current isn't an HTML element,\n // pass true to always subscribe since we can't track visibility\n observer.next(true)\n }\n return () => intersectionObserver.disconnect()\n })\n .pipe(\n startWith(false),\n distinctUntilChanged(),\n switchMap((isVisible) =>\n isVisible\n ? new Observable<void>((obs) => {\n return stateSource.subscribe(() => obs.next())\n })\n : EMPTY,\n ),\n )\n .subscribe({next: onStoreChanged})\n\n return () => subscription.unsubscribe()\n },\n [stateSource, ref],\n )\n\n // Create getSnapshot function to return current state\n const getSnapshot = useCallback(() => {\n const currentState = stateSource.getCurrent()\n if (currentState.data === null) throw resolvePreview(instance, docHandle)\n return currentState as UsePreviewResults\n }, [docHandle, instance, stateSource])\n\n return useSyncExternalStore(subscribe, getSnapshot)\n}\n","import {\n type DocumentHandle,\n getProjectionState,\n resolveProjection,\n type ValidProjection,\n} from '@sanity/sdk'\nimport {useCallback, useSyncExternalStore} from 'react'\nimport {distinctUntilChanged, EMPTY, Observable, startWith, switchMap} from 'rxjs'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\n/**\n * @public\n * @category Types\n */\nexport interface UseProjectionOptions extends DocumentHandle {\n ref?: React.RefObject<unknown>\n projection: ValidProjection\n}\n\n/**\n * @public\n * @category Types\n */\nexport interface UseProjectionResults<TData extends object> {\n data: TData\n isPending: boolean\n}\n\n/**\n * @beta\n *\n * Returns the projection values of a document (specified via a `DocumentHandle`),\n * based on the provided projection string. These values are live and will update in realtime.\n * To reduce unnecessary network requests for resolving the projection values, an optional `ref` can be passed to the hook so that projection\n * resolution will only occur if the `ref` is intersecting the current viewport.\n *\n * @category Documents\n * @param options - The document handle for the document you want to project values from, the projection string, and an optional ref\n * @returns The projection values for the given document and a boolean to indicate whether the resolution is pending\n *\n * @example Using a projection to render a preview of document\n * ```\n * // ProjectionComponent.jsx\n * export default function ProjectionComponent({ document }) {\n * const ref = useRef(null)\n * const { results: { title, coverImage, authors }, isPending } = useProjection({\n * document,\n * ref,\n * projection: `{\n * title,\n * 'coverImage': cover.asset->url,\n * 'authors': array::join(authors[]->{'name': firstName + ' ' + lastName + ' '}.name, ', ')\n * }`,\n * })\n *\n * return (\n * <article ref={ref} style={{ opacity: isPending ? 0.5 : 1}}>\n * <h2>{title}</h2>\n * <img src={coverImage} alt={title} />\n * <p>{authors}</p>\n * </article>\n * )\n * }\n * ```\n *\n * @example Combining with useDocuments to render a collection with specific fields\n * ```\n * // DocumentList.jsx\n * const { data } = useDocuments({ filter: '_type == \"article\"' })\n * return (\n * <div>\n * <h1>Books</h1>\n * <ul>\n * {data.map(book => (\n * <li key={book._id}>\n * <Suspense fallback='Loading…'>\n * <ProjectionComponent\n * document={book}\n * />\n * </Suspense>\n * </li>\n * ))}\n * </ul>\n * </div>\n * )\n * ```\n */\nexport function useProjection<TData extends object>({\n ref,\n projection,\n ...docHandle\n}: UseProjectionOptions): UseProjectionResults<TData> {\n const instance = useSanityInstance()\n const stateSource = getProjectionState<TData>(instance, {...docHandle, projection})\n\n if (stateSource.getCurrent().data === null) {\n throw resolveProjection(instance, {...docHandle, projection})\n }\n\n // Create subscribe function for useSyncExternalStore\n const subscribe = useCallback(\n (onStoreChanged: () => void) => {\n const subscription = new Observable<boolean>((observer) => {\n // For environments that don't have an intersection observer (e.g. server-side),\n // we pass true to always subscribe since we can't detect visibility\n if (typeof IntersectionObserver === 'undefined' || typeof HTMLElement === 'undefined') {\n observer.next(true)\n return\n }\n\n const intersectionObserver = new IntersectionObserver(\n ([entry]) => observer.next(entry.isIntersecting),\n {rootMargin: '0px', threshold: 0},\n )\n if (ref?.current && ref.current instanceof HTMLElement) {\n intersectionObserver.observe(ref.current)\n } else {\n // If no ref is provided or ref.current isn't an HTML element,\n // pass true to always subscribe since we can't track visibility\n observer.next(true)\n }\n return () => intersectionObserver.disconnect()\n })\n .pipe(\n startWith(false),\n distinctUntilChanged(),\n switchMap((isVisible) =>\n isVisible\n ? new Observable<void>((obs) => {\n return stateSource.subscribe(() => obs.next())\n })\n : EMPTY,\n ),\n )\n .subscribe({next: onStoreChanged})\n\n return () => subscription.unsubscribe()\n },\n [stateSource, ref],\n )\n\n return useSyncExternalStore(subscribe, stateSource.getCurrent) as UseProjectionResults<TData>\n}\n","import {\n getProjectState,\n type ProjectHandle,\n resolveProject,\n type SanityInstance,\n type SanityProject,\n type StateSource,\n} from '@sanity/sdk'\nimport {identity} from 'rxjs'\n\nimport {createStateSourceHook} from '../helpers/createStateSourceHook'\n\ntype UseProject = {\n /**\n *\n * Returns metadata for a given project\n *\n * @category Projects\n * @param projectId - The ID of the project to retrieve metadata for\n * @returns The metadata for the project\n * @example\n * ```tsx\n * function ProjectMetadata({ projectId }: { projectId: string }) {\n * const project = useProject(projectId)\n *\n * return (\n * <figure style={{ backgroundColor: project.metadata.color || 'lavender'}}>\n * <h1>{project.displayName}</h1>\n * </figure>\n * )\n * }\n * ```\n */\n (projectHandle?: ProjectHandle): SanityProject\n}\n\n/**\n * @public\n * @function\n */\nexport const useProject: UseProject = createStateSourceHook({\n // remove `undefined` since we're suspending when that is the case\n getState: getProjectState as (\n instance: SanityInstance,\n projectHandle?: ProjectHandle,\n ) => StateSource<SanityProject>,\n shouldSuspend: (instance, projectHandle) =>\n getProjectState(instance, projectHandle).getCurrent() === undefined,\n suspender: resolveProject,\n getConfig: identity,\n})\n","import {type SanityProject} from '@sanity/client'\nimport {getProjectsState, resolveProjects, type SanityInstance, type StateSource} from '@sanity/sdk'\n\nimport {createStateSourceHook} from '../helpers/createStateSourceHook'\n\n/**\n * @public\n * @category Types\n * @interface\n */\nexport type ProjectWithoutMembers = Omit<SanityProject, 'members'>\n\ntype UseProjects = {\n /**\n *\n * Returns metadata for each project you have access to.\n *\n * @category Projects\n * @returns An array of metadata (minus the projects’ members) for each project\n * @example\n * ```tsx\n * const projects = useProjects()\n *\n * return (\n * <select>\n * {projects.map((project) => (\n * <option key={project.id}>{project.displayName}</option>\n * ))}\n * </select>\n * )\n * ```\n */\n (): ProjectWithoutMembers[]\n}\n\n/**\n * @public\n * @function\n */\nexport const useProjects: UseProjects = createStateSourceHook({\n // remove `undefined` since we're suspending when that is the case\n getState: getProjectsState as (instance: SanityInstance) => StateSource<ProjectWithoutMembers[]>,\n shouldSuspend: (instance) => getProjectsState(instance).getCurrent() === undefined,\n suspender: resolveProjects,\n})\n","import {\n getUsersKey,\n type GetUsersOptions,\n getUsersState,\n loadMoreUsers,\n parseUsersKey,\n resolveUsers,\n type SanityUser,\n} from '@sanity/sdk'\nimport {useCallback, useEffect, useMemo, useState, useSyncExternalStore, useTransition} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\n/**\n * @public\n * @category Types\n */\nexport interface UsersResult {\n /**\n * The users fetched.\n */\n data: SanityUser[]\n /**\n * Whether there are more users to fetch.\n */\n hasMore: boolean\n\n /**\n * Whether a users request is currently in progress\n */\n isPending: boolean\n /**\n * Load more users.\n */\n loadMore: () => void\n}\n\n/**\n *\n * @public\n *\n * Retrieves the users for a given resource (either a project or an organization).\n *\n * @category Users\n * @param params - The resource type, project ID, and the limit of users to fetch\n * @returns A list of users, a boolean indicating whether there are more users to fetch, and a function to load more users\n *\n * @example\n * ```\n * const { data, hasMore, loadMore, isPending } = useUsers({\n * resourceType: 'organization',\n * organizationId: 'my-org-id',\n * batchSize: 10,\n * })\n *\n * return (\n * <div>\n * {data.map(user => (\n * <figure key={user.sanityUserId}>\n * <img src={user.profile.imageUrl} alt='' />\n * <figcaption>{user.profile.displayName}</figcaption>\n * <address>{user.profile.email}</address>\n * </figure>\n * ))}\n * {hasMore && <button onClick={loadMore}>{isPending ? 'Loading...' : 'Load More'</button>}\n * </div>\n * )\n * ```\n */\nexport function useUsers(options?: GetUsersOptions): UsersResult {\n const instance = useSanityInstance(options)\n // Use React's useTransition to avoid UI jank when user options change\n const [isPending, startTransition] = useTransition()\n\n // Get the unique key for this users request and its options\n const key = getUsersKey(instance, options)\n // Use a deferred state to avoid immediate re-renders when the users request changes\n const [deferredKey, setDeferredKey] = useState(key)\n // Parse the deferred users key back into users options\n const deferred = useMemo(() => parseUsersKey(deferredKey), [deferredKey])\n\n // Create an AbortController to cancel in-flight requests when needed\n const [ref, setRef] = useState<AbortController>(new AbortController())\n\n // When the users request or options change, start a transition to update the request\n useEffect(() => {\n if (key === deferredKey) return\n\n startTransition(() => {\n if (!ref.signal.aborted) {\n ref.abort()\n setRef(new AbortController())\n }\n\n setDeferredKey(key)\n })\n }, [deferredKey, key, ref])\n\n // Get the state source for this users request from the users store\n const {getCurrent, subscribe} = useMemo(() => {\n return getUsersState(instance, deferred)\n }, [instance, deferred])\n\n // If data isn't available yet, suspend rendering until it is\n // This is the React Suspense integration - throwing a promise\n // will cause React to show the nearest Suspense fallback\n if (getCurrent() === undefined) {\n throw resolveUsers(instance, {...deferred, signal: ref.signal})\n }\n\n // Subscribe to updates and get the current data\n // useSyncExternalStore ensures the component re-renders when the data changes\n const {data, hasMore} = useSyncExternalStore(subscribe, getCurrent)!\n\n const loadMore = useCallback(() => {\n loadMoreUsers(instance, options)\n }, [instance, options])\n\n return {data, hasMore, isPending, loadMore}\n}\n","// Local type declaration for Remix\ntype WindowWithEnv = Window &\n typeof globalThis & {\n ENV?: Record<string, unknown>\n }\n\ntype KnownEnvVar = 'DEV' | 'PKG_VERSION'\n\nexport function getEnv(key: KnownEnvVar): unknown {\n if (typeof import.meta !== 'undefined' && import.meta.env) {\n // Vite environment variables\n return (import.meta.env as unknown as Record<string, unknown>)[key]\n } else if (typeof process !== 'undefined' && process.env) {\n // Node.js or server-side environment variables\n return process.env[key]\n } else if (typeof window !== 'undefined' && (window as WindowWithEnv).ENV) {\n // Remix-style client-side environment variables\n return (window as WindowWithEnv).ENV?.[key]\n }\n return undefined\n}\n","import {version} from '../package.json'\nimport {getEnv} from './utils/getEnv'\n\n/**\n * This version is provided by pkg-utils at build time\n * @internal\n */\nexport const REACT_SDK_VERSION = getEnv('PKG_VERSION') || `${version}-development`\n"],"names":["SanityInstanceContext","createContext","useSanityInstance","config","$","_c","instance","useContext","Error","JSON","stringify","t0","match","createStateSourceHook","options","getState","getConfig","undefined","suspense","useHook","params","t1","suspender","shouldSuspend","t2","state","useSyncExternalStore","subscribe","getCurrent","useAuthState","getAuthState","useLoginUrl","getLoginUrlState","isInIframe","window","self","top","isLocalUrl","url","location","href","startsWith","AuthError","constructor","error","message","cause","createCallbackHook","callback","useHandleAuthCallback","handleAuthCallback","LoginCallback","URL","toString","then","_temp","useEffect","replacementLocation","history","replaceState","e","navigator","product","t","timeout","r","a","o","query","searchParams","indexOf","URLSearchParams","slice","decodeURIComponent","s","split","append","n","Object","entries","Array","isArray","method","body","toUpperCase","replace","connect","socket","Number","isNaN","length","knownProperties","mimicResponse","fromStream","toStream","_readableState","autoDestroy","fromProperties","Set","keys","concat","properties","property","get","value","bind","set","enumerable","configurable","defineProperties","once","destroy","emit","complete","readable","Transform","PassThrough","require$$0","zlib","require$$1","require$$2","decompressResponse","response","contentEncoding","headers","toLowerCase","includes","isBrotli","createBrotliDecompress","isEmpty","checker","transform","data","_encoding","flush","finalStream","decompressStream","createUnzip","end","pipe","m","h","d","w","y","ms","val","type","parse","isFinite","long","fmtLong","fmtShort","str","String","exec","parseFloat","msAbs","Math","abs","round","plural","name","isPlural","setup","env","createDebug","debug","default","coerce","disable","enable","enabled","humanize","forEach","key","names","skips","formatters","selectColor","namespace","hash","i","charCodeAt","colors","prevTime","enableOverride","namespacesCache","enabledCache","args","curr","Date","diff","prev","unshift","index","format","formatter","call","splice","formatArgs","log","apply","useColors","color","extend","defineProperty","namespaces","v","init","delimiter","newDebug","save","trim","filter","Boolean","ns","push","matchesTemplate","search","template","searchIndex","templateIndex","starIndex","matchIndex","map","join","skip","stack","console","warn","load","common","exports","storage","localstorage","warned","process","__nwjs","userAgent","document","documentElement","style","WebkitAppearance","firebug","exception","table","parseInt","module","c","lastC","setItem","removeItem","getItem","DEBUG","localStorage","j","hasFlag","flag","argv","prefix","position","terminatorPosition","os","tty","forceColor","FORCE_COLOR","min","translateLevel","level","hasBasic","has256","has16m","supportsColor","haveStream","streamIsTTY","TERM","platform","osRelease","release","some","sign","CI_NAME","test","TEAMCITY_VERSION","COLORTERM","version","TERM_PROGRAM_VERSION","TERM_PROGRAM","getSupportLevel","stream","isTTY","supportsColor_1","stdout","isatty","stderr","util","deprecate","inspectOpts","reduce","obj","prop","substring","_","k","fd","colorCode","getDate","hideDate","toISOString","write","formatWithOptions","require$$3","inspect","O","browser","srcModule","debug_1","arguments","http","https","Writable","assert","require$$4","require$$5","detectUnsupportedEnvironment","looksLikeNode","looksLikeBrowser","looksLikeV8","isFunction","captureStackTrace","useNativeURL","code","preservedUrlFields","events","eventHandlers","create","event","arg1","arg2","arg3","_redirectable","InvalidUrlError","createErrorType","TypeError","RedirectionError","TooManyRedirectsError","MaxBodyLengthExceededError","WriteAfterEndError","prototype","noop","RedirectableRequest","responseCallback","_sanitizeOptions","_options","_ended","_ending","_redirectCount","_redirects","_requestBodyLength","_requestBodyBuffers","on","_onNativeResponse","_processResponse","_performRequest","abort","destroyRequest","_currentRequest","encoding","isString","isBuffer","maxBodyLength","currentRequest","setHeader","removeHeader","setTimeout","msecs","destroyOnTimeout","removeListener","addListener","startTimer","_timeout","clearTimeout","clearTimer","b","host","hostname","pathname","path","searchPos","protocol","nativeProtocol","nativeProtocols","agents","scheme","agent","request","_currentUrl","_isRedirect","buffers","writeNext","buffer","finished","statusCode","trackRedirects","followRedirects","responseUrl","redirects","maxRedirects","requestHeaders","beforeRedirect","assign","Host","req","getHeader","removeMatchingHeaders","currentHostHeader","currentUrlParts","parseUrl","currentHost","currentUrl","redirectUrl","resolveUrl","spreadUrlObject","isSubdomain","responseDetails","requestDetails","wrap","protocols","wrappedProtocol","input","isURL","validateUrl","equal","wrappedRequest","writable","parsed","relative","base","resolve","urlObject","target","spread","port","regex","lastValue","header","baseClass","CustomError","subdomain","domain","dot","endsWith","followRedirectsModule","processNextickArgsModule","nextTick","fn","len","isarray","arr","Buffer","copyProps","src","dst","from","alloc","allocUnsafe","allocUnsafeSlow","SafeBuffer","arg","encodingOrOffset","size","fill","buf","SlowBuffer","objectToString","isBoolean","isNull","isNullOrUndefined","isNumber","isSymbol","isUndefined","isRegExp","re","isObject","isDate","isError","isPrimitive","inherits_browserModule","ctor","superCtor","super_","TempCtor","require","inherits","inheritsModule","_classCallCheck","Constructor","copyBuffer","offset","copy","BufferList","head","tail","entry","next","shift","ret","clear","p","custom","pna","err","cb","_this","readableDestroyed","destroyed","writableDestroyed","_writableState","errorEmitted","emitErrorNT","_destroy","undestroy","reading","ended","endEmitted","ending","finalCalled","prefinished","destroy_1","node","_stream_writable","CorkedRequest","finish","onCorkedFinish","asyncWrite","setImmediate","Duplex","WritableState","internalUtil","Stream","OurUint8Array","global","Uint8Array","_uint8ArrayToBuffer","chunk","_isUint8Array","destroyImpl","require$$6","nop","require$$7","isDuplex","objectMode","writableObjectMode","hwm","highWaterMark","writableHwm","writableHighWaterMark","defaultHwm","floor","needDrain","noDecode","decodeStrings","defaultEncoding","writing","corked","sync","bufferProcessing","onwrite","er","writecb","writelen","bufferedRequest","lastBufferedRequest","pendingcb","bufferedRequestCount","corkedRequestsFree","getBuffer","current","out","realHasInstance","Symbol","hasInstance","Function","object","_write","writev","_writev","final","_final","writeAfterEnd","validChunk","valid","isBuf","writeOrBuffer","cork","uncork","clearBuffer","setDefaultEncoding","decodeChunk","newChunk","last","doWrite","onwriteError","finishMaybe","onwriteStateUpdate","needFinish","afterWrite","onwriteDrain","l","holder","count","allBuffers","endWritable","callFinal","prefinish","need","corkReq","_undestroy","objectKeys","_stream_duplex","Readable","allowHalfOpen","onend","onEndNT","isEncoding","_normalizeEncoding","enc","retried","normalizeEncoding","nenc","string_decoder","StringDecoder","nb","text","utf16Text","utf16End","fillLast","utf8FillLast","base64Text","base64End","simpleWrite","simpleEnd","lastNeed","lastTotal","lastChar","utf8End","utf8Text","utf8CheckByte","byte","utf8CheckIncomplete","utf8CheckExtraBytes","total","_stream_readable","ReadableState","EElistenerCount","emitter","listeners","debugUtil","debuglog","require$$8","require$$9","kProxyEvents","prependListener","_events","require$$10","readableObjectMode","readableHwm","readableHighWaterMark","pipes","pipesCount","flowing","needReadable","emittedReadable","readableListening","resumeScheduled","awaitDrain","readingMore","decoder","require$$11","read","_read","skipChunkCheck","readableAddChunk","addToFront","onEofChunk","chunkInvalid","getPrototypeOf","addChunk","maybeReadMore","needMoreData","emitReadable","isPaused","setEncoding","MAX_HWM","computeNewHighWaterMark","howMuchToRead","nOrig","endReadable","doRead","fromList","emitReadable_","flow","maybeReadMore_","dest","pipeOpts","doEnd","endFn","unpipe","onunpipe","unpipeInfo","hasUnpiped","cleanup","ondrain","pipeOnDrain","cleanedUp","onclose","onfinish","onerror","ondata","increasedAwaitDrain","pause","resume","dests","ev","res","nReadingNextTick","resume_","paused","_fromList","fromListPartial","list","hasStrings","copyFromBufferString","copyFromBuffer","endReadableNT","xs","x","_stream_transform","afterTransform","ts","_transformState","transforming","writechunk","rs","needTransform","writeencoding","_transform","_flush","done","_this2","err2","_stream_passthrough","READABLE_STREAM","immutable","hasOwnProperty","source","xtend","DestroyableTransform","opts","_destroyed","through2","construct","through2Module","Through2","override","tick","maxTick","resolution","inc","timer","setInterval","unref","speedometer","seconds","pointer","delta","dist","btm","through","onprogress","time","drain","transferred","nextUpdate","now","speed","startTime","update","percentage","remaining","eta","runtime","tr","onlength","newLength","setLength","progress","net","tls","tunnelAgent","httpOverHttp","httpsOverHttp","httpOverHttps","httpsOverHttps","TunnelingAgent","createSocket","createSecureSocket","defaultPort","proxyOptions","proxy","maxSockets","Agent","defaultMaxSockets","requests","sockets","pending","onSocket","removeSocket","EventEmitter","addRequest","createConnection","onFree","onCloseOrRemove","placeholder","connectOptions","mergeOptions","proxyAuth","connectReq","useChunkedEncodingByDefault","onResponse","onUpgrade","onConnect","onError","upgrade","removeAllListeners","pos","secureSocket","servername","overrides","keyLen","NODE_DEBUG","getIt","denyList","isRetryAllowed","has","finalizeOptions","f","u","fromCodePoint","E","padStart","I","T","C","fromEntries","reverse","S","values","RegExp","cleaned","encoded","BASE_URL","generateHelpUrl","slug","ClientError","responseBody","details","props","extractErrorProps","ServerError","stringifyBody","isMutationError","isActionError","allItems","items","item","description","itemsStr","httpErrorMessage","isPlainObject","statusMessage","CorsOriginError","projectId","addOriginUrl","origin","useLogOut","logout","LoginError","resetErrorBoundary","authState","authErrorMessage","setAuthErrorMessage","useState","handleRetry","AuthStateType","ERROR","errorMessage","t3","t4","for","t5","t6","t7","querySelector","parsedUrl","mode","script","createElement","async","appendChild","AuthBoundary","LoginErrorComponent","fallbackProps","FallbackComponent","AuthSwitch","children","CallbackComponent","isLoggedOut","LOGGED_OUT","isDestroyingSession","loginUrl","LOGGING_IN","LOGGED_IN","DEFAULT_FALLBACK","ResourceProvider","fallback","parent","createChild","createSanityInstance","disposal","useRef","timeoutId","isDisposed","dispose","SDKProvider","configs","createNestedProviders","REDIRECT_URL","SanityApp","sanityConfigs","_temp2","useAuthToken","getTokenState","useCurrentUser","getCurrentUserState","useDashboardOrganizationId","getDashboardOrganizationId","useClient","getClientState","identity","useFrameConnection","onMessage","targetOrigin","connectTo","heartbeat","onStatus","controllerRef","channelRef","controller","getOrCreateController","channel","getOrCreateChannel","status","messageUnsubscribers","handler","unsubscribe","releaseChannel","frameWindow","removeTarget","addTarget","type_0","post","sendMessage","unsub","useWindowConnection","nodeRef","getOrCreateNode","statusUnsubscribe","eventStatus","messageUnsubscribe","releaseNode","type_1","data_0","fetchOptions","fetch","useManageFavorite","documentId","documentType","paramProjectId","dataset","paramDataset","resourceId","paramResourceId","resourceType","schemaName","isFavorited","setIsFavorited","setStatus","setResourceId","SDK_NODE_NAME","SDK_CHANNEL_NAME","instanceProjectId","instanceDataset","action","setFavoriteState","eventType","id","resource","success","handleFavoriteAction","favorite","unfavorite","t8","isConnected","useRecordDocumentHistoryEvent","recordEvent","useStudioWorkspacesByProjectIdDataset","workspacesByProjectIdAndDataset","setWorkspacesByProjectIdAndDataset","setError","fetchWorkspaces","signal","workspaceMap","noProjectIdAndDataset","context","availableResources","AbortController","useNavigateToStudioDocument","documentHandle","preferredStudioUrl","workspacesConnected","workspace","find","workspaces","navigateToStudioDocument","useDatasets","getDatasetsState","projectHandle","resolveDatasets","useApplyDocumentActions","applyDocumentActions","useDocument","doc","_useDocument","getDocumentState","resolveDocument","useDocumentEvent","ref","useInsertionEffect","documentEvent","stableHandler","subscribeDocumentEvents","useDocumentPermissions","actionOrActions","actions","getPermissionsState","firstValueFrom","observable","result","useDocumentSyncStatus","getDocumentSyncStatus","ignoredKeys","useEditDocument","docHandle","updater","nextValue","editDocument","nextValue_0","editActions","key_0","key_1","unset","useQuery","isPending","startTransition","useTransition","queryKey","getQueryKey","deferredQueryKey","setDeferredQueryKey","deferred","useMemo","parseQueryKey","aborted","getQueryState","currentSignal","resolveQuery","DEFAULT_BATCH_SIZE","DEFAULT_PERSPECTIVE","useDocuments","orderings","batchSize","perspective","limit","setLimit","conditions","trimmedSearch","searchFilter","createGroqSearchFilter","filterClause","orderClause","dataQuery","countQuery","pick","__dataset","t9","hasMore","t10","loadMore","t11","t12","ordering","field","direction","usePaginatedDocuments","pageSize","pageIndex","setPageIndex","startIndex","endIndex","totalPages","ceil","currentPage","t13","firstPage","t14","_temp3","previousPage","t15","prev_0","nextPage","t16","lastPage","t17","pageNumber","goToPage","hasFirstPage","hasPreviousPage","hasNextPage","hasLastPage","t18","max","usePreview","getPreviewState","stateSource","onStoreChanged","subscription","Observable","observer","IntersectionObserver","HTMLElement","intersectionObserver","isIntersecting","rootMargin","threshold","observe","disconnect","startWith","distinctUntilChanged","switchMap","isVisible","obs","EMPTY","currentState","resolvePreview","useProjection","projection","getProjectionState","resolveProjection","useProject","getProjectState","resolveProject","useProjects","getProjectsState","resolveProjects","useUsers","getUsersKey","deferredKey","setDeferredKey","parseUsersKey","setRef","getUsersState","resolveUsers","useCallback","loadMoreUsers","getEnv","import","ENV","REACT_SDK_VERSION"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAGaA,MAAAA,wBAAwBC,cAAqC,IAAI,GCwDjEC,oBAAoBC,CAAA,WAAA;AAAA,QAAAC,IAAAC,IAAA,CAAA,GAC/BC,WAAiBC,WAAAP,qBAAgC;AAAC,MAAA,CAE7CM;AAAQ,UAAA,IAAAE,MAET,qCAAqCL,SAAS,qBAAqBM,KAAAC,UAAeP,QAAe,MAAA,CAAA,CAAC,OAAO,EAAE,wFAAwF;AAAA,MAAA,CAIlMA;AAAeG,WAAAA;AAAQK,MAAAA;AAAAP,IAAAD,CAAAA,MAAAA,UAAAC,SAAAE,YAEdK,KAAAL,SAAQM,MAAOT,MAAM,GAACC,OAAAD,QAAAC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