@vielzeug/sandbox 1.2.2 → 1.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/_dev.cjs CHANGED
@@ -1,2 +1,2 @@
1
- var e=!globalThis.__SANDBOX_PROD__;function t(t){e&&console.warn(`[@vielzeug/sandbox] ${t}`)}function n(t){e&&t()}exports.devOnly=n,exports.warn=t;
1
+ function e(e){}function t(e){}exports.devOnly=t,exports.warn=e;
2
2
  //# sourceMappingURL=_dev.cjs.map
package/dist/_dev.cjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"_dev.cjs","names":[],"sources":["../src/_dev.ts"],"sourcesContent":["const isDev = !(globalThis as { __SANDBOX_PROD__?: boolean }).__SANDBOX_PROD__;\n\n/** @internal @security — some callers interpolate user-supplied values (e.g. namedStyles key) into msg; do not log PII. */\nexport function warn(msg: string): void {\n if (isDev) console.warn(`[@vielzeug/sandbox] ${msg}`);\n}\n\n/** @internal — Run fn only in dev builds. Use when dev-only logic goes beyond a single warn() / error() call. */\nexport function devOnly(fn: () => void): void {\n if (isDev) fn();\n}\n"],"mappings":"AAAA,IAAM,EAAQ,CAAE,WAA8C,iBAG9D,SAAgB,EAAK,EAAmB,CAClC,GAAO,QAAQ,KAAK,uBAAuB,GAAK,CACtD,CAGA,SAAgB,EAAQ,EAAsB,CACxC,GAAO,EAAG,CAChB"}
1
+ {"version":3,"file":"_dev.cjs","names":[],"sources":["../src/_dev.ts"],"sourcesContent":["const isDev = !(globalThis as { __SANDBOX_PROD__?: boolean }).__SANDBOX_PROD__;\n\n/** @internal @security — some callers interpolate user-supplied values (e.g. namedStyles key) into msg; do not log PII. */\nexport function warn(msg: string): void {\n if (isDev) console.warn(`[@vielzeug/sandbox] ${msg}`);\n}\n\n/** @internal — Run fn only in dev builds. Use when dev-only logic goes beyond a single warn() / error() call. */\nexport function devOnly(fn: () => void): void {\n if (isDev) fn();\n}\n"],"mappings":"AAGA,SAAgB,EAAK,EAAmB,CAExC,CAGA,SAAgB,EAAQ,EAAsB,CAE9C"}
package/dist/_dev.js CHANGED
@@ -1,12 +1,7 @@
1
1
  //#region src/_dev.ts
2
- var e = !globalThis.__SANDBOX_PROD__;
3
- function t(t) {
4
- e && console.warn(`[@vielzeug/sandbox] ${t}`);
5
- }
6
- function n(t) {
7
- e && t();
8
- }
2
+ function e(e) {}
3
+ function t(e) {}
9
4
  //#endregion
10
- export { n as devOnly, t as warn };
5
+ export { t as devOnly, e as warn };
11
6
 
12
7
  //# sourceMappingURL=_dev.js.map
