File size: 9,502 Bytes
bc20498
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
'use strict';
require('@ungap/with-resolvers');
const { $$ } = require('basic-devtools');

const { JSModules, assign, create, createOverload, createResolved, dedent, defineProperty, nodeInfo, registerJSModules } = require('./utils.js');
const { getDetails } = require('./script-handler.js');
const { registry: defaultRegistry, prefixes, configs } = require('./interpreters.js');
const { getRuntimeID } = require('./loader.js');
const { addAllListeners } = require('./listeners.js');
const { Hook, XWorker: XW } = require('./xworker.js');
const { polluteJS, js: jsHooks, code: codeHooks } = require('./hooks.js');
const workerURL = (require('./worker/url.js'));

const CUSTOM_SELECTORS = [];
exports.CUSTOM_SELECTORS = CUSTOM_SELECTORS;

const customObserver = new Map();
exports.customObserver = customObserver;

/**
 * @typedef {Object} Runtime custom configuration
 * @prop {object} interpreter the bootstrapped interpreter
 * @prop {(url:string, options?: object) => Worker} XWorker an XWorker constructor that defaults to same interpreter on the Worker.
 * @prop {object} config a cloned config used to bootstrap the interpreter
 * @prop {(code:string) => any} run an utility to run code within the interpreter
 * @prop {(code:string) => Promise<any>} runAsync an utility to run code asynchronously within the interpreter
 * @prop {(path:string, data:ArrayBuffer) => void} writeFile an utility to write a file in the virtual FS, if available
 */

const types = new Map();
const waitList = new Map();

// REQUIRES INTEGRATION TEST
/* c8 ignore start */
/**
 * @param {Element} node any DOM element registered via define.
 */
const handleCustomType = async (node) => {
    for (const selector of CUSTOM_SELECTORS) {
        if (node.matches(selector)) {
            const type = types.get(selector);
            const details = registry.get(type);
            const { resolve } = waitList.get(type);
            const { options, known } = details;

            if (known.has(node)) return;
            known.add(node);

            for (const [selector, callback] of customObserver) {
                if (node.matches(selector)) await callback(node);
            }

            const {
                interpreter: runtime,
                configURL,
                config,
                version,
                env,
                onerror,
                hooks,
            } = options;

            let error;
            try {
                const worker = workerURL(node);
                if (worker) {
                    const xworker = XW.call(new Hook(null, hooks), worker, {
                        ...nodeInfo(node, type),
                        version,
                        configURL,
                        type: runtime,
                        custom: type,
                        config: node.getAttribute('config') || config || {},
                        async: node.hasAttribute('async')
                    });
                    defineProperty(node, 'xworker', { value: xworker });
                    resolve({ type, xworker });
                    return;
                }
            }
            // let the custom type handle errors via its `io`
            catch (workerError) {
                error = workerError;
            }

            const name = getRuntimeID(runtime, version);
            const id = env || `${name}${config ? `|${config}` : ''}`;
            const { interpreter: engine, XWorker: Worker } = getDetails(
                type,
                id,
                name,
                version,
                config,
                configURL,
                runtime
            );

            const interpreter = await engine;

            const module = create(defaultRegistry.get(runtime));

            const hook = new Hook(interpreter, hooks);

            const XWorker = function XWorker(...args) {
                return Worker.apply(hook, args);
            };

            const resolved = {
                ...createResolved(
                    module,
                    type,
                    structuredClone(configs.get(name)),
                    interpreter,
                ),
                XWorker,
            };

            registerJSModules(runtime, module, interpreter, JSModules);
            module.registerJSModule(interpreter, 'polyscript', {
                XWorker,
                config: resolved.config,
                currentScript: type.startsWith('_') ? null : node,
                js_modules: JSModules,
            });

            // patch methods accordingly to hooks (and only if needed)
            for (const suffix of ['Run', 'RunAsync']) {
                let before = '';
                let after = '';

                for (const key of codeHooks) {
                    const value = hooks?.main?.[key];
                    if (value && key.endsWith(suffix)) {
                        if (key.startsWith('codeBefore'))
                            before = dedent(value());
                        else
                            after = dedent(value());
                    }
                }

                if (before || after) {
                    createOverload(
                        module,
                        `r${suffix.slice(1)}`,
                        before,
                        after,
                    );
                }

                let beforeCB, afterCB;
                // ignore onReady and onWorker
                for (let i = 2; i < jsHooks.length; i++) {
                    const key = jsHooks[i];
                    const value = hooks?.main?.[key];
                    if (value && key.endsWith(suffix)) {
                        if (key.startsWith('onBefore'))
                            beforeCB = value;
                        else
                            afterCB = value;
                    }
                }
                polluteJS(module, resolved, node, suffix.endsWith('Async'), beforeCB, afterCB);
            }

            details.queue = details.queue.then(() => {
                resolve(resolved);
                if (error) onerror?.(error, node);
                return hooks?.main?.onReady?.(resolved, node);
            });
        }
    }
};
exports.handleCustomType = handleCustomType;

