@vizhub/runtime 0.4.0 → 0.5.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.
Files changed (70) hide show
  1. package/README.md +33 -21
  2. package/dist/{buildHTML.d.ts → build/build.d.ts} +5 -6
  3. package/dist/build/build.d.ts.map +1 -0
  4. package/dist/{determineRuntimeVersion.d.ts → build/determineRuntimeVersion.d.ts} +1 -1
  5. package/dist/build/determineRuntimeVersion.d.ts.map +1 -0
  6. package/dist/build/determineRuntimeVersion.test.d.ts.map +1 -0
  7. package/dist/build/index.d.ts +2 -0
  8. package/dist/build/index.d.ts.map +1 -0
  9. package/dist/build/types.d.ts +7 -0
  10. package/dist/build/types.d.ts.map +1 -0
  11. package/dist/createVizContent-BOSPq-Jv.cjs +207 -0
  12. package/dist/createVizContent-BOSPq-Jv.cjs.map +1 -0
  13. package/dist/createVizContent-DjJF2PT_.js +565 -0
  14. package/dist/createVizContent-DjJF2PT_.js.map +1 -0
  15. package/dist/index.cjs +1 -1
  16. package/dist/index.cjs.map +1 -1
  17. package/dist/index.d.ts +4 -11
  18. package/dist/index.d.ts.map +1 -1
  19. package/dist/index.js +168 -75
  20. package/dist/index.js.map +1 -1
  21. package/dist/{createRuntime.d.ts → orchestration/createRuntime.d.ts} +1 -2
  22. package/dist/orchestration/createRuntime.d.ts.map +1 -0
  23. package/dist/orchestration/generateRequestId.d.ts +2 -0
  24. package/dist/orchestration/generateRequestId.d.ts.map +1 -0
  25. package/dist/orchestration/setupBuild.d.ts +10 -0
  26. package/dist/orchestration/setupBuild.d.ts.map +1 -0
  27. package/dist/orchestration/setupInvalidateVizCache.d.ts +3 -0
  28. package/dist/orchestration/setupInvalidateVizCache.d.ts.map +1 -0
  29. package/dist/{types.d.ts → orchestration/types.d.ts} +26 -14
  30. package/dist/orchestration/types.d.ts.map +1 -0
  31. package/dist/orchestration/worker.d.ts.map +1 -0
  32. package/dist/test/end-to-end.test.d.ts +2 -0
  33. package/dist/test/end-to-end.test.d.ts.map +1 -0
  34. package/dist/test/orchestration.test.d.ts +2 -0
  35. package/dist/test/orchestration.test.d.ts.map +1 -0
  36. package/dist/test/testInBrowser.d.ts.map +1 -1
  37. package/dist/test/testMockedIframeWithWorker.d.ts +2 -1
  38. package/dist/test/testMockedIframeWithWorker.d.ts.map +1 -1
  39. package/dist/test/testRuntimeWithWorker.d.ts +4 -3
  40. package/dist/test/testRuntimeWithWorker.d.ts.map +1 -1
  41. package/dist/test/testStackTrace.d.ts.map +1 -1
  42. package/dist/v3/computeBundleJSV3.d.ts +2 -2
  43. package/dist/v3/computeBundleJSV3.d.ts.map +1 -1
  44. package/dist/v3/htmlTemplate.d.ts.map +1 -1
  45. package/dist/v3/index.d.ts +9 -0
  46. package/dist/v3/index.d.ts.map +1 -1
  47. package/dist/v3/v3Build.d.ts +2 -1
  48. package/dist/v3/v3Build.d.ts.map +1 -1
  49. package/dist/v4/bundleModule.d.ts.map +1 -1
  50. package/dist/worker.cjs +8 -1
  51. package/dist/worker.cjs.map +1 -1
  52. package/dist/worker.js +354 -55
  53. package/dist/worker.js.map +1 -1
  54. package/package.json +4 -2
  55. package/dist/buildHTML.d.ts.map +0 -1
  56. package/dist/createRuntime.d.ts.map +0 -1
  57. package/dist/determineRuntimeVersion.d.ts.map +0 -1
  58. package/dist/determineRuntimeVersion.test.d.ts.map +0 -1
  59. package/dist/slugCache-Bt1Sipcs.cjs +0 -214
  60. package/dist/slugCache-Bt1Sipcs.cjs.map +0 -1
  61. package/dist/slugCache-CxGQFqi6.js +0 -841
  62. package/dist/slugCache-CxGQFqi6.js.map +0 -1
  63. package/dist/test/iframeWorkerManagement.test.d.ts +0 -2
  64. package/dist/test/iframeWorkerManagement.test.d.ts.map +0 -1
  65. package/dist/test/v3-hot-reloading.test.d.ts +0 -2
  66. package/dist/test/v3-hot-reloading.test.d.ts.map +0 -1
  67. package/dist/types.d.ts.map +0 -1
  68. package/dist/worker.d.ts.map +0 -1
  69. /package/dist/{determineRuntimeVersion.test.d.ts → build/determineRuntimeVersion.test.d.ts} +0 -0
  70. /package/dist/{worker.d.ts → orchestration/worker.d.ts} +0 -0