package/dist/_dev.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"_dev.js","names":[],"sources":["../src/_dev.ts"],"sourcesContent":["const isDev = !(globalThis as { __SANDBOX_PROD__?: boolean }).__SANDBOX_PROD__;\n\n/** @internal @security — some callers interpolate user-supplied values (e.g. namedStyles key) into msg; do not log PII. */\nexport function warn(msg: string): void {\n if (isDev) console.warn(`[@vielzeug/sandbox] ${msg}`);\n}\n\n/** @internal — Run fn only in dev builds. Use when dev-only logic goes beyond a single warn() / error() call. */\nexport function devOnly(fn: () => void): void {\n if (isDev) fn();\n}\n"],"mappings":";AAAA,IAAM,IAAQ,CAAE,WAA8C;AAG9D,SAAgB,EAAK,GAAmB;CACtC,AAAI,KAAO,QAAQ,KAAK,uBAAuB,GAAK;AACtD;AAGA,SAAgB,EAAQ,GAAsB;CAC5C,AAAI,KAAO,EAAG;AAChB"}
1
+ {"version":3,"file":"_dev.js","names":[],"sources":["../src/_dev.ts"],"sourcesContent":["const isDev = !(globalThis as { __SANDBOX_PROD__?: boolean }).__SANDBOX_PROD__;\n\n/** @internal @security — some callers interpolate user-supplied values (e.g. namedStyles key) into msg; do not log PII. */\nexport function warn(msg: string): void {\n if (isDev) console.warn(`[@vielzeug/sandbox] ${msg}`);\n}\n\n/** @internal — Run fn only in dev builds. Use when dev-only logic goes beyond a single warn() / error() call. */\nexport function devOnly(fn: () => void): void {\n if (isDev) fn();\n}\n"],"mappings":";AAGA,SAAgB,EAAK,GAAmB,CAExC;AAGA,SAAgB,EAAQ,GAAsB,CAE9C"}
package/dist/_sandbox.cjs CHANGED
@@ -1,4 +1,4 @@
1
- const e=require("./_dev.cjs"),t=require("./errors.cjs");var n=`ready`,r=`state-update`,i=`state-update-all`,a=`style-patch`,o=`html-patch`,s=`error`,c=`custom`,l=`resize`;function u(e){return typeof e==`object`&&!!e&&typeof e.type==`string`}function d(e){try{let t=new URL(e).origin;return t===`null`?null:t}catch{return null}}function f(e){return e.replace(/<\/style/gi,`\\3C /style`)}function p(e){return e.replace(/&/g,`&amp;`).replace(/"/g,`&quot;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`)}function m(e){return e.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`)}var h=/['";\n\r]/g;function g(e){return e.replace(h,``)}function _(e){return e.replace(h,``)}function v(e={}){let t=e.nonce?_(e.nonce):null,n=[`'unsafe-inline'`,...t?[`'nonce-${t}'`]:[],...(e.allowedScriptOrigins??[]).map(g),...(e.scripts??[]).map(d).filter(e=>e!==null)].join(` `),r=[`'unsafe-inline'`,...(e.allowedStyleOrigins??[]).map(g)].join(` `),i=[`data:`,...(e.allowedImageOrigins??[]).map(g)].join(` `),a=(e.allowedFontOrigins??[]).map(g).join(` `)||`'none'`;return[`default-src 'none'`,`script-src ${n}`,`style-src ${r}`,`img-src ${i}`,`font-src ${a}`,`connect-src 'none'`,`form-action 'none'`,`base-uri 'none'`].join(`; `)}var y=`if ('ontouchstart' in window) document.addEventListener('touchstart', function() {}, { passive: true });
1
+ require("./_dev.cjs");const e=require("./errors.cjs");var t=`ready`,n=`state-update`,r=`state-update-all`,i=`style-patch`,a=`html-patch`,o=`error`,s=`custom`,c=`resize`;function l(e){return typeof e==`object`&&!!e&&typeof e.type==`string`}function u(e){try{let t=new URL(e).origin;return t===`null`?null:t}catch{return null}}function d(e){return e.replace(/<\/style/gi,`\\3C /style`)}function f(e){return e.replace(/&/g,`&amp;`).replace(/"/g,`&quot;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`)}function p(e){return e.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`)}var m=/['";\n\r]/g;function h(e){return e.replace(m,``)}function g(e){return e.replace(m,``)}function _(e={}){let t=e.nonce?g(e.nonce):null,n=[`'unsafe-inline'`,...t?[`'nonce-${t}'`]:[],...(e.allowedScriptOrigins??[]).map(h),...(e.scripts??[]).map(u).filter(e=>e!==null)].join(` `),r=[`'unsafe-inline'`,...(e.allowedStyleOrigins??[]).map(h)].join(` `),i=[`data:`,...(e.allowedImageOrigins??[]).map(h)].join(` `),a=(e.allowedFontOrigins??[]).map(h).join(` `)||`'none'`;return[`default-src 'none'`,`script-src ${n}`,`style-src ${r}`,`img-src ${i}`,`font-src ${a}`,`connect-src 'none'`,`form-action 'none'`,`base-uri 'none'`].join(`; `)}var v=`if ('ontouchstart' in window) document.addEventListener('touchstart', function() {}, { passive: true });
2
2
  window.addEventListener('message', function(e) {
3
3
  var msg = e.data;
4
4
  if (msg && msg.type === 'state-update') {
@@ -59,23 +59,23 @@ if (typeof ResizeObserver !== 'undefined') {
59
59
  : entry.contentRect.height;
60
60
  post({ type: 'resize', height: h });
61
61
  }).observe(document.body);
62
- }`;function b(e,t={}){let n=p(v(t)),r=t.namedStyles??{};return`<!doctype html>
63
- <html lang="${p(t.lang??`en`)}">
62
+ }`;function y(e,t={}){let n=f(_(t)),r=t.namedStyles??{};return`<!doctype html>
63
+ <html lang="${f(t.lang??`en`)}">
64
64
  <head>
65
65
  <meta http-equiv="Content-Security-Policy" content="${n}">
66
66
  <meta charset="utf-8">
67
67
  <meta name="viewport" content="width=device-width, initial-scale=1">
68
- <title>${m(t.title??``)}</title>
69
- ${Object.entries(r).map(([e,t])=>`<style id="${p(e)}">${f(t)}</style>`).join(`
68
+ <title>${p(t.title??``)}</title>
69
+ ${Object.entries(r).map(([e,t])=>`<style id="${f(e)}">${d(t)}</style>`).join(`
70
70
  `)}
71
71
  </head>
72
72
  <body>
73
- ${(t.scripts??[]).map(e=>`<script crossorigin="anonymous" src="${p(e)}"><\/script>`).join(`
73
+ ${(t.scripts??[]).map(e=>`<script crossorigin="anonymous" src="${f(e)}"><\/script>`).join(`
74
74
  `)}
75
75
  ${e}
76
- <script${t.nonce?` nonce="${p(_(t.nonce))}"`:``}>
77
- ${y}
76
+ <script${t.nonce?` nonce="${f(g(t.nonce))}"`:``}>
77
+ ${v}
78
78
  <\/script>
79
79
  </body>
80
- </html>`}var x=5e3;function S(d,f={}){let p=null,m=new Set,h=!1,g=new AbortController,_={...f.namedStyles??{}},v=!1,y=0,S,C=new Promise(e=>{S=e}),w=null,T=null;function E(){T!==null&&(clearTimeout(T),T=null)}function D(){E(),w?.resolve(),w=null,v=!1}let O={[c]:e=>{typeof e.event==`string`&&k({detail:e.detail,event:e.event,type:c})},[s]:e=>{typeof e.message==`string`&&k({message:e.message,...typeof e.stack==`string`?{stack:e.stack}:{},type:s})},[n]:()=>{D(),S(),v=!0},[l]:e=>{typeof e.height==`number`&&k({height:e.height,type:l})}};function k(e){for(let t of m)t(e)}function A(e){if(!p||e.source!==p.contentWindow||!u(e.data))return;let t=e.data.generation;typeof t==`number`&&t!==y||Object.hasOwn(O,e.data.type)&&O[e.data.type](e.data)}function j(){return p||(p=document.createElement(`iframe`),p.setAttribute(`sandbox`,`allow-scripts`),p.setAttribute(`referrerpolicy`,`no-referrer`),d.appendChild(p),window.addEventListener(`message`,A),p)}function M(){h||(h=!0,D(),g.abort(),S(),p&&=(window.removeEventListener(`message`,A),p.remove(),null),m.clear())}function N(t){return h?(e.warn(`onMessage() called on a disposed sandbox — handler will never fire.`),()=>{}):(m.add(t),()=>{m.delete(t)})}function P(n,r){if(h)return e.warn(`render() called on a disposed sandbox.`),Promise.resolve();if(r?.signal?.aborted)return Promise.resolve();n.trim()||e.warn(`render() called with empty HTML.`),D();let i=++y,a=b(n,Object.keys(_).length>0?{...f,namedStyles:{..._}}:f).replace(`<head>`,`<head>\n<script>window.__sandboxGeneration=${i};<\/script>`);j().srcdoc=a;let o=new Promise((e,t)=>{w={reject:t,resolve:e}});return T=setTimeout(()=>{w&&(w.reject(new t.SandboxTimeoutError(`render() did not receive a 'ready' signal from the sandbox document within ${x}ms. The document is likely missing the bridge script — use buildDocument() to generate documents that include it.`)),w=null,T=null)},x),o}function F(t){if(h){e.warn(`patch() called on a disposed sandbox.`);return}if(!v||!p?.contentWindow){e.warn(`patch() called before render() has resolved — bridge is not yet initialized. Await the Promise returned by render() first.`);return}p.contentWindow.postMessage({html:t,type:o},`*`)}function I(t,n){if(h){e.warn(`setState() called on a disposed sandbox.`);return}if(!p?.contentWindow){e.warn(`setState() called before render() — sandbox has no document yet.`);return}v||e.warn(`setState() called before ready — state update may be lost if bridge is not yet initialized. Await the Promise returned by render() first.`),p.contentWindow.postMessage({key:t,type:r,value:n},`*`)}function L(t){if(h){e.warn(`setStateAll() called on a disposed sandbox.`);return}if(!p?.contentWindow){e.warn(`setStateAll() called before render() — sandbox has no document yet.`);return}v||e.warn(`setStateAll() called before ready — state updates may be lost. Await the Promise returned by render() first.`),p.contentWindow.postMessage({record:t,type:i},`*`)}function R(t,n){h||(e.devOnly(()=>{t in _||e.warn(`updateStyle('${t}', …) — '${t}' is not a known namedStyles key. The live patch will have no effect. Pass the id as a key in namedStyles when calling createSandbox().`)}),_[t]=n,v&&p?.contentWindow&&p.contentWindow.postMessage({css:n,id:t,type:a},`*`))}return{get disposalSignal(){return g.signal},dispose:M,get disposed(){return h},onMessage:N,patch:F,ready:C,render:P,setState:I,setStateAll:L,[Symbol.dispose](){M()},updateStyle:R}}exports.buildCsp=v,exports.buildDocument=b,exports.createSandbox=S;
80
+ </html>`}var b=5e3;function x(u,d={}){let f=null,p=new Set,m=!1,h=new AbortController,g={...d.namedStyles??{}},_=!1,v=0,x,S=new Promise(e=>{x=e}),C=null,w=null;function T(){w!==null&&(clearTimeout(w),w=null)}function E(){T(),C?.resolve(),C=null,_=!1}let D={[s]:e=>{typeof e.event==`string`&&O({detail:e.detail,event:e.event,type:s})},[o]:e=>{typeof e.message==`string`&&O({message:e.message,...typeof e.stack==`string`?{stack:e.stack}:{},type:o})},[t]:()=>{E(),x(),_=!0},[c]:e=>{typeof e.height==`number`&&O({height:e.height,type:c})}};function O(e){for(let t of p)t(e)}function k(e){if(!f||e.source!==f.contentWindow||!l(e.data))return;let t=e.data.generation;(typeof t!=`number`||t===v)&&Object.hasOwn(D,e.data.type)&&D[e.data.type](e.data)}function A(){return f||(f=document.createElement(`iframe`),f.setAttribute(`sandbox`,`allow-scripts`),f.setAttribute(`referrerpolicy`,`no-referrer`),u.appendChild(f),window.addEventListener(`message`,k),f)}function j(){m||(m=!0,E(),h.abort(),x(),f&&=(window.removeEventListener(`message`,k),f.remove(),null),p.clear())}function M(e){return m?()=>{}:(p.add(e),()=>{p.delete(e)})}function N(t,n){if(m||n?.signal?.aborted)return Promise.resolve();t.trim(),E();let r=++v,i=y(t,Object.keys(g).length>0?{...d,namedStyles:{...g}}:d).replace(`<head>`,`<head>\n<script>window.__sandboxGeneration=${r};<\/script>`);A().srcdoc=i;let a=new Promise((e,t)=>{C={reject:t,resolve:e}});return w=setTimeout(()=>{C&&(C.reject(new e.SandboxTimeoutError(`render() did not receive a 'ready' signal from the sandbox document within ${b}ms. The document is likely missing the bridge script — use buildDocument() to generate documents that include it.`)),C=null,w=null)},b),a}function P(e){m||!_||!f?.contentWindow||f.contentWindow.postMessage({html:e,type:a},`*`)}function F(e,t){m||f?.contentWindow&&f.contentWindow.postMessage({key:e,type:n,value:t},`*`)}function I(e){m||f?.contentWindow&&f.contentWindow.postMessage({record:e,type:r},`*`)}function L(e,t){m||(g[e]=t,_&&f?.contentWindow&&f.contentWindow.postMessage({css:t,id:e,type:i},`*`))}return{get disposalSignal(){return h.signal},dispose:j,get disposed(){return m},onMessage:M,patch:P,ready:S,render:N,setState:F,setStateAll:I,[Symbol.dispose](){j()},updateStyle:L}}exports.buildCsp=_,exports.buildDocument=y,exports.createSandbox=x;
81
81
  //# sourceMappingURL=_sandbox.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"_sandbox.cjs","names":[],"sources":["../src/_sandbox.ts"],"sourcesContent":["import type { SandboxHandle, SandboxMessage, SandboxOptions, Unsubscribe } from './types.js';\n\nimport { devOnly, warn } from './_dev';\nimport { SandboxTimeoutError } from './errors.js';\n\n// Re-export types so that _sandbox.ts still exposes them via its original named exports.\n// index.ts now imports types from ./types.js directly — these re-exports are kept only\n// to avoid breaking any direct imports of _sandbox.js in tests.\nexport type {\n SandboxBridge,\n SandboxHandle,\n SandboxMessage,\n SandboxOptions,\n SandboxStateUpdateDetail,\n Unsubscribe,\n} from './types.js';\n\n// ---------------------------------------------------------------------------\n// Protocol constants\n//\n// String values for the postMessage type field crossing the host↔sandbox\n// boundary. Inlined here (not a shared module) because the bridge script is\n// a plain-JS string that cannot import TypeScript modules.\n// ---------------------------------------------------------------------------\n\nconst MSG_READY = 'ready';\nconst MSG_STATE_UPDATE = 'state-update';\nconst MSG_STATE_UPDATE_ALL = 'state-update-all';\nconst MSG_STYLE_PATCH = 'style-patch';\nconst MSG_HTML_PATCH = 'html-patch';\nconst MSG_ERROR = 'error';\nconst MSG_CUSTOM = 'custom';\nconst MSG_RESIZE = 'resize';\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction isMsgObject(data: unknown): data is Record<string, unknown> & { type: string } {\n return typeof data === 'object' && data !== null && typeof (data as { type?: unknown }).type === 'string';\n}\n\nfunction extractOrigin(url: string): string | null {\n try {\n const o = new URL(url).origin;\n\n return o !== 'null' ? o : null;\n } catch {\n return null;\n }\n}\n\n// Prevent CSS breakout: the HTML spec treats <style> as a raw-text element —\n// it ends at the first `</style` token and the sequence cannot be escaped in\n// HTML. The correct fix is to escape `<` in CSS using its CSS unicode escape\n// `\\3C ` (trailing space terminates the escape sequence). This produces valid\n// CSS that the browser parses correctly, but breaks the HTML tokenizer's\n// `</style` match. The backslash itself is safe because CSS ignores unknown\n// escape sequences.\nfunction escapeCss(css: string): string {\n return css.replace(/<\\/style/gi, '\\\\3C /style');\n}\n\n// Escape a string for safe interpolation into an HTML double-quoted attribute\n// value (e.g. lang=\"…\", id=\"…\", nonce=\"…\"). Encodes the four characters that\n// can break out of an attribute or inject new attributes.\nfunction escapeAttr(value: string): string {\n return value.replace(/&/g, '&amp;').replace(/\"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');\n}\n\n// Escape a string for safe interpolation into HTML text content (e.g. <title>).\n// Encodes & and < to prevent tag/entity injection; > is included for symmetry.\nfunction escapeText(value: string): string {\n return value.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');\n}\n\n// ---------------------------------------------------------------------------\n// CSP builder\n// ---------------------------------------------------------------------------\n\n// Characters illegal inside CSP source-list tokens (origins and nonces alike) that\n// would allow directive injection or HTML attribute breakout. Specifically:\n// ';' — CSP directive separator (would inject a new directive)\n// '\"' / \"'\" — breaks out of the HTML content=\"...\" / nonce=\"...\" attribute\n// '\\n' / '\\r' — CSP header line folding / response-splitting\nconst CSP_UNSAFE_CHARS = /['\";\\n\\r]/g;\n\n// Origins must be scheme+host(+port) form; none of CSP_UNSAFE_CHARS belong there.\nfunction sanitizeCspOrigin(origin: string): string {\n return origin.replace(CSP_UNSAFE_CHARS, '');\n}\n\n// Sanitize a nonce for CSP-token embedding — CSP nonces must be base64\n// characters only; stripping quotes/semicolons/newlines prevents early token\n// termination inside 'nonce-{value}'. buildCsp() and buildDocument() MUST both\n// derive their nonce from this exact function: the CSP header's nonce token and\n// the bridge <script nonce=\"...\"> attribute have to match byte-for-byte, or the\n// browser silently rejects the script — breaking the bridge (and CSP nonce\n// matching is stricter than HTML-attribute escaping, so applying escapeAttr()\n// to the raw, unsanitized nonce for the attribute while sanitizing separately\n// for the CSP token can produce two different strings).\nfunction sanitizeNonce(nonce: string): string {\n return nonce.replace(CSP_UNSAFE_CHARS, '');\n}\n\n/**\n * Builds a strict Content-Security-Policy string for sandboxed iframe documents.\n *\n * Accepts SandboxOptions directly — origins from `scripts` URLs are extracted and\n * merged with `allowedScriptOrigins` automatically.\n */\nexport function buildCsp(options: SandboxOptions = {}): string {\n const safeNonce = options.nonce ? sanitizeNonce(options.nonce) : null;\n\n const scriptOrigins = [\n \"'unsafe-inline'\",\n ...(safeNonce ? [`'nonce-${safeNonce}'`] : []),\n ...(options.allowedScriptOrigins ?? []).map(sanitizeCspOrigin),\n ...(options.scripts ?? []).map(extractOrigin).filter((o): o is string => o !== null),\n ].join(' ');\n\n const styleOrigins = [\"'unsafe-inline'\", ...(options.allowedStyleOrigins ?? []).map(sanitizeCspOrigin)].join(' ');\n const imgOrigins = ['data:', ...(options.allowedImageOrigins ?? []).map(sanitizeCspOrigin)].join(' ');\n const fontOrigins = (options.allowedFontOrigins ?? []).map(sanitizeCspOrigin).join(' ') || \"'none'\";\n\n return [\n \"default-src 'none'\",\n `script-src ${scriptOrigins}`,\n `style-src ${styleOrigins}`,\n `img-src ${imgOrigins}`,\n `font-src ${fontOrigins}`,\n \"connect-src 'none'\",\n \"form-action 'none'\",\n \"base-uri 'none'\",\n ].join('; ');\n}\n\n// ---------------------------------------------------------------------------\n// Document builder\n// ---------------------------------------------------------------------------\n\n// Bridge script embedded in every sandbox document.\n//\n// Plain JS — cannot import TypeScript modules. Message type strings must\n// match the MSG_* constants above.\n//\n// Auto-resize: ResizeObserver on document.body emits 'resize' messages\n// automatically — consumers don't need to wire ResizeObserver in their\n// sandbox content. The observer is set up AFTER the 'ready' postMessage so\n// that the first resize callback (which fires synchronously on observe()) does\n// not arrive at the host before bridgeReady is set.\n//\n// style-patch is scoped to <style> elements (tagName guard) to prevent\n// accidental content injection into non-style elements with a matching id.\nconst BRIDGE_SCRIPT = `\nif ('ontouchstart' in window) document.addEventListener('touchstart', function() {}, { passive: true });\nwindow.addEventListener('message', function(e) {\n var msg = e.data;\n if (msg && msg.type === 'state-update') {\n document.dispatchEvent(new CustomEvent('sandbox:state-update', { detail: { key: msg.key, value: msg.value } }));\n }\n if (msg && msg.type === 'state-update-all' && msg.record && typeof msg.record === 'object') {\n var keys = Object.keys(msg.record);\n for (var i = 0; i < keys.length; i++) {\n var k = keys[i];\n document.dispatchEvent(new CustomEvent('sandbox:state-update', { detail: { key: k, value: msg.record[k] } }));\n }\n }\n if (msg && msg.type === 'style-patch' && msg.id && typeof msg.css === 'string') {\n var el = document.getElementById(msg.id);\n if (el && el.tagName === 'STYLE') el.textContent = msg.css;\n }\n if (msg && msg.type === 'html-patch' && typeof msg.html === 'string') {\n document.body.innerHTML = msg.html;\n }\n});\n// post() tags every outgoing message with window.__sandboxGeneration (set by render(),\n// see below) and always targets '*' — srcdoc iframes have origin 'null' so no specific\n// origin can be addressed. The host uses the generation tag to ignore messages from a\n// document a newer render() has already superseded.\nfunction post(msg) {\n msg.generation = window.__sandboxGeneration;\n parent.postMessage(msg, '*');\n}\nwindow.onerror = function(message, _src, _line, _col, err) {\n post({ type: 'error', message: String(message), stack: err && err.stack });\n return true;\n};\nwindow.addEventListener('unhandledrejection', function(e) {\n var reason = e.reason;\n post({ type: 'error', message: String(reason), stack: reason && reason.stack });\n});\nwindow.__sandbox__ = {\n emit: function(event, detail) {\n post({ type: 'custom', event: event, detail: detail });\n },\n onState: function(key, handler) {\n function listener(e) {\n if (e.detail && e.detail.key === key) handler(e.detail.value);\n }\n document.addEventListener('sandbox:state-update', listener);\n return function() {\n document.removeEventListener('sandbox:state-update', listener);\n };\n }\n};\npost({ type: 'ready' });\nif (typeof ResizeObserver !== 'undefined') {\n new ResizeObserver(function(entries) {\n var entry = entries[0];\n if (!entry) return;\n var h = entry.borderBoxSize && entry.borderBoxSize[0]\n ? entry.borderBoxSize[0].blockSize\n : entry.contentRect.height;\n post({ type: 'resize', height: h });\n }).observe(document.body);\n}\n`.trim();\n\n/**\n * Builds a complete, standalone sandbox HTML document.\n *\n * `namedStyles` entries are rendered as `<style id=\"key\">` elements in the\n * document `<head>`. External scripts carry `crossorigin=\"anonymous\"` so the\n * bridge's error handler receives full error details for cross-origin scripts.\n * The bridge script auto-emits `resize` messages via `ResizeObserver`.\n */\nexport function buildDocument(html: string, options: SandboxOptions = {}): string {\n // escapeAttr is applied to the whole CSP string when embedding it in content=\"...\"\n // because buildCsp() does not know the embedding context. Any user-supplied origin\n // values that survived sanitizeCspOrigin() but still contain & or < (very unusual)\n // would otherwise break the HTML attribute.\n const csp = escapeAttr(buildCsp(options));\n const named = options.namedStyles ?? {};\n const lang = escapeAttr(options.lang ?? 'en');\n const title = escapeText(options.title ?? '');\n\n const styleTags = Object.entries(named)\n .map(([id, css]) => `<style id=\"${escapeAttr(id)}\">${escapeCss(css)}</style>`)\n .join('\\n');\n\n const scriptTags = (options.scripts ?? [])\n .map((src) => `<script crossorigin=\"anonymous\" src=\"${escapeAttr(src)}\"></script>`)\n .join('\\n');\n\n // Must sanitize with the exact same sanitizeNonce() used by buildCsp() — see its\n // comment. escapeAttr() alone is not enough: it HTML-encodes but does not strip,\n // so a raw nonce containing e.g. ';' would attribute-escape differently than the\n // CSP token strips it, producing a mismatched nonce and a silently broken bridge.\n const nonceAttr = options.nonce ? ` nonce=\"${escapeAttr(sanitizeNonce(options.nonce))}\"` : '';\n\n return `<!doctype html>\n<html lang=\"${lang}\">\n<head>\n<meta http-equiv=\"Content-Security-Policy\" content=\"${csp}\">\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<title>${title}</title>\n${styleTags}\n</head>\n<body>\n${scriptTags}\n${html}\n<script${nonceAttr}>\n${BRIDGE_SCRIPT}\n</script>\n</body>\n</html>`;\n}\n\n// ---------------------------------------------------------------------------\n// Sandbox factory\n// ---------------------------------------------------------------------------\n\n// Dev-only timeout: if the bridge never fires 'ready' after a render(), warn\n// so the developer knows the bridge script is missing or broken.\nconst READY_TIMEOUT_MS = 5000;\n\nexport function createSandbox(container: HTMLElement, options: SandboxOptions = {}): SandboxHandle {\n // Iframe is created lazily on the first render() call — no DOM work until\n // there is content to show.\n let iframe: HTMLIFrameElement | null = null;\n const listeners = new Set<(msg: SandboxMessage) => void>();\n let disposed = false;\n const ac = new AbortController();\n\n // Mutable namedStyles baseline — updateStyle() patches this so re-renders\n // automatically use the latest CSS without the caller re-passing options.\n const namedStyles: Record<string, string> = { ...(options.namedStyles ?? {}) };\n\n // bridgeReady: true once the bridge inside the current document has fired MSG_READY.\n // Reset to false on each render() so setState/updateStyle guards work correctly.\n let bridgeReady = false;\n\n // Monotonic counter embedded into each srcdoc as window.__sandboxGeneration (see\n // render()). iframe.contentWindow's identity is stable across srcdoc navigations in\n // real browsers, so event.source alone cannot distinguish a superseded document's\n // messages from the current one — the generation tag closes that gap.\n let renderGeneration = 0;\n\n // First-render gate — resolves on first ready signal or on dispose().\n // Always resolves (never rejects) so callers can safely fire-and-forget it.\n // Check sandbox.disposed afterward to distinguish a dispose-resolution.\n let resolveReady!: () => void;\n const ready = new Promise<void>((resolve) => {\n resolveReady = resolve;\n });\n\n // Per-render settlers — replaced on each render(), resolved on the next 'ready'\n // message or when superseded/disposed (not an error — the document navigated away\n // or the sandbox was torn down intentionally), rejected only by the ready-timeout.\n let currentRenderSettlers: { reject: (err: unknown) => void; resolve: () => void } | null = null;\n let readyTimeoutId: ReturnType<typeof setTimeout> | null = null;\n\n function clearReadyTimeout(): void {\n if (readyTimeoutId !== null) {\n clearTimeout(readyTimeoutId);\n readyTimeoutId = null;\n }\n }\n\n // Supersede the in-flight render: resolve (not reject) its promise, clear the\n // timeout, and reset bridgeReady. All three must change together — keep them here.\n function supersedePendingRender(): void {\n clearReadyTimeout();\n currentRenderSettlers?.resolve();\n currentRenderSettlers = null;\n bridgeReady = false;\n }\n\n // Dispatch table for incoming sandbox→host messages.\n // Adding a new message type means adding one entry here — no separate allowlist.\n // Each handler constructs a typed SandboxMessage rather than casting, so the\n // compiler verifies the shape and malformed payloads are silently dropped.\n const msgHandlers: Record<string, (msg: Record<string, unknown>) => void> = {\n [MSG_CUSTOM]: (msg) => {\n if (typeof msg.event === 'string') {\n broadcast({ detail: msg.detail, event: msg.event, type: MSG_CUSTOM });\n }\n },\n [MSG_ERROR]: (msg) => {\n if (typeof msg.message === 'string') {\n broadcast({\n message: msg.message,\n ...(typeof msg.stack === 'string' ? { stack: msg.stack } : {}),\n type: MSG_ERROR,\n });\n }\n },\n [MSG_READY]: () => {\n // supersedePendingRender clears the timeout and resolves the render promise.\n // bridgeReady is re-set to true immediately after because the bridge IS ready.\n supersedePendingRender();\n resolveReady();\n bridgeReady = true;\n },\n [MSG_RESIZE]: (msg) => {\n if (typeof msg.height === 'number') broadcast({ height: msg.height, type: MSG_RESIZE });\n },\n };\n\n function broadcast(msg: SandboxMessage): void {\n for (const listener of listeners) listener(msg);\n }\n\n function handleMessage(event: MessageEvent): void {\n if (!iframe || event.source !== iframe.contentWindow) return;\n\n if (!isMsgObject(event.data)) return;\n\n // Reject messages tagged with a superseded generation — a document torn down by a\n // newer render() may still have a message in flight. Messages with no generation\n // (or a non-number one, e.g. from testing helpers) are trusted and pass through.\n const generation = event.data.generation;\n\n if (typeof generation === 'number' && generation !== renderGeneration) return;\n\n // Guard against prototype-inherited properties on msgHandlers (e.g. '__proto__',\n // '__defineGetter__') — these are not functions and calling them via ?.() throws.\n // Object.hasOwn ensures only keys explicitly defined in the dispatch table are invoked.\n if (Object.hasOwn(msgHandlers, event.data.type)) {\n msgHandlers[event.data.type]!(event.data);\n }\n }\n\n function ensureIframe(): HTMLIFrameElement {\n if (iframe) return iframe;\n\n iframe = document.createElement('iframe');\n iframe.setAttribute('sandbox', 'allow-scripts');\n iframe.setAttribute('referrerpolicy', 'no-referrer');\n container.appendChild(iframe);\n window.addEventListener('message', handleMessage);\n\n return iframe;\n }\n\n function dispose(): void {\n if (disposed) return;\n\n disposed = true;\n supersedePendingRender();\n ac.abort();\n resolveReady();\n\n if (iframe) {\n window.removeEventListener('message', handleMessage);\n iframe.remove();\n iframe = null;\n }\n\n listeners.clear();\n }\n\n function onMessage(handler: (msg: SandboxMessage) => void): Unsubscribe {\n if (disposed) {\n warn('onMessage() called on a disposed sandbox — handler will never fire.');\n\n return () => {};\n }\n\n listeners.add(handler);\n\n return () => {\n listeners.delete(handler);\n };\n }\n\n function render(html: string, renderOptions?: { signal?: AbortSignal }): Promise<void> {\n if (disposed) {\n warn('render() called on a disposed sandbox.');\n\n return Promise.resolve();\n }\n\n if (renderOptions?.signal?.aborted) return Promise.resolve();\n\n if (!html.trim()) {\n warn('render() called with empty HTML.');\n }\n\n // Supersede any in-flight render — its document navigated away.\n supersedePendingRender();\n\n const generation = ++renderGeneration;\n const docOptions = Object.keys(namedStyles).length > 0 ? { ...options, namedStyles: { ...namedStyles } } : options;\n\n // Inject the generation marker into <head> — it always appears before any user\n // content in the template, so this replace can never hit HTML inside `html`.\n const doc = buildDocument(html, docOptions).replace(\n '<head>',\n `<head>\\n<script>window.__sandboxGeneration=${generation};</script>`,\n );\n\n ensureIframe().srcdoc = doc;\n\n const p = new Promise<void>((resolve, reject) => {\n currentRenderSettlers = { reject, resolve };\n });\n\n // If the bridge never fires 'ready', reject with SandboxTimeoutError so the\n // document-missing-bridge-script failure is catchable rather than hanging forever.\n readyTimeoutId = setTimeout(() => {\n if (currentRenderSettlers) {\n currentRenderSettlers.reject(\n new SandboxTimeoutError(\n `render() did not receive a 'ready' signal from the sandbox document within ${READY_TIMEOUT_MS}ms. ` +\n 'The document is likely missing the bridge script — use buildDocument() to generate documents that include it.',\n ),\n );\n currentRenderSettlers = null;\n readyTimeoutId = null;\n }\n }, READY_TIMEOUT_MS);\n\n return p;\n }\n\n function patch(html: string): void {\n if (disposed) {\n warn('patch() called on a disposed sandbox.');\n\n return;\n }\n\n if (!bridgeReady || !iframe?.contentWindow) {\n warn(\n 'patch() called before render() has resolved — bridge is not yet initialized. Await the Promise returned by render() first.',\n );\n\n return;\n }\n\n // srcdoc iframes have origin 'null' — '*' is required because no specific origin can be targeted.\n iframe.contentWindow.postMessage({ html, type: MSG_HTML_PATCH }, '*');\n }\n\n function setState(key: string, value: unknown): void {\n if (disposed) {\n warn('setState() called on a disposed sandbox.');\n\n return;\n }\n\n if (!iframe?.contentWindow) {\n warn('setState() called before render() — sandbox has no document yet.');\n\n return;\n }\n\n if (!bridgeReady) {\n warn(\n 'setState() called before ready — state update may be lost if bridge is not yet initialized. Await the Promise returned by render() first.',\n );\n }\n\n // srcdoc iframes have origin 'null' — '*' is required because no specific origin can be targeted.\n iframe.contentWindow.postMessage({ key, type: MSG_STATE_UPDATE, value }, '*');\n }\n\n function setStateAll(record: Record<string, unknown>): void {\n if (disposed) {\n warn('setStateAll() called on a disposed sandbox.');\n\n return;\n }\n\n if (!iframe?.contentWindow) {\n warn('setStateAll() called before render() — sandbox has no document yet.');\n\n return;\n }\n\n if (!bridgeReady) {\n warn(\n 'setStateAll() called before ready — state updates may be lost. Await the Promise returned by render() first.',\n );\n }\n\n // srcdoc iframes have origin 'null' — '*' is required because no specific origin can be targeted.\n iframe.contentWindow.postMessage({ record, type: MSG_STATE_UPDATE_ALL }, '*');\n }\n\n function updateStyle(id: string, css: string): void {\n if (disposed) return;\n\n devOnly(() => {\n if (!(id in namedStyles)) {\n warn(\n `updateStyle('${id}', …) — '${id}' is not a known namedStyles key. ` +\n 'The live patch will have no effect. Pass the id as a key in namedStyles when calling createSandbox().',\n );\n }\n });\n\n namedStyles[id] = css;\n\n if (bridgeReady && iframe?.contentWindow) {\n // srcdoc iframes have origin 'null' — '*' is required because no specific origin can be targeted.\n iframe.contentWindow.postMessage({ css, id, type: MSG_STYLE_PATCH }, '*');\n }\n }\n\n return {\n get disposalSignal() {\n return ac.signal;\n },\n dispose,\n get disposed() {\n return disposed;\n },\n onMessage,\n patch,\n ready,\n render,\n setState,\n setStateAll,\n [Symbol.dispose]() {\n dispose();\n },\n updateStyle,\n };\n}\n"],"mappings":"wDAyBA,IAAM,EAAY,QACZ,EAAmB,eACnB,EAAuB,mBACvB,EAAk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F,EAEA,MACF,CAGA,EAAO,cAAc,YAAY,CAAE,OAAM,KAAM,CAAe,EAAG,GAAG,CACtE,CAEA,SAAS,EAAS,EAAa,EAAsB,CACnD,GAAI,EAAU,CACZ,EAAA,KAAK,0CAA0C,EAE/C,MACF,CAEA,GAAI,CAAC,GAAQ,cAAe,CAC1B,EAAA,KAAK,kEAAkE,EAEvE,MACF,CAEK,GACH,EAAA,KACE,2IACF,EAIF,EAAO,cAAc,YAAY,CAAE,MAAK,KAAM,EAAkB,OAAM,EAAG,GAAG,CAC9E,CAEA,SAAS,EAAY,EAAuC,CAC1D,GAAI,EAAU,CACZ,EAAA,KAAK,6CAA6C,EAElD,MACF,CAEA,GAAI,CAAC,GAAQ,cAAe,CAC1B,EAAA,KAAK,qEAAqE,EAE1E,MACF,CAEK,GACH,EAAA,KACE,8GACF,EAIF,EAAO,cAAc,YAAY,CAAE,SAAQ,KAAM,CAAqB,EAAG,GAAG,CAC9E,CAEA,SAAS,EAAY,EAAY,EAAmB,CAC9C,IAEJ,EAAA,YAAc,CACN,KAAM,GACV,EAAA,KACE,gBAAgB,EAAG,WAAW,EAAG,wIAEnC,CAEJ,CAAC,EAED,EAAY,GAAM,EAEd,GAAe,GAAQ,eAEzB,EAAO,cAAc,YAAY,CAAE,MAAK,KAAI,KAAM,CAAgB,EAAG,GAAG,EAE5E,CAEA,MAAO,CACL,IAAI,gBAAiB,CACnB,OAAO,EAAG,MACZ,EACA,UACA,IAAI,UAAW,CACb,OAAO,CACT,EACA,YACA,QACA,QACA,SACA,WACA,cACA,CAAC,OAAO,UAAW,CACjB,EAAQ,CACV,EACA,aACF,CACF"}
1
+ {"version":3,"file":"_sandbox.cjs","names":[],"sources":["../src/_sandbox.ts"],"sourcesContent":["import type { SandboxHandle, SandboxMessage, SandboxOptions, Unsubscribe } from './types.js';\n\nimport { devOnly, warn } from './_dev';\nimport { SandboxTimeoutError } from './errors.js';\n\n// Re-export types so that _sandbox.ts still exposes them via its original named exports.\n// index.ts now imports types from ./types.js directly — these re-exports are kept only\n// to avoid breaking any direct imports of _sandbox.js in tests.\nexport type {\n SandboxBridge,\n SandboxHandle,\n SandboxMessage,\n SandboxOptions,\n SandboxStateUpdateDetail,\n Unsubscribe,\n} from './types.js';\n\n// ---------------------------------------------------------------------------\n// Protocol constants\n//\n// String values for the postMessage type field crossing the host↔sandbox\n// boundary. Inlined here (not a shared module) because the bridge script is\n// a plain-JS string that cannot import TypeScript modules.\n// ---------------------------------------------------------------------------\n\nconst MSG_READY = 'ready';\nconst MSG_STATE_UPDATE = 'state-update';\nconst MSG_STATE_UPDATE_ALL = 'state-update-all';\nconst MSG_STYLE_PATCH = 'style-patch';\nconst MSG_HTML_PATCH = 'html-patch';\nconst MSG_ERROR = 'error';\nconst MSG_CUSTOM = 'custom';\nconst MSG_RESIZE = 'resize';\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction isMsgObject(data: unknown): data is Record<string, unknown> & { type: string } {\n return typeof data === 'object' && data !== null && typeof (data as { type?: unknown }).type === 'string';\n}\n\nfunction extractOrigin(url: string): string | null {\n try {\n const o = new URL(url).origin;\n\n return o !== 'null' ? o : null;\n } catch {\n return null;\n }\n}\n\n// Prevent CSS breakout: the HTML spec treats <style> as a raw-text element —\n// it ends at the first `</style` token and the sequence cannot be escaped in\n// HTML. The correct fix is to escape `<` in CSS using its CSS unicode escape\n// `\\3C ` (trailing space terminates the escape sequence). This produces valid\n// CSS that the browser parses correctly, but breaks the HTML tokenizer's\n// `</style` match. The backslash itself is safe because CSS ignores unknown\n// escape sequences.\nfunction escapeCss(css: string): string {\n return css.replace(/<\\/style/gi, '\\\\3C /style');\n}\n\n// Escape a string for safe interpolation into an HTML double-quoted attribute\n// value (e.g. lang=\"…\", id=\"…\", nonce=\"…\"). Encodes the four characters that\n// can break out of an attribute or inject new attributes.\nfunction escapeAttr(value: string): string {\n return value.replace(/&/g, '&amp;').replace(/\"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');\n}\n\n// Escape a string for safe interpolation into HTML text content (e.g. <title>).\n// Encodes & and < to prevent tag/entity injection; > is included for symmetry.\nfunction escapeText(value: string): string {\n return value.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');\n}\n\n// ---------------------------------------------------------------------------\n// CSP builder\n// ---------------------------------------------------------------------------\n\n// Characters illegal inside CSP source-list tokens (origins and nonces alike) that\n// would allow directive injection or HTML attribute breakout. Specifically:\n// ';' — CSP directive separator (would inject a new directive)\n// '\"' / \"'\" — breaks out of the HTML content=\"...\" / nonce=\"...\" attribute\n// '\\n' / '\\r' — CSP header line folding / response-splitting\nconst CSP_UNSAFE_CHARS = /['\";\\n\\r]/g;\n\n// Origins must be scheme+host(+port) form; none of CSP_UNSAFE_CHARS belong there.\nfunction sanitizeCspOrigin(origin: string): string {\n return origin.replace(CSP_UNSAFE_CHARS, '');\n}\n\n// Sanitize a nonce for CSP-token embedding — CSP nonces must be base64\n// characters only; stripping quotes/semicolons/newlines prevents early token\n// termination inside 'nonce-{value}'. buildCsp() and buildDocument() MUST both\n// derive their nonce from this exact function: the CSP header's nonce token and\n// the bridge <script nonce=\"...\"> attribute have to match byte-for-byte, or the\n// browser silently rejects the script — breaking the bridge (and CSP nonce\n// matching is stricter than HTML-attribute escaping, so applying escapeAttr()\n// to the raw, unsanitized nonce for the attribute while sanitizing separately\n// for the CSP token can produce two different strings).\nfunction sanitizeNonce(nonce: string): string {\n return nonce.replace(CSP_UNSAFE_CHARS, '');\n}\n\n/**\n * Builds a strict Content-Security-Policy string for sandboxed iframe documents.\n *\n * Accepts SandboxOptions directly — origins from `scripts` URLs are extracted and\n * merged with `allowedScriptOrigins` automatically.\n */\nexport function buildCsp(options: SandboxOptions = {}): string {\n const safeNonce = options.nonce ? sanitizeNonce(options.nonce) : null;\n\n const scriptOrigins = [\n \"'unsafe-inline'\",\n ...(safeNonce ? [`'nonce-${safeNonce}'`] : []),\n ...(options.allowedScriptOrigins ?? []).map(sanitizeCspOrigin),\n ...(options.scripts ?? []).map(extractOrigin).filter((o): o is string => o !== null),\n ].join(' ');\n\n const styleOrigins = [\"'unsafe-inline'\", ...(options.allowedStyleOrigins ?? []).map(sanitizeCspOrigin)].join(' ');\n const imgOrigins = ['data:', ...(options.allowedImageOrigins ?? []).map(sanitizeCspOrigin)].join(' ');\n const fontOrigins = (options.allowedFontOrigins ?? []).map(sanitizeCspOrigin).join(' ') || \"'none'\";\n\n return [\n \"default-src 'none'\",\n `script-src ${scriptOrigins}`,\n `style-src ${styleOrigins}`,\n `img-src ${imgOrigins}`,\n `font-src ${fontOrigins}`,\n \"connect-src 'none'\",\n \"form-action 'none'\",\n \"base-uri 'none'\",\n ].join('; ');\n}\n\n// ---------------------------------------------------------------------------\n// Document builder\n// ---------------------------------------------------------------------------\n\n// Bridge script embedded in every sandbox document.\n//\n// Plain JS — cannot import TypeScript modules. Message type strings must\n// match the MSG_* constants above.\n//\n// Auto-resize: ResizeObserver on document.body emits 'resize' messages\n// automatically — consumers don't need to wire ResizeObserver in their\n// sandbox content. The observer is set up AFTER the 'ready' postMessage so\n// that the first resize callback (which fires synchronously on observe()) does\n// not arrive at the host before bridgeReady is set.\n//\n// style-patch is scoped to <style> elements (tagName guard) to prevent\n// accidental content injection into non-style elements with a matching id.\nconst BRIDGE_SCRIPT = `\nif ('ontouchstart' in window) document.addEventListener('touchstart', function() {}, { passive: true });\nwindow.addEventListener('message', function(e) {\n var msg = e.data;\n if (msg && msg.type === 'state-update') {\n document.dispatchEvent(new CustomEvent('sandbox:state-update', { detail: { key: msg.key, value: msg.value } }));\n }\n if (msg && msg.type === 'state-update-all' && msg.record && typeof msg.record === 'object') {\n var keys = Object.keys(msg.record);\n for (var i = 0; i < keys.length; i++) {\n var k = keys[i];\n document.dispatchEvent(new CustomEvent('sandbox:state-update', { detail: { key: k, value: msg.record[k] } }));\n }\n }\n if (msg && msg.type === 'style-patch' && msg.id && typeof msg.css === 'string') {\n var el = document.getElementById(msg.id);\n if (el && el.tagName === 'STYLE') el.textContent = msg.css;\n }\n if (msg && msg.type === 'html-patch' && typeof msg.html === 'string') {\n document.body.innerHTML = msg.html;\n }\n});\n// post() tags every outgoing message with window.__sandboxGeneration (set by render(),\n// see below) and always targets '*' — srcdoc iframes have origin 'null' so no specific\n// origin can be addressed. The host uses the generation tag to ignore messages from a\n// document a newer render() has already superseded.\nfunction post(msg) {\n msg.generation = window.__sandboxGeneration;\n parent.postMessage(msg, '*');\n}\nwindow.onerror = function(message, _src, _line, _col, err) {\n post({ type: 'error', message: String(message), stack: err && err.stack });\n return true;\n};\nwindow.addEventListener('unhandledrejection', function(e) {\n var reason = e.reason;\n post({ type: 'error', message: String(reason), stack: reason && reason.stack });\n});\nwindow.__sandbox__ = {\n emit: function(event, detail) {\n post({ type: 'custom', event: event, detail: detail });\n },\n onState: function(key, handler) {\n function listener(e) {\n if (e.detail && e.detail.key === key) handler(e.detail.value);\n }\n document.addEventListener('sandbox:state-update', listener);\n return function() {\n document.removeEventListener('sandbox:state-update', listener);\n };\n }\n};\npost({ type: 'ready' });\nif (typeof ResizeObserver !== 'undefined') {\n new ResizeObserver(function(entries) {\n var entry = entries[0];\n if (!entry) return;\n var h = entry.borderBoxSize && entry.borderBoxSize[0]\n ? entry.borderBoxSize[0].blockSize\n : entry.contentRect.height;\n post({ type: 'resize', height: h });\n }).observe(document.body);\n}\n`.trim();\n\n/**\n * Builds a complete, standalone sandbox HTML document.\n *\n * `namedStyles` entries are rendered as `<style id=\"key\">` elements in the\n * document `<head>`. External scripts carry `crossorigin=\"anonymous\"` so the\n * bridge's error handler receives full error details for cross-origin scripts.\n * The bridge script auto-emits `resize` messages via `ResizeObserver`.\n */\nexport function buildDocument(html: string, options: SandboxOptions = {}): string {\n // escapeAttr is applied to the whole CSP string when embedding it in content=\"...\"\n // because buildCsp() does not know the embedding context. Any user-supplied origin\n // values that survived sanitizeCspOrigin() but still contain & or < (very unusual)\n // would otherwise break the HTML attribute.\n const csp = escapeAttr(buildCsp(options));\n const named = options.namedStyles ?? {};\n const lang = escapeAttr(options.lang ?? 'en');\n const title = escapeText(options.title ?? '');\n\n const styleTags = Object.entries(named)\n .map(([id, css]) => `<style id=\"${escapeAttr(id)}\">${escapeCss(css)}</style>`)\n .join('\\n');\n\n const scriptTags = (options.scripts ?? [])\n .map((src) => `<script crossorigin=\"anonymous\" src=\"${escapeAttr(src)}\"></script>`)\n .join('\\n');\n\n // Must sanitize with the exact same sanitizeNonce() used by buildCsp() — see its\n // comment. escapeAttr() alone is not enough: it HTML-encodes but does not strip,\n // so a raw nonce containing e.g. ';' would attribute-escape differently than the\n // CSP token strips it, producing a mismatched nonce and a silently broken bridge.\n const nonceAttr = options.nonce ? ` nonce=\"${escapeAttr(sanitizeNonce(options.nonce))}\"` : '';\n\n return `<!doctype html>\n<html lang=\"${lang}\">\n<head>\n<meta http-equiv=\"Content-Security-Policy\" content=\"${csp}\">\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<title>${title}</title>\n${styleTags}\n</head>\n<body>\n${scriptTags}\n${html}\n<script${nonceAttr}>\n${BRIDGE_SCRIPT}\n</script>\n</body>\n</html>`;\n}\n\n// ---------------------------------------------------------------------------\n// Sandbox factory\n// ---------------------------------------------------------------------------\n\n// Dev-only timeout: if the bridge never fires 'ready' after a render(), warn\n// so the developer knows the bridge script is missing or broken.\nconst READY_TIMEOUT_MS = 5000;\n\nexport function createSandbox(container: HTMLElement, options: SandboxOptions = {}): SandboxHandle {\n // Iframe is created lazily on the first render() call — no DOM work until\n // there is content to show.\n let iframe: HTMLIFrameElement | null = null;\n const listeners = new Set<(msg: SandboxMessage) => void>();\n let disposed = false;\n const ac = new AbortController();\n\n // Mutable namedStyles baseline — updateStyle() patches this so re-renders\n // automatically use the latest CSS without the caller re-passing options.\n const namedStyles: Record<string, string> = { ...(options.namedStyles ?? {}) };\n\n // bridgeReady: true once the bridge inside the current document has fired MSG_READY.\n // Reset to false on each render() so setState/updateStyle guards work correctly.\n let bridgeReady = false;\n\n // Monotonic counter embedded into each srcdoc as window.__sandboxGeneration (see\n // render()). iframe.contentWindow's identity is stable across srcdoc navigations in\n // real browsers, so event.source alone cannot distinguish a superseded document's\n // messages from the current one — the generation tag closes that gap.\n let renderGeneration = 0;\n\n // First-render gate — resolves on first ready signal or on dispose().\n // Always resolves (never rejects) so callers can safely fire-and-forget it.\n // Check sandbox.disposed afterward to distinguish a dispose-resolution.\n let resolveReady!: () => void;\n const ready = new Promise<void>((resolve) => {\n resolveReady = resolve;\n });\n\n // Per-render settlers — replaced on each render(), resolved on the next 'ready'\n // message or when superseded/disposed (not an error — the document navigated away\n // or the sandbox was torn down intentionally), rejected only by the ready-timeout.\n let currentRenderSettlers: { reject: (err: unknown) => void; resolve: () => void } | null = null;\n let readyTimeoutId: ReturnType<typeof setTimeout> | null = null;\n\n function clearReadyTimeout(): void {\n if (readyTimeoutId !== null) {\n clearTimeout(readyTimeoutId);\n readyTimeoutId = null;\n }\n }\n\n // Supersede the in-flight render: resolve (not reject) its promise, clear the\n // timeout, and reset bridgeReady. All three must change together — keep them here.\n function supersedePendingRender(): void {\n clearReadyTimeout();\n currentRenderSettlers?.resolve();\n currentRenderSettlers = null;\n bridgeReady = false;\n }\n\n // Dispatch table for incoming sandbox→host messages.\n // Adding a new message type means adding one entry here — no separate allowlist.\n // Each handler constructs a typed SandboxMessage rather than casting, so the\n // compiler verifies the shape and malformed payloads are silently dropped.\n const msgHandlers: Record<string, (msg: Record<string, unknown>) => void> = {\n [MSG_CUSTOM]: (msg) => {\n if (typeof msg.event === 'string') {\n broadcast({ detail: msg.detail, event: msg.event, type: MSG_CUSTOM });\n }\n },\n [MSG_ERROR]: (msg) => {\n if (typeof msg.message === 'string') {\n broadcast({\n message: msg.message,\n ...(typeof msg.stack === 'string' ? { stack: msg.stack } : {}),\n type: MSG_ERROR,\n });\n }\n },\n [MSG_READY]: () => {\n // supersedePendingRender clears the timeout and resolves the render promise.\n // bridgeReady is re-set to true immediately after because the bridge IS ready.\n supersedePendingRender();\n resolveReady();\n bridgeReady = true;\n },\n [MSG_RESIZE]: (msg) => {\n if (typeof msg.height === 'number') broadcast({ height: msg.height, type: MSG_RESIZE });\n },\n };\n\n function broadcast(msg: SandboxMessage): void {\n for (const listener of listeners) listener(msg);\n }\n\n function handleMessage(event: MessageEvent): void {\n if (!iframe || event.source !== iframe.contentWindow) return;\n\n if (!isMsgObject(event.data)) return;\n\n // Reject messages tagged with a superseded generation — a document torn down by a\n // newer render() may still have a message in flight. Messages with no generation\n // (or a non-number one, e.g. from testing helpers) are trusted and pass through.\n const generation = event.data.generation;\n\n if (typeof generation === 'number' && generation !== renderGeneration) return;\n\n // Guard against prototype-inherited properties on msgHandlers (e.g. '__proto__',\n // '__defineGetter__') — these are not functions and calling them via ?.() throws.\n // Object.hasOwn ensures only keys explicitly defined in the dispatch table are invoked.\n if (Object.hasOwn(msgHandlers, event.data.type)) {\n msgHandlers[event.data.type]!(event.data);\n }\n }\n\n function ensureIframe(): HTMLIFrameElement {\n if (iframe) return iframe;\n\n iframe = document.createElement('iframe');\n iframe.setAttribute('sandbox', 'allow-scripts');\n iframe.setAttribute('referrerpolicy', 'no-referrer');\n container.appendChild(iframe);\n window.addEventListener('message', handleMessage);\n\n return iframe;\n }\n\n function dispose(): void {\n if (disposed) return;\n\n disposed = true;\n supersedePendingRender();\n ac.abort();\n resolveReady();\n\n if (iframe) {\n window.removeEventListener('message', handleMessage);\n iframe.remove();\n iframe = null;\n }\n\n listeners.clear();\n }\n\n function onMessage(handler: (msg: SandboxMessage) => void): Unsubscribe {\n if (disposed) {\n warn('onMessage() called on a disposed sandbox — handler will never fire.');\n\n return () => {};\n }\n\n listeners.add(handler);\n\n return () => {\n listeners.delete(handler);\n };\n }\n\n function render(html: string, renderOptions?: { signal?: AbortSignal }): Promise<void> {\n if (disposed) {\n warn('render() called on a disposed sandbox.');\n\n return Promise.resolve();\n }\n\n if (renderOptions?.signal?.aborted) return Promise.resolve();\n\n if (!html.trim()) {\n warn('render() called with empty HTML.');\n }\n\n // Supersede any in-flight render — its document navigated away.\n supersedePendingRender();\n\n const generation = ++renderGeneration;\n const docOptions = Object.keys(namedStyles).length > 0 ? { ...options, namedStyles: { ...namedStyles } } : options;\n\n // Inject the generation marker into <head> — it always appears before any user\n // content in the template, so this replace can never hit HTML inside `html`.\n const doc = buildDocument(html, docOptions).replace(\n '<head>',\n `<head>\\n<script>window.__sandboxGeneration=${generation};</script>`,\n );\n\n ensureIframe().srcdoc = doc;\n\n const p = new Promise<void>((resolve, reject) => {\n currentRenderSettlers = { reject, resolve };\n });\n\n // If the bridge never fires 'ready', reject with SandboxTimeoutError so the\n // document-missing-bridge-script failure is catchable rather than hanging forever.\n readyTimeoutId = setTimeout(() => {\n if (currentRenderSettlers) {\n currentRenderSettlers.reject(\n new SandboxTimeoutError(\n `render() did not receive a 'ready' signal from the sandbox document within ${READY_TIMEOUT_MS}ms. ` +\n 'The document is likely missing the bridge script — use buildDocument() to generate documents that include it.',\n ),\n );\n currentRenderSettlers = null;\n readyTimeoutId = null;\n }\n }, READY_TIMEOUT_MS);\n\n return p;\n }\n\n function patch(html: string): void {\n if (disposed) {\n warn('patch() called on a disposed sandbox.');\n\n return;\n }\n\n if (!bridgeReady || !iframe?.contentWindow) {\n warn(\n 'patch() called before render() has resolved — bridge is not yet initialized. Await the Promise returned by render() first.',\n );\n\n return;\n }\n\n // srcdoc iframes have origin 'null' — '*' is required because no specific origin can be targeted.\n iframe.contentWindow.postMessage({ html, type: MSG_HTML_PATCH }, '*');\n }\n\n function setState(key: string, value: unknown): void {\n if (disposed) {\n warn('setState() called on a disposed sandbox.');\n\n return;\n }\n\n if (!iframe?.contentWindow) {\n warn('setState() called before render() — sandbox has no document yet.');\n\n return;\n }\n\n if (!bridgeReady) {\n warn(\n 'setState() called before ready — state update may be lost if bridge is not yet initialized. Await the Promise returned by render() first.',\n );\n }\n\n // srcdoc iframes have origin 'null' — '*' is required because no specific origin can be targeted.\n iframe.contentWindow.postMessage({ key, type: MSG_STATE_UPDATE, value }, '*');\n }\n\n function setStateAll(record: Record<string, unknown>): void {\n if (disposed) {\n warn('setStateAll() called on a disposed sandbox.');\n\n return;\n }\n\n if (!iframe?.contentWindow) {\n warn('setStateAll() called before render() — sandbox has no document yet.');\n\n return;\n }\n\n if (!bridgeReady) {\n warn(\n 'setStateAll() called before ready — state updates may be lost. Await the Promise returned by render() first.',\n );\n }\n\n // srcdoc iframes have origin 'null' — '*' is required because no specific origin can be targeted.\n iframe.contentWindow.postMessage({ record, type: MSG_STATE_UPDATE_ALL }, '*');\n }\n\n function updateStyle(id: string, css: string): void {\n if (disposed) return;\n\n devOnly(() => {\n if (!(id in namedStyles)) {\n warn(\n `updateStyle('${id}', …) — '${id}' is not a known namedStyles key. ` +\n 'The live patch will have no effect. Pass the id as a key in namedStyles when calling createSandbox().',\n );\n }\n });\n\n namedStyles[id] = css;\n\n if (bridgeReady && iframe?.contentWindow) {\n // srcdoc iframes have origin 'null' — '*' is required because no specific origin can be targeted.\n iframe.contentWindow.postMessage({ css, id, type: MSG_STYLE_PATCH }, '*');\n }\n }\n\n return {\n get disposalSignal() {\n return ac.signal;\n },\n dispose,\n get disposed() {\n return disposed;\n },\n onMessage,\n patch,\n ready,\n render,\n setState,\n setStateAll,\n [Symbol.dispose]() {\n dispose();\n },\n updateStyle,\n };\n}\n"],"mappings":"sDAyBA,IAAM,EAAY,QACZ,EAAmB,eACnB,EAAuB,mBACvB,EAAkB,cAClB,EAAiB,aACjB,EAAY,QACZ,EAAa,SACb,EAAa,SAMnB,SAAS,EAAY,EAAmE,CACtF,OAAO,OAAO,GAAS,YAAY,GAAiB,OAAQ,EAA4B,MAAS,QACnG,CAEA,SAAS,EAAc,EAA4B,CACjD,GAAI,CACF,IAAM,EAAI,IAAI,IAAI,CAAG,CAAC,CAAC,OAEvB,OAAO,IAAM,OAAa,KAAJ,CACxB,MAAQ,CACN,OAAO,IACT,CACF,CASA,SAAS,EAAU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AG,MACZ,EACA,UACA,IAAI,UAAW,CACb,OAAO,CACT,EACA,YACA,QACA,QACA,SACA,WACA,cACA,CAAC,OAAO,UAAW,CACjB,EAAQ,CACV,EACA,aACF,CACF"}
package/dist/_sandbox.js CHANGED
@@ -1,11 +1,11 @@
1
- import { devOnly as e, warn as t } from "./_dev.js";
2
- import { SandboxTimeoutError as n } from "./errors.js";
1
+ import "./_dev.js";
2
+ import { SandboxTimeoutError as e } from "./errors.js";
3
3
  //#region src/_sandbox.ts
4
- var r = "ready", i = "state-update", a = "state-update-all", o = "style-patch", s = "html-patch", c = "error", l = "custom", u = "resize";
5
- function d(e) {
4
+ var t = "ready", n = "state-update", r = "state-update-all", i = "style-patch", a = "html-patch", o = "error", s = "custom", c = "resize";
5
+ function l(e) {
6
6
  return typeof e == "object" && !!e && typeof e.type == "string";
7
7
  }
8
- function f(e) {
8
+ function u(e) {
9
9
  try {
10
10
  let t = new URL(e).origin;
11
11
  return t === "null" ? null : t;
@@ -13,29 +13,29 @@ function f(e) {
13
13
  return null;
14
14
  }
15
15
  }
16
- function p(e) {
16
+ function d(e) {
17
17
  return e.replace(/<\/style/gi, "\\3C /style");
18
18
  }
19
- function m(e) {
19
+ function f(e) {
20
20
  return e.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
21
21
  }
22
- function h(e) {
22
+ function p(e) {
23
23
  return e.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
24
24
  }
25
- var g = /['";\n\r]/g;
26
- function _(e) {
27
- return e.replace(g, "");
25
+ var m = /['";\n\r]/g;
26
+ function h(e) {
27
+ return e.replace(m, "");
28
28
  }
29
- function v(e) {
30
- return e.replace(g, "");
29
+ function g(e) {
30
+ return e.replace(m, "");
31
31
  }
32
- function y(e = {}) {
33
- let t = e.nonce ? v(e.nonce) : null, n = [
32
+ function _(e = {}) {
33
+ let t = e.nonce ? g(e.nonce) : null, n = [
34
34
  "'unsafe-inline'",
35
35
  ...t ? [`'nonce-${t}'`] : [],
36
- ...(e.allowedScriptOrigins ?? []).map(_),
37
- ...(e.scripts ?? []).map(f).filter((e) => e !== null)
38
- ].join(" "), r = ["'unsafe-inline'", ...(e.allowedStyleOrigins ?? []).map(_)].join(" "), i = ["data:", ...(e.allowedImageOrigins ?? []).map(_)].join(" "), a = (e.allowedFontOrigins ?? []).map(_).join(" ") || "'none'";
36
+ ...(e.allowedScriptOrigins ?? []).map(h),
37
+ ...(e.scripts ?? []).map(u).filter((e) => e !== null)
38
+ ].join(" "), r = ["'unsafe-inline'", ...(e.allowedStyleOrigins ?? []).map(h)].join(" "), i = ["data:", ...(e.allowedImageOrigins ?? []).map(h)].join(" "), a = (e.allowedFontOrigins ?? []).map(h).join(" ") || "'none'";
39
39
  return [
40
40
  "default-src 'none'",
41
41
  `script-src ${n}`,
@@ -47,174 +47,147 @@ function y(e = {}) {
47
47
  "base-uri 'none'"
48
48
  ].join("; ");
49
49
  }
50
- var b = "if ('ontouchstart' in window) document.addEventListener('touchstart', function() {}, { passive: true });\nwindow.addEventListener('message', function(e) {\n var msg = e.data;\n if (msg && msg.type === 'state-update') {\n document.dispatchEvent(new CustomEvent('sandbox:state-update', { detail: { key: msg.key, value: msg.value } }));\n }\n if (msg && msg.type === 'state-update-all' && msg.record && typeof msg.record === 'object') {\n var keys = Object.keys(msg.record);\n for (var i = 0; i < keys.length; i++) {\n var k = keys[i];\n document.dispatchEvent(new CustomEvent('sandbox:state-update', { detail: { key: k, value: msg.record[k] } }));\n }\n }\n if (msg && msg.type === 'style-patch' && msg.id && typeof msg.css === 'string') {\n var el = document.getElementById(msg.id);\n if (el && el.tagName === 'STYLE') el.textContent = msg.css;\n }\n if (msg && msg.type === 'html-patch' && typeof msg.html === 'string') {\n document.body.innerHTML = msg.html;\n }\n});\n// post() tags every outgoing message with window.__sandboxGeneration (set by render(),\n// see below) and always targets '*' — srcdoc iframes have origin 'null' so no specific\n// origin can be addressed. The host uses the generation tag to ignore messages from a\n// document a newer render() has already superseded.\nfunction post(msg) {\n msg.generation = window.__sandboxGeneration;\n parent.postMessage(msg, '*');\n}\nwindow.onerror = function(message, _src, _line, _col, err) {\n post({ type: 'error', message: String(message), stack: err && err.stack });\n return true;\n};\nwindow.addEventListener('unhandledrejection', function(e) {\n var reason = e.reason;\n post({ type: 'error', message: String(reason), stack: reason && reason.stack });\n});\nwindow.__sandbox__ = {\n emit: function(event, detail) {\n post({ type: 'custom', event: event, detail: detail });\n },\n onState: function(key, handler) {\n function listener(e) {\n if (e.detail && e.detail.key === key) handler(e.detail.value);\n }\n document.addEventListener('sandbox:state-update', listener);\n return function() {\n document.removeEventListener('sandbox:state-update', listener);\n };\n }\n};\npost({ type: 'ready' });\nif (typeof ResizeObserver !== 'undefined') {\n new ResizeObserver(function(entries) {\n var entry = entries[0];\n if (!entry) return;\n var h = entry.borderBoxSize && entry.borderBoxSize[0]\n ? entry.borderBoxSize[0].blockSize\n : entry.contentRect.height;\n post({ type: 'resize', height: h });\n }).observe(document.body);\n}";
51
- function x(e, t = {}) {
52
- let n = m(y(t)), r = t.namedStyles ?? {};
50
+ var v = "if ('ontouchstart' in window) document.addEventListener('touchstart', function() {}, { passive: true });\nwindow.addEventListener('message', function(e) {\n var msg = e.data;\n if (msg && msg.type === 'state-update') {\n document.dispatchEvent(new CustomEvent('sandbox:state-update', { detail: { key: msg.key, value: msg.value } }));\n }\n if (msg && msg.type === 'state-update-all' && msg.record && typeof msg.record === 'object') {\n var keys = Object.keys(msg.record);\n for (var i = 0; i < keys.length; i++) {\n var k = keys[i];\n document.dispatchEvent(new CustomEvent('sandbox:state-update', { detail: { key: k, value: msg.record[k] } }));\n }\n }\n if (msg && msg.type === 'style-patch' && msg.id && typeof msg.css === 'string') {\n var el = document.getElementById(msg.id);\n if (el && el.tagName === 'STYLE') el.textContent = msg.css;\n }\n if (msg && msg.type === 'html-patch' && typeof msg.html === 'string') {\n document.body.innerHTML = msg.html;\n }\n});\n// post() tags every outgoing message with window.__sandboxGeneration (set by render(),\n// see below) and always targets '*' — srcdoc iframes have origin 'null' so no specific\n// origin can be addressed. The host uses the generation tag to ignore messages from a\n// document a newer render() has already superseded.\nfunction post(msg) {\n msg.generation = window.__sandboxGeneration;\n parent.postMessage(msg, '*');\n}\nwindow.onerror = function(message, _src, _line, _col, err) {\n post({ type: 'error', message: String(message), stack: err && err.stack });\n return true;\n};\nwindow.addEventListener('unhandledrejection', function(e) {\n var reason = e.reason;\n post({ type: 'error', message: String(reason), stack: reason && reason.stack });\n});\nwindow.__sandbox__ = {\n emit: function(event, detail) {\n post({ type: 'custom', event: event, detail: detail });\n },\n onState: function(key, handler) {\n function listener(e) {\n if (e.detail && e.detail.key === key) handler(e.detail.value);\n }\n document.addEventListener('sandbox:state-update', listener);\n return function() {\n document.removeEventListener('sandbox:state-update', listener);\n };\n }\n};\npost({ type: 'ready' });\nif (typeof ResizeObserver !== 'undefined') {\n new ResizeObserver(function(entries) {\n var entry = entries[0];\n if (!entry) return;\n var h = entry.borderBoxSize && entry.borderBoxSize[0]\n ? entry.borderBoxSize[0].blockSize\n : entry.contentRect.height;\n post({ type: 'resize', height: h });\n }).observe(document.body);\n}";
51
+ function y(e, t = {}) {
52
+ let n = f(_(t)), r = t.namedStyles ?? {};
53
53
  return `<!doctype html>
54
- <html lang="${m(t.lang ?? "en")}">
54
+ <html lang="${f(t.lang ?? "en")}">
55
55
  <head>
56
56
  <meta http-equiv="Content-Security-Policy" content="${n}">
57
57
  <meta charset="utf-8">
58
58
  <meta name="viewport" content="width=device-width, initial-scale=1">
59
- <title>${h(t.title ?? "")}</title>
60
- ${Object.entries(r).map(([e, t]) => `<style id="${m(e)}">${p(t)}</style>`).join("\n")}
59
+ <title>${p(t.title ?? "")}</title>
60
+ ${Object.entries(r).map(([e, t]) => `<style id="${f(e)}">${d(t)}</style>`).join("\n")}
61
61
  </head>
62
62
  <body>
63
- ${(t.scripts ?? []).map((e) => `<script crossorigin="anonymous" src="${m(e)}"><\/script>`).join("\n")}
63
+ ${(t.scripts ?? []).map((e) => `<script crossorigin="anonymous" src="${f(e)}"><\/script>`).join("\n")}
64
64
  ${e}
65
- <script${t.nonce ? ` nonce="${m(v(t.nonce))}"` : ""}>
66
- ${b}
65
+ <script${t.nonce ? ` nonce="${f(g(t.nonce))}"` : ""}>
66
+ ${v}
67
67
  <\/script>
68
68
  </body>
69
69
  </html>`;
70
70
  }
71
- var S = 5e3;
72
- function C(f, p = {}) {
73
- let m = null, h = /* @__PURE__ */ new Set(), g = !1, _ = new AbortController(), v = { ...p.namedStyles ?? {} }, y = !1, b = 0, C, w = new Promise((e) => {
74
- C = e;
75
- }), T = null, E = null;
76
- function D() {
77
- E !== null && (clearTimeout(E), E = null);
71
+ var b = 5e3;
72
+ function x(u, d = {}) {
73
+ let f = null, p = /* @__PURE__ */ new Set(), m = !1, h = new AbortController(), g = { ...d.namedStyles ?? {} }, _ = !1, v = 0, x, S = new Promise((e) => {
74
+ x = e;
75
+ }), C = null, w = null;
76
+ function T() {
77
+ w !== null && (clearTimeout(w), w = null);
78
78
  }
79
- function O() {
80
- D(), T?.resolve(), T = null, y = !1;
79
+ function E() {
80
+ T(), C?.resolve(), C = null, _ = !1;
81
81
  }
82
- let k = {
83
- [l]: (e) => {
84
- typeof e.event == "string" && A({
82
+ let D = {
83
+ [s]: (e) => {
84
+ typeof e.event == "string" && O({
85
85
  detail: e.detail,
86
86
  event: e.event,
87
- type: l
87
+ type: s
88
88
  });
89
89
  },
90
- [c]: (e) => {
91
- typeof e.message == "string" && A({
90
+ [o]: (e) => {
91
+ typeof e.message == "string" && O({
92
92
  message: e.message,
93
93
  ...typeof e.stack == "string" ? { stack: e.stack } : {},
94
- type: c
94
+ type: o
95
95
  });
96
96
  },
97
- [r]: () => {
98
- O(), C(), y = !0;
97
+ [t]: () => {
98
+ E(), x(), _ = !0;
99
99
  },
100
- [u]: (e) => {
101
- typeof e.height == "number" && A({
100
+ [c]: (e) => {
101
+ typeof e.height == "number" && O({
102
102
  height: e.height,
103
- type: u
103
+ type: c
104
104
  });
105
105
  }
106
106
  };
107
- function A(e) {
108
- for (let t of h) t(e);
107
+ function O(e) {
108
+ for (let t of p) t(e);
109
109
  }
110
- function j(e) {
111
- if (!m || e.source !== m.contentWindow || !d(e.data)) return;
110
+ function k(e) {
111
+ if (!f || e.source !== f.contentWindow || !l(e.data)) return;
112
112
  let t = e.data.generation;
113
- typeof t == "number" && t !== b || Object.hasOwn(k, e.data.type) && k[e.data.type](e.data);
113
+ (typeof t != "number" || t === v) && Object.hasOwn(D, e.data.type) && D[e.data.type](e.data);
114
114
  }
115
- function M() {
116
- return m || (m = document.createElement("iframe"), m.setAttribute("sandbox", "allow-scripts"), m.setAttribute("referrerpolicy", "no-referrer"), f.appendChild(m), window.addEventListener("message", j), m);
115
+ function A() {
116
+ return f || (f = document.createElement("iframe"), f.setAttribute("sandbox", "allow-scripts"), f.setAttribute("referrerpolicy", "no-referrer"), u.appendChild(f), window.addEventListener("message", k), f);
117
117
  }
118
- function N() {
119
- g || (g = !0, O(), _.abort(), C(), m &&= (window.removeEventListener("message", j), m.remove(), null), h.clear());
118
+ function j() {
119
+ m || (m = !0, E(), h.abort(), x(), f &&= (window.removeEventListener("message", k), f.remove(), null), p.clear());
120
120
  }
121
- function P(e) {
122
- return g ? (t("onMessage() called on a disposed sandbox — handler will never fire."), () => {}) : (h.add(e), () => {
123
- h.delete(e);
121
+ function M(e) {
122
+ return m ? () => {} : (p.add(e), () => {
123
+ p.delete(e);
124
124
  });
125
125
  }
126
- function F(e, r) {
127
- if (g) return t("render() called on a disposed sandbox."), Promise.resolve();
128
- if (r?.signal?.aborted) return Promise.resolve();
129
- e.trim() || t("render() called with empty HTML."), O();
130
- let i = ++b, a = x(e, Object.keys(v).length > 0 ? {
131
- ...p,
132
- namedStyles: { ...v }
133
- } : p).replace("<head>", `<head>\n<script>window.__sandboxGeneration=${i};<\/script>`);
134
- M().srcdoc = a;
135
- let o = new Promise((e, t) => {
136
- T = {
126
+ function N(t, n) {
127
+ if (m || n?.signal?.aborted) return Promise.resolve();
128
+ t.trim(), E();
129
+ let r = ++v, i = y(t, Object.keys(g).length > 0 ? {
130
+ ...d,
131
+ namedStyles: { ...g }
132
+ } : d).replace("<head>", `<head>\n<script>window.__sandboxGeneration=${r};<\/script>`);
133
+ A().srcdoc = i;
134
+ let a = new Promise((e, t) => {
135
+ C = {
137
136
  reject: t,
138
137
  resolve: e
139
138
  };
140
139
  });
141
- return E = setTimeout(() => {
142
- T && (T.reject(new n(`render() did not receive a 'ready' signal from the sandbox document within ${S}ms. The document is likely missing the bridge script — use buildDocument() to generate documents that include it.`)), T = null, E = null);
143
- }, S), o;
140
+ return w = setTimeout(() => {
141
+ C && (C.reject(new e(`render() did not receive a 'ready' signal from the sandbox document within ${b}ms. The document is likely missing the bridge script — use buildDocument() to generate documents that include it.`)), C = null, w = null);
142
+ }, b), a;
144
143
  }
145
- function I(e) {
146
- if (g) {
147
- t("patch() called on a disposed sandbox.");
148
- return;
149
- }
150
- if (!y || !m?.contentWindow) {
151
- t("patch() called before render() has resolved — bridge is not yet initialized. Await the Promise returned by render() first.");
152
- return;
153
- }
154
- m.contentWindow.postMessage({
144
+ function P(e) {
145
+ m || !_ || !f?.contentWindow || f.contentWindow.postMessage({
155
146
  html: e,
156
- type: s
147
+ type: a
157
148
  }, "*");
158
149
  }
159
- function L(e, n) {
160
- if (g) {
161
- t("setState() called on a disposed sandbox.");
162
- return;
163
- }
164
- if (!m?.contentWindow) {
165
- t("setState() called before render() — sandbox has no document yet.");
166
- return;
167
- }
168
- y || t("setState() called before ready — state update may be lost if bridge is not yet initialized. Await the Promise returned by render() first."), m.contentWindow.postMessage({
150
+ function F(e, t) {
151
+ m || f?.contentWindow && f.contentWindow.postMessage({
169
152
  key: e,
170
- type: i,
171
- value: n
153
+ type: n,
154
+ value: t
172
155
  }, "*");
173
156
  }
174
- function R(e) {
175
- if (g) {
176
- t("setStateAll() called on a disposed sandbox.");
177
- return;
178
- }
179
- if (!m?.contentWindow) {
180
- t("setStateAll() called before render() — sandbox has no document yet.");
181
- return;
182
- }
183
- y || t("setStateAll() called before ready — state updates may be lost. Await the Promise returned by render() first."), m.contentWindow.postMessage({
157
+ function I(e) {
158
+ m || f?.contentWindow && f.contentWindow.postMessage({
184
159
  record: e,
185
- type: a
160
+ type: r
186
161
  }, "*");
187
162
  }
188
- function z(n, r) {
189
- g || (e(() => {
190
- n in v || t(`updateStyle('${n}', …) — '${n}' is not a known namedStyles key. The live patch will have no effect. Pass the id as a key in namedStyles when calling createSandbox().`);
191
- }), v[n] = r, y && m?.contentWindow && m.contentWindow.postMessage({
192
- css: r,
193
- id: n,
194
- type: o
163
+ function L(e, t) {
164
+ m || (g[e] = t, _ && f?.contentWindow && f.contentWindow.postMessage({
165
+ css: t,
166
+ id: e,
167
+ type: i
195
168
  }, "*"));
196
169
  }
197
170
  return {
198
171
  get disposalSignal() {
199
- return _.signal;
172
+ return h.signal;
200
173
  },
201
- dispose: N,
174
+ dispose: j,
202
175
  get disposed() {
203
- return g;
176
+ return m;
204
177
  },
205
- onMessage: P,
206
- patch: I,
207
- ready: w,
208
- render: F,
209
- setState: L,
210
- setStateAll: R,
178
+ onMessage: M,
179
+ patch: P,
180
+ ready: S,
181
+ render: N,
182
+ setState: F,
183
+ setStateAll: I,
211
184
  [Symbol.dispose]() {
212
- N();
185
+ j();
213
186
  },
214
- updateStyle: z
187
+ updateStyle: L
215
188
  };
216
189
  }
217
190
  //#endregion
218
- export { y as buildCsp, x as buildDocument, C as createSandbox };
191
+ export { _ as buildCsp, y as buildDocument, x as createSandbox };
219
192
 
220
193
  //# sourceMappingURL=_sandbox.js.map