/**
 * @type {Map<string, {options:object, known:WeakSet<Element>}>}
 */
const registry = new Map();

/**
 * @typedef {Object} CustomOptions custom configuration
 * @prop {'pyodide' | 'micropython' | 'ruby-wasm-wasi' | 'wasmoon'} interpreter the interpreter to use
 * @prop {string} [version] the optional interpreter version to use
 * @prop {string} [config] the optional config to use within such interpreter
 */

let dontBotherCount = 0;

/**
 * Allows custom types and components on the page to receive interpreters to execute any code
 * @param {string} type the unique `<script type="...">` identifier
 * @param {CustomOptions} options the custom type configuration
 */
const define = (type, options) => {
    // allow no-type to be bootstrapped out of the box
    let dontBother = type == null;

    if (dontBother)
        type = `_ps${dontBotherCount++}`;
    else if (defaultRegistry.has(type) || registry.has(type))
        throw new Error(`<script type="${type}"> already registered`);

    if (!defaultRegistry.has(options?.interpreter))
        throw new Error('Unspecified interpreter');

    // allows reaching out the interpreter helpers on events
    defaultRegistry.set(type, defaultRegistry.get(options.interpreter));

    // allows selector -> registry by type
    const selectors = [`script[type="${type}"]`];

    // ensure a Promise can resolve once a custom type has been bootstrapped
    whenDefined(type);

    if (dontBother) {
        // add a script then cleanup everything once that's ready
        const { hooks } = options;
        const onReady = hooks?.main?.onReady;
        options = {
            ...options,
            hooks: {
                ...hooks,
                main: {
                    ...hooks?.main,
                    onReady(resolved, node) {
                        CUSTOM_SELECTORS.splice(CUSTOM_SELECTORS.indexOf(type), 1);
                        defaultRegistry.delete(type);
                        registry.delete(type);
                        waitList.delete(type);
                        node.remove();
                        onReady?.(resolved);
                    }
                }
            },
        };
        document.head.append(
            assign(document.createElement('script'), { type })
        );
    }
    else {
        selectors.push(`${type}-script`);
        prefixes.push(`${type}-`);
    }

    for (const selector of selectors) types.set(selector, type);
    CUSTOM_SELECTORS.push(...selectors);

    // ensure always same env for this custom type
    registry.set(type, {
        options: assign({ env: type }, options),
        known: new WeakSet(),
        queue: Promise.resolve(),
    });

    if (!dontBother) addAllListeners(document);
    $$(selectors.join(',')).forEach(handleCustomType);
};
exports.define = define;

/**
 * Resolves whenever a defined custom type is bootstrapped on the page
 * @param {string} type the unique `<script type="...">` identifier
 * @returns {Promise<object>}
 */
const whenDefined = (type) => {
    if (!waitList.has(type)) waitList.set(type, Promise.withResolvers());
    return waitList.get(type).promise;
};
exports.whenDefined = whenDefined;
/* c8 ignore stop */