flexr 1.1.0 → 2.0.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 (133) hide show
  1. checksums.yaml +4 -4
  2. data/.rubocop.yml +2 -1
  3. data/CHANGELOG.md +116 -0
  4. data/CONTRIBUTING.md +46 -3
  5. data/README.md +5 -4
  6. data/Rakefile +191 -68
  7. data/Steepfile +7 -0
  8. data/benchmark/baselines/json.json +2 -2
  9. data/benchmark/golden/calculator_lexer.rb +276 -0
  10. data/benchmark/golden/graphql_lexer.rb +310 -0
  11. data/benchmark/golden/json_lexer.rb +292 -0
  12. data/benchmark/golden/regexp_tokenizer.rb +293 -0
  13. data/benchmark/golden/ruby_subset_lexer.rb +280 -0
  14. data/benchmark/golden/sql_lexer.rb +293 -0
  15. data/benchmark/golden/toml_lexer.rb +292 -0
  16. data/benchmark/golden/toy_lang_lexer.rb +273 -0
  17. data/benchmark/golden/with_lrama_lexer.rb +264 -0
  18. data/benchmark/golden/with_racc_lexer.rb +264 -0
  19. data/benchmark/lrama_lexer.rb +165 -0
  20. data/benchmark/matrix.rb +79 -0
  21. data/benchmark/profile.rb +109 -0
  22. data/benchmark/run.rb +4 -1
  23. data/benchmark/state_dispatch.rb +78 -0
  24. data/docs/README.md +1 -2
  25. data/docs/RELEASING.md +3 -2
  26. data/docs/explanation/backends.md +17 -0
  27. data/docs/how-to/deploy-a-standalone-lexer.md +1 -1
  28. data/docs/how-to/tune-performance.md +12 -0
  29. data/docs/migration-v2.md +74 -0
  30. data/docs/perf-log.md +196 -0
  31. data/docs/reference/README.md +2 -0
  32. data/docs/reference/cli.md +71 -5
  33. data/docs/reference/compatibility.md +10 -4
  34. data/docs/reference/diagnostics.md +338 -0
  35. data/docs/reference/dsl.md +12 -5
  36. data/docs/reference/errors.md +28 -0
  37. data/docs/reference/generated-artifacts.md +42 -4
  38. data/docs/reference/public-api.md +33 -8
  39. data/docs/reference/regexp.md +19 -7
  40. data/docs/reference/ruby-lsp.md +34 -0
  41. data/docs/reference/runtime.md +2 -2
  42. data/docs/reference/testing.md +57 -0
  43. data/docs/reference/tokens-and-locations.md +8 -0
  44. data/examples/graphql/README.md +14 -0
  45. data/examples/graphql/lexer.flexr.rb +29 -0
  46. data/examples/json/lexer.flexr.rb +6 -6
  47. data/examples/sql/README.md +16 -0
  48. data/examples/sql/lexer.flexr.rb +23 -0
  49. data/examples/toml/README.md +14 -0
  50. data/examples/toml/lexer.flexr.rb +23 -0
  51. data/gemfiles/ruby_lsp.gemfile +4 -0
  52. data/gemfiles/types.gemfile +7 -0
  53. data/lib/flexr/automaton/accel.rb +69 -1
  54. data/lib/flexr/automaton/analysis.rb +161 -7
  55. data/lib/flexr/automaton/compiler.rb +179 -25
  56. data/lib/flexr/automaton/types.rb +1 -1
  57. data/lib/flexr/cli.rb +117 -17
  58. data/lib/flexr/codegen/firstmatch.rb +1 -7
  59. data/lib/flexr/codegen/table.rb +8 -2
  60. data/lib/flexr/configuration.rb +8 -0
  61. data/lib/flexr/diagnostics.rb +39 -3
  62. data/lib/flexr/dsl.rb +12 -9
  63. data/lib/flexr/errors.rb +6 -6
  64. data/lib/flexr/generated.rb +65 -17
  65. data/lib/flexr/generator.rb +62 -34
  66. data/lib/flexr/grammar.rb +41 -0
  67. data/lib/flexr/ir.rb +2 -2
  68. data/lib/flexr/migration.rb +31 -0
  69. data/lib/flexr/minitest.rb +24 -0
  70. data/lib/flexr/options.rb +4 -2
  71. data/lib/flexr/regexp/matcher.rb +26 -0
  72. data/lib/flexr/regexp/normalizer.rb +4 -8
  73. data/lib/flexr/regexp/parser.rb +127 -21
  74. data/lib/flexr/regexp/tokenizer.rb +26 -26
  75. data/lib/flexr/rspec.rb +51 -0
  76. data/lib/flexr/runtime/core.rb +47 -17
  77. data/lib/flexr/runtime/errors.rb +6 -4
  78. data/lib/flexr/runtime/interpreter.rb +55 -46
  79. data/lib/flexr/runtime/location.rb +35 -12
  80. data/lib/flexr/runtime/record.rb +14 -0
  81. data/lib/flexr/runtime/token.rb +7 -1
  82. data/lib/flexr/runtime.rb +7 -2
  83. data/lib/flexr/source/passthrough.rb +14 -11
  84. data/lib/flexr/source/prism_reader.rb +53 -16
  85. data/lib/flexr/testing.rb +47 -0
  86. data/lib/flexr/trace.rb +197 -0
  87. data/lib/flexr/unicode/property.rb +1 -3
  88. data/lib/flexr/unicode/reference_regexp.rb +8 -10
  89. data/lib/flexr/version.rb +1 -1
  90. data/lib/flexr.rb +1 -0
  91. data/lib/ruby_lsp/flexr/addon.rb +114 -0
  92. data/sig/flexr.rbs +191 -0
  93. data/site/README.md +54 -3
  94. data/site/astro.config.mjs +3 -1
  95. data/site/package.json +12 -5
  96. data/site/playwright.config.mjs +16 -0
  97. data/site/pnpm-lock.yaml +218 -88
  98. data/site/ruby/playground.rb +57 -0
  99. data/site/scripts/prepare-playground.mjs +35 -0
  100. data/site/scripts/verify-site.mjs +5 -3
  101. data/site/src/content/docs/concepts/matching-semantics.md +4 -2
  102. data/site/src/content/docs/concepts/security-model.md +9 -1
  103. data/site/src/content/docs/learn/generation.md +1 -1
  104. data/site/src/content/docs/reference/dsl.md +2 -2
  105. data/site/src/content/docs/reference/public-api.md +4 -2
  106. data/site/src/content/docs/reference/tokens-and-locations.md +3 -0
  107. data/site/src/layouts/SiteLayout.astro +11 -3
  108. data/site/src/pages/index.astro +69 -155
  109. data/site/src/pages/playground.astro +40 -38
  110. data/site/src/playground/client.js +211 -0
  111. data/site/src/playground/graph-worker.mjs +11 -0
  112. data/site/src/playground/presets.mjs +33 -0
  113. data/site/src/playground/runtime.mjs +34 -0
  114. data/site/src/playground/share.mjs +30 -0
  115. data/site/src/playground/worker.mjs +29 -0
  116. data/site/src/styles/custom.css +12 -287
  117. data/site/src/styles/landing.css +239 -0
  118. data/site/tests/browser/playground.spec.mjs +99 -0
  119. data/site/tests/playground-runtime.test.mjs +85 -0
  120. data/test/ruby_lsp_addon_spec.rb +135 -0
  121. data/tools/docs_verify.rb +3 -2
  122. data/tools/golden.rb +54 -0
  123. data/tools/verification_failure.rb +119 -0
  124. metadata +56 -13
  125. data/benchmark/golden/calculator_lexer.sha256 +0 -1
  126. data/benchmark/golden/json_lexer.sha256 +0 -1
  127. data/benchmark/golden/regexp_tokenizer.sha256 +0 -1
  128. data/benchmark/golden/ruby_subset_lexer.sha256 +0 -1
  129. data/benchmark/golden/toy_lang_lexer.sha256 +0 -1
  130. data/benchmark/golden/with_lrama_lexer.sha256 +0 -1
  131. data/benchmark/golden/with_racc_lexer.sha256 +0 -1
  132. data/docs/releases/v1.1.0.md +0 -44
  133. data/site/public/playground.js +0 -189