@@ -1,214 +0,0 @@
1
- "use strict";const b=require("magic-sandbox"),V=require("sucrase"),g=require("@vizhub/viz-utils"),J=e=>{if(Object.keys(e).length===0)return null;const t="index.html"in e,n="index.js"in e,r="index.jsx"in e;return t?e["index.html"].includes('type="module"')?"v4":n||r?"v2":"v1":!t&&n?"v3":null},R={dependencies:{},vizhub:{},license:"MIT"},D=!1,E=e=>{const t=e["package.json"];try{const n=t?JSON.parse(t):R;return D&&console.log("[packageJSON] pkg:",JSON.stringify(n,null,2)),n}catch{return R}},$=e=>E(e).dependencies||{},I=e=>(E(e).vizhub||{}).libraries||{},O=({name:e,version:t},n,r="jsdelivr")=>{const s=n[e]&&n[e].path||"";return r==="jsdelivr"?`https://cdn.jsdelivr.net/npm/${e}@${t}${s}`:`https://unpkg.com/${e}@${t}${s}`},B=e=>{var n;const t=(n=e==null?void 0:e.vizhub)==null?void 0:n.libraries;return t?Object.entries(t).reduce((r,[s,o])=>(o.global&&(r[s]=o.global),r),{}):{}},A={d3:"d3",react:"React","react-dom":"ReactDOM"},F=e=>{const t=B(e);return{...A,...t}},y=(e,t)=>new RegExp(`<${t}\\b`,"i").test(e)&&new RegExp(`</${t}>`,"i").test(e),q=e=>{const t=e.trim();return y(t,"html")&&y(t,"head")&&y(t,"body")?t:`<html><head></head><body>${t}</body></html>`},_=(e,t)=>e.replace(new RegExp(`<script[^>]*src=["'][^"']*${t.source}[^"']*["'][^>]*>\\s*<\/script>`,"gi"),""),T=(e,t,n)=>e.replace(new RegExp(t,"i"),`${n}${t}`),Y=(e,t)=>{let n=q(e);const r=Object.entries($(t));if(r.length){const o=I(t);r.forEach(([c])=>{n=_(n,new RegExp(`${c}@`))});const i=r.map(([c,a])=>O({name:c,version:a},o)).map(c=>`<script src="${c}"><\/script>`).join(`
2
- `);n=T(n,"</head>",i+`
3
- `)}if(t["bundle.js"]!==void 0||t["index.js"]!==void 0){const o='<script src="bundle.js"><\/script>',i=/<script\b[^>]*\bsrc=["']bundle\.js["'][^>]*>\s*<\/script>/gi,c=[...n.matchAll(i)];c.length===1&&(()=>{const l=c[0].index??-1;if(l===-1)return!1;const d=n.search(/<body\b[^>]*>/i),m=n.search(/<\/body>/i);return d!==-1&&m!==-1&&l>d&&l<m})()||(n=n.replace(i,""),n=T(n,"</body>",o))}return/^\s*<!DOCTYPE/i.test(n)?n:`<!DOCTYPE html>${n}`},G=e=>{const t=e["index.html"];return!t&&!e["index.js"]&&!e["bundle.js"]?"":Y(t||"<!DOCTYPE html><html><head></head><body></body></html>",e)},M=e=>{let t=e.replace(/^\.\//,"");return t=t.replace(/\/+/g,"/"),t=t.replace(/\/$/,""),t},H=(e,t)=>{const n=e.includes("/")?e.slice(0,e.lastIndexOf("/")):"",r=t.split("/"),s=n?n.split("/"):[];for(const o of r)o===".."?s.pop():o!=="."&&o!==""&&s.push(o);return s.join("/")},k=e=>({name:"virtual-file-system",resolveId(t,n){if(t.startsWith("./")||t.startsWith("../")){const s=M(n?H(n,t):t);if(e[s])return s;const o=[".js",".jsx",".ts",".tsx"];for(const i of o){const c=s+i;if(e[c])return c}}if(e[t])return t;const r=[".js",".jsx",".ts",".tsx"];for(const s of r){const o=t+s;if(e[o])return o}return null},load(t){return e[t]?e[t]:null}});function C(){return{name:"sucrase",transform(e,t){if(!t.match(/\.(?:js|[jt]sx)$/))return null;const n=V.transform(e,{transforms:["jsx","typescript"],filePath:t,sourceMapOptions:{compiledFilename:"bundle.js"},production:!0});return{code:n.code,map:n.sourceMap}}}}const Q=async({files:e,rollup:t,enableSourcemap:n=!0})=>{if(!e["index.js"])throw new Error("Missing index.js");const s={input:"./index.js",plugins:[k(e),C()],onwarn(l,d){l.code!=="UNRESOLVED_IMPORT"&&d(l)}},o={format:"iife",sourcemap:n},i=E(e);if(i){const l=F(i);l&&(s.external=Object.keys(l),o.globals=l)}const c=await t(s),{output:a}=await c.generate(o);return a[0].code},Z=async({files:e,rollup:t,enableSourcemap:n})=>({...e,"bundle.js":await Q({files:e,rollup:t,enableSourcemap:n}),"index.html":G(e)}),x=e=>{const[t,...n]=e.split("/"),r=n.join("/");return{vizId:t,fileName:r}},K=`var EOL = {},
4
- EOF = {},
5
- QUOTE = 34,
6
- NEWLINE = 10,
7
- RETURN = 13;
8
-
9
- function objectConverter(columns) {
10
- return new Function(
11
- 'd',
12
- 'return {' +
13
- columns
14
- .map(function (name, i) {
15
- return (
16
- JSON.stringify(name) + ': d[' + i + '] || ""'
17
- );
18
- })
19
- .join(',') +
20
- '}',
21
- );
22
- }
23
-
24
- function customConverter(columns, f) {
25
- var object = objectConverter(columns);
26
- return function (row, i) {
27
- return f(object(row), i, columns);
28
- };
29
- }
30
-
31
- function dsv(delimiter) {
32
- var DELIMITER = delimiter.charCodeAt(0);
33
-
34
- function parse(text, f) {
35
- var convert,
36
- columns,
37
- rows = parseRows(text, function (row, i) {
38
- if (convert) return convert(row, i - 1);
39
- (columns = row),
40
- (convert = f
41
- ? customConverter(row, f)
42
- : objectConverter(row));
43
- });
44
- rows.columns = columns || [];
45
- return rows;
46
- }
47
-
48
- function parseRows(text, f) {
49
- var rows = [], // output rows
50
- N = text.length,
51
- I = 0, // current character index
52
- n = 0, // current line number
53
- t, // current token
54
- eof = N <= 0, // current token followed by EOF?
55
- eol = false; // current token followed by EOL?
56
-
57
- // Strip the trailing newline.
58
- if (text.charCodeAt(N - 1) === NEWLINE) --N;
59
- if (text.charCodeAt(N - 1) === RETURN) --N;
60
-
61
- function token() {
62
- if (eof) return EOF;
63
- if (eol) return (eol = false), EOL;
64
-
65
- // Unescape quotes.
66
- var i,
67
- j = I,
68
- c;
69
- if (text.charCodeAt(j) === QUOTE) {
70
- while (
71
- (I++ < N && text.charCodeAt(I) !== QUOTE) ||
72
- text.charCodeAt(++I) === QUOTE
73
- );
74
- if ((i = I) >= N) eof = true;
75
- else if ((c = text.charCodeAt(I++)) === NEWLINE)
76
- eol = true;
77
- else if (c === RETURN) {
78
- eol = true;
79
- if (text.charCodeAt(I) === NEWLINE) ++I;
80
- }
81
- return text.slice(j + 1, i - 1).replace(/""/g, '"');
82
- }
83
-
84
- // Find next delimiter or newline.
85
- while (I < N) {
86
- if ((c = text.charCodeAt((i = I++))) === NEWLINE)
87
- eol = true;
88
- else if (c === RETURN) {
89
- eol = true;
90
- if (text.charCodeAt(I) === NEWLINE) ++I;
91
- } else if (c !== DELIMITER) continue;
92
- return text.slice(j, i);
93
- }
94
-
95
- // Return last token before EOF.
96
- return (eof = true), text.slice(j, N);
97
- }
98
-
99
- while ((t = token()) !== EOF) {
100
- var row = [];
101
- while (t !== EOL && t !== EOF)
102
- row.push(t), (t = token());
103
- if (f && (row = f(row, n++)) == null) continue;
104
- rows.push(row);
105
- }
106
-
107
- return rows;
108
- }
109
-
110
- return {
111
- parse: parse,
112
- };
113
- }
114
-
115
- var csv = dsv(',');
116
-
117
- var csvParse = csv.parse;
118
-
119
- var tsv = dsv(' ');
120
-
121
- var tsvParse = tsv.parse;
122
-
123
- export { csvParse, tsvParse };`,X=e=>e.replace(/\\/g,"\\\\").replace(/`/g,"\\`"),tt=()=>({name:"transformDSV",transform:async(e,t)=>{const{fileName:n}=x(t),r=n.endsWith(".csv"),s=n.endsWith(".tsv");if(r||s)return{code:`
124
- ${K}
125
- const data = ${r?"csvParse":"tsvParse"}(\`${X(e)}\`);
126
- export default data;
127
- `,map:{mappings:""}}}}),et=e=>{const t=/^@([a-zA-Z0-9_-]+)\/([a-zA-Z0-9_-]+)$/,n=e.match(t);return n?{userName:n[1],idOrSlug:n[2]}:null},nt=({vizId:e,slugCache:t})=>({name:"vizResolve",resolveId:async(n,r)=>{if(n.startsWith("./")&&!(r!=null&&r.startsWith("https://"))){let o=n.substring(2);if(!o.endsWith(".js")&&!o.endsWith(".css")&&!o.endsWith(".csv")&&!o.endsWith(".svelte")&&(o+=".js"),r){const{vizId:i,fileName:c}=x(r),a=c.split("/").slice(0,-1).join("/"),l=a?`${a}/${o}`:o;return`${i}/${l}`}return e+"/"+o}const s=et(n);if(s){let o;if(g.isVizId(s.idOrSlug))o=s.idOrSlug;else{if(!t)throw new Error("slugCache is required to import by slug in v3 runtime");o=await t.get(`${s.userName}/${s.idOrSlug}`)}return o+"/index.js"}}}),rt=({vizCache:e,trackCSSImport:t})=>({name:"vizLoad",load:async n=>{const{vizId:r,fileName:s}=x(n);if(s.endsWith(".css"))return t(n),"";const o=await e.get(r),i=g.getFileText(o,s);if(i===null)throw new Error(`Imported file "${s}" not found.`);return i}}),P=new Map;let j;const v="https://cdn.jsdelivr.net/npm/svelte@4.2.9",st=`${v}/compiler.cjs`,ot=({getSvelteCompiler:e})=>({name:"transformSvelte",load:async t=>{if(!t.startsWith(v))return;const n=P.get(t);if(n)return n;const r=await fetch(t).then(s=>s.text());return P.set(t,r),r},resolveId:async(t,n)=>{if(t==="svelte")return`${v}/src/runtime/index.js`;if(t.startsWith("svelte/")){const r=t.slice(7);return`${v}/src/runtime/${r}/index.js`}if(/^https?:/.test(t))return t;if(t.startsWith(".")&&n&&n.startsWith(v)){const r=new URL(t,n).href;return new URL(t,n).href,r}},transform:async(t,n)=>{const{fileName:r}=x(n);if(r.endsWith(".svelte")){if(!j){if(!e)throw new Error("Svelte compiler not available");j=await e()}return j(t,{filename:r,hydratable:!0}).js}}}),it=async({files:e,rollup:t,enableSourcemap:n=!0,vizCache:r,vizId:s,slugCache:o,getSvelteCompiler:i})=>{const c=new Set,a=u=>{c.add(u)};if(!e["index.js"])throw new Error("Missing index.js");const d={input:"./index.js",plugins:[...s?[nt({vizId:s,slugCache:o})]:[],tt(),C(),ot({getSvelteCompiler:i}),...r?[rt({vizCache:r,trackCSSImport:a})]:[]],onwarn(u,w){u.code!=="UNRESOLVED_IMPORT"&&w(u)}},m={format:"umd",name:"Viz",sourcemap:!!n,compact:!0},p=E(e);if(p){const u=F(p);u&&(d.external=Object.keys(u),m.globals=u)}const f=await t(d),{output:h}=await f.generate(m);return{src:h[0].code,cssFiles:Array.from(c)}};function ct(){return Math.random().toString().slice(2,7)}const at=({cdn:e,src:t,styles:n})=>{const s=`viz-container-${ct()}`;return`<!DOCTYPE html>
128
- <html>
129
- <head>
130
- <meta charset="utf-8">${e}${n}
131
- <style>
132
- body {
133
- margin: 0;
134
- overflow: hidden;
135
- }
136
- #${s} {
137
- height: 100vh;
138
- }
139
- </style>
140
- </head>
141
- <body>
142
- <div id="${s}"></div>
143
- <script id="injected-script">${t}<\/script>
144
- <script>
145
- (() => {
146
- let cleanup;
147
- const render = () => {
148
- const container = document.getElementById('${s}');
149
- typeof cleanup === 'function' && cleanup();
150
- cleanup = Viz.main(container, { state: window.state, setState, writeFile });
151
- };
152
- const setState = (next) => {
153
- window.state = next(window.state);
154
- render();
155
- };
156
- const writeFile = (fileName, content) => {
157
- parent.postMessage({ type: 'writeFile', fileName, content }, "*");
158
- };
159
- const run = () => {
160
- try {
161
- setState((state) => state || {});
162
- } catch (error) {
163
- console.error(error);
164
- parent.postMessage({ type: 'runError', error }, "*");
165
- }
166
- }
167
- run();
168
- const runJS = (src) => {
169
- document.getElementById('injected-script')?.remove();
170
- const script = document.createElement('script');
171
- script.textContent = src;
172
- script.id = 'injected-script';
173
- document.body.appendChild(script);
174
- run();
175
- };
176
- const runCSS = (src, id) => {
177
- const styleElementId = 'injected-style' + id;
178
- let style = document.getElementById(styleElementId);
179
- if (!style) {
180
- style = document.createElement('style');
181
- style.type = 'text/css';
182
- style.id = styleElementId;
183
- document.head.appendChild(style);
184
- }
185
- style.textContent = src;
186
- };
187
- onmessage = (message) => {
188
- switch (message.data.type) {
189
- case 'runJS':
190
- runJS(message.data.src);
191
- parent.postMessage({ type: 'runDone' }, "*");
192
- break;
193
- case 'runCSS':
194
- runCSS(message.data.src, message.data.id);
195
- break;
196
- case 'ping':
197
- parent.postMessage({ type: 'pong' }, "*");
198
- break;
199
- default:
200
- break;
201
- }
202
- }
203
- })();
204
- <\/script>
205
- </body>
206
- </html>`},lt=async({files:e,rollup:t,enableSourcemap:n=!0,vizCache:r,vizId:s,slugCache:o,getSvelteCompiler:i})=>{const{src:c,cssFiles:a}=await it({files:e,rollup:t,enableSourcemap:n,vizCache:r,vizId:s,slugCache:o,getSvelteCompiler:i});let l="";if(a.length>0)for(let p=0;p<a.length;p++){const f=a[p],h=p>0?" ":`
207
- `,u="injected-style"+f,{vizId:w,fileName:N}=x(f),U=await r.get(w),W=g.getFileText(U,N);l+=`${h}<style id="${u}">${W}</style>`}let d="";const m=Object.entries($(e));if(m.length>0){const p=I(e);d=m.map(([f,h],u)=>{const w=O({name:f,version:h},p);return`${u>0?" ":`
208
- `}<script src="${w}"><\/script>`}).join("")}return at({cdn:d,src:c,styles:l})},ut=e=>{const t=[],n=/<script\b([^>]*)>[\s\S]*?<\/script>/gi;let r;for(;(r=n.exec(e))!==null;){const s=r[1];if(!/\btype\s*=\s*["']module["']/i.test(s))continue;const o=s.match(/\bsrc\s*=\s*["']([^"']+)["']/i);o&&t.push(o[1])}return t},dt=async({entryPoint:e,files:t,rollup:n,enableSourcemap:r=!0})=>{const s={input:`./${e}`,plugins:[k(t),C()],external:c=>(console.log("external",c),t[c]?!1:!c.startsWith("./")),onwarn(c,a){c.code!=="UNRESOLVED_IMPORT"&&a(c)}},o=await n(s),{output:i}=await o.generate({format:"es",sourcemap:r});return i[0].code},S=(e,t)=>new RegExp(`<${t}\\b`,"i").test(e)&&new RegExp(`</${t}>`,"i").test(e),pt=e=>{const t=e.trim();return S(t,"html")&&S(t,"head")&&S(t,"body")?t:`<html><head></head><body>${t}</body></html>`},mt=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),ft=(e,t,n)=>e.replace(new RegExp(t,"i"),`${n}${t}`),ht=e=>{const t=$(e);if(Object.keys(t).length===0)return null;const n=I(e),r={};for(const[s,o]of Object.entries(t))r[s]=O({name:s,version:o},n);return JSON.stringify({imports:r},null,2)},wt=(e,t)=>{if(!e["index.html"])return"";let n=pt(e["index.html"]);t.forEach((s,o)=>{const i=new RegExp(`<script\\b[^>]*\\bsrc=["']${mt(o)}["'][^>]*>[^<]*<\/script>`,"gi");n=n.replace(i,`<script type="module">
209
- ${s}
210
- <\/script>`)});const r=ht(e);if(r&&!/<script\b[^>]*type=["']importmap["'][^>]*>/i.test(n)){const o=`<script type="importmap">
211
- ${r}
212
- <\/script>
213
- `;n=ft(n,"</head>",o)}return/^\s*<!DOCTYPE/i.test(n)?n:`<!DOCTYPE html>${n}`},vt=async({files:e,rollup:t,enableSourcemap:n=!0})=>{const r=e["index.html"]||"",s=ut(r);if(s.length===0)return e;const o=new Map;for(const c of s){const a=await dt({entryPoint:c,files:e,rollup:t,enableSourcemap:n});o.set(c,a)}const i=wt(e,o);return{...e,"index.html":i}},L=({initialContents:e,handleCacheMiss:t})=>{const n=new Map(e.map(i=>[i.id,i]));return{get:async i=>{const c=n.get(i);if(c!==void 0)return c;if(!t)throw new Error(`Unresolved import from vizId ${i}, cache miss handler not provided.`);const a=await t(i);if(a)return n.set(i,a),a;throw new Error(`Unresolved import from vizId ${i}`)},set:i=>{n.set(i.id,i)},invalidate:i=>{n.delete(i)}}},z=(e,t="Sample Content for Exporting")=>{const n=g.generateVizId(),r={};return Object.entries(e).forEach(([s,o])=>{const i=Math.floor(Math.random()*1e7).toString();r[i]={name:s,text:o}}),{id:n,files:r,title:t}},gt=async({files:e,rollup:t,enableSourcemap:n=!0,vizCache:r,vizId:s,slugCache:o,getSvelteCompiler:i})=>{var a;if(!e&&!r)throw new Error("Either files or vizCache is required");if(!e&&r&&!s)throw new Error("vizId is required when using vizCache");if(!e&&r&&s&&(e=g.vizFilesToFileCollection((a=await r.get(s))==null?void 0:a.files)),!e)throw new Error("Upable to extract viz files");const c=J(e);if(c==="v1")return b.magicSandbox(e);if(c==="v2"){if(!t)throw new Error("Rollup is required for v2 runtime");return b.magicSandbox(await Z({files:e,rollup:t,enableSourcemap:n}))}if(c==="v3"){if(!t)throw new Error("Rollup is required for v3 runtime");if(!r&&!s){const l=z(e);s=l.id,r=L({initialContents:[l],handleCacheMiss:async()=>{throw new Error("Cache miss handler not implemented")}})}if(!r)throw new Error("vizCache is required for v3 runtime");if(!s)throw new Error("vizId is required for v3 runtime");return await lt({files:e,rollup:t,vizCache:r,vizId:s,slugCache:o,getSvelteCompiler:i})}if(c==="v4"){if(!t)throw new Error("Rollup is required for v4 runtime");return b.magicSandbox(await vt({files:e,rollup:t,enableSourcemap:n}))}throw new Error(`Unsupported runtime version: ${c}`)},xt=({initialMappings:e={},handleCacheMiss:t})=>{const n=new Map(Object.entries(e));return{get:async i=>{const c=n.get(i);if(c!==void 0)return c;if(!t)throw new Error(`Unresolved slug ${i}, cache miss handler not provided.`);const a=await t(i);if(a)return n.set(i,a),a;throw new Error(`Unresolved slug ${i}`)},set:(i,c)=>{n.set(i,c)},invalidate:i=>{n.delete(i)}}};exports.buildHTML=gt;exports.createSlugCache=xt;exports.createVizCache=L;exports.createVizContent=z;exports.svelteCompilerUrl=st;
214
- //# sourceMappingURL=slugCache-Bt1Sipcs.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"slugCache-Bt1Sipcs.cjs","sources":["../src/determineRuntimeVersion.ts","../src/common/packageJson.ts","../src/v2/getComputedIndexHtml.ts","../src/common/virtualFileSystem.ts","../src/common/sucrasePlugin.ts","../src/v2/computeBundleJSV2.ts","../src/v2/v2Build.ts","../src/v3/parseId.ts","../src/v3/transformDSV/dsvParseSrc.ts","../src/v3/transformDSV/index.ts","../src/v3/extractVizImport.ts","../src/v3/vizResolve.ts","../src/v3/vizLoad.ts","../src/v3/transformSvelte.ts","../src/v3/computeBundleJSV3.ts","../src/v3/htmlTemplate.ts","../src/v3/v3Build.ts","../src/v4/extractEntryPoints.ts","../src/v4/bundleModule.ts","../src/v4/stringUtils.ts","../src/v4/importMap.ts","../src/v4/updateHTML.ts","../src/v4/index.ts","../src/v3/vizCache.ts","../src/v3/createVizContent.ts","../src/buildHTML.ts","../src/v3/slugCache.ts"],"sourcesContent":["import { FileCollection } from \"@vizhub/viz-types\";\nimport type { runtimeVersion } from \"./types\";\n\nexport const determineRuntimeVersion = (\n files: FileCollection,\n): runtimeVersion | null => {\n if (Object.keys(files).length === 0) {\n return null;\n }\n\n const hasIndexHTML = \"index.html\" in files;\n\n const hasIndexJS = \"index.js\" in files;\n const hasIndexJSX = \"index.jsx\" in files;\n\n if (hasIndexHTML) {\n const hasModuleScript =\n files[\"index.html\"].includes('type=\"module\"');\n if (hasModuleScript) {\n return \"v4\";\n }\n\n if (hasIndexJS || hasIndexJSX) {\n return \"v2\";\n }\n return \"v1\";\n }\n\n if (!hasIndexHTML && hasIndexJS) {\n return \"v3\";\n }\n\n return null;\n};\n","import { FileCollection } from \"@vizhub/viz-types\";\n\nexport type Licence = string;\n\nexport interface PackageJson {\n dependencies?: {\n [key: string]: string;\n };\n vizhub?: {\n libraries?: {\n [key: string]: VizHubLibraryConfig;\n };\n };\n license?: Licence | { type: string };\n}\n\nconst EMPTY_PKG_JSON: PackageJson = {\n dependencies: {},\n vizhub: {},\n license: \"MIT\",\n};\n\nexport interface Dependency {\n name: string;\n version: string;\n}\n\nexport interface VizHubLibraryConfig {\n path?: string;\n global?: string;\n}\n\nexport interface VizHubLibraryConfigs {\n [key: string]: VizHubLibraryConfig;\n}\n\nconst DEBUG = false;\n\nexport const packageJSON = (\n files: FileCollection,\n): PackageJson => {\n const packageJsonText = files[\"package.json\"];\n DEBUG &&\n console.log(\n \"[packageJSON] packageJsonText:\",\n packageJsonText,\n );\n try {\n const pkg = packageJsonText\n ? JSON.parse(packageJsonText)\n : EMPTY_PKG_JSON;\n DEBUG &&\n console.log(\n \"[packageJSON] pkg:\",\n JSON.stringify(pkg, null, 2),\n );\n return pkg;\n } catch {\n DEBUG &&\n console.log(\n \"[packageJSON] Error parsing package.json\",\n );\n return EMPTY_PKG_JSON;\n }\n};\n\nexport const dependencies = (files: FileCollection) =>\n packageJSON(files).dependencies || {};\n\nexport const getConfiguredLibraries = (\n files: FileCollection,\n) => {\n const vizhubConfig = packageJSON(files).vizhub || {};\n return vizhubConfig.libraries || {};\n};\n\nexport const dependencySource = (\n { name, version }: Dependency,\n libraries: VizHubLibraryConfigs,\n cdn = \"jsdelivr\",\n) => {\n const path = libraries[name]\n ? libraries[name].path || \"\"\n : \"\";\n const src =\n cdn === \"jsdelivr\"\n ? `https://cdn.jsdelivr.net/npm/${name}@${version}${path}`\n : `https://unpkg.com/${name}@${version}${path}`;\n return src;\n};\n\nexport const getLicense = (files: FileCollection) => {\n const license = packageJSON(files).license;\n if (\n typeof license === \"object\" &&\n license !== null &&\n \"type\" in license\n ) {\n return license.type;\n }\n return license || EMPTY_PKG_JSON.license;\n};\n\nexport const getConfiguredGlobals = (\n pkg: PackageJson,\n): Record<string, string> => {\n const libraries = pkg?.vizhub?.libraries;\n if (libraries) {\n return Object.entries(libraries).reduce(\n (accumulator, [packageName, config]) => {\n if (config.global) {\n accumulator[packageName] = config.global;\n }\n return accumulator;\n },\n {} as Record<string, string>,\n );\n }\n return {};\n};\n\nconst defaultGlobals = {\n d3: \"d3\",\n react: \"React\",\n \"react-dom\": \"ReactDOM\",\n};\n\nexport const getGlobals = (\n pkg: PackageJson,\n): Record<string, string> => {\n const configuredGlobals = getConfiguredGlobals(pkg);\n\n return {\n ...defaultGlobals,\n ...configuredGlobals,\n };\n};\n","import { FileCollection } from \"@vizhub/viz-types\";\nimport {\n dependencies,\n getConfiguredLibraries,\n dependencySource,\n} from \"../common/packageJson\";\n\nconst DEBUG = false;\n\n/* ------------------------------------------------------------------ */\n/* tiny helpers */\n/* ------------------------------------------------------------------ */\n\nconst hasTagPair = (html: string, tag: string) =>\n new RegExp(`<${tag}\\\\b`, \"i\").test(html) &&\n new RegExp(`</${tag}>`, \"i\").test(html);\n\n/** Make sure we have a complete <html><head></head><body></body> skeleton. */\nconst normaliseSkeleton = (raw: string): string => {\n const trimmed = raw.trim();\n\n // If it already contains a *complete* html‑head‑body trio we keep it.\n if (\n hasTagPair(trimmed, \"html\") &&\n hasTagPair(trimmed, \"head\") &&\n hasTagPair(trimmed, \"body\")\n )\n return trimmed;\n\n // Otherwise wrap whatever is there inside a fresh skeleton.\n return `<html><head></head><body>${trimmed}</body></html>`;\n};\n\n/** Remove every script whose src matches the supplied RegExp (global & i). */\nconst stripScripts = (\n html: string,\n srcPattern: RegExp,\n): string =>\n html.replace(\n new RegExp(\n `<script[^>]*src=[\"'][^\"']*${srcPattern.source}[^\"']*[\"'][^>]*>\\\\s*</script>`,\n \"gi\",\n ),\n \"\",\n );\n\n/** Inject markup just before a closing tag (</head> or </body>). */\nconst injectBeforeClose = (\n html: string,\n closing: \"</head>\" | \"</body>\",\n markup: string,\n) =>\n html.replace(\n new RegExp(closing, \"i\"),\n `${markup}${closing}`,\n );\n\n/* ------------------------------------------------------------------ */\n/* core logic */\n/* ------------------------------------------------------------------ */\n\nconst injectScripts = (\n template: string,\n files: FileCollection,\n): string => {\n let html = normaliseSkeleton(template);\n\n /* -------------------- dependencies from package.json ------------ */\n const deps = Object.entries(dependencies(files)) as [\n string,\n string,\n ][];\n\n if (deps.length) {\n const libraries = getConfiguredLibraries(files);\n\n // Remove any previous dependency scripts\n deps.forEach(([name]) => {\n html = stripScripts(html, new RegExp(`${name}@`));\n });\n\n // Build & inject new ones (order preserved)\n const depMarkup = deps\n .map(([name, version]) =>\n dependencySource({ name, version }, libraries),\n )\n .map((src) => `<script src=\"${src}\"></script>`)\n .join(\"\\n\");\n\n html = injectBeforeClose(\n html,\n \"</head>\",\n depMarkup + \"\\n\",\n );\n }\n\n /* -------------------- ensure exactly ONE bundle.js -------------- */\n const needBundle =\n files[\"bundle.js\"] !== undefined ||\n files[\"index.js\"] !== undefined;\n\n if (needBundle) {\n const bundleTag = `<script src=\"bundle.js\"></script>`; // **no newline – keeps test #3 exact**\n\n // How many bundle.js scripts are already there & where?\n const bundleRe =\n /<script\\b[^>]*\\bsrc=[\"']bundle\\.js[\"'][^>]*>\\s*<\\/script>/gi;\n const matches = [...html.matchAll(bundleRe)];\n\n const oneInBody =\n matches.length === 1 &&\n (() => {\n const idx = matches[0].index ?? -1;\n if (idx === -1) return false;\n const bodyOpen = html.search(/<body\\b[^>]*>/i);\n const bodyClose = html.search(/<\\/body>/i);\n return (\n bodyOpen !== -1 &&\n bodyClose !== -1 &&\n idx > bodyOpen &&\n idx < bodyClose\n );\n })();\n\n if (!oneInBody) {\n // wipe them all, then inject a clean one at the end of <body>\n html = html.replace(bundleRe, \"\");\n html = injectBeforeClose(html, \"</body>\", bundleTag);\n }\n }\n\n /* -------------------- make sure <!DOCTYPE html> ----------------- */\n return /^\\s*<!DOCTYPE/i.test(html)\n ? html\n : `<!DOCTYPE html>${html}`;\n};\n\n/* ------------------------------------------------------------------ */\n/* public API */\n/* ------------------------------------------------------------------ */\n\nexport const getComputedIndexHtml = (\n files: FileCollection,\n): string => {\n const htmlTemplate = files[\"index.html\"];\n\n // No html and no JS – nothing to do.\n if (\n !htmlTemplate &&\n !files[\"index.js\"] &&\n !files[\"bundle.js\"]\n ) {\n DEBUG &&\n console.log(\n \"[getComputedIndexHtml] No index.html file found\",\n );\n return \"\";\n }\n\n const template =\n htmlTemplate ||\n \"<!DOCTYPE html><html><head></head><body></body></html>\";\n\n const result = injectScripts(template, files);\n\n DEBUG &&\n console.log(\"[getComputedIndexHtml] indexHtml\", result);\n\n return result;\n};\n","import { FileCollection } from \"@vizhub/viz-types\";\nimport { Plugin } from \"rollup\";\n\nconst normalizePath = (filepath: string): string => {\n // Remove leading ./\n let normalized = filepath.replace(/^\\.\\//, \"\");\n // Replace multiple slashes with single slash\n normalized = normalized.replace(/\\/+/g, \"/\");\n // Remove trailing slash\n normalized = normalized.replace(/\\/$/, \"\");\n return normalized;\n};\n\nconst joinPaths = (\n base: string,\n relative: string,\n): string => {\n // Get directory name of base path\n const baseDir = base.includes(\"/\")\n ? base.slice(0, base.lastIndexOf(\"/\"))\n : \"\";\n\n // Handle .. by removing one directory level\n const parts = relative.split(\"/\");\n const resultParts: string[] = baseDir\n ? baseDir.split(\"/\")\n : [];\n\n for (const part of parts) {\n if (part === \"..\") {\n resultParts.pop();\n } else if (part !== \".\" && part !== \"\") {\n resultParts.push(part);\n }\n }\n\n return resultParts.join(\"/\");\n};\n\nexport const virtualFileSystem = (\n files: FileCollection,\n): Plugin => {\n return {\n name: \"virtual-file-system\",\n\n resolveId(source: string, importer?: string) {\n // Handle relative paths\n if (\n source.startsWith(\"./\") ||\n source.startsWith(\"../\")\n ) {\n const resolvedPath = importer\n ? normalizePath(joinPaths(importer, source))\n : normalizePath(source);\n\n // Try exact match first\n if (files[resolvedPath]) {\n return resolvedPath;\n }\n\n // Try with extensions if no exact match is found\n const extensions = [\".js\", \".jsx\", \".ts\", \".tsx\"];\n for (const ext of extensions) {\n const pathWithExt = resolvedPath + ext;\n if (files[pathWithExt]) {\n return pathWithExt;\n }\n }\n }\n\n // Handle bare module imports\n if (files[source]) {\n return source;\n }\n\n // Try bare imports with extensions\n const extensions = [\".js\", \".jsx\", \".ts\", \".tsx\"];\n for (const ext of extensions) {\n const pathWithExt = source + ext;\n if (files[pathWithExt]) {\n return pathWithExt;\n }\n }\n\n return null;\n },\n\n load(id: string) {\n // Return the contents if the file exists in our virtual system\n if (files[id]) {\n return files[id];\n }\n\n return null;\n },\n };\n};\n","import { transform } from \"sucrase\";\nimport type { Plugin } from \"rollup\";\n\nexport function sucrasePlugin(): Plugin {\n return {\n name: \"sucrase\",\n transform(code, id) {\n // Transform .js, .jsx, and .tsx files\n if (!id.match(/\\.(?:js|[jt]sx)$/)) {\n return null;\n }\n\n const result = transform(code, {\n transforms: [\"jsx\", \"typescript\"],\n filePath: id, // For source maps\n sourceMapOptions: {\n compiledFilename: \"bundle.js\",\n },\n production: true,\n });\n\n return {\n code: result.code,\n map: result.sourceMap,\n };\n },\n };\n}\n","import type {\n RollupBuild,\n RollupOptions,\n OutputOptions,\n} from \"rollup\";\nimport { FileCollection } from \"@vizhub/viz-types\";\nimport { virtualFileSystem } from \"../common/virtualFileSystem.js\";\nimport { sucrasePlugin } from \"../common/sucrasePlugin.js\";\nimport {\n getGlobals,\n packageJSON,\n} from \"../common/packageJson.js\";\n\nexport const computeBundleJSV2 = async ({\n files,\n rollup,\n enableSourcemap = true,\n}: {\n files: FileCollection;\n rollup: (options: RollupOptions) => Promise<RollupBuild>;\n enableSourcemap?: boolean;\n}): Promise<string> => {\n const indexJSContent = files[\"index.js\"];\n if (!indexJSContent) {\n throw new Error(\"Missing index.js\");\n }\n\n const inputOptions: RollupOptions = {\n input: \"./index.js\",\n plugins: [virtualFileSystem(files), sucrasePlugin()],\n onwarn(warning, warn) {\n // Suppress \"treating module as external dependency\" warnings\n if (warning.code === \"UNRESOLVED_IMPORT\") return;\n warn(warning);\n },\n };\n\n const outputOptions: OutputOptions = {\n format: \"iife\",\n sourcemap: enableSourcemap,\n };\n\n const pkg = packageJSON(files);\n\n if (pkg) {\n const globals = getGlobals(pkg);\n if (globals) {\n inputOptions.external = Object.keys(globals);\n outputOptions.globals = globals;\n }\n }\n\n const bundle = await rollup(inputOptions);\n\n const { output } = await bundle.generate(outputOptions);\n return output[0].code;\n};\n","import type { RollupBuild, RollupOptions } from \"rollup\";\nimport { FileCollection } from \"@vizhub/viz-types\";\nimport { getComputedIndexHtml } from \"./getComputedIndexHtml\";\nimport { computeBundleJSV2 } from \"./computeBundleJSV2\";\n\nexport const v2Build = async ({\n files,\n rollup,\n enableSourcemap,\n}: {\n files: FileCollection;\n rollup: (options: RollupOptions) => Promise<RollupBuild>;\n enableSourcemap?: boolean;\n}): Promise<FileCollection> => ({\n ...files,\n \"bundle.js\": await computeBundleJSV2({\n files,\n rollup,\n enableSourcemap,\n }),\n \"index.html\": getComputedIndexHtml(files),\n});\n","import type { VizId } from \"@vizhub/viz-types\";\nimport type { ResolvedVizFileId } from \"./types\";\n\nexport const parseId = (\n id: ResolvedVizFileId,\n): {\n vizId: VizId;\n fileName: string;\n} => {\n const [vizId, ...fileNameParts] = id.split(\"/\");\n const fileName = fileNameParts.join(\"/\");\n return { vizId, fileName };\n};\n","export const dsvParseSrc = `var EOL = {},\n EOF = {},\n QUOTE = 34,\n NEWLINE = 10,\n RETURN = 13;\n\nfunction objectConverter(columns) {\n return new Function(\n 'd',\n 'return {' +\n columns\n .map(function (name, i) {\n return (\n JSON.stringify(name) + ': d[' + i + '] || \"\"'\n );\n })\n .join(',') +\n '}',\n );\n}\n\nfunction customConverter(columns, f) {\n var object = objectConverter(columns);\n return function (row, i) {\n return f(object(row), i, columns);\n };\n}\n\nfunction dsv(delimiter) {\n var DELIMITER = delimiter.charCodeAt(0);\n\n function parse(text, f) {\n var convert,\n columns,\n rows = parseRows(text, function (row, i) {\n if (convert) return convert(row, i - 1);\n (columns = row),\n (convert = f\n ? customConverter(row, f)\n : objectConverter(row));\n });\n rows.columns = columns || [];\n return rows;\n }\n\n function parseRows(text, f) {\n var rows = [], // output rows\n N = text.length,\n I = 0, // current character index\n n = 0, // current line number\n t, // current token\n eof = N <= 0, // current token followed by EOF?\n eol = false; // current token followed by EOL?\n\n // Strip the trailing newline.\n if (text.charCodeAt(N - 1) === NEWLINE) --N;\n if (text.charCodeAt(N - 1) === RETURN) --N;\n\n function token() {\n if (eof) return EOF;\n if (eol) return (eol = false), EOL;\n\n // Unescape quotes.\n var i,\n j = I,\n c;\n if (text.charCodeAt(j) === QUOTE) {\n while (\n (I++ < N && text.charCodeAt(I) !== QUOTE) ||\n text.charCodeAt(++I) === QUOTE\n );\n if ((i = I) >= N) eof = true;\n else if ((c = text.charCodeAt(I++)) === NEWLINE)\n eol = true;\n else if (c === RETURN) {\n eol = true;\n if (text.charCodeAt(I) === NEWLINE) ++I;\n }\n return text.slice(j + 1, i - 1).replace(/\"\"/g, '\"');\n }\n\n // Find next delimiter or newline.\n while (I < N) {\n if ((c = text.charCodeAt((i = I++))) === NEWLINE)\n eol = true;\n else if (c === RETURN) {\n eol = true;\n if (text.charCodeAt(I) === NEWLINE) ++I;\n } else if (c !== DELIMITER) continue;\n return text.slice(j, i);\n }\n\n // Return last token before EOF.\n return (eof = true), text.slice(j, N);\n }\n\n while ((t = token()) !== EOF) {\n var row = [];\n while (t !== EOL && t !== EOF)\n row.push(t), (t = token());\n if (f && (row = f(row, n++)) == null) continue;\n rows.push(row);\n }\n\n return rows;\n }\n\n return {\n parse: parse,\n };\n}\n\nvar csv = dsv(',');\n\nvar csvParse = csv.parse;\n\nvar tsv = dsv('\\t');\n\nvar tsvParse = tsv.parse;\n\nexport { csvParse, tsvParse };`;\n","import { InputPluginOption } from \"rollup\";\nimport type { ResolvedVizFileId } from \"../types\";\nimport { parseId } from \"../parseId\";\nimport { dsvParseSrc } from \"./dsvParseSrc.js\";\n\nconst DEBUG = false;\n\n// Escape backticks in a string so that it can be\n// used in a template literal. Also need to escape backslashes.\nconst escapeBackticks = (str: string) =>\n // str.replace(/`/g, '\\\\`');\n str.replace(/\\\\/g, \"\\\\\\\\\").replace(/`/g, \"\\\\`\");\n\n// Responsible for loading CSV and TSV files, which are\n// in general called Delimiter-Separated Values (DSV).\nexport const transformDSV = (): InputPluginOption => ({\n name: \"transformDSV\",\n\n // `id` here is of the form\n // `{vizId}/{fileName}`\n transform: async (\n text: string,\n id: ResolvedVizFileId,\n ) => {\n DEBUG && console.log(\"[transformDSV]: load() \" + id);\n const { vizId, fileName } = parseId(id);\n\n DEBUG &&\n console.log(\" [transformDSV] vizId: \" + vizId);\n DEBUG &&\n console.log(\" [transformDSV] fileName: \" + fileName);\n const isCSV = fileName.endsWith(\".csv\");\n const isTSV = fileName.endsWith(\".tsv\");\n if (isCSV || isTSV) {\n DEBUG &&\n console.log(\n \" [transformDSV] tracking DSV import for \" +\n id,\n );\n\n const parseFunction = isCSV ? \"csvParse\" : \"tsvParse\";\n\n return {\n code: `\n ${dsvParseSrc}\n const data = ${parseFunction}(\\`${escapeBackticks(text)}\\`);\n export default data;\n `,\n map: { mappings: \"\" },\n };\n }\n return undefined;\n },\n});\n","import { VizId } from \"@vizhub/viz-types\";\n\nexport type VizImport = {\n userName: string;\n idOrSlug: VizId | string;\n};\n\nexport const extractVizImport = (\n str: string,\n): VizImport | null => {\n // Updated regular expression pattern\n // Username: Alphanumeric characters, including underscores and hyphens\n // ID: Alphanumeric characters, including underscores, hyphens, and possibly other special characters\n const pattern = /^@([a-zA-Z0-9_-]+)\\/([a-zA-Z0-9_-]+)$/;\n const match = str.match(pattern);\n\n if (match) {\n // Extract the username and id\n return {\n userName: match[1],\n idOrSlug: match[2],\n };\n } else {\n // Return null if the string does not match\n return null;\n }\n};\n\n// // Example usages\n// const result1 = extractDetails(\"@curran/21f72bf74ef04ea0b9c9b82aaaec859a\");\n// console.log(result1); // { username: \"curran\", id: \"21f72bf74ef04ea0b9c9b82aaaec859a\" }\n\n// const result2 = extractDetails(\"@curran/scatter-plot\");\n// console.log(result2); // { username: \"curran\", id: \"scatter-plot\" }\n","// A custom Rollup plugin to:\n// * Implement a virtual file system\n// * Support importing across vizzes\n// Unified Rollup plugin for virtual file system and viz imports\n// Combines functionalities of 'virtual' and 'importFromViz' plugins\nimport { InputPluginOption } from \"rollup\";\nimport { VizId } from \"@vizhub/viz-types\";\nimport { isVizId } from \"@vizhub/viz-utils\";\nimport { extractVizImport } from \"./extractVizImport.js\";\nimport type { ResolvedVizFileId } from \"./types.js\";\nimport { parseId } from \"./parseId\";\nimport { SlugCache } from \"./slugCache.js\";\n\nconst debug = false;\n\nexport const vizResolve = ({\n vizId,\n slugCache,\n}: {\n vizId: VizId;\n slugCache?: SlugCache;\n}): InputPluginOption => ({\n name: \"vizResolve\",\n resolveId: async (\n id: string,\n importer: string | undefined,\n ): Promise<ResolvedVizFileId | undefined> => {\n if (debug) {\n console.log(\"[vizIdResolve] resolveId() \" + id);\n console.log(\" importer: \" + importer);\n }\n\n // Handle virtual file system resolution\n // .e.g. `import { foo } from './foo.js'`\n // .e.g. `import { foo } from './foo'`\n if (\n id.startsWith(\"./\") &&\n !importer?.startsWith(\"https://\")\n ) {\n let fileName = id.substring(2);\n\n // Handle CSS files\n // e.g. `import './styles.css'`\n // Handle JS files\n // e.g. `import { foo } from './foo.js'`\n // e.g. `import { foo } from './foo'`\n if (\n !fileName.endsWith(\".js\") &&\n !fileName.endsWith(\".css\") &&\n !fileName.endsWith(\".csv\") &&\n !fileName.endsWith(\".svelte\")\n ) {\n fileName += \".js\";\n }\n\n // const js = (name: string) =>\n // name.endsWith('.js') ? name : name + '.js';\n\n // If there is an importer, then the file is not part of\n // the entry point, so it should be resolved relative\n // to the importer's directory\n if (importer) {\n const {\n vizId: importerVizId,\n fileName: importerFileName,\n } = parseId(importer);\n // Get the directory of the importing file\n const importerDir = importerFileName\n .split(\"/\")\n .slice(0, -1)\n .join(\"/\");\n // Combine the directory with the imported file name\n const resolvedFileName = importerDir\n ? `${importerDir}/${fileName}`\n : fileName;\n return `${importerVizId}/${resolvedFileName}`;\n }\n return vizId + \"/\" + fileName;\n }\n\n // Handle viz import resolution\n // e.g. `import { foo } from '@curran/98e6d6509a1e407897d4f238a330efec'`\n // e.g. `import { foo } from '@curran/scatter-plot'`\n const vizImport = extractVizImport(id);\n if (vizImport) {\n let vizId: VizId;\n if (isVizId(vizImport.idOrSlug)) {\n vizId = vizImport.idOrSlug;\n } else {\n if (!slugCache) {\n throw new Error(\n \"slugCache is required to import by slug in v3 runtime\",\n );\n }\n\n vizId = await slugCache.get(\n `${vizImport.userName}/${vizImport.idOrSlug}`,\n );\n }\n return vizId + \"/index.js\";\n }\n\n // If neither condition is met, return undefined.\n return undefined;\n },\n});\n","import { InputPluginOption } from \"rollup\";\nimport { VizContent } from \"@vizhub/viz-types\";\nimport { getFileText } from \"@vizhub/viz-utils\";\nimport type { ResolvedVizFileId } from \"./types\";\nimport { parseId } from \"./parseId\";\nimport { VizCache } from \"./vizCache.js\";\n\nconst debug = false;\n\n// Responsible for loading all imports and\n// tracking which CSS files are imported.\n// Throws an error if a file is imported but not found.\nexport const vizLoad = ({\n vizCache,\n trackCSSImport,\n}: {\n vizCache: VizCache;\n trackCSSImport: (cssFile: ResolvedVizFileId) => void;\n}): InputPluginOption => ({\n name: \"vizLoad\",\n\n // `id` here is of the form\n // `{vizId}/{fileName}`\n load: async (id: ResolvedVizFileId) => {\n if (debug) {\n console.log(\"[vizLoadCSS]: load() \" + id);\n }\n\n const { vizId, fileName } = parseId(id);\n\n if (debug) {\n console.log(\" [vizLoadCSS] vizId: \" + vizId);\n console.log(\" [vizLoadCSS] fileName: \" + fileName);\n }\n\n // For CSS imports, all we need to do here is\n // keep track of them so they can be injected\n // into the IFrame later.\n if (fileName.endsWith(\".css\")) {\n if (debug) {\n console.log(\n \" [vizResolve] tracking CSS import for \" + id,\n );\n }\n // The import is tracked here so that it can be\n // injected into the IFrame later, external to the\n // Rollup build.\n trackCSSImport(id);\n // TODO consider using Rollup's `emitFile` to emit a CSS file.\n return \"\";\n }\n\n const content: VizContent = await vizCache.get(vizId);\n const fileText = getFileText(content, fileName);\n\n // If a file is imported but not found, throw an error.\n if (fileText === null) {\n throw new Error(\n `Imported file \"${fileName}\" not found.`,\n );\n // TODO ideally show username/slug instead of vizId\n // `Imported file \"${fileName}\" not found in viz ${vizId}`,\n // `Imported file \"${fileName}\" not found.`,\n // );\n }\n\n return fileText;\n },\n});\n","import type { InputPluginOption } from \"rollup\";\nimport { parseId } from \"./parseId\";\nimport type { ResolvedVizFileId } from \"./types\";\n\nconst debug = false;\n\n// The cache of fetched files.\nconst fetchedFileCache = new Map<string, string>();\n\n// The Svelte compiler.\nexport type SvelteCompiler = (\n code: string,\n options: any,\n) => { js: string };\nlet compile: SvelteCompiler;\n\nconst svelteURL =\n \"https://cdn.jsdelivr.net/npm/svelte@4.2.9\";\n\nexport const svelteCompilerUrl = `${svelteURL}/compiler.cjs`;\n\n// Responsible for transforming Svelte files.\n// Inspired by:\n// * https://github.com/sveltejs/sites/blob/master/packages/repl/src/lib/workers/compiler/index.js#L2\n// * https://github.com/sveltejs/sites/blob/master/packages/repl/src/lib/workers/bundler/index.js#L358\n// * https://github.com/sveltejs/rollup-plugin-svelte/blob/master/index.js#L146C4-L146C51\nexport const transformSvelte = ({\n getSvelteCompiler,\n}: {\n getSvelteCompiler?: () => Promise<any>;\n}): InputPluginOption => ({\n name: \"transformSvelte\",\n\n load: async (resolved: string) => {\n if (!resolved.startsWith(svelteURL)) {\n return;\n }\n if (debug) {\n console.log(\"[transformSvelte]: load() \" + resolved);\n }\n\n const cachedFile = fetchedFileCache.get(resolved);\n if (cachedFile) return cachedFile;\n\n const fetchedFile = await fetch(resolved).then((res) =>\n res.text(),\n );\n\n fetchedFileCache.set(resolved, fetchedFile);\n\n return fetchedFile;\n },\n\n // From https://github.com/sveltejs/sites/blob/master/packages/repl/src/lib/workers/bundler/index.js#L255C2-L271C5\n resolveId: async (importee, importer) => {\n if (debug) {\n console.log(\n \"[transformSvelte] resolveId() \" + importee,\n );\n console.log(\"importee: \" + importee);\n console.log(\"importer: \" + importer);\n }\n // importing from Svelte\n if (importee === `svelte`) {\n return `${svelteURL}/src/runtime/index.js`;\n }\n if (importee.startsWith(`svelte/`)) {\n const sub_path = importee.slice(7);\n return `${svelteURL}/src/runtime/${sub_path}/index.js`;\n }\n\n // importing from a URL\n if (/^https?:/.test(importee)) return importee;\n\n // Relative imports\n if (importee.startsWith(\".\")) {\n if (importer && importer.startsWith(svelteURL)) {\n const resolved = new URL(importee, importer).href;\n const url = new URL(importee, importer).href;\n if (debug) {\n console.log(\n \"[transformSvelte] resolveId() \" + resolved,\n );\n }\n return resolved;\n }\n }\n },\n\n transform: async (\n code: string,\n id: ResolvedVizFileId,\n ) => {\n const { fileName } = parseId(id);\n\n const isSvelte = fileName.endsWith(\".svelte\");\n\n if (isSvelte) {\n if (!compile) {\n if (!getSvelteCompiler) {\n throw new Error(\"Svelte compiler not available\");\n }\n compile = await getSvelteCompiler();\n }\n\n const compiled = compile(code, {\n filename: fileName,\n hydratable: true,\n });\n\n return compiled.js;\n }\n return undefined;\n },\n});\n","import { sucrasePlugin } from \"../common/sucrasePlugin\";\nimport type {\n RollupBuild,\n RollupOptions,\n OutputOptions,\n} from \"rollup\";\nimport { FileCollection, VizId } from \"@vizhub/viz-types\";\nimport {\n getGlobals,\n packageJSON,\n} from \"../common/packageJson.js\";\nimport { transformDSV } from \"./transformDSV/index.js\";\nimport { vizResolve } from \"./vizResolve.js\";\nimport { VizCache } from \"./vizCache.js\";\nimport { vizLoad } from \"./vizLoad.js\";\nimport { SlugCache } from \"./slugCache.js\";\nimport {\n SvelteCompiler,\n transformSvelte,\n} from \"./transformSvelte.js\";\n\nexport const computeBundleJSV3 = async ({\n files,\n rollup,\n enableSourcemap = true,\n vizCache,\n vizId,\n slugCache,\n getSvelteCompiler,\n}: {\n files: FileCollection;\n rollup: (options: RollupOptions) => Promise<RollupBuild>;\n enableSourcemap?: boolean;\n vizCache: VizCache;\n vizId: VizId;\n slugCache?: SlugCache;\n getSvelteCompiler?: () => Promise<SvelteCompiler>;\n}): Promise<{ src: string; cssFiles: string[] }> => {\n // Track CSS imports\n const cssFilesSet = new Set<string>();\n const trackCSSImport = (cssFile: string) => {\n cssFilesSet.add(cssFile);\n };\n const indexJSContent = files[\"index.js\"];\n if (!indexJSContent) {\n throw new Error(\"Missing index.js\");\n }\n\n const inputOptions: RollupOptions = {\n input: \"./index.js\",\n plugins: [\n ...(vizId ? [vizResolve({ vizId, slugCache })] : []),\n transformDSV(),\n sucrasePlugin(),\n transformSvelte({ getSvelteCompiler }),\n ...(vizCache\n ? [vizLoad({ vizCache, trackCSSImport })]\n : []),\n ],\n onwarn(warning, warn) {\n // Suppress \"treating module as external dependency\" warnings\n if (warning.code === \"UNRESOLVED_IMPORT\") return;\n warn(warning);\n },\n };\n\n const outputOptions: OutputOptions = {\n format: \"umd\",\n name: \"Viz\",\n sourcemap: enableSourcemap ? true : false,\n compact: true,\n };\n\n const pkg = packageJSON(files);\n if (pkg) {\n const globals = getGlobals(pkg);\n if (globals) {\n inputOptions.external = Object.keys(globals);\n outputOptions.globals = globals;\n }\n }\n\n const bundle = await rollup(inputOptions);\n\n const { output } = await bundle.generate(outputOptions);\n return {\n src: output[0].code,\n cssFiles: Array.from(cssFilesSet),\n };\n};\n","function randomDigits() {\n return Math.random().toString().slice(2, 7);\n}\n\nexport const htmlTemplate = ({\n cdn,\n src,\n styles,\n}: {\n cdn: string;\n src: string;\n styles: string;\n}) => {\n // Random container id to avoid conflicts and guarantee\n // the code is portable.\n const containerSuffix = randomDigits();\n\n const vizContainerId = `viz-container-${containerSuffix}`;\n\n return `<!DOCTYPE html>\n<html>\n<head>\n <meta charset=\"utf-8\">${cdn}${styles}\n <style>\n body {\n margin: 0;\n overflow: hidden;\n }\n #${vizContainerId} {\n height: 100vh;\n }\n </style>\n</head>\n<body>\n <div id=\"${vizContainerId}\"></div>\n <script id=\"injected-script\">${src}</script>\n <script>\n (() => {\n let cleanup;\n const render = () => {\n const container = document.getElementById('${vizContainerId}');\n typeof cleanup === 'function' && cleanup();\n cleanup = Viz.main(container, { state: window.state, setState, writeFile });\n };\n const setState = (next) => {\n window.state = next(window.state);\n render();\n };\n const writeFile = (fileName, content) => {\n parent.postMessage({ type: 'writeFile', fileName, content }, \"*\");\n };\n const run = () => {\n try {\n setState((state) => state || {});\n } catch (error) {\n console.error(error);\n parent.postMessage({ type: 'runError', error }, \"*\");\n }\n }\n run();\n const runJS = (src) => {\n document.getElementById('injected-script')?.remove();\n const script = document.createElement('script');\n script.textContent = src;\n script.id = 'injected-script';\n document.body.appendChild(script);\n run();\n };\n const runCSS = (src, id) => {\n const styleElementId = 'injected-style' + id;\n let style = document.getElementById(styleElementId);\n if (!style) {\n style = document.createElement('style');\n style.type = 'text/css';\n style.id = styleElementId;\n document.head.appendChild(style);\n }\n style.textContent = src;\n };\n onmessage = (message) => {\n switch (message.data.type) {\n case 'runJS':\n runJS(message.data.src);\n parent.postMessage({ type: 'runDone' }, \"*\");\n break;\n case 'runCSS':\n runCSS(message.data.src, message.data.id);\n break;\n case 'ping':\n parent.postMessage({ type: 'pong' }, \"*\");\n break;\n default:\n break;\n }\n }\n })();\n </script>\n</body>\n</html>`;\n};\n","import { RollupBuild, RollupOptions } from \"rollup\";\nimport { getFileText } from \"@vizhub/viz-utils\";\nimport { computeBundleJSV3 } from \"./computeBundleJSV3\";\nimport { htmlTemplate } from \"./htmlTemplate\";\nimport { VizCache } from \"./vizCache.js\";\nimport { FileCollection, VizId } from \"@vizhub/viz-types\";\nimport { parseId } from \"./parseId.js\";\nimport { ResolvedVizFileId } from \"./types.js\";\nimport { SlugCache } from \"./slugCache.js\";\nimport { SvelteCompiler } from \"./transformSvelte.js\";\nimport {\n dependencies,\n getConfiguredLibraries,\n dependencySource,\n} from \"../common/packageJson\";\n\nexport const v3Build = async ({\n files,\n rollup,\n enableSourcemap = true,\n vizCache,\n vizId,\n slugCache,\n getSvelteCompiler,\n}: {\n files: FileCollection;\n rollup: (options: RollupOptions) => Promise<RollupBuild>;\n enableSourcemap?: boolean;\n vizCache: VizCache;\n vizId: VizId;\n slugCache?: SlugCache;\n getSvelteCompiler?: () => Promise<SvelteCompiler>;\n}): Promise<string> => {\n const { src, cssFiles } = await computeBundleJSV3({\n files,\n rollup,\n enableSourcemap,\n vizCache,\n vizId,\n slugCache,\n getSvelteCompiler,\n });\n\n // Generate CSS styles from imported CSS files\n let styles = \"\";\n\n // Inject CSS files.\n if (cssFiles.length > 0) {\n for (let i = 0; i < cssFiles.length; i++) {\n const id: ResolvedVizFileId = cssFiles[i];\n const indent = i > 0 ? \" \" : \"\\n \";\n const styleElementId = \"injected-style\" + id;\n const { vizId, fileName } = parseId(id);\n const content = await vizCache.get(vizId);\n const src = getFileText(content, fileName);\n styles += `${indent}<style id=\"${styleElementId}\">${src}</style>`;\n }\n }\n\n // Generate CDN script tags for dependencies\n let cdn = \"\";\n const deps: [string, string][] = Object.entries(\n dependencies(files),\n );\n if (deps.length > 0) {\n const libraries = getConfiguredLibraries(files);\n cdn = deps\n .map(([name, version], i) => {\n const src = dependencySource(\n { name, version },\n libraries,\n );\n const indent = i > 0 ? \" \" : \"\\n \";\n return `${indent}<script src=\"${src}\"></script>`;\n })\n .join(\"\");\n }\n\n return htmlTemplate({ cdn, src, styles });\n};\n","/**\n * Extract module script entry points from index.html\n */\nexport const extractModuleEntryPoints = (\n html: string,\n): string[] => {\n const entryPoints: string[] = [];\n const scriptTag = /<script\\b([^>]*)>[\\s\\S]*?<\\/script>/gi;\n let m: RegExpExecArray | null;\n\n while ((m = scriptTag.exec(html)) !== null) {\n const attrs = m[1];\n if (!/\\btype\\s*=\\s*[\"']module[\"']/i.test(attrs))\n continue;\n const srcMatch = attrs.match(\n /\\bsrc\\s*=\\s*[\"']([^\"']+)[\"']/i,\n );\n if (srcMatch) entryPoints.push(srcMatch[1]);\n }\n return entryPoints;\n};\n","import type {\n RollupBuild,\n RollupOptions,\n OutputOptions,\n} from \"rollup\";\nimport { FileCollection } from \"@vizhub/viz-types\";\nimport { virtualFileSystem } from \"..//common/virtualFileSystem.js\";\nimport { sucrasePlugin } from \"..//common/sucrasePlugin.js\";\nimport { dependencies } from \"../common/packageJson.js\";\n\n/**\n * Bundle a single ES module entry point\n */\nexport const bundleESModule = async ({\n entryPoint,\n files,\n rollup,\n enableSourcemap = true,\n}: {\n entryPoint: string;\n files: FileCollection;\n rollup: (o: RollupOptions) => Promise<RollupBuild>;\n enableSourcemap?: boolean;\n}): Promise<string> => {\n const inputOptions: RollupOptions = {\n input: `./${entryPoint}`,\n plugins: [virtualFileSystem(files), sucrasePlugin()],\n external: (source: string) => {\n console.log(\"external\", source);\n if (files[source]) return false; // Treat all files in the collection as external{\n // external ./greeter.js\n return !source.startsWith(\"./\");\n // return files[source] === undefined; // Treat all files not in the collection as external\n },\n onwarn(w, warn) {\n if (w.code === \"UNRESOLVED_IMPORT\") return; // quiet noisy warnings\n warn(w);\n },\n };\n\n const bundle = await rollup(inputOptions);\n const { output } = await bundle.generate({\n format: \"es\",\n sourcemap: enableSourcemap,\n } as OutputOptions);\n\n return output[0].code;\n};\n","/**\n * Does the html already contain a <tag>…</tag> pair?\n */\nexport const hasTagPair = (html: string, tag: string) =>\n new RegExp(`<${tag}\\\\b`, \"i\").test(html) &&\n new RegExp(`</${tag}>`, \"i\").test(html);\n\n/**\n * Ensure <html><head></head><body></body> skeleton exists.\n */\nexport const normaliseSkeleton = (raw: string): string => {\n const trimmed = raw.trim();\n\n if (\n hasTagPair(trimmed, \"html\") &&\n hasTagPair(trimmed, \"head\") &&\n hasTagPair(trimmed, \"body\")\n )\n return trimmed;\n\n return `<html><head></head><body>${trimmed}</body></html>`;\n};\n\n/**\n * Escape characters so they can appear literally inside a RegExp.\n */\nexport const escapeRegExp = (s: string) =>\n s.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n\n/**\n * Inject markup immediately before </head> or </body>.\n */\nexport const injectBeforeClose = (\n html: string,\n closing: \"</head>\" | \"</body>\",\n markup: string,\n) =>\n html.replace(\n new RegExp(closing, \"i\"),\n `${markup}${closing}`,\n );\n","import { FileCollection } from \"@vizhub/viz-types\";\nimport {\n dependencies,\n getConfiguredLibraries,\n dependencySource,\n} from \"../common/packageJson.js\";\n\n/**\n * Generate an import map for all dependencies\n */\nexport const generateImportMap = (\n files: FileCollection,\n): string | null => {\n const deps = dependencies(files);\n if (Object.keys(deps).length === 0) return null;\n\n const libraries = getConfiguredLibraries(files);\n const imports: Record<string, string> = {};\n\n for (const [name, version] of Object.entries(deps)) {\n imports[name] = dependencySource(\n { name, version },\n libraries,\n );\n }\n return JSON.stringify({ imports }, null, 2);\n};\n","import { FileCollection } from \"@vizhub/viz-types\";\nimport {\n normaliseSkeleton,\n escapeRegExp,\n injectBeforeClose,\n} from \"./stringUtils.js\";\nimport { generateImportMap } from \"./importMap.js\";\n\n/**\n * Update HTML to include import map and bundled modules\n */\nexport const updateHTML = (\n files: FileCollection,\n bundled: Map<string, string>,\n): string => {\n if (!files[\"index.html\"]) return \"\";\n\n let html = normaliseSkeleton(files[\"index.html\"]);\n\n // Replace each <script src=\"…\"> with inline module\n bundled.forEach((code, src) => {\n const tagRe = new RegExp(\n `<script\\\\b[^>]*\\\\bsrc=[\"']${escapeRegExp(src)}[\"'][^>]*>[^<]*</script>`,\n \"gi\",\n );\n html = html.replace(\n tagRe,\n `<script type=\"module\">\\n${code}\\n</script>`,\n );\n });\n\n // Add <script type=\"importmap\"> if needed\n const importMapJson = generateImportMap(files);\n if (importMapJson) {\n const already =\n /<script\\b[^>]*type=[\"']importmap[\"'][^>]*>/i.test(\n html,\n );\n\n if (!already) {\n const importMapTag = `<script type=\"importmap\">\\n${importMapJson}\\n</script>\\n`;\n html = injectBeforeClose(\n html,\n \"</head>\",\n importMapTag,\n );\n }\n }\n\n // Ensure <!DOCTYPE html>\n return /^\\s*<!DOCTYPE/i.test(html)\n ? html\n : `<!DOCTYPE html>${html}`;\n};\n","import type { RollupBuild, RollupOptions } from \"rollup\";\nimport { FileCollection } from \"@vizhub/viz-types\";\nimport { extractModuleEntryPoints } from \"./extractEntryPoints.js\";\nimport { bundleESModule } from \"./bundleModule.js\";\nimport { updateHTML } from \"./updateHTML.js\";\n\nconst DEBUG = false;\n\n/**\n * Build for v4 runtime\n */\nexport const v4Build = async ({\n files,\n rollup,\n enableSourcemap = true,\n}: {\n files: FileCollection;\n rollup: (o: RollupOptions) => Promise<RollupBuild>;\n enableSourcemap?: boolean;\n}): Promise<FileCollection> => {\n const html = files[\"index.html\"] || \"\";\n const entryPoints = extractModuleEntryPoints(html);\n\n if (entryPoints.length === 0) {\n DEBUG &&\n console.log(\"[v4Build] No module entry points found\");\n return files; // nothing to bundle\n }\n\n const bundled = new Map<string, string>();\n for (const entry of entryPoints) {\n const code = await bundleESModule({\n entryPoint: entry,\n files,\n rollup,\n enableSourcemap,\n });\n bundled.set(entry, code);\n }\n\n const updatedHTML = updateHTML(files, bundled);\n\n return {\n ...files,\n \"index.html\": updatedHTML,\n };\n};\n\n// Export the extractModuleEntryPoints function for external use\nexport { extractModuleEntryPoints };\n","import { VizContent, VizId } from \"@vizhub/viz-types\";\n\nexport type VizCache = {\n get: (vizId: string) => Promise<VizContent>;\n set: (content: VizContent) => void;\n invalidate: (vizId: string) => void;\n};\n\n// A cache of viz content.\n// For use in resolving imports from other vizzes.\n// Runs both on the server and in the browser.\nexport const createVizCache = ({\n initialContents,\n handleCacheMiss,\n}: {\n initialContents: Array<VizContent>;\n handleCacheMiss?: (vizId: VizId) => Promise<VizContent>;\n}): VizCache => {\n // Track the content of cached vizzes.\n const contentMap = new Map<VizId, VizContent>(\n initialContents.map((content) => [content.id, content]),\n );\n\n // Gets the content of a viz.\n // Returns the cached content if it exists.\n // Otherwise, calls handleCacheMiss to fetch the content.\n const get = async (\n vizId: string,\n ): Promise<VizContent> => {\n const cachedContent: VizContent | undefined =\n contentMap.get(vizId);\n\n // Cache hit\n if (cachedContent !== undefined) {\n return cachedContent;\n }\n\n // Cache miss\n if (!handleCacheMiss) {\n throw new Error(\n `Unresolved import from vizId ${vizId}, cache miss handler not provided.`,\n );\n }\n const freshContent = await handleCacheMiss(vizId);\n\n if (freshContent) {\n contentMap.set(vizId, freshContent);\n return freshContent;\n }\n\n // TODO surface this error to the user\n throw new Error(\n `Unresolved import from vizId ${vizId}`,\n );\n };\n\n // Updates the content of a viz in the cache.\n const set = (content: VizContent) => {\n contentMap.set(content.id, content);\n };\n\n const invalidate = (vizId: VizId) => {\n contentMap.delete(vizId);\n };\n\n return { get, set, invalidate };\n};\n","import {\n FileCollection,\n VizContent,\n} from \"@vizhub/viz-types\";\nimport { generateVizId } from \"@vizhub/viz-utils\";\n\n/**\n * Creates a VizContent object with the given files\n * @param files An object with file names as keys and file content as values\n * @param title Optional title for the content\n * @returns A VizContent object with randomly generated IDs\n */\nexport const createVizContent = (\n files: FileCollection,\n title = \"Sample Content for Exporting\",\n): VizContent => {\n const contentId = generateVizId();\n\n const contentFiles: Record<\n string,\n { name: string; text: string }\n > = {};\n\n Object.entries(files).forEach(\n ([fileName, fileContent]) => {\n const fileId = Math.floor(\n Math.random() * 10000000,\n ).toString();\n contentFiles[fileId] = {\n name: fileName,\n text: fileContent,\n };\n },\n );\n\n return {\n id: contentId,\n files: contentFiles,\n title,\n };\n};\n","import { magicSandbox } from \"magic-sandbox\";\nimport { FileCollection } from \"@vizhub/viz-types\";\nimport type { RollupBuild, RollupOptions } from \"rollup\";\nimport { determineRuntimeVersion } from \"./determineRuntimeVersion.js\";\nimport { v2Build } from \"./v2/index.js\";\nimport { v3Build } from \"./v3/index.js\";\nimport { v4Build } from \"./v4/index.js\";\nimport { createVizCache, VizCache } from \"./v3/vizCache.js\";\nimport { createVizContent } from \"./v3/createVizContent.js\";\nimport { SlugCache } from \"./v3/slugCache.js\";\nimport { SvelteCompiler } from \"./v3/transformSvelte.js\";\nimport { vizFilesToFileCollection } from \"@vizhub/viz-utils\";\n\nconst DEBUG = false;\n\nexport const buildHTML = async ({\n files,\n rollup,\n enableSourcemap = true,\n vizCache,\n vizId,\n slugCache,\n getSvelteCompiler,\n}: {\n // Only required for v1 and v2 runtime\n // For v3, EITHER files OR vizCache is required\n files?: FileCollection;\n\n // Only required for v2 and v3 runtime\n rollup?: (options: RollupOptions) => Promise<RollupBuild>;\n enableSourcemap?: boolean;\n\n // Only required for v3 runtime\n // For v3, EITHER files OR vizCache is required\n vizCache?: VizCache;\n\n // Only required for v3 runtime\n vizId?: string;\n\n // Only required for v3 runtime\n slugCache?: SlugCache;\n\n // Only required for v3 runtime\n getSvelteCompiler?: () => Promise<SvelteCompiler>;\n}): Promise<string> => {\n DEBUG &&\n console.log(\n \"[buildHTML] files:\",\n JSON.stringify(files).substring(0, 100),\n );\n DEBUG && console.log(\"[buildHTML] vizCache:\", vizCache);\n DEBUG && console.log(\"[buildHTML] vizId:\", vizId);\n\n if (!files && !vizCache) {\n throw new Error(\"Either files or vizCache is required\");\n }\n\n if (!files && vizCache && !vizId) {\n throw new Error(\n \"vizId is required when using vizCache\",\n );\n }\n\n if (!files && vizCache && vizId) {\n files = vizFilesToFileCollection(\n (await vizCache.get(vizId))?.files,\n );\n }\n\n if (!files) {\n throw new Error(\"Upable to extract viz files\");\n }\n\n const version = determineRuntimeVersion(files);\n DEBUG && console.log(\"[buildHTML] version:\", version);\n if (version === \"v1\") {\n return magicSandbox(files);\n }\n if (version === \"v2\") {\n if (!rollup) {\n throw new Error(\"Rollup is required for v2 runtime\");\n }\n return magicSandbox(\n await v2Build({ files, rollup, enableSourcemap }),\n );\n }\n if (version === \"v3\") {\n if (!rollup) {\n throw new Error(\"Rollup is required for v3 runtime\");\n }\n\n if (!vizCache && !vizId) {\n const vizContent = createVizContent(files);\n vizId = vizContent.id;\n vizCache = createVizCache({\n initialContents: [vizContent],\n handleCacheMiss: async () => {\n throw new Error(\n \"Cache miss handler not implemented\",\n );\n },\n });\n }\n\n if (!vizCache) {\n throw new Error(\n \"vizCache is required for v3 runtime\",\n );\n }\n\n if (!vizId) {\n throw new Error(\"vizId is required for v3 runtime\");\n }\n\n return await v3Build({\n files,\n rollup,\n vizCache,\n vizId,\n slugCache,\n getSvelteCompiler,\n });\n }\n\n if (version === \"v4\") {\n if (!rollup) {\n throw new Error(\"Rollup is required for v4 runtime\");\n }\n DEBUG &&\n console.log(\"[buildHTML] v4Build\", {\n files,\n rollup,\n enableSourcemap,\n });\n return magicSandbox(\n await v4Build({ files, rollup, enableSourcemap }),\n );\n }\n\n throw new Error(\n `Unsupported runtime version: ${version}`,\n );\n};\n","import { VizId } from \"@vizhub/viz-types\";\n\nexport type SlugIdentifier = `${string}/${string}`;\n\nexport type SlugCache = {\n get: (slug: SlugIdentifier) => Promise<VizId>;\n set: (slug: SlugIdentifier, vizId: VizId) => void;\n invalidate: (slug: SlugIdentifier) => void;\n};\n\n// A cache of viz IDs for slug resolution.\n// Maps slug strings (username/slug) to viz IDs.\nexport const createSlugCache = ({\n initialMappings = {},\n handleCacheMiss,\n}: {\n initialMappings?: Record<SlugIdentifier, VizId>;\n handleCacheMiss?: (\n slug: SlugIdentifier,\n ) => Promise<VizId>;\n}): SlugCache => {\n // Track the mapping of slugs to viz IDs\n const slugMap = new Map<SlugIdentifier, VizId>(\n Object.entries(initialMappings) as [\n SlugIdentifier,\n VizId,\n ][],\n );\n\n // Gets the viz ID for a slug.\n // Returns the cached ID if it exists.\n // Otherwise, calls handleCacheMiss to resolve the slug.\n const get = async (\n slug: SlugIdentifier,\n ): Promise<VizId> => {\n const cachedVizId: VizId | undefined =\n slugMap.get(slug);\n\n // Cache hit\n if (cachedVizId !== undefined) {\n return cachedVizId;\n }\n\n // Cache miss\n if (!handleCacheMiss) {\n throw new Error(\n `Unresolved slug ${slug}, cache miss handler not provided.`,\n );\n }\n\n const resolvedVizId = await handleCacheMiss(slug);\n\n if (resolvedVizId) {\n slugMap.set(slug, resolvedVizId);\n return resolvedVizId;\n }\n\n throw new Error(`Unresolved slug ${slug}`);\n };\n\n // Updates the mapping of a slug to a viz ID in the cache.\n const set = (slug: SlugIdentifier, vizId: VizId) => {\n slugMap.set(slug, vizId);\n };\n\n // Removes a slug mapping from the cache.\n const invalidate = (slug: SlugIdentifier) => {\n slugMap.delete(slug);\n };\n\n return { get, set, invalidate };\n};\n"],"names":["determineRuntimeVersion","files","hasIndexHTML","hasIndexJS","hasIndexJSX","EMPTY_PKG_JSON","DEBUG","packageJSON","packageJsonText","pkg","dependencies","getConfiguredLibraries","dependencySource","name","version","libraries","cdn","path","getConfiguredGlobals","_a","accumulator","packageName","config","defaultGlobals","getGlobals","configuredGlobals","hasTagPair","html","tag","normaliseSkeleton","raw","trimmed","stripScripts","srcPattern","injectBeforeClose","closing","markup","injectScripts","template","deps","depMarkup","src","bundleTag","bundleRe","matches","idx","bodyOpen","bodyClose","getComputedIndexHtml","htmlTemplate","normalizePath","filepath","normalized","joinPaths","base","relative","baseDir","parts","resultParts","part","virtualFileSystem","source","importer","resolvedPath","extensions","ext","pathWithExt","id","sucrasePlugin","code","result","transform","computeBundleJSV2","rollup","enableSourcemap","inputOptions","warning","warn","outputOptions","globals","bundle","output","v2Build","parseId","vizId","fileNameParts","fileName","dsvParseSrc","escapeBackticks","str","transformDSV","text","isCSV","isTSV","extractVizImport","pattern","match","vizResolve","slugCache","importerVizId","importerFileName","importerDir","resolvedFileName","vizImport","isVizId","vizLoad","vizCache","trackCSSImport","content","fileText","getFileText","fetchedFileCache","compile","svelteURL","svelteCompilerUrl","transformSvelte","getSvelteCompiler","resolved","cachedFile","fetchedFile","res","importee","sub_path","computeBundleJSV3","cssFilesSet","cssFile","randomDigits","styles","vizContainerId","v3Build","cssFiles","i","indent","styleElementId","extractModuleEntryPoints","entryPoints","scriptTag","m","attrs","srcMatch","bundleESModule","entryPoint","w","escapeRegExp","s","generateImportMap","imports","updateHTML","bundled","tagRe","importMapJson","importMapTag","v4Build","entry","updatedHTML","createVizCache","initialContents","handleCacheMiss","contentMap","cachedContent","freshContent","createVizContent","title","contentId","generateVizId","contentFiles","fileContent","fileId","buildHTML","vizFilesToFileCollection","magicSandbox","vizContent","createSlugCache","initialMappings","slugMap","slug","cachedVizId","resolvedVizId"],"mappings":"kGAGaA,EACXC,GAC0B,CAC1B,GAAI,OAAO,KAAKA,CAAK,EAAE,SAAW,EACzB,OAAA,KAGT,MAAMC,EAAe,eAAgBD,EAE/BE,EAAa,aAAcF,EAC3BG,EAAc,cAAeH,EAEnC,OAAIC,EAEAD,EAAM,YAAY,EAAE,SAAS,eAAe,EAErC,KAGLE,GAAcC,EACT,KAEF,KAGL,CAACF,GAAgBC,EACZ,KAGF,IACT,ECjBME,EAA8B,CAClC,aAAc,CAAC,EACf,OAAQ,CAAC,EACT,QAAS,KACX,EAgBMC,EAAQ,GAEDC,EACXN,GACgB,CACV,MAAAO,EAAkBP,EAAM,cAAc,EAMxC,GAAA,CACF,MAAMQ,EAAMD,EACR,KAAK,MAAMA,CAAe,EAC1BH,EACJ,OAAAC,GACE,QAAQ,IACN,qBACA,KAAK,UAAUG,EAAK,KAAM,CAAC,CAC7B,EACKA,CAAA,MACD,CAKC,OAAAJ,CAAA,CAEX,EAEaK,EAAgBT,GAC3BM,EAAYN,CAAK,E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