@manyducks.co/dolla 0.77.0 → 0.77.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../node_modules/simple-color-hash/lib/index.js", "../src/classes/CrashCollector.ts", "../src/classes/DebugHub.ts", "../src/typeChecking.ts", "../src/utils.ts", "../src/state.ts", "../src/nodes/cond.ts", "../node_modules/nanoid/index.browser.js", "../src/nodes/html.ts", "../src/nodes/observer.ts", "../src/nodes/outlet.ts", "../src/nodes/portal.ts", "../src/view.ts", "../src/nodes/repeat.ts", "../src/nodes/text.ts", "../src/markup.ts", "../src/store.ts", "../src/stores/document.ts", "../src/stores/render.ts", "../src/views/default-crash-page.ts", "../src/views/default-view.ts", "../src/app.ts", "../src/views/fragment.ts", "../src/views/store-scope.ts", "../node_modules/@babel/runtime/helpers/esm/extends.js", "../node_modules/history/index.js", "../src/routing.ts", "../src/stores/router.ts", "../src/stores/language.ts", "../src/stores/http.ts", "../src/stores/dialog.ts"],
4
- "sourcesContent": ["\"use strict\";Object.defineProperty(exports,\"__esModule\",{value:!0});var _slicedToArray=function(){function a(a,b){var c=[],d=!0,e=!1,f=void 0;try{for(var g,h=a[Symbol.iterator]();!(d=(g=h.next()).done)&&(c.push(g.value),!(b&&c.length===b));d=!0);}catch(a){e=!0,f=a}finally{try{!d&&h[\"return\"]&&h[\"return\"]()}finally{if(e)throw f}}return c}return function(b,c){if(Array.isArray(b))return b;if(Symbol.iterator in Object(b))return a(b,c);throw new TypeError(\"Invalid attempt to destructure non-iterable instance\")}}(),rgbToHex=function(a){return a.reduce(function(a,b){return 16>b?a+\"0\"+b.toString(16):a+b.toString(16)},\"#\")},hslToRgb=function(a,b,c){var d=.5>c?c*(1+b):c+b-c*b,e=2*c-d,f=function(a,b,c){var d=Math.round,e=0>c?c+1:1<c?c-1:c;return e=e<1/6?a+6*(b-a)*e:e<1/2?b:e<2/3?a+6*(b-a)*(2/3-e):a,d(255*e)},g=f(e,d,a+1/3),h=f(e,d,a),i=f(e,d,a-1/3);return[g,h,i]},hslGeneration=function(a,b,c,d){var e=a%1007/1007,f=function(a,b,c){return a*(c-b)+b},g=f(e,b.min,b.max),h=f(e,c.min,c.max),i=f(e,d.max,d.min);// 1007 is a prime\nreturn[g,h,i]},standardHashFunction=function(a){return a.split(\"\").reduce(function(a,b,c){return a*b.charCodeAt(0)*c+1},1)},generateColorHash=function(a){var b=a.str,c=a.hue,d=c===void 0?{min:0,max:360}:c,e=a.sat,f=e===void 0?{min:.35,max:.65}:e,g=a.light,h=g===void 0?{min:.3,max:.7}:g,i=a.hashFunction,j=i===void 0?standardHashFunction:i,k=a.scheme,l=k===void 0?\"hex\":k,m=hslGeneration(j(b),d,f,h),n=_slicedToArray(m,3),o=n[0],p=n[1],q=n[2],r=hslToRgb(o/360,p,q),s=rgbToHex(r);if(\"hsl\"===l)return[o,p,q];return\"rgb\"===l?r:s};/**\n *\n * @param {Array} RGBArray\n *//**\n *\n * @param {number} H Hue\n * @param {number} S Saturation\n * @param {number} L Lightness\n *//**\n *\n * @param {string} hash generated hash\n * @param {number} hue Hue\n * @param {number} sat Saturation\n * @param {number} light Lightness\n *//**\n *\n * @param {string} str string to hash\n *//**\n *\n * @param {Object} {\n * str: String to be hashed,\n * hue: { min, max } values (in deg)\n * sat: { min, max } values (0 to 1)\n * light: { min, max } values (0 to 1),\n * hashFunction: Custom hash function,\n * scheme: return scheme\n * }\n */exports.default=generateColorHash,module.exports=exports.default;", "// ----- Types ----- //\n\ninterface ErrorContext {\n error: Error;\n severity: \"error\" | \"crash\";\n componentName: string;\n}\n\ninterface CrashOptions {\n error: Error;\n componentName?: string;\n}\n\ntype ErrorCallback = (ctx: ErrorContext) => void;\n\n// ----- Code ----- //\n\n/**\n * Receives errors that occur in components.\n */\nexport class CrashCollector {\n #errors: ErrorContext[] = [];\n #errorCallbacks: ErrorCallback[] = [];\n\n /**\n * Registers a callback to receive all errors that pass through the CrashCollector.\n * Returns a function that cancels this listener when called.\n */\n onError(callback: ErrorCallback) {\n this.#errorCallbacks.push(callback);\n\n return () => {\n this.#errorCallbacks.splice(this.#errorCallbacks.indexOf(callback), 1);\n };\n }\n\n /**\n * Reports an unrecoverable error that requires crashing the whole app.\n */\n crash({ error, componentName }: CrashOptions) {\n const ctx: ErrorContext = {\n error,\n severity: \"crash\",\n componentName: componentName ?? \"anonymous component\",\n };\n\n this.#errors.push(ctx);\n for (const callback of this.#errorCallbacks) {\n callback(ctx);\n }\n\n throw error; // Throws the error so developer can work with the stack trace in the console.\n }\n\n /**\n * Reports a recoverable error.\n */\n error({ error, componentName }: CrashOptions) {\n const ctx: ErrorContext = {\n error,\n severity: \"error\",\n componentName: componentName ?? \"anonymous component\",\n };\n\n this.#errors.push(ctx);\n for (const callback of this.#errorCallbacks) {\n callback(ctx);\n }\n }\n}\n", "import colorHash from \"simple-color-hash\";\nimport { isString } from \"../typeChecking.js\";\nimport { type CrashCollector } from \"./CrashCollector.js\";\n\nexport type DebugOptions = {\n /**\n * Determines which debug channels are printed. Supports multiple filters with commas,\n * a prepended `-` to exclude a channel and wildcards to match partial channels.\n *\n * @example \"store:*,-store:test\" // matches everything starting with \"store\" except \"store:test\"\n */\n filter?: string | RegExp;\n\n /**\n * Print info messages when true. Default: true for development builds, false for production builds.\n */\n info?: boolean | \"development\";\n\n /**\n * Print log messages when true. Default: true for development builds, false for production builds.\n */\n log?: boolean | \"development\";\n\n /**\n * Print warn messages when true. Default: true for development builds, false for production builds.\n */\n warn?: boolean | \"development\";\n\n /**\n * Print error messages when true. Default: true.\n */\n error?: boolean | \"development\";\n};\n\ntype DebugHubOptions = DebugOptions & {\n crashCollector: CrashCollector;\n mode: \"development\" | \"production\";\n};\n\nexport interface DebugChannelOptions {\n name: string;\n}\n\nexport interface DebugChannel {\n info(...args: any[]): void;\n log(...args: any[]): void;\n warn(...args: any[]): void;\n error(...args: any[]): void;\n}\n\n/**\n * The central trunk from which all channels branch.\n * Changing the filter here determines what kind of messages are printed across the app.\n */\nexport class DebugHub {\n #filter: string | RegExp = \"*,-dolla/*\";\n #matcher;\n #console;\n #options;\n\n constructor(options: DebugHubOptions, _console = getDefaultConsole()) {\n if (options.filter) {\n this.#filter = options.filter;\n }\n\n this.#matcher = makeMatcher(this.#filter);\n this.#console = _console;\n this.#options = options;\n }\n\n /**\n * Returns a debug channel labelled by `name`. Used for logging from components.\n */\n channel(options: DebugChannelOptions): DebugChannel {\n const _console = this.#console;\n const hubOptions = this.#options;\n\n const match = (value: string) => {\n return this.#matcher(value);\n };\n\n return {\n get info() {\n const name = options.name;\n\n if (\n hubOptions.info === false ||\n (isString(hubOptions.info) && hubOptions.info !== hubOptions.mode) ||\n !match(name)\n ) {\n return noOp;\n } else {\n const label = `%c${name}`;\n return _console.info.bind(_console, label, `color:${hash(label)};font-weight:bold`);\n }\n },\n\n get log() {\n const name = options.name;\n\n if (\n hubOptions.log === false ||\n (isString(hubOptions.log) && hubOptions.log !== hubOptions.mode) ||\n !match(name)\n ) {\n return noOp;\n } else {\n const label = `%c${name}`;\n return _console.log.bind(_console, label, `color:${hash(label)};font-weight:bold`);\n }\n },\n\n get warn() {\n const name = options.name;\n\n if (\n hubOptions.warn === false ||\n (isString(hubOptions.warn) && hubOptions.warn !== hubOptions.mode) ||\n !match(name)\n ) {\n return noOp;\n } else {\n const label = `%c${name}`;\n return _console.warn.bind(_console, label, `color:${hash(label)};font-weight:bold`);\n }\n },\n\n get error() {\n const name = options.name;\n\n if (\n hubOptions.error === false ||\n (isString(hubOptions.error) && hubOptions.error !== hubOptions.mode) ||\n !match(name)\n ) {\n return noOp;\n } else {\n const label = `%c${name}`;\n return _console.error.bind(_console, label, `color:${hash(label)};font-weight:bold`);\n }\n },\n };\n }\n\n get filter() {\n return this.#filter;\n }\n\n set filter(pattern) {\n this.#filter = pattern;\n this.#matcher = makeMatcher(pattern);\n }\n}\n\n/* ----- Helpers ----- */\n\nfunction getDefaultConsole() {\n if (typeof window !== \"undefined\" && window.console) {\n return window.console;\n }\n\n if (typeof global !== \"undefined\" && global.console) {\n return global.console;\n }\n}\n\nconst noOp = () => {};\n\nfunction hash(value: string) {\n return colorHash({\n str: value,\n sat: { min: 0.35, max: 0.55 },\n light: { min: 0.6, max: 0.6 },\n });\n}\n\ntype MatcherFunction = (value: string) => boolean;\n\n/**\n * Parses a filter string into a match function.\n *\n * @param pattern - A string or regular expression that specifies a pattern for names of debug channels you want to display.\n */\nexport function makeMatcher(pattern: string | RegExp) {\n if (pattern instanceof RegExp) {\n return (value: string) => pattern.test(value);\n }\n\n const matchers: Record<\"positive\" | \"negative\", MatcherFunction[]> = {\n positive: [],\n negative: [],\n };\n\n const parts = pattern\n .split(\",\")\n .map((p) => p.trim())\n .filter((p) => p !== \"\");\n\n for (let part of parts) {\n let section: \"positive\" | \"negative\" = \"positive\";\n\n if (part.startsWith(\"-\")) {\n section = \"negative\";\n part = part.slice(1);\n }\n\n if (part === \"*\") {\n matchers[section].push(function () {\n return true;\n });\n } else if (part.endsWith(\"*\")) {\n matchers[section].push(function (value) {\n return value.startsWith(part.slice(0, part.length - 1));\n });\n } else {\n matchers[section].push(function (value) {\n return value === part;\n });\n }\n }\n\n return function (name: string) {\n const { positive, negative } = matchers;\n\n // Matching any negative matcher disqualifies.\n if (negative.some((fn) => fn(name))) {\n return false;\n }\n\n // Matching at least one positive matcher is required if any are specified.\n if (positive.length > 0 && !positive.some((fn) => fn(name))) {\n return false;\n }\n\n return true;\n };\n}\n", "type TypeNames =\n // These values can be returned by `typeof`.\n | \"string\"\n | \"number\"\n | \"bigint\"\n | \"boolean\"\n | \"symbol\"\n | \"undefined\"\n | \"object\"\n | \"function\"\n // These values are more specific ones that `Type.of` can return.\n | \"null\"\n | \"array\"\n | \"class\"\n | \"promise\"\n | \"NaN\";\n\n/**\n * Represents an object that can be called with `new` to produce a T.\n */\ntype Factory<T> = { new (): T };\n\n/**\n * Extends `typeof` operator with more specific and useful type distinctions.\n */\nexport function typeOf(value: unknown): TypeNames {\n if (value === undefined) {\n return \"undefined\";\n }\n\n if (value === null) {\n return \"null\";\n }\n\n const type = typeof value;\n\n switch (type) {\n case \"number\":\n if (isNaN(value as any)) {\n return \"NaN\";\n }\n return \"number\";\n case \"function\":\n if (isClass(value)) {\n return \"class\";\n }\n\n return type;\n case \"object\":\n if (isArray(value)) {\n return \"array\";\n }\n\n if (isPromise(value)) {\n return \"promise\";\n }\n\n return type;\n default:\n return type;\n }\n}\n\n/**\n * Throws a TypeError unless `condition` is truthy.\n *\n * @param condition - Value whose truthiness is in question.\n * @param errorMessage - Optional message for the thrown TypeError.\n */\nexport function assert(condition: any, errorMessage?: string): void {\n if (!condition) {\n throw new TypeError(\n formatError(condition, errorMessage || \"Failed assertion. Value is not truthy. Got type: %t, value: %v\")\n );\n }\n}\n\n/**\n * Returns true if `value` is an array.\n */\nexport function isArray(value: unknown): value is Array<unknown> {\n return Array.isArray(value);\n}\n\n/**\n * Throws an error if `value` is not an array.\n */\nexport function assertArray(value: unknown, errorMessage?: string): value is Array<unknown> {\n if (isArray(value)) {\n return true;\n }\n\n throw new TypeError(formatError(value, errorMessage || \"Expected array. Got type: %t, value: %v\"));\n}\n\n/**\n * Returns a function that takes a `value` and ensures that it is an array for which `check` returns true for every item.\n *\n * @param check - Function to check items against.\n */\nexport function isArrayOf<T>(check: (item: unknown) => boolean): (value: unknown) => value is T[];\n\n/**\n * Returns true when `value` is an array and `check` returns true for every item.\n *\n * @param check - Function to check items against.\n * @param value - A possible array.\n */\nexport function isArrayOf<T>(check: (item: unknown) => boolean, value: unknown): value is T[];\n\nexport function isArrayOf<T>(...args: unknown[]) {\n const check = args[0] as (item: unknown) => boolean;\n\n const test = (value: unknown): value is T[] => {\n return isArray(value) && value.every((item) => check(item));\n };\n\n if (args.length < 2) {\n return test;\n } else {\n return test(args[1]);\n }\n}\n\n/**\n * Returns a function that takes a `value` and throws a TypeError unless it is an array for which `check` returns true for every item.\n *\n * @param check - Function to check items against.\n */\nexport function assertArrayOf<T>(check: (item: unknown) => boolean): (value: unknown) => value is T[];\n\n/**\n * Throws a TypeError unless `value` is an array and `check` returns true for every item.\n *\n * @param check - Function to check items against.\n * @param value - A possible array.\n * @param errorMessage - A custom error message.\n */\nexport function assertArrayOf<T>(\n check: (item: unknown) => boolean,\n value: unknown,\n errorMessage?: string\n): value is T[];\n\nexport function assertArrayOf<T>(...args: unknown[]) {\n const check = args[0] as (item: unknown) => boolean;\n const message = isString(args[2]) ? args[2] : \"Expected an array of valid items. Got type: %t, value: %v\";\n\n const test = (value: unknown): value is T[] => {\n if (isArray(value) && value.every((item) => check(item))) {\n return true;\n }\n\n throw new TypeError(formatError(value, message));\n };\n\n if (args.length < 2) {\n return test;\n } else {\n return test(args[1]);\n }\n}\n\n/**\n * Returns true if `value` is equal to `true` or `false`.\n */\nexport function isBoolean(value: unknown): value is boolean {\n return value === true || value === false;\n}\n\n/**\n * Throws a TypeError unless `value` is equal to `true` or `false`.\n */\nexport function assertBoolean(value: unknown, errorMessage?: string): value is boolean {\n if (isBoolean(value)) {\n return true;\n }\n\n throw new TypeError(formatError(value, errorMessage ?? \"Expected a boolean. Got type: %t, value: %v\"));\n}\n\n/**\n * Returns true if `value` is a string.\n */\nexport function isString(value: unknown): value is string {\n return typeof value === \"string\";\n}\n\n/**\n * Throws a TypeError unless `value` is a string.\n */\nexport function assertString(value: unknown, errorMessage?: string): value is string {\n if (isString(value)) {\n return true;\n }\n\n throw new TypeError(formatError(value, errorMessage ?? \"Expected a string. Got type: %t, value: %v\"));\n}\n\n// TODO: More specific validation for common types of strings? Email address, URL, UUID, etc?\n\n/**\n * Returns true if `value` is a function (but not a class).\n */\nexport function isFunction<T = (...args: unknown[]) => unknown>(value: unknown): value is T {\n return typeof value === \"function\" && !isClass(value);\n}\n\n/**\n * Throws a TypeError unless `value` is a function.\n */\nexport function assertFunction<T = (...args: unknown[]) => unknown>(value: unknown, errorMessage?: string): value is T {\n if (isFunction(value)) {\n return true;\n }\n\n throw new TypeError(formatError(value, errorMessage ?? \"Expected a function. Got type: %t, value: %v\"));\n}\n\n/**\n * Returns true if `value` is a number.\n */\nexport function isNumber(value: unknown): value is number {\n return typeof value === \"number\" && !isNaN(value);\n}\n\n/**\n * Throws a TypeError unless `value` is a number.\n */\nexport function assertNumber(value: unknown, errorMessage?: string): value is number {\n if (isNumber(value)) {\n return true;\n }\n\n throw new TypeError(formatError(value, errorMessage ?? \"Expected a number. Got type: %t, value: %v\"));\n}\n\n/**\n * Returns true if `value` implements the Promise protocol.\n * This matches true instances of Promise as well as any object that\n * implements `next`, `catch` and `finally` methods.\n *\n * To strictly match instances of Promise, use `isInstanceOf(Promise)`.\n */\nexport function isPromise<T = unknown>(value: unknown): value is Promise<T> {\n if (value == null) return false;\n\n const obj = value as any;\n\n return obj instanceof Promise || (isFunction(obj.then) && isFunction(obj.catch) && isFunction(obj.finally));\n}\n\n/**\n * Throws a TypeError unless `value` implements the Promise protocol.\n * This matches true instances of Promise as well as any object that\n * implements `next`, `catch` and `finally` methods.\n *\n * To strictly allow only instances of Promise, use `Type.assertInstanceOf(Promise)`.\n */\nexport function assertPromise<T = unknown>(value: unknown, errorMessage?: string): value is Promise<T> {\n if (isPromise(value)) {\n return true;\n }\n\n throw new TypeError(formatError(value, errorMessage ?? \"Expected a promise. Got type: %t, value: %v\"));\n}\n\n/**\n * Returns true if `value` is a class.\n */\nexport function isClass(value: unknown): value is { new (): unknown } {\n return typeof value === \"function\" && /^\\s*class\\s+/.test(value.toString());\n}\n\n/**\n * Throws a TypeError unless `value` is a class.\n */\nexport function assertClass(value: unknown, errorMessage?: string): value is { new (): unknown } {\n if (isClass(value)) {\n return true;\n }\n\n throw new TypeError(formatError(value, errorMessage ?? \"Expected a class. Got type: %t, value: %v\"));\n}\n\n/**\n * Returns a function that takes a `value` and returns true if `value` is an instance of `constructor`.\n *\n * @param constructor - The constructor a value must be an instance of to match.\n */\nexport function isInstanceOf<T extends Function>(constructor: T): (value: unknown) => value is T;\n\n/**\n * Returns `true` if `value` is an instance of `constructor`.\n *\n * @param constructor - The constructor `value` must be an instance of.\n * @param value - A value that may be an instance of `constructor`.\n */\nexport function isInstanceOf<T extends Function>(constructor: T, value: unknown): value is T;\n\nexport function isInstanceOf<T extends Function>(...args: unknown[]) {\n const constructor = args[0] as T;\n\n const test = (value: unknown): value is T => {\n return value instanceof constructor;\n };\n\n if (args.length < 2) {\n return test;\n } else {\n return test(args[1]);\n }\n}\n\n/**\n * Returns a function that takes a `value` and throws a TypeError unless `value` is an instance of `constructor`.\n *\n * @param constructor - The constructor a value must be an instance of to match.\n */\nexport function assertInstanceOf<T extends Function>(constructor: T): (value: unknown) => value is T;\n\n/**\n * Throws a TypeError unless `value` is an instance of `constructor`.\n *\n * @param constructor - The constructor `value` must be an instance of.\n * @param value - A value that may be an instance of `constructor`.\n * @param errorMessage - A custom error message for when the assertion fails.\n */\nexport function assertInstanceOf<T extends Function>(constructor: T, value: unknown, errorMessage?: string): value is T;\n\nexport function assertInstanceOf<T extends Function>(...args: unknown[]) {\n const constructor = args[0] as T;\n const errorMessage = isString(args[2])\n ? args[2]\n : `Expected instance of ${constructor.name}. Got type: %t, value: %v`;\n\n const test = (value: unknown): value is T => {\n if (value instanceof constructor) {\n return true;\n }\n\n throw new TypeError(formatError(value, errorMessage));\n };\n\n if (args.length < 2) {\n return test;\n } else {\n return test(args[1]);\n }\n}\n\n/**\n * Returns true if `value` is a Map.\n */\nexport function isMap<K = unknown, V = unknown>(value: any): value is Map<K, V> {\n return value instanceof Map;\n}\n\n/**\n * Throws a TypeError unless `value` is a Map.\n */\nexport function assertMap<K = unknown, V = unknown>(value: any, errorMessage?: string): value is Map<K, V> {\n if (isMap(value)) {\n return true;\n }\n\n throw new TypeError(formatError(value, errorMessage ?? \"Expected a Map. Got type: %t, value: %v\"));\n}\n\n/**\n * Returns true if `value` is a Set.\n */\nexport function isSet<T = unknown>(value: any): value is Set<T> {\n return value instanceof Set;\n}\n\n/**\n * Throws a TypeError if `value` is not a Set.\n */\nexport function assertSet<T = unknown>(value: any, errorMessage?: string): value is Set<T> {\n if (isSet(value)) {\n return true;\n }\n\n throw new TypeError(formatError(value, errorMessage ?? \"Expected a Set. Got type: %t, value: %v\"));\n}\n\n/**\n * Returns true if `value` implements the Iterable protocol.\n */\nexport function isIterable<T>(value: any): value is Iterable<T> {\n if (value == null) {\n return false;\n }\n\n // Must have a [Symbol.iterator] function that returns an iterator.\n if (!isFunction(value[Symbol.iterator])) {\n return false;\n }\n\n const iterator = value[Symbol.iterator]();\n\n // Iterator must implement the iterator protocol.\n if (!isFunction(iterator.next)) {\n return false;\n }\n\n // We have to assume next() returns the correct object.\n // We can't call it to make sure because we don't want to cause side effects.\n return true;\n}\n\n/**\n * Throws a TypeError unless `value` implements the Iterable protocol.\n */\nexport function assertIterable<T>(value: any, errorMessage?: string): value is Iterable<T> {\n if (isIterable(value)) {\n return true;\n }\n\n throw new TypeError(\n formatError(\n value,\n errorMessage ?? \"Expected an object that implements the iterable protocol. Got type: %t, value: %v\"\n )\n );\n}\n\n/**\n * Returns true if `value` is a plain JavaScript object.\n */\nexport function isObject(value: unknown): value is Record<string | number | symbol, unknown> {\n return value != null && typeof value === \"object\" && !isArray(value);\n}\n\n/**\n * Throws a TypeError unless `value` is a plain JavaScript object.\n */\nexport function assertObject(value: unknown, errorMessage?: string): value is object {\n if (isObject(value)) {\n return true;\n }\n\n throw new TypeError(formatError(value, errorMessage ?? \"Expected an object. Got type: %t, value: %v\"));\n}\n\n/**\n * Returns true if `value` is equal to `null`.\n */\nexport function isNull(value: unknown): value is null {\n return value === null;\n}\n\n/**\n * Throws a TypeError unless `value` is equal to `null`.\n */\nexport function assertNull(value: unknown, errorMessage?: string): value is null {\n if (value === null) {\n return true;\n }\n\n throw new TypeError(formatError(value, errorMessage ?? \"Expected null. Got type: %t, value: %v\"));\n}\n\n/**\n * Returns true if `value` is equal to `undefined`.\n */\nexport function isUndefined(value: unknown): value is undefined {\n return value === undefined;\n}\n\n/**\n * Throws a TypeError unless `value` is equal to `undefined`.\n */\nexport function assertUndefined(value: unknown, errorMessage?: string): value is undefined {\n if (value === undefined) {\n return true;\n }\n\n throw new TypeError(formatError(value, errorMessage ?? \"Expected undefined. Got type: %t, value: %v\"));\n}\n\n/**\n * Returns true if `value` is equal to `null` or `undefined`.\n */\nexport function isEmpty(value: unknown): value is void {\n return value === null || value === undefined;\n}\n\n/**\n * Throws a TypeError unless `value` is equal to `null` or `undefined`.\n */\nexport function assertEmpty(value: unknown, errorMessage?: string): value is void {\n if (value == null) {\n return true;\n }\n\n throw new TypeError(formatError(value, errorMessage ?? \"Expected null or undefined. Got type: %t, value: %v\"));\n}\n\n/**\n * Replaces `%t` and `%v` placeholders in a message with real values.\n */\nfunction formatError(value: unknown, message: string) {\n const typeName = typeOf(value);\n\n // TODO: Pretty format value as string based on type.\n const valueString = value?.toString?.() || String(value);\n\n return message.replaceAll(\"%t\", typeName).replaceAll(\"%v\", valueString);\n}\n", "import { isObject } from \"./typeChecking.js\";\n\nfunction isPlainObject<T = { [name: string]: any }>(value: any): value is T {\n return (\n value != null &&\n typeof value === \"object\" &&\n !Array.isArray(value) &&\n Object.getPrototypeOf(value) === Object.getPrototypeOf({})\n );\n}\n\nexport function deepEqual(one: any, two: any) {\n if (one === two) {\n return true;\n }\n\n if (isPlainObject(one) && isPlainObject(two)) {\n const keysOne = Object.keys(one);\n const keysTwo = Object.keys(two);\n\n if (keysOne.length !== keysTwo.length) {\n return false;\n }\n\n for (const key in one) {\n if (!deepEqual(one[key], two[key])) {\n return false;\n }\n }\n\n return true;\n }\n\n if (Array.isArray(one) && Array.isArray(two)) {\n if (one.length !== two.length) {\n return false;\n }\n\n for (const index in one) {\n if (!deepEqual(one[index], two[index])) {\n return false;\n }\n }\n\n return true;\n }\n\n return one === two;\n}\n\n/**\n * Takes an old value and a new value. Returns a merged copy if both are objects, otherwise returns the new value.\n */\nexport function merge(one: unknown, two: unknown) {\n if (isObject(one)) {\n if (!isObject(two)) {\n return two;\n }\n\n const merged = Object.assign({}, one) as any;\n\n for (const key in two) {\n merged[key] = merge(merged[key], two[key]);\n }\n\n return merged;\n } else {\n return two;\n }\n}\n\n/**\n * Returns a new object without the specified keys.\n * If called without object, returns a function that takes an object\n * and returns a version with the original keys omitted.\n *\n * @param keys - An array of keys to omit.\n * @param object - An object to clone without the omitted keys.\n */\nexport function omit<O extends Record<any, any>>(keys: (keyof O)[], object: O): Record<any, any> {\n const process = (object: Record<any, any>) => {\n const newObject: Record<any, any> = {};\n\n for (const key in object) {\n if (!keys.includes(key)) {\n newObject[key] = object[key];\n }\n }\n\n return newObject;\n };\n\n if (object == null) {\n return process;\n }\n\n return process(object);\n}\n", "import { typeOf } from \"./typeChecking.js\";\nimport { deepEqual } from \"./utils.js\";\n\n// Symbol to mark an observed value as unobserved. Callbacks are always called once for unobserved values.\nconst UNOBSERVED = Symbol(\"Unobserved\");\n\n// Symbol to access observe method used internally by the library.\nconst OBSERVE = Symbol(\"Observe\");\n\n/*==============================*\\\n|| Types ||\n\\*==============================*/\n\n/**\n * Stops the observer that created it when called.\n */\nexport type StopFunction = () => void;\ntype ObserveMethod<T> = (callback: (currentValue: T) => void) => StopFunction;\n\ntype Value<T> = T extends Readable<infer V> ? V : T;\n\n/**\n * Extracts value types from an array of Readables.\n */\nexport type ReadableValues<T extends MaybeReadable<any>[]> = {\n [K in keyof T]: Value<T[K]>;\n};\n\nexport interface Observable<T> {\n /**\n * Receives the latest value with `callback` whenever the value changes.\n * The `previousValue` is always undefined the first time the callback is called, then the same value as the last time it was called going forward.\n */\n [OBSERVE]: ObserveMethod<T>;\n}\n\nexport interface Readable<T> extends Observable<T> {\n /**\n * Returns the current value.\n */\n get(): T;\n}\n\nexport interface Writable<T> extends Readable<T> {\n /**\n * Sets a new value.\n */\n set(value: T): void;\n\n /**\n * Passes the current value to `callback` and takes `callback`'s return value as the new value.\n */\n update(callback: (currentValue: T) => T): void;\n}\n\nexport type MaybeReadable<T> = Readable<T> | T;\n\n/*==============================*\\\n|| Utilities ||\n\\*==============================*/\n\n// function isObservable<T>(value: any): value is Observable<T> {\n// return value != null && typeof value === \"object\" && typeof value[OBSERVE] === \"function\";\n// }\n\n// State.isObservable = isObservable;\n\nexport function isReadable<T>(value: any): value is Readable<T> {\n return (\n value != null &&\n typeof value === \"object\" &&\n typeof value[OBSERVE] === \"function\" &&\n typeof value.get === \"function\"\n );\n}\n\nexport function isWritable<T>(value: any): value is Writable<T> {\n return isReadable(value) && typeof (value as any).set === \"function\" && typeof (value as any).update === \"function\";\n}\n\n/*==============================*\\\n|| $() and $$() ||\n\\*==============================*/\n\nexport function $$<T>(value: Writable<T>): Writable<T>;\nexport function $$<T>(value: Readable<T>): never; // TODO: How to throw a type error in TS before runtime?\nexport function $$<T>(value: undefined): Writable<T | undefined>;\nexport function $$<T>(): Writable<T | undefined>;\nexport function $$<T>(value: T): Writable<Value<T>>;\n\n/**\n * Creates a proxy `Writable` around an existing `Writable`.\n * The config object contains custom `get` and `set` methods.\n * All reads of this proxy goes through the `get` method\n * and all writes go through `set`.\n */\nexport function $$<Source extends Writable<any>, Value>(source: Source, config: ProxyConfig<Value>): Writable<Value>;\n\n/**\n * Creates a proxy `Writable` around an existing `Readable`.\n * The config object contains custom `get` and `set` methods.\n * All reads of this proxy goes through the `get` method\n * and all writes go through `set`.\n */\nexport function $$<Source extends Readable<any>, Value>(source: Source, config: ProxyConfig<Value>): Writable<Value>;\n\n// Same as writable()\nexport function $$(initialValue?: any, config?: any) {\n if (config) {\n return proxy(initialValue, config);\n } else {\n return writable(initialValue);\n }\n}\n\nexport function $<T>(value: Writable<T>): Readable<T>;\nexport function $<T>(value: Readable<T>): Readable<T>;\nexport function $<T>(value: undefined): Readable<T | undefined>;\nexport function $<T>(): Readable<T | undefined>;\nexport function $<T>(value: T): Readable<Value<T>>;\n\nexport function $<I, O>(state: MaybeReadable<I>, compute: (value: I) => O | Readable<O>): Readable<O>;\n\nexport function $<I extends MaybeReadable<any>[], O>(\n states: [...I],\n compute: (...currentValues: ReadableValues<I>) => O | Readable<O>,\n): Readable<O>;\n\nexport function $<I1, I2, O>(\n state1: MaybeReadable<I1>,\n state2: MaybeReadable<I2>,\n compute: (value1: I1, value2: I2) => O | Readable<O>,\n): Readable<O>;\n\nexport function $<I1, I2, I3, O>(\n state1: MaybeReadable<I1>,\n state2: MaybeReadable<I2>,\n state3: MaybeReadable<I3>,\n compute: (value1: I1, value2: I2, value3: I3) => O | Readable<O>,\n): Readable<O>;\n\nexport function $<I1, I2, I3, I4, O>(\n state1: MaybeReadable<I1>,\n state2: MaybeReadable<I2>,\n state3: MaybeReadable<I3>,\n state4: MaybeReadable<I4>,\n compute: (value1: I1, value2: I2, value3: I3, value4: I4) => O | Readable<O>,\n): Readable<O>;\n\nexport function $<I1, I2, I3, I4, I5, O>(\n state1: MaybeReadable<I1>,\n state2: MaybeReadable<I2>,\n state3: MaybeReadable<I3>,\n state4: MaybeReadable<I4>,\n state5: MaybeReadable<I5>,\n compute: (value1: I1, value2: I2, value3: I3, value4: I4, value5: I5) => O | Readable<O>,\n): Readable<O>;\n\nexport function $<I1, I2, I3, I4, I5, I6, O>(\n state1: MaybeReadable<I1>,\n state2: MaybeReadable<I2>,\n state3: MaybeReadable<I3>,\n state4: MaybeReadable<I4>,\n state5: MaybeReadable<I5>,\n state6: MaybeReadable<I6>,\n compute: (value1: I1, value2: I2, value3: I3, value4: I4, value5: I5, value6: I6) => O | Readable<O>,\n): Readable<O>;\n\nexport function $<I1, I2, I3, I4, I5, I6, I7, O>(\n state1: MaybeReadable<I1>,\n state2: MaybeReadable<I2>,\n state3: MaybeReadable<I3>,\n state4: MaybeReadable<I4>,\n state5: MaybeReadable<I5>,\n state6: MaybeReadable<I6>,\n state7: MaybeReadable<I7>,\n compute: (value1: I1, value2: I2, value3: I3, value4: I4, value5: I5, value6: I6, value7: I7) => O | Readable<O>,\n): Readable<O>;\n\nexport function $<I1, I2, I3, I4, I5, I6, I7, I8, O>(\n state1: MaybeReadable<I1>,\n state2: MaybeReadable<I2>,\n state3: MaybeReadable<I3>,\n state4: MaybeReadable<I4>,\n state5: MaybeReadable<I5>,\n state6: MaybeReadable<I6>,\n state7: MaybeReadable<I7>,\n state8: MaybeReadable<I8>,\n compute: (\n value1: I1,\n value2: I2,\n value3: I3,\n value4: I4,\n value5: I5,\n value6: I6,\n value7: I7,\n value8: I8,\n ) => O | Readable<O>,\n): Readable<O>;\n\nexport function $<I1, I2, I3, I4, I5, I6, I7, I8, I9, O>(\n state1: MaybeReadable<I1>,\n state2: MaybeReadable<I2>,\n state3: MaybeReadable<I3>,\n state4: MaybeReadable<I4>,\n state5: MaybeReadable<I5>,\n state6: MaybeReadable<I6>,\n state7: MaybeReadable<I7>,\n state8: MaybeReadable<I8>,\n state9: MaybeReadable<I9>,\n compute: (\n value1: I1,\n value2: I2,\n value3: I3,\n value4: I4,\n value5: I5,\n value6: I6,\n value7: I7,\n value8: I8,\n value9: I9,\n ) => O | Readable<O>,\n): Readable<O>;\n\nexport function $<I1, I2, I3, I4, I5, I6, I7, I8, I9, I10, O>(\n state1: MaybeReadable<I1>,\n state2: MaybeReadable<I2>,\n state3: MaybeReadable<I3>,\n state4: MaybeReadable<I4>,\n state5: MaybeReadable<I5>,\n state6: MaybeReadable<I6>,\n state7: MaybeReadable<I7>,\n state8: MaybeReadable<I8>,\n state9: MaybeReadable<I9>,\n state10: MaybeReadable<I10>,\n compute: (\n value1: I1,\n value2: I2,\n value3: I3,\n value4: I4,\n value5: I5,\n value6: I6,\n value7: I7,\n value8: I8,\n value9: I9,\n value10: I10,\n ) => O | Readable<O>,\n): Readable<O>;\n\n// Hybrid of readable() and computed() - if last arg is a function, it's computed()\nexport function $(...args: any[]) {\n if (args.length > 1) {\n const callback = args.pop() as (...args: any) => void;\n const readables = args.flat().map(readable);\n return computed(...readables, callback);\n } else {\n return readable(args[0]);\n }\n}\n\n/*==============================*\\\n|| readable() ||\n\\*==============================*/\n\nfunction readable<T>(value: Writable<T>): Readable<T>;\nfunction readable<T>(value: Readable<T>): Readable<T>;\nfunction readable<T>(value: undefined): Readable<T | undefined>;\nfunction readable<T>(): Readable<T | undefined>;\nfunction readable<T>(value: T): Readable<Value<T>>;\n\nfunction readable(value?: unknown): Readable<any> {\n // Return a proxy Readable with the value of this Writable.\n if (isWritable(value)) {\n return {\n get: value.get,\n [OBSERVE]: value[OBSERVE],\n };\n }\n\n // Return the same Readable.\n if (isReadable(value)) {\n return value;\n }\n\n // Return a new Readable.\n return {\n get: () => value,\n [OBSERVE]: (callback) => {\n callback(value); // call with current value and undefined for the previous value\n return function stop() {}; // value can never change, so this function is not implemented\n },\n };\n}\n\n/*==============================*\\\n|| computed() ||\n\\*==============================*/\n\nfunction computed(...args: any): Readable<any> {\n const compute = args.pop();\n if (typeof compute !== \"function\") {\n throw new TypeError(`Final argument must be a function. Got ${typeOf(compute)}: ${compute}`);\n }\n if (args.length < 1) {\n throw new Error(`Must pass at least one value before the callback function.`);\n }\n const readables = args as Readable<any>[];\n const observers: ((...currentValues: any[]) => void)[] = [];\n\n let stopCallbacks: StopFunction[] = [];\n let isObserving = false;\n let observedValues: any[] = [];\n let valuesChanged: boolean[] = [];\n let latestComputedValue: any = UNOBSERVED;\n\n function updateValue() {\n if (!valuesChanged.some((x) => x)) {\n // No values changed. Nothing to do. No need to recompute.\n return;\n }\n\n const computedValue = compute(...observedValues);\n\n // Skip equality check on initial subscription to guarantee\n // that observers receive an initial value, even if undefined.\n if (!deepEqual(computedValue, latestComputedValue)) {\n // const previousValue = latestComputedValue === UNOBSERVED ? undefined : latestComputedValue;\n latestComputedValue = computedValue;\n\n for (const callback of observers) {\n callback(computedValue);\n }\n }\n\n for (let i = 0; i < observedValues.length; i++) {\n valuesChanged[i] = false;\n }\n }\n\n function startObserving() {\n if (isObserving) return;\n\n for (let i = 0; i < readables.length; i++) {\n const readable = readables[i];\n\n stopCallbacks.push(\n observe(readable, (value: any) => {\n if (!deepEqual(observedValues[i], value)) {\n observedValues[i] = value;\n valuesChanged[i] = true;\n\n if (isObserving) {\n updateValue();\n }\n }\n }),\n );\n }\n\n observedValues = readables.map((x) => x.get());\n for (let i = 0; i < observedValues.length; i++) {\n valuesChanged[i] = true;\n }\n isObserving = true;\n updateValue();\n }\n\n function stopObserving() {\n isObserving = false;\n\n for (const callback of stopCallbacks) {\n callback();\n }\n stopCallbacks = [];\n }\n\n return {\n get: () => {\n if (isObserving) {\n return latestComputedValue;\n } else {\n return compute(...readables.map((x) => x.get()));\n }\n },\n [OBSERVE]: (callback) => {\n // First start observing\n if (!isObserving) {\n startObserving();\n }\n\n // Then call callback and add it to observers for future changes\n callback(latestComputedValue);\n observers.push(callback);\n\n return function stop() {\n observers.splice(observers.indexOf(callback), 1);\n\n if (observers.length === 0) {\n stopObserving();\n }\n };\n },\n };\n}\n\n/*==============================*\\\n|| writable() ||\n\\*==============================*/\n\nfunction writable<T>(value: Writable<T>): Writable<T>;\nfunction writable<T>(value: Readable<T>): never; // TODO: How to throw a type error in TS before runtime?\nfunction writable<T>(value: undefined): Writable<T | undefined>;\nfunction writable<T>(): Writable<T | undefined>;\nfunction writable<T>(value: T): Writable<Value<T>>;\n\nfunction writable(value?: unknown): Writable<any> {\n // Return the same Writable.\n if (isWritable(value)) {\n return value;\n }\n\n // Throw error; can't add write access to a Readable.\n if (isReadable(value)) {\n throw new TypeError(`Failed to convert Readable into a Writable; can't add write access to a read-only value.`);\n }\n\n const observers: ((currentValue: any, previousValue?: any) => void)[] = [];\n\n let currentValue = value;\n\n // Return a new Writable.\n return {\n // ----- Readable ----- //\n\n get: () => currentValue,\n [OBSERVE]: (callback) => {\n observers.push(callback); // add observer\n\n function stop() {\n observers.splice(observers.indexOf(callback), 1);\n }\n\n callback(currentValue); // call with current value\n\n // return function to remove observer\n return stop;\n },\n\n // ----- Writable ----- //\n\n set: (newValue) => {\n if (!deepEqual(currentValue, newValue)) {\n const previousValue = currentValue;\n currentValue = newValue;\n for (const callback of observers) {\n callback(currentValue, previousValue);\n }\n }\n },\n update: (callback) => {\n const newValue = callback(currentValue);\n if (!deepEqual(currentValue, newValue)) {\n const previousValue = currentValue;\n currentValue = newValue;\n for (const callback of observers) {\n callback(currentValue, previousValue);\n }\n }\n },\n };\n}\n\n/*==============================*\\\n|| proxy() ||\n\\*==============================*/\n\ninterface ProxyConfig<Value> {\n get(): Value;\n set(value: Value): void;\n}\n\n/**\n * Creates a proxy `Writable` around an existing `Writable`.\n * The config object takes custom `get` and `set` methods.\n * All reads of this proxy goes through the `get` method\n * and all writes go through `set`.\n */\nfunction proxy<Source extends Writable<any>, Value>(source: Source, config: ProxyConfig<Value>): Writable<Value>;\n\n/**\n * Creates a proxy `Writable` around an existing `Readable`.\n * The config object takes custom `get` and `set` methods.\n * All reads of this proxy goes through the `get` method\n * and all writes go through `set`.\n */\nfunction proxy<Source extends Readable<any>, Value>(source: Source, config: ProxyConfig<Value>): Writable<Value>;\n\nfunction proxy<Source, Value>(source: Source, config: ProxyConfig<Value>): Writable<Value> {\n // Throw error; can't add write access to a Readable.\n if (!isReadable(source)) {\n throw new TypeError(`Proxy source must be a Readable.`);\n }\n\n // const observers: ((currentValue: any, previousValue?: any) => void)[] = [];\n // const currentValue = () => config.get();\n\n // Return a new Writable.\n return {\n // ----- Readable ----- //\n\n get: () => config.get(),\n [OBSERVE]: (callback) => {\n let lastComputedValue: any = UNOBSERVED;\n\n return observe(source, (_) => {\n const computedValue = config.get();\n\n if (!deepEqual(computedValue, lastComputedValue)) {\n // const previousValue = lastComputedValue === UNOBSERVED ? undefined : lastComputedValue;\n callback(computedValue);\n lastComputedValue = computedValue;\n }\n });\n },\n\n // ----- Writable ----- //\n\n set: (value) => {\n config.set(value);\n },\n update: (callback) => {\n config.set(callback(config.get()));\n },\n };\n}\n\n/*==============================*\\\n|| observe() ||\n\\*==============================*/\n\n/**\n * Observes a readable value. Calls `callback` each time the value changes.\n * Returns a function to stop observing changes. This MUST be called when you are done\n * with this observer to prevent memory leaks.\n */\nexport function observe<T>(state: Readable<T>, callback: (currentValue: T, previousValue: T) => void): StopFunction;\n\n/**\n * Observes a set of readable values.\n * Calls `callback` with each value in the same order as `readables` each time any of their values change.\n * Returns a function to stop observing changes. This MUST be called when you are done\n * with this observer to prevent memory leaks.\n */\nexport function observe<T extends MaybeReadable<any>[]>(\n states: [...T],\n callback: (currentValues: ReadableValues<T>, previousValues: ReadableValues<T>) => void,\n): StopFunction;\n\nexport function observe<I1, I2>(\n state1: MaybeReadable<I1>,\n state2: MaybeReadable<I2>,\n callback: (value1: I1, value2: I2) => void,\n): StopFunction;\n\nexport function observe<I1, I2, I3>(\n state1: MaybeReadable<I1>,\n state2: MaybeReadable<I2>,\n state3: MaybeReadable<I3>,\n callback: (value1: I1, value2: I2, value3: I3) => void,\n): StopFunction;\n\nexport function observe<I1, I2, I3, I4>(\n state1: MaybeReadable<I1>,\n state2: MaybeReadable<I2>,\n state3: MaybeReadable<I3>,\n state4: MaybeReadable<I4>,\n callback: (value1: I1, value2: I2, value3: I3, value4: I4) => void,\n): StopFunction;\n\nexport function observe<I1, I2, I3, I4, I5>(\n state1: MaybeReadable<I1>,\n state2: MaybeReadable<I2>,\n state3: MaybeReadable<I3>,\n state4: MaybeReadable<I4>,\n state5: MaybeReadable<I5>,\n callback: (value1: I1, value2: I2, value3: I3, value4: I4, value5: I5) => void,\n): StopFunction;\n\nexport function observe<I1, I2, I3, I4, I5, I6>(\n state1: MaybeReadable<I1>,\n state2: MaybeReadable<I2>,\n state3: MaybeReadable<I3>,\n state4: MaybeReadable<I4>,\n state5: MaybeReadable<I5>,\n state6: MaybeReadable<I6>,\n callback: (value1: I1, value2: I2, value3: I3, value4: I4, value5: I5, value6: I6) => void,\n): StopFunction;\n\nexport function observe<I1, I2, I3, I4, I5, I6, I7>(\n state1: MaybeReadable<I1>,\n state2: MaybeReadable<I2>,\n state3: MaybeReadable<I3>,\n state4: MaybeReadable<I4>,\n state5: MaybeReadable<I5>,\n state6: MaybeReadable<I6>,\n state7: MaybeReadable<I7>,\n callback: (value1: I1, value2: I2, value3: I3, value4: I4, value5: I5, value6: I6, value7: I7) => void,\n): StopFunction;\n\nexport function observe<I1, I2, I3, I4, I5, I6, I7, I8>(\n state1: MaybeReadable<I1>,\n state2: MaybeReadable<I2>,\n state3: MaybeReadable<I3>,\n state4: MaybeReadable<I4>,\n state5: MaybeReadable<I5>,\n state6: MaybeReadable<I6>,\n state7: MaybeReadable<I7>,\n state8: MaybeReadable<I8>,\n callback: (value1: I1, value2: I2, value3: I3, value4: I4, value5: I5, value6: I6, value7: I7, value8: I8) => void,\n): StopFunction;\n\nexport function observe<I1, I2, I3, I4, I5, I6, I7, I8, I9>(\n state1: MaybeReadable<I1>,\n state2: MaybeReadable<I2>,\n state3: MaybeReadable<I3>,\n state4: MaybeReadable<I4>,\n state5: MaybeReadable<I5>,\n state6: MaybeReadable<I6>,\n state7: MaybeReadable<I7>,\n state8: MaybeReadable<I8>,\n state9: MaybeReadable<I9>,\n callback: (\n value1: I1,\n value2: I2,\n value3: I3,\n value4: I4,\n value5: I5,\n value6: I6,\n value7: I7,\n value8: I8,\n value9: I9,\n ) => void,\n): StopFunction;\n\nexport function observe<I1, I2, I3, I4, I5, I6, I7, I8, I9, I10>(\n state1: MaybeReadable<I1>,\n state2: MaybeReadable<I2>,\n state3: MaybeReadable<I3>,\n state4: MaybeReadable<I4>,\n state5: MaybeReadable<I5>,\n state6: MaybeReadable<I6>,\n state7: MaybeReadable<I7>,\n state8: MaybeReadable<I8>,\n state9: MaybeReadable<I9>,\n state10: MaybeReadable<I10>,\n callback: (\n value1: I1,\n value2: I2,\n value3: I3,\n value4: I4,\n value5: I5,\n value6: I6,\n value7: I7,\n value8: I8,\n value9: I9,\n value10: I10,\n ) => void,\n): StopFunction;\n\nexport function observe(...args: any[]): StopFunction {\n const callback = args.pop() as (...args: any) => void;\n const readables = args.flat().map(readable);\n\n if (readables.length === 0) {\n throw new TypeError(`Expected at least one readable.`);\n }\n\n if (readables.length > 1) {\n return computed(...readables, callback)[OBSERVE](() => null);\n } else {\n return readables[0][OBSERVE](callback);\n }\n}\n\n/*==============================*\\\n|| unwrap() ||\n\\*==============================*/\n\nexport function unwrap<T>(value: MaybeReadable<T>): T;\n\nexport function unwrap(value: any) {\n if (isReadable(value)) {\n return value.get();\n }\n\n return value;\n}\n", "import { type AppContext, type ElementContext } from \"../app.js\";\nimport { renderMarkupToDOM, toMarkup, type DOMHandle, type Markup } from \"../markup.js\";\nimport { observe, type Readable, type StopFunction } from \"../state.js\";\nimport { type Renderable } from \"../types.js\";\n\nexport interface ConditionalConfig {\n $predicate: Readable<any>;\n thenContent?: Renderable;\n elseContent?: Renderable;\n appContext: AppContext;\n elementContext: ElementContext;\n}\n\nexport class Conditional implements DOMHandle {\n node: Node;\n endNode: Node;\n $predicate: Readable<any>;\n stopCallback?: StopFunction;\n thenContent?: Markup[];\n elseContent?: Markup[];\n connectedContent: DOMHandle[] = [];\n appContext: AppContext;\n elementContext: ElementContext;\n\n constructor(config: ConditionalConfig) {\n this.$predicate = config.$predicate;\n this.thenContent = config.thenContent ? toMarkup(config.thenContent) : undefined;\n this.elseContent = config.elseContent ? toMarkup(config.elseContent) : undefined;\n this.appContext = config.appContext;\n this.elementContext = config.elementContext;\n\n if (this.appContext.mode === \"development\") {\n this.node = document.createComment(\"Conditional\");\n this.endNode = document.createComment(\"/Conditional\");\n } else {\n this.node = document.createTextNode(\"\");\n this.endNode = document.createTextNode(\"\");\n }\n }\n\n get connected() {\n return this.node.parentNode != null;\n }\n\n connect(parent: Node, after?: Node | undefined): void {\n if (!this.connected) {\n parent.insertBefore(this.node, after?.nextSibling ?? null);\n if (this.appContext.mode === \"development\") {\n parent.insertBefore(this.endNode, this.node.nextSibling);\n }\n\n this.stopCallback = observe(this.$predicate, (value) => {\n this.update(value);\n });\n }\n }\n\n disconnect(): void {\n if (this.stopCallback) {\n this.stopCallback();\n this.stopCallback = undefined;\n }\n\n for (const handle of this.connectedContent) {\n handle.disconnect();\n }\n this.connectedContent = [];\n\n if (this.connected) {\n this.node.parentNode?.removeChild(this.node);\n this.endNode.parentNode?.removeChild(this.endNode);\n }\n }\n\n update(value: any) {\n for (const handle of this.connectedContent) {\n handle.disconnect();\n }\n this.connectedContent = [];\n\n if (this.node.parentNode == null) {\n return;\n }\n\n if (value && this.thenContent) {\n this.connectedContent = renderMarkupToDOM(this.thenContent, this);\n } else if (!value && this.elseContent) {\n this.connectedContent = renderMarkupToDOM(this.elseContent, this);\n }\n\n for (let i = 0; i < this.connectedContent.length; i++) {\n const handle = this.connectedContent[i];\n const previous = this.connectedContent[i - 1]?.node ?? this.node;\n handle.connect(this.node.parentNode, previous);\n }\n\n if (this.appContext.mode === \"development\") {\n this.node.textContent = `Conditional (${value ? \"truthy\" : \"falsy\"})`;\n }\n }\n\n async setChildren(children: DOMHandle[]): Promise<void> {}\n}\n", "export { urlAlphabet } from './url-alphabet/index.js'\nexport let random = bytes => crypto.getRandomValues(new Uint8Array(bytes))\nexport let customRandom = (alphabet, defaultSize, getRandom) => {\n let mask = (2 << (Math.log(alphabet.length - 1) / Math.LN2)) - 1\n let step = -~((1.6 * mask * defaultSize) / alphabet.length)\n return (size = defaultSize) => {\n let id = ''\n while (true) {\n let bytes = getRandom(step)\n let j = step\n while (j--) {\n id += alphabet[bytes[j] & mask] || ''\n if (id.length === size) return id\n }\n }\n }\n}\nexport let customAlphabet = (alphabet, size = 21) =>\n customRandom(alphabet, size, random)\nexport let nanoid = (size = 21) =>\n crypto.getRandomValues(new Uint8Array(size)).reduce((id, byte) => {\n byte &= 63\n if (byte < 36) {\n id += byte.toString(36)\n } else if (byte < 62) {\n id += (byte - 26).toString(36).toUpperCase()\n } else if (byte > 62) {\n id += '-'\n } else {\n id += '_'\n }\n return id\n }, '')\n", "import { nanoid } from \"nanoid\";\nimport { type AppContext, type ElementContext } from \"../app.js\";\nimport { renderMarkupToDOM, type DOMHandle, type Markup } from \"../markup.js\";\nimport { isReadable, isWritable, observe, type Readable, type StopFunction } from \"../state.js\";\nimport { isFunction, isNumber, isObject, isString } from \"../typeChecking.js\";\nimport { BuiltInStores } from \"../types.js\";\nimport { omit } from \"../utils.js\";\n\n//const eventHandlerProps = Object.values(eventPropsToEventNames).map((event) => \"on\" + event);\nconst isCamelCaseEventName = (key: string) => /^on[A-Z]/.test(key);\n\ntype HTMLOptions = {\n appContext: AppContext;\n elementContext: ElementContext;\n tag: string;\n props?: any;\n children?: Markup[];\n};\n\nexport class HTML implements DOMHandle {\n node;\n props: Record<string, any>;\n children: DOMHandle[];\n stopCallbacks: StopFunction[] = [];\n appContext;\n elementContext;\n uniqueId = nanoid();\n\n // Prevents 'onClickOutside' handlers from firing in the same cycle in which the element is connected.\n canClickAway = false;\n\n get connected() {\n return this.node.parentNode != null;\n }\n\n constructor({ tag, props, children, appContext, elementContext }: HTMLOptions) {\n elementContext = { ...elementContext };\n\n // This and all nested views will be created as SVG elements.\n if (tag.toLowerCase() === \"svg\") {\n elementContext.isSVG = true;\n }\n\n // Create node with the appropriate constructor.\n if (elementContext.isSVG) {\n this.node = document.createElementNS(\"http://www.w3.org/2000/svg\", tag);\n } else {\n this.node = document.createElement(tag);\n }\n\n // Add unique ID to attributes for debugging purposes.\n if (appContext.mode === \"development\") {\n this.node.dataset.uniqueId = this.uniqueId;\n }\n\n // Set ref if present. Refs can be a Ref object or a function that receives the node.\n if (props.ref) {\n if (isWritable(props.ref)) {\n props.ref.set(this.node);\n } else if (isFunction(props.ref)) {\n props.ref(this.node);\n } else {\n throw new Error(\"Expected an instance of Ref. Got: \" + props.ref);\n }\n }\n\n this.props = {\n ...omit([\"ref\", \"class\", \"className\"], props),\n class: props.className ?? props.class,\n };\n this.children = children ? renderMarkupToDOM(children, { appContext, elementContext }) : [];\n\n this.appContext = appContext;\n this.elementContext = elementContext;\n }\n\n connect(parent: Node, after?: Node) {\n if (parent == null) {\n throw new Error(`HTML element requires a parent element as the first argument to connect. Got: ${parent}`);\n }\n\n if (!this.connected) {\n for (const child of this.children) {\n child.connect(this.node);\n }\n\n this.applyProps(this.node, this.props);\n if (this.props.style) this.applyStyles(this.node, this.props.style, this.stopCallbacks);\n if (this.props.class) this.applyClasses(this.node, this.props.class, this.stopCallbacks);\n }\n\n parent.insertBefore(this.node, after?.nextSibling ?? null);\n\n setTimeout(() => {\n this.canClickAway = true;\n }, 0);\n }\n\n disconnect() {\n if (this.connected) {\n for (const child of this.children) {\n child.disconnect();\n }\n\n this.node.parentNode?.removeChild(this.node);\n\n this.canClickAway = false;\n\n for (const stop of this.stopCallbacks) {\n stop();\n }\n this.stopCallbacks = [];\n }\n }\n\n setChildren(next: DOMHandle[]) {\n const current = this.children;\n const patched: DOMHandle[] = [];\n const length = Math.max(current.length, next.length);\n\n for (let i = 0; i < length; i++) {\n if (!current[i] && next[i]) {\n // item was added\n patched[i] = next[i];\n patched[i].connect(this.node, patched[i - 1]?.node);\n } else if (current[i] && !next[i]) {\n // item was removed\n current[i].disconnect();\n } else if (current[i] != next[i]) {\n // item was replaced\n patched[i] = next[i];\n current[i].disconnect();\n patched[i].connect(this.node, patched[i - 1]?.node);\n }\n }\n\n this.children = patched;\n }\n\n getUpdateKey(type: string, value: string | number) {\n return `${this.uniqueId}:${type}:${value}`;\n }\n\n applyProps(element: HTMLElement | SVGElement, props: Record<string, unknown>) {\n const render = this.appContext.stores.get(\"render\")!.instance?.exports as BuiltInStores[\"render\"];\n\n const attachProp = <T>(value: Readable<T> | T, callback: (value: T) => void, updateKey: string) => {\n if (isReadable(value)) {\n this.stopCallbacks.push(\n observe(value, (value) => {\n render.update(() => {\n callback(value);\n }, updateKey);\n }),\n );\n } else {\n render.update(() => {\n callback(value);\n }, updateKey);\n }\n };\n\n for (const key in props) {\n const value = props[key];\n\n if (key === \"attributes\") {\n const values = value as Record<string, any>;\n // Set attributes directly without mapping props\n for (const name in values) {\n attachProp(\n values[name],\n (current) => {\n if (current == null) {\n (element as any).removeAttribute(name);\n } else {\n (element as any).setAttribute(name, String(current));\n }\n },\n this.getUpdateKey(\"attr\", name),\n );\n }\n } else if (key === \"eventListeners\") {\n const values = value as Record<string, any>;\n\n for (const name in values) {\n const listener: (e: Event) => void = isReadable<(e: Event) => void>(value)\n ? (e: Event) => value.get()(e)\n : (value as (e: Event) => void);\n\n element.addEventListener(name, listener);\n\n this.stopCallbacks.push(() => {\n element.removeEventListener(name, listener);\n });\n }\n } else if (key === \"$$value\") {\n if (!isWritable(value)) {\n throw new TypeError(`$$value property must be a Writable. Got: ${value} (${typeof value})`);\n }\n\n attachProp(\n value,\n (current) => {\n (element as any).value = String(current);\n },\n this.getUpdateKey(\"prop\", \"value\"),\n );\n\n const listener: EventListener = (e) => {\n const updated = toTypeOf(value.get(), (e.currentTarget as HTMLInputElement).value);\n value.set(updated);\n };\n\n element.addEventListener(\"input\", listener);\n\n this.stopCallbacks.push(() => {\n element.removeEventListener(\"input\", listener);\n });\n } else if (key === \"onClickOutside\" || key === \"onclickoutside\") {\n const listener = (e: Event) => {\n if (this.canClickAway && !element.contains(e.target as any)) {\n if (isReadable<(e: Event) => void>(value)) {\n value.get()(e);\n } else {\n (value as (e: Event) => void)(e);\n }\n }\n };\n\n const options = { capture: true };\n\n window.addEventListener(\"click\", listener, options);\n\n this.stopCallbacks.push(() => {\n window.removeEventListener(\"click\", listener, options);\n });\n } else if (isCamelCaseEventName(key)) {\n const eventName = key.slice(2).toLowerCase();\n\n const listener: (e: Event) => void = isReadable<(e: Event) => void>(value)\n ? (e: Event) => value.get()(e)\n : (value as (e: Event) => void);\n\n element.addEventListener(eventName, listener);\n\n this.stopCallbacks.push(() => {\n element.removeEventListener(eventName, listener);\n });\n } else if (key.includes(\"-\")) {\n // Names with dashes in them are not valid prop names, so they are treated as attributes.\n attachProp(\n value,\n (current) => {\n if (current == null) {\n element.removeAttribute(key);\n } else {\n element.setAttribute(key, String(current));\n }\n },\n this.getUpdateKey(\"attr\", key),\n );\n } else if (!privateProps.includes(key)) {\n if (this.elementContext.isSVG) {\n attachProp(\n value,\n (current) => {\n if (current != null) {\n element.setAttribute(key, String(props[key]));\n } else {\n element.removeAttribute(key);\n }\n },\n this.getUpdateKey(\"attr\", key),\n );\n } else {\n switch (key) {\n case \"contentEditable\":\n case \"value\":\n attachProp(\n value,\n (current) => {\n (element as any)[key] = String(current);\n },\n this.getUpdateKey(\"prop\", key),\n );\n break;\n\n case \"for\":\n attachProp(\n value,\n (current) => {\n (element as any).htmlFor = current;\n },\n this.getUpdateKey(\"prop\", \"htmlFor\"),\n );\n break;\n\n case \"checked\":\n attachProp(\n value,\n (current) => {\n (element as any).checked = current;\n\n // Set attribute also or styles don't take effect.\n if (current) {\n element.setAttribute(\"checked\", \"\");\n } else {\n element.removeAttribute(\"checked\");\n }\n },\n this.getUpdateKey(\"prop\", \"checked\"),\n );\n break;\n\n // Attribute-aliased props\n case \"exportParts\":\n case \"part\":\n case \"translate\":\n case \"title\": {\n const _key = key.toLowerCase();\n attachProp(\n value,\n (current) => {\n if (current == undefined) {\n element.removeAttribute(_key);\n } else {\n element.setAttribute(_key, String(current));\n }\n },\n this.getUpdateKey(\"attr\", _key),\n );\n break;\n }\n\n case \"autocomplete\":\n case \"autocapitalize\":\n attachProp(\n value,\n (current) => {\n if (typeof current === \"string\") {\n (element as any).autocomplete = current;\n } else if (current) {\n (element as any).autocomplete = \"on\";\n } else {\n (element as any).autocomplete = \"off\";\n }\n },\n this.getUpdateKey(\"prop\", key),\n );\n break;\n\n default: {\n attachProp(\n value,\n (current) => {\n (element as any)[key] = current;\n },\n this.getUpdateKey(\"prop\", key),\n );\n break;\n }\n }\n }\n }\n }\n }\n\n applyStyles(element: HTMLElement | SVGElement, styles: string | Record<string, any>, stopCallbacks: StopFunction[]) {\n const render = this.appContext.stores.get(\"render\")!.instance?.exports as BuiltInStores[\"render\"];\n const propStopCallbacks: StopFunction[] = [];\n\n if (styles == undefined) {\n element.style.cssText = \"\";\n } else if (typeof styles === \"string\") {\n element.style.cssText = styles;\n } else if (isReadable<object>(styles)) {\n let unapply: () => void;\n\n const stop = observe(styles, (current) => {\n render.update(\n () => {\n if (isFunction(unapply)) {\n unapply();\n }\n element.style.cssText = \"\";\n unapply = this.applyStyles(element, current, stopCallbacks);\n },\n this.getUpdateKey(\"styles\", \"*\"),\n );\n });\n\n stopCallbacks.push(stop);\n propStopCallbacks.push(stop);\n } else if (isObject(styles)) {\n styles = styles as Record<string, any>;\n\n for (const key in styles) {\n const value = styles[key];\n\n // Set style property or attribute.\n const setProperty = key.startsWith(\"--\")\n ? (key: string, value: string | null) =>\n value == null ? element.style.removeProperty(key) : element.style.setProperty(key, value)\n : (key: string, value: string | null) => (element.style[key as any] = value ?? \"\");\n\n if (isReadable<any>(value)) {\n const stop = observe(value, (current) => {\n render.update(\n () => {\n if (current != null) {\n setProperty(key, current);\n } else {\n element.style.removeProperty(key);\n }\n },\n this.getUpdateKey(\"style\", key),\n );\n });\n\n stopCallbacks.push(stop);\n propStopCallbacks.push(stop);\n } else if (isString(value)) {\n setProperty(key, value);\n } else if (isNumber(value)) {\n setProperty(key, String(value));\n } else {\n throw new TypeError(`Style properties should be strings, $states or numbers. Got (${key}: ${value})`);\n }\n }\n } else {\n throw new TypeError(`Expected style property to be a string, $state, or object. Got: ${styles}`);\n }\n\n return function unapply() {\n for (const stop of propStopCallbacks) {\n stop();\n stopCallbacks.splice(stopCallbacks.indexOf(stop), 1);\n }\n };\n }\n\n applyClasses(element: HTMLElement | SVGElement, classes: unknown, stopCallbacks: StopFunction[]) {\n const render = this.appContext.stores.get(\"render\")!.instance?.exports as BuiltInStores[\"render\"];\n const classStopCallbacks: StopFunction[] = [];\n\n if (isReadable(classes)) {\n let unapply: () => void;\n\n const stop = observe(classes, (current) => {\n render.update(\n () => {\n if (isFunction(unapply)) {\n unapply();\n }\n element.removeAttribute(\"class\");\n unapply = this.applyClasses(element, current, stopCallbacks);\n },\n this.getUpdateKey(\"attr\", \"class\"),\n );\n });\n\n stopCallbacks.push(stop);\n classStopCallbacks.push(stop);\n } else {\n const mapped = getClassMap(classes);\n\n for (const name in mapped) {\n const value = mapped[name];\n\n if (isReadable(value)) {\n const stop = observe(value, (current) => {\n render.update(() => {\n if (current) {\n element.classList.add(name);\n } else {\n element.classList.remove(name);\n }\n }); // NOTE: Not keyed; all update callbacks must run to apply all classes.\n });\n\n stopCallbacks.push(stop);\n classStopCallbacks.push(stop);\n } else if (value) {\n element.classList.add(name);\n }\n }\n }\n\n return function unapply() {\n for (const stop of classStopCallbacks) {\n stop();\n stopCallbacks.splice(stopCallbacks.indexOf(stop), 1);\n }\n };\n }\n}\n\nfunction getClassMap(classes: unknown) {\n let mapped: Record<string, boolean> = {};\n\n if (isString(classes)) {\n // Support multiple classes in one string like HTML.\n const names = classes.split(\" \");\n for (const name of names) {\n mapped[name] = true;\n }\n } else if (isObject(classes)) {\n Object.assign(mapped, classes);\n } else if (Array.isArray(classes)) {\n Array.from(classes)\n .filter((item) => item != null)\n .forEach((item) => {\n Object.assign(mapped, getClassMap(item));\n });\n }\n\n return mapped;\n}\n\n/**\n * Attempts to convert `source` to the same type as `target`.\n * Returns `source` as-is if conversion is not possible.\n */\nfunction toTypeOf<T>(target: T, source: unknown): T | unknown {\n const type = typeof target;\n\n if (type === \"string\") {\n return String(source);\n }\n\n if (type === \"number\") {\n return Number(source);\n }\n\n if (type === \"boolean\") {\n return Boolean(source);\n }\n\n return source;\n}\n\n// Attributes in this list will not be forwarded to the DOM node.\nconst privateProps = [\"ref\", \"children\", \"class\", \"style\", \"data\"];\n", "import { type AppContext, type ElementContext } from \"../app.js\";\nimport {\n getRenderHandle,\n isDOMHandle,\n isMarkup,\n isRenderable,\n renderMarkupToDOM,\n toMarkup,\n type DOMHandle,\n} from \"../markup.js\";\nimport { observe, type Readable, type StopFunction } from \"../state.js\";\nimport { typeOf } from \"../typeChecking.js\";\nimport type { Renderable } from \"../types.js\";\n\ninterface ObserverOptions {\n appContext: AppContext;\n elementContext: ElementContext;\n readables: Readable<any>[];\n renderFn: (...values: any) => Renderable;\n}\n\n/**\n * Displays dynamic children without a parent element.\n */\nexport class Observer implements DOMHandle {\n node: Node;\n endNode: Node;\n connectedViews: DOMHandle[] = [];\n renderFn: (...values: any) => Renderable;\n appContext;\n elementContext;\n observerControls;\n\n get connected() {\n return this.node.parentNode != null;\n }\n\n constructor({ readables, renderFn, appContext, elementContext }: ObserverOptions) {\n this.appContext = appContext;\n this.elementContext = elementContext;\n this.renderFn = renderFn;\n\n this.node = document.createComment(\"Observer\");\n this.endNode = document.createComment(\"/Observer\");\n\n let _stop: StopFunction | undefined;\n\n this.observerControls = {\n start: () => {\n if (_stop != null) return;\n\n _stop = observe(readables, (...values) => {\n const rendered = this.renderFn(...values);\n\n if (!isRenderable(rendered)) {\n console.error(rendered);\n throw new TypeError(\n `Observer received invalid value to render. Got type: ${typeOf(rendered)}, value: ${rendered}`\n );\n }\n\n if (Array.isArray(rendered)) {\n this.update(...rendered);\n } else {\n this.update(rendered);\n }\n });\n },\n stop: () => {\n if (_stop == null) return;\n\n _stop();\n _stop = undefined;\n },\n };\n }\n\n connect(parent: Node, after?: Node) {\n if (!this.connected) {\n parent.insertBefore(this.node, after?.nextSibling ?? null);\n this.observerControls.start();\n }\n }\n\n disconnect() {\n this.observerControls.stop();\n\n if (this.connected) {\n this.cleanup();\n this.node.parentNode?.removeChild(this.node);\n }\n }\n\n async setChildren() {\n console.warn(\"setChildren is not implemented for Dynamic\");\n }\n\n cleanup() {\n while (this.connectedViews.length > 0) {\n this.connectedViews.pop()?.disconnect();\n }\n }\n\n update(...children: Renderable[]) {\n this.cleanup();\n\n if (children == null || !this.connected) {\n return;\n }\n\n const handles: DOMHandle[] = children.map((c) => {\n if (isDOMHandle(c)) {\n return c;\n } else if (isMarkup(c)) {\n return getRenderHandle(renderMarkupToDOM(c, this));\n } else {\n return getRenderHandle(renderMarkupToDOM(toMarkup(c), this));\n }\n });\n\n for (const handle of handles) {\n const previous = this.connectedViews.at(-1)?.node || this.node;\n\n handle.connect(this.node.parentNode!, previous);\n\n this.connectedViews.push(handle);\n }\n\n if (this.appContext.mode === \"development\") {\n const lastNode = this.connectedViews.at(-1)?.node;\n if (this.endNode.previousSibling !== lastNode) {\n this.node.parentNode!.insertBefore(this.endNode, lastNode?.nextSibling ?? null);\n }\n }\n }\n}\n", "import { type AppContext, type ElementContext } from \"../app.js\";\nimport { type DOMHandle } from \"../markup.js\";\nimport { observe, type Readable, type StopFunction } from \"../state.js\";\n\nexport interface OutletConfig {\n $children: Readable<DOMHandle[]>;\n appContext: AppContext;\n elementContext: ElementContext;\n}\n\n/**\n * Manages an array of DOMHandles.\n */\nexport class Outlet implements DOMHandle {\n node: Node;\n endNode: Node;\n $children: Readable<DOMHandle[]>;\n stopCallback?: StopFunction;\n connectedChildren: DOMHandle[] = [];\n appContext: AppContext;\n elementContext: ElementContext;\n\n constructor(config: OutletConfig) {\n this.$children = config.$children;\n this.appContext = config.appContext;\n this.elementContext = config.elementContext;\n\n if (this.appContext.mode === \"development\") {\n this.node = document.createComment(\"Outlet\");\n this.endNode = document.createComment(\"/Outlet\");\n } else {\n this.node = document.createTextNode(\"\");\n this.endNode = document.createTextNode(\"\");\n }\n }\n\n get connected() {\n return this.node?.parentNode != null;\n }\n\n connect(parent: Node, after?: Node | undefined) {\n if (!this.connected) {\n parent.insertBefore(this.node, after?.nextSibling ?? null);\n\n this.stopCallback = observe(this.$children, (children) => {\n this.update(children);\n });\n }\n }\n\n disconnect() {\n if (this.stopCallback) {\n this.stopCallback();\n this.stopCallback = undefined;\n }\n\n if (this.connected) {\n for (const child of this.connectedChildren) {\n child.disconnect();\n }\n this.connectedChildren = [];\n this.endNode.parentNode?.removeChild(this.endNode);\n }\n }\n\n update(newChildren: DOMHandle[]) {\n for (const child of this.connectedChildren) {\n child.disconnect();\n }\n\n for (let i = 0; i < newChildren.length; i++) {\n const child = newChildren[i];\n const previous = i > 0 ? newChildren[i] : undefined;\n child.connect(this.node.parentElement!, previous?.node);\n }\n\n this.connectedChildren = newChildren;\n\n if (this.appContext.mode === \"development\") {\n this.node.textContent = `Outlet (${newChildren.length} ${newChildren.length === 1 ? \"child\" : \"children\"})`;\n this.node.parentElement?.insertBefore(\n this.endNode,\n this.connectedChildren[this.connectedChildren.length - 1]?.node?.nextSibling ?? null,\n );\n }\n }\n\n setChildren(children: DOMHandle[]) {\n throw new Error(`setChildren is not supported on Outlet`);\n }\n}\n", "import { type AppContext, type ElementContext } from \"../app.js\";\nimport { getRenderHandle, isDOMHandle, isMarkup, renderMarkupToDOM, toMarkup, type DOMHandle } from \"../markup.js\";\nimport { type Renderable } from \"../types.js\";\n\ninterface PortalConfig {\n content: Renderable;\n parent: Node;\n appContext: AppContext;\n elementContext: ElementContext;\n}\n\n/**\n * Renders content into a specified parent node.\n */\nexport class Portal implements DOMHandle {\n config: PortalConfig;\n handle?: DOMHandle;\n\n get connected() {\n if (!this.handle) {\n return false;\n }\n return this.handle.connected;\n }\n\n constructor(config: PortalConfig) {\n this.config = config;\n }\n\n connect(_parent: Node, _after?: Node) {\n const { content, parent } = this.config;\n\n if (isDOMHandle(content)) {\n this.handle = content;\n } else if (isMarkup(content)) {\n this.handle = getRenderHandle(renderMarkupToDOM(content, this.config));\n } else {\n this.handle = getRenderHandle(renderMarkupToDOM(toMarkup(content), this.config));\n }\n\n this.handle.connect(parent);\n }\n\n disconnect() {\n if (this.handle?.connected) {\n this.handle.disconnect();\n }\n }\n\n setChildren(children: DOMHandle[]) {\n this.handle?.setChildren(children);\n }\n}\n", "import { isArrayOf, typeOf } from \"./typeChecking.js\";\nimport { nanoid } from \"nanoid\";\nimport { type AppContext, type ElementContext } from \"./app.js\";\nimport { type DebugChannel } from \"./classes/DebugHub.js\";\nimport { getRenderHandle, isMarkup, m, renderMarkupToDOM, type DOMHandle, type Markup } from \"./markup.js\";\nimport { $, $$, isReadable, observe, type Readable, type ReadableValues, type MaybeReadable } from \"./state.js\";\nimport { type Store } from \"./store.js\";\nimport type { BuiltInStores } from \"./types.js\";\n\n/*=====================================*\\\n|| Types ||\n\\*=====================================*/\n\n/**\n * Any valid value that a View can return.\n */\nexport type ViewResult = Node | Readable<any> | Markup | Markup[] | null;\n\nexport type View<P> = (props: P, context: ViewContext) => ViewResult;\n\nexport interface ViewContext extends DebugChannel {\n /**\n * A string ID unique to this view.\n */\n readonly uniqueId: string;\n\n /**\n * Returns the shared instance of `store`.\n */\n getStore<T extends Store<any, any>>(store: T): ReturnType<T>;\n\n /**\n * Returns the shared instance of a built-in store.\n */\n getStore<N extends keyof BuiltInStores>(name: N): BuiltInStores[N];\n\n /**\n * Runs `callback` just before this view is connected. DOM nodes are not yet attached to the page.\n */\n beforeConnect(callback: () => void): void;\n\n /**\n * Runs `callback` after this view is connected. DOM nodes are now attached to the page.\n */\n onConnected(callback: () => void): void;\n\n /**\n * Runs `callback` just before this view is disconnected. DOM nodes are still attached to the page.\n */\n beforeDisconnect(callback: () => void): void;\n\n /**\n * Runs `callback` after this view is disconnected. DOM nodes are no longer attached to the page.\n */\n onDisconnected(callback: () => void): void;\n\n /**\n * The name of this view for logging and debugging purposes.\n */\n name: string;\n\n /**\n * Takes an Error object, unmounts the app and displays its crash page.\n */\n crash(error: Error): void;\n\n /**\n * Observes a readable value while this view is connected. Calls `callback` each time the value changes.\n */\n observe<T>(state: MaybeReadable<T>, callback: (currentValue: T) => void): void;\n\n /**\n * Observes a set of readable values while this view is connected.\n * Calls `callback` with each value in the same order as `readables` each time any of their values change.\n */\n observe<T extends MaybeReadable<any>[]>(\n states: [...T],\n callback: (...currentValues: ReadableValues<T>) => void,\n ): void;\n\n observe<I1, I2>(\n state1: MaybeReadable<I1>,\n state2: MaybeReadable<I2>,\n callback: (value1: I1, value2: I2) => void,\n ): void;\n\n observe<I1, I2, I3>(\n state1: MaybeReadable<I1>,\n state2: MaybeReadable<I2>,\n state3: MaybeReadable<I3>,\n callback: (value1: I1, value2: I2, value3: I3) => void,\n ): void;\n\n observe<I1, I2, I3, I4>(\n state1: MaybeReadable<I1>,\n state2: MaybeReadable<I2>,\n state3: MaybeReadable<I3>,\n state4: MaybeReadable<I4>,\n callback: (value1: I1, value2: I2, value3: I3, value4: I4) => void,\n ): void;\n\n observe<I1, I2, I3, I4, I5>(\n state1: MaybeReadable<I1>,\n state2: MaybeReadable<I2>,\n state3: MaybeReadable<I3>,\n state4: MaybeReadable<I4>,\n state5: MaybeReadable<I5>,\n callback: (value1: I1, value2: I2, value3: I3, value4: I4, value5: I5) => void,\n ): void;\n\n observe<I1, I2, I3, I4, I5, I6>(\n state1: MaybeReadable<I1>,\n state2: MaybeReadable<I2>,\n state3: MaybeReadable<I3>,\n state4: MaybeReadable<I4>,\n state5: MaybeReadable<I5>,\n state6: MaybeReadable<I6>,\n callback: (value1: I1, value2: I2, value3: I3, value4: I4, value5: I5, value6: I6) => void,\n ): void;\n\n observe<I1, I2, I3, I4, I5, I6, I7>(\n state1: MaybeReadable<I1>,\n state2: MaybeReadable<I2>,\n state3: MaybeReadable<I3>,\n state4: MaybeReadable<I4>,\n state5: MaybeReadable<I5>,\n state6: MaybeReadable<I6>,\n state7: MaybeReadable<I7>,\n callback: (value1: I1, value2: I2, value3: I3, value4: I4, value5: I5, value6: I6, value7: I7) => void,\n ): void;\n\n observe<I1, I2, I3, I4, I5, I6, I7, I8>(\n state1: MaybeReadable<I1>,\n state2: MaybeReadable<I2>,\n state3: MaybeReadable<I3>,\n state4: MaybeReadable<I4>,\n state5: MaybeReadable<I5>,\n state6: MaybeReadable<I6>,\n state7: MaybeReadable<I7>,\n state8: MaybeReadable<I8>,\n callback: (value1: I1, value2: I2, value3: I3, value4: I4, value5: I5, value6: I6, value7: I7, value8: I8) => void,\n ): void;\n\n observe<I1, I2, I3, I4, I5, I6, I7, I8, I9>(\n state1: MaybeReadable<I1>,\n state2: MaybeReadable<I2>,\n state3: MaybeReadable<I3>,\n state4: MaybeReadable<I4>,\n state5: MaybeReadable<I5>,\n state6: MaybeReadable<I6>,\n state7: MaybeReadable<I7>,\n state8: MaybeReadable<I8>,\n state9: MaybeReadable<I9>,\n callback: (\n value1: I1,\n value2: I2,\n value3: I3,\n value4: I4,\n value5: I5,\n value6: I6,\n value7: I7,\n value8: I8,\n value9: I9,\n ) => void,\n ): void;\n\n observe<I1, I2, I3, I4, I5, I6, I7, I8, I9, I10>(\n state1: MaybeReadable<I1>,\n state2: MaybeReadable<I2>,\n state3: MaybeReadable<I3>,\n state4: MaybeReadable<I4>,\n state5: MaybeReadable<I5>,\n state6: MaybeReadable<I6>,\n state7: MaybeReadable<I7>,\n state8: MaybeReadable<I8>,\n state9: MaybeReadable<I9>,\n state10: MaybeReadable<I10>,\n callback: (\n value1: I1,\n value2: I2,\n value3: I3,\n value4: I4,\n value5: I5,\n value6: I6,\n value7: I7,\n value8: I8,\n value9: I9,\n value10: I10,\n ) => void,\n ): void;\n\n /**\n * Returns a Markup element that displays this view's children.\n */\n outlet(): Markup;\n}\n\n/*=====================================*\\\n|| Context Accessors ||\n\\*=====================================*/\n\nexport interface ViewContextSecrets {\n appContext: AppContext;\n elementContext: ElementContext;\n}\n\nconst SECRETS = Symbol(\"VIEW_SECRETS\");\n\nexport function getViewSecrets(ctx: ViewContext): ViewContextSecrets {\n return (ctx as any)[SECRETS];\n}\n\n/*=====================================*\\\n|| View Init ||\n\\*=====================================*/\n\nexport function view<P>(callback: View<P>) {\n return callback;\n}\n\n/**\n * Parameters passed to the makeView function.\n */\ninterface ViewConfig<P> {\n view: View<P>;\n appContext: AppContext;\n elementContext: ElementContext;\n props: P;\n children?: Markup[];\n}\n\nexport function initView<P>(config: ViewConfig<P>): DOMHandle {\n const appContext = config.appContext;\n const elementContext = {\n ...config.elementContext,\n stores: new Map(),\n parent: config.elementContext,\n };\n const $$children = $$<DOMHandle[]>(renderMarkupToDOM(config.children ?? [], { appContext, elementContext }));\n\n let isConnected = false;\n\n // Lifecycle and observers\n const stopObserverCallbacks: (() => void)[] = [];\n const connectedCallbacks: (() => any)[] = [];\n const disconnectedCallbacks: (() => any)[] = [];\n const beforeConnectCallbacks: (() => void | Promise<void>)[] = [];\n const beforeDisconnectCallbacks: (() => void | Promise<void>)[] = [];\n\n const uniqueId = nanoid();\n\n const ctx: Omit<ViewContext, keyof DebugChannel> = {\n get uniqueId() {\n return uniqueId;\n },\n\n name: config.view.name ?? \"anonymous\",\n\n getStore(store: keyof BuiltInStores | Store<any, any>) {\n let name: string;\n\n if (typeof store === \"string\") {\n name = store as keyof BuiltInStores;\n } else {\n name = store.name;\n }\n\n if (typeof store !== \"string\") {\n let ec: ElementContext | undefined = elementContext;\n while (ec) {\n if (ec.stores.has(store)) {\n return ec.stores.get(store)?.instance!.exports;\n }\n ec = ec.parent;\n }\n }\n\n if (appContext.stores.has(store)) {\n const _store = appContext.stores.get(store)!;\n\n if (!_store.instance) {\n appContext.crashCollector.crash({\n componentName: ctx.name,\n error: new Error(`Store '${name}' is not registered on this app.`),\n });\n }\n\n return _store.instance!.exports;\n }\n\n appContext.crashCollector.crash({\n componentName: ctx.name,\n error: new Error(`Store '${name}' is not registered on this app.`),\n });\n },\n\n onConnected(callback) {\n connectedCallbacks.push(callback);\n },\n\n onDisconnected(callback) {\n disconnectedCallbacks.push(callback);\n },\n\n beforeConnect(callback) {\n beforeConnectCallbacks.push(callback);\n },\n\n beforeDisconnect(callback) {\n beforeDisconnectCallbacks.push(callback);\n },\n\n crash(error: Error) {\n config.appContext.crashCollector.crash({ error, componentName: ctx.name });\n },\n\n observe(...args: any[]) {\n const callback = args.pop();\n if (isConnected) {\n // If called when the component is connected, we assume this code is in a lifecycle hook\n // where it will be triggered at some point again after the component is reconnected.\n const stop = observe(args, callback);\n stopObserverCallbacks.push(stop);\n } else {\n // This should only happen if called in the body of the component function.\n // This code is not always re-run between when a component is disconnected and reconnected.\n connectedCallbacks.push(() => {\n const stop = observe(args, callback);\n stopObserverCallbacks.push(stop);\n });\n }\n },\n\n outlet() {\n return m(\"$outlet\", { $children: $($$children) });\n },\n };\n\n const debugChannel = appContext.debugHub.channel({\n get name() {\n return ctx.name;\n },\n });\n\n Object.defineProperties(ctx, Object.getOwnPropertyDescriptors(debugChannel));\n\n Object.defineProperty(ctx, SECRETS, {\n enumerable: false,\n configurable: false,\n value: {\n appContext,\n elementContext,\n } as ViewContextSecrets,\n });\n\n let rendered: DOMHandle | undefined;\n\n function initialize() {\n let result: unknown;\n\n try {\n result = config.view(config.props, ctx as ViewContext);\n } catch (error) {\n if (error instanceof Error) {\n appContext.crashCollector.crash({ error, componentName: ctx.name });\n }\n throw error;\n }\n\n if (result instanceof Promise) {\n appContext.crashCollector.crash({\n error: new TypeError(`View function cannot return a Promise.`),\n componentName: ctx.name,\n });\n }\n\n if (result === null) {\n // Do nothing.\n } else if (result instanceof Node) {\n rendered = getRenderHandle(renderMarkupToDOM(m(\"$node\", { value: result }), { appContext, elementContext }));\n } else if (isMarkup(result) || isArrayOf<Markup>(isMarkup, result)) {\n rendered = getRenderHandle(renderMarkupToDOM(result, { appContext, elementContext }));\n } else if (isReadable(result)) {\n rendered = getRenderHandle(\n renderMarkupToDOM(m(\"$observer\", { readables: [result], renderFn: (x) => x }), { appContext, elementContext }),\n );\n } else {\n console.warn(result, config);\n appContext.crashCollector.crash({\n error: new TypeError(\n `Expected '${\n config.view.name\n }' function to return a DOM node, Markup element, Readable or null. Got: ${typeOf(result)}`,\n ),\n componentName: ctx.name,\n });\n }\n }\n\n const handle: DOMHandle = {\n get node() {\n return rendered?.node!;\n },\n\n get connected() {\n return isConnected;\n },\n\n connect(parent: Node, after?: Node) {\n // Don't run lifecycle hooks or initialize if already connected.\n // Calling connect again can be used to re-order elements that are already connected to the DOM.\n const wasConnected = isConnected;\n\n if (!wasConnected) {\n initialize();\n while (beforeConnectCallbacks.length > 0) {\n const callback = beforeConnectCallbacks.shift()!;\n callback();\n }\n }\n\n if (rendered) {\n rendered.connect(parent, after);\n }\n\n if (!wasConnected) {\n isConnected = true;\n\n requestAnimationFrame(() => {\n while (connectedCallbacks.length > 0) {\n const callback = connectedCallbacks.shift()!;\n callback();\n }\n });\n }\n },\n\n disconnect() {\n while (beforeDisconnectCallbacks.length > 0) {\n const callback = beforeDisconnectCallbacks.shift()!;\n callback();\n }\n\n if (rendered) {\n rendered.disconnect();\n }\n\n isConnected = false;\n\n while (disconnectedCallbacks.length > 0) {\n const callback = disconnectedCallbacks.shift()!;\n callback();\n }\n\n while (stopObserverCallbacks.length > 0) {\n const callback = stopObserverCallbacks.shift()!;\n callback();\n }\n },\n\n async setChildren(children) {\n $$children.set(children);\n },\n };\n\n return handle;\n}\n", "import { type AppContext, type ElementContext } from \"../app.js\";\nimport { type DOMHandle } from \"../markup.js\";\nimport { $, $$, observe, type Readable, type Writable, type StopFunction } from \"../state.js\";\nimport { initView, type ViewContext, type ViewResult } from \"../view.js\";\n\n// ----- Types ----- //\n\ninterface RepeatOptions<T> {\n appContext: AppContext;\n elementContext: ElementContext;\n $items: Readable<T[]>;\n keyFn: (value: T, index: number) => string | number | symbol;\n renderFn: ($value: Readable<T>, $index: Readable<number>, ctx: ViewContext) => ViewResult;\n}\n\ntype ConnectedItem<T> = {\n key: any;\n $$value: Writable<T>;\n $$index: Writable<number>;\n handle: DOMHandle;\n};\n\n// ----- Code ----- //\n\nexport class Repeat<T> implements DOMHandle {\n node: Node;\n endNode: Node;\n $items: Readable<T[]>;\n stopCallback?: StopFunction;\n connectedItems: ConnectedItem<T>[] = [];\n appContext;\n elementContext;\n renderFn: ($value: Readable<T>, $index: Readable<number>, ctx: ViewContext) => ViewResult;\n keyFn: (value: T, index: number) => string | number | symbol;\n\n get connected() {\n return this.node.parentNode != null;\n }\n\n constructor({ appContext, elementContext, $items, renderFn, keyFn }: RepeatOptions<T>) {\n this.appContext = appContext;\n this.elementContext = elementContext;\n\n this.$items = $items;\n this.renderFn = renderFn;\n this.keyFn = keyFn;\n\n if (appContext.mode === \"development\") {\n this.node = document.createComment(\"Repeat\");\n this.endNode = document.createComment(\"/Repeat\");\n } else {\n this.node = document.createTextNode(\"\");\n this.endNode = document.createTextNode(\"\");\n }\n }\n\n connect(parent: Node, after?: Node) {\n if (!this.connected) {\n parent.insertBefore(this.node, after?.nextSibling ?? null);\n\n this.stopCallback = observe(this.$items, (value) => {\n this._update(Array.from(value));\n });\n }\n }\n\n disconnect() {\n if (this.stopCallback) {\n this.stopCallback();\n this.stopCallback = undefined;\n }\n\n if (this.connected) {\n this.node.parentNode?.removeChild(this.node);\n this.endNode.parentNode?.removeChild(this.endNode);\n }\n\n this._cleanup();\n }\n\n setChildren() {\n console.warn(\"setChildren is not implemented for repeat()\");\n }\n\n _cleanup() {\n for (const item of this.connectedItems) {\n item.handle.disconnect();\n }\n this.connectedItems = [];\n }\n\n _update(value: T[]) {\n if (value.length === 0 || !this.connected) {\n return this._cleanup();\n }\n\n type UpdateItem = { key: string | number | symbol; value: T; index: number };\n\n const potentialItems: UpdateItem[] = [];\n let index = 0;\n\n for (const item of value) {\n potentialItems.push({\n key: this.keyFn(item, index),\n value: item,\n index: index++,\n });\n }\n\n const newItems: ConnectedItem<T>[] = [];\n\n // Remove views for items that no longer exist in the new list.\n for (const connected of this.connectedItems) {\n const potentialItem = potentialItems.find((p) => p.key === connected.key);\n\n if (!potentialItem) {\n connected.handle.disconnect();\n }\n }\n\n // Add new views and update state for existing ones.\n for (const potential of potentialItems) {\n const connected = this.connectedItems.find((item) => item.key === potential.key);\n\n if (connected) {\n connected.$$value.set(potential.value);\n connected.$$index.set(potential.index);\n newItems[potential.index] = connected;\n } else {\n const $$value = $$(potential.value) as Writable<T>;\n const $$index = $$(potential.index);\n\n newItems[potential.index] = {\n key: potential.key,\n $$value,\n $$index,\n handle: initView({\n view: RepeatItemView,\n appContext: this.appContext,\n elementContext: this.elementContext,\n props: { $value: $($$value), $index: $($$index), renderFn: this.renderFn },\n }),\n };\n }\n }\n\n // Reconnect to ensure order. Lifecycle hooks won't be run again if the view is already connected.\n for (let i = 0; i < newItems.length; i++) {\n const item = newItems[i];\n const previous = newItems[i - 1]?.handle.node ?? this.node;\n item.handle.connect(this.node.parentNode!, previous);\n }\n\n this.connectedItems = newItems;\n\n if (this.appContext.mode === \"development\") {\n this.node.textContent = `Repeat (${newItems.length} item${newItems.length === 1 ? \"\" : \"s\"})`;\n\n const lastItem = newItems.at(-1)?.handle.node ?? this.node;\n this.node.parentNode?.insertBefore(this.endNode, lastItem.nextSibling);\n }\n }\n}\n\ninterface RepeatItemProps {\n $value: Readable<any>;\n $index: Readable<number>;\n renderFn: ($value: Readable<any>, $index: Readable<number>, ctx: ViewContext) => ViewResult;\n}\n\nfunction RepeatItemView({ $value, $index, renderFn }: RepeatItemProps, ctx: ViewContext) {\n return renderFn($value, $index, ctx);\n}\n", "import { type DOMHandle } from \"../markup.js\";\nimport { isReadable, observe, type Readable, type StopFunction } from \"../state.js\";\n\ninterface Stringable {\n toString(): string;\n}\n\ninterface TextOptions {\n value: Stringable | Readable<Stringable>;\n}\n\nexport class Text implements DOMHandle {\n node = document.createTextNode(\"\");\n value: Stringable | Readable<Stringable> = \"\";\n stopCallback?: StopFunction;\n\n get connected() {\n return this.node.parentNode != null;\n }\n\n constructor({ value }: TextOptions) {\n this.value = value;\n }\n\n async connect(parent: Node, after: Node | null = null) {\n if (!this.connected) {\n if (isReadable<Stringable>(this.value)) {\n this.stopCallback = observe(this.value, (value) => {\n this.update(value);\n });\n } else {\n this.update(this.value);\n }\n }\n\n parent.insertBefore(this.node, after?.nextSibling ?? null);\n }\n\n async disconnect() {\n if (this.connected) {\n if (this.stopCallback) {\n this.stopCallback();\n this.stopCallback = undefined;\n }\n\n this.node.parentNode!.removeChild(this.node);\n }\n }\n\n update(value?: Stringable) {\n if (value != null) {\n this.node.textContent = value.toString();\n } else {\n this.node.textContent = \"\";\n }\n }\n\n async setChildren() {}\n}\n", "import { type AppContext, type ElementContext } from \"./app.js\";\nimport { Conditional } from \"./nodes/cond.js\";\nimport { HTML } from \"./nodes/html.js\";\nimport { Observer } from \"./nodes/observer.js\";\nimport { Outlet } from \"./nodes/outlet.js\";\nimport { Portal } from \"./nodes/portal.js\";\nimport { Repeat } from \"./nodes/repeat.js\";\nimport { Text } from \"./nodes/text.js\";\nimport { $, isReadable, type Readable } from \"./state.js\";\nimport { isArray, isArrayOf, isFunction, isNumber, isObject, isString } from \"./typeChecking.js\";\nimport type { Renderable, Stringable } from \"./types.js\";\nimport { initView, type View, type ViewContext, type ViewResult } from \"./view.js\";\n\n/*===========================*\\\n|| Markup ||\n\\*===========================*/\n\nconst MARKUP = Symbol(\"Markup\");\n\n/**\n * Markup is a set of element metadata that hasn't been rendered to a DOMHandle yet.\n */\nexport interface Markup {\n type: string | View<any>;\n props?: Record<string, any>;\n children?: Markup[];\n}\n\n/**\n * DOMHandle is the generic interface for an element that can be manipulated by the framework.\n */\nexport interface DOMHandle {\n readonly node?: Node;\n readonly connected: boolean;\n\n connect(parent: Node, after?: Node): void;\n\n disconnect(): void;\n\n setChildren(children: DOMHandle[]): void;\n}\n\nexport function isMarkup(value: unknown): value is Markup {\n return isObject(value) && value[MARKUP] === true;\n}\n\nexport function isDOMHandle(value: unknown): value is DOMHandle {\n return isObject(value) && isFunction(value.connect) && isFunction(value.disconnect);\n}\n\nexport function toMarkup(renderables: Renderable | Renderable[]): Markup[] {\n if (!isArray(renderables)) {\n renderables = [renderables];\n }\n\n return renderables\n .flat(Infinity)\n .filter((x) => x !== null && x !== undefined && x !== false)\n .map((x) => {\n if (x instanceof Node) {\n return m(\"$node\", { value: x });\n }\n\n if (isMarkup(x)) {\n return x;\n }\n\n if (isString(x) || isNumber(x)) {\n return m(\"$text\", { value: x });\n }\n\n if (isReadable(x)) {\n return m(\"$observer\", {\n readables: [x],\n renderFn: (x) => x,\n });\n }\n\n console.error(x);\n throw new TypeError(`Unexpected child type. Got: ${x}`);\n });\n}\n\nexport interface MarkupAttributes {\n $text: { value: Stringable | Readable<Stringable> };\n $cond: { $predicate: Readable<any>; thenContent?: Renderable; elseContent?: Renderable };\n $repeat: {\n $items: Readable<any[]>;\n keyFn: (value: any, index: number) => string | number | symbol;\n renderFn: ($item: Readable<any>, $index: Readable<number>, c: ViewContext) => ViewResult;\n };\n $observer: {\n readables: Readable<any>[];\n renderFn: (...items: any) => Renderable;\n };\n $outlet: {\n $children: Readable<DOMHandle[]>;\n };\n $node: {\n value: Node;\n };\n $portal: {\n content: Renderable;\n parent: Node;\n };\n\n [tag: string]: Record<string, any>;\n}\n\nexport function m<T extends keyof MarkupAttributes>(\n type: T,\n attributes: MarkupAttributes[T],\n ...children: Renderable[]\n): Markup;\n\nexport function m<I>(type: View<I>, attributes?: I, ...children: Renderable[]): Markup;\n\nexport function m<P>(type: string | View<P>, props?: P, ...children: Renderable[]) {\n return {\n [MARKUP]: true,\n type,\n props,\n children: toMarkup(children),\n };\n}\n\n/*===========================*\\\n|| Markup Utils ||\n\\*===========================*/\n\n/**\n * Displays content conditionally. When `predicate` holds a truthy value, `thenContent` is displayed; when `predicate` holds a falsy value, `elseContent` is displayed.\n */\nexport function cond(predicate: any | Readable<any>, thenContent?: Renderable, elseContent?: Renderable): Markup {\n const $predicate = $(predicate);\n\n return m(\"$cond\", {\n $predicate,\n thenContent,\n elseContent,\n });\n}\n\n/**\n * Calls `renderFn` for each item in `items`. Dynamically adds and removes views as items change.\n * The result of `keyFn` is used to compare items and decide if item was added, removed or updated.\n */\nexport function repeat<T>(\n items: Readable<T[]> | T[],\n keyFn: (value: T, index: number) => string | number | symbol,\n renderFn: ($value: Readable<T>, $index: Readable<number>, ctx: ViewContext) => ViewResult,\n): Markup {\n const $items = $(items);\n\n return m(\"$repeat\", { $items, keyFn, renderFn });\n}\n\n/**\n * Render `content` into a `parent` node anywhere in the page, rather than at its position in the view.\n */\nexport function portal(content: Renderable, parent: Node) {\n return m(\"$portal\", { content, parent });\n}\n\n/*===========================*\\\n|| Render ||\n\\*===========================*/\n\ninterface RenderContext {\n appContext: AppContext;\n elementContext: ElementContext;\n}\n\n/**\n * Wraps any plain DOM node in a DOMHandle interface.\n */\nclass NodeHandle implements DOMHandle {\n node: Node;\n\n get connected() {\n return this.node.parentNode != null;\n }\n\n constructor(node: Node) {\n this.node = node;\n }\n\n async connect(parent: Node, after?: Node) {\n parent.insertBefore(this.node, after?.nextSibling ?? null);\n }\n\n async disconnect() {\n if (this.node.parentNode) {\n this.node.parentNode.removeChild(this.node);\n }\n }\n\n async setChildren(children: DOMHandle[]) {}\n}\n\nexport function renderMarkupToDOM(markup: Markup | Markup[], ctx: RenderContext): DOMHandle[] {\n const items = isArray(markup) ? markup : [markup];\n\n return items.map((item) => {\n if (isFunction(item.type)) {\n return initView({\n view: item.type as View<any>,\n props: item.props,\n children: item.children,\n appContext: ctx.appContext,\n elementContext: ctx.elementContext,\n });\n } else if (isString(item.type)) {\n switch (item.type) {\n case \"$node\": {\n const attrs = item.props! as MarkupAttributes[\"$node\"];\n return new NodeHandle(attrs.value);\n }\n case \"$text\": {\n const attrs = item.props! as MarkupAttributes[\"$text\"];\n return new Text({\n value: attrs.value,\n });\n }\n case \"$cond\": {\n const attrs = item.props! as MarkupAttributes[\"$cond\"];\n return new Conditional({\n $predicate: attrs.$predicate,\n thenContent: attrs.thenContent,\n elseContent: attrs.elseContent,\n appContext: ctx.appContext,\n elementContext: ctx.elementContext,\n });\n }\n case \"$repeat\": {\n const attrs = item.props! as MarkupAttributes[\"$repeat\"];\n return new Repeat({\n $items: attrs.$items,\n keyFn: attrs.keyFn,\n renderFn: attrs.renderFn,\n appContext: ctx.appContext,\n elementContext: ctx.elementContext,\n });\n }\n case \"$observer\": {\n const attrs = item.props! as MarkupAttributes[\"$observer\"];\n return new Observer({\n readables: attrs.readables,\n renderFn: attrs.renderFn,\n appContext: ctx.appContext,\n elementContext: ctx.elementContext,\n });\n }\n case \"$outlet\": {\n const attrs = item.props! as MarkupAttributes[\"$outlet\"];\n return new Outlet({\n $children: attrs.$children,\n appContext: ctx.appContext,\n elementContext: ctx.elementContext,\n });\n }\n case \"$portal\": {\n const attrs = item.props! as MarkupAttributes[\"$portal\"];\n return new Portal({\n content: attrs.content,\n parent: attrs.parent,\n appContext: ctx.appContext,\n elementContext: ctx.elementContext,\n });\n }\n default:\n if (item.type.startsWith(\"$\")) {\n throw new Error(`Unknown markup type: ${item.type}`);\n }\n return new HTML({\n tag: item.type,\n props: item.props,\n children: item.children,\n appContext: ctx.appContext,\n elementContext: ctx.elementContext,\n });\n }\n } else {\n throw new TypeError(`Expected a string or view function. Got: ${item.type}`);\n }\n });\n}\n\n/**\n * Combines one or more DOMHandles into a single DOMHandle.\n */\nexport function getRenderHandle(handles: DOMHandle[]): DOMHandle {\n if (handles.length === 1) {\n return handles[0];\n }\n\n const node = document.createComment(\"renderHandle\");\n\n let isConnected = false;\n\n return {\n get node() {\n return node;\n },\n get connected() {\n return isConnected;\n },\n connect(parent: Node, after?: Node) {\n parent.insertBefore(node, after ? after : null);\n\n for (const handle of handles) {\n const previous = handles[handles.length - 1]?.node ?? node;\n handle.connect(parent, previous);\n }\n\n isConnected = true;\n },\n disconnect() {\n if (isConnected) {\n for (const handle of handles) {\n handle.disconnect();\n }\n\n node.remove();\n }\n\n isConnected = false;\n },\n setChildren() {\n throw new Error(`setChildren not supported on renderHandle`);\n },\n };\n}\n\nexport function isRenderable(value: unknown): value is Renderable {\n return (\n value == null ||\n value === false ||\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n isMarkup(value) ||\n isReadable(value) ||\n isArrayOf(isRenderable, value)\n );\n}\n", "import { type AppContext, type ElementContext } from \"./app.js\";\nimport { type DebugChannel } from \"./classes/DebugHub.js\";\nimport { observe, type MaybeReadable, type ReadableValues } from \"./state.js\";\nimport { isObject, typeOf } from \"./typeChecking.js\";\nimport type { BuiltInStores } from \"./types.js\";\n\n/*=====================================*\\\n|| Types ||\n\\*=====================================*/\n\nexport type Store<O, E> = (context: StoreContext<O>) => E | Promise<E>;\n\nexport interface StoreContext<Options = any> extends DebugChannel {\n /**\n * Returns the shared instance of `store`.\n */\n getStore<T extends Store<any, any>>(store: T): ReturnType<T>;\n\n /**\n * Returns the shared instance of a built-in store.\n */\n getStore<N extends keyof BuiltInStores>(name: N): BuiltInStores[N];\n\n /**\n * Runs `callback` after this store is connected.\n */\n onConnected(callback: () => any): void;\n\n /**\n * Runs `callback` after this store is disconnected.\n */\n onDisconnected(callback: () => any): void;\n\n /**\n * The name of this store for logging and debugging purposes.\n */\n name: string;\n\n /**\n * Takes an Error object, unmounts the app and displays its crash page.\n */\n crash(error: Error): void;\n\n /**\n * Observes a readable value while this store is connected. Calls `callback` each time the value changes.\n */\n observe<T>(state: MaybeReadable<T>, callback: (currentValue: T) => void): void;\n\n /**\n * Observes a set of readable values while this store is connected.\n * Calls `callback` with each value in the same order as `readables` each time any of their values change.\n */\n observe<T extends MaybeReadable<any>[]>(\n states: [...T],\n callback: (...currentValues: ReadableValues<T>) => void\n ): void;\n\n observe<I1, I2>(\n state1: MaybeReadable<I1>,\n state2: MaybeReadable<I2>,\n callback: (value1: I1, value2: I2) => void\n ): void;\n\n observe<I1, I2, I3>(\n state1: MaybeReadable<I1>,\n state2: MaybeReadable<I2>,\n state3: MaybeReadable<I3>,\n callback: (value1: I1, value2: I2, value3: I3) => void\n ): void;\n\n observe<I1, I2, I3, I4>(\n state1: MaybeReadable<I1>,\n state2: MaybeReadable<I2>,\n state3: MaybeReadable<I3>,\n state4: MaybeReadable<I4>,\n callback: (value1: I1, value2: I2, value3: I3, value4: I4) => void\n ): void;\n\n observe<I1, I2, I3, I4, I5>(\n state1: MaybeReadable<I1>,\n state2: MaybeReadable<I2>,\n state3: MaybeReadable<I3>,\n state4: MaybeReadable<I4>,\n state5: MaybeReadable<I5>,\n callback: (value1: I1, value2: I2, value3: I3, value4: I4, value5: I5) => void\n ): void;\n\n observe<I1, I2, I3, I4, I5, I6>(\n state1: MaybeReadable<I1>,\n state2: MaybeReadable<I2>,\n state3: MaybeReadable<I3>,\n state4: MaybeReadable<I4>,\n state5: MaybeReadable<I5>,\n state6: MaybeReadable<I6>,\n callback: (value1: I1, value2: I2, value3: I3, value4: I4, value5: I5, value6: I6) => void\n ): void;\n\n observe<I1, I2, I3, I4, I5, I6, I7>(\n state1: MaybeReadable<I1>,\n state2: MaybeReadable<I2>,\n state3: MaybeReadable<I3>,\n state4: MaybeReadable<I4>,\n state5: MaybeReadable<I5>,\n state6: MaybeReadable<I6>,\n state7: MaybeReadable<I7>,\n callback: (value1: I1, value2: I2, value3: I3, value4: I4, value5: I5, value6: I6, value7: I7) => void\n ): void;\n\n observe<I1, I2, I3, I4, I5, I6, I7, I8>(\n state1: MaybeReadable<I1>,\n state2: MaybeReadable<I2>,\n state3: MaybeReadable<I3>,\n state4: MaybeReadable<I4>,\n state5: MaybeReadable<I5>,\n state6: MaybeReadable<I6>,\n state7: MaybeReadable<I7>,\n state8: MaybeReadable<I8>,\n callback: (value1: I1, value2: I2, value3: I3, value4: I4, value5: I5, value6: I6, value7: I7, value8: I8) => void\n ): void;\n\n observe<I1, I2, I3, I4, I5, I6, I7, I8, I9>(\n state1: MaybeReadable<I1>,\n state2: MaybeReadable<I2>,\n state3: MaybeReadable<I3>,\n state4: MaybeReadable<I4>,\n state5: MaybeReadable<I5>,\n state6: MaybeReadable<I6>,\n state7: MaybeReadable<I7>,\n state8: MaybeReadable<I8>,\n state9: MaybeReadable<I9>,\n callback: (\n value1: I1,\n value2: I2,\n value3: I3,\n value4: I4,\n value5: I5,\n value6: I6,\n value7: I7,\n value8: I8,\n value9: I9\n ) => void\n ): void;\n\n observe<I1, I2, I3, I4, I5, I6, I7, I8, I9, I10>(\n state1: MaybeReadable<I1>,\n state2: MaybeReadable<I2>,\n state3: MaybeReadable<I3>,\n state4: MaybeReadable<I4>,\n state5: MaybeReadable<I5>,\n state6: MaybeReadable<I6>,\n state7: MaybeReadable<I7>,\n state8: MaybeReadable<I8>,\n state9: MaybeReadable<I9>,\n state10: MaybeReadable<I10>,\n callback: (\n value1: I1,\n value2: I2,\n value3: I3,\n value4: I4,\n value5: I5,\n value6: I6,\n value7: I7,\n value8: I8,\n value9: I9,\n value10: I10\n ) => void\n ): void;\n\n /**\n * Options this store was initialized with.\n */\n options: Options;\n}\n\n/*=====================================*\\\n|| Context Accessors ||\n\\*=====================================*/\n\nexport interface StoreContextSecrets {\n appContext: AppContext;\n elementContext: ElementContext;\n}\n\nconst SECRETS = Symbol(\"STORE_SECRETS\");\n\nexport function getStoreSecrets(c: StoreContext): StoreContextSecrets {\n return (c as any)[SECRETS];\n}\n\n/*=====================================*\\\n|| Store Init ||\n\\*=====================================*/\n\nexport function store<O>(callback: Store<any, O>) {\n return callback;\n}\n\n/**\n * Parameters passed to the makeStore function.\n */\ninterface StoreConfig<O> {\n store: Store<O, any>;\n appContext: AppContext;\n elementContext: ElementContext;\n options?: O;\n}\n\nexport function initStore<O>(config: StoreConfig<O>) {\n const appContext = config.appContext;\n const elementContext = config.elementContext;\n\n let isConnected = false;\n\n // Lifecycle and observers\n const stopObserverCallbacks: (() => void)[] = [];\n const connectedCallbacks: (() => any)[] = [];\n const disconnectedCallbacks: (() => any)[] = [];\n\n const ctx: Omit<StoreContext, keyof DebugChannel> = {\n name: config.store.name ?? \"anonymous\",\n options: config.options,\n\n getStore(store: keyof BuiltInStores | Store<any, any>) {\n let name: string;\n\n if (typeof store === \"string\") {\n name = store as keyof BuiltInStores;\n } else {\n name = store.name;\n }\n\n if (typeof store !== \"string\") {\n let ec: ElementContext | undefined = elementContext;\n while (ec) {\n if (ec.stores.has(store)) {\n return ec.stores.get(store)?.instance!.exports;\n }\n ec = ec.parent;\n }\n }\n\n if (appContext.stores.has(store)) {\n const _store = appContext.stores.get(store)!;\n\n if (!_store.instance) {\n appContext.crashCollector.crash({\n componentName: ctx.name,\n error: new Error(\n `Store '${name}' was accessed before it was set up. Make sure '${name}' is registered before components that access it.`\n ),\n });\n }\n\n return _store.instance!.exports;\n }\n\n appContext.crashCollector.crash({\n componentName: ctx.name,\n error: new Error(`Store '${name}' is not registered on this app.`),\n });\n },\n\n onConnected(callback: () => any) {\n connectedCallbacks.push(callback);\n },\n\n onDisconnected(callback: () => any) {\n disconnectedCallbacks.push(callback);\n },\n\n crash(error: Error) {\n config.appContext.crashCollector.crash({ error, componentName: ctx.name });\n },\n\n observe(...args: any[]) {\n const callback = args.pop();\n const readables = args.flat();\n if (isConnected) {\n // If called when the component is connected, we assume this code is in a lifecycle hook\n // where it will be triggered at some point again after the component is reconnected.\n const stop = observe(readables, callback);\n stopObserverCallbacks.push(stop);\n } else {\n // This should only happen if called in the body of the component function.\n // This code is not always re-run between when a component is disconnected and reconnected.\n connectedCallbacks.push(() => {\n const stop = observe(readables, callback);\n stopObserverCallbacks.push(stop);\n });\n }\n },\n };\n\n const debugChannel = appContext.debugHub.channel({\n get name() {\n return ctx.name;\n },\n });\n\n Object.defineProperties(ctx, Object.getOwnPropertyDescriptors(debugChannel));\n\n Object.defineProperty(ctx, SECRETS, {\n enumerable: false,\n configurable: false,\n value: {\n appContext,\n elementContext,\n } as StoreContextSecrets,\n });\n\n let exports: any;\n\n return {\n get name() {\n return ctx.name;\n },\n\n get exports() {\n return exports;\n },\n\n setup() {\n let result: unknown;\n\n try {\n result = config.store(ctx as StoreContext<O>);\n } catch (error) {\n if (error instanceof Error) {\n appContext.crashCollector.crash({ error, componentName: ctx.name });\n } else {\n throw error;\n }\n }\n\n if (result instanceof Promise) {\n appContext.crashCollector.crash({\n error: new TypeError(`Store function cannot return a Promise`),\n componentName: ctx.name,\n });\n }\n\n if (!isObject(result)) {\n const error = new TypeError(`Expected ${ctx.name} function to return an object. Got: ${typeOf(result)}`);\n appContext.crashCollector.crash({ error, componentName: ctx.name });\n }\n\n exports = result;\n },\n\n connect() {\n while (connectedCallbacks.length > 0) {\n const callback = connectedCallbacks.shift()!;\n callback();\n }\n },\n\n disconnect() {\n while (disconnectedCallbacks.length > 0) {\n const callback = disconnectedCallbacks.shift()!;\n callback();\n }\n },\n };\n}\n", "import { $, $$ } from \"../state.js\";\nimport { type StoreContext } from \"../store.js\";\n\ntype ScreenOrientation = \"landscape\" | \"portrait\";\ntype ColorScheme = \"light\" | \"dark\";\n\nexport function DocumentStore(ctx: StoreContext) {\n ctx.name = \"dolla/document\";\n\n const $$title = $$(document.title);\n const $$visibility = $$(document.visibilityState);\n const $$orientation = $$<ScreenOrientation>(\"landscape\");\n const $$colorScheme = $$<ColorScheme>(\"light\");\n\n /* ----- Title and Visibility ----- */\n\n ctx.observe($$title, (current) => {\n document.title = current;\n });\n\n const onVisibilityChange = () => {\n $$visibility.set(document.visibilityState);\n };\n\n const onFocus = () => {\n $$visibility.set(\"visible\");\n };\n\n /* ----- Orientation ----- */\n\n const landscapeQuery = window.matchMedia(\"(orientation: landscape)\");\n\n function onOrientationChange(e: MediaQueryList | MediaQueryListEvent) {\n $$orientation.set(e.matches ? \"landscape\" : \"portrait\");\n }\n\n // Read initial orientation.\n onOrientationChange(landscapeQuery);\n\n /* ----- Color Scheme ----- */\n\n const colorSchemeQuery = window.matchMedia(\"(prefers-color-scheme: dark)\");\n\n function onColorChange(e: MediaQueryList | MediaQueryListEvent) {\n $$colorScheme.set(e.matches ? \"dark\" : \"light\");\n }\n\n // Read initial color scheme.\n onColorChange(colorSchemeQuery);\n\n /* ----- Lifecycle ----- */\n\n // Listen for changes while connected.\n ctx.onConnected(function () {\n landscapeQuery.addEventListener(\"change\", onOrientationChange);\n colorSchemeQuery.addEventListener(\"change\", onColorChange);\n document.addEventListener(\"visibilitychange\", onVisibilityChange);\n window.addEventListener(\"focus\", onFocus);\n });\n ctx.onDisconnected(function () {\n landscapeQuery.removeEventListener(\"change\", onOrientationChange);\n colorSchemeQuery.removeEventListener(\"change\", onColorChange);\n document.removeEventListener(\"visibilitychange\", onVisibilityChange);\n window.removeEventListener(\"focus\", onFocus);\n });\n\n /* ----- Exports ----- */\n\n return {\n $$title,\n $visibility: $($$visibility),\n $orientation: $($$orientation),\n $colorScheme: $($$colorScheme),\n };\n}\n", "import { type StoreContext } from \"../store.js\";\n\n/**\n * Batches DOM updates for better performance.\n */\nexport function RenderStore(ctx: StoreContext) {\n ctx.name = \"dolla/render\";\n\n // Keyed updates ensure only the most recent callback queued with a certain key\n // will be called, keeping DOM operations to a minimum.\n const keyedUpdates = new Map<string, () => void>();\n\n // All unkeyed updates are run on every batch.\n let unkeyedUpdates: (() => void)[] = [];\n\n let reads: (() => void)[] = [];\n\n let isUpdating = false;\n let isConnected = false;\n\n ctx.onConnected(() => {\n isConnected = true;\n });\n\n ctx.onDisconnected(() => {\n isConnected = false;\n });\n\n function runUpdates() {\n const totalQueued = keyedUpdates.size + unkeyedUpdates.length;\n\n if (!isConnected || totalQueued === 0) {\n isUpdating = false;\n }\n\n if (!isUpdating) {\n for (const callback of reads) {\n callback();\n }\n reads = [];\n return;\n }\n\n requestAnimationFrame(() => {\n ctx.info(`Batching ${keyedUpdates.size + unkeyedUpdates.length} queued DOM update(s).`);\n\n // Run keyed updates first.\n for (const callback of keyedUpdates.values()) {\n callback();\n }\n keyedUpdates.clear();\n\n // Run unkeyed updates second.\n for (const callback of unkeyedUpdates) {\n callback();\n }\n unkeyedUpdates = [];\n\n // Trigger again to catch updates queued while this batch was running.\n runUpdates();\n });\n }\n\n return {\n /**\n * Queues a callback to run in the next render batch.\n * Running your DOM mutations in update callbacks reduces layout thrashing.\n * Returns a Promise that resolves once the callback has run.\n */\n update(callback: () => void, key?: string): Promise<void> {\n return new Promise((resolve) => {\n if (key) {\n keyedUpdates.set(key, () => {\n callback();\n resolve();\n });\n } else {\n unkeyedUpdates.push(() => {\n callback();\n resolve();\n });\n }\n\n if (!isUpdating && isConnected) {\n isUpdating = true;\n runUpdates();\n }\n });\n },\n\n /**\n * Queues a callback that reads DOM information to run after the next render batch,\n * ensuring all writes have been performed before reading.\n * Returns a Promise that resolves once the callback has run.\n */\n read(callback: () => void): Promise<void> {\n return new Promise((resolve) => {\n reads.push(() => {\n callback();\n resolve();\n });\n\n if (!isUpdating && isConnected) {\n isUpdating = true;\n runUpdates();\n }\n });\n },\n };\n}\n", "import { m } from \"../markup.js\";\n\ntype CrashPageProps = {\n message: string;\n error: Error;\n componentName: string;\n};\n\nexport function DefaultCrashPage({ message, error, componentName }: CrashPageProps) {\n return m(\n \"div\",\n {\n style: {\n backgroundColor: \"#880000\",\n color: \"#fff\",\n padding: \"2rem\",\n position: \"fixed\",\n inset: 0,\n fontSize: \"20px\",\n },\n },\n m(\"h1\", { style: { marginBottom: \"0.5rem\" } }, \"The app has crashed\"),\n m(\n \"p\",\n { style: { marginBottom: \"0.25rem\" } },\n m(\"span\", { style: { fontFamily: \"monospace\" } }, componentName),\n \" says:\",\n ),\n m(\n \"blockquote\",\n {\n style: {\n backgroundColor: \"#991111\",\n padding: \"0.25em\",\n borderRadius: \"6px\",\n fontFamily: \"monospace\",\n marginBottom: \"1rem\",\n },\n },\n m(\n \"span\",\n {\n style: {\n display: \"inline-block\",\n backgroundColor: \"red\",\n padding: \"0.1em 0.4em\",\n marginRight: \"0.5em\",\n borderRadius: \"4px\",\n fontSize: \"0.9em\",\n fontWeight: \"bold\",\n },\n },\n error.name,\n ),\n message,\n ),\n m(\"p\", {}, \"Please see the browser console for details.\"),\n );\n}\n", "import { type ViewContext } from \"../view.js\";\n\nexport function DefaultView(_: {}, ctx: ViewContext) {\n return ctx.outlet();\n}\n", "import { CrashCollector } from \"./classes/CrashCollector.js\";\nimport { DebugHub, type DebugOptions } from \"./classes/DebugHub.js\";\nimport { DOMHandle, m } from \"./markup.js\";\nimport { initStore, type Store } from \"./store.js\";\nimport { DocumentStore } from \"./stores/document.js\";\nimport { RenderStore } from \"./stores/render.js\";\nimport { assertFunction, assertInstanceOf, isObject, isString } from \"./typeChecking.js\";\nimport { type BuiltInStores } from \"./types.js\";\nimport { merge } from \"./utils.js\";\nimport { initView, type View } from \"./view.js\";\nimport { DefaultCrashPage } from \"./views/default-crash-page.js\";\nimport { DefaultView } from \"./views/default-view.js\";\n\n// ----- Types ----- //\n\ninterface StoreConfig<O, E> {\n store: Store<O, E>;\n options?: O;\n}\n\ninterface IAppOptions {\n /**\n * Options for the debug system.\n */\n debug?: DebugOptions;\n\n /**\n * The view to be rendered by the app.\n */\n view?: View<{}>;\n\n /**\n * App-level stores.\n */\n stores?: StoreConfig<any, any>[];\n\n /**\n * Configures the app based on the environment it's running in.\n */\n mode?: \"development\" | \"production\";\n}\n\nexport interface AppContext {\n crashCollector: CrashCollector;\n debugHub: DebugHub;\n stores: Map<keyof BuiltInStores | StoreRegistration[\"store\"], StoreRegistration>;\n mode: \"development\" | \"production\";\n rootElement?: HTMLElement;\n rootView?: DOMHandle;\n}\n\nexport interface ElementContext {\n stores: Map<StoreRegistration[\"store\"], StoreRegistration>;\n isSVG?: boolean;\n componentName?: string; // name of the nearest parent component\n parent?: ElementContext;\n}\n\n/**\n * An object kept in App for each store registered with `addStore`.\n */\nexport interface StoreRegistration<O = any> {\n store: Store<O, any>;\n options?: O;\n instance?: ReturnType<typeof initStore>;\n}\n\ninterface ConfigureContext {\n /**\n * Returns the shared instance of `store`.\n */\n getStore<T extends Store<any, any>>(store: T): ReturnType<T>;\n\n /**\n * Returns the shared instance of a built-in store.\n */\n getStore<N extends keyof BuiltInStores>(name: N): BuiltInStores[N];\n}\n\ntype ConfigureCallback = (ctx: ConfigureContext) => void | Promise<void>;\n\nexport interface IApp {\n readonly isConnected: boolean;\n\n /**\n * Runs `callback` after app-level stores are connected to the app, but before views are connected to the DOM.\n * Use this function to run async configuration code before displaying content to the user.\n *\n * Note that this will delay content being displayed on the screen, so using some kind of splash screen is recommended.\n */\n configure(callback: ConfigureCallback): this;\n\n /**\n * Initializes and connects the app as a child of `element`.\n *\n * @param element - A selector string or a DOM node to attach to. If a string, follows the same format as that taken by `document.querySelector`.\n */\n connect(selector: string | Node): Promise<void>;\n\n /**\n * Disconnects views and tears down globals, removing the app from the page.\n */\n disconnect(): Promise<void>;\n}\n\n// ----- Code ----- //\n\nfunction isAppOptions(value: unknown): value is IAppOptions {\n return isObject(value);\n}\n\nexport function App(options?: IAppOptions): IApp {\n if (options && !isAppOptions(options)) {\n throw new TypeError(`App options must be an object. Got: ${options}`);\n }\n\n let isConnected = false;\n let mainView = m(options?.view ?? DefaultView);\n let configureCallback: ConfigureCallback | undefined;\n\n const settings: IAppOptions = merge(\n {\n debug: {\n filter: \"*,-dolla/*\",\n log: \"development\", // Only print logs in development.\n warn: \"development\", // Only print warnings in development.\n error: true, // Always print errors.\n },\n mode: \"production\",\n },\n options ?? {},\n );\n\n const stores = new Map<keyof BuiltInStores | Store<any, any>, StoreRegistration>([\n [\"render\", { store: RenderStore }],\n [\"document\", { store: DocumentStore }],\n ]);\n\n if (options?.stores) {\n for (const entry of options.stores) {\n assertFunction(entry.store, `Expected a store function. Got type: %t, value: %v`);\n stores.set(entry.store, entry);\n }\n }\n\n /*=============================*\\\n || Logging & Error Handling ||\n \\*=============================*/\n\n // Crash collector is used by components to handle crashes and errors.\n const crashCollector = new CrashCollector();\n const debugHub = new DebugHub({ ...settings.debug, crashCollector, mode: settings.mode! });\n const debugChannel = debugHub.channel({ name: \"dolla/App\" });\n\n // When an error of \"crash\" severity is reported by a component,\n // the app is disconnected and a crash page is connected.\n crashCollector.onError(async ({ error, severity, componentName }) => {\n // Disconnect app and connect crash page on \"crash\" severity.\n if (severity === \"crash\") {\n await disconnect();\n\n const instance = initView({\n view: DefaultCrashPage,\n appContext,\n elementContext,\n props: {\n message: error.message,\n error: error,\n componentName,\n },\n });\n\n instance.connect(appContext.rootElement!);\n }\n });\n\n /*=============================*\\\n || App Lifecycle ||\n \\*=============================*/\n\n async function connect(selector: string | Node) {\n return new Promise<void>(async (resolve) => {\n let element: HTMLElement | null = null;\n\n if (isString(selector)) {\n element = document.querySelector(selector);\n assertInstanceOf(HTMLElement, element, `Selector string '${selector}' did not match any element.`);\n }\n\n assertInstanceOf(HTMLElement, element, \"Expected a DOM node or a selector string. Got type: %t, value: %v\");\n\n appContext.rootElement = element!;\n\n // First, initialize the root view. The router store needs this to connect the initial route.\n appContext.rootView = initView({\n view: mainView.type as View<any>,\n props: mainView.props,\n appContext,\n elementContext,\n });\n\n // Initialize stores.\n for (let [key, item] of stores.entries()) {\n const { store, options } = item;\n\n // Channel prefix is displayed before the global's name in console messages that go through a debug channel.\n // Bundled stores get an additional 'dolla/' prefix so it's clear messages are from the framework.\n // 'dolla/*' messages are filtered out by default, but this can be overridden with the app's `debug.filter` option.\n const channelPrefix = isString(key) ? \"dolla/store\" : \"store\";\n const label = isString(key) ? key : store.name ?? \"(anonymous)\";\n const config = {\n store,\n appContext,\n elementContext,\n channelPrefix,\n label,\n options: options ?? {},\n };\n\n const instance = initStore(config);\n\n instance.setup();\n\n // Add instance and mark as ready.\n stores.set(key, { ...item, instance });\n }\n\n for (const { instance } of stores.values()) {\n instance!.connect();\n }\n\n if (configureCallback) {\n await configureCallback({\n // TODO: Add context methods\n getStore(store: keyof BuiltInStores | Store<any, any>) {\n let name: string;\n\n if (typeof store === \"string\") {\n name = store as keyof BuiltInStores;\n } else {\n name = store.name;\n }\n\n if (typeof store !== \"string\") {\n let ec: ElementContext | undefined = elementContext;\n while (ec) {\n if (ec.stores.has(store)) {\n return ec.stores.get(store)?.instance!.exports;\n }\n ec = ec.parent;\n }\n }\n\n if (appContext.stores.has(store)) {\n const _store = appContext.stores.get(store)!;\n\n if (!_store.instance) {\n appContext.crashCollector.crash({\n componentName: \"@manyducks.co/dolla/App\",\n error: new Error(`Store '${name}' is not registered on this app.`),\n });\n }\n\n return _store.instance!.exports;\n }\n\n appContext.crashCollector.crash({\n componentName: \"@manyducks.co/dolla/App\",\n error: new Error(`Store '${name}' is not registered on this app.`),\n });\n },\n });\n }\n\n // Then connect the root view.\n appContext.rootView!.connect(appContext.rootElement!);\n\n // The app is now connected.\n isConnected = true;\n\n resolve();\n });\n }\n\n async function disconnect() {\n if (isConnected) {\n // Remove the root view from the page (runs teardown callbacks on all connected views).\n appContext.rootView!.disconnect();\n\n // The app is considered disconnected at this point\n isConnected = false;\n\n // Disconnect stores\n for (const { instance } of stores.values()) {\n instance!.disconnect();\n }\n }\n }\n\n /*=============================*\\\n || Contexts ||\n \\*=============================*/\n\n const appContext: AppContext = {\n crashCollector,\n debugHub,\n stores,\n mode: settings.mode ?? \"production\",\n };\n const elementContext: ElementContext = {\n stores: new Map(),\n };\n\n /*=============================*\\\n || App Object ||\n \\*=============================*/\n\n const app = {\n connect,\n disconnect,\n\n get isConnected() {\n return isConnected;\n },\n\n configure(callback: ConfigureCallback) {\n if (configureCallback !== undefined) {\n debugChannel.warn(`Configure callback is already defined. Only the final configure call will take effect.`);\n }\n\n configureCallback = callback;\n\n return app;\n },\n };\n\n return app;\n}\n", "import { type ViewContext } from \"../view.js\";\n\nexport function Fragment(_: {}, ctx: ViewContext) {\n return ctx.outlet();\n}\n", "import { Store, initStore } from \"../store.js\";\nimport { isFunction } from \"../typeChecking.js\";\nimport { ViewContext, getViewSecrets } from \"../view.js\";\n\nexport interface StoreConfig<O, E> {\n store: Store<O, E>;\n options?: O;\n}\n\nexport interface StoreScopeProps {\n stores: (StoreConfig<unknown, unknown> | Store<unknown, unknown>)[];\n}\n\n/**\n * Creates an instance of a store available only to children of this StoreScope.\n */\nexport function StoreScope(props: StoreScopeProps, ctx: ViewContext) {\n const { appContext, elementContext } = getViewSecrets(ctx);\n\n const instances: ReturnType<typeof initStore>[] = [];\n\n for (const config of props.stores) {\n let store: Store<unknown, unknown>;\n let options: unknown;\n\n if (isFunction(config)) {\n store = config as Store<unknown, unknown>;\n } else {\n store = (config as StoreConfig<unknown, unknown>).store;\n options = (config as StoreConfig<unknown, unknown>).options;\n }\n\n const instance = initStore({\n store,\n options,\n appContext,\n elementContext,\n });\n\n instance.setup();\n\n elementContext.stores.set(store, { store, options, instance });\n\n instances.push(instance);\n }\n\n ctx.beforeConnect(() => {\n for (const instance of instances) {\n instance.connect();\n }\n });\n\n ctx.onDisconnected(() => {\n for (const instance of instances) {\n instance.disconnect();\n }\n });\n\n return ctx.outlet();\n}\n", "export default function _extends() {\n _extends = Object.assign || function (target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n\n for (var key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n }\n\n return target;\n };\n\n return _extends.apply(this, arguments);\n}", "import _extends from '@babel/runtime/helpers/esm/extends';\n\n/**\r\n * Actions represent the type of change to a location value.\r\n *\r\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#action\r\n */\nvar Action;\n\n(function (Action) {\n /**\r\n * A POP indicates a change to an arbitrary index in the history stack, such\r\n * as a back or forward navigation. It does not describe the direction of the\r\n * navigation, only that the current index changed.\r\n *\r\n * Note: This is the default action for newly created history objects.\r\n */\n Action[\"Pop\"] = \"POP\";\n /**\r\n * A PUSH indicates a new entry being added to the history stack, such as when\r\n * a link is clicked and a new page loads. When this happens, all subsequent\r\n * entries in the stack are lost.\r\n */\n\n Action[\"Push\"] = \"PUSH\";\n /**\r\n * A REPLACE indicates the entry at the current index in the history stack\r\n * being replaced by a new one.\r\n */\n\n Action[\"Replace\"] = \"REPLACE\";\n})(Action || (Action = {}));\n\nvar readOnly = process.env.NODE_ENV !== \"production\" ? function (obj) {\n return Object.freeze(obj);\n} : function (obj) {\n return obj;\n};\n\nfunction warning(cond, message) {\n if (!cond) {\n // eslint-disable-next-line no-console\n if (typeof console !== 'undefined') console.warn(message);\n\n try {\n // Welcome to debugging history!\n //\n // This error is thrown as a convenience so you can more easily\n // find the source for a warning that appears in the console by\n // enabling \"pause on exceptions\" in your JavaScript debugger.\n throw new Error(message); // eslint-disable-next-line no-empty\n } catch (e) {}\n }\n}\n\nvar BeforeUnloadEventType = 'beforeunload';\nvar HashChangeEventType = 'hashchange';\nvar PopStateEventType = 'popstate';\n/**\r\n * Browser history stores the location in regular URLs. This is the standard for\r\n * most web apps, but it requires some configuration on the server to ensure you\r\n * serve the same app at multiple URLs.\r\n *\r\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createbrowserhistory\r\n */\n\nfunction createBrowserHistory(options) {\n if (options === void 0) {\n options = {};\n }\n\n var _options = options,\n _options$window = _options.window,\n window = _options$window === void 0 ? document.defaultView : _options$window;\n var globalHistory = window.history;\n\n function getIndexAndLocation() {\n var _window$location = window.location,\n pathname = _window$location.pathname,\n search = _window$location.search,\n hash = _window$location.hash;\n var state = globalHistory.state || {};\n return [state.idx, readOnly({\n pathname: pathname,\n search: search,\n hash: hash,\n state: state.usr || null,\n key: state.key || 'default'\n })];\n }\n\n var blockedPopTx = null;\n\n function handlePop() {\n if (blockedPopTx) {\n blockers.call(blockedPopTx);\n blockedPopTx = null;\n } else {\n var nextAction = Action.Pop;\n\n var _getIndexAndLocation = getIndexAndLocation(),\n nextIndex = _getIndexAndLocation[0],\n nextLocation = _getIndexAndLocation[1];\n\n if (blockers.length) {\n if (nextIndex != null) {\n var delta = index - nextIndex;\n\n if (delta) {\n // Revert the POP\n blockedPopTx = {\n action: nextAction,\n location: nextLocation,\n retry: function retry() {\n go(delta * -1);\n }\n };\n go(delta);\n }\n } else {\n // Trying to POP to a location with no index. We did not create\n // this location, so we can't effectively block the navigation.\n process.env.NODE_ENV !== \"production\" ? warning(false, // TODO: Write up a doc that explains our blocking strategy in\n // detail and link to it here so people can understand better what\n // is going on and how to avoid it.\n \"You are trying to block a POP navigation to a location that was not \" + \"created by the history library. The block will fail silently in \" + \"production, but in general you should do all navigation with the \" + \"history library (instead of using window.history.pushState directly) \" + \"to avoid this situation.\") : void 0;\n }\n } else {\n applyTx(nextAction);\n }\n }\n }\n\n window.addEventListener(PopStateEventType, handlePop);\n var action = Action.Pop;\n\n var _getIndexAndLocation2 = getIndexAndLocation(),\n index = _getIndexAndLocation2[0],\n location = _getIndexAndLocation2[1];\n\n var listeners = createEvents();\n var blockers = createEvents();\n\n if (index == null) {\n index = 0;\n globalHistory.replaceState(_extends({}, globalHistory.state, {\n idx: index\n }), '');\n }\n\n function createHref(to) {\n return typeof to === 'string' ? to : createPath(to);\n } // state defaults to `null` because `window.history.state` does\n\n\n function getNextLocation(to, state) {\n if (state === void 0) {\n state = null;\n }\n\n return readOnly(_extends({\n pathname: location.pathname,\n hash: '',\n search: ''\n }, typeof to === 'string' ? parsePath(to) : to, {\n state: state,\n key: createKey()\n }));\n }\n\n function getHistoryStateAndUrl(nextLocation, index) {\n return [{\n usr: nextLocation.state,\n key: nextLocation.key,\n idx: index\n }, createHref(nextLocation)];\n }\n\n function allowTx(action, location, retry) {\n return !blockers.length || (blockers.call({\n action: action,\n location: location,\n retry: retry\n }), false);\n }\n\n function applyTx(nextAction) {\n action = nextAction;\n\n var _getIndexAndLocation3 = getIndexAndLocation();\n\n index = _getIndexAndLocation3[0];\n location = _getIndexAndLocation3[1];\n listeners.call({\n action: action,\n location: location\n });\n }\n\n function push(to, state) {\n var nextAction = Action.Push;\n var nextLocation = getNextLocation(to, state);\n\n function retry() {\n push(to, state);\n }\n\n if (allowTx(nextAction, nextLocation, retry)) {\n var _getHistoryStateAndUr = getHistoryStateAndUrl(nextLocation, index + 1),\n historyState = _getHistoryStateAndUr[0],\n url = _getHistoryStateAndUr[1]; // TODO: Support forced reloading\n // try...catch because iOS limits us to 100 pushState calls :/\n\n\n try {\n globalHistory.pushState(historyState, '', url);\n } catch (error) {\n // They are going to lose state here, but there is no real\n // way to warn them about it since the page will refresh...\n window.location.assign(url);\n }\n\n applyTx(nextAction);\n }\n }\n\n function replace(to, state) {\n var nextAction = Action.Replace;\n var nextLocation = getNextLocation(to, state);\n\n function retry() {\n replace(to, state);\n }\n\n if (allowTx(nextAction, nextLocation, retry)) {\n var _getHistoryStateAndUr2 = getHistoryStateAndUrl(nextLocation, index),\n historyState = _getHistoryStateAndUr2[0],\n url = _getHistoryStateAndUr2[1]; // TODO: Support forced reloading\n\n\n globalHistory.replaceState(historyState, '', url);\n applyTx(nextAction);\n }\n }\n\n function go(delta) {\n globalHistory.go(delta);\n }\n\n var history = {\n get action() {\n return action;\n },\n\n get location() {\n return location;\n },\n\n createHref: createHref,\n push: push,\n replace: replace,\n go: go,\n back: function back() {\n go(-1);\n },\n forward: function forward() {\n go(1);\n },\n listen: function listen(listener) {\n return listeners.push(listener);\n },\n block: function block(blocker) {\n var unblock = blockers.push(blocker);\n\n if (blockers.length === 1) {\n window.addEventListener(BeforeUnloadEventType, promptBeforeUnload);\n }\n\n return function () {\n unblock(); // Remove the beforeunload listener so the document may\n // still be salvageable in the pagehide event.\n // See https://html.spec.whatwg.org/#unloading-documents\n\n if (!blockers.length) {\n window.removeEventListener(BeforeUnloadEventType, promptBeforeUnload);\n }\n };\n }\n };\n return history;\n}\n/**\r\n * Hash history stores the location in window.location.hash. This makes it ideal\r\n * for situations where you don't want to send the location to the server for\r\n * some reason, either because you do cannot configure it or the URL space is\r\n * reserved for something else.\r\n *\r\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createhashhistory\r\n */\n\nfunction createHashHistory(options) {\n if (options === void 0) {\n options = {};\n }\n\n var _options2 = options,\n _options2$window = _options2.window,\n window = _options2$window === void 0 ? document.defaultView : _options2$window;\n var globalHistory = window.history;\n\n function getIndexAndLocation() {\n var _parsePath = parsePath(window.location.hash.substr(1)),\n _parsePath$pathname = _parsePath.pathname,\n pathname = _parsePath$pathname === void 0 ? '/' : _parsePath$pathname,\n _parsePath$search = _parsePath.search,\n search = _parsePath$search === void 0 ? '' : _parsePath$search,\n _parsePath$hash = _parsePath.hash,\n hash = _parsePath$hash === void 0 ? '' : _parsePath$hash;\n\n var state = globalHistory.state || {};\n return [state.idx, readOnly({\n pathname: pathname,\n search: search,\n hash: hash,\n state: state.usr || null,\n key: state.key || 'default'\n })];\n }\n\n var blockedPopTx = null;\n\n function handlePop() {\n if (blockedPopTx) {\n blockers.call(blockedPopTx);\n blockedPopTx = null;\n } else {\n var nextAction = Action.Pop;\n\n var _getIndexAndLocation4 = getIndexAndLocation(),\n nextIndex = _getIndexAndLocation4[0],\n nextLocation = _getIndexAndLocation4[1];\n\n if (blockers.length) {\n if (nextIndex != null) {\n var delta = index - nextIndex;\n\n if (delta) {\n // Revert the POP\n blockedPopTx = {\n action: nextAction,\n location: nextLocation,\n retry: function retry() {\n go(delta * -1);\n }\n };\n go(delta);\n }\n } else {\n // Trying to POP to a location with no index. We did not create\n // this location, so we can't effectively block the navigation.\n process.env.NODE_ENV !== \"production\" ? warning(false, // TODO: Write up a doc that explains our blocking strategy in\n // detail and link to it here so people can understand better\n // what is going on and how to avoid it.\n \"You are trying to block a POP navigation to a location that was not \" + \"created by the history library. The block will fail silently in \" + \"production, but in general you should do all navigation with the \" + \"history library (instead of using window.history.pushState directly) \" + \"to avoid this situation.\") : void 0;\n }\n } else {\n applyTx(nextAction);\n }\n }\n }\n\n window.addEventListener(PopStateEventType, handlePop); // popstate does not fire on hashchange in IE 11 and old (trident) Edge\n // https://developer.mozilla.org/de/docs/Web/API/Window/popstate_event\n\n window.addEventListener(HashChangeEventType, function () {\n var _getIndexAndLocation5 = getIndexAndLocation(),\n nextLocation = _getIndexAndLocation5[1]; // Ignore extraneous hashchange events.\n\n\n if (createPath(nextLocation) !== createPath(location)) {\n handlePop();\n }\n });\n var action = Action.Pop;\n\n var _getIndexAndLocation6 = getIndexAndLocation(),\n index = _getIndexAndLocation6[0],\n location = _getIndexAndLocation6[1];\n\n var listeners = createEvents();\n var blockers = createEvents();\n\n if (index == null) {\n index = 0;\n globalHistory.replaceState(_extends({}, globalHistory.state, {\n idx: index\n }), '');\n }\n\n function getBaseHref() {\n var base = document.querySelector('base');\n var href = '';\n\n if (base && base.getAttribute('href')) {\n var url = window.location.href;\n var hashIndex = url.indexOf('#');\n href = hashIndex === -1 ? url : url.slice(0, hashIndex);\n }\n\n return href;\n }\n\n function createHref(to) {\n return getBaseHref() + '#' + (typeof to === 'string' ? to : createPath(to));\n }\n\n function getNextLocation(to, state) {\n if (state === void 0) {\n state = null;\n }\n\n return readOnly(_extends({\n pathname: location.pathname,\n hash: '',\n search: ''\n }, typeof to === 'string' ? parsePath(to) : to, {\n state: state,\n key: createKey()\n }));\n }\n\n function getHistoryStateAndUrl(nextLocation, index) {\n return [{\n usr: nextLocation.state,\n key: nextLocation.key,\n idx: index\n }, createHref(nextLocation)];\n }\n\n function allowTx(action, location, retry) {\n return !blockers.length || (blockers.call({\n action: action,\n location: location,\n retry: retry\n }), false);\n }\n\n function applyTx(nextAction) {\n action = nextAction;\n\n var _getIndexAndLocation7 = getIndexAndLocation();\n\n index = _getIndexAndLocation7[0];\n location = _getIndexAndLocation7[1];\n listeners.call({\n action: action,\n location: location\n });\n }\n\n function push(to, state) {\n var nextAction = Action.Push;\n var nextLocation = getNextLocation(to, state);\n\n function retry() {\n push(to, state);\n }\n\n process.env.NODE_ENV !== \"production\" ? warning(nextLocation.pathname.charAt(0) === '/', \"Relative pathnames are not supported in hash history.push(\" + JSON.stringify(to) + \")\") : void 0;\n\n if (allowTx(nextAction, nextLocation, retry)) {\n var _getHistoryStateAndUr3 = getHistoryStateAndUrl(nextLocation, index + 1),\n historyState = _getHistoryStateAndUr3[0],\n url = _getHistoryStateAndUr3[1]; // TODO: Support forced reloading\n // try...catch because iOS limits us to 100 pushState calls :/\n\n\n try {\n globalHistory.pushState(historyState, '', url);\n } catch (error) {\n // They are going to lose state here, but there is no real\n // way to warn them about it since the page will refresh...\n window.location.assign(url);\n }\n\n applyTx(nextAction);\n }\n }\n\n function replace(to, state) {\n var nextAction = Action.Replace;\n var nextLocation = getNextLocation(to, state);\n\n function retry() {\n replace(to, state);\n }\n\n process.env.NODE_ENV !== \"production\" ? warning(nextLocation.pathname.charAt(0) === '/', \"Relative pathnames are not supported in hash history.replace(\" + JSON.stringify(to) + \")\") : void 0;\n\n if (allowTx(nextAction, nextLocation, retry)) {\n var _getHistoryStateAndUr4 = getHistoryStateAndUrl(nextLocation, index),\n historyState = _getHistoryStateAndUr4[0],\n url = _getHistoryStateAndUr4[1]; // TODO: Support forced reloading\n\n\n globalHistory.replaceState(historyState, '', url);\n applyTx(nextAction);\n }\n }\n\n function go(delta) {\n globalHistory.go(delta);\n }\n\n var history = {\n get action() {\n return action;\n },\n\n get location() {\n return location;\n },\n\n createHref: createHref,\n push: push,\n replace: replace,\n go: go,\n back: function back() {\n go(-1);\n },\n forward: function forward() {\n go(1);\n },\n listen: function listen(listener) {\n return listeners.push(listener);\n },\n block: function block(blocker) {\n var unblock = blockers.push(blocker);\n\n if (blockers.length === 1) {\n window.addEventListener(BeforeUnloadEventType, promptBeforeUnload);\n }\n\n return function () {\n unblock(); // Remove the beforeunload listener so the document may\n // still be salvageable in the pagehide event.\n // See https://html.spec.whatwg.org/#unloading-documents\n\n if (!blockers.length) {\n window.removeEventListener(BeforeUnloadEventType, promptBeforeUnload);\n }\n };\n }\n };\n return history;\n}\n/**\r\n * Memory history stores the current location in memory. It is designed for use\r\n * in stateful non-browser environments like tests and React Native.\r\n *\r\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#creatememoryhistory\r\n */\n\nfunction createMemoryHistory(options) {\n if (options === void 0) {\n options = {};\n }\n\n var _options3 = options,\n _options3$initialEntr = _options3.initialEntries,\n initialEntries = _options3$initialEntr === void 0 ? ['/'] : _options3$initialEntr,\n initialIndex = _options3.initialIndex;\n var entries = initialEntries.map(function (entry) {\n var location = readOnly(_extends({\n pathname: '/',\n search: '',\n hash: '',\n state: null,\n key: createKey()\n }, typeof entry === 'string' ? parsePath(entry) : entry));\n process.env.NODE_ENV !== \"production\" ? warning(location.pathname.charAt(0) === '/', \"Relative pathnames are not supported in createMemoryHistory({ initialEntries }) (invalid entry: \" + JSON.stringify(entry) + \")\") : void 0;\n return location;\n });\n var index = clamp(initialIndex == null ? entries.length - 1 : initialIndex, 0, entries.length - 1);\n var action = Action.Pop;\n var location = entries[index];\n var listeners = createEvents();\n var blockers = createEvents();\n\n function createHref(to) {\n return typeof to === 'string' ? to : createPath(to);\n }\n\n function getNextLocation(to, state) {\n if (state === void 0) {\n state = null;\n }\n\n return readOnly(_extends({\n pathname: location.pathname,\n search: '',\n hash: ''\n }, typeof to === 'string' ? parsePath(to) : to, {\n state: state,\n key: createKey()\n }));\n }\n\n function allowTx(action, location, retry) {\n return !blockers.length || (blockers.call({\n action: action,\n location: location,\n retry: retry\n }), false);\n }\n\n function applyTx(nextAction, nextLocation) {\n action = nextAction;\n location = nextLocation;\n listeners.call({\n action: action,\n location: location\n });\n }\n\n function push(to, state) {\n var nextAction = Action.Push;\n var nextLocation = getNextLocation(to, state);\n\n function retry() {\n push(to, state);\n }\n\n process.env.NODE_ENV !== \"production\" ? warning(location.pathname.charAt(0) === '/', \"Relative pathnames are not supported in memory history.push(\" + JSON.stringify(to) + \")\") : void 0;\n\n if (allowTx(nextAction, nextLocation, retry)) {\n index += 1;\n entries.splice(index, entries.length, nextLocation);\n applyTx(nextAction, nextLocation);\n }\n }\n\n function replace(to, state) {\n var nextAction = Action.Replace;\n var nextLocation = getNextLocation(to, state);\n\n function retry() {\n replace(to, state);\n }\n\n process.env.NODE_ENV !== \"production\" ? warning(location.pathname.charAt(0) === '/', \"Relative pathnames are not supported in memory history.replace(\" + JSON.stringify(to) + \")\") : void 0;\n\n if (allowTx(nextAction, nextLocation, retry)) {\n entries[index] = nextLocation;\n applyTx(nextAction, nextLocation);\n }\n }\n\n function go(delta) {\n var nextIndex = clamp(index + delta, 0, entries.length - 1);\n var nextAction = Action.Pop;\n var nextLocation = entries[nextIndex];\n\n function retry() {\n go(delta);\n }\n\n if (allowTx(nextAction, nextLocation, retry)) {\n index = nextIndex;\n applyTx(nextAction, nextLocation);\n }\n }\n\n var history = {\n get index() {\n return index;\n },\n\n get action() {\n return action;\n },\n\n get location() {\n return location;\n },\n\n createHref: createHref,\n push: push,\n replace: replace,\n go: go,\n back: function back() {\n go(-1);\n },\n forward: function forward() {\n go(1);\n },\n listen: function listen(listener) {\n return listeners.push(listener);\n },\n block: function block(blocker) {\n return blockers.push(blocker);\n }\n };\n return history;\n} ////////////////////////////////////////////////////////////////////////////////\n// UTILS\n////////////////////////////////////////////////////////////////////////////////\n\nfunction clamp(n, lowerBound, upperBound) {\n return Math.min(Math.max(n, lowerBound), upperBound);\n}\n\nfunction promptBeforeUnload(event) {\n // Cancel the event.\n event.preventDefault(); // Chrome (and legacy IE) requires returnValue to be set.\n\n event.returnValue = '';\n}\n\nfunction createEvents() {\n var handlers = [];\n return {\n get length() {\n return handlers.length;\n },\n\n push: function push(fn) {\n handlers.push(fn);\n return function () {\n handlers = handlers.filter(function (handler) {\n return handler !== fn;\n });\n };\n },\n call: function call(arg) {\n handlers.forEach(function (fn) {\n return fn && fn(arg);\n });\n }\n };\n}\n\nfunction createKey() {\n return Math.random().toString(36).substr(2, 8);\n}\n/**\r\n * Creates a string URL path from the given pathname, search, and hash components.\r\n *\r\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createpath\r\n */\n\n\nfunction createPath(_ref) {\n var _ref$pathname = _ref.pathname,\n pathname = _ref$pathname === void 0 ? '/' : _ref$pathname,\n _ref$search = _ref.search,\n search = _ref$search === void 0 ? '' : _ref$search,\n _ref$hash = _ref.hash,\n hash = _ref$hash === void 0 ? '' : _ref$hash;\n if (search && search !== '?') pathname += search.charAt(0) === '?' ? search : '?' + search;\n if (hash && hash !== '#') pathname += hash.charAt(0) === '#' ? hash : '#' + hash;\n return pathname;\n}\n/**\r\n * Parses a string URL path into its separate pathname, search, and hash components.\r\n *\r\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#parsepath\r\n */\n\nfunction parsePath(path) {\n var parsedPath = {};\n\n if (path) {\n var hashIndex = path.indexOf('#');\n\n if (hashIndex >= 0) {\n parsedPath.hash = path.substr(hashIndex);\n path = path.substr(0, hashIndex);\n }\n\n var searchIndex = path.indexOf('?');\n\n if (searchIndex >= 0) {\n parsedPath.search = path.substr(searchIndex);\n path = path.substr(0, searchIndex);\n }\n\n if (path) {\n parsedPath.pathname = path;\n }\n }\n\n return parsedPath;\n}\n\nexport { Action, createBrowserHistory, createHashHistory, createMemoryHistory, createPath, parsePath };\n//# sourceMappingURL=index.js.map\n", "import { assertString, assertArrayOf, isFunction } from \"./typeChecking.js\";\n\nexport type RouteMatch<T = Record<string, any>> = {\n /**\n * The path string that triggered this match.\n */\n path: string;\n\n /**\n * The pattern satisfied by `path`.\n */\n pattern: string;\n\n /**\n * Named params as parsed from `path`.\n */\n params: Record<string, string | number>;\n\n /**\n * Query params as parsed from `path`.\n */\n query: Record<string, string | number | boolean>;\n\n /**\n * Metadata registered to this route.\n */\n meta: T;\n};\n\nexport enum FragTypes {\n Literal = 1,\n Param = 2,\n Wildcard = 3,\n NumericParam = 4,\n}\n\nexport type RouteFragment = {\n name: string;\n type: FragTypes;\n value: string | number | null;\n};\n\nexport type ParsedRoute<T> = {\n pattern: string;\n fragments: RouteFragment[];\n meta: T;\n};\n\nexport type RouteMatchOptions<T> = {\n willMatch?: (route: ParsedRoute<T>) => boolean;\n};\n\n/**\n * Separates a URL path into multiple fragments.\n *\n * @param path - A path string (e.g. `\"/api/users/5\"`)\n * @returns an array of fragments (e.g. `[\"api\", \"users\", \"5\"]`)\n */\nexport function splitPath(path: string): string[] {\n assertString(path, \"Expected `path` to be a string. Got type: %t, value: %v\");\n\n return path\n .split(\"/\")\n .map((f) => f.trim())\n .filter((f) => f !== \"\");\n}\n\n/**\n * Joins multiple URL path fragments into a single string.\n *\n * @param parts - One or more URL fragments (e.g. `[\"api\", \"users\", 5]`)\n * @returns a joined path (e.g. `\"api/users/5\"`)\n */\nexport function joinPath(parts: { toString(): string }[]): string {\n assertArrayOf(\n (part) => isFunction(part?.toString),\n parts,\n \"Expected `parts` to be an array of objects with a .toString() method. Got type: %t, value: %v\",\n );\n\n parts = parts.filter((x) => x).flatMap(String);\n\n let joined = parts.shift()?.toString();\n\n if (joined) {\n for (const part of parts.map((p) => p.toString())) {\n if (part.startsWith(\".\")) {\n // Resolve relative path against joined\n joined = resolvePath(joined, part);\n } else if (joined[joined.length - 1] !== \"/\") {\n if (part[0] !== \"/\") {\n joined += \"/\" + part;\n } else {\n joined += part;\n }\n } else {\n if (part[0] === \"/\") {\n joined += part.slice(1);\n } else {\n joined += part;\n }\n }\n }\n\n // Remove trailing slash (unless path is just '/')\n if (joined && joined !== \"/\" && joined.endsWith(\"/\")) {\n joined = joined.slice(0, joined.length - 1);\n }\n }\n\n return joined ?? \"\";\n}\n\nexport function resolvePath(base: string, part: string | null) {\n assertString(base, \"Expected `base` to be a string. Got type: %t, value: %v\");\n\n if (part == null) {\n part = base;\n base = \"\";\n }\n\n if (part.startsWith(\"/\")) {\n return part;\n }\n\n let resolved = base;\n\n while (true) {\n if (part.startsWith(\"..\")) {\n for (let i = resolved.length; i > 0; --i) {\n if (resolved[i] === \"/\" || i === 0) {\n resolved = resolved.slice(0, i);\n part = part.replace(/^\\.\\.\\/?/, \"\");\n break;\n }\n }\n } else if (part.startsWith(\".\")) {\n part = part.replace(/^\\.\\/?/, \"\");\n } else {\n break;\n }\n }\n\n return joinPath([resolved, part]);\n}\n\nexport function parseQueryParams(query: string): Record<string, string | number | boolean> {\n if (!query) return {};\n\n if (query.startsWith(\"?\")) {\n query = query.slice(1);\n }\n\n const entries = query\n .split(\"&\")\n .filter((x) => x.trim() !== \"\")\n .map((entry) => {\n const [key, value] = entry.split(\"=\").map((x) => x.trim());\n\n if (value.toLowerCase() === \"true\") {\n return [key, true] as const;\n }\n\n if (value.toLowerCase() === \"false\") {\n return [key, false] as const;\n }\n\n // Return value as a number if it parses as one.\n if (!isNaN(Number(value))) {\n return [key, Number(value)] as const;\n }\n\n return [key, value] as const;\n });\n\n return Object.fromEntries(entries);\n}\n\n/**\n * Returns the nearest match, or undefined if the path matches no route.\n *\n * @param url - Path to match against routes.\n * @param options - Options to customize how matching operates.\n */\nexport function matchRoutes<T>(\n routes: ParsedRoute<T>[],\n url: string,\n options: RouteMatchOptions<T> = {},\n): RouteMatch<T> | undefined {\n const [path, query] = url.split(\"?\");\n const parts = splitPath(path);\n\n routes: for (const route of routes) {\n const { fragments } = route;\n const hasWildcard = fragments[fragments.length - 1]?.type === FragTypes.Wildcard;\n\n if (!hasWildcard && fragments.length !== parts.length) {\n continue routes;\n }\n\n if (options.willMatch && !options.willMatch(route)) {\n continue routes;\n }\n\n const matched: RouteFragment[] = [];\n\n fragments: for (let i = 0; i < fragments.length; i++) {\n const part = parts[i];\n const frag = fragments[i];\n\n if (part == null && frag.type !== FragTypes.Wildcard) {\n continue routes;\n }\n\n switch (frag.type) {\n case FragTypes.Literal:\n if (frag.name.toLowerCase() === part.toLowerCase()) {\n matched.push(frag);\n break;\n } else {\n continue routes;\n }\n case FragTypes.Param:\n matched.push({ ...frag, value: part });\n break;\n case FragTypes.Wildcard:\n matched.push({ ...frag, value: parts.slice(i).join(\"/\") });\n break fragments;\n case FragTypes.NumericParam:\n if (!isNaN(Number(part))) {\n matched.push({ ...frag, value: Number(part) });\n break;\n } else {\n continue routes;\n }\n default:\n throw new Error(`Unknown fragment type: ${frag.type}`);\n }\n }\n\n const params = Object.create(null);\n\n for (const frag of matched) {\n if (frag.type === FragTypes.Param) {\n params[frag.name] = decodeURIComponent(frag.value as string);\n }\n\n if (frag.type === FragTypes.NumericParam) {\n params[frag.name] = frag.value as number;\n }\n\n if (frag.type === FragTypes.Wildcard) {\n params.wildcard = \"/\" + decodeURIComponent(frag.value as string);\n }\n }\n\n return {\n path: \"/\" + matched.map((f) => f.value).join(\"/\"),\n pattern:\n \"/\" +\n fragments\n .map((f) => {\n if (f.type === FragTypes.Param) {\n return `{${f.name}}`;\n }\n\n if (f.type === FragTypes.NumericParam) {\n return `{#${f.name}}`;\n }\n\n return f.name;\n })\n .join(\"/\"),\n params,\n query: parseQueryParams(query),\n meta: route.meta,\n };\n }\n}\n\n/**\n * Sort routes descending by specificity. Guarantees that the most specific route matches first\n * no matter the order in which they were added.\n *\n * Routes without named params and routes with more fragments are weighted more heavily.\n */\nexport function sortRoutes<T>(routes: ParsedRoute<T>[]): ParsedRoute<T>[] {\n const withoutParams = [];\n const withNumericParams = [];\n const withParams = [];\n const wildcard = [];\n\n for (const route of routes) {\n const { fragments } = route;\n\n if (fragments.some((f) => f.type === FragTypes.Wildcard)) {\n wildcard.push(route);\n } else if (fragments.some((f) => f.type === FragTypes.NumericParam)) {\n withNumericParams.push(route);\n } else if (fragments.some((f) => f.type === FragTypes.Param)) {\n withParams.push(route);\n } else {\n withoutParams.push(route);\n }\n }\n\n const bySizeDesc = (a: ParsedRoute<T>, b: ParsedRoute<T>) => {\n if (a.fragments.length > b.fragments.length) {\n return -1;\n } else {\n return 1;\n }\n };\n\n withoutParams.sort(bySizeDesc);\n withNumericParams.sort(bySizeDesc);\n withParams.sort(bySizeDesc);\n wildcard.sort(bySizeDesc);\n\n return [...withoutParams, ...withNumericParams, ...withParams, ...wildcard];\n}\n\n/**\n * Converts a route pattern into a set of matchable fragments.\n *\n * @param route - A route string (e.g. \"/api/users/{id}\")\n */\nexport function patternToFragments(pattern: string): RouteFragment[] {\n const parts = splitPath(pattern);\n const fragments = [];\n\n for (let i = 0; i < parts.length; i++) {\n const part = parts[i];\n\n if (part === \"*\") {\n if (i !== parts.length - 1) {\n throw new Error(`Wildcard must be at the end of a pattern. Received: ${pattern}`);\n }\n fragments.push({\n type: FragTypes.Wildcard,\n name: \"*\",\n value: null,\n });\n } else if (part.at(0) === \"{\" && part.at(-1) === \"}\") {\n fragments.push({\n type: part[1] === \"#\" ? FragTypes.NumericParam : FragTypes.Param,\n name: part[1] === \"#\" ? part.slice(2, -1) : part.slice(1, -1),\n value: null,\n });\n } else {\n fragments.push({\n type: FragTypes.Literal,\n name: part,\n value: part,\n });\n }\n }\n\n return fragments;\n}\n", "import { createBrowserHistory, createHashHistory, type History, type Listener } from \"history\";\nimport { getRenderHandle, m, renderMarkupToDOM, type DOMHandle, type Markup } from \"../markup.js\";\nimport {\n joinPath,\n matchRoutes,\n parseQueryParams,\n patternToFragments,\n resolvePath,\n sortRoutes,\n splitPath,\n} from \"../routing.js\";\nimport { $, $$ } from \"../state.js\";\nimport { getStoreSecrets, type Store, type StoreContext } from \"../store.js\";\nimport { isFunction, isString } from \"../typeChecking.js\";\nimport { type BuiltInStores, type Stringable } from \"../types.js\";\nimport { type View } from \"../view.js\";\nimport { DefaultView } from \"../views/default-view.js\";\nimport { ElementContext } from \"../app.js\";\n\n// ----- Types ----- //\n\nexport interface RouteMatchContext {\n /**\n * Returns the shared instance of `store`.\n */\n getStore<T extends Store<any, any>>(store: T): ReturnType<T>;\n\n /**\n * Returns the shared instance of a built-in store.\n */\n getStore<N extends keyof BuiltInStores>(name: N): BuiltInStores[N];\n\n /**\n * Redirects the user to a different route instead of matching the current one.\n */\n redirect(path: string): void;\n}\n\nexport interface Route {\n /**\n * The path or path fragment to match.\n */\n path: string;\n\n /**\n * Path to redirect to when this route is matched, or a callback function that returns such path.\n */\n redirect?: string | ((ctx: RouteRedirectContext) => string) | ((ctx: RouteRedirectContext) => Promise<string>);\n\n /**\n * View to display when this route is matched.\n */\n view?: View<any>;\n\n /**\n * Subroutes.\n */\n routes?: Route[];\n\n /**\n * Called after the match is identified but before it is acted on. Use this to set state, load data, etc.\n */\n beforeMatch?: (ctx: RouteMatchContext) => void | Promise<void>;\n}\n\nexport interface RouteConfig {\n pattern: string;\n meta: {\n redirect?: string | ((ctx: RouteRedirectContext) => string) | ((ctx: RouteRedirectContext) => Promise<string>);\n pattern?: string;\n layers?: RouteLayer[];\n beforeMatch?: (ctx: RouteMatchContext) => void | Promise<void>;\n };\n}\n\nexport interface RouteLayer {\n id: number;\n markup: Markup;\n}\n\n/**\n * Object passed to redirect callbacks. Contains information useful for determining how to redirect.\n */\nexport interface RouteRedirectContext {\n /**\n * The path as it appears in the URL bar.\n */\n path: string;\n\n /**\n * The pattern that this path was matched with.\n */\n pattern: string;\n\n /**\n * Named route params parsed from `path`.\n */\n params: Record<string, string | number | undefined>;\n\n /**\n * Query params parsed from `path`.\n */\n query: Record<string, string | number | boolean | undefined>;\n}\n\n/**\n * An active route layer whose markup has been initialized into a view.\n */\ninterface ActiveLayer {\n id: number;\n handle: DOMHandle;\n}\n\ninterface ParsedParams {\n [key: string]: string | number | boolean | (string | number | boolean | null)[] | null;\n}\n\ninterface ParsedQuery extends ParsedParams {}\n\ninterface NavigateOptions {\n /**\n * Replace the current item in the history stack instead of adding a new one.\n * The back button will send the user to the page they visited before this. Defaults to false.\n */\n replace?: boolean;\n\n /**\n * Preserve existing query params (if any) when navigating. Defaults to false.\n */\n preserveQuery?: boolean;\n}\n\ninterface RouterStoreOptions {\n routes: Route[];\n\n /**\n * Use hash-based routing if true.\n */\n hash?: boolean;\n\n /**\n * A history object from the `history` package.\n *\n * @see https://www.npmjs.com/package/history\n */\n history?: History;\n}\n\n// ----- Code ----- //\n\nexport function RouterStore(ctx: StoreContext<RouterStoreOptions>) {\n ctx.name = \"dolla/router\";\n\n const { appContext, elementContext } = getStoreSecrets(ctx);\n const render = ctx.getStore(\"render\");\n\n let history: History;\n\n if (ctx.options.history) {\n history = ctx.options.history;\n } else if (ctx.options.hash) {\n history = createHashHistory();\n } else {\n history = createBrowserHistory();\n }\n\n let layerId = 0;\n\n /**\n * Parses a route definition object into a set of matchable routes.\n *\n * @param route - Route config object.\n * @param layers - Array of parent layers. Passed when this function calls itself on nested routes.\n */\n function prepareRoute(route: Route, parents: Route[] = [], layers: RouteLayer[] = []) {\n if (!(typeof route === \"object\" && !Array.isArray(route)) || !(typeof route.path === \"string\")) {\n throw new TypeError(`Route configs must be objects with a 'path' string property. Got: ${route}`);\n }\n\n if (route.redirect && route.routes) {\n throw new Error(`Route cannot have both a 'redirect' and nested 'routes'.`);\n } else if (route.redirect && route.view) {\n throw new Error(`Route cannot have both a 'redirect' and a 'view'.`);\n } else if (!route.view && !route.routes && !route.redirect) {\n throw new Error(`Route must have a 'view', a 'redirect', or a set of nested 'routes'.`);\n }\n\n let parts: string[] = [];\n\n for (const parent of parents) {\n parts.push(...splitPath(parent.path));\n }\n\n parts.push(...splitPath(route.path));\n\n // Remove trailing wildcard for joining with nested routes.\n if (parts[parts.length - 1] === \"*\") {\n parts.pop();\n }\n\n const routes: RouteConfig[] = [];\n\n if (route.redirect) {\n let redirect = route.redirect;\n\n if (isString(redirect)) {\n redirect = resolvePath(joinPath(parts), redirect);\n\n if (!redirect.startsWith(\"/\")) {\n redirect = \"/\" + redirect;\n }\n }\n\n routes.push({\n pattern: \"/\" + joinPath([...parts, ...splitPath(route.path)]),\n meta: {\n redirect,\n },\n });\n\n return routes;\n }\n\n let view: View<any> = DefaultView;\n\n if (typeof route.view === \"function\") {\n view = route.view;\n } else if (route.view) {\n throw new TypeError(`Route '${route.path}' expected a view function or undefined. Got: ${route.view}`);\n }\n\n const markup = m(view);\n const layer: RouteLayer = { id: layerId++, markup };\n\n // Parse nested routes if they exist.\n if (route.routes) {\n for (const subroute of route.routes) {\n routes.push(...prepareRoute(subroute, [...parents, route], [...layers, layer]));\n }\n } else {\n routes.push({\n pattern: parent ? joinPath([...parents.map((p) => p.path), route.path]) : route.path,\n meta: {\n pattern: route.path,\n layers: [...layers, layer],\n beforeMatch: route.beforeMatch,\n },\n });\n }\n\n return routes;\n }\n\n const routes = sortRoutes(\n ctx.options.routes\n .flatMap((route) => prepareRoute(route))\n .map((route) => ({\n pattern: route.pattern,\n meta: route.meta,\n fragments: patternToFragments(route.pattern),\n })),\n );\n\n // Test redirects to make sure all possible redirect targets actually exist.\n for (const route of routes) {\n if (route.meta.redirect) {\n let redirectPath: string;\n\n if (isFunction(route.meta.redirect)) {\n // throw new Error(`Redirect functions are not yet supported.`);\n // Just allow, though it could fail later. Best not to call the function and cause potential side effects.\n } else if (isString(route.meta.redirect)) {\n redirectPath = route.meta.redirect;\n\n const match = matchRoutes(routes, redirectPath, {\n willMatch(r) {\n return r !== route;\n },\n });\n\n if (!match) {\n throw new Error(`Found a redirect to an undefined URL. From '${route.pattern}' to '${route.meta.redirect}'`);\n }\n } else {\n throw new TypeError(`Expected a string or redirect function. Got: ${route.meta.redirect}`);\n }\n }\n }\n\n ctx.onConnected(() => {\n ctx.info(\"Routes registered:\", routes);\n });\n\n const $$pattern = $$<string | null>(null);\n const $$path = $$(\"\");\n const $$params = $$<ParsedParams>({});\n const $$query = $$<ParsedQuery>(parseQueryParams(window.location.search));\n\n // Update URL when query changes\n ctx.observe($$query, (current) => {\n const params = new URLSearchParams();\n\n for (const key in current) {\n params.set(key, String(current[key]));\n }\n\n const search = \"?\" + params.toString();\n\n if (search != history.location.search) {\n history.replace({\n pathname: history.location.pathname,\n search,\n });\n }\n });\n\n ctx.onConnected(() => {\n history.listen(onRouteChange);\n onRouteChange(history);\n\n ctx.info(\"Intercepting <a> clicks within root element:\", appContext.rootElement);\n catchLinks(appContext.rootElement!, (anchor) => {\n let href = anchor.getAttribute(\"href\")!;\n\n ctx.info(\"Intercepted link click\", anchor, href);\n\n if (!/^https?:\\/\\/|^\\//.test(href)) {\n href = joinPath([history.location.pathname, href]);\n }\n\n history.push(href);\n });\n });\n\n let activeLayers: ActiveLayer[] = [];\n let lastQuery: string;\n\n /**\n * Run when the location changes. Diffs and mounts new routes and updates\n * the $path, $route, $params and $query states accordingly.\n */\n const onRouteChange: Listener = async ({ location }) => {\n // Update query params if they've changed.\n if (location.search !== lastQuery) {\n lastQuery = location.search;\n\n $$query.set(parseQueryParams(location.search));\n }\n\n const matched = matchRoutes(routes, location.pathname);\n\n if (!matched) {\n $$pattern.set(null);\n $$path.set(location.pathname);\n $$params.set({\n wildcard: location.pathname,\n });\n return;\n }\n\n if (matched.meta.beforeMatch) {\n await matched.meta.beforeMatch({\n getStore(store: keyof BuiltInStores | Store<any, any>) {\n let name: string;\n\n if (typeof store === \"string\") {\n name = store as keyof BuiltInStores;\n } else {\n name = store.name;\n }\n\n if (typeof store !== \"string\") {\n let ec: ElementContext | undefined = elementContext;\n while (ec) {\n if (ec.stores.has(store)) {\n return ec.stores.get(store)?.instance!.exports;\n }\n ec = ec.parent;\n }\n }\n\n if (appContext.stores.has(store)) {\n const _store = appContext.stores.get(store)!;\n\n if (!_store.instance) {\n appContext.crashCollector.crash({\n componentName: ctx.name,\n error: new Error(`Store '${name}' is not registered on this app.`),\n });\n }\n\n return _store.instance!.exports;\n }\n\n appContext.crashCollector.crash({\n componentName: ctx.name,\n error: new Error(`Store '${name}' is not registered on this app.`),\n });\n },\n redirect: (path) => {\n // TODO: Implement\n throw new Error(`Redirect not yet implemented.`);\n },\n });\n }\n\n ctx.info(`Matched route: '${matched.pattern}' ('${matched.path}')`);\n\n if (matched.meta.redirect != null) {\n if (typeof matched.meta.redirect === \"string\") {\n const path = replaceParams(matched.meta.redirect, matched.params);\n ctx.info(`Redirecting to: '${path}'`);\n history.replace(path);\n } else if (typeof matched.meta.redirect === \"function\") {\n const redirectContext: RouteRedirectContext = {\n path: matched.path,\n pattern: matched.pattern,\n params: matched.params,\n query: matched.query,\n };\n let path = await matched.meta.redirect(redirectContext);\n if (typeof path !== \"string\") {\n throw new Error(`Redirect function must return a path to redirect to.`);\n }\n if (!path.startsWith(\"/\")) {\n // Not absolute. Resolve against matched path.\n path = resolvePath(matched.path, path);\n }\n ctx.info(`Redirecting to: '${path}'`);\n history.replace(path);\n } else {\n throw new TypeError(`Redirect must either be a path string or a function.`);\n }\n } else {\n $$path.set(matched.path);\n $$params.set(matched.params);\n\n if (matched.pattern !== $$pattern.get()) {\n $$pattern.set(matched.pattern);\n\n const layers = matched.meta.layers!;\n\n // Diff and update route layers.\n for (let i = 0; i < layers.length; i++) {\n const matchedLayer = layers[i];\n const activeLayer = activeLayers[i];\n\n if (activeLayer?.id !== matchedLayer.id) {\n ctx.info(`Replacing layer @${i} (active ID: ${activeLayer?.id}, matched ID: ${matchedLayer.id})`);\n\n activeLayers = activeLayers.slice(0, i);\n\n const parentLayer = activeLayers[activeLayers.length - 1];\n const renderContext = { appContext, elementContext };\n\n const rendered = renderMarkupToDOM(matchedLayer.markup, renderContext);\n const handle = getRenderHandle(rendered);\n\n if (activeLayer && activeLayer.handle.connected) {\n // Disconnect first mismatched active layer.\n activeLayer.handle.disconnect();\n }\n\n if (parentLayer) {\n parentLayer.handle.setChildren(rendered);\n } else {\n appContext.rootView!.setChildren(rendered);\n }\n\n // Push and connect new active layer.\n activeLayers.push({ id: matchedLayer.id, handle });\n }\n }\n }\n }\n };\n\n function navigate(path: Stringable, options?: NavigateOptions): void;\n function navigate(fragments: Stringable[], options?: NavigateOptions): void;\n\n function navigate(path: Stringable | Stringable[], options: NavigateOptions = {}) {\n let joined: string;\n\n if (Array.isArray(path)) {\n joined = joinPath(path);\n } else {\n joined = path.toString();\n }\n\n joined = resolvePath(history.location.pathname, joined);\n\n if (options.preserveQuery) {\n joined += history.location.search;\n }\n\n if (options.replace) {\n history.replace(joined);\n } else {\n history.push(joined);\n }\n }\n\n return {\n /**\n * The currently matched route pattern, if any.\n */\n $pattern: $($$pattern),\n\n /**\n * The current URL path.\n */\n $path: $($$path),\n\n /**\n * The current named path params.\n */\n $params: $($$params),\n\n /**\n * The current query params. Changes to this object will be reflected in the URL.\n */\n $$query,\n\n /**\n * Navigate backward. Pass a number of steps to hit the back button that many times.\n */\n back(steps = 1) {\n history.go(-steps);\n },\n\n /**\n * Navigate forward. Pass a number of steps to hit the forward button that many times.\n */\n forward(steps = 1) {\n history.go(steps);\n },\n\n /**\n * Navigates to another route.\n *\n * @example\n * navigate(\"/login\"); // navigate to `/login`\n * navigate([\"/users\", 215], { replace: true }); // replace current history entry with `/users/215`\n *\n * @param args - One or more path segments optionally followed by an options object.\n */\n navigate,\n\n /**\n * Updates a query param in place.\n */\n // updateQuery(key: string, value: string) {},\n\n /**\n * Updates a route param in place.\n */\n // updateParam(key: string, value: string) {},\n };\n}\n\nconst safeExternalLink = /(noopener|noreferrer) (noopener|noreferrer)/;\nconst protocolLink = /^[\\w-_]+:/;\n\n/**\n * Intercepts links within the root node.\n *\n * This is adapted from https://github.com/choojs/nanohref/blob/master/index.js\n *\n * @param root - Element under which to intercept link clicks\n * @param callback - Function to call when a click event is intercepted\n * @param _window - (optional) Override for global window object\n */\nexport function catchLinks(root: HTMLElement, callback: (anchor: HTMLAnchorElement) => void, _window = window) {\n function traverse(node: HTMLElement | null): HTMLAnchorElement | null {\n if (!node || node === root) {\n return null;\n }\n\n if (node.localName !== \"a\" || (node as any).href === undefined) {\n return traverse(node.parentNode as HTMLElement | null);\n }\n\n return node as HTMLAnchorElement;\n }\n\n function handler(e: MouseEvent) {\n if ((e.button && e.button !== 0) || e.ctrlKey || e.metaKey || e.altKey || e.shiftKey || e.defaultPrevented) {\n return;\n }\n\n const anchor = traverse(e.target as HTMLElement);\n\n if (!anchor) {\n return;\n }\n\n if (\n _window.location.protocol !== anchor.protocol ||\n _window.location.hostname !== anchor.hostname ||\n _window.location.port !== anchor.port ||\n anchor.hasAttribute(\"data-router-ignore\") ||\n anchor.hasAttribute(\"download\") ||\n (anchor.getAttribute(\"target\") === \"_blank\" && safeExternalLink.test(anchor.getAttribute(\"rel\")!)) ||\n protocolLink.test(anchor.getAttribute(\"href\")!)\n ) {\n return;\n }\n\n e.preventDefault();\n callback(anchor);\n }\n\n root.addEventListener(\"click\", handler);\n\n return function cancel() {\n root.removeEventListener(\"click\", handler);\n };\n}\n\n/**\n * Replace route pattern param placeholders with real matched values.\n */\nfunction replaceParams(path: string, params: Record<string, string | number>) {\n for (const key in params) {\n const value = params[key].toString();\n path = path.replace(`{${key}}`, value).replace(`{#${key}}`, value);\n }\n\n return path;\n}\n", "import { $, $$, isReadable, observe, type Readable } from \"../state.js\";\nimport { type StoreContext } from \"../store.js\";\nimport { assertObject, isFunction, isObject, isString, typeOf } from \"../typeChecking.js\";\nimport { type Stringable } from \"../types.js\";\nimport { deepEqual } from \"../utils.js\";\n\n// ----- Types ----- //\n\n// TODO: Is there a good way to represent infinitely nested recursive types?\n/**\n * An object where values are either a translated string or another nested Translation object.\n */\ntype Translation = Record<string, string | Record<string, string | Record<string, string | Record<string, string>>>>;\n\nexport interface LanguageConfig {\n name: string;\n\n /**\n * Path to a JSON file with translated strings for this language, a plain object containing said translations, or a callback function that returns them.\n */\n translations: string | Translation | (() => Translation) | (() => Promise<Translation>);\n}\n\ntype LanguageOptions = {\n languages: LanguageConfig[];\n\n /**\n * Default language to load on startup\n */\n defaultLanguage?: string;\n};\n\n// ----- Code ----- //\n\nexport function LanguageStore(ctx: StoreContext<LanguageOptions>) {\n ctx.name = \"dolla/language\";\n\n const languages = new Map<string, LanguageConfig>();\n const cache = new Map<string, Translation>();\n\n // Convert languages into Language instances.\n ctx.options.languages.forEach((entry) => {\n languages.set(entry.name, entry);\n });\n\n ctx.info(\n `App supports ${languages.size} language${languages.size === 1 ? \"\" : \"s\"}: '${[...languages.keys()].join(\"', '\")}'`,\n );\n\n async function getTranslation(config: LanguageConfig) {\n if (!cache.has(config.name)) {\n let fn: () => Promise<Translation>;\n\n if (isString(config.translations)) {\n fn = async () => {\n return fetch(config.translations as string).then((res) => res.json());\n };\n } else if (isFunction(config.translations)) {\n fn = async () => (config.translations as () => Translation)();\n } else if (isObject(config.translations)) {\n fn = async () => config.translations as Translation;\n } else {\n throw new TypeError(\n `Translation of '${\n config.name\n }' must be an object of translated strings, a path to an object of translated strings, a function that returns one, or an async function that resolves to one. Got type: ${typeOf(\n config.translations,\n )}, value: ${config.translations}`,\n );\n }\n\n try {\n const translation = await fn();\n assertObject(\n translation,\n `Expected '${config.name}' translations to resolve to an object. Got type: %t, value: %v`,\n );\n cache.set(config.name, translation);\n } catch (err) {\n throw err;\n }\n }\n\n return cache.get(config.name);\n }\n\n const $$isLoaded = $$(false);\n const $$language = $$<string>();\n const $$translation = $$<Translation>();\n\n // Fallback labels for missing state and data.\n const $noLanguageValue = $(\"[NO LANGUAGE SET]\");\n\n // TODO: Keep an eye on this for memory leaks. Keeping a bunch of unused alternates with varied values might be an issue.\n const translationCache: [\n key: string,\n values: Record<string, Stringable | Readable<Stringable>> | undefined,\n readable: Readable<string>,\n ][] = [];\n\n function getCached(\n key: string,\n values?: Record<string, Stringable | Readable<Stringable>>,\n ): Readable<string> | undefined {\n for (const entry of translationCache) {\n if (entry[0] === key && deepEqual(entry[1], values)) {\n return entry[2];\n }\n }\n }\n\n /**\n * Replaces {{placeholders}} with values in translated strings.\n */\n function replaceMustaches(template: string, values: Record<string, Stringable>) {\n for (const name in values) {\n template = template.replace(`{{${name}}}`, String(values[name]));\n }\n return template;\n }\n\n async function setLanguage(tag: string) {\n let realTag!: string;\n\n if (tag === \"auto\") {\n let tags = [];\n\n if (typeof navigator === \"object\") {\n const nav = navigator as any;\n\n if (nav.languages?.length > 0) {\n tags.push(...nav.languages);\n } else if (nav.language) {\n tags.push(nav.language);\n } else if (nav.browserLanguage) {\n tags.push(nav.browserLanguage);\n } else if (nav.userLanguage) {\n tags.push(nav.userLanguage);\n }\n }\n\n for (const tag of tags) {\n if (languages.has(tag)) {\n // Found a matching language.\n realTag = tag;\n }\n }\n } else {\n // Tag is the actual tag to set.\n if (languages.has(tag)) {\n realTag = tag;\n }\n }\n\n if (realTag == null) {\n const firstLanguage = ctx.options.languages[0];\n if (firstLanguage) {\n realTag = firstLanguage.name;\n }\n }\n\n if (!realTag || !languages.has(realTag)) {\n throw new Error(`Language '${tag}' is not configured for this app.`);\n }\n\n const lang = languages.get(realTag)!;\n\n try {\n const translation = await getTranslation(lang);\n\n $$translation.set(translation);\n $$language.set(realTag);\n\n ctx.info(\"set language to \" + realTag);\n } catch (error) {\n if (error instanceof Error) {\n ctx.crash(error);\n }\n }\n }\n\n // TODO: Determine and load default language.\n setLanguage(ctx.options.defaultLanguage ?? \"auto\").then(() => {\n $$isLoaded.set(true);\n });\n\n return {\n loaded: new Promise<void>((resolve, reject) => {\n const stop = observe($$isLoaded, (isLoaded) => {\n if (isLoaded) {\n setTimeout(() => {\n stop();\n resolve();\n }, 0);\n }\n });\n }),\n\n $isLoaded: $($$isLoaded),\n $currentLanguage: $($$language),\n supportedLanguages: [...languages.keys()],\n\n setLanguage,\n\n /**\n * Returns a Readable of the translated value.\n\n * @param key - Key to the translated value.\n * @param values - A map of {{placeholder}} names and the values to replace them with.\n */\n translate(key: string, values?: Record<string, Stringable | Readable<Stringable>>): Readable<string> {\n if (!$$language.get()) {\n return $noLanguageValue;\n }\n\n const cached = getCached(key, values);\n if (cached) {\n return cached;\n }\n\n if (values) {\n const readableValues: Record<string, Readable<any>> = {};\n\n for (const [key, value] of Object.entries<any>(values)) {\n if (isReadable(value)) {\n readableValues[key] = value;\n }\n }\n\n // This looks extremely weird, but it creates a joined state\n // that contains the translation with interpolated observable values.\n const readableEntries = Object.entries(readableValues);\n if (readableEntries.length > 0) {\n const readables = readableEntries.map((x) => x[1]);\n const $merged = $([$$translation, ...readables], (t, ...entryValues) => {\n const entries = entryValues.map((_, i) => readableEntries[i]);\n const mergedValues = {\n ...values,\n };\n\n for (let i = 0; i < entries.length; i++) {\n const key = entries[i][0];\n mergedValues[key] = entryValues[i];\n }\n\n const result = resolve(t, key) || `[NO TRANSLATION: ${key}]`;\n return replaceMustaches(result, mergedValues);\n });\n\n translationCache.push([key, values, $merged]);\n\n return $merged;\n }\n }\n\n const $replaced = $($$translation, (t) => {\n let result = resolve(t, key) || `[NO TRANSLATION: ${key}]`;\n\n if (values) {\n result = replaceMustaches(result, values);\n }\n\n return result;\n });\n\n translationCache.push([key, values, $replaced]);\n\n return $replaced;\n },\n };\n}\n\nfunction resolve(object: any, key: string) {\n const parsed = String(key)\n .split(/[\\.\\[\\]]/)\n .filter((part) => part.trim() !== \"\");\n let value = object;\n\n while (parsed.length > 0) {\n const part = parsed.shift()!;\n\n if (value != null) {\n value = value[part];\n } else {\n value = undefined;\n }\n }\n\n return value;\n}\n", "import { isObject } from \"../typeChecking.js\";\nimport { type StoreContext } from \"../store.js\";\n\ninterface HTTPStoreOptions {\n /**\n * The fetch function to use for requests. Pass this to mock for testing.\n */\n fetch?: typeof window.fetch;\n}\n\n/**\n * A simple HTTP client with middleware support. Middleware applies to all requests made through this store,\n * so it's the perfect way to handle things like auth headers and permission checks for API calls.\n */\nexport function HTTPStore(ctx: StoreContext<HTTPStoreOptions>) {\n ctx.name = \"dolla/http\";\n\n const fetch = ctx.options.fetch ?? getDefaultFetch();\n\n const middleware: HTTPMiddleware[] = [];\n\n async function request<ResBody, ReqBody>(method: string, uri: string, options?: RequestOptions<any>) {\n return makeRequest<ResBody, ReqBody>({ ...options, method, uri, middleware, fetch });\n }\n\n return {\n /**\n * Adds a new middleware that will apply to subsequent requests.\n * Returns a function to remove this middleware.\n *\n * @param middleware - A middleware function that will intercept requests.\n */\n middleware(fn: HTTPMiddleware) {\n middleware.push(fn);\n\n // Call returned function to remove this middleware for subsequent requests.\n return function remove() {\n middleware.splice(middleware.indexOf(fn), 1);\n };\n },\n\n async get<ResBody = unknown>(uri: string, options?: RequestOptions<never>) {\n return request<ResBody, never>(\"get\", uri, options);\n },\n\n async put<ResBody = unknown, ReqBody = unknown>(uri: string, options?: RequestOptions<ReqBody>) {\n return request<ResBody, ReqBody>(\"put\", uri, options);\n },\n\n async patch<ResBody = unknown, ReqBody = unknown>(uri: string, options?: RequestOptions<ReqBody>) {\n return request<ResBody, ReqBody>(\"patch\", uri, options);\n },\n\n async post<ResBody = unknown, ReqBody = unknown>(uri: string, options?: RequestOptions<ReqBody>) {\n return request<ResBody, ReqBody>(\"post\", uri, options);\n },\n\n async delete<ResBody = unknown>(uri: string, options?: RequestOptions<never>) {\n return request<ResBody, never>(\"delete\", uri, options);\n },\n\n async head<ResBody = unknown, ReqBody = unknown>(uri: string, options?: RequestOptions<ReqBody>) {\n return request<ResBody, ReqBody>(\"head\", uri, options);\n },\n\n async options<ResBody = unknown, ReqBody = unknown>(uri: string, options?: RequestOptions<ReqBody>) {\n return request<ResBody, ReqBody>(\"options\", uri, options);\n },\n\n async trace<ResBody = unknown, ReqBody = unknown>(uri: string, options?: RequestOptions<ReqBody>) {\n return request<ResBody, ReqBody>(\"trace\", uri, options);\n },\n };\n}\n\nfunction getDefaultFetch(): typeof window.fetch {\n if (typeof window !== \"undefined\" && window.fetch) {\n return window.fetch.bind(window);\n }\n\n if (typeof global !== \"undefined\" && global.fetch) {\n return global.fetch.bind(global);\n }\n\n throw new Error(\"Running in neither browser nor node. Please run this app in one of the supported environments.\");\n}\n\n/*====================*\\\n|| Request ||\n\\*====================*/\n\nexport type HTTPMiddleware = (\n request: HTTPRequest<unknown>,\n next: () => Promise<HTTPResponse<unknown>>,\n) => void | Promise<void>;\n\ninterface RequestOptions<ReqBody> {\n /**\n * Body to send with the request.\n */\n body?: ReqBody;\n\n /**\n * Headers to send with the request.\n */\n headers?: Record<string, any> | Headers;\n\n /**\n * Query params to interpolate into the URL.\n */\n query?: Record<string, any> | URLSearchParams;\n}\n\ninterface HTTPRequest<Body> {\n method: string;\n uri: string;\n readonly sameOrigin: boolean;\n headers: Headers;\n query: URLSearchParams;\n body: Body;\n}\n\ninterface HTTPResponse<Body> {\n method: string;\n uri: string;\n status: number;\n statusText: string;\n headers: Record<string, string>;\n body: Body;\n}\n\nclass HTTPResponseError extends Error {\n response;\n\n constructor(response: HTTPResponse<any>) {\n const { status, statusText, method, uri } = response;\n const message = `${status} ${statusText}: Request failed (${method.toUpperCase()} ${uri})`;\n\n super(message);\n\n this.response = response;\n }\n}\n\ninterface MakeRequestConfig<ReqBody> extends RequestOptions<ReqBody> {\n method: string;\n uri: string;\n middleware: HTTPMiddleware[];\n fetch: typeof window.fetch;\n}\n\nasync function makeRequest<ResBody, ReqBody>(config: MakeRequestConfig<ReqBody>) {\n const { headers, query, fetch, middleware } = config;\n\n const request: HTTPRequest<ReqBody> = {\n method: config.method,\n uri: config.uri,\n get sameOrigin() {\n return !request.uri.startsWith(\"http\");\n },\n query: new URLSearchParams(),\n headers: new Headers(),\n body: config.body!,\n };\n\n // Read headers into request\n if (headers) {\n if (headers instanceof Map || headers instanceof Headers) {\n headers.forEach((value, key) => {\n request.headers.set(key, value);\n });\n } else if (headers != null && typeof headers === \"object\" && !Array.isArray(headers)) {\n for (const name in headers) {\n const value = headers[name];\n if (value instanceof Date) {\n request.headers.set(name, value.toISOString());\n } else if (value != null) {\n request.headers.set(name, String(value));\n }\n }\n } else {\n throw new TypeError(`Unknown headers type. Got: ${headers}`);\n }\n }\n\n // Read query params into request\n if (query) {\n if (query instanceof Map || query instanceof URLSearchParams) {\n query.forEach((value, key) => {\n request.query.set(key, value);\n });\n } else if (query != null && typeof query === \"object\" && !Array.isArray(query)) {\n for (const name in query) {\n const value = query[name];\n if (value instanceof Date) {\n request.query.set(name, value.toISOString());\n } else if (value != null) {\n request.query.set(name, String(value));\n }\n }\n } else {\n throw new TypeError(`Unknown query params type. Got: ${query}`);\n }\n }\n\n let response: HTTPResponse<ResBody>;\n\n // This is the function that performs the actual request after the final middleware.\n const handler = async () => {\n const query = request.query.toString();\n const fullURL = query.length > 0 ? request.uri + \"?\" + query : request.uri;\n\n let reqBody: BodyInit;\n\n if (!request.headers.has(\"content-type\") && isObject(request.body)) {\n // Auto-detect JSON bodies and encode as a string with correct headers.\n request.headers.set(\"content-type\", \"application/json\");\n reqBody = JSON.stringify(request.body);\n } else {\n reqBody = request.body as BodyInit;\n }\n\n const fetched = await fetch(fullURL, {\n method: request.method,\n headers: request.headers,\n body: reqBody,\n });\n\n // Auto-parse response body based on content-type header\n const headers = Object.fromEntries<string>(fetched.headers.entries());\n const contentType = headers[\"content-type\"];\n\n let body: ResBody;\n\n if (contentType?.includes(\"application/json\")) {\n body = await fetched.json();\n } else if (contentType?.includes(\"application/x-www-form-urlencoded\")) {\n body = (await fetched.formData()) as ResBody;\n } else {\n body = (await fetched.text()) as ResBody;\n }\n\n response = {\n method: request.method,\n uri: request.uri,\n status: fetched.status,\n statusText: fetched.statusText,\n headers: headers,\n body,\n };\n };\n\n if (middleware.length > 0) {\n const mount = (index = 0) => {\n const current = middleware[index];\n const next = middleware[index + 1] ? mount(index + 1) : handler;\n\n return async () =>\n current(request, async () => {\n await next();\n return response;\n });\n };\n\n await mount()();\n } else {\n await handler();\n }\n\n if (response!.status < 200 || response!.status >= 400) {\n throw new HTTPResponseError(response!);\n }\n\n return response!;\n}\n", "import { type DOMHandle } from \"../markup.js\";\nimport { $$, observe, type Writable } from \"../state.js\";\nimport { getStoreSecrets, type StoreContext } from \"../store.js\";\nimport { initView, type View } from \"../view.js\";\n\nexport interface DialogProps {\n /**\n * Whether the dialog is currently open.\n */\n $$open: Writable<boolean>;\n\n /**\n * Calls `callback` immediately after dialog has been connected.\n */\n transitionIn: (callback: () => Promise<void>) => void;\n\n /**\n * Calls `callback` and awaits its Promise before disconnecting the dialog.\n */\n transitionOut: (callback: () => Promise<void>) => void;\n}\n\nexport interface OpenDialog {\n instance: DOMHandle;\n transitionInCallback?: () => Promise<void>;\n transitionOutCallback?: () => Promise<void>;\n}\n\n/**\n * Manages dialogs. Also known as modals.\n * TODO: Describe this better.\n */\nexport function DialogStore(ctx: StoreContext) {\n ctx.name = \"dolla/dialog\";\n\n const { appContext, elementContext } = getStoreSecrets(ctx);\n\n const render = ctx.getStore(\"render\");\n\n const container = document.createElement(\"div\");\n container.style.position = \"fixed\";\n container.style.top = \"0\";\n container.style.right = \"0\";\n container.style.bottom = \"0\";\n container.style.left = \"0\";\n container.style.zIndex = \"99999\";\n\n /**\n * A first-in-last-out queue of dialogs. The last one appears on top.\n * This way if a dialog opens another dialog the new dialog stacks.\n */\n const $$dialogs = $$<OpenDialog[]>([]);\n\n let activeDialogs: OpenDialog[] = [];\n\n function dialogChangedCallback() {\n // Container is only connected to the DOM when there is at least one dialog to display.\n if (activeDialogs.length > 0) {\n if (!container.parentNode) {\n document.body.appendChild(container);\n }\n } else {\n if (container.parentNode) {\n document.body.removeChild(container);\n }\n }\n }\n\n // Diff dialogs when value is updated, adding and removing dialogs as necessary.\n ctx.observe($$dialogs, (dialogs) => {\n render.update(() => {\n let removed: OpenDialog[] = [];\n let added: OpenDialog[] = [];\n\n for (const dialog of activeDialogs) {\n if (!dialogs.includes(dialog)) {\n removed.push(dialog);\n }\n }\n\n for (const dialog of dialogs) {\n if (!activeDialogs.includes(dialog)) {\n added.push(dialog);\n }\n }\n\n for (const dialog of removed) {\n if (dialog.transitionOutCallback) {\n dialog.transitionOutCallback().then(() => {\n dialog.instance.disconnect();\n activeDialogs.splice(activeDialogs.indexOf(dialog), 1);\n dialogChangedCallback();\n });\n } else {\n dialog.instance.disconnect();\n activeDialogs.splice(activeDialogs.indexOf(dialog), 1);\n }\n }\n\n for (const dialog of added) {\n dialog.instance.connect(container);\n\n if (dialog.transitionInCallback) {\n dialog.transitionInCallback();\n }\n\n activeDialogs.push(dialog);\n }\n\n dialogChangedCallback();\n });\n });\n\n ctx.onDisconnected(() => {\n if (container.parentNode) {\n document.body.removeChild(container);\n }\n });\n\n function open<P extends DialogProps>(view: View<P>, props?: Omit<P, keyof DialogProps>) {\n const $$open = $$(true);\n\n let dialog: OpenDialog | undefined;\n\n let transitionInCallback: (() => Promise<void>) | undefined;\n let transitionOutCallback: (() => Promise<void>) | undefined;\n\n let instance = initView({\n view: view as View<unknown>,\n appContext,\n elementContext,\n props: {\n ...props,\n $$open,\n transitionIn: (callback) => {\n transitionInCallback = callback;\n },\n transitionOut: (callback) => {\n transitionOutCallback = callback;\n },\n } as P,\n });\n\n dialog = {\n instance,\n\n // These must be getters because the fns passed to props aren't called until before connect.\n get transitionInCallback() {\n return transitionInCallback;\n },\n get transitionOutCallback() {\n return transitionOutCallback;\n },\n };\n\n $$dialogs.update((current) => {\n return [...current, dialog!];\n });\n\n const stopObserver = observe($$open, (value) => {\n if (!value) {\n closeDialog();\n }\n });\n\n function closeDialog() {\n $$dialogs.update((current) => {\n return current.filter((x) => x !== dialog);\n });\n dialog = undefined;\n\n stopObserver();\n }\n\n return closeDialog;\n }\n\n return {\n open,\n };\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAa,WAAO,eAAe,SAAQ,cAAa,EAAC,OAAM,KAAE,CAAC;AAAE,QAAI,iBAAe,2BAAU;AAAC,eAAS,EAAEA,IAAE,GAAE;AAAC,YAAI,IAAE,CAAC,GAAE,IAAE,MAAG,IAAE,OAAG,IAAE;AAAO,YAAG;AAAC,mBAAQ,GAAE,IAAEA,GAAE,OAAO,QAAQ,EAAE,GAAE,EAAE,KAAG,IAAE,EAAE,KAAK,GAAG,UAAQ,EAAE,KAAK,EAAE,KAAK,GAAE,EAAE,KAAG,EAAE,WAAS,KAAI,IAAE;AAAG;AAAA,QAAC,SAAOA,IAAE;AAAC,cAAE,MAA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ACA,IAAI,wBAAwB;AAC1B,eAAO;AAAA,MACT;AAAA,IACF;AAEA,cAAU,OAAO,CAAC,YAAY;AAC5B,aAAO,CAAC,GAAG,SAAS,MAAO;AAAA,IAC7B,CAAC;AAED,UAAM,eAAe,QAAQ,QAAQ,CAAC,UAAU;AAC9C,UAAI,CAAC,OAAO;AACV,oBAAY;AAAA,MACd;AAAA,IACF,CAAC;AAED,aAAS,cAAc;AACrB,gBAAU,OAAO,CAAC,YAAY;AAC5B,eAAO,QAAQ,OAAO,CAAC,MAAM,MAAM,MAAM;AAAA,MAC3C,CAAC;AACD,eAAS;AAET,mBAAa;AAAA,IACf;AAEA,WAAO;AAAA,EACT;AAEA,SAAO;AAAA,IACL;AAAA,EACF;AACF;",
6
- "names": ["a", "b", "c", "d", "e", "m", "colorHash", "process", "object", "readable", "callback", "parent", "parent", "value", "key", "parent", "parent", "parent", "parent", "parent", "parent", "x", "parent", "SECRETS", "SECRETS", "resolve", "resolve", "options", "Action", "cond", "window", "hash", "index", "action", "location", "hash", "parent", "routes", "tag", "resolve", "key", "fetch", "query", "headers"]
4
+ "sourcesContent": ["\"use strict\";Object.defineProperty(exports,\"__esModule\",{value:!0});var _slicedToArray=function(){function a(a,b){var c=[],d=!0,e=!1,f=void 0;try{for(var g,h=a[Symbol.iterator]();!(d=(g=h.next()).done)&&(c.push(g.value),!(b&&c.length===b));d=!0);}catch(a){e=!0,f=a}finally{try{!d&&h[\"return\"]&&h[\"return\"]()}finally{if(e)throw f}}return c}return function(b,c){if(Array.isArray(b))return b;if(Symbol.iterator in Object(b))return a(b,c);throw new TypeError(\"Invalid attempt to destructure non-iterable instance\")}}(),rgbToHex=function(a){return a.reduce(function(a,b){return 16>b?a+\"0\"+b.toString(16):a+b.toString(16)},\"#\")},hslToRgb=function(a,b,c){var d=.5>c?c*(1+b):c+b-c*b,e=2*c-d,f=function(a,b,c){var d=Math.round,e=0>c?c+1:1<c?c-1:c;return e=e<1/6?a+6*(b-a)*e:e<1/2?b:e<2/3?a+6*(b-a)*(2/3-e):a,d(255*e)},g=f(e,d,a+1/3),h=f(e,d,a),i=f(e,d,a-1/3);return[g,h,i]},hslGeneration=function(a,b,c,d){var e=a%1007/1007,f=function(a,b,c){return a*(c-b)+b},g=f(e,b.min,b.max),h=f(e,c.min,c.max),i=f(e,d.max,d.min);// 1007 is a prime\nreturn[g,h,i]},standardHashFunction=function(a){return a.split(\"\").reduce(function(a,b,c){return a*b.charCodeAt(0)*c+1},1)},generateColorHash=function(a){var b=a.str,c=a.hue,d=c===void 0?{min:0,max:360}:c,e=a.sat,f=e===void 0?{min:.35,max:.65}:e,g=a.light,h=g===void 0?{min:.3,max:.7}:g,i=a.hashFunction,j=i===void 0?standardHashFunction:i,k=a.scheme,l=k===void 0?\"hex\":k,m=hslGeneration(j(b),d,f,h),n=_slicedToArray(m,3),o=n[0],p=n[1],q=n[2],r=hslToRgb(o/360,p,q),s=rgbToHex(r);if(\"hsl\"===l)return[o,p,q];return\"rgb\"===l?r:s};/**\n *\n * @param {Array} RGBArray\n *//**\n *\n * @param {number} H Hue\n * @param {number} S Saturation\n * @param {number} L Lightness\n *//**\n *\n * @param {string} hash generated hash\n * @param {number} hue Hue\n * @param {number} sat Saturation\n * @param {number} light Lightness\n *//**\n *\n * @param {string} str string to hash\n *//**\n *\n * @param {Object} {\n * str: String to be hashed,\n * hue: { min, max } values (in deg)\n * sat: { min, max } values (0 to 1)\n * light: { min, max } values (0 to 1),\n * hashFunction: Custom hash function,\n * scheme: return scheme\n * }\n */exports.default=generateColorHash,module.exports=exports.default;", "// ----- Types ----- //\n\ninterface ErrorContext {\n error: Error;\n severity: \"error\" | \"crash\";\n componentName: string;\n}\n\ninterface CrashOptions {\n error: Error;\n componentName?: string;\n}\n\ntype ErrorCallback = (ctx: ErrorContext) => void;\n\n// ----- Code ----- //\n\n/**\n * Receives errors that occur in components.\n */\nexport class CrashCollector {\n #errors: ErrorContext[] = [];\n #errorCallbacks: ErrorCallback[] = [];\n\n /**\n * Registers a callback to receive all errors that pass through the CrashCollector.\n * Returns a function that cancels this listener when called.\n */\n onError(callback: ErrorCallback) {\n this.#errorCallbacks.push(callback);\n\n return () => {\n this.#errorCallbacks.splice(this.#errorCallbacks.indexOf(callback), 1);\n };\n }\n\n /**\n * Reports an unrecoverable error that requires crashing the whole app.\n */\n crash({ error, componentName }: CrashOptions) {\n const ctx: ErrorContext = {\n error,\n severity: \"crash\",\n componentName: componentName ?? \"anonymous component\",\n };\n\n this.#errors.push(ctx);\n for (const callback of this.#errorCallbacks) {\n callback(ctx);\n }\n\n throw error; // Throws the error so developer can work with the stack trace in the console.\n }\n\n /**\n * Reports a recoverable error.\n */\n error({ error, componentName }: CrashOptions) {\n const ctx: ErrorContext = {\n error,\n severity: \"error\",\n componentName: componentName ?? \"anonymous component\",\n };\n\n this.#errors.push(ctx);\n for (const callback of this.#errorCallbacks) {\n callback(ctx);\n }\n }\n}\n", "import colorHash from \"simple-color-hash\";\nimport { isString } from \"../typeChecking.js\";\nimport { type CrashCollector } from \"./CrashCollector.js\";\n\nexport type DebugOptions = {\n /**\n * Determines which debug channels are printed. Supports multiple filters with commas,\n * a prepended `-` to exclude a channel and wildcards to match partial channels.\n *\n * @example \"store:*,-store:test\" // matches everything starting with \"store\" except \"store:test\"\n */\n filter?: string | RegExp;\n\n /**\n * Print info messages when true. Default: true for development builds, false for production builds.\n */\n info?: boolean | \"development\";\n\n /**\n * Print log messages when true. Default: true for development builds, false for production builds.\n */\n log?: boolean | \"development\";\n\n /**\n * Print warn messages when true. Default: true for development builds, false for production builds.\n */\n warn?: boolean | \"development\";\n\n /**\n * Print error messages when true. Default: true.\n */\n error?: boolean | \"development\";\n};\n\ntype DebugHubOptions = DebugOptions & {\n crashCollector: CrashCollector;\n mode: \"development\" | \"production\";\n};\n\nexport interface DebugChannelOptions {\n name: string;\n}\n\nexport interface DebugChannel {\n info(...args: any[]): void;\n log(...args: any[]): void;\n warn(...args: any[]): void;\n error(...args: any[]): void;\n}\n\n/**\n * The central trunk from which all channels branch.\n * Changing the filter here determines what kind of messages are printed across the app.\n */\nexport class DebugHub {\n #filter: string | RegExp = \"*,-dolla/*\";\n #matcher;\n #console;\n #options;\n\n constructor(options: DebugHubOptions, _console = getDefaultConsole()) {\n if (options.filter) {\n this.#filter = options.filter;\n }\n\n this.#matcher = makeMatcher(this.#filter);\n this.#console = _console;\n this.#options = options;\n }\n\n /**\n * Returns a debug channel labelled by `name`. Used for logging from components.\n */\n channel(options: DebugChannelOptions): DebugChannel {\n const _console = this.#console;\n const hubOptions = this.#options;\n\n const match = (value: string) => {\n return this.#matcher(value);\n };\n\n return {\n get info() {\n const name = options.name;\n\n if (\n hubOptions.info === false ||\n (isString(hubOptions.info) && hubOptions.info !== hubOptions.mode) ||\n !match(name)\n ) {\n return noOp;\n } else {\n const label = `%c${name}`;\n return _console.info.bind(_console, label, `color:${hash(label)};font-weight:bold`);\n }\n },\n\n get log() {\n const name = options.name;\n\n if (\n hubOptions.log === false ||\n (isString(hubOptions.log) && hubOptions.log !== hubOptions.mode) ||\n !match(name)\n ) {\n return noOp;\n } else {\n const label = `%c${name}`;\n return _console.log.bind(_console, label, `color:${hash(label)};font-weight:bold`);\n }\n },\n\n get warn() {\n const name = options.name;\n\n if (\n hubOptions.warn === false ||\n (isString(hubOptions.warn) && hubOptions.warn !== hubOptions.mode) ||\n !match(name)\n ) {\n return noOp;\n } else {\n const label = `%c${name}`;\n return _console.warn.bind(_console, label, `color:${hash(label)};font-weight:bold`);\n }\n },\n\n get error() {\n const name = options.name;\n\n if (\n hubOptions.error === false ||\n (isString(hubOptions.error) && hubOptions.error !== hubOptions.mode) ||\n !match(name)\n ) {\n return noOp;\n } else {\n const label = `%c${name}`;\n return _console.error.bind(_console, label, `color:${hash(label)};font-weight:bold`);\n }\n },\n };\n }\n\n get filter() {\n return this.#filter;\n }\n\n set filter(pattern) {\n this.#filter = pattern;\n this.#matcher = makeMatcher(pattern);\n }\n}\n\n/* ----- Helpers ----- */\n\nfunction getDefaultConsole() {\n if (typeof window !== \"undefined\" && window.console) {\n return window.console;\n }\n\n if (typeof global !== \"undefined\" && global.console) {\n return global.console;\n }\n}\n\nconst noOp = () => {};\n\nfunction hash(value: string) {\n return colorHash({\n str: value,\n sat: { min: 0.35, max: 0.55 },\n light: { min: 0.6, max: 0.6 },\n });\n}\n\ntype MatcherFunction = (value: string) => boolean;\n\n/**\n * Parses a filter string into a match function.\n *\n * @param pattern - A string or regular expression that specifies a pattern for names of debug channels you want to display.\n */\nexport function makeMatcher(pattern: string | RegExp) {\n if (pattern instanceof RegExp) {\n return (value: string) => pattern.test(value);\n }\n\n const matchers: Record<\"positive\" | \"negative\", MatcherFunction[]> = {\n positive: [],\n negative: [],\n };\n\n const parts = pattern\n .split(\",\")\n .map((p) => p.trim())\n .filter((p) => p !== \"\");\n\n for (let part of parts) {\n let section: \"positive\" | \"negative\" = \"positive\";\n\n if (part.startsWith(\"-\")) {\n section = \"negative\";\n part = part.slice(1);\n }\n\n if (part === \"*\") {\n matchers[section].push(function () {\n return true;\n });\n } else if (part.endsWith(\"*\")) {\n matchers[section].push(function (value) {\n return value.startsWith(part.slice(0, part.length - 1));\n });\n } else {\n matchers[section].push(function (value) {\n return value === part;\n });\n }\n }\n\n return function (name: string) {\n const { positive, negative } = matchers;\n\n // Matching any negative matcher disqualifies.\n if (negative.some((fn) => fn(name))) {\n return false;\n }\n\n // Matching at least one positive matcher is required if any are specified.\n if (positive.length > 0 && !positive.some((fn) => fn(name))) {\n return false;\n }\n\n return true;\n };\n}\n", "type TypeNames =\n // These values can be returned by `typeof`.\n | \"string\"\n | \"number\"\n | \"bigint\"\n | \"boolean\"\n | \"symbol\"\n | \"undefined\"\n | \"object\"\n | \"function\"\n // These values are more specific ones that `Type.of` can return.\n | \"null\"\n | \"array\"\n | \"class\"\n | \"promise\"\n | \"NaN\";\n\n/**\n * Represents an object that can be called with `new` to produce a T.\n */\ntype Factory<T> = { new (): T };\n\n/**\n * Extends `typeof` operator with more specific and useful type distinctions.\n */\nexport function typeOf(value: unknown): TypeNames {\n if (value === undefined) {\n return \"undefined\";\n }\n\n if (value === null) {\n return \"null\";\n }\n\n const type = typeof value;\n\n switch (type) {\n case \"number\":\n if (isNaN(value as any)) {\n return \"NaN\";\n }\n return \"number\";\n case \"function\":\n if (isClass(value)) {\n return \"class\";\n }\n\n return type;\n case \"object\":\n if (isArray(value)) {\n return \"array\";\n }\n\n if (isPromise(value)) {\n return \"promise\";\n }\n\n return type;\n default:\n return type;\n }\n}\n\n/**\n * Throws a TypeError unless `condition` is truthy.\n *\n * @param condition - Value whose truthiness is in question.\n * @param errorMessage - Optional message for the thrown TypeError.\n */\nexport function assert(condition: any, errorMessage?: string): void {\n if (!condition) {\n throw new TypeError(\n formatError(condition, errorMessage || \"Failed assertion. Value is not truthy. Got type: %t, value: %v\")\n );\n }\n}\n\n/**\n * Returns true if `value` is an array.\n */\nexport function isArray(value: unknown): value is Array<unknown> {\n return Array.isArray(value);\n}\n\n/**\n * Throws an error if `value` is not an array.\n */\nexport function assertArray(value: unknown, errorMessage?: string): value is Array<unknown> {\n if (isArray(value)) {\n return true;\n }\n\n throw new TypeError(formatError(value, errorMessage || \"Expected array. Got type: %t, value: %v\"));\n}\n\n/**\n * Returns a function that takes a `value` and ensures that it is an array for which `check` returns true for every item.\n *\n * @param check - Function to check items against.\n */\nexport function isArrayOf<T>(check: (item: unknown) => boolean): (value: unknown) => value is T[];\n\n/**\n * Returns true when `value` is an array and `check` returns true for every item.\n *\n * @param check - Function to check items against.\n * @param value - A possible array.\n */\nexport function isArrayOf<T>(check: (item: unknown) => boolean, value: unknown): value is T[];\n\nexport function isArrayOf<T>(...args: unknown[]) {\n const check = args[0] as (item: unknown) => boolean;\n\n const test = (value: unknown): value is T[] => {\n return isArray(value) && value.every((item) => check(item));\n };\n\n if (args.length < 2) {\n return test;\n } else {\n return test(args[1]);\n }\n}\n\n/**\n * Returns a function that takes a `value` and throws a TypeError unless it is an array for which `check` returns true for every item.\n *\n * @param check - Function to check items against.\n */\nexport function assertArrayOf<T>(check: (item: unknown) => boolean): (value: unknown) => value is T[];\n\n/**\n * Throws a TypeError unless `value` is an array and `check` returns true for every item.\n *\n * @param check - Function to check items against.\n * @param value - A possible array.\n * @param errorMessage - A custom error message.\n */\nexport function assertArrayOf<T>(\n check: (item: unknown) => boolean,\n value: unknown,\n errorMessage?: string\n): value is T[];\n\nexport function assertArrayOf<T>(...args: unknown[]) {\n const check = args[0] as (item: unknown) => boolean;\n const message = isString(args[2]) ? args[2] : \"Expected an array of valid items. Got type: %t, value: %v\";\n\n const test = (value: unknown): value is T[] => {\n if (isArray(value) && value.every((item) => check(item))) {\n return true;\n }\n\n throw new TypeError(formatError(value, message));\n };\n\n if (args.length < 2) {\n return test;\n } else {\n return test(args[1]);\n }\n}\n\n/**\n * Returns true if `value` is equal to `true` or `false`.\n */\nexport function isBoolean(value: unknown): value is boolean {\n return value === true || value === false;\n}\n\n/**\n * Throws a TypeError unless `value` is equal to `true` or `false`.\n */\nexport function assertBoolean(value: unknown, errorMessage?: string): value is boolean {\n if (isBoolean(value)) {\n return true;\n }\n\n throw new TypeError(formatError(value, errorMessage ?? \"Expected a boolean. Got type: %t, value: %v\"));\n}\n\n/**\n * Returns true if `value` is a string.\n */\nexport function isString(value: unknown): value is string {\n return typeof value === \"string\";\n}\n\n/**\n * Throws a TypeError unless `value` is a string.\n */\nexport function assertString(value: unknown, errorMessage?: string): value is string {\n if (isString(value)) {\n return true;\n }\n\n throw new TypeError(formatError(value, errorMessage ?? \"Expected a string. Got type: %t, value: %v\"));\n}\n\n// TODO: More specific validation for common types of strings? Email address, URL, UUID, etc?\n\n/**\n * Returns true if `value` is a function (but not a class).\n */\nexport function isFunction<T = (...args: unknown[]) => unknown>(value: unknown): value is T {\n return typeof value === \"function\" && !isClass(value);\n}\n\n/**\n * Throws a TypeError unless `value` is a function.\n */\nexport function assertFunction<T = (...args: unknown[]) => unknown>(value: unknown, errorMessage?: string): value is T {\n if (isFunction(value)) {\n return true;\n }\n\n throw new TypeError(formatError(value, errorMessage ?? \"Expected a function. Got type: %t, value: %v\"));\n}\n\n/**\n * Returns true if `value` is a number.\n */\nexport function isNumber(value: unknown): value is number {\n return typeof value === \"number\" && !isNaN(value);\n}\n\n/**\n * Throws a TypeError unless `value` is a number.\n */\nexport function assertNumber(value: unknown, errorMessage?: string): value is number {\n if (isNumber(value)) {\n return true;\n }\n\n throw new TypeError(formatError(value, errorMessage ?? \"Expected a number. Got type: %t, value: %v\"));\n}\n\n/**\n * Returns true if `value` implements the Promise protocol.\n * This matches true instances of Promise as well as any object that\n * implements `next`, `catch` and `finally` methods.\n *\n * To strictly match instances of Promise, use `isInstanceOf(Promise)`.\n */\nexport function isPromise<T = unknown>(value: unknown): value is Promise<T> {\n if (value == null) return false;\n\n const obj = value as any;\n\n return obj instanceof Promise || (isFunction(obj.then) && isFunction(obj.catch) && isFunction(obj.finally));\n}\n\n/**\n * Throws a TypeError unless `value` implements the Promise protocol.\n * This matches true instances of Promise as well as any object that\n * implements `next`, `catch` and `finally` methods.\n *\n * To strictly allow only instances of Promise, use `Type.assertInstanceOf(Promise)`.\n */\nexport function assertPromise<T = unknown>(value: unknown, errorMessage?: string): value is Promise<T> {\n if (isPromise(value)) {\n return true;\n }\n\n throw new TypeError(formatError(value, errorMessage ?? \"Expected a promise. Got type: %t, value: %v\"));\n}\n\n/**\n * Returns true if `value` is a class.\n */\nexport function isClass(value: unknown): value is { new (): unknown } {\n return typeof value === \"function\" && /^\\s*class\\s+/.test(value.toString());\n}\n\n/**\n * Throws a TypeError unless `value` is a class.\n */\nexport function assertClass(value: unknown, errorMessage?: string): value is { new (): unknown } {\n if (isClass(value)) {\n return true;\n }\n\n throw new TypeError(formatError(value, errorMessage ?? \"Expected a class. Got type: %t, value: %v\"));\n}\n\n/**\n * Returns a function that takes a `value` and returns true if `value` is an instance of `constructor`.\n *\n * @param constructor - The constructor a value must be an instance of to match.\n */\nexport function isInstanceOf<T extends Function>(constructor: T): (value: unknown) => value is T;\n\n/**\n * Returns `true` if `value` is an instance of `constructor`.\n *\n * @param constructor - The constructor `value` must be an instance of.\n * @param value - A value that may be an instance of `constructor`.\n */\nexport function isInstanceOf<T extends Function>(constructor: T, value: unknown): value is T;\n\nexport function isInstanceOf<T extends Function>(...args: unknown[]) {\n const constructor = args[0] as T;\n\n const test = (value: unknown): value is T => {\n return value instanceof constructor;\n };\n\n if (args.length < 2) {\n return test;\n } else {\n return test(args[1]);\n }\n}\n\n/**\n * Returns a function that takes a `value` and throws a TypeError unless `value` is an instance of `constructor`.\n *\n * @param constructor - The constructor a value must be an instance of to match.\n */\nexport function assertInstanceOf<T extends Function>(constructor: T): (value: unknown) => value is T;\n\n/**\n * Throws a TypeError unless `value` is an instance of `constructor`.\n *\n * @param constructor - The constructor `value` must be an instance of.\n * @param value - A value that may be an instance of `constructor`.\n * @param errorMessage - A custom error message for when the assertion fails.\n */\nexport function assertInstanceOf<T extends Function>(constructor: T, value: unknown, errorMessage?: string): value is T;\n\nexport function assertInstanceOf<T extends Function>(...args: unknown[]) {\n const constructor = args[0] as T;\n const errorMessage = isString(args[2])\n ? args[2]\n : `Expected instance of ${constructor.name}. Got type: %t, value: %v`;\n\n const test = (value: unknown): value is T => {\n if (value instanceof constructor) {\n return true;\n }\n\n throw new TypeError(formatError(value, errorMessage));\n };\n\n if (args.length < 2) {\n return test;\n } else {\n return test(args[1]);\n }\n}\n\n/**\n * Returns true if `value` is a Map.\n */\nexport function isMap<K = unknown, V = unknown>(value: any): value is Map<K, V> {\n return value instanceof Map;\n}\n\n/**\n * Throws a TypeError unless `value` is a Map.\n */\nexport function assertMap<K = unknown, V = unknown>(value: any, errorMessage?: string): value is Map<K, V> {\n if (isMap(value)) {\n return true;\n }\n\n throw new TypeError(formatError(value, errorMessage ?? \"Expected a Map. Got type: %t, value: %v\"));\n}\n\n/**\n * Returns true if `value` is a Set.\n */\nexport function isSet<T = unknown>(value: any): value is Set<T> {\n return value instanceof Set;\n}\n\n/**\n * Throws a TypeError if `value` is not a Set.\n */\nexport function assertSet<T = unknown>(value: any, errorMessage?: string): value is Set<T> {\n if (isSet(value)) {\n return true;\n }\n\n throw new TypeError(formatError(value, errorMessage ?? \"Expected a Set. Got type: %t, value: %v\"));\n}\n\n/**\n * Returns true if `value` implements the Iterable protocol.\n */\nexport function isIterable<T>(value: any): value is Iterable<T> {\n if (value == null) {\n return false;\n }\n\n // Must have a [Symbol.iterator] function that returns an iterator.\n if (!isFunction(value[Symbol.iterator])) {\n return false;\n }\n\n const iterator = value[Symbol.iterator]();\n\n // Iterator must implement the iterator protocol.\n if (!isFunction(iterator.next)) {\n return false;\n }\n\n // We have to assume next() returns the correct object.\n // We can't call it to make sure because we don't want to cause side effects.\n return true;\n}\n\n/**\n * Throws a TypeError unless `value` implements the Iterable protocol.\n */\nexport function assertIterable<T>(value: any, errorMessage?: string): value is Iterable<T> {\n if (isIterable(value)) {\n return true;\n }\n\n throw new TypeError(\n formatError(\n value,\n errorMessage ?? \"Expected an object that implements the iterable protocol. Got type: %t, value: %v\"\n )\n );\n}\n\n/**\n * Returns true if `value` is a plain JavaScript object.\n */\nexport function isObject(value: unknown): value is Record<string | number | symbol, unknown> {\n return value != null && typeof value === \"object\" && !isArray(value);\n}\n\n/**\n * Throws a TypeError unless `value` is a plain JavaScript object.\n */\nexport function assertObject(value: unknown, errorMessage?: string): value is object {\n if (isObject(value)) {\n return true;\n }\n\n throw new TypeError(formatError(value, errorMessage ?? \"Expected an object. Got type: %t, value: %v\"));\n}\n\n/**\n * Returns true if `value` is equal to `null`.\n */\nexport function isNull(value: unknown): value is null {\n return value === null;\n}\n\n/**\n * Throws a TypeError unless `value` is equal to `null`.\n */\nexport function assertNull(value: unknown, errorMessage?: string): value is null {\n if (value === null) {\n return true;\n }\n\n throw new TypeError(formatError(value, errorMessage ?? \"Expected null. Got type: %t, value: %v\"));\n}\n\n/**\n * Returns true if `value` is equal to `undefined`.\n */\nexport function isUndefined(value: unknown): value is undefined {\n return value === undefined;\n}\n\n/**\n * Throws a TypeError unless `value` is equal to `undefined`.\n */\nexport function assertUndefined(value: unknown, errorMessage?: string): value is undefined {\n if (value === undefined) {\n return true;\n }\n\n throw new TypeError(formatError(value, errorMessage ?? \"Expected undefined. Got type: %t, value: %v\"));\n}\n\n/**\n * Returns true if `value` is equal to `null` or `undefined`.\n */\nexport function isEmpty(value: unknown): value is void {\n return value === null || value === undefined;\n}\n\n/**\n * Throws a TypeError unless `value` is equal to `null` or `undefined`.\n */\nexport function assertEmpty(value: unknown, errorMessage?: string): value is void {\n if (value == null) {\n return true;\n }\n\n throw new TypeError(formatError(value, errorMessage ?? \"Expected null or undefined. Got type: %t, value: %v\"));\n}\n\n/**\n * Replaces `%t` and `%v` placeholders in a message with real values.\n */\nfunction formatError(value: unknown, message: string) {\n const typeName = typeOf(value);\n\n // TODO: Pretty format value as string based on type.\n const valueString = value?.toString?.() || String(value);\n\n return message.replaceAll(\"%t\", typeName).replaceAll(\"%v\", valueString);\n}\n", "import { isObject } from \"./typeChecking.js\";\n\nfunction isPlainObject<T = { [name: string]: any }>(value: any): value is T {\n return (\n value != null &&\n typeof value === \"object\" &&\n !Array.isArray(value) &&\n Object.getPrototypeOf(value) === Object.getPrototypeOf({})\n );\n}\n\nexport function deepEqual(one: any, two: any) {\n if (one === two) {\n return true;\n }\n\n if (isPlainObject(one) && isPlainObject(two)) {\n const keysOne = Object.keys(one);\n const keysTwo = Object.keys(two);\n\n if (keysOne.length !== keysTwo.length) {\n return false;\n }\n\n for (const key in one) {\n if (!deepEqual(one[key], two[key])) {\n return false;\n }\n }\n\n return true;\n }\n\n if (Array.isArray(one) && Array.isArray(two)) {\n if (one.length !== two.length) {\n return false;\n }\n\n for (const index in one) {\n if (!deepEqual(one[index], two[index])) {\n return false;\n }\n }\n\n return true;\n }\n\n return one === two;\n}\n\n/**\n * Takes an old value and a new value. Returns a merged copy if both are objects, otherwise returns the new value.\n */\nexport function merge(one: unknown, two: unknown) {\n if (isObject(one)) {\n if (!isObject(two)) {\n return two;\n }\n\n const merged = Object.assign({}, one) as any;\n\n for (const key in two) {\n merged[key] = merge(merged[key], two[key]);\n }\n\n return merged;\n } else {\n return two;\n }\n}\n\n/**\n * Returns a new object without the specified keys.\n * If called without object, returns a function that takes an object\n * and returns a version with the original keys omitted.\n *\n * @param keys - An array of keys to omit.\n * @param object - An object to clone without the omitted keys.\n */\nexport function omit<O extends Record<any, any>>(keys: (keyof O)[], object: O): Record<any, any> {\n const process = (object: Record<any, any>) => {\n const newObject: Record<any, any> = {};\n\n for (const key in object) {\n if (!keys.includes(key)) {\n newObject[key] = object[key];\n }\n }\n\n return newObject;\n };\n\n if (object == null) {\n return process;\n }\n\n return process(object);\n}\n", "import { typeOf } from \"./typeChecking.js\";\nimport { deepEqual } from \"./utils.js\";\n\n// Symbol to mark an observed value as unobserved. Callbacks are always called once for unobserved values.\nconst UNOBSERVED = Symbol(\"Unobserved\");\n\n// Symbol to access observe method used internally by the library.\nconst OBSERVE = Symbol(\"Observe\");\n\n/*==============================*\\\n|| Types ||\n\\*==============================*/\n\n/**\n * Stops the observer that created it when called.\n */\nexport type StopFunction = () => void;\ntype ObserveMethod<T> = (callback: (currentValue: T) => void) => StopFunction;\n\ntype Value<T> = T extends Readable<infer V> ? V : T;\n\n/**\n * Extracts value types from an array of Readables.\n */\nexport type ReadableValues<T extends MaybeReadable<any>[]> = {\n [K in keyof T]: Value<T[K]>;\n};\n\nexport interface Observable<T> {\n /**\n * Receives the latest value with `callback` whenever the value changes.\n * The `previousValue` is always undefined the first time the callback is called, then the same value as the last time it was called going forward.\n */\n [OBSERVE]: ObserveMethod<T>;\n}\n\nexport interface Readable<T> extends Observable<T> {\n /**\n * Returns the current value.\n */\n get(): T;\n}\n\nexport interface Writable<T> extends Readable<T> {\n /**\n * Sets a new value.\n */\n set(value: T): void;\n\n /**\n * Passes the current value to `callback` and takes `callback`'s return value as the new value.\n */\n update(callback: (currentValue: T) => T): void;\n}\n\nexport type MaybeReadable<T> = Readable<T> | T;\n\n/*==============================*\\\n|| Utilities ||\n\\*==============================*/\n\n// function isObservable<T>(value: any): value is Observable<T> {\n// return value != null && typeof value === \"object\" && typeof value[OBSERVE] === \"function\";\n// }\n\n// State.isObservable = isObservable;\n\nexport function isReadable<T>(value: any): value is Readable<T> {\n return (\n value != null &&\n typeof value === \"object\" &&\n typeof value[OBSERVE] === \"function\" &&\n typeof value.get === \"function\"\n );\n}\n\nexport function isWritable<T>(value: any): value is Writable<T> {\n return isReadable(value) && typeof (value as any).set === \"function\" && typeof (value as any).update === \"function\";\n}\n\n/*==============================*\\\n|| $() and $$() ||\n\\*==============================*/\n\nexport function $$<T>(value: Writable<T>): Writable<T>;\nexport function $$<T>(value: Readable<T>): never; // TODO: How to throw a type error in TS before runtime?\nexport function $$<T>(value: undefined): Writable<T | undefined>;\nexport function $$<T>(): Writable<T | undefined>;\nexport function $$<T>(value: T): Writable<Value<T>>;\n\n/**\n * Creates a proxy `Writable` around an existing `Writable`.\n * The config object contains custom `get` and `set` methods.\n * All reads of this proxy goes through the `get` method\n * and all writes go through `set`.\n */\nexport function $$<Source extends Writable<any>, Value>(source: Source, config: ProxyConfig<Value>): Writable<Value>;\n\n/**\n * Creates a proxy `Writable` around an existing `Readable`.\n * The config object contains custom `get` and `set` methods.\n * All reads of this proxy goes through the `get` method\n * and all writes go through `set`.\n */\nexport function $$<Source extends Readable<any>, Value>(source: Source, config: ProxyConfig<Value>): Writable<Value>;\n\n// Same as writable()\nexport function $$(initialValue?: any, config?: any) {\n if (config) {\n return proxy(initialValue, config);\n } else {\n return writable(initialValue);\n }\n}\n\nexport function $<T>(value: Writable<T>): Readable<T>;\nexport function $<T>(value: Readable<T>): Readable<T>;\nexport function $<T>(value: undefined): Readable<T | undefined>;\nexport function $<T>(): Readable<T | undefined>;\nexport function $<T>(value: T): Readable<Value<T>>;\n\nexport function $<I, O>(state: MaybeReadable<I>, compute: (value: I) => O | Readable<O>): Readable<O>;\n\nexport function $<I extends MaybeReadable<any>[], O>(\n states: [...I],\n compute: (...currentValues: ReadableValues<I>) => O | Readable<O>,\n): Readable<O>;\n\nexport function $<I1, I2, O>(\n state1: MaybeReadable<I1>,\n state2: MaybeReadable<I2>,\n compute: (value1: I1, value2: I2) => O | Readable<O>,\n): Readable<O>;\n\nexport function $<I1, I2, I3, O>(\n state1: MaybeReadable<I1>,\n state2: MaybeReadable<I2>,\n state3: MaybeReadable<I3>,\n compute: (value1: I1, value2: I2, value3: I3) => O | Readable<O>,\n): Readable<O>;\n\nexport function $<I1, I2, I3, I4, O>(\n state1: MaybeReadable<I1>,\n state2: MaybeReadable<I2>,\n state3: MaybeReadable<I3>,\n state4: MaybeReadable<I4>,\n compute: (value1: I1, value2: I2, value3: I3, value4: I4) => O | Readable<O>,\n): Readable<O>;\n\nexport function $<I1, I2, I3, I4, I5, O>(\n state1: MaybeReadable<I1>,\n state2: MaybeReadable<I2>,\n state3: MaybeReadable<I3>,\n state4: MaybeReadable<I4>,\n state5: MaybeReadable<I5>,\n compute: (value1: I1, value2: I2, value3: I3, value4: I4, value5: I5) => O | Readable<O>,\n): Readable<O>;\n\nexport function $<I1, I2, I3, I4, I5, I6, O>(\n state1: MaybeReadable<I1>,\n state2: MaybeReadable<I2>,\n state3: MaybeReadable<I3>,\n state4: MaybeReadable<I4>,\n state5: MaybeReadable<I5>,\n state6: MaybeReadable<I6>,\n compute: (value1: I1, value2: I2, value3: I3, value4: I4, value5: I5, value6: I6) => O | Readable<O>,\n): Readable<O>;\n\nexport function $<I1, I2, I3, I4, I5, I6, I7, O>(\n state1: MaybeReadable<I1>,\n state2: MaybeReadable<I2>,\n state3: MaybeReadable<I3>,\n state4: MaybeReadable<I4>,\n state5: MaybeReadable<I5>,\n state6: MaybeReadable<I6>,\n state7: MaybeReadable<I7>,\n compute: (value1: I1, value2: I2, value3: I3, value4: I4, value5: I5, value6: I6, value7: I7) => O | Readable<O>,\n): Readable<O>;\n\nexport function $<I1, I2, I3, I4, I5, I6, I7, I8, O>(\n state1: MaybeReadable<I1>,\n state2: MaybeReadable<I2>,\n state3: MaybeReadable<I3>,\n state4: MaybeReadable<I4>,\n state5: MaybeReadable<I5>,\n state6: MaybeReadable<I6>,\n state7: MaybeReadable<I7>,\n state8: MaybeReadable<I8>,\n compute: (\n value1: I1,\n value2: I2,\n value3: I3,\n value4: I4,\n value5: I5,\n value6: I6,\n value7: I7,\n value8: I8,\n ) => O | Readable<O>,\n): Readable<O>;\n\nexport function $<I1, I2, I3, I4, I5, I6, I7, I8, I9, O>(\n state1: MaybeReadable<I1>,\n state2: MaybeReadable<I2>,\n state3: MaybeReadable<I3>,\n state4: MaybeReadable<I4>,\n state5: MaybeReadable<I5>,\n state6: MaybeReadable<I6>,\n state7: MaybeReadable<I7>,\n state8: MaybeReadable<I8>,\n state9: MaybeReadable<I9>,\n compute: (\n value1: I1,\n value2: I2,\n value3: I3,\n value4: I4,\n value5: I5,\n value6: I6,\n value7: I7,\n value8: I8,\n value9: I9,\n ) => O | Readable<O>,\n): Readable<O>;\n\nexport function $<I1, I2, I3, I4, I5, I6, I7, I8, I9, I10, O>(\n state1: MaybeReadable<I1>,\n state2: MaybeReadable<I2>,\n state3: MaybeReadable<I3>,\n state4: MaybeReadable<I4>,\n state5: MaybeReadable<I5>,\n state6: MaybeReadable<I6>,\n state7: MaybeReadable<I7>,\n state8: MaybeReadable<I8>,\n state9: MaybeReadable<I9>,\n state10: MaybeReadable<I10>,\n compute: (\n value1: I1,\n value2: I2,\n value3: I3,\n value4: I4,\n value5: I5,\n value6: I6,\n value7: I7,\n value8: I8,\n value9: I9,\n value10: I10,\n ) => O | Readable<O>,\n): Readable<O>;\n\n// Hybrid of readable() and computed() - if last arg is a function, it's computed()\nexport function $(...args: any[]) {\n if (args.length > 1) {\n const callback = args.pop() as (...args: any) => void;\n const readables = args.flat().map(readable);\n return computed(...readables, callback);\n } else {\n return readable(args[0]);\n }\n}\n\n/*==============================*\\\n|| readable() ||\n\\*==============================*/\n\nfunction readable<T>(value: Writable<T>): Readable<T>;\nfunction readable<T>(value: Readable<T>): Readable<T>;\nfunction readable<T>(value: undefined): Readable<T | undefined>;\nfunction readable<T>(): Readable<T | undefined>;\nfunction readable<T>(value: T): Readable<Value<T>>;\n\nfunction readable(value?: unknown): Readable<any> {\n // Return a proxy Readable with the value of this Writable.\n if (isWritable(value)) {\n return {\n get: value.get,\n [OBSERVE]: value[OBSERVE],\n };\n }\n\n // Return the same Readable.\n if (isReadable(value)) {\n return value;\n }\n\n // Return a new Readable.\n return {\n get: () => value,\n [OBSERVE]: (callback) => {\n callback(value); // call with current value and undefined for the previous value\n return function stop() {}; // value can never change, so this function is not implemented\n },\n };\n}\n\n/*==============================*\\\n|| computed() ||\n\\*==============================*/\n\nfunction computed(...args: any): Readable<any> {\n const compute = args.pop();\n if (typeof compute !== \"function\") {\n throw new TypeError(`Final argument must be a function. Got ${typeOf(compute)}: ${compute}`);\n }\n if (args.length < 1) {\n throw new Error(`Must pass at least one value before the callback function.`);\n }\n const readables = args as Readable<any>[];\n const observers: ((...currentValues: any[]) => void)[] = [];\n\n let stopCallbacks: StopFunction[] = [];\n let isObserving = false;\n let observedValues: any[] = [];\n let valuesChanged: boolean[] = [];\n let latestComputedValue: any = UNOBSERVED;\n\n // Defined if computed value is itself a readable.\n let computedStopCallback: StopFunction | undefined;\n\n function updateValue() {\n if (!valuesChanged.some((x) => x)) {\n // No values changed. Nothing to do. No need to recompute.\n return;\n }\n\n const computedValue = compute(...observedValues);\n\n if (isReadable(computedValue)) {\n if (computedStopCallback) {\n computedStopCallback();\n }\n\n latestComputedValue = computedValue;\n computedStopCallback = computedValue[OBSERVE]((current) => {\n latestComputedValue = current;\n\n for (const callback of observers) {\n callback(computedValue);\n }\n });\n } else if (!deepEqual(computedValue, latestComputedValue)) {\n // Skip equality check on initial subscription to guarantee\n // that observers receive an initial value, even if undefined.\n\n // Clean up any previous computed readable value.\n if (computedStopCallback) {\n computedStopCallback();\n computedStopCallback = undefined;\n }\n\n // const previousValue = latestComputedValue === UNOBSERVED ? undefined : latestComputedValue;\n latestComputedValue = computedValue;\n\n for (const callback of observers) {\n callback(computedValue);\n }\n }\n\n for (let i = 0; i < observedValues.length; i++) {\n valuesChanged[i] = false;\n }\n }\n\n function startObserving() {\n if (isObserving) return;\n\n for (let i = 0; i < readables.length; i++) {\n const readable = readables[i];\n\n stopCallbacks.push(\n observe(readable, (value: any) => {\n if (!deepEqual(observedValues[i], value)) {\n observedValues[i] = value;\n valuesChanged[i] = true;\n\n if (isObserving) {\n updateValue();\n }\n }\n }),\n );\n }\n\n observedValues = readables.map((x) => x.get());\n for (let i = 0; i < observedValues.length; i++) {\n valuesChanged[i] = true;\n }\n isObserving = true;\n updateValue();\n }\n\n function stopObserving() {\n isObserving = false;\n\n for (const callback of stopCallbacks) {\n callback();\n }\n stopCallbacks = [];\n }\n\n return {\n get: () => {\n let computed;\n\n if (isObserving) {\n computed = latestComputedValue;\n } else {\n computed = compute(...readables.map((x) => x.get()));\n }\n\n if (isReadable(computed)) {\n return computed.get();\n } else {\n return computed;\n }\n },\n [OBSERVE]: (callback) => {\n // First start observing\n if (!isObserving) {\n startObserving();\n }\n\n // Then call callback and add it to observers for future changes\n callback(latestComputedValue);\n observers.push(callback);\n\n return function stop() {\n observers.splice(observers.indexOf(callback), 1);\n\n if (observers.length === 0) {\n stopObserving();\n }\n };\n },\n };\n}\n\n/*==============================*\\\n|| writable() ||\n\\*==============================*/\n\nfunction writable<T>(value: Writable<T>): Writable<T>;\nfunction writable<T>(value: Readable<T>): never; // TODO: How to throw a type error in TS before runtime?\nfunction writable<T>(value: undefined): Writable<T | undefined>;\nfunction writable<T>(): Writable<T | undefined>;\nfunction writable<T>(value: T): Writable<Value<T>>;\n\nfunction writable(value?: unknown): Writable<any> {\n // Return the same Writable.\n if (isWritable(value)) {\n return value;\n }\n\n // Throw error; can't add write access to a Readable.\n if (isReadable(value)) {\n throw new TypeError(`Failed to convert Readable into a Writable; can't add write access to a read-only value.`);\n }\n\n const observers: ((currentValue: any, previousValue?: any) => void)[] = [];\n\n let currentValue = value;\n\n // Return a new Writable.\n return {\n // ----- Readable ----- //\n\n get: () => currentValue,\n [OBSERVE]: (callback) => {\n observers.push(callback); // add observer\n\n function stop() {\n observers.splice(observers.indexOf(callback), 1);\n }\n\n callback(currentValue); // call with current value\n\n // return function to remove observer\n return stop;\n },\n\n // ----- Writable ----- //\n\n set: (newValue) => {\n if (!deepEqual(currentValue, newValue)) {\n const previousValue = currentValue;\n currentValue = newValue;\n for (const callback of observers) {\n callback(currentValue, previousValue);\n }\n }\n },\n update: (callback) => {\n const newValue = callback(currentValue);\n if (!deepEqual(currentValue, newValue)) {\n const previousValue = currentValue;\n currentValue = newValue;\n for (const callback of observers) {\n callback(currentValue, previousValue);\n }\n }\n },\n };\n}\n\n/*==============================*\\\n|| proxy() ||\n\\*==============================*/\n\ninterface ProxyConfig<Value> {\n get(): Value;\n set(value: Value): void;\n}\n\n/**\n * Creates a proxy `Writable` around an existing `Writable`.\n * The config object takes custom `get` and `set` methods.\n * All reads of this proxy goes through the `get` method\n * and all writes go through `set`.\n */\nfunction proxy<Source extends Writable<any>, Value>(source: Source, config: ProxyConfig<Value>): Writable<Value>;\n\n/**\n * Creates a proxy `Writable` around an existing `Readable`.\n * The config object takes custom `get` and `set` methods.\n * All reads of this proxy goes through the `get` method\n * and all writes go through `set`.\n */\nfunction proxy<Source extends Readable<any>, Value>(source: Source, config: ProxyConfig<Value>): Writable<Value>;\n\nfunction proxy<Source, Value>(source: Source, config: ProxyConfig<Value>): Writable<Value> {\n // Throw error; can't add write access to a Readable.\n if (!isReadable(source)) {\n throw new TypeError(`Proxy source must be a Readable.`);\n }\n\n // const observers: ((currentValue: any, previousValue?: any) => void)[] = [];\n // const currentValue = () => config.get();\n\n // Return a new Writable.\n return {\n // ----- Readable ----- //\n\n get: () => config.get(),\n [OBSERVE]: (callback) => {\n let lastComputedValue: any = UNOBSERVED;\n\n return observe(source, (_) => {\n const computedValue = config.get();\n\n if (!deepEqual(computedValue, lastComputedValue)) {\n // const previousValue = lastComputedValue === UNOBSERVED ? undefined : lastComputedValue;\n callback(computedValue);\n lastComputedValue = computedValue;\n }\n });\n },\n\n // ----- Writable ----- //\n\n set: (value) => {\n config.set(value);\n },\n update: (callback) => {\n config.set(callback(config.get()));\n },\n };\n}\n\n/*==============================*\\\n|| observe() ||\n\\*==============================*/\n\n/**\n * Observes a readable value. Calls `callback` each time the value changes.\n * Returns a function to stop observing changes. This MUST be called when you are done\n * with this observer to prevent memory leaks.\n */\nexport function observe<T>(state: Readable<T>, callback: (currentValue: T, previousValue: T) => void): StopFunction;\n\n/**\n * Observes a set of readable values.\n * Calls `callback` with each value in the same order as `readables` each time any of their values change.\n * Returns a function to stop observing changes. This MUST be called when you are done\n * with this observer to prevent memory leaks.\n */\nexport function observe<T extends MaybeReadable<any>[]>(\n states: [...T],\n callback: (currentValues: ReadableValues<T>, previousValues: ReadableValues<T>) => void,\n): StopFunction;\n\nexport function observe<I1, I2>(\n state1: MaybeReadable<I1>,\n state2: MaybeReadable<I2>,\n callback: (value1: I1, value2: I2) => void,\n): StopFunction;\n\nexport function observe<I1, I2, I3>(\n state1: MaybeReadable<I1>,\n state2: MaybeReadable<I2>,\n state3: MaybeReadable<I3>,\n callback: (value1: I1, value2: I2, value3: I3) => void,\n): StopFunction;\n\nexport function observe<I1, I2, I3, I4>(\n state1: MaybeReadable<I1>,\n state2: MaybeReadable<I2>,\n state3: MaybeReadable<I3>,\n state4: MaybeReadable<I4>,\n callback: (value1: I1, value2: I2, value3: I3, value4: I4) => void,\n): StopFunction;\n\nexport function observe<I1, I2, I3, I4, I5>(\n state1: MaybeReadable<I1>,\n state2: MaybeReadable<I2>,\n state3: MaybeReadable<I3>,\n state4: MaybeReadable<I4>,\n state5: MaybeReadable<I5>,\n callback: (value1: I1, value2: I2, value3: I3, value4: I4, value5: I5) => void,\n): StopFunction;\n\nexport function observe<I1, I2, I3, I4, I5, I6>(\n state1: MaybeReadable<I1>,\n state2: MaybeReadable<I2>,\n state3: MaybeReadable<I3>,\n state4: MaybeReadable<I4>,\n state5: MaybeReadable<I5>,\n state6: MaybeReadable<I6>,\n callback: (value1: I1, value2: I2, value3: I3, value4: I4, value5: I5, value6: I6) => void,\n): StopFunction;\n\nexport function observe<I1, I2, I3, I4, I5, I6, I7>(\n state1: MaybeReadable<I1>,\n state2: MaybeReadable<I2>,\n state3: MaybeReadable<I3>,\n state4: MaybeReadable<I4>,\n state5: MaybeReadable<I5>,\n state6: MaybeReadable<I6>,\n state7: MaybeReadable<I7>,\n callback: (value1: I1, value2: I2, value3: I3, value4: I4, value5: I5, value6: I6, value7: I7) => void,\n): StopFunction;\n\nexport function observe<I1, I2, I3, I4, I5, I6, I7, I8>(\n state1: MaybeReadable<I1>,\n state2: MaybeReadable<I2>,\n state3: MaybeReadable<I3>,\n state4: MaybeReadable<I4>,\n state5: MaybeReadable<I5>,\n state6: MaybeReadable<I6>,\n state7: MaybeReadable<I7>,\n state8: MaybeReadable<I8>,\n callback: (value1: I1, value2: I2, value3: I3, value4: I4, value5: I5, value6: I6, value7: I7, value8: I8) => void,\n): StopFunction;\n\nexport function observe<I1, I2, I3, I4, I5, I6, I7, I8, I9>(\n state1: MaybeReadable<I1>,\n state2: MaybeReadable<I2>,\n state3: MaybeReadable<I3>,\n state4: MaybeReadable<I4>,\n state5: MaybeReadable<I5>,\n state6: MaybeReadable<I6>,\n state7: MaybeReadable<I7>,\n state8: MaybeReadable<I8>,\n state9: MaybeReadable<I9>,\n callback: (\n value1: I1,\n value2: I2,\n value3: I3,\n value4: I4,\n value5: I5,\n value6: I6,\n value7: I7,\n value8: I8,\n value9: I9,\n ) => void,\n): StopFunction;\n\nexport function observe<I1, I2, I3, I4, I5, I6, I7, I8, I9, I10>(\n state1: MaybeReadable<I1>,\n state2: MaybeReadable<I2>,\n state3: MaybeReadable<I3>,\n state4: MaybeReadable<I4>,\n state5: MaybeReadable<I5>,\n state6: MaybeReadable<I6>,\n state7: MaybeReadable<I7>,\n state8: MaybeReadable<I8>,\n state9: MaybeReadable<I9>,\n state10: MaybeReadable<I10>,\n callback: (\n value1: I1,\n value2: I2,\n value3: I3,\n value4: I4,\n value5: I5,\n value6: I6,\n value7: I7,\n value8: I8,\n value9: I9,\n value10: I10,\n ) => void,\n): StopFunction;\n\nexport function observe(...args: any[]): StopFunction {\n const callback = args.pop() as (...args: any) => void;\n const readables = args.flat().map(readable);\n\n if (readables.length === 0) {\n throw new TypeError(`Expected at least one readable.`);\n }\n\n if (readables.length > 1) {\n return computed(...readables, callback)[OBSERVE](() => null);\n } else {\n return readables[0][OBSERVE](callback);\n }\n}\n\n/*==============================*\\\n|| unwrap() ||\n\\*==============================*/\n\nexport function unwrap<T>(value: MaybeReadable<T>): T;\n\nexport function unwrap(value: any) {\n if (isReadable(value)) {\n return value.get();\n }\n\n return value;\n}\n", "import { type AppContext, type ElementContext } from \"../app.js\";\nimport { renderMarkupToDOM, toMarkup, type DOMHandle, type Markup } from \"../markup.js\";\nimport { observe, type Readable, type StopFunction } from \"../state.js\";\nimport { type Renderable } from \"../types.js\";\n\nexport interface ConditionalConfig {\n $predicate: Readable<any>;\n thenContent?: Renderable;\n elseContent?: Renderable;\n appContext: AppContext;\n elementContext: ElementContext;\n}\n\nexport class Conditional implements DOMHandle {\n node: Node;\n endNode: Node;\n $predicate: Readable<any>;\n stopCallback?: StopFunction;\n thenContent?: Markup[];\n elseContent?: Markup[];\n connectedContent: DOMHandle[] = [];\n appContext: AppContext;\n elementContext: ElementContext;\n\n constructor(config: ConditionalConfig) {\n this.$predicate = config.$predicate;\n this.thenContent = config.thenContent ? toMarkup(config.thenContent) : undefined;\n this.elseContent = config.elseContent ? toMarkup(config.elseContent) : undefined;\n this.appContext = config.appContext;\n this.elementContext = config.elementContext;\n\n if (this.appContext.mode === \"development\") {\n this.node = document.createComment(\"Conditional\");\n this.endNode = document.createComment(\"/Conditional\");\n } else {\n this.node = document.createTextNode(\"\");\n this.endNode = document.createTextNode(\"\");\n }\n }\n\n get connected() {\n return this.node.parentNode != null;\n }\n\n connect(parent: Node, after?: Node | undefined): void {\n if (!this.connected) {\n parent.insertBefore(this.node, after?.nextSibling ?? null);\n if (this.appContext.mode === \"development\") {\n parent.insertBefore(this.endNode, this.node.nextSibling);\n }\n\n this.stopCallback = observe(this.$predicate, (value) => {\n this.update(value);\n });\n }\n }\n\n disconnect(): void {\n if (this.stopCallback) {\n this.stopCallback();\n this.stopCallback = undefined;\n }\n\n for (const handle of this.connectedContent) {\n handle.disconnect();\n }\n this.connectedContent = [];\n\n if (this.connected) {\n this.node.parentNode?.removeChild(this.node);\n this.endNode.parentNode?.removeChild(this.endNode);\n }\n }\n\n update(value: any) {\n for (const handle of this.connectedContent) {\n handle.disconnect();\n }\n this.connectedContent = [];\n\n if (this.node.parentNode == null) {\n return;\n }\n\n if (value && this.thenContent) {\n this.connectedContent = renderMarkupToDOM(this.thenContent, this);\n } else if (!value && this.elseContent) {\n this.connectedContent = renderMarkupToDOM(this.elseContent, this);\n }\n\n for (let i = 0; i < this.connectedContent.length; i++) {\n const handle = this.connectedContent[i];\n const previous = this.connectedContent[i - 1]?.node ?? this.node;\n handle.connect(this.node.parentNode, previous);\n }\n\n if (this.appContext.mode === \"development\") {\n this.node.textContent = `Conditional (${value ? \"truthy\" : \"falsy\"})`;\n }\n }\n\n async setChildren(children: DOMHandle[]): Promise<void> {}\n}\n", "export { urlAlphabet } from './url-alphabet/index.js'\nexport let random = bytes => crypto.getRandomValues(new Uint8Array(bytes))\nexport let customRandom = (alphabet, defaultSize, getRandom) => {\n let mask = (2 << (Math.log(alphabet.length - 1) / Math.LN2)) - 1\n let step = -~((1.6 * mask * defaultSize) / alphabet.length)\n return (size = defaultSize) => {\n let id = ''\n while (true) {\n let bytes = getRandom(step)\n let j = step\n while (j--) {\n id += alphabet[bytes[j] & mask] || ''\n if (id.length === size) return id\n }\n }\n }\n}\nexport let customAlphabet = (alphabet, size = 21) =>\n customRandom(alphabet, size, random)\nexport let nanoid = (size = 21) =>\n crypto.getRandomValues(new Uint8Array(size)).reduce((id, byte) => {\n byte &= 63\n if (byte < 36) {\n id += byte.toString(36)\n } else if (byte < 62) {\n id += (byte - 26).toString(36).toUpperCase()\n } else if (byte > 62) {\n id += '-'\n } else {\n id += '_'\n }\n return id\n }, '')\n", "import { nanoid } from \"nanoid\";\nimport { type AppContext, type ElementContext } from \"../app.js\";\nimport { renderMarkupToDOM, type DOMHandle, type Markup } from \"../markup.js\";\nimport { isReadable, isWritable, observe, type Readable, type StopFunction } from \"../state.js\";\nimport { isFunction, isNumber, isObject, isString } from \"../typeChecking.js\";\nimport { BuiltInStores } from \"../types.js\";\nimport { omit } from \"../utils.js\";\n\n//const eventHandlerProps = Object.values(eventPropsToEventNames).map((event) => \"on\" + event);\nconst isCamelCaseEventName = (key: string) => /^on[A-Z]/.test(key);\n\ntype HTMLOptions = {\n appContext: AppContext;\n elementContext: ElementContext;\n tag: string;\n props?: any;\n children?: Markup[];\n};\n\nexport class HTML implements DOMHandle {\n node;\n props: Record<string, any>;\n children: DOMHandle[];\n stopCallbacks: StopFunction[] = [];\n appContext;\n elementContext;\n uniqueId = nanoid();\n\n // Prevents 'onClickOutside' handlers from firing in the same cycle in which the element is connected.\n canClickAway = false;\n\n get connected() {\n return this.node.parentNode != null;\n }\n\n constructor({ tag, props, children, appContext, elementContext }: HTMLOptions) {\n elementContext = { ...elementContext };\n\n // This and all nested views will be created as SVG elements.\n if (tag.toLowerCase() === \"svg\") {\n elementContext.isSVG = true;\n }\n\n // Create node with the appropriate constructor.\n if (elementContext.isSVG) {\n this.node = document.createElementNS(\"http://www.w3.org/2000/svg\", tag);\n } else {\n this.node = document.createElement(tag);\n }\n\n // Add unique ID to attributes for debugging purposes.\n if (appContext.mode === \"development\") {\n this.node.dataset.uniqueId = this.uniqueId;\n }\n\n // Set ref if present. Refs can be a Ref object or a function that receives the node.\n if (props.ref) {\n if (isWritable(props.ref)) {\n props.ref.set(this.node);\n } else if (isFunction(props.ref)) {\n props.ref(this.node);\n } else {\n throw new Error(\"Expected an instance of Ref. Got: \" + props.ref);\n }\n }\n\n this.props = {\n ...omit([\"ref\", \"class\", \"className\"], props),\n class: props.className ?? props.class,\n };\n this.children = children ? renderMarkupToDOM(children, { appContext, elementContext }) : [];\n\n this.appContext = appContext;\n this.elementContext = elementContext;\n }\n\n connect(parent: Node, after?: Node) {\n if (parent == null) {\n throw new Error(`HTML element requires a parent element as the first argument to connect. Got: ${parent}`);\n }\n\n if (!this.connected) {\n for (const child of this.children) {\n child.connect(this.node);\n }\n\n this.applyProps(this.node, this.props);\n if (this.props.style) this.applyStyles(this.node, this.props.style, this.stopCallbacks);\n if (this.props.class) this.applyClasses(this.node, this.props.class, this.stopCallbacks);\n }\n\n parent.insertBefore(this.node, after?.nextSibling ?? null);\n\n setTimeout(() => {\n this.canClickAway = true;\n }, 0);\n }\n\n disconnect() {\n if (this.connected) {\n for (const child of this.children) {\n child.disconnect();\n }\n\n this.node.parentNode?.removeChild(this.node);\n\n this.canClickAway = false;\n\n for (const stop of this.stopCallbacks) {\n stop();\n }\n this.stopCallbacks = [];\n }\n }\n\n setChildren(next: DOMHandle[]) {\n const current = this.children;\n const patched: DOMHandle[] = [];\n const length = Math.max(current.length, next.length);\n\n for (let i = 0; i < length; i++) {\n if (!current[i] && next[i]) {\n // item was added\n patched[i] = next[i];\n patched[i].connect(this.node, patched[i - 1]?.node);\n } else if (current[i] && !next[i]) {\n // item was removed\n current[i].disconnect();\n } else if (current[i] != next[i]) {\n // item was replaced\n patched[i] = next[i];\n current[i].disconnect();\n patched[i].connect(this.node, patched[i - 1]?.node);\n }\n }\n\n this.children = patched;\n }\n\n getUpdateKey(type: string, value: string | number) {\n return `${this.uniqueId}:${type}:${value}`;\n }\n\n applyProps(element: HTMLElement | SVGElement, props: Record<string, unknown>) {\n const render = this.appContext.stores.get(\"render\")!.instance?.exports as BuiltInStores[\"render\"];\n\n const attachProp = <T>(value: Readable<T> | T, callback: (value: T) => void, updateKey: string) => {\n if (isReadable(value)) {\n this.stopCallbacks.push(\n observe(value, (value) => {\n render.update(() => {\n callback(value);\n }, updateKey);\n }),\n );\n } else {\n render.update(() => {\n callback(value);\n }, updateKey);\n }\n };\n\n for (const key in props) {\n const value = props[key];\n\n if (key === \"attributes\") {\n const values = value as Record<string, any>;\n // Set attributes directly without mapping props\n for (const name in values) {\n attachProp(\n values[name],\n (current) => {\n if (current == null) {\n (element as any).removeAttribute(name);\n } else {\n (element as any).setAttribute(name, String(current));\n }\n },\n this.getUpdateKey(\"attr\", name),\n );\n }\n } else if (key === \"eventListeners\") {\n const values = value as Record<string, any>;\n\n for (const name in values) {\n const listener: (e: Event) => void = isReadable<(e: Event) => void>(value)\n ? (e: Event) => value.get()(e)\n : (value as (e: Event) => void);\n\n element.addEventListener(name, listener);\n\n this.stopCallbacks.push(() => {\n element.removeEventListener(name, listener);\n });\n }\n } else if (key === \"$$value\") {\n if (!isWritable(value)) {\n throw new TypeError(`$$value property must be a Writable. Got: ${value} (${typeof value})`);\n }\n\n attachProp(\n value,\n (current) => {\n (element as any).value = String(current);\n },\n this.getUpdateKey(\"prop\", \"value\"),\n );\n\n const listener: EventListener = (e) => {\n const updated = toTypeOf(value.get(), (e.currentTarget as HTMLInputElement).value);\n value.set(updated);\n };\n\n element.addEventListener(\"input\", listener);\n\n this.stopCallbacks.push(() => {\n element.removeEventListener(\"input\", listener);\n });\n } else if (key === \"onClickOutside\" || key === \"onclickoutside\") {\n const listener = (e: Event) => {\n if (this.canClickAway && !element.contains(e.target as any)) {\n if (isReadable<(e: Event) => void>(value)) {\n value.get()(e);\n } else {\n (value as (e: Event) => void)(e);\n }\n }\n };\n\n const options = { capture: true };\n\n window.addEventListener(\"click\", listener, options);\n\n this.stopCallbacks.push(() => {\n window.removeEventListener(\"click\", listener, options);\n });\n } else if (isCamelCaseEventName(key)) {\n const eventName = key.slice(2).toLowerCase();\n\n const listener: (e: Event) => void = isReadable<(e: Event) => void>(value)\n ? (e: Event) => value.get()(e)\n : (value as (e: Event) => void);\n\n element.addEventListener(eventName, listener);\n\n this.stopCallbacks.push(() => {\n element.removeEventListener(eventName, listener);\n });\n } else if (key.includes(\"-\")) {\n // Names with dashes in them are not valid prop names, so they are treated as attributes.\n attachProp(\n value,\n (current) => {\n if (current == null) {\n element.removeAttribute(key);\n } else {\n element.setAttribute(key, String(current));\n }\n },\n this.getUpdateKey(\"attr\", key),\n );\n } else if (!privateProps.includes(key)) {\n if (this.elementContext.isSVG) {\n attachProp(\n value,\n (current) => {\n if (current != null) {\n element.setAttribute(key, String(props[key]));\n } else {\n element.removeAttribute(key);\n }\n },\n this.getUpdateKey(\"attr\", key),\n );\n } else {\n switch (key) {\n case \"contentEditable\":\n case \"value\":\n attachProp(\n value,\n (current) => {\n (element as any)[key] = String(current);\n },\n this.getUpdateKey(\"prop\", key),\n );\n break;\n\n case \"for\":\n attachProp(\n value,\n (current) => {\n (element as any).htmlFor = current;\n },\n this.getUpdateKey(\"prop\", \"htmlFor\"),\n );\n break;\n\n case \"checked\":\n attachProp(\n value,\n (current) => {\n (element as any).checked = current;\n\n // Set attribute also or styles don't take effect.\n if (current) {\n element.setAttribute(\"checked\", \"\");\n } else {\n element.removeAttribute(\"checked\");\n }\n },\n this.getUpdateKey(\"prop\", \"checked\"),\n );\n break;\n\n // Attribute-aliased props\n case \"exportParts\":\n case \"part\":\n case \"translate\":\n case \"title\": {\n const _key = key.toLowerCase();\n attachProp(\n value,\n (current) => {\n if (current == undefined) {\n element.removeAttribute(_key);\n } else {\n element.setAttribute(_key, String(current));\n }\n },\n this.getUpdateKey(\"attr\", _key),\n );\n break;\n }\n\n case \"autocomplete\":\n case \"autocapitalize\":\n attachProp(\n value,\n (current) => {\n if (typeof current === \"string\") {\n (element as any).autocomplete = current;\n } else if (current) {\n (element as any).autocomplete = \"on\";\n } else {\n (element as any).autocomplete = \"off\";\n }\n },\n this.getUpdateKey(\"prop\", key),\n );\n break;\n\n default: {\n attachProp(\n value,\n (current) => {\n (element as any)[key] = current;\n },\n this.getUpdateKey(\"prop\", key),\n );\n break;\n }\n }\n }\n }\n }\n }\n\n applyStyles(element: HTMLElement | SVGElement, styles: string | Record<string, any>, stopCallbacks: StopFunction[]) {\n const render = this.appContext.stores.get(\"render\")!.instance?.exports as BuiltInStores[\"render\"];\n const propStopCallbacks: StopFunction[] = [];\n\n if (styles == undefined) {\n element.style.cssText = \"\";\n } else if (typeof styles === \"string\") {\n element.style.cssText = styles;\n } else if (isReadable<object>(styles)) {\n let unapply: () => void;\n\n const stop = observe(styles, (current) => {\n render.update(\n () => {\n if (isFunction(unapply)) {\n unapply();\n }\n element.style.cssText = \"\";\n unapply = this.applyStyles(element, current, stopCallbacks);\n },\n this.getUpdateKey(\"styles\", \"*\"),\n );\n });\n\n stopCallbacks.push(stop);\n propStopCallbacks.push(stop);\n } else if (isObject(styles)) {\n styles = styles as Record<string, any>;\n\n for (const key in styles) {\n const value = styles[key];\n\n // Set style property or attribute.\n const setProperty = key.startsWith(\"--\")\n ? (key: string, value: string | null) =>\n value == null ? element.style.removeProperty(key) : element.style.setProperty(key, value)\n : (key: string, value: string | null) => (element.style[key as any] = value ?? \"\");\n\n if (isReadable<any>(value)) {\n const stop = observe(value, (current) => {\n render.update(\n () => {\n if (current != null) {\n setProperty(key, current);\n } else {\n element.style.removeProperty(key);\n }\n },\n this.getUpdateKey(\"style\", key),\n );\n });\n\n stopCallbacks.push(stop);\n propStopCallbacks.push(stop);\n } else if (isString(value)) {\n setProperty(key, value);\n } else if (isNumber(value)) {\n setProperty(key, String(value));\n } else {\n throw new TypeError(`Style properties should be strings, $states or numbers. Got (${key}: ${value})`);\n }\n }\n } else {\n throw new TypeError(`Expected style property to be a string, $state, or object. Got: ${styles}`);\n }\n\n return function unapply() {\n for (const stop of propStopCallbacks) {\n stop();\n stopCallbacks.splice(stopCallbacks.indexOf(stop), 1);\n }\n };\n }\n\n applyClasses(element: HTMLElement | SVGElement, classes: unknown, stopCallbacks: StopFunction[]) {\n const render = this.appContext.stores.get(\"render\")!.instance?.exports as BuiltInStores[\"render\"];\n const classStopCallbacks: StopFunction[] = [];\n\n if (isReadable(classes)) {\n let unapply: () => void;\n\n const stop = observe(classes, (current) => {\n render.update(\n () => {\n if (isFunction(unapply)) {\n unapply();\n }\n element.removeAttribute(\"class\");\n unapply = this.applyClasses(element, current, stopCallbacks);\n },\n this.getUpdateKey(\"attr\", \"class\"),\n );\n });\n\n stopCallbacks.push(stop);\n classStopCallbacks.push(stop);\n } else {\n const mapped = getClassMap(classes);\n\n for (const name in mapped) {\n const value = mapped[name];\n\n if (isReadable(value)) {\n const stop = observe(value, (current) => {\n render.update(() => {\n if (current) {\n element.classList.add(name);\n } else {\n element.classList.remove(name);\n }\n }); // NOTE: Not keyed; all update callbacks must run to apply all classes.\n });\n\n stopCallbacks.push(stop);\n classStopCallbacks.push(stop);\n } else if (value) {\n element.classList.add(name);\n }\n }\n }\n\n return function unapply() {\n for (const stop of classStopCallbacks) {\n stop();\n stopCallbacks.splice(stopCallbacks.indexOf(stop), 1);\n }\n };\n }\n}\n\nfunction getClassMap(classes: unknown) {\n let mapped: Record<string, boolean> = {};\n\n if (isString(classes)) {\n // Support multiple classes in one string like HTML.\n const names = classes.split(\" \");\n for (const name of names) {\n mapped[name] = true;\n }\n } else if (isObject(classes)) {\n Object.assign(mapped, classes);\n } else if (Array.isArray(classes)) {\n Array.from(classes)\n .filter((item) => item != null)\n .forEach((item) => {\n Object.assign(mapped, getClassMap(item));\n });\n }\n\n return mapped;\n}\n\n/**\n * Attempts to convert `source` to the same type as `target`.\n * Returns `source` as-is if conversion is not possible.\n */\nfunction toTypeOf<T>(target: T, source: unknown): T | unknown {\n const type = typeof target;\n\n if (type === \"string\") {\n return String(source);\n }\n\n if (type === \"number\") {\n return Number(source);\n }\n\n if (type === \"boolean\") {\n return Boolean(source);\n }\n\n return source;\n}\n\n// Attributes in this list will not be forwarded to the DOM node.\nconst privateProps = [\"ref\", \"children\", \"class\", \"style\", \"data\"];\n", "import { type AppContext, type ElementContext } from \"../app.js\";\nimport {\n getRenderHandle,\n isDOMHandle,\n isMarkup,\n isRenderable,\n renderMarkupToDOM,\n toMarkup,\n type DOMHandle,\n} from \"../markup.js\";\nimport { observe, type Readable, type StopFunction } from \"../state.js\";\nimport { typeOf } from \"../typeChecking.js\";\nimport type { Renderable } from \"../types.js\";\n\ninterface ObserverOptions {\n appContext: AppContext;\n elementContext: ElementContext;\n readables: Readable<any>[];\n renderFn: (...values: any) => Renderable;\n}\n\n/**\n * Displays dynamic children without a parent element.\n */\nexport class Observer implements DOMHandle {\n node: Node;\n endNode: Node;\n connectedViews: DOMHandle[] = [];\n renderFn: (...values: any) => Renderable;\n appContext;\n elementContext;\n observerControls;\n\n get connected() {\n return this.node.parentNode != null;\n }\n\n constructor({ readables, renderFn, appContext, elementContext }: ObserverOptions) {\n this.appContext = appContext;\n this.elementContext = elementContext;\n this.renderFn = renderFn;\n\n this.node = document.createComment(\"Observer\");\n this.endNode = document.createComment(\"/Observer\");\n\n let _stop: StopFunction | undefined;\n\n this.observerControls = {\n start: () => {\n if (_stop != null) return;\n\n _stop = observe(readables, (...values) => {\n const rendered = this.renderFn(...values);\n\n if (!isRenderable(rendered)) {\n console.error(rendered);\n throw new TypeError(\n `Observer received invalid value to render. Got type: ${typeOf(rendered)}, value: ${rendered}`\n );\n }\n\n if (Array.isArray(rendered)) {\n this.update(...rendered);\n } else {\n this.update(rendered);\n }\n });\n },\n stop: () => {\n if (_stop == null) return;\n\n _stop();\n _stop = undefined;\n },\n };\n }\n\n connect(parent: Node, after?: Node) {\n if (!this.connected) {\n parent.insertBefore(this.node, after?.nextSibling ?? null);\n this.observerControls.start();\n }\n }\n\n disconnect() {\n this.observerControls.stop();\n\n if (this.connected) {\n this.cleanup();\n this.node.parentNode?.removeChild(this.node);\n }\n }\n\n async setChildren() {\n console.warn(\"setChildren is not implemented for Dynamic\");\n }\n\n cleanup() {\n while (this.connectedViews.length > 0) {\n this.connectedViews.pop()?.disconnect();\n }\n }\n\n update(...children: Renderable[]) {\n this.cleanup();\n\n if (children == null || !this.connected) {\n return;\n }\n\n const handles: DOMHandle[] = children.map((c) => {\n if (isDOMHandle(c)) {\n return c;\n } else if (isMarkup(c)) {\n return getRenderHandle(renderMarkupToDOM(c, this));\n } else {\n return getRenderHandle(renderMarkupToDOM(toMarkup(c), this));\n }\n });\n\n for (const handle of handles) {\n const previous = this.connectedViews.at(-1)?.node || this.node;\n\n handle.connect(this.node.parentNode!, previous);\n\n this.connectedViews.push(handle);\n }\n\n if (this.appContext.mode === \"development\") {\n const lastNode = this.connectedViews.at(-1)?.node;\n if (this.endNode.previousSibling !== lastNode) {\n this.node.parentNode!.insertBefore(this.endNode, lastNode?.nextSibling ?? null);\n }\n }\n }\n}\n", "import { type AppContext, type ElementContext } from \"../app.js\";\nimport { type DOMHandle } from \"../markup.js\";\nimport { observe, type Readable, type StopFunction } from \"../state.js\";\n\nexport interface OutletConfig {\n $children: Readable<DOMHandle[]>;\n appContext: AppContext;\n elementContext: ElementContext;\n}\n\n/**\n * Manages an array of DOMHandles.\n */\nexport class Outlet implements DOMHandle {\n node: Node;\n endNode: Node;\n $children: Readable<DOMHandle[]>;\n stopCallback?: StopFunction;\n connectedChildren: DOMHandle[] = [];\n appContext: AppContext;\n elementContext: ElementContext;\n\n constructor(config: OutletConfig) {\n this.$children = config.$children;\n this.appContext = config.appContext;\n this.elementContext = config.elementContext;\n\n if (this.appContext.mode === \"development\") {\n this.node = document.createComment(\"Outlet\");\n this.endNode = document.createComment(\"/Outlet\");\n } else {\n this.node = document.createTextNode(\"\");\n this.endNode = document.createTextNode(\"\");\n }\n }\n\n get connected() {\n return this.node?.parentNode != null;\n }\n\n connect(parent: Node, after?: Node | undefined) {\n if (!this.connected) {\n parent.insertBefore(this.node, after?.nextSibling ?? null);\n\n this.stopCallback = observe(this.$children, (children) => {\n this.update(children);\n });\n }\n }\n\n disconnect() {\n if (this.stopCallback) {\n this.stopCallback();\n this.stopCallback = undefined;\n }\n\n if (this.connected) {\n for (const child of this.connectedChildren) {\n child.disconnect();\n }\n this.connectedChildren = [];\n this.endNode.parentNode?.removeChild(this.endNode);\n }\n }\n\n update(newChildren: DOMHandle[]) {\n for (const child of this.connectedChildren) {\n child.disconnect();\n }\n\n for (let i = 0; i < newChildren.length; i++) {\n const child = newChildren[i];\n const previous = i > 0 ? newChildren[i] : undefined;\n child.connect(this.node.parentElement!, previous?.node);\n }\n\n this.connectedChildren = newChildren;\n\n if (this.appContext.mode === \"development\") {\n this.node.textContent = `Outlet (${newChildren.length} ${newChildren.length === 1 ? \"child\" : \"children\"})`;\n this.node.parentElement?.insertBefore(\n this.endNode,\n this.connectedChildren[this.connectedChildren.length - 1]?.node?.nextSibling ?? null,\n );\n }\n }\n\n setChildren(children: DOMHandle[]) {\n throw new Error(`setChildren is not supported on Outlet`);\n }\n}\n", "import { type AppContext, type ElementContext } from \"../app.js\";\nimport { getRenderHandle, isDOMHandle, isMarkup, renderMarkupToDOM, toMarkup, type DOMHandle } from \"../markup.js\";\nimport { type Renderable } from \"../types.js\";\n\ninterface PortalConfig {\n content: Renderable;\n parent: Node;\n appContext: AppContext;\n elementContext: ElementContext;\n}\n\n/**\n * Renders content into a specified parent node.\n */\nexport class Portal implements DOMHandle {\n config: PortalConfig;\n handle?: DOMHandle;\n\n get connected() {\n if (!this.handle) {\n return false;\n }\n return this.handle.connected;\n }\n\n constructor(config: PortalConfig) {\n this.config = config;\n }\n\n connect(_parent: Node, _after?: Node) {\n const { content, parent } = this.config;\n\n if (isDOMHandle(content)) {\n this.handle = content;\n } else if (isMarkup(content)) {\n this.handle = getRenderHandle(renderMarkupToDOM(content, this.config));\n } else {\n this.handle = getRenderHandle(renderMarkupToDOM(toMarkup(content), this.config));\n }\n\n this.handle.connect(parent);\n }\n\n disconnect() {\n if (this.handle?.connected) {\n this.handle.disconnect();\n }\n }\n\n setChildren(children: DOMHandle[]) {\n this.handle?.setChildren(children);\n }\n}\n", "import { isArrayOf, typeOf } from \"./typeChecking.js\";\nimport { nanoid } from \"nanoid\";\nimport { type AppContext, type ElementContext } from \"./app.js\";\nimport { type DebugChannel } from \"./classes/DebugHub.js\";\nimport { getRenderHandle, isMarkup, m, renderMarkupToDOM, type DOMHandle, type Markup } from \"./markup.js\";\nimport { $, $$, isReadable, observe, type Readable, type ReadableValues, type MaybeReadable } from \"./state.js\";\nimport { type Store } from \"./store.js\";\nimport type { BuiltInStores } from \"./types.js\";\n\n/*=====================================*\\\n|| Types ||\n\\*=====================================*/\n\n/**\n * Any valid value that a View can return.\n */\nexport type ViewResult = Node | Readable<any> | Markup | Markup[] | null;\n\nexport type View<P> = (props: P, context: ViewContext) => ViewResult;\n\nexport interface ViewContext extends DebugChannel {\n /**\n * A string ID unique to this view.\n */\n readonly uniqueId: string;\n\n /**\n * Returns the shared instance of `store`.\n */\n getStore<T extends Store<any, any>>(store: T): ReturnType<T>;\n\n /**\n * Returns the shared instance of a built-in store.\n */\n getStore<N extends keyof BuiltInStores>(name: N): BuiltInStores[N];\n\n /**\n * Runs `callback` just before this view is connected. DOM nodes are not yet attached to the page.\n */\n beforeConnect(callback: () => void): void;\n\n /**\n * Runs `callback` after this view is connected. DOM nodes are now attached to the page.\n */\n onConnected(callback: () => void): void;\n\n /**\n * Runs `callback` just before this view is disconnected. DOM nodes are still attached to the page.\n */\n beforeDisconnect(callback: () => void): void;\n\n /**\n * Runs `callback` after this view is disconnected. DOM nodes are no longer attached to the page.\n */\n onDisconnected(callback: () => void): void;\n\n /**\n * The name of this view for logging and debugging purposes.\n */\n name: string;\n\n /**\n * Takes an Error object, unmounts the app and displays its crash page.\n */\n crash(error: Error): void;\n\n /**\n * Observes a readable value while this view is connected. Calls `callback` each time the value changes.\n */\n observe<T>(state: MaybeReadable<T>, callback: (currentValue: T) => void): void;\n\n /**\n * Observes a set of readable values while this view is connected.\n * Calls `callback` with each value in the same order as `readables` each time any of their values change.\n */\n observe<T extends MaybeReadable<any>[]>(\n states: [...T],\n callback: (...currentValues: ReadableValues<T>) => void,\n ): void;\n\n observe<I1, I2>(\n state1: MaybeReadable<I1>,\n state2: MaybeReadable<I2>,\n callback: (value1: I1, value2: I2) => void,\n ): void;\n\n observe<I1, I2, I3>(\n state1: MaybeReadable<I1>,\n state2: MaybeReadable<I2>,\n state3: MaybeReadable<I3>,\n callback: (value1: I1, value2: I2, value3: I3) => void,\n ): void;\n\n observe<I1, I2, I3, I4>(\n state1: MaybeReadable<I1>,\n state2: MaybeReadable<I2>,\n state3: MaybeReadable<I3>,\n state4: MaybeReadable<I4>,\n callback: (value1: I1, value2: I2, value3: I3, value4: I4) => void,\n ): void;\n\n observe<I1, I2, I3, I4, I5>(\n state1: MaybeReadable<I1>,\n state2: MaybeReadable<I2>,\n state3: MaybeReadable<I3>,\n state4: MaybeReadable<I4>,\n state5: MaybeReadable<I5>,\n callback: (value1: I1, value2: I2, value3: I3, value4: I4, value5: I5) => void,\n ): void;\n\n observe<I1, I2, I3, I4, I5, I6>(\n state1: MaybeReadable<I1>,\n state2: MaybeReadable<I2>,\n state3: MaybeReadable<I3>,\n state4: MaybeReadable<I4>,\n state5: MaybeReadable<I5>,\n state6: MaybeReadable<I6>,\n callback: (value1: I1, value2: I2, value3: I3, value4: I4, value5: I5, value6: I6) => void,\n ): void;\n\n observe<I1, I2, I3, I4, I5, I6, I7>(\n state1: MaybeReadable<I1>,\n state2: MaybeReadable<I2>,\n state3: MaybeReadable<I3>,\n state4: MaybeReadable<I4>,\n state5: MaybeReadable<I5>,\n state6: MaybeReadable<I6>,\n state7: MaybeReadable<I7>,\n callback: (value1: I1, value2: I2, value3: I3, value4: I4, value5: I5, value6: I6, value7: I7) => void,\n ): void;\n\n observe<I1, I2, I3, I4, I5, I6, I7, I8>(\n state1: MaybeReadable<I1>,\n state2: MaybeReadable<I2>,\n state3: MaybeReadable<I3>,\n state4: MaybeReadable<I4>,\n state5: MaybeReadable<I5>,\n state6: MaybeReadable<I6>,\n state7: MaybeReadable<I7>,\n state8: MaybeReadable<I8>,\n callback: (value1: I1, value2: I2, value3: I3, value4: I4, value5: I5, value6: I6, value7: I7, value8: I8) => void,\n ): void;\n\n observe<I1, I2, I3, I4, I5, I6, I7, I8, I9>(\n state1: MaybeReadable<I1>,\n state2: MaybeReadable<I2>,\n state3: MaybeReadable<I3>,\n state4: MaybeReadable<I4>,\n state5: MaybeReadable<I5>,\n state6: MaybeReadable<I6>,\n state7: MaybeReadable<I7>,\n state8: MaybeReadable<I8>,\n state9: MaybeReadable<I9>,\n callback: (\n value1: I1,\n value2: I2,\n value3: I3,\n value4: I4,\n value5: I5,\n value6: I6,\n value7: I7,\n value8: I8,\n value9: I9,\n ) => void,\n ): void;\n\n observe<I1, I2, I3, I4, I5, I6, I7, I8, I9, I10>(\n state1: MaybeReadable<I1>,\n state2: MaybeReadable<I2>,\n state3: MaybeReadable<I3>,\n state4: MaybeReadable<I4>,\n state5: MaybeReadable<I5>,\n state6: MaybeReadable<I6>,\n state7: MaybeReadable<I7>,\n state8: MaybeReadable<I8>,\n state9: MaybeReadable<I9>,\n state10: MaybeReadable<I10>,\n callback: (\n value1: I1,\n value2: I2,\n value3: I3,\n value4: I4,\n value5: I5,\n value6: I6,\n value7: I7,\n value8: I8,\n value9: I9,\n value10: I10,\n ) => void,\n ): void;\n\n /**\n * Returns a Markup element that displays this view's children.\n */\n outlet(): Markup;\n}\n\n/*=====================================*\\\n|| Context Accessors ||\n\\*=====================================*/\n\nexport interface ViewContextSecrets {\n appContext: AppContext;\n elementContext: ElementContext;\n}\n\nconst SECRETS = Symbol(\"VIEW_SECRETS\");\n\nexport function getViewSecrets(ctx: ViewContext): ViewContextSecrets {\n return (ctx as any)[SECRETS];\n}\n\n/*=====================================*\\\n|| View Init ||\n\\*=====================================*/\n\nexport function view<P>(callback: View<P>) {\n return callback;\n}\n\n/**\n * Parameters passed to the makeView function.\n */\ninterface ViewConfig<P> {\n view: View<P>;\n appContext: AppContext;\n elementContext: ElementContext;\n props: P;\n children?: Markup[];\n}\n\nexport function initView<P>(config: ViewConfig<P>): DOMHandle {\n const appContext = config.appContext;\n const elementContext = {\n ...config.elementContext,\n stores: new Map(),\n parent: config.elementContext,\n };\n const $$children = $$<DOMHandle[]>(renderMarkupToDOM(config.children ?? [], { appContext, elementContext }));\n\n let isConnected = false;\n\n // Lifecycle and observers\n const stopObserverCallbacks: (() => void)[] = [];\n const connectedCallbacks: (() => any)[] = [];\n const disconnectedCallbacks: (() => any)[] = [];\n const beforeConnectCallbacks: (() => void | Promise<void>)[] = [];\n const beforeDisconnectCallbacks: (() => void | Promise<void>)[] = [];\n\n const uniqueId = nanoid();\n\n const ctx: Omit<ViewContext, keyof DebugChannel> = {\n get uniqueId() {\n return uniqueId;\n },\n\n name: config.view.name ?? \"anonymous\",\n\n getStore(store: keyof BuiltInStores | Store<any, any>) {\n let name: string;\n\n if (typeof store === \"string\") {\n name = store as keyof BuiltInStores;\n } else {\n name = store.name;\n }\n\n if (typeof store !== \"string\") {\n let ec: ElementContext | undefined = elementContext;\n while (ec) {\n if (ec.stores.has(store)) {\n return ec.stores.get(store)?.instance!.exports;\n }\n ec = ec.parent;\n }\n }\n\n if (appContext.stores.has(store)) {\n const _store = appContext.stores.get(store)!;\n\n if (!_store.instance) {\n appContext.crashCollector.crash({\n componentName: ctx.name,\n error: new Error(`Store '${name}' is not registered on this app.`),\n });\n }\n\n return _store.instance!.exports;\n }\n\n appContext.crashCollector.crash({\n componentName: ctx.name,\n error: new Error(`Store '${name}' is not registered on this app.`),\n });\n },\n\n onConnected(callback) {\n connectedCallbacks.push(callback);\n },\n\n onDisconnected(callback) {\n disconnectedCallbacks.push(callback);\n },\n\n beforeConnect(callback) {\n beforeConnectCallbacks.push(callback);\n },\n\n beforeDisconnect(callback) {\n beforeDisconnectCallbacks.push(callback);\n },\n\n crash(error: Error) {\n config.appContext.crashCollector.crash({ error, componentName: ctx.name });\n },\n\n observe(...args: any[]) {\n const callback = args.pop();\n if (isConnected) {\n // If called when the component is connected, we assume this code is in a lifecycle hook\n // where it will be triggered at some point again after the component is reconnected.\n const stop = observe(args, callback);\n stopObserverCallbacks.push(stop);\n } else {\n // This should only happen if called in the body of the component function.\n // This code is not always re-run between when a component is disconnected and reconnected.\n connectedCallbacks.push(() => {\n const stop = observe(args, callback);\n stopObserverCallbacks.push(stop);\n });\n }\n },\n\n outlet() {\n return m(\"$outlet\", { $children: $($$children) });\n },\n };\n\n const debugChannel = appContext.debugHub.channel({\n get name() {\n return ctx.name;\n },\n });\n\n Object.defineProperties(ctx, Object.getOwnPropertyDescriptors(debugChannel));\n\n Object.defineProperty(ctx, SECRETS, {\n enumerable: false,\n configurable: false,\n value: {\n appContext,\n elementContext,\n } as ViewContextSecrets,\n });\n\n let rendered: DOMHandle | undefined;\n\n function initialize() {\n let result: unknown;\n\n try {\n result = config.view(config.props, ctx as ViewContext);\n } catch (error) {\n if (error instanceof Error) {\n appContext.crashCollector.crash({ error, componentName: ctx.name });\n }\n throw error;\n }\n\n if (result instanceof Promise) {\n appContext.crashCollector.crash({\n error: new TypeError(`View function cannot return a Promise.`),\n componentName: ctx.name,\n });\n }\n\n if (result === null) {\n // Do nothing.\n } else if (result instanceof Node) {\n rendered = getRenderHandle(renderMarkupToDOM(m(\"$node\", { value: result }), { appContext, elementContext }));\n } else if (isMarkup(result) || isArrayOf<Markup>(isMarkup, result)) {\n rendered = getRenderHandle(renderMarkupToDOM(result, { appContext, elementContext }));\n } else if (isReadable(result)) {\n rendered = getRenderHandle(\n renderMarkupToDOM(m(\"$observer\", { readables: [result], renderFn: (x) => x }), { appContext, elementContext }),\n );\n } else {\n console.warn(result, config);\n appContext.crashCollector.crash({\n error: new TypeError(\n `Expected '${\n config.view.name\n }' function to return a DOM node, Markup element, Readable or null. Got: ${typeOf(result)}`,\n ),\n componentName: ctx.name,\n });\n }\n }\n\n const handle: DOMHandle = {\n get node() {\n return rendered?.node!;\n },\n\n get connected() {\n return isConnected;\n },\n\n connect(parent: Node, after?: Node) {\n // Don't run lifecycle hooks or initialize if already connected.\n // Calling connect again can be used to re-order elements that are already connected to the DOM.\n const wasConnected = isConnected;\n\n if (!wasConnected) {\n initialize();\n while (beforeConnectCallbacks.length > 0) {\n const callback = beforeConnectCallbacks.shift()!;\n callback();\n }\n }\n\n if (rendered) {\n rendered.connect(parent, after);\n }\n\n if (!wasConnected) {\n isConnected = true;\n\n requestAnimationFrame(() => {\n while (connectedCallbacks.length > 0) {\n const callback = connectedCallbacks.shift()!;\n callback();\n }\n });\n }\n },\n\n disconnect() {\n while (beforeDisconnectCallbacks.length > 0) {\n const callback = beforeDisconnectCallbacks.shift()!;\n callback();\n }\n\n if (rendered) {\n rendered.disconnect();\n }\n\n isConnected = false;\n\n while (disconnectedCallbacks.length > 0) {\n const callback = disconnectedCallbacks.shift()!;\n callback();\n }\n\n while (stopObserverCallbacks.length > 0) {\n const callback = stopObserverCallbacks.shift()!;\n callback();\n }\n },\n\n async setChildren(children) {\n $$children.set(children);\n },\n };\n\n return handle;\n}\n", "import { type AppContext, type ElementContext } from \"../app.js\";\nimport { type DOMHandle } from \"../markup.js\";\nimport { $, $$, observe, type Readable, type Writable, type StopFunction } from \"../state.js\";\nimport { initView, type ViewContext, type ViewResult } from \"../view.js\";\n\n// ----- Types ----- //\n\ninterface RepeatOptions<T> {\n appContext: AppContext;\n elementContext: ElementContext;\n $items: Readable<T[]>;\n keyFn: (value: T, index: number) => string | number | symbol;\n renderFn: ($value: Readable<T>, $index: Readable<number>, ctx: ViewContext) => ViewResult;\n}\n\ntype ConnectedItem<T> = {\n key: any;\n $$value: Writable<T>;\n $$index: Writable<number>;\n handle: DOMHandle;\n};\n\n// ----- Code ----- //\n\nexport class Repeat<T> implements DOMHandle {\n node: Node;\n endNode: Node;\n $items: Readable<T[]>;\n stopCallback?: StopFunction;\n connectedItems: ConnectedItem<T>[] = [];\n appContext;\n elementContext;\n renderFn: ($value: Readable<T>, $index: Readable<number>, ctx: ViewContext) => ViewResult;\n keyFn: (value: T, index: number) => string | number | symbol;\n\n get connected() {\n return this.node.parentNode != null;\n }\n\n constructor({ appContext, elementContext, $items, renderFn, keyFn }: RepeatOptions<T>) {\n this.appContext = appContext;\n this.elementContext = elementContext;\n\n this.$items = $items;\n this.renderFn = renderFn;\n this.keyFn = keyFn;\n\n if (appContext.mode === \"development\") {\n this.node = document.createComment(\"Repeat\");\n this.endNode = document.createComment(\"/Repeat\");\n } else {\n this.node = document.createTextNode(\"\");\n this.endNode = document.createTextNode(\"\");\n }\n }\n\n connect(parent: Node, after?: Node) {\n if (!this.connected) {\n parent.insertBefore(this.node, after?.nextSibling ?? null);\n\n this.stopCallback = observe(this.$items, (value) => {\n this._update(Array.from(value));\n });\n }\n }\n\n disconnect() {\n if (this.stopCallback) {\n this.stopCallback();\n this.stopCallback = undefined;\n }\n\n if (this.connected) {\n this.node.parentNode?.removeChild(this.node);\n this.endNode.parentNode?.removeChild(this.endNode);\n }\n\n this._cleanup();\n }\n\n setChildren() {\n console.warn(\"setChildren is not implemented for repeat()\");\n }\n\n _cleanup() {\n for (const item of this.connectedItems) {\n item.handle.disconnect();\n }\n this.connectedItems = [];\n }\n\n _update(value: T[]) {\n if (value.length === 0 || !this.connected) {\n return this._cleanup();\n }\n\n type UpdateItem = { key: string | number | symbol; value: T; index: number };\n\n const potentialItems: UpdateItem[] = [];\n let index = 0;\n\n for (const item of value) {\n potentialItems.push({\n key: this.keyFn(item, index),\n value: item,\n index: index++,\n });\n }\n\n const newItems: ConnectedItem<T>[] = [];\n\n // Remove views for items that no longer exist in the new list.\n for (const connected of this.connectedItems) {\n const potentialItem = potentialItems.find((p) => p.key === connected.key);\n\n if (!potentialItem) {\n connected.handle.disconnect();\n }\n }\n\n // Add new views and update state for existing ones.\n for (const potential of potentialItems) {\n const connected = this.connectedItems.find((item) => item.key === potential.key);\n\n if (connected) {\n connected.$$value.set(potential.value);\n connected.$$index.set(potential.index);\n newItems[potential.index] = connected;\n } else {\n const $$value = $$(potential.value) as Writable<T>;\n const $$index = $$(potential.index);\n\n newItems[potential.index] = {\n key: potential.key,\n $$value,\n $$index,\n handle: initView({\n view: RepeatItemView,\n appContext: this.appContext,\n elementContext: this.elementContext,\n props: { $value: $($$value), $index: $($$index), renderFn: this.renderFn },\n }),\n };\n }\n }\n\n // Reconnect to ensure order. Lifecycle hooks won't be run again if the view is already connected.\n for (let i = 0; i < newItems.length; i++) {\n const item = newItems[i];\n const previous = newItems[i - 1]?.handle.node ?? this.node;\n item.handle.connect(this.node.parentNode!, previous);\n }\n\n this.connectedItems = newItems;\n\n if (this.appContext.mode === \"development\") {\n this.node.textContent = `Repeat (${newItems.length} item${newItems.length === 1 ? \"\" : \"s\"})`;\n\n const lastItem = newItems.at(-1)?.handle.node ?? this.node;\n this.node.parentNode?.insertBefore(this.endNode, lastItem.nextSibling);\n }\n }\n}\n\ninterface RepeatItemProps {\n $value: Readable<any>;\n $index: Readable<number>;\n renderFn: ($value: Readable<any>, $index: Readable<number>, ctx: ViewContext) => ViewResult;\n}\n\nfunction RepeatItemView({ $value, $index, renderFn }: RepeatItemProps, ctx: ViewContext) {\n return renderFn($value, $index, ctx);\n}\n", "import { type DOMHandle } from \"../markup.js\";\nimport { isReadable, observe, type Readable, type StopFunction } from \"../state.js\";\n\ninterface Stringable {\n toString(): string;\n}\n\ninterface TextOptions {\n value: Stringable | Readable<Stringable>;\n}\n\nexport class Text implements DOMHandle {\n node = document.createTextNode(\"\");\n value: Stringable | Readable<Stringable> = \"\";\n stopCallback?: StopFunction;\n\n get connected() {\n return this.node.parentNode != null;\n }\n\n constructor({ value }: TextOptions) {\n this.value = value;\n }\n\n async connect(parent: Node, after: Node | null = null) {\n if (!this.connected) {\n if (isReadable<Stringable>(this.value)) {\n this.stopCallback = observe(this.value, (value) => {\n this.update(value);\n });\n } else {\n this.update(this.value);\n }\n }\n\n parent.insertBefore(this.node, after?.nextSibling ?? null);\n }\n\n async disconnect() {\n if (this.connected) {\n if (this.stopCallback) {\n this.stopCallback();\n this.stopCallback = undefined;\n }\n\n this.node.parentNode!.removeChild(this.node);\n }\n }\n\n update(value?: Stringable) {\n if (value != null) {\n this.node.textContent = value.toString();\n } else {\n this.node.textContent = \"\";\n }\n }\n\n async setChildren() {}\n}\n", "import { type AppContext, type ElementContext } from \"./app.js\";\nimport { Conditional } from \"./nodes/cond.js\";\nimport { HTML } from \"./nodes/html.js\";\nimport { Observer } from \"./nodes/observer.js\";\nimport { Outlet } from \"./nodes/outlet.js\";\nimport { Portal } from \"./nodes/portal.js\";\nimport { Repeat } from \"./nodes/repeat.js\";\nimport { Text } from \"./nodes/text.js\";\nimport { $, isReadable, type Readable } from \"./state.js\";\nimport { isArray, isArrayOf, isFunction, isNumber, isObject, isString } from \"./typeChecking.js\";\nimport type { Renderable, Stringable } from \"./types.js\";\nimport { initView, type View, type ViewContext, type ViewResult } from \"./view.js\";\n\n/*===========================*\\\n|| Markup ||\n\\*===========================*/\n\nconst MARKUP = Symbol(\"Markup\");\n\n/**\n * Markup is a set of element metadata that hasn't been rendered to a DOMHandle yet.\n */\nexport interface Markup {\n type: string | View<any>;\n props?: Record<string, any>;\n children?: Markup[];\n}\n\n/**\n * DOMHandle is the generic interface for an element that can be manipulated by the framework.\n */\nexport interface DOMHandle {\n readonly node?: Node;\n readonly connected: boolean;\n\n connect(parent: Node, after?: Node): void;\n\n disconnect(): void;\n\n setChildren(children: DOMHandle[]): void;\n}\n\nexport function isMarkup(value: unknown): value is Markup {\n return isObject(value) && value[MARKUP] === true;\n}\n\nexport function isDOMHandle(value: unknown): value is DOMHandle {\n return isObject(value) && isFunction(value.connect) && isFunction(value.disconnect);\n}\n\nexport function toMarkup(renderables: Renderable | Renderable[]): Markup[] {\n if (!isArray(renderables)) {\n renderables = [renderables];\n }\n\n return renderables\n .flat(Infinity)\n .filter((x) => x !== null && x !== undefined && x !== false)\n .map((x) => {\n if (x instanceof Node) {\n return m(\"$node\", { value: x });\n }\n\n if (isMarkup(x)) {\n return x;\n }\n\n if (isString(x) || isNumber(x)) {\n return m(\"$text\", { value: x });\n }\n\n if (isReadable(x)) {\n return m(\"$observer\", {\n readables: [x],\n renderFn: (x) => x,\n });\n }\n\n console.error(x);\n throw new TypeError(`Unexpected child type. Got: ${x}`);\n });\n}\n\nexport interface MarkupAttributes {\n $text: { value: Stringable | Readable<Stringable> };\n $cond: { $predicate: Readable<any>; thenContent?: Renderable; elseContent?: Renderable };\n $repeat: {\n $items: Readable<any[]>;\n keyFn: (value: any, index: number) => string | number | symbol;\n renderFn: ($item: Readable<any>, $index: Readable<number>, c: ViewContext) => ViewResult;\n };\n $observer: {\n readables: Readable<any>[];\n renderFn: (...items: any) => Renderable;\n };\n $outlet: {\n $children: Readable<DOMHandle[]>;\n };\n $node: {\n value: Node;\n };\n $portal: {\n content: Renderable;\n parent: Node;\n };\n\n [tag: string]: Record<string, any>;\n}\n\nexport function m<T extends keyof MarkupAttributes>(\n type: T,\n attributes: MarkupAttributes[T],\n ...children: Renderable[]\n): Markup;\n\nexport function m<I>(type: View<I>, attributes?: I, ...children: Renderable[]): Markup;\n\nexport function m<P>(type: string | View<P>, props?: P, ...children: Renderable[]) {\n return {\n [MARKUP]: true,\n type,\n props,\n children: toMarkup(children),\n };\n}\n\n/*===========================*\\\n|| Markup Utils ||\n\\*===========================*/\n\n/**\n * Displays content conditionally. When `predicate` holds a truthy value, `thenContent` is displayed; when `predicate` holds a falsy value, `elseContent` is displayed.\n */\nexport function cond(predicate: any | Readable<any>, thenContent?: Renderable, elseContent?: Renderable): Markup {\n const $predicate = $(predicate);\n\n return m(\"$cond\", {\n $predicate,\n thenContent,\n elseContent,\n });\n}\n\n/**\n * Calls `renderFn` for each item in `items`. Dynamically adds and removes views as items change.\n * The result of `keyFn` is used to compare items and decide if item was added, removed or updated.\n */\nexport function repeat<T>(\n items: Readable<T[]> | T[],\n keyFn: (value: T, index: number) => string | number | symbol,\n renderFn: ($value: Readable<T>, $index: Readable<number>, ctx: ViewContext) => ViewResult,\n): Markup {\n const $items = $(items);\n\n return m(\"$repeat\", { $items, keyFn, renderFn });\n}\n\n/**\n * Render `content` into a `parent` node anywhere in the page, rather than at its position in the view.\n */\nexport function portal(content: Renderable, parent: Node) {\n return m(\"$portal\", { content, parent });\n}\n\n/*===========================*\\\n|| Render ||\n\\*===========================*/\n\ninterface RenderContext {\n appContext: AppContext;\n elementContext: ElementContext;\n}\n\n/**\n * Wraps any plain DOM node in a DOMHandle interface.\n */\nclass NodeHandle implements DOMHandle {\n node: Node;\n\n get connected() {\n return this.node.parentNode != null;\n }\n\n constructor(node: Node) {\n this.node = node;\n }\n\n async connect(parent: Node, after?: Node) {\n parent.insertBefore(this.node, after?.nextSibling ?? null);\n }\n\n async disconnect() {\n if (this.node.parentNode) {\n this.node.parentNode.removeChild(this.node);\n }\n }\n\n async setChildren(children: DOMHandle[]) {}\n}\n\nexport function renderMarkupToDOM(markup: Markup | Markup[], ctx: RenderContext): DOMHandle[] {\n const items = isArray(markup) ? markup : [markup];\n\n return items.map((item) => {\n if (isFunction(item.type)) {\n return initView({\n view: item.type as View<any>,\n props: item.props,\n children: item.children,\n appContext: ctx.appContext,\n elementContext: ctx.elementContext,\n });\n } else if (isString(item.type)) {\n switch (item.type) {\n case \"$node\": {\n const attrs = item.props! as MarkupAttributes[\"$node\"];\n return new NodeHandle(attrs.value);\n }\n case \"$text\": {\n const attrs = item.props! as MarkupAttributes[\"$text\"];\n return new Text({\n value: attrs.value,\n });\n }\n case \"$cond\": {\n const attrs = item.props! as MarkupAttributes[\"$cond\"];\n return new Conditional({\n $predicate: attrs.$predicate,\n thenContent: attrs.thenContent,\n elseContent: attrs.elseContent,\n appContext: ctx.appContext,\n elementContext: ctx.elementContext,\n });\n }\n case \"$repeat\": {\n const attrs = item.props! as MarkupAttributes[\"$repeat\"];\n return new Repeat({\n $items: attrs.$items,\n keyFn: attrs.keyFn,\n renderFn: attrs.renderFn,\n appContext: ctx.appContext,\n elementContext: ctx.elementContext,\n });\n }\n case \"$observer\": {\n const attrs = item.props! as MarkupAttributes[\"$observer\"];\n return new Observer({\n readables: attrs.readables,\n renderFn: attrs.renderFn,\n appContext: ctx.appContext,\n elementContext: ctx.elementContext,\n });\n }\n case \"$outlet\": {\n const attrs = item.props! as MarkupAttributes[\"$outlet\"];\n return new Outlet({\n $children: attrs.$children,\n appContext: ctx.appContext,\n elementContext: ctx.elementContext,\n });\n }\n case \"$portal\": {\n const attrs = item.props! as MarkupAttributes[\"$portal\"];\n return new Portal({\n content: attrs.content,\n parent: attrs.parent,\n appContext: ctx.appContext,\n elementContext: ctx.elementContext,\n });\n }\n default:\n if (item.type.startsWith(\"$\")) {\n throw new Error(`Unknown markup type: ${item.type}`);\n }\n return new HTML({\n tag: item.type,\n props: item.props,\n children: item.children,\n appContext: ctx.appContext,\n elementContext: ctx.elementContext,\n });\n }\n } else {\n throw new TypeError(`Expected a string or view function. Got: ${item.type}`);\n }\n });\n}\n\n/**\n * Combines one or more DOMHandles into a single DOMHandle.\n */\nexport function getRenderHandle(handles: DOMHandle[]): DOMHandle {\n if (handles.length === 1) {\n return handles[0];\n }\n\n const node = document.createComment(\"renderHandle\");\n\n let isConnected = false;\n\n return {\n get node() {\n return node;\n },\n get connected() {\n return isConnected;\n },\n connect(parent: Node, after?: Node) {\n parent.insertBefore(node, after ? after : null);\n\n for (const handle of handles) {\n const previous = handles[handles.length - 1]?.node ?? node;\n handle.connect(parent, previous);\n }\n\n isConnected = true;\n },\n disconnect() {\n if (isConnected) {\n for (const handle of handles) {\n handle.disconnect();\n }\n\n node.remove();\n }\n\n isConnected = false;\n },\n setChildren() {\n throw new Error(`setChildren not supported on renderHandle`);\n },\n };\n}\n\nexport function isRenderable(value: unknown): value is Renderable {\n return (\n value == null ||\n value === false ||\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n isMarkup(value) ||\n isReadable(value) ||\n isArrayOf(isRenderable, value)\n );\n}\n", "import { type AppContext, type ElementContext } from \"./app.js\";\nimport { type DebugChannel } from \"./classes/DebugHub.js\";\nimport { observe, type MaybeReadable, type ReadableValues } from \"./state.js\";\nimport { isObject, typeOf } from \"./typeChecking.js\";\nimport type { BuiltInStores } from \"./types.js\";\n\n/*=====================================*\\\n|| Types ||\n\\*=====================================*/\n\nexport type Store<O, E> = (context: StoreContext<O>) => E | Promise<E>;\n\nexport interface StoreContext<Options = any> extends DebugChannel {\n /**\n * Returns the shared instance of `store`.\n */\n getStore<T extends Store<any, any>>(store: T): ReturnType<T>;\n\n /**\n * Returns the shared instance of a built-in store.\n */\n getStore<N extends keyof BuiltInStores>(name: N): BuiltInStores[N];\n\n /**\n * Runs `callback` after this store is connected.\n */\n onConnected(callback: () => any): void;\n\n /**\n * Runs `callback` after this store is disconnected.\n */\n onDisconnected(callback: () => any): void;\n\n /**\n * The name of this store for logging and debugging purposes.\n */\n name: string;\n\n /**\n * Takes an Error object, unmounts the app and displays its crash page.\n */\n crash(error: Error): void;\n\n /**\n * Observes a readable value while this store is connected. Calls `callback` each time the value changes.\n */\n observe<T>(state: MaybeReadable<T>, callback: (currentValue: T) => void): void;\n\n /**\n * Observes a set of readable values while this store is connected.\n * Calls `callback` with each value in the same order as `readables` each time any of their values change.\n */\n observe<T extends MaybeReadable<any>[]>(\n states: [...T],\n callback: (...currentValues: ReadableValues<T>) => void\n ): void;\n\n observe<I1, I2>(\n state1: MaybeReadable<I1>,\n state2: MaybeReadable<I2>,\n callback: (value1: I1, value2: I2) => void\n ): void;\n\n observe<I1, I2, I3>(\n state1: MaybeReadable<I1>,\n state2: MaybeReadable<I2>,\n state3: MaybeReadable<I3>,\n callback: (value1: I1, value2: I2, value3: I3) => void\n ): void;\n\n observe<I1, I2, I3, I4>(\n state1: MaybeReadable<I1>,\n state2: MaybeReadable<I2>,\n state3: MaybeReadable<I3>,\n state4: MaybeReadable<I4>,\n callback: (value1: I1, value2: I2, value3: I3, value4: I4) => void\n ): void;\n\n observe<I1, I2, I3, I4, I5>(\n state1: MaybeReadable<I1>,\n state2: MaybeReadable<I2>,\n state3: MaybeReadable<I3>,\n state4: MaybeReadable<I4>,\n state5: MaybeReadable<I5>,\n callback: (value1: I1, value2: I2, value3: I3, value4: I4, value5: I5) => void\n ): void;\n\n observe<I1, I2, I3, I4, I5, I6>(\n state1: MaybeReadable<I1>,\n state2: MaybeReadable<I2>,\n state3: MaybeReadable<I3>,\n state4: MaybeReadable<I4>,\n state5: MaybeReadable<I5>,\n state6: MaybeReadable<I6>,\n callback: (value1: I1, value2: I2, value3: I3, value4: I4, value5: I5, value6: I6) => void\n ): void;\n\n observe<I1, I2, I3, I4, I5, I6, I7>(\n state1: MaybeReadable<I1>,\n state2: MaybeReadable<I2>,\n state3: MaybeReadable<I3>,\n state4: MaybeReadable<I4>,\n state5: MaybeReadable<I5>,\n state6: MaybeReadable<I6>,\n state7: MaybeReadable<I7>,\n callback: (value1: I1, value2: I2, value3: I3, value4: I4, value5: I5, value6: I6, value7: I7) => void\n ): void;\n\n observe<I1, I2, I3, I4, I5, I6, I7, I8>(\n state1: MaybeReadable<I1>,\n state2: MaybeReadable<I2>,\n state3: MaybeReadable<I3>,\n state4: MaybeReadable<I4>,\n state5: MaybeReadable<I5>,\n state6: MaybeReadable<I6>,\n state7: MaybeReadable<I7>,\n state8: MaybeReadable<I8>,\n callback: (value1: I1, value2: I2, value3: I3, value4: I4, value5: I5, value6: I6, value7: I7, value8: I8) => void\n ): void;\n\n observe<I1, I2, I3, I4, I5, I6, I7, I8, I9>(\n state1: MaybeReadable<I1>,\n state2: MaybeReadable<I2>,\n state3: MaybeReadable<I3>,\n state4: MaybeReadable<I4>,\n state5: MaybeReadable<I5>,\n state6: MaybeReadable<I6>,\n state7: MaybeReadable<I7>,\n state8: MaybeReadable<I8>,\n state9: MaybeReadable<I9>,\n callback: (\n value1: I1,\n value2: I2,\n value3: I3,\n value4: I4,\n value5: I5,\n value6: I6,\n value7: I7,\n value8: I8,\n value9: I9\n ) => void\n ): void;\n\n observe<I1, I2, I3, I4, I5, I6, I7, I8, I9, I10>(\n state1: MaybeReadable<I1>,\n state2: MaybeReadable<I2>,\n state3: MaybeReadable<I3>,\n state4: MaybeReadable<I4>,\n state5: MaybeReadable<I5>,\n state6: MaybeReadable<I6>,\n state7: MaybeReadable<I7>,\n state8: MaybeReadable<I8>,\n state9: MaybeReadable<I9>,\n state10: MaybeReadable<I10>,\n callback: (\n value1: I1,\n value2: I2,\n value3: I3,\n value4: I4,\n value5: I5,\n value6: I6,\n value7: I7,\n value8: I8,\n value9: I9,\n value10: I10\n ) => void\n ): void;\n\n /**\n * Options this store was initialized with.\n */\n options: Options;\n}\n\n/*=====================================*\\\n|| Context Accessors ||\n\\*=====================================*/\n\nexport interface StoreContextSecrets {\n appContext: AppContext;\n elementContext: ElementContext;\n}\n\nconst SECRETS = Symbol(\"STORE_SECRETS\");\n\nexport function getStoreSecrets(c: StoreContext): StoreContextSecrets {\n return (c as any)[SECRETS];\n}\n\n/*=====================================*\\\n|| Store Init ||\n\\*=====================================*/\n\nexport function store<O>(callback: Store<any, O>) {\n return callback;\n}\n\n/**\n * Parameters passed to the makeStore function.\n */\ninterface StoreConfig<O> {\n store: Store<O, any>;\n appContext: AppContext;\n elementContext: ElementContext;\n options?: O;\n}\n\nexport function initStore<O>(config: StoreConfig<O>) {\n const appContext = config.appContext;\n const elementContext = config.elementContext;\n\n let isConnected = false;\n\n // Lifecycle and observers\n const stopObserverCallbacks: (() => void)[] = [];\n const connectedCallbacks: (() => any)[] = [];\n const disconnectedCallbacks: (() => any)[] = [];\n\n const ctx: Omit<StoreContext, keyof DebugChannel> = {\n name: config.store.name ?? \"anonymous\",\n options: config.options,\n\n getStore(store: keyof BuiltInStores | Store<any, any>) {\n let name: string;\n\n if (typeof store === \"string\") {\n name = store as keyof BuiltInStores;\n } else {\n name = store.name;\n }\n\n if (typeof store !== \"string\") {\n let ec: ElementContext | undefined = elementContext;\n while (ec) {\n if (ec.stores.has(store)) {\n return ec.stores.get(store)?.instance!.exports;\n }\n ec = ec.parent;\n }\n }\n\n if (appContext.stores.has(store)) {\n const _store = appContext.stores.get(store)!;\n\n if (!_store.instance) {\n appContext.crashCollector.crash({\n componentName: ctx.name,\n error: new Error(\n `Store '${name}' was accessed before it was set up. Make sure '${name}' is registered before components that access it.`\n ),\n });\n }\n\n return _store.instance!.exports;\n }\n\n appContext.crashCollector.crash({\n componentName: ctx.name,\n error: new Error(`Store '${name}' is not registered on this app.`),\n });\n },\n\n onConnected(callback: () => any) {\n connectedCallbacks.push(callback);\n },\n\n onDisconnected(callback: () => any) {\n disconnectedCallbacks.push(callback);\n },\n\n crash(error: Error) {\n config.appContext.crashCollector.crash({ error, componentName: ctx.name });\n },\n\n observe(...args: any[]) {\n const callback = args.pop();\n const readables = args.flat();\n if (isConnected) {\n // If called when the component is connected, we assume this code is in a lifecycle hook\n // where it will be triggered at some point again after the component is reconnected.\n const stop = observe(readables, callback);\n stopObserverCallbacks.push(stop);\n } else {\n // This should only happen if called in the body of the component function.\n // This code is not always re-run between when a component is disconnected and reconnected.\n connectedCallbacks.push(() => {\n const stop = observe(readables, callback);\n stopObserverCallbacks.push(stop);\n });\n }\n },\n };\n\n const debugChannel = appContext.debugHub.channel({\n get name() {\n return ctx.name;\n },\n });\n\n Object.defineProperties(ctx, Object.getOwnPropertyDescriptors(debugChannel));\n\n Object.defineProperty(ctx, SECRETS, {\n enumerable: false,\n configurable: false,\n value: {\n appContext,\n elementContext,\n } as StoreContextSecrets,\n });\n\n let exports: any;\n\n return {\n get name() {\n return ctx.name;\n },\n\n get exports() {\n return exports;\n },\n\n setup() {\n let result: unknown;\n\n try {\n result = config.store(ctx as StoreContext<O>);\n } catch (error) {\n if (error instanceof Error) {\n appContext.crashCollector.crash({ error, componentName: ctx.name });\n } else {\n throw error;\n }\n }\n\n if (result instanceof Promise) {\n appContext.crashCollector.crash({\n error: new TypeError(`Store function cannot return a Promise`),\n componentName: ctx.name,\n });\n }\n\n if (!isObject(result)) {\n const error = new TypeError(`Expected ${ctx.name} function to return an object. Got: ${typeOf(result)}`);\n appContext.crashCollector.crash({ error, componentName: ctx.name });\n }\n\n exports = result;\n },\n\n connect() {\n while (connectedCallbacks.length > 0) {\n const callback = connectedCallbacks.shift()!;\n callback();\n }\n },\n\n disconnect() {\n while (disconnectedCallbacks.length > 0) {\n const callback = disconnectedCallbacks.shift()!;\n callback();\n }\n },\n };\n}\n", "import { $, $$ } from \"../state.js\";\nimport { type StoreContext } from \"../store.js\";\n\ntype ScreenOrientation = \"landscape\" | \"portrait\";\ntype ColorScheme = \"light\" | \"dark\";\n\nexport function DocumentStore(ctx: StoreContext) {\n ctx.name = \"dolla/document\";\n\n const $$title = $$(document.title);\n const $$visibility = $$(document.visibilityState);\n const $$orientation = $$<ScreenOrientation>(\"landscape\");\n const $$colorScheme = $$<ColorScheme>(\"light\");\n\n /* ----- Title and Visibility ----- */\n\n ctx.observe($$title, (current) => {\n document.title = current;\n });\n\n const onVisibilityChange = () => {\n $$visibility.set(document.visibilityState);\n };\n\n const onFocus = () => {\n $$visibility.set(\"visible\");\n };\n\n /* ----- Orientation ----- */\n\n const landscapeQuery = window.matchMedia(\"(orientation: landscape)\");\n\n function onOrientationChange(e: MediaQueryList | MediaQueryListEvent) {\n $$orientation.set(e.matches ? \"landscape\" : \"portrait\");\n }\n\n // Read initial orientation.\n onOrientationChange(landscapeQuery);\n\n /* ----- Color Scheme ----- */\n\n const colorSchemeQuery = window.matchMedia(\"(prefers-color-scheme: dark)\");\n\n function onColorChange(e: MediaQueryList | MediaQueryListEvent) {\n $$colorScheme.set(e.matches ? \"dark\" : \"light\");\n }\n\n // Read initial color scheme.\n onColorChange(colorSchemeQuery);\n\n /* ----- Lifecycle ----- */\n\n // Listen for changes while connected.\n ctx.onConnected(function () {\n landscapeQuery.addEventListener(\"change\", onOrientationChange);\n colorSchemeQuery.addEventListener(\"change\", onColorChange);\n document.addEventListener(\"visibilitychange\", onVisibilityChange);\n window.addEventListener(\"focus\", onFocus);\n });\n ctx.onDisconnected(function () {\n landscapeQuery.removeEventListener(\"change\", onOrientationChange);\n colorSchemeQuery.removeEventListener(\"change\", onColorChange);\n document.removeEventListener(\"visibilitychange\", onVisibilityChange);\n window.removeEventListener(\"focus\", onFocus);\n });\n\n /* ----- Exports ----- */\n\n return {\n $$title,\n $visibility: $($$visibility),\n $orientation: $($$orientation),\n $colorScheme: $($$colorScheme),\n };\n}\n", "import { type StoreContext } from \"../store.js\";\n\n/**\n * Batches DOM updates for better performance.\n */\nexport function RenderStore(ctx: StoreContext) {\n ctx.name = \"dolla/render\";\n\n // Keyed updates ensure only the most recent callback queued with a certain key\n // will be called, keeping DOM operations to a minimum.\n const keyedUpdates = new Map<string, () => void>();\n\n // All unkeyed updates are run on every batch.\n let unkeyedUpdates: (() => void)[] = [];\n\n let reads: (() => void)[] = [];\n\n let isUpdating = false;\n let isConnected = false;\n\n ctx.onConnected(() => {\n isConnected = true;\n });\n\n ctx.onDisconnected(() => {\n isConnected = false;\n });\n\n function runUpdates() {\n const totalQueued = keyedUpdates.size + unkeyedUpdates.length;\n\n if (!isConnected || totalQueued === 0) {\n isUpdating = false;\n }\n\n if (!isUpdating) {\n for (const callback of reads) {\n callback();\n }\n reads = [];\n return;\n }\n\n requestAnimationFrame(() => {\n ctx.info(`Batching ${keyedUpdates.size + unkeyedUpdates.length} queued DOM update(s).`);\n\n // Run keyed updates first.\n for (const callback of keyedUpdates.values()) {\n callback();\n }\n keyedUpdates.clear();\n\n // Run unkeyed updates second.\n for (const callback of unkeyedUpdates) {\n callback();\n }\n unkeyedUpdates = [];\n\n // Trigger again to catch updates queued while this batch was running.\n runUpdates();\n });\n }\n\n return {\n /**\n * Queues a callback to run in the next render batch.\n * Running your DOM mutations in update callbacks reduces layout thrashing.\n * Returns a Promise that resolves once the callback has run.\n */\n update(callback: () => void, key?: string): Promise<void> {\n return new Promise((resolve) => {\n if (key) {\n keyedUpdates.set(key, () => {\n callback();\n resolve();\n });\n } else {\n unkeyedUpdates.push(() => {\n callback();\n resolve();\n });\n }\n\n if (!isUpdating && isConnected) {\n isUpdating = true;\n runUpdates();\n }\n });\n },\n\n /**\n * Queues a callback that reads DOM information to run after the next render batch,\n * ensuring all writes have been performed before reading.\n * Returns a Promise that resolves once the callback has run.\n */\n read(callback: () => void): Promise<void> {\n return new Promise((resolve) => {\n reads.push(() => {\n callback();\n resolve();\n });\n\n if (!isUpdating && isConnected) {\n isUpdating = true;\n runUpdates();\n }\n });\n },\n };\n}\n", "import { m } from \"../markup.js\";\n\ntype CrashPageProps = {\n message: string;\n error: Error;\n componentName: string;\n};\n\nexport function DefaultCrashPage({ message, error, componentName }: CrashPageProps) {\n return m(\n \"div\",\n {\n style: {\n backgroundColor: \"#880000\",\n color: \"#fff\",\n padding: \"2rem\",\n position: \"fixed\",\n inset: 0,\n fontSize: \"20px\",\n },\n },\n m(\"h1\", { style: { marginBottom: \"0.5rem\" } }, \"The app has crashed\"),\n m(\n \"p\",\n { style: { marginBottom: \"0.25rem\" } },\n m(\"span\", { style: { fontFamily: \"monospace\" } }, componentName),\n \" says:\",\n ),\n m(\n \"blockquote\",\n {\n style: {\n backgroundColor: \"#991111\",\n padding: \"0.25em\",\n borderRadius: \"6px\",\n fontFamily: \"monospace\",\n marginBottom: \"1rem\",\n },\n },\n m(\n \"span\",\n {\n style: {\n display: \"inline-block\",\n backgroundColor: \"red\",\n padding: \"0.1em 0.4em\",\n marginRight: \"0.5em\",\n borderRadius: \"4px\",\n fontSize: \"0.9em\",\n fontWeight: \"bold\",\n },\n },\n error.name,\n ),\n message,\n ),\n m(\"p\", {}, \"Please see the browser console for details.\"),\n );\n}\n", "import { type ViewContext } from \"../view.js\";\n\nexport function DefaultView(_: {}, ctx: ViewContext) {\n return ctx.outlet();\n}\n", "import { CrashCollector } from \"./classes/CrashCollector.js\";\nimport { DebugHub, type DebugOptions } from \"./classes/DebugHub.js\";\nimport { DOMHandle, m } from \"./markup.js\";\nimport { initStore, type Store } from \"./store.js\";\nimport { DocumentStore } from \"./stores/document.js\";\nimport { RenderStore } from \"./stores/render.js\";\nimport { assertFunction, assertInstanceOf, isObject, isString } from \"./typeChecking.js\";\nimport { type BuiltInStores } from \"./types.js\";\nimport { merge } from \"./utils.js\";\nimport { initView, type View } from \"./view.js\";\nimport { DefaultCrashPage } from \"./views/default-crash-page.js\";\nimport { DefaultView } from \"./views/default-view.js\";\n\n// ----- Types ----- //\n\ninterface StoreConfig<O, E> {\n store: Store<O, E>;\n options?: O;\n}\n\ninterface IAppOptions {\n /**\n * Options for the debug system.\n */\n debug?: DebugOptions;\n\n /**\n * The view to be rendered by the app.\n */\n view?: View<{}>;\n\n /**\n * App-level stores.\n */\n stores?: StoreConfig<any, any>[];\n\n /**\n * Configures the app based on the environment it's running in.\n */\n mode?: \"development\" | \"production\";\n}\n\nexport interface AppContext {\n crashCollector: CrashCollector;\n debugHub: DebugHub;\n stores: Map<keyof BuiltInStores | StoreRegistration[\"store\"], StoreRegistration>;\n mode: \"development\" | \"production\";\n rootElement?: HTMLElement;\n rootView?: DOMHandle;\n}\n\nexport interface ElementContext {\n stores: Map<StoreRegistration[\"store\"], StoreRegistration>;\n isSVG?: boolean;\n componentName?: string; // name of the nearest parent component\n parent?: ElementContext;\n}\n\n/**\n * An object kept in App for each store registered with `addStore`.\n */\nexport interface StoreRegistration<O = any> {\n store: Store<O, any>;\n options?: O;\n instance?: ReturnType<typeof initStore>;\n}\n\ninterface ConfigureContext {\n /**\n * Returns the shared instance of `store`.\n */\n getStore<T extends Store<any, any>>(store: T): ReturnType<T>;\n\n /**\n * Returns the shared instance of a built-in store.\n */\n getStore<N extends keyof BuiltInStores>(name: N): BuiltInStores[N];\n}\n\ntype ConfigureCallback = (ctx: ConfigureContext) => void | Promise<void>;\n\nexport interface IApp {\n readonly isConnected: boolean;\n\n /**\n * Runs `callback` after app-level stores are connected to the app, but before views are connected to the DOM.\n * Use this function to run async configuration code before displaying content to the user.\n *\n * Note that this will delay content being displayed on the screen, so using some kind of splash screen is recommended.\n */\n configure(callback: ConfigureCallback): this;\n\n /**\n * Initializes and connects the app as a child of `element`.\n *\n * @param element - A selector string or a DOM node to attach to. If a string, follows the same format as that taken by `document.querySelector`.\n */\n connect(selector: string | Node): Promise<void>;\n\n /**\n * Disconnects views and tears down globals, removing the app from the page.\n */\n disconnect(): Promise<void>;\n}\n\n// ----- Code ----- //\n\nfunction isAppOptions(value: unknown): value is IAppOptions {\n return isObject(value);\n}\n\nexport function App(options?: IAppOptions): IApp {\n if (options && !isAppOptions(options)) {\n throw new TypeError(`App options must be an object. Got: ${options}`);\n }\n\n let isConnected = false;\n let mainView = m(options?.view ?? DefaultView);\n let configureCallback: ConfigureCallback | undefined;\n\n const settings: IAppOptions = merge(\n {\n debug: {\n filter: \"*,-dolla/*\",\n log: \"development\", // Only print logs in development.\n warn: \"development\", // Only print warnings in development.\n error: true, // Always print errors.\n },\n mode: \"production\",\n },\n options ?? {},\n );\n\n const stores = new Map<keyof BuiltInStores | Store<any, any>, StoreRegistration>([\n [\"render\", { store: RenderStore }],\n [\"document\", { store: DocumentStore }],\n ]);\n\n if (options?.stores) {\n for (const entry of options.stores) {\n assertFunction(entry.store, `Expected a store function. Got type: %t, value: %v`);\n stores.set(entry.store, entry);\n }\n }\n\n /*=============================*\\\n || Logging & Error Handling ||\n \\*=============================*/\n\n // Crash collector is used by components to handle crashes and errors.\n const crashCollector = new CrashCollector();\n const debugHub = new DebugHub({ ...settings.debug, crashCollector, mode: settings.mode! });\n const debugChannel = debugHub.channel({ name: \"dolla/App\" });\n\n // When an error of \"crash\" severity is reported by a component,\n // the app is disconnected and a crash page is connected.\n crashCollector.onError(async ({ error, severity, componentName }) => {\n // Disconnect app and connect crash page on \"crash\" severity.\n if (severity === \"crash\") {\n await disconnect();\n\n const instance = initView({\n view: DefaultCrashPage,\n appContext,\n elementContext,\n props: {\n message: error.message,\n error: error,\n componentName,\n },\n });\n\n instance.connect(appContext.rootElement!);\n }\n });\n\n /*=============================*\\\n || App Lifecycle ||\n \\*=============================*/\n\n async function connect(selector: string | Node) {\n return new Promise<void>(async (resolve) => {\n let element: HTMLElement | null = null;\n\n if (isString(selector)) {\n element = document.querySelector(selector);\n assertInstanceOf(HTMLElement, element, `Selector string '${selector}' did not match any element.`);\n }\n\n assertInstanceOf(HTMLElement, element, \"Expected a DOM node or a selector string. Got type: %t, value: %v\");\n\n appContext.rootElement = element!;\n\n // First, initialize the root view. The router store needs this to connect the initial route.\n appContext.rootView = initView({\n view: mainView.type as View<any>,\n props: mainView.props,\n appContext,\n elementContext,\n });\n\n // Initialize stores.\n for (let [key, item] of stores.entries()) {\n const { store, options } = item;\n\n // Channel prefix is displayed before the global's name in console messages that go through a debug channel.\n // Bundled stores get an additional 'dolla/' prefix so it's clear messages are from the framework.\n // 'dolla/*' messages are filtered out by default, but this can be overridden with the app's `debug.filter` option.\n const channelPrefix = isString(key) ? \"dolla/store\" : \"store\";\n const label = isString(key) ? key : store.name ?? \"(anonymous)\";\n const config = {\n store,\n appContext,\n elementContext,\n channelPrefix,\n label,\n options: options ?? {},\n };\n\n const instance = initStore(config);\n\n instance.setup();\n\n // Add instance and mark as ready.\n stores.set(key, { ...item, instance });\n }\n\n for (const { instance } of stores.values()) {\n instance!.connect();\n }\n\n if (configureCallback) {\n await configureCallback({\n // TODO: Add context methods\n getStore(store: keyof BuiltInStores | Store<any, any>) {\n let name: string;\n\n if (typeof store === \"string\") {\n name = store as keyof BuiltInStores;\n } else {\n name = store.name;\n }\n\n if (typeof store !== \"string\") {\n let ec: ElementContext | undefined = elementContext;\n while (ec) {\n if (ec.stores.has(store)) {\n return ec.stores.get(store)?.instance!.exports;\n }\n ec = ec.parent;\n }\n }\n\n if (appContext.stores.has(store)) {\n const _store = appContext.stores.get(store)!;\n\n if (!_store.instance) {\n appContext.crashCollector.crash({\n componentName: \"@manyducks.co/dolla/App\",\n error: new Error(`Store '${name}' is not registered on this app.`),\n });\n }\n\n return _store.instance!.exports;\n }\n\n appContext.crashCollector.crash({\n componentName: \"@manyducks.co/dolla/App\",\n error: new Error(`Store '${name}' is not registered on this app.`),\n });\n },\n });\n }\n\n // Then connect the root view.\n appContext.rootView!.connect(appContext.rootElement!);\n\n // The app is now connected.\n isConnected = true;\n\n resolve();\n });\n }\n\n async function disconnect() {\n if (isConnected) {\n // Remove the root view from the page (runs teardown callbacks on all connected views).\n appContext.rootView!.disconnect();\n\n // The app is considered disconnected at this point\n isConnected = false;\n\n // Disconnect stores\n for (const { instance } of stores.values()) {\n instance!.disconnect();\n }\n }\n }\n\n /*=============================*\\\n || Contexts ||\n \\*=============================*/\n\n const appContext: AppContext = {\n crashCollector,\n debugHub,\n stores,\n mode: settings.mode ?? \"production\",\n };\n const elementContext: ElementContext = {\n stores: new Map(),\n };\n\n /*=============================*\\\n || App Object ||\n \\*=============================*/\n\n const app = {\n connect,\n disconnect,\n\n get isConnected() {\n return isConnected;\n },\n\n configure(callback: ConfigureCallback) {\n if (configureCallback !== undefined) {\n debugChannel.warn(`Configure callback is already defined. Only the final configure call will take effect.`);\n }\n\n configureCallback = callback;\n\n return app;\n },\n };\n\n return app;\n}\n", "import { type ViewContext } from \"../view.js\";\n\nexport function Fragment(_: {}, ctx: ViewContext) {\n return ctx.outlet();\n}\n", "import { Store, initStore } from \"../store.js\";\nimport { isFunction } from \"../typeChecking.js\";\nimport { ViewContext, getViewSecrets } from \"../view.js\";\n\nexport interface StoreConfig<O, E> {\n store: Store<O, E>;\n options?: O;\n}\n\nexport interface StoreScopeProps {\n stores: (StoreConfig<unknown, unknown> | Store<unknown, unknown>)[];\n}\n\n/**\n * Creates an instance of a store available only to children of this StoreScope.\n */\nexport function StoreScope(props: StoreScopeProps, ctx: ViewContext) {\n const { appContext, elementContext } = getViewSecrets(ctx);\n\n const instances: ReturnType<typeof initStore>[] = [];\n\n for (const config of props.stores) {\n let store: Store<unknown, unknown>;\n let options: unknown;\n\n if (isFunction(config)) {\n store = config as Store<unknown, unknown>;\n } else {\n store = (config as StoreConfig<unknown, unknown>).store;\n options = (config as StoreConfig<unknown, unknown>).options;\n }\n\n const instance = initStore({\n store,\n options,\n appContext,\n elementContext,\n });\n\n instance.setup();\n\n elementContext.stores.set(store, { store, options, instance });\n\n instances.push(instance);\n }\n\n ctx.beforeConnect(() => {\n for (const instance of instances) {\n instance.connect();\n }\n });\n\n ctx.onDisconnected(() => {\n for (const instance of instances) {\n instance.disconnect();\n }\n });\n\n return ctx.outlet();\n}\n", "export default function _extends() {\n _extends = Object.assign || function (target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n\n for (var key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n }\n\n return target;\n };\n\n return _extends.apply(this, arguments);\n}", "import _extends from '@babel/runtime/helpers/esm/extends';\n\n/**\r\n * Actions represent the type of change to a location value.\r\n *\r\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#action\r\n */\nvar Action;\n\n(function (Action) {\n /**\r\n * A POP indicates a change to an arbitrary index in the history stack, such\r\n * as a back or forward navigation. It does not describe the direction of the\r\n * navigation, only that the current index changed.\r\n *\r\n * Note: This is the default action for newly created history objects.\r\n */\n Action[\"Pop\"] = \"POP\";\n /**\r\n * A PUSH indicates a new entry being added to the history stack, such as when\r\n * a link is clicked and a new page loads. When this happens, all subsequent\r\n * entries in the stack are lost.\r\n */\n\n Action[\"Push\"] = \"PUSH\";\n /**\r\n * A REPLACE indicates the entry at the current index in the history stack\r\n * being replaced by a new one.\r\n */\n\n Action[\"Replace\"] = \"REPLACE\";\n})(Action || (Action = {}));\n\nvar readOnly = process.env.NODE_ENV !== \"production\" ? function (obj) {\n return Object.freeze(obj);\n} : function (obj) {\n return obj;\n};\n\nfunction warning(cond, message) {\n if (!cond) {\n // eslint-disable-next-line no-console\n if (typeof console !== 'undefined') console.warn(message);\n\n try {\n // Welcome to debugging history!\n //\n // This error is thrown as a convenience so you can more easily\n // find the source for a warning that appears in the console by\n // enabling \"pause on exceptions\" in your JavaScript debugger.\n throw new Error(message); // eslint-disable-next-line no-empty\n } catch (e) {}\n }\n}\n\nvar BeforeUnloadEventType = 'beforeunload';\nvar HashChangeEventType = 'hashchange';\nvar PopStateEventType = 'popstate';\n/**\r\n * Browser history stores the location in regular URLs. This is the standard for\r\n * most web apps, but it requires some configuration on the server to ensure you\r\n * serve the same app at multiple URLs.\r\n *\r\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createbrowserhistory\r\n */\n\nfunction createBrowserHistory(options) {\n if (options === void 0) {\n options = {};\n }\n\n var _options = options,\n _options$window = _options.window,\n window = _options$window === void 0 ? document.defaultView : _options$window;\n var globalHistory = window.history;\n\n function getIndexAndLocation() {\n var _window$location = window.location,\n pathname = _window$location.pathname,\n search = _window$location.search,\n hash = _window$location.hash;\n var state = globalHistory.state || {};\n return [state.idx, readOnly({\n pathname: pathname,\n search: search,\n hash: hash,\n state: state.usr || null,\n key: state.key || 'default'\n })];\n }\n\n var blockedPopTx = null;\n\n function handlePop() {\n if (blockedPopTx) {\n blockers.call(blockedPopTx);\n blockedPopTx = null;\n } else {\n var nextAction = Action.Pop;\n\n var _getIndexAndLocation = getIndexAndLocation(),\n nextIndex = _getIndexAndLocation[0],\n nextLocation = _getIndexAndLocation[1];\n\n if (blockers.length) {\n if (nextIndex != null) {\n var delta = index - nextIndex;\n\n if (delta) {\n // Revert the POP\n blockedPopTx = {\n action: nextAction,\n location: nextLocation,\n retry: function retry() {\n go(delta * -1);\n }\n };\n go(delta);\n }\n } else {\n // Trying to POP to a location with no index. We did not create\n // this location, so we can't effectively block the navigation.\n process.env.NODE_ENV !== \"production\" ? warning(false, // TODO: Write up a doc that explains our blocking strategy in\n // detail and link to it here so people can understand better what\n // is going on and how to avoid it.\n \"You are trying to block a POP navigation to a location that was not \" + \"created by the history library. The block will fail silently in \" + \"production, but in general you should do all navigation with the \" + \"history library (instead of using window.history.pushState directly) \" + \"to avoid this situation.\") : void 0;\n }\n } else {\n applyTx(nextAction);\n }\n }\n }\n\n window.addEventListener(PopStateEventType, handlePop);\n var action = Action.Pop;\n\n var _getIndexAndLocation2 = getIndexAndLocation(),\n index = _getIndexAndLocation2[0],\n location = _getIndexAndLocation2[1];\n\n var listeners = createEvents();\n var blockers = createEvents();\n\n if (index == null) {\n index = 0;\n globalHistory.replaceState(_extends({}, globalHistory.state, {\n idx: index\n }), '');\n }\n\n function createHref(to) {\n return typeof to === 'string' ? to : createPath(to);\n } // state defaults to `null` because `window.history.state` does\n\n\n function getNextLocation(to, state) {\n if (state === void 0) {\n state = null;\n }\n\n return readOnly(_extends({\n pathname: location.pathname,\n hash: '',\n search: ''\n }, typeof to === 'string' ? parsePath(to) : to, {\n state: state,\n key: createKey()\n }));\n }\n\n function getHistoryStateAndUrl(nextLocation, index) {\n return [{\n usr: nextLocation.state,\n key: nextLocation.key,\n idx: index\n }, createHref(nextLocation)];\n }\n\n function allowTx(action, location, retry) {\n return !blockers.length || (blockers.call({\n action: action,\n location: location,\n retry: retry\n }), false);\n }\n\n function applyTx(nextAction) {\n action = nextAction;\n\n var _getIndexAndLocation3 = getIndexAndLocation();\n\n index = _getIndexAndLocation3[0];\n location = _getIndexAndLocation3[1];\n listeners.call({\n action: action,\n location: location\n });\n }\n\n function push(to, state) {\n var nextAction = Action.Push;\n var nextLocation = getNextLocation(to, state);\n\n function retry() {\n push(to, state);\n }\n\n if (allowTx(nextAction, nextLocation, retry)) {\n var _getHistoryStateAndUr = getHistoryStateAndUrl(nextLocation, index + 1),\n historyState = _getHistoryStateAndUr[0],\n url = _getHistoryStateAndUr[1]; // TODO: Support forced reloading\n // try...catch because iOS limits us to 100 pushState calls :/\n\n\n try {\n globalHistory.pushState(historyState, '', url);\n } catch (error) {\n // They are going to lose state here, but there is no real\n // way to warn them about it since the page will refresh...\n window.location.assign(url);\n }\n\n applyTx(nextAction);\n }\n }\n\n function replace(to, state) {\n var nextAction = Action.Replace;\n var nextLocation = getNextLocation(to, state);\n\n function retry() {\n replace(to, state);\n }\n\n if (allowTx(nextAction, nextLocation, retry)) {\n var _getHistoryStateAndUr2 = getHistoryStateAndUrl(nextLocation, index),\n historyState = _getHistoryStateAndUr2[0],\n url = _getHistoryStateAndUr2[1]; // TODO: Support forced reloading\n\n\n globalHistory.replaceState(historyState, '', url);\n applyTx(nextAction);\n }\n }\n\n function go(delta) {\n globalHistory.go(delta);\n }\n\n var history = {\n get action() {\n return action;\n },\n\n get location() {\n return location;\n },\n\n createHref: createHref,\n push: push,\n replace: replace,\n go: go,\n back: function back() {\n go(-1);\n },\n forward: function forward() {\n go(1);\n },\n listen: function listen(listener) {\n return listeners.push(listener);\n },\n block: function block(blocker) {\n var unblock = blockers.push(blocker);\n\n if (blockers.length === 1) {\n window.addEventListener(BeforeUnloadEventType, promptBeforeUnload);\n }\n\n return function () {\n unblock(); // Remove the beforeunload listener so the document may\n // still be salvageable in the pagehide event.\n // See https://html.spec.whatwg.org/#unloading-documents\n\n if (!blockers.length) {\n window.removeEventListener(BeforeUnloadEventType, promptBeforeUnload);\n }\n };\n }\n };\n return history;\n}\n/**\r\n * Hash history stores the location in window.location.hash. This makes it ideal\r\n * for situations where you don't want to send the location to the server for\r\n * some reason, either because you do cannot configure it or the URL space is\r\n * reserved for something else.\r\n *\r\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createhashhistory\r\n */\n\nfunction createHashHistory(options) {\n if (options === void 0) {\n options = {};\n }\n\n var _options2 = options,\n _options2$window = _options2.window,\n window = _options2$window === void 0 ? document.defaultView : _options2$window;\n var globalHistory = window.history;\n\n function getIndexAndLocation() {\n var _parsePath = parsePath(window.location.hash.substr(1)),\n _parsePath$pathname = _parsePath.pathname,\n pathname = _parsePath$pathname === void 0 ? '/' : _parsePath$pathname,\n _parsePath$search = _parsePath.search,\n search = _parsePath$search === void 0 ? '' : _parsePath$search,\n _parsePath$hash = _parsePath.hash,\n hash = _parsePath$hash === void 0 ? '' : _parsePath$hash;\n\n var state = globalHistory.state || {};\n return [state.idx, readOnly({\n pathname: pathname,\n search: search,\n hash: hash,\n state: state.usr || null,\n key: state.key || 'default'\n })];\n }\n\n var blockedPopTx = null;\n\n function handlePop() {\n if (blockedPopTx) {\n blockers.call(blockedPopTx);\n blockedPopTx = null;\n } else {\n var nextAction = Action.Pop;\n\n var _getIndexAndLocation4 = getIndexAndLocation(),\n nextIndex = _getIndexAndLocation4[0],\n nextLocation = _getIndexAndLocation4[1];\n\n if (blockers.length) {\n if (nextIndex != null) {\n var delta = index - nextIndex;\n\n if (delta) {\n // Revert the POP\n blockedPopTx = {\n action: nextAction,\n location: nextLocation,\n retry: function retry() {\n go(delta * -1);\n }\n };\n go(delta);\n }\n } else {\n // Trying to POP to a location with no index. We did not create\n // this location, so we can't effectively block the navigation.\n process.env.NODE_ENV !== \"production\" ? warning(false, // TODO: Write up a doc that explains our blocking strategy in\n // detail and link to it here so people can understand better\n // what is going on and how to avoid it.\n \"You are trying to block a POP navigation to a location that was not \" + \"created by the history library. The block will fail silently in \" + \"production, but in general you should do all navigation with the \" + \"history library (instead of using window.history.pushState directly) \" + \"to avoid this situation.\") : void 0;\n }\n } else {\n applyTx(nextAction);\n }\n }\n }\n\n window.addEventListener(PopStateEventType, handlePop); // popstate does not fire on hashchange in IE 11 and old (trident) Edge\n // https://developer.mozilla.org/de/docs/Web/API/Window/popstate_event\n\n window.addEventListener(HashChangeEventType, function () {\n var _getIndexAndLocation5 = getIndexAndLocation(),\n nextLocation = _getIndexAndLocation5[1]; // Ignore extraneous hashchange events.\n\n\n if (createPath(nextLocation) !== createPath(location)) {\n handlePop();\n }\n });\n var action = Action.Pop;\n\n var _getIndexAndLocation6 = getIndexAndLocation(),\n index = _getIndexAndLocation6[0],\n location = _getIndexAndLocation6[1];\n\n var listeners = createEvents();\n var blockers = createEvents();\n\n if (index == null) {\n index = 0;\n globalHistory.replaceState(_extends({}, globalHistory.state, {\n idx: index\n }), '');\n }\n\n function getBaseHref() {\n var base = document.querySelector('base');\n var href = '';\n\n if (base && base.getAttribute('href')) {\n var url = window.location.href;\n var hashIndex = url.indexOf('#');\n href = hashIndex === -1 ? url : url.slice(0, hashIndex);\n }\n\n return href;\n }\n\n function createHref(to) {\n return getBaseHref() + '#' + (typeof to === 'string' ? to : createPath(to));\n }\n\n function getNextLocation(to, state) {\n if (state === void 0) {\n state = null;\n }\n\n return readOnly(_extends({\n pathname: location.pathname,\n hash: '',\n search: ''\n }, typeof to === 'string' ? parsePath(to) : to, {\n state: state,\n key: createKey()\n }));\n }\n\n function getHistoryStateAndUrl(nextLocation, index) {\n return [{\n usr: nextLocation.state,\n key: nextLocation.key,\n idx: index\n }, createHref(nextLocation)];\n }\n\n function allowTx(action, location, retry) {\n return !blockers.length || (blockers.call({\n action: action,\n location: location,\n retry: retry\n }), false);\n }\n\n function applyTx(nextAction) {\n action = nextAction;\n\n var _getIndexAndLocation7 = getIndexAndLocation();\n\n index = _getIndexAndLocation7[0];\n location = _getIndexAndLocation7[1];\n listeners.call({\n action: action,\n location: location\n });\n }\n\n function push(to, state) {\n var nextAction = Action.Push;\n var nextLocation = getNextLocation(to, state);\n\n function retry() {\n push(to, state);\n }\n\n process.env.NODE_ENV !== \"production\" ? warning(nextLocation.pathname.charAt(0) === '/', \"Relative pathnames are not supported in hash history.push(\" + JSON.stringify(to) + \")\") : void 0;\n\n if (allowTx(nextAction, nextLocation, retry)) {\n var _getHistoryStateAndUr3 = getHistoryStateAndUrl(nextLocation, index + 1),\n historyState = _getHistoryStateAndUr3[0],\n url = _getHistoryStateAndUr3[1]; // TODO: Support forced reloading\n // try...catch because iOS limits us to 100 pushState calls :/\n\n\n try {\n globalHistory.pushState(historyState, '', url);\n } catch (error) {\n // They are going to lose state here, but there is no real\n // way to warn them about it since the page will refresh...\n window.location.assign(url);\n }\n\n applyTx(nextAction);\n }\n }\n\n function replace(to, state) {\n var nextAction = Action.Replace;\n var nextLocation = getNextLocation(to, state);\n\n function retry() {\n replace(to, state);\n }\n\n process.env.NODE_ENV !== \"production\" ? warning(nextLocation.pathname.charAt(0) === '/', \"Relative pathnames are not supported in hash history.replace(\" + JSON.stringify(to) + \")\") : void 0;\n\n if (allowTx(nextAction, nextLocation, retry)) {\n var _getHistoryStateAndUr4 = getHistoryStateAndUrl(nextLocation, index),\n historyState = _getHistoryStateAndUr4[0],\n url = _getHistoryStateAndUr4[1]; // TODO: Support forced reloading\n\n\n globalHistory.replaceState(historyState, '', url);\n applyTx(nextAction);\n }\n }\n\n function go(delta) {\n globalHistory.go(delta);\n }\n\n var history = {\n get action() {\n return action;\n },\n\n get location() {\n return location;\n },\n\n createHref: createHref,\n push: push,\n replace: replace,\n go: go,\n back: function back() {\n go(-1);\n },\n forward: function forward() {\n go(1);\n },\n listen: function listen(listener) {\n return listeners.push(listener);\n },\n block: function block(blocker) {\n var unblock = blockers.push(blocker);\n\n if (blockers.length === 1) {\n window.addEventListener(BeforeUnloadEventType, promptBeforeUnload);\n }\n\n return function () {\n unblock(); // Remove the beforeunload listener so the document may\n // still be salvageable in the pagehide event.\n // See https://html.spec.whatwg.org/#unloading-documents\n\n if (!blockers.length) {\n window.removeEventListener(BeforeUnloadEventType, promptBeforeUnload);\n }\n };\n }\n };\n return history;\n}\n/**\r\n * Memory history stores the current location in memory. It is designed for use\r\n * in stateful non-browser environments like tests and React Native.\r\n *\r\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#creatememoryhistory\r\n */\n\nfunction createMemoryHistory(options) {\n if (options === void 0) {\n options = {};\n }\n\n var _options3 = options,\n _options3$initialEntr = _options3.initialEntries,\n initialEntries = _options3$initialEntr === void 0 ? ['/'] : _options3$initialEntr,\n initialIndex = _options3.initialIndex;\n var entries = initialEntries.map(function (entry) {\n var location = readOnly(_extends({\n pathname: '/',\n search: '',\n hash: '',\n state: null,\n key: createKey()\n }, typeof entry === 'string' ? parsePath(entry) : entry));\n process.env.NODE_ENV !== \"production\" ? warning(location.pathname.charAt(0) === '/', \"Relative pathnames are not supported in createMemoryHistory({ initialEntries }) (invalid entry: \" + JSON.stringify(entry) + \")\") : void 0;\n return location;\n });\n var index = clamp(initialIndex == null ? entries.length - 1 : initialIndex, 0, entries.length - 1);\n var action = Action.Pop;\n var location = entries[index];\n var listeners = createEvents();\n var blockers = createEvents();\n\n function createHref(to) {\n return typeof to === 'string' ? to : createPath(to);\n }\n\n function getNextLocation(to, state) {\n if (state === void 0) {\n state = null;\n }\n\n return readOnly(_extends({\n pathname: location.pathname,\n search: '',\n hash: ''\n }, typeof to === 'string' ? parsePath(to) : to, {\n state: state,\n key: createKey()\n }));\n }\n\n function allowTx(action, location, retry) {\n return !blockers.length || (blockers.call({\n action: action,\n location: location,\n retry: retry\n }), false);\n }\n\n function applyTx(nextAction, nextLocation) {\n action = nextAction;\n location = nextLocation;\n listeners.call({\n action: action,\n location: location\n });\n }\n\n function push(to, state) {\n var nextAction = Action.Push;\n var nextLocation = getNextLocation(to, state);\n\n function retry() {\n push(to, state);\n }\n\n process.env.NODE_ENV !== \"production\" ? warning(location.pathname.charAt(0) === '/', \"Relative pathnames are not supported in memory history.push(\" + JSON.stringify(to) + \")\") : void 0;\n\n if (allowTx(nextAction, nextLocation, retry)) {\n index += 1;\n entries.splice(index, entries.length, nextLocation);\n applyTx(nextAction, nextLocation);\n }\n }\n\n function replace(to, state) {\n var nextAction = Action.Replace;\n var nextLocation = getNextLocation(to, state);\n\n function retry() {\n replace(to, state);\n }\n\n process.env.NODE_ENV !== \"production\" ? warning(location.pathname.charAt(0) === '/', \"Relative pathnames are not supported in memory history.replace(\" + JSON.stringify(to) + \")\") : void 0;\n\n if (allowTx(nextAction, nextLocation, retry)) {\n entries[index] = nextLocation;\n applyTx(nextAction, nextLocation);\n }\n }\n\n function go(delta) {\n var nextIndex = clamp(index + delta, 0, entries.length - 1);\n var nextAction = Action.Pop;\n var nextLocation = entries[nextIndex];\n\n function retry() {\n go(delta);\n }\n\n if (allowTx(nextAction, nextLocation, retry)) {\n index = nextIndex;\n applyTx(nextAction, nextLocation);\n }\n }\n\n var history = {\n get index() {\n return index;\n },\n\n get action() {\n return action;\n },\n\n get location() {\n return location;\n },\n\n createHref: createHref,\n push: push,\n replace: replace,\n go: go,\n back: function back() {\n go(-1);\n },\n forward: function forward() {\n go(1);\n },\n listen: function listen(listener) {\n return listeners.push(listener);\n },\n block: function block(blocker) {\n return blockers.push(blocker);\n }\n };\n return history;\n} ////////////////////////////////////////////////////////////////////////////////\n// UTILS\n////////////////////////////////////////////////////////////////////////////////\n\nfunction clamp(n, lowerBound, upperBound) {\n return Math.min(Math.max(n, lowerBound), upperBound);\n}\n\nfunction promptBeforeUnload(event) {\n // Cancel the event.\n event.preventDefault(); // Chrome (and legacy IE) requires returnValue to be set.\n\n event.returnValue = '';\n}\n\nfunction createEvents() {\n var handlers = [];\n return {\n get length() {\n return handlers.length;\n },\n\n push: function push(fn) {\n handlers.push(fn);\n return function () {\n handlers = handlers.filter(function (handler) {\n return handler !== fn;\n });\n };\n },\n call: function call(arg) {\n handlers.forEach(function (fn) {\n return fn && fn(arg);\n });\n }\n };\n}\n\nfunction createKey() {\n return Math.random().toString(36).substr(2, 8);\n}\n/**\r\n * Creates a string URL path from the given pathname, search, and hash components.\r\n *\r\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createpath\r\n */\n\n\nfunction createPath(_ref) {\n var _ref$pathname = _ref.pathname,\n pathname = _ref$pathname === void 0 ? '/' : _ref$pathname,\n _ref$search = _ref.search,\n search = _ref$search === void 0 ? '' : _ref$search,\n _ref$hash = _ref.hash,\n hash = _ref$hash === void 0 ? '' : _ref$hash;\n if (search && search !== '?') pathname += search.charAt(0) === '?' ? search : '?' + search;\n if (hash && hash !== '#') pathname += hash.charAt(0) === '#' ? hash : '#' + hash;\n return pathname;\n}\n/**\r\n * Parses a string URL path into its separate pathname, search, and hash components.\r\n *\r\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#parsepath\r\n */\n\nfunction parsePath(path) {\n var parsedPath = {};\n\n if (path) {\n var hashIndex = path.indexOf('#');\n\n if (hashIndex >= 0) {\n parsedPath.hash = path.substr(hashIndex);\n path = path.substr(0, hashIndex);\n }\n\n var searchIndex = path.indexOf('?');\n\n if (searchIndex >= 0) {\n parsedPath.search = path.substr(searchIndex);\n path = path.substr(0, searchIndex);\n }\n\n if (path) {\n parsedPath.pathname = path;\n }\n }\n\n return parsedPath;\n}\n\nexport { Action, createBrowserHistory, createHashHistory, createMemoryHistory, createPath, parsePath };\n//# sourceMappingURL=index.js.map\n", "import { assertString, assertArrayOf, isFunction } from \"./typeChecking.js\";\n\nexport type RouteMatch<T = Record<string, any>> = {\n /**\n * The path string that triggered this match.\n */\n path: string;\n\n /**\n * The pattern satisfied by `path`.\n */\n pattern: string;\n\n /**\n * Named params as parsed from `path`.\n */\n params: Record<string, string | number>;\n\n /**\n * Query params as parsed from `path`.\n */\n query: Record<string, string | number | boolean>;\n\n /**\n * Metadata registered to this route.\n */\n meta: T;\n};\n\nexport enum FragTypes {\n Literal = 1,\n Param = 2,\n Wildcard = 3,\n NumericParam = 4,\n}\n\nexport type RouteFragment = {\n name: string;\n type: FragTypes;\n value: string | number | null;\n};\n\nexport type ParsedRoute<T> = {\n pattern: string;\n fragments: RouteFragment[];\n meta: T;\n};\n\nexport type RouteMatchOptions<T> = {\n willMatch?: (route: ParsedRoute<T>) => boolean;\n};\n\n/**\n * Separates a URL path into multiple fragments.\n *\n * @param path - A path string (e.g. `\"/api/users/5\"`)\n * @returns an array of fragments (e.g. `[\"api\", \"users\", \"5\"]`)\n */\nexport function splitPath(path: string): string[] {\n assertString(path, \"Expected `path` to be a string. Got type: %t, value: %v\");\n\n return path\n .split(\"/\")\n .map((f) => f.trim())\n .filter((f) => f !== \"\");\n}\n\n/**\n * Joins multiple URL path fragments into a single string.\n *\n * @param parts - One or more URL fragments (e.g. `[\"api\", \"users\", 5]`)\n * @returns a joined path (e.g. `\"api/users/5\"`)\n */\nexport function joinPath(parts: { toString(): string }[]): string {\n assertArrayOf(\n (part) => isFunction(part?.toString),\n parts,\n \"Expected `parts` to be an array of objects with a .toString() method. Got type: %t, value: %v\",\n );\n\n parts = parts.filter((x) => x).flatMap(String);\n\n let joined = parts.shift()?.toString();\n\n if (joined) {\n for (const part of parts.map((p) => p.toString())) {\n if (part.startsWith(\".\")) {\n // Resolve relative path against joined\n joined = resolvePath(joined, part);\n } else if (joined[joined.length - 1] !== \"/\") {\n if (part[0] !== \"/\") {\n joined += \"/\" + part;\n } else {\n joined += part;\n }\n } else {\n if (part[0] === \"/\") {\n joined += part.slice(1);\n } else {\n joined += part;\n }\n }\n }\n\n // Remove trailing slash (unless path is just '/')\n if (joined && joined !== \"/\" && joined.endsWith(\"/\")) {\n joined = joined.slice(0, joined.length - 1);\n }\n }\n\n return joined ?? \"\";\n}\n\nexport function resolvePath(base: string, part: string | null) {\n assertString(base, \"Expected `base` to be a string. Got type: %t, value: %v\");\n\n if (part == null) {\n part = base;\n base = \"\";\n }\n\n if (part.startsWith(\"/\")) {\n return part;\n }\n\n let resolved = base;\n\n while (true) {\n if (part.startsWith(\"..\")) {\n for (let i = resolved.length; i > 0; --i) {\n if (resolved[i] === \"/\" || i === 0) {\n resolved = resolved.slice(0, i);\n part = part.replace(/^\\.\\.\\/?/, \"\");\n break;\n }\n }\n } else if (part.startsWith(\".\")) {\n part = part.replace(/^\\.\\/?/, \"\");\n } else {\n break;\n }\n }\n\n return joinPath([resolved, part]);\n}\n\nexport function parseQueryParams(query: string): Record<string, string | number | boolean> {\n if (!query) return {};\n\n if (query.startsWith(\"?\")) {\n query = query.slice(1);\n }\n\n const entries = query\n .split(\"&\")\n .filter((x) => x.trim() !== \"\")\n .map((entry) => {\n const [key, value] = entry.split(\"=\").map((x) => x.trim());\n\n if (value.toLowerCase() === \"true\") {\n return [key, true] as const;\n }\n\n if (value.toLowerCase() === \"false\") {\n return [key, false] as const;\n }\n\n // Return value as a number if it parses as one.\n if (!isNaN(Number(value))) {\n return [key, Number(value)] as const;\n }\n\n return [key, value] as const;\n });\n\n return Object.fromEntries(entries);\n}\n\n/**\n * Returns the nearest match, or undefined if the path matches no route.\n *\n * @param url - Path to match against routes.\n * @param options - Options to customize how matching operates.\n */\nexport function matchRoutes<T>(\n routes: ParsedRoute<T>[],\n url: string,\n options: RouteMatchOptions<T> = {},\n): RouteMatch<T> | undefined {\n const [path, query] = url.split(\"?\");\n const parts = splitPath(path);\n\n routes: for (const route of routes) {\n const { fragments } = route;\n const hasWildcard = fragments[fragments.length - 1]?.type === FragTypes.Wildcard;\n\n if (!hasWildcard && fragments.length !== parts.length) {\n continue routes;\n }\n\n if (options.willMatch && !options.willMatch(route)) {\n continue routes;\n }\n\n const matched: RouteFragment[] = [];\n\n fragments: for (let i = 0; i < fragments.length; i++) {\n const part = parts[i];\n const frag = fragments[i];\n\n if (part == null && frag.type !== FragTypes.Wildcard) {\n continue routes;\n }\n\n switch (frag.type) {\n case FragTypes.Literal:\n if (frag.name.toLowerCase() === part.toLowerCase()) {\n matched.push(frag);\n break;\n } else {\n continue routes;\n }\n case FragTypes.Param:\n matched.push({ ...frag, value: part });\n break;\n case FragTypes.Wildcard:\n matched.push({ ...frag, value: parts.slice(i).join(\"/\") });\n break fragments;\n case FragTypes.NumericParam:\n if (!isNaN(Number(part))) {\n matched.push({ ...frag, value: Number(part) });\n break;\n } else {\n continue routes;\n }\n default:\n throw new Error(`Unknown fragment type: ${frag.type}`);\n }\n }\n\n const params = Object.create(null);\n\n for (const frag of matched) {\n if (frag.type === FragTypes.Param) {\n params[frag.name] = decodeURIComponent(frag.value as string);\n }\n\n if (frag.type === FragTypes.NumericParam) {\n params[frag.name] = frag.value as number;\n }\n\n if (frag.type === FragTypes.Wildcard) {\n params.wildcard = \"/\" + decodeURIComponent(frag.value as string);\n }\n }\n\n return {\n path: \"/\" + matched.map((f) => f.value).join(\"/\"),\n pattern:\n \"/\" +\n fragments\n .map((f) => {\n if (f.type === FragTypes.Param) {\n return `{${f.name}}`;\n }\n\n if (f.type === FragTypes.NumericParam) {\n return `{#${f.name}}`;\n }\n\n return f.name;\n })\n .join(\"/\"),\n params,\n query: parseQueryParams(query),\n meta: route.meta,\n };\n }\n}\n\n/**\n * Sort routes descending by specificity. Guarantees that the most specific route matches first\n * no matter the order in which they were added.\n *\n * Routes without named params and routes with more fragments are weighted more heavily.\n */\nexport function sortRoutes<T>(routes: ParsedRoute<T>[]): ParsedRoute<T>[] {\n const withoutParams = [];\n const withNumericParams = [];\n const withParams = [];\n const wildcard = [];\n\n for (const route of routes) {\n const { fragments } = route;\n\n if (fragments.some((f) => f.type === FragTypes.Wildcard)) {\n wildcard.push(route);\n } else if (fragments.some((f) => f.type === FragTypes.NumericParam)) {\n withNumericParams.push(route);\n } else if (fragments.some((f) => f.type === FragTypes.Param)) {\n withParams.push(route);\n } else {\n withoutParams.push(route);\n }\n }\n\n const bySizeDesc = (a: ParsedRoute<T>, b: ParsedRoute<T>) => {\n if (a.fragments.length > b.fragments.length) {\n return -1;\n } else {\n return 1;\n }\n };\n\n withoutParams.sort(bySizeDesc);\n withNumericParams.sort(bySizeDesc);\n withParams.sort(bySizeDesc);\n wildcard.sort(bySizeDesc);\n\n return [...withoutParams, ...withNumericParams, ...withParams, ...wildcard];\n}\n\n/**\n * Converts a route pattern into a set of matchable fragments.\n *\n * @param route - A route string (e.g. \"/api/users/{id}\")\n */\nexport function patternToFragments(pattern: string): RouteFragment[] {\n const parts = splitPath(pattern);\n const fragments = [];\n\n for (let i = 0; i < parts.length; i++) {\n const part = parts[i];\n\n if (part === \"*\") {\n if (i !== parts.length - 1) {\n throw new Error(`Wildcard must be at the end of a pattern. Received: ${pattern}`);\n }\n fragments.push({\n type: FragTypes.Wildcard,\n name: \"*\",\n value: null,\n });\n } else if (part.at(0) === \"{\" && part.at(-1) === \"}\") {\n fragments.push({\n type: part[1] === \"#\" ? FragTypes.NumericParam : FragTypes.Param,\n name: part[1] === \"#\" ? part.slice(2, -1) : part.slice(1, -1),\n value: null,\n });\n } else {\n fragments.push({\n type: FragTypes.Literal,\n name: part,\n value: part,\n });\n }\n }\n\n return fragments;\n}\n", "import { createBrowserHistory, createHashHistory, type History, type Listener } from \"history\";\nimport { getRenderHandle, m, renderMarkupToDOM, type DOMHandle, type Markup } from \"../markup.js\";\nimport {\n joinPath,\n matchRoutes,\n parseQueryParams,\n patternToFragments,\n resolvePath,\n sortRoutes,\n splitPath,\n} from \"../routing.js\";\nimport { $, $$ } from \"../state.js\";\nimport { getStoreSecrets, type Store, type StoreContext } from \"../store.js\";\nimport { isFunction, isString } from \"../typeChecking.js\";\nimport { type BuiltInStores, type Stringable } from \"../types.js\";\nimport { type View } from \"../view.js\";\nimport { DefaultView } from \"../views/default-view.js\";\nimport { ElementContext } from \"../app.js\";\n\n// ----- Types ----- //\n\nexport interface RouteMatchContext {\n /**\n * Returns the shared instance of `store`.\n */\n getStore<T extends Store<any, any>>(store: T): ReturnType<T>;\n\n /**\n * Returns the shared instance of a built-in store.\n */\n getStore<N extends keyof BuiltInStores>(name: N): BuiltInStores[N];\n\n /**\n * Redirects the user to a different route instead of matching the current one.\n */\n redirect(path: string): void;\n}\n\nexport interface Route {\n /**\n * The path or path fragment to match.\n */\n path: string;\n\n /**\n * Path to redirect to when this route is matched, or a callback function that returns such path.\n */\n redirect?: string | ((ctx: RouteRedirectContext) => string) | ((ctx: RouteRedirectContext) => Promise<string>);\n\n /**\n * View to display when this route is matched.\n */\n view?: View<any>;\n\n /**\n * Subroutes.\n */\n routes?: Route[];\n\n /**\n * Called after the match is identified but before it is acted on. Use this to set state, load data, etc.\n */\n beforeMatch?: (ctx: RouteMatchContext) => void | Promise<void>;\n}\n\nexport interface RouteConfig {\n pattern: string;\n meta: {\n redirect?: string | ((ctx: RouteRedirectContext) => string) | ((ctx: RouteRedirectContext) => Promise<string>);\n pattern?: string;\n layers?: RouteLayer[];\n beforeMatch?: (ctx: RouteMatchContext) => void | Promise<void>;\n };\n}\n\nexport interface RouteLayer {\n id: number;\n markup: Markup;\n}\n\n/**\n * Object passed to redirect callbacks. Contains information useful for determining how to redirect.\n */\nexport interface RouteRedirectContext {\n /**\n * The path as it appears in the URL bar.\n */\n path: string;\n\n /**\n * The pattern that this path was matched with.\n */\n pattern: string;\n\n /**\n * Named route params parsed from `path`.\n */\n params: Record<string, string | number | undefined>;\n\n /**\n * Query params parsed from `path`.\n */\n query: Record<string, string | number | boolean | undefined>;\n}\n\n/**\n * An active route layer whose markup has been initialized into a view.\n */\ninterface ActiveLayer {\n id: number;\n handle: DOMHandle;\n}\n\ninterface ParsedParams {\n [key: string]: string | number | boolean | (string | number | boolean | null)[] | null;\n}\n\ninterface ParsedQuery extends ParsedParams {}\n\ninterface NavigateOptions {\n /**\n * Replace the current item in the history stack instead of adding a new one.\n * The back button will send the user to the page they visited before this. Defaults to false.\n */\n replace?: boolean;\n\n /**\n * Preserve existing query params (if any) when navigating. Defaults to false.\n */\n preserveQuery?: boolean;\n}\n\ninterface RouterStoreOptions {\n routes: Route[];\n\n /**\n * Use hash-based routing if true.\n */\n hash?: boolean;\n\n /**\n * A history object from the `history` package.\n *\n * @see https://www.npmjs.com/package/history\n */\n history?: History;\n}\n\n// ----- Code ----- //\n\nexport function RouterStore(ctx: StoreContext<RouterStoreOptions>) {\n ctx.name = \"dolla/router\";\n\n const { appContext, elementContext } = getStoreSecrets(ctx);\n const render = ctx.getStore(\"render\");\n\n let history: History;\n\n if (ctx.options.history) {\n history = ctx.options.history;\n } else if (ctx.options.hash) {\n history = createHashHistory();\n } else {\n history = createBrowserHistory();\n }\n\n let layerId = 0;\n\n /**\n * Parses a route definition object into a set of matchable routes.\n *\n * @param route - Route config object.\n * @param layers - Array of parent layers. Passed when this function calls itself on nested routes.\n */\n function prepareRoute(route: Route, parents: Route[] = [], layers: RouteLayer[] = []) {\n if (!(typeof route === \"object\" && !Array.isArray(route)) || !(typeof route.path === \"string\")) {\n throw new TypeError(`Route configs must be objects with a 'path' string property. Got: ${route}`);\n }\n\n if (route.redirect && route.routes) {\n throw new Error(`Route cannot have both a 'redirect' and nested 'routes'.`);\n } else if (route.redirect && route.view) {\n throw new Error(`Route cannot have both a 'redirect' and a 'view'.`);\n } else if (!route.view && !route.routes && !route.redirect) {\n throw new Error(`Route must have a 'view', a 'redirect', or a set of nested 'routes'.`);\n }\n\n let parts: string[] = [];\n\n for (const parent of parents) {\n parts.push(...splitPath(parent.path));\n }\n\n parts.push(...splitPath(route.path));\n\n // Remove trailing wildcard for joining with nested routes.\n if (parts[parts.length - 1] === \"*\") {\n parts.pop();\n }\n\n const routes: RouteConfig[] = [];\n\n if (route.redirect) {\n let redirect = route.redirect;\n\n if (isString(redirect)) {\n redirect = resolvePath(joinPath(parts), redirect);\n\n if (!redirect.startsWith(\"/\")) {\n redirect = \"/\" + redirect;\n }\n }\n\n routes.push({\n pattern: \"/\" + joinPath([...parts, ...splitPath(route.path)]),\n meta: {\n redirect,\n },\n });\n\n return routes;\n }\n\n let view: View<any> = DefaultView;\n\n if (typeof route.view === \"function\") {\n view = route.view;\n } else if (route.view) {\n throw new TypeError(`Route '${route.path}' expected a view function or undefined. Got: ${route.view}`);\n }\n\n const markup = m(view);\n const layer: RouteLayer = { id: layerId++, markup };\n\n // Parse nested routes if they exist.\n if (route.routes) {\n for (const subroute of route.routes) {\n routes.push(...prepareRoute(subroute, [...parents, route], [...layers, layer]));\n }\n } else {\n routes.push({\n pattern: parent ? joinPath([...parents.map((p) => p.path), route.path]) : route.path,\n meta: {\n pattern: route.path,\n layers: [...layers, layer],\n beforeMatch: route.beforeMatch,\n },\n });\n }\n\n return routes;\n }\n\n const routes = sortRoutes(\n ctx.options.routes\n .flatMap((route) => prepareRoute(route))\n .map((route) => ({\n pattern: route.pattern,\n meta: route.meta,\n fragments: patternToFragments(route.pattern),\n })),\n );\n\n // Test redirects to make sure all possible redirect targets actually exist.\n for (const route of routes) {\n if (route.meta.redirect) {\n let redirectPath: string;\n\n if (isFunction(route.meta.redirect)) {\n // throw new Error(`Redirect functions are not yet supported.`);\n // Just allow, though it could fail later. Best not to call the function and cause potential side effects.\n } else if (isString(route.meta.redirect)) {\n redirectPath = route.meta.redirect;\n\n const match = matchRoutes(routes, redirectPath, {\n willMatch(r) {\n return r !== route;\n },\n });\n\n if (!match) {\n throw new Error(`Found a redirect to an undefined URL. From '${route.pattern}' to '${route.meta.redirect}'`);\n }\n } else {\n throw new TypeError(`Expected a string or redirect function. Got: ${route.meta.redirect}`);\n }\n }\n }\n\n ctx.onConnected(() => {\n ctx.info(\"Routes registered:\", routes);\n });\n\n const $$pattern = $$<string | null>(null);\n const $$path = $$(\"\");\n const $$params = $$<ParsedParams>({});\n const $$query = $$<ParsedQuery>(parseQueryParams(window.location.search));\n\n // Update URL when query changes\n ctx.observe($$query, (current) => {\n const params = new URLSearchParams();\n\n for (const key in current) {\n params.set(key, String(current[key]));\n }\n\n const search = \"?\" + params.toString();\n\n if (search != history.location.search) {\n history.replace({\n pathname: history.location.pathname,\n search,\n });\n }\n });\n\n ctx.onConnected(() => {\n history.listen(onRouteChange);\n onRouteChange(history);\n\n ctx.info(\"Intercepting <a> clicks within root element:\", appContext.rootElement);\n catchLinks(appContext.rootElement!, (anchor) => {\n let href = anchor.getAttribute(\"href\")!;\n\n ctx.info(\"Intercepted link click\", anchor, href);\n\n if (!/^https?:\\/\\/|^\\//.test(href)) {\n href = joinPath([history.location.pathname, href]);\n }\n\n history.push(href);\n });\n });\n\n let activeLayers: ActiveLayer[] = [];\n let lastQuery: string;\n\n /**\n * Run when the location changes. Diffs and mounts new routes and updates\n * the $path, $route, $params and $query states accordingly.\n */\n const onRouteChange: Listener = async ({ location }) => {\n // Update query params if they've changed.\n if (location.search !== lastQuery) {\n lastQuery = location.search;\n\n $$query.set(parseQueryParams(location.search));\n }\n\n const matched = matchRoutes(routes, location.pathname);\n\n if (!matched) {\n $$pattern.set(null);\n $$path.set(location.pathname);\n $$params.set({\n wildcard: location.pathname,\n });\n return;\n }\n\n if (matched.meta.beforeMatch) {\n await matched.meta.beforeMatch({\n getStore(store: keyof BuiltInStores | Store<any, any>) {\n let name: string;\n\n if (typeof store === \"string\") {\n name = store as keyof BuiltInStores;\n } else {\n name = store.name;\n }\n\n if (typeof store !== \"string\") {\n let ec: ElementContext | undefined = elementContext;\n while (ec) {\n if (ec.stores.has(store)) {\n return ec.stores.get(store)?.instance!.exports;\n }\n ec = ec.parent;\n }\n }\n\n if (appContext.stores.has(store)) {\n const _store = appContext.stores.get(store)!;\n\n if (!_store.instance) {\n appContext.crashCollector.crash({\n componentName: ctx.name,\n error: new Error(`Store '${name}' is not registered on this app.`),\n });\n }\n\n return _store.instance!.exports;\n }\n\n appContext.crashCollector.crash({\n componentName: ctx.name,\n error: new Error(`Store '${name}' is not registered on this app.`),\n });\n },\n redirect: (path) => {\n // TODO: Implement\n throw new Error(`Redirect not yet implemented.`);\n },\n });\n }\n\n ctx.info(`Matched route: '${matched.pattern}' ('${matched.path}')`);\n\n if (matched.meta.redirect != null) {\n if (typeof matched.meta.redirect === \"string\") {\n const path = replaceParams(matched.meta.redirect, matched.params);\n ctx.info(`Redirecting to: '${path}'`);\n history.replace(path);\n } else if (typeof matched.meta.redirect === \"function\") {\n const redirectContext: RouteRedirectContext = {\n path: matched.path,\n pattern: matched.pattern,\n params: matched.params,\n query: matched.query,\n };\n let path = await matched.meta.redirect(redirectContext);\n if (typeof path !== \"string\") {\n throw new Error(`Redirect function must return a path to redirect to.`);\n }\n if (!path.startsWith(\"/\")) {\n // Not absolute. Resolve against matched path.\n path = resolvePath(matched.path, path);\n }\n ctx.info(`Redirecting to: '${path}'`);\n history.replace(path);\n } else {\n throw new TypeError(`Redirect must either be a path string or a function.`);\n }\n } else {\n $$path.set(matched.path);\n $$params.set(matched.params);\n\n if (matched.pattern !== $$pattern.get()) {\n $$pattern.set(matched.pattern);\n\n const layers = matched.meta.layers!;\n\n // Diff and update route layers.\n for (let i = 0; i < layers.length; i++) {\n const matchedLayer = layers[i];\n const activeLayer = activeLayers[i];\n\n if (activeLayer?.id !== matchedLayer.id) {\n ctx.info(`Replacing layer @${i} (active ID: ${activeLayer?.id}, matched ID: ${matchedLayer.id})`);\n\n activeLayers = activeLayers.slice(0, i);\n\n const parentLayer = activeLayers[activeLayers.length - 1];\n const renderContext = { appContext, elementContext };\n\n const rendered = renderMarkupToDOM(matchedLayer.markup, renderContext);\n const handle = getRenderHandle(rendered);\n\n if (activeLayer && activeLayer.handle.connected) {\n // Disconnect first mismatched active layer.\n activeLayer.handle.disconnect();\n }\n\n if (parentLayer) {\n parentLayer.handle.setChildren(rendered);\n } else {\n appContext.rootView!.setChildren(rendered);\n }\n\n // Push and connect new active layer.\n activeLayers.push({ id: matchedLayer.id, handle });\n }\n }\n }\n }\n };\n\n function navigate(path: Stringable, options?: NavigateOptions): void;\n function navigate(fragments: Stringable[], options?: NavigateOptions): void;\n\n function navigate(path: Stringable | Stringable[], options: NavigateOptions = {}) {\n let joined: string;\n\n if (Array.isArray(path)) {\n joined = joinPath(path);\n } else {\n joined = path.toString();\n }\n\n joined = resolvePath(history.location.pathname, joined);\n\n if (options.preserveQuery) {\n joined += history.location.search;\n }\n\n if (options.replace) {\n history.replace(joined);\n } else {\n history.push(joined);\n }\n }\n\n return {\n /**\n * The currently matched route pattern, if any.\n */\n $pattern: $($$pattern),\n\n /**\n * The current URL path.\n */\n $path: $($$path),\n\n /**\n * The current named path params.\n */\n $params: $($$params),\n\n /**\n * The current query params. Changes to this object will be reflected in the URL.\n */\n $$query,\n\n /**\n * Navigate backward. Pass a number of steps to hit the back button that many times.\n */\n back(steps = 1) {\n history.go(-steps);\n },\n\n /**\n * Navigate forward. Pass a number of steps to hit the forward button that many times.\n */\n forward(steps = 1) {\n history.go(steps);\n },\n\n /**\n * Navigates to another route.\n *\n * @example\n * navigate(\"/login\"); // navigate to `/login`\n * navigate([\"/users\", 215], { replace: true }); // replace current history entry with `/users/215`\n *\n * @param args - One or more path segments optionally followed by an options object.\n */\n navigate,\n\n /**\n * Updates a query param in place.\n */\n // updateQuery(key: string, value: string) {},\n\n /**\n * Updates a route param in place.\n */\n // updateParam(key: string, value: string) {},\n };\n}\n\nconst safeExternalLink = /(noopener|noreferrer) (noopener|noreferrer)/;\nconst protocolLink = /^[\\w-_]+:/;\n\n/**\n * Intercepts links within the root node.\n *\n * This is adapted from https://github.com/choojs/nanohref/blob/master/index.js\n *\n * @param root - Element under which to intercept link clicks\n * @param callback - Function to call when a click event is intercepted\n * @param _window - (optional) Override for global window object\n */\nexport function catchLinks(root: HTMLElement, callback: (anchor: HTMLAnchorElement) => void, _window = window) {\n function traverse(node: HTMLElement | null): HTMLAnchorElement | null {\n if (!node || node === root) {\n return null;\n }\n\n if (node.localName !== \"a\" || (node as any).href === undefined) {\n return traverse(node.parentNode as HTMLElement | null);\n }\n\n return node as HTMLAnchorElement;\n }\n\n function handler(e: MouseEvent) {\n if ((e.button && e.button !== 0) || e.ctrlKey || e.metaKey || e.altKey || e.shiftKey || e.defaultPrevented) {\n return;\n }\n\n const anchor = traverse(e.target as HTMLElement);\n\n if (!anchor) {\n return;\n }\n\n if (\n _window.location.protocol !== anchor.protocol ||\n _window.location.hostname !== anchor.hostname ||\n _window.location.port !== anchor.port ||\n anchor.hasAttribute(\"data-router-ignore\") ||\n anchor.hasAttribute(\"download\") ||\n (anchor.getAttribute(\"target\") === \"_blank\" && safeExternalLink.test(anchor.getAttribute(\"rel\")!)) ||\n protocolLink.test(anchor.getAttribute(\"href\")!)\n ) {\n return;\n }\n\n e.preventDefault();\n callback(anchor);\n }\n\n root.addEventListener(\"click\", handler);\n\n return function cancel() {\n root.removeEventListener(\"click\", handler);\n };\n}\n\n/**\n * Replace route pattern param placeholders with real matched values.\n */\nfunction replaceParams(path: string, params: Record<string, string | number>) {\n for (const key in params) {\n const value = params[key].toString();\n path = path.replace(`{${key}}`, value).replace(`{#${key}}`, value);\n }\n\n return path;\n}\n", "import { $, $$, isReadable, observe, type Readable } from \"../state.js\";\nimport { type StoreContext } from \"../store.js\";\nimport { assertObject, isFunction, isObject, isString, typeOf } from \"../typeChecking.js\";\nimport { type Stringable } from \"../types.js\";\nimport { deepEqual } from \"../utils.js\";\n\n// ----- Types ----- //\n\n// TODO: Is there a good way to represent infinitely nested recursive types?\n/**\n * An object where values are either a translated string or another nested Translation object.\n */\ntype Translation = Record<string, string | Record<string, string | Record<string, string | Record<string, string>>>>;\n\nexport interface LanguageConfig {\n name: string;\n\n /**\n * Path to a JSON file with translated strings for this language, a plain object containing said translations, or a callback function that returns them.\n */\n translations: string | Translation | (() => Translation) | (() => Promise<Translation>);\n}\n\ntype LanguageOptions = {\n languages: LanguageConfig[];\n\n /**\n * Default language to load on startup\n */\n defaultLanguage?: string;\n};\n\n// ----- Code ----- //\n\nexport function LanguageStore(ctx: StoreContext<LanguageOptions>) {\n ctx.name = \"dolla/language\";\n\n const languages = new Map<string, LanguageConfig>();\n const cache = new Map<string, Translation>();\n\n // Convert languages into Language instances.\n ctx.options.languages.forEach((entry) => {\n languages.set(entry.name, entry);\n });\n\n ctx.info(\n `App supports ${languages.size} language${languages.size === 1 ? \"\" : \"s\"}: '${[...languages.keys()].join(\"', '\")}'`,\n );\n\n async function getTranslation(config: LanguageConfig) {\n if (!cache.has(config.name)) {\n let fn: () => Promise<Translation>;\n\n if (isString(config.translations)) {\n fn = async () => {\n return fetch(config.translations as string).then((res) => res.json());\n };\n } else if (isFunction(config.translations)) {\n fn = async () => (config.translations as () => Translation)();\n } else if (isObject(config.translations)) {\n fn = async () => config.translations as Translation;\n } else {\n throw new TypeError(\n `Translation of '${\n config.name\n }' must be an object of translated strings, a path to an object of translated strings, a function that returns one, or an async function that resolves to one. Got type: ${typeOf(\n config.translations,\n )}, value: ${config.translations}`,\n );\n }\n\n try {\n const translation = await fn();\n assertObject(\n translation,\n `Expected '${config.name}' translations to resolve to an object. Got type: %t, value: %v`,\n );\n cache.set(config.name, translation);\n } catch (err) {\n throw err;\n }\n }\n\n return cache.get(config.name);\n }\n\n const $$isLoaded = $$(false);\n const $$language = $$<string>();\n const $$translation = $$<Translation>();\n\n // Fallback labels for missing state and data.\n const $noLanguageValue = $(\"[NO LANGUAGE SET]\");\n\n // TODO: Keep an eye on this for memory leaks. Keeping a bunch of unused alternates with varied values might be an issue.\n const translationCache: [\n key: string,\n values: Record<string, Stringable | Readable<Stringable>> | undefined,\n readable: Readable<string>,\n ][] = [];\n\n function getCached(\n key: string,\n values?: Record<string, Stringable | Readable<Stringable>>,\n ): Readable<string> | undefined {\n for (const entry of translationCache) {\n if (entry[0] === key && deepEqual(entry[1], values)) {\n return entry[2];\n }\n }\n }\n\n /**\n * Replaces {{placeholders}} with values in translated strings.\n */\n function replaceMustaches(template: string, values: Record<string, Stringable>) {\n for (const name in values) {\n template = template.replace(`{{${name}}}`, String(values[name]));\n }\n return template;\n }\n\n async function setLanguage(tag: string) {\n let realTag!: string;\n\n if (tag === \"auto\") {\n let tags = [];\n\n if (typeof navigator === \"object\") {\n const nav = navigator as any;\n\n if (nav.languages?.length > 0) {\n tags.push(...nav.languages);\n } else if (nav.language) {\n tags.push(nav.language);\n } else if (nav.browserLanguage) {\n tags.push(nav.browserLanguage);\n } else if (nav.userLanguage) {\n tags.push(nav.userLanguage);\n }\n }\n\n for (const tag of tags) {\n if (languages.has(tag)) {\n // Found a matching language.\n realTag = tag;\n }\n }\n } else {\n // Tag is the actual tag to set.\n if (languages.has(tag)) {\n realTag = tag;\n }\n }\n\n if (realTag == null) {\n const firstLanguage = ctx.options.languages[0];\n if (firstLanguage) {\n realTag = firstLanguage.name;\n }\n }\n\n if (!realTag || !languages.has(realTag)) {\n throw new Error(`Language '${tag}' is not configured for this app.`);\n }\n\n const lang = languages.get(realTag)!;\n\n try {\n const translation = await getTranslation(lang);\n\n $$translation.set(translation);\n $$language.set(realTag);\n\n ctx.info(\"set language to \" + realTag);\n } catch (error) {\n if (error instanceof Error) {\n ctx.crash(error);\n }\n }\n }\n\n // TODO: Determine and load default language.\n setLanguage(ctx.options.defaultLanguage ?? \"auto\").then(() => {\n $$isLoaded.set(true);\n });\n\n return {\n loaded: new Promise<void>((resolve, reject) => {\n const stop = observe($$isLoaded, (isLoaded) => {\n if (isLoaded) {\n setTimeout(() => {\n stop();\n resolve();\n }, 0);\n }\n });\n }),\n\n $isLoaded: $($$isLoaded),\n $currentLanguage: $($$language),\n supportedLanguages: [...languages.keys()],\n\n setLanguage,\n\n /**\n * Returns a Readable of the translated value.\n\n * @param key - Key to the translated value.\n * @param values - A map of {{placeholder}} names and the values to replace them with.\n */\n translate(key: string, values?: Record<string, Stringable | Readable<Stringable>>): Readable<string> {\n if (!$$language.get()) {\n return $noLanguageValue;\n }\n\n const cached = getCached(key, values);\n if (cached) {\n return cached;\n }\n\n if (values) {\n const readableValues: Record<string, Readable<any>> = {};\n\n for (const [key, value] of Object.entries<any>(values)) {\n if (isReadable(value)) {\n readableValues[key] = value;\n }\n }\n\n // This looks extremely weird, but it creates a joined state\n // that contains the translation with interpolated observable values.\n const readableEntries = Object.entries(readableValues);\n if (readableEntries.length > 0) {\n const readables = readableEntries.map((x) => x[1]);\n const $merged = $([$$translation, ...readables], (t, ...entryValues) => {\n const entries = entryValues.map((_, i) => readableEntries[i]);\n const mergedValues = {\n ...values,\n };\n\n for (let i = 0; i < entries.length; i++) {\n const key = entries[i][0];\n mergedValues[key] = entryValues[i];\n }\n\n const result = resolve(t, key) || `[NO TRANSLATION: ${key}]`;\n return replaceMustaches(result, mergedValues);\n });\n\n translationCache.push([key, values, $merged]);\n\n return $merged;\n }\n }\n\n const $replaced = $($$translation, (t) => {\n let result = resolve(t, key) || `[NO TRANSLATION: ${key}]`;\n\n if (values) {\n result = replaceMustaches(result, values);\n }\n\n return result;\n });\n\n translationCache.push([key, values, $replaced]);\n\n return $replaced;\n },\n };\n}\n\nfunction resolve(object: any, key: string) {\n const parsed = String(key)\n .split(/[\\.\\[\\]]/)\n .filter((part) => part.trim() !== \"\");\n let value = object;\n\n while (parsed.length > 0) {\n const part = parsed.shift()!;\n\n if (value != null) {\n value = value[part];\n } else {\n value = undefined;\n }\n }\n\n return value;\n}\n", "import { isObject } from \"../typeChecking.js\";\nimport { type StoreContext } from \"../store.js\";\n\ninterface HTTPStoreOptions {\n /**\n * The fetch function to use for requests. Pass this to mock for testing.\n */\n fetch?: typeof window.fetch;\n}\n\n/**\n * A simple HTTP client with middleware support. Middleware applies to all requests made through this store,\n * so it's the perfect way to handle things like auth headers and permission checks for API calls.\n */\nexport function HTTPStore(ctx: StoreContext<HTTPStoreOptions>) {\n ctx.name = \"dolla/http\";\n\n const fetch = ctx.options.fetch ?? getDefaultFetch();\n\n const middleware: HTTPMiddleware[] = [];\n\n async function request<ResBody, ReqBody>(method: string, uri: string, options?: RequestOptions<any>) {\n return makeRequest<ResBody, ReqBody>({ ...options, method, uri, middleware, fetch });\n }\n\n return {\n /**\n * Adds a new middleware that will apply to subsequent requests.\n * Returns a function to remove this middleware.\n *\n * @param middleware - A middleware function that will intercept requests.\n */\n middleware(fn: HTTPMiddleware) {\n middleware.push(fn);\n\n // Call returned function to remove this middleware for subsequent requests.\n return function remove() {\n middleware.splice(middleware.indexOf(fn), 1);\n };\n },\n\n async get<ResBody = unknown>(uri: string, options?: RequestOptions<never>) {\n return request<ResBody, never>(\"get\", uri, options);\n },\n\n async put<ResBody = unknown, ReqBody = unknown>(uri: string, options?: RequestOptions<ReqBody>) {\n return request<ResBody, ReqBody>(\"put\", uri, options);\n },\n\n async patch<ResBody = unknown, ReqBody = unknown>(uri: string, options?: RequestOptions<ReqBody>) {\n return request<ResBody, ReqBody>(\"patch\", uri, options);\n },\n\n async post<ResBody = unknown, ReqBody = unknown>(uri: string, options?: RequestOptions<ReqBody>) {\n return request<ResBody, ReqBody>(\"post\", uri, options);\n },\n\n async delete<ResBody = unknown>(uri: string, options?: RequestOptions<never>) {\n return request<ResBody, never>(\"delete\", uri, options);\n },\n\n async head<ResBody = unknown, ReqBody = unknown>(uri: string, options?: RequestOptions<ReqBody>) {\n return request<ResBody, ReqBody>(\"head\", uri, options);\n },\n\n async options<ResBody = unknown, ReqBody = unknown>(uri: string, options?: RequestOptions<ReqBody>) {\n return request<ResBody, ReqBody>(\"options\", uri, options);\n },\n\n async trace<ResBody = unknown, ReqBody = unknown>(uri: string, options?: RequestOptions<ReqBody>) {\n return request<ResBody, ReqBody>(\"trace\", uri, options);\n },\n };\n}\n\nfunction getDefaultFetch(): typeof window.fetch {\n if (typeof window !== \"undefined\" && window.fetch) {\n return window.fetch.bind(window);\n }\n\n if (typeof global !== \"undefined\" && global.fetch) {\n return global.fetch.bind(global);\n }\n\n throw new Error(\"Running in neither browser nor node. Please run this app in one of the supported environments.\");\n}\n\n/*====================*\\\n|| Request ||\n\\*====================*/\n\nexport type HTTPMiddleware = (\n request: HTTPRequest<unknown>,\n next: () => Promise<HTTPResponse<unknown>>,\n) => void | Promise<void>;\n\ninterface RequestOptions<ReqBody> {\n /**\n * Body to send with the request.\n */\n body?: ReqBody;\n\n /**\n * Headers to send with the request.\n */\n headers?: Record<string, any> | Headers;\n\n /**\n * Query params to interpolate into the URL.\n */\n query?: Record<string, any> | URLSearchParams;\n}\n\ninterface HTTPRequest<Body> {\n method: string;\n uri: string;\n readonly sameOrigin: boolean;\n headers: Headers;\n query: URLSearchParams;\n body: Body;\n}\n\ninterface HTTPResponse<Body> {\n method: string;\n uri: string;\n status: number;\n statusText: string;\n headers: Record<string, string>;\n body: Body;\n}\n\nclass HTTPResponseError extends Error {\n response;\n\n constructor(response: HTTPResponse<any>) {\n const { status, statusText, method, uri } = response;\n const message = `${status} ${statusText}: Request failed (${method.toUpperCase()} ${uri})`;\n\n super(message);\n\n this.response = response;\n }\n}\n\ninterface MakeRequestConfig<ReqBody> extends RequestOptions<ReqBody> {\n method: string;\n uri: string;\n middleware: HTTPMiddleware[];\n fetch: typeof window.fetch;\n}\n\nasync function makeRequest<ResBody, ReqBody>(config: MakeRequestConfig<ReqBody>) {\n const { headers, query, fetch, middleware } = config;\n\n const request: HTTPRequest<ReqBody> = {\n method: config.method,\n uri: config.uri,\n get sameOrigin() {\n return !request.uri.startsWith(\"http\");\n },\n query: new URLSearchParams(),\n headers: new Headers(),\n body: config.body!,\n };\n\n // Read headers into request\n if (headers) {\n if (headers instanceof Map || headers instanceof Headers) {\n headers.forEach((value, key) => {\n request.headers.set(key, value);\n });\n } else if (headers != null && typeof headers === \"object\" && !Array.isArray(headers)) {\n for (const name in headers) {\n const value = headers[name];\n if (value instanceof Date) {\n request.headers.set(name, value.toISOString());\n } else if (value != null) {\n request.headers.set(name, String(value));\n }\n }\n } else {\n throw new TypeError(`Unknown headers type. Got: ${headers}`);\n }\n }\n\n // Read query params into request\n if (query) {\n if (query instanceof Map || query instanceof URLSearchParams) {\n query.forEach((value, key) => {\n request.query.set(key, value);\n });\n } else if (query != null && typeof query === \"object\" && !Array.isArray(query)) {\n for (const name in query) {\n const value = query[name];\n if (value instanceof Date) {\n request.query.set(name, value.toISOString());\n } else if (value != null) {\n request.query.set(name, String(value));\n }\n }\n } else {\n throw new TypeError(`Unknown query params type. Got: ${query}`);\n }\n }\n\n let response: HTTPResponse<ResBody>;\n\n // This is the function that performs the actual request after the final middleware.\n const handler = async () => {\n const query = request.query.toString();\n const fullURL = query.length > 0 ? request.uri + \"?\" + query : request.uri;\n\n let reqBody: BodyInit;\n\n if (!request.headers.has(\"content-type\") && isObject(request.body)) {\n // Auto-detect JSON bodies and encode as a string with correct headers.\n request.headers.set(\"content-type\", \"application/json\");\n reqBody = JSON.stringify(request.body);\n } else {\n reqBody = request.body as BodyInit;\n }\n\n const fetched = await fetch(fullURL, {\n method: request.method,\n headers: request.headers,\n body: reqBody,\n });\n\n // Auto-parse response body based on content-type header\n const headers = Object.fromEntries<string>(fetched.headers.entries());\n const contentType = headers[\"content-type\"];\n\n let body: ResBody;\n\n if (contentType?.includes(\"application/json\")) {\n body = await fetched.json();\n } else if (contentType?.includes(\"application/x-www-form-urlencoded\")) {\n body = (await fetched.formData()) as ResBody;\n } else {\n body = (await fetched.text()) as ResBody;\n }\n\n response = {\n method: request.method,\n uri: request.uri,\n status: fetched.status,\n statusText: fetched.statusText,\n headers: headers,\n body,\n };\n };\n\n if (middleware.length > 0) {\n const mount = (index = 0) => {\n const current = middleware[index];\n const next = middleware[index + 1] ? mount(index + 1) : handler;\n\n return async () =>\n current(request, async () => {\n await next();\n return response;\n });\n };\n\n await mount()();\n } else {\n await handler();\n }\n\n if (response!.status < 200 || response!.status >= 400) {\n throw new HTTPResponseError(response!);\n }\n\n return response!;\n}\n", "import { type DOMHandle } from \"../markup.js\";\nimport { $$, observe, type Writable } from \"../state.js\";\nimport { getStoreSecrets, type StoreContext } from \"../store.js\";\nimport { initView, type View } from \"../view.js\";\n\nexport interface DialogProps {\n /**\n * Whether the dialog is currently open.\n */\n $$open: Writable<boolean>;\n\n /**\n * Calls `callback` immediately after dialog has been connected.\n */\n transitionIn: (callback: () => Promise<void>) => void;\n\n /**\n * Calls `callback` and awaits its Promise before disconnecting the dialog.\n */\n transitionOut: (callback: () => Promise<void>) => void;\n}\n\nexport interface OpenDialog {\n instance: DOMHandle;\n transitionInCallback?: () => Promise<void>;\n transitionOutCallback?: () => Promise<void>;\n}\n\n/**\n * Manages dialogs. Also known as modals.\n * TODO: Describe this better.\n */\nexport function DialogStore(ctx: StoreContext) {\n ctx.name = \"dolla/dialog\";\n\n const { appContext, elementContext } = getStoreSecrets(ctx);\n\n const render = ctx.getStore(\"render\");\n\n const container = document.createElement(\"div\");\n container.style.position = \"fixed\";\n container.style.top = \"0\";\n container.style.right = \"0\";\n container.style.bottom = \"0\";\n container.style.left = \"0\";\n container.style.zIndex = \"99999\";\n\n /**\n * A first-in-last-out queue of dialogs. The last one appears on top.\n * This way if a dialog opens another dialog the new dialog stacks.\n */\n const $$dialogs = $$<OpenDialog[]>([]);\n\n let activeDialogs: OpenDialog[] = [];\n\n function dialogChangedCallback() {\n // Container is only connected to the DOM when there is at least one dialog to display.\n if (activeDialogs.length > 0) {\n if (!container.parentNode) {\n document.body.appendChild(container);\n }\n } else {\n if (container.parentNode) {\n document.body.removeChild(container);\n }\n }\n }\n\n // Diff dialogs when value is updated, adding and removing dialogs as necessary.\n ctx.observe($$dialogs, (dialogs) => {\n render.update(() => {\n let removed: OpenDialog[] = [];\n let added: OpenDialog[] = [];\n\n for (const dialog of activeDialogs) {\n if (!dialogs.includes(dialog)) {\n removed.push(dialog);\n }\n }\n\n for (const dialog of dialogs) {\n if (!activeDialogs.includes(dialog)) {\n added.push(dialog);\n }\n }\n\n for (const dialog of removed) {\n if (dialog.transitionOutCallback) {\n dialog.transitionOutCallback().then(() => {\n dialog.instance.disconnect();\n activeDialogs.splice(activeDialogs.indexOf(dialog), 1);\n dialogChangedCallback();\n });\n } else {\n dialog.instance.disconnect();\n activeDialogs.splice(activeDialogs.indexOf(dialog), 1);\n }\n }\n\n for (const dialog of added) {\n dialog.instance.connect(container);\n\n if (dialog.transitionInCallback) {\n dialog.transitionInCallback();\n }\n\n activeDialogs.push(dialog);\n }\n\n dialogChangedCallback();\n });\n });\n\n ctx.onDisconnected(() => {\n if (container.parentNode) {\n document.body.removeChild(container);\n }\n });\n\n function open<P extends DialogProps>(view: View<P>, props?: Omit<P, keyof DialogProps>) {\n const $$open = $$(true);\n\n let dialog: OpenDialog | undefined;\n\n let transitionInCallback: (() => Promise<void>) | undefined;\n let transitionOutCallback: (() => Promise<void>) | undefined;\n\n let instance = initView({\n view: view as View<unknown>,\n appContext,\n elementContext,\n props: {\n ...props,\n $$open,\n transitionIn: (callback) => {\n transitionInCallback = callback;\n },\n transitionOut: (callback) => {\n transitionOutCallback = callback;\n },\n } as P,\n });\n\n dialog = {\n instance,\n\n // These must be getters because the fns passed to props aren't called until before connect.\n get transitionInCallback() {\n return transitionInCallback;\n },\n get transitionOutCallback() {\n return transitionOutCallback;\n },\n };\n\n $$dialogs.update((current) => {\n return [...current, dialog!];\n });\n\n const stopObserver = observe($$open, (value) => {\n if (!value) {\n closeDialog();\n }\n });\n\n function closeDialog() {\n $$dialogs.update((current) => {\n return current.filter((x) => x !== dialog);\n });\n dialog = undefined;\n\n stopObserver();\n }\n\n return closeDialog;\n }\n\n return {\n open,\n };\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAa,WAAO,eAAe,SAAQ,cAAa,EAAC,OAAM,KAAE,CAAC;AAAE,QAAI,iBAAe,2BAA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"b", "c", "d", "e", "m", "colorHash", "process", "object", "readable", "computed", "callback", "parent", "parent", "value", "key", "parent", "parent", "parent", "parent", "parent", "parent", "x", "parent", "SECRETS", "SECRETS", "resolve", "resolve", "options", "Action", "cond", "window", "hash", "index", "action", "location", "hash", "parent", "routes", "tag", "resolve", "key", "fetch", "query", "headers"]
7
7
  }