generated from hrbrmstr/slightly-more-than-minimal
-
Notifications
You must be signed in to change notification settings - Fork 0
/
webr-worker.js.map
7 lines (7 loc) · 186 KB
/
webr-worker.js.map
1
2
3
4
5
6
7
{
"version": 3,
"sources": ["../src/node_modules/xmlhttprequest-ssl/lib/XMLHttpRequest.js", "../src/webR/compat.ts", "../src/webR/utils.ts", "../src/webR/chan/task-common.ts", "../src/webR/chan/message.ts", "../src/webR/chan/task-main.ts", "../src/webR/chan/queue.ts", "../src/webR/payload.ts", "../src/webR/chan/channel.ts", "../src/webR/chan/task-worker.ts", "../src/webR/emscripten.ts", "../src/webR/chan/channel-shared.ts", "../src/webR/chan/channel-service.ts", "../src/webR/chan/channel-common.ts", "../src/webR/robj.ts", "../src/webR/utils-r.ts", "../src/webR/robj-worker.ts", "../src/webR/webr-worker.ts"],
"sourcesContent": ["/**\n * Wrapper for built-in http.js to emulate the browser XMLHttpRequest object.\n *\n * This can be used with JS designed for browsers to improve reuse of code and\n * allow the use of existing libraries.\n *\n * Usage: include(\"XMLHttpRequest.js\") and use XMLHttpRequest per W3C specs.\n *\n * @author Dan DeFelippi <dan@driverdan.com>\n * @contributor David Ellis <d.f.ellis@ieee.org>\n * @license MIT\n */\n\nvar fs = require('fs');\nvar Url = require('url');\nvar spawn = require('child_process').spawn;\n\n/**\n * Module exports.\n */\n\nmodule.exports = XMLHttpRequest;\n\n// backwards-compat\nXMLHttpRequest.XMLHttpRequest = XMLHttpRequest;\n\n/**\n * `XMLHttpRequest` constructor.\n *\n * Supported options for the `opts` object are:\n *\n * - `agent`: An http.Agent instance; http.globalAgent may be used; if 'undefined', agent usage is disabled\n *\n * @param {Object} opts optional \"options\" object\n */\n\nfunction XMLHttpRequest(opts) {\n \"use strict\";\n\n opts = opts || {};\n\n /**\n * Private variables\n */\n var self = this;\n var http = require('http');\n var https = require('https');\n\n // Holds http.js objects\n var request;\n var response;\n\n // Request settings\n var settings = {};\n\n // Disable header blacklist.\n // Not part of XHR specs.\n var disableHeaderCheck = false;\n\n // Set some default headers\n var defaultHeaders = {\n \"User-Agent\": \"node-XMLHttpRequest\",\n \"Accept\": \"*/*\"\n };\n\n var headers = Object.assign({}, defaultHeaders);\n\n // These headers are not user setable.\n // The following are allowed but banned in the spec:\n // * user-agent\n var forbiddenRequestHeaders = [\n \"accept-charset\",\n \"accept-encoding\",\n \"access-control-request-headers\",\n \"access-control-request-method\",\n \"connection\",\n \"content-length\",\n \"content-transfer-encoding\",\n \"cookie\",\n \"cookie2\",\n \"date\",\n \"expect\",\n \"host\",\n \"keep-alive\",\n \"origin\",\n \"referer\",\n \"te\",\n \"trailer\",\n \"transfer-encoding\",\n \"upgrade\",\n \"via\"\n ];\n\n // These request methods are not allowed\n var forbiddenRequestMethods = [\n \"TRACE\",\n \"TRACK\",\n \"CONNECT\"\n ];\n\n // Send flag\n var sendFlag = false;\n // Error flag, used when errors occur or abort is called\n var errorFlag = false;\n var abortedFlag = false;\n\n // Event listeners\n var listeners = {};\n\n /**\n * Constants\n */\n\n this.UNSENT = 0;\n this.OPENED = 1;\n this.HEADERS_RECEIVED = 2;\n this.LOADING = 3;\n this.DONE = 4;\n\n /**\n * Public vars\n */\n\n // Current state\n this.readyState = this.UNSENT;\n\n // default ready state change handler in case one is not set or is set late\n this.onreadystatechange = null;\n\n // Result & response\n this.responseText = \"\";\n this.responseXML = \"\";\n this.response = Buffer.alloc(0);\n this.status = null;\n this.statusText = null;\n\n /**\n * Private methods\n */\n\n /**\n * Check if the specified header is allowed.\n *\n * @param string header Header to validate\n * @return boolean False if not allowed, otherwise true\n */\n var isAllowedHttpHeader = function(header) {\n return disableHeaderCheck || (header && forbiddenRequestHeaders.indexOf(header.toLowerCase()) === -1);\n };\n\n /**\n * Check if the specified method is allowed.\n *\n * @param string method Request method to validate\n * @return boolean False if not allowed, otherwise true\n */\n var isAllowedHttpMethod = function(method) {\n return (method && forbiddenRequestMethods.indexOf(method) === -1);\n };\n\n /**\n * Public methods\n */\n\n /**\n * Open the connection. Currently supports local server requests.\n *\n * @param string method Connection method (eg GET, POST)\n * @param string url URL for the connection.\n * @param boolean async Asynchronous connection. Default is true.\n * @param string user Username for basic authentication (optional)\n * @param string password Password for basic authentication (optional)\n */\n this.open = function(method, url, async, user, password) {\n this.abort();\n errorFlag = false;\n abortedFlag = false;\n\n // Check for valid request method\n if (!isAllowedHttpMethod(method)) {\n throw new Error(\"SecurityError: Request method not allowed\");\n }\n\n settings = {\n \"method\": method,\n \"url\": url.toString(),\n \"async\": (typeof async !== \"boolean\" ? true : async),\n \"user\": user || null,\n \"password\": password || null\n };\n\n setState(this.OPENED);\n };\n\n /**\n * Disables or enables isAllowedHttpHeader() check the request. Enabled by default.\n * This does not conform to the W3C spec.\n *\n * @param boolean state Enable or disable header checking.\n */\n this.setDisableHeaderCheck = function(state) {\n disableHeaderCheck = state;\n };\n\n /**\n * Sets a header for the request.\n *\n * @param string header Header name\n * @param string value Header value\n * @return boolean Header added\n */\n this.setRequestHeader = function(header, value) {\n if (this.readyState != this.OPENED) {\n throw new Error(\"INVALID_STATE_ERR: setRequestHeader can only be called when state is OPEN\");\n }\n if (!isAllowedHttpHeader(header)) {\n console.warn('Refused to set unsafe header \"' + header + '\"');\n return false;\n }\n if (sendFlag) {\n throw new Error(\"INVALID_STATE_ERR: send flag is true\");\n }\n headers[header] = value;\n return true;\n };\n\n /**\n * Gets a header from the server response.\n *\n * @param string header Name of header to get.\n * @return string Text of the header or null if it doesn't exist.\n */\n this.getResponseHeader = function(header) {\n if (typeof header === \"string\"\n && this.readyState > this.OPENED\n && response.headers[header.toLowerCase()]\n && !errorFlag\n ) {\n return response.headers[header.toLowerCase()];\n }\n\n return null;\n };\n\n /**\n * Gets all the response headers.\n *\n * @return string A string with all response headers separated by CR+LF\n */\n this.getAllResponseHeaders = function() {\n if (this.readyState < this.HEADERS_RECEIVED || errorFlag) {\n return \"\";\n }\n var result = \"\";\n\n for (var i in response.headers) {\n // Cookie headers are excluded\n if (i !== \"set-cookie\" && i !== \"set-cookie2\") {\n result += i + \": \" + response.headers[i] + \"\\r\\n\";\n }\n }\n return result.substr(0, result.length - 2);\n };\n\n /**\n * Gets a request header\n *\n * @param string name Name of header to get\n * @return string Returns the request header or empty string if not set\n */\n this.getRequestHeader = function(name) {\n // @TODO Make this case insensitive\n if (typeof name === \"string\" && headers[name]) {\n return headers[name];\n }\n\n return \"\";\n };\n\n /**\n * Sends the request to the server.\n *\n * @param string data Optional data to send as request body.\n */\n this.send = function(data) {\n if (this.readyState != this.OPENED) {\n throw new Error(\"INVALID_STATE_ERR: connection must be opened before send() is called\");\n }\n\n if (sendFlag) {\n throw new Error(\"INVALID_STATE_ERR: send has already been called\");\n }\n\n var ssl = false, local = false;\n var url = Url.parse(settings.url);\n var host;\n // Determine the server\n switch (url.protocol) {\n case 'https:':\n ssl = true;\n // SSL & non-SSL both need host, no break here.\n case 'http:':\n host = url.hostname;\n break;\n\n case 'file:':\n local = true;\n break;\n\n case undefined:\n case '':\n host = \"localhost\";\n break;\n\n default:\n throw new Error(\"Protocol not supported.\");\n }\n\n // Load files off the local filesystem (file://)\n if (local) {\n if (settings.method !== \"GET\") {\n throw new Error(\"XMLHttpRequest: Only GET method is supported\");\n }\n\n if (settings.async) {\n fs.readFile(unescape(url.pathname), function(error, data) {\n if (error) {\n self.handleError(error, error.errno || -1);\n } else {\n self.status = 200;\n self.responseText = data.toString('utf8');\n self.response = data;\n setState(self.DONE);\n }\n });\n } else {\n try {\n this.response = fs.readFileSync(unescape(url.pathname));\n this.responseText = this.response.toString('utf8');\n this.status = 200;\n setState(self.DONE);\n } catch(e) {\n this.handleError(e, e.errno || -1);\n }\n }\n\n return;\n }\n\n // Default to port 80. If accessing localhost on another port be sure\n // to use http://localhost:port/path\n var port = url.port || (ssl ? 443 : 80);\n // Add query string if one is used\n var uri = url.pathname + (url.search ? url.search : '');\n\n // Set the Host header or the server may reject the request\n headers[\"Host\"] = host;\n if (!((ssl && port === 443) || port === 80)) {\n headers[\"Host\"] += ':' + url.port;\n }\n\n // Set Basic Auth if necessary\n if (settings.user) {\n if (typeof settings.password == \"undefined\") {\n settings.password = \"\";\n }\n var authBuf = new Buffer(settings.user + \":\" + settings.password);\n headers[\"Authorization\"] = \"Basic \" + authBuf.toString(\"base64\");\n }\n\n // Set content length header\n if (settings.method === \"GET\" || settings.method === \"HEAD\") {\n data = null;\n } else if (data) {\n headers[\"Content-Length\"] = Buffer.isBuffer(data) ? data.length : Buffer.byteLength(data);\n\n if (!headers[\"Content-Type\"]) {\n headers[\"Content-Type\"] = \"text/plain;charset=UTF-8\";\n }\n } else if (settings.method === \"POST\") {\n // For a post with no data set Content-Length: 0.\n // This is required by buggy servers that don't meet the specs.\n headers[\"Content-Length\"] = 0;\n }\n\n var agent = opts.agent || false;\n var options = {\n host: host,\n port: port,\n path: uri,\n method: settings.method,\n headers: headers,\n agent: agent\n };\n\n if (ssl) {\n options.pfx = opts.pfx;\n options.key = opts.key;\n options.passphrase = opts.passphrase;\n options.cert = opts.cert;\n options.ca = opts.ca;\n options.ciphers = opts.ciphers;\n options.rejectUnauthorized = opts.rejectUnauthorized === false ? false : true;\n }\n\n // Reset error flag\n errorFlag = false;\n // Handle async requests\n if (settings.async) {\n // Use the proper protocol\n var doRequest = ssl ? https.request : http.request;\n\n // Request is being sent, set send flag\n sendFlag = true;\n\n // As per spec, this is called here for historical reasons.\n self.dispatchEvent(\"readystatechange\");\n\n // Handler for the response\n var responseHandler = function(resp) {\n // Set response var to the response we got back\n // This is so it remains accessable outside this scope\n response = resp;\n // Check for redirect\n // @TODO Prevent looped redirects\n if (response.statusCode === 302 || response.statusCode === 303 || response.statusCode === 307) {\n // Change URL to the redirect location\n settings.url = response.headers.location;\n var url = Url.parse(settings.url);\n // Set host var in case it's used later\n host = url.hostname;\n // Options for the new request\n var newOptions = {\n hostname: url.hostname,\n port: url.port,\n path: url.path,\n method: response.statusCode === 303 ? 'GET' : settings.method,\n headers: headers\n };\n\n if (ssl) {\n newOptions.pfx = opts.pfx;\n newOptions.key = opts.key;\n newOptions.passphrase = opts.passphrase;\n newOptions.cert = opts.cert;\n newOptions.ca = opts.ca;\n newOptions.ciphers = opts.ciphers;\n newOptions.rejectUnauthorized = opts.rejectUnauthorized === false ? false : true;\n }\n\n // Issue the new request\n request = doRequest(newOptions, responseHandler).on('error', errorHandler);\n request.end();\n // @TODO Check if an XHR event needs to be fired here\n return;\n }\n\n setState(self.HEADERS_RECEIVED);\n self.status = response.statusCode;\n\n response.on('data', function(chunk) {\n // Make sure there's some data\n if (chunk) {\n var data = Buffer.from(chunk);\n self.responseText += data.toString('utf8');\n self.response = Buffer.concat([self.response, data]);\n }\n // Don't emit state changes if the connection has been aborted.\n if (sendFlag) {\n setState(self.LOADING);\n }\n });\n\n response.on('end', function() {\n if (sendFlag) {\n // The sendFlag needs to be set before setState is called. Otherwise if we are chaining callbacks\n // there can be a timing issue (the callback is called and a new call is made before the flag is reset).\n sendFlag = false;\n // Discard the 'end' event if the connection has been aborted\n setState(self.DONE);\n }\n });\n\n response.on('error', function(error) {\n self.handleError(error);\n });\n }\n\n // Error handler for the request\n var errorHandler = function(error) {\n self.handleError(error);\n }\n\n // Create the request\n request = doRequest(options, responseHandler).on('error', errorHandler);\n\n if (opts.autoUnref) {\n request.on('socket', (socket) => {\n socket.unref();\n });\n }\n\n // Node 0.4 and later won't accept empty data. Make sure it's needed.\n if (data) {\n request.write(data);\n }\n\n request.end();\n\n self.dispatchEvent(\"loadstart\");\n } else { // Synchronous\n // Create a temporary file for communication with the other Node process\n var contentFile = \".node-xmlhttprequest-content-\" + process.pid;\n var syncFile = \".node-xmlhttprequest-sync-\" + process.pid;\n fs.writeFileSync(syncFile, \"\", \"utf8\");\n // The async request the other Node process executes\n var execString = \"var http = require('http'), https = require('https'), fs = require('fs');\"\n + \"var doRequest = http\" + (ssl ? \"s\" : \"\") + \".request;\"\n + \"var options = \" + JSON.stringify(options) + \";\"\n + \"var responseText = '';\"\n + \"var responseData = Buffer.alloc(0);\"\n + \"var req = doRequest(options, function(response) {\"\n + \"response.on('data', function(chunk) {\"\n + \" var data = Buffer.from(chunk);\"\n + \" responseText += data.toString('utf8');\"\n + \" responseData = Buffer.concat([responseData, data]);\"\n + \"});\"\n + \"response.on('end', function() {\"\n + \"fs.writeFileSync('\" + contentFile + \"', JSON.stringify({err: null, data: {statusCode: response.statusCode, headers: response.headers, text: responseText, data: responseData.toString('base64')}}), 'utf8');\"\n + \"fs.unlinkSync('\" + syncFile + \"');\"\n + \"});\"\n + \"response.on('error', function(error) {\"\n + \"fs.writeFileSync('\" + contentFile + \"', 'NODE-XMLHTTPREQUEST-ERROR:' + JSON.stringify(error), 'utf8');\"\n + \"fs.unlinkSync('\" + syncFile + \"');\"\n + \"});\"\n + \"}).on('error', function(error) {\"\n + \"fs.writeFileSync('\" + contentFile + \"', 'NODE-XMLHTTPREQUEST-ERROR:' + JSON.stringify(error), 'utf8');\"\n + \"fs.unlinkSync('\" + syncFile + \"');\"\n + \"});\"\n + (data ? \"req.write('\" + JSON.stringify(data).slice(1,-1).replace(/'/g, \"\\\\'\") + \"');\":\"\")\n + \"req.end();\";\n // Start the other Node Process, executing this string\n var syncProc = spawn(process.argv[0], [\"-e\", execString]);\n var statusText;\n while(fs.existsSync(syncFile)) {\n // Wait while the sync file is empty\n }\n self.responseText = fs.readFileSync(contentFile, 'utf8');\n // Kill the child process once the file has data\n syncProc.stdin.end();\n // Remove the temporary file\n fs.unlinkSync(contentFile);\n if (self.responseText.match(/^NODE-XMLHTTPREQUEST-ERROR:/)) {\n // If the file returned an error, handle it\n var errorObj = JSON.parse(self.responseText.replace(/^NODE-XMLHTTPREQUEST-ERROR:/, \"\"));\n self.handleError(errorObj, 503);\n } else {\n // If the file returned okay, parse its data and move to the DONE state\n self.status = self.responseText.replace(/^NODE-XMLHTTPREQUEST-STATUS:([0-9]*),.*/, \"$1\");\n var resp = JSON.parse(self.responseText.replace(/^NODE-XMLHTTPREQUEST-STATUS:[0-9]*,(.*)/, \"$1\"));\n response = {\n statusCode: self.status,\n headers: resp.data.headers\n };\n self.responseText = resp.data.text;\n self.response = Buffer.from(resp.data.data, 'base64');\n setState(self.DONE, true);\n }\n }\n };\n\n /**\n * Called when an error is encountered to deal with it.\n * @param status {number} HTTP status code to use rather than the default (0) for XHR errors.\n */\n this.handleError = function(error, status) {\n this.status = status || 0;\n this.statusText = error;\n this.responseText = error.stack;\n errorFlag = true;\n setState(this.DONE);\n };\n\n /**\n * Aborts a request.\n */\n this.abort = function() {\n if (request) {\n request.abort();\n request = null;\n }\n\n headers = Object.assign({}, defaultHeaders);\n this.responseText = \"\";\n this.responseXML = \"\";\n this.response = Buffer.alloc(0);\n\n errorFlag = abortedFlag = true\n if (this.readyState !== this.UNSENT\n && (this.readyState !== this.OPENED || sendFlag)\n && this.readyState !== this.DONE) {\n sendFlag = false;\n setState(this.DONE);\n }\n this.readyState = this.UNSENT;\n };\n\n /**\n * Adds an event listener. Preferred method of binding to events.\n */\n this.addEventListener = function(event, callback) {\n if (!(event in listeners)) {\n listeners[event] = [];\n }\n // Currently allows duplicate callbacks. Should it?\n listeners[event].push(callback);\n };\n\n /**\n * Remove an event callback that has already been bound.\n * Only works on the matching funciton, cannot be a copy.\n */\n this.removeEventListener = function(event, callback) {\n if (event in listeners) {\n // Filter will return a new array with the callback removed\n listeners[event] = listeners[event].filter(function(ev) {\n return ev !== callback;\n });\n }\n };\n\n /**\n * Dispatch any events, including both \"on\" methods and events attached using addEventListener.\n */\n this.dispatchEvent = function (event) {\n if (typeof self[\"on\" + event] === \"function\") {\n if (this.readyState === this.DONE && settings.async)\n setImmediate(function() { self[\"on\" + event]() })\n else\n self[\"on\" + event]()\n }\n if (event in listeners) {\n for (let i = 0, len = listeners[event].length; i < len; i++) {\n if (this.readyState === this.DONE)\n setImmediate(function() { listeners[event][i].call(self) })\n else\n listeners[event][i].call(self)\n }\n }\n };\n\n /**\n * Changes readyState and calls onreadystatechange.\n *\n * @param int state New state\n */\n var setState = function(state) {\n if ((self.readyState === state) || (self.readyState === self.UNSENT && abortedFlag))\n return\n\n self.readyState = state;\n\n if (settings.async || self.readyState < self.OPENED || self.readyState === self.DONE) {\n self.dispatchEvent(\"readystatechange\");\n }\n\n if (self.readyState === self.DONE) {\n let fire\n\n if (abortedFlag)\n fire = \"abort\"\n else if (errorFlag)\n fire = \"error\"\n else\n fire = \"load\"\n\n self.dispatchEvent(fire)\n\n // @TODO figure out InspectorInstrumentation::didLoadXHR(cookie)\n self.dispatchEvent(\"loadend\");\n }\n };\n};\n", "interface Process {\n browser: string | undefined;\n release: { [key: string]: string };\n}\ndeclare let process: Process;\n\nexport const IN_NODE =\n typeof process !== 'undefined' &&\n process.release &&\n process.release.name === 'node' &&\n typeof process.browser === 'undefined';\n\n// Adapted from https://github.com/pyodide/pyodide/blob/main/src/js/compat.ts\nexport let loadScript: (url: string) => Promise<void>;\nif (globalThis.document) {\n loadScript = (url) =>\n new Promise((resolve, reject) => {\n const script = document.createElement('script');\n script.src = url;\n script.onload = () => resolve();\n script.onerror = reject;\n document.head.appendChild(script);\n });\n} else if (globalThis.importScripts) {\n loadScript = async (url) => {\n try {\n globalThis.importScripts(url);\n } catch (e) {\n if (e instanceof TypeError) {\n await import(url);\n } else {\n throw e;\n }\n }\n };\n} else if (IN_NODE) {\n loadScript = async (url: string) => {\n const nodePathMod = (await import('path')).default;\n await import(nodePathMod.resolve(url));\n };\n} else {\n throw new Error('Cannot determine runtime environment');\n}\n", "import { IN_NODE } from './compat';\n\nexport type ResolveFn = (_value?: unknown) => void;\nexport type RejectFn = (_reason?: any) => void;\n\nexport function promiseHandles() {\n const out = {\n resolve: (_value?: unknown) => {},\n reject: (_reason?: any) => {},\n promise: null as unknown as Promise<unknown>,\n };\n\n const promise = new Promise((resolve, reject) => {\n out.resolve = resolve;\n out.reject = reject;\n });\n out.promise = promise;\n\n return out;\n}\n\nexport function sleep(ms: number) {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nexport function replaceInObject<T>(\n obj: T | T[],\n test: (obj: any) => boolean,\n replacer: (obj: any, ...replacerArgs: any[]) => unknown,\n ...replacerArgs: unknown[]\n): T | T[] {\n if (obj === null || typeof obj !== 'object') {\n return obj;\n }\n if (test(obj)) {\n return replacer(obj, ...replacerArgs) as T;\n }\n if (Array.isArray(obj) || ArrayBuffer.isView(obj)) {\n return (obj as unknown[]).map((v) =>\n replaceInObject(v, test, replacer, ...replacerArgs)\n ) as T[];\n }\n return Object.fromEntries(\n Object.entries(obj).map(([k, v], i) => [k, replaceInObject(v, test, replacer, ...replacerArgs)])\n ) as T;\n}\n\n/* Workaround for loading a cross-origin script.\n *\n * When fetching a worker script, the fetch is required by the spec to\n * use \"same-origin\" mode. This is to avoid loading a worker with a\n * cross-origin global scope, which can allow for a cross-origin\n * restriction bypass.\n *\n * When the fetch URL begins with 'http', we assume the request is\n * cross-origin. We download the content of the URL using a XHR first,\n * create a blob URL containing the requested content, then load the\n * blob URL as a script.\n *\n * The origin of a blob URL is the same as that of the environment that\n * created the URL, and so the global scope of the resulting worker is\n * no longer cross-origin. In that case, the cross-origin restriction\n * bypass is not possible, and the script is permitted to be loaded.\n */\nexport function newCrossOriginWorker(url: string, cb: (worker: Worker) => void): void {\n const req = new XMLHttpRequest();\n req.open('get', url, true);\n req.onload = () => {\n const worker = new Worker(URL.createObjectURL(new Blob([req.responseText])));\n cb(worker);\n };\n req.send();\n}\n\nexport function isCrossOrigin(urlString: string) {\n if (IN_NODE) return false;\n const url1 = new URL(location.href);\n const url2 = new URL(urlString, location.origin);\n if (url1.host === url2.host && url1.port === url2.port && url1.protocol === url2.protocol) {\n return false;\n }\n return true;\n}\n\nexport function throwUnreachable(context?: string) {\n let msg = 'Reached the unreachable';\n msg = msg + (context ? ': ' + context : '.');\n\n throw new Error(msg);\n}\n", "// Original code from Synclink and Comlink. Released under Apache 2.0.\n\nexport const SZ_BUF_DOESNT_FIT = 0;\nexport const SZ_BUF_FITS_IDX = 1;\nexport const SZ_BUF_SIZE_IDX = 0;\n\nexport interface Endpoint extends EventSource {\n postMessage(message: any, transfer?: Transferable[]): void;\n start?: () => void;\n}\n\nexport interface EventSource {\n addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: {}): void;\n\n removeEventListener(\n type: string,\n listener: EventListenerOrEventListenerObject,\n options?: {}\n ): void;\n}\n\nexport function toWireValue(value: any): [any, Transferable[]] {\n return [value, transferCache.get(value) || []];\n}\n\nconst transferCache = new WeakMap<any, Transferable[]>();\nexport function transfer<T>(obj: T, transfers: Transferable[]): T {\n transferCache.set(obj, transfers);\n return obj;\n}\n\nexport type UUID = string;\n\nexport function isUUID(x: any): x is UUID {\n return typeof x === 'string' && x.length === UUID_LENGTH;\n}\n\nexport const UUID_LENGTH = 63;\n\nexport function generateUUID(): UUID {\n const result = Array.from({ length: 4 }, randomSegment).join('-');\n if (result.length !== UUID_LENGTH) {\n throw new Error('comlink internal error: UUID has the wrong length');\n }\n return result;\n}\n\nfunction randomSegment() {\n let result = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER).toString(16);\n const pad = 15 - result.length;\n if (pad > 0) {\n result = Array.from({ length: pad }, () => 0).join('') + result;\n }\n return result;\n}\n", "/**\n * WebR communication channel messaging and request types.\n * @module Message\n */\nimport { generateUUID, transfer, UUID } from './task-common';\n\n/** A webR communication channel message. */\nexport interface Message {\n type: string;\n data?: any;\n}\n\n/** A webR communication channel request. */\nexport interface Request {\n type: 'request';\n data: {\n uuid: UUID;\n msg: Message;\n };\n}\n\n/** A webR communication channel response. */\nexport interface Response {\n type: 'response';\n data: {\n uuid: UUID;\n resp: unknown;\n };\n}\n\n/** @internal */\nexport function newRequest(msg: Message, transferables?: [Transferable]): Request {\n return newRequestResponseMessage(\n {\n type: 'request',\n data: {\n uuid: generateUUID(),\n msg: msg,\n },\n },\n transferables\n );\n}\n\n/** @internal */\nexport function newResponse(uuid: UUID, resp: unknown, transferables?: [Transferable]): Response {\n return newRequestResponseMessage(\n {\n type: 'response',\n data: {\n uuid,\n resp,\n },\n },\n transferables\n );\n}\n\n/** @internal */\nfunction newRequestResponseMessage<T>(msg: T, transferables?: [Transferable]): T {\n // Signal to Synclink that the data contains objects we wish to\n // transfer, as in `postMessage()`\n if (transferables) {\n transfer(msg, transferables);\n }\n return msg;\n}\n\n/** A webR communication channel sync-request.\n * @internal\n */\nexport interface SyncRequest {\n type: 'sync-request';\n data: {\n msg: Message;\n reqData: SyncRequestData;\n };\n}\n\n/** Transfer data required when using sync-request with SharedArrayBuffer.\n * @internal */\nexport interface SyncRequestData {\n taskId?: number;\n sizeBuffer: Int32Array;\n signalBuffer: Int32Array;\n dataBuffer: Uint8Array;\n}\n\n/** @internal */\nexport function newSyncRequest(msg: Message, data: SyncRequestData): SyncRequest {\n return {\n type: 'sync-request',\n data: { msg, reqData: data },\n };\n}\n\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder('utf-8');\n\n/**\n * Encode data for transfering from worker thread to main thread.\n * @param {any} data The message data to be serialised and encoded.\n * @return {Uint8Array} The encoded data.\n * @internal\n * */\nexport function encodeData(data: any): Uint8Array {\n // TODO: Pass a `replacer` function\n return encoder.encode(JSON.stringify(data));\n}\n\n/**\n * Decode data that has been transferred from worker thread to main thread.\n * @param {any} data The message data to be decoded.\n * @return {unknown} The data after decoding.\n * @internal\n * */\nexport function decodeData(data: Uint8Array): unknown {\n return JSON.parse(decoder.decode(data)) as unknown;\n}\n", "// Original code from Synclink and Comlink. Released under Apache 2.0.\n\nimport { Endpoint, SZ_BUF_FITS_IDX, SZ_BUF_SIZE_IDX, generateUUID } from './task-common';\n\nimport { sleep } from '../utils';\nimport { SyncRequestData, encodeData } from './message';\n\nimport { IN_NODE } from '../compat';\nimport type { Worker as NodeWorker } from 'worker_threads';\n\nconst encoder = new TextEncoder();\n\n/**\n * Respond to a blocking request. Most of the work has already been done in\n * asynclink, we are just responsible here for getting the return value back to\n * the requester through this slightly convoluted Atomics protocol.\n *\n * @param {Endpoint} endpoint A message port to receive messages from. Other\n * thread is blocked, so we can't send messages back.\n * @param {SyncRequestData} data The message that was recieved. We will use it\n * to read out the buffers to write the answer into. NOTE: requester\n * owns buffers.\n * @param {any} response The value we want to send back to the requester. We\n * have to encode it into data_buffer.\n */\nexport async function syncResponse(endpoint: Endpoint, data: SyncRequestData, response: any) {\n try {\n let { taskId, sizeBuffer, dataBuffer, signalBuffer } = data;\n // console.warn(msg);\n\n const bytes = encodeData(response);\n const fits = bytes.length <= dataBuffer.length;\n\n Atomics.store(sizeBuffer, SZ_BUF_SIZE_IDX, bytes.length);\n Atomics.store(sizeBuffer, SZ_BUF_FITS_IDX, +fits);\n if (!fits) {\n // console.log(\" need larger buffer\", taskId)\n // Request larger buffer\n const [uuid, dataPromise] = requestResponseMessage(endpoint);\n\n // Write UUID into dataBuffer so syncRequest knows where to respond to.\n dataBuffer.set(encoder.encode(uuid));\n await signalRequester(signalBuffer, taskId!);\n\n // Wait for response with new bigger dataBuffer\n dataBuffer = (await dataPromise).dataBuffer as Uint8Array;\n }\n\n // Encode result into dataBuffer\n dataBuffer.set(bytes);\n Atomics.store(sizeBuffer, SZ_BUF_FITS_IDX, +true);\n\n // console.log(\" signaling completion\", taskId)\n await signalRequester(signalBuffer, taskId as number);\n } catch (e) {\n console.warn(e);\n }\n}\n\nfunction requestResponseMessage(ep: Endpoint): [string, Promise<any>] {\n const id = generateUUID();\n return [\n id,\n new Promise((resolve) => {\n if (IN_NODE) {\n (ep as unknown as NodeWorker).once('message', (message: any) => {\n if (!message.id || message.id !== id) {\n return;\n }\n resolve(message);\n });\n } else {\n ep.addEventListener('message', function l(ev: MessageEvent) {\n if (!ev.data || !ev.data.id || ev.data.id !== id) {\n return;\n }\n ep.removeEventListener('message', l as EventListenerOrEventListenerObject);\n resolve(ev.data);\n } as EventListenerOrEventListenerObject);\n }\n if (ep.start) {\n ep.start();\n }\n }),\n ];\n}\n\nasync function signalRequester(signalBuffer: Int32Array, taskId: number) {\n const index = (taskId >> 1) % 32;\n let sleepTime = 1;\n while (Atomics.compareExchange(signalBuffer, index + 1, 0, taskId) !== 0) {\n // No Atomics.asyncWait except on Chrome =(\n await sleep(sleepTime);\n if (sleepTime < 32) {\n // exponential backoff\n sleepTime *= 2;\n }\n }\n Atomics.or(signalBuffer, 0, 1 << index);\n Atomics.notify(signalBuffer, 0);\n}\n", "// From https://stackoverflow.com/questions/47157428/how-to-implement-a-pseudo-blocking-async-queue-in-js-ts\n/**\n * @module Queue\n */\n\n/**\n * Asynchronous queue mechanism to be used by the communication channels.\n * @typeParam T The type of item to be stored in the queue.\n */\nexport class AsyncQueue<T> {\n #promises: Promise<T>[];\n #resolvers: ((t: T) => void)[];\n\n constructor() {\n this.#resolvers = [];\n this.#promises = [];\n }\n\n put(t: T) {\n if (!this.#resolvers.length) {\n this.#add();\n }\n const resolve = this.#resolvers.shift()!;\n resolve(t);\n }\n\n async get() {\n if (!this.#promises.length) {\n this.#add();\n }\n const promise = this.#promises.shift()!;\n return promise;\n }\n\n isEmpty() {\n return !this.#promises.length;\n }\n\n isBlocked() {\n return !!this.#resolvers.length;\n }\n\n get length() {\n return this.#promises.length - this.#resolvers.length;\n }\n\n #add() {\n this.#promises.push(\n new Promise((resolve) => {\n this.#resolvers.push(resolve);\n })\n );\n }\n}\n", "/**\n * Types containing references to R objects, raw data or errors over the webR\n * communication channel.\n * @module Payload\n */\nimport { WebRDataRaw, RPtr, RType } from './robj';\n\nexport type WebRPayloadRaw = {\n obj: WebRDataRaw;\n payloadType: 'raw';\n};\n\nexport type WebRPayloadPtr = {\n obj: {\n type?: RType;\n ptr: RPtr;\n methods?: string[];\n };\n payloadType: 'ptr';\n};\n\nexport type WebRPayloadErr = {\n obj: {\n message: string;\n name: string;\n stack?: string;\n };\n payloadType: 'err';\n};\n\n// On the main side we shouldn't see any error payload as these are\n// rethrown as JS exceptions\nexport type WebRPayload = WebRPayloadRaw | WebRPayloadPtr;\nexport type WebRPayloadWorker = WebRPayloadRaw | WebRPayloadPtr | WebRPayloadErr;\n\n/* @internal */\nexport function webRPayloadError(payload: WebRPayloadErr): Error {\n const e = new Error(payload.obj.message);\n e.name = payload.obj.name;\n e.stack = payload.obj.stack;\n return e;\n}\n\n/**\n * Test for an WebRPayload instance.\n *\n * @param {any} value The object to test.\n * @returns {boolean} True if the object is an instance of an WebRPayload.\n */\nexport function isWebRPayload(value: any): value is WebRPayload {\n return value && typeof value === 'object' && 'payloadType' in value && 'obj' in value;\n}\n\n/**\n * Test for an WebRPayloadPtr instance.\n *\n * @param {any} value The object to test.\n * @returns {boolean} True if the object is an instance of an WebRPayloadPtr.\n */\nexport function isWebRPayloadPtr(value: any): value is WebRPayloadPtr {\n return isWebRPayload(value) && value.payloadType === 'ptr';\n}\n\n/**\n * Test for an WebRPayloadRaw instance.\n *\n * @param {any} value The object to test.\n * @returns {boolean} True if the object is an instance of an WebRPayloadRaw.\n */\nexport function isWebRPayloadRaw(value: any): value is WebRPayloadRaw {\n return isWebRPayload(value) && value.payloadType === 'raw';\n}\n", "/**\n * Interfaces for the webR main and worker thread communication channels.\n * @module Channel\n */\n\nimport { promiseHandles, ResolveFn, RejectFn } from '../utils';\nimport { AsyncQueue } from './queue';\nimport { Message, newRequest, Response } from './message';\nimport { WebRPayload, WebRPayloadWorker, webRPayloadError } from '../payload';\n\n// The channel structure is asymetric:\n//\n// - The main thread maintains the input and output queues. All\n// messages sent from main are stored in the input queue. The input\n// queue is pull-based, it's the worker that initiates a transfer\n// via a sync-request.\n//\n// The output queue is filled at the initiative of the worker. The\n// main thread asynchronously reads from this queue, typically in an\n// async infloop.\n//\n// - The worker synchronously reads from the input queue. Reading a\n// message blocks until an input is available. Writing a message to\n// the output queue is equivalent to calling `postMessage()` and\n// returns immediately.\n//\n// Note that the messages sent from main to worker need to be\n// serialised. There is no structured cloning involved, and\n// ArrayBuffers can't be transferred, only copied.\n\nexport abstract class ChannelMain {\n inputQueue = new AsyncQueue<Message>();\n outputQueue = new AsyncQueue<Message>();\n\n #parked = new Map<string, { resolve: ResolveFn; reject: RejectFn }>();\n\n abstract initialised: Promise<unknown>;\n abstract close(): void;\n abstract interrupt(): void;\n\n async read(): Promise<Message> {\n return await this.outputQueue.get();\n }\n\n async flush(): Promise<Message[]> {\n const msg: Message[] = [];\n while (!this.outputQueue.isEmpty()) {\n msg.push(await this.read());\n }\n return msg;\n }\n\n write(msg: Message): void {\n this.inputQueue.put(msg);\n }\n\n async request(msg: Message, transferables?: [Transferable]): Promise<WebRPayload> {\n const req = newRequest(msg, transferables);\n\n const { resolve, reject, promise } = promiseHandles();\n this.#parked.set(req.data.uuid, { resolve, reject });\n\n this.write(req);\n return promise as Promise<WebRPayload>;\n }\n\n protected resolveResponse(msg: Response) {\n const uuid = msg.data.uuid;\n const handles = this.#parked.get(uuid);\n\n if (handles) {\n const payload = msg.data.resp as WebRPayloadWorker;\n this.#parked.delete(uuid);\n\n if (payload.payloadType === 'err') {\n handles.reject(webRPayloadError(payload));\n } else {\n handles.resolve(payload);\n }\n } else {\n console.warn(\"Can't find request.\");\n }\n }\n}\n\nexport interface ChannelWorker {\n resolve(): void;\n write(msg: Message, transfer?: [Transferable]): void;\n read(): Message;\n handleInterrupt(): void;\n setInterrupt(interrupt: () => void): void;\n run(args: string[]): void;\n inputOrDispatch: () => number;\n setDispatchHandler: (dispatch: (msg: Message) => void) => void;\n}\n", "// Original code from Synclink and Comlink. Released under Apache 2.0.\n\nimport {\n Endpoint,\n SZ_BUF_DOESNT_FIT,\n SZ_BUF_FITS_IDX,\n SZ_BUF_SIZE_IDX,\n UUID_LENGTH,\n} from './task-common';\n\nimport { newSyncRequest, Message, decodeData } from './message';\n\nconst decoder = new TextDecoder('utf-8');\n\nexport class SyncTask {\n endpoint: Endpoint;\n msg: Message;\n transfers: Transferable[];\n\n #scheduled = false;\n #resolved: boolean;\n #result?: any;\n #exception?: any;\n\n // sync only\n taskId?: number;\n #syncGen?: Generator<void, unknown, void>;\n sizeBuffer?: Int32Array;\n signalBuffer?: Int32Array;\n syncifier = new _Syncifier();\n\n constructor(endpoint: Endpoint, msg: Message, transfers: Transferable[] = []) {\n this.endpoint = endpoint;\n this.msg = msg;\n this.transfers = transfers;\n this.#resolved = false;\n }\n\n scheduleSync() {\n if (this.#scheduled) {\n return;\n }\n this.#scheduled = true;\n\n this.syncifier.scheduleTask(this);\n this.#syncGen = this.doSync();\n this.#syncGen.next();\n return this;\n }\n\n poll() {\n if (!this.#scheduled) {\n throw new Error('Task not synchronously scheduled');\n }\n\n const { done, value } = this.#syncGen!.next();\n if (!done) {\n return false;\n }\n\n this.#resolved = true;\n this.#result = value;\n\n return true;\n }\n\n *doSync() {\n // just use syncRequest.\n const { endpoint, msg, transfers } = this;\n const sizeBuffer = new Int32Array(new SharedArrayBuffer(8));\n const signalBuffer = this.signalBuffer!;\n const taskId = this.taskId;\n\n // Ensure status is cleared. We will notify\n let dataBuffer = acquireDataBuffer(UUID_LENGTH);\n // console.log(\"===requesting\", taskId);\n\n const syncMsg = newSyncRequest(msg, {\n sizeBuffer,\n dataBuffer,\n signalBuffer,\n taskId,\n });\n\n endpoint.postMessage(syncMsg, transfers);\n yield;\n\n if (Atomics.load(sizeBuffer, SZ_BUF_FITS_IDX) === SZ_BUF_DOESNT_FIT) {\n // There wasn't enough space, make a bigger dataBuffer.\n // First read uuid for response out of current dataBuffer\n const id = decoder.decode(dataBuffer.slice(0, UUID_LENGTH));\n releaseDataBuffer(dataBuffer);\n const size = Atomics.load(sizeBuffer, SZ_BUF_SIZE_IDX);\n dataBuffer = acquireDataBuffer(size);\n // console.log(\"===bigger data buffer\", taskId);\n endpoint.postMessage({ id, dataBuffer });\n yield;\n }\n\n const size = Atomics.load(sizeBuffer, SZ_BUF_SIZE_IDX);\n // console.log(\"===completing\", taskId);\n return decodeData(dataBuffer.slice(0, size));\n }\n\n get result() {\n if (this.#exception) {\n throw this.#exception;\n }\n // console.log(this.#resolved);\n if (this.#resolved) {\n return this.#result as unknown;\n }\n throw new Error('Not ready.');\n }\n\n syncify(): any {\n this.scheduleSync();\n this.syncifier.syncifyTask(this);\n return this.result;\n }\n}\n\nclass _Syncifier {\n nextTaskId: Int32Array;\n signalBuffer: Int32Array;\n tasks: Map<number, SyncTask>;\n\n constructor() {\n this.nextTaskId = new Int32Array([1]);\n this.signalBuffer = new Int32Array(new SharedArrayBuffer(32 * 4 + 4));\n this.tasks = new Map();\n }\n\n scheduleTask(task: SyncTask) {\n task.taskId = this.nextTaskId[0];\n this.nextTaskId[0] += 2;\n task.signalBuffer = this.signalBuffer;\n this.tasks.set(task.taskId, task);\n }\n\n waitOnSignalBuffer() {\n const timeout = 50;\n for (;;) {\n const status = Atomics.wait(this.signalBuffer, 0, 0, timeout);\n switch (status) {\n case 'ok':\n case 'not-equal':\n return;\n case 'timed-out':\n if (interruptBuffer[0] !== 0) {\n handleInterrupt();\n }\n break;\n default:\n throw new Error('Unreachable');\n }\n }\n }\n\n *tasksIdsToWakeup() {\n const flag = Atomics.load(this.signalBuffer, 0);\n for (let i = 0; i < 32; i++) {\n const bit = 1 << i;\n if (flag & bit) {\n Atomics.and(this.signalBuffer, 0, ~bit);\n const wokenTask = Atomics.exchange(this.signalBuffer, i + 1, 0);\n yield wokenTask;\n }\n }\n }\n\n pollTasks(task?: SyncTask) {\n let result = false;\n for (const wokenTaskId of this.tasksIdsToWakeup()) {\n // console.log(\"poll task\", wokenTaskId, \"looking for\",task);\n const wokenTask = this.tasks.get(wokenTaskId);\n if (!wokenTask) {\n throw new Error(`Assertion error: unknown taskId ${wokenTaskId}.`);\n }\n if (wokenTask.poll()) {\n // console.log(\"completed task \", wokenTaskId, wokenTask, wokenTask._result);\n this.tasks.delete(wokenTaskId);\n if (wokenTask === task) {\n result = true;\n }\n }\n }\n return result;\n }\n\n syncifyTask(task: SyncTask) {\n for (;;) {\n this.waitOnSignalBuffer();\n // console.log(\"syncifyTask:: woke\");\n if (this.pollTasks(task)) {\n return;\n }\n }\n }\n}\n\nconst dataBuffers: Uint8Array[][] = [];\n\nfunction acquireDataBuffer(size: number): Uint8Array {\n const powerof2 = Math.ceil(Math.log2(size));\n if (!dataBuffers[powerof2]) {\n dataBuffers[powerof2] = [];\n }\n const result = dataBuffers[powerof2].pop();\n if (result) {\n result.fill(0);\n return result;\n }\n return new Uint8Array(new SharedArrayBuffer(2 ** powerof2));\n}\n\nfunction releaseDataBuffer(buffer: Uint8Array) {\n const powerof2 = Math.ceil(Math.log2(buffer.byteLength));\n dataBuffers[powerof2].push(buffer);\n}\n\nlet interruptBuffer = new Int32Array(new ArrayBuffer(4));\n\nlet handleInterrupt = (): void => {\n interruptBuffer[0] = 0;\n throw new Error('Interrupted!');\n};\n\n/**\n * Sets the interrupt handler. This is called when the computation is\n * interrupted. Should zero the interrupt buffer and throw an exception.\n * @internal\n */\nexport function setInterruptHandler(handler: () => void) {\n handleInterrupt = handler;\n}\n\n/**\n * Sets the interrupt buffer. Should be a shared array buffer. When element 0\n * is set non-zero it signals an interrupt.\n * @internal\n */\nexport function setInterruptBuffer(buffer: ArrayBufferLike) {\n interruptBuffer = new Int32Array(buffer);\n}\n", "import type { RPtr, RTypeNumber } from './robj';\nimport type { UnwindProtectException } from './utils-r';\n\nexport interface Module extends EmscriptenModule {\n /* Add mkdirTree to FS namespace, missing from @types/emscripten at the\n * time of writing.\n */\n FS: typeof FS & {\n mkdirTree(path: string): void;\n };\n ENV: { [key: string]: string };\n LDSO: {\n loadedLibsByName: { [key: string]: any };\n loadedLibsByHandle: { [key: number]: any };\n };\n monitorRunDependencies: (n: number) => void;\n noImageDecoding: boolean;\n noAudioDecoding: boolean;\n noWasmDecoding: boolean;\n setPrompt: (prompt: string) => void;\n canvasExec: (op: string) => void;\n downloadFileContent: (\n URL: string,\n headers: Array<string>\n ) => {\n status: number;\n response: string | ArrayBuffer;\n };\n // Exported Emscripten JS API\n allocateUTF8: typeof allocateUTF8;\n allocateUTF8OnStack: typeof allocateUTF8OnStack;\n getValue: typeof getValue;\n setValue: typeof setValue;\n UTF8ToString: typeof UTF8ToString;\n callMain: (args: string[]) => void;\n // R symbols from Rinternals.h\n _ATTRIB: (ptr: RPtr) => RPtr;\n _CAR: (ptr: RPtr) => RPtr;\n _CDR: (ptr: RPtr) => RPtr;\n _CLOENV: (ptr: RPtr) => RPtr;\n _COMPLEX: (ptr: RPtr) => RPtr;\n _FRAME: (ptr: RPtr) => RPtr;\n _INTEGER: (ptr: RPtr) => RPtr;\n _INTERNAL: (ptr: RPtr) => RPtr;\n _LENGTH: (ptr: RPtr) => number;\n _LOGICAL: (ptr: RPtr) => RPtr;\n _PRINTNAME: (ptr: RPtr) => RPtr;\n _R_CHAR: (ptr: RPtr) => RPtr;\n _RAW: (ptr: RPtr) => RPtr;\n _REAL: (ptr: RPtr) => RPtr;\n _SETCAR: (x: RPtr, y: RPtr) => void;\n _STRING_ELT: (ptr: RPtr, idx: number) => RPtr;\n _STRING_PTR: (ptr: RPtr) => RPtr;\n _SYMVALUE: (ptr: RPtr) => RPtr;\n _TAG: (ptr: RPtr) => RPtr;\n _TYPEOF: (ptr: RPtr) => RPtr;\n _VECTOR_ELT: (ptr: RPtr, idx: number) => RPtr;\n _R_lsInternal3: (env: RPtr, all: number, sorted: number) => RPtr;\n _R_MakeExternalPtr: (p: number, tag: RPtr, prot: RPtr) => RPtr;\n _R_NewEnv: (enclos: RPtr, hash: number, size: number) => RPtr;\n _R_ParseEvalString: (code: number, env: RPtr) => RPtr;\n _R_PreserveObject: (ptr: RPtr) => void;\n _R_ReleaseObject: (ptr: RPtr) => void;\n _Rf_ScalarReal: (n: number) => RPtr;\n _Rf_ScalarLogical: (l: number) => RPtr;\n _Rf_ScalarInteger: (n: number) => RPtr;\n _Rf_ScalarString: (s: string) => RPtr;\n _Rf_allocList: (len: number) => RPtr;\n _Rf_allocVector: (type: RTypeNumber, len: number) => RPtr;\n _Rf_defineVar: (symbol: RPtr, value: RPtr, env: RPtr) => void;\n _Rf_error: (msg: EmPtr) => void;\n _Rf_eval: (call: RPtr, env: RPtr) => RPtr;\n _Rf_findVarInFrame: (rho: RPtr, symbol: RPtr) => RPtr;\n _Rf_listAppend: (source: RPtr, target: RPtr) => RPtr;\n _Rf_getAttrib: (ptr1: RPtr, ptr2: RPtr) => RPtr;\n _Rf_install: (ptr: number) => RPtr;\n _Rf_installTrChar: (name: RPtr) => RPtr;\n _Rf_lang1: (ptr1: RPtr) => RPtr;\n _Rf_lang2: (ptr1: RPtr, ptr2: RPtr) => RPtr;\n _Rf_lang3: (ptr1: RPtr, ptr2: RPtr, ptr3: RPtr) => RPtr;\n _Rf_lang4: (ptr1: RPtr, ptr2: RPtr, ptr3: RPtr, ptr4: RPtr) => RPtr;\n _Rf_lang5: (ptr1: RPtr, ptr2: RPtr, ptr3: RPtr, ptr4: RPtr, ptr5: RPtr) => RPtr;\n _Rf_lang6: (ptr1: RPtr, ptr2: RPtr, ptr3: RPtr, ptr4: RPtr, ptr5: RPtr, ptr6: RPtr) => RPtr;\n _Rf_mkChar: (ptr: number) => RPtr;\n _Rf_mkString: (ptr: number) => RPtr;\n _Rf_onintr: () => void;\n _Rf_protect: (ptr: RPtr) => RPtr;\n _R_ContinueUnwind: (cont: RPtr) => never;\n _R_ProtectWithIndex: (ptr1: RPtr, ptr2: RPtr) => void;\n _R_Reprotect: (ptr1: RPtr, ptr2: RPtr) => void;\n _Rf_setAttrib: (ptr1: RPtr, ptr2: RPtr, ptr3: RPtr) => RPtr;\n _Rf_unprotect: (n: number) => void;\n _Rf_unprotect_ptr: (ptr: RPtr) => void;\n _R_BaseEnv: RPtr;\n _R_BracketSymbol: RPtr;\n _R_Bracket2Symbol: RPtr;\n _R_DollarSymbol: RPtr;\n _R_EmptyEnv: RPtr;\n _R_FalseValue: RPtr;\n _R_GlobalEnv: RPtr;\n _R_Interactive: RPtr;\n _R_NaInt: RPtr;\n _R_NaReal: RPtr;\n _R_NaString: RPtr;\n _R_LogicalNAValue: RPtr;\n _R_NilValue: RPtr;\n _R_TrueValue: RPtr;\n _R_NamesSymbol: RPtr;\n _R_UnboundValue: RPtr;\n _SET_STRING_ELT: (ptr: RPtr, idx: number, val: RPtr) => void;\n _SET_VECTOR_ELT: (ptr: RPtr, idx: number, val: RPtr) => void;\n // TODO: Namespace all webR properties\n webr: {\n UnwindProtectException: typeof UnwindProtectException;\n readConsole: () => number;\n resolveInit: () => void;\n handleEvents: () => void;\n evalJs: (code: RPtr) => number;\n };\n}\n\nexport const Module = {} as Module;\n\ntype EmPtr = ReturnType<typeof Module.allocateUTF8>;\n\nexport interface DictEmPtrs {\n [key: string]: EmPtr;\n}\n\nexport function dictEmFree(dict: { [key: string | number]: EmPtr }) {\n Object.keys(dict).forEach((key) => Module._free(dict[key]));\n}\n", "import { promiseHandles, newCrossOriginWorker, isCrossOrigin } from '../utils';\nimport { Message, Response, SyncRequest } from './message';\nimport { Endpoint } from './task-common';\nimport { syncResponse } from './task-main';\nimport { ChannelMain, ChannelWorker } from './channel';\nimport { ChannelType } from './channel-common';\nimport { WebROptions } from '../webr-main';\n\nimport { IN_NODE } from '../compat';\nimport type { Worker as NodeWorker } from 'worker_threads';\nif (IN_NODE) {\n (globalThis as any).Worker = require('worker_threads').Worker as NodeWorker;\n}\n\n// Main ----------------------------------------------------------------\n\nexport class SharedBufferChannelMain extends ChannelMain {\n #interruptBuffer?: Int32Array;\n\n initialised: Promise<unknown>;\n resolve: (_?: unknown) => void;\n close = () => {};\n\n constructor(config: Required<WebROptions>) {\n super();\n const initWorker = (worker: Worker) => {\n this.#handleEventsFromWorker(worker);\n this.close = () => worker.terminate();\n const msg = {\n type: 'init',\n data: { config, channelType: ChannelType.SharedArrayBuffer },\n } as Message;\n worker.postMessage(msg);\n };\n\n if (isCrossOrigin(config.WEBR_URL)) {\n newCrossOriginWorker(`${config.WEBR_URL}webr-worker.js`, (worker: Worker) =>\n initWorker(worker)\n );\n } else {\n const worker = new Worker(`${config.WEBR_URL}webr-worker.js`);\n initWorker(worker);\n }\n\n ({ resolve: this.resolve, promise: this.initialised } = promiseHandles());\n }\n\n interrupt() {\n if (!this.#interruptBuffer) {\n throw new Error('Failed attempt to interrupt before initialising interruptBuffer');\n }\n this.#interruptBuffer[0] = 1;\n }\n\n #handleEventsFromWorker(worker: Worker) {\n if (IN_NODE) {\n (worker as unknown as NodeWorker).on('message', (message: Message) => {\n this.#onMessageFromWorker(worker, message);\n });\n } else {\n worker.onmessage = (ev: MessageEvent) =>\n this.#onMessageFromWorker(worker, ev.data as Message);\n }\n }\n\n #onMessageFromWorker = async (worker: Worker, message: Message) => {\n if (!message || !message.type) {\n return;\n }\n\n switch (message.type) {\n case 'resolve':\n this.#interruptBuffer = new Int32Array(message.data as SharedArrayBuffer);\n this.resolve();\n return;\n\n case 'response':\n this.resolveResponse(message as Response);\n return;\n\n default:\n this.outputQueue.put(message);\n return;\n\n case 'sync-request': {\n const msg = message as SyncRequest;\n const payload = msg.data.msg;\n const reqData = msg.data.reqData;\n\n switch (payload.type) {\n case 'read': {\n const response = await this.inputQueue.get();\n await syncResponse(worker, reqData, response);\n break;\n }\n default:\n throw new TypeError(`Unsupported request type '${payload.type}'.`);\n }\n return;\n }\n case 'request':\n throw new TypeError(\n \"Can't send messages of type 'request' from a worker. Please Use 'sync-request' instead.\"\n );\n }\n };\n}\n\n// Worker --------------------------------------------------------------\n\nimport { SyncTask, setInterruptHandler, setInterruptBuffer } from './task-worker';\nimport { Module } from '../emscripten';\n\nexport class SharedBufferChannelWorker implements ChannelWorker {\n #ep: Endpoint;\n #dispatch: (msg: Message) => void = () => 0;\n #interruptBuffer = new Int32Array(new SharedArrayBuffer(4));\n #interrupt = () => {};\n\n constructor() {\n this.#ep = (IN_NODE ? require('worker_threads').parentPort : globalThis) as Endpoint;\n setInterruptBuffer(this.#interruptBuffer.buffer);\n setInterruptHandler(() => this.handleInterrupt());\n }\n\n resolve() {\n this.write({ type: 'resolve', data: this.#interruptBuffer.buffer });\n }\n\n write(msg: Message, transfer?: [Transferable]) {\n this.#ep.postMessage(msg, transfer);\n }\n\n read(): Message {\n const msg = { type: 'read' } as Message;\n const task = new SyncTask(this.#ep, msg);\n return task.syncify() as Message;\n }\n\n inputOrDispatch(): number {\n for (;;) {\n const msg = this.read();\n if (msg.type === 'stdin') {\n return Module.allocateUTF8(msg.data as string);\n }\n this.#dispatch(msg);\n }\n }\n\n run(args: string[]) {\n Module.callMain(args);\n }\n\n setInterrupt(interrupt: () => void) {\n this.#interrupt = interrupt;\n }\n\n handleInterrupt() {\n if (this.#interruptBuffer[0] !== 0) {\n this.#interruptBuffer[0] = 0;\n this.#interrupt();\n }\n }\n\n setDispatchHandler(dispatch: (msg: Message) => void) {\n this.#dispatch = dispatch;\n }\n}\n", "import { promiseHandles, newCrossOriginWorker, isCrossOrigin } from '../utils';\nimport {\n Message,\n newRequest,\n Response,\n Request,\n newResponse,\n encodeData,\n decodeData,\n} from './message';\nimport { Endpoint } from './task-common';\nimport { ChannelMain, ChannelWorker } from './channel';\nimport { ChannelType } from './channel-common';\nimport { WebROptions } from '../webr-main';\n\nimport { IN_NODE } from '../compat';\nimport type { Worker as NodeWorker } from 'worker_threads';\nif (IN_NODE) {\n (globalThis as any).Worker = require('worker_threads').Worker as NodeWorker;\n}\n\n// Main ----------------------------------------------------------------\n\nexport class ServiceWorkerChannelMain extends ChannelMain {\n initialised: Promise<unknown>;\n\n resolve: (_?: unknown) => void;\n close = () => {};\n\n #syncMessageCache = new Map<string, Message>();\n #registration?: ServiceWorkerRegistration;\n #interrupted = false;\n\n constructor(config: Required<WebROptions>) {\n super();\n const initWorker = (worker: Worker) => {\n this.#handleEventsFromWorker(worker);\n this.close = () => worker.terminate();\n this.#registerServiceWorker(`${config.SW_URL}webr-serviceworker.js`).then((clientId) => {\n const msg = {\n type: 'init',\n data: {\n config,\n channelType: ChannelType.ServiceWorker,\n clientId,\n location: window.location.href,\n },\n } as Message;\n worker.postMessage(msg);\n });\n };\n\n if (isCrossOrigin(config.SW_URL)) {\n newCrossOriginWorker(`${config.SW_URL}webr-worker.js`, (worker: Worker) =>\n initWorker(worker)\n );\n } else {\n const worker = new Worker(`${config.SW_URL}webr-worker.js`);\n initWorker(worker);\n }\n\n ({ resolve: this.resolve, promise: this.initialised } = promiseHandles());\n }\n\n activeRegistration(): ServiceWorker {\n if (!this.#registration?.active) {\n throw new Error('Attempted to obtain a non-existent active registration.');\n }\n return this.#registration.active;\n }\n\n interrupt() {\n this.#interrupted = true;\n }\n\n async #registerServiceWorker(url: string): Promise<string> {\n // Register service worker\n this.#registration = await navigator.serviceWorker.register(url);\n await navigator.serviceWorker.ready;\n window.addEventListener('beforeunload', () => {\n this.#registration?.unregister();\n });\n\n // Ensure we can communicate with service worker and we have a client ID\n const clientId = await new Promise<string>((resolve) => {\n navigator.serviceWorker.addEventListener(\n 'message',\n function listener(event: MessageEvent<{ type: string; clientId: string }>) {\n if (event.data.type === 'registration-successful') {\n navigator.serviceWorker.removeEventListener('message', listener);\n resolve(event.data.clientId);\n }\n }\n );\n this.activeRegistration().postMessage({ type: 'register-client-main' });\n });\n\n // Setup listener for service worker messages\n navigator.serviceWorker.addEventListener('message', (event: MessageEvent<Request>) => {\n this.#onMessageFromServiceWorker(event);\n });\n return clientId;\n }\n\n async #onMessageFromServiceWorker(event: MessageEvent<Message>) {\n if (event.data.type === 'request') {\n const uuid = event.data.data as string;\n const message = this.#syncMessageCache.get(uuid);\n if (!message) {\n throw new Error('Request not found during service worker XHR request');\n }\n this.#syncMessageCache.delete(uuid);\n switch (message.type) {\n case 'read': {\n const response = await this.inputQueue.get();\n this.activeRegistration().postMessage({\n type: 'wasm-webr-fetch-response',\n uuid: uuid,\n response: newResponse(uuid, response),\n });\n break;\n }\n case 'interrupt': {\n const response = this.#interrupted;\n this.activeRegistration().postMessage({\n type: 'wasm-webr-fetch-response',\n uuid: uuid,\n response: newResponse(uuid, response),\n });\n this.#interrupted = false;\n break;\n }\n default:\n throw new TypeError(`Unsupported request type '${message.type}'.`);\n }\n return;\n }\n }\n\n #handleEventsFromWorker(worker: Worker) {\n if (IN_NODE) {\n (worker as unknown as NodeWorker).on('message', (message: Message) => {\n this.#onMessageFromWorker(worker, message);\n });\n } else {\n worker.onmessage = (ev: MessageEvent) =>\n this.#onMessageFromWorker(worker, ev.data as Message);\n }\n }\n\n #onMessageFromWorker = async (worker: Worker, message: Message) => {\n if (!message || !message.type) {\n return;\n }\n\n switch (message.type) {\n case 'resolve':\n this.resolve();\n return;\n\n case 'response':\n this.resolveResponse(message as Response);\n return;\n\n default:\n this.outputQueue.put(message);\n return;\n\n case 'sync-request': {\n const request = message.data as Request;\n this.#syncMessageCache.set(request.data.uuid, request.data.msg);\n return;\n }\n\n case 'request':\n throw new TypeError(\n \"Can't send messages of type 'request' from a worker.\" +\n 'Use service worker fetch request instead.'\n );\n }\n };\n}\n\n// Worker --------------------------------------------------------------\n\nimport { Module } from '../emscripten';\n\nexport class ServiceWorkerChannelWorker implements ChannelWorker {\n #ep: Endpoint;\n #mainThreadId: string;\n #location: string;\n #dispatch: (msg: Message) => void = () => 0;\n #interrupt = () => {};\n onMessageFromMainThread: (msg: Message) => void = () => {};\n\n constructor(data: { clientId?: string; location?: string }) {\n if (!data.clientId || !data.location) {\n throw Error(\"Can't start service worker channel\");\n }\n this.#mainThreadId = data.clientId;\n this.#location = data.location;\n this.#ep = (IN_NODE ? require('worker_threads').parentPort : globalThis) as Endpoint;\n }\n\n resolve() {\n this.write({ type: 'resolve' });\n }\n\n write(msg: Message, transfer?: [Transferable]) {\n this.#ep.postMessage(msg, transfer);\n }\n\n syncRequest(message: Message): Response {\n /*\n * Browsers timeout service workers after about 5 minutes on inactivity.\n * See e.g. service_worker_version.cc in Chromium.\n *\n * To avoid the service worker being shut down, we timeout our XHR after\n * 1 minute and then resend the request as a keep-alive. The service worker\n * uses the message UUID to identify the request and continue waiting for a\n * response from where it left off.\n */\n const request = newRequest(message);\n this.write({ type: 'sync-request', data: request });\n\n let retryCount = 0;\n for (;;) {\n try {\n const url = new URL('__wasm__/webr-fetch-request/', this.#location);\n const xhr = new XMLHttpRequest();\n xhr.timeout = 60000;\n xhr.responseType = 'arraybuffer';\n xhr.open('POST', url, false);\n const fetchReqBody = {\n clientId: this.#mainThreadId,\n uuid: request.data.uuid,\n };\n xhr.send(encodeData(fetchReqBody));\n return decodeData(new Uint8Array(xhr.response as ArrayBuffer)) as Response;\n } catch (e: any) {\n if (e instanceof DOMException && retryCount++ < 1000) {\n console.log('Service worker request failed - resending request');\n } else {\n throw e;\n }\n }\n }\n }\n\n read(): Message {\n const response = this.syncRequest({ type: 'read' });\n return response.data.resp as Message;\n }\n\n inputOrDispatch(): number {\n for (;;) {\n const msg = this.read();\n if (msg.type === 'stdin') {\n return Module.allocateUTF8(msg.data as string);\n }\n this.#dispatch(msg);\n }\n }\n\n run(args: string[]) {\n Module.callMain(args);\n }\n\n setInterrupt(interrupt: () => void) {\n this.#interrupt = interrupt;\n }\n\n handleInterrupt() {\n /* During R computation we have no way to directly interrupt the worker\n * thread. Instead, we hook into R's PolledEvents. Since we are not using\n * SharedArrayBuffer as a signal method, we instead send a message to the\n * main thread to ask if we should interrupt R.\n */\n const response = this.syncRequest({ type: 'interrupt' });\n const interrupted = response.data.resp as boolean;\n if (interrupted) {\n this.#interrupt();\n }\n }\n\n setDispatchHandler(dispatch: (msg: Message) => void) {\n this.#dispatch = dispatch;\n }\n}\n", "import { SharedBufferChannelMain, SharedBufferChannelWorker } from './channel-shared';\nimport { ServiceWorkerChannelMain, ServiceWorkerChannelWorker } from './channel-service';\nimport { WebROptions } from '../webr-main';\nimport { isCrossOrigin } from '../utils';\nimport { IN_NODE } from '../compat';\n\n// This file refers to objects imported from `./channel-shared` and\n// `./channel-service.` These can't be included in `./channel` as this\n// causes a circular dependency issue.\n\nexport const ChannelType = {\n Automatic: 0,\n SharedArrayBuffer: 1,\n ServiceWorker: 2,\n} as const;\n\nexport type ChannelInitMessage = {\n type: string;\n data: {\n config: Required<WebROptions>;\n channelType: Exclude<\n (typeof ChannelType)[keyof typeof ChannelType],\n typeof ChannelType.Automatic\n >;\n clientId?: string;\n location?: string;\n };\n};\n\nexport function newChannelMain(data: Required<WebROptions>) {\n switch (data.channelType) {\n case ChannelType.SharedArrayBuffer:\n return new SharedBufferChannelMain(data);\n case ChannelType.ServiceWorker:\n return new ServiceWorkerChannelMain(data);\n case ChannelType.Automatic:\n default:\n if (IN_NODE || crossOriginIsolated) {\n return new SharedBufferChannelMain(data);\n }\n /*\n * TODO: If we are not cross-origin isolated but we can still use service\n * workers, we could setup a service worker to inject the relevant headers\n * to enable cross-origin isolation.\n */\n if ('serviceWorker' in navigator && !isCrossOrigin(data.SW_URL)) {\n return new ServiceWorkerChannelMain(data);\n }\n throw new Error(\"Can't initialise main thread communication channel\");\n }\n}\n\nexport function newChannelWorker(msg: ChannelInitMessage) {\n switch (msg.data.channelType) {\n case ChannelType.SharedArrayBuffer:\n return new SharedBufferChannelWorker();\n case ChannelType.ServiceWorker:\n return new ServiceWorkerChannelWorker(msg.data);\n default:\n throw new Error('Unknown worker channel type recieved');\n }\n}\n", "/**\n * Common module for working with R objects.\n * @module RObject\n */\nimport * as RMain from './robj-main';\nimport * as RWorker from './robj-worker';\n\nexport type RPtr = number;\n\nexport const RTypeMap = {\n null: 0,\n symbol: 1,\n pairlist: 2,\n closure: 3,\n environment: 4,\n promise: 5,\n call: 6,\n special: 7,\n builtin: 8,\n string: 9,\n logical: 10,\n integer: 13,\n double: 14,\n complex: 15,\n character: 16,\n dots: 17,\n any: 18,\n list: 19,\n expression: 20,\n bytecode: 21,\n pointer: 22,\n weakref: 23,\n raw: 24,\n s4: 25,\n new: 30,\n free: 31,\n function: 99,\n} as const;\nexport type RType = keyof typeof RTypeMap;\nexport type RTypeNumber = (typeof RTypeMap)[keyof typeof RTypeMap];\n\nexport type Complex = {\n re: number;\n im: number;\n};\n\nexport type WebRDataRaw =\n | number\n | string\n | boolean\n | undefined\n | null\n | void\n | Complex\n | Error\n | ArrayBuffer\n | ArrayBufferView\n | Array<WebRDataRaw>\n | Map<WebRDataRaw, WebRDataRaw>\n | Set<WebRDataRaw>\n | { [key: string]: WebRDataRaw };\n\nexport type NamedEntries<T> = [string | null, T][];\nexport type NamedObject<T> = { [key: string]: T };\n\n/**\n * A union of JavaScript types that are able to be converted into an R object.\n *\n * `WebRData` is used both as a general input argument for R object construction\n * and also as a general return type when converting R objects into JavaScript.\n *\n */\nexport type WebRData =\n | RMain.RObject\n | RWorker.RObjectBase\n | RWorker.RObject\n | WebRDataRaw\n | WebRDataJs\n | WebRData[]\n | { [key: string]: WebRData };\n\n/**\n * A subset of {@link WebRData} for JavaScript objects that can be converted\n * into R atomic vectors.\n *\n * @typeParam T The JavaScript scalar type associated with the atomic vector.\n */\nexport type WebRDataAtomic<T> =\n | WebRDataScalar<T>\n | (T | null)[]\n | WebRDataJsAtomic<T>\n | NamedObject<T | null>;\n\n/**\n * `WebRDataJs` objects form a tree structure, used when serialising R objects\n * into a JavaScript respresentation.\n *\n * Nested R objects are serialised using the {@link WebRDataJsNode} type,\n * forming branches in the resulting tree structure, with leaves formed by the\n * remaining types.\n */\nexport type WebRDataJs =\n | WebRDataJsNull\n | WebRDataJsString\n | WebRDataJsSymbol\n | WebRDataJsNode\n | WebRDataJsAtomic<RWorker.atomicType>;\n\nexport type WebRDataJsNull = {\n type: 'null';\n};\n\nexport type WebRDataJsString = {\n type: 'string';\n value: string;\n};\n\nexport type WebRDataJsSymbol = {\n type: 'symbol';\n printname: string | null;\n symvalue: RPtr | null;\n internal: RPtr | null;\n};\n\nexport type WebRDataJsNode = {\n type: 'list' | 'pairlist' | 'environment';\n names: (string | null)[] | null;\n values: (WebRDataRaw | RWorker.RObject | RMain.RObject | WebRDataJs)[];\n};\n\nexport type WebRDataJsAtomic<T> = {\n type: 'logical' | 'integer' | 'double' | 'complex' | 'character' | 'raw';\n names: (string | null)[] | null;\n values: (T | null)[];\n};\n\n/**\n * Test for a {@link WebRDataJs} instance.\n *\n * @param {any} value The object to test.\n * @returns {boolean} True if the object is an instance of a {@link WebRDataJs}.\n */\nexport function isWebRDataJs(value: any): value is WebRDataJs {\n return value && typeof value === 'object' && Object.keys(RTypeMap).includes(value.type as string);\n}\n\n/**\n * A subset of WebRData for scalar JavaScript objects.\n */\nexport type WebRDataScalar<T> = T | RMain.RObject | RWorker.RObjectBase;\n\n/**\n * Test if an object is of type {@link Complex}.\n *\n * @param {any} value The object to test.\n * @returns {boolean} True if the object is of type {@link Complex}.\n */\nexport function isComplex(value: any): value is Complex {\n return value && typeof value === 'object' && 're' in value && 'im' in value;\n}\n", "import { Module, DictEmPtrs, dictEmFree } from './emscripten';\nimport { WebRData, RPtr } from './robj';\nimport { RObject, REnvironment, RHandle, handlePtr } from './robj-worker';\n\nexport function protect<T extends RHandle>(x: T): T {\n Module._Rf_protect(handlePtr(x));\n return x;\n}\n\nexport function protectInc<T extends RHandle>(x: T, prot: { n: number }): T {\n Module._Rf_protect(handlePtr(x));\n ++prot.n;\n return x;\n}\n\nexport function protectWithIndex(x: RHandle): { loc: number; ptr: RPtr } {\n // Integer size hardcoded to 4 bytes. This is fine but is there a\n // way to call sizeof?\n const pLoc = Module._malloc(4);\n\n Module._R_ProtectWithIndex(handlePtr(x), pLoc);\n const loc = Module.getValue(pLoc, 'i32');\n\n return { loc: loc, ptr: pLoc };\n}\n\nexport function unprotectIndex(index: { ptr: RPtr }): void {\n Module._Rf_unprotect(1);\n Module._free(index.ptr);\n}\n\nexport function reprotect<T extends RHandle>(x: T, index: { loc: number; ptr: RPtr }): T {\n Module._R_Reprotect(handlePtr(x), index.loc);\n return x;\n}\n\nexport function unprotect(n: number) {\n Module._Rf_unprotect(n);\n}\n\n// rlang convention: `env`-prefixed functions consistently take `env`\n// as first argument\nexport function envPoke(env: RHandle, sym: RHandle, value: RHandle) {\n Module._Rf_defineVar(handlePtr(sym), handlePtr(value), handlePtr(env));\n}\n\nexport function parseEvalBare(code: string, env: WebRData): RObject {\n const strings: DictEmPtrs = {};\n const prot = { n: 0 };\n\n try {\n const envObj = new REnvironment(env);\n protectInc(envObj, prot);\n\n strings.code = Module.allocateUTF8(code);\n\n const out = Module._R_ParseEvalString(strings.code, envObj.ptr);\n return RObject.wrap(out);\n } finally {\n dictEmFree(strings);\n unprotect(prot.n);\n }\n}\n\nexport class UnwindProtectException extends Error {\n cont: RPtr;\n constructor(message: string, cont: RPtr) {\n super(message);\n this.name = 'UnwindProtectException';\n this.cont = cont;\n }\n}\n\nexport function safeEval(call: RHandle, env: RHandle): RPtr {\n return Module.LDSO.loadedLibsByName['/usr/lib/R/library/webr/libs/webr.so'].module.ffi_safe_eval(\n handlePtr(call),\n handlePtr(env)\n );\n}\n", "/**\n * Module for working with R objects on the worker thead.\n * @module RWorker\n */\nimport { Module } from './emscripten';\nimport { Complex, isComplex, NamedEntries, NamedObject, WebRDataRaw, WebRDataScalar } from './robj';\nimport { WebRData, WebRDataAtomic, RPtr, RType, RTypeMap, RTypeNumber } from './robj';\nimport { isWebRDataJs, WebRDataJs, WebRDataJsAtomic, WebRDataJsNode } from './robj';\nimport { WebRDataJsNull, WebRDataJsString, WebRDataJsSymbol } from './robj';\nimport { envPoke, parseEvalBare, protect, protectInc, unprotect } from './utils-r';\nimport { protectWithIndex, reprotect, unprotectIndex, safeEval } from './utils-r';\nimport { ShelterID, isShelterID } from './webr-chan';\n\nexport type RHandle = RObject | RPtr;\n\nexport function handlePtr(x: RHandle): RPtr {\n if (isRObject(x)) {\n return x.ptr;\n } else {\n return x;\n }\n}\n\n// Throw if an R object does not match a certain R type\nfunction assertRType(obj: RObjectBase, type: RType) {\n if (Module._TYPEOF(obj.ptr) !== RTypeMap[type]) {\n throw new Error(`Unexpected object type \"${obj.type()}\" when expecting type \"${type}\"`);\n }\n}\n\n// TODO: Shelter should be a dictionary not an array\nexport const shelters = new Map<ShelterID, RPtr[]>();\n\n// Use this for implicit protection of objects sent to the main\n// thread. Currently uses the precious list but could use a different\n// mechanism in the future. Unprotection is explicit through\n// `Shelter.destroy()`.\nexport function keep(shelter: ShelterID, x: RHandle) {\n const ptr = handlePtr(x);\n Module._R_PreserveObject(ptr);\n\n // TODO: Remove when shelter transition is complete\n if (shelter === undefined) {\n return;\n }\n\n if (isShelterID(shelter)) {\n shelters.get(shelter)!.push(ptr);\n return;\n }\n\n throw new Error('Unexpected shelter type ' + typeof shelter);\n}\n\n// Frees objects preserved with `keep()`. This method is called by\n// users in the main thread to release objects that were automatically\n// protected before being sent away.\nexport function destroy(shelter: ShelterID, x: RHandle) {\n const ptr = handlePtr(x);\n Module._R_ReleaseObject(ptr);\n\n const objs: RPtr[] = shelters.get(shelter)!;\n const loc = objs.indexOf(ptr);\n\n if (loc < 0) {\n throw new Error(\"Can't find object in shelter.\");\n }\n\n objs.splice(loc, 1);\n}\n\nexport function purge(shelter: ShelterID) {\n const ptrs: RPtr[] = shelters.get(shelter)!;\n\n for (const ptr of ptrs) {\n try {\n Module._R_ReleaseObject(ptr);\n } catch (e) {\n console.error(e);\n }\n }\n\n shelters.set(shelter, []);\n}\n\nexport interface ToJsOptions {\n depth: number;\n}\n\nexport type Nullable<T> = T | RNull;\n\nfunction newObjectFromData(obj: WebRData): RObject {\n // Conversion of WebRDataJs type JS objects\n if (isWebRDataJs(obj)) {\n return new (getRWorkerClass(RTypeMap[obj.type]))(obj);\n }\n\n // Conversion of explicit R NULL value\n if (obj && typeof obj === 'object' && 'type' in obj && obj.type === 'null') {\n return new RNull();\n }\n\n // Direct conversion of scalar JS values\n if (obj === null) {\n return new RLogical({ type: 'logical', names: null, values: [null] });\n }\n if (typeof obj === 'boolean') {\n return new RLogical(obj);\n }\n if (typeof obj === 'number') {\n return new RDouble(obj);\n }\n if (typeof obj === 'string') {\n return new RCharacter(obj);\n }\n if (isComplex(obj)) {\n return new RComplex(obj);\n }\n if (Array.isArray(obj)) {\n return newObjectFromArray(obj);\n }\n\n throw new Error('Robj construction for this JS object is not yet supported');\n}\n\n// JS arrays are interpreted using R's c() function, so as to match\n// R's built in coercion rules\nfunction newObjectFromArray(arr: WebRData[]) {\n const prot = { n: 0 };\n\n try {\n const call = new RCall([new RSymbol('c'), ...arr]);\n protectInc(call, prot);\n return call.eval();\n } finally {\n unprotect(prot.n);\n }\n}\n\nexport class RObjectBase {\n ptr: RPtr;\n constructor(ptr: RPtr) {\n this.ptr = ptr;\n }\n\n type(): RType {\n const typeNumber = Module._TYPEOF(this.ptr) as RTypeNumber;\n const type = Object.keys(RTypeMap).find(\n (typeName) => RTypeMap[typeName as RType] === typeNumber\n );\n return type as RType;\n }\n}\n\nexport class RObject extends RObjectBase {\n constructor(data: WebRData) {\n if (!(data instanceof RObjectBase)) {\n return newObjectFromData(data);\n }\n\n super(data.ptr);\n }\n\n static wrap<T extends typeof RObject>(this: T, ptr: RPtr): InstanceType<T> {\n const type = Module._TYPEOF(ptr);\n return new (getRWorkerClass(type as RTypeNumber))(new RObjectBase(ptr)) as InstanceType<T>;\n }\n\n get [Symbol.toStringTag](): string {\n return `RObject:${this.type()}`;\n }\n\n /** @internal */\n static getPersistentObject(prop: keyof typeof objs): unknown {\n return objs[prop];\n }\n\n /** @internal */\n getPropertyValue(prop: keyof this): unknown {\n return this[prop];\n }\n\n inspect(): void {\n parseEvalBare('.Internal(inspect(x))', { x: this });\n }\n\n isNull(): this is RNull {\n return Module._TYPEOF(this.ptr) === RTypeMap.null;\n }\n\n isUnbound(): boolean {\n return this.ptr === objs.unboundValue.ptr;\n }\n\n attrs(): Nullable<RPairlist> {\n return RPairlist.wrap(Module._ATTRIB(this.ptr));\n }\n\n setNames(values: (string | null)[] | null): this {\n let namesObj: RObject;\n\n if (values === null) {\n namesObj = objs.null;\n } else if (Array.isArray(values) && values.every((v) => typeof v === 'string' || v === null)) {\n namesObj = new RCharacter(values);\n } else {\n throw new Error('Argument to setNames must be null or an Array of strings or null');\n }\n\n // `setAttrib()` protects its inputs\n Module._Rf_setAttrib(this.ptr, objs.namesSymbol.ptr, namesObj.ptr);\n return this;\n }\n\n names(): (string | null)[] | null {\n const names = RCharacter.wrap(Module._Rf_getAttrib(this.ptr, objs.namesSymbol.ptr));\n if (names.isNull()) {\n return null;\n } else {\n return names.toArray();\n }\n }\n\n includes(name: string) {\n const names = this.names();\n return names && names.includes(name);\n }\n\n toJs(options: ToJsOptions = { depth: 0 }, depth = 1): WebRDataJs {\n throw new Error('This R object cannot be converted to JS');\n }\n\n subset(prop: number | string): RObject {\n return this.#slice(prop, objs.bracketSymbol.ptr);\n }\n\n get(prop: number | string): RObject {\n return this.#slice(prop, objs.bracket2Symbol.ptr);\n }\n\n getDollar(prop: string): RObject {\n return this.#slice(prop, objs.dollarSymbol.ptr);\n }\n\n #slice(prop: number | string, op: RPtr): RObject {\n const prot = { n: 0 };\n\n try {\n const idx = new RObject(prop);\n protectInc(idx, prot);\n\n const call = Module._Rf_lang3(op, this.ptr, idx.ptr);\n protectInc(call, prot);\n\n return RObject.wrap(safeEval(call, objs.baseEnv));\n } finally {\n unprotect(prot.n);\n }\n }\n\n pluck(...path: (string | number)[]): RObject | undefined {\n const index = protectWithIndex(objs.null);\n\n try {\n const getter = (obj: RObject, prop: string | number): RObject => {\n const out = obj.get(prop);\n return reprotect(out, index);\n };\n const result = path.reduce(getter, this);\n\n return result.isNull() ? undefined : result;\n } finally {\n unprotectIndex(index);\n }\n }\n\n set(prop: string | number, value: RObject | WebRDataRaw): RObject {\n const prot = { n: 0 };\n\n try {\n const idx = new RObject(prop);\n protectInc(idx, prot);\n\n const valueObj = new RObject(value);\n protectInc(valueObj, prot);\n\n const assign = new RSymbol('[[<-');\n const call = Module._Rf_lang4(assign.ptr, this.ptr, idx.ptr, valueObj.ptr);\n protectInc(call, prot);\n\n return RObject.wrap(safeEval(call, objs.baseEnv));\n } finally {\n unprotect(prot.n);\n }\n }\n\n /** @internal */\n static getMethods(obj: RObject) {\n const props = new Set<string>();\n let cur: unknown = obj;\n do {\n Object.getOwnPropertyNames(cur).map((p) => props.add(p));\n } while ((cur = Object.getPrototypeOf(cur)));\n return [...props.keys()].filter((i) => typeof obj[i as keyof typeof obj] === 'function');\n }\n}\n\nexport class RNull extends RObject {\n constructor() {\n super(new RObjectBase(Module.getValue(Module._R_NilValue, '*')));\n return this;\n }\n\n toJs(): WebRDataJsNull {\n return { type: 'null' };\n }\n}\n\nexport class RSymbol extends RObject {\n // Note that symbols don't need to be protected. This also means\n // that allocating symbols in loops with random data is probably a\n // bad idea because this leaks memory.\n constructor(x: WebRDataScalar<string>) {\n if (x instanceof RObjectBase) {\n assertRType(x, 'symbol');\n super(x);\n return;\n }\n const name = Module.allocateUTF8(x as string);\n try {\n super(new RObjectBase(Module._Rf_install(name)));\n } finally {\n Module._free(name);\n }\n }\n\n toJs(): WebRDataJsSymbol {\n const obj = this.toObject();\n return {\n type: 'symbol',\n printname: obj.printname,\n symvalue: obj.symvalue,\n internal: obj.internal,\n };\n }\n\n toObject(): {\n printname: string | null;\n symvalue: RPtr | null;\n internal: RPtr | null;\n } {\n return {\n printname: this.printname().isUnbound() ? null : this.printname().toString(),\n symvalue: this.symvalue().isUnbound() ? null : this.symvalue().ptr,\n internal: this.internal().isNull() ? null : this.internal().ptr,\n };\n }\n\n toString(): string {\n return this.printname().toString();\n }\n\n printname(): RString {\n return RString.wrap(Module._PRINTNAME(this.ptr));\n }\n symvalue(): RObject {\n return RObject.wrap(Module._SYMVALUE(this.ptr));\n }\n internal(): RObject {\n return RObject.wrap(Module._INTERNAL(this.ptr));\n }\n}\n\nexport class RPairlist extends RObject {\n constructor(val: WebRData) {\n if (val instanceof RObjectBase) {\n assertRType(val, 'pairlist');\n super(val);\n return this;\n }\n\n const prot = { n: 0 };\n\n try {\n const { names, values } = toWebRData(val);\n\n const list = RPairlist.wrap(Module._Rf_allocList(values.length));\n protectInc(list, prot);\n\n for (\n let [i, next] = [0, list as Nullable<RPairlist>];\n !next.isNull();\n [i, next] = [i + 1, next.cdr()]\n ) {\n next.setcar(new RObject(values[i]));\n }\n\n list.setNames(names);\n super(list);\n } finally {\n unprotect(prot.n);\n }\n }\n\n get length(): number {\n return this.toArray().length;\n }\n\n toArray(options: ToJsOptions = { depth: 1 }): WebRData[] {\n return this.toJs(options).values;\n }\n\n toObject({\n allowDuplicateKey = true,\n allowEmptyKey = false,\n depth = 1,\n } = {}): NamedObject<WebRData> {\n const entries = this.entries({ depth });\n const keys = entries.map(([k, v]) => k);\n if (!allowDuplicateKey && new Set(keys).size !== keys.length) {\n throw new Error('Duplicate key when converting pairlist without allowDuplicateKey enabled');\n }\n if (!allowEmptyKey && keys.some((k) => !k)) {\n throw new Error('Empty or null key when converting pairlist without allowEmptyKey enabled');\n }\n return Object.fromEntries(\n entries.filter((u, idx) => entries.findIndex((v) => v[0] === u[0]) === idx)\n );\n }\n\n entries(options: ToJsOptions = { depth: 1 }): NamedEntries<WebRData> {\n const obj = this.toJs(options);\n return obj.values.map((v, i) => [obj.names ? obj.names[i] : null, v]);\n }\n\n toJs(options: ToJsOptions = { depth: 0 }, depth = 1): WebRDataJsNode {\n const namesArray: string[] = [];\n let hasNames = false;\n const values: WebRDataJsNode['values'] = [];\n\n for (let next = this as Nullable<RPairlist>; !next.isNull(); next = next.cdr()) {\n const symbol = next.tag();\n if (symbol.isNull()) {\n namesArray.push('');\n } else {\n hasNames = true;\n namesArray.push(symbol.toString());\n }\n if (options.depth && depth >= options.depth) {\n values.push(next.car());\n } else {\n values.push(next.car().toJs(options, depth + 1));\n }\n }\n const names = hasNames ? namesArray : null;\n return { type: 'pairlist', names, values };\n }\n\n includes(name: string): boolean {\n return name in this.toObject();\n }\n\n setcar(obj: RObject): void {\n Module._SETCAR(this.ptr, obj.ptr);\n }\n\n car(): RObject {\n return RObject.wrap(Module._CAR(this.ptr));\n }\n\n cdr(): Nullable<RPairlist> {\n return RObject.wrap(Module._CDR(this.ptr)) as Nullable<RPairlist>;\n }\n\n tag(): Nullable<RSymbol> {\n return RObject.wrap(Module._TAG(this.ptr)) as Nullable<RSymbol>;\n }\n}\n\nexport class RCall extends RObject {\n constructor(val: WebRData) {\n if (val instanceof RObjectBase) {\n assertRType(val, 'call');\n super(val);\n return this;\n }\n const prot = { n: 0 };\n\n try {\n const { values } = toWebRData(val);\n const objs = values.map((value) => protectInc(new RObject(value), prot));\n const call = RCall.wrap(Module._Rf_allocVector(RTypeMap.call, values.length));\n protectInc(call, prot);\n\n for (\n let [i, next] = [0, call as Nullable<RPairlist>];\n !next.isNull();\n [i, next] = [i + 1, next.cdr()]\n ) {\n next.setcar(objs[i]);\n }\n super(call);\n } finally {\n unprotect(prot.n);\n }\n }\n\n setcar(obj: RObject): void {\n Module._SETCAR(this.ptr, obj.ptr);\n }\n\n car(): RObject {\n return RObject.wrap(Module._CAR(this.ptr));\n }\n\n cdr(): Nullable<RPairlist> {\n return RObject.wrap(Module._CDR(this.ptr)) as Nullable<RPairlist>;\n }\n\n eval(): RObject {\n return RObject.wrap(safeEval(this.ptr, objs.baseEnv));\n }\n}\n\nexport class RList extends RObject {\n constructor(val: WebRData) {\n if (val instanceof RObjectBase) {\n assertRType(val, 'list');\n super(val);\n return this;\n }\n\n const prot = { n: 0 };\n\n try {\n const { names, values } = toWebRData(val);\n const ptr = Module._Rf_allocVector(RTypeMap.list, values.length);\n protectInc(ptr, prot);\n\n values.forEach((v, i) => {\n Module._SET_VECTOR_ELT(ptr, i, new RObject(v).ptr);\n });\n\n RObject.wrap(ptr).setNames(names);\n\n super(new RObjectBase(ptr));\n } finally {\n unprotect(prot.n);\n }\n }\n\n get length(): number {\n return Module._LENGTH(this.ptr);\n }\n\n toArray(options: { depth: number } = { depth: 1 }): WebRData[] {\n return this.toJs(options).values;\n }\n\n toObject({\n allowDuplicateKey = true,\n allowEmptyKey = false,\n depth = 1,\n } = {}): NamedObject<WebRData> {\n const entries = this.entries({ depth });\n const keys = entries.map(([k, v]) => k);\n if (!allowDuplicateKey && new Set(keys).size !== keys.length) {\n throw new Error('Duplicate key when converting list without allowDuplicateKey enabled');\n }\n if (!allowEmptyKey && keys.some((k) => !k)) {\n throw new Error('Empty or null key when converting list without allowEmptyKey enabled');\n }\n return Object.fromEntries(\n entries.filter((u, idx) => entries.findIndex((v) => v[0] === u[0]) === idx)\n );\n }\n\n entries(options: { depth: number } = { depth: 1 }): NamedEntries<WebRData> {\n const obj = this.toJs(options);\n return obj.values.map((v, i) => [obj.names ? obj.names[i] : null, v]);\n }\n\n toJs(options: { depth: number } = { depth: 0 }, depth = 1): WebRDataJsNode {\n return {\n type: 'list',\n names: this.names(),\n values: [...Array(this.length).keys()].map((i) => {\n if (options.depth && depth >= options.depth) {\n return this.get(i + 1);\n } else {\n return this.get(i + 1).toJs(options, depth + 1);\n }\n }),\n };\n }\n}\n\nexport class RFunction extends RObject {\n exec(...args: (WebRDataRaw | RObject)[]): RObject {\n const prot = { n: 0 };\n\n try {\n const call = new RCall([this, ...args]);\n protectInc(call, prot);\n return call.eval();\n } finally {\n unprotect(prot.n);\n }\n }\n}\n\nexport class RString extends RObject {\n // Unlike symbols, strings are not cached and must thus be protected\n constructor(x: WebRDataScalar<string>) {\n if (x instanceof RObjectBase) {\n assertRType(x, 'string');\n super(x);\n return;\n }\n\n const name = Module.allocateUTF8(x as string);\n\n try {\n super(new RObjectBase(Module._Rf_mkChar(name)));\n } finally {\n Module._free(name);\n }\n }\n\n toString(): string {\n return Module.UTF8ToString(Module._R_CHAR(this.ptr));\n }\n\n toJs(): WebRDataJsString {\n return {\n type: 'string',\n value: this.toString(),\n };\n }\n}\n\nexport class REnvironment extends RObject {\n constructor(val: WebRData = {}) {\n if (val instanceof RObjectBase) {\n assertRType(val, 'environment');\n super(val);\n return this;\n }\n let nProt = 0;\n\n try {\n const { names, values } = toWebRData(val);\n\n const ptr = protect(Module._R_NewEnv(objs.globalEnv.ptr, 0, 0));\n ++nProt;\n\n values.forEach((v, i) => {\n const name = names ? names[i] : null;\n if (!name) {\n throw new Error(\"Can't create object in new environment with empty symbol name\");\n }\n\n const sym = new RSymbol(name);\n const vObj = protect(new RObject(v));\n try {\n envPoke(ptr, sym, vObj);\n } finally {\n unprotect(1);\n }\n });\n\n super(new RObjectBase(ptr));\n } finally {\n unprotect(nProt);\n }\n }\n\n ls(all = false, sorted = true): string[] {\n const ls = RCharacter.wrap(Module._R_lsInternal3(this.ptr, Number(all), Number(sorted)));\n return ls.toArray() as string[];\n }\n\n bind(name: string, value: WebRData): void {\n const sym = new RSymbol(name);\n const valueObj = protect(new RObject(value));\n\n try {\n envPoke(this, sym, valueObj);\n } finally {\n unprotect(1);\n }\n }\n\n names(): string[] {\n return this.ls(true, true);\n }\n\n frame(): RObject {\n return RObject.wrap(Module._FRAME(this.ptr));\n }\n\n subset(prop: number | string): RObject {\n if (typeof prop === 'number') {\n throw new Error('Object of type environment is not subsettable');\n }\n return this.getDollar(prop);\n }\n\n toObject({ depth = 0 } = {}): NamedObject<WebRData> {\n const symbols = this.names();\n return Object.fromEntries(\n [...Array(symbols.length).keys()].map((i) => {\n return [symbols[i], this.getDollar(symbols[i]).toJs({ depth })];\n })\n );\n }\n\n toJs(options: { depth: number } = { depth: 0 }, depth = 1): WebRDataJsNode {\n const names = this.names();\n const values = [...Array(names.length).keys()].map((i) => {\n if (options.depth && depth >= options.depth) {\n return this.getDollar(names[i]);\n } else {\n return this.getDollar(names[i]).toJs(options, depth + 1);\n }\n });\n\n return {\n type: 'environment',\n names,\n values,\n };\n }\n}\n\ntype TypedArray =\n | Int8Array\n | Uint8Array\n | Int16Array\n | Uint16Array\n | Int32Array\n | Uint32Array\n | Float32Array\n | Float64Array;\n\nexport type atomicType = number | boolean | Complex | string;\n\nabstract class RVectorAtomic<T extends atomicType> extends RObject {\n constructor(\n val: WebRDataAtomic<T>,\n kind: RType,\n newSetter: (ptr: RPtr) => (v: any, i: number) => void\n ) {\n if (val instanceof RObjectBase) {\n assertRType(val, kind);\n super(val);\n return this;\n }\n\n const prot = { n: 0 };\n\n try {\n const { names, values } = toWebRData(val);\n\n const ptr = Module._Rf_allocVector(RTypeMap[kind], values.length);\n protectInc(ptr, prot);\n\n values.forEach(newSetter(ptr));\n RObject.wrap(ptr).setNames(names);\n\n super(new RObjectBase(ptr));\n } finally {\n unprotect(prot.n);\n }\n }\n\n get length(): number {\n return Module._LENGTH(this.ptr);\n }\n\n get(prop: number | string): this {\n return super.get(prop) as this;\n }\n\n subset(prop: number | string): this {\n return super.subset(prop) as this;\n }\n\n getDollar(prop: string): RObject {\n throw new Error('$ operator is invalid for atomic vectors');\n }\n\n detectMissing(): boolean[] {\n const prot = { n: 0 };\n\n try {\n const call = Module._Rf_lang2(new RSymbol('is.na').ptr, this.ptr);\n protectInc(call, prot);\n\n const val = RLogical.wrap(safeEval(call, objs.baseEnv));\n protectInc(val, prot);\n\n const ret = val.toTypedArray();\n return Array.from(ret).map((elt) => Boolean(elt));\n } finally {\n unprotect(prot.n);\n }\n }\n\n abstract toTypedArray(): TypedArray;\n\n toArray(): (T | null)[] {\n const arr = this.toTypedArray();\n return this.detectMissing().map((m, idx) => (m ? null : (arr[idx] as T)));\n }\n\n toObject({ allowDuplicateKey = true, allowEmptyKey = false } = {}): NamedObject<T | null> {\n const entries = this.entries();\n const keys = entries.map(([k, v]) => k);\n if (!allowDuplicateKey && new Set(keys).size !== keys.length) {\n throw new Error(\n 'Duplicate key when converting atomic vector without allowDuplicateKey enabled'\n );\n }\n if (!allowEmptyKey && keys.some((k) => !k)) {\n throw new Error(\n 'Empty or null key when converting atomic vector without allowEmptyKey enabled'\n );\n }\n return Object.fromEntries(\n entries.filter((u, idx) => entries.findIndex((v) => v[0] === u[0]) === idx)\n );\n }\n\n entries(): NamedEntries<T | null> {\n const values = this.toArray();\n const names = this.names();\n return values.map((v, i) => [names ? names[i] : null, v]);\n }\n\n toJs(): WebRDataJsAtomic<T> {\n return {\n type: this.type() as 'logical' | 'integer' | 'double' | 'complex' | 'character' | 'raw',\n names: this.names(),\n values: this.toArray(),\n };\n }\n}\n\nexport class RLogical extends RVectorAtomic<boolean> {\n constructor(val: WebRDataAtomic<boolean>) {\n super(val, 'logical', RLogical.#newSetter);\n }\n\n static #newSetter = (ptr: RPtr) => {\n const data = Module._LOGICAL(ptr);\n const naLogical = Module.getValue(Module._R_NaInt, 'i32');\n return (v: null | boolean, i: number) => {\n Module.setValue(data + 4 * i, v === null ? naLogical : Boolean(v), 'i32');\n };\n };\n\n getBoolean(idx: number): boolean | null {\n return this.get(idx).toArray()[0];\n }\n\n toBoolean(): boolean {\n if (this.length !== 1) {\n throw new Error(\"Can't convert atomic vector of length > 1 to a scalar JS value\");\n }\n const val = this.getBoolean(1);\n if (val === null) {\n throw new Error(\"Can't convert missing value `NA` to a JS boolean\");\n }\n return val;\n }\n\n toTypedArray(): Int32Array {\n return new Int32Array(\n Module.HEAP32.subarray(\n Module._LOGICAL(this.ptr) / 4,\n Module._LOGICAL(this.ptr) / 4 + this.length\n )\n );\n }\n\n toArray(): (boolean | null)[] {\n const arr = this.toTypedArray();\n return this.detectMissing().map((m, idx) => (m ? null : Boolean(arr[idx])));\n }\n}\n\nexport class RInteger extends RVectorAtomic<number> {\n constructor(val: WebRDataAtomic<number>) {\n super(val, 'integer', RInteger.#newSetter);\n }\n\n static #newSetter = (ptr: RPtr) => {\n const data = Module._INTEGER(ptr);\n const naInteger = Module.getValue(Module._R_NaInt, 'i32');\n\n return (v: null | number, i: number) => {\n Module.setValue(data + 4 * i, v === null ? naInteger : Math.round(Number(v)), 'i32');\n };\n };\n\n getNumber(idx: number): number | null {\n return this.get(idx).toArray()[0];\n }\n\n toNumber(): number {\n if (this.length !== 1) {\n throw new Error(\"Can't convert atomic vector of length > 1 to a scalar JS value\");\n }\n const val = this.getNumber(1);\n if (val === null) {\n throw new Error(\"Can't convert missing value `NA` to a JS number\");\n }\n return val;\n }\n\n toTypedArray(): Int32Array {\n return new Int32Array(\n Module.HEAP32.subarray(\n Module._INTEGER(this.ptr) / 4,\n Module._INTEGER(this.ptr) / 4 + this.length\n )\n );\n }\n}\n\nexport class RDouble extends RVectorAtomic<number> {\n constructor(val: WebRDataAtomic<number>) {\n super(val, 'double', RDouble.#newSetter);\n }\n\n static #newSetter = (ptr: RPtr) => {\n const data = Module._REAL(ptr);\n const naDouble = Module.getValue(Module._R_NaReal, 'double');\n\n return (v: null | number, i: number) => {\n Module.setValue(data + 8 * i, v === null ? naDouble : v, 'double');\n };\n };\n\n getNumber(idx: number): number | null {\n return this.get(idx).toArray()[0];\n }\n\n toNumber(): number {\n if (this.length !== 1) {\n throw new Error(\"Can't convert atomic vector of length > 1 to a scalar JS value\");\n }\n const val = this.getNumber(1);\n if (val === null) {\n throw new Error(\"Can't convert missing value `NA` to a JS number\");\n }\n return val;\n }\n\n toTypedArray(): Float64Array {\n return new Float64Array(\n Module.HEAPF64.subarray(Module._REAL(this.ptr) / 8, Module._REAL(this.ptr) / 8 + this.length)\n );\n }\n}\n\nexport class RComplex extends RVectorAtomic<Complex> {\n constructor(val: WebRDataAtomic<Complex>) {\n super(val, 'complex', RComplex.#newSetter);\n }\n\n static #newSetter = (ptr: RPtr) => {\n const data = Module._COMPLEX(ptr);\n const naDouble = Module.getValue(Module._R_NaReal, 'double');\n\n return (v: null | Complex, i: number) => {\n Module.setValue(data + 8 * (2 * i), v === null ? naDouble : v.re, 'double');\n Module.setValue(data + 8 * (2 * i + 1), v === null ? naDouble : v.im, 'double');\n };\n };\n\n getComplex(idx: number): Complex | null {\n return this.get(idx).toArray()[0];\n }\n\n toComplex(): Complex {\n if (this.length !== 1) {\n throw new Error(\"Can't convert atomic vector of length > 1 to a scalar JS value\");\n }\n const val = this.getComplex(1);\n if (val === null) {\n throw new Error(\"Can't convert missing value `NA` to a JS object\");\n }\n return val;\n }\n\n toTypedArray(): Float64Array {\n return new Float64Array(\n Module.HEAPF64.subarray(\n Module._COMPLEX(this.ptr) / 8,\n Module._COMPLEX(this.ptr) / 8 + 2 * this.length\n )\n );\n }\n\n toArray(): (Complex | null)[] {\n const arr = this.toTypedArray();\n return this.detectMissing().map((m, idx) =>\n m ? null : { re: arr[2 * idx], im: arr[2 * idx + 1] }\n );\n }\n}\n\nexport class RCharacter extends RVectorAtomic<string> {\n constructor(val: WebRDataAtomic<string>) {\n super(val, 'character', RCharacter.#newSetter);\n }\n\n static #newSetter = (ptr: RPtr) => {\n return (v: null | string, i: number) => {\n if (v === null) {\n Module._SET_STRING_ELT(ptr, i, objs.naString.ptr);\n } else {\n Module._SET_STRING_ELT(ptr, i, new RString(v).ptr);\n }\n };\n };\n\n getString(idx: number): string | null {\n return this.get(idx).toArray()[0];\n }\n\n toString(): string {\n if (this.length !== 1) {\n throw new Error(\"Can't convert atomic vector of length > 1 to a scalar JS value\");\n }\n const val = this.getString(1);\n if (val === null) {\n throw new Error(\"Can't convert missing value `NA` to a JS string\");\n }\n return val;\n }\n\n toTypedArray(): Uint32Array {\n return new Uint32Array(\n Module.HEAPU32.subarray(\n Module._STRING_PTR(this.ptr) / 4,\n Module._STRING_PTR(this.ptr) / 4 + this.length\n )\n );\n }\n\n toArray(): (string | null)[] {\n return this.detectMissing().map((m, idx) =>\n m ? null : Module.UTF8ToString(Module._R_CHAR(Module._STRING_ELT(this.ptr, idx)))\n );\n }\n}\n\nexport class RRaw extends RVectorAtomic<number> {\n constructor(val: WebRDataAtomic<number>) {\n super(val, 'raw', RRaw.#newSetter);\n }\n\n static #newSetter = (ptr: RPtr) => {\n const data = Module._RAW(ptr);\n\n return (v: number, i: number) => {\n Module.setValue(data + i, Number(v), 'i8');\n };\n };\n\n getNumber(idx: number): number | null {\n return this.get(idx).toArray()[0];\n }\n\n toNumber(): number {\n if (this.length !== 1) {\n throw new Error(\"Can't convert atomic vector of length > 1 to a scalar JS value\");\n }\n const val = this.getNumber(1);\n if (val === null) {\n throw new Error(\"Can't convert missing value `NA` to a JS number\");\n }\n return val;\n }\n\n toTypedArray(): Uint8Array {\n return new Uint8Array(\n Module.HEAPU8.subarray(Module._RAW(this.ptr), Module._RAW(this.ptr) + this.length)\n );\n }\n}\n\n/*\n * Convert the various types possible in the type union WebRData into\n * consistently typed arrays of names and values.\n */\nfunction toWebRData<T>(jsObj: WebRDataAtomic<T>): {\n names: (string | null)[] | null;\n values: (T | null)[];\n};\nfunction toWebRData(jsObj: WebRData): WebRData;\nfunction toWebRData(jsObj: WebRData): WebRData {\n if (isWebRDataJs(jsObj)) {\n return jsObj;\n } else if (Array.isArray(jsObj)) {\n return { names: null, values: jsObj };\n } else if (jsObj && typeof jsObj === 'object' && !isComplex(jsObj)) {\n return {\n names: Object.keys(jsObj),\n values: Object.values(jsObj),\n };\n }\n return { names: null, values: [jsObj] };\n}\n\nexport function getRWorkerClass(type: RTypeNumber): typeof RObject {\n const typeClasses: { [key: number]: typeof RObject } = {\n [RTypeMap.null]: RNull,\n [RTypeMap.symbol]: RSymbol,\n [RTypeMap.pairlist]: RPairlist,\n [RTypeMap.closure]: RFunction,\n [RTypeMap.environment]: REnvironment,\n [RTypeMap.call]: RCall,\n [RTypeMap.special]: RFunction,\n [RTypeMap.builtin]: RFunction,\n [RTypeMap.string]: RString,\n [RTypeMap.logical]: RLogical,\n [RTypeMap.integer]: RInteger,\n [RTypeMap.double]: RDouble,\n [RTypeMap.complex]: RComplex,\n [RTypeMap.character]: RCharacter,\n [RTypeMap.list]: RList,\n [RTypeMap.raw]: RRaw,\n [RTypeMap.function]: RFunction,\n };\n if (type in typeClasses) {\n return typeClasses[type];\n }\n return RObject;\n}\n\n/**\n * Test for an RWorker.RObject instance.\n *\n * RWorker.RObject is the internal interface to R objects, intended to be used\n * on the worker thread.\n *\n * @private\n * @param {any} value The object to test.\n * @return {boolean} True if the object is an instance of an RObject.\n */\nexport function isRObject(value: any): value is RObject {\n return value instanceof RObject;\n}\n\n/**\n * A store for persistent R objects, initialised at R startup.\n */\nexport let objs: {\n baseEnv: REnvironment,\n bracket2Symbol: RSymbol,\n bracketSymbol: RSymbol,\n dollarSymbol: RSymbol,\n emptyEnv: REnvironment,\n false: RLogical,\n globalEnv: REnvironment,\n na: RLogical,\n namesSymbol: RSymbol,\n naString: RObject,\n null: RNull,\n true: RLogical,\n unboundValue: RObject,\n};\n\n/**\n * Populate the persistent R object store.\n * @internal\n */\nexport function initPersistentObjects(){\n objs = {\n baseEnv: REnvironment.wrap(Module.getValue(Module._R_BaseEnv, '*')),\n bracket2Symbol: RSymbol.wrap(Module.getValue(Module._R_Bracket2Symbol, '*')),\n bracketSymbol: RSymbol.wrap(Module.getValue(Module._R_BracketSymbol, '*')),\n dollarSymbol: RSymbol.wrap(Module.getValue(Module._R_DollarSymbol, '*')),\n emptyEnv: REnvironment.wrap(Module.getValue(Module._R_EmptyEnv, '*')),\n false: RLogical.wrap(Module.getValue(Module._R_FalseValue, '*')),\n globalEnv: REnvironment.wrap(Module.getValue(Module._R_GlobalEnv, '*')),\n na: RLogical.wrap(Module.getValue(Module._R_LogicalNAValue, '*')),\n namesSymbol: RSymbol.wrap(Module.getValue(Module._R_NamesSymbol, '*')),\n naString: RObject.wrap(Module.getValue(Module._R_NaString, '*')),\n null: RNull.wrap(Module.getValue(Module._R_NilValue, '*')),\n true: RLogical.wrap(Module.getValue(Module._R_TrueValue, '*')),\n unboundValue: RObject.wrap(Module.getValue(Module._R_UnboundValue, '*')),\n };\n}\n", "import { loadScript } from './compat';\nimport { ChannelWorker } from './chan/channel';\nimport { newChannelWorker, ChannelInitMessage } from './chan/channel-common';\nimport { Message, Request, newResponse } from './chan/message';\nimport { FSNode, WebROptions } from './webr-main';\nimport { Module } from './emscripten';\nimport { IN_NODE } from './compat';\nimport { replaceInObject, throwUnreachable } from './utils';\nimport { WebRPayloadRaw, WebRPayloadPtr, WebRPayloadWorker, isWebRPayloadPtr } from './payload';\nimport { RObject, isRObject, REnvironment, RList, getRWorkerClass } from './robj-worker';\nimport { RCharacter, RString, keep, destroy, purge, shelters } from './robj-worker';\nimport { RLogical, RInteger, RDouble, initPersistentObjects, objs } from './robj-worker';\nimport { RPtr, RType, RTypeMap, WebRData, WebRDataRaw } from './robj';\nimport { protect, protectInc, unprotect, parseEvalBare, UnwindProtectException, safeEval } from './utils-r';\nimport { generateUUID } from './chan/task-common';\n\nimport {\n CallRObjectMethodMessage,\n CaptureRMessage,\n EvalROptions,\n EvalRMessage,\n EvalRMessageRaw,\n FSMessage,\n FSReadFileMessage,\n FSWriteFileMessage,\n NewRObjectMessage,\n ShelterMessage,\n ShelterDestroyMessage,\n} from './webr-chan';\n\nlet initialised = false;\nlet chan: ChannelWorker | undefined;\n\nconst onWorkerMessage = function (msg: Message) {\n if (!msg || !msg.type || msg.type !== 'init') {\n return;\n }\n if (initialised) {\n throw new Error(\"Can't initialise worker multiple times.\");\n }\n const messageInit = msg as ChannelInitMessage;\n chan = newChannelWorker(messageInit);\n init(messageInit.data.config);\n initialised = true;\n};\n\nif (IN_NODE) {\n require('worker_threads').parentPort.on('message', onWorkerMessage);\n (globalThis as any).XMLHttpRequest = require('xmlhttprequest-ssl')\n .XMLHttpRequest as XMLHttpRequest;\n} else {\n globalThis.onmessage = (ev: MessageEvent<Message>) => onWorkerMessage(ev.data);\n}\n\ntype XHRResponse = {\n status: number;\n response: string | ArrayBuffer;\n};\n\nlet _config: Required<WebROptions>;\n\nfunction dispatch(msg: Message): void {\n switch (msg.type) {\n case 'request': {\n const req = msg as Request;\n const reqMsg = req.data.msg;\n\n const write = (resp: WebRPayloadWorker, transferables?: [Transferable]) =>\n chan?.write(newResponse(req.data.uuid, resp, transferables));\n try {\n switch (reqMsg.type) {\n case 'lookupPath': {\n const msg = reqMsg as FSMessage;\n const node = Module.FS.lookupPath(msg.data.path, {}).node;\n write({\n obj: copyFSNode(node as FSNode),\n payloadType: 'raw',\n });\n break;\n }\n case 'mkdir': {\n const msg = reqMsg as FSMessage;\n write({\n obj: copyFSNode(Module.FS.mkdir(msg.data.path) as FSNode),\n payloadType: 'raw',\n });\n break;\n }\n case 'readFile': {\n const msg = reqMsg as FSReadFileMessage;\n const reqData = msg.data;\n const out = {\n obj: Module.FS.readFile(reqData.path, {\n encoding: 'binary',\n flags: reqData.flags,\n }),\n payloadType: 'raw',\n };\n write(out as WebRPayloadRaw, [out.obj.buffer]);\n break;\n }\n case 'rmdir': {\n const msg = reqMsg as FSMessage;\n write({\n obj: Module.FS.rmdir(msg.data.path),\n payloadType: 'raw',\n });\n break;\n }\n case 'writeFile': {\n const msg = reqMsg as FSWriteFileMessage;\n const reqData = msg.data;\n // FIXME: Use a replacer + reviver to transfer Uint8Array\n const data = Uint8Array.from(Object.values(reqData.data));\n write({\n obj: Module.FS.writeFile(reqData.path, data, { flags: reqData.flags }),\n payloadType: 'raw',\n });\n break;\n }\n case 'unlink': {\n const msg = reqMsg as FSMessage;\n write({\n obj: Module.FS.unlink(msg.data.path),\n payloadType: 'raw',\n });\n break;\n }\n\n case 'newShelter': {\n const id = generateUUID();\n shelters.set(id, []);\n\n write({\n payloadType: 'raw',\n obj: id,\n });\n break;\n }\n\n case 'shelterSize': {\n const msg = reqMsg as ShelterMessage;\n const size = shelters.get(msg.data)!.length;\n\n write({ payloadType: 'raw', obj: size });\n break;\n }\n\n case 'shelterPurge': {\n const msg = reqMsg as ShelterMessage;\n purge(msg.data);\n\n write({ payloadType: 'raw', obj: null });\n break;\n }\n\n case 'shelterDestroy': {\n const msg = reqMsg as ShelterDestroyMessage;\n destroy(msg.data.id, msg.data.obj.obj.ptr);\n\n write({ payloadType: 'raw', obj: null });\n break;\n }\n\n case 'captureR': {\n const msg = reqMsg as CaptureRMessage;\n const data = msg.data;\n\n const shelter = data.shelter;\n const prot = { n: 0 };\n\n try {\n const capture = captureR(data.code, data.options);\n protectInc(capture, prot);\n\n const result = capture.get('result');\n const outputs = capture.get(2) as RList;\n\n keep(shelter, result);\n\n const n = outputs.length;\n const output: any[] = [];\n\n for (let i = 1; i < n + 1; ++i) {\n const out = outputs.get(i);\n const type = (out.pluck(1, 1) as RCharacter).toString();\n const data = out.get(2);\n\n if (type === 'stdout' || type === 'stderr') {\n const msg = (data as RString).toString();\n output.push({ type, data: msg });\n } else {\n keep(shelter, data);\n const payload = {\n obj: {\n ptr: data.ptr,\n type: data.type(),\n methods: RObject.getMethods(data),\n },\n payloadType: 'ptr',\n } as WebRPayloadPtr;\n output.push({ type, data: payload });\n }\n }\n\n const resultPayload = {\n payloadType: 'ptr',\n obj: {\n ptr: result.ptr,\n type: result.type(),\n methods: RObject.getMethods(result),\n },\n } as WebRPayloadPtr;\n\n write({\n payloadType: 'raw',\n obj: {\n result: resultPayload,\n output: output,\n },\n });\n } finally {\n unprotect(prot.n);\n }\n break;\n }\n\n case 'evalR': {\n const msg = reqMsg as EvalRMessage;\n\n const result = evalR(msg.data.code, msg.data.options);\n keep(msg.data.shelter, result);\n\n write({\n obj: {\n type: result.type(),\n ptr: result.ptr,\n methods: RObject.getMethods(result),\n },\n payloadType: 'ptr',\n });\n break;\n }\n\n case 'evalRRaw': {\n const msg = reqMsg as EvalRMessageRaw;\n const result = evalR(msg.data.code, msg.data.options);\n\n protect(result);\n\n const throwType = () => {\n throw new Error(`Can't convert object of type ${result.type()} to ${msg.data.outputType}.`);\n };\n\n try {\n let out: WebRDataRaw = undefined;\n switch (msg.data.outputType) {\n case 'void':\n break;\n case 'boolean':\n switch (result.type()) {\n case 'logical':\n out = (result as RLogical).toBoolean();\n break;\n default:\n throwType();\n }\n break;\n case 'boolean[]':\n switch (result.type()) {\n case 'logical':\n out = (result as RLogical).toArray();\n if (out.some((i) => i === null)) {\n throwType();\n }\n break;\n default:\n throwType();\n }\n break;\n case 'number':\n switch (result.type()) {\n case 'logical':\n out = (result as RLogical).toBoolean();\n out = Number(out);\n break;\n case 'integer':\n out = (result as RInteger).toNumber();\n break;\n case 'double':\n out = (result as RDouble).toNumber();\n break;\n default:\n throwType();\n }\n break;\n case 'number[]':\n switch (result.type()) {\n case 'logical':\n out = (result as RLogical).toArray();\n out = out.map((i) => i === null ? throwType() : Number(i));\n break;\n case 'integer':\n out = (result as RInteger).toArray();\n if (out.some((i) => i === null)) {\n throwType();\n }\n break;\n case 'double':\n out = (result as RDouble).toArray();\n if (out.some((i) => i === null)) {\n throwType();\n }\n break;\n default:\n throwType();\n }\n break;\n case 'string':\n switch (result.type()) {\n case 'character':\n out = (result as RCharacter).toString();\n break;\n default:\n throwType();\n }\n break;\n case 'string[]':\n switch (result.type()) {\n case 'character':\n out = (result as RCharacter).toArray();\n if (out.some((i) => i === null)) {\n throwType();\n }\n break;\n default:\n throwType();\n }\n break;\n default:\n throw new Error('Unexpected output type in `evalRRaw().');\n }\n\n write({\n obj: out,\n payloadType: 'raw',\n });\n break;\n } finally {\n unprotect(1);\n }\n }\n\n case 'newRObject': {\n const msg = reqMsg as NewRObjectMessage;\n\n const payload = newRObject(msg.data.obj, msg.data.objType);\n keep(msg.data.shelter, payload.obj.ptr);\n\n write(payload);\n break;\n }\n\n case 'callRObjectMethod': {\n const msg = reqMsg as CallRObjectMethodMessage;\n const data = msg.data;\n const obj = data.payload ? RObject.wrap(data.payload.obj.ptr) : RObject;\n\n const payload = callRObjectMethod(obj, data.prop, data.args);\n if (isWebRPayloadPtr(payload)) {\n // TODO: Remove `!`\n keep(data.shelter!, payload.obj.ptr);\n }\n\n write(payload);\n break;\n }\n\n case 'installPackage': {\n // TODO: Use `evalRVoid()`\n evalR(`webr::install(\"${reqMsg.data.name as string}\", repos=\"${_config.PKG_URL}\")`);\n\n write({\n obj: true,\n payloadType: 'raw',\n });\n break;\n }\n default:\n throw new Error('Unknown event `' + reqMsg.type + '`');\n }\n } catch (_e) {\n const e = _e as Error;\n write({\n payloadType: 'err',\n obj: { name: e.name, message: e.message, stack: e.stack },\n });\n\n /* Capture continuation token and resume R's non-local transfer.\n * If the exception has reached this point there should no longer be\n * any `evalJs()` calls on the stack. As such, we assume there are no R\n * calls above us and it is safe to `longjmp` from here.\n */\n if (e instanceof UnwindProtectException) {\n Module._R_ContinueUnwind(e.cont);\n throwUnreachable();\n }\n }\n break;\n }\n default:\n throw new Error('Unknown event `' + msg.type + '`');\n }\n}\n\nfunction copyFSNode(obj: FSNode): FSNode {\n const retObj = {\n id: obj.id,\n name: obj.name,\n mode: obj.mode,\n isFolder: obj.isFolder,\n contents: {},\n };\n if (obj.isFolder) {\n retObj.contents = Object.entries(obj.contents).map(([, node]) => copyFSNode(node));\n }\n return retObj;\n}\n\nfunction downloadFileContent(URL: string, headers: Array<string> = []): XHRResponse {\n const request = new XMLHttpRequest();\n request.open('GET', URL, false);\n request.responseType = 'arraybuffer';\n\n try {\n headers.forEach((header) => {\n const splitHeader = header.split(': ');\n request.setRequestHeader(splitHeader[0], splitHeader[1]);\n });\n } catch {\n const responseText = 'An error occured setting headers in XMLHttpRequest';\n console.error(responseText);\n return { status: 400, response: responseText };\n }\n\n try {\n request.send(null);\n const status = IN_NODE\n ? (JSON.parse(String(request.status)) as { data: { statusCode: number } }).data.statusCode\n : request.status;\n\n if (status >= 200 && status < 300) {\n return { status: status, response: request.response as ArrayBuffer };\n } else {\n const responseText = new TextDecoder().decode(request.response as ArrayBuffer);\n console.error(`Error fetching ${URL} - ${responseText}`);\n return { status: status, response: responseText };\n }\n } catch {\n return { status: 400, response: 'An error occured in XMLHttpRequest' };\n }\n}\n\nfunction newRObject(data: WebRData, objType: RType | 'object'): WebRPayloadPtr {\n const RClass = objType === 'object' ? RObject : getRWorkerClass(RTypeMap[objType]);\n const obj = new RClass(\n replaceInObject(data, isWebRPayloadPtr, (t: WebRPayloadPtr) =>\n RObject.wrap(t.obj.ptr)\n ) as WebRData\n );\n return {\n obj: {\n type: obj.type(),\n ptr: obj.ptr,\n methods: RObject.getMethods(obj),\n },\n payloadType: 'ptr',\n };\n}\n\nfunction callRObjectMethod(\n obj: RObject | typeof RObject,\n prop: string,\n args: WebRPayloadWorker[]\n): WebRPayloadWorker {\n if (!(prop in obj)) {\n throw new ReferenceError(`${prop} is not defined`);\n }\n\n const fn = obj[prop as keyof typeof obj];\n if (typeof fn !== 'function') {\n throw Error('Requested property cannot be invoked');\n }\n\n const res = (fn as Function).apply(\n obj,\n args.map((arg) => {\n if (arg.payloadType === 'ptr') {\n return RObject.wrap(arg.obj.ptr);\n }\n return replaceInObject(arg.obj, isWebRPayloadPtr, (t: WebRPayloadPtr) =>\n RObject.wrap(t.obj.ptr)\n );\n })\n ) as WebRData;\n\n const ret = replaceInObject(res, isRObject, (obj: RObject) => {\n return {\n obj: { type: obj.type(), ptr: obj.ptr, methods: RObject.getMethods(obj) },\n payloadType: 'ptr',\n };\n }) as WebRDataRaw;\n\n return { obj: ret, payloadType: 'raw' };\n}\n\nfunction captureR(code: string, options: EvalROptions = {}): RList {\n const prot = { n: 0 };\n try {\n const _options: Required<EvalROptions> = Object.assign(\n {\n env: objs.globalEnv,\n captureStreams: true,\n captureConditions: true,\n withAutoprint: false,\n throwJsException: true,\n withHandlers: true,\n },\n replaceInObject(options, isWebRPayloadPtr, (t: WebRPayloadPtr) =>\n RObject.wrap(t.obj.ptr)\n )\n );\n\n const envObj = new REnvironment(_options.env);\n protectInc(envObj, prot);\n if (envObj.type() !== 'environment') {\n throw new Error('Attempted to evaluate R code with invalid environment object');\n }\n\n const tPtr = objs.true.ptr;\n const fPtr = objs.false.ptr;\n\n const fn = parseEvalBare('webr::eval_r', objs.baseEnv);\n protectInc(fn, prot);\n\n const codeObj = new RCharacter(code);\n protectInc(codeObj, prot);\n\n const call = Module._Rf_lang6(\n fn.ptr,\n codeObj.ptr,\n _options.captureConditions ? tPtr : fPtr,\n _options.captureStreams ? tPtr : fPtr,\n _options.withAutoprint ? tPtr : fPtr,\n _options.withHandlers ? tPtr : fPtr\n );\n protectInc(call, prot);\n\n const capture = RList.wrap(safeEval(call, envObj));\n protectInc(capture, prot);\n\n if (_options.captureConditions && _options.throwJsException) {\n const output = capture.get('output') as RList;\n const error = (output.toArray() as RObject[]).find(\n (out) => out.get('type').toString() === 'error'\n );\n if (error) {\n throw new Error(\n error.pluck('data', 'message')?.toString() || 'An error occured evaluating R code.'\n );\n }\n }\n\n return capture;\n } finally {\n unprotect(prot.n);\n }\n}\n\nfunction evalR(code: string, options: EvalROptions = {}): RObject {\n const capture = captureR(code, options);\n Module._Rf_protect(capture.ptr);\n\n try {\n // Send captured conditions and output to the JS console. By default, captured\n // error conditions are thrown and so do not need to be handled here.\n const output = capture.get('output') as RList;\n for (let i = 1; i <= output.length; i++) {\n const out = output.get(i);\n const outputType = out.get('type').toString();\n switch (outputType) {\n case 'stdout':\n console.log(out.get('data').toString());\n break;\n case 'stderr':\n console.warn(out.get('data').toString());\n break;\n case 'message':\n console.warn(out.pluck('data', 'message')?.toString() || '');\n break;\n case 'warning':\n console.warn(`Warning message: \\n${out.pluck('data', 'message')?.toString() || ''}`);\n break;\n default:\n console.warn(`Output of type ${outputType}:`);\n console.warn(out.get('data').toJs());\n break;\n }\n }\n return capture.get('result');\n } finally {\n Module._Rf_unprotect(1);\n }\n}\n\nfunction init(config: Required<WebROptions>) {\n _config = config;\n\n const env = { ...config.REnv };\n if (!env.TZ) {\n const fmt = new Intl.DateTimeFormat();\n env.TZ = fmt.resolvedOptions().timeZone;\n }\n\n Module.preRun = [];\n Module.arguments = _config.RArgs;\n Module.noExitRuntime = true;\n Module.noImageDecoding = true;\n Module.noAudioDecoding = true;\n Module.noInitialRun = true;\n\n // Don't instantiate .so libraries packaged through `WEBR_REPO` too\n // early. Otherwise C++ libraries with dynamic initialisation of\n // global variables might call into the R API too early, before R has\n // started.\n Module.noWasmDecoding = true;\n\n Module.preRun.push(() => {\n if (IN_NODE) {\n globalThis.FS = Module.FS;\n }\n Module.FS.mkdirTree(_config.homedir);\n Module.ENV.HOME = _config.homedir;\n Module.FS.chdir(_config.homedir);\n\n Module.ENV = Object.assign(Module.ENV, env);\n });\n\n chan?.setDispatchHandler(dispatch);\n\n Module.onRuntimeInitialized = () => {\n chan?.run(_config.RArgs);\n };\n\n Module.webr = {\n UnwindProtectException: UnwindProtectException,\n resolveInit: () => {\n initPersistentObjects();\n chan?.setInterrupt(Module._Rf_onintr);\n Module.setValue(Module._R_Interactive, _config.interactive, '*');\n evalR(`options(webr_pkg_repos=\"${_config.PKG_URL}\")`);\n chan?.resolve();\n },\n\n readConsole: () => {\n if (!chan) {\n throw new Error(\"Can't read console input without a communication channel\");\n }\n return chan.inputOrDispatch();\n },\n\n handleEvents: () => {\n chan?.handleInterrupt();\n },\n\n evalJs: (code: RPtr): number => {\n try {\n return (0, eval)(Module.UTF8ToString(code));\n } catch (e) {\n /* Capture continuation token and resume R's non-local transfer here.\n * By resuming here we avoid potentially unwinding a target intermediate\n * R stack on the way up to the top level.\n */\n if (e instanceof UnwindProtectException) {\n Module._R_ContinueUnwind(e.cont);\n throwUnreachable();\n }\n const msg = Module.allocateUTF8OnStack(\n `An error occured during JavaScript evaluation:\\n ${(e as { message: string }).message}`\n );\n Module._Rf_error(msg);\n }\n throwUnreachable();\n return 0;\n },\n };\n\n Module.locateFile = (path: string) => _config.WEBR_URL + path;\n Module.downloadFileContent = downloadFileContent;\n\n Module.print = (text: string) => {\n chan?.write({ type: 'stdout', data: text });\n };\n Module.printErr = (text: string) => {\n chan?.write({ type: 'stderr', data: text });\n };\n Module.setPrompt = (prompt: string) => {\n chan?.write({ type: 'prompt', data: prompt });\n };\n Module.canvasExec = (op: string) => {\n chan?.write({ type: 'canvasExec', data: op });\n };\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n (globalThis as any).Module = Module;\n\n // At the next tick, launch the REPL. This never returns.\n setTimeout(() => {\n const scriptSrc = `${_config.WEBR_URL}R.bin.js`;\n loadScript(scriptSrc);\n });\n}\n"],
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA,mEAAAA,SAAA;AAaA,QAAI,KAAK,QAAQ;AACjB,QAAI,MAAM,QAAQ;AAClB,QAAI,QAAQ,QAAQ,iBAAiB;AAMrC,IAAAA,QAAO,UAAUC;AAGjB,IAAAA,gBAAe,iBAAiBA;AAYhC,aAASA,gBAAe,MAAM;AAC5B;AAEA,aAAO,QAAQ,CAAC;AAKhB,UAAI,OAAO;AACX,UAAI,OAAO,QAAQ;AACnB,UAAI,QAAQ,QAAQ;AAGpB,UAAI;AACJ,UAAI;AAGJ,UAAI,WAAW,CAAC;AAIhB,UAAI,qBAAqB;AAGzB,UAAI,iBAAiB;AAAA,QACnB,cAAc;AAAA,QACd,UAAU;AAAA,MACZ;AAEA,UAAI,UAAU,OAAO,OAAO,CAAC,GAAG,cAAc;AAK9C,UAAI,0BAA0B;AAAA,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BAA2B,QAAQ,WAAW;AACpD,mCAAM;AAAA,IACR;AAAA,IAEA,aAAa,MAAM;AACjB,UAAI,CAAC,MAAM;AACT,cAAM,IAAI,MAAM,0DAA0D;AAAA,MAC5E;AACA,aAAO,KAAK,gBAAgB;AAAA,IAC9B;AAAA,IAEA,cAAc,MAAM;AAClB,mCAAM;AAAA,IACR;AAAA,IAEA,QAAQ,CAAC,SAAuB;AAC9B,UAAI;AACF,gBAAQ,GAAG,MAAM,OAAO,aAAa,IAAI,CAAC;AAAA,MAC5C,SAAS,GAAP;AAKA,YAAI,aAAa,wBAAwB;AACvC,iBAAO,kBAAkB,EAAE,IAAI;AAC/B,2BAAiB;AAAA,QACnB;AACA,cAAM,MAAM,OAAO;AAAA,UACjB;AAAA,IAAsD,EAA0B;AAAA,QAClF;AACA,eAAO,UAAU,GAAG;AAAA,MACtB;AACA,uBAAiB;AACjB,aAAO;AAAA,IACT;AAAA,EACF;AAEA,SAAO,aAAa,CAAC,SAAiB,QAAQ,WAAW;AACzD,SAAO,sBAAsB;AAE7B,SAAO,QAAQ,CAAC,SAAiB;AAC/B,iCAAM,MAAM,EAAE,MAAM,UAAU,MAAM,KAAK;AAAA,EAC3C;AACA,SAAO,WAAW,CAAC,SAAiB;AAClC,iCAAM,MAAM,EAAE,MAAM,UAAU,MAAM,KAAK;AAAA,EAC3C;AACA,SAAO,YAAY,CAAC,WAAmB;AACrC,iCAAM,MAAM,EAAE,MAAM,UAAU,MAAM,OAAO;AAAA,EAC7C;AACA,SAAO,aAAa,CAAC,OAAe;AAClC,iCAAM,MAAM,EAAE,MAAM,cAAc,MAAM,GAAG;AAAA,EAC7C;AAGA,EAAC,WAAmB,SAAS;AAG7B,aAAW,MAAM;AACf,UAAM,YAAY,GAAG,QAAQ;AAC7B,eAAW,SAAS;AAAA,EACtB,CAAC;AACH;",
"names": ["module", "XMLHttpRequest", "data", "resp", "url", "encoder", "decoder", "size", "_interruptBuffer", "transfer", "dispatch", "_handleEventsFromWorker", "handleEventsFromWorker_fn", "_onMessageFromWorker", "_ep", "_dispatch", "_interrupt", "transfer", "dispatch", "objs", "_newSetter", "msg", "data", "URL", "obj"]
}