{ "version": 3, "sources": ["../../../node_modules/timing-function/lib/UnitBezier.js", "../../../node_modules/levenshtein-edit-distance/index.js", "../../../node_modules/propose/propose.js", "../../../node_modules/fast-deep-equal/index.js", "../../../theatre/core/src/index.ts", "../../../theatre/core/src/coreExports.ts", "../../../node_modules/lodash-es/isArray.js", "../../../node_modules/lodash-es/_freeGlobal.js", "../../../node_modules/lodash-es/_root.js", "../../../node_modules/lodash-es/_Symbol.js", "../../../node_modules/lodash-es/_getRawTag.js", "../../../node_modules/lodash-es/_objectToString.js", "../../../node_modules/lodash-es/_baseGetTag.js", "../../../node_modules/lodash-es/isObjectLike.js", "../../../node_modules/lodash-es/isSymbol.js", "../../../node_modules/lodash-es/_isKey.js", "../../../node_modules/lodash-es/isObject.js", "../../../node_modules/lodash-es/isFunction.js", "../../../node_modules/lodash-es/_coreJsData.js", "../../../node_modules/lodash-es/_isMasked.js", "../../../node_modules/lodash-es/_toSource.js", "../../../node_modules/lodash-es/_baseIsNative.js", "../../../node_modules/lodash-es/_getValue.js", "../../../node_modules/lodash-es/_getNative.js", "../../../node_modules/lodash-es/_nativeCreate.js", "../../../node_modules/lodash-es/_hashClear.js", "../../../node_modules/lodash-es/_hashDelete.js", "../../../node_modules/lodash-es/_hashGet.js", "../../../node_modules/lodash-es/_hashHas.js", "../../../node_modules/lodash-es/_hashSet.js", "../../../node_modules/lodash-es/_Hash.js", "../../../node_modules/lodash-es/_listCacheClear.js", "../../../node_modules/lodash-es/eq.js", "../../../node_modules/lodash-es/_assocIndexOf.js", "../../../node_modules/lodash-es/_listCacheDelete.js", "../../../node_modules/lodash-es/_listCacheGet.js", "../../../node_modules/lodash-es/_listCacheHas.js", "../../../node_modules/lodash-es/_listCacheSet.js", "../../../node_modules/lodash-es/_ListCache.js", "../../../node_modules/lodash-es/_Map.js", "../../../node_modules/lodash-es/_mapCacheClear.js", "../../../node_modules/lodash-es/_isKeyable.js", "../../../node_modules/lodash-es/_getMapData.js", "../../../node_modules/lodash-es/_mapCacheDelete.js", "../../../node_modules/lodash-es/_mapCacheGet.js", "../../../node_modules/lodash-es/_mapCacheHas.js", "../../../node_modules/lodash-es/_mapCacheSet.js", "../../../node_modules/lodash-es/_MapCache.js", "../../../node_modules/lodash-es/memoize.js", "../../../node_modules/lodash-es/_memoizeCapped.js", "../../../node_modules/lodash-es/_stringToPath.js", "../../../node_modules/lodash-es/_arrayMap.js", "../../../node_modules/lodash-es/_baseToString.js", "../../../node_modules/lodash-es/toString.js", "../../../node_modules/lodash-es/_castPath.js", "../../../node_modules/lodash-es/_toKey.js", "../../../node_modules/lodash-es/_baseGet.js", "../../../node_modules/lodash-es/get.js", "../../../node_modules/lodash-es/_overArg.js", "../../../node_modules/lodash-es/_getPrototype.js", "../../../node_modules/lodash-es/isPlainObject.js", "../../../node_modules/lodash-es/last.js", "../../dataverse/src/pointer.ts", "../../dataverse/src/utils/updateDeep.ts", "../../dataverse/src/utils/Stack.ts", "../../dataverse/src/prism/Interface.ts", "../../dataverse/src/prism/discoveryMechanism.ts", "../../dataverse/src/prism/prism.ts", "../../dataverse/src/Atom.ts", "../../dataverse/src/pointerToPrism.ts", "../../dataverse/src/val.ts", "../../dataverse/src/Ticker.ts", "../../dataverse/src/PointerProxy.ts", "../../../theatre/core/src/projects/projectsSingleton.ts", "../../../theatre/core/src/privateAPIs.ts", "../../../theatre/shared/src/utils/index.ts", "../../../theatre/shared/src/utils/getDeep.ts", "../../../theatre/shared/src/utils/SimpleCache.ts", "../../../node_modules/lodash-es/_defineProperty.js", "../../../node_modules/lodash-es/_baseAssignValue.js", "../../../node_modules/lodash-es/_assignValue.js", "../../../node_modules/lodash-es/_isIndex.js", "../../../node_modules/lodash-es/_baseSet.js", "../../../node_modules/lodash-es/set.js", "../../../theatre/core/src/sheetObjects/getPropDefaultsOfSheetObject.ts", "../../../theatre/core/src/sequences/interpolationTripleAtPosition.ts", "../../../theatre/shared/src/utils/deepMergeWithCache.ts", "../../../theatre/shared/src/utils/pointerDeep.ts", "../../../theatre/shared/src/utils/valToAtom.ts", "../../../node_modules/lodash-es/_trimmedEndIndex.js", "../../../node_modules/lodash-es/_baseTrim.js", "../../../node_modules/lodash-es/toNumber.js", "../../../node_modules/lodash-es/toFinite.js", "../../../node_modules/lodash-es/toInteger.js", "../../../node_modules/lodash-es/identity.js", "../../../node_modules/lodash-es/_WeakMap.js", "../../../node_modules/lodash-es/_baseCreate.js", "../../../node_modules/lodash-es/_copyArray.js", "../../../node_modules/lodash-es/_arrayEach.js", "../../../node_modules/lodash-es/_copyObject.js", "../../../node_modules/lodash-es/isLength.js", "../../../node_modules/lodash-es/isArrayLike.js", "../../../node_modules/lodash-es/_isPrototype.js", "../../../node_modules/lodash-es/_baseTimes.js", "../../../node_modules/lodash-es/_baseIsArguments.js", "../../../node_modules/lodash-es/isArguments.js", "../../../node_modules/lodash-es/stubFalse.js", "../../../node_modules/lodash-es/isBuffer.js", "../../../node_modules/lodash-es/_baseIsTypedArray.js", "../../../node_modules/lodash-es/_baseUnary.js", "../../../node_modules/lodash-es/_nodeUtil.js", "../../../node_modules/lodash-es/isTypedArray.js", "../../../node_modules/lodash-es/_arrayLikeKeys.js", "../../../node_modules/lodash-es/_nativeKeys.js", "../../../node_modules/lodash-es/_baseKeys.js", "../../../node_modules/lodash-es/keys.js", "../../../node_modules/lodash-es/_nativeKeysIn.js", "../../../node_modules/lodash-es/_baseKeysIn.js", "../../../node_modules/lodash-es/keysIn.js", "../../../node_modules/lodash-es/_arrayPush.js", "../../../node_modules/lodash-es/_baseSlice.js", "../../../node_modules/lodash-es/_castSlice.js", "../../../node_modules/lodash-es/_hasUnicode.js", "../../../node_modules/lodash-es/_asciiToArray.js", "../../../node_modules/lodash-es/_unicodeToArray.js", "../../../node_modules/lodash-es/_stringToArray.js", "../../../node_modules/lodash-es/_baseClamp.js", "../../../node_modules/lodash-es/clamp.js", "../../../node_modules/lodash-es/_stackClear.js", "../../../node_modules/lodash-es/_stackDelete.js", "../../../node_modules/lodash-es/_stackGet.js", "../../../node_modules/lodash-es/_stackHas.js", "../../../node_modules/lodash-es/_stackSet.js", "../../../node_modules/lodash-es/_Stack.js", "../../../node_modules/lodash-es/_baseAssign.js", "../../../node_modules/lodash-es/_baseAssignIn.js", "../../../node_modules/lodash-es/_cloneBuffer.js", "../../../node_modules/lodash-es/_arrayFilter.js", "../../../node_modules/lodash-es/stubArray.js", "../../../node_modules/lodash-es/_getSymbols.js", "../../../node_modules/lodash-es/_copySymbols.js", "../../../node_modules/lodash-es/_getSymbolsIn.js", "../../../node_modules/lodash-es/_copySymbolsIn.js", "../../../node_modules/lodash-es/_baseGetAllKeys.js", "../../../node_modules/lodash-es/_getAllKeys.js", "../../../node_modules/lodash-es/_getAllKeysIn.js", "../../../node_modules/lodash-es/_DataView.js", "../../../node_modules/lodash-es/_Promise.js", "../../../node_modules/lodash-es/_Set.js", "../../../node_modules/lodash-es/_getTag.js", "../../../node_modules/lodash-es/_initCloneArray.js", "../../../node_modules/lodash-es/_Uint8Array.js", "../../../node_modules/lodash-es/_cloneArrayBuffer.js", "../../../node_modules/lodash-es/_cloneDataView.js", "../../../node_modules/lodash-es/_cloneRegExp.js", "../../../node_modules/lodash-es/_cloneSymbol.js", "../../../node_modules/lodash-es/_cloneTypedArray.js", "../../../node_modules/lodash-es/_initCloneByTag.js", "../../../node_modules/lodash-es/_initCloneObject.js", "../../../node_modules/lodash-es/_baseIsMap.js", "../../../node_modules/lodash-es/isMap.js", "../../../node_modules/lodash-es/_baseIsSet.js", "../../../node_modules/lodash-es/isSet.js", "../../../node_modules/lodash-es/_baseClone.js", "../../../node_modules/lodash-es/cloneDeep.js", "../../../node_modules/lodash-es/_setCacheAdd.js", "../../../node_modules/lodash-es/_setCacheHas.js", "../../../node_modules/lodash-es/_SetCache.js", "../../../node_modules/lodash-es/_arraySome.js", "../../../node_modules/lodash-es/_cacheHas.js", "../../../node_modules/lodash-es/_equalArrays.js", "../../../node_modules/lodash-es/_mapToArray.js", "../../../node_modules/lodash-es/_setToArray.js", "../../../node_modules/lodash-es/_equalByTag.js", "../../../node_modules/lodash-es/_equalObjects.js", "../../../node_modules/lodash-es/_baseIsEqualDeep.js", "../../../node_modules/lodash-es/_baseIsEqual.js", "../../../node_modules/lodash-es/_baseIsMatch.js", "../../../node_modules/lodash-es/_isStrictComparable.js", "../../../node_modules/lodash-es/_getMatchData.js", "../../../node_modules/lodash-es/_matchesStrictComparable.js", "../../../node_modules/lodash-es/_baseMatches.js", "../../../node_modules/lodash-es/_baseHasIn.js", "../../../node_modules/lodash-es/_hasPath.js", "../../../node_modules/lodash-es/hasIn.js", "../../../node_modules/lodash-es/_baseMatchesProperty.js", "../../../node_modules/lodash-es/_baseProperty.js", "../../../node_modules/lodash-es/_basePropertyDeep.js", "../../../node_modules/lodash-es/property.js", "../../../node_modules/lodash-es/_baseIteratee.js", "../../../node_modules/lodash-es/_createBaseFor.js", "../../../node_modules/lodash-es/_baseFor.js", "../../../node_modules/lodash-es/_baseForOwn.js", "../../../node_modules/lodash-es/now.js", "../../../node_modules/lodash-es/debounce.js", "../../../node_modules/lodash-es/_parent.js", "../../../node_modules/lodash-es/isInteger.js", "../../../node_modules/lodash-es/mapValues.js", "../../../node_modules/lodash-es/_baseUnset.js", "../../../node_modules/lodash-es/_baseRepeat.js", "../../../node_modules/lodash-es/_asciiSize.js", "../../../node_modules/lodash-es/_unicodeSize.js", "../../../node_modules/lodash-es/_stringSize.js", "../../../node_modules/lodash-es/_createPadding.js", "../../../node_modules/lodash-es/padStart.js", "../../../node_modules/lodash-es/unset.js", "../../../node_modules/lodash-es/lodash.js", "../../../theatre/core/src/sheetObjects/TheatreSheetObject.ts", "../../../theatre/shared/src/utils/memoizeFn.ts", "../../../theatre/shared/src/propTypes/utils.ts", "../../../theatre/core/src/sheetObjects/SheetObject.ts", "../../../theatre/shared/src/_logger/logger.ts", "../../../theatre/shared/src/logger.ts", "../../../theatre/core/src/sheetObjects/getOrderingOfPropTypeConfig.ts", "../../../theatre/core/src/sheetObjects/SheetObjectTemplate.ts", "../../../theatre/shared/src/utils/addresses.ts", "../../../theatre/shared/src/utils/didYouMean.ts", "../../../theatre/shared/src/utils/errors.ts", "../../../theatre/shared/src/utils/defer.ts", "../../../theatre/shared/src/utils/noop.ts", "../../../theatre/core/src/sequences/playbackControllers/DefaultPlaybackController.ts", "../../../theatre/shared/src/globalVariableNames.ts", "../../../theatre/shared/src/notify.ts", "../../../theatre/core/src/sequences/playbackControllers/AudioPlaybackController.ts", "../../../theatre/core/src/rafDrivers.ts", "../../../theatre/core/src/coreTicker.ts", "../../../theatre/core/src/sequences/TheatreSequence.ts", "../../../theatre/shared/src/instanceTypes.ts", "../../../theatre/core/src/sequences/Sequence.ts", "../../../theatre/core/src/propTypes/index.ts", "../../../theatre/shared/src/utils/ellipsify.ts", "../../../theatre/shared/src/utils/userReadableTypeOfValue.ts", "../../../theatre/shared/src/utils/color.ts", "../../../theatre/core/src/propTypes/internals.ts", "../../../theatre/shared/src/utils/slashedPaths.ts", "../../../theatre/core/src/sheets/TheatreSheet.ts", "../../../theatre/core/src/sheets/Sheet.ts", "../../../theatre/core/src/sheets/SheetTemplate.ts", "../../../theatre/shared/src/utils/delay.ts", "../../../node_modules/immer/src/utils/errors.ts", "../../../node_modules/immer/src/utils/common.ts", "../../../node_modules/immer/src/utils/plugins.ts", "../../../node_modules/immer/src/core/scope.ts", "../../../node_modules/immer/src/core/finalize.ts", "../../../node_modules/immer/src/core/proxy.ts", "../../../node_modules/immer/src/core/immerClass.ts", "../../../node_modules/immer/src/core/current.ts", "../../../node_modules/immer/src/plugins/es5.ts", "../../../node_modules/immer/src/plugins/patches.ts", "../../../node_modules/immer/src/plugins/mapset.ts", "../../../node_modules/immer/src/plugins/all.ts", "../../../node_modules/immer/src/immer.ts", "../../../node_modules/immer/src/utils/env.ts", "../../../theatre/shared/src/globals.ts", "../../../theatre/core/src/projects/initialiseProjectState.ts", "../../../theatre/core/src/_coreLogger.ts", "../../../theatre/core/src/projects/Project.ts", "../../../theatre/core/src/projects/TheatreProject.ts", "../../../theatre/core/src/CoreBundle.ts", "../src/core-only.ts"], "sourcesContent": ["// Generated by CoffeeScript 1.8.0\n\n/*\n * Source: http://stackoverflow.com/a/11697909/607997\n * http://codepen.io/onedayitwillmake/details/EHDmw\n * by Mario Gonzalez\n */\n\n/*\n * Solver for cubic bezier curve with implicit control points at (0,0) and (1.0, 1.0)\n */\nvar UnitBezier;\n\nmodule.exports = UnitBezier = (function() {\n function UnitBezier(p1x, p1y, p2x, p2y) {\n this.set(p1x, p1y, p2x, p2y);\n }\n\n UnitBezier.prototype.set = function(p1x, p1y, p2x, p2y) {\n this._cx = 3.0 * p1x;\n this._bx = 3.0 * (p2x - p1x) - this._cx;\n this._ax = 1.0 - this._cx - this._bx;\n this._cy = 3.0 * p1y;\n this._by = 3.0 * (p2y - p1y) - this._cy;\n this._ay = 1.0 - this._cy - this._by;\n };\n\n UnitBezier.epsilon = 1e-6;\n\n UnitBezier.prototype._sampleCurveX = function(t) {\n return ((this._ax * t + this._bx) * t + this._cx) * t;\n };\n\n UnitBezier.prototype._sampleCurveY = function(t) {\n return ((this._ay * t + this._by) * t + this._cy) * t;\n };\n\n UnitBezier.prototype._sampleCurveDerivativeX = function(t) {\n return (3.0 * this._ax * t + 2.0 * this._bx) * t + this._cx;\n };\n\n UnitBezier.prototype._solveCurveX = function(x, epsilon) {\n var d2, i, t0, t1, t2, x2;\n t0 = void 0;\n t1 = void 0;\n t2 = void 0;\n x2 = void 0;\n d2 = void 0;\n i = void 0;\n t2 = x;\n i = 0;\n while (i < 8) {\n x2 = this._sampleCurveX(t2) - x;\n if (Math.abs(x2) < epsilon) {\n return t2;\n }\n d2 = this._sampleCurveDerivativeX(t2);\n if (Math.abs(d2) < epsilon) {\n break;\n }\n t2 = t2 - x2 / d2;\n i++;\n }\n t0 = 0.0;\n t1 = 1.0;\n t2 = x;\n if (t2 < t0) {\n return t0;\n }\n if (t2 > t1) {\n return t1;\n }\n while (t0 < t1) {\n x2 = this._sampleCurveX(t2);\n if (Math.abs(x2 - x) < epsilon) {\n return t2;\n }\n if (x > x2) {\n t0 = t2;\n } else {\n t1 = t2;\n }\n t2 = (t1 - t0) * .5 + t0;\n }\n return t2;\n };\n\n UnitBezier.prototype.solve = function(x, epsilon) {\n return this._sampleCurveY(this._solveCurveX(x, epsilon));\n };\n\n UnitBezier.prototype.solveSimple = function(x) {\n return this._sampleCurveY(this._solveCurveX(x, 1e-6));\n };\n\n return UnitBezier;\n\n})();\n", "var cache,\n codes;\n\ncache = [];\ncodes = [];\n\nfunction levenshtein(value, other, insensitive) {\n var length,\n lengthOther,\n code,\n result,\n distance,\n distanceOther,\n index,\n indexOther;\n\n if (value === other) {\n return 0;\n }\n\n length = value.length;\n lengthOther = other.length;\n\n if (length === 0) {\n return lengthOther;\n }\n\n if (lengthOther === 0) {\n return length;\n }\n\n if (insensitive) {\n value = value.toLowerCase();\n other = other.toLowerCase();\n }\n\n index = 0;\n\n while (index < length) {\n codes[index] = value.charCodeAt(index);\n cache[index] = ++index;\n }\n\n indexOther = 0;\n\n while (indexOther < lengthOther) {\n code = other.charCodeAt(indexOther);\n\n result = distance = indexOther++;\n\n index = -1;\n\n while (++index < length) {\n distanceOther = code === codes[index] ? distance : distance + 1;\n\n distance = cache[index];\n\n cache[index] = result = distance > result\n ? distanceOther > result\n ? result + 1\n : distanceOther\n : distanceOther > distance\n ? distance + 1\n : distanceOther;\n }\n }\n\n return result;\n}\n\nmodule.exports = levenshtein;\n", "var levenshtein = require('levenshtein-edit-distance');\r\n\r\nfunction propose() {\r\n var ratio;\r\n var distance;\r\n var proposed;\r\n var threshold;\r\n var ignoreCase;\r\n var max_ratio = 0;\r\n var word = arguments[0];\r\n var dictionary = arguments[1];\r\n var len = dictionary.length;\r\n var options = arguments[2];\r\n\r\n if (options) {\r\n threshold = options.threshold;\r\n ignoreCase = options.ignoreCase;\r\n }\r\n\r\n if (threshold === undefined)\r\n threshold = 0;\r\n\r\n for (var i = 0; i < len; ++i) {\r\n if (ignoreCase)\r\n distance = levenshtein(word, dictionary[i], true);\r\n else\r\n distance = levenshtein(word, dictionary[i]);\r\n\r\n if (distance > word.length)\r\n ratio = 1 - distance / dictionary[i].length;\r\n else\r\n ratio = 1 - distance / word.length;\r\n\r\n if (ratio > max_ratio) {\r\n max_ratio = ratio;\r\n proposed = dictionary[i];\r\n }\r\n }\r\n\r\n if (max_ratio >= threshold)\r\n return proposed;\r\n\r\n return null;\r\n}\r\n\r\nmodule.exports = propose;", "'use strict';\n\n// do not edit .js files directly - edit src/index.jst\n\n\n\nmodule.exports = function equal(a, b) {\n if (a === b) return true;\n\n if (a && b && typeof a == 'object' && typeof b == 'object') {\n if (a.constructor !== b.constructor) return false;\n\n var length, i, keys;\n if (Array.isArray(a)) {\n length = a.length;\n if (length != b.length) return false;\n for (i = length; i-- !== 0;)\n if (!equal(a[i], b[i])) return false;\n return true;\n }\n\n\n\n if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;\n if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf();\n if (a.toString !== Object.prototype.toString) return a.toString() === b.toString();\n\n keys = Object.keys(a);\n length = keys.length;\n if (length !== Object.keys(b).length) return false;\n\n for (i = length; i-- !== 0;)\n if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;\n\n for (i = length; i-- !== 0;) {\n var key = keys[i];\n\n if (!equal(a[key], b[key])) return false;\n }\n\n return true;\n }\n\n // true if both NaN, false otherwise\n return a!==a && b!==b;\n};\n", "/**\n * The library providing the runtime functionality of Theatre.js.\n *\n * @packageDocumentation\n */\n\nexport * from './coreExports'\nexport type {IProject, IProjectConfig} from './projects/TheatreProject'\nexport type {ISequence} from './sequences/TheatreSequence'\nexport type {ISheetObject} from './sheetObjects/TheatreSheetObject'\nexport type {ISheet} from './sheets/TheatreSheet'\nexport type {UnknownShorthandCompoundProps} from './propTypes'\nimport * as globalVariableNames from '@theatre/shared/globalVariableNames'\nimport type StudioBundle from '@theatre/studio/StudioBundle'\nimport CoreBundle from './CoreBundle'\nimport type {OnDiskState} from './projects/store/storeTypes'\n\n/**\n * NOTE: **INTERNAL and UNSTABLE** - This _WILL_ break between minor versions.\n *\n * This type represents the object returned by `studio.createContnentOfSaveFile()`. It's\n * meant for advanced users who want to interact with the state of projects. In the vast\n * majority of cases, you __should not__ use this type. Either an API for your use-case\n * already exists, or you should open an issue on GitHub: https://github.com/theatre-js/theatre/issues\n *\n */\nexport type __UNSTABLE_Project_OnDiskState = OnDiskState\n\nregisterCoreBundle()\n\n/**\n * @remarks\n * the studio and core need to communicate with each other somehow, and currently we do that\n * by registering each of them as a global variable. This function does the work of registering\n * the core bundle (everything exported from `@theatre/core`) to window.__TheatreJS_CoreBundle.\n */\nfunction registerCoreBundle() {\n // This only works in a browser environment\n if (typeof window == 'undefined') return\n\n // another core bundle may already be registered\n\n const existingBundle: CoreBundle | undefined =\n // @ts-ignore ignore\n window[globalVariableNames.coreBundle]\n\n if (typeof existingBundle !== 'undefined') {\n if (\n typeof existingBundle === 'object' &&\n existingBundle &&\n typeof existingBundle.version === 'string'\n ) {\n /*\n Another core bundle is registered. This usually means the bundler is not configured correctly and\n is bundling `@theatre/core` multiple times, but, there are legitimate scenarios where a user may want\n to include multiple instances of `@theatre/core` on the same page.\n\n For example, an article might embed two separate interactive graphics that\n are made by different teams (and even different tech stacks -- one in JS, the other in clojurescript).\n\n If both of those graphics use Theatre.js, our current setup makes them conflict with one another.\n\n ----------------------\n --------------------\n ----------------------\n -------.\n\n | /\\_/\\ |\n | ( o.o ) | --------> graphic1 made with JS+Theatre.js\n | > ^ < |\n\n ## ---\n ----------------------\n --------------------\n ----------------------\n -------.\n\n | __ _ |\n | o'')}____// | --------> graphic2 made with clojurescript+Theatre.js\n | `_/ ) |\n | (_(_/-(_/ |\n \n ---------------------\n -----\u2665.\n\n @todo Make it possible to have multiple separate bundles on the same page, but still communicate\n that there is more than one bundle so we can warn the user about bundler misconfiguration.\n \n */\n throw new Error(\n `It seems that the module '@theatre/core' is loaded more than once. This could have two possible causes:\\n` +\n `1. You might have two separate versions of Theatre.js in node_modules.\\n` +\n `2. Or this might be a bundling misconfiguration, in case you're using a bundler like Webpack/ESBuild/Rollup.\\n\\n` +\n `Note that it **is okay** to import '@theatre/core' multiple times. But those imports should point to the same module.`,\n )\n } else {\n throw new Error(\n `The variable window.${globalVariableNames.coreBundle} seems to be already set by a module other than @theatre/core.`,\n )\n }\n }\n\n const coreBundle = new CoreBundle()\n\n // @ts-ignore ignore\n window[globalVariableNames.coreBundle] = coreBundle\n\n const possibleExistingStudioBundle: undefined | StudioBundle =\n // @ts-ignore ignore\n window[globalVariableNames.studioBundle]\n\n if (\n possibleExistingStudioBundle &&\n possibleExistingStudioBundle !== null &&\n possibleExistingStudioBundle.type === 'Theatre_StudioBundle'\n ) {\n possibleExistingStudioBundle.registerCoreBundle(coreBundle)\n }\n}\n", "import projectsSingleton from './projects/projectsSingleton'\nimport type {OnDiskState} from './projects/store/storeTypes'\nimport type {IProject, IProjectConfig} from './projects/TheatreProject'\nimport TheatreProject from './projects/TheatreProject'\nimport globals from '@theatre/shared/globals'\nimport * as types from './propTypes'\nimport {InvalidArgumentError} from '@theatre/shared/utils/errors'\nimport {validateName} from '@theatre/shared/utils/sanitizers'\nimport userReadableTypeOfValue from '@theatre/shared/utils/userReadableTypeOfValue'\nimport deepEqual from 'fast-deep-equal'\nimport type {PointerType, Prism} from '@theatre/dataverse'\nimport {isPointer} from '@theatre/dataverse'\nimport {isPrism, pointerToPrism} from '@theatre/dataverse'\nimport type {$IntentionalAny, VoidFn} from '@theatre/shared/utils/types'\nimport type {ProjectId} from '@theatre/shared/utils/ids'\nimport {_coreLogger} from './_coreLogger'\nimport {getCoreTicker} from './coreTicker'\nimport type {IRafDriver} from './rafDrivers'\nimport {privateAPI} from './privateAPIs'\nexport {notify} from '@theatre/shared/notify'\nexport {types}\nexport {createRafDriver} from './rafDrivers'\nexport type {IRafDriver} from './rafDrivers'\n\n/**\n * Returns a project of the given id, or creates one if it doesn't already exist.\n *\n * @remarks\n * If \\@theatre/studio is also loaded, then the state of the project will be managed by the studio.\n *\n * [Learn more about exporting](https://www.theatrejs.com/docs/latest/manual/projects#state)\n *\n * @example\n * Usage:\n * ```ts\n * import {getProject} from '@theatre/core'\n * const config = {} // the config can be empty when starting a new project\n * const project = getProject(\"a-unique-id\", config)\n * ```\n *\n * @example\n * Usage with an explicit state:\n * ```ts\n * import {getProject} from '@theatre/core'\n * import state from './saved-state.json'\n * const config = {state} // here the config contains our saved state\n * const project = getProject(\"a-unique-id\", config)\n * ```\n */\nexport function getProject(id: string, config: IProjectConfig = {}): IProject {\n const existingProject = projectsSingleton.get(id as ProjectId)\n if (existingProject) {\n if (process.env.NODE_ENV !== 'production') {\n if (!deepEqual(config, existingProject.config)) {\n throw new Error(\n `You seem to have called Theatre.getProject(\"${id}\", config) twice, with different config objects. ` +\n `This is disallowed because changing the config of a project on the fly can lead to hard-to-debug issues.\\n\\n` +\n `You can fix this by either calling Theatre.getProject() once per projectId,` +\n ` or calling it multiple times but with the exact same config.`,\n )\n }\n }\n return existingProject.publicApi\n }\n\n const rootLogger = _coreLogger()\n const plogger = rootLogger.named('Project', id)\n\n if (process.env.NODE_ENV !== 'production') {\n validateName(id, 'projectName in Theatre.getProject(projectName)', true)\n validateProjectIdOrThrow(id)\n plogger._debug('validated projectName', {projectName: id})\n }\n\n if (config.state) {\n if (process.env.NODE_ENV !== 'production') {\n shallowValidateOnDiskState(id as ProjectId, config.state)\n plogger._debug('shallow validated config.state on disk')\n } else {\n deepValidateOnDiskState(id as ProjectId, config.state)\n plogger._debug('deep validated config.state on disk')\n }\n } else {\n plogger._debug('no config.state')\n }\n\n return new TheatreProject(id, config)\n}\n\n/**\n * Lightweight validator that only makes sure the state's definitionVersion is correct.\n * Does not do a thorough validation of the state.\n */\nconst shallowValidateOnDiskState = (projectId: ProjectId, s: OnDiskState) => {\n if (\n Array.isArray(s) ||\n s == null ||\n s.definitionVersion !== globals.currentProjectStateDefinitionVersion\n ) {\n throw new InvalidArgumentError(\n `Error validating conf.state in Theatre.getProject(${JSON.stringify(\n projectId,\n )}, conf). The state seems to be formatted in a way that is unreadable to Theatre.js. Read more at https://www.theatrejs.com/docs/latest/manual/projects#state`,\n )\n }\n}\n\nconst deepValidateOnDiskState = (projectId: ProjectId, s: OnDiskState) => {\n shallowValidateOnDiskState(projectId, s)\n // @TODO do a deep validation here\n}\n\nconst validateProjectIdOrThrow = (value: string) => {\n if (typeof value !== 'string') {\n throw new InvalidArgumentError(\n `Argument 'projectId' in \\`Theatre.getProject(projectId, ...)\\` must be a string. Instead, it was ${userReadableTypeOfValue(\n value,\n )}.`,\n )\n }\n\n const idTrimmed = value.trim()\n if (idTrimmed.length !== value.length) {\n throw new InvalidArgumentError(\n `Argument 'projectId' in \\`Theatre.getProject(\"${value}\", ...)\\` should not have surrounding whitespace.`,\n )\n }\n\n if (idTrimmed.length < 3) {\n throw new InvalidArgumentError(\n `Argument 'projectId' in \\`Theatre.getProject(\"${value}\", ...)\\` should be at least 3 characters long.`,\n )\n }\n}\n\n/**\n * Calls `callback` every time the pointed value of `pointer` changes.\n *\n * @param pointer - A Pointer (like `object.props.x`)\n * @param callback - The callback is called every time the value of pointer changes\n * @param rafDriver - (optional) The `rafDriver` to use. Learn how to use `rafDriver`s [from the docs](https://www.theatrejs.com/docs/latest/manual/advanced#rafdrivers).\n * @returns An unsubscribe function\n *\n * @example\n * Usage:\n * ```ts\n * import {getProject, onChange} from '@theatre/core'\n *\n * const obj = getProject(\"A project\").sheet(\"Scene\").object(\"Box\", {position: {x: 0}})\n *\n * const usubscribe = onChange(obj.props.position.x, (x) => {\n * console.log('position.x changed to:', x)\n * })\n *\n * setTimeout(usubscribe, 10000) // stop listening to changes after 10 seconds\n * ```\n */\nexport function onChange<\n P extends PointerType<$IntentionalAny> | Prism<$IntentionalAny>,\n>(\n pointer: P,\n callback: (\n value: P extends PointerType\n ? T\n : P extends Prism\n ? T\n : unknown,\n ) => void,\n rafDriver?: IRafDriver,\n): VoidFn {\n const ticker = rafDriver ? privateAPI(rafDriver).ticker : getCoreTicker()\n\n if (isPointer(pointer)) {\n const pr = pointerToPrism(pointer)\n return pr.onChange(ticker, callback as $IntentionalAny, true)\n } else if (isPrism(pointer)) {\n return pointer.onChange(ticker, callback as $IntentionalAny, true)\n } else {\n throw new Error(\n `Called onChange(p) where p is neither a pointer nor a prism.`,\n )\n }\n}\n\n/**\n * Takes a Pointer and returns the value it points to.\n *\n * @param pointer - A pointer (like `object.props.x`)\n * @returns The value the pointer points to\n *\n * @example\n *\n * Usage\n * ```ts\n * import {val, getProject} from '@theatre/core'\n *\n * const obj = getProject(\"A project\").sheet(\"Scene\").object(\"Box\", {position: {x: 0}})\n *\n * console.log(val(obj.props.position.x)) // logs the value of obj.props.x\n * ```\n */\nexport function val(pointer: PointerType): T {\n if (isPointer(pointer)) {\n return pointerToPrism(pointer).getValue() as $IntentionalAny\n } else {\n throw new Error(`Called val(p) where p is not a pointer.`)\n }\n}\n", "/**\n * Checks if `value` is classified as an `Array` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array, else `false`.\n * @example\n *\n * _.isArray([1, 2, 3]);\n * // => true\n *\n * _.isArray(document.body.children);\n * // => false\n *\n * _.isArray('abc');\n * // => false\n *\n * _.isArray(_.noop);\n * // => false\n */\nvar isArray = Array.isArray;\n\nexport default isArray;\n", "/** Detect free variable `global` from Node.js. */\nvar freeGlobal = typeof global == 'object' && global && global.Object === Object && global;\n\nexport default freeGlobal;\n", "import freeGlobal from './_freeGlobal.js';\n\n/** Detect free variable `self`. */\nvar freeSelf = typeof self == 'object' && self && self.Object === Object && self;\n\n/** Used as a reference to the global object. */\nvar root = freeGlobal || freeSelf || Function('return this')();\n\nexport default root;\n", "import root from './_root.js';\n\n/** Built-in value references. */\nvar Symbol = root.Symbol;\n\nexport default Symbol;\n", "import Symbol from './_Symbol.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar nativeObjectToString = objectProto.toString;\n\n/** Built-in value references. */\nvar symToStringTag = Symbol ? Symbol.toStringTag : undefined;\n\n/**\n * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the raw `toStringTag`.\n */\nfunction getRawTag(value) {\n var isOwn = hasOwnProperty.call(value, symToStringTag),\n tag = value[symToStringTag];\n\n try {\n value[symToStringTag] = undefined;\n var unmasked = true;\n } catch (e) {}\n\n var result = nativeObjectToString.call(value);\n if (unmasked) {\n if (isOwn) {\n value[symToStringTag] = tag;\n } else {\n delete value[symToStringTag];\n }\n }\n return result;\n}\n\nexport default getRawTag;\n", "/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar nativeObjectToString = objectProto.toString;\n\n/**\n * Converts `value` to a string using `Object.prototype.toString`.\n *\n * @private\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n */\nfunction objectToString(value) {\n return nativeObjectToString.call(value);\n}\n\nexport default objectToString;\n", "import Symbol from './_Symbol.js';\nimport getRawTag from './_getRawTag.js';\nimport objectToString from './_objectToString.js';\n\n/** `Object#toString` result references. */\nvar nullTag = '[object Null]',\n undefinedTag = '[object Undefined]';\n\n/** Built-in value references. */\nvar symToStringTag = Symbol ? Symbol.toStringTag : undefined;\n\n/**\n * The base implementation of `getTag` without fallbacks for buggy environments.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\nfunction baseGetTag(value) {\n if (value == null) {\n return value === undefined ? undefinedTag : nullTag;\n }\n return (symToStringTag && symToStringTag in Object(value))\n ? getRawTag(value)\n : objectToString(value);\n}\n\nexport default baseGetTag;\n", "/**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\nfunction isObjectLike(value) {\n return value != null && typeof value == 'object';\n}\n\nexport default isObjectLike;\n", "import baseGetTag from './_baseGetTag.js';\nimport isObjectLike from './isObjectLike.js';\n\n/** `Object#toString` result references. */\nvar symbolTag = '[object Symbol]';\n\n/**\n * Checks if `value` is classified as a `Symbol` primitive or object.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.\n * @example\n *\n * _.isSymbol(Symbol.iterator);\n * // => true\n *\n * _.isSymbol('abc');\n * // => false\n */\nfunction isSymbol(value) {\n return typeof value == 'symbol' ||\n (isObjectLike(value) && baseGetTag(value) == symbolTag);\n}\n\nexport default isSymbol;\n", "import isArray from './isArray.js';\nimport isSymbol from './isSymbol.js';\n\n/** Used to match property names within property paths. */\nvar reIsDeepProp = /\\.|\\[(?:[^[\\]]*|([\"'])(?:(?!\\1)[^\\\\]|\\\\.)*?\\1)\\]/,\n reIsPlainProp = /^\\w*$/;\n\n/**\n * Checks if `value` is a property name and not a property path.\n *\n * @private\n * @param {*} value The value to check.\n * @param {Object} [object] The object to query keys on.\n * @returns {boolean} Returns `true` if `value` is a property name, else `false`.\n */\nfunction isKey(value, object) {\n if (isArray(value)) {\n return false;\n }\n var type = typeof value;\n if (type == 'number' || type == 'symbol' || type == 'boolean' ||\n value == null || isSymbol(value)) {\n return true;\n }\n return reIsPlainProp.test(value) || !reIsDeepProp.test(value) ||\n (object != null && value in Object(object));\n}\n\nexport default isKey;\n", "/**\n * Checks if `value` is the\n * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)\n * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an object, else `false`.\n * @example\n *\n * _.isObject({});\n * // => true\n *\n * _.isObject([1, 2, 3]);\n * // => true\n *\n * _.isObject(_.noop);\n * // => true\n *\n * _.isObject(null);\n * // => false\n */\nfunction isObject(value) {\n var type = typeof value;\n return value != null && (type == 'object' || type == 'function');\n}\n\nexport default isObject;\n", "import baseGetTag from './_baseGetTag.js';\nimport isObject from './isObject.js';\n\n/** `Object#toString` result references. */\nvar asyncTag = '[object AsyncFunction]',\n funcTag = '[object Function]',\n genTag = '[object GeneratorFunction]',\n proxyTag = '[object Proxy]';\n\n/**\n * Checks if `value` is classified as a `Function` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a function, else `false`.\n * @example\n *\n * _.isFunction(_);\n * // => true\n *\n * _.isFunction(/abc/);\n * // => false\n */\nfunction isFunction(value) {\n if (!isObject(value)) {\n return false;\n }\n // The use of `Object#toString` avoids issues with the `typeof` operator\n // in Safari 9 which returns 'object' for typed arrays and other constructors.\n var tag = baseGetTag(value);\n return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;\n}\n\nexport default isFunction;\n", "import root from './_root.js';\n\n/** Used to detect overreaching core-js shims. */\nvar coreJsData = root['__core-js_shared__'];\n\nexport default coreJsData;\n", "import coreJsData from './_coreJsData.js';\n\n/** Used to detect methods masquerading as native. */\nvar maskSrcKey = (function() {\n var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');\n return uid ? ('Symbol(src)_1.' + uid) : '';\n}());\n\n/**\n * Checks if `func` has its source masked.\n *\n * @private\n * @param {Function} func The function to check.\n * @returns {boolean} Returns `true` if `func` is masked, else `false`.\n */\nfunction isMasked(func) {\n return !!maskSrcKey && (maskSrcKey in func);\n}\n\nexport default isMasked;\n", "/** Used for built-in method references. */\nvar funcProto = Function.prototype;\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/**\n * Converts `func` to its source code.\n *\n * @private\n * @param {Function} func The function to convert.\n * @returns {string} Returns the source code.\n */\nfunction toSource(func) {\n if (func != null) {\n try {\n return funcToString.call(func);\n } catch (e) {}\n try {\n return (func + '');\n } catch (e) {}\n }\n return '';\n}\n\nexport default toSource;\n", "import isFunction from './isFunction.js';\nimport isMasked from './_isMasked.js';\nimport isObject from './isObject.js';\nimport toSource from './_toSource.js';\n\n/**\n * Used to match `RegExp`\n * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).\n */\nvar reRegExpChar = /[\\\\^$.*+?()[\\]{}|]/g;\n\n/** Used to detect host constructors (Safari). */\nvar reIsHostCtor = /^\\[object .+?Constructor\\]$/;\n\n/** Used for built-in method references. */\nvar funcProto = Function.prototype,\n objectProto = Object.prototype;\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/** Used to detect if a method is native. */\nvar reIsNative = RegExp('^' +\n funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\\\$&')\n .replace(/hasOwnProperty|(function).*?(?=\\\\\\()| for .+?(?=\\\\\\])/g, '$1.*?') + '$'\n);\n\n/**\n * The base implementation of `_.isNative` without bad shim checks.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a native function,\n * else `false`.\n */\nfunction baseIsNative(value) {\n if (!isObject(value) || isMasked(value)) {\n return false;\n }\n var pattern = isFunction(value) ? reIsNative : reIsHostCtor;\n return pattern.test(toSource(value));\n}\n\nexport default baseIsNative;\n", "/**\n * Gets the value at `key` of `object`.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\nfunction getValue(object, key) {\n return object == null ? undefined : object[key];\n}\n\nexport default getValue;\n", "import baseIsNative from './_baseIsNative.js';\nimport getValue from './_getValue.js';\n\n/**\n * Gets the native function at `key` of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {string} key The key of the method to get.\n * @returns {*} Returns the function if it's native, else `undefined`.\n */\nfunction getNative(object, key) {\n var value = getValue(object, key);\n return baseIsNative(value) ? value : undefined;\n}\n\nexport default getNative;\n", "import getNative from './_getNative.js';\n\n/* Built-in method references that are verified to be native. */\nvar nativeCreate = getNative(Object, 'create');\n\nexport default nativeCreate;\n", "import nativeCreate from './_nativeCreate.js';\n\n/**\n * Removes all key-value entries from the hash.\n *\n * @private\n * @name clear\n * @memberOf Hash\n */\nfunction hashClear() {\n this.__data__ = nativeCreate ? nativeCreate(null) : {};\n this.size = 0;\n}\n\nexport default hashClear;\n", "/**\n * Removes `key` and its value from the hash.\n *\n * @private\n * @name delete\n * @memberOf Hash\n * @param {Object} hash The hash to modify.\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction hashDelete(key) {\n var result = this.has(key) && delete this.__data__[key];\n this.size -= result ? 1 : 0;\n return result;\n}\n\nexport default hashDelete;\n", "import nativeCreate from './_nativeCreate.js';\n\n/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Gets the hash value for `key`.\n *\n * @private\n * @name get\n * @memberOf Hash\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction hashGet(key) {\n var data = this.__data__;\n if (nativeCreate) {\n var result = data[key];\n return result === HASH_UNDEFINED ? undefined : result;\n }\n return hasOwnProperty.call(data, key) ? data[key] : undefined;\n}\n\nexport default hashGet;\n", "import nativeCreate from './_nativeCreate.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Checks if a hash value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Hash\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction hashHas(key) {\n var data = this.__data__;\n return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key);\n}\n\nexport default hashHas;\n", "import nativeCreate from './_nativeCreate.js';\n\n/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/**\n * Sets the hash `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf Hash\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the hash instance.\n */\nfunction hashSet(key, value) {\n var data = this.__data__;\n this.size += this.has(key) ? 0 : 1;\n data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;\n return this;\n}\n\nexport default hashSet;\n", "import hashClear from './_hashClear.js';\nimport hashDelete from './_hashDelete.js';\nimport hashGet from './_hashGet.js';\nimport hashHas from './_hashHas.js';\nimport hashSet from './_hashSet.js';\n\n/**\n * Creates a hash object.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction Hash(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n// Add methods to `Hash`.\nHash.prototype.clear = hashClear;\nHash.prototype['delete'] = hashDelete;\nHash.prototype.get = hashGet;\nHash.prototype.has = hashHas;\nHash.prototype.set = hashSet;\n\nexport default Hash;\n", "/**\n * Removes all key-value entries from the list cache.\n *\n * @private\n * @name clear\n * @memberOf ListCache\n */\nfunction listCacheClear() {\n this.__data__ = [];\n this.size = 0;\n}\n\nexport default listCacheClear;\n", "/**\n * Performs a\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * comparison between two values to determine if they are equivalent.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n * @example\n *\n * var object = { 'a': 1 };\n * var other = { 'a': 1 };\n *\n * _.eq(object, object);\n * // => true\n *\n * _.eq(object, other);\n * // => false\n *\n * _.eq('a', 'a');\n * // => true\n *\n * _.eq('a', Object('a'));\n * // => false\n *\n * _.eq(NaN, NaN);\n * // => true\n */\nfunction eq(value, other) {\n return value === other || (value !== value && other !== other);\n}\n\nexport default eq;\n", "import eq from './eq.js';\n\n/**\n * Gets the index at which the `key` is found in `array` of key-value pairs.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} key The key to search for.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction assocIndexOf(array, key) {\n var length = array.length;\n while (length--) {\n if (eq(array[length][0], key)) {\n return length;\n }\n }\n return -1;\n}\n\nexport default assocIndexOf;\n", "import assocIndexOf from './_assocIndexOf.js';\n\n/** Used for built-in method references. */\nvar arrayProto = Array.prototype;\n\n/** Built-in value references. */\nvar splice = arrayProto.splice;\n\n/**\n * Removes `key` and its value from the list cache.\n *\n * @private\n * @name delete\n * @memberOf ListCache\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction listCacheDelete(key) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n if (index < 0) {\n return false;\n }\n var lastIndex = data.length - 1;\n if (index == lastIndex) {\n data.pop();\n } else {\n splice.call(data, index, 1);\n }\n --this.size;\n return true;\n}\n\nexport default listCacheDelete;\n", "import assocIndexOf from './_assocIndexOf.js';\n\n/**\n * Gets the list cache value for `key`.\n *\n * @private\n * @name get\n * @memberOf ListCache\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction listCacheGet(key) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n return index < 0 ? undefined : data[index][1];\n}\n\nexport default listCacheGet;\n", "import assocIndexOf from './_assocIndexOf.js';\n\n/**\n * Checks if a list cache value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf ListCache\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction listCacheHas(key) {\n return assocIndexOf(this.__data__, key) > -1;\n}\n\nexport default listCacheHas;\n", "import assocIndexOf from './_assocIndexOf.js';\n\n/**\n * Sets the list cache `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf ListCache\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the list cache instance.\n */\nfunction listCacheSet(key, value) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n if (index < 0) {\n ++this.size;\n data.push([key, value]);\n } else {\n data[index][1] = value;\n }\n return this;\n}\n\nexport default listCacheSet;\n", "import listCacheClear from './_listCacheClear.js';\nimport listCacheDelete from './_listCacheDelete.js';\nimport listCacheGet from './_listCacheGet.js';\nimport listCacheHas from './_listCacheHas.js';\nimport listCacheSet from './_listCacheSet.js';\n\n/**\n * Creates an list cache object.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction ListCache(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n// Add methods to `ListCache`.\nListCache.prototype.clear = listCacheClear;\nListCache.prototype['delete'] = listCacheDelete;\nListCache.prototype.get = listCacheGet;\nListCache.prototype.has = listCacheHas;\nListCache.prototype.set = listCacheSet;\n\nexport default ListCache;\n", "import getNative from './_getNative.js';\nimport root from './_root.js';\n\n/* Built-in method references that are verified to be native. */\nvar Map = getNative(root, 'Map');\n\nexport default Map;\n", "import Hash from './_Hash.js';\nimport ListCache from './_ListCache.js';\nimport Map from './_Map.js';\n\n/**\n * Removes all key-value entries from the map.\n *\n * @private\n * @name clear\n * @memberOf MapCache\n */\nfunction mapCacheClear() {\n this.size = 0;\n this.__data__ = {\n 'hash': new Hash,\n 'map': new (Map || ListCache),\n 'string': new Hash\n };\n}\n\nexport default mapCacheClear;\n", "/**\n * Checks if `value` is suitable for use as unique object key.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is suitable, else `false`.\n */\nfunction isKeyable(value) {\n var type = typeof value;\n return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')\n ? (value !== '__proto__')\n : (value === null);\n}\n\nexport default isKeyable;\n", "import isKeyable from './_isKeyable.js';\n\n/**\n * Gets the data for `map`.\n *\n * @private\n * @param {Object} map The map to query.\n * @param {string} key The reference key.\n * @returns {*} Returns the map data.\n */\nfunction getMapData(map, key) {\n var data = map.__data__;\n return isKeyable(key)\n ? data[typeof key == 'string' ? 'string' : 'hash']\n : data.map;\n}\n\nexport default getMapData;\n", "import getMapData from './_getMapData.js';\n\n/**\n * Removes `key` and its value from the map.\n *\n * @private\n * @name delete\n * @memberOf MapCache\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction mapCacheDelete(key) {\n var result = getMapData(this, key)['delete'](key);\n this.size -= result ? 1 : 0;\n return result;\n}\n\nexport default mapCacheDelete;\n", "import getMapData from './_getMapData.js';\n\n/**\n * Gets the map value for `key`.\n *\n * @private\n * @name get\n * @memberOf MapCache\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction mapCacheGet(key) {\n return getMapData(this, key).get(key);\n}\n\nexport default mapCacheGet;\n", "import getMapData from './_getMapData.js';\n\n/**\n * Checks if a map value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf MapCache\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction mapCacheHas(key) {\n return getMapData(this, key).has(key);\n}\n\nexport default mapCacheHas;\n", "import getMapData from './_getMapData.js';\n\n/**\n * Sets the map `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf MapCache\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the map cache instance.\n */\nfunction mapCacheSet(key, value) {\n var data = getMapData(this, key),\n size = data.size;\n\n data.set(key, value);\n this.size += data.size == size ? 0 : 1;\n return this;\n}\n\nexport default mapCacheSet;\n", "import mapCacheClear from './_mapCacheClear.js';\nimport mapCacheDelete from './_mapCacheDelete.js';\nimport mapCacheGet from './_mapCacheGet.js';\nimport mapCacheHas from './_mapCacheHas.js';\nimport mapCacheSet from './_mapCacheSet.js';\n\n/**\n * Creates a map cache object to store key-value pairs.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction MapCache(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n// Add methods to `MapCache`.\nMapCache.prototype.clear = mapCacheClear;\nMapCache.prototype['delete'] = mapCacheDelete;\nMapCache.prototype.get = mapCacheGet;\nMapCache.prototype.has = mapCacheHas;\nMapCache.prototype.set = mapCacheSet;\n\nexport default MapCache;\n", "import MapCache from './_MapCache.js';\n\n/** Error message constants. */\nvar FUNC_ERROR_TEXT = 'Expected a function';\n\n/**\n * Creates a function that memoizes the result of `func`. If `resolver` is\n * provided, it determines the cache key for storing the result based on the\n * arguments provided to the memoized function. By default, the first argument\n * provided to the memoized function is used as the map cache key. The `func`\n * is invoked with the `this` binding of the memoized function.\n *\n * **Note:** The cache is exposed as the `cache` property on the memoized\n * function. Its creation may be customized by replacing the `_.memoize.Cache`\n * constructor with one whose instances implement the\n * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)\n * method interface of `clear`, `delete`, `get`, `has`, and `set`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to have its output memoized.\n * @param {Function} [resolver] The function to resolve the cache key.\n * @returns {Function} Returns the new memoized function.\n * @example\n *\n * var object = { 'a': 1, 'b': 2 };\n * var other = { 'c': 3, 'd': 4 };\n *\n * var values = _.memoize(_.values);\n * values(object);\n * // => [1, 2]\n *\n * values(other);\n * // => [3, 4]\n *\n * object.a = 2;\n * values(object);\n * // => [1, 2]\n *\n * // Modify the result cache.\n * values.cache.set(object, ['a', 'b']);\n * values(object);\n * // => ['a', 'b']\n *\n * // Replace `_.memoize.Cache`.\n * _.memoize.Cache = WeakMap;\n */\nfunction memoize(func, resolver) {\n if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n var memoized = function() {\n var args = arguments,\n key = resolver ? resolver.apply(this, args) : args[0],\n cache = memoized.cache;\n\n if (cache.has(key)) {\n return cache.get(key);\n }\n var result = func.apply(this, args);\n memoized.cache = cache.set(key, result) || cache;\n return result;\n };\n memoized.cache = new (memoize.Cache || MapCache);\n return memoized;\n}\n\n// Expose `MapCache`.\nmemoize.Cache = MapCache;\n\nexport default memoize;\n", "import memoize from './memoize.js';\n\n/** Used as the maximum memoize cache size. */\nvar MAX_MEMOIZE_SIZE = 500;\n\n/**\n * A specialized version of `_.memoize` which clears the memoized function's\n * cache when it exceeds `MAX_MEMOIZE_SIZE`.\n *\n * @private\n * @param {Function} func The function to have its output memoized.\n * @returns {Function} Returns the new memoized function.\n */\nfunction memoizeCapped(func) {\n var result = memoize(func, function(key) {\n if (cache.size === MAX_MEMOIZE_SIZE) {\n cache.clear();\n }\n return key;\n });\n\n var cache = result.cache;\n return result;\n}\n\nexport default memoizeCapped;\n", "import memoizeCapped from './_memoizeCapped.js';\n\n/** Used to match property names within property paths. */\nvar rePropName = /[^.[\\]]+|\\[(?:(-?\\d+(?:\\.\\d+)?)|([\"'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2)\\]|(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))/g;\n\n/** Used to match backslashes in property paths. */\nvar reEscapeChar = /\\\\(\\\\)?/g;\n\n/**\n * Converts `string` to a property path array.\n *\n * @private\n * @param {string} string The string to convert.\n * @returns {Array} Returns the property path array.\n */\nvar stringToPath = memoizeCapped(function(string) {\n var result = [];\n if (string.charCodeAt(0) === 46 /* . */) {\n result.push('');\n }\n string.replace(rePropName, function(match, number, quote, subString) {\n result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match));\n });\n return result;\n});\n\nexport default stringToPath;\n", "/**\n * A specialized version of `_.map` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the new mapped array.\n */\nfunction arrayMap(array, iteratee) {\n var index = -1,\n length = array == null ? 0 : array.length,\n result = Array(length);\n\n while (++index < length) {\n result[index] = iteratee(array[index], index, array);\n }\n return result;\n}\n\nexport default arrayMap;\n", "import Symbol from './_Symbol.js';\nimport arrayMap from './_arrayMap.js';\nimport isArray from './isArray.js';\nimport isSymbol from './isSymbol.js';\n\n/** Used as references for various `Number` constants. */\nvar INFINITY = 1 / 0;\n\n/** Used to convert symbols to primitives and strings. */\nvar symbolProto = Symbol ? Symbol.prototype : undefined,\n symbolToString = symbolProto ? symbolProto.toString : undefined;\n\n/**\n * The base implementation of `_.toString` which doesn't convert nullish\n * values to empty strings.\n *\n * @private\n * @param {*} value The value to process.\n * @returns {string} Returns the string.\n */\nfunction baseToString(value) {\n // Exit early for strings to avoid a performance hit in some environments.\n if (typeof value == 'string') {\n return value;\n }\n if (isArray(value)) {\n // Recursively convert values (susceptible to call stack limits).\n return arrayMap(value, baseToString) + '';\n }\n if (isSymbol(value)) {\n return symbolToString ? symbolToString.call(value) : '';\n }\n var result = (value + '');\n return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;\n}\n\nexport default baseToString;\n", "import baseToString from './_baseToString.js';\n\n/**\n * Converts `value` to a string. An empty string is returned for `null`\n * and `undefined` values. The sign of `-0` is preserved.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n * @example\n *\n * _.toString(null);\n * // => ''\n *\n * _.toString(-0);\n * // => '-0'\n *\n * _.toString([1, 2, 3]);\n * // => '1,2,3'\n */\nfunction toString(value) {\n return value == null ? '' : baseToString(value);\n}\n\nexport default toString;\n", "import isArray from './isArray.js';\nimport isKey from './_isKey.js';\nimport stringToPath from './_stringToPath.js';\nimport toString from './toString.js';\n\n/**\n * Casts `value` to a path array if it's not one.\n *\n * @private\n * @param {*} value The value to inspect.\n * @param {Object} [object] The object to query keys on.\n * @returns {Array} Returns the cast property path array.\n */\nfunction castPath(value, object) {\n if (isArray(value)) {\n return value;\n }\n return isKey(value, object) ? [value] : stringToPath(toString(value));\n}\n\nexport default castPath;\n", "import isSymbol from './isSymbol.js';\n\n/** Used as references for various `Number` constants. */\nvar INFINITY = 1 / 0;\n\n/**\n * Converts `value` to a string key if it's not a string or symbol.\n *\n * @private\n * @param {*} value The value to inspect.\n * @returns {string|symbol} Returns the key.\n */\nfunction toKey(value) {\n if (typeof value == 'string' || isSymbol(value)) {\n return value;\n }\n var result = (value + '');\n return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;\n}\n\nexport default toKey;\n", "import castPath from './_castPath.js';\nimport toKey from './_toKey.js';\n\n/**\n * The base implementation of `_.get` without support for default values.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Array|string} path The path of the property to get.\n * @returns {*} Returns the resolved value.\n */\nfunction baseGet(object, path) {\n path = castPath(path, object);\n\n var index = 0,\n length = path.length;\n\n while (object != null && index < length) {\n object = object[toKey(path[index++])];\n }\n return (index && index == length) ? object : undefined;\n}\n\nexport default baseGet;\n", "import baseGet from './_baseGet.js';\n\n/**\n * Gets the value at `path` of `object`. If the resolved value is\n * `undefined`, the `defaultValue` is returned in its place.\n *\n * @static\n * @memberOf _\n * @since 3.7.0\n * @category Object\n * @param {Object} object The object to query.\n * @param {Array|string} path The path of the property to get.\n * @param {*} [defaultValue] The value returned for `undefined` resolved values.\n * @returns {*} Returns the resolved value.\n * @example\n *\n * var object = { 'a': [{ 'b': { 'c': 3 } }] };\n *\n * _.get(object, 'a[0].b.c');\n * // => 3\n *\n * _.get(object, ['a', '0', 'b', 'c']);\n * // => 3\n *\n * _.get(object, 'a.b.c', 'default');\n * // => 'default'\n */\nfunction get(object, path, defaultValue) {\n var result = object == null ? undefined : baseGet(object, path);\n return result === undefined ? defaultValue : result;\n}\n\nexport default get;\n", "/**\n * Creates a unary function that invokes `func` with its argument transformed.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {Function} transform The argument transform.\n * @returns {Function} Returns the new function.\n */\nfunction overArg(func, transform) {\n return function(arg) {\n return func(transform(arg));\n };\n}\n\nexport default overArg;\n", "import overArg from './_overArg.js';\n\n/** Built-in value references. */\nvar getPrototype = overArg(Object.getPrototypeOf, Object);\n\nexport default getPrototype;\n", "import baseGetTag from './_baseGetTag.js';\nimport getPrototype from './_getPrototype.js';\nimport isObjectLike from './isObjectLike.js';\n\n/** `Object#toString` result references. */\nvar objectTag = '[object Object]';\n\n/** Used for built-in method references. */\nvar funcProto = Function.prototype,\n objectProto = Object.prototype;\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/** Used to infer the `Object` constructor. */\nvar objectCtorString = funcToString.call(Object);\n\n/**\n * Checks if `value` is a plain object, that is, an object created by the\n * `Object` constructor or one with a `[[Prototype]]` of `null`.\n *\n * @static\n * @memberOf _\n * @since 0.8.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * }\n *\n * _.isPlainObject(new Foo);\n * // => false\n *\n * _.isPlainObject([1, 2, 3]);\n * // => false\n *\n * _.isPlainObject({ 'x': 0, 'y': 0 });\n * // => true\n *\n * _.isPlainObject(Object.create(null));\n * // => true\n */\nfunction isPlainObject(value) {\n if (!isObjectLike(value) || baseGetTag(value) != objectTag) {\n return false;\n }\n var proto = getPrototype(value);\n if (proto === null) {\n return true;\n }\n var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor;\n return typeof Ctor == 'function' && Ctor instanceof Ctor &&\n funcToString.call(Ctor) == objectCtorString;\n}\n\nexport default isPlainObject;\n", "/**\n * Gets the last element of `array`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to query.\n * @returns {*} Returns the last element of `array`.\n * @example\n *\n * _.last([1, 2, 3]);\n * // => 3\n */\nfunction last(array) {\n var length = array == null ? 0 : array.length;\n return length ? array[length - 1] : undefined;\n}\n\nexport default last;\n", "import type {$IntentionalAny} from './types'\n\ntype PathToProp = Array\n\nexport type PointerMeta = {\n root: {}\n path: (string | number)[]\n}\n\n/** We are using an empty object as a WeakMap key for storing pointer meta data */\ntype WeakPointerKey = {}\n\nexport type UnindexableTypesForPointer =\n | number\n | string\n | boolean\n | null\n | void\n | undefined\n | Function // eslint-disable-line @typescript-eslint/ban-types\n\nexport type UnindexablePointer = {\n [K in $IntentionalAny]: Pointer\n}\n\nconst pointerMetaWeakMap = new WeakMap()\nconst cachedSubPathPointersWeakMap = new WeakMap<\n WeakPointerKey,\n Map>\n>()\n\n/**\n * A wrapper type for the type a `Pointer` points to.\n */\nexport type PointerType = {\n /**\n * Only accessible via the type system.\n * This is a helper for getting the underlying pointer type\n * via the type space.\n */\n $$__pointer_type: O\n}\n\n/**\n * The type of {@link Atom} pointers. See {@link pointer|pointer()} for an\n * explanation of pointers.\n *\n * @see Atom\n *\n * @remarks\n * The Pointer type is quite tricky because it doesn't play well with `any` and other inexact types.\n * Here is an example that one would expect to work, but currently doesn't:\n * ```ts\n * declare function expectAnyPointer(pointer: Pointer): void\n *\n * expectAnyPointer(null as Pointer<{}>) // this shows as a type error because Pointer<{}> is not assignable to Pointer, even though it should\n * ```\n *\n * The current solution is to just avoid using `any` with pointer-related code (or type-test it well).\n * But if you enjoy solving typescript puzzles, consider fixing this :)\n * Potentially, [TypeScript variance annotations in 4.7+](https://devblogs.microsoft.com/typescript/announcing-typescript-4-7-beta/#optional-variance-annotations-for-type-parameters)\n * might be able to help us.\n */\nexport type Pointer = PointerType &\n // `Exclude` will remove `undefined` from the first type\n // `undefined extends O ? undefined : never` will give us `undefined` if `O` is `... | undefined`\n PointerInner, undefined extends O ? undefined : never>\n\n// By separating the `O` (non-undefined) from the `undefined` or `never`, we\n// can properly use `O extends ...` to determine the kind of potential value\n// without actually discarding optionality information.\ntype PointerInner = O extends UnindexableTypesForPointer\n ? UnindexablePointer\n : unknown extends O\n ? UnindexablePointer\n : O extends (infer T)[]\n ? Pointer[]\n : O extends {}\n ? {\n [K in keyof O]-?: Pointer\n }\n : UnindexablePointer\n\nconst pointerMetaSymbol = Symbol('pointerMeta')\n\nconst proxyHandler = {\n get(\n pointerKey: WeakPointerKey,\n prop: string | typeof pointerMetaSymbol,\n ): $IntentionalAny {\n if (prop === pointerMetaSymbol) return pointerMetaWeakMap.get(pointerKey)!\n\n let subPathPointers = cachedSubPathPointersWeakMap.get(pointerKey)\n if (!subPathPointers) {\n subPathPointers = new Map()\n cachedSubPathPointersWeakMap.set(pointerKey, subPathPointers)\n }\n\n const existing = subPathPointers.get(prop)\n if (existing !== undefined) return existing\n\n const meta = pointerMetaWeakMap.get(pointerKey)!\n\n const subPointer = pointer({root: meta.root, path: [...meta.path, prop]})\n subPathPointers.set(prop, subPointer)\n return subPointer\n },\n}\n\n/**\n * Returns the metadata associated with the pointer. Usually the root object and\n * the path.\n *\n * @param p - The pointer.\n */\nexport const getPointerMeta = <_>(p: PointerType<_>): PointerMeta => {\n // @ts-ignore @todo\n const meta: PointerMeta = p[\n pointerMetaSymbol as unknown as $IntentionalAny\n ] as $IntentionalAny\n return meta\n}\n\n/**\n * Returns the root object and the path of the pointer.\n *\n * @example\n * ```ts\n * const {root, path} = getPointerParts(pointer)\n * ```\n *\n * @param p - The pointer.\n *\n * @returns An object with two properties: `root`-the root object or the pointer, and `path`-the path of the pointer. `path` is an array of the property-chain.\n */\nexport const getPointerParts = <_>(\n p: Pointer<_>,\n): {root: {}; path: PathToProp} => {\n const {root, path} = getPointerMeta(p)\n return {root, path}\n}\n\n/**\n * Creates a pointer to a (nested) property of an {@link Atom}.\n *\n * @remarks\n * Pointers are used to make prisms of properties or nested properties of\n * {@link Atom|Atoms}.\n *\n * Pointers also allow easy construction of new pointers pointing to nested members\n * of the root object, by simply using property chaining. E.g. `somePointer.a.b` will\n * create a new pointer that has `'a'` and `'b'` added to the path of `somePointer`.\n *\n * @example\n * ```ts\n * // Here, sum is a prism that updates whenever the a or b prop of someAtom does.\n * const sum = prism(() => {\n * return val(pointer({root: someAtom, path: ['a']})) + val(pointer({root: someAtom, path: ['b']}));\n * });\n *\n * // Note, atoms have a convenience Atom.pointer property that points to the root,\n * // which you would normally use in this situation.\n * const sum = prism(() => {\n * return val(someAtom.pointer.a) + val(someAtom.pointer.b);\n * });\n * ```\n *\n * @param args - The pointer parameters.\n *\n * @typeParam O - The type of the value being pointed to.\n */\nfunction pointer(args: {root: {}; path?: Array}) {\n const meta: PointerMeta = {\n root: args.root as $IntentionalAny,\n path: args.path ?? [],\n }\n const pointerKey: WeakPointerKey = {}\n pointerMetaWeakMap.set(pointerKey, meta)\n return new Proxy(pointerKey, proxyHandler) as Pointer\n}\n\nexport default pointer\n\n/**\n * Returns whether `p` is a pointer.\n */\nexport const isPointer = (p: $IntentionalAny): p is Pointer => {\n return p && !!getPointerMeta(p)\n}\n", "import type {$FixMe, $IntentionalAny} from '../types'\n\nexport default function updateDeep(\n state: S,\n path: (string | number | undefined)[],\n reducer: (...args: $IntentionalAny[]) => $IntentionalAny,\n): S {\n if (path.length === 0) return reducer(state)\n return hoop(state, path as $IntentionalAny, reducer)\n}\n\nconst hoop = (\n s: $FixMe,\n path: (string | number)[],\n reducer: $FixMe,\n): $FixMe => {\n if (path.length === 0) {\n return reducer(s)\n }\n if (Array.isArray(s)) {\n let [index, ...restOfPath] = path\n index = parseInt(String(index), 10)\n if (isNaN(index)) index = 0\n const oldVal = s[index]\n const newVal = hoop(oldVal, restOfPath, reducer)\n if (oldVal === newVal) return s\n const newS = [...s]\n newS.splice(index, 1, newVal)\n return newS\n } else if (typeof s === 'object' && s !== null) {\n const [key, ...restOfPath] = path\n const oldVal = s[key]\n const newVal = hoop(oldVal, restOfPath, reducer)\n if (oldVal === newVal) return s\n const newS = {...s, [key]: newVal}\n return newS\n } else {\n const [key, ...restOfPath] = path\n\n return {[key]: hoop(undefined, restOfPath, reducer)}\n }\n}\n", "interface Node {\n next: undefined | Node\n data: Data\n}\n\n/**\n * Just a simple LinkedList\n */\nexport default class Stack {\n _head: undefined | Node\n\n constructor() {\n this._head = undefined\n }\n\n peek() {\n return this._head && this._head.data\n }\n\n pop() {\n const head = this._head\n if (!head) {\n return undefined\n }\n this._head = head.next\n return head.data\n }\n\n push(data: Data) {\n const node = {next: this._head, data}\n this._head = node\n }\n}\n", "import type Ticker from '../Ticker'\nimport type {$IntentionalAny, VoidFn} from '../types'\n\ntype IDependent = (msgComingFrom: Prism<$IntentionalAny>) => void\n\n/**\n * Common interface for prisms.\n */\nexport interface Prism {\n /**\n * Whether the object is a prism.\n */\n isPrism: true\n\n /**\n * Whether the prism is hot.\n */\n isHot: boolean\n\n /**\n * Calls `listener` with a fresh value every time the prism _has_ a new value, throttled by Ticker.\n */\n onChange(\n ticker: Ticker,\n listener: (v: V) => void,\n immediate?: boolean,\n ): VoidFn\n\n onStale(cb: () => void): VoidFn\n\n /**\n * Keep the prism hot, even if there are no tappers (subscribers).\n */\n keepHot(): VoidFn\n\n /**\n * Add a prism as a dependent of this prism.\n *\n * @param d - The prism to be made a dependent of this prism.\n *\n * @see _removeDependent\n *\n * @internal\n */\n _addDependent(d: IDependent): void\n\n /**\n * Remove a prism as a dependent of this prism.\n *\n * @param d - The prism to be removed from as a dependent of this prism.\n *\n * @see _addDependent\n * @internal\n */\n _removeDependent(d: IDependent): void\n\n /**\n * Gets the current value of the prism. If the value is stale, it causes the prism to freshen.\n */\n getValue(): V\n}\n\n/**\n * Returns whether `d` is a prism.\n */\nexport function isPrism(d: any): d is Prism {\n return !!(d && d.isPrism && d.isPrism === true)\n}\n", "import type {$IntentionalAny} from '../types'\nimport Stack from '../utils/Stack'\nimport type {Prism} from './Interface'\n\nfunction createMechanism() {\n const noop = () => {}\n\n const stack = new Stack()\n const noopCollector: Collector = noop\n\n type Collector = (d: Prism<$IntentionalAny>) => void\n\n const pushCollector = (collector: Collector): void => {\n stack.push(collector)\n }\n\n const popCollector = (collector: Collector): void => {\n const existing = stack.peek()\n if (existing !== collector) {\n throw new Error(`Popped collector is not on top of the stack`)\n }\n stack.pop()\n }\n\n const startIgnoringDependencies = () => {\n stack.push(noopCollector)\n }\n\n const stopIgnoringDependencies = () => {\n if (stack.peek() !== noopCollector) {\n if (process.env.NODE_ENV === 'development') {\n console.warn('This should never happen')\n }\n } else {\n stack.pop()\n }\n }\n\n const reportResolutionStart = (d: Prism<$IntentionalAny>) => {\n const possibleCollector = stack.peek()\n if (possibleCollector) {\n possibleCollector(d)\n }\n\n stack.push(noopCollector)\n }\n\n const reportResolutionEnd = (_d: Prism<$IntentionalAny>) => {\n stack.pop()\n }\n\n return {\n type: 'Dataverse_discoveryMechanism' as 'Dataverse_discoveryMechanism',\n startIgnoringDependencies,\n stopIgnoringDependencies,\n reportResolutionStart,\n reportResolutionEnd,\n pushCollector,\n popCollector,\n }\n}\n\nfunction getSharedMechanism(): ReturnType {\n const varName = '__dataverse_discoveryMechanism_sharedStack'\n const root =\n typeof window !== 'undefined'\n ? window\n : typeof global !== 'undefined'\n ? global\n : {}\n if (root) {\n const existingMechanism: ReturnType | undefined =\n // @ts-ignore ignore\n root[varName]\n if (\n existingMechanism &&\n typeof existingMechanism === 'object' &&\n existingMechanism.type === 'Dataverse_discoveryMechanism'\n ) {\n return existingMechanism\n } else {\n const mechanism = createMechanism()\n // @ts-ignore ignore\n root[varName] = mechanism\n return mechanism\n }\n } else {\n return createMechanism()\n }\n}\n\nexport const {\n startIgnoringDependencies,\n stopIgnoringDependencies,\n reportResolutionEnd,\n reportResolutionStart,\n pushCollector,\n popCollector,\n} = getSharedMechanism()\n", "import type Ticker from '../Ticker'\nimport type {$IntentionalAny, VoidFn} from '../types'\nimport Stack from '../utils/Stack'\nimport type {Prism} from './Interface'\nimport {isPrism} from './Interface'\nimport {\n startIgnoringDependencies,\n stopIgnoringDependencies,\n pushCollector,\n popCollector,\n reportResolutionStart,\n reportResolutionEnd,\n} from './discoveryMechanism'\n\ntype IDependent = (msgComingFrom: Prism<$IntentionalAny>) => void\n\nconst voidFn = () => {}\n\nclass HotHandle {\n private _didMarkDependentsAsStale: boolean = false\n private _isFresh: boolean = false\n protected _cacheOfDendencyValues: Map, unknown> = new Map()\n\n /**\n * @internal\n */\n protected _dependents: Set = new Set()\n\n /**\n * @internal\n */\n protected _dependencies: Set> = new Set()\n\n protected _possiblyStaleDeps = new Set>()\n\n private _scope: HotScope = new HotScope(\n this as $IntentionalAny as HotHandle,\n )\n\n /**\n * @internal\n */\n protected _lastValue: undefined | V = undefined\n\n /**\n * If true, the prism is stale even though its dependencies aren't\n * marked as such. This is used by `prism.source()` and `prism.state()`\n * to mark the prism as stale.\n */\n private _forciblySetToStale: boolean = false\n\n constructor(\n private readonly _fn: () => V,\n private readonly _prismInstance: PrismInstance,\n ) {\n for (const d of this._dependencies) {\n d._addDependent(this._reactToDependencyGoingStale)\n }\n\n startIgnoringDependencies()\n this.getValue()\n stopIgnoringDependencies()\n }\n\n get hasDependents(): boolean {\n return this._dependents.size > 0\n }\n removeDependent(d: IDependent) {\n this._dependents.delete(d)\n }\n addDependent(d: IDependent) {\n this._dependents.add(d)\n }\n\n destroy() {\n for (const d of this._dependencies) {\n d._removeDependent(this._reactToDependencyGoingStale)\n }\n cleanupScopeStack(this._scope)\n }\n\n getValue(): V {\n if (!this._isFresh) {\n const newValue = this._recalculate()\n this._lastValue = newValue\n this._isFresh = true\n this._didMarkDependentsAsStale = false\n this._forciblySetToStale = false\n }\n return this._lastValue!\n }\n\n _recalculate() {\n let value: V\n\n if (!this._forciblySetToStale) {\n if (this._possiblyStaleDeps.size > 0) {\n let anActuallyStaleDepWasFound = false\n startIgnoringDependencies()\n for (const dep of this._possiblyStaleDeps) {\n if (this._cacheOfDendencyValues.get(dep) !== dep.getValue()) {\n anActuallyStaleDepWasFound = true\n break\n }\n }\n stopIgnoringDependencies()\n this._possiblyStaleDeps.clear()\n if (!anActuallyStaleDepWasFound) {\n return this._lastValue!\n }\n }\n }\n\n const newDeps: Set> = new Set()\n this._cacheOfDendencyValues.clear()\n\n const collector = (observedDep: Prism): void => {\n newDeps.add(observedDep)\n this._addDependency(observedDep)\n }\n\n pushCollector(collector)\n\n hookScopeStack.push(this._scope)\n try {\n value = this._fn()\n } catch (error) {\n console.error(error)\n } finally {\n const topOfTheStack = hookScopeStack.pop()\n if (topOfTheStack !== this._scope) {\n console.warn(\n // @todo guide the user to report the bug in an issue\n `The Prism hook stack has slipped. This is a bug.`,\n )\n }\n }\n\n popCollector(collector)\n\n for (const dep of this._dependencies) {\n if (!newDeps.has(dep)) {\n this._removeDependency(dep)\n }\n }\n\n this._dependencies = newDeps\n\n startIgnoringDependencies()\n for (const dep of newDeps) {\n this._cacheOfDendencyValues.set(dep, dep.getValue())\n }\n stopIgnoringDependencies()\n\n return value!\n }\n\n forceStale() {\n this._forciblySetToStale = true\n this._markAsStale()\n }\n\n protected _reactToDependencyGoingStale = (which: Prism<$IntentionalAny>) => {\n this._possiblyStaleDeps.add(which)\n\n this._markAsStale()\n }\n\n private _markAsStale() {\n if (this._didMarkDependentsAsStale) return\n\n this._didMarkDependentsAsStale = true\n this._isFresh = false\n\n for (const dependent of this._dependents) {\n dependent(this._prismInstance)\n }\n }\n\n /**\n * @internal\n */\n protected _addDependency(d: Prism<$IntentionalAny>) {\n if (this._dependencies.has(d)) return\n this._dependencies.add(d)\n d._addDependent(this._reactToDependencyGoingStale)\n }\n\n /**\n * @internal\n */\n protected _removeDependency(d: Prism<$IntentionalAny>) {\n if (!this._dependencies.has(d)) return\n this._dependencies.delete(d)\n d._removeDependent(this._reactToDependencyGoingStale)\n }\n}\n\nconst emptyObject = {}\n\nclass PrismInstance implements Prism {\n /**\n * Whether the object is a prism.\n */\n readonly isPrism: true = true\n\n private _state:\n | {hot: false; handle: undefined}\n | {hot: true; handle: HotHandle} = {\n hot: false,\n handle: undefined,\n }\n\n constructor(private readonly _fn: () => V) {}\n\n /**\n * Whether the prism is hot.\n */\n get isHot(): boolean {\n return this._state.hot\n }\n\n onChange(\n ticker: Ticker,\n listener: (v: V) => void,\n immediate: boolean = false,\n ): VoidFn {\n // the prism will call this function every time it goes from fresh to stale\n const dependent = () => {\n // schedule the listener to be called on the next tick, unless\n // we're already on a tick, in which case it'll be called on the current tick.\n ticker.onThisOrNextTick(refresh)\n }\n\n // let's cache the last value so we don't call the listener if the value hasn't changed\n let lastValue: V | typeof emptyObject =\n // use an empty object as the initial value so that the listener is called on the first tick.\n // if we were to use, say, undefined, and this.getValue() also returned undefined, the listener\n // would never be called.\n emptyObject\n\n // this function will be _scheduled_ to be called on the currently running, or next tick,\n // after the prism has gone from fresh to stale.\n const refresh = () => {\n const newValue = this.getValue()\n // if the value hasn't changed, don't call the listener\n if (newValue === lastValue) return\n\n // the value has changed - cache it\n lastValue = newValue\n\n // and let the listener know\n listener(newValue)\n }\n\n // add the dependent to the prism's list of dependents (which will make it go hot)\n this._addDependent(dependent)\n\n // if the caller wants the listener to be called immediately, call it now\n if (immediate) {\n lastValue = this.getValue()\n listener(lastValue as $IntentionalAny as V)\n }\n\n // the unsubscribe function\n const unsubscribe = () => {\n // remove the dependent from the prism's list of dependents (and if it was the last dependent, the prism will go cold)\n this._removeDependent(dependent)\n // in case we're scheduled for a tick, cancel that\n ticker.offThisOrNextTick(refresh)\n ticker.offNextTick(refresh)\n }\n\n return unsubscribe\n }\n\n /**\n * Calls `callback` every time the prism's state goes from `fresh-\\>stale.` Returns an `unsubscribe()` function.\n */\n onStale(callback: () => void): VoidFn {\n const untap = () => {\n this._removeDependent(fn)\n }\n const fn = () => callback()\n this._addDependent(fn)\n return untap\n }\n\n /**\n * Keep the prism hot, even if there are no tappers (subscribers).\n */\n keepHot() {\n return this.onStale(() => {})\n }\n\n /**\n * Add a prism as a dependent of this prism.\n *\n * @param d - The prism to be made a dependent of this prism.\n *\n * @see _removeDependent\n */\n _addDependent(d: IDependent) {\n if (!this._state.hot) {\n this._goHot()\n }\n this._state.handle!.addDependent(d)\n }\n\n private _goHot() {\n const hotHandle = new HotHandle(this._fn, this)\n this._state = {\n hot: true,\n handle: hotHandle,\n }\n }\n\n /**\n * Remove a prism as a dependent of this prism.\n *\n * @param d - The prism to be removed from as a dependent of this prism.\n *\n * @see _addDependent\n */\n _removeDependent(d: IDependent) {\n const state = this._state\n if (!state.hot) {\n return\n }\n const handle = state.handle\n handle.removeDependent(d)\n if (!handle.hasDependents) {\n this._state = {hot: false, handle: undefined}\n handle.destroy()\n }\n }\n\n /**\n * Gets the current value of the prism. If the value is stale, it causes the prism to freshen.\n */\n getValue(): V {\n /**\n * TODO We should prevent (or warn about) a common mistake users make, which is reading the value of\n * a prism in the body of a react component (e.g. `der.getValue()` (often via `val()`) instead of `useVal()`\n * or `uesPrism()`).\n *\n * Although that's the most common example of this mistake, you can also find it outside of react components.\n * Basically the user runs `der.getValue()` assuming the read is detected by a wrapping prism when it's not.\n *\n * Sometiems the prism isn't even hot when the user assumes it is.\n *\n * We can fix this type of mistake by:\n * 1. Warning the user when they call `getValue()` on a cold prism.\n * 2. Warning the user about calling `getValue()` on a hot-but-stale prism\n * if `getValue()` isn't called by a known mechanism like a `PrismEmitter`.\n *\n * Design constraints:\n * - This fix should not have a perf-penalty in production. Perhaps use a global flag + `process.env.NODE_ENV !== 'production'`\n * to enable it.\n * - In the case of `onStale()`, we don't control when the user calls\n * `getValue()` (as opposed to `onChange()` which calls `getValue()` directly).\n * Perhaps we can disable the check in that case.\n * - Probably the best place to add this check is right here in this method plus some changes to `reportResulutionStart()`,\n * which would have to be changed to let the caller know if there is an actual collector (a prism)\n * present in its stack.\n */\n reportResolutionStart(this)\n\n const state = this._state\n\n let val: V\n if (state.hot) {\n val = state.handle.getValue()\n } else {\n val = calculateColdPrism(this._fn)\n }\n\n reportResolutionEnd(this)\n return val\n }\n}\n\ninterface PrismScope {\n effect(key: string, cb: () => () => void, deps?: unknown[]): void\n memo(\n key: string,\n fn: () => T,\n deps: undefined | $IntentionalAny[] | ReadonlyArray<$IntentionalAny>,\n ): T\n state(key: string, initialValue: T): [T, (val: T) => void]\n ref(key: string, initialValue: T): IRef\n sub(key: string): PrismScope\n source(subscribe: (fn: (val: V) => void) => VoidFn, getValue: () => V): V\n}\n\nclass HotScope implements PrismScope {\n constructor(private readonly _hotHandle: HotHandle) {}\n\n protected readonly _refs: Map> = new Map()\n ref(key: string, initialValue: T): IRef {\n let ref = this._refs.get(key)\n if (ref !== undefined) {\n return ref as $IntentionalAny as IRef\n } else {\n const ref = {\n current: initialValue,\n }\n this._refs.set(key, ref)\n return ref\n }\n }\n isPrismScope = true\n\n // NOTE probably not a great idea to eager-allocate all of these objects/maps for every scope,\n // especially because most wouldn't get used in the majority of cases. However, back when these\n // were stored on weakmaps, they were uncomfortable to inspect in the debugger.\n readonly subs: Record = {}\n readonly effects: Map = new Map()\n\n effect(key: string, cb: () => () => void, deps?: unknown[]): void {\n let effect = this.effects.get(key)\n if (effect === undefined) {\n effect = {\n cleanup: voidFn,\n deps: undefined,\n }\n this.effects.set(key, effect)\n }\n\n if (depsHaveChanged(effect.deps, deps)) {\n effect.cleanup()\n\n startIgnoringDependencies()\n effect.cleanup = safelyRun(cb, voidFn).value\n stopIgnoringDependencies()\n effect.deps = deps\n }\n /**\n * TODO: we should cleanup dangling effects too.\n * Example:\n * ```ts\n * let i = 0\n * prism(() => {\n * if (i === 0) prism.effect(\"this effect will only run once\", () => {}, [])\n * i++\n * })\n * ```\n */\n }\n\n readonly memos: Map = new Map()\n\n memo(\n key: string,\n fn: () => T,\n deps: undefined | $IntentionalAny[] | ReadonlyArray<$IntentionalAny>,\n ): T {\n let memo = this.memos.get(key)\n if (memo === undefined) {\n memo = {\n cachedValue: null,\n // undefined will always indicate \"deps have changed\", so we set its initial value as such\n deps: undefined,\n }\n this.memos.set(key, memo)\n }\n\n if (depsHaveChanged(memo.deps, deps)) {\n startIgnoringDependencies()\n\n memo.cachedValue = safelyRun(fn, undefined).value\n stopIgnoringDependencies()\n memo.deps = deps\n }\n\n return memo.cachedValue as $IntentionalAny as T\n }\n\n state(key: string, initialValue: T): [T, (val: T) => void] {\n const {value, setValue} = this.memo(\n 'state/' + key,\n () => {\n const value = {current: initialValue}\n const setValue = (newValue: T) => {\n value.current = newValue\n this._hotHandle.forceStale()\n }\n return {value, setValue}\n },\n [],\n )\n\n return [value.current, setValue]\n }\n\n sub(key: string): HotScope {\n if (!this.subs[key]) {\n this.subs[key] = new HotScope(this._hotHandle)\n }\n return this.subs[key]\n }\n\n cleanupEffects() {\n for (const effect of this.effects.values()) {\n safelyRun(effect.cleanup, undefined)\n }\n this.effects.clear()\n }\n\n source(subscribe: (fn: (val: V) => void) => VoidFn, getValue: () => V): V {\n const sourceKey = '$$source/blah'\n this.effect(\n sourceKey,\n () => {\n const unsub = subscribe(() => {\n this._hotHandle.forceStale()\n })\n return unsub\n },\n [subscribe],\n )\n return getValue()\n }\n}\n\nfunction cleanupScopeStack(scope: HotScope) {\n for (const sub of Object.values(scope.subs)) {\n cleanupScopeStack(sub)\n }\n scope.cleanupEffects()\n}\n\nfunction safelyRun(\n fn: () => T,\n returnValueInCaseOfError: U,\n): {ok: true; value: T} | {ok: false; value: U} {\n try {\n return {value: fn(), ok: true}\n } catch (error) {\n // Naming this function can allow the error reporter additional context to the user on where this error came from\n setTimeout(function PrismReportThrow() {\n // ensure that the error gets reported, but does not crash the current execution scope\n throw error\n })\n return {value: returnValueInCaseOfError, ok: false}\n }\n}\n\nconst hookScopeStack = new Stack()\n\ntype IRef = {\n current: T\n}\n\ntype IEffect = {\n deps: undefined | unknown[]\n cleanup: VoidFn\n}\n\ntype IMemo = {\n deps: undefined | unknown[] | ReadonlyArray\n cachedValue: unknown\n}\n\n/**\n * Just like React's `useRef()`, `prism.ref()` allows us to create a prism that holds a reference to some value.\n * The only difference is that `prism.ref()` requires a key to be passed into it, whlie `useRef()` doesn't.\n * This means that we can call `prism.ref()` in any order, and we can call it multiple times with the same key.\n * @param key - The key for the ref. Should be unique inside of the prism.\n * @param initialValue - The initial value for the ref.\n * @returns `{current: V}` - The ref object.\n *\n * Note that the ref object will always return its initial value if the prism is cold. It'll only record\n * its current value if the prism is hot (and will forget again if the prism goes cold again).\n *\n * @example\n * ```ts\n * const pr = prism(() => {\n * const ref1 = prism.ref(\"ref1\", 0)\n * console.log(ref1.current) // will print 0, and if the prism is hot, it'll print the current value\n * ref1.current++ // changing the current value of the ref\n * })\n * ```\n */\nfunction ref(key: string, initialValue: T): IRef {\n const scope = hookScopeStack.peek()\n if (!scope) {\n throw new Error(`prism.ref() is called outside of a prism() call.`)\n }\n\n return scope.ref(key, initialValue)\n}\n\n/**\n * An effect hook, similar to React's `useEffect()`, but is not sensitive to call order by using `key`.\n *\n * @param key - the key for the effect. Should be uniqe inside of the prism.\n * @param cb - the callback function. Requires returning a cleanup function.\n * @param deps - the dependency array\n */\nfunction effect(key: string, cb: () => () => void, deps?: unknown[]): void {\n const scope = hookScopeStack.peek()\n if (!scope) {\n throw new Error(`prism.effect() is called outside of a prism() call.`)\n }\n\n return scope.effect(key, cb, deps)\n}\n\nfunction depsHaveChanged(\n oldDeps: undefined | unknown[] | ReadonlyArray,\n newDeps: undefined | unknown[] | ReadonlyArray,\n): boolean {\n if (oldDeps === undefined || newDeps === undefined) {\n return true\n }\n\n const len = oldDeps.length\n if (len !== newDeps.length) return true\n\n for (let i = 0; i < len; i++) {\n if (oldDeps[i] !== newDeps[i]) return true\n }\n\n return false\n}\n\n/**\n * `prism.memo()` works just like React's `useMemo()` hook. It's a way to cache the result of a function call.\n * The only difference is that `prism.memo()` requires a key to be passed into it, whlie `useMemo()` doesn't.\n * This means that we can call `prism.memo()` in any order, and we can call it multiple times with the same key.\n *\n * @param key - The key for the memo. Should be unique inside of the prism\n * @param fn - The function to memoize\n * @param deps - The dependency array. Provide `[]` if you want to the value to be memoized only once and never re-calculated.\n * @returns The result of the function call\n *\n * @example\n * ```ts\n * const pr = prism(() => {\n * const memoizedReturnValueOfExpensiveFn = prism.memo(\"memo1\", expensiveFn, [])\n * })\n * ```\n */\nfunction memo(\n key: string,\n fn: () => T,\n deps: undefined | $IntentionalAny[] | ReadonlyArray<$IntentionalAny>,\n): T {\n const scope = hookScopeStack.peek()\n if (!scope) {\n throw new Error(`prism.memo() is called outside of a prism() call.`)\n }\n\n return scope.memo(key, fn, deps)\n}\n\n/**\n * A state hook, similar to react's `useState()`.\n *\n * @param key - the key for the state\n * @param initialValue - the initial value\n * @returns [currentState, setState]\n *\n * @example\n * ```ts\n * import {prism} from 'dataverse'\n *\n * // This prism holds the current mouse position and updates when the mouse moves\n * const mousePositionD = prism(() => {\n * const [pos, setPos] = prism.state<[x: number, y: number]>('pos', [0, 0])\n *\n * prism.effect(\n * 'setupListeners',\n * () => {\n * const handleMouseMove = (e: MouseEvent) => {\n * setPos([e.screenX, e.screenY])\n * }\n * document.addEventListener('mousemove', handleMouseMove)\n *\n * return () => {\n * document.removeEventListener('mousemove', handleMouseMove)\n * }\n * },\n * [],\n * )\n *\n * return pos\n * })\n * ```\n */\nfunction state(key: string, initialValue: T): [T, (val: T) => void] {\n const scope = hookScopeStack.peek()\n if (!scope) {\n throw new Error(`prism.state() is called outside of a prism() call.`)\n }\n\n return scope.state(key, initialValue)\n}\n\n/**\n * This is useful to make sure your code is running inside a `prism()` call.\n *\n * @example\n * ```ts\n * import {prism} from '@theatre/dataverse'\n *\n * function onlyUsefulInAPrism() {\n * prism.ensurePrism()\n * }\n *\n * prism(() => {\n * onlyUsefulInAPrism() // will run fine\n * })\n *\n * setTimeout(() => {\n * onlyUsefulInAPrism() // throws an error\n * console.log('This will never get logged')\n * }, 0)\n * ```\n */\nfunction ensurePrism(): void {\n const scope = hookScopeStack.peek()\n if (!scope) {\n throw new Error(`The parent function is called outside of a prism() call.`)\n }\n}\n\nfunction scope(key: string, fn: () => T): T {\n const parentScope = hookScopeStack.peek()\n if (!parentScope) {\n throw new Error(`prism.scope() is called outside of a prism() call.`)\n }\n const subScope = parentScope.sub(key)\n hookScopeStack.push(subScope)\n const ret = safelyRun(fn, undefined).value\n hookScopeStack.pop()\n return ret as $IntentionalAny as T\n}\n\n/**\n * Just an alias for `prism.memo(key, () => prism(fn), deps).getValue()`. It creates a new prism, memoizes it, and returns the value.\n * `prism.sub()` is useful when you want to divide your prism into smaller prisms, each of which\n * would _only_ recalculate when _certain_ dependencies change. In other words, it's an optimization tool.\n *\n * @param key - The key for the memo. Should be unique inside of the prism\n * @param fn - The function to run inside the prism\n * @param deps - The dependency array. Provide `[]` if you want to the value to be memoized only once and never re-calculated.\n * @returns The value of the inner prism\n */\nfunction sub(\n key: string,\n fn: () => T,\n deps: undefined | $IntentionalAny[],\n): T {\n return memo(key, () => prism(fn), deps).getValue()\n}\n\n/**\n * @returns true if the current function is running inside a `prism()` call.\n */\nfunction inPrism(): boolean {\n return !!hookScopeStack.peek()\n}\n\nconst possiblePrismToValue =

| unknown>(\n input: P,\n): P extends Prism ? T : P => {\n if (isPrism(input)) {\n return input.getValue() as $IntentionalAny\n } else {\n return input as $IntentionalAny\n }\n}\n\n/**\n * `prism.source()` allow a prism to react to changes in some external source (other than other prisms).\n * For example, `Atom.pointerToPrism()` uses `prism.source()` to create a prism that reacts to changes in the atom's value.\n \n * @param subscribe - The prism will call this function as soon as the prism goes hot. This function should return an unsubscribe function function which the prism will call when it goes cold.\n * @param getValue - A function that returns the current value of the external source.\n * @returns The current value of the source\n * \n * Example:\n * ```ts\n * function prismFromInputElement(input: HTMLInputElement): Prism {\n * function listen(cb: (value: string) => void) {\n * const listener = () => {\n * cb(input.value)\n * }\n * input.addEventListener('input', listener)\n * return () => {\n * input.removeEventListener('input', listener)\n * }\n * }\n * \n * function get() {\n * return input.value\n * }\n * return prism(() => prism.source(listen, get))\n * }\n * ```\n */\nfunction source(\n subscribe: (fn: (val: V) => void) => VoidFn,\n getValue: () => V,\n): V {\n const scope = hookScopeStack.peek()\n if (!scope) {\n throw new Error(`prism.source() is called outside of a prism() call.`)\n }\n\n return scope.source(subscribe, getValue)\n}\n\ntype IPrismFn = {\n (fn: () => T): Prism\n ref: typeof ref\n effect: typeof effect\n memo: typeof memo\n ensurePrism: typeof ensurePrism\n state: typeof state\n scope: typeof scope\n sub: typeof sub\n inPrism: typeof inPrism\n source: typeof source\n}\n\n/**\n * Creates a prism from the passed function that adds all prisms referenced\n * in it as dependencies, and reruns the function when these change.\n *\n * @param fn - The function to rerun when the prisms referenced in it change.\n */\nconst prism: IPrismFn = (fn) => {\n return new PrismInstance(fn)\n}\n\nclass ColdScope implements PrismScope {\n effect(key: string, cb: () => () => void, deps?: unknown[]): void {\n console.warn(`prism.effect() does not run in cold prisms`)\n }\n memo(\n key: string,\n fn: () => T,\n deps: any[] | readonly any[] | undefined,\n ): T {\n return fn()\n }\n state(key: string, initialValue: T): [T, (val: T) => void] {\n return [initialValue, () => {}]\n }\n ref(key: string, initialValue: T): IRef {\n return {current: initialValue}\n }\n sub(key: string): ColdScope {\n return new ColdScope()\n }\n source(subscribe: (fn: (val: V) => void) => VoidFn, getValue: () => V): V {\n return getValue()\n }\n}\n\nfunction calculateColdPrism(fn: () => V): V {\n const scope = new ColdScope()\n hookScopeStack.push(scope)\n let value: V\n try {\n value = fn()\n } catch (error) {\n console.error(error)\n } finally {\n const topOfTheStack = hookScopeStack.pop()\n if (topOfTheStack !== scope) {\n console.warn(\n // @todo guide the user to report the bug in an issue\n `The Prism hook stack has slipped. This is a bug.`,\n )\n }\n }\n return value!\n}\n\nprism.ref = ref\nprism.effect = effect\nprism.memo = memo\nprism.ensurePrism = ensurePrism\nprism.state = state\nprism.scope = scope\nprism.sub = sub\nprism.inPrism = inPrism\nprism.source = source\n\nexport default prism\n", "import get from 'lodash-es/get'\nimport isPlainObject from 'lodash-es/isPlainObject'\nimport last from 'lodash-es/last'\nimport type {Prism} from './prism/Interface'\nimport type {Pointer} from './pointer'\nimport {getPointerParts} from './pointer'\nimport {isPointer} from './pointer'\nimport pointer from './pointer'\nimport type {$FixMe, $IntentionalAny} from './types'\nimport updateDeep from './utils/updateDeep'\nimport prism from './prism/prism'\nimport type {PointerToPrismProvider} from './pointerToPrism'\n\ntype Listener = (newVal: unknown) => void\n\nenum ValueTypes {\n Dict,\n Array,\n Other,\n}\n\nconst getTypeOfValue = (v: unknown): ValueTypes => {\n if (Array.isArray(v)) return ValueTypes.Array\n if (isPlainObject(v)) return ValueTypes.Dict\n return ValueTypes.Other\n}\n\nconst getKeyOfValue = (\n v: unknown,\n key: string | number,\n vType: ValueTypes = getTypeOfValue(v),\n): unknown => {\n if (vType === ValueTypes.Dict && typeof key === 'string') {\n return (v as $IntentionalAny)[key]\n } else if (vType === ValueTypes.Array && isValidArrayIndex(key)) {\n return (v as $IntentionalAny)[key]\n } else {\n return undefined\n }\n}\n\nconst isValidArrayIndex = (key: string | number): boolean => {\n const inNumber = typeof key === 'number' ? key : parseInt(key, 10)\n return (\n !isNaN(inNumber) &&\n inNumber >= 0 &&\n inNumber < Infinity &&\n (inNumber | 0) === inNumber\n )\n}\n\nclass Scope {\n children: Map = new Map()\n identityChangeListeners: Set = new Set()\n constructor(\n readonly _parent: undefined | Scope,\n readonly _path: (string | number)[],\n ) {}\n\n addIdentityChangeListener(cb: Listener) {\n this.identityChangeListeners.add(cb)\n }\n\n removeIdentityChangeListener(cb: Listener) {\n this.identityChangeListeners.delete(cb)\n this._checkForGC()\n }\n\n removeChild(key: string | number) {\n this.children.delete(key)\n this._checkForGC()\n }\n\n getChild(key: string | number) {\n return this.children.get(key)\n }\n\n getOrCreateChild(key: string | number) {\n let child = this.children.get(key)\n if (!child) {\n child = child = new Scope(this, this._path.concat([key]))\n this.children.set(key, child)\n }\n return child\n }\n\n _checkForGC() {\n if (this.identityChangeListeners.size > 0) return\n if (this.children.size > 0) return\n\n if (this._parent) {\n this._parent.removeChild(last(this._path) as string | number)\n }\n }\n}\n\n/**\n * Wraps an object whose (sub)properties can be individually tracked.\n */\nexport default class Atom implements PointerToPrismProvider {\n private _currentState: State\n /**\n * @internal\n */\n readonly $$isPointerToPrismProvider = true\n private readonly _rootScope: Scope\n /**\n * Convenience property that gives you a pointer to the root of the atom.\n *\n * @remarks\n * Equivalent to `pointer({ root: thisAtom, path: [] })`.\n */\n readonly pointer: Pointer = pointer({root: this as $FixMe, path: []})\n\n readonly prism: Prism = this.pointerToPrism(\n this.pointer,\n ) as $IntentionalAny\n\n constructor(initialState: State) {\n this._currentState = initialState\n this._rootScope = new Scope(undefined, [])\n }\n\n /**\n * Sets the state of the atom.\n *\n * @param newState - The new state of the atom.\n */\n set(newState: State) {\n const oldState = this._currentState\n this._currentState = newState\n\n this._checkUpdates(this._rootScope, oldState, newState)\n }\n\n get(): State {\n return this._currentState\n }\n\n /**\n * Returns the value at the given pointer\n *\n * @param pointerOrFn - A pointer to the desired path. Could also be a function returning a pointer\n *\n * Example\n * ```ts\n * const atom = atom({ a: { b: 1 } })\n * atom.getByPointer(atom.pointer.a.b) // 1\n * atom.getByPointer((p) => p.a.b) // 1\n * ```\n */\n getByPointer(\n pointerOrFn: Pointer | ((p: Pointer) => Pointer),\n ): S {\n const pointer = isPointer(pointerOrFn)\n ? pointerOrFn\n : (pointerOrFn as $IntentionalAny)(this.pointer)\n\n const path = getPointerParts(pointer).path\n return this._getIn(path) as S\n }\n\n /**\n * Gets the state of the atom at `path`.\n */\n private _getIn(path: (string | number)[]): unknown {\n return path.length === 0 ? this.get() : get(this.get(), path)\n }\n\n reduce(fn: (state: State) => State) {\n this.set(fn(this.get()))\n }\n\n /**\n * Reduces the value at the given pointer\n *\n * @param pointerOrFn - A pointer to the desired path. Could also be a function returning a pointer\n *\n * Example\n * ```ts\n * const atom = atom({ a: { b: 1 } })\n * atom.reduceByPointer(atom.pointer.a.b, (b) => b + 1) // atom.get().a.b === 2\n * atom.reduceByPointer((p) => p.a.b, (b) => b + 1) // atom.get().a.b === 2\n * ```\n */\n reduceByPointer(\n pointerOrFn: Pointer | ((p: Pointer) => Pointer),\n reducer: (s: S) => S,\n ) {\n const pointer = isPointer(pointerOrFn)\n ? pointerOrFn\n : (pointerOrFn as $IntentionalAny)(this.pointer)\n\n const path = getPointerParts(pointer).path\n const newState = updateDeep(this.get(), path, reducer)\n this.set(newState)\n }\n\n /**\n * Sets the value at the given pointer\n *\n * @param pointerOrFn - A pointer to the desired path. Could also be a function returning a pointer\n *\n * Example\n * ```ts\n * const atom = atom({ a: { b: 1 } })\n * atom.setByPointer(atom.pointer.a.b, 2) // atom.get().a.b === 2\n * atom.setByPointer((p) => p.a.b, 2) // atom.get().a.b === 2\n * ```\n */\n setByPointer(\n pointerOrFn: Pointer | ((p: Pointer) => Pointer),\n val: S,\n ) {\n this.reduceByPointer(pointerOrFn, () => val)\n }\n\n private _checkUpdates(scope: Scope, oldState: unknown, newState: unknown) {\n if (oldState === newState) return\n for (const cb of scope.identityChangeListeners) {\n cb(newState)\n }\n\n if (scope.children.size === 0) return\n\n // @todo we can probably skip checking value types\n const oldValueType = getTypeOfValue(oldState)\n const newValueType = getTypeOfValue(newState)\n\n if (oldValueType === ValueTypes.Other && oldValueType === newValueType)\n return\n\n for (const [childKey, childScope] of scope.children) {\n const oldChildVal = getKeyOfValue(oldState, childKey, oldValueType)\n const newChildVal = getKeyOfValue(newState, childKey, newValueType)\n this._checkUpdates(childScope, oldChildVal, newChildVal)\n }\n }\n\n private _getOrCreateScopeForPath(path: (string | number)[]): Scope {\n let curScope = this._rootScope\n for (const pathEl of path) {\n curScope = curScope.getOrCreateChild(pathEl)\n }\n return curScope\n }\n\n private _onPointerValueChange =

(\n pointer: Pointer

,\n cb: (v: P) => void,\n ): (() => void) => {\n const {path} = getPointerParts(pointer)\n const scope = this._getOrCreateScopeForPath(path)\n scope.identityChangeListeners.add(cb as $IntentionalAny)\n const unsubscribe = () => {\n scope.identityChangeListeners.delete(cb as $IntentionalAny)\n }\n return unsubscribe\n }\n\n /**\n * Returns a new prism of the value at the provided path.\n *\n * @param pointer - The path to create the prism at.\n *\n * ```ts\n * const pr = atom({ a: { b: 1 } }).pointerToPrism(atom.pointer.a.b)\n * pr.getValue() // 1\n * ```\n */\n pointerToPrism

(pointer: Pointer

): Prism

{\n const {path} = getPointerParts(pointer)\n const subscribe = (listener: (val: unknown) => void) =>\n this._onPointerValueChange(pointer, listener)\n\n const getValue = () => this._getIn(path)\n\n return prism(() => {\n return prism.source(subscribe, getValue)\n }) as Prism

\n }\n}\n", "import type {Prism} from './prism/Interface'\nimport type {Pointer, PointerType} from './pointer'\nimport {getPointerMeta} from './pointer'\nimport type {$IntentionalAny} from './types'\n\nconst identifyPrismWeakMap = new WeakMap<{}, Prism>()\n\n/**\n * Interface for objects that can provide a prism at a certain path.\n */\nexport interface PointerToPrismProvider {\n /**\n * @internal\n * Future: We could consider using a `Symbol.for(\"dataverse/PointerToPrismProvider\")` as a key here, similar to\n * how {@link Iterable} works for `of`.\n */\n readonly $$isPointerToPrismProvider: true\n /**\n * Returns a prism of the value at the provided pointer.\n */\n pointerToPrism

(pointer: Pointer

): Prism

\n}\n\nexport function isPointerToPrismProvider(\n val: unknown,\n): val is PointerToPrismProvider {\n return (\n typeof val === 'object' &&\n val !== null &&\n (val as $IntentionalAny)['$$isPointerToPrismProvider'] === true\n )\n}\n\n/**\n * Returns a prism of the value at the provided pointer. Prisms are\n * cached per pointer.\n *\n * @param pointer - The pointer to return the prism at.\n */\n\nexport const pointerToPrism =

>(\n pointer: P,\n): Prism

? T : void> => {\n const meta = getPointerMeta(pointer)\n\n let prismInstance = identifyPrismWeakMap.get(meta)\n if (!prismInstance) {\n const root = meta.root\n if (!isPointerToPrismProvider(root)) {\n throw new Error(\n `Cannot run pointerToPrism() on a pointer whose root is not an PointerToPrismProvider`,\n )\n }\n prismInstance = root.pointerToPrism(pointer as $IntentionalAny)\n identifyPrismWeakMap.set(meta, prismInstance)\n }\n return prismInstance as $IntentionalAny\n}\n", "import type {Prism} from './prism/Interface'\nimport {isPrism} from './prism/Interface'\nimport type {PointerType} from './pointer'\nimport {isPointer} from './pointer'\nimport type {$IntentionalAny} from './types'\nimport {pointerToPrism} from './pointerToPrism'\n\n/**\n * Convenience function that returns a plain value from its argument, whether it\n * is a pointer, a prism or a plain value itself.\n *\n * @remarks\n * For pointers, the value is returned by first creating a prism, so it is\n * reactive e.g. when used in a `prism`.\n *\n * @param input - The argument to return a value from.\n */\n\nexport const val = <\n P extends\n | PointerType<$IntentionalAny>\n | Prism<$IntentionalAny>\n | undefined\n | null,\n>(\n input: P,\n): P extends PointerType\n ? T\n : P extends Prism\n ? T\n : P extends undefined | null\n ? P\n : unknown => {\n if (isPointer(input)) {\n return pointerToPrism(input).getValue() as $IntentionalAny\n } else if (isPrism(input)) {\n return input.getValue() as $IntentionalAny\n } else {\n return input as $IntentionalAny\n }\n}\n", "type ICallback = (t: number) => void\n\n/**\n * The number of ticks that can pass without any scheduled callbacks before the Ticker goes dormant. This is to prevent\n * the Ticker from staying active forever, even if there are no scheduled callbacks.\n *\n * Perhaps counting ticks vs. time is not the best way to do this. But it's a start.\n */\nexport const EMPTY_TICKS_BEFORE_GOING_DORMANT = 60 /*fps*/ * 3 /*seconds*/ // on a 60fps screen, 3 seconds should pass before the ticker goes dormant\n\n/**\n * The Ticker class helps schedule callbacks. Scheduled callbacks are executed per tick. Ticks can be triggered by an\n * external scheduling strategy, e.g. a raf.\n */\nexport default class Ticker {\n private _scheduledForThisOrNextTick: Set\n private _scheduledForNextTick: Set\n private _timeAtCurrentTick: number\n private _ticking: boolean = false\n\n /**\n * Whether the Ticker is dormant\n */\n private _dormant: boolean = true\n\n private _numberOfDormantTicks = 0\n\n /**\n * Whether the Ticker is dormant\n */\n get dormant(): boolean {\n return this._dormant\n }\n /**\n * Counts up for every tick executed.\n * Internally, this is used to measure ticks per second.\n *\n * This is \"public\" to TypeScript, because it's a tool for performance measurements.\n * Consider this as experimental, and do not rely on it always being here in future releases.\n */\n public __ticks = 0\n\n constructor(\n private _conf?: {\n /**\n * This is called when the Ticker goes dormant.\n */\n onDormant?: () => void\n /**\n * This is called when the Ticker goes active.\n */\n onActive?: () => void\n },\n ) {\n this._scheduledForThisOrNextTick = new Set()\n this._scheduledForNextTick = new Set()\n this._timeAtCurrentTick = 0\n }\n\n /**\n * Registers for fn to be called either on this tick or the next tick.\n *\n * If `onThisOrNextTick()` is called while `Ticker.tick()` is running, the\n * side effect _will_ be called within the running tick. If you don't want this\n * behavior, you can use `onNextTick()`.\n *\n * Note that `fn` will be added to a `Set()`. Which means, if you call `onThisOrNextTick(fn)`\n * with the same fn twice in a single tick, it'll only run once.\n *\n * @param fn - The function to be registered.\n *\n * @see offThisOrNextTick\n */\n onThisOrNextTick(fn: ICallback) {\n this._scheduledForThisOrNextTick.add(fn)\n if (this._dormant) {\n this._goActive()\n }\n }\n\n /**\n * Registers a side effect to be called on the next tick.\n *\n * @param fn - The function to be registered.\n *\n * @see onThisOrNextTick\n * @see offNextTick\n */\n onNextTick(fn: ICallback) {\n this._scheduledForNextTick.add(fn)\n if (this._dormant) {\n this._goActive()\n }\n }\n\n /**\n * De-registers a fn to be called either on this tick or the next tick.\n *\n * @param fn - The function to be de-registered.\n *\n * @see onThisOrNextTick\n */\n offThisOrNextTick(fn: ICallback) {\n this._scheduledForThisOrNextTick.delete(fn)\n }\n\n /**\n * De-registers a fn to be called on the next tick.\n *\n * @param fn - The function to be de-registered.\n *\n * @see onNextTick\n */\n offNextTick(fn: ICallback) {\n this._scheduledForNextTick.delete(fn)\n }\n\n /**\n * The time at the start of the current tick if there is a tick in progress, otherwise defaults to\n * `performance.now()`.\n */\n get time() {\n if (this._ticking) {\n return this._timeAtCurrentTick\n } else return performance.now()\n }\n\n private _goActive() {\n if (!this._dormant) return\n this._dormant = false\n this._conf?.onActive?.()\n }\n\n private _goDormant() {\n if (this._dormant) return\n this._dormant = true\n this._numberOfDormantTicks = 0\n this._conf?.onDormant?.()\n }\n\n /**\n * Triggers a tick which starts executing the callbacks scheduled for this tick.\n *\n * @param t - The time at the tick.\n *\n * @see onThisOrNextTick\n * @see onNextTick\n */\n tick(t: number = performance.now()) {\n if (process.env.NODE_ENV === 'development') {\n if (!(this instanceof Ticker)) {\n throw new Error(\n 'ticker.tick must be called while bound to the ticker. As in, \"ticker.tick(time)\" or \"requestAnimationFrame((t) => ticker.tick(t))\" for performance.',\n )\n }\n }\n\n this.__ticks++\n\n if (!this._dormant) {\n if (\n this._scheduledForNextTick.size === 0 &&\n this._scheduledForThisOrNextTick.size === 0\n ) {\n this._numberOfDormantTicks++\n if (this._numberOfDormantTicks >= EMPTY_TICKS_BEFORE_GOING_DORMANT) {\n this._goDormant()\n return\n }\n }\n }\n\n this._ticking = true\n this._timeAtCurrentTick = t\n for (const v of this._scheduledForNextTick) {\n this._scheduledForThisOrNextTick.add(v)\n }\n\n this._scheduledForNextTick.clear()\n this._tick(0)\n this._ticking = false\n }\n\n private _tick(iterationNumber: number): void {\n const time = this.time\n\n if (iterationNumber > 10) {\n console.warn('_tick() recursing for 10 times')\n }\n\n if (iterationNumber > 100) {\n throw new Error(`Maximum recursion limit for _tick()`)\n }\n\n const oldSet = this._scheduledForThisOrNextTick\n this._scheduledForThisOrNextTick = new Set()\n for (const fn of oldSet) {\n fn(time)\n }\n\n if (this._scheduledForThisOrNextTick.size > 0) {\n return this._tick(iterationNumber + 1)\n }\n }\n}\n", "import Atom from './Atom'\nimport {val} from './val'\nimport type {Pointer} from './pointer'\nimport {getPointerMeta} from './pointer'\nimport pointer from './pointer'\nimport type {$FixMe, $IntentionalAny} from './types'\nimport prism from './prism/prism'\nimport type {Prism} from './prism/Interface'\nimport type {PointerToPrismProvider} from './pointerToPrism'\n\n/**\n * Allows creating pointer-prisms where the pointer can be switched out.\n *\n * @remarks\n * This allows reacting not just to value changes at a certain pointer, but changes\n * to the proxied pointer too.\n */\nexport default class PointerProxy\n implements PointerToPrismProvider\n{\n /**\n * @internal\n */\n readonly $$isPointerToPrismProvider = true\n private readonly _currentPointerBox: Atom>\n /**\n * Convenience pointer pointing to the root of this PointerProxy.\n *\n * @remarks\n * Allows convenient use of {@link pointerToPrism} and {@link val}.\n */\n readonly pointer: Pointer\n\n constructor(currentPointer: Pointer) {\n this._currentPointerBox = new Atom(currentPointer)\n this.pointer = pointer({root: this as $FixMe, path: []})\n }\n\n /**\n * Sets the underlying pointer.\n * @param p - The pointer to be proxied.\n */\n setPointer(p: Pointer) {\n this._currentPointerBox.set(p)\n }\n\n /**\n * Returns a prism of the value at the provided sub-path of the proxied pointer.\n *\n * @param path - The path to create the prism at.\n */\n pointerToPrism

(pointer: Pointer

): Prism

{\n const {path} = getPointerMeta(pointer)\n return prism(() => {\n const currentPointer = this._currentPointerBox.prism.getValue()\n const subPointer = path.reduce(\n (pointerSoFar, pathItem) => (pointerSoFar as $IntentionalAny)[pathItem],\n currentPointer,\n )\n return val(subPointer) as P\n })\n }\n}\n", "import {Atom} from '@theatre/dataverse'\nimport type {ProjectId} from '@theatre/shared/utils/ids'\nimport type Project from './Project'\n\ninterface State {\n projects: Record\n}\n\nclass ProjectsSingleton {\n readonly atom = new Atom({projects: {}} as State)\n constructor() {}\n\n /**\n * We're trusting here that each project id is unique\n */\n add(id: ProjectId, project: Project) {\n this.atom.setByPointer((p) => p.projects[id], project)\n }\n\n get(id: ProjectId): Project | undefined {\n return this.atom.get().projects[id]\n }\n\n has(id: ProjectId) {\n return !!this.get(id)\n }\n}\n\nconst singleton = new ProjectsSingleton()\n\nexport default singleton\n", "import type {IProject} from '@theatre/core/projects/TheatreProject'\nimport type Project from '@theatre/core/projects/Project'\nimport type Sequence from '@theatre/core/sequences/Sequence'\nimport type {ISequence} from '@theatre/core/sequences/TheatreSequence'\nimport type SheetObject from '@theatre/core/sheetObjects/SheetObject'\nimport type {ISheetObject} from '@theatre/core/sheetObjects/TheatreSheetObject'\nimport type Sheet from '@theatre/core/sheets/Sheet'\nimport type {ISheet} from '@theatre/core/sheets/TheatreSheet'\nimport type {UnknownShorthandCompoundProps} from './propTypes/internals'\nimport type {$IntentionalAny} from '@theatre/shared/utils/types'\nimport type {IRafDriver, RafDriverPrivateAPI} from './rafDrivers'\n\nconst publicAPIToPrivateAPIMap = new WeakMap()\n\n/**\n * Given a public API object, returns the corresponding private API object.\n */\nexport function privateAPI

(\n pub: P,\n): P extends IProject\n ? Project\n : P extends ISheet\n ? Sheet\n : P extends ISheetObject<$IntentionalAny>\n ? SheetObject\n : P extends ISequence\n ? Sequence\n : P extends IRafDriver\n ? RafDriverPrivateAPI\n : never {\n return publicAPIToPrivateAPIMap.get(pub)\n}\n\n/**\n * Notes the relationship between a public API object and its corresponding private API object,\n * so that `privateAPI` can find it.\n */\nexport function setPrivateAPI(pub: IProject, priv: Project): void\nexport function setPrivateAPI(pub: ISheet, priv: Sheet): void\nexport function setPrivateAPI(pub: ISequence, priv: Sequence): void\nexport function setPrivateAPI(pub: IRafDriver, priv: RafDriverPrivateAPI): void\nexport function setPrivateAPI(\n pub: ISheetObject,\n priv: SheetObject,\n): void\nexport function setPrivateAPI(pub: {}, priv: {}): void {\n publicAPIToPrivateAPIMap.set(pub, priv)\n}\n", "/**\n * This is just an empty object used in place of `{}` when you want to:\n * 1. Not create many new objects (less GC pressure)\n * 2. Have the empty object be a singleton (so that `===` works), so it can be fed to memoized functions.\n */\nexport const emptyObject = {}\n\n/**\n * The array equivalent of {@link emptyObject}.\n */\nexport const emptyArray: ReadonlyArray = []\n", "import lodashGet from 'lodash-es/get'\nimport type {PathToProp} from './addresses'\nimport type {SerializableValue} from './types'\n\n/**\n * Returns the value at `path` of `v`.\n *\n * Example:\n * ```ts\n * getDeep({a: {b: 1}}, ['a', 'b']) // 1\n * getDeep({a: {b: 1}}, ['a', 'c']) // undefined\n * getDeep({a: {b: 1}}, []) // {a: {b: 1}}\n * getDeep('hello', []) // 'hello''\n * getDeep('hello', ['a']) // undefined\n * ```\n */\nexport default function getDeep(\n v: SerializableValue,\n path: PathToProp,\n): unknown {\n if (path.length === 0) return v\n return lodashGet(v, path)\n}\n", "import type {$IntentionalAny} from './types'\n\n/**\n * A basic cache\n */\nexport default class SimpleCache {\n /**\n * NOTE this could also be a Map.\n */\n protected _values: Record = {}\n constructor() {}\n\n /**\n * get the cache item at `key` or produce it using `producer` and cache _that_.\n *\n * Note that this won't work if you change the producer, like `get(key, producer1); get(key, producer2)`.\n */\n get(key: string, producer: () => T): T {\n if (this.has(key)) {\n return this._values[key] as $IntentionalAny\n } else {\n const cachedValue = producer()\n this._values[key] = cachedValue\n return cachedValue\n }\n }\n\n /**\n * Returns true if the cache has an item at `key`.\n */\n has(key: string): boolean {\n return this._values.hasOwnProperty(key)\n }\n}\n", "import getNative from './_getNative.js';\n\nvar defineProperty = (function() {\n try {\n var func = getNative(Object, 'defineProperty');\n func({}, '', {});\n return func;\n } catch (e) {}\n}());\n\nexport default defineProperty;\n", "import defineProperty from './_defineProperty.js';\n\n/**\n * The base implementation of `assignValue` and `assignMergeValue` without\n * value checks.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {string} key The key of the property to assign.\n * @param {*} value The value to assign.\n */\nfunction baseAssignValue(object, key, value) {\n if (key == '__proto__' && defineProperty) {\n defineProperty(object, key, {\n 'configurable': true,\n 'enumerable': true,\n 'value': value,\n 'writable': true\n });\n } else {\n object[key] = value;\n }\n}\n\nexport default baseAssignValue;\n", "import baseAssignValue from './_baseAssignValue.js';\nimport eq from './eq.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Assigns `value` to `key` of `object` if the existing value is not equivalent\n * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {string} key The key of the property to assign.\n * @param {*} value The value to assign.\n */\nfunction assignValue(object, key, value) {\n var objValue = object[key];\n if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) ||\n (value === undefined && !(key in object))) {\n baseAssignValue(object, key, value);\n }\n}\n\nexport default assignValue;\n", "/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/** Used to detect unsigned integer values. */\nvar reIsUint = /^(?:0|[1-9]\\d*)$/;\n\n/**\n * Checks if `value` is a valid array-like index.\n *\n * @private\n * @param {*} value The value to check.\n * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.\n * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.\n */\nfunction isIndex(value, length) {\n var type = typeof value;\n length = length == null ? MAX_SAFE_INTEGER : length;\n\n return !!length &&\n (type == 'number' ||\n (type != 'symbol' && reIsUint.test(value))) &&\n (value > -1 && value % 1 == 0 && value < length);\n}\n\nexport default isIndex;\n", "import assignValue from './_assignValue.js';\nimport castPath from './_castPath.js';\nimport isIndex from './_isIndex.js';\nimport isObject from './isObject.js';\nimport toKey from './_toKey.js';\n\n/**\n * The base implementation of `_.set`.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {Array|string} path The path of the property to set.\n * @param {*} value The value to set.\n * @param {Function} [customizer] The function to customize path creation.\n * @returns {Object} Returns `object`.\n */\nfunction baseSet(object, path, value, customizer) {\n if (!isObject(object)) {\n return object;\n }\n path = castPath(path, object);\n\n var index = -1,\n length = path.length,\n lastIndex = length - 1,\n nested = object;\n\n while (nested != null && ++index < length) {\n var key = toKey(path[index]),\n newValue = value;\n\n if (key === '__proto__' || key === 'constructor' || key === 'prototype') {\n return object;\n }\n\n if (index != lastIndex) {\n var objValue = nested[key];\n newValue = customizer ? customizer(objValue, key, nested) : undefined;\n if (newValue === undefined) {\n newValue = isObject(objValue)\n ? objValue\n : (isIndex(path[index + 1]) ? [] : {});\n }\n }\n assignValue(nested, key, newValue);\n nested = nested[key];\n }\n return object;\n}\n\nexport default baseSet;\n", "import baseSet from './_baseSet.js';\n\n/**\n * Sets the value at `path` of `object`. If a portion of `path` doesn't exist,\n * it's created. Arrays are created for missing index properties while objects\n * are created for all other missing properties. Use `_.setWith` to customize\n * `path` creation.\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 3.7.0\n * @category Object\n * @param {Object} object The object to modify.\n * @param {Array|string} path The path of the property to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns `object`.\n * @example\n *\n * var object = { 'a': [{ 'b': { 'c': 3 } }] };\n *\n * _.set(object, 'a[0].b.c', 4);\n * console.log(object.a[0].b.c);\n * // => 4\n *\n * _.set(object, ['x', '0', 'y', 'z'], 5);\n * console.log(object.x[0].y.z);\n * // => 5\n */\nfunction set(object, path, value) {\n return object == null ? object : baseSet(object, path, value);\n}\n\nexport default set;\n", "import type {SheetObjectPropTypeConfig} from '@theatre/core/sheets/TheatreSheet'\nimport type {\n $FixMe,\n SerializableMap,\n SerializableValue,\n} from '@theatre/shared/utils/types'\nimport type {\n PropTypeConfig,\n PropTypeConfig_Compound,\n PropTypeConfig_Enum,\n} from '@theatre/core/propTypes'\n\nconst cachedDefaults = new WeakMap()\n\n/**\n * Generates and caches a default value for the config of a SheetObject.\n */\nexport default function getPropDefaultsOfSheetObject(\n config: SheetObjectPropTypeConfig,\n): SerializableMap {\n return getDefaultsOfPropTypeConfig(config) as SerializableMap // sheet objects result in non-primitive objects\n}\n\nfunction getDefaultsOfPropTypeConfig(\n config: PropTypeConfig,\n): SerializableValue {\n if (cachedDefaults.has(config)) {\n return cachedDefaults.get(config)!\n }\n\n const generated =\n config.type === 'compound'\n ? generateDefaultsForCompound(config)\n : config.type === 'enum'\n ? generateDefaultsForEnum(config)\n : config.default\n\n cachedDefaults.set(config, generated)\n\n return generated\n}\n\nfunction generateDefaultsForEnum(config: PropTypeConfig_Enum) {\n const defaults: SerializableMap = {\n $case: config.defaultCase,\n }\n\n for (const [case_, caseConf] of Object.entries(config.cases)) {\n defaults[case_] = getDefaultsOfPropTypeConfig(caseConf)\n }\n\n return defaults\n}\n\nfunction generateDefaultsForCompound(config: PropTypeConfig_Compound<$FixMe>) {\n const defaults: SerializableMap = {}\n for (const [key, propConf] of Object.entries(config.props)) {\n defaults[key] = getDefaultsOfPropTypeConfig(propConf)\n }\n\n return defaults\n}\n", "import type {\n BasicKeyframedTrack,\n Keyframe,\n TrackData,\n} from '@theatre/core/projects/store/types/SheetState_Historic'\nimport type {Prism, Pointer} from '@theatre/dataverse'\nimport {prism, val} from '@theatre/dataverse'\nimport type {IUtilContext} from '@theatre/shared/logger'\nimport type {SerializableValue} from '@theatre/shared/utils/types'\nimport UnitBezier from 'timing-function/lib/UnitBezier'\n\n/** `left` and `right` are not necessarily the same type. */\nexport type InterpolationTriple = {\n /** `left` and `right` are not necessarily the same type. */\n left: SerializableValue\n /** `left` and `right` are not necessarily the same type. */\n right?: SerializableValue\n progression: number\n}\n\n// @remarks This new implementation supports sequencing non-numeric props, but it's also heavier\n// on the GC. This shouldn't be a problem for the vast majority of users, but it's also a\n// low-hanging fruit for perf optimization.\n// It can be improved by:\n// 1. Not creating a new InterpolationTriple object on every change\n// 2. Caching propConfig.deserializeAndSanitize(value)\n\nexport default function interpolationTripleAtPosition(\n ctx: IUtilContext,\n trackP: Pointer,\n timeD: Prism,\n): Prism {\n return prism(() => {\n const track = val(trackP)\n const driverD = prism.memo(\n 'driver',\n () => {\n if (!track) {\n return prism(() => undefined)\n } else if (track.type === 'BasicKeyframedTrack') {\n return _forKeyframedTrack(ctx, track, timeD)\n } else {\n ctx.logger.error(`Track type not yet supported.`)\n return prism(() => undefined)\n }\n },\n [track],\n )\n\n return driverD.getValue()\n })\n}\n\ntype IStartedState = {\n started: true\n validFrom: number\n validTo: number\n der: Prism\n}\n\ntype IState = {started: false} | IStartedState\n\nfunction _forKeyframedTrack(\n ctx: IUtilContext,\n track: BasicKeyframedTrack,\n timeD: Prism,\n): Prism {\n return prism(() => {\n let stateRef = prism.ref('state', {started: false})\n let state = stateRef.current\n\n const time = timeD.getValue()\n\n if (!state.started || time < state.validFrom || state.validTo <= time) {\n stateRef.current = state = updateState(ctx, timeD, track)\n }\n\n return state.der.getValue()\n })\n}\n\nconst undefinedConstD = prism(() => undefined)\n\nfunction updateState(\n ctx: IUtilContext,\n progressionD: Prism,\n track: BasicKeyframedTrack,\n): IStartedState {\n const progression = progressionD.getValue()\n if (track.keyframes.length === 0) {\n return {\n started: true,\n validFrom: -Infinity,\n validTo: Infinity,\n der: undefinedConstD,\n }\n }\n\n let currentKeyframeIndex = 0\n\n while (true) {\n const currentKeyframe = track.keyframes[currentKeyframeIndex]\n\n if (!currentKeyframe) {\n if (process.env.NODE_ENV !== 'production') {\n ctx.logger.error(`Bug here`)\n }\n return states.error\n }\n\n const isLastKeyframe = currentKeyframeIndex === track.keyframes.length - 1\n\n if (progression < currentKeyframe.position) {\n if (currentKeyframeIndex === 0) {\n return states.beforeFirstKeyframe(currentKeyframe)\n } else {\n if (process.env.NODE_ENV !== 'production') {\n ctx.logger.error(`Bug here`)\n }\n return states.error\n // note: uncomment these if we support starting with currentPointIndex != 0\n // currentPointIndex--\n // continue\n }\n } else if (currentKeyframe.position === progression) {\n if (isLastKeyframe) {\n return states.lastKeyframe(currentKeyframe)\n } else {\n return states.between(\n currentKeyframe,\n track.keyframes[currentKeyframeIndex + 1],\n progressionD,\n )\n }\n } else {\n // last point\n if (currentKeyframeIndex === track.keyframes.length - 1) {\n return states.lastKeyframe(currentKeyframe)\n } else {\n const nextKeyframeIndex = currentKeyframeIndex + 1\n if (track.keyframes[nextKeyframeIndex].position <= progression) {\n currentKeyframeIndex = nextKeyframeIndex\n continue\n } else {\n return states.between(\n currentKeyframe,\n track.keyframes[currentKeyframeIndex + 1],\n progressionD,\n )\n }\n }\n }\n }\n}\n\nconst states = {\n beforeFirstKeyframe(kf: Keyframe): IStartedState {\n return {\n started: true,\n validFrom: -Infinity,\n validTo: kf.position,\n der: prism(() => ({left: kf.value, progression: 0})),\n }\n },\n lastKeyframe(kf: Keyframe): IStartedState {\n return {\n started: true,\n validFrom: kf.position,\n validTo: Infinity,\n der: prism(() => ({left: kf.value, progression: 0})),\n }\n },\n between(\n left: Keyframe,\n right: Keyframe,\n progressionD: Prism,\n ): IStartedState {\n if (!left.connectedRight) {\n return {\n started: true,\n validFrom: left.position,\n validTo: right.position,\n der: prism(() => ({left: left.value, progression: 0})),\n }\n }\n\n const globalProgressionToLocalProgression = (\n globalProgression: number,\n ): number => {\n return (\n (globalProgression - left.position) / (right.position - left.position)\n )\n }\n\n if (!left.type || left.type === 'bezier') {\n const solver = new UnitBezier(\n left.handles[2],\n left.handles[3],\n right.handles[0],\n right.handles[1],\n )\n\n const bezierDer = prism(() => {\n const progression = globalProgressionToLocalProgression(\n progressionD.getValue(),\n )\n const valueProgression = solver.solveSimple(progression)\n\n return {\n left: left.value,\n right: right.value,\n progression: valueProgression,\n }\n })\n\n return {\n started: true,\n validFrom: left.position,\n validTo: right.position,\n der: bezierDer,\n }\n }\n\n const holdDer = prism(() => {\n const progression = globalProgressionToLocalProgression(\n progressionD.getValue(),\n )\n const valueProgression = Math.floor(progression)\n return {\n left: left.value,\n right: right.value,\n progression: valueProgression,\n }\n })\n\n return {\n started: true,\n validFrom: left.position,\n validTo: right.position,\n der: holdDer,\n }\n },\n error: {\n started: true,\n validFrom: -Infinity,\n validTo: Infinity,\n der: undefinedConstD,\n } as IStartedState,\n}\n", "import type {$IntentionalAny} from '@theatre/shared/utils/types'\nimport type {DeepPartialOfSerializableValue, SerializableMap} from './types'\n\n/**\n * This is like `Object.assign(base, override)`, with the following differences:\n *\n * 1. It returns a new value, instead of mutating `base`:\n * ```js\n * const cache = new WeakMap()\n * const base = {foo: 1}\n * const override = {bar: 1}\n * const result = deepMergeWithCache(base, override, cache)\n * console.log(result) // {foo: 1, bar: 1}\n * console.log(base) // base is not mutated, so: {foo: 1}\n * ```\n *\n * 2. It does a recursive merge for objects:\n * ```js\n * const cache = new WeakMap()\n * const base = {a: {b: 1}}\n * const override = {a: {b: 2}}\n * const result = deepMergeWithCache(base, override, cache)\n * console.log(result) // {a: {b: 2}}\n * ```\n *\n * 2. It uses a WeakMap to cache its results at each level. So merges are referentially stable:\n * ```js\n * const cache = new WeakMap()\n * const base = {a: {b: 1}}\n * const override1 = {a: {b: 2}}\n * const result1 = deepMergeWithCache(base, override, cache)\n * console.log(result1 === deepMergeWithCache(base, override, cache)) // true\n *\n * const override2 = {...override, c: 1}\n * const result2 = deepMergeWithCache(base, override2, cache)\n *\n * console.log(result1.a === result2.a) // logs true, because override1.a === override2.a\n * ```\n *\n * 4. Both `base` and `override` must be plain JSON values and *NO* arrays, so: `boolean, string, number, undefined, {}`\n *\n * Rationale: This is used in {@link SheetObject.getValues} to deep-merge static and sequenced\n * and other types of overrides. If we were to do a deep-merge without a cache, we'd be creating and discarding\n * several JS objects on each frame for every Theatre object, and that would pressure the GC.\n * Plus, keeping the values referentially stable helps lib authors optimize how they patch these values\n * to the rendering engine.\n */\nexport default function deepMergeWithCache(\n base: DeepPartialOfSerializableValue,\n override: DeepPartialOfSerializableValue,\n cache: WeakMap<{}, unknown>,\n): DeepPartialOfSerializableValue {\n const _cache: WeakMap<\n SerializableMap,\n {\n override: DeepPartialOfSerializableValue\n merged: DeepPartialOfSerializableValue\n }\n > = cache as $IntentionalAny\n\n const possibleCachedValue = _cache.get(base)\n\n if (possibleCachedValue && possibleCachedValue.override === override) {\n return possibleCachedValue.merged\n }\n\n const merged = {...base}\n for (const key of Object.keys(override)) {\n const valueInOverride = override[key]\n const valueInBase = base[key]\n\n // @ts-ignore @todo\n merged[key] =\n typeof valueInOverride === 'object' && typeof valueInBase === 'object'\n ? deepMergeWithCache(\n valueInBase as SerializableMap,\n valueInOverride,\n cache,\n )\n : valueInOverride === undefined\n ? valueInBase\n : valueInOverride\n }\n\n cache.set(base, {override, merged})\n return merged\n}\n", "import type {Pointer} from '@theatre/dataverse'\nimport type {PathToProp} from './addresses'\nimport type {$IntentionalAny} from './types'\n\n/**\n * Points deep into a pointer, using `toAppend` as the path. This is _NOT_ type-safe, so use with caution.\n */\nexport default function pointerDeep(\n base: Pointer,\n toAppend: PathToProp,\n): Pointer {\n let p = base as $IntentionalAny\n for (const k of toAppend) {\n p = p[k]\n }\n return p\n}\n", "import {Atom, prism} from '@theatre/dataverse'\n\n/**\n * A prism hook that converts `val` into an atom, and returns that atom.\n */\nexport const valToAtom = (key: string, vals: T): Atom => {\n const a = prism.memo(key, () => new Atom(vals), [])\n a.set(vals)\n return a\n}\n", "/** Used to match a single whitespace character. */\nvar reWhitespace = /\\s/;\n\n/**\n * Used by `_.trim` and `_.trimEnd` to get the index of the last non-whitespace\n * character of `string`.\n *\n * @private\n * @param {string} string The string to inspect.\n * @returns {number} Returns the index of the last non-whitespace character.\n */\nfunction trimmedEndIndex(string) {\n var index = string.length;\n\n while (index-- && reWhitespace.test(string.charAt(index))) {}\n return index;\n}\n\nexport default trimmedEndIndex;\n", "import trimmedEndIndex from './_trimmedEndIndex.js';\n\n/** Used to match leading whitespace. */\nvar reTrimStart = /^\\s+/;\n\n/**\n * The base implementation of `_.trim`.\n *\n * @private\n * @param {string} string The string to trim.\n * @returns {string} Returns the trimmed string.\n */\nfunction baseTrim(string) {\n return string\n ? string.slice(0, trimmedEndIndex(string) + 1).replace(reTrimStart, '')\n : string;\n}\n\nexport default baseTrim;\n", "import baseTrim from './_baseTrim.js';\nimport isObject from './isObject.js';\nimport isSymbol from './isSymbol.js';\n\n/** Used as references for various `Number` constants. */\nvar NAN = 0 / 0;\n\n/** Used to detect bad signed hexadecimal string values. */\nvar reIsBadHex = /^[-+]0x[0-9a-f]+$/i;\n\n/** Used to detect binary string values. */\nvar reIsBinary = /^0b[01]+$/i;\n\n/** Used to detect octal string values. */\nvar reIsOctal = /^0o[0-7]+$/i;\n\n/** Built-in method references without a dependency on `root`. */\nvar freeParseInt = parseInt;\n\n/**\n * Converts `value` to a number.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to process.\n * @returns {number} Returns the number.\n * @example\n *\n * _.toNumber(3.2);\n * // => 3.2\n *\n * _.toNumber(Number.MIN_VALUE);\n * // => 5e-324\n *\n * _.toNumber(Infinity);\n * // => Infinity\n *\n * _.toNumber('3.2');\n * // => 3.2\n */\nfunction toNumber(value) {\n if (typeof value == 'number') {\n return value;\n }\n if (isSymbol(value)) {\n return NAN;\n }\n if (isObject(value)) {\n var other = typeof value.valueOf == 'function' ? value.valueOf() : value;\n value = isObject(other) ? (other + '') : other;\n }\n if (typeof value != 'string') {\n return value === 0 ? value : +value;\n }\n value = baseTrim(value);\n var isBinary = reIsBinary.test(value);\n return (isBinary || reIsOctal.test(value))\n ? freeParseInt(value.slice(2), isBinary ? 2 : 8)\n : (reIsBadHex.test(value) ? NAN : +value);\n}\n\nexport default toNumber;\n", "import toNumber from './toNumber.js';\n\n/** Used as references for various `Number` constants. */\nvar INFINITY = 1 / 0,\n MAX_INTEGER = 1.7976931348623157e+308;\n\n/**\n * Converts `value` to a finite number.\n *\n * @static\n * @memberOf _\n * @since 4.12.0\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {number} Returns the converted number.\n * @example\n *\n * _.toFinite(3.2);\n * // => 3.2\n *\n * _.toFinite(Number.MIN_VALUE);\n * // => 5e-324\n *\n * _.toFinite(Infinity);\n * // => 1.7976931348623157e+308\n *\n * _.toFinite('3.2');\n * // => 3.2\n */\nfunction toFinite(value) {\n if (!value) {\n return value === 0 ? value : 0;\n }\n value = toNumber(value);\n if (value === INFINITY || value === -INFINITY) {\n var sign = (value < 0 ? -1 : 1);\n return sign * MAX_INTEGER;\n }\n return value === value ? value : 0;\n}\n\nexport default toFinite;\n", "import toFinite from './toFinite.js';\n\n/**\n * Converts `value` to an integer.\n *\n * **Note:** This method is loosely based on\n * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {number} Returns the converted integer.\n * @example\n *\n * _.toInteger(3.2);\n * // => 3\n *\n * _.toInteger(Number.MIN_VALUE);\n * // => 0\n *\n * _.toInteger(Infinity);\n * // => 1.7976931348623157e+308\n *\n * _.toInteger('3.2');\n * // => 3\n */\nfunction toInteger(value) {\n var result = toFinite(value),\n remainder = result % 1;\n\n return result === result ? (remainder ? result - remainder : result) : 0;\n}\n\nexport default toInteger;\n", "/**\n * This method returns the first argument it receives.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Util\n * @param {*} value Any value.\n * @returns {*} Returns `value`.\n * @example\n *\n * var object = { 'a': 1 };\n *\n * console.log(_.identity(object) === object);\n * // => true\n */\nfunction identity(value) {\n return value;\n}\n\nexport default identity;\n", "import getNative from './_getNative.js';\nimport root from './_root.js';\n\n/* Built-in method references that are verified to be native. */\nvar WeakMap = getNative(root, 'WeakMap');\n\nexport default WeakMap;\n", "import isObject from './isObject.js';\n\n/** Built-in value references. */\nvar objectCreate = Object.create;\n\n/**\n * The base implementation of `_.create` without support for assigning\n * properties to the created object.\n *\n * @private\n * @param {Object} proto The object to inherit from.\n * @returns {Object} Returns the new object.\n */\nvar baseCreate = (function() {\n function object() {}\n return function(proto) {\n if (!isObject(proto)) {\n return {};\n }\n if (objectCreate) {\n return objectCreate(proto);\n }\n object.prototype = proto;\n var result = new object;\n object.prototype = undefined;\n return result;\n };\n}());\n\nexport default baseCreate;\n", "/**\n * Copies the values of `source` to `array`.\n *\n * @private\n * @param {Array} source The array to copy values from.\n * @param {Array} [array=[]] The array to copy values to.\n * @returns {Array} Returns `array`.\n */\nfunction copyArray(source, array) {\n var index = -1,\n length = source.length;\n\n array || (array = Array(length));\n while (++index < length) {\n array[index] = source[index];\n }\n return array;\n}\n\nexport default copyArray;\n", "/**\n * A specialized version of `_.forEach` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns `array`.\n */\nfunction arrayEach(array, iteratee) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (iteratee(array[index], index, array) === false) {\n break;\n }\n }\n return array;\n}\n\nexport default arrayEach;\n", "import assignValue from './_assignValue.js';\nimport baseAssignValue from './_baseAssignValue.js';\n\n/**\n * Copies properties of `source` to `object`.\n *\n * @private\n * @param {Object} source The object to copy properties from.\n * @param {Array} props The property identifiers to copy.\n * @param {Object} [object={}] The object to copy properties to.\n * @param {Function} [customizer] The function to customize copied values.\n * @returns {Object} Returns `object`.\n */\nfunction copyObject(source, props, object, customizer) {\n var isNew = !object;\n object || (object = {});\n\n var index = -1,\n length = props.length;\n\n while (++index < length) {\n var key = props[index];\n\n var newValue = customizer\n ? customizer(object[key], source[key], key, object, source)\n : undefined;\n\n if (newValue === undefined) {\n newValue = source[key];\n }\n if (isNew) {\n baseAssignValue(object, key, newValue);\n } else {\n assignValue(object, key, newValue);\n }\n }\n return object;\n}\n\nexport default copyObject;\n", "/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/**\n * Checks if `value` is a valid array-like length.\n *\n * **Note:** This method is loosely based on\n * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.\n * @example\n *\n * _.isLength(3);\n * // => true\n *\n * _.isLength(Number.MIN_VALUE);\n * // => false\n *\n * _.isLength(Infinity);\n * // => false\n *\n * _.isLength('3');\n * // => false\n */\nfunction isLength(value) {\n return typeof value == 'number' &&\n value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;\n}\n\nexport default isLength;\n", "import isFunction from './isFunction.js';\nimport isLength from './isLength.js';\n\n/**\n * Checks if `value` is array-like. A value is considered array-like if it's\n * not a function and has a `value.length` that's an integer greater than or\n * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is array-like, else `false`.\n * @example\n *\n * _.isArrayLike([1, 2, 3]);\n * // => true\n *\n * _.isArrayLike(document.body.children);\n * // => true\n *\n * _.isArrayLike('abc');\n * // => true\n *\n * _.isArrayLike(_.noop);\n * // => false\n */\nfunction isArrayLike(value) {\n return value != null && isLength(value.length) && !isFunction(value);\n}\n\nexport default isArrayLike;\n", "/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Checks if `value` is likely a prototype object.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.\n */\nfunction isPrototype(value) {\n var Ctor = value && value.constructor,\n proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;\n\n return value === proto;\n}\n\nexport default isPrototype;\n", "/**\n * The base implementation of `_.times` without support for iteratee shorthands\n * or max array length checks.\n *\n * @private\n * @param {number} n The number of times to invoke `iteratee`.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the array of results.\n */\nfunction baseTimes(n, iteratee) {\n var index = -1,\n result = Array(n);\n\n while (++index < n) {\n result[index] = iteratee(index);\n }\n return result;\n}\n\nexport default baseTimes;\n", "import baseGetTag from './_baseGetTag.js';\nimport isObjectLike from './isObjectLike.js';\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]';\n\n/**\n * The base implementation of `_.isArguments`.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an `arguments` object,\n */\nfunction baseIsArguments(value) {\n return isObjectLike(value) && baseGetTag(value) == argsTag;\n}\n\nexport default baseIsArguments;\n", "import baseIsArguments from './_baseIsArguments.js';\nimport isObjectLike from './isObjectLike.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/** Built-in value references. */\nvar propertyIsEnumerable = objectProto.propertyIsEnumerable;\n\n/**\n * Checks if `value` is likely an `arguments` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an `arguments` object,\n * else `false`.\n * @example\n *\n * _.isArguments(function() { return arguments; }());\n * // => true\n *\n * _.isArguments([1, 2, 3]);\n * // => false\n */\nvar isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {\n return isObjectLike(value) && hasOwnProperty.call(value, 'callee') &&\n !propertyIsEnumerable.call(value, 'callee');\n};\n\nexport default isArguments;\n", "/**\n * This method returns `false`.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {boolean} Returns `false`.\n * @example\n *\n * _.times(2, _.stubFalse);\n * // => [false, false]\n */\nfunction stubFalse() {\n return false;\n}\n\nexport default stubFalse;\n", "import root from './_root.js';\nimport stubFalse from './stubFalse.js';\n\n/** Detect free variable `exports`. */\nvar freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;\n\n/** Detect free variable `module`. */\nvar freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;\n\n/** Detect the popular CommonJS extension `module.exports`. */\nvar moduleExports = freeModule && freeModule.exports === freeExports;\n\n/** Built-in value references. */\nvar Buffer = moduleExports ? root.Buffer : undefined;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;\n\n/**\n * Checks if `value` is a buffer.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.\n * @example\n *\n * _.isBuffer(new Buffer(2));\n * // => true\n *\n * _.isBuffer(new Uint8Array(2));\n * // => false\n */\nvar isBuffer = nativeIsBuffer || stubFalse;\n\nexport default isBuffer;\n", "import baseGetTag from './_baseGetTag.js';\nimport isLength from './isLength.js';\nimport isObjectLike from './isObjectLike.js';\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]',\n arrayTag = '[object Array]',\n boolTag = '[object Boolean]',\n dateTag = '[object Date]',\n errorTag = '[object Error]',\n funcTag = '[object Function]',\n mapTag = '[object Map]',\n numberTag = '[object Number]',\n objectTag = '[object Object]',\n regexpTag = '[object RegExp]',\n setTag = '[object Set]',\n stringTag = '[object String]',\n weakMapTag = '[object WeakMap]';\n\nvar arrayBufferTag = '[object ArrayBuffer]',\n dataViewTag = '[object DataView]',\n float32Tag = '[object Float32Array]',\n float64Tag = '[object Float64Array]',\n int8Tag = '[object Int8Array]',\n int16Tag = '[object Int16Array]',\n int32Tag = '[object Int32Array]',\n uint8Tag = '[object Uint8Array]',\n uint8ClampedTag = '[object Uint8ClampedArray]',\n uint16Tag = '[object Uint16Array]',\n uint32Tag = '[object Uint32Array]';\n\n/** Used to identify `toStringTag` values of typed arrays. */\nvar typedArrayTags = {};\ntypedArrayTags[float32Tag] = typedArrayTags[float64Tag] =\ntypedArrayTags[int8Tag] = typedArrayTags[int16Tag] =\ntypedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =\ntypedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =\ntypedArrayTags[uint32Tag] = true;\ntypedArrayTags[argsTag] = typedArrayTags[arrayTag] =\ntypedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =\ntypedArrayTags[dataViewTag] = typedArrayTags[dateTag] =\ntypedArrayTags[errorTag] = typedArrayTags[funcTag] =\ntypedArrayTags[mapTag] = typedArrayTags[numberTag] =\ntypedArrayTags[objectTag] = typedArrayTags[regexpTag] =\ntypedArrayTags[setTag] = typedArrayTags[stringTag] =\ntypedArrayTags[weakMapTag] = false;\n\n/**\n * The base implementation of `_.isTypedArray` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.\n */\nfunction baseIsTypedArray(value) {\n return isObjectLike(value) &&\n isLength(value.length) && !!typedArrayTags[baseGetTag(value)];\n}\n\nexport default baseIsTypedArray;\n", "/**\n * The base implementation of `_.unary` without support for storing metadata.\n *\n * @private\n * @param {Function} func The function to cap arguments for.\n * @returns {Function} Returns the new capped function.\n */\nfunction baseUnary(func) {\n return function(value) {\n return func(value);\n };\n}\n\nexport default baseUnary;\n", "import freeGlobal from './_freeGlobal.js';\n\n/** Detect free variable `exports`. */\nvar freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;\n\n/** Detect free variable `module`. */\nvar freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;\n\n/** Detect the popular CommonJS extension `module.exports`. */\nvar moduleExports = freeModule && freeModule.exports === freeExports;\n\n/** Detect free variable `process` from Node.js. */\nvar freeProcess = moduleExports && freeGlobal.process;\n\n/** Used to access faster Node.js helpers. */\nvar nodeUtil = (function() {\n try {\n // Use `util.types` for Node.js 10+.\n var types = freeModule && freeModule.require && freeModule.require('util').types;\n\n if (types) {\n return types;\n }\n\n // Legacy `process.binding('util')` for Node.js < 10.\n return freeProcess && freeProcess.binding && freeProcess.binding('util');\n } catch (e) {}\n}());\n\nexport default nodeUtil;\n", "import baseIsTypedArray from './_baseIsTypedArray.js';\nimport baseUnary from './_baseUnary.js';\nimport nodeUtil from './_nodeUtil.js';\n\n/* Node.js helper references. */\nvar nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;\n\n/**\n * Checks if `value` is classified as a typed array.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.\n * @example\n *\n * _.isTypedArray(new Uint8Array);\n * // => true\n *\n * _.isTypedArray([]);\n * // => false\n */\nvar isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;\n\nexport default isTypedArray;\n", "import baseTimes from './_baseTimes.js';\nimport isArguments from './isArguments.js';\nimport isArray from './isArray.js';\nimport isBuffer from './isBuffer.js';\nimport isIndex from './_isIndex.js';\nimport isTypedArray from './isTypedArray.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Creates an array of the enumerable property names of the array-like `value`.\n *\n * @private\n * @param {*} value The value to query.\n * @param {boolean} inherited Specify returning inherited property names.\n * @returns {Array} Returns the array of property names.\n */\nfunction arrayLikeKeys(value, inherited) {\n var isArr = isArray(value),\n isArg = !isArr && isArguments(value),\n isBuff = !isArr && !isArg && isBuffer(value),\n isType = !isArr && !isArg && !isBuff && isTypedArray(value),\n skipIndexes = isArr || isArg || isBuff || isType,\n result = skipIndexes ? baseTimes(value.length, String) : [],\n length = result.length;\n\n for (var key in value) {\n if ((inherited || hasOwnProperty.call(value, key)) &&\n !(skipIndexes && (\n // Safari 9 has enumerable `arguments.length` in strict mode.\n key == 'length' ||\n // Node.js 0.10 has enumerable non-index properties on buffers.\n (isBuff && (key == 'offset' || key == 'parent')) ||\n // PhantomJS 2 has enumerable non-index properties on typed arrays.\n (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||\n // Skip index properties.\n isIndex(key, length)\n ))) {\n result.push(key);\n }\n }\n return result;\n}\n\nexport default arrayLikeKeys;\n", "import overArg from './_overArg.js';\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeKeys = overArg(Object.keys, Object);\n\nexport default nativeKeys;\n", "import isPrototype from './_isPrototype.js';\nimport nativeKeys from './_nativeKeys.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\nfunction baseKeys(object) {\n if (!isPrototype(object)) {\n return nativeKeys(object);\n }\n var result = [];\n for (var key in Object(object)) {\n if (hasOwnProperty.call(object, key) && key != 'constructor') {\n result.push(key);\n }\n }\n return result;\n}\n\nexport default baseKeys;\n", "import arrayLikeKeys from './_arrayLikeKeys.js';\nimport baseKeys from './_baseKeys.js';\nimport isArrayLike from './isArrayLike.js';\n\n/**\n * Creates an array of the own enumerable property names of `object`.\n *\n * **Note:** Non-object values are coerced to objects. See the\n * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)\n * for more details.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.keys(new Foo);\n * // => ['a', 'b'] (iteration order is not guaranteed)\n *\n * _.keys('hi');\n * // => ['0', '1']\n */\nfunction keys(object) {\n return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);\n}\n\nexport default keys;\n", "/**\n * This function is like\n * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)\n * except that it includes inherited enumerable properties.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\nfunction nativeKeysIn(object) {\n var result = [];\n if (object != null) {\n for (var key in Object(object)) {\n result.push(key);\n }\n }\n return result;\n}\n\nexport default nativeKeysIn;\n", "import isObject from './isObject.js';\nimport isPrototype from './_isPrototype.js';\nimport nativeKeysIn from './_nativeKeysIn.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\nfunction baseKeysIn(object) {\n if (!isObject(object)) {\n return nativeKeysIn(object);\n }\n var isProto = isPrototype(object),\n result = [];\n\n for (var key in object) {\n if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {\n result.push(key);\n }\n }\n return result;\n}\n\nexport default baseKeysIn;\n", "import arrayLikeKeys from './_arrayLikeKeys.js';\nimport baseKeysIn from './_baseKeysIn.js';\nimport isArrayLike from './isArrayLike.js';\n\n/**\n * Creates an array of the own and inherited enumerable property names of `object`.\n *\n * **Note:** Non-object values are coerced to objects.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.keysIn(new Foo);\n * // => ['a', 'b', 'c'] (iteration order is not guaranteed)\n */\nfunction keysIn(object) {\n return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object);\n}\n\nexport default keysIn;\n", "/**\n * Appends the elements of `values` to `array`.\n *\n * @private\n * @param {Array} array The array to modify.\n * @param {Array} values The values to append.\n * @returns {Array} Returns `array`.\n */\nfunction arrayPush(array, values) {\n var index = -1,\n length = values.length,\n offset = array.length;\n\n while (++index < length) {\n array[offset + index] = values[index];\n }\n return array;\n}\n\nexport default arrayPush;\n", "/**\n * The base implementation of `_.slice` without an iteratee call guard.\n *\n * @private\n * @param {Array} array The array to slice.\n * @param {number} [start=0] The start position.\n * @param {number} [end=array.length] The end position.\n * @returns {Array} Returns the slice of `array`.\n */\nfunction baseSlice(array, start, end) {\n var index = -1,\n length = array.length;\n\n if (start < 0) {\n start = -start > length ? 0 : (length + start);\n }\n end = end > length ? length : end;\n if (end < 0) {\n end += length;\n }\n length = start > end ? 0 : ((end - start) >>> 0);\n start >>>= 0;\n\n var result = Array(length);\n while (++index < length) {\n result[index] = array[index + start];\n }\n return result;\n}\n\nexport default baseSlice;\n", "import baseSlice from './_baseSlice.js';\n\n/**\n * Casts `array` to a slice if it's needed.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {number} start The start position.\n * @param {number} [end=array.length] The end position.\n * @returns {Array} Returns the cast slice.\n */\nfunction castSlice(array, start, end) {\n var length = array.length;\n end = end === undefined ? length : end;\n return (!start && end >= length) ? array : baseSlice(array, start, end);\n}\n\nexport default castSlice;\n", "/** Used to compose unicode character classes. */\nvar rsAstralRange = '\\\\ud800-\\\\udfff',\n rsComboMarksRange = '\\\\u0300-\\\\u036f',\n reComboHalfMarksRange = '\\\\ufe20-\\\\ufe2f',\n rsComboSymbolsRange = '\\\\u20d0-\\\\u20ff',\n rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,\n rsVarRange = '\\\\ufe0e\\\\ufe0f';\n\n/** Used to compose unicode capture groups. */\nvar rsZWJ = '\\\\u200d';\n\n/** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */\nvar reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']');\n\n/**\n * Checks if `string` contains Unicode symbols.\n *\n * @private\n * @param {string} string The string to inspect.\n * @returns {boolean} Returns `true` if a symbol is found, else `false`.\n */\nfunction hasUnicode(string) {\n return reHasUnicode.test(string);\n}\n\nexport default hasUnicode;\n", "/**\n * Converts an ASCII `string` to an array.\n *\n * @private\n * @param {string} string The string to convert.\n * @returns {Array} Returns the converted array.\n */\nfunction asciiToArray(string) {\n return string.split('');\n}\n\nexport default asciiToArray;\n", "/** Used to compose unicode character classes. */\nvar rsAstralRange = '\\\\ud800-\\\\udfff',\n rsComboMarksRange = '\\\\u0300-\\\\u036f',\n reComboHalfMarksRange = '\\\\ufe20-\\\\ufe2f',\n rsComboSymbolsRange = '\\\\u20d0-\\\\u20ff',\n rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,\n rsVarRange = '\\\\ufe0e\\\\ufe0f';\n\n/** Used to compose unicode capture groups. */\nvar rsAstral = '[' + rsAstralRange + ']',\n rsCombo = '[' + rsComboRange + ']',\n rsFitz = '\\\\ud83c[\\\\udffb-\\\\udfff]',\n rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',\n rsNonAstral = '[^' + rsAstralRange + ']',\n rsRegional = '(?:\\\\ud83c[\\\\udde6-\\\\uddff]){2}',\n rsSurrPair = '[\\\\ud800-\\\\udbff][\\\\udc00-\\\\udfff]',\n rsZWJ = '\\\\u200d';\n\n/** Used to compose unicode regexes. */\nvar reOptMod = rsModifier + '?',\n rsOptVar = '[' + rsVarRange + ']?',\n rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',\n rsSeq = rsOptVar + reOptMod + rsOptJoin,\n rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';\n\n/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */\nvar reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');\n\n/**\n * Converts a Unicode `string` to an array.\n *\n * @private\n * @param {string} string The string to convert.\n * @returns {Array} Returns the converted array.\n */\nfunction unicodeToArray(string) {\n return string.match(reUnicode) || [];\n}\n\nexport default unicodeToArray;\n", "import asciiToArray from './_asciiToArray.js';\nimport hasUnicode from './_hasUnicode.js';\nimport unicodeToArray from './_unicodeToArray.js';\n\n/**\n * Converts `string` to an array.\n *\n * @private\n * @param {string} string The string to convert.\n * @returns {Array} Returns the converted array.\n */\nfunction stringToArray(string) {\n return hasUnicode(string)\n ? unicodeToArray(string)\n : asciiToArray(string);\n}\n\nexport default stringToArray;\n", "/**\n * The base implementation of `_.clamp` which doesn't coerce arguments.\n *\n * @private\n * @param {number} number The number to clamp.\n * @param {number} [lower] The lower bound.\n * @param {number} upper The upper bound.\n * @returns {number} Returns the clamped number.\n */\nfunction baseClamp(number, lower, upper) {\n if (number === number) {\n if (upper !== undefined) {\n number = number <= upper ? number : upper;\n }\n if (lower !== undefined) {\n number = number >= lower ? number : lower;\n }\n }\n return number;\n}\n\nexport default baseClamp;\n", "import baseClamp from './_baseClamp.js';\nimport toNumber from './toNumber.js';\n\n/**\n * Clamps `number` within the inclusive `lower` and `upper` bounds.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Number\n * @param {number} number The number to clamp.\n * @param {number} [lower] The lower bound.\n * @param {number} upper The upper bound.\n * @returns {number} Returns the clamped number.\n * @example\n *\n * _.clamp(-10, -5, 5);\n * // => -5\n *\n * _.clamp(10, -5, 5);\n * // => 5\n */\nfunction clamp(number, lower, upper) {\n if (upper === undefined) {\n upper = lower;\n lower = undefined;\n }\n if (upper !== undefined) {\n upper = toNumber(upper);\n upper = upper === upper ? upper : 0;\n }\n if (lower !== undefined) {\n lower = toNumber(lower);\n lower = lower === lower ? lower : 0;\n }\n return baseClamp(toNumber(number), lower, upper);\n}\n\nexport default clamp;\n", "import ListCache from './_ListCache.js';\n\n/**\n * Removes all key-value entries from the stack.\n *\n * @private\n * @name clear\n * @memberOf Stack\n */\nfunction stackClear() {\n this.__data__ = new ListCache;\n this.size = 0;\n}\n\nexport default stackClear;\n", "/**\n * Removes `key` and its value from the stack.\n *\n * @private\n * @name delete\n * @memberOf Stack\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction stackDelete(key) {\n var data = this.__data__,\n result = data['delete'](key);\n\n this.size = data.size;\n return result;\n}\n\nexport default stackDelete;\n", "/**\n * Gets the stack value for `key`.\n *\n * @private\n * @name get\n * @memberOf Stack\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction stackGet(key) {\n return this.__data__.get(key);\n}\n\nexport default stackGet;\n", "/**\n * Checks if a stack value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Stack\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction stackHas(key) {\n return this.__data__.has(key);\n}\n\nexport default stackHas;\n", "import ListCache from './_ListCache.js';\nimport Map from './_Map.js';\nimport MapCache from './_MapCache.js';\n\n/** Used as the size to enable large array optimizations. */\nvar LARGE_ARRAY_SIZE = 200;\n\n/**\n * Sets the stack `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf Stack\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the stack cache instance.\n */\nfunction stackSet(key, value) {\n var data = this.__data__;\n if (data instanceof ListCache) {\n var pairs = data.__data__;\n if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {\n pairs.push([key, value]);\n this.size = ++data.size;\n return this;\n }\n data = this.__data__ = new MapCache(pairs);\n }\n data.set(key, value);\n this.size = data.size;\n return this;\n}\n\nexport default stackSet;\n", "import ListCache from './_ListCache.js';\nimport stackClear from './_stackClear.js';\nimport stackDelete from './_stackDelete.js';\nimport stackGet from './_stackGet.js';\nimport stackHas from './_stackHas.js';\nimport stackSet from './_stackSet.js';\n\n/**\n * Creates a stack cache object to store key-value pairs.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction Stack(entries) {\n var data = this.__data__ = new ListCache(entries);\n this.size = data.size;\n}\n\n// Add methods to `Stack`.\nStack.prototype.clear = stackClear;\nStack.prototype['delete'] = stackDelete;\nStack.prototype.get = stackGet;\nStack.prototype.has = stackHas;\nStack.prototype.set = stackSet;\n\nexport default Stack;\n", "import copyObject from './_copyObject.js';\nimport keys from './keys.js';\n\n/**\n * The base implementation of `_.assign` without support for multiple sources\n * or `customizer` functions.\n *\n * @private\n * @param {Object} object The destination object.\n * @param {Object} source The source object.\n * @returns {Object} Returns `object`.\n */\nfunction baseAssign(object, source) {\n return object && copyObject(source, keys(source), object);\n}\n\nexport default baseAssign;\n", "import copyObject from './_copyObject.js';\nimport keysIn from './keysIn.js';\n\n/**\n * The base implementation of `_.assignIn` without support for multiple sources\n * or `customizer` functions.\n *\n * @private\n * @param {Object} object The destination object.\n * @param {Object} source The source object.\n * @returns {Object} Returns `object`.\n */\nfunction baseAssignIn(object, source) {\n return object && copyObject(source, keysIn(source), object);\n}\n\nexport default baseAssignIn;\n", "import root from './_root.js';\n\n/** Detect free variable `exports`. */\nvar freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;\n\n/** Detect free variable `module`. */\nvar freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;\n\n/** Detect the popular CommonJS extension `module.exports`. */\nvar moduleExports = freeModule && freeModule.exports === freeExports;\n\n/** Built-in value references. */\nvar Buffer = moduleExports ? root.Buffer : undefined,\n allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined;\n\n/**\n * Creates a clone of `buffer`.\n *\n * @private\n * @param {Buffer} buffer The buffer to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Buffer} Returns the cloned buffer.\n */\nfunction cloneBuffer(buffer, isDeep) {\n if (isDeep) {\n return buffer.slice();\n }\n var length = buffer.length,\n result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length);\n\n buffer.copy(result);\n return result;\n}\n\nexport default cloneBuffer;\n", "/**\n * A specialized version of `_.filter` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {Array} Returns the new filtered array.\n */\nfunction arrayFilter(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length,\n resIndex = 0,\n result = [];\n\n while (++index < length) {\n var value = array[index];\n if (predicate(value, index, array)) {\n result[resIndex++] = value;\n }\n }\n return result;\n}\n\nexport default arrayFilter;\n", "/**\n * This method returns a new empty array.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {Array} Returns the new empty array.\n * @example\n *\n * var arrays = _.times(2, _.stubArray);\n *\n * console.log(arrays);\n * // => [[], []]\n *\n * console.log(arrays[0] === arrays[1]);\n * // => false\n */\nfunction stubArray() {\n return [];\n}\n\nexport default stubArray;\n", "import arrayFilter from './_arrayFilter.js';\nimport stubArray from './stubArray.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Built-in value references. */\nvar propertyIsEnumerable = objectProto.propertyIsEnumerable;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeGetSymbols = Object.getOwnPropertySymbols;\n\n/**\n * Creates an array of the own enumerable symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of symbols.\n */\nvar getSymbols = !nativeGetSymbols ? stubArray : function(object) {\n if (object == null) {\n return [];\n }\n object = Object(object);\n return arrayFilter(nativeGetSymbols(object), function(symbol) {\n return propertyIsEnumerable.call(object, symbol);\n });\n};\n\nexport default getSymbols;\n", "import copyObject from './_copyObject.js';\nimport getSymbols from './_getSymbols.js';\n\n/**\n * Copies own symbols of `source` to `object`.\n *\n * @private\n * @param {Object} source The object to copy symbols from.\n * @param {Object} [object={}] The object to copy symbols to.\n * @returns {Object} Returns `object`.\n */\nfunction copySymbols(source, object) {\n return copyObject(source, getSymbols(source), object);\n}\n\nexport default copySymbols;\n", "import arrayPush from './_arrayPush.js';\nimport getPrototype from './_getPrototype.js';\nimport getSymbols from './_getSymbols.js';\nimport stubArray from './stubArray.js';\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeGetSymbols = Object.getOwnPropertySymbols;\n\n/**\n * Creates an array of the own and inherited enumerable symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of symbols.\n */\nvar getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) {\n var result = [];\n while (object) {\n arrayPush(result, getSymbols(object));\n object = getPrototype(object);\n }\n return result;\n};\n\nexport default getSymbolsIn;\n", "import copyObject from './_copyObject.js';\nimport getSymbolsIn from './_getSymbolsIn.js';\n\n/**\n * Copies own and inherited symbols of `source` to `object`.\n *\n * @private\n * @param {Object} source The object to copy symbols from.\n * @param {Object} [object={}] The object to copy symbols to.\n * @returns {Object} Returns `object`.\n */\nfunction copySymbolsIn(source, object) {\n return copyObject(source, getSymbolsIn(source), object);\n}\n\nexport default copySymbolsIn;\n", "import arrayPush from './_arrayPush.js';\nimport isArray from './isArray.js';\n\n/**\n * The base implementation of `getAllKeys` and `getAllKeysIn` which uses\n * `keysFunc` and `symbolsFunc` to get the enumerable property names and\n * symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Function} keysFunc The function to get the keys of `object`.\n * @param {Function} symbolsFunc The function to get the symbols of `object`.\n * @returns {Array} Returns the array of property names and symbols.\n */\nfunction baseGetAllKeys(object, keysFunc, symbolsFunc) {\n var result = keysFunc(object);\n return isArray(object) ? result : arrayPush(result, symbolsFunc(object));\n}\n\nexport default baseGetAllKeys;\n", "import baseGetAllKeys from './_baseGetAllKeys.js';\nimport getSymbols from './_getSymbols.js';\nimport keys from './keys.js';\n\n/**\n * Creates an array of own enumerable property names and symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names and symbols.\n */\nfunction getAllKeys(object) {\n return baseGetAllKeys(object, keys, getSymbols);\n}\n\nexport default getAllKeys;\n", "import baseGetAllKeys from './_baseGetAllKeys.js';\nimport getSymbolsIn from './_getSymbolsIn.js';\nimport keysIn from './keysIn.js';\n\n/**\n * Creates an array of own and inherited enumerable property names and\n * symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names and symbols.\n */\nfunction getAllKeysIn(object) {\n return baseGetAllKeys(object, keysIn, getSymbolsIn);\n}\n\nexport default getAllKeysIn;\n", "import getNative from './_getNative.js';\nimport root from './_root.js';\n\n/* Built-in method references that are verified to be native. */\nvar DataView = getNative(root, 'DataView');\n\nexport default DataView;\n", "import getNative from './_getNative.js';\nimport root from './_root.js';\n\n/* Built-in method references that are verified to be native. */\nvar Promise = getNative(root, 'Promise');\n\nexport default Promise;\n", "import getNative from './_getNative.js';\nimport root from './_root.js';\n\n/* Built-in method references that are verified to be native. */\nvar Set = getNative(root, 'Set');\n\nexport default Set;\n", "import DataView from './_DataView.js';\nimport Map from './_Map.js';\nimport Promise from './_Promise.js';\nimport Set from './_Set.js';\nimport WeakMap from './_WeakMap.js';\nimport baseGetTag from './_baseGetTag.js';\nimport toSource from './_toSource.js';\n\n/** `Object#toString` result references. */\nvar mapTag = '[object Map]',\n objectTag = '[object Object]',\n promiseTag = '[object Promise]',\n setTag = '[object Set]',\n weakMapTag = '[object WeakMap]';\n\nvar dataViewTag = '[object DataView]';\n\n/** Used to detect maps, sets, and weakmaps. */\nvar dataViewCtorString = toSource(DataView),\n mapCtorString = toSource(Map),\n promiseCtorString = toSource(Promise),\n setCtorString = toSource(Set),\n weakMapCtorString = toSource(WeakMap);\n\n/**\n * Gets the `toStringTag` of `value`.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\nvar getTag = baseGetTag;\n\n// Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.\nif ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) ||\n (Map && getTag(new Map) != mapTag) ||\n (Promise && getTag(Promise.resolve()) != promiseTag) ||\n (Set && getTag(new Set) != setTag) ||\n (WeakMap && getTag(new WeakMap) != weakMapTag)) {\n getTag = function(value) {\n var result = baseGetTag(value),\n Ctor = result == objectTag ? value.constructor : undefined,\n ctorString = Ctor ? toSource(Ctor) : '';\n\n if (ctorString) {\n switch (ctorString) {\n case dataViewCtorString: return dataViewTag;\n case mapCtorString: return mapTag;\n case promiseCtorString: return promiseTag;\n case setCtorString: return setTag;\n case weakMapCtorString: return weakMapTag;\n }\n }\n return result;\n };\n}\n\nexport default getTag;\n", "/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Initializes an array clone.\n *\n * @private\n * @param {Array} array The array to clone.\n * @returns {Array} Returns the initialized clone.\n */\nfunction initCloneArray(array) {\n var length = array.length,\n result = new array.constructor(length);\n\n // Add properties assigned by `RegExp#exec`.\n if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) {\n result.index = array.index;\n result.input = array.input;\n }\n return result;\n}\n\nexport default initCloneArray;\n", "import root from './_root.js';\n\n/** Built-in value references. */\nvar Uint8Array = root.Uint8Array;\n\nexport default Uint8Array;\n", "import Uint8Array from './_Uint8Array.js';\n\n/**\n * Creates a clone of `arrayBuffer`.\n *\n * @private\n * @param {ArrayBuffer} arrayBuffer The array buffer to clone.\n * @returns {ArrayBuffer} Returns the cloned array buffer.\n */\nfunction cloneArrayBuffer(arrayBuffer) {\n var result = new arrayBuffer.constructor(arrayBuffer.byteLength);\n new Uint8Array(result).set(new Uint8Array(arrayBuffer));\n return result;\n}\n\nexport default cloneArrayBuffer;\n", "import cloneArrayBuffer from './_cloneArrayBuffer.js';\n\n/**\n * Creates a clone of `dataView`.\n *\n * @private\n * @param {Object} dataView The data view to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Object} Returns the cloned data view.\n */\nfunction cloneDataView(dataView, isDeep) {\n var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer;\n return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);\n}\n\nexport default cloneDataView;\n", "/** Used to match `RegExp` flags from their coerced string values. */\nvar reFlags = /\\w*$/;\n\n/**\n * Creates a clone of `regexp`.\n *\n * @private\n * @param {Object} regexp The regexp to clone.\n * @returns {Object} Returns the cloned regexp.\n */\nfunction cloneRegExp(regexp) {\n var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));\n result.lastIndex = regexp.lastIndex;\n return result;\n}\n\nexport default cloneRegExp;\n", "import Symbol from './_Symbol.js';\n\n/** Used to convert symbols to primitives and strings. */\nvar symbolProto = Symbol ? Symbol.prototype : undefined,\n symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;\n\n/**\n * Creates a clone of the `symbol` object.\n *\n * @private\n * @param {Object} symbol The symbol object to clone.\n * @returns {Object} Returns the cloned symbol object.\n */\nfunction cloneSymbol(symbol) {\n return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {};\n}\n\nexport default cloneSymbol;\n", "import cloneArrayBuffer from './_cloneArrayBuffer.js';\n\n/**\n * Creates a clone of `typedArray`.\n *\n * @private\n * @param {Object} typedArray The typed array to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Object} Returns the cloned typed array.\n */\nfunction cloneTypedArray(typedArray, isDeep) {\n var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;\n return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);\n}\n\nexport default cloneTypedArray;\n", "import cloneArrayBuffer from './_cloneArrayBuffer.js';\nimport cloneDataView from './_cloneDataView.js';\nimport cloneRegExp from './_cloneRegExp.js';\nimport cloneSymbol from './_cloneSymbol.js';\nimport cloneTypedArray from './_cloneTypedArray.js';\n\n/** `Object#toString` result references. */\nvar boolTag = '[object Boolean]',\n dateTag = '[object Date]',\n mapTag = '[object Map]',\n numberTag = '[object Number]',\n regexpTag = '[object RegExp]',\n setTag = '[object Set]',\n stringTag = '[object String]',\n symbolTag = '[object Symbol]';\n\nvar arrayBufferTag = '[object ArrayBuffer]',\n dataViewTag = '[object DataView]',\n float32Tag = '[object Float32Array]',\n float64Tag = '[object Float64Array]',\n int8Tag = '[object Int8Array]',\n int16Tag = '[object Int16Array]',\n int32Tag = '[object Int32Array]',\n uint8Tag = '[object Uint8Array]',\n uint8ClampedTag = '[object Uint8ClampedArray]',\n uint16Tag = '[object Uint16Array]',\n uint32Tag = '[object Uint32Array]';\n\n/**\n * Initializes an object clone based on its `toStringTag`.\n *\n * **Note:** This function only supports cloning values with tags of\n * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`.\n *\n * @private\n * @param {Object} object The object to clone.\n * @param {string} tag The `toStringTag` of the object to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Object} Returns the initialized clone.\n */\nfunction initCloneByTag(object, tag, isDeep) {\n var Ctor = object.constructor;\n switch (tag) {\n case arrayBufferTag:\n return cloneArrayBuffer(object);\n\n case boolTag:\n case dateTag:\n return new Ctor(+object);\n\n case dataViewTag:\n return cloneDataView(object, isDeep);\n\n case float32Tag: case float64Tag:\n case int8Tag: case int16Tag: case int32Tag:\n case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag:\n return cloneTypedArray(object, isDeep);\n\n case mapTag:\n return new Ctor;\n\n case numberTag:\n case stringTag:\n return new Ctor(object);\n\n case regexpTag:\n return cloneRegExp(object);\n\n case setTag:\n return new Ctor;\n\n case symbolTag:\n return cloneSymbol(object);\n }\n}\n\nexport default initCloneByTag;\n", "import baseCreate from './_baseCreate.js';\nimport getPrototype from './_getPrototype.js';\nimport isPrototype from './_isPrototype.js';\n\n/**\n * Initializes an object clone.\n *\n * @private\n * @param {Object} object The object to clone.\n * @returns {Object} Returns the initialized clone.\n */\nfunction initCloneObject(object) {\n return (typeof object.constructor == 'function' && !isPrototype(object))\n ? baseCreate(getPrototype(object))\n : {};\n}\n\nexport default initCloneObject;\n", "import getTag from './_getTag.js';\nimport isObjectLike from './isObjectLike.js';\n\n/** `Object#toString` result references. */\nvar mapTag = '[object Map]';\n\n/**\n * The base implementation of `_.isMap` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a map, else `false`.\n */\nfunction baseIsMap(value) {\n return isObjectLike(value) && getTag(value) == mapTag;\n}\n\nexport default baseIsMap;\n", "import baseIsMap from './_baseIsMap.js';\nimport baseUnary from './_baseUnary.js';\nimport nodeUtil from './_nodeUtil.js';\n\n/* Node.js helper references. */\nvar nodeIsMap = nodeUtil && nodeUtil.isMap;\n\n/**\n * Checks if `value` is classified as a `Map` object.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a map, else `false`.\n * @example\n *\n * _.isMap(new Map);\n * // => true\n *\n * _.isMap(new WeakMap);\n * // => false\n */\nvar isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap;\n\nexport default isMap;\n", "import getTag from './_getTag.js';\nimport isObjectLike from './isObjectLike.js';\n\n/** `Object#toString` result references. */\nvar setTag = '[object Set]';\n\n/**\n * The base implementation of `_.isSet` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a set, else `false`.\n */\nfunction baseIsSet(value) {\n return isObjectLike(value) && getTag(value) == setTag;\n}\n\nexport default baseIsSet;\n", "import baseIsSet from './_baseIsSet.js';\nimport baseUnary from './_baseUnary.js';\nimport nodeUtil from './_nodeUtil.js';\n\n/* Node.js helper references. */\nvar nodeIsSet = nodeUtil && nodeUtil.isSet;\n\n/**\n * Checks if `value` is classified as a `Set` object.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a set, else `false`.\n * @example\n *\n * _.isSet(new Set);\n * // => true\n *\n * _.isSet(new WeakSet);\n * // => false\n */\nvar isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet;\n\nexport default isSet;\n", "import Stack from './_Stack.js';\nimport arrayEach from './_arrayEach.js';\nimport assignValue from './_assignValue.js';\nimport baseAssign from './_baseAssign.js';\nimport baseAssignIn from './_baseAssignIn.js';\nimport cloneBuffer from './_cloneBuffer.js';\nimport copyArray from './_copyArray.js';\nimport copySymbols from './_copySymbols.js';\nimport copySymbolsIn from './_copySymbolsIn.js';\nimport getAllKeys from './_getAllKeys.js';\nimport getAllKeysIn from './_getAllKeysIn.js';\nimport getTag from './_getTag.js';\nimport initCloneArray from './_initCloneArray.js';\nimport initCloneByTag from './_initCloneByTag.js';\nimport initCloneObject from './_initCloneObject.js';\nimport isArray from './isArray.js';\nimport isBuffer from './isBuffer.js';\nimport isMap from './isMap.js';\nimport isObject from './isObject.js';\nimport isSet from './isSet.js';\nimport keys from './keys.js';\nimport keysIn from './keysIn.js';\n\n/** Used to compose bitmasks for cloning. */\nvar CLONE_DEEP_FLAG = 1,\n CLONE_FLAT_FLAG = 2,\n CLONE_SYMBOLS_FLAG = 4;\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]',\n arrayTag = '[object Array]',\n boolTag = '[object Boolean]',\n dateTag = '[object Date]',\n errorTag = '[object Error]',\n funcTag = '[object Function]',\n genTag = '[object GeneratorFunction]',\n mapTag = '[object Map]',\n numberTag = '[object Number]',\n objectTag = '[object Object]',\n regexpTag = '[object RegExp]',\n setTag = '[object Set]',\n stringTag = '[object String]',\n symbolTag = '[object Symbol]',\n weakMapTag = '[object WeakMap]';\n\nvar arrayBufferTag = '[object ArrayBuffer]',\n dataViewTag = '[object DataView]',\n float32Tag = '[object Float32Array]',\n float64Tag = '[object Float64Array]',\n int8Tag = '[object Int8Array]',\n int16Tag = '[object Int16Array]',\n int32Tag = '[object Int32Array]',\n uint8Tag = '[object Uint8Array]',\n uint8ClampedTag = '[object Uint8ClampedArray]',\n uint16Tag = '[object Uint16Array]',\n uint32Tag = '[object Uint32Array]';\n\n/** Used to identify `toStringTag` values supported by `_.clone`. */\nvar cloneableTags = {};\ncloneableTags[argsTag] = cloneableTags[arrayTag] =\ncloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] =\ncloneableTags[boolTag] = cloneableTags[dateTag] =\ncloneableTags[float32Tag] = cloneableTags[float64Tag] =\ncloneableTags[int8Tag] = cloneableTags[int16Tag] =\ncloneableTags[int32Tag] = cloneableTags[mapTag] =\ncloneableTags[numberTag] = cloneableTags[objectTag] =\ncloneableTags[regexpTag] = cloneableTags[setTag] =\ncloneableTags[stringTag] = cloneableTags[symbolTag] =\ncloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] =\ncloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true;\ncloneableTags[errorTag] = cloneableTags[funcTag] =\ncloneableTags[weakMapTag] = false;\n\n/**\n * The base implementation of `_.clone` and `_.cloneDeep` which tracks\n * traversed objects.\n *\n * @private\n * @param {*} value The value to clone.\n * @param {boolean} bitmask The bitmask flags.\n * 1 - Deep clone\n * 2 - Flatten inherited properties\n * 4 - Clone symbols\n * @param {Function} [customizer] The function to customize cloning.\n * @param {string} [key] The key of `value`.\n * @param {Object} [object] The parent object of `value`.\n * @param {Object} [stack] Tracks traversed objects and their clone counterparts.\n * @returns {*} Returns the cloned value.\n */\nfunction baseClone(value, bitmask, customizer, key, object, stack) {\n var result,\n isDeep = bitmask & CLONE_DEEP_FLAG,\n isFlat = bitmask & CLONE_FLAT_FLAG,\n isFull = bitmask & CLONE_SYMBOLS_FLAG;\n\n if (customizer) {\n result = object ? customizer(value, key, object, stack) : customizer(value);\n }\n if (result !== undefined) {\n return result;\n }\n if (!isObject(value)) {\n return value;\n }\n var isArr = isArray(value);\n if (isArr) {\n result = initCloneArray(value);\n if (!isDeep) {\n return copyArray(value, result);\n }\n } else {\n var tag = getTag(value),\n isFunc = tag == funcTag || tag == genTag;\n\n if (isBuffer(value)) {\n return cloneBuffer(value, isDeep);\n }\n if (tag == objectTag || tag == argsTag || (isFunc && !object)) {\n result = (isFlat || isFunc) ? {} : initCloneObject(value);\n if (!isDeep) {\n return isFlat\n ? copySymbolsIn(value, baseAssignIn(result, value))\n : copySymbols(value, baseAssign(result, value));\n }\n } else {\n if (!cloneableTags[tag]) {\n return object ? value : {};\n }\n result = initCloneByTag(value, tag, isDeep);\n }\n }\n // Check for circular references and return its corresponding clone.\n stack || (stack = new Stack);\n var stacked = stack.get(value);\n if (stacked) {\n return stacked;\n }\n stack.set(value, result);\n\n if (isSet(value)) {\n value.forEach(function(subValue) {\n result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack));\n });\n } else if (isMap(value)) {\n value.forEach(function(subValue, key) {\n result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack));\n });\n }\n\n var keysFunc = isFull\n ? (isFlat ? getAllKeysIn : getAllKeys)\n : (isFlat ? keysIn : keys);\n\n var props = isArr ? undefined : keysFunc(value);\n arrayEach(props || value, function(subValue, key) {\n if (props) {\n key = subValue;\n subValue = value[key];\n }\n // Recursively populate clone (susceptible to call stack limits).\n assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack));\n });\n return result;\n}\n\nexport default baseClone;\n", "import baseClone from './_baseClone.js';\n\n/** Used to compose bitmasks for cloning. */\nvar CLONE_DEEP_FLAG = 1,\n CLONE_SYMBOLS_FLAG = 4;\n\n/**\n * This method is like `_.clone` except that it recursively clones `value`.\n *\n * @static\n * @memberOf _\n * @since 1.0.0\n * @category Lang\n * @param {*} value The value to recursively clone.\n * @returns {*} Returns the deep cloned value.\n * @see _.clone\n * @example\n *\n * var objects = [{ 'a': 1 }, { 'b': 2 }];\n *\n * var deep = _.cloneDeep(objects);\n * console.log(deep[0] === objects[0]);\n * // => false\n */\nfunction cloneDeep(value) {\n return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG);\n}\n\nexport default cloneDeep;\n", "/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/**\n * Adds `value` to the array cache.\n *\n * @private\n * @name add\n * @memberOf SetCache\n * @alias push\n * @param {*} value The value to cache.\n * @returns {Object} Returns the cache instance.\n */\nfunction setCacheAdd(value) {\n this.__data__.set(value, HASH_UNDEFINED);\n return this;\n}\n\nexport default setCacheAdd;\n", "/**\n * Checks if `value` is in the array cache.\n *\n * @private\n * @name has\n * @memberOf SetCache\n * @param {*} value The value to search for.\n * @returns {number} Returns `true` if `value` is found, else `false`.\n */\nfunction setCacheHas(value) {\n return this.__data__.has(value);\n}\n\nexport default setCacheHas;\n", "import MapCache from './_MapCache.js';\nimport setCacheAdd from './_setCacheAdd.js';\nimport setCacheHas from './_setCacheHas.js';\n\n/**\n *\n * Creates an array cache object to store unique values.\n *\n * @private\n * @constructor\n * @param {Array} [values] The values to cache.\n */\nfunction SetCache(values) {\n var index = -1,\n length = values == null ? 0 : values.length;\n\n this.__data__ = new MapCache;\n while (++index < length) {\n this.add(values[index]);\n }\n}\n\n// Add methods to `SetCache`.\nSetCache.prototype.add = SetCache.prototype.push = setCacheAdd;\nSetCache.prototype.has = setCacheHas;\n\nexport default SetCache;\n", "/**\n * A specialized version of `_.some` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {boolean} Returns `true` if any element passes the predicate check,\n * else `false`.\n */\nfunction arraySome(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (predicate(array[index], index, array)) {\n return true;\n }\n }\n return false;\n}\n\nexport default arraySome;\n", "/**\n * Checks if a `cache` value for `key` exists.\n *\n * @private\n * @param {Object} cache The cache to query.\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction cacheHas(cache, key) {\n return cache.has(key);\n}\n\nexport default cacheHas;\n", "import SetCache from './_SetCache.js';\nimport arraySome from './_arraySome.js';\nimport cacheHas from './_cacheHas.js';\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1,\n COMPARE_UNORDERED_FLAG = 2;\n\n/**\n * A specialized version of `baseIsEqualDeep` for arrays with support for\n * partial deep comparisons.\n *\n * @private\n * @param {Array} array The array to compare.\n * @param {Array} other The other array to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `array` and `other` objects.\n * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.\n */\nfunction equalArrays(array, other, bitmask, customizer, equalFunc, stack) {\n var isPartial = bitmask & COMPARE_PARTIAL_FLAG,\n arrLength = array.length,\n othLength = other.length;\n\n if (arrLength != othLength && !(isPartial && othLength > arrLength)) {\n return false;\n }\n // Check that cyclic values are equal.\n var arrStacked = stack.get(array);\n var othStacked = stack.get(other);\n if (arrStacked && othStacked) {\n return arrStacked == other && othStacked == array;\n }\n var index = -1,\n result = true,\n seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined;\n\n stack.set(array, other);\n stack.set(other, array);\n\n // Ignore non-index properties.\n while (++index < arrLength) {\n var arrValue = array[index],\n othValue = other[index];\n\n if (customizer) {\n var compared = isPartial\n ? customizer(othValue, arrValue, index, other, array, stack)\n : customizer(arrValue, othValue, index, array, other, stack);\n }\n if (compared !== undefined) {\n if (compared) {\n continue;\n }\n result = false;\n break;\n }\n // Recursively compare arrays (susceptible to call stack limits).\n if (seen) {\n if (!arraySome(other, function(othValue, othIndex) {\n if (!cacheHas(seen, othIndex) &&\n (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {\n return seen.push(othIndex);\n }\n })) {\n result = false;\n break;\n }\n } else if (!(\n arrValue === othValue ||\n equalFunc(arrValue, othValue, bitmask, customizer, stack)\n )) {\n result = false;\n break;\n }\n }\n stack['delete'](array);\n stack['delete'](other);\n return result;\n}\n\nexport default equalArrays;\n", "/**\n * Converts `map` to its key-value pairs.\n *\n * @private\n * @param {Object} map The map to convert.\n * @returns {Array} Returns the key-value pairs.\n */\nfunction mapToArray(map) {\n var index = -1,\n result = Array(map.size);\n\n map.forEach(function(value, key) {\n result[++index] = [key, value];\n });\n return result;\n}\n\nexport default mapToArray;\n", "/**\n * Converts `set` to an array of its values.\n *\n * @private\n * @param {Object} set The set to convert.\n * @returns {Array} Returns the values.\n */\nfunction setToArray(set) {\n var index = -1,\n result = Array(set.size);\n\n set.forEach(function(value) {\n result[++index] = value;\n });\n return result;\n}\n\nexport default setToArray;\n", "import Symbol from './_Symbol.js';\nimport Uint8Array from './_Uint8Array.js';\nimport eq from './eq.js';\nimport equalArrays from './_equalArrays.js';\nimport mapToArray from './_mapToArray.js';\nimport setToArray from './_setToArray.js';\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1,\n COMPARE_UNORDERED_FLAG = 2;\n\n/** `Object#toString` result references. */\nvar boolTag = '[object Boolean]',\n dateTag = '[object Date]',\n errorTag = '[object Error]',\n mapTag = '[object Map]',\n numberTag = '[object Number]',\n regexpTag = '[object RegExp]',\n setTag = '[object Set]',\n stringTag = '[object String]',\n symbolTag = '[object Symbol]';\n\nvar arrayBufferTag = '[object ArrayBuffer]',\n dataViewTag = '[object DataView]';\n\n/** Used to convert symbols to primitives and strings. */\nvar symbolProto = Symbol ? Symbol.prototype : undefined,\n symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;\n\n/**\n * A specialized version of `baseIsEqualDeep` for comparing objects of\n * the same `toStringTag`.\n *\n * **Note:** This function only supports comparing values with tags of\n * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {string} tag The `toStringTag` of the objects to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\nfunction equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {\n switch (tag) {\n case dataViewTag:\n if ((object.byteLength != other.byteLength) ||\n (object.byteOffset != other.byteOffset)) {\n return false;\n }\n object = object.buffer;\n other = other.buffer;\n\n case arrayBufferTag:\n if ((object.byteLength != other.byteLength) ||\n !equalFunc(new Uint8Array(object), new Uint8Array(other))) {\n return false;\n }\n return true;\n\n case boolTag:\n case dateTag:\n case numberTag:\n // Coerce booleans to `1` or `0` and dates to milliseconds.\n // Invalid dates are coerced to `NaN`.\n return eq(+object, +other);\n\n case errorTag:\n return object.name == other.name && object.message == other.message;\n\n case regexpTag:\n case stringTag:\n // Coerce regexes to strings and treat strings, primitives and objects,\n // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring\n // for more details.\n return object == (other + '');\n\n case mapTag:\n var convert = mapToArray;\n\n case setTag:\n var isPartial = bitmask & COMPARE_PARTIAL_FLAG;\n convert || (convert = setToArray);\n\n if (object.size != other.size && !isPartial) {\n return false;\n }\n // Assume cyclic values are equal.\n var stacked = stack.get(object);\n if (stacked) {\n return stacked == other;\n }\n bitmask |= COMPARE_UNORDERED_FLAG;\n\n // Recursively compare objects (susceptible to call stack limits).\n stack.set(object, other);\n var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);\n stack['delete'](object);\n return result;\n\n case symbolTag:\n if (symbolValueOf) {\n return symbolValueOf.call(object) == symbolValueOf.call(other);\n }\n }\n return false;\n}\n\nexport default equalByTag;\n", "import getAllKeys from './_getAllKeys.js';\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1;\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * A specialized version of `baseIsEqualDeep` for objects with support for\n * partial deep comparisons.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\nfunction equalObjects(object, other, bitmask, customizer, equalFunc, stack) {\n var isPartial = bitmask & COMPARE_PARTIAL_FLAG,\n objProps = getAllKeys(object),\n objLength = objProps.length,\n othProps = getAllKeys(other),\n othLength = othProps.length;\n\n if (objLength != othLength && !isPartial) {\n return false;\n }\n var index = objLength;\n while (index--) {\n var key = objProps[index];\n if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) {\n return false;\n }\n }\n // Check that cyclic values are equal.\n var objStacked = stack.get(object);\n var othStacked = stack.get(other);\n if (objStacked && othStacked) {\n return objStacked == other && othStacked == object;\n }\n var result = true;\n stack.set(object, other);\n stack.set(other, object);\n\n var skipCtor = isPartial;\n while (++index < objLength) {\n key = objProps[index];\n var objValue = object[key],\n othValue = other[key];\n\n if (customizer) {\n var compared = isPartial\n ? customizer(othValue, objValue, key, other, object, stack)\n : customizer(objValue, othValue, key, object, other, stack);\n }\n // Recursively compare objects (susceptible to call stack limits).\n if (!(compared === undefined\n ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack))\n : compared\n )) {\n result = false;\n break;\n }\n skipCtor || (skipCtor = key == 'constructor');\n }\n if (result && !skipCtor) {\n var objCtor = object.constructor,\n othCtor = other.constructor;\n\n // Non `Object` object instances with different constructors are not equal.\n if (objCtor != othCtor &&\n ('constructor' in object && 'constructor' in other) &&\n !(typeof objCtor == 'function' && objCtor instanceof objCtor &&\n typeof othCtor == 'function' && othCtor instanceof othCtor)) {\n result = false;\n }\n }\n stack['delete'](object);\n stack['delete'](other);\n return result;\n}\n\nexport default equalObjects;\n", "import Stack from './_Stack.js';\nimport equalArrays from './_equalArrays.js';\nimport equalByTag from './_equalByTag.js';\nimport equalObjects from './_equalObjects.js';\nimport getTag from './_getTag.js';\nimport isArray from './isArray.js';\nimport isBuffer from './isBuffer.js';\nimport isTypedArray from './isTypedArray.js';\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1;\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]',\n arrayTag = '[object Array]',\n objectTag = '[object Object]';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * A specialized version of `baseIsEqual` for arrays and objects which performs\n * deep comparisons and tracks traversed objects enabling objects with circular\n * references to be compared.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} [stack] Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\nfunction baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {\n var objIsArr = isArray(object),\n othIsArr = isArray(other),\n objTag = objIsArr ? arrayTag : getTag(object),\n othTag = othIsArr ? arrayTag : getTag(other);\n\n objTag = objTag == argsTag ? objectTag : objTag;\n othTag = othTag == argsTag ? objectTag : othTag;\n\n var objIsObj = objTag == objectTag,\n othIsObj = othTag == objectTag,\n isSameTag = objTag == othTag;\n\n if (isSameTag && isBuffer(object)) {\n if (!isBuffer(other)) {\n return false;\n }\n objIsArr = true;\n objIsObj = false;\n }\n if (isSameTag && !objIsObj) {\n stack || (stack = new Stack);\n return (objIsArr || isTypedArray(object))\n ? equalArrays(object, other, bitmask, customizer, equalFunc, stack)\n : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);\n }\n if (!(bitmask & COMPARE_PARTIAL_FLAG)) {\n var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),\n othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');\n\n if (objIsWrapped || othIsWrapped) {\n var objUnwrapped = objIsWrapped ? object.value() : object,\n othUnwrapped = othIsWrapped ? other.value() : other;\n\n stack || (stack = new Stack);\n return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);\n }\n }\n if (!isSameTag) {\n return false;\n }\n stack || (stack = new Stack);\n return equalObjects(object, other, bitmask, customizer, equalFunc, stack);\n}\n\nexport default baseIsEqualDeep;\n", "import baseIsEqualDeep from './_baseIsEqualDeep.js';\nimport isObjectLike from './isObjectLike.js';\n\n/**\n * The base implementation of `_.isEqual` which supports partial comparisons\n * and tracks traversed objects.\n *\n * @private\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @param {boolean} bitmask The bitmask flags.\n * 1 - Unordered comparison\n * 2 - Partial comparison\n * @param {Function} [customizer] The function to customize comparisons.\n * @param {Object} [stack] Tracks traversed `value` and `other` objects.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n */\nfunction baseIsEqual(value, other, bitmask, customizer, stack) {\n if (value === other) {\n return true;\n }\n if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) {\n return value !== value && other !== other;\n }\n return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);\n}\n\nexport default baseIsEqual;\n", "import Stack from './_Stack.js';\nimport baseIsEqual from './_baseIsEqual.js';\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1,\n COMPARE_UNORDERED_FLAG = 2;\n\n/**\n * The base implementation of `_.isMatch` without support for iteratee shorthands.\n *\n * @private\n * @param {Object} object The object to inspect.\n * @param {Object} source The object of property values to match.\n * @param {Array} matchData The property names, values, and compare flags to match.\n * @param {Function} [customizer] The function to customize comparisons.\n * @returns {boolean} Returns `true` if `object` is a match, else `false`.\n */\nfunction baseIsMatch(object, source, matchData, customizer) {\n var index = matchData.length,\n length = index,\n noCustomizer = !customizer;\n\n if (object == null) {\n return !length;\n }\n object = Object(object);\n while (index--) {\n var data = matchData[index];\n if ((noCustomizer && data[2])\n ? data[1] !== object[data[0]]\n : !(data[0] in object)\n ) {\n return false;\n }\n }\n while (++index < length) {\n data = matchData[index];\n var key = data[0],\n objValue = object[key],\n srcValue = data[1];\n\n if (noCustomizer && data[2]) {\n if (objValue === undefined && !(key in object)) {\n return false;\n }\n } else {\n var stack = new Stack;\n if (customizer) {\n var result = customizer(objValue, srcValue, key, object, source, stack);\n }\n if (!(result === undefined\n ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack)\n : result\n )) {\n return false;\n }\n }\n }\n return true;\n}\n\nexport default baseIsMatch;\n", "import isObject from './isObject.js';\n\n/**\n * Checks if `value` is suitable for strict equality comparisons, i.e. `===`.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` if suitable for strict\n * equality comparisons, else `false`.\n */\nfunction isStrictComparable(value) {\n return value === value && !isObject(value);\n}\n\nexport default isStrictComparable;\n", "import isStrictComparable from './_isStrictComparable.js';\nimport keys from './keys.js';\n\n/**\n * Gets the property names, values, and compare flags of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the match data of `object`.\n */\nfunction getMatchData(object) {\n var result = keys(object),\n length = result.length;\n\n while (length--) {\n var key = result[length],\n value = object[key];\n\n result[length] = [key, value, isStrictComparable(value)];\n }\n return result;\n}\n\nexport default getMatchData;\n", "/**\n * A specialized version of `matchesProperty` for source values suitable\n * for strict equality comparisons, i.e. `===`.\n *\n * @private\n * @param {string} key The key of the property to get.\n * @param {*} srcValue The value to match.\n * @returns {Function} Returns the new spec function.\n */\nfunction matchesStrictComparable(key, srcValue) {\n return function(object) {\n if (object == null) {\n return false;\n }\n return object[key] === srcValue &&\n (srcValue !== undefined || (key in Object(object)));\n };\n}\n\nexport default matchesStrictComparable;\n", "import baseIsMatch from './_baseIsMatch.js';\nimport getMatchData from './_getMatchData.js';\nimport matchesStrictComparable from './_matchesStrictComparable.js';\n\n/**\n * The base implementation of `_.matches` which doesn't clone `source`.\n *\n * @private\n * @param {Object} source The object of property values to match.\n * @returns {Function} Returns the new spec function.\n */\nfunction baseMatches(source) {\n var matchData = getMatchData(source);\n if (matchData.length == 1 && matchData[0][2]) {\n return matchesStrictComparable(matchData[0][0], matchData[0][1]);\n }\n return function(object) {\n return object === source || baseIsMatch(object, source, matchData);\n };\n}\n\nexport default baseMatches;\n", "/**\n * The base implementation of `_.hasIn` without support for deep paths.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {Array|string} key The key to check.\n * @returns {boolean} Returns `true` if `key` exists, else `false`.\n */\nfunction baseHasIn(object, key) {\n return object != null && key in Object(object);\n}\n\nexport default baseHasIn;\n", "import castPath from './_castPath.js';\nimport isArguments from './isArguments.js';\nimport isArray from './isArray.js';\nimport isIndex from './_isIndex.js';\nimport isLength from './isLength.js';\nimport toKey from './_toKey.js';\n\n/**\n * Checks if `path` exists on `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Array|string} path The path to check.\n * @param {Function} hasFunc The function to check properties.\n * @returns {boolean} Returns `true` if `path` exists, else `false`.\n */\nfunction hasPath(object, path, hasFunc) {\n path = castPath(path, object);\n\n var index = -1,\n length = path.length,\n result = false;\n\n while (++index < length) {\n var key = toKey(path[index]);\n if (!(result = object != null && hasFunc(object, key))) {\n break;\n }\n object = object[key];\n }\n if (result || ++index != length) {\n return result;\n }\n length = object == null ? 0 : object.length;\n return !!length && isLength(length) && isIndex(key, length) &&\n (isArray(object) || isArguments(object));\n}\n\nexport default hasPath;\n", "import baseHasIn from './_baseHasIn.js';\nimport hasPath from './_hasPath.js';\n\n/**\n * Checks if `path` is a direct or inherited property of `object`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The object to query.\n * @param {Array|string} path The path to check.\n * @returns {boolean} Returns `true` if `path` exists, else `false`.\n * @example\n *\n * var object = _.create({ 'a': _.create({ 'b': 2 }) });\n *\n * _.hasIn(object, 'a');\n * // => true\n *\n * _.hasIn(object, 'a.b');\n * // => true\n *\n * _.hasIn(object, ['a', 'b']);\n * // => true\n *\n * _.hasIn(object, 'b');\n * // => false\n */\nfunction hasIn(object, path) {\n return object != null && hasPath(object, path, baseHasIn);\n}\n\nexport default hasIn;\n", "import baseIsEqual from './_baseIsEqual.js';\nimport get from './get.js';\nimport hasIn from './hasIn.js';\nimport isKey from './_isKey.js';\nimport isStrictComparable from './_isStrictComparable.js';\nimport matchesStrictComparable from './_matchesStrictComparable.js';\nimport toKey from './_toKey.js';\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1,\n COMPARE_UNORDERED_FLAG = 2;\n\n/**\n * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.\n *\n * @private\n * @param {string} path The path of the property to get.\n * @param {*} srcValue The value to match.\n * @returns {Function} Returns the new spec function.\n */\nfunction baseMatchesProperty(path, srcValue) {\n if (isKey(path) && isStrictComparable(srcValue)) {\n return matchesStrictComparable(toKey(path), srcValue);\n }\n return function(object) {\n var objValue = get(object, path);\n return (objValue === undefined && objValue === srcValue)\n ? hasIn(object, path)\n : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG);\n };\n}\n\nexport default baseMatchesProperty;\n", "/**\n * The base implementation of `_.property` without support for deep paths.\n *\n * @private\n * @param {string} key The key of the property to get.\n * @returns {Function} Returns the new accessor function.\n */\nfunction baseProperty(key) {\n return function(object) {\n return object == null ? undefined : object[key];\n };\n}\n\nexport default baseProperty;\n", "import baseGet from './_baseGet.js';\n\n/**\n * A specialized version of `baseProperty` which supports deep paths.\n *\n * @private\n * @param {Array|string} path The path of the property to get.\n * @returns {Function} Returns the new accessor function.\n */\nfunction basePropertyDeep(path) {\n return function(object) {\n return baseGet(object, path);\n };\n}\n\nexport default basePropertyDeep;\n", "import baseProperty from './_baseProperty.js';\nimport basePropertyDeep from './_basePropertyDeep.js';\nimport isKey from './_isKey.js';\nimport toKey from './_toKey.js';\n\n/**\n * Creates a function that returns the value at `path` of a given object.\n *\n * @static\n * @memberOf _\n * @since 2.4.0\n * @category Util\n * @param {Array|string} path The path of the property to get.\n * @returns {Function} Returns the new accessor function.\n * @example\n *\n * var objects = [\n * { 'a': { 'b': 2 } },\n * { 'a': { 'b': 1 } }\n * ];\n *\n * _.map(objects, _.property('a.b'));\n * // => [2, 1]\n *\n * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b');\n * // => [1, 2]\n */\nfunction property(path) {\n return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path);\n}\n\nexport default property;\n", "import baseMatches from './_baseMatches.js';\nimport baseMatchesProperty from './_baseMatchesProperty.js';\nimport identity from './identity.js';\nimport isArray from './isArray.js';\nimport property from './property.js';\n\n/**\n * The base implementation of `_.iteratee`.\n *\n * @private\n * @param {*} [value=_.identity] The value to convert to an iteratee.\n * @returns {Function} Returns the iteratee.\n */\nfunction baseIteratee(value) {\n // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9.\n // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details.\n if (typeof value == 'function') {\n return value;\n }\n if (value == null) {\n return identity;\n }\n if (typeof value == 'object') {\n return isArray(value)\n ? baseMatchesProperty(value[0], value[1])\n : baseMatches(value);\n }\n return property(value);\n}\n\nexport default baseIteratee;\n", "/**\n * Creates a base function for methods like `_.forIn` and `_.forOwn`.\n *\n * @private\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {Function} Returns the new base function.\n */\nfunction createBaseFor(fromRight) {\n return function(object, iteratee, keysFunc) {\n var index = -1,\n iterable = Object(object),\n props = keysFunc(object),\n length = props.length;\n\n while (length--) {\n var key = props[fromRight ? length : ++index];\n if (iteratee(iterable[key], key, iterable) === false) {\n break;\n }\n }\n return object;\n };\n}\n\nexport default createBaseFor;\n", "import createBaseFor from './_createBaseFor.js';\n\n/**\n * The base implementation of `baseForOwn` which iterates over `object`\n * properties returned by `keysFunc` and invokes `iteratee` for each property.\n * Iteratee functions may exit iteration early by explicitly returning `false`.\n *\n * @private\n * @param {Object} object The object to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @param {Function} keysFunc The function to get the keys of `object`.\n * @returns {Object} Returns `object`.\n */\nvar baseFor = createBaseFor();\n\nexport default baseFor;\n", "import baseFor from './_baseFor.js';\nimport keys from './keys.js';\n\n/**\n * The base implementation of `_.forOwn` without support for iteratee shorthands.\n *\n * @private\n * @param {Object} object The object to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Object} Returns `object`.\n */\nfunction baseForOwn(object, iteratee) {\n return object && baseFor(object, iteratee, keys);\n}\n\nexport default baseForOwn;\n", "import root from './_root.js';\n\n/**\n * Gets the timestamp of the number of milliseconds that have elapsed since\n * the Unix epoch (1 January 1970 00:00:00 UTC).\n *\n * @static\n * @memberOf _\n * @since 2.4.0\n * @category Date\n * @returns {number} Returns the timestamp.\n * @example\n *\n * _.defer(function(stamp) {\n * console.log(_.now() - stamp);\n * }, _.now());\n * // => Logs the number of milliseconds it took for the deferred invocation.\n */\nvar now = function() {\n return root.Date.now();\n};\n\nexport default now;\n", "import isObject from './isObject.js';\nimport now from './now.js';\nimport toNumber from './toNumber.js';\n\n/** Error message constants. */\nvar FUNC_ERROR_TEXT = 'Expected a function';\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeMax = Math.max,\n nativeMin = Math.min;\n\n/**\n * Creates a debounced function that delays invoking `func` until after `wait`\n * milliseconds have elapsed since the last time the debounced function was\n * invoked. The debounced function comes with a `cancel` method to cancel\n * delayed `func` invocations and a `flush` method to immediately invoke them.\n * Provide `options` to indicate whether `func` should be invoked on the\n * leading and/or trailing edge of the `wait` timeout. The `func` is invoked\n * with the last arguments provided to the debounced function. Subsequent\n * calls to the debounced function return the result of the last `func`\n * invocation.\n *\n * **Note:** If `leading` and `trailing` options are `true`, `func` is\n * invoked on the trailing edge of the timeout only if the debounced function\n * is invoked more than once during the `wait` timeout.\n *\n * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred\n * until to the next tick, similar to `setTimeout` with a timeout of `0`.\n *\n * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)\n * for details over the differences between `_.debounce` and `_.throttle`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to debounce.\n * @param {number} [wait=0] The number of milliseconds to delay.\n * @param {Object} [options={}] The options object.\n * @param {boolean} [options.leading=false]\n * Specify invoking on the leading edge of the timeout.\n * @param {number} [options.maxWait]\n * The maximum time `func` is allowed to be delayed before it's invoked.\n * @param {boolean} [options.trailing=true]\n * Specify invoking on the trailing edge of the timeout.\n * @returns {Function} Returns the new debounced function.\n * @example\n *\n * // Avoid costly calculations while the window size is in flux.\n * jQuery(window).on('resize', _.debounce(calculateLayout, 150));\n *\n * // Invoke `sendMail` when clicked, debouncing subsequent calls.\n * jQuery(element).on('click', _.debounce(sendMail, 300, {\n * 'leading': true,\n * 'trailing': false\n * }));\n *\n * // Ensure `batchLog` is invoked once after 1 second of debounced calls.\n * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });\n * var source = new EventSource('/stream');\n * jQuery(source).on('message', debounced);\n *\n * // Cancel the trailing debounced invocation.\n * jQuery(window).on('popstate', debounced.cancel);\n */\nfunction debounce(func, wait, options) {\n var lastArgs,\n lastThis,\n maxWait,\n result,\n timerId,\n lastCallTime,\n lastInvokeTime = 0,\n leading = false,\n maxing = false,\n trailing = true;\n\n if (typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n wait = toNumber(wait) || 0;\n if (isObject(options)) {\n leading = !!options.leading;\n maxing = 'maxWait' in options;\n maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait;\n trailing = 'trailing' in options ? !!options.trailing : trailing;\n }\n\n function invokeFunc(time) {\n var args = lastArgs,\n thisArg = lastThis;\n\n lastArgs = lastThis = undefined;\n lastInvokeTime = time;\n result = func.apply(thisArg, args);\n return result;\n }\n\n function leadingEdge(time) {\n // Reset any `maxWait` timer.\n lastInvokeTime = time;\n // Start the timer for the trailing edge.\n timerId = setTimeout(timerExpired, wait);\n // Invoke the leading edge.\n return leading ? invokeFunc(time) : result;\n }\n\n function remainingWait(time) {\n var timeSinceLastCall = time - lastCallTime,\n timeSinceLastInvoke = time - lastInvokeTime,\n timeWaiting = wait - timeSinceLastCall;\n\n return maxing\n ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke)\n : timeWaiting;\n }\n\n function shouldInvoke(time) {\n var timeSinceLastCall = time - lastCallTime,\n timeSinceLastInvoke = time - lastInvokeTime;\n\n // Either this is the first call, activity has stopped and we're at the\n // trailing edge, the system time has gone backwards and we're treating\n // it as the trailing edge, or we've hit the `maxWait` limit.\n return (lastCallTime === undefined || (timeSinceLastCall >= wait) ||\n (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait));\n }\n\n function timerExpired() {\n var time = now();\n if (shouldInvoke(time)) {\n return trailingEdge(time);\n }\n // Restart the timer.\n timerId = setTimeout(timerExpired, remainingWait(time));\n }\n\n function trailingEdge(time) {\n timerId = undefined;\n\n // Only invoke if we have `lastArgs` which means `func` has been\n // debounced at least once.\n if (trailing && lastArgs) {\n return invokeFunc(time);\n }\n lastArgs = lastThis = undefined;\n return result;\n }\n\n function cancel() {\n if (timerId !== undefined) {\n clearTimeout(timerId);\n }\n lastInvokeTime = 0;\n lastArgs = lastCallTime = lastThis = timerId = undefined;\n }\n\n function flush() {\n return timerId === undefined ? result : trailingEdge(now());\n }\n\n function debounced() {\n var time = now(),\n isInvoking = shouldInvoke(time);\n\n lastArgs = arguments;\n lastThis = this;\n lastCallTime = time;\n\n if (isInvoking) {\n if (timerId === undefined) {\n return leadingEdge(lastCallTime);\n }\n if (maxing) {\n // Handle invocations in a tight loop.\n clearTimeout(timerId);\n timerId = setTimeout(timerExpired, wait);\n return invokeFunc(lastCallTime);\n }\n }\n if (timerId === undefined) {\n timerId = setTimeout(timerExpired, wait);\n }\n return result;\n }\n debounced.cancel = cancel;\n debounced.flush = flush;\n return debounced;\n}\n\nexport default debounce;\n", "import baseGet from './_baseGet.js';\nimport baseSlice from './_baseSlice.js';\n\n/**\n * Gets the parent value at `path` of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Array} path The path to get the parent value of.\n * @returns {*} Returns the parent value.\n */\nfunction parent(object, path) {\n return path.length < 2 ? object : baseGet(object, baseSlice(path, 0, -1));\n}\n\nexport default parent;\n", "import toInteger from './toInteger.js';\n\n/**\n * Checks if `value` is an integer.\n *\n * **Note:** This method is based on\n * [`Number.isInteger`](https://mdn.io/Number/isInteger).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an integer, else `false`.\n * @example\n *\n * _.isInteger(3);\n * // => true\n *\n * _.isInteger(Number.MIN_VALUE);\n * // => false\n *\n * _.isInteger(Infinity);\n * // => false\n *\n * _.isInteger('3');\n * // => false\n */\nfunction isInteger(value) {\n return typeof value == 'number' && value == toInteger(value);\n}\n\nexport default isInteger;\n", "import baseAssignValue from './_baseAssignValue.js';\nimport baseForOwn from './_baseForOwn.js';\nimport baseIteratee from './_baseIteratee.js';\n\n/**\n * Creates an object with the same keys as `object` and values generated\n * by running each own enumerable string keyed property of `object` thru\n * `iteratee`. The iteratee is invoked with three arguments:\n * (value, key, object).\n *\n * @static\n * @memberOf _\n * @since 2.4.0\n * @category Object\n * @param {Object} object The object to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @returns {Object} Returns the new mapped object.\n * @see _.mapKeys\n * @example\n *\n * var users = {\n * 'fred': { 'user': 'fred', 'age': 40 },\n * 'pebbles': { 'user': 'pebbles', 'age': 1 }\n * };\n *\n * _.mapValues(users, function(o) { return o.age; });\n * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)\n *\n * // The `_.property` iteratee shorthand.\n * _.mapValues(users, 'age');\n * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)\n */\nfunction mapValues(object, iteratee) {\n var result = {};\n iteratee = baseIteratee(iteratee, 3);\n\n baseForOwn(object, function(value, key, object) {\n baseAssignValue(result, key, iteratee(value, key, object));\n });\n return result;\n}\n\nexport default mapValues;\n", "import castPath from './_castPath.js';\nimport last from './last.js';\nimport parent from './_parent.js';\nimport toKey from './_toKey.js';\n\n/**\n * The base implementation of `_.unset`.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {Array|string} path The property path to unset.\n * @returns {boolean} Returns `true` if the property is deleted, else `false`.\n */\nfunction baseUnset(object, path) {\n path = castPath(path, object);\n object = parent(object, path);\n return object == null || delete object[toKey(last(path))];\n}\n\nexport default baseUnset;\n", "/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeFloor = Math.floor;\n\n/**\n * The base implementation of `_.repeat` which doesn't coerce arguments.\n *\n * @private\n * @param {string} string The string to repeat.\n * @param {number} n The number of times to repeat the string.\n * @returns {string} Returns the repeated string.\n */\nfunction baseRepeat(string, n) {\n var result = '';\n if (!string || n < 1 || n > MAX_SAFE_INTEGER) {\n return result;\n }\n // Leverage the exponentiation by squaring algorithm for a faster repeat.\n // See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details.\n do {\n if (n % 2) {\n result += string;\n }\n n = nativeFloor(n / 2);\n if (n) {\n string += string;\n }\n } while (n);\n\n return result;\n}\n\nexport default baseRepeat;\n", "import baseProperty from './_baseProperty.js';\n\n/**\n * Gets the size of an ASCII `string`.\n *\n * @private\n * @param {string} string The string inspect.\n * @returns {number} Returns the string size.\n */\nvar asciiSize = baseProperty('length');\n\nexport default asciiSize;\n", "/** Used to compose unicode character classes. */\nvar rsAstralRange = '\\\\ud800-\\\\udfff',\n rsComboMarksRange = '\\\\u0300-\\\\u036f',\n reComboHalfMarksRange = '\\\\ufe20-\\\\ufe2f',\n rsComboSymbolsRange = '\\\\u20d0-\\\\u20ff',\n rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,\n rsVarRange = '\\\\ufe0e\\\\ufe0f';\n\n/** Used to compose unicode capture groups. */\nvar rsAstral = '[' + rsAstralRange + ']',\n rsCombo = '[' + rsComboRange + ']',\n rsFitz = '\\\\ud83c[\\\\udffb-\\\\udfff]',\n rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',\n rsNonAstral = '[^' + rsAstralRange + ']',\n rsRegional = '(?:\\\\ud83c[\\\\udde6-\\\\uddff]){2}',\n rsSurrPair = '[\\\\ud800-\\\\udbff][\\\\udc00-\\\\udfff]',\n rsZWJ = '\\\\u200d';\n\n/** Used to compose unicode regexes. */\nvar reOptMod = rsModifier + '?',\n rsOptVar = '[' + rsVarRange + ']?',\n rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',\n rsSeq = rsOptVar + reOptMod + rsOptJoin,\n rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';\n\n/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */\nvar reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');\n\n/**\n * Gets the size of a Unicode `string`.\n *\n * @private\n * @param {string} string The string inspect.\n * @returns {number} Returns the string size.\n */\nfunction unicodeSize(string) {\n var result = reUnicode.lastIndex = 0;\n while (reUnicode.test(string)) {\n ++result;\n }\n return result;\n}\n\nexport default unicodeSize;\n", "import asciiSize from './_asciiSize.js';\nimport hasUnicode from './_hasUnicode.js';\nimport unicodeSize from './_unicodeSize.js';\n\n/**\n * Gets the number of symbols in `string`.\n *\n * @private\n * @param {string} string The string to inspect.\n * @returns {number} Returns the string size.\n */\nfunction stringSize(string) {\n return hasUnicode(string)\n ? unicodeSize(string)\n : asciiSize(string);\n}\n\nexport default stringSize;\n", "import baseRepeat from './_baseRepeat.js';\nimport baseToString from './_baseToString.js';\nimport castSlice from './_castSlice.js';\nimport hasUnicode from './_hasUnicode.js';\nimport stringSize from './_stringSize.js';\nimport stringToArray from './_stringToArray.js';\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeCeil = Math.ceil;\n\n/**\n * Creates the padding for `string` based on `length`. The `chars` string\n * is truncated if the number of characters exceeds `length`.\n *\n * @private\n * @param {number} length The padding length.\n * @param {string} [chars=' '] The string used as padding.\n * @returns {string} Returns the padding for `string`.\n */\nfunction createPadding(length, chars) {\n chars = chars === undefined ? ' ' : baseToString(chars);\n\n var charsLength = chars.length;\n if (charsLength < 2) {\n return charsLength ? baseRepeat(chars, length) : chars;\n }\n var result = baseRepeat(chars, nativeCeil(length / stringSize(chars)));\n return hasUnicode(chars)\n ? castSlice(stringToArray(result), 0, length).join('')\n : result.slice(0, length);\n}\n\nexport default createPadding;\n", "import createPadding from './_createPadding.js';\nimport stringSize from './_stringSize.js';\nimport toInteger from './toInteger.js';\nimport toString from './toString.js';\n\n/**\n * Pads `string` on the left side if it's shorter than `length`. Padding\n * characters are truncated if they exceed `length`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category String\n * @param {string} [string=''] The string to pad.\n * @param {number} [length=0] The padding length.\n * @param {string} [chars=' '] The string used as padding.\n * @returns {string} Returns the padded string.\n * @example\n *\n * _.padStart('abc', 6);\n * // => ' abc'\n *\n * _.padStart('abc', 6, '_-');\n * // => '_-_abc'\n *\n * _.padStart('abc', 3);\n * // => 'abc'\n */\nfunction padStart(string, length, chars) {\n string = toString(string);\n length = toInteger(length);\n\n var strLength = length ? stringSize(string) : 0;\n return (length && strLength < length)\n ? (createPadding(length - strLength, chars) + string)\n : string;\n}\n\nexport default padStart;\n", "import baseUnset from './_baseUnset.js';\n\n/**\n * Removes the property at `path` of `object`.\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The object to modify.\n * @param {Array|string} path The path of the property to unset.\n * @returns {boolean} Returns `true` if the property is deleted, else `false`.\n * @example\n *\n * var object = { 'a': [{ 'b': { 'c': 7 } }] };\n * _.unset(object, 'a[0].b.c');\n * // => true\n *\n * console.log(object);\n * // => { 'a': [{ 'b': {} }] };\n *\n * _.unset(object, ['a', '0', 'b', 'c']);\n * // => true\n *\n * console.log(object);\n * // => { 'a': [{ 'b': {} }] };\n */\nfunction unset(object, path) {\n return object == null ? true : baseUnset(object, path);\n}\n\nexport default unset;\n", "/**\n * @license\n * Lodash (Custom Build) \n * Build: `lodash modularize exports=\"es\" -o ./`\n * Copyright OpenJS Foundation and other contributors \n * Released under MIT license \n * Based on Underscore.js 1.8.3 \n * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors\n */\nexport { default as add } from './add.js';\nexport { default as after } from './after.js';\nexport { default as ary } from './ary.js';\nexport { default as assign } from './assign.js';\nexport { default as assignIn } from './assignIn.js';\nexport { default as assignInWith } from './assignInWith.js';\nexport { default as assignWith } from './assignWith.js';\nexport { default as at } from './at.js';\nexport { default as attempt } from './attempt.js';\nexport { default as before } from './before.js';\nexport { default as bind } from './bind.js';\nexport { default as bindAll } from './bindAll.js';\nexport { default as bindKey } from './bindKey.js';\nexport { default as camelCase } from './camelCase.js';\nexport { default as capitalize } from './capitalize.js';\nexport { default as castArray } from './castArray.js';\nexport { default as ceil } from './ceil.js';\nexport { default as chain } from './chain.js';\nexport { default as chunk } from './chunk.js';\nexport { default as clamp } from './clamp.js';\nexport { default as clone } from './clone.js';\nexport { default as cloneDeep } from './cloneDeep.js';\nexport { default as cloneDeepWith } from './cloneDeepWith.js';\nexport { default as cloneWith } from './cloneWith.js';\nexport { default as commit } from './commit.js';\nexport { default as compact } from './compact.js';\nexport { default as concat } from './concat.js';\nexport { default as cond } from './cond.js';\nexport { default as conforms } from './conforms.js';\nexport { default as conformsTo } from './conformsTo.js';\nexport { default as constant } from './constant.js';\nexport { default as countBy } from './countBy.js';\nexport { default as create } from './create.js';\nexport { default as curry } from './curry.js';\nexport { default as curryRight } from './curryRight.js';\nexport { default as debounce } from './debounce.js';\nexport { default as deburr } from './deburr.js';\nexport { default as defaultTo } from './defaultTo.js';\nexport { default as defaults } from './defaults.js';\nexport { default as defaultsDeep } from './defaultsDeep.js';\nexport { default as defer } from './defer.js';\nexport { default as delay } from './delay.js';\nexport { default as difference } from './difference.js';\nexport { default as differenceBy } from './differenceBy.js';\nexport { default as differenceWith } from './differenceWith.js';\nexport { default as divide } from './divide.js';\nexport { default as drop } from './drop.js';\nexport { default as dropRight } from './dropRight.js';\nexport { default as dropRightWhile } from './dropRightWhile.js';\nexport { default as dropWhile } from './dropWhile.js';\nexport { default as each } from './each.js';\nexport { default as eachRight } from './eachRight.js';\nexport { default as endsWith } from './endsWith.js';\nexport { default as entries } from './entries.js';\nexport { default as entriesIn } from './entriesIn.js';\nexport { default as eq } from './eq.js';\nexport { default as escape } from './escape.js';\nexport { default as escapeRegExp } from './escapeRegExp.js';\nexport { default as every } from './every.js';\nexport { default as extend } from './extend.js';\nexport { default as extendWith } from './extendWith.js';\nexport { default as fill } from './fill.js';\nexport { default as filter } from './filter.js';\nexport { default as find } from './find.js';\nexport { default as findIndex } from './findIndex.js';\nexport { default as findKey } from './findKey.js';\nexport { default as findLast } from './findLast.js';\nexport { default as findLastIndex } from './findLastIndex.js';\nexport { default as findLastKey } from './findLastKey.js';\nexport { default as first } from './first.js';\nexport { default as flatMap } from './flatMap.js';\nexport { default as flatMapDeep } from './flatMapDeep.js';\nexport { default as flatMapDepth } from './flatMapDepth.js';\nexport { default as flatten } from './flatten.js';\nexport { default as flattenDeep } from './flattenDeep.js';\nexport { default as flattenDepth } from './flattenDepth.js';\nexport { default as flip } from './flip.js';\nexport { default as floor } from './floor.js';\nexport { default as flow } from './flow.js';\nexport { default as flowRight } from './flowRight.js';\nexport { default as forEach } from './forEach.js';\nexport { default as forEachRight } from './forEachRight.js';\nexport { default as forIn } from './forIn.js';\nexport { default as forInRight } from './forInRight.js';\nexport { default as forOwn } from './forOwn.js';\nexport { default as forOwnRight } from './forOwnRight.js';\nexport { default as fromPairs } from './fromPairs.js';\nexport { default as functions } from './functions.js';\nexport { default as functionsIn } from './functionsIn.js';\nexport { default as get } from './get.js';\nexport { default as groupBy } from './groupBy.js';\nexport { default as gt } from './gt.js';\nexport { default as gte } from './gte.js';\nexport { default as has } from './has.js';\nexport { default as hasIn } from './hasIn.js';\nexport { default as head } from './head.js';\nexport { default as identity } from './identity.js';\nexport { default as inRange } from './inRange.js';\nexport { default as includes } from './includes.js';\nexport { default as indexOf } from './indexOf.js';\nexport { default as initial } from './initial.js';\nexport { default as intersection } from './intersection.js';\nexport { default as intersectionBy } from './intersectionBy.js';\nexport { default as intersectionWith } from './intersectionWith.js';\nexport { default as invert } from './invert.js';\nexport { default as invertBy } from './invertBy.js';\nexport { default as invoke } from './invoke.js';\nexport { default as invokeMap } from './invokeMap.js';\nexport { default as isArguments } from './isArguments.js';\nexport { default as isArray } from './isArray.js';\nexport { default as isArrayBuffer } from './isArrayBuffer.js';\nexport { default as isArrayLike } from './isArrayLike.js';\nexport { default as isArrayLikeObject } from './isArrayLikeObject.js';\nexport { default as isBoolean } from './isBoolean.js';\nexport { default as isBuffer } from './isBuffer.js';\nexport { default as isDate } from './isDate.js';\nexport { default as isElement } from './isElement.js';\nexport { default as isEmpty } from './isEmpty.js';\nexport { default as isEqual } from './isEqual.js';\nexport { default as isEqualWith } from './isEqualWith.js';\nexport { default as isError } from './isError.js';\nexport { default as isFinite } from './isFinite.js';\nexport { default as isFunction } from './isFunction.js';\nexport { default as isInteger } from './isInteger.js';\nexport { default as isLength } from './isLength.js';\nexport { default as isMap } from './isMap.js';\nexport { default as isMatch } from './isMatch.js';\nexport { default as isMatchWith } from './isMatchWith.js';\nexport { default as isNaN } from './isNaN.js';\nexport { default as isNative } from './isNative.js';\nexport { default as isNil } from './isNil.js';\nexport { default as isNull } from './isNull.js';\nexport { default as isNumber } from './isNumber.js';\nexport { default as isObject } from './isObject.js';\nexport { default as isObjectLike } from './isObjectLike.js';\nexport { default as isPlainObject } from './isPlainObject.js';\nexport { default as isRegExp } from './isRegExp.js';\nexport { default as isSafeInteger } from './isSafeInteger.js';\nexport { default as isSet } from './isSet.js';\nexport { default as isString } from './isString.js';\nexport { default as isSymbol } from './isSymbol.js';\nexport { default as isTypedArray } from './isTypedArray.js';\nexport { default as isUndefined } from './isUndefined.js';\nexport { default as isWeakMap } from './isWeakMap.js';\nexport { default as isWeakSet } from './isWeakSet.js';\nexport { default as iteratee } from './iteratee.js';\nexport { default as join } from './join.js';\nexport { default as kebabCase } from './kebabCase.js';\nexport { default as keyBy } from './keyBy.js';\nexport { default as keys } from './keys.js';\nexport { default as keysIn } from './keysIn.js';\nexport { default as last } from './last.js';\nexport { default as lastIndexOf } from './lastIndexOf.js';\nexport { default as lodash } from './wrapperLodash.js';\nexport { default as lowerCase } from './lowerCase.js';\nexport { default as lowerFirst } from './lowerFirst.js';\nexport { default as lt } from './lt.js';\nexport { default as lte } from './lte.js';\nexport { default as map } from './map.js';\nexport { default as mapKeys } from './mapKeys.js';\nexport { default as mapValues } from './mapValues.js';\nexport { default as matches } from './matches.js';\nexport { default as matchesProperty } from './matchesProperty.js';\nexport { default as max } from './max.js';\nexport { default as maxBy } from './maxBy.js';\nexport { default as mean } from './mean.js';\nexport { default as meanBy } from './meanBy.js';\nexport { default as memoize } from './memoize.js';\nexport { default as merge } from './merge.js';\nexport { default as mergeWith } from './mergeWith.js';\nexport { default as method } from './method.js';\nexport { default as methodOf } from './methodOf.js';\nexport { default as min } from './min.js';\nexport { default as minBy } from './minBy.js';\nexport { default as mixin } from './mixin.js';\nexport { default as multiply } from './multiply.js';\nexport { default as negate } from './negate.js';\nexport { default as next } from './next.js';\nexport { default as noop } from './noop.js';\nexport { default as now } from './now.js';\nexport { default as nth } from './nth.js';\nexport { default as nthArg } from './nthArg.js';\nexport { default as omit } from './omit.js';\nexport { default as omitBy } from './omitBy.js';\nexport { default as once } from './once.js';\nexport { default as orderBy } from './orderBy.js';\nexport { default as over } from './over.js';\nexport { default as overArgs } from './overArgs.js';\nexport { default as overEvery } from './overEvery.js';\nexport { default as overSome } from './overSome.js';\nexport { default as pad } from './pad.js';\nexport { default as padEnd } from './padEnd.js';\nexport { default as padStart } from './padStart.js';\nexport { default as parseInt } from './parseInt.js';\nexport { default as partial } from './partial.js';\nexport { default as partialRight } from './partialRight.js';\nexport { default as partition } from './partition.js';\nexport { default as pick } from './pick.js';\nexport { default as pickBy } from './pickBy.js';\nexport { default as plant } from './plant.js';\nexport { default as property } from './property.js';\nexport { default as propertyOf } from './propertyOf.js';\nexport { default as pull } from './pull.js';\nexport { default as pullAll } from './pullAll.js';\nexport { default as pullAllBy } from './pullAllBy.js';\nexport { default as pullAllWith } from './pullAllWith.js';\nexport { default as pullAt } from './pullAt.js';\nexport { default as random } from './random.js';\nexport { default as range } from './range.js';\nexport { default as rangeRight } from './rangeRight.js';\nexport { default as rearg } from './rearg.js';\nexport { default as reduce } from './reduce.js';\nexport { default as reduceRight } from './reduceRight.js';\nexport { default as reject } from './reject.js';\nexport { default as remove } from './remove.js';\nexport { default as repeat } from './repeat.js';\nexport { default as replace } from './replace.js';\nexport { default as rest } from './rest.js';\nexport { default as result } from './result.js';\nexport { default as reverse } from './reverse.js';\nexport { default as round } from './round.js';\nexport { default as sample } from './sample.js';\nexport { default as sampleSize } from './sampleSize.js';\nexport { default as set } from './set.js';\nexport { default as setWith } from './setWith.js';\nexport { default as shuffle } from './shuffle.js';\nexport { default as size } from './size.js';\nexport { default as slice } from './slice.js';\nexport { default as snakeCase } from './snakeCase.js';\nexport { default as some } from './some.js';\nexport { default as sortBy } from './sortBy.js';\nexport { default as sortedIndex } from './sortedIndex.js';\nexport { default as sortedIndexBy } from './sortedIndexBy.js';\nexport { default as sortedIndexOf } from './sortedIndexOf.js';\nexport { default as sortedLastIndex } from './sortedLastIndex.js';\nexport { default as sortedLastIndexBy } from './sortedLastIndexBy.js';\nexport { default as sortedLastIndexOf } from './sortedLastIndexOf.js';\nexport { default as sortedUniq } from './sortedUniq.js';\nexport { default as sortedUniqBy } from './sortedUniqBy.js';\nexport { default as split } from './split.js';\nexport { default as spread } from './spread.js';\nexport { default as startCase } from './startCase.js';\nexport { default as startsWith } from './startsWith.js';\nexport { default as stubArray } from './stubArray.js';\nexport { default as stubFalse } from './stubFalse.js';\nexport { default as stubObject } from './stubObject.js';\nexport { default as stubString } from './stubString.js';\nexport { default as stubTrue } from './stubTrue.js';\nexport { default as subtract } from './subtract.js';\nexport { default as sum } from './sum.js';\nexport { default as sumBy } from './sumBy.js';\nexport { default as tail } from './tail.js';\nexport { default as take } from './take.js';\nexport { default as takeRight } from './takeRight.js';\nexport { default as takeRightWhile } from './takeRightWhile.js';\nexport { default as takeWhile } from './takeWhile.js';\nexport { default as tap } from './tap.js';\nexport { default as template } from './template.js';\nexport { default as templateSettings } from './templateSettings.js';\nexport { default as throttle } from './throttle.js';\nexport { default as thru } from './thru.js';\nexport { default as times } from './times.js';\nexport { default as toArray } from './toArray.js';\nexport { default as toFinite } from './toFinite.js';\nexport { default as toInteger } from './toInteger.js';\nexport { default as toIterator } from './toIterator.js';\nexport { default as toJSON } from './toJSON.js';\nexport { default as toLength } from './toLength.js';\nexport { default as toLower } from './toLower.js';\nexport { default as toNumber } from './toNumber.js';\nexport { default as toPairs } from './toPairs.js';\nexport { default as toPairsIn } from './toPairsIn.js';\nexport { default as toPath } from './toPath.js';\nexport { default as toPlainObject } from './toPlainObject.js';\nexport { default as toSafeInteger } from './toSafeInteger.js';\nexport { default as toString } from './toString.js';\nexport { default as toUpper } from './toUpper.js';\nexport { default as transform } from './transform.js';\nexport { default as trim } from './trim.js';\nexport { default as trimEnd } from './trimEnd.js';\nexport { default as trimStart } from './trimStart.js';\nexport { default as truncate } from './truncate.js';\nexport { default as unary } from './unary.js';\nexport { default as unescape } from './unescape.js';\nexport { default as union } from './union.js';\nexport { default as unionBy } from './unionBy.js';\nexport { default as unionWith } from './unionWith.js';\nexport { default as uniq } from './uniq.js';\nexport { default as uniqBy } from './uniqBy.js';\nexport { default as uniqWith } from './uniqWith.js';\nexport { default as uniqueId } from './uniqueId.js';\nexport { default as unset } from './unset.js';\nexport { default as unzip } from './unzip.js';\nexport { default as unzipWith } from './unzipWith.js';\nexport { default as update } from './update.js';\nexport { default as updateWith } from './updateWith.js';\nexport { default as upperCase } from './upperCase.js';\nexport { default as upperFirst } from './upperFirst.js';\nexport { default as value } from './value.js';\nexport { default as valueOf } from './valueOf.js';\nexport { default as values } from './values.js';\nexport { default as valuesIn } from './valuesIn.js';\nexport { default as without } from './without.js';\nexport { default as words } from './words.js';\nexport { default as wrap } from './wrap.js';\nexport { default as wrapperAt } from './wrapperAt.js';\nexport { default as wrapperChain } from './wrapperChain.js';\nexport { default as wrapperCommit } from './commit.js';\nexport { default as wrapperLodash } from './wrapperLodash.js';\nexport { default as wrapperNext } from './next.js';\nexport { default as wrapperPlant } from './plant.js';\nexport { default as wrapperReverse } from './wrapperReverse.js';\nexport { default as wrapperToIterator } from './toIterator.js';\nexport { default as wrapperValue } from './wrapperValue.js';\nexport { default as xor } from './xor.js';\nexport { default as xorBy } from './xorBy.js';\nexport { default as xorWith } from './xorWith.js';\nexport { default as zip } from './zip.js';\nexport { default as zipObject } from './zipObject.js';\nexport { default as zipObjectDeep } from './zipObjectDeep.js';\nexport { default as zipWith } from './zipWith.js';\nexport { default } from './lodash.default.js';\n", "import {privateAPI, setPrivateAPI} from '@theatre/core/privateAPIs'\nimport type {IProject} from '@theatre/core/projects/TheatreProject'\nimport type {ISheet} from '@theatre/core/sheets/TheatreSheet'\nimport type {SheetObjectAddress} from '@theatre/shared/utils/addresses'\nimport SimpleCache from '@theatre/shared/utils/SimpleCache'\nimport type {\n $FixMe,\n DeepPartialOfSerializableValue,\n VoidFn,\n} from '@theatre/shared/utils/types'\nimport type {Prism, Pointer} from '@theatre/dataverse'\nimport {prism, val} from '@theatre/dataverse'\nimport type SheetObject from './SheetObject'\nimport type {\n UnknownShorthandCompoundProps,\n PropsValue,\n} from '@theatre/core/propTypes/internals'\nimport {debounce} from 'lodash-es'\nimport type {DebouncedFunc} from 'lodash-es'\nimport type {IRafDriver} from '@theatre/core/rafDrivers'\nimport {onChange} from '@theatre/core/coreExports'\n\nexport interface ISheetObject<\n Props extends UnknownShorthandCompoundProps = UnknownShorthandCompoundProps,\n> {\n /**\n * All Objects will have `object.type === 'Theatre_SheetObject_PublicAPI'`\n */\n readonly type: 'Theatre_SheetObject_PublicAPI'\n\n /**\n * The current values of the props.\n *\n * @example\n * Usage:\n * ```ts\n * const obj = sheet.object(\"obj\", {x: 0})\n * console.log(obj.value.x) // prints 0 or the current numeric value\n * ```\n *\n * Future: Notice that if the user actually changes the Props config for one of the\n * properties, then this type can't be guaranteed accurrate.\n * * Right now the user can't change prop configs, but we'll probably enable that\n * functionality later via (`object.overrideConfig()`). We need to educate the\n * user that they can't rely on static types to know the type of object.value.\n */\n readonly value: PropsValue\n\n /**\n * A Pointer to the props of the object.\n *\n * More documentation soon.\n */\n readonly props: Pointer\n\n /**\n * The instance of Sheet the Object belongs to\n */\n readonly sheet: ISheet\n\n /**\n * The Project the project belongs to\n */\n readonly project: IProject\n\n /**\n * An object representing the address of the Object\n */\n readonly address: SheetObjectAddress\n\n /**\n * Calls `fn` every time the value of the props change.\n *\n * @param fn - The callback is called every time the value of the props change, plus once at the beginning.\n * @param rafDriver - (optional) The `rafDriver` to use. Learn how to use `rafDriver`s [from the docs](https://www.theatrejs.com/docs/latest/manual/advanced#rafdrivers).\n * @returns an Unsubscribe function\n *\n * @example\n * Usage:\n * ```ts\n * const obj = sheet.object(\"Box\", {position: {x: 0, y: 0}})\n * const div = document.getElementById(\"box\")\n *\n * const unsubscribe = obj.onValuesChange((newValues) => {\n * div.style.left = newValues.position.x + 'px'\n * div.style.top = newValues.position.y + 'px'\n * })\n *\n * // you can call unsubscribe() to stop listening to changes\n * ```\n */\n onValuesChange(\n fn: (values: this['value']) => void,\n rafDriver?: IRafDriver,\n ): VoidFn\n\n /**\n * Sets the initial value of the object. This value overrides the default\n * values defined in the prop types, but would itself be overridden if the user\n * overrides it in the UI with a static or animated value.\n *\n * @example\n * Usage:\n * ```ts\n * const obj = sheet.object(\"obj\", {position: {x: 0, y: 0}})\n *\n * obj.value // {position: {x: 0, y: 0}}\n *\n * // here, we only override position.x\n * obj.initialValue = {position: {x: 2}}\n *\n * obj.value // {position: {x: 2, y: 0}}\n * ```\n */\n set initialValue(value: DeepPartialOfSerializableValue)\n}\n\n// Enabled for https://linear.app/theatre/issue/P-217/if-objvalue-is-read-make-sure-its-derivation-remains-hot-for-a-while\n// Disable to test old behavior\nconst KEEP_HOT_FOR_MS: undefined | number = 5 * 1000\n\nexport default class TheatreSheetObject<\n Props extends UnknownShorthandCompoundProps = UnknownShorthandCompoundProps,\n> implements ISheetObject\n{\n get type(): 'Theatre_SheetObject_PublicAPI' {\n return 'Theatre_SheetObject_PublicAPI'\n }\n private readonly _cache = new SimpleCache()\n /** @internal See https://linear.app/theatre/issue/P-217/if-objvalue-is-read-make-sure-its-derivation-remains-hot-for-a-while */\n private _keepHotUntapDebounce: undefined | DebouncedFunc = undefined\n\n /**\n * @internal\n */\n constructor(internals: SheetObject) {\n setPrivateAPI(this, internals)\n }\n\n get props(): Pointer {\n return privateAPI(this).propsP as $FixMe\n }\n\n get sheet(): ISheet {\n return privateAPI(this).sheet.publicApi\n }\n\n get project(): IProject {\n return privateAPI(this).sheet.project.publicApi\n }\n\n get address(): SheetObjectAddress {\n return {...privateAPI(this).address}\n }\n\n private _valuesPrism(): Prism {\n return this._cache.get('_valuesPrism', () => {\n const sheetObject = privateAPI(this)\n const d: Prism> = prism(() => {\n return val(sheetObject.getValues().getValue()) as $FixMe\n })\n return d\n })\n }\n\n onValuesChange(\n fn: (values: this['value']) => void,\n rafDriver?: IRafDriver,\n ): VoidFn {\n return onChange(this._valuesPrism(), fn, rafDriver)\n }\n\n // internal: Make the deviration keepHot if directly read\n get value(): PropsValue {\n const der = this._valuesPrism()\n if (KEEP_HOT_FOR_MS != null) {\n if (!der.isHot) {\n // prism not hot, so keep it hot and set up `_keepHotUntapDebounce`\n if (this._keepHotUntapDebounce != null) {\n // defensive checks\n if (process.env.NODE_ENV === 'development') {\n privateAPI(this)._logger.errorDev(\n '`sheet.value` keepHot debouncer is set, even though the derivation is not actually hot.',\n )\n }\n // \"flush\" calls the `untap()` for previous `.keepHot()`.\n // This is defensive, as this code path is also already an invariant.\n // We have to flush though to avoid calling keepHot a second time and introducing two or more debounce fns.\n this._keepHotUntapDebounce.flush()\n }\n\n const untap = der.keepHot()\n // add a debounced function, so we keep this hot for some period of time that this .value is being read\n this._keepHotUntapDebounce = debounce(() => {\n untap()\n this._keepHotUntapDebounce = undefined\n }, KEEP_HOT_FOR_MS)\n }\n\n if (this._keepHotUntapDebounce) {\n // we enabled this \"keep hot\" and need to keep refreshing the timer on the debounce\n // See https://linear.app/theatre/issue/P-217/if-objvalue-is-read-make-sure-its-derivation-remains-hot-for-a-while\n this._keepHotUntapDebounce()\n }\n }\n return der.getValue()\n }\n\n set initialValue(val: DeepPartialOfSerializableValue) {\n privateAPI(this).setInitialValue(val)\n }\n}\n", "/**\n * Memoizes a unary function using a simple weakmap. The argument to the unary\n * function must be WeakCache-able, which means it must be an object and not a plain\n * number/string/boolean/etc.\n *\n * @example\n * ```ts\n * const fn = memoizeFn((el) => getBoundingClientRect(el))\n *\n * const b1 = fn(el)\n * const b2 = fn(el)\n * assert.equal(b1, b2)\n * ```\n */\nexport default function memoizeFn(\n producer: (k: K) => V,\n): (k: K) => V {\n const cache = new WeakMap()\n\n return (k: K): V => {\n if (!cache.has(k)) {\n cache.set(k, producer(k))\n }\n return cache.get(k)!\n }\n}\n", "import type {\n IBasePropType,\n PropTypeConfig,\n PropTypeConfig_AllSimples,\n PropTypeConfig_Compound,\n PropTypeConfig_Enum,\n} from '@theatre/core/propTypes'\nimport type {PathToProp} from '@theatre/shared/utils/addresses'\nimport type {$IntentionalAny} from '@theatre/shared/utils/types'\nimport memoizeFn from '@theatre/shared/utils/memoizeFn'\n\n/**\n * Either compound or enum properties can be considered \"composite\"\n * */\nexport function isPropConfigComposite(\n c: PropTypeConfig,\n): c is PropTypeConfig_Compound<{}> | PropTypeConfig_Enum {\n return c.type === 'compound' || c.type === 'enum'\n}\n\n/**\n * Returns the prop config at the given path. Traverses composite props until\n * it reaches the deepest prop config. Returns `undefined` if none is found.\n *\n * This is _NOT_ type-safe, so use with caution.\n */\nexport function getPropConfigByPath(\n parentConf: PropTypeConfig | undefined,\n path: PathToProp,\n): undefined | PropTypeConfig {\n if (!parentConf) return undefined\n const [key, ...rest] = path\n if (key === undefined) return parentConf\n if (!isPropConfigComposite(parentConf)) return undefined\n\n const sub =\n parentConf.type === 'enum'\n ? parentConf.cases[key]\n : (parentConf as $IntentionalAny).props[key]\n\n return getPropConfigByPath(sub, rest)\n}\n\n/**\n * @param value - An arbitrary value. May be matching the prop's type or not\n * @param propConfig - The configuration object for a prop\n * @returns value if it matches the prop's type\n * otherwise returns the default value for the prop\n */\nexport function valueInProp(\n value: unknown,\n propConfig: PropConfig,\n): PropConfig extends IBasePropType<$IntentionalAny, $IntentionalAny, infer T>\n ? T\n : never {\n const sanitizedVal = propConfig.deserializeAndSanitize(value)\n if (sanitizedVal === undefined) {\n return propConfig.default\n } else {\n return sanitizedVal\n }\n}\n\n/**\n * Returns true if the prop can be sequenced according to its config. This basically returns false for composite props,\n * and true for everything else.\n */\nexport function isPropConfSequencable(\n conf: PropTypeConfig,\n): conf is Extract {\n return !isPropConfigComposite(conf) // now all non-compounds are sequencable\n}\n\n/**\n * This basically checks of the compound prop has at least one simple prop in its descendants.\n * In other words, if the compound props has no subs, or its subs are only compounds that eventually\n * don't have simple subs, this will return false.\n */\nexport const compoundHasSimpleDescendants = memoizeFn(\n (conf: PropTypeConfig_Compound<{}> | PropTypeConfig_Enum): boolean => {\n if (conf.type === 'enum') {\n throw new Error(`Not implemented yet for enums`)\n }\n\n for (const key in conf.props) {\n const subConf = conf.props[\n key as $IntentionalAny as keyof typeof conf.props\n ] as PropTypeConfig\n if (isPropConfigComposite(subConf)) {\n if (compoundHasSimpleDescendants(subConf)) {\n return true\n }\n } else {\n return true\n }\n }\n return false\n },\n)\n\n/**\n * Iterates recursively over the simple props of a compound prop. Returns a generator.\n *\n *\n * @param conf - The prop config\n * @param pathPrefix - The path prefix to prepend to the paths of the props\n * @returns A generator that yields the path and the config of each simple prop\n *\n * * Example:\n * ```ts\n * const conf = types.compound({a: {b: 1, c: {d: 2}}})\n * for (const {path, conf} of iteratePropType(conf, ['foo'])) {\n * console.log({path, conf})\n * }\n * // logs:\n * // {path: ['foo', 'a', 'b'], conf: {type: 'number', default: 1}}\n * // {path: ['foo', 'a', 'c', 'd'], conf: {type: 'number', default: 2}}\n * ```\n */\nexport function* iteratePropType(\n conf: PropTypeConfig,\n pathPrefix: PathToProp,\n): Generator<{path: PathToProp; conf: PropTypeConfig}, void, void> {\n if (conf.type === 'compound') {\n for (const key in conf.props) {\n yield* iteratePropType(conf.props[key] as PropTypeConfig, [\n ...pathPrefix,\n key,\n ])\n }\n } else if (conf.type === 'enum') {\n throw new Error(`Not implemented yet`)\n } else {\n return yield {path: pathPrefix, conf}\n }\n}\n", "import type {InterpolationTriple} from '@theatre/core/sequences/interpolationTripleAtPosition'\nimport interpolationTripleAtPosition from '@theatre/core/sequences/interpolationTripleAtPosition'\nimport type Sheet from '@theatre/core/sheets/Sheet'\nimport type {SheetObjectAddress} from '@theatre/shared/utils/addresses'\nimport deepMergeWithCache from '@theatre/shared/utils/deepMergeWithCache'\nimport type {SequenceTrackId} from '@theatre/shared/utils/ids'\nimport pointerDeep from '@theatre/shared/utils/pointerDeep'\nimport SimpleCache from '@theatre/shared/utils/SimpleCache'\nimport type {\n $FixMe,\n $IntentionalAny,\n DeepPartialOfSerializableValue,\n SerializableMap,\n SerializableValue,\n} from '@theatre/shared/utils/types'\nimport {valToAtom} from '@theatre/shared/utils/valToAtom'\nimport type {PointerToPrismProvider, Prism, Pointer} from '@theatre/dataverse'\n\nimport {Atom, getPointerParts, pointer, prism, val} from '@theatre/dataverse'\nimport type SheetObjectTemplate from './SheetObjectTemplate'\nimport TheatreSheetObject from './TheatreSheetObject'\nimport type {Interpolator, PropTypeConfig} from '@theatre/core/propTypes'\nimport {getPropConfigByPath} from '@theatre/shared/propTypes/utils'\nimport type {ILogger, IUtilContext} from '@theatre/shared/logger'\n\n/**\n * Internally, the sheet's actual configured value is not a specific type, since we\n * can change the prop config at will, as such this is an alias of {@link SerializableMap}.\n *\n * TODO: Incorporate this knowledge into SheetObject & TemplateSheetObject\n */\ntype SheetObjectPropsValue = SerializableMap\n\n/**\n * An object on a sheet consisting of zero or more properties which can\n * be overridden statically or overridden by being sequenced.\n *\n * Note that this cannot be generic over `Props`, since the user is\n * able to change prop configs for the sheet object's properties.\n */\nexport default class SheetObject implements PointerToPrismProvider {\n get type(): 'Theatre_SheetObject' {\n return 'Theatre_SheetObject'\n }\n readonly $$isPointerToPrismProvider: true = true\n readonly address: SheetObjectAddress\n readonly publicApi: TheatreSheetObject\n private readonly _initialValue = new Atom({})\n private readonly _cache = new SimpleCache()\n readonly _logger: ILogger\n private readonly _internalUtilCtx: IUtilContext\n\n constructor(\n readonly sheet: Sheet,\n readonly template: SheetObjectTemplate,\n readonly nativeObject: unknown,\n ) {\n this._logger = sheet._logger.named(\n 'SheetObject',\n template.address.objectKey,\n )\n this._logger._trace('creating object')\n this._internalUtilCtx = {logger: this._logger.utilFor.internal()}\n this.address = {\n ...template.address,\n sheetInstanceId: sheet.address.sheetInstanceId,\n }\n\n this.publicApi = new TheatreSheetObject(this)\n }\n\n getValues(): Prism> {\n // Cache the prism because only one is needed per SheetObject.\n // Also, if `onValuesChange()` is unsubscribed from, this prism will go cold\n // and free its resources. So it's no problem to still keep it on the cache.\n return this._cache.get('getValues()', () =>\n prism(() => {\n /**\n * The final value is a deep-merge of defaults + initial + static + sequenced values.\n * We calculate each of those separately, and deep merge them one-by-one until\n * we get the final value.\n *\n * Notes on performance: This prism _will_ recalculate every time any value of any prop changes,\n * including nested props. In other words, if foo.bar.baz changes, this prism will recalculate. Even more,\n * if boo.bar.baz is sequenced and the sequence is playing, this prism will recalculate on every frame.\n * This might sound inefficient, but we have a few tricks to make it fast:\n *\n * First, on each recalculation, most of the prisms that this prism depends on will not have changed,\n * and so reading them is cheap. For example, if foo.bar.baz changed due to being sequenced, but\n * foo.bar2 hasn't because it is static, reading foo.bar2 will be cheap.\n *\n * Secondly, as we deep merge each layer, we use a cache to avoid recalculating the same merge over and over.\n *\n * Third, we have sorted our layers in the order of how likely they are to change. For example, sequenced\n * values are likely to change on each frame, so they're layerd on last. Static values seldom change,\n * and default values almost never do, so they're layered on first.\n *\n * All of this means that most the work of this prism is done on the very first calculation, and subsequent\n * recalculations are cheap.\n *\n * Question: What about object.initialValue which _could_ change on every frame, but isn't layerd on last?\n * Answer: initialValue is seldom used (it's only used in `@theatre/r3f` as far as we know). So this won't\n * affect the majority of use cases. And in case it _is_ used, it's better for us to implement an alternative\n * to `object.getValues()` that does not layer initialValue (and also skips defaultValue too). This is discussed\n * in issue [P-208](https://linear.app/theatre/issue/P-208/use-overrides-rather-than-final-values-in-r3f).\n */\n\n /**\n * The lowest layer is the default value of the root prop. Since an object's config\n * _could_ change, we read it as a prism. Otherwise, we could have just `getDefaultsOfPropTypeConfig(this.template.staticConfig)`.\n *\n * Note: If studio is not present, there is no known use-case for the config of an object to change on the fly, so\n * we could read this value statically.\n */\n const defaults = val(this.template.getDefaultValues())\n\n /**\n * The second layer is the initialValue, which is what the user sets with `sheetObject.initialValue = someValue`.\n */\n const initial = val(this._initialValue.pointer)\n\n /**\n * For each deep-merge, we need a separate WeakMap to cache the result of the merge. See {@link deepMergeWithCache}\n * to learn how that works.\n *\n * Here we use a `prism.memo()` so we can re-use our cache.\n */\n const withInitialCache = prism.memo(\n 'withInitialCache',\n () => new WeakMap(),\n [],\n )\n\n // deep-merge the defaultValues with the initialValues.\n const withInitial = deepMergeWithCache(\n defaults,\n initial,\n withInitialCache,\n )\n\n /**\n * The third layer are the static values. Since these are (currently) commnon to all instances\n * of the same SheetObject, we can read it from the template.\n */\n const statics = val(this.template.getStaticValues())\n\n // Similar to above, we need a separate but stable WeakMap to cache the result of merging the static values\n const withStaticsCache = prism.memo(\n 'withStatics',\n () => new WeakMap(),\n [],\n )\n\n // deep-merge the static values with the previous layer\n const withStatics = deepMergeWithCache(\n withInitial,\n statics,\n withStaticsCache,\n )\n\n /**\n * The final values (all layers merged together) will be put inside this variable\n */\n let final = withStatics\n /**\n * The sequenced values will be put in this variable\n */\n let sequenced\n\n {\n // NOTE: we're reading the sequenced values as a prism to a pointer. This should be refactored\n // to a simple pointer.\n const pointerToSequencedValuesD = prism.memo(\n 'seq',\n () => this.getSequencedValues(),\n [],\n )\n\n // like before, we need a separate but stable WeakMap to cache the result of merging the sequenced values\n // on top of the last layer\n const withSeqsCache = prism.memo(\n 'withSeqsCache',\n () => new WeakMap(),\n [],\n )\n\n // read the sequenced values\n // (val(val(x))) unwraps the pointer and the prism\n sequenced = val(val(pointerToSequencedValuesD))\n\n // deep-merge the sequenced values with the previous layer\n const withSeqs = deepMergeWithCache(final, sequenced, withSeqsCache)\n final = withSeqs\n }\n\n // Finally, we wrap the final value in an atom, so we can return a pointer to it.\n const a = valToAtom('finalAtom', final)\n\n // Since we only return a pointer, the value cannot be mutated from outside of this prism.\n return a.pointer\n }),\n )\n }\n\n getValueByPointer(pointer: Pointer): T {\n const allValuesP = val(this.getValues())\n const {path} = getPointerParts(pointer)\n\n return val(\n pointerDeep(allValuesP as $FixMe, path),\n ) as SerializableValue as T\n }\n\n pointerToPrism

(pointer: Pointer

): Prism

{\n const {path} = getPointerParts(pointer)\n /**\n * @remarks\n * TODO perf: Too much indirection here.\n */\n return prism(() => {\n const allValuesP = val(this.getValues())\n return val(pointerDeep(allValuesP as $FixMe, path)) as SerializableMap\n }) as $IntentionalAny as Prism

\n }\n\n /**\n * Returns values of props that are sequenced.\n */\n getSequencedValues(): Prism> {\n return prism(() => {\n const tracksToProcessD = prism.memo(\n 'tracksToProcess',\n () => this.template.getArrayOfValidSequenceTracks(),\n [],\n )\n\n const tracksToProcess = val(tracksToProcessD)\n const valsAtom = new Atom({})\n const config = val(this.template.configPointer)\n\n prism.effect(\n 'processTracks',\n () => {\n const untaps: Array<() => void> = []\n\n for (const {trackId, pathToProp} of tracksToProcess) {\n const pr = this._trackIdToPrism(trackId)\n const propConfig = getPropConfigByPath(\n config,\n pathToProp,\n )! as Extract\n\n const deserializeAndSanitize = propConfig.deserializeAndSanitize\n const interpolate =\n propConfig.interpolate! as Interpolator<$IntentionalAny>\n\n const updateSequenceValueFromItsPrism = () => {\n const triple = pr.getValue()\n\n if (!triple)\n return valsAtom.setByPointer(\n (p) => pointerDeep(p, pathToProp),\n undefined,\n )\n\n const leftDeserialized = deserializeAndSanitize(triple.left)\n\n const left =\n leftDeserialized === undefined\n ? propConfig.default\n : leftDeserialized\n\n if (triple.right === undefined)\n return valsAtom.setByPointer(\n (p) => pointerDeep(p, pathToProp),\n left,\n )\n\n const rightDeserialized = deserializeAndSanitize(triple.right)\n const right =\n rightDeserialized === undefined\n ? propConfig.default\n : rightDeserialized\n\n return valsAtom.setByPointer(\n (p) => pointerDeep(p, pathToProp),\n interpolate(left, right, triple.progression),\n )\n }\n const untap = pr.onStale(updateSequenceValueFromItsPrism)\n\n updateSequenceValueFromItsPrism()\n untaps.push(untap)\n }\n return () => {\n for (const untap of untaps) {\n untap()\n }\n }\n },\n [config, ...tracksToProcess],\n )\n\n return valsAtom.pointer\n })\n }\n\n protected _trackIdToPrism(\n trackId: SequenceTrackId,\n ): Prism {\n const trackP =\n this.template.project.pointers.historic.sheetsById[this.address.sheetId]\n .sequence.tracksByObject[this.address.objectKey].trackData[trackId]\n\n const timeD = this.sheet.getSequence().positionPrism\n\n return interpolationTripleAtPosition(this._internalUtilCtx, trackP, timeD)\n }\n\n get propsP(): Pointer {\n return this._cache.get('propsP', () =>\n pointer<{props: {}}>({root: this, path: []}),\n ) as $FixMe\n }\n\n validateValue(\n pointer: Pointer,\n value: DeepPartialOfSerializableValue,\n ) {\n // @todo\n }\n\n setInitialValue(val: DeepPartialOfSerializableValue) {\n this.validateValue(this.propsP, val)\n this._initialValue.set(val)\n }\n}\n", "/** @public configuration type */\nexport interface ITheatreLogger {\n error(level: ITheatreLogMeta, message: string, args?: Loggable): void\n warn(level: ITheatreLogMeta, message: string, args?: Loggable): void\n debug(level: ITheatreLogMeta, message: string, args?: Loggable): void\n trace(level: ITheatreLogMeta, message: string, args?: Loggable): void\n}\n\ntype ITheatreLogMeta = Readonly<{\n audience: 'public' | 'dev' | 'internal'\n category: 'general' | 'todo' | 'troubleshooting'\n level: TheatreLoggerLevel\n}>\n\n/** @public configuration type */\nexport interface ITheatreConsoleLogger {\n /** ERROR level logs */\n error(message: string, ...args: any[]): void\n /** WARN level logs */\n warn(message: string, ...args: any[]): void\n /** DEBUG level logs */\n info(message: string, ...args: any[]): void\n /** TRACE level logs */\n debug(message: string, ...args: any[]): void\n}\n\n/**\n * \"Downgraded\" {@link ILogger} for passing down to utility functions.\n *\n * A util logger is usually back by some specific {@link _Audience}.\n */\nexport interface IUtilLogger {\n /** Usually equivalent to `console.error`. */\n error(message: string, args?: object): void\n /** Usually equivalent to `console.warn`. */\n warn(message: string, args?: object): void\n /** Usually equivalent to `console.info`. */\n debug(message: string, args?: object): void\n /** Usually equivalent to `console.debug`. */\n trace(message: string, args?: object): void\n named(name: string, key?: string): IUtilLogger\n}\n\ntype Loggable = Record\ntype LogFn = (message: string, args?: Loggable) => void\n/**\n * Allow for the arguments to only be computed if the level is included.\n * If the level is not included, then the fn will still be passed to the filtered\n * function.\n */\ntype LazyLogFn = (message: string, args: () => Loggable) => void\n\nfunction lazy(f: LogFn): LazyLogFn {\n return function lazyLogIncluded(m, lazyArg) {\n return f(m, lazyArg())\n }\n}\n\nexport type _LogFns = Readonly<\n {\n [P in keyof typeof LEVELS]: LogFn\n }\n>\n\nexport type _LazyLogFns = Readonly<\n {\n [P in keyof typeof LEVELS]: LazyLogFn\n }\n>\n\n/** Internal library logger\n * TODO document these fns\n */\nexport interface ILogger extends _LogFns {\n named(name: string, key?: string | number): ILogger\n lazy: _LazyLogFns\n readonly utilFor: {\n internal(): IUtilLogger\n dev(): IUtilLogger\n public(): IUtilLogger\n }\n}\n\nexport type ITheatreLoggerConfig =\n | /** default {@link console} */\n 'console'\n | {\n type: 'console'\n /** default `true` */\n style?: boolean\n /** default {@link console} */\n console?: ITheatreConsoleLogger\n }\n | {\n type: 'named'\n named(names: string[]): ITheatreLogger\n }\n | {\n type: 'keyed'\n keyed(\n nameAndKeys: {\n name: string\n key?: string | number\n }[],\n ): ITheatreLogger\n }\n\nexport type ITheatreLogSource = {names: {name: string; key?: number | string}[]}\n\nexport type ITheatreLogIncludes = {\n /**\n * General information max level.\n * e.g. `Project imported might be corrupted`\n */\n min?: TheatreLoggerLevel\n /**\n * Include logs meant for developers using Theatre.js\n * e.g. `Created new project 'Abc' with options {...}`\n *\n * defaults to `true` if `internal: true` or defaults to `false`.\n */\n dev?: boolean\n /**\n * Include logs meant for internal development of Theatre.js\n * e.g. `Migrated project 'Abc' { duration_ms: 34, from_version: 1, to_version: 3, imported_settings: false }`\n *\n * defaults to `false`\n */\n internal?: boolean\n}\n\nexport type ITheatreLoggingConfig = ITheatreLogIncludes & {\n include?: (source: ITheatreLogSource) => ITheatreLogIncludes\n consoleStyle?: boolean\n}\n\n/** @internal */\nenum _Category {\n GENERAL = 1 << 0,\n TODO = 1 << 1,\n TROUBLESHOOTING = 1 << 2,\n}\n\n/** @internal */\nenum _Audience {\n /** Logs for developers of Theatre.js */\n INTERNAL = 1 << 3,\n /** Logs for developers using Theatre.js */\n DEV = 1 << 4,\n /** Logs for users of the app using Theatre.js */\n PUBLIC = 1 << 5,\n}\n\nexport enum TheatreLoggerLevel {\n TRACE = 1 << 6,\n DEBUG = 1 << 7,\n WARN = 1 << 8,\n ERROR = 1 << 9,\n}\n\n/**\n * @internal Theatre.js internal \"dev\" levels are odd numbers\n *\n * You can check if a level is odd quickly by doing `level & 1 === 1`\n */\nexport enum _LoggerLevel {\n /** The highest logging level number. */\n ERROR_PUBLIC = TheatreLoggerLevel.ERROR |\n _Audience.PUBLIC |\n _Category.GENERAL,\n ERROR_DEV = TheatreLoggerLevel.ERROR | _Audience.DEV | _Category.GENERAL,\n /** @internal this was an unexpected event */\n _HMM = TheatreLoggerLevel.ERROR |\n _Audience.INTERNAL |\n _Category.TROUBLESHOOTING,\n _TODO = TheatreLoggerLevel.ERROR | _Audience.INTERNAL | _Category.TODO,\n _ERROR = TheatreLoggerLevel.ERROR | _Audience.INTERNAL | _Category.GENERAL,\n WARN_PUBLIC = TheatreLoggerLevel.WARN | _Audience.PUBLIC | _Category.GENERAL,\n WARN_DEV = TheatreLoggerLevel.WARN | _Audience.DEV | _Category.GENERAL,\n /** @internal surface this in this moment, but it probably shouldn't be left in the code after debugging. */\n _KAPOW = TheatreLoggerLevel.WARN |\n _Audience.INTERNAL |\n _Category.TROUBLESHOOTING,\n _WARN = TheatreLoggerLevel.WARN | _Audience.INTERNAL | _Category.GENERAL,\n DEBUG_DEV = TheatreLoggerLevel.DEBUG | _Audience.DEV | _Category.GENERAL,\n /** @internal debug logs for implementation details */\n _DEBUG = TheatreLoggerLevel.DEBUG | _Audience.INTERNAL | _Category.GENERAL,\n /** trace logs like when the project is saved */\n TRACE_DEV = TheatreLoggerLevel.TRACE | _Audience.DEV | _Category.GENERAL,\n /**\n * The lowest logging level number.\n * @internal trace logs for implementation details\n */\n _TRACE = TheatreLoggerLevel.TRACE | _Audience.INTERNAL | _Category.GENERAL,\n}\n\nconst LEVELS = {\n _hmm: getLogMeta(_LoggerLevel._HMM),\n _todo: getLogMeta(_LoggerLevel._TODO),\n _error: getLogMeta(_LoggerLevel._ERROR),\n errorDev: getLogMeta(_LoggerLevel.ERROR_DEV),\n errorPublic: getLogMeta(_LoggerLevel.ERROR_PUBLIC),\n _kapow: getLogMeta(_LoggerLevel._KAPOW),\n _warn: getLogMeta(_LoggerLevel._WARN),\n warnDev: getLogMeta(_LoggerLevel.WARN_DEV),\n warnPublic: getLogMeta(_LoggerLevel.WARN_PUBLIC),\n _debug: getLogMeta(_LoggerLevel._DEBUG),\n debugDev: getLogMeta(_LoggerLevel.DEBUG_DEV),\n _trace: getLogMeta(_LoggerLevel._TRACE),\n traceDev: getLogMeta(_LoggerLevel.TRACE_DEV),\n}\n\nfunction getLogMeta(level: _LoggerLevel): ITheatreLogMeta {\n return Object.freeze({\n audience: hasFlag(level, _Audience.INTERNAL)\n ? 'internal'\n : hasFlag(level, _Audience.DEV)\n ? 'dev'\n : 'public',\n category: hasFlag(level, _Category.TROUBLESHOOTING)\n ? 'troubleshooting'\n : hasFlag(level, _Category.TODO)\n ? 'todo'\n : 'general',\n level:\n // I think this is equivalent... but I'm not using it until we have tests.\n // this code won't really impact performance much anyway, since it's just computed once\n // up front.\n // level &\n // (TheatreLoggerLevel.TRACE |\n // TheatreLoggerLevel.DEBUG |\n // TheatreLoggerLevel.WARN |\n // TheatreLoggerLevel.ERROR),\n hasFlag(level, TheatreLoggerLevel.ERROR)\n ? TheatreLoggerLevel.ERROR\n : hasFlag(level, TheatreLoggerLevel.WARN)\n ? TheatreLoggerLevel.WARN\n : hasFlag(level, TheatreLoggerLevel.DEBUG)\n ? TheatreLoggerLevel.DEBUG\n : // no other option\n TheatreLoggerLevel.TRACE,\n })\n}\n\n/**\n * This is a helper function to determine whether the logger level has a bit flag set.\n *\n * Flags are interesting, because they give us an opportunity to very easily set up filtering\n * based on category and level. This is not available from public api, yet, but it's a good\n * start.\n */\nfunction hasFlag(level: _LoggerLevel, flag: number): boolean {\n return (level & flag) === flag\n}\n\n/**\n * @internal\n *\n * You'd think max, means number \"max\", but since we use this system of bit flags,\n * we actually need to go the other way, with comparisons being math less than.\n *\n * NOTE: Keep this in the same file as {@link _Audience} to ensure basic compilers\n * can inline the enum values.\n */\nfunction shouldLog(\n includes: Required,\n level: _LoggerLevel,\n) {\n return (\n ((level & _Audience.PUBLIC) === _Audience.PUBLIC\n ? true\n : (level & _Audience.DEV) === _Audience.DEV\n ? includes.dev\n : (level & _Audience.INTERNAL) === _Audience.INTERNAL\n ? includes.internal\n : false) && includes.min <= level\n )\n}\n\nexport {shouldLog as _loggerShouldLog}\n\ntype InternalLoggerStyleRef = {\n italic?: RegExp\n bold?: RegExp\n color?: (name: string) => string\n collapseOnRE: RegExp\n cssMemo: Map\n css(this: InternalLoggerStyleRef, name: string): string\n collapsed(this: InternalLoggerStyleRef, name: string): string\n}\n\ntype InternalLoggerRef = {\n loggingConsoleStyle: boolean\n loggerConsoleStyle: boolean\n includes: Required\n filtered: (\n this: ITheatreLogSource,\n level: _LoggerLevel,\n message: string,\n args?: Loggable | (() => Loggable),\n ) => void\n include: (obj: ITheatreLogSource) => ITheatreLogIncludes\n create: (obj: ITheatreLogSource) => ILogger\n creatExt: (obj: ITheatreLogSource) => ITheatreLogger\n style: InternalLoggerStyleRef\n named(\n this: InternalLoggerRef,\n parent: ITheatreLogSource,\n name: string,\n key?: number | string,\n ): ILogger\n}\n\nconst DEFAULTS: InternalLoggerRef = {\n loggingConsoleStyle: true,\n loggerConsoleStyle: true,\n includes: Object.freeze({\n internal: false,\n dev: false,\n min: TheatreLoggerLevel.WARN,\n }),\n filtered: function defaultFiltered() {},\n include: function defaultInclude() {\n return {}\n },\n create: null!,\n creatExt: null!,\n named(this: InternalLoggerRef, parent, name, key) {\n return this.create({\n names: [...parent.names, {name, key}],\n })\n },\n style: {\n bold: undefined, // /Service$/\n italic: undefined, // /Model$/\n cssMemo: new Map([\n // handle empty names so we don't have to check for\n // name.length > 0 during this.css('')\n ['', ''],\n // bring a specific override\n // [\"Marker\", \"color:#aea9ff;font-size:0.75em;text-transform:uppercase\"]\n ]),\n collapseOnRE: /[a-z- ]+/g,\n color: undefined,\n // create collapsed name\n // insert collapsed name into cssMemo with original's style\n collapsed(this, name) {\n if (name.length < 5) return name\n const collapsed = name.replace(this.collapseOnRE, '')\n if (!this.cssMemo.has(collapsed)) {\n this.cssMemo.set(collapsed, this.css(name))\n }\n return collapsed\n },\n css(this, name): string {\n const found = this.cssMemo.get(name)\n if (found) return found\n let css = `color:${\n this.color?.(name) ??\n `hsl(${\n (name.charCodeAt(0) + name.charCodeAt(name.length - 1)) % 360\n }, 100%, 60%)`\n }`\n if (this.bold?.test(name)) {\n css += ';font-weight:600'\n }\n if (this.italic?.test(name)) {\n css += ';font-style:italic'\n }\n this.cssMemo.set(name, css)\n return css\n },\n },\n}\n\n/** @internal */\nexport type ITheatreInternalLogger = {\n configureLogger(config: ITheatreLoggerConfig): void\n configureLogging(config: ITheatreLoggingConfig): void\n getLogger(): ILogger\n}\n\nexport type ITheatreInternalLoggerOptions = {\n _error?: (message: string, args?: object) => void\n _debug?: (message: string, args?: object) => void\n}\n\nexport function createTheatreInternalLogger(\n useConsole: ITheatreConsoleLogger = console,\n // Not yet, used, but good pattern to have in case we want to log something\n // or report something interesting.\n _options: ITheatreInternalLoggerOptions = {},\n): ITheatreInternalLogger {\n const ref: InternalLoggerRef = {...DEFAULTS, includes: {...DEFAULTS.includes}}\n const createConsole = {\n styled: createConsoleLoggerStyled.bind(ref, useConsole),\n noStyle: createConsoleLoggerNoStyle.bind(ref, useConsole),\n }\n const createExtBound = createExtLogger.bind(ref)\n function getConCreate() {\n return ref.loggingConsoleStyle && ref.loggerConsoleStyle\n ? createConsole.styled\n : createConsole.noStyle\n }\n ref.create = getConCreate()\n\n return {\n configureLogger(config) {\n if (config === 'console') {\n ref.loggerConsoleStyle = DEFAULTS.loggerConsoleStyle\n ref.create = getConCreate()\n } else if (config.type === 'console') {\n ref.loggerConsoleStyle = config.style ?? DEFAULTS.loggerConsoleStyle\n ref.create = getConCreate()\n } else if (config.type === 'keyed') {\n ref.creatExt = (source) => config.keyed(source.names)\n ref.create = createExtBound\n } else if (config.type === 'named') {\n ref.creatExt = configNamedToKeyed.bind(null, config.named)\n ref.create = createExtBound\n }\n },\n configureLogging(config) {\n ref.includes.dev = config.dev ?? DEFAULTS.includes.dev\n ref.includes.internal = config.internal ?? DEFAULTS.includes.internal\n ref.includes.min = config.min ?? DEFAULTS.includes.min\n ref.include = config.include ?? DEFAULTS.include\n ref.loggingConsoleStyle =\n config.consoleStyle ?? DEFAULTS.loggingConsoleStyle\n ref.create = getConCreate()\n },\n getLogger() {\n return ref.create({names: []})\n },\n }\n}\n\n/** used by `configureLogger` for `'named'` */\nfunction configNamedToKeyed(\n namedFn: (names: string[]) => ITheatreLogger,\n source: ITheatreLogSource,\n): ITheatreLogger {\n const names: string[] = []\n for (let {name, key} of source.names) {\n names.push(key == null ? name : `${name} (${key})`)\n }\n return namedFn(names)\n}\n\nfunction createExtLogger(\n this: InternalLoggerRef,\n source: ITheatreLogSource,\n): ILogger {\n const includes = {...this.includes, ...this.include(source)}\n const f = this.filtered\n const named = this.named.bind(this, source)\n const ext = this.creatExt(source)\n\n const _HMM = shouldLog(includes, _LoggerLevel._HMM)\n const _TODO = shouldLog(includes, _LoggerLevel._TODO)\n const _ERROR = shouldLog(includes, _LoggerLevel._ERROR)\n const ERROR_DEV = shouldLog(includes, _LoggerLevel.ERROR_DEV)\n const ERROR_PUBLIC = shouldLog(includes, _LoggerLevel.ERROR_PUBLIC)\n const _WARN = shouldLog(includes, _LoggerLevel._WARN)\n const _KAPOW = shouldLog(includes, _LoggerLevel._KAPOW)\n const WARN_DEV = shouldLog(includes, _LoggerLevel.WARN_DEV)\n const WARN_PUBLIC = shouldLog(includes, _LoggerLevel.WARN_PUBLIC)\n const _DEBUG = shouldLog(includes, _LoggerLevel._DEBUG)\n const DEBUG_DEV = shouldLog(includes, _LoggerLevel.DEBUG_DEV)\n const _TRACE = shouldLog(includes, _LoggerLevel._TRACE)\n const TRACE_DEV = shouldLog(includes, _LoggerLevel.TRACE_DEV)\n const _hmm = _HMM\n ? ext.error.bind(ext, LEVELS._hmm)\n : f.bind(source, _LoggerLevel._HMM)\n const _todo = _TODO\n ? ext.error.bind(ext, LEVELS._todo)\n : f.bind(source, _LoggerLevel._TODO)\n const _error = _ERROR\n ? ext.error.bind(ext, LEVELS._error)\n : f.bind(source, _LoggerLevel._ERROR)\n const errorDev = ERROR_DEV\n ? ext.error.bind(ext, LEVELS.errorDev)\n : f.bind(source, _LoggerLevel.ERROR_DEV)\n const errorPublic = ERROR_PUBLIC\n ? ext.error.bind(ext, LEVELS.errorPublic)\n : f.bind(source, _LoggerLevel.ERROR_PUBLIC)\n const _kapow = _KAPOW\n ? ext.warn.bind(ext, LEVELS._kapow)\n : f.bind(source, _LoggerLevel._KAPOW)\n const _warn = _WARN\n ? ext.warn.bind(ext, LEVELS._warn)\n : f.bind(source, _LoggerLevel._WARN)\n const warnDev = WARN_DEV\n ? ext.warn.bind(ext, LEVELS.warnDev)\n : f.bind(source, _LoggerLevel.WARN_DEV)\n const warnPublic = WARN_PUBLIC\n ? ext.warn.bind(ext, LEVELS.warnPublic)\n : f.bind(source, _LoggerLevel.WARN_DEV)\n const _debug = _DEBUG\n ? ext.debug.bind(ext, LEVELS._debug)\n : f.bind(source, _LoggerLevel._DEBUG)\n const debugDev = DEBUG_DEV\n ? ext.debug.bind(ext, LEVELS.debugDev)\n : f.bind(source, _LoggerLevel.DEBUG_DEV)\n const _trace = _TRACE\n ? ext.trace.bind(ext, LEVELS._trace)\n : f.bind(source, _LoggerLevel._TRACE)\n const traceDev = TRACE_DEV\n ? ext.trace.bind(ext, LEVELS.traceDev)\n : f.bind(source, _LoggerLevel.TRACE_DEV)\n const logger: ILogger = {\n _hmm,\n _todo,\n _error,\n errorDev,\n errorPublic,\n _kapow,\n _warn,\n warnDev,\n warnPublic,\n _debug,\n debugDev,\n _trace,\n traceDev,\n lazy: {\n _hmm: _HMM ? lazy(_hmm) : _hmm,\n _todo: _TODO ? lazy(_todo) : _todo,\n _error: _ERROR ? lazy(_error) : _error,\n errorDev: ERROR_DEV ? lazy(errorDev) : errorDev,\n errorPublic: ERROR_PUBLIC ? lazy(errorPublic) : errorPublic,\n _kapow: _KAPOW ? lazy(_kapow) : _kapow,\n _warn: _WARN ? lazy(_warn) : _warn,\n warnDev: WARN_DEV ? lazy(warnDev) : warnDev,\n warnPublic: WARN_PUBLIC ? lazy(warnPublic) : warnPublic,\n _debug: _DEBUG ? lazy(_debug) : _debug,\n debugDev: DEBUG_DEV ? lazy(debugDev) : debugDev,\n _trace: _TRACE ? lazy(_trace) : _trace,\n traceDev: TRACE_DEV ? lazy(traceDev) : traceDev,\n },\n //\n named,\n utilFor: {\n internal() {\n return {\n debug: logger._debug,\n error: logger._error,\n warn: logger._warn,\n trace: logger._trace,\n named(name, key) {\n return logger.named(name, key).utilFor.internal()\n },\n }\n },\n dev() {\n return {\n debug: logger.debugDev,\n error: logger.errorDev,\n warn: logger.warnDev,\n trace: logger.traceDev,\n named(name, key) {\n return logger.named(name, key).utilFor.dev()\n },\n }\n },\n public() {\n return {\n error: logger.errorPublic,\n warn: logger.warnPublic,\n debug(message, obj) {\n logger._warn(`(public \"debug\" filtered out) ${message}`, obj)\n },\n trace(message, obj) {\n logger._warn(`(public \"trace\" filtered out) ${message}`, obj)\n },\n named(name, key) {\n return logger.named(name, key).utilFor.public()\n },\n }\n },\n },\n }\n\n return logger\n}\n\nfunction createConsoleLoggerStyled(\n this: InternalLoggerRef,\n con: ITheatreConsoleLogger,\n source: ITheatreLogSource,\n): ILogger {\n const includes = {...this.includes, ...this.include(source)}\n\n const styleArgs: any[] = []\n let prefix = ''\n for (let i = 0; i < source.names.length; i++) {\n const {name, key} = source.names[i]\n prefix += ` %c${name}`\n styleArgs.push(this.style.css(name))\n if (key != null) {\n const keyStr = `%c#${key}`\n prefix += keyStr\n styleArgs.push(this.style.css(keyStr))\n }\n }\n\n const f = this.filtered\n const named = this.named.bind(this, source)\n const prefixArr = [prefix, ...styleArgs]\n return _createConsoleLogger(\n f,\n source,\n includes,\n con,\n prefixArr,\n styledKapowPrefix(prefixArr),\n named,\n )\n}\n\nfunction styledKapowPrefix(args: ReadonlyArray): ReadonlyArray {\n const start = args.slice(0)\n for (let i = 1; i < start.length; i++)\n // add big font to all part styles\n start[i] += ';background-color:#e0005a;padding:2px;color:white'\n return start\n}\n\nfunction createConsoleLoggerNoStyle(\n this: InternalLoggerRef,\n con: ITheatreConsoleLogger,\n source: ITheatreLogSource,\n): ILogger {\n const includes = {...this.includes, ...this.include(source)}\n\n let prefix = ''\n for (let i = 0; i < source.names.length; i++) {\n const {name, key} = source.names[i]\n prefix += ` ${name}`\n if (key != null) {\n prefix += `#${key}`\n }\n }\n\n const f = this.filtered\n const named = this.named.bind(this, source)\n const prefixArr = [prefix]\n return _createConsoleLogger(\n f,\n source,\n includes,\n con,\n prefixArr,\n prefixArr,\n named,\n )\n}\n\n/** Used by {@link createConsoleLoggerNoStyle} and {@link createConsoleLoggerStyled} */\nfunction _createConsoleLogger(\n f: (\n this: ITheatreLogSource,\n level: _LoggerLevel,\n message: string,\n args?: object | undefined,\n ) => void,\n source: ITheatreLogSource,\n includes: {min: TheatreLoggerLevel; dev: boolean; internal: boolean},\n con: ITheatreConsoleLogger,\n prefix: ReadonlyArray,\n kapowPrefix: ReadonlyArray,\n named: (name: string, key?: string | number | undefined) => ILogger,\n) {\n const _HMM = shouldLog(includes, _LoggerLevel._HMM)\n const _TODO = shouldLog(includes, _LoggerLevel._TODO)\n const _ERROR = shouldLog(includes, _LoggerLevel._ERROR)\n const ERROR_DEV = shouldLog(includes, _LoggerLevel.ERROR_DEV)\n const ERROR_PUBLIC = shouldLog(includes, _LoggerLevel.ERROR_PUBLIC)\n const _WARN = shouldLog(includes, _LoggerLevel._WARN)\n const _KAPOW = shouldLog(includes, _LoggerLevel._KAPOW)\n const WARN_DEV = shouldLog(includes, _LoggerLevel.WARN_DEV)\n const WARN_PUBLIC = shouldLog(includes, _LoggerLevel.WARN_PUBLIC)\n const _DEBUG = shouldLog(includes, _LoggerLevel._DEBUG)\n const DEBUG_DEV = shouldLog(includes, _LoggerLevel.DEBUG_DEV)\n const _TRACE = shouldLog(includes, _LoggerLevel._TRACE)\n const TRACE_DEV = shouldLog(includes, _LoggerLevel.TRACE_DEV)\n const _hmm = _HMM\n ? con.error.bind(con, ...prefix)\n : f.bind(source, _LoggerLevel._HMM)\n const _todo = _TODO\n ? con.error.bind(con, ...prefix)\n : f.bind(source, _LoggerLevel._TODO)\n const _error = _ERROR\n ? con.error.bind(con, ...prefix)\n : f.bind(source, _LoggerLevel._ERROR)\n const errorDev = ERROR_DEV\n ? con.error.bind(con, ...prefix)\n : f.bind(source, _LoggerLevel.ERROR_DEV)\n const errorPublic = ERROR_PUBLIC\n ? con.error.bind(con, ...prefix)\n : f.bind(source, _LoggerLevel.ERROR_PUBLIC)\n const _kapow = _KAPOW\n ? con.warn.bind(con, ...kapowPrefix)\n : f.bind(source, _LoggerLevel._KAPOW)\n const _warn = _WARN\n ? con.warn.bind(con, ...prefix)\n : f.bind(source, _LoggerLevel._WARN)\n const warnDev = WARN_DEV\n ? con.warn.bind(con, ...prefix)\n : f.bind(source, _LoggerLevel.WARN_DEV)\n const warnPublic = WARN_PUBLIC\n ? con.warn.bind(con, ...prefix)\n : f.bind(source, _LoggerLevel.WARN_DEV)\n const _debug = _DEBUG\n ? con.info.bind(con, ...prefix)\n : f.bind(source, _LoggerLevel._DEBUG)\n const debugDev = DEBUG_DEV\n ? con.info.bind(con, ...prefix)\n : f.bind(source, _LoggerLevel.DEBUG_DEV)\n const _trace = _TRACE\n ? con.debug.bind(con, ...prefix)\n : f.bind(source, _LoggerLevel._TRACE)\n const traceDev = TRACE_DEV\n ? con.debug.bind(con, ...prefix)\n : f.bind(source, _LoggerLevel.TRACE_DEV)\n const logger: ILogger = {\n _hmm,\n _todo,\n _error,\n errorDev,\n errorPublic,\n _kapow,\n _warn,\n warnDev,\n warnPublic,\n _debug,\n debugDev,\n _trace,\n traceDev,\n lazy: {\n _hmm: _HMM ? lazy(_hmm) : _hmm,\n _todo: _TODO ? lazy(_todo) : _todo,\n _error: _ERROR ? lazy(_error) : _error,\n errorDev: ERROR_DEV ? lazy(errorDev) : errorDev,\n errorPublic: ERROR_PUBLIC ? lazy(errorPublic) : errorPublic,\n _kapow: _KAPOW ? lazy(_kapow) : _kapow,\n _warn: _WARN ? lazy(_warn) : _warn,\n warnDev: WARN_DEV ? lazy(warnDev) : warnDev,\n warnPublic: WARN_PUBLIC ? lazy(warnPublic) : warnPublic,\n _debug: _DEBUG ? lazy(_debug) : _debug,\n debugDev: DEBUG_DEV ? lazy(debugDev) : debugDev,\n _trace: _TRACE ? lazy(_trace) : _trace,\n traceDev: TRACE_DEV ? lazy(traceDev) : traceDev,\n },\n //\n named,\n utilFor: {\n internal() {\n return {\n debug: logger._debug,\n error: logger._error,\n warn: logger._warn,\n trace: logger._trace,\n named(name, key) {\n return logger.named(name, key).utilFor.internal()\n },\n }\n },\n dev() {\n return {\n debug: logger.debugDev,\n error: logger.errorDev,\n warn: logger.warnDev,\n trace: logger.traceDev,\n named(name, key) {\n return logger.named(name, key).utilFor.dev()\n },\n }\n },\n public() {\n return {\n error: logger.errorPublic,\n warn: logger.warnPublic,\n debug(message, obj) {\n logger._warn(`(public \"debug\" filtered out) ${message}`, obj)\n },\n trace(message, obj) {\n logger._warn(`(public \"trace\" filtered out) ${message}`, obj)\n },\n named(name, key) {\n return logger.named(name, key).utilFor.public()\n },\n }\n },\n },\n }\n\n return logger\n}\n", "export type {\n ILogger,\n IUtilLogger,\n ITheatreConsoleLogger,\n ITheatreLogIncludes,\n ITheatreLogSource,\n ITheatreLoggerConfig,\n ITheatreLoggingConfig,\n ITheatreInternalLogger,\n} from './_logger/logger'\nimport {createTheatreInternalLogger, TheatreLoggerLevel} from './_logger/logger'\nimport type {IUtilLogger} from './_logger/logger'\nexport {TheatreLoggerLevel, createTheatreInternalLogger} from './_logger/logger'\n\n/**\n * Common object interface for the context to pass in to utility functions.\n *\n * Prefer to pass this into utility function rather than an {@link IUtilLogger}.\n */\nexport interface IUtilContext {\n readonly logger: IUtilLogger\n}\n\nconst internal = createTheatreInternalLogger(console, {\n _debug: function () {},\n _error: function () {},\n})\n\ninternal.configureLogging({\n dev: true,\n min: TheatreLoggerLevel.TRACE,\n})\n\nexport default internal\n .getLogger()\n .named('Theatre.js (default logger)')\n .utilFor.dev()\n", "import type {$IntentionalAny} from '@theatre/shared/utils/types'\nimport type {\n PropTypeConfig,\n PropTypeConfig_Compound,\n} from '@theatre/core/propTypes'\nimport {isPropConfigComposite} from '@theatre/shared/propTypes/utils'\n\ntype EncodedPropPath = string\ntype Order = number\n\ntype Mapping = Map\n\nconst cache = new WeakMap, Mapping>()\n\nexport default function getOrderingOfPropTypeConfig(\n config: PropTypeConfig_Compound<$IntentionalAny>,\n): Mapping {\n const existing = cache.get(config)\n if (existing) return existing\n\n const map: Mapping = new Map()\n cache.set(config, map)\n\n iterateOnCompound([], config, map)\n\n return map\n}\n\nfunction iterateOnCompound(\n path: string[],\n config: PropTypeConfig_Compound<$IntentionalAny>,\n map: Mapping,\n) {\n for (const [key, subConf] of Object.entries(config.props)) {\n if (!isPropConfigComposite(subConf)) {\n const subPath = [...path, key]\n map.set(JSON.stringify(subPath), map.size)\n iterateOnAny(subPath, subConf, map)\n }\n }\n\n for (const [key, subConf] of Object.entries(config.props)) {\n if (isPropConfigComposite(subConf)) {\n const subPath = [...path, key]\n map.set(JSON.stringify(subPath), map.size)\n iterateOnAny(subPath, subConf, map)\n }\n }\n}\n\n// function iterateOnEnum(\n// path: string[],\n// config: PropTypeConfig_Enum,\n// map: Mapping,\n// ) {\n// for (const [key, subConf] of Object.entries(config.cases)) {\n// const subPath = [...path, key]\n// map.set(JSON.stringify(subPath), map.size)\n// iterateOnAny(subPath, subConf, map)\n// }\n// }\n\nfunction iterateOnAny(path: string[], config: PropTypeConfig, map: Mapping) {\n if (config.type === 'compound') {\n iterateOnCompound(path, config, map)\n } else if (config.type === 'enum') {\n throw new Error(`Enums aren't supported yet`)\n } else {\n map.set(JSON.stringify(path), map.size)\n }\n}\n", "import type Project from '@theatre/core/projects/Project'\nimport type Sheet from '@theatre/core/sheets/Sheet'\nimport type SheetTemplate from '@theatre/core/sheets/SheetTemplate'\nimport type {\n SheetObjectActionsConfig,\n SheetObjectPropTypeConfig,\n} from '@theatre/core/sheets/TheatreSheet'\nimport {emptyArray} from '@theatre/shared/utils'\nimport type {\n PathToProp,\n SheetObjectAddress,\n WithoutSheetInstance,\n} from '@theatre/shared/utils/addresses'\nimport getDeep from '@theatre/shared/utils/getDeep'\nimport type {ObjectAddressKey, SequenceTrackId} from '@theatre/shared/utils/ids'\nimport SimpleCache from '@theatre/shared/utils/SimpleCache'\nimport type {\n $FixMe,\n $IntentionalAny,\n SerializableMap,\n SerializablePrimitive,\n SerializableValue,\n} from '@theatre/shared/utils/types'\nimport type {Prism, Pointer} from '@theatre/dataverse'\nimport {Atom, getPointerParts, prism, val} from '@theatre/dataverse'\nimport set from 'lodash-es/set'\nimport getPropDefaultsOfSheetObject from './getPropDefaultsOfSheetObject'\nimport SheetObject from './SheetObject'\nimport logger from '@theatre/shared/logger'\nimport {\n getPropConfigByPath,\n isPropConfSequencable,\n} from '@theatre/shared/propTypes/utils'\nimport getOrderingOfPropTypeConfig from './getOrderingOfPropTypeConfig'\nimport type {SheetState_Historic} from '@theatre/core/projects/store/types/SheetState_Historic'\nimport {cloneDeep, unset} from 'lodash-es'\n\nfunction isObjectEmpty(obj: unknown): boolean {\n return (\n typeof obj === 'object' && obj !== null && Object.keys(obj).length === 0\n )\n}\n\n/**\n * Given an object like: `{transform: {type: 'absolute', position: {x: 0}}}`,\n * if both `transform.type` and `transform.position.x` are sequenced, this\n * type would look like:\n *\n * ```ts\n * {\n * transform: {\n * type: 'SDFJSDFJ', // track id of transform.type\n * position: {\n * x: 'NCXNS' // track id of transform.position.x\n * }\n * }\n * }\n * ```\n */\nexport type IPropPathToTrackIdTree = {\n [propName in string]?: SequenceTrackId | IPropPathToTrackIdTree\n}\n\n/**\n * TODO: Add documentation, and share examples of sheet objects.\n *\n * See {@link SheetObject} for more information.\n */\nexport default class SheetObjectTemplate {\n readonly address: WithoutSheetInstance\n readonly type: 'Theatre_SheetObjectTemplate' = 'Theatre_SheetObjectTemplate'\n protected _config: Atom\n readonly _temp_actions_atom: Atom\n readonly _cache = new SimpleCache()\n readonly project: Project\n readonly pointerToSheetState: Pointer\n readonly pointerToStaticOverrides: Pointer<\n SerializableMap | undefined\n >\n\n get staticConfig() {\n return this._config.get()\n }\n\n get configPointer() {\n return this._config.pointer\n }\n\n get _temp_actions() {\n return this._temp_actions_atom.get()\n }\n\n get _temp_actionsPointer() {\n return this._temp_actions_atom.pointer\n }\n\n constructor(\n readonly sheetTemplate: SheetTemplate,\n objectKey: ObjectAddressKey,\n nativeObject: unknown,\n config: SheetObjectPropTypeConfig,\n _temp_actions: SheetObjectActionsConfig,\n ) {\n this.address = {...sheetTemplate.address, objectKey}\n this._config = new Atom(config)\n this._temp_actions_atom = new Atom(_temp_actions)\n this.project = sheetTemplate.project\n\n this.pointerToSheetState =\n this.sheetTemplate.project.pointers.historic.sheetsById[\n this.address.sheetId\n ]\n\n this.pointerToStaticOverrides =\n this.pointerToSheetState.staticOverrides.byObject[this.address.objectKey]\n }\n\n createInstance(\n sheet: Sheet,\n nativeObject: unknown,\n config: SheetObjectPropTypeConfig,\n ): SheetObject {\n this._config.set(config)\n return new SheetObject(sheet, this, nativeObject)\n }\n\n reconfigure(config: SheetObjectPropTypeConfig) {\n this._config.set(config)\n }\n\n /**\n * The `actions` api is temporary until we implement events.\n */\n _temp_setActions(actions: SheetObjectActionsConfig) {\n this._temp_actions_atom.set(actions)\n }\n\n /**\n * Returns the default values (all defaults are read from the config)\n */\n getDefaultValues(): Prism {\n return this._cache.get('getDefaultValues()', () =>\n prism(() => {\n const config = val(this.configPointer)\n return getPropDefaultsOfSheetObject(config)\n }),\n )\n }\n\n /**\n * Returns values that are set statically (ie, not sequenced, and not defaults)\n */\n getStaticValues(): Prism {\n return this._cache.get('getStaticValues', () =>\n prism(() => {\n const json = val(this.pointerToStaticOverrides) ?? {}\n\n const config = val(this.configPointer)\n const deserialized = config.deserializeAndSanitize(json) || {}\n return deserialized\n }),\n )\n }\n\n /**\n * Filters through the sequenced tracks and returns those tracks who are valid\n * according to the object's prop types, then sorted in the same order as the config\n *\n * Returns an array.\n */\n getArrayOfValidSequenceTracks(): Prism<\n Array<{pathToProp: PathToProp; trackId: SequenceTrackId}>\n > {\n return this._cache.get('getArrayOfValidSequenceTracks', () =>\n prism((): Array<{pathToProp: PathToProp; trackId: SequenceTrackId}> => {\n const pointerToSheetState =\n this.project.pointers.historic.sheetsById[this.address.sheetId]\n\n const trackIdByPropPath = val(\n pointerToSheetState.sequence.tracksByObject[this.address.objectKey]\n .trackIdByPropPath,\n )\n\n if (!trackIdByPropPath) return emptyArray as $IntentionalAny\n\n const arrayOfIds: Array<{\n pathToProp: PathToProp\n trackId: SequenceTrackId\n }> = []\n\n if (!trackIdByPropPath) return emptyArray as $IntentionalAny\n\n const objectConfig = val(this.configPointer)\n\n const _entries = Object.entries(trackIdByPropPath)\n for (const [pathToPropInString, trackId] of _entries) {\n const pathToProp = parsePathToProp(pathToPropInString)\n if (!pathToProp) continue\n\n const propConfig = getPropConfigByPath(objectConfig, pathToProp)\n\n const isSequencable = propConfig && isPropConfSequencable(propConfig)\n\n if (!isSequencable) continue\n\n arrayOfIds.push({pathToProp, trackId: trackId!})\n }\n\n const mapping = getOrderingOfPropTypeConfig(objectConfig)\n\n arrayOfIds.sort((a, b) => {\n const pathToPropA = a.pathToProp\n const pathToPropB = b.pathToProp\n\n const indexA = mapping.get(JSON.stringify(pathToPropA))!\n const indexB = mapping.get(JSON.stringify(pathToPropB))!\n\n if (indexA > indexB) {\n return 1\n }\n\n return -1\n })\n\n if (arrayOfIds.length === 0) {\n return emptyArray as $IntentionalAny\n } else {\n return arrayOfIds\n }\n }),\n )\n }\n\n /**\n * Filters through the sequenced tracks those tracks that are valid\n * according to the object's prop types.\n *\n * Returns a map.\n *\n * Not available in core.\n */\n getMapOfValidSequenceTracks_forStudio(): Prism {\n return this._cache.get('getMapOfValidSequenceTracks_forStudio', () =>\n prism(() => {\n const arr = val(this.getArrayOfValidSequenceTracks())\n let map = {}\n\n for (const {pathToProp, trackId} of arr) {\n set(map, pathToProp, trackId)\n }\n\n return map\n }),\n )\n }\n\n /**\n * @returns The static overrides that are not sequenced. Returns undefined if there are no static overrides,\n * or if all those static overrides are sequenced.\n */\n getStaticButNotSequencedOverrides(): Prism {\n return this._cache.get('getStaticButNotSequencedOverrides', () =>\n prism(() => {\n const staticOverrides = val(this.getStaticValues())\n const arrayOfValidSequenceTracks = val(\n this.getArrayOfValidSequenceTracks(),\n )\n\n const staticButNotSequencedOverrides = cloneDeep(staticOverrides)\n\n for (const {pathToProp} of arrayOfValidSequenceTracks) {\n unset(staticButNotSequencedOverrides, pathToProp)\n // also unset the parent if it's empty, and so on\n let parentPath = pathToProp.slice(0, -1)\n while (parentPath.length > 0) {\n const parentValue = getDeep(\n staticButNotSequencedOverrides,\n parentPath,\n )\n if (!isObjectEmpty(parentValue)) break\n unset(staticButNotSequencedOverrides, parentPath)\n parentPath = parentPath.slice(0, -1)\n }\n }\n\n if (isObjectEmpty(staticButNotSequencedOverrides)) {\n return undefined\n } else {\n return staticButNotSequencedOverrides\n }\n }),\n )\n }\n\n getDefaultsAtPointer(\n pointer: Pointer,\n ): SerializableValue | undefined {\n const {path} = getPointerParts(pointer)\n const defaults = this.getDefaultValues().getValue()\n\n const defaultsAtPath = getDeep(defaults, path)\n return defaultsAtPath as $FixMe\n }\n}\n\nfunction parsePathToProp(\n pathToPropInString: string,\n): undefined | Array {\n try {\n const pathToProp = JSON.parse(pathToPropInString)\n return pathToProp\n } catch (e) {\n logger.warn(\n `property ${JSON.stringify(\n pathToPropInString,\n )} cannot be parsed. Skipping.`,\n )\n return undefined\n }\n}\n", "import type {ObjectAddressKey, ProjectId, SheetId, SheetInstanceId} from './ids'\nimport memoizeFn from './memoizeFn'\nimport type {Nominal} from './Nominal'\n\n/**\n * Addresses are used to identify projects, sheets, objects, and other things.\n *\n * For example, a project's address looks like `{projectId: 'my-project'}`, and a sheet's\n * address looks like `{projectId: 'my-project', sheetId: 'my-sheet'}`.\n *\n * As you see, a Sheet's address is a superset of a Project's address. This is so that we can\n * use the same address type for both. All addresses follow the same rule. An object's address\n * extends its sheet's address, which extends its project's address.\n *\n * For example, generating an object's address from a sheet's address is as simple as `{...sheetAddress, objectId: 'my-object'}`.\n *\n * Also, if you need the projectAddress of an object, you can just re-use the object's address:\n * `aFunctionThatRequiresProjectAddress(objectAddress)`.\n */\n\n/**\n * Represents the address to a project\n */\nexport interface ProjectAddress {\n projectId: ProjectId\n}\n\n/**\n * Represents the address to a specific instance of a Sheet\n *\n * @example\n * ```ts\n * const sheet = project.sheet('a sheet', 'some instance id')\n * sheet.address.sheetId === 'a sheet'\n * sheet.address.sheetInstanceId === 'sheetInstanceId'\n * ```\n *\n * See {@link WithoutSheetInstance} for a type that doesn't include the sheet instance id.\n */\nexport interface SheetAddress extends ProjectAddress {\n sheetId: SheetId\n sheetInstanceId: SheetInstanceId\n}\n\n/**\n * Removes `sheetInstanceId` from an address, making it refer to\n * all instances of a certain `sheetId`.\n *\n * See {@link SheetAddress} for a type that includes the sheet instance id.\n */\nexport type WithoutSheetInstance = Omit<\n T,\n 'sheetInstanceId'\n>\n\nexport type SheetInstanceOptional =\n WithoutSheetInstance & {sheetInstanceId?: SheetInstanceId | undefined}\n\n/**\n * Represents the address to a Sheet's Object.\n *\n * It includes the sheetInstance, so it's specific to a single instance of a sheet. If you\n * would like an address that doesn't include the sheetInstance, use `WithoutSheetInstance`.\n */\nexport interface SheetObjectAddress extends SheetAddress {\n /**\n * The key of the object.\n *\n * @example\n * ```ts\n * const obj = sheet.object('foo', {})\n * obj.address.objectKey === 'foo'\n * ```\n */\n objectKey: ObjectAddressKey\n}\n\n/**\n * This is a simple array representing the path to a prop, without specifying the object.\n */\nexport type PathToProp = Array\n\n/**\n * Just like {@link PathToProp}, but encoded as a string. Since this type is nominal,\n * it can only be generated using {@link encodePathToProp}.\n */\nexport type PathToProp_Encoded = Nominal<'PathToProp_Encoded'>\n\n/**\n * Encodes a {@link PathToProp} as a string, and caches the result, so as long\n * as the input is the same, the output won't have to be re-generated.\n */\nexport const encodePathToProp = memoizeFn(\n (p: PathToProp): PathToProp_Encoded =>\n // we're using JSON.stringify here, but we could use a faster alternative.\n // If you happen to do that, first make sure no `PathToProp_Encoded` is ever\n // used in the store, otherwise you'll have to write a migration.\n JSON.stringify(p) as PathToProp_Encoded,\n)\n\n/**\n * The decoder of {@link encodePathToProp}.\n */\nexport const decodePathToProp = (s: PathToProp_Encoded): PathToProp =>\n JSON.parse(s)\n\n/**\n * Represents the path to a certain prop of an object\n */\nexport interface PropAddress extends SheetObjectAddress {\n pathToProp: PathToProp\n}\n\n/**\n * Represents the address of a certain sequence of a sheet.\n *\n * Since currently sheets are single-sequence only, `sequenceName` is always `'default'` for now.\n */\nexport interface SequenceAddress extends SheetAddress {\n sequenceName: string\n}\n\n/**\n * Returns true if `path` starts with `pathPrefix`.\n *\n * Example:\n * ```ts\n * const prefix: PathToProp = ['a', 'b']\n * console.log(doesPathStartWith(['a', 'b', 'c'], prefix)) // true\n * console.log(doesPathStartWith(['x', 'b', 'c'], prefix)) // false\n * ```\n */\nexport function doesPathStartWith(path: PathToProp, pathPrefix: PathToProp) {\n return pathPrefix.every((pathPart, i) => pathPart === path[i])\n}\n\n/**\n * Returns true if pathToPropA and pathToPropB are equal.\n */\nexport function arePathsEqual(\n pathToPropA: PathToProp,\n pathToPropB: PathToProp,\n) {\n if (pathToPropA.length !== pathToPropB.length) return false\n for (let i = 0; i < pathToPropA.length; i++) {\n if (pathToPropA[i] !== pathToPropB[i]) return false\n }\n return true\n}\n\n/**\n * Given an array of `PathToProp`s, returns the longest common prefix.\n *\n * Example\n * ```\n * commonRootOfPathsToProps([\n * ['a','b','c','d','e'],\n * ['a','b','x','y','z'],\n * ['a','b','c']\n * ]) // = ['a','b']\n * ```\n */\nexport function commonRootOfPathsToProps(pathsToProps: PathToProp[]) {\n const commonPathToProp: PathToProp = []\n while (true) {\n const i = commonPathToProp.length\n let candidatePathPart = pathsToProps[0]?.[i]\n if (candidatePathPart === undefined) return commonPathToProp\n\n for (const pathToProp of pathsToProps) {\n if (candidatePathPart !== pathToProp[i]) {\n return commonPathToProp\n }\n }\n\n commonPathToProp.push(candidatePathPart)\n }\n}\n", "import propose from 'propose'\n\n/**\n * Proposes a suggestion to fix a typo in `str`, using the options provided in `dictionary`.\n *\n * Example:\n * ```ts\n * didYouMean('helo', ['hello', 'world']) // 'Did you mean \"hello\"?'\n * ```\n */\nexport default function didYouMean(\n str: string,\n dictionary: string[],\n prepend: string = 'Did you mean ',\n append: string = '?',\n): string {\n const p = propose(str, dictionary, {\n threshold: 0.7,\n })\n\n if (p) {\n return prepend + JSON.stringify(p) + append\n } else {\n return ''\n }\n}\n", "/**\n * All errors thrown to end-users should be an instance of this class.\n */\nexport class TheatreError extends Error {}\n\n/**\n * If an end-user provided an invalid argument to a public API, the error thrown\n * should be an instance of this class.\n */\nexport class InvalidArgumentError extends TheatreError {}\n", "export interface Deferred {\n resolve: (d: PromiseType) => void\n reject: (d: unknown) => void\n promise: Promise\n status: 'pending' | 'resolved' | 'rejected'\n}\n\n/**\n * A simple imperative API for resolving/rejecting a promise.\n *\n * Example:\n * ```ts\n * function doSomethingAsync() {\n * const deferred = defer()\n *\n * setTimeout(() => {\n * if (Math.random() > 0.5) {\n * deferred.resolve('success')\n * } else {\n * deferred.reject('Something went wrong')\n * }\n * }, 1000)\n *\n * // we're just returning the promise, so that the caller cannot resolve/reject it\n * return deferred.promise\n * }\n *\n * ```\n */\nexport function defer(): Deferred {\n let resolve: (d: PromiseType) => void\n let reject: (d: unknown) => void\n const promise = new Promise((rs, rj) => {\n resolve = (v) => {\n rs(v)\n deferred.status = 'resolved'\n }\n reject = (v) => {\n rj(v)\n deferred.status = 'rejected'\n }\n })\n\n const deferred: Deferred = {\n resolve: resolve!,\n reject: reject!,\n promise,\n status: 'pending',\n }\n return deferred\n}\n", "/**\n * Just an empty function\n */\nconst noop = () => {}\n\nexport default noop\n", "import type {\n IPlaybackDirection,\n IPlaybackRange,\n} from '@theatre/core/sequences/Sequence'\nimport {defer} from '@theatre/shared/utils/defer'\nimport noop from '@theatre/shared/utils/noop'\nimport type {Prism, Pointer, Ticker} from '@theatre/dataverse'\nimport {Atom} from '@theatre/dataverse'\n\nexport interface IPlaybackState {\n position: number\n playing: boolean\n}\n\nexport interface IPlaybackController {\n getCurrentPosition(): number\n gotoPosition(position: number): void\n readonly statePointer: Pointer\n destroy(): void\n\n play(\n iterationCount: number,\n range: IPlaybackRange,\n rate: number,\n direction: IPlaybackDirection,\n ticker: Ticker,\n ): Promise\n\n /**\n * Controls the playback within a range. Repeats infinitely unless stopped.\n *\n * @remarks\n * One use case for this is to play the playback within the focus range.\n *\n * @param rangeD - The prism that contains the range that will be used for the playback\n *\n * @returns a promise that gets rejected if the playback stopped for whatever reason\n *\n */\n playDynamicRange(\n rangeD: Prism,\n ticker: Ticker,\n ): Promise\n\n pause(): void\n}\n\nexport default class DefaultPlaybackController implements IPlaybackController {\n _stopPlayCallback: () => void = noop\n private _state: Atom = new Atom({\n position: 0,\n playing: false,\n })\n readonly statePointer: Pointer\n\n constructor() {\n this.statePointer = this._state.pointer\n }\n\n destroy() {}\n\n pause() {\n this._stopPlayCallback()\n this.playing = false\n this._stopPlayCallback = noop\n }\n\n gotoPosition(time: number) {\n this._updatePositionInState(time)\n }\n\n private _updatePositionInState(time: number) {\n this._state.setByPointer((p) => p.position, time)\n }\n\n getCurrentPosition() {\n return this._state.get().position\n }\n\n get playing() {\n return this._state.get().playing\n }\n\n set playing(playing: boolean) {\n this._state.setByPointer((p) => p.playing, playing)\n }\n\n play(\n iterationCount: number,\n range: IPlaybackRange,\n rate: number,\n direction: IPlaybackDirection,\n ticker: Ticker,\n ): Promise {\n if (this.playing) {\n this.pause()\n }\n\n this.playing = true\n\n const iterationLength = range[1] - range[0]\n\n {\n const startPos = this.getCurrentPosition()\n\n if (startPos < range[0] || startPos > range[1]) {\n if (direction === 'normal' || direction === 'alternate') {\n this._updatePositionInState(range[0])\n } else if (\n direction === 'reverse' ||\n direction === 'alternateReverse'\n ) {\n this._updatePositionInState(range[1])\n }\n } else if (direction === 'normal' || direction === 'alternate') {\n if (startPos === range[1]) {\n this._updatePositionInState(range[0])\n }\n } else {\n if (startPos === range[0]) {\n this._updatePositionInState(range[1])\n }\n }\n }\n\n const deferred = defer()\n const initialTickerTime = ticker.time\n const totalPlaybackLength = iterationLength * iterationCount\n\n let initialElapsedPos = this.getCurrentPosition() - range[0]\n\n if (direction === 'reverse' || direction === 'alternateReverse') {\n initialElapsedPos = range[1] - this.getCurrentPosition()\n }\n\n const tick = (currentTickerTime: number) => {\n const elapsedTickerTime = Math.max(\n currentTickerTime - initialTickerTime,\n 0,\n )\n const elapsedTickerTimeInSeconds = elapsedTickerTime / 1000\n\n const elapsedPos = Math.min(\n elapsedTickerTimeInSeconds * rate + initialElapsedPos,\n totalPlaybackLength,\n )\n\n if (elapsedPos !== totalPlaybackLength) {\n const iterationNumber = Math.floor(elapsedPos / iterationLength)\n\n let currentIterationPos =\n ((elapsedPos / iterationLength) % 1) * iterationLength\n\n if (direction !== 'normal') {\n if (direction === 'reverse') {\n currentIterationPos = iterationLength - currentIterationPos\n } else {\n const isCurrentIterationNumberEven = iterationNumber % 2 === 0\n if (direction === 'alternate') {\n if (!isCurrentIterationNumberEven) {\n currentIterationPos = iterationLength - currentIterationPos\n }\n } else {\n if (isCurrentIterationNumberEven) {\n currentIterationPos = iterationLength - currentIterationPos\n }\n }\n }\n }\n\n this._updatePositionInState(currentIterationPos + range[0])\n requestNextTick()\n } else {\n if (direction === 'normal') {\n this._updatePositionInState(range[1])\n } else if (direction === 'reverse') {\n this._updatePositionInState(range[0])\n } else {\n const isLastIterationEven = (iterationCount - 1) % 2 === 0\n if (direction === 'alternate') {\n if (isLastIterationEven) {\n this._updatePositionInState(range[1])\n } else {\n this._updatePositionInState(range[0])\n }\n } else {\n if (isLastIterationEven) {\n this._updatePositionInState(range[0])\n } else {\n this._updatePositionInState(range[1])\n }\n }\n }\n this.playing = false\n deferred.resolve(true)\n }\n }\n\n this._stopPlayCallback = () => {\n ticker.offThisOrNextTick(tick)\n ticker.offNextTick(tick)\n\n if (this.playing) deferred.resolve(false)\n }\n const requestNextTick = () => ticker.onNextTick(tick)\n ticker.onThisOrNextTick(tick)\n return deferred.promise\n }\n\n playDynamicRange(\n rangeD: Prism,\n ticker: Ticker,\n ): Promise {\n if (this.playing) {\n this.pause()\n }\n\n this.playing = true\n\n const deferred = defer()\n\n // We're keeping the rangeD hot, so we can read from it on every tick without\n // causing unnecessary recalculations\n const untapFromRangeD = rangeD.keepHot()\n // We'll release our subscription once this promise resolves/rejects, for whatever reason\n void deferred.promise.then(untapFromRangeD, untapFromRangeD)\n\n let lastTickerTime = ticker.time\n\n const tick = (currentTickerTime: number) => {\n const elapsedSinceLastTick = Math.max(\n currentTickerTime - lastTickerTime,\n 0,\n )\n lastTickerTime = currentTickerTime\n const elapsedSinceLastTickInSeconds = elapsedSinceLastTick / 1000\n\n const lastPosition = this.getCurrentPosition()\n\n const range = rangeD.getValue()\n\n if (lastPosition < range[0] || lastPosition > range[1]) {\n this.gotoPosition(range[0])\n } else {\n let newPosition = lastPosition + elapsedSinceLastTickInSeconds\n if (newPosition > range[1]) {\n newPosition = range[0] + (newPosition - range[1])\n }\n this.gotoPosition(newPosition)\n }\n\n requestNextTick()\n }\n\n this._stopPlayCallback = () => {\n ticker.offThisOrNextTick(tick)\n ticker.offNextTick(tick)\n\n deferred.resolve(false)\n }\n const requestNextTick = () => ticker.onNextTick(tick)\n ticker.onThisOrNextTick(tick)\n return deferred.promise\n }\n}\n", "/**\n * The names of the global variables that the core or studio bundle\n * use to store their references.\n */\nexport const studioBundle = '__TheatreJS_StudioBundle'\nexport const coreBundle = '__TheatreJS_CoreBundle'\nexport const notifications = '__TheatreJS_Notifications'\n", "import logger from './logger'\nimport * as globalVariableNames from './globalVariableNames'\n\nexport type Notification = {title: string; message: string}\nexport type NotificationType = 'info' | 'success' | 'warning' | 'error'\nexport type Notify = (\n /**\n * The title of the notification.\n */\n title: string,\n /**\n * The message of the notification.\n */\n message: string,\n /**\n * An array of doc pages to link to.\n */\n docs?: {url: string; title: string}[],\n /**\n * Whether duplicate notifications should be allowed.\n */\n allowDuplicates?: boolean,\n) => void\nexport type Notifiers = {\n /**\n * Show a success notification.\n */\n success: Notify\n /**\n * Show a warning notification.\n *\n * Say what happened in the title.\n * In the message, start with 1) a reassurance, then 2) explain why it happened, and 3) what the user can do about it.\n */\n warning: Notify\n /**\n * Show an info notification.\n */\n info: Notify\n /**\n * Show an error notification.\n */\n error: Notify\n}\n\nconst createHandler =\n (type: NotificationType): Notify =>\n (...args) => {\n switch (type) {\n case 'success': {\n logger.debug(args.slice(0, 2).join('\\n'))\n break\n }\n case 'info': {\n logger.debug(args.slice(0, 2).join('\\n'))\n break\n }\n case 'warning': {\n logger.warn(args.slice(0, 2).join('\\n'))\n break\n }\n case 'error': {\n // don't log errors, they're already logged by the browser\n }\n }\n\n return typeof window !== 'undefined'\n ? // @ts-ignore\n window[globalVariableNames.notifications]?.notify[type](...args)\n : undefined\n }\n\nexport const notify: Notifiers = {\n warning: createHandler('warning'),\n success: createHandler('success'),\n info: createHandler('info'),\n error: createHandler('error'),\n}\n\nif (typeof window !== 'undefined') {\n window.addEventListener('error', (e) => {\n notify.error(\n `An error occurred`,\n `

${e.message}
\\n\\nSee **console** for details.`,\n )\n })\n\n window.addEventListener('unhandledrejection', (e) => {\n notify.error(\n `An error occurred`,\n `
${e.reason}
\\n\\nSee **console** for details.`,\n )\n })\n}\n", "import type {\n IPlaybackDirection,\n IPlaybackRange,\n} from '@theatre/core/sequences/Sequence'\nimport {defer} from '@theatre/shared/utils/defer'\nimport {InvalidArgumentError} from '@theatre/shared/utils/errors'\nimport noop from '@theatre/shared/utils/noop'\nimport type {Prism, Pointer, Ticker} from '@theatre/dataverse'\nimport {Atom} from '@theatre/dataverse'\nimport type {\n IPlaybackController,\n IPlaybackState,\n} from './DefaultPlaybackController'\nimport {notify} from '@theatre/shared/notify'\n\nexport default class AudioPlaybackController implements IPlaybackController {\n _mainGain: GainNode\n private _state: Atom = new Atom({\n position: 0,\n playing: false,\n })\n readonly statePointer: Pointer\n _stopPlayCallback: () => void = noop\n\n constructor(\n private readonly _decodedBuffer: AudioBuffer,\n private readonly _audioContext: AudioContext,\n private readonly _nodeDestination: AudioNode,\n ) {\n this.statePointer = this._state.pointer\n\n this._mainGain = this._audioContext.createGain()\n this._mainGain.connect(this._nodeDestination)\n }\n\n playDynamicRange(\n rangeD: Prism,\n ticker: Ticker,\n ): Promise {\n const deferred = defer()\n if (this._playing) this.pause()\n\n this._playing = true\n\n let stop: undefined | (() => void) = undefined\n\n const play = () => {\n stop?.()\n stop = this._loopInRange(rangeD.getValue(), ticker).stop\n }\n\n // We're keeping the rangeD hot, so we can read from it on every tick without\n // causing unnecessary recalculations\n const untapFromRangeD = rangeD.onStale(play)\n play()\n\n this._stopPlayCallback = () => {\n stop?.()\n untapFromRangeD()\n deferred.resolve(false)\n }\n\n return deferred.promise\n }\n\n private _loopInRange(\n range: IPlaybackRange,\n ticker: Ticker,\n ): {stop: () => void} {\n const rate = 1\n let startPos = this.getCurrentPosition()\n const iterationLength = range[1] - range[0]\n\n if (startPos < range[0] || startPos > range[1]) {\n // if we're currently out of the range\n this._updatePositionInState(range[0])\n } else if (startPos === range[1]) {\n // if we're currently at the very end of the range\n this._updatePositionInState(range[0])\n }\n startPos = this.getCurrentPosition()\n\n const currentSource = this._audioContext.createBufferSource()\n currentSource.buffer = this._decodedBuffer\n currentSource.connect(this._mainGain)\n currentSource.playbackRate.value = rate\n\n currentSource.loop = true\n currentSource.loopStart = range[0]\n currentSource.loopEnd = range[1]\n\n const initialTickerTime = ticker.time\n let initialElapsedPos = startPos - range[0]\n\n currentSource.start(0, startPos)\n\n const tick = (currentTickerTime: number) => {\n const elapsedTickerTime = Math.max(\n currentTickerTime - initialTickerTime,\n 0,\n )\n const elapsedTickerTimeInSeconds = elapsedTickerTime / 1000\n\n const elapsedPos = elapsedTickerTimeInSeconds * rate + initialElapsedPos\n\n let currentIterationPos =\n ((elapsedPos / iterationLength) % 1) * iterationLength\n\n this._updatePositionInState(currentIterationPos + range[0])\n requestNextTick()\n }\n\n const requestNextTick = () => ticker.onNextTick(tick)\n ticker.onThisOrNextTick(tick)\n\n const stop = () => {\n currentSource.stop()\n currentSource.disconnect()\n ticker.offThisOrNextTick(tick)\n ticker.offNextTick(tick)\n }\n\n return {stop}\n }\n\n private get _playing() {\n return this._state.get().playing\n }\n\n private set _playing(playing: boolean) {\n this._state.setByPointer((p) => p.playing, playing)\n }\n\n destroy() {}\n\n pause() {\n this._stopPlayCallback()\n this._playing = false\n this._stopPlayCallback = noop\n }\n\n gotoPosition(time: number) {\n this._updatePositionInState(time)\n }\n\n private _updatePositionInState(time: number) {\n this._state.reduce((s) => ({...s, position: time}))\n }\n\n getCurrentPosition() {\n return this._state.get().position\n }\n\n play(\n iterationCount: number,\n range: IPlaybackRange,\n rate: number,\n direction: IPlaybackDirection,\n ticker: Ticker,\n ): Promise {\n if (this._playing) {\n this.pause()\n }\n\n this._playing = true\n\n let startPos = this.getCurrentPosition()\n const iterationLength = range[1] - range[0]\n\n if (direction !== 'normal') {\n throw new InvalidArgumentError(\n `Audio-controlled sequences can only be played in the \"normal\" direction. ` +\n `'${direction}' given.`,\n )\n }\n\n if (startPos < range[0] || startPos > range[1]) {\n // if we're currently out of the range\n this._updatePositionInState(range[0])\n } else if (startPos === range[1]) {\n // if we're currently at the very end of the range\n this._updatePositionInState(range[0])\n }\n startPos = this.getCurrentPosition()\n\n const deferred = defer()\n\n const currentSource = this._audioContext.createBufferSource()\n currentSource.buffer = this._decodedBuffer\n currentSource.connect(this._mainGain)\n currentSource.playbackRate.value = rate\n\n if (iterationCount > 1000) {\n notify.warning(\n \"Can't play sequences with audio more than 1000 times\",\n `The sequence will still play, but only 1000 times. The \\`iterationCount: ${iterationCount}\\` provided to \\`sequence.play()\\`\nis too high for a sequence with audio.\n\nTo fix this, either set \\`iterationCount\\` to a lower value, or remove the audio from the sequence.`,\n [\n {\n url: 'https://www.theatrejs.com/docs/latest/manual/audio',\n title: 'Using Audio',\n },\n {\n url: 'https://www.theatrejs.com/docs/latest/api/core#sequence.attachaudio',\n title: 'Audio API',\n },\n ],\n )\n iterationCount = 1000\n }\n\n if (iterationCount > 1) {\n currentSource.loop = true\n currentSource.loopStart = range[0]\n currentSource.loopEnd = range[1]\n }\n\n const initialTickerTime = ticker.time\n let initialElapsedPos = startPos - range[0]\n const totalPlaybackLength = iterationLength * iterationCount\n\n currentSource.start(0, startPos, totalPlaybackLength - initialElapsedPos)\n\n const tick = (currentTickerTime: number) => {\n const elapsedTickerTime = Math.max(\n currentTickerTime - initialTickerTime,\n 0,\n )\n const elapsedTickerTimeInSeconds = elapsedTickerTime / 1000\n\n const elapsedPos = Math.min(\n elapsedTickerTimeInSeconds * rate + initialElapsedPos,\n totalPlaybackLength,\n )\n\n if (elapsedPos !== totalPlaybackLength) {\n let currentIterationPos =\n ((elapsedPos / iterationLength) % 1) * iterationLength\n\n this._updatePositionInState(currentIterationPos + range[0])\n requestNextTick()\n } else {\n this._updatePositionInState(range[1])\n this._playing = false\n cleanup()\n deferred.resolve(true)\n }\n }\n\n const cleanup = () => {\n currentSource.stop()\n currentSource.disconnect()\n }\n\n this._stopPlayCallback = () => {\n cleanup()\n ticker.offThisOrNextTick(tick)\n ticker.offNextTick(tick)\n\n if (this._playing) deferred.resolve(false)\n }\n const requestNextTick = () => ticker.onNextTick(tick)\n ticker.onThisOrNextTick(tick)\n return deferred.promise\n }\n}\n", "import {Ticker} from '@theatre/dataverse'\nimport {setPrivateAPI} from './privateAPIs'\n\nexport interface IRafDriver {\n /**\n * All raf derivers have have `driver.type === 'Theatre_RafDriver_PublicAPI'`\n */\n readonly type: 'Theatre_RafDriver_PublicAPI'\n /**\n * The name of the driver. This is used for debugging purposes.\n */\n name: string\n /**\n * The id of the driver. This is used for debugging purposes.\n * It's guaranteed to be unique.\n */\n id: number\n /**\n * This is called by the driver when it's time to tick forward.\n * The time param is of the same type returned by `performance.now()`.\n */\n tick: (time: number) => void\n}\n\nexport interface RafDriverPrivateAPI {\n readonly type: 'Theatre_RafDriver_PrivateAPI'\n publicApi: IRafDriver\n ticker: Ticker\n start?: () => void\n stop?: () => void\n}\n\nlet lastDriverId = 0\n\n/**\n * Creates a custom raf driver.\n * `rafDriver`s allow you to control when and how often computations in Theatre tick forward. (raf stands for [`requestAnimationFrame`](https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame)).\n * The default `rafDriver` in Theatre creates a `raf` loop and ticks forward on each frame. You can create your own `rafDriver`, which enables the following use-cases:\n *\n * 1. When using Theatre.js alongside other animation libs (`@react-three/fiber`/`gsap`/`lenis`/`etc`), you'd want all animation libs to use a single `raf` loop to keep the libraries in sync and also to get better performance.\n * 2. In XR sessions, you'd want Theatre to tick forward using [`xr.requestAnimationFrame()`](https://developer.mozilla.org/en-US/docs/Web/API/XRSession/requestAnimationFrame).\n * 3. In some advanced cases, you'd just want to manually tick forward (many ticks per frame, or skipping many frames, etc). This is useful for recording an animation, rendering to a file, testing an animation, running benchmarks, etc.\n *\n * Here is how you'd create a custom `rafDriver`:\n *\n * ```js\n * import { createRafDriver } from '@theatre/core'\n *\n * const rafDriver = createRafDriver({ name: 'a custom 5fps raf driver' })\n *\n * setInterval(() => {\n * rafDriver.tick(performance.now())\n * }, 200)\n * ```\n *\n * Now, any time you set up an `onChange()` listener, pass your custom `rafDriver`:\n *\n * ```js\n * import { onChange } from '@theatre/core'\n *\n * onChange(\n * // let's say object is a Theatre object, the one returned from calling `sheet.object()`\n * object.props,\n * // this callback will now only be called at 5fps (and won't be called if there are no new values)\n * // even if `sequence.play()` updates `object.props` at 60fps, this listener is called a maximum of 5fps\n * (propValues) => {\n * console.log(propValues)\n * },\n * rafDriver,\n * )\n *\n * // this will update the values of `object.props` at 60fps, but the listener above will still get called a maximum of 5fps\n * sheet.sequence.play()\n *\n * // we can also customize at what resolution the sequence's playhead moves forward\n * sheet.sequence.play({ rafDriver }) // the playhead will move forward at 5fps\n * ```\n *\n * You can optionally make studio use this `rafDriver`. This means the parts of the studio that tick based on raf, will now tick at 5fps. This is only useful if you're doing something crazy like running the studio (and not the core) in an XR frame.\n *\n * ```js\n * studio.initialize({\n * __experimental_rafDriver: rafDriver,\n * })\n * ```\n *\n * `rafDriver`s can optionally provide a `start/stop` callback. Theatre will call `start()` when it actually has computations scheduled, and will call `stop` if there is nothing to update after a few ticks:\n *\n * ```js\n * import { createRafDriver } from '@theatre/core'\n * import type { IRafDriver } from '@theare/core'\n *\n * function createBasicRafDriver(): IRafDriver {\n * let rafId: number | null = null\n * const start = (): void => {\n * if (typeof window !== 'undefined') {\n * const onAnimationFrame = (t: number) => {\n * driver.tick(t)\n * rafId = window.requestAnimationFrame(onAnimationFrame)\n * }\n * rafId = window.requestAnimationFrame(onAnimationFrame)\n * } else {\n * driver.tick(0)\n * setTimeout(() => driver.tick(1), 0)\n * }\n * }\n *\n * const stop = (): void => {\n * if (typeof window !== 'undefined') {\n * if (rafId !== null) {\n * window.cancelAnimationFrame(rafId)\n * }\n * } else {\n * // nothing to do in SSR\n * }\n * }\n *\n * const driver = createRafDriver({ name: 'DefaultCoreRafDriver', start, stop })\n *\n * return driver\n * }\n * ```\n */\nexport function createRafDriver(conf?: {\n name?: string\n start?: () => void\n stop?: () => void\n}): IRafDriver {\n const tick = (time: number): void => {\n ticker.tick(time)\n }\n\n const ticker = new Ticker({\n onActive() {\n conf?.start?.()\n },\n onDormant() {\n conf?.stop?.()\n },\n })\n\n const driverPublicApi: IRafDriver = {\n tick,\n id: lastDriverId++,\n name: conf?.name ?? `CustomRafDriver-${lastDriverId}`,\n type: 'Theatre_RafDriver_PublicAPI',\n }\n\n const driverPrivateApi: RafDriverPrivateAPI = {\n type: 'Theatre_RafDriver_PrivateAPI',\n publicApi: driverPublicApi,\n ticker,\n start: conf?.start,\n stop: conf?.stop,\n }\n\n setPrivateAPI(driverPublicApi, driverPrivateApi)\n\n return driverPublicApi\n}\n", "import type {Ticker} from '@theatre/dataverse'\nimport {privateAPI} from './privateAPIs'\nimport type {IRafDriver, RafDriverPrivateAPI} from './rafDrivers'\nimport {createRafDriver} from './rafDrivers'\n\n/**\n * Creates a rafDrive that uses `window.requestAnimationFrame` in browsers,\n * or a single `setTimeout` in SSR.\n */\nfunction createBasicRafDriver(): IRafDriver {\n let rafId: number | null = null\n const start = (): void => {\n if (typeof window !== 'undefined') {\n const onAnimationFrame = (t: number) => {\n driver.tick(t)\n rafId = window.requestAnimationFrame(onAnimationFrame)\n }\n rafId = window.requestAnimationFrame(onAnimationFrame)\n } else {\n driver.tick(0)\n setTimeout(() => driver.tick(1), 0)\n }\n }\n\n const stop = (): void => {\n if (typeof window !== 'undefined') {\n if (rafId !== null) {\n window.cancelAnimationFrame(rafId)\n }\n } else {\n // nothing to do in SSR\n }\n }\n\n const driver = createRafDriver({name: 'DefaultCoreRafDriver', start, stop})\n\n return driver\n}\n\nlet coreRafDriver: RafDriverPrivateAPI | undefined\n\n/**\n * Returns the rafDriver that is used by the core internally. Creates a new one if it's not set yet.\n */\nexport function getCoreRafDriver(): RafDriverPrivateAPI {\n if (!coreRafDriver) {\n setCoreRafDriver(createBasicRafDriver())\n }\n return coreRafDriver!\n}\n\n/**\n *\n * @returns The ticker that is used by the core internally.\n */\nexport function getCoreTicker(): Ticker {\n return getCoreRafDriver().ticker\n}\n\n/**\n * Sets the rafDriver that is used by the core internally.\n */\nexport function setCoreRafDriver(driver: IRafDriver) {\n if (coreRafDriver) {\n throw new Error(`\\`setCoreRafDriver()\\` is already called.`)\n }\n const driverPrivateApi = privateAPI(driver)\n coreRafDriver = driverPrivateApi\n}\n", "import {privateAPI, setPrivateAPI} from '@theatre/core/privateAPIs'\nimport {defer} from '@theatre/shared/utils/defer'\nimport type Sequence from './Sequence'\nimport type {IPlaybackDirection, IPlaybackRange} from './Sequence'\nimport type {Keyframe} from '@theatre/core/projects/store/types/SheetState_Historic'\nimport AudioPlaybackController from './playbackControllers/AudioPlaybackController'\nimport {getCoreTicker} from '@theatre/core/coreTicker'\nimport type {Pointer} from '@theatre/dataverse'\nimport {notify} from '@theatre/shared/notify'\nimport type {IRafDriver} from '@theatre/core/rafDrivers'\n\ninterface IAttachAudioArgs {\n /**\n * Either a URL to the audio file (eg \"http://localhost:3000/audio.mp3\") or an instance of AudioBuffer\n */\n source: string | AudioBuffer\n /**\n * An optional AudioContext. If not provided, one will be created.\n */\n audioContext?: AudioContext\n /**\n * An AudioNode to feed the audio into. Will use audioContext.destination if not provided.\n */\n destinationNode?: AudioNode\n}\n\nexport interface ISequence {\n readonly type: 'Theatre_Sequence_PublicAPI'\n\n /**\n * Starts playback of a sequence.\n * Returns a promise that either resolves to true when the playback completes,\n * or resolves to false if playback gets interrupted (for example by calling sequence.pause())\n *\n * @returns A promise that resolves when the playback is finished, or rejects if interruped\n *\n * @example\n * Usage:\n * ```ts\n * // plays the sequence from the current position to sequence.length\n * sheet.sequence.play()\n *\n * // plays the sequence at 2.4x speed\n * sheet.sequence.play({rate: 2.4})\n *\n * // plays the sequence from second 1 to 4\n * sheet.sequence.play({range: [1, 4]})\n *\n * // plays the sequence 4 times\n * sheet.sequence.play({iterationCount: 4})\n *\n * // plays the sequence in reverse\n * sheet.sequence.play({direction: 'reverse'})\n *\n * // plays the sequence back and forth forever (until interrupted)\n * sheet.sequence.play({iterationCount: Infinity, direction: 'alternateReverse})\n *\n * // plays the sequence and logs \"done\" once playback is finished\n * sheet.sequence.play().then(() => console.log('done'))\n * ```\n */\n play(conf?: {\n /**\n * The number of times the animation must run. Must be an integer larger\n * than 0. Defaults to 1. Pick Infinity to run forever\n */\n iterationCount?: number\n /**\n * Limits the range to be played. Default is [0, sequence.length]\n */\n range?: IPlaybackRange\n /**\n * The playback rate. Defaults to 1. Choosing 2 would play the animation\n * at twice the speed.\n */\n rate?: number\n /**\n * The direction of the playback. Similar to CSS's animation-direction\n */\n direction?: IPlaybackDirection\n\n /**\n * Optionally provide a rafDriver to use for the playback. It'll default to\n * the core driver if not provided, which is a `requestAnimationFrame()` driver.\n * Learn how to use `rafDriver`s [from the docs](https://www.theatrejs.com/docs/latest/manual/advanced#rafdrivers).\n */\n rafDriver?: IRafDriver\n }): Promise\n\n /**\n * Pauses the currently playing animation\n */\n pause(): void\n\n /**\n * The current position of the playhead.\n * In a time-based sequence, this represents the current time in seconds.\n */\n position: number\n\n /**\n * A Pointer to the sequence's inner state.\n *\n * @remarks\n * As with any Pointer, you can use this with {@link onChange | onChange()} to listen to its value changes\n * or with {@link val | val()} to read its current value.\n *\n * @example Usage\n * ```ts\n * import {onChange, val} from '@theatre/core'\n *\n * // let's assume `sheet` is a sheet\n * const sequence = sheet.sequence\n *\n * onChange(sequence.pointer.length, (len) => {\n * console.log(\"Length of the sequence changed to:\", len)\n * })\n *\n * onChange(sequence.pointer.position, (position) => {\n * console.log(\"Position of the sequence changed to:\", position)\n * })\n *\n * onChange(sequence.pointer.playing, (playing) => {\n * console.log(playing ? 'playing' : 'paused')\n * })\n *\n * // we can also read the current value of the pointer\n * console.log('current length is', val(sequence.pointer.length))\n * ```\n */\n pointer: Pointer<{\n playing: boolean\n length: number\n position: number\n }>\n\n /**\n * Given a property, returns a list of keyframes that affect that property.\n *\n * @example\n * Usage:\n * ```ts\n * // let's assume `sheet` is a sheet and obj is one of its objects\n * const keyframes = sheet.sequence.__experimental_getKeyframes(obj.pointer.x)\n * console.log(keyframes) // an array of keyframes\n * ```\n */\n __experimental_getKeyframes(prop: Pointer<{}>): Keyframe[]\n\n /**\n * Attaches an audio source to the sequence. Playing the sequence automatically\n * plays the audio source and their times are kept in sync.\n *\n * @returns A promise that resolves once the audio source is loaded and decoded\n *\n * Learn more [here](https://www.theatrejs.com/docs/latest/manual/audio).\n *\n * @example\n * Usage:\n * ```ts\n * // Loads and decodes audio from the URL and then attaches it to the sequence\n * await sheet.sequence.attachAudio({source: \"http://localhost:3000/audio.mp3\"})\n * sheet.sequence.play()\n *\n * // Providing your own AudioAPI Context, destination, etc\n * const audioContext: AudioContext = {...} // create an AudioContext using the Audio API\n * const audioBuffer: AudioBuffer = {...} // create an AudioBuffer\n * const destinationNode = audioContext.destination\n *\n * await sheet.sequence.attachAudio({source: audioBuffer, audioContext, destinationNode})\n * ```\n *\n * Note: It's better to provide the `audioContext` rather than allow Theatre.js to create it.\n * That's because some browsers [suspend the audioContext](https://developer.chrome.com/blog/autoplay/#webaudio)\n * unless it's initiated by a user gesture, like a click. If that happens, Theatre.js will\n * wait for a user gesture to resume the audioContext. But that's probably not an\n * optimal user experience. It is better to provide a button or some other UI element\n * to communicate to the user that they have to initiate the animation.\n *\n * @example\n * Example:\n * ```ts\n * // html: \n * const button = document.getElementById('start')\n *\n * button.addEventListener('click', async () => {\n * const audioContext = ...\n * await sheet.sequence.attachAudio({audioContext, source: '...'})\n * sheet.sequence.play()\n * })\n * ```\n */\n attachAudio(args: IAttachAudioArgs): Promise<{\n /**\n * An {@link https://developer.mozilla.org/en-US/docs/Web/API/AudioBuffer | AudioBuffer}.\n * If `args.source` is a URL, then `decodedBuffer` would be the result\n * of {@link https://developer.mozilla.org/en-US/docs/Web/API/BaseAudioContext/decodeAudioData | audioContext.decodeAudioData()}\n * on the audio file at that URL.\n *\n * If `args.source` is an `AudioBuffer`, then `decodedBuffer` would be equal to `args.source`\n */\n decodedBuffer: AudioBuffer\n /**\n * The `AudioContext`. It is either equal to `source.audioContext` if it is provided, or\n * one that's created on the fly.\n */\n audioContext: AudioContext\n /**\n * Equals to either `args.destinationNode`, or if none is provided, it equals `audioContext.destinationNode`.\n *\n * See `gainNode` for more info.\n */\n destinationNode: AudioNode\n\n /**\n * This is an intermediate GainNode that Theatre.js feeds its audio to. It is by default\n * connected to destinationNode, but you can disconnect the gainNode and feed it to your own graph.\n *\n * @example\n * For example:\n * ```ts\n * const {gainNode, audioContext} = await sequence.attachAudio({source: '/audio.mp3'})\n * // disconnect the gainNode (at this point, the sequence's audio track won't be audible)\n * gainNode.disconnect()\n * // create our own gain node\n * const lowerGain = audioContext.createGain()\n * // lower its volume to 10%\n * lowerGain.gain.setValueAtTime(0.1, audioContext.currentTime)\n * // feed the sequence's audio to our lowered gainNode\n * gainNode.connect(lowerGain)\n * // feed the lowered gainNode to the audioContext's destination\n * lowerGain.connect(audioContext.destination)\n * // now audio will be audible, with 10% the volume\n * ```\n */\n gainNode: GainNode\n }>\n}\n\nexport default class TheatreSequence implements ISequence {\n get type(): 'Theatre_Sequence_PublicAPI' {\n return 'Theatre_Sequence_PublicAPI'\n }\n\n /**\n * @internal\n */\n constructor(sheet: Sequence) {\n setPrivateAPI(this, sheet)\n }\n\n play(\n conf?: Partial<{\n iterationCount: number\n range: IPlaybackRange\n rate: number\n direction: IPlaybackDirection\n rafDriver: IRafDriver\n }>,\n ): Promise {\n const priv = privateAPI(this)\n if (priv._project.isReady()) {\n const ticker = conf?.rafDriver\n ? privateAPI(conf.rafDriver).ticker\n : getCoreTicker()\n return priv.play(conf ?? {}, ticker)\n } else {\n if (process.env.NODE_ENV !== 'production') {\n notify.warning(\n \"Sequence can't be played\",\n 'You seem to have called `sequence.play()` before the project has finished loading.\\n\\n' +\n 'This would **not** a problem in production when using `@theatre/core`, since Theatre.js loads instantly in core mode. ' +\n \"However, when using `@theatre/studio`, it takes a few milliseconds for it to load your project's state, \" +\n `before which your sequences cannot start playing.\\n` +\n `\\n` +\n 'To fix this, simply defer calling `sequence.play()` until after the project is loaded, like this:\\n\\n' +\n '```\\n' +\n `project.ready.then(() => {\\n` +\n ` sequence.play()\\n` +\n `})\\n` +\n '```',\n [\n {\n url: 'https://www.theatrejs.com/docs/0.5/api/core#project.ready',\n title: 'Project.ready',\n },\n ],\n )\n }\n const d = defer()\n d.resolve(true)\n return d.promise\n }\n }\n\n pause() {\n privateAPI(this).pause()\n }\n\n get position() {\n return privateAPI(this).position\n }\n\n set position(position: number) {\n privateAPI(this).position = position\n }\n\n __experimental_getKeyframes(prop: Pointer): Keyframe[] {\n return privateAPI(this).getKeyframesOfSimpleProp(prop)\n }\n\n async attachAudio(args: IAttachAudioArgs): Promise<{\n decodedBuffer: AudioBuffer\n audioContext: AudioContext\n destinationNode: AudioNode\n gainNode: GainNode\n }> {\n const {audioContext, destinationNode, decodedBuffer, gainNode} =\n await resolveAudioBuffer(args)\n\n const playbackController = new AudioPlaybackController(\n decodedBuffer,\n audioContext,\n gainNode,\n )\n\n privateAPI(this).replacePlaybackController(playbackController)\n\n return {audioContext, destinationNode, decodedBuffer, gainNode}\n }\n\n get pointer(): ISequence['pointer'] {\n return privateAPI(this).pointer\n }\n}\n\nasync function resolveAudioBuffer(args: IAttachAudioArgs): Promise<{\n decodedBuffer: AudioBuffer\n audioContext: AudioContext\n destinationNode: AudioNode\n gainNode: GainNode\n}> {\n function getAudioContext(): Promise {\n if (args.audioContext) return Promise.resolve(args.audioContext)\n const ctx = new AudioContext()\n if (ctx.state === 'running') return Promise.resolve(ctx)\n\n // AudioContext is suspended, probably because the browser\n // has blocked it since it is not initiated by a user gesture\n\n // if in SSR, just resolve the promise, as there is not much more to be done\n if (typeof window === 'undefined') {\n return Promise.resolve(ctx)\n }\n return new Promise((resolve) => {\n const listener = () => {\n ctx.resume().catch((err) => {\n console.error(err)\n })\n }\n\n const eventsToHookInto: Array = [\n 'mousedown',\n 'keydown',\n 'touchstart',\n ]\n\n const eventListenerOpts = {capture: true, passive: false}\n eventsToHookInto.forEach((eventName) => {\n window.addEventListener(eventName, listener, eventListenerOpts)\n })\n\n ctx.addEventListener('statechange', () => {\n if (ctx.state === 'running') {\n eventsToHookInto.forEach((eventName) => {\n window.removeEventListener(eventName, listener, eventListenerOpts)\n })\n resolve(ctx)\n }\n })\n })\n }\n\n async function getAudioBuffer(): Promise {\n if (args.source instanceof AudioBuffer) {\n return args.source\n }\n\n const decodedBufferDeferred = defer()\n if (typeof args.source !== 'string') {\n throw new Error(\n `Error validating arguments to sequence.attachAudio(). ` +\n `args.source must either be a string or an instance of AudioBuffer.`,\n )\n }\n\n let fetchResponse\n try {\n fetchResponse = await fetch(args.source)\n } catch (e) {\n console.error(e)\n throw new Error(\n `Could not fetch '${args.source}'. Network error logged above.`,\n )\n }\n\n let arrayBuffer\n try {\n arrayBuffer = await fetchResponse.arrayBuffer()\n } catch (e) {\n console.error(e)\n throw new Error(`Could not read '${args.source}' as an arrayBuffer.`)\n }\n\n const audioContext = await audioContextPromise\n\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n audioContext.decodeAudioData(\n arrayBuffer,\n decodedBufferDeferred.resolve,\n decodedBufferDeferred.reject,\n )\n\n let decodedBuffer\n try {\n decodedBuffer = await decodedBufferDeferred.promise\n } catch (e) {\n console.error(e)\n throw new Error(`Could not decode ${args.source} as an audio file.`)\n }\n\n return decodedBuffer\n }\n\n const audioContextPromise = getAudioContext()\n const audioBufferPromise = getAudioBuffer()\n\n const [audioContext, decodedBuffer] = await Promise.all([\n audioContextPromise,\n audioBufferPromise,\n ])\n\n const destinationNode = args.destinationNode || audioContext.destination\n const gainNode = audioContext.createGain()\n gainNode.connect(destinationNode)\n\n return {\n audioContext,\n decodedBuffer,\n gainNode,\n destinationNode,\n }\n}\n", "import type {IProject, ISheet, ISheetObject} from '@theatre/core'\nimport type Project from '@theatre/core/projects/Project'\nimport type SheetObject from '@theatre/core/sheetObjects/SheetObject'\nimport type SheetObjectTemplate from '@theatre/core/sheetObjects/SheetObjectTemplate'\nimport type Sheet from '@theatre/core/sheets/Sheet'\nimport type SheetTemplate from '@theatre/core/sheets/SheetTemplate'\nimport type {$IntentionalAny} from './utils/types'\n\n/**\n * Since \\@theatre/core and \\@theatre/studio are separate bundles,\n * they cannot use `x instanceof Y` to detect object types.\n *\n * The functions in this module are supposed to be a replacement for that.\n */\n\nexport const isProject = typeAsserter('Theatre_Project')\n\nexport const isSheet = typeAsserter('Theatre_Sheet')\nexport const isSheetTemplate = typeAsserter(\n 'Theatre_SheetTemplate',\n)\n\nexport const isSheetObject = typeAsserter('Theatre_SheetObject')\n\nexport const isSheetObjectTemplate = typeAsserter(\n 'Theatre_SheetObjectTemplate',\n)\n\nexport const isProjectPublicAPI = typeAsserter(\n 'Theatre_Project_PublicAPI',\n)\n\nexport const isSheetPublicAPI = typeAsserter('Theatre_Sheet_PublicAPI')\n\nexport const isSheetObjectPublicAPI = typeAsserter(\n 'Theatre_SheetObject_PublicAPI',\n)\n\nfunction typeAsserter(\n t: T['type'],\n): (v: unknown) => v is T {\n return (v: unknown): v is T =>\n typeof v === 'object' && !!v && (v as $IntentionalAny).type === t\n}\n", "import type Project from '@theatre/core/projects/Project'\nimport type Sheet from '@theatre/core/sheets/Sheet'\nimport {encodePathToProp} from '@theatre/shared/utils/addresses'\nimport type {SequenceAddress} from '@theatre/shared/utils/addresses'\nimport didYouMean from '@theatre/shared/utils/didYouMean'\nimport {InvalidArgumentError} from '@theatre/shared/utils/errors'\nimport type {\n Prism,\n Pointer,\n Ticker,\n PointerToPrismProvider,\n} from '@theatre/dataverse'\nimport {getPointerParts} from '@theatre/dataverse'\nimport {Atom} from '@theatre/dataverse'\nimport {pointer} from '@theatre/dataverse'\nimport {prism, val} from '@theatre/dataverse'\nimport {padStart} from 'lodash-es'\nimport type {\n IPlaybackController,\n IPlaybackState,\n} from './playbackControllers/DefaultPlaybackController'\nimport DefaultPlaybackController from './playbackControllers/DefaultPlaybackController'\nimport TheatreSequence from './TheatreSequence'\nimport type {Keyframe} from '@theatre/core/projects/store/types/SheetState_Historic'\nimport type {ILogger} from '@theatre/shared/logger'\nimport type {ISequence} from '..'\nimport {notify} from '@theatre/shared/notify'\nimport type {$IntentionalAny} from '@theatre/dataverse/src/types'\nimport {isSheetObject} from '@theatre/shared/instanceTypes'\n\nexport type IPlaybackRange = [from: number, to: number]\n\nexport type IPlaybackDirection =\n | 'normal'\n | 'reverse'\n | 'alternate'\n | 'alternateReverse'\n\nconst possibleDirections = [\n 'normal',\n 'reverse',\n 'alternate',\n 'alternateReverse',\n]\n\nexport default class Sequence implements PointerToPrismProvider {\n public readonly address: SequenceAddress\n publicApi: TheatreSequence\n\n private _playbackControllerBox: Atom\n private _prismOfStatePointer: Prism>\n private _positionD: Prism\n private _positionFormatterD: Prism\n _playableRangeD: undefined | Prism<{start: number; end: number}>\n\n readonly pointer: ISequence['pointer'] = pointer({root: this, path: []})\n readonly $$isPointerToPrismProvider = true\n readonly _logger: ILogger\n\n constructor(\n readonly _project: Project,\n readonly _sheet: Sheet,\n readonly _lengthD: Prism,\n readonly _subUnitsPerUnitD: Prism,\n playbackController?: IPlaybackController,\n ) {\n this._logger = _project._logger\n .named('Sheet', _sheet.address.sheetId)\n .named('Instance', _sheet.address.sheetInstanceId)\n\n this.address = {...this._sheet.address, sequenceName: 'default'}\n\n this.publicApi = new TheatreSequence(this)\n\n this._playbackControllerBox = new Atom(\n playbackController ?? new DefaultPlaybackController(),\n )\n\n this._prismOfStatePointer = prism(\n () => this._playbackControllerBox.prism.getValue().statePointer,\n )\n\n this._positionD = prism(() => {\n const statePointer = this._prismOfStatePointer.getValue()\n return val(statePointer.position)\n })\n\n this._positionFormatterD = prism(() => {\n const subUnitsPerUnit = val(this._subUnitsPerUnitD)\n return new TimeBasedPositionFormatter(subUnitsPerUnit)\n })\n }\n\n pointerToPrism(pointer: Pointer): Prism {\n const {path} = getPointerParts(pointer)\n if (path.length === 0) {\n return prism((): ISequence['pointer']['$$__pointer_type'] => ({\n length: val(this.pointer.length),\n playing: val(this.pointer.playing),\n position: val(this.pointer.position),\n })) as $IntentionalAny as Prism\n }\n if (path.length > 1) {\n return prism(() => undefined) as $IntentionalAny as Prism\n }\n const [prop] = path\n if (prop === 'length') {\n return this._lengthD as $IntentionalAny as Prism\n } else if (prop === 'position') {\n return this._positionD as $IntentionalAny as Prism\n } else if (prop === 'playing') {\n return prism(() => {\n return val(this._prismOfStatePointer.getValue().playing)\n }) as $IntentionalAny as Prism\n } else {\n return prism(() => undefined) as $IntentionalAny as Prism\n }\n }\n\n /**\n * Takes a pointer to a property of a SheetObject and returns the keyframes of that property.\n *\n * Theoretically, this method can be called from inside a prism so it can be reactive.\n */\n getKeyframesOfSimpleProp(prop: Pointer): Keyframe[] {\n const {path, root} = getPointerParts(prop)\n\n if (!isSheetObject(root)) {\n throw new InvalidArgumentError(\n 'Argument prop must be a pointer to a SheetObject property',\n )\n }\n\n const trackP = val(\n this._project.pointers.historic.sheetsById[this._sheet.address.sheetId]\n .sequence.tracksByObject[root.address.objectKey],\n )\n\n if (!trackP) {\n return []\n }\n\n const {trackData, trackIdByPropPath} = trackP\n const objectAddress = encodePathToProp(path)\n const id = trackIdByPropPath[objectAddress]\n\n if (!id) {\n return []\n }\n\n const track = trackData[id]\n\n if (!track) {\n return []\n }\n\n return track.keyframes\n }\n\n get positionFormatter(): ISequencePositionFormatter {\n return this._positionFormatterD.getValue()\n }\n\n get prismOfStatePointer() {\n return this._prismOfStatePointer\n }\n\n get length() {\n return this._lengthD.getValue()\n }\n\n get positionPrism() {\n return this._positionD\n }\n\n get position() {\n return this._playbackControllerBox.get().getCurrentPosition()\n }\n\n get subUnitsPerUnit(): number {\n return this._subUnitsPerUnitD.getValue()\n }\n\n get positionSnappedToGrid(): number {\n return this.closestGridPosition(this.position)\n }\n\n closestGridPosition = (posInUnitSpace: number): number => {\n const subUnitsPerUnit = this.subUnitsPerUnit\n const gridLength = 1 / subUnitsPerUnit\n\n return parseFloat(\n (Math.round(posInUnitSpace / gridLength) * gridLength).toFixed(3),\n )\n }\n\n set position(requestedPosition: number) {\n let position = requestedPosition\n this.pause()\n if (process.env.NODE_ENV !== 'production') {\n if (typeof position !== 'number') {\n console.error(\n `value t in sequence.position = t must be a number. ${typeof position} given`,\n )\n position = 0\n }\n if (position < 0) {\n console.error(\n `sequence.position must be a positive number. ${position} given`,\n )\n position = 0\n }\n }\n if (position > this.length) {\n position = this.length\n }\n const dur = this.length\n this._playbackControllerBox\n .get()\n .gotoPosition(position > dur ? dur : position)\n }\n\n getDurationCold() {\n return this._lengthD.getValue()\n }\n\n get playing() {\n return val(this._playbackControllerBox.get().statePointer.playing)\n }\n\n _makeRangeFromSequenceTemplate(): Prism {\n return prism(() => {\n return [0, val(this._lengthD)]\n })\n }\n\n /**\n * Controls the playback within a range. Repeats infinitely unless stopped.\n *\n * @remarks\n * One use case for this is to play the playback within the focus range.\n *\n * @param rangeD - The prism that contains the range that will be used for the playback\n *\n * @returns a promise that gets rejected if the playback stopped for whatever reason\n *\n */\n playDynamicRange(\n rangeD: Prism,\n ticker: Ticker,\n ): Promise {\n return this._playbackControllerBox.get().playDynamicRange(rangeD, ticker)\n }\n\n async play(\n conf: Partial<{\n iterationCount: number\n range: IPlaybackRange\n rate: number\n direction: IPlaybackDirection\n }>,\n ticker: Ticker,\n ): Promise {\n const sequenceDuration = this.length\n const range: IPlaybackRange =\n conf && conf.range ? conf.range : [0, sequenceDuration]\n\n if (process.env.NODE_ENV !== 'production') {\n if (typeof range[0] !== 'number' || range[0] < 0) {\n throw new InvalidArgumentError(\n `Argument conf.range[0] in sequence.play(conf) must be a positive number. ${JSON.stringify(\n range[0],\n )} given.`,\n )\n }\n if (range[0] >= sequenceDuration) {\n throw new InvalidArgumentError(\n `Argument conf.range[0] in sequence.play(conf) cannot be longer than the duration of the sequence, which is ${sequenceDuration}s. ${JSON.stringify(\n range[0],\n )} given.`,\n )\n }\n if (typeof range[1] !== 'number' || range[1] <= 0) {\n throw new InvalidArgumentError(\n `Argument conf.range[1] in sequence.play(conf) must be a number larger than zero. ${JSON.stringify(\n range[1],\n )} given.`,\n )\n }\n\n if (range[1] > sequenceDuration) {\n notify.warning(\n \"Couldn't play sequence in given range\",\n `Your animation will still play until the end of the sequence, however the argument \\`conf.range[1]\\` given in \\`sequence.play(conf)\\` (${JSON.stringify(\n range[1],\n )}s) is longer than the duration of the sequence (${sequenceDuration}s).\n\nTo fix this, either set \\`conf.range[1]\\` to be less the duration of the sequence, or adjust the sequence duration in the UI.`,\n [\n {\n url: 'https://www.theatrejs.com/docs/latest/manual/sequences',\n title: 'Sequences',\n },\n {\n url: 'https://www.theatrejs.com/docs/latest/manual/sequences',\n title: 'Playback API',\n },\n ],\n )\n range[1] = sequenceDuration\n }\n\n if (range[1] <= range[0]) {\n throw new InvalidArgumentError(\n `Argument conf.range[1] in sequence.play(conf) must be larger than conf.range[0]. ${JSON.stringify(\n range,\n )} given.`,\n )\n }\n }\n\n const iterationCount =\n conf && typeof conf.iterationCount === 'number' ? conf.iterationCount : 1\n if (process.env.NODE_ENV !== 'production') {\n if (\n !(Number.isInteger(iterationCount) && iterationCount > 0) &&\n iterationCount !== Infinity\n ) {\n throw new InvalidArgumentError(\n `Argument conf.iterationCount in sequence.play(conf) must be an integer larger than 0. ${JSON.stringify(\n iterationCount,\n )} given.`,\n )\n }\n }\n\n const rate = conf && typeof conf.rate !== 'undefined' ? conf.rate : 1\n\n if (process.env.NODE_ENV !== 'production') {\n if (typeof rate !== 'number' || rate === 0) {\n throw new InvalidArgumentError(\n `Argument conf.rate in sequence.play(conf) must be a number larger than 0. ${JSON.stringify(\n rate,\n )} given.`,\n )\n }\n\n if (rate < 0) {\n throw new InvalidArgumentError(\n `Argument conf.rate in sequence.play(conf) must be a number larger than 0. ${JSON.stringify(\n rate,\n )} given. If you want the animation to play backwards, try setting conf.direction to 'reverse' or 'alternateReverse'.`,\n )\n }\n }\n\n const direction = conf && conf.direction ? conf.direction : 'normal'\n\n if (process.env.NODE_ENV !== 'production') {\n if (possibleDirections.indexOf(direction) === -1) {\n throw new InvalidArgumentError(\n `Argument conf.direction in sequence.play(conf) must be one of ${JSON.stringify(\n possibleDirections,\n )}. ${JSON.stringify(direction)} given. ${didYouMean(\n direction,\n possibleDirections,\n )}`,\n )\n }\n }\n\n return await this._play(\n iterationCount,\n [range[0], range[1]],\n rate,\n direction,\n ticker,\n )\n }\n\n protected _play(\n iterationCount: number,\n range: IPlaybackRange,\n rate: number,\n direction: IPlaybackDirection,\n ticker: Ticker,\n ): Promise {\n return this._playbackControllerBox\n .get()\n .play(iterationCount, range, rate, direction, ticker)\n }\n\n pause() {\n this._playbackControllerBox.get().pause()\n }\n\n replacePlaybackController(playbackController: IPlaybackController) {\n this.pause()\n const oldController = this._playbackControllerBox.get()\n this._playbackControllerBox.set(playbackController)\n\n const time = oldController.getCurrentPosition()\n oldController.destroy()\n playbackController.gotoPosition(time)\n }\n}\n\nexport interface ISequencePositionFormatter {\n formatSubUnitForGrid(posInUnitSpace: number): string\n formatFullUnitForGrid(posInUnitSpace: number): string\n formatForPlayhead(posInUnitSpace: number): string\n formatBasic(posInUnitSpace: number): string\n}\n\nclass TimeBasedPositionFormatter implements ISequencePositionFormatter {\n constructor(private readonly _fps: number) {}\n formatSubUnitForGrid(posInUnitSpace: number): string {\n const subSecondPos = posInUnitSpace % 1\n const frame = 1 / this._fps\n\n const frames = Math.round(subSecondPos / frame)\n return frames + 'f'\n }\n\n formatFullUnitForGrid(posInUnitSpace: number): string {\n let p = posInUnitSpace\n\n let s = ''\n\n if (p >= hour) {\n const hours = Math.floor(p / hour)\n s += hours + 'h'\n p = p % hour\n }\n\n if (p >= minute) {\n const minutes = Math.floor(p / minute)\n s += minutes + 'm'\n p = p % minute\n }\n\n if (p >= second) {\n const seconds = Math.floor(p / second)\n s += seconds + 's'\n p = p % second\n }\n\n const frame = 1 / this._fps\n\n if (p >= frame) {\n const frames = Math.floor(p / frame)\n s += frames + 'f'\n p = p % frame\n }\n\n return s.length === 0 ? '0s' : s\n }\n\n formatForPlayhead(posInUnitSpace: number): string {\n let p = posInUnitSpace\n\n let s = ''\n\n if (p >= hour) {\n const hours = Math.floor(p / hour)\n s += padStart(hours.toString(), 2, '0') + 'h'\n p = p % hour\n }\n\n if (p >= minute) {\n const minutes = Math.floor(p / minute)\n s += padStart(minutes.toString(), 2, '0') + 'm'\n p = p % minute\n } else if (s.length > 0) {\n s += '00m'\n }\n\n if (p >= second) {\n const seconds = Math.floor(p / second)\n s += padStart(seconds.toString(), 2, '0') + 's'\n p = p % second\n } else {\n s += '00s'\n }\n\n const frameLength = 1 / this._fps\n\n if (p >= frameLength) {\n const frames = Math.round(p / frameLength)\n s += padStart(frames.toString(), 2, '0') + 'f'\n p = p % frameLength\n } else if (p / frameLength > 0.98) {\n const frames = 1\n s += padStart(frames.toString(), 2, '0') + 'f'\n p = p % frameLength\n } else {\n s += '00f'\n }\n\n return s.length === 0 ? '00s00f' : s\n }\n\n formatBasic(posInUnitSpace: number): string {\n return posInUnitSpace.toFixed(2) + 's'\n }\n}\n\nconst second = 1\nconst minute = second * 60\nconst hour = minute * 60\n", "import type {$FixMe, $IntentionalAny} from '@theatre/shared/utils/types'\nimport userReadableTypeOfValue from '@theatre/shared/utils/userReadableTypeOfValue'\nimport type {Rgba} from '@theatre/shared/utils/color'\nimport {\n decorateRgba,\n linearSrgbToOklab,\n oklabToLinearSrgb,\n srgbToLinearSrgb,\n linearSrgbToSrgb,\n} from '@theatre/shared/utils/color'\nimport {clamp, mapValues} from 'lodash-es'\nimport type {\n UnknownShorthandCompoundProps,\n UnknownValidCompoundProps,\n ShorthandCompoundPropsToLonghandCompoundProps,\n} from './internals'\nimport {propTypeSymbol, sanitizeCompoundProps} from './internals'\n// eslint-disable-next-line unused-imports/no-unused-imports\nimport type SheetObject from '@theatre/core/sheetObjects/SheetObject'\nimport type {Asset, File} from '@theatre/shared/utils/assets'\n\n// Notes on naming:\n// As of now, prop types are either `simple` or `composite`.\n// The compound type is a composite type. So is the upcoming enum type.\n// Composite types are not directly sequenceable yet. Their simple sub/descendent props are.\n\n/**\n * Validates the common options given to all prop types, such as `opts.label`\n *\n * @param fnCallSignature - See references for examples\n * @param opts - The common options of all prop types\n * @returns void - will throw if options are invalid\n */\nconst validateCommonOpts = (fnCallSignature: string, opts?: CommonOpts) => {\n if (process.env.NODE_ENV !== 'production') {\n if (opts === undefined) return\n if (typeof opts !== 'object' || opts === null) {\n throw new Error(\n `opts in ${fnCallSignature} must either be undefined or an object.`,\n )\n }\n if (Object.prototype.hasOwnProperty.call(opts, 'label')) {\n const {label} = opts\n if (typeof label !== 'string') {\n throw new Error(\n `opts.label in ${fnCallSignature} should be a string. ${userReadableTypeOfValue(\n label,\n )} given.`,\n )\n }\n if (label.trim().length !== label.length) {\n throw new Error(\n `opts.label in ${fnCallSignature} should not start/end with whitespace. \"${label}\" given.`,\n )\n }\n if (label.length === 0) {\n throw new Error(\n `opts.label in ${fnCallSignature} should not be an empty string. If you wish to have no label, remove opts.label from opts.`,\n )\n }\n }\n }\n}\n\n/**\n * A compound prop type (basically a JS object).\n *\n * @example\n * Usage:\n * ```ts\n * // shorthand\n * const position = {\n * x: 0,\n * y: 0\n * }\n * assert(sheet.object('some object', position).value.x === 0)\n *\n * // nesting\n * const foo = {bar: {baz: {quo: 0}}}\n * assert(sheet.object('some object', foo).value.bar.baz.quo === 0)\n *\n * // With additional options:\n * const position = t.compound(\n * {x: 0, y: 0},\n * // a custom label for the prop:\n * {label: \"Position\"}\n * )\n * ```\n *\n */\nexport const compound = (\n props: Props,\n opts: CommonOpts = {},\n): PropTypeConfig_Compound<\n ShorthandCompoundPropsToLonghandCompoundProps\n> => {\n validateCommonOpts('t.compound(props, opts)', opts)\n const sanitizedProps = sanitizeCompoundProps(props)\n const deserializationCache = new WeakMap<{}, unknown>()\n const config: PropTypeConfig_Compound<\n ShorthandCompoundPropsToLonghandCompoundProps\n > = {\n type: 'compound',\n props: sanitizedProps as $IntentionalAny,\n valueType: null as $IntentionalAny,\n [propTypeSymbol]: 'TheatrePropType',\n label: opts.label,\n default: mapValues(sanitizedProps, (p) => p.default) as $IntentionalAny,\n deserializeAndSanitize: (json: unknown) => {\n if (typeof json !== 'object' || !json) return undefined\n if (deserializationCache.has(json)) {\n return deserializationCache.get(json)\n }\n\n // TODO we should probably also check here whether `json` is a pure object rather\n // than an instance of a class, just to avoid the possible edge cases of handling\n // class instances.\n\n const deserialized: $FixMe = {}\n let atLeastOnePropWasDeserialized = false\n for (const [key, propConfig] of Object.entries(sanitizedProps)) {\n if (Object.prototype.hasOwnProperty.call(json, key)) {\n const deserializedSub = propConfig.deserializeAndSanitize(\n (json as $IntentionalAny)[key] as unknown,\n )\n if (deserializedSub != null) {\n atLeastOnePropWasDeserialized = true\n deserialized[key] = deserializedSub\n }\n }\n }\n deserializationCache.set(json, deserialized)\n if (atLeastOnePropWasDeserialized) {\n return deserialized\n }\n },\n }\n return config\n}\n\n/**\n * A file prop type\n *\n * @example\n * Usage:\n * ```ts\n *\n * // with a label:\n * const obj = sheet.object('key', {\n * url: t.file('My file.glb', {\n * label: 'Model'\n * })\n * })\n * ```\n *\n * @param opts - Options (See usage examples)\n */\nexport const file = (\n // The defaultValue parameter is a string for convenience, but it will be converted to an Asset object\n defaultValue: File['id'],\n opts: {\n label?: string\n interpolate?: Interpolator\n } = {},\n): PropTypeConfig_File => {\n if (process.env.NODE_ENV !== 'production') {\n validateCommonOpts('t.file(defaultValue, opts)', opts)\n }\n\n const interpolate: Interpolator = (left, right, progression) => {\n const stringInterpolate = opts.interpolate ?? leftInterpolate\n\n return {\n type: 'file',\n id: stringInterpolate(left.id, right.id, progression),\n }\n }\n\n return {\n type: 'file',\n default: {type: 'file', id: defaultValue},\n valueType: null as $IntentionalAny,\n [propTypeSymbol]: 'TheatrePropType',\n label: opts.label,\n interpolate,\n deserializeAndSanitize: _ensureFile,\n }\n}\n\nconst _ensureFile = (val: unknown): File | undefined => {\n if (!val) return undefined\n\n let valid = true\n\n if (\n typeof (val as $IntentionalAny).id !== 'string' &&\n ![null, undefined].includes((val as $IntentionalAny).id)\n ) {\n valid = false\n }\n\n if ((val as $IntentionalAny).type !== 'file') valid = false\n\n if (!valid) return undefined\n\n return val as File\n}\n\n/**\n * An image prop type\n *\n * @example\n * Usage:\n * ```ts\n *\n * // with a label:\n * const obj = sheet.object('key', {\n * url: t.image('My image.png', {\n * label: 'texture'\n * })\n * })\n * ```\n *\n * @param opts - Options (See usage examples)\n */\nexport const image = (\n // The defaultValue parameter is a string for convenience, but it will be converted to an Asset object\n defaultValue: Asset['id'],\n opts: {\n label?: string\n interpolate?: Interpolator\n } = {},\n): PropTypeConfig_Image => {\n if (process.env.NODE_ENV !== 'production') {\n validateCommonOpts('t.image(defaultValue, opts)', opts)\n }\n\n const interpolate: Interpolator = (left, right, progression) => {\n const stringInterpolate = opts.interpolate ?? leftInterpolate\n\n return {\n type: 'image',\n id: stringInterpolate(left.id, right.id, progression),\n }\n }\n\n return {\n type: 'image',\n default: {type: 'image', id: defaultValue},\n valueType: null as $IntentionalAny,\n [propTypeSymbol]: 'TheatrePropType',\n label: opts.label,\n interpolate,\n deserializeAndSanitize: _ensureImage,\n }\n}\n\nconst _ensureImage = (val: unknown): Asset | undefined => {\n if (!val) return undefined\n\n let valid = true\n\n if (\n typeof (val as $IntentionalAny).id !== 'string' &&\n ![null, undefined].includes((val as $IntentionalAny).id)\n ) {\n valid = false\n }\n\n if ((val as $IntentionalAny).type !== 'image') valid = false\n\n if (!valid) return undefined\n\n return val as Asset\n}\n\n/**\n * A number prop type.\n *\n * @example\n * Usage\n * ```ts\n * // shorthand:\n * const obj = sheet.object('key', {x: 0})\n *\n * // With options (equal to above)\n * const obj = sheet.object('key', {\n * x: t.number(0)\n * })\n *\n * // With a range (note that opts.range is just a visual guide, not a validation rule)\n * const x = t.number(0, {range: [0, 10]}) // limited to 0 and 10\n *\n * // With custom nudging\n * const x = t.number(0, {nudgeMultiplier: 0.1}) // nudging will happen in 0.1 increments\n *\n * // With custom nudging function\n * const x = t.number({\n * nudgeFn: (\n * // the mouse movement (in pixels)\n * deltaX: number,\n * // the movement as a fraction of the width of the number editor's input\n * deltaFraction: number,\n * // A multiplier that's usually 1, but might be another number if user wants to nudge slower/faster\n * magnitude: number,\n * // the configuration of the number\n * config: {nudgeMultiplier?: number; range?: [number, number]},\n * ): number => {\n * return deltaX * magnitude\n * },\n * })\n * ```\n *\n * @param defaultValue - The default value (Must be a finite number)\n * @param opts - The options (See usage examples)\n * @returns A number prop config\n */\nexport const number = (\n defaultValue: number,\n opts: {\n nudgeFn?: PropTypeConfig_Number['nudgeFn']\n range?: PropTypeConfig_Number['range']\n nudgeMultiplier?: number\n label?: string\n } = {},\n): PropTypeConfig_Number => {\n if (process.env.NODE_ENV !== 'production') {\n validateCommonOpts('t.number(defaultValue, opts)', opts)\n if (typeof defaultValue !== 'number' || !isFinite(defaultValue)) {\n throw new Error(\n `Argument defaultValue in t.number(defaultValue) must be a number. ${userReadableTypeOfValue(\n defaultValue,\n )} given.`,\n )\n }\n if (typeof opts === 'object' && opts !== null) {\n if (Object.prototype.hasOwnProperty.call(opts, 'range')) {\n if (!Array.isArray(opts.range)) {\n throw new Error(\n `opts.range in t.number(defaultValue, opts) must be a tuple of two numbers. ${userReadableTypeOfValue(\n opts.range,\n )} given.`,\n )\n }\n if (opts.range.length !== 2) {\n throw new Error(\n `opts.range in t.number(defaultValue, opts) must have two elements. ${opts.range.length} given.`,\n )\n }\n if (!opts.range.every((n) => typeof n === 'number' && !isNaN(n))) {\n throw new Error(\n `opts.range in t.number(defaultValue, opts) must be a tuple of two numbers.`,\n )\n }\n if (opts.range[0] >= opts.range[1]) {\n throw new Error(\n `opts.range[0] in t.number(defaultValue, opts) must be smaller than opts.range[1]. Given: ${JSON.stringify(\n opts.range,\n )}`,\n )\n }\n }\n if (Object.prototype.hasOwnProperty.call(opts, 'nudgeMultiplier')) {\n if (\n typeof opts.nudgeMultiplier !== 'number' ||\n !isFinite(opts.nudgeMultiplier)\n ) {\n throw new Error(\n `opts.nudgeMultiplier in t.number(defaultValue, opts) must be a finite number. ${userReadableTypeOfValue(\n opts.nudgeMultiplier,\n )} given.`,\n )\n }\n }\n if (Object.prototype.hasOwnProperty.call(opts, 'nudgeFn')) {\n if (typeof opts.nudgeFn !== 'function') {\n throw new Error(\n `opts.nudgeFn in t.number(defaultValue, opts) must be a function. ${userReadableTypeOfValue(\n opts.nudgeFn,\n )} given.`,\n )\n }\n }\n }\n }\n\n return {\n type: 'number',\n valueType: 0,\n default: defaultValue,\n [propTypeSymbol]: 'TheatrePropType',\n ...(opts ? opts : {}),\n label: opts.label,\n nudgeFn: opts.nudgeFn ?? defaultNumberNudgeFn,\n nudgeMultiplier:\n typeof opts.nudgeMultiplier === 'number'\n ? opts.nudgeMultiplier\n : undefined,\n interpolate: _interpolateNumber,\n deserializeAndSanitize: numberDeserializer(opts.range),\n }\n}\n\nconst numberDeserializer = (range?: PropTypeConfig_Number['range']) =>\n range\n ? (json: unknown): undefined | number => {\n if (!(typeof json === 'number' && isFinite(json))) return undefined\n return clamp(json, range[0], range[1])\n }\n : _ensureNumber\n\nconst _ensureNumber = (value: unknown): undefined | number =>\n typeof value === 'number' && isFinite(value) ? value : undefined\n\nconst _interpolateNumber = (\n left: number,\n right: number,\n progression: number,\n): number => {\n return left + progression * (right - left)\n}\n\nexport const rgba = (\n defaultValue: Rgba = {r: 0, g: 0, b: 0, a: 1},\n opts: CommonOpts = {},\n): PropTypeConfig_Rgba => {\n if (process.env.NODE_ENV !== 'production') {\n validateCommonOpts('t.rgba(defaultValue, opts)', opts)\n\n // Lots of duplicated code and stuff that probably shouldn't be here, mostly\n // because we are still figuring out how we are doing validation, sanitization,\n // decoding, decorating.\n\n // Validate default value\n let valid = true\n for (const p of ['r', 'g', 'b', 'a']) {\n if (\n !Object.prototype.hasOwnProperty.call(defaultValue, p) ||\n typeof (defaultValue as $IntentionalAny)[p] !== 'number'\n ) {\n valid = false\n }\n }\n\n if (!valid) {\n throw new Error(\n `Argument defaultValue in t.rgba(defaultValue) must be of the shape { r: number; g: number, b: number, a: number; }.`,\n )\n }\n }\n\n // Clamp defaultValue components between 0 and 1\n const sanitized = {}\n for (const component of ['r', 'g', 'b', 'a']) {\n ;(sanitized as $IntentionalAny)[component] = Math.min(\n Math.max((defaultValue as $IntentionalAny)[component], 0),\n 1,\n )\n }\n\n return {\n type: 'rgba',\n valueType: null as $IntentionalAny,\n default: decorateRgba(sanitized as Rgba),\n [propTypeSymbol]: 'TheatrePropType',\n label: opts.label,\n interpolate: _interpolateRgba,\n deserializeAndSanitize: _sanitizeRgba,\n }\n}\n\nconst _sanitizeRgba = (val: unknown): Rgba | undefined => {\n if (!val) return undefined\n let valid = true\n for (const c of ['r', 'g', 'b', 'a']) {\n if (\n !Object.prototype.hasOwnProperty.call(val, c) ||\n typeof (val as $IntentionalAny)[c] !== 'number'\n ) {\n valid = false\n }\n }\n\n if (!valid) return undefined\n\n // Clamp defaultValue components between 0 and 1\n const sanitized = {}\n for (const c of ['r', 'g', 'b', 'a']) {\n ;(sanitized as $IntentionalAny)[c] = Math.min(\n Math.max((val as $IntentionalAny)[c], 0),\n 1,\n )\n }\n\n return decorateRgba(sanitized as Rgba)\n}\n\nconst _interpolateRgba = (\n left: Rgba,\n right: Rgba,\n progression: number,\n): Rgba => {\n const leftLab = linearSrgbToOklab(srgbToLinearSrgb(left))\n const rightLab = linearSrgbToOklab(srgbToLinearSrgb(right))\n\n const interpolatedLab = {\n L: (1 - progression) * leftLab.L + progression * rightLab.L,\n a: (1 - progression) * leftLab.a + progression * rightLab.a,\n b: (1 - progression) * leftLab.b + progression * rightLab.b,\n alpha: (1 - progression) * leftLab.alpha + progression * rightLab.alpha,\n }\n\n const interpolatedRgba = linearSrgbToSrgb(oklabToLinearSrgb(interpolatedLab))\n\n return decorateRgba(interpolatedRgba)\n}\n\n/**\n * A boolean prop type\n *\n * @example\n * Usage:\n * ```ts\n * // shorthand:\n * const obj = sheet.object('key', {isOn: true})\n *\n * // with a label:\n * const obj = sheet.object('key', {\n * isOn: t.boolean(true, {\n * label: 'Enabled'\n * })\n * })\n * ```\n *\n * @param defaultValue - The default value (must be a boolean)\n * @param opts - Options (See usage examples)\n */\nexport const boolean = (\n defaultValue: boolean,\n opts: {\n label?: string\n interpolate?: Interpolator\n } = {},\n): PropTypeConfig_Boolean => {\n if (process.env.NODE_ENV !== 'production') {\n validateCommonOpts('t.boolean(defaultValue, opts)', opts)\n if (typeof defaultValue !== 'boolean') {\n throw new Error(\n `defaultValue in t.boolean(defaultValue) must be a boolean. ${userReadableTypeOfValue(\n defaultValue,\n )} given.`,\n )\n }\n }\n\n return {\n type: 'boolean',\n default: defaultValue,\n valueType: null as $IntentionalAny,\n [propTypeSymbol]: 'TheatrePropType',\n label: opts.label,\n interpolate: opts.interpolate ?? leftInterpolate,\n deserializeAndSanitize: _ensureBoolean,\n }\n}\n\nconst _ensureBoolean = (val: unknown): boolean | undefined => {\n return typeof val === 'boolean' ? val : undefined\n}\n\nfunction leftInterpolate(left: T): T {\n return left\n}\n\n/**\n * A string prop type\n *\n * @example\n * Usage:\n * ```ts\n * // shorthand:\n * const obj = sheet.object('key', {message: \"Animation loading\"})\n *\n * // with a label:\n * const obj = sheet.object('key', {\n * message: t.string(\"Animation Loading\", {\n * label: 'The Message'\n * })\n * })\n * ```\n *\n * @param defaultValue - The default value (must be a string)\n * @param opts - The options (See usage examples)\n * @returns A string prop type\n */\nexport const string = (\n defaultValue: string,\n opts: {\n label?: string\n interpolate?: Interpolator\n } = {},\n): PropTypeConfig_String => {\n if (process.env.NODE_ENV !== 'production') {\n validateCommonOpts('t.string(defaultValue, opts)', opts)\n if (typeof defaultValue !== 'string') {\n throw new Error(\n `defaultValue in t.string(defaultValue) must be a string. ${userReadableTypeOfValue(\n defaultValue,\n )} given.`,\n )\n }\n }\n return {\n type: 'string',\n default: defaultValue,\n valueType: null as $IntentionalAny,\n [propTypeSymbol]: 'TheatrePropType',\n label: opts.label,\n interpolate: opts.interpolate ?? leftInterpolate,\n deserializeAndSanitize: _ensureString,\n }\n}\n\nfunction _ensureString(s: unknown): string | undefined {\n return typeof s === 'string' ? s : undefined\n}\n\n/**\n * A stringLiteral prop type, useful for building menus or radio buttons.\n *\n * @example\n * Usage:\n * ```ts\n * // Basic usage\n * const obj = sheet.object('key', {\n * light: t.stringLiteral(\"r\", {r: \"Red\", \"g\": \"Green\"})\n * })\n *\n * // Shown as a radio switch with a custom label\n * const obj = sheet.object('key', {\n * light: t.stringLiteral(\"r\", {r: \"Red\", \"g\": \"Green\"})\n * }, {as: \"switch\", label: \"Street Light\"})\n * ```\n *\n * @returns A stringLiteral prop type\n *\n */\nexport function stringLiteral<\n ValuesAndLabels extends {[key in string]: string},\n>(\n /**\n * Default value (a string that equals one of the options)\n */\n defaultValue: Extract,\n /**\n * The options. Use the `\"value\": \"Label\"` format.\n *\n * An object like `{[value]: Label}`. Example: `{r: \"Red\", \"g\": \"Green\"}`\n */\n valuesAndLabels: ValuesAndLabels,\n /**\n * opts.as Determines if editor is shown as a menu or a switch. Either 'menu' or 'switch'. Default: 'menu'\n */\n opts: {\n as?: 'menu' | 'switch'\n label?: string\n interpolate?: Interpolator>\n } = {},\n): PropTypeConfig_StringLiteral> {\n return {\n type: 'stringLiteral',\n default: defaultValue,\n valuesAndLabels: {...valuesAndLabels},\n [propTypeSymbol]: 'TheatrePropType',\n valueType: null as $IntentionalAny,\n as: opts.as ?? 'menu',\n label: opts.label,\n interpolate: opts.interpolate ?? leftInterpolate,\n deserializeAndSanitize(\n json: unknown,\n ): undefined | Extract {\n if (typeof json !== 'string') return undefined\n if (Object.prototype.hasOwnProperty.call(valuesAndLabels, json)) {\n return json as $IntentionalAny\n } else {\n return undefined\n }\n },\n }\n}\n\n/**\n * A linear interpolator for a certain value type.\n *\n * @param left - the value to interpolate from (beginning)\n * @param right - the value to interpolate to (end)\n * @param progression - the amount of progression. Starts at 0 and ends at 1. But could overshoot in either direction\n *\n * @example\n * ```ts\n * const numberInterpolator: Interpolator = (left, right, progression) => left + progression * (right - left)\n *\n * numberInterpolator(-50, 50, 0.5) === 0\n * numberInterpolator(-50, 50, 0) === -50\n * numberInterpolator(-50, 50, 1) === 50\n * numberInterpolator(-50, 50, 2) === 150 // overshoot\n * ```\n */\nexport type Interpolator = (left: T, right: T, progression: number) => T\n\nexport interface IBasePropType<\n LiteralIdentifier extends string,\n ValueType,\n DeserializeType = ValueType,\n> {\n /**\n * Each prop config has a string literal identifying it. For example,\n * `assert.equal(t.number(10).type, 'number')`\n */\n type: LiteralIdentifier\n /**\n * the `valueType` is only used by typescript. It won't be present in runtime.\n */\n valueType: ValueType\n [propTypeSymbol]: 'TheatrePropType'\n /**\n * Each prop type may be given a custom label instead of the name of the sub-prop\n * it is in.\n *\n * @example\n * ```ts\n * const position = {\n * x: t.number(0), // label would be 'x'\n * y: t.number(0, {label: 'top'}) // label would be 'top'\n * }\n * ```\n */\n label: string | undefined\n default: ValueType\n /**\n * Each prop config has a `deserializeAndSanitize()` function that deserializes and sanitizes\n * any js value into one that is acceptable by this prop config, or `undefined`.\n *\n * As a rule, the value returned by this function should not hold any reference to `json` or any\n * other value referenced by the descendent props of `json`. This is to ensure that json values\n * controlled by the user can never change the values in the store. See `deserializeAndSanitize()` in\n * `t.compound()` or `t.rgba()` as examples.\n *\n * The `DeserializeType` is usually equal to `ValueType`. That is the case with\n * all simple prop configs, such as `number`, `string`, or `rgba`. However, composite\n * configs such as `compound` or `enum` may deserialize+sanitize into a partial value. For example,\n * a prop config of `t.compound({x: t.number(0), y: t.number(0)})` may deserialize+sanitize into `{x: 10}`.\n * This behavior is used by {@link SheetObject.getValues} to replace the missing sub-props\n * with their default value.\n *\n * Admittedly, this partial deserialization behavior is not what the word \"deserialize\"\n * typically implies in most codebases, so feel free to change this name into a more\n * appropriate one.\n *\n * Additionally, returning an `undefined` allows {@link SheetObject.getValues} to\n * replace the `undefined` with the default value of that prop.\n */\n deserializeAndSanitize: (json: unknown) => undefined | DeserializeType\n}\n\ninterface ISimplePropType\n extends IBasePropType {\n interpolate: Interpolator\n}\n\nexport interface PropTypeConfig_Number\n extends ISimplePropType<'number', number> {\n range?: [min: number, max: number]\n nudgeFn: NumberNudgeFn\n /**\n * See {@link defaultNumberNudgeFn} to see how `nudgeMultiplier` is treated.\n */\n nudgeMultiplier: number | undefined\n}\n\nexport type NumberNudgeFn = (p: {\n deltaX: number\n deltaFraction: number\n magnitude: number\n config: PropTypeConfig_Number\n}) => number\n\n/**\n * This is the default nudging behavior. It'll be used if `config.nudgeFn` is empty in {@link number} `types.number(defaultValue, config)`.\n *\n * Its behavior is as follows:\n * - If `config.nudgeMultiplier` is set, then it'll be used as the unit of incrementing/decrementing the prop's value.\n * For example, if `types.number(0, {nudgeMultiplier: 0.5})`, then nudging the number will make its value go up/down by 0.5, so: 0, 0.5, 1.0, -0.5, ...\n * Note that if the prop's value is, say, 0.1, then nudging it will still make its value go up/down by 0.5, so: 0.6, 1.1, -0.6, ...\n * - Otherwise, the amount of nudge will be determined based on whether the number has a range.\n *\n */\nconst defaultNumberNudgeFn: NumberNudgeFn = ({\n config,\n deltaX,\n deltaFraction,\n magnitude,\n}) => {\n const {range} = config\n\n if (\n !config.nudgeMultiplier &&\n range &&\n !range.includes(Infinity) &&\n !range.includes(-Infinity)\n ) {\n return deltaFraction * (range[1] - range[0]) * magnitude\n }\n\n return deltaX * magnitude * (config.nudgeMultiplier ?? 1)\n}\n\nexport interface PropTypeConfig_Boolean\n extends ISimplePropType<'boolean', boolean> {}\n\ntype CommonOpts = {\n /**\n * Each prop type may be given a custom label instead of the name of the sub-prop\n * it is in.\n *\n * @example\n * ```ts\n * const position = {\n * x: t.number(0), // label would be 'x'\n * y: t.number(0, {label: 'top'}) // label would be 'top'\n * }\n * ```\n */\n label?: string\n}\n\nexport interface PropTypeConfig_String\n extends ISimplePropType<'string', string> {}\n\nexport interface PropTypeConfig_StringLiteral\n extends ISimplePropType<'stringLiteral', T> {\n valuesAndLabels: Record\n as: 'menu' | 'switch'\n}\n\nexport interface PropTypeConfig_Rgba extends ISimplePropType<'rgba', Rgba> {}\n\nexport interface PropTypeConfig_Image extends ISimplePropType<'image', Asset> {}\nexport interface PropTypeConfig_File extends ISimplePropType<'file', File> {}\n\ntype DeepPartialCompound = {\n [K in keyof Props]?: DeepPartial\n}\n\ntype DeepPartial =\n Conf extends PropTypeConfig_AllSimples\n ? Conf['valueType']\n : Conf extends PropTypeConfig_Compound\n ? DeepPartialCompound\n : never\n\nexport interface PropTypeConfig_Compound<\n Props extends UnknownValidCompoundProps,\n> extends IBasePropType<\n 'compound',\n {[K in keyof Props]: Props[K]['valueType']},\n DeepPartialCompound\n > {\n props: Record\n}\n\nexport interface PropTypeConfig_Enum extends IBasePropType<'enum', {}> {\n cases: Record\n defaultCase: string\n}\n\nexport type PropTypeConfig_AllSimples =\n | PropTypeConfig_Number\n | PropTypeConfig_Boolean\n | PropTypeConfig_String\n | PropTypeConfig_StringLiteral<$IntentionalAny>\n | PropTypeConfig_Rgba\n | PropTypeConfig_Image\n | PropTypeConfig_File\n\nexport type PropTypeConfig =\n | PropTypeConfig_AllSimples\n | PropTypeConfig_Compound<$IntentionalAny>\n | PropTypeConfig_Enum\n\nexport type {UnknownShorthandCompoundProps}\n", "/**\n * Truncates a string to a given length, adding an ellipsis if it was truncated.\n * Example:\n * ```ts\n * ellipsify('hello world', 5) // 'hello...'\n * ellipsify('hello world', 100) // 'hello world'\n * ```\n */\nexport default function ellipsify(str: string, maxLength: number) {\n if (str.length <= maxLength) return str\n return str.substr(0, maxLength - 3) + '...'\n}\n", "import ellipsify from './ellipsify'\n\n/**\n * Returns a short, user-readable description of the type of `value`.\n * Examples:\n * ```ts\n * userReadableTypeOfValue(1) // 'number(1)'\n * userReadableTypeOfValue(12345678901112) // 'number(1234567...)'\n * userReadableTypeOfValue('hello') // 'string(\"hello\")'\n * userReadableTypeOfValue('hello world this is a long string') // 'string(\"hello wo...\")'\n * userReadableTypeOfValue({a: 1, b: 2}) // 'object'\n * userReadableTypeOfValue([1, 2, 3]) // 'array'\n * userReadableTypeOfValue(null) // 'null'\n * userReadableTypeOfValue(undefined) // 'undefined'\n * userReadableTypeOfValue(true) // 'true'\n * ```\n */\nconst userReadableTypeOfValue = (v: unknown): string => {\n if (typeof v === 'string') {\n return `string(\"${ellipsify(v, 10)}\")`\n } else if (typeof v === 'number') {\n return `number(${ellipsify(String(v), 10)})`\n } else if (v === null) {\n return 'null'\n } else if (v === undefined) {\n return 'undefined'\n } else if (typeof v === 'boolean') {\n return String(v)\n } else if (Array.isArray(v)) {\n return 'array'\n } else if (typeof v === 'object') {\n return 'object'\n } else {\n return 'unknown'\n }\n}\n\nexport default userReadableTypeOfValue\n", "import {clamp} from 'lodash-es'\n\n/**\n * Robust check for a valid hex value (without the \"#\") in a string\n *\n * @remarks\n *\n * Supports all the syntax variants of \n * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/hex-color#syntax}:\n *\n *\n * ```javascript\n * #RGB // The three-value syntax\n * #RGBA // The four-value syntax\n * #RRGGBB // The six-value syntax\n * #RRGGBBAA // The eight-value syntax\n * ```\n */\nexport const validHexRegExp = /^#*([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i\n\nexport function parseRgbaFromHex(rgba: string) {\n rgba = rgba.trim().toLowerCase()\n\n const match = rgba.match(validHexRegExp)\n\n if (!match) {\n return {\n r: 0,\n g: 0,\n b: 0,\n a: 1,\n }\n }\n\n const hex = _hexInEightValueSyntax(match[1])\n\n return {\n r: parseInt(hex.substr(0, 2), 16) / 255,\n g: parseInt(hex.substr(2, 2), 16) / 255,\n b: parseInt(hex.substr(4, 2), 16) / 255,\n a: parseInt(hex.substr(6, 2), 16) / 255,\n }\n}\n\nexport function rgba2hex(\n rgba: Rgba,\n {\n /** Alpha is usually an optional value for most hex inputs, so if it's opaque, we can omit its value. */\n removeAlphaIfOpaque = false,\n } = {},\n) {\n const alpha = ((rgba.a * 255) | (1 << 8)).toString(16).slice(1)\n\n const hex =\n ((rgba.r * 255) | (1 << 8)).toString(16).slice(1) +\n ((rgba.g * 255) | (1 << 8)).toString(16).slice(1) +\n ((rgba.b * 255) | (1 << 8)).toString(16).slice(1) +\n (removeAlphaIfOpaque && alpha === 'ff' ? '' : alpha)\n\n return `#${hex}`\n}\n\n// TODO: We should add a decorate property to the propConfig too.\n// Right now, each place that has anything to do with a color is individually\n// responsible for defining a toString() function on the object it returns.\nexport function decorateRgba(rgba: Rgba) {\n return {\n ...rgba,\n toString() {\n return rgba2hex(this, {removeAlphaIfOpaque: true})\n },\n }\n}\n\nexport function clampRgba(rgba: Rgba) {\n return Object.fromEntries(\n Object.entries(rgba).map(([key, value]) => [key, clamp(value, 0, 1)]),\n ) as Rgba\n}\n\nexport function linearSrgbToSrgb(rgba: Rgba) {\n function compress(x: number) {\n // This looks funky because sRGB uses a linear scale below 0.0031308 in\n // order to avoid an infinite slope, while trying to approximate gamma 2.2\n // as closely as possible, hence the branching and the 2.4 exponent.\n if (x >= 0.0031308) return 1.055 * x ** (1.0 / 2.4) - 0.055\n else return 12.92 * x\n }\n return clampRgba({\n r: compress(rgba.r),\n g: compress(rgba.g),\n b: compress(rgba.b),\n a: rgba.a,\n })\n}\n\nexport function srgbToLinearSrgb(rgba: Rgba) {\n function expand(x: number) {\n if (x >= 0.04045) return ((x + 0.055) / (1 + 0.055)) ** 2.4\n else return x / 12.92\n }\n return {\n r: expand(rgba.r),\n g: expand(rgba.g),\n b: expand(rgba.b),\n a: rgba.a,\n }\n}\n\nexport function linearSrgbToOklab(rgba: Rgba) {\n let l = 0.4122214708 * rgba.r + 0.5363325363 * rgba.g + 0.0514459929 * rgba.b\n let m = 0.2119034982 * rgba.r + 0.6806995451 * rgba.g + 0.1073969566 * rgba.b\n let s = 0.0883024619 * rgba.r + 0.2817188376 * rgba.g + 0.6299787005 * rgba.b\n\n let l_ = Math.cbrt(l)\n let m_ = Math.cbrt(m)\n let s_ = Math.cbrt(s)\n\n return {\n L: 0.2104542553 * l_ + 0.793617785 * m_ - 0.0040720468 * s_,\n a: 1.9779984951 * l_ - 2.428592205 * m_ + 0.4505937099 * s_,\n b: 0.0259040371 * l_ + 0.7827717662 * m_ - 0.808675766 * s_,\n alpha: rgba.a,\n }\n}\n\nexport function oklabToLinearSrgb(laba: Laba) {\n let l_ = laba.L + 0.3963377774 * laba.a + 0.2158037573 * laba.b\n let m_ = laba.L - 0.1055613458 * laba.a - 0.0638541728 * laba.b\n let s_ = laba.L - 0.0894841775 * laba.a - 1.291485548 * laba.b\n\n let l = l_ * l_ * l_\n let m = m_ * m_ * m_\n let s = s_ * s_ * s_\n\n return {\n r: +4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s,\n g: -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s,\n b: -0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s,\n a: laba.alpha,\n }\n}\n\nexport type Rgba = {\n r: number\n g: number\n b: number\n a: number\n}\n\nexport type Laba = {\n L: number\n a: number\n b: number\n alpha: number\n}\n\n/**\n * Returns a hex string in the eight-value syntax\n */\nfunction _hexInEightValueSyntax(hex: string): string {\n switch (hex.length) {\n case 3:\n return `${hex.repeat(2)}ff`\n case 4:\n const rgb = hex.substr(0, 3)\n const alpha = hex[3]\n return `${rgb.repeat(2)}${alpha.repeat(2)}`\n case 6:\n return `${hex}ff`\n }\n\n return hex\n}\n", "import {InvalidArgumentError} from '@theatre/shared/utils/errors'\nimport type {$IntentionalAny} from '@theatre/shared/utils/types'\nimport userReadableTypeOfValue from '@theatre/shared/utils/userReadableTypeOfValue'\nimport {isPlainObject} from 'lodash-es'\nimport type {\n PropTypeConfig,\n PropTypeConfig_Boolean,\n PropTypeConfig_Compound,\n PropTypeConfig_Number,\n PropTypeConfig_String,\n} from './index'\nimport * as t from './index'\n\nexport const propTypeSymbol = Symbol('TheatrePropType_Basic')\n\nexport type UnknownValidCompoundProps = {\n [K in string]: PropTypeConfig\n}\n\n/**\n *\n * This does not include Rgba since Rgba does not have a predictable\n * object shape. We prefer to infer that compound props are described as\n * `Record` for now.\n *\n * In the future, it might be reasonable to wrap these types up into something\n * which would allow us to differentiate between values at runtime\n * (e.g. `val.type = \"Rgba\"` vs `val.type = \"Compound\"` etc)\n */\ntype UnknownShorthandProp =\n | string\n | number\n | boolean\n | PropTypeConfig\n | UnknownShorthandCompoundProps\n\n/** Given an object like this, we have enough info to predict the compound prop */\nexport type UnknownShorthandCompoundProps = {\n [K in string]: UnknownShorthandProp\n}\n\nexport type ShorthandPropToLonghandProp

=\n P extends string\n ? PropTypeConfig_String\n : P extends number\n ? PropTypeConfig_Number\n : P extends boolean\n ? PropTypeConfig_Boolean\n : P extends PropTypeConfig\n ? P\n : P extends UnknownShorthandCompoundProps\n ? PropTypeConfig_Compound>\n : never\n\nexport type ShorthandCompoundPropsToInitialValue<\n P extends UnknownShorthandCompoundProps,\n> = LonghandCompoundPropsToInitialValue<\n ShorthandCompoundPropsToLonghandCompoundProps

\n>\n\ntype LonghandCompoundPropsToInitialValue

=\n {\n [K in keyof P]: P[K]['valueType']\n }\n\nexport type PropsValue

= P extends UnknownValidCompoundProps\n ? LonghandCompoundPropsToInitialValue

\n : P extends UnknownShorthandCompoundProps\n ? LonghandCompoundPropsToInitialValue<\n ShorthandCompoundPropsToLonghandCompoundProps

\n >\n : never\n\nexport type ShorthandCompoundPropsToLonghandCompoundProps<\n P extends UnknownShorthandCompoundProps,\n> = {\n [K in keyof P]: ShorthandPropToLonghandProp\n}\n\nexport function isLonghandPropType(t: unknown): t is PropTypeConfig {\n return (\n typeof t === 'object' &&\n !!t &&\n (t as $IntentionalAny)[propTypeSymbol] === 'TheatrePropType'\n )\n}\n\nexport function toLonghandProp(p: unknown): PropTypeConfig {\n if (typeof p === 'number') {\n return t.number(p)\n } else if (typeof p === 'boolean') {\n return t.boolean(p)\n } else if (typeof p === 'string') {\n return t.string(p)\n } else if (typeof p === 'object' && !!p) {\n if (isLonghandPropType(p)) return p\n if (isPlainObject(p)) {\n return t.compound(p as $IntentionalAny)\n } else {\n throw new InvalidArgumentError(\n `This value is not a valid prop type: ${userReadableTypeOfValue(p)}`,\n )\n }\n } else {\n throw new InvalidArgumentError(\n `This value is not a valid prop type: ${userReadableTypeOfValue(p)}`,\n )\n }\n}\n\nexport function sanitizeCompoundProps(\n props: UnknownShorthandCompoundProps,\n): UnknownValidCompoundProps {\n const sanitizedProps: UnknownValidCompoundProps = {}\n if (process.env.NODE_ENV !== 'production') {\n if (typeof props !== 'object' || !props) {\n throw new InvalidArgumentError(\n `t.compound() expects an object, like: {x: 10}. ${userReadableTypeOfValue(\n props,\n )} given.`,\n )\n }\n }\n for (const key of Object.keys(props)) {\n if (process.env.NODE_ENV !== 'production') {\n if (typeof key !== 'string') {\n throw new InvalidArgumentError(\n `t.compound()'s keys must be all strings. ${userReadableTypeOfValue(\n key,\n )} given.`,\n )\n } else if (key.length === 0 || !key.match(/^\\w+$/)) {\n throw new InvalidArgumentError(\n `compound key ${userReadableTypeOfValue(\n key,\n )} is invalid. The keys must be alphanumeric and start with a letter.`,\n )\n } else if (key.length > 64) {\n throw new InvalidArgumentError(\n `compound key ${userReadableTypeOfValue(key)} is too long.`,\n )\n }\n }\n\n const val = props[key]\n if (isLonghandPropType(val)) {\n sanitizedProps[key] = val as $IntentionalAny\n } else {\n sanitizedProps[key] = toLonghandProp(val) as $IntentionalAny\n }\n }\n return sanitizedProps\n}\n", "import {InvalidArgumentError} from './errors'\nimport {notify} from '@theatre/shared/notify'\n\n/**\n * Make the given string's \"path\" slashes normalized with preceding and trailing spaces.\n *\n * - It removes starting and trailing slashes: `/foo/bar/` becomes `foo / bar`\n * - It adds wraps each slash with a single space, so that `foo/bar` becomes `foo / bar`\n *\n */\nconst normalizeSlashedPath = (p: string): string =>\n p\n // remove starting slashes\n .replace(/^[\\s\\/]*/, '')\n // remove ending slashes\n .replace(/[\\s\\/]*$/, '')\n // make middle slashes consistent\n .replace(/\\s*\\/\\s*/g, ' / ')\n\nconst getValidationErrorsOfSlashedPath = (p: string): void | string => {\n if (typeof p !== 'string') return `it is not a string. (it is a ${typeof p})`\n\n const components = p.split(/\\//)\n if (components.length === 0) return `it is empty.`\n\n for (let i = 0; i < components.length; i++) {\n const component = components[i].trim()\n if (component.length === 0) return `the component #${i + 1} is empty.`\n if (component.length > 64)\n return `the component '${component}' must have 64 characters or less.`\n }\n}\n\n/**\n * Sanitizes a `path` and warns the user if the input doesn't match the sanitized output.\n *\n * See {@link normalizeSlashedPath} for examples of how we do sanitization.\n */\nexport function validateAndSanitiseSlashedPathOrThrow(\n unsanitisedPath: string,\n fnName: string,\n) {\n const sanitisedPath = normalizeSlashedPath(unsanitisedPath)\n if (process.env.NODE_ENV !== 'development') {\n return sanitisedPath\n }\n const validation = getValidationErrorsOfSlashedPath(sanitisedPath)\n if (validation) {\n throw new InvalidArgumentError(\n `The path in ${fnName}(${\n typeof unsanitisedPath === 'string' ? `\"${unsanitisedPath}\"` : ''\n }) is invalid because ${validation}`,\n )\n }\n if (unsanitisedPath !== sanitisedPath) {\n notify.warning(\n 'Invalid path provided to object',\n `The path in \\`${fnName}(\"${unsanitisedPath}\")\\` was sanitized to \\`\"${sanitisedPath}\"\\`.\\n\\n` +\n 'Please replace the path with the sanitized one, otherwise it will likely break in the future.',\n [\n {\n url: 'https://www.theatrejs.com/docs/latest/manual/objects#creating-sheet-objects',\n title: 'Sheet Objects',\n },\n {\n url: 'https://www.theatrejs.com/docs/latest/api/core#sheet.object',\n title: 'API',\n },\n ],\n )\n }\n return sanitisedPath\n}\n", "import {privateAPI, setPrivateAPI} from '@theatre/core/privateAPIs'\nimport type {IProject} from '@theatre/core/projects/TheatreProject'\nimport type TheatreSequence from '@theatre/core/sequences/TheatreSequence'\nimport type {ISequence} from '@theatre/core/sequences/TheatreSequence'\nimport type {PropTypeConfig_Compound} from '@theatre/core/propTypes'\nimport {compound} from '@theatre/core/propTypes'\nimport type {ISheetObject} from '@theatre/core/sheetObjects/TheatreSheetObject'\nimport type Sheet from '@theatre/core/sheets/Sheet'\nimport type {SheetAddress} from '@theatre/shared/utils/addresses'\nimport {InvalidArgumentError} from '@theatre/shared/utils/errors'\nimport {validateAndSanitiseSlashedPathOrThrow} from '@theatre/shared/utils/slashedPaths'\nimport type {$FixMe, $IntentionalAny} from '@theatre/shared/utils/types'\nimport userReadableTypeOfValue from '@theatre/shared/utils/userReadableTypeOfValue'\nimport deepEqual from 'fast-deep-equal'\nimport type {\n UnknownShorthandCompoundProps,\n UnknownValidCompoundProps,\n} from '@theatre/core/propTypes/internals'\nimport type SheetObject from '@theatre/core/sheetObjects/SheetObject'\nimport type {ObjectAddressKey} from '@theatre/shared/utils/ids'\nimport {notify} from '@theatre/shared/notify'\n\nexport type SheetObjectPropTypeConfig =\n PropTypeConfig_Compound\n\nexport type SheetObjectAction = (object: ISheetObject) => void\n\nexport type SheetObjectActionsConfig = Record\n\nexport interface ISheet {\n /**\n * All sheets have `sheet.type === 'Theatre_Sheet_PublicAPI'`\n */\n readonly type: 'Theatre_Sheet_PublicAPI'\n\n /**\n * The Project this Sheet belongs to\n */\n readonly project: IProject\n\n /**\n * The address of the Sheet\n */\n readonly address: SheetAddress\n\n /**\n * Creates a child object for the sheet\n *\n * **Docs: https://www.theatrejs.com/docs/latest/manual/objects**\n *\n * @param key - Each object is identified by a key, which is a non-empty string\n * @param props - The props of the object. See examples\n * @param options - (Optional) Provide `{reconfigure: true}` to reconfigure an existing object, or `{actions: { ... }}` to add custom buttons to the UI. Read the example below for details.\n *\n * @returns An Object\n *\n * @example\n * Usage:\n * ```ts\n * // Create an object named \"a unique key\" with no props\n * const obj = sheet.object(\"a unique key\", {})\n * obj.address.objectKey // \"a unique key\"\n *\n *\n * // Create an object with {x: 0}\n * const obj = sheet.object(\"obj\", {x: 0})\n * obj.value.x // returns 0 or the current number that the user has set\n *\n * // Create an object with nested props\n * const obj = sheet.object(\"obj\", {position: {x: 0, y: 0}})\n * obj.value.position // {x: 0, y: 0}\n *\n * // you can also reconfigure an existing object:\n * const obj = sheet.object(\"obj\", {foo: 0})\n * console.log(object.value.foo) // prints 0\n *\n * const obj2 = sheet.object(\"obj\", {bar: 0}, {reconfigure: true})\n * console.log(object.value.foo) // prints undefined, since we've removed this prop via reconfiguring the object\n * console.log(object.value.bar) // prints 0, since we've introduced this prop by reconfiguring the object\n *\n * assert(obj === obj2) // passes, because reconfiguring the object returns the same object\n *\n * // you can add custom actions to an object:\n * const obj = sheet.object(\"obj\", {foo: 0}, {\n * actions: {\n * // This will display a button in the UI that will reset the value of `foo` to 0\n * Reset: () => {\n * studio.transaction((api) => {\n * api.set(obj.props.foo, 0)\n * })\n * }\n * }\n * })\n * ```\n */\n object(\n key: string,\n props: Props,\n options?: {\n reconfigure?: boolean\n __actions__THIS_API_IS_UNSTABLE_AND_WILL_CHANGE_IN_THE_NEXT_VERSION?: SheetObjectActionsConfig\n },\n ): ISheetObject\n\n /**\n * Detaches a previously created child object from the sheet.\n *\n * If you call `sheet.object(key)` again with the same `key`, the object's values of the object's\n * props WILL NOT be reset to their initial values.\n *\n * @param key - The `key` of the object previously given to `sheet.object(key, ...)`.\n */\n detachObject(key: string): void\n\n /**\n * The Sequence of this Sheet\n */\n readonly sequence: ISequence\n}\n\nconst weakMapOfUnsanitizedProps = new WeakMap<\n SheetObject,\n UnknownShorthandCompoundProps\n>()\n\nexport default class TheatreSheet implements ISheet {\n get type(): 'Theatre_Sheet_PublicAPI' {\n return 'Theatre_Sheet_PublicAPI'\n }\n /**\n * @internal\n */\n constructor(sheet: Sheet) {\n setPrivateAPI(this, sheet)\n }\n\n object(\n key: string,\n config: Props,\n opts?: {\n reconfigure?: boolean\n __actions__THIS_API_IS_UNSTABLE_AND_WILL_CHANGE_IN_THE_NEXT_VERSION?: SheetObjectActionsConfig\n },\n ): ISheetObject {\n const internal = privateAPI(this)\n const sanitizedPath = validateAndSanitiseSlashedPathOrThrow(\n key,\n `sheet.object`,\n )\n\n const existingObject = internal.getObject(sanitizedPath as ObjectAddressKey)\n\n /**\n * Future: `nativeObject` Idea is to potentially allow the user to provide their own\n * object in to the object call as a way to keep a handle to an underlying object via\n * the {@link ISheetObject}.\n *\n * For example, a THREEjs object or an HTMLElement is passed in.\n */\n const nativeObject = null\n\n const actions =\n opts?.__actions__THIS_API_IS_UNSTABLE_AND_WILL_CHANGE_IN_THE_NEXT_VERSION\n\n if (existingObject) {\n if (process.env.NODE_ENV !== 'production') {\n const prevConfig = weakMapOfUnsanitizedProps.get(existingObject)\n if (prevConfig) {\n if (opts?.reconfigure === true) {\n const sanitizedConfig = compound(config)\n existingObject.template.reconfigure(sanitizedConfig)\n weakMapOfUnsanitizedProps.set(existingObject, config)\n return existingObject.publicApi as $IntentionalAny\n } else if (!deepEqual(config, prevConfig)) {\n throw new Error(\n `You seem to have called sheet.object(\"${key}\", config) twice, with different values for \\`config\\`. ` +\n `This is disallowed because changing the config of an object on the fly would make it difficult to reason about.\\n\\n` +\n `You can fix this by either re-using the existing object, or calling sheet.object(\"${key}\", config) with the same config.\\n\\n` +\n `If you mean to reconfigure the object's config, set \\`{reconfigure: true}\\` in sheet.object(\"${key}\", config, {reconfigure: true})`,\n )\n }\n }\n }\n\n if (actions) {\n existingObject.template._temp_setActions(actions)\n }\n\n return existingObject.publicApi as $IntentionalAny\n } else {\n const sanitizedConfig = compound(config)\n const object = internal.createObject(\n sanitizedPath as ObjectAddressKey,\n nativeObject,\n sanitizedConfig,\n actions,\n )\n if (process.env.NODE_ENV !== 'production') {\n weakMapOfUnsanitizedProps.set(object as $FixMe, config)\n }\n return object.publicApi as $IntentionalAny\n }\n }\n\n get sequence(): TheatreSequence {\n return privateAPI(this).getSequence().publicApi\n }\n\n get project(): IProject {\n return privateAPI(this).project.publicApi\n }\n\n get address(): SheetAddress {\n return {...privateAPI(this).address}\n }\n\n detachObject(key: string) {\n const internal = privateAPI(this)\n const sanitizedPath = validateAndSanitiseSlashedPathOrThrow(\n key,\n `sheet.deleteObject(\"${key}\")`,\n ) as ObjectAddressKey\n\n const obj = internal.getObject(sanitizedPath)\n if (!obj) {\n notify.warning(\n `Couldn\\'t delete object \"${sanitizedPath}\"`,\n `There is no object with key \"${sanitizedPath}\".\n\nTo fix this, make sure you are calling \\`sheet.deleteObject(\"${sanitizedPath}\")\\` with the correct key.`,\n )\n console.warn(`Object key \"${sanitizedPath}\" does not exist.`)\n return\n }\n\n internal.deleteObject(sanitizedPath as ObjectAddressKey)\n }\n}\n\nconst validateSequenceNameOrThrow = (value: string) => {\n if (typeof value !== 'string') {\n throw new InvalidArgumentError(\n `Argument 'name' in \\`sheet.getSequence(name)\\` must be a string. Instead, it was ${userReadableTypeOfValue(\n value,\n )}.`,\n )\n }\n\n const idTrimmed = value.trim()\n if (idTrimmed.length !== value.length) {\n throw new InvalidArgumentError(\n `Argument 'name' in \\`sheet.getSequence(\"${value}\")\\` should not have surrounding whitespace.`,\n )\n }\n\n if (idTrimmed.length < 3) {\n throw new InvalidArgumentError(\n `Argument 'name' in \\`sheet.getSequence(\"${value}\")\\` should be at least 3 characters long.`,\n )\n }\n}\n", "import type Project from '@theatre/core/projects/Project'\nimport Sequence from '@theatre/core/sequences/Sequence'\nimport type SheetObject from '@theatre/core/sheetObjects/SheetObject'\nimport type {\n SheetObjectActionsConfig,\n SheetObjectPropTypeConfig,\n} from '@theatre/core/sheets/TheatreSheet'\nimport TheatreSheet from '@theatre/core/sheets/TheatreSheet'\nimport type {SheetAddress} from '@theatre/shared/utils/addresses'\nimport {Atom, prism, val} from '@theatre/dataverse'\nimport type SheetTemplate from './SheetTemplate'\nimport type {ObjectAddressKey, SheetInstanceId} from '@theatre/shared/utils/ids'\nimport type {StrictRecord} from '@theatre/shared/utils/types'\nimport type {ILogger} from '@theatre/shared/logger'\nimport {isInteger} from 'lodash-es'\n\ntype SheetObjectMap = StrictRecord\n\n/**\n * Future: `nativeObject` Idea is to potentially allow the user to provide their own\n * object in to the object call as a way to keep a handle to an underlying object via\n * the {@link ISheetObject}.\n *\n * For example, a THREEjs object or an HTMLElement is passed in.\n */\nexport type ObjectNativeObject = unknown\n\nexport default class Sheet {\n private readonly _objects: Atom = new Atom({})\n private _sequence: undefined | Sequence\n readonly address: SheetAddress\n readonly publicApi: TheatreSheet\n readonly project: Project\n readonly objectsP = this._objects.pointer\n type: 'Theatre_Sheet' = 'Theatre_Sheet'\n readonly _logger: ILogger\n\n constructor(\n readonly template: SheetTemplate,\n public readonly instanceId: SheetInstanceId,\n ) {\n this._logger = template.project._logger.named('Sheet', instanceId)\n this._logger._trace('creating sheet')\n this.project = template.project\n this.address = {\n ...template.address,\n sheetInstanceId: this.instanceId,\n }\n\n this.publicApi = new TheatreSheet(this)\n }\n\n /**\n * @remarks At some point, we have to reconcile the concept of \"an object\"\n * with that of \"an element.\"\n */\n createObject(\n objectKey: ObjectAddressKey,\n nativeObject: ObjectNativeObject,\n config: SheetObjectPropTypeConfig,\n actions: SheetObjectActionsConfig = {},\n ): SheetObject {\n const objTemplate = this.template.getObjectTemplate(\n objectKey,\n nativeObject,\n config,\n actions,\n )\n\n const object = objTemplate.createInstance(this, nativeObject, config)\n\n this._objects.setByPointer((p) => p[objectKey], object)\n\n return object\n }\n\n getObject(key: ObjectAddressKey): SheetObject | undefined {\n return this._objects.get()[key]\n }\n\n deleteObject(objectKey: ObjectAddressKey) {\n this._objects.reduce((state) => {\n const newState = {...state}\n delete newState[objectKey]\n return newState\n })\n }\n\n getSequence(): Sequence {\n if (!this._sequence) {\n const lengthD = prism(() => {\n const unsanitized = val(\n this.project.pointers.historic.sheetsById[this.address.sheetId]\n .sequence.length,\n )\n return sanitizeSequenceLength(unsanitized)\n })\n\n const subUnitsPerUnitD = prism(() => {\n const unsanitized = val(\n this.project.pointers.historic.sheetsById[this.address.sheetId]\n .sequence.subUnitsPerUnit,\n )\n return sanitizeSequenceSubUnitsPerUnit(unsanitized)\n })\n\n this._sequence = new Sequence(\n this.template.project,\n this,\n lengthD,\n subUnitsPerUnitD,\n )\n }\n return this._sequence\n }\n}\n\nconst sanitizeSequenceLength = (len: number | undefined): number =>\n typeof len === 'number' && isFinite(len) && len > 0 ? len : 10\n\nconst sanitizeSequenceSubUnitsPerUnit = (subs: number | undefined): number =>\n typeof subs === 'number' && isInteger(subs) && subs >= 1 && subs <= 1000\n ? subs\n : 30\n", "import type Project from '@theatre/core/projects/Project'\nimport SheetObjectTemplate from '@theatre/core/sheetObjects/SheetObjectTemplate'\nimport type {\n SheetAddress,\n WithoutSheetInstance,\n} from '@theatre/shared/utils/addresses'\nimport {Atom} from '@theatre/dataverse'\nimport type {Pointer} from '@theatre/dataverse'\nimport Sheet from './Sheet'\nimport type {ObjectNativeObject} from './Sheet'\nimport type {\n SheetObjectActionsConfig,\n SheetObjectPropTypeConfig,\n} from './TheatreSheet'\nimport type {\n ObjectAddressKey,\n SheetId,\n SheetInstanceId,\n} from '@theatre/shared/utils/ids'\nimport type {StrictRecord} from '@theatre/shared/utils/types'\n\ntype SheetTemplateObjectTemplateMap = StrictRecord<\n ObjectAddressKey,\n SheetObjectTemplate\n>\n\nexport default class SheetTemplate {\n readonly type: 'Theatre_SheetTemplate' = 'Theatre_SheetTemplate'\n readonly address: WithoutSheetInstance\n private _instances = new Atom>({})\n readonly instancesP: Pointer> =\n this._instances.pointer\n\n private _objectTemplates = new Atom({})\n readonly objectTemplatesP = this._objectTemplates.pointer\n\n constructor(readonly project: Project, sheetId: SheetId) {\n this.address = {...project.address, sheetId}\n }\n\n getInstance(instanceId: SheetInstanceId): Sheet {\n let inst = this._instances.get()[instanceId]\n\n if (!inst) {\n inst = new Sheet(this, instanceId)\n this._instances.setByPointer((p) => p[instanceId], inst)\n }\n\n return inst\n }\n\n getObjectTemplate(\n objectKey: ObjectAddressKey,\n nativeObject: ObjectNativeObject,\n config: SheetObjectPropTypeConfig,\n actions: SheetObjectActionsConfig,\n ): SheetObjectTemplate {\n let template = this._objectTemplates.get()[objectKey]\n\n if (!template) {\n template = new SheetObjectTemplate(\n this,\n objectKey,\n nativeObject,\n config,\n actions,\n )\n this._objectTemplates.setByPointer((p) => p[objectKey], template)\n }\n\n return template\n }\n}\n", "const delay = (dur: number) =>\n new Promise((resolve) => setTimeout(resolve, dur))\n\nexport default delay\n", "const errors = {\n\t0: \"Illegal state\",\n\t1: \"Immer drafts cannot have computed properties\",\n\t2: \"This object has been frozen and should not be mutated\",\n\t3(data: any) {\n\t\treturn (\n\t\t\t\"Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? \" +\n\t\t\tdata\n\t\t)\n\t},\n\t4: \"An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.\",\n\t5: \"Immer forbids circular references\",\n\t6: \"The first or second argument to `produce` must be a function\",\n\t7: \"The third argument to `produce` must be a function or undefined\",\n\t8: \"First argument to `createDraft` must be a plain object, an array, or an immerable object\",\n\t9: \"First argument to `finishDraft` must be a draft returned by `createDraft`\",\n\t10: \"The given draft is already finalized\",\n\t11: \"Object.defineProperty() cannot be used on an Immer draft\",\n\t12: \"Object.setPrototypeOf() cannot be used on an Immer draft\",\n\t13: \"Immer only supports deleting array indices\",\n\t14: \"Immer only supports setting array indices and the 'length' property\",\n\t15(path: string) {\n\t\treturn \"Cannot apply patch, path doesn't resolve: \" + path\n\t},\n\t16: 'Sets cannot have \"replace\" patches.',\n\t17(op: string) {\n\t\treturn \"Unsupported patch operation: \" + op\n\t},\n\t18(plugin: string) {\n\t\treturn `The plugin for '${plugin}' has not been loaded into Immer. To enable the plugin, import and call \\`enable${plugin}()\\` when initializing your application.`\n\t},\n\t20: \"Cannot use proxies if Proxy, Proxy.revocable or Reflect are not available\",\n\t21(thing: string) {\n\t\treturn `produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '${thing}'`\n\t},\n\t22(thing: string) {\n\t\treturn `'current' expects a draft, got: ${thing}`\n\t},\n\t23(thing: string) {\n\t\treturn `'original' expects a draft, got: ${thing}`\n\t},\n\t24: \"Patching reserved attributes like __proto__, prototype and constructor is not allowed\"\n} as const\n\nexport function die(error: keyof typeof errors, ...args: any[]): never {\n\tif (__DEV__) {\n\t\tconst e = errors[error]\n\t\tconst msg = !e\n\t\t\t? \"unknown error nr: \" + error\n\t\t\t: typeof e === \"function\"\n\t\t\t? e.apply(null, args as any)\n\t\t\t: e\n\t\tthrow new Error(`[Immer] ${msg}`)\n\t}\n\tthrow new Error(\n\t\t`[Immer] minified error nr: ${error}${\n\t\t\targs.length ? \" \" + args.map(s => `'${s}'`).join(\",\") : \"\"\n\t\t}. Find the full error at: https://bit.ly/3cXEKWf`\n\t)\n}\n", "import {\n\tDRAFT_STATE,\n\tDRAFTABLE,\n\thasSet,\n\tObjectish,\n\tDrafted,\n\tAnyObject,\n\tAnyMap,\n\tAnySet,\n\tImmerState,\n\thasMap,\n\tArchtype,\n\tdie\n} from \"../internal\"\n\n/** Returns true if the given value is an Immer draft */\n/*#__PURE__*/\nexport function isDraft(value: any): boolean {\n\treturn !!value && !!value[DRAFT_STATE]\n}\n\n/** Returns true if the given value can be drafted by Immer */\n/*#__PURE__*/\nexport function isDraftable(value: any): boolean {\n\tif (!value) return false\n\treturn (\n\t\tisPlainObject(value) ||\n\t\tArray.isArray(value) ||\n\t\t!!value[DRAFTABLE] ||\n\t\t!!value.constructor[DRAFTABLE] ||\n\t\tisMap(value) ||\n\t\tisSet(value)\n\t)\n}\n\nconst objectCtorString = Object.prototype.constructor.toString()\n/*#__PURE__*/\nexport function isPlainObject(value: any): boolean {\n\tif (!value || typeof value !== \"object\") return false\n\tconst proto = Object.getPrototypeOf(value)\n\tif (proto === null) {\n\t\treturn true\n\t}\n\tconst Ctor =\n\t\tObject.hasOwnProperty.call(proto, \"constructor\") && proto.constructor\n\n\tif (Ctor === Object) return true\n\n\treturn (\n\t\ttypeof Ctor == \"function\" &&\n\t\tFunction.toString.call(Ctor) === objectCtorString\n\t)\n}\n\n/** Get the underlying object that is represented by the given draft */\n/*#__PURE__*/\nexport function original(value: T): T | undefined\nexport function original(value: Drafted): any {\n\tif (!isDraft(value)) die(23, value)\n\treturn value[DRAFT_STATE].base_\n}\n\n/*#__PURE__*/\nexport const ownKeys: (target: AnyObject) => PropertyKey[] =\n\ttypeof Reflect !== \"undefined\" && Reflect.ownKeys\n\t\t? Reflect.ownKeys\n\t\t: typeof Object.getOwnPropertySymbols !== \"undefined\"\n\t\t? obj =>\n\t\t\t\tObject.getOwnPropertyNames(obj).concat(\n\t\t\t\t\tObject.getOwnPropertySymbols(obj) as any\n\t\t\t\t)\n\t\t: /* istanbul ignore next */ Object.getOwnPropertyNames\n\nexport const getOwnPropertyDescriptors =\n\tObject.getOwnPropertyDescriptors ||\n\tfunction getOwnPropertyDescriptors(target: any) {\n\t\t// Polyfill needed for Hermes and IE, see https://github.com/facebook/hermes/issues/274\n\t\tconst res: any = {}\n\t\townKeys(target).forEach(key => {\n\t\t\tres[key] = Object.getOwnPropertyDescriptor(target, key)\n\t\t})\n\t\treturn res\n\t}\n\nexport function each(\n\tobj: T,\n\titer: (key: string | number, value: any, source: T) => void,\n\tenumerableOnly?: boolean\n): void\nexport function each(obj: any, iter: any, enumerableOnly = false) {\n\tif (getArchtype(obj) === Archtype.Object) {\n\t\t;(enumerableOnly ? Object.keys : ownKeys)(obj).forEach(key => {\n\t\t\tif (!enumerableOnly || typeof key !== \"symbol\") iter(key, obj[key], obj)\n\t\t})\n\t} else {\n\t\tobj.forEach((entry: any, index: any) => iter(index, entry, obj))\n\t}\n}\n\n/*#__PURE__*/\nexport function getArchtype(thing: any): Archtype {\n\t/* istanbul ignore next */\n\tconst state: undefined | ImmerState = thing[DRAFT_STATE]\n\treturn state\n\t\t? state.type_ > 3\n\t\t\t? state.type_ - 4 // cause Object and Array map back from 4 and 5\n\t\t\t: (state.type_ as any) // others are the same\n\t\t: Array.isArray(thing)\n\t\t? Archtype.Array\n\t\t: isMap(thing)\n\t\t? Archtype.Map\n\t\t: isSet(thing)\n\t\t? Archtype.Set\n\t\t: Archtype.Object\n}\n\n/*#__PURE__*/\nexport function has(thing: any, prop: PropertyKey): boolean {\n\treturn getArchtype(thing) === Archtype.Map\n\t\t? thing.has(prop)\n\t\t: Object.prototype.hasOwnProperty.call(thing, prop)\n}\n\n/*#__PURE__*/\nexport function get(thing: AnyMap | AnyObject, prop: PropertyKey): any {\n\t// @ts-ignore\n\treturn getArchtype(thing) === Archtype.Map ? thing.get(prop) : thing[prop]\n}\n\n/*#__PURE__*/\nexport function set(thing: any, propOrOldValue: PropertyKey, value: any) {\n\tconst t = getArchtype(thing)\n\tif (t === Archtype.Map) thing.set(propOrOldValue, value)\n\telse if (t === Archtype.Set) {\n\t\tthing.delete(propOrOldValue)\n\t\tthing.add(value)\n\t} else thing[propOrOldValue] = value\n}\n\n/*#__PURE__*/\nexport function is(x: any, y: any): boolean {\n\t// From: https://github.com/facebook/fbjs/blob/c69904a511b900266935168223063dd8772dfc40/packages/fbjs/src/core/shallowEqual.js\n\tif (x === y) {\n\t\treturn x !== 0 || 1 / x === 1 / y\n\t} else {\n\t\treturn x !== x && y !== y\n\t}\n}\n\n/*#__PURE__*/\nexport function isMap(target: any): target is AnyMap {\n\treturn hasMap && target instanceof Map\n}\n\n/*#__PURE__*/\nexport function isSet(target: any): target is AnySet {\n\treturn hasSet && target instanceof Set\n}\n/*#__PURE__*/\nexport function latest(state: ImmerState): any {\n\treturn state.copy_ || state.base_\n}\n\n/*#__PURE__*/\nexport function shallowCopy(base: any) {\n\tif (Array.isArray(base)) return Array.prototype.slice.call(base)\n\tconst descriptors = getOwnPropertyDescriptors(base)\n\tdelete descriptors[DRAFT_STATE as any]\n\tlet keys = ownKeys(descriptors)\n\tfor (let i = 0; i < keys.length; i++) {\n\t\tconst key: any = keys[i]\n\t\tconst desc = descriptors[key]\n\t\tif (desc.writable === false) {\n\t\t\tdesc.writable = true\n\t\t\tdesc.configurable = true\n\t\t}\n\t\t// like object.assign, we will read any _own_, get/set accessors. This helps in dealing\n\t\t// with libraries that trap values, like mobx or vue\n\t\t// unlike object.assign, non-enumerables will be copied as well\n\t\tif (desc.get || desc.set)\n\t\t\tdescriptors[key] = {\n\t\t\t\tconfigurable: true,\n\t\t\t\twritable: true, // could live with !!desc.set as well here...\n\t\t\t\tenumerable: desc.enumerable,\n\t\t\t\tvalue: base[key]\n\t\t\t}\n\t}\n\treturn Object.create(Object.getPrototypeOf(base), descriptors)\n}\n\n/**\n * Freezes draftable objects. Returns the original object.\n * By default freezes shallowly, but if the second argument is `true` it will freeze recursively.\n *\n * @param obj\n * @param deep\n */\nexport function freeze(obj: T, deep?: boolean): T\nexport function freeze(obj: any, deep: boolean = false): T {\n\tif (isFrozen(obj) || isDraft(obj) || !isDraftable(obj)) return obj\n\tif (getArchtype(obj) > 1 /* Map or Set */) {\n\t\tobj.set = obj.add = obj.clear = obj.delete = dontMutateFrozenCollections as any\n\t}\n\tObject.freeze(obj)\n\tif (deep) each(obj, (key, value) => freeze(value, true), true)\n\treturn obj\n}\n\nfunction dontMutateFrozenCollections() {\n\tdie(2)\n}\n\nexport function isFrozen(obj: any): boolean {\n\tif (obj == null || typeof obj !== \"object\") return true\n\t// See #600, IE dies on non-objects in Object.isFrozen\n\treturn Object.isFrozen(obj)\n}\n", "import {\n\tImmerState,\n\tPatch,\n\tImmerScope,\n\tDrafted,\n\tAnyObject,\n\tImmerBaseState,\n\tAnyMap,\n\tAnySet,\n\tProxyType,\n\tdie\n} from \"../internal\"\n\n/** Plugin utilities */\nconst plugins: {\n\tPatches?: {\n\t\tgeneratePatches_(\n\t\t\tstate: ImmerState,\n\t\t\tbasePath: PatchPath,\n\t\t\tpatches: Patch[],\n\t\t\tinversePatches: Patch[]\n\t\t): void\n\t\tgenerateReplacementPatches_(\n\t\t\trootState: ImmerState,\n\t\t\treplacement: any,\n\t\t\tpatches: Patch[],\n\t\t\tinversePatches: Patch[]\n\t\t): void\n\t\tapplyPatches_(draft: T, patches: Patch[]): T\n\t}\n\tES5?: {\n\t\twillFinalizeES5_(scope: ImmerScope, result: any, isReplaced: boolean): void\n\t\tcreateES5Proxy_(\n\t\t\tbase: T,\n\t\t\tparent?: ImmerState\n\t\t): Drafted\n\t\thasChanges_(state: ES5ArrayState | ES5ObjectState): boolean\n\t}\n\tMapSet?: {\n\t\tproxyMap_(target: T, parent?: ImmerState): T\n\t\tproxySet_(target: T, parent?: ImmerState): T\n\t}\n} = {}\n\ntype Plugins = typeof plugins\n\nexport function getPlugin(\n\tpluginKey: K\n): Exclude {\n\tconst plugin = plugins[pluginKey]\n\tif (!plugin) {\n\t\tdie(18, pluginKey)\n\t}\n\t// @ts-ignore\n\treturn plugin\n}\n\nexport function loadPlugin(\n\tpluginKey: K,\n\timplementation: Plugins[K]\n): void {\n\tif (!plugins[pluginKey]) plugins[pluginKey] = implementation\n}\n\n/** ES5 Plugin */\n\ninterface ES5BaseState extends ImmerBaseState {\n\tassigned_: {[key: string]: any}\n\tparent_?: ImmerState\n\trevoked_: boolean\n}\n\nexport interface ES5ObjectState extends ES5BaseState {\n\ttype_: ProxyType.ES5Object\n\tdraft_: Drafted\n\tbase_: AnyObject\n\tcopy_: AnyObject | null\n}\n\nexport interface ES5ArrayState extends ES5BaseState {\n\ttype_: ProxyType.ES5Array\n\tdraft_: Drafted\n\tbase_: any\n\tcopy_: any\n}\n\n/** Map / Set plugin */\n\nexport interface MapState extends ImmerBaseState {\n\ttype_: ProxyType.Map\n\tcopy_: AnyMap | undefined\n\tassigned_: Map | undefined\n\tbase_: AnyMap\n\trevoked_: boolean\n\tdraft_: Drafted\n}\n\nexport interface SetState extends ImmerBaseState {\n\ttype_: ProxyType.Set\n\tcopy_: AnySet | undefined\n\tbase_: AnySet\n\tdrafts_: Map // maps the original value to the draft value in the new set\n\trevoked_: boolean\n\tdraft_: Drafted\n}\n\n/** Patches plugin */\n\nexport type PatchPath = (string | number)[]\n", "import {\n\tPatch,\n\tPatchListener,\n\tDrafted,\n\tImmer,\n\tDRAFT_STATE,\n\tImmerState,\n\tProxyType,\n\tgetPlugin\n} from \"../internal\"\nimport {die} from \"../utils/errors\"\n\n/** Each scope represents a `produce` call. */\n\nexport interface ImmerScope {\n\tpatches_?: Patch[]\n\tinversePatches_?: Patch[]\n\tcanAutoFreeze_: boolean\n\tdrafts_: any[]\n\tparent_?: ImmerScope\n\tpatchListener_?: PatchListener\n\timmer_: Immer\n\tunfinalizedDrafts_: number\n}\n\nlet currentScope: ImmerScope | undefined\n\nexport function getCurrentScope() {\n\tif (__DEV__ && !currentScope) die(0)\n\treturn currentScope!\n}\n\nfunction createScope(\n\tparent_: ImmerScope | undefined,\n\timmer_: Immer\n): ImmerScope {\n\treturn {\n\t\tdrafts_: [],\n\t\tparent_,\n\t\timmer_,\n\t\t// Whenever the modified draft contains a draft from another scope, we\n\t\t// need to prevent auto-freezing so the unowned draft can be finalized.\n\t\tcanAutoFreeze_: true,\n\t\tunfinalizedDrafts_: 0\n\t}\n}\n\nexport function usePatchesInScope(\n\tscope: ImmerScope,\n\tpatchListener?: PatchListener\n) {\n\tif (patchListener) {\n\t\tgetPlugin(\"Patches\") // assert we have the plugin\n\t\tscope.patches_ = []\n\t\tscope.inversePatches_ = []\n\t\tscope.patchListener_ = patchListener\n\t}\n}\n\nexport function revokeScope(scope: ImmerScope) {\n\tleaveScope(scope)\n\tscope.drafts_.forEach(revokeDraft)\n\t// @ts-ignore\n\tscope.drafts_ = null\n}\n\nexport function leaveScope(scope: ImmerScope) {\n\tif (scope === currentScope) {\n\t\tcurrentScope = scope.parent_\n\t}\n}\n\nexport function enterScope(immer: Immer) {\n\treturn (currentScope = createScope(currentScope, immer))\n}\n\nfunction revokeDraft(draft: Drafted) {\n\tconst state: ImmerState = draft[DRAFT_STATE]\n\tif (\n\t\tstate.type_ === ProxyType.ProxyObject ||\n\t\tstate.type_ === ProxyType.ProxyArray\n\t)\n\t\tstate.revoke_()\n\telse state.revoked_ = true\n}\n", "import {\n\tImmerScope,\n\tDRAFT_STATE,\n\tisDraftable,\n\tNOTHING,\n\tPatchPath,\n\teach,\n\thas,\n\tfreeze,\n\tImmerState,\n\tisDraft,\n\tSetState,\n\tset,\n\tProxyType,\n\tgetPlugin,\n\tdie,\n\trevokeScope,\n\tisFrozen,\n\tshallowCopy\n} from \"../internal\"\n\nexport function processResult(result: any, scope: ImmerScope) {\n\tscope.unfinalizedDrafts_ = scope.drafts_.length\n\tconst baseDraft = scope.drafts_![0]\n\tconst isReplaced = result !== undefined && result !== baseDraft\n\tif (!scope.immer_.useProxies_)\n\t\tgetPlugin(\"ES5\").willFinalizeES5_(scope, result, isReplaced)\n\tif (isReplaced) {\n\t\tif (baseDraft[DRAFT_STATE].modified_) {\n\t\t\trevokeScope(scope)\n\t\t\tdie(4)\n\t\t}\n\t\tif (isDraftable(result)) {\n\t\t\t// Finalize the result in case it contains (or is) a subset of the draft.\n\t\t\tresult = finalize(scope, result)\n\t\t\tif (!scope.parent_) maybeFreeze(scope, result)\n\t\t}\n\t\tif (scope.patches_) {\n\t\t\tgetPlugin(\"Patches\").generateReplacementPatches_(\n\t\t\t\tbaseDraft[DRAFT_STATE],\n\t\t\t\tresult,\n\t\t\t\tscope.patches_,\n\t\t\t\tscope.inversePatches_!\n\t\t\t)\n\t\t}\n\t} else {\n\t\t// Finalize the base draft.\n\t\tresult = finalize(scope, baseDraft, [])\n\t}\n\trevokeScope(scope)\n\tif (scope.patches_) {\n\t\tscope.patchListener_!(scope.patches_, scope.inversePatches_!)\n\t}\n\treturn result !== NOTHING ? result : undefined\n}\n\nfunction finalize(rootScope: ImmerScope, value: any, path?: PatchPath) {\n\t// Don't recurse in tho recursive data structures\n\tif (isFrozen(value)) return value\n\n\tconst state: ImmerState = value[DRAFT_STATE]\n\t// A plain object, might need freezing, might contain drafts\n\tif (!state) {\n\t\teach(\n\t\t\tvalue,\n\t\t\t(key, childValue) =>\n\t\t\t\tfinalizeProperty(rootScope, state, value, key, childValue, path),\n\t\t\ttrue // See #590, don't recurse into non-enumarable of non drafted objects\n\t\t)\n\t\treturn value\n\t}\n\t// Never finalize drafts owned by another scope.\n\tif (state.scope_ !== rootScope) return value\n\t// Unmodified draft, return the (frozen) original\n\tif (!state.modified_) {\n\t\tmaybeFreeze(rootScope, state.base_, true)\n\t\treturn state.base_\n\t}\n\t// Not finalized yet, let's do that now\n\tif (!state.finalized_) {\n\t\tstate.finalized_ = true\n\t\tstate.scope_.unfinalizedDrafts_--\n\t\tconst result =\n\t\t\t// For ES5, create a good copy from the draft first, with added keys and without deleted keys.\n\t\t\tstate.type_ === ProxyType.ES5Object || state.type_ === ProxyType.ES5Array\n\t\t\t\t? (state.copy_ = shallowCopy(state.draft_))\n\t\t\t\t: state.copy_\n\t\t// Finalize all children of the copy\n\t\t// For sets we clone before iterating, otherwise we can get in endless loop due to modifying during iteration, see #628\n\t\t// Although the original test case doesn't seem valid anyway, so if this in the way we can turn the next line\n\t\t// back to each(result, ....)\n\t\teach(\n\t\t\tstate.type_ === ProxyType.Set ? new Set(result) : result,\n\t\t\t(key, childValue) =>\n\t\t\t\tfinalizeProperty(rootScope, state, result, key, childValue, path)\n\t\t)\n\t\t// everything inside is frozen, we can freeze here\n\t\tmaybeFreeze(rootScope, result, false)\n\t\t// first time finalizing, let's create those patches\n\t\tif (path && rootScope.patches_) {\n\t\t\tgetPlugin(\"Patches\").generatePatches_(\n\t\t\t\tstate,\n\t\t\t\tpath,\n\t\t\t\trootScope.patches_,\n\t\t\t\trootScope.inversePatches_!\n\t\t\t)\n\t\t}\n\t}\n\treturn state.copy_\n}\n\nfunction finalizeProperty(\n\trootScope: ImmerScope,\n\tparentState: undefined | ImmerState,\n\ttargetObject: any,\n\tprop: string | number,\n\tchildValue: any,\n\trootPath?: PatchPath\n) {\n\tif (__DEV__ && childValue === targetObject) die(5)\n\tif (isDraft(childValue)) {\n\t\tconst path =\n\t\t\trootPath &&\n\t\t\tparentState &&\n\t\t\tparentState!.type_ !== ProxyType.Set && // Set objects are atomic since they have no keys.\n\t\t\t!has((parentState as Exclude).assigned_!, prop) // Skip deep patches for assigned keys.\n\t\t\t\t? rootPath!.concat(prop)\n\t\t\t\t: undefined\n\t\t// Drafts owned by `scope` are finalized here.\n\t\tconst res = finalize(rootScope, childValue, path)\n\t\tset(targetObject, prop, res)\n\t\t// Drafts from another scope must prevented to be frozen\n\t\t// if we got a draft back from finalize, we're in a nested produce and shouldn't freeze\n\t\tif (isDraft(res)) {\n\t\t\trootScope.canAutoFreeze_ = false\n\t\t} else return\n\t}\n\t// Search new objects for unfinalized drafts. Frozen objects should never contain drafts.\n\tif (isDraftable(childValue) && !isFrozen(childValue)) {\n\t\tif (!rootScope.immer_.autoFreeze_ && rootScope.unfinalizedDrafts_ < 1) {\n\t\t\t// optimization: if an object is not a draft, and we don't have to\n\t\t\t// deepfreeze everything, and we are sure that no drafts are left in the remaining object\n\t\t\t// cause we saw and finalized all drafts already; we can stop visiting the rest of the tree.\n\t\t\t// This benefits especially adding large data tree's without further processing.\n\t\t\t// See add-data.js perf test\n\t\t\treturn\n\t\t}\n\t\tfinalize(rootScope, childValue)\n\t\t// immer deep freezes plain objects, so if there is no parent state, we freeze as well\n\t\tif (!parentState || !parentState.scope_.parent_)\n\t\t\tmaybeFreeze(rootScope, childValue)\n\t}\n}\n\nfunction maybeFreeze(scope: ImmerScope, value: any, deep = false) {\n\tif (scope.immer_.autoFreeze_ && scope.canAutoFreeze_) {\n\t\tfreeze(value, deep)\n\t}\n}\n", "import {\n\teach,\n\thas,\n\tis,\n\tisDraftable,\n\tshallowCopy,\n\tlatest,\n\tImmerBaseState,\n\tImmerState,\n\tDrafted,\n\tAnyObject,\n\tAnyArray,\n\tObjectish,\n\tgetCurrentScope,\n\tDRAFT_STATE,\n\tdie,\n\tcreateProxy,\n\tProxyType\n} from \"../internal\"\n\ninterface ProxyBaseState extends ImmerBaseState {\n\tassigned_: {\n\t\t[property: string]: boolean\n\t}\n\tparent_?: ImmerState\n\trevoke_(): void\n}\n\nexport interface ProxyObjectState extends ProxyBaseState {\n\ttype_: ProxyType.ProxyObject\n\tbase_: any\n\tcopy_: any\n\tdraft_: Drafted\n}\n\nexport interface ProxyArrayState extends ProxyBaseState {\n\ttype_: ProxyType.ProxyArray\n\tbase_: AnyArray\n\tcopy_: AnyArray | null\n\tdraft_: Drafted\n}\n\ntype ProxyState = ProxyObjectState | ProxyArrayState\n\n/**\n * Returns a new draft of the `base` object.\n *\n * The second argument is the parent draft-state (used internally).\n */\nexport function createProxyProxy(\n\tbase: T,\n\tparent?: ImmerState\n): Drafted {\n\tconst isArray = Array.isArray(base)\n\tconst state: ProxyState = {\n\t\ttype_: isArray ? ProxyType.ProxyArray : (ProxyType.ProxyObject as any),\n\t\t// Track which produce call this is associated with.\n\t\tscope_: parent ? parent.scope_ : getCurrentScope()!,\n\t\t// True for both shallow and deep changes.\n\t\tmodified_: false,\n\t\t// Used during finalization.\n\t\tfinalized_: false,\n\t\t// Track which properties have been assigned (true) or deleted (false).\n\t\tassigned_: {},\n\t\t// The parent draft state.\n\t\tparent_: parent,\n\t\t// The base state.\n\t\tbase_: base,\n\t\t// The base proxy.\n\t\tdraft_: null as any, // set below\n\t\t// The base copy with any updated values.\n\t\tcopy_: null,\n\t\t// Called by the `produce` function.\n\t\trevoke_: null as any,\n\t\tisManual_: false\n\t}\n\n\t// the traps must target something, a bit like the 'real' base.\n\t// but also, we need to be able to determine from the target what the relevant state is\n\t// (to avoid creating traps per instance to capture the state in closure,\n\t// and to avoid creating weird hidden properties as well)\n\t// So the trick is to use 'state' as the actual 'target'! (and make sure we intercept everything)\n\t// Note that in the case of an array, we put the state in an array to have better Reflect defaults ootb\n\tlet target: T = state as any\n\tlet traps: ProxyHandler> = objectTraps\n\tif (isArray) {\n\t\ttarget = [state] as any\n\t\ttraps = arrayTraps\n\t}\n\n\tconst {revoke, proxy} = Proxy.revocable(target, traps)\n\tstate.draft_ = proxy as any\n\tstate.revoke_ = revoke\n\treturn proxy as any\n}\n\n/**\n * Object drafts\n */\nexport const objectTraps: ProxyHandler = {\n\tget(state, prop) {\n\t\tif (prop === DRAFT_STATE) return state\n\n\t\tconst source = latest(state)\n\t\tif (!has(source, prop)) {\n\t\t\t// non-existing or non-own property...\n\t\t\treturn readPropFromProto(state, source, prop)\n\t\t}\n\t\tconst value = source[prop]\n\t\tif (state.finalized_ || !isDraftable(value)) {\n\t\t\treturn value\n\t\t}\n\t\t// Check for existing draft in modified state.\n\t\t// Assigned values are never drafted. This catches any drafts we created, too.\n\t\tif (value === peek(state.base_, prop)) {\n\t\t\tprepareCopy(state)\n\t\t\treturn (state.copy_![prop as any] = createProxy(\n\t\t\t\tstate.scope_.immer_,\n\t\t\t\tvalue,\n\t\t\t\tstate\n\t\t\t))\n\t\t}\n\t\treturn value\n\t},\n\thas(state, prop) {\n\t\treturn prop in latest(state)\n\t},\n\townKeys(state) {\n\t\treturn Reflect.ownKeys(latest(state))\n\t},\n\tset(\n\t\tstate: ProxyObjectState,\n\t\tprop: string /* strictly not, but helps TS */,\n\t\tvalue\n\t) {\n\t\tconst desc = getDescriptorFromProto(latest(state), prop)\n\t\tif (desc?.set) {\n\t\t\t// special case: if this write is captured by a setter, we have\n\t\t\t// to trigger it with the correct context\n\t\t\tdesc.set.call(state.draft_, value)\n\t\t\treturn true\n\t\t}\n\t\tif (!state.modified_) {\n\t\t\t// the last check is because we need to be able to distinguish setting a non-existing to undefined (which is a change)\n\t\t\t// from setting an existing property with value undefined to undefined (which is not a change)\n\t\t\tconst current = peek(latest(state), prop)\n\t\t\t// special case, if we assigning the original value to a draft, we can ignore the assignment\n\t\t\tconst currentState: ProxyObjectState = current?.[DRAFT_STATE]\n\t\t\tif (currentState && currentState.base_ === value) {\n\t\t\t\tstate.copy_![prop] = value\n\t\t\t\tstate.assigned_[prop] = false\n\t\t\t\treturn true\n\t\t\t}\n\t\t\tif (is(value, current) && (value !== undefined || has(state.base_, prop)))\n\t\t\t\treturn true\n\t\t\tprepareCopy(state)\n\t\t\tmarkChanged(state)\n\t\t}\n\n\t\tif (\n\t\t\tstate.copy_![prop] === value &&\n\t\t\t// special case: NaN\n\t\t\ttypeof value !== \"number\" &&\n\t\t\t// special case: handle new props with value 'undefined'\n\t\t\t(value !== undefined || prop in state.copy_)\n\t\t)\n\t\t\treturn true\n\n\t\t// @ts-ignore\n\t\tstate.copy_![prop] = value\n\t\tstate.assigned_[prop] = true\n\t\treturn true\n\t},\n\tdeleteProperty(state, prop: string) {\n\t\t// The `undefined` check is a fast path for pre-existing keys.\n\t\tif (peek(state.base_, prop) !== undefined || prop in state.base_) {\n\t\t\tstate.assigned_[prop] = false\n\t\t\tprepareCopy(state)\n\t\t\tmarkChanged(state)\n\t\t} else {\n\t\t\t// if an originally not assigned property was deleted\n\t\t\tdelete state.assigned_[prop]\n\t\t}\n\t\t// @ts-ignore\n\t\tif (state.copy_) delete state.copy_[prop]\n\t\treturn true\n\t},\n\t// Note: We never coerce `desc.value` into an Immer draft, because we can't make\n\t// the same guarantee in ES5 mode.\n\tgetOwnPropertyDescriptor(state, prop) {\n\t\tconst owner = latest(state)\n\t\tconst desc = Reflect.getOwnPropertyDescriptor(owner, prop)\n\t\tif (!desc) return desc\n\t\treturn {\n\t\t\twritable: true,\n\t\t\tconfigurable: state.type_ !== ProxyType.ProxyArray || prop !== \"length\",\n\t\t\tenumerable: desc.enumerable,\n\t\t\tvalue: owner[prop]\n\t\t}\n\t},\n\tdefineProperty() {\n\t\tdie(11)\n\t},\n\tgetPrototypeOf(state) {\n\t\treturn Object.getPrototypeOf(state.base_)\n\t},\n\tsetPrototypeOf() {\n\t\tdie(12)\n\t}\n}\n\n/**\n * Array drafts\n */\n\nconst arrayTraps: ProxyHandler<[ProxyArrayState]> = {}\neach(objectTraps, (key, fn) => {\n\t// @ts-ignore\n\tarrayTraps[key] = function() {\n\t\targuments[0] = arguments[0][0]\n\t\treturn fn.apply(this, arguments)\n\t}\n})\narrayTraps.deleteProperty = function(state, prop) {\n\tif (__DEV__ && isNaN(parseInt(prop as any))) die(13)\n\treturn objectTraps.deleteProperty!.call(this, state[0], prop)\n}\narrayTraps.set = function(state, prop, value) {\n\tif (__DEV__ && prop !== \"length\" && isNaN(parseInt(prop as any))) die(14)\n\treturn objectTraps.set!.call(this, state[0], prop, value, state[0])\n}\n\n// Access a property without creating an Immer draft.\nfunction peek(draft: Drafted, prop: PropertyKey) {\n\tconst state = draft[DRAFT_STATE]\n\tconst source = state ? latest(state) : draft\n\treturn source[prop]\n}\n\nfunction readPropFromProto(state: ImmerState, source: any, prop: PropertyKey) {\n\tconst desc = getDescriptorFromProto(source, prop)\n\treturn desc\n\t\t? `value` in desc\n\t\t\t? desc.value\n\t\t\t: // This is a very special case, if the prop is a getter defined by the\n\t\t\t // prototype, we should invoke it with the draft as context!\n\t\t\t desc.get?.call(state.draft_)\n\t\t: undefined\n}\n\nfunction getDescriptorFromProto(\n\tsource: any,\n\tprop: PropertyKey\n): PropertyDescriptor | undefined {\n\t// 'in' checks proto!\n\tif (!(prop in source)) return undefined\n\tlet proto = Object.getPrototypeOf(source)\n\twhile (proto) {\n\t\tconst desc = Object.getOwnPropertyDescriptor(proto, prop)\n\t\tif (desc) return desc\n\t\tproto = Object.getPrototypeOf(proto)\n\t}\n\treturn undefined\n}\n\nexport function markChanged(state: ImmerState) {\n\tif (!state.modified_) {\n\t\tstate.modified_ = true\n\t\tif (state.parent_) {\n\t\t\tmarkChanged(state.parent_)\n\t\t}\n\t}\n}\n\nexport function prepareCopy(state: {base_: any; copy_: any}) {\n\tif (!state.copy_) {\n\t\tstate.copy_ = shallowCopy(state.base_)\n\t}\n}\n", "import {\n\tIProduceWithPatches,\n\tIProduce,\n\tImmerState,\n\tDrafted,\n\tisDraftable,\n\tprocessResult,\n\tPatch,\n\tObjectish,\n\tDRAFT_STATE,\n\tDraft,\n\tPatchListener,\n\tisDraft,\n\tisMap,\n\tisSet,\n\tcreateProxyProxy,\n\tgetPlugin,\n\tdie,\n\thasProxies,\n\tenterScope,\n\trevokeScope,\n\tleaveScope,\n\tusePatchesInScope,\n\tgetCurrentScope,\n\tNOTHING,\n\tfreeze,\n\tcurrent\n} from \"../internal\"\n\ninterface ProducersFns {\n\tproduce: IProduce\n\tproduceWithPatches: IProduceWithPatches\n}\n\nexport class Immer implements ProducersFns {\n\tuseProxies_: boolean = hasProxies\n\n\tautoFreeze_: boolean = true\n\n\tconstructor(config?: {useProxies?: boolean; autoFreeze?: boolean}) {\n\t\tif (typeof config?.useProxies === \"boolean\")\n\t\t\tthis.setUseProxies(config!.useProxies)\n\t\tif (typeof config?.autoFreeze === \"boolean\")\n\t\t\tthis.setAutoFreeze(config!.autoFreeze)\n\t}\n\n\t/**\n\t * The `produce` function takes a value and a \"recipe function\" (whose\n\t * return value often depends on the base state). The recipe function is\n\t * free to mutate its first argument however it wants. All mutations are\n\t * only ever applied to a __copy__ of the base state.\n\t *\n\t * Pass only a function to create a \"curried producer\" which relieves you\n\t * from passing the recipe function every time.\n\t *\n\t * Only plain objects and arrays are made mutable. All other objects are\n\t * considered uncopyable.\n\t *\n\t * Note: This function is __bound__ to its `Immer` instance.\n\t *\n\t * @param {any} base - the initial state\n\t * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified\n\t * @param {Function} patchListener - optional function that will be called with all the patches produced here\n\t * @returns {any} a new state, or the initial state if nothing was modified\n\t */\n\tproduce: IProduce = (base: any, recipe?: any, patchListener?: any) => {\n\t\t// curried invocation\n\t\tif (typeof base === \"function\" && typeof recipe !== \"function\") {\n\t\t\tconst defaultBase = recipe\n\t\t\trecipe = base\n\n\t\t\tconst self = this\n\t\t\treturn function curriedProduce(\n\t\t\t\tthis: any,\n\t\t\t\tbase = defaultBase,\n\t\t\t\t...args: any[]\n\t\t\t) {\n\t\t\t\treturn self.produce(base, (draft: Drafted) => recipe.call(this, draft, ...args)) // prettier-ignore\n\t\t\t}\n\t\t}\n\n\t\tif (typeof recipe !== \"function\") die(6)\n\t\tif (patchListener !== undefined && typeof patchListener !== \"function\")\n\t\t\tdie(7)\n\n\t\tlet result\n\n\t\t// Only plain objects, arrays, and \"immerable classes\" are drafted.\n\t\tif (isDraftable(base)) {\n\t\t\tconst scope = enterScope(this)\n\t\t\tconst proxy = createProxy(this, base, undefined)\n\t\t\tlet hasError = true\n\t\t\ttry {\n\t\t\t\tresult = recipe(proxy)\n\t\t\t\thasError = false\n\t\t\t} finally {\n\t\t\t\t// finally instead of catch + rethrow better preserves original stack\n\t\t\t\tif (hasError) revokeScope(scope)\n\t\t\t\telse leaveScope(scope)\n\t\t\t}\n\t\t\tif (typeof Promise !== \"undefined\" && result instanceof Promise) {\n\t\t\t\treturn result.then(\n\t\t\t\t\tresult => {\n\t\t\t\t\t\tusePatchesInScope(scope, patchListener)\n\t\t\t\t\t\treturn processResult(result, scope)\n\t\t\t\t\t},\n\t\t\t\t\terror => {\n\t\t\t\t\t\trevokeScope(scope)\n\t\t\t\t\t\tthrow error\n\t\t\t\t\t}\n\t\t\t\t)\n\t\t\t}\n\t\t\tusePatchesInScope(scope, patchListener)\n\t\t\treturn processResult(result, scope)\n\t\t} else if (!base || typeof base !== \"object\") {\n\t\t\tresult = recipe(base)\n\t\t\tif (result === NOTHING) return undefined\n\t\t\tif (result === undefined) result = base\n\t\t\tif (this.autoFreeze_) freeze(result, true)\n\t\t\treturn result\n\t\t} else die(21, base)\n\t}\n\n\tproduceWithPatches: IProduceWithPatches = (\n\t\targ1: any,\n\t\targ2?: any,\n\t\targ3?: any\n\t): any => {\n\t\tif (typeof arg1 === \"function\") {\n\t\t\treturn (state: any, ...args: any[]) =>\n\t\t\t\tthis.produceWithPatches(state, (draft: any) => arg1(draft, ...args))\n\t\t}\n\n\t\tlet patches: Patch[], inversePatches: Patch[]\n\t\tconst nextState = this.produce(arg1, arg2, (p: Patch[], ip: Patch[]) => {\n\t\t\tpatches = p\n\t\t\tinversePatches = ip\n\t\t})\n\t\treturn [nextState, patches!, inversePatches!]\n\t}\n\n\tcreateDraft(base: T): Draft {\n\t\tif (!isDraftable(base)) die(8)\n\t\tif (isDraft(base)) base = current(base)\n\t\tconst scope = enterScope(this)\n\t\tconst proxy = createProxy(this, base, undefined)\n\t\tproxy[DRAFT_STATE].isManual_ = true\n\t\tleaveScope(scope)\n\t\treturn proxy as any\n\t}\n\n\tfinishDraft>(\n\t\tdraft: D,\n\t\tpatchListener?: PatchListener\n\t): D extends Draft ? T : never {\n\t\tconst state: ImmerState = draft && (draft as any)[DRAFT_STATE]\n\t\tif (__DEV__) {\n\t\t\tif (!state || !state.isManual_) die(9)\n\t\t\tif (state.finalized_) die(10)\n\t\t}\n\t\tconst {scope_: scope} = state\n\t\tusePatchesInScope(scope, patchListener)\n\t\treturn processResult(undefined, scope)\n\t}\n\n\t/**\n\t * Pass true to automatically freeze all copies created by Immer.\n\t *\n\t * By default, auto-freezing is enabled.\n\t */\n\tsetAutoFreeze(value: boolean) {\n\t\tthis.autoFreeze_ = value\n\t}\n\n\t/**\n\t * Pass true to use the ES2015 `Proxy` class when creating drafts, which is\n\t * always faster than using ES5 proxies.\n\t *\n\t * By default, feature detection is used, so calling this is rarely necessary.\n\t */\n\tsetUseProxies(value: boolean) {\n\t\tif (value && !hasProxies) {\n\t\t\tdie(20)\n\t\t}\n\t\tthis.useProxies_ = value\n\t}\n\n\tapplyPatches(base: T, patches: Patch[]): T {\n\t\t// If a patch replaces the entire state, take that replacement as base\n\t\t// before applying patches\n\t\tlet i: number\n\t\tfor (i = patches.length - 1; i >= 0; i--) {\n\t\t\tconst patch = patches[i]\n\t\t\tif (patch.path.length === 0 && patch.op === \"replace\") {\n\t\t\t\tbase = patch.value\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tconst applyPatchesImpl = getPlugin(\"Patches\").applyPatches_\n\t\tif (isDraft(base)) {\n\t\t\t// N.B: never hits if some patch a replacement, patches are never drafts\n\t\t\treturn applyPatchesImpl(base, patches) as any\n\t\t}\n\t\t// Otherwise, produce a copy of the base state.\n\t\treturn this.produce(base, (draft: Drafted) =>\n\t\t\tapplyPatchesImpl(draft, patches.slice(i + 1))\n\t\t) as any\n\t}\n}\n\nexport function createProxy(\n\timmer: Immer,\n\tvalue: T,\n\tparent?: ImmerState\n): Drafted {\n\t// precondition: createProxy should be guarded by isDraftable, so we know we can safely draft\n\tconst draft: Drafted = isMap(value)\n\t\t? getPlugin(\"MapSet\").proxyMap_(value, parent)\n\t\t: isSet(value)\n\t\t? getPlugin(\"MapSet\").proxySet_(value, parent)\n\t\t: immer.useProxies_\n\t\t? createProxyProxy(value, parent)\n\t\t: getPlugin(\"ES5\").createES5Proxy_(value, parent)\n\n\tconst scope = parent ? parent.scope_ : getCurrentScope()\n\tscope.drafts_.push(draft)\n\treturn draft\n}\n", "import {\n\tdie,\n\tisDraft,\n\tshallowCopy,\n\teach,\n\tDRAFT_STATE,\n\tget,\n\tset,\n\tImmerState,\n\tisDraftable,\n\tArchtype,\n\tgetArchtype,\n\tgetPlugin\n} from \"../internal\"\n\n/** Takes a snapshot of the current state of a draft and finalizes it (but without freezing). This is a great utility to print the current state during debugging (no Proxies in the way). The output of current can also be safely leaked outside the producer. */\nexport function current(value: T): T\nexport function current(value: any): any {\n\tif (!isDraft(value)) die(22, value)\n\treturn currentImpl(value)\n}\n\nfunction currentImpl(value: any): any {\n\tif (!isDraftable(value)) return value\n\tconst state: ImmerState | undefined = value[DRAFT_STATE]\n\tlet copy: any\n\tconst archType = getArchtype(value)\n\tif (state) {\n\t\tif (\n\t\t\t!state.modified_ &&\n\t\t\t(state.type_ < 4 || !getPlugin(\"ES5\").hasChanges_(state as any))\n\t\t)\n\t\t\treturn state.base_\n\t\t// Optimization: avoid generating new drafts during copying\n\t\tstate.finalized_ = true\n\t\tcopy = copyHelper(value, archType)\n\t\tstate.finalized_ = false\n\t} else {\n\t\tcopy = copyHelper(value, archType)\n\t}\n\n\teach(copy, (key, childValue) => {\n\t\tif (state && get(state.base_, key) === childValue) return // no need to copy or search in something that didn't change\n\t\tset(copy, key, currentImpl(childValue))\n\t})\n\t// In the future, we might consider freezing here, based on the current settings\n\treturn archType === Archtype.Set ? new Set(copy) : copy\n}\n\nfunction copyHelper(value: any, archType: number): any {\n\t// creates a shallow copy, even if it is a map or set\n\tswitch (archType) {\n\t\tcase Archtype.Map:\n\t\t\treturn new Map(value)\n\t\tcase Archtype.Set:\n\t\t\t// Set will be cloned as array temporarily, so that we can replace individual items\n\t\t\treturn Array.from(value)\n\t}\n\treturn shallowCopy(value)\n}\n", "import {\n\tImmerState,\n\tDrafted,\n\tES5ArrayState,\n\tES5ObjectState,\n\teach,\n\thas,\n\tisDraft,\n\tlatest,\n\tDRAFT_STATE,\n\tis,\n\tloadPlugin,\n\tImmerScope,\n\tProxyType,\n\tgetCurrentScope,\n\tdie,\n\tmarkChanged,\n\tobjectTraps,\n\townKeys,\n\tgetOwnPropertyDescriptors\n} from \"../internal\"\n\ntype ES5State = ES5ArrayState | ES5ObjectState\n\nexport function enableES5() {\n\tfunction willFinalizeES5_(\n\t\tscope: ImmerScope,\n\t\tresult: any,\n\t\tisReplaced: boolean\n\t) {\n\t\tif (!isReplaced) {\n\t\t\tif (scope.patches_) {\n\t\t\t\tmarkChangesRecursively(scope.drafts_![0])\n\t\t\t}\n\t\t\t// This is faster when we don't care about which attributes changed.\n\t\t\tmarkChangesSweep(scope.drafts_)\n\t\t}\n\t\t// When a child draft is returned, look for changes.\n\t\telse if (\n\t\t\tisDraft(result) &&\n\t\t\t(result[DRAFT_STATE] as ES5State).scope_ === scope\n\t\t) {\n\t\t\tmarkChangesSweep(scope.drafts_)\n\t\t}\n\t}\n\n\tfunction createES5Draft(isArray: boolean, base: any) {\n\t\tif (isArray) {\n\t\t\tconst draft = new Array(base.length)\n\t\t\tfor (let i = 0; i < base.length; i++)\n\t\t\t\tObject.defineProperty(draft, \"\" + i, proxyProperty(i, true))\n\t\t\treturn draft\n\t\t} else {\n\t\t\tconst descriptors = getOwnPropertyDescriptors(base)\n\t\t\tdelete descriptors[DRAFT_STATE as any]\n\t\t\tconst keys = ownKeys(descriptors)\n\t\t\tfor (let i = 0; i < keys.length; i++) {\n\t\t\t\tconst key: any = keys[i]\n\t\t\t\tdescriptors[key] = proxyProperty(\n\t\t\t\t\tkey,\n\t\t\t\t\tisArray || !!descriptors[key].enumerable\n\t\t\t\t)\n\t\t\t}\n\t\t\treturn Object.create(Object.getPrototypeOf(base), descriptors)\n\t\t}\n\t}\n\n\tfunction createES5Proxy_(\n\t\tbase: T,\n\t\tparent?: ImmerState\n\t): Drafted {\n\t\tconst isArray = Array.isArray(base)\n\t\tconst draft = createES5Draft(isArray, base)\n\n\t\tconst state: ES5ObjectState | ES5ArrayState = {\n\t\t\ttype_: isArray ? ProxyType.ES5Array : (ProxyType.ES5Object as any),\n\t\t\tscope_: parent ? parent.scope_ : getCurrentScope(),\n\t\t\tmodified_: false,\n\t\t\tfinalized_: false,\n\t\t\tassigned_: {},\n\t\t\tparent_: parent,\n\t\t\t// base is the object we are drafting\n\t\t\tbase_: base,\n\t\t\t// draft is the draft object itself, that traps all reads and reads from either the base (if unmodified) or copy (if modified)\n\t\t\tdraft_: draft,\n\t\t\tcopy_: null,\n\t\t\trevoked_: false,\n\t\t\tisManual_: false\n\t\t}\n\n\t\tObject.defineProperty(draft, DRAFT_STATE, {\n\t\t\tvalue: state,\n\t\t\t// enumerable: false <- the default\n\t\t\twritable: true\n\t\t})\n\t\treturn draft\n\t}\n\n\t// property descriptors are recycled to make sure we don't create a get and set closure per property,\n\t// but share them all instead\n\tconst descriptors: {[prop: string]: PropertyDescriptor} = {}\n\n\tfunction proxyProperty(\n\t\tprop: string | number,\n\t\tenumerable: boolean\n\t): PropertyDescriptor {\n\t\tlet desc = descriptors[prop]\n\t\tif (desc) {\n\t\t\tdesc.enumerable = enumerable\n\t\t} else {\n\t\t\tdescriptors[prop] = desc = {\n\t\t\t\tconfigurable: true,\n\t\t\t\tenumerable,\n\t\t\t\tget(this: any) {\n\t\t\t\t\tconst state = this[DRAFT_STATE]\n\t\t\t\t\tif (__DEV__) assertUnrevoked(state)\n\t\t\t\t\t// @ts-ignore\n\t\t\t\t\treturn objectTraps.get(state, prop)\n\t\t\t\t},\n\t\t\t\tset(this: any, value) {\n\t\t\t\t\tconst state = this[DRAFT_STATE]\n\t\t\t\t\tif (__DEV__) assertUnrevoked(state)\n\t\t\t\t\t// @ts-ignore\n\t\t\t\t\tobjectTraps.set(state, prop, value)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn desc\n\t}\n\n\t// This looks expensive, but only proxies are visited, and only objects without known changes are scanned.\n\tfunction markChangesSweep(drafts: Drafted[]) {\n\t\t// The natural order of drafts in the `scope` array is based on when they\n\t\t// were accessed. By processing drafts in reverse natural order, we have a\n\t\t// better chance of processing leaf nodes first. When a leaf node is known to\n\t\t// have changed, we can avoid any traversal of its ancestor nodes.\n\t\tfor (let i = drafts.length - 1; i >= 0; i--) {\n\t\t\tconst state: ES5State = drafts[i][DRAFT_STATE]\n\t\t\tif (!state.modified_) {\n\t\t\t\tswitch (state.type_) {\n\t\t\t\t\tcase ProxyType.ES5Array:\n\t\t\t\t\t\tif (hasArrayChanges(state)) markChanged(state)\n\t\t\t\t\t\tbreak\n\t\t\t\t\tcase ProxyType.ES5Object:\n\t\t\t\t\t\tif (hasObjectChanges(state)) markChanged(state)\n\t\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tfunction markChangesRecursively(object: any) {\n\t\tif (!object || typeof object !== \"object\") return\n\t\tconst state: ES5State | undefined = object[DRAFT_STATE]\n\t\tif (!state) return\n\t\tconst {base_, draft_, assigned_, type_} = state\n\t\tif (type_ === ProxyType.ES5Object) {\n\t\t\t// Look for added keys.\n\t\t\t// probably there is a faster way to detect changes, as sweep + recurse seems to do some\n\t\t\t// unnecessary work.\n\t\t\t// also: probably we can store the information we detect here, to speed up tree finalization!\n\t\t\teach(draft_, key => {\n\t\t\t\tif ((key as any) === DRAFT_STATE) return\n\t\t\t\t// The `undefined` check is a fast path for pre-existing keys.\n\t\t\t\tif ((base_ as any)[key] === undefined && !has(base_, key)) {\n\t\t\t\t\tassigned_[key] = true\n\t\t\t\t\tmarkChanged(state)\n\t\t\t\t} else if (!assigned_[key]) {\n\t\t\t\t\t// Only untouched properties trigger recursion.\n\t\t\t\t\tmarkChangesRecursively(draft_[key])\n\t\t\t\t}\n\t\t\t})\n\t\t\t// Look for removed keys.\n\t\t\teach(base_, key => {\n\t\t\t\t// The `undefined` check is a fast path for pre-existing keys.\n\t\t\t\tif (draft_[key] === undefined && !has(draft_, key)) {\n\t\t\t\t\tassigned_[key] = false\n\t\t\t\t\tmarkChanged(state)\n\t\t\t\t}\n\t\t\t})\n\t\t} else if (type_ === ProxyType.ES5Array) {\n\t\t\tif (hasArrayChanges(state as ES5ArrayState)) {\n\t\t\t\tmarkChanged(state)\n\t\t\t\tassigned_.length = true\n\t\t\t}\n\n\t\t\tif (draft_.length < base_.length) {\n\t\t\t\tfor (let i = draft_.length; i < base_.length; i++) assigned_[i] = false\n\t\t\t} else {\n\t\t\t\tfor (let i = base_.length; i < draft_.length; i++) assigned_[i] = true\n\t\t\t}\n\n\t\t\t// Minimum count is enough, the other parts has been processed.\n\t\t\tconst min = Math.min(draft_.length, base_.length)\n\n\t\t\tfor (let i = 0; i < min; i++) {\n\t\t\t\t// Only untouched indices trigger recursion.\n\t\t\t\tif (assigned_[i] === undefined) markChangesRecursively(draft_[i])\n\t\t\t}\n\t\t}\n\t}\n\n\tfunction hasObjectChanges(state: ES5ObjectState) {\n\t\tconst {base_, draft_} = state\n\n\t\t// Search for added keys and changed keys. Start at the back, because\n\t\t// non-numeric keys are ordered by time of definition on the object.\n\t\tconst keys = ownKeys(draft_)\n\t\tfor (let i = keys.length - 1; i >= 0; i--) {\n\t\t\tconst key: any = keys[i]\n\t\t\tif (key === DRAFT_STATE) continue\n\t\t\tconst baseValue = base_[key]\n\t\t\t// The `undefined` check is a fast path for pre-existing keys.\n\t\t\tif (baseValue === undefined && !has(base_, key)) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t\t// Once a base key is deleted, future changes go undetected, because its\n\t\t\t// descriptor is erased. This branch detects any missed changes.\n\t\t\telse {\n\t\t\t\tconst value = draft_[key]\n\t\t\t\tconst state: ImmerState = value && value[DRAFT_STATE]\n\t\t\t\tif (state ? state.base_ !== baseValue : !is(value, baseValue)) {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// At this point, no keys were added or changed.\n\t\t// Compare key count to determine if keys were deleted.\n\t\tconst baseIsDraft = !!base_[DRAFT_STATE as any]\n\t\treturn keys.length !== ownKeys(base_).length + (baseIsDraft ? 0 : 1) // + 1 to correct for DRAFT_STATE\n\t}\n\n\tfunction hasArrayChanges(state: ES5ArrayState) {\n\t\tconst {draft_} = state\n\t\tif (draft_.length !== state.base_.length) return true\n\t\t// See #116\n\t\t// If we first shorten the length, our array interceptors will be removed.\n\t\t// If after that new items are added, result in the same original length,\n\t\t// those last items will have no intercepting property.\n\t\t// So if there is no own descriptor on the last position, we know that items were removed and added\n\t\t// N.B.: splice, unshift, etc only shift values around, but not prop descriptors, so we only have to check\n\t\t// the last one\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(\n\t\t\tdraft_,\n\t\t\tdraft_.length - 1\n\t\t)\n\t\t// descriptor can be null, but only for newly created sparse arrays, eg. new Array(10)\n\t\tif (descriptor && !descriptor.get) return true\n\t\t// For all other cases, we don't have to compare, as they would have been picked up by the index setters\n\t\treturn false\n\t}\n\n\tfunction hasChanges_(state: ES5State) {\n\t\treturn state.type_ === ProxyType.ES5Object\n\t\t\t? hasObjectChanges(state)\n\t\t\t: hasArrayChanges(state)\n\t}\n\n\tfunction assertUnrevoked(state: any /*ES5State | MapState | SetState*/) {\n\t\tif (state.revoked_) die(3, JSON.stringify(latest(state)))\n\t}\n\n\tloadPlugin(\"ES5\", {\n\t\tcreateES5Proxy_,\n\t\twillFinalizeES5_,\n\t\thasChanges_\n\t})\n}\n", "import {immerable} from \"../immer\"\nimport {\n\tImmerState,\n\tPatch,\n\tSetState,\n\tES5ArrayState,\n\tProxyArrayState,\n\tMapState,\n\tES5ObjectState,\n\tProxyObjectState,\n\tPatchPath,\n\tget,\n\teach,\n\thas,\n\tgetArchtype,\n\tisSet,\n\tisMap,\n\tloadPlugin,\n\tProxyType,\n\tArchtype,\n\tdie,\n\tisDraft,\n\tisDraftable,\n\tNOTHING\n} from \"../internal\"\n\nexport function enablePatches() {\n\tconst REPLACE = \"replace\"\n\tconst ADD = \"add\"\n\tconst REMOVE = \"remove\"\n\n\tfunction generatePatches_(\n\t\tstate: ImmerState,\n\t\tbasePath: PatchPath,\n\t\tpatches: Patch[],\n\t\tinversePatches: Patch[]\n\t): void {\n\t\tswitch (state.type_) {\n\t\t\tcase ProxyType.ProxyObject:\n\t\t\tcase ProxyType.ES5Object:\n\t\t\tcase ProxyType.Map:\n\t\t\t\treturn generatePatchesFromAssigned(\n\t\t\t\t\tstate,\n\t\t\t\t\tbasePath,\n\t\t\t\t\tpatches,\n\t\t\t\t\tinversePatches\n\t\t\t\t)\n\t\t\tcase ProxyType.ES5Array:\n\t\t\tcase ProxyType.ProxyArray:\n\t\t\t\treturn generateArrayPatches(state, basePath, patches, inversePatches)\n\t\t\tcase ProxyType.Set:\n\t\t\t\treturn generateSetPatches(\n\t\t\t\t\t(state as any) as SetState,\n\t\t\t\t\tbasePath,\n\t\t\t\t\tpatches,\n\t\t\t\t\tinversePatches\n\t\t\t\t)\n\t\t}\n\t}\n\n\tfunction generateArrayPatches(\n\t\tstate: ES5ArrayState | ProxyArrayState,\n\t\tbasePath: PatchPath,\n\t\tpatches: Patch[],\n\t\tinversePatches: Patch[]\n\t) {\n\t\tlet {base_, assigned_} = state\n\t\tlet copy_ = state.copy_!\n\n\t\t// Reduce complexity by ensuring `base` is never longer.\n\t\tif (copy_.length < base_.length) {\n\t\t\t// @ts-ignore\n\t\t\t;[base_, copy_] = [copy_, base_]\n\t\t\t;[patches, inversePatches] = [inversePatches, patches]\n\t\t}\n\n\t\t// Process replaced indices.\n\t\tfor (let i = 0; i < base_.length; i++) {\n\t\t\tif (assigned_[i] && copy_[i] !== base_[i]) {\n\t\t\t\tconst path = basePath.concat([i])\n\t\t\t\tpatches.push({\n\t\t\t\t\top: REPLACE,\n\t\t\t\t\tpath,\n\t\t\t\t\t// Need to maybe clone it, as it can in fact be the original value\n\t\t\t\t\t// due to the base/copy inversion at the start of this function\n\t\t\t\t\tvalue: clonePatchValueIfNeeded(copy_[i])\n\t\t\t\t})\n\t\t\t\tinversePatches.push({\n\t\t\t\t\top: REPLACE,\n\t\t\t\t\tpath,\n\t\t\t\t\tvalue: clonePatchValueIfNeeded(base_[i])\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\n\t\t// Process added indices.\n\t\tfor (let i = base_.length; i < copy_.length; i++) {\n\t\t\tconst path = basePath.concat([i])\n\t\t\tpatches.push({\n\t\t\t\top: ADD,\n\t\t\t\tpath,\n\t\t\t\t// Need to maybe clone it, as it can in fact be the original value\n\t\t\t\t// due to the base/copy inversion at the start of this function\n\t\t\t\tvalue: clonePatchValueIfNeeded(copy_[i])\n\t\t\t})\n\t\t}\n\t\tif (base_.length < copy_.length) {\n\t\t\tinversePatches.push({\n\t\t\t\top: REPLACE,\n\t\t\t\tpath: basePath.concat([\"length\"]),\n\t\t\t\tvalue: base_.length\n\t\t\t})\n\t\t}\n\t}\n\n\t// This is used for both Map objects and normal objects.\n\tfunction generatePatchesFromAssigned(\n\t\tstate: MapState | ES5ObjectState | ProxyObjectState,\n\t\tbasePath: PatchPath,\n\t\tpatches: Patch[],\n\t\tinversePatches: Patch[]\n\t) {\n\t\tconst {base_, copy_} = state\n\t\teach(state.assigned_!, (key, assignedValue) => {\n\t\t\tconst origValue = get(base_, key)\n\t\t\tconst value = get(copy_!, key)\n\t\t\tconst op = !assignedValue ? REMOVE : has(base_, key) ? REPLACE : ADD\n\t\t\tif (origValue === value && op === REPLACE) return\n\t\t\tconst path = basePath.concat(key as any)\n\t\t\tpatches.push(op === REMOVE ? {op, path} : {op, path, value})\n\t\t\tinversePatches.push(\n\t\t\t\top === ADD\n\t\t\t\t\t? {op: REMOVE, path}\n\t\t\t\t\t: op === REMOVE\n\t\t\t\t\t? {op: ADD, path, value: clonePatchValueIfNeeded(origValue)}\n\t\t\t\t\t: {op: REPLACE, path, value: clonePatchValueIfNeeded(origValue)}\n\t\t\t)\n\t\t})\n\t}\n\n\tfunction generateSetPatches(\n\t\tstate: SetState,\n\t\tbasePath: PatchPath,\n\t\tpatches: Patch[],\n\t\tinversePatches: Patch[]\n\t) {\n\t\tlet {base_, copy_} = state\n\n\t\tlet i = 0\n\t\tbase_.forEach((value: any) => {\n\t\t\tif (!copy_!.has(value)) {\n\t\t\t\tconst path = basePath.concat([i])\n\t\t\t\tpatches.push({\n\t\t\t\t\top: REMOVE,\n\t\t\t\t\tpath,\n\t\t\t\t\tvalue\n\t\t\t\t})\n\t\t\t\tinversePatches.unshift({\n\t\t\t\t\top: ADD,\n\t\t\t\t\tpath,\n\t\t\t\t\tvalue\n\t\t\t\t})\n\t\t\t}\n\t\t\ti++\n\t\t})\n\t\ti = 0\n\t\tcopy_!.forEach((value: any) => {\n\t\t\tif (!base_.has(value)) {\n\t\t\t\tconst path = basePath.concat([i])\n\t\t\t\tpatches.push({\n\t\t\t\t\top: ADD,\n\t\t\t\t\tpath,\n\t\t\t\t\tvalue\n\t\t\t\t})\n\t\t\t\tinversePatches.unshift({\n\t\t\t\t\top: REMOVE,\n\t\t\t\t\tpath,\n\t\t\t\t\tvalue\n\t\t\t\t})\n\t\t\t}\n\t\t\ti++\n\t\t})\n\t}\n\n\tfunction generateReplacementPatches_(\n\t\trootState: ImmerState,\n\t\treplacement: any,\n\t\tpatches: Patch[],\n\t\tinversePatches: Patch[]\n\t): void {\n\t\tpatches.push({\n\t\t\top: REPLACE,\n\t\t\tpath: [],\n\t\t\tvalue: replacement === NOTHING ? undefined : replacement\n\t\t})\n\t\tinversePatches.push({\n\t\t\top: REPLACE,\n\t\t\tpath: [],\n\t\t\tvalue: rootState.base_\n\t\t})\n\t}\n\n\tfunction applyPatches_(draft: T, patches: Patch[]): T {\n\t\tpatches.forEach(patch => {\n\t\t\tconst {path, op} = patch\n\n\t\t\tlet base: any = draft\n\t\t\tfor (let i = 0; i < path.length - 1; i++) {\n\t\t\t\tconst parentType = getArchtype(base)\n\t\t\t\tconst p = \"\" + path[i]\n\t\t\t\t// See #738, avoid prototype pollution\n\t\t\t\tif (\n\t\t\t\t\t(parentType === Archtype.Object || parentType === Archtype.Array) &&\n\t\t\t\t\t(p === \"__proto__\" || p === \"constructor\")\n\t\t\t\t)\n\t\t\t\t\tdie(24)\n\t\t\t\tif (typeof base === \"function\" && p === \"prototype\") die(24)\n\t\t\t\tbase = get(base, p)\n\t\t\t\tif (typeof base !== \"object\") die(15, path.join(\"/\"))\n\t\t\t}\n\n\t\t\tconst type = getArchtype(base)\n\t\t\tconst value = deepClonePatchValue(patch.value) // used to clone patch to ensure original patch is not modified, see #411\n\t\t\tconst key = path[path.length - 1]\n\t\t\tswitch (op) {\n\t\t\t\tcase REPLACE:\n\t\t\t\t\tswitch (type) {\n\t\t\t\t\t\tcase Archtype.Map:\n\t\t\t\t\t\t\treturn base.set(key, value)\n\t\t\t\t\t\t/* istanbul ignore next */\n\t\t\t\t\t\tcase Archtype.Set:\n\t\t\t\t\t\t\tdie(16)\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t// if value is an object, then it's assigned by reference\n\t\t\t\t\t\t\t// in the following add or remove ops, the value field inside the patch will also be modifyed\n\t\t\t\t\t\t\t// so we use value from the cloned patch\n\t\t\t\t\t\t\t// @ts-ignore\n\t\t\t\t\t\t\treturn (base[key] = value)\n\t\t\t\t\t}\n\t\t\t\tcase ADD:\n\t\t\t\t\tswitch (type) {\n\t\t\t\t\t\tcase Archtype.Array:\n\t\t\t\t\t\t\treturn base.splice(key as any, 0, value)\n\t\t\t\t\t\tcase Archtype.Map:\n\t\t\t\t\t\t\treturn base.set(key, value)\n\t\t\t\t\t\tcase Archtype.Set:\n\t\t\t\t\t\t\treturn base.add(value)\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\treturn (base[key] = value)\n\t\t\t\t\t}\n\t\t\t\tcase REMOVE:\n\t\t\t\t\tswitch (type) {\n\t\t\t\t\t\tcase Archtype.Array:\n\t\t\t\t\t\t\treturn base.splice(key as any, 1)\n\t\t\t\t\t\tcase Archtype.Map:\n\t\t\t\t\t\t\treturn base.delete(key)\n\t\t\t\t\t\tcase Archtype.Set:\n\t\t\t\t\t\t\treturn base.delete(patch.value)\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\treturn delete base[key]\n\t\t\t\t\t}\n\t\t\t\tdefault:\n\t\t\t\t\tdie(17, op)\n\t\t\t}\n\t\t})\n\n\t\treturn draft\n\t}\n\n\t// optimize: this is quite a performance hit, can we detect intelligently when it is needed?\n\t// E.g. auto-draft when new objects from outside are assigned and modified?\n\t// (See failing test when deepClone just returns obj)\n\tfunction deepClonePatchValue(obj: T): T\n\tfunction deepClonePatchValue(obj: any) {\n\t\tif (!isDraftable(obj)) return obj\n\t\tif (Array.isArray(obj)) return obj.map(deepClonePatchValue)\n\t\tif (isMap(obj))\n\t\t\treturn new Map(\n\t\t\t\tArray.from(obj.entries()).map(([k, v]) => [k, deepClonePatchValue(v)])\n\t\t\t)\n\t\tif (isSet(obj)) return new Set(Array.from(obj).map(deepClonePatchValue))\n\t\tconst cloned = Object.create(Object.getPrototypeOf(obj))\n\t\tfor (const key in obj) cloned[key] = deepClonePatchValue(obj[key])\n\t\tif (has(obj, immerable)) cloned[immerable] = obj[immerable]\n\t\treturn cloned\n\t}\n\n\tfunction clonePatchValueIfNeeded(obj: T): T {\n\t\tif (isDraft(obj)) {\n\t\t\treturn deepClonePatchValue(obj)\n\t\t} else return obj\n\t}\n\n\tloadPlugin(\"Patches\", {\n\t\tapplyPatches_,\n\t\tgeneratePatches_,\n\t\tgenerateReplacementPatches_\n\t})\n}\n", "// types only!\nimport {\n\tImmerState,\n\tAnyMap,\n\tAnySet,\n\tMapState,\n\tSetState,\n\tDRAFT_STATE,\n\tgetCurrentScope,\n\tlatest,\n\titeratorSymbol,\n\tisDraftable,\n\tcreateProxy,\n\tloadPlugin,\n\tmarkChanged,\n\tProxyType,\n\tdie,\n\teach\n} from \"../internal\"\n\nexport function enableMapSet() {\n\t/* istanbul ignore next */\n\tvar extendStatics = function(d: any, b: any): any {\n\t\textendStatics =\n\t\t\tObject.setPrototypeOf ||\n\t\t\t({__proto__: []} instanceof Array &&\n\t\t\t\tfunction(d, b) {\n\t\t\t\t\td.__proto__ = b\n\t\t\t\t}) ||\n\t\t\tfunction(d, b) {\n\t\t\t\tfor (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]\n\t\t\t}\n\t\treturn extendStatics(d, b)\n\t}\n\n\t// Ugly hack to resolve #502 and inherit built in Map / Set\n\tfunction __extends(d: any, b: any): any {\n\t\textendStatics(d, b)\n\t\tfunction __(this: any): any {\n\t\t\tthis.constructor = d\n\t\t}\n\t\td.prototype =\n\t\t\t// @ts-ignore\n\t\t\t((__.prototype = b.prototype), new __())\n\t}\n\n\tconst DraftMap = (function(_super) {\n\t\t__extends(DraftMap, _super)\n\t\t// Create class manually, cause #502\n\t\tfunction DraftMap(this: any, target: AnyMap, parent?: ImmerState): any {\n\t\t\tthis[DRAFT_STATE] = {\n\t\t\t\ttype_: ProxyType.Map,\n\t\t\t\tparent_: parent,\n\t\t\t\tscope_: parent ? parent.scope_ : getCurrentScope()!,\n\t\t\t\tmodified_: false,\n\t\t\t\tfinalized_: false,\n\t\t\t\tcopy_: undefined,\n\t\t\t\tassigned_: undefined,\n\t\t\t\tbase_: target,\n\t\t\t\tdraft_: this as any,\n\t\t\t\tisManual_: false,\n\t\t\t\trevoked_: false\n\t\t\t} as MapState\n\t\t\treturn this\n\t\t}\n\t\tconst p = DraftMap.prototype\n\n\t\tObject.defineProperty(p, \"size\", {\n\t\t\tget: function() {\n\t\t\t\treturn latest(this[DRAFT_STATE]).size\n\t\t\t}\n\t\t\t// enumerable: false,\n\t\t\t// configurable: true\n\t\t})\n\n\t\tp.has = function(key: any): boolean {\n\t\t\treturn latest(this[DRAFT_STATE]).has(key)\n\t\t}\n\n\t\tp.set = function(key: any, value: any) {\n\t\t\tconst state: MapState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tif (!latest(state).has(key) || latest(state).get(key) !== value) {\n\t\t\t\tprepareMapCopy(state)\n\t\t\t\tmarkChanged(state)\n\t\t\t\tstate.assigned_!.set(key, true)\n\t\t\t\tstate.copy_!.set(key, value)\n\t\t\t\tstate.assigned_!.set(key, true)\n\t\t\t}\n\t\t\treturn this\n\t\t}\n\n\t\tp.delete = function(key: any): boolean {\n\t\t\tif (!this.has(key)) {\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\tconst state: MapState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tprepareMapCopy(state)\n\t\t\tmarkChanged(state)\n\t\t\tstate.assigned_!.set(key, false)\n\t\t\tstate.copy_!.delete(key)\n\t\t\treturn true\n\t\t}\n\n\t\tp.clear = function() {\n\t\t\tconst state: MapState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tif (latest(state).size) {\n\t\t\t\tprepareMapCopy(state)\n\t\t\t\tmarkChanged(state)\n\t\t\t\tstate.assigned_ = new Map()\n\t\t\t\teach(state.base_, key => {\n\t\t\t\t\tstate.assigned_!.set(key, false)\n\t\t\t\t})\n\t\t\t\tstate.copy_!.clear()\n\t\t\t}\n\t\t}\n\n\t\tp.forEach = function(\n\t\t\tcb: (value: any, key: any, self: any) => void,\n\t\t\tthisArg?: any\n\t\t) {\n\t\t\tconst state: MapState = this[DRAFT_STATE]\n\t\t\tlatest(state).forEach((_value: any, key: any, _map: any) => {\n\t\t\t\tcb.call(thisArg, this.get(key), key, this)\n\t\t\t})\n\t\t}\n\n\t\tp.get = function(key: any): any {\n\t\t\tconst state: MapState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tconst value = latest(state).get(key)\n\t\t\tif (state.finalized_ || !isDraftable(value)) {\n\t\t\t\treturn value\n\t\t\t}\n\t\t\tif (value !== state.base_.get(key)) {\n\t\t\t\treturn value // either already drafted or reassigned\n\t\t\t}\n\t\t\t// despite what it looks, this creates a draft only once, see above condition\n\t\t\tconst draft = createProxy(state.scope_.immer_, value, state)\n\t\t\tprepareMapCopy(state)\n\t\t\tstate.copy_!.set(key, draft)\n\t\t\treturn draft\n\t\t}\n\n\t\tp.keys = function(): IterableIterator {\n\t\t\treturn latest(this[DRAFT_STATE]).keys()\n\t\t}\n\n\t\tp.values = function(): IterableIterator {\n\t\t\tconst iterator = this.keys()\n\t\t\treturn {\n\t\t\t\t[iteratorSymbol]: () => this.values(),\n\t\t\t\tnext: () => {\n\t\t\t\t\tconst r = iterator.next()\n\t\t\t\t\t/* istanbul ignore next */\n\t\t\t\t\tif (r.done) return r\n\t\t\t\t\tconst value = this.get(r.value)\n\t\t\t\t\treturn {\n\t\t\t\t\t\tdone: false,\n\t\t\t\t\t\tvalue\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} as any\n\t\t}\n\n\t\tp.entries = function(): IterableIterator<[any, any]> {\n\t\t\tconst iterator = this.keys()\n\t\t\treturn {\n\t\t\t\t[iteratorSymbol]: () => this.entries(),\n\t\t\t\tnext: () => {\n\t\t\t\t\tconst r = iterator.next()\n\t\t\t\t\t/* istanbul ignore next */\n\t\t\t\t\tif (r.done) return r\n\t\t\t\t\tconst value = this.get(r.value)\n\t\t\t\t\treturn {\n\t\t\t\t\t\tdone: false,\n\t\t\t\t\t\tvalue: [r.value, value]\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} as any\n\t\t}\n\n\t\tp[iteratorSymbol] = function() {\n\t\t\treturn this.entries()\n\t\t}\n\n\t\treturn DraftMap\n\t})(Map)\n\n\tfunction proxyMap_(target: T, parent?: ImmerState): T {\n\t\t// @ts-ignore\n\t\treturn new DraftMap(target, parent)\n\t}\n\n\tfunction prepareMapCopy(state: MapState) {\n\t\tif (!state.copy_) {\n\t\t\tstate.assigned_ = new Map()\n\t\t\tstate.copy_ = new Map(state.base_)\n\t\t}\n\t}\n\n\tconst DraftSet = (function(_super) {\n\t\t__extends(DraftSet, _super)\n\t\t// Create class manually, cause #502\n\t\tfunction DraftSet(this: any, target: AnySet, parent?: ImmerState) {\n\t\t\tthis[DRAFT_STATE] = {\n\t\t\t\ttype_: ProxyType.Set,\n\t\t\t\tparent_: parent,\n\t\t\t\tscope_: parent ? parent.scope_ : getCurrentScope()!,\n\t\t\t\tmodified_: false,\n\t\t\t\tfinalized_: false,\n\t\t\t\tcopy_: undefined,\n\t\t\t\tbase_: target,\n\t\t\t\tdraft_: this,\n\t\t\t\tdrafts_: new Map(),\n\t\t\t\trevoked_: false,\n\t\t\t\tisManual_: false\n\t\t\t} as SetState\n\t\t\treturn this\n\t\t}\n\t\tconst p = DraftSet.prototype\n\n\t\tObject.defineProperty(p, \"size\", {\n\t\t\tget: function() {\n\t\t\t\treturn latest(this[DRAFT_STATE]).size\n\t\t\t}\n\t\t\t// enumerable: true,\n\t\t})\n\n\t\tp.has = function(value: any): boolean {\n\t\t\tconst state: SetState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\t// bit of trickery here, to be able to recognize both the value, and the draft of its value\n\t\t\tif (!state.copy_) {\n\t\t\t\treturn state.base_.has(value)\n\t\t\t}\n\t\t\tif (state.copy_.has(value)) return true\n\t\t\tif (state.drafts_.has(value) && state.copy_.has(state.drafts_.get(value)))\n\t\t\t\treturn true\n\t\t\treturn false\n\t\t}\n\n\t\tp.add = function(value: any): any {\n\t\t\tconst state: SetState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tif (!this.has(value)) {\n\t\t\t\tprepareSetCopy(state)\n\t\t\t\tmarkChanged(state)\n\t\t\t\tstate.copy_!.add(value)\n\t\t\t}\n\t\t\treturn this\n\t\t}\n\n\t\tp.delete = function(value: any): any {\n\t\t\tif (!this.has(value)) {\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\tconst state: SetState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tprepareSetCopy(state)\n\t\t\tmarkChanged(state)\n\t\t\treturn (\n\t\t\t\tstate.copy_!.delete(value) ||\n\t\t\t\t(state.drafts_.has(value)\n\t\t\t\t\t? state.copy_!.delete(state.drafts_.get(value))\n\t\t\t\t\t: /* istanbul ignore next */ false)\n\t\t\t)\n\t\t}\n\n\t\tp.clear = function() {\n\t\t\tconst state: SetState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tif (latest(state).size) {\n\t\t\t\tprepareSetCopy(state)\n\t\t\t\tmarkChanged(state)\n\t\t\t\tstate.copy_!.clear()\n\t\t\t}\n\t\t}\n\n\t\tp.values = function(): IterableIterator {\n\t\t\tconst state: SetState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tprepareSetCopy(state)\n\t\t\treturn state.copy_!.values()\n\t\t}\n\n\t\tp.entries = function entries(): IterableIterator<[any, any]> {\n\t\t\tconst state: SetState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tprepareSetCopy(state)\n\t\t\treturn state.copy_!.entries()\n\t\t}\n\n\t\tp.keys = function(): IterableIterator {\n\t\t\treturn this.values()\n\t\t}\n\n\t\tp[iteratorSymbol] = function() {\n\t\t\treturn this.values()\n\t\t}\n\n\t\tp.forEach = function forEach(cb: any, thisArg?: any) {\n\t\t\tconst iterator = this.values()\n\t\t\tlet result = iterator.next()\n\t\t\twhile (!result.done) {\n\t\t\t\tcb.call(thisArg, result.value, result.value, this)\n\t\t\t\tresult = iterator.next()\n\t\t\t}\n\t\t}\n\n\t\treturn DraftSet\n\t})(Set)\n\n\tfunction proxySet_(target: T, parent?: ImmerState): T {\n\t\t// @ts-ignore\n\t\treturn new DraftSet(target, parent)\n\t}\n\n\tfunction prepareSetCopy(state: SetState) {\n\t\tif (!state.copy_) {\n\t\t\t// create drafts for all entries to preserve insertion order\n\t\t\tstate.copy_ = new Set()\n\t\t\tstate.base_.forEach(value => {\n\t\t\t\tif (isDraftable(value)) {\n\t\t\t\t\tconst draft = createProxy(state.scope_.immer_, value, state)\n\t\t\t\t\tstate.drafts_.set(value, draft)\n\t\t\t\t\tstate.copy_!.add(draft)\n\t\t\t\t} else {\n\t\t\t\t\tstate.copy_!.add(value)\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t}\n\n\tfunction assertUnrevoked(state: any /*ES5State | MapState | SetState*/) {\n\t\tif (state.revoked_) die(3, JSON.stringify(latest(state)))\n\t}\n\n\tloadPlugin(\"MapSet\", {proxyMap_, proxySet_})\n}\n", "import {enableES5} from \"./es5\"\nimport {enableMapSet} from \"./mapset\"\nimport {enablePatches} from \"./patches\"\n\nexport function enableAllPlugins() {\n\tenableES5()\n\tenableMapSet()\n\tenablePatches()\n}\n", "import {\n\tIProduce,\n\tIProduceWithPatches,\n\tImmer,\n\tDraft,\n\tImmutable\n} from \"./internal\"\n\nexport {\n\tDraft,\n\tImmutable,\n\tPatch,\n\tPatchListener,\n\toriginal,\n\tcurrent,\n\tisDraft,\n\tisDraftable,\n\tNOTHING as nothing,\n\tDRAFTABLE as immerable,\n\tfreeze\n} from \"./internal\"\n\nconst immer = new Immer()\n\n/**\n * The `produce` function takes a value and a \"recipe function\" (whose\n * return value often depends on the base state). The recipe function is\n * free to mutate its first argument however it wants. All mutations are\n * only ever applied to a __copy__ of the base state.\n *\n * Pass only a function to create a \"curried producer\" which relieves you\n * from passing the recipe function every time.\n *\n * Only plain objects and arrays are made mutable. All other objects are\n * considered uncopyable.\n *\n * Note: This function is __bound__ to its `Immer` instance.\n *\n * @param {any} base - the initial state\n * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified\n * @param {Function} patchListener - optional function that will be called with all the patches produced here\n * @returns {any} a new state, or the initial state if nothing was modified\n */\nexport const produce: IProduce = immer.produce\nexport default produce\n\n/**\n * Like `produce`, but `produceWithPatches` always returns a tuple\n * [nextState, patches, inversePatches] (instead of just the next state)\n */\nexport const produceWithPatches: IProduceWithPatches = immer.produceWithPatches.bind(\n\timmer\n)\n\n/**\n * Pass true to automatically freeze all copies created by Immer.\n *\n * Always freeze by default, even in production mode\n */\nexport const setAutoFreeze = immer.setAutoFreeze.bind(immer)\n\n/**\n * Pass true to use the ES2015 `Proxy` class when creating drafts, which is\n * always faster than using ES5 proxies.\n *\n * By default, feature detection is used, so calling this is rarely necessary.\n */\nexport const setUseProxies = immer.setUseProxies.bind(immer)\n\n/**\n * Apply an array of Immer patches to the first argument.\n *\n * This function is a producer, which means copy-on-write is in effect.\n */\nexport const applyPatches = immer.applyPatches.bind(immer)\n\n/**\n * Create an Immer draft from the given base state, which may be a draft itself.\n * The draft can be modified until you finalize it with the `finishDraft` function.\n */\nexport const createDraft = immer.createDraft.bind(immer)\n\n/**\n * Finalize an Immer draft from a `createDraft` call, returning the base state\n * (if no changes were made) or a modified copy. The draft must *not* be\n * mutated afterwards.\n *\n * Pass a function as the 2nd argument to generate Immer patches based on the\n * changes that were made.\n */\nexport const finishDraft = immer.finishDraft.bind(immer)\n\n/**\n * This function is actually a no-op, but can be used to cast an immutable type\n * to an draft type and make TypeScript happy\n *\n * @param value\n */\nexport function castDraft(value: T): Draft {\n\treturn value as any\n}\n\n/**\n * This function is actually a no-op, but can be used to cast a mutable type\n * to an immutable type and make TypeScript happy\n * @param value\n */\nexport function castImmutable(value: T): Immutable {\n\treturn value as any\n}\n\nexport {Immer}\n\nexport {enableES5} from \"./plugins/es5\"\nexport {enablePatches} from \"./plugins/patches\"\nexport {enableMapSet} from \"./plugins/mapset\"\nexport {enableAllPlugins} from \"./plugins/all\"\n", "// Should be no imports here!\n\n// Some things that should be evaluated before all else...\n\n// We only want to know if non-polyfilled symbols are available\nconst hasSymbol =\n\ttypeof Symbol !== \"undefined\" && typeof Symbol(\"x\") === \"symbol\"\nexport const hasMap = typeof Map !== \"undefined\"\nexport const hasSet = typeof Set !== \"undefined\"\nexport const hasProxies =\n\ttypeof Proxy !== \"undefined\" &&\n\ttypeof Proxy.revocable !== \"undefined\" &&\n\ttypeof Reflect !== \"undefined\"\n\n/**\n * The sentinel value returned by producers to replace the draft with undefined.\n */\nexport const NOTHING: Nothing = hasSymbol\n\t? Symbol.for(\"immer-nothing\")\n\t: ({[\"immer-nothing\"]: true} as any)\n\n/**\n * To let Immer treat your class instances as plain immutable objects\n * (albeit with a custom prototype), you must define either an instance property\n * or a static property on each of your custom classes.\n *\n * Otherwise, your class instance will never be drafted, which means it won't be\n * safe to mutate in a produce callback.\n */\nexport const DRAFTABLE: unique symbol = hasSymbol\n\t? Symbol.for(\"immer-draftable\")\n\t: (\"__$immer_draftable\" as any)\n\nexport const DRAFT_STATE: unique symbol = hasSymbol\n\t? Symbol.for(\"immer-state\")\n\t: (\"__$immer_state\" as any)\n\n// Even a polyfilled Symbol might provide Symbol.iterator\nexport const iteratorSymbol: typeof Symbol.iterator =\n\t(typeof Symbol != \"undefined\" && Symbol.iterator) || (\"@@iterator\" as any)\n\n/** Use a class type for `nothing` so its type is unique */\nexport class Nothing {\n\t// This lets us do `Exclude`\n\t// @ts-ignore\n\tprivate _!: unique symbol\n}\n", "const globals = {\n /**\n * If the schema of the redux store changes in a backwards-incompatible way, then this version number should be incremented.\n *\n * While this looks like semver, it is not. There are no patch numbers, so any change in this number is a breaking change.\n *\n * However, as long as the schema of the redux store is backwards-compatible, then we don't have to change this number.\n *\n * Since the 0.4.0 release, this number has not had to change.\n */\n currentProjectStateDefinitionVersion: '0.4.0',\n}\n\nexport default globals\n", "import type {Studio} from '@theatre/studio/Studio'\nimport delay from '@theatre/shared/utils/delay'\nimport {original} from 'immer'\nimport type Project from './Project'\nimport type {OnDiskState} from './store/storeTypes'\nimport globals from '@theatre/shared/globals'\n\n/**\n * @remarks\n * TODO this could be turned into a simple prism, like:\n * `editor.isReady: Prism<{isReady: true} | {isReady: false, reason: 'conflictBetweenDiskStateAndBrowserState'}>`\n */\nexport default async function initialiseProjectState(\n studio: Studio,\n project: Project,\n onDiskState: OnDiskState | undefined,\n) {\n /*\n * If in the future we move to IndexedDB to store the state, we'll have\n * to deal with it being async (as opposed to localStorage that is synchronous.)\n * so here we're artifically delaying the loading of the state to make sure users\n * don't count on the state always being already loaded synchronously\n */\n await delay(0)\n\n studio.transaction(({drafts}) => {\n const projectId = project.address.projectId\n\n drafts.ephemeral.coreByProject[projectId] = {\n lastExportedObject: null,\n loadingState: {type: 'loading'},\n }\n\n drafts.ahistoric.coreByProject[projectId] = {\n ahistoricStuff: '',\n }\n\n function useInitialState() {\n drafts.ephemeral.coreByProject[projectId].loadingState = {\n type: 'loaded',\n }\n\n drafts.historic.coreByProject[projectId] = {\n sheetsById: {},\n definitionVersion: globals.currentProjectStateDefinitionVersion,\n revisionHistory: [],\n }\n }\n\n function useOnDiskState(state: OnDiskState) {\n drafts.ephemeral.coreByProject[projectId].loadingState = {\n type: 'loaded',\n }\n\n drafts.historic.coreByProject[projectId] = state\n }\n\n function useBrowserState() {\n drafts.ephemeral.coreByProject[projectId].loadingState = {\n type: 'loaded',\n }\n }\n\n function browserStateIsNotBasedOnDiskState(onDiskState: OnDiskState) {\n drafts.ephemeral.coreByProject[projectId].loadingState = {\n type: 'browserStateIsNotBasedOnDiskState',\n onDiskState,\n }\n }\n\n const browserState = original(drafts.historic)?.coreByProject[\n project.address.projectId\n ]\n\n if (!browserState) {\n if (!onDiskState) {\n useInitialState()\n } else {\n useOnDiskState(onDiskState)\n }\n } else {\n if (!onDiskState) {\n useBrowserState()\n } else {\n if (\n browserState.revisionHistory.indexOf(\n onDiskState.revisionHistory[0],\n ) == -1\n ) {\n browserStateIsNotBasedOnDiskState(onDiskState)\n } else {\n useBrowserState()\n }\n }\n }\n })\n}\n", "import type {\n ITheatreLoggerConfig,\n ITheatreLoggingConfig,\n} from '@theatre/shared/logger'\nimport {TheatreLoggerLevel} from '@theatre/shared/logger'\nimport {createTheatreInternalLogger} from '@theatre/shared/logger'\n\nexport type CoreLoggingConfig = Partial<{\n logger: ITheatreLoggerConfig\n logging: ITheatreLoggingConfig\n}>\n\nfunction noop() {}\n\nexport function _coreLogger(config?: CoreLoggingConfig) {\n const internalMin = config?.logging?.internal\n ? config.logging.min ?? TheatreLoggerLevel.WARN\n : Infinity // if not internal, then don't show any logs\n const shouldDebugLogger = internalMin <= TheatreLoggerLevel.DEBUG\n const shouldShowLoggerErrors = internalMin <= TheatreLoggerLevel.ERROR\n const internal = createTheatreInternalLogger(undefined, {\n _debug: shouldDebugLogger\n ? console.debug.bind(console, '_coreLogger(TheatreInternalLogger) debug')\n : noop,\n _error: shouldShowLoggerErrors\n ? console.error.bind(console, '_coreLogger(TheatreInternalLogger) error')\n : noop,\n })\n\n if (config) {\n const {logger, logging} = config\n if (logger) internal.configureLogger(logger)\n if (logging) internal.configureLogging(logging)\n else {\n // default to showing Theatre.js dev logs in non-production environments\n internal.configureLogging({\n dev: process.env.NODE_ENV !== 'production',\n })\n }\n }\n\n return internal.getLogger().named('Theatre')\n}\n", "import type {OnDiskState} from '@theatre/core/projects/store/storeTypes'\nimport type TheatreProject from '@theatre/core/projects/TheatreProject'\nimport type Sheet from '@theatre/core/sheets/Sheet'\nimport SheetTemplate from '@theatre/core/sheets/SheetTemplate'\nimport type {Studio} from '@theatre/studio/Studio'\nimport type {ProjectAddress} from '@theatre/shared/utils/addresses'\nimport type {Pointer} from '@theatre/dataverse'\nimport {PointerProxy} from '@theatre/dataverse'\nimport {Atom} from '@theatre/dataverse'\nimport initialiseProjectState from './initialiseProjectState'\nimport projectsSingleton from './projectsSingleton'\nimport type {ProjectState} from './store/storeTypes'\nimport type {Deferred} from '@theatre/shared/utils/defer'\nimport {defer} from '@theatre/shared/utils/defer'\nimport globals from '@theatre/shared/globals'\nimport type {\n ProjectId,\n SheetId,\n SheetInstanceId,\n} from '@theatre/shared/utils/ids'\nimport type {\n ILogger,\n ITheatreLoggerConfig,\n ITheatreLoggingConfig,\n} from '@theatre/shared/logger'\nimport {_coreLogger} from '@theatre/core/_coreLogger'\n\ntype ICoreAssetStorage = {\n /** Returns a URL for the provided asset ID */\n getAssetUrl: (assetId: string) => string\n}\n\ninterface IStudioAssetStorage extends ICoreAssetStorage {\n /** Creates an asset from the provided blob and returns a promise to its ID */\n createAsset: (asset: File) => Promise\n}\n\nexport type IAssetStorageConfig = {\n /**\n * An object containing the core asset storage methods.\n */\n coreAssetStorage: ICoreAssetStorage\n}\n\ntype IAssetConf = {\n /** The base URL for assets. */\n baseUrl?: string\n}\n\nexport type Conf = Partial<{\n state: OnDiskState\n assets: IAssetConf\n experiments: ExperimentsConf\n}>\n\nexport type ExperimentsConf = Partial<{\n logger: ITheatreLoggerConfig\n logging: ITheatreLoggingConfig\n}>\n\nexport default class Project {\n readonly pointers: {\n historic: Pointer\n ahistoric: Pointer\n ephemeral: Pointer\n }\n\n private readonly _pointerProxies: {\n historic: PointerProxy\n ahistoric: PointerProxy\n ephemeral: PointerProxy\n }\n\n readonly address: ProjectAddress\n\n private readonly _studioReadyDeferred: Deferred\n private readonly _assetStorageReadyDeferred: Deferred\n private readonly _readyPromise: Promise\n\n private _sheetTemplates = new Atom<{\n [sheetId: string]: SheetTemplate | undefined\n }>({})\n sheetTemplatesP = this._sheetTemplates.pointer\n private _studio: Studio | undefined\n assetStorage: IStudioAssetStorage\n\n type: 'Theatre_Project' = 'Theatre_Project'\n readonly _logger: ILogger\n\n constructor(\n id: ProjectId,\n readonly config: Conf = {},\n readonly publicApi: TheatreProject,\n ) {\n this._logger = _coreLogger({logging: {dev: true}}).named('Project', id)\n this._logger.traceDev('creating project')\n this.address = {projectId: id}\n\n const onDiskStateAtom = new Atom({\n ahistoric: {\n ahistoricStuff: '',\n },\n historic: config.state ?? {\n sheetsById: {},\n definitionVersion: globals.currentProjectStateDefinitionVersion,\n revisionHistory: [],\n },\n ephemeral: {\n loadingState: {\n type: 'loaded',\n },\n lastExportedObject: null,\n },\n })\n\n this._assetStorageReadyDeferred = defer()\n this.assetStorage = {\n getAssetUrl: (assetId: string) => `${config.assets?.baseUrl}/${assetId}`,\n\n // Until the asset storage is ready, we'll throw an error when the user tries to use it\n createAsset: () => {\n throw new Error(`Please wait for Project.ready to use assets.`)\n },\n }\n\n this._pointerProxies = {\n historic: new PointerProxy(onDiskStateAtom.pointer.historic),\n ahistoric: new PointerProxy(onDiskStateAtom.pointer.ahistoric),\n ephemeral: new PointerProxy(onDiskStateAtom.pointer.ephemeral),\n }\n\n this.pointers = {\n historic: this._pointerProxies.historic.pointer,\n ahistoric: this._pointerProxies.ahistoric.pointer,\n ephemeral: this._pointerProxies.ephemeral.pointer,\n }\n\n projectsSingleton.add(id, this)\n\n this._studioReadyDeferred = defer()\n\n this._readyPromise = Promise.all([\n this._studioReadyDeferred.promise,\n this._assetStorageReadyDeferred.promise,\n // hide the array from the user, i.e. make it Promise instead of Promise<[undefined, undefined]>\n ]).then(() => {})\n\n if (config.state) {\n setTimeout(() => {\n // The user has provided config.state but in case @theatre/studio is loaded,\n // let's give it one tick to attach itself\n if (!this._studio) {\n this._studioReadyDeferred.resolve(undefined)\n this._assetStorageReadyDeferred.resolve(undefined)\n this._logger._trace('ready deferred resolved with no state')\n }\n }, 0)\n } else {\n if (typeof window === 'undefined') {\n if (process.env.NODE_ENV === 'production') {\n console.error(\n `Argument config.state in Theatre.getProject(\"${id}\", config) is empty. ` +\n `You can safely ignore this message if you're developing a Next.js/Remix project in development mode. But if you are shipping to your end-users, ` +\n `then you need to set config.state, ` +\n `otherwise your project's state will be empty and nothing will animate. Learn more at https://www.theatrejs.com/docs/latest/manual/projects#state`,\n )\n }\n } else {\n setTimeout(() => {\n if (!this._studio) {\n throw new Error(\n `Argument config.state in Theatre.getProject(\"${id}\", config) is empty. This is fine ` +\n `while you are using @theatre/core along with @theatre/studio. But since @theatre/studio ` +\n `is not loaded, the state of project \"${id}\" will be empty.\\n\\n` +\n `To fix this, you need to add @theatre/studio into the bundle and export ` +\n `the project's state. Learn how to do that at https://www.theatrejs.com/docs/latest/manual/projects#state\\n`,\n )\n }\n }, 1000)\n }\n }\n }\n\n attachToStudio(studio: Studio) {\n if (this._studio) {\n if (this._studio !== studio) {\n throw new Error(\n `Project ${this.address.projectId} is already attached to studio ${this._studio.address.studioId}`,\n )\n } else {\n console.warn(\n `Project ${this.address.projectId} is already attached to studio ${this._studio.address.studioId}`,\n )\n return\n }\n }\n this._studio = studio\n\n studio.initialized\n .then(async () => {\n await initialiseProjectState(studio, this, this.config.state)\n\n this._pointerProxies.historic.setPointer(\n studio.atomP.historic.coreByProject[this.address.projectId],\n )\n this._pointerProxies.ahistoric.setPointer(\n studio.atomP.ahistoric.coreByProject[this.address.projectId],\n )\n this._pointerProxies.ephemeral.setPointer(\n studio.atomP.ephemeral.coreByProject[this.address.projectId],\n )\n\n // asset storage has to be initialized after the pointers are set\n await studio\n .createAssetStorage(this, this.config.assets?.baseUrl)\n .then((assetStorage) => {\n this.assetStorage = assetStorage\n this._assetStorageReadyDeferred.resolve(undefined)\n })\n\n this._studioReadyDeferred.resolve(undefined)\n })\n .catch((err) => {\n console.error(err)\n throw err\n })\n }\n\n get isAttachedToStudio() {\n return !!this._studio\n }\n\n get ready() {\n return this._readyPromise\n }\n\n isReady() {\n return (\n this._studioReadyDeferred.status === 'resolved' &&\n this._assetStorageReadyDeferred.status === 'resolved'\n )\n }\n\n getOrCreateSheet(\n sheetId: SheetId,\n instanceId: SheetInstanceId = 'default' as SheetInstanceId,\n ): Sheet {\n let template = this._sheetTemplates.get()[sheetId]\n\n if (!template) {\n template = new SheetTemplate(this, sheetId)\n this._sheetTemplates.reduce((s) => ({...s, [sheetId]: template}))\n }\n\n return template.getInstance(instanceId)\n }\n}\n", "import {privateAPI, setPrivateAPI} from '@theatre/core/privateAPIs'\nimport Project from '@theatre/core/projects/Project'\nimport type {ISheet} from '@theatre/core/sheets/TheatreSheet'\n\nimport type {ProjectAddress} from '@theatre/shared/utils/addresses'\nimport type {Asset, File} from '@theatre/shared/utils/assets'\nimport type {\n ProjectId,\n SheetId,\n SheetInstanceId,\n} from '@theatre/shared/utils/ids'\nimport {validateInstanceId} from '@theatre/shared/utils/sanitizers'\nimport {validateAndSanitiseSlashedPathOrThrow} from '@theatre/shared/utils/slashedPaths'\nimport type {$IntentionalAny} from '@theatre/shared/utils/types'\n\n/**\n * A project's config object (currently the only point of configuration is the project's state)\n */\nexport type IProjectConfig = {\n /**\n * The state of the project, as [exported](https://www.theatrejs.com/docs/latest/manual/projects#state) by the studio.\n */\n state?: $IntentionalAny\n assets?: {\n baseUrl?: string\n }\n}\n\n// export type IProjectConfigExperiments = {\n// /**\n// * Defaults to using global `console` with style args.\n// *\n// * (TODO: check for browser environment before using style args)\n// */\n// logger?: ITheatreLoggerConfig\n// /**\n// * Defaults:\n// * * `production` builds: console - error\n// * * `development` builds: console - error, warning\n// */\n// logging?: ITheatreLoggingConfig\n// }\n\n/**\n * A Theatre.js project\n */\nexport interface IProject {\n readonly type: 'Theatre_Project_PublicAPI'\n /**\n * If `@theatre/studio` is used, this promise would resolve when studio has loaded\n * the state of the project into memory.\n *\n * If `@theatre/studio` is not used, this promise is already resolved.\n */\n readonly ready: Promise\n /**\n * Shows whether the project is ready to be used.\n * Better to use {@link IProject.ready}, which is a promise that would\n * resolve when the project is ready.\n */\n readonly isReady: boolean\n /**\n * The project's address\n */\n readonly address: ProjectAddress\n\n /**\n * Creates a Sheet under the project\n * @param sheetId - Sheets are identified by their `sheetId`, which must be a string longer than 3 characters\n * @param instanceId - Optionally provide an `instanceId` if you want to create multiple instances of the same Sheet\n * @returns The newly created Sheet\n *\n * **Docs: https://www.theatrejs.com/docs/latest/manual/sheets**\n */\n sheet(sheetId: string, instanceId?: string): ISheet\n\n /**\n * Returns the URL for an asset.\n *\n * @param asset - The asset to get the URL for\n * @returns The URL for the asset, or `undefined` if the asset is not found\n */\n getAssetUrl(asset: Asset | File): string | undefined\n}\n\nexport default class TheatreProject implements IProject {\n get type(): 'Theatre_Project_PublicAPI' {\n return 'Theatre_Project_PublicAPI'\n }\n /**\n * @internal\n */\n constructor(id: string, config: IProjectConfig = {}) {\n setPrivateAPI(this, new Project(id as ProjectId, config, this))\n }\n\n get ready(): Promise {\n return privateAPI(this).ready\n }\n\n get isReady(): boolean {\n return privateAPI(this).isReady()\n }\n\n get address(): ProjectAddress {\n return {...privateAPI(this).address}\n }\n\n getAssetUrl(asset: Asset): string | undefined {\n // probably should put this in project.getAssetUrl but this will do for now\n if (!this.isReady) {\n console.error(\n 'Calling `project.getAssetUrl()` before `project.ready` is resolved, will always return `undefined`. ' +\n 'Either use `project.ready.then(() => project.getAssetUrl())` or `await project.ready` before calling `project.getAssetUrl()`.',\n )\n return undefined\n }\n\n return asset.id\n ? privateAPI(this).assetStorage.getAssetUrl(asset.id)\n : undefined\n }\n\n sheet(sheetId: string, instanceId: string = 'default'): ISheet {\n const sanitizedPath = validateAndSanitiseSlashedPathOrThrow(\n sheetId,\n 'project.sheet',\n )\n\n if (process.env.NODE_ENV !== 'production') {\n validateInstanceId(\n instanceId,\n 'instanceId in project.sheet(sheetId, instanceId)',\n true,\n )\n }\n\n return privateAPI(this).getOrCreateSheet(\n sanitizedPath as SheetId,\n instanceId as SheetInstanceId,\n ).publicApi\n }\n}\n", "import type {Studio} from '@theatre/studio/Studio'\nimport projectsSingleton from './projects/projectsSingleton'\nimport {privateAPI} from './privateAPIs'\nimport * as coreExports from './coreExports'\nimport {getCoreRafDriver} from './coreTicker'\n\nexport type CoreBits = {\n projectsP: typeof projectsSingleton.atom.pointer.projects\n privateAPI: typeof privateAPI\n coreExports: typeof coreExports\n getCoreRafDriver: typeof getCoreRafDriver\n}\n\nexport default class CoreBundle {\n private _studio: Studio | undefined = undefined\n constructor() {}\n\n get type(): 'Theatre_CoreBundle' {\n return 'Theatre_CoreBundle'\n }\n\n get version() {\n return process.env.THEATRE_VERSION\n }\n\n getBitsForStudio(studio: Studio, callback: (bits: CoreBits) => void) {\n if (this._studio) {\n throw new Error(`@theatre/core is already attached to @theatre/studio`)\n }\n this._studio = studio\n const bits: CoreBits = {\n projectsP: projectsSingleton.atom.pointer.projects,\n privateAPI: privateAPI,\n coreExports,\n getCoreRafDriver,\n }\n\n callback(bits)\n }\n}\n", "import * as core from '@theatre/core'\n\n// @ts-ignore\nwindow.Theatre = {\n core,\n get studio() {\n alert(\n \"Theatre.studio is only available in the core-and-studio.js bundle. You're using the core-only.min.js bundle.\",\n )\n return undefined\n },\n}\n"], "mappings": "gkCAAA,oBAWA,GAAI,IAEJ,GAAO,QAAU,GAAc,UAAW,CACxC,WAAoB,EAAK,EAAK,EAAK,EAAK,CACtC,KAAK,IAAI,EAAK,EAAK,EAAK,GAG1B,SAAW,UAAU,IAAM,SAAS,EAAK,EAAK,EAAK,EAAK,CACtD,KAAK,IAAM,EAAM,EACjB,KAAK,IAAM,EAAO,GAAM,GAA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