@vizhub/runtime 0.3.0 → 0.3.2

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 (260) hide show
  1. package/dist/cjs/buildHTML.js +71 -0
  2. package/dist/cjs/common/packageJson.js +81 -0
  3. package/dist/cjs/common/packageJson.test.js +148 -0
  4. package/dist/cjs/common/sucrasePlugin.js +27 -0
  5. package/dist/cjs/common/virtualFileSystem.js +79 -0
  6. package/dist/cjs/determineRuntimeVersion.js +26 -0
  7. package/dist/cjs/determineRuntimeVersion.test.js +103 -0
  8. package/dist/cjs/index.js +9 -0
  9. package/dist/cjs/package.json +1 -0
  10. package/dist/cjs/test/fixtures/v1/basicHTML.js +18 -0
  11. package/dist/cjs/test/fixtures/v1/fetchProxy.js +15 -0
  12. package/dist/cjs/test/fixtures/v1/index.js +15 -0
  13. package/dist/cjs/test/fixtures/v1/jsScriptTag.js +12 -0
  14. package/dist/cjs/test/fixtures/v1/protocolTest.js +18 -0
  15. package/dist/cjs/test/fixtures/v1/styleTest.js +18 -0
  16. package/dist/cjs/test/fixtures/v1/xmlTest.js +22 -0
  17. package/dist/cjs/test/fixtures/v2/basicBundle.js +8 -0
  18. package/dist/cjs/test/fixtures/v2/basicBundleNoExtension.js +8 -0
  19. package/dist/cjs/test/fixtures/v2/d3Import.js +10 -0
  20. package/dist/cjs/test/fixtures/v2/d3ImportPkg.js +22 -0
  21. package/dist/cjs/test/fixtures/v2/d3RosettaImportPkg.js +22 -0
  22. package/dist/cjs/test/fixtures/v2/es6Preserve.js +9 -0
  23. package/dist/cjs/test/fixtures/v2/generatorSupport.js +9 -0
  24. package/dist/cjs/test/fixtures/v2/index.js +45 -0
  25. package/dist/cjs/test/fixtures/v2/jsxTranspile.js +9 -0
  26. package/dist/cjs/test/fixtures/v2/reactDomImport.js +11 -0
  27. package/dist/cjs/test/fixtures/v2/reactDomImportPkg.js +27 -0
  28. package/dist/cjs/test/fixtures/v2/reactImport.js +10 -0
  29. package/dist/cjs/test/fixtures/v2/reactImportPkg.js +20 -0
  30. package/dist/cjs/test/fixtures/v2/sourceMapErrorFixture.js +22 -0
  31. package/dist/cjs/test/fixtures/v2/unicodeSupport.js +9 -0
  32. package/dist/cjs/test/fixtures/v3/basicIndexJS.js +10 -0
  33. package/dist/cjs/test/fixtures/v3/cssImport.js +12 -0
  34. package/dist/cjs/test/fixtures/v3/csvImport.js +14 -0
  35. package/dist/cjs/test/fixtures/v3/csvStrangeChars.js +15 -0
  36. package/dist/cjs/test/fixtures/v3/index.js +25 -0
  37. package/dist/cjs/test/fixtures/v3/jsExport.js +13 -0
  38. package/dist/cjs/test/fixtures/v3/sourcemap.js +13 -0
  39. package/dist/cjs/test/fixtures/v3/svelte.js +21 -0
  40. package/dist/cjs/test/fixtures/v3/vizContent.js +14 -0
  41. package/dist/cjs/test/fixtures/v3/vizImport.js +88 -0
  42. package/dist/cjs/test/fixtures/v4/d3Usage.js +34 -0
  43. package/dist/cjs/test/fixtures/v4/esmBuild.js +21 -0
  44. package/dist/cjs/test/fixtures/v4/fetchInterception.js +21 -0
  45. package/dist/cjs/test/fixtures/v4/index.js +21 -0
  46. package/dist/cjs/test/fixtures/v4/jsScriptTagTypeModule.js +21 -0
  47. package/dist/cjs/test/fixtures/v4/jsScriptTagTypeModules.js +15 -0
  48. package/dist/cjs/test/fixtures/v4/reactHooks.js +50 -0
  49. package/dist/cjs/test/fixtures/v4/reactJsx.js +37 -0
  50. package/dist/cjs/test/fixtures/v4/threeJsUsage.js +27 -0
  51. package/dist/cjs/test/fixtures/v4/typeScriptSupport.js +32 -0
  52. package/dist/cjs/test/testInBrowser.js +50 -0
  53. package/dist/cjs/test/testStackTrace.js +58 -0
  54. package/dist/cjs/test/v1.test.js +70 -0
  55. package/dist/cjs/test/v2.test.js +124 -0
  56. package/dist/cjs/test/v3.test.js +119 -0
  57. package/dist/cjs/test/v4.test.js +105 -0
  58. package/dist/cjs/types.js +2 -0
  59. package/dist/cjs/utils/vizContentToFileCollection.js +23 -0
  60. package/dist/cjs/utils/vizContentToFileCollection.test.js +77 -0
  61. package/dist/cjs/v2/computeBundleJSV2.js +33 -0
  62. package/dist/cjs/v2/getComputedIndexHtml.js +86 -0
  63. package/dist/cjs/v2/getComputedIndexHtml.test.js +136 -0
  64. package/dist/cjs/v2/index.js +5 -0
  65. package/dist/cjs/v2/v2Build.js +15 -0
  66. package/dist/cjs/v3/cleanRollupErrorMessage.js +13 -0
  67. package/dist/cjs/v3/computeBundleJSV3.js +52 -0
  68. package/dist/cjs/v3/createVizContent.js +27 -0
  69. package/dist/cjs/v3/extractVizImport.js +27 -0
  70. package/dist/cjs/v3/extractVizImport.test.js +32 -0
  71. package/dist/cjs/v3/htmlTemplate.js +93 -0
  72. package/dist/cjs/v3/index.js +5 -0
  73. package/dist/cjs/v3/parseId.js +9 -0
  74. package/dist/cjs/v3/parseId.test.js +27 -0
  75. package/dist/cjs/v3/setupV3Runtime.js +345 -0
  76. package/dist/cjs/v3/slugCache.js +39 -0
  77. package/dist/cjs/v3/slugCache.test.js +107 -0
  78. package/dist/cjs/v3/transformDSV/dsvParseSrc.js +124 -0
  79. package/dist/cjs/v3/transformDSV/index.js +44 -0
  80. package/dist/cjs/v3/transformSvelte.js +81 -0
  81. package/dist/cjs/v3/types.js +2 -0
  82. package/dist/cjs/v3/v3Build.js +34 -0
  83. package/dist/cjs/v3/vizCache.js +40 -0
  84. package/dist/cjs/v3/vizCache.test.js +100 -0
  85. package/dist/cjs/v3/vizLoad.js +50 -0
  86. package/dist/cjs/v3/vizResolve.js +73 -0
  87. package/dist/cjs/v4/index.js +138 -0
  88. package/dist/esm/buildHTML.js +67 -0
  89. package/dist/esm/common/packageJson.js +71 -0
  90. package/dist/esm/common/packageJson.test.js +146 -0
  91. package/dist/esm/common/sucrasePlugin.js +24 -0
  92. package/dist/esm/common/virtualFileSystem.js +75 -0
  93. package/dist/esm/determineRuntimeVersion.js +22 -0
  94. package/dist/esm/determineRuntimeVersion.test.js +101 -0
  95. package/dist/esm/index.js +3 -0
  96. package/dist/esm/test/fixtures/v1/basicHTML.js +15 -0
  97. package/dist/esm/test/fixtures/v1/fetchProxy.js +12 -0
  98. package/dist/esm/test/fixtures/v1/index.js +6 -0
  99. package/dist/esm/test/fixtures/v1/jsScriptTag.js +9 -0
  100. package/dist/esm/test/fixtures/v1/protocolTest.js +15 -0
  101. package/dist/esm/test/fixtures/v1/styleTest.js +15 -0
  102. package/dist/esm/test/fixtures/v1/xmlTest.js +19 -0
  103. package/dist/esm/test/fixtures/v2/basicBundle.js +5 -0
  104. package/dist/esm/test/fixtures/v2/basicBundleNoExtension.js +5 -0
  105. package/dist/esm/test/fixtures/v2/d3Import.js +7 -0
  106. package/dist/esm/test/fixtures/v2/d3ImportPkg.js +19 -0
  107. package/dist/esm/test/fixtures/v2/d3RosettaImportPkg.js +19 -0
  108. package/dist/esm/test/fixtures/v2/es6Preserve.js +6 -0
  109. package/dist/esm/test/fixtures/v2/generatorSupport.js +6 -0
  110. package/dist/esm/test/fixtures/v2/index.js +15 -0
  111. package/dist/esm/test/fixtures/v2/jsxTranspile.js +6 -0
  112. package/dist/esm/test/fixtures/v2/reactDomImport.js +8 -0
  113. package/dist/esm/test/fixtures/v2/reactDomImportPkg.js +24 -0
  114. package/dist/esm/test/fixtures/v2/reactImport.js +7 -0
  115. package/dist/esm/test/fixtures/v2/reactImportPkg.js +17 -0
  116. package/dist/esm/test/fixtures/v2/sourceMapErrorFixture.js +19 -0
  117. package/dist/esm/test/fixtures/v2/unicodeSupport.js +6 -0
  118. package/dist/esm/test/fixtures/v3/basicIndexJS.js +7 -0
  119. package/dist/esm/test/fixtures/v3/cssImport.js +9 -0
  120. package/dist/esm/test/fixtures/v3/csvImport.js +11 -0
  121. package/dist/esm/test/fixtures/v3/csvStrangeChars.js +12 -0
  122. package/dist/esm/test/fixtures/v3/index.js +9 -0
  123. package/dist/esm/test/fixtures/v3/jsExport.js +10 -0
  124. package/dist/esm/test/fixtures/v3/sourcemap.js +10 -0
  125. package/dist/esm/test/fixtures/v3/svelte.js +18 -0
  126. package/dist/esm/test/fixtures/v3/vizContent.js +11 -0
  127. package/dist/esm/test/fixtures/v3/vizImport.js +85 -0
  128. package/dist/esm/test/fixtures/v4/d3Usage.js +31 -0
  129. package/dist/esm/test/fixtures/v4/esmBuild.js +18 -0
  130. package/dist/esm/test/fixtures/v4/fetchInterception.js +18 -0
  131. package/dist/esm/test/fixtures/v4/index.js +9 -0
  132. package/dist/esm/test/fixtures/v4/jsScriptTagTypeModule.js +18 -0
  133. package/dist/esm/test/fixtures/v4/jsScriptTagTypeModules.js +12 -0
  134. package/dist/esm/test/fixtures/v4/reactHooks.js +47 -0
  135. package/dist/esm/test/fixtures/v4/reactJsx.js +34 -0
  136. package/dist/esm/test/fixtures/v4/threeJsUsage.js +24 -0
  137. package/dist/esm/test/fixtures/v4/typeScriptSupport.js +29 -0
  138. package/dist/esm/test/testInBrowser.js +47 -0
  139. package/dist/esm/test/testStackTrace.js +55 -0
  140. package/dist/esm/test/v1.test.js +65 -0
  141. package/dist/esm/test/v2.test.js +121 -0
  142. package/dist/esm/test/v3.test.js +114 -0
  143. package/dist/esm/test/v4.test.js +100 -0
  144. package/dist/esm/types.js +1 -0
  145. package/dist/esm/utils/vizContentToFileCollection.js +19 -0
  146. package/dist/esm/utils/vizContentToFileCollection.test.js +75 -0
  147. package/dist/esm/v2/computeBundleJSV2.js +29 -0
  148. package/dist/esm/v2/getComputedIndexHtml.js +81 -0
  149. package/dist/esm/v2/getComputedIndexHtml.test.js +134 -0
  150. package/dist/esm/v2/index.js +1 -0
  151. package/dist/esm/v2/v2Build.js +11 -0
  152. package/dist/esm/v3/cleanRollupErrorMessage.js +9 -0
  153. package/dist/esm/v3/computeBundleJSV3.js +48 -0
  154. package/dist/esm/v3/createVizContent.js +23 -0
  155. package/dist/esm/v3/extractVizImport.js +23 -0
  156. package/dist/esm/v3/extractVizImport.test.js +30 -0
  157. package/dist/esm/v3/htmlTemplate.js +89 -0
  158. package/dist/esm/v3/index.js +1 -0
  159. package/dist/esm/v3/parseId.js +5 -0
  160. package/dist/esm/v3/parseId.test.js +25 -0
  161. package/dist/esm/v3/setupV3Runtime.js +341 -0
  162. package/dist/esm/v3/slugCache.js +35 -0
  163. package/dist/esm/v3/slugCache.test.js +105 -0
  164. package/dist/esm/v3/transformDSV/dsvParseSrc.js +121 -0
  165. package/dist/esm/v3/transformDSV/index.js +40 -0
  166. package/dist/esm/v3/transformSvelte.js +77 -0
  167. package/dist/esm/v3/types.js +1 -0
  168. package/dist/esm/v3/v3Build.js +30 -0
  169. package/dist/esm/v3/vizCache.js +36 -0
  170. package/dist/esm/v3/vizCache.test.js +98 -0
  171. package/dist/esm/v3/vizLoad.js +46 -0
  172. package/dist/esm/v3/vizResolve.js +69 -0
  173. package/dist/esm/v4/index.js +134 -0
  174. package/dist/types/buildHTML.d.ts +14 -0
  175. package/dist/types/common/packageJson.d.ts +39 -0
  176. package/dist/types/common/packageJson.test.d.ts +1 -0
  177. package/dist/types/common/sucrasePlugin.d.ts +2 -0
  178. package/dist/types/common/virtualFileSystem.d.ts +3 -0
  179. package/dist/types/determineRuntimeVersion.d.ts +3 -0
  180. package/dist/types/determineRuntimeVersion.test.d.ts +1 -0
  181. package/dist/types/index.d.ts +3 -0
  182. package/dist/types/test/fixtures/v1/basicHTML.d.ts +3 -0
  183. package/dist/types/test/fixtures/v1/fetchProxy.d.ts +5 -0
  184. package/dist/types/test/fixtures/v1/index.d.ts +6 -0
  185. package/dist/types/test/fixtures/v1/jsScriptTag.d.ts +4 -0
  186. package/dist/types/test/fixtures/v1/protocolTest.d.ts +3 -0
  187. package/dist/types/test/fixtures/v1/styleTest.d.ts +4 -0
  188. package/dist/types/test/fixtures/v1/xmlTest.d.ts +4 -0
  189. package/dist/types/test/fixtures/v2/basicBundle.d.ts +5 -0
  190. package/dist/types/test/fixtures/v2/basicBundleNoExtension.d.ts +5 -0
  191. package/dist/types/test/fixtures/v2/d3Import.d.ts +4 -0
  192. package/dist/types/test/fixtures/v2/d3ImportPkg.d.ts +5 -0
  193. package/dist/types/test/fixtures/v2/d3RosettaImportPkg.d.ts +5 -0
  194. package/dist/types/test/fixtures/v2/es6Preserve.d.ts +4 -0
  195. package/dist/types/test/fixtures/v2/generatorSupport.d.ts +4 -0
  196. package/dist/types/test/fixtures/v2/index.d.ts +14 -0
  197. package/dist/types/test/fixtures/v2/jsxTranspile.d.ts +4 -0
  198. package/dist/types/test/fixtures/v2/reactDomImport.d.ts +4 -0
  199. package/dist/types/test/fixtures/v2/reactDomImportPkg.d.ts +5 -0
  200. package/dist/types/test/fixtures/v2/reactImport.d.ts +4 -0
  201. package/dist/types/test/fixtures/v2/reactImportPkg.d.ts +5 -0
  202. package/dist/types/test/fixtures/v2/sourceMapErrorFixture.d.ts +5 -0
  203. package/dist/types/test/fixtures/v2/unicodeSupport.d.ts +4 -0
  204. package/dist/types/test/fixtures/v3/basicIndexJS.d.ts +3 -0
  205. package/dist/types/test/fixtures/v3/cssImport.d.ts +4 -0
  206. package/dist/types/test/fixtures/v3/csvImport.d.ts +4 -0
  207. package/dist/types/test/fixtures/v3/csvStrangeChars.d.ts +4 -0
  208. package/dist/types/test/fixtures/v3/index.d.ts +9 -0
  209. package/dist/types/test/fixtures/v3/jsExport.d.ts +4 -0
  210. package/dist/types/test/fixtures/v3/sourcemap.d.ts +3 -0
  211. package/dist/types/test/fixtures/v3/svelte.d.ts +4 -0
  212. package/dist/types/test/fixtures/v3/vizContent.d.ts +2 -0
  213. package/dist/types/test/fixtures/v3/vizImport.d.ts +6 -0
  214. package/dist/types/test/fixtures/v4/d3Usage.d.ts +5 -0
  215. package/dist/types/test/fixtures/v4/esmBuild.d.ts +5 -0
  216. package/dist/types/test/fixtures/v4/fetchInterception.d.ts +5 -0
  217. package/dist/types/test/fixtures/v4/index.d.ts +9 -0
  218. package/dist/types/test/fixtures/v4/jsScriptTagTypeModule.d.ts +4 -0
  219. package/dist/types/test/fixtures/v4/jsScriptTagTypeModules.d.ts +5 -0
  220. package/dist/types/test/fixtures/v4/reactHooks.d.ts +6 -0
  221. package/dist/types/test/fixtures/v4/reactJsx.d.ts +6 -0
  222. package/dist/types/test/fixtures/v4/threeJsUsage.d.ts +4 -0
  223. package/dist/types/test/fixtures/v4/typeScriptSupport.d.ts +5 -0
  224. package/dist/types/test/testInBrowser.d.ts +15 -0
  225. package/dist/types/test/testStackTrace.d.ts +9 -0
  226. package/dist/types/test/v1.test.d.ts +1 -0
  227. package/dist/types/test/v2.test.d.ts +1 -0
  228. package/dist/types/test/v3.test.d.ts +1 -0
  229. package/dist/types/test/v4.test.d.ts +1 -0
  230. package/dist/types/types.d.ts +1 -0
  231. package/dist/types/utils/vizContentToFileCollection.d.ts +7 -0
  232. package/dist/types/utils/vizContentToFileCollection.test.d.ts +1 -0
  233. package/dist/types/v2/computeBundleJSV2.d.ts +7 -0
  234. package/dist/types/v2/getComputedIndexHtml.d.ts +4 -0
  235. package/dist/types/v2/getComputedIndexHtml.test.d.ts +1 -0
  236. package/dist/types/v2/index.d.ts +1 -0
  237. package/dist/types/v2/v2Build.d.ts +7 -0
  238. package/dist/types/v3/cleanRollupErrorMessage.d.ts +4 -0
  239. package/dist/types/v3/computeBundleJSV3.d.ts +17 -0
  240. package/dist/types/v3/createVizContent.d.ts +8 -0
  241. package/dist/types/v3/extractVizImport.d.ts +6 -0
  242. package/dist/types/v3/extractVizImport.test.d.ts +1 -0
  243. package/dist/types/v3/htmlTemplate.d.ts +5 -0
  244. package/dist/types/v3/index.d.ts +1 -0
  245. package/dist/types/v3/parseId.d.ts +6 -0
  246. package/dist/types/v3/parseId.test.d.ts +1 -0
  247. package/dist/types/v3/setupV3Runtime.d.ts +15 -0
  248. package/dist/types/v3/slugCache.d.ts +11 -0
  249. package/dist/types/v3/slugCache.test.d.ts +1 -0
  250. package/dist/types/v3/transformDSV/dsvParseSrc.d.ts +1 -0
  251. package/dist/types/v3/transformDSV/index.d.ts +2 -0
  252. package/dist/types/v3/transformSvelte.d.ts +8 -0
  253. package/dist/types/v3/types.d.ts +65 -0
  254. package/dist/types/v3/v3Build.d.ts +14 -0
  255. package/dist/types/v3/vizCache.d.ts +10 -0
  256. package/dist/types/v3/vizCache.test.d.ts +1 -0
  257. package/dist/types/v3/vizLoad.d.ts +7 -0
  258. package/dist/types/v3/vizResolve.d.ts +7 -0
  259. package/dist/types/v4/index.d.ts +10 -0
  260. package/package.json +14 -7
