code-playpad 0.10.0 → 0.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +218 -17
- package/dist/THIRD-PARTY-NOTICES.txt +223 -0
- package/dist/cdn.js +2 -2
- package/dist/compiler-B408qd3N.js +151 -0
- package/dist/{config-CT3H6Oum.js → config-DB58UVsk.js} +1 -1
- package/dist/{cpp-CO2abWii.js → cpp-C77X5wRk.js} +1 -1
- package/dist/{cpp-Cs32J8JC.js → cpp-DuOQ_23Z.js} +1 -1
- package/dist/{dist-DXjodKfp.js → dist-B4dyQ4mN.js} +1 -1
- package/dist/{dist-BkpKCrXQ.js → dist-BFlbXnjn.js} +1 -1
- package/dist/dist-BoJapv5W.js +28 -0
- package/dist/dist-BqLa1O1y.js +6 -0
- package/dist/dist-CJRlQ049.js +6 -0
- package/dist/{dist-CJxiVI4a.js → dist-DBpvb9b1.js} +1 -1
- package/dist/{dist-BIgiGgKu.js → dist-DRocX-cv.js} +1 -1
- package/dist/dist-DfjaG4Ra.js +6 -0
- package/dist/{dist-D2igTc4m.js → dist-DviSDQoT.js} +1 -1
- package/dist/dist-F28mE6nM.js +8 -0
- package/dist/{dist-CNOK8CHE.js → dist-TxeNlzAy.js} +1 -1
- package/dist/dist-y6lcdYKh.js +14 -0
- package/dist/element-COcjM0hI.js +521 -0
- package/dist/element.d.ts +26 -0
- package/dist/element.js +1 -1
- package/dist/hints-DpBIeoeG.js +6 -0
- package/dist/index.d.ts +3 -3
- package/dist/index.js +1 -1
- package/dist/{java-DeBiVPXO.js → java-Df5HdXMz.js} +1 -1
- package/dist/{java-8qjVCjsN.js → java-DyH3mSiH.js} +1 -1
- package/dist/{javascript-DLPaJJzf.js → javascript-BtHVyxzg.js} +2 -2
- package/dist/{javascript-B1tVx7AD.js → javascript-CWolHiSP.js} +1 -1
- package/dist/languages.d.ts +1 -1
- package/dist/{pyodide-BOoYEfX1.js → pyodide-3MPS4ySA.js} +2 -2
- package/dist/{pyodide-C8ImkXdD.js → pyodide-EUDn__Gx.js} +1 -1
- package/dist/react-CL1KABFm.js +9 -0
- package/dist/react-Db_rGDYu.js +4 -0
- package/dist/react-runtime-19.2.8.js +240 -0
- package/dist/react-vendor.generated-DMxIoCMn.js +6 -0
- package/dist/react-version.generated-BNNJmf7J.js +6 -0
- package/dist/react.d.ts +5 -1
- package/dist/react.js +1 -1
- package/dist/runtime/config.d.ts +15 -1
- package/dist/runtime/react/boot.d.ts +9 -0
- package/dist/runtime/react/compiler.d.ts +30 -0
- package/dist/runtime/react-vendor.generated.d.ts +5 -0
- package/dist/runtime/react-version.generated.d.ts +3 -0
- package/dist/runtime/react.d.ts +2 -0
- package/dist/standalone.js +214 -17
- package/dist/{hints-CCMgezw9.js → types-CfcYqU2K.js} +1 -1
- package/dist/types.d.ts +23 -0
- package/dist/worker-runtime-DvpugeXD.js +9 -0
- package/dist/{worker-runtime-sUPz1J56.js → worker-runtime-PykJQLB7.js} +1 -1
- package/package.json +21 -6
- package/dist/dist--J_vhCIU.js +0 -14
- package/dist/dist-BNvM_BAY.js +0 -6
- package/dist/dist-D7jBL3Ib.js +0 -28
- package/dist/dist-DfFrsBkU.js +0 -8
- package/dist/element-CQGYVEF7.js +0 -324
- package/dist/worker-runtime-DfYet3xy.js +0 -9
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
* Bundles CodeMirror 6 and Lezer (MIT) © Marijn Haverbeke and others.
|
|
4
4
|
* Full third-party licences: THIRD-PARTY-NOTICES.txt in this package.
|
|
5
5
|
*/
|
|
6
|
-
import{
|
|
6
|
+
import{l as e}from"./config-DB58UVsk.js";import{t}from"./worker-runtime-DvpugeXD.js";var n=`let currentId=null,stdinLines=[],stdinExhausted=!1,nextRequest=1,inputWaitMs=0;const pendingLines=new Map;let sucrasePromise=null,sucraseURL=null;const pendingModules=new Map;class TransformLoadError extends Error{}function requestModule(t){return new Promise((e,r)=>{pendingModules.set(t,{resolve:e,reject:r}),post({type:"module-request",id:currentId,name:t})})}function post(t){self.postMessage(t)}let functionLineOffset=0;try{new Function('throw new Error("probe")')()}catch(t){const e=/<anonymous>:(\\d+):/.exec(t.stack||"");e&&(functionLineOffset=Number(e[1])-1)}let currentFiles=[];const FLUSH_BYTES=8192,FLUSH_MS=16,EAGER_POSTS=32;let outputQueue=[],queuedChars=0,windowStart=-1/0,windowPosts=0;function writeOutput(t,e){const r=outputQueue[outputQueue.length-1];r&&r.type===t?r.text+=e:outputQueue.push({type:t,text:e}),queuedChars+=e.length;const i=performance.now();i-windowStart>=FLUSH_MS&&(windowStart=i,windowPosts=0),(windowPosts<EAGER_POSTS||queuedChars>=FLUSH_BYTES)&&flushOutput()}function flushOutput(){if(!outputQueue.length)return;windowPosts++;const t=outputQueue;outputQueue=[],queuedChars=0;for(const e of t)post({type:e.type,id:currentId,text:e.text})}function format(t,e,r){if(e=e||new Set,typeof t=="string")return r?t:JSON.stringify(t);if(typeof t=="bigint")return String(t)+"n";if(typeof t=="function")return"[Function"+(t.name?": "+t.name:"")+"]";if(typeof t=="symbol"||t==null||typeof t!="object")return String(t);if(e.has(t))return"[Circular]";e.add(t);try{if(t instanceof Error)return t.stack||t.name+": "+t.message;if(Array.isArray(t))return"[ "+t.map(n=>format(n,e)).join(", ")+" ]";if(t instanceof Map)return"Map("+t.size+") { "+[...t].map(([n,o])=>format(n,e)+" => "+format(o,e)).join(", ")+" }";if(t instanceof Set)return"Set("+t.size+") { "+[...t].map(n=>format(n,e)).join(", ")+" }";if(t instanceof Date)return t.toISOString();if(t instanceof Promise)return"Promise { \\u2026 }";const i=Object.entries(t).map(([n,o])=>n+": "+format(o,e)),a=t.constructor&&t.constructor.name;return(a&&a!=="Object"?a+" ":"")+"{ "+i.join(", ")+" }"}finally{e.delete(t)}}function formatArgs(t){return t.map(e=>format(e,null,!0)).join(" ")+\`
|
|
7
7
|
\`}const nativeConsole=self.console;self.console=Object.assign(Object.create(nativeConsole),{log:(...t)=>writeOutput("stdout",formatArgs(t)),info:(...t)=>writeOutput("stdout",formatArgs(t)),debug:(...t)=>writeOutput("stdout",formatArgs(t)),warn:(...t)=>writeOutput("stderr",formatArgs(t)),error:(...t)=>writeOutput("stderr",formatArgs(t))}),self._ppReadLine=async()=>{if(stdinLines.length){const i=stdinLines.shift();return writeOutput("echo",i+\`
|
|
8
8
|
\`),i}const t=nextRequest++;flushOutput();const e=performance.now(),r=await new Promise(i=>{pendingLines.set(t,i),post({type:"stdin-request",id:currentId,request:t})});return inputWaitMs+=performance.now()-e,typeof r!="string"&&(stdinExhausted=!0),typeof r=="string"?r:null};async function input(t){t!==void 0&&writeOutput("stdout",String(t));const e=await self._ppReadLine();if(e===null)throw new Error("EOF: no more input");return e}self.input=input;async function loadSucrase(){return sucrasePromise||(sucrasePromise=(async()=>{try{if(sucraseURL)return await import(sucraseURL);const t=await requestModule("sucrase"),e=URL.createObjectURL(new Blob([t],{type:"text/javascript"}));try{return await import(e)}finally{URL.revokeObjectURL(e)}}catch(t){const e=sucraseURL?" from "+sucraseURL:"";throw new TransformLoadError("Could not load the TypeScript transform (Sucrase)"+e+": "+(t&&t.message?t.message:String(t)))}})(),sucrasePromise.catch(()=>{sucrasePromise=null})),sucrasePromise}function isModule(t,e){return Object.keys(t).length>1?!0:/^\\s*(import|export)\\s/m.test(t[e]||"")}function needsTypeScript(t){return/\\.(ts|tsx|jsx|mts|cts)$/.test(t)}function transformsFor(t){const e=["imports"];return/\\.tsx?$|\\.mts$|\\.cts$/.test(t)&&e.push("typescript"),/\\.[jt]sx$/.test(t)&&e.push("jsx"),e}async function runAsModules(t,e){const{transform:r}=await loadSucrase(),i=new Map,a=(n,o)=>{if(!o.startsWith("."))return null;const u=((n.includes("/")?n.slice(0,n.lastIndexOf("/")+1):"")+o).split("/"),d=[];for(const p of u)p==="."||p===""||(p===".."?d.pop():d.push(p));const c=d.join("/");return[c,c+".js",c+".ts",c+".tsx",c+".jsx",c+".json",c+"/index.js",c+"/index.ts"].find(p=>p in t)||null};function s(n){if(i.has(n))return i.get(n).exports;const o={exports:{}};if(i.set(n,o),n.endsWith(".json")){try{o.exports=JSON.parse(t[n])}catch(c){throw new SyntaxError("Invalid JSON in "+n+": "+c.message)}return o.exports}const{code:f}=r(t[n],{transforms:transformsFor(n),filePath:n,preserveDynamicImport:!0}),u=c=>{const l=a(n,c);if(!l)throw new Error('Cannot find module "'+c+'" from "'+n+'"');return s(l)};return new Function("exports","require","module","__filename","input","console",f+\`
|
|
9
9
|
//# sourceURL=\`+n)(o.exports,u,o,n,input,self.console),o.exports}s(e)}async function run(t){currentId=t.id,stdinLines=t.stdin?String(t.stdin).replace(/\\n$/,"").split(\`
|
|
@@ -13,4 +13,4 @@ import{s as e}from"./config-CT3H6Oum.js";import{t}from"./worker-runtime-DfYet3xy
|
|
|
13
13
|
\`).replace(/\\s+$/,"")}self.onmessage=async t=>{const e=t.data;try{if(e.type==="init")e.sucraseURL&&(sucraseURL=e.sucraseURL),post({type:"ready",version:"es2022",interactiveStdin:!0});else if(e.type==="run")await run(e);else if(e.type==="stdin-response"){const r=pendingLines.get(e.request);r&&(pendingLines.delete(e.request),r(e.text))}else if(e.type==="module"){const r=pendingModules.get(e.name);r&&(pendingModules.delete(e.name),typeof e.code=="string"?r.resolve(e.code):r.reject(new Error(e.error||"the page did not provide "+e.name)))}}catch(r){post({type:"fatal",id:e&&e.id,message:formatError(r)})}};
|
|
14
14
|
`,r=`sucrase-3.35.1.js`,i=new class extends t{id=`javascript`;get source(){return n}initPayload(){return{sucraseURL:e()}}async loadModule(e){if(e!==`sucrase`)throw Error(`no module named ${e}`);try{let{SUCRASE_SOURCE:e}=this.#e===0?await import(`./sucrase-3.35.1.js`):await import(
|
|
15
15
|
/* @vite-ignore */
|
|
16
|
-
this.#t());return e}catch(e){throw this.#e++,e}}#e=0;#t(){let e=import.meta.url;return new URL(`./`+r+`?retry=`+this.#e,e).href}get label(){return`JavaScript`}};function a(e,t,n){return{id:e,get label(){return t},get ready(){return i.ready},get interactiveStdin(){return i.interactiveStdin},async editorLanguage(){let{javascript:e}=await import(`./dist-
|
|
16
|
+
this.#t());return e}catch(e){throw this.#e++,e}}#e=0;#t(){let e=import.meta.url;return new URL(`./`+r+`?retry=`+this.#e,e).href}get label(){return`JavaScript`}};function a(e,t,n){return{id:e,get label(){return t},get ready(){return i.ready},get interactiveStdin(){return i.interactiveStdin},async editorLanguage(){let{javascript:e}=await import(`./dist-BoJapv5W.js`);return e({typescript:n})},load:e=>i.load(e),run:(e,t)=>i.run(e,t),stop:e=>i.stop(e)}}var o=a(`javascript`,`JavaScript`,!1),s=a(`typescript`,`TypeScript`,!0);export{o as javascriptRuntime,s as typescriptRuntime};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{l as e}from"./config-DB58UVsk.js";import{t}from"./worker-runtime-PykJQLB7.js";var n=`let currentId=null,stdinLines=[],stdinExhausted=!1,nextRequest=1,inputWaitMs=0;const pendingLines=new Map;let sucrasePromise=null,sucraseURL=null;const pendingModules=new Map;class TransformLoadError extends Error{}function requestModule(t){return new Promise((e,r)=>{pendingModules.set(t,{resolve:e,reject:r}),post({type:"module-request",id:currentId,name:t})})}function post(t){self.postMessage(t)}let functionLineOffset=0;try{new Function('throw new Error("probe")')()}catch(t){const e=/<anonymous>:(\\d+):/.exec(t.stack||"");e&&(functionLineOffset=Number(e[1])-1)}let currentFiles=[];const FLUSH_BYTES=8192,FLUSH_MS=16,EAGER_POSTS=32;let outputQueue=[],queuedChars=0,windowStart=-1/0,windowPosts=0;function writeOutput(t,e){const r=outputQueue[outputQueue.length-1];r&&r.type===t?r.text+=e:outputQueue.push({type:t,text:e}),queuedChars+=e.length;const i=performance.now();i-windowStart>=FLUSH_MS&&(windowStart=i,windowPosts=0),(windowPosts<EAGER_POSTS||queuedChars>=FLUSH_BYTES)&&flushOutput()}function flushOutput(){if(!outputQueue.length)return;windowPosts++;const t=outputQueue;outputQueue=[],queuedChars=0;for(const e of t)post({type:e.type,id:currentId,text:e.text})}function format(t,e,r){if(e=e||new Set,typeof t=="string")return r?t:JSON.stringify(t);if(typeof t=="bigint")return String(t)+"n";if(typeof t=="function")return"[Function"+(t.name?": "+t.name:"")+"]";if(typeof t=="symbol"||t==null||typeof t!="object")return String(t);if(e.has(t))return"[Circular]";e.add(t);try{if(t instanceof Error)return t.stack||t.name+": "+t.message;if(Array.isArray(t))return"[ "+t.map(n=>format(n,e)).join(", ")+" ]";if(t instanceof Map)return"Map("+t.size+") { "+[...t].map(([n,o])=>format(n,e)+" => "+format(o,e)).join(", ")+" }";if(t instanceof Set)return"Set("+t.size+") { "+[...t].map(n=>format(n,e)).join(", ")+" }";if(t instanceof Date)return t.toISOString();if(t instanceof Promise)return"Promise { \\u2026 }";const i=Object.entries(t).map(([n,o])=>n+": "+format(o,e)),a=t.constructor&&t.constructor.name;return(a&&a!=="Object"?a+" ":"")+"{ "+i.join(", ")+" }"}finally{e.delete(t)}}function formatArgs(t){return t.map(e=>format(e,null,!0)).join(" ")+\`
|
|
2
2
|
\`}const nativeConsole=self.console;self.console=Object.assign(Object.create(nativeConsole),{log:(...t)=>writeOutput("stdout",formatArgs(t)),info:(...t)=>writeOutput("stdout",formatArgs(t)),debug:(...t)=>writeOutput("stdout",formatArgs(t)),warn:(...t)=>writeOutput("stderr",formatArgs(t)),error:(...t)=>writeOutput("stderr",formatArgs(t))}),self._ppReadLine=async()=>{if(stdinLines.length){const i=stdinLines.shift();return writeOutput("echo",i+\`
|
|
3
3
|
\`),i}const t=nextRequest++;flushOutput();const e=performance.now(),r=await new Promise(i=>{pendingLines.set(t,i),post({type:"stdin-request",id:currentId,request:t})});return inputWaitMs+=performance.now()-e,typeof r!="string"&&(stdinExhausted=!0),typeof r=="string"?r:null};async function input(t){t!==void 0&&writeOutput("stdout",String(t));const e=await self._ppReadLine();if(e===null)throw new Error("EOF: no more input");return e}self.input=input;async function loadSucrase(){return sucrasePromise||(sucrasePromise=(async()=>{try{if(sucraseURL)return await import(sucraseURL);const t=await requestModule("sucrase"),e=URL.createObjectURL(new Blob([t],{type:"text/javascript"}));try{return await import(e)}finally{URL.revokeObjectURL(e)}}catch(t){const e=sucraseURL?" from "+sucraseURL:"";throw new TransformLoadError("Could not load the TypeScript transform (Sucrase)"+e+": "+(t&&t.message?t.message:String(t)))}})(),sucrasePromise.catch(()=>{sucrasePromise=null})),sucrasePromise}function isModule(t,e){return Object.keys(t).length>1?!0:/^\\s*(import|export)\\s/m.test(t[e]||"")}function needsTypeScript(t){return/\\.(ts|tsx|jsx|mts|cts)$/.test(t)}function transformsFor(t){const e=["imports"];return/\\.tsx?$|\\.mts$|\\.cts$/.test(t)&&e.push("typescript"),/\\.[jt]sx$/.test(t)&&e.push("jsx"),e}async function runAsModules(t,e){const{transform:r}=await loadSucrase(),i=new Map,a=(n,o)=>{if(!o.startsWith("."))return null;const u=((n.includes("/")?n.slice(0,n.lastIndexOf("/")+1):"")+o).split("/"),d=[];for(const p of u)p==="."||p===""||(p===".."?d.pop():d.push(p));const c=d.join("/");return[c,c+".js",c+".ts",c+".tsx",c+".jsx",c+".json",c+"/index.js",c+"/index.ts"].find(p=>p in t)||null};function s(n){if(i.has(n))return i.get(n).exports;const o={exports:{}};if(i.set(n,o),n.endsWith(".json")){try{o.exports=JSON.parse(t[n])}catch(c){throw new SyntaxError("Invalid JSON in "+n+": "+c.message)}return o.exports}const{code:f}=r(t[n],{transforms:transformsFor(n),filePath:n,preserveDynamicImport:!0}),u=c=>{const l=a(n,c);if(!l)throw new Error('Cannot find module "'+c+'" from "'+n+'"');return s(l)};return new Function("exports","require","module","__filename","input","console",f+\`
|
|
4
4
|
//# sourceURL=\`+n)(o.exports,u,o,n,input,self.console),o.exports}s(e)}async function run(t){currentId=t.id,stdinLines=t.stdin?String(t.stdin).replace(/\\n$/,"").split(\`
|
package/dist/languages.d.ts
CHANGED
|
@@ -6,4 +6,4 @@ export declare function highlightedExtensions(): string[];
|
|
|
6
6
|
* honest answer for a .csv or a .txt, and better than a wrong grammar.
|
|
7
7
|
* A missing optional peer dependency also lands here rather than throwing.
|
|
8
8
|
*/
|
|
9
|
-
export declare function editorLanguageForFile(name: string): Promise<Extension | null>;
|
|
9
|
+
export declare function editorLanguageForFile(name: string, runtime?: string): Promise<Extension | null>;
|
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
* Bundles CodeMirror 6 and Lezer (MIT) © Marijn Haverbeke and others.
|
|
4
4
|
* Full third-party licences: THIRD-PARTY-NOTICES.txt in this package.
|
|
5
5
|
*/
|
|
6
|
-
import{
|
|
6
|
+
import{s as e}from"./config-DB58UVsk.js";import{t}from"./worker-runtime-DvpugeXD.js";var n=`let pyodide=null,stdinLines=[],stdinExhausted=!1,currentId=null,interactive=!1,inputWaitMs=0,nextRequest=1;const pendingLines=new Map,MOUNT="/home/pyodide/playground";let written=new Set,internals=null;const REFRESH=["import importlib, os, sys","MOUNT = "+JSON.stringify(MOUNT),"os.makedirs(MOUNT, exist_ok=True)","sys.path.insert(0, MOUNT) if MOUNT not in sys.path else None","os.chdir(MOUNT)","for _name, _mod in list(sys.modules.items()):",' _file = getattr(_mod, "__file__", None) or ""',' _paths = list(getattr(_mod, "__path__", None) or [])'," if _file.startswith(MOUNT) or any(str(p).startswith(MOUNT) for p in _paths):"," del sys.modules[_name]","importlib.invalidate_caches()"].join(\`
|
|
7
7
|
\`);function flushStreams(){try{pyodide.runPython(\`import sys
|
|
8
8
|
sys.stdout.flush()
|
|
9
9
|
sys.stderr.flush()\`,{globals:internals})}catch{}flushOutput()}const INPUT_OVERRIDE=["import builtins, sys, js","from pyodide.ffi import run_sync","",'def _pg_input(prompt=""):',' if prompt != "":'," sys.stdout.write(str(prompt))"," sys.stdout.flush()"," line = run_sync(js._pgReadLine())"," # Pyodide maps JS null to its own JsNull singleton, not None, so test"," # for what we want rather than for the several ways EOF can arrive."," if not isinstance(line, str):",' raise EOFError("EOF when reading a line")'," return line","",'_pg_input.__name__ = "input"','_pg_input.__qualname__ = "input"',"_pg_input.__doc__ = builtins.input.__doc__","builtins.input = _pg_input"].join(\`
|
|
@@ -15,4 +15,4 @@ sys.stderr.flush()\`,{globals:internals})}catch{}flushOutput()}const INPUT_OVERR
|
|
|
15
15
|
\`}return stdinExhausted=!0,null},autoEOF:!1});let s=pyodide.version;try{s=pyodide.runPython("import sys; '.'.join(str(p) for p in sys.version_info[:3])")}catch{}if(internals=pyodide.runPython("dict()"),typeof WebAssembly.Suspending=="function")try{pyodide.runPython(INPUT_OVERRIDE,{globals:internals}),interactive=!0}catch{interactive=!1}post({type:"ready",version:s,interactiveStdin:interactive})}async function run(e){let t=null;currentId=e.id,stdinLines=e.stdin?String(e.stdin).replace(/\\n$/,"").split(\`
|
|
16
16
|
\`):[],stdinExhausted=!1,inputWaitMs=0,windowStart=-1/0;for(const i of pendingLines.values())i(null);pendingLines.clear();const n=performance.now();try{e.files&&syncFiles(e.files);try{await pyodide.loadPackagesFromImports(e.code,{messageCallback:r=>post({type:"progress",id:e.id,phase:"packages",message:r}),errorCallback:()=>{}})}catch(r){post({type:"stderr",id:e.id,text:"Could not auto-install packages: "+formatError(r)+\`
|
|
17
17
|
\`})}t=pyodide.runPython('dict(__name__="__main__")'),e.entry&&t.set("__file__",e.entry);const i={globals:t};e.entry&&(i.filename=MOUNT+"/"+e.entry);const s=await pyodide.runPythonAsync(e.code,i);flushStreams();let o;if(s!=null)try{t.set("_pg_last",s),o=pyodide.runPython("repr(_pg_last)",{globals:t})}catch{o=String(s)}s&&typeof s.destroy=="function"&&s.destroy(),post({type:"result",id:e.id,value:o,durationMs:performance.now()-n-inputWaitMs})}catch(i){flushStreams();const s=formatError(i);post({type:"error",id:e.id,message:s,hint:stdinExhausted&&s.indexOf("EOFError")!==-1?"input() asked for a line that standard input did not have. Add one line per input() call in the box above, then run again.":void 0,hintAbout:stdinExhausted&&s.indexOf("EOFError")!==-1?"stdin":void 0,durationMs:performance.now()-n-inputWaitMs})}finally{if(currentId=null,t){try{t.destroy()}catch{}t=null}}}self.onmessage=async e=>{const t=e.data;try{if(t.type==="init")await boot(t.indexURL);else if(t.type==="run")await run(t);else if(t.type==="stdin-response"){const n=pendingLines.get(t.request);n&&(pendingLines.delete(t.request),n(t.text===void 0?null:t.text))}}catch(n){post({type:"fatal",id:t&&t.id,message:formatError(n)})}};
|
|
18
|
-
`,r=new class extends t{id=`python`;get source(){return n}initPayload(){return{indexURL:e()}}get label(){return this.version?`Python ${this.version.split(`.`).slice(0,2).join(`.`)}`:`Python`}async editorLanguage(){let{python:e}=await import(`./dist
|
|
18
|
+
`,r=new class extends t{id=`python`;get source(){return n}initPayload(){return{indexURL:e()}}get label(){return this.version?`Python ${this.version.split(`.`).slice(0,2).join(`.`)}`:`Python`}async editorLanguage(){let{python:e}=await import(`./dist-y6lcdYKh.js`);return e()}};export{r as pythonRuntime};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{s as e}from"./config-DB58UVsk.js";import{t}from"./worker-runtime-PykJQLB7.js";var n=`let pyodide=null,stdinLines=[],stdinExhausted=!1,currentId=null,interactive=!1,inputWaitMs=0,nextRequest=1;const pendingLines=new Map,MOUNT="/home/pyodide/playground";let written=new Set,internals=null;const REFRESH=["import importlib, os, sys","MOUNT = "+JSON.stringify(MOUNT),"os.makedirs(MOUNT, exist_ok=True)","sys.path.insert(0, MOUNT) if MOUNT not in sys.path else None","os.chdir(MOUNT)","for _name, _mod in list(sys.modules.items()):",' _file = getattr(_mod, "__file__", None) or ""',' _paths = list(getattr(_mod, "__path__", None) or [])'," if _file.startswith(MOUNT) or any(str(p).startswith(MOUNT) for p in _paths):"," del sys.modules[_name]","importlib.invalidate_caches()"].join(\`
|
|
2
2
|
\`);function flushStreams(){try{pyodide.runPython(\`import sys
|
|
3
3
|
sys.stdout.flush()
|
|
4
4
|
sys.stderr.flush()\`,{globals:internals})}catch{}flushOutput()}const INPUT_OVERRIDE=["import builtins, sys, js","from pyodide.ffi import run_sync","",'def _pg_input(prompt=""):',' if prompt != "":'," sys.stdout.write(str(prompt))"," sys.stdout.flush()"," line = run_sync(js._pgReadLine())"," # Pyodide maps JS null to its own JsNull singleton, not None, so test"," # for what we want rather than for the several ways EOF can arrive."," if not isinstance(line, str):",' raise EOFError("EOF when reading a line")'," return line","",'_pg_input.__name__ = "input"','_pg_input.__qualname__ = "input"',"_pg_input.__doc__ = builtins.input.__doc__","builtins.input = _pg_input"].join(\`
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/*!
|
|
2
|
+
* code-playpad — MIT © 2026 Seung Hun Lee
|
|
3
|
+
* Bundles CodeMirror 6 and Lezer (MIT) © Marijn Haverbeke and others.
|
|
4
|
+
* Full third-party licences: THIRD-PARTY-NOTICES.txt in this package.
|
|
5
|
+
*/
|
|
6
|
+
import{t as e}from"./types-CfcYqU2K.js";import{t}from"./react-version.generated-BNNJmf7J.js";import{c as n}from"./config-DB58UVsk.js";var r=`(function(){var a=function(e,n){e.__playpad=1,parent.postMessage(e,"*",n||[])};function l(e,n){if(typeof e=="string")return e;if(typeof e=="function")return"[Function "+(e.name||"anonymous")+"]";if(typeof e!="object"||e===null)return String(e);if(e instanceof Error)return e.name+": "+e.message;if(e instanceof Node)return"<"+e.nodeName.toLowerCase()+">";try{return JSON.stringify(e)}catch{return String(e)}}function C(e){if(typeof e[0]!="string")return e.map(function(o){return l(o)}).join(" ");var n=1,r=e[0].replace(/%([sdifoOc%])/g,function(o,i){if(i==="%")return"%";if(n>=e.length)return o;var c=e[n++];return i==="c"?"":i==="d"||i==="i"?String(parseInt(c,10)):i==="f"?String(parseFloat(c)):l(c)});return[r].concat(e.slice(n).map(function(o){return l(o)})).join(" ")}["log","info","warn","error","debug"].forEach(function(e){var n=console[e];console[e]=function(){var r=Array.prototype.slice.call(arguments);a({type:"console",level:e==="debug"?"log":e,text:C(r)}),n.apply(console,r)}});function M(e){var n=/playpad-project\\/([^\\s:)]+):(\\d+)/.exec(e&&e.stack||"");return n?{file:n[1],line:Number(n[2])}:{}}function u(e,n){var r=e&&typeof e=="object"&&"message"in e,o=r&&e.name?e.name+": ":"",i=M(e);a({type:"error",message:n+o+(r?e.message:l(e)),file:i.file,line:i.line})}addEventListener("error",function(e){e.error?u(e.error,"Uncaught "):e.message==="Script error."?a({type:"error",message:"An error happened in the preview, but this browser hides its details. Open the browser's developer console to see it."}):u(e.message,"Uncaught ")}),window.reportError=function(e){u(e,"Uncaught ")};function O(e){return function(){try{return e.apply(this,arguments)}catch(n){u(n,"Uncaught ")}}}["setTimeout","setInterval","requestAnimationFrame","queueMicrotask"].forEach(function(e){var n=window[e];window[e]=function(r){var o=Array.prototype.slice.call(arguments);return typeof r=="function"&&(o[0]=O(r)),n.apply(window,o)}}),addEventListener("unhandledrejection",function(e){u(e.reason,"Unhandled promise rejection: ")}),window.alert=function(e){a({type:"alert",text:e===void 0?"":String(e)})},window.confirm=function(){return console.warn("confirm() cannot wait for an answer in this preview, so it returned true."),!0},window.prompt=function(){return console.warn("prompt() cannot wait for an answer in this preview, so it returned null."),null};var T=1e3,h=!1,v=0,b=0,x=new MessageChannel;x.port1.onmessage=function(){h=!1},window.__playpadLoopGuard=function(){if(!h){h=!0,v=performance.now(),b=0,x.port2.postMessage(0);return}if((++b&63)===0&&performance.now()-v>T)throw new Error("This loop ran for more than 1 second. Is it infinite?")};function U(e){var n=e.nonce;function r(s){n&&(s.nonce=n),document.head.appendChild(s)}function o(s){var d=document.createElement("script");d.textContent=s,r(d)}function i(){if(!window.__vendor){a({type:"fatal",message:"The preview could not run the React runtime. A Content-Security-Policy on this page probably blocks it."});return}var s={};window.__playpadDefine=function(t,f){s[t]=f};var d={};e.modules.forEach(function(t){d[t.path]=t,t.kind==="js"&&o("__playpadDefine("+JSON.stringify(t.path)+",function(require,module,exports){"+t.text+\`
|
|
7
|
+
});
|
|
8
|
+
//# sourceURL=playpad-project/\`+t.path)});var y={};function _(t){if(y[t])return y[t].exports;var f=d[t],m=y[t]={exports:{}};if(f.kind==="json")m.exports=JSON.parse(f.text);else if(f.kind==="css"){var w=document.createElement("style");n&&(w.nonce=n),w.dataset.file=t,w.textContent=f.text,document.head.appendChild(w)}else{if(!s[t])throw new Error("The file "+t+" could not be loaded.");s[t](function(p){if(window.__vendor[p])return window.__vendor[p];if(f.links[p])return _(f.links[p]);throw new Error('Cannot find "'+p+'" from '+t+".")},m,m.exports)}return m.exports}var g=document.getElementById("root");if(g){var S;new MutationObserver(function(){clearTimeout(S),S=setTimeout(function(){a({type:"render",rootText:g.textContent})},100)}).observe(g,{childList:!0,subtree:!0,characterData:!0})}var L=!1;try{e.entries.forEach(_)}catch(t){L=!0,u(t,"Uncaught ")}a({type:"entry-done",failed:L})}if(e.vendor)o(e.vendor),i();else{var c=document.createElement("script");c.src=e.runtimeURL,c.onload=i,c.onerror=function(){a({type:"fatal",message:"The React runtime could not be loaded from "+e.runtimeURL+"."})},r(c)}}function E(){var e=new MessageChannel;e.port1.onmessage=function(n){e.port1.close(),U(n.data)},a({type:"booted"},[e.port2])}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",E):E()})();
|
|
9
|
+
`,i=5e3,a=4e3,o=65536,s=[`src/main.jsx`,`src/main.js`],c=`<!doctype html><html lang="en"><head><meta charset="utf-8"></head><body><div id="root"></div></body></html>`;function l(e){return/^([a-z][a-z0-9+.-]*:|\/\/)/i.test(e)}function u(e,t,i){let{CompileError:a,compileProject:o,resolveImport:u}=i,d=t.endsWith(`.html`)?t:`index.html`,f=Object.hasOwn(e,d),p=new DOMParser().parseFromString(f?e[d]:c,`text/html`),m=[];if(f){let t=[...p.querySelectorAll(`script[src], link[rel="stylesheet"][href]`)],n=[];for(let r of t){let t=r.tagName===`SCRIPT`,i=r.getAttribute(t?`src`:`href`);if(l(i))throw new a(d,`This project can't load "${i}". The preview can only use the project's own files.`);let o=u(e,d,i);if(!o)throw new a(d,`The file "${i}" does not exist.`);(t?n:m).push(o),r.remove()}if(!n.length)throw new a(d,`Add <script type="module" src="/src/main.jsx"><\/script> so the app has an entry file.`);m.push(...n)}else{let n=t.endsWith(`.html`)?void 0:Object.hasOwn(e,t)?t:s.find(t=>Object.hasOwn(e,t));if(!n)throw new a(`index.html`,`This project has no entry file. Add src/main.jsx.`);m.push(n)}let h=o(e,m),{nonce:g,runtimeURL:_}=n(),v=p.createElement(`meta`);v.httpEquiv=`Content-Security-Policy`,v.content=`default-src 'none'; script-src 'unsafe-inline'${_?` ${_}`:``}; style-src 'unsafe-inline'; img-src data:; font-src data:; form-action 'none'; base-uri 'none'`;let y=p.createElement(`script`);return g&&y.setAttribute(`nonce`,g),y.textContent=r,p.head.prepend(v,y),{html:`<!doctype html>${p.documentElement.outerHTML}`,modules:h,entries:m}}var d=class{preview;payload;#e=null;#t=null;#n=null;#r=null;#i=null;#a=null;#o=``;#s=``;#c;#l=performance.now();#u=!1;#d=null;#f=null;constructor(e,t,n,r){this.preview=e,this.payload=t,this.#i=n,this.#a=r}get live(){return this.#e!==null}open(e){let t=document.createElement(`iframe`);t.setAttribute(`sandbox`,`allow-scripts allow-forms`),t.setAttribute(`allow`,``),t.setAttribute(`referrerpolicy`,`no-referrer`),t.title=`Preview`,t.className=`cp-preview-frame`,t.srcdoc=e,this.#e=t,this.#t=this.preview.host.ownerDocument.defaultView??window,this.#t.addEventListener(`message`,this.#v),this.preview.host.replaceChildren(t),this.#n=setTimeout(()=>{this.fail(`The preview did not start. A Content-Security-Policy on this page probably blocks it: see "Host pages with a CSP" in the README.`)},i)}fail(e,t={},n){this.#n&&clearTimeout(this.#n),this.#n=null,this.#h(e,t),this.#p(!0,n)}#p(e,t){let n=this.#i;this.#i=null,this.#a=null,n?.({stdout:this.#o,...this.#s?{stderr:this.#s}:{},...t?{hint:t}:{},...e&&this.#c?{problem:this.#c}:{},durationMs:Math.round(performance.now()-this.#l),failed:e})}#m(e,t){this.#i&&(e===`warn`||e===`error`?this.#s+=`${t}\n`:this.#o+=`${t}\n`),this.preview.onConsole(e,t)}#h(e,t){let n=(t.file?`${t.file}${t.line?`:${t.line}`:``}${t.column?`:${t.column}`:``}: `:``)+e;this.#m(`error`,n),this.#g(n);let r={message:n,...t};this.#i?this.#c??=r:this.preview.onError(r)}#g(e){this.#d||(this.#d=document.createElement(`pre`),this.#d.className=`cp-preview-banner`,this.#d.setAttribute(`role`,`alert`),this.preview.host.append(this.#d)),this.#d.textContent=e}#_(e){this.#f||(this.#f=document.createElement(`div`),this.#f.className=`cp-preview-notice`,this.#f.setAttribute(`role`,`status`),this.preview.host.append(this.#f)),this.#f.textContent=e,this.#f.hidden=!1,this.#r&&clearTimeout(this.#r),this.#r=setTimeout(()=>{this.#f&&(this.#f.hidden=!0)},a)}showCompileBanner(e){e&&this.#d&&(this.#d.textContent+=`\n${e}`)}#v=e=>{if(!this.#e||e.source!==this.#e.contentWindow)return;let t=e.data;if(typeof t!=`object`||!t||t.__playpad!==1)return;let n=e=>String(e??``).slice(0,o);switch(t.type){case`booted`:if(this.#u)return;this.#u=!0,this.#n&&clearTimeout(this.#n),this.#n=null,this.preview.onStart?.(),e.ports[0]?.postMessage(this.payload);break;case`console`:{let e=t.level===`info`||t.level===`warn`||t.level===`error`?t.level:`log`;this.#m(e,n(t.text));break}case`error`:this.#h(n(t.message),{...typeof t.file==`string`?{file:t.file.slice(0,512)}:{},...typeof t.line==`number`?{line:t.line}:{}});break;case`fatal`:this.fail(n(t.message));break;case`entry-done`:this.#i&&this.#p(t.failed===!0);break;case`render`:this.preview.onRender(n(t.rootText));break;case`alert`:this.#m(`info`,`alert: ${n(t.text)}`),this.#_(n(t.text))}};dispose(t){this.#n&&clearTimeout(this.#n),this.#r&&clearTimeout(this.#r),this.#t?.removeEventListener(`message`,this.#v),this.#e=null,this.preview.host.replaceChildren(),this.#a&&t&&this.#a(new e),this.#i=null,this.#a=null}},f=new class{id=`react`;label=`React ${t}`;interactiveStdin=!1;statusDecidesFailure=!0;#e=null;#t=null;#n=null;#r=/* @__PURE__ */ new WeakMap;#i=/* @__PURE__ */ new WeakMap;get ready(){return this.#e!==null}async editorLanguage(){let{javascript:e}=await import(`./dist-BoJapv5W.js`);return e({jsx:!0})}load(){return this.#n??=(async()=>{try{let e=import(`./compiler-B408qd3N.js`),t=n().runtimeURL?null:import(`./react-vendor.generated-DMxIoCMn.js`);this.#t=(await t)?.REACT_VENDOR_SOURCE??null,this.#e=await e}catch(e){throw this.#n=null,Error(`The React runtime could not be loaded. Check your connection and reload the page. (${e.message})`)}})(),this.#n}run(e,t={}){let r=t.preview;if(!r)return Promise.reject(/* @__PURE__ */ Error(`React needs a <code-playpad> widget to render in.`));this.dispose(r.host);let i,a=t.files??{},o=new Promise((e,t)=>{let a=n().runtimeURL;i=new d(r,{...a?{runtimeURL:a}:{vendor:this.#t},nonce:n().nonce},e,t)});return this.#r.set(r.host,i),this.#i.set(o,i),this.#a(i,a,t.entry??`index.html`),o}async#a(e,t,n){try{await this.load();let r=this.#e,i;try{i=u(t,n,r)}catch(t){if(t instanceof r.CompileError){e.fail(t.reason,{file:t.file,...t.line?{line:t.line}:{},...t.column?{column:t.column}:{}},t.hint),e.showCompileBanner(t.hint);return}throw t}e.payload.modules=i.modules,e.payload.entries=i.entries,e.open(i.html)}catch(t){e.fail(t.message)}}stop(e){e&&this.#i.get(e)?.dispose(!0)}hasLivePreview(e){return this.#r.get(e)?.live??!1}dispose(e){this.#r.get(e)?.dispose(!0),this.#r.delete(e)}};export{f as reactRuntime};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import{u as e}from"./element-COcjM0hI.js";import{t}from"./react-version.generated-BNNJmf7J.js";import{c as n}from"./config-DB58UVsk.js";var r=`(function(){var a=function(e,n){e.__playpad=1,parent.postMessage(e,"*",n||[])};function l(e,n){if(typeof e=="string")return e;if(typeof e=="function")return"[Function "+(e.name||"anonymous")+"]";if(typeof e!="object"||e===null)return String(e);if(e instanceof Error)return e.name+": "+e.message;if(e instanceof Node)return"<"+e.nodeName.toLowerCase()+">";try{return JSON.stringify(e)}catch{return String(e)}}function C(e){if(typeof e[0]!="string")return e.map(function(o){return l(o)}).join(" ");var n=1,r=e[0].replace(/%([sdifoOc%])/g,function(o,i){if(i==="%")return"%";if(n>=e.length)return o;var c=e[n++];return i==="c"?"":i==="d"||i==="i"?String(parseInt(c,10)):i==="f"?String(parseFloat(c)):l(c)});return[r].concat(e.slice(n).map(function(o){return l(o)})).join(" ")}["log","info","warn","error","debug"].forEach(function(e){var n=console[e];console[e]=function(){var r=Array.prototype.slice.call(arguments);a({type:"console",level:e==="debug"?"log":e,text:C(r)}),n.apply(console,r)}});function M(e){var n=/playpad-project\\/([^\\s:)]+):(\\d+)/.exec(e&&e.stack||"");return n?{file:n[1],line:Number(n[2])}:{}}function u(e,n){var r=e&&typeof e=="object"&&"message"in e,o=r&&e.name?e.name+": ":"",i=M(e);a({type:"error",message:n+o+(r?e.message:l(e)),file:i.file,line:i.line})}addEventListener("error",function(e){e.error?u(e.error,"Uncaught "):e.message==="Script error."?a({type:"error",message:"An error happened in the preview, but this browser hides its details. Open the browser's developer console to see it."}):u(e.message,"Uncaught ")}),window.reportError=function(e){u(e,"Uncaught ")};function O(e){return function(){try{return e.apply(this,arguments)}catch(n){u(n,"Uncaught ")}}}["setTimeout","setInterval","requestAnimationFrame","queueMicrotask"].forEach(function(e){var n=window[e];window[e]=function(r){var o=Array.prototype.slice.call(arguments);return typeof r=="function"&&(o[0]=O(r)),n.apply(window,o)}}),addEventListener("unhandledrejection",function(e){u(e.reason,"Unhandled promise rejection: ")}),window.alert=function(e){a({type:"alert",text:e===void 0?"":String(e)})},window.confirm=function(){return console.warn("confirm() cannot wait for an answer in this preview, so it returned true."),!0},window.prompt=function(){return console.warn("prompt() cannot wait for an answer in this preview, so it returned null."),null};var T=1e3,h=!1,v=0,b=0,x=new MessageChannel;x.port1.onmessage=function(){h=!1},window.__playpadLoopGuard=function(){if(!h){h=!0,v=performance.now(),b=0,x.port2.postMessage(0);return}if((++b&63)===0&&performance.now()-v>T)throw new Error("This loop ran for more than 1 second. Is it infinite?")};function U(e){var n=e.nonce;function r(s){n&&(s.nonce=n),document.head.appendChild(s)}function o(s){var d=document.createElement("script");d.textContent=s,r(d)}function i(){if(!window.__vendor){a({type:"fatal",message:"The preview could not run the React runtime. A Content-Security-Policy on this page probably blocks it."});return}var s={};window.__playpadDefine=function(t,f){s[t]=f};var d={};e.modules.forEach(function(t){d[t.path]=t,t.kind==="js"&&o("__playpadDefine("+JSON.stringify(t.path)+",function(require,module,exports){"+t.text+\`
|
|
2
|
+
});
|
|
3
|
+
//# sourceURL=playpad-project/\`+t.path)});var y={};function _(t){if(y[t])return y[t].exports;var f=d[t],m=y[t]={exports:{}};if(f.kind==="json")m.exports=JSON.parse(f.text);else if(f.kind==="css"){var w=document.createElement("style");n&&(w.nonce=n),w.dataset.file=t,w.textContent=f.text,document.head.appendChild(w)}else{if(!s[t])throw new Error("The file "+t+" could not be loaded.");s[t](function(p){if(window.__vendor[p])return window.__vendor[p];if(f.links[p])return _(f.links[p]);throw new Error('Cannot find "'+p+'" from '+t+".")},m,m.exports)}return m.exports}var g=document.getElementById("root");if(g){var S;new MutationObserver(function(){clearTimeout(S),S=setTimeout(function(){a({type:"render",rootText:g.textContent})},100)}).observe(g,{childList:!0,subtree:!0,characterData:!0})}var L=!1;try{e.entries.forEach(_)}catch(t){L=!0,u(t,"Uncaught ")}a({type:"entry-done",failed:L})}if(e.vendor)o(e.vendor),i();else{var c=document.createElement("script");c.src=e.runtimeURL,c.onload=i,c.onerror=function(){a({type:"fatal",message:"The React runtime could not be loaded from "+e.runtimeURL+"."})},r(c)}}function E(){var e=new MessageChannel;e.port1.onmessage=function(n){e.port1.close(),U(n.data)},a({type:"booted"},[e.port2])}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",E):E()})();
|
|
4
|
+
`,i=5e3,a=4e3,o=65536,s=[`src/main.jsx`,`src/main.js`],c=`<!doctype html><html lang="en"><head><meta charset="utf-8"></head><body><div id="root"></div></body></html>`;function l(e){return/^([a-z][a-z0-9+.-]*:|\/\/)/i.test(e)}function u(e,t,i){let{CompileError:a,compileProject:o,resolveImport:u}=i,d=t.endsWith(`.html`)?t:`index.html`,f=Object.hasOwn(e,d),p=new DOMParser().parseFromString(f?e[d]:c,`text/html`),m=[];if(f){let t=[...p.querySelectorAll(`script[src], link[rel="stylesheet"][href]`)],n=[];for(let r of t){let t=r.tagName===`SCRIPT`,i=r.getAttribute(t?`src`:`href`);if(l(i))throw new a(d,`This project can't load "${i}". The preview can only use the project's own files.`);let o=u(e,d,i);if(!o)throw new a(d,`The file "${i}" does not exist.`);(t?n:m).push(o),r.remove()}if(!n.length)throw new a(d,`Add <script type="module" src="/src/main.jsx"><\/script> so the app has an entry file.`);m.push(...n)}else{let n=t.endsWith(`.html`)?void 0:Object.hasOwn(e,t)?t:s.find(t=>Object.hasOwn(e,t));if(!n)throw new a(`index.html`,`This project has no entry file. Add src/main.jsx.`);m.push(n)}let h=o(e,m),{nonce:g,runtimeURL:_}=n(),v=p.createElement(`meta`);v.httpEquiv=`Content-Security-Policy`,v.content=`default-src 'none'; script-src 'unsafe-inline'${_?` ${_}`:``}; style-src 'unsafe-inline'; img-src data:; font-src data:; form-action 'none'; base-uri 'none'`;let y=p.createElement(`script`);return g&&y.setAttribute(`nonce`,g),y.textContent=r,p.head.prepend(v,y),{html:`<!doctype html>${p.documentElement.outerHTML}`,modules:h,entries:m}}var d=class{preview;payload;#e=null;#t=null;#n=null;#r=null;#i=null;#a=null;#o=``;#s=``;#c;#l=performance.now();#u=!1;#d=null;#f=null;constructor(e,t,n,r){this.preview=e,this.payload=t,this.#i=n,this.#a=r}get live(){return this.#e!==null}open(e){let t=document.createElement(`iframe`);t.setAttribute(`sandbox`,`allow-scripts allow-forms`),t.setAttribute(`allow`,``),t.setAttribute(`referrerpolicy`,`no-referrer`),t.title=`Preview`,t.className=`cp-preview-frame`,t.srcdoc=e,this.#e=t,this.#t=this.preview.host.ownerDocument.defaultView??window,this.#t.addEventListener(`message`,this.#v),this.preview.host.replaceChildren(t),this.#n=setTimeout(()=>{this.fail(`The preview did not start. A Content-Security-Policy on this page probably blocks it: see "Host pages with a CSP" in the README.`)},i)}fail(e,t={},n){this.#n&&clearTimeout(this.#n),this.#n=null,this.#h(e,t),this.#p(!0,n)}#p(e,t){let n=this.#i;this.#i=null,this.#a=null,n?.({stdout:this.#o,...this.#s?{stderr:this.#s}:{},...t?{hint:t}:{},...e&&this.#c?{problem:this.#c}:{},durationMs:Math.round(performance.now()-this.#l),failed:e})}#m(e,t){this.#i&&(e===`warn`||e===`error`?this.#s+=`${t}\n`:this.#o+=`${t}\n`),this.preview.onConsole(e,t)}#h(e,t){let n=(t.file?`${t.file}${t.line?`:${t.line}`:``}${t.column?`:${t.column}`:``}: `:``)+e;this.#m(`error`,n),this.#g(n);let r={message:n,...t};this.#i?this.#c??=r:this.preview.onError(r)}#g(e){this.#d||(this.#d=document.createElement(`pre`),this.#d.className=`cp-preview-banner`,this.#d.setAttribute(`role`,`alert`),this.preview.host.append(this.#d)),this.#d.textContent=e}#_(e){this.#f||(this.#f=document.createElement(`div`),this.#f.className=`cp-preview-notice`,this.#f.setAttribute(`role`,`status`),this.preview.host.append(this.#f)),this.#f.textContent=e,this.#f.hidden=!1,this.#r&&clearTimeout(this.#r),this.#r=setTimeout(()=>{this.#f&&(this.#f.hidden=!0)},a)}showCompileBanner(e){e&&this.#d&&(this.#d.textContent+=`\n${e}`)}#v=e=>{if(!this.#e||e.source!==this.#e.contentWindow)return;let t=e.data;if(typeof t!=`object`||!t||t.__playpad!==1)return;let n=e=>String(e??``).slice(0,o);switch(t.type){case`booted`:if(this.#u)return;this.#u=!0,this.#n&&clearTimeout(this.#n),this.#n=null,this.preview.onStart?.(),e.ports[0]?.postMessage(this.payload);break;case`console`:{let e=t.level===`info`||t.level===`warn`||t.level===`error`?t.level:`log`;this.#m(e,n(t.text));break}case`error`:this.#h(n(t.message),{...typeof t.file==`string`?{file:t.file.slice(0,512)}:{},...typeof t.line==`number`?{line:t.line}:{}});break;case`fatal`:this.fail(n(t.message));break;case`entry-done`:this.#i&&this.#p(t.failed===!0);break;case`render`:this.preview.onRender(n(t.rootText));break;case`alert`:this.#m(`info`,`alert: ${n(t.text)}`),this.#_(n(t.text))}};dispose(t){this.#n&&clearTimeout(this.#n),this.#r&&clearTimeout(this.#r),this.#t?.removeEventListener(`message`,this.#v),this.#e=null,this.preview.host.replaceChildren(),this.#a&&t&&this.#a(new e),this.#i=null,this.#a=null}},f=new class{id=`react`;label=`React ${t}`;interactiveStdin=!1;statusDecidesFailure=!0;#e=null;#t=null;#n=null;#r=/* @__PURE__ */ new WeakMap;#i=/* @__PURE__ */ new WeakMap;get ready(){return this.#e!==null}async editorLanguage(){let{javascript:e}=await import(`@codemirror/lang-javascript`);return e({jsx:!0})}load(){return this.#n??=(async()=>{try{let e=import(`./compiler-B408qd3N.js`),t=n().runtimeURL?null:import(`./react-vendor.generated-DMxIoCMn.js`);this.#t=(await t)?.REACT_VENDOR_SOURCE??null,this.#e=await e}catch(e){throw this.#n=null,Error(`The React runtime could not be loaded. Check your connection and reload the page. (${e.message})`)}})(),this.#n}run(e,t={}){let r=t.preview;if(!r)return Promise.reject(/* @__PURE__ */ Error(`React needs a <code-playpad> widget to render in.`));this.dispose(r.host);let i,a=t.files??{},o=new Promise((e,t)=>{let a=n().runtimeURL;i=new d(r,{...a?{runtimeURL:a}:{vendor:this.#t},nonce:n().nonce},e,t)});return this.#r.set(r.host,i),this.#i.set(o,i),this.#a(i,a,t.entry??`index.html`),o}async#a(e,t,n){try{await this.load();let r=this.#e,i;try{i=u(t,n,r)}catch(t){if(t instanceof r.CompileError){e.fail(t.reason,{file:t.file,...t.line?{line:t.line}:{},...t.column?{column:t.column}:{}},t.hint),e.showCompileBanner(t.hint);return}throw t}e.payload.modules=i.modules,e.payload.entries=i.entries,e.open(i.html)}catch(t){e.fail(t.message)}}stop(e){e&&this.#i.get(e)?.dispose(!0)}hasLivePreview(e){return this.#r.get(e)?.live??!1}dispose(e){this.#r.get(e)?.dispose(!0),this.#r.delete(e)}};export{f as reactRuntime};
|