@@ -0,0 +1,211 @@
1
+ import workerUrl from './worker.mjs?worker&url';
2
+ import graphWorkerUrl from './graph-worker.mjs?worker&url';
3
+ import { PRESETS } from './presets.mjs';
4
+ import { decodeState, encodeState, validateState } from './share.mjs';
5
+
6
+ const source = document.querySelector('#spec');
7
+ const input = document.querySelector('#input');
8
+ const mode = document.querySelector('#mode');
9
+ const status = document.querySelector('#status');
10
+ const runButton = document.querySelector('[data-action="run"]');
11
+ const stopButton = document.querySelector('[data-action="stop"]');
12
+ const steps = document.querySelector('#step');
13
+ let worker;
14
+ let timer;
15
+ let graphWorker;
16
+ let graphTimer;
17
+ let trace = [];
18
+ let dot = '';
19
+
20
+ function show(id, text) { document.querySelector(`#${id}`).textContent = text; }
21
+
22
+ function stop(message = 'Stopped. Edit the source or input, then run again.') {
23
+ worker?.terminate();
24
+ worker = undefined;
25
+ clearTimeout(timer);
26
+ runButton.disabled = false;
27
+ stopButton.disabled = true;
28
+ status.textContent = message;
29
+ }
30
+
31
+ function selectStep(index) {
32
+ steps.value = String(Math.max(0, Math.min(index, trace.length - 1)));
33
+ const selected = trace[Number(steps.value)];
34
+ show('step-position', selected ? `Step ${Number(steps.value) + 1} of ${trace.length}` : 'No scan steps.');
35
+ show('decisions', selected ? JSON.stringify(selected, null, 2) : 'Run a specification to inspect its decisions.');
36
+ }
37
+
38
+ function display(result) {
39
+ if (!result || typeof result !== 'object') throw new Error('The worker returned an invalid result.');
40
+ if (typeof result.error === 'string') {
41
+ show('diagnostics', result.error);
42
+ show('tokens', 'Execution failed.');
43
+ show('generated', 'Generation did not finish.');
44
+ show('console', 'No console output.');
45
+ show('graph', 'No automaton is available.');
46
+ show('dot', '');
47
+ stop('The specification or input failed. Read the diagnostic below.');
48
+ return;
49
+ }
50
+ if (!Array.isArray(result.tokens) || !Array.isArray(result.steps) || typeof result.generated !== 'string' || typeof result.dot !== 'string') {
51
+ throw new Error('The worker returned an invalid result.');
52
+ }
53
+ show('tokens', JSON.stringify(result.tokens, null, 2));
54
+ show('diagnostics', result.diagnostics || 'No diagnostics.');
55
+ show('generated', result.generated);
56
+ show('console', result.console || 'No console output.');
57
+ dot = result.dot;
58
+ show('dot', dot);
59
+ show('graph', 'Select Draw DFA to load Graphviz and render this automaton.');
60
+ trace = result.steps;
61
+ steps.max = String(Math.max(0, trace.length - 1));
62
+ steps.disabled = trace.length === 0;
63
+ selectStep(0);
64
+ stop(`${result.tokens.length} token${result.tokens.length === 1 ? '' : 's'}, ${trace.length} step${trace.length === 1 ? '' : 's'}. Ruby ${result.ruby_version}, Prism ${result.prism_version}.`);
65
+ show('metrics', `${(Number(result.wasm_bytes) / 1_048_576).toFixed(2)} MiB Ruby download; download/compile ${Math.round(Number(result.download_ms))} ms; VM and flexr startup ${Math.round(Number(result.startup_ms))} ms. Cached downloads may be faster.`);
66
+ }
67
+
68
+ function run() {
69
+ stop();
70
+ try {
71
+ const state = validateState({ source: source.value, input: input.value, mode: mode.value });
72
+ show('tokens', 'Running…');
73
+ show('diagnostics', 'Compiling…');
74
+ show('generated', 'Generating…');
75
+ show('graph', 'Compiling…');
76
+ show('dot', 'Compiling…');
77
+ show('console', 'Running…');
78
+ graphWorker?.terminate();
79
+ clearTimeout(graphTimer);
80
+ trace = [];
81
+ dot = '';
82
+ selectStep(0);
83
+ const url = new URL(workerUrl, location.href).href;
84
+ const bootstrap = `let queued; self.onmessage=e=>{queued=e.data}; import(${JSON.stringify(url)}).then(()=>{if(queued)self.dispatchEvent(new MessageEvent('message',{data:queued}))});`;
85
+ const blob = URL.createObjectURL(new Blob([bootstrap], { type: 'text/javascript' }));
86
+ worker = new Worker(blob, { type: 'module' });
87
+ URL.revokeObjectURL(blob);
88
+ runButton.disabled = true;
89
+ stopButton.disabled = false;
90
+ status.textContent = 'Loading Ruby locally. The runtime is about 31 MiB before compression.';
91
+ timer = setTimeout(() => stop('Runtime loading exceeded 30 seconds. Check the connection and retry.'), 30_000);
92
+ worker.onerror = () => stop('The worker failed. Retry, or reduce the specification.');
93
+ let started = false;
94
+ const currentWorker = worker;
95
+ worker.onmessage = ({ data }) => {
96
+ if (currentWorker !== worker) return;
97
+ if (data?.phase === 'ready' && !started) {
98
+ started = true;
99
+ clearTimeout(timer);
100
+ status.textContent = 'Running the specification in a worker…';
101
+ timer = setTimeout(() => stop('Execution exceeded 5 seconds and was stopped. Reduce the specification or input.'), 5_000);
102
+ } else if (data?.phase === 'error') {
103
+ stop(String(data.error));
104
+ } else if (data?.phase === 'result') {
105
+ try { display(data.result); } catch (error) { stop(error.message); }
106
+ }
107
+ };
108
+ const base = new URL(`${import.meta.env.BASE_URL}/playground-runtime/`.replaceAll('//', '/'), location.origin).href;
109
+ worker.postMessage({ state, base });
110
+ } catch (error) { stop(error.message); }
111
+ }
112
+
113
+ function safeSvg(text) {
114
+ const parsed = new DOMParser().parseFromString(text, 'image/svg+xml');
115
+ const allowed = new Set(['svg', 'g', 'title', 'polygon', 'path', 'ellipse', 'text', 'polyline', 'rect', 'line', 'circle']);
116
+ const attributes = new Set(['viewBox', 'width', 'height', 'fill', 'stroke', 'transform', 'points', 'd', 'rx', 'ry', 'cx', 'cy', 'x', 'y', 'font-family', 'font-size', 'text-anchor', 'stroke-width']);
117
+ function copy(node) {
118
+ if (node.nodeType === Node.TEXT_NODE) return document.createTextNode(node.textContent);
119
+ if (node.nodeType !== Node.ELEMENT_NODE || !allowed.has(node.localName)) return document.createTextNode('');
120
+ const clean = document.createElementNS('http://www.w3.org/2000/svg', node.localName);
121
+ for (const attribute of node.attributes) {
122
+ if (attributes.has(attribute.name) && !/url\s*\(/i.test(attribute.value)) clean.setAttribute(attribute.name, attribute.value);
123
+ }
124
+ for (const child of node.childNodes) clean.append(copy(child));
125
+ return clean;
126
+ }
127
+ if (parsed.documentElement.localName !== 'svg') throw new Error('Graphviz returned invalid SVG.');
128
+ return copy(parsed.documentElement);
129
+ }
130
+
131
+ function drawGraph() {
132
+ if (!dot) { show('graph', 'Run a specification first.'); return; }
133
+ graphWorker?.terminate();
134
+ clearTimeout(graphTimer);
135
+ show('graph', 'Drawing DFA…');
136
+ graphWorker = new Worker(graphWorkerUrl, { type: 'module' });
137
+ graphTimer = setTimeout(() => {
138
+ graphWorker.terminate();
139
+ show('graph', 'Drawing exceeded 5 seconds. Inspect the DOT output instead.');
140
+ }, 5000);
141
+ graphWorker.onmessage = ({ data }) => {
142
+ clearTimeout(graphTimer);
143
+ graphWorker.terminate();
144
+ try {
145
+ if (typeof data?.svg !== 'string' || data.svg.length > 2_000_000) throw new Error(data?.error || 'The diagram is too large. Inspect the DOT output.');
146
+ document.querySelector('#graph').replaceChildren(safeSvg(data.svg));
147
+ } catch (error) { show('graph', error.message); }
148
+ };
149
+ graphWorker.onerror = () => {
150
+ clearTimeout(graphTimer);
151
+ graphWorker.terminate();
152
+ show('graph', 'Graphviz could not draw this DFA. Inspect the DOT output instead.');
153
+ };
154
+ graphWorker.postMessage(dot);
155
+ }
156
+
157
+ let languagePresets;
158
+ document.querySelector('#preset').addEventListener('change', async event => {
159
+ stop();
160
+ const name = event.target.value;
161
+ try {
162
+ let preset = PRESETS[name];
163
+ if (!preset) {
164
+ status.textContent = 'Loading the repository example…';
165
+ languagePresets ||= fetch(`${import.meta.env.BASE_URL}/playground-runtime/presets.json`.replaceAll('//', '/'))
166
+ .then(response => {
167
+ if (!response.ok) throw new Error('The example presets could not be downloaded.');
168
+ return response.json();
169
+ });
170
+ preset = (await languagePresets)[name];
171
+ }
172
+ const state = validateState({ ...preset, mode: mode.value });
173
+ if (event.target.value !== name) return;
174
+ source.value = state.source;
175
+ input.value = state.input;
176
+ status.textContent = 'Preset loaded. Edit it or run it as written.';
177
+ } catch (error) { status.textContent = error.message; }
178
+ });
179
+ document.querySelector('[data-action="run"]').addEventListener('click', run);
180
+ document.querySelector('[data-action="stop"]').addEventListener('click', () => stop());
181
+ document.querySelector('[data-action="draw"]').addEventListener('click', drawGraph);
182
+ document.querySelector('[data-action="previous"]').addEventListener('click', () => selectStep(Number(steps.value) - 1));
183
+ document.querySelector('[data-action="next"]').addEventListener('click', () => selectStep(Number(steps.value) + 1));
184
+ steps.addEventListener('input', () => selectStep(Number(steps.value)));
185
+ document.querySelector('[data-action="share"]').addEventListener('click', async () => {
186
+ try {
187
+ const hash = encodeState({ source: source.value, input: input.value, mode: mode.value });
188
+ history.replaceState(null, '', `#${hash}`);
189
+ const link = document.querySelector('#share-link');
190
+ link.value = location.href;
191
+ link.hidden = false;
192
+ link.select();
193
+ await navigator.clipboard?.writeText(location.href);
194
+ status.textContent = 'Share link ready below. Opening it loads the text without running it.';
195
+ } catch (error) { status.textContent = error.message; }
196
+ });
197
+
198
+ source.value = PRESETS.longest.source;
199
+ input.value = PRESETS.longest.input;
200
+ function restoreShare() {
201
+ if (location.hash.length <= 1) return;
202
+ try {
203
+ const state = decodeState(location.hash.slice(1));
204
+ source.value = state.source;
205
+ input.value = state.input;
206
+ mode.value = state.mode;
207
+ status.textContent = 'Shared source loaded. Review it before selecting Run.';
208
+ } catch (error) { status.textContent = error.message; }
209
+ }
210
+ restoreShare();
211
+ window.addEventListener('hashchange', restoreShare);
@@ -0,0 +1,11 @@
1
+ import { instance } from '@viz-js/viz';
2
+
3
+ self.onmessage = async ({ data }) => {
4
+ try {
5
+ if (typeof data !== 'string' || data.length > 500_000) throw new Error('DFA is too large to draw. Inspect its DOT output instead.');
6
+ const viz = await instance();
7
+ self.postMessage({ svg: viz.renderString(data, { format: 'svg', engine: 'dot' }) });
8
+ } catch (error) {
9
+ self.postMessage({ error: error instanceof Error ? error.message : String(error) });
10
+ }
11
+ };
@@ -0,0 +1,33 @@
1
+ export const PRESETS = {
2
+ longest: {
3
+ input: 'if == total',
4
+ source: `class Lexer < Flexr::Lexer
5
+ emits :EQ, :ASSIGN, :IF, :IDENT
6
+ rule(/[ \\t\\n]+/, skip: true)
7
+ rule(/==/, emit: :EQ)
8
+ rule(/=/, emit: :ASSIGN)
9
+ rule(/if/, emit: :IF)
10
+ rule(/[a-z_][a-z0-9_]*/, emit: :IDENT)
11
+ end`,
12
+ },
13
+ calculator: {
14
+ input: '12 + 3 * 4',
15
+ source: `class Lexer < Flexr::Lexer
16
+ emits :INTEGER, :PLUS, :STAR
17
+ rule(/[ \\t\\n]+/, skip: true)
18
+ rule(/[0-9]+/) { emit :INTEGER, text.to_i }
19
+ rule(/\\+/, emit: :PLUS)
20
+ rule(/\\*/, emit: :STAR)
21
+ end`,
22
+ },
23
+ json: {
24
+ input: '{"ok": true, "count": 2}',
25
+ source: `class Lexer < Flexr::Lexer
26
+ rule(/[ \\t\\n]+/, skip: true)
27
+ rule(/[{}:,\\[\\]]/) { emit text }
28
+ rule(/true|false|null/, emit: :KEYWORD)
29
+ rule(/"[^"\\n]*"/, emit: :STRING)
30
+ rule(/[0-9]+/) { emit :NUMBER, text.to_i }
31
+ end`,
32
+ },
33
+ };
@@ -0,0 +1,34 @@
1
+ import { DefaultRubyVM } from '@ruby/wasm-wasi/dist/browser';
2
+ import { validateState } from './share.mjs';
3
+
4
+ function rubyData(value) {
5
+ const bytes = new TextEncoder().encode(JSON.stringify(value));
6
+ let binary = '';
7
+ for (let index = 0; index < bytes.length; index += 4096) binary += String.fromCharCode(...bytes.subarray(index, index + 4096));
8
+ return `JSON.parse(${JSON.stringify(btoa(binary))}.unpack1("m0"))`;
9
+ }
10
+
11
+ export async function createRuntime(binary, assets) {
12
+ const module = await WebAssembly.compile(binary);
13
+ return {
14
+ async run(request, ready = () => {}) {
15
+ validateState(request);
16
+ const start = performance.now();
17
+ const { vm } = await DefaultRubyVM(module, { consolePrint: false });
18
+ vm.eval(`require "json"; require "fileutils"
19
+ ${rubyData(assets.files)}.each do |path, source|
20
+ FileUtils.mkdir_p(File.dirname(path))
21
+ File.write(path, source)
22
+ end
23
+ $LOAD_PATH.unshift("/app/lib")
24
+ require "flexr/cli"
25
+ require "flexr/trace"
26
+ load "/app/playground.rb"
27
+ `);
28
+ const startupMs = performance.now() - start;
29
+ ready(startupMs);
30
+ const result = JSON.parse(vm.eval(`FlexrPlayground.run(${rubyData(request)})`).toString());
31
+ return { ...result, startup_ms: startupMs };
32
+ },
33
+ };
34
+ }
@@ -0,0 +1,30 @@
1
+ export const MAX_TEXT = 20_000;
2
+ const MAX_HASH = 220_000;
3
+
4
+ export function validateState(value) {
5
+ if (!value || typeof value !== 'object' || typeof value.source !== 'string' || typeof value.input !== 'string' ||
6
+ !['runtime', 'generated'].includes(value.mode) || value.source.length > MAX_TEXT || value.input.length > MAX_TEXT) {
7
+ throw new Error(`Invalid playground state. Source and input are limited to ${MAX_TEXT} characters each.`);
8
+ }
9
+ return { source: value.source, input: value.input, mode: value.mode };
10
+ }
11
+
12
+ export function encodeState(value) {
13
+ const bytes = new TextEncoder().encode(JSON.stringify(validateState(value)));
14
+ let binary = '';
15
+ for (let index = 0; index < bytes.length; index += 4096) binary += String.fromCharCode(...bytes.subarray(index, index + 4096));
16
+ const encoded = btoa(binary).replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/, '');
17
+ if (encoded.length > MAX_HASH) throw new Error('Share link is too large. Reduce the source or input.');
18
+ return encoded;
19
+ }
20
+
21
+ export function decodeState(hash) {
22
+ if (hash.length > MAX_HASH) throw new Error('Share link is too large.');
23
+ try {
24
+ const binary = atob(hash.replaceAll('-', '+').replaceAll('_', '/'));
25
+ const bytes = Uint8Array.from(binary, character => character.charCodeAt(0));
26
+ return validateState(JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)));
27
+ } catch {
28
+ throw new Error('Invalid playground share link.');
29
+ }
30
+ }
@@ -0,0 +1,29 @@
1
+ import { createRuntime } from './runtime.mjs';
2
+
3
+ export async function run({ state, base }) {
4
+ try {
5
+ const start = performance.now();
6
+ const [response, data] = await Promise.all([fetch(`${base}ruby.wasm`), fetch(`${base}flexr.json`)]);
7
+ if (!response.ok || !data.ok) throw new Error('The Ruby runtime could not be downloaded. Retry when the connection is available.');
8
+ const binary = await response.arrayBuffer();
9
+ const assets = await data.json();
10
+ const runtime = await createRuntime(binary, assets);
11
+ const downloadMs = performance.now() - start;
12
+ for (const name of ['fetch', 'XMLHttpRequest', 'WebSocket', 'WebTransport', 'EventSource', 'Worker', 'importScripts']) {
13
+ for (let target = globalThis; target; target = Object.getPrototypeOf(target)) {
14
+ const property = Object.getOwnPropertyDescriptor(target, name);
15
+ if (target === globalThis || property?.configurable) {
16
+ Object.defineProperty(target, name, { value: undefined, configurable: false, writable: false });
17
+ }
18
+ }
19
+ }
20
+ const result = await runtime.run(state, startupMs => postMessage({ phase: 'ready', startupMs }));
21
+ const payload = JSON.stringify({ ...result, wasm_bytes: binary.byteLength, download_ms: downloadMs });
22
+ if (new TextEncoder().encode(payload).byteLength > 4_000_000) throw new Error('Output exceeds 4 MB. Reduce the input or number of states.');
23
+ postMessage({ phase: 'result', result: JSON.parse(payload) });
24
+ } catch (error) {
25
+ postMessage({ phase: 'error', error: error instanceof Error ? error.message : String(error) });
26
+ }
27
+ }
28
+
29
+ self.onmessage = ({ data }) => run(data);