Skip to content
File

Blob: src/pyodide/internal/pool/sentinel.ts

typescript53 lines
1// This is https://github.com/pyodide/pyodide/blob/main/src/core/sentinel.ts.
2// It goes into `pyodide.js` not `pyodide.asm.js`. We don't use `pyodide.js` so we have to reproduce
3// it here.
4 
5import { wasmInstantiate } from 'pyodide-internal:pool/builtin_wrappers';
6 
7// Per https://github.com/tc39/proposal-arraybuffer-base64/issues/51#issuecomment-3010378969, we
8// should be able to replace `decodeBase64()` with `Uint8Array.fromBase64()` once we update to a v8
9// released after September 2nd.
10const base64Lookup = new Uint8Array(128);
11for (let t = 0; t < 64; t++) {
12 let idx;
13 if (t < 26) {
14 idx = t + 65;
15 } else if (t < 52) {
16 idx = t + 71;
17 } else if (t < 62) {
18 idx = t - 4;
19 } else {
20 idx = t * 4 - 205;
21 }
22 base64Lookup[idx] = t;
23}
24 
25function decodeBase64(input: string): Uint8Array {
26 const outputSize = ((input.length * 3) / 4) | 0;
27 const output = new Uint8Array(outputSize);
28 let inIdx = 0;
29 let outIdx = 0;
30 while (inIdx < input.length) {
31 const chunk1 = base64Lookup[input.charCodeAt(inIdx++)]!;
32 const chunk2 = base64Lookup[input.charCodeAt(inIdx++)]!;
33 const chunk3 = base64Lookup[input.charCodeAt(inIdx++)]!;
34 const chunk4 = base64Lookup[input.charCodeAt(inIdx++)]!;
35 output[outIdx++] = (chunk1 << 2) | (chunk2 >> 4);
36 output[outIdx++] = (chunk2 << 4) | (chunk3 >> 2);
37 output[outIdx++] = (chunk3 << 6) | chunk4;
38 }
39 return output;
40}
41 
42// This string is https://github.com/pyodide/pyodide/blob/main/src/core/sentinel.wat assembled and
43// hex encoded.
44const sentinelWasm = decodeBase64(
45 'AGFzbQEAAAABDANfAGAAAW9gAW8BfwMDAgECByECD2NyZWF0ZV9zZW50aW5lbAAAC2lzX3NlbnRpbmVsAAEKEwIHAPsBAPsbCwkAIAD7GvsUAAs'
46);
47 
48export async function getSentinelImport() {
49 const imports = {};
50 const { instance } = await wasmInstantiate(sentinelWasm, imports);
51 return instance.exports;
52}