@@ -0,0 +1,93 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.htmlTemplate = void 0;
4
+ function randomDigits() {
5
+ return Math.random().toString().slice(2, 7);
6
+ }
7
+ const htmlTemplate = ({ cdn, src, styles, }) => {
8
+ // Random container id to avoid conflicts and guarantee
9
+ // the code is portable.
10
+ const containerSuffix = randomDigits();
11
+ const vizContainerId = `viz-container-${containerSuffix}`;
12
+ return `<!DOCTYPE html>
13
+ <html>
14
+ <head>
15
+ <meta charset="utf-8">${cdn}${styles}
16
+ <style>
17
+ body {
18
+ margin: 0;
19
+ overflow: hidden;
20
+ }
21
+ #${vizContainerId} {
22
+ height: 100vh;
23
+ }
24
+ </style>
25
+ </head>
26
+ <body>
27
+ <div id="${vizContainerId}"></div>
28
+ <script id="injected-script">${src}</script>
29
+ <script>
30
+ (() => {
31
+ let cleanup;
32
+ const render = () => {
33
+ const container = document.getElementById('${vizContainerId}');
34
+ typeof cleanup === 'function' && cleanup();
35
+ cleanup = Viz.main(container, { state: window.state, setState, writeFile });
36
+ };
37
+ const setState = (next) => {
38
+ window.state = next(window.state);
39
+ render();
40
+ };
41
+ const writeFile = (fileName, content) => {
42
+ parent.postMessage({ type: 'writeFile', fileName, content }, "*");
43
+ };
44
+ const run = () => {
45
+ try {
46
+ setState((state) => state || {});
47
+ } catch (error) {
48
+ console.error(error);
49
+ parent.postMessage({ type: 'runError', error }, "*");
50
+ }
51
+ }
52
+ run();
53
+ const runJS = (src) => {
54
+ document.getElementById('injected-script')?.remove();
55
+ const script = document.createElement('script');
56
+ script.textContent = src;
57
+ script.id = 'injected-script';
58
+ document.body.appendChild(script);
59
+ run();
60
+ };
61
+ const runCSS = (src, id) => {
62
+ const styleElementId = 'injected-style' + id;
63
+ let style = document.getElementById(styleElementId);
64
+ if (!style) {
65
+ style = document.createElement('style');
66
+ style.type = 'text/css';
67
+ style.id = styleElementId;
68
+ document.head.appendChild(style);
69
+ }
70
+ style.textContent = src;
71
+ };
72
+ onmessage = (message) => {
73
+ switch (message.data.type) {
74
+ case 'runJS':
75
+ runJS(message.data.src);
76
+ parent.postMessage({ type: 'runDone' }, "*");
77
+ break;
78
+ case 'runCSS':
79
+ runCSS(message.data.src, message.data.id);
80
+ break;
81
+ case 'ping':
82
+ parent.postMessage({ type: 'pong' }, "*");
83
+ break;
84
+ default:
85
+ break;
86
+ }
87
+ }
88
+ })();
89
+ </script>
90
+ </body>
91
+ </html>`;
92
+ };
93
+ exports.htmlTemplate = htmlTemplate;
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.v3Build = void 0;
4
+ var v3Build_js_1 = require("./v3Build.js");
5
+ Object.defineProperty(exports, "v3Build", { enumerable: true, get: function () { return v3Build_js_1.v3Build; } });
@@ -0,0 +1,9 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.parseId = void 0;
4
+ const parseId = (id) => {
5
+ const [vizId, ...fileNameParts] = id.split("/");
6
+ const fileName = fileNameParts.join("/");
7
+ return { vizId, fileName };
8
+ };
9
+ exports.parseId = parseId;
@@ -0,0 +1,27 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const vitest_1 = require("vitest");
4
+ const parseId_1 = require("./parseId");
5
+ (0, vitest_1.describe)("parseId", () => {
6
+ (0, vitest_1.it)("should correctly parse viz id and filename", () => {
7
+ const result = (0, parseId_1.parseId)("21f72bf74ef04ea0b9c9b82aaaec859a/index.js");
8
+ (0, vitest_1.expect)(result).toEqual({
9
+ vizId: "21f72bf74ef04ea0b9c9b82aaaec859a",
10
+ fileName: "index.js",
11
+ });
12
+ });
13
+ (0, vitest_1.it)("should handle alphanumeric ids", () => {
14
+ const result = (0, parseId_1.parseId)("scatter-plot/visualization.js");
15
+ (0, vitest_1.expect)(result).toEqual({
16
+ vizId: "scatter-plot",
17
+ fileName: "visualization.js",
18
+ });
19
+ });
20
+ (0, vitest_1.it)("should handle complex filenames", () => {
21
+ const result = (0, parseId_1.parseId)("my-viz/nested/path/file.test.js");
22
+ (0, vitest_1.expect)(result).toEqual({
23
+ vizId: "my-viz",
24
+ fileName: "nested/path/file.test.js",
25
+ });
26
+ });
27
+ });
@@ -0,0 +1,345 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.setupV3Runtime = void 0;
4
+ const parseId_1 = require("./parseId");
5
+ const cleanRollupErrorMessage_1 = require("./cleanRollupErrorMessage");
6
+ const viz_utils_1 = require("@vizhub/viz-utils");
7
+ // Flag for debugging.
8
+ const debug = false;
9
+ // Nothing happening.
10
+ const IDLE = "IDLE";
11
+ // An update has been enqueued
12
+ // via requestAnimationFrame.
13
+ const ENQUEUED = "ENQUEUED";
14
+ // An update (build and run) is pending,
15
+ // and the files have not changed.
16
+ const PENDING_CLEAN = "PENDING_CLEAN";
17
+ // An update (build and run) is pending,
18
+ // and the files have changed
19
+ // while this run is taking place.
20
+ const PENDING_DIRTY = "PENDING_DIRTY";
21
+ const setupV3Runtime = ({ vizId, iframe, setSrcdocErrorMessage, getLatestContent, resolveSlugKey, writeFile, worker, }) => {
22
+ // Valid State Transitions:
23
+ //
24
+ // * IDLE --> ENQUEUED
25
+ // When the system is idle and files are changed.
26
+ //
27
+ // * ENQUEUED --> PENDING_CLEAN
28
+ // When the pending changes run.
29
+ //
30
+ // * PENDING_CLEAN --> IDLE
31
+ // When the pending update finishes running
32
+ // and files were not changed in the mean time.
33
+ //
34
+ // * PENDING_CLEAN --> PENDING_DIRTY
35
+ // When files are changed while an update is pending.
36
+ //
37
+ // * PENDING_DIRTY --> ENQUEUED
38
+ // When the pending update finishes running
39
+ // and files were changed in the mean time.
40
+ //
41
+ // When a build error happens, the state is set to IDLE.
42
+ // This is to prevent a build error from causing
43
+ // the whole system to stop working.
44
+ //
45
+ // Valid State Transitions (with build errors):
46
+ // TODO complete this section
47
+ let state = IDLE;
48
+ if (debug) {
49
+ setInterval(() => {
50
+ console.log("state", state);
51
+ }, 1000);
52
+ }
53
+ // Pending promise resolvers.
54
+ let pendingBuildPromise = null;
55
+ let pendingRunPromise = null;
56
+ // Logic around profiling build times.
57
+ const profileBuildTimes = debug;
58
+ let buildTimes = [];
59
+ const avg = (arr) => arr.reduce((a, b) => a + b, 0) / arr.length;
60
+ const n = 100;
61
+ // This runs when the build worker sends a message.
62
+ worker.addEventListener("message", async ({ data }) => {
63
+ const message = data;
64
+ // Handle 'buildResponse' messages.
65
+ // These are sent by the build worker in response
66
+ // to a 'buildRequest' message.
67
+ if (message.type === "buildResponse") {
68
+ const buildResult = message.buildResult;
69
+ const error = message.error;
70
+ if (profileBuildTimes && buildResult) {
71
+ buildTimes.push(buildResult.time);
72
+ // Every n times, log the rolling average.
73
+ if (buildTimes.length % n === 0) {
74
+ console.log("Average build time: " +
75
+ avg(buildTimes) +
76
+ " ms");
77
+ buildTimes = [];
78
+ }
79
+ }
80
+ // Regardless of whether the build succeeded or failed,
81
+ // resolve the pending build promise,
82
+ // so that the system remains responsive.
83
+ if (pendingBuildPromise) {
84
+ pendingBuildPromise(buildResult);
85
+ pendingBuildPromise = null;
86
+ }
87
+ if (error) {
88
+ setSrcdocErrorMessage((0, cleanRollupErrorMessage_1.cleanRollupErrorMessage)({
89
+ rawMessage: error.message,
90
+ vizId,
91
+ }));
92
+ }
93
+ }
94
+ // Handle 'contentRequest' messages.
95
+ // These are sent by the worker when it needs
96
+ // to get the content of a file, in order to
97
+ // populate its VizCache.
98
+ if (message.type === "contentRequest") {
99
+ const { vizId } = message;
100
+ const content = await getLatestContent(vizId);
101
+ const contentResponseMessage = {
102
+ type: "contentResponse",
103
+ vizId: message.vizId,
104
+ content,
105
+ };
106
+ if (debug) {
107
+ console.log("[v3 runtime] received contentRequest, sending contentResponse", contentResponseMessage);
108
+ }
109
+ // Send the content back to the worker.
110
+ worker.postMessage(contentResponseMessage);
111
+ }
112
+ // Handle 'resolveSlugRequest' messages.
113
+ // These are sent by the worker when it needs
114
+ // to resolve a slug import to a viz ID.
115
+ if (message.type === "resolveSlugRequest") {
116
+ const { slugKey } = message;
117
+ const resolveSlugResponseMessage = {
118
+ type: "resolveSlugResponse",
119
+ slugKey,
120
+ requestId: message.requestId,
121
+ vizId: await resolveSlugKey(slugKey),
122
+ };
123
+ if (debug) {
124
+ console.log("[v3 runtime] received resolveSlugRequest, sending resolveSlugResponse", resolveSlugResponseMessage);
125
+ }
126
+ // Send the viz ID back to the worker.
127
+ worker.postMessage(resolveSlugResponseMessage);
128
+ }
129
+ // Handle 'invalidateVizCacheResponse' messages.
130
+ // These are sent by the worker in response to
131
+ // an 'invalidateVizCacheRequest' message.
132
+ if (message.type === "invalidateVizCacheResponse") {
133
+ if (debug) {
134
+ console.log("[v3 runtime] received invalidateVizCacheResponse", message);
135
+ }
136
+ // Leverage existing infra for executing the hot reloading.
137
+ handleCodeChange();
138
+ }
139
+ if (message.type === "resetSrcdocResponse") {
140
+ const srcdoc = message.srcdoc;
141
+ const error = message.error;
142
+ if (error) {
143
+ setSrcdocErrorMessage((0, cleanRollupErrorMessage_1.cleanRollupErrorMessage)({
144
+ rawMessage: error.message,
145
+ vizId,
146
+ }));
147
+ }
148
+ else {
149
+ setSrcdocErrorMessage(null);
150
+ // Really reset the srcdoc!
151
+ // console.log('Really reset the srcdoc!');
152
+ if (srcdoc) {
153
+ iframe.srcdoc = srcdoc;
154
+ }
155
+ }
156
+ }
157
+ });
158
+ // This runs when the IFrame sends a message.
159
+ window.addEventListener("message", ({ data }) => {
160
+ // Handle 'runDone' and 'runError' messages.
161
+ // These happen in response to sending a 'runJS' message.
162
+ if (data.type === "runDone" ||
163
+ data.type === "runError") {
164
+ // console.log('got ' + data.type);
165
+ if (pendingRunPromise) {
166
+ // TODO pass errors out for display
167
+ // pendingRunPromise(data as V3WindowMessage);
168
+ pendingRunPromise();
169
+ pendingRunPromise = null;
170
+ }
171
+ }
172
+ if (data.type === "runError") {
173
+ setSrcdocErrorMessage(data.error.message);
174
+ }
175
+ if (data.type === "writeFile") {
176
+ if (data.fileName && data.content) {
177
+ writeFile(data.fileName, data.content);
178
+ }
179
+ }
180
+ });
181
+ const handleCodeChange = () => {
182
+ if (state === IDLE) {
183
+ state = ENQUEUED;
184
+ update();
185
+ }
186
+ else if (state === PENDING_CLEAN) {
187
+ state = PENDING_DIRTY;
188
+ }
189
+ };
190
+ // This runs when one or more imported vizzes are changed.
191
+ const invalidateVizCache = (changedVizIds) => {
192
+ // Send a message to the worker to invalidate the cache.
193
+ const message = {
194
+ type: "invalidateVizCacheRequest",
195
+ changedVizIds,
196
+ };
197
+ worker.postMessage(message);
198
+ };
199
+ const profileHotReloadFPS = true;
200
+ let updateCount = 0;
201
+ if (profileHotReloadFPS) {
202
+ setInterval(() => {
203
+ if (debug && updateCount > 0) {
204
+ console.log(updateCount +
205
+ " hot reload" +
206
+ (updateCount !== 1 ? "s" : "") +
207
+ " in the last second");
208
+ }
209
+ updateCount = 0;
210
+ }, 1000);
211
+ }
212
+ const build = () => {
213
+ return new Promise((resolve) => {
214
+ pendingBuildPromise = resolve;
215
+ const message = {
216
+ type: "buildRequest",
217
+ vizId,
218
+ enableSourcemap: true,
219
+ };
220
+ worker.postMessage(message);
221
+ });
222
+ };
223
+ // Builds and runs the latest files.
224
+ const update = async () => {
225
+ state = PENDING_CLEAN;
226
+ if (debug) {
227
+ console.log("update: before run");
228
+ }
229
+ // Build the code. This may fail and return `undefined`.
230
+ const buildResult = await build();
231
+ // If the build was successful, run the code.
232
+ if (buildResult !== undefined) {
233
+ await run(buildResult);
234
+ }
235
+ if (debug) {
236
+ console.log("update: after run");
237
+ }
238
+ updateCount++;
239
+ // TypeScript can't comprehend that `state`
240
+ // may change during the await calls above.
241
+ // @ts-ignore
242
+ if (state === PENDING_DIRTY) {
243
+ requestAnimationFrame(update);
244
+ state = ENQUEUED;
245
+ }
246
+ else {
247
+ state = IDLE;
248
+ }
249
+ };
250
+ let previousCSSFiles = [];
251
+ const run = (buildResult) => {
252
+ return new Promise((resolve) => {
253
+ const { src, warnings, cssFiles } = buildResult;
254
+ // Sanity check.
255
+ // At this point, since there were no errors,
256
+ // we expect there to be a `src` property.
257
+ // This should never happen, but log & error just in case!
258
+ if (src === undefined) {
259
+ if (debug) {
260
+ console.log("[v3 runtime] src is undefined, but no errors!");
261
+ }
262
+ throw new Error("[v3 runtime] src is undefined, but no errors!");
263
+ }
264
+ // Set pendingRunPromise because at this point,
265
+ // we expect an asynchronous response when the run is done.
266
+ // The iframe should send either a `runDone` or `runError` message.
267
+ pendingRunPromise = resolve;
268
+ // Handle build warnings
269
+ if (warnings.length > 0) {
270
+ // TODO: Distinguish between warnings and errors in UI
271
+ setSrcdocErrorMessage(warnings
272
+ .map((warning) => warning.message)
273
+ .join("\n\n"));
274
+ }
275
+ else {
276
+ setSrcdocErrorMessage(null); // Clear error message if no warnings
277
+ }
278
+ if (iframe.contentWindow) {
279
+ // For each cssFiles
280
+ for (const cssFile of cssFiles) {
281
+ const { vizId, fileName } = (0, parseId_1.parseId)(cssFile);
282
+ getLatestContent(vizId).then((content) => {
283
+ const src = (0, viz_utils_1.getFileText)(content, fileName);
284
+ if (src === null) {
285
+ // The file doesn't exist.
286
+ // TODO surface this error to the user
287
+ // in a nicer way than this.
288
+ console.warn(`Imported CSS file ${fileName} doesn't exist.`);
289
+ return;
290
+ }
291
+ // TODO only inject CSS if it has changed.
292
+ const runCSSMessage = {
293
+ type: "runCSS",
294
+ id: cssFile,
295
+ src,
296
+ };
297
+ if (debug) {
298
+ console.log("runCSSMessage", runCSSMessage);
299
+ }
300
+ iframe.contentWindow?.postMessage(runCSSMessage, window.location.origin);
301
+ });
302
+ }
303
+ // Detect which CSS files have been removed
304
+ // and remove them from the iframe.
305
+ const removedCSSFiles = previousCSSFiles.filter((id) => !cssFiles.includes(id));
306
+ previousCSSFiles = cssFiles;
307
+ if (debug) {
308
+ console.log("removedCSSFiles", removedCSSFiles);
309
+ }
310
+ for (const id of removedCSSFiles) {
311
+ const removeCSSMessage = {
312
+ type: "runCSS",
313
+ id,
314
+ src: "",
315
+ };
316
+ iframe.contentWindow?.postMessage(removeCSSMessage, window.location.origin);
317
+ }
318
+ // Clear the console before each run.
319
+ console.clear();
320
+ const runJSMessage = {
321
+ type: "runJS",
322
+ src,
323
+ };
324
+ iframe.contentWindow.postMessage(runJSMessage, window.location.origin);
325
+ }
326
+ });
327
+ };
328
+ const resetSrcdoc = (changedVizIds) => {
329
+ state = IDLE;
330
+ pendingBuildPromise = null;
331
+ pendingRunPromise = null;
332
+ const message = {
333
+ type: "resetSrcdocRequest",
334
+ vizId,
335
+ changedVizIds,
336
+ };
337
+ worker.postMessage(message);
338
+ };
339
+ return {
340
+ handleCodeChange,
341
+ invalidateVizCache,
342
+ resetSrcdoc,
343
+ };
344
+ };
345
+ exports.setupV3Runtime = setupV3Runtime;
@@ -0,0 +1,39 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createSlugCache = void 0;
4
+ // A cache of viz IDs for slug resolution.
5
+ // Maps slug strings (username/slug) to viz IDs.
6
+ const createSlugCache = ({ initialMappings = {}, handleCacheMiss, }) => {
7
+ // Track the mapping of slugs to viz IDs
8
+ const slugMap = new Map(Object.entries(initialMappings));
9
+ // Gets the viz ID for a slug.
10
+ // Returns the cached ID if it exists.
11
+ // Otherwise, calls handleCacheMiss to resolve the slug.
12
+ const get = async (slug) => {
13
+ const cachedVizId = slugMap.get(slug);
14
+ // Cache hit
15
+ if (cachedVizId !== undefined) {
16
+ return cachedVizId;
17
+ }
18
+ // Cache miss
19
+ if (!handleCacheMiss) {
20
+ throw new Error(`Unresolved slug ${slug}, cache miss handler not provided.`);
21
+ }
22
+ const resolvedVizId = await handleCacheMiss(slug);
23
+ if (resolvedVizId) {
24
+ slugMap.set(slug, resolvedVizId);
25
+ return resolvedVizId;
26
+ }
27
+ throw new Error(`Unresolved slug ${slug}`);
28
+ };
29
+ // Updates the mapping of a slug to a viz ID in the cache.
30
+ const set = (slug, vizId) => {
31
+ slugMap.set(slug, vizId);
32
+ };
33
+ // Removes a slug mapping from the cache.
34
+ const invalidate = (slug) => {
35
+ slugMap.delete(slug);
36
+ };
37
+ return { get, set, invalidate };
38
+ };
39
+ exports.createSlugCache = createSlugCache;
@@ -0,0 +1,107 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const vitest_1 = require("vitest");
4
+ const slugCache_1 = require("./slugCache");
5
+ (0, vitest_1.describe)("SlugCache", () => {
6
+ (0, vitest_1.describe)("SlugCache - get method", () => {
7
+ (0, vitest_1.it)("should return vizId from cache if available", async () => {
8
+ const initialMappings = {
9
+ "user1/viz-slug": "viz-123",
10
+ };
11
+ const slugCache = (0, slugCache_1.createSlugCache)({
12
+ initialMappings,
13
+ handleCacheMiss: vitest_1.vi.fn(),
14
+ });
15
+ const vizId = await slugCache.get("user1/viz-slug");
16
+ (0, vitest_1.expect)(vizId).toEqual("viz-123");
17
+ (0, vitest_1.expect)(vitest_1.vi.fn()).toHaveBeenCalledTimes(0); // handleCacheMiss should not be called
18
+ });
19
+ (0, vitest_1.it)("should resolve slug on cache miss and store it", async () => {
20
+ const handleCacheMissMock = vitest_1.vi
21
+ .fn()
22
+ .mockResolvedValue("viz-456");
23
+ const slugCache = (0, slugCache_1.createSlugCache)({
24
+ initialMappings: {},
25
+ handleCacheMiss: handleCacheMissMock,
26
+ });
27
+ const vizId = await slugCache.get("user2/new-viz");
28
+ (0, vitest_1.expect)(handleCacheMissMock).toHaveBeenCalledWith("user2/new-viz");
29
+ (0, vitest_1.expect)(vizId).toEqual("viz-456");
30
+ // Verify that the cache now contains the resolved mapping
31
+ const cachedVizId = await slugCache.get("user2/new-viz");
32
+ (0, vitest_1.expect)(cachedVizId).toEqual("viz-456");
33
+ (0, vitest_1.expect)(handleCacheMissMock).toHaveBeenCalledTimes(1); // Should only be called once
34
+ });
35
+ (0, vitest_1.it)("should throw an error if handleCacheMiss does not return a vizId", async () => {
36
+ const handleCacheMissMock = vitest_1.vi
37
+ .fn()
38
+ .mockResolvedValue(undefined);
39
+ const slugCache = (0, slugCache_1.createSlugCache)({
40
+ initialMappings: {},
41
+ handleCacheMiss: handleCacheMissMock,
42
+ });
43
+ await (0, vitest_1.expect)(slugCache.get("nonexistent/slug")).rejects.toThrow("Unresolved slug nonexistent/slug");
44
+ });
45
+ (0, vitest_1.it)("should throw an error if no handleCacheMiss is provided and slug not found", async () => {
46
+ const slugCache = (0, slugCache_1.createSlugCache)({
47
+ initialMappings: {},
48
+ });
49
+ await (0, vitest_1.expect)(slugCache.get("missing/slug")).rejects.toThrow("Unresolved slug missing/slug, cache miss handler not provided.");
50
+ });
51
+ });
52
+ (0, vitest_1.describe)("SlugCache - set method", () => {
53
+ (0, vitest_1.it)("should add new mapping to the cache", async () => {
54
+ const slugCache = (0, slugCache_1.createSlugCache)({
55
+ initialMappings: {},
56
+ handleCacheMiss: vitest_1.vi.fn(),
57
+ });
58
+ const slug = "user3/new-viz";
59
+ const vizId = "viz-789";
60
+ slugCache.set(slug, vizId);
61
+ // Verify new mapping is added
62
+ const resolvedVizId = await slugCache.get(slug);
63
+ (0, vitest_1.expect)(resolvedVizId).toEqual(vizId);
64
+ });
65
+ (0, vitest_1.it)("should update existing mapping in the cache", async () => {
66
+ const initialMappings = {
67
+ "user4/existing-viz": "old-viz-id",
68
+ };
69
+ const slugCache = (0, slugCache_1.createSlugCache)({
70
+ initialMappings,
71
+ handleCacheMiss: vitest_1.vi.fn(),
72
+ });
73
+ const slug = "user4/existing-viz";
74
+ const updatedVizId = "updated-viz-id";
75
+ // Update existing mapping
76
+ slugCache.set(slug, updatedVizId);
77
+ // Verify mapping is updated
78
+ const resolvedVizId = await slugCache.get(slug);
79
+ (0, vitest_1.expect)(resolvedVizId).toEqual(updatedVizId);
80
+ });
81
+ });
82
+ (0, vitest_1.describe)("SlugCache - invalidate method", () => {
83
+ (0, vitest_1.it)("should remove a mapping from the cache", async () => {
84
+ const initialMappings = {
85
+ "user5/to-remove": "viz-to-remove",
86
+ };
87
+ const handleCacheMissMock = vitest_1.vi.fn();
88
+ const slugCache = (0, slugCache_1.createSlugCache)({
89
+ initialMappings,
90
+ handleCacheMiss: handleCacheMissMock,
91
+ });
92
+ // Verify mapping exists initially
93
+ const initialVizId = await slugCache.get("user5/to-remove");
94
+ (0, vitest_1.expect)(initialVizId).toEqual("viz-to-remove");
95
+ // Invalidate the mapping
96
+ slugCache.invalidate("user5/to-remove");
97
+ // Trying to get it should trigger the cache miss handler
98
+ try {
99
+ await slugCache.get("user5/to-remove");
100
+ }
101
+ catch (e) {
102
+ // Ignore error if handleCacheMiss throws
103
+ }
104
+ (0, vitest_1.expect)(handleCacheMissMock).toHaveBeenCalledWith("user5/to-remove");
105
+ });
106
+ });
107
+ });