beads-ui 0.11.2 → 0.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGES.md +24 -0
- package/app/main.bundle.js +4 -0
- package/app/main.bundle.js.map +2 -2
- package/package.json +1 -1
- package/server/app.js +10 -1
- package/server/cli/commands.js +92 -10
- package/server/cli/daemon.js +70 -1
- package/server/cli/open.js +39 -0
package/app/main.bundle.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../node_modules/ms/index.js", "../node_modules/debug/src/common.js", "../node_modules/debug/src/browser.js", "../node_modules/lit-html/src/lit-html.ts", "data/sort.js", "data/list-selectors.js", "utils/logging.js", "data/providers.js", "data/subscription-issue-store.js", "data/subscriptions-store.js", "data/subscription-issue-stores.js", "utils/issue-url.js", "router.js", "state.js", "utils/activity-indicator.js", "utils/toast.js", "utils/issue-id-renderer.js", "utils/priority.js", "utils/priority-badge.js", "utils/type-badge.js", "views/board.js", "../node_modules/dompurify/src/utils.ts", "../node_modules/dompurify/src/tags.ts", "../node_modules/dompurify/src/attrs.ts", "../node_modules/dompurify/src/regexp.ts", "../node_modules/dompurify/src/purify.ts", "../node_modules/lit-html/src/directive.ts", "../node_modules/lit-html/src/directives/unsafe-html.ts", "../node_modules/marked/src/defaults.ts", "../node_modules/marked/src/rules.ts", "../node_modules/marked/src/helpers.ts", "../node_modules/marked/src/Tokenizer.ts", "../node_modules/marked/src/Lexer.ts", "../node_modules/marked/src/Renderer.ts", "../node_modules/marked/src/TextRenderer.ts", "../node_modules/marked/src/Parser.ts", "../node_modules/marked/src/Hooks.ts", "../node_modules/marked/src/Instance.ts", "../node_modules/marked/src/marked.ts", "utils/markdown.js", "utils/status.js", "views/detail.js", "views/issue-row.js", "views/epics.js", "views/fatal-error-dialog.js", "views/issue-dialog.js", "utils/issue-type.js", "views/list.js", "views/nav.js", "views/new-issue-dialog.js", "views/workspace-picker.js", "protocol.js", "ws.js", "main.js"],
|
|
4
|
-
"sourcesContent": ["/**\n * Helpers.\n */\n\nvar s = 1000;\nvar m = s * 60;\nvar h = m * 60;\nvar d = h * 24;\nvar w = d * 7;\nvar y = d * 365.25;\n\n/**\n * Parse or format the given `val`.\n *\n * Options:\n *\n * - `long` verbose formatting [false]\n *\n * @param {String|Number} val\n * @param {Object} [options]\n * @throws {Error} throw an error if val is not a non-empty string or a number\n * @return {String|Number}\n * @api public\n */\n\nmodule.exports = function (val, options) {\n options = options || {};\n var type = typeof val;\n if (type === 'string' && val.length > 0) {\n return parse(val);\n } else if (type === 'number' && isFinite(val)) {\n return options.long ? fmtLong(val) : fmtShort(val);\n }\n throw new Error(\n 'val is not a non-empty string or a valid number. val=' +\n JSON.stringify(val)\n );\n};\n\n/**\n * Parse the given `str` and return milliseconds.\n *\n * @param {String} str\n * @return {Number}\n * @api private\n */\n\nfunction parse(str) {\n str = String(str);\n if (str.length > 100) {\n return;\n }\n var match = /^(-?(?:\\d+)?\\.?\\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(\n str\n );\n if (!match) {\n return;\n }\n var n = parseFloat(match[1]);\n var type = (match[2] || 'ms').toLowerCase();\n switch (type) {\n case 'years':\n case 'year':\n case 'yrs':\n case 'yr':\n case 'y':\n return n * y;\n case 'weeks':\n case 'week':\n case 'w':\n return n * w;\n case 'days':\n case 'day':\n case 'd':\n return n * d;\n case 'hours':\n case 'hour':\n case 'hrs':\n case 'hr':\n case 'h':\n return n * h;\n case 'minutes':\n case 'minute':\n case 'mins':\n case 'min':\n case 'm':\n return n * m;\n case 'seconds':\n case 'second':\n case 'secs':\n case 'sec':\n case 's':\n return n * s;\n case 'milliseconds':\n case 'millisecond':\n case 'msecs':\n case 'msec':\n case 'ms':\n return n;\n default:\n return undefined;\n }\n}\n\n/**\n * Short format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtShort(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return Math.round(ms / d) + 'd';\n }\n if (msAbs >= h) {\n return Math.round(ms / h) + 'h';\n }\n if (msAbs >= m) {\n return Math.round(ms / m) + 'm';\n }\n if (msAbs >= s) {\n return Math.round(ms / s) + 's';\n }\n return ms + 'ms';\n}\n\n/**\n * Long format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtLong(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return plural(ms, msAbs, d, 'day');\n }\n if (msAbs >= h) {\n return plural(ms, msAbs, h, 'hour');\n }\n if (msAbs >= m) {\n return plural(ms, msAbs, m, 'minute');\n }\n if (msAbs >= s) {\n return plural(ms, msAbs, s, 'second');\n }\n return ms + ' ms';\n}\n\n/**\n * Pluralization helper.\n */\n\nfunction plural(ms, msAbs, n, name) {\n var isPlural = msAbs >= n * 1.5;\n return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');\n}\n", "\n/**\n * This is the common logic for both the Node.js and web browser\n * implementations of `debug()`.\n */\n\nfunction setup(env) {\n\tcreateDebug.debug = createDebug;\n\tcreateDebug.default = createDebug;\n\tcreateDebug.coerce = coerce;\n\tcreateDebug.disable = disable;\n\tcreateDebug.enable = enable;\n\tcreateDebug.enabled = enabled;\n\tcreateDebug.humanize = require('ms');\n\tcreateDebug.destroy = destroy;\n\n\tObject.keys(env).forEach(key => {\n\t\tcreateDebug[key] = env[key];\n\t});\n\n\t/**\n\t* The currently active debug mode names, and names to skip.\n\t*/\n\n\tcreateDebug.names = [];\n\tcreateDebug.skips = [];\n\n\t/**\n\t* Map of special \"%n\" handling functions, for the debug \"format\" argument.\n\t*\n\t* Valid key names are a single, lower or upper-case letter, i.e. \"n\" and \"N\".\n\t*/\n\tcreateDebug.formatters = {};\n\n\t/**\n\t* Selects a color for a debug namespace\n\t* @param {String} namespace The namespace string for the debug instance to be colored\n\t* @return {Number|String} An ANSI color code for the given namespace\n\t* @api private\n\t*/\n\tfunction selectColor(namespace) {\n\t\tlet hash = 0;\n\n\t\tfor (let i = 0; i < namespace.length; i++) {\n\t\t\thash = ((hash << 5) - hash) + namespace.charCodeAt(i);\n\t\t\thash |= 0; // Convert to 32bit integer\n\t\t}\n\n\t\treturn createDebug.colors[Math.abs(hash) % createDebug.colors.length];\n\t}\n\tcreateDebug.selectColor = selectColor;\n\n\t/**\n\t* Create a debugger with the given `namespace`.\n\t*\n\t* @param {String} namespace\n\t* @return {Function}\n\t* @api public\n\t*/\n\tfunction createDebug(namespace) {\n\t\tlet prevTime;\n\t\tlet enableOverride = null;\n\t\tlet namespacesCache;\n\t\tlet enabledCache;\n\n\t\tfunction debug(...args) {\n\t\t\t// Disabled?\n\t\t\tif (!debug.enabled) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst self = debug;\n\n\t\t\t// Set `diff` timestamp\n\t\t\tconst curr = Number(new Date());\n\t\t\tconst ms = curr - (prevTime || curr);\n\t\t\tself.diff = ms;\n\t\t\tself.prev = prevTime;\n\t\t\tself.curr = curr;\n\t\t\tprevTime = curr;\n\n\t\t\targs[0] = createDebug.coerce(args[0]);\n\n\t\t\tif (typeof args[0] !== 'string') {\n\t\t\t\t// Anything else let's inspect with %O\n\t\t\t\targs.unshift('%O');\n\t\t\t}\n\n\t\t\t// Apply any `formatters` transformations\n\t\t\tlet index = 0;\n\t\t\targs[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {\n\t\t\t\t// If we encounter an escaped % then don't increase the array index\n\t\t\t\tif (match === '%%') {\n\t\t\t\t\treturn '%';\n\t\t\t\t}\n\t\t\t\tindex++;\n\t\t\t\tconst formatter = createDebug.formatters[format];\n\t\t\t\tif (typeof formatter === 'function') {\n\t\t\t\t\tconst val = args[index];\n\t\t\t\t\tmatch = formatter.call(self, val);\n\n\t\t\t\t\t// Now we need to remove `args[index]` since it's inlined in the `format`\n\t\t\t\t\targs.splice(index, 1);\n\t\t\t\t\tindex--;\n\t\t\t\t}\n\t\t\t\treturn match;\n\t\t\t});\n\n\t\t\t// Apply env-specific formatting (colors, etc.)\n\t\t\tcreateDebug.formatArgs.call(self, args);\n\n\t\t\tconst logFn = self.log || createDebug.log;\n\t\t\tlogFn.apply(self, args);\n\t\t}\n\n\t\tdebug.namespace = namespace;\n\t\tdebug.useColors = createDebug.useColors();\n\t\tdebug.color = createDebug.selectColor(namespace);\n\t\tdebug.extend = extend;\n\t\tdebug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.\n\n\t\tObject.defineProperty(debug, 'enabled', {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: false,\n\t\t\tget: () => {\n\t\t\t\tif (enableOverride !== null) {\n\t\t\t\t\treturn enableOverride;\n\t\t\t\t}\n\t\t\t\tif (namespacesCache !== createDebug.namespaces) {\n\t\t\t\t\tnamespacesCache = createDebug.namespaces;\n\t\t\t\t\tenabledCache = createDebug.enabled(namespace);\n\t\t\t\t}\n\n\t\t\t\treturn enabledCache;\n\t\t\t},\n\t\t\tset: v => {\n\t\t\t\tenableOverride = v;\n\t\t\t}\n\t\t});\n\n\t\t// Env-specific initialization logic for debug instances\n\t\tif (typeof createDebug.init === 'function') {\n\t\t\tcreateDebug.init(debug);\n\t\t}\n\n\t\treturn debug;\n\t}\n\n\tfunction extend(namespace, delimiter) {\n\t\tconst newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);\n\t\tnewDebug.log = this.log;\n\t\treturn newDebug;\n\t}\n\n\t/**\n\t* Enables a debug mode by namespaces. This can include modes\n\t* separated by a colon and wildcards.\n\t*\n\t* @param {String} namespaces\n\t* @api public\n\t*/\n\tfunction enable(namespaces) {\n\t\tcreateDebug.save(namespaces);\n\t\tcreateDebug.namespaces = namespaces;\n\n\t\tcreateDebug.names = [];\n\t\tcreateDebug.skips = [];\n\n\t\tconst split = (typeof namespaces === 'string' ? namespaces : '')\n\t\t\t.trim()\n\t\t\t.replace(/\\s+/g, ',')\n\t\t\t.split(',')\n\t\t\t.filter(Boolean);\n\n\t\tfor (const ns of split) {\n\t\t\tif (ns[0] === '-') {\n\t\t\t\tcreateDebug.skips.push(ns.slice(1));\n\t\t\t} else {\n\t\t\t\tcreateDebug.names.push(ns);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Checks if the given string matches a namespace template, honoring\n\t * asterisks as wildcards.\n\t *\n\t * @param {String} search\n\t * @param {String} template\n\t * @return {Boolean}\n\t */\n\tfunction matchesTemplate(search, template) {\n\t\tlet searchIndex = 0;\n\t\tlet templateIndex = 0;\n\t\tlet starIndex = -1;\n\t\tlet matchIndex = 0;\n\n\t\twhile (searchIndex < search.length) {\n\t\t\tif (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === '*')) {\n\t\t\t\t// Match character or proceed with wildcard\n\t\t\t\tif (template[templateIndex] === '*') {\n\t\t\t\t\tstarIndex = templateIndex;\n\t\t\t\t\tmatchIndex = searchIndex;\n\t\t\t\t\ttemplateIndex++; // Skip the '*'\n\t\t\t\t} else {\n\t\t\t\t\tsearchIndex++;\n\t\t\t\t\ttemplateIndex++;\n\t\t\t\t}\n\t\t\t} else if (starIndex !== -1) { // eslint-disable-line no-negated-condition\n\t\t\t\t// Backtrack to the last '*' and try to match more characters\n\t\t\t\ttemplateIndex = starIndex + 1;\n\t\t\t\tmatchIndex++;\n\t\t\t\tsearchIndex = matchIndex;\n\t\t\t} else {\n\t\t\t\treturn false; // No match\n\t\t\t}\n\t\t}\n\n\t\t// Handle trailing '*' in template\n\t\twhile (templateIndex < template.length && template[templateIndex] === '*') {\n\t\t\ttemplateIndex++;\n\t\t}\n\n\t\treturn templateIndex === template.length;\n\t}\n\n\t/**\n\t* Disable debug output.\n\t*\n\t* @return {String} namespaces\n\t* @api public\n\t*/\n\tfunction disable() {\n\t\tconst namespaces = [\n\t\t\t...createDebug.names,\n\t\t\t...createDebug.skips.map(namespace => '-' + namespace)\n\t\t].join(',');\n\t\tcreateDebug.enable('');\n\t\treturn namespaces;\n\t}\n\n\t/**\n\t* Returns true if the given mode name is enabled, false otherwise.\n\t*\n\t* @param {String} name\n\t* @return {Boolean}\n\t* @api public\n\t*/\n\tfunction enabled(name) {\n\t\tfor (const skip of createDebug.skips) {\n\t\t\tif (matchesTemplate(name, skip)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\tfor (const ns of createDebug.names) {\n\t\t\tif (matchesTemplate(name, ns)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/**\n\t* Coerce `val`.\n\t*\n\t* @param {Mixed} val\n\t* @return {Mixed}\n\t* @api private\n\t*/\n\tfunction coerce(val) {\n\t\tif (val instanceof Error) {\n\t\t\treturn val.stack || val.message;\n\t\t}\n\t\treturn val;\n\t}\n\n\t/**\n\t* XXX DO NOT USE. This is a temporary stub function.\n\t* XXX It WILL be removed in the next major release.\n\t*/\n\tfunction destroy() {\n\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t}\n\n\tcreateDebug.enable(createDebug.load());\n\n\treturn createDebug;\n}\n\nmodule.exports = setup;\n", "/* eslint-env browser */\n\n/**\n * This is the web browser implementation of `debug()`.\n */\n\nexports.formatArgs = formatArgs;\nexports.save = save;\nexports.load = load;\nexports.useColors = useColors;\nexports.storage = localstorage();\nexports.destroy = (() => {\n\tlet warned = false;\n\n\treturn () => {\n\t\tif (!warned) {\n\t\t\twarned = true;\n\t\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t\t}\n\t};\n})();\n\n/**\n * Colors.\n */\n\nexports.colors = [\n\t'#0000CC',\n\t'#0000FF',\n\t'#0033CC',\n\t'#0033FF',\n\t'#0066CC',\n\t'#0066FF',\n\t'#0099CC',\n\t'#0099FF',\n\t'#00CC00',\n\t'#00CC33',\n\t'#00CC66',\n\t'#00CC99',\n\t'#00CCCC',\n\t'#00CCFF',\n\t'#3300CC',\n\t'#3300FF',\n\t'#3333CC',\n\t'#3333FF',\n\t'#3366CC',\n\t'#3366FF',\n\t'#3399CC',\n\t'#3399FF',\n\t'#33CC00',\n\t'#33CC33',\n\t'#33CC66',\n\t'#33CC99',\n\t'#33CCCC',\n\t'#33CCFF',\n\t'#6600CC',\n\t'#6600FF',\n\t'#6633CC',\n\t'#6633FF',\n\t'#66CC00',\n\t'#66CC33',\n\t'#9900CC',\n\t'#9900FF',\n\t'#9933CC',\n\t'#9933FF',\n\t'#99CC00',\n\t'#99CC33',\n\t'#CC0000',\n\t'#CC0033',\n\t'#CC0066',\n\t'#CC0099',\n\t'#CC00CC',\n\t'#CC00FF',\n\t'#CC3300',\n\t'#CC3333',\n\t'#CC3366',\n\t'#CC3399',\n\t'#CC33CC',\n\t'#CC33FF',\n\t'#CC6600',\n\t'#CC6633',\n\t'#CC9900',\n\t'#CC9933',\n\t'#CCCC00',\n\t'#CCCC33',\n\t'#FF0000',\n\t'#FF0033',\n\t'#FF0066',\n\t'#FF0099',\n\t'#FF00CC',\n\t'#FF00FF',\n\t'#FF3300',\n\t'#FF3333',\n\t'#FF3366',\n\t'#FF3399',\n\t'#FF33CC',\n\t'#FF33FF',\n\t'#FF6600',\n\t'#FF6633',\n\t'#FF9900',\n\t'#FF9933',\n\t'#FFCC00',\n\t'#FFCC33'\n];\n\n/**\n * Currently only WebKit-based Web Inspectors, Firefox >= v31,\n * and the Firebug extension (any Firefox version) are known\n * to support \"%c\" CSS customizations.\n *\n * TODO: add a `localStorage` variable to explicitly enable/disable colors\n */\n\n// eslint-disable-next-line complexity\nfunction useColors() {\n\t// NB: In an Electron preload script, document will be defined but not fully\n\t// initialized. Since we know we're in Chrome, we'll just detect this case\n\t// explicitly\n\tif (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {\n\t\treturn true;\n\t}\n\n\t// Internet Explorer and Edge do not support colors.\n\tif (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\\/(\\d+)/)) {\n\t\treturn false;\n\t}\n\n\tlet m;\n\n\t// Is webkit? http://stackoverflow.com/a/16459606/376773\n\t// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632\n\t// eslint-disable-next-line no-return-assign\n\treturn (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||\n\t\t// Is firebug? http://stackoverflow.com/a/398120/376773\n\t\t(typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||\n\t\t// Is firefox >= v31?\n\t\t// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages\n\t\t(typeof navigator !== 'undefined' && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\\/(\\d+)/)) && parseInt(m[1], 10) >= 31) ||\n\t\t// Double check webkit in userAgent just in case we are in a worker\n\t\t(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\\/(\\d+)/));\n}\n\n/**\n * Colorize log arguments if enabled.\n *\n * @api public\n */\n\nfunction formatArgs(args) {\n\targs[0] = (this.useColors ? '%c' : '') +\n\t\tthis.namespace +\n\t\t(this.useColors ? ' %c' : ' ') +\n\t\targs[0] +\n\t\t(this.useColors ? '%c ' : ' ') +\n\t\t'+' + module.exports.humanize(this.diff);\n\n\tif (!this.useColors) {\n\t\treturn;\n\t}\n\n\tconst c = 'color: ' + this.color;\n\targs.splice(1, 0, c, 'color: inherit');\n\n\t// The final \"%c\" is somewhat tricky, because there could be other\n\t// arguments passed either before or after the %c, so we need to\n\t// figure out the correct index to insert the CSS into\n\tlet index = 0;\n\tlet lastC = 0;\n\targs[0].replace(/%[a-zA-Z%]/g, match => {\n\t\tif (match === '%%') {\n\t\t\treturn;\n\t\t}\n\t\tindex++;\n\t\tif (match === '%c') {\n\t\t\t// We only are interested in the *last* %c\n\t\t\t// (the user may have provided their own)\n\t\t\tlastC = index;\n\t\t}\n\t});\n\n\targs.splice(lastC, 0, c);\n}\n\n/**\n * Invokes `console.debug()` when available.\n * No-op when `console.debug` is not a \"function\".\n * If `console.debug` is not available, falls back\n * to `console.log`.\n *\n * @api public\n */\nexports.log = console.debug || console.log || (() => {});\n\n/**\n * Save `namespaces`.\n *\n * @param {String} namespaces\n * @api private\n */\nfunction save(namespaces) {\n\ttry {\n\t\tif (namespaces) {\n\t\t\texports.storage.setItem('debug', namespaces);\n\t\t} else {\n\t\t\texports.storage.removeItem('debug');\n\t\t}\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n}\n\n/**\n * Load `namespaces`.\n *\n * @return {String} returns the previously persisted debug modes\n * @api private\n */\nfunction load() {\n\tlet r;\n\ttry {\n\t\tr = exports.storage.getItem('debug') || exports.storage.getItem('DEBUG') ;\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n\n\t// If debug isn't set in LS, and we're in Electron, try to load $DEBUG\n\tif (!r && typeof process !== 'undefined' && 'env' in process) {\n\t\tr = process.env.DEBUG;\n\t}\n\n\treturn r;\n}\n\n/**\n * Localstorage attempts to return the localstorage.\n *\n * This is necessary because safari throws\n * when a user disables cookies/localstorage\n * and you attempt to access it.\n *\n * @return {LocalStorage}\n * @api private\n */\n\nfunction localstorage() {\n\ttry {\n\t\t// TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context\n\t\t// The Browser also has localStorage in the global context.\n\t\treturn localStorage;\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n}\n\nmodule.exports = require('./common')(exports);\n\nconst {formatters} = module.exports;\n\n/**\n * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.\n */\n\nformatters.j = function (v) {\n\ttry {\n\t\treturn JSON.stringify(v);\n\t} catch (error) {\n\t\treturn '[UnexpectedJSONParseError]: ' + error.message;\n\t}\n};\n", "/**\n * @license\n * Copyright 2017 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\n\n// IMPORTANT: these imports must be type-only\nimport type {Directive, DirectiveResult, PartInfo} from './directive.js';\nimport type {TrustedHTML, TrustedTypesWindow} from 'trusted-types/lib/index.js';\n\nconst DEV_MODE = true;\nconst ENABLE_EXTRA_SECURITY_HOOKS = true;\nconst ENABLE_SHADYDOM_NOPATCH = true;\nconst NODE_MODE = false;\n\n// Allows minifiers to rename references to globalThis\nconst global = globalThis;\n\n/**\n * Contains types that are part of the unstable debug API.\n *\n * Everything in this API is not stable and may change or be removed in the future,\n * even on patch releases.\n */\n// eslint-disable-next-line @typescript-eslint/no-namespace\nexport namespace LitUnstable {\n /**\n * When Lit is running in dev mode and `window.emitLitDebugLogEvents` is true,\n * we will emit 'lit-debug' events to window, with live details about the update and render\n * lifecycle. These can be useful for writing debug tooling and visualizations.\n *\n * Please be aware that running with window.emitLitDebugLogEvents has performance overhead,\n * making certain operations that are normally very cheap (like a no-op render) much slower,\n * because we must copy data and dispatch events.\n */\n // eslint-disable-next-line @typescript-eslint/no-namespace\n export namespace DebugLog {\n export type Entry =\n | TemplatePrep\n | TemplateInstantiated\n | TemplateInstantiatedAndUpdated\n | TemplateUpdating\n | BeginRender\n | EndRender\n | CommitPartEntry\n | SetPartValue;\n export interface TemplatePrep {\n kind: 'template prep';\n template: Template;\n strings: TemplateStringsArray;\n clonableTemplate: HTMLTemplateElement;\n parts: TemplatePart[];\n }\n export interface BeginRender {\n kind: 'begin render';\n id: number;\n value: unknown;\n container: HTMLElement | DocumentFragment;\n options: RenderOptions | undefined;\n part: ChildPart | undefined;\n }\n export interface EndRender {\n kind: 'end render';\n id: number;\n value: unknown;\n container: HTMLElement | DocumentFragment;\n options: RenderOptions | undefined;\n part: ChildPart;\n }\n export interface TemplateInstantiated {\n kind: 'template instantiated';\n template: Template | CompiledTemplate;\n instance: TemplateInstance;\n options: RenderOptions | undefined;\n fragment: Node;\n parts: Array<Part | undefined>;\n values: unknown[];\n }\n export interface TemplateInstantiatedAndUpdated {\n kind: 'template instantiated and updated';\n template: Template | CompiledTemplate;\n instance: TemplateInstance;\n options: RenderOptions | undefined;\n fragment: Node;\n parts: Array<Part | undefined>;\n values: unknown[];\n }\n export interface TemplateUpdating {\n kind: 'template updating';\n template: Template | CompiledTemplate;\n instance: TemplateInstance;\n options: RenderOptions | undefined;\n parts: Array<Part | undefined>;\n values: unknown[];\n }\n export interface SetPartValue {\n kind: 'set part';\n part: Part;\n value: unknown;\n valueIndex: number;\n values: unknown[];\n templateInstance: TemplateInstance;\n }\n\n export type CommitPartEntry =\n | CommitNothingToChildEntry\n | CommitText\n | CommitNode\n | CommitAttribute\n | CommitProperty\n | CommitBooleanAttribute\n | CommitEventListener\n | CommitToElementBinding;\n\n export interface CommitNothingToChildEntry {\n kind: 'commit nothing to child';\n start: ChildNode;\n end: ChildNode | null;\n parent: Disconnectable | undefined;\n options: RenderOptions | undefined;\n }\n\n export interface CommitText {\n kind: 'commit text';\n node: Text;\n value: unknown;\n options: RenderOptions | undefined;\n }\n\n export interface CommitNode {\n kind: 'commit node';\n start: Node;\n parent: Disconnectable | undefined;\n value: Node;\n options: RenderOptions | undefined;\n }\n\n export interface CommitAttribute {\n kind: 'commit attribute';\n element: Element;\n name: string;\n value: unknown;\n options: RenderOptions | undefined;\n }\n\n export interface CommitProperty {\n kind: 'commit property';\n element: Element;\n name: string;\n value: unknown;\n options: RenderOptions | undefined;\n }\n\n export interface CommitBooleanAttribute {\n kind: 'commit boolean attribute';\n element: Element;\n name: string;\n value: boolean;\n options: RenderOptions | undefined;\n }\n\n export interface CommitEventListener {\n kind: 'commit event listener';\n element: Element;\n name: string;\n value: unknown;\n oldListener: unknown;\n options: RenderOptions | undefined;\n // True if we're removing the old event listener (e.g. because settings changed, or value is nothing)\n removeListener: boolean;\n // True if we're adding a new event listener (e.g. because first render, or settings changed)\n addListener: boolean;\n }\n\n export interface CommitToElementBinding {\n kind: 'commit to element binding';\n element: Element;\n value: unknown;\n options: RenderOptions | undefined;\n }\n }\n}\n\ninterface DebugLoggingWindow {\n // Even in dev mode, we generally don't want to emit these events, as that's\n // another level of cost, so only emit them when DEV_MODE is true _and_ when\n // window.emitLitDebugEvents is true.\n emitLitDebugLogEvents?: boolean;\n}\n\n/**\n * Useful for visualizing and logging insights into what the Lit template system is doing.\n *\n * Compiled out of prod mode builds.\n */\nconst debugLogEvent = DEV_MODE\n ? (event: LitUnstable.DebugLog.Entry) => {\n const shouldEmit = (global as unknown as DebugLoggingWindow)\n .emitLitDebugLogEvents;\n if (!shouldEmit) {\n return;\n }\n global.dispatchEvent(\n new CustomEvent<LitUnstable.DebugLog.Entry>('lit-debug', {\n detail: event,\n })\n );\n }\n : undefined;\n// Used for connecting beginRender and endRender events when there are nested\n// renders when errors are thrown preventing an endRender event from being\n// called.\nlet debugLogRenderId = 0;\n\nlet issueWarning: (code: string, warning: string) => void;\n\nif (DEV_MODE) {\n global.litIssuedWarnings ??= new Set();\n\n /**\n * Issue a warning if we haven't already, based either on `code` or `warning`.\n * Warnings are disabled automatically only by `warning`; disabling via `code`\n * can be done by users.\n */\n issueWarning = (code: string, warning: string) => {\n warning += code\n ? ` See https://lit.dev/msg/${code} for more information.`\n : '';\n if (\n !global.litIssuedWarnings!.has(warning) &&\n !global.litIssuedWarnings!.has(code)\n ) {\n console.warn(warning);\n global.litIssuedWarnings!.add(warning);\n }\n };\n\n queueMicrotask(() => {\n issueWarning(\n 'dev-mode',\n `Lit is in dev mode. Not recommended for production!`\n );\n });\n}\n\nconst wrap =\n ENABLE_SHADYDOM_NOPATCH &&\n global.ShadyDOM?.inUse &&\n global.ShadyDOM?.noPatch === true\n ? (global.ShadyDOM!.wrap as <T extends Node>(node: T) => T)\n : <T extends Node>(node: T) => node;\n\nconst trustedTypes = (global as unknown as TrustedTypesWindow).trustedTypes;\n\n/**\n * Our TrustedTypePolicy for HTML which is declared using the html template\n * tag function.\n *\n * That HTML is a developer-authored constant, and is parsed with innerHTML\n * before any untrusted expressions have been mixed in. Therefor it is\n * considered safe by construction.\n */\nconst policy = trustedTypes\n ? trustedTypes.createPolicy('lit-html', {\n createHTML: (s) => s,\n })\n : undefined;\n\n/**\n * Used to sanitize any value before it is written into the DOM. This can be\n * used to implement a security policy of allowed and disallowed values in\n * order to prevent XSS attacks.\n *\n * One way of using this callback would be to check attributes and properties\n * against a list of high risk fields, and require that values written to such\n * fields be instances of a class which is safe by construction. Closure's Safe\n * HTML Types is one implementation of this technique (\n * https://github.com/google/safe-html-types/blob/master/doc/safehtml-types.md).\n * The TrustedTypes polyfill in API-only mode could also be used as a basis\n * for this technique (https://github.com/WICG/trusted-types).\n *\n * @param node The HTML node (usually either a #text node or an Element) that\n * is being written to. Note that this is just an exemplar node, the write\n * may take place against another instance of the same class of node.\n * @param name The name of an attribute or property (for example, 'href').\n * @param type Indicates whether the write that's about to be performed will\n * be to a property or a node.\n * @return A function that will sanitize this class of writes.\n */\nexport type SanitizerFactory = (\n node: Node,\n name: string,\n type: 'property' | 'attribute'\n) => ValueSanitizer;\n\n/**\n * A function which can sanitize values that will be written to a specific kind\n * of DOM sink.\n *\n * See SanitizerFactory.\n *\n * @param value The value to sanitize. Will be the actual value passed into\n * the lit-html template literal, so this could be of any type.\n * @return The value to write to the DOM. Usually the same as the input value,\n * unless sanitization is needed.\n */\nexport type ValueSanitizer = (value: unknown) => unknown;\n\nconst identityFunction: ValueSanitizer = (value: unknown) => value;\nconst noopSanitizer: SanitizerFactory = (\n _node: Node,\n _name: string,\n _type: 'property' | 'attribute'\n) => identityFunction;\n\n/** Sets the global sanitizer factory. */\nconst setSanitizer = (newSanitizer: SanitizerFactory) => {\n if (!ENABLE_EXTRA_SECURITY_HOOKS) {\n return;\n }\n if (sanitizerFactoryInternal !== noopSanitizer) {\n throw new Error(\n `Attempted to overwrite existing lit-html security policy.` +\n ` setSanitizeDOMValueFactory should be called at most once.`\n );\n }\n sanitizerFactoryInternal = newSanitizer;\n};\n\n/**\n * Only used in internal tests, not a part of the public API.\n */\nconst _testOnlyClearSanitizerFactoryDoNotCallOrElse = () => {\n sanitizerFactoryInternal = noopSanitizer;\n};\n\nconst createSanitizer: SanitizerFactory = (node, name, type) => {\n return sanitizerFactoryInternal(node, name, type);\n};\n\n// Added to an attribute name to mark the attribute as bound so we can find\n// it easily.\nconst boundAttributeSuffix = '$lit$';\n\n// This marker is used in many syntactic positions in HTML, so it must be\n// a valid element name and attribute name. We don't support dynamic names (yet)\n// but this at least ensures that the parse tree is closer to the template\n// intention.\nconst marker = `lit$${Math.random().toFixed(9).slice(2)}$`;\n\n// String used to tell if a comment is a marker comment\nconst markerMatch = '?' + marker;\n\n// Text used to insert a comment marker node. We use processing instruction\n// syntax because it's slightly smaller, but parses as a comment node.\nconst nodeMarker = `<${markerMatch}>`;\n\nconst d =\n NODE_MODE && global.document === undefined\n ? ({\n createTreeWalker() {\n return {};\n },\n } as unknown as Document)\n : document;\n\n// Creates a dynamic marker. We never have to search for these in the DOM.\nconst createMarker = () => d.createComment('');\n\n// https://tc39.github.io/ecma262/#sec-typeof-operator\ntype Primitive = null | undefined | boolean | number | string | symbol | bigint;\nconst isPrimitive = (value: unknown): value is Primitive =>\n value === null || (typeof value != 'object' && typeof value != 'function');\nconst isArray = Array.isArray;\nconst isIterable = (value: unknown): value is Iterable<unknown> =>\n isArray(value) ||\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n typeof (value as any)?.[Symbol.iterator] === 'function';\n\nconst SPACE_CHAR = `[ \\t\\n\\f\\r]`;\nconst ATTR_VALUE_CHAR = `[^ \\t\\n\\f\\r\"'\\`<>=]`;\nconst NAME_CHAR = `[^\\\\s\"'>=/]`;\n\n// These regexes represent the five parsing states that we care about in the\n// Template's HTML scanner. They match the *end* of the state they're named\n// after.\n// Depending on the match, we transition to a new state. If there's no match,\n// we stay in the same state.\n// Note that the regexes are stateful. We utilize lastIndex and sync it\n// across the multiple regexes used. In addition to the five regexes below\n// we also dynamically create a regex to find the matching end tags for raw\n// text elements.\n\n/**\n * End of text is: `<` followed by:\n * (comment start) or (tag) or (dynamic tag binding)\n */\nconst textEndRegex = /<(?:(!--|\\/[^a-zA-Z])|(\\/?[a-zA-Z][^>\\s]*)|(\\/?$))/g;\nconst COMMENT_START = 1;\nconst TAG_NAME = 2;\nconst DYNAMIC_TAG_NAME = 3;\n\nconst commentEndRegex = /-->/g;\n/**\n * Comments not started with <!--, like </{, can be ended by a single `>`\n */\nconst comment2EndRegex = />/g;\n\n/**\n * The tagEnd regex matches the end of the \"inside an opening\" tag syntax\n * position. It either matches a `>`, an attribute-like sequence, or the end\n * of the string after a space (attribute-name position ending).\n *\n * See attributes in the HTML spec:\n * https://www.w3.org/TR/html5/syntax.html#elements-attributes\n *\n * \" \\t\\n\\f\\r\" are HTML space characters:\n * https://infra.spec.whatwg.org/#ascii-whitespace\n *\n * So an attribute is:\n * * The name: any character except a whitespace character, (\"), ('), \">\",\n * \"=\", or \"/\". Note: this is different from the HTML spec which also excludes control characters.\n * * Followed by zero or more space characters\n * * Followed by \"=\"\n * * Followed by zero or more space characters\n * * Followed by:\n * * Any character except space, ('), (\"), \"<\", \">\", \"=\", (`), or\n * * (\") then any non-(\"), or\n * * (') then any non-(')\n */\nconst tagEndRegex = new RegExp(\n `>|${SPACE_CHAR}(?:(${NAME_CHAR}+)(${SPACE_CHAR}*=${SPACE_CHAR}*(?:${ATTR_VALUE_CHAR}|(\"|')|))|$)`,\n 'g'\n);\nconst ENTIRE_MATCH = 0;\nconst ATTRIBUTE_NAME = 1;\nconst SPACES_AND_EQUALS = 2;\nconst QUOTE_CHAR = 3;\n\nconst singleQuoteAttrEndRegex = /'/g;\nconst doubleQuoteAttrEndRegex = /\"/g;\n/**\n * Matches the raw text elements.\n *\n * Comments are not parsed within raw text elements, so we need to search their\n * text content for marker strings.\n */\nconst rawTextElement = /^(?:script|style|textarea|title)$/i;\n\n/** TemplateResult types */\nconst HTML_RESULT = 1;\nconst SVG_RESULT = 2;\nconst MATHML_RESULT = 3;\n\ntype ResultType = typeof HTML_RESULT | typeof SVG_RESULT | typeof MATHML_RESULT;\n\n// TemplatePart types\n// IMPORTANT: these must match the values in PartType\nconst ATTRIBUTE_PART = 1;\nconst CHILD_PART = 2;\nconst PROPERTY_PART = 3;\nconst BOOLEAN_ATTRIBUTE_PART = 4;\nconst EVENT_PART = 5;\nconst ELEMENT_PART = 6;\nconst COMMENT_PART = 7;\n\n/**\n * The return type of the template tag functions, {@linkcode html} and\n * {@linkcode svg} when it hasn't been compiled by @lit-labs/compiler.\n *\n * A `TemplateResult` object holds all the information about a template\n * expression required to render it: the template strings, expression values,\n * and type of template (html or svg).\n *\n * `TemplateResult` objects do not create any DOM on their own. To create or\n * update DOM you need to render the `TemplateResult`. See\n * [Rendering](https://lit.dev/docs/components/rendering) for more information.\n *\n */\nexport type UncompiledTemplateResult<T extends ResultType = ResultType> = {\n // This property needs to remain unminified.\n ['_$litType$']: T;\n strings: TemplateStringsArray;\n values: unknown[];\n};\n\n/**\n * This is a template result that may be either uncompiled or compiled.\n *\n * In the future, TemplateResult will be this type. If you want to explicitly\n * note that a template result is potentially compiled, you can reference this\n * type and it will continue to behave the same through the next major version\n * of Lit. This can be useful for code that wants to prepare for the next\n * major version of Lit.\n */\nexport type MaybeCompiledTemplateResult<T extends ResultType = ResultType> =\n | UncompiledTemplateResult<T>\n | CompiledTemplateResult;\n\n/**\n * The return type of the template tag functions, {@linkcode html} and\n * {@linkcode svg}.\n *\n * A `TemplateResult` object holds all the information about a template\n * expression required to render it: the template strings, expression values,\n * and type of template (html or svg).\n *\n * `TemplateResult` objects do not create any DOM on their own. To create or\n * update DOM you need to render the `TemplateResult`. See\n * [Rendering](https://lit.dev/docs/components/rendering) for more information.\n *\n * In Lit 4, this type will be an alias of\n * MaybeCompiledTemplateResult, so that code will get type errors if it assumes\n * that Lit templates are not compiled. When deliberately working with only\n * one, use either {@linkcode CompiledTemplateResult} or\n * {@linkcode UncompiledTemplateResult} explicitly.\n */\nexport type TemplateResult<T extends ResultType = ResultType> =\n UncompiledTemplateResult<T>;\n\nexport type HTMLTemplateResult = TemplateResult<typeof HTML_RESULT>;\n\nexport type SVGTemplateResult = TemplateResult<typeof SVG_RESULT>;\n\nexport type MathMLTemplateResult = TemplateResult<typeof MATHML_RESULT>;\n\n/**\n * A TemplateResult that has been compiled by @lit-labs/compiler, skipping the\n * prepare step.\n */\nexport interface CompiledTemplateResult {\n // This is a factory in order to make template initialization lazy\n // and allow ShadyRenderOptions scope to be passed in.\n // This property needs to remain unminified.\n ['_$litType$']: CompiledTemplate;\n values: unknown[];\n}\n\nexport interface CompiledTemplate extends Omit<Template, 'el'> {\n // el is overridden to be optional. We initialize it on first render\n el?: HTMLTemplateElement;\n\n // The prepared HTML string to create a template element from.\n // The type is a TemplateStringsArray to guarantee that the value came from\n // source code, preventing a JSON injection attack.\n h: TemplateStringsArray;\n}\n\n/**\n * Generates a template literal tag function that returns a TemplateResult with\n * the given result type.\n */\nconst tag =\n <T extends ResultType>(type: T) =>\n (strings: TemplateStringsArray, ...values: unknown[]): TemplateResult<T> => {\n // Warn against templates octal escape sequences\n // We do this here rather than in render so that the warning is closer to the\n // template definition.\n if (DEV_MODE && strings.some((s) => s === undefined)) {\n console.warn(\n 'Some template strings are undefined.\\n' +\n 'This is probably caused by illegal octal escape sequences.'\n );\n }\n if (DEV_MODE) {\n // Import static-html.js results in a circular dependency which g3 doesn't\n // handle. Instead we know that static values must have the field\n // `_$litStatic$`.\n if (\n values.some((val) => (val as {_$litStatic$: unknown})?.['_$litStatic$'])\n ) {\n issueWarning(\n '',\n `Static values 'literal' or 'unsafeStatic' cannot be used as values to non-static templates.\\n` +\n `Please use the static 'html' tag function. See https://lit.dev/docs/templates/expressions/#static-expressions`\n );\n }\n }\n return {\n // This property needs to remain unminified.\n ['_$litType$']: type,\n strings,\n values,\n };\n };\n\n/**\n * Interprets a template literal as an HTML template that can efficiently\n * render to and update a container.\n *\n * ```ts\n * const header = (title: string) => html`<h1>${title}</h1>`;\n * ```\n *\n * The `html` tag returns a description of the DOM to render as a value. It is\n * lazy, meaning no work is done until the template is rendered. When rendering,\n * if a template comes from the same expression as a previously rendered result,\n * it's efficiently updated instead of replaced.\n */\nexport const html = tag(HTML_RESULT);\n\n/**\n * Interprets a template literal as an SVG fragment that can efficiently render\n * to and update a container.\n *\n * ```ts\n * const rect = svg`<rect width=\"10\" height=\"10\"></rect>`;\n *\n * const myImage = html`\n * <svg viewBox=\"0 0 10 10\" xmlns=\"http://www.w3.org/2000/svg\">\n * ${rect}\n * </svg>`;\n * ```\n *\n * The `svg` *tag function* should only be used for SVG fragments, or elements\n * that would be contained **inside** an `<svg>` HTML element. A common error is\n * placing an `<svg>` *element* in a template tagged with the `svg` tag\n * function. The `<svg>` element is an HTML element and should be used within a\n * template tagged with the {@linkcode html} tag function.\n *\n * In LitElement usage, it's invalid to return an SVG fragment from the\n * `render()` method, as the SVG fragment will be contained within the element's\n * shadow root and thus not be properly contained within an `<svg>` HTML\n * element.\n */\nexport const svg = tag(SVG_RESULT);\n\n/**\n * Interprets a template literal as MathML fragment that can efficiently render\n * to and update a container.\n *\n * ```ts\n * const num = mathml`<mn>1</mn>`;\n *\n * const eq = html`\n * <math>\n * ${num}\n * </math>`;\n * ```\n *\n * The `mathml` *tag function* should only be used for MathML fragments, or\n * elements that would be contained **inside** a `<math>` HTML element. A common\n * error is placing a `<math>` *element* in a template tagged with the `mathml`\n * tag function. The `<math>` element is an HTML element and should be used\n * within a template tagged with the {@linkcode html} tag function.\n *\n * In LitElement usage, it's invalid to return an MathML fragment from the\n * `render()` method, as the MathML fragment will be contained within the\n * element's shadow root and thus not be properly contained within a `<math>`\n * HTML element.\n */\nexport const mathml = tag(MATHML_RESULT);\n\n/**\n * A sentinel value that signals that a value was handled by a directive and\n * should not be written to the DOM.\n */\nexport const noChange = Symbol.for('lit-noChange');\n\n/**\n * A sentinel value that signals a ChildPart to fully clear its content.\n *\n * ```ts\n * const button = html`${\n * user.isAdmin\n * ? html`<button>DELETE</button>`\n * : nothing\n * }`;\n * ```\n *\n * Prefer using `nothing` over other falsy values as it provides a consistent\n * behavior between various expression binding contexts.\n *\n * In child expressions, `undefined`, `null`, `''`, and `nothing` all behave the\n * same and render no nodes. In attribute expressions, `nothing` _removes_ the\n * attribute, while `undefined` and `null` will render an empty string. In\n * property expressions `nothing` becomes `undefined`.\n */\nexport const nothing = Symbol.for('lit-nothing');\n\n/**\n * The cache of prepared templates, keyed by the tagged TemplateStringsArray\n * and _not_ accounting for the specific template tag used. This means that\n * template tags cannot be dynamic - they must statically be one of html, svg,\n * or attr. This restriction simplifies the cache lookup, which is on the hot\n * path for rendering.\n */\nconst templateCache = new WeakMap<TemplateStringsArray, Template>();\n\n/**\n * Object specifying options for controlling lit-html rendering. Note that\n * while `render` may be called multiple times on the same `container` (and\n * `renderBefore` reference node) to efficiently update the rendered content,\n * only the options passed in during the first render are respected during\n * the lifetime of renders to that unique `container` + `renderBefore`\n * combination.\n */\nexport interface RenderOptions {\n /**\n * An object to use as the `this` value for event listeners. It's often\n * useful to set this to the host component rendering a template.\n */\n host?: object;\n /**\n * A DOM node before which to render content in the container.\n */\n renderBefore?: ChildNode | null;\n /**\n * Node used for cloning the template (`importNode` will be called on this\n * node). This controls the `ownerDocument` of the rendered DOM, along with\n * any inherited context. Defaults to the global `document`.\n */\n creationScope?: {importNode(node: Node, deep?: boolean): Node};\n /**\n * The initial connected state for the top-level part being rendered. If no\n * `isConnected` option is set, `AsyncDirective`s will be connected by\n * default. Set to `false` if the initial render occurs in a disconnected tree\n * and `AsyncDirective`s should see `isConnected === false` for their initial\n * render. The `part.setConnected()` method must be used subsequent to initial\n * render to change the connected state of the part.\n */\n isConnected?: boolean;\n}\n\nconst walker = d.createTreeWalker(\n d,\n 129 /* NodeFilter.SHOW_{ELEMENT|COMMENT} */\n);\n\nlet sanitizerFactoryInternal: SanitizerFactory = noopSanitizer;\n\n//\n// Classes only below here, const variable declarations only above here...\n//\n// Keeping variable declarations and classes together improves minification.\n// Interfaces and type aliases can be interleaved freely.\n//\n\n// Type for classes that have a `_directive` or `_directives[]` field, used by\n// `resolveDirective`\nexport interface DirectiveParent {\n _$parent?: DirectiveParent;\n _$isConnected: boolean;\n __directive?: Directive;\n __directives?: Array<Directive | undefined>;\n}\n\nfunction trustFromTemplateString(\n tsa: TemplateStringsArray,\n stringFromTSA: string\n): TrustedHTML {\n // A security check to prevent spoofing of Lit template results.\n // In the future, we may be able to replace this with Array.isTemplateObject,\n // though we might need to make that check inside of the html and svg\n // functions, because precompiled templates don't come in as\n // TemplateStringArray objects.\n if (!isArray(tsa) || !tsa.hasOwnProperty('raw')) {\n let message = 'invalid template strings array';\n if (DEV_MODE) {\n message = `\n Internal Error: expected template strings to be an array\n with a 'raw' field. Faking a template strings array by\n calling html or svg like an ordinary function is effectively\n the same as calling unsafeHtml and can lead to major security\n issues, e.g. opening your code up to XSS attacks.\n If you're using the html or svg tagged template functions normally\n and still seeing this error, please file a bug at\n https://github.com/lit/lit/issues/new?template=bug_report.md\n and include information about your build tooling, if any.\n `\n .trim()\n .replace(/\\n */g, '\\n');\n }\n throw new Error(message);\n }\n return policy !== undefined\n ? policy.createHTML(stringFromTSA)\n : (stringFromTSA as unknown as TrustedHTML);\n}\n\n/**\n * Returns an HTML string for the given TemplateStringsArray and result type\n * (HTML or SVG), along with the case-sensitive bound attribute names in\n * template order. The HTML contains comment markers denoting the `ChildPart`s\n * and suffixes on bound attributes denoting the `AttributeParts`.\n *\n * @param strings template strings array\n * @param type HTML or SVG\n * @return Array containing `[html, attrNames]` (array returned for terseness,\n * to avoid object fields since this code is shared with non-minified SSR\n * code)\n */\nconst getTemplateHtml = (\n strings: TemplateStringsArray,\n type: ResultType\n): [TrustedHTML, Array<string>] => {\n // Insert makers into the template HTML to represent the position of\n // bindings. The following code scans the template strings to determine the\n // syntactic position of the bindings. They can be in text position, where\n // we insert an HTML comment, attribute value position, where we insert a\n // sentinel string and re-write the attribute name, or inside a tag where\n // we insert the sentinel string.\n const l = strings.length - 1;\n // Stores the case-sensitive bound attribute names in the order of their\n // parts. ElementParts are also reflected in this array as undefined\n // rather than a string, to disambiguate from attribute bindings.\n const attrNames: Array<string> = [];\n let html =\n type === SVG_RESULT ? '<svg>' : type === MATHML_RESULT ? '<math>' : '';\n\n // When we're inside a raw text tag (not it's text content), the regex\n // will still be tagRegex so we can find attributes, but will switch to\n // this regex when the tag ends.\n let rawTextEndRegex: RegExp | undefined;\n\n // The current parsing state, represented as a reference to one of the\n // regexes\n let regex = textEndRegex;\n\n for (let i = 0; i < l; i++) {\n const s = strings[i];\n // The index of the end of the last attribute name. When this is\n // positive at end of a string, it means we're in an attribute value\n // position and need to rewrite the attribute name.\n // We also use a special value of -2 to indicate that we encountered\n // the end of a string in attribute name position.\n let attrNameEndIndex = -1;\n let attrName: string | undefined;\n let lastIndex = 0;\n let match!: RegExpExecArray | null;\n\n // The conditions in this loop handle the current parse state, and the\n // assignments to the `regex` variable are the state transitions.\n while (lastIndex < s.length) {\n // Make sure we start searching from where we previously left off\n regex.lastIndex = lastIndex;\n match = regex.exec(s);\n if (match === null) {\n break;\n }\n lastIndex = regex.lastIndex;\n if (regex === textEndRegex) {\n if (match[COMMENT_START] === '!--') {\n regex = commentEndRegex;\n } else if (match[COMMENT_START] !== undefined) {\n // We started a weird comment, like </{\n regex = comment2EndRegex;\n } else if (match[TAG_NAME] !== undefined) {\n if (rawTextElement.test(match[TAG_NAME])) {\n // Record if we encounter a raw-text element. We'll switch to\n // this regex at the end of the tag.\n rawTextEndRegex = new RegExp(`</${match[TAG_NAME]}`, 'g');\n }\n regex = tagEndRegex;\n } else if (match[DYNAMIC_TAG_NAME] !== undefined) {\n if (DEV_MODE) {\n throw new Error(\n 'Bindings in tag names are not supported. Please use static templates instead. ' +\n 'See https://lit.dev/docs/templates/expressions/#static-expressions'\n );\n }\n regex = tagEndRegex;\n }\n } else if (regex === tagEndRegex) {\n if (match[ENTIRE_MATCH] === '>') {\n // End of a tag. If we had started a raw-text element, use that\n // regex\n regex = rawTextEndRegex ?? textEndRegex;\n // We may be ending an unquoted attribute value, so make sure we\n // clear any pending attrNameEndIndex\n attrNameEndIndex = -1;\n } else if (match[ATTRIBUTE_NAME] === undefined) {\n // Attribute name position\n attrNameEndIndex = -2;\n } else {\n attrNameEndIndex = regex.lastIndex - match[SPACES_AND_EQUALS].length;\n attrName = match[ATTRIBUTE_NAME];\n regex =\n match[QUOTE_CHAR] === undefined\n ? tagEndRegex\n : match[QUOTE_CHAR] === '\"'\n ? doubleQuoteAttrEndRegex\n : singleQuoteAttrEndRegex;\n }\n } else if (\n regex === doubleQuoteAttrEndRegex ||\n regex === singleQuoteAttrEndRegex\n ) {\n regex = tagEndRegex;\n } else if (regex === commentEndRegex || regex === comment2EndRegex) {\n regex = textEndRegex;\n } else {\n // Not one of the five state regexes, so it must be the dynamically\n // created raw text regex and we're at the close of that element.\n regex = tagEndRegex;\n rawTextEndRegex = undefined;\n }\n }\n\n if (DEV_MODE) {\n // If we have a attrNameEndIndex, which indicates that we should\n // rewrite the attribute name, assert that we're in a valid attribute\n // position - either in a tag, or a quoted attribute value.\n console.assert(\n attrNameEndIndex === -1 ||\n regex === tagEndRegex ||\n regex === singleQuoteAttrEndRegex ||\n regex === doubleQuoteAttrEndRegex,\n 'unexpected parse state B'\n );\n }\n\n // We have four cases:\n // 1. We're in text position, and not in a raw text element\n // (regex === textEndRegex): insert a comment marker.\n // 2. We have a non-negative attrNameEndIndex which means we need to\n // rewrite the attribute name to add a bound attribute suffix.\n // 3. We're at the non-first binding in a multi-binding attribute, use a\n // plain marker.\n // 4. We're somewhere else inside the tag. If we're in attribute name\n // position (attrNameEndIndex === -2), add a sequential suffix to\n // generate a unique attribute name.\n\n // Detect a binding next to self-closing tag end and insert a space to\n // separate the marker from the tag end:\n const end =\n regex === tagEndRegex && strings[i + 1].startsWith('/>') ? ' ' : '';\n html +=\n regex === textEndRegex\n ? s + nodeMarker\n : attrNameEndIndex >= 0\n ? (attrNames.push(attrName!),\n s.slice(0, attrNameEndIndex) +\n boundAttributeSuffix +\n s.slice(attrNameEndIndex)) +\n marker +\n end\n : s + marker + (attrNameEndIndex === -2 ? i : end);\n }\n\n const htmlResult: string | TrustedHTML =\n html +\n (strings[l] || '<?>') +\n (type === SVG_RESULT ? '</svg>' : type === MATHML_RESULT ? '</math>' : '');\n\n // Returned as an array for terseness\n return [trustFromTemplateString(strings, htmlResult), attrNames];\n};\n\n/** @internal */\nexport type {Template};\nclass Template {\n /** @internal */\n el!: HTMLTemplateElement;\n\n parts: Array<TemplatePart> = [];\n\n constructor(\n // This property needs to remain unminified.\n {strings, ['_$litType$']: type}: UncompiledTemplateResult,\n options?: RenderOptions\n ) {\n let node: Node | null;\n let nodeIndex = 0;\n let attrNameIndex = 0;\n const partCount = strings.length - 1;\n const parts = this.parts;\n\n // Create template element\n const [html, attrNames] = getTemplateHtml(strings, type);\n this.el = Template.createElement(html, options);\n walker.currentNode = this.el.content;\n\n // Re-parent SVG or MathML nodes into template root\n if (type === SVG_RESULT || type === MATHML_RESULT) {\n const wrapper = this.el.content.firstChild!;\n wrapper.replaceWith(...wrapper.childNodes);\n }\n\n // Walk the template to find binding markers and create TemplateParts\n while ((node = walker.nextNode()) !== null && parts.length < partCount) {\n if (node.nodeType === 1) {\n if (DEV_MODE) {\n const tag = (node as Element).localName;\n // Warn if `textarea` includes an expression and throw if `template`\n // does since these are not supported. We do this by checking\n // innerHTML for anything that looks like a marker. This catches\n // cases like bindings in textarea there markers turn into text nodes.\n if (\n /^(?:textarea|template)$/i!.test(tag) &&\n (node as Element).innerHTML.includes(marker)\n ) {\n const m =\n `Expressions are not supported inside \\`${tag}\\` ` +\n `elements. See https://lit.dev/msg/expression-in-${tag} for more ` +\n `information.`;\n if (tag === 'template') {\n throw new Error(m);\n } else issueWarning('', m);\n }\n }\n // TODO (justinfagnani): for attempted dynamic tag names, we don't\n // increment the bindingIndex, and it'll be off by 1 in the element\n // and off by two after it.\n if ((node as Element).hasAttributes()) {\n for (const name of (node as Element).getAttributeNames()) {\n if (name.endsWith(boundAttributeSuffix)) {\n const realName = attrNames[attrNameIndex++];\n const value = (node as Element).getAttribute(name)!;\n const statics = value.split(marker);\n const m = /([.?@])?(.*)/.exec(realName)!;\n parts.push({\n type: ATTRIBUTE_PART,\n index: nodeIndex,\n name: m[2],\n strings: statics,\n ctor:\n m[1] === '.'\n ? PropertyPart\n : m[1] === '?'\n ? BooleanAttributePart\n : m[1] === '@'\n ? EventPart\n : AttributePart,\n });\n (node as Element).removeAttribute(name);\n } else if (name.startsWith(marker)) {\n parts.push({\n type: ELEMENT_PART,\n index: nodeIndex,\n });\n (node as Element).removeAttribute(name);\n }\n }\n }\n // TODO (justinfagnani): benchmark the regex against testing for each\n // of the 3 raw text element names.\n if (rawTextElement.test((node as Element).tagName)) {\n // For raw text elements we need to split the text content on\n // markers, create a Text node for each segment, and create\n // a TemplatePart for each marker.\n const strings = (node as Element).textContent!.split(marker);\n const lastIndex = strings.length - 1;\n if (lastIndex > 0) {\n (node as Element).textContent = trustedTypes\n ? (trustedTypes.emptyScript as unknown as '')\n : '';\n // Generate a new text node for each literal section\n // These nodes are also used as the markers for child parts\n for (let i = 0; i < lastIndex; i++) {\n (node as Element).append(strings[i], createMarker());\n // Walk past the marker node we just added\n walker.nextNode();\n parts.push({type: CHILD_PART, index: ++nodeIndex});\n }\n // Note because this marker is added after the walker's current\n // node, it will be walked to in the outer loop (and ignored), so\n // we don't need to adjust nodeIndex here\n (node as Element).append(strings[lastIndex], createMarker());\n }\n }\n } else if (node.nodeType === 8) {\n const data = (node as Comment).data;\n if (data === markerMatch) {\n parts.push({type: CHILD_PART, index: nodeIndex});\n } else {\n let i = -1;\n while ((i = (node as Comment).data.indexOf(marker, i + 1)) !== -1) {\n // Comment node has a binding marker inside, make an inactive part\n // The binding won't work, but subsequent bindings will\n parts.push({type: COMMENT_PART, index: nodeIndex});\n // Move to the end of the match\n i += marker.length - 1;\n }\n }\n }\n nodeIndex++;\n }\n\n if (DEV_MODE) {\n // If there was a duplicate attribute on a tag, then when the tag is\n // parsed into an element the attribute gets de-duplicated. We can detect\n // this mismatch if we haven't precisely consumed every attribute name\n // when preparing the template. This works because `attrNames` is built\n // from the template string and `attrNameIndex` comes from processing the\n // resulting DOM.\n if (attrNames.length !== attrNameIndex) {\n throw new Error(\n `Detected duplicate attribute bindings. This occurs if your template ` +\n `has duplicate attributes on an element tag. For example ` +\n `\"<input ?disabled=\\${true} ?disabled=\\${false}>\" contains a ` +\n `duplicate \"disabled\" attribute. The error was detected in ` +\n `the following template: \\n` +\n '`' +\n strings.join('${...}') +\n '`'\n );\n }\n }\n\n // We could set walker.currentNode to another node here to prevent a memory\n // leak, but every time we prepare a template, we immediately render it\n // and re-use the walker in new TemplateInstance._clone().\n debugLogEvent &&\n debugLogEvent({\n kind: 'template prep',\n template: this,\n clonableTemplate: this.el,\n parts: this.parts,\n strings,\n });\n }\n\n // Overridden via `litHtmlPolyfillSupport` to provide platform support.\n /** @nocollapse */\n static createElement(html: TrustedHTML, _options?: RenderOptions) {\n const el = d.createElement('template');\n el.innerHTML = html as unknown as string;\n return el;\n }\n}\n\nexport interface Disconnectable {\n _$parent?: Disconnectable;\n _$disconnectableChildren?: Set<Disconnectable>;\n // Rather than hold connection state on instances, Disconnectables recursively\n // fetch the connection state from the RootPart they are connected in via\n // getters up the Disconnectable tree via _$parent references. This pushes the\n // cost of tracking the isConnected state to `AsyncDirectives`, and avoids\n // needing to pass all Disconnectables (parts, template instances, and\n // directives) their connection state each time it changes, which would be\n // costly for trees that have no AsyncDirectives.\n _$isConnected: boolean;\n}\n\nfunction resolveDirective(\n part: ChildPart | AttributePart | ElementPart,\n value: unknown,\n parent: DirectiveParent = part,\n attributeIndex?: number\n): unknown {\n // Bail early if the value is explicitly noChange. Note, this means any\n // nested directive is still attached and is not run.\n if (value === noChange) {\n return value;\n }\n let currentDirective =\n attributeIndex !== undefined\n ? (parent as AttributePart).__directives?.[attributeIndex]\n : (parent as ChildPart | ElementPart | Directive).__directive;\n const nextDirectiveConstructor = isPrimitive(value)\n ? undefined\n : // This property needs to remain unminified.\n (value as DirectiveResult)['_$litDirective$'];\n if (currentDirective?.constructor !== nextDirectiveConstructor) {\n // This property needs to remain unminified.\n currentDirective?.['_$notifyDirectiveConnectionChanged']?.(false);\n if (nextDirectiveConstructor === undefined) {\n currentDirective = undefined;\n } else {\n currentDirective = new nextDirectiveConstructor(part as PartInfo);\n currentDirective._$initialize(part, parent, attributeIndex);\n }\n if (attributeIndex !== undefined) {\n ((parent as AttributePart).__directives ??= [])[attributeIndex] =\n currentDirective;\n } else {\n (parent as ChildPart | Directive).__directive = currentDirective;\n }\n }\n if (currentDirective !== undefined) {\n value = resolveDirective(\n part,\n currentDirective._$resolve(part, (value as DirectiveResult).values),\n currentDirective,\n attributeIndex\n );\n }\n return value;\n}\n\nexport type {TemplateInstance};\n/**\n * An updateable instance of a Template. Holds references to the Parts used to\n * update the template instance.\n */\nclass TemplateInstance implements Disconnectable {\n _$template: Template;\n _$parts: Array<Part | undefined> = [];\n\n /** @internal */\n _$parent: ChildPart;\n /** @internal */\n _$disconnectableChildren?: Set<Disconnectable> = undefined;\n\n constructor(template: Template, parent: ChildPart) {\n this._$template = template;\n this._$parent = parent;\n }\n\n // Called by ChildPart parentNode getter\n get parentNode() {\n return this._$parent.parentNode;\n }\n\n // See comment in Disconnectable interface for why this is a getter\n get _$isConnected() {\n return this._$parent._$isConnected;\n }\n\n // This method is separate from the constructor because we need to return a\n // DocumentFragment and we don't want to hold onto it with an instance field.\n _clone(options: RenderOptions | undefined) {\n const {\n el: {content},\n parts: parts,\n } = this._$template;\n const fragment = (options?.creationScope ?? d).importNode(content, true);\n walker.currentNode = fragment;\n\n let node = walker.nextNode()!;\n let nodeIndex = 0;\n let partIndex = 0;\n let templatePart = parts[0];\n\n while (templatePart !== undefined) {\n if (nodeIndex === templatePart.index) {\n let part: Part | undefined;\n if (templatePart.type === CHILD_PART) {\n part = new ChildPart(\n node as HTMLElement,\n node.nextSibling,\n this,\n options\n );\n } else if (templatePart.type === ATTRIBUTE_PART) {\n part = new templatePart.ctor(\n node as HTMLElement,\n templatePart.name,\n templatePart.strings,\n this,\n options\n );\n } else if (templatePart.type === ELEMENT_PART) {\n part = new ElementPart(node as HTMLElement, this, options);\n }\n this._$parts.push(part);\n templatePart = parts[++partIndex];\n }\n if (nodeIndex !== templatePart?.index) {\n node = walker.nextNode()!;\n nodeIndex++;\n }\n }\n // We need to set the currentNode away from the cloned tree so that we\n // don't hold onto the tree even if the tree is detached and should be\n // freed.\n walker.currentNode = d;\n return fragment;\n }\n\n _update(values: Array<unknown>) {\n let i = 0;\n for (const part of this._$parts) {\n if (part !== undefined) {\n debugLogEvent &&\n debugLogEvent({\n kind: 'set part',\n part,\n value: values[i],\n valueIndex: i,\n values,\n templateInstance: this,\n });\n if ((part as AttributePart).strings !== undefined) {\n (part as AttributePart)._$setValue(values, part as AttributePart, i);\n // The number of values the part consumes is part.strings.length - 1\n // since values are in between template spans. We increment i by 1\n // later in the loop, so increment it by part.strings.length - 2 here\n i += (part as AttributePart).strings!.length - 2;\n } else {\n part._$setValue(values[i]);\n }\n }\n i++;\n }\n }\n}\n\n/*\n * Parts\n */\ntype AttributeTemplatePart = {\n readonly type: typeof ATTRIBUTE_PART;\n readonly index: number;\n readonly name: string;\n readonly ctor: typeof AttributePart;\n readonly strings: ReadonlyArray<string>;\n};\ntype ChildTemplatePart = {\n readonly type: typeof CHILD_PART;\n readonly index: number;\n};\ntype ElementTemplatePart = {\n readonly type: typeof ELEMENT_PART;\n readonly index: number;\n};\ntype CommentTemplatePart = {\n readonly type: typeof COMMENT_PART;\n readonly index: number;\n};\n\n/**\n * A TemplatePart represents a dynamic part in a template, before the template\n * is instantiated. When a template is instantiated Parts are created from\n * TemplateParts.\n */\ntype TemplatePart =\n | ChildTemplatePart\n | AttributeTemplatePart\n | ElementTemplatePart\n | CommentTemplatePart;\n\nexport type Part =\n | ChildPart\n | AttributePart\n | PropertyPart\n | BooleanAttributePart\n | ElementPart\n | EventPart;\n\nexport type {ChildPart};\nclass ChildPart implements Disconnectable {\n readonly type = CHILD_PART;\n readonly options: RenderOptions | undefined;\n _$committedValue: unknown = nothing;\n /** @internal */\n __directive?: Directive;\n /** @internal */\n _$startNode: ChildNode;\n /** @internal */\n _$endNode: ChildNode | null;\n private _textSanitizer: ValueSanitizer | undefined;\n /** @internal */\n _$parent: Disconnectable | undefined;\n /**\n * Connection state for RootParts only (i.e. ChildPart without _$parent\n * returned from top-level `render`). This field is unused otherwise. The\n * intention would be clearer if we made `RootPart` a subclass of `ChildPart`\n * with this field (and a different _$isConnected getter), but the subclass\n * caused a perf regression, possibly due to making call sites polymorphic.\n * @internal\n */\n __isConnected: boolean;\n\n // See comment in Disconnectable interface for why this is a getter\n get _$isConnected() {\n // ChildParts that are not at the root should always be created with a\n // parent; only RootChildNode's won't, so they return the local isConnected\n // state\n return this._$parent?._$isConnected ?? this.__isConnected;\n }\n\n // The following fields will be patched onto ChildParts when required by\n // AsyncDirective\n /** @internal */\n _$disconnectableChildren?: Set<Disconnectable> = undefined;\n /** @internal */\n _$notifyConnectionChanged?(\n isConnected: boolean,\n removeFromParent?: boolean,\n from?: number\n ): void;\n /** @internal */\n _$reparentDisconnectables?(parent: Disconnectable): void;\n\n constructor(\n startNode: ChildNode,\n endNode: ChildNode | null,\n parent: TemplateInstance | ChildPart | undefined,\n options: RenderOptions | undefined\n ) {\n this._$startNode = startNode;\n this._$endNode = endNode;\n this._$parent = parent;\n this.options = options;\n // Note __isConnected is only ever accessed on RootParts (i.e. when there is\n // no _$parent); the value on a non-root-part is \"don't care\", but checking\n // for parent would be more code\n this.__isConnected = options?.isConnected ?? true;\n if (ENABLE_EXTRA_SECURITY_HOOKS) {\n // Explicitly initialize for consistent class shape.\n this._textSanitizer = undefined;\n }\n }\n\n /**\n * The parent node into which the part renders its content.\n *\n * A ChildPart's content consists of a range of adjacent child nodes of\n * `.parentNode`, possibly bordered by 'marker nodes' (`.startNode` and\n * `.endNode`).\n *\n * - If both `.startNode` and `.endNode` are non-null, then the part's content\n * consists of all siblings between `.startNode` and `.endNode`, exclusively.\n *\n * - If `.startNode` is non-null but `.endNode` is null, then the part's\n * content consists of all siblings following `.startNode`, up to and\n * including the last child of `.parentNode`. If `.endNode` is non-null, then\n * `.startNode` will always be non-null.\n *\n * - If both `.endNode` and `.startNode` are null, then the part's content\n * consists of all child nodes of `.parentNode`.\n */\n get parentNode(): Node {\n let parentNode: Node = wrap(this._$startNode).parentNode!;\n const parent = this._$parent;\n if (\n parent !== undefined &&\n parentNode?.nodeType === 11 /* Node.DOCUMENT_FRAGMENT */\n ) {\n // If the parentNode is a DocumentFragment, it may be because the DOM is\n // still in the cloned fragment during initial render; if so, get the real\n // parentNode the part will be committed into by asking the parent.\n parentNode = (parent as ChildPart | TemplateInstance).parentNode;\n }\n return parentNode;\n }\n\n /**\n * The part's leading marker node, if any. See `.parentNode` for more\n * information.\n */\n get startNode(): Node | null {\n return this._$startNode;\n }\n\n /**\n * The part's trailing marker node, if any. See `.parentNode` for more\n * information.\n */\n get endNode(): Node | null {\n return this._$endNode;\n }\n\n _$setValue(value: unknown, directiveParent: DirectiveParent = this): void {\n if (DEV_MODE && this.parentNode === null) {\n throw new Error(\n `This \\`ChildPart\\` has no \\`parentNode\\` and therefore cannot accept a value. This likely means the element containing the part was manipulated in an unsupported way outside of Lit's control such that the part's marker nodes were ejected from DOM. For example, setting the element's \\`innerHTML\\` or \\`textContent\\` can do this.`\n );\n }\n value = resolveDirective(this, value, directiveParent);\n if (isPrimitive(value)) {\n // Non-rendering child values. It's important that these do not render\n // empty text nodes to avoid issues with preventing default <slot>\n // fallback content.\n if (value === nothing || value == null || value === '') {\n if (this._$committedValue !== nothing) {\n debugLogEvent &&\n debugLogEvent({\n kind: 'commit nothing to child',\n start: this._$startNode,\n end: this._$endNode,\n parent: this._$parent,\n options: this.options,\n });\n this._$clear();\n }\n this._$committedValue = nothing;\n } else if (value !== this._$committedValue && value !== noChange) {\n this._commitText(value);\n }\n // This property needs to remain unminified.\n } else if ((value as TemplateResult)['_$litType$'] !== undefined) {\n this._commitTemplateResult(value as TemplateResult);\n } else if ((value as Node).nodeType !== undefined) {\n if (DEV_MODE && this.options?.host === value) {\n this._commitText(\n `[probable mistake: rendered a template's host in itself ` +\n `(commonly caused by writing \\${this} in a template]`\n );\n console.warn(\n `Attempted to render the template host`,\n value,\n `inside itself. This is almost always a mistake, and in dev mode `,\n `we render some warning text. In production however, we'll `,\n `render it, which will usually result in an error, and sometimes `,\n `in the element disappearing from the DOM.`\n );\n return;\n }\n this._commitNode(value as Node);\n } else if (isIterable(value)) {\n this._commitIterable(value);\n } else {\n // Fallback, will render the string representation\n this._commitText(value);\n }\n }\n\n private _insert<T extends Node>(node: T) {\n return wrap(wrap(this._$startNode).parentNode!).insertBefore(\n node,\n this._$endNode\n );\n }\n\n private _commitNode(value: Node): void {\n if (this._$committedValue !== value) {\n this._$clear();\n if (\n ENABLE_EXTRA_SECURITY_HOOKS &&\n sanitizerFactoryInternal !== noopSanitizer\n ) {\n const parentNodeName = this._$startNode.parentNode?.nodeName;\n if (parentNodeName === 'STYLE' || parentNodeName === 'SCRIPT') {\n let message = 'Forbidden';\n if (DEV_MODE) {\n if (parentNodeName === 'STYLE') {\n message =\n `Lit does not support binding inside style nodes. ` +\n `This is a security risk, as style injection attacks can ` +\n `exfiltrate data and spoof UIs. ` +\n `Consider instead using css\\`...\\` literals ` +\n `to compose styles, and do dynamic styling with ` +\n `css custom properties, ::parts, <slot>s, ` +\n `and by mutating the DOM rather than stylesheets.`;\n } else {\n message =\n `Lit does not support binding inside script nodes. ` +\n `This is a security risk, as it could allow arbitrary ` +\n `code execution.`;\n }\n }\n throw new Error(message);\n }\n }\n debugLogEvent &&\n debugLogEvent({\n kind: 'commit node',\n start: this._$startNode,\n parent: this._$parent,\n value: value,\n options: this.options,\n });\n this._$committedValue = this._insert(value);\n }\n }\n\n private _commitText(value: unknown): void {\n // If the committed value is a primitive it means we called _commitText on\n // the previous render, and we know that this._$startNode.nextSibling is a\n // Text node. We can now just replace the text content (.data) of the node.\n if (\n this._$committedValue !== nothing &&\n isPrimitive(this._$committedValue)\n ) {\n const node = wrap(this._$startNode).nextSibling as Text;\n if (ENABLE_EXTRA_SECURITY_HOOKS) {\n if (this._textSanitizer === undefined) {\n this._textSanitizer = createSanitizer(node, 'data', 'property');\n }\n value = this._textSanitizer(value);\n }\n debugLogEvent &&\n debugLogEvent({\n kind: 'commit text',\n node,\n value,\n options: this.options,\n });\n (node as Text).data = value as string;\n } else {\n if (ENABLE_EXTRA_SECURITY_HOOKS) {\n const textNode = d.createTextNode('');\n this._commitNode(textNode);\n // When setting text content, for security purposes it matters a lot\n // what the parent is. For example, <style> and <script> need to be\n // handled with care, while <span> does not. So first we need to put a\n // text node into the document, then we can sanitize its content.\n if (this._textSanitizer === undefined) {\n this._textSanitizer = createSanitizer(textNode, 'data', 'property');\n }\n value = this._textSanitizer(value);\n debugLogEvent &&\n debugLogEvent({\n kind: 'commit text',\n node: textNode,\n value,\n options: this.options,\n });\n textNode.data = value as string;\n } else {\n this._commitNode(d.createTextNode(value as string));\n debugLogEvent &&\n debugLogEvent({\n kind: 'commit text',\n node: wrap(this._$startNode).nextSibling as Text,\n value,\n options: this.options,\n });\n }\n }\n this._$committedValue = value;\n }\n\n private _commitTemplateResult(\n result: TemplateResult | CompiledTemplateResult\n ): void {\n // This property needs to remain unminified.\n const {values, ['_$litType$']: type} = result;\n // If $litType$ is a number, result is a plain TemplateResult and we get\n // the template from the template cache. If not, result is a\n // CompiledTemplateResult and _$litType$ is a CompiledTemplate and we need\n // to create the <template> element the first time we see it.\n const template: Template | CompiledTemplate =\n typeof type === 'number'\n ? this._$getTemplate(result as UncompiledTemplateResult)\n : (type.el === undefined &&\n (type.el = Template.createElement(\n trustFromTemplateString(type.h, type.h[0]),\n this.options\n )),\n type);\n\n if ((this._$committedValue as TemplateInstance)?._$template === template) {\n debugLogEvent &&\n debugLogEvent({\n kind: 'template updating',\n template,\n instance: this._$committedValue as TemplateInstance,\n parts: (this._$committedValue as TemplateInstance)._$parts,\n options: this.options,\n values,\n });\n (this._$committedValue as TemplateInstance)._update(values);\n } else {\n const instance = new TemplateInstance(template as Template, this);\n const fragment = instance._clone(this.options);\n debugLogEvent &&\n debugLogEvent({\n kind: 'template instantiated',\n template,\n instance,\n parts: instance._$parts,\n options: this.options,\n fragment,\n values,\n });\n instance._update(values);\n debugLogEvent &&\n debugLogEvent({\n kind: 'template instantiated and updated',\n template,\n instance,\n parts: instance._$parts,\n options: this.options,\n fragment,\n values,\n });\n this._commitNode(fragment);\n this._$committedValue = instance;\n }\n }\n\n // Overridden via `litHtmlPolyfillSupport` to provide platform support.\n /** @internal */\n _$getTemplate(result: UncompiledTemplateResult) {\n let template = templateCache.get(result.strings);\n if (template === undefined) {\n templateCache.set(result.strings, (template = new Template(result)));\n }\n return template;\n }\n\n private _commitIterable(value: Iterable<unknown>): void {\n // For an Iterable, we create a new InstancePart per item, then set its\n // value to the item. This is a little bit of overhead for every item in\n // an Iterable, but it lets us recurse easily and efficiently update Arrays\n // of TemplateResults that will be commonly returned from expressions like:\n // array.map((i) => html`${i}`), by reusing existing TemplateInstances.\n\n // If value is an array, then the previous render was of an\n // iterable and value will contain the ChildParts from the previous\n // render. If value is not an array, clear this part and make a new\n // array for ChildParts.\n if (!isArray(this._$committedValue)) {\n this._$committedValue = [];\n this._$clear();\n }\n\n // Lets us keep track of how many items we stamped so we can clear leftover\n // items from a previous render\n const itemParts = this._$committedValue as ChildPart[];\n let partIndex = 0;\n let itemPart: ChildPart | undefined;\n\n for (const item of value) {\n if (partIndex === itemParts.length) {\n // If no existing part, create a new one\n // TODO (justinfagnani): test perf impact of always creating two parts\n // instead of sharing parts between nodes\n // https://github.com/lit/lit/issues/1266\n itemParts.push(\n (itemPart = new ChildPart(\n this._insert(createMarker()),\n this._insert(createMarker()),\n this,\n this.options\n ))\n );\n } else {\n // Reuse an existing part\n itemPart = itemParts[partIndex];\n }\n itemPart._$setValue(item);\n partIndex++;\n }\n\n if (partIndex < itemParts.length) {\n // itemParts always have end nodes\n this._$clear(\n itemPart && wrap(itemPart._$endNode!).nextSibling,\n partIndex\n );\n // Truncate the parts array so _value reflects the current state\n itemParts.length = partIndex;\n }\n }\n\n /**\n * Removes the nodes contained within this Part from the DOM.\n *\n * @param start Start node to clear from, for clearing a subset of the part's\n * DOM (used when truncating iterables)\n * @param from When `start` is specified, the index within the iterable from\n * which ChildParts are being removed, used for disconnecting directives\n * in those Parts.\n *\n * @internal\n */\n _$clear(\n start: ChildNode | null = wrap(this._$startNode).nextSibling,\n from?: number\n ) {\n this._$notifyConnectionChanged?.(false, true, from);\n while (start !== this._$endNode) {\n // The non-null assertion is safe because if _$startNode.nextSibling is\n // null, then _$endNode is also null, and we would not have entered this\n // loop.\n const n = wrap(start!).nextSibling;\n wrap(start!).remove();\n start = n;\n }\n }\n\n /**\n * Implementation of RootPart's `isConnected`. Note that this method\n * should only be called on `RootPart`s (the `ChildPart` returned from a\n * top-level `render()` call). It has no effect on non-root ChildParts.\n * @param isConnected Whether to set\n * @internal\n */\n setConnected(isConnected: boolean) {\n if (this._$parent === undefined) {\n this.__isConnected = isConnected;\n this._$notifyConnectionChanged?.(isConnected);\n } else if (DEV_MODE) {\n throw new Error(\n 'part.setConnected() may only be called on a ' +\n 'RootPart returned from render().'\n );\n }\n }\n}\n\n/**\n * A top-level `ChildPart` returned from `render` that manages the connected\n * state of `AsyncDirective`s created throughout the tree below it.\n */\nexport interface RootPart extends ChildPart {\n /**\n * Sets the connection state for `AsyncDirective`s contained within this root\n * ChildPart.\n *\n * lit-html does not automatically monitor the connectedness of DOM rendered;\n * as such, it is the responsibility of the caller to `render` to ensure that\n * `part.setConnected(false)` is called before the part object is potentially\n * discarded, to ensure that `AsyncDirective`s have a chance to dispose of\n * any resources being held. If a `RootPart` that was previously\n * disconnected is subsequently re-connected (and its `AsyncDirective`s should\n * re-connect), `setConnected(true)` should be called.\n *\n * @param isConnected Whether directives within this tree should be connected\n * or not\n */\n setConnected(isConnected: boolean): void;\n}\n\nexport type {AttributePart};\nclass AttributePart implements Disconnectable {\n readonly type:\n | typeof ATTRIBUTE_PART\n | typeof PROPERTY_PART\n | typeof BOOLEAN_ATTRIBUTE_PART\n | typeof EVENT_PART = ATTRIBUTE_PART;\n readonly element: HTMLElement;\n readonly name: string;\n readonly options: RenderOptions | undefined;\n\n /**\n * If this attribute part represents an interpolation, this contains the\n * static strings of the interpolation. For single-value, complete bindings,\n * this is undefined.\n */\n readonly strings?: ReadonlyArray<string>;\n /** @internal */\n _$committedValue: unknown | Array<unknown> = nothing;\n /** @internal */\n __directives?: Array<Directive | undefined>;\n /** @internal */\n _$parent: Disconnectable;\n /** @internal */\n _$disconnectableChildren?: Set<Disconnectable> = undefined;\n\n protected _sanitizer: ValueSanitizer | undefined;\n\n get tagName() {\n return this.element.tagName;\n }\n\n // See comment in Disconnectable interface for why this is a getter\n get _$isConnected() {\n return this._$parent._$isConnected;\n }\n\n constructor(\n element: HTMLElement,\n name: string,\n strings: ReadonlyArray<string>,\n parent: Disconnectable,\n options: RenderOptions | undefined\n ) {\n this.element = element;\n this.name = name;\n this._$parent = parent;\n this.options = options;\n if (strings.length > 2 || strings[0] !== '' || strings[1] !== '') {\n this._$committedValue = new Array(strings.length - 1).fill(new String());\n this.strings = strings;\n } else {\n this._$committedValue = nothing;\n }\n if (ENABLE_EXTRA_SECURITY_HOOKS) {\n this._sanitizer = undefined;\n }\n }\n\n /**\n * Sets the value of this part by resolving the value from possibly multiple\n * values and static strings and committing it to the DOM.\n * If this part is single-valued, `this._strings` will be undefined, and the\n * method will be called with a single value argument. If this part is\n * multi-value, `this._strings` will be defined, and the method is called\n * with the value array of the part's owning TemplateInstance, and an offset\n * into the value array from which the values should be read.\n * This method is overloaded this way to eliminate short-lived array slices\n * of the template instance values, and allow a fast-path for single-valued\n * parts.\n *\n * @param value The part value, or an array of values for multi-valued parts\n * @param valueIndex the index to start reading values from. `undefined` for\n * single-valued parts\n * @param noCommit causes the part to not commit its value to the DOM. Used\n * in hydration to prime attribute parts with their first-rendered value,\n * but not set the attribute, and in SSR to no-op the DOM operation and\n * capture the value for serialization.\n *\n * @internal\n */\n _$setValue(\n value: unknown | Array<unknown>,\n directiveParent: DirectiveParent = this,\n valueIndex?: number,\n noCommit?: boolean\n ) {\n const strings = this.strings;\n\n // Whether any of the values has changed, for dirty-checking\n let change = false;\n\n if (strings === undefined) {\n // Single-value binding case\n value = resolveDirective(this, value, directiveParent, 0);\n change =\n !isPrimitive(value) ||\n (value !== this._$committedValue && value !== noChange);\n if (change) {\n this._$committedValue = value;\n }\n } else {\n // Interpolation case\n const values = value as Array<unknown>;\n value = strings[0];\n\n let i, v;\n for (i = 0; i < strings.length - 1; i++) {\n v = resolveDirective(this, values[valueIndex! + i], directiveParent, i);\n\n if (v === noChange) {\n // If the user-provided value is `noChange`, use the previous value\n v = (this._$committedValue as Array<unknown>)[i];\n }\n change ||=\n !isPrimitive(v) || v !== (this._$committedValue as Array<unknown>)[i];\n if (v === nothing) {\n value = nothing;\n } else if (value !== nothing) {\n value += (v ?? '') + strings[i + 1];\n }\n // We always record each value, even if one is `nothing`, for future\n // change detection.\n (this._$committedValue as Array<unknown>)[i] = v;\n }\n }\n if (change && !noCommit) {\n this._commitValue(value);\n }\n }\n\n /** @internal */\n _commitValue(value: unknown) {\n if (value === nothing) {\n (wrap(this.element) as Element).removeAttribute(this.name);\n } else {\n if (ENABLE_EXTRA_SECURITY_HOOKS) {\n if (this._sanitizer === undefined) {\n this._sanitizer = sanitizerFactoryInternal(\n this.element,\n this.name,\n 'attribute'\n );\n }\n value = this._sanitizer(value ?? '');\n }\n debugLogEvent &&\n debugLogEvent({\n kind: 'commit attribute',\n element: this.element,\n name: this.name,\n value,\n options: this.options,\n });\n (wrap(this.element) as Element).setAttribute(\n this.name,\n (value ?? '') as string\n );\n }\n }\n}\n\nexport type {PropertyPart};\nclass PropertyPart extends AttributePart {\n override readonly type = PROPERTY_PART;\n\n /** @internal */\n override _commitValue(value: unknown) {\n if (ENABLE_EXTRA_SECURITY_HOOKS) {\n if (this._sanitizer === undefined) {\n this._sanitizer = sanitizerFactoryInternal(\n this.element,\n this.name,\n 'property'\n );\n }\n value = this._sanitizer(value);\n }\n debugLogEvent &&\n debugLogEvent({\n kind: 'commit property',\n element: this.element,\n name: this.name,\n value,\n options: this.options,\n });\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (this.element as any)[this.name] = value === nothing ? undefined : value;\n }\n}\n\nexport type {BooleanAttributePart};\nclass BooleanAttributePart extends AttributePart {\n override readonly type = BOOLEAN_ATTRIBUTE_PART;\n\n /** @internal */\n override _commitValue(value: unknown) {\n debugLogEvent &&\n debugLogEvent({\n kind: 'commit boolean attribute',\n element: this.element,\n name: this.name,\n value: !!(value && value !== nothing),\n options: this.options,\n });\n (wrap(this.element) as Element).toggleAttribute(\n this.name,\n !!value && value !== nothing\n );\n }\n}\n\ntype EventListenerWithOptions = EventListenerOrEventListenerObject &\n Partial<AddEventListenerOptions>;\n\n/**\n * An AttributePart that manages an event listener via add/removeEventListener.\n *\n * This part works by adding itself as the event listener on an element, then\n * delegating to the value passed to it. This reduces the number of calls to\n * add/removeEventListener if the listener changes frequently, such as when an\n * inline function is used as a listener.\n *\n * Because event options are passed when adding listeners, we must take case\n * to add and remove the part as a listener when the event options change.\n */\nexport type {EventPart};\nclass EventPart extends AttributePart {\n override readonly type = EVENT_PART;\n\n constructor(\n element: HTMLElement,\n name: string,\n strings: ReadonlyArray<string>,\n parent: Disconnectable,\n options: RenderOptions | undefined\n ) {\n super(element, name, strings, parent, options);\n\n if (DEV_MODE && this.strings !== undefined) {\n throw new Error(\n `A \\`<${element.localName}>\\` has a \\`@${name}=...\\` listener with ` +\n 'invalid content. Event listeners in templates must have exactly ' +\n 'one expression and no surrounding text.'\n );\n }\n }\n\n // EventPart does not use the base _$setValue/_resolveValue implementation\n // since the dirty checking is more complex\n /** @internal */\n override _$setValue(\n newListener: unknown,\n directiveParent: DirectiveParent = this\n ) {\n newListener =\n resolveDirective(this, newListener, directiveParent, 0) ?? nothing;\n if (newListener === noChange) {\n return;\n }\n const oldListener = this._$committedValue;\n\n // If the new value is nothing or any options change we have to remove the\n // part as a listener.\n const shouldRemoveListener =\n (newListener === nothing && oldListener !== nothing) ||\n (newListener as EventListenerWithOptions).capture !==\n (oldListener as EventListenerWithOptions).capture ||\n (newListener as EventListenerWithOptions).once !==\n (oldListener as EventListenerWithOptions).once ||\n (newListener as EventListenerWithOptions).passive !==\n (oldListener as EventListenerWithOptions).passive;\n\n // If the new value is not nothing and we removed the listener, we have\n // to add the part as a listener.\n const shouldAddListener =\n newListener !== nothing &&\n (oldListener === nothing || shouldRemoveListener);\n\n debugLogEvent &&\n debugLogEvent({\n kind: 'commit event listener',\n element: this.element,\n name: this.name,\n value: newListener,\n options: this.options,\n removeListener: shouldRemoveListener,\n addListener: shouldAddListener,\n oldListener,\n });\n if (shouldRemoveListener) {\n this.element.removeEventListener(\n this.name,\n this,\n oldListener as EventListenerWithOptions\n );\n }\n if (shouldAddListener) {\n this.element.addEventListener(\n this.name,\n this,\n newListener as EventListenerWithOptions\n );\n }\n this._$committedValue = newListener;\n }\n\n handleEvent(event: Event) {\n if (typeof this._$committedValue === 'function') {\n this._$committedValue.call(this.options?.host ?? this.element, event);\n } else {\n (this._$committedValue as EventListenerObject).handleEvent(event);\n }\n }\n}\n\nexport type {ElementPart};\nclass ElementPart implements Disconnectable {\n readonly type = ELEMENT_PART;\n\n /** @internal */\n __directive?: Directive;\n\n // This is to ensure that every Part has a _$committedValue\n _$committedValue: undefined;\n\n /** @internal */\n _$parent!: Disconnectable;\n\n /** @internal */\n _$disconnectableChildren?: Set<Disconnectable> = undefined;\n\n options: RenderOptions | undefined;\n\n constructor(\n public element: Element,\n parent: Disconnectable,\n options: RenderOptions | undefined\n ) {\n this._$parent = parent;\n this.options = options;\n }\n\n // See comment in Disconnectable interface for why this is a getter\n get _$isConnected() {\n return this._$parent._$isConnected;\n }\n\n _$setValue(value: unknown): void {\n debugLogEvent &&\n debugLogEvent({\n kind: 'commit to element binding',\n element: this.element,\n value,\n options: this.options,\n });\n resolveDirective(this, value);\n }\n}\n\n/**\n * END USERS SHOULD NOT RELY ON THIS OBJECT.\n *\n * Private exports for use by other Lit packages, not intended for use by\n * external users.\n *\n * We currently do not make a mangled rollup build of the lit-ssr code. In order\n * to keep a number of (otherwise private) top-level exports mangled in the\n * client side code, we export a _$LH object containing those members (or\n * helper methods for accessing private fields of those members), and then\n * re-export them for use in lit-ssr. This keeps lit-ssr agnostic to whether the\n * client-side code is being used in `dev` mode or `prod` mode.\n *\n * This has a unique name, to disambiguate it from private exports in\n * lit-element, which re-exports all of lit-html.\n *\n * @private\n */\nexport const _$LH = {\n // Used in lit-ssr\n _boundAttributeSuffix: boundAttributeSuffix,\n _marker: marker,\n _markerMatch: markerMatch,\n _HTML_RESULT: HTML_RESULT,\n _getTemplateHtml: getTemplateHtml,\n // Used in tests and private-ssr-support\n _TemplateInstance: TemplateInstance,\n _isIterable: isIterable,\n _resolveDirective: resolveDirective,\n _ChildPart: ChildPart,\n _AttributePart: AttributePart,\n _BooleanAttributePart: BooleanAttributePart,\n _EventPart: EventPart,\n _PropertyPart: PropertyPart,\n _ElementPart: ElementPart,\n};\n\n// Apply polyfills if available\nconst polyfillSupport = DEV_MODE\n ? global.litHtmlPolyfillSupportDevMode\n : global.litHtmlPolyfillSupport;\npolyfillSupport?.(Template, ChildPart);\n\n// IMPORTANT: do not change the property name or the assignment expression.\n// This line will be used in regexes to search for lit-html usage.\n(global.litHtmlVersions ??= []).push('3.3.1');\nif (DEV_MODE && global.litHtmlVersions.length > 1) {\n queueMicrotask(() => {\n issueWarning!(\n 'multiple-versions',\n `Multiple versions of Lit loaded. ` +\n `Loading multiple versions is not recommended.`\n );\n });\n}\n\n/**\n * Renders a value, usually a lit-html TemplateResult, to the container.\n *\n * This example renders the text \"Hello, Zoe!\" inside a paragraph tag, appending\n * it to the container `document.body`.\n *\n * ```js\n * import {html, render} from 'lit';\n *\n * const name = \"Zoe\";\n * render(html`<p>Hello, ${name}!</p>`, document.body);\n * ```\n *\n * @param value Any [renderable\n * value](https://lit.dev/docs/templates/expressions/#child-expressions),\n * typically a {@linkcode TemplateResult} created by evaluating a template tag\n * like {@linkcode html} or {@linkcode svg}.\n * @param container A DOM container to render to. The first render will append\n * the rendered value to the container, and subsequent renders will\n * efficiently update the rendered value if the same result type was\n * previously rendered there.\n * @param options See {@linkcode RenderOptions} for options documentation.\n * @see\n * {@link https://lit.dev/docs/libraries/standalone-templates/#rendering-lit-html-templates| Rendering Lit HTML Templates}\n */\nexport const render = (\n value: unknown,\n container: HTMLElement | DocumentFragment,\n options?: RenderOptions\n): RootPart => {\n if (DEV_MODE && container == null) {\n // Give a clearer error message than\n // Uncaught TypeError: Cannot read properties of null (reading\n // '_$litPart$')\n // which reads like an internal Lit error.\n throw new TypeError(`The container to render into may not be ${container}`);\n }\n const renderId = DEV_MODE ? debugLogRenderId++ : 0;\n const partOwnerNode = options?.renderBefore ?? container;\n // This property needs to remain unminified.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let part: ChildPart = (partOwnerNode as any)['_$litPart$'];\n debugLogEvent &&\n debugLogEvent({\n kind: 'begin render',\n id: renderId,\n value,\n container,\n options,\n part,\n });\n if (part === undefined) {\n const endNode = options?.renderBefore ?? null;\n // This property needs to remain unminified.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (partOwnerNode as any)['_$litPart$'] = part = new ChildPart(\n container.insertBefore(createMarker(), endNode),\n endNode,\n undefined,\n options ?? {}\n );\n }\n part._$setValue(value);\n debugLogEvent &&\n debugLogEvent({\n kind: 'end render',\n id: renderId,\n value,\n container,\n options,\n part,\n });\n return part as RootPart;\n};\n\nif (ENABLE_EXTRA_SECURITY_HOOKS) {\n render.setSanitizer = setSanitizer;\n render.createSanitizer = createSanitizer;\n if (DEV_MODE) {\n render._testOnlyClearSanitizerFactoryDoNotCallOrElse =\n _testOnlyClearSanitizerFactoryDoNotCallOrElse;\n }\n}\n", "/**\n * Shared sort comparators for issues lists.\n * Centralizes sorting so views and stores stay consistent.\n */\n\n/**\n * @typedef {{ id: string, title?: string, status?: 'open'|'in_progress'|'closed', priority?: number, issue_type?: string, created_at?: number, updated_at?: number, closed_at?: number }} IssueLite\n */\n\n/**\n * Compare by priority asc, then created_at asc, then id asc.\n *\n * @param {IssueLite} a\n * @param {IssueLite} b\n */\nexport function cmpPriorityThenCreated(a, b) {\n const pa = a.priority ?? 2;\n const pb = b.priority ?? 2;\n if (pa !== pb) {\n return pa - pb;\n }\n const ca = a.created_at ?? 0;\n const cb = b.created_at ?? 0;\n if (ca !== cb) {\n return ca < cb ? -1 : 1;\n }\n const ida = a.id;\n const idb = b.id;\n return ida < idb ? -1 : ida > idb ? 1 : 0;\n}\n\n/**\n * Compare by closed_at desc, then id asc for stability.\n *\n * @param {IssueLite} a\n * @param {IssueLite} b\n */\nexport function cmpClosedDesc(a, b) {\n const ca = a.closed_at ?? 0;\n const cb = b.closed_at ?? 0;\n if (ca !== cb) {\n return ca < cb ? 1 : -1;\n }\n const ida = a?.id;\n const idb = b?.id;\n return ida < idb ? -1 : ida > idb ? 1 : 0;\n}\n", "/**\n * List selectors utility: compose subscription membership with issues entities\n * and apply view-specific sorting. Provides a lightweight `subscribe` that\n * triggers once per issues envelope to let views re-render.\n */\n/**\n * @typedef {{ id: string, title?: string, status?: 'open'|'in_progress'|'closed', priority?: number, issue_type?: string, created_at?: number, updated_at?: number, closed_at?: number }} IssueLite\n */\nimport { cmpClosedDesc, cmpPriorityThenCreated } from './sort.js';\n\n/**\n * Factory for list selectors.\n *\n * Source of truth is per-subscription stores providing snapshots for a given\n * client id. Central issues store fallback has been removed.\n *\n * @param {{ snapshotFor?: (client_id: string) => IssueLite[], subscribe?: (fn: () => void) => () => void }} [issue_stores]\n */\nexport function createListSelectors(issue_stores = undefined) {\n // Sorting comparators are centralized in app/data/sort.js\n\n /**\n * Get entities for a subscription id with Issues List sort (priority asc \u2192 created asc).\n *\n * @param {string} client_id\n * @returns {IssueLite[]}\n */\n function selectIssuesFor(client_id) {\n if (!issue_stores || typeof issue_stores.snapshotFor !== 'function') {\n return [];\n }\n return issue_stores\n .snapshotFor(client_id)\n .slice()\n .sort(cmpPriorityThenCreated);\n }\n\n /**\n * Get entities for a Board column with column-specific sort.\n *\n * @param {string} client_id\n * @param {'ready'|'blocked'|'in_progress'|'closed'} mode\n * @returns {IssueLite[]}\n */\n function selectBoardColumn(client_id, mode) {\n const arr =\n issue_stores && issue_stores.snapshotFor\n ? issue_stores.snapshotFor(client_id).slice()\n : [];\n if (mode === 'in_progress') {\n arr.sort(cmpPriorityThenCreated);\n } else if (mode === 'closed') {\n arr.sort(cmpClosedDesc);\n } else {\n // ready/blocked share the same sort\n arr.sort(cmpPriorityThenCreated);\n }\n return arr;\n }\n\n /**\n * Get children for an epic subscribed as client id `epic:${id}`.\n * Sorted as Issues List (priority asc \u2192 created asc).\n *\n * @param {string} epic_id\n * @returns {IssueLite[]}\n */\n function selectEpicChildren(epic_id) {\n if (!issue_stores || typeof issue_stores.snapshotFor !== 'function') {\n return [];\n }\n // Epic detail subscription uses client id `detail:<id>` and contains the\n // epic entity with a `dependents` array. Render children from that list.\n const arr = /** @type {any[]} */ (\n issue_stores.snapshotFor(`detail:${epic_id}`) || []\n );\n const epic = arr.find((it) => String(it?.id || '') === String(epic_id));\n const dependents = Array.isArray(epic?.dependents) ? epic.dependents : [];\n return /** @type {IssueLite[]} */ (\n dependents.slice().sort(cmpPriorityThenCreated)\n );\n }\n\n /**\n * Subscribe for re-render; triggers once per issues envelope.\n *\n * @param {() => void} fn\n * @returns {() => void}\n */\n function subscribe(fn) {\n if (issue_stores && typeof issue_stores.subscribe === 'function') {\n return issue_stores.subscribe(fn);\n }\n return () => {};\n }\n\n return {\n selectIssuesFor,\n selectBoardColumn,\n selectEpicChildren,\n subscribe\n };\n}\n", "/**\n * Debug logger helper for the browser app.\n */\nimport createDebug from 'debug';\n\n/**\n * Create a namespaced logger.\n *\n * @param {string} ns - Module namespace suffix (e.g., 'ws', 'views:list').\n */\nexport function debug(ns) {\n return createDebug(`beads-ui:${ns}`);\n}\n", "/**\n * @import { MessageType } from '../protocol.js'\n */\nimport { debug } from '../utils/logging.js';\n\n/**\n * Data layer: typed wrappers around the ws transport for mutations and\n * single-issue fetch. List reads have been removed in favor of push-only\n * stores and selectors (see docs/adr/001-push-only-lists.md).\n *\n * @param {(type: MessageType, payload?: unknown) => Promise<unknown>} transport - Request/response function.\n * @returns {{ updateIssue: (input: { id: string, title?: string, acceptance?: string, notes?: string, design?: string, status?: 'open'|'in_progress'|'closed', priority?: number, assignee?: string }) => Promise<unknown> }}\n */\nexport function createDataLayer(transport) {\n const log = debug('data');\n /**\n * Update issue fields by dispatching specific mutations.\n * Supported fields: title, acceptance, notes, design, status, priority, assignee.\n * Returns the updated issue on success.\n *\n * @param {{ id: string, title?: string, acceptance?: string, notes?: string, design?: string, status?: 'open'|'in_progress'|'closed', priority?: number, assignee?: string }} input\n * @returns {Promise<unknown>}\n */\n async function updateIssue(input) {\n const { id } = input;\n\n log('updateIssue %s %o', id, Object.keys(input));\n\n /** @type {unknown} */\n let last = null;\n if (typeof input.title === 'string') {\n last = await transport('edit-text', {\n id,\n field: 'title',\n value: input.title\n });\n }\n if (typeof input.acceptance === 'string') {\n last = await transport('edit-text', {\n id,\n field: 'acceptance',\n value: input.acceptance\n });\n }\n if (typeof input.notes === 'string') {\n last = await transport('edit-text', {\n id,\n field: 'notes',\n value: input.notes\n });\n }\n if (typeof input.design === 'string') {\n last = await transport('edit-text', {\n id,\n field: 'design',\n value: input.design\n });\n }\n if (typeof input.status === 'string') {\n last = await transport('update-status', {\n id,\n status: input.status\n });\n }\n if (typeof input.priority === 'number') {\n last = await transport('update-priority', {\n id,\n priority: input.priority\n });\n }\n // type updates are not supported via UI\n if (typeof input.assignee === 'string') {\n last = await transport('update-assignee', {\n id,\n assignee: input.assignee\n });\n }\n log('updateIssue done %s', id);\n return last;\n }\n\n return {\n updateIssue\n };\n}\n", "/**\n * @import { SubscriptionIssueStore, SubscriptionIssueStoreOptions } from '../../types/subscription-issue-store.js'\n */\nimport { debug } from '../utils/logging.js';\nimport { cmpPriorityThenCreated } from './sort.js';\n\n/**\n * Per-subscription issue store. Holds full Issue objects and exposes a\n * deterministic, read-only snapshot for rendering. Applies snapshot/upsert/\n * delete messages in revision order and preserves object identity per id.\n */\n\n/**\n * Create a SubscriptionIssueStore for a given subscription id.\n *\n * @param {string} id\n * @param {SubscriptionIssueStoreOptions} [options]\n * @returns {SubscriptionIssueStore}\n */\nexport function createSubscriptionIssueStore(id, options = {}) {\n const log = debug(`issue-store:${id}`);\n /** @type {Map<string, any>} */\n const items_by_id = new Map();\n /** @type {any[]} */\n let ordered = [];\n /** @type {number} */\n let last_revision = 0;\n /** @type {Set<() => void>} */\n const listeners = new Set();\n /** @type {boolean} */\n let is_disposed = false;\n /** @type {(a:any,b:any)=>number} */\n const sort = options.sort || cmpPriorityThenCreated;\n\n function emit() {\n for (const fn of Array.from(listeners)) {\n try {\n fn();\n } catch {\n // ignore listener errors\n }\n }\n }\n\n function rebuildOrdered() {\n ordered = Array.from(items_by_id.values()).sort(sort);\n }\n\n /**\n * Apply snapshot/upsert/delete in revision order. Snapshots reset state.\n * - Ignore messages with revision <= last_revision (except snapshot which resets first).\n * - Preserve object identity when updating an existing item by mutating\n * fields in place rather than replacing the object reference.\n *\n * @param {{ type: 'snapshot'|'upsert'|'delete', id: string, revision: number, issues?: any[], issue?: any, issue_id?: string }} msg\n */\n function applyPush(msg) {\n if (is_disposed) {\n return;\n }\n if (!msg || msg.id !== id) {\n return;\n }\n const rev = Number(msg.revision) || 0;\n log('apply %s rev=%d', msg.type, rev);\n // Ignore stale messages for all types, including snapshots\n if (rev <= last_revision && msg.type !== 'snapshot') {\n return; // stale or duplicate non-snapshot\n }\n if (msg.type === 'snapshot') {\n if (rev <= last_revision) {\n return; // ignore stale snapshot\n }\n items_by_id.clear();\n const items = Array.isArray(msg.issues) ? msg.issues : [];\n for (const it of items) {\n if (it && typeof it.id === 'string' && it.id.length > 0) {\n items_by_id.set(it.id, it);\n }\n }\n rebuildOrdered();\n last_revision = rev;\n emit();\n return;\n }\n if (msg.type === 'upsert') {\n const it = msg.issue;\n if (it && typeof it.id === 'string' && it.id.length > 0) {\n const existing = items_by_id.get(it.id);\n if (!existing) {\n items_by_id.set(it.id, it);\n } else {\n // Guard with updated_at; prefer newer\n const prev_ts = Number.isFinite(existing.updated_at)\n ? /** @type {number} */ (existing.updated_at)\n : 0;\n const next_ts = Number.isFinite(it.updated_at)\n ? /** @type {number} */ (it.updated_at)\n : 0;\n if (prev_ts <= next_ts) {\n // Mutate existing object to preserve reference\n for (const k of Object.keys(existing)) {\n if (!(k in it)) {\n // remove keys that disappeared to avoid stale fields\n delete existing[k];\n }\n }\n for (const [k, v] of Object.entries(it)) {\n // @ts-ignore - dynamic assignment\n existing[k] = v;\n }\n } else {\n // stale by timestamp; ignore\n }\n }\n rebuildOrdered();\n }\n last_revision = rev;\n emit();\n } else if (msg.type === 'delete') {\n const rid = String(msg.issue_id || '');\n if (rid) {\n items_by_id.delete(rid);\n rebuildOrdered();\n }\n last_revision = rev;\n emit();\n }\n }\n\n return {\n id,\n /**\n * @param {() => void} fn\n */\n subscribe(fn) {\n listeners.add(fn);\n return () => {\n listeners.delete(fn);\n };\n },\n applyPush,\n snapshot() {\n // Return as read-only view; callers must not mutate\n return ordered;\n },\n size() {\n return items_by_id.size;\n },\n /**\n * @param {string} xid\n */\n getById(xid) {\n return items_by_id.get(xid);\n },\n dispose() {\n is_disposed = true;\n items_by_id.clear();\n ordered = [];\n listeners.clear();\n last_revision = 0;\n }\n };\n}\n", "/**\n * @import { MessageType } from '../protocol.js'\n */\nimport { debug } from '../utils/logging.js';\n\n/**\n * Client-side list subscription store.\n *\n * Maintains per-subscription state keyed by client-provided `id`.\n * Applies server `list-delta` events per subscription key and exposes simple\n * selectors for rendering.\n */\n\n/**\n * @typedef {{ type: string, params?: Record<string, string|number|boolean> }} SubscriptionSpec\n */\n\n/**\n * Generate a stable subscription key string from a spec.\n * Mirrors server `keyOf` implementation (sorted params, URLSearchParams).\n *\n * @param {SubscriptionSpec} spec\n * @returns {string}\n */\nexport function subKeyOf(spec) {\n const type = String(spec.type || '').trim();\n /** @type {Record<string, string>} */\n const flat = {};\n if (spec.params && typeof spec.params === 'object') {\n const keys = Object.keys(spec.params).sort();\n for (const k of keys) {\n const v = spec.params[k];\n flat[k] = String(v);\n }\n }\n const enc = new URLSearchParams(flat).toString();\n return enc.length > 0 ? `${type}?${enc}` : type;\n}\n\n/**\n * Create a list subscription store.\n *\n * Wiring:\n * - Use `subscribeList` to register a subscription and send the request.\n *\n * Selectors are synchronous and return derived state by client id.\n *\n * @param {(type: MessageType, payload?: unknown) => Promise<unknown>} send - ws send.\n */\nexport function createSubscriptionStore(send) {\n const log = debug('subs');\n /** @type {Map<string, { key: string, itemsById: Map<string, true> }>} */\n const subs_by_id = new Map();\n /** @type {Map<string, Set<string>>} */\n const ids_by_key = new Map();\n\n /**\n * Apply a delta to all client ids mapped to a given key.\n *\n * @param {string} key\n * @param {{ added: string[], updated: string[], removed: string[] }} delta\n */\n function applyDelta(key, delta) {\n log(\n 'applyDelta %s +%d ~%d -%d',\n key,\n (delta.added || []).length,\n (delta.updated || []).length,\n (delta.removed || []).length\n );\n const id_set = ids_by_key.get(key);\n if (!id_set || id_set.size === 0) {\n return;\n }\n const added = Array.isArray(delta.added) ? delta.added : [];\n const updated = Array.isArray(delta.updated) ? delta.updated : [];\n const removed = Array.isArray(delta.removed) ? delta.removed : [];\n\n for (const client_id of Array.from(id_set)) {\n const entry = subs_by_id.get(client_id);\n if (!entry) {\n continue;\n }\n const items = entry.itemsById;\n for (const id of added) {\n if (typeof id === 'string' && id.length > 0) {\n items.set(id, true);\n }\n }\n for (const id of updated) {\n if (typeof id === 'string' && id.length > 0) {\n items.set(id, true);\n }\n }\n for (const id of removed) {\n if (typeof id === 'string' && id.length > 0) {\n items.delete(id);\n }\n }\n }\n }\n\n /**\n * Subscribe to a list spec with a client-provided id.\n * Returns an unsubscribe function.\n * Creates an empty items store immediately; server will publish deltas.\n *\n * @param {string} client_id\n * @param {SubscriptionSpec} spec\n * @returns {Promise<() => Promise<void>>}\n */\n async function subscribeList(client_id, spec) {\n const key = subKeyOf(spec);\n log('subscribe %s key=%s', client_id, key);\n // Initialize local entry immediately to capture early deltas\n if (!subs_by_id.has(client_id)) {\n subs_by_id.set(client_id, { key, itemsById: new Map() });\n } else {\n // Update key mapping if client id is reused for a different spec\n const prev = subs_by_id.get(client_id);\n if (prev && prev.key !== key) {\n const prev_ids = ids_by_key.get(prev.key);\n if (prev_ids) {\n prev_ids.delete(client_id);\n if (prev_ids.size === 0) {\n ids_by_key.delete(prev.key);\n }\n }\n subs_by_id.set(client_id, { key, itemsById: new Map() });\n }\n }\n if (!ids_by_key.has(key)) {\n ids_by_key.set(key, new Set());\n }\n const set = ids_by_key.get(key);\n if (set) {\n set.add(client_id);\n }\n try {\n await send('subscribe-list', {\n id: client_id,\n type: spec.type,\n params: spec.params\n });\n } catch (err) {\n const entry = subs_by_id.get(client_id) || null;\n if (entry) {\n const subscribers = ids_by_key.get(entry.key);\n if (subscribers) {\n subscribers.delete(client_id);\n if (subscribers.size === 0) {\n ids_by_key.delete(entry.key);\n }\n }\n }\n subs_by_id.delete(client_id);\n throw err;\n }\n\n return async () => {\n log('unsubscribe %s key=%s', client_id, key);\n try {\n await send('unsubscribe-list', { id: client_id });\n } catch {\n // ignore transport errors on unsubscribe\n }\n // Cleanup local mappings\n const entry = subs_by_id.get(client_id) || null;\n if (entry) {\n const s = ids_by_key.get(entry.key);\n if (s) {\n s.delete(client_id);\n if (s.size === 0) {\n ids_by_key.delete(entry.key);\n }\n }\n }\n subs_by_id.delete(client_id);\n };\n }\n\n /**\n * Selectors by client id.\n */\n const selectors = {\n /**\n * Get an array of item ids for a subscription.\n *\n * @param {string} client_id\n * @returns {string[]}\n */\n getIds(client_id) {\n const entry = subs_by_id.get(client_id);\n if (!entry) {\n return [];\n }\n return Array.from(entry.itemsById.keys());\n },\n /**\n * Check if an id exists in a subscription.\n *\n * @param {string} client_id\n * @param {string} id\n * @returns {boolean}\n */\n has(client_id, id) {\n const entry = subs_by_id.get(client_id);\n if (!entry) {\n return false;\n }\n return entry.itemsById.has(id);\n },\n /**\n * Count items for a subscription.\n *\n * @param {string} client_id\n * @returns {number}\n */\n count(client_id) {\n const entry = subs_by_id.get(client_id);\n return entry ? entry.itemsById.size : 0;\n },\n /**\n * Return a shallow object copy `{ [id]: true }` for rendering helpers.\n *\n * @param {string} client_id\n * @returns {Record<string, true>}\n */\n getItemsById(client_id) {\n const entry = subs_by_id.get(client_id);\n /** @type {Record<string, true>} */\n const out = {};\n if (!entry) {\n return out;\n }\n for (const id of entry.itemsById.keys()) {\n out[id] = true;\n }\n return out;\n }\n };\n\n return {\n subscribeList,\n // test/diagnostics helpers\n _applyDelta: applyDelta,\n _subKeyOf: subKeyOf,\n selectors\n };\n}\n", "/**\n * @import { SubscriptionIssueStoreOptions } from '../../types/subscription-issue-store.js'\n * @import { IssueLite } from './list-selectors.js'\n */\nimport { debug } from '../utils/logging.js';\nimport { createSubscriptionIssueStore } from './subscription-issue-store.js';\nimport { subKeyOf } from './subscriptions-store.js';\n\n/**\n * Registry managing per-subscription issue stores. Stores receive full-issue\n * push envelopes (snapshot/upsert/delete) per subscription id and expose\n * read-only snapshots for rendering.\n */\nexport function createSubscriptionIssueStores() {\n const log = debug('issue-stores');\n /** @type {Map<string, ReturnType<typeof createSubscriptionIssueStore>>} */\n const stores_by_id = new Map();\n /** @type {Map<string, string>} */\n const key_by_id = new Map();\n /** @type {Set<() => void>} */\n const listeners = new Set();\n /** @type {Map<string, () => void>} */\n const store_unsubs = new Map();\n\n function emit() {\n for (const fn of Array.from(listeners)) {\n try {\n fn();\n } catch {\n // ignore\n }\n }\n }\n\n /**\n * Ensure a store exists for client_id and attach a listener that fans out\n * store-level updates to global listeners.\n *\n * @param {string} client_id\n * @param {{ type: string, params?: Record<string, string|number|boolean> }} [spec]\n * @param {SubscriptionIssueStoreOptions} [options]\n */\n function register(client_id, spec, options) {\n const next_key = spec ? subKeyOf(spec) : '';\n const prev_key = key_by_id.get(client_id) || '';\n const has_store = stores_by_id.has(client_id);\n log('register %s key=%s (prev=%s)', client_id, next_key, prev_key);\n // If the subscription spec changed for an existing client id, replace the\n // underlying store to reset revision state and avoid ignoring a fresh\n // snapshot with a lower revision (different server list).\n if (has_store && prev_key && next_key && prev_key !== next_key) {\n const prev_store = stores_by_id.get(client_id);\n if (prev_store) {\n try {\n prev_store.dispose();\n } catch {\n // ignore\n }\n }\n const off_prev = store_unsubs.get(client_id);\n if (off_prev) {\n try {\n off_prev();\n } catch {\n // ignore\n }\n store_unsubs.delete(client_id);\n }\n const new_store = createSubscriptionIssueStore(client_id, options);\n stores_by_id.set(client_id, new_store);\n const off_new = new_store.subscribe(() => emit());\n store_unsubs.set(client_id, off_new);\n } else if (!has_store) {\n const store = createSubscriptionIssueStore(client_id, options);\n stores_by_id.set(client_id, store);\n // Fan out per-store events to global subscribers\n const off = store.subscribe(() => emit());\n store_unsubs.set(client_id, off);\n }\n key_by_id.set(client_id, next_key);\n return () => unregister(client_id);\n }\n\n /**\n * @param {string} client_id\n */\n function unregister(client_id) {\n log('unregister %s', client_id);\n key_by_id.delete(client_id);\n const store = stores_by_id.get(client_id);\n if (store) {\n store.dispose();\n stores_by_id.delete(client_id);\n }\n const off = store_unsubs.get(client_id);\n if (off) {\n try {\n off();\n } catch {\n // ignore\n }\n store_unsubs.delete(client_id);\n }\n }\n\n return {\n register,\n unregister,\n /**\n * @param {string} client_id\n */\n getStore(client_id) {\n return stores_by_id.get(client_id) || null;\n },\n /**\n * @param {string} client_id\n * @returns {IssueLite[]}\n */\n snapshotFor(client_id) {\n const s = stores_by_id.get(client_id);\n return s ? /** @type {IssueLite[]} */ (s.snapshot().slice()) : [];\n },\n /**\n * @param {() => void} fn\n */\n subscribe(fn) {\n listeners.add(fn);\n return () => listeners.delete(fn);\n }\n // No recompute helpers in vNext; stores are updated directly via push\n };\n}\n", "/**\n * Build a canonical issue hash that retains the view.\n *\n * @param {'issues'|'epics'|'board'} view\n * @param {string} id\n */\nexport function issueHashFor(view, id) {\n const v = view === 'epics' || view === 'board' ? view : 'issues';\n return `#/${v}?issue=${encodeURIComponent(id)}`;\n}\n", "import { issueHashFor } from './utils/issue-url.js';\nimport { debug } from './utils/logging.js';\n\n/**\n * Hash-based router for tabs (issues/epics/board) and deep-linked issue ids.\n */\n\n/**\n * Parse an application hash and extract the selected issue id.\n * Supports canonical form \"#/(issues|epics|board)?issue=<id>\" and legacy\n * \"#/issue/<id>\" which we will rewrite to the canonical form.\n *\n * @param {string} hash\n * @returns {string | null}\n */\nexport function parseHash(hash) {\n const h = String(hash || '');\n // Extract the fragment sans leading '#'\n const frag = h.startsWith('#') ? h.slice(1) : h;\n const qIndex = frag.indexOf('?');\n const query = qIndex >= 0 ? frag.slice(qIndex + 1) : '';\n if (query) {\n const params = new URLSearchParams(query);\n const id = params.get('issue');\n if (id) {\n return decodeURIComponent(id);\n }\n }\n // Legacy pattern: #/issue/<id>\n const m = /^\\/issue\\/([^\\s?#]+)/.exec(frag);\n return m && m[1] ? decodeURIComponent(m[1]) : null;\n}\n\n/**\n * Parse the current view from hash.\n *\n * @param {string} hash\n * @returns {'issues'|'epics'|'board'}\n */\nexport function parseView(hash) {\n const h = String(hash || '');\n if (/^#\\/epics(\\b|\\/|$)/.test(h)) {\n return 'epics';\n }\n if (/^#\\/board(\\b|\\/|$)/.test(h)) {\n return 'board';\n }\n // Default to issues (also covers #/issues and unknown/empty)\n return 'issues';\n}\n\n/**\n * @param {{ getState: () => any, setState: (patch: any) => void }} store\n */\nexport function createHashRouter(store) {\n const log = debug('router');\n /** @type {(ev?: HashChangeEvent) => any} */\n const onHashChange = () => {\n const hash = window.location.hash || '';\n // Rewrite legacy #/issue/<id> to canonical #/issues?issue=<id>\n const legacyMatch = /^#\\/issue\\/([^\\s?#]+)/.exec(hash);\n if (legacyMatch && legacyMatch[1]) {\n const id = decodeURIComponent(legacyMatch[1]);\n // Update state immediately for consumers expecting sync selection\n store.setState({ selected_id: id, view: 'issues' });\n const next = `#/issues?issue=${encodeURIComponent(id)}`;\n if (window.location.hash !== next) {\n window.location.hash = next;\n return; // will trigger handler again\n }\n }\n const id = parseHash(hash);\n const view = parseView(hash);\n log('hash change \u2192 view=%s id=%s', view, id);\n store.setState({ selected_id: id, view });\n };\n\n return {\n start() {\n window.addEventListener('hashchange', onHashChange);\n onHashChange();\n },\n stop() {\n window.removeEventListener('hashchange', onHashChange);\n },\n /**\n * @param {string} id\n */\n gotoIssue(id) {\n // Keep current view in hash and append issue param via helper\n const s = store.getState ? store.getState() : { view: 'issues' };\n const view = s.view || 'issues';\n const next = issueHashFor(view, id);\n log('goto issue %s (view=%s)', id, view);\n if (window.location.hash !== next) {\n window.location.hash = next;\n } else {\n // Force state update even if hash is the same\n store.setState({ selected_id: id, view });\n }\n },\n /**\n * Navigate to a top-level view.\n *\n * @param {'issues'|'epics'|'board'} view\n */\n /**\n * @param {'issues'|'epics'|'board'} view\n */\n gotoView(view) {\n const s = store.getState ? store.getState() : { selected_id: null };\n const id = s.selected_id;\n const next = id ? issueHashFor(view, id) : `#/${view}`;\n log('goto view %s (id=%s)', view, id || '');\n if (window.location.hash !== next) {\n window.location.hash = next;\n } else {\n store.setState({ view, selected_id: null });\n }\n }\n };\n}\n", "/**\n * Minimal app state store with subscription.\n */\nimport { debug } from './utils/logging.js';\n\n/**\n * @typedef {'all'|'open'|'in_progress'|'closed'|'ready'} StatusFilter\n */\n\n/**\n * @typedef {{ status: StatusFilter, search: string, type: string }} Filters\n */\n\n/**\n * @typedef {'issues'|'epics'|'board'} ViewName\n */\n\n/**\n * @typedef {'today'|'3'|'7'} ClosedFilter\n */\n\n/**\n * @typedef {{ closed_filter: ClosedFilter }} BoardState\n */\n\n/**\n * @typedef {Object} WorkspaceInfo\n * @property {string} path - Full path to workspace\n * @property {string} database - Path to the database file\n * @property {number} [pid] - Process ID of the daemon\n * @property {string} [version] - Version of beads\n */\n\n/**\n * @typedef {Object} WorkspaceState\n * @property {WorkspaceInfo | null} current - Currently active workspace\n * @property {WorkspaceInfo[]} available - All available workspaces\n */\n\n/**\n * @typedef {{ selected_id: string | null, view: ViewName, filters: Filters, board: BoardState, workspace: WorkspaceState }} AppState\n */\n\n/**\n * Create a simple store for application state.\n *\n * @param {Partial<AppState>} [initial]\n * @returns {{ getState: () => AppState, setState: (patch: { selected_id?: string | null, filters?: Partial<Filters>, workspace?: Partial<WorkspaceState> }) => void, subscribe: (fn: (s: AppState) => void) => () => void }}\n */\nexport function createStore(initial = {}) {\n const log = debug('state');\n /** @type {AppState} */\n let state = {\n selected_id: initial.selected_id ?? null,\n view: initial.view ?? 'issues',\n filters: {\n status: initial.filters?.status ?? 'all',\n search: initial.filters?.search ?? '',\n type:\n typeof initial.filters?.type === 'string' ? initial.filters?.type : ''\n },\n board: {\n closed_filter:\n initial.board?.closed_filter === '3' ||\n initial.board?.closed_filter === '7' ||\n initial.board?.closed_filter === 'today'\n ? initial.board?.closed_filter\n : 'today'\n },\n workspace: {\n current: initial.workspace?.current ?? null,\n available: initial.workspace?.available ?? []\n }\n };\n\n /** @type {Set<(s: AppState) => void>} */\n const subs = new Set();\n\n function emit() {\n for (const fn of Array.from(subs)) {\n try {\n fn(state);\n } catch {\n // ignore\n }\n }\n }\n\n return {\n getState() {\n return state;\n },\n /**\n * Update state. Nested filters can be partial.\n *\n * @param {{ selected_id?: string | null, filters?: Partial<Filters>, board?: Partial<BoardState>, workspace?: Partial<WorkspaceState> }} patch\n */\n setState(patch) {\n /** @type {AppState} */\n const next = {\n ...state,\n ...patch,\n filters: { ...state.filters, ...(patch.filters || {}) },\n board: { ...state.board, ...(patch.board || {}) },\n workspace: {\n current:\n patch.workspace?.current !== undefined\n ? patch.workspace.current\n : state.workspace.current,\n available:\n patch.workspace?.available !== undefined\n ? patch.workspace.available\n : state.workspace.available\n }\n };\n // Avoid emitting if nothing changed (shallow compare)\n const workspace_changed =\n next.workspace.current?.path !== state.workspace.current?.path ||\n next.workspace.available.length !== state.workspace.available.length;\n if (\n next.selected_id === state.selected_id &&\n next.view === state.view &&\n next.filters.status === state.filters.status &&\n next.filters.search === state.filters.search &&\n next.filters.type === state.filters.type &&\n next.board.closed_filter === state.board.closed_filter &&\n !workspace_changed\n ) {\n return;\n }\n state = next;\n log('state change %o', {\n selected_id: state.selected_id,\n view: state.view,\n filters: state.filters,\n board: state.board,\n workspace: state.workspace.current?.path\n });\n emit();\n },\n subscribe(fn) {\n subs.add(fn);\n return () => subs.delete(fn);\n }\n };\n}\n", "/**\n * @import { MessageType } from '../protocol.js'\n */\nimport { debug } from './logging.js';\n\n/**\n * Track in-flight UI actions and toggle a bound indicator element.\n *\n * @param {HTMLElement | null} mount_element\n * @returns {{ wrapSend: (fn: (type: MessageType, payload?: unknown) => Promise<unknown>) => (type: MessageType, payload?: unknown) => Promise<unknown>, start: () => void, done: () => void, getCount: () => number, getActiveRequests: () => Array<{ id: number, type: string, elapsed_ms: number }> }}\n */\nexport function createActivityIndicator(mount_element) {\n const log = debug('activity');\n /** @type {number} */\n let pending_count = 0;\n /** @type {Map<number, { type: string, start_ts: number }>} */\n const active_requests = new Map();\n /** @type {number} */\n let next_request_id = 1;\n\n function render() {\n if (!mount_element) {\n return;\n }\n const is_active = pending_count > 0;\n mount_element.toggleAttribute('hidden', !is_active);\n mount_element.setAttribute('aria-busy', is_active ? 'true' : 'false');\n }\n\n function start() {\n pending_count += 1;\n log('start count=%d', pending_count);\n render();\n }\n\n function done() {\n const prev = pending_count;\n pending_count = Math.max(0, pending_count - 1);\n if (prev <= 0) {\n log('done called but count was already %d', prev);\n } else {\n log('done count=%d\u2192%d', prev, pending_count);\n }\n render();\n }\n\n /**\n * Wrap a transport-style send function to track activity.\n * Includes a safety timeout to prevent the loading indicator from getting stuck\n * if a request hangs due to network issues or server problems.\n *\n * @param {(type: MessageType, payload?: unknown) => Promise<unknown>} send_fn\n * @returns {(type: MessageType, payload?: unknown) => Promise<unknown>}\n */\n function wrapSend(send_fn) {\n // Safety timeout: if a request takes longer than this, force decrement the counter\n const SAFETY_TIMEOUT_MS = 30000; // 30 seconds\n\n return async (type, payload) => {\n const req_id = next_request_id++;\n const start_ts = Date.now();\n active_requests.set(req_id, { type, start_ts });\n log(\n 'request start id=%d type=%s count=%d',\n req_id,\n type,\n pending_count + 1\n );\n start();\n\n // Track if we've already called done() for this request\n let completed = false;\n const markComplete = () => {\n if (!completed) {\n completed = true;\n active_requests.delete(req_id);\n done();\n }\n };\n\n // Safety timeout: force decrement if request takes too long\n const timeout_id = setTimeout(() => {\n if (!completed) {\n log(\n 'request TIMEOUT id=%d type=%s elapsed=%dms',\n req_id,\n type,\n Date.now() - start_ts\n );\n markComplete();\n }\n }, SAFETY_TIMEOUT_MS);\n\n try {\n const result = await send_fn(type, payload);\n const elapsed = Date.now() - start_ts;\n log('request done id=%d type=%s elapsed=%dms', req_id, type, elapsed);\n return result;\n } catch (err) {\n const elapsed = Date.now() - start_ts;\n log(\n 'request error id=%d type=%s elapsed=%dms err=%o',\n req_id,\n type,\n elapsed,\n err\n );\n throw err;\n } finally {\n clearTimeout(timeout_id);\n markComplete();\n }\n };\n }\n\n render();\n\n return {\n wrapSend,\n start,\n done,\n getCount: () => pending_count,\n /**\n * Get details about active requests (for debugging stuck indicators).\n *\n * @returns {Array<{ id: number, type: string, elapsed_ms: number }>}\n */\n getActiveRequests: () => {\n const now = Date.now();\n return Array.from(active_requests.entries()).map(([id, info]) => ({\n id,\n type: info.type,\n elapsed_ms: now - info.start_ts\n }));\n }\n };\n}\n", "/**\n * Show a transient global toast message anchored to the viewport.\n *\n * @param {string} text - Message text.\n * @param {'info'|'success'|'error'} [variant] - Visual variant.\n * @param {number} [duration_ms] - Auto-dismiss delay in milliseconds.\n */\nexport function showToast(text, variant = 'info', duration_ms = 2800) {\n const el = document.createElement('div');\n el.className = 'toast';\n el.textContent = text;\n el.style.position = 'fixed';\n el.style.right = '12px';\n el.style.bottom = '12px';\n el.style.zIndex = '1000';\n el.style.color = '#fff';\n el.style.padding = '8px 10px';\n el.style.borderRadius = '4px';\n el.style.fontSize = '12px';\n if (variant === 'success') {\n el.style.background = '#156d36';\n } else if (variant === 'error') {\n el.style.background = '#9f2011';\n } else {\n el.style.background = 'rgba(0,0,0,0.85)';\n }\n (document.body || document.documentElement).appendChild(el);\n setTimeout(() => {\n try {\n el.remove();\n } catch {\n /* ignore */\n }\n }, duration_ms);\n}\n", "/**\n * Create a reusable, copy-to-clipboard issue ID renderer.\n * Looks like the current inline ID (monospace `#123`) but acts as a button\n * that copies the full, prefixed ID (e.g., `UI-123`) when activated.\n * Shows transient \"Copied\" feedback and then restores the ID.\n *\n * @param {string} id - Full issue id including the prefix (e.g., \"UI-123\").\n * @param {{ class_name?: string, duration_ms?: number }} [opts]\n * @returns {HTMLButtonElement}\n */\nexport function createIssueIdRenderer(id, opts) {\n /** @type {number} */\n const duration =\n typeof opts?.duration_ms === 'number' ? opts.duration_ms : 1200;\n /** @type {HTMLButtonElement} */\n const btn = document.createElement('button');\n // Visual: match inline ID look; keep it neutral and text-like\n btn.className =\n (opts?.class_name ? opts.class_name + ' ' : '') + 'mono id-copy';\n btn.type = 'button';\n btn.setAttribute('aria-live', 'polite');\n btn.setAttribute('title', 'Copy issue ID');\n btn.setAttribute('aria-label', `Copy issue ID ${id}`);\n btn.textContent = id;\n\n /** Copy handler with feedback. */\n async function doCopy() {\n try {\n let copied = false;\n if (\n navigator.clipboard &&\n typeof navigator.clipboard.writeText === 'function'\n ) {\n await navigator.clipboard.writeText(String(id));\n copied = true;\n } else {\n // Fallback for non-secure contexts (HTTP, non-localhost)\n // where navigator.clipboard is undefined.\n const ta = document.createElement('textarea');\n ta.value = String(id);\n ta.style.position = 'fixed';\n ta.style.left = '-9999px';\n ta.style.opacity = '0';\n // Append inside the nearest open <dialog> if any \u2014 showModal()\n // creates a top-layer that makes document.body inert.\n const container = btn.closest('dialog[open]') || document.body;\n container.appendChild(ta);\n ta.focus();\n ta.select();\n try {\n copied = document.execCommand('copy');\n } finally {\n container.removeChild(ta);\n }\n }\n if (copied) {\n btn.textContent = 'Copied';\n const oldAria = btn.getAttribute('aria-label') || '';\n btn.setAttribute('aria-label', 'Copied');\n setTimeout(\n () => {\n btn.textContent = id;\n btn.setAttribute('aria-label', oldAria);\n },\n Math.max(80, duration)\n );\n }\n } catch {\n // On failure, leave text as-is; no throw to avoid disruptive UX\n }\n }\n\n btn.addEventListener('click', (ev) => {\n ev.preventDefault();\n ev.stopPropagation();\n void doCopy();\n });\n btn.addEventListener('keydown', (ev) => {\n // Ensure keyboard activation works even in non-interactive test envs\n if (ev.key === 'Enter' || ev.key === ' ') {\n ev.preventDefault();\n ev.stopPropagation();\n void doCopy();\n }\n });\n\n return btn;\n}\n", "export const priority_levels = ['Critical', 'High', 'Medium', 'Low', 'Backlog'];\n", "import { priority_levels } from './priority.js';\n\n/**\n * Create a colored badge for a priority value (0..4).\n *\n * @param {number | null | undefined} priority\n * @returns {HTMLSpanElement}\n */\nexport function createPriorityBadge(priority) {\n const p = typeof priority === 'number' ? priority : 2;\n const el = document.createElement('span');\n el.className = 'priority-badge';\n el.classList.add(`is-p${Math.max(0, Math.min(4, p))}`);\n el.setAttribute('role', 'img');\n const label = labelForPriority(p);\n el.setAttribute('title', label);\n el.setAttribute('aria-label', `Priority: ${label}`);\n el.textContent = emojiForPriority(p) + ' ' + label;\n return el;\n}\n\n/**\n * @param {number} p\n */\nfunction labelForPriority(p) {\n const i = Math.max(0, Math.min(4, p));\n return priority_levels[i] || 'Medium';\n}\n\n/**\n * @param {number} p\n */\nexport function emojiForPriority(p) {\n switch (p) {\n case 0:\n return '\uD83D\uDD25';\n case 1:\n return '\u26A1\uFE0F';\n case 2:\n return '\uD83D\uDD27';\n case 3:\n return '\uD83E\uDEB6';\n case 4:\n return '\uD83D\uDCA4';\n default:\n return '\uD83D\uDD27';\n }\n}\n", "/**\n * Create a compact, colored badge for an issue type.\n *\n * @param {string | undefined | null} issue_type - One of: bug, feature, task, epic, chore\n * @returns {HTMLSpanElement}\n */\nexport function createTypeBadge(issue_type) {\n const el = document.createElement('span');\n el.className = 'type-badge';\n\n const t = (issue_type || '').toString().toLowerCase();\n const KNOWN = new Set(['bug', 'feature', 'task', 'epic', 'chore']);\n const kind = KNOWN.has(t) ? t : 'neutral';\n el.classList.add(`type-badge--${kind}`);\n el.setAttribute('role', 'img');\n const label = KNOWN.has(t)\n ? t === 'bug'\n ? 'Bug'\n : t === 'feature'\n ? 'Feature'\n : t === 'task'\n ? 'Task'\n : t === 'epic'\n ? 'Epic'\n : 'Chore'\n : '\u2014';\n el.setAttribute(\n 'aria-label',\n KNOWN.has(t) ? `Issue type: ${label}` : 'Issue type: unknown'\n );\n el.setAttribute('title', KNOWN.has(t) ? `Type: ${label}` : 'Type: unknown');\n el.textContent = label;\n return el;\n}\n", "import { html, render } from 'lit-html';\nimport { createListSelectors } from '../data/list-selectors.js';\nimport { cmpClosedDesc, cmpPriorityThenCreated } from '../data/sort.js';\nimport { createIssueIdRenderer } from '../utils/issue-id-renderer.js';\nimport { debug } from '../utils/logging.js';\nimport { createPriorityBadge } from '../utils/priority-badge.js';\nimport { showToast } from '../utils/toast.js';\nimport { createTypeBadge } from '../utils/type-badge.js';\n\n/**\n * @typedef {{\n * id: string,\n * title?: string,\n * status?: 'open'|'in_progress'|'closed',\n * priority?: number,\n * issue_type?: string,\n * created_at?: number,\n * updated_at?: number,\n * closed_at?: number\n * }} IssueLite\n */\n\n/**\n * Map column IDs to their corresponding status values.\n *\n * @type {Record<string, 'open'|'in_progress'|'closed'>}\n */\nconst COLUMN_STATUS_MAP = {\n 'blocked-col': 'open',\n 'ready-col': 'open',\n 'in-progress-col': 'in_progress',\n 'closed-col': 'closed'\n};\n\n/**\n * Create the Board view with Blocked, Ready, In progress, Closed.\n * Push-only: derives items from per-subscription stores.\n *\n * Sorting rules:\n * - Ready/Blocked/In progress: priority asc, then created_at asc.\n * - Closed: closed_at desc.\n *\n * @param {HTMLElement} mount_element\n * @param {unknown} _data - Unused (legacy param retained for call-compat)\n * @param {(id: string) => void} gotoIssue - Navigate to issue detail.\n * @param {{ getState: () => any, setState: (patch: any) => void, subscribe?: (fn: (s:any)=>void)=>()=>void }} [store]\n * @param {{ selectors: { getIds: (client_id: string) => string[], count?: (client_id: string) => number } }} [subscriptions]\n * @param {{ snapshotFor?: (client_id: string) => any[], subscribe?: (fn: () => void) => () => void }} [issueStores]\n * @param {(type: string, payload: unknown) => Promise<unknown>} [transport] - Transport function for sending updates\n * @returns {{ load: () => Promise<void>, clear: () => void }}\n */\nexport function createBoardView(\n mount_element,\n _data,\n gotoIssue,\n store,\n subscriptions = undefined,\n issueStores = undefined,\n transport = undefined\n) {\n const log = debug('views:board');\n /** @type {IssueLite[]} */\n let list_ready = [];\n /** @type {IssueLite[]} */\n let list_blocked = [];\n /** @type {IssueLite[]} */\n let list_in_progress = [];\n /** @type {IssueLite[]} */\n let list_closed = [];\n /** @type {IssueLite[]} */\n let list_closed_raw = [];\n // Centralized selection helpers\n const selectors = issueStores ? createListSelectors(issueStores) : null;\n\n /**\n * Closed column filter mode.\n * 'today' \u2192 items with closed_at since local day start\n * '3' \u2192 last 3 days; '7' \u2192 last 7 days\n *\n * @type {'today'|'3'|'7'}\n */\n let closed_filter_mode = 'today';\n if (store) {\n try {\n const s = store.getState();\n const cf =\n s && s.board ? String(s.board.closed_filter || 'today') : 'today';\n if (cf === 'today' || cf === '3' || cf === '7') {\n closed_filter_mode = /** @type {any} */ (cf);\n }\n } catch {\n // ignore store init errors\n }\n }\n\n function template() {\n return html`\n <div class=\"panel__body board-root\">\n ${columnTemplate('Blocked', 'blocked-col', list_blocked)}\n ${columnTemplate('Ready', 'ready-col', list_ready)}\n ${columnTemplate('In Progress', 'in-progress-col', list_in_progress)}\n ${columnTemplate('Closed', 'closed-col', list_closed)}\n </div>\n `;\n }\n\n /**\n * @param {string} title\n * @param {string} id\n * @param {IssueLite[]} items\n */\n function columnTemplate(title, id, items) {\n const item_count = Array.isArray(items) ? items.length : 0;\n const count_label = item_count === 1 ? '1 issue' : `${item_count} issues`;\n return html`\n <section class=\"board-column\" id=${id}>\n <header\n class=\"board-column__header\"\n id=${id + '-header'}\n role=\"heading\"\n aria-level=\"2\"\n >\n <div class=\"board-column__title\">\n <span class=\"board-column__title-text\">${title}</span>\n <span class=\"badge board-column__count\" aria-label=${count_label}>\n ${item_count}\n </span>\n </div>\n ${id === 'closed-col'\n ? html`<label class=\"board-closed-filter\">\n <span class=\"visually-hidden\">Filter closed issues</span>\n <select\n id=\"closed-filter\"\n aria-label=\"Filter closed issues\"\n @change=${onClosedFilterChange}\n >\n <option\n value=\"today\"\n ?selected=${closed_filter_mode === 'today'}\n >\n Today\n </option>\n <option value=\"3\" ?selected=${closed_filter_mode === '3'}>\n Last 3 days\n </option>\n <option value=\"7\" ?selected=${closed_filter_mode === '7'}>\n Last 7 days\n </option>\n </select>\n </label>`\n : ''}\n </header>\n <div\n class=\"board-column__body\"\n role=\"list\"\n aria-labelledby=${id + '-header'}\n >\n ${items.map((it) => cardTemplate(it))}\n </div>\n </section>\n `;\n }\n\n /**\n * @param {IssueLite} it\n */\n function cardTemplate(it) {\n return html`\n <article\n class=\"board-card\"\n data-issue-id=${it.id}\n role=\"listitem\"\n tabindex=\"-1\"\n draggable=\"true\"\n @click=${(/** @type {MouseEvent} */ ev) => onCardClick(ev, it.id)}\n @dragstart=${(/** @type {DragEvent} */ ev) => onDragStart(ev, it.id)}\n @dragend=${onDragEnd}\n >\n <div class=\"board-card__title text-truncate\">\n ${it.title || '(no title)'}\n </div>\n <div class=\"board-card__meta\">\n ${createTypeBadge(it.issue_type)} ${createPriorityBadge(it.priority)}\n ${createIssueIdRenderer(it.id, { class_name: 'mono' })}\n </div>\n </article>\n `;\n }\n\n /** @type {string|null} */\n let dragging_id = null;\n\n /**\n * Handle card click, ignoring clicks during drag operations.\n *\n * @param {MouseEvent} ev\n * @param {string} id\n */\n function onCardClick(ev, id) {\n // Only navigate if this wasn't a drag operation\n if (!dragging_id) {\n gotoIssue(id);\n }\n }\n\n /**\n * Handle drag start: store issue id in dataTransfer and add dragging class.\n *\n * @param {DragEvent} ev\n * @param {string} id\n */\n function onDragStart(ev, id) {\n dragging_id = id;\n if (ev.dataTransfer) {\n ev.dataTransfer.setData('text/plain', id);\n ev.dataTransfer.effectAllowed = 'move';\n }\n const target = /** @type {HTMLElement} */ (ev.target);\n target.classList.add('board-card--dragging');\n log('dragstart %s', id);\n }\n\n /**\n * Handle drag end: remove dragging class.\n *\n * @param {DragEvent} ev\n */\n function onDragEnd(ev) {\n const target = /** @type {HTMLElement} */ (ev.target);\n target.classList.remove('board-card--dragging');\n // Clear any highlighted drop target\n clearDropTarget();\n // Clear dragging_id after a short delay to allow click event to check it\n setTimeout(() => {\n dragging_id = null;\n }, 0);\n log('dragend');\n }\n\n /**\n * Clear the currently highlighted drop target column.\n */\n function clearDropTarget() {\n /** @type {HTMLElement[]} */\n const all_cols = Array.from(\n mount_element.querySelectorAll('.board-column--drag-over')\n );\n for (const c of all_cols) {\n c.classList.remove('board-column--drag-over');\n }\n }\n\n /**\n * Update issue status via WebSocket transport.\n *\n * @param {string} issue_id\n * @param {'open'|'in_progress'|'closed'} new_status\n */\n async function updateIssueStatus(issue_id, new_status) {\n if (!transport) {\n log('no transport available, status update skipped');\n showToast('Cannot update status: not connected', 'error');\n return;\n }\n try {\n log('update-status %s \u2192 %s', issue_id, new_status);\n await transport('update-status', { id: issue_id, status: new_status });\n showToast('Status updated', 'success', 1500);\n } catch (err) {\n log('update-status failed: %o', err);\n showToast('Failed to update status', 'error');\n }\n }\n\n function doRender() {\n render(template(), mount_element);\n postRenderEnhance();\n }\n\n /**\n * Enhance rendered board with a11y and keyboard navigation.\n * - Roving tabindex per column (first card tabbable).\n * - ArrowUp/ArrowDown within column.\n * - ArrowLeft/ArrowRight to adjacent non-empty column (focus top card).\n * - Enter/Space to open details for focused card.\n */\n function postRenderEnhance() {\n try {\n /** @type {HTMLElement[]} */\n const columns = Array.from(\n mount_element.querySelectorAll('.board-column')\n );\n for (const col of columns) {\n const body = /** @type {HTMLElement|null} */ (\n col.querySelector('.board-column__body')\n );\n if (!body) {\n continue;\n }\n /** @type {HTMLElement[]} */\n const cards = Array.from(body.querySelectorAll('.board-card'));\n // Assign aria-label using column header for screen readers\n const header = /** @type {HTMLElement|null} */ (\n col.querySelector('.board-column__header')\n );\n const col_name = header ? header.textContent?.trim() || '' : '';\n for (const card of cards) {\n const title_el = /** @type {HTMLElement|null} */ (\n card.querySelector('.board-card__title')\n );\n const t = title_el ? title_el.textContent?.trim() || '' : '';\n card.setAttribute(\n 'aria-label',\n `Issue ${t || '(no title)'} \u2014 Column ${col_name}`\n );\n // Default roving setup\n card.tabIndex = -1;\n }\n if (cards.length > 0) {\n cards[0].tabIndex = 0;\n }\n }\n } catch {\n // non-fatal\n }\n }\n\n // Delegate keyboard handling from mount_element\n mount_element.addEventListener('keydown', (ev) => {\n const target = ev.target;\n if (!target || !(target instanceof HTMLElement)) {\n return;\n }\n // Do not intercept keys inside editable controls\n const tag = String(target.tagName || '').toLowerCase();\n if (\n tag === 'input' ||\n tag === 'textarea' ||\n tag === 'select' ||\n target.isContentEditable === true\n ) {\n return;\n }\n const card = target.closest('.board-card');\n if (!card) {\n return;\n }\n const key = String(ev.key || '');\n if (key === 'Enter' || key === ' ') {\n ev.preventDefault();\n const id = card.getAttribute('data-issue-id');\n if (id) {\n gotoIssue(id);\n }\n return;\n }\n if (\n key !== 'ArrowUp' &&\n key !== 'ArrowDown' &&\n key !== 'ArrowLeft' &&\n key !== 'ArrowRight'\n ) {\n return;\n }\n ev.preventDefault();\n // Column context\n const col = /** @type {HTMLElement|null} */ (card.closest('.board-column'));\n if (!col) {\n return;\n }\n const body = col.querySelector('.board-column__body');\n if (!body) {\n return;\n }\n /** @type {HTMLElement[]} */\n const cards = Array.from(body.querySelectorAll('.board-card'));\n const idx = cards.indexOf(/** @type {HTMLElement} */ (card));\n if (idx === -1) {\n return;\n }\n if (key === 'ArrowDown' && idx < cards.length - 1) {\n moveFocus(cards[idx], cards[idx + 1]);\n return;\n }\n if (key === 'ArrowUp' && idx > 0) {\n moveFocus(cards[idx], cards[idx - 1]);\n return;\n }\n if (key === 'ArrowRight' || key === 'ArrowLeft') {\n // Find adjacent column with at least one card\n /** @type {HTMLElement[]} */\n const cols = Array.from(mount_element.querySelectorAll('.board-column'));\n const col_idx = cols.indexOf(col);\n if (col_idx === -1) {\n return;\n }\n const dir = key === 'ArrowRight' ? 1 : -1;\n let next_idx = col_idx + dir;\n /** @type {HTMLElement|null} */\n let target_col = null;\n while (next_idx >= 0 && next_idx < cols.length) {\n const candidate = cols[next_idx];\n const c_body = /** @type {HTMLElement|null} */ (\n candidate.querySelector('.board-column__body')\n );\n const c_cards = c_body\n ? Array.from(c_body.querySelectorAll('.board-card'))\n : [];\n if (c_cards.length > 0) {\n target_col = candidate;\n break;\n }\n next_idx += dir;\n }\n if (target_col) {\n const first = /** @type {HTMLElement|null} */ (\n target_col.querySelector('.board-column__body .board-card')\n );\n if (first) {\n moveFocus(/** @type {HTMLElement} */ (card), first);\n }\n }\n return;\n }\n });\n\n // Track the currently highlighted column to avoid flicker\n /** @type {HTMLElement|null} */\n let current_drop_target = null;\n\n // Delegate drag and drop handling for columns\n mount_element.addEventListener('dragover', (ev) => {\n ev.preventDefault();\n if (ev.dataTransfer) {\n ev.dataTransfer.dropEffect = 'move';\n }\n // Find the column being dragged over\n const target = /** @type {HTMLElement} */ (ev.target);\n const col = /** @type {HTMLElement|null} */ (\n target.closest('.board-column')\n );\n\n // Only update if we've entered a different column\n if (col && col !== current_drop_target) {\n // Remove highlight from previous column\n if (current_drop_target) {\n current_drop_target.classList.remove('board-column--drag-over');\n }\n // Highlight the new column\n col.classList.add('board-column--drag-over');\n current_drop_target = col;\n }\n });\n\n mount_element.addEventListener('dragleave', (ev) => {\n const related = /** @type {HTMLElement|null} */ (ev.relatedTarget);\n // Only clear if we're leaving the mount element entirely\n if (!related || !mount_element.contains(related)) {\n if (current_drop_target) {\n current_drop_target.classList.remove('board-column--drag-over');\n current_drop_target = null;\n }\n }\n });\n\n mount_element.addEventListener('drop', (ev) => {\n ev.preventDefault();\n // Clear the drop target highlight\n if (current_drop_target) {\n current_drop_target.classList.remove('board-column--drag-over');\n current_drop_target = null;\n }\n\n const target = /** @type {HTMLElement} */ (ev.target);\n const col = target.closest('.board-column');\n if (!col) {\n return;\n }\n\n const col_id = col.id;\n const new_status = COLUMN_STATUS_MAP[col_id];\n if (!new_status) {\n log('drop on unknown column: %s', col_id);\n return;\n }\n\n const issue_id = ev.dataTransfer?.getData('text/plain');\n if (!issue_id) {\n log('drop without issue id');\n return;\n }\n\n log('drop %s on %s \u2192 %s', issue_id, col_id, new_status);\n void updateIssueStatus(issue_id, new_status);\n });\n\n /**\n * @param {HTMLElement} from\n * @param {HTMLElement} to\n */\n function moveFocus(from, to) {\n try {\n from.tabIndex = -1;\n to.tabIndex = 0;\n to.focus();\n } catch {\n // ignore focus errors\n }\n }\n\n // Sort helpers centralized in app/data/sort.js\n\n /**\n * Recompute closed list from raw using the current filter and sort.\n */\n function applyClosedFilter() {\n log('applyClosedFilter %s', closed_filter_mode);\n /** @type {IssueLite[]} */\n let items = Array.isArray(list_closed_raw) ? [...list_closed_raw] : [];\n const now = new Date();\n let since_ts = 0;\n if (closed_filter_mode === 'today') {\n const start = new Date(\n now.getFullYear(),\n now.getMonth(),\n now.getDate(),\n 0,\n 0,\n 0,\n 0\n );\n since_ts = start.getTime();\n } else if (closed_filter_mode === '3') {\n since_ts = now.getTime() - 3 * 24 * 60 * 60 * 1000;\n } else if (closed_filter_mode === '7') {\n since_ts = now.getTime() - 7 * 24 * 60 * 60 * 1000;\n }\n items = items.filter((it) => {\n const s = Number.isFinite(it.closed_at)\n ? /** @type {number} */ (it.closed_at)\n : NaN;\n if (!Number.isFinite(s)) {\n return false;\n }\n return s >= since_ts;\n });\n items.sort(cmpClosedDesc);\n list_closed = items;\n }\n\n /**\n * @param {Event} ev\n */\n function onClosedFilterChange(ev) {\n try {\n const el = /** @type {HTMLSelectElement} */ (ev.target);\n const v = String(el.value || 'today');\n closed_filter_mode = v === '3' || v === '7' ? v : 'today';\n log('closed filter %s', closed_filter_mode);\n if (store) {\n try {\n store.setState({ board: { closed_filter: closed_filter_mode } });\n } catch {\n // ignore store errors\n }\n }\n applyClosedFilter();\n doRender();\n } catch {\n // ignore\n }\n }\n\n /**\n * Compose lists from subscriptions + issues store and render.\n */\n function refreshFromStores() {\n try {\n if (selectors) {\n const in_progress = selectors.selectBoardColumn(\n 'tab:board:in-progress',\n 'in_progress'\n );\n const blocked = selectors.selectBoardColumn(\n 'tab:board:blocked',\n 'blocked'\n );\n const ready_raw = selectors.selectBoardColumn(\n 'tab:board:ready',\n 'ready'\n );\n const closed = selectors.selectBoardColumn(\n 'tab:board:closed',\n 'closed'\n );\n\n // Ready excludes items that are in progress\n /** @type {Set<string>} */\n const in_prog_ids = new Set(in_progress.map((i) => i.id));\n const ready = ready_raw.filter((i) => !in_prog_ids.has(i.id));\n\n list_ready = ready;\n list_blocked = blocked;\n list_in_progress = in_progress;\n list_closed_raw = closed;\n }\n applyClosedFilter();\n doRender();\n } catch {\n list_ready = [];\n list_blocked = [];\n list_in_progress = [];\n list_closed = [];\n doRender();\n }\n }\n\n // Live updates: recompose on issue store envelopes\n if (selectors) {\n selectors.subscribe(() => {\n try {\n refreshFromStores();\n } catch {\n // ignore\n }\n });\n }\n\n return {\n async load() {\n // Compose lists from subscriptions + issues store\n log('load');\n refreshFromStores();\n // If nothing is present yet (e.g., immediately after switching back\n // to the Board and before list-delta arrives), fetch via data layer as\n // a fallback so the board is not empty on initial display.\n try {\n const has_subs = Boolean(subscriptions && subscriptions.selectors);\n /**\n * @param {string} id\n */\n const cnt = (id) => {\n if (!has_subs || !subscriptions) {\n return 0;\n }\n const sel = subscriptions.selectors;\n if (typeof sel.count === 'function') {\n return Number(sel.count(id) || 0);\n }\n try {\n const arr = sel.getIds(id);\n return Array.isArray(arr) ? arr.length : 0;\n } catch {\n return 0;\n }\n };\n const total_items =\n cnt('tab:board:ready') +\n cnt('tab:board:blocked') +\n cnt('tab:board:in-progress') +\n cnt('tab:board:closed');\n const data = /** @type {any} */ (_data);\n const can_fetch =\n data &&\n typeof data.getReady === 'function' &&\n typeof data.getBlocked === 'function' &&\n typeof data.getInProgress === 'function' &&\n typeof data.getClosed === 'function';\n if (total_items === 0 && can_fetch) {\n log('fallback fetch');\n /** @type {[IssueLite[], IssueLite[], IssueLite[], IssueLite[]]} */\n const [ready_raw, blocked_raw, in_prog_raw, closed_raw] =\n await Promise.all([\n data.getReady().catch(() => []),\n data.getBlocked().catch(() => []),\n data.getInProgress().catch(() => []),\n data.getClosed().catch(() => [])\n ]);\n // Normalize and map unknowns to IssueLite shape\n /** @type {IssueLite[]} */\n let ready = Array.isArray(ready_raw) ? ready_raw.map((it) => it) : [];\n /** @type {IssueLite[]} */\n const blocked = Array.isArray(blocked_raw)\n ? blocked_raw.map((it) => it)\n : [];\n /** @type {IssueLite[]} */\n const in_prog = Array.isArray(in_prog_raw)\n ? in_prog_raw.map((it) => it)\n : [];\n /** @type {IssueLite[]} */\n const closed = Array.isArray(closed_raw)\n ? closed_raw.map((it) => it)\n : [];\n\n // Remove items from Ready that are already In Progress\n /** @type {Set<string>} */\n const in_progress_ids = new Set(in_prog.map((i) => i.id));\n ready = ready.filter((i) => !in_progress_ids.has(i.id));\n\n // Sort as per column rules\n ready.sort(cmpPriorityThenCreated);\n blocked.sort(cmpPriorityThenCreated);\n in_prog.sort(cmpPriorityThenCreated);\n list_ready = ready;\n list_blocked = blocked;\n list_in_progress = in_prog;\n list_closed_raw = closed;\n applyClosedFilter();\n doRender();\n }\n } catch {\n // ignore fallback errors\n }\n },\n clear() {\n mount_element.replaceChildren();\n list_ready = [];\n list_blocked = [];\n list_in_progress = [];\n list_closed = [];\n }\n };\n}\n", "const {\n entries,\n setPrototypeOf,\n isFrozen,\n getPrototypeOf,\n getOwnPropertyDescriptor,\n} = Object;\n\nlet { freeze, seal, create } = Object; // eslint-disable-line import/no-mutable-exports\nlet { apply, construct } = typeof Reflect !== 'undefined' && Reflect;\n\nif (!freeze) {\n freeze = function <T>(x: T): T {\n return x;\n };\n}\n\nif (!seal) {\n seal = function <T>(x: T): T {\n return x;\n };\n}\n\nif (!apply) {\n apply = function <T>(\n func: (thisArg: any, ...args: any[]) => T,\n thisArg: any,\n ...args: any[]\n ): T {\n return func.apply(thisArg, args);\n };\n}\n\nif (!construct) {\n construct = function <T>(Func: new (...args: any[]) => T, ...args: any[]): T {\n return new Func(...args);\n };\n}\n\nconst arrayForEach = unapply(Array.prototype.forEach);\nconst arrayIndexOf = unapply(Array.prototype.indexOf);\nconst arrayLastIndexOf = unapply(Array.prototype.lastIndexOf);\nconst arrayPop = unapply(Array.prototype.pop);\nconst arrayPush = unapply(Array.prototype.push);\nconst arraySlice = unapply(Array.prototype.slice);\nconst arraySplice = unapply(Array.prototype.splice);\n\nconst stringToLowerCase = unapply(String.prototype.toLowerCase);\nconst stringToString = unapply(String.prototype.toString);\nconst stringMatch = unapply(String.prototype.match);\nconst stringReplace = unapply(String.prototype.replace);\nconst stringIndexOf = unapply(String.prototype.indexOf);\nconst stringTrim = unapply(String.prototype.trim);\n\nconst objectHasOwnProperty = unapply(Object.prototype.hasOwnProperty);\n\nconst regExpTest = unapply(RegExp.prototype.test);\n\nconst typeErrorCreate = unconstruct(TypeError);\n\n/**\n * Creates a new function that calls the given function with a specified thisArg and arguments.\n *\n * @param func - The function to be wrapped and called.\n * @returns A new function that calls the given function with a specified thisArg and arguments.\n */\nfunction unapply<T>(\n func: (thisArg: any, ...args: any[]) => T\n): (thisArg: any, ...args: any[]) => T {\n return (thisArg: any, ...args: any[]): T => {\n if (thisArg instanceof RegExp) {\n thisArg.lastIndex = 0;\n }\n\n return apply(func, thisArg, args);\n };\n}\n\n/**\n * Creates a new function that constructs an instance of the given constructor function with the provided arguments.\n *\n * @param func - The constructor function to be wrapped and called.\n * @returns A new function that constructs an instance of the given constructor function with the provided arguments.\n */\nfunction unconstruct<T>(\n Func: new (...args: any[]) => T\n): (...args: any[]) => T {\n return (...args: any[]): T => construct(Func, args);\n}\n\n/**\n * Add properties to a lookup table\n *\n * @param set - The set to which elements will be added.\n * @param array - The array containing elements to be added to the set.\n * @param transformCaseFunc - An optional function to transform the case of each element before adding to the set.\n * @returns The modified set with added elements.\n */\nfunction addToSet(\n set: Record<string, any>,\n array: readonly any[],\n transformCaseFunc: ReturnType<typeof unapply<string>> = stringToLowerCase\n): Record<string, any> {\n if (setPrototypeOf) {\n // Make 'in' and truthy checks like Boolean(set.constructor)\n // independent of any properties defined on Object.prototype.\n // Prevent prototype setters from intercepting set as a this value.\n setPrototypeOf(set, null);\n }\n\n let l = array.length;\n while (l--) {\n let element = array[l];\n if (typeof element === 'string') {\n const lcElement = transformCaseFunc(element);\n if (lcElement !== element) {\n // Config presets (e.g. tags.js, attrs.js) are immutable.\n if (!isFrozen(array)) {\n (array as any[])[l] = lcElement;\n }\n\n element = lcElement;\n }\n }\n\n set[element] = true;\n }\n\n return set;\n}\n\n/**\n * Clean up an array to harden against CSPP\n *\n * @param array - The array to be cleaned.\n * @returns The cleaned version of the array\n */\nfunction cleanArray<T>(array: T[]): Array<T | null> {\n for (let index = 0; index < array.length; index++) {\n const isPropertyExist = objectHasOwnProperty(array, index);\n\n if (!isPropertyExist) {\n array[index] = null;\n }\n }\n\n return array;\n}\n\n/**\n * Shallow clone an object\n *\n * @param object - The object to be cloned.\n * @returns A new object that copies the original.\n */\nfunction clone<T extends Record<string, any>>(object: T): T {\n const newObject = create(null);\n\n for (const [property, value] of entries(object)) {\n const isPropertyExist = objectHasOwnProperty(object, property);\n\n if (isPropertyExist) {\n if (Array.isArray(value)) {\n newObject[property] = cleanArray(value);\n } else if (\n value &&\n typeof value === 'object' &&\n value.constructor === Object\n ) {\n newObject[property] = clone(value);\n } else {\n newObject[property] = value;\n }\n }\n }\n\n return newObject;\n}\n\n/**\n * This method automatically checks if the prop is function or getter and behaves accordingly.\n *\n * @param object - The object to look up the getter function in its prototype chain.\n * @param prop - The property name for which to find the getter function.\n * @returns The getter function found in the prototype chain or a fallback function.\n */\nfunction lookupGetter<T extends Record<string, any>>(\n object: T,\n prop: string\n): ReturnType<typeof unapply<any>> | (() => null) {\n while (object !== null) {\n const desc = getOwnPropertyDescriptor(object, prop);\n\n if (desc) {\n if (desc.get) {\n return unapply(desc.get);\n }\n\n if (typeof desc.value === 'function') {\n return unapply(desc.value);\n }\n }\n\n object = getPrototypeOf(object);\n }\n\n function fallbackValue(): null {\n return null;\n }\n\n return fallbackValue;\n}\n\nexport {\n // Array\n arrayForEach,\n arrayIndexOf,\n arrayLastIndexOf,\n arrayPop,\n arrayPush,\n arraySlice,\n arraySplice,\n // Object\n entries,\n freeze,\n getPrototypeOf,\n getOwnPropertyDescriptor,\n isFrozen,\n setPrototypeOf,\n seal,\n clone,\n create,\n objectHasOwnProperty,\n // RegExp\n regExpTest,\n // String\n stringIndexOf,\n stringMatch,\n stringReplace,\n stringToLowerCase,\n stringToString,\n stringTrim,\n // Errors\n typeErrorCreate,\n // Other\n lookupGetter,\n addToSet,\n // Reflect\n unapply,\n unconstruct,\n};\n", "import { freeze } from './utils.js';\n\nexport const html = freeze([\n 'a',\n 'abbr',\n 'acronym',\n 'address',\n 'area',\n 'article',\n 'aside',\n 'audio',\n 'b',\n 'bdi',\n 'bdo',\n 'big',\n 'blink',\n 'blockquote',\n 'body',\n 'br',\n 'button',\n 'canvas',\n 'caption',\n 'center',\n 'cite',\n 'code',\n 'col',\n 'colgroup',\n 'content',\n 'data',\n 'datalist',\n 'dd',\n 'decorator',\n 'del',\n 'details',\n 'dfn',\n 'dialog',\n 'dir',\n 'div',\n 'dl',\n 'dt',\n 'element',\n 'em',\n 'fieldset',\n 'figcaption',\n 'figure',\n 'font',\n 'footer',\n 'form',\n 'h1',\n 'h2',\n 'h3',\n 'h4',\n 'h5',\n 'h6',\n 'head',\n 'header',\n 'hgroup',\n 'hr',\n 'html',\n 'i',\n 'img',\n 'input',\n 'ins',\n 'kbd',\n 'label',\n 'legend',\n 'li',\n 'main',\n 'map',\n 'mark',\n 'marquee',\n 'menu',\n 'menuitem',\n 'meter',\n 'nav',\n 'nobr',\n 'ol',\n 'optgroup',\n 'option',\n 'output',\n 'p',\n 'picture',\n 'pre',\n 'progress',\n 'q',\n 'rp',\n 'rt',\n 'ruby',\n 's',\n 'samp',\n 'search',\n 'section',\n 'select',\n 'shadow',\n 'slot',\n 'small',\n 'source',\n 'spacer',\n 'span',\n 'strike',\n 'strong',\n 'style',\n 'sub',\n 'summary',\n 'sup',\n 'table',\n 'tbody',\n 'td',\n 'template',\n 'textarea',\n 'tfoot',\n 'th',\n 'thead',\n 'time',\n 'tr',\n 'track',\n 'tt',\n 'u',\n 'ul',\n 'var',\n 'video',\n 'wbr',\n] as const);\n\nexport const svg = freeze([\n 'svg',\n 'a',\n 'altglyph',\n 'altglyphdef',\n 'altglyphitem',\n 'animatecolor',\n 'animatemotion',\n 'animatetransform',\n 'circle',\n 'clippath',\n 'defs',\n 'desc',\n 'ellipse',\n 'enterkeyhint',\n 'exportparts',\n 'filter',\n 'font',\n 'g',\n 'glyph',\n 'glyphref',\n 'hkern',\n 'image',\n 'inputmode',\n 'line',\n 'lineargradient',\n 'marker',\n 'mask',\n 'metadata',\n 'mpath',\n 'part',\n 'path',\n 'pattern',\n 'polygon',\n 'polyline',\n 'radialgradient',\n 'rect',\n 'stop',\n 'style',\n 'switch',\n 'symbol',\n 'text',\n 'textpath',\n 'title',\n 'tref',\n 'tspan',\n 'view',\n 'vkern',\n] as const);\n\nexport const svgFilters = freeze([\n 'feBlend',\n 'feColorMatrix',\n 'feComponentTransfer',\n 'feComposite',\n 'feConvolveMatrix',\n 'feDiffuseLighting',\n 'feDisplacementMap',\n 'feDistantLight',\n 'feDropShadow',\n 'feFlood',\n 'feFuncA',\n 'feFuncB',\n 'feFuncG',\n 'feFuncR',\n 'feGaussianBlur',\n 'feImage',\n 'feMerge',\n 'feMergeNode',\n 'feMorphology',\n 'feOffset',\n 'fePointLight',\n 'feSpecularLighting',\n 'feSpotLight',\n 'feTile',\n 'feTurbulence',\n] as const);\n\n// List of SVG elements that are disallowed by default.\n// We still need to know them so that we can do namespace\n// checks properly in case one wants to add them to\n// allow-list.\nexport const svgDisallowed = freeze([\n 'animate',\n 'color-profile',\n 'cursor',\n 'discard',\n 'font-face',\n 'font-face-format',\n 'font-face-name',\n 'font-face-src',\n 'font-face-uri',\n 'foreignobject',\n 'hatch',\n 'hatchpath',\n 'mesh',\n 'meshgradient',\n 'meshpatch',\n 'meshrow',\n 'missing-glyph',\n 'script',\n 'set',\n 'solidcolor',\n 'unknown',\n 'use',\n] as const);\n\nexport const mathMl = freeze([\n 'math',\n 'menclose',\n 'merror',\n 'mfenced',\n 'mfrac',\n 'mglyph',\n 'mi',\n 'mlabeledtr',\n 'mmultiscripts',\n 'mn',\n 'mo',\n 'mover',\n 'mpadded',\n 'mphantom',\n 'mroot',\n 'mrow',\n 'ms',\n 'mspace',\n 'msqrt',\n 'mstyle',\n 'msub',\n 'msup',\n 'msubsup',\n 'mtable',\n 'mtd',\n 'mtext',\n 'mtr',\n 'munder',\n 'munderover',\n 'mprescripts',\n] as const);\n\n// Similarly to SVG, we want to know all MathML elements,\n// even those that we disallow by default.\nexport const mathMlDisallowed = freeze([\n 'maction',\n 'maligngroup',\n 'malignmark',\n 'mlongdiv',\n 'mscarries',\n 'mscarry',\n 'msgroup',\n 'mstack',\n 'msline',\n 'msrow',\n 'semantics',\n 'annotation',\n 'annotation-xml',\n 'mprescripts',\n 'none',\n] as const);\n\nexport const text = freeze(['#text'] as const);\n", "import { freeze } from './utils.js';\n\nexport const html = freeze([\n 'accept',\n 'action',\n 'align',\n 'alt',\n 'autocapitalize',\n 'autocomplete',\n 'autopictureinpicture',\n 'autoplay',\n 'background',\n 'bgcolor',\n 'border',\n 'capture',\n 'cellpadding',\n 'cellspacing',\n 'checked',\n 'cite',\n 'class',\n 'clear',\n 'color',\n 'cols',\n 'colspan',\n 'controls',\n 'controlslist',\n 'coords',\n 'crossorigin',\n 'datetime',\n 'decoding',\n 'default',\n 'dir',\n 'disabled',\n 'disablepictureinpicture',\n 'disableremoteplayback',\n 'download',\n 'draggable',\n 'enctype',\n 'enterkeyhint',\n 'exportparts',\n 'face',\n 'for',\n 'headers',\n 'height',\n 'hidden',\n 'high',\n 'href',\n 'hreflang',\n 'id',\n 'inert',\n 'inputmode',\n 'integrity',\n 'ismap',\n 'kind',\n 'label',\n 'lang',\n 'list',\n 'loading',\n 'loop',\n 'low',\n 'max',\n 'maxlength',\n 'media',\n 'method',\n 'min',\n 'minlength',\n 'multiple',\n 'muted',\n 'name',\n 'nonce',\n 'noshade',\n 'novalidate',\n 'nowrap',\n 'open',\n 'optimum',\n 'part',\n 'pattern',\n 'placeholder',\n 'playsinline',\n 'popover',\n 'popovertarget',\n 'popovertargetaction',\n 'poster',\n 'preload',\n 'pubdate',\n 'radiogroup',\n 'readonly',\n 'rel',\n 'required',\n 'rev',\n 'reversed',\n 'role',\n 'rows',\n 'rowspan',\n 'spellcheck',\n 'scope',\n 'selected',\n 'shape',\n 'size',\n 'sizes',\n 'slot',\n 'span',\n 'srclang',\n 'start',\n 'src',\n 'srcset',\n 'step',\n 'style',\n 'summary',\n 'tabindex',\n 'title',\n 'translate',\n 'type',\n 'usemap',\n 'valign',\n 'value',\n 'width',\n 'wrap',\n 'xmlns',\n 'slot',\n] as const);\n\nexport const svg = freeze([\n 'accent-height',\n 'accumulate',\n 'additive',\n 'alignment-baseline',\n 'amplitude',\n 'ascent',\n 'attributename',\n 'attributetype',\n 'azimuth',\n 'basefrequency',\n 'baseline-shift',\n 'begin',\n 'bias',\n 'by',\n 'class',\n 'clip',\n 'clippathunits',\n 'clip-path',\n 'clip-rule',\n 'color',\n 'color-interpolation',\n 'color-interpolation-filters',\n 'color-profile',\n 'color-rendering',\n 'cx',\n 'cy',\n 'd',\n 'dx',\n 'dy',\n 'diffuseconstant',\n 'direction',\n 'display',\n 'divisor',\n 'dur',\n 'edgemode',\n 'elevation',\n 'end',\n 'exponent',\n 'fill',\n 'fill-opacity',\n 'fill-rule',\n 'filter',\n 'filterunits',\n 'flood-color',\n 'flood-opacity',\n 'font-family',\n 'font-size',\n 'font-size-adjust',\n 'font-stretch',\n 'font-style',\n 'font-variant',\n 'font-weight',\n 'fx',\n 'fy',\n 'g1',\n 'g2',\n 'glyph-name',\n 'glyphref',\n 'gradientunits',\n 'gradienttransform',\n 'height',\n 'href',\n 'id',\n 'image-rendering',\n 'in',\n 'in2',\n 'intercept',\n 'k',\n 'k1',\n 'k2',\n 'k3',\n 'k4',\n 'kerning',\n 'keypoints',\n 'keysplines',\n 'keytimes',\n 'lang',\n 'lengthadjust',\n 'letter-spacing',\n 'kernelmatrix',\n 'kernelunitlength',\n 'lighting-color',\n 'local',\n 'marker-end',\n 'marker-mid',\n 'marker-start',\n 'markerheight',\n 'markerunits',\n 'markerwidth',\n 'maskcontentunits',\n 'maskunits',\n 'max',\n 'mask',\n 'mask-type',\n 'media',\n 'method',\n 'mode',\n 'min',\n 'name',\n 'numoctaves',\n 'offset',\n 'operator',\n 'opacity',\n 'order',\n 'orient',\n 'orientation',\n 'origin',\n 'overflow',\n 'paint-order',\n 'path',\n 'pathlength',\n 'patterncontentunits',\n 'patterntransform',\n 'patternunits',\n 'points',\n 'preservealpha',\n 'preserveaspectratio',\n 'primitiveunits',\n 'r',\n 'rx',\n 'ry',\n 'radius',\n 'refx',\n 'refy',\n 'repeatcount',\n 'repeatdur',\n 'restart',\n 'result',\n 'rotate',\n 'scale',\n 'seed',\n 'shape-rendering',\n 'slope',\n 'specularconstant',\n 'specularexponent',\n 'spreadmethod',\n 'startoffset',\n 'stddeviation',\n 'stitchtiles',\n 'stop-color',\n 'stop-opacity',\n 'stroke-dasharray',\n 'stroke-dashoffset',\n 'stroke-linecap',\n 'stroke-linejoin',\n 'stroke-miterlimit',\n 'stroke-opacity',\n 'stroke',\n 'stroke-width',\n 'style',\n 'surfacescale',\n 'systemlanguage',\n 'tabindex',\n 'tablevalues',\n 'targetx',\n 'targety',\n 'transform',\n 'transform-origin',\n 'text-anchor',\n 'text-decoration',\n 'text-rendering',\n 'textlength',\n 'type',\n 'u1',\n 'u2',\n 'unicode',\n 'values',\n 'viewbox',\n 'visibility',\n 'version',\n 'vert-adv-y',\n 'vert-origin-x',\n 'vert-origin-y',\n 'width',\n 'word-spacing',\n 'wrap',\n 'writing-mode',\n 'xchannelselector',\n 'ychannelselector',\n 'x',\n 'x1',\n 'x2',\n 'xmlns',\n 'y',\n 'y1',\n 'y2',\n 'z',\n 'zoomandpan',\n] as const);\n\nexport const mathMl = freeze([\n 'accent',\n 'accentunder',\n 'align',\n 'bevelled',\n 'close',\n 'columnsalign',\n 'columnlines',\n 'columnspan',\n 'denomalign',\n 'depth',\n 'dir',\n 'display',\n 'displaystyle',\n 'encoding',\n 'fence',\n 'frame',\n 'height',\n 'href',\n 'id',\n 'largeop',\n 'length',\n 'linethickness',\n 'lspace',\n 'lquote',\n 'mathbackground',\n 'mathcolor',\n 'mathsize',\n 'mathvariant',\n 'maxsize',\n 'minsize',\n 'movablelimits',\n 'notation',\n 'numalign',\n 'open',\n 'rowalign',\n 'rowlines',\n 'rowspacing',\n 'rowspan',\n 'rspace',\n 'rquote',\n 'scriptlevel',\n 'scriptminsize',\n 'scriptsizemultiplier',\n 'selection',\n 'separator',\n 'separators',\n 'stretchy',\n 'subscriptshift',\n 'supscriptshift',\n 'symmetric',\n 'voffset',\n 'width',\n 'xmlns',\n]);\n\nexport const xml = freeze([\n 'xlink:href',\n 'xml:id',\n 'xlink:title',\n 'xml:space',\n 'xmlns:xlink',\n] as const);\n", "import { seal } from './utils.js';\n\n// eslint-disable-next-line unicorn/better-regex\nexport const MUSTACHE_EXPR = seal(/\\{\\{[\\w\\W]*|[\\w\\W]*\\}\\}/gm); // Specify template detection regex for SAFE_FOR_TEMPLATES mode\nexport const ERB_EXPR = seal(/<%[\\w\\W]*|[\\w\\W]*%>/gm);\nexport const TMPLIT_EXPR = seal(/\\$\\{[\\w\\W]*/gm); // eslint-disable-line unicorn/better-regex\nexport const DATA_ATTR = seal(/^data-[\\-\\w.\\u00B7-\\uFFFF]+$/); // eslint-disable-line no-useless-escape\nexport const ARIA_ATTR = seal(/^aria-[\\-\\w]+$/); // eslint-disable-line no-useless-escape\nexport const IS_ALLOWED_URI = seal(\n /^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\\-]+(?:[^a-z+.\\-:]|$))/i // eslint-disable-line no-useless-escape\n);\nexport const IS_SCRIPT_OR_DATA = seal(/^(?:\\w+script|data):/i);\nexport const ATTR_WHITESPACE = seal(\n /[\\u0000-\\u0020\\u00A0\\u1680\\u180E\\u2000-\\u2029\\u205F\\u3000]/g // eslint-disable-line no-control-regex\n);\nexport const DOCTYPE_NAME = seal(/^html$/i);\nexport const CUSTOM_ELEMENT = seal(/^[a-z][.\\w]*(-[.\\w]+)+$/i);\n", "/* eslint-disable @typescript-eslint/indent */\n\nimport type { TrustedHTML, TrustedTypesWindow } from 'trusted-types/lib';\nimport type { Config, UseProfilesConfig } from './config';\nimport * as TAGS from './tags.js';\nimport * as ATTRS from './attrs.js';\nimport * as EXPRESSIONS from './regexp.js';\nimport {\n addToSet,\n clone,\n entries,\n freeze,\n arrayForEach,\n arrayLastIndexOf,\n arrayPop,\n arrayPush,\n arraySplice,\n stringMatch,\n stringReplace,\n stringToLowerCase,\n stringToString,\n stringIndexOf,\n stringTrim,\n regExpTest,\n typeErrorCreate,\n lookupGetter,\n create,\n objectHasOwnProperty,\n} from './utils.js';\n\nexport type { Config } from './config';\n\ndeclare const VERSION: string;\n\n// https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType\nconst NODE_TYPE = {\n element: 1,\n attribute: 2,\n text: 3,\n cdataSection: 4,\n entityReference: 5, // Deprecated\n entityNode: 6, // Deprecated\n progressingInstruction: 7,\n comment: 8,\n document: 9,\n documentType: 10,\n documentFragment: 11,\n notation: 12, // Deprecated\n};\n\nconst getGlobal = function (): WindowLike {\n return typeof window === 'undefined' ? null : window;\n};\n\n/**\n * Creates a no-op policy for internal use only.\n * Don't export this function outside this module!\n * @param trustedTypes The policy factory.\n * @param purifyHostElement The Script element used to load DOMPurify (to determine policy name suffix).\n * @return The policy created (or null, if Trusted Types\n * are not supported or creating the policy failed).\n */\nconst _createTrustedTypesPolicy = function (\n trustedTypes: TrustedTypePolicyFactory,\n purifyHostElement: HTMLScriptElement\n) {\n if (\n typeof trustedTypes !== 'object' ||\n typeof trustedTypes.createPolicy !== 'function'\n ) {\n return null;\n }\n\n // Allow the callers to control the unique policy name\n // by adding a data-tt-policy-suffix to the script element with the DOMPurify.\n // Policy creation with duplicate names throws in Trusted Types.\n let suffix = null;\n const ATTR_NAME = 'data-tt-policy-suffix';\n if (purifyHostElement && purifyHostElement.hasAttribute(ATTR_NAME)) {\n suffix = purifyHostElement.getAttribute(ATTR_NAME);\n }\n\n const policyName = 'dompurify' + (suffix ? '#' + suffix : '');\n\n try {\n return trustedTypes.createPolicy(policyName, {\n createHTML(html) {\n return html;\n },\n createScriptURL(scriptUrl) {\n return scriptUrl;\n },\n });\n } catch (_) {\n // Policy creation failed (most likely another DOMPurify script has\n // already run). Skip creating the policy, as this will only cause errors\n // if TT are enforced.\n console.warn(\n 'TrustedTypes policy ' + policyName + ' could not be created.'\n );\n return null;\n }\n};\n\nconst _createHooksMap = function (): HooksMap {\n return {\n afterSanitizeAttributes: [],\n afterSanitizeElements: [],\n afterSanitizeShadowDOM: [],\n beforeSanitizeAttributes: [],\n beforeSanitizeElements: [],\n beforeSanitizeShadowDOM: [],\n uponSanitizeAttribute: [],\n uponSanitizeElement: [],\n uponSanitizeShadowNode: [],\n };\n};\n\nfunction createDOMPurify(window: WindowLike = getGlobal()): DOMPurify {\n const DOMPurify: DOMPurify = (root: WindowLike) => createDOMPurify(root);\n\n DOMPurify.version = VERSION;\n\n DOMPurify.removed = [];\n\n if (\n !window ||\n !window.document ||\n window.document.nodeType !== NODE_TYPE.document ||\n !window.Element\n ) {\n // Not running in a browser, provide a factory function\n // so that you can pass your own Window\n DOMPurify.isSupported = false;\n\n return DOMPurify;\n }\n\n let { document } = window;\n\n const originalDocument = document;\n const currentScript: HTMLScriptElement =\n originalDocument.currentScript as HTMLScriptElement;\n const {\n DocumentFragment,\n HTMLTemplateElement,\n Node,\n Element,\n NodeFilter,\n NamedNodeMap = window.NamedNodeMap || (window as any).MozNamedAttrMap,\n HTMLFormElement,\n DOMParser,\n trustedTypes,\n } = window;\n\n const ElementPrototype = Element.prototype;\n\n const cloneNode = lookupGetter(ElementPrototype, 'cloneNode');\n const remove = lookupGetter(ElementPrototype, 'remove');\n const getNextSibling = lookupGetter(ElementPrototype, 'nextSibling');\n const getChildNodes = lookupGetter(ElementPrototype, 'childNodes');\n const getParentNode = lookupGetter(ElementPrototype, 'parentNode');\n\n // As per issue #47, the web-components registry is inherited by a\n // new document created via createHTMLDocument. As per the spec\n // (http://w3c.github.io/webcomponents/spec/custom/#creating-and-passing-registries)\n // a new empty registry is used when creating a template contents owner\n // document, so we use that as our parent document to ensure nothing\n // is inherited.\n if (typeof HTMLTemplateElement === 'function') {\n const template = document.createElement('template');\n if (template.content && template.content.ownerDocument) {\n document = template.content.ownerDocument;\n }\n }\n\n let trustedTypesPolicy;\n let emptyHTML = '';\n\n const {\n implementation,\n createNodeIterator,\n createDocumentFragment,\n getElementsByTagName,\n } = document;\n const { importNode } = originalDocument;\n\n let hooks = _createHooksMap();\n\n /**\n * Expose whether this browser supports running the full DOMPurify.\n */\n DOMPurify.isSupported =\n typeof entries === 'function' &&\n typeof getParentNode === 'function' &&\n implementation &&\n implementation.createHTMLDocument !== undefined;\n\n const {\n MUSTACHE_EXPR,\n ERB_EXPR,\n TMPLIT_EXPR,\n DATA_ATTR,\n ARIA_ATTR,\n IS_SCRIPT_OR_DATA,\n ATTR_WHITESPACE,\n CUSTOM_ELEMENT,\n } = EXPRESSIONS;\n\n let { IS_ALLOWED_URI } = EXPRESSIONS;\n\n /**\n * We consider the elements and attributes below to be safe. Ideally\n * don't add any new ones but feel free to remove unwanted ones.\n */\n\n /* allowed element names */\n let ALLOWED_TAGS = null;\n const DEFAULT_ALLOWED_TAGS = addToSet({}, [\n ...TAGS.html,\n ...TAGS.svg,\n ...TAGS.svgFilters,\n ...TAGS.mathMl,\n ...TAGS.text,\n ]);\n\n /* Allowed attribute names */\n let ALLOWED_ATTR = null;\n const DEFAULT_ALLOWED_ATTR = addToSet({}, [\n ...ATTRS.html,\n ...ATTRS.svg,\n ...ATTRS.mathMl,\n ...ATTRS.xml,\n ]);\n\n /*\n * Configure how DOMPurify should handle custom elements and their attributes as well as customized built-in elements.\n * @property {RegExp|Function|null} tagNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any custom elements)\n * @property {RegExp|Function|null} attributeNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any attributes not on the allow list)\n * @property {boolean} allowCustomizedBuiltInElements allow custom elements derived from built-ins if they pass CUSTOM_ELEMENT_HANDLING.tagNameCheck. Default: `false`.\n */\n let CUSTOM_ELEMENT_HANDLING = Object.seal(\n create(null, {\n tagNameCheck: {\n writable: true,\n configurable: false,\n enumerable: true,\n value: null,\n },\n attributeNameCheck: {\n writable: true,\n configurable: false,\n enumerable: true,\n value: null,\n },\n allowCustomizedBuiltInElements: {\n writable: true,\n configurable: false,\n enumerable: true,\n value: false,\n },\n })\n );\n\n /* Explicitly forbidden tags (overrides ALLOWED_TAGS/ADD_TAGS) */\n let FORBID_TAGS = null;\n\n /* Explicitly forbidden attributes (overrides ALLOWED_ATTR/ADD_ATTR) */\n let FORBID_ATTR = null;\n\n /* Config object to store ADD_TAGS/ADD_ATTR functions (when used as functions) */\n const EXTRA_ELEMENT_HANDLING = Object.seal(\n create(null, {\n tagCheck: {\n writable: true,\n configurable: false,\n enumerable: true,\n value: null,\n },\n attributeCheck: {\n writable: true,\n configurable: false,\n enumerable: true,\n value: null,\n },\n })\n );\n\n /* Decide if ARIA attributes are okay */\n let ALLOW_ARIA_ATTR = true;\n\n /* Decide if custom data attributes are okay */\n let ALLOW_DATA_ATTR = true;\n\n /* Decide if unknown protocols are okay */\n let ALLOW_UNKNOWN_PROTOCOLS = false;\n\n /* Decide if self-closing tags in attributes are allowed.\n * Usually removed due to a mXSS issue in jQuery 3.0 */\n let ALLOW_SELF_CLOSE_IN_ATTR = true;\n\n /* Output should be safe for common template engines.\n * This means, DOMPurify removes data attributes, mustaches and ERB\n */\n let SAFE_FOR_TEMPLATES = false;\n\n /* Output should be safe even for XML used within HTML and alike.\n * This means, DOMPurify removes comments when containing risky content.\n */\n let SAFE_FOR_XML = true;\n\n /* Decide if document with <html>... should be returned */\n let WHOLE_DOCUMENT = false;\n\n /* Track whether config is already set on this instance of DOMPurify. */\n let SET_CONFIG = false;\n\n /* Decide if all elements (e.g. style, script) must be children of\n * document.body. By default, browsers might move them to document.head */\n let FORCE_BODY = false;\n\n /* Decide if a DOM `HTMLBodyElement` should be returned, instead of a html\n * string (or a TrustedHTML object if Trusted Types are supported).\n * If `WHOLE_DOCUMENT` is enabled a `HTMLHtmlElement` will be returned instead\n */\n let RETURN_DOM = false;\n\n /* Decide if a DOM `DocumentFragment` should be returned, instead of a html\n * string (or a TrustedHTML object if Trusted Types are supported) */\n let RETURN_DOM_FRAGMENT = false;\n\n /* Try to return a Trusted Type object instead of a string, return a string in\n * case Trusted Types are not supported */\n let RETURN_TRUSTED_TYPE = false;\n\n /* Output should be free from DOM clobbering attacks?\n * This sanitizes markups named with colliding, clobberable built-in DOM APIs.\n */\n let SANITIZE_DOM = true;\n\n /* Achieve full DOM Clobbering protection by isolating the namespace of named\n * properties and JS variables, mitigating attacks that abuse the HTML/DOM spec rules.\n *\n * HTML/DOM spec rules that enable DOM Clobbering:\n * - Named Access on Window (§7.3.3)\n * - DOM Tree Accessors (§3.1.5)\n * - Form Element Parent-Child Relations (§4.10.3)\n * - Iframe srcdoc / Nested WindowProxies (§4.8.5)\n * - HTMLCollection (§4.2.10.2)\n *\n * Namespace isolation is implemented by prefixing `id` and `name` attributes\n * with a constant string, i.e., `user-content-`\n */\n let SANITIZE_NAMED_PROPS = false;\n const SANITIZE_NAMED_PROPS_PREFIX = 'user-content-';\n\n /* Keep element content when removing element? */\n let KEEP_CONTENT = true;\n\n /* If a `Node` is passed to sanitize(), then performs sanitization in-place instead\n * of importing it into a new Document and returning a sanitized copy */\n let IN_PLACE = false;\n\n /* Allow usage of profiles like html, svg and mathMl */\n let USE_PROFILES: UseProfilesConfig | false = {};\n\n /* Tags to ignore content of when KEEP_CONTENT is true */\n let FORBID_CONTENTS = null;\n const DEFAULT_FORBID_CONTENTS = addToSet({}, [\n 'annotation-xml',\n 'audio',\n 'colgroup',\n 'desc',\n 'foreignobject',\n 'head',\n 'iframe',\n 'math',\n 'mi',\n 'mn',\n 'mo',\n 'ms',\n 'mtext',\n 'noembed',\n 'noframes',\n 'noscript',\n 'plaintext',\n 'script',\n 'style',\n 'svg',\n 'template',\n 'thead',\n 'title',\n 'video',\n 'xmp',\n ]);\n\n /* Tags that are safe for data: URIs */\n let DATA_URI_TAGS = null;\n const DEFAULT_DATA_URI_TAGS = addToSet({}, [\n 'audio',\n 'video',\n 'img',\n 'source',\n 'image',\n 'track',\n ]);\n\n /* Attributes safe for values like \"javascript:\" */\n let URI_SAFE_ATTRIBUTES = null;\n const DEFAULT_URI_SAFE_ATTRIBUTES = addToSet({}, [\n 'alt',\n 'class',\n 'for',\n 'id',\n 'label',\n 'name',\n 'pattern',\n 'placeholder',\n 'role',\n 'summary',\n 'title',\n 'value',\n 'style',\n 'xmlns',\n ]);\n\n const MATHML_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';\n const SVG_NAMESPACE = 'http://www.w3.org/2000/svg';\n const HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';\n /* Document namespace */\n let NAMESPACE = HTML_NAMESPACE;\n let IS_EMPTY_INPUT = false;\n\n /* Allowed XHTML+XML namespaces */\n let ALLOWED_NAMESPACES = null;\n const DEFAULT_ALLOWED_NAMESPACES = addToSet(\n {},\n [MATHML_NAMESPACE, SVG_NAMESPACE, HTML_NAMESPACE],\n stringToString\n );\n\n let MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, [\n 'mi',\n 'mo',\n 'mn',\n 'ms',\n 'mtext',\n ]);\n\n let HTML_INTEGRATION_POINTS = addToSet({}, ['annotation-xml']);\n\n // Certain elements are allowed in both SVG and HTML\n // namespace. We need to specify them explicitly\n // so that they don't get erroneously deleted from\n // HTML namespace.\n const COMMON_SVG_AND_HTML_ELEMENTS = addToSet({}, [\n 'title',\n 'style',\n 'font',\n 'a',\n 'script',\n ]);\n\n /* Parsing of strict XHTML documents */\n let PARSER_MEDIA_TYPE: null | DOMParserSupportedType = null;\n const SUPPORTED_PARSER_MEDIA_TYPES = ['application/xhtml+xml', 'text/html'];\n const DEFAULT_PARSER_MEDIA_TYPE = 'text/html';\n let transformCaseFunc: null | Parameters<typeof addToSet>[2] = null;\n\n /* Keep a reference to config to pass to hooks */\n let CONFIG: Config | null = null;\n\n /* Ideally, do not touch anything below this line */\n /* ______________________________________________ */\n\n const formElement = document.createElement('form');\n\n const isRegexOrFunction = function (\n testValue: unknown\n ): testValue is Function | RegExp {\n return testValue instanceof RegExp || testValue instanceof Function;\n };\n\n /**\n * _parseConfig\n *\n * @param cfg optional config literal\n */\n // eslint-disable-next-line complexity\n const _parseConfig = function (cfg: Config = {}): void {\n if (CONFIG && CONFIG === cfg) {\n return;\n }\n\n /* Shield configuration object from tampering */\n if (!cfg || typeof cfg !== 'object') {\n cfg = {};\n }\n\n /* Shield configuration object from prototype pollution */\n cfg = clone(cfg);\n\n PARSER_MEDIA_TYPE =\n // eslint-disable-next-line unicorn/prefer-includes\n SUPPORTED_PARSER_MEDIA_TYPES.indexOf(cfg.PARSER_MEDIA_TYPE) === -1\n ? DEFAULT_PARSER_MEDIA_TYPE\n : cfg.PARSER_MEDIA_TYPE;\n\n // HTML tags and attributes are not case-sensitive, converting to lowercase. Keeping XHTML as is.\n transformCaseFunc =\n PARSER_MEDIA_TYPE === 'application/xhtml+xml'\n ? stringToString\n : stringToLowerCase;\n\n /* Set configuration parameters */\n ALLOWED_TAGS = objectHasOwnProperty(cfg, 'ALLOWED_TAGS')\n ? addToSet({}, cfg.ALLOWED_TAGS, transformCaseFunc)\n : DEFAULT_ALLOWED_TAGS;\n ALLOWED_ATTR = objectHasOwnProperty(cfg, 'ALLOWED_ATTR')\n ? addToSet({}, cfg.ALLOWED_ATTR, transformCaseFunc)\n : DEFAULT_ALLOWED_ATTR;\n ALLOWED_NAMESPACES = objectHasOwnProperty(cfg, 'ALLOWED_NAMESPACES')\n ? addToSet({}, cfg.ALLOWED_NAMESPACES, stringToString)\n : DEFAULT_ALLOWED_NAMESPACES;\n URI_SAFE_ATTRIBUTES = objectHasOwnProperty(cfg, 'ADD_URI_SAFE_ATTR')\n ? addToSet(\n clone(DEFAULT_URI_SAFE_ATTRIBUTES),\n cfg.ADD_URI_SAFE_ATTR,\n transformCaseFunc\n )\n : DEFAULT_URI_SAFE_ATTRIBUTES;\n DATA_URI_TAGS = objectHasOwnProperty(cfg, 'ADD_DATA_URI_TAGS')\n ? addToSet(\n clone(DEFAULT_DATA_URI_TAGS),\n cfg.ADD_DATA_URI_TAGS,\n transformCaseFunc\n )\n : DEFAULT_DATA_URI_TAGS;\n FORBID_CONTENTS = objectHasOwnProperty(cfg, 'FORBID_CONTENTS')\n ? addToSet({}, cfg.FORBID_CONTENTS, transformCaseFunc)\n : DEFAULT_FORBID_CONTENTS;\n FORBID_TAGS = objectHasOwnProperty(cfg, 'FORBID_TAGS')\n ? addToSet({}, cfg.FORBID_TAGS, transformCaseFunc)\n : clone({});\n FORBID_ATTR = objectHasOwnProperty(cfg, 'FORBID_ATTR')\n ? addToSet({}, cfg.FORBID_ATTR, transformCaseFunc)\n : clone({});\n USE_PROFILES = objectHasOwnProperty(cfg, 'USE_PROFILES')\n ? cfg.USE_PROFILES\n : false;\n ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false; // Default true\n ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false; // Default true\n ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false; // Default false\n ALLOW_SELF_CLOSE_IN_ATTR = cfg.ALLOW_SELF_CLOSE_IN_ATTR !== false; // Default true\n SAFE_FOR_TEMPLATES = cfg.SAFE_FOR_TEMPLATES || false; // Default false\n SAFE_FOR_XML = cfg.SAFE_FOR_XML !== false; // Default true\n WHOLE_DOCUMENT = cfg.WHOLE_DOCUMENT || false; // Default false\n RETURN_DOM = cfg.RETURN_DOM || false; // Default false\n RETURN_DOM_FRAGMENT = cfg.RETURN_DOM_FRAGMENT || false; // Default false\n RETURN_TRUSTED_TYPE = cfg.RETURN_TRUSTED_TYPE || false; // Default false\n FORCE_BODY = cfg.FORCE_BODY || false; // Default false\n SANITIZE_DOM = cfg.SANITIZE_DOM !== false; // Default true\n SANITIZE_NAMED_PROPS = cfg.SANITIZE_NAMED_PROPS || false; // Default false\n KEEP_CONTENT = cfg.KEEP_CONTENT !== false; // Default true\n IN_PLACE = cfg.IN_PLACE || false; // Default false\n IS_ALLOWED_URI = cfg.ALLOWED_URI_REGEXP || EXPRESSIONS.IS_ALLOWED_URI;\n NAMESPACE = cfg.NAMESPACE || HTML_NAMESPACE;\n MATHML_TEXT_INTEGRATION_POINTS =\n cfg.MATHML_TEXT_INTEGRATION_POINTS || MATHML_TEXT_INTEGRATION_POINTS;\n HTML_INTEGRATION_POINTS =\n cfg.HTML_INTEGRATION_POINTS || HTML_INTEGRATION_POINTS;\n\n CUSTOM_ELEMENT_HANDLING = cfg.CUSTOM_ELEMENT_HANDLING || {};\n if (\n cfg.CUSTOM_ELEMENT_HANDLING &&\n isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck)\n ) {\n CUSTOM_ELEMENT_HANDLING.tagNameCheck =\n cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck;\n }\n\n if (\n cfg.CUSTOM_ELEMENT_HANDLING &&\n isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)\n ) {\n CUSTOM_ELEMENT_HANDLING.attributeNameCheck =\n cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck;\n }\n\n if (\n cfg.CUSTOM_ELEMENT_HANDLING &&\n typeof cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements ===\n 'boolean'\n ) {\n CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements =\n cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements;\n }\n\n if (SAFE_FOR_TEMPLATES) {\n ALLOW_DATA_ATTR = false;\n }\n\n if (RETURN_DOM_FRAGMENT) {\n RETURN_DOM = true;\n }\n\n /* Parse profile info */\n if (USE_PROFILES) {\n ALLOWED_TAGS = addToSet({}, TAGS.text);\n ALLOWED_ATTR = [];\n if (USE_PROFILES.html === true) {\n addToSet(ALLOWED_TAGS, TAGS.html);\n addToSet(ALLOWED_ATTR, ATTRS.html);\n }\n\n if (USE_PROFILES.svg === true) {\n addToSet(ALLOWED_TAGS, TAGS.svg);\n addToSet(ALLOWED_ATTR, ATTRS.svg);\n addToSet(ALLOWED_ATTR, ATTRS.xml);\n }\n\n if (USE_PROFILES.svgFilters === true) {\n addToSet(ALLOWED_TAGS, TAGS.svgFilters);\n addToSet(ALLOWED_ATTR, ATTRS.svg);\n addToSet(ALLOWED_ATTR, ATTRS.xml);\n }\n\n if (USE_PROFILES.mathMl === true) {\n addToSet(ALLOWED_TAGS, TAGS.mathMl);\n addToSet(ALLOWED_ATTR, ATTRS.mathMl);\n addToSet(ALLOWED_ATTR, ATTRS.xml);\n }\n }\n\n /* Merge configuration parameters */\n if (cfg.ADD_TAGS) {\n if (typeof cfg.ADD_TAGS === 'function') {\n EXTRA_ELEMENT_HANDLING.tagCheck = cfg.ADD_TAGS;\n } else {\n if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) {\n ALLOWED_TAGS = clone(ALLOWED_TAGS);\n }\n\n addToSet(ALLOWED_TAGS, cfg.ADD_TAGS, transformCaseFunc);\n }\n }\n\n if (cfg.ADD_ATTR) {\n if (typeof cfg.ADD_ATTR === 'function') {\n EXTRA_ELEMENT_HANDLING.attributeCheck = cfg.ADD_ATTR;\n } else {\n if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) {\n ALLOWED_ATTR = clone(ALLOWED_ATTR);\n }\n\n addToSet(ALLOWED_ATTR, cfg.ADD_ATTR, transformCaseFunc);\n }\n }\n\n if (cfg.ADD_URI_SAFE_ATTR) {\n addToSet(URI_SAFE_ATTRIBUTES, cfg.ADD_URI_SAFE_ATTR, transformCaseFunc);\n }\n\n if (cfg.FORBID_CONTENTS) {\n if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {\n FORBID_CONTENTS = clone(FORBID_CONTENTS);\n }\n\n addToSet(FORBID_CONTENTS, cfg.FORBID_CONTENTS, transformCaseFunc);\n }\n\n /* Add #text in case KEEP_CONTENT is set to true */\n if (KEEP_CONTENT) {\n ALLOWED_TAGS['#text'] = true;\n }\n\n /* Add html, head and body to ALLOWED_TAGS in case WHOLE_DOCUMENT is true */\n if (WHOLE_DOCUMENT) {\n addToSet(ALLOWED_TAGS, ['html', 'head', 'body']);\n }\n\n /* Add tbody to ALLOWED_TAGS in case tables are permitted, see #286, #365 */\n if (ALLOWED_TAGS.table) {\n addToSet(ALLOWED_TAGS, ['tbody']);\n delete FORBID_TAGS.tbody;\n }\n\n if (cfg.TRUSTED_TYPES_POLICY) {\n if (typeof cfg.TRUSTED_TYPES_POLICY.createHTML !== 'function') {\n throw typeErrorCreate(\n 'TRUSTED_TYPES_POLICY configuration option must provide a \"createHTML\" hook.'\n );\n }\n\n if (typeof cfg.TRUSTED_TYPES_POLICY.createScriptURL !== 'function') {\n throw typeErrorCreate(\n 'TRUSTED_TYPES_POLICY configuration option must provide a \"createScriptURL\" hook.'\n );\n }\n\n // Overwrite existing TrustedTypes policy.\n trustedTypesPolicy = cfg.TRUSTED_TYPES_POLICY;\n\n // Sign local variables required by `sanitize`.\n emptyHTML = trustedTypesPolicy.createHTML('');\n } else {\n // Uninitialized policy, attempt to initialize the internal dompurify policy.\n if (trustedTypesPolicy === undefined) {\n trustedTypesPolicy = _createTrustedTypesPolicy(\n trustedTypes,\n currentScript\n );\n }\n\n // If creating the internal policy succeeded sign internal variables.\n if (trustedTypesPolicy !== null && typeof emptyHTML === 'string') {\n emptyHTML = trustedTypesPolicy.createHTML('');\n }\n }\n\n // Prevent further manipulation of configuration.\n // Not available in IE8, Safari 5, etc.\n if (freeze) {\n freeze(cfg);\n }\n\n CONFIG = cfg;\n };\n\n /* Keep track of all possible SVG and MathML tags\n * so that we can perform the namespace checks\n * correctly. */\n const ALL_SVG_TAGS = addToSet({}, [\n ...TAGS.svg,\n ...TAGS.svgFilters,\n ...TAGS.svgDisallowed,\n ]);\n const ALL_MATHML_TAGS = addToSet({}, [\n ...TAGS.mathMl,\n ...TAGS.mathMlDisallowed,\n ]);\n\n /**\n * @param element a DOM element whose namespace is being checked\n * @returns Return false if the element has a\n * namespace that a spec-compliant parser would never\n * return. Return true otherwise.\n */\n const _checkValidNamespace = function (element: Element): boolean {\n let parent = getParentNode(element);\n\n // In JSDOM, if we're inside shadow DOM, then parentNode\n // can be null. We just simulate parent in this case.\n if (!parent || !parent.tagName) {\n parent = {\n namespaceURI: NAMESPACE,\n tagName: 'template',\n };\n }\n\n const tagName = stringToLowerCase(element.tagName);\n const parentTagName = stringToLowerCase(parent.tagName);\n\n if (!ALLOWED_NAMESPACES[element.namespaceURI]) {\n return false;\n }\n\n if (element.namespaceURI === SVG_NAMESPACE) {\n // The only way to switch from HTML namespace to SVG\n // is via <svg>. If it happens via any other tag, then\n // it should be killed.\n if (parent.namespaceURI === HTML_NAMESPACE) {\n return tagName === 'svg';\n }\n\n // The only way to switch from MathML to SVG is via`\n // svg if parent is either <annotation-xml> or MathML\n // text integration points.\n if (parent.namespaceURI === MATHML_NAMESPACE) {\n return (\n tagName === 'svg' &&\n (parentTagName === 'annotation-xml' ||\n MATHML_TEXT_INTEGRATION_POINTS[parentTagName])\n );\n }\n\n // We only allow elements that are defined in SVG\n // spec. All others are disallowed in SVG namespace.\n return Boolean(ALL_SVG_TAGS[tagName]);\n }\n\n if (element.namespaceURI === MATHML_NAMESPACE) {\n // The only way to switch from HTML namespace to MathML\n // is via <math>. If it happens via any other tag, then\n // it should be killed.\n if (parent.namespaceURI === HTML_NAMESPACE) {\n return tagName === 'math';\n }\n\n // The only way to switch from SVG to MathML is via\n // <math> and HTML integration points\n if (parent.namespaceURI === SVG_NAMESPACE) {\n return tagName === 'math' && HTML_INTEGRATION_POINTS[parentTagName];\n }\n\n // We only allow elements that are defined in MathML\n // spec. All others are disallowed in MathML namespace.\n return Boolean(ALL_MATHML_TAGS[tagName]);\n }\n\n if (element.namespaceURI === HTML_NAMESPACE) {\n // The only way to switch from SVG to HTML is via\n // HTML integration points, and from MathML to HTML\n // is via MathML text integration points\n if (\n parent.namespaceURI === SVG_NAMESPACE &&\n !HTML_INTEGRATION_POINTS[parentTagName]\n ) {\n return false;\n }\n\n if (\n parent.namespaceURI === MATHML_NAMESPACE &&\n !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]\n ) {\n return false;\n }\n\n // We disallow tags that are specific for MathML\n // or SVG and should never appear in HTML namespace\n return (\n !ALL_MATHML_TAGS[tagName] &&\n (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName])\n );\n }\n\n // For XHTML and XML documents that support custom namespaces\n if (\n PARSER_MEDIA_TYPE === 'application/xhtml+xml' &&\n ALLOWED_NAMESPACES[element.namespaceURI]\n ) {\n return true;\n }\n\n // The code should never reach this place (this means\n // that the element somehow got namespace that is not\n // HTML, SVG, MathML or allowed via ALLOWED_NAMESPACES).\n // Return false just in case.\n return false;\n };\n\n /**\n * _forceRemove\n *\n * @param node a DOM node\n */\n const _forceRemove = function (node: Node): void {\n arrayPush(DOMPurify.removed, { element: node });\n\n try {\n // eslint-disable-next-line unicorn/prefer-dom-node-remove\n getParentNode(node).removeChild(node);\n } catch (_) {\n remove(node);\n }\n };\n\n /**\n * _removeAttribute\n *\n * @param name an Attribute name\n * @param element a DOM node\n */\n const _removeAttribute = function (name: string, element: Element): void {\n try {\n arrayPush(DOMPurify.removed, {\n attribute: element.getAttributeNode(name),\n from: element,\n });\n } catch (_) {\n arrayPush(DOMPurify.removed, {\n attribute: null,\n from: element,\n });\n }\n\n element.removeAttribute(name);\n\n // We void attribute values for unremovable \"is\" attributes\n if (name === 'is') {\n if (RETURN_DOM || RETURN_DOM_FRAGMENT) {\n try {\n _forceRemove(element);\n } catch (_) {}\n } else {\n try {\n element.setAttribute(name, '');\n } catch (_) {}\n }\n }\n };\n\n /**\n * _initDocument\n *\n * @param dirty - a string of dirty markup\n * @return a DOM, filled with the dirty markup\n */\n const _initDocument = function (dirty: string): Document {\n /* Create a HTML document */\n let doc = null;\n let leadingWhitespace = null;\n\n if (FORCE_BODY) {\n dirty = '<remove></remove>' + dirty;\n } else {\n /* If FORCE_BODY isn't used, leading whitespace needs to be preserved manually */\n const matches = stringMatch(dirty, /^[\\r\\n\\t ]+/);\n leadingWhitespace = matches && matches[0];\n }\n\n if (\n PARSER_MEDIA_TYPE === 'application/xhtml+xml' &&\n NAMESPACE === HTML_NAMESPACE\n ) {\n // Root of XHTML doc must contain xmlns declaration (see https://www.w3.org/TR/xhtml1/normative.html#strict)\n dirty =\n '<html xmlns=\"http://www.w3.org/1999/xhtml\"><head></head><body>' +\n dirty +\n '</body></html>';\n }\n\n const dirtyPayload = trustedTypesPolicy\n ? trustedTypesPolicy.createHTML(dirty)\n : dirty;\n /*\n * Use the DOMParser API by default, fallback later if needs be\n * DOMParser not work for svg when has multiple root element.\n */\n if (NAMESPACE === HTML_NAMESPACE) {\n try {\n doc = new DOMParser().parseFromString(dirtyPayload, PARSER_MEDIA_TYPE);\n } catch (_) {}\n }\n\n /* Use createHTMLDocument in case DOMParser is not available */\n if (!doc || !doc.documentElement) {\n doc = implementation.createDocument(NAMESPACE, 'template', null);\n try {\n doc.documentElement.innerHTML = IS_EMPTY_INPUT\n ? emptyHTML\n : dirtyPayload;\n } catch (_) {\n // Syntax error if dirtyPayload is invalid xml\n }\n }\n\n const body = doc.body || doc.documentElement;\n\n if (dirty && leadingWhitespace) {\n body.insertBefore(\n document.createTextNode(leadingWhitespace),\n body.childNodes[0] || null\n );\n }\n\n /* Work on whole document or just its body */\n if (NAMESPACE === HTML_NAMESPACE) {\n return getElementsByTagName.call(\n doc,\n WHOLE_DOCUMENT ? 'html' : 'body'\n )[0];\n }\n\n return WHOLE_DOCUMENT ? doc.documentElement : body;\n };\n\n /**\n * Creates a NodeIterator object that you can use to traverse filtered lists of nodes or elements in a document.\n *\n * @param root The root element or node to start traversing on.\n * @return The created NodeIterator\n */\n const _createNodeIterator = function (root: Node): NodeIterator {\n return createNodeIterator.call(\n root.ownerDocument || root,\n root,\n // eslint-disable-next-line no-bitwise\n NodeFilter.SHOW_ELEMENT |\n NodeFilter.SHOW_COMMENT |\n NodeFilter.SHOW_TEXT |\n NodeFilter.SHOW_PROCESSING_INSTRUCTION |\n NodeFilter.SHOW_CDATA_SECTION,\n null\n );\n };\n\n /**\n * _isClobbered\n *\n * @param element element to check for clobbering attacks\n * @return true if clobbered, false if safe\n */\n const _isClobbered = function (element: Element): boolean {\n return (\n element instanceof HTMLFormElement &&\n (typeof element.nodeName !== 'string' ||\n typeof element.textContent !== 'string' ||\n typeof element.removeChild !== 'function' ||\n !(element.attributes instanceof NamedNodeMap) ||\n typeof element.removeAttribute !== 'function' ||\n typeof element.setAttribute !== 'function' ||\n typeof element.namespaceURI !== 'string' ||\n typeof element.insertBefore !== 'function' ||\n typeof element.hasChildNodes !== 'function')\n );\n };\n\n /**\n * Checks whether the given object is a DOM node.\n *\n * @param value object to check whether it's a DOM node\n * @return true is object is a DOM node\n */\n const _isNode = function (value: unknown): value is Node {\n return typeof Node === 'function' && value instanceof Node;\n };\n\n function _executeHooks<T extends HookFunction>(\n hooks: HookFunction[],\n currentNode: Parameters<T>[0],\n data: Parameters<T>[1]\n ): void {\n arrayForEach(hooks, (hook: T) => {\n hook.call(DOMPurify, currentNode, data, CONFIG);\n });\n }\n\n /**\n * _sanitizeElements\n *\n * @protect nodeName\n * @protect textContent\n * @protect removeChild\n * @param currentNode to check for permission to exist\n * @return true if node was killed, false if left alive\n */\n const _sanitizeElements = function (currentNode: any): boolean {\n let content = null;\n\n /* Execute a hook if present */\n _executeHooks(hooks.beforeSanitizeElements, currentNode, null);\n\n /* Check if element is clobbered or can clobber */\n if (_isClobbered(currentNode)) {\n _forceRemove(currentNode);\n return true;\n }\n\n /* Now let's check the element's type and name */\n const tagName = transformCaseFunc(currentNode.nodeName);\n\n /* Execute a hook if present */\n _executeHooks(hooks.uponSanitizeElement, currentNode, {\n tagName,\n allowedTags: ALLOWED_TAGS,\n });\n\n /* Detect mXSS attempts abusing namespace confusion */\n if (\n SAFE_FOR_XML &&\n currentNode.hasChildNodes() &&\n !_isNode(currentNode.firstElementChild) &&\n regExpTest(/<[/\\w!]/g, currentNode.innerHTML) &&\n regExpTest(/<[/\\w!]/g, currentNode.textContent)\n ) {\n _forceRemove(currentNode);\n return true;\n }\n\n /* Remove any occurrence of processing instructions */\n if (currentNode.nodeType === NODE_TYPE.progressingInstruction) {\n _forceRemove(currentNode);\n return true;\n }\n\n /* Remove any kind of possibly harmful comments */\n if (\n SAFE_FOR_XML &&\n currentNode.nodeType === NODE_TYPE.comment &&\n regExpTest(/<[/\\w]/g, currentNode.data)\n ) {\n _forceRemove(currentNode);\n return true;\n }\n\n /* Remove element if anything forbids its presence */\n if (\n !(\n EXTRA_ELEMENT_HANDLING.tagCheck instanceof Function &&\n EXTRA_ELEMENT_HANDLING.tagCheck(tagName)\n ) &&\n (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName])\n ) {\n /* Check if we have a custom element to handle */\n if (!FORBID_TAGS[tagName] && _isBasicCustomElement(tagName)) {\n if (\n CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp &&\n regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName)\n ) {\n return false;\n }\n\n if (\n CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function &&\n CUSTOM_ELEMENT_HANDLING.tagNameCheck(tagName)\n ) {\n return false;\n }\n }\n\n /* Keep content except for bad-listed elements */\n if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) {\n const parentNode = getParentNode(currentNode) || currentNode.parentNode;\n const childNodes = getChildNodes(currentNode) || currentNode.childNodes;\n\n if (childNodes && parentNode) {\n const childCount = childNodes.length;\n\n for (let i = childCount - 1; i >= 0; --i) {\n const childClone = cloneNode(childNodes[i], true);\n childClone.__removalCount = (currentNode.__removalCount || 0) + 1;\n parentNode.insertBefore(childClone, getNextSibling(currentNode));\n }\n }\n }\n\n _forceRemove(currentNode);\n return true;\n }\n\n /* Check whether element has a valid namespace */\n if (currentNode instanceof Element && !_checkValidNamespace(currentNode)) {\n _forceRemove(currentNode);\n return true;\n }\n\n /* Make sure that older browsers don't get fallback-tag mXSS */\n if (\n (tagName === 'noscript' ||\n tagName === 'noembed' ||\n tagName === 'noframes') &&\n regExpTest(/<\\/no(script|embed|frames)/i, currentNode.innerHTML)\n ) {\n _forceRemove(currentNode);\n return true;\n }\n\n /* Sanitize element content to be template-safe */\n if (SAFE_FOR_TEMPLATES && currentNode.nodeType === NODE_TYPE.text) {\n /* Get the element's text content */\n content = currentNode.textContent;\n\n arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], (expr: RegExp) => {\n content = stringReplace(content, expr, ' ');\n });\n\n if (currentNode.textContent !== content) {\n arrayPush(DOMPurify.removed, { element: currentNode.cloneNode() });\n currentNode.textContent = content;\n }\n }\n\n /* Execute a hook if present */\n _executeHooks(hooks.afterSanitizeElements, currentNode, null);\n\n return false;\n };\n\n /**\n * _isValidAttribute\n *\n * @param lcTag Lowercase tag name of containing element.\n * @param lcName Lowercase attribute name.\n * @param value Attribute value.\n * @return Returns true if `value` is valid, otherwise false.\n */\n // eslint-disable-next-line complexity\n const _isValidAttribute = function (\n lcTag: string,\n lcName: string,\n value: string\n ): boolean {\n /* Make sure attribute cannot clobber */\n if (\n SANITIZE_DOM &&\n (lcName === 'id' || lcName === 'name') &&\n (value in document || value in formElement)\n ) {\n return false;\n }\n\n /* Allow valid data-* attributes: At least one character after \"-\"\n (https://html.spec.whatwg.org/multipage/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes)\n XML-compatible (https://html.spec.whatwg.org/multipage/infrastructure.html#xml-compatible and http://www.w3.org/TR/xml/#d0e804)\n We don't need to check the value; it's always URI safe. */\n if (\n ALLOW_DATA_ATTR &&\n !FORBID_ATTR[lcName] &&\n regExpTest(DATA_ATTR, lcName)\n ) {\n // This attribute is safe\n } else if (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR, lcName)) {\n // This attribute is safe\n /* Check if ADD_ATTR function allows this attribute */\n } else if (\n EXTRA_ELEMENT_HANDLING.attributeCheck instanceof Function &&\n EXTRA_ELEMENT_HANDLING.attributeCheck(lcName, lcTag)\n ) {\n // This attribute is safe\n /* Otherwise, check the name is permitted */\n } else if (!ALLOWED_ATTR[lcName] || FORBID_ATTR[lcName]) {\n if (\n // First condition does a very basic check if a) it's basically a valid custom element tagname AND\n // b) if the tagName passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck\n // and c) if the attribute name passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.attributeNameCheck\n (_isBasicCustomElement(lcTag) &&\n ((CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp &&\n regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, lcTag)) ||\n (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function &&\n CUSTOM_ELEMENT_HANDLING.tagNameCheck(lcTag))) &&\n ((CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof RegExp &&\n regExpTest(CUSTOM_ELEMENT_HANDLING.attributeNameCheck, lcName)) ||\n (CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof Function &&\n CUSTOM_ELEMENT_HANDLING.attributeNameCheck(lcName, lcTag)))) ||\n // Alternative, second condition checks if it's an `is`-attribute, AND\n // the value passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck\n (lcName === 'is' &&\n CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements &&\n ((CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp &&\n regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, value)) ||\n (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function &&\n CUSTOM_ELEMENT_HANDLING.tagNameCheck(value))))\n ) {\n // If user has supplied a regexp or function in CUSTOM_ELEMENT_HANDLING.tagNameCheck, we need to also allow derived custom elements using the same tagName test.\n // Additionally, we need to allow attributes passing the CUSTOM_ELEMENT_HANDLING.attributeNameCheck user has configured, as custom elements can define these at their own discretion.\n } else {\n return false;\n }\n /* Check value is safe. First, is attr inert? If so, is safe */\n } else if (URI_SAFE_ATTRIBUTES[lcName]) {\n // This attribute is safe\n /* Check no script, data or unknown possibly unsafe URI\n unless we know URI values are safe for that attribute */\n } else if (\n regExpTest(IS_ALLOWED_URI, stringReplace(value, ATTR_WHITESPACE, ''))\n ) {\n // This attribute is safe\n /* Keep image data URIs alive if src/xlink:href is allowed */\n /* Further prevent gadget XSS for dynamically built script tags */\n } else if (\n (lcName === 'src' || lcName === 'xlink:href' || lcName === 'href') &&\n lcTag !== 'script' &&\n stringIndexOf(value, 'data:') === 0 &&\n DATA_URI_TAGS[lcTag]\n ) {\n // This attribute is safe\n /* Allow unknown protocols: This provides support for links that\n are handled by protocol handlers which may be unknown ahead of\n time, e.g. fb:, spotify: */\n } else if (\n ALLOW_UNKNOWN_PROTOCOLS &&\n !regExpTest(IS_SCRIPT_OR_DATA, stringReplace(value, ATTR_WHITESPACE, ''))\n ) {\n // This attribute is safe\n /* Check for binary attributes */\n } else if (value) {\n return false;\n } else {\n // Binary attributes are safe at this point\n /* Anything else, presume unsafe, do not add it back */\n }\n\n return true;\n };\n\n /**\n * _isBasicCustomElement\n * checks if at least one dash is included in tagName, and it's not the first char\n * for more sophisticated checking see https://github.com/sindresorhus/validate-element-name\n *\n * @param tagName name of the tag of the node to sanitize\n * @returns Returns true if the tag name meets the basic criteria for a custom element, otherwise false.\n */\n const _isBasicCustomElement = function (tagName: string): RegExpMatchArray {\n return tagName !== 'annotation-xml' && stringMatch(tagName, CUSTOM_ELEMENT);\n };\n\n /**\n * _sanitizeAttributes\n *\n * @protect attributes\n * @protect nodeName\n * @protect removeAttribute\n * @protect setAttribute\n *\n * @param currentNode to sanitize\n */\n const _sanitizeAttributes = function (currentNode: Element): void {\n /* Execute a hook if present */\n _executeHooks(hooks.beforeSanitizeAttributes, currentNode, null);\n\n const { attributes } = currentNode;\n\n /* Check if we have attributes; if not we might have a text node */\n if (!attributes || _isClobbered(currentNode)) {\n return;\n }\n\n const hookEvent = {\n attrName: '',\n attrValue: '',\n keepAttr: true,\n allowedAttributes: ALLOWED_ATTR,\n forceKeepAttr: undefined,\n };\n let l = attributes.length;\n\n /* Go backwards over all attributes; safely remove bad ones */\n while (l--) {\n const attr = attributes[l];\n const { name, namespaceURI, value: attrValue } = attr;\n const lcName = transformCaseFunc(name);\n\n const initValue = attrValue;\n let value = name === 'value' ? initValue : stringTrim(initValue);\n\n /* Execute a hook if present */\n hookEvent.attrName = lcName;\n hookEvent.attrValue = value;\n hookEvent.keepAttr = true;\n hookEvent.forceKeepAttr = undefined; // Allows developers to see this is a property they can set\n _executeHooks(hooks.uponSanitizeAttribute, currentNode, hookEvent);\n value = hookEvent.attrValue;\n\n /* Full DOM Clobbering protection via namespace isolation,\n * Prefix id and name attributes with `user-content-`\n */\n if (SANITIZE_NAMED_PROPS && (lcName === 'id' || lcName === 'name')) {\n // Remove the attribute with this value\n _removeAttribute(name, currentNode);\n\n // Prefix the value and later re-create the attribute with the sanitized value\n value = SANITIZE_NAMED_PROPS_PREFIX + value;\n }\n\n /* Work around a security issue with comments inside attributes */\n if (\n SAFE_FOR_XML &&\n regExpTest(/((--!?|])>)|<\\/(style|title|textarea)/i, value)\n ) {\n _removeAttribute(name, currentNode);\n continue;\n }\n\n /* Make sure we cannot easily use animated hrefs, even if animations are allowed */\n if (lcName === 'attributename' && stringMatch(value, 'href')) {\n _removeAttribute(name, currentNode);\n continue;\n }\n\n /* Did the hooks approve of the attribute? */\n if (hookEvent.forceKeepAttr) {\n continue;\n }\n\n /* Did the hooks approve of the attribute? */\n if (!hookEvent.keepAttr) {\n _removeAttribute(name, currentNode);\n continue;\n }\n\n /* Work around a security issue in jQuery 3.0 */\n if (!ALLOW_SELF_CLOSE_IN_ATTR && regExpTest(/\\/>/i, value)) {\n _removeAttribute(name, currentNode);\n continue;\n }\n\n /* Sanitize attribute content to be template-safe */\n if (SAFE_FOR_TEMPLATES) {\n arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], (expr: RegExp) => {\n value = stringReplace(value, expr, ' ');\n });\n }\n\n /* Is `value` valid for this attribute? */\n const lcTag = transformCaseFunc(currentNode.nodeName);\n if (!_isValidAttribute(lcTag, lcName, value)) {\n _removeAttribute(name, currentNode);\n continue;\n }\n\n /* Handle attributes that require Trusted Types */\n if (\n trustedTypesPolicy &&\n typeof trustedTypes === 'object' &&\n typeof trustedTypes.getAttributeType === 'function'\n ) {\n if (namespaceURI) {\n /* Namespaces are not yet supported, see https://bugs.chromium.org/p/chromium/issues/detail?id=1305293 */\n } else {\n switch (trustedTypes.getAttributeType(lcTag, lcName)) {\n case 'TrustedHTML': {\n value = trustedTypesPolicy.createHTML(value);\n break;\n }\n\n case 'TrustedScriptURL': {\n value = trustedTypesPolicy.createScriptURL(value);\n break;\n }\n\n default: {\n break;\n }\n }\n }\n }\n\n /* Handle invalid data-* attribute set by try-catching it */\n if (value !== initValue) {\n try {\n if (namespaceURI) {\n currentNode.setAttributeNS(namespaceURI, name, value);\n } else {\n /* Fallback to setAttribute() for browser-unrecognized namespaces e.g. \"x-schema\". */\n currentNode.setAttribute(name, value);\n }\n\n if (_isClobbered(currentNode)) {\n _forceRemove(currentNode);\n } else {\n arrayPop(DOMPurify.removed);\n }\n } catch (_) {\n _removeAttribute(name, currentNode);\n }\n }\n }\n\n /* Execute a hook if present */\n _executeHooks(hooks.afterSanitizeAttributes, currentNode, null);\n };\n\n /**\n * _sanitizeShadowDOM\n *\n * @param fragment to iterate over recursively\n */\n const _sanitizeShadowDOM = function (fragment: DocumentFragment): void {\n let shadowNode = null;\n const shadowIterator = _createNodeIterator(fragment);\n\n /* Execute a hook if present */\n _executeHooks(hooks.beforeSanitizeShadowDOM, fragment, null);\n\n while ((shadowNode = shadowIterator.nextNode())) {\n /* Execute a hook if present */\n _executeHooks(hooks.uponSanitizeShadowNode, shadowNode, null);\n\n /* Sanitize tags and elements */\n _sanitizeElements(shadowNode);\n\n /* Check attributes next */\n _sanitizeAttributes(shadowNode);\n\n /* Deep shadow DOM detected */\n if (shadowNode.content instanceof DocumentFragment) {\n _sanitizeShadowDOM(shadowNode.content);\n }\n }\n\n /* Execute a hook if present */\n _executeHooks(hooks.afterSanitizeShadowDOM, fragment, null);\n };\n\n // eslint-disable-next-line complexity\n DOMPurify.sanitize = function (dirty, cfg = {}) {\n let body = null;\n let importedNode = null;\n let currentNode = null;\n let returnNode = null;\n /* Make sure we have a string to sanitize.\n DO NOT return early, as this will return the wrong type if\n the user has requested a DOM object rather than a string */\n IS_EMPTY_INPUT = !dirty;\n if (IS_EMPTY_INPUT) {\n dirty = '<!-->';\n }\n\n /* Stringify, in case dirty is an object */\n if (typeof dirty !== 'string' && !_isNode(dirty)) {\n if (typeof dirty.toString === 'function') {\n dirty = dirty.toString();\n if (typeof dirty !== 'string') {\n throw typeErrorCreate('dirty is not a string, aborting');\n }\n } else {\n throw typeErrorCreate('toString is not a function');\n }\n }\n\n /* Return dirty HTML if DOMPurify cannot run */\n if (!DOMPurify.isSupported) {\n return dirty;\n }\n\n /* Assign config vars */\n if (!SET_CONFIG) {\n _parseConfig(cfg);\n }\n\n /* Clean up removed elements */\n DOMPurify.removed = [];\n\n /* Check if dirty is correctly typed for IN_PLACE */\n if (typeof dirty === 'string') {\n IN_PLACE = false;\n }\n\n if (IN_PLACE) {\n /* Do some early pre-sanitization to avoid unsafe root nodes */\n if ((dirty as Node).nodeName) {\n const tagName = transformCaseFunc((dirty as Node).nodeName);\n if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {\n throw typeErrorCreate(\n 'root node is forbidden and cannot be sanitized in-place'\n );\n }\n }\n } else if (dirty instanceof Node) {\n /* If dirty is a DOM element, append to an empty document to avoid\n elements being stripped by the parser */\n body = _initDocument('<!---->');\n importedNode = body.ownerDocument.importNode(dirty, true);\n if (\n importedNode.nodeType === NODE_TYPE.element &&\n importedNode.nodeName === 'BODY'\n ) {\n /* Node is already a body, use as is */\n body = importedNode;\n } else if (importedNode.nodeName === 'HTML') {\n body = importedNode;\n } else {\n // eslint-disable-next-line unicorn/prefer-dom-node-append\n body.appendChild(importedNode);\n }\n } else {\n /* Exit directly if we have nothing to do */\n if (\n !RETURN_DOM &&\n !SAFE_FOR_TEMPLATES &&\n !WHOLE_DOCUMENT &&\n // eslint-disable-next-line unicorn/prefer-includes\n dirty.indexOf('<') === -1\n ) {\n return trustedTypesPolicy && RETURN_TRUSTED_TYPE\n ? trustedTypesPolicy.createHTML(dirty)\n : dirty;\n }\n\n /* Initialize the document to work on */\n body = _initDocument(dirty);\n\n /* Check we have a DOM node from the data */\n if (!body) {\n return RETURN_DOM ? null : RETURN_TRUSTED_TYPE ? emptyHTML : '';\n }\n }\n\n /* Remove first element node (ours) if FORCE_BODY is set */\n if (body && FORCE_BODY) {\n _forceRemove(body.firstChild);\n }\n\n /* Get node iterator */\n const nodeIterator = _createNodeIterator(IN_PLACE ? dirty : body);\n\n /* Now start iterating over the created document */\n while ((currentNode = nodeIterator.nextNode())) {\n /* Sanitize tags and elements */\n _sanitizeElements(currentNode);\n\n /* Check attributes next */\n _sanitizeAttributes(currentNode);\n\n /* Shadow DOM detected, sanitize it */\n if (currentNode.content instanceof DocumentFragment) {\n _sanitizeShadowDOM(currentNode.content);\n }\n }\n\n /* If we sanitized `dirty` in-place, return it. */\n if (IN_PLACE) {\n return dirty;\n }\n\n /* Return sanitized string or DOM */\n if (RETURN_DOM) {\n if (RETURN_DOM_FRAGMENT) {\n returnNode = createDocumentFragment.call(body.ownerDocument);\n\n while (body.firstChild) {\n // eslint-disable-next-line unicorn/prefer-dom-node-append\n returnNode.appendChild(body.firstChild);\n }\n } else {\n returnNode = body;\n }\n\n if (ALLOWED_ATTR.shadowroot || ALLOWED_ATTR.shadowrootmode) {\n /*\n AdoptNode() is not used because internal state is not reset\n (e.g. the past names map of a HTMLFormElement), this is safe\n in theory but we would rather not risk another attack vector.\n The state that is cloned by importNode() is explicitly defined\n by the specs.\n */\n returnNode = importNode.call(originalDocument, returnNode, true);\n }\n\n return returnNode;\n }\n\n let serializedHTML = WHOLE_DOCUMENT ? body.outerHTML : body.innerHTML;\n\n /* Serialize doctype if allowed */\n if (\n WHOLE_DOCUMENT &&\n ALLOWED_TAGS['!doctype'] &&\n body.ownerDocument &&\n body.ownerDocument.doctype &&\n body.ownerDocument.doctype.name &&\n regExpTest(EXPRESSIONS.DOCTYPE_NAME, body.ownerDocument.doctype.name)\n ) {\n serializedHTML =\n '<!DOCTYPE ' + body.ownerDocument.doctype.name + '>\\n' + serializedHTML;\n }\n\n /* Sanitize final string template-safe */\n if (SAFE_FOR_TEMPLATES) {\n arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], (expr: RegExp) => {\n serializedHTML = stringReplace(serializedHTML, expr, ' ');\n });\n }\n\n return trustedTypesPolicy && RETURN_TRUSTED_TYPE\n ? trustedTypesPolicy.createHTML(serializedHTML)\n : serializedHTML;\n };\n\n DOMPurify.setConfig = function (cfg = {}) {\n _parseConfig(cfg);\n SET_CONFIG = true;\n };\n\n DOMPurify.clearConfig = function () {\n CONFIG = null;\n SET_CONFIG = false;\n };\n\n DOMPurify.isValidAttribute = function (tag, attr, value) {\n /* Initialize shared config vars if necessary. */\n if (!CONFIG) {\n _parseConfig({});\n }\n\n const lcTag = transformCaseFunc(tag);\n const lcName = transformCaseFunc(attr);\n return _isValidAttribute(lcTag, lcName, value);\n };\n\n DOMPurify.addHook = function (\n entryPoint: keyof HooksMap,\n hookFunction: HookFunction\n ) {\n if (typeof hookFunction !== 'function') {\n return;\n }\n\n arrayPush(hooks[entryPoint], hookFunction);\n };\n\n DOMPurify.removeHook = function (\n entryPoint: keyof HooksMap,\n hookFunction: HookFunction\n ) {\n if (hookFunction !== undefined) {\n const index = arrayLastIndexOf(hooks[entryPoint], hookFunction);\n\n return index === -1\n ? undefined\n : arraySplice(hooks[entryPoint], index, 1)[0];\n }\n\n return arrayPop(hooks[entryPoint]);\n };\n\n DOMPurify.removeHooks = function (entryPoint: keyof HooksMap) {\n hooks[entryPoint] = [];\n };\n\n DOMPurify.removeAllHooks = function () {\n hooks = _createHooksMap();\n };\n\n return DOMPurify;\n}\n\nexport default createDOMPurify();\n\nexport interface DOMPurify {\n /**\n * Creates a DOMPurify instance using the given window-like object. Defaults to `window`.\n */\n (root?: WindowLike): DOMPurify;\n\n /**\n * Version label, exposed for easier checks\n * if DOMPurify is up to date or not\n */\n version: string;\n\n /**\n * Array of elements that DOMPurify removed during sanitation.\n * Empty if nothing was removed.\n */\n removed: Array<RemovedElement | RemovedAttribute>;\n\n /**\n * Expose whether this browser supports running the full DOMPurify.\n */\n isSupported: boolean;\n\n /**\n * Set the configuration once.\n *\n * @param cfg configuration object\n */\n setConfig(cfg?: Config): void;\n\n /**\n * Removes the configuration.\n */\n clearConfig(): void;\n\n /**\n * Provides core sanitation functionality.\n *\n * @param dirty string or DOM node\n * @param cfg object\n * @returns Sanitized TrustedHTML.\n */\n sanitize(\n dirty: string | Node,\n cfg: Config & { RETURN_TRUSTED_TYPE: true }\n ): TrustedHTML;\n\n /**\n * Provides core sanitation functionality.\n *\n * @param dirty DOM node\n * @param cfg object\n * @returns Sanitized DOM node.\n */\n sanitize(dirty: Node, cfg: Config & { IN_PLACE: true }): Node;\n\n /**\n * Provides core sanitation functionality.\n *\n * @param dirty string or DOM node\n * @param cfg object\n * @returns Sanitized DOM node.\n */\n sanitize(dirty: string | Node, cfg: Config & { RETURN_DOM: true }): Node;\n\n /**\n * Provides core sanitation functionality.\n *\n * @param dirty string or DOM node\n * @param cfg object\n * @returns Sanitized document fragment.\n */\n sanitize(\n dirty: string | Node,\n cfg: Config & { RETURN_DOM_FRAGMENT: true }\n ): DocumentFragment;\n\n /**\n * Provides core sanitation functionality.\n *\n * @param dirty string or DOM node\n * @param cfg object\n * @returns Sanitized string.\n */\n sanitize(dirty: string | Node, cfg?: Config): string;\n\n /**\n * Checks if an attribute value is valid.\n * Uses last set config, if any. Otherwise, uses config defaults.\n *\n * @param tag Tag name of containing element.\n * @param attr Attribute name.\n * @param value Attribute value.\n * @returns Returns true if `value` is valid. Otherwise, returns false.\n */\n isValidAttribute(tag: string, attr: string, value: string): boolean;\n\n /**\n * Adds a DOMPurify hook.\n *\n * @param entryPoint entry point for the hook to add\n * @param hookFunction function to execute\n */\n addHook(entryPoint: BasicHookName, hookFunction: NodeHook): void;\n\n /**\n * Adds a DOMPurify hook.\n *\n * @param entryPoint entry point for the hook to add\n * @param hookFunction function to execute\n */\n addHook(entryPoint: ElementHookName, hookFunction: ElementHook): void;\n\n /**\n * Adds a DOMPurify hook.\n *\n * @param entryPoint entry point for the hook to add\n * @param hookFunction function to execute\n */\n addHook(\n entryPoint: DocumentFragmentHookName,\n hookFunction: DocumentFragmentHook\n ): void;\n\n /**\n * Adds a DOMPurify hook.\n *\n * @param entryPoint entry point for the hook to add\n * @param hookFunction function to execute\n */\n addHook(\n entryPoint: 'uponSanitizeElement',\n hookFunction: UponSanitizeElementHook\n ): void;\n\n /**\n * Adds a DOMPurify hook.\n *\n * @param entryPoint entry point for the hook to add\n * @param hookFunction function to execute\n */\n addHook(\n entryPoint: 'uponSanitizeAttribute',\n hookFunction: UponSanitizeAttributeHook\n ): void;\n\n /**\n * Remove a DOMPurify hook at a given entryPoint\n * (pops it from the stack of hooks if hook not specified)\n *\n * @param entryPoint entry point for the hook to remove\n * @param hookFunction optional specific hook to remove\n * @returns removed hook\n */\n removeHook(\n entryPoint: BasicHookName,\n hookFunction?: NodeHook\n ): NodeHook | undefined;\n\n /**\n * Remove a DOMPurify hook at a given entryPoint\n * (pops it from the stack of hooks if hook not specified)\n *\n * @param entryPoint entry point for the hook to remove\n * @param hookFunction optional specific hook to remove\n * @returns removed hook\n */\n removeHook(\n entryPoint: ElementHookName,\n hookFunction?: ElementHook\n ): ElementHook | undefined;\n\n /**\n * Remove a DOMPurify hook at a given entryPoint\n * (pops it from the stack of hooks if hook not specified)\n *\n * @param entryPoint entry point for the hook to remove\n * @param hookFunction optional specific hook to remove\n * @returns removed hook\n */\n removeHook(\n entryPoint: DocumentFragmentHookName,\n hookFunction?: DocumentFragmentHook\n ): DocumentFragmentHook | undefined;\n\n /**\n * Remove a DOMPurify hook at a given entryPoint\n * (pops it from the stack of hooks if hook not specified)\n *\n * @param entryPoint entry point for the hook to remove\n * @param hookFunction optional specific hook to remove\n * @returns removed hook\n */\n removeHook(\n entryPoint: 'uponSanitizeElement',\n hookFunction?: UponSanitizeElementHook\n ): UponSanitizeElementHook | undefined;\n\n /**\n * Remove a DOMPurify hook at a given entryPoint\n * (pops it from the stack of hooks if hook not specified)\n *\n * @param entryPoint entry point for the hook to remove\n * @param hookFunction optional specific hook to remove\n * @returns removed hook\n */\n removeHook(\n entryPoint: 'uponSanitizeAttribute',\n hookFunction?: UponSanitizeAttributeHook\n ): UponSanitizeAttributeHook | undefined;\n\n /**\n * Removes all DOMPurify hooks at a given entryPoint\n *\n * @param entryPoint entry point for the hooks to remove\n */\n removeHooks(entryPoint: HookName): void;\n\n /**\n * Removes all DOMPurify hooks.\n */\n removeAllHooks(): void;\n}\n\n/**\n * An element removed by DOMPurify.\n */\nexport interface RemovedElement {\n /**\n * The element that was removed.\n */\n element: Node;\n}\n\n/**\n * An element removed by DOMPurify.\n */\nexport interface RemovedAttribute {\n /**\n * The attribute that was removed.\n */\n attribute: Attr | null;\n\n /**\n * The element that the attribute was removed.\n */\n from: Node;\n}\n\ntype BasicHookName =\n | 'beforeSanitizeElements'\n | 'afterSanitizeElements'\n | 'uponSanitizeShadowNode';\ntype ElementHookName = 'beforeSanitizeAttributes' | 'afterSanitizeAttributes';\ntype DocumentFragmentHookName =\n | 'beforeSanitizeShadowDOM'\n | 'afterSanitizeShadowDOM';\ntype UponSanitizeElementHookName = 'uponSanitizeElement';\ntype UponSanitizeAttributeHookName = 'uponSanitizeAttribute';\n\ninterface HooksMap {\n beforeSanitizeElements: NodeHook[];\n afterSanitizeElements: NodeHook[];\n beforeSanitizeShadowDOM: DocumentFragmentHook[];\n uponSanitizeShadowNode: NodeHook[];\n afterSanitizeShadowDOM: DocumentFragmentHook[];\n beforeSanitizeAttributes: ElementHook[];\n afterSanitizeAttributes: ElementHook[];\n uponSanitizeElement: UponSanitizeElementHook[];\n uponSanitizeAttribute: UponSanitizeAttributeHook[];\n}\n\ntype ArrayElement<T> = T extends Array<infer U> ? U : never;\n\ntype HookFunction = ArrayElement<HooksMap[keyof HooksMap]>;\n\nexport type HookName =\n | BasicHookName\n | ElementHookName\n | DocumentFragmentHookName\n | UponSanitizeElementHookName\n | UponSanitizeAttributeHookName;\n\nexport type NodeHook = (\n this: DOMPurify,\n currentNode: Node,\n hookEvent: null,\n config: Config\n) => void;\n\nexport type ElementHook = (\n this: DOMPurify,\n currentNode: Element,\n hookEvent: null,\n config: Config\n) => void;\n\nexport type DocumentFragmentHook = (\n this: DOMPurify,\n currentNode: DocumentFragment,\n hookEvent: null,\n config: Config\n) => void;\n\nexport type UponSanitizeElementHook = (\n this: DOMPurify,\n currentNode: Node,\n hookEvent: UponSanitizeElementHookEvent,\n config: Config\n) => void;\n\nexport type UponSanitizeAttributeHook = (\n this: DOMPurify,\n currentNode: Element,\n hookEvent: UponSanitizeAttributeHookEvent,\n config: Config\n) => void;\n\nexport interface UponSanitizeElementHookEvent {\n tagName: string;\n allowedTags: Record<string, boolean>;\n}\n\nexport interface UponSanitizeAttributeHookEvent {\n attrName: string;\n attrValue: string;\n keepAttr: boolean;\n allowedAttributes: Record<string, boolean>;\n forceKeepAttr: boolean | undefined;\n}\n\n/**\n * A `Window`-like object containing the properties and types that DOMPurify requires.\n */\nexport type WindowLike = Pick<\n typeof globalThis,\n | 'DocumentFragment'\n | 'HTMLTemplateElement'\n | 'Node'\n | 'Element'\n | 'NodeFilter'\n | 'NamedNodeMap'\n | 'HTMLFormElement'\n | 'DOMParser'\n> & {\n document?: Document;\n MozNamedAttrMap?: typeof window.NamedNodeMap;\n} & Pick<TrustedTypesWindow, 'trustedTypes'>;\n", "/**\n * @license\n * Copyright 2017 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\n\nimport {Disconnectable, Part} from './lit-html.js';\n\nexport {\n AttributePart,\n BooleanAttributePart,\n ChildPart,\n ElementPart,\n EventPart,\n Part,\n PropertyPart,\n} from './lit-html.js';\n\nexport interface DirectiveClass {\n new (part: PartInfo): Directive;\n}\n\n/**\n * This utility type extracts the signature of a directive class's render()\n * method so we can use it for the type of the generated directive function.\n */\nexport type DirectiveParameters<C extends Directive> = Parameters<C['render']>;\n\n/**\n * A generated directive function doesn't evaluate the directive, but just\n * returns a DirectiveResult object that captures the arguments.\n */\nexport interface DirectiveResult<C extends DirectiveClass = DirectiveClass> {\n /**\n * This property needs to remain unminified.\n * @internal\n */\n ['_$litDirective$']: C;\n /** @internal */\n values: DirectiveParameters<InstanceType<C>>;\n}\n\nexport const PartType = {\n ATTRIBUTE: 1,\n CHILD: 2,\n PROPERTY: 3,\n BOOLEAN_ATTRIBUTE: 4,\n EVENT: 5,\n ELEMENT: 6,\n} as const;\n\nexport type PartType = (typeof PartType)[keyof typeof PartType];\n\nexport interface ChildPartInfo {\n readonly type: typeof PartType.CHILD;\n}\n\nexport interface AttributePartInfo {\n readonly type:\n | typeof PartType.ATTRIBUTE\n | typeof PartType.PROPERTY\n | typeof PartType.BOOLEAN_ATTRIBUTE\n | typeof PartType.EVENT;\n readonly strings?: ReadonlyArray<string>;\n readonly name: string;\n readonly tagName: string;\n}\n\nexport interface ElementPartInfo {\n readonly type: typeof PartType.ELEMENT;\n}\n\n/**\n * Information about the part a directive is bound to.\n *\n * This is useful for checking that a directive is attached to a valid part,\n * such as with directive that can only be used on attribute bindings.\n */\nexport type PartInfo = ChildPartInfo | AttributePartInfo | ElementPartInfo;\n\n/**\n * Creates a user-facing directive function from a Directive class. This\n * function has the same parameters as the directive's render() method.\n */\nexport const directive =\n <C extends DirectiveClass>(c: C) =>\n (...values: DirectiveParameters<InstanceType<C>>): DirectiveResult<C> => ({\n // This property needs to remain unminified.\n ['_$litDirective$']: c,\n values,\n });\n\n/**\n * Base class for creating custom directives. Users should extend this class,\n * implement `render` and/or `update`, and then pass their subclass to\n * `directive`.\n */\nexport abstract class Directive implements Disconnectable {\n //@internal\n __part!: Part;\n //@internal\n __attributeIndex: number | undefined;\n //@internal\n __directive?: Directive;\n\n //@internal\n _$parent!: Disconnectable;\n\n // These will only exist on the AsyncDirective subclass\n //@internal\n _$disconnectableChildren?: Set<Disconnectable>;\n // This property needs to remain unminified.\n //@internal\n ['_$notifyDirectiveConnectionChanged']?(isConnected: boolean): void;\n\n constructor(_partInfo: PartInfo) {}\n\n // See comment in Disconnectable interface for why this is a getter\n get _$isConnected() {\n return this._$parent._$isConnected;\n }\n\n /** @internal */\n _$initialize(\n part: Part,\n parent: Disconnectable,\n attributeIndex: number | undefined\n ) {\n this.__part = part;\n this._$parent = parent;\n this.__attributeIndex = attributeIndex;\n }\n /** @internal */\n _$resolve(part: Part, props: Array<unknown>): unknown {\n return this.update(part, props);\n }\n\n abstract render(...props: Array<unknown>): unknown;\n\n update(_part: Part, props: Array<unknown>): unknown {\n return this.render(...props);\n }\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\n\nimport {nothing, TemplateResult, noChange} from '../lit-html.js';\nimport {directive, Directive, PartInfo, PartType} from '../directive.js';\n\nconst HTML_RESULT = 1;\n\nexport class UnsafeHTMLDirective extends Directive {\n static directiveName = 'unsafeHTML';\n static resultType = HTML_RESULT;\n\n private _value: unknown = nothing;\n private _templateResult?: TemplateResult;\n\n constructor(partInfo: PartInfo) {\n super(partInfo);\n if (partInfo.type !== PartType.CHILD) {\n throw new Error(\n `${\n (this.constructor as typeof UnsafeHTMLDirective).directiveName\n }() can only be used in child bindings`\n );\n }\n }\n\n render(value: string | typeof nothing | typeof noChange | undefined | null) {\n if (value === nothing || value == null) {\n this._templateResult = undefined;\n return (this._value = value);\n }\n if (value === noChange) {\n return value;\n }\n if (typeof value != 'string') {\n throw new Error(\n `${\n (this.constructor as typeof UnsafeHTMLDirective).directiveName\n }() called with a non-string value`\n );\n }\n if (value === this._value) {\n return this._templateResult;\n }\n this._value = value;\n const strings = [value] as unknown as TemplateStringsArray;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (strings as any).raw = strings;\n // WARNING: impersonating a TemplateResult like this is extremely\n // dangerous. Third-party directives should not do this.\n return (this._templateResult = {\n // Cast to a known set of integers that satisfy ResultType so that we\n // don't have to export ResultType and possibly encourage this pattern.\n // This property needs to remain unminified.\n ['_$litType$']: (this.constructor as typeof UnsafeHTMLDirective)\n .resultType as 1 | 2,\n strings,\n values: [],\n });\n }\n}\n\n/**\n * Renders the result as HTML, rather than text.\n *\n * The values `undefined`, `null`, and `nothing`, will all result in no content\n * (empty string) being rendered.\n *\n * Note, this is unsafe to use with any user-provided input that hasn't been\n * sanitized or escaped, as it may lead to cross-site-scripting\n * vulnerabilities.\n */\nexport const unsafeHTML = directive(UnsafeHTMLDirective);\n", "import type { MarkedOptions } from './MarkedOptions.ts';\n\n/**\n * Gets the original marked default options.\n */\nexport function _getDefaults<ParserOutput = string, RendererOutput = string>(): MarkedOptions<ParserOutput, RendererOutput> {\n return {\n async: false,\n breaks: false,\n extensions: null,\n gfm: true,\n hooks: null,\n pedantic: false,\n renderer: null,\n silent: false,\n tokenizer: null,\n walkTokens: null,\n };\n}\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport let _defaults: MarkedOptions<any, any> = _getDefaults();\n\nexport function changeDefaults<ParserOutput = string, RendererOutput = string>(newDefaults: MarkedOptions<ParserOutput, RendererOutput>) {\n _defaults = newDefaults;\n}\n", "const noopTest = { exec: () => null } as unknown as RegExp;\n\nfunction edit(regex: string | RegExp, opt = '') {\n let source = typeof regex === 'string' ? regex : regex.source;\n const obj = {\n replace: (name: string | RegExp, val: string | RegExp) => {\n let valSource = typeof val === 'string' ? val : val.source;\n valSource = valSource.replace(other.caret, '$1');\n source = source.replace(name, valSource);\n return obj;\n },\n getRegex: () => {\n return new RegExp(source, opt);\n },\n };\n return obj;\n}\n\nconst supportsLookbehind = (() => {\ntry {\n // eslint-disable-next-line prefer-regex-literals\n return !!new RegExp('(?<=1)(?<!1)');\n} catch {\n // See browser support here:\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Lookbehind_assertion\n return false;\n}\n})();\n\nexport const other = {\n codeRemoveIndent: /^(?: {1,4}| {0,3}\\t)/gm,\n outputLinkReplace: /\\\\([\\[\\]])/g,\n indentCodeCompensation: /^(\\s+)(?:```)/,\n beginningSpace: /^\\s+/,\n endingHash: /#$/,\n startingSpaceChar: /^ /,\n endingSpaceChar: / $/,\n nonSpaceChar: /[^ ]/,\n newLineCharGlobal: /\\n/g,\n tabCharGlobal: /\\t/g,\n multipleSpaceGlobal: /\\s+/g,\n blankLine: /^[ \\t]*$/,\n doubleBlankLine: /\\n[ \\t]*\\n[ \\t]*$/,\n blockquoteStart: /^ {0,3}>/,\n blockquoteSetextReplace: /\\n {0,3}((?:=+|-+) *)(?=\\n|$)/g,\n blockquoteSetextReplace2: /^ {0,3}>[ \\t]?/gm,\n listReplaceTabs: /^\\t+/,\n listReplaceNesting: /^ {1,4}(?=( {4})*[^ ])/g,\n listIsTask: /^\\[[ xX]\\] +\\S/,\n listReplaceTask: /^\\[[ xX]\\] +/,\n listTaskCheckbox: /\\[[ xX]\\]/,\n anyLine: /\\n.*\\n/,\n hrefBrackets: /^<(.*)>$/,\n tableDelimiter: /[:|]/,\n tableAlignChars: /^\\||\\| *$/g,\n tableRowBlankLine: /\\n[ \\t]*$/,\n tableAlignRight: /^ *-+: *$/,\n tableAlignCenter: /^ *:-+: *$/,\n tableAlignLeft: /^ *:-+ *$/,\n startATag: /^<a /i,\n endATag: /^<\\/a>/i,\n startPreScriptTag: /^<(pre|code|kbd|script)(\\s|>)/i,\n endPreScriptTag: /^<\\/(pre|code|kbd|script)(\\s|>)/i,\n startAngleBracket: /^</,\n endAngleBracket: />$/,\n pedanticHrefTitle: /^([^'\"]*[^\\s])\\s+(['\"])(.*)\\2/,\n unicodeAlphaNumeric: /[\\p{L}\\p{N}]/u,\n escapeTest: /[&<>\"']/,\n escapeReplace: /[&<>\"']/g,\n escapeTestNoEncode: /[<>\"']|&(?!(#\\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\\w+);)/,\n escapeReplaceNoEncode: /[<>\"']|&(?!(#\\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\\w+);)/g,\n unescapeTest: /&(#(?:\\d+)|(?:#x[0-9A-Fa-f]+)|(?:\\w+));?/ig,\n caret: /(^|[^\\[])\\^/g,\n percentDecode: /%25/g,\n findPipe: /\\|/g,\n splitPipe: / \\|/,\n slashPipe: /\\\\\\|/g,\n carriageReturn: /\\r\\n|\\r/g,\n spaceLine: /^ +$/gm,\n notSpaceStart: /^\\S*/,\n endingNewline: /\\n$/,\n listItemRegex: (bull: string) => new RegExp(`^( {0,3}${bull})((?:[\\t ][^\\\\n]*)?(?:\\\\n|$))`),\n nextBulletRegex: (indent: number) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}(?:[*+-]|\\\\d{1,9}[.)])((?:[ \\t][^\\\\n]*)?(?:\\\\n|$))`),\n hrRegex: (indent: number) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\\\* *){3,})(?:\\\\n+|$)`),\n fencesBeginRegex: (indent: number) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}(?:\\`\\`\\`|~~~)`),\n headingBeginRegex: (indent: number) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}#`),\n htmlBeginRegex: (indent: number) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}<(?:[a-z].*>|!--)`, 'i'),\n};\n\n/**\n * Block-Level Grammar\n */\n\nconst newline = /^(?:[ \\t]*(?:\\n|$))+/;\nconst blockCode = /^((?: {4}| {0,3}\\t)[^\\n]+(?:\\n(?:[ \\t]*(?:\\n|$))*)?)+/;\nconst fences = /^ {0,3}(`{3,}(?=[^`\\n]*(?:\\n|$))|~{3,})([^\\n]*)(?:\\n|$)(?:|([\\s\\S]*?)(?:\\n|$))(?: {0,3}\\1[~`]* *(?=\\n|$)|$)/;\nconst hr = /^ {0,3}((?:-[\\t ]*){3,}|(?:_[ \\t]*){3,}|(?:\\*[ \\t]*){3,})(?:\\n+|$)/;\nconst heading = /^ {0,3}(#{1,6})(?=\\s|$)(.*)(?:\\n+|$)/;\nconst bullet = /(?:[*+-]|\\d{1,9}[.)])/;\nconst lheadingCore = /^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\\n(?!\\s*?\\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\\n {0,3}(=+|-+) *(?:\\n+|$)/;\nconst lheading = edit(lheadingCore)\n .replace(/bull/g, bullet) // lists can interrupt\n .replace(/blockCode/g, /(?: {4}| {0,3}\\t)/) // indented code blocks can interrupt\n .replace(/fences/g, / {0,3}(?:`{3,}|~{3,})/) // fenced code blocks can interrupt\n .replace(/blockquote/g, / {0,3}>/) // blockquote can interrupt\n .replace(/heading/g, / {0,3}#{1,6}/) // ATX heading can interrupt\n .replace(/html/g, / {0,3}<[^\\n>]+>\\n/) // block html can interrupt\n .replace(/\\|table/g, '') // table not in commonmark\n .getRegex();\nconst lheadingGfm = edit(lheadingCore)\n .replace(/bull/g, bullet) // lists can interrupt\n .replace(/blockCode/g, /(?: {4}| {0,3}\\t)/) // indented code blocks can interrupt\n .replace(/fences/g, / {0,3}(?:`{3,}|~{3,})/) // fenced code blocks can interrupt\n .replace(/blockquote/g, / {0,3}>/) // blockquote can interrupt\n .replace(/heading/g, / {0,3}#{1,6}/) // ATX heading can interrupt\n .replace(/html/g, / {0,3}<[^\\n>]+>\\n/) // block html can interrupt\n .replace(/table/g, / {0,3}\\|?(?:[:\\- ]*\\|)+[\\:\\- ]*\\n/) // table can interrupt\n .getRegex();\nconst _paragraph = /^([^\\n]+(?:\\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\\n)[^\\n]+)*)/;\nconst blockText = /^[^\\n]+/;\nconst _blockLabel = /(?!\\s*\\])(?:\\\\[\\s\\S]|[^\\[\\]\\\\])+/;\nconst def = edit(/^ {0,3}\\[(label)\\]: *(?:\\n[ \\t]*)?([^<\\s][^\\s]*|<.*?>)(?:(?: +(?:\\n[ \\t]*)?| *\\n[ \\t]*)(title))? *(?:\\n+|$)/)\n .replace('label', _blockLabel)\n .replace('title', /(?:\"(?:\\\\\"?|[^\"\\\\])*\"|'[^'\\n]*(?:\\n[^'\\n]+)*\\n?'|\\([^()]*\\))/)\n .getRegex();\n\nconst list = edit(/^( {0,3}bull)([ \\t][^\\n]+?)?(?:\\n|$)/)\n .replace(/bull/g, bullet)\n .getRegex();\n\nconst _tag = 'address|article|aside|base|basefont|blockquote|body|caption'\n + '|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption'\n + '|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe'\n + '|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option'\n + '|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title'\n + '|tr|track|ul';\nconst _comment = /<!--(?:-?>|[\\s\\S]*?(?:-->|$))/;\nconst html = edit(\n '^ {0,3}(?:' // optional indentation\n+ '<(script|pre|style|textarea)[\\\\s>][\\\\s\\\\S]*?(?:</\\\\1>[^\\\\n]*\\\\n+|$)' // (1)\n+ '|comment[^\\\\n]*(\\\\n+|$)' // (2)\n+ '|<\\\\?[\\\\s\\\\S]*?(?:\\\\?>\\\\n*|$)' // (3)\n+ '|<![A-Z][\\\\s\\\\S]*?(?:>\\\\n*|$)' // (4)\n+ '|<!\\\\[CDATA\\\\[[\\\\s\\\\S]*?(?:\\\\]\\\\]>\\\\n*|$)' // (5)\n+ '|</?(tag)(?: +|\\\\n|/?>)[\\\\s\\\\S]*?(?:(?:\\\\n[ \\t]*)+\\\\n|$)' // (6)\n+ '|<(?!script|pre|style|textarea)([a-z][\\\\w-]*)(?:attribute)*? */?>(?=[ \\\\t]*(?:\\\\n|$))[\\\\s\\\\S]*?(?:(?:\\\\n[ \\t]*)+\\\\n|$)' // (7) open tag\n+ '|</(?!script|pre|style|textarea)[a-z][\\\\w-]*\\\\s*>(?=[ \\\\t]*(?:\\\\n|$))[\\\\s\\\\S]*?(?:(?:\\\\n[ \\t]*)+\\\\n|$)' // (7) closing tag\n+ ')', 'i')\n .replace('comment', _comment)\n .replace('tag', _tag)\n .replace('attribute', / +[a-zA-Z:_][\\w.:-]*(?: *= *\"[^\"\\n]*\"| *= *'[^'\\n]*'| *= *[^\\s\"'=<>`]+)?/)\n .getRegex();\n\nconst paragraph = edit(_paragraph)\n .replace('hr', hr)\n .replace('heading', ' {0,3}#{1,6}(?:\\\\s|$)')\n .replace('|lheading', '') // setext headings don't interrupt commonmark paragraphs\n .replace('|table', '')\n .replace('blockquote', ' {0,3}>')\n .replace('fences', ' {0,3}(?:`{3,}(?=[^`\\\\n]*\\\\n)|~{3,})[^\\\\n]*\\\\n')\n .replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt\n .replace('html', '</?(?:tag)(?: +|\\\\n|/?>)|<(?:script|pre|style|textarea|!--)')\n .replace('tag', _tag) // pars can be interrupted by type (6) html blocks\n .getRegex();\n\nconst blockquote = edit(/^( {0,3}> ?(paragraph|[^\\n]*)(?:\\n|$))+/)\n .replace('paragraph', paragraph)\n .getRegex();\n\n/**\n * Normal Block Grammar\n */\n\nconst blockNormal = {\n blockquote,\n code: blockCode,\n def,\n fences,\n heading,\n hr,\n html,\n lheading,\n list,\n newline,\n paragraph,\n table: noopTest,\n text: blockText,\n};\n\ntype BlockKeys = keyof typeof blockNormal;\n\n/**\n * GFM Block Grammar\n */\n\nconst gfmTable = edit(\n '^ *([^\\\\n ].*)\\\\n' // Header\n+ ' {0,3}((?:\\\\| *)?:?-+:? *(?:\\\\| *:?-+:? *)*(?:\\\\| *)?)' // Align\n+ '(?:\\\\n((?:(?! *\\\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\\\n|$))*)\\\\n*|$)') // Cells\n .replace('hr', hr)\n .replace('heading', ' {0,3}#{1,6}(?:\\\\s|$)')\n .replace('blockquote', ' {0,3}>')\n .replace('code', '(?: {4}| {0,3}\\t)[^\\\\n]')\n .replace('fences', ' {0,3}(?:`{3,}(?=[^`\\\\n]*\\\\n)|~{3,})[^\\\\n]*\\\\n')\n .replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt\n .replace('html', '</?(?:tag)(?: +|\\\\n|/?>)|<(?:script|pre|style|textarea|!--)')\n .replace('tag', _tag) // tables can be interrupted by type (6) html blocks\n .getRegex();\n\nconst blockGfm: Record<BlockKeys, RegExp> = {\n ...blockNormal,\n lheading: lheadingGfm,\n table: gfmTable,\n paragraph: edit(_paragraph)\n .replace('hr', hr)\n .replace('heading', ' {0,3}#{1,6}(?:\\\\s|$)')\n .replace('|lheading', '') // setext headings don't interrupt commonmark paragraphs\n .replace('table', gfmTable) // interrupt paragraphs with table\n .replace('blockquote', ' {0,3}>')\n .replace('fences', ' {0,3}(?:`{3,}(?=[^`\\\\n]*\\\\n)|~{3,})[^\\\\n]*\\\\n')\n .replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt\n .replace('html', '</?(?:tag)(?: +|\\\\n|/?>)|<(?:script|pre|style|textarea|!--)')\n .replace('tag', _tag) // pars can be interrupted by type (6) html blocks\n .getRegex(),\n};\n\n/**\n * Pedantic grammar (original John Gruber's loose markdown specification)\n */\n\nconst blockPedantic: Record<BlockKeys, RegExp> = {\n ...blockNormal,\n html: edit(\n '^ *(?:comment *(?:\\\\n|\\\\s*$)'\n + '|<(tag)[\\\\s\\\\S]+?</\\\\1> *(?:\\\\n{2,}|\\\\s*$)' // closed tag\n + '|<tag(?:\"[^\"]*\"|\\'[^\\']*\\'|\\\\s[^\\'\"/>\\\\s]*)*?/?> *(?:\\\\n{2,}|\\\\s*$))')\n .replace('comment', _comment)\n .replace(/tag/g, '(?!(?:'\n + 'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub'\n + '|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)'\n + '\\\\b)\\\\w+(?!:|[^\\\\w\\\\s@]*@)\\\\b')\n .getRegex(),\n def: /^ *\\[([^\\]]+)\\]: *<?([^\\s>]+)>?(?: +([\"(][^\\n]+[\")]))? *(?:\\n+|$)/,\n heading: /^(#{1,6})(.*)(?:\\n+|$)/,\n fences: noopTest, // fences not supported\n lheading: /^(.+?)\\n {0,3}(=+|-+) *(?:\\n+|$)/,\n paragraph: edit(_paragraph)\n .replace('hr', hr)\n .replace('heading', ' *#{1,6} *[^\\n]')\n .replace('lheading', lheading)\n .replace('|table', '')\n .replace('blockquote', ' {0,3}>')\n .replace('|fences', '')\n .replace('|list', '')\n .replace('|html', '')\n .replace('|tag', '')\n .getRegex(),\n};\n\n/**\n * Inline-Level Grammar\n */\n\nconst escape = /^\\\\([!\"#$%&'()*+,\\-./:;<=>?@\\[\\]\\\\^_`{|}~])/;\nconst inlineCode = /^(`+)([^`]|[^`][\\s\\S]*?[^`])\\1(?!`)/;\nconst br = /^( {2,}|\\\\)\\n(?!\\s*$)/;\nconst inlineText = /^(`+|[^`])(?:(?= {2,}\\n)|[\\s\\S]*?(?:(?=[\\\\<!\\[`*_]|\\b_|$)|[^ ](?= {2,}\\n)))/;\n\n// list of unicode punctuation marks, plus any missing characters from CommonMark spec\nconst _punctuation = /[\\p{P}\\p{S}]/u;\nconst _punctuationOrSpace = /[\\s\\p{P}\\p{S}]/u;\nconst _notPunctuationOrSpace = /[^\\s\\p{P}\\p{S}]/u;\nconst punctuation = edit(/^((?![*_])punctSpace)/, 'u')\n .replace(/punctSpace/g, _punctuationOrSpace).getRegex();\n\n// GFM allows ~ inside strong and em for strikethrough\nconst _punctuationGfmStrongEm = /(?!~)[\\p{P}\\p{S}]/u;\nconst _punctuationOrSpaceGfmStrongEm = /(?!~)[\\s\\p{P}\\p{S}]/u;\nconst _notPunctuationOrSpaceGfmStrongEm = /(?:[^\\s\\p{P}\\p{S}]|~)/u;\n\n// sequences em should skip over [title](link), `code`, <html>\nconst blockSkip = edit(/link|precode-code|html/, 'g')\n .replace('link', /\\[(?:[^\\[\\]`]|(?<a>`+)[^`]+\\k<a>(?!`))*?\\]\\((?:\\\\[\\s\\S]|[^\\\\\\(\\)]|\\((?:\\\\[\\s\\S]|[^\\\\\\(\\)])*\\))*\\)/)\n .replace('precode-', supportsLookbehind ? '(?<!`)()' : '(^^|[^`])')\n .replace('code', /(?<b>`+)[^`]+\\k<b>(?!`)/)\n .replace('html', /<(?! )[^<>]*?>/)\n .getRegex();\n\nconst emStrongLDelimCore = /^(?:\\*+(?:((?!\\*)punct)|[^\\s*]))|^_+(?:((?!_)punct)|([^\\s_]))/;\n\nconst emStrongLDelim = edit(emStrongLDelimCore, 'u')\n .replace(/punct/g, _punctuation)\n .getRegex();\n\nconst emStrongLDelimGfm = edit(emStrongLDelimCore, 'u')\n .replace(/punct/g, _punctuationGfmStrongEm)\n .getRegex();\n\nconst emStrongRDelimAstCore =\n '^[^_*]*?__[^_*]*?\\\\*[^_*]*?(?=__)' // Skip orphan inside strong\n+ '|[^*]+(?=[^*])' // Consume to delim\n+ '|(?!\\\\*)punct(\\\\*+)(?=[\\\\s]|$)' // (1) #*** can only be a Right Delimiter\n+ '|notPunctSpace(\\\\*+)(?!\\\\*)(?=punctSpace|$)' // (2) a***#, a*** can only be a Right Delimiter\n+ '|(?!\\\\*)punctSpace(\\\\*+)(?=notPunctSpace)' // (3) #***a, ***a can only be Left Delimiter\n+ '|[\\\\s](\\\\*+)(?!\\\\*)(?=punct)' // (4) ***# can only be Left Delimiter\n+ '|(?!\\\\*)punct(\\\\*+)(?!\\\\*)(?=punct)' // (5) #***# can be either Left or Right Delimiter\n+ '|notPunctSpace(\\\\*+)(?=notPunctSpace)'; // (6) a***a can be either Left or Right Delimiter\n\nconst emStrongRDelimAst = edit(emStrongRDelimAstCore, 'gu')\n .replace(/notPunctSpace/g, _notPunctuationOrSpace)\n .replace(/punctSpace/g, _punctuationOrSpace)\n .replace(/punct/g, _punctuation)\n .getRegex();\n\nconst emStrongRDelimAstGfm = edit(emStrongRDelimAstCore, 'gu')\n .replace(/notPunctSpace/g, _notPunctuationOrSpaceGfmStrongEm)\n .replace(/punctSpace/g, _punctuationOrSpaceGfmStrongEm)\n .replace(/punct/g, _punctuationGfmStrongEm)\n .getRegex();\n\n// (6) Not allowed for _\nconst emStrongRDelimUnd = edit(\n '^[^_*]*?\\\\*\\\\*[^_*]*?_[^_*]*?(?=\\\\*\\\\*)' // Skip orphan inside strong\n+ '|[^_]+(?=[^_])' // Consume to delim\n+ '|(?!_)punct(_+)(?=[\\\\s]|$)' // (1) #___ can only be a Right Delimiter\n+ '|notPunctSpace(_+)(?!_)(?=punctSpace|$)' // (2) a___#, a___ can only be a Right Delimiter\n+ '|(?!_)punctSpace(_+)(?=notPunctSpace)' // (3) #___a, ___a can only be Left Delimiter\n+ '|[\\\\s](_+)(?!_)(?=punct)' // (4) ___# can only be Left Delimiter\n+ '|(?!_)punct(_+)(?!_)(?=punct)', 'gu') // (5) #___# can be either Left or Right Delimiter\n .replace(/notPunctSpace/g, _notPunctuationOrSpace)\n .replace(/punctSpace/g, _punctuationOrSpace)\n .replace(/punct/g, _punctuation)\n .getRegex();\n\nconst anyPunctuation = edit(/\\\\(punct)/, 'gu')\n .replace(/punct/g, _punctuation)\n .getRegex();\n\nconst autolink = edit(/^<(scheme:[^\\s\\x00-\\x1f<>]*|email)>/)\n .replace('scheme', /[a-zA-Z][a-zA-Z0-9+.-]{1,31}/)\n .replace('email', /[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/)\n .getRegex();\n\nconst _inlineComment = edit(_comment).replace('(?:-->|$)', '-->').getRegex();\nconst tag = edit(\n '^comment'\n + '|^</[a-zA-Z][\\\\w:-]*\\\\s*>' // self-closing tag\n + '|^<[a-zA-Z][\\\\w-]*(?:attribute)*?\\\\s*/?>' // open tag\n + '|^<\\\\?[\\\\s\\\\S]*?\\\\?>' // processing instruction, e.g. <?php ?>\n + '|^<![a-zA-Z]+\\\\s[\\\\s\\\\S]*?>' // declaration, e.g. <!DOCTYPE html>\n + '|^<!\\\\[CDATA\\\\[[\\\\s\\\\S]*?\\\\]\\\\]>') // CDATA section\n .replace('comment', _inlineComment)\n .replace('attribute', /\\s+[a-zA-Z:_][\\w.:-]*(?:\\s*=\\s*\"[^\"]*\"|\\s*=\\s*'[^']*'|\\s*=\\s*[^\\s\"'=<>`]+)?/)\n .getRegex();\n\nconst _inlineLabel = /(?:\\[(?:\\\\[\\s\\S]|[^\\[\\]\\\\])*\\]|\\\\[\\s\\S]|`+[^`]*?`+(?!`)|[^\\[\\]\\\\`])*?/;\n\nconst link = edit(/^!?\\[(label)\\]\\(\\s*(href)(?:(?:[ \\t]*(?:\\n[ \\t]*)?)(title))?\\s*\\)/)\n .replace('label', _inlineLabel)\n .replace('href', /<(?:\\\\.|[^\\n<>\\\\])+>|[^ \\t\\n\\x00-\\x1f]*/)\n .replace('title', /\"(?:\\\\\"?|[^\"\\\\])*\"|'(?:\\\\'?|[^'\\\\])*'|\\((?:\\\\\\)?|[^)\\\\])*\\)/)\n .getRegex();\n\nconst reflink = edit(/^!?\\[(label)\\]\\[(ref)\\]/)\n .replace('label', _inlineLabel)\n .replace('ref', _blockLabel)\n .getRegex();\n\nconst nolink = edit(/^!?\\[(ref)\\](?:\\[\\])?/)\n .replace('ref', _blockLabel)\n .getRegex();\n\nconst reflinkSearch = edit('reflink|nolink(?!\\\\()', 'g')\n .replace('reflink', reflink)\n .replace('nolink', nolink)\n .getRegex();\n\nconst _caseInsensitiveProtocol = /[hH][tT][tT][pP][sS]?|[fF][tT][pP]/;\n\n/**\n * Normal Inline Grammar\n */\n\nconst inlineNormal = {\n _backpedal: noopTest, // only used for GFM url\n anyPunctuation,\n autolink,\n blockSkip,\n br,\n code: inlineCode,\n del: noopTest,\n emStrongLDelim,\n emStrongRDelimAst,\n emStrongRDelimUnd,\n escape,\n link,\n nolink,\n punctuation,\n reflink,\n reflinkSearch,\n tag,\n text: inlineText,\n url: noopTest,\n};\n\ntype InlineKeys = keyof typeof inlineNormal;\n\n/**\n * Pedantic Inline Grammar\n */\n\nconst inlinePedantic: Record<InlineKeys, RegExp> = {\n ...inlineNormal,\n link: edit(/^!?\\[(label)\\]\\((.*?)\\)/)\n .replace('label', _inlineLabel)\n .getRegex(),\n reflink: edit(/^!?\\[(label)\\]\\s*\\[([^\\]]*)\\]/)\n .replace('label', _inlineLabel)\n .getRegex(),\n};\n\n/**\n * GFM Inline Grammar\n */\n\nconst inlineGfm: Record<InlineKeys, RegExp> = {\n ...inlineNormal,\n emStrongRDelimAst: emStrongRDelimAstGfm,\n emStrongLDelim: emStrongLDelimGfm,\n url: edit(/^((?:protocol):\\/\\/|www\\.)(?:[a-zA-Z0-9\\-]+\\.?)+[^\\s<]*|^email/)\n .replace('protocol', _caseInsensitiveProtocol)\n .replace('email', /[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/)\n .getRegex(),\n _backpedal: /(?:[^?!.,:;*_'\"~()&]+|\\([^)]*\\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'\"~)]+(?!$))+/,\n del: /^(~~?)(?=[^\\s~])((?:\\\\[\\s\\S]|[^\\\\])*?(?:\\\\[\\s\\S]|[^\\s~\\\\]))\\1(?=[^~]|$)/,\n text: edit(/^([`~]+|[^`~])(?:(?= {2,}\\n)|(?=[a-zA-Z0-9.!#$%&'*+\\/=?_`{\\|}~-]+@)|[\\s\\S]*?(?:(?=[\\\\<!\\[`*~_]|\\b_|protocol:\\/\\/|www\\.|$)|[^ ](?= {2,}\\n)|[^a-zA-Z0-9.!#$%&'*+\\/=?_`{\\|}~-](?=[a-zA-Z0-9.!#$%&'*+\\/=?_`{\\|}~-]+@)))/)\n .replace('protocol', _caseInsensitiveProtocol)\n .getRegex(),\n};\n\n/**\n * GFM + Line Breaks Inline Grammar\n */\n\nconst inlineBreaks: Record<InlineKeys, RegExp> = {\n ...inlineGfm,\n br: edit(br).replace('{2,}', '*').getRegex(),\n text: edit(inlineGfm.text)\n .replace('\\\\b_', '\\\\b_| {2,}\\\\n')\n .replace(/\\{2,\\}/g, '*')\n .getRegex(),\n};\n\n/**\n * exports\n */\n\nexport const block = {\n normal: blockNormal,\n gfm: blockGfm,\n pedantic: blockPedantic,\n};\n\nexport const inline = {\n normal: inlineNormal,\n gfm: inlineGfm,\n breaks: inlineBreaks,\n pedantic: inlinePedantic,\n};\n\nexport interface Rules {\n other: typeof other\n block: Record<BlockKeys, RegExp>\n inline: Record<InlineKeys, RegExp>\n}\n", "import { other } from './rules.ts';\n\n/**\n * Helpers\n */\nconst escapeReplacements: { [index: string]: string } = {\n '&': '&',\n '<': '<',\n '>': '>',\n '\"': '"',\n \"'\": ''',\n};\nconst getEscapeReplacement = (ch: string) => escapeReplacements[ch];\n\nexport function escape(html: string, encode?: boolean) {\n if (encode) {\n if (other.escapeTest.test(html)) {\n return html.replace(other.escapeReplace, getEscapeReplacement);\n }\n } else {\n if (other.escapeTestNoEncode.test(html)) {\n return html.replace(other.escapeReplaceNoEncode, getEscapeReplacement);\n }\n }\n\n return html;\n}\n\nexport function unescape(html: string) {\n // explicitly match decimal, hex, and named HTML entities\n return html.replace(other.unescapeTest, (_, n) => {\n n = n.toLowerCase();\n if (n === 'colon') return ':';\n if (n.charAt(0) === '#') {\n return n.charAt(1) === 'x'\n ? String.fromCharCode(parseInt(n.substring(2), 16))\n : String.fromCharCode(+n.substring(1));\n }\n return '';\n });\n}\n\nexport function cleanUrl(href: string) {\n try {\n href = encodeURI(href).replace(other.percentDecode, '%');\n } catch {\n return null;\n }\n return href;\n}\n\nexport function splitCells(tableRow: string, count?: number) {\n // ensure that every cell-delimiting pipe has a space\n // before it to distinguish it from an escaped pipe\n const row = tableRow.replace(other.findPipe, (match, offset, str) => {\n let escaped = false;\n let curr = offset;\n while (--curr >= 0 && str[curr] === '\\\\') escaped = !escaped;\n if (escaped) {\n // odd number of slashes means | is escaped\n // so we leave it alone\n return '|';\n } else {\n // add space before unescaped |\n return ' |';\n }\n }),\n cells = row.split(other.splitPipe);\n let i = 0;\n\n // First/last cell in a row cannot be empty if it has no leading/trailing pipe\n if (!cells[0].trim()) {\n cells.shift();\n }\n if (cells.length > 0 && !cells.at(-1)?.trim()) {\n cells.pop();\n }\n\n if (count) {\n if (cells.length > count) {\n cells.splice(count);\n } else {\n while (cells.length < count) cells.push('');\n }\n }\n\n for (; i < cells.length; i++) {\n // leading or trailing whitespace is ignored per the gfm spec\n cells[i] = cells[i].trim().replace(other.slashPipe, '|');\n }\n return cells;\n}\n\n/**\n * Remove trailing 'c's. Equivalent to str.replace(/c*$/, '').\n * /c*$/ is vulnerable to REDOS.\n *\n * @param str\n * @param c\n * @param invert Remove suffix of non-c chars instead. Default falsey.\n */\nexport function rtrim(str: string, c: string, invert?: boolean) {\n const l = str.length;\n if (l === 0) {\n return '';\n }\n\n // Length of suffix matching the invert condition.\n let suffLen = 0;\n\n // Step left until we fail to match the invert condition.\n while (suffLen < l) {\n const currChar = str.charAt(l - suffLen - 1);\n if (currChar === c && !invert) {\n suffLen++;\n } else if (currChar !== c && invert) {\n suffLen++;\n } else {\n break;\n }\n }\n\n return str.slice(0, l - suffLen);\n}\n\nexport function findClosingBracket(str: string, b: string) {\n if (str.indexOf(b[1]) === -1) {\n return -1;\n }\n\n let level = 0;\n for (let i = 0; i < str.length; i++) {\n if (str[i] === '\\\\') {\n i++;\n } else if (str[i] === b[0]) {\n level++;\n } else if (str[i] === b[1]) {\n level--;\n if (level < 0) {\n return i;\n }\n }\n }\n if (level > 0) {\n return -2;\n }\n\n return -1;\n}\n", "import { _defaults } from './defaults.ts';\nimport {\n rtrim,\n splitCells,\n findClosingBracket,\n} from './helpers.ts';\nimport type { Rules } from './rules.ts';\nimport type { _Lexer } from './Lexer.ts';\nimport type { Links, Tokens, Token } from './Tokens.ts';\nimport type { MarkedOptions } from './MarkedOptions.ts';\n\nfunction outputLink(cap: string[], link: Pick<Tokens.Link, 'href' | 'title'>, raw: string, lexer: _Lexer, rules: Rules): Tokens.Link | Tokens.Image {\n const href = link.href;\n const title = link.title || null;\n const text = cap[1].replace(rules.other.outputLinkReplace, '$1');\n\n lexer.state.inLink = true;\n const token: Tokens.Link | Tokens.Image = {\n type: cap[0].charAt(0) === '!' ? 'image' : 'link',\n raw,\n href,\n title,\n text,\n tokens: lexer.inlineTokens(text),\n };\n lexer.state.inLink = false;\n return token;\n}\n\nfunction indentCodeCompensation(raw: string, text: string, rules: Rules) {\n const matchIndentToCode = raw.match(rules.other.indentCodeCompensation);\n\n if (matchIndentToCode === null) {\n return text;\n }\n\n const indentToCode = matchIndentToCode[1];\n\n return text\n .split('\\n')\n .map(node => {\n const matchIndentInNode = node.match(rules.other.beginningSpace);\n if (matchIndentInNode === null) {\n return node;\n }\n\n const [indentInNode] = matchIndentInNode;\n\n if (indentInNode.length >= indentToCode.length) {\n return node.slice(indentToCode.length);\n }\n\n return node;\n })\n .join('\\n');\n}\n\n/**\n * Tokenizer\n */\nexport class _Tokenizer<ParserOutput = string, RendererOutput = string> {\n options: MarkedOptions<ParserOutput, RendererOutput>;\n rules!: Rules; // set by the lexer\n lexer!: _Lexer<ParserOutput, RendererOutput>; // set by the lexer\n\n constructor(options?: MarkedOptions<ParserOutput, RendererOutput>) {\n this.options = options || _defaults;\n }\n\n space(src: string): Tokens.Space | undefined {\n const cap = this.rules.block.newline.exec(src);\n if (cap && cap[0].length > 0) {\n return {\n type: 'space',\n raw: cap[0],\n };\n }\n }\n\n code(src: string): Tokens.Code | undefined {\n const cap = this.rules.block.code.exec(src);\n if (cap) {\n const text = cap[0].replace(this.rules.other.codeRemoveIndent, '');\n return {\n type: 'code',\n raw: cap[0],\n codeBlockStyle: 'indented',\n text: !this.options.pedantic\n ? rtrim(text, '\\n')\n : text,\n };\n }\n }\n\n fences(src: string): Tokens.Code | undefined {\n const cap = this.rules.block.fences.exec(src);\n if (cap) {\n const raw = cap[0];\n const text = indentCodeCompensation(raw, cap[3] || '', this.rules);\n\n return {\n type: 'code',\n raw,\n lang: cap[2] ? cap[2].trim().replace(this.rules.inline.anyPunctuation, '$1') : cap[2],\n text,\n };\n }\n }\n\n heading(src: string): Tokens.Heading | undefined {\n const cap = this.rules.block.heading.exec(src);\n if (cap) {\n let text = cap[2].trim();\n\n // remove trailing #s\n if (this.rules.other.endingHash.test(text)) {\n const trimmed = rtrim(text, '#');\n if (this.options.pedantic) {\n text = trimmed.trim();\n } else if (!trimmed || this.rules.other.endingSpaceChar.test(trimmed)) {\n // CommonMark requires space before trailing #s\n text = trimmed.trim();\n }\n }\n\n return {\n type: 'heading',\n raw: cap[0],\n depth: cap[1].length,\n text,\n tokens: this.lexer.inline(text),\n };\n }\n }\n\n hr(src: string): Tokens.Hr | undefined {\n const cap = this.rules.block.hr.exec(src);\n if (cap) {\n return {\n type: 'hr',\n raw: rtrim(cap[0], '\\n'),\n };\n }\n }\n\n blockquote(src: string): Tokens.Blockquote | undefined {\n const cap = this.rules.block.blockquote.exec(src);\n if (cap) {\n let lines = rtrim(cap[0], '\\n').split('\\n');\n let raw = '';\n let text = '';\n const tokens: Token[] = [];\n\n while (lines.length > 0) {\n let inBlockquote = false;\n const currentLines = [];\n\n let i;\n for (i = 0; i < lines.length; i++) {\n // get lines up to a continuation\n if (this.rules.other.blockquoteStart.test(lines[i])) {\n currentLines.push(lines[i]);\n inBlockquote = true;\n } else if (!inBlockquote) {\n currentLines.push(lines[i]);\n } else {\n break;\n }\n }\n lines = lines.slice(i);\n\n const currentRaw = currentLines.join('\\n');\n const currentText = currentRaw\n // precede setext continuation with 4 spaces so it isn't a setext\n .replace(this.rules.other.blockquoteSetextReplace, '\\n $1')\n .replace(this.rules.other.blockquoteSetextReplace2, '');\n raw = raw ? `${raw}\\n${currentRaw}` : currentRaw;\n text = text ? `${text}\\n${currentText}` : currentText;\n\n // parse blockquote lines as top level tokens\n // merge paragraphs if this is a continuation\n const top = this.lexer.state.top;\n this.lexer.state.top = true;\n this.lexer.blockTokens(currentText, tokens, true);\n this.lexer.state.top = top;\n\n // if there is no continuation then we are done\n if (lines.length === 0) {\n break;\n }\n\n const lastToken = tokens.at(-1);\n\n if (lastToken?.type === 'code') {\n // blockquote continuation cannot be preceded by a code block\n break;\n } else if (lastToken?.type === 'blockquote') {\n // include continuation in nested blockquote\n const oldToken = lastToken as Tokens.Blockquote;\n const newText = oldToken.raw + '\\n' + lines.join('\\n');\n const newToken = this.blockquote(newText)!;\n tokens[tokens.length - 1] = newToken;\n\n raw = raw.substring(0, raw.length - oldToken.raw.length) + newToken.raw;\n text = text.substring(0, text.length - oldToken.text.length) + newToken.text;\n break;\n } else if (lastToken?.type === 'list') {\n // include continuation in nested list\n const oldToken = lastToken as Tokens.List;\n const newText = oldToken.raw + '\\n' + lines.join('\\n');\n const newToken = this.list(newText)!;\n tokens[tokens.length - 1] = newToken;\n\n raw = raw.substring(0, raw.length - lastToken.raw.length) + newToken.raw;\n text = text.substring(0, text.length - oldToken.raw.length) + newToken.raw;\n lines = newText.substring(tokens.at(-1)!.raw.length).split('\\n');\n continue;\n }\n }\n\n return {\n type: 'blockquote',\n raw,\n tokens,\n text,\n };\n }\n }\n\n list(src: string): Tokens.List | undefined {\n let cap = this.rules.block.list.exec(src);\n if (cap) {\n let bull = cap[1].trim();\n const isordered = bull.length > 1;\n\n const list: Tokens.List = {\n type: 'list',\n raw: '',\n ordered: isordered,\n start: isordered ? +bull.slice(0, -1) : '',\n loose: false,\n items: [],\n };\n\n bull = isordered ? `\\\\d{1,9}\\\\${bull.slice(-1)}` : `\\\\${bull}`;\n\n if (this.options.pedantic) {\n bull = isordered ? bull : '[*+-]';\n }\n\n // Get next list item\n const itemRegex = this.rules.other.listItemRegex(bull);\n let endsWithBlankLine = false;\n // Check if current bullet point can start a new List Item\n while (src) {\n let endEarly = false;\n let raw = '';\n let itemContents = '';\n if (!(cap = itemRegex.exec(src))) {\n break;\n }\n\n if (this.rules.block.hr.test(src)) { // End list if bullet was actually HR (possibly move into itemRegex?)\n break;\n }\n\n raw = cap[0];\n src = src.substring(raw.length);\n\n let line = cap[2].split('\\n', 1)[0].replace(this.rules.other.listReplaceTabs, (t: string) => ' '.repeat(3 * t.length));\n let nextLine = src.split('\\n', 1)[0];\n let blankLine = !line.trim();\n\n let indent = 0;\n if (this.options.pedantic) {\n indent = 2;\n itemContents = line.trimStart();\n } else if (blankLine) {\n indent = cap[1].length + 1;\n } else {\n indent = cap[2].search(this.rules.other.nonSpaceChar); // Find first non-space char\n indent = indent > 4 ? 1 : indent; // Treat indented code blocks (> 4 spaces) as having only 1 indent\n itemContents = line.slice(indent);\n indent += cap[1].length;\n }\n\n if (blankLine && this.rules.other.blankLine.test(nextLine)) { // Items begin with at most one blank line\n raw += nextLine + '\\n';\n src = src.substring(nextLine.length + 1);\n endEarly = true;\n }\n\n if (!endEarly) {\n const nextBulletRegex = this.rules.other.nextBulletRegex(indent);\n const hrRegex = this.rules.other.hrRegex(indent);\n const fencesBeginRegex = this.rules.other.fencesBeginRegex(indent);\n const headingBeginRegex = this.rules.other.headingBeginRegex(indent);\n const htmlBeginRegex = this.rules.other.htmlBeginRegex(indent);\n\n // Check if following lines should be included in List Item\n while (src) {\n const rawLine = src.split('\\n', 1)[0];\n let nextLineWithoutTabs;\n nextLine = rawLine;\n\n // Re-align to follow commonmark nesting rules\n if (this.options.pedantic) {\n nextLine = nextLine.replace(this.rules.other.listReplaceNesting, ' ');\n nextLineWithoutTabs = nextLine;\n } else {\n nextLineWithoutTabs = nextLine.replace(this.rules.other.tabCharGlobal, ' ');\n }\n\n // End list item if found code fences\n if (fencesBeginRegex.test(nextLine)) {\n break;\n }\n\n // End list item if found start of new heading\n if (headingBeginRegex.test(nextLine)) {\n break;\n }\n\n // End list item if found start of html block\n if (htmlBeginRegex.test(nextLine)) {\n break;\n }\n\n // End list item if found start of new bullet\n if (nextBulletRegex.test(nextLine)) {\n break;\n }\n\n // Horizontal rule found\n if (hrRegex.test(nextLine)) {\n break;\n }\n\n if (nextLineWithoutTabs.search(this.rules.other.nonSpaceChar) >= indent || !nextLine.trim()) { // Dedent if possible\n itemContents += '\\n' + nextLineWithoutTabs.slice(indent);\n } else {\n // not enough indentation\n if (blankLine) {\n break;\n }\n\n // paragraph continuation unless last line was a different block level element\n if (line.replace(this.rules.other.tabCharGlobal, ' ').search(this.rules.other.nonSpaceChar) >= 4) { // indented code block\n break;\n }\n if (fencesBeginRegex.test(line)) {\n break;\n }\n if (headingBeginRegex.test(line)) {\n break;\n }\n if (hrRegex.test(line)) {\n break;\n }\n\n itemContents += '\\n' + nextLine;\n }\n\n if (!blankLine && !nextLine.trim()) { // Check if current line is blank\n blankLine = true;\n }\n\n raw += rawLine + '\\n';\n src = src.substring(rawLine.length + 1);\n line = nextLineWithoutTabs.slice(indent);\n }\n }\n\n if (!list.loose) {\n // If the previous item ended with a blank line, the list is loose\n if (endsWithBlankLine) {\n list.loose = true;\n } else if (this.rules.other.doubleBlankLine.test(raw)) {\n endsWithBlankLine = true;\n }\n }\n\n list.items.push({\n type: 'list_item',\n raw,\n task: !!this.options.gfm && this.rules.other.listIsTask.test(itemContents),\n loose: false,\n text: itemContents,\n tokens: [],\n });\n\n list.raw += raw;\n }\n\n // Do not consume newlines at end of final item. Alternatively, make itemRegex *start* with any newlines to simplify/speed up endsWithBlankLine logic\n const lastItem = list.items.at(-1);\n if (lastItem) {\n lastItem.raw = lastItem.raw.trimEnd();\n lastItem.text = lastItem.text.trimEnd();\n } else {\n // not a list since there were no items\n return;\n }\n list.raw = list.raw.trimEnd();\n\n // Item child tokens handled here at end because we needed to have the final item to trim it first\n for (const item of list.items) {\n this.lexer.state.top = false;\n item.tokens = this.lexer.blockTokens(item.text, []);\n if (item.task) {\n // Remove checkbox markdown from item tokens\n item.text = item.text.replace(this.rules.other.listReplaceTask, '');\n if (item.tokens[0]?.type === 'text' || item.tokens[0]?.type === 'paragraph') {\n item.tokens[0].raw = item.tokens[0].raw.replace(this.rules.other.listReplaceTask, '');\n item.tokens[0].text = item.tokens[0].text.replace(this.rules.other.listReplaceTask, '');\n for (let i = this.lexer.inlineQueue.length - 1; i >= 0; i--) {\n if (this.rules.other.listIsTask.test(this.lexer.inlineQueue[i].src)) {\n this.lexer.inlineQueue[i].src = this.lexer.inlineQueue[i].src.replace(this.rules.other.listReplaceTask, '');\n break;\n }\n }\n }\n\n const taskRaw = this.rules.other.listTaskCheckbox.exec(item.raw);\n if (taskRaw) {\n const checkboxToken: Tokens.Checkbox = {\n type: 'checkbox',\n raw: taskRaw[0] + ' ',\n checked: taskRaw[0] !== '[ ]',\n };\n item.checked = checkboxToken.checked;\n if (list.loose) {\n if (item.tokens[0] && ['paragraph', 'text'].includes(item.tokens[0].type) && 'tokens' in item.tokens[0] && item.tokens[0].tokens) {\n item.tokens[0].raw = checkboxToken.raw + item.tokens[0].raw;\n item.tokens[0].text = checkboxToken.raw + item.tokens[0].text;\n item.tokens[0].tokens.unshift(checkboxToken);\n } else {\n item.tokens.unshift({\n type: 'paragraph',\n raw: checkboxToken.raw,\n text: checkboxToken.raw,\n tokens: [checkboxToken],\n });\n }\n } else {\n item.tokens.unshift(checkboxToken);\n }\n }\n }\n\n if (!list.loose) {\n // Check if list should be loose\n const spacers = item.tokens.filter(t => t.type === 'space');\n const hasMultipleLineBreaks = spacers.length > 0 && spacers.some(t => this.rules.other.anyLine.test(t.raw));\n\n list.loose = hasMultipleLineBreaks;\n }\n }\n\n // Set all items to loose if list is loose\n if (list.loose) {\n for (const item of list.items) {\n item.loose = true;\n for (const token of item.tokens) {\n if (token.type === 'text') {\n token.type = 'paragraph';\n }\n }\n }\n }\n\n return list;\n }\n }\n\n html(src: string): Tokens.HTML | undefined {\n const cap = this.rules.block.html.exec(src);\n if (cap) {\n const token: Tokens.HTML = {\n type: 'html',\n block: true,\n raw: cap[0],\n pre: cap[1] === 'pre' || cap[1] === 'script' || cap[1] === 'style',\n text: cap[0],\n };\n return token;\n }\n }\n\n def(src: string): Tokens.Def | undefined {\n const cap = this.rules.block.def.exec(src);\n if (cap) {\n const tag = cap[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal, ' ');\n const href = cap[2] ? cap[2].replace(this.rules.other.hrefBrackets, '$1').replace(this.rules.inline.anyPunctuation, '$1') : '';\n const title = cap[3] ? cap[3].substring(1, cap[3].length - 1).replace(this.rules.inline.anyPunctuation, '$1') : cap[3];\n return {\n type: 'def',\n tag,\n raw: cap[0],\n href,\n title,\n };\n }\n }\n\n table(src: string): Tokens.Table | undefined {\n const cap = this.rules.block.table.exec(src);\n if (!cap) {\n return;\n }\n\n if (!this.rules.other.tableDelimiter.test(cap[2])) {\n // delimiter row must have a pipe (|) or colon (:) otherwise it is a setext heading\n return;\n }\n\n const headers = splitCells(cap[1]);\n const aligns = cap[2].replace(this.rules.other.tableAlignChars, '').split('|');\n const rows = cap[3]?.trim() ? cap[3].replace(this.rules.other.tableRowBlankLine, '').split('\\n') : [];\n\n const item: Tokens.Table = {\n type: 'table',\n raw: cap[0],\n header: [],\n align: [],\n rows: [],\n };\n\n if (headers.length !== aligns.length) {\n // header and align columns must be equal, rows can be different.\n return;\n }\n\n for (const align of aligns) {\n if (this.rules.other.tableAlignRight.test(align)) {\n item.align.push('right');\n } else if (this.rules.other.tableAlignCenter.test(align)) {\n item.align.push('center');\n } else if (this.rules.other.tableAlignLeft.test(align)) {\n item.align.push('left');\n } else {\n item.align.push(null);\n }\n }\n\n for (let i = 0; i < headers.length; i++) {\n item.header.push({\n text: headers[i],\n tokens: this.lexer.inline(headers[i]),\n header: true,\n align: item.align[i],\n });\n }\n\n for (const row of rows) {\n item.rows.push(splitCells(row, item.header.length).map((cell, i) => {\n return {\n text: cell,\n tokens: this.lexer.inline(cell),\n header: false,\n align: item.align[i],\n };\n }));\n }\n\n return item;\n }\n\n lheading(src: string): Tokens.Heading | undefined {\n const cap = this.rules.block.lheading.exec(src);\n if (cap) {\n return {\n type: 'heading',\n raw: cap[0],\n depth: cap[2].charAt(0) === '=' ? 1 : 2,\n text: cap[1],\n tokens: this.lexer.inline(cap[1]),\n };\n }\n }\n\n paragraph(src: string): Tokens.Paragraph | undefined {\n const cap = this.rules.block.paragraph.exec(src);\n if (cap) {\n const text = cap[1].charAt(cap[1].length - 1) === '\\n'\n ? cap[1].slice(0, -1)\n : cap[1];\n return {\n type: 'paragraph',\n raw: cap[0],\n text,\n tokens: this.lexer.inline(text),\n };\n }\n }\n\n text(src: string): Tokens.Text | undefined {\n const cap = this.rules.block.text.exec(src);\n if (cap) {\n return {\n type: 'text',\n raw: cap[0],\n text: cap[0],\n tokens: this.lexer.inline(cap[0]),\n };\n }\n }\n\n escape(src: string): Tokens.Escape | undefined {\n const cap = this.rules.inline.escape.exec(src);\n if (cap) {\n return {\n type: 'escape',\n raw: cap[0],\n text: cap[1],\n };\n }\n }\n\n tag(src: string): Tokens.Tag | undefined {\n const cap = this.rules.inline.tag.exec(src);\n if (cap) {\n if (!this.lexer.state.inLink && this.rules.other.startATag.test(cap[0])) {\n this.lexer.state.inLink = true;\n } else if (this.lexer.state.inLink && this.rules.other.endATag.test(cap[0])) {\n this.lexer.state.inLink = false;\n }\n if (!this.lexer.state.inRawBlock && this.rules.other.startPreScriptTag.test(cap[0])) {\n this.lexer.state.inRawBlock = true;\n } else if (this.lexer.state.inRawBlock && this.rules.other.endPreScriptTag.test(cap[0])) {\n this.lexer.state.inRawBlock = false;\n }\n\n return {\n type: 'html',\n raw: cap[0],\n inLink: this.lexer.state.inLink,\n inRawBlock: this.lexer.state.inRawBlock,\n block: false,\n text: cap[0],\n };\n }\n }\n\n link(src: string): Tokens.Link | Tokens.Image | undefined {\n const cap = this.rules.inline.link.exec(src);\n if (cap) {\n const trimmedUrl = cap[2].trim();\n if (!this.options.pedantic && this.rules.other.startAngleBracket.test(trimmedUrl)) {\n // commonmark requires matching angle brackets\n if (!(this.rules.other.endAngleBracket.test(trimmedUrl))) {\n return;\n }\n\n // ending angle bracket cannot be escaped\n const rtrimSlash = rtrim(trimmedUrl.slice(0, -1), '\\\\');\n if ((trimmedUrl.length - rtrimSlash.length) % 2 === 0) {\n return;\n }\n } else {\n // find closing parenthesis\n const lastParenIndex = findClosingBracket(cap[2], '()');\n if (lastParenIndex === -2) {\n // more open parens than closed\n return;\n }\n\n if (lastParenIndex > -1) {\n const start = cap[0].indexOf('!') === 0 ? 5 : 4;\n const linkLen = start + cap[1].length + lastParenIndex;\n cap[2] = cap[2].substring(0, lastParenIndex);\n cap[0] = cap[0].substring(0, linkLen).trim();\n cap[3] = '';\n }\n }\n let href = cap[2];\n let title = '';\n if (this.options.pedantic) {\n // split pedantic href and title\n const link = this.rules.other.pedanticHrefTitle.exec(href);\n\n if (link) {\n href = link[1];\n title = link[3];\n }\n } else {\n title = cap[3] ? cap[3].slice(1, -1) : '';\n }\n\n href = href.trim();\n if (this.rules.other.startAngleBracket.test(href)) {\n if (this.options.pedantic && !(this.rules.other.endAngleBracket.test(trimmedUrl))) {\n // pedantic allows starting angle bracket without ending angle bracket\n href = href.slice(1);\n } else {\n href = href.slice(1, -1);\n }\n }\n return outputLink(cap, {\n href: href ? href.replace(this.rules.inline.anyPunctuation, '$1') : href,\n title: title ? title.replace(this.rules.inline.anyPunctuation, '$1') : title,\n }, cap[0], this.lexer, this.rules);\n }\n }\n\n reflink(src: string, links: Links): Tokens.Link | Tokens.Image | Tokens.Text | undefined {\n let cap;\n if ((cap = this.rules.inline.reflink.exec(src))\n || (cap = this.rules.inline.nolink.exec(src))) {\n const linkString = (cap[2] || cap[1]).replace(this.rules.other.multipleSpaceGlobal, ' ');\n const link = links[linkString.toLowerCase()];\n if (!link) {\n const text = cap[0].charAt(0);\n return {\n type: 'text',\n raw: text,\n text,\n };\n }\n return outputLink(cap, link, cap[0], this.lexer, this.rules);\n }\n }\n\n emStrong(src: string, maskedSrc: string, prevChar = ''): Tokens.Em | Tokens.Strong | undefined {\n let match = this.rules.inline.emStrongLDelim.exec(src);\n if (!match) return;\n\n // _ can't be between two alphanumerics. \\p{L}\\p{N} includes non-english alphabet/numbers as well\n if (match[3] && prevChar.match(this.rules.other.unicodeAlphaNumeric)) return;\n\n const nextChar = match[1] || match[2] || '';\n\n if (!nextChar || !prevChar || this.rules.inline.punctuation.exec(prevChar)) {\n // unicode Regex counts emoji as 1 char; spread into array for proper count (used multiple times below)\n const lLength = [...match[0]].length - 1;\n let rDelim, rLength, delimTotal = lLength, midDelimTotal = 0;\n\n const endReg = match[0][0] === '*' ? this.rules.inline.emStrongRDelimAst : this.rules.inline.emStrongRDelimUnd;\n endReg.lastIndex = 0;\n\n // Clip maskedSrc to same section of string as src (move to lexer?)\n maskedSrc = maskedSrc.slice(-1 * src.length + lLength);\n\n while ((match = endReg.exec(maskedSrc)) != null) {\n rDelim = match[1] || match[2] || match[3] || match[4] || match[5] || match[6];\n\n if (!rDelim) continue; // skip single * in __abc*abc__\n\n rLength = [...rDelim].length;\n\n if (match[3] || match[4]) { // found another Left Delim\n delimTotal += rLength;\n continue;\n } else if (match[5] || match[6]) { // either Left or Right Delim\n if (lLength % 3 && !((lLength + rLength) % 3)) {\n midDelimTotal += rLength;\n continue; // CommonMark Emphasis Rules 9-10\n }\n }\n\n delimTotal -= rLength;\n\n if (delimTotal > 0) continue; // Haven't found enough closing delimiters\n\n // Remove extra characters. *a*** -> *a*\n rLength = Math.min(rLength, rLength + delimTotal + midDelimTotal);\n // char length can be >1 for unicode characters;\n const lastCharLength = [...match[0]][0].length;\n const raw = src.slice(0, lLength + match.index + lastCharLength + rLength);\n\n // Create `em` if smallest delimiter has odd char count. *a***\n if (Math.min(lLength, rLength) % 2) {\n const text = raw.slice(1, -1);\n return {\n type: 'em',\n raw,\n text,\n tokens: this.lexer.inlineTokens(text),\n };\n }\n\n // Create 'strong' if smallest delimiter has even char count. **a***\n const text = raw.slice(2, -2);\n return {\n type: 'strong',\n raw,\n text,\n tokens: this.lexer.inlineTokens(text),\n };\n }\n }\n }\n\n codespan(src: string): Tokens.Codespan | undefined {\n const cap = this.rules.inline.code.exec(src);\n if (cap) {\n let text = cap[2].replace(this.rules.other.newLineCharGlobal, ' ');\n const hasNonSpaceChars = this.rules.other.nonSpaceChar.test(text);\n const hasSpaceCharsOnBothEnds = this.rules.other.startingSpaceChar.test(text) && this.rules.other.endingSpaceChar.test(text);\n if (hasNonSpaceChars && hasSpaceCharsOnBothEnds) {\n text = text.substring(1, text.length - 1);\n }\n return {\n type: 'codespan',\n raw: cap[0],\n text,\n };\n }\n }\n\n br(src: string): Tokens.Br | undefined {\n const cap = this.rules.inline.br.exec(src);\n if (cap) {\n return {\n type: 'br',\n raw: cap[0],\n };\n }\n }\n\n del(src: string): Tokens.Del | undefined {\n const cap = this.rules.inline.del.exec(src);\n if (cap) {\n return {\n type: 'del',\n raw: cap[0],\n text: cap[2],\n tokens: this.lexer.inlineTokens(cap[2]),\n };\n }\n }\n\n autolink(src: string): Tokens.Link | undefined {\n const cap = this.rules.inline.autolink.exec(src);\n if (cap) {\n let text, href;\n if (cap[2] === '@') {\n text = cap[1];\n href = 'mailto:' + text;\n } else {\n text = cap[1];\n href = text;\n }\n\n return {\n type: 'link',\n raw: cap[0],\n text,\n href,\n tokens: [\n {\n type: 'text',\n raw: text,\n text,\n },\n ],\n };\n }\n }\n\n url(src: string): Tokens.Link | undefined {\n let cap;\n if (cap = this.rules.inline.url.exec(src)) {\n let text, href;\n if (cap[2] === '@') {\n text = cap[0];\n href = 'mailto:' + text;\n } else {\n // do extended autolink path validation\n let prevCapZero;\n do {\n prevCapZero = cap[0];\n cap[0] = this.rules.inline._backpedal.exec(cap[0])?.[0] ?? '';\n } while (prevCapZero !== cap[0]);\n text = cap[0];\n if (cap[1] === 'www.') {\n href = 'http://' + cap[0];\n } else {\n href = cap[0];\n }\n }\n return {\n type: 'link',\n raw: cap[0],\n text,\n href,\n tokens: [\n {\n type: 'text',\n raw: text,\n text,\n },\n ],\n };\n }\n }\n\n inlineText(src: string): Tokens.Text | undefined {\n const cap = this.rules.inline.text.exec(src);\n if (cap) {\n const escaped = this.lexer.state.inRawBlock;\n return {\n type: 'text',\n raw: cap[0],\n text: cap[0],\n escaped,\n };\n }\n }\n}\n", "import { _Tokenizer } from './Tokenizer.ts';\nimport { _defaults } from './defaults.ts';\nimport { other, block, inline } from './rules.ts';\nimport type { Token, TokensList, Tokens } from './Tokens.ts';\nimport type { MarkedOptions } from './MarkedOptions.ts';\n\n/**\n * Block Lexer\n */\nexport class _Lexer<ParserOutput = string, RendererOutput = string> {\n tokens: TokensList;\n options: MarkedOptions<ParserOutput, RendererOutput>;\n state: {\n inLink: boolean;\n inRawBlock: boolean;\n top: boolean;\n };\n\n public inlineQueue: { src: string, tokens: Token[] }[];\n\n private tokenizer: _Tokenizer<ParserOutput, RendererOutput>;\n\n constructor(options?: MarkedOptions<ParserOutput, RendererOutput>) {\n // TokenList cannot be created in one go\n this.tokens = [] as unknown as TokensList;\n this.tokens.links = Object.create(null);\n this.options = options || _defaults;\n this.options.tokenizer = this.options.tokenizer || new _Tokenizer<ParserOutput, RendererOutput>();\n this.tokenizer = this.options.tokenizer;\n this.tokenizer.options = this.options;\n this.tokenizer.lexer = this;\n this.inlineQueue = [];\n this.state = {\n inLink: false,\n inRawBlock: false,\n top: true,\n };\n\n const rules = {\n other,\n block: block.normal,\n inline: inline.normal,\n };\n\n if (this.options.pedantic) {\n rules.block = block.pedantic;\n rules.inline = inline.pedantic;\n } else if (this.options.gfm) {\n rules.block = block.gfm;\n if (this.options.breaks) {\n rules.inline = inline.breaks;\n } else {\n rules.inline = inline.gfm;\n }\n }\n this.tokenizer.rules = rules;\n }\n\n /**\n * Expose Rules\n */\n static get rules() {\n return {\n block,\n inline,\n };\n }\n\n /**\n * Static Lex Method\n */\n static lex<ParserOutput = string, RendererOutput = string>(src: string, options?: MarkedOptions<ParserOutput, RendererOutput>) {\n const lexer = new _Lexer<ParserOutput, RendererOutput>(options);\n return lexer.lex(src);\n }\n\n /**\n * Static Lex Inline Method\n */\n static lexInline<ParserOutput = string, RendererOutput = string>(src: string, options?: MarkedOptions<ParserOutput, RendererOutput>) {\n const lexer = new _Lexer<ParserOutput, RendererOutput>(options);\n return lexer.inlineTokens(src);\n }\n\n /**\n * Preprocessing\n */\n lex(src: string) {\n src = src.replace(other.carriageReturn, '\\n');\n\n this.blockTokens(src, this.tokens);\n\n for (let i = 0; i < this.inlineQueue.length; i++) {\n const next = this.inlineQueue[i];\n this.inlineTokens(next.src, next.tokens);\n }\n this.inlineQueue = [];\n\n return this.tokens;\n }\n\n /**\n * Lexing\n */\n blockTokens(src: string, tokens?: Token[], lastParagraphClipped?: boolean): Token[];\n blockTokens(src: string, tokens?: TokensList, lastParagraphClipped?: boolean): TokensList;\n blockTokens(src: string, tokens: Token[] = [], lastParagraphClipped = false) {\n if (this.options.pedantic) {\n src = src.replace(other.tabCharGlobal, ' ').replace(other.spaceLine, '');\n }\n\n while (src) {\n let token: Tokens.Generic | undefined;\n\n if (this.options.extensions?.block?.some((extTokenizer) => {\n if (token = extTokenizer.call({ lexer: this }, src, tokens)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n return true;\n }\n return false;\n })) {\n continue;\n }\n\n // newline\n if (token = this.tokenizer.space(src)) {\n src = src.substring(token.raw.length);\n const lastToken = tokens.at(-1);\n if (token.raw.length === 1 && lastToken !== undefined) {\n // if there's a single \\n as a spacer, it's terminating the last line,\n // so move it there so that we don't get unnecessary paragraph tags\n lastToken.raw += '\\n';\n } else {\n tokens.push(token);\n }\n continue;\n }\n\n // code\n if (token = this.tokenizer.code(src)) {\n src = src.substring(token.raw.length);\n const lastToken = tokens.at(-1);\n // An indented code block cannot interrupt a paragraph.\n if (lastToken?.type === 'paragraph' || lastToken?.type === 'text') {\n lastToken.raw += (lastToken.raw.endsWith('\\n') ? '' : '\\n') + token.raw;\n lastToken.text += '\\n' + token.text;\n this.inlineQueue.at(-1)!.src = lastToken.text;\n } else {\n tokens.push(token);\n }\n continue;\n }\n\n // fences\n if (token = this.tokenizer.fences(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // heading\n if (token = this.tokenizer.heading(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // hr\n if (token = this.tokenizer.hr(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // blockquote\n if (token = this.tokenizer.blockquote(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // list\n if (token = this.tokenizer.list(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // html\n if (token = this.tokenizer.html(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // def\n if (token = this.tokenizer.def(src)) {\n src = src.substring(token.raw.length);\n const lastToken = tokens.at(-1);\n if (lastToken?.type === 'paragraph' || lastToken?.type === 'text') {\n lastToken.raw += (lastToken.raw.endsWith('\\n') ? '' : '\\n') + token.raw;\n lastToken.text += '\\n' + token.raw;\n this.inlineQueue.at(-1)!.src = lastToken.text;\n } else if (!this.tokens.links[token.tag]) {\n this.tokens.links[token.tag] = {\n href: token.href,\n title: token.title,\n };\n tokens.push(token);\n }\n continue;\n }\n\n // table (gfm)\n if (token = this.tokenizer.table(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // lheading\n if (token = this.tokenizer.lheading(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // top-level paragraph\n // prevent paragraph consuming extensions by clipping 'src' to extension start\n let cutSrc = src;\n if (this.options.extensions?.startBlock) {\n let startIndex = Infinity;\n const tempSrc = src.slice(1);\n let tempStart;\n this.options.extensions.startBlock.forEach((getStartIndex) => {\n tempStart = getStartIndex.call({ lexer: this }, tempSrc);\n if (typeof tempStart === 'number' && tempStart >= 0) {\n startIndex = Math.min(startIndex, tempStart);\n }\n });\n if (startIndex < Infinity && startIndex >= 0) {\n cutSrc = src.substring(0, startIndex + 1);\n }\n }\n if (this.state.top && (token = this.tokenizer.paragraph(cutSrc))) {\n const lastToken = tokens.at(-1);\n if (lastParagraphClipped && lastToken?.type === 'paragraph') {\n lastToken.raw += (lastToken.raw.endsWith('\\n') ? '' : '\\n') + token.raw;\n lastToken.text += '\\n' + token.text;\n this.inlineQueue.pop();\n this.inlineQueue.at(-1)!.src = lastToken.text;\n } else {\n tokens.push(token);\n }\n lastParagraphClipped = cutSrc.length !== src.length;\n src = src.substring(token.raw.length);\n continue;\n }\n\n // text\n if (token = this.tokenizer.text(src)) {\n src = src.substring(token.raw.length);\n const lastToken = tokens.at(-1);\n if (lastToken?.type === 'text') {\n lastToken.raw += (lastToken.raw.endsWith('\\n') ? '' : '\\n') + token.raw;\n lastToken.text += '\\n' + token.text;\n this.inlineQueue.pop();\n this.inlineQueue.at(-1)!.src = lastToken.text;\n } else {\n tokens.push(token);\n }\n continue;\n }\n\n if (src) {\n const errMsg = 'Infinite loop on byte: ' + src.charCodeAt(0);\n if (this.options.silent) {\n console.error(errMsg);\n break;\n } else {\n throw new Error(errMsg);\n }\n }\n }\n\n this.state.top = true;\n return tokens;\n }\n\n inline(src: string, tokens: Token[] = []) {\n this.inlineQueue.push({ src, tokens });\n return tokens;\n }\n\n /**\n * Lexing/Compiling\n */\n inlineTokens(src: string, tokens: Token[] = []): Token[] {\n // String with links masked to avoid interference with em and strong\n let maskedSrc = src;\n let match: RegExpExecArray | null = null;\n\n // Mask out reflinks\n if (this.tokens.links) {\n const links = Object.keys(this.tokens.links);\n if (links.length > 0) {\n while ((match = this.tokenizer.rules.inline.reflinkSearch.exec(maskedSrc)) != null) {\n if (links.includes(match[0].slice(match[0].lastIndexOf('[') + 1, -1))) {\n maskedSrc = maskedSrc.slice(0, match.index)\n + '[' + 'a'.repeat(match[0].length - 2) + ']'\n + maskedSrc.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex);\n }\n }\n }\n }\n\n // Mask out escaped characters\n while ((match = this.tokenizer.rules.inline.anyPunctuation.exec(maskedSrc)) != null) {\n maskedSrc = maskedSrc.slice(0, match.index) + '++' + maskedSrc.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);\n }\n\n // Mask out other blocks\n let offset;\n while ((match = this.tokenizer.rules.inline.blockSkip.exec(maskedSrc)) != null) {\n offset = match[2] ? match[2].length : 0;\n maskedSrc = maskedSrc.slice(0, match.index + offset) + '[' + 'a'.repeat(match[0].length - offset - 2) + ']' + maskedSrc.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);\n }\n\n // Mask out blocks from extensions\n maskedSrc = this.options.hooks?.emStrongMask?.call({ lexer: this }, maskedSrc) ?? maskedSrc;\n\n let keepPrevChar = false;\n let prevChar = '';\n while (src) {\n if (!keepPrevChar) {\n prevChar = '';\n }\n keepPrevChar = false;\n\n let token: Tokens.Generic | undefined;\n\n // extensions\n if (this.options.extensions?.inline?.some((extTokenizer) => {\n if (token = extTokenizer.call({ lexer: this }, src, tokens)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n return true;\n }\n return false;\n })) {\n continue;\n }\n\n // escape\n if (token = this.tokenizer.escape(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // tag\n if (token = this.tokenizer.tag(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // link\n if (token = this.tokenizer.link(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // reflink, nolink\n if (token = this.tokenizer.reflink(src, this.tokens.links)) {\n src = src.substring(token.raw.length);\n const lastToken = tokens.at(-1);\n if (token.type === 'text' && lastToken?.type === 'text') {\n lastToken.raw += token.raw;\n lastToken.text += token.text;\n } else {\n tokens.push(token);\n }\n continue;\n }\n\n // em & strong\n if (token = this.tokenizer.emStrong(src, maskedSrc, prevChar)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // code\n if (token = this.tokenizer.codespan(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // br\n if (token = this.tokenizer.br(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // del (gfm)\n if (token = this.tokenizer.del(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // autolink\n if (token = this.tokenizer.autolink(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // url (gfm)\n if (!this.state.inLink && (token = this.tokenizer.url(src))) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // text\n // prevent inlineText consuming extensions by clipping 'src' to extension start\n let cutSrc = src;\n if (this.options.extensions?.startInline) {\n let startIndex = Infinity;\n const tempSrc = src.slice(1);\n let tempStart;\n this.options.extensions.startInline.forEach((getStartIndex) => {\n tempStart = getStartIndex.call({ lexer: this }, tempSrc);\n if (typeof tempStart === 'number' && tempStart >= 0) {\n startIndex = Math.min(startIndex, tempStart);\n }\n });\n if (startIndex < Infinity && startIndex >= 0) {\n cutSrc = src.substring(0, startIndex + 1);\n }\n }\n if (token = this.tokenizer.inlineText(cutSrc)) {\n src = src.substring(token.raw.length);\n if (token.raw.slice(-1) !== '_') { // Track prevChar before string of ____ started\n prevChar = token.raw.slice(-1);\n }\n keepPrevChar = true;\n const lastToken = tokens.at(-1);\n if (lastToken?.type === 'text') {\n lastToken.raw += token.raw;\n lastToken.text += token.text;\n } else {\n tokens.push(token);\n }\n continue;\n }\n\n if (src) {\n const errMsg = 'Infinite loop on byte: ' + src.charCodeAt(0);\n if (this.options.silent) {\n console.error(errMsg);\n break;\n } else {\n throw new Error(errMsg);\n }\n }\n }\n\n return tokens;\n }\n}\n", "import { _defaults } from './defaults.ts';\nimport {\n cleanUrl,\n escape,\n} from './helpers.ts';\nimport { other } from './rules.ts';\nimport type { MarkedOptions } from './MarkedOptions.ts';\nimport type { Tokens } from './Tokens.ts';\nimport type { _Parser } from './Parser.ts';\n\n/**\n * Renderer\n */\nexport class _Renderer<ParserOutput = string, RendererOutput = string> {\n options: MarkedOptions<ParserOutput, RendererOutput>;\n parser!: _Parser<ParserOutput, RendererOutput>; // set by the parser\n constructor(options?: MarkedOptions<ParserOutput, RendererOutput>) {\n this.options = options || _defaults;\n }\n\n space(token: Tokens.Space): RendererOutput {\n return '' as RendererOutput;\n }\n\n code({ text, lang, escaped }: Tokens.Code): RendererOutput {\n const langString = (lang || '').match(other.notSpaceStart)?.[0];\n\n const code = text.replace(other.endingNewline, '') + '\\n';\n\n if (!langString) {\n return '<pre><code>'\n + (escaped ? code : escape(code, true))\n + '</code></pre>\\n' as RendererOutput;\n }\n\n return '<pre><code class=\"language-'\n + escape(langString)\n + '\">'\n + (escaped ? code : escape(code, true))\n + '</code></pre>\\n' as RendererOutput;\n }\n\n blockquote({ tokens }: Tokens.Blockquote): RendererOutput {\n const body = this.parser.parse(tokens);\n return `<blockquote>\\n${body}</blockquote>\\n` as RendererOutput;\n }\n\n html({ text }: Tokens.HTML | Tokens.Tag): RendererOutput {\n return text as RendererOutput;\n }\n\n def(token: Tokens.Def): RendererOutput {\n return '' as RendererOutput;\n }\n\n heading({ tokens, depth }: Tokens.Heading): RendererOutput {\n return `<h${depth}>${this.parser.parseInline(tokens)}</h${depth}>\\n` as RendererOutput;\n }\n\n hr(token: Tokens.Hr): RendererOutput {\n return '<hr>\\n' as RendererOutput;\n }\n\n list(token: Tokens.List): RendererOutput {\n const ordered = token.ordered;\n const start = token.start;\n\n let body = '';\n for (let j = 0; j < token.items.length; j++) {\n const item = token.items[j];\n body += this.listitem(item);\n }\n\n const type = ordered ? 'ol' : 'ul';\n const startAttr = (ordered && start !== 1) ? (' start=\"' + start + '\"') : '';\n return '<' + type + startAttr + '>\\n' + body + '</' + type + '>\\n' as RendererOutput;\n }\n\n listitem(item: Tokens.ListItem): RendererOutput {\n return `<li>${this.parser.parse(item.tokens)}</li>\\n` as RendererOutput;\n }\n\n checkbox({ checked }: Tokens.Checkbox): RendererOutput {\n return '<input '\n + (checked ? 'checked=\"\" ' : '')\n + 'disabled=\"\" type=\"checkbox\"> ' as RendererOutput;\n }\n\n paragraph({ tokens }: Tokens.Paragraph): RendererOutput {\n return `<p>${this.parser.parseInline(tokens)}</p>\\n` as RendererOutput;\n }\n\n table(token: Tokens.Table): RendererOutput {\n let header = '';\n\n // header\n let cell = '';\n for (let j = 0; j < token.header.length; j++) {\n cell += this.tablecell(token.header[j]);\n }\n header += this.tablerow({ text: cell as ParserOutput });\n\n let body = '';\n for (let j = 0; j < token.rows.length; j++) {\n const row = token.rows[j];\n\n cell = '';\n for (let k = 0; k < row.length; k++) {\n cell += this.tablecell(row[k]);\n }\n\n body += this.tablerow({ text: cell as ParserOutput });\n }\n if (body) body = `<tbody>${body}</tbody>`;\n\n return '<table>\\n'\n + '<thead>\\n'\n + header\n + '</thead>\\n'\n + body\n + '</table>\\n' as RendererOutput;\n }\n\n tablerow({ text }: Tokens.TableRow<ParserOutput>): RendererOutput {\n return `<tr>\\n${text}</tr>\\n` as RendererOutput;\n }\n\n tablecell(token: Tokens.TableCell): RendererOutput {\n const content = this.parser.parseInline(token.tokens);\n const type = token.header ? 'th' : 'td';\n const tag = token.align\n ? `<${type} align=\"${token.align}\">`\n : `<${type}>`;\n return tag + content + `</${type}>\\n` as RendererOutput;\n }\n\n /**\n * span level renderer\n */\n strong({ tokens }: Tokens.Strong): RendererOutput {\n return `<strong>${this.parser.parseInline(tokens)}</strong>` as RendererOutput;\n }\n\n em({ tokens }: Tokens.Em): RendererOutput {\n return `<em>${this.parser.parseInline(tokens)}</em>` as RendererOutput;\n }\n\n codespan({ text }: Tokens.Codespan): RendererOutput {\n return `<code>${escape(text, true)}</code>` as RendererOutput;\n }\n\n br(token: Tokens.Br): RendererOutput {\n return '<br>' as RendererOutput;\n }\n\n del({ tokens }: Tokens.Del): RendererOutput {\n return `<del>${this.parser.parseInline(tokens)}</del>` as RendererOutput;\n }\n\n link({ href, title, tokens }: Tokens.Link): RendererOutput {\n const text = this.parser.parseInline(tokens) as string;\n const cleanHref = cleanUrl(href);\n if (cleanHref === null) {\n return text as RendererOutput;\n }\n href = cleanHref;\n let out = '<a href=\"' + href + '\"';\n if (title) {\n out += ' title=\"' + (escape(title)) + '\"';\n }\n out += '>' + text + '</a>';\n return out as RendererOutput;\n }\n\n image({ href, title, text, tokens }: Tokens.Image): RendererOutput {\n if (tokens) {\n text = this.parser.parseInline(tokens, this.parser.textRenderer) as string;\n }\n const cleanHref = cleanUrl(href);\n if (cleanHref === null) {\n return escape(text) as RendererOutput;\n }\n href = cleanHref;\n\n let out = `<img src=\"${href}\" alt=\"${text}\"`;\n if (title) {\n out += ` title=\"${escape(title)}\"`;\n }\n out += '>';\n return out as RendererOutput;\n }\n\n text(token: Tokens.Text | Tokens.Escape): RendererOutput {\n return 'tokens' in token && token.tokens\n ? this.parser.parseInline(token.tokens) as unknown as RendererOutput\n : ('escaped' in token && token.escaped ? token.text as RendererOutput : escape(token.text) as RendererOutput);\n }\n}\n", "import type { Tokens } from './Tokens.ts';\n\n/**\n * TextRenderer\n * returns only the textual part of the token\n */\nexport class _TextRenderer<RendererOutput = string> {\n // no need for block level renderers\n strong({ text }: Tokens.Strong): RendererOutput {\n return text as RendererOutput;\n }\n\n em({ text }: Tokens.Em): RendererOutput {\n return text as RendererOutput;\n }\n\n codespan({ text }: Tokens.Codespan): RendererOutput {\n return text as RendererOutput;\n }\n\n del({ text }: Tokens.Del): RendererOutput {\n return text as RendererOutput;\n }\n\n html({ text }: Tokens.HTML | Tokens.Tag): RendererOutput {\n return text as RendererOutput;\n }\n\n text({ text }: Tokens.Text | Tokens.Escape | Tokens.Tag): RendererOutput {\n return text as RendererOutput;\n }\n\n link({ text }: Tokens.Link): RendererOutput {\n return '' + text as RendererOutput;\n }\n\n image({ text }: Tokens.Image): RendererOutput {\n return '' + text as RendererOutput;\n }\n\n br(): RendererOutput {\n return '' as RendererOutput;\n }\n\n checkbox({ raw }: Tokens.Checkbox): RendererOutput {\n return raw as RendererOutput;\n }\n}\n", "import { _Renderer } from './Renderer.ts';\nimport { _TextRenderer } from './TextRenderer.ts';\nimport { _defaults } from './defaults.ts';\nimport type { MarkedToken, Token, Tokens } from './Tokens.ts';\nimport type { MarkedOptions } from './MarkedOptions.ts';\n\n/**\n * Parsing & Compiling\n */\nexport class _Parser<ParserOutput = string, RendererOutput = string> {\n options: MarkedOptions<ParserOutput, RendererOutput>;\n renderer: _Renderer<ParserOutput, RendererOutput>;\n textRenderer: _TextRenderer<RendererOutput>;\n constructor(options?: MarkedOptions<ParserOutput, RendererOutput>) {\n this.options = options || _defaults;\n this.options.renderer = this.options.renderer || new _Renderer<ParserOutput, RendererOutput>();\n this.renderer = this.options.renderer;\n this.renderer.options = this.options;\n this.renderer.parser = this;\n this.textRenderer = new _TextRenderer<RendererOutput>();\n }\n\n /**\n * Static Parse Method\n */\n static parse<ParserOutput = string, RendererOutput = string>(tokens: Token[], options?: MarkedOptions<ParserOutput, RendererOutput>) {\n const parser = new _Parser<ParserOutput, RendererOutput>(options);\n return parser.parse(tokens);\n }\n\n /**\n * Static Parse Inline Method\n */\n static parseInline<ParserOutput = string, RendererOutput = string>(tokens: Token[], options?: MarkedOptions<ParserOutput, RendererOutput>) {\n const parser = new _Parser<ParserOutput, RendererOutput>(options);\n return parser.parseInline(tokens);\n }\n\n /**\n * Parse Loop\n */\n parse(tokens: Token[]): ParserOutput {\n let out = '';\n\n for (let i = 0; i < tokens.length; i++) {\n const anyToken = tokens[i];\n\n // Run any renderer extensions\n if (this.options.extensions?.renderers?.[anyToken.type]) {\n const genericToken = anyToken as Tokens.Generic;\n const ret = this.options.extensions.renderers[genericToken.type].call({ parser: this }, genericToken);\n if (ret !== false || !['space', 'hr', 'heading', 'code', 'table', 'blockquote', 'list', 'html', 'def', 'paragraph', 'text'].includes(genericToken.type)) {\n out += ret || '';\n continue;\n }\n }\n\n const token = anyToken as MarkedToken;\n\n switch (token.type) {\n case 'space': {\n out += this.renderer.space(token);\n break;\n }\n case 'hr': {\n out += this.renderer.hr(token);\n break;\n }\n case 'heading': {\n out += this.renderer.heading(token);\n break;\n }\n case 'code': {\n out += this.renderer.code(token);\n break;\n }\n case 'table': {\n out += this.renderer.table(token);\n break;\n }\n case 'blockquote': {\n out += this.renderer.blockquote(token);\n break;\n }\n case 'list': {\n out += this.renderer.list(token);\n break;\n }\n case 'checkbox': {\n out += this.renderer.checkbox(token);\n break;\n }\n case 'html': {\n out += this.renderer.html(token);\n break;\n }\n case 'def': {\n out += this.renderer.def(token);\n break;\n }\n case 'paragraph': {\n out += this.renderer.paragraph(token);\n break;\n }\n case 'text': {\n out += this.renderer.text(token);\n break;\n }\n\n default: {\n const errMsg = 'Token with \"' + token.type + '\" type was not found.';\n if (this.options.silent) {\n console.error(errMsg);\n return '' as ParserOutput;\n } else {\n throw new Error(errMsg);\n }\n }\n }\n }\n\n return out as ParserOutput;\n }\n\n /**\n * Parse Inline Tokens\n */\n parseInline(tokens: Token[], renderer: _Renderer<ParserOutput, RendererOutput> | _TextRenderer<RendererOutput> = this.renderer): ParserOutput {\n let out = '';\n\n for (let i = 0; i < tokens.length; i++) {\n const anyToken = tokens[i];\n\n // Run any renderer extensions\n if (this.options.extensions?.renderers?.[anyToken.type]) {\n const ret = this.options.extensions.renderers[anyToken.type].call({ parser: this }, anyToken);\n if (ret !== false || !['escape', 'html', 'link', 'image', 'strong', 'em', 'codespan', 'br', 'del', 'text'].includes(anyToken.type)) {\n out += ret || '';\n continue;\n }\n }\n\n const token = anyToken as MarkedToken;\n\n switch (token.type) {\n case 'escape': {\n out += renderer.text(token);\n break;\n }\n case 'html': {\n out += renderer.html(token);\n break;\n }\n case 'link': {\n out += renderer.link(token);\n break;\n }\n case 'image': {\n out += renderer.image(token);\n break;\n }\n case 'checkbox': {\n out += renderer.checkbox(token);\n break;\n }\n case 'strong': {\n out += renderer.strong(token);\n break;\n }\n case 'em': {\n out += renderer.em(token);\n break;\n }\n case 'codespan': {\n out += renderer.codespan(token);\n break;\n }\n case 'br': {\n out += renderer.br(token);\n break;\n }\n case 'del': {\n out += renderer.del(token);\n break;\n }\n case 'text': {\n out += renderer.text(token);\n break;\n }\n default: {\n const errMsg = 'Token with \"' + token.type + '\" type was not found.';\n if (this.options.silent) {\n console.error(errMsg);\n return '' as ParserOutput;\n } else {\n throw new Error(errMsg);\n }\n }\n }\n }\n return out as ParserOutput;\n }\n}\n", "import { _defaults } from './defaults.ts';\nimport { _Lexer } from './Lexer.ts';\nimport { _Parser } from './Parser.ts';\nimport type { MarkedOptions } from './MarkedOptions.ts';\nimport type { Token, TokensList } from './Tokens.ts';\n\nexport class _Hooks<ParserOutput = string, RendererOutput = string> {\n options: MarkedOptions<ParserOutput, RendererOutput>;\n block?: boolean;\n\n constructor(options?: MarkedOptions<ParserOutput, RendererOutput>) {\n this.options = options || _defaults;\n }\n\n static passThroughHooks = new Set([\n 'preprocess',\n 'postprocess',\n 'processAllTokens',\n 'emStrongMask',\n ]);\n\n static passThroughHooksRespectAsync = new Set([\n 'preprocess',\n 'postprocess',\n 'processAllTokens',\n ]);\n\n /**\n * Process markdown before marked\n */\n preprocess(markdown: string) {\n return markdown;\n }\n\n /**\n * Process HTML after marked is finished\n */\n postprocess(html: ParserOutput) {\n return html;\n }\n\n /**\n * Process all tokens before walk tokens\n */\n processAllTokens(tokens: Token[] | TokensList) {\n return tokens;\n }\n\n /**\n * Mask contents that should not be interpreted as em/strong delimiters\n */\n emStrongMask(src: string) {\n return src;\n }\n\n /**\n * Provide function to tokenize markdown\n */\n provideLexer() {\n return this.block ? _Lexer.lex : _Lexer.lexInline;\n }\n\n /**\n * Provide function to parse tokens\n */\n provideParser() {\n return this.block ? _Parser.parse<ParserOutput, RendererOutput> : _Parser.parseInline<ParserOutput, RendererOutput>;\n }\n}\n", "import { _getDefaults } from './defaults.ts';\nimport { _Lexer } from './Lexer.ts';\nimport { _Parser } from './Parser.ts';\nimport { _Hooks } from './Hooks.ts';\nimport { _Renderer } from './Renderer.ts';\nimport { _Tokenizer } from './Tokenizer.ts';\nimport { _TextRenderer } from './TextRenderer.ts';\nimport { escape } from './helpers.ts';\nimport type { MarkedExtension, MarkedOptions } from './MarkedOptions.ts';\nimport type { Token, Tokens, TokensList } from './Tokens.ts';\n\nexport type MaybePromise = void | Promise<void>;\n\ntype UnknownFunction = (...args: unknown[]) => unknown;\ntype GenericRendererFunction = (...args: unknown[]) => string | false;\n\nexport class Marked<ParserOutput = string, RendererOutput = string> {\n defaults = _getDefaults<ParserOutput, RendererOutput>();\n options = this.setOptions;\n\n parse = this.parseMarkdown(true);\n parseInline = this.parseMarkdown(false);\n\n Parser = _Parser<ParserOutput, RendererOutput>;\n Renderer = _Renderer<ParserOutput, RendererOutput>;\n TextRenderer = _TextRenderer<RendererOutput>;\n Lexer = _Lexer;\n Tokenizer = _Tokenizer<ParserOutput, RendererOutput>;\n Hooks = _Hooks<ParserOutput, RendererOutput>;\n\n constructor(...args: MarkedExtension<ParserOutput, RendererOutput>[]) {\n this.use(...args);\n }\n\n /**\n * Run callback for every token\n */\n walkTokens(tokens: Token[] | TokensList, callback: (token: Token) => MaybePromise | MaybePromise[]) {\n let values: MaybePromise[] = [];\n for (const token of tokens) {\n values = values.concat(callback.call(this, token));\n switch (token.type) {\n case 'table': {\n const tableToken = token as Tokens.Table;\n for (const cell of tableToken.header) {\n values = values.concat(this.walkTokens(cell.tokens, callback));\n }\n for (const row of tableToken.rows) {\n for (const cell of row) {\n values = values.concat(this.walkTokens(cell.tokens, callback));\n }\n }\n break;\n }\n case 'list': {\n const listToken = token as Tokens.List;\n values = values.concat(this.walkTokens(listToken.items, callback));\n break;\n }\n default: {\n const genericToken = token as Tokens.Generic;\n if (this.defaults.extensions?.childTokens?.[genericToken.type]) {\n this.defaults.extensions.childTokens[genericToken.type].forEach((childTokens) => {\n const tokens = genericToken[childTokens].flat(Infinity) as Token[] | TokensList;\n values = values.concat(this.walkTokens(tokens, callback));\n });\n } else if (genericToken.tokens) {\n values = values.concat(this.walkTokens(genericToken.tokens, callback));\n }\n }\n }\n }\n return values;\n }\n\n use(...args: MarkedExtension<ParserOutput, RendererOutput>[]) {\n const extensions: MarkedOptions<ParserOutput, RendererOutput>['extensions'] = this.defaults.extensions || { renderers: {}, childTokens: {} };\n\n args.forEach((pack) => {\n // copy options to new object\n const opts = { ...pack } as MarkedOptions<ParserOutput, RendererOutput>;\n\n // set async to true if it was set to true before\n opts.async = this.defaults.async || opts.async || false;\n\n // ==-- Parse \"addon\" extensions --== //\n if (pack.extensions) {\n pack.extensions.forEach((ext) => {\n if (!ext.name) {\n throw new Error('extension name required');\n }\n if ('renderer' in ext) { // Renderer extensions\n const prevRenderer = extensions.renderers[ext.name];\n if (prevRenderer) {\n // Replace extension with func to run new extension but fall back if false\n extensions.renderers[ext.name] = function(...args) {\n let ret = ext.renderer.apply(this, args);\n if (ret === false) {\n ret = prevRenderer.apply(this, args);\n }\n return ret;\n };\n } else {\n extensions.renderers[ext.name] = ext.renderer;\n }\n }\n if ('tokenizer' in ext) { // Tokenizer Extensions\n if (!ext.level || (ext.level !== 'block' && ext.level !== 'inline')) {\n throw new Error(\"extension level must be 'block' or 'inline'\");\n }\n const extLevel = extensions[ext.level];\n if (extLevel) {\n extLevel.unshift(ext.tokenizer);\n } else {\n extensions[ext.level] = [ext.tokenizer];\n }\n if (ext.start) { // Function to check for start of token\n if (ext.level === 'block') {\n if (extensions.startBlock) {\n extensions.startBlock.push(ext.start);\n } else {\n extensions.startBlock = [ext.start];\n }\n } else if (ext.level === 'inline') {\n if (extensions.startInline) {\n extensions.startInline.push(ext.start);\n } else {\n extensions.startInline = [ext.start];\n }\n }\n }\n }\n if ('childTokens' in ext && ext.childTokens) { // Child tokens to be visited by walkTokens\n extensions.childTokens[ext.name] = ext.childTokens;\n }\n });\n opts.extensions = extensions;\n }\n\n // ==-- Parse \"overwrite\" extensions --== //\n if (pack.renderer) {\n const renderer = this.defaults.renderer || new _Renderer<ParserOutput, RendererOutput>(this.defaults);\n for (const prop in pack.renderer) {\n if (!(prop in renderer)) {\n throw new Error(`renderer '${prop}' does not exist`);\n }\n if (['options', 'parser'].includes(prop)) {\n // ignore options property\n continue;\n }\n const rendererProp = prop as Exclude<keyof _Renderer<ParserOutput, RendererOutput>, 'options' | 'parser'>;\n const rendererFunc = pack.renderer[rendererProp] as GenericRendererFunction;\n const prevRenderer = renderer[rendererProp] as GenericRendererFunction;\n // Replace renderer with func to run extension, but fall back if false\n renderer[rendererProp] = (...args: unknown[]) => {\n let ret = rendererFunc.apply(renderer, args);\n if (ret === false) {\n ret = prevRenderer.apply(renderer, args);\n }\n return (ret || '') as RendererOutput;\n };\n }\n opts.renderer = renderer;\n }\n if (pack.tokenizer) {\n const tokenizer = this.defaults.tokenizer || new _Tokenizer<ParserOutput, RendererOutput>(this.defaults);\n for (const prop in pack.tokenizer) {\n if (!(prop in tokenizer)) {\n throw new Error(`tokenizer '${prop}' does not exist`);\n }\n if (['options', 'rules', 'lexer'].includes(prop)) {\n // ignore options, rules, and lexer properties\n continue;\n }\n const tokenizerProp = prop as Exclude<keyof _Tokenizer<ParserOutput, RendererOutput>, 'options' | 'rules' | 'lexer'>;\n const tokenizerFunc = pack.tokenizer[tokenizerProp] as UnknownFunction;\n const prevTokenizer = tokenizer[tokenizerProp] as UnknownFunction;\n // Replace tokenizer with func to run extension, but fall back if false\n // @ts-expect-error cannot type tokenizer function dynamically\n tokenizer[tokenizerProp] = (...args: unknown[]) => {\n let ret = tokenizerFunc.apply(tokenizer, args);\n if (ret === false) {\n ret = prevTokenizer.apply(tokenizer, args);\n }\n return ret;\n };\n }\n opts.tokenizer = tokenizer;\n }\n\n // ==-- Parse Hooks extensions --== //\n if (pack.hooks) {\n const hooks = this.defaults.hooks || new _Hooks<ParserOutput, RendererOutput>();\n for (const prop in pack.hooks) {\n if (!(prop in hooks)) {\n throw new Error(`hook '${prop}' does not exist`);\n }\n if (['options', 'block'].includes(prop)) {\n // ignore options and block properties\n continue;\n }\n const hooksProp = prop as Exclude<keyof _Hooks<ParserOutput, RendererOutput>, 'options' | 'block'>;\n const hooksFunc = pack.hooks[hooksProp] as UnknownFunction;\n const prevHook = hooks[hooksProp] as UnknownFunction;\n if (_Hooks.passThroughHooks.has(prop)) {\n // @ts-expect-error cannot type hook function dynamically\n hooks[hooksProp] = (arg: unknown) => {\n if (this.defaults.async && _Hooks.passThroughHooksRespectAsync.has(prop)) {\n return (async() => {\n const ret = await hooksFunc.call(hooks, arg);\n return prevHook.call(hooks, ret);\n })();\n }\n\n const ret = hooksFunc.call(hooks, arg);\n return prevHook.call(hooks, ret);\n };\n } else {\n // @ts-expect-error cannot type hook function dynamically\n hooks[hooksProp] = (...args: unknown[]) => {\n if (this.defaults.async) {\n return (async() => {\n let ret = await hooksFunc.apply(hooks, args);\n if (ret === false) {\n ret = await prevHook.apply(hooks, args);\n }\n return ret;\n })();\n }\n\n let ret = hooksFunc.apply(hooks, args);\n if (ret === false) {\n ret = prevHook.apply(hooks, args);\n }\n return ret;\n };\n }\n }\n opts.hooks = hooks;\n }\n\n // ==-- Parse WalkTokens extensions --== //\n if (pack.walkTokens) {\n const walkTokens = this.defaults.walkTokens;\n const packWalktokens = pack.walkTokens;\n opts.walkTokens = function(token) {\n let values: MaybePromise[] = [];\n values.push(packWalktokens.call(this, token));\n if (walkTokens) {\n values = values.concat(walkTokens.call(this, token));\n }\n return values;\n };\n }\n\n this.defaults = { ...this.defaults, ...opts };\n });\n\n return this;\n }\n\n setOptions(opt: MarkedOptions<ParserOutput, RendererOutput>) {\n this.defaults = { ...this.defaults, ...opt };\n return this;\n }\n\n lexer(src: string, options?: MarkedOptions<ParserOutput, RendererOutput>) {\n return _Lexer.lex(src, options ?? this.defaults);\n }\n\n parser(tokens: Token[], options?: MarkedOptions<ParserOutput, RendererOutput>) {\n return _Parser.parse<ParserOutput, RendererOutput>(tokens, options ?? this.defaults);\n }\n\n private parseMarkdown(blockType: boolean) {\n type overloadedParse = {\n (src: string, options: MarkedOptions<ParserOutput, RendererOutput> & { async: true }): Promise<ParserOutput>;\n (src: string, options: MarkedOptions<ParserOutput, RendererOutput> & { async: false }): ParserOutput;\n (src: string, options?: MarkedOptions<ParserOutput, RendererOutput> | null): ParserOutput | Promise<ParserOutput>;\n };\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const parse: overloadedParse = (src: string, options?: MarkedOptions<ParserOutput, RendererOutput> | null): any => {\n const origOpt = { ...options };\n const opt = { ...this.defaults, ...origOpt };\n\n const throwError = this.onError(!!opt.silent, !!opt.async);\n\n // throw error if an extension set async to true but parse was called with async: false\n if (this.defaults.async === true && origOpt.async === false) {\n return throwError(new Error('marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise.'));\n }\n\n // throw error in case of non string input\n if (typeof src === 'undefined' || src === null) {\n return throwError(new Error('marked(): input parameter is undefined or null'));\n }\n if (typeof src !== 'string') {\n return throwError(new Error('marked(): input parameter is of type '\n + Object.prototype.toString.call(src) + ', string expected'));\n }\n\n if (opt.hooks) {\n opt.hooks.options = opt;\n opt.hooks.block = blockType;\n }\n\n if (opt.async) {\n return (async() => {\n const processedSrc = opt.hooks ? await opt.hooks.preprocess(src) : src;\n const lexer = opt.hooks ? await opt.hooks.provideLexer() : (blockType ? _Lexer.lex : _Lexer.lexInline);\n const tokens = await lexer(processedSrc, opt);\n const processedTokens = opt.hooks ? await opt.hooks.processAllTokens(tokens) : tokens;\n if (opt.walkTokens) {\n await Promise.all(this.walkTokens(processedTokens, opt.walkTokens));\n }\n const parser = opt.hooks ? await opt.hooks.provideParser() : (blockType ? _Parser.parse : _Parser.parseInline);\n const html = await parser(processedTokens, opt);\n return opt.hooks ? await opt.hooks.postprocess(html) : html;\n })().catch(throwError);\n }\n\n try {\n if (opt.hooks) {\n src = opt.hooks.preprocess(src) as string;\n }\n const lexer = opt.hooks ? opt.hooks.provideLexer() : (blockType ? _Lexer.lex : _Lexer.lexInline);\n let tokens = lexer(src, opt);\n if (opt.hooks) {\n tokens = opt.hooks.processAllTokens(tokens);\n }\n if (opt.walkTokens) {\n this.walkTokens(tokens, opt.walkTokens);\n }\n const parser = opt.hooks ? opt.hooks.provideParser() : (blockType ? _Parser.parse : _Parser.parseInline);\n let html = parser(tokens, opt);\n if (opt.hooks) {\n html = opt.hooks.postprocess(html);\n }\n return html;\n } catch(e) {\n return throwError(e as Error);\n }\n };\n\n return parse;\n }\n\n private onError(silent: boolean, async: boolean) {\n return (e: Error): string | Promise<string> => {\n e.message += '\\nPlease report this to https://github.com/markedjs/marked.';\n\n if (silent) {\n const msg = '<p>An error occurred:</p><pre>'\n + escape(e.message + '', true)\n + '</pre>';\n if (async) {\n return Promise.resolve(msg);\n }\n return msg;\n }\n\n if (async) {\n return Promise.reject(e);\n }\n throw e;\n };\n }\n}\n", "import { _Lexer } from './Lexer.ts';\nimport { _Parser } from './Parser.ts';\nimport { _Tokenizer } from './Tokenizer.ts';\nimport { _Renderer } from './Renderer.ts';\nimport { _TextRenderer } from './TextRenderer.ts';\nimport { _Hooks } from './Hooks.ts';\nimport { Marked } from './Instance.ts';\nimport {\n _getDefaults,\n changeDefaults,\n _defaults,\n} from './defaults.ts';\nimport type { MarkedExtension, MarkedOptions } from './MarkedOptions.ts';\nimport type { Token, TokensList } from './Tokens.ts';\nimport type { MaybePromise } from './Instance.ts';\n\nconst markedInstance = new Marked();\n\n/**\n * Compiles markdown to HTML asynchronously.\n *\n * @param src String of markdown source to be compiled\n * @param options Hash of options, having async: true\n * @return Promise of string of compiled HTML\n */\nexport function marked(src: string, options: MarkedOptions & { async: true }): Promise<string>;\n\n/**\n * Compiles markdown to HTML.\n *\n * @param src String of markdown source to be compiled\n * @param options Optional hash of options\n * @return String of compiled HTML. Will be a Promise of string if async is set to true by any extensions.\n */\nexport function marked(src: string, options: MarkedOptions & { async: false }): string;\nexport function marked(src: string, options: MarkedOptions & { async: true }): Promise<string>;\nexport function marked(src: string, options?: MarkedOptions | null): string | Promise<string>;\nexport function marked(src: string, opt?: MarkedOptions | null): string | Promise<string> {\n return markedInstance.parse(src, opt);\n}\n\n/**\n * Sets the default options.\n *\n * @param options Hash of options\n */\nmarked.options =\n marked.setOptions = function(options: MarkedOptions) {\n markedInstance.setOptions(options);\n marked.defaults = markedInstance.defaults;\n changeDefaults(marked.defaults);\n return marked;\n };\n\n/**\n * Gets the original marked default options.\n */\nmarked.getDefaults = _getDefaults;\n\nmarked.defaults = _defaults;\n\n/**\n * Use Extension\n */\n\nmarked.use = function(...args: MarkedExtension[]) {\n markedInstance.use(...args);\n marked.defaults = markedInstance.defaults;\n changeDefaults(marked.defaults);\n return marked;\n};\n\n/**\n * Run callback for every token\n */\n\nmarked.walkTokens = function(tokens: Token[] | TokensList, callback: (token: Token) => MaybePromise | MaybePromise[]) {\n return markedInstance.walkTokens(tokens, callback);\n};\n\n/**\n * Compiles markdown to HTML without enclosing `p` tag.\n *\n * @param src String of markdown source to be compiled\n * @param options Hash of options\n * @return String of compiled HTML\n */\nmarked.parseInline = markedInstance.parseInline;\n\n/**\n * Expose\n */\nmarked.Parser = _Parser;\nmarked.parser = _Parser.parse;\nmarked.Renderer = _Renderer;\nmarked.TextRenderer = _TextRenderer;\nmarked.Lexer = _Lexer;\nmarked.lexer = _Lexer.lex;\nmarked.Tokenizer = _Tokenizer;\nmarked.Hooks = _Hooks;\nmarked.parse = marked;\n\nexport const options = marked.options;\nexport const setOptions = marked.setOptions;\nexport const use = marked.use;\nexport const walkTokens = marked.walkTokens;\nexport const parseInline = marked.parseInline;\nexport const parse = marked;\nexport const parser = _Parser.parse;\nexport const lexer = _Lexer.lex;\nexport { _defaults as defaults, _getDefaults as getDefaults } from './defaults.ts';\nexport { _Lexer as Lexer } from './Lexer.ts';\nexport { _Parser as Parser } from './Parser.ts';\nexport { _Tokenizer as Tokenizer } from './Tokenizer.ts';\nexport { _Renderer as Renderer } from './Renderer.ts';\nexport { _TextRenderer as TextRenderer } from './TextRenderer.ts';\nexport { _Hooks as Hooks } from './Hooks.ts';\nexport { Marked } from './Instance.ts';\nexport type * from './MarkedOptions.ts';\nexport type * from './Tokens.ts';\n", "import DOMPurify from 'dompurify';\nimport { unsafeHTML } from 'lit-html/directives/unsafe-html.js';\nimport { marked } from 'marked';\n\n/**\n * Render Markdown safely as HTML using marked and DOMPurify.\n * Returns a lit-html TemplateResult via the unsafeHTML directive so it can be\n * embedded directly in templates.\n *\n * @param {string} markdown - Markdown source text\n */\nexport function renderMarkdown(markdown) {\n const parsed = /** @type {string} */ (marked.parse(markdown));\n const html_string = DOMPurify.sanitize(parsed);\n return unsafeHTML(html_string);\n}\n", "/**\n * Known status values in canonical order.\n *\n * @type {Array<'open'|'in_progress'|'closed'>}\n */\nexport const STATUSES = ['open', 'in_progress', 'closed'];\n\n/**\n * Map canonical status to display label.\n *\n * @param {string | null | undefined} status\n * @returns {string}\n */\nexport function statusLabel(status) {\n switch ((status || '').toString()) {\n case 'open':\n return 'Open';\n case 'in_progress':\n return 'In progress';\n case 'closed':\n return 'Closed';\n default:\n return (status || '').toString() || 'Open';\n }\n}\n", "// Issue Detail view implementation (lit-html based)\nimport { html, render } from 'lit-html';\nimport { parseView } from '../router.js';\nimport { issueHashFor } from '../utils/issue-url.js';\nimport { debug } from '../utils/logging.js';\nimport { renderMarkdown } from '../utils/markdown.js';\nimport { emojiForPriority } from '../utils/priority-badge.js';\nimport { priority_levels } from '../utils/priority.js';\nimport { statusLabel } from '../utils/status.js';\nimport { showToast } from '../utils/toast.js';\nimport { createTypeBadge } from '../utils/type-badge.js';\n\n/**\n * Format a date string for display.\n *\n * @param {string} [dateStr]\n * @returns {string}\n */\nfunction formatCommentDate(dateStr) {\n if (!dateStr) return '';\n try {\n const date = new Date(dateStr);\n return date.toLocaleDateString(undefined, {\n year: 'numeric',\n month: 'short',\n day: 'numeric',\n hour: '2-digit',\n minute: '2-digit'\n });\n } catch {\n return dateStr;\n }\n}\n\n/**\n * @typedef {Object} Dependency\n * @property {string} id\n * @property {string} [title]\n * @property {string} [status]\n * @property {number} [priority]\n * @property {string} [issue_type]\n */\n\n/**\n * @typedef {Object} Comment\n * @property {number} id\n * @property {string} [author]\n * @property {string} text\n * @property {string} [created_at]\n */\n\n/**\n * @typedef {Object} IssueDetail\n * @property {string} id\n * @property {string} [title]\n * @property {string} [description]\n * @property {string} [design]\n * @property {string} [acceptance]\n * @property {string} [notes]\n * @property {string} [status]\n * @property {string} [assignee]\n * @property {number} [priority]\n * @property {string[]} [labels]\n * @property {Dependency[]} [dependencies]\n * @property {Dependency[]} [dependents]\n * @property {Comment[]} [comments]\n */\n\n/**\n * @param {string} hash\n */\nfunction defaultNavigateFn(hash) {\n window.location.hash = hash;\n}\n\n/**\n * Create the Issue Detail view.\n *\n * @param {HTMLElement} mount_element - Element to render into.\n * @param {(type: string, payload?: unknown) => Promise<unknown>} sendFn - RPC transport.\n * @param {(hash: string) => void} [navigateFn] - Navigation function; defaults to setting location.hash.\n * @param {{ snapshotFor?: (client_id: string) => any[], subscribe?: (fn: () => void) => () => void }} [issue_stores] - Optional issue stores for live updates.\n * @returns {{ load: (id: string) => Promise<void>, clear: () => void, destroy: () => void }} View API.\n */\nexport function createDetailView(\n mount_element,\n sendFn,\n navigateFn = defaultNavigateFn,\n issue_stores = undefined\n) {\n const log = debug('views:detail');\n /** @type {IssueDetail | null} */\n let current = null;\n /** @type {string | null} */\n let current_id = null;\n /** @type {boolean} */\n let pending = false;\n /** @type {boolean} */\n let edit_title = false;\n /** @type {boolean} */\n let edit_desc = false;\n /** @type {boolean} */\n let edit_design = false;\n /** @type {boolean} */\n let edit_notes = false;\n /** @type {boolean} */\n let edit_accept = false;\n /** @type {boolean} */\n let edit_assignee = false;\n /** @type {string} */\n let new_label_text = '';\n /** @type {string} */\n let comment_text = '';\n /** @type {boolean} */\n let comment_pending = false;\n\n /** @type {HTMLDialogElement | null} */\n let delete_dialog = null;\n\n function ensureDeleteDialog() {\n if (delete_dialog) return delete_dialog;\n delete_dialog = document.createElement('dialog');\n delete_dialog.id = 'delete-confirm-dialog';\n delete_dialog.setAttribute('role', 'alertdialog');\n delete_dialog.setAttribute('aria-modal', 'true');\n document.body.appendChild(delete_dialog);\n return delete_dialog;\n }\n\n function openDeleteDialog() {\n if (!current) return;\n const dialog = ensureDeleteDialog();\n const issueId = current.id;\n const issueTitle = current.title || '(no title)';\n dialog.innerHTML = `\n <div class=\"delete-confirm\">\n <h2 class=\"delete-confirm__title\">Delete Issue</h2>\n <p class=\"delete-confirm__message\">\n Are you sure you want to delete issue <strong>${issueId}</strong> \u2014 <strong>${issueTitle}</strong>? This action cannot be undone.\n </p>\n <div class=\"delete-confirm__actions\">\n <button type=\"button\" class=\"btn\" id=\"delete-cancel-btn\">Cancel</button>\n <button type=\"button\" class=\"btn danger\" id=\"delete-confirm-btn\">Delete</button>\n </div>\n </div>\n `;\n const cancelBtn = dialog.querySelector('#delete-cancel-btn');\n const confirmBtn = dialog.querySelector('#delete-confirm-btn');\n\n cancelBtn?.addEventListener('click', () => {\n if (typeof dialog.close === 'function') {\n dialog.close();\n }\n dialog.removeAttribute('open');\n });\n\n confirmBtn?.addEventListener('click', async () => {\n if (typeof dialog.close === 'function') {\n dialog.close();\n }\n dialog.removeAttribute('open');\n await performDelete();\n });\n\n dialog.addEventListener('cancel', (ev) => {\n ev.preventDefault();\n if (typeof dialog.close === 'function') {\n dialog.close();\n }\n dialog.removeAttribute('open');\n });\n\n if (typeof dialog.showModal === 'function') {\n try {\n dialog.showModal();\n dialog.setAttribute('open', '');\n } catch {\n dialog.setAttribute('open', '');\n }\n } else {\n dialog.setAttribute('open', '');\n }\n }\n\n async function performDelete() {\n if (!current) return;\n const id = current.id;\n try {\n await sendFn('delete-issue', { id });\n current = null;\n current_id = null;\n doRender();\n // Navigate back to close the dialog\n const view = parseView(window.location.hash || '');\n navigateFn(`#/${view}`);\n } catch (err) {\n log('delete failed: %o', err);\n showToast('Failed to delete issue', 'error');\n }\n }\n\n /**\n * @param {Event} ev\n */\n function onDeleteClick(ev) {\n ev.stopPropagation();\n ev.preventDefault();\n openDeleteDialog();\n }\n\n /** @param {string} id */\n function issueHref(id) {\n /** @type {'issues'|'epics'|'board'} */\n const view = parseView(window.location.hash || '');\n return issueHashFor(view, id);\n }\n\n /**\n * @param {string} message\n */\n function renderPlaceholder(message) {\n render(\n html`\n <div class=\"panel__body\" id=\"detail-root\">\n <p class=\"muted\">${message}</p>\n </div>\n `,\n mount_element\n );\n }\n\n /**\n * Refresh current from subscription store snapshot if available.\n */\n function refreshFromStore() {\n if (\n !current_id ||\n !issue_stores ||\n typeof issue_stores.snapshotFor !== 'function'\n ) {\n return;\n }\n const arr = /** @type {IssueDetail[]} */ (\n issue_stores.snapshotFor(`detail:${current_id}`)\n );\n if (Array.isArray(arr) && arr.length > 0) {\n // First item is the issue for this subscription\n const found =\n arr.find((it) => String(it.id) === String(current_id)) || arr[0];\n current = /** @type {IssueDetail} */ (found);\n }\n }\n\n // Live updates: re-render when issue stores change\n if (issue_stores && typeof issue_stores.subscribe === 'function') {\n issue_stores.subscribe(() => {\n try {\n refreshFromStore();\n doRender();\n } catch (err) {\n log('issue stores listener error %o', err);\n }\n });\n }\n\n // Handlers\n const onTitleSpanClick = () => {\n edit_title = true;\n doRender();\n };\n /**\n * @param {KeyboardEvent} ev\n */\n const onTitleKeydown = (ev) => {\n if (ev.key === 'Enter') {\n edit_title = true;\n doRender();\n } else if (ev.key === 'Escape') {\n edit_title = false;\n doRender();\n }\n };\n const onTitleSave = async () => {\n if (!current || pending) {\n return;\n }\n const input = /** @type {HTMLInputElement|null} */ (\n mount_element.querySelector('h2 input')\n );\n const prev = current.title || '';\n const next = input ? input.value : '';\n if (next === prev) {\n edit_title = false;\n doRender();\n return;\n }\n pending = true;\n if (input) {\n input.disabled = true;\n }\n try {\n log('save title %s \u2192 %s', String(current.id), next);\n const updated = await sendFn('edit-text', {\n id: current.id,\n field: 'title',\n value: next\n });\n if (updated && typeof updated === 'object') {\n current = /** @type {IssueDetail} */ (updated);\n edit_title = false;\n doRender();\n }\n } catch (err) {\n log('save title failed %s %o', String(current.id), err);\n current.title = prev;\n edit_title = false;\n doRender();\n showToast('Failed to save title', 'error');\n } finally {\n pending = false;\n }\n };\n const onTitleCancel = () => {\n edit_title = false;\n doRender();\n };\n // Assignee inline edit handlers\n const onAssigneeSpanClick = () => {\n edit_assignee = true;\n doRender();\n };\n /**\n * @param {KeyboardEvent} ev\n */\n const onAssigneeKeydown = (ev) => {\n if (ev.key === 'Enter') {\n ev.preventDefault();\n edit_assignee = true;\n doRender();\n } else if (ev.key === 'Escape') {\n ev.preventDefault();\n edit_assignee = false;\n doRender();\n }\n };\n const onAssigneeSave = async () => {\n if (!current || pending) {\n return;\n }\n const input = /** @type {HTMLInputElement|null} */ (\n mount_element.querySelector('#detail-root .prop.assignee input')\n );\n const prev = current?.assignee ?? '';\n const next = input?.value ?? '';\n if (next === prev) {\n edit_assignee = false;\n doRender();\n return;\n }\n pending = true;\n if (input) {\n input.disabled = true;\n }\n try {\n log('save assignee %s \u2192 %s', String(current.id), next);\n const updated = await sendFn('update-assignee', {\n id: current.id,\n assignee: next\n });\n if (updated && typeof updated === 'object') {\n current = /** @type {IssueDetail} */ (updated);\n edit_assignee = false;\n doRender();\n }\n } catch (err) {\n log('save assignee failed %s %o', String(current.id), err);\n // revert visually\n current.assignee = prev;\n edit_assignee = false;\n doRender();\n showToast('Failed to update assignee', 'error');\n } finally {\n pending = false;\n }\n };\n const onAssigneeCancel = () => {\n edit_assignee = false;\n doRender();\n };\n\n // Labels handlers\n /**\n * @param {Event} ev\n */\n const onLabelInput = (ev) => {\n const el = /** @type {HTMLInputElement} */ (ev.currentTarget);\n new_label_text = el.value || '';\n };\n /**\n * @param {KeyboardEvent} e\n */\n function onLabelKeydown(e) {\n if (e.key === 'Enter') {\n e.preventDefault();\n void onAddLabel();\n }\n }\n async function onAddLabel() {\n if (!current || pending) {\n return;\n }\n const text = new_label_text.trim();\n if (!text) {\n return;\n }\n pending = true;\n try {\n log('add label %s \u2192 %s', String(current.id), text);\n const updated = await sendFn('label-add', {\n id: current.id,\n label: text\n });\n if (updated && typeof updated === 'object') {\n current = /** @type {IssueDetail} */ (updated);\n new_label_text = '';\n doRender();\n }\n } catch (err) {\n log('add label failed %s %o', String(current.id), err);\n showToast('Failed to add label', 'error');\n } finally {\n pending = false;\n }\n }\n /**\n * @param {string} label\n */\n async function onRemoveLabel(label) {\n if (!current || pending) {\n return;\n }\n pending = true;\n try {\n log('remove label %s \u2192 %s', String(current?.id || ''), label);\n const updated = await sendFn('label-remove', {\n id: current.id,\n label\n });\n if (updated && typeof updated === 'object') {\n current = /** @type {IssueDetail} */ (updated);\n doRender();\n }\n } catch (err) {\n log('remove label failed %s %o', String(current?.id || ''), err);\n showToast('Failed to remove label', 'error');\n } finally {\n pending = false;\n }\n }\n /**\n * @param {Event} ev\n */\n const onStatusChange = async (ev) => {\n if (!current || pending) {\n doRender();\n return;\n }\n const sel = /** @type {HTMLSelectElement} */ (ev.currentTarget);\n const prev = current.status || 'open';\n const next = sel.value;\n if (next === prev) {\n return;\n }\n pending = true;\n current.status = next;\n doRender();\n try {\n log('update status %s \u2192 %s', String(current.id), next);\n const updated = await sendFn('update-status', {\n id: current.id,\n status: next\n });\n if (updated && typeof updated === 'object') {\n current = /** @type {IssueDetail} */ (updated);\n doRender();\n }\n } catch (err) {\n log('update status failed %s %o', String(current.id), err);\n current.status = prev;\n doRender();\n showToast('Failed to update status', 'error');\n } finally {\n pending = false;\n }\n };\n /**\n * @param {Event} ev\n */\n const onPriorityChange = async (ev) => {\n if (!current || pending) {\n doRender();\n return;\n }\n const sel = /** @type {HTMLSelectElement} */ (ev.currentTarget);\n const prev = typeof current.priority === 'number' ? current.priority : 2;\n const next = Number(sel.value);\n if (next === prev) {\n return;\n }\n pending = true;\n current.priority = next;\n doRender();\n try {\n log('update priority %s \u2192 %d', String(current.id), next);\n const updated = await sendFn('update-priority', {\n id: current.id,\n priority: next\n });\n if (updated && typeof updated === 'object') {\n current = /** @type {IssueDetail} */ (updated);\n doRender();\n }\n } catch (err) {\n log('update priority failed %s %o', String(current.id), err);\n current.priority = prev;\n doRender();\n showToast('Failed to update priority', 'error');\n } finally {\n pending = false;\n }\n };\n\n const onDescEdit = () => {\n edit_desc = true;\n doRender();\n };\n /**\n * @param {KeyboardEvent} ev\n */\n const onDescKeydown = (ev) => {\n if (ev.key === 'Escape') {\n edit_desc = false;\n doRender();\n } else if (ev.key === 'Enter' && ev.ctrlKey) {\n const btn = /** @type {HTMLButtonElement|null} */ (\n mount_element.querySelector('#detail-root .editable-actions button')\n );\n if (btn) {\n btn.click();\n }\n }\n };\n const onDescSave = async () => {\n if (!current || pending) {\n return;\n }\n const ta = /** @type {HTMLTextAreaElement|null} */ (\n mount_element.querySelector('#detail-root textarea')\n );\n const prev = current.description || '';\n const next = ta ? ta.value : '';\n if (next === prev) {\n edit_desc = false;\n doRender();\n return;\n }\n pending = true;\n if (ta) {\n ta.disabled = true;\n }\n try {\n log('save description %s', String(current?.id || ''));\n const updated = await sendFn('edit-text', {\n id: current.id,\n field: 'description',\n value: next\n });\n if (updated && typeof updated === 'object') {\n current = /** @type {IssueDetail} */ (updated);\n edit_desc = false;\n doRender();\n }\n } catch (err) {\n log('save description failed %s %o', String(current?.id || ''), err);\n current.description = prev;\n edit_desc = false;\n doRender();\n showToast('Failed to save description', 'error');\n } finally {\n pending = false;\n }\n };\n const onDescCancel = () => {\n edit_desc = false;\n doRender();\n };\n\n // Design inline edit handlers (same UX as Description)\n const onDesignEdit = () => {\n edit_design = true;\n doRender();\n try {\n const ta = /** @type {HTMLTextAreaElement|null} */ (\n mount_element.querySelector('#detail-root .design textarea')\n );\n if (ta) {\n ta.focus();\n }\n } catch (err) {\n log('focus design textarea failed %o', err);\n }\n };\n /**\n * @param {KeyboardEvent} ev\n */\n const onDesignKeydown = (ev) => {\n if (ev.key === 'Escape') {\n edit_design = false;\n doRender();\n } else if (ev.key === 'Enter' && (ev.ctrlKey || ev.metaKey)) {\n const btn = /** @type {HTMLButtonElement|null} */ (\n mount_element.querySelector(\n '#detail-root .design .editable-actions button'\n )\n );\n if (btn) {\n btn.click();\n }\n }\n };\n const onDesignSave = async () => {\n if (!current || pending) {\n return;\n }\n const ta = /** @type {HTMLTextAreaElement|null} */ (\n mount_element.querySelector('#detail-root .design textarea')\n );\n const prev = current.design || '';\n const next = ta ? ta.value : '';\n if (next === prev) {\n edit_design = false;\n doRender();\n return;\n }\n pending = true;\n if (ta) {\n ta.disabled = true;\n }\n try {\n log('save design %s', String(current?.id || ''));\n const updated = await sendFn('edit-text', {\n id: current.id,\n field: 'design',\n value: next\n });\n if (updated && typeof updated === 'object') {\n current = /** @type {IssueDetail} */ (updated);\n edit_design = false;\n doRender();\n }\n } catch (err) {\n log('save design failed %s %o', String(current?.id || ''), err);\n current.design = prev;\n edit_design = false;\n doRender();\n showToast('Failed to save design', 'error');\n } finally {\n pending = false;\n }\n };\n const onDesignCancel = () => {\n edit_design = false;\n doRender();\n };\n\n // Notes inline edit handlers\n const onNotesEdit = () => {\n edit_notes = true;\n doRender();\n };\n /**\n * @param {KeyboardEvent} ev\n */\n const onNotesKeydown = (ev) => {\n if (ev.key === 'Escape') {\n edit_notes = false;\n doRender();\n } else if (ev.key === 'Enter' && (ev.ctrlKey || ev.metaKey)) {\n const btn = /** @type {HTMLButtonElement|null} */ (\n mount_element.querySelector(\n '#detail-root .notes .editable-actions button'\n )\n );\n if (btn) {\n btn.click();\n }\n }\n };\n const onNotesSave = async () => {\n if (!current || pending) {\n return;\n }\n const ta = /** @type {HTMLTextAreaElement|null} */ (\n mount_element.querySelector('#detail-root .notes textarea')\n );\n const prev = current.notes || '';\n const next = ta ? ta.value : '';\n if (next === prev) {\n edit_notes = false;\n doRender();\n return;\n }\n pending = true;\n if (ta) {\n ta.disabled = true;\n }\n try {\n log('save notes %s', String(current?.id || ''));\n const updated = await sendFn('edit-text', {\n id: current.id,\n field: 'notes',\n value: next\n });\n if (updated && typeof updated === 'object') {\n current = /** @type {IssueDetail} */ (updated);\n edit_notes = false;\n doRender();\n }\n } catch (err) {\n log('save notes failed %s %o', String(current?.id || ''), err);\n current.notes = prev;\n edit_notes = false;\n doRender();\n showToast('Failed to save notes', 'error');\n } finally {\n pending = false;\n }\n };\n const onNotesCancel = () => {\n edit_notes = false;\n doRender();\n };\n\n const onAcceptEdit = () => {\n edit_accept = true;\n doRender();\n };\n /**\n * @param {KeyboardEvent} ev\n */\n const onAcceptKeydown = (ev) => {\n if (ev.key === 'Escape') {\n edit_accept = false;\n doRender();\n } else if (ev.key === 'Enter' && (ev.ctrlKey || ev.metaKey)) {\n const btn = /** @type {HTMLButtonElement|null} */ (\n mount_element.querySelector(\n '#detail-root .acceptance .editable-actions button'\n )\n );\n if (btn) {\n btn.click();\n }\n }\n };\n const onAcceptSave = async () => {\n if (!current || pending) {\n return;\n }\n const ta = /** @type {HTMLTextAreaElement|null} */ (\n mount_element.querySelector('#detail-root .acceptance textarea')\n );\n const prev = current.acceptance || '';\n const next = ta ? ta.value : '';\n if (next === prev) {\n edit_accept = false;\n doRender();\n return;\n }\n pending = true;\n if (ta) {\n ta.disabled = true;\n }\n try {\n log('save acceptance %s', String(current?.id || ''));\n const updated = await sendFn('edit-text', {\n id: current.id,\n field: 'acceptance',\n value: next\n });\n if (updated && typeof updated === 'object') {\n current = /** @type {IssueDetail} */ (updated);\n edit_accept = false;\n doRender();\n }\n } catch (err) {\n log('save acceptance failed %s %o', String(current?.id || ''), err);\n current.acceptance = prev;\n edit_accept = false;\n doRender();\n showToast('Failed to save acceptance', 'error');\n } finally {\n pending = false;\n }\n };\n const onAcceptCancel = () => {\n edit_accept = false;\n doRender();\n };\n\n // Comment input handlers\n /**\n * @param {Event} ev\n */\n const onCommentInput = (ev) => {\n const el = /** @type {HTMLTextAreaElement} */ (ev.currentTarget);\n const prev_has_text = comment_text.trim().length > 0;\n comment_text = el.value || '';\n const has_text = comment_text.trim().length > 0;\n // Re-render when the \"has content\" state changes to update button disabled state\n if (prev_has_text !== has_text) {\n doRender();\n }\n };\n\n const onCommentSubmit = async () => {\n if (!current || comment_pending || !comment_text.trim()) {\n return;\n }\n comment_pending = true;\n doRender();\n try {\n log('add comment to %s', String(current.id));\n const result = await sendFn('add-comment', {\n id: current.id,\n text: comment_text.trim()\n });\n if (Array.isArray(result)) {\n // Update comments in current issue\n /** @type {any} */ (current).comments = result;\n comment_text = '';\n doRender();\n }\n } catch (err) {\n log('add comment failed %s %o', String(current.id), err);\n showToast('Failed to add comment', 'error');\n } finally {\n comment_pending = false;\n doRender();\n }\n };\n\n /**\n * @param {KeyboardEvent} ev\n */\n const onCommentKeydown = (ev) => {\n if (ev.key === 'Enter' && (ev.ctrlKey || ev.metaKey)) {\n ev.preventDefault();\n onCommentSubmit();\n }\n };\n\n /**\n * @param {'Dependencies'|'Dependents'} title\n * @param {Dependency[]} items\n */\n function depsSection(title, items) {\n const test_id =\n title === 'Dependencies' ? 'add-dependency' : 'add-dependent';\n return html`\n <div class=\"props-card\">\n <div>\n <div class=\"props-card__title\">${title}</div>\n </div>\n <ul>\n ${!items || items.length === 0\n ? null\n : items.map((dep) => {\n const did = dep.id;\n const href = issueHref(did);\n return html`<li\n data-href=${href}\n @click=${() => navigateFn(href)}\n >\n ${createTypeBadge(dep.issue_type || '')}\n <span class=\"text-truncate\">${dep.title || ''}</span>\n <button\n aria-label=${`Remove dependency ${did}`}\n @click=${makeDepRemoveClick(did, title)}\n >\n \u00D7\n </button>\n </li>`;\n })}\n </ul>\n <div class=\"props-card__footer\">\n <input type=\"text\" placeholder=\"Issue ID\" data-testid=${test_id} />\n <button @click=${makeDepAddClick(items, title)}>Add</button>\n </div>\n </div>\n `;\n }\n\n /**\n * @param {IssueDetail} issue\n */\n function detailTemplate(issue) {\n const title_zone = edit_title\n ? html`<div class=\"detail-title\">\n <h2>\n <input\n type=\"text\"\n aria-label=\"Edit title\"\n .value=${issue.title || ''}\n @keydown=${onTitleInputKeydown}\n />\n <button @click=${onTitleSave}>Save</button>\n <button @click=${onTitleCancel}>Cancel</button>\n </h2>\n </div>`\n : html`<div class=\"detail-title\">\n <h2>\n <span\n class=\"editable\"\n tabindex=\"0\"\n role=\"button\"\n aria-label=\"Edit title\"\n @click=${onTitleSpanClick}\n @keydown=${onTitleKeydown}\n >${issue.title || ''}</span\n >\n </h2>\n </div>`;\n\n const status_select = html`<select\n class=${`badge-select badge--status is-${issue.status || 'open'}`}\n @change=${onStatusChange}\n .value=${issue.status || 'open'}\n ?disabled=${pending}\n >\n ${(() => {\n const cur = String(issue.status || 'open');\n return ['open', 'in_progress', 'closed'].map(\n (s) =>\n html`<option value=${s} ?selected=${cur === s}>\n ${statusLabel(s)}\n </option>`\n );\n })()}\n </select>`;\n\n const priority_select = html`<select\n class=${`badge-select badge--priority is-p${String(\n typeof issue.priority === 'number' ? issue.priority : 2\n )}`}\n @change=${onPriorityChange}\n .value=${String(typeof issue.priority === 'number' ? issue.priority : 2)}\n ?disabled=${pending}\n >\n ${(() => {\n const cur = String(\n typeof issue.priority === 'number' ? issue.priority : 2\n );\n return priority_levels.map(\n (p, i) =>\n html`<option value=${String(i)} ?selected=${cur === String(i)}>\n ${emojiForPriority(i)} ${p}\n </option>`\n );\n })()}\n </select>`;\n\n const desc_block = edit_desc\n ? html`<div class=\"description\">\n <textarea\n @keydown=${onDescKeydown}\n .value=${issue.description || ''}\n rows=\"8\"\n style=\"width:100%\"\n ></textarea>\n <div class=\"editable-actions\">\n <button @click=${onDescSave}>Save</button>\n <button @click=${onDescCancel}>Cancel</button>\n </div>\n </div>`\n : html`<div\n class=\"md editable\"\n tabindex=\"0\"\n role=\"button\"\n aria-label=\"Edit description\"\n @click=${onDescEdit}\n @keydown=${onDescEditableKeydown}\n >\n ${(() => {\n const text = issue.description || '';\n if (text.trim() === '') {\n return html`<div class=\"muted\">Description</div>`;\n }\n return renderMarkdown(text);\n })()}\n </div>`;\n\n // Normalize acceptance text: prefer issue.acceptance, fallback to acceptance_criteria from bd\n const acceptance_text = (() => {\n /** @type {any} */\n const any_issue = issue;\n const raw = String(\n issue.acceptance || any_issue.acceptance_criteria || ''\n );\n return raw;\n })();\n\n const accept_block = edit_accept\n ? html`<div class=\"acceptance\">\n ${acceptance_text.trim().length > 0\n ? html`<div class=\"props-card__title\">Acceptance Criteria</div>`\n : ''}\n <textarea\n @keydown=${onAcceptKeydown}\n .value=${acceptance_text}\n rows=\"6\"\n style=\"width:100%\"\n ></textarea>\n <div class=\"editable-actions\">\n <button @click=${onAcceptSave}>Save</button>\n <button @click=${onAcceptCancel}>Cancel</button>\n </div>\n </div>`\n : html`<div class=\"acceptance\">\n ${(() => {\n const text = acceptance_text;\n const has = text.trim().length > 0;\n return html`${has\n ? html`<div class=\"props-card__title\">Acceptance Criteria</div>`\n : ''}\n <div\n class=\"md editable\"\n tabindex=\"0\"\n role=\"button\"\n aria-label=\"Edit acceptance criteria\"\n @click=${onAcceptEdit}\n @keydown=${onAcceptEditableKeydown}\n >\n ${has\n ? renderMarkdown(text)\n : html`<div class=\"muted\">Add acceptance criteria\u2026</div>`}\n </div>`;\n })()}\n </div>`;\n\n // Notes: editable in-place similar to Description\n const notes_text = String(issue.notes || '');\n const notes_block = edit_notes\n ? html`<div class=\"notes\">\n ${notes_text.trim().length > 0\n ? html`<div class=\"props-card__title\">Notes</div>`\n : ''}\n <textarea\n @keydown=${onNotesKeydown}\n .value=${notes_text}\n rows=\"6\"\n style=\"width:100%\"\n ></textarea>\n <div class=\"editable-actions\">\n <button @click=${onNotesSave}>Save</button>\n <button @click=${onNotesCancel}>Cancel</button>\n </div>\n </div>`\n : html`<div class=\"notes\">\n ${(() => {\n const text = notes_text;\n const has = text.trim().length > 0;\n return html`${has\n ? html`<div class=\"props-card__title\">Notes</div>`\n : ''}\n <div\n class=\"md editable\"\n tabindex=\"0\"\n role=\"button\"\n aria-label=\"Edit notes\"\n @click=${onNotesEdit}\n @keydown=${onNotesEditableKeydown}\n >\n ${has\n ? renderMarkdown(text)\n : html`<div class=\"muted\">Add notes\u2026</div>`}\n </div>`;\n })()}\n </div>`;\n\n // Labels section\n const labels = Array.isArray(issue.labels) ? issue.labels : [];\n const labels_block = html`<div class=\"props-card labels\">\n <div>\n <div class=\"props-card__title\">Labels</div>\n </div>\n <ul>\n ${labels.map(\n (l) =>\n html`<li>\n <span class=\"badge\" title=${l}\n >${l}\n <button\n class=\"icon-button\"\n title=\"Remove label\"\n aria-label=${'Remove label ' + l}\n @click=${() => onRemoveLabel(l)}\n style=\"margin-left:6px\"\n >\n \u00D7\n </button></span\n >\n </li>`\n )}\n </ul>\n <div class=\"props-card__footer\">\n <input\n type=\"text\"\n placeholder=\"Label\"\n size=\"12\"\n .value=${new_label_text}\n @input=${onLabelInput}\n @keydown=${onLabelKeydown}\n />\n <button @click=${onAddLabel}>Add</button>\n </div>\n </div>`;\n\n // Design section block\n const design_text = String(issue.design || '');\n const design_block = edit_design\n ? html`<div class=\"design\">\n ${design_text.trim().length > 0\n ? html`<div class=\"props-card__title\">Design</div>`\n : ''}\n <textarea\n @keydown=${onDesignKeydown}\n .value=${design_text}\n rows=\"6\"\n style=\"width:100%\"\n ></textarea>\n <div class=\"editable-actions\">\n <button @click=${onDesignSave}>Save</button>\n <button @click=${onDesignCancel}>Cancel</button>\n </div>\n </div>`\n : html`<div class=\"design\">\n ${(() => {\n const text = design_text;\n const has = text.trim().length > 0;\n return html`${has\n ? html`<div class=\"props-card__title\">Design</div>`\n : ''}\n <div\n class=\"md editable\"\n tabindex=\"0\"\n role=\"button\"\n aria-label=\"Edit design\"\n @click=${onDesignEdit}\n @keydown=${onDesignEditableKeydown}\n >\n ${has\n ? renderMarkdown(text)\n : html`<div class=\"muted\">Add design\u2026</div>`}\n </div>`;\n })()}\n </div>`;\n\n // Comments section\n const comments = Array.isArray(/** @type {any} */ (issue).comments)\n ? /** @type {Comment[]} */ (/** @type {any} */ (issue).comments)\n : [];\n const comments_block = html`<div class=\"comments\">\n <div class=\"props-card__title\">Comments</div>\n ${comments.length === 0\n ? html`<div class=\"muted\">No comments yet</div>`\n : comments.map(\n (c) => html`\n <div class=\"comment-item\">\n <div class=\"comment-header\">\n <span class=\"comment-author\">${c.author || 'Unknown'}</span>\n <span class=\"comment-date\"\n >${formatCommentDate(c.created_at)}</span\n >\n </div>\n <div class=\"comment-text\">${c.text}</div>\n </div>\n `\n )}\n <div class=\"comment-input\">\n <textarea\n placeholder=\"Add a comment... (Ctrl+Enter to submit)\"\n rows=\"3\"\n .value=${comment_text}\n @input=${onCommentInput}\n @keydown=${onCommentKeydown}\n ?disabled=${comment_pending}\n ></textarea>\n <button\n @click=${onCommentSubmit}\n ?disabled=${comment_pending || !comment_text.trim()}\n >\n ${comment_pending ? 'Adding...' : 'Add Comment'}\n </button>\n </div>\n </div>`;\n\n return html`\n <div class=\"panel__body\" id=\"detail-root\">\n <div class=\"detail-layout\">\n <div class=\"detail-main\">\n ${title_zone} ${desc_block} ${design_block} ${notes_block}\n ${accept_block} ${comments_block}\n </div>\n <div class=\"detail-side\">\n <div class=\"props-card\">\n <div class=\"props-card__header\">\n <div class=\"props-card__title\">Properties</div>\n <button class=\"delete-issue-btn\" title=\"Delete issue\" aria-label=\"Delete issue\" @click=${onDeleteClick}>\n <svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\">\n <polyline points=\"3 6 5 6 21 6\"></polyline>\n <path d=\"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2\"></path>\n <line x1=\"10\" y1=\"11\" x2=\"10\" y2=\"17\"></line>\n <line x1=\"14\" y1=\"11\" x2=\"14\" y2=\"17\"></line>\n </svg>\n <span class=\"tooltip\">Delete issue</span>\n </button>\n </div>\n <div class=\"prop\">\n <div class=\"label\">Type</div>\n <div class=\"value\">\n ${createTypeBadge(/** @type {any} */ (issue).issue_type)}\n </div>\n </div>\n <div class=\"prop\">\n <div class=\"label\">Status</div>\n <div class=\"value\">${status_select}</div>\n </div>\n <div class=\"prop\">\n <div class=\"label\">Priority</div>\n <div class=\"value\">${priority_select}</div>\n </div>\n <div class=\"prop assignee\">\n <div class=\"label\">Assignee</div>\n <div class=\"value\">\n ${\n edit_assignee\n ? html`<input\n type=\"text\"\n aria-label=\"Edit assignee\"\n .value=${\n /** @type {any} */ (issue).assignee || ''\n }\n size=${Math.min(\n 40,\n Math.max(12, (issue.assignee || '').length + 3)\n )}\n @keydown=${\n /** @param {KeyboardEvent} e */ (e) => {\n if (e.key === 'Escape') {\n e.preventDefault();\n onAssigneeCancel();\n } else if (e.key === 'Enter') {\n e.preventDefault();\n onAssigneeSave();\n }\n }\n }\n />\n <button\n class=\"btn\"\n style=\"margin-left:6px\"\n @click=${onAssigneeSave}\n >\n Save\n </button>\n <button\n class=\"btn\"\n style=\"margin-left:6px\"\n @click=${onAssigneeCancel}\n >\n Cancel\n </button>`\n : html`${(() => {\n const raw = issue.assignee || '';\n const has = raw.trim().length > 0;\n const text = has ? raw : 'Unassigned';\n const cls = has ? 'editable' : 'editable muted';\n return html`<span\n class=${cls}\n tabindex=\"0\"\n role=\"button\"\n aria-label=\"Edit assignee\"\n @click=${onAssigneeSpanClick}\n @keydown=${onAssigneeKeydown}\n >${text}</span\n >`;\n })()}`\n }\n </div>\n </div>\n </div>\n ${labels_block}\n ${depsSection('Dependencies', issue.dependencies || [])}\n ${depsSection('Dependents', issue.dependents || [])}\n </div>\n </div>\n </div>\n </div>\n `;\n }\n\n function doRender() {\n if (!current) {\n renderPlaceholder(current_id ? 'Loading\u2026' : 'No issue selected');\n return;\n }\n render(detailTemplate(current), mount_element);\n }\n\n /**\n * Create a click handler for the remove button of a dependency row.\n *\n * @param {string} did\n * @param {'Dependencies'|'Dependents'} title\n * @returns {(ev: Event) => Promise<void>}\n */\n function makeDepRemoveClick(did, title) {\n return async (ev) => {\n ev.stopPropagation();\n if (!current || pending) {\n return;\n }\n pending = true;\n try {\n if (title === 'Dependencies') {\n const updated = await sendFn('dep-remove', {\n a: current.id,\n b: did,\n view_id: current.id\n });\n if (updated && typeof updated === 'object') {\n current = /** @type {IssueDetail} */ (updated);\n doRender();\n }\n } else {\n const updated = await sendFn('dep-remove', {\n a: did,\n b: current.id,\n view_id: current.id\n });\n if (updated && typeof updated === 'object') {\n current = /** @type {IssueDetail} */ (updated);\n doRender();\n }\n }\n } catch (err) {\n log('dep-remove failed %o', err);\n } finally {\n pending = false;\n }\n };\n }\n\n /**\n * Create a click handler for the Add button in a dependency section.\n *\n * @param {Dependency[]} items\n * @param {'Dependencies'|'Dependents'} title\n * @returns {(ev: Event) => Promise<void>}\n */\n function makeDepAddClick(items, title) {\n return async (ev) => {\n if (!current || pending) {\n return;\n }\n const btn = /** @type {HTMLButtonElement} */ (ev.currentTarget);\n const input = /** @type {HTMLInputElement|null} */ (\n btn.previousElementSibling\n );\n const target = input ? input.value.trim() : '';\n if (!target || target === current.id) {\n showToast('Enter a different issue id');\n return;\n }\n const set = new Set((items || []).map((d) => d.id));\n if (set.has(target)) {\n showToast('Link already exists');\n return;\n }\n pending = true;\n if (btn) {\n btn.disabled = true;\n }\n if (input) {\n input.disabled = true;\n }\n try {\n if (title === 'Dependencies') {\n const updated = await sendFn('dep-add', {\n a: current.id,\n b: target,\n view_id: current.id\n });\n if (updated && typeof updated === 'object') {\n current = /** @type {IssueDetail} */ (updated);\n doRender();\n }\n } else {\n const updated = await sendFn('dep-add', {\n a: target,\n b: current.id,\n view_id: current.id\n });\n if (updated && typeof updated === 'object') {\n current = /** @type {IssueDetail} */ (updated);\n doRender();\n }\n }\n } catch (err) {\n log('dep-add failed %o', err);\n showToast('Failed to add dependency', 'error');\n } finally {\n pending = false;\n }\n };\n }\n /**\n * @param {KeyboardEvent} ev\n */\n function onTitleInputKeydown(ev) {\n if (ev.key === 'Escape') {\n edit_title = false;\n doRender();\n } else if (ev.key === 'Enter') {\n ev.preventDefault();\n onTitleSave();\n }\n }\n\n /**\n * @param {KeyboardEvent} ev\n */\n function onDescEditableKeydown(ev) {\n if (ev.key === 'Enter') {\n onDescEdit();\n }\n }\n\n /**\n * @param {KeyboardEvent} ev\n */\n function onAcceptEditableKeydown(ev) {\n if (ev.key === 'Enter') {\n onAcceptEdit();\n }\n }\n\n /**\n * @param {KeyboardEvent} ev\n */\n function onNotesEditableKeydown(ev) {\n if (ev.key === 'Enter') {\n onNotesEdit();\n }\n }\n\n /**\n * @param {KeyboardEvent} ev\n */\n function onDesignEditableKeydown(ev) {\n if (ev.key === 'Enter') {\n onDesignEdit();\n }\n }\n\n return {\n async load(id) {\n if (!id) {\n renderPlaceholder('No issue selected');\n return;\n }\n current_id = String(id);\n // Try from store first; show placeholder while waiting for snapshot\n current = null;\n refreshFromStore();\n if (!current) {\n renderPlaceholder('Loading\u2026');\n }\n // Render from current (if available) or keep placeholder until push arrives\n pending = false;\n comment_text = '';\n comment_pending = false;\n doRender();\n\n // Fetch comments if not already present\n if (current && !(/** @type {any} */ (current).comments)) {\n try {\n const comments = await sendFn('get-comments', { id: current_id });\n if (Array.isArray(comments) && current && current_id === id) {\n /** @type {any} */ (current).comments = comments;\n doRender();\n }\n } catch (err) {\n log('fetch comments failed %s %o', id, err);\n }\n }\n },\n clear() {\n renderPlaceholder('Select an issue to view details');\n },\n destroy() {\n mount_element.replaceChildren();\n if (delete_dialog && delete_dialog.parentNode) {\n delete_dialog.parentNode.removeChild(delete_dialog);\n delete_dialog = null;\n }\n }\n };\n}\n", "import { html } from 'lit-html';\nimport { createIssueIdRenderer } from '../utils/issue-id-renderer.js';\nimport { emojiForPriority } from '../utils/priority-badge.js';\nimport { priority_levels } from '../utils/priority.js';\nimport { statusLabel } from '../utils/status.js';\nimport { createTypeBadge } from '../utils/type-badge.js';\n\n/**\n * @typedef {{ id: string, title?: string, status?: string, priority?: number, issue_type?: string, assignee?: string, dependency_count?: number, dependent_count?: number }} IssueRowData\n */\n\n/**\n * Create a reusable issue row renderer used by list and epics views.\n * Handles inline editing for title/assignee and selects for status/priority.\n *\n * @param {{\n * navigate: (id: string) => void,\n * onUpdate: (id: string, patch: { title?: string, assignee?: string, status?: 'open'|'in_progress'|'closed', priority?: number }) => Promise<void>,\n * requestRender: () => void,\n * getSelectedId?: () => string | null,\n * row_class?: string\n * }} options\n * @returns {(it: IssueRowData) => import('lit-html').TemplateResult<1>}\n */\nexport function createIssueRowRenderer(options) {\n const navigate = options.navigate;\n const on_update = options.onUpdate;\n const request_render = options.requestRender;\n const get_selected_id = options.getSelectedId || (() => null);\n const row_class = options.row_class || 'issue-row';\n\n /** @type {Set<string>} */\n const editing = new Set();\n\n /**\n * @param {string} id\n * @param {'title'|'assignee'} key\n * @param {string} value\n * @param {string} [placeholder]\n */\n function editableText(id, key, value, placeholder = '') {\n const k = `${id}:${key}`;\n const is_edit = editing.has(k);\n if (is_edit) {\n return html`<span>\n <input\n type=\"text\"\n .value=${value}\n class=\"inline-edit\"\n @keydown=${\n /** @param {KeyboardEvent} e */ async (e) => {\n if (e.key === 'Escape') {\n editing.delete(k);\n request_render();\n } else if (e.key === 'Enter') {\n const el = /** @type {HTMLInputElement} */ (e.currentTarget);\n const next = el.value || '';\n if (next !== value) {\n await on_update(id, { [key]: next });\n }\n editing.delete(k);\n request_render();\n }\n }\n }\n @blur=${\n /** @param {Event} ev */ async (ev) => {\n const el = /** @type {HTMLInputElement} */ (ev.currentTarget);\n const next = el.value || '';\n if (next !== value) {\n await on_update(id, { [key]: next });\n }\n editing.delete(k);\n request_render();\n }\n }\n autofocus\n />\n </span>`;\n }\n return html`<span\n class=\"editable text-truncate ${value ? '' : 'muted'}\"\n tabindex=\"0\"\n role=\"button\"\n @click=${\n /** @param {MouseEvent} e */ (e) => {\n e.stopPropagation();\n e.preventDefault();\n editing.add(k);\n request_render();\n }\n }\n @keydown=${\n /** @param {KeyboardEvent} e */ (e) => {\n if (e.key === 'Enter') {\n e.preventDefault();\n e.stopPropagation();\n editing.add(k);\n request_render();\n }\n }\n }\n >${value || placeholder}</span\n >`;\n }\n\n /**\n * @param {string} id\n * @param {'priority'|'status'} key\n * @returns {(ev: Event) => Promise<void>}\n */\n function makeSelectChange(id, key) {\n return async (ev) => {\n const sel = /** @type {HTMLSelectElement} */ (ev.currentTarget);\n const val = sel.value || '';\n /** @type {{ [k:string]: any }} */\n const patch = {};\n patch[key] = key === 'priority' ? Number(val) : val;\n await on_update(id, patch);\n };\n }\n\n /**\n * @param {string} id\n * @returns {(ev: Event) => void}\n */\n function makeRowClick(id) {\n return (ev) => {\n const el = /** @type {HTMLElement|null} */ (ev.target);\n if (el && (el.tagName === 'INPUT' || el.tagName === 'SELECT')) {\n return;\n }\n navigate(id);\n };\n }\n\n /**\n * @param {IssueRowData} it\n */\n function rowTemplate(it) {\n const cur_status = String(it.status || 'open');\n const cur_prio = String(it.priority ?? 2);\n const is_selected = get_selected_id() === it.id;\n return html`<tr\n role=\"row\"\n class=\"${row_class} ${is_selected ? 'selected' : ''}\"\n data-issue-id=${it.id}\n @click=${makeRowClick(it.id)}\n >\n <td role=\"gridcell\" class=\"mono\">${createIssueIdRenderer(it.id)}</td>\n <td role=\"gridcell\">${createTypeBadge(it.issue_type)}</td>\n <td role=\"gridcell\">${editableText(it.id, 'title', it.title || '')}</td>\n <td role=\"gridcell\">\n <select\n class=\"badge-select badge--status is-${cur_status}\"\n .value=${cur_status}\n @change=${makeSelectChange(it.id, 'status')}\n >\n ${['open', 'in_progress', 'closed'].map(\n (s) =>\n html`<option value=${s} ?selected=${cur_status === s}>\n ${statusLabel(s)}\n </option>`\n )}\n </select>\n </td>\n <td role=\"gridcell\">\n ${editableText(it.id, 'assignee', it.assignee || '', 'Unassigned')}\n </td>\n <td role=\"gridcell\">\n <select\n class=\"badge-select badge--priority ${'is-p' + cur_prio}\"\n .value=${cur_prio}\n @change=${makeSelectChange(it.id, 'priority')}\n >\n ${priority_levels.map(\n (p, i) =>\n html`<option\n value=${String(i)}\n ?selected=${cur_prio === String(i)}\n >\n ${emojiForPriority(i)} ${p}\n </option>`\n )}\n </select>\n </td>\n <td role=\"gridcell\" class=\"deps-col\">\n ${(it.dependency_count || 0) > 0 || (it.dependent_count || 0) > 0\n ? html`<span class=\"deps-indicator\"\n >${(it.dependency_count || 0) > 0\n ? html`<span\n class=\"dep-count\"\n title=\"${it.dependency_count} ${(it.dependency_count ||\n 0) === 1\n ? 'dependency'\n : 'dependencies'}\"\n >\u2192${it.dependency_count}</span\n >`\n : ''}${(it.dependent_count || 0) > 0\n ? html`<span\n class=\"dependent-count\"\n title=\"${it.dependent_count} ${(it.dependent_count || 0) ===\n 1\n ? 'dependent'\n : 'dependents'}\"\n >\u2190${it.dependent_count}</span\n >`\n : ''}</span\n >`\n : ''}\n </td>\n </tr>`;\n }\n\n return rowTemplate;\n}\n", "import { html, render } from 'lit-html';\nimport { createListSelectors } from '../data/list-selectors.js';\nimport { createIssueIdRenderer } from '../utils/issue-id-renderer.js';\nimport { createIssueRowRenderer } from './issue-row.js';\n\n/**\n * @typedef {{ id: string, title?: string, status?: string, priority?: number, issue_type?: string, assignee?: string, created_at?: number, updated_at?: number }} IssueLite\n */\n\n/**\n * Epics view (push-only):\n * - Derives epic groups from the local issues store (no RPC reads).\n * - Subscribes to `tab:epics` for top-level membership.\n * - On expand, subscribes to `detail:{id}` (issue-detail) for the epic.\n * - Renders children from the epic detail's `dependents` list.\n * - Provides inline edits via mutations; UI re-renders on push.\n *\n * @param {HTMLElement} mount_element\n * @param {{ updateIssue: (input: any) => Promise<any> }} data\n * @param {(id: string) => void} goto_issue - Navigate to issue detail.\n * @param {{ subscribeList: (client_id: string, spec: { type: string, params?: Record<string, string|number|boolean> }) => Promise<() => Promise<void>>, selectors: { getIds: (client_id: string) => string[], count?: (client_id: string) => number } }} [subscriptions]\n * @param {{ snapshotFor?: (client_id: string) => any[], subscribe?: (fn: () => void) => () => void }} [issue_stores]\n */\nexport function createEpicsView(\n mount_element,\n data,\n goto_issue,\n subscriptions = undefined,\n issue_stores = undefined\n) {\n /** @type {any[]} */\n let groups = [];\n /** @type {Set<string>} */\n const expanded = new Set();\n /** @type {Set<string>} */\n const loading = new Set();\n /** @type {Map<string, () => Promise<void>>} */\n const epic_unsubs = new Map();\n // Centralized selection helpers\n const selectors = issue_stores ? createListSelectors(issue_stores) : null;\n // Live re-render on pushes: recompute groups when stores change\n if (selectors) {\n selectors.subscribe(() => {\n const had_none = groups.length === 0;\n groups = buildGroupsFromSnapshot();\n doRender();\n // Auto-expand first epic when transitioning from empty to non-empty\n if (had_none && groups.length > 0) {\n const first_id = String(groups[0].epic?.id || '');\n if (first_id && !expanded.has(first_id)) {\n void toggle(first_id);\n }\n }\n });\n }\n\n // Shared row renderer used for children rows\n const renderRow = createIssueRowRenderer({\n navigate: (id) => goto_issue(id),\n onUpdate: updateInline,\n requestRender: doRender,\n getSelectedId: () => null,\n row_class: 'epic-row'\n });\n\n function doRender() {\n render(template(), mount_element);\n }\n\n function template() {\n if (!groups.length) {\n return html`<div class=\"panel__header muted\">No epics found.</div>`;\n }\n return html`${groups.map((g) => groupTemplate(g))}`;\n }\n\n /**\n * @param {any} g\n */\n function groupTemplate(g) {\n const epic = g.epic || {};\n const id = String(epic.id || '');\n const is_open = expanded.has(id);\n // Compose children via selectors\n const list = selectors ? selectors.selectEpicChildren(id) : [];\n const is_loading = loading.has(id);\n return html`\n <div class=\"epic-group\" data-epic-id=${id}>\n <div\n class=\"epic-header\"\n @click=${() => toggle(id)}\n role=\"button\"\n tabindex=\"0\"\n aria-expanded=${is_open}\n >\n ${createIssueIdRenderer(id, { class_name: 'mono' })}\n <span class=\"text-truncate\" style=\"margin-left:8px\"\n >${epic.title || '(no title)'}</span\n >\n <span\n class=\"epic-progress\"\n style=\"margin-left:auto; display:flex; align-items:center; gap:8px;\"\n >\n <progress\n value=${Number(g.closed_children || 0)}\n max=${Math.max(1, Number(g.total_children || 0))}\n ></progress>\n <span class=\"muted mono\"\n >${g.closed_children}/${g.total_children}</span\n >\n </span>\n </div>\n ${is_open\n ? html`<div class=\"epic-children\">\n ${is_loading\n ? html`<div class=\"muted\">Loading\u2026</div>`\n : list.length === 0\n ? html`<div class=\"muted\">No issues found</div>`\n : html`<table class=\"table\">\n <colgroup>\n <col style=\"width: 100px\" />\n <col style=\"width: 120px\" />\n <col />\n <col style=\"width: 120px\" />\n <col style=\"width: 160px\" />\n <col style=\"width: 130px\" />\n </colgroup>\n <thead>\n <tr>\n <th>ID</th>\n <th>Type</th>\n <th>Title</th>\n <th>Status</th>\n <th>Assignee</th>\n <th>Priority</th>\n </tr>\n </thead>\n <tbody>\n ${list.map((it) => renderRow(it))}\n </tbody>\n </table>`}\n </div>`\n : null}\n </div>\n `;\n }\n\n /**\n * @param {string} id\n * @param {{ [k: string]: any }} patch\n */\n async function updateInline(id, patch) {\n try {\n await data.updateIssue({ id, ...patch });\n // Re-render; view will update on subsequent push\n doRender();\n } catch {\n // swallow; UI remains\n }\n }\n\n /**\n * @param {string} epic_id\n */\n async function toggle(epic_id) {\n if (!expanded.has(epic_id)) {\n expanded.add(epic_id);\n loading.add(epic_id);\n doRender();\n // Subscribe to epic detail; children are rendered from `dependents`\n if (subscriptions && typeof subscriptions.subscribeList === 'function') {\n try {\n // Register store first to avoid dropping the initial snapshot\n try {\n if (issue_stores && /** @type {any} */ (issue_stores).register) {\n /** @type {any} */ (issue_stores).register(`detail:${epic_id}`, {\n type: 'issue-detail',\n params: { id: epic_id }\n });\n }\n } catch {\n // ignore\n }\n const u = await subscriptions.subscribeList(`detail:${epic_id}`, {\n type: 'issue-detail',\n params: { id: epic_id }\n });\n epic_unsubs.set(epic_id, u);\n } catch {\n // ignore subscription failures\n }\n }\n // Mark as not loading after subscribe attempt; membership will stream in\n loading.delete(epic_id);\n } else {\n expanded.delete(epic_id);\n // Unsubscribe when collapsing\n if (epic_unsubs.has(epic_id)) {\n try {\n const u = epic_unsubs.get(epic_id);\n if (u) {\n await u();\n }\n } catch {\n // ignore\n }\n epic_unsubs.delete(epic_id);\n try {\n if (issue_stores && /** @type {any} */ (issue_stores).unregister) {\n /** @type {any} */ (issue_stores).unregister(`detail:${epic_id}`);\n }\n } catch {\n // ignore\n }\n }\n }\n doRender();\n }\n\n /** Build groups from the current `tab:epics` snapshot. */\n function buildGroupsFromSnapshot() {\n /** @type {IssueLite[]} */\n const epic_entities =\n issue_stores && issue_stores.snapshotFor\n ? /** @type {IssueLite[]} */ (\n issue_stores.snapshotFor('tab:epics') || []\n )\n : [];\n const next_groups = [];\n for (const epic of epic_entities) {\n const dependents = Array.isArray(/** @type {any} */ (epic).dependents)\n ? /** @type {any[]} */ (/** @type {any} */ (epic).dependents)\n : [];\n // Prefer explicit counters when provided by server; otherwise derive\n const has_total = Number.isFinite(\n /** @type {any} */ (epic).total_children\n );\n const has_closed = Number.isFinite(\n /** @type {any} */ (epic).closed_children\n );\n const total = has_total\n ? Number(/** @type {any} */ (epic).total_children) || 0\n : dependents.length;\n let closed = has_closed\n ? Number(/** @type {any} */ (epic).closed_children) || 0\n : 0;\n if (!has_closed) {\n for (const d of dependents) {\n if (String(d.status || '') === 'closed') {\n closed++;\n }\n }\n }\n next_groups.push({\n epic,\n total_children: total,\n closed_children: closed\n });\n }\n return next_groups;\n }\n\n return {\n async load() {\n groups = buildGroupsFromSnapshot();\n doRender();\n // Auto-expand first epic on screen\n try {\n if (groups.length > 0) {\n const first_id = String(groups[0].epic?.id || '');\n if (first_id && !expanded.has(first_id)) {\n // This will render and load children lazily\n await toggle(first_id);\n }\n }\n } catch {\n // ignore auto-expand failures\n }\n }\n };\n}\n", "/**\n * Create and manage a fatal error dialog that surfaces stderr output from\n * backend failures (e.g., bd command errors).\n *\n * @param {HTMLElement} mount_element\n * @returns {{ open: (title: string, message: string, detail?: string) => void, close: () => void, getElement: () => HTMLDialogElement }}\n */\nexport function createFatalErrorDialog(mount_element) {\n const dialog = document.createElement('dialog');\n dialog.id = 'fatal-error-dialog';\n dialog.setAttribute('role', 'alertdialog');\n dialog.setAttribute('aria-modal', 'true');\n dialog.innerHTML = `\n <div class=\"fatal-error\">\n <div class=\"fatal-error__icon\" aria-hidden=\"true\">!</div>\n <div class=\"fatal-error__body\">\n <p class=\"fatal-error__eyebrow\">Critical</p>\n <h2 class=\"fatal-error__title\" id=\"fatal-error-title\">Command failed</h2>\n <p class=\"fatal-error__message\" id=\"fatal-error-message\"></p>\n <pre class=\"fatal-error__detail\" id=\"fatal-error-detail\"></pre>\n <div class=\"fatal-error__actions\">\n <button type=\"button\" class=\"btn primary\" id=\"fatal-error-reload\">Reload</button>\n <button type=\"button\" class=\"btn\" id=\"fatal-error-close\">Dismiss</button>\n </div>\n </div>\n </div>`;\n mount_element.appendChild(dialog);\n\n const title_el = dialog.querySelector('#fatal-error-title');\n const message_el = dialog.querySelector('#fatal-error-message');\n const detail_el = dialog.querySelector('#fatal-error-detail');\n const reload_btn = dialog.querySelector('#fatal-error-reload');\n const close_btn = dialog.querySelector('#fatal-error-close');\n\n const close = () => {\n if (typeof dialog.close === 'function') {\n try {\n dialog.close();\n } catch {\n // ignore close errors\n }\n }\n dialog.removeAttribute('open');\n };\n\n /**\n * @param {string} title\n * @param {string} message\n * @param {string} [detail]\n */\n const open = (title, message, detail = '') => {\n if (title_el) {\n title_el.textContent = title || 'Unexpected Error';\n }\n if (message_el) {\n message_el.textContent = message || 'An unrecoverable error occurred.';\n }\n\n const detail_text = typeof detail === 'string' ? detail.trim() : '';\n if (detail_el) {\n if (detail_text.length > 0) {\n detail_el.textContent = detail_text;\n detail_el.removeAttribute('hidden');\n } else {\n detail_el.textContent = 'No additional diagnostics available.';\n detail_el.setAttribute('hidden', '');\n }\n }\n\n if (typeof dialog.showModal === 'function') {\n try {\n dialog.showModal();\n dialog.setAttribute('open', '');\n } catch {\n dialog.setAttribute('open', '');\n }\n } else {\n dialog.setAttribute('open', '');\n }\n };\n\n if (reload_btn) {\n reload_btn.addEventListener('click', () => {\n window.location.reload();\n });\n }\n\n if (close_btn) {\n close_btn.addEventListener('click', () => close());\n }\n\n dialog.addEventListener('cancel', (ev) => {\n ev.preventDefault();\n close();\n });\n\n return {\n open,\n close,\n getElement() {\n return dialog;\n }\n };\n}\n", "// Lightweight wrapper around the native <dialog> for issue details\nimport { createIssueIdRenderer } from '../utils/issue-id-renderer.js';\n\n// Provides: open(id), close(), getMount()\n// Ensures accessibility, backdrop click to close, and Esc handling.\n\n/**\n * @typedef {{ getState: () => { selected_id: string|null } }} Store\n */\n\n/**\n * Create and manage the Issue Details dialog.\n *\n * @param {HTMLElement} mount_element - Container to attach the <dialog> to (e.g., #detail-panel)\n * @param {Store} store - Read-only access to app state\n * @param {() => void} onClose - Called when dialog requests close (backdrop/esc/button)\n * @returns {{ open: (id: string) => void, close: () => void, getMount: () => HTMLElement }}\n */\nexport function createIssueDialog(mount_element, store, onClose) {\n const dialog = document.createElement('dialog');\n dialog.id = 'issue-dialog';\n dialog.setAttribute('role', 'dialog');\n dialog.setAttribute('aria-modal', 'true');\n\n // Shell: header (id + close) + body mount\n dialog.innerHTML = `\n <div class=\"issue-dialog__container\" part=\"container\">\n <header class=\"issue-dialog__header\">\n <div class=\"issue-dialog__title\">\n <span class=\"mono\" id=\"issue-dialog-title\"></span>\n </div>\n <button type=\"button\" class=\"issue-dialog__close\" aria-label=\"Close\">\u00D7</button>\n </header>\n <div class=\"issue-dialog__body\" id=\"issue-dialog-body\"></div>\n </div>\n `;\n\n mount_element.appendChild(dialog);\n\n const body_mount = /** @type {HTMLElement} */ (\n dialog.querySelector('#issue-dialog-body')\n );\n const title_el = /** @type {HTMLElement} */ (\n dialog.querySelector('#issue-dialog-title')\n );\n const btn_close = /** @type {HTMLButtonElement} */ (\n dialog.querySelector('.issue-dialog__close')\n );\n\n /**\n * @param {string} id\n */\n function setTitle(id) {\n // Use copyable ID renderer but keep visible text as raw id for tests/clarity\n title_el.replaceChildren();\n title_el.appendChild(createIssueIdRenderer(id));\n }\n\n // Backdrop click: when clicking the dialog itself (outside container), close\n dialog.addEventListener('mousedown', (ev) => {\n if (ev.target === dialog) {\n ev.preventDefault();\n requestClose();\n }\n });\n // Esc key produces a cancel event on <dialog>\n dialog.addEventListener('cancel', (ev) => {\n ev.preventDefault();\n requestClose();\n });\n // Close button\n btn_close.addEventListener('click', () => requestClose());\n\n /** @type {HTMLElement | null} */\n let last_focus = null;\n\n function requestClose() {\n try {\n if (typeof dialog.close === 'function') {\n dialog.close();\n } else {\n dialog.removeAttribute('open');\n }\n } catch {\n dialog.removeAttribute('open');\n }\n try {\n onClose();\n } catch {\n // ignore consumer errors\n }\n // Restore focus to the element that had focus before opening\n restoreFocus();\n }\n\n /**\n * @param {string} id\n */\n function open(id) {\n // Capture currently focused element to restore after closing\n try {\n const ae = document.activeElement;\n if (ae && ae instanceof HTMLElement) {\n last_focus = ae;\n } else {\n last_focus = null;\n }\n } catch {\n last_focus = null;\n }\n setTitle(id);\n try {\n if ('showModal' in dialog && typeof dialog.showModal === 'function') {\n dialog.showModal();\n } else {\n dialog.setAttribute('open', '');\n }\n // Focus the dialog container for keyboard users\n setTimeout(() => {\n try {\n btn_close.focus();\n } catch {\n // ignore\n }\n }, 0);\n } catch {\n // Fallback for environments without <dialog>\n dialog.setAttribute('open', '');\n }\n }\n\n function close() {\n try {\n if (typeof dialog.close === 'function') {\n dialog.close();\n } else {\n dialog.removeAttribute('open');\n }\n } catch {\n dialog.removeAttribute('open');\n }\n restoreFocus();\n }\n\n function restoreFocus() {\n try {\n if (last_focus && document.contains(last_focus)) {\n last_focus.focus();\n }\n } catch {\n // ignore focus errors\n } finally {\n last_focus = null;\n }\n }\n\n return {\n open,\n close,\n getMount() {\n return body_mount;\n }\n };\n}\n", "/**\n * Known issue types in canonical order for dropdowns.\n *\n * @type {Array<'bug'|'feature'|'task'|'epic'|'chore'>}\n */\nexport const ISSUE_TYPES = ['bug', 'feature', 'task', 'epic', 'chore'];\n\n/**\n * Return a human-friendly label for an issue type.\n *\n * @param {string | null | undefined} type\n * @returns {string}\n */\nexport function typeLabel(type) {\n switch ((type || '').toString().toLowerCase()) {\n case 'bug':\n return 'Bug';\n case 'feature':\n return 'Feature';\n case 'task':\n return 'Task';\n case 'epic':\n return 'Epic';\n case 'chore':\n return 'Chore';\n default:\n return '';\n }\n}\n", "import { html, render } from 'lit-html';\nimport { createListSelectors } from '../data/list-selectors.js';\nimport { cmpClosedDesc } from '../data/sort.js';\nimport { ISSUE_TYPES, typeLabel } from '../utils/issue-type.js';\nimport { issueHashFor } from '../utils/issue-url.js';\nimport { debug } from '../utils/logging.js';\nimport { statusLabel } from '../utils/status.js';\nimport { createIssueRowRenderer } from './issue-row.js';\n\n// List view implementation; requires a transport send function.\n\n/**\n * @typedef {{ id: string, title?: string, status?: 'closed'|'open'|'in_progress', priority?: number, issue_type?: string, assignee?: string, labels?: string[] }} Issue\n */\n\n/**\n * Create the Issues List view.\n *\n * @param {HTMLElement} mount_element - Element to render into.\n * @param {(type: string, payload?: unknown) => Promise<unknown>} sendFn - RPC transport.\n * @param {(hash: string) => void} [navigate_fn] - Navigation function (defaults to setting location.hash).\n * @param {{ getState: () => any, setState: (patch: any) => void, subscribe: (fn: (s:any)=>void)=>()=>void }} [store] - Optional state store.\n * @param {{ selectors: { getIds: (client_id: string) => string[] } }} [_subscriptions]\n * @param {{ snapshotFor?: (client_id: string) => any[], subscribe?: (fn: () => void) => () => void }} [issueStores]\n * @returns {{ load: () => Promise<void>, destroy: () => void }} View API.\n */\n/**\n * Create the Issues List view.\n *\n * @param {HTMLElement} mount_element\n * @param {(type: string, payload?: unknown) => Promise<unknown>} sendFn\n * @param {(hash: string) => void} [navigateFn]\n * @param {{ getState: () => any, setState: (patch: any) => void, subscribe: (fn: (s:any)=>void)=>()=>void }} [store]\n * @param {{ selectors: { getIds: (client_id: string) => string[] } }} [_subscriptions]\n * @param {{ snapshotFor?: (client_id: string) => any[], subscribe?: (fn: () => void) => () => void }} [issue_stores]\n * @returns {{ load: () => Promise<void>, destroy: () => void }}\n */\nexport function createListView(\n mount_element,\n sendFn,\n navigateFn,\n store,\n _subscriptions = undefined,\n issue_stores = undefined\n) {\n const log = debug('views:list');\n // Touch unused param to satisfy lint rules without impacting behavior\n /** @type {any} */ (void _subscriptions);\n /** @type {string[]} */\n let status_filters = [];\n /** @type {string} */\n let search_text = '';\n /** @type {Issue[]} */\n let issues_cache = [];\n /** @type {string[]} */\n let type_filters = [];\n /** @type {string | null} */\n let selected_id = store ? store.getState().selected_id : null;\n /** @type {null | (() => void)} */\n let unsubscribe = null;\n let status_dropdown_open = false;\n let type_dropdown_open = false;\n\n /**\n * Normalize legacy string filter to array format.\n *\n * @param {string | string[] | undefined} val\n * @returns {string[]}\n */\n function normalizeStatusFilter(val) {\n if (Array.isArray(val)) return val;\n if (typeof val === 'string' && val !== '' && val !== 'all') return [val];\n return [];\n }\n\n /**\n * Normalize legacy string filter to array format.\n *\n * @param {string | string[] | undefined} val\n * @returns {string[]}\n */\n function normalizeTypeFilter(val) {\n if (Array.isArray(val)) return val;\n if (typeof val === 'string' && val !== '') return [val];\n return [];\n }\n\n // Shared row renderer (used in template below)\n const row_renderer = createIssueRowRenderer({\n navigate: (id) => {\n const nav = navigateFn || ((h) => (window.location.hash = h));\n /** @type {'issues'|'epics'|'board'} */\n const view = store ? store.getState().view : 'issues';\n nav(issueHashFor(view, id));\n },\n onUpdate: updateInline,\n requestRender: doRender,\n getSelectedId: () => selected_id,\n row_class: 'issue-row'\n });\n\n /**\n * Toggle a status filter chip.\n *\n * @param {string} status\n */\n const toggleStatusFilter = async (status) => {\n if (status_filters.includes(status)) {\n status_filters = status_filters.filter((s) => s !== status);\n } else {\n status_filters = [...status_filters, status];\n }\n log('status toggle %s -> %o', status, status_filters);\n if (store) {\n store.setState({ filters: { status: status_filters } });\n }\n await load();\n };\n\n /**\n * Event: search input.\n */\n /**\n * @param {Event} ev\n */\n const onSearchInput = (ev) => {\n const input = /** @type {HTMLInputElement} */ (ev.currentTarget);\n search_text = input.value;\n log('search input %s', search_text);\n if (store) {\n store.setState({ filters: { search: search_text } });\n }\n doRender();\n };\n\n /**\n * Toggle a type filter chip.\n *\n * @param {string} type\n */\n const toggleTypeFilter = (type) => {\n if (type_filters.includes(type)) {\n type_filters = type_filters.filter((t) => t !== type);\n } else {\n type_filters = [...type_filters, type];\n }\n log('type toggle %s -> %o', type, type_filters);\n if (store) {\n store.setState({ filters: { type: type_filters } });\n }\n doRender();\n };\n\n /**\n * Toggle status dropdown open/closed.\n *\n * @param {Event} e\n */\n const toggleStatusDropdown = (e) => {\n e.stopPropagation();\n status_dropdown_open = !status_dropdown_open;\n type_dropdown_open = false;\n doRender();\n };\n\n /**\n * Toggle type dropdown open/closed.\n *\n * @param {Event} e\n */\n const toggleTypeDropdown = (e) => {\n e.stopPropagation();\n type_dropdown_open = !type_dropdown_open;\n status_dropdown_open = false;\n doRender();\n };\n\n /**\n * Get display text for dropdown trigger.\n *\n * @param {string[]} selected\n * @param {string} label\n * @param {(val: string) => string} formatter\n * @returns {string}\n */\n function getDropdownDisplayText(selected, label, formatter) {\n if (selected.length === 0) return `${label}: Any`;\n if (selected.length === 1) return `${label}: ${formatter(selected[0])}`;\n return `${label} (${selected.length})`;\n }\n\n // Initialize filters from store on first render so reload applies persisted state\n if (store) {\n const s = store.getState();\n if (s && s.filters && typeof s.filters === 'object') {\n status_filters = normalizeStatusFilter(s.filters.status);\n search_text = s.filters.search || '';\n type_filters = normalizeTypeFilter(s.filters.type);\n }\n }\n // Initial values are reflected via bound `.value` in the template\n // Compose helpers: centralize membership + entity selection + sorting\n const selectors = issue_stores ? createListSelectors(issue_stores) : null;\n\n /**\n * Build lit-html template for the list view.\n */\n function template() {\n let filtered = issues_cache;\n if (status_filters.length > 0 && !status_filters.includes('ready')) {\n filtered = filtered.filter((it) =>\n status_filters.includes(String(it.status || ''))\n );\n }\n if (search_text) {\n const needle = search_text.toLowerCase();\n filtered = filtered.filter((it) => {\n const a = String(it.id).toLowerCase();\n const b = String(it.title || '').toLowerCase();\n return a.includes(needle) || b.includes(needle);\n });\n }\n if (type_filters.length > 0) {\n filtered = filtered.filter((it) =>\n type_filters.includes(String(it.issue_type || ''))\n );\n }\n // Sorting: closed list is a special case \u2192 sort by closed_at desc only\n if (status_filters.length === 1 && status_filters[0] === 'closed') {\n filtered = filtered.slice().sort(cmpClosedDesc);\n }\n\n return html`\n <div class=\"panel__header\">\n <div class=\"filter-dropdown ${status_dropdown_open ? 'is-open' : ''}\">\n <button\n class=\"filter-dropdown__trigger\"\n @click=${toggleStatusDropdown}\n >\n ${getDropdownDisplayText(status_filters, 'Status', statusLabel)}\n <span class=\"filter-dropdown__arrow\">\u25BE</span>\n </button>\n <div class=\"filter-dropdown__menu\">\n ${['ready', 'open', 'in_progress', 'closed'].map(\n (s) => html`\n <label class=\"filter-dropdown__option\">\n <input\n type=\"checkbox\"\n .checked=${status_filters.includes(s)}\n @change=${() => toggleStatusFilter(s)}\n />\n ${s === 'ready' ? 'Ready' : statusLabel(s)}\n </label>\n `\n )}\n </div>\n </div>\n <div class=\"filter-dropdown ${type_dropdown_open ? 'is-open' : ''}\">\n <button class=\"filter-dropdown__trigger\" @click=${toggleTypeDropdown}>\n ${getDropdownDisplayText(type_filters, 'Types', typeLabel)}\n <span class=\"filter-dropdown__arrow\">\u25BE</span>\n </button>\n <div class=\"filter-dropdown__menu\">\n ${ISSUE_TYPES.map(\n (t) => html`\n <label class=\"filter-dropdown__option\">\n <input\n type=\"checkbox\"\n .checked=${type_filters.includes(t)}\n @change=${() => toggleTypeFilter(t)}\n />\n ${typeLabel(t)}\n </label>\n `\n )}\n </div>\n </div>\n <input\n type=\"search\"\n placeholder=\"Search\u2026\"\n @input=${onSearchInput}\n .value=${search_text}\n />\n </div>\n <div class=\"panel__body\" id=\"list-root\">\n ${filtered.length === 0\n ? html`<div class=\"issues-block\">\n <div class=\"muted\" style=\"padding:10px 12px;\">No issues</div>\n </div>`\n : html`<div class=\"issues-block\">\n <table\n class=\"table\"\n role=\"grid\"\n aria-rowcount=${String(filtered.length)}\n aria-colcount=\"6\"\n >\n <colgroup>\n <col style=\"width: 100px\" />\n <col style=\"width: 120px\" />\n <col />\n <col style=\"width: 120px\" />\n <col style=\"width: 160px\" />\n <col style=\"width: 130px\" />\n <col style=\"width: 80px\" />\n </colgroup>\n <thead>\n <tr role=\"row\">\n <th role=\"columnheader\">ID</th>\n <th role=\"columnheader\">Type</th>\n <th role=\"columnheader\">Title</th>\n <th role=\"columnheader\">Status</th>\n <th role=\"columnheader\">Assignee</th>\n <th role=\"columnheader\">Priority</th>\n <th role=\"columnheader\">Deps</th>\n </tr>\n </thead>\n <tbody role=\"rowgroup\">\n ${filtered.map((it) => row_renderer(it))}\n </tbody>\n </table>\n </div>`}\n </div>\n `;\n }\n\n /**\n * Render the current issues_cache with filters applied.\n */\n function doRender() {\n render(template(), mount_element);\n }\n\n // Initial render (header + body shell with current state)\n doRender();\n // no separate ready checkbox when using select option\n\n /**\n * Update minimal fields inline via ws mutations and refresh that row's data.\n *\n * @param {string} id\n * @param {{ [k: string]: any }} patch\n */\n async function updateInline(id, patch) {\n try {\n log('updateInline %s %o', id, Object.keys(patch));\n // Dispatch specific mutations based on provided keys\n if (typeof patch.title === 'string') {\n await sendFn('edit-text', { id, field: 'title', value: patch.title });\n }\n if (typeof patch.assignee === 'string') {\n await sendFn('update-assignee', { id, assignee: patch.assignee });\n }\n if (typeof patch.status === 'string') {\n await sendFn('update-status', { id, status: patch.status });\n }\n if (typeof patch.priority === 'number') {\n await sendFn('update-priority', { id, priority: patch.priority });\n }\n } catch {\n // ignore failures; UI state remains as-is\n }\n }\n\n /**\n * Load issues from local push stores and re-render.\n */\n async function load() {\n log('load');\n // Preserve scroll position to avoid jarring jumps on live refresh\n const beforeEl = /** @type {HTMLElement|null} */ (\n mount_element.querySelector('#list-root')\n );\n const prevScroll = beforeEl ? beforeEl.scrollTop : 0;\n // Compose items from subscriptions membership and issues store entities\n try {\n if (selectors) {\n issues_cache = /** @type {Issue[]} */ (\n selectors.selectIssuesFor('tab:issues')\n );\n } else {\n issues_cache = [];\n }\n } catch (err) {\n log('load failed: %o', err);\n issues_cache = [];\n }\n doRender();\n // Restore scroll position if possible\n try {\n const afterEl = /** @type {HTMLElement|null} */ (\n mount_element.querySelector('#list-root')\n );\n if (afterEl && prevScroll > 0) {\n afterEl.scrollTop = prevScroll;\n }\n } catch {\n // ignore\n }\n }\n\n // Keyboard navigation\n mount_element.tabIndex = 0;\n mount_element.addEventListener('keydown', (ev) => {\n // Grid cell Up/Down navigation when focus is inside the table and not within\n // an editable control (input/textarea/select). Preserves column position.\n if (ev.key === 'ArrowDown' || ev.key === 'ArrowUp') {\n const tgt = /** @type {HTMLElement} */ (ev.target);\n const table =\n tgt && typeof tgt.closest === 'function'\n ? tgt.closest('#list-root table.table')\n : null;\n if (table) {\n // Do not intercept when inside native editable controls\n const in_editable = Boolean(\n tgt &&\n typeof tgt.closest === 'function' &&\n (tgt.closest('input') ||\n tgt.closest('textarea') ||\n tgt.closest('select'))\n );\n if (!in_editable) {\n const cell =\n tgt && typeof tgt.closest === 'function' ? tgt.closest('td') : null;\n if (cell && cell.parentElement) {\n const row = /** @type {HTMLTableRowElement} */ (cell.parentElement);\n const tbody = /** @type {HTMLTableSectionElement|null} */ (\n row.parentElement\n );\n if (tbody && tbody.querySelectorAll) {\n const rows = Array.from(tbody.querySelectorAll('tr'));\n const row_idx = Math.max(0, rows.indexOf(row));\n const col_idx = cell.cellIndex || 0;\n const next_idx =\n ev.key === 'ArrowDown'\n ? Math.min(row_idx + 1, rows.length - 1)\n : Math.max(row_idx - 1, 0);\n const next_row = rows[next_idx];\n const next_cell =\n next_row && next_row.cells ? next_row.cells[col_idx] : null;\n if (next_cell) {\n const focusable = /** @type {HTMLElement|null} */ (\n next_cell.querySelector(\n 'button:not([disabled]), [tabindex]:not([tabindex=\"-1\"]), a[href], select:not([disabled]), input:not([disabled]):not([type=\"hidden\"]), textarea:not([disabled])'\n )\n );\n if (focusable && typeof focusable.focus === 'function') {\n ev.preventDefault();\n focusable.focus();\n return;\n }\n }\n }\n }\n }\n }\n }\n\n const tbody = /** @type {HTMLTableSectionElement|null} */ (\n mount_element.querySelector('#list-root tbody')\n );\n const items = tbody ? tbody.querySelectorAll('tr') : [];\n if (items.length === 0) {\n return;\n }\n let idx = 0;\n if (selected_id) {\n const arr = Array.from(items);\n idx = arr.findIndex((el) => {\n const did = el.getAttribute('data-issue-id') || '';\n return did === selected_id;\n });\n if (idx < 0) {\n idx = 0;\n }\n }\n if (ev.key === 'ArrowDown') {\n ev.preventDefault();\n const next = items[Math.min(idx + 1, items.length - 1)];\n const next_id = next ? next.getAttribute('data-issue-id') : '';\n const set = next_id ? next_id : null;\n if (store && set) {\n store.setState({ selected_id: set });\n }\n selected_id = set;\n doRender();\n } else if (ev.key === 'ArrowUp') {\n ev.preventDefault();\n const prev = items[Math.max(idx - 1, 0)];\n const prev_id = prev ? prev.getAttribute('data-issue-id') : '';\n const set = prev_id ? prev_id : null;\n if (store && set) {\n store.setState({ selected_id: set });\n }\n selected_id = set;\n doRender();\n } else if (ev.key === 'Enter') {\n ev.preventDefault();\n const current = items[idx];\n const id = current ? current.getAttribute('data-issue-id') : '';\n if (id) {\n const nav = navigateFn || ((h) => (window.location.hash = h));\n /** @type {'issues'|'epics'|'board'} */\n const view = store ? store.getState().view : 'issues';\n nav(issueHashFor(view, id));\n }\n }\n });\n\n // Click outside to close dropdowns\n /** @param {MouseEvent} e */\n const clickOutsideHandler = (e) => {\n const target = /** @type {HTMLElement|null} */ (e.target);\n if (target && !target.closest('.filter-dropdown')) {\n if (status_dropdown_open || type_dropdown_open) {\n status_dropdown_open = false;\n type_dropdown_open = false;\n doRender();\n }\n }\n };\n document.addEventListener('click', clickOutsideHandler);\n\n // Keep selection in sync with store\n if (store) {\n unsubscribe = store.subscribe((s) => {\n if (s.selected_id !== selected_id) {\n selected_id = s.selected_id;\n log('selected %s', selected_id || '(none)');\n doRender();\n }\n if (s.filters && typeof s.filters === 'object') {\n const next_status = normalizeStatusFilter(s.filters.status);\n const next_search = s.filters.search || '';\n let needs_render = false;\n const status_changed =\n JSON.stringify(next_status) !== JSON.stringify(status_filters);\n if (status_changed) {\n status_filters = next_status;\n // Reload on any status scope change to keep cache correct\n void load();\n return;\n }\n if (next_search !== search_text) {\n search_text = next_search;\n needs_render = true;\n }\n const next_type_arr = normalizeTypeFilter(s.filters.type);\n const type_changed =\n JSON.stringify(next_type_arr) !== JSON.stringify(type_filters);\n if (type_changed) {\n type_filters = next_type_arr;\n needs_render = true;\n }\n if (needs_render) {\n doRender();\n }\n }\n });\n }\n\n // Live updates: recompose and re-render when issue stores change\n if (selectors) {\n selectors.subscribe(() => {\n try {\n issues_cache = /** @type {Issue[]} */ (\n selectors.selectIssuesFor('tab:issues')\n );\n doRender();\n } catch {\n // ignore\n }\n });\n }\n\n return {\n load,\n destroy() {\n mount_element.replaceChildren();\n document.removeEventListener('click', clickOutsideHandler);\n if (unsubscribe) {\n unsubscribe();\n unsubscribe = null;\n }\n }\n };\n}\n", "import { html, render } from 'lit-html';\nimport { debug } from '../utils/logging.js';\n\n/**\n * Render the top navigation with three tabs and handle route changes.\n *\n * @param {HTMLElement} mount_element\n * @param {{ getState: () => any, subscribe: (fn: (s: any) => void) => () => void }} store\n * @param {{ gotoView: (v: 'issues'|'epics'|'board') => void }} router\n */\nexport function createTopNav(mount_element, store, router) {\n const log = debug('views:nav');\n /** @type {(() => void) | null} */\n let unsubscribe = null;\n\n /**\n * @param {'issues'|'epics'|'board'} view\n * @returns {(ev: MouseEvent) => void}\n */\n function onClick(view) {\n return (ev) => {\n ev.preventDefault();\n log('click tab %s', view);\n router.gotoView(view);\n };\n }\n\n function template() {\n const s = store.getState();\n const active = s.view || 'issues';\n return html`\n <nav class=\"header-nav\" aria-label=\"Primary\">\n <a\n href=\"#/issues\"\n class=\"tab ${active === 'issues' ? 'active' : ''}\"\n @click=${onClick('issues')}\n >Issues</a\n >\n <a\n href=\"#/epics\"\n class=\"tab ${active === 'epics' ? 'active' : ''}\"\n @click=${onClick('epics')}\n >Epics</a\n >\n <a\n href=\"#/board\"\n class=\"tab ${active === 'board' ? 'active' : ''}\"\n @click=${onClick('board')}\n >Board</a\n >\n </nav>\n `;\n }\n\n function doRender() {\n render(template(), mount_element);\n }\n\n doRender();\n unsubscribe = store.subscribe(() => doRender());\n\n return {\n destroy() {\n if (unsubscribe) {\n unsubscribe();\n unsubscribe = null;\n }\n render(html``, mount_element);\n }\n };\n}\n", "import { ISSUE_TYPES, typeLabel } from '../utils/issue-type.js';\nimport { priority_levels } from '../utils/priority.js';\n\n/**\n * Create and manage the New Issue dialog (native <dialog>).\n *\n * @param {HTMLElement} mount_element - Container to attach dialog (e.g., main#app)\n * @param {(type: import('../protocol.js').MessageType, payload?: unknown) => Promise<unknown>} sendFn - Transport function\n * @param {{ gotoIssue: (id: string) => void }} router - Router for opening details after create\n * @param {{ setState: (patch: any) => void, getState: () => any }} [store]\n * @returns {{ open: () => void, close: () => void }}\n */\nexport function createNewIssueDialog(mount_element, sendFn, router, store) {\n const dialog = /** @type {HTMLDialogElement} */ (\n document.createElement('dialog')\n );\n dialog.id = 'new-issue-dialog';\n dialog.setAttribute('role', 'dialog');\n dialog.setAttribute('aria-modal', 'true');\n\n dialog.innerHTML = `\n <div class=\"new-issue__container\" part=\"container\">\n <header class=\"new-issue__header\">\n <div class=\"new-issue__title\">New Issue</div>\n <button type=\"button\" class=\"new-issue__close\" aria-label=\"Close\">\u00D7</button>\n </header>\n <div class=\"new-issue__body\">\n <form id=\"new-issue-form\" class=\"new-issue__form\">\n <label for=\"new-title\">Title</label>\n <input id=\"new-title\" name=\"title\" type=\"text\" required placeholder=\"Short summary\" />\n\n <label for=\"new-type\">Type</label>\n <select id=\"new-type\" name=\"type\" aria-label=\"Issue type\"></select>\n\n <label for=\"new-priority\">Priority</label>\n <select id=\"new-priority\" name=\"priority\" aria-label=\"Priority\"></select>\n\n <label for=\"new-labels\">Labels</label>\n <input id=\"new-labels\" name=\"labels\" type=\"text\" placeholder=\"comma,separated\" />\n\n <label for=\"new-description\">Description</label>\n <textarea id=\"new-description\" name=\"description\" rows=\"6\" placeholder=\"Optional markdown description\"></textarea>\n\n <div aria-live=\"polite\" role=\"status\" class=\"new-issue__error\" id=\"new-issue-error\"></div>\n\n <div class=\"new-issue__actions\" style=\"grid-column: 1 / -1\">\n <button type=\"button\" id=\"btn-cancel\">Cancel (Esc)</button>\n <button type=\"submit\" id=\"btn-create\">Create</button>\n </div>\n </form>\n </div>\n </div>\n `;\n\n mount_element.appendChild(dialog);\n\n const form = /** @type {HTMLFormElement} */ (\n dialog.querySelector('#new-issue-form')\n );\n const input_title = /** @type {HTMLInputElement} */ (\n dialog.querySelector('#new-title')\n );\n const sel_type = /** @type {HTMLSelectElement} */ (\n dialog.querySelector('#new-type')\n );\n const sel_priority = /** @type {HTMLSelectElement} */ (\n dialog.querySelector('#new-priority')\n );\n const input_labels = /** @type {HTMLInputElement} */ (\n dialog.querySelector('#new-labels')\n );\n const input_description = /** @type {HTMLTextAreaElement} */ (\n dialog.querySelector('#new-description')\n );\n const error_box = /** @type {HTMLDivElement} */ (\n dialog.querySelector('#new-issue-error')\n );\n const btn_cancel = /** @type {HTMLButtonElement} */ (\n dialog.querySelector('#btn-cancel')\n );\n const btn_create = /** @type {HTMLButtonElement} */ (\n dialog.querySelector('#btn-create')\n );\n const btn_close = /** @type {HTMLButtonElement} */ (\n dialog.querySelector('.new-issue__close')\n );\n\n // Populate selects\n function populateSelects() {\n sel_type.replaceChildren();\n // Empty option to allow leaving type unspecified\n const optEmpty = document.createElement('option');\n optEmpty.value = '';\n optEmpty.textContent = '\u2014 Select \u2014';\n sel_type.appendChild(optEmpty);\n for (const t of ISSUE_TYPES) {\n const o = document.createElement('option');\n o.value = t;\n o.textContent = typeLabel(t);\n sel_type.appendChild(o);\n }\n\n sel_priority.replaceChildren();\n for (let i = 0; i <= 4; i += 1) {\n const o = document.createElement('option');\n o.value = String(i);\n const label = priority_levels[i] || 'Medium';\n o.textContent = `${i} \u2013 ${label}`;\n sel_priority.appendChild(o);\n }\n }\n populateSelects();\n\n function requestClose() {\n try {\n if (typeof dialog.close === 'function') {\n dialog.close();\n } else {\n dialog.removeAttribute('open');\n }\n } catch {\n dialog.removeAttribute('open');\n }\n }\n\n /**\n * @param {boolean} is_busy\n */\n function setBusy(is_busy) {\n input_title.disabled = is_busy;\n sel_type.disabled = is_busy;\n sel_priority.disabled = is_busy;\n input_labels.disabled = is_busy;\n input_description.disabled = is_busy;\n btn_cancel.disabled = is_busy;\n btn_create.disabled = is_busy;\n btn_create.textContent = is_busy ? 'Creating\u2026' : 'Create';\n }\n\n function clearError() {\n error_box.textContent = '';\n }\n\n /**\n * @param {string} msg\n */\n function setError(msg) {\n error_box.textContent = msg;\n }\n\n function loadDefaults() {\n try {\n const t = window.localStorage.getItem('beads-ui.new.type');\n if (t) {\n sel_type.value = t;\n } else {\n sel_type.value = '';\n }\n const p = window.localStorage.getItem('beads-ui.new.priority');\n if (p && /^\\d$/.test(p)) {\n sel_priority.value = p;\n } else {\n sel_priority.value = '2';\n }\n } catch {\n sel_type.value = '';\n sel_priority.value = '2';\n }\n }\n\n function saveDefaults() {\n const t = sel_type.value || '';\n const p = sel_priority.value || '';\n if (t.length > 0) {\n window.localStorage.setItem('beads-ui.new.type', t);\n }\n if (p.length > 0) {\n window.localStorage.setItem('beads-ui.new.priority', p);\n }\n }\n\n /**\n * Extract numeric suffix from an id like \"UI-123\"; return -1 when absent.\n *\n * @param {string} id\n */\n function idNumeric(id) {\n const m = /-(\\d+)$/.exec(String(id || ''));\n return m && m[1] ? Number(m[1]) : -1;\n }\n\n /**\n * Submit handler: validate, create, then open the created issue details.\n *\n * @returns {Promise<void>}\n */\n async function createNow() {\n clearError();\n const title = String(input_title.value || '').trim();\n if (title.length === 0) {\n setError('Title is required');\n input_title.focus();\n return;\n }\n const prio = Number(sel_priority.value || '2');\n if (!(prio >= 0 && prio <= 4)) {\n setError('Priority must be 0..4');\n sel_priority.focus();\n return;\n }\n const type = String(sel_type.value || '');\n const desc = String(input_description.value || '');\n const labels = String(input_labels.value || '')\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n\n /** @type {{ title: string, type?: string, priority?: number, description?: string }} */\n const payload = { title };\n if (type.length > 0) {\n payload.type = type;\n }\n if (String(prio).length > 0) {\n payload.priority = prio;\n }\n if (desc.length > 0) {\n payload.description = desc;\n }\n\n setBusy(true);\n try {\n await sendFn('create-issue', payload);\n } catch {\n setBusy(false);\n setError('Failed to create issue');\n return;\n }\n\n saveDefaults();\n\n // Best-effort: find the created id by matching title among open issues and picking the highest numeric id\n /** @type {any} */\n let list = null;\n try {\n list = await sendFn('list-issues', {\n filters: { status: 'open', limit: 50 }\n });\n } catch {\n list = null;\n }\n let created_id = '';\n if (Array.isArray(list)) {\n const matches = list.filter((it) => String(it.title || '') === title);\n if (matches.length > 0) {\n let best = matches[0];\n for (const it of matches) {\n const ai = idNumeric(best.id || '');\n const bi = idNumeric(it.id || '');\n if (bi > ai) {\n best = it;\n }\n }\n created_id = String(best.id || '');\n }\n }\n\n // Apply labels if any\n if (created_id && labels.length > 0) {\n for (const label of labels) {\n try {\n await sendFn('label-add', { id: created_id, label });\n } catch {\n // ignore label failures\n }\n }\n }\n\n // Navigate to created issue if found\n if (created_id) {\n try {\n router.gotoIssue(created_id);\n } catch {\n // ignore routing errors\n }\n // Also set state directly to ensure dialog opens even if hash routing is suppressed in tests\n try {\n if (store) {\n store.setState({ selected_id: created_id });\n }\n } catch {\n // ignore\n }\n }\n\n setBusy(false);\n requestClose();\n }\n\n // Events\n dialog.addEventListener('cancel', (ev) => {\n ev.preventDefault();\n requestClose();\n });\n btn_close.addEventListener('click', () => requestClose());\n btn_cancel.addEventListener('click', () => requestClose());\n dialog.addEventListener('keydown', (ev) => {\n if (ev.key === 'Enter' && (ev.ctrlKey || ev.metaKey)) {\n ev.preventDefault();\n void createNow();\n }\n });\n form.addEventListener('submit', (ev) => {\n ev.preventDefault();\n void createNow();\n });\n\n return {\n open() {\n form.reset();\n clearError();\n loadDefaults();\n try {\n if ('showModal' in dialog && typeof dialog.showModal === 'function') {\n dialog.showModal();\n } else {\n dialog.setAttribute('open', '');\n }\n } catch {\n dialog.setAttribute('open', '');\n }\n setTimeout(() => {\n try {\n input_title.focus();\n } catch {\n // ignore\n }\n }, 0);\n },\n close() {\n requestClose();\n }\n };\n}\n", "import { html, render } from 'lit-html';\nimport { debug } from '../utils/logging.js';\n\n/**\n * @typedef {import('../state.js').WorkspaceInfo} WorkspaceInfo\n */\n\n/**\n * Extract the project name from a workspace path. Returns just the directory\n * name (e.g., 'myproject' from '/home/user/code/myproject').\n *\n * @param {string} workspace_path\n * @returns {string}\n */\nfunction getProjectName(workspace_path) {\n if (!workspace_path) return 'Unknown';\n const parts = workspace_path.split('/').filter(Boolean);\n return parts.length > 0 ? parts[parts.length - 1] : 'Unknown';\n}\n\n/**\n * Create the workspace picker dropdown component.\n *\n * @param {HTMLElement} mount_element\n * @param {{ getState: () => any, subscribe: (fn: (s: any) => void) => () => void }} store\n * @param {(workspace_path: string) => Promise<void>} onWorkspaceChange\n */\nexport function createWorkspacePicker(mount_element, store, onWorkspaceChange) {\n const log = debug('views:workspace-picker');\n /** @type {(() => void) | null} */\n let unsubscribe = null;\n /** @type {boolean} */\n let is_switching = false;\n\n /**\n * Handle workspace selection change.\n *\n * @param {Event} ev\n */\n async function onChange(ev) {\n const select = /** @type {HTMLSelectElement} */ (ev.target);\n const new_path = select.value;\n const s = store.getState();\n const current_path = s.workspace?.current?.path || '';\n\n if (new_path && new_path !== current_path) {\n log('switching workspace to %s', new_path);\n is_switching = true;\n doRender();\n try {\n await onWorkspaceChange(new_path);\n } catch (err) {\n log('workspace switch failed: %o', err);\n } finally {\n is_switching = false;\n doRender();\n }\n }\n }\n\n function template() {\n const s = store.getState();\n const current = s.workspace?.current;\n const available = s.workspace?.available || [];\n\n // Don't render if no workspaces available\n if (available.length === 0) {\n return html``;\n }\n\n // If only one workspace, show it as a simple label\n if (available.length === 1) {\n const name = getProjectName(available[0].path);\n return html`\n <div class=\"workspace-picker workspace-picker--single\">\n <span class=\"workspace-picker__label\" title=\"${available[0].path}\"\n >${name}</span\n >\n </div>\n `;\n }\n\n // Multiple workspaces: show dropdown\n const current_path = current?.path || '';\n return html`\n <div class=\"workspace-picker\">\n <select\n class=\"workspace-picker__select\"\n @change=${onChange}\n ?disabled=${is_switching}\n aria-label=\"Select project workspace\"\n >\n ${available.map(\n (/** @type {WorkspaceInfo} */ ws) => html`\n <option\n value=\"${ws.path}\"\n ?selected=${ws.path === current_path}\n title=\"${ws.path}\"\n >\n ${getProjectName(ws.path)}\n </option>\n `\n )}\n </select>\n ${is_switching\n ? html`<span\n class=\"workspace-picker__loading\"\n aria-hidden=\"true\"\n ></span>`\n : ''}\n </div>\n `;\n }\n\n function doRender() {\n render(template(), mount_element);\n }\n\n doRender();\n unsubscribe = store.subscribe(() => doRender());\n\n return {\n destroy() {\n if (unsubscribe) {\n unsubscribe();\n unsubscribe = null;\n }\n render(html``, mount_element);\n }\n };\n}\n", "/**\n * Protocol definitions for beads-ui WebSocket communication.\n *\n * Conventions\n * - All messages are JSON objects.\n * - Client \u2192 Server uses RequestEnvelope.\n * - Server \u2192 Client uses ReplyEnvelope.\n * - Every request is correlated by `id` in replies.\n * - Server can also send unsolicited events (e.g., subscription `snapshot`).\n */\n\n/** @typedef {'list-issues'|'update-status'|'edit-text'|'update-priority'|'create-issue'|'list-ready'|'dep-add'|'dep-remove'|'epic-status'|'update-assignee'|'label-add'|'label-remove'|'subscribe-list'|'unsubscribe-list'|'snapshot'|'upsert'|'delete'|'get-comments'|'add-comment'|'delete-issue'|'list-workspaces'|'set-workspace'|'get-workspace'|'workspace-changed'} MessageType */\n\n/**\n * @typedef {Object} RequestEnvelope\n * @property {string} id - Unique id to correlate request/response.\n * @property {MessageType} type - Message type.\n * @property {unknown} [payload] - Message payload.\n */\n\n/**\n * @typedef {Object} ErrorObject\n * @property {string} code - Stable error code.\n * @property {string} message - Human-readable message.\n * @property {unknown} [details] - Optional extra info for debugging.\n */\n\n/**\n * @typedef {Object} ReplyEnvelope\n * @property {string} id - Correlates to the originating request.\n * @property {boolean} ok - True when request succeeded; false on error.\n * @property {MessageType} type - Echoes request type (or event type).\n * @property {unknown} [payload] - Response payload.\n * @property {ErrorObject} [error] - Present when ok=false.\n */\n\n/** @type {MessageType[]} */\nexport const MESSAGE_TYPES = /** @type {const} */ ([\n 'list-issues',\n 'update-status',\n 'edit-text',\n 'update-priority',\n 'create-issue',\n 'list-ready',\n 'dep-add',\n 'dep-remove',\n 'epic-status',\n 'update-assignee',\n 'label-add',\n 'label-remove',\n 'subscribe-list',\n 'unsubscribe-list',\n // vNext per-subscription full-issue push events\n 'snapshot',\n 'upsert',\n 'delete',\n // Comments\n 'get-comments',\n 'add-comment',\n // Delete issue\n 'delete-issue',\n // Workspace management\n 'list-workspaces',\n 'set-workspace',\n 'get-workspace',\n 'workspace-changed'\n]);\n\n/**\n * Generate a lexically sortable request id.\n *\n * @returns {string}\n */\nexport function nextId() {\n const now = Date.now().toString(36);\n const rand = Math.random().toString(36).slice(2, 8);\n return `${now}-${rand}`;\n}\n\n/**\n * Create a request envelope.\n *\n * @param {MessageType} type - Message type.\n * @param {unknown} [payload] - Message payload.\n * @param {string} [id] - Optional id; generated if omitted.\n * @returns {RequestEnvelope}\n */\nexport function makeRequest(type, payload, id = nextId()) {\n return { id, type, payload };\n}\n\n/**\n * Create a successful reply envelope for a given request.\n *\n * @param {RequestEnvelope} req - Original request.\n * @param {unknown} [payload] - Reply payload.\n * @returns {ReplyEnvelope}\n */\nexport function makeOk(req, payload) {\n return { id: req.id, ok: true, type: req.type, payload };\n}\n\n/**\n * Create an error reply envelope for a given request.\n *\n * @param {RequestEnvelope} req - Original request.\n * @param {string} code\n * @param {string} message\n * @param {unknown} [details]\n * @returns {ReplyEnvelope}\n */\nexport function makeError(req, code, message, details) {\n return {\n id: req.id,\n ok: false,\n type: req.type,\n error: { code, message, details }\n };\n}\n\n/**\n * Check if a value is a plain object.\n *\n * @param {unknown} value\n * @returns {value is Record<string, unknown>}\n */\nfunction isRecord(value) {\n return !!value && typeof value === 'object' && !Array.isArray(value);\n}\n\n/**\n * Type guard for MessageType values.\n *\n * @param {unknown} value\n * @returns {value is MessageType}\n */\nexport function isMessageType(value) {\n return (\n typeof value === 'string' &&\n MESSAGE_TYPES.includes(/** @type {MessageType} */ (value))\n );\n}\n\n/**\n * Type guard for RequestEnvelope.\n *\n * @param {unknown} value\n * @returns {value is RequestEnvelope}\n */\nexport function isRequest(value) {\n if (!isRecord(value)) {\n return false;\n }\n return (\n typeof value.id === 'string' &&\n typeof value.type === 'string' &&\n (value.payload === undefined || 'payload' in value)\n );\n}\n\n/**\n * Type guard for ReplyEnvelope.\n *\n * @param {unknown} value\n * @returns {value is ReplyEnvelope}\n */\nexport function isReply(value) {\n if (!isRecord(value)) {\n return false;\n }\n if (\n typeof value.id !== 'string' ||\n typeof value.ok !== 'boolean' ||\n !isMessageType(value.type)\n ) {\n return false;\n }\n if (value.ok === false) {\n const err = value.error;\n if (\n !isRecord(err) ||\n typeof err.code !== 'string' ||\n typeof err.message !== 'string'\n ) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Normalize and validate an incoming JSON value as a RequestEnvelope.\n * Throws a user-friendly error if invalid.\n *\n * @param {unknown} json\n * @returns {RequestEnvelope}\n */\nexport function decodeRequest(json) {\n if (!isRequest(json)) {\n throw new Error('Invalid request envelope');\n }\n return json;\n}\n\n/**\n * Normalize and validate an incoming JSON value as a ReplyEnvelope.\n *\n * @param {unknown} json\n * @returns {ReplyEnvelope}\n */\nexport function decodeReply(json) {\n if (!isReply(json)) {\n throw new Error('Invalid reply envelope');\n }\n return json;\n}\n", "/**\n * @import { MessageType } from './protocol.js'\n */\n/**\n * Persistent WebSocket client with reconnect, request/response correlation,\n * and simple event dispatching.\n *\n * Usage:\n * const ws = createWsClient();\n * const data = await ws.send('list-issues', { filters: {} });\n * const off = ws.on('snapshot', (payload) => { <push event> });\n */\nimport { MESSAGE_TYPES, makeRequest, nextId } from './protocol.js';\nimport { debug } from './utils/logging.js';\n\n/**\n * @typedef {'connecting'|'open'|'closed'|'reconnecting'} ConnectionState\n */\n\n/**\n * @typedef {{ initialMs?: number, maxMs?: number, factor?: number, jitterRatio?: number }} BackoffOptions\n */\n\n/**\n * @typedef {{ url?: string, backoff?: BackoffOptions }} ClientOptions\n */\n\n/**\n * Create a WebSocket client with auto-reconnect and message correlation.\n *\n * @param {ClientOptions} [options]\n */\nexport function createWsClient(options = {}) {\n const log = debug('ws');\n\n /** @type {BackoffOptions} */\n const backoff = {\n initialMs: options.backoff?.initialMs ?? 1000,\n maxMs: options.backoff?.maxMs ?? 30000,\n factor: options.backoff?.factor ?? 2,\n jitterRatio: options.backoff?.jitterRatio ?? 0.2\n };\n\n /** @type {() => string} */\n const resolveUrl = () => {\n if (options.url && options.url.length > 0) {\n return options.url;\n }\n if (typeof location !== 'undefined') {\n return (\n (location.protocol === 'https:' ? 'wss://' : 'ws://') +\n location.host +\n '/ws'\n );\n }\n return 'ws://localhost/ws';\n };\n\n /** @type {WebSocket | null} */\n let ws = null;\n /** @type {ConnectionState} */\n let state = 'closed';\n /** @type {number} */\n let attempts = 0;\n /** @type {ReturnType<typeof setTimeout> | null} */\n let reconnect_timer = null;\n /** @type {boolean} */\n let should_reconnect = true;\n\n /** @type {Map<string, { resolve: (v: any) => void, reject: (e: any) => void, type: string }>} */\n const pending = new Map();\n /** @type {Array<ReturnType<typeof makeRequest>>} */\n const queue = [];\n /** @type {Map<string, Set<(payload: any) => void>>} */\n const handlers = new Map();\n /** @type {Set<(s: ConnectionState) => void>} */\n const connection_handlers = new Set();\n\n /**\n * @param {ConnectionState} s\n */\n function notifyConnection(s) {\n for (const fn of Array.from(connection_handlers)) {\n try {\n fn(s);\n } catch {\n // ignore listener errors\n }\n }\n }\n\n function scheduleReconnect() {\n if (!should_reconnect || reconnect_timer) {\n return;\n }\n state = 'reconnecting';\n log('ws reconnecting\u2026');\n notifyConnection(state);\n const base = Math.min(\n backoff.maxMs || 0,\n (backoff.initialMs || 0) * Math.pow(backoff.factor || 1, attempts)\n );\n const jitter = (backoff.jitterRatio || 0) * base;\n const delay = Math.max(\n 0,\n Math.round(base + (Math.random() * 2 - 1) * jitter)\n );\n log('ws retry in %d ms (attempt %d)', delay, attempts + 1);\n reconnect_timer = setTimeout(() => {\n reconnect_timer = null;\n connect();\n }, delay);\n }\n\n /** @param {ReturnType<typeof makeRequest>} req */\n function sendRaw(req) {\n try {\n ws?.send(JSON.stringify(req));\n } catch (err) {\n log('ws send failed', err);\n }\n }\n\n function onOpen() {\n state = 'open';\n log('ws open');\n notifyConnection(state);\n attempts = 0;\n // flush queue\n while (queue.length) {\n const req = queue.shift();\n if (req) {\n sendRaw(req);\n }\n }\n }\n\n /** @param {MessageEvent} ev */\n function onMessage(ev) {\n /** @type {any} */\n let msg;\n try {\n msg = JSON.parse(String(ev.data));\n } catch {\n log('ws received non-JSON message');\n return;\n }\n if (!msg || typeof msg.id !== 'string' || typeof msg.type !== 'string') {\n log('ws received invalid envelope');\n return;\n }\n\n if (pending.has(msg.id)) {\n const entry = pending.get(msg.id);\n pending.delete(msg.id);\n if (msg.ok) {\n entry?.resolve(msg.payload);\n } else {\n entry?.reject(msg.error || new Error('ws error'));\n }\n return;\n }\n\n // Treat as server-initiated event\n const set = handlers.get(msg.type);\n if (set && set.size > 0) {\n for (const fn of Array.from(set)) {\n try {\n fn(msg.payload);\n } catch (err) {\n log('ws event handler error', err);\n }\n }\n } else {\n log('ws received unhandled message type: %s', msg.type);\n }\n }\n\n function onClose() {\n state = 'closed';\n log('ws closed');\n notifyConnection(state);\n // fail all pending\n for (const [id, p] of pending.entries()) {\n p.reject(new Error('ws disconnected'));\n pending.delete(id);\n }\n attempts += 1;\n scheduleReconnect();\n }\n\n function connect() {\n if (!should_reconnect) {\n return;\n }\n const url = resolveUrl();\n try {\n ws = new WebSocket(url);\n log('ws connecting %s', url);\n state = 'connecting';\n notifyConnection(state);\n ws.addEventListener('open', onOpen);\n ws.addEventListener('message', onMessage);\n ws.addEventListener('error', () => {\n // let close handler handle reconnect\n });\n ws.addEventListener('close', onClose);\n } catch (err) {\n log('ws connect failed %o', err);\n scheduleReconnect();\n }\n }\n\n connect();\n\n return {\n /**\n * Send a request and await its correlated reply payload.\n *\n * @param {MessageType} type\n * @param {unknown} [payload]\n * @returns {Promise<any>}\n */\n send(type, payload) {\n if (!MESSAGE_TYPES.includes(type)) {\n return Promise.reject(new Error(`unknown message type: ${type}`));\n }\n const id = nextId();\n const req = makeRequest(type, payload, id);\n log('send %s id=%s', type, id);\n return new Promise((resolve, reject) => {\n pending.set(id, { resolve, reject, type });\n if (ws && ws.readyState === ws.OPEN) {\n sendRaw(req);\n } else {\n log('queue %s id=%s (state=%s)', type, id, state);\n queue.push(req);\n }\n });\n },\n /**\n * Register a handler for a server-initiated event type.\n * Returns an unsubscribe function.\n *\n * @param {MessageType} type\n * @param {(payload: any) => void} handler\n * @returns {() => void}\n */\n on(type, handler) {\n if (!handlers.has(type)) {\n handlers.set(type, new Set());\n }\n const set = handlers.get(type);\n set?.add(handler);\n return () => {\n set?.delete(handler);\n };\n },\n /**\n * Subscribe to connection state changes.\n *\n * @param {(state: ConnectionState) => void} handler\n * @returns {() => void}\n */\n onConnection(handler) {\n connection_handlers.add(handler);\n return () => {\n connection_handlers.delete(handler);\n };\n },\n /** Close and stop reconnecting. */\n close() {\n should_reconnect = false;\n if (reconnect_timer) {\n clearTimeout(reconnect_timer);\n reconnect_timer = null;\n }\n try {\n ws?.close();\n } catch {\n /* ignore */\n }\n },\n /** For diagnostics in tests or UI. */\n getState() {\n return state;\n }\n };\n}\n", "/**\n * @import { MessageType } from './protocol.js'\n */\nimport { html, render } from 'lit-html';\nimport { createListSelectors } from './data/list-selectors.js';\nimport { createDataLayer } from './data/providers.js';\nimport { createSubscriptionIssueStores } from './data/subscription-issue-stores.js';\nimport { createSubscriptionStore } from './data/subscriptions-store.js';\nimport { createHashRouter, parseHash, parseView } from './router.js';\nimport { createStore } from './state.js';\nimport { createActivityIndicator } from './utils/activity-indicator.js';\nimport { debug } from './utils/logging.js';\nimport { showToast } from './utils/toast.js';\nimport { createBoardView } from './views/board.js';\nimport { createDetailView } from './views/detail.js';\nimport { createEpicsView } from './views/epics.js';\nimport { createFatalErrorDialog } from './views/fatal-error-dialog.js';\nimport { createIssueDialog } from './views/issue-dialog.js';\nimport { createListView } from './views/list.js';\nimport { createTopNav } from './views/nav.js';\nimport { createNewIssueDialog } from './views/new-issue-dialog.js';\nimport { createWorkspacePicker } from './views/workspace-picker.js';\nimport { createWsClient } from './ws.js';\n\n/**\n * Bootstrap the SPA shell with two panels.\n *\n * @param {HTMLElement} root_element - The container element to render into.\n */\nexport function bootstrap(root_element) {\n const log = debug('main');\n log('bootstrap start');\n\n // Render route shells (nav is mounted in header)\n const shell = html`\n <section id=\"issues-root\" class=\"route issues\">\n <aside id=\"list-panel\" class=\"panel\"></aside>\n </section>\n <section id=\"epics-root\" class=\"route epics\" hidden></section>\n <section id=\"board-root\" class=\"route board\" hidden></section>\n <section id=\"detail-panel\" class=\"route detail\" hidden></section>\n `;\n render(shell, root_element);\n\n /** @type {HTMLElement|null} */\n const nav_mount = document.getElementById('top-nav');\n /** @type {HTMLElement|null} */\n const issues_root = document.getElementById('issues-root');\n /** @type {HTMLElement|null} */\n const epics_root = document.getElementById('epics-root');\n /** @type {HTMLElement|null} */\n const board_root = document.getElementById('board-root');\n\n /** @type {HTMLElement|null} */\n const list_mount = document.getElementById('list-panel');\n /** @type {HTMLElement|null} */\n const detail_mount = document.getElementById('detail-panel');\n if (list_mount && issues_root && epics_root && board_root && detail_mount) {\n /** @type {HTMLElement|null} */\n const header_loading = document.getElementById('header-loading');\n const activity = createActivityIndicator(header_loading);\n const fatal_dialog = createFatalErrorDialog(root_element);\n\n /**\n * Show a blocking dialog when a backend command fails.\n *\n * @param {unknown} err\n * @param {string} context\n */\n function showFatalFromError(err, context) {\n /** @type {string} */\n let message = 'Request failed';\n /** @type {string} */\n let detail = '';\n\n if (err && typeof err === 'object') {\n const any = /** @type {{ message?: unknown, details?: unknown }} */ (\n err\n );\n if (typeof any.message === 'string' && any.message.length > 0) {\n message = any.message;\n }\n if (typeof any.details === 'string') {\n detail = any.details;\n } else if (any.details && typeof any.details === 'object') {\n try {\n detail = JSON.stringify(any.details, null, 2);\n } catch {\n detail = '';\n }\n }\n } else if (typeof err === 'string' && err.length > 0) {\n message = err;\n }\n\n const title =\n context && context.length > 0\n ? `Failed to load ${context}`\n : 'Request failed';\n\n fatal_dialog.open(title, message, detail);\n }\n\n const client = createWsClient();\n const tracked_send = activity.wrapSend((type, payload) =>\n client.send(type, payload)\n );\n // Subscriptions: wire client events and expose subscribe/unsubscribe helpers\n const subscriptions = createSubscriptionStore(tracked_send);\n // Per-subscription stores (source of truth)\n const sub_issue_stores = createSubscriptionIssueStores();\n // Route per-subscription push envelopes to the owning store\n client.on('snapshot', (payload) => {\n const p = /** @type {any} */ (payload);\n const id = p && typeof p.id === 'string' ? p.id : '';\n const store = id ? sub_issue_stores.getStore(id) : null;\n if (store && p && p.type === 'snapshot') {\n try {\n store.applyPush(p);\n } catch {\n // ignore\n }\n }\n });\n client.on('upsert', (payload) => {\n const p = /** @type {any} */ (payload);\n const id = p && typeof p.id === 'string' ? p.id : '';\n const store = id ? sub_issue_stores.getStore(id) : null;\n if (store && p && p.type === 'upsert') {\n try {\n store.applyPush(p);\n } catch {\n // ignore\n }\n }\n });\n client.on('delete', (payload) => {\n const p = /** @type {any} */ (payload);\n const id = p && typeof p.id === 'string' ? p.id : '';\n const store = id ? sub_issue_stores.getStore(id) : null;\n if (store && p && p.type === 'delete') {\n try {\n store.applyPush(p);\n } catch {\n // ignore\n }\n }\n });\n // Derived list selectors: render from per-subscription snapshots\n const listSelectors = createListSelectors(sub_issue_stores);\n\n // --- Workspace management ---\n /**\n * Clear all subscriptions and stores, then re-establish them.\n * Called when switching workspaces.\n */\n async function clearAndResubscribe() {\n log('clearing all subscriptions for workspace switch');\n // Unsubscribe from server-side subscriptions first\n if (unsub_issues_tab) {\n void unsub_issues_tab().catch(() => {});\n unsub_issues_tab = null;\n }\n if (unsub_epics_tab) {\n void unsub_epics_tab().catch(() => {});\n unsub_epics_tab = null;\n }\n if (unsub_board_ready) {\n void unsub_board_ready().catch(() => {});\n unsub_board_ready = null;\n }\n if (unsub_board_in_progress) {\n void unsub_board_in_progress().catch(() => {});\n unsub_board_in_progress = null;\n }\n if (unsub_board_closed) {\n void unsub_board_closed().catch(() => {});\n unsub_board_closed = null;\n }\n if (unsub_board_blocked) {\n void unsub_board_blocked().catch(() => {});\n unsub_board_blocked = null;\n }\n // Clear all subscription stores\n const storeIds = [\n 'tab:issues',\n 'tab:epics',\n 'tab:board:ready',\n 'tab:board:in-progress',\n 'tab:board:closed',\n 'tab:board:blocked'\n ];\n for (const id of storeIds) {\n try {\n sub_issue_stores.unregister(id);\n } catch {\n // ignore\n }\n }\n // Also clear any detail stores\n const s = store.getState();\n if (s.selected_id) {\n try {\n sub_issue_stores.unregister(`detail:${s.selected_id}`);\n } catch {\n // ignore\n }\n }\n // Force re-subscribe by resetting last spec key\n last_issues_spec_key = null;\n // Re-establish subscriptions for current view\n ensureTabSubscriptions(store.getState());\n }\n\n /**\n * Handle workspace change request from the picker.\n *\n * @param {string} workspace_path\n */\n async function handleWorkspaceChange(workspace_path) {\n log('requesting workspace switch to %s', workspace_path);\n try {\n const result = await client.send('set-workspace', {\n path: workspace_path\n });\n log('workspace switch result: %o', result);\n if (result && result.workspace) {\n // Update state with new workspace\n store.setState({\n workspace: {\n current: {\n path: result.workspace.root_dir,\n database: result.workspace.db_path\n }\n }\n });\n // Persist preference\n window.localStorage.setItem('beads-ui.workspace', workspace_path);\n // Clear and resubscribe if workspace actually changed\n if (result.changed) {\n await clearAndResubscribe();\n showToast(\n 'Switched to ' + getProjectName(workspace_path),\n 'success',\n 2000\n );\n }\n }\n } catch (err) {\n log('workspace switch failed: %o', err);\n showToast('Failed to switch workspace', 'error', 3000);\n throw err;\n }\n }\n\n /**\n * Extract project name from path.\n *\n * @param {string} path\n * @returns {string}\n */\n function getProjectName(path) {\n if (!path) return 'Unknown';\n const parts = path.split('/').filter(Boolean);\n return parts.length > 0 ? parts[parts.length - 1] : 'Unknown';\n }\n\n /**\n * Load available workspaces from server and update state.\n */\n async function loadWorkspaces() {\n try {\n const result = await client.send('list-workspaces', {});\n log('workspaces loaded: %o', result);\n if (result && Array.isArray(result.workspaces)) {\n const available = result.workspaces.map((/** @type {any} */ ws) => ({\n path: ws.path,\n database: ws.database,\n pid: ws.pid,\n version: ws.version\n }));\n const current = result.current\n ? {\n path: result.current.root_dir,\n database: result.current.db_path\n }\n : null;\n store.setState({ workspace: { current, available } });\n\n // Check if we have a saved preference that differs from current\n const savedWorkspace =\n window.localStorage.getItem('beads-ui.workspace');\n if (savedWorkspace && current && savedWorkspace !== current.path) {\n // Check if saved workspace is in available list\n const savedExists = available.some(\n (/** @type {{ path: string }} */ ws) => ws.path === savedWorkspace\n );\n if (savedExists) {\n log('restoring saved workspace preference: %s', savedWorkspace);\n await handleWorkspaceChange(savedWorkspace);\n }\n }\n }\n } catch (err) {\n log('failed to load workspaces: %o', err);\n }\n }\n\n // Handle workspace-changed events from server (e.g., if another client changes workspace)\n client.on('workspace-changed', (payload) => {\n log('workspace-changed event: %o', payload);\n if (payload && payload.root_dir) {\n store.setState({\n workspace: {\n current: {\n path: payload.root_dir,\n database: payload.db_path\n }\n }\n });\n // Reload workspaces to get fresh list\n void loadWorkspaces();\n // Clear and resubscribe\n void clearAndResubscribe();\n }\n });\n\n // --- End workspace management (mounting happens after store is created) ---\n\n // Show toasts for WebSocket connectivity changes\n /** @type {boolean} */\n let had_disconnect = false;\n if (typeof client.onConnection === 'function') {\n /** @type {(s: 'connecting'|'open'|'closed'|'reconnecting') => void} */\n const onConn = (s) => {\n log('ws state %s', s);\n if (s === 'reconnecting' || s === 'closed') {\n had_disconnect = true;\n showToast('Connection lost. Reconnecting\u2026', 'error', 4000);\n } else if (s === 'open' && had_disconnect) {\n had_disconnect = false;\n showToast('Reconnected', 'success', 2200);\n }\n };\n client.onConnection(onConn);\n }\n // Load persisted filters (status/search/type) from localStorage\n /** @type {{ status: 'all'|'open'|'in_progress'|'closed'|'ready', search: string, type: string }} */\n let persisted_filters = { status: 'all', search: '', type: '' };\n try {\n const raw = window.localStorage.getItem('beads-ui.filters');\n if (raw) {\n const obj = JSON.parse(raw);\n if (obj && typeof obj === 'object') {\n const ALLOWED = ['bug', 'feature', 'task', 'epic', 'chore'];\n let parsed_type = '';\n if (typeof obj.type === 'string' && ALLOWED.includes(obj.type)) {\n parsed_type = obj.type;\n } else if (Array.isArray(obj.types)) {\n // Backwards compatibility: pick first valid from previous array format\n let first_valid = '';\n for (const it of obj.types) {\n if (ALLOWED.includes(String(it))) {\n first_valid = /** @type {string} */ (it);\n break;\n }\n }\n parsed_type = first_valid;\n }\n persisted_filters = {\n status: ['all', 'open', 'in_progress', 'closed', 'ready'].includes(\n obj.status\n )\n ? obj.status\n : 'all',\n search: typeof obj.search === 'string' ? obj.search : '',\n type: parsed_type\n };\n }\n }\n } catch (err) {\n log('filters parse error: %o', err);\n }\n // Load last-view from storage\n /** @type {'issues'|'epics'|'board'} */\n let last_view = 'issues';\n try {\n const raw_view = window.localStorage.getItem('beads-ui.view');\n if (\n raw_view === 'issues' ||\n raw_view === 'epics' ||\n raw_view === 'board'\n ) {\n last_view = raw_view;\n }\n } catch (err) {\n log('view parse error: %o', err);\n }\n // Load board preferences\n /** @type {{ closed_filter: 'today'|'3'|'7' }} */\n let persistedBoard = { closed_filter: 'today' };\n try {\n const raw_board = window.localStorage.getItem('beads-ui.board');\n if (raw_board) {\n const obj = JSON.parse(raw_board);\n if (obj && typeof obj === 'object') {\n const cf = String(obj.closed_filter || 'today');\n if (cf === 'today' || cf === '3' || cf === '7') {\n persistedBoard.closed_filter = cf;\n }\n }\n }\n } catch (err) {\n log('board prefs parse error: %o', err);\n }\n\n const store = createStore({\n filters: persisted_filters,\n view: last_view,\n board: persistedBoard\n });\n const router = createHashRouter(store);\n router.start();\n /**\n * @param {string} type\n * @param {unknown} payload\n */\n const transport = async (type, payload) => {\n try {\n return await tracked_send(/** @type {MessageType} */ (type), payload);\n } catch {\n return [];\n }\n };\n // Top navigation (optional mount)\n if (nav_mount) {\n createTopNav(nav_mount, store, router);\n }\n\n // Workspace picker (mount now that store exists)\n const workspace_mount = document.getElementById('workspace-picker');\n if (workspace_mount) {\n createWorkspacePicker(workspace_mount, store, handleWorkspaceChange);\n }\n // Load workspaces after WebSocket is connected\n void loadWorkspaces();\n\n // Global New Issue dialog (UI-106) mounted at root so it is always visible\n const new_issue_dialog = createNewIssueDialog(\n root_element,\n (type, payload) => tracked_send(type, payload),\n router,\n store\n );\n // Header button\n try {\n const btn_new = /** @type {HTMLButtonElement|null} */ (\n document.getElementById('new-issue-btn')\n );\n if (btn_new) {\n btn_new.addEventListener('click', () => new_issue_dialog.open());\n }\n } catch {\n // ignore missing header\n }\n\n // Local transport shim: for list-issues, serve from local listSelectors;\n // otherwise forward to ws transport for mutations/show.\n /**\n * @param {MessageType} type\n * @param {unknown} payload\n */\n const listTransport = async (type, payload) => {\n if (type === 'list-issues') {\n try {\n return listSelectors.selectIssuesFor('tab:issues');\n } catch (err) {\n log('list selectors failed: %o', err);\n return [];\n }\n }\n return transport(type, payload);\n };\n\n const issues_view = createListView(\n list_mount,\n /** @type {any} */ (listTransport),\n (hash) => {\n const id = parseHash(hash);\n if (id) {\n router.gotoIssue(id);\n }\n },\n store,\n subscriptions,\n sub_issue_stores\n );\n // Persist filter changes to localStorage\n store.subscribe((s) => {\n const data = {\n status: s.filters.status,\n search: s.filters.search,\n type: typeof s.filters.type === 'string' ? s.filters.type : ''\n };\n window.localStorage.setItem('beads-ui.filters', JSON.stringify(data));\n });\n // Persist board preferences\n store.subscribe((s) => {\n window.localStorage.setItem(\n 'beads-ui.board',\n JSON.stringify({ closed_filter: s.board.closed_filter })\n );\n });\n void issues_view.load();\n\n // Dialog for issue details (UI-104)\n const dialog = createIssueDialog(detail_mount, store, () => {\n // Close: clear selection and return to current view\n const s = store.getState();\n store.setState({ selected_id: null });\n try {\n /** @type {'issues'|'epics'|'board'} */\n const v = s.view || 'issues';\n router.gotoView(v);\n } catch {\n // ignore\n }\n });\n\n /** @type {ReturnType<typeof createDetailView> | null} */\n let detail = null;\n // Mount details into the dialog body only\n detail = createDetailView(\n dialog.getMount(),\n transport,\n (hash) => {\n const id = parseHash(hash);\n if (id) {\n router.gotoIssue(id);\n } else {\n // No issue ID - navigate to view (closes dialog)\n const view = parseView(hash);\n router.gotoView(view);\n }\n },\n sub_issue_stores\n );\n\n // If router already set a selected id (deep-link), open dialog now\n const initial_id = store.getState().selected_id;\n if (initial_id) {\n detail_mount.hidden = false;\n dialog.open(initial_id);\n if (detail) {\n void detail.load(initial_id);\n }\n // Ensure detail subscription is active on initial deep-link\n const client_id = `detail:${initial_id}`;\n const spec = { type: 'issue-detail', params: { id: initial_id } };\n // Register store first to avoid dropping the initial snapshot\n try {\n sub_issue_stores.register(client_id, spec);\n } catch (err) {\n log('register detail store failed: %o', err);\n }\n void subscriptions.subscribeList(client_id, spec).catch((err) => {\n log('detail subscribe failed: %o', err);\n showFatalFromError(err, 'issue details');\n });\n }\n\n // Open/close dialog based on selected_id (always dialog; no page variant)\n /** @type {null | (() => Promise<void>)} */\n let unsub_detail = null;\n store.subscribe((s) => {\n const id = s.selected_id;\n if (id) {\n detail_mount.hidden = false;\n dialog.open(id);\n if (detail) {\n void detail.load(id);\n }\n // Wire per-issue subscription for detail\n const client_id = `detail:${id}`;\n const spec = { type: 'issue-detail', params: { id } };\n // Ensure per-subscription issue store exists before subscribing\n try {\n sub_issue_stores.register(client_id, spec);\n } catch {\n // ignore\n }\n // Subscribe server-side\n void subscriptions\n .subscribeList(client_id, spec)\n .then((unsub) => {\n // Unsubscribe previous if any\n if (unsub_detail) {\n void unsub_detail().catch(() => {});\n }\n unsub_detail = unsub;\n })\n .catch((err) => {\n log('detail subscribe failed: %o', err);\n showFatalFromError(err, 'issue details');\n });\n } else {\n try {\n dialog.close();\n } catch {\n // ignore\n }\n if (detail) {\n detail.clear();\n }\n detail_mount.hidden = true;\n if (unsub_detail) {\n void unsub_detail().catch(() => {});\n unsub_detail = null;\n }\n }\n });\n\n // Removed: issues-changed handling. All views re-render from\n // per-subscription stores which are updated by snapshot/upsert/delete.\n\n // Toggle route shells on view/detail change and persist\n const data = createDataLayer(transport);\n const epics_view = createEpicsView(\n epics_root,\n data,\n (id) => router.gotoIssue(id),\n subscriptions,\n sub_issue_stores\n );\n const board_view = createBoardView(\n board_root,\n data,\n (id) => router.gotoIssue(id),\n store,\n subscriptions,\n sub_issue_stores,\n transport\n );\n // Preload epics when switching to view\n /**\n * @param {{ selected_id: string | null, view: 'issues'|'epics'|'board', filters: any }} s\n */\n // --- Subscriptions: tab-level management and filter-driven updates ---\n /** @type {null | (() => Promise<void>)} */\n let unsub_issues_tab = null;\n /** @type {null | (() => Promise<void>)} */\n let unsub_epics_tab = null;\n /** @type {null | (() => Promise<void>)} */\n let unsub_board_ready = null;\n /** @type {null | (() => Promise<void>)} */\n let unsub_board_in_progress = null;\n /** @type {null | (() => Promise<void>)} */\n let unsub_board_closed = null;\n /** @type {null | (() => Promise<void>)} */\n let unsub_board_blocked = null;\n\n // Track in-flight subscriptions to prevent duplicates during rapid view switching\n /** @type {Set<string>} */\n const pending_subscriptions = new Set();\n\n // Expose activity debug info globally for diagnostics\n // @ts-ignore\n window.__bdui_debug = {\n getPendingSubscriptions: () => Array.from(pending_subscriptions),\n getActivityCount: () => activity.getCount(),\n getActiveRequests: () => activity.getActiveRequests()\n };\n\n /**\n * Compute subscription spec for Issues tab based on filters.\n *\n * @param {{ status?: string }} filters\n * @returns {{ type: string, params?: Record<string, string|number|boolean> }}\n */\n function computeIssuesSpec(filters) {\n const st = String(filters?.status || 'all');\n if (st === 'ready') {\n return { type: 'ready-issues' };\n }\n if (st === 'in_progress') {\n return { type: 'in-progress-issues' };\n }\n if (st === 'closed') {\n return { type: 'closed-issues' };\n }\n // \"all\" and \"open\" map to all-issues; client filters apply locally\n return { type: 'all-issues' };\n }\n\n /** @type {string|null} */\n let last_issues_spec_key = null;\n /**\n * Ensure only the active tab has subscriptions; clean up previous.\n *\n * @param {{ view: 'issues'|'epics'|'board', filters: any }} s\n */\n function ensureTabSubscriptions(s) {\n // Issues tab\n if (s.view === 'issues') {\n const spec = computeIssuesSpec(s.filters || {});\n const key = JSON.stringify(spec);\n // Register store first to capture the initial snapshot\n try {\n sub_issue_stores.register('tab:issues', spec);\n } catch (err) {\n log('register issues store failed: %o', err);\n }\n // Only (re)subscribe if not yet subscribed, spec changed, and not already in-flight\n const issues_sub_key = `tab:issues:${key}`;\n if (\n (!unsub_issues_tab || key !== last_issues_spec_key) &&\n !pending_subscriptions.has(issues_sub_key)\n ) {\n pending_subscriptions.add(issues_sub_key);\n void subscriptions\n .subscribeList('tab:issues', spec)\n .then((unsub) => {\n unsub_issues_tab = unsub;\n last_issues_spec_key = key;\n })\n .catch((err) => {\n log('subscribe issues failed: %o', err);\n showFatalFromError(err, 'issues list');\n })\n .finally(() => {\n pending_subscriptions.delete(issues_sub_key);\n });\n }\n } else if (unsub_issues_tab) {\n void unsub_issues_tab().catch(() => {});\n unsub_issues_tab = null;\n last_issues_spec_key = null;\n try {\n sub_issue_stores.unregister('tab:issues');\n } catch (err) {\n log('unregister issues store failed: %o', err);\n }\n }\n\n // Epics tab\n if (s.view === 'epics') {\n // Register store first to avoid race with initial snapshot\n try {\n sub_issue_stores.register('tab:epics', { type: 'epics' });\n } catch (err) {\n log('register epics store failed: %o', err);\n }\n // Only subscribe if not already subscribed and not in-flight\n if (!unsub_epics_tab && !pending_subscriptions.has('tab:epics')) {\n pending_subscriptions.add('tab:epics');\n void subscriptions\n .subscribeList('tab:epics', { type: 'epics' })\n .then((unsub) => {\n unsub_epics_tab = unsub;\n })\n .catch((err) => {\n log('subscribe epics failed: %o', err);\n showFatalFromError(err, 'epics');\n })\n .finally(() => {\n pending_subscriptions.delete('tab:epics');\n });\n }\n } else if (unsub_epics_tab) {\n void unsub_epics_tab().catch(() => {});\n unsub_epics_tab = null;\n try {\n sub_issue_stores.unregister('tab:epics');\n } catch (err) {\n log('unregister epics store failed: %o', err);\n }\n }\n\n // Board tab subscribes to lists used by columns\n if (s.view === 'board') {\n // Ready column\n if (\n !unsub_board_ready &&\n !pending_subscriptions.has('tab:board:ready')\n ) {\n try {\n sub_issue_stores.register('tab:board:ready', {\n type: 'ready-issues'\n });\n } catch (err) {\n log('register board:ready store failed: %o', err);\n }\n pending_subscriptions.add('tab:board:ready');\n void subscriptions\n .subscribeList('tab:board:ready', { type: 'ready-issues' })\n .then((u) => (unsub_board_ready = u))\n .catch((err) => {\n log('subscribe board ready failed: %o', err);\n showFatalFromError(err, 'board (Ready)');\n })\n .finally(() => {\n pending_subscriptions.delete('tab:board:ready');\n });\n }\n // In Progress column\n if (\n !unsub_board_in_progress &&\n !pending_subscriptions.has('tab:board:in-progress')\n ) {\n try {\n sub_issue_stores.register('tab:board:in-progress', {\n type: 'in-progress-issues'\n });\n } catch (err) {\n log('register board:in-progress store failed: %o', err);\n }\n pending_subscriptions.add('tab:board:in-progress');\n void subscriptions\n .subscribeList('tab:board:in-progress', {\n type: 'in-progress-issues'\n })\n .then((u) => (unsub_board_in_progress = u))\n .catch((err) => {\n log('subscribe board in-progress failed: %o', err);\n showFatalFromError(err, 'board (In Progress)');\n })\n .finally(() => {\n pending_subscriptions.delete('tab:board:in-progress');\n });\n }\n // Closed column\n if (\n !unsub_board_closed &&\n !pending_subscriptions.has('tab:board:closed')\n ) {\n try {\n sub_issue_stores.register('tab:board:closed', {\n type: 'closed-issues'\n });\n } catch (err) {\n log('register board:closed store failed: %o', err);\n }\n pending_subscriptions.add('tab:board:closed');\n void subscriptions\n .subscribeList('tab:board:closed', { type: 'closed-issues' })\n .then((u) => (unsub_board_closed = u))\n .catch((err) => {\n log('subscribe board closed failed: %o', err);\n showFatalFromError(err, 'board (Closed)');\n })\n .finally(() => {\n pending_subscriptions.delete('tab:board:closed');\n });\n }\n // Blocked column\n if (\n !unsub_board_blocked &&\n !pending_subscriptions.has('tab:board:blocked')\n ) {\n try {\n sub_issue_stores.register('tab:board:blocked', {\n type: 'blocked-issues'\n });\n } catch (err) {\n log('register board:blocked store failed: %o', err);\n }\n pending_subscriptions.add('tab:board:blocked');\n void subscriptions\n .subscribeList('tab:board:blocked', { type: 'blocked-issues' })\n .then((u) => (unsub_board_blocked = u))\n .catch((err) => {\n log('subscribe board blocked failed: %o', err);\n showFatalFromError(err, 'board (Blocked)');\n })\n .finally(() => {\n pending_subscriptions.delete('tab:board:blocked');\n });\n }\n } else {\n // Unsubscribe all board lists when leaving the board view\n if (unsub_board_ready) {\n void unsub_board_ready().catch(() => {});\n unsub_board_ready = null;\n try {\n sub_issue_stores.unregister('tab:board:ready');\n } catch (err) {\n log('unregister board:ready failed: %o', err);\n }\n }\n if (unsub_board_in_progress) {\n void unsub_board_in_progress().catch(() => {});\n unsub_board_in_progress = null;\n try {\n sub_issue_stores.unregister('tab:board:in-progress');\n } catch (err) {\n log('unregister board:in-progress failed: %o', err);\n }\n }\n if (unsub_board_closed) {\n void unsub_board_closed().catch(() => {});\n unsub_board_closed = null;\n try {\n sub_issue_stores.unregister('tab:board:closed');\n } catch (err) {\n log('unregister board:closed failed: %o', err);\n }\n }\n if (unsub_board_blocked) {\n void unsub_board_blocked().catch(() => {});\n unsub_board_blocked = null;\n try {\n sub_issue_stores.unregister('tab:board:blocked');\n } catch (err) {\n log('unregister board:blocked failed: %o', err);\n }\n }\n }\n }\n\n /**\n * Manage route visibility and list subscriptions per view.\n *\n * @param {{ selected_id: string | null, view: 'issues'|'epics'|'board', filters: any }} s\n */\n const onRouteChange = (s) => {\n if (issues_root && epics_root && board_root && detail_mount) {\n // Underlying route visibility is controlled only by selected view\n issues_root.hidden = s.view !== 'issues';\n epics_root.hidden = s.view !== 'epics';\n board_root.hidden = s.view !== 'board';\n // detail_mount visibility handled in subscription above\n }\n // Ensure subscriptions for the active tab before loading the view to\n // avoid empty initial renders due to racing list-delta.\n ensureTabSubscriptions(s);\n if (!s.selected_id && s.view === 'epics') {\n void epics_view.load();\n }\n if (!s.selected_id && s.view === 'board') {\n void board_view.load();\n }\n window.localStorage.setItem('beads-ui.view', s.view);\n };\n store.subscribe(onRouteChange);\n // Ensure initial state is reflected (fixes reload on #/epics)\n onRouteChange(store.getState());\n\n // Removed redundant filter-change subscription: handled by ensureTabSubscriptions\n\n // Keyboard shortcuts: Ctrl/Cmd+N opens new issue; Ctrl/Cmd+Enter submits inside dialog\n window.addEventListener('keydown', (ev) => {\n const is_modifier = ev.ctrlKey || ev.metaKey;\n const key = String(ev.key || '').toLowerCase();\n const target = /** @type {HTMLElement} */ (ev.target);\n const tag =\n target && target.tagName ? String(target.tagName).toLowerCase() : '';\n const is_editable =\n tag === 'input' ||\n tag === 'textarea' ||\n tag === 'select' ||\n (target &&\n typeof target.isContentEditable === 'boolean' &&\n target.isContentEditable);\n if (is_modifier && key === 'n') {\n // Do not hijack when typing in inputs; common UX\n if (!is_editable) {\n ev.preventDefault();\n new_issue_dialog.open();\n }\n }\n });\n }\n}\n\nif (typeof window !== 'undefined' && typeof document !== 'undefined') {\n window.addEventListener('DOMContentLoaded', () => {\n // Initialize theme from saved preference or OS preference\n try {\n const saved = window.localStorage.getItem('beads-ui.theme');\n const prefersDark =\n window.matchMedia &&\n window.matchMedia('(prefers-color-scheme: dark)').matches;\n const initial =\n saved === 'dark' || saved === 'light'\n ? saved\n : prefersDark\n ? 'dark'\n : 'light';\n document.documentElement.setAttribute('data-theme', initial);\n const sw = /** @type {HTMLInputElement|null} */ (\n document.getElementById('theme-switch')\n );\n if (sw) {\n sw.checked = initial === 'dark';\n }\n } catch {\n // ignore theme init errors\n }\n\n // Wire up theme switch in header\n const themeSwitch = /** @type {HTMLInputElement|null} */ (\n document.getElementById('theme-switch')\n );\n if (themeSwitch) {\n themeSwitch.addEventListener('change', () => {\n const mode = themeSwitch.checked ? 'dark' : 'light';\n document.documentElement.setAttribute('data-theme', mode);\n window.localStorage.setItem('beads-ui.theme', mode);\n });\n }\n\n /** @type {HTMLElement|null} */\n const app_root = document.getEl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ACA,OACA,SACA,OACA,KACA,KACA,KACA,KACA,KACA,KACA,OACA,SACA,SACA,KACA,OACA,IACA,MACA,QACA,MACA,MACA,QACA,SACA,KACA,OACA,MACA,OACA,UACA,OACA,WACA,QACA,MACA,OACA,KACA,WACA,SACA,SACA,IACA,UACA,MACA,WACA,IACA,KACA,KACA,OACA,IACA,OACA,SACA,UACA,SACA,SACA,OACA,QACA,SACA,SACA,OACA,SACA,SACA,QACA,MACA,UACA,MACA,QACA,QACA,KACA,WACA,WACA,QACA,KACA,QACA,OACA,KACA,QACA,KACA,IACA,KACA,MACA,QACA,KAAK,CACG,EAEG8E,GAAM9E,GAAO,CACxB,MACA,IACA,WACA,cACA,eACA,eACA,gBACA,mBACA,SACA,WACA,OACA,OACA,UACA,eACA,cACA,SACA,OACA,IACA,QACA,WACA,QACA,QACA,YACA,OACA,iBACA,SACA,OACA,WACA,QACA,OACA,OACA,UACA,UACA,WACA,iBACA,OACA,OACA,QACA,SACA,SACA,OACA,WACA,QACA,OACA,QACA,OACA,OAAO,CACC,EAEG+E,GAAa/E,GAAO,CAC/B,UACA,gBACA,sBACA,cACA,mBACA,oBACA,oBACA,iBACA,eACA,UACA,UACA,UACA,UACA,UACA,iBACA,UACA,UACA,cACA,eACA,WACA,eACA,qBACA,cACA,SACA,cAAc,CACN,EAMGgF,GAAgBhF,GAAO,CAClC,UACA,gBACA,SACA,UACA,YACA,mBACA,iBACA,gBACA,gBACA,gBACA,QACA,YACA,OACA,eACA,YACA,UACA,gBACA,SACA,MACA,aACA,UACA,KAAK,CACG,EAEGiF,GAASjF,GAAO,CAC3B,OACA,WACA,SACA,UACA,QACA,SACA,KACA,aACA,gBACA,KACA,KACA,QACA,UACA,WACA,QACA,OACA,KACA,SACA,QACA,SACA,OACA,OACA,UACA,SACA,MACA,QACA,MACA,SACA,aACA,aAAa,CACL,EAIGkF,GAAmBlF,GAAO,CACrC,UACA,cACA,aACA,WACA,YACA,UACA,UACA,SACA,SACA,QACA,YACA,aACA,iBACA,cACA,MAAM,CACE,EAEGmF,GAAOnF,GAAO,CAAC,OAAO,CAAU,EC1RhC6E,GAAO7E,GAAO,CACzB,SACA,SACA,QACA,MACA,iBACA,eACA,uBACA,WACA,aACA,UACA,SACA,UACA,cACA,cACA,UACA,OACA,QACA,QACA,QACA,OACA,UACA,WACA,eACA,SACA,cACA,WACA,WACA,UACA,MACA,WACA,0BACA,wBACA,WACA,YACA,UACA,eACA,cACA,OACA,MACA,UACA,SACA,SACA,OACA,OACA,WACA,KACA,QACA,YACA,YACA,QACA,OACA,QACA,OACA,OACA,UACA,OACA,MACA,MACA,YACA,QACA,SACA,MACA,YACA,WACA,QACA,OACA,QACA,UACA,aACA,SACA,OACA,UACA,OACA,UACA,cACA,cACA,UACA,gBACA,sBACA,SACA,UACA,UACA,aACA,WACA,MACA,WACA,MACA,WACA,OACA,OACA,UACA,aACA,QACA,WACA,QACA,OACA,QACA,OACA,OACA,UACA,QACA,MACA,SACA,OACA,QACA,UACA,WACA,QACA,YACA,OACA,SACA,SACA,QACA,QACA,OACA,QACA,MAAM,CACE,EAEG8E,GAAM9E,GAAO,CACxB,gBACA,aACA,WACA,qBACA,YACA,SACA,gBACA,gBACA,UACA,gBACA,iBACA,QACA,OACA,KACA,QACA,OACA,gBACA,YACA,YACA,QACA,sBACA,8BACA,gBACA,kBACA,KACA,KACA,IACA,KACA,KACA,kBACA,YACA,UACA,UACA,MACA,WACA,YACA,MACA,WACA,OACA,eACA,YACA,SACA,cACA,cACA,gBACA,cACA,YACA,mBACA,eACA,aACA,eACA,cACA,KACA,KACA,KACA,KACA,aACA,WACA,gBACA,oBACA,SACA,OACA,KACA,kBACA,KACA,MACA,YACA,IACA,KACA,KACA,KACA,KACA,UACA,YACA,aACA,WACA,OACA,eACA,iBACA,eACA,mBACA,iBACA,QACA,aACA,aACA,eACA,eACA,cACA,cACA,mBACA,YACA,MACA,OACA,YACA,QACA,SACA,OACA,MACA,OACA,aACA,SACA,WACA,UACA,QACA,SACA,cACA,SACA,WACA,cACA,OACA,aACA,sBACA,mBACA,eACA,SACA,gBACA,sBACA,iBACA,IACA,KACA,KACA,SACA,OACA,OACA,cACA,YACA,UACA,SACA,SACA,QACA,OACA,kBACA,QACA,mBACA,mBACA,eACA,cACA,eACA,cACA,aACA,eACA,mBACA,oBACA,iBACA,kBACA,oBACA,iBACA,SACA,eACA,QACA,eACA,iBACA,WACA,cACA,UACA,UACA,YACA,mBACA,cACA,kBACA,iBACA,aACA,OACA,KACA,KACA,UACA,SACA,UACA,aACA,UACA,aACA,gBACA,gBACA,QACA,eACA,OACA,eACA,mBACA,mBACA,IACA,KACA,KACA,QACA,IACA,KACA,KACA,IACA,YAAY,CACJ,EAEGiF,GAASjF,GAAO,CAC3B,SACA,cACA,QACA,WACA,QACA,eACA,cACA,aACA,aACA,QACA,MACA,UACA,eACA,WACA,QACA,QACA,SACA,OACA,KACA,UACA,SACA,gBACA,SACA,SACA,iBACA,YACA,WACA,cACA,UACA,UACA,gBACA,WACA,WACA,OACA,WACA,WACA,aACA,UACA,SACA,SACA,cACA,gBACA,uBACA,YACA,YACA,aACA,WACA,iBACA,iBACA,YACA,UACA,QACA,OAAO,CACR,EAEYoF,GAAMpF,GAAO,CACxB,aACA,SACA,cACA,YACA,aAAa,CACL,ECpXGqF,GAAgBpF,GAAK,2BAA2B,EAChDqF,GAAWrF,GAAK,uBAAuB,EACvCsF,GAActF,GAAK,eAAe,EAClCuF,GAAYvF,GAAK,8BAA8B,EAC/CwF,GAAYxF,GAAK,gBAAgB,EACjCyF,GAAiBzF,GAC5B,oGAEW0F,GAAoB1F,GAAK,uBAAuB,EAChD2F,GAAkB3F,GAC7B,+DAEW4F,GAAe5F,GAAK,SAAS,EAC7B6F,GAAiB7F,GAAK,0BAA0B,uMCmBvD8F,GAAY,CAChBlC,QAAS,EACTmC,UAAW,EACXb,KAAM,EACNc,aAAc,EACdC,gBAAiB,EACjBC,WAAY,EACZC,uBAAwB,EACxBC,QAAS,EACTC,SAAU,EACVC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AAO,aAAa,QAAQ,gBAAgB,EACpDC,EACJ,OAAO,YACP,OAAO,WAAW,8BAA8B,EAAE,QAC9CC,EACJF,IAAU,QAAUA,IAAU,QAC1BA,EACAC,EACE,OACA,QACR,SAAS,gBAAgB,aAAa,aAAcC,CAAO,EAC3D,IAAMC,EACJ,SAAS,eAAe,cAAc,EAEpCA,IACFA,EAAG,QAAUD,IAAY,OAE7B,MAAQ,CAER,CAGA,IAAME,EACJ,SAAS,eAAe,cAAc,EAEpCA,GACFA,EAAY,iBAAiB,SAAU,IAAM,CAC3C,IAAMC,EAAOD,EAAY,QAAU,OAAS,QAC5C,SAAS,gBAAgB,aAAa,aAAcC,CAAI,EACxD,OAAO,aAAa,QAAQ,iBAAkBA,CAAI,CACpD,CAAC,EAIH,IAAMC,EAAW,SAAS,eAAe,KAAK,EAC1CA,GACF9H,GAAU8H,CAAQ,CAEtB,CAAC",
|
|
4
|
+
"sourcesContent": ["/**\n * Helpers.\n */\n\nvar s = 1000;\nvar m = s * 60;\nvar h = m * 60;\nvar d = h * 24;\nvar w = d * 7;\nvar y = d * 365.25;\n\n/**\n * Parse or format the given `val`.\n *\n * Options:\n *\n * - `long` verbose formatting [false]\n *\n * @param {String|Number} val\n * @param {Object} [options]\n * @throws {Error} throw an error if val is not a non-empty string or a number\n * @return {String|Number}\n * @api public\n */\n\nmodule.exports = function (val, options) {\n options = options || {};\n var type = typeof val;\n if (type === 'string' && val.length > 0) {\n return parse(val);\n } else if (type === 'number' && isFinite(val)) {\n return options.long ? fmtLong(val) : fmtShort(val);\n }\n throw new Error(\n 'val is not a non-empty string or a valid number. val=' +\n JSON.stringify(val)\n );\n};\n\n/**\n * Parse the given `str` and return milliseconds.\n *\n * @param {String} str\n * @return {Number}\n * @api private\n */\n\nfunction parse(str) {\n str = String(str);\n if (str.length > 100) {\n return;\n }\n var match = /^(-?(?:\\d+)?\\.?\\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(\n str\n );\n if (!match) {\n return;\n }\n var n = parseFloat(match[1]);\n var type = (match[2] || 'ms').toLowerCase();\n switch (type) {\n case 'years':\n case 'year':\n case 'yrs':\n case 'yr':\n case 'y':\n return n * y;\n case 'weeks':\n case 'week':\n case 'w':\n return n * w;\n case 'days':\n case 'day':\n case 'd':\n return n * d;\n case 'hours':\n case 'hour':\n case 'hrs':\n case 'hr':\n case 'h':\n return n * h;\n case 'minutes':\n case 'minute':\n case 'mins':\n case 'min':\n case 'm':\n return n * m;\n case 'seconds':\n case 'second':\n case 'secs':\n case 'sec':\n case 's':\n return n * s;\n case 'milliseconds':\n case 'millisecond':\n case 'msecs':\n case 'msec':\n case 'ms':\n return n;\n default:\n return undefined;\n }\n}\n\n/**\n * Short format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtShort(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return Math.round(ms / d) + 'd';\n }\n if (msAbs >= h) {\n return Math.round(ms / h) + 'h';\n }\n if (msAbs >= m) {\n return Math.round(ms / m) + 'm';\n }\n if (msAbs >= s) {\n return Math.round(ms / s) + 's';\n }\n return ms + 'ms';\n}\n\n/**\n * Long format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtLong(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return plural(ms, msAbs, d, 'day');\n }\n if (msAbs >= h) {\n return plural(ms, msAbs, h, 'hour');\n }\n if (msAbs >= m) {\n return plural(ms, msAbs, m, 'minute');\n }\n if (msAbs >= s) {\n return plural(ms, msAbs, s, 'second');\n }\n return ms + ' ms';\n}\n\n/**\n * Pluralization helper.\n */\n\nfunction plural(ms, msAbs, n, name) {\n var isPlural = msAbs >= n * 1.5;\n return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');\n}\n", "\n/**\n * This is the common logic for both the Node.js and web browser\n * implementations of `debug()`.\n */\n\nfunction setup(env) {\n\tcreateDebug.debug = createDebug;\n\tcreateDebug.default = createDebug;\n\tcreateDebug.coerce = coerce;\n\tcreateDebug.disable = disable;\n\tcreateDebug.enable = enable;\n\tcreateDebug.enabled = enabled;\n\tcreateDebug.humanize = require('ms');\n\tcreateDebug.destroy = destroy;\n\n\tObject.keys(env).forEach(key => {\n\t\tcreateDebug[key] = env[key];\n\t});\n\n\t/**\n\t* The currently active debug mode names, and names to skip.\n\t*/\n\n\tcreateDebug.names = [];\n\tcreateDebug.skips = [];\n\n\t/**\n\t* Map of special \"%n\" handling functions, for the debug \"format\" argument.\n\t*\n\t* Valid key names are a single, lower or upper-case letter, i.e. \"n\" and \"N\".\n\t*/\n\tcreateDebug.formatters = {};\n\n\t/**\n\t* Selects a color for a debug namespace\n\t* @param {String} namespace The namespace string for the debug instance to be colored\n\t* @return {Number|String} An ANSI color code for the given namespace\n\t* @api private\n\t*/\n\tfunction selectColor(namespace) {\n\t\tlet hash = 0;\n\n\t\tfor (let i = 0; i < namespace.length; i++) {\n\t\t\thash = ((hash << 5) - hash) + namespace.charCodeAt(i);\n\t\t\thash |= 0; // Convert to 32bit integer\n\t\t}\n\n\t\treturn createDebug.colors[Math.abs(hash) % createDebug.colors.length];\n\t}\n\tcreateDebug.selectColor = selectColor;\n\n\t/**\n\t* Create a debugger with the given `namespace`.\n\t*\n\t* @param {String} namespace\n\t* @return {Function}\n\t* @api public\n\t*/\n\tfunction createDebug(namespace) {\n\t\tlet prevTime;\n\t\tlet enableOverride = null;\n\t\tlet namespacesCache;\n\t\tlet enabledCache;\n\n\t\tfunction debug(...args) {\n\t\t\t// Disabled?\n\t\t\tif (!debug.enabled) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst self = debug;\n\n\t\t\t// Set `diff` timestamp\n\t\t\tconst curr = Number(new Date());\n\t\t\tconst ms = curr - (prevTime || curr);\n\t\t\tself.diff = ms;\n\t\t\tself.prev = prevTime;\n\t\t\tself.curr = curr;\n\t\t\tprevTime = curr;\n\n\t\t\targs[0] = createDebug.coerce(args[0]);\n\n\t\t\tif (typeof args[0] !== 'string') {\n\t\t\t\t// Anything else let's inspect with %O\n\t\t\t\targs.unshift('%O');\n\t\t\t}\n\n\t\t\t// Apply any `formatters` transformations\n\t\t\tlet index = 0;\n\t\t\targs[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {\n\t\t\t\t// If we encounter an escaped % then don't increase the array index\n\t\t\t\tif (match === '%%') {\n\t\t\t\t\treturn '%';\n\t\t\t\t}\n\t\t\t\tindex++;\n\t\t\t\tconst formatter = createDebug.formatters[format];\n\t\t\t\tif (typeof formatter === 'function') {\n\t\t\t\t\tconst val = args[index];\n\t\t\t\t\tmatch = formatter.call(self, val);\n\n\t\t\t\t\t// Now we need to remove `args[index]` since it's inlined in the `format`\n\t\t\t\t\targs.splice(index, 1);\n\t\t\t\t\tindex--;\n\t\t\t\t}\n\t\t\t\treturn match;\n\t\t\t});\n\n\t\t\t// Apply env-specific formatting (colors, etc.)\n\t\t\tcreateDebug.formatArgs.call(self, args);\n\n\t\t\tconst logFn = self.log || createDebug.log;\n\t\t\tlogFn.apply(self, args);\n\t\t}\n\n\t\tdebug.namespace = namespace;\n\t\tdebug.useColors = createDebug.useColors();\n\t\tdebug.color = createDebug.selectColor(namespace);\n\t\tdebug.extend = extend;\n\t\tdebug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.\n\n\t\tObject.defineProperty(debug, 'enabled', {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: false,\n\t\t\tget: () => {\n\t\t\t\tif (enableOverride !== null) {\n\t\t\t\t\treturn enableOverride;\n\t\t\t\t}\n\t\t\t\tif (namespacesCache !== createDebug.namespaces) {\n\t\t\t\t\tnamespacesCache = createDebug.namespaces;\n\t\t\t\t\tenabledCache = createDebug.enabled(namespace);\n\t\t\t\t}\n\n\t\t\t\treturn enabledCache;\n\t\t\t},\n\t\t\tset: v => {\n\t\t\t\tenableOverride = v;\n\t\t\t}\n\t\t});\n\n\t\t// Env-specific initialization logic for debug instances\n\t\tif (typeof createDebug.init === 'function') {\n\t\t\tcreateDebug.init(debug);\n\t\t}\n\n\t\treturn debug;\n\t}\n\n\tfunction extend(namespace, delimiter) {\n\t\tconst newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);\n\t\tnewDebug.log = this.log;\n\t\treturn newDebug;\n\t}\n\n\t/**\n\t* Enables a debug mode by namespaces. This can include modes\n\t* separated by a colon and wildcards.\n\t*\n\t* @param {String} namespaces\n\t* @api public\n\t*/\n\tfunction enable(namespaces) {\n\t\tcreateDebug.save(namespaces);\n\t\tcreateDebug.namespaces = namespaces;\n\n\t\tcreateDebug.names = [];\n\t\tcreateDebug.skips = [];\n\n\t\tconst split = (typeof namespaces === 'string' ? namespaces : '')\n\t\t\t.trim()\n\t\t\t.replace(/\\s+/g, ',')\n\t\t\t.split(',')\n\t\t\t.filter(Boolean);\n\n\t\tfor (const ns of split) {\n\t\t\tif (ns[0] === '-') {\n\t\t\t\tcreateDebug.skips.push(ns.slice(1));\n\t\t\t} else {\n\t\t\t\tcreateDebug.names.push(ns);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Checks if the given string matches a namespace template, honoring\n\t * asterisks as wildcards.\n\t *\n\t * @param {String} search\n\t * @param {String} template\n\t * @return {Boolean}\n\t */\n\tfunction matchesTemplate(search, template) {\n\t\tlet searchIndex = 0;\n\t\tlet templateIndex = 0;\n\t\tlet starIndex = -1;\n\t\tlet matchIndex = 0;\n\n\t\twhile (searchIndex < search.length) {\n\t\t\tif (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === '*')) {\n\t\t\t\t// Match character or proceed with wildcard\n\t\t\t\tif (template[templateIndex] === '*') {\n\t\t\t\t\tstarIndex = templateIndex;\n\t\t\t\t\tmatchIndex = searchIndex;\n\t\t\t\t\ttemplateIndex++; // Skip the '*'\n\t\t\t\t} else {\n\t\t\t\t\tsearchIndex++;\n\t\t\t\t\ttemplateIndex++;\n\t\t\t\t}\n\t\t\t} else if (starIndex !== -1) { // eslint-disable-line no-negated-condition\n\t\t\t\t// Backtrack to the last '*' and try to match more characters\n\t\t\t\ttemplateIndex = starIndex + 1;\n\t\t\t\tmatchIndex++;\n\t\t\t\tsearchIndex = matchIndex;\n\t\t\t} else {\n\t\t\t\treturn false; // No match\n\t\t\t}\n\t\t}\n\n\t\t// Handle trailing '*' in template\n\t\twhile (templateIndex < template.length && template[templateIndex] === '*') {\n\t\t\ttemplateIndex++;\n\t\t}\n\n\t\treturn templateIndex === template.length;\n\t}\n\n\t/**\n\t* Disable debug output.\n\t*\n\t* @return {String} namespaces\n\t* @api public\n\t*/\n\tfunction disable() {\n\t\tconst namespaces = [\n\t\t\t...createDebug.names,\n\t\t\t...createDebug.skips.map(namespace => '-' + namespace)\n\t\t].join(',');\n\t\tcreateDebug.enable('');\n\t\treturn namespaces;\n\t}\n\n\t/**\n\t* Returns true if the given mode name is enabled, false otherwise.\n\t*\n\t* @param {String} name\n\t* @return {Boolean}\n\t* @api public\n\t*/\n\tfunction enabled(name) {\n\t\tfor (const skip of createDebug.skips) {\n\t\t\tif (matchesTemplate(name, skip)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\tfor (const ns of createDebug.names) {\n\t\t\tif (matchesTemplate(name, ns)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/**\n\t* Coerce `val`.\n\t*\n\t* @param {Mixed} val\n\t* @return {Mixed}\n\t* @api private\n\t*/\n\tfunction coerce(val) {\n\t\tif (val instanceof Error) {\n\t\t\treturn val.stack || val.message;\n\t\t}\n\t\treturn val;\n\t}\n\n\t/**\n\t* XXX DO NOT USE. This is a temporary stub function.\n\t* XXX It WILL be removed in the next major release.\n\t*/\n\tfunction destroy() {\n\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t}\n\n\tcreateDebug.enable(createDebug.load());\n\n\treturn createDebug;\n}\n\nmodule.exports = setup;\n", "/* eslint-env browser */\n\n/**\n * This is the web browser implementation of `debug()`.\n */\n\nexports.formatArgs = formatArgs;\nexports.save = save;\nexports.load = load;\nexports.useColors = useColors;\nexports.storage = localstorage();\nexports.destroy = (() => {\n\tlet warned = false;\n\n\treturn () => {\n\t\tif (!warned) {\n\t\t\twarned = true;\n\t\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t\t}\n\t};\n})();\n\n/**\n * Colors.\n */\n\nexports.colors = [\n\t'#0000CC',\n\t'#0000FF',\n\t'#0033CC',\n\t'#0033FF',\n\t'#0066CC',\n\t'#0066FF',\n\t'#0099CC',\n\t'#0099FF',\n\t'#00CC00',\n\t'#00CC33',\n\t'#00CC66',\n\t'#00CC99',\n\t'#00CCCC',\n\t'#00CCFF',\n\t'#3300CC',\n\t'#3300FF',\n\t'#3333CC',\n\t'#3333FF',\n\t'#3366CC',\n\t'#3366FF',\n\t'#3399CC',\n\t'#3399FF',\n\t'#33CC00',\n\t'#33CC33',\n\t'#33CC66',\n\t'#33CC99',\n\t'#33CCCC',\n\t'#33CCFF',\n\t'#6600CC',\n\t'#6600FF',\n\t'#6633CC',\n\t'#6633FF',\n\t'#66CC00',\n\t'#66CC33',\n\t'#9900CC',\n\t'#9900FF',\n\t'#9933CC',\n\t'#9933FF',\n\t'#99CC00',\n\t'#99CC33',\n\t'#CC0000',\n\t'#CC0033',\n\t'#CC0066',\n\t'#CC0099',\n\t'#CC00CC',\n\t'#CC00FF',\n\t'#CC3300',\n\t'#CC3333',\n\t'#CC3366',\n\t'#CC3399',\n\t'#CC33CC',\n\t'#CC33FF',\n\t'#CC6600',\n\t'#CC6633',\n\t'#CC9900',\n\t'#CC9933',\n\t'#CCCC00',\n\t'#CCCC33',\n\t'#FF0000',\n\t'#FF0033',\n\t'#FF0066',\n\t'#FF0099',\n\t'#FF00CC',\n\t'#FF00FF',\n\t'#FF3300',\n\t'#FF3333',\n\t'#FF3366',\n\t'#FF3399',\n\t'#FF33CC',\n\t'#FF33FF',\n\t'#FF6600',\n\t'#FF6633',\n\t'#FF9900',\n\t'#FF9933',\n\t'#FFCC00',\n\t'#FFCC33'\n];\n\n/**\n * Currently only WebKit-based Web Inspectors, Firefox >= v31,\n * and the Firebug extension (any Firefox version) are known\n * to support \"%c\" CSS customizations.\n *\n * TODO: add a `localStorage` variable to explicitly enable/disable colors\n */\n\n// eslint-disable-next-line complexity\nfunction useColors() {\n\t// NB: In an Electron preload script, document will be defined but not fully\n\t// initialized. Since we know we're in Chrome, we'll just detect this case\n\t// explicitly\n\tif (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {\n\t\treturn true;\n\t}\n\n\t// Internet Explorer and Edge do not support colors.\n\tif (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\\/(\\d+)/)) {\n\t\treturn false;\n\t}\n\n\tlet m;\n\n\t// Is webkit? http://stackoverflow.com/a/16459606/376773\n\t// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632\n\t// eslint-disable-next-line no-return-assign\n\treturn (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||\n\t\t// Is firebug? http://stackoverflow.com/a/398120/376773\n\t\t(typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||\n\t\t// Is firefox >= v31?\n\t\t// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages\n\t\t(typeof navigator !== 'undefined' && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\\/(\\d+)/)) && parseInt(m[1], 10) >= 31) ||\n\t\t// Double check webkit in userAgent just in case we are in a worker\n\t\t(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\\/(\\d+)/));\n}\n\n/**\n * Colorize log arguments if enabled.\n *\n * @api public\n */\n\nfunction formatArgs(args) {\n\targs[0] = (this.useColors ? '%c' : '') +\n\t\tthis.namespace +\n\t\t(this.useColors ? ' %c' : ' ') +\n\t\targs[0] +\n\t\t(this.useColors ? '%c ' : ' ') +\n\t\t'+' + module.exports.humanize(this.diff);\n\n\tif (!this.useColors) {\n\t\treturn;\n\t}\n\n\tconst c = 'color: ' + this.color;\n\targs.splice(1, 0, c, 'color: inherit');\n\n\t// The final \"%c\" is somewhat tricky, because there could be other\n\t// arguments passed either before or after the %c, so we need to\n\t// figure out the correct index to insert the CSS into\n\tlet index = 0;\n\tlet lastC = 0;\n\targs[0].replace(/%[a-zA-Z%]/g, match => {\n\t\tif (match === '%%') {\n\t\t\treturn;\n\t\t}\n\t\tindex++;\n\t\tif (match === '%c') {\n\t\t\t// We only are interested in the *last* %c\n\t\t\t// (the user may have provided their own)\n\t\t\tlastC = index;\n\t\t}\n\t});\n\n\targs.splice(lastC, 0, c);\n}\n\n/**\n * Invokes `console.debug()` when available.\n * No-op when `console.debug` is not a \"function\".\n * If `console.debug` is not available, falls back\n * to `console.log`.\n *\n * @api public\n */\nexports.log = console.debug || console.log || (() => {});\n\n/**\n * Save `namespaces`.\n *\n * @param {String} namespaces\n * @api private\n */\nfunction save(namespaces) {\n\ttry {\n\t\tif (namespaces) {\n\t\t\texports.storage.setItem('debug', namespaces);\n\t\t} else {\n\t\t\texports.storage.removeItem('debug');\n\t\t}\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n}\n\n/**\n * Load `namespaces`.\n *\n * @return {String} returns the previously persisted debug modes\n * @api private\n */\nfunction load() {\n\tlet r;\n\ttry {\n\t\tr = exports.storage.getItem('debug') || exports.storage.getItem('DEBUG') ;\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n\n\t// If debug isn't set in LS, and we're in Electron, try to load $DEBUG\n\tif (!r && typeof process !== 'undefined' && 'env' in process) {\n\t\tr = process.env.DEBUG;\n\t}\n\n\treturn r;\n}\n\n/**\n * Localstorage attempts to return the localstorage.\n *\n * This is necessary because safari throws\n * when a user disables cookies/localstorage\n * and you attempt to access it.\n *\n * @return {LocalStorage}\n * @api private\n */\n\nfunction localstorage() {\n\ttry {\n\t\t// TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context\n\t\t// The Browser also has localStorage in the global context.\n\t\treturn localStorage;\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n}\n\nmodule.exports = require('./common')(exports);\n\nconst {formatters} = module.exports;\n\n/**\n * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.\n */\n\nformatters.j = function (v) {\n\ttry {\n\t\treturn JSON.stringify(v);\n\t} catch (error) {\n\t\treturn '[UnexpectedJSONParseError]: ' + error.message;\n\t}\n};\n", "/**\n * @license\n * Copyright 2017 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\n\n// IMPORTANT: these imports must be type-only\nimport type {Directive, DirectiveResult, PartInfo} from './directive.js';\nimport type {TrustedHTML, TrustedTypesWindow} from 'trusted-types/lib/index.js';\n\nconst DEV_MODE = true;\nconst ENABLE_EXTRA_SECURITY_HOOKS = true;\nconst ENABLE_SHADYDOM_NOPATCH = true;\nconst NODE_MODE = false;\n\n// Allows minifiers to rename references to globalThis\nconst global = globalThis;\n\n/**\n * Contains types that are part of the unstable debug API.\n *\n * Everything in this API is not stable and may change or be removed in the future,\n * even on patch releases.\n */\n// eslint-disable-next-line @typescript-eslint/no-namespace\nexport namespace LitUnstable {\n /**\n * When Lit is running in dev mode and `window.emitLitDebugLogEvents` is true,\n * we will emit 'lit-debug' events to window, with live details about the update and render\n * lifecycle. These can be useful for writing debug tooling and visualizations.\n *\n * Please be aware that running with window.emitLitDebugLogEvents has performance overhead,\n * making certain operations that are normally very cheap (like a no-op render) much slower,\n * because we must copy data and dispatch events.\n */\n // eslint-disable-next-line @typescript-eslint/no-namespace\n export namespace DebugLog {\n export type Entry =\n | TemplatePrep\n | TemplateInstantiated\n | TemplateInstantiatedAndUpdated\n | TemplateUpdating\n | BeginRender\n | EndRender\n | CommitPartEntry\n | SetPartValue;\n export interface TemplatePrep {\n kind: 'template prep';\n template: Template;\n strings: TemplateStringsArray;\n clonableTemplate: HTMLTemplateElement;\n parts: TemplatePart[];\n }\n export interface BeginRender {\n kind: 'begin render';\n id: number;\n value: unknown;\n container: HTMLElement | DocumentFragment;\n options: RenderOptions | undefined;\n part: ChildPart | undefined;\n }\n export interface EndRender {\n kind: 'end render';\n id: number;\n value: unknown;\n container: HTMLElement | DocumentFragment;\n options: RenderOptions | undefined;\n part: ChildPart;\n }\n export interface TemplateInstantiated {\n kind: 'template instantiated';\n template: Template | CompiledTemplate;\n instance: TemplateInstance;\n options: RenderOptions | undefined;\n fragment: Node;\n parts: Array<Part | undefined>;\n values: unknown[];\n }\n export interface TemplateInstantiatedAndUpdated {\n kind: 'template instantiated and updated';\n template: Template | CompiledTemplate;\n instance: TemplateInstance;\n options: RenderOptions | undefined;\n fragment: Node;\n parts: Array<Part | undefined>;\n values: unknown[];\n }\n export interface TemplateUpdating {\n kind: 'template updating';\n template: Template | CompiledTemplate;\n instance: TemplateInstance;\n options: RenderOptions | undefined;\n parts: Array<Part | undefined>;\n values: unknown[];\n }\n export interface SetPartValue {\n kind: 'set part';\n part: Part;\n value: unknown;\n valueIndex: number;\n values: unknown[];\n templateInstance: TemplateInstance;\n }\n\n export type CommitPartEntry =\n | CommitNothingToChildEntry\n | CommitText\n | CommitNode\n | CommitAttribute\n | CommitProperty\n | CommitBooleanAttribute\n | CommitEventListener\n | CommitToElementBinding;\n\n export interface CommitNothingToChildEntry {\n kind: 'commit nothing to child';\n start: ChildNode;\n end: ChildNode | null;\n parent: Disconnectable | undefined;\n options: RenderOptions | undefined;\n }\n\n export interface CommitText {\n kind: 'commit text';\n node: Text;\n value: unknown;\n options: RenderOptions | undefined;\n }\n\n export interface CommitNode {\n kind: 'commit node';\n start: Node;\n parent: Disconnectable | undefined;\n value: Node;\n options: RenderOptions | undefined;\n }\n\n export interface CommitAttribute {\n kind: 'commit attribute';\n element: Element;\n name: string;\n value: unknown;\n options: RenderOptions | undefined;\n }\n\n export interface CommitProperty {\n kind: 'commit property';\n element: Element;\n name: string;\n value: unknown;\n options: RenderOptions | undefined;\n }\n\n export interface CommitBooleanAttribute {\n kind: 'commit boolean attribute';\n element: Element;\n name: string;\n value: boolean;\n options: RenderOptions | undefined;\n }\n\n export interface CommitEventListener {\n kind: 'commit event listener';\n element: Element;\n name: string;\n value: unknown;\n oldListener: unknown;\n options: RenderOptions | undefined;\n // True if we're removing the old event listener (e.g. because settings changed, or value is nothing)\n removeListener: boolean;\n // True if we're adding a new event listener (e.g. because first render, or settings changed)\n addListener: boolean;\n }\n\n export interface CommitToElementBinding {\n kind: 'commit to element binding';\n element: Element;\n value: unknown;\n options: RenderOptions | undefined;\n }\n }\n}\n\ninterface DebugLoggingWindow {\n // Even in dev mode, we generally don't want to emit these events, as that's\n // another level of cost, so only emit them when DEV_MODE is true _and_ when\n // window.emitLitDebugEvents is true.\n emitLitDebugLogEvents?: boolean;\n}\n\n/**\n * Useful for visualizing and logging insights into what the Lit template system is doing.\n *\n * Compiled out of prod mode builds.\n */\nconst debugLogEvent = DEV_MODE\n ? (event: LitUnstable.DebugLog.Entry) => {\n const shouldEmit = (global as unknown as DebugLoggingWindow)\n .emitLitDebugLogEvents;\n if (!shouldEmit) {\n return;\n }\n global.dispatchEvent(\n new CustomEvent<LitUnstable.DebugLog.Entry>('lit-debug', {\n detail: event,\n })\n );\n }\n : undefined;\n// Used for connecting beginRender and endRender events when there are nested\n// renders when errors are thrown preventing an endRender event from being\n// called.\nlet debugLogRenderId = 0;\n\nlet issueWarning: (code: string, warning: string) => void;\n\nif (DEV_MODE) {\n global.litIssuedWarnings ??= new Set();\n\n /**\n * Issue a warning if we haven't already, based either on `code` or `warning`.\n * Warnings are disabled automatically only by `warning`; disabling via `code`\n * can be done by users.\n */\n issueWarning = (code: string, warning: string) => {\n warning += code\n ? ` See https://lit.dev/msg/${code} for more information.`\n : '';\n if (\n !global.litIssuedWarnings!.has(warning) &&\n !global.litIssuedWarnings!.has(code)\n ) {\n console.warn(warning);\n global.litIssuedWarnings!.add(warning);\n }\n };\n\n queueMicrotask(() => {\n issueWarning(\n 'dev-mode',\n `Lit is in dev mode. Not recommended for production!`\n );\n });\n}\n\nconst wrap =\n ENABLE_SHADYDOM_NOPATCH &&\n global.ShadyDOM?.inUse &&\n global.ShadyDOM?.noPatch === true\n ? (global.ShadyDOM!.wrap as <T extends Node>(node: T) => T)\n : <T extends Node>(node: T) => node;\n\nconst trustedTypes = (global as unknown as TrustedTypesWindow).trustedTypes;\n\n/**\n * Our TrustedTypePolicy for HTML which is declared using the html template\n * tag function.\n *\n * That HTML is a developer-authored constant, and is parsed with innerHTML\n * before any untrusted expressions have been mixed in. Therefor it is\n * considered safe by construction.\n */\nconst policy = trustedTypes\n ? trustedTypes.createPolicy('lit-html', {\n createHTML: (s) => s,\n })\n : undefined;\n\n/**\n * Used to sanitize any value before it is written into the DOM. This can be\n * used to implement a security policy of allowed and disallowed values in\n * order to prevent XSS attacks.\n *\n * One way of using this callback would be to check attributes and properties\n * against a list of high risk fields, and require that values written to such\n * fields be instances of a class which is safe by construction. Closure's Safe\n * HTML Types is one implementation of this technique (\n * https://github.com/google/safe-html-types/blob/master/doc/safehtml-types.md).\n * The TrustedTypes polyfill in API-only mode could also be used as a basis\n * for this technique (https://github.com/WICG/trusted-types).\n *\n * @param node The HTML node (usually either a #text node or an Element) that\n * is being written to. Note that this is just an exemplar node, the write\n * may take place against another instance of the same class of node.\n * @param name The name of an attribute or property (for example, 'href').\n * @param type Indicates whether the write that's about to be performed will\n * be to a property or a node.\n * @return A function that will sanitize this class of writes.\n */\nexport type SanitizerFactory = (\n node: Node,\n name: string,\n type: 'property' | 'attribute'\n) => ValueSanitizer;\n\n/**\n * A function which can sanitize values that will be written to a specific kind\n * of DOM sink.\n *\n * See SanitizerFactory.\n *\n * @param value The value to sanitize. Will be the actual value passed into\n * the lit-html template literal, so this could be of any type.\n * @return The value to write to the DOM. Usually the same as the input value,\n * unless sanitization is needed.\n */\nexport type ValueSanitizer = (value: unknown) => unknown;\n\nconst identityFunction: ValueSanitizer = (value: unknown) => value;\nconst noopSanitizer: SanitizerFactory = (\n _node: Node,\n _name: string,\n _type: 'property' | 'attribute'\n) => identityFunction;\n\n/** Sets the global sanitizer factory. */\nconst setSanitizer = (newSanitizer: SanitizerFactory) => {\n if (!ENABLE_EXTRA_SECURITY_HOOKS) {\n return;\n }\n if (sanitizerFactoryInternal !== noopSanitizer) {\n throw new Error(\n `Attempted to overwrite existing lit-html security policy.` +\n ` setSanitizeDOMValueFactory should be called at most once.`\n );\n }\n sanitizerFactoryInternal = newSanitizer;\n};\n\n/**\n * Only used in internal tests, not a part of the public API.\n */\nconst _testOnlyClearSanitizerFactoryDoNotCallOrElse = () => {\n sanitizerFactoryInternal = noopSanitizer;\n};\n\nconst createSanitizer: SanitizerFactory = (node, name, type) => {\n return sanitizerFactoryInternal(node, name, type);\n};\n\n// Added to an attribute name to mark the attribute as bound so we can find\n// it easily.\nconst boundAttributeSuffix = '$lit$';\n\n// This marker is used in many syntactic positions in HTML, so it must be\n// a valid element name and attribute name. We don't support dynamic names (yet)\n// but this at least ensures that the parse tree is closer to the template\n// intention.\nconst marker = `lit$${Math.random().toFixed(9).slice(2)}$`;\n\n// String used to tell if a comment is a marker comment\nconst markerMatch = '?' + marker;\n\n// Text used to insert a comment marker node. We use processing instruction\n// syntax because it's slightly smaller, but parses as a comment node.\nconst nodeMarker = `<${markerMatch}>`;\n\nconst d =\n NODE_MODE && global.document === undefined\n ? ({\n createTreeWalker() {\n return {};\n },\n } as unknown as Document)\n : document;\n\n// Creates a dynamic marker. We never have to search for these in the DOM.\nconst createMarker = () => d.createComment('');\n\n// https://tc39.github.io/ecma262/#sec-typeof-operator\ntype Primitive = null | undefined | boolean | number | string | symbol | bigint;\nconst isPrimitive = (value: unknown): value is Primitive =>\n value === null || (typeof value != 'object' && typeof value != 'function');\nconst isArray = Array.isArray;\nconst isIterable = (value: unknown): value is Iterable<unknown> =>\n isArray(value) ||\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n typeof (value as any)?.[Symbol.iterator] === 'function';\n\nconst SPACE_CHAR = `[ \\t\\n\\f\\r]`;\nconst ATTR_VALUE_CHAR = `[^ \\t\\n\\f\\r\"'\\`<>=]`;\nconst NAME_CHAR = `[^\\\\s\"'>=/]`;\n\n// These regexes represent the five parsing states that we care about in the\n// Template's HTML scanner. They match the *end* of the state they're named\n// after.\n// Depending on the match, we transition to a new state. If there's no match,\n// we stay in the same state.\n// Note that the regexes are stateful. We utilize lastIndex and sync it\n// across the multiple regexes used. In addition to the five regexes below\n// we also dynamically create a regex to find the matching end tags for raw\n// text elements.\n\n/**\n * End of text is: `<` followed by:\n * (comment start) or (tag) or (dynamic tag binding)\n */\nconst textEndRegex = /<(?:(!--|\\/[^a-zA-Z])|(\\/?[a-zA-Z][^>\\s]*)|(\\/?$))/g;\nconst COMMENT_START = 1;\nconst TAG_NAME = 2;\nconst DYNAMIC_TAG_NAME = 3;\n\nconst commentEndRegex = /-->/g;\n/**\n * Comments not started with <!--, like </{, can be ended by a single `>`\n */\nconst comment2EndRegex = />/g;\n\n/**\n * The tagEnd regex matches the end of the \"inside an opening\" tag syntax\n * position. It either matches a `>`, an attribute-like sequence, or the end\n * of the string after a space (attribute-name position ending).\n *\n * See attributes in the HTML spec:\n * https://www.w3.org/TR/html5/syntax.html#elements-attributes\n *\n * \" \\t\\n\\f\\r\" are HTML space characters:\n * https://infra.spec.whatwg.org/#ascii-whitespace\n *\n * So an attribute is:\n * * The name: any character except a whitespace character, (\"), ('), \">\",\n * \"=\", or \"/\". Note: this is different from the HTML spec which also excludes control characters.\n * * Followed by zero or more space characters\n * * Followed by \"=\"\n * * Followed by zero or more space characters\n * * Followed by:\n * * Any character except space, ('), (\"), \"<\", \">\", \"=\", (`), or\n * * (\") then any non-(\"), or\n * * (') then any non-(')\n */\nconst tagEndRegex = new RegExp(\n `>|${SPACE_CHAR}(?:(${NAME_CHAR}+)(${SPACE_CHAR}*=${SPACE_CHAR}*(?:${ATTR_VALUE_CHAR}|(\"|')|))|$)`,\n 'g'\n);\nconst ENTIRE_MATCH = 0;\nconst ATTRIBUTE_NAME = 1;\nconst SPACES_AND_EQUALS = 2;\nconst QUOTE_CHAR = 3;\n\nconst singleQuoteAttrEndRegex = /'/g;\nconst doubleQuoteAttrEndRegex = /\"/g;\n/**\n * Matches the raw text elements.\n *\n * Comments are not parsed within raw text elements, so we need to search their\n * text content for marker strings.\n */\nconst rawTextElement = /^(?:script|style|textarea|title)$/i;\n\n/** TemplateResult types */\nconst HTML_RESULT = 1;\nconst SVG_RESULT = 2;\nconst MATHML_RESULT = 3;\n\ntype ResultType = typeof HTML_RESULT | typeof SVG_RESULT | typeof MATHML_RESULT;\n\n// TemplatePart types\n// IMPORTANT: these must match the values in PartType\nconst ATTRIBUTE_PART = 1;\nconst CHILD_PART = 2;\nconst PROPERTY_PART = 3;\nconst BOOLEAN_ATTRIBUTE_PART = 4;\nconst EVENT_PART = 5;\nconst ELEMENT_PART = 6;\nconst COMMENT_PART = 7;\n\n/**\n * The return type of the template tag functions, {@linkcode html} and\n * {@linkcode svg} when it hasn't been compiled by @lit-labs/compiler.\n *\n * A `TemplateResult` object holds all the information about a template\n * expression required to render it: the template strings, expression values,\n * and type of template (html or svg).\n *\n * `TemplateResult` objects do not create any DOM on their own. To create or\n * update DOM you need to render the `TemplateResult`. See\n * [Rendering](https://lit.dev/docs/components/rendering) for more information.\n *\n */\nexport type UncompiledTemplateResult<T extends ResultType = ResultType> = {\n // This property needs to remain unminified.\n ['_$litType$']: T;\n strings: TemplateStringsArray;\n values: unknown[];\n};\n\n/**\n * This is a template result that may be either uncompiled or compiled.\n *\n * In the future, TemplateResult will be this type. If you want to explicitly\n * note that a template result is potentially compiled, you can reference this\n * type and it will continue to behave the same through the next major version\n * of Lit. This can be useful for code that wants to prepare for the next\n * major version of Lit.\n */\nexport type MaybeCompiledTemplateResult<T extends ResultType = ResultType> =\n | UncompiledTemplateResult<T>\n | CompiledTemplateResult;\n\n/**\n * The return type of the template tag functions, {@linkcode html} and\n * {@linkcode svg}.\n *\n * A `TemplateResult` object holds all the information about a template\n * expression required to render it: the template strings, expression values,\n * and type of template (html or svg).\n *\n * `TemplateResult` objects do not create any DOM on their own. To create or\n * update DOM you need to render the `TemplateResult`. See\n * [Rendering](https://lit.dev/docs/components/rendering) for more information.\n *\n * In Lit 4, this type will be an alias of\n * MaybeCompiledTemplateResult, so that code will get type errors if it assumes\n * that Lit templates are not compiled. When deliberately working with only\n * one, use either {@linkcode CompiledTemplateResult} or\n * {@linkcode UncompiledTemplateResult} explicitly.\n */\nexport type TemplateResult<T extends ResultType = ResultType> =\n UncompiledTemplateResult<T>;\n\nexport type HTMLTemplateResult = TemplateResult<typeof HTML_RESULT>;\n\nexport type SVGTemplateResult = TemplateResult<typeof SVG_RESULT>;\n\nexport type MathMLTemplateResult = TemplateResult<typeof MATHML_RESULT>;\n\n/**\n * A TemplateResult that has been compiled by @lit-labs/compiler, skipping the\n * prepare step.\n */\nexport interface CompiledTemplateResult {\n // This is a factory in order to make template initialization lazy\n // and allow ShadyRenderOptions scope to be passed in.\n // This property needs to remain unminified.\n ['_$litType$']: CompiledTemplate;\n values: unknown[];\n}\n\nexport interface CompiledTemplate extends Omit<Template, 'el'> {\n // el is overridden to be optional. We initialize it on first render\n el?: HTMLTemplateElement;\n\n // The prepared HTML string to create a template element from.\n // The type is a TemplateStringsArray to guarantee that the value came from\n // source code, preventing a JSON injection attack.\n h: TemplateStringsArray;\n}\n\n/**\n * Generates a template literal tag function that returns a TemplateResult with\n * the given result type.\n */\nconst tag =\n <T extends ResultType>(type: T) =>\n (strings: TemplateStringsArray, ...values: unknown[]): TemplateResult<T> => {\n // Warn against templates octal escape sequences\n // We do this here rather than in render so that the warning is closer to the\n // template definition.\n if (DEV_MODE && strings.some((s) => s === undefined)) {\n console.warn(\n 'Some template strings are undefined.\\n' +\n 'This is probably caused by illegal octal escape sequences.'\n );\n }\n if (DEV_MODE) {\n // Import static-html.js results in a circular dependency which g3 doesn't\n // handle. Instead we know that static values must have the field\n // `_$litStatic$`.\n if (\n values.some((val) => (val as {_$litStatic$: unknown})?.['_$litStatic$'])\n ) {\n issueWarning(\n '',\n `Static values 'literal' or 'unsafeStatic' cannot be used as values to non-static templates.\\n` +\n `Please use the static 'html' tag function. See https://lit.dev/docs/templates/expressions/#static-expressions`\n );\n }\n }\n return {\n // This property needs to remain unminified.\n ['_$litType$']: type,\n strings,\n values,\n };\n };\n\n/**\n * Interprets a template literal as an HTML template that can efficiently\n * render to and update a container.\n *\n * ```ts\n * const header = (title: string) => html`<h1>${title}</h1>`;\n * ```\n *\n * The `html` tag returns a description of the DOM to render as a value. It is\n * lazy, meaning no work is done until the template is rendered. When rendering,\n * if a template comes from the same expression as a previously rendered result,\n * it's efficiently updated instead of replaced.\n */\nexport const html = tag(HTML_RESULT);\n\n/**\n * Interprets a template literal as an SVG fragment that can efficiently render\n * to and update a container.\n *\n * ```ts\n * const rect = svg`<rect width=\"10\" height=\"10\"></rect>`;\n *\n * const myImage = html`\n * <svg viewBox=\"0 0 10 10\" xmlns=\"http://www.w3.org/2000/svg\">\n * ${rect}\n * </svg>`;\n * ```\n *\n * The `svg` *tag function* should only be used for SVG fragments, or elements\n * that would be contained **inside** an `<svg>` HTML element. A common error is\n * placing an `<svg>` *element* in a template tagged with the `svg` tag\n * function. The `<svg>` element is an HTML element and should be used within a\n * template tagged with the {@linkcode html} tag function.\n *\n * In LitElement usage, it's invalid to return an SVG fragment from the\n * `render()` method, as the SVG fragment will be contained within the element's\n * shadow root and thus not be properly contained within an `<svg>` HTML\n * element.\n */\nexport const svg = tag(SVG_RESULT);\n\n/**\n * Interprets a template literal as MathML fragment that can efficiently render\n * to and update a container.\n *\n * ```ts\n * const num = mathml`<mn>1</mn>`;\n *\n * const eq = html`\n * <math>\n * ${num}\n * </math>`;\n * ```\n *\n * The `mathml` *tag function* should only be used for MathML fragments, or\n * elements that would be contained **inside** a `<math>` HTML element. A common\n * error is placing a `<math>` *element* in a template tagged with the `mathml`\n * tag function. The `<math>` element is an HTML element and should be used\n * within a template tagged with the {@linkcode html} tag function.\n *\n * In LitElement usage, it's invalid to return an MathML fragment from the\n * `render()` method, as the MathML fragment will be contained within the\n * element's shadow root and thus not be properly contained within a `<math>`\n * HTML element.\n */\nexport const mathml = tag(MATHML_RESULT);\n\n/**\n * A sentinel value that signals that a value was handled by a directive and\n * should not be written to the DOM.\n */\nexport const noChange = Symbol.for('lit-noChange');\n\n/**\n * A sentinel value that signals a ChildPart to fully clear its content.\n *\n * ```ts\n * const button = html`${\n * user.isAdmin\n * ? html`<button>DELETE</button>`\n * : nothing\n * }`;\n * ```\n *\n * Prefer using `nothing` over other falsy values as it provides a consistent\n * behavior between various expression binding contexts.\n *\n * In child expressions, `undefined`, `null`, `''`, and `nothing` all behave the\n * same and render no nodes. In attribute expressions, `nothing` _removes_ the\n * attribute, while `undefined` and `null` will render an empty string. In\n * property expressions `nothing` becomes `undefined`.\n */\nexport const nothing = Symbol.for('lit-nothing');\n\n/**\n * The cache of prepared templates, keyed by the tagged TemplateStringsArray\n * and _not_ accounting for the specific template tag used. This means that\n * template tags cannot be dynamic - they must statically be one of html, svg,\n * or attr. This restriction simplifies the cache lookup, which is on the hot\n * path for rendering.\n */\nconst templateCache = new WeakMap<TemplateStringsArray, Template>();\n\n/**\n * Object specifying options for controlling lit-html rendering. Note that\n * while `render` may be called multiple times on the same `container` (and\n * `renderBefore` reference node) to efficiently update the rendered content,\n * only the options passed in during the first render are respected during\n * the lifetime of renders to that unique `container` + `renderBefore`\n * combination.\n */\nexport interface RenderOptions {\n /**\n * An object to use as the `this` value for event listeners. It's often\n * useful to set this to the host component rendering a template.\n */\n host?: object;\n /**\n * A DOM node before which to render content in the container.\n */\n renderBefore?: ChildNode | null;\n /**\n * Node used for cloning the template (`importNode` will be called on this\n * node). This controls the `ownerDocument` of the rendered DOM, along with\n * any inherited context. Defaults to the global `document`.\n */\n creationScope?: {importNode(node: Node, deep?: boolean): Node};\n /**\n * The initial connected state for the top-level part being rendered. If no\n * `isConnected` option is set, `AsyncDirective`s will be connected by\n * default. Set to `false` if the initial render occurs in a disconnected tree\n * and `AsyncDirective`s should see `isConnected === false` for their initial\n * render. The `part.setConnected()` method must be used subsequent to initial\n * render to change the connected state of the part.\n */\n isConnected?: boolean;\n}\n\nconst walker = d.createTreeWalker(\n d,\n 129 /* NodeFilter.SHOW_{ELEMENT|COMMENT} */\n);\n\nlet sanitizerFactoryInternal: SanitizerFactory = noopSanitizer;\n\n//\n// Classes only below here, const variable declarations only above here...\n//\n// Keeping variable declarations and classes together improves minification.\n// Interfaces and type aliases can be interleaved freely.\n//\n\n// Type for classes that have a `_directive` or `_directives[]` field, used by\n// `resolveDirective`\nexport interface DirectiveParent {\n _$parent?: DirectiveParent;\n _$isConnected: boolean;\n __directive?: Directive;\n __directives?: Array<Directive | undefined>;\n}\n\nfunction trustFromTemplateString(\n tsa: TemplateStringsArray,\n stringFromTSA: string\n): TrustedHTML {\n // A security check to prevent spoofing of Lit template results.\n // In the future, we may be able to replace this with Array.isTemplateObject,\n // though we might need to make that check inside of the html and svg\n // functions, because precompiled templates don't come in as\n // TemplateStringArray objects.\n if (!isArray(tsa) || !tsa.hasOwnProperty('raw')) {\n let message = 'invalid template strings array';\n if (DEV_MODE) {\n message = `\n Internal Error: expected template strings to be an array\n with a 'raw' field. Faking a template strings array by\n calling html or svg like an ordinary function is effectively\n the same as calling unsafeHtml and can lead to major security\n issues, e.g. opening your code up to XSS attacks.\n If you're using the html or svg tagged template functions normally\n and still seeing this error, please file a bug at\n https://github.com/lit/lit/issues/new?template=bug_report.md\n and include information about your build tooling, if any.\n `\n .trim()\n .replace(/\\n */g, '\\n');\n }\n throw new Error(message);\n }\n return policy !== undefined\n ? policy.createHTML(stringFromTSA)\n : (stringFromTSA as unknown as TrustedHTML);\n}\n\n/**\n * Returns an HTML string for the given TemplateStringsArray and result type\n * (HTML or SVG), along with the case-sensitive bound attribute names in\n * template order. The HTML contains comment markers denoting the `ChildPart`s\n * and suffixes on bound attributes denoting the `AttributeParts`.\n *\n * @param strings template strings array\n * @param type HTML or SVG\n * @return Array containing `[html, attrNames]` (array returned for terseness,\n * to avoid object fields since this code is shared with non-minified SSR\n * code)\n */\nconst getTemplateHtml = (\n strings: TemplateStringsArray,\n type: ResultType\n): [TrustedHTML, Array<string>] => {\n // Insert makers into the template HTML to represent the position of\n // bindings. The following code scans the template strings to determine the\n // syntactic position of the bindings. They can be in text position, where\n // we insert an HTML comment, attribute value position, where we insert a\n // sentinel string and re-write the attribute name, or inside a tag where\n // we insert the sentinel string.\n const l = strings.length - 1;\n // Stores the case-sensitive bound attribute names in the order of their\n // parts. ElementParts are also reflected in this array as undefined\n // rather than a string, to disambiguate from attribute bindings.\n const attrNames: Array<string> = [];\n let html =\n type === SVG_RESULT ? '<svg>' : type === MATHML_RESULT ? '<math>' : '';\n\n // When we're inside a raw text tag (not it's text content), the regex\n // will still be tagRegex so we can find attributes, but will switch to\n // this regex when the tag ends.\n let rawTextEndRegex: RegExp | undefined;\n\n // The current parsing state, represented as a reference to one of the\n // regexes\n let regex = textEndRegex;\n\n for (let i = 0; i < l; i++) {\n const s = strings[i];\n // The index of the end of the last attribute name. When this is\n // positive at end of a string, it means we're in an attribute value\n // position and need to rewrite the attribute name.\n // We also use a special value of -2 to indicate that we encountered\n // the end of a string in attribute name position.\n let attrNameEndIndex = -1;\n let attrName: string | undefined;\n let lastIndex = 0;\n let match!: RegExpExecArray | null;\n\n // The conditions in this loop handle the current parse state, and the\n // assignments to the `regex` variable are the state transitions.\n while (lastIndex < s.length) {\n // Make sure we start searching from where we previously left off\n regex.lastIndex = lastIndex;\n match = regex.exec(s);\n if (match === null) {\n break;\n }\n lastIndex = regex.lastIndex;\n if (regex === textEndRegex) {\n if (match[COMMENT_START] === '!--') {\n regex = commentEndRegex;\n } else if (match[COMMENT_START] !== undefined) {\n // We started a weird comment, like </{\n regex = comment2EndRegex;\n } else if (match[TAG_NAME] !== undefined) {\n if (rawTextElement.test(match[TAG_NAME])) {\n // Record if we encounter a raw-text element. We'll switch to\n // this regex at the end of the tag.\n rawTextEndRegex = new RegExp(`</${match[TAG_NAME]}`, 'g');\n }\n regex = tagEndRegex;\n } else if (match[DYNAMIC_TAG_NAME] !== undefined) {\n if (DEV_MODE) {\n throw new Error(\n 'Bindings in tag names are not supported. Please use static templates instead. ' +\n 'See https://lit.dev/docs/templates/expressions/#static-expressions'\n );\n }\n regex = tagEndRegex;\n }\n } else if (regex === tagEndRegex) {\n if (match[ENTIRE_MATCH] === '>') {\n // End of a tag. If we had started a raw-text element, use that\n // regex\n regex = rawTextEndRegex ?? textEndRegex;\n // We may be ending an unquoted attribute value, so make sure we\n // clear any pending attrNameEndIndex\n attrNameEndIndex = -1;\n } else if (match[ATTRIBUTE_NAME] === undefined) {\n // Attribute name position\n attrNameEndIndex = -2;\n } else {\n attrNameEndIndex = regex.lastIndex - match[SPACES_AND_EQUALS].length;\n attrName = match[ATTRIBUTE_NAME];\n regex =\n match[QUOTE_CHAR] === undefined\n ? tagEndRegex\n : match[QUOTE_CHAR] === '\"'\n ? doubleQuoteAttrEndRegex\n : singleQuoteAttrEndRegex;\n }\n } else if (\n regex === doubleQuoteAttrEndRegex ||\n regex === singleQuoteAttrEndRegex\n ) {\n regex = tagEndRegex;\n } else if (regex === commentEndRegex || regex === comment2EndRegex) {\n regex = textEndRegex;\n } else {\n // Not one of the five state regexes, so it must be the dynamically\n // created raw text regex and we're at the close of that element.\n regex = tagEndRegex;\n rawTextEndRegex = undefined;\n }\n }\n\n if (DEV_MODE) {\n // If we have a attrNameEndIndex, which indicates that we should\n // rewrite the attribute name, assert that we're in a valid attribute\n // position - either in a tag, or a quoted attribute value.\n console.assert(\n attrNameEndIndex === -1 ||\n regex === tagEndRegex ||\n regex === singleQuoteAttrEndRegex ||\n regex === doubleQuoteAttrEndRegex,\n 'unexpected parse state B'\n );\n }\n\n // We have four cases:\n // 1. We're in text position, and not in a raw text element\n // (regex === textEndRegex): insert a comment marker.\n // 2. We have a non-negative attrNameEndIndex which means we need to\n // rewrite the attribute name to add a bound attribute suffix.\n // 3. We're at the non-first binding in a multi-binding attribute, use a\n // plain marker.\n // 4. We're somewhere else inside the tag. If we're in attribute name\n // position (attrNameEndIndex === -2), add a sequential suffix to\n // generate a unique attribute name.\n\n // Detect a binding next to self-closing tag end and insert a space to\n // separate the marker from the tag end:\n const end =\n regex === tagEndRegex && strings[i + 1].startsWith('/>') ? ' ' : '';\n html +=\n regex === textEndRegex\n ? s + nodeMarker\n : attrNameEndIndex >= 0\n ? (attrNames.push(attrName!),\n s.slice(0, attrNameEndIndex) +\n boundAttributeSuffix +\n s.slice(attrNameEndIndex)) +\n marker +\n end\n : s + marker + (attrNameEndIndex === -2 ? i : end);\n }\n\n const htmlResult: string | TrustedHTML =\n html +\n (strings[l] || '<?>') +\n (type === SVG_RESULT ? '</svg>' : type === MATHML_RESULT ? '</math>' : '');\n\n // Returned as an array for terseness\n return [trustFromTemplateString(strings, htmlResult), attrNames];\n};\n\n/** @internal */\nexport type {Template};\nclass Template {\n /** @internal */\n el!: HTMLTemplateElement;\n\n parts: Array<TemplatePart> = [];\n\n constructor(\n // This property needs to remain unminified.\n {strings, ['_$litType$']: type}: UncompiledTemplateResult,\n options?: RenderOptions\n ) {\n let node: Node | null;\n let nodeIndex = 0;\n let attrNameIndex = 0;\n const partCount = strings.length - 1;\n const parts = this.parts;\n\n // Create template element\n const [html, attrNames] = getTemplateHtml(strings, type);\n this.el = Template.createElement(html, options);\n walker.currentNode = this.el.content;\n\n // Re-parent SVG or MathML nodes into template root\n if (type === SVG_RESULT || type === MATHML_RESULT) {\n const wrapper = this.el.content.firstChild!;\n wrapper.replaceWith(...wrapper.childNodes);\n }\n\n // Walk the template to find binding markers and create TemplateParts\n while ((node = walker.nextNode()) !== null && parts.length < partCount) {\n if (node.nodeType === 1) {\n if (DEV_MODE) {\n const tag = (node as Element).localName;\n // Warn if `textarea` includes an expression and throw if `template`\n // does since these are not supported. We do this by checking\n // innerHTML for anything that looks like a marker. This catches\n // cases like bindings in textarea there markers turn into text nodes.\n if (\n /^(?:textarea|template)$/i!.test(tag) &&\n (node as Element).innerHTML.includes(marker)\n ) {\n const m =\n `Expressions are not supported inside \\`${tag}\\` ` +\n `elements. See https://lit.dev/msg/expression-in-${tag} for more ` +\n `information.`;\n if (tag === 'template') {\n throw new Error(m);\n } else issueWarning('', m);\n }\n }\n // TODO (justinfagnani): for attempted dynamic tag names, we don't\n // increment the bindingIndex, and it'll be off by 1 in the element\n // and off by two after it.\n if ((node as Element).hasAttributes()) {\n for (const name of (node as Element).getAttributeNames()) {\n if (name.endsWith(boundAttributeSuffix)) {\n const realName = attrNames[attrNameIndex++];\n const value = (node as Element).getAttribute(name)!;\n const statics = value.split(marker);\n const m = /([.?@])?(.*)/.exec(realName)!;\n parts.push({\n type: ATTRIBUTE_PART,\n index: nodeIndex,\n name: m[2],\n strings: statics,\n ctor:\n m[1] === '.'\n ? PropertyPart\n : m[1] === '?'\n ? BooleanAttributePart\n : m[1] === '@'\n ? EventPart\n : AttributePart,\n });\n (node as Element).removeAttribute(name);\n } else if (name.startsWith(marker)) {\n parts.push({\n type: ELEMENT_PART,\n index: nodeIndex,\n });\n (node as Element).removeAttribute(name);\n }\n }\n }\n // TODO (justinfagnani): benchmark the regex against testing for each\n // of the 3 raw text element names.\n if (rawTextElement.test((node as Element).tagName)) {\n // For raw text elements we need to split the text content on\n // markers, create a Text node for each segment, and create\n // a TemplatePart for each marker.\n const strings = (node as Element).textContent!.split(marker);\n const lastIndex = strings.length - 1;\n if (lastIndex > 0) {\n (node as Element).textContent = trustedTypes\n ? (trustedTypes.emptyScript as unknown as '')\n : '';\n // Generate a new text node for each literal section\n // These nodes are also used as the markers for child parts\n for (let i = 0; i < lastIndex; i++) {\n (node as Element).append(strings[i], createMarker());\n // Walk past the marker node we just added\n walker.nextNode();\n parts.push({type: CHILD_PART, index: ++nodeIndex});\n }\n // Note because this marker is added after the walker's current\n // node, it will be walked to in the outer loop (and ignored), so\n // we don't need to adjust nodeIndex here\n (node as Element).append(strings[lastIndex], createMarker());\n }\n }\n } else if (node.nodeType === 8) {\n const data = (node as Comment).data;\n if (data === markerMatch) {\n parts.push({type: CHILD_PART, index: nodeIndex});\n } else {\n let i = -1;\n while ((i = (node as Comment).data.indexOf(marker, i + 1)) !== -1) {\n // Comment node has a binding marker inside, make an inactive part\n // The binding won't work, but subsequent bindings will\n parts.push({type: COMMENT_PART, index: nodeIndex});\n // Move to the end of the match\n i += marker.length - 1;\n }\n }\n }\n nodeIndex++;\n }\n\n if (DEV_MODE) {\n // If there was a duplicate attribute on a tag, then when the tag is\n // parsed into an element the attribute gets de-duplicated. We can detect\n // this mismatch if we haven't precisely consumed every attribute name\n // when preparing the template. This works because `attrNames` is built\n // from the template string and `attrNameIndex` comes from processing the\n // resulting DOM.\n if (attrNames.length !== attrNameIndex) {\n throw new Error(\n `Detected duplicate attribute bindings. This occurs if your template ` +\n `has duplicate attributes on an element tag. For example ` +\n `\"<input ?disabled=\\${true} ?disabled=\\${false}>\" contains a ` +\n `duplicate \"disabled\" attribute. The error was detected in ` +\n `the following template: \\n` +\n '`' +\n strings.join('${...}') +\n '`'\n );\n }\n }\n\n // We could set walker.currentNode to another node here to prevent a memory\n // leak, but every time we prepare a template, we immediately render it\n // and re-use the walker in new TemplateInstance._clone().\n debugLogEvent &&\n debugLogEvent({\n kind: 'template prep',\n template: this,\n clonableTemplate: this.el,\n parts: this.parts,\n strings,\n });\n }\n\n // Overridden via `litHtmlPolyfillSupport` to provide platform support.\n /** @nocollapse */\n static createElement(html: TrustedHTML, _options?: RenderOptions) {\n const el = d.createElement('template');\n el.innerHTML = html as unknown as string;\n return el;\n }\n}\n\nexport interface Disconnectable {\n _$parent?: Disconnectable;\n _$disconnectableChildren?: Set<Disconnectable>;\n // Rather than hold connection state on instances, Disconnectables recursively\n // fetch the connection state from the RootPart they are connected in via\n // getters up the Disconnectable tree via _$parent references. This pushes the\n // cost of tracking the isConnected state to `AsyncDirectives`, and avoids\n // needing to pass all Disconnectables (parts, template instances, and\n // directives) their connection state each time it changes, which would be\n // costly for trees that have no AsyncDirectives.\n _$isConnected: boolean;\n}\n\nfunction resolveDirective(\n part: ChildPart | AttributePart | ElementPart,\n value: unknown,\n parent: DirectiveParent = part,\n attributeIndex?: number\n): unknown {\n // Bail early if the value is explicitly noChange. Note, this means any\n // nested directive is still attached and is not run.\n if (value === noChange) {\n return value;\n }\n let currentDirective =\n attributeIndex !== undefined\n ? (parent as AttributePart).__directives?.[attributeIndex]\n : (parent as ChildPart | ElementPart | Directive).__directive;\n const nextDirectiveConstructor = isPrimitive(value)\n ? undefined\n : // This property needs to remain unminified.\n (value as DirectiveResult)['_$litDirective$'];\n if (currentDirective?.constructor !== nextDirectiveConstructor) {\n // This property needs to remain unminified.\n currentDirective?.['_$notifyDirectiveConnectionChanged']?.(false);\n if (nextDirectiveConstructor === undefined) {\n currentDirective = undefined;\n } else {\n currentDirective = new nextDirectiveConstructor(part as PartInfo);\n currentDirective._$initialize(part, parent, attributeIndex);\n }\n if (attributeIndex !== undefined) {\n ((parent as AttributePart).__directives ??= [])[attributeIndex] =\n currentDirective;\n } else {\n (parent as ChildPart | Directive).__directive = currentDirective;\n }\n }\n if (currentDirective !== undefined) {\n value = resolveDirective(\n part,\n currentDirective._$resolve(part, (value as DirectiveResult).values),\n currentDirective,\n attributeIndex\n );\n }\n return value;\n}\n\nexport type {TemplateInstance};\n/**\n * An updateable instance of a Template. Holds references to the Parts used to\n * update the template instance.\n */\nclass TemplateInstance implements Disconnectable {\n _$template: Template;\n _$parts: Array<Part | undefined> = [];\n\n /** @internal */\n _$parent: ChildPart;\n /** @internal */\n _$disconnectableChildren?: Set<Disconnectable> = undefined;\n\n constructor(template: Template, parent: ChildPart) {\n this._$template = template;\n this._$parent = parent;\n }\n\n // Called by ChildPart parentNode getter\n get parentNode() {\n return this._$parent.parentNode;\n }\n\n // See comment in Disconnectable interface for why this is a getter\n get _$isConnected() {\n return this._$parent._$isConnected;\n }\n\n // This method is separate from the constructor because we need to return a\n // DocumentFragment and we don't want to hold onto it with an instance field.\n _clone(options: RenderOptions | undefined) {\n const {\n el: {content},\n parts: parts,\n } = this._$template;\n const fragment = (options?.creationScope ?? d).importNode(content, true);\n walker.currentNode = fragment;\n\n let node = walker.nextNode()!;\n let nodeIndex = 0;\n let partIndex = 0;\n let templatePart = parts[0];\n\n while (templatePart !== undefined) {\n if (nodeIndex === templatePart.index) {\n let part: Part | undefined;\n if (templatePart.type === CHILD_PART) {\n part = new ChildPart(\n node as HTMLElement,\n node.nextSibling,\n this,\n options\n );\n } else if (templatePart.type === ATTRIBUTE_PART) {\n part = new templatePart.ctor(\n node as HTMLElement,\n templatePart.name,\n templatePart.strings,\n this,\n options\n );\n } else if (templatePart.type === ELEMENT_PART) {\n part = new ElementPart(node as HTMLElement, this, options);\n }\n this._$parts.push(part);\n templatePart = parts[++partIndex];\n }\n if (nodeIndex !== templatePart?.index) {\n node = walker.nextNode()!;\n nodeIndex++;\n }\n }\n // We need to set the currentNode away from the cloned tree so that we\n // don't hold onto the tree even if the tree is detached and should be\n // freed.\n walker.currentNode = d;\n return fragment;\n }\n\n _update(values: Array<unknown>) {\n let i = 0;\n for (const part of this._$parts) {\n if (part !== undefined) {\n debugLogEvent &&\n debugLogEvent({\n kind: 'set part',\n part,\n value: values[i],\n valueIndex: i,\n values,\n templateInstance: this,\n });\n if ((part as AttributePart).strings !== undefined) {\n (part as AttributePart)._$setValue(values, part as AttributePart, i);\n // The number of values the part consumes is part.strings.length - 1\n // since values are in between template spans. We increment i by 1\n // later in the loop, so increment it by part.strings.length - 2 here\n i += (part as AttributePart).strings!.length - 2;\n } else {\n part._$setValue(values[i]);\n }\n }\n i++;\n }\n }\n}\n\n/*\n * Parts\n */\ntype AttributeTemplatePart = {\n readonly type: typeof ATTRIBUTE_PART;\n readonly index: number;\n readonly name: string;\n readonly ctor: typeof AttributePart;\n readonly strings: ReadonlyArray<string>;\n};\ntype ChildTemplatePart = {\n readonly type: typeof CHILD_PART;\n readonly index: number;\n};\ntype ElementTemplatePart = {\n readonly type: typeof ELEMENT_PART;\n readonly index: number;\n};\ntype CommentTemplatePart = {\n readonly type: typeof COMMENT_PART;\n readonly index: number;\n};\n\n/**\n * A TemplatePart represents a dynamic part in a template, before the template\n * is instantiated. When a template is instantiated Parts are created from\n * TemplateParts.\n */\ntype TemplatePart =\n | ChildTemplatePart\n | AttributeTemplatePart\n | ElementTemplatePart\n | CommentTemplatePart;\n\nexport type Part =\n | ChildPart\n | AttributePart\n | PropertyPart\n | BooleanAttributePart\n | ElementPart\n | EventPart;\n\nexport type {ChildPart};\nclass ChildPart implements Disconnectable {\n readonly type = CHILD_PART;\n readonly options: RenderOptions | undefined;\n _$committedValue: unknown = nothing;\n /** @internal */\n __directive?: Directive;\n /** @internal */\n _$startNode: ChildNode;\n /** @internal */\n _$endNode: ChildNode | null;\n private _textSanitizer: ValueSanitizer | undefined;\n /** @internal */\n _$parent: Disconnectable | undefined;\n /**\n * Connection state for RootParts only (i.e. ChildPart without _$parent\n * returned from top-level `render`). This field is unused otherwise. The\n * intention would be clearer if we made `RootPart` a subclass of `ChildPart`\n * with this field (and a different _$isConnected getter), but the subclass\n * caused a perf regression, possibly due to making call sites polymorphic.\n * @internal\n */\n __isConnected: boolean;\n\n // See comment in Disconnectable interface for why this is a getter\n get _$isConnected() {\n // ChildParts that are not at the root should always be created with a\n // parent; only RootChildNode's won't, so they return the local isConnected\n // state\n return this._$parent?._$isConnected ?? this.__isConnected;\n }\n\n // The following fields will be patched onto ChildParts when required by\n // AsyncDirective\n /** @internal */\n _$disconnectableChildren?: Set<Disconnectable> = undefined;\n /** @internal */\n _$notifyConnectionChanged?(\n isConnected: boolean,\n removeFromParent?: boolean,\n from?: number\n ): void;\n /** @internal */\n _$reparentDisconnectables?(parent: Disconnectable): void;\n\n constructor(\n startNode: ChildNode,\n endNode: ChildNode | null,\n parent: TemplateInstance | ChildPart | undefined,\n options: RenderOptions | undefined\n ) {\n this._$startNode = startNode;\n this._$endNode = endNode;\n this._$parent = parent;\n this.options = options;\n // Note __isConnected is only ever accessed on RootParts (i.e. when there is\n // no _$parent); the value on a non-root-part is \"don't care\", but checking\n // for parent would be more code\n this.__isConnected = options?.isConnected ?? true;\n if (ENABLE_EXTRA_SECURITY_HOOKS) {\n // Explicitly initialize for consistent class shape.\n this._textSanitizer = undefined;\n }\n }\n\n /**\n * The parent node into which the part renders its content.\n *\n * A ChildPart's content consists of a range of adjacent child nodes of\n * `.parentNode`, possibly bordered by 'marker nodes' (`.startNode` and\n * `.endNode`).\n *\n * - If both `.startNode` and `.endNode` are non-null, then the part's content\n * consists of all siblings between `.startNode` and `.endNode`, exclusively.\n *\n * - If `.startNode` is non-null but `.endNode` is null, then the part's\n * content consists of all siblings following `.startNode`, up to and\n * including the last child of `.parentNode`. If `.endNode` is non-null, then\n * `.startNode` will always be non-null.\n *\n * - If both `.endNode` and `.startNode` are null, then the part's content\n * consists of all child nodes of `.parentNode`.\n */\n get parentNode(): Node {\n let parentNode: Node = wrap(this._$startNode).parentNode!;\n const parent = this._$parent;\n if (\n parent !== undefined &&\n parentNode?.nodeType === 11 /* Node.DOCUMENT_FRAGMENT */\n ) {\n // If the parentNode is a DocumentFragment, it may be because the DOM is\n // still in the cloned fragment during initial render; if so, get the real\n // parentNode the part will be committed into by asking the parent.\n parentNode = (parent as ChildPart | TemplateInstance).parentNode;\n }\n return parentNode;\n }\n\n /**\n * The part's leading marker node, if any. See `.parentNode` for more\n * information.\n */\n get startNode(): Node | null {\n return this._$startNode;\n }\n\n /**\n * The part's trailing marker node, if any. See `.parentNode` for more\n * information.\n */\n get endNode(): Node | null {\n return this._$endNode;\n }\n\n _$setValue(value: unknown, directiveParent: DirectiveParent = this): void {\n if (DEV_MODE && this.parentNode === null) {\n throw new Error(\n `This \\`ChildPart\\` has no \\`parentNode\\` and therefore cannot accept a value. This likely means the element containing the part was manipulated in an unsupported way outside of Lit's control such that the part's marker nodes were ejected from DOM. For example, setting the element's \\`innerHTML\\` or \\`textContent\\` can do this.`\n );\n }\n value = resolveDirective(this, value, directiveParent);\n if (isPrimitive(value)) {\n // Non-rendering child values. It's important that these do not render\n // empty text nodes to avoid issues with preventing default <slot>\n // fallback content.\n if (value === nothing || value == null || value === '') {\n if (this._$committedValue !== nothing) {\n debugLogEvent &&\n debugLogEvent({\n kind: 'commit nothing to child',\n start: this._$startNode,\n end: this._$endNode,\n parent: this._$parent,\n options: this.options,\n });\n this._$clear();\n }\n this._$committedValue = nothing;\n } else if (value !== this._$committedValue && value !== noChange) {\n this._commitText(value);\n }\n // This property needs to remain unminified.\n } else if ((value as TemplateResult)['_$litType$'] !== undefined) {\n this._commitTemplateResult(value as TemplateResult);\n } else if ((value as Node).nodeType !== undefined) {\n if (DEV_MODE && this.options?.host === value) {\n this._commitText(\n `[probable mistake: rendered a template's host in itself ` +\n `(commonly caused by writing \\${this} in a template]`\n );\n console.warn(\n `Attempted to render the template host`,\n value,\n `inside itself. This is almost always a mistake, and in dev mode `,\n `we render some warning text. In production however, we'll `,\n `render it, which will usually result in an error, and sometimes `,\n `in the element disappearing from the DOM.`\n );\n return;\n }\n this._commitNode(value as Node);\n } else if (isIterable(value)) {\n this._commitIterable(value);\n } else {\n // Fallback, will render the string representation\n this._commitText(value);\n }\n }\n\n private _insert<T extends Node>(node: T) {\n return wrap(wrap(this._$startNode).parentNode!).insertBefore(\n node,\n this._$endNode\n );\n }\n\n private _commitNode(value: Node): void {\n if (this._$committedValue !== value) {\n this._$clear();\n if (\n ENABLE_EXTRA_SECURITY_HOOKS &&\n sanitizerFactoryInternal !== noopSanitizer\n ) {\n const parentNodeName = this._$startNode.parentNode?.nodeName;\n if (parentNodeName === 'STYLE' || parentNodeName === 'SCRIPT') {\n let message = 'Forbidden';\n if (DEV_MODE) {\n if (parentNodeName === 'STYLE') {\n message =\n `Lit does not support binding inside style nodes. ` +\n `This is a security risk, as style injection attacks can ` +\n `exfiltrate data and spoof UIs. ` +\n `Consider instead using css\\`...\\` literals ` +\n `to compose styles, and do dynamic styling with ` +\n `css custom properties, ::parts, <slot>s, ` +\n `and by mutating the DOM rather than stylesheets.`;\n } else {\n message =\n `Lit does not support binding inside script nodes. ` +\n `This is a security risk, as it could allow arbitrary ` +\n `code execution.`;\n }\n }\n throw new Error(message);\n }\n }\n debugLogEvent &&\n debugLogEvent({\n kind: 'commit node',\n start: this._$startNode,\n parent: this._$parent,\n value: value,\n options: this.options,\n });\n this._$committedValue = this._insert(value);\n }\n }\n\n private _commitText(value: unknown): void {\n // If the committed value is a primitive it means we called _commitText on\n // the previous render, and we know that this._$startNode.nextSibling is a\n // Text node. We can now just replace the text content (.data) of the node.\n if (\n this._$committedValue !== nothing &&\n isPrimitive(this._$committedValue)\n ) {\n const node = wrap(this._$startNode).nextSibling as Text;\n if (ENABLE_EXTRA_SECURITY_HOOKS) {\n if (this._textSanitizer === undefined) {\n this._textSanitizer = createSanitizer(node, 'data', 'property');\n }\n value = this._textSanitizer(value);\n }\n debugLogEvent &&\n debugLogEvent({\n kind: 'commit text',\n node,\n value,\n options: this.options,\n });\n (node as Text).data = value as string;\n } else {\n if (ENABLE_EXTRA_SECURITY_HOOKS) {\n const textNode = d.createTextNode('');\n this._commitNode(textNode);\n // When setting text content, for security purposes it matters a lot\n // what the parent is. For example, <style> and <script> need to be\n // handled with care, while <span> does not. So first we need to put a\n // text node into the document, then we can sanitize its content.\n if (this._textSanitizer === undefined) {\n this._textSanitizer = createSanitizer(textNode, 'data', 'property');\n }\n value = this._textSanitizer(value);\n debugLogEvent &&\n debugLogEvent({\n kind: 'commit text',\n node: textNode,\n value,\n options: this.options,\n });\n textNode.data = value as string;\n } else {\n this._commitNode(d.createTextNode(value as string));\n debugLogEvent &&\n debugLogEvent({\n kind: 'commit text',\n node: wrap(this._$startNode).nextSibling as Text,\n value,\n options: this.options,\n });\n }\n }\n this._$committedValue = value;\n }\n\n private _commitTemplateResult(\n result: TemplateResult | CompiledTemplateResult\n ): void {\n // This property needs to remain unminified.\n const {values, ['_$litType$']: type} = result;\n // If $litType$ is a number, result is a plain TemplateResult and we get\n // the template from the template cache. If not, result is a\n // CompiledTemplateResult and _$litType$ is a CompiledTemplate and we need\n // to create the <template> element the first time we see it.\n const template: Template | CompiledTemplate =\n typeof type === 'number'\n ? this._$getTemplate(result as UncompiledTemplateResult)\n : (type.el === undefined &&\n (type.el = Template.createElement(\n trustFromTemplateString(type.h, type.h[0]),\n this.options\n )),\n type);\n\n if ((this._$committedValue as TemplateInstance)?._$template === template) {\n debugLogEvent &&\n debugLogEvent({\n kind: 'template updating',\n template,\n instance: this._$committedValue as TemplateInstance,\n parts: (this._$committedValue as TemplateInstance)._$parts,\n options: this.options,\n values,\n });\n (this._$committedValue as TemplateInstance)._update(values);\n } else {\n const instance = new TemplateInstance(template as Template, this);\n const fragment = instance._clone(this.options);\n debugLogEvent &&\n debugLogEvent({\n kind: 'template instantiated',\n template,\n instance,\n parts: instance._$parts,\n options: this.options,\n fragment,\n values,\n });\n instance._update(values);\n debugLogEvent &&\n debugLogEvent({\n kind: 'template instantiated and updated',\n template,\n instance,\n parts: instance._$parts,\n options: this.options,\n fragment,\n values,\n });\n this._commitNode(fragment);\n this._$committedValue = instance;\n }\n }\n\n // Overridden via `litHtmlPolyfillSupport` to provide platform support.\n /** @internal */\n _$getTemplate(result: UncompiledTemplateResult) {\n let template = templateCache.get(result.strings);\n if (template === undefined) {\n templateCache.set(result.strings, (template = new Template(result)));\n }\n return template;\n }\n\n private _commitIterable(value: Iterable<unknown>): void {\n // For an Iterable, we create a new InstancePart per item, then set its\n // value to the item. This is a little bit of overhead for every item in\n // an Iterable, but it lets us recurse easily and efficiently update Arrays\n // of TemplateResults that will be commonly returned from expressions like:\n // array.map((i) => html`${i}`), by reusing existing TemplateInstances.\n\n // If value is an array, then the previous render was of an\n // iterable and value will contain the ChildParts from the previous\n // render. If value is not an array, clear this part and make a new\n // array for ChildParts.\n if (!isArray(this._$committedValue)) {\n this._$committedValue = [];\n this._$clear();\n }\n\n // Lets us keep track of how many items we stamped so we can clear leftover\n // items from a previous render\n const itemParts = this._$committedValue as ChildPart[];\n let partIndex = 0;\n let itemPart: ChildPart | undefined;\n\n for (const item of value) {\n if (partIndex === itemParts.length) {\n // If no existing part, create a new one\n // TODO (justinfagnani): test perf impact of always creating two parts\n // instead of sharing parts between nodes\n // https://github.com/lit/lit/issues/1266\n itemParts.push(\n (itemPart = new ChildPart(\n this._insert(createMarker()),\n this._insert(createMarker()),\n this,\n this.options\n ))\n );\n } else {\n // Reuse an existing part\n itemPart = itemParts[partIndex];\n }\n itemPart._$setValue(item);\n partIndex++;\n }\n\n if (partIndex < itemParts.length) {\n // itemParts always have end nodes\n this._$clear(\n itemPart && wrap(itemPart._$endNode!).nextSibling,\n partIndex\n );\n // Truncate the parts array so _value reflects the current state\n itemParts.length = partIndex;\n }\n }\n\n /**\n * Removes the nodes contained within this Part from the DOM.\n *\n * @param start Start node to clear from, for clearing a subset of the part's\n * DOM (used when truncating iterables)\n * @param from When `start` is specified, the index within the iterable from\n * which ChildParts are being removed, used for disconnecting directives\n * in those Parts.\n *\n * @internal\n */\n _$clear(\n start: ChildNode | null = wrap(this._$startNode).nextSibling,\n from?: number\n ) {\n this._$notifyConnectionChanged?.(false, true, from);\n while (start !== this._$endNode) {\n // The non-null assertion is safe because if _$startNode.nextSibling is\n // null, then _$endNode is also null, and we would not have entered this\n // loop.\n const n = wrap(start!).nextSibling;\n wrap(start!).remove();\n start = n;\n }\n }\n\n /**\n * Implementation of RootPart's `isConnected`. Note that this method\n * should only be called on `RootPart`s (the `ChildPart` returned from a\n * top-level `render()` call). It has no effect on non-root ChildParts.\n * @param isConnected Whether to set\n * @internal\n */\n setConnected(isConnected: boolean) {\n if (this._$parent === undefined) {\n this.__isConnected = isConnected;\n this._$notifyConnectionChanged?.(isConnected);\n } else if (DEV_MODE) {\n throw new Error(\n 'part.setConnected() may only be called on a ' +\n 'RootPart returned from render().'\n );\n }\n }\n}\n\n/**\n * A top-level `ChildPart` returned from `render` that manages the connected\n * state of `AsyncDirective`s created throughout the tree below it.\n */\nexport interface RootPart extends ChildPart {\n /**\n * Sets the connection state for `AsyncDirective`s contained within this root\n * ChildPart.\n *\n * lit-html does not automatically monitor the connectedness of DOM rendered;\n * as such, it is the responsibility of the caller to `render` to ensure that\n * `part.setConnected(false)` is called before the part object is potentially\n * discarded, to ensure that `AsyncDirective`s have a chance to dispose of\n * any resources being held. If a `RootPart` that was previously\n * disconnected is subsequently re-connected (and its `AsyncDirective`s should\n * re-connect), `setConnected(true)` should be called.\n *\n * @param isConnected Whether directives within this tree should be connected\n * or not\n */\n setConnected(isConnected: boolean): void;\n}\n\nexport type {AttributePart};\nclass AttributePart implements Disconnectable {\n readonly type:\n | typeof ATTRIBUTE_PART\n | typeof PROPERTY_PART\n | typeof BOOLEAN_ATTRIBUTE_PART\n | typeof EVENT_PART = ATTRIBUTE_PART;\n readonly element: HTMLElement;\n readonly name: string;\n readonly options: RenderOptions | undefined;\n\n /**\n * If this attribute part represents an interpolation, this contains the\n * static strings of the interpolation. For single-value, complete bindings,\n * this is undefined.\n */\n readonly strings?: ReadonlyArray<string>;\n /** @internal */\n _$committedValue: unknown | Array<unknown> = nothing;\n /** @internal */\n __directives?: Array<Directive | undefined>;\n /** @internal */\n _$parent: Disconnectable;\n /** @internal */\n _$disconnectableChildren?: Set<Disconnectable> = undefined;\n\n protected _sanitizer: ValueSanitizer | undefined;\n\n get tagName() {\n return this.element.tagName;\n }\n\n // See comment in Disconnectable interface for why this is a getter\n get _$isConnected() {\n return this._$parent._$isConnected;\n }\n\n constructor(\n element: HTMLElement,\n name: string,\n strings: ReadonlyArray<string>,\n parent: Disconnectable,\n options: RenderOptions | undefined\n ) {\n this.element = element;\n this.name = name;\n this._$parent = parent;\n this.options = options;\n if (strings.length > 2 || strings[0] !== '' || strings[1] !== '') {\n this._$committedValue = new Array(strings.length - 1).fill(new String());\n this.strings = strings;\n } else {\n this._$committedValue = nothing;\n }\n if (ENABLE_EXTRA_SECURITY_HOOKS) {\n this._sanitizer = undefined;\n }\n }\n\n /**\n * Sets the value of this part by resolving the value from possibly multiple\n * values and static strings and committing it to the DOM.\n * If this part is single-valued, `this._strings` will be undefined, and the\n * method will be called with a single value argument. If this part is\n * multi-value, `this._strings` will be defined, and the method is called\n * with the value array of the part's owning TemplateInstance, and an offset\n * into the value array from which the values should be read.\n * This method is overloaded this way to eliminate short-lived array slices\n * of the template instance values, and allow a fast-path for single-valued\n * parts.\n *\n * @param value The part value, or an array of values for multi-valued parts\n * @param valueIndex the index to start reading values from. `undefined` for\n * single-valued parts\n * @param noCommit causes the part to not commit its value to the DOM. Used\n * in hydration to prime attribute parts with their first-rendered value,\n * but not set the attribute, and in SSR to no-op the DOM operation and\n * capture the value for serialization.\n *\n * @internal\n */\n _$setValue(\n value: unknown | Array<unknown>,\n directiveParent: DirectiveParent = this,\n valueIndex?: number,\n noCommit?: boolean\n ) {\n const strings = this.strings;\n\n // Whether any of the values has changed, for dirty-checking\n let change = false;\n\n if (strings === undefined) {\n // Single-value binding case\n value = resolveDirective(this, value, directiveParent, 0);\n change =\n !isPrimitive(value) ||\n (value !== this._$committedValue && value !== noChange);\n if (change) {\n this._$committedValue = value;\n }\n } else {\n // Interpolation case\n const values = value as Array<unknown>;\n value = strings[0];\n\n let i, v;\n for (i = 0; i < strings.length - 1; i++) {\n v = resolveDirective(this, values[valueIndex! + i], directiveParent, i);\n\n if (v === noChange) {\n // If the user-provided value is `noChange`, use the previous value\n v = (this._$committedValue as Array<unknown>)[i];\n }\n change ||=\n !isPrimitive(v) || v !== (this._$committedValue as Array<unknown>)[i];\n if (v === nothing) {\n value = nothing;\n } else if (value !== nothing) {\n value += (v ?? '') + strings[i + 1];\n }\n // We always record each value, even if one is `nothing`, for future\n // change detection.\n (this._$committedValue as Array<unknown>)[i] = v;\n }\n }\n if (change && !noCommit) {\n this._commitValue(value);\n }\n }\n\n /** @internal */\n _commitValue(value: unknown) {\n if (value === nothing) {\n (wrap(this.element) as Element).removeAttribute(this.name);\n } else {\n if (ENABLE_EXTRA_SECURITY_HOOKS) {\n if (this._sanitizer === undefined) {\n this._sanitizer = sanitizerFactoryInternal(\n this.element,\n this.name,\n 'attribute'\n );\n }\n value = this._sanitizer(value ?? '');\n }\n debugLogEvent &&\n debugLogEvent({\n kind: 'commit attribute',\n element: this.element,\n name: this.name,\n value,\n options: this.options,\n });\n (wrap(this.element) as Element).setAttribute(\n this.name,\n (value ?? '') as string\n );\n }\n }\n}\n\nexport type {PropertyPart};\nclass PropertyPart extends AttributePart {\n override readonly type = PROPERTY_PART;\n\n /** @internal */\n override _commitValue(value: unknown) {\n if (ENABLE_EXTRA_SECURITY_HOOKS) {\n if (this._sanitizer === undefined) {\n this._sanitizer = sanitizerFactoryInternal(\n this.element,\n this.name,\n 'property'\n );\n }\n value = this._sanitizer(value);\n }\n debugLogEvent &&\n debugLogEvent({\n kind: 'commit property',\n element: this.element,\n name: this.name,\n value,\n options: this.options,\n });\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (this.element as any)[this.name] = value === nothing ? undefined : value;\n }\n}\n\nexport type {BooleanAttributePart};\nclass BooleanAttributePart extends AttributePart {\n override readonly type = BOOLEAN_ATTRIBUTE_PART;\n\n /** @internal */\n override _commitValue(value: unknown) {\n debugLogEvent &&\n debugLogEvent({\n kind: 'commit boolean attribute',\n element: this.element,\n name: this.name,\n value: !!(value && value !== nothing),\n options: this.options,\n });\n (wrap(this.element) as Element).toggleAttribute(\n this.name,\n !!value && value !== nothing\n );\n }\n}\n\ntype EventListenerWithOptions = EventListenerOrEventListenerObject &\n Partial<AddEventListenerOptions>;\n\n/**\n * An AttributePart that manages an event listener via add/removeEventListener.\n *\n * This part works by adding itself as the event listener on an element, then\n * delegating to the value passed to it. This reduces the number of calls to\n * add/removeEventListener if the listener changes frequently, such as when an\n * inline function is used as a listener.\n *\n * Because event options are passed when adding listeners, we must take case\n * to add and remove the part as a listener when the event options change.\n */\nexport type {EventPart};\nclass EventPart extends AttributePart {\n override readonly type = EVENT_PART;\n\n constructor(\n element: HTMLElement,\n name: string,\n strings: ReadonlyArray<string>,\n parent: Disconnectable,\n options: RenderOptions | undefined\n ) {\n super(element, name, strings, parent, options);\n\n if (DEV_MODE && this.strings !== undefined) {\n throw new Error(\n `A \\`<${element.localName}>\\` has a \\`@${name}=...\\` listener with ` +\n 'invalid content. Event listeners in templates must have exactly ' +\n 'one expression and no surrounding text.'\n );\n }\n }\n\n // EventPart does not use the base _$setValue/_resolveValue implementation\n // since the dirty checking is more complex\n /** @internal */\n override _$setValue(\n newListener: unknown,\n directiveParent: DirectiveParent = this\n ) {\n newListener =\n resolveDirective(this, newListener, directiveParent, 0) ?? nothing;\n if (newListener === noChange) {\n return;\n }\n const oldListener = this._$committedValue;\n\n // If the new value is nothing or any options change we have to remove the\n // part as a listener.\n const shouldRemoveListener =\n (newListener === nothing && oldListener !== nothing) ||\n (newListener as EventListenerWithOptions).capture !==\n (oldListener as EventListenerWithOptions).capture ||\n (newListener as EventListenerWithOptions).once !==\n (oldListener as EventListenerWithOptions).once ||\n (newListener as EventListenerWithOptions).passive !==\n (oldListener as EventListenerWithOptions).passive;\n\n // If the new value is not nothing and we removed the listener, we have\n // to add the part as a listener.\n const shouldAddListener =\n newListener !== nothing &&\n (oldListener === nothing || shouldRemoveListener);\n\n debugLogEvent &&\n debugLogEvent({\n kind: 'commit event listener',\n element: this.element,\n name: this.name,\n value: newListener,\n options: this.options,\n removeListener: shouldRemoveListener,\n addListener: shouldAddListener,\n oldListener,\n });\n if (shouldRemoveListener) {\n this.element.removeEventListener(\n this.name,\n this,\n oldListener as EventListenerWithOptions\n );\n }\n if (shouldAddListener) {\n this.element.addEventListener(\n this.name,\n this,\n newListener as EventListenerWithOptions\n );\n }\n this._$committedValue = newListener;\n }\n\n handleEvent(event: Event) {\n if (typeof this._$committedValue === 'function') {\n this._$committedValue.call(this.options?.host ?? this.element, event);\n } else {\n (this._$committedValue as EventListenerObject).handleEvent(event);\n }\n }\n}\n\nexport type {ElementPart};\nclass ElementPart implements Disconnectable {\n readonly type = ELEMENT_PART;\n\n /** @internal */\n __directive?: Directive;\n\n // This is to ensure that every Part has a _$committedValue\n _$committedValue: undefined;\n\n /** @internal */\n _$parent!: Disconnectable;\n\n /** @internal */\n _$disconnectableChildren?: Set<Disconnectable> = undefined;\n\n options: RenderOptions | undefined;\n\n constructor(\n public element: Element,\n parent: Disconnectable,\n options: RenderOptions | undefined\n ) {\n this._$parent = parent;\n this.options = options;\n }\n\n // See comment in Disconnectable interface for why this is a getter\n get _$isConnected() {\n return this._$parent._$isConnected;\n }\n\n _$setValue(value: unknown): void {\n debugLogEvent &&\n debugLogEvent({\n kind: 'commit to element binding',\n element: this.element,\n value,\n options: this.options,\n });\n resolveDirective(this, value);\n }\n}\n\n/**\n * END USERS SHOULD NOT RELY ON THIS OBJECT.\n *\n * Private exports for use by other Lit packages, not intended for use by\n * external users.\n *\n * We currently do not make a mangled rollup build of the lit-ssr code. In order\n * to keep a number of (otherwise private) top-level exports mangled in the\n * client side code, we export a _$LH object containing those members (or\n * helper methods for accessing private fields of those members), and then\n * re-export them for use in lit-ssr. This keeps lit-ssr agnostic to whether the\n * client-side code is being used in `dev` mode or `prod` mode.\n *\n * This has a unique name, to disambiguate it from private exports in\n * lit-element, which re-exports all of lit-html.\n *\n * @private\n */\nexport const _$LH = {\n // Used in lit-ssr\n _boundAttributeSuffix: boundAttributeSuffix,\n _marker: marker,\n _markerMatch: markerMatch,\n _HTML_RESULT: HTML_RESULT,\n _getTemplateHtml: getTemplateHtml,\n // Used in tests and private-ssr-support\n _TemplateInstance: TemplateInstance,\n _isIterable: isIterable,\n _resolveDirective: resolveDirective,\n _ChildPart: ChildPart,\n _AttributePart: AttributePart,\n _BooleanAttributePart: BooleanAttributePart,\n _EventPart: EventPart,\n _PropertyPart: PropertyPart,\n _ElementPart: ElementPart,\n};\n\n// Apply polyfills if available\nconst polyfillSupport = DEV_MODE\n ? global.litHtmlPolyfillSupportDevMode\n : global.litHtmlPolyfillSupport;\npolyfillSupport?.(Template, ChildPart);\n\n// IMPORTANT: do not change the property name or the assignment expression.\n// This line will be used in regexes to search for lit-html usage.\n(global.litHtmlVersions ??= []).push('3.3.1');\nif (DEV_MODE && global.litHtmlVersions.length > 1) {\n queueMicrotask(() => {\n issueWarning!(\n 'multiple-versions',\n `Multiple versions of Lit loaded. ` +\n `Loading multiple versions is not recommended.`\n );\n });\n}\n\n/**\n * Renders a value, usually a lit-html TemplateResult, to the container.\n *\n * This example renders the text \"Hello, Zoe!\" inside a paragraph tag, appending\n * it to the container `document.body`.\n *\n * ```js\n * import {html, render} from 'lit';\n *\n * const name = \"Zoe\";\n * render(html`<p>Hello, ${name}!</p>`, document.body);\n * ```\n *\n * @param value Any [renderable\n * value](https://lit.dev/docs/templates/expressions/#child-expressions),\n * typically a {@linkcode TemplateResult} created by evaluating a template tag\n * like {@linkcode html} or {@linkcode svg}.\n * @param container A DOM container to render to. The first render will append\n * the rendered value to the container, and subsequent renders will\n * efficiently update the rendered value if the same result type was\n * previously rendered there.\n * @param options See {@linkcode RenderOptions} for options documentation.\n * @see\n * {@link https://lit.dev/docs/libraries/standalone-templates/#rendering-lit-html-templates| Rendering Lit HTML Templates}\n */\nexport const render = (\n value: unknown,\n container: HTMLElement | DocumentFragment,\n options?: RenderOptions\n): RootPart => {\n if (DEV_MODE && container == null) {\n // Give a clearer error message than\n // Uncaught TypeError: Cannot read properties of null (reading\n // '_$litPart$')\n // which reads like an internal Lit error.\n throw new TypeError(`The container to render into may not be ${container}`);\n }\n const renderId = DEV_MODE ? debugLogRenderId++ : 0;\n const partOwnerNode = options?.renderBefore ?? container;\n // This property needs to remain unminified.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let part: ChildPart = (partOwnerNode as any)['_$litPart$'];\n debugLogEvent &&\n debugLogEvent({\n kind: 'begin render',\n id: renderId,\n value,\n container,\n options,\n part,\n });\n if (part === undefined) {\n const endNode = options?.renderBefore ?? null;\n // This property needs to remain unminified.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (partOwnerNode as any)['_$litPart$'] = part = new ChildPart(\n container.insertBefore(createMarker(), endNode),\n endNode,\n undefined,\n options ?? {}\n );\n }\n part._$setValue(value);\n debugLogEvent &&\n debugLogEvent({\n kind: 'end render',\n id: renderId,\n value,\n container,\n options,\n part,\n });\n return part as RootPart;\n};\n\nif (ENABLE_EXTRA_SECURITY_HOOKS) {\n render.setSanitizer = setSanitizer;\n render.createSanitizer = createSanitizer;\n if (DEV_MODE) {\n render._testOnlyClearSanitizerFactoryDoNotCallOrElse =\n _testOnlyClearSanitizerFactoryDoNotCallOrElse;\n }\n}\n", "/**\n * Shared sort comparators for issues lists.\n * Centralizes sorting so views and stores stay consistent.\n */\n\n/**\n * @typedef {{ id: string, title?: string, status?: 'open'|'in_progress'|'closed', priority?: number, issue_type?: string, created_at?: number, updated_at?: number, closed_at?: number }} IssueLite\n */\n\n/**\n * Compare by priority asc, then created_at asc, then id asc.\n *\n * @param {IssueLite} a\n * @param {IssueLite} b\n */\nexport function cmpPriorityThenCreated(a, b) {\n const pa = a.priority ?? 2;\n const pb = b.priority ?? 2;\n if (pa !== pb) {\n return pa - pb;\n }\n const ca = a.created_at ?? 0;\n const cb = b.created_at ?? 0;\n if (ca !== cb) {\n return ca < cb ? -1 : 1;\n }\n const ida = a.id;\n const idb = b.id;\n return ida < idb ? -1 : ida > idb ? 1 : 0;\n}\n\n/**\n * Compare by closed_at desc, then id asc for stability.\n *\n * @param {IssueLite} a\n * @param {IssueLite} b\n */\nexport function cmpClosedDesc(a, b) {\n const ca = a.closed_at ?? 0;\n const cb = b.closed_at ?? 0;\n if (ca !== cb) {\n return ca < cb ? 1 : -1;\n }\n const ida = a?.id;\n const idb = b?.id;\n return ida < idb ? -1 : ida > idb ? 1 : 0;\n}\n", "/**\n * List selectors utility: compose subscription membership with issues entities\n * and apply view-specific sorting. Provides a lightweight `subscribe` that\n * triggers once per issues envelope to let views re-render.\n */\n/**\n * @typedef {{ id: string, title?: string, status?: 'open'|'in_progress'|'closed', priority?: number, issue_type?: string, created_at?: number, updated_at?: number, closed_at?: number }} IssueLite\n */\nimport { cmpClosedDesc, cmpPriorityThenCreated } from './sort.js';\n\n/**\n * Factory for list selectors.\n *\n * Source of truth is per-subscription stores providing snapshots for a given\n * client id. Central issues store fallback has been removed.\n *\n * @param {{ snapshotFor?: (client_id: string) => IssueLite[], subscribe?: (fn: () => void) => () => void }} [issue_stores]\n */\nexport function createListSelectors(issue_stores = undefined) {\n // Sorting comparators are centralized in app/data/sort.js\n\n /**\n * Get entities for a subscription id with Issues List sort (priority asc \u2192 created asc).\n *\n * @param {string} client_id\n * @returns {IssueLite[]}\n */\n function selectIssuesFor(client_id) {\n if (!issue_stores || typeof issue_stores.snapshotFor !== 'function') {\n return [];\n }\n return issue_stores\n .snapshotFor(client_id)\n .slice()\n .sort(cmpPriorityThenCreated);\n }\n\n /**\n * Get entities for a Board column with column-specific sort.\n *\n * @param {string} client_id\n * @param {'ready'|'blocked'|'in_progress'|'closed'} mode\n * @returns {IssueLite[]}\n */\n function selectBoardColumn(client_id, mode) {\n const arr =\n issue_stores && issue_stores.snapshotFor\n ? issue_stores.snapshotFor(client_id).slice()\n : [];\n if (mode === 'in_progress') {\n arr.sort(cmpPriorityThenCreated);\n } else if (mode === 'closed') {\n arr.sort(cmpClosedDesc);\n } else {\n // ready/blocked share the same sort\n arr.sort(cmpPriorityThenCreated);\n }\n return arr;\n }\n\n /**\n * Get children for an epic subscribed as client id `epic:${id}`.\n * Sorted as Issues List (priority asc \u2192 created asc).\n *\n * @param {string} epic_id\n * @returns {IssueLite[]}\n */\n function selectEpicChildren(epic_id) {\n if (!issue_stores || typeof issue_stores.snapshotFor !== 'function') {\n return [];\n }\n // Epic detail subscription uses client id `detail:<id>` and contains the\n // epic entity with a `dependents` array. Render children from that list.\n const arr = /** @type {any[]} */ (\n issue_stores.snapshotFor(`detail:${epic_id}`) || []\n );\n const epic = arr.find((it) => String(it?.id || '') === String(epic_id));\n const dependents = Array.isArray(epic?.dependents) ? epic.dependents : [];\n return /** @type {IssueLite[]} */ (\n dependents.slice().sort(cmpPriorityThenCreated)\n );\n }\n\n /**\n * Subscribe for re-render; triggers once per issues envelope.\n *\n * @param {() => void} fn\n * @returns {() => void}\n */\n function subscribe(fn) {\n if (issue_stores && typeof issue_stores.subscribe === 'function') {\n return issue_stores.subscribe(fn);\n }\n return () => {};\n }\n\n return {\n selectIssuesFor,\n selectBoardColumn,\n selectEpicChildren,\n subscribe\n };\n}\n", "/**\n * Debug logger helper for the browser app.\n */\nimport createDebug from 'debug';\n\n/**\n * Create a namespaced logger.\n *\n * @param {string} ns - Module namespace suffix (e.g., 'ws', 'views:list').\n */\nexport function debug(ns) {\n return createDebug(`beads-ui:${ns}`);\n}\n", "/**\n * @import { MessageType } from '../protocol.js'\n */\nimport { debug } from '../utils/logging.js';\n\n/**\n * Data layer: typed wrappers around the ws transport for mutations and\n * single-issue fetch. List reads have been removed in favor of push-only\n * stores and selectors (see docs/adr/001-push-only-lists.md).\n *\n * @param {(type: MessageType, payload?: unknown) => Promise<unknown>} transport - Request/response function.\n * @returns {{ updateIssue: (input: { id: string, title?: string, acceptance?: string, notes?: string, design?: string, status?: 'open'|'in_progress'|'closed', priority?: number, assignee?: string }) => Promise<unknown> }}\n */\nexport function createDataLayer(transport) {\n const log = debug('data');\n /**\n * Update issue fields by dispatching specific mutations.\n * Supported fields: title, acceptance, notes, design, status, priority, assignee.\n * Returns the updated issue on success.\n *\n * @param {{ id: string, title?: string, acceptance?: string, notes?: string, design?: string, status?: 'open'|'in_progress'|'closed', priority?: number, assignee?: string }} input\n * @returns {Promise<unknown>}\n */\n async function updateIssue(input) {\n const { id } = input;\n\n log('updateIssue %s %o', id, Object.keys(input));\n\n /** @type {unknown} */\n let last = null;\n if (typeof input.title === 'string') {\n last = await transport('edit-text', {\n id,\n field: 'title',\n value: input.title\n });\n }\n if (typeof input.acceptance === 'string') {\n last = await transport('edit-text', {\n id,\n field: 'acceptance',\n value: input.acceptance\n });\n }\n if (typeof input.notes === 'string') {\n last = await transport('edit-text', {\n id,\n field: 'notes',\n value: input.notes\n });\n }\n if (typeof input.design === 'string') {\n last = await transport('edit-text', {\n id,\n field: 'design',\n value: input.design\n });\n }\n if (typeof input.status === 'string') {\n last = await transport('update-status', {\n id,\n status: input.status\n });\n }\n if (typeof input.priority === 'number') {\n last = await transport('update-priority', {\n id,\n priority: input.priority\n });\n }\n // type updates are not supported via UI\n if (typeof input.assignee === 'string') {\n last = await transport('update-assignee', {\n id,\n assignee: input.assignee\n });\n }\n log('updateIssue done %s', id);\n return last;\n }\n\n return {\n updateIssue\n };\n}\n", "/**\n * @import { SubscriptionIssueStore, SubscriptionIssueStoreOptions } from '../../types/subscription-issue-store.js'\n */\nimport { debug } from '../utils/logging.js';\nimport { cmpPriorityThenCreated } from './sort.js';\n\n/**\n * Per-subscription issue store. Holds full Issue objects and exposes a\n * deterministic, read-only snapshot for rendering. Applies snapshot/upsert/\n * delete messages in revision order and preserves object identity per id.\n */\n\n/**\n * Create a SubscriptionIssueStore for a given subscription id.\n *\n * @param {string} id\n * @param {SubscriptionIssueStoreOptions} [options]\n * @returns {SubscriptionIssueStore}\n */\nexport function createSubscriptionIssueStore(id, options = {}) {\n const log = debug(`issue-store:${id}`);\n /** @type {Map<string, any>} */\n const items_by_id = new Map();\n /** @type {any[]} */\n let ordered = [];\n /** @type {number} */\n let last_revision = 0;\n /** @type {Set<() => void>} */\n const listeners = new Set();\n /** @type {boolean} */\n let is_disposed = false;\n /** @type {(a:any,b:any)=>number} */\n const sort = options.sort || cmpPriorityThenCreated;\n\n function emit() {\n for (const fn of Array.from(listeners)) {\n try {\n fn();\n } catch {\n // ignore listener errors\n }\n }\n }\n\n function rebuildOrdered() {\n ordered = Array.from(items_by_id.values()).sort(sort);\n }\n\n /**\n * Apply snapshot/upsert/delete in revision order. Snapshots reset state.\n * - Ignore messages with revision <= last_revision (except snapshot which resets first).\n * - Preserve object identity when updating an existing item by mutating\n * fields in place rather than replacing the object reference.\n *\n * @param {{ type: 'snapshot'|'upsert'|'delete', id: string, revision: number, issues?: any[], issue?: any, issue_id?: string }} msg\n */\n function applyPush(msg) {\n if (is_disposed) {\n return;\n }\n if (!msg || msg.id !== id) {\n return;\n }\n const rev = Number(msg.revision) || 0;\n log('apply %s rev=%d', msg.type, rev);\n // Ignore stale messages for all types, including snapshots\n if (rev <= last_revision && msg.type !== 'snapshot') {\n return; // stale or duplicate non-snapshot\n }\n if (msg.type === 'snapshot') {\n if (rev <= last_revision) {\n return; // ignore stale snapshot\n }\n items_by_id.clear();\n const items = Array.isArray(msg.issues) ? msg.issues : [];\n for (const it of items) {\n if (it && typeof it.id === 'string' && it.id.length > 0) {\n items_by_id.set(it.id, it);\n }\n }\n rebuildOrdered();\n last_revision = rev;\n emit();\n return;\n }\n if (msg.type === 'upsert') {\n const it = msg.issue;\n if (it && typeof it.id === 'string' && it.id.length > 0) {\n const existing = items_by_id.get(it.id);\n if (!existing) {\n items_by_id.set(it.id, it);\n } else {\n // Guard with updated_at; prefer newer\n const prev_ts = Number.isFinite(existing.updated_at)\n ? /** @type {number} */ (existing.updated_at)\n : 0;\n const next_ts = Number.isFinite(it.updated_at)\n ? /** @type {number} */ (it.updated_at)\n : 0;\n if (prev_ts <= next_ts) {\n // Mutate existing object to preserve reference\n for (const k of Object.keys(existing)) {\n if (!(k in it)) {\n // remove keys that disappeared to avoid stale fields\n delete existing[k];\n }\n }\n for (const [k, v] of Object.entries(it)) {\n // @ts-ignore - dynamic assignment\n existing[k] = v;\n }\n } else {\n // stale by timestamp; ignore\n }\n }\n rebuildOrdered();\n }\n last_revision = rev;\n emit();\n } else if (msg.type === 'delete') {\n const rid = String(msg.issue_id || '');\n if (rid) {\n items_by_id.delete(rid);\n rebuildOrdered();\n }\n last_revision = rev;\n emit();\n }\n }\n\n return {\n id,\n /**\n * @param {() => void} fn\n */\n subscribe(fn) {\n listeners.add(fn);\n return () => {\n listeners.delete(fn);\n };\n },\n applyPush,\n snapshot() {\n // Return as read-only view; callers must not mutate\n return ordered;\n },\n size() {\n return items_by_id.size;\n },\n /**\n * @param {string} xid\n */\n getById(xid) {\n return items_by_id.get(xid);\n },\n dispose() {\n is_disposed = true;\n items_by_id.clear();\n ordered = [];\n listeners.clear();\n last_revision = 0;\n }\n };\n}\n", "/**\n * @import { MessageType } from '../protocol.js'\n */\nimport { debug } from '../utils/logging.js';\n\n/**\n * Client-side list subscription store.\n *\n * Maintains per-subscription state keyed by client-provided `id`.\n * Applies server `list-delta` events per subscription key and exposes simple\n * selectors for rendering.\n */\n\n/**\n * @typedef {{ type: string, params?: Record<string, string|number|boolean> }} SubscriptionSpec\n */\n\n/**\n * Generate a stable subscription key string from a spec.\n * Mirrors server `keyOf` implementation (sorted params, URLSearchParams).\n *\n * @param {SubscriptionSpec} spec\n * @returns {string}\n */\nexport function subKeyOf(spec) {\n const type = String(spec.type || '').trim();\n /** @type {Record<string, string>} */\n const flat = {};\n if (spec.params && typeof spec.params === 'object') {\n const keys = Object.keys(spec.params).sort();\n for (const k of keys) {\n const v = spec.params[k];\n flat[k] = String(v);\n }\n }\n const enc = new URLSearchParams(flat).toString();\n return enc.length > 0 ? `${type}?${enc}` : type;\n}\n\n/**\n * Create a list subscription store.\n *\n * Wiring:\n * - Use `subscribeList` to register a subscription and send the request.\n *\n * Selectors are synchronous and return derived state by client id.\n *\n * @param {(type: MessageType, payload?: unknown) => Promise<unknown>} send - ws send.\n */\nexport function createSubscriptionStore(send) {\n const log = debug('subs');\n /** @type {Map<string, { key: string, itemsById: Map<string, true> }>} */\n const subs_by_id = new Map();\n /** @type {Map<string, Set<string>>} */\n const ids_by_key = new Map();\n\n /**\n * Apply a delta to all client ids mapped to a given key.\n *\n * @param {string} key\n * @param {{ added: string[], updated: string[], removed: string[] }} delta\n */\n function applyDelta(key, delta) {\n log(\n 'applyDelta %s +%d ~%d -%d',\n key,\n (delta.added || []).length,\n (delta.updated || []).length,\n (delta.removed || []).length\n );\n const id_set = ids_by_key.get(key);\n if (!id_set || id_set.size === 0) {\n return;\n }\n const added = Array.isArray(delta.added) ? delta.added : [];\n const updated = Array.isArray(delta.updated) ? delta.updated : [];\n const removed = Array.isArray(delta.removed) ? delta.removed : [];\n\n for (const client_id of Array.from(id_set)) {\n const entry = subs_by_id.get(client_id);\n if (!entry) {\n continue;\n }\n const items = entry.itemsById;\n for (const id of added) {\n if (typeof id === 'string' && id.length > 0) {\n items.set(id, true);\n }\n }\n for (const id of updated) {\n if (typeof id === 'string' && id.length > 0) {\n items.set(id, true);\n }\n }\n for (const id of removed) {\n if (typeof id === 'string' && id.length > 0) {\n items.delete(id);\n }\n }\n }\n }\n\n /**\n * Subscribe to a list spec with a client-provided id.\n * Returns an unsubscribe function.\n * Creates an empty items store immediately; server will publish deltas.\n *\n * @param {string} client_id\n * @param {SubscriptionSpec} spec\n * @returns {Promise<() => Promise<void>>}\n */\n async function subscribeList(client_id, spec) {\n const key = subKeyOf(spec);\n log('subscribe %s key=%s', client_id, key);\n // Initialize local entry immediately to capture early deltas\n if (!subs_by_id.has(client_id)) {\n subs_by_id.set(client_id, { key, itemsById: new Map() });\n } else {\n // Update key mapping if client id is reused for a different spec\n const prev = subs_by_id.get(client_id);\n if (prev && prev.key !== key) {\n const prev_ids = ids_by_key.get(prev.key);\n if (prev_ids) {\n prev_ids.delete(client_id);\n if (prev_ids.size === 0) {\n ids_by_key.delete(prev.key);\n }\n }\n subs_by_id.set(client_id, { key, itemsById: new Map() });\n }\n }\n if (!ids_by_key.has(key)) {\n ids_by_key.set(key, new Set());\n }\n const set = ids_by_key.get(key);\n if (set) {\n set.add(client_id);\n }\n try {\n await send('subscribe-list', {\n id: client_id,\n type: spec.type,\n params: spec.params\n });\n } catch (err) {\n const entry = subs_by_id.get(client_id) || null;\n if (entry) {\n const subscribers = ids_by_key.get(entry.key);\n if (subscribers) {\n subscribers.delete(client_id);\n if (subscribers.size === 0) {\n ids_by_key.delete(entry.key);\n }\n }\n }\n subs_by_id.delete(client_id);\n throw err;\n }\n\n return async () => {\n log('unsubscribe %s key=%s', client_id, key);\n try {\n await send('unsubscribe-list', { id: client_id });\n } catch {\n // ignore transport errors on unsubscribe\n }\n // Cleanup local mappings\n const entry = subs_by_id.get(client_id) || null;\n if (entry) {\n const s = ids_by_key.get(entry.key);\n if (s) {\n s.delete(client_id);\n if (s.size === 0) {\n ids_by_key.delete(entry.key);\n }\n }\n }\n subs_by_id.delete(client_id);\n };\n }\n\n /**\n * Selectors by client id.\n */\n const selectors = {\n /**\n * Get an array of item ids for a subscription.\n *\n * @param {string} client_id\n * @returns {string[]}\n */\n getIds(client_id) {\n const entry = subs_by_id.get(client_id);\n if (!entry) {\n return [];\n }\n return Array.from(entry.itemsById.keys());\n },\n /**\n * Check if an id exists in a subscription.\n *\n * @param {string} client_id\n * @param {string} id\n * @returns {boolean}\n */\n has(client_id, id) {\n const entry = subs_by_id.get(client_id);\n if (!entry) {\n return false;\n }\n return entry.itemsById.has(id);\n },\n /**\n * Count items for a subscription.\n *\n * @param {string} client_id\n * @returns {number}\n */\n count(client_id) {\n const entry = subs_by_id.get(client_id);\n return entry ? entry.itemsById.size : 0;\n },\n /**\n * Return a shallow object copy `{ [id]: true }` for rendering helpers.\n *\n * @param {string} client_id\n * @returns {Record<string, true>}\n */\n getItemsById(client_id) {\n const entry = subs_by_id.get(client_id);\n /** @type {Record<string, true>} */\n const out = {};\n if (!entry) {\n return out;\n }\n for (const id of entry.itemsById.keys()) {\n out[id] = true;\n }\n return out;\n }\n };\n\n return {\n subscribeList,\n // test/diagnostics helpers\n _applyDelta: applyDelta,\n _subKeyOf: subKeyOf,\n selectors\n };\n}\n", "/**\n * @import { SubscriptionIssueStoreOptions } from '../../types/subscription-issue-store.js'\n * @import { IssueLite } from './list-selectors.js'\n */\nimport { debug } from '../utils/logging.js';\nimport { createSubscriptionIssueStore } from './subscription-issue-store.js';\nimport { subKeyOf } from './subscriptions-store.js';\n\n/**\n * Registry managing per-subscription issue stores. Stores receive full-issue\n * push envelopes (snapshot/upsert/delete) per subscription id and expose\n * read-only snapshots for rendering.\n */\nexport function createSubscriptionIssueStores() {\n const log = debug('issue-stores');\n /** @type {Map<string, ReturnType<typeof createSubscriptionIssueStore>>} */\n const stores_by_id = new Map();\n /** @type {Map<string, string>} */\n const key_by_id = new Map();\n /** @type {Set<() => void>} */\n const listeners = new Set();\n /** @type {Map<string, () => void>} */\n const store_unsubs = new Map();\n\n function emit() {\n for (const fn of Array.from(listeners)) {\n try {\n fn();\n } catch {\n // ignore\n }\n }\n }\n\n /**\n * Ensure a store exists for client_id and attach a listener that fans out\n * store-level updates to global listeners.\n *\n * @param {string} client_id\n * @param {{ type: string, params?: Record<string, string|number|boolean> }} [spec]\n * @param {SubscriptionIssueStoreOptions} [options]\n */\n function register(client_id, spec, options) {\n const next_key = spec ? subKeyOf(spec) : '';\n const prev_key = key_by_id.get(client_id) || '';\n const has_store = stores_by_id.has(client_id);\n log('register %s key=%s (prev=%s)', client_id, next_key, prev_key);\n // If the subscription spec changed for an existing client id, replace the\n // underlying store to reset revision state and avoid ignoring a fresh\n // snapshot with a lower revision (different server list).\n if (has_store && prev_key && next_key && prev_key !== next_key) {\n const prev_store = stores_by_id.get(client_id);\n if (prev_store) {\n try {\n prev_store.dispose();\n } catch {\n // ignore\n }\n }\n const off_prev = store_unsubs.get(client_id);\n if (off_prev) {\n try {\n off_prev();\n } catch {\n // ignore\n }\n store_unsubs.delete(client_id);\n }\n const new_store = createSubscriptionIssueStore(client_id, options);\n stores_by_id.set(client_id, new_store);\n const off_new = new_store.subscribe(() => emit());\n store_unsubs.set(client_id, off_new);\n } else if (!has_store) {\n const store = createSubscriptionIssueStore(client_id, options);\n stores_by_id.set(client_id, store);\n // Fan out per-store events to global subscribers\n const off = store.subscribe(() => emit());\n store_unsubs.set(client_id, off);\n }\n key_by_id.set(client_id, next_key);\n return () => unregister(client_id);\n }\n\n /**\n * @param {string} client_id\n */\n function unregister(client_id) {\n log('unregister %s', client_id);\n key_by_id.delete(client_id);\n const store = stores_by_id.get(client_id);\n if (store) {\n store.dispose();\n stores_by_id.delete(client_id);\n }\n const off = store_unsubs.get(client_id);\n if (off) {\n try {\n off();\n } catch {\n // ignore\n }\n store_unsubs.delete(client_id);\n }\n }\n\n return {\n register,\n unregister,\n /**\n * @param {string} client_id\n */\n getStore(client_id) {\n return stores_by_id.get(client_id) || null;\n },\n /**\n * @param {string} client_id\n * @returns {IssueLite[]}\n */\n snapshotFor(client_id) {\n const s = stores_by_id.get(client_id);\n return s ? /** @type {IssueLite[]} */ (s.snapshot().slice()) : [];\n },\n /**\n * @param {() => void} fn\n */\n subscribe(fn) {\n listeners.add(fn);\n return () => listeners.delete(fn);\n }\n // No recompute helpers in vNext; stores are updated directly via push\n };\n}\n", "/**\n * Build a canonical issue hash that retains the view.\n *\n * @param {'issues'|'epics'|'board'} view\n * @param {string} id\n */\nexport function issueHashFor(view, id) {\n const v = view === 'epics' || view === 'board' ? view : 'issues';\n return `#/${v}?issue=${encodeURIComponent(id)}`;\n}\n", "import { issueHashFor } from './utils/issue-url.js';\nimport { debug } from './utils/logging.js';\n\n/**\n * Hash-based router for tabs (issues/epics/board) and deep-linked issue ids.\n */\n\n/**\n * Parse an application hash and extract the selected issue id.\n * Supports canonical form \"#/(issues|epics|board)?issue=<id>\" and legacy\n * \"#/issue/<id>\" which we will rewrite to the canonical form.\n *\n * @param {string} hash\n * @returns {string | null}\n */\nexport function parseHash(hash) {\n const h = String(hash || '');\n // Extract the fragment sans leading '#'\n const frag = h.startsWith('#') ? h.slice(1) : h;\n const qIndex = frag.indexOf('?');\n const query = qIndex >= 0 ? frag.slice(qIndex + 1) : '';\n if (query) {\n const params = new URLSearchParams(query);\n const id = params.get('issue');\n if (id) {\n return decodeURIComponent(id);\n }\n }\n // Legacy pattern: #/issue/<id>\n const m = /^\\/issue\\/([^\\s?#]+)/.exec(frag);\n return m && m[1] ? decodeURIComponent(m[1]) : null;\n}\n\n/**\n * Parse the current view from hash.\n *\n * @param {string} hash\n * @returns {'issues'|'epics'|'board'}\n */\nexport function parseView(hash) {\n const h = String(hash || '');\n if (/^#\\/epics(\\b|\\/|$)/.test(h)) {\n return 'epics';\n }\n if (/^#\\/board(\\b|\\/|$)/.test(h)) {\n return 'board';\n }\n // Default to issues (also covers #/issues and unknown/empty)\n return 'issues';\n}\n\n/**\n * @param {{ getState: () => any, setState: (patch: any) => void }} store\n */\nexport function createHashRouter(store) {\n const log = debug('router');\n /** @type {(ev?: HashChangeEvent) => any} */\n const onHashChange = () => {\n const hash = window.location.hash || '';\n // Rewrite legacy #/issue/<id> to canonical #/issues?issue=<id>\n const legacyMatch = /^#\\/issue\\/([^\\s?#]+)/.exec(hash);\n if (legacyMatch && legacyMatch[1]) {\n const id = decodeURIComponent(legacyMatch[1]);\n // Update state immediately for consumers expecting sync selection\n store.setState({ selected_id: id, view: 'issues' });\n const next = `#/issues?issue=${encodeURIComponent(id)}`;\n if (window.location.hash !== next) {\n window.location.hash = next;\n return; // will trigger handler again\n }\n }\n const id = parseHash(hash);\n const view = parseView(hash);\n log('hash change \u2192 view=%s id=%s', view, id);\n store.setState({ selected_id: id, view });\n };\n\n return {\n start() {\n window.addEventListener('hashchange', onHashChange);\n onHashChange();\n },\n stop() {\n window.removeEventListener('hashchange', onHashChange);\n },\n /**\n * @param {string} id\n */\n gotoIssue(id) {\n // Keep current view in hash and append issue param via helper\n const s = store.getState ? store.getState() : { view: 'issues' };\n const view = s.view || 'issues';\n const next = issueHashFor(view, id);\n log('goto issue %s (view=%s)', id, view);\n if (window.location.hash !== next) {\n window.location.hash = next;\n } else {\n // Force state update even if hash is the same\n store.setState({ selected_id: id, view });\n }\n },\n /**\n * Navigate to a top-level view.\n *\n * @param {'issues'|'epics'|'board'} view\n */\n /**\n * @param {'issues'|'epics'|'board'} view\n */\n gotoView(view) {\n const s = store.getState ? store.getState() : { selected_id: null };\n const id = s.selected_id;\n const next = id ? issueHashFor(view, id) : `#/${view}`;\n log('goto view %s (id=%s)', view, id || '');\n if (window.location.hash !== next) {\n window.location.hash = next;\n } else {\n store.setState({ view, selected_id: null });\n }\n }\n };\n}\n", "/**\n * Minimal app state store with subscription.\n */\nimport { debug } from './utils/logging.js';\n\n/**\n * @typedef {'all'|'open'|'in_progress'|'closed'|'ready'} StatusFilter\n */\n\n/**\n * @typedef {{ status: StatusFilter, search: string, type: string }} Filters\n */\n\n/**\n * @typedef {'issues'|'epics'|'board'} ViewName\n */\n\n/**\n * @typedef {'today'|'3'|'7'} ClosedFilter\n */\n\n/**\n * @typedef {{ closed_filter: ClosedFilter }} BoardState\n */\n\n/**\n * @typedef {Object} WorkspaceInfo\n * @property {string} path - Full path to workspace\n * @property {string} database - Path to the database file\n * @property {number} [pid] - Process ID of the daemon\n * @property {string} [version] - Version of beads\n */\n\n/**\n * @typedef {Object} WorkspaceState\n * @property {WorkspaceInfo | null} current - Currently active workspace\n * @property {WorkspaceInfo[]} available - All available workspaces\n */\n\n/**\n * @typedef {{ selected_id: string | null, view: ViewName, filters: Filters, board: BoardState, workspace: WorkspaceState }} AppState\n */\n\n/**\n * Create a simple store for application state.\n *\n * @param {Partial<AppState>} [initial]\n * @returns {{ getState: () => AppState, setState: (patch: { selected_id?: string | null, filters?: Partial<Filters>, workspace?: Partial<WorkspaceState> }) => void, subscribe: (fn: (s: AppState) => void) => () => void }}\n */\nexport function createStore(initial = {}) {\n const log = debug('state');\n /** @type {AppState} */\n let state = {\n selected_id: initial.selected_id ?? null,\n view: initial.view ?? 'issues',\n filters: {\n status: initial.filters?.status ?? 'all',\n search: initial.filters?.search ?? '',\n type:\n typeof initial.filters?.type === 'string' ? initial.filters?.type : ''\n },\n board: {\n closed_filter:\n initial.board?.closed_filter === '3' ||\n initial.board?.closed_filter === '7' ||\n initial.board?.closed_filter === 'today'\n ? initial.board?.closed_filter\n : 'today'\n },\n workspace: {\n current: initial.workspace?.current ?? null,\n available: initial.workspace?.available ?? []\n }\n };\n\n /** @type {Set<(s: AppState) => void>} */\n const subs = new Set();\n\n function emit() {\n for (const fn of Array.from(subs)) {\n try {\n fn(state);\n } catch {\n // ignore\n }\n }\n }\n\n return {\n getState() {\n return state;\n },\n /**\n * Update state. Nested filters can be partial.\n *\n * @param {{ selected_id?: string | null, filters?: Partial<Filters>, board?: Partial<BoardState>, workspace?: Partial<WorkspaceState> }} patch\n */\n setState(patch) {\n /** @type {AppState} */\n const next = {\n ...state,\n ...patch,\n filters: { ...state.filters, ...(patch.filters || {}) },\n board: { ...state.board, ...(patch.board || {}) },\n workspace: {\n current:\n patch.workspace?.current !== undefined\n ? patch.workspace.current\n : state.workspace.current,\n available:\n patch.workspace?.available !== undefined\n ? patch.workspace.available\n : state.workspace.available\n }\n };\n // Avoid emitting if nothing changed (shallow compare)\n const workspace_changed =\n next.workspace.current?.path !== state.workspace.current?.path ||\n next.workspace.available.length !== state.workspace.available.length;\n if (\n next.selected_id === state.selected_id &&\n next.view === state.view &&\n next.filters.status === state.filters.status &&\n next.filters.search === state.filters.search &&\n next.filters.type === state.filters.type &&\n next.board.closed_filter === state.board.closed_filter &&\n !workspace_changed\n ) {\n return;\n }\n state = next;\n log('state change %o', {\n selected_id: state.selected_id,\n view: state.view,\n filters: state.filters,\n board: state.board,\n workspace: state.workspace.current?.path\n });\n emit();\n },\n subscribe(fn) {\n subs.add(fn);\n return () => subs.delete(fn);\n }\n };\n}\n", "/**\n * @import { MessageType } from '../protocol.js'\n */\nimport { debug } from './logging.js';\n\n/**\n * Track in-flight UI actions and toggle a bound indicator element.\n *\n * @param {HTMLElement | null} mount_element\n * @returns {{ wrapSend: (fn: (type: MessageType, payload?: unknown) => Promise<unknown>) => (type: MessageType, payload?: unknown) => Promise<unknown>, start: () => void, done: () => void, getCount: () => number, getActiveRequests: () => Array<{ id: number, type: string, elapsed_ms: number }> }}\n */\nexport function createActivityIndicator(mount_element) {\n const log = debug('activity');\n /** @type {number} */\n let pending_count = 0;\n /** @type {Map<number, { type: string, start_ts: number }>} */\n const active_requests = new Map();\n /** @type {number} */\n let next_request_id = 1;\n\n function render() {\n if (!mount_element) {\n return;\n }\n const is_active = pending_count > 0;\n mount_element.toggleAttribute('hidden', !is_active);\n mount_element.setAttribute('aria-busy', is_active ? 'true' : 'false');\n }\n\n function start() {\n pending_count += 1;\n log('start count=%d', pending_count);\n render();\n }\n\n function done() {\n const prev = pending_count;\n pending_count = Math.max(0, pending_count - 1);\n if (prev <= 0) {\n log('done called but count was already %d', prev);\n } else {\n log('done count=%d\u2192%d', prev, pending_count);\n }\n render();\n }\n\n /**\n * Wrap a transport-style send function to track activity.\n * Includes a safety timeout to prevent the loading indicator from getting stuck\n * if a request hangs due to network issues or server problems.\n *\n * @param {(type: MessageType, payload?: unknown) => Promise<unknown>} send_fn\n * @returns {(type: MessageType, payload?: unknown) => Promise<unknown>}\n */\n function wrapSend(send_fn) {\n // Safety timeout: if a request takes longer than this, force decrement the counter\n const SAFETY_TIMEOUT_MS = 30000; // 30 seconds\n\n return async (type, payload) => {\n const req_id = next_request_id++;\n const start_ts = Date.now();\n active_requests.set(req_id, { type, start_ts });\n log(\n 'request start id=%d type=%s count=%d',\n req_id,\n type,\n pending_count + 1\n );\n start();\n\n // Track if we've already called done() for this request\n let completed = false;\n const markComplete = () => {\n if (!completed) {\n completed = true;\n active_requests.delete(req_id);\n done();\n }\n };\n\n // Safety timeout: force decrement if request takes too long\n const timeout_id = setTimeout(() => {\n if (!completed) {\n log(\n 'request TIMEOUT id=%d type=%s elapsed=%dms',\n req_id,\n type,\n Date.now() - start_ts\n );\n markComplete();\n }\n }, SAFETY_TIMEOUT_MS);\n\n try {\n const result = await send_fn(type, payload);\n const elapsed = Date.now() - start_ts;\n log('request done id=%d type=%s elapsed=%dms', req_id, type, elapsed);\n return result;\n } catch (err) {\n const elapsed = Date.now() - start_ts;\n log(\n 'request error id=%d type=%s elapsed=%dms err=%o',\n req_id,\n type,\n elapsed,\n err\n );\n throw err;\n } finally {\n clearTimeout(timeout_id);\n markComplete();\n }\n };\n }\n\n render();\n\n return {\n wrapSend,\n start,\n done,\n getCount: () => pending_count,\n /**\n * Get details about active requests (for debugging stuck indicators).\n *\n * @returns {Array<{ id: number, type: string, elapsed_ms: number }>}\n */\n getActiveRequests: () => {\n const now = Date.now();\n return Array.from(active_requests.entries()).map(([id, info]) => ({\n id,\n type: info.type,\n elapsed_ms: now - info.start_ts\n }));\n }\n };\n}\n", "/**\n * Show a transient global toast message anchored to the viewport.\n *\n * @param {string} text - Message text.\n * @param {'info'|'success'|'error'} [variant] - Visual variant.\n * @param {number} [duration_ms] - Auto-dismiss delay in milliseconds.\n */\nexport function showToast(text, variant = 'info', duration_ms = 2800) {\n const el = document.createElement('div');\n el.className = 'toast';\n el.textContent = text;\n el.style.position = 'fixed';\n el.style.right = '12px';\n el.style.bottom = '12px';\n el.style.zIndex = '1000';\n el.style.color = '#fff';\n el.style.padding = '8px 10px';\n el.style.borderRadius = '4px';\n el.style.fontSize = '12px';\n if (variant === 'success') {\n el.style.background = '#156d36';\n } else if (variant === 'error') {\n el.style.background = '#9f2011';\n } else {\n el.style.background = 'rgba(0,0,0,0.85)';\n }\n (document.body || document.documentElement).appendChild(el);\n setTimeout(() => {\n try {\n el.remove();\n } catch {\n /* ignore */\n }\n }, duration_ms);\n}\n", "/**\n * Create a reusable, copy-to-clipboard issue ID renderer.\n * Looks like the current inline ID (monospace `#123`) but acts as a button\n * that copies the full, prefixed ID (e.g., `UI-123`) when activated.\n * Shows transient \"Copied\" feedback and then restores the ID.\n *\n * @param {string} id - Full issue id including the prefix (e.g., \"UI-123\").\n * @param {{ class_name?: string, duration_ms?: number }} [opts]\n * @returns {HTMLButtonElement}\n */\nexport function createIssueIdRenderer(id, opts) {\n /** @type {number} */\n const duration =\n typeof opts?.duration_ms === 'number' ? opts.duration_ms : 1200;\n /** @type {HTMLButtonElement} */\n const btn = document.createElement('button');\n // Visual: match inline ID look; keep it neutral and text-like\n btn.className =\n (opts?.class_name ? opts.class_name + ' ' : '') + 'mono id-copy';\n btn.type = 'button';\n btn.setAttribute('aria-live', 'polite');\n btn.setAttribute('title', 'Copy issue ID');\n btn.setAttribute('aria-label', `Copy issue ID ${id}`);\n btn.textContent = id;\n\n /** Copy handler with feedback. */\n async function doCopy() {\n try {\n let copied = false;\n if (\n navigator.clipboard &&\n typeof navigator.clipboard.writeText === 'function'\n ) {\n await navigator.clipboard.writeText(String(id));\n copied = true;\n } else {\n // Fallback for non-secure contexts (HTTP, non-localhost)\n // where navigator.clipboard is undefined.\n const ta = document.createElement('textarea');\n ta.value = String(id);\n ta.style.position = 'fixed';\n ta.style.left = '-9999px';\n ta.style.opacity = '0';\n // Append inside the nearest open <dialog> if any \u2014 showModal()\n // creates a top-layer that makes document.body inert.\n const container = btn.closest('dialog[open]') || document.body;\n container.appendChild(ta);\n ta.focus();\n ta.select();\n try {\n copied = document.execCommand('copy');\n } finally {\n container.removeChild(ta);\n }\n }\n if (copied) {\n btn.textContent = 'Copied';\n const oldAria = btn.getAttribute('aria-label') || '';\n btn.setAttribute('aria-label', 'Copied');\n setTimeout(\n () => {\n btn.textContent = id;\n btn.setAttribute('aria-label', oldAria);\n },\n Math.max(80, duration)\n );\n }\n } catch {\n // On failure, leave text as-is; no throw to avoid disruptive UX\n }\n }\n\n btn.addEventListener('click', (ev) => {\n ev.preventDefault();\n ev.stopPropagation();\n void doCopy();\n });\n btn.addEventListener('keydown', (ev) => {\n // Ensure keyboard activation works even in non-interactive test envs\n if (ev.key === 'Enter' || ev.key === ' ') {\n ev.preventDefault();\n ev.stopPropagation();\n void doCopy();\n }\n });\n\n return btn;\n}\n", "export const priority_levels = ['Critical', 'High', 'Medium', 'Low', 'Backlog'];\n", "import { priority_levels } from './priority.js';\n\n/**\n * Create a colored badge for a priority value (0..4).\n *\n * @param {number | null | undefined} priority\n * @returns {HTMLSpanElement}\n */\nexport function createPriorityBadge(priority) {\n const p = typeof priority === 'number' ? priority : 2;\n const el = document.createElement('span');\n el.className = 'priority-badge';\n el.classList.add(`is-p${Math.max(0, Math.min(4, p))}`);\n el.setAttribute('role', 'img');\n const label = labelForPriority(p);\n el.setAttribute('title', label);\n el.setAttribute('aria-label', `Priority: ${label}`);\n el.textContent = emojiForPriority(p) + ' ' + label;\n return el;\n}\n\n/**\n * @param {number} p\n */\nfunction labelForPriority(p) {\n const i = Math.max(0, Math.min(4, p));\n return priority_levels[i] || 'Medium';\n}\n\n/**\n * @param {number} p\n */\nexport function emojiForPriority(p) {\n switch (p) {\n case 0:\n return '\uD83D\uDD25';\n case 1:\n return '\u26A1\uFE0F';\n case 2:\n return '\uD83D\uDD27';\n case 3:\n return '\uD83E\uDEB6';\n case 4:\n return '\uD83D\uDCA4';\n default:\n return '\uD83D\uDD27';\n }\n}\n", "/**\n * Create a compact, colored badge for an issue type.\n *\n * @param {string | undefined | null} issue_type - One of: bug, feature, task, epic, chore\n * @returns {HTMLSpanElement}\n */\nexport function createTypeBadge(issue_type) {\n const el = document.createElement('span');\n el.className = 'type-badge';\n\n const t = (issue_type || '').toString().toLowerCase();\n const KNOWN = new Set(['bug', 'feature', 'task', 'epic', 'chore']);\n const kind = KNOWN.has(t) ? t : 'neutral';\n el.classList.add(`type-badge--${kind}`);\n el.setAttribute('role', 'img');\n const label = KNOWN.has(t)\n ? t === 'bug'\n ? 'Bug'\n : t === 'feature'\n ? 'Feature'\n : t === 'task'\n ? 'Task'\n : t === 'epic'\n ? 'Epic'\n : 'Chore'\n : '\u2014';\n el.setAttribute(\n 'aria-label',\n KNOWN.has(t) ? `Issue type: ${label}` : 'Issue type: unknown'\n );\n el.setAttribute('title', KNOWN.has(t) ? `Type: ${label}` : 'Type: unknown');\n el.textContent = label;\n return el;\n}\n", "import { html, render } from 'lit-html';\nimport { createListSelectors } from '../data/list-selectors.js';\nimport { cmpClosedDesc, cmpPriorityThenCreated } from '../data/sort.js';\nimport { createIssueIdRenderer } from '../utils/issue-id-renderer.js';\nimport { debug } from '../utils/logging.js';\nimport { createPriorityBadge } from '../utils/priority-badge.js';\nimport { showToast } from '../utils/toast.js';\nimport { createTypeBadge } from '../utils/type-badge.js';\n\n/**\n * @typedef {{\n * id: string,\n * title?: string,\n * status?: 'open'|'in_progress'|'closed',\n * priority?: number,\n * issue_type?: string,\n * created_at?: number,\n * updated_at?: number,\n * closed_at?: number\n * }} IssueLite\n */\n\n/**\n * Map column IDs to their corresponding status values.\n *\n * @type {Record<string, 'open'|'in_progress'|'closed'>}\n */\nconst COLUMN_STATUS_MAP = {\n 'blocked-col': 'open',\n 'ready-col': 'open',\n 'in-progress-col': 'in_progress',\n 'closed-col': 'closed'\n};\n\n/**\n * Create the Board view with Blocked, Ready, In progress, Closed.\n * Push-only: derives items from per-subscription stores.\n *\n * Sorting rules:\n * - Ready/Blocked/In progress: priority asc, then created_at asc.\n * - Closed: closed_at desc.\n *\n * @param {HTMLElement} mount_element\n * @param {unknown} _data - Unused (legacy param retained for call-compat)\n * @param {(id: string) => void} gotoIssue - Navigate to issue detail.\n * @param {{ getState: () => any, setState: (patch: any) => void, subscribe?: (fn: (s:any)=>void)=>()=>void }} [store]\n * @param {{ selectors: { getIds: (client_id: string) => string[], count?: (client_id: string) => number } }} [subscriptions]\n * @param {{ snapshotFor?: (client_id: string) => any[], subscribe?: (fn: () => void) => () => void }} [issueStores]\n * @param {(type: string, payload: unknown) => Promise<unknown>} [transport] - Transport function for sending updates\n * @returns {{ load: () => Promise<void>, clear: () => void }}\n */\nexport function createBoardView(\n mount_element,\n _data,\n gotoIssue,\n store,\n subscriptions = undefined,\n issueStores = undefined,\n transport = undefined\n) {\n const log = debug('views:board');\n /** @type {IssueLite[]} */\n let list_ready = [];\n /** @type {IssueLite[]} */\n let list_blocked = [];\n /** @type {IssueLite[]} */\n let list_in_progress = [];\n /** @type {IssueLite[]} */\n let list_closed = [];\n /** @type {IssueLite[]} */\n let list_closed_raw = [];\n // Centralized selection helpers\n const selectors = issueStores ? createListSelectors(issueStores) : null;\n\n /**\n * Closed column filter mode.\n * 'today' \u2192 items with closed_at since local day start\n * '3' \u2192 last 3 days; '7' \u2192 last 7 days\n *\n * @type {'today'|'3'|'7'}\n */\n let closed_filter_mode = 'today';\n if (store) {\n try {\n const s = store.getState();\n const cf =\n s && s.board ? String(s.board.closed_filter || 'today') : 'today';\n if (cf === 'today' || cf === '3' || cf === '7') {\n closed_filter_mode = /** @type {any} */ (cf);\n }\n } catch {\n // ignore store init errors\n }\n }\n\n function template() {\n return html`\n <div class=\"panel__body board-root\">\n ${columnTemplate('Blocked', 'blocked-col', list_blocked)}\n ${columnTemplate('Ready', 'ready-col', list_ready)}\n ${columnTemplate('In Progress', 'in-progress-col', list_in_progress)}\n ${columnTemplate('Closed', 'closed-col', list_closed)}\n </div>\n `;\n }\n\n /**\n * @param {string} title\n * @param {string} id\n * @param {IssueLite[]} items\n */\n function columnTemplate(title, id, items) {\n const item_count = Array.isArray(items) ? items.length : 0;\n const count_label = item_count === 1 ? '1 issue' : `${item_count} issues`;\n return html`\n <section class=\"board-column\" id=${id}>\n <header\n class=\"board-column__header\"\n id=${id + '-header'}\n role=\"heading\"\n aria-level=\"2\"\n >\n <div class=\"board-column__title\">\n <span class=\"board-column__title-text\">${title}</span>\n <span class=\"badge board-column__count\" aria-label=${count_label}>\n ${item_count}\n </span>\n </div>\n ${id === 'closed-col'\n ? html`<label class=\"board-closed-filter\">\n <span class=\"visually-hidden\">Filter closed issues</span>\n <select\n id=\"closed-filter\"\n aria-label=\"Filter closed issues\"\n @change=${onClosedFilterChange}\n >\n <option\n value=\"today\"\n ?selected=${closed_filter_mode === 'today'}\n >\n Today\n </option>\n <option value=\"3\" ?selected=${closed_filter_mode === '3'}>\n Last 3 days\n </option>\n <option value=\"7\" ?selected=${closed_filter_mode === '7'}>\n Last 7 days\n </option>\n </select>\n </label>`\n : ''}\n </header>\n <div\n class=\"board-column__body\"\n role=\"list\"\n aria-labelledby=${id + '-header'}\n >\n ${items.map((it) => cardTemplate(it))}\n </div>\n </section>\n `;\n }\n\n /**\n * @param {IssueLite} it\n */\n function cardTemplate(it) {\n return html`\n <article\n class=\"board-card\"\n data-issue-id=${it.id}\n role=\"listitem\"\n tabindex=\"-1\"\n draggable=\"true\"\n @click=${(/** @type {MouseEvent} */ ev) => onCardClick(ev, it.id)}\n @dragstart=${(/** @type {DragEvent} */ ev) => onDragStart(ev, it.id)}\n @dragend=${onDragEnd}\n >\n <div class=\"board-card__title text-truncate\">\n ${it.title || '(no title)'}\n </div>\n <div class=\"board-card__meta\">\n ${createTypeBadge(it.issue_type)} ${createPriorityBadge(it.priority)}\n ${createIssueIdRenderer(it.id, { class_name: 'mono' })}\n </div>\n </article>\n `;\n }\n\n /** @type {string|null} */\n let dragging_id = null;\n\n /**\n * Handle card click, ignoring clicks during drag operations.\n *\n * @param {MouseEvent} ev\n * @param {string} id\n */\n function onCardClick(ev, id) {\n // Only navigate if this wasn't a drag operation\n if (!dragging_id) {\n gotoIssue(id);\n }\n }\n\n /**\n * Handle drag start: store issue id in dataTransfer and add dragging class.\n *\n * @param {DragEvent} ev\n * @param {string} id\n */\n function onDragStart(ev, id) {\n dragging_id = id;\n if (ev.dataTransfer) {\n ev.dataTransfer.setData('text/plain', id);\n ev.dataTransfer.effectAllowed = 'move';\n }\n const target = /** @type {HTMLElement} */ (ev.target);\n target.classList.add('board-card--dragging');\n log('dragstart %s', id);\n }\n\n /**\n * Handle drag end: remove dragging class.\n *\n * @param {DragEvent} ev\n */\n function onDragEnd(ev) {\n const target = /** @type {HTMLElement} */ (ev.target);\n target.classList.remove('board-card--dragging');\n // Clear any highlighted drop target\n clearDropTarget();\n // Clear dragging_id after a short delay to allow click event to check it\n setTimeout(() => {\n dragging_id = null;\n }, 0);\n log('dragend');\n }\n\n /**\n * Clear the currently highlighted drop target column.\n */\n function clearDropTarget() {\n /** @type {HTMLElement[]} */\n const all_cols = Array.from(\n mount_element.querySelectorAll('.board-column--drag-over')\n );\n for (const c of all_cols) {\n c.classList.remove('board-column--drag-over');\n }\n }\n\n /**\n * Update issue status via WebSocket transport.\n *\n * @param {string} issue_id\n * @param {'open'|'in_progress'|'closed'} new_status\n */\n async function updateIssueStatus(issue_id, new_status) {\n if (!transport) {\n log('no transport available, status update skipped');\n showToast('Cannot update status: not connected', 'error');\n return;\n }\n try {\n log('update-status %s \u2192 %s', issue_id, new_status);\n await transport('update-status', { id: issue_id, status: new_status });\n showToast('Status updated', 'success', 1500);\n } catch (err) {\n log('update-status failed: %o', err);\n showToast('Failed to update status', 'error');\n }\n }\n\n function doRender() {\n render(template(), mount_element);\n postRenderEnhance();\n }\n\n /**\n * Enhance rendered board with a11y and keyboard navigation.\n * - Roving tabindex per column (first card tabbable).\n * - ArrowUp/ArrowDown within column.\n * - ArrowLeft/ArrowRight to adjacent non-empty column (focus top card).\n * - Enter/Space to open details for focused card.\n */\n function postRenderEnhance() {\n try {\n /** @type {HTMLElement[]} */\n const columns = Array.from(\n mount_element.querySelectorAll('.board-column')\n );\n for (const col of columns) {\n const body = /** @type {HTMLElement|null} */ (\n col.querySelector('.board-column__body')\n );\n if (!body) {\n continue;\n }\n /** @type {HTMLElement[]} */\n const cards = Array.from(body.querySelectorAll('.board-card'));\n // Assign aria-label using column header for screen readers\n const header = /** @type {HTMLElement|null} */ (\n col.querySelector('.board-column__header')\n );\n const col_name = header ? header.textContent?.trim() || '' : '';\n for (const card of cards) {\n const title_el = /** @type {HTMLElement|null} */ (\n card.querySelector('.board-card__title')\n );\n const t = title_el ? title_el.textContent?.trim() || '' : '';\n card.setAttribute(\n 'aria-label',\n `Issue ${t || '(no title)'} \u2014 Column ${col_name}`\n );\n // Default roving setup\n card.tabIndex = -1;\n }\n if (cards.length > 0) {\n cards[0].tabIndex = 0;\n }\n }\n } catch {\n // non-fatal\n }\n }\n\n // Delegate keyboard handling from mount_element\n mount_element.addEventListener('keydown', (ev) => {\n const target = ev.target;\n if (!target || !(target instanceof HTMLElement)) {\n return;\n }\n // Do not intercept keys inside editable controls\n const tag = String(target.tagName || '').toLowerCase();\n if (\n tag === 'input' ||\n tag === 'textarea' ||\n tag === 'select' ||\n target.isContentEditable === true\n ) {\n return;\n }\n const card = target.closest('.board-card');\n if (!card) {\n return;\n }\n const key = String(ev.key || '');\n if (key === 'Enter' || key === ' ') {\n ev.preventDefault();\n const id = card.getAttribute('data-issue-id');\n if (id) {\n gotoIssue(id);\n }\n return;\n }\n if (\n key !== 'ArrowUp' &&\n key !== 'ArrowDown' &&\n key !== 'ArrowLeft' &&\n key !== 'ArrowRight'\n ) {\n return;\n }\n ev.preventDefault();\n // Column context\n const col = /** @type {HTMLElement|null} */ (card.closest('.board-column'));\n if (!col) {\n return;\n }\n const body = col.querySelector('.board-column__body');\n if (!body) {\n return;\n }\n /** @type {HTMLElement[]} */\n const cards = Array.from(body.querySelectorAll('.board-card'));\n const idx = cards.indexOf(/** @type {HTMLElement} */ (card));\n if (idx === -1) {\n return;\n }\n if (key === 'ArrowDown' && idx < cards.length - 1) {\n moveFocus(cards[idx], cards[idx + 1]);\n return;\n }\n if (key === 'ArrowUp' && idx > 0) {\n moveFocus(cards[idx], cards[idx - 1]);\n return;\n }\n if (key === 'ArrowRight' || key === 'ArrowLeft') {\n // Find adjacent column with at least one card\n /** @type {HTMLElement[]} */\n const cols = Array.from(mount_element.querySelectorAll('.board-column'));\n const col_idx = cols.indexOf(col);\n if (col_idx === -1) {\n return;\n }\n const dir = key === 'ArrowRight' ? 1 : -1;\n let next_idx = col_idx + dir;\n /** @type {HTMLElement|null} */\n let target_col = null;\n while (next_idx >= 0 && next_idx < cols.length) {\n const candidate = cols[next_idx];\n const c_body = /** @type {HTMLElement|null} */ (\n candidate.querySelector('.board-column__body')\n );\n const c_cards = c_body\n ? Array.from(c_body.querySelectorAll('.board-card'))\n : [];\n if (c_cards.length > 0) {\n target_col = candidate;\n break;\n }\n next_idx += dir;\n }\n if (target_col) {\n const first = /** @type {HTMLElement|null} */ (\n target_col.querySelector('.board-column__body .board-card')\n );\n if (first) {\n moveFocus(/** @type {HTMLElement} */ (card), first);\n }\n }\n return;\n }\n });\n\n // Track the currently highlighted column to avoid flicker\n /** @type {HTMLElement|null} */\n let current_drop_target = null;\n\n // Delegate drag and drop handling for columns\n mount_element.addEventListener('dragover', (ev) => {\n ev.preventDefault();\n if (ev.dataTransfer) {\n ev.dataTransfer.dropEffect = 'move';\n }\n // Find the column being dragged over\n const target = /** @type {HTMLElement} */ (ev.target);\n const col = /** @type {HTMLElement|null} */ (\n target.closest('.board-column')\n );\n\n // Only update if we've entered a different column\n if (col && col !== current_drop_target) {\n // Remove highlight from previous column\n if (current_drop_target) {\n current_drop_target.classList.remove('board-column--drag-over');\n }\n // Highlight the new column\n col.classList.add('board-column--drag-over');\n current_drop_target = col;\n }\n });\n\n mount_element.addEventListener('dragleave', (ev) => {\n const related = /** @type {HTMLElement|null} */ (ev.relatedTarget);\n // Only clear if we're leaving the mount element entirely\n if (!related || !mount_element.contains(related)) {\n if (current_drop_target) {\n current_drop_target.classList.remove('board-column--drag-over');\n current_drop_target = null;\n }\n }\n });\n\n mount_element.addEventListener('drop', (ev) => {\n ev.preventDefault();\n // Clear the drop target highlight\n if (current_drop_target) {\n current_drop_target.classList.remove('board-column--drag-over');\n current_drop_target = null;\n }\n\n const target = /** @type {HTMLElement} */ (ev.target);\n const col = target.closest('.board-column');\n if (!col) {\n return;\n }\n\n const col_id = col.id;\n const new_status = COLUMN_STATUS_MAP[col_id];\n if (!new_status) {\n log('drop on unknown column: %s', col_id);\n return;\n }\n\n const issue_id = ev.dataTransfer?.getData('text/plain');\n if (!issue_id) {\n log('drop without issue id');\n return;\n }\n\n log('drop %s on %s \u2192 %s', issue_id, col_id, new_status);\n void updateIssueStatus(issue_id, new_status);\n });\n\n /**\n * @param {HTMLElement} from\n * @param {HTMLElement} to\n */\n function moveFocus(from, to) {\n try {\n from.tabIndex = -1;\n to.tabIndex = 0;\n to.focus();\n } catch {\n // ignore focus errors\n }\n }\n\n // Sort helpers centralized in app/data/sort.js\n\n /**\n * Recompute closed list from raw using the current filter and sort.\n */\n function applyClosedFilter() {\n log('applyClosedFilter %s', closed_filter_mode);\n /** @type {IssueLite[]} */\n let items = Array.isArray(list_closed_raw) ? [...list_closed_raw] : [];\n const now = new Date();\n let since_ts = 0;\n if (closed_filter_mode === 'today') {\n const start = new Date(\n now.getFullYear(),\n now.getMonth(),\n now.getDate(),\n 0,\n 0,\n 0,\n 0\n );\n since_ts = start.getTime();\n } else if (closed_filter_mode === '3') {\n since_ts = now.getTime() - 3 * 24 * 60 * 60 * 1000;\n } else if (closed_filter_mode === '7') {\n since_ts = now.getTime() - 7 * 24 * 60 * 60 * 1000;\n }\n items = items.filter((it) => {\n const s = Number.isFinite(it.closed_at)\n ? /** @type {number} */ (it.closed_at)\n : NaN;\n if (!Number.isFinite(s)) {\n return false;\n }\n return s >= since_ts;\n });\n items.sort(cmpClosedDesc);\n list_closed = items;\n }\n\n /**\n * @param {Event} ev\n */\n function onClosedFilterChange(ev) {\n try {\n const el = /** @type {HTMLSelectElement} */ (ev.target);\n const v = String(el.value || 'today');\n closed_filter_mode = v === '3' || v === '7' ? v : 'today';\n log('closed filter %s', closed_filter_mode);\n if (store) {\n try {\n store.setState({ board: { closed_filter: closed_filter_mode } });\n } catch {\n // ignore store errors\n }\n }\n applyClosedFilter();\n doRender();\n } catch {\n // ignore\n }\n }\n\n /**\n * Compose lists from subscriptions + issues store and render.\n */\n function refreshFromStores() {\n try {\n if (selectors) {\n const in_progress = selectors.selectBoardColumn(\n 'tab:board:in-progress',\n 'in_progress'\n );\n const blocked = selectors.selectBoardColumn(\n 'tab:board:blocked',\n 'blocked'\n );\n const ready_raw = selectors.selectBoardColumn(\n 'tab:board:ready',\n 'ready'\n );\n const closed = selectors.selectBoardColumn(\n 'tab:board:closed',\n 'closed'\n );\n\n // Ready excludes items that are in progress\n /** @type {Set<string>} */\n const in_prog_ids = new Set(in_progress.map((i) => i.id));\n const ready = ready_raw.filter((i) => !in_prog_ids.has(i.id));\n\n list_ready = ready;\n list_blocked = blocked;\n list_in_progress = in_progress;\n list_closed_raw = closed;\n }\n applyClosedFilter();\n doRender();\n } catch {\n list_ready = [];\n list_blocked = [];\n list_in_progress = [];\n list_closed = [];\n doRender();\n }\n }\n\n // Live updates: recompose on issue store envelopes\n if (selectors) {\n selectors.subscribe(() => {\n try {\n refreshFromStores();\n } catch {\n // ignore\n }\n });\n }\n\n return {\n async load() {\n // Compose lists from subscriptions + issues store\n log('load');\n refreshFromStores();\n // If nothing is present yet (e.g., immediately after switching back\n // to the Board and before list-delta arrives), fetch via data layer as\n // a fallback so the board is not empty on initial display.\n try {\n const has_subs = Boolean(subscriptions && subscriptions.selectors);\n /**\n * @param {string} id\n */\n const cnt = (id) => {\n if (!has_subs || !subscriptions) {\n return 0;\n }\n const sel = subscriptions.selectors;\n if (typeof sel.count === 'function') {\n return Number(sel.count(id) || 0);\n }\n try {\n const arr = sel.getIds(id);\n return Array.isArray(arr) ? arr.length : 0;\n } catch {\n return 0;\n }\n };\n const total_items =\n cnt('tab:board:ready') +\n cnt('tab:board:blocked') +\n cnt('tab:board:in-progress') +\n cnt('tab:board:closed');\n const data = /** @type {any} */ (_data);\n const can_fetch =\n data &&\n typeof data.getReady === 'function' &&\n typeof data.getBlocked === 'function' &&\n typeof data.getInProgress === 'function' &&\n typeof data.getClosed === 'function';\n if (total_items === 0 && can_fetch) {\n log('fallback fetch');\n /** @type {[IssueLite[], IssueLite[], IssueLite[], IssueLite[]]} */\n const [ready_raw, blocked_raw, in_prog_raw, closed_raw] =\n await Promise.all([\n data.getReady().catch(() => []),\n data.getBlocked().catch(() => []),\n data.getInProgress().catch(() => []),\n data.getClosed().catch(() => [])\n ]);\n // Normalize and map unknowns to IssueLite shape\n /** @type {IssueLite[]} */\n let ready = Array.isArray(ready_raw) ? ready_raw.map((it) => it) : [];\n /** @type {IssueLite[]} */\n const blocked = Array.isArray(blocked_raw)\n ? blocked_raw.map((it) => it)\n : [];\n /** @type {IssueLite[]} */\n const in_prog = Array.isArray(in_prog_raw)\n ? in_prog_raw.map((it) => it)\n : [];\n /** @type {IssueLite[]} */\n const closed = Array.isArray(closed_raw)\n ? closed_raw.map((it) => it)\n : [];\n\n // Remove items from Ready that are already In Progress\n /** @type {Set<string>} */\n const in_progress_ids = new Set(in_prog.map((i) => i.id));\n ready = ready.filter((i) => !in_progress_ids.has(i.id));\n\n // Sort as per column rules\n ready.sort(cmpPriorityThenCreated);\n blocked.sort(cmpPriorityThenCreated);\n in_prog.sort(cmpPriorityThenCreated);\n list_ready = ready;\n list_blocked = blocked;\n list_in_progress = in_prog;\n list_closed_raw = closed;\n applyClosedFilter();\n doRender();\n }\n } catch {\n // ignore fallback errors\n }\n },\n clear() {\n mount_element.replaceChildren();\n list_ready = [];\n list_blocked = [];\n list_in_progress = [];\n list_closed = [];\n }\n };\n}\n", "const {\n entries,\n setPrototypeOf,\n isFrozen,\n getPrototypeOf,\n getOwnPropertyDescriptor,\n} = Object;\n\nlet { freeze, seal, create } = Object; // eslint-disable-line import/no-mutable-exports\nlet { apply, construct } = typeof Reflect !== 'undefined' && Reflect;\n\nif (!freeze) {\n freeze = function <T>(x: T): T {\n return x;\n };\n}\n\nif (!seal) {\n seal = function <T>(x: T): T {\n return x;\n };\n}\n\nif (!apply) {\n apply = function <T>(\n func: (thisArg: any, ...args: any[]) => T,\n thisArg: any,\n ...args: any[]\n ): T {\n return func.apply(thisArg, args);\n };\n}\n\nif (!construct) {\n construct = function <T>(Func: new (...args: any[]) => T, ...args: any[]): T {\n return new Func(...args);\n };\n}\n\nconst arrayForEach = unapply(Array.prototype.forEach);\nconst arrayIndexOf = unapply(Array.prototype.indexOf);\nconst arrayLastIndexOf = unapply(Array.prototype.lastIndexOf);\nconst arrayPop = unapply(Array.prototype.pop);\nconst arrayPush = unapply(Array.prototype.push);\nconst arraySlice = unapply(Array.prototype.slice);\nconst arraySplice = unapply(Array.prototype.splice);\n\nconst stringToLowerCase = unapply(String.prototype.toLowerCase);\nconst stringToString = unapply(String.prototype.toString);\nconst stringMatch = unapply(String.prototype.match);\nconst stringReplace = unapply(String.prototype.replace);\nconst stringIndexOf = unapply(String.prototype.indexOf);\nconst stringTrim = unapply(String.prototype.trim);\n\nconst objectHasOwnProperty = unapply(Object.prototype.hasOwnProperty);\n\nconst regExpTest = unapply(RegExp.prototype.test);\n\nconst typeErrorCreate = unconstruct(TypeError);\n\n/**\n * Creates a new function that calls the given function with a specified thisArg and arguments.\n *\n * @param func - The function to be wrapped and called.\n * @returns A new function that calls the given function with a specified thisArg and arguments.\n */\nfunction unapply<T>(\n func: (thisArg: any, ...args: any[]) => T\n): (thisArg: any, ...args: any[]) => T {\n return (thisArg: any, ...args: any[]): T => {\n if (thisArg instanceof RegExp) {\n thisArg.lastIndex = 0;\n }\n\n return apply(func, thisArg, args);\n };\n}\n\n/**\n * Creates a new function that constructs an instance of the given constructor function with the provided arguments.\n *\n * @param func - The constructor function to be wrapped and called.\n * @returns A new function that constructs an instance of the given constructor function with the provided arguments.\n */\nfunction unconstruct<T>(\n Func: new (...args: any[]) => T\n): (...args: any[]) => T {\n return (...args: any[]): T => construct(Func, args);\n}\n\n/**\n * Add properties to a lookup table\n *\n * @param set - The set to which elements will be added.\n * @param array - The array containing elements to be added to the set.\n * @param transformCaseFunc - An optional function to transform the case of each element before adding to the set.\n * @returns The modified set with added elements.\n */\nfunction addToSet(\n set: Record<string, any>,\n array: readonly any[],\n transformCaseFunc: ReturnType<typeof unapply<string>> = stringToLowerCase\n): Record<string, any> {\n if (setPrototypeOf) {\n // Make 'in' and truthy checks like Boolean(set.constructor)\n // independent of any properties defined on Object.prototype.\n // Prevent prototype setters from intercepting set as a this value.\n setPrototypeOf(set, null);\n }\n\n let l = array.length;\n while (l--) {\n let element = array[l];\n if (typeof element === 'string') {\n const lcElement = transformCaseFunc(element);\n if (lcElement !== element) {\n // Config presets (e.g. tags.js, attrs.js) are immutable.\n if (!isFrozen(array)) {\n (array as any[])[l] = lcElement;\n }\n\n element = lcElement;\n }\n }\n\n set[element] = true;\n }\n\n return set;\n}\n\n/**\n * Clean up an array to harden against CSPP\n *\n * @param array - The array to be cleaned.\n * @returns The cleaned version of the array\n */\nfunction cleanArray<T>(array: T[]): Array<T | null> {\n for (let index = 0; index < array.length; index++) {\n const isPropertyExist = objectHasOwnProperty(array, index);\n\n if (!isPropertyExist) {\n array[index] = null;\n }\n }\n\n return array;\n}\n\n/**\n * Shallow clone an object\n *\n * @param object - The object to be cloned.\n * @returns A new object that copies the original.\n */\nfunction clone<T extends Record<string, any>>(object: T): T {\n const newObject = create(null);\n\n for (const [property, value] of entries(object)) {\n const isPropertyExist = objectHasOwnProperty(object, property);\n\n if (isPropertyExist) {\n if (Array.isArray(value)) {\n newObject[property] = cleanArray(value);\n } else if (\n value &&\n typeof value === 'object' &&\n value.constructor === Object\n ) {\n newObject[property] = clone(value);\n } else {\n newObject[property] = value;\n }\n }\n }\n\n return newObject;\n}\n\n/**\n * This method automatically checks if the prop is function or getter and behaves accordingly.\n *\n * @param object - The object to look up the getter function in its prototype chain.\n * @param prop - The property name for which to find the getter function.\n * @returns The getter function found in the prototype chain or a fallback function.\n */\nfunction lookupGetter<T extends Record<string, any>>(\n object: T,\n prop: string\n): ReturnType<typeof unapply<any>> | (() => null) {\n while (object !== null) {\n const desc = getOwnPropertyDescriptor(object, prop);\n\n if (desc) {\n if (desc.get) {\n return unapply(desc.get);\n }\n\n if (typeof desc.value === 'function') {\n return unapply(desc.value);\n }\n }\n\n object = getPrototypeOf(object);\n }\n\n function fallbackValue(): null {\n return null;\n }\n\n return fallbackValue;\n}\n\nexport {\n // Array\n arrayForEach,\n arrayIndexOf,\n arrayLastIndexOf,\n arrayPop,\n arrayPush,\n arraySlice,\n arraySplice,\n // Object\n entries,\n freeze,\n getPrototypeOf,\n getOwnPropertyDescriptor,\n isFrozen,\n setPrototypeOf,\n seal,\n clone,\n create,\n objectHasOwnProperty,\n // RegExp\n regExpTest,\n // String\n stringIndexOf,\n stringMatch,\n stringReplace,\n stringToLowerCase,\n stringToString,\n stringTrim,\n // Errors\n typeErrorCreate,\n // Other\n lookupGetter,\n addToSet,\n // Reflect\n unapply,\n unconstruct,\n};\n", "import { freeze } from './utils.js';\n\nexport const html = freeze([\n 'a',\n 'abbr',\n 'acronym',\n 'address',\n 'area',\n 'article',\n 'aside',\n 'audio',\n 'b',\n 'bdi',\n 'bdo',\n 'big',\n 'blink',\n 'blockquote',\n 'body',\n 'br',\n 'button',\n 'canvas',\n 'caption',\n 'center',\n 'cite',\n 'code',\n 'col',\n 'colgroup',\n 'content',\n 'data',\n 'datalist',\n 'dd',\n 'decorator',\n 'del',\n 'details',\n 'dfn',\n 'dialog',\n 'dir',\n 'div',\n 'dl',\n 'dt',\n 'element',\n 'em',\n 'fieldset',\n 'figcaption',\n 'figure',\n 'font',\n 'footer',\n 'form',\n 'h1',\n 'h2',\n 'h3',\n 'h4',\n 'h5',\n 'h6',\n 'head',\n 'header',\n 'hgroup',\n 'hr',\n 'html',\n 'i',\n 'img',\n 'input',\n 'ins',\n 'kbd',\n 'label',\n 'legend',\n 'li',\n 'main',\n 'map',\n 'mark',\n 'marquee',\n 'menu',\n 'menuitem',\n 'meter',\n 'nav',\n 'nobr',\n 'ol',\n 'optgroup',\n 'option',\n 'output',\n 'p',\n 'picture',\n 'pre',\n 'progress',\n 'q',\n 'rp',\n 'rt',\n 'ruby',\n 's',\n 'samp',\n 'search',\n 'section',\n 'select',\n 'shadow',\n 'slot',\n 'small',\n 'source',\n 'spacer',\n 'span',\n 'strike',\n 'strong',\n 'style',\n 'sub',\n 'summary',\n 'sup',\n 'table',\n 'tbody',\n 'td',\n 'template',\n 'textarea',\n 'tfoot',\n 'th',\n 'thead',\n 'time',\n 'tr',\n 'track',\n 'tt',\n 'u',\n 'ul',\n 'var',\n 'video',\n 'wbr',\n] as const);\n\nexport const svg = freeze([\n 'svg',\n 'a',\n 'altglyph',\n 'altglyphdef',\n 'altglyphitem',\n 'animatecolor',\n 'animatemotion',\n 'animatetransform',\n 'circle',\n 'clippath',\n 'defs',\n 'desc',\n 'ellipse',\n 'enterkeyhint',\n 'exportparts',\n 'filter',\n 'font',\n 'g',\n 'glyph',\n 'glyphref',\n 'hkern',\n 'image',\n 'inputmode',\n 'line',\n 'lineargradient',\n 'marker',\n 'mask',\n 'metadata',\n 'mpath',\n 'part',\n 'path',\n 'pattern',\n 'polygon',\n 'polyline',\n 'radialgradient',\n 'rect',\n 'stop',\n 'style',\n 'switch',\n 'symbol',\n 'text',\n 'textpath',\n 'title',\n 'tref',\n 'tspan',\n 'view',\n 'vkern',\n] as const);\n\nexport const svgFilters = freeze([\n 'feBlend',\n 'feColorMatrix',\n 'feComponentTransfer',\n 'feComposite',\n 'feConvolveMatrix',\n 'feDiffuseLighting',\n 'feDisplacementMap',\n 'feDistantLight',\n 'feDropShadow',\n 'feFlood',\n 'feFuncA',\n 'feFuncB',\n 'feFuncG',\n 'feFuncR',\n 'feGaussianBlur',\n 'feImage',\n 'feMerge',\n 'feMergeNode',\n 'feMorphology',\n 'feOffset',\n 'fePointLight',\n 'feSpecularLighting',\n 'feSpotLight',\n 'feTile',\n 'feTurbulence',\n] as const);\n\n// List of SVG elements that are disallowed by default.\n// We still need to know them so that we can do namespace\n// checks properly in case one wants to add them to\n// allow-list.\nexport const svgDisallowed = freeze([\n 'animate',\n 'color-profile',\n 'cursor',\n 'discard',\n 'font-face',\n 'font-face-format',\n 'font-face-name',\n 'font-face-src',\n 'font-face-uri',\n 'foreignobject',\n 'hatch',\n 'hatchpath',\n 'mesh',\n 'meshgradient',\n 'meshpatch',\n 'meshrow',\n 'missing-glyph',\n 'script',\n 'set',\n 'solidcolor',\n 'unknown',\n 'use',\n] as const);\n\nexport const mathMl = freeze([\n 'math',\n 'menclose',\n 'merror',\n 'mfenced',\n 'mfrac',\n 'mglyph',\n 'mi',\n 'mlabeledtr',\n 'mmultiscripts',\n 'mn',\n 'mo',\n 'mover',\n 'mpadded',\n 'mphantom',\n 'mroot',\n 'mrow',\n 'ms',\n 'mspace',\n 'msqrt',\n 'mstyle',\n 'msub',\n 'msup',\n 'msubsup',\n 'mtable',\n 'mtd',\n 'mtext',\n 'mtr',\n 'munder',\n 'munderover',\n 'mprescripts',\n] as const);\n\n// Similarly to SVG, we want to know all MathML elements,\n// even those that we disallow by default.\nexport const mathMlDisallowed = freeze([\n 'maction',\n 'maligngroup',\n 'malignmark',\n 'mlongdiv',\n 'mscarries',\n 'mscarry',\n 'msgroup',\n 'mstack',\n 'msline',\n 'msrow',\n 'semantics',\n 'annotation',\n 'annotation-xml',\n 'mprescripts',\n 'none',\n] as const);\n\nexport const text = freeze(['#text'] as const);\n", "import { freeze } from './utils.js';\n\nexport const html = freeze([\n 'accept',\n 'action',\n 'align',\n 'alt',\n 'autocapitalize',\n 'autocomplete',\n 'autopictureinpicture',\n 'autoplay',\n 'background',\n 'bgcolor',\n 'border',\n 'capture',\n 'cellpadding',\n 'cellspacing',\n 'checked',\n 'cite',\n 'class',\n 'clear',\n 'color',\n 'cols',\n 'colspan',\n 'controls',\n 'controlslist',\n 'coords',\n 'crossorigin',\n 'datetime',\n 'decoding',\n 'default',\n 'dir',\n 'disabled',\n 'disablepictureinpicture',\n 'disableremoteplayback',\n 'download',\n 'draggable',\n 'enctype',\n 'enterkeyhint',\n 'exportparts',\n 'face',\n 'for',\n 'headers',\n 'height',\n 'hidden',\n 'high',\n 'href',\n 'hreflang',\n 'id',\n 'inert',\n 'inputmode',\n 'integrity',\n 'ismap',\n 'kind',\n 'label',\n 'lang',\n 'list',\n 'loading',\n 'loop',\n 'low',\n 'max',\n 'maxlength',\n 'media',\n 'method',\n 'min',\n 'minlength',\n 'multiple',\n 'muted',\n 'name',\n 'nonce',\n 'noshade',\n 'novalidate',\n 'nowrap',\n 'open',\n 'optimum',\n 'part',\n 'pattern',\n 'placeholder',\n 'playsinline',\n 'popover',\n 'popovertarget',\n 'popovertargetaction',\n 'poster',\n 'preload',\n 'pubdate',\n 'radiogroup',\n 'readonly',\n 'rel',\n 'required',\n 'rev',\n 'reversed',\n 'role',\n 'rows',\n 'rowspan',\n 'spellcheck',\n 'scope',\n 'selected',\n 'shape',\n 'size',\n 'sizes',\n 'slot',\n 'span',\n 'srclang',\n 'start',\n 'src',\n 'srcset',\n 'step',\n 'style',\n 'summary',\n 'tabindex',\n 'title',\n 'translate',\n 'type',\n 'usemap',\n 'valign',\n 'value',\n 'width',\n 'wrap',\n 'xmlns',\n 'slot',\n] as const);\n\nexport const svg = freeze([\n 'accent-height',\n 'accumulate',\n 'additive',\n 'alignment-baseline',\n 'amplitude',\n 'ascent',\n 'attributename',\n 'attributetype',\n 'azimuth',\n 'basefrequency',\n 'baseline-shift',\n 'begin',\n 'bias',\n 'by',\n 'class',\n 'clip',\n 'clippathunits',\n 'clip-path',\n 'clip-rule',\n 'color',\n 'color-interpolation',\n 'color-interpolation-filters',\n 'color-profile',\n 'color-rendering',\n 'cx',\n 'cy',\n 'd',\n 'dx',\n 'dy',\n 'diffuseconstant',\n 'direction',\n 'display',\n 'divisor',\n 'dur',\n 'edgemode',\n 'elevation',\n 'end',\n 'exponent',\n 'fill',\n 'fill-opacity',\n 'fill-rule',\n 'filter',\n 'filterunits',\n 'flood-color',\n 'flood-opacity',\n 'font-family',\n 'font-size',\n 'font-size-adjust',\n 'font-stretch',\n 'font-style',\n 'font-variant',\n 'font-weight',\n 'fx',\n 'fy',\n 'g1',\n 'g2',\n 'glyph-name',\n 'glyphref',\n 'gradientunits',\n 'gradienttransform',\n 'height',\n 'href',\n 'id',\n 'image-rendering',\n 'in',\n 'in2',\n 'intercept',\n 'k',\n 'k1',\n 'k2',\n 'k3',\n 'k4',\n 'kerning',\n 'keypoints',\n 'keysplines',\n 'keytimes',\n 'lang',\n 'lengthadjust',\n 'letter-spacing',\n 'kernelmatrix',\n 'kernelunitlength',\n 'lighting-color',\n 'local',\n 'marker-end',\n 'marker-mid',\n 'marker-start',\n 'markerheight',\n 'markerunits',\n 'markerwidth',\n 'maskcontentunits',\n 'maskunits',\n 'max',\n 'mask',\n 'mask-type',\n 'media',\n 'method',\n 'mode',\n 'min',\n 'name',\n 'numoctaves',\n 'offset',\n 'operator',\n 'opacity',\n 'order',\n 'orient',\n 'orientation',\n 'origin',\n 'overflow',\n 'paint-order',\n 'path',\n 'pathlength',\n 'patterncontentunits',\n 'patterntransform',\n 'patternunits',\n 'points',\n 'preservealpha',\n 'preserveaspectratio',\n 'primitiveunits',\n 'r',\n 'rx',\n 'ry',\n 'radius',\n 'refx',\n 'refy',\n 'repeatcount',\n 'repeatdur',\n 'restart',\n 'result',\n 'rotate',\n 'scale',\n 'seed',\n 'shape-rendering',\n 'slope',\n 'specularconstant',\n 'specularexponent',\n 'spreadmethod',\n 'startoffset',\n 'stddeviation',\n 'stitchtiles',\n 'stop-color',\n 'stop-opacity',\n 'stroke-dasharray',\n 'stroke-dashoffset',\n 'stroke-linecap',\n 'stroke-linejoin',\n 'stroke-miterlimit',\n 'stroke-opacity',\n 'stroke',\n 'stroke-width',\n 'style',\n 'surfacescale',\n 'systemlanguage',\n 'tabindex',\n 'tablevalues',\n 'targetx',\n 'targety',\n 'transform',\n 'transform-origin',\n 'text-anchor',\n 'text-decoration',\n 'text-rendering',\n 'textlength',\n 'type',\n 'u1',\n 'u2',\n 'unicode',\n 'values',\n 'viewbox',\n 'visibility',\n 'version',\n 'vert-adv-y',\n 'vert-origin-x',\n 'vert-origin-y',\n 'width',\n 'word-spacing',\n 'wrap',\n 'writing-mode',\n 'xchannelselector',\n 'ychannelselector',\n 'x',\n 'x1',\n 'x2',\n 'xmlns',\n 'y',\n 'y1',\n 'y2',\n 'z',\n 'zoomandpan',\n] as const);\n\nexport const mathMl = freeze([\n 'accent',\n 'accentunder',\n 'align',\n 'bevelled',\n 'close',\n 'columnsalign',\n 'columnlines',\n 'columnspan',\n 'denomalign',\n 'depth',\n 'dir',\n 'display',\n 'displaystyle',\n 'encoding',\n 'fence',\n 'frame',\n 'height',\n 'href',\n 'id',\n 'largeop',\n 'length',\n 'linethickness',\n 'lspace',\n 'lquote',\n 'mathbackground',\n 'mathcolor',\n 'mathsize',\n 'mathvariant',\n 'maxsize',\n 'minsize',\n 'movablelimits',\n 'notation',\n 'numalign',\n 'open',\n 'rowalign',\n 'rowlines',\n 'rowspacing',\n 'rowspan',\n 'rspace',\n 'rquote',\n 'scriptlevel',\n 'scriptminsize',\n 'scriptsizemultiplier',\n 'selection',\n 'separator',\n 'separators',\n 'stretchy',\n 'subscriptshift',\n 'supscriptshift',\n 'symmetric',\n 'voffset',\n 'width',\n 'xmlns',\n]);\n\nexport const xml = freeze([\n 'xlink:href',\n 'xml:id',\n 'xlink:title',\n 'xml:space',\n 'xmlns:xlink',\n] as const);\n", "import { seal } from './utils.js';\n\n// eslint-disable-next-line unicorn/better-regex\nexport const MUSTACHE_EXPR = seal(/\\{\\{[\\w\\W]*|[\\w\\W]*\\}\\}/gm); // Specify template detection regex for SAFE_FOR_TEMPLATES mode\nexport const ERB_EXPR = seal(/<%[\\w\\W]*|[\\w\\W]*%>/gm);\nexport const TMPLIT_EXPR = seal(/\\$\\{[\\w\\W]*/gm); // eslint-disable-line unicorn/better-regex\nexport const DATA_ATTR = seal(/^data-[\\-\\w.\\u00B7-\\uFFFF]+$/); // eslint-disable-line no-useless-escape\nexport const ARIA_ATTR = seal(/^aria-[\\-\\w]+$/); // eslint-disable-line no-useless-escape\nexport const IS_ALLOWED_URI = seal(\n /^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\\-]+(?:[^a-z+.\\-:]|$))/i // eslint-disable-line no-useless-escape\n);\nexport const IS_SCRIPT_OR_DATA = seal(/^(?:\\w+script|data):/i);\nexport const ATTR_WHITESPACE = seal(\n /[\\u0000-\\u0020\\u00A0\\u1680\\u180E\\u2000-\\u2029\\u205F\\u3000]/g // eslint-disable-line no-control-regex\n);\nexport const DOCTYPE_NAME = seal(/^html$/i);\nexport const CUSTOM_ELEMENT = seal(/^[a-z][.\\w]*(-[.\\w]+)+$/i);\n", "/* eslint-disable @typescript-eslint/indent */\n\nimport type { TrustedHTML, TrustedTypesWindow } from 'trusted-types/lib';\nimport type { Config, UseProfilesConfig } from './config';\nimport * as TAGS from './tags.js';\nimport * as ATTRS from './attrs.js';\nimport * as EXPRESSIONS from './regexp.js';\nimport {\n addToSet,\n clone,\n entries,\n freeze,\n arrayForEach,\n arrayLastIndexOf,\n arrayPop,\n arrayPush,\n arraySplice,\n stringMatch,\n stringReplace,\n stringToLowerCase,\n stringToString,\n stringIndexOf,\n stringTrim,\n regExpTest,\n typeErrorCreate,\n lookupGetter,\n create,\n objectHasOwnProperty,\n} from './utils.js';\n\nexport type { Config } from './config';\n\ndeclare const VERSION: string;\n\n// https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType\nconst NODE_TYPE = {\n element: 1,\n attribute: 2,\n text: 3,\n cdataSection: 4,\n entityReference: 5, // Deprecated\n entityNode: 6, // Deprecated\n progressingInstruction: 7,\n comment: 8,\n document: 9,\n documentType: 10,\n documentFragment: 11,\n notation: 12, // Deprecated\n};\n\nconst getGlobal = function (): WindowLike {\n return typeof window === 'undefined' ? null : window;\n};\n\n/**\n * Creates a no-op policy for internal use only.\n * Don't export this function outside this module!\n * @param trustedTypes The policy factory.\n * @param purifyHostElement The Script element used to load DOMPurify (to determine policy name suffix).\n * @return The policy created (or null, if Trusted Types\n * are not supported or creating the policy failed).\n */\nconst _createTrustedTypesPolicy = function (\n trustedTypes: TrustedTypePolicyFactory,\n purifyHostElement: HTMLScriptElement\n) {\n if (\n typeof trustedTypes !== 'object' ||\n typeof trustedTypes.createPolicy !== 'function'\n ) {\n return null;\n }\n\n // Allow the callers to control the unique policy name\n // by adding a data-tt-policy-suffix to the script element with the DOMPurify.\n // Policy creation with duplicate names throws in Trusted Types.\n let suffix = null;\n const ATTR_NAME = 'data-tt-policy-suffix';\n if (purifyHostElement && purifyHostElement.hasAttribute(ATTR_NAME)) {\n suffix = purifyHostElement.getAttribute(ATTR_NAME);\n }\n\n const policyName = 'dompurify' + (suffix ? '#' + suffix : '');\n\n try {\n return trustedTypes.createPolicy(policyName, {\n createHTML(html) {\n return html;\n },\n createScriptURL(scriptUrl) {\n return scriptUrl;\n },\n });\n } catch (_) {\n // Policy creation failed (most likely another DOMPurify script has\n // already run). Skip creating the policy, as this will only cause errors\n // if TT are enforced.\n console.warn(\n 'TrustedTypes policy ' + policyName + ' could not be created.'\n );\n return null;\n }\n};\n\nconst _createHooksMap = function (): HooksMap {\n return {\n afterSanitizeAttributes: [],\n afterSanitizeElements: [],\n afterSanitizeShadowDOM: [],\n beforeSanitizeAttributes: [],\n beforeSanitizeElements: [],\n beforeSanitizeShadowDOM: [],\n uponSanitizeAttribute: [],\n uponSanitizeElement: [],\n uponSanitizeShadowNode: [],\n };\n};\n\nfunction createDOMPurify(window: WindowLike = getGlobal()): DOMPurify {\n const DOMPurify: DOMPurify = (root: WindowLike) => createDOMPurify(root);\n\n DOMPurify.version = VERSION;\n\n DOMPurify.removed = [];\n\n if (\n !window ||\n !window.document ||\n window.document.nodeType !== NODE_TYPE.document ||\n !window.Element\n ) {\n // Not running in a browser, provide a factory function\n // so that you can pass your own Window\n DOMPurify.isSupported = false;\n\n return DOMPurify;\n }\n\n let { document } = window;\n\n const originalDocument = document;\n const currentScript: HTMLScriptElement =\n originalDocument.currentScript as HTMLScriptElement;\n const {\n DocumentFragment,\n HTMLTemplateElement,\n Node,\n Element,\n NodeFilter,\n NamedNodeMap = window.NamedNodeMap || (window as any).MozNamedAttrMap,\n HTMLFormElement,\n DOMParser,\n trustedTypes,\n } = window;\n\n const ElementPrototype = Element.prototype;\n\n const cloneNode = lookupGetter(ElementPrototype, 'cloneNode');\n const remove = lookupGetter(ElementPrototype, 'remove');\n const getNextSibling = lookupGetter(ElementPrototype, 'nextSibling');\n const getChildNodes = lookupGetter(ElementPrototype, 'childNodes');\n const getParentNode = lookupGetter(ElementPrototype, 'parentNode');\n\n // As per issue #47, the web-components registry is inherited by a\n // new document created via createHTMLDocument. As per the spec\n // (http://w3c.github.io/webcomponents/spec/custom/#creating-and-passing-registries)\n // a new empty registry is used when creating a template contents owner\n // document, so we use that as our parent document to ensure nothing\n // is inherited.\n if (typeof HTMLTemplateElement === 'function') {\n const template = document.createElement('template');\n if (template.content && template.content.ownerDocument) {\n document = template.content.ownerDocument;\n }\n }\n\n let trustedTypesPolicy;\n let emptyHTML = '';\n\n const {\n implementation,\n createNodeIterator,\n createDocumentFragment,\n getElementsByTagName,\n } = document;\n const { importNode } = originalDocument;\n\n let hooks = _createHooksMap();\n\n /**\n * Expose whether this browser supports running the full DOMPurify.\n */\n DOMPurify.isSupported =\n typeof entries === 'function' &&\n typeof getParentNode === 'function' &&\n implementation &&\n implementation.createHTMLDocument !== undefined;\n\n const {\n MUSTACHE_EXPR,\n ERB_EXPR,\n TMPLIT_EXPR,\n DATA_ATTR,\n ARIA_ATTR,\n IS_SCRIPT_OR_DATA,\n ATTR_WHITESPACE,\n CUSTOM_ELEMENT,\n } = EXPRESSIONS;\n\n let { IS_ALLOWED_URI } = EXPRESSIONS;\n\n /**\n * We consider the elements and attributes below to be safe. Ideally\n * don't add any new ones but feel free to remove unwanted ones.\n */\n\n /* allowed element names */\n let ALLOWED_TAGS = null;\n const DEFAULT_ALLOWED_TAGS = addToSet({}, [\n ...TAGS.html,\n ...TAGS.svg,\n ...TAGS.svgFilters,\n ...TAGS.mathMl,\n ...TAGS.text,\n ]);\n\n /* Allowed attribute names */\n let ALLOWED_ATTR = null;\n const DEFAULT_ALLOWED_ATTR = addToSet({}, [\n ...ATTRS.html,\n ...ATTRS.svg,\n ...ATTRS.mathMl,\n ...ATTRS.xml,\n ]);\n\n /*\n * Configure how DOMPurify should handle custom elements and their attributes as well as customized built-in elements.\n * @property {RegExp|Function|null} tagNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any custom elements)\n * @property {RegExp|Function|null} attributeNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any attributes not on the allow list)\n * @property {boolean} allowCustomizedBuiltInElements allow custom elements derived from built-ins if they pass CUSTOM_ELEMENT_HANDLING.tagNameCheck. Default: `false`.\n */\n let CUSTOM_ELEMENT_HANDLING = Object.seal(\n create(null, {\n tagNameCheck: {\n writable: true,\n configurable: false,\n enumerable: true,\n value: null,\n },\n attributeNameCheck: {\n writable: true,\n configurable: false,\n enumerable: true,\n value: null,\n },\n allowCustomizedBuiltInElements: {\n writable: true,\n configurable: false,\n enumerable: true,\n value: false,\n },\n })\n );\n\n /* Explicitly forbidden tags (overrides ALLOWED_TAGS/ADD_TAGS) */\n let FORBID_TAGS = null;\n\n /* Explicitly forbidden attributes (overrides ALLOWED_ATTR/ADD_ATTR) */\n let FORBID_ATTR = null;\n\n /* Config object to store ADD_TAGS/ADD_ATTR functions (when used as functions) */\n const EXTRA_ELEMENT_HANDLING = Object.seal(\n create(null, {\n tagCheck: {\n writable: true,\n configurable: false,\n enumerable: true,\n value: null,\n },\n attributeCheck: {\n writable: true,\n configurable: false,\n enumerable: true,\n value: null,\n },\n })\n );\n\n /* Decide if ARIA attributes are okay */\n let ALLOW_ARIA_ATTR = true;\n\n /* Decide if custom data attributes are okay */\n let ALLOW_DATA_ATTR = true;\n\n /* Decide if unknown protocols are okay */\n let ALLOW_UNKNOWN_PROTOCOLS = false;\n\n /* Decide if self-closing tags in attributes are allowed.\n * Usually removed due to a mXSS issue in jQuery 3.0 */\n let ALLOW_SELF_CLOSE_IN_ATTR = true;\n\n /* Output should be safe for common template engines.\n * This means, DOMPurify removes data attributes, mustaches and ERB\n */\n let SAFE_FOR_TEMPLATES = false;\n\n /* Output should be safe even for XML used within HTML and alike.\n * This means, DOMPurify removes comments when containing risky content.\n */\n let SAFE_FOR_XML = true;\n\n /* Decide if document with <html>... should be returned */\n let WHOLE_DOCUMENT = false;\n\n /* Track whether config is already set on this instance of DOMPurify. */\n let SET_CONFIG = false;\n\n /* Decide if all elements (e.g. style, script) must be children of\n * document.body. By default, browsers might move them to document.head */\n let FORCE_BODY = false;\n\n /* Decide if a DOM `HTMLBodyElement` should be returned, instead of a html\n * string (or a TrustedHTML object if Trusted Types are supported).\n * If `WHOLE_DOCUMENT` is enabled a `HTMLHtmlElement` will be returned instead\n */\n let RETURN_DOM = false;\n\n /* Decide if a DOM `DocumentFragment` should be returned, instead of a html\n * string (or a TrustedHTML object if Trusted Types are supported) */\n let RETURN_DOM_FRAGMENT = false;\n\n /* Try to return a Trusted Type object instead of a string, return a string in\n * case Trusted Types are not supported */\n let RETURN_TRUSTED_TYPE = false;\n\n /* Output should be free from DOM clobbering attacks?\n * This sanitizes markups named with colliding, clobberable built-in DOM APIs.\n */\n let SANITIZE_DOM = true;\n\n /* Achieve full DOM Clobbering protection by isolating the namespace of named\n * properties and JS variables, mitigating attacks that abuse the HTML/DOM spec rules.\n *\n * HTML/DOM spec rules that enable DOM Clobbering:\n * - Named Access on Window (§7.3.3)\n * - DOM Tree Accessors (§3.1.5)\n * - Form Element Parent-Child Relations (§4.10.3)\n * - Iframe srcdoc / Nested WindowProxies (§4.8.5)\n * - HTMLCollection (§4.2.10.2)\n *\n * Namespace isolation is implemented by prefixing `id` and `name` attributes\n * with a constant string, i.e., `user-content-`\n */\n let SANITIZE_NAMED_PROPS = false;\n const SANITIZE_NAMED_PROPS_PREFIX = 'user-content-';\n\n /* Keep element content when removing element? */\n let KEEP_CONTENT = true;\n\n /* If a `Node` is passed to sanitize(), then performs sanitization in-place instead\n * of importing it into a new Document and returning a sanitized copy */\n let IN_PLACE = false;\n\n /* Allow usage of profiles like html, svg and mathMl */\n let USE_PROFILES: UseProfilesConfig | false = {};\n\n /* Tags to ignore content of when KEEP_CONTENT is true */\n let FORBID_CONTENTS = null;\n const DEFAULT_FORBID_CONTENTS = addToSet({}, [\n 'annotation-xml',\n 'audio',\n 'colgroup',\n 'desc',\n 'foreignobject',\n 'head',\n 'iframe',\n 'math',\n 'mi',\n 'mn',\n 'mo',\n 'ms',\n 'mtext',\n 'noembed',\n 'noframes',\n 'noscript',\n 'plaintext',\n 'script',\n 'style',\n 'svg',\n 'template',\n 'thead',\n 'title',\n 'video',\n 'xmp',\n ]);\n\n /* Tags that are safe for data: URIs */\n let DATA_URI_TAGS = null;\n const DEFAULT_DATA_URI_TAGS = addToSet({}, [\n 'audio',\n 'video',\n 'img',\n 'source',\n 'image',\n 'track',\n ]);\n\n /* Attributes safe for values like \"javascript:\" */\n let URI_SAFE_ATTRIBUTES = null;\n const DEFAULT_URI_SAFE_ATTRIBUTES = addToSet({}, [\n 'alt',\n 'class',\n 'for',\n 'id',\n 'label',\n 'name',\n 'pattern',\n 'placeholder',\n 'role',\n 'summary',\n 'title',\n 'value',\n 'style',\n 'xmlns',\n ]);\n\n const MATHML_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';\n const SVG_NAMESPACE = 'http://www.w3.org/2000/svg';\n const HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';\n /* Document namespace */\n let NAMESPACE = HTML_NAMESPACE;\n let IS_EMPTY_INPUT = false;\n\n /* Allowed XHTML+XML namespaces */\n let ALLOWED_NAMESPACES = null;\n const DEFAULT_ALLOWED_NAMESPACES = addToSet(\n {},\n [MATHML_NAMESPACE, SVG_NAMESPACE, HTML_NAMESPACE],\n stringToString\n );\n\n let MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, [\n 'mi',\n 'mo',\n 'mn',\n 'ms',\n 'mtext',\n ]);\n\n let HTML_INTEGRATION_POINTS = addToSet({}, ['annotation-xml']);\n\n // Certain elements are allowed in both SVG and HTML\n // namespace. We need to specify them explicitly\n // so that they don't get erroneously deleted from\n // HTML namespace.\n const COMMON_SVG_AND_HTML_ELEMENTS = addToSet({}, [\n 'title',\n 'style',\n 'font',\n 'a',\n 'script',\n ]);\n\n /* Parsing of strict XHTML documents */\n let PARSER_MEDIA_TYPE: null | DOMParserSupportedType = null;\n const SUPPORTED_PARSER_MEDIA_TYPES = ['application/xhtml+xml', 'text/html'];\n const DEFAULT_PARSER_MEDIA_TYPE = 'text/html';\n let transformCaseFunc: null | Parameters<typeof addToSet>[2] = null;\n\n /* Keep a reference to config to pass to hooks */\n let CONFIG: Config | null = null;\n\n /* Ideally, do not touch anything below this line */\n /* ______________________________________________ */\n\n const formElement = document.createElement('form');\n\n const isRegexOrFunction = function (\n testValue: unknown\n ): testValue is Function | RegExp {\n return testValue instanceof RegExp || testValue instanceof Function;\n };\n\n /**\n * _parseConfig\n *\n * @param cfg optional config literal\n */\n // eslint-disable-next-line complexity\n const _parseConfig = function (cfg: Config = {}): void {\n if (CONFIG && CONFIG === cfg) {\n return;\n }\n\n /* Shield configuration object from tampering */\n if (!cfg || typeof cfg !== 'object') {\n cfg = {};\n }\n\n /* Shield configuration object from prototype pollution */\n cfg = clone(cfg);\n\n PARSER_MEDIA_TYPE =\n // eslint-disable-next-line unicorn/prefer-includes\n SUPPORTED_PARSER_MEDIA_TYPES.indexOf(cfg.PARSER_MEDIA_TYPE) === -1\n ? DEFAULT_PARSER_MEDIA_TYPE\n : cfg.PARSER_MEDIA_TYPE;\n\n // HTML tags and attributes are not case-sensitive, converting to lowercase. Keeping XHTML as is.\n transformCaseFunc =\n PARSER_MEDIA_TYPE === 'application/xhtml+xml'\n ? stringToString\n : stringToLowerCase;\n\n /* Set configuration parameters */\n ALLOWED_TAGS = objectHasOwnProperty(cfg, 'ALLOWED_TAGS')\n ? addToSet({}, cfg.ALLOWED_TAGS, transformCaseFunc)\n : DEFAULT_ALLOWED_TAGS;\n ALLOWED_ATTR = objectHasOwnProperty(cfg, 'ALLOWED_ATTR')\n ? addToSet({}, cfg.ALLOWED_ATTR, transformCaseFunc)\n : DEFAULT_ALLOWED_ATTR;\n ALLOWED_NAMESPACES = objectHasOwnProperty(cfg, 'ALLOWED_NAMESPACES')\n ? addToSet({}, cfg.ALLOWED_NAMESPACES, stringToString)\n : DEFAULT_ALLOWED_NAMESPACES;\n URI_SAFE_ATTRIBUTES = objectHasOwnProperty(cfg, 'ADD_URI_SAFE_ATTR')\n ? addToSet(\n clone(DEFAULT_URI_SAFE_ATTRIBUTES),\n cfg.ADD_URI_SAFE_ATTR,\n transformCaseFunc\n )\n : DEFAULT_URI_SAFE_ATTRIBUTES;\n DATA_URI_TAGS = objectHasOwnProperty(cfg, 'ADD_DATA_URI_TAGS')\n ? addToSet(\n clone(DEFAULT_DATA_URI_TAGS),\n cfg.ADD_DATA_URI_TAGS,\n transformCaseFunc\n )\n : DEFAULT_DATA_URI_TAGS;\n FORBID_CONTENTS = objectHasOwnProperty(cfg, 'FORBID_CONTENTS')\n ? addToSet({}, cfg.FORBID_CONTENTS, transformCaseFunc)\n : DEFAULT_FORBID_CONTENTS;\n FORBID_TAGS = objectHasOwnProperty(cfg, 'FORBID_TAGS')\n ? addToSet({}, cfg.FORBID_TAGS, transformCaseFunc)\n : clone({});\n FORBID_ATTR = objectHasOwnProperty(cfg, 'FORBID_ATTR')\n ? addToSet({}, cfg.FORBID_ATTR, transformCaseFunc)\n : clone({});\n USE_PROFILES = objectHasOwnProperty(cfg, 'USE_PROFILES')\n ? cfg.USE_PROFILES\n : false;\n ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false; // Default true\n ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false; // Default true\n ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false; // Default false\n ALLOW_SELF_CLOSE_IN_ATTR = cfg.ALLOW_SELF_CLOSE_IN_ATTR !== false; // Default true\n SAFE_FOR_TEMPLATES = cfg.SAFE_FOR_TEMPLATES || false; // Default false\n SAFE_FOR_XML = cfg.SAFE_FOR_XML !== false; // Default true\n WHOLE_DOCUMENT = cfg.WHOLE_DOCUMENT || false; // Default false\n RETURN_DOM = cfg.RETURN_DOM || false; // Default false\n RETURN_DOM_FRAGMENT = cfg.RETURN_DOM_FRAGMENT || false; // Default false\n RETURN_TRUSTED_TYPE = cfg.RETURN_TRUSTED_TYPE || false; // Default false\n FORCE_BODY = cfg.FORCE_BODY || false; // Default false\n SANITIZE_DOM = cfg.SANITIZE_DOM !== false; // Default true\n SANITIZE_NAMED_PROPS = cfg.SANITIZE_NAMED_PROPS || false; // Default false\n KEEP_CONTENT = cfg.KEEP_CONTENT !== false; // Default true\n IN_PLACE = cfg.IN_PLACE || false; // Default false\n IS_ALLOWED_URI = cfg.ALLOWED_URI_REGEXP || EXPRESSIONS.IS_ALLOWED_URI;\n NAMESPACE = cfg.NAMESPACE || HTML_NAMESPACE;\n MATHML_TEXT_INTEGRATION_POINTS =\n cfg.MATHML_TEXT_INTEGRATION_POINTS || MATHML_TEXT_INTEGRATION_POINTS;\n HTML_INTEGRATION_POINTS =\n cfg.HTML_INTEGRATION_POINTS || HTML_INTEGRATION_POINTS;\n\n CUSTOM_ELEMENT_HANDLING = cfg.CUSTOM_ELEMENT_HANDLING || {};\n if (\n cfg.CUSTOM_ELEMENT_HANDLING &&\n isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck)\n ) {\n CUSTOM_ELEMENT_HANDLING.tagNameCheck =\n cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck;\n }\n\n if (\n cfg.CUSTOM_ELEMENT_HANDLING &&\n isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)\n ) {\n CUSTOM_ELEMENT_HANDLING.attributeNameCheck =\n cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck;\n }\n\n if (\n cfg.CUSTOM_ELEMENT_HANDLING &&\n typeof cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements ===\n 'boolean'\n ) {\n CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements =\n cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements;\n }\n\n if (SAFE_FOR_TEMPLATES) {\n ALLOW_DATA_ATTR = false;\n }\n\n if (RETURN_DOM_FRAGMENT) {\n RETURN_DOM = true;\n }\n\n /* Parse profile info */\n if (USE_PROFILES) {\n ALLOWED_TAGS = addToSet({}, TAGS.text);\n ALLOWED_ATTR = [];\n if (USE_PROFILES.html === true) {\n addToSet(ALLOWED_TAGS, TAGS.html);\n addToSet(ALLOWED_ATTR, ATTRS.html);\n }\n\n if (USE_PROFILES.svg === true) {\n addToSet(ALLOWED_TAGS, TAGS.svg);\n addToSet(ALLOWED_ATTR, ATTRS.svg);\n addToSet(ALLOWED_ATTR, ATTRS.xml);\n }\n\n if (USE_PROFILES.svgFilters === true) {\n addToSet(ALLOWED_TAGS, TAGS.svgFilters);\n addToSet(ALLOWED_ATTR, ATTRS.svg);\n addToSet(ALLOWED_ATTR, ATTRS.xml);\n }\n\n if (USE_PROFILES.mathMl === true) {\n addToSet(ALLOWED_TAGS, TAGS.mathMl);\n addToSet(ALLOWED_ATTR, ATTRS.mathMl);\n addToSet(ALLOWED_ATTR, ATTRS.xml);\n }\n }\n\n /* Merge configuration parameters */\n if (cfg.ADD_TAGS) {\n if (typeof cfg.ADD_TAGS === 'function') {\n EXTRA_ELEMENT_HANDLING.tagCheck = cfg.ADD_TAGS;\n } else {\n if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) {\n ALLOWED_TAGS = clone(ALLOWED_TAGS);\n }\n\n addToSet(ALLOWED_TAGS, cfg.ADD_TAGS, transformCaseFunc);\n }\n }\n\n if (cfg.ADD_ATTR) {\n if (typeof cfg.ADD_ATTR === 'function') {\n EXTRA_ELEMENT_HANDLING.attributeCheck = cfg.ADD_ATTR;\n } else {\n if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) {\n ALLOWED_ATTR = clone(ALLOWED_ATTR);\n }\n\n addToSet(ALLOWED_ATTR, cfg.ADD_ATTR, transformCaseFunc);\n }\n }\n\n if (cfg.ADD_URI_SAFE_ATTR) {\n addToSet(URI_SAFE_ATTRIBUTES, cfg.ADD_URI_SAFE_ATTR, transformCaseFunc);\n }\n\n if (cfg.FORBID_CONTENTS) {\n if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {\n FORBID_CONTENTS = clone(FORBID_CONTENTS);\n }\n\n addToSet(FORBID_CONTENTS, cfg.FORBID_CONTENTS, transformCaseFunc);\n }\n\n /* Add #text in case KEEP_CONTENT is set to true */\n if (KEEP_CONTENT) {\n ALLOWED_TAGS['#text'] = true;\n }\n\n /* Add html, head and body to ALLOWED_TAGS in case WHOLE_DOCUMENT is true */\n if (WHOLE_DOCUMENT) {\n addToSet(ALLOWED_TAGS, ['html', 'head', 'body']);\n }\n\n /* Add tbody to ALLOWED_TAGS in case tables are permitted, see #286, #365 */\n if (ALLOWED_TAGS.table) {\n addToSet(ALLOWED_TAGS, ['tbody']);\n delete FORBID_TAGS.tbody;\n }\n\n if (cfg.TRUSTED_TYPES_POLICY) {\n if (typeof cfg.TRUSTED_TYPES_POLICY.createHTML !== 'function') {\n throw typeErrorCreate(\n 'TRUSTED_TYPES_POLICY configuration option must provide a \"createHTML\" hook.'\n );\n }\n\n if (typeof cfg.TRUSTED_TYPES_POLICY.createScriptURL !== 'function') {\n throw typeErrorCreate(\n 'TRUSTED_TYPES_POLICY configuration option must provide a \"createScriptURL\" hook.'\n );\n }\n\n // Overwrite existing TrustedTypes policy.\n trustedTypesPolicy = cfg.TRUSTED_TYPES_POLICY;\n\n // Sign local variables required by `sanitize`.\n emptyHTML = trustedTypesPolicy.createHTML('');\n } else {\n // Uninitialized policy, attempt to initialize the internal dompurify policy.\n if (trustedTypesPolicy === undefined) {\n trustedTypesPolicy = _createTrustedTypesPolicy(\n trustedTypes,\n currentScript\n );\n }\n\n // If creating the internal policy succeeded sign internal variables.\n if (trustedTypesPolicy !== null && typeof emptyHTML === 'string') {\n emptyHTML = trustedTypesPolicy.createHTML('');\n }\n }\n\n // Prevent further manipulation of configuration.\n // Not available in IE8, Safari 5, etc.\n if (freeze) {\n freeze(cfg);\n }\n\n CONFIG = cfg;\n };\n\n /* Keep track of all possible SVG and MathML tags\n * so that we can perform the namespace checks\n * correctly. */\n const ALL_SVG_TAGS = addToSet({}, [\n ...TAGS.svg,\n ...TAGS.svgFilters,\n ...TAGS.svgDisallowed,\n ]);\n const ALL_MATHML_TAGS = addToSet({}, [\n ...TAGS.mathMl,\n ...TAGS.mathMlDisallowed,\n ]);\n\n /**\n * @param element a DOM element whose namespace is being checked\n * @returns Return false if the element has a\n * namespace that a spec-compliant parser would never\n * return. Return true otherwise.\n */\n const _checkValidNamespace = function (element: Element): boolean {\n let parent = getParentNode(element);\n\n // In JSDOM, if we're inside shadow DOM, then parentNode\n // can be null. We just simulate parent in this case.\n if (!parent || !parent.tagName) {\n parent = {\n namespaceURI: NAMESPACE,\n tagName: 'template',\n };\n }\n\n const tagName = stringToLowerCase(element.tagName);\n const parentTagName = stringToLowerCase(parent.tagName);\n\n if (!ALLOWED_NAMESPACES[element.namespaceURI]) {\n return false;\n }\n\n if (element.namespaceURI === SVG_NAMESPACE) {\n // The only way to switch from HTML namespace to SVG\n // is via <svg>. If it happens via any other tag, then\n // it should be killed.\n if (parent.namespaceURI === HTML_NAMESPACE) {\n return tagName === 'svg';\n }\n\n // The only way to switch from MathML to SVG is via`\n // svg if parent is either <annotation-xml> or MathML\n // text integration points.\n if (parent.namespaceURI === MATHML_NAMESPACE) {\n return (\n tagName === 'svg' &&\n (parentTagName === 'annotation-xml' ||\n MATHML_TEXT_INTEGRATION_POINTS[parentTagName])\n );\n }\n\n // We only allow elements that are defined in SVG\n // spec. All others are disallowed in SVG namespace.\n return Boolean(ALL_SVG_TAGS[tagName]);\n }\n\n if (element.namespaceURI === MATHML_NAMESPACE) {\n // The only way to switch from HTML namespace to MathML\n // is via <math>. If it happens via any other tag, then\n // it should be killed.\n if (parent.namespaceURI === HTML_NAMESPACE) {\n return tagName === 'math';\n }\n\n // The only way to switch from SVG to MathML is via\n // <math> and HTML integration points\n if (parent.namespaceURI === SVG_NAMESPACE) {\n return tagName === 'math' && HTML_INTEGRATION_POINTS[parentTagName];\n }\n\n // We only allow elements that are defined in MathML\n // spec. All others are disallowed in MathML namespace.\n return Boolean(ALL_MATHML_TAGS[tagName]);\n }\n\n if (element.namespaceURI === HTML_NAMESPACE) {\n // The only way to switch from SVG to HTML is via\n // HTML integration points, and from MathML to HTML\n // is via MathML text integration points\n if (\n parent.namespaceURI === SVG_NAMESPACE &&\n !HTML_INTEGRATION_POINTS[parentTagName]\n ) {\n return false;\n }\n\n if (\n parent.namespaceURI === MATHML_NAMESPACE &&\n !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]\n ) {\n return false;\n }\n\n // We disallow tags that are specific for MathML\n // or SVG and should never appear in HTML namespace\n return (\n !ALL_MATHML_TAGS[tagName] &&\n (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName])\n );\n }\n\n // For XHTML and XML documents that support custom namespaces\n if (\n PARSER_MEDIA_TYPE === 'application/xhtml+xml' &&\n ALLOWED_NAMESPACES[element.namespaceURI]\n ) {\n return true;\n }\n\n // The code should never reach this place (this means\n // that the element somehow got namespace that is not\n // HTML, SVG, MathML or allowed via ALLOWED_NAMESPACES).\n // Return false just in case.\n return false;\n };\n\n /**\n * _forceRemove\n *\n * @param node a DOM node\n */\n const _forceRemove = function (node: Node): void {\n arrayPush(DOMPurify.removed, { element: node });\n\n try {\n // eslint-disable-next-line unicorn/prefer-dom-node-remove\n getParentNode(node).removeChild(node);\n } catch (_) {\n remove(node);\n }\n };\n\n /**\n * _removeAttribute\n *\n * @param name an Attribute name\n * @param element a DOM node\n */\n const _removeAttribute = function (name: string, element: Element): void {\n try {\n arrayPush(DOMPurify.removed, {\n attribute: element.getAttributeNode(name),\n from: element,\n });\n } catch (_) {\n arrayPush(DOMPurify.removed, {\n attribute: null,\n from: element,\n });\n }\n\n element.removeAttribute(name);\n\n // We void attribute values for unremovable \"is\" attributes\n if (name === 'is') {\n if (RETURN_DOM || RETURN_DOM_FRAGMENT) {\n try {\n _forceRemove(element);\n } catch (_) {}\n } else {\n try {\n element.setAttribute(name, '');\n } catch (_) {}\n }\n }\n };\n\n /**\n * _initDocument\n *\n * @param dirty - a string of dirty markup\n * @return a DOM, filled with the dirty markup\n */\n const _initDocument = function (dirty: string): Document {\n /* Create a HTML document */\n let doc = null;\n let leadingWhitespace = null;\n\n if (FORCE_BODY) {\n dirty = '<remove></remove>' + dirty;\n } else {\n /* If FORCE_BODY isn't used, leading whitespace needs to be preserved manually */\n const matches = stringMatch(dirty, /^[\\r\\n\\t ]+/);\n leadingWhitespace = matches && matches[0];\n }\n\n if (\n PARSER_MEDIA_TYPE === 'application/xhtml+xml' &&\n NAMESPACE === HTML_NAMESPACE\n ) {\n // Root of XHTML doc must contain xmlns declaration (see https://www.w3.org/TR/xhtml1/normative.html#strict)\n dirty =\n '<html xmlns=\"http://www.w3.org/1999/xhtml\"><head></head><body>' +\n dirty +\n '</body></html>';\n }\n\n const dirtyPayload = trustedTypesPolicy\n ? trustedTypesPolicy.createHTML(dirty)\n : dirty;\n /*\n * Use the DOMParser API by default, fallback later if needs be\n * DOMParser not work for svg when has multiple root element.\n */\n if (NAMESPACE === HTML_NAMESPACE) {\n try {\n doc = new DOMParser().parseFromString(dirtyPayload, PARSER_MEDIA_TYPE);\n } catch (_) {}\n }\n\n /* Use createHTMLDocument in case DOMParser is not available */\n if (!doc || !doc.documentElement) {\n doc = implementation.createDocument(NAMESPACE, 'template', null);\n try {\n doc.documentElement.innerHTML = IS_EMPTY_INPUT\n ? emptyHTML\n : dirtyPayload;\n } catch (_) {\n // Syntax error if dirtyPayload is invalid xml\n }\n }\n\n const body = doc.body || doc.documentElement;\n\n if (dirty && leadingWhitespace) {\n body.insertBefore(\n document.createTextNode(leadingWhitespace),\n body.childNodes[0] || null\n );\n }\n\n /* Work on whole document or just its body */\n if (NAMESPACE === HTML_NAMESPACE) {\n return getElementsByTagName.call(\n doc,\n WHOLE_DOCUMENT ? 'html' : 'body'\n )[0];\n }\n\n return WHOLE_DOCUMENT ? doc.documentElement : body;\n };\n\n /**\n * Creates a NodeIterator object that you can use to traverse filtered lists of nodes or elements in a document.\n *\n * @param root The root element or node to start traversing on.\n * @return The created NodeIterator\n */\n const _createNodeIterator = function (root: Node): NodeIterator {\n return createNodeIterator.call(\n root.ownerDocument || root,\n root,\n // eslint-disable-next-line no-bitwise\n NodeFilter.SHOW_ELEMENT |\n NodeFilter.SHOW_COMMENT |\n NodeFilter.SHOW_TEXT |\n NodeFilter.SHOW_PROCESSING_INSTRUCTION |\n NodeFilter.SHOW_CDATA_SECTION,\n null\n );\n };\n\n /**\n * _isClobbered\n *\n * @param element element to check for clobbering attacks\n * @return true if clobbered, false if safe\n */\n const _isClobbered = function (element: Element): boolean {\n return (\n element instanceof HTMLFormElement &&\n (typeof element.nodeName !== 'string' ||\n typeof element.textContent !== 'string' ||\n typeof element.removeChild !== 'function' ||\n !(element.attributes instanceof NamedNodeMap) ||\n typeof element.removeAttribute !== 'function' ||\n typeof element.setAttribute !== 'function' ||\n typeof element.namespaceURI !== 'string' ||\n typeof element.insertBefore !== 'function' ||\n typeof element.hasChildNodes !== 'function')\n );\n };\n\n /**\n * Checks whether the given object is a DOM node.\n *\n * @param value object to check whether it's a DOM node\n * @return true is object is a DOM node\n */\n const _isNode = function (value: unknown): value is Node {\n return typeof Node === 'function' && value instanceof Node;\n };\n\n function _executeHooks<T extends HookFunction>(\n hooks: HookFunction[],\n currentNode: Parameters<T>[0],\n data: Parameters<T>[1]\n ): void {\n arrayForEach(hooks, (hook: T) => {\n hook.call(DOMPurify, currentNode, data, CONFIG);\n });\n }\n\n /**\n * _sanitizeElements\n *\n * @protect nodeName\n * @protect textContent\n * @protect removeChild\n * @param currentNode to check for permission to exist\n * @return true if node was killed, false if left alive\n */\n const _sanitizeElements = function (currentNode: any): boolean {\n let content = null;\n\n /* Execute a hook if present */\n _executeHooks(hooks.beforeSanitizeElements, currentNode, null);\n\n /* Check if element is clobbered or can clobber */\n if (_isClobbered(currentNode)) {\n _forceRemove(currentNode);\n return true;\n }\n\n /* Now let's check the element's type and name */\n const tagName = transformCaseFunc(currentNode.nodeName);\n\n /* Execute a hook if present */\n _executeHooks(hooks.uponSanitizeElement, currentNode, {\n tagName,\n allowedTags: ALLOWED_TAGS,\n });\n\n /* Detect mXSS attempts abusing namespace confusion */\n if (\n SAFE_FOR_XML &&\n currentNode.hasChildNodes() &&\n !_isNode(currentNode.firstElementChild) &&\n regExpTest(/<[/\\w!]/g, currentNode.innerHTML) &&\n regExpTest(/<[/\\w!]/g, currentNode.textContent)\n ) {\n _forceRemove(currentNode);\n return true;\n }\n\n /* Remove any occurrence of processing instructions */\n if (currentNode.nodeType === NODE_TYPE.progressingInstruction) {\n _forceRemove(currentNode);\n return true;\n }\n\n /* Remove any kind of possibly harmful comments */\n if (\n SAFE_FOR_XML &&\n currentNode.nodeType === NODE_TYPE.comment &&\n regExpTest(/<[/\\w]/g, currentNode.data)\n ) {\n _forceRemove(currentNode);\n return true;\n }\n\n /* Remove element if anything forbids its presence */\n if (\n !(\n EXTRA_ELEMENT_HANDLING.tagCheck instanceof Function &&\n EXTRA_ELEMENT_HANDLING.tagCheck(tagName)\n ) &&\n (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName])\n ) {\n /* Check if we have a custom element to handle */\n if (!FORBID_TAGS[tagName] && _isBasicCustomElement(tagName)) {\n if (\n CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp &&\n regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName)\n ) {\n return false;\n }\n\n if (\n CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function &&\n CUSTOM_ELEMENT_HANDLING.tagNameCheck(tagName)\n ) {\n return false;\n }\n }\n\n /* Keep content except for bad-listed elements */\n if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) {\n const parentNode = getParentNode(currentNode) || currentNode.parentNode;\n const childNodes = getChildNodes(currentNode) || currentNode.childNodes;\n\n if (childNodes && parentNode) {\n const childCount = childNodes.length;\n\n for (let i = childCount - 1; i >= 0; --i) {\n const childClone = cloneNode(childNodes[i], true);\n childClone.__removalCount = (currentNode.__removalCount || 0) + 1;\n parentNode.insertBefore(childClone, getNextSibling(currentNode));\n }\n }\n }\n\n _forceRemove(currentNode);\n return true;\n }\n\n /* Check whether element has a valid namespace */\n if (currentNode instanceof Element && !_checkValidNamespace(currentNode)) {\n _forceRemove(currentNode);\n return true;\n }\n\n /* Make sure that older browsers don't get fallback-tag mXSS */\n if (\n (tagName === 'noscript' ||\n tagName === 'noembed' ||\n tagName === 'noframes') &&\n regExpTest(/<\\/no(script|embed|frames)/i, currentNode.innerHTML)\n ) {\n _forceRemove(currentNode);\n return true;\n }\n\n /* Sanitize element content to be template-safe */\n if (SAFE_FOR_TEMPLATES && currentNode.nodeType === NODE_TYPE.text) {\n /* Get the element's text content */\n content = currentNode.textContent;\n\n arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], (expr: RegExp) => {\n content = stringReplace(content, expr, ' ');\n });\n\n if (currentNode.textContent !== content) {\n arrayPush(DOMPurify.removed, { element: currentNode.cloneNode() });\n currentNode.textContent = content;\n }\n }\n\n /* Execute a hook if present */\n _executeHooks(hooks.afterSanitizeElements, currentNode, null);\n\n return false;\n };\n\n /**\n * _isValidAttribute\n *\n * @param lcTag Lowercase tag name of containing element.\n * @param lcName Lowercase attribute name.\n * @param value Attribute value.\n * @return Returns true if `value` is valid, otherwise false.\n */\n // eslint-disable-next-line complexity\n const _isValidAttribute = function (\n lcTag: string,\n lcName: string,\n value: string\n ): boolean {\n /* Make sure attribute cannot clobber */\n if (\n SANITIZE_DOM &&\n (lcName === 'id' || lcName === 'name') &&\n (value in document || value in formElement)\n ) {\n return false;\n }\n\n /* Allow valid data-* attributes: At least one character after \"-\"\n (https://html.spec.whatwg.org/multipage/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes)\n XML-compatible (https://html.spec.whatwg.org/multipage/infrastructure.html#xml-compatible and http://www.w3.org/TR/xml/#d0e804)\n We don't need to check the value; it's always URI safe. */\n if (\n ALLOW_DATA_ATTR &&\n !FORBID_ATTR[lcName] &&\n regExpTest(DATA_ATTR, lcName)\n ) {\n // This attribute is safe\n } else if (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR, lcName)) {\n // This attribute is safe\n /* Check if ADD_ATTR function allows this attribute */\n } else if (\n EXTRA_ELEMENT_HANDLING.attributeCheck instanceof Function &&\n EXTRA_ELEMENT_HANDLING.attributeCheck(lcName, lcTag)\n ) {\n // This attribute is safe\n /* Otherwise, check the name is permitted */\n } else if (!ALLOWED_ATTR[lcName] || FORBID_ATTR[lcName]) {\n if (\n // First condition does a very basic check if a) it's basically a valid custom element tagname AND\n // b) if the tagName passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck\n // and c) if the attribute name passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.attributeNameCheck\n (_isBasicCustomElement(lcTag) &&\n ((CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp &&\n regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, lcTag)) ||\n (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function &&\n CUSTOM_ELEMENT_HANDLING.tagNameCheck(lcTag))) &&\n ((CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof RegExp &&\n regExpTest(CUSTOM_ELEMENT_HANDLING.attributeNameCheck, lcName)) ||\n (CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof Function &&\n CUSTOM_ELEMENT_HANDLING.attributeNameCheck(lcName, lcTag)))) ||\n // Alternative, second condition checks if it's an `is`-attribute, AND\n // the value passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck\n (lcName === 'is' &&\n CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements &&\n ((CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp &&\n regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, value)) ||\n (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function &&\n CUSTOM_ELEMENT_HANDLING.tagNameCheck(value))))\n ) {\n // If user has supplied a regexp or function in CUSTOM_ELEMENT_HANDLING.tagNameCheck, we need to also allow derived custom elements using the same tagName test.\n // Additionally, we need to allow attributes passing the CUSTOM_ELEMENT_HANDLING.attributeNameCheck user has configured, as custom elements can define these at their own discretion.\n } else {\n return false;\n }\n /* Check value is safe. First, is attr inert? If so, is safe */\n } else if (URI_SAFE_ATTRIBUTES[lcName]) {\n // This attribute is safe\n /* Check no script, data or unknown possibly unsafe URI\n unless we know URI values are safe for that attribute */\n } else if (\n regExpTest(IS_ALLOWED_URI, stringReplace(value, ATTR_WHITESPACE, ''))\n ) {\n // This attribute is safe\n /* Keep image data URIs alive if src/xlink:href is allowed */\n /* Further prevent gadget XSS for dynamically built script tags */\n } else if (\n (lcName === 'src' || lcName === 'xlink:href' || lcName === 'href') &&\n lcTag !== 'script' &&\n stringIndexOf(value, 'data:') === 0 &&\n DATA_URI_TAGS[lcTag]\n ) {\n // This attribute is safe\n /* Allow unknown protocols: This provides support for links that\n are handled by protocol handlers which may be unknown ahead of\n time, e.g. fb:, spotify: */\n } else if (\n ALLOW_UNKNOWN_PROTOCOLS &&\n !regExpTest(IS_SCRIPT_OR_DATA, stringReplace(value, ATTR_WHITESPACE, ''))\n ) {\n // This attribute is safe\n /* Check for binary attributes */\n } else if (value) {\n return false;\n } else {\n // Binary attributes are safe at this point\n /* Anything else, presume unsafe, do not add it back */\n }\n\n return true;\n };\n\n /**\n * _isBasicCustomElement\n * checks if at least one dash is included in tagName, and it's not the first char\n * for more sophisticated checking see https://github.com/sindresorhus/validate-element-name\n *\n * @param tagName name of the tag of the node to sanitize\n * @returns Returns true if the tag name meets the basic criteria for a custom element, otherwise false.\n */\n const _isBasicCustomElement = function (tagName: string): RegExpMatchArray {\n return tagName !== 'annotation-xml' && stringMatch(tagName, CUSTOM_ELEMENT);\n };\n\n /**\n * _sanitizeAttributes\n *\n * @protect attributes\n * @protect nodeName\n * @protect removeAttribute\n * @protect setAttribute\n *\n * @param currentNode to sanitize\n */\n const _sanitizeAttributes = function (currentNode: Element): void {\n /* Execute a hook if present */\n _executeHooks(hooks.beforeSanitizeAttributes, currentNode, null);\n\n const { attributes } = currentNode;\n\n /* Check if we have attributes; if not we might have a text node */\n if (!attributes || _isClobbered(currentNode)) {\n return;\n }\n\n const hookEvent = {\n attrName: '',\n attrValue: '',\n keepAttr: true,\n allowedAttributes: ALLOWED_ATTR,\n forceKeepAttr: undefined,\n };\n let l = attributes.length;\n\n /* Go backwards over all attributes; safely remove bad ones */\n while (l--) {\n const attr = attributes[l];\n const { name, namespaceURI, value: attrValue } = attr;\n const lcName = transformCaseFunc(name);\n\n const initValue = attrValue;\n let value = name === 'value' ? initValue : stringTrim(initValue);\n\n /* Execute a hook if present */\n hookEvent.attrName = lcName;\n hookEvent.attrValue = value;\n hookEvent.keepAttr = true;\n hookEvent.forceKeepAttr = undefined; // Allows developers to see this is a property they can set\n _executeHooks(hooks.uponSanitizeAttribute, currentNode, hookEvent);\n value = hookEvent.attrValue;\n\n /* Full DOM Clobbering protection via namespace isolation,\n * Prefix id and name attributes with `user-content-`\n */\n if (SANITIZE_NAMED_PROPS && (lcName === 'id' || lcName === 'name')) {\n // Remove the attribute with this value\n _removeAttribute(name, currentNode);\n\n // Prefix the value and later re-create the attribute with the sanitized value\n value = SANITIZE_NAMED_PROPS_PREFIX + value;\n }\n\n /* Work around a security issue with comments inside attributes */\n if (\n SAFE_FOR_XML &&\n regExpTest(/((--!?|])>)|<\\/(style|title|textarea)/i, value)\n ) {\n _removeAttribute(name, currentNode);\n continue;\n }\n\n /* Make sure we cannot easily use animated hrefs, even if animations are allowed */\n if (lcName === 'attributename' && stringMatch(value, 'href')) {\n _removeAttribute(name, currentNode);\n continue;\n }\n\n /* Did the hooks approve of the attribute? */\n if (hookEvent.forceKeepAttr) {\n continue;\n }\n\n /* Did the hooks approve of the attribute? */\n if (!hookEvent.keepAttr) {\n _removeAttribute(name, currentNode);\n continue;\n }\n\n /* Work around a security issue in jQuery 3.0 */\n if (!ALLOW_SELF_CLOSE_IN_ATTR && regExpTest(/\\/>/i, value)) {\n _removeAttribute(name, currentNode);\n continue;\n }\n\n /* Sanitize attribute content to be template-safe */\n if (SAFE_FOR_TEMPLATES) {\n arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], (expr: RegExp) => {\n value = stringReplace(value, expr, ' ');\n });\n }\n\n /* Is `value` valid for this attribute? */\n const lcTag = transformCaseFunc(currentNode.nodeName);\n if (!_isValidAttribute(lcTag, lcName, value)) {\n _removeAttribute(name, currentNode);\n continue;\n }\n\n /* Handle attributes that require Trusted Types */\n if (\n trustedTypesPolicy &&\n typeof trustedTypes === 'object' &&\n typeof trustedTypes.getAttributeType === 'function'\n ) {\n if (namespaceURI) {\n /* Namespaces are not yet supported, see https://bugs.chromium.org/p/chromium/issues/detail?id=1305293 */\n } else {\n switch (trustedTypes.getAttributeType(lcTag, lcName)) {\n case 'TrustedHTML': {\n value = trustedTypesPolicy.createHTML(value);\n break;\n }\n\n case 'TrustedScriptURL': {\n value = trustedTypesPolicy.createScriptURL(value);\n break;\n }\n\n default: {\n break;\n }\n }\n }\n }\n\n /* Handle invalid data-* attribute set by try-catching it */\n if (value !== initValue) {\n try {\n if (namespaceURI) {\n currentNode.setAttributeNS(namespaceURI, name, value);\n } else {\n /* Fallback to setAttribute() for browser-unrecognized namespaces e.g. \"x-schema\". */\n currentNode.setAttribute(name, value);\n }\n\n if (_isClobbered(currentNode)) {\n _forceRemove(currentNode);\n } else {\n arrayPop(DOMPurify.removed);\n }\n } catch (_) {\n _removeAttribute(name, currentNode);\n }\n }\n }\n\n /* Execute a hook if present */\n _executeHooks(hooks.afterSanitizeAttributes, currentNode, null);\n };\n\n /**\n * _sanitizeShadowDOM\n *\n * @param fragment to iterate over recursively\n */\n const _sanitizeShadowDOM = function (fragment: DocumentFragment): void {\n let shadowNode = null;\n const shadowIterator = _createNodeIterator(fragment);\n\n /* Execute a hook if present */\n _executeHooks(hooks.beforeSanitizeShadowDOM, fragment, null);\n\n while ((shadowNode = shadowIterator.nextNode())) {\n /* Execute a hook if present */\n _executeHooks(hooks.uponSanitizeShadowNode, shadowNode, null);\n\n /* Sanitize tags and elements */\n _sanitizeElements(shadowNode);\n\n /* Check attributes next */\n _sanitizeAttributes(shadowNode);\n\n /* Deep shadow DOM detected */\n if (shadowNode.content instanceof DocumentFragment) {\n _sanitizeShadowDOM(shadowNode.content);\n }\n }\n\n /* Execute a hook if present */\n _executeHooks(hooks.afterSanitizeShadowDOM, fragment, null);\n };\n\n // eslint-disable-next-line complexity\n DOMPurify.sanitize = function (dirty, cfg = {}) {\n let body = null;\n let importedNode = null;\n let currentNode = null;\n let returnNode = null;\n /* Make sure we have a string to sanitize.\n DO NOT return early, as this will return the wrong type if\n the user has requested a DOM object rather than a string */\n IS_EMPTY_INPUT = !dirty;\n if (IS_EMPTY_INPUT) {\n dirty = '<!-->';\n }\n\n /* Stringify, in case dirty is an object */\n if (typeof dirty !== 'string' && !_isNode(dirty)) {\n if (typeof dirty.toString === 'function') {\n dirty = dirty.toString();\n if (typeof dirty !== 'string') {\n throw typeErrorCreate('dirty is not a string, aborting');\n }\n } else {\n throw typeErrorCreate('toString is not a function');\n }\n }\n\n /* Return dirty HTML if DOMPurify cannot run */\n if (!DOMPurify.isSupported) {\n return dirty;\n }\n\n /* Assign config vars */\n if (!SET_CONFIG) {\n _parseConfig(cfg);\n }\n\n /* Clean up removed elements */\n DOMPurify.removed = [];\n\n /* Check if dirty is correctly typed for IN_PLACE */\n if (typeof dirty === 'string') {\n IN_PLACE = false;\n }\n\n if (IN_PLACE) {\n /* Do some early pre-sanitization to avoid unsafe root nodes */\n if ((dirty as Node).nodeName) {\n const tagName = transformCaseFunc((dirty as Node).nodeName);\n if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {\n throw typeErrorCreate(\n 'root node is forbidden and cannot be sanitized in-place'\n );\n }\n }\n } else if (dirty instanceof Node) {\n /* If dirty is a DOM element, append to an empty document to avoid\n elements being stripped by the parser */\n body = _initDocument('<!---->');\n importedNode = body.ownerDocument.importNode(dirty, true);\n if (\n importedNode.nodeType === NODE_TYPE.element &&\n importedNode.nodeName === 'BODY'\n ) {\n /* Node is already a body, use as is */\n body = importedNode;\n } else if (importedNode.nodeName === 'HTML') {\n body = importedNode;\n } else {\n // eslint-disable-next-line unicorn/prefer-dom-node-append\n body.appendChild(importedNode);\n }\n } else {\n /* Exit directly if we have nothing to do */\n if (\n !RETURN_DOM &&\n !SAFE_FOR_TEMPLATES &&\n !WHOLE_DOCUMENT &&\n // eslint-disable-next-line unicorn/prefer-includes\n dirty.indexOf('<') === -1\n ) {\n return trustedTypesPolicy && RETURN_TRUSTED_TYPE\n ? trustedTypesPolicy.createHTML(dirty)\n : dirty;\n }\n\n /* Initialize the document to work on */\n body = _initDocument(dirty);\n\n /* Check we have a DOM node from the data */\n if (!body) {\n return RETURN_DOM ? null : RETURN_TRUSTED_TYPE ? emptyHTML : '';\n }\n }\n\n /* Remove first element node (ours) if FORCE_BODY is set */\n if (body && FORCE_BODY) {\n _forceRemove(body.firstChild);\n }\n\n /* Get node iterator */\n const nodeIterator = _createNodeIterator(IN_PLACE ? dirty : body);\n\n /* Now start iterating over the created document */\n while ((currentNode = nodeIterator.nextNode())) {\n /* Sanitize tags and elements */\n _sanitizeElements(currentNode);\n\n /* Check attributes next */\n _sanitizeAttributes(currentNode);\n\n /* Shadow DOM detected, sanitize it */\n if (currentNode.content instanceof DocumentFragment) {\n _sanitizeShadowDOM(currentNode.content);\n }\n }\n\n /* If we sanitized `dirty` in-place, return it. */\n if (IN_PLACE) {\n return dirty;\n }\n\n /* Return sanitized string or DOM */\n if (RETURN_DOM) {\n if (RETURN_DOM_FRAGMENT) {\n returnNode = createDocumentFragment.call(body.ownerDocument);\n\n while (body.firstChild) {\n // eslint-disable-next-line unicorn/prefer-dom-node-append\n returnNode.appendChild(body.firstChild);\n }\n } else {\n returnNode = body;\n }\n\n if (ALLOWED_ATTR.shadowroot || ALLOWED_ATTR.shadowrootmode) {\n /*\n AdoptNode() is not used because internal state is not reset\n (e.g. the past names map of a HTMLFormElement), this is safe\n in theory but we would rather not risk another attack vector.\n The state that is cloned by importNode() is explicitly defined\n by the specs.\n */\n returnNode = importNode.call(originalDocument, returnNode, true);\n }\n\n return returnNode;\n }\n\n let serializedHTML = WHOLE_DOCUMENT ? body.outerHTML : body.innerHTML;\n\n /* Serialize doctype if allowed */\n if (\n WHOLE_DOCUMENT &&\n ALLOWED_TAGS['!doctype'] &&\n body.ownerDocument &&\n body.ownerDocument.doctype &&\n body.ownerDocument.doctype.name &&\n regExpTest(EXPRESSIONS.DOCTYPE_NAME, body.ownerDocument.doctype.name)\n ) {\n serializedHTML =\n '<!DOCTYPE ' + body.ownerDocument.doctype.name + '>\\n' + serializedHTML;\n }\n\n /* Sanitize final string template-safe */\n if (SAFE_FOR_TEMPLATES) {\n arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], (expr: RegExp) => {\n serializedHTML = stringReplace(serializedHTML, expr, ' ');\n });\n }\n\n return trustedTypesPolicy && RETURN_TRUSTED_TYPE\n ? trustedTypesPolicy.createHTML(serializedHTML)\n : serializedHTML;\n };\n\n DOMPurify.setConfig = function (cfg = {}) {\n _parseConfig(cfg);\n SET_CONFIG = true;\n };\n\n DOMPurify.clearConfig = function () {\n CONFIG = null;\n SET_CONFIG = false;\n };\n\n DOMPurify.isValidAttribute = function (tag, attr, value) {\n /* Initialize shared config vars if necessary. */\n if (!CONFIG) {\n _parseConfig({});\n }\n\n const lcTag = transformCaseFunc(tag);\n const lcName = transformCaseFunc(attr);\n return _isValidAttribute(lcTag, lcName, value);\n };\n\n DOMPurify.addHook = function (\n entryPoint: keyof HooksMap,\n hookFunction: HookFunction\n ) {\n if (typeof hookFunction !== 'function') {\n return;\n }\n\n arrayPush(hooks[entryPoint], hookFunction);\n };\n\n DOMPurify.removeHook = function (\n entryPoint: keyof HooksMap,\n hookFunction: HookFunction\n ) {\n if (hookFunction !== undefined) {\n const index = arrayLastIndexOf(hooks[entryPoint], hookFunction);\n\n return index === -1\n ? undefined\n : arraySplice(hooks[entryPoint], index, 1)[0];\n }\n\n return arrayPop(hooks[entryPoint]);\n };\n\n DOMPurify.removeHooks = function (entryPoint: keyof HooksMap) {\n hooks[entryPoint] = [];\n };\n\n DOMPurify.removeAllHooks = function () {\n hooks = _createHooksMap();\n };\n\n return DOMPurify;\n}\n\nexport default createDOMPurify();\n\nexport interface DOMPurify {\n /**\n * Creates a DOMPurify instance using the given window-like object. Defaults to `window`.\n */\n (root?: WindowLike): DOMPurify;\n\n /**\n * Version label, exposed for easier checks\n * if DOMPurify is up to date or not\n */\n version: string;\n\n /**\n * Array of elements that DOMPurify removed during sanitation.\n * Empty if nothing was removed.\n */\n removed: Array<RemovedElement | RemovedAttribute>;\n\n /**\n * Expose whether this browser supports running the full DOMPurify.\n */\n isSupported: boolean;\n\n /**\n * Set the configuration once.\n *\n * @param cfg configuration object\n */\n setConfig(cfg?: Config): void;\n\n /**\n * Removes the configuration.\n */\n clearConfig(): void;\n\n /**\n * Provides core sanitation functionality.\n *\n * @param dirty string or DOM node\n * @param cfg object\n * @returns Sanitized TrustedHTML.\n */\n sanitize(\n dirty: string | Node,\n cfg: Config & { RETURN_TRUSTED_TYPE: true }\n ): TrustedHTML;\n\n /**\n * Provides core sanitation functionality.\n *\n * @param dirty DOM node\n * @param cfg object\n * @returns Sanitized DOM node.\n */\n sanitize(dirty: Node, cfg: Config & { IN_PLACE: true }): Node;\n\n /**\n * Provides core sanitation functionality.\n *\n * @param dirty string or DOM node\n * @param cfg object\n * @returns Sanitized DOM node.\n */\n sanitize(dirty: string | Node, cfg: Config & { RETURN_DOM: true }): Node;\n\n /**\n * Provides core sanitation functionality.\n *\n * @param dirty string or DOM node\n * @param cfg object\n * @returns Sanitized document fragment.\n */\n sanitize(\n dirty: string | Node,\n cfg: Config & { RETURN_DOM_FRAGMENT: true }\n ): DocumentFragment;\n\n /**\n * Provides core sanitation functionality.\n *\n * @param dirty string or DOM node\n * @param cfg object\n * @returns Sanitized string.\n */\n sanitize(dirty: string | Node, cfg?: Config): string;\n\n /**\n * Checks if an attribute value is valid.\n * Uses last set config, if any. Otherwise, uses config defaults.\n *\n * @param tag Tag name of containing element.\n * @param attr Attribute name.\n * @param value Attribute value.\n * @returns Returns true if `value` is valid. Otherwise, returns false.\n */\n isValidAttribute(tag: string, attr: string, value: string): boolean;\n\n /**\n * Adds a DOMPurify hook.\n *\n * @param entryPoint entry point for the hook to add\n * @param hookFunction function to execute\n */\n addHook(entryPoint: BasicHookName, hookFunction: NodeHook): void;\n\n /**\n * Adds a DOMPurify hook.\n *\n * @param entryPoint entry point for the hook to add\n * @param hookFunction function to execute\n */\n addHook(entryPoint: ElementHookName, hookFunction: ElementHook): void;\n\n /**\n * Adds a DOMPurify hook.\n *\n * @param entryPoint entry point for the hook to add\n * @param hookFunction function to execute\n */\n addHook(\n entryPoint: DocumentFragmentHookName,\n hookFunction: DocumentFragmentHook\n ): void;\n\n /**\n * Adds a DOMPurify hook.\n *\n * @param entryPoint entry point for the hook to add\n * @param hookFunction function to execute\n */\n addHook(\n entryPoint: 'uponSanitizeElement',\n hookFunction: UponSanitizeElementHook\n ): void;\n\n /**\n * Adds a DOMPurify hook.\n *\n * @param entryPoint entry point for the hook to add\n * @param hookFunction function to execute\n */\n addHook(\n entryPoint: 'uponSanitizeAttribute',\n hookFunction: UponSanitizeAttributeHook\n ): void;\n\n /**\n * Remove a DOMPurify hook at a given entryPoint\n * (pops it from the stack of hooks if hook not specified)\n *\n * @param entryPoint entry point for the hook to remove\n * @param hookFunction optional specific hook to remove\n * @returns removed hook\n */\n removeHook(\n entryPoint: BasicHookName,\n hookFunction?: NodeHook\n ): NodeHook | undefined;\n\n /**\n * Remove a DOMPurify hook at a given entryPoint\n * (pops it from the stack of hooks if hook not specified)\n *\n * @param entryPoint entry point for the hook to remove\n * @param hookFunction optional specific hook to remove\n * @returns removed hook\n */\n removeHook(\n entryPoint: ElementHookName,\n hookFunction?: ElementHook\n ): ElementHook | undefined;\n\n /**\n * Remove a DOMPurify hook at a given entryPoint\n * (pops it from the stack of hooks if hook not specified)\n *\n * @param entryPoint entry point for the hook to remove\n * @param hookFunction optional specific hook to remove\n * @returns removed hook\n */\n removeHook(\n entryPoint: DocumentFragmentHookName,\n hookFunction?: DocumentFragmentHook\n ): DocumentFragmentHook | undefined;\n\n /**\n * Remove a DOMPurify hook at a given entryPoint\n * (pops it from the stack of hooks if hook not specified)\n *\n * @param entryPoint entry point for the hook to remove\n * @param hookFunction optional specific hook to remove\n * @returns removed hook\n */\n removeHook(\n entryPoint: 'uponSanitizeElement',\n hookFunction?: UponSanitizeElementHook\n ): UponSanitizeElementHook | undefined;\n\n /**\n * Remove a DOMPurify hook at a given entryPoint\n * (pops it from the stack of hooks if hook not specified)\n *\n * @param entryPoint entry point for the hook to remove\n * @param hookFunction optional specific hook to remove\n * @returns removed hook\n */\n removeHook(\n entryPoint: 'uponSanitizeAttribute',\n hookFunction?: UponSanitizeAttributeHook\n ): UponSanitizeAttributeHook | undefined;\n\n /**\n * Removes all DOMPurify hooks at a given entryPoint\n *\n * @param entryPoint entry point for the hooks to remove\n */\n removeHooks(entryPoint: HookName): void;\n\n /**\n * Removes all DOMPurify hooks.\n */\n removeAllHooks(): void;\n}\n\n/**\n * An element removed by DOMPurify.\n */\nexport interface RemovedElement {\n /**\n * The element that was removed.\n */\n element: Node;\n}\n\n/**\n * An element removed by DOMPurify.\n */\nexport interface RemovedAttribute {\n /**\n * The attribute that was removed.\n */\n attribute: Attr | null;\n\n /**\n * The element that the attribute was removed.\n */\n from: Node;\n}\n\ntype BasicHookName =\n | 'beforeSanitizeElements'\n | 'afterSanitizeElements'\n | 'uponSanitizeShadowNode';\ntype ElementHookName = 'beforeSanitizeAttributes' | 'afterSanitizeAttributes';\ntype DocumentFragmentHookName =\n | 'beforeSanitizeShadowDOM'\n | 'afterSanitizeShadowDOM';\ntype UponSanitizeElementHookName = 'uponSanitizeElement';\ntype UponSanitizeAttributeHookName = 'uponSanitizeAttribute';\n\ninterface HooksMap {\n beforeSanitizeElements: NodeHook[];\n afterSanitizeElements: NodeHook[];\n beforeSanitizeShadowDOM: DocumentFragmentHook[];\n uponSanitizeShadowNode: NodeHook[];\n afterSanitizeShadowDOM: DocumentFragmentHook[];\n beforeSanitizeAttributes: ElementHook[];\n afterSanitizeAttributes: ElementHook[];\n uponSanitizeElement: UponSanitizeElementHook[];\n uponSanitizeAttribute: UponSanitizeAttributeHook[];\n}\n\ntype ArrayElement<T> = T extends Array<infer U> ? U : never;\n\ntype HookFunction = ArrayElement<HooksMap[keyof HooksMap]>;\n\nexport type HookName =\n | BasicHookName\n | ElementHookName\n | DocumentFragmentHookName\n | UponSanitizeElementHookName\n | UponSanitizeAttributeHookName;\n\nexport type NodeHook = (\n this: DOMPurify,\n currentNode: Node,\n hookEvent: null,\n config: Config\n) => void;\n\nexport type ElementHook = (\n this: DOMPurify,\n currentNode: Element,\n hookEvent: null,\n config: Config\n) => void;\n\nexport type DocumentFragmentHook = (\n this: DOMPurify,\n currentNode: DocumentFragment,\n hookEvent: null,\n config: Config\n) => void;\n\nexport type UponSanitizeElementHook = (\n this: DOMPurify,\n currentNode: Node,\n hookEvent: UponSanitizeElementHookEvent,\n config: Config\n) => void;\n\nexport type UponSanitizeAttributeHook = (\n this: DOMPurify,\n currentNode: Element,\n hookEvent: UponSanitizeAttributeHookEvent,\n config: Config\n) => void;\n\nexport interface UponSanitizeElementHookEvent {\n tagName: string;\n allowedTags: Record<string, boolean>;\n}\n\nexport interface UponSanitizeAttributeHookEvent {\n attrName: string;\n attrValue: string;\n keepAttr: boolean;\n allowedAttributes: Record<string, boolean>;\n forceKeepAttr: boolean | undefined;\n}\n\n/**\n * A `Window`-like object containing the properties and types that DOMPurify requires.\n */\nexport type WindowLike = Pick<\n typeof globalThis,\n | 'DocumentFragment'\n | 'HTMLTemplateElement'\n | 'Node'\n | 'Element'\n | 'NodeFilter'\n | 'NamedNodeMap'\n | 'HTMLFormElement'\n | 'DOMParser'\n> & {\n document?: Document;\n MozNamedAttrMap?: typeof window.NamedNodeMap;\n} & Pick<TrustedTypesWindow, 'trustedTypes'>;\n", "/**\n * @license\n * Copyright 2017 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\n\nimport {Disconnectable, Part} from './lit-html.js';\n\nexport {\n AttributePart,\n BooleanAttributePart,\n ChildPart,\n ElementPart,\n EventPart,\n Part,\n PropertyPart,\n} from './lit-html.js';\n\nexport interface DirectiveClass {\n new (part: PartInfo): Directive;\n}\n\n/**\n * This utility type extracts the signature of a directive class's render()\n * method so we can use it for the type of the generated directive function.\n */\nexport type DirectiveParameters<C extends Directive> = Parameters<C['render']>;\n\n/**\n * A generated directive function doesn't evaluate the directive, but just\n * returns a DirectiveResult object that captures the arguments.\n */\nexport interface DirectiveResult<C extends DirectiveClass = DirectiveClass> {\n /**\n * This property needs to remain unminified.\n * @internal\n */\n ['_$litDirective$']: C;\n /** @internal */\n values: DirectiveParameters<InstanceType<C>>;\n}\n\nexport const PartType = {\n ATTRIBUTE: 1,\n CHILD: 2,\n PROPERTY: 3,\n BOOLEAN_ATTRIBUTE: 4,\n EVENT: 5,\n ELEMENT: 6,\n} as const;\n\nexport type PartType = (typeof PartType)[keyof typeof PartType];\n\nexport interface ChildPartInfo {\n readonly type: typeof PartType.CHILD;\n}\n\nexport interface AttributePartInfo {\n readonly type:\n | typeof PartType.ATTRIBUTE\n | typeof PartType.PROPERTY\n | typeof PartType.BOOLEAN_ATTRIBUTE\n | typeof PartType.EVENT;\n readonly strings?: ReadonlyArray<string>;\n readonly name: string;\n readonly tagName: string;\n}\n\nexport interface ElementPartInfo {\n readonly type: typeof PartType.ELEMENT;\n}\n\n/**\n * Information about the part a directive is bound to.\n *\n * This is useful for checking that a directive is attached to a valid part,\n * such as with directive that can only be used on attribute bindings.\n */\nexport type PartInfo = ChildPartInfo | AttributePartInfo | ElementPartInfo;\n\n/**\n * Creates a user-facing directive function from a Directive class. This\n * function has the same parameters as the directive's render() method.\n */\nexport const directive =\n <C extends DirectiveClass>(c: C) =>\n (...values: DirectiveParameters<InstanceType<C>>): DirectiveResult<C> => ({\n // This property needs to remain unminified.\n ['_$litDirective$']: c,\n values,\n });\n\n/**\n * Base class for creating custom directives. Users should extend this class,\n * implement `render` and/or `update`, and then pass their subclass to\n * `directive`.\n */\nexport abstract class Directive implements Disconnectable {\n //@internal\n __part!: Part;\n //@internal\n __attributeIndex: number | undefined;\n //@internal\n __directive?: Directive;\n\n //@internal\n _$parent!: Disconnectable;\n\n // These will only exist on the AsyncDirective subclass\n //@internal\n _$disconnectableChildren?: Set<Disconnectable>;\n // This property needs to remain unminified.\n //@internal\n ['_$notifyDirectiveConnectionChanged']?(isConnected: boolean): void;\n\n constructor(_partInfo: PartInfo) {}\n\n // See comment in Disconnectable interface for why this is a getter\n get _$isConnected() {\n return this._$parent._$isConnected;\n }\n\n /** @internal */\n _$initialize(\n part: Part,\n parent: Disconnectable,\n attributeIndex: number | undefined\n ) {\n this.__part = part;\n this._$parent = parent;\n this.__attributeIndex = attributeIndex;\n }\n /** @internal */\n _$resolve(part: Part, props: Array<unknown>): unknown {\n return this.update(part, props);\n }\n\n abstract render(...props: Array<unknown>): unknown;\n\n update(_part: Part, props: Array<unknown>): unknown {\n return this.render(...props);\n }\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\n\nimport {nothing, TemplateResult, noChange} from '../lit-html.js';\nimport {directive, Directive, PartInfo, PartType} from '../directive.js';\n\nconst HTML_RESULT = 1;\n\nexport class UnsafeHTMLDirective extends Directive {\n static directiveName = 'unsafeHTML';\n static resultType = HTML_RESULT;\n\n private _value: unknown = nothing;\n private _templateResult?: TemplateResult;\n\n constructor(partInfo: PartInfo) {\n super(partInfo);\n if (partInfo.type !== PartType.CHILD) {\n throw new Error(\n `${\n (this.constructor as typeof UnsafeHTMLDirective).directiveName\n }() can only be used in child bindings`\n );\n }\n }\n\n render(value: string | typeof nothing | typeof noChange | undefined | null) {\n if (value === nothing || value == null) {\n this._templateResult = undefined;\n return (this._value = value);\n }\n if (value === noChange) {\n return value;\n }\n if (typeof value != 'string') {\n throw new Error(\n `${\n (this.constructor as typeof UnsafeHTMLDirective).directiveName\n }() called with a non-string value`\n );\n }\n if (value === this._value) {\n return this._templateResult;\n }\n this._value = value;\n const strings = [value] as unknown as TemplateStringsArray;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (strings as any).raw = strings;\n // WARNING: impersonating a TemplateResult like this is extremely\n // dangerous. Third-party directives should not do this.\n return (this._templateResult = {\n // Cast to a known set of integers that satisfy ResultType so that we\n // don't have to export ResultType and possibly encourage this pattern.\n // This property needs to remain unminified.\n ['_$litType$']: (this.constructor as typeof UnsafeHTMLDirective)\n .resultType as 1 | 2,\n strings,\n values: [],\n });\n }\n}\n\n/**\n * Renders the result as HTML, rather than text.\n *\n * The values `undefined`, `null`, and `nothing`, will all result in no content\n * (empty string) being rendered.\n *\n * Note, this is unsafe to use with any user-provided input that hasn't been\n * sanitized or escaped, as it may lead to cross-site-scripting\n * vulnerabilities.\n */\nexport const unsafeHTML = directive(UnsafeHTMLDirective);\n", "import type { MarkedOptions } from './MarkedOptions.ts';\n\n/**\n * Gets the original marked default options.\n */\nexport function _getDefaults<ParserOutput = string, RendererOutput = string>(): MarkedOptions<ParserOutput, RendererOutput> {\n return {\n async: false,\n breaks: false,\n extensions: null,\n gfm: true,\n hooks: null,\n pedantic: false,\n renderer: null,\n silent: false,\n tokenizer: null,\n walkTokens: null,\n };\n}\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport let _defaults: MarkedOptions<any, any> = _getDefaults();\n\nexport function changeDefaults<ParserOutput = string, RendererOutput = string>(newDefaults: MarkedOptions<ParserOutput, RendererOutput>) {\n _defaults = newDefaults;\n}\n", "const noopTest = { exec: () => null } as unknown as RegExp;\n\nfunction edit(regex: string | RegExp, opt = '') {\n let source = typeof regex === 'string' ? regex : regex.source;\n const obj = {\n replace: (name: string | RegExp, val: string | RegExp) => {\n let valSource = typeof val === 'string' ? val : val.source;\n valSource = valSource.replace(other.caret, '$1');\n source = source.replace(name, valSource);\n return obj;\n },\n getRegex: () => {\n return new RegExp(source, opt);\n },\n };\n return obj;\n}\n\nconst supportsLookbehind = (() => {\ntry {\n // eslint-disable-next-line prefer-regex-literals\n return !!new RegExp('(?<=1)(?<!1)');\n} catch {\n // See browser support here:\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Lookbehind_assertion\n return false;\n}\n})();\n\nexport const other = {\n codeRemoveIndent: /^(?: {1,4}| {0,3}\\t)/gm,\n outputLinkReplace: /\\\\([\\[\\]])/g,\n indentCodeCompensation: /^(\\s+)(?:```)/,\n beginningSpace: /^\\s+/,\n endingHash: /#$/,\n startingSpaceChar: /^ /,\n endingSpaceChar: / $/,\n nonSpaceChar: /[^ ]/,\n newLineCharGlobal: /\\n/g,\n tabCharGlobal: /\\t/g,\n multipleSpaceGlobal: /\\s+/g,\n blankLine: /^[ \\t]*$/,\n doubleBlankLine: /\\n[ \\t]*\\n[ \\t]*$/,\n blockquoteStart: /^ {0,3}>/,\n blockquoteSetextReplace: /\\n {0,3}((?:=+|-+) *)(?=\\n|$)/g,\n blockquoteSetextReplace2: /^ {0,3}>[ \\t]?/gm,\n listReplaceTabs: /^\\t+/,\n listReplaceNesting: /^ {1,4}(?=( {4})*[^ ])/g,\n listIsTask: /^\\[[ xX]\\] +\\S/,\n listReplaceTask: /^\\[[ xX]\\] +/,\n listTaskCheckbox: /\\[[ xX]\\]/,\n anyLine: /\\n.*\\n/,\n hrefBrackets: /^<(.*)>$/,\n tableDelimiter: /[:|]/,\n tableAlignChars: /^\\||\\| *$/g,\n tableRowBlankLine: /\\n[ \\t]*$/,\n tableAlignRight: /^ *-+: *$/,\n tableAlignCenter: /^ *:-+: *$/,\n tableAlignLeft: /^ *:-+ *$/,\n startATag: /^<a /i,\n endATag: /^<\\/a>/i,\n startPreScriptTag: /^<(pre|code|kbd|script)(\\s|>)/i,\n endPreScriptTag: /^<\\/(pre|code|kbd|script)(\\s|>)/i,\n startAngleBracket: /^</,\n endAngleBracket: />$/,\n pedanticHrefTitle: /^([^'\"]*[^\\s])\\s+(['\"])(.*)\\2/,\n unicodeAlphaNumeric: /[\\p{L}\\p{N}]/u,\n escapeTest: /[&<>\"']/,\n escapeReplace: /[&<>\"']/g,\n escapeTestNoEncode: /[<>\"']|&(?!(#\\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\\w+);)/,\n escapeReplaceNoEncode: /[<>\"']|&(?!(#\\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\\w+);)/g,\n unescapeTest: /&(#(?:\\d+)|(?:#x[0-9A-Fa-f]+)|(?:\\w+));?/ig,\n caret: /(^|[^\\[])\\^/g,\n percentDecode: /%25/g,\n findPipe: /\\|/g,\n splitPipe: / \\|/,\n slashPipe: /\\\\\\|/g,\n carriageReturn: /\\r\\n|\\r/g,\n spaceLine: /^ +$/gm,\n notSpaceStart: /^\\S*/,\n endingNewline: /\\n$/,\n listItemRegex: (bull: string) => new RegExp(`^( {0,3}${bull})((?:[\\t ][^\\\\n]*)?(?:\\\\n|$))`),\n nextBulletRegex: (indent: number) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}(?:[*+-]|\\\\d{1,9}[.)])((?:[ \\t][^\\\\n]*)?(?:\\\\n|$))`),\n hrRegex: (indent: number) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\\\* *){3,})(?:\\\\n+|$)`),\n fencesBeginRegex: (indent: number) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}(?:\\`\\`\\`|~~~)`),\n headingBeginRegex: (indent: number) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}#`),\n htmlBeginRegex: (indent: number) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}<(?:[a-z].*>|!--)`, 'i'),\n};\n\n/**\n * Block-Level Grammar\n */\n\nconst newline = /^(?:[ \\t]*(?:\\n|$))+/;\nconst blockCode = /^((?: {4}| {0,3}\\t)[^\\n]+(?:\\n(?:[ \\t]*(?:\\n|$))*)?)+/;\nconst fences = /^ {0,3}(`{3,}(?=[^`\\n]*(?:\\n|$))|~{3,})([^\\n]*)(?:\\n|$)(?:|([\\s\\S]*?)(?:\\n|$))(?: {0,3}\\1[~`]* *(?=\\n|$)|$)/;\nconst hr = /^ {0,3}((?:-[\\t ]*){3,}|(?:_[ \\t]*){3,}|(?:\\*[ \\t]*){3,})(?:\\n+|$)/;\nconst heading = /^ {0,3}(#{1,6})(?=\\s|$)(.*)(?:\\n+|$)/;\nconst bullet = /(?:[*+-]|\\d{1,9}[.)])/;\nconst lheadingCore = /^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\\n(?!\\s*?\\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\\n {0,3}(=+|-+) *(?:\\n+|$)/;\nconst lheading = edit(lheadingCore)\n .replace(/bull/g, bullet) // lists can interrupt\n .replace(/blockCode/g, /(?: {4}| {0,3}\\t)/) // indented code blocks can interrupt\n .replace(/fences/g, / {0,3}(?:`{3,}|~{3,})/) // fenced code blocks can interrupt\n .replace(/blockquote/g, / {0,3}>/) // blockquote can interrupt\n .replace(/heading/g, / {0,3}#{1,6}/) // ATX heading can interrupt\n .replace(/html/g, / {0,3}<[^\\n>]+>\\n/) // block html can interrupt\n .replace(/\\|table/g, '') // table not in commonmark\n .getRegex();\nconst lheadingGfm = edit(lheadingCore)\n .replace(/bull/g, bullet) // lists can interrupt\n .replace(/blockCode/g, /(?: {4}| {0,3}\\t)/) // indented code blocks can interrupt\n .replace(/fences/g, / {0,3}(?:`{3,}|~{3,})/) // fenced code blocks can interrupt\n .replace(/blockquote/g, / {0,3}>/) // blockquote can interrupt\n .replace(/heading/g, / {0,3}#{1,6}/) // ATX heading can interrupt\n .replace(/html/g, / {0,3}<[^\\n>]+>\\n/) // block html can interrupt\n .replace(/table/g, / {0,3}\\|?(?:[:\\- ]*\\|)+[\\:\\- ]*\\n/) // table can interrupt\n .getRegex();\nconst _paragraph = /^([^\\n]+(?:\\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\\n)[^\\n]+)*)/;\nconst blockText = /^[^\\n]+/;\nconst _blockLabel = /(?!\\s*\\])(?:\\\\[\\s\\S]|[^\\[\\]\\\\])+/;\nconst def = edit(/^ {0,3}\\[(label)\\]: *(?:\\n[ \\t]*)?([^<\\s][^\\s]*|<.*?>)(?:(?: +(?:\\n[ \\t]*)?| *\\n[ \\t]*)(title))? *(?:\\n+|$)/)\n .replace('label', _blockLabel)\n .replace('title', /(?:\"(?:\\\\\"?|[^\"\\\\])*\"|'[^'\\n]*(?:\\n[^'\\n]+)*\\n?'|\\([^()]*\\))/)\n .getRegex();\n\nconst list = edit(/^( {0,3}bull)([ \\t][^\\n]+?)?(?:\\n|$)/)\n .replace(/bull/g, bullet)\n .getRegex();\n\nconst _tag = 'address|article|aside|base|basefont|blockquote|body|caption'\n + '|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption'\n + '|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe'\n + '|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option'\n + '|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title'\n + '|tr|track|ul';\nconst _comment = /<!--(?:-?>|[\\s\\S]*?(?:-->|$))/;\nconst html = edit(\n '^ {0,3}(?:' // optional indentation\n+ '<(script|pre|style|textarea)[\\\\s>][\\\\s\\\\S]*?(?:</\\\\1>[^\\\\n]*\\\\n+|$)' // (1)\n+ '|comment[^\\\\n]*(\\\\n+|$)' // (2)\n+ '|<\\\\?[\\\\s\\\\S]*?(?:\\\\?>\\\\n*|$)' // (3)\n+ '|<![A-Z][\\\\s\\\\S]*?(?:>\\\\n*|$)' // (4)\n+ '|<!\\\\[CDATA\\\\[[\\\\s\\\\S]*?(?:\\\\]\\\\]>\\\\n*|$)' // (5)\n+ '|</?(tag)(?: +|\\\\n|/?>)[\\\\s\\\\S]*?(?:(?:\\\\n[ \\t]*)+\\\\n|$)' // (6)\n+ '|<(?!script|pre|style|textarea)([a-z][\\\\w-]*)(?:attribute)*? */?>(?=[ \\\\t]*(?:\\\\n|$))[\\\\s\\\\S]*?(?:(?:\\\\n[ \\t]*)+\\\\n|$)' // (7) open tag\n+ '|</(?!script|pre|style|textarea)[a-z][\\\\w-]*\\\\s*>(?=[ \\\\t]*(?:\\\\n|$))[\\\\s\\\\S]*?(?:(?:\\\\n[ \\t]*)+\\\\n|$)' // (7) closing tag\n+ ')', 'i')\n .replace('comment', _comment)\n .replace('tag', _tag)\n .replace('attribute', / +[a-zA-Z:_][\\w.:-]*(?: *= *\"[^\"\\n]*\"| *= *'[^'\\n]*'| *= *[^\\s\"'=<>`]+)?/)\n .getRegex();\n\nconst paragraph = edit(_paragraph)\n .replace('hr', hr)\n .replace('heading', ' {0,3}#{1,6}(?:\\\\s|$)')\n .replace('|lheading', '') // setext headings don't interrupt commonmark paragraphs\n .replace('|table', '')\n .replace('blockquote', ' {0,3}>')\n .replace('fences', ' {0,3}(?:`{3,}(?=[^`\\\\n]*\\\\n)|~{3,})[^\\\\n]*\\\\n')\n .replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt\n .replace('html', '</?(?:tag)(?: +|\\\\n|/?>)|<(?:script|pre|style|textarea|!--)')\n .replace('tag', _tag) // pars can be interrupted by type (6) html blocks\n .getRegex();\n\nconst blockquote = edit(/^( {0,3}> ?(paragraph|[^\\n]*)(?:\\n|$))+/)\n .replace('paragraph', paragraph)\n .getRegex();\n\n/**\n * Normal Block Grammar\n */\n\nconst blockNormal = {\n blockquote,\n code: blockCode,\n def,\n fences,\n heading,\n hr,\n html,\n lheading,\n list,\n newline,\n paragraph,\n table: noopTest,\n text: blockText,\n};\n\ntype BlockKeys = keyof typeof blockNormal;\n\n/**\n * GFM Block Grammar\n */\n\nconst gfmTable = edit(\n '^ *([^\\\\n ].*)\\\\n' // Header\n+ ' {0,3}((?:\\\\| *)?:?-+:? *(?:\\\\| *:?-+:? *)*(?:\\\\| *)?)' // Align\n+ '(?:\\\\n((?:(?! *\\\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\\\n|$))*)\\\\n*|$)') // Cells\n .replace('hr', hr)\n .replace('heading', ' {0,3}#{1,6}(?:\\\\s|$)')\n .replace('blockquote', ' {0,3}>')\n .replace('code', '(?: {4}| {0,3}\\t)[^\\\\n]')\n .replace('fences', ' {0,3}(?:`{3,}(?=[^`\\\\n]*\\\\n)|~{3,})[^\\\\n]*\\\\n')\n .replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt\n .replace('html', '</?(?:tag)(?: +|\\\\n|/?>)|<(?:script|pre|style|textarea|!--)')\n .replace('tag', _tag) // tables can be interrupted by type (6) html blocks\n .getRegex();\n\nconst blockGfm: Record<BlockKeys, RegExp> = {\n ...blockNormal,\n lheading: lheadingGfm,\n table: gfmTable,\n paragraph: edit(_paragraph)\n .replace('hr', hr)\n .replace('heading', ' {0,3}#{1,6}(?:\\\\s|$)')\n .replace('|lheading', '') // setext headings don't interrupt commonmark paragraphs\n .replace('table', gfmTable) // interrupt paragraphs with table\n .replace('blockquote', ' {0,3}>')\n .replace('fences', ' {0,3}(?:`{3,}(?=[^`\\\\n]*\\\\n)|~{3,})[^\\\\n]*\\\\n')\n .replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt\n .replace('html', '</?(?:tag)(?: +|\\\\n|/?>)|<(?:script|pre|style|textarea|!--)')\n .replace('tag', _tag) // pars can be interrupted by type (6) html blocks\n .getRegex(),\n};\n\n/**\n * Pedantic grammar (original John Gruber's loose markdown specification)\n */\n\nconst blockPedantic: Record<BlockKeys, RegExp> = {\n ...blockNormal,\n html: edit(\n '^ *(?:comment *(?:\\\\n|\\\\s*$)'\n + '|<(tag)[\\\\s\\\\S]+?</\\\\1> *(?:\\\\n{2,}|\\\\s*$)' // closed tag\n + '|<tag(?:\"[^\"]*\"|\\'[^\\']*\\'|\\\\s[^\\'\"/>\\\\s]*)*?/?> *(?:\\\\n{2,}|\\\\s*$))')\n .replace('comment', _comment)\n .replace(/tag/g, '(?!(?:'\n + 'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub'\n + '|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)'\n + '\\\\b)\\\\w+(?!:|[^\\\\w\\\\s@]*@)\\\\b')\n .getRegex(),\n def: /^ *\\[([^\\]]+)\\]: *<?([^\\s>]+)>?(?: +([\"(][^\\n]+[\")]))? *(?:\\n+|$)/,\n heading: /^(#{1,6})(.*)(?:\\n+|$)/,\n fences: noopTest, // fences not supported\n lheading: /^(.+?)\\n {0,3}(=+|-+) *(?:\\n+|$)/,\n paragraph: edit(_paragraph)\n .replace('hr', hr)\n .replace('heading', ' *#{1,6} *[^\\n]')\n .replace('lheading', lheading)\n .replace('|table', '')\n .replace('blockquote', ' {0,3}>')\n .replace('|fences', '')\n .replace('|list', '')\n .replace('|html', '')\n .replace('|tag', '')\n .getRegex(),\n};\n\n/**\n * Inline-Level Grammar\n */\n\nconst escape = /^\\\\([!\"#$%&'()*+,\\-./:;<=>?@\\[\\]\\\\^_`{|}~])/;\nconst inlineCode = /^(`+)([^`]|[^`][\\s\\S]*?[^`])\\1(?!`)/;\nconst br = /^( {2,}|\\\\)\\n(?!\\s*$)/;\nconst inlineText = /^(`+|[^`])(?:(?= {2,}\\n)|[\\s\\S]*?(?:(?=[\\\\<!\\[`*_]|\\b_|$)|[^ ](?= {2,}\\n)))/;\n\n// list of unicode punctuation marks, plus any missing characters from CommonMark spec\nconst _punctuation = /[\\p{P}\\p{S}]/u;\nconst _punctuationOrSpace = /[\\s\\p{P}\\p{S}]/u;\nconst _notPunctuationOrSpace = /[^\\s\\p{P}\\p{S}]/u;\nconst punctuation = edit(/^((?![*_])punctSpace)/, 'u')\n .replace(/punctSpace/g, _punctuationOrSpace).getRegex();\n\n// GFM allows ~ inside strong and em for strikethrough\nconst _punctuationGfmStrongEm = /(?!~)[\\p{P}\\p{S}]/u;\nconst _punctuationOrSpaceGfmStrongEm = /(?!~)[\\s\\p{P}\\p{S}]/u;\nconst _notPunctuationOrSpaceGfmStrongEm = /(?:[^\\s\\p{P}\\p{S}]|~)/u;\n\n// sequences em should skip over [title](link), `code`, <html>\nconst blockSkip = edit(/link|precode-code|html/, 'g')\n .replace('link', /\\[(?:[^\\[\\]`]|(?<a>`+)[^`]+\\k<a>(?!`))*?\\]\\((?:\\\\[\\s\\S]|[^\\\\\\(\\)]|\\((?:\\\\[\\s\\S]|[^\\\\\\(\\)])*\\))*\\)/)\n .replace('precode-', supportsLookbehind ? '(?<!`)()' : '(^^|[^`])')\n .replace('code', /(?<b>`+)[^`]+\\k<b>(?!`)/)\n .replace('html', /<(?! )[^<>]*?>/)\n .getRegex();\n\nconst emStrongLDelimCore = /^(?:\\*+(?:((?!\\*)punct)|[^\\s*]))|^_+(?:((?!_)punct)|([^\\s_]))/;\n\nconst emStrongLDelim = edit(emStrongLDelimCore, 'u')\n .replace(/punct/g, _punctuation)\n .getRegex();\n\nconst emStrongLDelimGfm = edit(emStrongLDelimCore, 'u')\n .replace(/punct/g, _punctuationGfmStrongEm)\n .getRegex();\n\nconst emStrongRDelimAstCore =\n '^[^_*]*?__[^_*]*?\\\\*[^_*]*?(?=__)' // Skip orphan inside strong\n+ '|[^*]+(?=[^*])' // Consume to delim\n+ '|(?!\\\\*)punct(\\\\*+)(?=[\\\\s]|$)' // (1) #*** can only be a Right Delimiter\n+ '|notPunctSpace(\\\\*+)(?!\\\\*)(?=punctSpace|$)' // (2) a***#, a*** can only be a Right Delimiter\n+ '|(?!\\\\*)punctSpace(\\\\*+)(?=notPunctSpace)' // (3) #***a, ***a can only be Left Delimiter\n+ '|[\\\\s](\\\\*+)(?!\\\\*)(?=punct)' // (4) ***# can only be Left Delimiter\n+ '|(?!\\\\*)punct(\\\\*+)(?!\\\\*)(?=punct)' // (5) #***# can be either Left or Right Delimiter\n+ '|notPunctSpace(\\\\*+)(?=notPunctSpace)'; // (6) a***a can be either Left or Right Delimiter\n\nconst emStrongRDelimAst = edit(emStrongRDelimAstCore, 'gu')\n .replace(/notPunctSpace/g, _notPunctuationOrSpace)\n .replace(/punctSpace/g, _punctuationOrSpace)\n .replace(/punct/g, _punctuation)\n .getRegex();\n\nconst emStrongRDelimAstGfm = edit(emStrongRDelimAstCore, 'gu')\n .replace(/notPunctSpace/g, _notPunctuationOrSpaceGfmStrongEm)\n .replace(/punctSpace/g, _punctuationOrSpaceGfmStrongEm)\n .replace(/punct/g, _punctuationGfmStrongEm)\n .getRegex();\n\n// (6) Not allowed for _\nconst emStrongRDelimUnd = edit(\n '^[^_*]*?\\\\*\\\\*[^_*]*?_[^_*]*?(?=\\\\*\\\\*)' // Skip orphan inside strong\n+ '|[^_]+(?=[^_])' // Consume to delim\n+ '|(?!_)punct(_+)(?=[\\\\s]|$)' // (1) #___ can only be a Right Delimiter\n+ '|notPunctSpace(_+)(?!_)(?=punctSpace|$)' // (2) a___#, a___ can only be a Right Delimiter\n+ '|(?!_)punctSpace(_+)(?=notPunctSpace)' // (3) #___a, ___a can only be Left Delimiter\n+ '|[\\\\s](_+)(?!_)(?=punct)' // (4) ___# can only be Left Delimiter\n+ '|(?!_)punct(_+)(?!_)(?=punct)', 'gu') // (5) #___# can be either Left or Right Delimiter\n .replace(/notPunctSpace/g, _notPunctuationOrSpace)\n .replace(/punctSpace/g, _punctuationOrSpace)\n .replace(/punct/g, _punctuation)\n .getRegex();\n\nconst anyPunctuation = edit(/\\\\(punct)/, 'gu')\n .replace(/punct/g, _punctuation)\n .getRegex();\n\nconst autolink = edit(/^<(scheme:[^\\s\\x00-\\x1f<>]*|email)>/)\n .replace('scheme', /[a-zA-Z][a-zA-Z0-9+.-]{1,31}/)\n .replace('email', /[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/)\n .getRegex();\n\nconst _inlineComment = edit(_comment).replace('(?:-->|$)', '-->').getRegex();\nconst tag = edit(\n '^comment'\n + '|^</[a-zA-Z][\\\\w:-]*\\\\s*>' // self-closing tag\n + '|^<[a-zA-Z][\\\\w-]*(?:attribute)*?\\\\s*/?>' // open tag\n + '|^<\\\\?[\\\\s\\\\S]*?\\\\?>' // processing instruction, e.g. <?php ?>\n + '|^<![a-zA-Z]+\\\\s[\\\\s\\\\S]*?>' // declaration, e.g. <!DOCTYPE html>\n + '|^<!\\\\[CDATA\\\\[[\\\\s\\\\S]*?\\\\]\\\\]>') // CDATA section\n .replace('comment', _inlineComment)\n .replace('attribute', /\\s+[a-zA-Z:_][\\w.:-]*(?:\\s*=\\s*\"[^\"]*\"|\\s*=\\s*'[^']*'|\\s*=\\s*[^\\s\"'=<>`]+)?/)\n .getRegex();\n\nconst _inlineLabel = /(?:\\[(?:\\\\[\\s\\S]|[^\\[\\]\\\\])*\\]|\\\\[\\s\\S]|`+[^`]*?`+(?!`)|[^\\[\\]\\\\`])*?/;\n\nconst link = edit(/^!?\\[(label)\\]\\(\\s*(href)(?:(?:[ \\t]*(?:\\n[ \\t]*)?)(title))?\\s*\\)/)\n .replace('label', _inlineLabel)\n .replace('href', /<(?:\\\\.|[^\\n<>\\\\])+>|[^ \\t\\n\\x00-\\x1f]*/)\n .replace('title', /\"(?:\\\\\"?|[^\"\\\\])*\"|'(?:\\\\'?|[^'\\\\])*'|\\((?:\\\\\\)?|[^)\\\\])*\\)/)\n .getRegex();\n\nconst reflink = edit(/^!?\\[(label)\\]\\[(ref)\\]/)\n .replace('label', _inlineLabel)\n .replace('ref', _blockLabel)\n .getRegex();\n\nconst nolink = edit(/^!?\\[(ref)\\](?:\\[\\])?/)\n .replace('ref', _blockLabel)\n .getRegex();\n\nconst reflinkSearch = edit('reflink|nolink(?!\\\\()', 'g')\n .replace('reflink', reflink)\n .replace('nolink', nolink)\n .getRegex();\n\nconst _caseInsensitiveProtocol = /[hH][tT][tT][pP][sS]?|[fF][tT][pP]/;\n\n/**\n * Normal Inline Grammar\n */\n\nconst inlineNormal = {\n _backpedal: noopTest, // only used for GFM url\n anyPunctuation,\n autolink,\n blockSkip,\n br,\n code: inlineCode,\n del: noopTest,\n emStrongLDelim,\n emStrongRDelimAst,\n emStrongRDelimUnd,\n escape,\n link,\n nolink,\n punctuation,\n reflink,\n reflinkSearch,\n tag,\n text: inlineText,\n url: noopTest,\n};\n\ntype InlineKeys = keyof typeof inlineNormal;\n\n/**\n * Pedantic Inline Grammar\n */\n\nconst inlinePedantic: Record<InlineKeys, RegExp> = {\n ...inlineNormal,\n link: edit(/^!?\\[(label)\\]\\((.*?)\\)/)\n .replace('label', _inlineLabel)\n .getRegex(),\n reflink: edit(/^!?\\[(label)\\]\\s*\\[([^\\]]*)\\]/)\n .replace('label', _inlineLabel)\n .getRegex(),\n};\n\n/**\n * GFM Inline Grammar\n */\n\nconst inlineGfm: Record<InlineKeys, RegExp> = {\n ...inlineNormal,\n emStrongRDelimAst: emStrongRDelimAstGfm,\n emStrongLDelim: emStrongLDelimGfm,\n url: edit(/^((?:protocol):\\/\\/|www\\.)(?:[a-zA-Z0-9\\-]+\\.?)+[^\\s<]*|^email/)\n .replace('protocol', _caseInsensitiveProtocol)\n .replace('email', /[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/)\n .getRegex(),\n _backpedal: /(?:[^?!.,:;*_'\"~()&]+|\\([^)]*\\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'\"~)]+(?!$))+/,\n del: /^(~~?)(?=[^\\s~])((?:\\\\[\\s\\S]|[^\\\\])*?(?:\\\\[\\s\\S]|[^\\s~\\\\]))\\1(?=[^~]|$)/,\n text: edit(/^([`~]+|[^`~])(?:(?= {2,}\\n)|(?=[a-zA-Z0-9.!#$%&'*+\\/=?_`{\\|}~-]+@)|[\\s\\S]*?(?:(?=[\\\\<!\\[`*~_]|\\b_|protocol:\\/\\/|www\\.|$)|[^ ](?= {2,}\\n)|[^a-zA-Z0-9.!#$%&'*+\\/=?_`{\\|}~-](?=[a-zA-Z0-9.!#$%&'*+\\/=?_`{\\|}~-]+@)))/)\n .replace('protocol', _caseInsensitiveProtocol)\n .getRegex(),\n};\n\n/**\n * GFM + Line Breaks Inline Grammar\n */\n\nconst inlineBreaks: Record<InlineKeys, RegExp> = {\n ...inlineGfm,\n br: edit(br).replace('{2,}', '*').getRegex(),\n text: edit(inlineGfm.text)\n .replace('\\\\b_', '\\\\b_| {2,}\\\\n')\n .replace(/\\{2,\\}/g, '*')\n .getRegex(),\n};\n\n/**\n * exports\n */\n\nexport const block = {\n normal: blockNormal,\n gfm: blockGfm,\n pedantic: blockPedantic,\n};\n\nexport const inline = {\n normal: inlineNormal,\n gfm: inlineGfm,\n breaks: inlineBreaks,\n pedantic: inlinePedantic,\n};\n\nexport interface Rules {\n other: typeof other\n block: Record<BlockKeys, RegExp>\n inline: Record<InlineKeys, RegExp>\n}\n", "import { other } from './rules.ts';\n\n/**\n * Helpers\n */\nconst escapeReplacements: { [index: string]: string } = {\n '&': '&',\n '<': '<',\n '>': '>',\n '\"': '"',\n \"'\": ''',\n};\nconst getEscapeReplacement = (ch: string) => escapeReplacements[ch];\n\nexport function escape(html: string, encode?: boolean) {\n if (encode) {\n if (other.escapeTest.test(html)) {\n return html.replace(other.escapeReplace, getEscapeReplacement);\n }\n } else {\n if (other.escapeTestNoEncode.test(html)) {\n return html.replace(other.escapeReplaceNoEncode, getEscapeReplacement);\n }\n }\n\n return html;\n}\n\nexport function unescape(html: string) {\n // explicitly match decimal, hex, and named HTML entities\n return html.replace(other.unescapeTest, (_, n) => {\n n = n.toLowerCase();\n if (n === 'colon') return ':';\n if (n.charAt(0) === '#') {\n return n.charAt(1) === 'x'\n ? String.fromCharCode(parseInt(n.substring(2), 16))\n : String.fromCharCode(+n.substring(1));\n }\n return '';\n });\n}\n\nexport function cleanUrl(href: string) {\n try {\n href = encodeURI(href).replace(other.percentDecode, '%');\n } catch {\n return null;\n }\n return href;\n}\n\nexport function splitCells(tableRow: string, count?: number) {\n // ensure that every cell-delimiting pipe has a space\n // before it to distinguish it from an escaped pipe\n const row = tableRow.replace(other.findPipe, (match, offset, str) => {\n let escaped = false;\n let curr = offset;\n while (--curr >= 0 && str[curr] === '\\\\') escaped = !escaped;\n if (escaped) {\n // odd number of slashes means | is escaped\n // so we leave it alone\n return '|';\n } else {\n // add space before unescaped |\n return ' |';\n }\n }),\n cells = row.split(other.splitPipe);\n let i = 0;\n\n // First/last cell in a row cannot be empty if it has no leading/trailing pipe\n if (!cells[0].trim()) {\n cells.shift();\n }\n if (cells.length > 0 && !cells.at(-1)?.trim()) {\n cells.pop();\n }\n\n if (count) {\n if (cells.length > count) {\n cells.splice(count);\n } else {\n while (cells.length < count) cells.push('');\n }\n }\n\n for (; i < cells.length; i++) {\n // leading or trailing whitespace is ignored per the gfm spec\n cells[i] = cells[i].trim().replace(other.slashPipe, '|');\n }\n return cells;\n}\n\n/**\n * Remove trailing 'c's. Equivalent to str.replace(/c*$/, '').\n * /c*$/ is vulnerable to REDOS.\n *\n * @param str\n * @param c\n * @param invert Remove suffix of non-c chars instead. Default falsey.\n */\nexport function rtrim(str: string, c: string, invert?: boolean) {\n const l = str.length;\n if (l === 0) {\n return '';\n }\n\n // Length of suffix matching the invert condition.\n let suffLen = 0;\n\n // Step left until we fail to match the invert condition.\n while (suffLen < l) {\n const currChar = str.charAt(l - suffLen - 1);\n if (currChar === c && !invert) {\n suffLen++;\n } else if (currChar !== c && invert) {\n suffLen++;\n } else {\n break;\n }\n }\n\n return str.slice(0, l - suffLen);\n}\n\nexport function findClosingBracket(str: string, b: string) {\n if (str.indexOf(b[1]) === -1) {\n return -1;\n }\n\n let level = 0;\n for (let i = 0; i < str.length; i++) {\n if (str[i] === '\\\\') {\n i++;\n } else if (str[i] === b[0]) {\n level++;\n } else if (str[i] === b[1]) {\n level--;\n if (level < 0) {\n return i;\n }\n }\n }\n if (level > 0) {\n return -2;\n }\n\n return -1;\n}\n", "import { _defaults } from './defaults.ts';\nimport {\n rtrim,\n splitCells,\n findClosingBracket,\n} from './helpers.ts';\nimport type { Rules } from './rules.ts';\nimport type { _Lexer } from './Lexer.ts';\nimport type { Links, Tokens, Token } from './Tokens.ts';\nimport type { MarkedOptions } from './MarkedOptions.ts';\n\nfunction outputLink(cap: string[], link: Pick<Tokens.Link, 'href' | 'title'>, raw: string, lexer: _Lexer, rules: Rules): Tokens.Link | Tokens.Image {\n const href = link.href;\n const title = link.title || null;\n const text = cap[1].replace(rules.other.outputLinkReplace, '$1');\n\n lexer.state.inLink = true;\n const token: Tokens.Link | Tokens.Image = {\n type: cap[0].charAt(0) === '!' ? 'image' : 'link',\n raw,\n href,\n title,\n text,\n tokens: lexer.inlineTokens(text),\n };\n lexer.state.inLink = false;\n return token;\n}\n\nfunction indentCodeCompensation(raw: string, text: string, rules: Rules) {\n const matchIndentToCode = raw.match(rules.other.indentCodeCompensation);\n\n if (matchIndentToCode === null) {\n return text;\n }\n\n const indentToCode = matchIndentToCode[1];\n\n return text\n .split('\\n')\n .map(node => {\n const matchIndentInNode = node.match(rules.other.beginningSpace);\n if (matchIndentInNode === null) {\n return node;\n }\n\n const [indentInNode] = matchIndentInNode;\n\n if (indentInNode.length >= indentToCode.length) {\n return node.slice(indentToCode.length);\n }\n\n return node;\n })\n .join('\\n');\n}\n\n/**\n * Tokenizer\n */\nexport class _Tokenizer<ParserOutput = string, RendererOutput = string> {\n options: MarkedOptions<ParserOutput, RendererOutput>;\n rules!: Rules; // set by the lexer\n lexer!: _Lexer<ParserOutput, RendererOutput>; // set by the lexer\n\n constructor(options?: MarkedOptions<ParserOutput, RendererOutput>) {\n this.options = options || _defaults;\n }\n\n space(src: string): Tokens.Space | undefined {\n const cap = this.rules.block.newline.exec(src);\n if (cap && cap[0].length > 0) {\n return {\n type: 'space',\n raw: cap[0],\n };\n }\n }\n\n code(src: string): Tokens.Code | undefined {\n const cap = this.rules.block.code.exec(src);\n if (cap) {\n const text = cap[0].replace(this.rules.other.codeRemoveIndent, '');\n return {\n type: 'code',\n raw: cap[0],\n codeBlockStyle: 'indented',\n text: !this.options.pedantic\n ? rtrim(text, '\\n')\n : text,\n };\n }\n }\n\n fences(src: string): Tokens.Code | undefined {\n const cap = this.rules.block.fences.exec(src);\n if (cap) {\n const raw = cap[0];\n const text = indentCodeCompensation(raw, cap[3] || '', this.rules);\n\n return {\n type: 'code',\n raw,\n lang: cap[2] ? cap[2].trim().replace(this.rules.inline.anyPunctuation, '$1') : cap[2],\n text,\n };\n }\n }\n\n heading(src: string): Tokens.Heading | undefined {\n const cap = this.rules.block.heading.exec(src);\n if (cap) {\n let text = cap[2].trim();\n\n // remove trailing #s\n if (this.rules.other.endingHash.test(text)) {\n const trimmed = rtrim(text, '#');\n if (this.options.pedantic) {\n text = trimmed.trim();\n } else if (!trimmed || this.rules.other.endingSpaceChar.test(trimmed)) {\n // CommonMark requires space before trailing #s\n text = trimmed.trim();\n }\n }\n\n return {\n type: 'heading',\n raw: cap[0],\n depth: cap[1].length,\n text,\n tokens: this.lexer.inline(text),\n };\n }\n }\n\n hr(src: string): Tokens.Hr | undefined {\n const cap = this.rules.block.hr.exec(src);\n if (cap) {\n return {\n type: 'hr',\n raw: rtrim(cap[0], '\\n'),\n };\n }\n }\n\n blockquote(src: string): Tokens.Blockquote | undefined {\n const cap = this.rules.block.blockquote.exec(src);\n if (cap) {\n let lines = rtrim(cap[0], '\\n').split('\\n');\n let raw = '';\n let text = '';\n const tokens: Token[] = [];\n\n while (lines.length > 0) {\n let inBlockquote = false;\n const currentLines = [];\n\n let i;\n for (i = 0; i < lines.length; i++) {\n // get lines up to a continuation\n if (this.rules.other.blockquoteStart.test(lines[i])) {\n currentLines.push(lines[i]);\n inBlockquote = true;\n } else if (!inBlockquote) {\n currentLines.push(lines[i]);\n } else {\n break;\n }\n }\n lines = lines.slice(i);\n\n const currentRaw = currentLines.join('\\n');\n const currentText = currentRaw\n // precede setext continuation with 4 spaces so it isn't a setext\n .replace(this.rules.other.blockquoteSetextReplace, '\\n $1')\n .replace(this.rules.other.blockquoteSetextReplace2, '');\n raw = raw ? `${raw}\\n${currentRaw}` : currentRaw;\n text = text ? `${text}\\n${currentText}` : currentText;\n\n // parse blockquote lines as top level tokens\n // merge paragraphs if this is a continuation\n const top = this.lexer.state.top;\n this.lexer.state.top = true;\n this.lexer.blockTokens(currentText, tokens, true);\n this.lexer.state.top = top;\n\n // if there is no continuation then we are done\n if (lines.length === 0) {\n break;\n }\n\n const lastToken = tokens.at(-1);\n\n if (lastToken?.type === 'code') {\n // blockquote continuation cannot be preceded by a code block\n break;\n } else if (lastToken?.type === 'blockquote') {\n // include continuation in nested blockquote\n const oldToken = lastToken as Tokens.Blockquote;\n const newText = oldToken.raw + '\\n' + lines.join('\\n');\n const newToken = this.blockquote(newText)!;\n tokens[tokens.length - 1] = newToken;\n\n raw = raw.substring(0, raw.length - oldToken.raw.length) + newToken.raw;\n text = text.substring(0, text.length - oldToken.text.length) + newToken.text;\n break;\n } else if (lastToken?.type === 'list') {\n // include continuation in nested list\n const oldToken = lastToken as Tokens.List;\n const newText = oldToken.raw + '\\n' + lines.join('\\n');\n const newToken = this.list(newText)!;\n tokens[tokens.length - 1] = newToken;\n\n raw = raw.substring(0, raw.length - lastToken.raw.length) + newToken.raw;\n text = text.substring(0, text.length - oldToken.raw.length) + newToken.raw;\n lines = newText.substring(tokens.at(-1)!.raw.length).split('\\n');\n continue;\n }\n }\n\n return {\n type: 'blockquote',\n raw,\n tokens,\n text,\n };\n }\n }\n\n list(src: string): Tokens.List | undefined {\n let cap = this.rules.block.list.exec(src);\n if (cap) {\n let bull = cap[1].trim();\n const isordered = bull.length > 1;\n\n const list: Tokens.List = {\n type: 'list',\n raw: '',\n ordered: isordered,\n start: isordered ? +bull.slice(0, -1) : '',\n loose: false,\n items: [],\n };\n\n bull = isordered ? `\\\\d{1,9}\\\\${bull.slice(-1)}` : `\\\\${bull}`;\n\n if (this.options.pedantic) {\n bull = isordered ? bull : '[*+-]';\n }\n\n // Get next list item\n const itemRegex = this.rules.other.listItemRegex(bull);\n let endsWithBlankLine = false;\n // Check if current bullet point can start a new List Item\n while (src) {\n let endEarly = false;\n let raw = '';\n let itemContents = '';\n if (!(cap = itemRegex.exec(src))) {\n break;\n }\n\n if (this.rules.block.hr.test(src)) { // End list if bullet was actually HR (possibly move into itemRegex?)\n break;\n }\n\n raw = cap[0];\n src = src.substring(raw.length);\n\n let line = cap[2].split('\\n', 1)[0].replace(this.rules.other.listReplaceTabs, (t: string) => ' '.repeat(3 * t.length));\n let nextLine = src.split('\\n', 1)[0];\n let blankLine = !line.trim();\n\n let indent = 0;\n if (this.options.pedantic) {\n indent = 2;\n itemContents = line.trimStart();\n } else if (blankLine) {\n indent = cap[1].length + 1;\n } else {\n indent = cap[2].search(this.rules.other.nonSpaceChar); // Find first non-space char\n indent = indent > 4 ? 1 : indent; // Treat indented code blocks (> 4 spaces) as having only 1 indent\n itemContents = line.slice(indent);\n indent += cap[1].length;\n }\n\n if (blankLine && this.rules.other.blankLine.test(nextLine)) { // Items begin with at most one blank line\n raw += nextLine + '\\n';\n src = src.substring(nextLine.length + 1);\n endEarly = true;\n }\n\n if (!endEarly) {\n const nextBulletRegex = this.rules.other.nextBulletRegex(indent);\n const hrRegex = this.rules.other.hrRegex(indent);\n const fencesBeginRegex = this.rules.other.fencesBeginRegex(indent);\n const headingBeginRegex = this.rules.other.headingBeginRegex(indent);\n const htmlBeginRegex = this.rules.other.htmlBeginRegex(indent);\n\n // Check if following lines should be included in List Item\n while (src) {\n const rawLine = src.split('\\n', 1)[0];\n let nextLineWithoutTabs;\n nextLine = rawLine;\n\n // Re-align to follow commonmark nesting rules\n if (this.options.pedantic) {\n nextLine = nextLine.replace(this.rules.other.listReplaceNesting, ' ');\n nextLineWithoutTabs = nextLine;\n } else {\n nextLineWithoutTabs = nextLine.replace(this.rules.other.tabCharGlobal, ' ');\n }\n\n // End list item if found code fences\n if (fencesBeginRegex.test(nextLine)) {\n break;\n }\n\n // End list item if found start of new heading\n if (headingBeginRegex.test(nextLine)) {\n break;\n }\n\n // End list item if found start of html block\n if (htmlBeginRegex.test(nextLine)) {\n break;\n }\n\n // End list item if found start of new bullet\n if (nextBulletRegex.test(nextLine)) {\n break;\n }\n\n // Horizontal rule found\n if (hrRegex.test(nextLine)) {\n break;\n }\n\n if (nextLineWithoutTabs.search(this.rules.other.nonSpaceChar) >= indent || !nextLine.trim()) { // Dedent if possible\n itemContents += '\\n' + nextLineWithoutTabs.slice(indent);\n } else {\n // not enough indentation\n if (blankLine) {\n break;\n }\n\n // paragraph continuation unless last line was a different block level element\n if (line.replace(this.rules.other.tabCharGlobal, ' ').search(this.rules.other.nonSpaceChar) >= 4) { // indented code block\n break;\n }\n if (fencesBeginRegex.test(line)) {\n break;\n }\n if (headingBeginRegex.test(line)) {\n break;\n }\n if (hrRegex.test(line)) {\n break;\n }\n\n itemContents += '\\n' + nextLine;\n }\n\n if (!blankLine && !nextLine.trim()) { // Check if current line is blank\n blankLine = true;\n }\n\n raw += rawLine + '\\n';\n src = src.substring(rawLine.length + 1);\n line = nextLineWithoutTabs.slice(indent);\n }\n }\n\n if (!list.loose) {\n // If the previous item ended with a blank line, the list is loose\n if (endsWithBlankLine) {\n list.loose = true;\n } else if (this.rules.other.doubleBlankLine.test(raw)) {\n endsWithBlankLine = true;\n }\n }\n\n list.items.push({\n type: 'list_item',\n raw,\n task: !!this.options.gfm && this.rules.other.listIsTask.test(itemContents),\n loose: false,\n text: itemContents,\n tokens: [],\n });\n\n list.raw += raw;\n }\n\n // Do not consume newlines at end of final item. Alternatively, make itemRegex *start* with any newlines to simplify/speed up endsWithBlankLine logic\n const lastItem = list.items.at(-1);\n if (lastItem) {\n lastItem.raw = lastItem.raw.trimEnd();\n lastItem.text = lastItem.text.trimEnd();\n } else {\n // not a list since there were no items\n return;\n }\n list.raw = list.raw.trimEnd();\n\n // Item child tokens handled here at end because we needed to have the final item to trim it first\n for (const item of list.items) {\n this.lexer.state.top = false;\n item.tokens = this.lexer.blockTokens(item.text, []);\n if (item.task) {\n // Remove checkbox markdown from item tokens\n item.text = item.text.replace(this.rules.other.listReplaceTask, '');\n if (item.tokens[0]?.type === 'text' || item.tokens[0]?.type === 'paragraph') {\n item.tokens[0].raw = item.tokens[0].raw.replace(this.rules.other.listReplaceTask, '');\n item.tokens[0].text = item.tokens[0].text.replace(this.rules.other.listReplaceTask, '');\n for (let i = this.lexer.inlineQueue.length - 1; i >= 0; i--) {\n if (this.rules.other.listIsTask.test(this.lexer.inlineQueue[i].src)) {\n this.lexer.inlineQueue[i].src = this.lexer.inlineQueue[i].src.replace(this.rules.other.listReplaceTask, '');\n break;\n }\n }\n }\n\n const taskRaw = this.rules.other.listTaskCheckbox.exec(item.raw);\n if (taskRaw) {\n const checkboxToken: Tokens.Checkbox = {\n type: 'checkbox',\n raw: taskRaw[0] + ' ',\n checked: taskRaw[0] !== '[ ]',\n };\n item.checked = checkboxToken.checked;\n if (list.loose) {\n if (item.tokens[0] && ['paragraph', 'text'].includes(item.tokens[0].type) && 'tokens' in item.tokens[0] && item.tokens[0].tokens) {\n item.tokens[0].raw = checkboxToken.raw + item.tokens[0].raw;\n item.tokens[0].text = checkboxToken.raw + item.tokens[0].text;\n item.tokens[0].tokens.unshift(checkboxToken);\n } else {\n item.tokens.unshift({\n type: 'paragraph',\n raw: checkboxToken.raw,\n text: checkboxToken.raw,\n tokens: [checkboxToken],\n });\n }\n } else {\n item.tokens.unshift(checkboxToken);\n }\n }\n }\n\n if (!list.loose) {\n // Check if list should be loose\n const spacers = item.tokens.filter(t => t.type === 'space');\n const hasMultipleLineBreaks = spacers.length > 0 && spacers.some(t => this.rules.other.anyLine.test(t.raw));\n\n list.loose = hasMultipleLineBreaks;\n }\n }\n\n // Set all items to loose if list is loose\n if (list.loose) {\n for (const item of list.items) {\n item.loose = true;\n for (const token of item.tokens) {\n if (token.type === 'text') {\n token.type = 'paragraph';\n }\n }\n }\n }\n\n return list;\n }\n }\n\n html(src: string): Tokens.HTML | undefined {\n const cap = this.rules.block.html.exec(src);\n if (cap) {\n const token: Tokens.HTML = {\n type: 'html',\n block: true,\n raw: cap[0],\n pre: cap[1] === 'pre' || cap[1] === 'script' || cap[1] === 'style',\n text: cap[0],\n };\n return token;\n }\n }\n\n def(src: string): Tokens.Def | undefined {\n const cap = this.rules.block.def.exec(src);\n if (cap) {\n const tag = cap[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal, ' ');\n const href = cap[2] ? cap[2].replace(this.rules.other.hrefBrackets, '$1').replace(this.rules.inline.anyPunctuation, '$1') : '';\n const title = cap[3] ? cap[3].substring(1, cap[3].length - 1).replace(this.rules.inline.anyPunctuation, '$1') : cap[3];\n return {\n type: 'def',\n tag,\n raw: cap[0],\n href,\n title,\n };\n }\n }\n\n table(src: string): Tokens.Table | undefined {\n const cap = this.rules.block.table.exec(src);\n if (!cap) {\n return;\n }\n\n if (!this.rules.other.tableDelimiter.test(cap[2])) {\n // delimiter row must have a pipe (|) or colon (:) otherwise it is a setext heading\n return;\n }\n\n const headers = splitCells(cap[1]);\n const aligns = cap[2].replace(this.rules.other.tableAlignChars, '').split('|');\n const rows = cap[3]?.trim() ? cap[3].replace(this.rules.other.tableRowBlankLine, '').split('\\n') : [];\n\n const item: Tokens.Table = {\n type: 'table',\n raw: cap[0],\n header: [],\n align: [],\n rows: [],\n };\n\n if (headers.length !== aligns.length) {\n // header and align columns must be equal, rows can be different.\n return;\n }\n\n for (const align of aligns) {\n if (this.rules.other.tableAlignRight.test(align)) {\n item.align.push('right');\n } else if (this.rules.other.tableAlignCenter.test(align)) {\n item.align.push('center');\n } else if (this.rules.other.tableAlignLeft.test(align)) {\n item.align.push('left');\n } else {\n item.align.push(null);\n }\n }\n\n for (let i = 0; i < headers.length; i++) {\n item.header.push({\n text: headers[i],\n tokens: this.lexer.inline(headers[i]),\n header: true,\n align: item.align[i],\n });\n }\n\n for (const row of rows) {\n item.rows.push(splitCells(row, item.header.length).map((cell, i) => {\n return {\n text: cell,\n tokens: this.lexer.inline(cell),\n header: false,\n align: item.align[i],\n };\n }));\n }\n\n return item;\n }\n\n lheading(src: string): Tokens.Heading | undefined {\n const cap = this.rules.block.lheading.exec(src);\n if (cap) {\n return {\n type: 'heading',\n raw: cap[0],\n depth: cap[2].charAt(0) === '=' ? 1 : 2,\n text: cap[1],\n tokens: this.lexer.inline(cap[1]),\n };\n }\n }\n\n paragraph(src: string): Tokens.Paragraph | undefined {\n const cap = this.rules.block.paragraph.exec(src);\n if (cap) {\n const text = cap[1].charAt(cap[1].length - 1) === '\\n'\n ? cap[1].slice(0, -1)\n : cap[1];\n return {\n type: 'paragraph',\n raw: cap[0],\n text,\n tokens: this.lexer.inline(text),\n };\n }\n }\n\n text(src: string): Tokens.Text | undefined {\n const cap = this.rules.block.text.exec(src);\n if (cap) {\n return {\n type: 'text',\n raw: cap[0],\n text: cap[0],\n tokens: this.lexer.inline(cap[0]),\n };\n }\n }\n\n escape(src: string): Tokens.Escape | undefined {\n const cap = this.rules.inline.escape.exec(src);\n if (cap) {\n return {\n type: 'escape',\n raw: cap[0],\n text: cap[1],\n };\n }\n }\n\n tag(src: string): Tokens.Tag | undefined {\n const cap = this.rules.inline.tag.exec(src);\n if (cap) {\n if (!this.lexer.state.inLink && this.rules.other.startATag.test(cap[0])) {\n this.lexer.state.inLink = true;\n } else if (this.lexer.state.inLink && this.rules.other.endATag.test(cap[0])) {\n this.lexer.state.inLink = false;\n }\n if (!this.lexer.state.inRawBlock && this.rules.other.startPreScriptTag.test(cap[0])) {\n this.lexer.state.inRawBlock = true;\n } else if (this.lexer.state.inRawBlock && this.rules.other.endPreScriptTag.test(cap[0])) {\n this.lexer.state.inRawBlock = false;\n }\n\n return {\n type: 'html',\n raw: cap[0],\n inLink: this.lexer.state.inLink,\n inRawBlock: this.lexer.state.inRawBlock,\n block: false,\n text: cap[0],\n };\n }\n }\n\n link(src: string): Tokens.Link | Tokens.Image | undefined {\n const cap = this.rules.inline.link.exec(src);\n if (cap) {\n const trimmedUrl = cap[2].trim();\n if (!this.options.pedantic && this.rules.other.startAngleBracket.test(trimmedUrl)) {\n // commonmark requires matching angle brackets\n if (!(this.rules.other.endAngleBracket.test(trimmedUrl))) {\n return;\n }\n\n // ending angle bracket cannot be escaped\n const rtrimSlash = rtrim(trimmedUrl.slice(0, -1), '\\\\');\n if ((trimmedUrl.length - rtrimSlash.length) % 2 === 0) {\n return;\n }\n } else {\n // find closing parenthesis\n const lastParenIndex = findClosingBracket(cap[2], '()');\n if (lastParenIndex === -2) {\n // more open parens than closed\n return;\n }\n\n if (lastParenIndex > -1) {\n const start = cap[0].indexOf('!') === 0 ? 5 : 4;\n const linkLen = start + cap[1].length + lastParenIndex;\n cap[2] = cap[2].substring(0, lastParenIndex);\n cap[0] = cap[0].substring(0, linkLen).trim();\n cap[3] = '';\n }\n }\n let href = cap[2];\n let title = '';\n if (this.options.pedantic) {\n // split pedantic href and title\n const link = this.rules.other.pedanticHrefTitle.exec(href);\n\n if (link) {\n href = link[1];\n title = link[3];\n }\n } else {\n title = cap[3] ? cap[3].slice(1, -1) : '';\n }\n\n href = href.trim();\n if (this.rules.other.startAngleBracket.test(href)) {\n if (this.options.pedantic && !(this.rules.other.endAngleBracket.test(trimmedUrl))) {\n // pedantic allows starting angle bracket without ending angle bracket\n href = href.slice(1);\n } else {\n href = href.slice(1, -1);\n }\n }\n return outputLink(cap, {\n href: href ? href.replace(this.rules.inline.anyPunctuation, '$1') : href,\n title: title ? title.replace(this.rules.inline.anyPunctuation, '$1') : title,\n }, cap[0], this.lexer, this.rules);\n }\n }\n\n reflink(src: string, links: Links): Tokens.Link | Tokens.Image | Tokens.Text | undefined {\n let cap;\n if ((cap = this.rules.inline.reflink.exec(src))\n || (cap = this.rules.inline.nolink.exec(src))) {\n const linkString = (cap[2] || cap[1]).replace(this.rules.other.multipleSpaceGlobal, ' ');\n const link = links[linkString.toLowerCase()];\n if (!link) {\n const text = cap[0].charAt(0);\n return {\n type: 'text',\n raw: text,\n text,\n };\n }\n return outputLink(cap, link, cap[0], this.lexer, this.rules);\n }\n }\n\n emStrong(src: string, maskedSrc: string, prevChar = ''): Tokens.Em | Tokens.Strong | undefined {\n let match = this.rules.inline.emStrongLDelim.exec(src);\n if (!match) return;\n\n // _ can't be between two alphanumerics. \\p{L}\\p{N} includes non-english alphabet/numbers as well\n if (match[3] && prevChar.match(this.rules.other.unicodeAlphaNumeric)) return;\n\n const nextChar = match[1] || match[2] || '';\n\n if (!nextChar || !prevChar || this.rules.inline.punctuation.exec(prevChar)) {\n // unicode Regex counts emoji as 1 char; spread into array for proper count (used multiple times below)\n const lLength = [...match[0]].length - 1;\n let rDelim, rLength, delimTotal = lLength, midDelimTotal = 0;\n\n const endReg = match[0][0] === '*' ? this.rules.inline.emStrongRDelimAst : this.rules.inline.emStrongRDelimUnd;\n endReg.lastIndex = 0;\n\n // Clip maskedSrc to same section of string as src (move to lexer?)\n maskedSrc = maskedSrc.slice(-1 * src.length + lLength);\n\n while ((match = endReg.exec(maskedSrc)) != null) {\n rDelim = match[1] || match[2] || match[3] || match[4] || match[5] || match[6];\n\n if (!rDelim) continue; // skip single * in __abc*abc__\n\n rLength = [...rDelim].length;\n\n if (match[3] || match[4]) { // found another Left Delim\n delimTotal += rLength;\n continue;\n } else if (match[5] || match[6]) { // either Left or Right Delim\n if (lLength % 3 && !((lLength + rLength) % 3)) {\n midDelimTotal += rLength;\n continue; // CommonMark Emphasis Rules 9-10\n }\n }\n\n delimTotal -= rLength;\n\n if (delimTotal > 0) continue; // Haven't found enough closing delimiters\n\n // Remove extra characters. *a*** -> *a*\n rLength = Math.min(rLength, rLength + delimTotal + midDelimTotal);\n // char length can be >1 for unicode characters;\n const lastCharLength = [...match[0]][0].length;\n const raw = src.slice(0, lLength + match.index + lastCharLength + rLength);\n\n // Create `em` if smallest delimiter has odd char count. *a***\n if (Math.min(lLength, rLength) % 2) {\n const text = raw.slice(1, -1);\n return {\n type: 'em',\n raw,\n text,\n tokens: this.lexer.inlineTokens(text),\n };\n }\n\n // Create 'strong' if smallest delimiter has even char count. **a***\n const text = raw.slice(2, -2);\n return {\n type: 'strong',\n raw,\n text,\n tokens: this.lexer.inlineTokens(text),\n };\n }\n }\n }\n\n codespan(src: string): Tokens.Codespan | undefined {\n const cap = this.rules.inline.code.exec(src);\n if (cap) {\n let text = cap[2].replace(this.rules.other.newLineCharGlobal, ' ');\n const hasNonSpaceChars = this.rules.other.nonSpaceChar.test(text);\n const hasSpaceCharsOnBothEnds = this.rules.other.startingSpaceChar.test(text) && this.rules.other.endingSpaceChar.test(text);\n if (hasNonSpaceChars && hasSpaceCharsOnBothEnds) {\n text = text.substring(1, text.length - 1);\n }\n return {\n type: 'codespan',\n raw: cap[0],\n text,\n };\n }\n }\n\n br(src: string): Tokens.Br | undefined {\n const cap = this.rules.inline.br.exec(src);\n if (cap) {\n return {\n type: 'br',\n raw: cap[0],\n };\n }\n }\n\n del(src: string): Tokens.Del | undefined {\n const cap = this.rules.inline.del.exec(src);\n if (cap) {\n return {\n type: 'del',\n raw: cap[0],\n text: cap[2],\n tokens: this.lexer.inlineTokens(cap[2]),\n };\n }\n }\n\n autolink(src: string): Tokens.Link | undefined {\n const cap = this.rules.inline.autolink.exec(src);\n if (cap) {\n let text, href;\n if (cap[2] === '@') {\n text = cap[1];\n href = 'mailto:' + text;\n } else {\n text = cap[1];\n href = text;\n }\n\n return {\n type: 'link',\n raw: cap[0],\n text,\n href,\n tokens: [\n {\n type: 'text',\n raw: text,\n text,\n },\n ],\n };\n }\n }\n\n url(src: string): Tokens.Link | undefined {\n let cap;\n if (cap = this.rules.inline.url.exec(src)) {\n let text, href;\n if (cap[2] === '@') {\n text = cap[0];\n href = 'mailto:' + text;\n } else {\n // do extended autolink path validation\n let prevCapZero;\n do {\n prevCapZero = cap[0];\n cap[0] = this.rules.inline._backpedal.exec(cap[0])?.[0] ?? '';\n } while (prevCapZero !== cap[0]);\n text = cap[0];\n if (cap[1] === 'www.') {\n href = 'http://' + cap[0];\n } else {\n href = cap[0];\n }\n }\n return {\n type: 'link',\n raw: cap[0],\n text,\n href,\n tokens: [\n {\n type: 'text',\n raw: text,\n text,\n },\n ],\n };\n }\n }\n\n inlineText(src: string): Tokens.Text | undefined {\n const cap = this.rules.inline.text.exec(src);\n if (cap) {\n const escaped = this.lexer.state.inRawBlock;\n return {\n type: 'text',\n raw: cap[0],\n text: cap[0],\n escaped,\n };\n }\n }\n}\n", "import { _Tokenizer } from './Tokenizer.ts';\nimport { _defaults } from './defaults.ts';\nimport { other, block, inline } from './rules.ts';\nimport type { Token, TokensList, Tokens } from './Tokens.ts';\nimport type { MarkedOptions } from './MarkedOptions.ts';\n\n/**\n * Block Lexer\n */\nexport class _Lexer<ParserOutput = string, RendererOutput = string> {\n tokens: TokensList;\n options: MarkedOptions<ParserOutput, RendererOutput>;\n state: {\n inLink: boolean;\n inRawBlock: boolean;\n top: boolean;\n };\n\n public inlineQueue: { src: string, tokens: Token[] }[];\n\n private tokenizer: _Tokenizer<ParserOutput, RendererOutput>;\n\n constructor(options?: MarkedOptions<ParserOutput, RendererOutput>) {\n // TokenList cannot be created in one go\n this.tokens = [] as unknown as TokensList;\n this.tokens.links = Object.create(null);\n this.options = options || _defaults;\n this.options.tokenizer = this.options.tokenizer || new _Tokenizer<ParserOutput, RendererOutput>();\n this.tokenizer = this.options.tokenizer;\n this.tokenizer.options = this.options;\n this.tokenizer.lexer = this;\n this.inlineQueue = [];\n this.state = {\n inLink: false,\n inRawBlock: false,\n top: true,\n };\n\n const rules = {\n other,\n block: block.normal,\n inline: inline.normal,\n };\n\n if (this.options.pedantic) {\n rules.block = block.pedantic;\n rules.inline = inline.pedantic;\n } else if (this.options.gfm) {\n rules.block = block.gfm;\n if (this.options.breaks) {\n rules.inline = inline.breaks;\n } else {\n rules.inline = inline.gfm;\n }\n }\n this.tokenizer.rules = rules;\n }\n\n /**\n * Expose Rules\n */\n static get rules() {\n return {\n block,\n inline,\n };\n }\n\n /**\n * Static Lex Method\n */\n static lex<ParserOutput = string, RendererOutput = string>(src: string, options?: MarkedOptions<ParserOutput, RendererOutput>) {\n const lexer = new _Lexer<ParserOutput, RendererOutput>(options);\n return lexer.lex(src);\n }\n\n /**\n * Static Lex Inline Method\n */\n static lexInline<ParserOutput = string, RendererOutput = string>(src: string, options?: MarkedOptions<ParserOutput, RendererOutput>) {\n const lexer = new _Lexer<ParserOutput, RendererOutput>(options);\n return lexer.inlineTokens(src);\n }\n\n /**\n * Preprocessing\n */\n lex(src: string) {\n src = src.replace(other.carriageReturn, '\\n');\n\n this.blockTokens(src, this.tokens);\n\n for (let i = 0; i < this.inlineQueue.length; i++) {\n const next = this.inlineQueue[i];\n this.inlineTokens(next.src, next.tokens);\n }\n this.inlineQueue = [];\n\n return this.tokens;\n }\n\n /**\n * Lexing\n */\n blockTokens(src: string, tokens?: Token[], lastParagraphClipped?: boolean): Token[];\n blockTokens(src: string, tokens?: TokensList, lastParagraphClipped?: boolean): TokensList;\n blockTokens(src: string, tokens: Token[] = [], lastParagraphClipped = false) {\n if (this.options.pedantic) {\n src = src.replace(other.tabCharGlobal, ' ').replace(other.spaceLine, '');\n }\n\n while (src) {\n let token: Tokens.Generic | undefined;\n\n if (this.options.extensions?.block?.some((extTokenizer) => {\n if (token = extTokenizer.call({ lexer: this }, src, tokens)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n return true;\n }\n return false;\n })) {\n continue;\n }\n\n // newline\n if (token = this.tokenizer.space(src)) {\n src = src.substring(token.raw.length);\n const lastToken = tokens.at(-1);\n if (token.raw.length === 1 && lastToken !== undefined) {\n // if there's a single \\n as a spacer, it's terminating the last line,\n // so move it there so that we don't get unnecessary paragraph tags\n lastToken.raw += '\\n';\n } else {\n tokens.push(token);\n }\n continue;\n }\n\n // code\n if (token = this.tokenizer.code(src)) {\n src = src.substring(token.raw.length);\n const lastToken = tokens.at(-1);\n // An indented code block cannot interrupt a paragraph.\n if (lastToken?.type === 'paragraph' || lastToken?.type === 'text') {\n lastToken.raw += (lastToken.raw.endsWith('\\n') ? '' : '\\n') + token.raw;\n lastToken.text += '\\n' + token.text;\n this.inlineQueue.at(-1)!.src = lastToken.text;\n } else {\n tokens.push(token);\n }\n continue;\n }\n\n // fences\n if (token = this.tokenizer.fences(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // heading\n if (token = this.tokenizer.heading(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // hr\n if (token = this.tokenizer.hr(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // blockquote\n if (token = this.tokenizer.blockquote(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // list\n if (token = this.tokenizer.list(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // html\n if (token = this.tokenizer.html(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // def\n if (token = this.tokenizer.def(src)) {\n src = src.substring(token.raw.length);\n const lastToken = tokens.at(-1);\n if (lastToken?.type === 'paragraph' || lastToken?.type === 'text') {\n lastToken.raw += (lastToken.raw.endsWith('\\n') ? '' : '\\n') + token.raw;\n lastToken.text += '\\n' + token.raw;\n this.inlineQueue.at(-1)!.src = lastToken.text;\n } else if (!this.tokens.links[token.tag]) {\n this.tokens.links[token.tag] = {\n href: token.href,\n title: token.title,\n };\n tokens.push(token);\n }\n continue;\n }\n\n // table (gfm)\n if (token = this.tokenizer.table(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // lheading\n if (token = this.tokenizer.lheading(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // top-level paragraph\n // prevent paragraph consuming extensions by clipping 'src' to extension start\n let cutSrc = src;\n if (this.options.extensions?.startBlock) {\n let startIndex = Infinity;\n const tempSrc = src.slice(1);\n let tempStart;\n this.options.extensions.startBlock.forEach((getStartIndex) => {\n tempStart = getStartIndex.call({ lexer: this }, tempSrc);\n if (typeof tempStart === 'number' && tempStart >= 0) {\n startIndex = Math.min(startIndex, tempStart);\n }\n });\n if (startIndex < Infinity && startIndex >= 0) {\n cutSrc = src.substring(0, startIndex + 1);\n }\n }\n if (this.state.top && (token = this.tokenizer.paragraph(cutSrc))) {\n const lastToken = tokens.at(-1);\n if (lastParagraphClipped && lastToken?.type === 'paragraph') {\n lastToken.raw += (lastToken.raw.endsWith('\\n') ? '' : '\\n') + token.raw;\n lastToken.text += '\\n' + token.text;\n this.inlineQueue.pop();\n this.inlineQueue.at(-1)!.src = lastToken.text;\n } else {\n tokens.push(token);\n }\n lastParagraphClipped = cutSrc.length !== src.length;\n src = src.substring(token.raw.length);\n continue;\n }\n\n // text\n if (token = this.tokenizer.text(src)) {\n src = src.substring(token.raw.length);\n const lastToken = tokens.at(-1);\n if (lastToken?.type === 'text') {\n lastToken.raw += (lastToken.raw.endsWith('\\n') ? '' : '\\n') + token.raw;\n lastToken.text += '\\n' + token.text;\n this.inlineQueue.pop();\n this.inlineQueue.at(-1)!.src = lastToken.text;\n } else {\n tokens.push(token);\n }\n continue;\n }\n\n if (src) {\n const errMsg = 'Infinite loop on byte: ' + src.charCodeAt(0);\n if (this.options.silent) {\n console.error(errMsg);\n break;\n } else {\n throw new Error(errMsg);\n }\n }\n }\n\n this.state.top = true;\n return tokens;\n }\n\n inline(src: string, tokens: Token[] = []) {\n this.inlineQueue.push({ src, tokens });\n return tokens;\n }\n\n /**\n * Lexing/Compiling\n */\n inlineTokens(src: string, tokens: Token[] = []): Token[] {\n // String with links masked to avoid interference with em and strong\n let maskedSrc = src;\n let match: RegExpExecArray | null = null;\n\n // Mask out reflinks\n if (this.tokens.links) {\n const links = Object.keys(this.tokens.links);\n if (links.length > 0) {\n while ((match = this.tokenizer.rules.inline.reflinkSearch.exec(maskedSrc)) != null) {\n if (links.includes(match[0].slice(match[0].lastIndexOf('[') + 1, -1))) {\n maskedSrc = maskedSrc.slice(0, match.index)\n + '[' + 'a'.repeat(match[0].length - 2) + ']'\n + maskedSrc.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex);\n }\n }\n }\n }\n\n // Mask out escaped characters\n while ((match = this.tokenizer.rules.inline.anyPunctuation.exec(maskedSrc)) != null) {\n maskedSrc = maskedSrc.slice(0, match.index) + '++' + maskedSrc.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);\n }\n\n // Mask out other blocks\n let offset;\n while ((match = this.tokenizer.rules.inline.blockSkip.exec(maskedSrc)) != null) {\n offset = match[2] ? match[2].length : 0;\n maskedSrc = maskedSrc.slice(0, match.index + offset) + '[' + 'a'.repeat(match[0].length - offset - 2) + ']' + maskedSrc.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);\n }\n\n // Mask out blocks from extensions\n maskedSrc = this.options.hooks?.emStrongMask?.call({ lexer: this }, maskedSrc) ?? maskedSrc;\n\n let keepPrevChar = false;\n let prevChar = '';\n while (src) {\n if (!keepPrevChar) {\n prevChar = '';\n }\n keepPrevChar = false;\n\n let token: Tokens.Generic | undefined;\n\n // extensions\n if (this.options.extensions?.inline?.some((extTokenizer) => {\n if (token = extTokenizer.call({ lexer: this }, src, tokens)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n return true;\n }\n return false;\n })) {\n continue;\n }\n\n // escape\n if (token = this.tokenizer.escape(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // tag\n if (token = this.tokenizer.tag(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // link\n if (token = this.tokenizer.link(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // reflink, nolink\n if (token = this.tokenizer.reflink(src, this.tokens.links)) {\n src = src.substring(token.raw.length);\n const lastToken = tokens.at(-1);\n if (token.type === 'text' && lastToken?.type === 'text') {\n lastToken.raw += token.raw;\n lastToken.text += token.text;\n } else {\n tokens.push(token);\n }\n continue;\n }\n\n // em & strong\n if (token = this.tokenizer.emStrong(src, maskedSrc, prevChar)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // code\n if (token = this.tokenizer.codespan(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // br\n if (token = this.tokenizer.br(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // del (gfm)\n if (token = this.tokenizer.del(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // autolink\n if (token = this.tokenizer.autolink(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // url (gfm)\n if (!this.state.inLink && (token = this.tokenizer.url(src))) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // text\n // prevent inlineText consuming extensions by clipping 'src' to extension start\n let cutSrc = src;\n if (this.options.extensions?.startInline) {\n let startIndex = Infinity;\n const tempSrc = src.slice(1);\n let tempStart;\n this.options.extensions.startInline.forEach((getStartIndex) => {\n tempStart = getStartIndex.call({ lexer: this }, tempSrc);\n if (typeof tempStart === 'number' && tempStart >= 0) {\n startIndex = Math.min(startIndex, tempStart);\n }\n });\n if (startIndex < Infinity && startIndex >= 0) {\n cutSrc = src.substring(0, startIndex + 1);\n }\n }\n if (token = this.tokenizer.inlineText(cutSrc)) {\n src = src.substring(token.raw.length);\n if (token.raw.slice(-1) !== '_') { // Track prevChar before string of ____ started\n prevChar = token.raw.slice(-1);\n }\n keepPrevChar = true;\n const lastToken = tokens.at(-1);\n if (lastToken?.type === 'text') {\n lastToken.raw += token.raw;\n lastToken.text += token.text;\n } else {\n tokens.push(token);\n }\n continue;\n }\n\n if (src) {\n const errMsg = 'Infinite loop on byte: ' + src.charCodeAt(0);\n if (this.options.silent) {\n console.error(errMsg);\n break;\n } else {\n throw new Error(errMsg);\n }\n }\n }\n\n return tokens;\n }\n}\n", "import { _defaults } from './defaults.ts';\nimport {\n cleanUrl,\n escape,\n} from './helpers.ts';\nimport { other } from './rules.ts';\nimport type { MarkedOptions } from './MarkedOptions.ts';\nimport type { Tokens } from './Tokens.ts';\nimport type { _Parser } from './Parser.ts';\n\n/**\n * Renderer\n */\nexport class _Renderer<ParserOutput = string, RendererOutput = string> {\n options: MarkedOptions<ParserOutput, RendererOutput>;\n parser!: _Parser<ParserOutput, RendererOutput>; // set by the parser\n constructor(options?: MarkedOptions<ParserOutput, RendererOutput>) {\n this.options = options || _defaults;\n }\n\n space(token: Tokens.Space): RendererOutput {\n return '' as RendererOutput;\n }\n\n code({ text, lang, escaped }: Tokens.Code): RendererOutput {\n const langString = (lang || '').match(other.notSpaceStart)?.[0];\n\n const code = text.replace(other.endingNewline, '') + '\\n';\n\n if (!langString) {\n return '<pre><code>'\n + (escaped ? code : escape(code, true))\n + '</code></pre>\\n' as RendererOutput;\n }\n\n return '<pre><code class=\"language-'\n + escape(langString)\n + '\">'\n + (escaped ? code : escape(code, true))\n + '</code></pre>\\n' as RendererOutput;\n }\n\n blockquote({ tokens }: Tokens.Blockquote): RendererOutput {\n const body = this.parser.parse(tokens);\n return `<blockquote>\\n${body}</blockquote>\\n` as RendererOutput;\n }\n\n html({ text }: Tokens.HTML | Tokens.Tag): RendererOutput {\n return text as RendererOutput;\n }\n\n def(token: Tokens.Def): RendererOutput {\n return '' as RendererOutput;\n }\n\n heading({ tokens, depth }: Tokens.Heading): RendererOutput {\n return `<h${depth}>${this.parser.parseInline(tokens)}</h${depth}>\\n` as RendererOutput;\n }\n\n hr(token: Tokens.Hr): RendererOutput {\n return '<hr>\\n' as RendererOutput;\n }\n\n list(token: Tokens.List): RendererOutput {\n const ordered = token.ordered;\n const start = token.start;\n\n let body = '';\n for (let j = 0; j < token.items.length; j++) {\n const item = token.items[j];\n body += this.listitem(item);\n }\n\n const type = ordered ? 'ol' : 'ul';\n const startAttr = (ordered && start !== 1) ? (' start=\"' + start + '\"') : '';\n return '<' + type + startAttr + '>\\n' + body + '</' + type + '>\\n' as RendererOutput;\n }\n\n listitem(item: Tokens.ListItem): RendererOutput {\n return `<li>${this.parser.parse(item.tokens)}</li>\\n` as RendererOutput;\n }\n\n checkbox({ checked }: Tokens.Checkbox): RendererOutput {\n return '<input '\n + (checked ? 'checked=\"\" ' : '')\n + 'disabled=\"\" type=\"checkbox\"> ' as RendererOutput;\n }\n\n paragraph({ tokens }: Tokens.Paragraph): RendererOutput {\n return `<p>${this.parser.parseInline(tokens)}</p>\\n` as RendererOutput;\n }\n\n table(token: Tokens.Table): RendererOutput {\n let header = '';\n\n // header\n let cell = '';\n for (let j = 0; j < token.header.length; j++) {\n cell += this.tablecell(token.header[j]);\n }\n header += this.tablerow({ text: cell as ParserOutput });\n\n let body = '';\n for (let j = 0; j < token.rows.length; j++) {\n const row = token.rows[j];\n\n cell = '';\n for (let k = 0; k < row.length; k++) {\n cell += this.tablecell(row[k]);\n }\n\n body += this.tablerow({ text: cell as ParserOutput });\n }\n if (body) body = `<tbody>${body}</tbody>`;\n\n return '<table>\\n'\n + '<thead>\\n'\n + header\n + '</thead>\\n'\n + body\n + '</table>\\n' as RendererOutput;\n }\n\n tablerow({ text }: Tokens.TableRow<ParserOutput>): RendererOutput {\n return `<tr>\\n${text}</tr>\\n` as RendererOutput;\n }\n\n tablecell(token: Tokens.TableCell): RendererOutput {\n const content = this.parser.parseInline(token.tokens);\n const type = token.header ? 'th' : 'td';\n const tag = token.align\n ? `<${type} align=\"${token.align}\">`\n : `<${type}>`;\n return tag + content + `</${type}>\\n` as RendererOutput;\n }\n\n /**\n * span level renderer\n */\n strong({ tokens }: Tokens.Strong): RendererOutput {\n return `<strong>${this.parser.parseInline(tokens)}</strong>` as RendererOutput;\n }\n\n em({ tokens }: Tokens.Em): RendererOutput {\n return `<em>${this.parser.parseInline(tokens)}</em>` as RendererOutput;\n }\n\n codespan({ text }: Tokens.Codespan): RendererOutput {\n return `<code>${escape(text, true)}</code>` as RendererOutput;\n }\n\n br(token: Tokens.Br): RendererOutput {\n return '<br>' as RendererOutput;\n }\n\n del({ tokens }: Tokens.Del): RendererOutput {\n return `<del>${this.parser.parseInline(tokens)}</del>` as RendererOutput;\n }\n\n link({ href, title, tokens }: Tokens.Link): RendererOutput {\n const text = this.parser.parseInline(tokens) as string;\n const cleanHref = cleanUrl(href);\n if (cleanHref === null) {\n return text as RendererOutput;\n }\n href = cleanHref;\n let out = '<a href=\"' + href + '\"';\n if (title) {\n out += ' title=\"' + (escape(title)) + '\"';\n }\n out += '>' + text + '</a>';\n return out as RendererOutput;\n }\n\n image({ href, title, text, tokens }: Tokens.Image): RendererOutput {\n if (tokens) {\n text = this.parser.parseInline(tokens, this.parser.textRenderer) as string;\n }\n const cleanHref = cleanUrl(href);\n if (cleanHref === null) {\n return escape(text) as RendererOutput;\n }\n href = cleanHref;\n\n let out = `<img src=\"${href}\" alt=\"${text}\"`;\n if (title) {\n out += ` title=\"${escape(title)}\"`;\n }\n out += '>';\n return out as RendererOutput;\n }\n\n text(token: Tokens.Text | Tokens.Escape): RendererOutput {\n return 'tokens' in token && token.tokens\n ? this.parser.parseInline(token.tokens) as unknown as RendererOutput\n : ('escaped' in token && token.escaped ? token.text as RendererOutput : escape(token.text) as RendererOutput);\n }\n}\n", "import type { Tokens } from './Tokens.ts';\n\n/**\n * TextRenderer\n * returns only the textual part of the token\n */\nexport class _TextRenderer<RendererOutput = string> {\n // no need for block level renderers\n strong({ text }: Tokens.Strong): RendererOutput {\n return text as RendererOutput;\n }\n\n em({ text }: Tokens.Em): RendererOutput {\n return text as RendererOutput;\n }\n\n codespan({ text }: Tokens.Codespan): RendererOutput {\n return text as RendererOutput;\n }\n\n del({ text }: Tokens.Del): RendererOutput {\n return text as RendererOutput;\n }\n\n html({ text }: Tokens.HTML | Tokens.Tag): RendererOutput {\n return text as RendererOutput;\n }\n\n text({ text }: Tokens.Text | Tokens.Escape | Tokens.Tag): RendererOutput {\n return text as RendererOutput;\n }\n\n link({ text }: Tokens.Link): RendererOutput {\n return '' + text as RendererOutput;\n }\n\n image({ text }: Tokens.Image): RendererOutput {\n return '' + text as RendererOutput;\n }\n\n br(): RendererOutput {\n return '' as RendererOutput;\n }\n\n checkbox({ raw }: Tokens.Checkbox): RendererOutput {\n return raw as RendererOutput;\n }\n}\n", "import { _Renderer } from './Renderer.ts';\nimport { _TextRenderer } from './TextRenderer.ts';\nimport { _defaults } from './defaults.ts';\nimport type { MarkedToken, Token, Tokens } from './Tokens.ts';\nimport type { MarkedOptions } from './MarkedOptions.ts';\n\n/**\n * Parsing & Compiling\n */\nexport class _Parser<ParserOutput = string, RendererOutput = string> {\n options: MarkedOptions<ParserOutput, RendererOutput>;\n renderer: _Renderer<ParserOutput, RendererOutput>;\n textRenderer: _TextRenderer<RendererOutput>;\n constructor(options?: MarkedOptions<ParserOutput, RendererOutput>) {\n this.options = options || _defaults;\n this.options.renderer = this.options.renderer || new _Renderer<ParserOutput, RendererOutput>();\n this.renderer = this.options.renderer;\n this.renderer.options = this.options;\n this.renderer.parser = this;\n this.textRenderer = new _TextRenderer<RendererOutput>();\n }\n\n /**\n * Static Parse Method\n */\n static parse<ParserOutput = string, RendererOutput = string>(tokens: Token[], options?: MarkedOptions<ParserOutput, RendererOutput>) {\n const parser = new _Parser<ParserOutput, RendererOutput>(options);\n return parser.parse(tokens);\n }\n\n /**\n * Static Parse Inline Method\n */\n static parseInline<ParserOutput = string, RendererOutput = string>(tokens: Token[], options?: MarkedOptions<ParserOutput, RendererOutput>) {\n const parser = new _Parser<ParserOutput, RendererOutput>(options);\n return parser.parseInline(tokens);\n }\n\n /**\n * Parse Loop\n */\n parse(tokens: Token[]): ParserOutput {\n let out = '';\n\n for (let i = 0; i < tokens.length; i++) {\n const anyToken = tokens[i];\n\n // Run any renderer extensions\n if (this.options.extensions?.renderers?.[anyToken.type]) {\n const genericToken = anyToken as Tokens.Generic;\n const ret = this.options.extensions.renderers[genericToken.type].call({ parser: this }, genericToken);\n if (ret !== false || !['space', 'hr', 'heading', 'code', 'table', 'blockquote', 'list', 'html', 'def', 'paragraph', 'text'].includes(genericToken.type)) {\n out += ret || '';\n continue;\n }\n }\n\n const token = anyToken as MarkedToken;\n\n switch (token.type) {\n case 'space': {\n out += this.renderer.space(token);\n break;\n }\n case 'hr': {\n out += this.renderer.hr(token);\n break;\n }\n case 'heading': {\n out += this.renderer.heading(token);\n break;\n }\n case 'code': {\n out += this.renderer.code(token);\n break;\n }\n case 'table': {\n out += this.renderer.table(token);\n break;\n }\n case 'blockquote': {\n out += this.renderer.blockquote(token);\n break;\n }\n case 'list': {\n out += this.renderer.list(token);\n break;\n }\n case 'checkbox': {\n out += this.renderer.checkbox(token);\n break;\n }\n case 'html': {\n out += this.renderer.html(token);\n break;\n }\n case 'def': {\n out += this.renderer.def(token);\n break;\n }\n case 'paragraph': {\n out += this.renderer.paragraph(token);\n break;\n }\n case 'text': {\n out += this.renderer.text(token);\n break;\n }\n\n default: {\n const errMsg = 'Token with \"' + token.type + '\" type was not found.';\n if (this.options.silent) {\n console.error(errMsg);\n return '' as ParserOutput;\n } else {\n throw new Error(errMsg);\n }\n }\n }\n }\n\n return out as ParserOutput;\n }\n\n /**\n * Parse Inline Tokens\n */\n parseInline(tokens: Token[], renderer: _Renderer<ParserOutput, RendererOutput> | _TextRenderer<RendererOutput> = this.renderer): ParserOutput {\n let out = '';\n\n for (let i = 0; i < tokens.length; i++) {\n const anyToken = tokens[i];\n\n // Run any renderer extensions\n if (this.options.extensions?.renderers?.[anyToken.type]) {\n const ret = this.options.extensions.renderers[anyToken.type].call({ parser: this }, anyToken);\n if (ret !== false || !['escape', 'html', 'link', 'image', 'strong', 'em', 'codespan', 'br', 'del', 'text'].includes(anyToken.type)) {\n out += ret || '';\n continue;\n }\n }\n\n const token = anyToken as MarkedToken;\n\n switch (token.type) {\n case 'escape': {\n out += renderer.text(token);\n break;\n }\n case 'html': {\n out += renderer.html(token);\n break;\n }\n case 'link': {\n out += renderer.link(token);\n break;\n }\n case 'image': {\n out += renderer.image(token);\n break;\n }\n case 'checkbox': {\n out += renderer.checkbox(token);\n break;\n }\n case 'strong': {\n out += renderer.strong(token);\n break;\n }\n case 'em': {\n out += renderer.em(token);\n break;\n }\n case 'codespan': {\n out += renderer.codespan(token);\n break;\n }\n case 'br': {\n out += renderer.br(token);\n break;\n }\n case 'del': {\n out += renderer.del(token);\n break;\n }\n case 'text': {\n out += renderer.text(token);\n break;\n }\n default: {\n const errMsg = 'Token with \"' + token.type + '\" type was not found.';\n if (this.options.silent) {\n console.error(errMsg);\n return '' as ParserOutput;\n } else {\n throw new Error(errMsg);\n }\n }\n }\n }\n return out as ParserOutput;\n }\n}\n", "import { _defaults } from './defaults.ts';\nimport { _Lexer } from './Lexer.ts';\nimport { _Parser } from './Parser.ts';\nimport type { MarkedOptions } from './MarkedOptions.ts';\nimport type { Token, TokensList } from './Tokens.ts';\n\nexport class _Hooks<ParserOutput = string, RendererOutput = string> {\n options: MarkedOptions<ParserOutput, RendererOutput>;\n block?: boolean;\n\n constructor(options?: MarkedOptions<ParserOutput, RendererOutput>) {\n this.options = options || _defaults;\n }\n\n static passThroughHooks = new Set([\n 'preprocess',\n 'postprocess',\n 'processAllTokens',\n 'emStrongMask',\n ]);\n\n static passThroughHooksRespectAsync = new Set([\n 'preprocess',\n 'postprocess',\n 'processAllTokens',\n ]);\n\n /**\n * Process markdown before marked\n */\n preprocess(markdown: string) {\n return markdown;\n }\n\n /**\n * Process HTML after marked is finished\n */\n postprocess(html: ParserOutput) {\n return html;\n }\n\n /**\n * Process all tokens before walk tokens\n */\n processAllTokens(tokens: Token[] | TokensList) {\n return tokens;\n }\n\n /**\n * Mask contents that should not be interpreted as em/strong delimiters\n */\n emStrongMask(src: string) {\n return src;\n }\n\n /**\n * Provide function to tokenize markdown\n */\n provideLexer() {\n return this.block ? _Lexer.lex : _Lexer.lexInline;\n }\n\n /**\n * Provide function to parse tokens\n */\n provideParser() {\n return this.block ? _Parser.parse<ParserOutput, RendererOutput> : _Parser.parseInline<ParserOutput, RendererOutput>;\n }\n}\n", "import { _getDefaults } from './defaults.ts';\nimport { _Lexer } from './Lexer.ts';\nimport { _Parser } from './Parser.ts';\nimport { _Hooks } from './Hooks.ts';\nimport { _Renderer } from './Renderer.ts';\nimport { _Tokenizer } from './Tokenizer.ts';\nimport { _TextRenderer } from './TextRenderer.ts';\nimport { escape } from './helpers.ts';\nimport type { MarkedExtension, MarkedOptions } from './MarkedOptions.ts';\nimport type { Token, Tokens, TokensList } from './Tokens.ts';\n\nexport type MaybePromise = void | Promise<void>;\n\ntype UnknownFunction = (...args: unknown[]) => unknown;\ntype GenericRendererFunction = (...args: unknown[]) => string | false;\n\nexport class Marked<ParserOutput = string, RendererOutput = string> {\n defaults = _getDefaults<ParserOutput, RendererOutput>();\n options = this.setOptions;\n\n parse = this.parseMarkdown(true);\n parseInline = this.parseMarkdown(false);\n\n Parser = _Parser<ParserOutput, RendererOutput>;\n Renderer = _Renderer<ParserOutput, RendererOutput>;\n TextRenderer = _TextRenderer<RendererOutput>;\n Lexer = _Lexer;\n Tokenizer = _Tokenizer<ParserOutput, RendererOutput>;\n Hooks = _Hooks<ParserOutput, RendererOutput>;\n\n constructor(...args: MarkedExtension<ParserOutput, RendererOutput>[]) {\n this.use(...args);\n }\n\n /**\n * Run callback for every token\n */\n walkTokens(tokens: Token[] | TokensList, callback: (token: Token) => MaybePromise | MaybePromise[]) {\n let values: MaybePromise[] = [];\n for (const token of tokens) {\n values = values.concat(callback.call(this, token));\n switch (token.type) {\n case 'table': {\n const tableToken = token as Tokens.Table;\n for (const cell of tableToken.header) {\n values = values.concat(this.walkTokens(cell.tokens, callback));\n }\n for (const row of tableToken.rows) {\n for (const cell of row) {\n values = values.concat(this.walkTokens(cell.tokens, callback));\n }\n }\n break;\n }\n case 'list': {\n const listToken = token as Tokens.List;\n values = values.concat(this.walkTokens(listToken.items, callback));\n break;\n }\n default: {\n const genericToken = token as Tokens.Generic;\n if (this.defaults.extensions?.childTokens?.[genericToken.type]) {\n this.defaults.extensions.childTokens[genericToken.type].forEach((childTokens) => {\n const tokens = genericToken[childTokens].flat(Infinity) as Token[] | TokensList;\n values = values.concat(this.walkTokens(tokens, callback));\n });\n } else if (genericToken.tokens) {\n values = values.concat(this.walkTokens(genericToken.tokens, callback));\n }\n }\n }\n }\n return values;\n }\n\n use(...args: MarkedExtension<ParserOutput, RendererOutput>[]) {\n const extensions: MarkedOptions<ParserOutput, RendererOutput>['extensions'] = this.defaults.extensions || { renderers: {}, childTokens: {} };\n\n args.forEach((pack) => {\n // copy options to new object\n const opts = { ...pack } as MarkedOptions<ParserOutput, RendererOutput>;\n\n // set async to true if it was set to true before\n opts.async = this.defaults.async || opts.async || false;\n\n // ==-- Parse \"addon\" extensions --== //\n if (pack.extensions) {\n pack.extensions.forEach((ext) => {\n if (!ext.name) {\n throw new Error('extension name required');\n }\n if ('renderer' in ext) { // Renderer extensions\n const prevRenderer = extensions.renderers[ext.name];\n if (prevRenderer) {\n // Replace extension with func to run new extension but fall back if false\n extensions.renderers[ext.name] = function(...args) {\n let ret = ext.renderer.apply(this, args);\n if (ret === false) {\n ret = prevRenderer.apply(this, args);\n }\n return ret;\n };\n } else {\n extensions.renderers[ext.name] = ext.renderer;\n }\n }\n if ('tokenizer' in ext) { // Tokenizer Extensions\n if (!ext.level || (ext.level !== 'block' && ext.level !== 'inline')) {\n throw new Error(\"extension level must be 'block' or 'inline'\");\n }\n const extLevel = extensions[ext.level];\n if (extLevel) {\n extLevel.unshift(ext.tokenizer);\n } else {\n extensions[ext.level] = [ext.tokenizer];\n }\n if (ext.start) { // Function to check for start of token\n if (ext.level === 'block') {\n if (extensions.startBlock) {\n extensions.startBlock.push(ext.start);\n } else {\n extensions.startBlock = [ext.start];\n }\n } else if (ext.level === 'inline') {\n if (extensions.startInline) {\n extensions.startInline.push(ext.start);\n } else {\n extensions.startInline = [ext.start];\n }\n }\n }\n }\n if ('childTokens' in ext && ext.childTokens) { // Child tokens to be visited by walkTokens\n extensions.childTokens[ext.name] = ext.childTokens;\n }\n });\n opts.extensions = extensions;\n }\n\n // ==-- Parse \"overwrite\" extensions --== //\n if (pack.renderer) {\n const renderer = this.defaults.renderer || new _Renderer<ParserOutput, RendererOutput>(this.defaults);\n for (const prop in pack.renderer) {\n if (!(prop in renderer)) {\n throw new Error(`renderer '${prop}' does not exist`);\n }\n if (['options', 'parser'].includes(prop)) {\n // ignore options property\n continue;\n }\n const rendererProp = prop as Exclude<keyof _Renderer<ParserOutput, RendererOutput>, 'options' | 'parser'>;\n const rendererFunc = pack.renderer[rendererProp] as GenericRendererFunction;\n const prevRenderer = renderer[rendererProp] as GenericRendererFunction;\n // Replace renderer with func to run extension, but fall back if false\n renderer[rendererProp] = (...args: unknown[]) => {\n let ret = rendererFunc.apply(renderer, args);\n if (ret === false) {\n ret = prevRenderer.apply(renderer, args);\n }\n return (ret || '') as RendererOutput;\n };\n }\n opts.renderer = renderer;\n }\n if (pack.tokenizer) {\n const tokenizer = this.defaults.tokenizer || new _Tokenizer<ParserOutput, RendererOutput>(this.defaults);\n for (const prop in pack.tokenizer) {\n if (!(prop in tokenizer)) {\n throw new Error(`tokenizer '${prop}' does not exist`);\n }\n if (['options', 'rules', 'lexer'].includes(prop)) {\n // ignore options, rules, and lexer properties\n continue;\n }\n const tokenizerProp = prop as Exclude<keyof _Tokenizer<ParserOutput, RendererOutput>, 'options' | 'rules' | 'lexer'>;\n const tokenizerFunc = pack.tokenizer[tokenizerProp] as UnknownFunction;\n const prevTokenizer = tokenizer[tokenizerProp] as UnknownFunction;\n // Replace tokenizer with func to run extension, but fall back if false\n // @ts-expect-error cannot type tokenizer function dynamically\n tokenizer[tokenizerProp] = (...args: unknown[]) => {\n let ret = tokenizerFunc.apply(tokenizer, args);\n if (ret === false) {\n ret = prevTokenizer.apply(tokenizer, args);\n }\n return ret;\n };\n }\n opts.tokenizer = tokenizer;\n }\n\n // ==-- Parse Hooks extensions --== //\n if (pack.hooks) {\n const hooks = this.defaults.hooks || new _Hooks<ParserOutput, RendererOutput>();\n for (const prop in pack.hooks) {\n if (!(prop in hooks)) {\n throw new Error(`hook '${prop}' does not exist`);\n }\n if (['options', 'block'].includes(prop)) {\n // ignore options and block properties\n continue;\n }\n const hooksProp = prop as Exclude<keyof _Hooks<ParserOutput, RendererOutput>, 'options' | 'block'>;\n const hooksFunc = pack.hooks[hooksProp] as UnknownFunction;\n const prevHook = hooks[hooksProp] as UnknownFunction;\n if (_Hooks.passThroughHooks.has(prop)) {\n // @ts-expect-error cannot type hook function dynamically\n hooks[hooksProp] = (arg: unknown) => {\n if (this.defaults.async && _Hooks.passThroughHooksRespectAsync.has(prop)) {\n return (async() => {\n const ret = await hooksFunc.call(hooks, arg);\n return prevHook.call(hooks, ret);\n })();\n }\n\n const ret = hooksFunc.call(hooks, arg);\n return prevHook.call(hooks, ret);\n };\n } else {\n // @ts-expect-error cannot type hook function dynamically\n hooks[hooksProp] = (...args: unknown[]) => {\n if (this.defaults.async) {\n return (async() => {\n let ret = await hooksFunc.apply(hooks, args);\n if (ret === false) {\n ret = await prevHook.apply(hooks, args);\n }\n return ret;\n })();\n }\n\n let ret = hooksFunc.apply(hooks, args);\n if (ret === false) {\n ret = prevHook.apply(hooks, args);\n }\n return ret;\n };\n }\n }\n opts.hooks = hooks;\n }\n\n // ==-- Parse WalkTokens extensions --== //\n if (pack.walkTokens) {\n const walkTokens = this.defaults.walkTokens;\n const packWalktokens = pack.walkTokens;\n opts.walkTokens = function(token) {\n let values: MaybePromise[] = [];\n values.push(packWalktokens.call(this, token));\n if (walkTokens) {\n values = values.concat(walkTokens.call(this, token));\n }\n return values;\n };\n }\n\n this.defaults = { ...this.defaults, ...opts };\n });\n\n return this;\n }\n\n setOptions(opt: MarkedOptions<ParserOutput, RendererOutput>) {\n this.defaults = { ...this.defaults, ...opt };\n return this;\n }\n\n lexer(src: string, options?: MarkedOptions<ParserOutput, RendererOutput>) {\n return _Lexer.lex(src, options ?? this.defaults);\n }\n\n parser(tokens: Token[], options?: MarkedOptions<ParserOutput, RendererOutput>) {\n return _Parser.parse<ParserOutput, RendererOutput>(tokens, options ?? this.defaults);\n }\n\n private parseMarkdown(blockType: boolean) {\n type overloadedParse = {\n (src: string, options: MarkedOptions<ParserOutput, RendererOutput> & { async: true }): Promise<ParserOutput>;\n (src: string, options: MarkedOptions<ParserOutput, RendererOutput> & { async: false }): ParserOutput;\n (src: string, options?: MarkedOptions<ParserOutput, RendererOutput> | null): ParserOutput | Promise<ParserOutput>;\n };\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const parse: overloadedParse = (src: string, options?: MarkedOptions<ParserOutput, RendererOutput> | null): any => {\n const origOpt = { ...options };\n const opt = { ...this.defaults, ...origOpt };\n\n const throwError = this.onError(!!opt.silent, !!opt.async);\n\n // throw error if an extension set async to true but parse was called with async: false\n if (this.defaults.async === true && origOpt.async === false) {\n return throwError(new Error('marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise.'));\n }\n\n // throw error in case of non string input\n if (typeof src === 'undefined' || src === null) {\n return throwError(new Error('marked(): input parameter is undefined or null'));\n }\n if (typeof src !== 'string') {\n return throwError(new Error('marked(): input parameter is of type '\n + Object.prototype.toString.call(src) + ', string expected'));\n }\n\n if (opt.hooks) {\n opt.hooks.options = opt;\n opt.hooks.block = blockType;\n }\n\n if (opt.async) {\n return (async() => {\n const processedSrc = opt.hooks ? await opt.hooks.preprocess(src) : src;\n const lexer = opt.hooks ? await opt.hooks.provideLexer() : (blockType ? _Lexer.lex : _Lexer.lexInline);\n const tokens = await lexer(processedSrc, opt);\n const processedTokens = opt.hooks ? await opt.hooks.processAllTokens(tokens) : tokens;\n if (opt.walkTokens) {\n await Promise.all(this.walkTokens(processedTokens, opt.walkTokens));\n }\n const parser = opt.hooks ? await opt.hooks.provideParser() : (blockType ? _Parser.parse : _Parser.parseInline);\n const html = await parser(processedTokens, opt);\n return opt.hooks ? await opt.hooks.postprocess(html) : html;\n })().catch(throwError);\n }\n\n try {\n if (opt.hooks) {\n src = opt.hooks.preprocess(src) as string;\n }\n const lexer = opt.hooks ? opt.hooks.provideLexer() : (blockType ? _Lexer.lex : _Lexer.lexInline);\n let tokens = lexer(src, opt);\n if (opt.hooks) {\n tokens = opt.hooks.processAllTokens(tokens);\n }\n if (opt.walkTokens) {\n this.walkTokens(tokens, opt.walkTokens);\n }\n const parser = opt.hooks ? opt.hooks.provideParser() : (blockType ? _Parser.parse : _Parser.parseInline);\n let html = parser(tokens, opt);\n if (opt.hooks) {\n html = opt.hooks.postprocess(html);\n }\n return html;\n } catch(e) {\n return throwError(e as Error);\n }\n };\n\n return parse;\n }\n\n private onError(silent: boolean, async: boolean) {\n return (e: Error): string | Promise<string> => {\n e.message += '\\nPlease report this to https://github.com/markedjs/marked.';\n\n if (silent) {\n const msg = '<p>An error occurred:</p><pre>'\n + escape(e.message + '', true)\n + '</pre>';\n if (async) {\n return Promise.resolve(msg);\n }\n return msg;\n }\n\n if (async) {\n return Promise.reject(e);\n }\n throw e;\n };\n }\n}\n", "import { _Lexer } from './Lexer.ts';\nimport { _Parser } from './Parser.ts';\nimport { _Tokenizer } from './Tokenizer.ts';\nimport { _Renderer } from './Renderer.ts';\nimport { _TextRenderer } from './TextRenderer.ts';\nimport { _Hooks } from './Hooks.ts';\nimport { Marked } from './Instance.ts';\nimport {\n _getDefaults,\n changeDefaults,\n _defaults,\n} from './defaults.ts';\nimport type { MarkedExtension, MarkedOptions } from './MarkedOptions.ts';\nimport type { Token, TokensList } from './Tokens.ts';\nimport type { MaybePromise } from './Instance.ts';\n\nconst markedInstance = new Marked();\n\n/**\n * Compiles markdown to HTML asynchronously.\n *\n * @param src String of markdown source to be compiled\n * @param options Hash of options, having async: true\n * @return Promise of string of compiled HTML\n */\nexport function marked(src: string, options: MarkedOptions & { async: true }): Promise<string>;\n\n/**\n * Compiles markdown to HTML.\n *\n * @param src String of markdown source to be compiled\n * @param options Optional hash of options\n * @return String of compiled HTML. Will be a Promise of string if async is set to true by any extensions.\n */\nexport function marked(src: string, options: MarkedOptions & { async: false }): string;\nexport function marked(src: string, options: MarkedOptions & { async: true }): Promise<string>;\nexport function marked(src: string, options?: MarkedOptions | null): string | Promise<string>;\nexport function marked(src: string, opt?: MarkedOptions | null): string | Promise<string> {\n return markedInstance.parse(src, opt);\n}\n\n/**\n * Sets the default options.\n *\n * @param options Hash of options\n */\nmarked.options =\n marked.setOptions = function(options: MarkedOptions) {\n markedInstance.setOptions(options);\n marked.defaults = markedInstance.defaults;\n changeDefaults(marked.defaults);\n return marked;\n };\n\n/**\n * Gets the original marked default options.\n */\nmarked.getDefaults = _getDefaults;\n\nmarked.defaults = _defaults;\n\n/**\n * Use Extension\n */\n\nmarked.use = function(...args: MarkedExtension[]) {\n markedInstance.use(...args);\n marked.defaults = markedInstance.defaults;\n changeDefaults(marked.defaults);\n return marked;\n};\n\n/**\n * Run callback for every token\n */\n\nmarked.walkTokens = function(tokens: Token[] | TokensList, callback: (token: Token) => MaybePromise | MaybePromise[]) {\n return markedInstance.walkTokens(tokens, callback);\n};\n\n/**\n * Compiles markdown to HTML without enclosing `p` tag.\n *\n * @param src String of markdown source to be compiled\n * @param options Hash of options\n * @return String of compiled HTML\n */\nmarked.parseInline = markedInstance.parseInline;\n\n/**\n * Expose\n */\nmarked.Parser = _Parser;\nmarked.parser = _Parser.parse;\nmarked.Renderer = _Renderer;\nmarked.TextRenderer = _TextRenderer;\nmarked.Lexer = _Lexer;\nmarked.lexer = _Lexer.lex;\nmarked.Tokenizer = _Tokenizer;\nmarked.Hooks = _Hooks;\nmarked.parse = marked;\n\nexport const options = marked.options;\nexport const setOptions = marked.setOptions;\nexport const use = marked.use;\nexport const walkTokens = marked.walkTokens;\nexport const parseInline = marked.parseInline;\nexport const parse = marked;\nexport const parser = _Parser.parse;\nexport const lexer = _Lexer.lex;\nexport { _defaults as defaults, _getDefaults as getDefaults } from './defaults.ts';\nexport { _Lexer as Lexer } from './Lexer.ts';\nexport { _Parser as Parser } from './Parser.ts';\nexport { _Tokenizer as Tokenizer } from './Tokenizer.ts';\nexport { _Renderer as Renderer } from './Renderer.ts';\nexport { _TextRenderer as TextRenderer } from './TextRenderer.ts';\nexport { _Hooks as Hooks } from './Hooks.ts';\nexport { Marked } from './Instance.ts';\nexport type * from './MarkedOptions.ts';\nexport type * from './Tokens.ts';\n", "import DOMPurify from 'dompurify';\nimport { unsafeHTML } from 'lit-html/directives/unsafe-html.js';\nimport { marked } from 'marked';\n\n/**\n * Render Markdown safely as HTML using marked and DOMPurify.\n * Returns a lit-html TemplateResult via the unsafeHTML directive so it can be\n * embedded directly in templates.\n *\n * @param {string} markdown - Markdown source text\n */\nexport function renderMarkdown(markdown) {\n const parsed = /** @type {string} */ (marked.parse(markdown));\n const html_string = DOMPurify.sanitize(parsed);\n return unsafeHTML(html_string);\n}\n", "/**\n * Known status values in canonical order.\n *\n * @type {Array<'open'|'in_progress'|'closed'>}\n */\nexport const STATUSES = ['open', 'in_progress', 'closed'];\n\n/**\n * Map canonical status to display label.\n *\n * @param {string | null | undefined} status\n * @returns {string}\n */\nexport function statusLabel(status) {\n switch ((status || '').toString()) {\n case 'open':\n return 'Open';\n case 'in_progress':\n return 'In progress';\n case 'closed':\n return 'Closed';\n default:\n return (status || '').toString() || 'Open';\n }\n}\n", "// Issue Detail view implementation (lit-html based)\nimport { html, render } from 'lit-html';\nimport { parseView } from '../router.js';\nimport { issueHashFor } from '../utils/issue-url.js';\nimport { debug } from '../utils/logging.js';\nimport { renderMarkdown } from '../utils/markdown.js';\nimport { emojiForPriority } from '../utils/priority-badge.js';\nimport { priority_levels } from '../utils/priority.js';\nimport { statusLabel } from '../utils/status.js';\nimport { showToast } from '../utils/toast.js';\nimport { createTypeBadge } from '../utils/type-badge.js';\n\n/**\n * Format a date string for display.\n *\n * @param {string} [dateStr]\n * @returns {string}\n */\nfunction formatCommentDate(dateStr) {\n if (!dateStr) return '';\n try {\n const date = new Date(dateStr);\n return date.toLocaleDateString(undefined, {\n year: 'numeric',\n month: 'short',\n day: 'numeric',\n hour: '2-digit',\n minute: '2-digit'\n });\n } catch {\n return dateStr;\n }\n}\n\n/**\n * @typedef {Object} Dependency\n * @property {string} id\n * @property {string} [title]\n * @property {string} [status]\n * @property {number} [priority]\n * @property {string} [issue_type]\n */\n\n/**\n * @typedef {Object} Comment\n * @property {number} id\n * @property {string} [author]\n * @property {string} text\n * @property {string} [created_at]\n */\n\n/**\n * @typedef {Object} IssueDetail\n * @property {string} id\n * @property {string} [title]\n * @property {string} [description]\n * @property {string} [design]\n * @property {string} [acceptance]\n * @property {string} [notes]\n * @property {string} [status]\n * @property {(string|null)} [close_reason]\n * @property {string} [assignee]\n * @property {number} [priority]\n * @property {string[]} [labels]\n * @property {Dependency[]} [dependencies]\n * @property {Dependency[]} [dependents]\n * @property {Comment[]} [comments]\n */\n\n/**\n * @param {string} hash\n */\nfunction defaultNavigateFn(hash) {\n window.location.hash = hash;\n}\n\n/**\n * Create the Issue Detail view.\n *\n * @param {HTMLElement} mount_element - Element to render into.\n * @param {(type: string, payload?: unknown) => Promise<unknown>} sendFn - RPC transport.\n * @param {(hash: string) => void} [navigateFn] - Navigation function; defaults to setting location.hash.\n * @param {{ snapshotFor?: (client_id: string) => any[], subscribe?: (fn: () => void) => () => void }} [issue_stores] - Optional issue stores for live updates.\n * @returns {{ load: (id: string) => Promise<void>, clear: () => void, destroy: () => void }} View API.\n */\nexport function createDetailView(\n mount_element,\n sendFn,\n navigateFn = defaultNavigateFn,\n issue_stores = undefined\n) {\n const log = debug('views:detail');\n /** @type {IssueDetail | null} */\n let current = null;\n /** @type {string | null} */\n let current_id = null;\n /** @type {boolean} */\n let pending = false;\n /** @type {boolean} */\n let edit_title = false;\n /** @type {boolean} */\n let edit_desc = false;\n /** @type {boolean} */\n let edit_design = false;\n /** @type {boolean} */\n let edit_notes = false;\n /** @type {boolean} */\n let edit_accept = false;\n /** @type {boolean} */\n let edit_assignee = false;\n /** @type {string} */\n let new_label_text = '';\n /** @type {string} */\n let comment_text = '';\n /** @type {boolean} */\n let comment_pending = false;\n\n /** @type {HTMLDialogElement | null} */\n let delete_dialog = null;\n\n function ensureDeleteDialog() {\n if (delete_dialog) return delete_dialog;\n delete_dialog = document.createElement('dialog');\n delete_dialog.id = 'delete-confirm-dialog';\n delete_dialog.setAttribute('role', 'alertdialog');\n delete_dialog.setAttribute('aria-modal', 'true');\n document.body.appendChild(delete_dialog);\n return delete_dialog;\n }\n\n function openDeleteDialog() {\n if (!current) return;\n const dialog = ensureDeleteDialog();\n const issueId = current.id;\n const issueTitle = current.title || '(no title)';\n dialog.innerHTML = `\n <div class=\"delete-confirm\">\n <h2 class=\"delete-confirm__title\">Delete Issue</h2>\n <p class=\"delete-confirm__message\">\n Are you sure you want to delete issue <strong>${issueId}</strong> \u2014 <strong>${issueTitle}</strong>? This action cannot be undone.\n </p>\n <div class=\"delete-confirm__actions\">\n <button type=\"button\" class=\"btn\" id=\"delete-cancel-btn\">Cancel</button>\n <button type=\"button\" class=\"btn danger\" id=\"delete-confirm-btn\">Delete</button>\n </div>\n </div>\n `;\n const cancelBtn = dialog.querySelector('#delete-cancel-btn');\n const confirmBtn = dialog.querySelector('#delete-confirm-btn');\n\n cancelBtn?.addEventListener('click', () => {\n if (typeof dialog.close === 'function') {\n dialog.close();\n }\n dialog.removeAttribute('open');\n });\n\n confirmBtn?.addEventListener('click', async () => {\n if (typeof dialog.close === 'function') {\n dialog.close();\n }\n dialog.removeAttribute('open');\n await performDelete();\n });\n\n dialog.addEventListener('cancel', (ev) => {\n ev.preventDefault();\n if (typeof dialog.close === 'function') {\n dialog.close();\n }\n dialog.removeAttribute('open');\n });\n\n if (typeof dialog.showModal === 'function') {\n try {\n dialog.showModal();\n dialog.setAttribute('open', '');\n } catch {\n dialog.setAttribute('open', '');\n }\n } else {\n dialog.setAttribute('open', '');\n }\n }\n\n async function performDelete() {\n if (!current) return;\n const id = current.id;\n try {\n await sendFn('delete-issue', { id });\n current = null;\n current_id = null;\n doRender();\n // Navigate back to close the dialog\n const view = parseView(window.location.hash || '');\n navigateFn(`#/${view}`);\n } catch (err) {\n log('delete failed: %o', err);\n showToast('Failed to delete issue', 'error');\n }\n }\n\n /**\n * @param {Event} ev\n */\n function onDeleteClick(ev) {\n ev.stopPropagation();\n ev.preventDefault();\n openDeleteDialog();\n }\n\n /** @param {string} id */\n function issueHref(id) {\n /** @type {'issues'|'epics'|'board'} */\n const view = parseView(window.location.hash || '');\n return issueHashFor(view, id);\n }\n\n /**\n * @param {string} message\n */\n function renderPlaceholder(message) {\n render(\n html`\n <div class=\"panel__body\" id=\"detail-root\">\n <p class=\"muted\">${message}</p>\n </div>\n `,\n mount_element\n );\n }\n\n /**\n * Refresh current from subscription store snapshot if available.\n */\n function refreshFromStore() {\n if (\n !current_id ||\n !issue_stores ||\n typeof issue_stores.snapshotFor !== 'function'\n ) {\n return;\n }\n const arr = /** @type {IssueDetail[]} */ (\n issue_stores.snapshotFor(`detail:${current_id}`)\n );\n if (Array.isArray(arr) && arr.length > 0) {\n // First item is the issue for this subscription\n const found =\n arr.find((it) => String(it.id) === String(current_id)) || arr[0];\n current = /** @type {IssueDetail} */ (found);\n }\n }\n\n // Live updates: re-render when issue stores change\n if (issue_stores && typeof issue_stores.subscribe === 'function') {\n issue_stores.subscribe(() => {\n try {\n refreshFromStore();\n doRender();\n } catch (err) {\n log('issue stores listener error %o', err);\n }\n });\n }\n\n // Handlers\n const onTitleSpanClick = () => {\n edit_title = true;\n doRender();\n };\n /**\n * @param {KeyboardEvent} ev\n */\n const onTitleKeydown = (ev) => {\n if (ev.key === 'Enter') {\n edit_title = true;\n doRender();\n } else if (ev.key === 'Escape') {\n edit_title = false;\n doRender();\n }\n };\n const onTitleSave = async () => {\n if (!current || pending) {\n return;\n }\n const input = /** @type {HTMLInputElement|null} */ (\n mount_element.querySelector('h2 input')\n );\n const prev = current.title || '';\n const next = input ? input.value : '';\n if (next === prev) {\n edit_title = false;\n doRender();\n return;\n }\n pending = true;\n if (input) {\n input.disabled = true;\n }\n try {\n log('save title %s \u2192 %s', String(current.id), next);\n const updated = await sendFn('edit-text', {\n id: current.id,\n field: 'title',\n value: next\n });\n if (updated && typeof updated === 'object') {\n current = /** @type {IssueDetail} */ (updated);\n edit_title = false;\n doRender();\n }\n } catch (err) {\n log('save title failed %s %o', String(current.id), err);\n current.title = prev;\n edit_title = false;\n doRender();\n showToast('Failed to save title', 'error');\n } finally {\n pending = false;\n }\n };\n const onTitleCancel = () => {\n edit_title = false;\n doRender();\n };\n // Assignee inline edit handlers\n const onAssigneeSpanClick = () => {\n edit_assignee = true;\n doRender();\n };\n /**\n * @param {KeyboardEvent} ev\n */\n const onAssigneeKeydown = (ev) => {\n if (ev.key === 'Enter') {\n ev.preventDefault();\n edit_assignee = true;\n doRender();\n } else if (ev.key === 'Escape') {\n ev.preventDefault();\n edit_assignee = false;\n doRender();\n }\n };\n const onAssigneeSave = async () => {\n if (!current || pending) {\n return;\n }\n const input = /** @type {HTMLInputElement|null} */ (\n mount_element.querySelector('#detail-root .prop.assignee input')\n );\n const prev = current?.assignee ?? '';\n const next = input?.value ?? '';\n if (next === prev) {\n edit_assignee = false;\n doRender();\n return;\n }\n pending = true;\n if (input) {\n input.disabled = true;\n }\n try {\n log('save assignee %s \u2192 %s', String(current.id), next);\n const updated = await sendFn('update-assignee', {\n id: current.id,\n assignee: next\n });\n if (updated && typeof updated === 'object') {\n current = /** @type {IssueDetail} */ (updated);\n edit_assignee = false;\n doRender();\n }\n } catch (err) {\n log('save assignee failed %s %o', String(current.id), err);\n // revert visually\n current.assignee = prev;\n edit_assignee = false;\n doRender();\n showToast('Failed to update assignee', 'error');\n } finally {\n pending = false;\n }\n };\n const onAssigneeCancel = () => {\n edit_assignee = false;\n doRender();\n };\n\n // Labels handlers\n /**\n * @param {Event} ev\n */\n const onLabelInput = (ev) => {\n const el = /** @type {HTMLInputElement} */ (ev.currentTarget);\n new_label_text = el.value || '';\n };\n /**\n * @param {KeyboardEvent} e\n */\n function onLabelKeydown(e) {\n if (e.key === 'Enter') {\n e.preventDefault();\n void onAddLabel();\n }\n }\n async function onAddLabel() {\n if (!current || pending) {\n return;\n }\n const text = new_label_text.trim();\n if (!text) {\n return;\n }\n pending = true;\n try {\n log('add label %s \u2192 %s', String(current.id), text);\n const updated = await sendFn('label-add', {\n id: current.id,\n label: text\n });\n if (updated && typeof updated === 'object') {\n current = /** @type {IssueDetail} */ (updated);\n new_label_text = '';\n doRender();\n }\n } catch (err) {\n log('add label failed %s %o', String(current.id), err);\n showToast('Failed to add label', 'error');\n } finally {\n pending = false;\n }\n }\n /**\n * @param {string} label\n */\n async function onRemoveLabel(label) {\n if (!current || pending) {\n return;\n }\n pending = true;\n try {\n log('remove label %s \u2192 %s', String(current?.id || ''), label);\n const updated = await sendFn('label-remove', {\n id: current.id,\n label\n });\n if (updated && typeof updated === 'object') {\n current = /** @type {IssueDetail} */ (updated);\n doRender();\n }\n } catch (err) {\n log('remove label failed %s %o', String(current?.id || ''), err);\n showToast('Failed to remove label', 'error');\n } finally {\n pending = false;\n }\n }\n /**\n * @param {Event} ev\n */\n const onStatusChange = async (ev) => {\n if (!current || pending) {\n doRender();\n return;\n }\n const sel = /** @type {HTMLSelectElement} */ (ev.currentTarget);\n const prev = current.status || 'open';\n const next = sel.value;\n if (next === prev) {\n return;\n }\n pending = true;\n current.status = next;\n doRender();\n try {\n log('update status %s \u2192 %s', String(current.id), next);\n const updated = await sendFn('update-status', {\n id: current.id,\n status: next\n });\n if (updated && typeof updated === 'object') {\n current = /** @type {IssueDetail} */ (updated);\n doRender();\n }\n } catch (err) {\n log('update status failed %s %o', String(current.id), err);\n current.status = prev;\n doRender();\n showToast('Failed to update status', 'error');\n } finally {\n pending = false;\n }\n };\n /**\n * @param {Event} ev\n */\n const onPriorityChange = async (ev) => {\n if (!current || pending) {\n doRender();\n return;\n }\n const sel = /** @type {HTMLSelectElement} */ (ev.currentTarget);\n const prev = typeof current.priority === 'number' ? current.priority : 2;\n const next = Number(sel.value);\n if (next === prev) {\n return;\n }\n pending = true;\n current.priority = next;\n doRender();\n try {\n log('update priority %s \u2192 %d', String(current.id), next);\n const updated = await sendFn('update-priority', {\n id: current.id,\n priority: next\n });\n if (updated && typeof updated === 'object') {\n current = /** @type {IssueDetail} */ (updated);\n doRender();\n }\n } catch (err) {\n log('update priority failed %s %o', String(current.id), err);\n current.priority = prev;\n doRender();\n showToast('Failed to update priority', 'error');\n } finally {\n pending = false;\n }\n };\n\n const onDescEdit = () => {\n edit_desc = true;\n doRender();\n };\n /**\n * @param {KeyboardEvent} ev\n */\n const onDescKeydown = (ev) => {\n if (ev.key === 'Escape') {\n edit_desc = false;\n doRender();\n } else if (ev.key === 'Enter' && ev.ctrlKey) {\n const btn = /** @type {HTMLButtonElement|null} */ (\n mount_element.querySelector('#detail-root .editable-actions button')\n );\n if (btn) {\n btn.click();\n }\n }\n };\n const onDescSave = async () => {\n if (!current || pending) {\n return;\n }\n const ta = /** @type {HTMLTextAreaElement|null} */ (\n mount_element.querySelector('#detail-root textarea')\n );\n const prev = current.description || '';\n const next = ta ? ta.value : '';\n if (next === prev) {\n edit_desc = false;\n doRender();\n return;\n }\n pending = true;\n if (ta) {\n ta.disabled = true;\n }\n try {\n log('save description %s', String(current?.id || ''));\n const updated = await sendFn('edit-text', {\n id: current.id,\n field: 'description',\n value: next\n });\n if (updated && typeof updated === 'object') {\n current = /** @type {IssueDetail} */ (updated);\n edit_desc = false;\n doRender();\n }\n } catch (err) {\n log('save description failed %s %o', String(current?.id || ''), err);\n current.description = prev;\n edit_desc = false;\n doRender();\n showToast('Failed to save description', 'error');\n } finally {\n pending = false;\n }\n };\n const onDescCancel = () => {\n edit_desc = false;\n doRender();\n };\n\n // Design inline edit handlers (same UX as Description)\n const onDesignEdit = () => {\n edit_design = true;\n doRender();\n try {\n const ta = /** @type {HTMLTextAreaElement|null} */ (\n mount_element.querySelector('#detail-root .design textarea')\n );\n if (ta) {\n ta.focus();\n }\n } catch (err) {\n log('focus design textarea failed %o', err);\n }\n };\n /**\n * @param {KeyboardEvent} ev\n */\n const onDesignKeydown = (ev) => {\n if (ev.key === 'Escape') {\n edit_design = false;\n doRender();\n } else if (ev.key === 'Enter' && (ev.ctrlKey || ev.metaKey)) {\n const btn = /** @type {HTMLButtonElement|null} */ (\n mount_element.querySelector(\n '#detail-root .design .editable-actions button'\n )\n );\n if (btn) {\n btn.click();\n }\n }\n };\n const onDesignSave = async () => {\n if (!current || pending) {\n return;\n }\n const ta = /** @type {HTMLTextAreaElement|null} */ (\n mount_element.querySelector('#detail-root .design textarea')\n );\n const prev = current.design || '';\n const next = ta ? ta.value : '';\n if (next === prev) {\n edit_design = false;\n doRender();\n return;\n }\n pending = true;\n if (ta) {\n ta.disabled = true;\n }\n try {\n log('save design %s', String(current?.id || ''));\n const updated = await sendFn('edit-text', {\n id: current.id,\n field: 'design',\n value: next\n });\n if (updated && typeof updated === 'object') {\n current = /** @type {IssueDetail} */ (updated);\n edit_design = false;\n doRender();\n }\n } catch (err) {\n log('save design failed %s %o', String(current?.id || ''), err);\n current.design = prev;\n edit_design = false;\n doRender();\n showToast('Failed to save design', 'error');\n } finally {\n pending = false;\n }\n };\n const onDesignCancel = () => {\n edit_design = false;\n doRender();\n };\n\n // Notes inline edit handlers\n const onNotesEdit = () => {\n edit_notes = true;\n doRender();\n };\n /**\n * @param {KeyboardEvent} ev\n */\n const onNotesKeydown = (ev) => {\n if (ev.key === 'Escape') {\n edit_notes = false;\n doRender();\n } else if (ev.key === 'Enter' && (ev.ctrlKey || ev.metaKey)) {\n const btn = /** @type {HTMLButtonElement|null} */ (\n mount_element.querySelector(\n '#detail-root .notes .editable-actions button'\n )\n );\n if (btn) {\n btn.click();\n }\n }\n };\n const onNotesSave = async () => {\n if (!current || pending) {\n return;\n }\n const ta = /** @type {HTMLTextAreaElement|null} */ (\n mount_element.querySelector('#detail-root .notes textarea')\n );\n const prev = current.notes || '';\n const next = ta ? ta.value : '';\n if (next === prev) {\n edit_notes = false;\n doRender();\n return;\n }\n pending = true;\n if (ta) {\n ta.disabled = true;\n }\n try {\n log('save notes %s', String(current?.id || ''));\n const updated = await sendFn('edit-text', {\n id: current.id,\n field: 'notes',\n value: next\n });\n if (updated && typeof updated === 'object') {\n current = /** @type {IssueDetail} */ (updated);\n edit_notes = false;\n doRender();\n }\n } catch (err) {\n log('save notes failed %s %o', String(current?.id || ''), err);\n current.notes = prev;\n edit_notes = false;\n doRender();\n showToast('Failed to save notes', 'error');\n } finally {\n pending = false;\n }\n };\n const onNotesCancel = () => {\n edit_notes = false;\n doRender();\n };\n\n const onAcceptEdit = () => {\n edit_accept = true;\n doRender();\n };\n /**\n * @param {KeyboardEvent} ev\n */\n const onAcceptKeydown = (ev) => {\n if (ev.key === 'Escape') {\n edit_accept = false;\n doRender();\n } else if (ev.key === 'Enter' && (ev.ctrlKey || ev.metaKey)) {\n const btn = /** @type {HTMLButtonElement|null} */ (\n mount_element.querySelector(\n '#detail-root .acceptance .editable-actions button'\n )\n );\n if (btn) {\n btn.click();\n }\n }\n };\n const onAcceptSave = async () => {\n if (!current || pending) {\n return;\n }\n const ta = /** @type {HTMLTextAreaElement|null} */ (\n mount_element.querySelector('#detail-root .acceptance textarea')\n );\n const prev = current.acceptance || '';\n const next = ta ? ta.value : '';\n if (next === prev) {\n edit_accept = false;\n doRender();\n return;\n }\n pending = true;\n if (ta) {\n ta.disabled = true;\n }\n try {\n log('save acceptance %s', String(current?.id || ''));\n const updated = await sendFn('edit-text', {\n id: current.id,\n field: 'acceptance',\n value: next\n });\n if (updated && typeof updated === 'object') {\n current = /** @type {IssueDetail} */ (updated);\n edit_accept = false;\n doRender();\n }\n } catch (err) {\n log('save acceptance failed %s %o', String(current?.id || ''), err);\n current.acceptance = prev;\n edit_accept = false;\n doRender();\n showToast('Failed to save acceptance', 'error');\n } finally {\n pending = false;\n }\n };\n const onAcceptCancel = () => {\n edit_accept = false;\n doRender();\n };\n\n // Comment input handlers\n /**\n * @param {Event} ev\n */\n const onCommentInput = (ev) => {\n const el = /** @type {HTMLTextAreaElement} */ (ev.currentTarget);\n const prev_has_text = comment_text.trim().length > 0;\n comment_text = el.value || '';\n const has_text = comment_text.trim().length > 0;\n // Re-render when the \"has content\" state changes to update button disabled state\n if (prev_has_text !== has_text) {\n doRender();\n }\n };\n\n const onCommentSubmit = async () => {\n if (!current || comment_pending || !comment_text.trim()) {\n return;\n }\n comment_pending = true;\n doRender();\n try {\n log('add comment to %s', String(current.id));\n const result = await sendFn('add-comment', {\n id: current.id,\n text: comment_text.trim()\n });\n if (Array.isArray(result)) {\n // Update comments in current issue\n /** @type {any} */ (current).comments = result;\n comment_text = '';\n doRender();\n }\n } catch (err) {\n log('add comment failed %s %o', String(current.id), err);\n showToast('Failed to add comment', 'error');\n } finally {\n comment_pending = false;\n doRender();\n }\n };\n\n /**\n * @param {KeyboardEvent} ev\n */\n const onCommentKeydown = (ev) => {\n if (ev.key === 'Enter' && (ev.ctrlKey || ev.metaKey)) {\n ev.preventDefault();\n onCommentSubmit();\n }\n };\n\n /**\n * @param {'Dependencies'|'Dependents'} title\n * @param {Dependency[]} items\n */\n function depsSection(title, items) {\n const test_id =\n title === 'Dependencies' ? 'add-dependency' : 'add-dependent';\n return html`\n <div class=\"props-card\">\n <div>\n <div class=\"props-card__title\">${title}</div>\n </div>\n <ul>\n ${!items || items.length === 0\n ? null\n : items.map((dep) => {\n const did = dep.id;\n const href = issueHref(did);\n return html`<li\n data-href=${href}\n @click=${() => navigateFn(href)}\n >\n ${createTypeBadge(dep.issue_type || '')}\n <span class=\"text-truncate\">${dep.title || ''}</span>\n <button\n aria-label=${`Remove dependency ${did}`}\n @click=${makeDepRemoveClick(did, title)}\n >\n \u00D7\n </button>\n </li>`;\n })}\n </ul>\n <div class=\"props-card__footer\">\n <input type=\"text\" placeholder=\"Issue ID\" data-testid=${test_id} />\n <button @click=${makeDepAddClick(items, title)}>Add</button>\n </div>\n </div>\n `;\n }\n\n /**\n * @param {IssueDetail} issue\n */\n function detailTemplate(issue) {\n const title_zone = edit_title\n ? html`<div class=\"detail-title\">\n <h2>\n <input\n type=\"text\"\n aria-label=\"Edit title\"\n .value=${issue.title || ''}\n @keydown=${onTitleInputKeydown}\n />\n <button @click=${onTitleSave}>Save</button>\n <button @click=${onTitleCancel}>Cancel</button>\n </h2>\n </div>`\n : html`<div class=\"detail-title\">\n <h2>\n <span\n class=\"editable\"\n tabindex=\"0\"\n role=\"button\"\n aria-label=\"Edit title\"\n @click=${onTitleSpanClick}\n @keydown=${onTitleKeydown}\n >${issue.title || ''}</span\n >\n </h2>\n </div>`;\n\n const status_select = html`<select\n class=${`badge-select badge--status is-${issue.status || 'open'}`}\n @change=${onStatusChange}\n .value=${issue.status || 'open'}\n ?disabled=${pending}\n >\n ${(() => {\n const cur = String(issue.status || 'open');\n return ['open', 'in_progress', 'closed'].map(\n (s) =>\n html`<option value=${s} ?selected=${cur === s}>\n ${statusLabel(s)}\n </option>`\n );\n })()}\n </select>`;\n\n const priority_select = html`<select\n class=${`badge-select badge--priority is-p${String(\n typeof issue.priority === 'number' ? issue.priority : 2\n )}`}\n @change=${onPriorityChange}\n .value=${String(typeof issue.priority === 'number' ? issue.priority : 2)}\n ?disabled=${pending}\n >\n ${(() => {\n const cur = String(\n typeof issue.priority === 'number' ? issue.priority : 2\n );\n return priority_levels.map(\n (p, i) =>\n html`<option value=${String(i)} ?selected=${cur === String(i)}>\n ${emojiForPriority(i)} ${p}\n </option>`\n );\n })()}\n </select>`;\n\n const desc_block = edit_desc\n ? html`<div class=\"description\">\n <textarea\n @keydown=${onDescKeydown}\n .value=${issue.description || ''}\n rows=\"8\"\n style=\"width:100%\"\n ></textarea>\n <div class=\"editable-actions\">\n <button @click=${onDescSave}>Save</button>\n <button @click=${onDescCancel}>Cancel</button>\n </div>\n </div>`\n : html`<div\n class=\"md editable\"\n tabindex=\"0\"\n role=\"button\"\n aria-label=\"Edit description\"\n @click=${onDescEdit}\n @keydown=${onDescEditableKeydown}\n >\n ${(() => {\n const text = issue.description || '';\n if (text.trim() === '') {\n return html`<div class=\"muted\">Description</div>`;\n }\n return renderMarkdown(text);\n })()}\n </div>`;\n\n // Normalize acceptance text: prefer issue.acceptance, fallback to acceptance_criteria from bd\n const acceptance_text = (() => {\n /** @type {any} */\n const any_issue = issue;\n const raw = String(\n issue.acceptance || any_issue.acceptance_criteria || ''\n );\n return raw;\n })();\n\n const accept_block = edit_accept\n ? html`<div class=\"acceptance\">\n ${acceptance_text.trim().length > 0\n ? html`<div class=\"props-card__title\">Acceptance Criteria</div>`\n : ''}\n <textarea\n @keydown=${onAcceptKeydown}\n .value=${acceptance_text}\n rows=\"6\"\n style=\"width:100%\"\n ></textarea>\n <div class=\"editable-actions\">\n <button @click=${onAcceptSave}>Save</button>\n <button @click=${onAcceptCancel}>Cancel</button>\n </div>\n </div>`\n : html`<div class=\"acceptance\">\n ${(() => {\n const text = acceptance_text;\n const has = text.trim().length > 0;\n return html`${has\n ? html`<div class=\"props-card__title\">Acceptance Criteria</div>`\n : ''}\n <div\n class=\"md editable\"\n tabindex=\"0\"\n role=\"button\"\n aria-label=\"Edit acceptance criteria\"\n @click=${onAcceptEdit}\n @keydown=${onAcceptEditableKeydown}\n >\n ${has\n ? renderMarkdown(text)\n : html`<div class=\"muted\">Add acceptance criteria\u2026</div>`}\n </div>`;\n })()}\n </div>`;\n\n // Notes: editable in-place similar to Description\n const notes_text = String(issue.notes || '');\n const notes_block = edit_notes\n ? html`<div class=\"notes\">\n ${notes_text.trim().length > 0\n ? html`<div class=\"props-card__title\">Notes</div>`\n : ''}\n <textarea\n @keydown=${onNotesKeydown}\n .value=${notes_text}\n rows=\"6\"\n style=\"width:100%\"\n ></textarea>\n <div class=\"editable-actions\">\n <button @click=${onNotesSave}>Save</button>\n <button @click=${onNotesCancel}>Cancel</button>\n </div>\n </div>`\n : html`<div class=\"notes\">\n ${(() => {\n const text = notes_text;\n const has = text.trim().length > 0;\n return html`${has\n ? html`<div class=\"props-card__title\">Notes</div>`\n : ''}\n <div\n class=\"md editable\"\n tabindex=\"0\"\n role=\"button\"\n aria-label=\"Edit notes\"\n @click=${onNotesEdit}\n @keydown=${onNotesEditableKeydown}\n >\n ${has\n ? renderMarkdown(text)\n : html`<div class=\"muted\">Add notes\u2026</div>`}\n </div>`;\n })()}\n </div>`;\n\n // Labels section\n const labels = Array.isArray(issue.labels) ? issue.labels : [];\n const labels_block = html`<div class=\"props-card labels\">\n <div>\n <div class=\"props-card__title\">Labels</div>\n </div>\n <ul>\n ${labels.map(\n (l) =>\n html`<li>\n <span class=\"badge\" title=${l}\n >${l}\n <button\n class=\"icon-button\"\n title=\"Remove label\"\n aria-label=${'Remove label ' + l}\n @click=${() => onRemoveLabel(l)}\n style=\"margin-left:6px\"\n >\n \u00D7\n </button></span\n >\n </li>`\n )}\n </ul>\n <div class=\"props-card__footer\">\n <input\n type=\"text\"\n placeholder=\"Label\"\n size=\"12\"\n .value=${new_label_text}\n @input=${onLabelInput}\n @keydown=${onLabelKeydown}\n />\n <button @click=${onAddLabel}>Add</button>\n </div>\n </div>`;\n\n // Design section block\n const design_text = String(issue.design || '');\n const design_block = edit_design\n ? html`<div class=\"design\">\n ${design_text.trim().length > 0\n ? html`<div class=\"props-card__title\">Design</div>`\n : ''}\n <textarea\n @keydown=${onDesignKeydown}\n .value=${design_text}\n rows=\"6\"\n style=\"width:100%\"\n ></textarea>\n <div class=\"editable-actions\">\n <button @click=${onDesignSave}>Save</button>\n <button @click=${onDesignCancel}>Cancel</button>\n </div>\n </div>`\n : html`<div class=\"design\">\n ${(() => {\n const text = design_text;\n const has = text.trim().length > 0;\n return html`${has\n ? html`<div class=\"props-card__title\">Design</div>`\n : ''}\n <div\n class=\"md editable\"\n tabindex=\"0\"\n role=\"button\"\n aria-label=\"Edit design\"\n @click=${onDesignEdit}\n @keydown=${onDesignEditableKeydown}\n >\n ${has\n ? renderMarkdown(text)\n : html`<div class=\"muted\">Add design\u2026</div>`}\n </div>`;\n })()}\n </div>`;\n\n // Comments section\n const comments = Array.isArray(/** @type {any} */ (issue).comments)\n ? /** @type {Comment[]} */ (/** @type {any} */ (issue).comments)\n : [];\n const comments_block = html`<div class=\"comments\">\n <div class=\"props-card__title\">Comments</div>\n ${comments.length === 0\n ? html`<div class=\"muted\">No comments yet</div>`\n : comments.map(\n (c) => html`\n <div class=\"comment-item\">\n <div class=\"comment-header\">\n <span class=\"comment-author\">${c.author || 'Unknown'}</span>\n <span class=\"comment-date\"\n >${formatCommentDate(c.created_at)}</span\n >\n </div>\n <div class=\"comment-text\">${c.text}</div>\n </div>\n `\n )}\n <div class=\"comment-input\">\n <textarea\n placeholder=\"Add a comment... (Ctrl+Enter to submit)\"\n rows=\"3\"\n .value=${comment_text}\n @input=${onCommentInput}\n @keydown=${onCommentKeydown}\n ?disabled=${comment_pending}\n ></textarea>\n <button\n @click=${onCommentSubmit}\n ?disabled=${comment_pending || !comment_text.trim()}\n >\n ${comment_pending ? 'Adding...' : 'Add Comment'}\n </button>\n </div>\n </div>`;\n\n return html`\n <div class=\"panel__body\" id=\"detail-root\">\n <div class=\"detail-layout\">\n <div class=\"detail-main\">\n ${title_zone} ${desc_block} ${design_block} ${notes_block}\n ${accept_block} ${comments_block}\n </div>\n <div class=\"detail-side\">\n <div class=\"props-card\">\n <div class=\"props-card__header\">\n <div class=\"props-card__title\">Properties</div>\n <button class=\"delete-issue-btn\" title=\"Delete issue\" aria-label=\"Delete issue\" @click=${onDeleteClick}>\n <svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\">\n <polyline points=\"3 6 5 6 21 6\"></polyline>\n <path d=\"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2\"></path>\n <line x1=\"10\" y1=\"11\" x2=\"10\" y2=\"17\"></line>\n <line x1=\"14\" y1=\"11\" x2=\"14\" y2=\"17\"></line>\n </svg>\n <span class=\"tooltip\">Delete issue</span>\n </button>\n </div>\n <div class=\"prop\">\n <div class=\"label\">Type</div>\n <div class=\"value\">\n ${createTypeBadge(/** @type {any} */ (issue).issue_type)}\n </div>\n </div>\n <div class=\"prop\">\n <div class=\"label\">Status</div>\n <div class=\"value\">${status_select}</div>\n </div>\n ${\n issue.close_reason\n ? html`<div class=\"prop\">\n <div class=\"label\">Close Reason</div>\n <div class=\"value\">${issue.close_reason}</div>\n </div>`\n : ''\n }\n <div class=\"prop\">\n <div class=\"label\">Priority</div>\n <div class=\"value\">${priority_select}</div>\n </div>\n <div class=\"prop assignee\">\n <div class=\"label\">Assignee</div>\n <div class=\"value\">\n ${\n edit_assignee\n ? html`<input\n type=\"text\"\n aria-label=\"Edit assignee\"\n .value=${\n /** @type {any} */ (issue).assignee || ''\n }\n size=${Math.min(\n 40,\n Math.max(12, (issue.assignee || '').length + 3)\n )}\n @keydown=${\n /** @param {KeyboardEvent} e */ (e) => {\n if (e.key === 'Escape') {\n e.preventDefault();\n onAssigneeCancel();\n } else if (e.key === 'Enter') {\n e.preventDefault();\n onAssigneeSave();\n }\n }\n }\n />\n <button\n class=\"btn\"\n style=\"margin-left:6px\"\n @click=${onAssigneeSave}\n >\n Save\n </button>\n <button\n class=\"btn\"\n style=\"margin-left:6px\"\n @click=${onAssigneeCancel}\n >\n Cancel\n </button>`\n : html`${(() => {\n const raw = issue.assignee || '';\n const has = raw.trim().length > 0;\n const text = has ? raw : 'Unassigned';\n const cls = has ? 'editable' : 'editable muted';\n return html`<span\n class=${cls}\n tabindex=\"0\"\n role=\"button\"\n aria-label=\"Edit assignee\"\n @click=${onAssigneeSpanClick}\n @keydown=${onAssigneeKeydown}\n >${text}</span\n >`;\n })()}`\n }\n </div>\n </div>\n </div>\n ${labels_block}\n ${depsSection('Dependencies', issue.dependencies || [])}\n ${depsSection('Dependents', issue.dependents || [])}\n </div>\n </div>\n </div>\n </div>\n `;\n }\n\n function doRender() {\n if (!current) {\n renderPlaceholder(current_id ? 'Loading\u2026' : 'No issue selected');\n return;\n }\n render(detailTemplate(current), mount_element);\n }\n\n /**\n * Create a click handler for the remove button of a dependency row.\n *\n * @param {string} did\n * @param {'Dependencies'|'Dependents'} title\n * @returns {(ev: Event) => Promise<void>}\n */\n function makeDepRemoveClick(did, title) {\n return async (ev) => {\n ev.stopPropagation();\n if (!current || pending) {\n return;\n }\n pending = true;\n try {\n if (title === 'Dependencies') {\n const updated = await sendFn('dep-remove', {\n a: current.id,\n b: did,\n view_id: current.id\n });\n if (updated && typeof updated === 'object') {\n current = /** @type {IssueDetail} */ (updated);\n doRender();\n }\n } else {\n const updated = await sendFn('dep-remove', {\n a: did,\n b: current.id,\n view_id: current.id\n });\n if (updated && typeof updated === 'object') {\n current = /** @type {IssueDetail} */ (updated);\n doRender();\n }\n }\n } catch (err) {\n log('dep-remove failed %o', err);\n } finally {\n pending = false;\n }\n };\n }\n\n /**\n * Create a click handler for the Add button in a dependency section.\n *\n * @param {Dependency[]} items\n * @param {'Dependencies'|'Dependents'} title\n * @returns {(ev: Event) => Promise<void>}\n */\n function makeDepAddClick(items, title) {\n return async (ev) => {\n if (!current || pending) {\n return;\n }\n const btn = /** @type {HTMLButtonElement} */ (ev.currentTarget);\n const input = /** @type {HTMLInputElement|null} */ (\n btn.previousElementSibling\n );\n const target = input ? input.value.trim() : '';\n if (!target || target === current.id) {\n showToast('Enter a different issue id');\n return;\n }\n const set = new Set((items || []).map((d) => d.id));\n if (set.has(target)) {\n showToast('Link already exists');\n return;\n }\n pending = true;\n if (btn) {\n btn.disabled = true;\n }\n if (input) {\n input.disabled = true;\n }\n try {\n if (title === 'Dependencies') {\n const updated = await sendFn('dep-add', {\n a: current.id,\n b: target,\n view_id: current.id\n });\n if (updated && typeof updated === 'object') {\n current = /** @type {IssueDetail} */ (updated);\n doRender();\n }\n } else {\n const updated = await sendFn('dep-add', {\n a: target,\n b: current.id,\n view_id: current.id\n });\n if (updated && typeof updated === 'object') {\n current = /** @type {IssueDetail} */ (updated);\n doRender();\n }\n }\n } catch (err) {\n log('dep-add failed %o', err);\n showToast('Failed to add dependency', 'error');\n } finally {\n pending = false;\n }\n };\n }\n /**\n * @param {KeyboardEvent} ev\n */\n function onTitleInputKeydown(ev) {\n if (ev.key === 'Escape') {\n edit_title = false;\n doRender();\n } else if (ev.key === 'Enter') {\n ev.preventDefault();\n onTitleSave();\n }\n }\n\n /**\n * @param {KeyboardEvent} ev\n */\n function onDescEditableKeydown(ev) {\n if (ev.key === 'Enter') {\n onDescEdit();\n }\n }\n\n /**\n * @param {KeyboardEvent} ev\n */\n function onAcceptEditableKeydown(ev) {\n if (ev.key === 'Enter') {\n onAcceptEdit();\n }\n }\n\n /**\n * @param {KeyboardEvent} ev\n */\n function onNotesEditableKeydown(ev) {\n if (ev.key === 'Enter') {\n onNotesEdit();\n }\n }\n\n /**\n * @param {KeyboardEvent} ev\n */\n function onDesignEditableKeydown(ev) {\n if (ev.key === 'Enter') {\n onDesignEdit();\n }\n }\n\n return {\n async load(id) {\n if (!id) {\n renderPlaceholder('No issue selected');\n return;\n }\n current_id = String(id);\n // Try from store first; show placeholder while waiting for snapshot\n current = null;\n refreshFromStore();\n if (!current) {\n renderPlaceholder('Loading\u2026');\n }\n // Render from current (if available) or keep placeholder until push arrives\n pending = false;\n comment_text = '';\n comment_pending = false;\n doRender();\n\n // Fetch comments if not already present\n if (current && !(/** @type {any} */ (current).comments)) {\n try {\n const comments = await sendFn('get-comments', { id: current_id });\n if (Array.isArray(comments) && current && current_id === id) {\n /** @type {any} */ (current).comments = comments;\n doRender();\n }\n } catch (err) {\n log('fetch comments failed %s %o', id, err);\n }\n }\n },\n clear() {\n renderPlaceholder('Select an issue to view details');\n },\n destroy() {\n mount_element.replaceChildren();\n if (delete_dialog && delete_dialog.parentNode) {\n delete_dialog.parentNode.removeChild(delete_dialog);\n delete_dialog = null;\n }\n }\n };\n}\n", "import { html } from 'lit-html';\nimport { createIssueIdRenderer } from '../utils/issue-id-renderer.js';\nimport { emojiForPriority } from '../utils/priority-badge.js';\nimport { priority_levels } from '../utils/priority.js';\nimport { statusLabel } from '../utils/status.js';\nimport { createTypeBadge } from '../utils/type-badge.js';\n\n/**\n * @typedef {{ id: string, title?: string, status?: string, priority?: number, issue_type?: string, assignee?: string, dependency_count?: number, dependent_count?: number }} IssueRowData\n */\n\n/**\n * Create a reusable issue row renderer used by list and epics views.\n * Handles inline editing for title/assignee and selects for status/priority.\n *\n * @param {{\n * navigate: (id: string) => void,\n * onUpdate: (id: string, patch: { title?: string, assignee?: string, status?: 'open'|'in_progress'|'closed', priority?: number }) => Promise<void>,\n * requestRender: () => void,\n * getSelectedId?: () => string | null,\n * row_class?: string\n * }} options\n * @returns {(it: IssueRowData) => import('lit-html').TemplateResult<1>}\n */\nexport function createIssueRowRenderer(options) {\n const navigate = options.navigate;\n const on_update = options.onUpdate;\n const request_render = options.requestRender;\n const get_selected_id = options.getSelectedId || (() => null);\n const row_class = options.row_class || 'issue-row';\n\n /** @type {Set<string>} */\n const editing = new Set();\n\n /**\n * @param {string} id\n * @param {'title'|'assignee'} key\n * @param {string} value\n * @param {string} [placeholder]\n */\n function editableText(id, key, value, placeholder = '') {\n const k = `${id}:${key}`;\n const is_edit = editing.has(k);\n if (is_edit) {\n return html`<span>\n <input\n type=\"text\"\n .value=${value}\n class=\"inline-edit\"\n @keydown=${\n /** @param {KeyboardEvent} e */ async (e) => {\n if (e.key === 'Escape') {\n editing.delete(k);\n request_render();\n } else if (e.key === 'Enter') {\n const el = /** @type {HTMLInputElement} */ (e.currentTarget);\n const next = el.value || '';\n if (next !== value) {\n await on_update(id, { [key]: next });\n }\n editing.delete(k);\n request_render();\n }\n }\n }\n @blur=${\n /** @param {Event} ev */ async (ev) => {\n const el = /** @type {HTMLInputElement} */ (ev.currentTarget);\n const next = el.value || '';\n if (next !== value) {\n await on_update(id, { [key]: next });\n }\n editing.delete(k);\n request_render();\n }\n }\n autofocus\n />\n </span>`;\n }\n return html`<span\n class=\"editable text-truncate ${value ? '' : 'muted'}\"\n tabindex=\"0\"\n role=\"button\"\n @click=${\n /** @param {MouseEvent} e */ (e) => {\n e.stopPropagation();\n e.preventDefault();\n editing.add(k);\n request_render();\n }\n }\n @keydown=${\n /** @param {KeyboardEvent} e */ (e) => {\n if (e.key === 'Enter') {\n e.preventDefault();\n e.stopPropagation();\n editing.add(k);\n request_render();\n }\n }\n }\n >${value || placeholder}</span\n >`;\n }\n\n /**\n * @param {string} id\n * @param {'priority'|'status'} key\n * @returns {(ev: Event) => Promise<void>}\n */\n function makeSelectChange(id, key) {\n return async (ev) => {\n const sel = /** @type {HTMLSelectElement} */ (ev.currentTarget);\n const val = sel.value || '';\n /** @type {{ [k:string]: any }} */\n const patch = {};\n patch[key] = key === 'priority' ? Number(val) : val;\n await on_update(id, patch);\n };\n }\n\n /**\n * @param {string} id\n * @returns {(ev: Event) => void}\n */\n function makeRowClick(id) {\n return (ev) => {\n const el = /** @type {HTMLElement|null} */ (ev.target);\n if (el && (el.tagName === 'INPUT' || el.tagName === 'SELECT')) {\n return;\n }\n navigate(id);\n };\n }\n\n /**\n * @param {IssueRowData} it\n */\n function rowTemplate(it) {\n const cur_status = String(it.status || 'open');\n const cur_prio = String(it.priority ?? 2);\n const is_selected = get_selected_id() === it.id;\n return html`<tr\n role=\"row\"\n class=\"${row_class} ${is_selected ? 'selected' : ''}\"\n data-issue-id=${it.id}\n @click=${makeRowClick(it.id)}\n >\n <td role=\"gridcell\" class=\"mono\">${createIssueIdRenderer(it.id)}</td>\n <td role=\"gridcell\">${createTypeBadge(it.issue_type)}</td>\n <td role=\"gridcell\">${editableText(it.id, 'title', it.title || '')}</td>\n <td role=\"gridcell\">\n <select\n class=\"badge-select badge--status is-${cur_status}\"\n .value=${cur_status}\n @change=${makeSelectChange(it.id, 'status')}\n >\n ${['open', 'in_progress', 'closed'].map(\n (s) =>\n html`<option value=${s} ?selected=${cur_status === s}>\n ${statusLabel(s)}\n </option>`\n )}\n </select>\n </td>\n <td role=\"gridcell\">\n ${editableText(it.id, 'assignee', it.assignee || '', 'Unassigned')}\n </td>\n <td role=\"gridcell\">\n <select\n class=\"badge-select badge--priority ${'is-p' + cur_prio}\"\n .value=${cur_prio}\n @change=${makeSelectChange(it.id, 'priority')}\n >\n ${priority_levels.map(\n (p, i) =>\n html`<option\n value=${String(i)}\n ?selected=${cur_prio === String(i)}\n >\n ${emojiForPriority(i)} ${p}\n </option>`\n )}\n </select>\n </td>\n <td role=\"gridcell\" class=\"deps-col\">\n ${(it.dependency_count || 0) > 0 || (it.dependent_count || 0) > 0\n ? html`<span class=\"deps-indicator\"\n >${(it.dependency_count || 0) > 0\n ? html`<span\n class=\"dep-count\"\n title=\"${it.dependency_count} ${(it.dependency_count ||\n 0) === 1\n ? 'dependency'\n : 'dependencies'}\"\n >\u2192${it.dependency_count}</span\n >`\n : ''}${(it.dependent_count || 0) > 0\n ? html`<span\n class=\"dependent-count\"\n title=\"${it.dependent_count} ${(it.dependent_count || 0) ===\n 1\n ? 'dependent'\n : 'dependents'}\"\n >\u2190${it.dependent_count}</span\n >`\n : ''}</span\n >`\n : ''}\n </td>\n </tr>`;\n }\n\n return rowTemplate;\n}\n", "import { html, render } from 'lit-html';\nimport { createListSelectors } from '../data/list-selectors.js';\nimport { createIssueIdRenderer } from '../utils/issue-id-renderer.js';\nimport { createIssueRowRenderer } from './issue-row.js';\n\n/**\n * @typedef {{ id: string, title?: string, status?: string, priority?: number, issue_type?: string, assignee?: string, created_at?: number, updated_at?: number }} IssueLite\n */\n\n/**\n * Epics view (push-only):\n * - Derives epic groups from the local issues store (no RPC reads).\n * - Subscribes to `tab:epics` for top-level membership.\n * - On expand, subscribes to `detail:{id}` (issue-detail) for the epic.\n * - Renders children from the epic detail's `dependents` list.\n * - Provides inline edits via mutations; UI re-renders on push.\n *\n * @param {HTMLElement} mount_element\n * @param {{ updateIssue: (input: any) => Promise<any> }} data\n * @param {(id: string) => void} goto_issue - Navigate to issue detail.\n * @param {{ subscribeList: (client_id: string, spec: { type: string, params?: Record<string, string|number|boolean> }) => Promise<() => Promise<void>>, selectors: { getIds: (client_id: string) => string[], count?: (client_id: string) => number } }} [subscriptions]\n * @param {{ snapshotFor?: (client_id: string) => any[], subscribe?: (fn: () => void) => () => void }} [issue_stores]\n */\nexport function createEpicsView(\n mount_element,\n data,\n goto_issue,\n subscriptions = undefined,\n issue_stores = undefined\n) {\n /** @type {any[]} */\n let groups = [];\n /** @type {Set<string>} */\n const expanded = new Set();\n /** @type {Set<string>} */\n const loading = new Set();\n /** @type {Map<string, () => Promise<void>>} */\n const epic_unsubs = new Map();\n // Centralized selection helpers\n const selectors = issue_stores ? createListSelectors(issue_stores) : null;\n // Live re-render on pushes: recompute groups when stores change\n if (selectors) {\n selectors.subscribe(() => {\n const had_none = groups.length === 0;\n groups = buildGroupsFromSnapshot();\n doRender();\n // Auto-expand first epic when transitioning from empty to non-empty\n if (had_none && groups.length > 0) {\n const first_id = String(groups[0].epic?.id || '');\n if (first_id && !expanded.has(first_id)) {\n void toggle(first_id);\n }\n }\n });\n }\n\n // Shared row renderer used for children rows\n const renderRow = createIssueRowRenderer({\n navigate: (id) => goto_issue(id),\n onUpdate: updateInline,\n requestRender: doRender,\n getSelectedId: () => null,\n row_class: 'epic-row'\n });\n\n function doRender() {\n render(template(), mount_element);\n }\n\n function template() {\n if (!groups.length) {\n return html`<div class=\"panel__header muted\">No epics found.</div>`;\n }\n return html`${groups.map((g) => groupTemplate(g))}`;\n }\n\n /**\n * @param {any} g\n */\n function groupTemplate(g) {\n const epic = g.epic || {};\n const id = String(epic.id || '');\n const is_open = expanded.has(id);\n // Compose children via selectors\n const list = selectors ? selectors.selectEpicChildren(id) : [];\n const is_loading = loading.has(id);\n return html`\n <div class=\"epic-group\" data-epic-id=${id}>\n <div\n class=\"epic-header\"\n @click=${() => toggle(id)}\n role=\"button\"\n tabindex=\"0\"\n aria-expanded=${is_open}\n >\n ${createIssueIdRenderer(id, { class_name: 'mono' })}\n <span class=\"text-truncate\" style=\"margin-left:8px\"\n >${epic.title || '(no title)'}</span\n >\n <span\n class=\"epic-progress\"\n style=\"margin-left:auto; display:flex; align-items:center; gap:8px;\"\n >\n <progress\n value=${Number(g.closed_children || 0)}\n max=${Math.max(1, Number(g.total_children || 0))}\n ></progress>\n <span class=\"muted mono\"\n >${g.closed_children}/${g.total_children}</span\n >\n </span>\n </div>\n ${is_open\n ? html`<div class=\"epic-children\">\n ${is_loading\n ? html`<div class=\"muted\">Loading\u2026</div>`\n : list.length === 0\n ? html`<div class=\"muted\">No issues found</div>`\n : html`<table class=\"table\">\n <colgroup>\n <col style=\"width: 100px\" />\n <col style=\"width: 120px\" />\n <col />\n <col style=\"width: 120px\" />\n <col style=\"width: 160px\" />\n <col style=\"width: 130px\" />\n </colgroup>\n <thead>\n <tr>\n <th>ID</th>\n <th>Type</th>\n <th>Title</th>\n <th>Status</th>\n <th>Assignee</th>\n <th>Priority</th>\n </tr>\n </thead>\n <tbody>\n ${list.map((it) => renderRow(it))}\n </tbody>\n </table>`}\n </div>`\n : null}\n </div>\n `;\n }\n\n /**\n * @param {string} id\n * @param {{ [k: string]: any }} patch\n */\n async function updateInline(id, patch) {\n try {\n await data.updateIssue({ id, ...patch });\n // Re-render; view will update on subsequent push\n doRender();\n } catch {\n // swallow; UI remains\n }\n }\n\n /**\n * @param {string} epic_id\n */\n async function toggle(epic_id) {\n if (!expanded.has(epic_id)) {\n expanded.add(epic_id);\n loading.add(epic_id);\n doRender();\n // Subscribe to epic detail; children are rendered from `dependents`\n if (subscriptions && typeof subscriptions.subscribeList === 'function') {\n try {\n // Register store first to avoid dropping the initial snapshot\n try {\n if (issue_stores && /** @type {any} */ (issue_stores).register) {\n /** @type {any} */ (issue_stores).register(`detail:${epic_id}`, {\n type: 'issue-detail',\n params: { id: epic_id }\n });\n }\n } catch {\n // ignore\n }\n const u = await subscriptions.subscribeList(`detail:${epic_id}`, {\n type: 'issue-detail',\n params: { id: epic_id }\n });\n epic_unsubs.set(epic_id, u);\n } catch {\n // ignore subscription failures\n }\n }\n // Mark as not loading after subscribe attempt; membership will stream in\n loading.delete(epic_id);\n } else {\n expanded.delete(epic_id);\n // Unsubscribe when collapsing\n if (epic_unsubs.has(epic_id)) {\n try {\n const u = epic_unsubs.get(epic_id);\n if (u) {\n await u();\n }\n } catch {\n // ignore\n }\n epic_unsubs.delete(epic_id);\n try {\n if (issue_stores && /** @type {any} */ (issue_stores).unregister) {\n /** @type {any} */ (issue_stores).unregister(`detail:${epic_id}`);\n }\n } catch {\n // ignore\n }\n }\n }\n doRender();\n }\n\n /** Build groups from the current `tab:epics` snapshot. */\n function buildGroupsFromSnapshot() {\n /** @type {IssueLite[]} */\n const epic_entities =\n issue_stores && issue_stores.snapshotFor\n ? /** @type {IssueLite[]} */ (\n issue_stores.snapshotFor('tab:epics') || []\n )\n : [];\n const next_groups = [];\n for (const epic of epic_entities) {\n const dependents = Array.isArray(/** @type {any} */ (epic).dependents)\n ? /** @type {any[]} */ (/** @type {any} */ (epic).dependents)\n : [];\n // Prefer explicit counters when provided by server; otherwise derive\n const has_total = Number.isFinite(\n /** @type {any} */ (epic).total_children\n );\n const has_closed = Number.isFinite(\n /** @type {any} */ (epic).closed_children\n );\n const total = has_total\n ? Number(/** @type {any} */ (epic).total_children) || 0\n : dependents.length;\n let closed = has_closed\n ? Number(/** @type {any} */ (epic).closed_children) || 0\n : 0;\n if (!has_closed) {\n for (const d of dependents) {\n if (String(d.status || '') === 'closed') {\n closed++;\n }\n }\n }\n next_groups.push({\n epic,\n total_children: total,\n closed_children: closed\n });\n }\n return next_groups;\n }\n\n return {\n async load() {\n groups = buildGroupsFromSnapshot();\n doRender();\n // Auto-expand first epic on screen\n try {\n if (groups.length > 0) {\n const first_id = String(groups[0].epic?.id || '');\n if (first_id && !expanded.has(first_id)) {\n // This will render and load children lazily\n await toggle(first_id);\n }\n }\n } catch {\n // ignore auto-expand failures\n }\n }\n };\n}\n", "/**\n * Create and manage a fatal error dialog that surfaces stderr output from\n * backend failures (e.g., bd command errors).\n *\n * @param {HTMLElement} mount_element\n * @returns {{ open: (title: string, message: string, detail?: string) => void, close: () => void, getElement: () => HTMLDialogElement }}\n */\nexport function createFatalErrorDialog(mount_element) {\n const dialog = document.createElement('dialog');\n dialog.id = 'fatal-error-dialog';\n dialog.setAttribute('role', 'alertdialog');\n dialog.setAttribute('aria-modal', 'true');\n dialog.innerHTML = `\n <div class=\"fatal-error\">\n <div class=\"fatal-error__icon\" aria-hidden=\"true\">!</div>\n <div class=\"fatal-error__body\">\n <p class=\"fatal-error__eyebrow\">Critical</p>\n <h2 class=\"fatal-error__title\" id=\"fatal-error-title\">Command failed</h2>\n <p class=\"fatal-error__message\" id=\"fatal-error-message\"></p>\n <pre class=\"fatal-error__detail\" id=\"fatal-error-detail\"></pre>\n <div class=\"fatal-error__actions\">\n <button type=\"button\" class=\"btn primary\" id=\"fatal-error-reload\">Reload</button>\n <button type=\"button\" class=\"btn\" id=\"fatal-error-close\">Dismiss</button>\n </div>\n </div>\n </div>`;\n mount_element.appendChild(dialog);\n\n const title_el = dialog.querySelector('#fatal-error-title');\n const message_el = dialog.querySelector('#fatal-error-message');\n const detail_el = dialog.querySelector('#fatal-error-detail');\n const reload_btn = dialog.querySelector('#fatal-error-reload');\n const close_btn = dialog.querySelector('#fatal-error-close');\n\n const close = () => {\n if (typeof dialog.close === 'function') {\n try {\n dialog.close();\n } catch {\n // ignore close errors\n }\n }\n dialog.removeAttribute('open');\n };\n\n /**\n * @param {string} title\n * @param {string} message\n * @param {string} [detail]\n */\n const open = (title, message, detail = '') => {\n if (title_el) {\n title_el.textContent = title || 'Unexpected Error';\n }\n if (message_el) {\n message_el.textContent = message || 'An unrecoverable error occurred.';\n }\n\n const detail_text = typeof detail === 'string' ? detail.trim() : '';\n if (detail_el) {\n if (detail_text.length > 0) {\n detail_el.textContent = detail_text;\n detail_el.removeAttribute('hidden');\n } else {\n detail_el.textContent = 'No additional diagnostics available.';\n detail_el.setAttribute('hidden', '');\n }\n }\n\n if (typeof dialog.showModal === 'function') {\n try {\n dialog.showModal();\n dialog.setAttribute('open', '');\n } catch {\n dialog.setAttribute('open', '');\n }\n } else {\n dialog.setAttribute('open', '');\n }\n };\n\n if (reload_btn) {\n reload_btn.addEventListener('click', () => {\n window.location.reload();\n });\n }\n\n if (close_btn) {\n close_btn.addEventListener('click', () => close());\n }\n\n dialog.addEventListener('cancel', (ev) => {\n ev.preventDefault();\n close();\n });\n\n return {\n open,\n close,\n getElement() {\n return dialog;\n }\n };\n}\n", "// Lightweight wrapper around the native <dialog> for issue details\nimport { createIssueIdRenderer } from '../utils/issue-id-renderer.js';\n\n// Provides: open(id), close(), getMount()\n// Ensures accessibility, backdrop click to close, and Esc handling.\n\n/**\n * @typedef {{ getState: () => { selected_id: string|null } }} Store\n */\n\n/**\n * Create and manage the Issue Details dialog.\n *\n * @param {HTMLElement} mount_element - Container to attach the <dialog> to (e.g., #detail-panel)\n * @param {Store} store - Read-only access to app state\n * @param {() => void} onClose - Called when dialog requests close (backdrop/esc/button)\n * @returns {{ open: (id: string) => void, close: () => void, getMount: () => HTMLElement }}\n */\nexport function createIssueDialog(mount_element, store, onClose) {\n const dialog = document.createElement('dialog');\n dialog.id = 'issue-dialog';\n dialog.setAttribute('role', 'dialog');\n dialog.setAttribute('aria-modal', 'true');\n\n // Shell: header (id + close) + body mount\n dialog.innerHTML = `\n <div class=\"issue-dialog__container\" part=\"container\">\n <header class=\"issue-dialog__header\">\n <div class=\"issue-dialog__title\">\n <span class=\"mono\" id=\"issue-dialog-title\"></span>\n </div>\n <button type=\"button\" class=\"issue-dialog__close\" aria-label=\"Close\">\u00D7</button>\n </header>\n <div class=\"issue-dialog__body\" id=\"issue-dialog-body\"></div>\n </div>\n `;\n\n mount_element.appendChild(dialog);\n\n const body_mount = /** @type {HTMLElement} */ (\n dialog.querySelector('#issue-dialog-body')\n );\n const title_el = /** @type {HTMLElement} */ (\n dialog.querySelector('#issue-dialog-title')\n );\n const btn_close = /** @type {HTMLButtonElement} */ (\n dialog.querySelector('.issue-dialog__close')\n );\n\n /**\n * @param {string} id\n */\n function setTitle(id) {\n // Use copyable ID renderer but keep visible text as raw id for tests/clarity\n title_el.replaceChildren();\n title_el.appendChild(createIssueIdRenderer(id));\n }\n\n // Backdrop click: when clicking the dialog itself (outside container), close\n dialog.addEventListener('mousedown', (ev) => {\n if (ev.target === dialog) {\n ev.preventDefault();\n requestClose();\n }\n });\n // Esc key produces a cancel event on <dialog>\n dialog.addEventListener('cancel', (ev) => {\n ev.preventDefault();\n requestClose();\n });\n // Close button\n btn_close.addEventListener('click', () => requestClose());\n\n /** @type {HTMLElement | null} */\n let last_focus = null;\n\n function requestClose() {\n try {\n if (typeof dialog.close === 'function') {\n dialog.close();\n } else {\n dialog.removeAttribute('open');\n }\n } catch {\n dialog.removeAttribute('open');\n }\n try {\n onClose();\n } catch {\n // ignore consumer errors\n }\n // Restore focus to the element that had focus before opening\n restoreFocus();\n }\n\n /**\n * @param {string} id\n */\n function open(id) {\n // Capture currently focused element to restore after closing\n try {\n const ae = document.activeElement;\n if (ae && ae instanceof HTMLElement) {\n last_focus = ae;\n } else {\n last_focus = null;\n }\n } catch {\n last_focus = null;\n }\n setTitle(id);\n try {\n if ('showModal' in dialog && typeof dialog.showModal === 'function') {\n dialog.showModal();\n } else {\n dialog.setAttribute('open', '');\n }\n // Focus the dialog container for keyboard users\n setTimeout(() => {\n try {\n btn_close.focus();\n } catch {\n // ignore\n }\n }, 0);\n } catch {\n // Fallback for environments without <dialog>\n dialog.setAttribute('open', '');\n }\n }\n\n function close() {\n try {\n if (typeof dialog.close === 'function') {\n dialog.close();\n } else {\n dialog.removeAttribute('open');\n }\n } catch {\n dialog.removeAttribute('open');\n }\n restoreFocus();\n }\n\n function restoreFocus() {\n try {\n if (last_focus && document.contains(last_focus)) {\n last_focus.focus();\n }\n } catch {\n // ignore focus errors\n } finally {\n last_focus = null;\n }\n }\n\n return {\n open,\n close,\n getMount() {\n return body_mount;\n }\n };\n}\n", "/**\n * Known issue types in canonical order for dropdowns.\n *\n * @type {Array<'bug'|'feature'|'task'|'epic'|'chore'>}\n */\nexport const ISSUE_TYPES = ['bug', 'feature', 'task', 'epic', 'chore'];\n\n/**\n * Return a human-friendly label for an issue type.\n *\n * @param {string | null | undefined} type\n * @returns {string}\n */\nexport function typeLabel(type) {\n switch ((type || '').toString().toLowerCase()) {\n case 'bug':\n return 'Bug';\n case 'feature':\n return 'Feature';\n case 'task':\n return 'Task';\n case 'epic':\n return 'Epic';\n case 'chore':\n return 'Chore';\n default:\n return '';\n }\n}\n", "import { html, render } from 'lit-html';\nimport { createListSelectors } from '../data/list-selectors.js';\nimport { cmpClosedDesc } from '../data/sort.js';\nimport { ISSUE_TYPES, typeLabel } from '../utils/issue-type.js';\nimport { issueHashFor } from '../utils/issue-url.js';\nimport { debug } from '../utils/logging.js';\nimport { statusLabel } from '../utils/status.js';\nimport { createIssueRowRenderer } from './issue-row.js';\n\n// List view implementation; requires a transport send function.\n\n/**\n * @typedef {{ id: string, title?: string, status?: 'closed'|'open'|'in_progress', priority?: number, issue_type?: string, assignee?: string, labels?: string[] }} Issue\n */\n\n/**\n * Create the Issues List view.\n *\n * @param {HTMLElement} mount_element - Element to render into.\n * @param {(type: string, payload?: unknown) => Promise<unknown>} sendFn - RPC transport.\n * @param {(hash: string) => void} [navigate_fn] - Navigation function (defaults to setting location.hash).\n * @param {{ getState: () => any, setState: (patch: any) => void, subscribe: (fn: (s:any)=>void)=>()=>void }} [store] - Optional state store.\n * @param {{ selectors: { getIds: (client_id: string) => string[] } }} [_subscriptions]\n * @param {{ snapshotFor?: (client_id: string) => any[], subscribe?: (fn: () => void) => () => void }} [issueStores]\n * @returns {{ load: () => Promise<void>, destroy: () => void }} View API.\n */\n/**\n * Create the Issues List view.\n *\n * @param {HTMLElement} mount_element\n * @param {(type: string, payload?: unknown) => Promise<unknown>} sendFn\n * @param {(hash: string) => void} [navigateFn]\n * @param {{ getState: () => any, setState: (patch: any) => void, subscribe: (fn: (s:any)=>void)=>()=>void }} [store]\n * @param {{ selectors: { getIds: (client_id: string) => string[] } }} [_subscriptions]\n * @param {{ snapshotFor?: (client_id: string) => any[], subscribe?: (fn: () => void) => () => void }} [issue_stores]\n * @returns {{ load: () => Promise<void>, destroy: () => void }}\n */\nexport function createListView(\n mount_element,\n sendFn,\n navigateFn,\n store,\n _subscriptions = undefined,\n issue_stores = undefined\n) {\n const log = debug('views:list');\n // Touch unused param to satisfy lint rules without impacting behavior\n /** @type {any} */ (void _subscriptions);\n /** @type {string[]} */\n let status_filters = [];\n /** @type {string} */\n let search_text = '';\n /** @type {Issue[]} */\n let issues_cache = [];\n /** @type {string[]} */\n let type_filters = [];\n /** @type {string | null} */\n let selected_id = store ? store.getState().selected_id : null;\n /** @type {null | (() => void)} */\n let unsubscribe = null;\n let status_dropdown_open = false;\n let type_dropdown_open = false;\n\n /**\n * Normalize legacy string filter to array format.\n *\n * @param {string | string[] | undefined} val\n * @returns {string[]}\n */\n function normalizeStatusFilter(val) {\n if (Array.isArray(val)) return val;\n if (typeof val === 'string' && val !== '' && val !== 'all') return [val];\n return [];\n }\n\n /**\n * Normalize legacy string filter to array format.\n *\n * @param {string | string[] | undefined} val\n * @returns {string[]}\n */\n function normalizeTypeFilter(val) {\n if (Array.isArray(val)) return val;\n if (typeof val === 'string' && val !== '') return [val];\n return [];\n }\n\n // Shared row renderer (used in template below)\n const row_renderer = createIssueRowRenderer({\n navigate: (id) => {\n const nav = navigateFn || ((h) => (window.location.hash = h));\n /** @type {'issues'|'epics'|'board'} */\n const view = store ? store.getState().view : 'issues';\n nav(issueHashFor(view, id));\n },\n onUpdate: updateInline,\n requestRender: doRender,\n getSelectedId: () => selected_id,\n row_class: 'issue-row'\n });\n\n /**\n * Toggle a status filter chip.\n *\n * @param {string} status\n */\n const toggleStatusFilter = async (status) => {\n if (status_filters.includes(status)) {\n status_filters = status_filters.filter((s) => s !== status);\n } else {\n status_filters = [...status_filters, status];\n }\n log('status toggle %s -> %o', status, status_filters);\n if (store) {\n store.setState({ filters: { status: status_filters } });\n }\n await load();\n };\n\n /**\n * Event: search input.\n */\n /**\n * @param {Event} ev\n */\n const onSearchInput = (ev) => {\n const input = /** @type {HTMLInputElement} */ (ev.currentTarget);\n search_text = input.value;\n log('search input %s', search_text);\n if (store) {\n store.setState({ filters: { search: search_text } });\n }\n doRender();\n };\n\n /**\n * Toggle a type filter chip.\n *\n * @param {string} type\n */\n const toggleTypeFilter = (type) => {\n if (type_filters.includes(type)) {\n type_filters = type_filters.filter((t) => t !== type);\n } else {\n type_filters = [...type_filters, type];\n }\n log('type toggle %s -> %o', type, type_filters);\n if (store) {\n store.setState({ filters: { type: type_filters } });\n }\n doRender();\n };\n\n /**\n * Toggle status dropdown open/closed.\n *\n * @param {Event} e\n */\n const toggleStatusDropdown = (e) => {\n e.stopPropagation();\n status_dropdown_open = !status_dropdown_open;\n type_dropdown_open = false;\n doRender();\n };\n\n /**\n * Toggle type dropdown open/closed.\n *\n * @param {Event} e\n */\n const toggleTypeDropdown = (e) => {\n e.stopPropagation();\n type_dropdown_open = !type_dropdown_open;\n status_dropdown_open = false;\n doRender();\n };\n\n /**\n * Get display text for dropdown trigger.\n *\n * @param {string[]} selected\n * @param {string} label\n * @param {(val: string) => string} formatter\n * @returns {string}\n */\n function getDropdownDisplayText(selected, label, formatter) {\n if (selected.length === 0) return `${label}: Any`;\n if (selected.length === 1) return `${label}: ${formatter(selected[0])}`;\n return `${label} (${selected.length})`;\n }\n\n // Initialize filters from store on first render so reload applies persisted state\n if (store) {\n const s = store.getState();\n if (s && s.filters && typeof s.filters === 'object') {\n status_filters = normalizeStatusFilter(s.filters.status);\n search_text = s.filters.search || '';\n type_filters = normalizeTypeFilter(s.filters.type);\n }\n }\n // Initial values are reflected via bound `.value` in the template\n // Compose helpers: centralize membership + entity selection + sorting\n const selectors = issue_stores ? createListSelectors(issue_stores) : null;\n\n /**\n * Build lit-html template for the list view.\n */\n function template() {\n let filtered = issues_cache;\n if (status_filters.length > 0 && !status_filters.includes('ready')) {\n filtered = filtered.filter((it) =>\n status_filters.includes(String(it.status || ''))\n );\n }\n if (search_text) {\n const needle = search_text.toLowerCase();\n filtered = filtered.filter((it) => {\n const a = String(it.id).toLowerCase();\n const b = String(it.title || '').toLowerCase();\n return a.includes(needle) || b.includes(needle);\n });\n }\n if (type_filters.length > 0) {\n filtered = filtered.filter((it) =>\n type_filters.includes(String(it.issue_type || ''))\n );\n }\n // Sorting: closed list is a special case \u2192 sort by closed_at desc only\n if (status_filters.length === 1 && status_filters[0] === 'closed') {\n filtered = filtered.slice().sort(cmpClosedDesc);\n }\n\n return html`\n <div class=\"panel__header\">\n <div class=\"filter-dropdown ${status_dropdown_open ? 'is-open' : ''}\">\n <button\n class=\"filter-dropdown__trigger\"\n @click=${toggleStatusDropdown}\n >\n ${getDropdownDisplayText(status_filters, 'Status', statusLabel)}\n <span class=\"filter-dropdown__arrow\">\u25BE</span>\n </button>\n <div class=\"filter-dropdown__menu\">\n ${['ready', 'open', 'in_progress', 'closed'].map(\n (s) => html`\n <label class=\"filter-dropdown__option\">\n <input\n type=\"checkbox\"\n .checked=${status_filters.includes(s)}\n @change=${() => toggleStatusFilter(s)}\n />\n ${s === 'ready' ? 'Ready' : statusLabel(s)}\n </label>\n `\n )}\n </div>\n </div>\n <div class=\"filter-dropdown ${type_dropdown_open ? 'is-open' : ''}\">\n <button class=\"filter-dropdown__trigger\" @click=${toggleTypeDropdown}>\n ${getDropdownDisplayText(type_filters, 'Types', typeLabel)}\n <span class=\"filter-dropdown__arrow\">\u25BE</span>\n </button>\n <div class=\"filter-dropdown__menu\">\n ${ISSUE_TYPES.map(\n (t) => html`\n <label class=\"filter-dropdown__option\">\n <input\n type=\"checkbox\"\n .checked=${type_filters.includes(t)}\n @change=${() => toggleTypeFilter(t)}\n />\n ${typeLabel(t)}\n </label>\n `\n )}\n </div>\n </div>\n <input\n type=\"search\"\n placeholder=\"Search\u2026\"\n @input=${onSearchInput}\n .value=${search_text}\n />\n </div>\n <div class=\"panel__body\" id=\"list-root\">\n ${filtered.length === 0\n ? html`<div class=\"issues-block\">\n <div class=\"muted\" style=\"padding:10px 12px;\">No issues</div>\n </div>`\n : html`<div class=\"issues-block\">\n <table\n class=\"table\"\n role=\"grid\"\n aria-rowcount=${String(filtered.length)}\n aria-colcount=\"6\"\n >\n <colgroup>\n <col style=\"width: 100px\" />\n <col style=\"width: 120px\" />\n <col />\n <col style=\"width: 120px\" />\n <col style=\"width: 160px\" />\n <col style=\"width: 130px\" />\n <col style=\"width: 80px\" />\n </colgroup>\n <thead>\n <tr role=\"row\">\n <th role=\"columnheader\">ID</th>\n <th role=\"columnheader\">Type</th>\n <th role=\"columnheader\">Title</th>\n <th role=\"columnheader\">Status</th>\n <th role=\"columnheader\">Assignee</th>\n <th role=\"columnheader\">Priority</th>\n <th role=\"columnheader\">Deps</th>\n </tr>\n </thead>\n <tbody role=\"rowgroup\">\n ${filtered.map((it) => row_renderer(it))}\n </tbody>\n </table>\n </div>`}\n </div>\n `;\n }\n\n /**\n * Render the current issues_cache with filters applied.\n */\n function doRender() {\n render(template(), mount_element);\n }\n\n // Initial render (header + body shell with current state)\n doRender();\n // no separate ready checkbox when using select option\n\n /**\n * Update minimal fields inline via ws mutations and refresh that row's data.\n *\n * @param {string} id\n * @param {{ [k: string]: any }} patch\n */\n async function updateInline(id, patch) {\n try {\n log('updateInline %s %o', id, Object.keys(patch));\n // Dispatch specific mutations based on provided keys\n if (typeof patch.title === 'string') {\n await sendFn('edit-text', { id, field: 'title', value: patch.title });\n }\n if (typeof patch.assignee === 'string') {\n await sendFn('update-assignee', { id, assignee: patch.assignee });\n }\n if (typeof patch.status === 'string') {\n await sendFn('update-status', { id, status: patch.status });\n }\n if (typeof patch.priority === 'number') {\n await sendFn('update-priority', { id, priority: patch.priority });\n }\n } catch {\n // ignore failures; UI state remains as-is\n }\n }\n\n /**\n * Load issues from local push stores and re-render.\n */\n async function load() {\n log('load');\n // Preserve scroll position to avoid jarring jumps on live refresh\n const beforeEl = /** @type {HTMLElement|null} */ (\n mount_element.querySelector('#list-root')\n );\n const prevScroll = beforeEl ? beforeEl.scrollTop : 0;\n // Compose items from subscriptions membership and issues store entities\n try {\n if (selectors) {\n issues_cache = /** @type {Issue[]} */ (\n selectors.selectIssuesFor('tab:issues')\n );\n } else {\n issues_cache = [];\n }\n } catch (err) {\n log('load failed: %o', err);\n issues_cache = [];\n }\n doRender();\n // Restore scroll position if possible\n try {\n const afterEl = /** @type {HTMLElement|null} */ (\n mount_element.querySelector('#list-root')\n );\n if (afterEl && prevScroll > 0) {\n afterEl.scrollTop = prevScroll;\n }\n } catch {\n // ignore\n }\n }\n\n // Keyboard navigation\n mount_element.tabIndex = 0;\n mount_element.addEventListener('keydown', (ev) => {\n // Grid cell Up/Down navigation when focus is inside the table and not within\n // an editable control (input/textarea/select). Preserves column position.\n if (ev.key === 'ArrowDown' || ev.key === 'ArrowUp') {\n const tgt = /** @type {HTMLElement} */ (ev.target);\n const table =\n tgt && typeof tgt.closest === 'function'\n ? tgt.closest('#list-root table.table')\n : null;\n if (table) {\n // Do not intercept when inside native editable controls\n const in_editable = Boolean(\n tgt &&\n typeof tgt.closest === 'function' &&\n (tgt.closest('input') ||\n tgt.closest('textarea') ||\n tgt.closest('select'))\n );\n if (!in_editable) {\n const cell =\n tgt && typeof tgt.closest === 'function' ? tgt.closest('td') : null;\n if (cell && cell.parentElement) {\n const row = /** @type {HTMLTableRowElement} */ (cell.parentElement);\n const tbody = /** @type {HTMLTableSectionElement|null} */ (\n row.parentElement\n );\n if (tbody && tbody.querySelectorAll) {\n const rows = Array.from(tbody.querySelectorAll('tr'));\n const row_idx = Math.max(0, rows.indexOf(row));\n const col_idx = cell.cellIndex || 0;\n const next_idx =\n ev.key === 'ArrowDown'\n ? Math.min(row_idx + 1, rows.length - 1)\n : Math.max(row_idx - 1, 0);\n const next_row = rows[next_idx];\n const next_cell =\n next_row && next_row.cells ? next_row.cells[col_idx] : null;\n if (next_cell) {\n const focusable = /** @type {HTMLElement|null} */ (\n next_cell.querySelector(\n 'button:not([disabled]), [tabindex]:not([tabindex=\"-1\"]), a[href], select:not([disabled]), input:not([disabled]):not([type=\"hidden\"]), textarea:not([disabled])'\n )\n );\n if (focusable && typeof focusable.focus === 'function') {\n ev.preventDefault();\n focusable.focus();\n return;\n }\n }\n }\n }\n }\n }\n }\n\n const tbody = /** @type {HTMLTableSectionElement|null} */ (\n mount_element.querySelector('#list-root tbody')\n );\n const items = tbody ? tbody.querySelectorAll('tr') : [];\n if (items.length === 0) {\n return;\n }\n let idx = 0;\n if (selected_id) {\n const arr = Array.from(items);\n idx = arr.findIndex((el) => {\n const did = el.getAttribute('data-issue-id') || '';\n return did === selected_id;\n });\n if (idx < 0) {\n idx = 0;\n }\n }\n if (ev.key === 'ArrowDown') {\n ev.preventDefault();\n const next = items[Math.min(idx + 1, items.length - 1)];\n const next_id = next ? next.getAttribute('data-issue-id') : '';\n const set = next_id ? next_id : null;\n if (store && set) {\n store.setState({ selected_id: set });\n }\n selected_id = set;\n doRender();\n } else if (ev.key === 'ArrowUp') {\n ev.preventDefault();\n const prev = items[Math.max(idx - 1, 0)];\n const prev_id = prev ? prev.getAttribute('data-issue-id') : '';\n const set = prev_id ? prev_id : null;\n if (store && set) {\n store.setState({ selected_id: set });\n }\n selected_id = set;\n doRender();\n } else if (ev.key === 'Enter') {\n ev.preventDefault();\n const current = items[idx];\n const id = current ? current.getAttribute('data-issue-id') : '';\n if (id) {\n const nav = navigateFn || ((h) => (window.location.hash = h));\n /** @type {'issues'|'epics'|'board'} */\n const view = store ? store.getState().view : 'issues';\n nav(issueHashFor(view, id));\n }\n }\n });\n\n // Click outside to close dropdowns\n /** @param {MouseEvent} e */\n const clickOutsideHandler = (e) => {\n const target = /** @type {HTMLElement|null} */ (e.target);\n if (target && !target.closest('.filter-dropdown')) {\n if (status_dropdown_open || type_dropdown_open) {\n status_dropdown_open = false;\n type_dropdown_open = false;\n doRender();\n }\n }\n };\n document.addEventListener('click', clickOutsideHandler);\n\n // Keep selection in sync with store\n if (store) {\n unsubscribe = store.subscribe((s) => {\n if (s.selected_id !== selected_id) {\n selected_id = s.selected_id;\n log('selected %s', selected_id || '(none)');\n doRender();\n }\n if (s.filters && typeof s.filters === 'object') {\n const next_status = normalizeStatusFilter(s.filters.status);\n const next_search = s.filters.search || '';\n let needs_render = false;\n const status_changed =\n JSON.stringify(next_status) !== JSON.stringify(status_filters);\n if (status_changed) {\n status_filters = next_status;\n // Reload on any status scope change to keep cache correct\n void load();\n return;\n }\n if (next_search !== search_text) {\n search_text = next_search;\n needs_render = true;\n }\n const next_type_arr = normalizeTypeFilter(s.filters.type);\n const type_changed =\n JSON.stringify(next_type_arr) !== JSON.stringify(type_filters);\n if (type_changed) {\n type_filters = next_type_arr;\n needs_render = true;\n }\n if (needs_render) {\n doRender();\n }\n }\n });\n }\n\n // Live updates: recompose and re-render when issue stores change\n if (selectors) {\n selectors.subscribe(() => {\n try {\n issues_cache = /** @type {Issue[]} */ (\n selectors.selectIssuesFor('tab:issues')\n );\n doRender();\n } catch {\n // ignore\n }\n });\n }\n\n return {\n load,\n destroy() {\n mount_element.replaceChildren();\n document.removeEventListener('click', clickOutsideHandler);\n if (unsubscribe) {\n unsubscribe();\n unsubscribe = null;\n }\n }\n };\n}\n", "import { html, render } from 'lit-html';\nimport { debug } from '../utils/logging.js';\n\n/**\n * Render the top navigation with three tabs and handle route changes.\n *\n * @param {HTMLElement} mount_element\n * @param {{ getState: () => any, subscribe: (fn: (s: any) => void) => () => void }} store\n * @param {{ gotoView: (v: 'issues'|'epics'|'board') => void }} router\n */\nexport function createTopNav(mount_element, store, router) {\n const log = debug('views:nav');\n /** @type {(() => void) | null} */\n let unsubscribe = null;\n\n /**\n * @param {'issues'|'epics'|'board'} view\n * @returns {(ev: MouseEvent) => void}\n */\n function onClick(view) {\n return (ev) => {\n ev.preventDefault();\n log('click tab %s', view);\n router.gotoView(view);\n };\n }\n\n function template() {\n const s = store.getState();\n const active = s.view || 'issues';\n return html`\n <nav class=\"header-nav\" aria-label=\"Primary\">\n <a\n href=\"#/issues\"\n class=\"tab ${active === 'issues' ? 'active' : ''}\"\n @click=${onClick('issues')}\n >Issues</a\n >\n <a\n href=\"#/epics\"\n class=\"tab ${active === 'epics' ? 'active' : ''}\"\n @click=${onClick('epics')}\n >Epics</a\n >\n <a\n href=\"#/board\"\n class=\"tab ${active === 'board' ? 'active' : ''}\"\n @click=${onClick('board')}\n >Board</a\n >\n </nav>\n `;\n }\n\n function doRender() {\n render(template(), mount_element);\n }\n\n doRender();\n unsubscribe = store.subscribe(() => doRender());\n\n return {\n destroy() {\n if (unsubscribe) {\n unsubscribe();\n unsubscribe = null;\n }\n render(html``, mount_element);\n }\n };\n}\n", "import { ISSUE_TYPES, typeLabel } from '../utils/issue-type.js';\nimport { priority_levels } from '../utils/priority.js';\n\n/**\n * Create and manage the New Issue dialog (native <dialog>).\n *\n * @param {HTMLElement} mount_element - Container to attach dialog (e.g., main#app)\n * @param {(type: import('../protocol.js').MessageType, payload?: unknown) => Promise<unknown>} sendFn - Transport function\n * @param {{ gotoIssue: (id: string) => void }} router - Router for opening details after create\n * @param {{ setState: (patch: any) => void, getState: () => any }} [store]\n * @returns {{ open: () => void, close: () => void }}\n */\nexport function createNewIssueDialog(mount_element, sendFn, router, store) {\n const dialog = /** @type {HTMLDialogElement} */ (\n document.createElement('dialog')\n );\n dialog.id = 'new-issue-dialog';\n dialog.setAttribute('role', 'dialog');\n dialog.setAttribute('aria-modal', 'true');\n\n dialog.innerHTML = `\n <div class=\"new-issue__container\" part=\"container\">\n <header class=\"new-issue__header\">\n <div class=\"new-issue__title\">New Issue</div>\n <button type=\"button\" class=\"new-issue__close\" aria-label=\"Close\">\u00D7</button>\n </header>\n <div class=\"new-issue__body\">\n <form id=\"new-issue-form\" class=\"new-issue__form\">\n <label for=\"new-title\">Title</label>\n <input id=\"new-title\" name=\"title\" type=\"text\" required placeholder=\"Short summary\" />\n\n <label for=\"new-type\">Type</label>\n <select id=\"new-type\" name=\"type\" aria-label=\"Issue type\"></select>\n\n <label for=\"new-priority\">Priority</label>\n <select id=\"new-priority\" name=\"priority\" aria-label=\"Priority\"></select>\n\n <label for=\"new-labels\">Labels</label>\n <input id=\"new-labels\" name=\"labels\" type=\"text\" placeholder=\"comma,separated\" />\n\n <label for=\"new-description\">Description</label>\n <textarea id=\"new-description\" name=\"description\" rows=\"6\" placeholder=\"Optional markdown description\"></textarea>\n\n <div aria-live=\"polite\" role=\"status\" class=\"new-issue__error\" id=\"new-issue-error\"></div>\n\n <div class=\"new-issue__actions\" style=\"grid-column: 1 / -1\">\n <button type=\"button\" id=\"btn-cancel\">Cancel (Esc)</button>\n <button type=\"submit\" id=\"btn-create\">Create</button>\n </div>\n </form>\n </div>\n </div>\n `;\n\n mount_element.appendChild(dialog);\n\n const form = /** @type {HTMLFormElement} */ (\n dialog.querySelector('#new-issue-form')\n );\n const input_title = /** @type {HTMLInputElement} */ (\n dialog.querySelector('#new-title')\n );\n const sel_type = /** @type {HTMLSelectElement} */ (\n dialog.querySelector('#new-type')\n );\n const sel_priority = /** @type {HTMLSelectElement} */ (\n dialog.querySelector('#new-priority')\n );\n const input_labels = /** @type {HTMLInputElement} */ (\n dialog.querySelector('#new-labels')\n );\n const input_description = /** @type {HTMLTextAreaElement} */ (\n dialog.querySelector('#new-description')\n );\n const error_box = /** @type {HTMLDivElement} */ (\n dialog.querySelector('#new-issue-error')\n );\n const btn_cancel = /** @type {HTMLButtonElement} */ (\n dialog.querySelector('#btn-cancel')\n );\n const btn_create = /** @type {HTMLButtonElement} */ (\n dialog.querySelector('#btn-create')\n );\n const btn_close = /** @type {HTMLButtonElement} */ (\n dialog.querySelector('.new-issue__close')\n );\n\n // Populate selects\n function populateSelects() {\n sel_type.replaceChildren();\n // Empty option to allow leaving type unspecified\n const optEmpty = document.createElement('option');\n optEmpty.value = '';\n optEmpty.textContent = '\u2014 Select \u2014';\n sel_type.appendChild(optEmpty);\n for (const t of ISSUE_TYPES) {\n const o = document.createElement('option');\n o.value = t;\n o.textContent = typeLabel(t);\n sel_type.appendChild(o);\n }\n\n sel_priority.replaceChildren();\n for (let i = 0; i <= 4; i += 1) {\n const o = document.createElement('option');\n o.value = String(i);\n const label = priority_levels[i] || 'Medium';\n o.textContent = `${i} \u2013 ${label}`;\n sel_priority.appendChild(o);\n }\n }\n populateSelects();\n\n function requestClose() {\n try {\n if (typeof dialog.close === 'function') {\n dialog.close();\n } else {\n dialog.removeAttribute('open');\n }\n } catch {\n dialog.removeAttribute('open');\n }\n }\n\n /**\n * @param {boolean} is_busy\n */\n function setBusy(is_busy) {\n input_title.disabled = is_busy;\n sel_type.disabled = is_busy;\n sel_priority.disabled = is_busy;\n input_labels.disabled = is_busy;\n input_description.disabled = is_busy;\n btn_cancel.disabled = is_busy;\n btn_create.disabled = is_busy;\n btn_create.textContent = is_busy ? 'Creating\u2026' : 'Create';\n }\n\n function clearError() {\n error_box.textContent = '';\n }\n\n /**\n * @param {string} msg\n */\n function setError(msg) {\n error_box.textContent = msg;\n }\n\n function loadDefaults() {\n try {\n const t = window.localStorage.getItem('beads-ui.new.type');\n if (t) {\n sel_type.value = t;\n } else {\n sel_type.value = '';\n }\n const p = window.localStorage.getItem('beads-ui.new.priority');\n if (p && /^\\d$/.test(p)) {\n sel_priority.value = p;\n } else {\n sel_priority.value = '2';\n }\n } catch {\n sel_type.value = '';\n sel_priority.value = '2';\n }\n }\n\n function saveDefaults() {\n const t = sel_type.value || '';\n const p = sel_priority.value || '';\n if (t.length > 0) {\n window.localStorage.setItem('beads-ui.new.type', t);\n }\n if (p.length > 0) {\n window.localStorage.setItem('beads-ui.new.priority', p);\n }\n }\n\n /**\n * Extract numeric suffix from an id like \"UI-123\"; return -1 when absent.\n *\n * @param {string} id\n */\n function idNumeric(id) {\n const m = /-(\\d+)$/.exec(String(id || ''));\n return m && m[1] ? Number(m[1]) : -1;\n }\n\n /**\n * Submit handler: validate, create, then open the created issue details.\n *\n * @returns {Promise<void>}\n */\n async function createNow() {\n clearError();\n const title = String(input_title.value || '').trim();\n if (title.length === 0) {\n setError('Title is required');\n input_title.focus();\n return;\n }\n const prio = Number(sel_priority.value || '2');\n if (!(prio >= 0 && prio <= 4)) {\n setError('Priority must be 0..4');\n sel_priority.focus();\n return;\n }\n const type = String(sel_type.value || '');\n const desc = String(input_description.value || '');\n const labels = String(input_labels.value || '')\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n\n /** @type {{ title: string, type?: string, priority?: number, description?: string }} */\n const payload = { title };\n if (type.length > 0) {\n payload.type = type;\n }\n if (String(prio).length > 0) {\n payload.priority = prio;\n }\n if (desc.length > 0) {\n payload.description = desc;\n }\n\n setBusy(true);\n try {\n await sendFn('create-issue', payload);\n } catch {\n setBusy(false);\n setError('Failed to create issue');\n return;\n }\n\n saveDefaults();\n\n // Best-effort: find the created id by matching title among open issues and picking the highest numeric id\n /** @type {any} */\n let list = null;\n try {\n list = await sendFn('list-issues', {\n filters: { status: 'open', limit: 50 }\n });\n } catch {\n list = null;\n }\n let created_id = '';\n if (Array.isArray(list)) {\n const matches = list.filter((it) => String(it.title || '') === title);\n if (matches.length > 0) {\n let best = matches[0];\n for (const it of matches) {\n const ai = idNumeric(best.id || '');\n const bi = idNumeric(it.id || '');\n if (bi > ai) {\n best = it;\n }\n }\n created_id = String(best.id || '');\n }\n }\n\n // Apply labels if any\n if (created_id && labels.length > 0) {\n for (const label of labels) {\n try {\n await sendFn('label-add', { id: created_id, label });\n } catch {\n // ignore label failures\n }\n }\n }\n\n // Navigate to created issue if found\n if (created_id) {\n try {\n router.gotoIssue(created_id);\n } catch {\n // ignore routing errors\n }\n // Also set state directly to ensure dialog opens even if hash routing is suppressed in tests\n try {\n if (store) {\n store.setState({ selected_id: created_id });\n }\n } catch {\n // ignore\n }\n }\n\n setBusy(false);\n requestClose();\n }\n\n // Events\n dialog.addEventListener('cancel', (ev) => {\n ev.preventDefault();\n requestClose();\n });\n btn_close.addEventListener('click', () => requestClose());\n btn_cancel.addEventListener('click', () => requestClose());\n dialog.addEventListener('keydown', (ev) => {\n if (ev.key === 'Enter' && (ev.ctrlKey || ev.metaKey)) {\n ev.preventDefault();\n void createNow();\n }\n });\n form.addEventListener('submit', (ev) => {\n ev.preventDefault();\n void createNow();\n });\n\n return {\n open() {\n form.reset();\n clearError();\n loadDefaults();\n try {\n if ('showModal' in dialog && typeof dialog.showModal === 'function') {\n dialog.showModal();\n } else {\n dialog.setAttribute('open', '');\n }\n } catch {\n dialog.setAttribute('open', '');\n }\n setTimeout(() => {\n try {\n input_title.focus();\n } catch {\n // ignore\n }\n }, 0);\n },\n close() {\n requestClose();\n }\n };\n}\n", "import { html, render } from 'lit-html';\nimport { debug } from '../utils/logging.js';\n\n/**\n * @typedef {import('../state.js').WorkspaceInfo} WorkspaceInfo\n */\n\n/**\n * Extract the project name from a workspace path. Returns just the directory\n * name (e.g., 'myproject' from '/home/user/code/myproject').\n *\n * @param {string} workspace_path\n * @returns {string}\n */\nfunction getProjectName(workspace_path) {\n if (!workspace_path) return 'Unknown';\n const parts = workspace_path.split('/').filter(Boolean);\n return parts.length > 0 ? parts[parts.length - 1] : 'Unknown';\n}\n\n/**\n * Create the workspace picker dropdown component.\n *\n * @param {HTMLElement} mount_element\n * @param {{ getState: () => any, subscribe: (fn: (s: any) => void) => () => void }} store\n * @param {(workspace_path: string) => Promise<void>} onWorkspaceChange\n */\nexport function createWorkspacePicker(mount_element, store, onWorkspaceChange) {\n const log = debug('views:workspace-picker');\n /** @type {(() => void) | null} */\n let unsubscribe = null;\n /** @type {boolean} */\n let is_switching = false;\n\n /**\n * Handle workspace selection change.\n *\n * @param {Event} ev\n */\n async function onChange(ev) {\n const select = /** @type {HTMLSelectElement} */ (ev.target);\n const new_path = select.value;\n const s = store.getState();\n const current_path = s.workspace?.current?.path || '';\n\n if (new_path && new_path !== current_path) {\n log('switching workspace to %s', new_path);\n is_switching = true;\n doRender();\n try {\n await onWorkspaceChange(new_path);\n } catch (err) {\n log('workspace switch failed: %o', err);\n } finally {\n is_switching = false;\n doRender();\n }\n }\n }\n\n function template() {\n const s = store.getState();\n const current = s.workspace?.current;\n const available = s.workspace?.available || [];\n\n // Don't render if no workspaces available\n if (available.length === 0) {\n return html``;\n }\n\n // If only one workspace, show it as a simple label\n if (available.length === 1) {\n const name = getProjectName(available[0].path);\n return html`\n <div class=\"workspace-picker workspace-picker--single\">\n <span class=\"workspace-picker__label\" title=\"${available[0].path}\"\n >${name}</span\n >\n </div>\n `;\n }\n\n // Multiple workspaces: show dropdown\n const current_path = current?.path || '';\n return html`\n <div class=\"workspace-picker\">\n <select\n class=\"workspace-picker__select\"\n @change=${onChange}\n ?disabled=${is_switching}\n aria-label=\"Select project workspace\"\n >\n ${available.map(\n (/** @type {WorkspaceInfo} */ ws) => html`\n <option\n value=\"${ws.path}\"\n ?selected=${ws.path === current_path}\n title=\"${ws.path}\"\n >\n ${getProjectName(ws.path)}\n </option>\n `\n )}\n </select>\n ${is_switching\n ? html`<span\n class=\"workspace-picker__loading\"\n aria-hidden=\"true\"\n ></span>`\n : ''}\n </div>\n `;\n }\n\n function doRender() {\n render(template(), mount_element);\n }\n\n doRender();\n unsubscribe = store.subscribe(() => doRender());\n\n return {\n destroy() {\n if (unsubscribe) {\n unsubscribe();\n unsubscribe = null;\n }\n render(html``, mount_element);\n }\n };\n}\n", "/**\n * Protocol definitions for beads-ui WebSocket communication.\n *\n * Conventions\n * - All messages are JSON objects.\n * - Client \u2192 Server uses RequestEnvelope.\n * - Server \u2192 Client uses ReplyEnvelope.\n * - Every request is correlated by `id` in replies.\n * - Server can also send unsolicited events (e.g., subscription `snapshot`).\n */\n\n/** @typedef {'list-issues'|'update-status'|'edit-text'|'update-priority'|'create-issue'|'list-ready'|'dep-add'|'dep-remove'|'epic-status'|'update-assignee'|'label-add'|'label-remove'|'subscribe-list'|'unsubscribe-list'|'snapshot'|'upsert'|'delete'|'get-comments'|'add-comment'|'delete-issue'|'list-workspaces'|'set-workspace'|'get-workspace'|'workspace-changed'} MessageType */\n\n/**\n * @typedef {Object} RequestEnvelope\n * @property {string} id - Unique id to correlate request/response.\n * @property {MessageType} type - Message type.\n * @property {unknown} [payload] - Message payload.\n */\n\n/**\n * @typedef {Object} ErrorObject\n * @property {string} code - Stable error code.\n * @property {string} message - Human-readable message.\n * @property {unknown} [details] - Optional extra info for debugging.\n */\n\n/**\n * @typedef {Object} ReplyEnvelope\n * @property {string} id - Correlates to the originating request.\n * @property {boolean} ok - True when request succeeded; false on error.\n * @property {MessageType} type - Echoes request type (or event type).\n * @property {unknown} [payload] - Response payload.\n * @property {ErrorObject} [error] - Present when ok=false.\n */\n\n/** @type {MessageType[]} */\nexport const MESSAGE_TYPES = /** @type {const} */ ([\n 'list-issues',\n 'update-status',\n 'edit-text',\n 'update-priority',\n 'create-issue',\n 'list-ready',\n 'dep-add',\n 'dep-remove',\n 'epic-status',\n 'update-assignee',\n 'label-add',\n 'label-remove',\n 'subscribe-list',\n 'unsubscribe-list',\n // vNext per-subscription full-issue push events\n 'snapshot',\n 'upsert',\n 'delete',\n // Comments\n 'get-comments',\n 'add-comment',\n // Delete issue\n 'delete-issue',\n // Workspace management\n 'list-workspaces',\n 'set-workspace',\n 'get-workspace',\n 'workspace-changed'\n]);\n\n/**\n * Generate a lexically sortable request id.\n *\n * @returns {string}\n */\nexport function nextId() {\n const now = Date.now().toString(36);\n const rand = Math.random().toString(36).slice(2, 8);\n return `${now}-${rand}`;\n}\n\n/**\n * Create a request envelope.\n *\n * @param {MessageType} type - Message type.\n * @param {unknown} [payload] - Message payload.\n * @param {string} [id] - Optional id; generated if omitted.\n * @returns {RequestEnvelope}\n */\nexport function makeRequest(type, payload, id = nextId()) {\n return { id, type, payload };\n}\n\n/**\n * Create a successful reply envelope for a given request.\n *\n * @param {RequestEnvelope} req - Original request.\n * @param {unknown} [payload] - Reply payload.\n * @returns {ReplyEnvelope}\n */\nexport function makeOk(req, payload) {\n return { id: req.id, ok: true, type: req.type, payload };\n}\n\n/**\n * Create an error reply envelope for a given request.\n *\n * @param {RequestEnvelope} req - Original request.\n * @param {string} code\n * @param {string} message\n * @param {unknown} [details]\n * @returns {ReplyEnvelope}\n */\nexport function makeError(req, code, message, details) {\n return {\n id: req.id,\n ok: false,\n type: req.type,\n error: { code, message, details }\n };\n}\n\n/**\n * Check if a value is a plain object.\n *\n * @param {unknown} value\n * @returns {value is Record<string, unknown>}\n */\nfunction isRecord(value) {\n return !!value && typeof value === 'object' && !Array.isArray(value);\n}\n\n/**\n * Type guard for MessageType values.\n *\n * @param {unknown} value\n * @returns {value is MessageType}\n */\nexport function isMessageType(value) {\n return (\n typeof value === 'string' &&\n MESSAGE_TYPES.includes(/** @type {MessageType} */ (value))\n );\n}\n\n/**\n * Type guard for RequestEnvelope.\n *\n * @param {unknown} value\n * @returns {value is RequestEnvelope}\n */\nexport function isRequest(value) {\n if (!isRecord(value)) {\n return false;\n }\n return (\n typeof value.id === 'string' &&\n typeof value.type === 'string' &&\n (value.payload === undefined || 'payload' in value)\n );\n}\n\n/**\n * Type guard for ReplyEnvelope.\n *\n * @param {unknown} value\n * @returns {value is ReplyEnvelope}\n */\nexport function isReply(value) {\n if (!isRecord(value)) {\n return false;\n }\n if (\n typeof value.id !== 'string' ||\n typeof value.ok !== 'boolean' ||\n !isMessageType(value.type)\n ) {\n return false;\n }\n if (value.ok === false) {\n const err = value.error;\n if (\n !isRecord(err) ||\n typeof err.code !== 'string' ||\n typeof err.message !== 'string'\n ) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Normalize and validate an incoming JSON value as a RequestEnvelope.\n * Throws a user-friendly error if invalid.\n *\n * @param {unknown} json\n * @returns {RequestEnvelope}\n */\nexport function decodeRequest(json) {\n if (!isRequest(json)) {\n throw new Error('Invalid request envelope');\n }\n return json;\n}\n\n/**\n * Normalize and validate an incoming JSON value as a ReplyEnvelope.\n *\n * @param {unknown} json\n * @returns {ReplyEnvelope}\n */\nexport function decodeReply(json) {\n if (!isReply(json)) {\n throw new Error('Invalid reply envelope');\n }\n return json;\n}\n", "/**\n * @import { MessageType } from './protocol.js'\n */\n/**\n * Persistent WebSocket client with reconnect, request/response correlation,\n * and simple event dispatching.\n *\n * Usage:\n * const ws = createWsClient();\n * const data = await ws.send('list-issues', { filters: {} });\n * const off = ws.on('snapshot', (payload) => { <push event> });\n */\nimport { MESSAGE_TYPES, makeRequest, nextId } from './protocol.js';\nimport { debug } from './utils/logging.js';\n\n/**\n * @typedef {'connecting'|'open'|'closed'|'reconnecting'} ConnectionState\n */\n\n/**\n * @typedef {{ initialMs?: number, maxMs?: number, factor?: number, jitterRatio?: number }} BackoffOptions\n */\n\n/**\n * @typedef {{ url?: string, backoff?: BackoffOptions }} ClientOptions\n */\n\n/**\n * Create a WebSocket client with auto-reconnect and message correlation.\n *\n * @param {ClientOptions} [options]\n */\nexport function createWsClient(options = {}) {\n const log = debug('ws');\n\n /** @type {BackoffOptions} */\n const backoff = {\n initialMs: options.backoff?.initialMs ?? 1000,\n maxMs: options.backoff?.maxMs ?? 30000,\n factor: options.backoff?.factor ?? 2,\n jitterRatio: options.backoff?.jitterRatio ?? 0.2\n };\n\n /** @type {() => string} */\n const resolveUrl = () => {\n if (options.url && options.url.length > 0) {\n return options.url;\n }\n if (typeof location !== 'undefined') {\n return (\n (location.protocol === 'https:' ? 'wss://' : 'ws://') +\n location.host +\n '/ws'\n );\n }\n return 'ws://localhost/ws';\n };\n\n /** @type {WebSocket | null} */\n let ws = null;\n /** @type {ConnectionState} */\n let state = 'closed';\n /** @type {number} */\n let attempts = 0;\n /** @type {ReturnType<typeof setTimeout> | null} */\n let reconnect_timer = null;\n /** @type {boolean} */\n let should_reconnect = true;\n\n /** @type {Map<string, { resolve: (v: any) => void, reject: (e: any) => void, type: string }>} */\n const pending = new Map();\n /** @type {Array<ReturnType<typeof makeRequest>>} */\n const queue = [];\n /** @type {Map<string, Set<(payload: any) => void>>} */\n const handlers = new Map();\n /** @type {Set<(s: ConnectionState) => void>} */\n const connection_handlers = new Set();\n\n /**\n * @param {ConnectionState} s\n */\n function notifyConnection(s) {\n for (const fn of Array.from(connection_handlers)) {\n try {\n fn(s);\n } catch {\n // ignore listener errors\n }\n }\n }\n\n function scheduleReconnect() {\n if (!should_reconnect || reconnect_timer) {\n return;\n }\n state = 'reconnecting';\n log('ws reconnecting\u2026');\n notifyConnection(state);\n const base = Math.min(\n backoff.maxMs || 0,\n (backoff.initialMs || 0) * Math.pow(backoff.factor || 1, attempts)\n );\n const jitter = (backoff.jitterRatio || 0) * base;\n const delay = Math.max(\n 0,\n Math.round(base + (Math.random() * 2 - 1) * jitter)\n );\n log('ws retry in %d ms (attempt %d)', delay, attempts + 1);\n reconnect_timer = setTimeout(() => {\n reconnect_timer = null;\n connect();\n }, delay);\n }\n\n /** @param {ReturnType<typeof makeRequest>} req */\n function sendRaw(req) {\n try {\n ws?.send(JSON.stringify(req));\n } catch (err) {\n log('ws send failed', err);\n }\n }\n\n function onOpen() {\n state = 'open';\n log('ws open');\n notifyConnection(state);\n attempts = 0;\n // flush queue\n while (queue.length) {\n const req = queue.shift();\n if (req) {\n sendRaw(req);\n }\n }\n }\n\n /** @param {MessageEvent} ev */\n function onMessage(ev) {\n /** @type {any} */\n let msg;\n try {\n msg = JSON.parse(String(ev.data));\n } catch {\n log('ws received non-JSON message');\n return;\n }\n if (!msg || typeof msg.id !== 'string' || typeof msg.type !== 'string') {\n log('ws received invalid envelope');\n return;\n }\n\n if (pending.has(msg.id)) {\n const entry = pending.get(msg.id);\n pending.delete(msg.id);\n if (msg.ok) {\n entry?.resolve(msg.payload);\n } else {\n entry?.reject(msg.error || new Error('ws error'));\n }\n return;\n }\n\n // Treat as server-initiated event\n const set = handlers.get(msg.type);\n if (set && set.size > 0) {\n for (const fn of Array.from(set)) {\n try {\n fn(msg.payload);\n } catch (err) {\n log('ws event handler error', err);\n }\n }\n } else {\n log('ws received unhandled message type: %s', msg.type);\n }\n }\n\n function onClose() {\n state = 'closed';\n log('ws closed');\n notifyConnection(state);\n // fail all pending\n for (const [id, p] of pending.entries()) {\n p.reject(new Error('ws disconnected'));\n pending.delete(id);\n }\n attempts += 1;\n scheduleReconnect();\n }\n\n function connect() {\n if (!should_reconnect) {\n return;\n }\n const url = resolveUrl();\n try {\n ws = new WebSocket(url);\n log('ws connecting %s', url);\n state = 'connecting';\n notifyConnection(state);\n ws.addEventListener('open', onOpen);\n ws.addEventListener('message', onMessage);\n ws.addEventListener('error', () => {\n // let close handler handle reconnect\n });\n ws.addEventListener('close', onClose);\n } catch (err) {\n log('ws connect failed %o', err);\n scheduleReconnect();\n }\n }\n\n connect();\n\n return {\n /**\n * Send a request and await its correlated reply payload.\n *\n * @param {MessageType} type\n * @param {unknown} [payload]\n * @returns {Promise<any>}\n */\n send(type, payload) {\n if (!MESSAGE_TYPES.includes(type)) {\n return Promise.reject(new Error(`unknown message type: ${type}`));\n }\n const id = nextId();\n const req = makeRequest(type, payload, id);\n log('send %s id=%s', type, id);\n return new Promise((resolve, reject) => {\n pending.set(id, { resolve, reject, type });\n if (ws && ws.readyState === ws.OPEN) {\n sendRaw(req);\n } else {\n log('queue %s id=%s (state=%s)', type, id, state);\n queue.push(req);\n }\n });\n },\n /**\n * Register a handler for a server-initiated event type.\n * Returns an unsubscribe function.\n *\n * @param {MessageType} type\n * @param {(payload: any) => void} handler\n * @returns {() => void}\n */\n on(type, handler) {\n if (!handlers.has(type)) {\n handlers.set(type, new Set());\n }\n const set = handlers.get(type);\n set?.add(handler);\n return () => {\n set?.delete(handler);\n };\n },\n /**\n * Subscribe to connection state changes.\n *\n * @param {(state: ConnectionState) => void} handler\n * @returns {() => void}\n */\n onConnection(handler) {\n connection_handlers.add(handler);\n return () => {\n connection_handlers.delete(handler);\n };\n },\n /** Close and stop reconnecting. */\n close() {\n should_reconnect = false;\n if (reconnect_timer) {\n clearTimeout(reconnect_timer);\n reconnect_timer = null;\n }\n try {\n ws?.close();\n } catch {\n /* ignore */\n }\n },\n /** For diagnostics in tests or UI. */\n getState() {\n return state;\n }\n };\n}\n", "/**\n * @import { MessageType } from './protocol.js'\n */\nimport { html, render } from 'lit-html';\nimport { createListSelectors } from './data/list-selectors.js';\nimport { createDataLayer } from './data/providers.js';\nimport { createSubscriptionIssueStores } from './data/subscription-issue-stores.js';\nimport { createSubscriptionStore } from './data/subscriptions-store.js';\nimport { createHashRouter, parseHash, parseView } from './router.js';\nimport { createStore } from './state.js';\nimport { createActivityIndicator } from './utils/activity-indicator.js';\nimport { debug } from './utils/logging.js';\nimport { showToast } from './utils/toast.js';\nimport { createBoardView } from './views/board.js';\nimport { createDetailView } from './views/detail.js';\nimport { createEpicsView } from './views/epics.js';\nimport { createFatalErrorDialog } from './views/fatal-error-dialog.js';\nimport { createIssueDialog } from './views/issue-dialog.js';\nimport { createListView } from './views/list.js';\nimport { createTopNav } from './views/nav.js';\nimport { createNewIssueDialog } from './views/new-issue-dialog.js';\nimport { createWorkspacePicker } from './views/workspace-picker.js';\nimport { createWsClient } from './ws.js';\n\n/**\n * Bootstrap the SPA shell with two panels.\n *\n * @param {HTMLElement} root_element - The container element to render into.\n */\nexport function bootstrap(root_element) {\n const log = debug('main');\n log('bootstrap start');\n\n // Render route shells (nav is mounted in header)\n const shell = html`\n <section id=\"issues-root\" class=\"route issues\">\n <aside id=\"list-panel\" class=\"panel\"></aside>\n </section>\n <section id=\"epics-root\" class=\"route epics\" hidden></section>\n <section id=\"board-root\" class=\"route board\" hidden></section>\n <section id=\"detail-panel\" class=\"route detail\" hidden></section>\n `;\n render(shell, root_element);\n\n /** @type {HTMLElement|null} */\n const nav_mount = document.getElementById('top-nav');\n /** @type {HTMLElement|null} */\n const issues_root = document.getElementById('issues-root');\n /** @type {HTMLElement|null} */\n const epics_root = document.getElementById('epics-root');\n /** @type {HTMLElement|null} */\n const board_root = document.getElementById('board-root');\n\n /** @type {HTMLElement|null} */\n const list_mount = document.getElementById('list-panel');\n /** @type {HTMLElement|null} */\n const detail_mount = document.getElementById('detail-panel');\n if (list_mount && issues_root && epics_root && board_root && detail_mount) {\n /** @type {HTMLElement|null} */\n const header_loading = document.getElementById('header-loading');\n const activity = createActivityIndicator(header_loading);\n const fatal_dialog = createFatalErrorDialog(root_element);\n\n /**\n * Show a blocking dialog when a backend command fails.\n *\n * @param {unknown} err\n * @param {string} context\n */\n function showFatalFromError(err, context) {\n /** @type {string} */\n let message = 'Request failed';\n /** @type {string} */\n let detail = '';\n\n if (err && typeof err === 'object') {\n const any = /** @type {{ message?: unknown, details?: unknown }} */ (\n err\n );\n if (typeof any.message === 'string' && any.message.length > 0) {\n message = any.message;\n }\n if (typeof any.details === 'string') {\n detail = any.details;\n } else if (any.details && typeof any.details === 'object') {\n try {\n detail = JSON.stringify(any.details, null, 2);\n } catch {\n detail = '';\n }\n }\n } else if (typeof err === 'string' && err.length > 0) {\n message = err;\n }\n\n const title =\n context && context.length > 0\n ? `Failed to load ${context}`\n : 'Request failed';\n\n fatal_dialog.open(title, message, detail);\n }\n\n const client = createWsClient();\n const tracked_send = activity.wrapSend((type, payload) =>\n client.send(type, payload)\n );\n // Subscriptions: wire client events and expose subscribe/unsubscribe helpers\n const subscriptions = createSubscriptionStore(tracked_send);\n // Per-subscription stores (source of truth)\n const sub_issue_stores = createSubscriptionIssueStores();\n // Route per-subscription push envelopes to the owning store\n client.on('snapshot', (payload) => {\n const p = /** @type {any} */ (payload);\n const id = p && typeof p.id === 'string' ? p.id : '';\n const store = id ? sub_issue_stores.getStore(id) : null;\n if (store && p && p.type === 'snapshot') {\n try {\n store.applyPush(p);\n } catch {\n // ignore\n }\n }\n });\n client.on('upsert', (payload) => {\n const p = /** @type {any} */ (payload);\n const id = p && typeof p.id === 'string' ? p.id : '';\n const store = id ? sub_issue_stores.getStore(id) : null;\n if (store && p && p.type === 'upsert') {\n try {\n store.applyPush(p);\n } catch {\n // ignore\n }\n }\n });\n client.on('delete', (payload) => {\n const p = /** @type {any} */ (payload);\n const id = p && typeof p.id === 'string' ? p.id : '';\n const store = id ? sub_issue_stores.getStore(id) : null;\n if (store && p && p.type === 'delete') {\n try {\n store.applyPush(p);\n } catch {\n // ignore\n }\n }\n });\n // Derived list selectors: render from per-subscription snapshots\n const listSelectors = createListSelectors(sub_issue_stores);\n\n // --- Workspace management ---\n /**\n * Clear all subscriptions and stores, then re-establish them.\n * Called when switching workspaces.\n */\n async function clearAndResubscribe() {\n log('clearing all subscriptions for workspace switch');\n // Unsubscribe from server-side subscriptions first\n if (unsub_issues_tab) {\n void unsub_issues_tab().catch(() => {});\n unsub_issues_tab = null;\n }\n if (unsub_epics_tab) {\n void unsub_epics_tab().catch(() => {});\n unsub_epics_tab = null;\n }\n if (unsub_board_ready) {\n void unsub_board_ready().catch(() => {});\n unsub_board_ready = null;\n }\n if (unsub_board_in_progress) {\n void unsub_board_in_progress().catch(() => {});\n unsub_board_in_progress = null;\n }\n if (unsub_board_closed) {\n void unsub_board_closed().catch(() => {});\n unsub_board_closed = null;\n }\n if (unsub_board_blocked) {\n void unsub_board_blocked().catch(() => {});\n unsub_board_blocked = null;\n }\n // Clear all subscription stores\n const storeIds = [\n 'tab:issues',\n 'tab:epics',\n 'tab:board:ready',\n 'tab:board:in-progress',\n 'tab:board:closed',\n 'tab:board:blocked'\n ];\n for (const id of storeIds) {\n try {\n sub_issue_stores.unregister(id);\n } catch {\n // ignore\n }\n }\n // Also clear any detail stores\n const s = store.getState();\n if (s.selected_id) {\n try {\n sub_issue_stores.unregister(`detail:${s.selected_id}`);\n } catch {\n // ignore\n }\n }\n // Force re-subscribe by resetting last spec key\n last_issues_spec_key = null;\n // Re-establish subscriptions for current view\n ensureTabSubscriptions(store.getState());\n }\n\n /**\n * Handle workspace change request from the picker.\n *\n * @param {string} workspace_path\n */\n async function handleWorkspaceChange(workspace_path) {\n log('requesting workspace switch to %s', workspace_path);\n try {\n const result = await client.send('set-workspace', {\n path: workspace_path\n });\n log('workspace switch result: %o', result);\n if (result && result.workspace) {\n // Update state with new workspace\n store.setState({\n workspace: {\n current: {\n path: result.workspace.root_dir,\n database: result.workspace.db_path\n }\n }\n });\n // Persist preference\n window.localStorage.setItem('beads-ui.workspace', workspace_path);\n // Clear and resubscribe if workspace actually changed\n if (result.changed) {\n await clearAndResubscribe();\n showToast(\n 'Switched to ' + getProjectName(workspace_path),\n 'success',\n 2000\n );\n }\n }\n } catch (err) {\n log('workspace switch failed: %o', err);\n showToast('Failed to switch workspace', 'error', 3000);\n throw err;\n }\n }\n\n /**\n * Extract project name from path.\n *\n * @param {string} path\n * @returns {string}\n */\n function getProjectName(path) {\n if (!path) return 'Unknown';\n const parts = path.split('/').filter(Boolean);\n return parts.length > 0 ? parts[parts.length - 1] : 'Unknown';\n }\n\n /**\n * Load available workspaces from server and update state.\n */\n async function loadWorkspaces() {\n try {\n const result = await client.send('list-workspaces', {});\n log('workspaces loaded: %o', result);\n if (result && Array.isArray(result.workspaces)) {\n const available = result.workspaces.map((/** @type {any} */ ws) => ({\n path: ws.path,\n database: ws.database,\n pid: ws.pid,\n version: ws.version\n }));\n const current = result.current\n ? {\n path: result.current.root_dir,\n database: result.current.db_path\n }\n : null;\n store.setState({ workspace: { current, available } });\n\n // Check if we have a saved preference that differs from current\n const savedWorkspace =\n window.localStorage.getItem('beads-ui.workspace');\n if (savedWorkspace && current && savedWorkspace !== current.path) {\n // Check if saved workspace is in available list\n const savedExists = available.some(\n (/** @type {{ path: string }} */ ws) => ws.path === savedWorkspace\n );\n if (savedExists) {\n log('restoring saved workspace preference: %s', savedWorkspace);\n await handleWorkspaceChange(savedWorkspace);\n }\n }\n }\n } catch (err) {\n log('failed to load workspaces: %o', err);\n }\n }\n\n // Handle workspace-changed events from server (e.g., if another client changes workspace)\n client.on('workspace-changed', (payload) => {\n log('workspace-changed event: %o', payload);\n if (payload && payload.root_dir) {\n store.setState({\n workspace: {\n current: {\n path: payload.root_dir,\n database: payload.db_path\n }\n }\n });\n // Reload workspaces to get fresh list\n void loadWorkspaces();\n // Clear and resubscribe\n void clearAndResubscribe();\n }\n });\n\n // --- End workspace management (mounting happens after store is created) ---\n\n // Show toasts for WebSocket connectivity changes\n /** @type {boolean} */\n let had_disconnect = false;\n if (typeof client.onConnection === 'function') {\n /** @type {(s: 'connecting'|'open'|'closed'|'reconnecting') => void} */\n const onConn = (s) => {\n log('ws state %s', s);\n if (s === 'reconnecting' || s === 'closed') {\n had_disconnect = true;\n showToast('Connection lost. Reconnecting\u2026', 'error', 4000);\n } else if (s === 'open' && had_disconnect) {\n had_disconnect = false;\n showToast('Reconnected', 'success', 2200);\n }\n };\n client.onConnection(onConn);\n }\n // Load persisted filters (status/search/type) from localStorage\n /** @type {{ status: 'all'|'open'|'in_progress'|'closed'|'ready', search: string, type: string }} */\n let persisted_filters = { status: 'all', search: '', type: '' };\n try {\n const raw = window.localStorage.getItem('beads-ui.filters');\n if (raw) {\n const obj = JSON.parse(raw);\n if (obj && typeof obj === 'object') {\n const ALLOWED = ['bug', 'feature', 'task', 'epic', 'chore'];\n let parsed_type = '';\n if (typeof obj.type === 'string' && ALLOWED.includes(obj.type)) {\n parsed_type = obj.type;\n } else if (Array.isArray(obj.types)) {\n // Backwards compatibility: pick first valid from previous array format\n let first_valid = '';\n for (const it of obj.types) {\n if (ALLOWED.includes(String(it))) {\n first_valid = /** @type {string} */ (it);\n break;\n }\n }\n parsed_type = first_valid;\n }\n persisted_filters = {\n status: ['all', 'open', 'in_progress', 'closed', 'ready'].includes(\n obj.status\n )\n ? obj.status\n : 'all',\n search: typeof obj.search === 'string' ? obj.search : '',\n type: parsed_type\n };\n }\n }\n } catch (err) {\n log('filters parse error: %o', err);\n }\n // Load last-view from storage\n /** @type {'issues'|'epics'|'board'} */\n let last_view = 'issues';\n try {\n const raw_view = window.localStorage.getItem('beads-ui.view');\n if (\n raw_view === 'issues' ||\n raw_view === 'epics' ||\n raw_view === 'board'\n ) {\n last_view = raw_view;\n }\n } catch (err) {\n log('view parse error: %o', err);\n }\n // Load board preferences\n /** @type {{ closed_filter: 'today'|'3'|'7' }} */\n let persistedBoard = { closed_filter: 'today' };\n try {\n const raw_board = window.localStorage.getItem('beads-ui.board');\n if (raw_board) {\n const obj = JSON.parse(raw_board);\n if (obj && typeof obj === 'object') {\n const cf = String(obj.closed_filter || 'today');\n if (cf === 'today' || cf === '3' || cf === '7') {\n persistedBoard.closed_filter = cf;\n }\n }\n }\n } catch (err) {\n log('board prefs parse error: %o', err);\n }\n\n const store = createStore({\n filters: persisted_filters,\n view: last_view,\n board: persistedBoard\n });\n const router = createHashRouter(store);\n router.start();\n /**\n * @param {string} type\n * @param {unknown} payload\n */\n const transport = async (type, payload) => {\n try {\n return await tracked_send(/** @type {MessageType} */ (type), payload);\n } catch {\n return [];\n }\n };\n // Top navigation (optional mount)\n if (nav_mount) {\n createTopNav(nav_mount, store, router);\n }\n\n // Workspace picker (mount now that store exists)\n const workspace_mount = document.getElementById('workspace-picker');\n if (workspace_mount) {\n createWorkspacePicker(workspace_mount, store, handleWorkspaceChange);\n }\n // Load workspaces after WebSocket is connected\n void loadWorkspaces();\n\n // Global New Issue dialog (UI-106) mounted at root so it is always visible\n const new_issue_dialog = createNewIssueDialog(\n root_element,\n (type, payload) => tracked_send(type, payload),\n router,\n store\n );\n // Header button\n try {\n const btn_new = /** @type {HTMLButtonElement|null} */ (\n document.getElementById('new-issue-btn')\n );\n if (btn_new) {\n btn_new.addEventListener('click', () => new_issue_dialog.open());\n }\n } catch {\n // ignore missing header\n }\n\n // Local transport shim: for list-issues, serve from local listSelectors;\n // otherwise forward to ws transport for mutations/show.\n /**\n * @param {MessageType} type\n * @param {unknown} payload\n */\n const listTransport = async (type, payload) => {\n if (type === 'list-issues') {\n try {\n return listSelectors.selectIssuesFor('tab:issues');\n } catch (err) {\n log('list selectors failed: %o', err);\n return [];\n }\n }\n return transport(type, payload);\n };\n\n const issues_view = createListView(\n list_mount,\n /** @type {any} */ (listTransport),\n (hash) => {\n const id = parseHash(hash);\n if (id) {\n router.gotoIssue(id);\n }\n },\n store,\n subscriptions,\n sub_issue_stores\n );\n // Persist filter changes to localStorage\n store.subscribe((s) => {\n const data = {\n status: s.filters.status,\n search: s.filters.search,\n type: typeof s.filters.type === 'string' ? s.filters.type : ''\n };\n window.localStorage.setItem('beads-ui.filters', JSON.stringify(data));\n });\n // Persist board preferences\n store.subscribe((s) => {\n window.localStorage.setItem(\n 'beads-ui.board',\n JSON.stringify({ closed_filter: s.board.closed_filter })\n );\n });\n void issues_view.load();\n\n // Dialog for issue details (UI-104)\n const dialog = createIssueDialog(detail_mount, store, () => {\n // Close: clear selection and return to current view\n const s = store.getState();\n store.setState({ selected_id: null });\n try {\n /** @type {'issues'|'epics'|'board'} */\n const v = s.view || 'issues';\n router.gotoView(v);\n } catch {\n // ignore\n }\n });\n\n /** @type {ReturnType<typeof createDetailView> | null} */\n let detail = null;\n // Mount details into the dialog body only\n detail = createDetailView(\n dialog.getMount(),\n transport,\n (hash) => {\n const id = parseHash(hash);\n if (id) {\n router.gotoIssue(id);\n } else {\n // No issue ID - navigate to view (closes dialog)\n const view = parseView(hash);\n router.gotoView(view);\n }\n },\n sub_issue_stores\n );\n\n // If router already set a selected id (deep-link), open dialog now\n const initial_id = store.getState().selected_id;\n if (initial_id) {\n detail_mount.hidden = false;\n dialog.open(initial_id);\n if (detail) {\n void detail.load(initial_id);\n }\n // Ensure detail subscription is active on initial deep-link\n const client_id = `detail:${initial_id}`;\n const spec = { type: 'issue-detail', params: { id: initial_id } };\n // Register store first to avoid dropping the initial snapshot\n try {\n sub_issue_stores.register(client_id, spec);\n } catch (err) {\n log('register detail store failed: %o', err);\n }\n void subscriptions.subscribeList(client_id, spec).catch((err) => {\n log('detail subscribe failed: %o', err);\n showFatalFromError(err, 'issue details');\n });\n }\n\n // Open/close dialog based on selected_id (always dialog; no page variant)\n /** @type {null | (() => Promise<void>)} */\n let unsub_detail = null;\n store.subscribe((s) => {\n const id = s.selected_id;\n if (id) {\n detail_mount.hidden = false;\n dialog.open(id);\n if (detail) {\n void detail.load(id);\n }\n // Wire per-issue subscription for detail\n const client_id = `detail:${id}`;\n const spec = { type: 'issue-detail', params: { id } };\n // Ensure per-subscription issue store exists before subscribing\n try {\n sub_issue_stores.register(client_id, spec);\n } catch {\n // ignore\n }\n // Subscribe server-side\n void subscriptions\n .subscribeList(client_id, spec)\n .then((unsub) => {\n // Unsubscribe previous if any\n if (unsub_detail) {\n void unsub_detail().catch(() => {});\n }\n unsub_detail = unsub;\n })\n .catch((err) => {\n log('detail subscribe failed: %o', err);\n showFatalFromError(err, 'issue details');\n });\n } else {\n try {\n dialog.close();\n } catch {\n // ignore\n }\n if (detail) {\n detail.clear();\n }\n detail_mount.hidden = true;\n if (unsub_detail) {\n void unsub_detail().catch(() => {});\n unsub_detail = null;\n }\n }\n });\n\n // Removed: issues-changed handling. All views re-render from\n // per-subscription stores which are updated by snapshot/upsert/delete.\n\n // Toggle route shells on view/detail change and persist\n const data = createDataLayer(transport);\n const epics_view = createEpicsView(\n epics_root,\n data,\n (id) => router.gotoIssue(id),\n subscriptions,\n sub_issue_stores\n );\n const board_view = createBoardView(\n board_root,\n data,\n (id) => router.gotoIssue(id),\n store,\n subscriptions,\n sub_issue_stores,\n transport\n );\n // Preload epics when switching to view\n /**\n * @param {{ selected_id: string | null, view: 'issues'|'epics'|'board', filters: any }} s\n */\n // --- Subscriptions: tab-level management and filter-driven updates ---\n /** @type {null | (() => Promise<void>)} */\n let unsub_issues_tab = null;\n /** @type {null | (() => Promise<void>)} */\n let unsub_epics_tab = null;\n /** @type {null | (() => Promise<void>)} */\n let unsub_board_ready = null;\n /** @type {null | (() => Promise<void>)} */\n let unsub_board_in_progress = null;\n /** @type {null | (() => Promise<void>)} */\n let unsub_board_closed = null;\n /** @type {null | (() => Promise<void>)} */\n let unsub_board_blocked = null;\n\n // Track in-flight subscriptions to prevent duplicates during rapid view switching\n /** @type {Set<string>} */\n const pending_subscriptions = new Set();\n\n // Expose activity debug info globally for diagnostics\n // @ts-ignore\n window.__bdui_debug = {\n getPendingSubscriptions: () => Array.from(pending_subscriptions),\n getActivityCount: () => activity.getCount(),\n getActiveRequests: () => activity.getActiveRequests()\n };\n\n /**\n * Compute subscription spec for Issues tab based on filters.\n *\n * @param {{ status?: string }} filters\n * @returns {{ type: string, params?: Record<string, string|number|boolean> }}\n */\n function computeIssuesSpec(filters) {\n const st = String(filters?.status || 'all');\n if (st === 'ready') {\n return { type: 'ready-issues' };\n }\n if (st === 'in_progress') {\n return { type: 'in-progress-issues' };\n }\n if (st === 'closed') {\n return { type: 'closed-issues' };\n }\n // \"all\" and \"open\" map to all-issues; client filters apply locally\n return { type: 'all-issues' };\n }\n\n /** @type {string|null} */\n let last_issues_spec_key = null;\n /**\n * Ensure only the active tab has subscriptions; clean up previous.\n *\n * @param {{ view: 'issues'|'epics'|'board', filters: any }} s\n */\n function ensureTabSubscriptions(s) {\n // Issues tab\n if (s.view === 'issues') {\n const spec = computeIssuesSpec(s.filters || {});\n const key = JSON.stringify(spec);\n // Register store first to capture the initial snapshot\n try {\n sub_issue_stores.register('tab:issues', spec);\n } catch (err) {\n log('register issues store failed: %o', err);\n }\n // Only (re)subscribe if not yet subscribed, spec changed, and not already in-flight\n const issues_sub_key = `tab:issues:${key}`;\n if (\n (!unsub_issues_tab || key !== last_issues_spec_key) &&\n !pending_subscriptions.has(issues_sub_key)\n ) {\n pending_subscriptions.add(issues_sub_key);\n void subscriptions\n .subscribeList('tab:issues', spec)\n .then((unsub) => {\n unsub_issues_tab = unsub;\n last_issues_spec_key = key;\n })\n .catch((err) => {\n log('subscribe issues failed: %o', err);\n showFatalFromError(err, 'issues list');\n })\n .finally(() => {\n pending_subscriptions.delete(issues_sub_key);\n });\n }\n } else if (unsub_issues_tab) {\n void unsub_issues_tab().catch(() => {});\n unsub_issues_tab = null;\n last_issues_spec_key = null;\n try {\n sub_issue_stores.unregister('tab:issues');\n } catch (err) {\n log('unregister issues store failed: %o', err);\n }\n }\n\n // Epics tab\n if (s.view === 'epics') {\n // Register store first to avoid race with initial snapshot\n try {\n sub_issue_stores.register('tab:epics', { type: 'epics' });\n } catch (err) {\n log('register epics store failed: %o', err);\n }\n // Only subscribe if not already subscribed and not in-flight\n if (!unsub_epics_tab && !pending_subscriptions.has('tab:epics')) {\n pending_subscriptions.add('tab:epics');\n void subscriptions\n .subscribeList('tab:epics', { type: 'epics' })\n .then((unsub) => {\n unsub_epics_tab = unsub;\n })\n .catch((err) => {\n log('subscribe epics failed: %o', err);\n showFatalFromError(err, 'epics');\n })\n .finally(() => {\n pending_subscriptions.delete('tab:epics');\n });\n }\n } else if (unsub_epics_tab) {\n void unsub_epics_tab().catch(() => {});\n unsub_epics_tab = null;\n try {\n sub_issue_stores.unregister('tab:epics');\n } catch (err) {\n log('unregister epics store failed: %o', err);\n }\n }\n\n // Board tab subscribes to lists used by columns\n if (s.view === 'board') {\n // Ready column\n if (\n !unsub_board_ready &&\n !pending_subscriptions.has('tab:board:ready')\n ) {\n try {\n sub_issue_stores.register('tab:board:ready', {\n type: 'ready-issues'\n });\n } catch (err) {\n log('register board:ready store failed: %o', err);\n }\n pending_subscriptions.add('tab:board:ready');\n void subscriptions\n .subscribeList('tab:board:ready', { type: 'ready-issues' })\n .then((u) => (unsub_board_ready = u))\n .catch((err) => {\n log('subscribe board ready failed: %o', err);\n showFatalFromError(err, 'board (Ready)');\n })\n .finally(() => {\n pending_subscriptions.delete('tab:board:ready');\n });\n }\n // In Progress column\n if (\n !unsub_board_in_progress &&\n !pending_subscriptions.has('tab:board:in-progress')\n ) {\n try {\n sub_issue_stores.register('tab:board:in-progress', {\n type: 'in-progress-issues'\n });\n } catch (err) {\n log('register board:in-progress store failed: %o', err);\n }\n pending_subscriptions.add('tab:board:in-progress');\n void subscriptions\n .subscribeList('tab:board:in-progress', {\n type: 'in-progress-issues'\n })\n .then((u) => (unsub_board_in_progress = u))\n .catch((err) => {\n log('subscribe board in-progress failed: %o', err);\n showFatalFromError(err, 'board (In Progress)');\n })\n .finally(() => {\n pending_subscriptions.delete('tab:board:in-progress');\n });\n }\n // Closed column\n if (\n !unsub_board_closed &&\n !pending_subscriptions.has('tab:board:closed')\n ) {\n try {\n sub_issue_stores.register('tab:board:closed', {\n type: 'closed-issues'\n });\n } catch (err) {\n log('register board:closed store failed: %o', err);\n }\n pending_subscriptions.add('tab:board:closed');\n void subscriptions\n .subscribeList('tab:board:closed', { type: 'closed-issues' })\n .then((u) => (unsub_board_closed = u))\n .catch((err) => {\n log('subscribe board closed failed: %o', err);\n showFatalFromError(err, 'board (Closed)');\n })\n .finally(() => {\n pending_subscriptions.delete('tab:board:closed');\n });\n }\n // Blocked column\n if (\n !unsub_board_blocked &&\n !pending_subscriptions.has('tab:board:blocked')\n ) {\n try {\n sub_issue_stores.register('tab:board:blocked', {\n type: 'blocked-issues'\n });\n } catch (err) {\n log('register board:blocked store failed: %o', err);\n }\n pending_subscriptions.add('tab:board:blocked');\n void subscriptions\n .subscribeList('tab:board:blocked', { type: 'blocked-issues' })\n .then((u) => (unsub_board_blocked = u))\n .catch((err) => {\n log('subscribe board blocked failed: %o', err);\n showFatalFromError(err, 'board (Blocked)');\n })\n .finally(() => {\n pending_subscriptions.delete('tab:board:blocked');\n });\n }\n } else {\n // Unsubscribe all board lists when leaving the board view\n if (unsub_board_ready) {\n void unsub_board_ready().catch(() => {});\n unsub_board_ready = null;\n try {\n sub_issue_stores.unregister('tab:board:ready');\n } catch (err) {\n log('unregister board:ready failed: %o', err);\n }\n }\n if (unsub_board_in_progress) {\n void unsub_board_in_progress().catch(() => {});\n unsub_board_in_progress = null;\n try {\n sub_issue_stores.unregister('tab:board:in-progress');\n } catch (err) {\n log('unregister board:in-progress failed: %o', err);\n }\n }\n if (unsub_board_closed) {\n void unsub_board_closed().catch(() => {});\n unsub_board_closed = null;\n try {\n sub_issue_stores.unregister('tab:board:closed');\n } catch (err) {\n log('unregister board:closed failed: %o', err);\n }\n }\n if (unsub_board_blocked) {\n void unsub_board_blocked().catch(() => {});\n unsub_board_blocked = null;\n try {\n sub_issue_stores.unregister('tab:board:blocked');\n } catch (err) {\n log('unregister board:blocked failed: %o', err);\n }\n }\n }\n }\n\n /**\n * Manage route visibility and list subscriptions per view.\n *\n * @param {{ selected_id: string | null, view: 'issues'|'epics'|'board', filters: any }} s\n */\n const onRouteChange = (s) => {\n if (issues_root && epics_root && board_root && detail_mount) {\n // Underlying route visibility is controlled only by selected view\n issues_root.hidden = s.view !== 'issues';\n epics_root.hidden = s.view !== 'epics';\n board_root.hidden = s.view !== 'board';\n // detail_mount visibility handled in subscription above\n }\n // Ensure subscriptions for the active tab before loading the view to\n // avoid empty initial renders due to racing list-delta.\n ensureTabSubscriptions(s);\n if (!s.selected_id && s.view === 'epics') {\n void epics_view.load();\n }\n if (!s.selected_id && s.view === 'board') {\n void board_view.load();\n }\n window.localStorage.setItem('beads-ui.view', s.view);\n };\n store.subscribe(onRouteChange);\n // Ensure initial state is reflected (fixes reload on #/epics)\n onRouteChange(store.getState());\n\n // Removed redundant filter-change subscription: handled by ensureTabSubscriptions\n\n // Keyboard shortcuts: Ctrl/Cmd+N opens new issue; Ctrl/Cmd+Enter submits inside dialog\n window.addEventListener('keydown', (ev) => {\n const is_modifier = ev.ctrlKey || ev.metaKey;\n const key = String(ev.key || '').toLowerCase();\n const target = /** @type {HTMLElement} */ (ev.target);\n const tag =\n target && target.tagName ? String(target.tagName).toLowerCase() : '';\n const is_editable =\n tag === 'input' ||\n tag === 'textarea' ||\n tag === 'select' ||\n (target &&\n typeof target.isContentEditable === 'boolean' &&\n target.isContentEditable);\n if (is_modifier && key === 'n') {\n // Do not hijack when typing in inputs; common UX\n if (!is_editable) {\n ev.preventDefault();\n new_issue_dialog.open();\n }\n }\n });\n }\n}\n\nif (typeof window !== 'undefined' && typeof document !== 'undefined') {\n window.addEventListener('DOMContentLoaded', () => {\n // Initialize theme from saved preference or OS preference\n try {\n const saved = window.localStorage.getItem('beads-ui.theme');\n const prefersDark =\n window.matchMedia &&\n window.matchMedia('(prefers-color-scheme: dark)').matches;\n const initial =\n saved === 'dark' || saved === 'light'\n ? saved\n : prefersDark\n ? 'dark'\n : 'light';\n document.documentElement.setAttribute('data-theme', initial);\n const sw = /** @type {HTMLInputElement|null} */ (\n document.getElementById('theme-switch')\n );\n if (sw) {\n sw.checked = initial === 'dark';\n }\n } catch {\n // ignore theme init errors\n }\n\n // Wire up theme switch in header\n const themeSwitch = /** @type {HTMLInputElement|null} */ (\n document.getElementById('theme-switch')\n );\n if (themeSwitch) {\n themeSwitch.addEventListener('change', () => {\n const mode = themeSwitch.checked ? 'dark' : 'light';\n document.documentElement.setAttribute('data-theme', mode);\n window.localStorage.setItem('beads-ui.theme', mode);\n });\n }\n\n /** @type {HTMLElement|null} */\n const app_root = document.getElementById('app');\n if (app_root) {\n bootstrap(app_root);\n }\n });\n}\n"],
|
|
5
|
+
"mappings": "sqBAAA,IAAAA,GAAAC,GAAA,CAAAC,GAAAC,KAAA,CAIA,IAAIC,GAAI,IACJC,GAAID,GAAI,GACRE,GAAID,GAAI,GACRE,GAAID,GAAI,GACRE,GAAID,GAAI,EACRE,GAAIF,GAAI,OAgBZJ,GAAO,QAAU,SAAUO,EAAKC,EAAS,CACvCA,EAAUA,GAAW,CAAC,EACtB,IAAIC,EAAO,OAAOF,EAClB,GAAIE,IAAS,UAAYF,EAAI,OAAS,EACpC,OAAOG,GAAMH,CAAG,EACX,GAAIE,IAAS,UAAY,SAASF,CAAG,EAC1C,OAAOC,EAAQ,KAAOG,GAAQJ,CAAG,EAAIK,GAASL,CAAG,EAEnD,MAAM,IAAI,MACR,wDACE,KAAK,UAAUA,CAAG,CACtB,CACF,EAUA,SAASG,GAAMG,EAAK,CAElB,GADAA,EAAM,OA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AIH,GAAMI,CAAK,EAEjCF,EAAUC,CAAQ,EAAIC,GAK5B,OAAOF,CACT,CASA,SAASK,GACPN,EACAO,EAAY,CAEZ,KAAOP,IAAW,MAAM,CACtB,IAAMQ,EAAO5E,GAAyBoE,EAAQO,CAAI,EAElD,GAAIC,EAAM,CACR,GAAIA,EAAKC,IACP,OAAOxD,GAAQuD,EAAKC,GAAG,EAGzB,GAAI,OAAOD,EAAKL,OAAU,WACxB,OAAOlD,GAAQuD,EAAKL,KAAK,CAE7B,CAEAH,EAASrE,GAAeqE,CAAM,CAChC,CAEA,SAASU,GAAa,CACpB,OAAO,IACT,CAEA,OAAOA,CACT,CCjNO,IAAMC,GAAO7E,GAAO,CACzB,IACA,OACA,UACA,UACA,OACA,UACA,QACA,QACA,IACA,MACA,MACA,MACA,QACA,aACA,OACA,KACA,SACA,SACA,UACA,SACA,OACA,OACA,MACA,WACA,UACA,OACA,WACA,KACA,YACA,MACA,UACA,MACA,SACA,MACA,MACA,KACA,KACA,UACA,KACA,WACA,aACA,SACA,OACA,SACA,OACA,KACA,KACA,KACA,KACA,KACA,KACA,OACA,SACA,SACA,KACA,OACA,IACA,MACA,QACA,MACA,MACA,QACA,SACA,KACA,OACA,MACA,OACA,UACA,OACA,WACA,QACA,MACA,OACA,KACA,WACA,SACA,SACA,IACA,UACA,MACA,WACA,IACA,KACA,KACA,OACA,IACA,OACA,SACA,UACA,SACA,SACA,OACA,QACA,SACA,SACA,OACA,SACA,SACA,QACA,MACA,UACA,MACA,QACA,QACA,KACA,WACA,WACA,QACA,KACA,QACA,OACA,KACA,QACA,KACA,IACA,KACA,MACA,QACA,KAAK,CACG,EAEG8E,GAAM9E,GAAO,CACxB,MACA,IACA,WACA,cACA,eACA,eACA,gBACA,mBACA,SACA,WACA,OACA,OACA,UACA,eACA,cACA,SACA,OACA,IACA,QACA,WACA,QACA,QACA,YACA,OACA,iBACA,SACA,OACA,WACA,QACA,OACA,OACA,UACA,UACA,WACA,iBACA,OACA,OACA,QACA,SACA,SACA,OACA,WACA,QACA,OACA,QACA,OACA,OAAO,CACC,EAEG+E,GAAa/E,GAAO,CAC/B,UACA,gBACA,sBACA,cACA,mBACA,oBACA,oBACA,iBACA,eACA,UACA,UACA,UACA,UACA,UACA,iBACA,UACA,UACA,cACA,eACA,WACA,eACA,qBACA,cACA,SACA,cAAc,CACN,EAMGgF,GAAgBhF,GAAO,CAClC,UACA,gBACA,SACA,UACA,YACA,mBACA,iBACA,gBACA,gBACA,gBACA,QACA,YACA,OACA,eACA,YACA,UACA,gBACA,SACA,MACA,aACA,UACA,KAAK,CACG,EAEGiF,GAASjF,GAAO,CAC3B,OACA,WACA,SACA,UACA,QACA,SACA,KACA,aACA,gBACA,KACA,KACA,QACA,UACA,WACA,QACA,OACA,KACA,SACA,QACA,SACA,OACA,OACA,UACA,SACA,MACA,QACA,MACA,SACA,aACA,aAAa,CACL,EAIGkF,GAAmBlF,GAAO,CACrC,UACA,cACA,aACA,WACA,YACA,UACA,UACA,SACA,SACA,QACA,YACA,aACA,iBACA,cACA,MAAM,CACE,EAEGmF,GAAOnF,GAAO,CAAC,OAAO,CAAU,EC1RhC6E,GAAO7E,GAAO,CACzB,SACA,SACA,QACA,MACA,iBACA,eACA,uBACA,WACA,aACA,UACA,SACA,UACA,cACA,cACA,UACA,OACA,QACA,QACA,QACA,OACA,UACA,WACA,eACA,SACA,cACA,WACA,WACA,UACA,MACA,WACA,0BACA,wBACA,WACA,YACA,UACA,eACA,cACA,OACA,MACA,UACA,SACA,SACA,OACA,OACA,WACA,KACA,QACA,YACA,YACA,QACA,OACA,QACA,OACA,OACA,UACA,OACA,MACA,MACA,YACA,QACA,SACA,MACA,YACA,WACA,QACA,OACA,QACA,UACA,aACA,SACA,OACA,UACA,OACA,UACA,cACA,cACA,UACA,gBACA,sBACA,SACA,UACA,UACA,aACA,WACA,MACA,WACA,MACA,WACA,OACA,OACA,UACA,aACA,QACA,WACA,QACA,OACA,QACA,OACA,OACA,UACA,QACA,MACA,SACA,OACA,QACA,UACA,WACA,QACA,YACA,OACA,SACA,SACA,QACA,QACA,OACA,QACA,MAAM,CACE,EAEG8E,GAAM9E,GAAO,CACxB,gBACA,aACA,WACA,qBACA,YACA,SACA,gBACA,gBACA,UACA,gBACA,iBACA,QACA,OACA,KACA,QACA,OACA,gBACA,YACA,YACA,QACA,sBACA,8BACA,gBACA,kBACA,KACA,KACA,IACA,KACA,KACA,kBACA,YACA,UACA,UACA,MACA,WACA,YACA,MACA,WACA,OACA,eACA,YACA,SACA,cACA,cACA,gBACA,cACA,YACA,mBACA,eACA,aACA,eACA,cACA,KACA,KACA,KACA,KACA,aACA,WACA,gBACA,oBACA,SACA,OACA,KACA,kBACA,KACA,MACA,YACA,IACA,KACA,KACA,KACA,KACA,UACA,YACA,aACA,WACA,OACA,eACA,iBACA,eACA,mBACA,iBACA,QACA,aACA,aACA,eACA,eACA,cACA,cACA,mBACA,YACA,MACA,OACA,YACA,QACA,SACA,OACA,MACA,OACA,aACA,SACA,WACA,UACA,QACA,SACA,cACA,SACA,WACA,cACA,OACA,aACA,sBACA,mBACA,eACA,SACA,gBACA,sBACA,iBACA,IACA,KACA,KACA,SACA,OACA,OACA,cACA,YACA,UACA,SACA,SACA,QACA,OACA,kBACA,QACA,mBACA,mBACA,eACA,cACA,eACA,cACA,aACA,eACA,mBACA,oBACA,iBACA,kBACA,oBACA,iBACA,SACA,eACA,QACA,eACA,iBACA,WACA,cACA,UACA,UACA,YACA,mBACA,cACA,kBACA,iBACA,aACA,OACA,KACA,KACA,UACA,SACA,UACA,aACA,UACA,aACA,gBACA,gBACA,QACA,eACA,OACA,eACA,mBACA,mBACA,IACA,KACA,KACA,QACA,IACA,KACA,KACA,IACA,YAAY,CACJ,EAEGiF,GAASjF,GAAO,CAC3B,SACA,cACA,QACA,WACA,QACA,eACA,cACA,aACA,aACA,QACA,MACA,UACA,eACA,WACA,QACA,QACA,SACA,OACA,KACA,UACA,SACA,gBACA,SACA,SACA,iBACA,YACA,WACA,c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AAK,EAC1CA,GACF9H,GAAU8H,CAAQ,CAEtB,CAAC",
|
|
6
6
|
"names": ["require_ms", "__commonJSMin", "exports", "module", "s", "m", "h", "d", "w", "y", "val", "options", "type", "parse", "fmtLong", "fmtShort", "str", "match", "n", "ms", "msAbs", "plural", "name", "isPlural", "require_common", "__commonJSMin", "exports", "module", "setup", "env", "createDebug", "coerce", "disable", "enable", "enabled", "destroy", "key", "selectColor", "namespace", "hash", "i", "prevTime", "enableOverride", "namespacesCache", "enabledCache", "debug", "args", "self", "curr", "ms", "index", "match", "format", "formatter", "val", "extend", "v", "delimiter", "newDebug", "namespaces", "split", "ns", "matchesTemplate", "search", "template", "searchIndex", "templateIndex", "starIndex", "matchIndex", "name", "skip", "require_browser", "__commonJSMin", "exports", "module", "formatArgs", "save", "load", "useColors", "localstorage", "warned", "m", "args", "c", "index", "lastC", "match", "namespaces", "formatters", "v", "error", "global", "globalThis", "trustedTypes", "policy", "createPolicy", "createHTML", "s", "boundAttributeSuffix", "marker", "Math", "random", "toFixed", "slice", "markerMatch", "nodeMarker", "d", "document", "createMarker", "createComment", "isPrimitive", "value", "isArray", "Array", "isIterable", "Symbol", "iterator", "SPACE_CHAR", "textEndRegex", "commentEndRegex", "comment2EndRegex", "tagEndRegex", "RegExp", "singleQuoteAttrEndRegex", "doubleQuoteAttrEndRegex", "rawTextElement", "tag", "type", "strings", "values", "_$litType$", "html", "svg", "mathml", "noChange", "for", "nothing", "templateCache", "WeakMap", "walker", "createTreeWalker", "trustFromTemplateString", "tsa", "stringFromTSA", "hasOwnProperty", "Error", "getTemplateHtml", "l", "length", "attrNames", "rawTextEndRegex", "regex", "i", "attrName", "match", "attrNameEndIndex", "lastIndex", "exec", "test", "end", "startsWith", "push", "Template", "constructor", "options", "node", "this", "parts", "nodeIndex", "attrNameIndex", "partCount", "el", "createElement", "currentNode", "content", "wrapper", "firstChild", "replaceWith", "childNodes", "nextNode", "nodeType", "hasAttributes", "name", "getAttributeNames", "endsWith", "realName", "statics", "getAttribute", "split", "m", "index", "ctor", "PropertyPart", "BooleanAttributePart", "EventPart", "AttributePart", "removeAttribute", "tagName", "textContent", "emptyScript", "append", "data", "indexOf", "_options", "innerHTML", "resolveDirective", "part", "parent", "attributeIndex", "currentDirective", "__directives", "__directive", "nextDirectiveConstructor", "_$initialize", "_$resolve", "TemplateInstance", "template", "_$parts", "_$disconnectableChildren", "_$template", "_$parent", "parentNode", "_$isConnected", "fragment", "creationScope", "importNode", "partIndex", "templatePart", "ChildPart", "nextSibling", "ElementPart", "_$setValue", "__isConnected", "startNode", "endNode", "_$committedValue", "_$startNode", "_$endNode", "isConnected", "directiveParent", "_$clear", "_commitText", "_commitTemplateResult", "_commitNode", "_commitIterable", "insertBefore", "_insert", "createTextNode", "result", "_$getTemplate", "h", "_update", "instance", "_clone", "get", "set", "itemParts", "itemPart", "item", "start", "from", "_$notifyConnectionChanged", "n", "remove", "element", "fill", "String", "valueIndex", "noCommit", "change", "v", "_commitValue", "setAttribute", "toggleAttribute", "super", "newListener", "oldListener", "shouldRemoveListener", "capture", "once", "passive", "shouldAddListener", "removeEventListener", "addEventListener", "event", "call", "host", "handleEvent", "polyfillSupport", "global", "litHtmlPolyfillSupport", "Template", "ChildPart", "litHtmlVersions", "push", "render", "value", "container", "options", "partOwnerNode", "renderBefore", "part", "endNode", "insertBefore", "createMarker", "_$setValue", "cmpPriorityThenCreated", "a", "b", "pa", "pb", "ca", "cb", "ida", "idb", "cmpClosedDesc", "createListSelectors", "issue_stores", "selectIssuesFor", "client_id", "cmpPriorityThenCreated", "selectBoardColumn", "mode", "arr", "cmpClosedDesc", "selectEpicChildren", "epic_id", "epic", "it", "subscribe", "fn", "import_debug", "debug", "ns", "createDebug", "createDataLayer", "transport", "log", "debug", "updateIssue", "input", "id", "last", "createSubscriptionIssueStore", "id", "options", "log", "debug", "items_by_id", "ordered", "last_revision", "listeners", "is_disposed", "sort", "cmpPriorityThenCreated", "emit", "fn", "rebuildOrdered", "applyPush", "msg", "rev", "items", "it", "existing", "prev_ts", "next_ts", "k", "v", "rid", "xid", "subKeyOf", "spec", "type", "flat", "keys", "k", "v", "enc", "createSubscriptionStore", "send", "log", "debug", "subs_by_id", "ids_by_key", "applyDelta", "key", "delta", "id_set", "added", "updated", "removed", "client_id", "entry", "items", "id", "subscribeList", "prev", "prev_ids", "set", "err", "subscribers", "s", "out", "createSubscriptionIssueStores", "log", "debug", "stores_by_id", "key_by_id", "listeners", "store_unsubs", "emit", "fn", "register", "client_id", "spec", "options", "next_key", "subKeyOf", "prev_key", "has_store", "prev_store", "off_prev", "new_store", "createSubscriptionIssueStore", "off_new", "store", "off", "unregister", "s", "issueHashFor", "view", "id", "parseHash", "hash", "h", "frag", "qIndex", "query", "id", "m", "parseView", "createHashRouter", "store", "log", "debug", "onHashChange", "legacyMatch", "next", "view", "issueHashFor", "createStore", "initial", "log", "debug", "state", "subs", "emit", "fn", "patch", "next", "workspace_changed", "createActivityIndicator", "mount_element", "log", "debug", "pending_count", "active_requests", "next_request_id", "render", "is_active", "start", "done", "prev", "wrapSend", "send_fn", "type", "payload", "req_id", "start_ts", "completed", "markComplete", "timeout_id", "result", "elapsed", "err", "now", "id", "info", "showToast", "text", "variant", "duration_ms", "el", "createIssueIdRenderer", "id", "opts", "duration", "btn", "doCopy", "copied", "ta", "container", "oldAria", "ev", "priority_levels", "createPriorityBadge", "priority", "p", "el", "label", "labelForPriority", "emojiForPriority", "i", "priority_levels", "createTypeBadge", "issue_type", "el", "KNOWN", "kind", "label", "COLUMN_STATUS_MAP", "createBoardView", "mount_element", "_data", "gotoIssue", "store", "subscriptions", "issueStores", "transport", "log", "debug", "list_ready", "list_blocked", "list_in_progress", "list_closed", "list_closed_raw", "selectors", "createListSelectors", "closed_filter_mode", "s", "cf", "template", "x", "columnTemplate", "title", "id", "items", "item_count", "count_label", "onClosedFilterChange", "it", "cardTemplate", "ev", "onCardClick", "onDragStart", "onDragEnd", "createTypeBadge", "createPriorityBadge", "createIssueIdRenderer", "dragging_id", "clearDropTarget", "all_cols", "c", "updateIssueStatus", "issue_id", "new_status", "showToast", "err", "doRender", "B", "postRenderEnhance", "columns", "col", "body", "cards", "header", "col_name", "card", "title_el", "t", "target", "tag", "key", "idx", "moveFocus", "cols", "col_idx", "dir", "next_idx", "target_col", "candidate", "c_body", "first", "current_drop_target", "related", "col_id", "from", "to", "applyClosedFilter", "now", "since_ts", "cmpClosedDesc", "el", "v", "refreshFromStores", "in_progress", "blocked", "ready_raw", "closed", "in_prog_ids", "i", "has_subs", "cnt", "sel", "arr", "total_items", "data", "can_fetch", "blocked_raw", "in_prog_raw", "closed_raw", "ready", "in_prog", "in_progress_ids", "cmpPriorityThenCreated", "entries", "setPrototypeOf", "isFrozen", "getPrototypeOf", "getOwnPropertyDescriptor", "Object", "freeze", "seal", "create", "apply", "construct", "Reflect", "x", "func", "thisArg", "_len", "arguments", "length", "args", "Array", "_key", "Func", "_len2", "_key2", "arrayForEach", "unapply", "prototype", "forEach", "arrayLastIndexOf", "lastIndexOf", "arrayPop", "pop", "arrayPush", "push", "arraySplice", "splice", "stringToLowerCase", "String", "toLowerCase", "stringToString", "toString", "stringMatch", "match", "stringReplace", "replace", "stringIndexOf", "indexOf", "stringTrim", "trim", "objectHasOwnProperty", "hasOwnProperty", "regExpTest", "RegExp", "test", "typeErrorCreate", "unconstruct", "TypeError", "lastIndex", "_len3", "_key3", "_len4", "_key4", "addToSet", "set", "array", "transformCaseFunc", "l", "element", "lcElement", "cleanArray", "index", "clone", "object", "newObject", "property", "value", "isArray", "constructor", "lookupGetter", "prop", "desc", "get", "fallbackValue", "html", "svg", "svgFilters", "svgDisallowed", "mathMl", "mathMlDisallowed", "text", "xml", "MUSTACHE_EXPR", "ERB_EXPR", "TMPLIT_EXPR", "DATA_ATTR", "ARIA_ATTR", "IS_ALLOWED_URI", "IS_SCRIPT_OR_DATA", "ATTR_WHITESPACE", "DOCTYPE_NAME", "CUSTOM_ELEMENT", "NODE_TYPE", "attribute", "cdataSection", "entityReference", "entityNode", "progressingInstruction", "comment", "document", "documentType", "documentFragment", "notation", "getGlobal", "window", "_createTrustedTypesPolicy", "trustedTypes", "purifyHostElement", "createPolicy", "suffix", "ATTR_NAME", "hasAttribute", "getAttribute", "policyName", "createHTML", "createScriptURL", "scriptUrl", "console", "warn", "_createHooksMap", "afterSanitizeAttributes", "afterSanitizeElements", "afterSanitizeShadowDOM", "beforeSanitizeAttributes", "beforeSanitizeElements", "beforeSanitizeShadowDOM", "uponSanitizeAttribute", "uponSanitizeElement", "uponSanitizeShadowNode", "createDOMPurify", "undefined", "DOMPurify", "root", "version", "VERSION", "removed", "nodeType", "Element", "isSupported", "originalDocument", "currentScript", "DocumentFragment", "HTMLTemplateElement", "Node", "NodeFilter", "NamedNodeMap", "MozNamedAttrMap", "HTMLFormElement", "DOMParser", "ElementPrototype", "cloneNode", "remove", "getNextSibling", "getChildNodes", "getParentNode", "template", "createElement", "content", "ownerDocument", "trustedTypesPolicy", "emptyHTML", "implementation", "createNodeIterator", "createDocumentFragment", "getElementsByTagName", "importNode", "hooks", "createHTMLDocument", "EXPRESSIONS", "ALLOWED_TAGS", "DEFAULT_ALLOWED_TAGS", "TAGS", "ALLOWED_ATTR", "DEFAULT_ALLOWED_ATTR", "ATTRS", "CUSTOM_ELEMENT_HANDLING", "tagNameCheck", "writable", "configurable", "enumerable", "attributeNameCheck", "allowCustomizedBuiltInElements", "FORBID_TAGS", "FORBID_ATTR", "EXTRA_ELEMENT_HANDLING", "tagCheck", "attributeCheck", "ALLOW_ARIA_ATTR", "ALLOW_DATA_ATTR", "ALLOW_UNKNOWN_PROTOCOLS", "ALLOW_SELF_CLOSE_IN_ATTR", "SAFE_FOR_TEMPLATES", "SAFE_FOR_XML", "WHOLE_DOCUMENT", "SET_CONFIG", "FORCE_BODY", "RETURN_DOM", "RETURN_DOM_FRAGMENT", "RETURN_TRUSTED_TYPE", "SANITIZE_DOM", "SANITIZE_NAMED_PROPS", "SANITIZE_NAMED_PROPS_PREFIX", "KEEP_CONTENT", "IN_PLACE", "USE_PROFILES", "FORBID_CONTENTS", "DEFAULT_FORBID_CONTENTS", "DATA_URI_TAGS", "DEFAULT_DATA_URI_TAGS", "URI_SAFE_ATTRIBUTES", "DEFAULT_URI_SAFE_ATTRIBUTES", "MATHML_NAMESPACE", "SVG_NAMESPACE", "HTML_NAMESPACE", "NAMESPACE", "IS_EMPTY_INPUT", "ALLOWED_NAMESPACES", "DEFAULT_ALLOWED_NAMESPACES", "MATHML_TEXT_INTEGRATION_POINTS", "HTML_INTEGRATION_POINTS", "COMMON_SVG_AND_HTML_ELEMENTS", "PARSER_MEDIA_TYPE", "SUPPORTED_PARSER_MEDIA_TYPES", "DEFAULT_PARSER_MEDIA_TYPE", "CONFIG", "formElement", "isRegexOrFunction", "testValue", "Function", "_parseConfig", "cfg", "ADD_URI_SAFE_ATTR", "ADD_DATA_URI_TAGS", "ALLOWED_URI_REGEXP", "ADD_TAGS", "ADD_ATTR", "table", "tbody", "TRUSTED_TYPES_POLICY", "ALL_SVG_TAGS", "ALL_MATHML_TAGS", "_checkValidNamespace", "parent", "tagName", "namespaceURI", "parentTagName", "Boolean", "_forceRemove", "node", "removeChild", "_removeAttribute", "name", "getAttributeNode", "from", "removeAttribute", "setAttribute", "_initDocument", "dirty", "doc", "leadingWhitespace", "matches", "dirtyPayload", "parseFromString", "documentElement", "createDocument", "innerHTML", "body", "insertBefore", "createTextNode", "childNodes", "call", "_createNodeIterator", "SHOW_ELEMENT", "SHOW_COMMENT", "SHOW_TEXT", "SHOW_PROCESSING_INSTRUCTION", "SHOW_CDATA_SECTION", "_isClobbered", "nodeName", "textContent", "attributes", "hasChildNodes", "_isNode", "_executeHooks", "currentNode", "data", "hook", "_sanitizeElements", "allowedTags", "firstElementChild", "_isBasicCustomElement", "parentNode", "childCount", "i", "childClone", "__removalCount", "expr", "_isValidAttribute", "lcTag", "lcName", "_sanitizeAttributes", "hookEvent", "attrName", "attrValue", "keepAttr", "allowedAttributes", "forceKeepAttr", "attr", "initValue", "getAttributeType", "setAttributeNS", "_sanitizeShadowDOM", "fragment", "shadowNode", "shadowIterator", "nextNode", "sanitize", "importedNode", "returnNode", "appendChild", "firstChild", "nodeIterator", "shadowroot", "shadowrootmode", "serializedHTML", "outerHTML", "doctype", "setConfig", "clearConfig", "isValidAttribute", "tag", "addHook", "entryPoint", "hookFunction", "removeHook", "removeHooks", "removeAllHooks", "purify", "PartType", "ATTRIBUTE", "CHILD", "PROPERTY", "BOOLEAN_ATTRIBUTE", "EVENT", "ELEMENT", "directive", "c", "values", "_$litDirective$", "Directive", "_partInfo", "_$isConnected", "this", "_$parent", "part", "parent", "attributeIndex", "__part", "__attributeIndex", "props", "update", "_part", "render", "UnsafeHTMLDirective", "Directive", "partInfo", "super", "this", "_value", "nothing", "type", "PartType", "CHILD", "Error", "constructor", "directiveName", "value", "_templateResult", "noChange", "strings", "raw", "_$litType$", "resultType", "values", "unsafeHTML", "directive", "_getDefaults", "_defaults", "changeDefaults", "newDefaults", "noopTest", "edit", "regex", "opt", "source", "obj", "name", "val", "valSource", "other", "supportsLookbehind", "bull", "indent", "newline", "blockCode", "fences", "hr", "heading", "bullet", "lheadingCore", "lheading", "lheadingGfm", "_paragraph", "blockText", "_blockLabel", "def", "list", "_tag", "_comment", "html", "paragraph", "blockquote", "blockNormal", "gfmTable", "blockGfm", "blockPedantic", "escape", "inlineCode", "br", "inlineText", "_punctuation", "_punctuationOrSpace", "_notPunctuationOrSpace", "punctuation", "_punctuationGfmStrongEm", "_punctuationOrSpaceGfmStrongEm", "_notPunctuationOrSpaceGfmStrongEm", "blockSkip", "emStrongLDelimCore", "emStrongLDelim", "emStrongLDelimGfm", "emStrongRDelimAstCore", "emStrongRDelimAst", "emStrongRDelimAstGfm", "emStrongRDelimUnd", "anyPunctuation", "autolink", "_inlineComment", "tag", "_inlineLabel", "link", "reflink", "nolink", "reflinkSearch", "_caseInsensitiveProtocol", "inlineNormal", "inlinePedantic", "inlineGfm", "inlineBreaks", "block", "inline", "escapeReplacements", "getEscapeReplacement", "ch", "encode", "cleanUrl", "href", "splitCells", "tableRow", "count", "row", "match", "offset", "str", "escaped", "curr", "cells", "i", "rtrim", "c", "invert", "l", "suffLen", "currChar", "findClosingBracket", "b", "level", "outputLink", "cap", "raw", "lexer", "rules", "title", "text", "token", "indentCodeCompensation", "matchIndentToCode", "indentToCode", "node", "matchIndentInNode", "indentInNode", "_Tokenizer", "options", "__publicField", "src", "trimmed", "lines", "tokens", "inBlockquote", "currentLines", "currentRaw", "currentText", "top", "lastToken", "oldToken", "newText", "newToken", "isordered", "itemRegex", "endsWithBlankLine", "endEarly", "itemContents", "line", "t", "nextLine", "blankLine", "nextBulletRegex", "hrRegex", "fencesBeginRegex", "headingBeginRegex", "htmlBeginRegex", "rawLine", "nextLineWithoutTabs", "lastItem", "item", "taskRaw", "checkboxToken", "spacers", "hasMultipleLineBreaks", "headers", "aligns", "rows", "align", "cell", "trimmedUrl", "rtrimSlash", "lastParenIndex", "linkLen", "links", "linkString", "maskedSrc", "prevChar", "lLength", "rDelim", "rLength", "delimTotal", "midDelimTotal", "endReg", "lastCharLength", "hasNonSpaceChars", "hasSpaceCharsOnBothEnds", "prevCapZero", "_Lexer", "__Lexer", "next", "lastParagraphClipped", "extTokenizer", "cutSrc", "startIndex", "tempSrc", "tempStart", "getStartIndex", "errMsg", "keepPrevChar", "_Renderer", "lang", "langString", "code", "depth", "ordered", "start", "body", "j", "type", "startAttr", "checked", "header", "k", "content", "cleanHref", "out", "_TextRenderer", "_Parser", "__Parser", "anyToken", "genericToken", "ret", "renderer", "_Hooks", "_a", "markdown", "Marked", "args", "callback", "values", "tableToken", "listToken", "childTokens", "extensions", "pack", "opts", "ext", "prevRenderer", "extLevel", "prop", "rendererProp", "rendererFunc", "tokenizer", "tokenizerProp", "tokenizerFunc", "prevTokenizer", "hooks", "hooksProp", "hooksFunc", "prevHook", "arg", "walkTokens", "packWalktokens", "blockType", "origOpt", "throwError", "processedSrc", "processedTokens", "e", "silent", "async", "msg", "markedInstance", "marked", "setOptions", "use", "parseInline", "parser", "_Parser", "lexer", "_Lexer", "renderMarkdown", "markdown", "parsed", "d", "html_string", "purify", "o", "statusLabel", "status", "formatCommentDate", "dateStr", "defaultNavigateFn", "hash", "createDetailView", "mount_element", "sendFn", "navigateFn", "issue_stores", "log", "debug", "current", "current_id", "pending", "edit_title", "edit_desc", "edit_design", "edit_notes", "edit_accept", "edit_assignee", "new_label_text", "comment_text", "comment_pending", "delete_dialog", "ensureDeleteDialog", "openDeleteDialog", "dialog", "issueId", "issueTitle", "cancelBtn", "confirmBtn", "performDelete", "ev", "id", "doRender", "view", "parseView", "err", "showToast", "onDeleteClick", "issueHref", "issueHashFor", "renderPlaceholder", "message", "B", "x", "refreshFromStore", "arr", "it", "onTitleSpanClick", "onTitleKeydown", "onTitleSave", "input", "prev", "next", "updated", "onTitleCancel", "onAssigneeSpanClick", "onAssigneeKeydown", "onAssigneeSave", "onAssigneeCancel", "onLabelInput", "onLabelKeydown", "e", "onAddLabel", "text", "onRemoveLabel", "label", "onStatusChange", "sel", "onPriorityChange", "onDescEdit", "onDescKeydown", "btn", "onDescSave", "ta", "onDescCancel", "onDesignEdit", "onDesignKeydown", "onDesignSave", "onDesignCancel", "onNotesEdit", "onNotesKeydown", "onNotesSave", "onNotesCancel", "onAcceptEdit", "onAcceptKeydown", "onAcceptSave", "onAcceptCancel", "onCommentInput", "el", "prev_has_text", "has_text", "onCommentSubmit", "result", "onCommentKeydown", "depsSection", "title", "items", "test_id", "dep", "did", "href", "createTypeBadge", "makeDepRemoveClick", "makeDepAddClick", "detailTemplate", "issue", "title_zone", "onTitleInputKeydown", "status_select", "cur", "s", "statusLabel", "priority_select", "priority_levels", "p", "i", "emojiForPriority", "desc_block", "onDescEditableKeydown", "renderMarkdown", "acceptance_text", "any_issue", "accept_block", "has", "onAcceptEditableKeydown", "notes_text", "notes_block", "onNotesEditableKeydown", "labels", "labels_block", "l", "design_text", "design_block", "onDesignEditableKeydown", "comments", "comments_block", "c", "raw", "target", "d", "createIssueRowRenderer", "options", "navigate", "on_update", "request_render", "get_selected_id", "row_class", "editing", "editableText", "id", "key", "value", "placeholder", "k", "x", "e", "next", "ev", "makeSelectChange", "val", "patch", "makeRowClick", "el", "rowTemplate", "it", "cur_status", "cur_prio", "is_selected", "createIssueIdRenderer", "createTypeBadge", "s", "statusLabel", "priority_levels", "p", "i", "emojiForPriority", "createEpicsView", "mount_element", "data", "goto_issue", "subscriptions", "issue_stores", "groups", "expanded", "loading", "epic_unsubs", "selectors", "createListSelectors", "had_none", "buildGroupsFromSnapshot", "doRender", "first_id", "toggle", "renderRow", "createIssueRowRenderer", "id", "updateInline", "B", "template", "x", "g", "groupTemplate", "epic", "is_open", "list", "is_loading", "createIssueIdRenderer", "it", "patch", "epic_id", "u", "epic_entities", "next_groups", "dependents", "has_total", "has_closed", "total", "closed", "d", "createFatalErrorDialog", "mount_element", "dialog", "title_el", "message_el", "detail_el", "reload_btn", "close_btn", "close", "open", "title", "message", "detail", "detail_text", "ev", "createIssueDialog", "mount_element", "store", "onClose", "dialog", "body_mount", "title_el", "btn_close", "setTitle", "id", "createIssueIdRenderer", "ev", "requestClose", "last_focus", "restoreFocus", "open", "ae", "close", "ISSUE_TYPES", "typeLabel", "type", "createListView", "mount_element", "sendFn", "navigateFn", "store", "_subscriptions", "issue_stores", "log", "debug", "status_filters", "search_text", "issues_cache", "type_filters", "selected_id", "unsubscribe", "status_dropdown_open", "type_dropdown_open", "normalizeStatusFilter", "val", "normalizeTypeFilter", "row_renderer", "createIssueRowRenderer", "id", "nav", "h", "view", "issueHashFor", "updateInline", "doRender", "toggleStatusFilter", "status", "s", "load", "onSearchInput", "ev", "toggleTypeFilter", "type", "t", "toggleStatusDropdown", "e", "toggleTypeDropdown", "getDropdownDisplayText", "selected", "label", "formatter", "selectors", "createListSelectors", "template", "filtered", "it", "needle", "a", "b", "cmpClosedDesc", "x", "statusLabel", "typeLabel", "ISSUE_TYPES", "B", "patch", "beforeEl", "prevScroll", "err", "afterEl", "tgt", "cell", "row", "tbody", "rows", "row_idx", "col_idx", "next_idx", "next_row", "next_cell", "focusable", "items", "idx", "el", "next", "next_id", "set", "prev", "prev_id", "current", "clickOutsideHandler", "target", "next_status", "next_search", "needs_render", "next_type_arr", "createTopNav", "mount_element", "store", "router", "log", "debug", "unsubscribe", "onClick", "view", "ev", "template", "active", "x", "doRender", "B", "createNewIssueDialog", "mount_element", "sendFn", "router", "store", "dialog", "form", "input_title", "sel_type", "sel_priority", "input_labels", "input_description", "error_box", "btn_cancel", "btn_create", "btn_close", "populateSelects", "optEmpty", "t", "ISSUE_TYPES", "o", "typeLabel", "i", "label", "priority_levels", "requestClose", "setBusy", "is_busy", "clearError", "setError", "msg", "loadDefaults", "p", "saveDefaults", "idNumeric", "id", "m", "createNow", "title", "prio", "type", "desc", "labels", "s", "payload", "list", "created_id", "matches", "it", "best", "ai", "ev", "getProjectName", "workspace_path", "parts", "createWorkspacePicker", "mount_element", "store", "onWorkspaceChange", "log", "debug", "unsubscribe", "is_switching", "onChange", "ev", "new_path", "current_path", "doRender", "err", "template", "s", "current", "available", "x", "name", "ws", "B", "MESSAGE_TYPES", "nextId", "now", "rand", "makeRequest", "type", "payload", "id", "createWsClient", "options", "log", "debug", "backoff", "resolveUrl", "ws", "state", "attempts", "reconnect_timer", "should_reconnect", "pending", "queue", "handlers", "connection_handlers", "notifyConnection", "s", "fn", "scheduleReconnect", "base", "jitter", "delay", "connect", "sendRaw", "req", "err", "onOpen", "onMessage", "ev", "msg", "entry", "set", "onClose", "id", "p", "url", "type", "payload", "MESSAGE_TYPES", "nextId", "makeRequest", "resolve", "reject", "handler", "bootstrap", "root_element", "log", "debug", "shell", "x", "B", "nav_mount", "issues_root", "epics_root", "board_root", "list_mount", "detail_mount", "showFatalFromError", "err", "context", "message", "detail", "any", "title", "fatal_dialog", "getProjectName", "path", "parts", "computeIssuesSpec", "filters", "st", "ensureTabSubscriptions", "s", "spec", "key", "sub_issue_stores", "issues_sub_key", "unsub_issues_tab", "last_issues_spec_key", "pending_subscriptions", "subscriptions", "unsub", "unsub_epics_tab", "unsub_board_ready", "u", "unsub_board_in_progress", "unsub_board_closed", "unsub_board_blocked", "header_loading", "activity", "createActivityIndicator", "createFatalErrorDialog", "client", "createWsClient", "tracked_send", "type", "payload", "createSubscriptionStore", "createSubscriptionIssueStores", "p", "id", "store", "listSelectors", "createListSelectors", "clearAndResubscribe", "storeIds", "handleWorkspaceChange", "workspace_path", "result", "showToast", "loadWorkspaces", "available", "ws", "current", "savedWorkspace", "had_disconnect", "onConn", "persisted_filters", "raw", "obj", "ALLOWED", "parsed_type", "first_valid", "it", "last_view", "raw_view", "persistedBoard", "raw_board", "cf", "createStore", "router", "createHashRouter", "transport", "createTopNav", "workspace_mount", "createWorkspacePicker", "new_issue_dialog", "createNewIssueDialog", "btn_new", "issues_view", "createListView", "hash", "parseHash", "data", "dialog", "createIssueDialog", "v", "createDetailView", "view", "parseView", "initial_id", "client_id", "unsub_detail", "createDataLayer", "epics_view", "createEpicsView", "board_view", "createBoardView", "onRouteChange", "ev", "is_modifier", "target", "tag", "is_editable", "saved", "prefersDark", "initial", "sw", "themeSwitch", "mode", "app_root"]
|
|
7
7
|
}
|