@inkandswitch/patchwork-pkg-base 0.0.73 → 0.0.74

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.
Files changed (31) hide show
  1. package/module-settings-url +1 -1
  2. package/package.json +1 -1
  3. package/packages/chat/dist/{ChatRoot-BRiX2ym6.js → ChatRoot-BYmq4SXi.js} +3541 -6287
  4. package/packages/chat/dist/{context-tool-CAHkp64h.js → context-tool-Bob-FZ_T.js} +2 -2
  5. package/packages/chat/dist/{index-Bt9HfG9I.js → index-wkaHcVCz.js} +3 -3
  6. package/packages/chat/dist/index.js +1 -1
  7. package/packages/chat/dist/{tool-DoxHbcfW.js → tool-DCOdh_fx.js} +1 -1
  8. package/packages/chat/package.json +3 -3
  9. package/packages/isolation/dist/assets/{component-DA0d3480.js → component-Daum8ibW.js} +118 -240
  10. package/packages/isolation/dist/assets/component-Daum8ibW.js.map +1 -0
  11. package/packages/isolation/dist/index.js +1 -1
  12. package/packages/threepane/dist/IsolatedDocumentArea-54ZI7TNY.js +2 -0
  13. package/packages/threepane/dist/PatchworkFrame-REYVVXOP.js +2 -0
  14. package/packages/threepane/dist/PatchworkFrame-REYVVXOP.js.map +7 -0
  15. package/packages/threepane/dist/{chunk-FX3MJIE5.js → chunk-DV7PRUYR.js} +3 -3
  16. package/packages/threepane/dist/chunk-DV7PRUYR.js.map +7 -0
  17. package/packages/threepane/dist/chunk-ESMUVHPH.js +2 -0
  18. package/packages/threepane/dist/chunk-ESMUVHPH.js.map +7 -0
  19. package/packages/threepane/dist/{datatypes-WPL4KARJ.js → datatypes-5DFL6VIN.js} +2 -2
  20. package/packages/threepane/dist/index.js +1 -1
  21. package/plugin-registry-url +1 -1
  22. package/packages/chat/dist/assets/worker-CFUOJ0Hd.js +0 -9
  23. package/packages/isolation/dist/assets/component-DA0d3480.js.map +0 -1
  24. package/packages/threepane/dist/IsolatedDocumentArea-MSJE4GCW.js +0 -2
  25. package/packages/threepane/dist/PatchworkFrame-3XYJCU3F.js +0 -2
  26. package/packages/threepane/dist/PatchworkFrame-3XYJCU3F.js.map +0 -7
  27. package/packages/threepane/dist/chunk-2NJMYYSD.js +0 -2
  28. package/packages/threepane/dist/chunk-2NJMYYSD.js.map +0 -7
  29. package/packages/threepane/dist/chunk-FX3MJIE5.js.map +0 -7
  30. /package/packages/threepane/dist/{IsolatedDocumentArea-MSJE4GCW.js.map → IsolatedDocumentArea-54ZI7TNY.js.map} +0 -0
  31. /package/packages/threepane/dist/{datatypes-WPL4KARJ.js.map → datatypes-5DFL6VIN.js.map} +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"file":"component-DA0d3480.js","sources":["../../node_modules/.pnpm/ms@2.1.3/node_modules/ms/index.js","../../node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/common.js","../../node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/browser.js","../../src/log.ts","../../src/bridges/repo-bridge.ts","../../src/bridges/registry-bridge.ts","../../src/bridges/resource-bridge.ts","../../src/bridges/access-control.ts","../../src/bridges/navigation-bridge.ts","../../src/bridges/drag-drop-bridge.ts","../../src/bridges/providers-bridge.ts","../../src/boot/iframe/main.ts","../../src/boot/iframe/local-storage.ts","../../src/boot/iframe/fetch-proxy.ts","../../src/boot/iframe/link-interception.ts","../../src/boot/iframe/rpc.ts","../../src/boot/iframe/providers-bridge.ts","../../src/boot/iframe/es-module-shims.ts","../../src/boot/iframe/worker-shim.ts","../../src/boot/iframe/worker-bootstrap.ts","../../src/boot/iframe/registry.ts","../../src/boot/iframe/root-component-data.ts","../../src/boot/iframe/drag-drop.ts","../../src/boot/host/srcdoc.ts","../../src/boot/host/styles.ts","../../src/esms-source.generated.ts","../../src/boot/host/assets.ts","../../src/boot/host/import-map.ts","../../src/boot/host/config.ts","../../src/boot/host/boot.ts","../../src/component.ts"],"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","import debug from \"debug\";\n\n/** Shared debug logger for the isolation boundary (host side). */\nexport const log = debug(\"patchwork:elements:isolation\");\n","/**\n * Creates an ephemeral intermediary Repo that sits between the host's main\n * Repo and an isolated iframe's Repo. It enforces an allowlist of document\n * URLs — only documents the user has authorized can sync to the iframe.\n *\n * Access control uses `shareConfig` on the intermediary Repo with `access()`\n * and `announce()` callbacks that gate per-document sync:\n * - `access`: gates ALL peers (including host) by allowlist — the intermediary\n * never holds non-allowlisted documents in memory\n * - `announce`: only announces allowlisted documents\n *\n * The intermediary has no persistent storage (`isEphemeral: true`).\n */\nimport {\n Repo,\n type AutomergeUrl,\n type PeerId,\n type DocumentId,\n parseAutomergeUrl,\n} from \"@automerge/automerge-repo/slim\";\nimport { MessageChannelNetworkAdapter } from \"@automerge/automerge-repo-network-messagechannel\";\nimport { log } from \"../log.js\";\n\n/**\n * A set of document IDs, addable by either automerge URL or raw document ID,\n * queryable by either. The allowlist and denylist are both just such sets\n * gated against by the intermediary repo's shareConfig — they differ only in\n * meaning, so they share this base. Kept as distinct named subclasses below so\n * the security-meaningful names (and their types) stay explicit at call sites.\n */\nclass SyncDocumentSet {\n #ids = new Set<DocumentId>();\n\n add(url: AutomergeUrl): void {\n const { documentId } = parseAutomergeUrl(url);\n this.#ids.add(documentId);\n }\n\n addDocumentId(documentId: DocumentId): void {\n this.#ids.add(documentId);\n }\n\n has(documentId: DocumentId): boolean {\n return this.#ids.has(documentId);\n }\n\n hasUrl(url: AutomergeUrl): boolean {\n const { documentId } = parseAutomergeUrl(url);\n return this.#ids.has(documentId);\n }\n\n get size(): number {\n return this.#ids.size;\n }\n}\n\n/**\n * Document IDs the iframe is allowed to sync. Used by the intermediary repo's\n * shareConfig to gate document access.\n */\nexport class SyncAllowlist extends SyncDocumentSet {}\n\n/**\n * Document IDs that must never sync to the iframe, regardless of allowlist\n * status — the denylist takes precedence. Protects sensitive documents: the\n * account doc, module settings, tool/package source code, and branches docs.\n *\n * Unlike the allowlist, the denylist is populated asynchronously (it walks\n * documents to discover the protected set). Callers must not seed the allowlist\n * or sync anything to the iframe until it is fully populated, or a protected\n * doc could slip through before its entry lands. `setReady` records the\n * populate promise; `whenReady()` lets the boot path await it, and the\n * synchronous `isReady` flag lets the per-document sync gate fail closed\n * cheaply (see createIntermediaryRepo).\n */\nexport class SyncDenylist extends SyncDocumentSet {\n // A denylist with no population scheduled is trivially ready (empty but\n // complete). setReady() marks it not-ready until its populate promise lands.\n #ready: Promise<void> = Promise.resolve();\n isReady = true;\n\n /** Record the population promise; not ready until it resolves. */\n setReady(populated: Promise<void>): void {\n this.isReady = false;\n this.#ready = populated.then(() => {\n this.isReady = true;\n });\n }\n\n /** Resolves once population has completed. */\n whenReady(): Promise<void> {\n return this.#ready;\n }\n}\n\nexport interface IntermediaryRepoOptions {\n /** The allowlist controlling which documents can sync to the iframe. */\n allowlist: SyncAllowlist;\n /** The host Repo to sync allowed documents from. */\n hostRepo: Repo;\n /** Optional denylist — denylisted documents are blocked regardless of allowlist. */\n denylist?: SyncDenylist;\n /**\n * Called when the iframe requests a document that's not on the allowlist\n * or denylist. If it returns true, the document is added to the allowlist.\n */\n onAccessRequest?: (documentId: DocumentId) => Promise<boolean>;\n}\n\nexport interface IntermediaryRepo {\n /** Port to hand to the iframe's Repo via MessageChannelNetworkAdapter. */\n iframePort: MessagePort;\n /** Tear down the intermediary repo and close all channels. */\n shutdown(): void;\n}\n\n/**\n * Create an intermediary repo gated by the caller-supplied allowlist and\n * denylist (both already seeded before this runs).\n *\n * Two MessageChannels are created:\n * 1. hostChannel — connects intermediary ↔ host repo\n * 2. iframeChannel — connects intermediary ↔ iframe repo\n *\n * The intermediary's `shareConfig` gates document sync:\n * - Only allowlisted documents are accepted from any peer (including the host)\n * - Only allowlisted documents are announced to the iframe peer\n */\nexport function createIntermediaryRepo(\n options: IntermediaryRepoOptions\n): IntermediaryRepo {\n const { allowlist, hostRepo, denylist, onAccessRequest } = options;\n\n const hostRepoPeerId = hostRepo.peerId;\n\n // Channel connecting intermediary ↔ host repo\n const hostChannel = new MessageChannel();\n const hostAdapter = new MessageChannelNetworkAdapter(hostChannel.port1, {\n useWeakRef: true,\n });\n\n // Channel connecting intermediary ↔ iframe repo\n const iframeChannel = new MessageChannel();\n const iframeAdapter = new MessageChannelNetworkAdapter(iframeChannel.port1, {\n useWeakRef: true,\n });\n\n // The one denylist gate, shared by `announce` and `access` so the two can\n // never drift apart (both must agree for the security invariant to hold).\n // Returns why a document is blocked from crossing to the iframe, or null if\n // the denylist permits it (the caller still applies the allowlist).\n // - \"not-ready\": the denylist hasn't finished populating; fail closed to the\n // iframe so a protected doc can't sync during the population window.\n // Defense in depth — the boot path already awaits readiness before this\n // repo exists, so on the normal path this never fires.\n // - \"denylisted\": the document is in the protected set.\n // The host peer is never gated here; only iframe-bound sync is.\n const denylistBlock = (\n peerId: PeerId,\n documentId: DocumentId\n ): \"not-ready\" | \"denylisted\" | null => {\n if (peerId === hostRepoPeerId) return null;\n if (denylist && !denylist.isReady) return \"not-ready\";\n if (denylist?.has(documentId)) return \"denylisted\";\n return null;\n };\n\n const repo = new Repo({\n peerId: `intermediary-${crypto.randomUUID().slice(0, 8)}` as PeerId,\n network: [hostAdapter, iframeAdapter],\n isEphemeral: true,\n shareConfig: {\n announce: async (peerId: PeerId, documentId?: DocumentId) => {\n if (!documentId) return true;\n if (denylistBlock(peerId, documentId)) return false;\n return allowlist.has(documentId);\n },\n access: async (peerId: PeerId, documentId?: DocumentId) => {\n if (!documentId) return false;\n const blocked = denylistBlock(peerId, documentId);\n if (blocked === \"not-ready\") {\n log(`access ${documentId} BLOCKED (denylist not ready)`);\n return false;\n }\n if (blocked === \"denylisted\") {\n log(`access ${documentId} DENIED`);\n return false;\n }\n if (allowlist.has(documentId)) return true;\n\n // Not allowlisted, not denylisted — prompt the user if this\n // is an iframe request and we have a callback\n if (peerId !== hostRepoPeerId && onAccessRequest) {\n log(`access ${documentId} prompting user`);\n const approved = await onAccessRequest(documentId);\n if (approved) {\n log(`access ${documentId} APPROVED by user`);\n // Re-evaluate share config so previously-denied peers\n // pick up the new allowlist entry\n repo.shareConfigChanged();\n return true;\n }\n log(`access ${documentId} REJECTED by user`);\n return false;\n }\n\n if (peerId !== hostRepoPeerId) {\n log(`access ${documentId} BLOCKED`);\n }\n return false;\n },\n },\n });\n\n // Connect the host repo to the other end of the isolation host channel\n const isolationHostAdapter = new MessageChannelNetworkAdapter(\n hostChannel.port2,\n {\n useWeakRef: true,\n }\n );\n hostRepo.networkSubsystem.addNetworkAdapter(isolationHostAdapter);\n\n return {\n iframePort: iframeChannel.port2,\n\n shutdown() {\n isolationHostAdapter.disconnect();\n hostChannel.port1.close();\n hostChannel.port2.close();\n iframeChannel.port1.close();\n iframeChannel.port2.close();\n },\n };\n}\n","/**\n * Registry bridge — owns *packages*: how a registry (plugin) package is named,\n * located, and served. A package's real location (automerge document ID or\n * external URL) is replaced by an opaque `registry--<sanitized-name>` marker\n * segment so it never crosses into the iframe. The `PackagesUrlMapper` holds this\n * registry-owned mapping; the resource bridge only calls `resolvePackageRequest`.\n *\n * Two phases:\n * - **registration** (`getRegistries` / `watchRegistries`) — produce serializable\n * `RegistryEntry`s with `importUrl` mapped to a marker. One memoized\n * `resolvePackage` per package reads its `package.json` once, resolving the\n * entry + name and registering its baked automerge dependencies.\n * - **serve** — `resolvePackageRequest` maps a marker request back to a fetchable\n * URL; `rewriteServedSource` rewrites baked automerge dep URLs to markers, but\n * only for packages that declared such deps at registration.\n */\n\nimport {\n isValidAutomergeUrl,\n type AutomergeUrl,\n} from \"@automerge/automerge-repo/slim\";\nimport {\n getImportableUrlFromAutomergeUrl,\n resolvePackageExport,\n} from \"@inkandswitch/patchwork-filesystem\";\nimport { getAllRegistries } from \"@inkandswitch/patchwork-plugins\";\nimport type { RegistryEntry } from \"../types.js\";\nimport { log } from \"../log.js\";\n\n/**\n * Prefix of a package marker segment (`registry--<sanitized-name>`). A single\n * path segment with no internal `/`, so it survives the baked-dependency form's\n * `encodeURIComponent` as one segment — see `#markerSegmentFor`.\n */\nexport const REGISTRY_MARKER_PREFIX = \"registry--\";\n\n/**\n * A resolved package, discriminated by hosting so the caller can mint its marker\n * without re-scanning a URL:\n * - **automerge** — bare `automergeUrl` + the entry's `subpath` under the folder\n * (e.g. `dist/index.js`).\n * - **external** — the already-resolved `entryUrl` (plain HTTP(S)).\n *\n * Both carry the package `name` (best-effort, for the marker) and\n * `hasAutomergeDeps` (whether `package.json` declared any `automerge:` deps — the\n * serve path's rewrite gate).\n */\ntype ResolvedPackage = { packageName?: string; hasAutomergeDeps: boolean } & (\n | { hosting: \"automerge\"; automergeUrl: string; subpath: string }\n | { hosting: \"external\"; entryUrl: string }\n);\n\n/** The subset of a tool package's `package.json` this module reads. */\ninterface PackageJson {\n name?: string;\n dependencies?: Record<string, string>;\n}\n\n// ---------------------------------------------------------------------------\n// URL helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Split an automerge URL into its base and trailing heads (version) suffix.\n * Automerge URLs may be pinned to specific heads as `automerge:<id>#<heads>`;\n * `isValidAutomergeUrl` only recognizes the base, so callers strip the heads\n * before validating and restore them afterwards.\n */\nfunction stripHeads(segment: string): { base: string; heads: string } {\n const hashIdx = segment.indexOf(\"#\");\n return hashIdx >= 0\n ? { base: segment.slice(0, hashIdx), heads: segment.slice(hashIdx + 1) }\n : { base: segment, heads: \"\" };\n}\n\n/**\n * Split a marker name-part into `{ pkg, heads }`. The heads suffix arrives as `#`\n * (chunk/entry form) or `%23` (double-encoded baked-dependency form) after one\n * decode by `splitFirstSegment`; a sanitized package name contains neither `#`\n * nor `%`, so splitting on whichever appears first is unambiguous. `heads` excludes\n * its marker (empty if unpinned).\n */\nfunction splitMarkerHeads(namepart: string): { pkg: string; heads: string } {\n const hashIdx = namepart.indexOf(\"#\");\n const pctIdx = namepart.indexOf(\"%23\");\n let idx = -1;\n let markerLen = 0;\n if (hashIdx >= 0 && (pctIdx < 0 || hashIdx < pctIdx)) {\n idx = hashIdx;\n markerLen = 1;\n } else if (pctIdx >= 0) {\n idx = pctIdx;\n markerLen = 3;\n }\n return idx < 0\n ? { pkg: namepart, heads: \"\" }\n : { pkg: namepart.slice(0, idx), heads: namepart.slice(idx + markerLen) };\n}\n\n/**\n * Split a URL into its decoded first path segment and the raw remaining path.\n * The shared primitive behind `classify`, `markerNameFromUrl`, and `resolveMarker`\n * for \"what is this request for\".\n *\n * Security-critical: normalizes via the WHATWG `URL` parser FIRST, so `..`/`.` are\n * collapsed before inspection — a traversal like `<origin>/assets/../automerge:<id>/x`\n * presents `automerge:<id>` as `first` (blocked), rather than sneaking past a raw\n * prefix check. Returns `{ first: \"\", rest: \"\" }` if the URL can't be parsed.\n */\nexport function splitFirstSegment(url: string): { first: string; rest: string } {\n let pathname: string;\n try {\n pathname = new URL(url, window.location.origin).pathname;\n } catch {\n return { first: \"\", rest: \"\" };\n }\n const trimmed = pathname.replace(/^\\/+/, \"\");\n const slashIdx = trimmed.indexOf(\"/\");\n const rawFirst = slashIdx < 0 ? trimmed : trimmed.slice(0, slashIdx);\n const rest = slashIdx < 0 ? \"\" : trimmed.slice(slashIdx + 1);\n let first: string;\n try {\n first = decodeURIComponent(rawFirst);\n } catch {\n first = rawFirst;\n }\n return { first, rest };\n}\n\n// ---------------------------------------------------------------------------\n// PackagesUrlMapper\n// ---------------------------------------------------------------------------\n\n/**\n * Maps real package locations (automerge document IDs or external URLs) to opaque\n * `registry--<name>` marker segments and back. Tool code inside the iframe sees\n * `registry--@patchwork--codemirror-base/dist/index.js`, never a real location —\n * so IDs/locations don't leak, while the marker stays a hierarchical URL for\n * relative import resolution.\n */\nexport class PackagesUrlMapper {\n #counter = 0;\n // Raw automerge URL → package name (e.g., \"automerge:3Dz...\" → \"@patchwork--folder\")\n #automergeToPackage = new Map<string, string>();\n // Package name → raw automerge URL\n #packageToAutomerge = new Map<string, string>();\n // Package name → external package-root URL (ends in \"/\"), for statically-hosted\n // tools. `resolveMarker` appends the request's subpath to it.\n #packageToExternalRoot = new Map<string, string>();\n // importUrl → memoized `resolvePackage` promise, so a package's `package.json`\n // is read once regardless of how many of its plugins register (boot or live).\n #packageResolution = new Map<\n string,\n Promise<ResolvedPackage | undefined>\n >();\n // Marker names of packages that declared automerge deps — the serve path's\n // rewrite gate. Others are served without a source scan.\n #packagesWithAutomergeDeps = new Set<string>();\n\n /**\n * Sanitize a package name for use as a URL path segment.\n * \"@patchwork/folder\" -> \"@patchwork--folder\"\n */\n #sanitizeName(name: string): string {\n return name.replace(/\\//g, \"--\");\n }\n\n /**\n * Resolve a package's `importUrl` once (memoized by `importUrl`, so N plugins of\n * one package cost one `package.json` read), reading `package.json` a single\n * time to find the entry + name and register its `automerge:` deps\n * (`#registerAutomergeDeps`). The caller mints the package marker from the result\n * and records it via `markPackageHasDeps` if `hasAutomergeDeps`.\n *\n * - **automerge** — read the folder's `package.json` and resolve its export;\n * undefined if unreachable.\n * - **external** — the importUrl is already the entry; read `package.json` at\n * the convention-derived root for name + deps (best-effort).\n */\n resolvePackage(importUrl: string): Promise<ResolvedPackage | undefined> {\n let pending = this.#packageResolution.get(importUrl);\n if (!pending) {\n pending = this.#resolvePackageUncached(importUrl);\n this.#packageResolution.set(importUrl, pending);\n }\n return pending;\n }\n\n async #resolvePackageUncached(\n importUrl: string\n ): Promise<ResolvedPackage | undefined> {\n // External: a manifest `importUrl` is either a package *directory*\n // (`.../tools/<name>/`) or a full entry file (`.../dist/index.js`). Mirror\n // the host loader `httpEntryPointUrl`: a URL that already names a module\n // file is the entry as-is (keep the `!namesModuleFile` guard); otherwise\n // fetch package.json at the root and resolve `exports[\".\"]`/`main`. Without\n // this, `encodeExternal` gets a bare directory, mints an empty subpath, and\n // the iframe imports the 404ing directory. Best-effort: on no package.json\n // or no resolvable entry, keep `importUrl` as the entry.\n if (!isValidAutomergeUrl(importUrl)) {\n const root = packageRootFromUrl(importUrl);\n const pkgJson = root ? await fetchPackageJson(root) : undefined;\n const hasAutomergeDeps = this.#registerAutomergeDeps(pkgJson);\n let entryUrl = importUrl;\n if (!namesModuleFile(importUrl) && pkgJson && root) {\n try {\n const entryPoint = resolvePackageExport(pkgJson);\n if (entryPoint) entryUrl = new URL(entryPoint, root).href;\n } catch {\n // no valid exports/main — keep importUrl as the entry (best-effort)\n }\n }\n return {\n hosting: \"external\",\n entryUrl,\n packageName: pkgJson?.name,\n hasAutomergeDeps,\n };\n }\n\n // Automerge: read the folder's package.json, resolve its export. Return the\n // bare automerge URL + entry subpath so the caller mints the marker directly\n // (never embedding the URL just to scan it back out).\n const folderPath = getImportableUrlFromAutomergeUrl(importUrl as AutomergeUrl);\n const base = new URL(folderPath, window.location.origin);\n const pkgJson = await fetchPackageJson(base.href);\n if (!pkgJson) return undefined;\n\n const entryPoint = resolvePackageExport(pkgJson);\n if (!entryPoint) return undefined;\n\n // base.href ends in \"/<encoded-automerge>/\"; the entry resolved against it,\n // minus that prefix, is the subpath (e.g. \"dist/index.js\").\n const subpath = new URL(entryPoint, base).href.slice(base.href.length);\n const hasAutomergeDeps = this.#registerAutomergeDeps(pkgJson);\n return {\n hosting: \"automerge\",\n automergeUrl: importUrl,\n subpath,\n packageName: pkgJson.name,\n hasAutomergeDeps,\n };\n }\n\n /**\n * Register each `automerge:`-valued dependency in `pkgJson` as a dep→marker\n * mapping (for `rewriteAutomergeDepsInSource`), returning whether any were found.\n */\n #registerAutomergeDeps(pkgJson: PackageJson | undefined): boolean {\n let found = false;\n for (const [name, version] of Object.entries(pkgJson?.dependencies ?? {})) {\n const { base } = stripHeads(version);\n if (isValidAutomergeUrl(base)) {\n this.encodeSegment(version, name);\n found = true;\n }\n }\n return found;\n }\n\n /** Record (by marker name) that a package declared automerge deps, so the serve\n * path rewrites its baked dep literals. */\n markPackageHasDeps(markerName: string): void {\n this.#packagesWithAutomergeDeps.add(markerName);\n }\n\n /** Whether `markerName`'s package declared automerge deps — the serve-path\n * rewrite gate. */\n packageNeedsRewrite(markerName: string): boolean {\n return this.#packagesWithAutomergeDeps.has(markerName);\n }\n\n /** The marker name (`registry--<sanitized-name>`) a package maps under, from its\n * package name. Keys `markPackageHasDeps` / `packageNeedsRewrite`. */\n markerNameFor(name: string): string {\n return `${REGISTRY_MARKER_PREFIX}${this.#sanitizeName(name)}`;\n }\n\n /**\n * Register an automerge base under a package name (reusing an existing mapping)\n * and return its marker segment, carrying heads as a `%23<heads>` suffix.\n *\n * Single-segment `registry--<name>` (not `registry/<name>`, not a `pkg:` scheme)\n * is required: the baked-dependency form is `encodeURIComponent`d whole by\n * `getImportableUrlFromAutomergeUrl`, and a segment with no internal `/` survives\n * as one segment — so chunk and dependency forms alike present the marker as the\n * first path segment, and `classify` / `resolveMarker` treat every request\n * uniformly.\n */\n #markerSegmentFor(base: string, heads: string, name?: string): string {\n let pkg = this.#automergeToPackage.get(base);\n if (!pkg) {\n pkg = name ? this.#sanitizeName(name) : `unknown-${this.#counter++}`;\n this.#automergeToPackage.set(base, pkg);\n this.#packageToAutomerge.set(pkg, base);\n }\n const marker = `${REGISTRY_MARKER_PREFIX}${pkg}`;\n return heads ? `${marker}%23${heads}` : marker;\n }\n\n /**\n * Has this automerge base been registered as a dependency? The source rewrite's\n * allowlist: only registered dep URLs are rewritten to markers; a URL a tool\n * fabricated is left raw, so its request stays a raw automerge path `classify`\n * blocks.\n */\n isRegisteredDependency(base: string): boolean {\n return this.#automergeToPackage.has(base);\n }\n\n /**\n * ENCODE (automerge → marker). Map a bare automerge URL (e.g.\n * `automerge:HaCFn…#26oUrk…`) to its bare marker segment\n * (`registry--@chee--patchwork-llm%2326oUrk…`), registering the mapping if new.\n * The single automerge-encoding primitive — used for both package entries and\n * baked `package.json` dependency URLs; the caller (or a runtime\n * `getImportableUrlFromAutomergeUrl` call) appends a subpath and origin-prefixes\n * it, and `resolveMarker` reverses the result. Returns null if not a valid\n * automerge URL.\n */\n encodeSegment(folderUrl: string, name?: string): string | null {\n const { base, heads } = stripHeads(folderUrl);\n if (!isValidAutomergeUrl(base)) return null;\n return this.#markerSegmentFor(base, heads, name);\n }\n\n /**\n * ENCODE (external → marker). Map a statically-hosted package entry URL to a\n * host-origin `registry--<name>` marker URL, registering the package root\n * (derived via `packageRootFromUrl`) if new, so the external location never\n * crosses into the iframe:\n * `https://netlify.app/tool/dist/index.js` → `<origin>/registry--<name>/dist/index.js`.\n * `name` is the package name, so a package's plugins share one marker. Chunk\n * requests under the marker reverse via `resolveMarker`. Returns `entryUrl`\n * unchanged if its root can't be derived.\n */\n encodeExternal(entryUrl: string, name: string): string {\n const root = packageRootFromUrl(entryUrl);\n if (!root) return entryUrl;\n\n const pkg = this.#sanitizeName(name);\n if (!this.#packageToExternalRoot.has(pkg)) {\n this.#packageToExternalRoot.set(pkg, root);\n }\n const marker = `${REGISTRY_MARKER_PREFIX}${pkg}`;\n // entryUrl starts with root (root came from it), so this is a prefix swap.\n const subpath = entryUrl.startsWith(root) ? entryUrl.slice(root.length) : \"\";\n return `${window.location.origin}/${marker}/${subpath}`;\n }\n\n /**\n * RESOLVE (marker → real location). Turn an inbound `registry--<name>` marker\n * request into the real fetchable location — an automerge path (SW-resolvable)\n * or an external URL (fetched directly); null if it carries no known marker.\n *\n * The marker is always the request's first path segment, so we parse it and look\n * the package up by exact name — no scan. A package is in exactly one map;\n * automerge is checked first only for precedence.\n */\n resolveMarker(url: string): string | null {\n const { first, rest } = splitFirstSegment(url);\n if (!first.startsWith(REGISTRY_MARKER_PREFIX)) return null;\n const { pkg, heads } = splitMarkerHeads(\n first.slice(REGISTRY_MARKER_PREFIX.length)\n );\n\n // Automerge: the real automerge URL (+ heads), URL-encoded as the first path\n // segment, then the subpath — the SW-resolvable form.\n const automergeUrl = this.#packageToAutomerge.get(pkg);\n if (automergeUrl !== undefined) {\n const full = heads ? `${automergeUrl}#${heads}` : automergeUrl;\n return `${encodeURIComponent(full)}/${rest}`;\n }\n\n // External: the registered root (ends in \"/\") + the subpath.\n const root = this.#packageToExternalRoot.get(pkg);\n if (root !== undefined) return `${root}${rest}`;\n\n return null;\n }\n\n}\n\n// ---------------------------------------------------------------------------\n// Package entry resolution\n// ---------------------------------------------------------------------------\n\n/** Bundler output directory names an entry point commonly sits under. */\nconst BUNDLE_OUTPUT_DIRS = new Set([\"dist\", \"build\", \"out\", \"lib\"]);\n\n/** Extensions marking a URL as a direct entry point vs. a package/site root. */\nconst MODULE_FILE_EXTENSION = /\\.(mjs|cjs|js|mts|cts|ts|jsx|tsx)$/;\n\n// TODO: this duplicates `patchwork-filesystem`'s internal `httpEntryPointUrl`\n// (same regex + package.json-entry resolution). Delegate to it once that helper\n// is exported, instead of maintaining a parallel copy here.\n/** Whether a URL's pathname already names a module file (a direct entry). */\nfunction namesModuleFile(moduleUrl: string): boolean {\n try {\n return MODULE_FILE_EXTENSION.test(new URL(moduleUrl, window.location.origin).pathname);\n } catch {\n return false;\n }\n}\n\n/**\n * Derive a module URL's package-root directory (ends in \"/\") by the publish\n * convention: bundled tools serve code under `<pkgroot>/dist/…` alongside\n * `<pkgroot>/package.json`. The root is the parent of the nearest bundler-output\n * dir (`dist`/`build`/…) in the path, or the module's own directory if none.\n * Stable across a package's chunks. Returns null if the URL can't be parsed.\n */\nfunction packageRootFromUrl(moduleUrl: string): string | null {\n let base: URL;\n try {\n base = new URL(moduleUrl, window.location.origin);\n } catch {\n return null;\n }\n const segments = base.pathname.split(\"/\").filter(Boolean);\n // Drop the filename; look for the nearest bundler-output dir among the path\n // dirs and treat its parent as the package root.\n const dirs = segments.slice(0, -1);\n for (let i = dirs.length - 1; i >= 0; i--) {\n if (BUNDLE_OUTPUT_DIRS.has(dirs[i])) {\n const rootPath = dirs.slice(0, i).join(\"/\");\n return new URL(`/${rootPath}${rootPath ? \"/\" : \"\"}`, base.origin).href;\n }\n }\n // No bundler dir in the path — the module's own directory is the root.\n return new URL(\".\", base).href;\n}\n\n// ---------------------------------------------------------------------------\n// Source rewriting\n// ---------------------------------------------------------------------------\n\n/**\n * Fetch and parse `package.json` from an already-derived package-root URL.\n * Returns undefined if none is found or on any error.\n */\nasync function fetchPackageJson(\n packageRoot: string\n): Promise<PackageJson | undefined> {\n let candidate: string;\n try {\n candidate = new URL(\"package.json\", packageRoot).href;\n } catch {\n return undefined;\n }\n try {\n const response = await fetch(candidate);\n if (response.ok) return await response.json();\n } catch {\n // ignore\n }\n return undefined;\n}\n\n/**\n * Matches an `automerge:` URL (base + optional `#<heads>`) embedded in served\n * source. The `[A-Za-z0-9]` alphabet is what `isValidAutomergeUrl` accepts and\n * stops at the closing quote/paren; each match is re-validated before use, so an\n * over-match is harmless.\n */\nconst AUTOMERGE_URL_IN_SOURCE = /automerge:[A-Za-z0-9]+(?:#[A-Za-z0-9]+)?/g;\n\n/**\n * Prepare a served registry module's source for the iframe: rewrite baked\n * `automerge:` dep literals to markers, but only if the owning package (identified\n * by `requestUrl`'s marker name) declared automerge deps at registration — so\n * most served modules skip the source scan entirely. The serve-time source entry\n * point the resource bridge calls.\n */\nexport function rewriteServedSource(\n source: string,\n requestUrl: string,\n mapper: PackagesUrlMapper\n): string {\n const markerName = markerNameFromUrl(requestUrl);\n if (!markerName || !mapper.packageNeedsRewrite(markerName)) return source;\n return rewriteAutomergeDepsInSource(source, mapper);\n}\n\n/**\n * Rewrite baked `automerge:` dependency literals in served source to `registry--`\n * markers before the source crosses into the iframe.\n *\n * Tools built with `@chee/patchwork-bundles` bake a dep's automerge URL into the\n * source (handed to `getImportableUrlFromAutomergeUrl` at runtime). Left alone it\n * leaks the ID and yields a raw-automerge request `classify` blocks; rewritten to\n * a marker, the runtime call instead produces a marker request `resolveMarker`\n * maps back. The **mapper is the allowlist**: only an already-registered dep base\n * is rewritten (registration precedes any serve), so a URL a tool fabricated for\n * some other document is left raw and blocked like any smuggled ID.\n */\nfunction rewriteAutomergeDepsInSource(\n source: string,\n mapper: PackagesUrlMapper\n): string {\n return source.replace(AUTOMERGE_URL_IN_SOURCE, (match) => {\n const { base } = stripHeads(match);\n if (!mapper.isRegisteredDependency(base)) return match;\n const marker = mapper.encodeSegment(match);\n return marker ?? match;\n });\n}\n\n/**\n * Extract the `registry--<name>` marker name (decoded first path segment) from a\n * request URL, or null if it has none. Identifies the package that owns a served\n * module.\n */\nfunction markerNameFromUrl(url: string): string | null {\n const { first } = splitFirstSegment(url);\n return first.startsWith(REGISTRY_MARKER_PREFIX) ? first : null;\n}\n\n// ---------------------------------------------------------------------------\n// Request resolution (the interface the resource bridge calls)\n// ---------------------------------------------------------------------------\n\n/**\n * Resolve an inbound `registry` request (a `registry--` marker URL) to a fetchable\n * URL — the read side the resource bridge calls after `classify` admits it. A\n * marker arrives either as a chunk/entry path\n * (`<origin>/registry--@scope--name/dist/chunk.js`) or the baked-dependency form\n * where `getImportableUrlFromAutomergeUrl` percent-encoded the bare marker\n * (`<origin>/registry--%40scope--name%2523h/sub`); `resolveMarker` handles both.\n * A non-marker URL (a platform asset) is returned unchanged.\n */\nexport function resolvePackageRequest(\n url: string,\n mapper: PackagesUrlMapper\n): string {\n return mapper.resolveMarker(url) ?? url;\n}\n\n// ---------------------------------------------------------------------------\n// Registry population (boot + live updates)\n// ---------------------------------------------------------------------------\n\n/**\n * Convert a host registry plugin into a serializable `RegistryEntry` for the\n * iframe: resolve its `importUrl` (via the memoized `mapper.resolvePackage`, which\n * also registers the package's automerge deps in the same read), map it to a\n * `registry--` marker (automerge via `encodeSegment`, external via `encodeExternal`\n * — both keyed by package name so a package's plugins share one marker), record\n * the package if it declared deps, and strip non-cloneable fields + deep-copy so\n * the entry survives `postMessage`.\n *\n * Returns `undefined` (and logs) if the plugin can't be cloned. Shared by\n * `getRegistries` and `watchRegistries` so both produce entries identically.\n */\nasync function processRegistryPlugin(\n plugin: any,\n mapper: PackagesUrlMapper\n): Promise<RegistryEntry | undefined> {\n let importUrl = plugin.importUrl as string | undefined;\n if (importUrl) {\n const resolved = await mapper.resolvePackage(importUrl);\n if (!resolved) {\n importUrl = undefined;\n } else {\n // Marker keyed by package name (plugins of a package share one marker),\n // falling back to the plugin id if package.json had no name.\n const name = resolved.packageName ?? plugin.id;\n if (resolved.hosting === \"automerge\") {\n // `<origin>/registry--<name>/<subpath>` from the bare automerge URL.\n const marker = mapper.encodeSegment(resolved.automergeUrl, name);\n importUrl = marker\n ? `${window.location.origin}/${marker}/${resolved.subpath}`\n : undefined;\n } else {\n importUrl = mapper.encodeExternal(resolved.entryUrl, name);\n }\n // Record (by the same marker name) so the serve path rewrites this\n // package's baked dep literals.\n if (resolved.hasAutomergeDeps) {\n mapper.markPackageHasDeps(mapper.markerNameFor(name));\n }\n }\n }\n\n const { load, module, ...rest } = plugin;\n let entry: RegistryEntry;\n try {\n entry = structuredClone(rest);\n } catch (err) {\n log(`skipping non-cloneable plugin: ${rest.id}`, err);\n return undefined;\n }\n entry.importUrl = importUrl;\n return entry;\n}\n\n/**\n * Collect registry entries from all plugin registries (with importUrls mapped to\n * `registry--` marker URLs) for the iframe's initial registry population.\n */\nexport async function getRegistries(\n mapper: PackagesUrlMapper\n): Promise<RegistryEntry[]> {\n const entries: RegistryEntry[] = [];\n for (const [, registry] of getAllRegistries()) {\n for (const plugin of registry.all()) {\n const entry = await processRegistryPlugin(plugin, mapper);\n if (entry) entries.push(entry);\n }\n }\n return entries;\n}\n\n/**\n * Watch all host registries for new plugin registrations and push each (as a\n * mapped, serializable entry) to the iframe via the RPC port.\n *\n * Returns a cleanup function that unsubscribes from all registries.\n */\nexport function watchRegistries(\n port: MessagePort,\n mapper: PackagesUrlMapper\n): () => void {\n const unsubs: Array<() => void> = [];\n\n for (const [, registry] of getAllRegistries()) {\n const unsub = registry.on(\"registered\", async (plugin: any) => {\n const entry = await processRegistryPlugin(plugin, mapper);\n if (!entry) return;\n log(`pushing registry update: ${entry.id}`);\n port.postMessage({ type: \"plugin-registered\", entry });\n });\n unsubs.push(unsub);\n }\n\n return () => {\n for (const unsub of unsubs) unsub();\n };\n}\n","/**\n * Resource bridge — owns *resources*: the host-side `fetch-package` /\n * `fetch-resource` RPC and the allowlist that gates it. The sandboxed iframe's\n * opaque origin can't reach the host service worker, so this bridge re-opens that\n * channel over RPC — the iframe asks for a URL, the host classifies, resolves,\n * fetches, and returns it (source + resolved URL for `fetch-package`; bytes +\n * content type for `fetch-resource`).\n *\n * `classify` gates every request: only `platform` (import-map runtime) and\n * `registry` (tool code behind a `registry--` marker) are served, so a tool can't\n * smuggle a raw automerge ID through the proxy. Anything package-specific (marker\n * resolution, source rewriting) is delegated to the registry bridge.\n */\n\nimport { log } from \"../log.js\";\nimport {\n type PackagesUrlMapper,\n REGISTRY_MARKER_PREFIX,\n resolvePackageRequest,\n rewriteServedSource,\n splitFirstSegment,\n} from \"./registry-bridge.js\";\n\nexport interface ResourceBridgeOptions {\n port: MessagePort;\n mapper: PackagesUrlMapper;\n}\n\n// ---------------------------------------------------------------------------\n// Request classification (allowlist)\n// ---------------------------------------------------------------------------\n\n/**\n * First path segments of the platform (import-map) build's runtime code: the\n * bootloader emits externals to `/packages/<name>.js` and Vite hoists their\n * chunks to `/assets/`. Same files for every user, no user data — served freely.\n *\n * Safe as a fixed allowlist because the service worker only loads a *document*\n * when the whole decoded pathname parses as an absolute URL (the encoded automerge\n * URL as the first segment); a `packages`/`assets` first segment is a non-scheme\n * word, so it can never resolve to one.\n */\nconst PLATFORM_FIRST_SEGMENTS = new Set([\"packages\", \"assets\"]);\n\n/**\n * How a served-resource request is handled at the isolation boundary:\n * - `platform` — import-map runtime code; served straight through.\n * - `registry` — registry tool code (a `registry--` marker URL); resolved via\n * the registry bridge and served with its automerge deps rewritten.\n * - `blocked` — anything else; rejected before resolution or fetch.\n */\nexport type RequestClass = \"platform\" | \"registry\" | \"blocked\";\n\n/**\n * Classify a served-resource request — the allowlist gating the fetch proxy.\n * Decided entirely by the FIRST path segment (via `splitFirstSegment`, which\n * normalizes `..`/`.` first, so a traversal like `<origin>/assets/../automerge:<id>/x`\n * presents the smuggled ID as `first` and is blocked). `registry--` and the\n * platform prefixes are ordinary segments the SW can't mistake for a document, so\n * there is no ordering subtlety.\n */\nexport function classify(url: string): RequestClass {\n // Non-host-origin: an external importUrl (registration-time input), already\n // mapped to a marker before any request — registry code. Inbound requests never\n // legitimately arrive in this form.\n if (!url.startsWith(window.location.origin + \"/\")) return \"registry\";\n\n const { first } = splitFirstSegment(url);\n\n // Registry: a `registry--` marker. It must have no internal `/` — a decoded\n // segment containing one is an encoded-slash traversal\n // (`registry--x%2F..%2Fautomerge:…`), rejected.\n if (first.startsWith(REGISTRY_MARKER_PREFIX) && !first.includes(\"/\")) {\n return \"registry\";\n }\n\n if (PLATFORM_FIRST_SEGMENTS.has(first)) return \"platform\";\n\n // Anything else (incl. `<origin>/automerge:…`, a normalized traversal escape).\n return \"blocked\";\n}\n\n/**\n * Shared skeleton for both fetch-proxy handlers: classify once, reject `blocked`,\n * resolve + fetch, post an error on failure. Success handling differs per type, so\n * it's passed as `onResponse` (given the `RequestClass` and responsible for posting\n * the success message — the resource handler transfers its ArrayBuffer).\n */\nasync function handleFetchRpc(\n msg: { id: number; url: string },\n type: \"fetch-package\" | \"fetch-resource\",\n port: MessagePort,\n mapper: PackagesUrlMapper,\n onResponse: (\n response: Response,\n requestClass: RequestClass,\n id: number\n ) => Promise<void> | void\n): Promise<void> {\n const errorType = `${type}-error` as const;\n const { id, url } = msg;\n\n // Classify once; reject `blocked` before any resolution/fetch, pass the verdict on.\n const requestClass = classify(url);\n if (requestClass === \"blocked\") {\n const error = `blocked: request not allowed by the isolation allowlist (${url})`;\n log(`${type} blocked ${url}`);\n port.postMessage({ type: errorType, id, error });\n return;\n }\n\n try {\n const fetchUrl = resolvePackageRequest(url, mapper);\n log(fetchUrl !== url ? `${type} ${url} → ${fetchUrl}` : `${type} ${url}`);\n\n const response = await fetch(fetchUrl);\n if (!response.ok) {\n const error = `HTTP ${response.status}: ${response.statusText} (${fetchUrl})`;\n log(`${type} error ${url}: ${error}`);\n port.postMessage({ type: errorType, id, error });\n return;\n }\n // Awaited so a failure reading the body is caught by the catch below.\n await onResponse(response, requestClass, id);\n } catch (err) {\n const error = err instanceof Error ? err.message : String(err);\n log(`${type} error ${url}: ${error}`);\n port.postMessage({ type: errorType, id, error });\n }\n}\n\n/**\n * Start the host-side resource bridge — the RPC handler for module and resource\n * loading.\n *\n * Handles two message types:\n * - `fetch-package`: returns source text + resolved URL (for es-module-shims)\n * - `fetch-resource`: returns ArrayBuffer + content type (for fetch proxy)\n */\nexport function startResourceBridge(options: ResourceBridgeOptions): () => void {\n const { port, mapper } = options;\n\n const onMessage = async (event: MessageEvent) => {\n const msg = event.data;\n if (!msg) return;\n\n if (msg.type === \"fetch-package\") {\n await handleFetchRpc(msg, \"fetch-package\", port, mapper, async (response, requestClass, id) => {\n const rawSource = await response.text();\n\n // Rewrite baked automerge dep URLs to markers before the source crosses\n // in (a no-op for platform code and for registry packages without deps).\n const source =\n requestClass === \"registry\"\n ? rewriteServedSource(rawSource, msg.url, mapper)\n : rawSource;\n\n // Return the requested URL (`msg.url`) as the resolved URL, so esms\n // resolves relative chunk imports against the marker/path — never the real\n // location. Deliberately NOT `response.url`: a fetch redirect must not move\n // the iframe onto a real (location-leaking) URL.\n port.postMessage({\n type: \"fetch-package-response\",\n id,\n source,\n resolvedUrl: msg.url,\n });\n });\n return;\n }\n\n if (msg.type === \"fetch-resource\") {\n await handleFetchRpc(msg, \"fetch-resource\", port, mapper, async (response, _requestClass, id) => {\n const body = await response.arrayBuffer();\n const contentType =\n response.headers.get(\"content-type\") || \"application/octet-stream\";\n // Transfer (not copy) the ArrayBuffer for efficiency.\n port.postMessage(\n { type: \"fetch-resource-response\", id, body, contentType },\n [body]\n );\n });\n return;\n }\n };\n\n port.addEventListener(\"message\", onMessage);\n port.start();\n\n return () => {\n port.removeEventListener(\"message\", onMessage);\n };\n}\n","/**\n * Access control for the isolation boundary.\n *\n * - Allowlist population: one-shot scans of a document's content for automerge\n * URLs, adding each to the allowlist unless it is sensitive (see\n * `denylistIfSensitive`).\n * - Denylist: a shared singleton (`getDenylist`) that blocks sensitive\n * documents (account doc, module settings, tool source code) from ever\n * syncing to the iframe. Populated eagerly over the known protected roots at\n * boot, and lazily extended (by `denylistIfSensitive`) for sensitive docs\n * discovered later in content. Also watches plugin registries and the\n * account doc to denylist tool source / the user's settings doc as they\n * appear. The denylist is a classification *cache*: a sensitive doc is\n * walked once, then every later check is an O(1) set lookup.\n */\n\nimport {\n type AutomergeUrl,\n type DocumentId,\n type Repo,\n isValidAutomergeUrl,\n parseAutomergeUrl,\n} from \"@automerge/automerge-repo/slim\";\nimport { getAllRegistries } from \"@inkandswitch/patchwork-plugins\";\nimport {\n type FolderDoc,\n type BranchesDoc,\n type HasPatchworkMetadata,\n type ModuleSettingsDoc,\n} from \"@inkandswitch/patchwork-filesystem\";\nimport { SyncAllowlist, SyncDenylist } from \"./repo-bridge.js\";\nimport { log } from \"../log.js\";\n\n// ---------------------------------------------------------------------------\n// Allowlist population\n// ---------------------------------------------------------------------------\n\n/**\n * Scan a single document's content for automerge URLs and add any new ones to\n * the allowlist (unless they are denylisted or turn out to be sensitive — see\n * {@link checkAndDenylistIfSensitive}).\n *\n * This is a one-shot scan, not a live subscription: it reads the document's\n * current contents once. Callers re-invoke it (via the wrappers below) when\n * they want to pick up newly-referenced URLs — at boot from the root docs, and\n * lazily when an access request arrives for a URL we haven't seen yet.\n *\n * @param isStale - optional guard returning true if the caller has been torn\n * down (e.g. a newer init epoch started). Checked once after `repo.find`\n * resolves so we don't mutate a stale allowlist. Omit for lazy re-scans where\n * staleness doesn't matter.\n */\nasync function scanDocIntoAllowlist(\n repo: Repo,\n docUrl: AutomergeUrl,\n allowlist: SyncAllowlist,\n denylist: SyncDenylist | undefined,\n isStale?: () => boolean\n): Promise<void> {\n try {\n const handle = await repo.find(docUrl);\n if (isStale?.()) return;\n\n const doc = handle.doc();\n if (!doc) return;\n\n const urls = new Set<AutomergeUrl>();\n collectAutomergeUrls(doc, urls);\n for (const url of urls) {\n await allowlistUrlUnlessSensitive(repo, url, allowlist, denylist);\n }\n log(`allowlist scanned from ${docUrl}`);\n } catch (err) {\n log(`scanDocIntoAllowlist: failed to scan ${docUrl}`, err);\n }\n}\n\n/**\n * Add one already-known automerge URL to the allowlist, unless it is sensitive.\n *\n * This is the single \"denylist-check, then add a URL we already hold\" step,\n * shared by the content scan ({@link scanDocIntoAllowlist}, which discovers URLs\n * inside a document) and by callers that already have the URL in hand and simply\n * need to disclose it to the iframe under an explicit user gesture (e.g. a\n * drag-and-drop into an isolated tool — see the drag-drop bridge).\n *\n * A URL might point at a sensitive document (the account doc, a branches doc,\n * module settings, tool source). Those are denylisted instead of allowlisted and\n * are never handed to the tool. The denylist takes precedence over any grant.\n *\n * Returns true if the URL is now allowlisted (or already was), false if it was\n * denylisted instead — so a caller building a payload to forward can drop the\n * URLs that didn't survive.\n */\nexport async function allowlistUrlUnlessSensitive(\n repo: Repo,\n url: AutomergeUrl,\n allowlist: SyncAllowlist,\n denylist: SyncDenylist | undefined\n): Promise<boolean> {\n if (allowlist.hasUrl(url)) return true;\n if (denylist && (await denylistIfSensitive(repo, url, denylist))) {\n return false;\n }\n allowlist.add(url);\n log(`allowlisted ${url}`);\n return true;\n}\n\n/**\n * Build the document allowlist for one isolation boot: create it, add each\n * root URL (skipping any that turns out to be sensitive — those stay\n * denylisted and are simply never handed to the tool), then transitively scan\n * the roots so everything they reference is allowlisted too.\n *\n * The returned allowlist is what gates the intermediary repo's sync. Later,\n * newly-added references are picked up lazily via `refreshAllowlistFromRoots`.\n *\n * `isStale` stops the (async) scan early if a newer init epoch started; the\n * caller re-checks staleness and discards the result on abort.\n */\nexport async function buildAllowlist(\n repo: Repo,\n rootUrls: AutomergeUrl[],\n denylist: SyncDenylist,\n isStale: () => boolean\n): Promise<SyncAllowlist> {\n const allowlist = new SyncAllowlist();\n\n for (const url of rootUrls) {\n if (await denylistIfSensitive(repo, url, denylist)) {\n log(`root ${url} is sensitive — denylisted, not allowlisted`);\n continue;\n }\n allowlist.add(url);\n log(`allowlisted root ${url}`);\n }\n\n await populateAllowlistFromRoots(\n repo,\n rootUrls,\n allowlist,\n denylist,\n isStale\n );\n return allowlist;\n}\n\n/**\n * Scan multiple root documents into the allowlist, adding everything they\n * transitively reference. Stops early if `isStale` flips (a newer init epoch\n * started). Used by `buildAllowlist` for the initial boot-time seed.\n */\nasync function populateAllowlistFromRoots(\n repo: Repo,\n rootUrls: AutomergeUrl[],\n allowlist: SyncAllowlist,\n denylist: SyncDenylist | undefined,\n isStale: () => boolean\n): Promise<void> {\n for (const url of rootUrls) {\n await scanDocIntoAllowlist(repo, url, allowlist, denylist, isStale);\n if (isStale()) return;\n }\n}\n\n/**\n * Re-scan all root documents and add any newly-referenced automerge URLs to\n * the allowlist. Called lazily (e.g. when an access request arrives) rather\n * than on every change, to catch references the user just added.\n */\nasync function refreshAllowlistFromRoots(\n repo: Repo,\n rootUrls: AutomergeUrl[],\n allowlist: SyncAllowlist,\n denylist: SyncDenylist | undefined\n): Promise<void> {\n for (const url of rootUrls) {\n await scanDocIntoAllowlist(repo, url, allowlist, denylist);\n }\n}\n\n/**\n * Decide whether the iframe may access a document that isn't yet on the\n * allowlist — the intermediary repo's `onAccessRequest` gate.\n *\n * Unknown documents are NOT auto-allowlisted; the user is prompted. This is a\n * safe default: it stops a tool from silently gaining access to any URL it\n * constructs. The cost is that documents the iframe itself just created also\n * prompt.\n *\n * TODO: once the Author ID API is available, auto-allowlist unknown documents\n * whose author matches the iframe's assigned author ID (the iframe created\n * them) and continue to prompt for all others.\n *\n * Returns true (and allowlists the doc) if access is granted.\n */\nexport async function handleAccessRequest(\n repo: Repo,\n rootUrls: AutomergeUrl[],\n allowlist: SyncAllowlist,\n denylist: SyncDenylist,\n documentId: DocumentId\n): Promise<boolean> {\n if (repo.handles[documentId]) {\n // Known to the host but not yet allowlisted — the URL may have been added\n // since the initial scan (e.g. the user typed a new reference), so re-scan\n // roots before asking. (Skipped for unknown docs: a root re-scan can't\n // surface a doc the host has never seen, so it would be wasted work.)\n await refreshAllowlistFromRoots(repo, rootUrls, allowlist, denylist);\n if (allowlist.has(documentId)) return true;\n }\n\n // TODO: remove temp approval\n // const approved = window.confirm(\n // `A tool wants to access a document:\\n\\n` +\n // `Document ID: ${documentId}\\n\\n` +\n // `This may be a document the tool just created, or one it is ` +\n // `trying to open. Allow access?`\n // );\n // if (approved) {\n // allowlist.addDocumentId(documentId);\n // }\n // return approved;\n allowlist.addDocumentId(documentId);\n return true;\n}\n\n/**\n * Decide whether a document URL carried by a bridged provider value may be\n * relayed to the iframe. Like {@link handleAccessRequest} but keyed by URL (the\n * form bridged values carry) and without the silent-vs-prompt policy, which is\n * the provider bridge's concern — this is only reached for provider types that\n * are allowed to prompt.\n *\n * Grants immediately if already allowlisted; otherwise re-scans the roots (the\n * URL may have been referenced since the initial scan) and, failing that,\n * prompts the user. Returns true (and allowlists the URL) if access is granted.\n */\nexport async function requestBridgedUrlAccess(\n repo: Repo,\n rootUrls: AutomergeUrl[],\n allowlist: SyncAllowlist,\n denylist: SyncDenylist,\n url: AutomergeUrl\n): Promise<boolean> {\n if (allowlist.hasUrl(url)) return true;\n // Re-scan root documents in case the URL was referenced recently.\n await refreshAllowlistFromRoots(repo, rootUrls, allowlist, denylist);\n if (allowlist.hasUrl(url)) return true;\n\n const approved = window.confirm(\n `A bridged provider wants to share a document URL:\\n\\n` +\n `URL: ${url}\\n\\n` +\n `Allow access?`\n );\n if (approved) {\n allowlist.add(url);\n return true;\n }\n return false;\n}\n\n/**\n * Recursively walks a value and collects all valid automerge URLs found.\n */\nfunction collectAutomergeUrls(value: unknown, urls: Set<AutomergeUrl>): void {\n if (typeof value === \"string\") {\n if (isValidAutomergeUrl(value)) urls.add(value);\n return;\n }\n if (Array.isArray(value)) {\n for (const item of value) collectAutomergeUrls(item, urls);\n return;\n }\n if (value !== null && typeof value === \"object\") {\n for (const v of Object.values(value as Record<string, unknown>))\n collectAutomergeUrls(v, urls);\n }\n}\n\n// ---------------------------------------------------------------------------\n// Denylist population\n// ---------------------------------------------------------------------------\n\n/** Denylist a FolderDoc and all its child documents. */\nasync function denylistFolderDoc(\n repo: Repo,\n folderUrl: AutomergeUrl,\n denylist: SyncDenylist\n): Promise<void> {\n denylist.add(folderUrl);\n try {\n const handle = await repo.find<FolderDoc>(folderUrl);\n const doc = handle.doc();\n for (const docLink of doc?.docs ?? []) {\n denylist.add(docLink.url);\n }\n } catch (err) {\n log(`denylistFolderDoc: failed to read folder ${folderUrl}`, err);\n }\n}\n\n/**\n * Denylist a module entry (either a BranchesDoc or a direct FolderDoc)\n * and all its transitive children.\n */\nasync function denylistModuleEntry(\n repo: Repo,\n moduleUrl: AutomergeUrl,\n denylist: SyncDenylist\n): Promise<void> {\n denylist.add(moduleUrl);\n try {\n const handle = await repo.find<HasPatchworkMetadata>(moduleUrl);\n const doc = handle.doc();\n const type = doc?.[\"@patchwork\"]?.type;\n\n if (type === \"branches\") {\n const branchesDoc = doc as unknown as BranchesDoc;\n for (const branchUrl of Object.values(branchesDoc.branches ?? {})) {\n await denylistFolderDoc(repo, branchUrl, denylist);\n }\n } else {\n await denylistFolderDoc(repo, moduleUrl, denylist);\n }\n log(`denylisted module with entry ${moduleUrl}`);\n } catch (err) {\n log(`denylistModuleEntry: failed to read module ${moduleUrl}`, err);\n }\n}\n\n/**\n * The set of module-settings document URLs the user currently has, drawn from\n * both sources of truth: the ModuleWatcher's loaded URLs and the account doc's\n * `moduleSettingsUrl` (the user's own bundle, which the bootloader wires into\n * the watcher only lazily — so reading the account doc directly catches it even\n * before the watcher has it). Used both to seed the denylist and to recognize a\n * settings doc on the fly.\n */\nfunction getModuleSettingsUrls(): AutomergeUrl[] {\n const urls = new Set<AutomergeUrl>();\n const moduleWatcher = (window as any).patchwork?.packages;\n if (moduleWatcher?.urls) {\n for (const url of Object.values(moduleWatcher.urls) as AutomergeUrl[]) {\n if (isValidAutomergeUrl(url)) urls.add(url);\n }\n }\n const userSettingsUrl = (window as any).accountDocHandle?.doc()\n ?.moduleSettingsUrl;\n if (userSettingsUrl && isValidAutomergeUrl(userSettingsUrl)) {\n urls.add(userSettingsUrl);\n }\n return [...urls];\n}\n\n/** Denylist a module-settings doc and every module entry it references. */\nasync function denylistModuleSettings(\n repo: Repo,\n settingsUrl: AutomergeUrl,\n denylist: SyncDenylist\n): Promise<void> {\n denylist.add(settingsUrl);\n try {\n const handle = await repo.find<ModuleSettingsDoc>(settingsUrl);\n const doc = handle.doc();\n for (const moduleUrl of doc?.modules ?? []) {\n await denylistModuleEntry(repo, moduleUrl, denylist);\n }\n } catch (err) {\n log(`failed to read module settings ${settingsUrl}`, err);\n }\n}\n\n/**\n * Eagerly enumerate and denylist the protected set — the documents that must\n * never reach a tool, because access would let it damage the user's whole\n * environment rather than just the documents it was given:\n *\n * 1. Account document — the root of the user's identity/config.\n * 2. Module settings docs — control which tools are installed.\n * 3. Tool/package source code (folder & branches docs reachable from the\n * module settings, plus every plugin importUrl) — editing another tool's\n * source could inject code that runs with that tool's access.\n *\n * This is the eager pass over the *known* roots. Sensitive docs that are only\n * discovered later (e.g. referenced deep in user content) are caught lazily by\n * `denylistIfSensitive`, which shares the same recognition logic.\n */\nexport async function populateDenylist(\n repo: Repo,\n denylist: SyncDenylist\n): Promise<void> {\n // 1. Account document\n const accountUrl = (window as any).accountDocHandle?.url;\n if (accountUrl) denylist.add(accountUrl);\n\n // 2 + 3. Module settings docs (from the watcher and the account doc) and the\n // tool source reachable from each.\n for (const settingsUrl of getModuleSettingsUrls()) {\n await denylistModuleSettings(repo, settingsUrl, denylist);\n }\n\n // 4. Denylist all plugin importUrls from the registry as a catch-all.\n for (const [, registry] of getAllRegistries()) {\n for (const plugin of registry.all()) {\n const importUrl = (plugin as any).importUrl as string | undefined;\n if (importUrl && isValidAutomergeUrl(importUrl)) {\n await denylistModuleEntry(repo, importUrl as AutomergeUrl, denylist);\n }\n }\n }\n\n log(`denylist populated with ${denylist.size} documents`);\n}\n\n/** Whether two automerge URLs refer to the same document (by documentId). */\nfunction sameDoc(a: AutomergeUrl, b: AutomergeUrl): boolean {\n try {\n return parseAutomergeUrl(a).documentId === parseAutomergeUrl(b).documentId;\n } catch {\n return false;\n }\n}\n\n/**\n * The single authority on \"is this URL a sensitive document, and if so add it\n * (with its descendants) to the denylist.\" Used both by the lazy allowlist scan\n * (before allowlisting a content-referenced URL) and by the root-URL gate in\n * the isolation element. Returns true if the document was denylisted (caller\n * must skip allowlisting it).\n *\n * Recognition, cheapest first:\n * 1. Already denylisted — an O(1) set lookup. Once the eager `populateDenylist`\n * pass has run, the account doc, every module-settings doc, and all\n * tool-source folder/branches docs are already here, so this short-circuit\n * catches them with no I/O.\n * 2. The account doc, matched by identity.\n * 3. A module-settings doc, matched by membership in the user's settings set\n * (covers a settings doc wired in after the eager pass).\n * 4. A branches or module-settings doc, matched by `@patchwork.type` (covers\n * docs only discovered via content references, not from a known root).\n *\n * Note on folders: a plain tool-source FolderDoc has no distinguishing\n * `@patchwork.type` — it is structurally identical to a user-content folder.\n * It is recognized ONLY by provenance: it was reached from a module-settings\n * doc during a denylist walk and is therefore already in the set (step 1). We\n * deliberately do NOT fingerprint folders by shape, which would wrongly block\n * the user's own content folders.\n */\nexport async function denylistIfSensitive(\n repo: Repo,\n url: AutomergeUrl,\n denylist: SyncDenylist\n): Promise<boolean> {\n // 1. Already known sensitive.\n if (denylist.hasUrl(url)) return true;\n\n // 2. The account doc, by identity.\n const accountUrl = (window as any).accountDocHandle?.url as\n | AutomergeUrl\n | undefined;\n if (accountUrl && sameDoc(url, accountUrl)) {\n log(`dynamically denylisting account doc: ${url}`);\n denylist.add(url);\n return true;\n }\n\n // 3. A module-settings doc the user has, by membership.\n if (\n getModuleSettingsUrls().some((settingsUrl) => sameDoc(url, settingsUrl))\n ) {\n log(`dynamically denylisting module settings doc (membership): ${url}`);\n await denylistModuleSettings(repo, url, denylist);\n return true;\n }\n\n // 4. A branches or module-settings doc discovered via content, by type.\n try {\n const handle = await repo.find<HasPatchworkMetadata>(url);\n const type = handle.doc()?.[\"@patchwork\"]?.type;\n\n if (type === \"branches\") {\n log(`dynamically denylisting branches doc: ${url}`);\n await denylistModuleEntry(repo, url, denylist);\n return true;\n }\n if (type === \"patchwork:module-settings\") {\n log(`dynamically denylisting module settings doc: ${url}`);\n await denylistModuleSettings(repo, url, denylist);\n return true;\n }\n } catch (err) {\n log(`denylistIfSensitive: failed to read ${url}`, err);\n }\n\n return false;\n}\n\n// ---------------------------------------------------------------------------\n// Shared denylist singleton\n// ---------------------------------------------------------------------------\n\nlet sharedDenylist: SyncDenylist | null = null;\n\n/**\n * Get the shared denylist, creating and populating it on first call.\n *\n * This is a deliberate process-lifetime singleton, shared by every isolation\n * instance on the page. The denylisted set — account doc, module settings,\n * tool/package source code — is global and identical for all instances, and\n * the plugin registries it watches are themselves page-global singletons. So a\n * single shared denylist (and its registry listeners, which therefore also\n * live for the page's lifetime and are intentionally never removed) is correct;\n * there is nothing per-instance to scope or tear down.\n */\nexport function getDenylist(repo: Repo): SyncDenylist {\n if (sharedDenylist) return sharedDenylist;\n\n const denylist = new SyncDenylist();\n // Assign the singleton before kicking off population so concurrent callers\n // share this instance and its single in-flight populate (via whenReady),\n // rather than re-populating. Record the promise so callers can await it\n // before allowlisting anything (see SyncDenylist.setReady / the boot path).\n sharedDenylist = denylist;\n denylist.setReady(populateDenylist(repo, denylist));\n\n // Watch for new plugin registrations and denylist their source code.\n for (const [, registry] of getAllRegistries()) {\n registry.on(\"registered\", (plugin: any) => {\n const importUrl = plugin.importUrl as string | undefined;\n if (importUrl && isValidAutomergeUrl(importUrl)) {\n void denylistModuleEntry(repo, importUrl as AutomergeUrl, denylist);\n }\n });\n }\n\n // The user's own module-settings doc is wired into the ModuleWatcher lazily\n // (the bootloader adds it when it appears on the account doc), so the eager\n // populate above can miss it. Watch the account doc and denylist that\n // settings doc (and its tool source) when it first appears, then stop. This\n // mirrors the bootloader's own wireModuleSettingsWhenReady.\n const accountHandle = (window as any).accountDocHandle;\n if (accountHandle) {\n const onChange = () => {\n const settingsUrl = accountHandle.doc()?.moduleSettingsUrl;\n if (settingsUrl && isValidAutomergeUrl(settingsUrl)) {\n accountHandle.off?.(\"change\", onChange);\n void denylistModuleSettings(\n repo,\n settingsUrl as AutomergeUrl,\n denylist\n );\n }\n };\n onChange();\n if (!accountHandle.doc()?.moduleSettingsUrl) {\n accountHandle.on?.(\"change\", onChange);\n }\n }\n\n return denylist;\n}\n","/**\n * Navigation bridge — forwards `patchwork:open-document` events from the\n * iframe to the host element so that tools can trigger navigation.\n *\n * Navigation is gated by the intermediary's allowlist: allowlisted\n * documents navigate immediately, others require user confirmation.\n *\n * Protocol:\n * iframe → host: { type: \"open-document\", detail: OpenDocumentEventDetail }\n */\n\nimport type { AutomergeUrl } from \"@automerge/automerge-repo/slim\";\nimport type { OpenDocumentEventDetail } from \"../../events.js\";\nimport { log } from \"../log.js\";\n\n/**\n * Host-side navigation bridge.\n *\n * Listens on the RPC port for `open-document` messages from the iframe\n * and re-dispatches them as `patchwork:open-document` CustomEvents on\n * the host element.\n *\n * Navigation is gated by an `isAllowed` callback that checks the\n * intermediary repo's allowlist. Allowlisted documents navigate\n * immediately; non-allowlisted documents require user confirmation.\n */\nexport function startHostNavigationBridge(\n rpcPort: MessagePort,\n hostElement: HTMLElement,\n isAllowed: (url: AutomergeUrl) => boolean\n): () => void {\n const onMessage = (event: MessageEvent) => {\n const msg = event.data;\n if (msg?.type !== \"open-document\") return;\n\n const detail = msg.detail as OpenDocumentEventDetail;\n\n if (!isAllowed(detail.url)) {\n log(`navigation prompted: ${detail.url}`);\n const title = detail.title ?? \"Unknown\";\n const type = detail.type ?? \"unknown\";\n const allowed = window.confirm(\n `A tool wants to open a document:\\n\\n` +\n `Title: ${title}\\n` +\n `Type: ${type}\\n` +\n `URL: ${detail.url}\\n\\n` +\n `Allow navigation?`\n );\n if (!allowed) {\n log(`navigation denied: ${detail.url}`);\n return;\n }\n } else {\n log(`navigation allowed: ${detail.url}`);\n }\n\n hostElement.dispatchEvent(\n new CustomEvent(\"patchwork:open-document\", {\n detail,\n bubbles: true,\n composed: true,\n })\n );\n };\n\n rpcPort.addEventListener(\"message\", onMessage);\n\n return () => {\n rpcPort.removeEventListener(\"message\", onMessage);\n };\n}\n","/**\n * Drag-and-drop bridge — delivers a host-side drag (e.g. a document dragged out\n * of the sidebar) into an isolated tool running in the iframe.\n *\n * Direction matters. The navigation bridge runs iframe → host (a tool asks the\n * host to open a document it already knows). This bridge runs the OTHER way,\n * **host → iframe**: the host is disclosing document URLs *into* untrusted tool\n * code. That is exactly the thing the isolation boundary exists to control (see\n * ISOLATION.md, \"controlling which automerge URLs the isolated context can\n * learn\"), so disclosure here is deliberately scoped:\n *\n * - Only the patchwork document-drag MIME types are read; arbitrary drag data\n * is never forwarded.\n * - Every dragged URL is run through the allowlist gate (`allowlistDrop`),\n * which denylist-checks it first. A URL that resolves to a sensitive document\n * (account doc, module settings, tool source) is dropped from the payload and\n * never crosses — even as text.\n * - The drag is the user's own gesture, so the surviving URLs are allowlisted\n * silently (no prompt), the same authorization signal as opening a document.\n *\n * A cross-realm drag is inherently cross-view, so it is always a *copy*\n * (add-link), never a move — which is the correct semantic for dropping a\n * document reference into another document anyway.\n *\n * ## Why an overlay\n *\n * The iframe is cross-origin (opaque origin: `allow-scripts` without\n * `allow-same-origin`). When a host-initiated drag moves over such an iframe the\n * browser routes the drag events *into the iframe's document*, but the iframe's\n * `drop` fires with an EMPTY DataTransfer — the browser blocks the custom drag\n * types cross-origin (Chromium #251718, FilePond #218). So the tool's own drop\n * handler inside the iframe can never see the payload, and the host's listeners\n * on the <iframe> element don't fire over the content region either.\n *\n * The fix is a transparent host-owned overlay raised *on top of* the iframe for\n * the duration of a drag. Because the overlay is a plain host-DOM element, the\n * host receives `dragover`/`drop` with the full (same-origin) DataTransfer. We\n * parse and gate it host-side, then forward only the surviving documents into\n * the iframe over RPC, where they are re-dispatched as a synthetic drop the\n * tool's own handler consumes. The overlay exists ONLY while a drag is active,\n * so it never interferes with normal pointer input.\n *\n * Protocol:\n * host → iframe: { type: \"drop\", formats: Record<string,string>, x, y }\n * (x, y are iframe-local client coordinates for the drop point.)\n */\n\nimport {\n type AutomergeUrl,\n type DocumentId,\n isValidAutomergeUrl,\n isValidDocumentId,\n stringifyAutomergeUrl,\n} from \"@automerge/automerge-repo/slim\";\nimport { log } from \"../log.js\";\n\n// The patchwork document-drag MIME types. Mirrors the sideboard's convention\n// (duplicated on purpose across tools — a shared package is a later step). Only\n// these are read off the drag; anything else is ignored.\nconst PATCHWORK_DND = \"text/x-patchwork-dnd\";\nconst PATCHWORK_URLS = \"text/x-patchwork-urls\";\nconst URI_LIST = \"text/uri-list\";\nconst PLAIN = \"text/plain\";\n\n/** Any patchwork document-drag format present on the drag? */\nfunction isPatchworkDrag(dt: DataTransfer | null): boolean {\n if (!dt) return false;\n return (\n dt.types.includes(PATCHWORK_DND) ||\n dt.types.includes(PATCHWORK_URLS) ||\n dt.types.includes(URI_LIST) ||\n dt.types.includes(PLAIN)\n );\n}\n\n/** Turn an automerge url or a patchwork web link into a DocumentId, or null.\n * Mirrors the drop target's `urlToDocId` (codemirror-markdown/embed.ts). */\nfunction urlToDocId(raw: string): DocumentId | null {\n const trimmed = raw.trim();\n if (!trimmed) return null;\n const am = trimmed.match(/automerge:([a-zA-Z0-9]+)/);\n if (am && isValidDocumentId(am[1])) return am[1] as DocumentId;\n const web = trimmed.match(/[#&?]doc=([a-zA-Z0-9]+)/);\n if (web && isValidDocumentId(web[1])) return web[1] as DocumentId;\n return null;\n}\n\n/**\n * A structured drag item, as produced by the sideboard on the `text/x-patchwork-dnd`\n * format. We keep only the fields the drop target reads (`url`, `toolId`); every\n * other field (name, type, source, internal ids) is deliberately dropped so no\n * incidental data crosses.\n */\ntype DndItem = { url: string; toolId?: string };\n\n/**\n * Extract, from a drag's DataTransfer, the set of dragged documents keyed by\n * DocumentId, preserving an explicit `toolId` where the structured format\n * carried one. Reads formats in the same preference order as the drop target.\n */\nfunction extractItems(dt: DataTransfer): Map<DocumentId, { toolId?: string }> {\n const items = new Map<DocumentId, { toolId?: string }>();\n const add = (docId: DocumentId | null, toolId?: string) => {\n if (!docId || items.has(docId)) return;\n items.set(docId, { toolId });\n };\n\n const dnd = dt.getData(PATCHWORK_DND);\n if (dnd) {\n try {\n const parsed = JSON.parse(dnd) as { items?: DndItem[] };\n for (const item of parsed?.items ?? []) {\n if (item?.url) add(urlToDocId(item.url), item.toolId);\n }\n } catch {\n // fall through to the other formats\n }\n }\n if (items.size > 0) return items;\n\n const urls = dt.getData(PATCHWORK_URLS);\n if (urls) {\n try {\n const parsed: unknown = JSON.parse(urls);\n if (Array.isArray(parsed)) {\n for (const u of parsed) add(urlToDocId(String(u)));\n }\n } catch {\n // fall through\n }\n }\n if (items.size > 0) return items;\n\n const text = dt.getData(URI_LIST) || dt.getData(PLAIN);\n if (text) {\n for (const line of text.split(/\\r?\\n/)) {\n if (line.startsWith(\"#\")) continue; // uri-list comments\n add(urlToDocId(line));\n }\n }\n return items;\n}\n\n/**\n * Build the forwarded formats from the *surviving* (allowlisted) items only.\n * We reconstruct the format strings from scratch rather than forwarding the raw\n * drag data, so a denylisted or unparseable URL never crosses the boundary even\n * as text. The two structured formats are enough for the drop target — it reads\n * `text/x-patchwork-dnd` first, then `text/x-patchwork-urls`.\n */\nfunction buildForwardedFormats(\n survivors: Array<{ docId: DocumentId; toolId?: string }>\n): Record<string, string> {\n const urls = survivors.map(({ docId }) => stringifyAutomergeUrl(docId));\n return {\n [PATCHWORK_DND]: JSON.stringify({\n source: \"isolation:drag-drop-bridge\",\n items: survivors.map(({ docId, toolId }) => ({\n url: stringifyAutomergeUrl(docId),\n ...(toolId ? { toolId } : {}),\n })),\n }),\n [PATCHWORK_URLS]: JSON.stringify(urls),\n };\n}\n\n/**\n * Host-side drag-and-drop bridge.\n *\n * Watches the host document for a patchwork document drag; while one is active,\n * raises a transparent overlay over the iframe so the host (not the cross-origin\n * iframe) receives the drop with its full DataTransfer. On drop the dragged\n * documents are gated and the surviving set is posted into the iframe over RPC,\n * where it is re-dispatched as a synthetic drop the tool's own handler consumes.\n *\n * @param allowlistDrop - gate + disclose one dragged URL. Returns true if the\n * URL survived (is now allowlisted) and may be forwarded; false if it was\n * denylisted and must be withheld. Closes over the intermediary allowlist /\n * denylist (see boot.ts) — this bridge holds no policy of its own.\n */\nexport function startHostDragDropBridge(\n rpcPort: MessagePort,\n getIframe: () => HTMLIFrameElement | null,\n allowlistDrop: (url: AutomergeUrl) => Promise<boolean>\n): () => void {\n // The overlay is created lazily on first drag and reused. It is only in the\n // DOM (and only pointer-catching) while a drag is active, so it never blocks\n // normal input. Positioned to track the iframe exactly. The iframe is fetched\n // lazily (via getIframe) because the bridge is started before createIframe\n // builds the element; it exists by the time any drag can occur.\n let overlay: HTMLDivElement | null = null;\n\n const positionOverlay = () => {\n const iframeEl = getIframe();\n if (!overlay || !iframeEl) return;\n const rect = iframeEl.getBoundingClientRect();\n overlay.style.top = `${rect.top}px`;\n overlay.style.left = `${rect.left}px`;\n overlay.style.width = `${rect.width}px`;\n overlay.style.height = `${rect.height}px`;\n };\n\n const showOverlay = () => {\n if (!overlay) {\n overlay = document.createElement(\"div\");\n overlay.setAttribute(\"data-patchwork-isolation-drop-overlay\", \"\");\n overlay.style.cssText =\n \"position: fixed; z-index: 2147483647; background: transparent;\";\n overlay.addEventListener(\"dragover\", onOverlayDragOver);\n overlay.addEventListener(\"drop\", onOverlayDrop);\n // A drag that leaves the overlay (back over host chrome, or out of the\n // window) tears it down so it never lingers and blocks input.\n overlay.addEventListener(\"dragleave\", onOverlayDragLeave);\n }\n positionOverlay();\n if (!overlay.isConnected) document.body.appendChild(overlay);\n };\n\n const hideOverlay = () => {\n overlay?.remove();\n };\n\n // Detect the start of a drag anywhere over the host page. We do NOT depend on\n // the sideboard's drag signal — any patchwork document drag entering the host\n // document raises the overlay, keeping the platform decoupled from the drag\n // source. `dragenter` bubbles to document, so one listener suffices.\n const onDocDragEnter = (event: DragEvent) => {\n if (!isPatchworkDrag(event.dataTransfer)) return;\n showOverlay();\n };\n\n const onOverlayDragOver = (event: DragEvent) => {\n if (!isPatchworkDrag(event.dataTransfer)) return;\n // Accept the drag so the browser permits a drop and shows a copy cursor.\n event.preventDefault();\n if (event.dataTransfer) event.dataTransfer.dropEffect = \"copy\";\n };\n\n const onOverlayDragLeave = (event: DragEvent) => {\n // Only tear down when the pointer actually leaves the overlay (not on the\n // spurious dragleave fired when moving between child nodes — the overlay has\n // none, but relatedTarget null also covers leaving the window).\n if (event.relatedTarget === overlay) return;\n hideOverlay();\n };\n\n const onOverlayDrop = (event: DragEvent) => {\n const dt = event.dataTransfer;\n // Always tear the overlay down on drop, whatever the payload.\n hideOverlay();\n if (!isPatchworkDrag(dt) || !dt) return;\n event.preventDefault();\n\n const items = extractItems(dt);\n if (items.size === 0) return;\n\n const iframeEl = getIframe();\n if (!iframeEl) return;\n\n // Iframe-local coordinates for the drop point. The overlay is positioned to\n // exactly cover the iframe, so subtracting the iframe's top-left maps the\n // drop's client coords to the iframe's own client coords (unscaled layout).\n const rect = iframeEl.getBoundingClientRect();\n const x = event.clientX - rect.left;\n const y = event.clientY - rect.top;\n\n // Gate every dragged URL before anything crosses. Denylisted URLs are\n // dropped from the payload; survivors are allowlisted (silently — the drag\n // is the user's authorization) so the embed renders without a later prompt.\n void (async () => {\n const survivors: Array<{ docId: DocumentId; toolId?: string }> = [];\n for (const [docId, { toolId }] of items) {\n const url = stringifyAutomergeUrl(docId);\n if (!isValidAutomergeUrl(url)) continue;\n if (await allowlistDrop(url)) {\n survivors.push({ docId, toolId });\n } else {\n log(`drop withheld (denylisted): ${docId}`);\n }\n }\n if (survivors.length === 0) {\n log(\"drop had no forwardable documents\");\n return;\n }\n log(`forwarding drop of ${survivors.length} document(s)`);\n rpcPort.postMessage({\n type: \"drop\",\n formats: buildForwardedFormats(survivors),\n x,\n y,\n });\n })();\n };\n\n // Keep the overlay aligned if the layout shifts mid-drag.\n const onScrollOrResize = () => positionOverlay();\n\n document.addEventListener(\"dragenter\", onDocDragEnter, true);\n window.addEventListener(\"scroll\", onScrollOrResize, true);\n window.addEventListener(\"resize\", onScrollOrResize);\n\n return () => {\n document.removeEventListener(\"dragenter\", onDocDragEnter, true);\n window.removeEventListener(\"scroll\", onScrollOrResize, true);\n window.removeEventListener(\"resize\", onScrollOrResize);\n hideOverlay();\n overlay = null;\n };\n}\n","/**\n * Providers bridge — relays provider subscriptions from the iframe to\n * host-side providers across the isolation boundary.\n *\n * The iframe forwards ALL unclaimed `patchwork:subscribe` events to the\n * host via RPC. The host checks the subscription type against an allowlist\n * and either answers it (by dispatching a real `patchwork:subscribe` on\n * the host element) or rejects it.\n *\n * This bridge exists because DOM events don't cross iframe boundaries.\n * Provider subscriptions use `patchwork:subscribe` CustomEvents that bubble\n * up the DOM tree — inside the iframe, they can only reach local providers.\n * Subscriptions that no local provider answers (e.g. `patchwork:contact`)\n * are forwarded here so host-side providers (e.g. AccountProvider) can\n * respond.\n *\n * Security: the allowlist is managed on the host side. The iframe cannot\n * influence which subscription types are bridged.\n *\n * Protocol:\n * iframe → host: { type: \"providers-bridge\", id, selector }\n * host → iframe: { type: \"providers-bridge-change\", id, value }\n * host → iframe: { type: \"providers-bridge-rejected\", id }\n * iframe → host: { type: \"providers-bridge-unsubscribe\", id }\n */\n\nimport { isValidAutomergeUrl } from \"@automerge/automerge-repo/slim\";\nimport { log } from \"../log.js\";\n\n/**\n * Provider subscription types that have been analyzed for security\n * implications and are safe to bridge across the isolation boundary.\n *\n * WARNING: Adding new types here requires independent security analysis.\n * Each bridged provider type is a channel through which information flows\n * from the trusted host context into the untrusted iframe. The value\n * filter checks for automerge URL leaks, but other sensitive data\n * (user identity, behavioral signals, etc.) may also be a concern.\n *\n * In the future we hope to have a different security design that will\n * allow us to loosen this requirement and give tool authors more freedom\n * over which providers are bridged.\n */\nexport const ALLOWED_PROVIDERS = [\n \"patchwork:contact\",\n \"patchwork:selected-doc\",\n // The active theme id (a plain string). Carries no automerge URLs or user\n // identity, so it is safe to relay into the iframe; lets isolated tools\n // (e.g. the titlebar theme tool) mirror the host's active theme.\n \"patchwork:current-theme\",\n];\n\n/**\n * Resolve the set of provider types to bridge for one isolation instance: the\n * intersection of the element's `shared-providers` attribute (comma-separated,\n * host-set) and `ALLOWED_PROVIDERS`. Types requested but not in the hard\n * allowlist are dropped with a console warning — they need independent security\n * analysis before being added. No providers are bridged unless opted in.\n */\nexport function resolveBridgedProviders(element: HTMLElement): string[] {\n const requested = (element.getAttribute(\"shared-providers\") ?? \"\")\n .split(\",\")\n .map((s) => s.trim())\n .filter(Boolean);\n const bridged: string[] = [];\n for (const provider of requested) {\n if (ALLOWED_PROVIDERS.includes(provider)) {\n bridged.push(provider);\n } else {\n console.warn(\n `[patchwork-isolation] shared-providers: \"${provider}\" is not in ALLOWED_PROVIDERS. ` +\n `New provider types need independent security analysis before being added.`\n );\n }\n }\n return bridged;\n}\n\ninterface ActiveSubscription {\n port: MessagePort;\n cleanup: () => void;\n}\n\n/**\n * Optional async filter applied to values before relaying them to the iframe.\n * Receives the subscription type and value; returns the (possibly modified)\n * value, or `undefined` to suppress the emission entirely.\n *\n * This can be used to check values against the allowlist and prompt the user\n * for access to URLs the iframe doesn't already know about.\n */\nexport type BridgeValueFilter = (\n selectorType: string,\n value: unknown\n) => Promise<unknown | undefined> | unknown | undefined;\n\n/**\n * Build a {@link BridgeValueFilter} that vets every automerge URL a bridged\n * value carries before it crosses to the iframe.\n *\n * Two per-URL checks, chosen by provider type:\n * - `isAllowed(url)` — synchronous allowlist membership, no side effects.\n * - `requestAccess(url)` — may re-scan, prompt the user, and grant access.\n *\n * `patchwork:selected-doc` uses `isAllowed` only: unknown URLs are silently\n * dropped, never prompted. Its semantic is \"which of my allowlisted documents\n * is selected\" — not \"give me access to the selected document\" — and prompting\n * on it would fire spuriously as the user navigates (the old iframe is about to\n * be torn down). Every other bridged type uses `requestAccess`.\n *\n * Handles the value shapes a provider can emit: a single automerge-URL string\n * (suppressed entirely if rejected), or an array (each automerge-URL element\n * kept only if allowed; non-URL elements passed through). Any other value is\n * relayed unchanged.\n */\nexport function makeBridgedValueFilter(checks: {\n isAllowed: (url: string) => boolean;\n requestAccess: (url: string) => Promise<boolean>;\n}): BridgeValueFilter {\n return async (selectorType, value) => {\n const silent = selectorType === \"patchwork:selected-doc\";\n const checkUrl = (url: string): boolean | Promise<boolean> =>\n silent ? checks.isAllowed(url) : checks.requestAccess(url);\n\n // Single automerge URL value\n if (typeof value === \"string\" && isValidAutomergeUrl(value)) {\n return (await checkUrl(value)) ? value : undefined;\n }\n\n // Array of values (may contain automerge URLs)\n if (Array.isArray(value)) {\n const result: unknown[] = [];\n for (const item of value) {\n if (typeof item === \"string\" && isValidAutomergeUrl(item)) {\n if (await checkUrl(item)) result.push(item);\n } else {\n result.push(item);\n }\n }\n return result;\n }\n\n return value;\n };\n}\n\n/**\n * Start the host-side providers bridge.\n *\n * @param rpcPort - The RPC MessagePort shared with the iframe\n * @param hostElement - The host DOM element to dispatch subscriptions on\n * (typically the `<patchwork-isolation>` element, whose ancestors include\n * the providers that should answer bridged subscriptions)\n * @param allowedTypes - Subscription types to bridge for this instance.\n * Should be the intersection of ALLOWED_PROVIDERS and the per-instance\n * `shared-providers` attribute, computed by the caller.\n * @param valueFilter - Optional filter applied to values before relaying\n * @returns Cleanup function\n */\nexport function startHostProvidersBridge(\n rpcPort: MessagePort,\n hostElement: HTMLElement,\n allowedTypes: string[] = [],\n valueFilter?: BridgeValueFilter\n): () => void {\n const allowed = new Set(allowedTypes);\n const active = new Map<number, ActiveSubscription>();\n\n const onMessage = (event: MessageEvent) => {\n const msg = event.data;\n if (!msg) return;\n\n if (msg.type === \"providers-bridge\") {\n const { id, selector } = msg as {\n id: number;\n selector: { type: string; [key: string]: unknown };\n };\n\n if (!allowed.has(selector.type)) {\n log(`providers-bridge rejected: ${selector.type}`);\n rpcPort.postMessage({ type: \"providers-bridge-rejected\", id });\n return;\n }\n\n log(`providers-bridge accepted: ${selector.type} (id=${id})`);\n\n // Create a MessageChannel for the host-side subscription\n const channel = new MessageChannel();\n const hostPort = channel.port2;\n\n // Listen for values from the host provider\n hostPort.addEventListener(\"message\", async (e: MessageEvent) => {\n if (e.data?.type === \"change\") {\n const value = valueFilter\n ? await valueFilter(selector.type, e.data.value)\n : e.data.value;\n if (value === undefined) return;\n rpcPort.postMessage({\n type: \"providers-bridge-change\",\n id,\n value,\n });\n }\n });\n hostPort.start();\n\n // Dispatch a real patchwork:subscribe event on the host element\n // so ancestor providers (e.g. AccountProvider) can answer it\n hostElement.dispatchEvent(\n new CustomEvent(\"patchwork:subscribe\", {\n detail: { selector, port: channel.port1 },\n bubbles: true,\n composed: true,\n })\n );\n\n const cleanup = () => {\n hostPort.postMessage({ type: \"unsubscribe\" });\n hostPort.close();\n channel.port1.close();\n };\n\n active.set(id, { port: hostPort, cleanup });\n return;\n }\n\n if (msg.type === \"providers-bridge-unsubscribe\") {\n const { id } = msg as { id: number };\n const sub = active.get(id);\n if (sub) {\n log(`providers-bridge unsubscribe (id=${id})`);\n sub.cleanup();\n active.delete(id);\n }\n return;\n }\n };\n\n rpcPort.addEventListener(\"message\", onMessage);\n\n return () => {\n rpcPort.removeEventListener(\"message\", onMessage);\n for (const [, sub] of active) {\n sub.cleanup();\n }\n active.clear();\n };\n}\n","/**\n * The isolated iframe's runtime — the code that runs *inside* the sandbox.\n *\n * `boot` and its injected helpers (`installLocalStorageStub`, `installFetchProxy`,\n * `installLinkInterception`) are written as typed functions so tsc checks them,\n * but they never execute in the host: `../host/srcdoc.ts` serializes each with\n * `.toString()` into the iframe's srcdoc `<script>`. Because the iframe has no\n * module system until es-module-shims loads (step 5), everything the iframe needs\n * at boot must live in these functions; the helpers are passed into `boot()`\n * rather than closed over, since `.toString()` can't capture surrounding scope.\n */\n\n// RegistryEntry is a host↔iframe wire type — see ../../types.ts.\nimport type { RegistryEntry } from \"../../types.js\";\nexport type { RegistryEntry };\n\n// The injected iframe code (each concern in its own ./*.ts, serialized into the\n// srcdoc by ../host/srcdoc.ts). Imported as types only: boot() receives these\n// via `deps` at runtime and never references the module bindings directly.\nimport type { installLocalStorageStub } from \"./local-storage.js\";\nimport type { installFetchProxy } from \"./fetch-proxy.js\";\nimport type { installLinkInterception } from \"./link-interception.js\";\nimport type { createRpcClient, RpcClient } from \"./rpc.js\";\nimport type {\n createProvidersBridge,\n ProvidersBridge,\n} from \"./providers-bridge.js\";\nimport type { setupEsModuleShims } from \"./es-module-shims.js\";\nimport type { installWorkerShim } from \"./worker-shim.js\";\nimport type { createRegistry, Registry } from \"./registry.js\";\nimport type {\n createRootComponentData,\n RootComponentData,\n} from \"./root-component-data.js\";\nimport type { createDragDrop, DragDrop } from \"./drag-drop.js\";\n\n// ---------------------------------------------------------------------------\n// Type declarations for runtime globals available inside the iframe.\n// ---------------------------------------------------------------------------\n\ninterface InitMessage {\n rpcPort: MessagePort;\n syncPort: MessagePort;\n data: {\n rootComponentId: string;\n /**\n * Opaque JSON data for the root component, relayed verbatim from the host\n * (the boundary never parses it). Materialized as-is into the root's inert\n * `<script type=\"application/json\" data-root-component-data>`; the root\n * parses + re-reads it. Live changes arrive later as\n * `root-component-data-update` RPC messages.\n */\n rootComponentData: string;\n registryEntries: RegistryEntry[];\n esmsSource: string;\n hostStyles: string;\n importMap: { imports?: Record<string, string>; scopes?: any };\n hostOrigin: string;\n automergeWasm: ArrayBuffer;\n subductionWasm: ArrayBuffer;\n };\n}\n\n/**\n * The iframe code injected into `boot()`. Each lives at module scope (./helpers.ts,\n * ./rpc.ts) so tsc checks it, and is serialized into the srcdoc by\n * ../host/srcdoc.ts; `boot()` receives them here since `.toString()` can't\n * capture surrounding scope.\n */\ninterface BootDeps {\n installLocalStorageStub: typeof installLocalStorageStub;\n installFetchProxy: typeof installFetchProxy;\n installLinkInterception: typeof installLinkInterception;\n createRpcClient: typeof createRpcClient;\n createProvidersBridge: typeof createProvidersBridge;\n setupEsModuleShims: typeof setupEsModuleShims;\n installWorkerShim: typeof installWorkerShim;\n /**\n * `workerBootstrap` serialized to source (`.toString()`), assembled in\n * ../host/srcdoc.ts. Passed as a string (not a function) because it runs\n * inside a worker blob, not the iframe — `installWorkerShim` embeds it.\n */\n workerBootstrapSource: string;\n createRegistry: typeof createRegistry;\n createRootComponentData: typeof createRootComponentData;\n createDragDrop: typeof createDragDrop;\n}\n\n// ---------------------------------------------------------------------------\n// Boot function — runs inside the iframe via boot.toString() + IIFE.\n// ---------------------------------------------------------------------------\n\nexport async function boot(deps: BootDeps) {\n const {\n installLocalStorageStub,\n installFetchProxy,\n installLinkInterception,\n createRpcClient,\n createProvidersBridge,\n setupEsModuleShims,\n installWorkerShim,\n workerBootstrapSource,\n createRegistry,\n createRootComponentData,\n createDragDrop,\n } = deps;\n // Minimal debug-compatible logger. The real `debug` package isn't available\n // until modules load, but we need logging during bootstrap.\n // Respects the same localStorage(\"debug\") namespace convention.\n const NAMESPACE = \"patchwork:elements:isolation:iframe\";\n const peerId = \"isolation-\" + crypto.randomUUID().slice(0, 8);\n let debugEnabled = false;\n const log = (...args: unknown[]) => {\n if (!debugEnabled) return;\n console.debug(`%c${NAMESPACE}`, \"color: #7c3aed\", ...args);\n };\n\n // 1. Stub localStorage (no-op in-memory; see the injected helper), then\n // evaluate the debug flag now that localStorage is available.\n installLocalStorageStub();\n {\n const pattern = localStorage.getItem(\"debug\") || \"\";\n if (pattern) {\n const re = new RegExp(\n \"^\" +\n pattern\n .split(\",\")\n .map((p: string) => p.trim().replace(/\\*/g, \".*?\"))\n .join(\"$|^\") +\n \"$\"\n );\n debugEnabled = re.test(NAMESPACE);\n }\n }\n\n // Tag all debug-package output from inside the iframe\n const _originalConsoleDebug = console.debug;\n console.debug = (...args: any[]) => {\n if (typeof args[0] === \"string\" && args[0].startsWith(\"%c\")) {\n args[0] = `[${peerId}] ` + args[0];\n }\n _originalConsoleDebug.apply(console, args);\n };\n\n // 2. Declare the RPC port and its inbound-message consumers.\n // The RPC client (fetch req-reply), providers bridge, and plugin registry each\n // own their own state; see ./rpc.ts, ./providers-bridge.ts, ./registry.ts. The\n // port itself is owned here because it fans messages out to all three. They're\n // created once the port arrives (step 4).\n let rpcPort: MessagePort;\n let rpc: RpcClient;\n let providers: ProvidersBridge;\n let registry: Registry;\n let rootComponentData: RootComponentData;\n let dragDrop: DragDrop;\n\n // Route an inbound RPC message to whichever consumer owns it.\n function handleRpcMessage(event: MessageEvent) {\n if (rpc.handle(event)) return;\n if (providers.handle(event)) return;\n if (registry.handle(event)) return;\n if (rootComponentData.handle(event)) return;\n if (dragDrop.handle(event)) return;\n }\n\n // 3. Wait for the init (\"boot\") message from the host.\n const init: InitMessage = await new Promise((resolve) => {\n window.addEventListener(\"message\", function handler(event: MessageEvent) {\n if (!event.data || event.data.type !== \"boot\") return;\n window.removeEventListener(\"message\", handler);\n resolve({\n rpcPort: event.ports[0],\n syncPort: event.ports[1],\n data: event.data,\n });\n });\n });\n\n // 4. Create the message consumers and start routing the RPC port.\n rpcPort = init.rpcPort;\n rpc = createRpcClient(rpcPort);\n providers = createProvidersBridge(rpcPort, log);\n registry = createRegistry(log);\n rootComponentData = createRootComponentData(log);\n dragDrop = createDragDrop(log);\n rpcPort.addEventListener(\"message\", handleRpcMessage);\n rpcPort.start();\n\n // 5. Navigation bridge: forward patchwork:open-document events to host.\n // We do NOT stopPropagation — the event still bubbles within the iframe\n // so that providers (e.g. SelectedDocProvider) inside the iframe can\n // observe it. The host's SelectedDocProvider deduplicates by URL, so\n // forwarding the same selection back is a no-op.\n //\n // This listener (like the RPC and patchwork:subscribe listeners) is never\n // removed: it is bound to the iframe's own document and lives for the\n // iframe's whole lifetime. The host tears the iframe down wholesale, so\n // there is nothing to clean up.\n document.addEventListener(\n \"patchwork:open-document\",\n ((event: CustomEvent) => {\n rpcPort.postMessage({ type: \"open-document\", detail: event.detail });\n }) as EventListener,\n true\n );\n\n const d = init.data;\n log(\"init\", { root: d.rootComponentId });\n\n // 6. Inject host page stylesheets so tools render with the same CSS\n // framework (Tailwind, DaisyUI, etc.) as on the host.\n if (d.hostStyles) {\n const style = document.createElement(\"style\");\n style.textContent = d.hostStyles;\n document.head.appendChild(style);\n }\n\n try {\n // 7. Stand up es-module-shims (source hook → RPC, import map). All module\n // loading below goes through the returned importShim. See ./es-module-shims.ts.\n const importShim = await setupEsModuleShims({\n esmsSource: d.esmsSource,\n importMap: d.importMap,\n fetchModule: rpc.fetchModule,\n log,\n });\n\n // 8. Import core runtime modules\n const [\n automerge,\n automergeSubduction,\n automergeRepo,\n messagechannel,\n patchworkElements,\n patchworkPlugins,\n patchworkProviders,\n ] = await Promise.all([\n importShim(\"@automerge/automerge/slim\"),\n importShim(\"@automerge/automerge-subduction/slim\"),\n importShim(\"@automerge/automerge-repo/slim\"),\n importShim(\"@automerge/automerge-repo-network-messagechannel\"),\n importShim(\"@inkandswitch/patchwork-elements\"),\n importShim(\"@inkandswitch/patchwork-plugins\"),\n importShim(\"@inkandswitch/patchwork-providers\"),\n ]);\n\n log(\"modules loaded\");\n\n // 9. Initialize WASM from transferred ArrayBuffers\n automergeSubduction.initSync(new Uint8Array(d.subductionWasm));\n await automerge.initializeWasm(new Uint8Array(d.automergeWasm));\n log(\"wasm initialized\");\n\n // 10. Route host-origin fetches through RPC, and intercept host-origin\n // <link> insertions that would bypass that proxy. See ./fetch-proxy.ts and\n // ./link-interception.ts. Order matters: link interception fetches through\n // the patched proxy.\n const hostOrigin = d.hostOrigin;\n installFetchProxy(hostOrigin, rpc.fetchResource, log);\n installLinkInterception(hostOrigin, log);\n\n // Also intercept tool-spawned Web Workers: a worker can't load a host-origin\n // script from the opaque-origin iframe, so route its module loading back\n // through this iframe's RPC (same automerge filter, no new host surface, no\n // sync port). See ./worker-shim.ts.\n installWorkerShim({\n fetchModule: rpc.fetchModule,\n fetchResource: rpc.fetchResource,\n esmsSource: d.esmsSource,\n workerBootstrapSource,\n importMap: d.importMap,\n hostOrigin,\n log,\n });\n\n // 11. Create in-memory Repo\n const syncAdapter = new messagechannel.MessageChannelNetworkAdapter(\n init.syncPort\n );\n const repo = new automergeRepo.Repo({\n peerId: peerId,\n network: [syncAdapter],\n });\n (window as any).repo = repo;\n log(\"repo connected\");\n\n // 12. Register the patchwork-view and repo-provider custom elements, then\n // create the root <repo-provider> wrapper — mirrors the host bootloader\n // pattern. It answers `repo:handle-descriptor` subscriptions so\n // OverlayRepo.find() doesn't hang.\n patchworkElements.registerPatchworkViewElement({ repo });\n patchworkProviders.registerRepoProviderElement(repo);\n const repoProvider = document.createElement(\"repo-provider\");\n document.body.appendChild(repoProvider);\n\n // 13. Register plugins (initial set + drain any queued live pushes, then go\n // live). Now that importShim + the plugins module exist, hand them to the\n // registry created above. See ./registry.ts.\n registry.start(importShim, patchworkPlugins, d.registryEntries);\n\n // 14. Mount the isolated root component.\n // The root is an ordinary patchwork:component named by the boot spec; the\n // normal <patchwork-view component=...> path resolves and mounts it from the\n // iframe's own registry (incl. the not-yet-loaded and hot-reload cases). Its\n // data travels as an inert <script> child (created by rootComponentData.mount)\n // — data, never executable, so nothing tool-bearing is ever constructed from\n // host-supplied content. It is appended before the <patchwork-view> connects,\n // and patchwork-view defers its render by a microtask, so the data is in\n // place before the root's mount fn runs. Later changes arrive as\n // `root-component-data-update` messages (see handleRpcMessage / the\n // rootComponentData helper); the root re-reads reactively without a reboot.\n const rootView = document.createElement(\"patchwork-view\");\n rootView.setAttribute(\"component\", d.rootComponentId);\n rootComponentData.mount(rootView, d.rootComponentData ?? \"{}\");\n repoProvider.appendChild(rootView);\n\n // 15. Providers bridge — forward unclaimed patchwork:subscribe events to\n // the host so host-side providers can answer them (see ./providers-bridge.ts).\n providers.install();\n\n log(`boot complete — root \"${d.rootComponentId}\"`);\n rpcPort.postMessage({ type: \"boot-complete\" });\n } catch (err: any) {\n console.error(\"[iframe] boot failed:\", err);\n document.body.textContent = \"Failed to load tool: \" + (err.message || err);\n rpcPort.postMessage({ type: \"boot-error\", error: String(err) });\n }\n}\n","/**\n * `localStorage` stub for the sandboxed iframe. Injected into `boot()` and\n * serialized into the srcdoc by ../host/srcdoc.ts (see ./main.ts for why the\n * iframe helpers are defined at module scope but run inside the sandbox).\n */\n\n/**\n * Give the sandboxed iframe a `localStorage`. An opaque-origin iframe throws on\n * any `localStorage` access, which would break tools (and the `debug` package)\n * that read it. We install an in-memory no-op stub — except `getItem(\"debug\")`,\n * which returns `patchwork:*` so debug logging works inside the iframe when the\n * host has it enabled. Only runs if real `localStorage` is unavailable.\n */\nexport function installLocalStorageStub(): void {\n try {\n void localStorage;\n } catch {\n Object.defineProperty(window, \"localStorage\", {\n value: {\n getItem: (key: string) => (key === \"debug\" ? \"patchwork:*\" : null),\n setItem: () => {},\n removeItem: () => {},\n clear: () => {},\n length: 0,\n key: () => null,\n },\n });\n }\n}\n","/**\n * Host-origin fetch proxy for the sandboxed iframe. Injected into `boot()` and\n * serialized into the srcdoc by ../host/srcdoc.ts (see ./main.ts).\n */\n\nimport type { IframeLog } from \"./types.js\";\nimport type { FetchResourceResult } from \"./rpc.js\";\n\n/**\n * Install the host-origin fetch proxy. The sandboxed iframe can't reach the\n * host's service worker, so any fetch to a host-origin URL (package resources,\n * CSS @imports, etc.) is routed through the RPC `fetchResource` sender instead;\n * everything else falls through to the real `fetch`. Installed after WASM init\n * so `initializeWasm`/`initSync` aren't affected.\n */\nexport function installFetchProxy(\n hostOrigin: string,\n fetchResource: (url: string) => Promise<FetchResourceResult>,\n log: IframeLog\n): void {\n const originalFetch = self.fetch;\n (self as any).fetch = async (\n input: RequestInfo | URL,\n requestInit?: RequestInit\n ): Promise<Response> => {\n const url = typeof input === \"string\" ? input : input.toString();\n if (url.startsWith(hostOrigin)) {\n const result = await fetchResource(url);\n return new Response(result.body, {\n status: 200,\n headers: { \"Content-Type\": result.contentType },\n });\n }\n return originalFetch(input, requestInit);\n };\n log(\"fetch proxy installed\");\n}\n","/**\n * Host-origin `<link>` interception for the sandboxed iframe. Injected into\n * `boot()` and serialized into the srcdoc by ../host/srcdoc.ts (see ./main.ts).\n */\n\nimport type { IframeLog } from \"./types.js\";\n\n/**\n * Intercept host-origin <link> insertions SYNCHRONOUSLY, at insertion time.\n * Native <link> elements make direct browser requests that bypass the fetch\n * proxy and CORS-fail from the opaque origin. Crucially, the browser begins\n * that native request the instant the element is inserted — BEFORE any async\n * MutationObserver callback can run — so we can't fix it after the fact by\n * removing/replacing the node. We intervene before the node enters the DOM, by\n * patching the DOM insertion methods. Two cases, both produced at runtime by\n * code running inside the iframe:\n *\n * - rel=\"modulepreload\": emitted by bundler runtime (e.g. Vite's\n * __vitePreload) when a code-split chunk loads. Flip to \"modulepreload-shim\":\n * the browser ignores the unknown rel (no native fetch), while es-module-shims\n * honors it and preloads the chunk through its source hook → our RPC. (The\n * chunk also loads via the rewritten importShim dynamic import; this just\n * makes the parallel preload work instead of CORS-failing.)\n *\n * - rel=\"stylesheet\": emitted by tool code loaded inside isolation that injects\n * its own host-origin stylesheet <link> at runtime. Substitute a <style>\n * element in the link's place and fill it by fetching the CSS through the\n * proxy. The link itself never enters the DOM, so no native request is made.\n * We map the original link → its <style> so a later link.remove()/removeChild()\n * also removes the substituted <style>.\n *\n * Must run after `installFetchProxy` — the stylesheet path fetches through the\n * patched global `fetch`.\n */\nexport function installLinkInterception(hostOrigin: string, log: IframeLog): void {\n const styleForLink = new WeakMap<HTMLLinkElement, HTMLStyleElement>();\n\n // Returns a replacement node to insert instead of `node`, or `node` itself\n // (possibly mutated) when no substitution is needed.\n const interceptInsertedNode = (node: Node): Node => {\n if (\n !(node instanceof HTMLLinkElement) ||\n !node.href ||\n !node.href.startsWith(hostOrigin)\n ) {\n return node;\n }\n\n if (node.rel === \"modulepreload\") {\n log(\"converted modulepreload → modulepreload-shim:\", node.href);\n node.rel = \"modulepreload-shim\";\n return node;\n }\n\n if (node.rel === \"stylesheet\") {\n const href = node.href;\n const style = document.createElement(\"style\");\n // Carry over data-* attributes (some tools key off them).\n for (const attr of Array.from(node.attributes)) {\n if (attr.name.startsWith(\"data-\")) {\n style.setAttribute(attr.name, attr.value);\n }\n }\n styleForLink.set(node, style);\n fetch(href)\n .then((r) => r.text())\n .then((css) => {\n style.textContent = css;\n })\n .catch((err) => log(\"failed to load stylesheet:\", href, err));\n log(\"substituted stylesheet link → style:\", href);\n return style;\n }\n\n return node;\n };\n\n // Removal: when a substituted stylesheet <link> is removed, also remove the\n // <style> we inserted in its place. The link itself was never inserted (we\n // swapped in the <style>), so for a mapped link we just remove the style and\n // skip the native call (which would throw NotFoundError). For every other\n // node we defer to native behavior unchanged.\n const removeSubstituteStyle = (node: Node): boolean => {\n if (node instanceof HTMLLinkElement) {\n const style = styleForLink.get(node);\n if (style) {\n style.remove();\n styleForLink.delete(node);\n return true;\n }\n }\n return false;\n };\n\n // Install the prototype patches once. boot() runs a single time per iframe,\n // and the iframe (with these globals) is destroyed wholesale when the host\n // element is torn down — so there is nothing to restore. The guard stops the\n // wrappers stacking if this is ever re-invoked.\n const PATCH_FLAG = \"__patchworkDomPatched\";\n if (!(Node.prototype as any)[PATCH_FLAG]) {\n (Node.prototype as any)[PATCH_FLAG] = true;\n\n const patchInsertion = (method: \"appendChild\" | \"insertBefore\") => {\n const original = (Node.prototype as any)[method] as (\n ...args: any[]\n ) => Node;\n (Node.prototype as any)[method] = function (\n this: Node,\n ...args: any[]\n ): Node {\n args[0] = interceptInsertedNode(args[0]);\n return original.apply(this, args);\n };\n };\n patchInsertion(\"appendChild\");\n patchInsertion(\"insertBefore\");\n\n const originalRemoveChild = Node.prototype.removeChild;\n (Node.prototype as any).removeChild = function (\n this: Node,\n child: Node\n ): Node {\n if (removeSubstituteStyle(child)) return child;\n return originalRemoveChild.call(this, child);\n };\n const originalRemove = Element.prototype.remove;\n (Element.prototype as any).remove = function (this: Element): void {\n if (removeSubstituteStyle(this)) return;\n originalRemove.call(this);\n };\n }\n}\n","/**\n * The iframe side of the host RPC — request/reply for module source and static\n * resources. Runs inside the sandbox: like the other iframe helpers it's defined\n * at module scope (so tsc checks it) but serialized into the srcdoc by\n * ../host/srcdoc.ts and called from `boot()`.\n *\n * `createRpcClient` owns the reply-matching maps and the request counter, and\n * exposes the two senders plus `handle()`. `boot()` owns the RPC `MessagePort`\n * itself — because that one port also carries messages for other features\n * (live plugin registrations, the providers bridge) — so `boot()` registers the\n * port listener and calls `handle()` first, falling through to its own cases for\n * anything the client doesn't consume.\n */\n\nexport interface FetchModuleResult {\n source: string;\n resolvedUrl: string;\n}\n\nexport interface FetchResourceResult {\n body: ArrayBuffer;\n contentType: string;\n}\n\nexport interface RpcClient {\n /** Request a module's source + resolved URL (for the es-module-shims hook). */\n fetchModule(url: string): Promise<FetchModuleResult>;\n /** Request a static resource's bytes + content type (for the fetch proxy). */\n fetchResource(url: string): Promise<FetchResourceResult>;\n /**\n * Handle an inbound RPC message. Returns true if it was one of this client's\n * replies (and was consumed), false otherwise — letting the caller route the\n * message to another handler.\n */\n handle(event: MessageEvent): boolean;\n}\n\n/**\n * Create the iframe's RPC client over `port`. The port is owned by the caller\n * (`boot()`); this only sends requests and resolves the replies it recognizes.\n */\nexport function createRpcClient(port: MessagePort): RpcClient {\n const pendingModuleFetches = new Map<\n number,\n { resolve: (r: FetchModuleResult) => void; reject: (e: Error) => void }\n >();\n const pendingResourceFetches = new Map<\n number,\n { resolve: (r: FetchResourceResult) => void; reject: (e: Error) => void }\n >();\n let fetchId = 0;\n\n function fetchModule(url: string): Promise<FetchModuleResult> {\n return new Promise((resolve, reject) => {\n const id = ++fetchId;\n pendingModuleFetches.set(id, { resolve, reject });\n port.postMessage({ type: \"fetch-package\", id, url });\n });\n }\n\n function fetchResource(url: string): Promise<FetchResourceResult> {\n return new Promise((resolve, reject) => {\n const id = ++fetchId;\n pendingResourceFetches.set(id, { resolve, reject });\n port.postMessage({ type: \"fetch-resource\", id, url });\n });\n }\n\n function handle(event: MessageEvent): boolean {\n const msg = event.data;\n if (!msg) return false;\n\n if (msg.type === \"fetch-package-response\") {\n const pending = pendingModuleFetches.get(msg.id);\n if (pending) {\n pendingModuleFetches.delete(msg.id);\n pending.resolve({ source: msg.source, resolvedUrl: msg.resolvedUrl });\n }\n return true;\n }\n if (msg.type === \"fetch-package-error\") {\n const pending = pendingModuleFetches.get(msg.id);\n if (pending) {\n pendingModuleFetches.delete(msg.id);\n pending.reject(new Error(msg.error));\n }\n return true;\n }\n if (msg.type === \"fetch-resource-response\") {\n const pending = pendingResourceFetches.get(msg.id);\n if (pending) {\n pendingResourceFetches.delete(msg.id);\n pending.resolve({ body: msg.body, contentType: msg.contentType });\n }\n return true;\n }\n if (msg.type === \"fetch-resource-error\") {\n const pending = pendingResourceFetches.get(msg.id);\n if (pending) {\n pendingResourceFetches.delete(msg.id);\n pending.reject(new Error(msg.error));\n }\n return true;\n }\n\n return false;\n }\n\n return { fetchModule, fetchResource, handle };\n}\n","/**\n * The iframe side of the providers bridge (the host side is\n * bridges/providers-bridge.ts). Runs inside the sandbox: defined at module scope\n * so tsc checks it, serialized into the srcdoc by ../host/srcdoc.ts, and called\n * from `boot()`.\n *\n * Provider subscriptions (`patchwork:subscribe` events) that no in-iframe\n * provider claims are forwarded to the host over the RPC port, and the host's\n * pushed values are relayed back to the subscribing consumer. `createProvidersBridge`\n * owns the subscription bookkeeping; `boot()` owns the RPC port and calls\n * `handle()` for the inbound `providers-bridge-*` messages.\n */\n\nimport type { IframeLog } from \"./types.js\";\n\nexport interface ProvidersBridge {\n /**\n * Register the document-level `patchwork:subscribe` listener that forwards\n * unclaimed subscriptions to the host. Call once, after the RPC port is live.\n */\n install(): void;\n /**\n * Handle an inbound RPC message. Returns true if it was a `providers-bridge-*`\n * message (and was consumed), false otherwise.\n */\n handle(event: MessageEvent): boolean;\n}\n\n/**\n * Create the iframe's providers bridge over `rpcPort` (owned by the caller).\n */\nexport function createProvidersBridge(\n rpcPort: MessagePort,\n log: IframeLog\n): ProvidersBridge {\n // Consumer ports for subscriptions currently forwarded to the host, keyed by\n // the id we assigned when forwarding.\n const bridgedSubscriptions = new Map<number, MessagePort>();\n let bridgeId = 0;\n\n function handle(event: MessageEvent): boolean {\n const msg = event.data;\n if (!msg) return false;\n\n if (msg.type === \"providers-bridge-change\") {\n // Host provider pushed a value — relay to the consumer's port.\n log(\"providers-bridge: received change for id:\", msg.id, \"value:\", msg.value);\n const port = bridgedSubscriptions.get(msg.id);\n if (port) {\n port.postMessage({ type: \"change\", value: msg.value });\n }\n return true;\n }\n if (msg.type === \"providers-bridge-rejected\") {\n // Host rejected this subscription type — clean up.\n log(\"providers-bridge: rejected by host for id:\", msg.id);\n bridgedSubscriptions.delete(msg.id);\n return true;\n }\n\n return false;\n }\n\n function install(): void {\n // Forward unclaimed patchwork:subscribe events to the host so host-side\n // providers (e.g. AccountProvider for patchwork:contact) can answer them.\n // Local providers call stopPropagation(), so only unclaimed subscriptions\n // reach document.\n document.addEventListener(\"patchwork:subscribe\", ((event: CustomEvent) => {\n const detail = event.detail;\n if (!detail?.selector?.type || !detail?.port) return;\n\n log(\"providers-bridge: captured unclaimed subscription:\", detail.selector.type, detail.selector);\n\n event.stopPropagation();\n const id = ++bridgeId;\n const consumerPort = detail.port as MessagePort;\n bridgedSubscriptions.set(id, consumerPort);\n\n // Forward to host\n rpcPort.postMessage({\n type: \"providers-bridge\",\n id,\n selector: detail.selector,\n });\n\n // Listen for consumer unsubscribe\n consumerPort.addEventListener(\"message\", (e: MessageEvent) => {\n if (e.data?.type === \"unsubscribe\") {\n log(\"providers-bridge: consumer unsubscribed:\", detail.selector.type, id);\n rpcPort.postMessage({ type: \"providers-bridge-unsubscribe\", id });\n bridgedSubscriptions.delete(id);\n consumerPort.close();\n }\n });\n consumerPort.start();\n }) as EventListener);\n }\n\n return { install, handle };\n}\n","/**\n * Stands up es-module-shims inside the sandboxed iframe. Runs in the sandbox:\n * defined at module scope so tsc checks it, serialized into the srcdoc by\n * ../host/srcdoc.ts, and called from `boot()`.\n *\n * es-module-shims is what lets the iframe load ES modules at all: every import\n * goes through its `source` hook, which fetches the module text over RPC (the\n * iframe can't fetch host-origin URLs directly) and hands it back. `boot()` then\n * drives module loading through the returned `importShim`.\n */\n\nimport type { IframeLog } from \"./types.js\";\n\nexport interface ImportShim {\n (specifier: string): Promise<any>;\n addImportMap(map: { imports?: Record<string, string>; scopes?: any }): void;\n}\n\nexport interface EsModuleShimsConfig {\n /** The es-module-shims source, inlined into a <script> to load the shim. */\n esmsSource: string;\n /** The host's import map, resolved to absolute URLs. */\n importMap?: { imports?: Record<string, string>; scopes?: any };\n /** Fetches a module's source + resolved URL over RPC (see ./rpc.ts). */\n fetchModule: (\n url: string\n ) => Promise<{ source: string; resolvedUrl: string }>;\n log: IframeLog;\n}\n\n/**\n * Configure and load es-module-shims, then return its `importShim`. Steps:\n * 1. Set `esmsInitOptions` with a `source` hook that fetches every module over\n * RPC (and rewrites methods named `import` — see below).\n * 2. Inline the shim source as a <script> and wait a macrotask for it to init.\n * 3. Register the host's import map.\n */\nexport async function setupEsModuleShims(\n config: EsModuleShimsConfig\n): Promise<ImportShim> {\n const { esmsSource, importMap, fetchModule, log } = config;\n\n // Configure es-module-shims with the source hook before loading it.\n (self as any).esmsInitOptions = {\n shimMode: true,\n async source(\n url: string,\n _fetchOpts: any,\n _parent: string,\n _defaultSource: Function\n ) {\n log(\"source hook:\", url);\n const result = await fetchModule(url);\n // Rewrite class methods literally named `import` to bracket notation.\n // es-module-shims' lexer misreads a method named `import` as a dynamic\n // `import()` expression and throws a parse error. This is a live case,\n // not vestigial: @automerge/automerge-repo/slim's Repo class has an\n // `import(binary, args) { … }` method, and Repo loads into every iframe.\n const source = result.source.replace(\n /^(\\s+)import\\s*\\(([^)]*)\\)\\s*\\{/gm,\n '$1[\"import\"]($2) {'\n );\n return { source, url: result.resolvedUrl, type: \"js\" };\n },\n };\n\n // Inline es-module-shims source and wait for initialization.\n const esmsScript = document.createElement(\"script\");\n esmsScript.textContent = esmsSource;\n document.head.appendChild(esmsScript);\n\n await new Promise<void>((resolve) => setTimeout(resolve, 0));\n\n const importShim: ImportShim = (self as any).importShim;\n if (!importShim) {\n throw new Error(\"es-module-shims failed to initialize\");\n }\n\n // Add the host's import map.\n if (importMap) {\n importShim.addImportMap(importMap);\n }\n log(\"importmap configured\");\n\n return importShim;\n}\n","/**\n * Iframe-side Web Worker shim. Injected into `boot()` and serialized into the\n * srcdoc by ../host/srcdoc.ts (see ./main.ts), like `installFetchProxy`.\n *\n * A tool in the sandbox may construct a Web Worker (e.g. `@chee/patchwork-llm`'s\n * model worker). The opaque origin blocks it: a host-origin worker script can't\n * be loaded cross-origin, and even a same-origin blob worker can't load its own\n * modules (which resolve to host-origin URLs it can't fetch). The shim patches\n * `self.Worker` so that, for a module worker whose script is host-origin or a\n * `blob:` (a tool that fetched the script text itself), we instead build a\n * same-origin blob worker running es-module-shims + `workerBootstrap`, and hand\n * it a `MessagePort` back to the iframe. The worker's module/resource loads are\n * relayed over that port to the iframe's existing `fetchModule`/`fetchResource`\n * RPC — so the host sees only the iframe, and the worker gets no sync port and no\n * capability the iframe lacks. Other workers use the native `Worker`.\n */\n\nimport type { IframeLog } from \"./types.js\";\nimport type { FetchModuleResult, FetchResourceResult } from \"./rpc.js\";\nimport type { ImportMap } from \"../host/import-map.js\";\n\nexport interface WorkerShimDeps {\n fetchModule: (url: string) => Promise<FetchModuleResult>;\n fetchResource: (url: string) => Promise<FetchResourceResult>;\n /** es-module-shims source (same variant the iframe inlines). */\n esmsSource: string;\n /**\n * `workerBootstrap` serialized to source — injected, not imported, because\n * this shim is itself serialized into the srcdoc and can't reference another\n * module binding. Assembled in ../host/srcdoc.ts where both are in scope.\n */\n workerBootstrapSource: string;\n /** Host import map, resolved to absolute URLs. */\n importMap: ImportMap;\n /** Host origin — decides which worker scripts to intercept. */\n hostOrigin: string;\n log: IframeLog;\n}\n\nexport function installWorkerShim(deps: WorkerShimDeps): void {\n const {\n fetchModule,\n fetchResource,\n esmsSource,\n workerBootstrapSource,\n importMap,\n hostOrigin,\n log,\n } = deps;\n const OriginalWorker = self.Worker;\n\n // Intercept module workers whose script is host-origin (needs our relay) or a\n // `blob:` (a tool that fetched the worker text and made its own blob — still\n // can't load its modules from the sandbox). Others use the native constructor.\n function shouldIntercept(url: string, isModule: boolean): boolean {\n return (\n isModule && (url.startsWith(hostOrigin + \"/\") || url.startsWith(\"blob:\"))\n );\n }\n\n (self as any).Worker = function PatchedWorker(\n scriptURL: string | URL,\n options?: WorkerOptions\n ): Worker {\n const url =\n typeof scriptURL === \"string\" ? scriptURL : scriptURL.toString();\n if (!shouldIntercept(url, options?.type === \"module\")) {\n return new OriginalWorker(scriptURL, options);\n }\n log(\"worker shim: intercepting\", url.slice(0, 80));\n\n // Relay: forward the worker's module/resource requests to the iframe's RPC.\n const channel = new MessageChannel();\n channel.port1.addEventListener(\"message\", (event: MessageEvent) => {\n const m = event.data;\n if (m?.type === \"fetch-package\")\n relay(fetchModule(m.url), \"fetch-package\", m.id);\n else if (m?.type === \"fetch-resource\")\n relay(fetchResource(m.url), \"fetch-resource\", m.id);\n // Other message types are ignored — the relay exposes only fetch.\n });\n channel.port1.start();\n function relay(work: Promise<any>, type: string, id: number) {\n work.then(\n (r) => {\n const transfer = type === \"fetch-resource\" ? [r.body] : [];\n channel.port1.postMessage(\n { type: `${type}-response`, id, ...r },\n transfer\n );\n },\n (err) =>\n channel.port1.postMessage({\n type: `${type}-error`,\n id,\n error: err instanceof Error ? err.message : String(err),\n })\n );\n }\n\n // Construct the harness synchronously (tools do `new Worker(...)` then\n // `postMessage(...)`). It waits for the relay port; we fetch the entry (only\n // a blob's source must be delivered — host entries load via the relay) and\n // send it with the port. Failures surface as a worker error, not a hang.\n const worker = buildHarnessWorker();\n resolveEntry(url).then(\n (entrySource) =>\n worker.postMessage(\n { type: \"isolation-relay-port\", entryUrl: url, entrySource },\n [channel.port2]\n ),\n (err) => {\n log(\"worker shim: failed to load entry source\", err);\n worker.postMessage({\n type: \"isolation-relay-error\",\n error: err instanceof Error ? err.message : String(err),\n });\n }\n );\n return worker;\n } as unknown as typeof Worker;\n\n // A `blob:` entry can't be fetched by the worker, so read its text here (the\n // blob is same-origin to the iframe) and deliver it. A host-origin entry is\n // loaded by the worker's source hook via the relay, so no source is delivered.\n async function resolveEntry(url: string): Promise<string | undefined> {\n if (!url.startsWith(\"blob:\")) return undefined;\n return (await fetch(url)).text();\n }\n\n /**\n * Build the harness worker from a blob of three parts (order matters:\n * es-module-shims reads `esmsInitOptions` synchronously when it evaluates):\n * 1. `workerBootstrap(params)` — installs the relay-backed `source` hook.\n * 2. es-module-shims source.\n * 3. `__isolationWorkerStart()` — runs the entry.\n *\n * A CLASSIC worker (not `{type:\"module\"}`): the blob has no top-level\n * import/export (es-module-shims is an IIFE; the bootstrap uses only dynamic\n * `importShim`), and a classic worker's top-level script is exempt from the\n * \"module worker can't follow a cross-origin redirect\" restriction. All real\n * ESM inside runs through es-module-shims.\n */\n function buildHarnessWorker(): Worker {\n const params = { importMap, hostOrigin };\n const blobSource = [\n `(${workerBootstrapSource})(${JSON.stringify(params)});`,\n esmsSource,\n `self.__isolationWorkerStart().catch((e) => { throw e; });`,\n ].join(\"\\n\");\n const blobUrl = URL.createObjectURL(\n new Blob([blobSource], { type: \"text/javascript\" })\n );\n const worker = new OriginalWorker(blobUrl);\n // Revoke on a later turn: the worker fetches its blob asynchronously, and\n // revoking synchronously would fail the load.\n setTimeout(() => URL.revokeObjectURL(blobUrl), 10000);\n return worker;\n }\n}\n","/**\n * The bootstrap that runs INSIDE a tool-spawned Web Worker.\n *\n * A tool in the isolated iframe may construct a Web Worker (e.g.\n * `@chee/patchwork-llm`'s model worker). The iframe's opaque origin means a\n * worker can't load host-origin scripts, and even a same-origin blob worker has\n * none of the iframe's module-loading machinery. This bootstrap re-establishes\n * it *inside the worker*: es-module-shims with a `source` hook that relays\n * host-origin module/resource loads back to the iframe (never to the host\n * directly), so the worker can load nothing the iframe couldn't. External (CDN)\n * modules are fetched directly by the worker. See `./worker-shim.ts` for the\n * iframe side that builds and wires this.\n *\n * Serialized with `.toString()` (by `./worker-shim.ts`) into the worker blob, so\n * it must not reference module-scope bindings — everything is a parameter, a\n * local, or a global.\n *\n * **Ordering.** es-module-shims reads `self.esmsInitOptions` synchronously when\n * its source evaluates, so the blob runs in three parts: (1) this function,\n * which installs `esmsInitOptions` and stashes `self.__isolationWorkerStart`;\n * (2) the es-module-shims source; (3) `__isolationWorkerStart()`.\n *\n * The worker's own application protocol uses `self.postMessage`/`onmessage`; the\n * iframe relay is a separate, transferred `MessagePort`.\n */\n\nimport type { ImportMap } from \"../host/import-map.js\";\n\nexport interface WorkerBootstrapParams {\n /** The host's import map, resolved to absolute URLs (same as the iframe's). */\n importMap: ImportMap;\n /** Host origin — module/resource URLs under it relay to the iframe. */\n hostOrigin: string;\n}\n\n/** What the iframe delivers to boot the worker (relay port + entry to run). */\ninterface RelayInit {\n port: MessagePort;\n /** Entry module URL, used as its base so relative imports resolve. */\n entryUrl: string;\n /**\n * Entry source, supplied ONLY for a `blob:` entry (the worker can't fetch the\n * iframe's blob URL). Host-origin entries are loaded via the relay like any\n * other module, so this is undefined for them.\n */\n entrySource?: string;\n}\n\nexport function workerBootstrap(params: WorkerBootstrapParams): void {\n // ── App-message buffering ────────────────────────────────────────────────\n // The tool posts app messages (e.g. `{type:\"generate\"}`) on the worker's\n // global channel before the real worker installs `self.onmessage` (its module\n // loads asynchronously over the relay). Buffer non-relay messages and replay\n // them once the handler is set. The target workers use `self.onmessage = …`\n // (assignment), so intercepting that property suffices.\n let appHandler: ((ev: MessageEvent) => void) | null = null;\n const appBuffer: MessageEvent[] = [];\n try {\n Object.defineProperty(self, \"onmessage\", {\n configurable: true,\n get: () => appHandler,\n set(fn: ((ev: MessageEvent) => void) | null) {\n appHandler = fn;\n if (fn) for (const ev of appBuffer.splice(0)) fn(ev);\n },\n });\n } catch {\n // If onmessage can't be redefined, fall back to no buffering (best effort).\n }\n\n // ── Relay to the iframe (request/reply over a MessagePort) ───────────────\n let relayPort: MessagePort | undefined;\n let reqId = 0;\n const pending = new Map<\n number,\n { resolve: (v: any) => void; reject: (e: Error) => void }\n >();\n\n // One persistent global listener: claim the iframe's relay-init/-error control\n // messages; route everything else (tool app messages) through the buffer.\n const relayReady = new Promise<RelayInit>((resolve, reject) => {\n self.addEventListener(\"message\", (event: MessageEvent) => {\n const m = event.data;\n if (m && m.type === \"isolation-relay-port\") {\n resolve({\n port: event.ports[0],\n entryUrl: m.entryUrl,\n entrySource: m.entrySource,\n });\n } else if (m && m.type === \"isolation-relay-error\") {\n reject(new Error(m.error));\n } else if (appHandler) {\n appHandler(event);\n } else {\n appBuffer.push(event);\n }\n });\n });\n\n // Generic request/reply. `type` is \"fetch-package\" | \"fetch-resource\"; the\n // reply is `<type>-response` (resolve) or `<type>-error` (reject).\n function request<T>(type: string, url: string): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n const id = ++reqId;\n pending.set(id, { resolve, reject });\n relayPort!.postMessage({ type, id, url });\n });\n }\n function onRelayMessage(event: MessageEvent) {\n const m = event.data;\n if (!m || typeof m.id !== \"number\") return;\n const p = pending.get(m.id);\n if (!p) return;\n pending.delete(m.id);\n if (m.type === \"fetch-package-response\")\n p.resolve({ source: m.source, resolvedUrl: m.resolvedUrl });\n else if (m.type === \"fetch-resource-response\")\n p.resolve({ body: m.body, contentType: m.contentType });\n else if (m.type.endsWith(\"-error\")) p.reject(new Error(m.error));\n }\n\n // Bracket a class method literally named `import` — es-module-shims' lexer\n // misreads it as a dynamic import. Only relayed host modules need this (e.g.\n // @automerge/automerge-repo/slim's `Repo.import()`); it matches ../es-module-shims.ts.\n function fixImportMethod(src: string): string {\n return src.replace(\n /^(\\s+)import\\s*\\(([^)]*)\\)\\s*\\{/gm,\n '$1[\"import\"]($2) {'\n );\n }\n\n // A `blob:` entry can't be fetched by the worker, so its source is delivered in\n // the relay-init message; phase 2 records it here for the source hook to serve\n // (host-origin entries are undefined here and load via the relay like any\n // other module). Set before `importShim(entry)` runs, so the hook sees it.\n let blobEntry: { url: string; source: string } | undefined;\n\n // Install the source hook BEFORE the shim source runs (see Ordering above).\n // Host-origin modules relay to the iframe (same allowlist + marker resolution);\n // external modules are fetched directly by the worker (its `fetch` follows\n // redirects and returns final text, so a CDN import that would fail as a\n // module-worker cross-origin redirect works here).\n (self as any).esmsInitOptions = {\n shimMode: true,\n async source(url: string) {\n if (blobEntry && url === blobEntry.url) {\n return {\n source: fixImportMethod(blobEntry.source),\n url: blobEntry.url,\n type: \"js\" as const,\n };\n }\n if (url.startsWith(params.hostOrigin + \"/\")) {\n const r = await request<{ source: string; resolvedUrl: string }>(\n \"fetch-package\",\n url\n );\n return {\n source: fixImportMethod(r.source),\n url: r.resolvedUrl,\n type: \"js\" as const,\n };\n }\n const res = await fetch(url);\n if (!res.ok) throw new Error(`worker source ${url}: HTTP ${res.status}`);\n return {\n source: await res.text(),\n url: res.url || url,\n type: \"js\" as const,\n };\n },\n };\n\n // Phase 2: the blob calls this after the shim source has evaluated. The name\n // is inlined (not a module-scope const) so it survives `.toString()`.\n (self as any).__isolationWorkerStart = async function start() {\n const importShim = (self as any).importShim as\n | ((specifier: string) => Promise<any>)\n | undefined;\n if (!importShim)\n throw new Error(\"worker: es-module-shims failed to initialize\");\n\n const init = await relayReady;\n relayPort = init.port;\n relayPort.addEventListener(\"message\", onRelayMessage);\n relayPort.start();\n\n if (params.importMap) importShim.addImportMap(params.importMap);\n\n // Route the worker's own host-origin fetch(es) through the relay too\n // (mirrors ../fetch-proxy.ts); non-host fetches use native fetch.\n const nativeFetch = self.fetch;\n (self as any).fetch = async (\n input: RequestInfo | URL,\n fetchInit?: RequestInit\n ) => {\n const u = typeof input === \"string\" ? input : input.toString();\n if (u.startsWith(params.hostOrigin)) {\n const r = await request<{ body: ArrayBuffer; contentType: string }>(\n \"fetch-resource\",\n u\n );\n return new Response(r.body, {\n status: 200,\n headers: { \"Content-Type\": r.contentType },\n });\n }\n return nativeFetch(input, fetchInit);\n };\n\n // Record a blob entry's delivered source for the source hook (see above).\n if (init.entrySource !== undefined) {\n blobEntry = { url: init.entryUrl, source: init.entrySource };\n }\n\n await importShim(init.entryUrl);\n };\n}\n","/**\n * The iframe's plugin registry. Runs inside the sandbox: defined at module scope\n * so tsc checks it, serialized into the srcdoc by ../host/srcdoc.ts, and called\n * from `boot()`.\n *\n * Two-phase because of timing: `plugin-registered` pushes can arrive on the RPC\n * port as soon as it's live (early in boot), but actually registering a plugin\n * needs `importShim` + the plugins module, which don't exist until modules load.\n * So `handle()` queues early arrivals; `start()` (called once the modules are\n * ready) registers the initial set, drains the queue, and switches to live mode\n * where subsequent `handle()` calls register immediately.\n */\n\nimport type { RegistryEntry } from \"../../types.js\";\nimport type { IframeLog } from \"./types.js\";\n\n/** The `@inkandswitch/patchwork-plugins` module surface the registry needs. */\ninterface PatchworkPlugins {\n registerPlugins(plugins: unknown[], importUrl: string): void;\n}\n\n/** The es-module-shims importer used to lazy-load a plugin's implementation. */\ntype ImportShim = (specifier: string) => Promise<any>;\n\nexport interface Registry {\n /**\n * Handle an inbound RPC message. Returns true if it was a `plugin-registered`\n * push (and was consumed), false otherwise. Before `start()`, consumed pushes\n * are queued; after, they register immediately.\n */\n handle(event: MessageEvent): boolean;\n /**\n * Register the initial entries, drain any queued pushes, and switch to live\n * mode. Call once, after the runtime modules are loaded.\n */\n start(\n importShim: ImportShim,\n patchworkPlugins: PatchworkPlugins,\n entries: RegistryEntry[] | undefined\n ): void;\n}\n\nexport function createRegistry(log: IframeLog): Registry {\n // Early `plugin-registered` arrivals wait here until start() runs; null once\n // started (live mode registers immediately instead of queuing).\n let pending: RegistryEntry[] | null = [];\n let importShim: ImportShim;\n let patchworkPlugins: PatchworkPlugins;\n\n // Register one entry as a lazy-loading plugin. importUrls are `registry--`\n // marker URLs (mapped by the host before boot); the implementation is fetched\n // via importShim only when the plugin is actually used.\n function registerEntry(entry: RegistryEntry) {\n const plugin = {\n ...entry,\n load: entry.importUrl\n ? async () => {\n const mod = await importShim(entry.importUrl!);\n // A module that exports a `plugins` array (the common case) must\n // contain an entry matching this registration's id+type — that entry's\n // own load() is the implementation. If none matches, the module does\n // not provide what this entry claims; fail loudly rather than returning\n // the module namespace object (a non-function), which would surface far\n // downstream as an opaque \"module is not a function\" mount error.\n if (Array.isArray(mod.plugins)) {\n const match = mod.plugins.find(\n (p: any) => p.id === entry.id && p.type === entry.type\n );\n if (match && typeof match.load === \"function\") {\n return match.load();\n }\n const available = mod.plugins\n .map((p: any) => `${p.type}:${p.id}`)\n .join(\", \");\n throw new Error(\n `plugin ${entry.type}:${entry.id} not found in module ${entry.importUrl} ` +\n `(exports: ${available || \"none\"})`\n );\n }\n // No `plugins` array — a plain module whose default/namespace export is\n // the implementation.\n return mod.default || mod;\n }\n : undefined,\n };\n patchworkPlugins.registerPlugins([plugin], entry.importUrl || \"\");\n }\n\n function handle(event: MessageEvent): boolean {\n const msg = event.data;\n if (!msg || msg.type !== \"plugin-registered\") return false;\n if (pending) {\n pending.push(msg.entry); // not started yet — queue it\n } else {\n log(\"registering live plugin update:\", msg.entry.id);\n registerEntry(msg.entry);\n }\n return true;\n }\n\n function start(\n shim: ImportShim,\n plugins: PatchworkPlugins,\n entries: RegistryEntry[] | undefined\n ): void {\n importShim = shim;\n patchworkPlugins = plugins;\n\n if (entries) {\n for (const entry of entries) registerEntry(entry);\n log(\"plugins registered:\", entries.length);\n }\n\n // Drain pushes that arrived before we were ready, then switch to live mode.\n const queued = pending ?? [];\n pending = null;\n for (const entry of queued) {\n log(\"registering deferred plugin update:\", entry.id);\n registerEntry(entry);\n }\n }\n\n return { handle, start };\n}\n","/**\n * The root component's data, inside the iframe. Runs in the sandbox: defined at\n * module scope so tsc checks it, serialized into the srcdoc by ../host/srcdoc.ts,\n * and called from `boot()`.\n *\n * The host relays the root's inputs as an opaque JSON string it never parses\n * (see boot/host/config.ts). Here we materialize that string into an inert\n * `<script type=\"application/json\" data-root-component-data>` child of the root\n * `<patchwork-view>` — data, never executable, so nothing tool-bearing is ever\n * constructed from host-supplied code. The root component reads (and reactively\n * re-reads) that script.\n *\n * Live updates: the host watches its own data `<script>` and sends\n * `root-component-data-update` messages; `handle()` rewrites this script's text\n * in place (no reboot), and the root observes the node and re-reads.\n */\n\nimport type { IframeLog } from \"./types.js\";\n\nexport interface RootComponentData {\n /**\n * Create the inert data `<script>` (seeded with `initialData`) and append it\n * to the root view. Call once, before the `<patchwork-view>` connects, so the\n * data is in place before the root's mount fn runs.\n */\n mount(rootView: HTMLElement, initialData: string): void;\n /**\n * Handle an inbound RPC message. Returns true if it was a\n * `root-component-data-update` (and rewrote the script), false otherwise —\n * letting the caller route the message to another consumer.\n */\n handle(event: MessageEvent): boolean;\n}\n\n/** Create the iframe-side root-component-data manager. */\nexport function createRootComponentData(log: IframeLog): RootComponentData {\n let script: HTMLScriptElement | null = null;\n\n function mount(rootView: HTMLElement, initialData: string) {\n script = document.createElement(\"script\");\n script.type = \"application/json\";\n script.setAttribute(\"data-root-component-data\", \"\");\n // Verbatim — the data is already a JSON string from the host; do not\n // re-serialize (the boundary treats it as an opaque blob).\n script.textContent = initialData ?? \"{}\";\n rootView.appendChild(script);\n }\n\n function handle(event: MessageEvent): boolean {\n if (event.data?.type !== \"root-component-data-update\") return false;\n // Inert data, never executed — same trust posture as the boot-time value.\n if (script) {\n script.textContent = event.data.rootComponentData;\n log(\"root component data updated\");\n }\n return true;\n }\n\n return { mount, handle };\n}\n","/**\n * Drag-and-drop, inside the iframe. Runs in the sandbox: defined at module scope\n * so tsc checks it, serialized into the srcdoc by ../host/srcdoc.ts, and called\n * from `boot()`.\n *\n * A host-forwarded drag (see bridges/drag-drop-bridge.ts) arrives as a `drop`\n * RPC message carrying the already-gated, already-filtered document formats plus\n * the iframe-local drop coordinates. Native drag events can't cross into a\n * cross-origin iframe with any usable data, so the host reconstructs the drop\n * over RPC and this module re-dispatches it as a *synthetic* DOM drop — letting\n * an isolated tool's own drop handler (e.g. codemirror-markdown's) consume it\n * unchanged. Tool-agnostic: nothing here knows about any particular tool.\n *\n * A cross-realm drop is always a copy (`effectAllowed`/`dropEffect` = \"copy\") —\n * the host-side move-vs-link identity check can't span realms, and embedding a\n * document reference is the correct semantic anyway.\n */\n\nimport type { IframeLog } from \"./types.js\";\n\nexport interface DragDrop {\n /**\n * Handle an inbound RPC message. Returns true if it was a `drop` (and\n * re-dispatched a synthetic drop), false otherwise — letting the caller route\n * the message to another consumer.\n */\n handle(event: MessageEvent): boolean;\n}\n\n/** Create the iframe-side drag-and-drop consumer. */\nexport function createDragDrop(log: IframeLog): DragDrop {\n function handle(event: MessageEvent): boolean {\n if (event.data?.type !== \"drop\") return false;\n\n const { formats, x, y } = event.data as {\n formats: Record<string, string>;\n x: number;\n y: number;\n };\n\n // The element under the drop point is where the tool's handler lives (it\n // typically registers on a content element and reads via bubbling).\n // Dispatching here mirrors a real drop's target so target-membership checks\n // (e.g. CodeMirror's `eventBelongsToEditor`) pass.\n const target = document.elementFromPoint(x, y);\n if (!target) {\n log(\"synthetic drop: no element at drop point\");\n return true;\n }\n\n const dt = new DataTransfer();\n for (const [type, data] of Object.entries(formats)) {\n try {\n dt.setData(type, data);\n } catch {\n // Some environments guard setData outside a real drag; skip that format.\n }\n }\n dt.effectAllowed = \"copy\";\n dt.dropEffect = \"copy\";\n\n const init: DragEventInit = {\n bubbles: true,\n cancelable: true,\n composed: true,\n clientX: x,\n clientY: y,\n dataTransfer: dt,\n };\n // Fire dragover then drop: some drop targets only arm on a preceding\n // dragover (and it lets them set dropEffect), matching a real sequence.\n target.dispatchEvent(new DragEvent(\"dragover\", init));\n target.dispatchEvent(new DragEvent(\"drop\", init));\n log(\"synthetic drop dispatched\");\n return true;\n }\n\n return { handle };\n}\n","/**\n * Builds the `srcdoc` HTML string for the isolated iframe — the host-side\n * assembly step. The iframe's runtime code lives in `./iframe-bootstrap.ts` as\n * typed functions (`boot` + its injected helpers); here we serialize them with\n * `.toString()` into the srcdoc's `<script>` and wrap them in the minimal HTML\n * shell (base layout + first-paint theming).\n */\n\nimport { boot } from \"../iframe/main.js\";\nimport { installLocalStorageStub } from \"../iframe/local-storage.js\";\nimport { installFetchProxy } from \"../iframe/fetch-proxy.js\";\nimport { installLinkInterception } from \"../iframe/link-interception.js\";\nimport { createRpcClient } from \"../iframe/rpc.js\";\nimport { createProvidersBridge } from \"../iframe/providers-bridge.js\";\nimport { setupEsModuleShims } from \"../iframe/es-module-shims.js\";\nimport { installWorkerShim } from \"../iframe/worker-shim.js\";\nimport { workerBootstrap } from \"../iframe/worker-bootstrap.js\";\nimport { createRegistry } from \"../iframe/registry.js\";\nimport { createRootComponentData } from \"../iframe/root-component-data.js\";\nimport { createDragDrop } from \"../iframe/drag-drop.js\";\n\n/**\n * The host's current resolved appearance, used to paint the iframe's first\n * frame to match. Both values are resolved browser values (not theming-tool\n * variables/attributes), so this stays independent of any specific theme tool.\n */\nexport interface IframeAppearance {\n /** Resolved background color to paint before the theme CSS loads. */\n background?: string;\n /** Resolved `color-scheme` (so form controls/scrollbars match immediately). */\n colorScheme?: string;\n}\n\n/**\n * Allow only characters that are safe to interpolate into the static srcdoc\n * CSS below. These values come from the host's own computed styles (a resolved\n * `rgb(...)`/`color()` string and a `color-scheme` keyword), not from tools,\n * but we sanitize anyway so nothing can break out of the <style> context.\n */\nfunction cssSafe(value: string): string {\n return value.replace(/[^a-zA-Z0-9 #%(),.\\-/]/g, \"\");\n}\n\n/**\n * Build the iframe srcdoc. The host's current background and color-scheme are\n * baked into the static markup so the iframe's *first paint* already matches\n * the host — eliminating the flash of white that otherwise shows until the\n * theming tool boots inside the iframe and applies the real theme CSS. This is\n * tool-agnostic: it mirrors whatever the host actually renders, with no\n * knowledge of how (or which tool) produced it.\n */\nexport function generateIframeSrcdoc(appearance?: IframeAppearance): string {\n const background = appearance?.background ? cssSafe(appearance.background) : \"\";\n const colorScheme = appearance?.colorScheme\n ? cssSafe(appearance.colorScheme)\n : \"\";\n const firstPaint =\n background || colorScheme\n ? `\\n ${colorScheme ? `color-scheme: ${colorScheme};` : \"\"}${\n background ? ` background: ${background};` : \"\"\n }`\n : \"\";\n\n return `<!DOCTYPE html>\n<html>\n<head>\n <meta charset=\"utf-8\">\n <style>\n *, *::before, *::after { box-sizing: border-box; }\n html, body {\n margin: 0;\n padding: 0;\n width: 100%;\n height: 100%;\n overflow: hidden;\n display: flex;\n flex-direction: row;${firstPaint}\n }\n /* Base layout for the platform elements, mirroring the host app shell's\n global.css. Without these, patchwork-view / repo-provider default to\n display:inline inside the iframe and any root that relies on a full-size\n flex/height context (e.g. a frame's document column) collapses. The host\n provides this for free via its site stylesheet; the isolated realm must\n provide it itself since that stylesheet does not cross the boundary. */\n repo-provider {\n flex: 1;\n min-width: 0;\n display: flex;\n width: 100%;\n height: 100%;\n }\n patchwork-view {\n display: block;\n width: 100%;\n height: 100%;\n contain: layout;\n }\n </style>\n</head>\n<body>\n <script>\n // The iframe script. boot() and its injected code (helpers + RPC client) are\n // defined as typed functions in ../iframe/*.ts and serialized in here via\n // .toString(); they're passed to boot() since they can't close over its scope.\n (${boot.toString()})({\n installLocalStorageStub: ${installLocalStorageStub.toString()},\n installFetchProxy: ${installFetchProxy.toString()},\n installLinkInterception: ${installLinkInterception.toString()},\n createRpcClient: ${createRpcClient.toString()},\n createProvidersBridge: ${createProvidersBridge.toString()},\n setupEsModuleShims: ${setupEsModuleShims.toString()},\n installWorkerShim: ${installWorkerShim.toString()},\n workerBootstrapSource: ${JSON.stringify(workerBootstrap.toString())},\n createRegistry: ${createRegistry.toString()},\n createRootComponentData: ${createRootComponentData.toString()},\n createDragDrop: ${createDragDrop.toString()},\n });\n </script>\n</body>\n</html>`;\n}\n","/**\n * Reads the live host page's current visual state so the iframe can match it.\n * Two reads, both host-side and both tool-agnostic:\n * - `readHostAppearance` — the resolved background + color-scheme, baked into\n * the iframe's srcdoc so its first paint matches (no flash of white before\n * the theming tool boots inside).\n * - `collectHostStyles` — the host's stylesheets as one CSS string, injected\n * into the iframe so tools render with the same CSS framework as the host.\n */\n\n/**\n * The host's current appearance, read off the live page so the iframe can match\n * it from its very first paint (avoiding a flash of unstyled white before the\n * theming tool boots inside the iframe).\n *\n * Both values are read tool-agnostically — as *resolved* browser values, not\n * via any theming tool's CSS variables, attribute conventions, or palette. The\n * platform must not depend on which theming tool (if any) is installed:\n * - `background` is the host's actual painted background, found by walking up\n * from the isolation element to the first ancestor with a non-transparent\n * computed `backgroundColor` (whatever produced it). Empty if none.\n * - `colorScheme` is the resolved `color-scheme` (a CSS standard property) so\n * the iframe's scrollbars/form controls match. Empty if unset.\n *\n * The real theme is applied to the iframe's content later, when the theming\n * tool boots inside it; this only paints the first frame so it doesn't flash.\n */\nexport interface HostAppearance {\n background: string;\n colorScheme: string;\n}\n\nexport function readHostAppearance(el: Element): HostAppearance {\n // Walk ancestors for the first real (non-transparent) background. The visible\n // backdrop behind the iframe is painted by some ancestor (e.g. a frame\n // container); we mirror its resolved color without knowing which element or\n // how it was themed.\n let background = \"\";\n for (let node: Element | null = el; node; node = node.parentElement) {\n const bg = getComputedStyle(node).backgroundColor;\n if (bg && bg !== \"transparent\" && !bg.startsWith(\"rgba(0, 0, 0, 0)\")) {\n background = bg;\n break;\n }\n }\n\n const colorScheme = getComputedStyle(document.documentElement).colorScheme;\n return {\n background,\n // \"normal\" is the unset default — don't emit it.\n colorScheme: colorScheme && colorScheme !== \"normal\" ? colorScheme : \"\",\n };\n}\n\n/** Collect all host page stylesheets as a single CSS string. */\nexport async function collectHostStyles(): Promise<string> {\n const sheets = await Promise.all(\n Array.from(document.styleSheets).map(async (sheet) => {\n try {\n return Array.from(sheet.cssRules)\n .map((r) => r.cssText)\n .join(\"\\n\");\n } catch {\n if (sheet.href) {\n try {\n return await fetch(sheet.href).then((r) => r.text());\n } catch {\n return \"\";\n }\n }\n return \"\";\n }\n })\n );\n return sheets.filter(Boolean).join(\"\\n\");\n}\n","// AUTO-GENERATED by scripts/generate-esms-source.mjs — do not edit.\n// Source: es-module-shims/wasm (matches the variant core serves at /es-module-shims.js).\nexport const esmsSource: string = \"/** ES Module Shims Wasm @version 2.8.4 */\\n(function () {\\n\\n const self_ = typeof globalThis !== 'undefined' ? globalThis : self;\\n\\n let invalidate;\\n const hotReload$1 = url => invalidate(new URL(url, baseUrl).href);\\n const initHotReload = (topLevelLoad, importShim) => {\\n let _importHook = importHook,\\n _resolveHook = resolveHook,\\n _metaHook = metaHook;\\n\\n let defaultResolve;\\n let hotResolveHook = (id, parent, _defaultResolve) => {\\n if (!defaultResolve) defaultResolve = _defaultResolve;\\n const originalParent = stripVersion(parent);\\n const url = stripVersion(defaultResolve(id, originalParent));\\n const hotState = getHotState(url);\\n const parents = hotState.p;\\n if (!parents.includes(originalParent)) parents.push(originalParent);\\n return toVersioned(url, hotState);\\n };\\n const hotImportHook = (url, _, __, source, sourceType) => {\\n const hotState = getHotState(url);\\n hotState.e = typeof source === 'string' ? source : true;\\n hotState.t = sourceType;\\n };\\n const hotMetaHook = (metaObj, url) => (metaObj.hot = new Hot(url));\\n\\n const Hot = class Hot {\\n constructor(url) {\\n this.data = getHotState((this.url = stripVersion(url))).d;\\n }\\n accept(deps, cb) {\\n if (typeof deps === 'function') {\\n cb = deps;\\n deps = null;\\n }\\n const hotState = getHotState(this.url);\\n if (!hotState.A) return;\\n (hotState.a = hotState.a || []).push([\\n typeof deps === 'string' ? defaultResolve(deps, this.url)\\n : deps ? deps.map(d => defaultResolve(d, this.url))\\n : null,\\n cb\\n ]);\\n }\\n dispose(cb) {\\n getHotState(this.url).u = cb;\\n }\\n invalidate() {\\n const hotState = getHotState(this.url);\\n hotState.a = hotState.A = null;\\n const seen = [this.url];\\n hotState.p.forEach(p => invalidate(p, this.url, seen));\\n }\\n };\\n\\n const versionedRegEx = /\\\\?v=\\\\d+$/;\\n const stripVersion = url => {\\n const versionMatch = url.match(versionedRegEx);\\n return versionMatch ? url.slice(0, -versionMatch[0].length) : url;\\n };\\n\\n const toVersioned = (url, hotState) => {\\n const { v } = hotState;\\n return url + (v ? '?v=' + v : '');\\n };\\n\\n let hotRegistry = {},\\n curInvalidationRoots = new Set(),\\n curInvalidationInterval;\\n const getHotState = url =>\\n hotRegistry[url] ||\\n (hotRegistry[url] = {\\n // version\\n v: 0,\\n // accept list ([deps, cb] pairs)\\n a: null,\\n // accepting acceptors\\n A: true,\\n // unload callback\\n u: null,\\n // entry point or inline script source\\n e: false,\\n // hot data\\n d: {},\\n // parents\\n p: [],\\n // source type\\n t: undefined\\n });\\n\\n invalidate = (url, fromUrl, seen = []) => {\\n const hotState = hotRegistry[url];\\n if (!hotState || seen.includes(url)) return false;\\n seen.push(url);\\n hotState.A = false;\\n if (\\n fromUrl &&\\n hotState.a &&\\n hotState.a.some(([d]) => d && (typeof d === 'string' ? d === fromUrl : d.includes(fromUrl)))\\n ) {\\n curInvalidationRoots.add(fromUrl);\\n } else {\\n if (hotState.e || hotState.a) curInvalidationRoots.add(url);\\n hotState.v++;\\n if (!hotState.a) hotState.p.forEach(p => invalidate(p, url, seen));\\n }\\n if (!curInvalidationInterval) curInvalidationInterval = setTimeout(handleInvalidations, hotReloadInterval);\\n return true;\\n };\\n\\n const handleInvalidations = () => {\\n curInvalidationInterval = null;\\n const earlyRoots = new Set();\\n for (const root of curInvalidationRoots) {\\n const hotState = hotRegistry[root];\\n topLevelLoad(\\n toVersioned(root, hotState),\\n baseUrl,\\n defaultFetchOpts,\\n typeof hotState.e === 'string' ? hotState.e : undefined,\\n false,\\n undefined,\\n hotState.t\\n ).then(m => {\\n if (hotState.a) {\\n hotState.a.forEach(([d, c]) => d === null && !earlyRoots.has(c) && c(m));\\n // unload should be the latest unload handler from the just loaded module\\n if (hotState.u) {\\n hotState.u(hotState.d);\\n hotState.u = null;\\n }\\n }\\n hotState.p.forEach(p => {\\n const hotState = hotRegistry[p];\\n if (hotState && hotState.a)\\n hotState.a.forEach(\\n async ([d, c]) =>\\n d &&\\n !earlyRoots.has(c) &&\\n (typeof d === 'string' ?\\n d === root && c(m)\\n : c(await Promise.all(d.map(d => (earlyRoots.add(c), importShim(toVersioned(d, getHotState(d))))))))\\n );\\n });\\n }, throwError);\\n }\\n curInvalidationRoots = new Set();\\n };\\n\\n setHooks(\\n _importHook ? chain(_importHook, hotImportHook) : hotImportHook,\\n _resolveHook ?\\n (id, parent, defaultResolve) =>\\n hotResolveHook(id, parent, (id, parent) => _resolveHook(id, parent, defaultResolve))\\n : hotResolveHook,\\n _metaHook ? chain(_metaHook, hotMetaHook) : hotMetaHook\\n );\\n };\\n\\n const hasDocument = typeof document !== 'undefined';\\n\\n const noop = () => {};\\n\\n const chain = (a, b) =>\\n function () {\\n a.apply(this, arguments);\\n b.apply(this, arguments);\\n };\\n\\n const dynamicImport = (u, _errUrl) => import(u);\\n\\n const defineValue = (obj, prop, value) =>\\n Object.defineProperty(obj, prop, { writable: false, configurable: false, value });\\n\\n const optionsScript = hasDocument ? document.querySelector('script[type=esms-options]') : undefined;\\n\\n const esmsInitOptions = optionsScript ? JSON.parse(optionsScript.innerHTML) : {};\\n Object.assign(esmsInitOptions, self_.esmsInitOptions || {});\\n\\n const version = \\\"2.8.4\\\";\\n\\n const r$1 = esmsInitOptions.version;\\n if (self_.importShim || (r$1 && r$1 !== version)) {\\n return;\\n }\\n\\n // shim mode is determined on initialization, no late shim mode\\n const shimMode =\\n esmsInitOptions.shimMode ||\\n (hasDocument ?\\n document.querySelectorAll('script[type=module-shim],script[type=importmap-shim],link[rel=modulepreload-shim]')\\n .length > 0\\n // Without a document, shim mode is always true as we cannot polyfill\\n : true);\\n\\n let importHook,\\n resolveHook,\\n fetchHook = fetch,\\n sourceHook,\\n metaHook,\\n tsTransform =\\n esmsInitOptions.tsTransform ||\\n (hasDocument && document.currentScript && document.currentScript.src.replace(/(\\\\.\\\\w+)?\\\\.js$/, '-typescript.js')) ||\\n './es-module-shims-typescript.js';\\n\\n const defaultFetchOpts = { credentials: 'same-origin' };\\n\\n const globalHook = name => (typeof name === 'string' ? self_[name] : name);\\n\\n if (esmsInitOptions.onimport) importHook = globalHook(esmsInitOptions.onimport);\\n if (esmsInitOptions.resolve) resolveHook = globalHook(esmsInitOptions.resolve);\\n if (esmsInitOptions.fetch) fetchHook = globalHook(esmsInitOptions.fetch);\\n if (esmsInitOptions.source) sourceHook = globalHook(esmsInitOptions.source);\\n if (esmsInitOptions.meta) metaHook = globalHook(esmsInitOptions.meta);\\n\\n const hasCustomizationHooks = importHook || resolveHook || fetchHook !== fetch || sourceHook || metaHook;\\n\\n const {\\n noLoadEventRetriggers,\\n enforceIntegrity,\\n hotReload,\\n hotReloadInterval = 100,\\n nativePassthrough = !hasCustomizationHooks && !hotReload\\n } = esmsInitOptions;\\n\\n const setHooks = (importHook_, resolveHook_, metaHook_) => (\\n (importHook = importHook_),\\n (resolveHook = resolveHook_),\\n (metaHook = metaHook_)\\n );\\n\\n const mapOverrides = esmsInitOptions.mapOverrides;\\n\\n let nonce = esmsInitOptions.nonce;\\n if (!nonce && hasDocument) {\\n const nonceElement = document.querySelector('script[nonce]');\\n if (nonceElement) nonce = nonceElement.nonce || nonceElement.getAttribute('nonce');\\n }\\n\\n const onerror = globalHook(esmsInitOptions.onerror || console.error.bind(console));\\n\\n const enable = Array.isArray(esmsInitOptions.polyfillEnable) ? esmsInitOptions.polyfillEnable : [];\\n const disable = Array.isArray(esmsInitOptions.polyfillDisable) ? esmsInitOptions.polyfillDisable : [];\\n\\n const enableAll = esmsInitOptions.polyfillEnable === 'all' || enable.includes('all');\\n const wasmInstancePhaseEnabled =\\n enable.includes('wasm-modules') || enable.includes('wasm-module-instances') || enableAll;\\n const wasmSourcePhaseEnabled =\\n enable.includes('wasm-modules') || enable.includes('wasm-module-sources') || enableAll;\\n const deferPhaseEnabled = enable.includes('import-defer') || enableAll;\\n const cssModulesEnabled = !disable.includes('css-modules');\\n const jsonModulesEnabled = !disable.includes('json-modules');\\n\\n const onpolyfill =\\n esmsInitOptions.onpolyfill ?\\n globalHook(esmsInitOptions.onpolyfill)\\n : () => {\\n console.log(`%c^^ Module error above is polyfilled and can be ignored ^^`, 'font-weight:900;color:#391');\\n };\\n\\n const baseUrl =\\n hasDocument ? document.baseURI\\n : typeof location !== 'undefined' ?\\n `${location.protocol}//${location.host}${\\n location.pathname.includes('/') ?\\n location.pathname.slice(0, location.pathname.lastIndexOf('/') + 1)\\n : location.pathname\\n }`\\n : 'about:blank';\\n\\n const createBlob = (source, type = 'text/javascript') => URL.createObjectURL(new Blob([source], { type }));\\n let { skip } = esmsInitOptions;\\n if (Array.isArray(skip)) {\\n const l = skip.map(s => new URL(s, baseUrl).href);\\n skip = s => l.some(i => (i[i.length - 1] === '/' && s.startsWith(i)) || s === i);\\n } else if (typeof skip === 'string') {\\n const r = new RegExp(skip);\\n skip = s => r.test(s);\\n } else if (skip instanceof RegExp) {\\n skip = s => skip.test(s);\\n }\\n\\n const dispatchError = error => self_.dispatchEvent(Object.assign(new Event('error'), { error }));\\n\\n const throwError = err => {\\n (self_.reportError || dispatchError)(err);\\n onerror(err);\\n };\\n\\n const fromParent = parent => (parent ? ` imported from ${parent}` : '');\\n\\n const backslashRegEx = /\\\\\\\\/g;\\n\\n const asURL = url => {\\n try {\\n if (url.indexOf(':') !== -1) return new URL(url).href;\\n } catch (_) {}\\n };\\n\\n const resolveUrl = (relUrl, parentUrl) =>\\n resolveIfNotPlainOrUrl(relUrl, parentUrl) || asURL(relUrl) || resolveIfNotPlainOrUrl('./' + relUrl, parentUrl);\\n\\n const resolveIfNotPlainOrUrl = (relUrl, parentUrl) => {\\n const hIdx = parentUrl.indexOf('#'),\\n qIdx = parentUrl.indexOf('?');\\n if (hIdx + qIdx > -2)\\n parentUrl = parentUrl.slice(\\n 0,\\n hIdx === -1 ? qIdx\\n : qIdx === -1 || qIdx > hIdx ? hIdx\\n : qIdx\\n );\\n if (relUrl.indexOf('\\\\\\\\') !== -1) relUrl = relUrl.replace(backslashRegEx, '/');\\n // protocol-relative\\n if (relUrl[0] === '/' && relUrl[1] === '/') {\\n return parentUrl.slice(0, parentUrl.indexOf(':') + 1) + relUrl;\\n }\\n // relative-url\\n else if (\\n (relUrl[0] === '.' &&\\n (relUrl[1] === '/' ||\\n (relUrl[1] === '.' && (relUrl[2] === '/' || (relUrl.length === 2 && (relUrl += '/')))) ||\\n (relUrl.length === 1 && (relUrl += '/')))) ||\\n relUrl[0] === '/'\\n ) {\\n const parentProtocol = parentUrl.slice(0, parentUrl.indexOf(':') + 1);\\n if (parentProtocol === 'blob:') {\\n throw new TypeError(\\n `Failed to resolve module specifier \\\"${relUrl}\\\". Invalid relative url or base scheme isn't hierarchical.`\\n );\\n }\\n // Disabled, but these cases will give inconsistent results for deep backtracking\\n //if (parentUrl[parentProtocol.length] !== '/')\\n // throw new Error('Cannot resolve');\\n // read pathname from parent URL\\n // pathname taken to be part after leading \\\"/\\\"\\n let pathname;\\n if (parentUrl[parentProtocol.length + 1] === '/') {\\n // resolving to a :// so we need to read out the auth and host\\n if (parentProtocol !== 'file:') {\\n pathname = parentUrl.slice(parentProtocol.length + 2);\\n pathname = pathname.slice(pathname.indexOf('/') + 1);\\n } else {\\n pathname = parentUrl.slice(8);\\n }\\n } else {\\n // resolving to :/ so pathname is the /... part\\n pathname = parentUrl.slice(parentProtocol.length + (parentUrl[parentProtocol.length] === '/'));\\n }\\n\\n if (relUrl[0] === '/') return parentUrl.slice(0, parentUrl.length - pathname.length - 1) + relUrl;\\n\\n // join together and split for removal of .. and . segments\\n // looping the string instead of anything fancy for perf reasons\\n // '../../../../../z' resolved to 'x/y' is just 'z'\\n const segmented = pathname.slice(0, pathname.lastIndexOf('/') + 1) + relUrl;\\n\\n const output = [];\\n let segmentIndex = -1;\\n for (let i = 0; i < segmented.length; i++) {\\n // busy reading a segment - only terminate on '/'\\n if (segmentIndex !== -1) {\\n if (segmented[i] === '/') {\\n output.push(segmented.slice(segmentIndex, i + 1));\\n segmentIndex = -1;\\n }\\n continue;\\n }\\n // new segment - check if it is relative\\n else if (segmented[i] === '.') {\\n // ../ segment\\n if (segmented[i + 1] === '.' && (segmented[i + 2] === '/' || i + 2 === segmented.length)) {\\n output.pop();\\n i += 2;\\n continue;\\n }\\n // ./ segment\\n else if (segmented[i + 1] === '/' || i + 1 === segmented.length) {\\n i += 1;\\n continue;\\n }\\n }\\n // it is the start of a new segment\\n while (segmented[i] === '/') i++;\\n segmentIndex = i;\\n }\\n // finish reading out the last segment\\n if (segmentIndex !== -1) output.push(segmented.slice(segmentIndex));\\n return parentUrl.slice(0, parentUrl.length - pathname.length) + output.join('');\\n }\\n };\\n\\n const resolveAndComposeImportMap = (json, baseUrl, parentMap) => {\\n const outMap = {\\n imports: { ...parentMap.imports },\\n scopes: { ...parentMap.scopes },\\n integrity: { ...parentMap.integrity }\\n };\\n\\n if (json.imports) resolveAndComposePackages(json.imports, outMap.imports, baseUrl, parentMap);\\n\\n if (json.scopes)\\n for (let s in json.scopes) {\\n const resolvedScope = resolveUrl(s, baseUrl);\\n resolveAndComposePackages(\\n json.scopes[s],\\n outMap.scopes[resolvedScope] || (outMap.scopes[resolvedScope] = {}),\\n baseUrl,\\n parentMap\\n );\\n }\\n\\n if (json.integrity) resolveAndComposeIntegrity(json.integrity, outMap.integrity, baseUrl);\\n\\n return outMap;\\n };\\n\\n const getMatch = (path, matchObj) => {\\n if (matchObj[path]) return path;\\n let sepIndex = path.length;\\n do {\\n const segment = path.slice(0, sepIndex + 1);\\n if (segment in matchObj) return segment;\\n } while ((sepIndex = path.lastIndexOf('/', sepIndex - 1)) !== -1);\\n };\\n\\n const applyPackages = (id, packages) => {\\n const pkgName = getMatch(id, packages);\\n if (pkgName) {\\n const pkg = packages[pkgName];\\n if (pkg === null) return;\\n return pkg + id.slice(pkgName.length);\\n }\\n };\\n\\n const resolveImportMap = (importMap, resolvedOrPlain, parentUrl) => {\\n let scopeUrl = parentUrl && getMatch(parentUrl, importMap.scopes);\\n while (scopeUrl) {\\n const packageResolution = applyPackages(resolvedOrPlain, importMap.scopes[scopeUrl]);\\n if (packageResolution) return packageResolution;\\n scopeUrl = getMatch(scopeUrl.slice(0, scopeUrl.lastIndexOf('/')), importMap.scopes);\\n }\\n return applyPackages(resolvedOrPlain, importMap.imports) || (resolvedOrPlain.indexOf(':') !== -1 && resolvedOrPlain);\\n };\\n\\n const resolveAndComposePackages = (packages, outPackages, baseUrl, parentMap) => {\\n for (let p in packages) {\\n const resolvedLhs = resolveIfNotPlainOrUrl(p, baseUrl) || p;\\n if (\\n (!shimMode || !mapOverrides) &&\\n outPackages[resolvedLhs] &&\\n outPackages[resolvedLhs] !== packages[resolvedLhs]\\n ) {\\n console.warn(\\n `es-module-shims: Rejected map override \\\"${resolvedLhs}\\\" from ${outPackages[resolvedLhs]} to ${packages[resolvedLhs]}.`\\n );\\n continue;\\n }\\n let target = packages[p];\\n if (typeof target !== 'string') continue;\\n const mapped = resolveImportMap(parentMap, resolveIfNotPlainOrUrl(target, baseUrl) || target, baseUrl);\\n if (mapped) {\\n outPackages[resolvedLhs] = mapped;\\n continue;\\n }\\n console.warn(`es-module-shims: Mapping \\\"${p}\\\" -> \\\"${packages[p]}\\\" does not resolve`);\\n }\\n };\\n\\n const resolveAndComposeIntegrity = (integrity, outIntegrity, baseUrl) => {\\n for (let p in integrity) {\\n const resolvedLhs = resolveIfNotPlainOrUrl(p, baseUrl) || p;\\n if (\\n (!shimMode || !mapOverrides) &&\\n outIntegrity[resolvedLhs] &&\\n outIntegrity[resolvedLhs] !== integrity[resolvedLhs]\\n ) {\\n console.warn(\\n `es-module-shims: Rejected map integrity override \\\"${resolvedLhs}\\\" from ${outIntegrity[resolvedLhs]} to ${integrity[resolvedLhs]}.`\\n );\\n }\\n outIntegrity[resolvedLhs] = integrity[p];\\n }\\n };\\n\\n let policy;\\n if (\\n typeof self !== 'undefined' &&\\n (typeof self.trustedTypes !== 'undefined' || typeof self.TrustedTypes !== 'undefined')\\n ) {\\n try {\\n policy = (self.trustedTypes || self.TrustedTypes).createPolicy('es-module-shims', {\\n createHTML: html => html,\\n createScript: script => script\\n });\\n } catch {}\\n }\\n\\n function maybeTrustedInnerHTML(html) {\\n return policy ? policy.createHTML(html) : html;\\n }\\n\\n function maybeTrustedScript(script) {\\n return policy ? policy.createScript(script) : script;\\n }\\n\\n // support browsers without dynamic import support (eg Firefox 6x)\\n let supportsJsonType = false;\\n let supportsCssType = false;\\n\\n const supports = hasDocument && HTMLScriptElement.supports;\\n\\n let supportsImportMaps = supports && supports.name === 'supports' && supports('importmap');\\n let supportsWasmInstancePhase = false;\\n let supportsWasmSourcePhase = false;\\n let supportsMultipleImportMaps = false;\\n\\n const wasmBytes = [0, 97, 115, 109, 1, 0, 0, 0];\\n\\n let featureDetectionPromise = (async function () {\\n // In shim mode, feature detection results are unused — skip the iframe overhead\\n if (shimMode) return;\\n if (!hasDocument)\\n return Promise.all([\\n import(createBlob(`import\\\"${createBlob('{}', 'text/json')}\\\"with{type:\\\"json\\\"}`)).then(\\n () => (\\n (supportsJsonType = true),\\n import(createBlob(`import\\\"${createBlob('', 'text/css')}\\\"with{type:\\\"css\\\"}`)).then(\\n () => (supportsCssType = true),\\n noop\\n )\\n ),\\n noop\\n ),\\n wasmInstancePhaseEnabled &&\\n import(createBlob(`import\\\"${createBlob(new Uint8Array(wasmBytes), 'application/wasm')}\\\"`)).then(\\n () => (supportsWasmInstancePhase = true),\\n noop\\n ),\\n wasmSourcePhaseEnabled &&\\n import(createBlob(`import source x from\\\"${createBlob(new Uint8Array(wasmBytes), 'application/wasm')}\\\"`)).then(\\n () => (supportsWasmSourcePhase = true),\\n noop\\n )\\n ]);\\n\\n const msgTag = `s${version}`;\\n return new Promise(resolve => {\\n const iframe = document.createElement('iframe');\\n iframe.style.display = 'none';\\n iframe.setAttribute('nonce', nonce);\\n function cb({ data }) {\\n const isFeatureDetectionMessage = Array.isArray(data) && data[0] === msgTag;\\n if (!isFeatureDetectionMessage) return;\\n [\\n ,\\n supportsImportMaps,\\n supportsMultipleImportMaps,\\n supportsJsonType,\\n supportsCssType,\\n supportsWasmSourcePhase,\\n supportsWasmInstancePhase\\n ] = data;\\n resolve();\\n document.head.removeChild(iframe);\\n window.removeEventListener('message', cb, false);\\n }\\n window.addEventListener('message', cb, false);\\n // Feature checking with careful avoidance of unnecessary work - all gated on initial import map supports check. CSS gates on JSON feature check, Wasm instance phase gates on wasm source phase check.\\n const importMapTest = `<script nonce=${nonce || ''}>${\\n policy ? 't=(window.trustedTypes||window.TrustedTypes).createPolicy(\\\"es-module-shims\\\",{createScript:s=>s});' : ''\\n }b=(s,type='text/javascript')=>URL.createObjectURL(new Blob([s],{type}));c=u=>import(u).then(()=>true,()=>false);i=innerText=>document.head.appendChild(Object.assign(document.createElement('script'),{type:'importmap',nonce:\\\"${nonce}\\\",text:${\\n policy ? 't.createScript(innerText)' : 'innerText'\\n }}));i(\\\\`{\\\"imports\\\":{\\\"x\\\":\\\"\\\\${b('')}\\\"}}\\\\`);i(\\\\`{\\\"imports\\\":{\\\"y\\\":\\\"\\\\${b('')}\\\"}}\\\\`);cm=${\\n supportsImportMaps && jsonModulesEnabled ? `c(b(\\\\`import\\\"\\\\${b('{}','text/json')}\\\"with{type:\\\"json\\\"}\\\\`))` : 'false'\\n };sp=${\\n supportsImportMaps && wasmSourcePhaseEnabled ?\\n `c(b(\\\\`import source x from \\\"\\\\${b(new Uint8Array(${JSON.stringify(wasmBytes)}),'application/wasm')\\\\}\\\"\\\\`))`\\n : 'false'\\n };Promise.all([${supportsImportMaps ? 'true' : \\\"c('x')\\\"},${supportsImportMaps ? \\\"c('y')\\\" : false},cm,${\\n supportsImportMaps && cssModulesEnabled ?\\n `cm.then(s=>s?c(b(\\\\`import\\\"\\\\${b('','text/css')\\\\}\\\"with{type:\\\"css\\\"}\\\\`)):false)`\\n : 'false'\\n },sp,${\\n supportsImportMaps && wasmInstancePhaseEnabled ?\\n `${wasmSourcePhaseEnabled ? 'sp.then(s=>s?' : ''}c(b(\\\\`import\\\"\\\\${b(new Uint8Array(${JSON.stringify(wasmBytes)}),'application/wasm')\\\\}\\\"\\\\`))${wasmSourcePhaseEnabled ? ':false)' : ''}`\\n : 'false'\\n }]).then(a=>parent.postMessage(['${msgTag}'].concat(a),'*'))<${''}/script>`;\\n\\n // Safari will call onload eagerly on head injection, but we don't want the Wechat\\n // path to trigger before setting srcdoc, therefore we track the timing\\n let readyForOnload = false,\\n onloadCalledWhileNotReady = false;\\n function doOnload() {\\n if (!readyForOnload) {\\n onloadCalledWhileNotReady = true;\\n return;\\n }\\n // WeChat browser doesn't support setting srcdoc scripts\\n // But iframe sandboxes don't support contentDocument so we do this as a fallback\\n const doc = iframe.contentDocument;\\n if (doc && doc.head.childNodes.length === 0) {\\n const s = doc.createElement('script');\\n if (nonce) s.setAttribute('nonce', nonce);\\n s.innerText = maybeTrustedScript(importMapTest.slice(15 + (nonce ? nonce.length : 0), -9));\\n doc.head.appendChild(s);\\n }\\n }\\n\\n iframe.onload = doOnload;\\n // WeChat browser requires append before setting srcdoc\\n document.head.appendChild(iframe);\\n\\n // setting srcdoc is not supported in React native webviews on iOS\\n // setting src to a blob URL results in a navigation event in webviews\\n // document.write gives usability warnings\\n readyForOnload = true;\\n if ('srcdoc' in iframe) iframe.srcdoc = maybeTrustedInnerHTML(importMapTest);\\n else iframe.contentDocument.write(importMapTest);\\n // retrigger onload for Safari only if necessary\\n if (onloadCalledWhileNotReady) doOnload();\\n });\\n })();\\n\\n /* es-module-lexer (minimal) 2.3.1 */\\n let e,a,r,i=2<<19;const s=1===new Uint8Array(new Uint16Array([1]).buffer)[0]?function(e,a){const r=e.length;let i=0;for(;i<r;)a[i]=e.charCodeAt(i++);}:function(e,a){const r=e.length;let i=0;for(;i<r;){const r=e.charCodeAt(i);a[i++]=(255&r)<<8|r>>>8;}},f=\\\"etaourceeferromsyncunctionlassvoyiedelecontininstantybreareturdebuggeawaithrwhileforifcatcfinallelsxportport\\\";let c$1,t,n;function parse(k,l=\\\"@\\\"){c$1=k,t=l;const u=2*c$1.length+(2<<18);if(u>i||!e){for(;u>i;)i*=2;a=new ArrayBuffer(i),s(f,new Uint16Array(a,16,108)),e=function(e,a,r){\\\"use asm\\\";var i=new e.Int8Array(r),s=new e.Int16Array(r),f=new e.Int32Array(r),c=new e.Uint8Array(r),t=new e.Uint16Array(r),n=1040;function b(e){e=e|0;var a=0,r=0,c=0,t=0,n=0,b=0,k=0,o=0,w=0,g=0,p=0,y=0,m=0,O=0,T=0;y=s[398]|0;a=f[71]|0;f[68]=a;k=a;p=a;o=y;g=0;e:while(1){r=f[72]|0;t=o<<16>>16==y<<16>>16;c=g&e;b=a;while(1){n=b+2|0;if(b>>>0>=r>>>0){a=0;w=100;break e}a=s[n>>1]|0;if(!(M(a)|0)){if(t){switch(a<<16>>16){case 125:case 93:case 41:case 59:case 44:{w=100;break e}default:{}}if(c?se(a)|0:0){w=100;break e}}if(!(se(a)|0))break}b=n;}f[71]=n;a:do{switch(a<<16>>16){case 101:{if((o<<16>>16==0?Q(n)|0:0)?(S(b+4|0,214,10)|0)==0:0){u();w=89;}else w=89;break}case 105:{if(((s[b+4>>1]|0)==109?Q(n)|0:0)?(S(b+6|0,224,8)|0)==0:0){l();w=89;}else w=89;break}case 99:{if((((s[b+4>>1]|0)==108?Q(n)|0:0)?(S(b+6|0,70,6)|0)==0:0)?L(s[b+12>>1]|0)|0:0){i[800]=1;w=89;}else w=89;break}case 40:{b=f[69]|0;w=o&65535;f[b+(w<<3)>>2]=1;s[398]=o+1<<16>>16;f[b+(w<<3)+4>>2]=k;w=89;break}case 91:{b=f[69]|0;w=o&65535;f[b+(w<<3)>>2]=8;s[398]=o+1<<16>>16;f[b+(w<<3)+4>>2]=k;w=89;break}case 93:if(!(o<<16>>16)){ee();break a}else {s[398]=o+-1<<16>>16;w=89;break a}case 44:{r=s[397]|0;if((!(o<<16>>16==0|r<<16>>16==0)?(f[(f[69]|0)+((o&65535)+-1<<3)>>2]|0)==5:0)?(m=f[(f[70]|0)+((r&65535)+-1<<2)>>2]|0,(f[m+4>>2]|0)==0):0){f[m+4>>2]=p+2;f[71]=b+4;v(1)|0;w=f[71]|0;f[m+16>>2]=w;f[71]=w+-2;w=89;}else w=89;break}case 41:{if(!(o<<16>>16)){ee();break a}w=o+-1<<16>>16;s[398]=w;r=s[397]|0;if(r<<16>>16!=0?(f[(f[69]|0)+((w&65535)<<3)>>2]|0)==5:0){c=f[(f[70]|0)+((r&65535)+-1<<2)>>2]|0;if(!(f[c+4>>2]|0))f[c+4>>2]=p+2;f[c+12>>2]=b+4;s[397]=r+-1<<16>>16;w=89;}else w=89;break}case 123:{w=f[62]|0;do{if((s[p>>1]|0)==41&(w|0)!=0?(f[w+12>>2]|0)==(p+2|0):0){r=f[63]|0;f[62]=r;if(!r){f[58]=0;break}else {f[r+32>>2]=0;break}}}while(0);b=f[69]|0;w=o&65535;f[b+(w<<3)>>2]=(i[800]|0)==0?2:6;s[398]=o+1<<16>>16;f[b+(w<<3)+4>>2]=k;i[800]=0;w=89;break}case 125:{if(!(o<<16>>16)){ee();break a}k=f[69]|0;w=o+-1<<16>>16;s[398]=w;if((f[k+((w&65535)<<3)>>2]|0)==4){d();w=89;}else w=89;break}case 34:case 39:{A(a);w=89;break}case 47:switch(s[b+4>>1]|0){case 47:{F();break a}case 42:{x(1);break a}default:{c=s[p>>1]|0;r:do{if(!($(c)|0)){if(!(c<<16>>16==41?K(f[(f[69]|0)+((o&65535)<<3)+4>>2]|0)|0:0))w=62;}else switch(c<<16>>16){case 46:if(((s[p+-2>>1]|0)+-48&65535)<10){w=62;break r}else break r;case 43:if((s[p+-2>>1]|0)==43){w=62;break r}else break r;case 45:if((s[p+-2>>1]|0)==45){w=62;break r}else break r;default:break r}}while(0);r:do{if((w|0)==62){w=0;if(o<<16>>16!=0?(O=f[69]|0,T=(o&65535)+-1|0,c<<16>>16==102?(f[O+(T<<3)>>2]|0)==1:0):0){if(((s[p+-2>>1]|0)==111?C(p+-4|0)|0:0)?B(f[O+(T<<3)+4>>2]|0,178,3)|0:0)break}else w=67;if((w|0)==67?(0,c<<16>>16==125):0){t=f[69]|0;r=o&65535;if(U(f[t+(r<<3)+4>>2]|0)|0)break;if((f[t+(r<<3)>>2]|0)==6)break}if(!(h(p)|0)){switch(c<<16>>16){case 0:break r;case 47:{if(i[799]|0)break r;break}default:{}}w=f[64]|0;if((w|0?p>>>0>=(f[w>>2]|0)>>>0:0)?p>>>0<=(f[w+4>>2]|0)>>>0:0){I();i[799]=0;w=89;break a}t=f[3]|0;r=p;do{if(r>>>0<=t>>>0)break;r=r+-2|0;f[68]=r;c=s[r>>1]|0;}while(!(D(c)|0));if(M(c)|0){do{if(r>>>0<=t>>>0)break;r=r+-2|0;f[68]=r;}while(M(s[r>>1]|0)|0);if(q(r)|0){I();i[799]=0;w=89;break a}}i[799]=1;w=89;break a}}}while(0);I();i[799]=0;w=89;break a}}case 96:{b=f[69]|0;w=o&65535;f[b+(w<<3)+4>>2]=k;s[398]=o+1<<16>>16;f[b+(w<<3)>>2]=3;d();w=89;break}default:w=89;}}while(0);if((w|0)==89){w=0;f[68]=f[71];}if(i[798]|0){a=0;break}r=f[68]|0;a:do{if((r|0)==(p|0))if(g&((s[398]|0)==y<<16>>16&e)){a=s[f[71]>>1]|0;if(se(a)|0)break e;else a=1;}else a=g;else {if(a<<16>>16==47){a=(i[799]|0)==0;break}if(G(a)|0)a=1;else {switch(a<<16>>16){case 96:case 34:case 39:case 41:case 93:case 125:{a=1;break a}default:{}}a=0;}}}while(0);k=r;p=r;o=s[398]|0;g=a;a=f[71]|0;}if((w|0)==100)f[71]=n;return a|0}function k(){var e=0,a=0,r=0,c=0,t=0,b=0,k=0,o=0,w=0;w=n;n=n+10240|0;s[397]=0;s[398]=0;f[68]=f[2];i[799]=0;f[67]=0;i[798]=0;f[69]=w+2048;f[70]=w;i[800]=0;r=(f[3]|0)+-2|0;f[71]=r;e=r+(f[65]<<1)|0;f[72]=e;e:while(1){a=r+2|0;f[71]=a;if(r>>>0>=e>>>0){c=85;break}e=s[a>>1]|0;a:do{switch(e<<16>>16){case 9:case 10:case 11:case 12:case 13:case 32:break;case 101:{if(((s[398]|0)==0?Q(a)|0:0)?(S(r+4|0,214,10)|0)==0:0){u();c=84;}else c=84;break}case 105:{if(((s[r+4>>1]|0)==109?Q(a)|0:0)?(S(r+6|0,224,8)|0)==0:0){l();c=84;}else c=84;break}case 99:{if((((s[r+4>>1]|0)==108?Q(a)|0:0)?(S(r+6|0,70,6)|0)==0:0)?L(s[r+12>>1]|0)|0:0){i[800]=1;c=84;}else c=84;break}case 40:{r=f[69]|0;c=s[398]|0;f[r+((c&65535)<<3)>>2]=1;a=f[68]|0;s[398]=c+1<<16>>16;f[r+((c&65535)<<3)+4>>2]=a;c=84;break}case 91:{r=f[69]|0;c=s[398]|0;f[r+((c&65535)<<3)>>2]=8;a=f[68]|0;s[398]=c+1<<16>>16;f[r+((c&65535)<<3)+4>>2]=a;c=84;break}case 93:{e=s[398]|0;if(!(e<<16>>16)){c=21;break e}s[398]=e+-1<<16>>16;c=84;break}case 44:{e=s[397]|0;if(((e<<16>>16!=0?(t=s[398]|0,t<<16>>16!=0):0)?(f[(f[69]|0)+((t&65535)+-1<<3)>>2]|0)==5:0)?(b=f[(f[70]|0)+((e&65535)+-1<<2)>>2]|0,(f[b+4>>2]|0)==0):0){f[b+4>>2]=(f[68]|0)+2;f[71]=r+4;v(1)|0;c=f[71]|0;f[b+16>>2]=c;f[71]=c+-2;c=84;}else c=84;break}case 41:{e=s[398]|0;if(!(e<<16>>16)){c=29;break e}s[398]=e+-1<<16>>16;a=s[397]|0;if(a<<16>>16!=0?(f[(f[69]|0)+((e+-1&65535)<<3)>>2]|0)==5:0){e=f[(f[70]|0)+((a&65535)+-1<<2)>>2]|0;if(!(f[e+4>>2]|0))f[e+4>>2]=(f[68]|0)+2;f[e+12>>2]=r+4;s[397]=a+-1<<16>>16;c=84;}else c=84;break}case 123:{e=f[68]|0;c=f[62]|0;do{if((s[e>>1]|0)==41&(c|0)!=0?(f[c+12>>2]|0)==(e+2|0):0){a=f[63]|0;f[62]=a;if(!a){f[58]=0;break}else {f[a+32>>2]=0;break}}}while(0);r=f[69]|0;c=s[398]|0;f[r+((c&65535)<<3)>>2]=(i[800]|0)==0?2:6;s[398]=c+1<<16>>16;f[r+((c&65535)<<3)+4>>2]=e;i[800]=0;c=84;break}case 125:{e=s[398]|0;if(!(e<<16>>16)){c=42;break e}c=f[69]|0;s[398]=e+-1<<16>>16;if((f[c+((e+-1&65535)<<3)>>2]|0)==4){d();c=84;}else c=84;break}case 34:case 39:{A(e);c=84;break}case 47:switch(s[r+4>>1]|0){case 47:{F();break a}case 42:{x(1);break a}default:{e=f[68]|0;a=s[e>>1]|0;r:do{if(!($(a)|0))if(a<<16>>16==41){r=s[398]|0;if(!(K(f[(f[69]|0)+((r&65535)<<3)+4>>2]|0)|0))c=57;}else c=56;else switch(a<<16>>16){case 46:if(((s[e+-2>>1]|0)+-48&65535)<10){c=56;break r}else break r;case 43:if((s[e+-2>>1]|0)==43){c=56;break r}else break r;case 45:if((s[e+-2>>1]|0)==45){c=56;break r}else break r;default:break r}}while(0);if((c|0)==56){r=s[398]|0;c=57;}r:do{if((c|0)==57){c=0;if(r<<16>>16!=0?(k=f[69]|0,o=(r&65535)+-1|0,a<<16>>16==102?(f[k+(o<<3)>>2]|0)==1:0):0){if(((s[e+-2>>1]|0)==111?C(e+-4|0)|0:0)?B(f[k+(o<<3)+4>>2]|0,178,3)|0:0)break}else c=62;if((c|0)==62?(0,a<<16>>16==125):0){c=f[69]|0;r=r&65535;if(U(f[c+(r<<3)+4>>2]|0)|0)break;if((f[c+(r<<3)>>2]|0)==6)break}if(!(h(e)|0)){switch(a<<16>>16){case 0:break r;case 47:{if(i[799]|0)break r;break}default:{}}c=f[64]|0;if((c|0?e>>>0>=(f[c>>2]|0)>>>0:0)?e>>>0<=(f[c+4>>2]|0)>>>0:0){I();i[799]=0;c=84;break a}r=f[3]|0;do{if(e>>>0<=r>>>0)break;e=e+-2|0;f[68]=e;a=s[e>>1]|0;}while(!(D(a)|0));if(M(a)|0){do{if(e>>>0<=r>>>0)break;e=e+-2|0;f[68]=e;}while(M(s[e>>1]|0)|0);if(q(e)|0){I();i[799]=0;c=84;break a}}i[799]=1;c=84;break a}}}while(0);I();i[799]=0;c=84;break a}}case 96:{r=f[69]|0;c=s[398]|0;f[r+((c&65535)<<3)+4>>2]=f[68];s[398]=c+1<<16>>16;f[r+((c&65535)<<3)>>2]=3;d();c=84;break}default:c=84;}}while(0);if((c|0)==84){c=0;f[68]=f[71];}r=f[71]|0;e=f[72]|0;}if((c|0)==21){ee();e=0;}else if((c|0)==29){ee();e=0;}else if((c|0)==42){ee();e=0;}else if((c|0)==85)e=(i[798]|0)==0?(s[397]|s[398])<<16>>16==0:0;n=w;return e|0}function l(){var e=0,a=0,r=0,c=0,t=0,n=0;n=f[71]|0;f[71]=n+12;e=v(1)|0;r=f[71]|0;e:do{if(e<<16>>16!=46){if(!(e<<16>>16==115&r>>>0>(n+12|0)>>>0)){if(!(e<<16>>16==100&r>>>0>(n+10|0)>>>0)){r=0;t=28;break}if(S(r+2|0,32,8)|0){a=r;e=100;r=0;t=60;break}if(!(L(s[r+10>>1]|0)|0)){a=r;e=100;r=0;t=60;break}f[71]=r+10;e=v(1)|0;if(e<<16>>16==42){e=42;c=2;t=62;break}f[71]=r;r=0;t=28;break}if((S(r+2|0,22,10)|0)==0?L(s[r+12>>1]|0)|0:0){f[71]=r+12;e=v(1)|0;a=f[71]|0;if((a|0)!=(r+12|0)){if(e<<16>>16!=102){r=1;t=28;break}if(S(a+2|0,40,6)|0){e=102;r=1;t=60;break}if(!(D(s[a+8>>1]|0)|0)){e=102;r=1;t=60;break}}f[71]=r;r=0;t=28;}else {a=r;e=115;r=0;t=60;}}else {f[71]=r+2;switch((v(1)|0)<<16>>16){case 109:{e=f[71]|0;if(S(e+2|0,16,6)|0)break e;a=f[68]|0;if(!(N(a)|0)?(s[a>>1]|0)==46:0)break e;g(n,n,e+8|0,2);break e}case 115:{e=f[71]|0;if(S(e+2|0,22,10)|0)break e;a=f[68]|0;if(!(N(a)|0)?(s[a>>1]|0)==46:0)break e;f[71]=e+12;e=v(1)|0;r=1;t=28;break e}case 100:{e=f[71]|0;if(S(e+2|0,32,8)|0)break e;a=f[68]|0;if(!(N(a)|0)?(s[a>>1]|0)==46:0)break e;f[71]=e+10;e=v(1)|0;r=2;t=28;break e}default:break e}}}while(0);e:do{if((t|0)==28){if(e<<16>>16==40){a=f[69]|0;c=s[398]|0;f[a+((c&65535)<<3)>>2]=5;e=f[71]|0;s[398]=c+1<<16>>16;f[a+((c&65535)<<3)+4>>2]=e;if((s[f[68]>>1]|0)==46)break;f[71]=e+2;a=v(1)|0;g(n,f[71]|0,0,e);if(!r)e=f[62]|0;else {e=f[62]|0;f[e+28>>2]=(r|0)==1?5:7;}c=f[70]|0;n=s[397]|0;s[397]=n+1<<16>>16;f[c+((n&65535)<<2)>>2]=e;switch(a<<16>>16){case 39:{A(39);break}case 34:{A(34);break}case 96:{if(!(y()|0))t=37;break}default:t=37;}if((t|0)==37){f[71]=(f[71]|0)+-2;break}e=(f[71]|0)+2|0;f[71]=e;switch((v(1)|0)<<16>>16){case 44:{f[71]=(f[71]|0)+2;v(1)|0;c=f[62]|0;f[c+4>>2]=e;n=f[71]|0;f[c+16>>2]=n;i[c+24>>0]=1;f[71]=n+-2;break e}case 41:{s[398]=(s[398]|0)+-1<<16>>16;n=f[62]|0;f[n+4>>2]=e;f[n+12>>2]=(f[71]|0)+2;i[n+24>>0]=1;s[397]=(s[397]|0)+-1<<16>>16;break e}default:{f[71]=(f[71]|0)+-2;break e}}}if(!((r|0)==0&e<<16>>16==123)){switch(e<<16>>16){case 42:case 39:case 34:{c=r;t=62;break e}default:{}}a=f[71]|0;t=60;break}e=f[71]|0;if(s[398]|0){f[71]=e+-2;break}while(1){if(e>>>0>=(f[72]|0)>>>0)break;e=v(1)|0;if(!(ae(e)|0)){if(e<<16>>16==125){t=50;break}}else A(e);e=(f[71]|0)+2|0;f[71]=e;}if((t|0)==50)f[71]=(f[71]|0)+2;c=(v(1)|0)<<16>>16==102;e=f[71]|0;if(c?S(e+2|0,40,6)|0:0){ee();break}f[71]=e+8;e=v(1)|0;if(ae(e)|0){w(n,e,0);break}else {ee();break}}}while(0);if((t|0)==60)if((a|0)==(n+12|0))f[71]=n+10;else {c=r;t=62;}do{if((t|0)==62){if(!((e<<16>>16==42|(c|0)!=2)&(s[398]|0)==0)){f[71]=(f[71]|0)+-2;break}e=f[72]|0;a=f[71]|0;while(1){if(a>>>0>=e>>>0){t=69;break}r=s[a>>1]|0;if(ae(r)|0){t=67;break}t=a+2|0;f[71]=t;a=t;}if((t|0)==67){w(n,r,c);break}else if((t|0)==69){ee();break}}}while(0);return}function u(){var e=0,a=0,r=0,i=0,c=0,t=0,n=0,k=0,l=0,u=0;k=f[71]|0;l=f[64]|0;f[71]=k+12;a=v(1)|0;e=f[71]|0;if(!((e|0)==(k+12|0)?!(O(a)|0):0))u=3;e:do{if((u|0)==3){a:do{switch(a<<16>>16){case 123:{f[71]=e+2;e=v(1)|0;r=f[71]|0;while(1){if(ae(e)|0){A(e);e=(f[71]|0)+2|0;f[71]=e;}else {H(e)|0;e=f[71]|0;}v(1)|0;e=p(r,e)|0;if(e<<16>>16==44){f[71]=(f[71]|0)+2;e=v(1)|0;}a=r;r=f[71]|0;if(e<<16>>16==125){u=15;break}if((r|0)==(a|0)){u=12;break}if(r>>>0>(f[72]|0)>>>0){u=14;break}}if((u|0)==12){ee();break e}else if((u|0)==14){ee();break e}else if((u|0)==15){f[71]=r+2;u=49;break a}break}case 42:{f[71]=e+2;v(1)|0;u=f[71]|0;p(u,u)|0;u=49;break}case 100:{f[71]=e+14;switch((v(1)|0)<<16>>16){case 97:{a=f[71]|0;if((S(a+2|0,46,8)|0)==0?M(s[a+10>>1]|0)|0:0){f[71]=a+10;v(0)|0;u=21;}break}case 102:{u=21;break}case 99:{a=f[71]|0;if(((S(a+2|0,68,8)|0)==0?(l=s[a+10>>1]|0,L(l)|0|l<<16>>16==123):0)?(f[71]=a+10,r=v(1)|0,r<<16>>16!=123):0){n=r;u=30;}break}default:{}}r:do{if((u|0)==21?(i=f[71]|0,(S(i+2|0,54,14)|0)==0):0){a=s[i+16>>1]|0;if(!(L(a)|0))switch(a<<16>>16){case 40:case 42:break;default:break r}f[71]=i+16;a=v(1)|0;if(a<<16>>16==42){f[71]=(f[71]|0)+2;a=v(1)|0;}if(a<<16>>16!=40){n=a;u=30;}}}while(0);if((u|0)==30?(c=f[71]|0,H(n)|0,t=f[71]|0,t>>>0>c>>>0):0){E(e,e+14|0,c,t);f[71]=(f[71]|0)+-2;break e}E(e,e+14|0,0,0);f[71]=e+12;break e}case 97:{f[71]=e+10;v(0)|0;e=f[71]|0;u=34;break}case 102:{u=34;break}case 99:{if((S(e+2|0,68,8)|0)==0?D(s[e+10>>1]|0)|0:0){f[71]=e+10;u=v(1)|0;l=f[71]|0;H(u)|0;u=f[71]|0;E(l,u,l,u);f[71]=(f[71]|0)+-2;break e}f[71]=e+4;e=e+4|0;u=41;break}case 108:case 118:{u=41;break}default:break e}}while(0);if((u|0)==34){f[71]=e+16;e=v(1)|0;if(e<<16>>16==42){f[71]=(f[71]|0)+2;e=v(1)|0;}l=f[71]|0;H(e)|0;u=f[71]|0;E(l,u,l,u);f[71]=(f[71]|0)+-2;break}else if((u|0)==41){f[71]=e+6;while(1){a=v(1)|0;e=f[71]|0;if(e>>>0>(f[72]|0)>>>0)break;a=P(a)|0;if((f[71]|0)==(e|0))break;if(a<<16>>16==61)a=b(1)|0;e=f[71]|0;if(a<<16>>16!=44)break;f[71]=e+2;}f[71]=e+-2;break}else if((u|0)==49){u=(v(1)|0)<<16>>16==102;e=f[71]|0;if(u?(S(e+2|0,40,6)|0)==0:0){f[71]=e+8;w(k,v(1)|0,0);e=(l|0)==0?236:l+16|0;while(1){e=f[e>>2]|0;if(!e)break e;f[e+12>>2]=0;f[e+8>>2]=0;e=e+16|0;}}f[71]=e+-2;break}}}while(0);return}function o(){var e=0,a=0,r=0,i=0,c=0,t=0,n=0;e=f[71]|0;c=(s[e>>1]|0)==123;f[71]=e+2;e=v(1)|0;t=c?125:93;e:while(1){if((t|0)==(e&65535|0))break;i=f[71]|0;if(i>>>0>(f[72]|0)>>>0)break;if((e<<16>>16==46?(s[i+2>>1]|0)==46:0)?(s[i+4>>1]|0)==46:0){f[71]=i+6;e=P(v(1)|0)|0;}else n=9;a:do{if((n|0)==9){n=0;do{if(c){do{if(e<<16>>16==91){b(0)|0;f[71]=(f[71]|0)+2;a=i;}else {if(ae(e)|0){A(e);f[71]=(f[71]|0)+2;a=i;break}if((e+-48&65535)>=10){H(e)|0;a=f[71]|0;break}e=i;r:while(1){r=e+2|0;a=s[r>>1]|0;i:do{if((a+-48&65535)>=10){switch(a<<16>>16){case 67:case 68:case 70:case 97:case 65:case 99:case 100:case 102:case 46:case 66:case 69:case 79:case 88:case 95:case 98:case 101:case 110:case 111:case 120:break i;case 43:case 45:break;default:break r}switch(s[e>>1]|0){case 69:case 101:break;default:break r}}}while(0);e=r;}f[71]=r;a=i;}}while(0);e=v(1)|0;if(e<<16>>16==58){f[71]=(f[71]|0)+2;e=P(v(1)|0)|0;break}if(a>>>0>i>>>0)E(i,a,i,a);}else if(e<<16>>16==44){f[71]=i+2;e=v(1)|0;break a}else {e=P(e)|0;break}}while(0);if(e<<16>>16==61)e=b(0)|0;if(e<<16>>16!=44)break e;f[71]=(f[71]|0)+2;e=v(1)|0;}}while(0)}return}function h(e){e=e|0;e:do{switch(s[e>>1]|0){case 100:switch(s[e+-2>>1]|0){case 105:{e=B(e+-4|0,76,2)|0;break e}case 108:{e=B(e+-4|0,80,3)|0;break e}default:{e=0;break e}}case 101:switch(s[e+-2>>1]|0){case 115:switch(s[e+-4>>1]|0){case 108:{e=z(e+-6|0,101)|0;break e}case 97:{e=z(e+-6|0,99)|0;break e}default:{e=0;break e}}case 116:{e=B(e+-4|0,86,4)|0;break e}case 117:{e=B(e+-4|0,94,6)|0;break e}default:{e=0;break e}}case 102:{if((s[e+-2>>1]|0)==111?(s[e+-4>>1]|0)==101:0)switch(s[e+-6>>1]|0){case 99:{e=B(e+-8|0,106,6)|0;break e}case 112:{e=B(e+-8|0,118,2)|0;break e}default:{e=0;break e}}else e=0;break}case 107:{e=B(e+-2|0,122,4)|0;break}case 110:{if(z(e+-2|0,105)|0)e=1;else e=B(e+-2|0,130,5)|0;break}case 111:{e=z(e+-2|0,100)|0;break}case 114:{e=B(e+-2|0,140,7)|0;break}case 116:{e=B(e+-2|0,154,4)|0;break}case 119:switch(s[e+-2>>1]|0){case 101:{e=z(e+-4|0,110)|0;break e}case 111:{e=B(e+-4|0,162,3)|0;break e}default:{e=0;break e}}default:e=0;}}while(0);return e|0}function w(e,a,r){e=e|0;a=a|0;r=r|0;var i=0,c=0;i=(f[71]|0)+2|0;switch(a<<16>>16){case 39:{A(39);c=5;break}case 34:{A(34);c=5;break}default:ee();}do{if((c|0)==5){g(e,i,f[71]|0,1);if((r|0)>0)f[(f[62]|0)+28>>2]=(r|0)==1?4:6;f[71]=(f[71]|0)+2;c=(v(0)|0)<<16>>16==119;a=f[71]|0;if(((c?(s[a+2>>1]|0)==105:0)?(s[a+4>>1]|0)==116:0)?(s[a+6>>1]|0)==104:0){f[71]=a+8;if((v(1)|0)<<16>>16!=123){f[71]=a;break}r=f[71]|0;i=r;e:while(1){f[71]=i+2;i=v(1)|0;switch(i<<16>>16){case 39:{A(39);f[71]=(f[71]|0)+2;i=v(1)|0;break}case 34:{A(34);f[71]=(f[71]|0)+2;i=v(1)|0;break}default:i=H(i)|0;}if(i<<16>>16!=58){c=20;break}f[71]=(f[71]|0)+2;switch((v(1)|0)<<16>>16){case 39:{A(39);break}case 34:{A(34);break}default:{c=24;break e}}f[71]=(f[71]|0)+2;switch((v(1)|0)<<16>>16){case 125:{c=28;break e}case 44:break;default:{c=26;break e}}i=(f[71]|0)+2|0;f[71]=i;}if((c|0)==20){f[71]=a;break}else if((c|0)==24){f[71]=a;break}else if((c|0)==26){f[71]=a;break}else if((c|0)==28){c=f[62]|0;f[c+16>>2]=r;f[c+12>>2]=(f[71]|0)+2;break}}f[71]=a+-2;}}while(0);return}function d(){var e=0,a=0,r=0;a=f[72]|0;r=f[71]|0;e:while(1){e=r+2|0;if(r>>>0>=a>>>0){a=10;break}switch(s[e>>1]|0){case 96:{a=7;break e}case 36:{if((s[r+4>>1]|0)==123){a=6;break e}break}case 92:{e=r+4|0;break}default:{}}r=e;}if((a|0)==6){e=r+4|0;f[71]=e;a=f[69]|0;r=s[398]|0;f[a+((r&65535)<<3)>>2]=4;s[398]=r+1<<16>>16;f[a+((r&65535)<<3)+4>>2]=e;}else if((a|0)==7){f[71]=e;a=f[69]|0;r=(s[398]|0)+-1<<16>>16;s[398]=r;if((f[a+((r&65535)<<3)>>2]|0)!=3)ee();}else if((a|0)==10){f[71]=e;ee();}return}function v(e){e=e|0;var a=0,r=0,i=0;r=f[71]|0;e:do{a=s[r>>1]|0;a:do{if(a<<16>>16!=47)if(e)if(L(a)|0)break;else break e;else if(M(a)|0)break;else break e;else switch(s[r+2>>1]|0){case 47:{F();break a}case 42:{x(e);break a}default:{a=47;break e}}}while(0);i=f[71]|0;r=i+2|0;f[71]=r;}while(i>>>0<(f[72]|0)>>>0);return a|0}function A(e){e=e|0;var a=0,r=0,i=0,c=0;c=f[72]|0;a=f[71]|0;while(1){i=a+2|0;if(a>>>0>=c>>>0){a=9;break}r=s[i>>1]|0;if(r<<16>>16==e<<16>>16){a=10;break}if(r<<16>>16==92){r=a+4|0;if((s[r>>1]|0)==13){a=a+6|0;a=(s[a>>1]|0)==10?a:r;}else a=r;}else if(se(r)|0){a=9;break}else a=i;}if((a|0)==9){f[71]=i;ee();}else if((a|0)==10)f[71]=i;return}function C(e){e=e|0;var a=0,r=0;a=s[e>>1]|0;if(L(a)|0)r=3;else switch(a<<16>>16){case 41:case 125:case 93:{r=3;break}default:e=0;}e:do{if((r|0)==3){r=f[3]|0;while(1){if(e>>>0<=r>>>0)break;e=e+-2|0;if(!(L(a)|0))break;a=s[e>>1]|0;}switch(a<<16>>16){case 41:case 125:case 93:{e=1;break e}default:{}}e=(O(a)|0)^1;}}while(0);return e|0}function g(e,a,r,s){e=e|0;a=a|0;r=r|0;s=s|0;var c=0,t=0;t=f[66]|0;f[66]=t+36;c=f[62]|0;f[((c|0)==0?232:c+32|0)>>2]=t;f[63]=c;f[62]=t;f[t+8>>2]=e;if(2==(s|0)){e=3;c=r;}else {e=1==(s|0)?1:2;c=1==(s|0)?r+2|0:0;}f[t+12>>2]=c;f[t+28>>2]=e;f[t>>2]=a;f[t+4>>2]=r;f[t+16>>2]=0;f[t+20>>2]=s;i[t+24>>0]=1==(s|0)&1;f[t+32>>2]=0;return}function p(e,a){e=e|0;a=a|0;var r=0,i=0,c=0,t=0;r=f[71]|0;i=s[r>>1]|0;c=(e|0)==(a|0)?0:e;t=(e|0)==(a|0)?0:a;if(i<<16>>16==97){f[71]=r+4;r=v(1)|0;e=f[71]|0;if(ae(r)|0){A(r);a=(f[71]|0)+2|0;f[71]=a;}else {H(r)|0;a=f[71]|0;}i=v(1)|0;r=f[71]|0;}if((r|0)!=(e|0))E(e,a,c,t);return i|0}function y(){var e=0,a=0,r=0,i=0;i=f[71]|0;r=f[72]|0;a=i;e:while(1){e=a+2|0;if(a>>>0>=r>>>0){a=7;break}switch(s[e>>1]|0){case 96:{a=8;break e}case 92:{e=a+4|0;break}case 36:{if((s[a+4>>1]|0)==123){a=7;break e}break}default:{}}a=e;}if((a|0)==7){f[71]=i;e=0;}else if((a|0)==8){f[71]=e;e=1;}return e|0}function m(){var e=0,a=0,r=0;r=f[72]|0;a=f[71]|0;e:while(1){e=a+2|0;if(a>>>0>=r>>>0){a=6;break}switch(s[e>>1]|0){case 13:case 10:{a=6;break e}case 93:{a=7;break e}case 92:{e=a+4|0;break}default:{}}a=e;}if((a|0)==6){f[71]=e;ee();e=0;}else if((a|0)==7){f[71]=e;e=93;}return e|0}function I(){var e=0,a=0;e:while(1){e=f[71]|0;f[71]=e+2;if(e>>>0>=(f[72]|0)>>>0){a=7;break}switch(s[e+2>>1]|0){case 13:case 10:{a=7;break e}case 47:break e;case 91:{m()|0;break}case 92:{f[71]=e+4;break}default:{}}}if((a|0)==7)ee();return}function U(e){e=e|0;switch(s[e>>1]|0){case 62:{e=(s[e+-2>>1]|0)==61;break}case 41:case 59:{e=1;break}case 104:{e=B(e+-2|0,188,4)|0;break}case 121:{e=B(e+-2|0,196,6)|0;break}case 101:{e=B(e+-2|0,208,3)|0;break}default:e=0;}return e|0}function x(e){e=e|0;var a=0,r=0,i=0,c=0,t=0;c=(f[71]|0)+2|0;f[71]=c;r=f[72]|0;while(1){a=c+2|0;if(c>>>0>=r>>>0)break;i=s[a>>1]|0;if(!e?se(i)|0:0)break;if(i<<16>>16==42?(s[c+4>>1]|0)==47:0){t=8;break}c=a;}if((t|0)==8){f[71]=a;a=c+4|0;}f[71]=a;return}function S(e,a,r){e=e|0;a=a|0;r=r|0;var s=0,f=0;e:do{if(!r)e=0;else {while(1){s=i[e>>0]|0;f=i[a>>0]|0;if(s<<24>>24!=f<<24>>24)break;r=r+-1|0;if(!r){e=0;break e}else {e=e+1|0;a=a+1|0;}}e=(s&255)-(f&255)|0;}}while(0);return e|0}function O(e){e=e|0;e:do{switch(e<<16>>16){case 38:case 37:case 33:{e=1;break}default:if((e&-8)<<16>>16==40|(e+-58&65535)<6)e=1;else {switch(e<<16>>16){case 91:case 93:case 94:{e=1;break e}default:{}}e=(e+-123&65535)<4;}}}while(0);return e|0}function $(e){e=e|0;e:do{switch(e<<16>>16){case 38:case 37:case 33:break;default:if(!((e+-58&65535)<6|(e+-40&65535)<7&e<<16>>16!=41)){switch(e<<16>>16){case 91:case 94:break e;default:{}}return e<<16>>16!=125&(e+-123&65535)<4|0}}}while(0);return 1}function T(e){e=e|0;var a=0;a=s[e>>1]|0;e:do{if((a+-9&65535)>=5){switch(a<<16>>16){case 160:case 32:{a=1;break e}default:{}}if(O(a)|0)return a<<16>>16!=46|(N(e)|0)|0;else a=0;}else a=1;}while(0);return a|0}function j(e){e=e|0;var a=0,r=0;r=n;n=n+16|0;f[r>>2]=0;f[65]=e;a=f[3]|0;s[a+(e<<1)>>1]=0;f[r>>2]=a+(e<<1)+2;f[66]=a+(e<<1)+2;f[58]=0;f[62]=0;f[60]=0;f[59]=0;f[64]=0;f[61]=0;n=r;return a|0}function B(e,a,r){e=e|0;a=a|0;r=r|0;var i=0,s=0;s=e+(0-r<<1)+2|0;i=f[3]|0;if(s>>>0>=i>>>0?(S(s,a,r<<1)|0)==0:0)if((s|0)==(i|0))i=1;else i=T(e+(0-r<<1)|0)|0;else i=0;return i|0}function E(e,a,r,i){e=e|0;a=a|0;r=r|0;i=i|0;var s=0,c=0;s=f[66]|0;f[66]=s+20;c=f[64]|0;f[((c|0)==0?236:c+16|0)>>2]=s;f[64]=s;f[s>>2]=e;f[s+4>>2]=a;f[s+8>>2]=r;f[s+12>>2]=i;f[s+16>>2]=0;return}function P(e){e=e|0;var a=0;switch(e<<16>>16){case 91:case 123:{o();f[71]=(f[71]|0)+2;break}default:{a=f[71]|0;H(e)|0;e=f[71]|0;if(e>>>0>a>>>0)E(a,e,a,e);}}return v(1)|0}function q(e){e=e|0;switch(s[e>>1]|0){case 107:{e=B(e+-2|0,122,4)|0;break}case 101:{if((s[e+-2>>1]|0)==117)e=B(e+-4|0,94,6)|0;else e=0;break}default:e=0;}return e|0}function z(e,a){e=e|0;a=a|0;var r=0;r=f[3]|0;if(r>>>0<=e>>>0?(s[e>>1]|0)==a<<16>>16:0)if((r|0)==(e|0))r=1;else r=D(s[e+-2>>1]|0)|0;else r=0;return r|0}function D(e){e=e|0;e:do{if((e+-9&65535)<5)e=1;else {switch(e<<16>>16){case 32:case 160:{e=1;break e}default:{}}e=e<<16>>16!=46&(O(e)|0);}}while(0);return e|0}function F(){var e=0,a=0,r=0;e=f[72]|0;r=f[71]|0;e:while(1){a=r+2|0;if(r>>>0>=e>>>0)break;switch(s[a>>1]|0){case 13:case 10:break e;default:r=a;}}f[71]=a;return}function G(e){e=e|0;e:do{if(((e&-33)+-65&65535)<26|(e+-48&65535)<10)e=1;else {switch(e<<16>>16){case 36:case 95:{e=1;break e}default:{}}e=(e&65535)>127;}}while(0);return e|0}function H(e){e=e|0;while(1){if(L(e)|0)break;if(O(e)|0)break;e=(f[71]|0)+2|0;f[71]=e;e=s[e>>1]|0;if(!(e<<16>>16)){e=0;break}}return e|0}function J(){var e=0;e=f[(f[60]|0)+20>>2]|0;switch(e|0){case 1:{e=-1;break}case 2:{e=-2;break}default:e=e-(f[3]|0)>>1;}return e|0}function K(e){e=e|0;if(!(B(e,168,5)|0)?!(B(e,178,3)|0):0)e=B(e,184,2)|0;else e=1;return e|0}function L(e){e=e|0;switch(e<<16>>16){case 160:case 9:case 10:case 11:case 12:case 13:case 32:{e=1;break}default:e=0;}return e|0}function M(e){e=e|0;switch(e<<16>>16){case 160:case 32:case 12:case 11:case 9:{e=1;break}default:e=0;}return e|0}function N(e){e=e|0;if((s[e>>1]|0)==46?(s[e+-2>>1]|0)==46:0)e=(s[e+-4>>1]|0)==46;else e=0;return e|0}function Q(e){e=e|0;if((f[3]|0)==(e|0))e=1;else e=T(e+-2|0)|0;return e|0}function R(){var e=0;e=f[(f[61]|0)+12>>2]|0;if(!e)e=-1;else e=e-(f[3]|0)>>1;return e|0}function V(){var e=0;e=f[(f[60]|0)+12>>2]|0;if(!e)e=-1;else e=e-(f[3]|0)>>1;return e|0}function W(){var e=0;e=f[(f[61]|0)+8>>2]|0;if(!e)e=-1;else e=e-(f[3]|0)>>1;return e|0}function X(){var e=0;e=f[(f[60]|0)+16>>2]|0;if(!e)e=-1;else e=e-(f[3]|0)>>1;return e|0}function Y(){var e=0;e=f[(f[60]|0)+4>>2]|0;if(!e)e=-1;else e=e-(f[3]|0)>>1;return e|0}function Z(){var e=0;e=f[60]|0;e=f[((e|0)==0?232:e+32|0)>>2]|0;f[60]=e;return (e|0)!=0|0}function _(){var e=0;e=f[61]|0;e=f[((e|0)==0?236:e+16|0)>>2]|0;f[61]=e;return (e|0)!=0|0}function ee(){i[798]=1;f[67]=(f[71]|0)-(f[3]|0)>>1;f[71]=(f[72]|0)+2;return}function ae(e){e=e|0;return e<<16>>16==39|e<<16>>16==34|0}function re(){return (f[(f[60]|0)+8>>2]|0)-(f[3]|0)>>1|0}function ie(){return (f[(f[61]|0)+4>>2]|0)-(f[3]|0)>>1|0}function se(e){e=e|0;return e<<16>>16==13|e<<16>>16==10|0}function fe(){return (f[f[60]>>2]|0)-(f[3]|0)>>1|0}function ce(){return (f[f[61]>>2]|0)-(f[3]|0)>>1|0}function te(){return c[(f[60]|0)+24>>0]|0|0}function ne(e){e=e|0;f[3]=e;return}function be(){return f[(f[60]|0)+28>>2]|0}function ke(){return f[67]|0}function le(e,a){e=e|0;a=a|0;n=e+a+15&-16;return a}return {su:le,ai:X,e:ke,ee:ie,ele:R,els:W,es:ce,id:J,ie:Y,ip:te,is:fe,it:be,p:k,re:_,ri:Z,sa:j,se:V,ses:ne,ss:re}}(\\\"undefined\\\"!=typeof globalThis?globalThis:self,{},a),r=e.su(i-(2<<17),1040);}const h=c$1.length+1;e.ses(r),e.sa(h-1),s(c$1,new Uint16Array(a,r,h)),e.p()||(n=e.e(),o());const w=[],d=[];for(;e.ri();){const a=e.is(),r=e.ie(),i=e.ai(),s=e.id(),f=e.ss(),t=e.se(),n=e.it();let k;e.ip()&&(k=b(-1===s?a:a+1,c$1.charCodeAt(-1===s?a-1:a)));let l=null;w.push({t:n,n:k,s:a,e:r,ss:f,se:t,d:s,a:i,at:l});}for(;e.re();){const a=e.es(),r=e.ee(),i=e.els(),s=e.ele(),f=i<0?void 0:v(i,s),c=v(a,r);d.push({s:a,e:r,ls:i,le:s,n:c,ln:f});}return [w,d];function v(e,a){const r=c$1.charCodeAt(e);return 34===r||39===r?b(e+1,r):c$1.slice(e,a)}}function b(e,a){n=e;let r=\\\"\\\",i=n;for(;;){n>=c$1.length&&o();const e=c$1.charCodeAt(n);if(e===a)break;92===e?(r+=c$1.slice(i,n),r+=k(),i=n):(8232===e||8233===e||u(e)&&96!==a&&o(),++n);}return r+=c$1.slice(i,n++),r}function k(){let e=c$1.charCodeAt(++n);switch(++n,e){case 110:return \\\"\\\\n\\\";case 114:return \\\"\\\\r\\\";case 120:return String.fromCharCode(l(2));case 117:return function(){const e=c$1.charCodeAt(n);let a;123===e?(++n,a=l(c$1.indexOf(\\\"}\\\",n)-n),++n,a>1114111&&o()):a=l(4);return a<=65535?String.fromCharCode(a):(a-=65536,String.fromCharCode(55296+(a>>10),56320+(1023&a)))}();case 116:return \\\"\\\\t\\\";case 98:return \\\"\\\\b\\\";case 118:return \\\"\\\\v\\\";case 102:return \\\"\\\\f\\\";case 13:10===c$1.charCodeAt(n)&&++n;case 10:return \\\"\\\";case 56:case 57:o();default:if(e>=48&&e<=55){let a=c$1.substr(n-1,3).match(/^[0-7]+/)[0],r=parseInt(a,8);return r>255&&(a=a.slice(0,-1),r=parseInt(a,8)),n+=a.length-1,e=c$1.charCodeAt(n),\\\"0\\\"===a&&56!==e&&57!==e||o(),String.fromCharCode(r)}return u(e)?\\\"\\\":String.fromCharCode(e)}}function l(e){const a=n;let r=0,i=0;for(let a=0;a<e;++a,++n){let e,s=c$1.charCodeAt(n);if(95!==s){if(s>=97)e=s-97+10;else if(s>=65)e=s-65+10;else {if(!(s>=48&&s<=57))break;e=s-48;}if(e>=16)break;i=s,r=16*r+e;}else 95!==i&&0!==a||o(),i=s;}return 95!==i&&n-a===e||o(),r}function u(e){return 13===e||10===e}function o(){throw Object.assign(Error(`Parse error ${t}:${c$1.slice(0,n).split(\\\"\\\\n\\\").length}:${n-c$1.lastIndexOf(\\\"\\\\n\\\",n-1)}`),{idx:n})}\\n\\n const _resolve = (id, parentUrl = baseUrl) => {\\n const urlResolved = resolveIfNotPlainOrUrl(id, parentUrl) || asURL(id);\\n const firstResolved = firstImportMap && resolveImportMap(firstImportMap, urlResolved || id, parentUrl);\\n const composedResolved =\\n composedImportMap === firstImportMap ? firstResolved : (\\n resolveImportMap(composedImportMap, urlResolved || id, parentUrl)\\n );\\n const resolved = composedResolved || firstResolved || throwUnresolved(id, parentUrl);\\n // needsShim, shouldShim per load record to set on parent\\n let n = false,\\n N = false;\\n if (!supportsImportMaps) {\\n // bare specifier -> needs shim\\n if (!urlResolved) n = true;\\n // url mapping -> should shim\\n else if (urlResolved !== resolved) N = true;\\n } else if (!supportsMultipleImportMaps) {\\n // bare specifier and not resolved by first import map -> needs shim\\n if (!urlResolved && !firstResolved) n = true;\\n // resolution doesn't match first import map -> should shim\\n if (firstResolved && resolved !== firstResolved) N = true;\\n }\\n return { r: resolved, n, N };\\n };\\n\\n const resolve = (id, parentUrl) => {\\n if (!resolveHook) return _resolve(id, parentUrl);\\n const result = resolveHook(id, parentUrl, defaultResolve);\\n\\n return result ? { r: result, n: true, N: true } : _resolve(id, parentUrl);\\n };\\n\\n // import()\\n async function importShim(id, opts, parentUrl) {\\n if (typeof opts === 'string') {\\n parentUrl = opts;\\n opts = undefined;\\n }\\n await initPromise; // needed for shim check\\n if (shimMode || !baselineSupport) {\\n if (hasDocument) processScriptsAndPreloads();\\n legacyAcceptingImportMaps = false;\\n }\\n let sourceType = undefined;\\n if (typeof opts === 'object') {\\n if (opts.lang === 'ts') sourceType = 'ts';\\n if (typeof opts.with === 'object' && typeof opts.with.type === 'string') {\\n sourceType = opts.with.type;\\n }\\n }\\n return topLevelLoad(id, parentUrl || baseUrl, defaultFetchOpts, undefined, undefined, undefined, sourceType);\\n }\\n\\n // import.source()\\n // (opts not currently supported as no use cases yet)\\n if (shimMode || wasmSourcePhaseEnabled)\\n importShim.source = async (id, opts, parentUrl) => {\\n if (typeof opts === 'string') {\\n parentUrl = opts;\\n opts = undefined;\\n }\\n await initPromise; // needed for shim check\\n if (shimMode || !baselineSupport) {\\n if (hasDocument) processScriptsAndPreloads();\\n legacyAcceptingImportMaps = false;\\n }\\n await importMapPromise;\\n const url = resolve(id, parentUrl || baseUrl).r;\\n const load = getOrCreateLoad(url, defaultFetchOpts, undefined, undefined);\\n await load.f;\\n return importShim._s[load.r];\\n };\\n\\n // import.defer() is just a proxy for import(), since we can't actually defer\\n if (shimMode || deferPhaseEnabled) importShim.defer = importShim;\\n\\n if (hotReload) {\\n initHotReload(topLevelLoad, importShim);\\n importShim.hotReload = hotReload$1;\\n }\\n\\n const defaultResolve = (id, parentUrl) => {\\n return (\\n resolveImportMap(composedImportMap, resolveIfNotPlainOrUrl(id, parentUrl) || id, parentUrl) ||\\n throwUnresolved(id, parentUrl)\\n );\\n };\\n\\n const throwUnresolved = (id, parentUrl) => {\\n throw Error(`Unable to resolve specifier '${id}'${fromParent(parentUrl)}`);\\n };\\n\\n const metaResolve = function (id, parentUrl = this.url) {\\n return resolve(id, `${parentUrl}`).r;\\n };\\n\\n importShim.resolve = (id, parentUrl) => resolve(id, parentUrl).r;\\n importShim.getImportMap = () => JSON.parse(JSON.stringify(composedImportMap));\\n importShim.addImportMap = importMapIn => {\\n if (!shimMode) throw new Error('Unsupported in polyfill mode.');\\n composedImportMap = resolveAndComposeImportMap(importMapIn, baseUrl, composedImportMap);\\n };\\n importShim.version = version;\\n\\n const registry = (importShim._r = {});\\n // Wasm caches\\n const sourceCache = (importShim._s = {});\\n /* const instanceCache = */ importShim._i = new WeakMap();\\n\\n // Ensure this version is the only version\\n defineValue(self_, 'importShim', Object.freeze(importShim));\\n const shimModeOptions = { ...esmsInitOptions, shimMode: true };\\n if (optionsScript) optionsScript.innerText = maybeTrustedScript(JSON.stringify(shimModeOptions));\\n self_.esmsInitOptions = shimModeOptions;\\n\\n const loadAll = async (load, seen) => {\\n seen[load.u] = 1;\\n await load.L;\\n await Promise.all(\\n load.d.map(({ l: dep, s: sourcePhase }) => {\\n if (dep.b || seen[dep.u]) return;\\n if (sourcePhase) return dep.f;\\n return loadAll(dep, seen);\\n })\\n );\\n };\\n\\n let importMapSrc = false;\\n let multipleImportMaps = false;\\n let firstImportMap = null;\\n // To support polyfilling multiple import maps, we separately track the composed import map from the first import map\\n let composedImportMap = { imports: {}, scopes: {}, integrity: {} };\\n let baselineSupport;\\n\\n const initPromise = featureDetectionPromise.then(() => {\\n baselineSupport =\\n supportsImportMaps &&\\n (!jsonModulesEnabled || supportsJsonType) &&\\n (!cssModulesEnabled || supportsCssType) &&\\n (!wasmInstancePhaseEnabled || supportsWasmInstancePhase) &&\\n (!wasmSourcePhaseEnabled || supportsWasmSourcePhase) &&\\n !deferPhaseEnabled &&\\n (!multipleImportMaps || supportsMultipleImportMaps) &&\\n !importMapSrc &&\\n !hasCustomizationHooks;\\n if (!shimMode && typeof WebAssembly !== 'undefined') {\\n if (wasmSourcePhaseEnabled && !Object.getPrototypeOf(WebAssembly.Module).name) {\\n const s = Symbol();\\n const brand = m => defineValue(m, s, 'WebAssembly.Module');\\n class AbstractModuleSource {\\n get [Symbol.toStringTag]() {\\n if (this[s]) return this[s];\\n throw new TypeError('Not an AbstractModuleSource');\\n }\\n }\\n const { Module: wasmModule, compile: wasmCompile, compileStreaming: wasmCompileStreaming } = WebAssembly;\\n WebAssembly.Module = Object.setPrototypeOf(\\n Object.assign(function Module(...args) {\\n return brand(new wasmModule(...args));\\n }, wasmModule),\\n AbstractModuleSource\\n );\\n WebAssembly.Module.prototype = Object.setPrototypeOf(wasmModule.prototype, AbstractModuleSource.prototype);\\n WebAssembly.compile = function compile(...args) {\\n return wasmCompile(...args).then(brand);\\n };\\n WebAssembly.compileStreaming = function compileStreaming(...args) {\\n return wasmCompileStreaming(...args).then(brand);\\n };\\n }\\n }\\n if (hasDocument) {\\n if (!supportsImportMaps) {\\n const supports = HTMLScriptElement.supports || (type => type === 'classic' || type === 'module');\\n HTMLScriptElement.supports = type => type === 'importmap' || supports(type);\\n }\\n if (shimMode || !baselineSupport) {\\n attachMutationObserver();\\n if (document.readyState === 'complete') {\\n readyStateCompleteCheck();\\n } else {\\n document.addEventListener('readystatechange', readyListener);\\n }\\n }\\n processScriptsAndPreloads();\\n }\\n return undefined;\\n });\\n\\n const attachMutationObserver = () => {\\n const observer = new MutationObserver(mutations => {\\n for (const mutation of mutations) {\\n if (mutation.type !== 'childList') continue;\\n for (const node of mutation.addedNodes) {\\n if (node.tagName === 'SCRIPT') {\\n if (node.type === (shimMode ? 'module-shim' : 'module') && !node.ep) processScript(node, true);\\n if (node.type === (shimMode ? 'importmap-shim' : 'importmap') && !node.ep) processImportMap(node, true);\\n } else if (\\n node.tagName === 'LINK' &&\\n node.rel === (shimMode ? 'modulepreload-shim' : 'modulepreload') &&\\n !node.ep\\n ) {\\n processPreload(node);\\n }\\n }\\n }\\n });\\n observer.observe(document, { childList: true });\\n observer.observe(document.head, { childList: true });\\n processScriptsAndPreloads();\\n };\\n\\n let importMapPromise = initPromise;\\n let firstPolyfillLoad = true;\\n let legacyAcceptingImportMaps = true;\\n\\n async function topLevelLoad(\\n url,\\n parentUrl,\\n fetchOpts,\\n source,\\n nativelyLoaded,\\n lastStaticLoadPromise,\\n sourceType\\n ) {\\n await initPromise;\\n await importMapPromise;\\n url = (await resolve(url, parentUrl)).r;\\n\\n // we mock import('./x.css', { with: { type: 'css' }}) support via an inline static reexport\\n // because we can't syntactically pass through to dynamic import with a second argument\\n if (sourceType === 'css' || sourceType === 'json') {\\n // Direct reexport for hot reloading skipped due to Firefox bug https://bugzilla.mozilla.org/show_bug.cgi?id=1965620\\n source = `import m from'${url}'with{type:\\\"${sourceType}\\\"};export default m;`;\\n url += '?entry';\\n }\\n\\n if (importHook) await importHook(url, typeof fetchOpts !== 'string' ? fetchOpts : {}, parentUrl, source, sourceType);\\n // early analysis opt-out - no need to even fetch if we have feature support\\n if (!shimMode && baselineSupport && nativePassthrough && sourceType !== 'ts') {\\n // for polyfill case, only dynamic import needs a return value here, and dynamic import will never pass nativelyLoaded\\n if (nativelyLoaded) return null;\\n await lastStaticLoadPromise;\\n return dynamicImport(source ? createBlob(source) : url);\\n }\\n const load = getOrCreateLoad(url, fetchOpts, undefined, source);\\n linkLoad(load, fetchOpts);\\n const seen = {};\\n await loadAll(load, seen);\\n resolveDeps(load, seen);\\n await lastStaticLoadPromise;\\n if (!shimMode && !load.n) {\\n if (nativelyLoaded) {\\n return;\\n }\\n if (source) {\\n return await dynamicImport(createBlob(source));\\n }\\n }\\n if (firstPolyfillLoad && !shimMode && load.n && nativelyLoaded) {\\n onpolyfill();\\n firstPolyfillLoad = false;\\n }\\n const module = await (shimMode || load.n || load.N || !nativePassthrough || (!nativelyLoaded && source) ?\\n dynamicImport(load.b, load.u)\\n : import(load.u));\\n // if the top-level load is a shell, run its update function\\n if (load.s) (await dynamicImport(load.s, load.u)).u$_(module);\\n revokeObjectURLs(Object.keys(seen));\\n return module;\\n }\\n\\n const revokeObjectURLs = registryKeys => {\\n let curIdx = 0;\\n const handler = self_.requestIdleCallback || self_.requestAnimationFrame || (fn => setTimeout(fn, 0));\\n handler(cleanup);\\n function cleanup() {\\n for (const key of registryKeys.slice(curIdx, (curIdx += 100))) {\\n const load = registry[key];\\n if (load && load.b && load.b !== load.u) URL.revokeObjectURL(load.b);\\n }\\n if (curIdx < registryKeys.length) handler(cleanup);\\n }\\n };\\n\\n const urlJsString = url => `'${url.replace(/'/g, \\\"\\\\\\\\'\\\")}'`;\\n\\n let resolvedSource, lastIndex;\\n const pushStringTo = (load, originalIndex, dynamicImportEndStack) => {\\n while (dynamicImportEndStack[dynamicImportEndStack.length - 1] < originalIndex) {\\n const dynamicImportEnd = dynamicImportEndStack.pop();\\n resolvedSource += `${load.S.slice(lastIndex, dynamicImportEnd)}, ${urlJsString(load.r)}`;\\n lastIndex = dynamicImportEnd;\\n }\\n resolvedSource += load.S.slice(lastIndex, originalIndex);\\n lastIndex = originalIndex;\\n };\\n\\n const pushSourceURL = (load, commentPrefix, commentStart, dynamicImportEndStack) => {\\n const urlStart = commentStart + commentPrefix.length;\\n const commentEnd = load.S.indexOf('\\\\n', urlStart);\\n const urlEnd = commentEnd !== -1 ? commentEnd : load.S.length;\\n let sourceUrl = load.S.slice(urlStart, urlEnd);\\n try {\\n sourceUrl = new URL(sourceUrl, load.r).href;\\n } catch (e) {}\\n pushStringTo(load, urlStart, dynamicImportEndStack);\\n resolvedSource += sourceUrl;\\n lastIndex = urlEnd;\\n };\\n\\n const resolveDeps = (load, seen) => {\\n if (load.b || !seen[load.u]) return;\\n seen[load.u] = 0;\\n\\n for (const { l: dep, s: sourcePhase } of load.d) {\\n if (!sourcePhase) resolveDeps(dep, seen);\\n }\\n\\n if (!load.n) load.n = load.d.some(dep => dep.l.n);\\n if (!load.N) load.N = load.d.some(dep => dep.l.N);\\n\\n // use native loader whenever possible (n = needs shim) via executable subgraph passthrough\\n // so long as the module doesn't use dynamic import or unsupported URL mappings (N = should shim)\\n if (nativePassthrough && !shimMode && !load.n && !load.N) {\\n load.b = load.u;\\n load.S = undefined;\\n return;\\n }\\n\\n const [imports, exports] = load.a;\\n\\n // \\\"execution\\\"\\n let source = load.S,\\n depIndex = 0,\\n dynamicImportEndStack = [];\\n\\n // once all deps have loaded we can inline the dependency resolution blobs\\n // and define this blob\\n resolvedSource = '';\\n lastIndex = 0;\\n\\n for (const { s: start, e: end, ss: statementStart, se: statementEnd, d: dynamicImportIndex, t, a, at } of imports) {\\n // source phase\\n if (t === 4) {\\n let { l: depLoad } = load.d[depIndex++];\\n pushStringTo(load, statementStart, dynamicImportEndStack);\\n resolvedSource += `${source.slice(statementStart, start - 1).replace('source', '')}/*${source.slice(start - 1, end + 1)}*/'${createBlob(`export default importShim._s[${urlJsString(depLoad.r)}]`)}'`;\\n lastIndex = end + 1;\\n }\\n // dependency source replacements\\n else if (dynamicImportIndex === -1) {\\n let keepAssertion = false;\\n if (a > 0 && !shimMode) {\\n // strip assertions only when unsupported in polyfill mode\\n // minimal lexer builds do not provide parsed attributes, so sniff the assertion source directly\\n const assertion = source.slice(a, statementEnd - 1);\\n keepAssertion =\\n nativePassthrough &&\\n ((supportsJsonType && assertion.includes('json')) || (supportsCssType && assertion.includes('css')));\\n }\\n\\n // defer phase stripping\\n if (t === 6) {\\n pushStringTo(load, statementStart, dynamicImportEndStack);\\n resolvedSource += source.slice(statementStart, start - 1).replace('defer', '');\\n lastIndex = start;\\n }\\n let { l: depLoad } = load.d[depIndex++],\\n blobUrl = depLoad.b,\\n cycleShell = !blobUrl;\\n if (cycleShell) {\\n // circular shell creation\\n if (!(blobUrl = depLoad.s)) {\\n blobUrl = depLoad.s = createBlob(\\n `export function u$_(m){${depLoad.a[1]\\n .map(({ s, e }, i) => {\\n const q = depLoad.S[s] === '\\\"' || depLoad.S[s] === \\\"'\\\";\\n return `e$_${i}=m${q ? `[` : '.'}${depLoad.S.slice(s, e)}${q ? `]` : ''}`;\\n })\\n .join(',')}}${\\n depLoad.a[1].length ? `let ${depLoad.a[1].map((_, i) => `e$_${i}`).join(',')};` : ''\\n }export {${depLoad.a[1]\\n .map(({ s, e }, i) => `e$_${i} as ${depLoad.S.slice(s, e)}`)\\n .join(',')}}\\\\n//# sourceURL=${depLoad.r}?cycle`\\n );\\n }\\n }\\n\\n pushStringTo(load, start - 1, dynamicImportEndStack);\\n resolvedSource += `/*${source.slice(start - 1, end + 1)}*/'${blobUrl}'`;\\n\\n // circular shell execution\\n if (!cycleShell && depLoad.s) {\\n resolvedSource += `;import*as m$_${depIndex} from'${depLoad.b}';import{u$_ as u$_${depIndex}}from'${depLoad.s}';u$_${depIndex}(m$_${depIndex})`;\\n depLoad.s = undefined;\\n }\\n lastIndex = keepAssertion ? end + 1 : statementEnd;\\n }\\n // import.meta\\n else if (dynamicImportIndex === -2) {\\n load.m = { url: load.r, resolve: metaResolve };\\n if (metaHook) metaHook(load.m, load.u);\\n pushStringTo(load, start, dynamicImportEndStack);\\n resolvedSource += `importShim._r[${urlJsString(load.u)}].m`;\\n lastIndex = statementEnd;\\n }\\n // dynamic import\\n else {\\n pushStringTo(load, statementStart + 6, dynamicImportEndStack);\\n resolvedSource += `Shim${t === 5 ? '.source' : ''}(`;\\n dynamicImportEndStack.push(statementEnd - 1);\\n lastIndex = start;\\n }\\n }\\n\\n // support progressive cycle binding updates (try statement avoids tdz errors)\\n if (load.s && (imports.length === 0 || imports[imports.length - 1].d === -1))\\n resolvedSource += `\\\\n;import{u$_}from'${load.s}';try{u$_({${exports\\n .filter(e => e.ln)\\n .map(({ s, e, ln }) => `${source.slice(s, e)}:${ln}`)\\n .join(',')}})}catch(_){};\\\\n`;\\n\\n let sourceURLCommentStart = source.lastIndexOf(sourceURLCommentPrefix);\\n let sourceMapURLCommentStart = source.lastIndexOf(sourceMapURLCommentPrefix);\\n\\n // ignore sourceMap comments before already spliced code\\n if (sourceURLCommentStart < lastIndex) sourceURLCommentStart = -1;\\n if (sourceMapURLCommentStart < lastIndex) sourceMapURLCommentStart = -1;\\n\\n // sourceURL first / only\\n if (\\n sourceURLCommentStart !== -1 &&\\n (sourceMapURLCommentStart === -1 || sourceMapURLCommentStart > sourceURLCommentStart)\\n ) {\\n pushSourceURL(load, sourceURLCommentPrefix, sourceURLCommentStart, dynamicImportEndStack);\\n }\\n // sourceMappingURL\\n if (sourceMapURLCommentStart !== -1) {\\n pushSourceURL(load, sourceMapURLCommentPrefix, sourceMapURLCommentStart, dynamicImportEndStack);\\n // sourceURL last\\n if (sourceURLCommentStart !== -1 && sourceURLCommentStart > sourceMapURLCommentStart)\\n pushSourceURL(load, sourceURLCommentPrefix, sourceURLCommentStart, dynamicImportEndStack);\\n }\\n\\n pushStringTo(load, source.length, dynamicImportEndStack);\\n\\n if (sourceURLCommentStart === -1) resolvedSource += sourceURLCommentPrefix + load.r;\\n\\n load.b = createBlob(resolvedSource);\\n load.S = resolvedSource = undefined;\\n };\\n\\n const sourceURLCommentPrefix = '\\\\n//# sourceURL=';\\n const sourceMapURLCommentPrefix = '\\\\n//# sourceMappingURL=';\\n const cssUrlRegEx = /url\\\\(\\\\s*(?:([\\\"'])((?:\\\\\\\\.|[^\\\\n\\\\\\\\\\\"'])+)\\\\1|((?:\\\\\\\\.|[^\\\\s,\\\"'()\\\\\\\\])+))\\\\s*\\\\)/g;\\n\\n // restrict in-flight fetches to a pool of 100\\n let p = [];\\n let c = 0;\\n const pushFetchPool = () => {\\n if (++c > 100) return new Promise(r => p.push(r));\\n };\\n const popFetchPool = () => {\\n c--;\\n if (p.length) p.shift()();\\n };\\n\\n const doFetch = async (url, fetchOpts, parent) => {\\n if (enforceIntegrity && !fetchOpts.integrity) throw Error(`No integrity for ${url}${fromParent(parent)}.`);\\n let res,\\n poolQueue = pushFetchPool();\\n if (poolQueue) await poolQueue;\\n try {\\n res = await fetchHook(url, fetchOpts);\\n } catch (e) {\\n e.message = `Unable to fetch ${url}${fromParent(parent)} - see network log for details.\\\\n` + e.message;\\n throw e;\\n } finally {\\n popFetchPool();\\n }\\n\\n if (!res.ok) {\\n const error = new TypeError(`${res.status} ${res.statusText} ${res.url}${fromParent(parent)}`);\\n error.response = res;\\n throw error;\\n }\\n return res;\\n };\\n\\n let esmsTsTransform;\\n const initTs = async () => {\\n const m = await import(tsTransform);\\n if (!esmsTsTransform) esmsTsTransform = m.transform;\\n };\\n\\n async function defaultSourceHook(url, fetchOpts, parent) {\\n let res = await doFetch(url, fetchOpts, parent),\\n contentType,\\n [, json, type, jsts] =\\n (contentType = res.headers.get('content-type') || '').match(\\n /^(?:[^/;]+\\\\/(?:[^/+;]+\\\\+)?(json)|(?:text|application)\\\\/(?:x-)?((java|type)script|wasm|css))(?:;|$)/\\n ) || [];\\n if (!(type = json || (jsts ? jsts[0] + 's' : type || (/\\\\.m?ts(\\\\?|#|$)/.test(url) && 'ts')))) {\\n throw Error(\\n `Unsupported Content-Type \\\"${contentType}\\\" loading ${url}${fromParent(parent)}. Modules must be served with a valid MIME type like application/javascript.`\\n );\\n }\\n return {\\n url: res.url,\\n source: await (type > 'v' ? WebAssembly.compileStreaming(res) : res.text()),\\n type\\n };\\n }\\n\\n const hotPrefix = 'var h=import.meta.hot,';\\n const fetchModule = async (reqUrl, fetchOpts, parent) => {\\n const mapIntegrity = composedImportMap.integrity[reqUrl];\\n fetchOpts = mapIntegrity && !fetchOpts.integrity ? { ...fetchOpts, integrity: mapIntegrity } : fetchOpts;\\n let {\\n url = reqUrl,\\n source,\\n type\\n } = (await (sourceHook || defaultSourceHook)(reqUrl, fetchOpts, parent, defaultSourceHook)) || {};\\n if (type === 'wasm') {\\n const exports = WebAssembly.Module.exports((sourceCache[url] = source));\\n const imports = WebAssembly.Module.imports(source);\\n const rStr = urlJsString(url);\\n source = `import*as $_ns from${rStr};`;\\n let i = 0,\\n obj = '';\\n for (const { module, kind } of imports) {\\n const specifier = urlJsString(module);\\n source += `import*as impt${i} from${specifier};\\\\n`;\\n obj += `${specifier}:${kind === 'global' ? `importShim._i.get(impt${i})||impt${i++}` : `impt${i++}`},`;\\n }\\n source += `${hotPrefix}i=await WebAssembly.instantiate(importShim._s[${rStr}],{${obj}});importShim._i.set($_ns,i);`;\\n obj = '';\\n for (const { name, kind } of exports) {\\n source += `export let ${name}=i.exports['${name}'];`;\\n if (kind === 'global') source += `try{${name}=${name}.value}catch(_){${name}=undefined}`;\\n obj += `${name},`;\\n }\\n source += `if(h)h.accept(m=>({${obj}}=m))`;\\n } else if (type === 'json') {\\n source = `${hotPrefix}j=JSON.parse(${JSON.stringify(source)});export{j as default};if(h)h.accept(m=>j=m.default)`;\\n } else if (type === 'css') {\\n source = `${hotPrefix}s=h&&h.data.s||new CSSStyleSheet();s.replaceSync(${JSON.stringify(\\n source.replace(\\n cssUrlRegEx,\\n (_match, quotes = '', relUrl1, relUrl2) => `url(${quotes}${resolveUrl(relUrl1 || relUrl2, url)}${quotes})`\\n )\\n )});if(h){h.data.s=s;h.accept(()=>{})}export default s`;\\n } else if (type === 'ts') {\\n if (!esmsTsTransform) await initTs();\\n const transformed = esmsTsTransform(source, url);\\n // even if the TypeScript is valid JavaScript, unless it was a top-level inline source, it wasn't served with\\n // a valid JS MIME here, so we must still polyfill it\\n source = transformed === undefined ? source : transformed;\\n }\\n return { url, source, type };\\n };\\n\\n const getOrCreateLoad = (url, fetchOpts, parent, source) => {\\n if (source && registry[url]) {\\n let i = 0;\\n while (registry[url + '#' + ++i]);\\n url += '#' + i;\\n }\\n let load = registry[url];\\n if (load) return load;\\n registry[url] = load = {\\n // url\\n u: url,\\n // response url\\n r: source ? url : undefined,\\n // fetchPromise\\n f: undefined,\\n // source\\n S: source,\\n // linkPromise\\n L: undefined,\\n // analysis\\n a: undefined,\\n // deps\\n d: undefined,\\n // blobUrl\\n b: undefined,\\n // shellUrl\\n s: undefined,\\n // needsShim: does it fail execution in the current native loader?\\n n: false,\\n // shouldShim: does it need to be loaded by the polyfill loader?\\n N: false,\\n // type\\n t: null,\\n // meta\\n m: null\\n };\\n load.f = (async () => {\\n if (load.S === undefined) {\\n // preload fetch options override fetch options (race)\\n ({ url: load.r, source: load.S, type: load.t } = await (fetchCache[url] || fetchModule(url, fetchOpts, parent)));\\n if (\\n !load.n &&\\n load.t !== 'js' &&\\n !shimMode &&\\n ((load.t === 'css' && !supportsCssType) ||\\n (load.t === 'json' && !supportsJsonType) ||\\n (load.t === 'wasm' && !supportsWasmInstancePhase && !supportsWasmSourcePhase) ||\\n load.t === 'ts')\\n ) {\\n load.n = true;\\n }\\n }\\n try {\\n load.a = parse(load.S, load.u);\\n } catch (e) {\\n throwError(e);\\n load.a = [[], [], false];\\n }\\n return load;\\n })();\\n return load;\\n };\\n\\n const featErr = feat =>\\n Error(\\n `${feat} feature must be enabled via <script type=\\\"esms-options\\\">{ \\\"polyfillEnable\\\": [\\\"${feat}\\\"] }<${''}/script>`\\n );\\n\\n const linkLoad = (load, fetchOpts) => {\\n if (load.L) return;\\n load.L = load.f.then(() => {\\n let childFetchOpts = fetchOpts;\\n load.d = load.a[0]\\n .map(({ n, d, t, a, se }) => {\\n const phaseImport = t >= 4;\\n const sourcePhase = phaseImport && t < 6;\\n if (phaseImport) {\\n if (!shimMode && (sourcePhase ? !wasmSourcePhaseEnabled : !deferPhaseEnabled))\\n throw featErr(sourcePhase ? 'wasm-module-sources' : 'import-defer');\\n if (!sourcePhase || !supportsWasmSourcePhase) load.n = true;\\n }\\n let source = undefined;\\n if (a > 0 && !shimMode && nativePassthrough) {\\n const assertion = load.S.slice(a, se - 1);\\n // no need to fetch JSON/CSS if supported, since it's a leaf node, we'll just strip the assertion syntax\\n if (assertion.includes('json')) {\\n if (supportsJsonType) source = '';\\n else load.n = true;\\n } else if (assertion.includes('css')) {\\n if (supportsCssType) source = '';\\n else load.n = true;\\n }\\n }\\n if (d !== -1 || !n) return;\\n const resolved = resolve(n, load.r || load.u);\\n if (resolved.n || hasCustomizationHooks) load.n = true;\\n if (d >= 0 || resolved.N) load.N = true;\\n if (d !== -1) return;\\n if (skip && skip(resolved.r) && !sourcePhase) return { l: { b: resolved.r }, s: false };\\n if (childFetchOpts.integrity) childFetchOpts = { ...childFetchOpts, integrity: undefined };\\n const child = { l: getOrCreateLoad(resolved.r, childFetchOpts, load.r, source), s: sourcePhase };\\n // assertion case -> inline the CSS / JSON URL directly\\n if (source === '') child.l.b = child.l.u;\\n if (!child.s) linkLoad(child.l, fetchOpts);\\n // load, sourcePhase\\n return child;\\n })\\n .filter(l => l);\\n });\\n };\\n\\n const processScriptsAndPreloads = () => {\\n for (const link of document.querySelectorAll(shimMode ? 'link[rel=modulepreload-shim]' : 'link[rel=modulepreload]')) {\\n if (!link.ep) processPreload(link);\\n }\\n for (const script of document.querySelectorAll('script[type]')) {\\n if (script.type === 'importmap' + (shimMode ? '-shim' : '')) {\\n if (!script.ep) processImportMap(script);\\n } else if (script.type === 'module' + (shimMode ? '-shim' : '')) {\\n legacyAcceptingImportMaps = false;\\n if (!script.ep) processScript(script);\\n }\\n }\\n };\\n\\n const getFetchOpts = script => {\\n const fetchOpts = {};\\n if (script.integrity) fetchOpts.integrity = script.integrity;\\n if (script.referrerPolicy) fetchOpts.referrerPolicy = script.referrerPolicy;\\n if (script.fetchPriority) fetchOpts.priority = script.fetchPriority;\\n if (script.crossOrigin === 'use-credentials') fetchOpts.credentials = 'include';\\n else if (script.crossOrigin === 'anonymous') fetchOpts.credentials = 'omit';\\n else fetchOpts.credentials = 'same-origin';\\n return fetchOpts;\\n };\\n\\n let lastStaticLoadPromise = Promise.resolve();\\n\\n let domContentLoaded = false;\\n let domContentLoadedCnt = 1;\\n const domContentLoadedCheck = m => {\\n if (m === undefined) {\\n if (domContentLoaded) return;\\n domContentLoaded = true;\\n domContentLoadedCnt--;\\n }\\n if (--domContentLoadedCnt === 0 && !noLoadEventRetriggers && (shimMode || !baselineSupport)) {\\n document.removeEventListener('DOMContentLoaded', domContentLoadedEvent);\\n document.dispatchEvent(new Event('DOMContentLoaded'));\\n }\\n };\\n let loadCnt = 1;\\n const loadCheck = () => {\\n if (--loadCnt === 0 && !noLoadEventRetriggers && (shimMode || !baselineSupport)) {\\n window.removeEventListener('load', loadEvent);\\n window.dispatchEvent(new Event('load'));\\n }\\n };\\n\\n const domContentLoadedEvent = async () => {\\n await initPromise;\\n domContentLoadedCheck();\\n };\\n const loadEvent = async () => {\\n await initPromise;\\n domContentLoadedCheck();\\n loadCheck();\\n };\\n\\n // this should always trigger because we assume es-module-shims is itself a domcontentloaded requirement\\n if (hasDocument) {\\n document.addEventListener('DOMContentLoaded', domContentLoadedEvent);\\n window.addEventListener('load', loadEvent);\\n }\\n\\n const readyListener = async () => {\\n await initPromise;\\n processScriptsAndPreloads();\\n if (document.readyState === 'complete') {\\n readyStateCompleteCheck();\\n }\\n };\\n\\n let readyStateCompleteCnt = 1;\\n const readyStateCompleteCheck = () => {\\n if (--readyStateCompleteCnt === 0) {\\n domContentLoadedCheck();\\n if (!noLoadEventRetriggers && (shimMode || !baselineSupport)) {\\n document.removeEventListener('readystatechange', readyListener);\\n document.dispatchEvent(new Event('readystatechange'));\\n }\\n }\\n };\\n\\n const hasNext = script => script.nextSibling || (script.parentNode && hasNext(script.parentNode));\\n const epCheck = (script, ready) =>\\n script.ep ||\\n (!ready && ((!script.src && !script.innerHTML) || !hasNext(script))) ||\\n script.getAttribute('noshim') !== null ||\\n !(script.ep = true);\\n\\n const processImportMap = (script, ready = readyStateCompleteCnt > 0) => {\\n if (epCheck(script, ready)) return;\\n // we dont currently support external import maps in polyfill mode to match native\\n if (script.src) {\\n if (!shimMode) return;\\n importMapSrc = true;\\n }\\n importMapPromise = importMapPromise\\n .then(async () => {\\n composedImportMap = resolveAndComposeImportMap(\\n script.src ? await (await doFetch(script.src, getFetchOpts(script))).json() : JSON.parse(script.innerHTML),\\n script.src || baseUrl,\\n composedImportMap\\n );\\n })\\n .catch(e => {\\n if (e instanceof SyntaxError)\\n e = new Error(`Unable to parse import map ${e.message} in: ${script.src || script.innerHTML}`);\\n throwError(e);\\n });\\n if (!firstImportMap && legacyAcceptingImportMaps) importMapPromise.then(() => (firstImportMap = composedImportMap));\\n if (!legacyAcceptingImportMaps && !multipleImportMaps) {\\n multipleImportMaps = true;\\n if (!shimMode && baselineSupport && !supportsMultipleImportMaps) {\\n baselineSupport = false;\\n if (hasDocument) attachMutationObserver();\\n }\\n }\\n legacyAcceptingImportMaps = false;\\n };\\n\\n const processScript = (script, ready = readyStateCompleteCnt > 0) => {\\n if (epCheck(script, ready)) return;\\n // does this load block readystate complete\\n const isBlockingReadyScript = script.getAttribute('async') === null && readyStateCompleteCnt > 0;\\n // does this load block DOMContentLoaded\\n const isDomContentLoadedScript = domContentLoadedCnt > 0;\\n const isLoadScript = loadCnt > 0;\\n if (isLoadScript) loadCnt++;\\n if (isBlockingReadyScript) readyStateCompleteCnt++;\\n if (isDomContentLoadedScript) domContentLoadedCnt++;\\n let loadPromise;\\n const ts = script.lang === 'ts';\\n if (ts && !script.src) {\\n loadPromise = Promise.resolve(esmsTsTransform || initTs())\\n .then(() => {\\n const transformed = esmsTsTransform(script.innerHTML, baseUrl);\\n if (transformed !== undefined) {\\n onpolyfill();\\n firstPolyfillLoad = false;\\n }\\n return topLevelLoad(\\n script.src || baseUrl,\\n baseUrl,\\n getFetchOpts(script),\\n transformed === undefined ? script.innerHTML : transformed,\\n !shimMode && transformed === undefined,\\n isBlockingReadyScript && lastStaticLoadPromise,\\n 'ts'\\n );\\n })\\n .catch(throwError);\\n } else {\\n loadPromise = topLevelLoad(\\n script.src || baseUrl,\\n baseUrl,\\n getFetchOpts(script),\\n !script.src ? script.innerHTML : undefined,\\n !shimMode,\\n isBlockingReadyScript && lastStaticLoadPromise,\\n ts ? 'ts' : undefined\\n ).catch(throwError);\\n }\\n if (!noLoadEventRetriggers) loadPromise.then(() => script.dispatchEvent(new Event('load')));\\n if (isBlockingReadyScript && !ts) {\\n lastStaticLoadPromise = loadPromise.then(readyStateCompleteCheck);\\n }\\n if (isDomContentLoadedScript) loadPromise.then(domContentLoadedCheck);\\n if (isLoadScript) loadPromise.then(loadCheck);\\n };\\n\\n const fetchCache = {};\\n const processPreload = link => {\\n link.ep = true;\\n initPromise.then(() => {\\n if (baselineSupport && !shimMode) return;\\n if (fetchCache[link.href]) return;\\n fetchCache[link.href] = fetchModule(link.href, getFetchOpts(link));\\n });\\n };\\n\\n})();\\n\";\n","/**\n * Boot assets — the es-module-shims source, the automerge/subduction WASM\n * binaries, and the collected host styles. Fetched once and shared across all\n * isolation instances on the page (the promise is cached), since they are\n * identical for every iframe.\n *\n * Package note (differs from core): the es-module-shims source is **bundled**\n * (see ../../esms-source.generated.ts), not fetched from a host-served\n * `/es-module-shims.js`. The opaque-origin iframe can't fetch it itself and a\n * patchwork-base package can't assume the host serves it. The two WASM binaries\n * are still fetched from the host origin — that is a stable platform contract\n * every patchwork tool relies on (e.g. @patchwork/tasks fetches the same paths).\n */\n\nimport { collectHostStyles } from \"./styles.js\";\nimport { esmsSource } from \"../../esms-source.generated.js\";\n\nexport interface BootAssets {\n esmsSource: string;\n automergeWasm: ArrayBuffer;\n subductionWasm: ArrayBuffer;\n hostStyles: string;\n}\n\nlet bootAssetsPromise: Promise<BootAssets> | null = null;\n\nexport function fetchBootAssets(): Promise<BootAssets> {\n if (bootAssetsPromise) return bootAssetsPromise;\n\n bootAssetsPromise = Promise.all([\n fetch(\"/automerge.wasm?main\").then((r) => {\n if (!r.ok) throw new Error(`Failed to fetch automerge.wasm: ${r.status}`);\n return r.arrayBuffer();\n }),\n fetch(\"/subduction.wasm\").then((r) => {\n if (!r.ok)\n throw new Error(`Failed to fetch subduction.wasm: ${r.status}`);\n return r.arrayBuffer();\n }),\n collectHostStyles(),\n ]).then(([automergeWasm, subductionWasm, hostStyles]) => ({\n esmsSource,\n automergeWasm,\n subductionWasm,\n hostStyles,\n }));\n\n return bootAssetsPromise;\n}\n","/**\n * Reads the host page's `<script type=\"importmap\">` and resolves every URL in\n * it to absolute (against the host's `baseURI`), so the same import map can be\n * handed to the iframe's es-module-shims where relative bases don't apply.\n */\n\nexport interface ImportMap {\n imports?: Record<string, string>;\n scopes?: Record<string, Record<string, string>>;\n}\n\n/** Read the host page's import map and resolve all URLs to absolute. */\nexport function getResolvedImportMap(): ImportMap {\n const script = document.querySelector('script[type=\"importmap\"]');\n if (!script?.textContent) return {};\n try {\n const raw: ImportMap = JSON.parse(script.textContent);\n const baseURI = document.baseURI;\n const resolved: ImportMap = {};\n\n if (raw.imports) {\n resolved.imports = {};\n for (const [key, value] of Object.entries(raw.imports)) {\n try {\n resolved.imports[key] = new URL(value, baseURI).href;\n } catch {\n resolved.imports[key] = value;\n }\n }\n }\n\n if (raw.scopes) {\n resolved.scopes = {};\n for (const [scopeKey, scopeMap] of Object.entries(raw.scopes)) {\n let resolvedKey: string;\n try {\n resolvedKey = new URL(scopeKey, baseURI).href;\n } catch {\n resolvedKey = scopeKey;\n }\n resolved.scopes[resolvedKey] = {};\n for (const [k, v] of Object.entries(scopeMap)) {\n try {\n resolved.scopes[resolvedKey][k] = new URL(v, baseURI).href;\n } catch {\n resolved.scopes[resolvedKey][k] = v;\n }\n }\n }\n }\n\n return resolved;\n } catch {\n return {};\n }\n}\n","/**\n * The isolated iframe's config, read directly off the mounted host element (the\n * `<patchwork-view component=\"patchwork-isolation\">`). The element IS the config\n * surface — there is no separate spec object — so these are the reads\n * `bootIsolation` composes, alongside the boot assets, import map, and styles.\n *\n * Structural config lives in attributes; the root component's data rides as an\n * opaque `<script type=\"application/json\" data-root-component-data>` child that\n * the boundary relays verbatim (never parsing).\n */\n\nimport type { AutomergeUrl } from \"@automerge/automerge-repo/slim\";\n\n/** The root `patchwork:component` id to mount inside the iframe. */\nexport function readRootComponentId(host: HTMLElement): string {\n return host.getAttribute(\"root-component\") ?? \"\";\n}\n\n/** The `automerge-allowlist` attribute, parsed into a URL list (sync seeds). */\nexport function readAllowlistUrls(host: HTMLElement): AutomergeUrl[] {\n return (host.getAttribute(\"automerge-allowlist\") ?? \"\")\n .split(\",\")\n .map((s) => s.trim())\n .filter(Boolean) as AutomergeUrl[];\n}\n\n/**\n * The inert data `<script>`, located by its explicit `data-root-component-data`\n * marker. `:scope >` restricts the match to a direct child, so it never reaches\n * into the iframe `bootIsolation` appends; the marker (rather than a structural\n * `type=\"application/json\"` scan) makes the lookup deterministic even if other\n * inert scripts are present.\n */\nexport function findRootComponentDataScript(\n host: HTMLElement\n): HTMLScriptElement | null {\n return host.querySelector<HTMLScriptElement>(\n \":scope > script[data-root-component-data]\"\n );\n}\n\n/**\n * The opaque root-component data: the text of the data `<script>`. Never parsed\n * here — relayed verbatim to the iframe, which writes it into the root's own\n * `<script>` for the root to parse. Absent → \"{}\".\n */\nexport function readRootComponentData(host: HTMLElement): string {\n return findRootComponentDataScript(host)?.textContent ?? \"{}\";\n}\n","/**\n * bootIsolation — the host-side boot sequence for one isolated iframe. Given the\n * mounted host element (a `<patchwork-view component=\"patchwork-isolation\">`), it\n * reads all of its config directly off that element and:\n *\n * 1. Fetches boot assets (es-module-shims, WASM, host styles) — cached\n * 2. Gets the shared denylist (singleton, populated once from sensitive docs)\n * 3. Builds the allowlist seeded from the `automerge-allowlist` attribute\n * (+ transitive content)\n * 4. Creates the intermediary repo gated by allowlist + denylist\n * 5. Starts host-side RPC for plugin loading, navigation, and bridged providers\n * 6. Creates the sandboxed iframe and posts the boot message\n *\n * The element IS the config surface — there is no separate spec object. Reads\n * off `host`:\n * - `root-component` attribute → the root `patchwork:component` to mount\n * - `automerge-allowlist` attribute → sync allowlist seeds (comma-separated)\n * - `shared-providers` attribute → bridged providers (via the providers bridge)\n * - the inert `<script data-root-component-data>` child → opaque root-component data\n * - nearest `<repo-provider>` ancestor → the host repo\n *\n * It returns an {@link IsolationHandle} synchronously; the async work runs in\n * the background. `teardown()` cancels any in-flight boot and tears down\n * everything wired so far — idempotent, safe at any point. Live changes to the\n * data `<script>` are watched here and streamed to the running iframe (no\n * reboot) via `root-component-data-update` messages.\n *\n * No tool code ever runs in the host: everything read is data, and the iframe\n * resolves/mounts the root component against its own registry.\n */\n\nimport type { AutomergeUrl } from \"@automerge/automerge-repo/slim\";\nimport type { RepoProviderElement } from \"@inkandswitch/patchwork-providers\";\nimport {\n createIntermediaryRepo,\n type IntermediaryRepo,\n PackagesUrlMapper,\n getRegistries,\n startResourceBridge,\n watchRegistries,\n buildAllowlist,\n handleAccessRequest,\n requestBridgedUrlAccess,\n getDenylist,\n allowlistUrlUnlessSensitive,\n startHostNavigationBridge,\n startHostDragDropBridge,\n startHostProvidersBridge,\n resolveBridgedProviders,\n makeBridgedValueFilter,\n} from \"../../bridges/index.js\";\nimport { generateIframeSrcdoc } from \"./srcdoc.js\";\nimport { log } from \"../../log.js\";\nimport { fetchBootAssets } from \"./assets.js\";\nimport { readHostAppearance } from \"./styles.js\";\nimport { getResolvedImportMap } from \"./import-map.js\";\nimport {\n readRootComponentId,\n readAllowlistUrls,\n readRootComponentData,\n findRootComponentDataScript,\n} from \"./config.js\";\n\nexport interface IsolationHandle {\n /**\n * Cancel any in-flight boot and tear down everything wired so far (bridges,\n * intermediary repo, iframe, the root-component-data observer). Idempotent.\n *\n * Live data updates are handled internally: `bootIsolation` watches the data\n * `<script>` and streams changes to the running iframe with no reboot, so the\n * caller drives everything by mutating the host element's DOM — attributes to\n * reboot, the data `<script>` text to update in place.\n */\n teardown(): void;\n}\n\n/** The host repo comes from the nearest `<repo-provider>` ancestor of `host`. */\nfunction getRepo(host: HTMLElement) {\n const repoProvider = host.closest<RepoProviderElement>(\"repo-provider\");\n const repo = repoProvider?.repo;\n if (!repo) log(\"no <repo-provider> ancestor found\");\n return repo;\n}\n\nexport function bootIsolation(host: HTMLElement): IsolationHandle {\n // Cancellation: teardown (or a reconfigure that tears this down) flips this,\n // and every async step re-checks it after an await and bails before mutating\n // more state — a stale boot can't keep running.\n let cancelled = false;\n const stale = () => cancelled;\n\n // Snapshot the structural config at boot time. (The root-component data is\n // read lazily — on the initial boot message and on each push — so it is never\n // captured here.)\n const rootComponentId = readRootComponentId(host);\n const rootUrls = readAllowlistUrls(host);\n\n // State wired up during the boot, torn down together. All start empty, so\n // teardown() before/during boot is a safe no-op over them.\n const cleanups: Array<() => void> = [];\n let hostRpcPort: MessagePort | null = null;\n let intermediary: IntermediaryRepo | null = null;\n let iframe: HTMLIFrameElement | null = null;\n\n async function run() {\n log(`init root \"${rootComponentId}\" with ${rootUrls.length} root URLs`);\n\n const repo = getRepo(host);\n if (!repo) return;\n\n let assets;\n try {\n assets = await fetchBootAssets();\n } catch (err) {\n console.error(\"[patchwork-isolation] failed to load boot assets:\", err);\n return;\n }\n if (stale()) return;\n\n const importMap = getResolvedImportMap();\n const mapper = new PackagesUrlMapper();\n\n // ── Access control ──────────────────────────────────────\n // Wait for the denylist to finish populating before seeding the allowlist\n // or creating the intermediary repo. Otherwise a protected doc that appears\n // in root content could be allowlisted/synced during the population window\n // (the denylist is built asynchronously).\n const denylist = getDenylist(repo);\n await denylist.whenReady();\n if (stale()) return;\n\n const allowlist = await buildAllowlist(repo, rootUrls, denylist, stale);\n if (stale()) return;\n\n intermediary = createIntermediaryRepo({\n allowlist,\n hostRepo: repo,\n denylist,\n onAccessRequest: (documentId) =>\n handleAccessRequest(repo, rootUrls, allowlist, denylist, documentId),\n });\n\n log(\"intermediary repo and allowlist ready\");\n\n // ── Bridged providers ────────────────────────────────────\n // The effective set for this instance: shared-providers ∩ ALLOWED_PROVIDERS\n // (see providers-bridge).\n const bridgedProviders = resolveBridgedProviders(host);\n\n // The bridge filters URLs in bridged values against the allowlist; the\n // silent-vs-prompt policy per provider type lives in the bridge.\n const bridgedValueFilter = makeBridgedValueFilter({\n isAllowed: (url) => allowlist.hasUrl(url as AutomergeUrl),\n requestAccess: (url) =>\n requestBridgedUrlAccess(\n repo,\n rootUrls,\n allowlist,\n denylist,\n url as AutomergeUrl\n ),\n });\n\n // ── Host-side RPC ───────────────────────────────────────\n const rpcChannel = new MessageChannel();\n hostRpcPort = rpcChannel.port1;\n\n cleanups.push(\n startResourceBridge({ port: hostRpcPort, mapper }),\n startHostNavigationBridge(hostRpcPort, host, (url) =>\n allowlist.hasUrl(url)\n ),\n // Drag-and-drop INTO the iframe (host → iframe). Unlike navigation, this\n // discloses document URLs to untrusted tool code, so each dragged URL is\n // gated: denylist-checked, then allowlisted (silently — the drag is the\n // user's authorization). Denylisted URLs are withheld. The iframe element\n // is fetched lazily; it exists by the time any drop can occur.\n startHostDragDropBridge(\n hostRpcPort,\n () => iframe,\n (url) => allowlistUrlUnlessSensitive(repo, url, allowlist, denylist)\n ),\n startHostProvidersBridge(\n hostRpcPort,\n host,\n bridgedProviders,\n bridgedValueFilter\n ),\n watchRegistries(hostRpcPort, mapper)\n );\n\n // ── Iframe ──────────────────────────────────────────────\n createIframe(rpcChannel.port2, intermediary.iframePort, mapper, assets, {\n rootComponentId,\n importMap,\n });\n }\n\n function createIframe(\n rpcPort: MessagePort,\n syncPort: MessagePort,\n mapper: PackagesUrlMapper,\n assets: Awaited<ReturnType<typeof fetchBootAssets>>,\n config: {\n rootComponentId: string;\n importMap: ReturnType<typeof getResolvedImportMap>;\n }\n ) {\n const el = document.createElement(\"iframe\");\n el.sandbox.add(\"allow-scripts\");\n el.style.cssText =\n \"border: none; width: 100%; height: 100%; display: block;\";\n // Bake the host's current background + color-scheme into the srcdoc so the\n // iframe's first paint matches the host (no flash of white before the\n // theming tool boots inside). Read tool-agnostically off the live element —\n // `host` is still connected, so its ancestors carry the host background.\n el.srcdoc = generateIframeSrcdoc(readHostAppearance(host));\n iframe = el;\n\n el.addEventListener(\"load\", async () => {\n if (stale() || !el.contentWindow) return;\n log(\"iframe ready\");\n\n const registryEntries = await getRegistries(mapper);\n if (stale() || !el.contentWindow) return;\n\n const automergeWasm = assets.automergeWasm.slice(0);\n const subductionWasm = assets.subductionWasm.slice(0);\n\n log(\n `sending boot message with ${registryEntries.length} registry entries, root \"${config.rootComponentId}\"`\n );\n el.contentWindow.postMessage(\n {\n type: \"boot\",\n rootComponentId: config.rootComponentId,\n // Read the data fresh at send time (not a boot-start snapshot): a\n // change between boot start and this async send is reflected in the\n // initial boot rather than lost, since a pre-port push no-ops.\n rootComponentData: readRootComponentData(host),\n registryEntries,\n esmsSource: assets.esmsSource,\n hostStyles: assets.hostStyles,\n importMap: config.importMap,\n hostOrigin: window.location.origin,\n automergeWasm,\n subductionWasm,\n },\n \"*\",\n [rpcPort, syncPort, automergeWasm, subductionWasm]\n );\n });\n\n const onBootMessage = (event: MessageEvent) => {\n if (event.data?.type === \"boot-error\") {\n console.error(\n \"[patchwork-isolation] iframe boot failed:\",\n event.data.error\n );\n }\n };\n hostRpcPort!.addEventListener(\"message\", onBootMessage);\n cleanups.push(() =>\n hostRpcPort?.removeEventListener(\"message\", onBootMessage)\n );\n\n host.appendChild(el);\n }\n\n let toreDown = false;\n function teardown() {\n if (toreDown) return;\n toreDown = true;\n cancelled = true;\n log(\"teardown\");\n\n for (const fn of cleanups) fn();\n cleanups.length = 0;\n\n hostRpcPort?.close();\n hostRpcPort = null;\n\n intermediary?.shutdown();\n intermediary = null;\n\n iframe?.remove();\n iframe = null;\n }\n\n // Push the current root-component data to the running iframe (no reboot).\n // No-op if torn down or the RPC port isn't wired yet — the boot is still in\n // flight and its boot message reads the data fresh at send time, so the latest\n // is delivered regardless. (We don't buffer here — a stale in-flight push would\n // race the boot message.)\n function pushRootComponentData() {\n if (toreDown || !hostRpcPort) return;\n hostRpcPort.postMessage({\n type: \"root-component-data-update\",\n rootComponentData: readRootComponentData(host),\n });\n }\n\n // Watch the data <script> for changes and stream them to the iframe. Scoped\n // to the script node itself (not `host`, whose children include the appended\n // iframe): `characterData` catches an in-place text edit, `childList` a\n // text-node swap, and `subtree` extends both to the script's text node —\n // together, \"the JSON changed, however the consumer applied it.\" Debounced so\n // one render touching the text pushes once. Torn down with the rest.\n const dataScript = findRootComponentDataScript(host);\n if (dataScript) {\n let pushQueued = false;\n const dataObserver = new MutationObserver(() => {\n if (pushQueued) return;\n pushQueued = true;\n queueMicrotask(() => {\n pushQueued = false;\n log(\"root component data changed; pushing to iframe\");\n pushRootComponentData();\n });\n });\n dataObserver.observe(dataScript, {\n characterData: true,\n childList: true,\n subtree: true,\n });\n cleanups.push(() => dataObserver.disconnect());\n }\n\n void run();\n return { teardown };\n}\n","import type { ComponentRender } from \"@inkandswitch/patchwork-elements\";\nimport { bootIsolation, type IsolationHandle } from \"./boot/index.js\";\nimport { log } from \"./log.js\";\n\n/**\n * The isolation `patchwork:component` mount function.\n *\n * Cross-package units are resolved through the registry by id, never imported,\n * so isolation ships as a `patchwork:component` (`patchwork-isolation`). The\n * consumer mounts it with `<patchwork-view component=\"patchwork-isolation\">` and\n * puts all the config on that element's DOM surface:\n *\n * <patchwork-view\n * component=\"patchwork-isolation\"\n * root-component=\"threepane-isolation-root\" // which root to mount inside the iframe\n * automerge-allowlist=\"automerge:abc,automerge:def\" // sync allowlist seeds\n * shared-providers=\"patchwork:contact,...\"> // bridged providers\n * <script type=\"application/json\" data-root-component-data> // opaque root-component data\n * {...}\n * </script>\n * </patchwork-view>\n *\n * `bootIsolation(element)` reads all of that off the element directly (plus the\n * `<repo-provider>` ancestor) and appends the iframe to it. It also watches the props `<script>`\n * internally and streams prop changes to the running iframe with no reboot.\n *\n * So this mount fn's only added responsibility is **structural** changes: it\n * observes `root-component` / `automerge-allowlist` / `shared-providers` and\n * **reboots** the iframe when one changes (`patchwork-view` doesn't observe\n * those attributes, so nothing else would).\n */\nexport const mountIsolation: ComponentRender = (element) => {\n let handle: IsolationHandle | null = bootIsolation(element);\n\n let rebootQueued = false;\n const attrObserver = new MutationObserver(() => {\n if (rebootQueued) return;\n rebootQueued = true;\n queueMicrotask(() => {\n rebootQueued = false;\n log(\"config attribute changed; rebooting iframe\");\n handle?.teardown();\n handle = bootIsolation(element);\n });\n });\n attrObserver.observe(element, {\n attributes: true,\n attributeFilter: [\n \"root-component\",\n \"automerge-allowlist\",\n \"shared-providers\",\n ],\n });\n\n return () => {\n attrObserver.disconnect();\n handle?.teardown();\n handle = null;\n };\n};\n"],"names":["require$$0","pkgJson","hasAutomergeDeps","entryPoint"],"mappings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