@graffiticode/l0000-view 0.1.3 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../../../node_modules/use-sync-external-store/cjs/use-sync-external-store-shim.production.js","../../../node_modules/use-sync-external-store/cjs/use-sync-external-store-shim.development.js","../../../node_modules/use-sync-external-store/shim/index.js","../../../node_modules/swr/dist/_internal/events.mjs","../../../node_modules/dequal/lite/index.mjs","../../../node_modules/swr/dist/_internal/config-context-12s-CCVTDPOP.mjs","../../../node_modules/swr/dist/_internal/constants.mjs","../../../node_modules/swr/dist/_internal/index.mjs","../../../node_modules/swr/dist/index/index.mjs","../src/lib/api.ts","../src/swr/fetchers.ts","../src/view.tsx","../src/components/form/Form.tsx"],"sourcesContent":["/**\n * @license React\n * use-sync-external-store-shim.production.js\n *\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n\"use strict\";\nvar React = require(\"react\");\nfunction is(x, y) {\n return (x === y && (0 !== x || 1 / x === 1 / y)) || (x !== x && y !== y);\n}\nvar objectIs = \"function\" === typeof Object.is ? Object.is : is,\n useState = React.useState,\n useEffect = React.useEffect,\n useLayoutEffect = React.useLayoutEffect,\n useDebugValue = React.useDebugValue;\nfunction useSyncExternalStore$2(subscribe, getSnapshot) {\n var value = getSnapshot(),\n _useState = useState({ inst: { value: value, getSnapshot: getSnapshot } }),\n inst = _useState[0].inst,\n forceUpdate = _useState[1];\n useLayoutEffect(\n function () {\n inst.value = value;\n inst.getSnapshot = getSnapshot;\n checkIfSnapshotChanged(inst) && forceUpdate({ inst: inst });\n },\n [subscribe, value, getSnapshot]\n );\n useEffect(\n function () {\n checkIfSnapshotChanged(inst) && forceUpdate({ inst: inst });\n return subscribe(function () {\n checkIfSnapshotChanged(inst) && forceUpdate({ inst: inst });\n });\n },\n [subscribe]\n );\n useDebugValue(value);\n return value;\n}\nfunction checkIfSnapshotChanged(inst) {\n var latestGetSnapshot = inst.getSnapshot;\n inst = inst.value;\n try {\n var nextValue = latestGetSnapshot();\n return !objectIs(inst, nextValue);\n } catch (error) {\n return !0;\n }\n}\nfunction useSyncExternalStore$1(subscribe, getSnapshot) {\n return getSnapshot();\n}\nvar shim =\n \"undefined\" === typeof window ||\n \"undefined\" === typeof window.document ||\n \"undefined\" === typeof window.document.createElement\n ? useSyncExternalStore$1\n : useSyncExternalStore$2;\nexports.useSyncExternalStore =\n void 0 !== React.useSyncExternalStore ? React.useSyncExternalStore : shim;\n","/**\n * @license React\n * use-sync-external-store-shim.development.js\n *\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n\"use strict\";\n\"production\" !== process.env.NODE_ENV &&\n (function () {\n function is(x, y) {\n return (x === y && (0 !== x || 1 / x === 1 / y)) || (x !== x && y !== y);\n }\n function useSyncExternalStore$2(subscribe, getSnapshot) {\n didWarnOld18Alpha ||\n void 0 === React.startTransition ||\n ((didWarnOld18Alpha = !0),\n console.error(\n \"You are using an outdated, pre-release alpha of React 18 that does not support useSyncExternalStore. The use-sync-external-store shim will not work correctly. Upgrade to a newer pre-release.\"\n ));\n var value = getSnapshot();\n if (!didWarnUncachedGetSnapshot) {\n var cachedValue = getSnapshot();\n objectIs(value, cachedValue) ||\n (console.error(\n \"The result of getSnapshot should be cached to avoid an infinite loop\"\n ),\n (didWarnUncachedGetSnapshot = !0));\n }\n cachedValue = useState({\n inst: { value: value, getSnapshot: getSnapshot }\n });\n var inst = cachedValue[0].inst,\n forceUpdate = cachedValue[1];\n useLayoutEffect(\n function () {\n inst.value = value;\n inst.getSnapshot = getSnapshot;\n checkIfSnapshotChanged(inst) && forceUpdate({ inst: inst });\n },\n [subscribe, value, getSnapshot]\n );\n useEffect(\n function () {\n checkIfSnapshotChanged(inst) && forceUpdate({ inst: inst });\n return subscribe(function () {\n checkIfSnapshotChanged(inst) && forceUpdate({ inst: inst });\n });\n },\n [subscribe]\n );\n useDebugValue(value);\n return value;\n }\n function checkIfSnapshotChanged(inst) {\n var latestGetSnapshot = inst.getSnapshot;\n inst = inst.value;\n try {\n var nextValue = latestGetSnapshot();\n return !objectIs(inst, nextValue);\n } catch (error) {\n return !0;\n }\n }\n function useSyncExternalStore$1(subscribe, getSnapshot) {\n return getSnapshot();\n }\n \"undefined\" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ &&\n \"function\" ===\n typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart &&\n __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());\n var React = require(\"react\"),\n objectIs = \"function\" === typeof Object.is ? Object.is : is,\n useState = React.useState,\n useEffect = React.useEffect,\n useLayoutEffect = React.useLayoutEffect,\n useDebugValue = React.useDebugValue,\n didWarnOld18Alpha = !1,\n didWarnUncachedGetSnapshot = !1,\n shim =\n \"undefined\" === typeof window ||\n \"undefined\" === typeof window.document ||\n \"undefined\" === typeof window.document.createElement\n ? useSyncExternalStore$1\n : useSyncExternalStore$2;\n exports.useSyncExternalStore =\n void 0 !== React.useSyncExternalStore ? React.useSyncExternalStore : shim;\n \"undefined\" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ &&\n \"function\" ===\n typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop &&\n __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error());\n })();\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('../cjs/use-sync-external-store-shim.production.js');\n} else {\n module.exports = require('../cjs/use-sync-external-store-shim.development.js');\n}\n","const FOCUS_EVENT = 0;\nconst RECONNECT_EVENT = 1;\nconst MUTATE_EVENT = 2;\nconst ERROR_REVALIDATE_EVENT = 3;\n\nexport { ERROR_REVALIDATE_EVENT, FOCUS_EVENT, MUTATE_EVENT, RECONNECT_EVENT };\n","var has = Object.prototype.hasOwnProperty;\n\nexport function dequal(foo, bar) {\n\tvar ctor, len;\n\tif (foo === bar) return true;\n\n\tif (foo && bar && (ctor=foo.constructor) === bar.constructor) {\n\t\tif (ctor === Date) return foo.getTime() === bar.getTime();\n\t\tif (ctor === RegExp) return foo.toString() === bar.toString();\n\n\t\tif (ctor === Array) {\n\t\t\tif ((len=foo.length) === bar.length) {\n\t\t\t\twhile (len-- && dequal(foo[len], bar[len]));\n\t\t\t}\n\t\t\treturn len === -1;\n\t\t}\n\n\t\tif (!ctor || typeof foo === 'object') {\n\t\t\tlen = 0;\n\t\t\tfor (ctor in foo) {\n\t\t\t\tif (has.call(foo, ctor) && ++len && !has.call(bar, ctor)) return false;\n\t\t\t\tif (!(ctor in bar) || !dequal(foo[ctor], bar[ctor])) return false;\n\t\t\t}\n\t\t\treturn Object.keys(bar).length === len;\n\t\t}\n\t}\n\n\treturn foo !== foo && bar !== bar;\n}\n","'use client';\nimport React, { useEffect, useLayoutEffect, createContext, useContext, useMemo, useRef, createElement } from 'react';\nimport * as revalidateEvents from './events.mjs';\nimport { dequal } from 'dequal/lite';\n\n// Global state used to deduplicate requests and store listeners\nconst SWRGlobalState = new WeakMap();\n\n// Shared state between server components and client components\nconst noop = ()=>{};\n// Using noop() as the undefined value as undefined can be replaced\n// by something else. Prettier ignore and extra parentheses are necessary here\n// to ensure that tsc doesn't remove the __NOINLINE__ comment.\n// prettier-ignore\nconst UNDEFINED = /*#__NOINLINE__*/ noop();\nconst OBJECT = Object;\nconst isUndefined = (v)=>v === UNDEFINED;\nconst isFunction = (v)=>typeof v == 'function';\nconst mergeObjects = (a, b)=>({\n ...a,\n ...b\n });\nconst isPromiseLike = (x)=>isFunction(x.then);\n\nconst EMPTY_CACHE = {};\nconst INITIAL_CACHE = {};\nconst STR_UNDEFINED = 'undefined';\n// NOTE: Use the function to guarantee it's re-evaluated between jsdom and node runtime for tests.\nconst isWindowDefined = typeof window != STR_UNDEFINED;\nconst isDocumentDefined = typeof document != STR_UNDEFINED;\nconst isLegacyDeno = isWindowDefined && 'Deno' in window;\nconst hasRequestAnimationFrame = ()=>isWindowDefined && typeof window['requestAnimationFrame'] != STR_UNDEFINED;\nconst createCacheHelper = (cache, key)=>{\n const state = SWRGlobalState.get(cache);\n return [\n // Getter\n ()=>!isUndefined(key) && cache.get(key) || EMPTY_CACHE,\n // Setter\n (info)=>{\n if (!isUndefined(key)) {\n const prev = cache.get(key);\n // Before writing to the store, we keep the value in the initial cache\n // if it's not there yet.\n if (!(key in INITIAL_CACHE)) {\n INITIAL_CACHE[key] = prev;\n }\n state[5](key, mergeObjects(prev, info), prev || EMPTY_CACHE);\n }\n },\n // Subscriber\n state[6],\n // Get server cache snapshot\n ()=>{\n if (!isUndefined(key)) {\n // If the cache was updated on the client, we return the stored initial value.\n if (key in INITIAL_CACHE) return INITIAL_CACHE[key];\n }\n // If we haven't done any client-side updates, we return the current value.\n return !isUndefined(key) && cache.get(key) || EMPTY_CACHE;\n }\n ];\n} // export { UNDEFINED, OBJECT, isUndefined, isFunction, mergeObjects, isPromiseLike }\n;\n\n/**\n * Due to the bug https://bugs.chromium.org/p/chromium/issues/detail?id=678075,\n * it's not reliable to detect if the browser is currently online or offline\n * based on `navigator.onLine`.\n * As a workaround, we always assume it's online on the first load, and change\n * the status upon `online` or `offline` events.\n */ let online = true;\nconst isOnline = ()=>online;\n// For node and React Native, `add/removeEventListener` doesn't exist on window.\nconst [onWindowEvent, offWindowEvent] = isWindowDefined && window.addEventListener ? [\n window.addEventListener.bind(window),\n window.removeEventListener.bind(window)\n] : [\n noop,\n noop\n];\nconst isVisible = ()=>{\n const visibilityState = isDocumentDefined && document.visibilityState;\n return isUndefined(visibilityState) || visibilityState !== 'hidden';\n};\nconst initFocus = (callback)=>{\n // focus revalidate\n if (isDocumentDefined) {\n document.addEventListener('visibilitychange', callback);\n }\n onWindowEvent('focus', callback);\n return ()=>{\n if (isDocumentDefined) {\n document.removeEventListener('visibilitychange', callback);\n }\n offWindowEvent('focus', callback);\n };\n};\nconst initReconnect = (callback)=>{\n // revalidate on reconnected\n const onOnline = ()=>{\n online = true;\n callback();\n };\n // nothing to revalidate, just update the status\n const onOffline = ()=>{\n online = false;\n };\n onWindowEvent('online', onOnline);\n onWindowEvent('offline', onOffline);\n return ()=>{\n offWindowEvent('online', onOnline);\n offWindowEvent('offline', onOffline);\n };\n};\nconst preset = {\n isOnline,\n isVisible\n};\nconst defaultConfigOptions = {\n initFocus,\n initReconnect\n};\n\nconst IS_REACT_LEGACY = !React.useId;\nconst IS_SERVER = !isWindowDefined || isLegacyDeno;\n// Polyfill requestAnimationFrame\nconst rAF = (f)=>hasRequestAnimationFrame() ? window['requestAnimationFrame'](f) : setTimeout(f, 1);\n// React currently throws a warning when using useLayoutEffect on the server.\n// To get around it, we can conditionally useEffect on the server (no-op) and\n// useLayoutEffect in the browser.\nconst useIsomorphicLayoutEffect = IS_SERVER ? useEffect : useLayoutEffect;\n// This assignment is to extend the Navigator type to use effectiveType.\nconst navigatorConnection = typeof navigator !== 'undefined' && navigator.connection;\n// Adjust the config based on slow connection status (<= 70Kbps).\nconst slowConnection = !IS_SERVER && navigatorConnection && ([\n 'slow-2g',\n '2g'\n].includes(navigatorConnection.effectiveType) || navigatorConnection.saveData);\n\n// use WeakMap to store the object->key mapping\n// so the objects can be garbage collected.\n// WeakMap uses a hashtable under the hood, so the lookup\n// complexity is almost O(1).\nconst table = new WeakMap();\nconst getTypeName = (value)=>OBJECT.prototype.toString.call(value);\nconst isObjectTypeName = (typeName, type)=>typeName === `[object ${type}]`;\n// counter of the key\nlet counter = 0;\n// A stable hash implementation that supports:\n// - Fast and ensures unique hash properties\n// - Handles unserializable values\n// - Handles object key ordering\n// - Generates short results\n//\n// This is not a serialization function, and the result is not guaranteed to be\n// parsable.\nconst stableHash = (arg)=>{\n const type = typeof arg;\n const typeName = getTypeName(arg);\n const isDate = isObjectTypeName(typeName, 'Date');\n const isRegex = isObjectTypeName(typeName, 'RegExp');\n const isPlainObject = isObjectTypeName(typeName, 'Object');\n let result;\n let index;\n if (OBJECT(arg) === arg && !isDate && !isRegex) {\n // Object/function, not null/date/regexp. Use WeakMap to store the id first.\n // If it's already hashed, directly return the result.\n result = table.get(arg);\n if (result) return result;\n // Store the hash first for circular reference detection before entering the\n // recursive `stableHash` calls.\n // For other objects like set and map, we use this id directly as the hash.\n result = ++counter + '~';\n table.set(arg, result);\n if (Array.isArray(arg)) {\n // Array.\n result = '@';\n for(index = 0; index < arg.length; index++){\n result += stableHash(arg[index]) + ',';\n }\n table.set(arg, result);\n }\n if (isPlainObject) {\n // Object, sort keys.\n result = '#';\n const keys = OBJECT.keys(arg).sort();\n while(!isUndefined(index = keys.pop())){\n if (!isUndefined(arg[index])) {\n result += index + ':' + stableHash(arg[index]) + ',';\n }\n }\n table.set(arg, result);\n }\n } else {\n result = isDate ? arg.toJSON() : type == 'symbol' ? arg.toString() : type == 'string' ? JSON.stringify(arg) : '' + arg;\n }\n return result;\n};\n\nconst serialize = (key)=>{\n if (isFunction(key)) {\n try {\n key = key();\n } catch (err) {\n // dependencies not ready\n key = '';\n }\n }\n // Use the original key as the argument of fetcher. This can be a string or an\n // array of values.\n const args = key;\n // If key is not falsy, or not an empty array, hash it.\n key = typeof key == 'string' ? key : (Array.isArray(key) ? key.length : key) ? stableHash(key) : '';\n return [\n key,\n args\n ];\n};\n\n// Global timestamp.\nlet __timestamp = 0;\nconst getTimestamp = ()=>++__timestamp;\n\nasync function internalMutate(...args) {\n const [cache, _key, _data, _opts] = args;\n // When passing as a boolean, it's explicitly used to disable/enable\n // revalidation.\n const options = mergeObjects({\n populateCache: true,\n throwOnError: true\n }, typeof _opts === 'boolean' ? {\n revalidate: _opts\n } : _opts || {});\n let populateCache = options.populateCache;\n const rollbackOnErrorOption = options.rollbackOnError;\n let optimisticData = options.optimisticData;\n const rollbackOnError = (error)=>{\n return typeof rollbackOnErrorOption === 'function' ? rollbackOnErrorOption(error) : rollbackOnErrorOption !== false;\n };\n const throwOnError = options.throwOnError;\n // If the second argument is a key filter, return the mutation results for all\n // filtered keys.\n if (isFunction(_key)) {\n const keyFilter = _key;\n const matchedKeys = [];\n const it = cache.keys();\n for (const key of it){\n if (// Skip the special useSWRInfinite and useSWRSubscription keys.\n !/^\\$(inf|sub)\\$/.test(key) && keyFilter(cache.get(key)._k)) {\n matchedKeys.push(key);\n }\n }\n return Promise.all(matchedKeys.map(mutateByKey));\n }\n return mutateByKey(_key);\n async function mutateByKey(_k) {\n // Serialize key\n const [key] = serialize(_k);\n if (!key) return;\n const [get, set] = createCacheHelper(cache, key);\n const [EVENT_REVALIDATORS, MUTATION, FETCH, PRELOAD] = SWRGlobalState.get(cache);\n const startRevalidate = ()=>{\n const revalidators = EVENT_REVALIDATORS[key];\n const revalidate = isFunction(options.revalidate) ? options.revalidate(get().data, _k) : options.revalidate !== false;\n if (revalidate) {\n // Invalidate the key by deleting the concurrent request markers so new\n // requests will not be deduped.\n delete FETCH[key];\n delete PRELOAD[key];\n if (revalidators && revalidators[0]) {\n return revalidators[0](revalidateEvents.MUTATE_EVENT).then(()=>get().data);\n }\n }\n return get().data;\n };\n // If there is no new data provided, revalidate the key with current state.\n if (args.length < 3) {\n // Revalidate and broadcast state.\n return startRevalidate();\n }\n let data = _data;\n let error;\n let isError = false;\n // Update global timestamps.\n const beforeMutationTs = getTimestamp();\n MUTATION[key] = [\n beforeMutationTs,\n 0\n ];\n const hasOptimisticData = !isUndefined(optimisticData);\n const state = get();\n // `displayedData` is the current value on screen. It could be the optimistic value\n // that is going to be overridden by a `committedData`, or get reverted back.\n // `committedData` is the validated value that comes from a fetch or mutation.\n const displayedData = state.data;\n const currentData = state._c;\n const committedData = isUndefined(currentData) ? displayedData : currentData;\n // Do optimistic data update.\n if (hasOptimisticData) {\n optimisticData = isFunction(optimisticData) ? optimisticData(committedData, displayedData) : optimisticData;\n // When we set optimistic data, backup the current committedData data in `_c`.\n set({\n data: optimisticData,\n _c: committedData\n });\n }\n if (isFunction(data)) {\n // `data` is a function, call it passing current cache value.\n try {\n data = data(committedData);\n } catch (err) {\n // If it throws an error synchronously, we shouldn't update the cache.\n error = err;\n isError = true;\n }\n }\n // `data` is a promise/thenable, resolve the final data first.\n if (data && isPromiseLike(data)) {\n // This means that the mutation is async, we need to check timestamps to\n // avoid race conditions.\n data = await data.catch((err)=>{\n error = err;\n isError = true;\n });\n // Check if other mutations have occurred since we've started this mutation.\n // If there's a race we don't update cache or broadcast the change,\n // just return the data.\n if (beforeMutationTs !== MUTATION[key][0]) {\n if (isError) throw error;\n return data;\n } else if (isError && hasOptimisticData && rollbackOnError(error)) {\n // Rollback. Always populate the cache in this case but without\n // transforming the data.\n populateCache = true;\n // Reset data to be the latest committed data, and clear the `_c` value.\n set({\n data: committedData,\n _c: UNDEFINED\n });\n }\n }\n // If we should write back the cache after request.\n if (populateCache) {\n if (!isError) {\n // Transform the result into data.\n if (isFunction(populateCache)) {\n const populateCachedData = populateCache(data, committedData);\n set({\n data: populateCachedData,\n error: UNDEFINED,\n _c: UNDEFINED\n });\n } else {\n // Only update cached data and reset the error if there's no error. Data can be `undefined` here.\n set({\n data,\n error: UNDEFINED,\n _c: UNDEFINED\n });\n }\n }\n }\n // Reset the timestamp to mark the mutation has ended.\n MUTATION[key][1] = getTimestamp();\n // Update existing SWR Hooks' internal states:\n Promise.resolve(startRevalidate()).then(()=>{\n // The mutation and revalidation are ended, we can clear it since the data is\n // not an optimistic value anymore.\n set({\n _c: UNDEFINED\n });\n });\n // Throw error or return data\n if (isError) {\n if (throwOnError) throw error;\n return;\n }\n return data;\n }\n}\n\nconst revalidateAllKeys = (revalidators, type)=>{\n for(const key in revalidators){\n if (revalidators[key][0]) revalidators[key][0](type);\n }\n};\nconst initCache = (provider, options)=>{\n // The global state for a specific provider will be used to deduplicate\n // requests and store listeners. As well as a mutate function that is bound to\n // the cache.\n // The provider's global state might be already initialized. Let's try to get the\n // global state associated with the provider first.\n if (!SWRGlobalState.has(provider)) {\n const opts = mergeObjects(defaultConfigOptions, options);\n // If there's no global state bound to the provider, create a new one with the\n // new mutate function.\n const EVENT_REVALIDATORS = Object.create(null);\n const mutate = internalMutate.bind(UNDEFINED, provider);\n let unmount = noop;\n const subscriptions = Object.create(null);\n const subscribe = (key, callback)=>{\n const subs = subscriptions[key] || [];\n subscriptions[key] = subs;\n subs.push(callback);\n return ()=>subs.splice(subs.indexOf(callback), 1);\n };\n const setter = (key, value, prev)=>{\n provider.set(key, value);\n const subs = subscriptions[key];\n if (subs) {\n for (const fn of subs){\n fn(value, prev);\n }\n }\n };\n const initProvider = ()=>{\n if (!SWRGlobalState.has(provider)) {\n // Update the state if it's new, or if the provider has been extended.\n SWRGlobalState.set(provider, [\n EVENT_REVALIDATORS,\n Object.create(null),\n Object.create(null),\n Object.create(null),\n mutate,\n setter,\n subscribe\n ]);\n if (!IS_SERVER) {\n // When listening to the native events for auto revalidations,\n // we intentionally put a delay (setTimeout) here to make sure they are\n // fired after immediate JavaScript executions, which can be\n // React's state updates.\n // This avoids some unnecessary revalidations such as\n // https://github.com/vercel/swr/issues/1680.\n const releaseFocus = opts.initFocus(setTimeout.bind(UNDEFINED, revalidateAllKeys.bind(UNDEFINED, EVENT_REVALIDATORS, revalidateEvents.FOCUS_EVENT)));\n const releaseReconnect = opts.initReconnect(setTimeout.bind(UNDEFINED, revalidateAllKeys.bind(UNDEFINED, EVENT_REVALIDATORS, revalidateEvents.RECONNECT_EVENT)));\n unmount = ()=>{\n // eslint-disable-next-line @typescript-eslint/no-unused-expressions\n releaseFocus && releaseFocus();\n // eslint-disable-next-line @typescript-eslint/no-unused-expressions\n releaseReconnect && releaseReconnect();\n // When un-mounting, we need to remove the cache provider from the state\n // storage too because it's a side-effect. Otherwise, when re-mounting we\n // will not re-register those event listeners.\n SWRGlobalState.delete(provider);\n };\n }\n }\n };\n initProvider();\n // This is a new provider, we need to initialize it and setup DOM events\n // listeners for `focus` and `reconnect` actions.\n // We might want to inject an extra layer on top of `provider` in the future,\n // such as key serialization, auto GC, etc.\n // For now, it's just a `Map` interface without any modifications.\n return [\n provider,\n mutate,\n initProvider,\n unmount\n ];\n }\n return [\n provider,\n SWRGlobalState.get(provider)[4]\n ];\n};\n\n// error retry\nconst onErrorRetry = (_, __, config, revalidate, opts)=>{\n const maxRetryCount = config.errorRetryCount;\n const currentRetryCount = opts.retryCount;\n // Exponential backoff\n const timeout = ~~((Math.random() + 0.5) * (1 << (currentRetryCount < 8 ? currentRetryCount : 8))) * config.errorRetryInterval;\n if (!isUndefined(maxRetryCount) && currentRetryCount > maxRetryCount) {\n return;\n }\n setTimeout(revalidate, timeout, opts);\n};\nconst compare = dequal;\n// Default cache provider\nconst [cache, mutate] = initCache(new Map());\n// Default config\nconst defaultConfig = mergeObjects({\n // events\n onLoadingSlow: noop,\n onSuccess: noop,\n onError: noop,\n onErrorRetry,\n onDiscarded: noop,\n // switches\n revalidateOnFocus: true,\n revalidateOnReconnect: true,\n revalidateIfStale: true,\n shouldRetryOnError: true,\n // timeouts\n errorRetryInterval: slowConnection ? 10000 : 5000,\n focusThrottleInterval: 5 * 1000,\n dedupingInterval: 2 * 1000,\n loadingTimeout: slowConnection ? 5000 : 3000,\n // providers\n compare,\n isPaused: ()=>false,\n cache,\n mutate,\n fallback: {}\n}, // use web preset by default\npreset);\n\nconst mergeConfigs = (a, b)=>{\n // Need to create a new object to avoid mutating the original here.\n const v = mergeObjects(a, b);\n // If two configs are provided, merge their `use` and `fallback` options.\n if (b) {\n const { use: u1, fallback: f1 } = a;\n const { use: u2, fallback: f2 } = b;\n if (u1 && u2) {\n v.use = u1.concat(u2);\n }\n if (f1 && f2) {\n v.fallback = mergeObjects(f1, f2);\n }\n }\n return v;\n};\n\nconst SWRConfigContext = createContext({});\nconst SWRConfig = (props)=>{\n const { value } = props;\n const parentConfig = useContext(SWRConfigContext);\n const isFunctionalConfig = isFunction(value);\n const config = useMemo(()=>isFunctionalConfig ? value(parentConfig) : value, [\n isFunctionalConfig,\n parentConfig,\n value\n ]);\n // Extend parent context values and middleware.\n const extendedConfig = useMemo(()=>isFunctionalConfig ? config : mergeConfigs(parentConfig, config), [\n isFunctionalConfig,\n parentConfig,\n config\n ]);\n // Should not use the inherited provider.\n const provider = config && config.provider;\n // initialize the cache only on first access.\n const cacheContextRef = useRef(UNDEFINED);\n if (provider && !cacheContextRef.current) {\n cacheContextRef.current = initCache(provider(extendedConfig.cache || cache), config);\n }\n const cacheContext = cacheContextRef.current;\n // Override the cache if a new provider is given.\n if (cacheContext) {\n extendedConfig.cache = cacheContext[0];\n extendedConfig.mutate = cacheContext[1];\n }\n // Unsubscribe events.\n useIsomorphicLayoutEffect(()=>{\n if (cacheContext) {\n // eslint-disable-next-line @typescript-eslint/no-unused-expressions\n cacheContext[2] && cacheContext[2]();\n return cacheContext[3];\n }\n }, []);\n return createElement(SWRConfigContext.Provider, mergeObjects(props, {\n value: extendedConfig\n }));\n};\n\nexport { noop as A, isPromiseLike as B, IS_SERVER as I, OBJECT as O, SWRConfigContext as S, UNDEFINED as U, isFunction as a, SWRGlobalState as b, cache as c, defaultConfig as d, isUndefined as e, mergeConfigs as f, SWRConfig as g, initCache as h, isWindowDefined as i, mutate as j, compare as k, stableHash as l, mergeObjects as m, internalMutate as n, getTimestamp as o, preset as p, defaultConfigOptions as q, IS_REACT_LEGACY as r, serialize as s, rAF as t, useIsomorphicLayoutEffect as u, slowConnection as v, isDocumentDefined as w, isLegacyDeno as x, hasRequestAnimationFrame as y, createCacheHelper as z };\n","const INFINITE_PREFIX = '$inf$';\n\nexport { INFINITE_PREFIX };\n","import { i as isWindowDefined, a as isFunction, S as SWRConfigContext, m as mergeObjects, d as defaultConfig, s as serialize, b as SWRGlobalState, c as cache, e as isUndefined, I as IS_SERVER, f as mergeConfigs } from './config-context-12s-CCVTDPOP.mjs';\nexport { r as IS_REACT_LEGACY, O as OBJECT, g as SWRConfig, U as UNDEFINED, k as compare, z as createCacheHelper, q as defaultConfigOptions, o as getTimestamp, y as hasRequestAnimationFrame, h as initCache, n as internalMutate, w as isDocumentDefined, x as isLegacyDeno, B as isPromiseLike, j as mutate, A as noop, p as preset, t as rAF, v as slowConnection, l as stableHash, u as useIsomorphicLayoutEffect } from './config-context-12s-CCVTDPOP.mjs';\nimport * as revalidateEvents from './events.mjs';\nexport { revalidateEvents };\nimport { INFINITE_PREFIX } from './constants.mjs';\nexport { INFINITE_PREFIX } from './constants.mjs';\nimport React, { useContext, useMemo } from 'react';\nexport * from './types.mjs';\n\n// @ts-expect-error\nconst enableDevtools = isWindowDefined && window.__SWR_DEVTOOLS_USE__;\nconst use = enableDevtools ? window.__SWR_DEVTOOLS_USE__ : [];\nconst setupDevTools = ()=>{\n if (enableDevtools) {\n // @ts-expect-error\n window.__SWR_DEVTOOLS_REACT__ = React;\n }\n};\n\nconst normalize = (args)=>{\n return isFunction(args[1]) ? [\n args[0],\n args[1],\n args[2] || {}\n ] : [\n args[0],\n null,\n (args[1] === null ? args[2] : args[1]) || {}\n ];\n};\n\nconst useSWRConfig = ()=>{\n const parentConfig = useContext(SWRConfigContext);\n const mergedConfig = useMemo(()=>mergeObjects(defaultConfig, parentConfig), [\n parentConfig\n ]);\n return mergedConfig;\n};\n\nconst preload = (key_, fetcher)=>{\n // preload should be a no-op on the server\n if (IS_SERVER) {\n return undefined;\n }\n const [key, fnArg] = serialize(key_);\n const [, , , PRELOAD] = SWRGlobalState.get(cache);\n // Prevent preload to be called multiple times before used.\n if (PRELOAD[key]) return PRELOAD[key];\n const req = fetcher(fnArg);\n PRELOAD[key] = req;\n return req;\n};\nconst middleware = (useSWRNext)=>(key_, fetcher_, config)=>{\n // fetcher might be a sync function, so this should not be an async function\n const fetcher = fetcher_ && ((...args)=>{\n const [key] = serialize(key_);\n const [, , , PRELOAD] = SWRGlobalState.get(cache);\n if (key.startsWith(INFINITE_PREFIX)) {\n // we want the infinite fetcher to be called.\n // handling of the PRELOAD cache happens there.\n return fetcher_(...args);\n }\n const req = PRELOAD[key];\n if (isUndefined(req)) return fetcher_(...args);\n delete PRELOAD[key];\n return req;\n });\n return useSWRNext(key_, fetcher, config);\n };\n\nconst BUILT_IN_MIDDLEWARE = use.concat(middleware);\n\n// It's tricky to pass generic types as parameters, so we just directly override\n// the types here.\nconst withArgs = (hook)=>{\n return function useSWRArgs(...args) {\n // Get the default and inherited configuration.\n const fallbackConfig = useSWRConfig();\n // Normalize arguments.\n const [key, fn, _config] = normalize(args);\n // Merge configurations.\n const config = mergeConfigs(fallbackConfig, _config);\n // Apply middleware\n let next = hook;\n const { use } = config;\n const middleware = (use || []).concat(BUILT_IN_MIDDLEWARE);\n for(let i = middleware.length; i--;){\n next = middleware[i](next);\n }\n return next(key, fn || config.fetcher || null, config);\n };\n};\n\n// Add a callback function to a list of keyed callback functions and return\n// the unsubscribe function.\nconst subscribeCallback = (key, callbacks, callback)=>{\n const keyedRevalidators = callbacks[key] || (callbacks[key] = []);\n keyedRevalidators.push(callback);\n return ()=>{\n const index = keyedRevalidators.indexOf(callback);\n if (index >= 0) {\n // O(1): faster than splice\n keyedRevalidators[index] = keyedRevalidators[keyedRevalidators.length - 1];\n keyedRevalidators.pop();\n }\n };\n};\n\n// Create a custom hook with a middleware\nconst withMiddleware = (useSWR, middleware)=>{\n return (...args)=>{\n const [key, fn, config] = normalize(args);\n const uses = (config.use || []).concat(middleware);\n return useSWR(key, fn, {\n ...config,\n use: uses\n });\n };\n};\n\nsetupDevTools();\n\nexport { IS_SERVER, SWRGlobalState, cache, defaultConfig, isFunction, isUndefined, isWindowDefined, mergeConfigs, mergeObjects, normalize, preload, serialize, subscribeCallback, useSWRConfig, withArgs, withMiddleware };\n","import React, { useRef, useMemo, useCallback, useDebugValue } from 'react';\nimport { useSyncExternalStore } from 'use-sync-external-store/shim';\nimport { UNDEFINED as UNDEFINED$1, OBJECT as OBJECT$1, SWRConfig as SWRConfig$1, defaultConfig, withArgs, SWRGlobalState, serialize as serialize$1, createCacheHelper, isUndefined as isUndefined$1, isPromiseLike, IS_SERVER, noop as noop$1, getTimestamp, isFunction as isFunction$1, revalidateEvents, internalMutate, useIsomorphicLayoutEffect, subscribeCallback, rAF, IS_REACT_LEGACY, mergeObjects } from '../_internal/index.mjs';\nexport { mutate, preload, useSWRConfig } from '../_internal/index.mjs';\n\n// Shared state between server components and client components\nconst noop = ()=>{};\n// Using noop() as the undefined value as undefined can be replaced\n// by something else. Prettier ignore and extra parentheses are necessary here\n// to ensure that tsc doesn't remove the __NOINLINE__ comment.\n// prettier-ignore\nconst UNDEFINED = /*#__NOINLINE__*/ noop();\nconst OBJECT = Object;\nconst isUndefined = (v)=>v === UNDEFINED;\nconst isFunction = (v)=>typeof v == 'function';\n\n// use WeakMap to store the object->key mapping\n// so the objects can be garbage collected.\n// WeakMap uses a hashtable under the hood, so the lookup\n// complexity is almost O(1).\nconst table = new WeakMap();\nconst getTypeName = (value)=>OBJECT.prototype.toString.call(value);\nconst isObjectTypeName = (typeName, type)=>typeName === `[object ${type}]`;\n// counter of the key\nlet counter = 0;\n// A stable hash implementation that supports:\n// - Fast and ensures unique hash properties\n// - Handles unserializable values\n// - Handles object key ordering\n// - Generates short results\n//\n// This is not a serialization function, and the result is not guaranteed to be\n// parsable.\nconst stableHash = (arg)=>{\n const type = typeof arg;\n const typeName = getTypeName(arg);\n const isDate = isObjectTypeName(typeName, 'Date');\n const isRegex = isObjectTypeName(typeName, 'RegExp');\n const isPlainObject = isObjectTypeName(typeName, 'Object');\n let result;\n let index;\n if (OBJECT(arg) === arg && !isDate && !isRegex) {\n // Object/function, not null/date/regexp. Use WeakMap to store the id first.\n // If it's already hashed, directly return the result.\n result = table.get(arg);\n if (result) return result;\n // Store the hash first for circular reference detection before entering the\n // recursive `stableHash` calls.\n // For other objects like set and map, we use this id directly as the hash.\n result = ++counter + '~';\n table.set(arg, result);\n if (Array.isArray(arg)) {\n // Array.\n result = '@';\n for(index = 0; index < arg.length; index++){\n result += stableHash(arg[index]) + ',';\n }\n table.set(arg, result);\n }\n if (isPlainObject) {\n // Object, sort keys.\n result = '#';\n const keys = OBJECT.keys(arg).sort();\n while(!isUndefined(index = keys.pop())){\n if (!isUndefined(arg[index])) {\n result += index + ':' + stableHash(arg[index]) + ',';\n }\n }\n table.set(arg, result);\n }\n } else {\n result = isDate ? arg.toJSON() : type == 'symbol' ? arg.toString() : type == 'string' ? JSON.stringify(arg) : '' + arg;\n }\n return result;\n};\n\nconst serialize = (key)=>{\n if (isFunction(key)) {\n try {\n key = key();\n } catch (err) {\n // dependencies not ready\n key = '';\n }\n }\n // Use the original key as the argument of fetcher. This can be a string or an\n // array of values.\n const args = key;\n // If key is not falsy, or not an empty array, hash it.\n key = typeof key == 'string' ? key : (Array.isArray(key) ? key.length : key) ? stableHash(key) : '';\n return [\n key,\n args\n ];\n};\n\nconst unstable_serialize = (key)=>serialize(key)[0];\n\n/// <reference types=\"react/experimental\" />\nconst use = React.use || // This extra generic is to avoid TypeScript mixing up the generic and JSX sytax\n// and emitting an error.\n// We assume that this is only for the `use(thenable)` case, not `use(context)`.\n// https://github.com/facebook/react/blob/aed00dacfb79d17c53218404c52b1c7aa59c4a89/packages/react-server/src/ReactFizzThenable.js#L45\n((thenable)=>{\n switch(thenable.status){\n case 'pending':\n throw thenable;\n case 'fulfilled':\n return thenable.value;\n case 'rejected':\n throw thenable.reason;\n default:\n thenable.status = 'pending';\n thenable.then((v)=>{\n thenable.status = 'fulfilled';\n thenable.value = v;\n }, (e)=>{\n thenable.status = 'rejected';\n thenable.reason = e;\n });\n throw thenable;\n }\n});\nconst WITH_DEDUPE = {\n dedupe: true\n};\nconst resolvedUndef = Promise.resolve(UNDEFINED$1);\nconst sub = ()=>noop$1;\n/**\n * The core implementation of the useSWR hook.\n *\n * This is the main handler function that implements all SWR functionality including\n * data fetching, caching, revalidation, error handling, and state management.\n * It manages the complete lifecycle of SWR requests from initialization through\n * cleanup.\n *\n * Key responsibilities:\n * - Key serialization and normalization\n * - Cache state management and synchronization\n * - Automatic and manual revalidation\n * - Error handling and retry logic\n * - Suspense integration\n * - Loading state management\n * - Effect cleanup and memory management\n *\n * @template Data - The type of data returned by the fetcher\n * @template Error - The type of error that can be thrown\n *\n * @param _key - The SWR key (string, array, object, function, or falsy)\n * @param fetcher - The fetcher function to retrieve data, or null to disable fetching\n * @param config - Complete SWR configuration object with both public and internal options\n *\n * @returns SWRResponse object containing data, error, mutate function, and loading states\n *\n * @internal This is the internal implementation. Use `useSWR` instead.\n */ const useSWRHandler = (_key, fetcher, config)=>{\n const { cache, compare, suspense, fallbackData, revalidateOnMount, revalidateIfStale, refreshInterval, refreshWhenHidden, refreshWhenOffline, keepPreviousData, strictServerPrefetchWarning } = config;\n const [EVENT_REVALIDATORS, MUTATION, FETCH, PRELOAD] = SWRGlobalState.get(cache);\n // `key` is the identifier of the SWR internal state,\n // `fnArg` is the argument/arguments parsed from the key, which will be passed\n // to the fetcher.\n // All of them are derived from `_key`.\n const [key, fnArg] = serialize$1(_key);\n // If it's the initial render of this hook.\n const initialMountedRef = useRef(false);\n // If the hook is unmounted already. This will be used to prevent some effects\n // to be called after unmounting.\n const unmountedRef = useRef(false);\n // Refs to keep the key and config.\n const keyRef = useRef(key);\n const fetcherRef = useRef(fetcher);\n const configRef = useRef(config);\n const getConfig = ()=>configRef.current;\n const isActive = ()=>getConfig().isVisible() && getConfig().isOnline();\n const [getCache, setCache, subscribeCache, getInitialCache] = createCacheHelper(cache, key);\n const stateDependencies = useRef({}).current;\n // Resolve the fallback data from either the inline option, or the global provider.\n // If it's a promise, we simply let React suspend and resolve it for us.\n const fallback = isUndefined$1(fallbackData) ? isUndefined$1(config.fallback) ? UNDEFINED$1 : config.fallback[key] : fallbackData;\n const isEqual = (prev, current)=>{\n for(const _ in stateDependencies){\n const t = _;\n if (t === 'data') {\n if (!compare(prev[t], current[t])) {\n if (!isUndefined$1(prev[t])) {\n return false;\n }\n if (!compare(returnedData, current[t])) {\n return false;\n }\n }\n } else {\n if (current[t] !== prev[t]) {\n return false;\n }\n }\n }\n return true;\n };\n const isInitialMount = !initialMountedRef.current;\n const getSnapshot = useMemo(()=>{\n const cachedData = getCache();\n const initialData = getInitialCache();\n const getSelectedCache = (state)=>{\n // We only select the needed fields from the state.\n const snapshot = mergeObjects(state);\n delete snapshot._k;\n const shouldStartRequest = (()=>{\n if (!key) return false;\n if (!fetcher) return false;\n // If it's paused, we skip revalidation.\n if (getConfig().isPaused()) return false;\n // If `revalidateOnMount` is set, we take the value directly.\n if (isInitialMount && !isUndefined$1(revalidateOnMount)) return revalidateOnMount;\n const data = !isUndefined$1(fallback) ? fallback : snapshot.data;\n if (suspense) return isUndefined$1(data) || revalidateIfStale;\n return isUndefined$1(data) || revalidateIfStale;\n })();\n if (!shouldStartRequest) {\n return snapshot;\n }\n return {\n isValidating: true,\n isLoading: true,\n ...snapshot\n };\n };\n const clientSnapshot = getSelectedCache(cachedData);\n const serverSnapshot = cachedData === initialData ? clientSnapshot : getSelectedCache(initialData);\n // To make sure that we are returning the same object reference to avoid\n // unnecessary re-renders, we keep the previous snapshot and use deep\n // comparison to check if we need to return a new one.\n let memorizedSnapshot = clientSnapshot;\n return [\n ()=>{\n const newSnapshot = getSelectedCache(getCache());\n const compareResult = isEqual(newSnapshot, memorizedSnapshot);\n if (compareResult) {\n // Mentally, we should always return the `memorizedSnapshot` here\n // as there's no change between the new and old snapshots.\n // However, since the `isEqual` function only compares selected fields,\n // the values of the unselected fields might be changed. That's\n // simply because we didn't track them.\n // To support the case in https://github.com/vercel/swr/pull/2576,\n // we need to update these fields in the `memorizedSnapshot` too\n // with direct mutations to ensure the snapshot is always up-to-date\n // even for the unselected fields, but only trigger re-renders when\n // the selected fields are changed.\n memorizedSnapshot.data = newSnapshot.data;\n memorizedSnapshot.isLoading = newSnapshot.isLoading;\n memorizedSnapshot.isValidating = newSnapshot.isValidating;\n memorizedSnapshot.error = newSnapshot.error;\n return memorizedSnapshot;\n } else {\n memorizedSnapshot = newSnapshot;\n return newSnapshot;\n }\n },\n ()=>serverSnapshot\n ];\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [\n cache,\n key\n ]);\n // Get the current state that SWR should return.\n const cached = useSyncExternalStore(useCallback((callback)=>subscribeCache(key, (current, prev)=>{\n if (!isEqual(prev, current)) callback();\n }), // eslint-disable-next-line react-hooks/exhaustive-deps\n [\n cache,\n key\n ]), getSnapshot[0], getSnapshot[1]);\n const hasRevalidator = EVENT_REVALIDATORS[key] && EVENT_REVALIDATORS[key].length > 0;\n const cachedData = cached.data;\n const data = isUndefined$1(cachedData) ? fallback && isPromiseLike(fallback) ? use(fallback) : fallback : cachedData;\n const error = cached.error;\n // Use a ref to store previously returned data. Use the initial data as its initial value.\n const laggyDataRef = useRef(data);\n const returnedData = keepPreviousData ? isUndefined$1(cachedData) ? isUndefined$1(laggyDataRef.current) ? data : laggyDataRef.current : cachedData : data;\n const hasKeyButNoData = key && isUndefined$1(data);\n const hydrationRef = useRef(null);\n // Note: the conditionally hook call is fine because the environment\n // `IS_SERVER` never changes.\n // @ts-expect-error -- use hydrationRef directly\n !IS_SERVER && // getServerSnapshot is only called during hydration\n // eslint-disable-next-line react-hooks/rules-of-hooks\n useSyncExternalStore(sub, ()=>{\n hydrationRef.current = false;\n return hydrationRef;\n }, ()=>{\n hydrationRef.current = true;\n return hydrationRef;\n });\n const isHydration = hydrationRef.current;\n // During the initial SSR render, warn if the key has no data pre-fetched via:\n // - fallback data\n // - preload calls\n // - initial data from the cache provider\n // We only warn once for each key during Hydration.\n if (strictServerPrefetchWarning && isHydration && !suspense && hasKeyButNoData) {\n console.warn(`Missing pre-initiated data for serialized key \"${key}\" during server-side rendering. Data fetching should be initiated on the server and provided to SWR via fallback data. You can set \"strictServerPrefetchWarning: false\" to disable this warning.`);\n }\n // Resolve the default validating state:\n // If it's able to validate, and it should revalidate when mount, this will be true.\n // - Suspense mode and there's stale data for the initial render.\n // - Not suspense mode and there is no fallback data and `revalidateIfStale` is enabled.\n // - `revalidateIfStale` is enabled but `data` is not defined.\n const shouldDoInitialRevalidation = (()=>{\n if (!key || !fetcher) return false;\n // If it's paused, we skip revalidation.\n if (getConfig().isPaused()) return false;\n // if a key already has revalidators and also has error, we should not trigger revalidation\n if (hasRevalidator && !isUndefined$1(error)) return false;\n // If `revalidateOnMount` is set, we take the value directly.\n if (isInitialMount && !isUndefined$1(revalidateOnMount)) return revalidateOnMount;\n // Under suspense mode, it will always fetch on render if there is no\n // stale data so no need to revalidate immediately mount it again.\n // If data exists, only revalidate if `revalidateIfStale` is true.\n if (suspense) return isUndefined$1(data) ? false : revalidateIfStale;\n // If there is no stale data, we need to revalidate when mount;\n // If `revalidateIfStale` is set to true, we will always revalidate.\n return isUndefined$1(data) || revalidateIfStale;\n })();\n const defaultValidatingState = isInitialMount && shouldDoInitialRevalidation;\n const isValidating = isUndefined$1(cached.isValidating) ? defaultValidatingState : cached.isValidating;\n const isLoading = isUndefined$1(cached.isLoading) ? defaultValidatingState : cached.isLoading;\n // The revalidation function is a carefully crafted wrapper of the original\n // `fetcher`, to correctly handle the many edge cases.\n const revalidate = useCallback(async (revalidateOpts)=>{\n const currentFetcher = fetcherRef.current;\n if (!key || !currentFetcher || unmountedRef.current || getConfig().isPaused()) {\n return false;\n }\n let newData;\n let startAt;\n let loading = true;\n const opts = revalidateOpts || {};\n // If there is no ongoing concurrent request, or `dedupe` is not set, a\n // new request should be initiated.\n const shouldStartNewRequest = !FETCH[key] || !opts.dedupe;\n /*\n For React 17\n Do unmount check for calls:\n If key has changed during the revalidation, or the component has been\n unmounted, old dispatch and old event callbacks should not take any\n effect\n\n For React 18\n only check if key has changed\n https://github.com/reactwg/react-18/discussions/82\n */ const callbackSafeguard = ()=>{\n if (IS_REACT_LEGACY) {\n return !unmountedRef.current && key === keyRef.current && initialMountedRef.current;\n }\n return key === keyRef.current;\n };\n // The final state object when the request finishes.\n const finalState = {\n isValidating: false,\n isLoading: false\n };\n const finishRequestAndUpdateState = ()=>{\n setCache(finalState);\n };\n const cleanupState = ()=>{\n // Check if it's still the same request before deleting it.\n const requestInfo = FETCH[key];\n if (requestInfo && requestInfo[1] === startAt) {\n delete FETCH[key];\n }\n };\n // Start fetching. Change the `isValidating` state, update the cache.\n const initialState = {\n isValidating: true\n };\n // It is in the `isLoading` state, if and only if there is no cached data.\n // This bypasses fallback data and laggy data.\n if (isUndefined$1(getCache().data)) {\n initialState.isLoading = true;\n }\n try {\n if (shouldStartNewRequest) {\n setCache(initialState);\n // If no cache is being rendered currently (it shows a blank page),\n // we trigger the loading slow event.\n if (config.loadingTimeout && isUndefined$1(getCache().data)) {\n setTimeout(()=>{\n if (loading && callbackSafeguard()) {\n getConfig().onLoadingSlow(key, config);\n }\n }, config.loadingTimeout);\n }\n // Start the request and save the timestamp.\n // Key must be truthy if entering here.\n FETCH[key] = [\n currentFetcher(fnArg),\n getTimestamp()\n ];\n }\n // Wait until the ongoing request is done. Deduplication is also\n // considered here.\n ;\n [newData, startAt] = FETCH[key];\n newData = await newData;\n if (shouldStartNewRequest) {\n // If the request isn't interrupted, clean it up after the\n // deduplication interval.\n setTimeout(cleanupState, config.dedupingInterval);\n }\n // If there're other ongoing request(s), started after the current one,\n // we need to ignore the current one to avoid possible race conditions:\n // req1------------------>res1 (current one)\n // req2---------------->res2\n // the request that fired later will always be kept.\n // The timestamp maybe be `undefined` or a number\n if (!FETCH[key] || FETCH[key][1] !== startAt) {\n if (shouldStartNewRequest) {\n if (callbackSafeguard()) {\n getConfig().onDiscarded(key);\n }\n }\n return false;\n }\n // Clear error.\n finalState.error = UNDEFINED$1;\n // If there're other mutations(s), that overlapped with the current revalidation:\n // case 1:\n // req------------------>res\n // mutate------>end\n // case 2:\n // req------------>res\n // mutate------>end\n // case 3:\n // req------------------>res\n // mutate-------...---------->\n // we have to ignore the revalidation result (res) because it's no longer fresh.\n // meanwhile, a new revalidation should be triggered when the mutation ends.\n const mutationInfo = MUTATION[key];\n if (!isUndefined$1(mutationInfo) && // case 1\n (startAt <= mutationInfo[0] || // case 2\n startAt <= mutationInfo[1] || // case 3\n mutationInfo[1] === 0)) {\n finishRequestAndUpdateState();\n if (shouldStartNewRequest) {\n if (callbackSafeguard()) {\n getConfig().onDiscarded(key);\n }\n }\n return false;\n }\n // Deep compare with the latest state to avoid extra re-renders.\n // For local state, compare and assign.\n const cacheData = getCache().data;\n // Since the compare fn could be custom fn\n // cacheData might be different from newData even when compare fn returns True\n finalState.data = compare(cacheData, newData) ? cacheData : newData;\n // Trigger the successful callback if it's the original request.\n if (shouldStartNewRequest) {\n if (callbackSafeguard()) {\n getConfig().onSuccess(newData, key, config);\n }\n }\n } catch (err) {\n cleanupState();\n const currentConfig = getConfig();\n const { shouldRetryOnError } = currentConfig;\n // Not paused, we continue handling the error. Otherwise, discard it.\n if (!currentConfig.isPaused()) {\n // Get a new error, don't use deep comparison for errors.\n finalState.error = err;\n // Error event and retry logic. Only for the actual request, not\n // deduped ones.\n if (shouldStartNewRequest && callbackSafeguard()) {\n currentConfig.onError(err, key, currentConfig);\n if (shouldRetryOnError === true || isFunction$1(shouldRetryOnError) && shouldRetryOnError(err)) {\n if (!getConfig().revalidateOnFocus || !getConfig().revalidateOnReconnect || isActive()) {\n // If it's inactive, stop. It will auto-revalidate when\n // refocusing or reconnecting.\n // When retrying, deduplication is always enabled.\n currentConfig.onErrorRetry(err, key, currentConfig, (_opts)=>{\n const revalidators = EVENT_REVALIDATORS[key];\n if (revalidators && revalidators[0]) {\n revalidators[0](revalidateEvents.ERROR_REVALIDATE_EVENT, _opts);\n }\n }, {\n retryCount: (opts.retryCount || 0) + 1,\n dedupe: true\n });\n }\n }\n }\n }\n }\n // Mark loading as stopped.\n loading = false;\n // Update the current hook's state.\n finishRequestAndUpdateState();\n return true;\n }, // `setState` is immutable, and `eventsCallback`, `fnArg`, and\n // `keyValidating` are depending on `key`, so we can exclude them from\n // the deps array.\n //\n // FIXME:\n // `fn` and `config` might be changed during the lifecycle,\n // but they might be changed every render like this.\n // `useSWR('key', () => fetch('/api/'), { suspense: true })`\n // So we omit the values from the deps array\n // even though it might cause unexpected behaviors.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [\n key,\n cache\n ]);\n // Similar to the global mutate but bound to the current cache and key.\n // `cache` isn't allowed to change during the lifecycle.\n const boundMutate = useCallback(// Use callback to make sure `keyRef.current` returns latest result every time\n (...args)=>{\n return internalMutate(cache, keyRef.current, ...args);\n }, // eslint-disable-next-line react-hooks/exhaustive-deps\n []);\n // The logic for updating refs.\n useIsomorphicLayoutEffect(()=>{\n fetcherRef.current = fetcher;\n configRef.current = config;\n // Handle laggy data updates. If there's cached data of the current key,\n // it'll be the correct reference.\n if (!isUndefined$1(cachedData)) {\n laggyDataRef.current = cachedData;\n }\n });\n // After mounted or key changed.\n useIsomorphicLayoutEffect(()=>{\n if (!key) return;\n const softRevalidate = revalidate.bind(UNDEFINED$1, WITH_DEDUPE);\n let nextFocusRevalidatedAt = 0;\n if (getConfig().revalidateOnFocus) {\n const initNow = Date.now();\n nextFocusRevalidatedAt = initNow + getConfig().focusThrottleInterval;\n }\n // Expose revalidators to global event listeners. So we can trigger\n // revalidation from the outside.\n const onRevalidate = (type, opts = {})=>{\n if (type == revalidateEvents.FOCUS_EVENT) {\n const now = Date.now();\n if (getConfig().revalidateOnFocus && now > nextFocusRevalidatedAt && isActive()) {\n nextFocusRevalidatedAt = now + getConfig().focusThrottleInterval;\n softRevalidate();\n }\n } else if (type == revalidateEvents.RECONNECT_EVENT) {\n if (getConfig().revalidateOnReconnect && isActive()) {\n softRevalidate();\n }\n } else if (type == revalidateEvents.MUTATE_EVENT) {\n return revalidate();\n } else if (type == revalidateEvents.ERROR_REVALIDATE_EVENT) {\n return revalidate(opts);\n }\n return;\n };\n const unsubEvents = subscribeCallback(key, EVENT_REVALIDATORS, onRevalidate);\n // Mark the component as mounted and update corresponding refs.\n unmountedRef.current = false;\n keyRef.current = key;\n initialMountedRef.current = true;\n // Keep the original key in the cache.\n setCache({\n _k: fnArg\n });\n // Trigger a revalidation\n if (shouldDoInitialRevalidation) {\n // Performance optimization: if a request is already in progress for this key,\n // skip the revalidation to avoid redundant work\n if (!FETCH[key]) {\n if (isUndefined$1(data) || IS_SERVER) {\n // Revalidate immediately.\n softRevalidate();\n } else {\n // Delay the revalidate if we have data to return so we won't block\n // rendering.\n rAF(softRevalidate);\n }\n }\n }\n return ()=>{\n // Mark it as unmounted.\n unmountedRef.current = true;\n unsubEvents();\n };\n }, [\n key\n ]);\n // Polling\n useIsomorphicLayoutEffect(()=>{\n let timer;\n function next() {\n // Use the passed interval\n // ...or invoke the function with the updated data to get the interval\n const interval = isFunction$1(refreshInterval) ? refreshInterval(getCache().data) : refreshInterval;\n // We only start the next interval if `refreshInterval` is not 0, and:\n // - `force` is true, which is the start of polling\n // - or `timer` is not 0, which means the effect wasn't canceled\n if (interval && timer !== -1) {\n timer = setTimeout(execute, interval);\n }\n }\n function execute() {\n // Check if it's OK to execute:\n // Only revalidate when the page is visible, online, and not errored.\n if (!getCache().error && (refreshWhenHidden || getConfig().isVisible()) && (refreshWhenOffline || getConfig().isOnline())) {\n revalidate(WITH_DEDUPE).then(next);\n } else {\n // Schedule the next interval to check again.\n next();\n }\n }\n next();\n return ()=>{\n if (timer) {\n clearTimeout(timer);\n timer = -1;\n }\n };\n }, [\n refreshInterval,\n refreshWhenHidden,\n refreshWhenOffline,\n key\n ]);\n // Display debug info in React DevTools.\n useDebugValue(returnedData);\n // In Suspense mode, we can't return the empty `data` state.\n // If there is an `error`, the `error` needs to be thrown to the error boundary.\n // If there is no `error`, the `revalidation` promise needs to be thrown to\n // the suspense boundary.\n if (suspense) {\n // SWR should throw when trying to use Suspense on the server with React 18,\n // without providing any fallback data. This causes hydration errors. See:\n // https://github.com/vercel/swr/issues/1832\n if (!IS_REACT_LEGACY && IS_SERVER && hasKeyButNoData) {\n throw new Error('Fallback data is required when using Suspense in SSR.');\n }\n // Always update fetcher and config refs even with the Suspense mode.\n if (hasKeyButNoData) {\n fetcherRef.current = fetcher;\n configRef.current = config;\n unmountedRef.current = false;\n }\n const req = PRELOAD[key];\n const mutateReq = !isUndefined$1(req) && hasKeyButNoData ? boundMutate(req) : resolvedUndef;\n use(mutateReq);\n if (!isUndefined$1(error) && hasKeyButNoData) {\n throw error;\n }\n const revalidation = hasKeyButNoData ? revalidate(WITH_DEDUPE) : resolvedUndef;\n if (!isUndefined$1(returnedData) && hasKeyButNoData) {\n // @ts-ignore modify react promise status\n revalidation.status = 'fulfilled';\n // @ts-ignore modify react promise value\n revalidation.value = true;\n }\n use(revalidation);\n }\n const swrResponse = {\n mutate: boundMutate,\n get data () {\n stateDependencies.data = true;\n return returnedData;\n },\n get error () {\n stateDependencies.error = true;\n return error;\n },\n get isValidating () {\n stateDependencies.isValidating = true;\n return isValidating;\n },\n get isLoading () {\n stateDependencies.isLoading = true;\n return isLoading;\n }\n };\n return swrResponse;\n};\nconst SWRConfig = OBJECT$1.defineProperty(SWRConfig$1, 'defaultValue', {\n value: defaultConfig\n});\n/**\n * A hook to fetch data.\n *\n * @see {@link https://swr.vercel.app}\n *\n * @example\n * ```jsx\n * import useSWR from 'swr'\n * function Profile() {\n * const { data, error, isLoading } = useSWR('/api/user', fetcher)\n * if (error) return <div>failed to load</div>\n * if (isLoading) return <div>loading...</div>\n * return <div>hello {data.name}!</div>\n * }\n * ```\n */ const useSWR = withArgs(useSWRHandler);\n\n// useSWR\n\nexport { SWRConfig, useSWR as default, unstable_serialize };\n","// SPDX-License-Identifier: MIT\n// Client for the Graffiticode data/compile API. Uses the platform API host derived from\n// the page's location (local console in dev, api.graffiticode.org in prod).\n\nfunction getApiUrl(): string {\n const host = window.document.location.host;\n return host.indexOf(\"localhost\") === 0\n ? \"http://localhost:3100\"\n : \"https://api.graffiticode.org\";\n}\n\nexport const getApiData = async ({\n accessToken,\n id,\n}: {\n accessToken?: string;\n id: string;\n}) => {\n const resp = await fetch(`${getApiUrl()}/data?id=${id}`, {\n headers: { Authorization: accessToken || \"\" },\n });\n const { status, error, data } = await resp.json();\n if (status !== \"success\") {\n throw new Error(`failed to get data ${id}: ${error?.message}`);\n }\n return data;\n};\n\nexport const postApiCompile = async ({\n accessToken,\n id,\n data,\n}: {\n accessToken?: string;\n id: string;\n data: any;\n}) => {\n const resp = await fetch(`${getApiUrl()}/compile`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n authorization: accessToken || \"\",\n \"x-graffiticode-storage-type\": \"persistent\",\n },\n body: JSON.stringify({ id, data }),\n });\n const out = await resp.json();\n if (out.status !== \"success\") {\n throw new Error(`failed to post compile ${id}: ${out.error?.message}`);\n }\n return out.data;\n};\n","// SPDX-License-Identifier: MIT\nimport { postApiCompile, getApiData } from \"../lib/api\";\n\nexport const compile = async ({\n accessToken,\n id,\n data,\n}: {\n accessToken?: string;\n id: string;\n data: any;\n}) => {\n // Empty data → recompile the full id; otherwise recompile with the code id only.\n const index = Object.keys(data).length > 0 ? 1 : 2;\n id = id.split(\"+\").slice(0, index).join(\"+\");\n return await postApiCompile({ accessToken, id, data });\n};\n\nexport const getData = async ({\n accessToken,\n id,\n}: {\n accessToken?: string;\n id: string;\n}) => {\n return await getApiData({ accessToken, id });\n};\n","// SPDX-License-Identifier: MIT\n//\n// View is the SHARED, inherited front-end harness. It manages form state, drives\n// compile/getData, reads its inputs from the URL search params, and posts state to the host\n// via window.parent.postMessage — so it works both embedded in an iframe and standalone. It\n// is parameterized by the language-specific `Form`: child languages import this `View` and\n// inject their own `Form` (the only language-specific UX). L0000 ships the base `Form` (JSON),\n// so its own embed mounts `<View Form={Form} />`.\n//\n// Compile/getData responses use the envelope `{ data, errors }`: successful output in `data`,\n// compile errors in `errors`. The View stores `data` as the form's data model (so recompiles\n// operate on real data, not the envelope) and threads `errors` to the Form alongside it.\n//\n// ── State ──────────────────────────────────────────────────────────────────────────────────\n//\n// The data model lives in React state and every `apply` re-renders. It used to live in an\n// EXTERNAL mutable store (`createState`) that React did not track, which meant a form seeded\n// from the `?data=` search param never appeared at all: the seed mutated the store from an\n// effect, nothing re-rendered, and the harness kept showing the empty `<div/>` it had already\n// committed. Keep state here, and keep the reducer PURE — it is re-run under StrictMode.\n//\n// ── The action protocol ────────────────────────────────────────────────────────────────────\n//\n// `init` replace the model (a fresh load)\n// `compiled` MERGE the compile result over the model. It must not replace: a compile response\n// carries only what the compiler produced, so replacing discards client-side state\n// (focus, in-progress entries) and re-initializes the whole form on every edit.\n// `update` a user edit; merges, and requests a recompile\n// `response` a learner's answer; merges, and requests a recompile\n// `focus` selection tracking; merges under `focus` and does NOT recompile\n//\n// `loaded` the stored model arriving from getData. Merges exactly like `compiled`; it is a\n// separate type only so the harness can tell an EXTERNAL load from the echo of an\n// edit the Form itself just reported (see `formModel` below).\n//\n// `response` and `focus` were previously unhandled, so they fell to the `default:` branch and\n// returned the model UNCHANGED — silently discarding every answer a learner typed into an\n// L0166/L0179 spreadsheet and every response an L0175 item collected.\n//\n// ── formModel: which model the Form is rendered from ───────────────────────────────────────\n//\n// A CONTROLLED Form (the default, `formModel: \"live\"`) renders whatever the model currently\n// says, so it must see every change — including its own edits coming back.\n//\n// An UNCONTROLLED Form owns its own editing state and only SEEDS from the model. L0166's\n// spreadsheet Form — which L0179 injects — is one: its TableEditor builds a ProseMirror\n// document from `interaction.cells` and, whenever that object's IDENTITY changes, rebuilds the\n// whole document and puts the caret back in A1. Feeding such a Form its own reported edits\n// re-seeds it on every keystroke commit: the grid visibly redraws and the selection jumps.\n//\n// L0166 never hits this because its state lives in an untracked closure that re-renders\n// nothing — the editor is seeded once and left alone. `formModel: \"loaded\"` makes that\n// deliberate rather than accidental: the Form renders from the model as last loaded from\n// OUTSIDE it (`init`, `loaded`), while `update`/`response` and the compile results they\n// trigger keep updating the live model for postMessage, recompiles, and reporting.\n//\n// A language whose Form needs different semantics for one of these passes `reduce`. It is\n// consulted FIRST and returns `undefined` for anything it does not claim, so a language adds\n// cases without restating the generic ones. This exists because L0179 injects L0166's\n// spreadsheet Form, whose `update` must merge cell text into `data.interaction.cells` rather\n// than onto the top level — a shape that has no business being hardcoded here.\nimport { useCallback, useEffect, useMemo, useReducer, useRef, useState } from \"react\";\nimport type { ComponentType, CSSProperties } from \"react\";\nimport useSWR from \"swr\";\nimport { compile, getData } from \"./swr/fetchers\";\nimport \"./index.css\";\n\nexport interface CompileError {\n message: string;\n from?: number;\n to?: number;\n}\n\nexport interface StateAction {\n type: string;\n args?: any;\n}\n\n/**\n * A language's extra reducer cases. Return the next data model to claim an action, or\n * `undefined` to fall through to the generic handling below.\n */\nexport type LanguageReducer = (data: any, action: StateAction) => any | undefined;\n\nexport interface FormProps {\n state: {\n data: any;\n errors: CompileError[];\n apply: (action: StateAction) => void;\n };\n}\n\nexport type FormComponent = ComponentType<FormProps>;\n\n/**\n * Which model the Form renders from.\n *\n * `live` — everything, including the Form's own edits coming back (a controlled Form).\n * `loaded` — only the model as last loaded from outside the Form (an uncontrolled Form that\n * seeds itself from the model and owns its editing state thereafter).\n */\nexport type FormModel = \"live\" | \"loaded\";\n\n/** Actions that represent a user changing the form, and so warrant a recompile. */\nconst RECOMPILE_ON = new Set([\"update\", \"response\"]);\n\n/**\n * Actions that carry a model from OUTSIDE the Form, and so may re-seed an uncontrolled one.\n * `compiled` is absent deliberately: after the initial load every compile is a response to an\n * edit the Form itself reported, and re-seeding from it is the flash this exists to stop.\n */\nconst EXTERNAL_LOAD = new Set([\"init\", \"loaded\"]);\n\n// Normalize a response into the { data, errors } envelope. Accepts a bare value (treated\n// as data with no errors) for backward/forward compatibility.\nfunction asEnvelope(payload: any): { data: any; errors: CompileError[] } {\n if (payload && typeof payload === \"object\" && Array.isArray(payload.errors)) {\n return { data: payload.data ?? null, errors: payload.errors };\n }\n return { data: payload, errors: [] };\n}\n\nfunction hasRenderable(data: any, errors: CompileError[]): boolean {\n if (errors.length > 0) return true;\n if (data === undefined || data === null) return false;\n if (typeof data === \"object\" && !Array.isArray(data) && Object.keys(data).length === 0) {\n return false;\n }\n return true;\n}\n\nfunction baseReduce(data: any, { type, args }: StateAction): any {\n switch (type) {\n case \"init\":\n return { ...args };\n case \"compiled\":\n case \"loaded\":\n case \"update\":\n case \"response\":\n return { ...data, ...args };\n case \"focus\":\n return { ...data, focus: args };\n default:\n console.error(`Unimplemented action type: ${type}`);\n return data;\n }\n}\n\ninterface ViewState {\n data: any;\n /**\n * What the Form is rendered from. Under `formModel: \"live\"` it is always `data`; under\n * `\"loaded\"` its IDENTITY only changes on an external load, which is what keeps an\n * uncontrolled Form from re-seeding itself on its own edits.\n */\n renderData: any;\n /** Bumped by each user edit. The compile effect keys off it, never off `data` itself. */\n compileSeq: number;\n}\n\nconst makeReducer =\n (reduce: LanguageReducer | undefined, formModel: FormModel) =>\n (prev: ViewState, action: StateAction): ViewState => {\n const claimed = reduce ? reduce(prev.data, action) : undefined;\n const data = claimed !== undefined ? claimed : baseReduce(prev.data, action);\n if (data === prev.data || JSON.stringify(data) === JSON.stringify(prev.data)) {\n return prev;\n }\n return {\n data,\n renderData:\n formModel === \"live\" || EXTERNAL_LOAD.has(action.type) ? data : prev.renderData,\n compileSeq: prev.compileSeq + (RECOMPILE_ON.has(action.type) ? 1 : 0),\n };\n };\n\nexport const View = ({\n Form,\n reduce,\n formModel = \"live\",\n}: {\n Form: FormComponent;\n reduce?: LanguageReducer;\n formModel?: FormModel;\n}) => {\n const [params] = useState(() => new URLSearchParams(window.location.search));\n const [id] = useState<string | undefined>(params.get(\"id\") ?? undefined);\n const [accessToken] = useState<string | undefined>(params.get(\"access_token\") ?? undefined);\n const [targetOrigin] = useState<string | undefined>(params.get(\"origin\") ?? undefined);\n const [errors, setErrors] = useState<CompileError[]>([]);\n\n const reducer = useMemo(() => makeReducer(reduce, formModel), [reduce, formModel]);\n const [state, apply] = useReducer(reducer, undefined, () => ({\n data: {},\n renderData: {},\n compileSeq: 0,\n }));\n const { data, renderData, compileSeq } = state;\n\n // Initialize from a `data` search param on first load.\n useEffect(() => {\n const seed = params.get(\"data\");\n if (seed) apply({ type: \"init\", args: JSON.parse(seed) });\n }, []);\n\n // Announce load to the host.\n useEffect(() => {\n if (targetOrigin) {\n window.parent.postMessage({ type: \"onload\", data }, targetOrigin);\n }\n }, []);\n\n // Post state to the host whenever it changes.\n useEffect(() => {\n if (targetOrigin) {\n window.parent.postMessage({ type: \"data-updated\", data }, targetOrigin);\n }\n }, [JSON.stringify(data)]);\n\n // Fetch stored data when an id is present.\n //\n // Revalidation is off: this is a one-shot load, and a background refetch on window focus\n // would re-apply the STORED model over whatever the learner has since entered — the form\n // silently reverting when you tab away and back.\n const getDataResp = useSWR(id ? { accessToken, id } : null, getData, {\n revalidateOnFocus: false,\n revalidateOnReconnect: false,\n revalidateIfStale: false,\n });\n\n // Apply the loaded data in an EFFECT. Applying it during render (as this used to) both\n // mutated state mid-render and re-ran on every subsequent render, because the SWR result\n // stays populated — the old code only escaped that loop by flipping its own fetch key to\n // null, which is what let a warm cache entry re-apply a stale model later.\n useEffect(() => {\n if (getDataResp.data === undefined) return;\n const env = asEnvelope(getDataResp.data);\n apply({ type: \"loaded\", args: env.data });\n setErrors(env.errors);\n }, [getDataResp.data]);\n\n // Recompile after a user edit.\n //\n // Deliberately NOT SWR: a compile is a mutation, not a cacheable query. Keying it on the\n // data (as this used to) meant returning a cell to a value it already held replayed an\n // OLDER compiled snapshot straight out of the cache, reverting the sheet. A bare request\n // with last-write-wins ordering has no cache to go stale.\n const latestCompile = useRef(0);\n useEffect(() => {\n if (compileSeq === 0 || !id) return;\n const seq = ++latestCompile.current;\n if (targetOrigin) {\n window.parent.postMessage({ focus: { type: \"update\", value: data } }, targetOrigin);\n }\n let cancelled = false;\n (async () => {\n try {\n const out = await compile({ accessToken, id, data });\n // Drop a response that a newer edit has already superseded, so a slow compile can\n // never overwrite a faster one that started later.\n if (cancelled || seq !== latestCompile.current) return;\n const env = asEnvelope(out);\n apply({ type: \"compiled\", args: env.data });\n setErrors(env.errors);\n } catch (err: any) {\n if (!cancelled && seq === latestCompile.current) {\n setErrors([{ message: String(err?.message ?? err) }]);\n }\n }\n })();\n return () => {\n cancelled = true;\n };\n }, [compileSeq]);\n\n // The Form sees `renderData`; everything else here (postMessage, recompiles) uses the live\n // `data`. They are the same object unless the language asked for `formModel: \"loaded\"`, and\n // the fallback covers the one case where they can disagree about EXISTENCE rather than\n // content: a model that arrived without ever passing through an external load.\n const formData = hasRenderable(renderData, []) ? renderData : data;\n const formState = useMemo(() => ({ data: formData, errors, apply }), [formData, errors]);\n\n // Render priority: real content first; otherwise surface why there's none.\n // A getData failure (e.g. a stale/expired token 401ing a public read) used to\n // fall through to a blank `<div/>` with no console output — indistinguishable\n // from \"still loading\" and impossible to diagnose. Show the error (and a\n // retry) instead. Once data has loaded, a later revalidation error is ignored\n // so the form isn't replaced by an error screen.\n const retry = useCallback(() => getDataResp.mutate(), [getDataResp]);\n\n if (hasRenderable(data, errors)) {\n return <Form state={formState} />;\n }\n if (getDataResp.error) {\n return (\n <div role=\"alert\" style={MESSAGE_STYLE}>\n <p style={{ margin: 0, fontWeight: 600 }}>Couldn’t load this form.</p>\n <p style={{ margin: \"4px 0 12px\", color: \"#555\" }}>\n {String((getDataResp.error as { message?: string })?.message ?? getDataResp.error)}\n </p>\n <button type=\"button\" style={RETRY_STYLE} onClick={retry}>\n Retry\n </button>\n </div>\n );\n }\n if (getDataResp.isLoading) {\n return (\n <div role=\"status\" aria-live=\"polite\" style={MESSAGE_STYLE}>\n Loading…\n </div>\n );\n }\n return <div />;\n};\n\nconst MESSAGE_STYLE: CSSProperties = {\n display: \"flex\",\n flexDirection: \"column\",\n alignItems: \"center\",\n justifyContent: \"center\",\n height: \"100%\",\n padding: \"24px\",\n textAlign: \"center\",\n font: \"14px/1.4 system-ui, sans-serif\",\n};\n\nconst RETRY_STYLE: CSSProperties = {\n padding: \"6px 14px\",\n border: \"1px solid #888\",\n borderRadius: \"4px\",\n background: \"#fff\",\n cursor: \"pointer\",\n};\n","// SPDX-License-Identifier: MIT\n//\n// L0000's base Form: renders compile errors when present, otherwise the compiled data\n// model as stringified JSON. This is the trivial default rendering; child languages\n// supply their own Form and inject it into the shared View instead.\nimport \"../../index.css\";\nimport type { FormProps, CompileError } from \"../../view\";\n\nfunction ErrorList({ errors }: { errors: CompileError[] }) {\n return (\n <div className=\"flex flex-col gap-2 font-mono text-xs\">\n {errors.map((error, i) => (\n <div\n key={i}\n className=\"rounded-md border border-red-200 bg-red-50 p-3 text-red-800\"\n >\n {error.message}\n {typeof error.from === \"number\" && error.from >= 0 && (\n <span className=\"ml-2 text-red-400\">\n [{error.from}\n {typeof error.to === \"number\" && error.to >= 0 ? `–${error.to}` : \"\"}]\n </span>\n )}\n </div>\n ))}\n </div>\n );\n}\n\nexport const Form = ({ state }: FormProps) => {\n const errors = state.errors ?? [];\n if (errors.length > 0) {\n return <ErrorList errors={errors} />;\n }\n const source = state.data;\n return (\n <pre className=\"rounded-md bg-zinc-50 text-zinc-900 text-xs font-mono p-4 overflow-auto\">\n {JSON.stringify(source, null, 2)}\n </pre>\n );\n};\n"],"names":["React","require$$0","is","x","y","objectIs","useState","useEffect","useLayoutEffect","useDebugValue","useSyncExternalStore$2","subscribe","getSnapshot","value","_useState","inst","forceUpdate","checkIfSnapshotChanged","latestGetSnapshot","nextValue","useSyncExternalStore$1","shim","useSyncExternalStoreShim_production","didWarnOld18Alpha","didWarnUncachedGetSnapshot","cachedValue","useSyncExternalStoreShim_development","shimModule","require$$1","FOCUS_EVENT","RECONNECT_EVENT","MUTATE_EVENT","ERROR_REVALIDATE_EVENT","has","dequal","foo","bar","ctor","len","SWRGlobalState","noop","UNDEFINED","OBJECT","isUndefined","v","isFunction","mergeObjects","a","b","isPromiseLike","EMPTY_CACHE","INITIAL_CACHE","STR_UNDEFINED","isWindowDefined","isDocumentDefined","isLegacyDeno","hasRequestAnimationFrame","createCacheHelper","cache","key","state","info","prev","online","isOnline","onWindowEvent","offWindowEvent","isVisible","visibilityState","initFocus","callback","initReconnect","onOnline","onOffline","preset","defaultConfigOptions","IS_REACT_LEGACY","IS_SERVER","rAF","f","useIsomorphicLayoutEffect","navigatorConnection","slowConnection","table","getTypeName","isObjectTypeName","typeName","type","counter","stableHash","arg","isDate","isRegex","isPlainObject","result","index","keys","serialize","args","__timestamp","getTimestamp","internalMutate","_key","_data","_opts","options","populateCache","rollbackOnErrorOption","optimisticData","rollbackOnError","error","throwOnError","keyFilter","matchedKeys","it","mutateByKey","_k","get","set","EVENT_REVALIDATORS","MUTATION","FETCH","PRELOAD","startRevalidate","revalidators","revalidateEvents.MUTATE_EVENT","data","isError","beforeMutationTs","hasOptimisticData","displayedData","currentData","committedData","err","populateCachedData","revalidateAllKeys","initCache","provider","opts","mutate","unmount","subscriptions","subs","setter","fn","initProvider","releaseFocus","revalidateEvents.FOCUS_EVENT","releaseReconnect","revalidateEvents.RECONNECT_EVENT","onErrorRetry","_","__","config","revalidate","maxRetryCount","currentRetryCount","timeout","compare","defaultConfig","mergeConfigs","u1","f1","u2","f2","SWRConfigContext","createContext","INFINITE_PREFIX","enableDevtools","use","setupDevTools","normalize","useSWRConfig","parentConfig","useContext","useMemo","middleware","useSWRNext","key_","fetcher_","req","BUILT_IN_MIDDLEWARE","withArgs","hook","fallbackConfig","_config","next","i","subscribeCallback","callbacks","keyedRevalidators","thenable","WITH_DEDUPE","resolvedUndef","UNDEFINED$1","sub","noop$1","useSWRHandler","fetcher","suspense","fallbackData","revalidateOnMount","revalidateIfStale","refreshInterval","refreshWhenHidden","refreshWhenOffline","keepPreviousData","strictServerPrefetchWarning","fnArg","serialize$1","initialMountedRef","useRef","unmountedRef","keyRef","fetcherRef","configRef","getConfig","isActive","getCache","setCache","subscribeCache","getInitialCache","stateDependencies","fallback","isUndefined$1","isEqual","current","t","returnedData","isInitialMount","cachedData","initialData","getSelectedCache","snapshot","clientSnapshot","serverSnapshot","memorizedSnapshot","newSnapshot","cached","useSyncExternalStore","useCallback","hasRevalidator","laggyDataRef","hasKeyButNoData","hydrationRef","isHydration","shouldDoInitialRevalidation","defaultValidatingState","isValidating","isLoading","revalidateOpts","currentFetcher","newData","startAt","loading","shouldStartNewRequest","callbackSafeguard","finalState","finishRequestAndUpdateState","cleanupState","requestInfo","initialState","mutationInfo","cacheData","currentConfig","shouldRetryOnError","isFunction$1","revalidateEvents.ERROR_REVALIDATE_EVENT","boundMutate","softRevalidate","nextFocusRevalidatedAt","unsubEvents","now","timer","interval","execute","mutateReq","revalidation","useSWR","getApiUrl","getApiData","accessToken","id","resp","status","postApiCompile","out","_a","compile","getData","RECOMPILE_ON","EXTERNAL_LOAD","asEnvelope","payload","hasRenderable","errors","baseReduce","makeReducer","reduce","formModel","action","claimed","View","Form","params","targetOrigin","setErrors","reducer","apply","useReducer","renderData","compileSeq","seed","getDataResp","env","latestCompile","seq","cancelled","formData","formState","retry","jsx","jsxs","MESSAGE_STYLE","RETRY_STYLE","ErrorList","source"],"mappings":";;;;;;;;;;;;;;;;AAWA,MAAIA,IAAQC;AACZ,WAASC,EAAGC,GAAGC,GAAG;AAChB,WAAQD,MAAMC,MAAYD,MAAN,KAAW,IAAIA,MAAM,IAAIC,MAAQD,MAAMA,KAAKC,MAAMA;AAAA,EACxE;AACA,MAAIC,IAA0B,OAAO,OAAO,MAA7B,aAAkC,OAAO,KAAKH,GAC3DI,IAAWN,EAAM,UACjBO,IAAYP,EAAM,WAClBQ,IAAkBR,EAAM,iBACxBS,IAAgBT,EAAM;AACxB,WAASU,EAAuBC,GAAWC,GAAa;AACtD,QAAIC,IAAQD,EAAW,GACrBE,IAAYR,EAAS,EAAE,MAAM,EAAE,OAAOO,GAAO,aAAaD,EAAW,GAAI,GACzEG,IAAOD,EAAU,CAAC,EAAE,MACpBE,IAAcF,EAAU,CAAC;AAC3B,WAAAN;AAAA,MACE,WAAY;AACV,QAAAO,EAAK,QAAQF,GACbE,EAAK,cAAcH,GACnBK,EAAuBF,CAAI,KAAKC,EAAY,EAAE,MAAMD,EAAI,CAAE;AAAA,MAChE;AAAA,MACI,CAACJ,GAAWE,GAAOD,CAAW;AAAA,IAClC,GACEL;AAAA,MACE,WAAY;AACV,eAAAU,EAAuBF,CAAI,KAAKC,EAAY,EAAE,M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MAAM;AACR,GAEMC,KAA6B;AAAA,EACjC,SAAS;AAAA,EACT,QAAQ;AAAA,EACR,cAAc;AAAA,EACd,YAAY;AAAA,EACZ,QAAQ;AACV;ACrUA,SAASC,GAAU,EAAE,QAAA9B,KAAsC;AACzD,SACE,gBAAA0B,EAAC,SAAI,WAAU,yCACZ,YAAO,IAAI,CAACnN,GAAO6E,MAClB,gBAAAuI;AAAA,IAAC;AAAA,IAAA;AAAA,MAEC,WAAU;AAAA,MAET,UAAA;AAAA,QAAApN,EAAM;AAAA,QACN,OAAOA,EAAM,QAAS,YAAYA,EAAM,QAAQ,KAC/C,gBAAAoN,GAAC,QAAA,EAAK,WAAU,qBAAoB,UAAA;AAAA,UAAA;AAAA,UAChCpN,EAAM;AAAA,UACP,OAAOA,EAAM,MAAO,YAAYA,EAAM,MAAM,IAAI,IAAIA,EAAM,EAAE,KAAK;AAAA,UAAG;AAAA,QAAA,EAAA,CACvE;AAAA,MAAA;AAAA,IAAA;AAAA,IARG6E;AAAA,EAAA,CAWR,GACH;AAEJ;AAEO,MAAMoH,KAAO,CAAC,EAAE,OAAAnP,QAAuB;AAC5C,QAAM2O,IAAS3O,EAAM,UAAU,CAAA;AAC/B,MAAI2O,EAAO,SAAS;AAClB,WAAO,gBAAA0B,EAACI,MAAU,QAAA9B,GAAgB;AAEpC,QAAM+B,IAAS1Q,EAAM;AACrB,SACE,gBAAAqQ,EAAC,SAAI,WAAU,2EACZ,eAAK,UAAUK,GAAQ,MAAM,CAAC,EAAA,CACjC;AAEJ;","x_google_ignoreList":[0,1,2,3,4,5,6,7,8]}
1
+ {"version":3,"file":"index.js","sources":["../../../node_modules/use-sync-external-store/cjs/use-sync-external-store-shim.production.js","../../../node_modules/use-sync-external-store/cjs/use-sync-external-store-shim.development.js","../../../node_modules/use-sync-external-store/shim/index.js","../../../node_modules/swr/dist/_internal/events.mjs","../../../node_modules/dequal/lite/index.mjs","../../../node_modules/swr/dist/_internal/config-context-12s-CCVTDPOP.mjs","../../../node_modules/swr/dist/_internal/constants.mjs","../../../node_modules/swr/dist/_internal/index.mjs","../../../node_modules/swr/dist/index/index.mjs","../src/lib/api.ts","../src/swr/fetchers.ts","../src/view.tsx","../src/components/form/Form.tsx"],"sourcesContent":["/**\n * @license React\n * use-sync-external-store-shim.production.js\n *\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n\"use strict\";\nvar React = require(\"react\");\nfunction is(x, y) {\n return (x === y && (0 !== x || 1 / x === 1 / y)) || (x !== x && y !== y);\n}\nvar objectIs = \"function\" === typeof Object.is ? Object.is : is,\n useState = React.useState,\n useEffect = React.useEffect,\n useLayoutEffect = React.useLayoutEffect,\n useDebugValue = React.useDebugValue;\nfunction useSyncExternalStore$2(subscribe, getSnapshot) {\n var value = getSnapshot(),\n _useState = useState({ inst: { value: value, getSnapshot: getSnapshot } }),\n inst = _useState[0].inst,\n forceUpdate = _useState[1];\n useLayoutEffect(\n function () {\n inst.value = value;\n inst.getSnapshot = getSnapshot;\n checkIfSnapshotChanged(inst) && forceUpdate({ inst: inst });\n },\n [subscribe, value, getSnapshot]\n );\n useEffect(\n function () {\n checkIfSnapshotChanged(inst) && forceUpdate({ inst: inst });\n return subscribe(function () {\n checkIfSnapshotChanged(inst) && forceUpdate({ inst: inst });\n });\n },\n [subscribe]\n );\n useDebugValue(value);\n return value;\n}\nfunction checkIfSnapshotChanged(inst) {\n var latestGetSnapshot = inst.getSnapshot;\n inst = inst.value;\n try {\n var nextValue = latestGetSnapshot();\n return !objectIs(inst, nextValue);\n } catch (error) {\n return !0;\n }\n}\nfunction useSyncExternalStore$1(subscribe, getSnapshot) {\n return getSnapshot();\n}\nvar shim =\n \"undefined\" === typeof window ||\n \"undefined\" === typeof window.document ||\n \"undefined\" === typeof window.document.createElement\n ? useSyncExternalStore$1\n : useSyncExternalStore$2;\nexports.useSyncExternalStore =\n void 0 !== React.useSyncExternalStore ? React.useSyncExternalStore : shim;\n","/**\n * @license React\n * use-sync-external-store-shim.development.js\n *\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n\"use strict\";\n\"production\" !== process.env.NODE_ENV &&\n (function () {\n function is(x, y) {\n return (x === y && (0 !== x || 1 / x === 1 / y)) || (x !== x && y !== y);\n }\n function useSyncExternalStore$2(subscribe, getSnapshot) {\n didWarnOld18Alpha ||\n void 0 === React.startTransition ||\n ((didWarnOld18Alpha = !0),\n console.error(\n \"You are using an outdated, pre-release alpha of React 18 that does not support useSyncExternalStore. The use-sync-external-store shim will not work correctly. Upgrade to a newer pre-release.\"\n ));\n var value = getSnapshot();\n if (!didWarnUncachedGetSnapshot) {\n var cachedValue = getSnapshot();\n objectIs(value, cachedValue) ||\n (console.error(\n \"The result of getSnapshot should be cached to avoid an infinite loop\"\n ),\n (didWarnUncachedGetSnapshot = !0));\n }\n cachedValue = useState({\n inst: { value: value, getSnapshot: getSnapshot }\n });\n var inst = cachedValue[0].inst,\n forceUpdate = cachedValue[1];\n useLayoutEffect(\n function () {\n inst.value = value;\n inst.getSnapshot = getSnapshot;\n checkIfSnapshotChanged(inst) && forceUpdate({ inst: inst });\n },\n [subscribe, value, getSnapshot]\n );\n useEffect(\n function () {\n checkIfSnapshotChanged(inst) && forceUpdate({ inst: inst });\n return subscribe(function () {\n checkIfSnapshotChanged(inst) && forceUpdate({ inst: inst });\n });\n },\n [subscribe]\n );\n useDebugValue(value);\n return value;\n }\n function checkIfSnapshotChanged(inst) {\n var latestGetSnapshot = inst.getSnapshot;\n inst = inst.value;\n try {\n var nextValue = latestGetSnapshot();\n return !objectIs(inst, nextValue);\n } catch (error) {\n return !0;\n }\n }\n function useSyncExternalStore$1(subscribe, getSnapshot) {\n return getSnapshot();\n }\n \"undefined\" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ &&\n \"function\" ===\n typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart &&\n __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());\n var React = require(\"react\"),\n objectIs = \"function\" === typeof Object.is ? Object.is : is,\n useState = React.useState,\n useEffect = React.useEffect,\n useLayoutEffect = React.useLayoutEffect,\n useDebugValue = React.useDebugValue,\n didWarnOld18Alpha = !1,\n didWarnUncachedGetSnapshot = !1,\n shim =\n \"undefined\" === typeof window ||\n \"undefined\" === typeof window.document ||\n \"undefined\" === typeof window.document.createElement\n ? useSyncExternalStore$1\n : useSyncExternalStore$2;\n exports.useSyncExternalStore =\n void 0 !== React.useSyncExternalStore ? React.useSyncExternalStore : shim;\n \"undefined\" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ &&\n \"function\" ===\n typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop &&\n __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error());\n })();\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('../cjs/use-sync-external-store-shim.production.js');\n} else {\n module.exports = require('../cjs/use-sync-external-store-shim.development.js');\n}\n","const FOCUS_EVENT = 0;\nconst RECONNECT_EVENT = 1;\nconst MUTATE_EVENT = 2;\nconst ERROR_REVALIDATE_EVENT = 3;\n\nexport { ERROR_REVALIDATE_EVENT, FOCUS_EVENT, MUTATE_EVENT, RECONNECT_EVENT };\n","var has = Object.prototype.hasOwnProperty;\n\nexport function dequal(foo, bar) {\n\tvar ctor, len;\n\tif (foo === bar) return true;\n\n\tif (foo && bar && (ctor=foo.constructor) === bar.constructor) {\n\t\tif (ctor === Date) return foo.getTime() === bar.getTime();\n\t\tif (ctor === RegExp) return foo.toString() === bar.toString();\n\n\t\tif (ctor === Array) {\n\t\t\tif ((len=foo.length) === bar.length) {\n\t\t\t\twhile (len-- && dequal(foo[len], bar[len]));\n\t\t\t}\n\t\t\treturn len === -1;\n\t\t}\n\n\t\tif (!ctor || typeof foo === 'object') {\n\t\t\tlen = 0;\n\t\t\tfor (ctor in foo) {\n\t\t\t\tif (has.call(foo, ctor) && ++len && !has.call(bar, ctor)) return false;\n\t\t\t\tif (!(ctor in bar) || !dequal(foo[ctor], bar[ctor])) return false;\n\t\t\t}\n\t\t\treturn Object.keys(bar).length === len;\n\t\t}\n\t}\n\n\treturn foo !== foo && bar !== bar;\n}\n","'use client';\nimport React, { useEffect, useLayoutEffect, createContext, useContext, useMemo, useRef, createElement } from 'react';\nimport * as revalidateEvents from './events.mjs';\nimport { dequal } from 'dequal/lite';\n\n// Global state used to deduplicate requests and store listeners\nconst SWRGlobalState = new WeakMap();\n\n// Shared state between server components and client components\nconst noop = ()=>{};\n// Using noop() as the undefined value as undefined can be replaced\n// by something else. Prettier ignore and extra parentheses are necessary here\n// to ensure that tsc doesn't remove the __NOINLINE__ comment.\n// prettier-ignore\nconst UNDEFINED = /*#__NOINLINE__*/ noop();\nconst OBJECT = Object;\nconst isUndefined = (v)=>v === UNDEFINED;\nconst isFunction = (v)=>typeof v == 'function';\nconst mergeObjects = (a, b)=>({\n ...a,\n ...b\n });\nconst isPromiseLike = (x)=>isFunction(x.then);\n\nconst EMPTY_CACHE = {};\nconst INITIAL_CACHE = {};\nconst STR_UNDEFINED = 'undefined';\n// NOTE: Use the function to guarantee it's re-evaluated between jsdom and node runtime for tests.\nconst isWindowDefined = typeof window != STR_UNDEFINED;\nconst isDocumentDefined = typeof document != STR_UNDEFINED;\nconst isLegacyDeno = isWindowDefined && 'Deno' in window;\nconst hasRequestAnimationFrame = ()=>isWindowDefined && typeof window['requestAnimationFrame'] != STR_UNDEFINED;\nconst createCacheHelper = (cache, key)=>{\n const state = SWRGlobalState.get(cache);\n return [\n // Getter\n ()=>!isUndefined(key) && cache.get(key) || EMPTY_CACHE,\n // Setter\n (info)=>{\n if (!isUndefined(key)) {\n const prev = cache.get(key);\n // Before writing to the store, we keep the value in the initial cache\n // if it's not there yet.\n if (!(key in INITIAL_CACHE)) {\n INITIAL_CACHE[key] = prev;\n }\n state[5](key, mergeObjects(prev, info), prev || EMPTY_CACHE);\n }\n },\n // Subscriber\n state[6],\n // Get server cache snapshot\n ()=>{\n if (!isUndefined(key)) {\n // If the cache was updated on the client, we return the stored initial value.\n if (key in INITIAL_CACHE) return INITIAL_CACHE[key];\n }\n // If we haven't done any client-side updates, we return the current value.\n return !isUndefined(key) && cache.get(key) || EMPTY_CACHE;\n }\n ];\n} // export { UNDEFINED, OBJECT, isUndefined, isFunction, mergeObjects, isPromiseLike }\n;\n\n/**\n * Due to the bug https://bugs.chromium.org/p/chromium/issues/detail?id=678075,\n * it's not reliable to detect if the browser is currently online or offline\n * based on `navigator.onLine`.\n * As a workaround, we always assume it's online on the first load, and change\n * the status upon `online` or `offline` events.\n */ let online = true;\nconst isOnline = ()=>online;\n// For node and React Native, `add/removeEventListener` doesn't exist on window.\nconst [onWindowEvent, offWindowEvent] = isWindowDefined && window.addEventListener ? [\n window.addEventListener.bind(window),\n window.removeEventListener.bind(window)\n] : [\n noop,\n noop\n];\nconst isVisible = ()=>{\n const visibilityState = isDocumentDefined && document.visibilityState;\n return isUndefined(visibilityState) || visibilityState !== 'hidden';\n};\nconst initFocus = (callback)=>{\n // focus revalidate\n if (isDocumentDefined) {\n document.addEventListener('visibilitychange', callback);\n }\n onWindowEvent('focus', callback);\n return ()=>{\n if (isDocumentDefined) {\n document.removeEventListener('visibilitychange', callback);\n }\n offWindowEvent('focus', callback);\n };\n};\nconst initReconnect = (callback)=>{\n // revalidate on reconnected\n const onOnline = ()=>{\n online = true;\n callback();\n };\n // nothing to revalidate, just update the status\n const onOffline = ()=>{\n online = false;\n };\n onWindowEvent('online', onOnline);\n onWindowEvent('offline', onOffline);\n return ()=>{\n offWindowEvent('online', onOnline);\n offWindowEvent('offline', onOffline);\n };\n};\nconst preset = {\n isOnline,\n isVisible\n};\nconst defaultConfigOptions = {\n initFocus,\n initReconnect\n};\n\nconst IS_REACT_LEGACY = !React.useId;\nconst IS_SERVER = !isWindowDefined || isLegacyDeno;\n// Polyfill requestAnimationFrame\nconst rAF = (f)=>hasRequestAnimationFrame() ? window['requestAnimationFrame'](f) : setTimeout(f, 1);\n// React currently throws a warning when using useLayoutEffect on the server.\n// To get around it, we can conditionally useEffect on the server (no-op) and\n// useLayoutEffect in the browser.\nconst useIsomorphicLayoutEffect = IS_SERVER ? useEffect : useLayoutEffect;\n// This assignment is to extend the Navigator type to use effectiveType.\nconst navigatorConnection = typeof navigator !== 'undefined' && navigator.connection;\n// Adjust the config based on slow connection status (<= 70Kbps).\nconst slowConnection = !IS_SERVER && navigatorConnection && ([\n 'slow-2g',\n '2g'\n].includes(navigatorConnection.effectiveType) || navigatorConnection.saveData);\n\n// use WeakMap to store the object->key mapping\n// so the objects can be garbage collected.\n// WeakMap uses a hashtable under the hood, so the lookup\n// complexity is almost O(1).\nconst table = new WeakMap();\nconst getTypeName = (value)=>OBJECT.prototype.toString.call(value);\nconst isObjectTypeName = (typeName, type)=>typeName === `[object ${type}]`;\n// counter of the key\nlet counter = 0;\n// A stable hash implementation that supports:\n// - Fast and ensures unique hash properties\n// - Handles unserializable values\n// - Handles object key ordering\n// - Generates short results\n//\n// This is not a serialization function, and the result is not guaranteed to be\n// parsable.\nconst stableHash = (arg)=>{\n const type = typeof arg;\n const typeName = getTypeName(arg);\n const isDate = isObjectTypeName(typeName, 'Date');\n const isRegex = isObjectTypeName(typeName, 'RegExp');\n const isPlainObject = isObjectTypeName(typeName, 'Object');\n let result;\n let index;\n if (OBJECT(arg) === arg && !isDate && !isRegex) {\n // Object/function, not null/date/regexp. Use WeakMap to store the id first.\n // If it's already hashed, directly return the result.\n result = table.get(arg);\n if (result) return result;\n // Store the hash first for circular reference detection before entering the\n // recursive `stableHash` calls.\n // For other objects like set and map, we use this id directly as the hash.\n result = ++counter + '~';\n table.set(arg, result);\n if (Array.isArray(arg)) {\n // Array.\n result = '@';\n for(index = 0; index < arg.length; index++){\n result += stableHash(arg[index]) + ',';\n }\n table.set(arg, result);\n }\n if (isPlainObject) {\n // Object, sort keys.\n result = '#';\n const keys = OBJECT.keys(arg).sort();\n while(!isUndefined(index = keys.pop())){\n if (!isUndefined(arg[index])) {\n result += index + ':' + stableHash(arg[index]) + ',';\n }\n }\n table.set(arg, result);\n }\n } else {\n result = isDate ? arg.toJSON() : type == 'symbol' ? arg.toString() : type == 'string' ? JSON.stringify(arg) : '' + arg;\n }\n return result;\n};\n\nconst serialize = (key)=>{\n if (isFunction(key)) {\n try {\n key = key();\n } catch (err) {\n // dependencies not ready\n key = '';\n }\n }\n // Use the original key as the argument of fetcher. This can be a string or an\n // array of values.\n const args = key;\n // If key is not falsy, or not an empty array, hash it.\n key = typeof key == 'string' ? key : (Array.isArray(key) ? key.length : key) ? stableHash(key) : '';\n return [\n key,\n args\n ];\n};\n\n// Global timestamp.\nlet __timestamp = 0;\nconst getTimestamp = ()=>++__timestamp;\n\nasync function internalMutate(...args) {\n const [cache, _key, _data, _opts] = args;\n // When passing as a boolean, it's explicitly used to disable/enable\n // revalidation.\n const options = mergeObjects({\n populateCache: true,\n throwOnError: true\n }, typeof _opts === 'boolean' ? {\n revalidate: _opts\n } : _opts || {});\n let populateCache = options.populateCache;\n const rollbackOnErrorOption = options.rollbackOnError;\n let optimisticData = options.optimisticData;\n const rollbackOnError = (error)=>{\n return typeof rollbackOnErrorOption === 'function' ? rollbackOnErrorOption(error) : rollbackOnErrorOption !== false;\n };\n const throwOnError = options.throwOnError;\n // If the second argument is a key filter, return the mutation results for all\n // filtered keys.\n if (isFunction(_key)) {\n const keyFilter = _key;\n const matchedKeys = [];\n const it = cache.keys();\n for (const key of it){\n if (// Skip the special useSWRInfinite and useSWRSubscription keys.\n !/^\\$(inf|sub)\\$/.test(key) && keyFilter(cache.get(key)._k)) {\n matchedKeys.push(key);\n }\n }\n return Promise.all(matchedKeys.map(mutateByKey));\n }\n return mutateByKey(_key);\n async function mutateByKey(_k) {\n // Serialize key\n const [key] = serialize(_k);\n if (!key) return;\n const [get, set] = createCacheHelper(cache, key);\n const [EVENT_REVALIDATORS, MUTATION, FETCH, PRELOAD] = SWRGlobalState.get(cache);\n const startRevalidate = ()=>{\n const revalidators = EVENT_REVALIDATORS[key];\n const revalidate = isFunction(options.revalidate) ? options.revalidate(get().data, _k) : options.revalidate !== false;\n if (revalidate) {\n // Invalidate the key by deleting the concurrent request markers so new\n // requests will not be deduped.\n delete FETCH[key];\n delete PRELOAD[key];\n if (revalidators && revalidators[0]) {\n return revalidators[0](revalidateEvents.MUTATE_EVENT).then(()=>get().data);\n }\n }\n return get().data;\n };\n // If there is no new data provided, revalidate the key with current state.\n if (args.length < 3) {\n // Revalidate and broadcast state.\n return startRevalidate();\n }\n let data = _data;\n let error;\n let isError = false;\n // Update global timestamps.\n const beforeMutationTs = getTimestamp();\n MUTATION[key] = [\n beforeMutationTs,\n 0\n ];\n const hasOptimisticData = !isUndefined(optimisticData);\n const state = get();\n // `displayedData` is the current value on screen. It could be the optimistic value\n // that is going to be overridden by a `committedData`, or get reverted back.\n // `committedData` is the validated value that comes from a fetch or mutation.\n const displayedData = state.data;\n const currentData = state._c;\n const committedData = isUndefined(currentData) ? displayedData : currentData;\n // Do optimistic data update.\n if (hasOptimisticData) {\n optimisticData = isFunction(optimisticData) ? optimisticData(committedData, displayedData) : optimisticData;\n // When we set optimistic data, backup the current committedData data in `_c`.\n set({\n data: optimisticData,\n _c: committedData\n });\n }\n if (isFunction(data)) {\n // `data` is a function, call it passing current cache value.\n try {\n data = data(committedData);\n } catch (err) {\n // If it throws an error synchronously, we shouldn't update the cache.\n error = err;\n isError = true;\n }\n }\n // `data` is a promise/thenable, resolve the final data first.\n if (data && isPromiseLike(data)) {\n // This means that the mutation is async, we need to check timestamps to\n // avoid race conditions.\n data = await data.catch((err)=>{\n error = err;\n isError = true;\n });\n // Check if other mutations have occurred since we've started this mutation.\n // If there's a race we don't update cache or broadcast the change,\n // just return the data.\n if (beforeMutationTs !== MUTATION[key][0]) {\n if (isError) throw error;\n return data;\n } else if (isError && hasOptimisticData && rollbackOnError(error)) {\n // Rollback. Always populate the cache in this case but without\n // transforming the data.\n populateCache = true;\n // Reset data to be the latest committed data, and clear the `_c` value.\n set({\n data: committedData,\n _c: UNDEFINED\n });\n }\n }\n // If we should write back the cache after request.\n if (populateCache) {\n if (!isError) {\n // Transform the result into data.\n if (isFunction(populateCache)) {\n const populateCachedData = populateCache(data, committedData);\n set({\n data: populateCachedData,\n error: UNDEFINED,\n _c: UNDEFINED\n });\n } else {\n // Only update cached data and reset the error if there's no error. Data can be `undefined` here.\n set({\n data,\n error: UNDEFINED,\n _c: UNDEFINED\n });\n }\n }\n }\n // Reset the timestamp to mark the mutation has ended.\n MUTATION[key][1] = getTimestamp();\n // Update existing SWR Hooks' internal states:\n Promise.resolve(startRevalidate()).then(()=>{\n // The mutation and revalidation are ended, we can clear it since the data is\n // not an optimistic value anymore.\n set({\n _c: UNDEFINED\n });\n });\n // Throw error or return data\n if (isError) {\n if (throwOnError) throw error;\n return;\n }\n return data;\n }\n}\n\nconst revalidateAllKeys = (revalidators, type)=>{\n for(const key in revalidators){\n if (revalidators[key][0]) revalidators[key][0](type);\n }\n};\nconst initCache = (provider, options)=>{\n // The global state for a specific provider will be used to deduplicate\n // requests and store listeners. As well as a mutate function that is bound to\n // the cache.\n // The provider's global state might be already initialized. Let's try to get the\n // global state associated with the provider first.\n if (!SWRGlobalState.has(provider)) {\n const opts = mergeObjects(defaultConfigOptions, options);\n // If there's no global state bound to the provider, create a new one with the\n // new mutate function.\n const EVENT_REVALIDATORS = Object.create(null);\n const mutate = internalMutate.bind(UNDEFINED, provider);\n let unmount = noop;\n const subscriptions = Object.create(null);\n const subscribe = (key, callback)=>{\n const subs = subscriptions[key] || [];\n subscriptions[key] = subs;\n subs.push(callback);\n return ()=>subs.splice(subs.indexOf(callback), 1);\n };\n const setter = (key, value, prev)=>{\n provider.set(key, value);\n const subs = subscriptions[key];\n if (subs) {\n for (const fn of subs){\n fn(value, prev);\n }\n }\n };\n const initProvider = ()=>{\n if (!SWRGlobalState.has(provider)) {\n // Update the state if it's new, or if the provider has been extended.\n SWRGlobalState.set(provider, [\n EVENT_REVALIDATORS,\n Object.create(null),\n Object.create(null),\n Object.create(null),\n mutate,\n setter,\n subscribe\n ]);\n if (!IS_SERVER) {\n // When listening to the native events for auto revalidations,\n // we intentionally put a delay (setTimeout) here to make sure they are\n // fired after immediate JavaScript executions, which can be\n // React's state updates.\n // This avoids some unnecessary revalidations such as\n // https://github.com/vercel/swr/issues/1680.\n const releaseFocus = opts.initFocus(setTimeout.bind(UNDEFINED, revalidateAllKeys.bind(UNDEFINED, EVENT_REVALIDATORS, revalidateEvents.FOCUS_EVENT)));\n const releaseReconnect = opts.initReconnect(setTimeout.bind(UNDEFINED, revalidateAllKeys.bind(UNDEFINED, EVENT_REVALIDATORS, revalidateEvents.RECONNECT_EVENT)));\n unmount = ()=>{\n // eslint-disable-next-line @typescript-eslint/no-unused-expressions\n releaseFocus && releaseFocus();\n // eslint-disable-next-line @typescript-eslint/no-unused-expressions\n releaseReconnect && releaseReconnect();\n // When un-mounting, we need to remove the cache provider from the state\n // storage too because it's a side-effect. Otherwise, when re-mounting we\n // will not re-register those event listeners.\n SWRGlobalState.delete(provider);\n };\n }\n }\n };\n initProvider();\n // This is a new provider, we need to initialize it and setup DOM events\n // listeners for `focus` and `reconnect` actions.\n // We might want to inject an extra layer on top of `provider` in the future,\n // such as key serialization, auto GC, etc.\n // For now, it's just a `Map` interface without any modifications.\n return [\n provider,\n mutate,\n initProvider,\n unmount\n ];\n }\n return [\n provider,\n SWRGlobalState.get(provider)[4]\n ];\n};\n\n// error retry\nconst onErrorRetry = (_, __, config, revalidate, opts)=>{\n const maxRetryCount = config.errorRetryCount;\n const currentRetryCount = opts.retryCount;\n // Exponential backoff\n const timeout = ~~((Math.random() + 0.5) * (1 << (currentRetryCount < 8 ? currentRetryCount : 8))) * config.errorRetryInterval;\n if (!isUndefined(maxRetryCount) && currentRetryCount > maxRetryCount) {\n return;\n }\n setTimeout(revalidate, timeout, opts);\n};\nconst compare = dequal;\n// Default cache provider\nconst [cache, mutate] = initCache(new Map());\n// Default config\nconst defaultConfig = mergeObjects({\n // events\n onLoadingSlow: noop,\n onSuccess: noop,\n onError: noop,\n onErrorRetry,\n onDiscarded: noop,\n // switches\n revalidateOnFocus: true,\n revalidateOnReconnect: true,\n revalidateIfStale: true,\n shouldRetryOnError: true,\n // timeouts\n errorRetryInterval: slowConnection ? 10000 : 5000,\n focusThrottleInterval: 5 * 1000,\n dedupingInterval: 2 * 1000,\n loadingTimeout: slowConnection ? 5000 : 3000,\n // providers\n compare,\n isPaused: ()=>false,\n cache,\n mutate,\n fallback: {}\n}, // use web preset by default\npreset);\n\nconst mergeConfigs = (a, b)=>{\n // Need to create a new object to avoid mutating the original here.\n const v = mergeObjects(a, b);\n // If two configs are provided, merge their `use` and `fallback` options.\n if (b) {\n const { use: u1, fallback: f1 } = a;\n const { use: u2, fallback: f2 } = b;\n if (u1 && u2) {\n v.use = u1.concat(u2);\n }\n if (f1 && f2) {\n v.fallback = mergeObjects(f1, f2);\n }\n }\n return v;\n};\n\nconst SWRConfigContext = createContext({});\nconst SWRConfig = (props)=>{\n const { value } = props;\n const parentConfig = useContext(SWRConfigContext);\n const isFunctionalConfig = isFunction(value);\n const config = useMemo(()=>isFunctionalConfig ? value(parentConfig) : value, [\n isFunctionalConfig,\n parentConfig,\n value\n ]);\n // Extend parent context values and middleware.\n const extendedConfig = useMemo(()=>isFunctionalConfig ? config : mergeConfigs(parentConfig, config), [\n isFunctionalConfig,\n parentConfig,\n config\n ]);\n // Should not use the inherited provider.\n const provider = config && config.provider;\n // initialize the cache only on first access.\n const cacheContextRef = useRef(UNDEFINED);\n if (provider && !cacheContextRef.current) {\n cacheContextRef.current = initCache(provider(extendedConfig.cache || cache), config);\n }\n const cacheContext = cacheContextRef.current;\n // Override the cache if a new provider is given.\n if (cacheContext) {\n extendedConfig.cache = cacheContext[0];\n extendedConfig.mutate = cacheContext[1];\n }\n // Unsubscribe events.\n useIsomorphicLayoutEffect(()=>{\n if (cacheContext) {\n // eslint-disable-next-line @typescript-eslint/no-unused-expressions\n cacheContext[2] && cacheContext[2]();\n return cacheContext[3];\n }\n }, []);\n return createElement(SWRConfigContext.Provider, mergeObjects(props, {\n value: extendedConfig\n }));\n};\n\nexport { noop as A, isPromiseLike as B, IS_SERVER as I, OBJECT as O, SWRConfigContext as S, UNDEFINED as U, isFunction as a, SWRGlobalState as b, cache as c, defaultConfig as d, isUndefined as e, mergeConfigs as f, SWRConfig as g, initCache as h, isWindowDefined as i, mutate as j, compare as k, stableHash as l, mergeObjects as m, internalMutate as n, getTimestamp as o, preset as p, defaultConfigOptions as q, IS_REACT_LEGACY as r, serialize as s, rAF as t, useIsomorphicLayoutEffect as u, slowConnection as v, isDocumentDefined as w, isLegacyDeno as x, hasRequestAnimationFrame as y, createCacheHelper as z };\n","const INFINITE_PREFIX = '$inf$';\n\nexport { INFINITE_PREFIX };\n","import { i as isWindowDefined, a as isFunction, S as SWRConfigContext, m as mergeObjects, d as defaultConfig, s as serialize, b as SWRGlobalState, c as cache, e as isUndefined, I as IS_SERVER, f as mergeConfigs } from './config-context-12s-CCVTDPOP.mjs';\nexport { r as IS_REACT_LEGACY, O as OBJECT, g as SWRConfig, U as UNDEFINED, k as compare, z as createCacheHelper, q as defaultConfigOptions, o as getTimestamp, y as hasRequestAnimationFrame, h as initCache, n as internalMutate, w as isDocumentDefined, x as isLegacyDeno, B as isPromiseLike, j as mutate, A as noop, p as preset, t as rAF, v as slowConnection, l as stableHash, u as useIsomorphicLayoutEffect } from './config-context-12s-CCVTDPOP.mjs';\nimport * as revalidateEvents from './events.mjs';\nexport { revalidateEvents };\nimport { INFINITE_PREFIX } from './constants.mjs';\nexport { INFINITE_PREFIX } from './constants.mjs';\nimport React, { useContext, useMemo } from 'react';\nexport * from './types.mjs';\n\n// @ts-expect-error\nconst enableDevtools = isWindowDefined && window.__SWR_DEVTOOLS_USE__;\nconst use = enableDevtools ? window.__SWR_DEVTOOLS_USE__ : [];\nconst setupDevTools = ()=>{\n if (enableDevtools) {\n // @ts-expect-error\n window.__SWR_DEVTOOLS_REACT__ = React;\n }\n};\n\nconst normalize = (args)=>{\n return isFunction(args[1]) ? [\n args[0],\n args[1],\n args[2] || {}\n ] : [\n args[0],\n null,\n (args[1] === null ? args[2] : args[1]) || {}\n ];\n};\n\nconst useSWRConfig = ()=>{\n const parentConfig = useContext(SWRConfigContext);\n const mergedConfig = useMemo(()=>mergeObjects(defaultConfig, parentConfig), [\n parentConfig\n ]);\n return mergedConfig;\n};\n\nconst preload = (key_, fetcher)=>{\n // preload should be a no-op on the server\n if (IS_SERVER) {\n return undefined;\n }\n const [key, fnArg] = serialize(key_);\n const [, , , PRELOAD] = SWRGlobalState.get(cache);\n // Prevent preload to be called multiple times before used.\n if (PRELOAD[key]) return PRELOAD[key];\n const req = fetcher(fnArg);\n PRELOAD[key] = req;\n return req;\n};\nconst middleware = (useSWRNext)=>(key_, fetcher_, config)=>{\n // fetcher might be a sync function, so this should not be an async function\n const fetcher = fetcher_ && ((...args)=>{\n const [key] = serialize(key_);\n const [, , , PRELOAD] = SWRGlobalState.get(cache);\n if (key.startsWith(INFINITE_PREFIX)) {\n // we want the infinite fetcher to be called.\n // handling of the PRELOAD cache happens there.\n return fetcher_(...args);\n }\n const req = PRELOAD[key];\n if (isUndefined(req)) return fetcher_(...args);\n delete PRELOAD[key];\n return req;\n });\n return useSWRNext(key_, fetcher, config);\n };\n\nconst BUILT_IN_MIDDLEWARE = use.concat(middleware);\n\n// It's tricky to pass generic types as parameters, so we just directly override\n// the types here.\nconst withArgs = (hook)=>{\n return function useSWRArgs(...args) {\n // Get the default and inherited configuration.\n const fallbackConfig = useSWRConfig();\n // Normalize arguments.\n const [key, fn, _config] = normalize(args);\n // Merge configurations.\n const config = mergeConfigs(fallbackConfig, _config);\n // Apply middleware\n let next = hook;\n const { use } = config;\n const middleware = (use || []).concat(BUILT_IN_MIDDLEWARE);\n for(let i = middleware.length; i--;){\n next = middleware[i](next);\n }\n return next(key, fn || config.fetcher || null, config);\n };\n};\n\n// Add a callback function to a list of keyed callback functions and return\n// the unsubscribe function.\nconst subscribeCallback = (key, callbacks, callback)=>{\n const keyedRevalidators = callbacks[key] || (callbacks[key] = []);\n keyedRevalidators.push(callback);\n return ()=>{\n const index = keyedRevalidators.indexOf(callback);\n if (index >= 0) {\n // O(1): faster than splice\n keyedRevalidators[index] = keyedRevalidators[keyedRevalidators.length - 1];\n keyedRevalidators.pop();\n }\n };\n};\n\n// Create a custom hook with a middleware\nconst withMiddleware = (useSWR, middleware)=>{\n return (...args)=>{\n const [key, fn, config] = normalize(args);\n const uses = (config.use || []).concat(middleware);\n return useSWR(key, fn, {\n ...config,\n use: uses\n });\n };\n};\n\nsetupDevTools();\n\nexport { IS_SERVER, SWRGlobalState, cache, defaultConfig, isFunction, isUndefined, isWindowDefined, mergeConfigs, mergeObjects, normalize, preload, serialize, subscribeCallback, useSWRConfig, withArgs, withMiddleware };\n","import React, { useRef, useMemo, useCallback, useDebugValue } from 'react';\nimport { useSyncExternalStore } from 'use-sync-external-store/shim';\nimport { UNDEFINED as UNDEFINED$1, OBJECT as OBJECT$1, SWRConfig as SWRConfig$1, defaultConfig, withArgs, SWRGlobalState, serialize as serialize$1, createCacheHelper, isUndefined as isUndefined$1, isPromiseLike, IS_SERVER, noop as noop$1, getTimestamp, isFunction as isFunction$1, revalidateEvents, internalMutate, useIsomorphicLayoutEffect, subscribeCallback, rAF, IS_REACT_LEGACY, mergeObjects } from '../_internal/index.mjs';\nexport { mutate, preload, useSWRConfig } from '../_internal/index.mjs';\n\n// Shared state between server components and client components\nconst noop = ()=>{};\n// Using noop() as the undefined value as undefined can be replaced\n// by something else. Prettier ignore and extra parentheses are necessary here\n// to ensure that tsc doesn't remove the __NOINLINE__ comment.\n// prettier-ignore\nconst UNDEFINED = /*#__NOINLINE__*/ noop();\nconst OBJECT = Object;\nconst isUndefined = (v)=>v === UNDEFINED;\nconst isFunction = (v)=>typeof v == 'function';\n\n// use WeakMap to store the object->key mapping\n// so the objects can be garbage collected.\n// WeakMap uses a hashtable under the hood, so the lookup\n// complexity is almost O(1).\nconst table = new WeakMap();\nconst getTypeName = (value)=>OBJECT.prototype.toString.call(value);\nconst isObjectTypeName = (typeName, type)=>typeName === `[object ${type}]`;\n// counter of the key\nlet counter = 0;\n// A stable hash implementation that supports:\n// - Fast and ensures unique hash properties\n// - Handles unserializable values\n// - Handles object key ordering\n// - Generates short results\n//\n// This is not a serialization function, and the result is not guaranteed to be\n// parsable.\nconst stableHash = (arg)=>{\n const type = typeof arg;\n const typeName = getTypeName(arg);\n const isDate = isObjectTypeName(typeName, 'Date');\n const isRegex = isObjectTypeName(typeName, 'RegExp');\n const isPlainObject = isObjectTypeName(typeName, 'Object');\n let result;\n let index;\n if (OBJECT(arg) === arg && !isDate && !isRegex) {\n // Object/function, not null/date/regexp. Use WeakMap to store the id first.\n // If it's already hashed, directly return the result.\n result = table.get(arg);\n if (result) return result;\n // Store the hash first for circular reference detection before entering the\n // recursive `stableHash` calls.\n // For other objects like set and map, we use this id directly as the hash.\n result = ++counter + '~';\n table.set(arg, result);\n if (Array.isArray(arg)) {\n // Array.\n result = '@';\n for(index = 0; index < arg.length; index++){\n result += stableHash(arg[index]) + ',';\n }\n table.set(arg, result);\n }\n if (isPlainObject) {\n // Object, sort keys.\n result = '#';\n const keys = OBJECT.keys(arg).sort();\n while(!isUndefined(index = keys.pop())){\n if (!isUndefined(arg[index])) {\n result += index + ':' + stableHash(arg[index]) + ',';\n }\n }\n table.set(arg, result);\n }\n } else {\n result = isDate ? arg.toJSON() : type == 'symbol' ? arg.toString() : type == 'string' ? JSON.stringify(arg) : '' + arg;\n }\n return result;\n};\n\nconst serialize = (key)=>{\n if (isFunction(key)) {\n try {\n key = key();\n } catch (err) {\n // dependencies not ready\n key = '';\n }\n }\n // Use the original key as the argument of fetcher. This can be a string or an\n // array of values.\n const args = key;\n // If key is not falsy, or not an empty array, hash it.\n key = typeof key == 'string' ? key : (Array.isArray(key) ? key.length : key) ? stableHash(key) : '';\n return [\n key,\n args\n ];\n};\n\nconst unstable_serialize = (key)=>serialize(key)[0];\n\n/// <reference types=\"react/experimental\" />\nconst use = React.use || // This extra generic is to avoid TypeScript mixing up the generic and JSX sytax\n// and emitting an error.\n// We assume that this is only for the `use(thenable)` case, not `use(context)`.\n// https://github.com/facebook/react/blob/aed00dacfb79d17c53218404c52b1c7aa59c4a89/packages/react-server/src/ReactFizzThenable.js#L45\n((thenable)=>{\n switch(thenable.status){\n case 'pending':\n throw thenable;\n case 'fulfilled':\n return thenable.value;\n case 'rejected':\n throw thenable.reason;\n default:\n thenable.status = 'pending';\n thenable.then((v)=>{\n thenable.status = 'fulfilled';\n thenable.value = v;\n }, (e)=>{\n thenable.status = 'rejected';\n thenable.reason = e;\n });\n throw thenable;\n }\n});\nconst WITH_DEDUPE = {\n dedupe: true\n};\nconst resolvedUndef = Promise.resolve(UNDEFINED$1);\nconst sub = ()=>noop$1;\n/**\n * The core implementation of the useSWR hook.\n *\n * This is the main handler function that implements all SWR functionality including\n * data fetching, caching, revalidation, error handling, and state management.\n * It manages the complete lifecycle of SWR requests from initialization through\n * cleanup.\n *\n * Key responsibilities:\n * - Key serialization and normalization\n * - Cache state management and synchronization\n * - Automatic and manual revalidation\n * - Error handling and retry logic\n * - Suspense integration\n * - Loading state management\n * - Effect cleanup and memory management\n *\n * @template Data - The type of data returned by the fetcher\n * @template Error - The type of error that can be thrown\n *\n * @param _key - The SWR key (string, array, object, function, or falsy)\n * @param fetcher - The fetcher function to retrieve data, or null to disable fetching\n * @param config - Complete SWR configuration object with both public and internal options\n *\n * @returns SWRResponse object containing data, error, mutate function, and loading states\n *\n * @internal This is the internal implementation. Use `useSWR` instead.\n */ const useSWRHandler = (_key, fetcher, config)=>{\n const { cache, compare, suspense, fallbackData, revalidateOnMount, revalidateIfStale, refreshInterval, refreshWhenHidden, refreshWhenOffline, keepPreviousData, strictServerPrefetchWarning } = config;\n const [EVENT_REVALIDATORS, MUTATION, FETCH, PRELOAD] = SWRGlobalState.get(cache);\n // `key` is the identifier of the SWR internal state,\n // `fnArg` is the argument/arguments parsed from the key, which will be passed\n // to the fetcher.\n // All of them are derived from `_key`.\n const [key, fnArg] = serialize$1(_key);\n // If it's the initial render of this hook.\n const initialMountedRef = useRef(false);\n // If the hook is unmounted already. This will be used to prevent some effects\n // to be called after unmounting.\n const unmountedRef = useRef(false);\n // Refs to keep the key and config.\n const keyRef = useRef(key);\n const fetcherRef = useRef(fetcher);\n const configRef = useRef(config);\n const getConfig = ()=>configRef.current;\n const isActive = ()=>getConfig().isVisible() && getConfig().isOnline();\n const [getCache, setCache, subscribeCache, getInitialCache] = createCacheHelper(cache, key);\n const stateDependencies = useRef({}).current;\n // Resolve the fallback data from either the inline option, or the global provider.\n // If it's a promise, we simply let React suspend and resolve it for us.\n const fallback = isUndefined$1(fallbackData) ? isUndefined$1(config.fallback) ? UNDEFINED$1 : config.fallback[key] : fallbackData;\n const isEqual = (prev, current)=>{\n for(const _ in stateDependencies){\n const t = _;\n if (t === 'data') {\n if (!compare(prev[t], current[t])) {\n if (!isUndefined$1(prev[t])) {\n return false;\n }\n if (!compare(returnedData, current[t])) {\n return false;\n }\n }\n } else {\n if (current[t] !== prev[t]) {\n return false;\n }\n }\n }\n return true;\n };\n const isInitialMount = !initialMountedRef.current;\n const getSnapshot = useMemo(()=>{\n const cachedData = getCache();\n const initialData = getInitialCache();\n const getSelectedCache = (state)=>{\n // We only select the needed fields from the state.\n const snapshot = mergeObjects(state);\n delete snapshot._k;\n const shouldStartRequest = (()=>{\n if (!key) return false;\n if (!fetcher) return false;\n // If it's paused, we skip revalidation.\n if (getConfig().isPaused()) return false;\n // If `revalidateOnMount` is set, we take the value directly.\n if (isInitialMount && !isUndefined$1(revalidateOnMount)) return revalidateOnMount;\n const data = !isUndefined$1(fallback) ? fallback : snapshot.data;\n if (suspense) return isUndefined$1(data) || revalidateIfStale;\n return isUndefined$1(data) || revalidateIfStale;\n })();\n if (!shouldStartRequest) {\n return snapshot;\n }\n return {\n isValidating: true,\n isLoading: true,\n ...snapshot\n };\n };\n const clientSnapshot = getSelectedCache(cachedData);\n const serverSnapshot = cachedData === initialData ? clientSnapshot : getSelectedCache(initialData);\n // To make sure that we are returning the same object reference to avoid\n // unnecessary re-renders, we keep the previous snapshot and use deep\n // comparison to check if we need to return a new one.\n let memorizedSnapshot = clientSnapshot;\n return [\n ()=>{\n const newSnapshot = getSelectedCache(getCache());\n const compareResult = isEqual(newSnapshot, memorizedSnapshot);\n if (compareResult) {\n // Mentally, we should always return the `memorizedSnapshot` here\n // as there's no change between the new and old snapshots.\n // However, since the `isEqual` function only compares selected fields,\n // the values of the unselected fields might be changed. That's\n // simply because we didn't track them.\n // To support the case in https://github.com/vercel/swr/pull/2576,\n // we need to update these fields in the `memorizedSnapshot` too\n // with direct mutations to ensure the snapshot is always up-to-date\n // even for the unselected fields, but only trigger re-renders when\n // the selected fields are changed.\n memorizedSnapshot.data = newSnapshot.data;\n memorizedSnapshot.isLoading = newSnapshot.isLoading;\n memorizedSnapshot.isValidating = newSnapshot.isValidating;\n memorizedSnapshot.error = newSnapshot.error;\n return memorizedSnapshot;\n } else {\n memorizedSnapshot = newSnapshot;\n return newSnapshot;\n }\n },\n ()=>serverSnapshot\n ];\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [\n cache,\n key\n ]);\n // Get the current state that SWR should return.\n const cached = useSyncExternalStore(useCallback((callback)=>subscribeCache(key, (current, prev)=>{\n if (!isEqual(prev, current)) callback();\n }), // eslint-disable-next-line react-hooks/exhaustive-deps\n [\n cache,\n key\n ]), getSnapshot[0], getSnapshot[1]);\n const hasRevalidator = EVENT_REVALIDATORS[key] && EVENT_REVALIDATORS[key].length > 0;\n const cachedData = cached.data;\n const data = isUndefined$1(cachedData) ? fallback && isPromiseLike(fallback) ? use(fallback) : fallback : cachedData;\n const error = cached.error;\n // Use a ref to store previously returned data. Use the initial data as its initial value.\n const laggyDataRef = useRef(data);\n const returnedData = keepPreviousData ? isUndefined$1(cachedData) ? isUndefined$1(laggyDataRef.current) ? data : laggyDataRef.current : cachedData : data;\n const hasKeyButNoData = key && isUndefined$1(data);\n const hydrationRef = useRef(null);\n // Note: the conditionally hook call is fine because the environment\n // `IS_SERVER` never changes.\n // @ts-expect-error -- use hydrationRef directly\n !IS_SERVER && // getServerSnapshot is only called during hydration\n // eslint-disable-next-line react-hooks/rules-of-hooks\n useSyncExternalStore(sub, ()=>{\n hydrationRef.current = false;\n return hydrationRef;\n }, ()=>{\n hydrationRef.current = true;\n return hydrationRef;\n });\n const isHydration = hydrationRef.current;\n // During the initial SSR render, warn if the key has no data pre-fetched via:\n // - fallback data\n // - preload calls\n // - initial data from the cache provider\n // We only warn once for each key during Hydration.\n if (strictServerPrefetchWarning && isHydration && !suspense && hasKeyButNoData) {\n console.warn(`Missing pre-initiated data for serialized key \"${key}\" during server-side rendering. Data fetching should be initiated on the server and provided to SWR via fallback data. You can set \"strictServerPrefetchWarning: false\" to disable this warning.`);\n }\n // Resolve the default validating state:\n // If it's able to validate, and it should revalidate when mount, this will be true.\n // - Suspense mode and there's stale data for the initial render.\n // - Not suspense mode and there is no fallback data and `revalidateIfStale` is enabled.\n // - `revalidateIfStale` is enabled but `data` is not defined.\n const shouldDoInitialRevalidation = (()=>{\n if (!key || !fetcher) return false;\n // If it's paused, we skip revalidation.\n if (getConfig().isPaused()) return false;\n // if a key already has revalidators and also has error, we should not trigger revalidation\n if (hasRevalidator && !isUndefined$1(error)) return false;\n // If `revalidateOnMount` is set, we take the value directly.\n if (isInitialMount && !isUndefined$1(revalidateOnMount)) return revalidateOnMount;\n // Under suspense mode, it will always fetch on render if there is no\n // stale data so no need to revalidate immediately mount it again.\n // If data exists, only revalidate if `revalidateIfStale` is true.\n if (suspense) return isUndefined$1(data) ? false : revalidateIfStale;\n // If there is no stale data, we need to revalidate when mount;\n // If `revalidateIfStale` is set to true, we will always revalidate.\n return isUndefined$1(data) || revalidateIfStale;\n })();\n const defaultValidatingState = isInitialMount && shouldDoInitialRevalidation;\n const isValidating = isUndefined$1(cached.isValidating) ? defaultValidatingState : cached.isValidating;\n const isLoading = isUndefined$1(cached.isLoading) ? defaultValidatingState : cached.isLoading;\n // The revalidation function is a carefully crafted wrapper of the original\n // `fetcher`, to correctly handle the many edge cases.\n const revalidate = useCallback(async (revalidateOpts)=>{\n const currentFetcher = fetcherRef.current;\n if (!key || !currentFetcher || unmountedRef.current || getConfig().isPaused()) {\n return false;\n }\n let newData;\n let startAt;\n let loading = true;\n const opts = revalidateOpts || {};\n // If there is no ongoing concurrent request, or `dedupe` is not set, a\n // new request should be initiated.\n const shouldStartNewRequest = !FETCH[key] || !opts.dedupe;\n /*\n For React 17\n Do unmount check for calls:\n If key has changed during the revalidation, or the component has been\n unmounted, old dispatch and old event callbacks should not take any\n effect\n\n For React 18\n only check if key has changed\n https://github.com/reactwg/react-18/discussions/82\n */ const callbackSafeguard = ()=>{\n if (IS_REACT_LEGACY) {\n return !unmountedRef.current && key === keyRef.current && initialMountedRef.current;\n }\n return key === keyRef.current;\n };\n // The final state object when the request finishes.\n const finalState = {\n isValidating: false,\n isLoading: false\n };\n const finishRequestAndUpdateState = ()=>{\n setCache(finalState);\n };\n const cleanupState = ()=>{\n // Check if it's still the same request before deleting it.\n const requestInfo = FETCH[key];\n if (requestInfo && requestInfo[1] === startAt) {\n delete FETCH[key];\n }\n };\n // Start fetching. Change the `isValidating` state, update the cache.\n const initialState = {\n isValidating: true\n };\n // It is in the `isLoading` state, if and only if there is no cached data.\n // This bypasses fallback data and laggy data.\n if (isUndefined$1(getCache().data)) {\n initialState.isLoading = true;\n }\n try {\n if (shouldStartNewRequest) {\n setCache(initialState);\n // If no cache is being rendered currently (it shows a blank page),\n // we trigger the loading slow event.\n if (config.loadingTimeout && isUndefined$1(getCache().data)) {\n setTimeout(()=>{\n if (loading && callbackSafeguard()) {\n getConfig().onLoadingSlow(key, config);\n }\n }, config.loadingTimeout);\n }\n // Start the request and save the timestamp.\n // Key must be truthy if entering here.\n FETCH[key] = [\n currentFetcher(fnArg),\n getTimestamp()\n ];\n }\n // Wait until the ongoing request is done. Deduplication is also\n // considered here.\n ;\n [newData, startAt] = FETCH[key];\n newData = await newData;\n if (shouldStartNewRequest) {\n // If the request isn't interrupted, clean it up after the\n // deduplication interval.\n setTimeout(cleanupState, config.dedupingInterval);\n }\n // If there're other ongoing request(s), started after the current one,\n // we need to ignore the current one to avoid possible race conditions:\n // req1------------------>res1 (current one)\n // req2---------------->res2\n // the request that fired later will always be kept.\n // The timestamp maybe be `undefined` or a number\n if (!FETCH[key] || FETCH[key][1] !== startAt) {\n if (shouldStartNewRequest) {\n if (callbackSafeguard()) {\n getConfig().onDiscarded(key);\n }\n }\n return false;\n }\n // Clear error.\n finalState.error = UNDEFINED$1;\n // If there're other mutations(s), that overlapped with the current revalidation:\n // case 1:\n // req------------------>res\n // mutate------>end\n // case 2:\n // req------------>res\n // mutate------>end\n // case 3:\n // req------------------>res\n // mutate-------...---------->\n // we have to ignore the revalidation result (res) because it's no longer fresh.\n // meanwhile, a new revalidation should be triggered when the mutation ends.\n const mutationInfo = MUTATION[key];\n if (!isUndefined$1(mutationInfo) && // case 1\n (startAt <= mutationInfo[0] || // case 2\n startAt <= mutationInfo[1] || // case 3\n mutationInfo[1] === 0)) {\n finishRequestAndUpdateState();\n if (shouldStartNewRequest) {\n if (callbackSafeguard()) {\n getConfig().onDiscarded(key);\n }\n }\n return false;\n }\n // Deep compare with the latest state to avoid extra re-renders.\n // For local state, compare and assign.\n const cacheData = getCache().data;\n // Since the compare fn could be custom fn\n // cacheData might be different from newData even when compare fn returns True\n finalState.data = compare(cacheData, newData) ? cacheData : newData;\n // Trigger the successful callback if it's the original request.\n if (shouldStartNewRequest) {\n if (callbackSafeguard()) {\n getConfig().onSuccess(newData, key, config);\n }\n }\n } catch (err) {\n cleanupState();\n const currentConfig = getConfig();\n const { shouldRetryOnError } = currentConfig;\n // Not paused, we continue handling the error. Otherwise, discard it.\n if (!currentConfig.isPaused()) {\n // Get a new error, don't use deep comparison for errors.\n finalState.error = err;\n // Error event and retry logic. Only for the actual request, not\n // deduped ones.\n if (shouldStartNewRequest && callbackSafeguard()) {\n currentConfig.onError(err, key, currentConfig);\n if (shouldRetryOnError === true || isFunction$1(shouldRetryOnError) && shouldRetryOnError(err)) {\n if (!getConfig().revalidateOnFocus || !getConfig().revalidateOnReconnect || isActive()) {\n // If it's inactive, stop. It will auto-revalidate when\n // refocusing or reconnecting.\n // When retrying, deduplication is always enabled.\n currentConfig.onErrorRetry(err, key, currentConfig, (_opts)=>{\n const revalidators = EVENT_REVALIDATORS[key];\n if (revalidators && revalidators[0]) {\n revalidators[0](revalidateEvents.ERROR_REVALIDATE_EVENT, _opts);\n }\n }, {\n retryCount: (opts.retryCount || 0) + 1,\n dedupe: true\n });\n }\n }\n }\n }\n }\n // Mark loading as stopped.\n loading = false;\n // Update the current hook's state.\n finishRequestAndUpdateState();\n return true;\n }, // `setState` is immutable, and `eventsCallback`, `fnArg`, and\n // `keyValidating` are depending on `key`, so we can exclude them from\n // the deps array.\n //\n // FIXME:\n // `fn` and `config` might be changed during the lifecycle,\n // but they might be changed every render like this.\n // `useSWR('key', () => fetch('/api/'), { suspense: true })`\n // So we omit the values from the deps array\n // even though it might cause unexpected behaviors.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [\n key,\n cache\n ]);\n // Similar to the global mutate but bound to the current cache and key.\n // `cache` isn't allowed to change during the lifecycle.\n const boundMutate = useCallback(// Use callback to make sure `keyRef.current` returns latest result every time\n (...args)=>{\n return internalMutate(cache, keyRef.current, ...args);\n }, // eslint-disable-next-line react-hooks/exhaustive-deps\n []);\n // The logic for updating refs.\n useIsomorphicLayoutEffect(()=>{\n fetcherRef.current = fetcher;\n configRef.current = config;\n // Handle laggy data updates. If there's cached data of the current key,\n // it'll be the correct reference.\n if (!isUndefined$1(cachedData)) {\n laggyDataRef.current = cachedData;\n }\n });\n // After mounted or key changed.\n useIsomorphicLayoutEffect(()=>{\n if (!key) return;\n const softRevalidate = revalidate.bind(UNDEFINED$1, WITH_DEDUPE);\n let nextFocusRevalidatedAt = 0;\n if (getConfig().revalidateOnFocus) {\n const initNow = Date.now();\n nextFocusRevalidatedAt = initNow + getConfig().focusThrottleInterval;\n }\n // Expose revalidators to global event listeners. So we can trigger\n // revalidation from the outside.\n const onRevalidate = (type, opts = {})=>{\n if (type == revalidateEvents.FOCUS_EVENT) {\n const now = Date.now();\n if (getConfig().revalidateOnFocus && now > nextFocusRevalidatedAt && isActive()) {\n nextFocusRevalidatedAt = now + getConfig().focusThrottleInterval;\n softRevalidate();\n }\n } else if (type == revalidateEvents.RECONNECT_EVENT) {\n if (getConfig().revalidateOnReconnect && isActive()) {\n softRevalidate();\n }\n } else if (type == revalidateEvents.MUTATE_EVENT) {\n return revalidate();\n } else if (type == revalidateEvents.ERROR_REVALIDATE_EVENT) {\n return revalidate(opts);\n }\n return;\n };\n const unsubEvents = subscribeCallback(key, EVENT_REVALIDATORS, onRevalidate);\n // Mark the component as mounted and update corresponding refs.\n unmountedRef.current = false;\n keyRef.current = key;\n initialMountedRef.current = true;\n // Keep the original key in the cache.\n setCache({\n _k: fnArg\n });\n // Trigger a revalidation\n if (shouldDoInitialRevalidation) {\n // Performance optimization: if a request is already in progress for this key,\n // skip the revalidation to avoid redundant work\n if (!FETCH[key]) {\n if (isUndefined$1(data) || IS_SERVER) {\n // Revalidate immediately.\n softRevalidate();\n } else {\n // Delay the revalidate if we have data to return so we won't block\n // rendering.\n rAF(softRevalidate);\n }\n }\n }\n return ()=>{\n // Mark it as unmounted.\n unmountedRef.current = true;\n unsubEvents();\n };\n }, [\n key\n ]);\n // Polling\n useIsomorphicLayoutEffect(()=>{\n let timer;\n function next() {\n // Use the passed interval\n // ...or invoke the function with the updated data to get the interval\n const interval = isFunction$1(refreshInterval) ? refreshInterval(getCache().data) : refreshInterval;\n // We only start the next interval if `refreshInterval` is not 0, and:\n // - `force` is true, which is the start of polling\n // - or `timer` is not 0, which means the effect wasn't canceled\n if (interval && timer !== -1) {\n timer = setTimeout(execute, interval);\n }\n }\n function execute() {\n // Check if it's OK to execute:\n // Only revalidate when the page is visible, online, and not errored.\n if (!getCache().error && (refreshWhenHidden || getConfig().isVisible()) && (refreshWhenOffline || getConfig().isOnline())) {\n revalidate(WITH_DEDUPE).then(next);\n } else {\n // Schedule the next interval to check again.\n next();\n }\n }\n next();\n return ()=>{\n if (timer) {\n clearTimeout(timer);\n timer = -1;\n }\n };\n }, [\n refreshInterval,\n refreshWhenHidden,\n refreshWhenOffline,\n key\n ]);\n // Display debug info in React DevTools.\n useDebugValue(returnedData);\n // In Suspense mode, we can't return the empty `data` state.\n // If there is an `error`, the `error` needs to be thrown to the error boundary.\n // If there is no `error`, the `revalidation` promise needs to be thrown to\n // the suspense boundary.\n if (suspense) {\n // SWR should throw when trying to use Suspense on the server with React 18,\n // without providing any fallback data. This causes hydration errors. See:\n // https://github.com/vercel/swr/issues/1832\n if (!IS_REACT_LEGACY && IS_SERVER && hasKeyButNoData) {\n throw new Error('Fallback data is required when using Suspense in SSR.');\n }\n // Always update fetcher and config refs even with the Suspense mode.\n if (hasKeyButNoData) {\n fetcherRef.current = fetcher;\n configRef.current = config;\n unmountedRef.current = false;\n }\n const req = PRELOAD[key];\n const mutateReq = !isUndefined$1(req) && hasKeyButNoData ? boundMutate(req) : resolvedUndef;\n use(mutateReq);\n if (!isUndefined$1(error) && hasKeyButNoData) {\n throw error;\n }\n const revalidation = hasKeyButNoData ? revalidate(WITH_DEDUPE) : resolvedUndef;\n if (!isUndefined$1(returnedData) && hasKeyButNoData) {\n // @ts-ignore modify react promise status\n revalidation.status = 'fulfilled';\n // @ts-ignore modify react promise value\n revalidation.value = true;\n }\n use(revalidation);\n }\n const swrResponse = {\n mutate: boundMutate,\n get data () {\n stateDependencies.data = true;\n return returnedData;\n },\n get error () {\n stateDependencies.error = true;\n return error;\n },\n get isValidating () {\n stateDependencies.isValidating = true;\n return isValidating;\n },\n get isLoading () {\n stateDependencies.isLoading = true;\n return isLoading;\n }\n };\n return swrResponse;\n};\nconst SWRConfig = OBJECT$1.defineProperty(SWRConfig$1, 'defaultValue', {\n value: defaultConfig\n});\n/**\n * A hook to fetch data.\n *\n * @see {@link https://swr.vercel.app}\n *\n * @example\n * ```jsx\n * import useSWR from 'swr'\n * function Profile() {\n * const { data, error, isLoading } = useSWR('/api/user', fetcher)\n * if (error) return <div>failed to load</div>\n * if (isLoading) return <div>loading...</div>\n * return <div>hello {data.name}!</div>\n * }\n * ```\n */ const useSWR = withArgs(useSWRHandler);\n\n// useSWR\n\nexport { SWRConfig, useSWR as default, unstable_serialize };\n","// SPDX-License-Identifier: MIT\n// Client for the Graffiticode data/compile API. Uses the platform API host derived from\n// the page's location (local console in dev, api.graffiticode.org in prod).\n\nfunction getApiUrl(): string {\n const host = window.document.location.host;\n return host.indexOf(\"localhost\") === 0\n ? \"http://localhost:3100\"\n : \"https://api.graffiticode.org\";\n}\n\nexport const getApiData = async ({\n accessToken,\n id,\n}: {\n accessToken?: string;\n id: string;\n}) => {\n const resp = await fetch(`${getApiUrl()}/data?id=${id}`, {\n headers: { Authorization: accessToken || \"\" },\n });\n const { status, error, data } = await resp.json();\n if (status !== \"success\") {\n throw new Error(`failed to get data ${id}: ${error?.message}`);\n }\n return data;\n};\n\nexport const postApiCompile = async ({\n accessToken,\n id,\n data,\n}: {\n accessToken?: string;\n id: string;\n data: any;\n}) => {\n const resp = await fetch(`${getApiUrl()}/compile`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n authorization: accessToken || \"\",\n \"x-graffiticode-storage-type\": \"persistent\",\n },\n body: JSON.stringify({ id, data }),\n });\n const out = await resp.json();\n if (out.status !== \"success\") {\n throw new Error(`failed to post compile ${id}: ${out.error?.message}`);\n }\n return out.data;\n};\n","// SPDX-License-Identifier: MIT\nimport { postApiCompile, getApiData } from \"../lib/api\";\n\nexport const compile = async ({\n accessToken,\n id,\n data,\n}: {\n accessToken?: string;\n id: string;\n data: any;\n}) => {\n // Empty data → recompile the full id; otherwise recompile with the code id only.\n const index = Object.keys(data).length > 0 ? 1 : 2;\n id = id.split(\"+\").slice(0, index).join(\"+\");\n return await postApiCompile({ accessToken, id, data });\n};\n\nexport const getData = async ({\n accessToken,\n id,\n}: {\n accessToken?: string;\n id: string;\n}) => {\n return await getApiData({ accessToken, id });\n};\n","// SPDX-License-Identifier: MIT\n//\n// View is the SHARED, inherited front-end harness. It manages form state, drives\n// compile/getData, reads its inputs from the URL search params, and posts state to the host\n// via window.parent.postMessage — so it works both embedded in an iframe and standalone. It\n// is parameterized by the language-specific `Form`: child languages import this `View` and\n// inject their own `Form` (the only language-specific UX). L0000 ships the base `Form` (JSON),\n// so its own embed mounts `<View Form={Form} />`.\n//\n// Compile/getData responses use the envelope `{ data, errors }`: successful output in `data`,\n// compile errors in `errors`. The View stores `data` as the form's data model (so recompiles\n// operate on real data, not the envelope) and threads `errors` to the Form alongside it.\n//\n// ── State ──────────────────────────────────────────────────────────────────────────────────\n//\n// The data model lives in React state and every `apply` re-renders. It used to live in an\n// EXTERNAL mutable store (`createState`) that React did not track, which meant a form seeded\n// from the `?data=` search param never appeared at all: the seed mutated the store from an\n// effect, nothing re-rendered, and the harness kept showing the empty `<div/>` it had already\n// committed. Keep state here, and keep the reducer PURE — it is re-run under StrictMode.\n//\n// ── The action protocol ────────────────────────────────────────────────────────────────────\n//\n// `init` replace the model (a fresh load)\n// `compiled` MERGE the compile result over the model. It must not replace: a compile response\n// carries only what the compiler produced, so replacing discards client-side state\n// (focus, in-progress entries) and re-initializes the whole form on every edit.\n// `update` a user edit; merges, and requests a recompile\n// `response` a learner's answer; merges, and requests a recompile\n// `focus` selection tracking; merges under `focus` and does NOT recompile\n//\n// `loaded` the stored model arriving from getData. Merges exactly like `compiled`; it is a\n// separate type only so the harness can tell an EXTERNAL load from the echo of an\n// edit the Form itself just reported (see `formModel` below).\n//\n// `response` and `focus` were previously unhandled, so they fell to the `default:` branch and\n// returned the model UNCHANGED — silently discarding every answer a learner typed into an\n// L0166/L0179 spreadsheet and every response an L0175 item collected.\n//\n// ── formModel: which model the Form is rendered from ───────────────────────────────────────\n//\n// A CONTROLLED Form (the default, `formModel: \"live\"`) renders whatever the model currently\n// says, so it must see every change — including its own edits coming back.\n//\n// An UNCONTROLLED Form owns its own editing state and only SEEDS from the model. L0166's\n// spreadsheet Form — which L0179 injects — is one: its TableEditor builds a ProseMirror\n// document from `interaction.cells` and, whenever that object's IDENTITY changes, rebuilds the\n// whole document and puts the caret back in A1. Feeding such a Form its own reported edits\n// re-seeds it on every keystroke commit: the grid visibly redraws and the selection jumps.\n//\n// L0166 never hits this because its state lives in an untracked closure that re-renders\n// nothing — the editor is seeded once and left alone. `formModel: \"loaded\"` makes that\n// deliberate rather than accidental: the Form renders from the model as last loaded from\n// OUTSIDE it (`init`, `loaded`), while `update`/`response` and the compile results they\n// trigger keep updating the live model for postMessage, recompiles, and reporting.\n//\n// A language whose Form needs different semantics for one of these passes `reduce`. It is\n// consulted FIRST and returns `undefined` for anything it does not claim, so a language adds\n// cases without restating the generic ones. This exists because L0179 injects L0166's\n// spreadsheet Form, whose `update` must merge cell text into `data.interaction.cells` rather\n// than onto the top level — a shape that has no business being hardcoded here.\nimport { useCallback, useEffect, useMemo, useReducer, useRef, useState } from \"react\";\nimport type { ComponentType, CSSProperties } from \"react\";\nimport useSWR from \"swr\";\nimport { compile, getData } from \"./swr/fetchers\";\nimport \"./index.css\";\n\nexport interface CompileError {\n message: string;\n from?: number;\n to?: number;\n}\n\nexport interface StateAction {\n type: string;\n args?: any;\n}\n\n/**\n * A language's extra reducer cases. Return the next data model to claim an action, or\n * `undefined` to fall through to the generic handling below.\n */\nexport type LanguageReducer = (data: any, action: StateAction) => any | undefined;\n\nexport interface FormProps {\n state: {\n data: any;\n errors: CompileError[];\n apply: (action: StateAction) => void;\n };\n}\n\nexport type FormComponent = ComponentType<FormProps>;\n\n/**\n * Which model the Form renders from.\n *\n * `live` — everything, including the Form's own edits coming back (a controlled Form).\n * `loaded` — only the model as last loaded from outside the Form (an uncontrolled Form that\n * seeds itself from the model and owns its editing state thereafter).\n */\nexport type FormModel = \"live\" | \"loaded\";\n\n/** Actions that represent a user changing the form, and so warrant a recompile. */\nconst RECOMPILE_ON = new Set([\"update\", \"response\"]);\n\n/**\n * Actions that carry a model from OUTSIDE the Form, and so may re-seed an uncontrolled one.\n * `compiled` is absent deliberately: after the initial load every compile is a response to an\n * edit the Form itself reported, and re-seeding from it is the flash this exists to stop.\n */\nconst EXTERNAL_LOAD = new Set([\"init\", \"loaded\"]);\n\n// Normalize a response into the { data, errors } envelope. Accepts a bare value (treated\n// as data with no errors) for backward/forward compatibility.\nfunction asEnvelope(payload: any): { data: any; errors: CompileError[] } {\n if (payload && typeof payload === \"object\" && Array.isArray(payload.errors)) {\n return { data: payload.data ?? null, errors: payload.errors };\n }\n return { data: payload, errors: [] };\n}\n\nfunction hasRenderable(data: any, errors: CompileError[]): boolean {\n if (errors.length > 0) return true;\n if (data === undefined || data === null) return false;\n if (typeof data === \"object\" && !Array.isArray(data) && Object.keys(data).length === 0) {\n return false;\n }\n return true;\n}\n\nfunction baseReduce(data: any, { type, args }: StateAction): any {\n switch (type) {\n case \"init\":\n return { ...args };\n case \"compiled\":\n case \"loaded\":\n case \"update\":\n case \"response\":\n return { ...data, ...args };\n case \"focus\":\n return { ...data, focus: args };\n default:\n console.error(`Unimplemented action type: ${type}`);\n return data;\n }\n}\n\n/**\n * Structural equality, used to decide whether an action actually changed the model.\n *\n * This replaces `JSON.stringify(a) === JSON.stringify(b)`, which serialized the ENTIRE model\n * twice on every dispatched action. For a spreadsheet of a few hundred cells that is real work\n * on a path that runs on every keystroke, focus change and response — and it is work done to\n * answer a question that usually resolves on the first differing key.\n *\n * Unlike the stringify comparison this is insensitive to key ORDER, which is the intended\n * meaning: a model whose keys were rebuilt in a different order has not changed.\n */\nconst deepEqual = (a: any, b: any): boolean => {\n if (a === b) return true;\n if (typeof a !== typeof b || a === null || b === null || typeof a !== \"object\") return false;\n if (Array.isArray(a) !== Array.isArray(b)) return false;\n if (Array.isArray(a)) {\n if (a.length !== b.length) return false;\n return a.every((item, i) => deepEqual(item, b[i]));\n }\n const aKeys = Object.keys(a);\n if (aKeys.length !== Object.keys(b).length) return false;\n return aKeys.every((k) => Object.prototype.hasOwnProperty.call(b, k) && deepEqual(a[k], b[k]));\n};\n\ninterface ViewState {\n data: any;\n /**\n * What the Form is rendered from. Under `formModel: \"live\"` it is always `data`; under\n * `\"loaded\"` its IDENTITY only changes on an external load, which is what keeps an\n * uncontrolled Form from re-seeding itself on its own edits.\n */\n renderData: any;\n /** Bumped by each user edit. The compile effect keys off it, never off `data` itself. */\n compileSeq: number;\n /**\n * Bumped whenever `data` changes. Effects that need to run on a real change key off this\n * instead of off a serialization of the whole model.\n */\n version: number;\n}\n\nconst makeReducer =\n (reduce: LanguageReducer | undefined, formModel: FormModel) =>\n (prev: ViewState, action: StateAction): ViewState => {\n const claimed = reduce ? reduce(prev.data, action) : undefined;\n const data = claimed !== undefined ? claimed : baseReduce(prev.data, action);\n if (data === prev.data || deepEqual(data, prev.data)) {\n return prev;\n }\n return {\n data,\n renderData:\n formModel === \"live\" || EXTERNAL_LOAD.has(action.type) ? data : prev.renderData,\n compileSeq: prev.compileSeq + (RECOMPILE_ON.has(action.type) ? 1 : 0),\n version: prev.version + 1,\n };\n };\n\nexport const View = ({\n Form,\n reduce,\n formModel = \"live\",\n}: {\n Form: FormComponent;\n reduce?: LanguageReducer;\n formModel?: FormModel;\n}) => {\n const [params] = useState(() => new URLSearchParams(window.location.search));\n const [id] = useState<string | undefined>(params.get(\"id\") ?? undefined);\n const [accessToken] = useState<string | undefined>(params.get(\"access_token\") ?? undefined);\n const [targetOrigin] = useState<string | undefined>(params.get(\"origin\") ?? undefined);\n const [errors, setErrors] = useState<CompileError[]>([]);\n\n const reducer = useMemo(() => makeReducer(reduce, formModel), [reduce, formModel]);\n const [state, apply] = useReducer(reducer, undefined, () => ({\n data: {},\n renderData: {},\n compileSeq: 0,\n version: 0,\n }));\n const { data, renderData, compileSeq, version } = state;\n\n // Initialize from a `data` search param on first load.\n useEffect(() => {\n const seed = params.get(\"data\");\n if (seed) apply({ type: \"init\", args: JSON.parse(seed) });\n }, []);\n\n // Announce load to the host.\n useEffect(() => {\n if (targetOrigin) {\n window.parent.postMessage({ type: \"onload\", data }, targetOrigin);\n }\n }, []);\n\n // Post state to the host whenever it changes.\n //\n // Keyed on the reducer's own version counter. It used to be keyed on `JSON.stringify(data)`,\n // which serialized the whole model on EVERY render rather than only when something changed —\n // and the reducer already knows the answer, because it returns `prev` untouched when an action\n // changes nothing.\n useEffect(() => {\n if (targetOrigin) {\n window.parent.postMessage({ type: \"data-updated\", data }, targetOrigin);\n }\n }, [version]);\n\n // Fetch stored data when an id is present.\n //\n // Revalidation is off: this is a one-shot load, and a background refetch on window focus\n // would re-apply the STORED model over whatever the learner has since entered — the form\n // silently reverting when you tab away and back.\n const getDataResp = useSWR(id ? { accessToken, id } : null, getData, {\n revalidateOnFocus: false,\n revalidateOnReconnect: false,\n revalidateIfStale: false,\n });\n\n // Apply the loaded data in an EFFECT. Applying it during render (as this used to) both\n // mutated state mid-render and re-ran on every subsequent render, because the SWR result\n // stays populated — the old code only escaped that loop by flipping its own fetch key to\n // null, which is what let a warm cache entry re-apply a stale model later.\n useEffect(() => {\n if (getDataResp.data === undefined) return;\n const env = asEnvelope(getDataResp.data);\n apply({ type: \"loaded\", args: env.data });\n setErrors(env.errors);\n }, [getDataResp.data]);\n\n // Recompile after a user edit.\n //\n // Deliberately NOT SWR: a compile is a mutation, not a cacheable query. Keying it on the\n // data (as this used to) meant returning a cell to a value it already held replayed an\n // OLDER compiled snapshot straight out of the cache, reverting the sheet. A bare request\n // with last-write-wins ordering has no cache to go stale.\n const latestCompile = useRef(0);\n useEffect(() => {\n if (compileSeq === 0 || !id) return;\n const seq = ++latestCompile.current;\n if (targetOrigin) {\n window.parent.postMessage({ focus: { type: \"update\", value: data } }, targetOrigin);\n }\n let cancelled = false;\n (async () => {\n try {\n const out = await compile({ accessToken, id, data });\n // Drop a response that a newer edit has already superseded, so a slow compile can\n // never overwrite a faster one that started later.\n if (cancelled || seq !== latestCompile.current) return;\n const env = asEnvelope(out);\n apply({ type: \"compiled\", args: env.data });\n setErrors(env.errors);\n } catch (err: any) {\n if (!cancelled && seq === latestCompile.current) {\n setErrors([{ message: String(err?.message ?? err) }]);\n }\n }\n })();\n return () => {\n cancelled = true;\n };\n }, [compileSeq]);\n\n // The Form sees `renderData`; everything else here (postMessage, recompiles) uses the live\n // `data`. They are the same object unless the language asked for `formModel: \"loaded\"`, and\n // the fallback covers the one case where they can disagree about EXISTENCE rather than\n // content: a model that arrived without ever passing through an external load.\n const formData = hasRenderable(renderData, []) ? renderData : data;\n const formState = useMemo(() => ({ data: formData, errors, apply }), [formData, errors]);\n\n // Render priority: real content first; otherwise surface why there's none.\n // A getData failure (e.g. a stale/expired token 401ing a public read) used to\n // fall through to a blank `<div/>` with no console output — indistinguishable\n // from \"still loading\" and impossible to diagnose. Show the error (and a\n // retry) instead. Once data has loaded, a later revalidation error is ignored\n // so the form isn't replaced by an error screen.\n const retry = useCallback(() => getDataResp.mutate(), [getDataResp]);\n\n if (hasRenderable(data, errors)) {\n return <Form state={formState} />;\n }\n if (getDataResp.error) {\n return (\n <div role=\"alert\" style={MESSAGE_STYLE}>\n <p style={{ margin: 0, fontWeight: 600 }}>Couldn’t load this form.</p>\n <p style={{ margin: \"4px 0 12px\", color: \"#555\" }}>\n {String((getDataResp.error as { message?: string })?.message ?? getDataResp.error)}\n </p>\n <button type=\"button\" style={RETRY_STYLE} onClick={retry}>\n Retry\n </button>\n </div>\n );\n }\n if (getDataResp.isLoading) {\n return (\n <div role=\"status\" aria-live=\"polite\" style={MESSAGE_STYLE}>\n Loading…\n </div>\n );\n }\n return <div />;\n};\n\nconst MESSAGE_STYLE: CSSProperties = {\n display: \"flex\",\n flexDirection: \"column\",\n alignItems: \"center\",\n justifyContent: \"center\",\n height: \"100%\",\n padding: \"24px\",\n textAlign: \"center\",\n font: \"14px/1.4 system-ui, sans-serif\",\n};\n\nconst RETRY_STYLE: CSSProperties = {\n padding: \"6px 14px\",\n border: \"1px solid #888\",\n borderRadius: \"4px\",\n background: \"#fff\",\n cursor: \"pointer\",\n};\n","// SPDX-License-Identifier: MIT\n//\n// L0000's base Form: renders compile errors when present, otherwise the compiled data\n// model as stringified JSON. This is the trivial default rendering; child languages\n// supply their own Form and inject it into the shared View instead.\nimport \"../../index.css\";\nimport type { FormProps, CompileError } from \"../../view\";\n\nfunction ErrorList({ errors }: { errors: CompileError[] }) {\n return (\n <div className=\"flex flex-col gap-2 font-mono text-xs\">\n {errors.map((error, i) => (\n <div\n key={i}\n className=\"rounded-md border border-red-200 bg-red-50 p-3 text-red-800\"\n >\n {error.message}\n {typeof error.from === \"number\" && error.from >= 0 && (\n <span className=\"ml-2 text-red-400\">\n [{error.from}\n {typeof error.to === \"number\" && error.to >= 0 ? `–${error.to}` : \"\"}]\n </span>\n )}\n </div>\n ))}\n </div>\n );\n}\n\nexport const Form = ({ state }: FormProps) => {\n const errors = state.errors ?? [];\n if (errors.length > 0) {\n return <ErrorList errors={errors} />;\n }\n const source = state.data;\n return (\n <pre className=\"rounded-md bg-zinc-50 text-zinc-900 text-xs font-mono p-4 overflow-auto\">\n {JSON.stringify(source, null, 2)}\n </pre>\n );\n};\n"],"names":["React","require$$0","is","x","y","objectIs","useState","useEffect","useLayoutEffect","useDebugValue","useSyncExternalStore$2","subscribe","getSnapshot","value","_useState","inst","forceUpdate","checkIfSnapshotChanged","latestGetSnapshot","nextValue","useSyncExternalStore$1","shim","useSyncExternalStoreShim_production","didWarnOld18Alpha","didWarnUncachedGetSnapshot","cachedValue","useSyncExternalStoreShim_development","shimModule","require$$1","FOCUS_EVENT","RECONNECT_EVENT","MUTATE_EVENT","ERROR_REVALIDATE_EVENT","has","dequal","foo","bar","ctor","len","SWRGlobalState","noop","UNDEFINED","OBJECT","isUndefined","v","isFunction","mergeObjects","a","b","isPromiseLike","EMPTY_CACHE","INITIAL_CACHE","STR_UNDEFINED","isWindowDefined","isDocumentDefined","isLegacyDeno","hasRequestAnimationFrame","createCacheHelper","cache","key","state","info","prev","online","isOnline","onWindowEvent","offWindowEvent","isVisible","visibilityState","initFocus","callback","initReconnect","onOnline","onOffline","preset","defaultConfigOptions","IS_REACT_LEGACY","IS_SERVER","rAF","f","useIsomorphicLayoutEffect","navigatorConnection","slowConnection","table","getTypeName","isObjectTypeName","typeName","type","counter","stableHash","arg","isDate","isRegex","isPlainObject","result","index","keys","serialize","args","__timestamp","getTimestamp","internalMutate","_key","_data","_opts","options","populateCache","rollbackOnErrorOption","optimisticData","rollbackOnError","error","throwOnError","keyFilter","matchedKeys","it","mutateByKey","_k","get","set","EVENT_REVALIDATORS","MUTATION","FETCH","PRELOAD","startRevalidate","revalidators","revalidateEvents.MUTATE_EVENT","data","isError","beforeMutationTs","hasOptimisticData","displayedData","currentData","committedData","err","populateCachedData","revalidateAllKeys","initCache","provider","opts","mutate","unmount","subscriptions","subs","setter","fn","initProvider","releaseFocus","revalidateEvents.FOCUS_EVENT","releaseReconnect","revalidateEvents.RECONNECT_EVENT","onErrorRetry","_","__","config","revalidate","maxRetryCount","currentRetryCount","timeout","compare","defaultConfig","mergeConfigs","u1","f1","u2","f2","SWRConfigContext","createContext","INFINITE_PREFIX","enableDevtools","use","setupDevTools","normalize","useSWRConfig","parentConfig","useContext","useMemo","middleware","useSWRNext","key_","fetcher_","req","BUILT_IN_MIDDLEWARE","withArgs","hook","fallbackConfig","_config","next","i","subscribeCallback","callbacks","keyedRevalidators","thenable","e","WITH_DEDUPE","resolvedUndef","UNDEFINED$1","sub","noop$1","useSWRHandler","fetcher","suspense","fallbackData","revalidateOnMount","revalidateIfStale","refreshInterval","refreshWhenHidden","refreshWhenOffline","keepPreviousData","strictServerPrefetchWarning","fnArg","serialize$1","initialMountedRef","useRef","unmountedRef","keyRef","fetcherRef","configRef","getConfig","isActive","getCache","setCache","subscribeCache","getInitialCache","stateDependencies","fallback","isUndefined$1","isEqual","current","t","returnedData","isInitialMount","cachedData","initialData","getSelectedCache","snapshot","clientSnapshot","serverSnapshot","memorizedSnapshot","newSnapshot","cached","useSyncExternalStore","useCallback","hasRevalidator","laggyDataRef","hasKeyButNoData","hydrationRef","isHydration","shouldDoInitialRevalidation","defaultValidatingState","isValidating","isLoading","revalidateOpts","currentFetcher","newData","startAt","loading","shouldStartNewRequest","callbackSafeguard","finalState","finishRequestAndUpdateState","cleanupState","requestInfo","initialState","mutationInfo","cacheData","currentConfig","shouldRetryOnError","isFunction$1","revalidateEvents.ERROR_REVALIDATE_EVENT","boundMutate","softRevalidate","nextFocusRevalidatedAt","unsubEvents","now","timer","interval","execute","mutateReq","revalidation","useSWR","getApiUrl","getApiData","accessToken","id","resp","status","postApiCompile","out","_a","compile","getData","RECOMPILE_ON","EXTERNAL_LOAD","asEnvelope","payload","hasRenderable","errors","baseReduce","deepEqual","item","aKeys","k","makeReducer","reduce","formModel","action","claimed","View","Form","params","targetOrigin","setErrors","reducer","apply","useReducer","renderData","compileSeq","version","seed","getDataResp","env","latestCompile","seq","cancelled","formData","formState","retry","jsx","jsxs","MESSAGE_STYLE","RETRY_STYLE","ErrorList","source"],"mappings":";;;;;;;;;;;;;;;;AAWA,MAAIA,IAAQC;AACZ,WAASC,EAAGC,GAAGC,GAAG;AAChB,WAAQD,MAAMC,MAAYD,MAAN,KAAW,IAAIA,MAAM,IAAIC,MAAQD,MAAMA,KAAKC,MAAMA;AAAA,EACxE;AACA,MAAIC,IAA0B,OAAO,OAAO,MAA7B,aAAkC,OAAO,KAAKH,GAC3DI,IAAWN,EAAM,UACjBO,IAAYP,EAAM,WAClBQ,IAAkBR,EAAM,iBACxBS,IAAgBT,EAAM;AACxB,WAASU,EAAuBC,GAAWC,GAAa;AACtD,QAAIC,IAAQD,E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