@lvce-editor/renderer-process 30.40.0 → 30.41.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -118,25 +118,25 @@ const confirm = message => {
118
118
  return window.confirm(message);
119
119
  };
120
120
 
121
- const state$e = {
121
+ const state$f = {
122
122
  styleSheets: Object.create(null),
123
123
  texts: Object.create(null)
124
124
  };
125
125
  const set$b = (id, sheet) => {
126
- state$e.styleSheets[id] = sheet;
126
+ state$f.styleSheets[id] = sheet;
127
127
  };
128
128
  const get$b = id => {
129
- return state$e.styleSheets[id];
129
+ return state$f.styleSheets[id];
130
130
  };
131
131
  const setText$2 = (id, text) => {
132
- state$e.texts[id] = text;
132
+ state$f.texts[id] = text;
133
133
  };
134
134
  const getText = id => {
135
- return state$e.texts[id];
135
+ return state$f.texts[id];
136
136
  };
137
137
  const remove$5 = id => {
138
- delete state$e.styleSheets[id];
139
- delete state$e.texts[id];
138
+ delete state$f.styleSheets[id];
139
+ delete state$f.texts[id];
140
140
  };
141
141
 
142
142
  const addCssStyleSheet = (id, text) => {
@@ -331,7 +331,7 @@ const createIdGenerator = () => {
331
331
  };
332
332
  const create$J = createIdGenerator();
333
333
 
334
- const state$d = Object.create(null);
334
+ const state$e = Object.create(null);
335
335
  const retainString = (item, index) => {
336
336
  const value = new Promise(resolve => {
337
337
  item.getAsString(resolve);
@@ -382,22 +382,22 @@ const retainItems = dataTransfer => {
382
382
  };
383
383
  const add$2 = dataTransfer => {
384
384
  const id = create$J();
385
- state$d[id] = retainItems(dataTransfer);
385
+ state$e[id] = retainItems(dataTransfer);
386
386
  return id;
387
387
  };
388
388
  const acquire$2 = id => {
389
- const items = state$d[id];
389
+ const items = state$e[id];
390
390
  if (!items) {
391
391
  throw new Error(`Drop data not found: ${id}`);
392
392
  }
393
- delete state$d[id];
393
+ delete state$e[id];
394
394
  return items;
395
395
  };
396
396
 
397
- const state$c = Object.create(null);
397
+ const state$d = Object.create(null);
398
398
  const acquire$1 = id => {
399
- const promise = state$c[id];
400
- delete state$c[id];
399
+ const promise = state$d[id];
400
+ delete state$d[id];
401
401
  return promise;
402
402
  };
403
403
  const getFileHandles$1 = async ids => {
@@ -407,7 +407,7 @@ const getFileHandles$1 = async ids => {
407
407
  };
408
408
  const add$1 = promise => {
409
409
  const id = create$J();
410
- state$c[id] = promise;
410
+ state$d[id] = promise;
411
411
  return id;
412
412
  };
413
413
  const addFileHandle$1 = fileHandle => {
@@ -609,14 +609,14 @@ const getEventListenerArgs = (params, event) => {
609
609
  return serialized;
610
610
  };
611
611
 
612
- const state$b = {
612
+ const state$c = {
613
613
  ipc: undefined
614
614
  };
615
615
  const getIpc = () => {
616
- return state$b.ipc;
616
+ return state$c.ipc;
617
617
  };
618
618
  const setIpc = value => {
619
- state$b.ipc = value;
619
+ state$c.ipc = value;
620
620
  };
621
621
 
622
622
  const nameAnonymousFunction$1 = (fn, name) => {
@@ -2039,238 +2039,389 @@ const unregisterView = uid => {
2039
2039
  viewRpcIds.delete(uid);
2040
2040
  };
2041
2041
 
2042
- const downloadFile = (fileName, url) => {
2043
- const a = document.createElement('a');
2044
- a.href = url;
2045
- a.download = fileName;
2046
- a.click();
2047
- };
2048
-
2049
- const isFile = value => {
2050
- return value instanceof File;
2051
- };
2052
-
2053
- const getFilePathElectron = async file => {
2054
- if (!isFile(file)) {
2055
- throw new TypeError(`file must be of type File`);
2042
+ const normalizeLine = line => {
2043
+ if (line.startsWith('Error: ')) {
2044
+ return line.slice('Error: '.length);
2056
2045
  }
2057
- if (!globalThis.electronGlobals) {
2058
- throw new Error(`electron globals are not available`);
2046
+ if (line.startsWith('VError: ')) {
2047
+ return line.slice('VError: '.length);
2059
2048
  }
2060
- const filePath = globalThis.electronGlobals.getPathForFile(file);
2061
- return filePath;
2049
+ return line;
2062
2050
  };
2063
-
2064
- const validFormats = new Set(['file', 'fileSystemHandle', 'string']);
2065
- const validateOptions = options => {
2066
- if (!options || !Array.isArray(options.formats) || typeof options.includeElectronFilePaths !== 'boolean') {
2067
- throw new TypeError('Invalid drop data options');
2068
- }
2069
- for (const format of options.formats) {
2070
- if (!validFormats.has(format)) {
2071
- throw new TypeError(`Invalid drop data format: ${format}`);
2072
- }
2051
+ const getCombinedMessage = (error, message) => {
2052
+ const stringifiedError = normalizeLine(`${error}`);
2053
+ if (message) {
2054
+ return `${message}: ${stringifiedError}`;
2073
2055
  }
2056
+ return stringifiedError;
2074
2057
  };
2075
- const resolveString = async item => {
2076
- return {
2077
- index: item.index,
2078
- kind: 'string',
2079
- type: item.type,
2080
- value: await item.value
2081
- };
2058
+ const NewLine$3 = '\n';
2059
+ const getNewLineIndex$1 = (string, startIndex = undefined) => {
2060
+ return string.indexOf(NewLine$3, startIndex);
2082
2061
  };
2083
- const resolveFile = async (item, formats, includeElectronFilePaths) => {
2084
- const includeFile = formats.has('file');
2085
- const includeFileSystemHandle = formats.has('fileSystemHandle');
2086
- const fileSystemHandle = includeFileSystemHandle ? await item.fileSystemHandle : undefined;
2087
- const electronFilePath = includeElectronFilePaths && globalThis.electronGlobals && item.file ? await getFilePathElectron(item.file) : undefined;
2088
- if ((!includeFile || !item.file) && !fileSystemHandle && electronFilePath === undefined) {
2089
- return undefined;
2062
+ const mergeStacks$1 = (parent, child) => {
2063
+ if (!child) {
2064
+ return parent;
2090
2065
  }
2091
- return {
2092
- ...(electronFilePath !== undefined && {
2093
- electronFilePath
2094
- }),
2095
- ...(includeFile && item.file && {
2096
- file: item.file
2097
- }),
2098
- ...(fileSystemHandle && {
2099
- fileSystemHandle
2100
- }),
2101
- index: item.index,
2102
- kind: 'file',
2103
- name: fileSystemHandle?.name || item.file?.name || '',
2104
- type: item.type
2105
- };
2066
+ const parentNewLineIndex = getNewLineIndex$1(parent);
2067
+ const childNewLineIndex = getNewLineIndex$1(child);
2068
+ if (childNewLineIndex === -1) {
2069
+ return parent;
2070
+ }
2071
+ const parentFirstLine = parent.slice(0, parentNewLineIndex);
2072
+ const childRest = child.slice(childNewLineIndex);
2073
+ const childFirstLine = normalizeLine(child.slice(0, childNewLineIndex));
2074
+ if (parentFirstLine.includes(childFirstLine)) {
2075
+ return parentFirstLine + childRest;
2076
+ }
2077
+ return child;
2106
2078
  };
2107
- const get$6 = async (dropId, options) => {
2108
- validateOptions(options);
2109
- const retainedItems = acquire$2(dropId);
2110
- const formats = new Set(options.formats);
2111
- const items = [];
2112
- for (const retainedItem of retainedItems) {
2113
- if (retainedItem.kind === 'string') {
2114
- if (formats.has('string')) {
2115
- items.push(await resolveString(retainedItem));
2116
- }
2117
- continue;
2079
+ let VError$1 = class VError extends Error {
2080
+ constructor(error, message) {
2081
+ const combinedMessage = getCombinedMessage(error, message);
2082
+ super(combinedMessage);
2083
+ this.name = 'VError';
2084
+ if (error instanceof Error) {
2085
+ this.stack = mergeStacks$1(this.stack, error.stack);
2118
2086
  }
2119
- const item = await resolveFile(retainedItem, formats, options.includeElectronFilePaths);
2120
- if (item) {
2121
- items.push(item);
2087
+ if (error.codeFrame) {
2088
+ // @ts-ignore
2089
+ this.codeFrame = error.codeFrame;
2090
+ }
2091
+ if (error.code) {
2092
+ // @ts-ignore
2093
+ this.code = error.code;
2122
2094
  }
2123
2095
  }
2124
- return items;
2125
2096
  };
2126
2097
 
2127
- const isFileSystemFileHandle = value => {
2128
- if (!value || typeof value !== 'object') {
2129
- return false;
2098
+ const isMessagePort$1 = value => {
2099
+ return value && value instanceof MessagePort;
2100
+ };
2101
+ const isMessagePortMain = value => {
2102
+ return value && value.constructor && value.constructor.name === 'MessagePortMain';
2103
+ };
2104
+ const isOffscreenCanvas = value => {
2105
+ return typeof OffscreenCanvas !== 'undefined' && value instanceof OffscreenCanvas;
2106
+ };
2107
+ const isInstanceOf = (value, constructorName) => {
2108
+ return value?.constructor?.name === constructorName;
2109
+ };
2110
+ const isSocket = value => {
2111
+ return isInstanceOf(value, 'Socket');
2112
+ };
2113
+ const transferrables$1 = [isMessagePort$1, isMessagePortMain, isOffscreenCanvas, isSocket];
2114
+ const isTransferrable$1 = value => {
2115
+ for (const fn of transferrables$1) {
2116
+ if (fn(value)) {
2117
+ return true;
2118
+ }
2130
2119
  }
2131
- const candidate = value;
2132
- return candidate.kind === 'file' && typeof candidate.getFile === 'function';
2120
+ return false;
2133
2121
  };
2134
- const getNativeFile = async item => {
2135
- if (item.kind === 'file-legacy') {
2136
- return item.value instanceof File ? item.value : undefined;
2122
+ const walkValue$1 = (value, transferrables, isTransferrable) => {
2123
+ if (!value) {
2124
+ return;
2137
2125
  }
2138
- if (item.file instanceof File) {
2139
- return item.file;
2126
+ if (isTransferrable(value)) {
2127
+ transferrables.push(value);
2128
+ return;
2140
2129
  }
2141
- if (isFileSystemFileHandle(item.value)) {
2142
- return item.value.getFile();
2130
+ if (Array.isArray(value)) {
2131
+ for (const item of value) {
2132
+ walkValue$1(item, transferrables, isTransferrable);
2133
+ }
2134
+ return;
2135
+ }
2136
+ if (typeof value === 'object') {
2137
+ for (const property of Object.values(value)) {
2138
+ walkValue$1(property, transferrables, isTransferrable);
2139
+ }
2143
2140
  }
2144
- return undefined;
2145
2141
  };
2146
- const addElectronPath = async item => {
2147
- if (!globalThis.electronGlobals) {
2148
- return item;
2142
+ const getTransferrables = value => {
2143
+ const transferrables = [];
2144
+ walkValue$1(value, transferrables, isTransferrable$1);
2145
+ return transferrables;
2146
+ };
2147
+ const removeValues = (value, toRemove) => {
2148
+ if (!value) {
2149
+ return value;
2149
2150
  }
2150
- const file = await getNativeFile(item);
2151
- if (!file) {
2152
- return item;
2151
+ if (Array.isArray(value)) {
2152
+ const newItems = [];
2153
+ for (const item of value) {
2154
+ if (!toRemove.includes(item)) {
2155
+ newItems.push(removeValues(item, toRemove));
2156
+ }
2157
+ }
2158
+ return newItems;
2153
2159
  }
2154
- const path = await getFilePathElectron(file);
2155
- return {
2156
- ...item,
2157
- path
2158
- };
2159
- };
2160
- const get$5 = async ids => {
2161
- const items = await getFileHandles$1(ids);
2162
- return Promise.all(items.map(addElectronPath));
2160
+ if (typeof value === 'object') {
2161
+ const newObject = Object.create(null);
2162
+ for (const [key, property] of Object.entries(value)) {
2163
+ if (!toRemove.includes(property)) {
2164
+ newObject[key] = removeValues(property, toRemove);
2165
+ }
2166
+ }
2167
+ return newObject;
2168
+ }
2169
+ return value;
2163
2170
  };
2164
2171
 
2165
- const showDirectoryPicker = options => {
2166
- // @ts-expect-error
2167
- return window.showDirectoryPicker(options);
2172
+ // workaround for electron not supporting transferrable objects
2173
+ // as parameters. If the transferrable object is a parameter, in electron
2174
+ // only an empty objected is received in the main process
2175
+ const fixElectronParameters = value => {
2176
+ const transfer = getTransferrables(value);
2177
+ const newValue = removeValues(value, transfer);
2178
+ return {
2179
+ newValue,
2180
+ transfer
2181
+ };
2168
2182
  };
2169
- const showFilePicker = options => {
2170
- // @ts-expect-error
2171
- return window.showOpenFilePicker(options);
2183
+ const attachEvents$8 = that => {
2184
+ const handleMessage = (...args) => {
2185
+ const data = that.getData(...args);
2186
+ that.dispatchEvent(new MessageEvent('message', {
2187
+ data
2188
+ }));
2189
+ };
2190
+ that.onMessage(handleMessage);
2191
+ const handleClose = event => {
2192
+ that.dispatchEvent(new Event('close'));
2193
+ };
2194
+ that.onClose(handleClose);
2172
2195
  };
2173
- const showSaveFilePicker = options => {
2174
- // @ts-expect-error
2175
- return window.showSaveFilePicker(options);
2196
+ class Ipc extends EventTarget {
2197
+ constructor(rawIpc) {
2198
+ super();
2199
+ this._rawIpc = rawIpc;
2200
+ attachEvents$8(this);
2201
+ }
2202
+ }
2203
+ const E_INCOMPATIBLE_NATIVE_MODULE = 'E_INCOMPATIBLE_NATIVE_MODULE';
2204
+ const E_MODULES_NOT_SUPPORTED_IN_ELECTRON = 'E_MODULES_NOT_SUPPORTED_IN_ELECTRON';
2205
+ const ERR_MODULE_NOT_FOUND = 'ERR_MODULE_NOT_FOUND';
2206
+ const NewLine$2 = '\n';
2207
+ const joinLines$2 = lines => {
2208
+ return lines.join(NewLine$2);
2176
2209
  };
2177
-
2178
- const requestPermission = (handle, options) => {
2179
- return handle.requestPermission(options);
2210
+ const RE_AT$1 = /^\s+at/;
2211
+ const RE_AT_PROMISE_INDEX$1 = /^\s*at async Promise.all \(index \d+\)$/;
2212
+ const isNormalStackLine$1 = line => {
2213
+ return RE_AT$1.test(line) && !RE_AT_PROMISE_INDEX$1.test(line);
2180
2214
  };
2181
- const getFileHandles = ids => {
2182
- return getFileHandles$1(ids);
2215
+ const getDetails$1 = lines => {
2216
+ const index = lines.findIndex(isNormalStackLine$1);
2217
+ if (index === -1) {
2218
+ return {
2219
+ actualMessage: joinLines$2(lines),
2220
+ rest: []
2221
+ };
2222
+ }
2223
+ let lastIndex = index - 1;
2224
+ while (++lastIndex < lines.length) {
2225
+ if (!isNormalStackLine$1(lines[lastIndex])) {
2226
+ break;
2227
+ }
2228
+ }
2229
+ return {
2230
+ actualMessage: lines[index - 1],
2231
+ rest: lines.slice(index, lastIndex)
2232
+ };
2183
2233
  };
2184
- const addFileHandle = fileHandle => {
2185
- return addFileHandle$1(fileHandle);
2234
+ const splitLines$2 = lines => {
2235
+ return lines.split(NewLine$2);
2186
2236
  };
2187
-
2188
- const getTitleBarHeight = () => {
2189
- if (
2190
- // @ts-expect-error
2191
- globalThis.navigator.windowControlsOverlay?.getTitlebarAreaRect) {
2192
- // @ts-expect-error
2193
- const titleBarRect = globalThis.navigator.windowControlsOverlay.getTitlebarAreaRect();
2194
- return titleBarRect.height;
2195
- }
2196
- return 0;
2237
+ const RE_MESSAGE_CODE_BLOCK_START = /^Error: The module '.*'$/;
2238
+ const RE_MESSAGE_CODE_BLOCK_END = /^\s* at/;
2239
+ const isMessageCodeBlockStartIndex = line => {
2240
+ return RE_MESSAGE_CODE_BLOCK_START.test(line);
2197
2241
  };
2198
- const getBounds = () => {
2242
+ const isMessageCodeBlockEndIndex = line => {
2243
+ return RE_MESSAGE_CODE_BLOCK_END.test(line);
2244
+ };
2245
+ const getMessageCodeBlock = stderr => {
2246
+ const lines = splitLines$2(stderr);
2247
+ const startIndex = lines.findIndex(isMessageCodeBlockStartIndex);
2248
+ const endIndex = startIndex + lines.slice(startIndex).findIndex(isMessageCodeBlockEndIndex, startIndex);
2249
+ const relevantLines = lines.slice(startIndex, endIndex);
2250
+ const relevantMessage = relevantLines.join(' ').slice('Error: '.length);
2251
+ return relevantMessage;
2252
+ };
2253
+ const isModuleNotFoundMessage = line => {
2254
+ return line.includes('[ERR_MODULE_NOT_FOUND]');
2255
+ };
2256
+ const getModuleNotFoundError = stderr => {
2257
+ const lines = splitLines$2(stderr);
2258
+ const messageIndex = lines.findIndex(isModuleNotFoundMessage);
2259
+ const message = lines[messageIndex];
2199
2260
  return {
2200
- titleBarHeight: getTitleBarHeight(),
2201
- windowHeight: window.innerHeight,
2202
- windowWidth: window.innerWidth
2261
+ code: ERR_MODULE_NOT_FOUND,
2262
+ message
2203
2263
  };
2204
2264
  };
2205
-
2206
- const getPathName = () => {
2207
- return location.pathname;
2265
+ const isModuleNotFoundError = stderr => {
2266
+ if (!stderr) {
2267
+ return false;
2268
+ }
2269
+ return stderr.includes('ERR_MODULE_NOT_FOUND');
2208
2270
  };
2209
- const getHref = () => {
2210
- return location.href;
2271
+ const isModulesSyntaxError = stderr => {
2272
+ if (!stderr) {
2273
+ return false;
2274
+ }
2275
+ return stderr.includes('SyntaxError: Cannot use import statement outside a module');
2211
2276
  };
2212
- const matchesPathName = (currentPathName, pathName) => {
2213
- const resolvedPathName = new URL(pathName, getHref()).pathname;
2214
- return currentPathName === resolvedPathName;
2277
+ const RE_NATIVE_MODULE_ERROR = /^innerError Error: Cannot find module '.*.node'/;
2278
+ const RE_NATIVE_MODULE_ERROR_2 = /was compiled against a different Node.js version/;
2279
+ const isUnhelpfulNativeModuleError = stderr => {
2280
+ return RE_NATIVE_MODULE_ERROR.test(stderr) && RE_NATIVE_MODULE_ERROR_2.test(stderr);
2215
2281
  };
2216
- const setPathName = pathName => {
2217
- const currentPathName = getPathName();
2218
- if (matchesPathName(currentPathName, pathName)) {
2219
- return;
2220
- }
2221
- history.pushState(null, '', pathName);
2282
+ const getNativeModuleErrorMessage = stderr => {
2283
+ const message = getMessageCodeBlock(stderr);
2284
+ return {
2285
+ code: E_INCOMPATIBLE_NATIVE_MODULE,
2286
+ message: `Incompatible native node module: ${message}`
2287
+ };
2222
2288
  };
2223
- const hydrate$3 = () => {
2224
- // addEventListener('popstate', handlePopState)
2289
+ const getModuleSyntaxError = () => {
2290
+ return {
2291
+ code: E_MODULES_NOT_SUPPORTED_IN_ELECTRON,
2292
+ message: `ES Modules are not supported in electron`
2293
+ };
2225
2294
  };
2226
-
2227
- const shouldLaunchMultipleWorkers = true;
2228
-
2229
- const getConfig = () => {
2230
- const configElement = document.getElementById('Config');
2231
- if (!configElement?.textContent) {
2232
- return {};
2295
+ const getHelpfulChildProcessError = (stdout, stderr) => {
2296
+ if (isUnhelpfulNativeModuleError(stderr)) {
2297
+ return getNativeModuleErrorMessage(stderr);
2233
2298
  }
2234
- return JSON.parse(configElement.textContent);
2299
+ if (isModulesSyntaxError(stderr)) {
2300
+ return getModuleSyntaxError();
2301
+ }
2302
+ if (isModuleNotFoundError(stderr)) {
2303
+ return getModuleNotFoundError(stderr);
2304
+ }
2305
+ const lines = splitLines$2(stderr);
2306
+ const {
2307
+ actualMessage,
2308
+ rest
2309
+ } = getDetails$1(lines);
2310
+ return {
2311
+ code: '',
2312
+ message: actualMessage,
2313
+ stack: rest
2314
+ };
2235
2315
  };
2236
- const getInitData = () => {
2237
- const initData = {
2238
- Config: {
2239
- ...getConfig(),
2240
- shouldLaunchMultipleWorkers: shouldLaunchMultipleWorkers
2241
- },
2242
- Layout: {
2243
- bounds: getBounds()
2244
- },
2245
- Location: {
2246
- href: getHref()
2316
+ let IpcError$1 = class IpcError extends VError$1 {
2317
+ // @ts-ignore
2318
+ constructor(betterMessage, stdout = '', stderr = '') {
2319
+ if (stdout || stderr) {
2320
+ // @ts-ignore
2321
+ const {
2322
+ code,
2323
+ message,
2324
+ stack
2325
+ } = getHelpfulChildProcessError(stdout, stderr);
2326
+ const cause = new Error(message);
2327
+ // @ts-ignore
2328
+ cause.code = code;
2329
+ if (stack) {
2330
+ Object.defineProperty(cause, 'stack', {
2331
+ configurable: true,
2332
+ enumerable: false,
2333
+ value: stack,
2334
+ writable: true
2335
+ });
2336
+ }
2337
+ super(cause, betterMessage);
2338
+ } else {
2339
+ super(betterMessage);
2247
2340
  }
2248
- };
2249
- return initData;
2341
+ // @ts-ignore
2342
+ this.name = 'IpcError';
2343
+ // @ts-ignore
2344
+ this.stdout = stdout;
2345
+ // @ts-ignore
2346
+ this.stderr = stderr;
2347
+ }
2250
2348
  };
2251
-
2252
- const MessagePort$1 = 1;
2253
- const ModuleWorker = 2;
2254
- const ReferencePort = 3;
2255
- const ModuleWorkerWithMessagePort = 4;
2256
- const Electron$1 = 5;
2257
-
2258
- const Message$2 = 'message';
2259
- const Error$3 = 'error';
2260
-
2261
- const withResolvers = () => {
2262
- return Promise.withResolvers();
2349
+ const readyMessage = 'ready';
2350
+ const getData$2 = event => {
2351
+ return event.data;
2263
2352
  };
2264
-
2265
- const getFirstEvent$1 = (eventTarget, eventMap) => {
2353
+ const listen$9 = () => {
2354
+ return globalThis;
2355
+ };
2356
+ const signal$a = global => {
2357
+ global.postMessage(readyMessage);
2358
+ };
2359
+ class IpcChildWithElectronWindow extends Ipc {
2360
+ getData(event) {
2361
+ return getData$2(event);
2362
+ }
2363
+ send(message) {
2364
+ this._rawIpc.postMessage(message);
2365
+ }
2366
+ sendAndTransfer(message) {
2367
+ const {
2368
+ newValue,
2369
+ transfer
2370
+ } = fixElectronParameters(message);
2371
+ this._rawIpc.postMessage(newValue, location.origin, transfer);
2372
+ }
2373
+ dispose() {
2374
+ // ignore
2375
+ }
2376
+ onClose(callback) {
2377
+ // ignore
2378
+ }
2379
+ onMessage(callback) {
2380
+ const wrapped = event => {
2381
+ const {
2382
+ ports
2383
+ } = event;
2384
+ if (ports.length > 0) {
2385
+ return;
2386
+ }
2387
+ callback(event);
2388
+ this._rawIpc.removeEventListener('message', wrapped);
2389
+ };
2390
+ this._rawIpc.addEventListener('message', wrapped);
2391
+ }
2392
+ }
2393
+ const wrap$h = window => {
2394
+ return new IpcChildWithElectronWindow(window);
2395
+ };
2396
+ const IpcChildWithElectronWindow$1 = {
2397
+ __proto__: null,
2398
+ listen: listen$9,
2399
+ signal: signal$a,
2400
+ wrap: wrap$h
2401
+ };
2402
+ const addListener = (emitter, type, callback) => {
2403
+ if ('addEventListener' in emitter) {
2404
+ emitter.addEventListener(type, callback);
2405
+ } else {
2406
+ emitter.on(type, callback);
2407
+ }
2408
+ };
2409
+ const removeListener = (emitter, type, callback) => {
2410
+ if ('removeEventListener' in emitter) {
2411
+ emitter.removeEventListener(type, callback);
2412
+ } else {
2413
+ emitter.off(type, callback);
2414
+ }
2415
+ };
2416
+ const getFirstEvent$1 = (eventEmitter, eventMap) => {
2266
2417
  const {
2267
2418
  promise,
2268
2419
  resolve
2269
- } = withResolvers();
2420
+ } = Promise.withResolvers();
2270
2421
  const listenerMap = Object.create(null);
2271
2422
  const cleanup = value => {
2272
2423
  for (const event of Object.keys(eventMap)) {
2273
- eventTarget.removeEventListener(event, listenerMap[event]);
2424
+ removeListener(eventEmitter, event, listenerMap[event]);
2274
2425
  }
2275
2426
  resolve(value);
2276
2427
  };
@@ -2281,93 +2432,97 @@ const getFirstEvent$1 = (eventTarget, eventMap) => {
2281
2432
  type
2282
2433
  });
2283
2434
  };
2284
- eventTarget.addEventListener(event, listener);
2435
+ addListener(eventEmitter, event, listener);
2285
2436
  listenerMap[event] = listener;
2286
2437
  }
2287
2438
  return promise;
2288
2439
  };
2289
-
2290
- /**
2291
- *
2292
- * @param {Worker} worker
2293
- * @returns
2294
- */
2295
- const getFirstWorkerEvent$1 = worker => {
2296
- return getFirstEvent$1(worker, {
2297
- error: Error$3,
2298
- message: Message$2
2440
+ const Message$1 = 3;
2441
+ const create$5$1 = async ({
2442
+ isMessagePortOpen,
2443
+ messagePort
2444
+ }) => {
2445
+ if (!isMessagePort$1(messagePort)) {
2446
+ throw new IpcError$1('port must be of type MessagePort');
2447
+ }
2448
+ if (isMessagePortOpen) {
2449
+ return messagePort;
2450
+ }
2451
+ const eventPromise = getFirstEvent$1(messagePort, {
2452
+ message: Message$1
2299
2453
  });
2300
- };
2301
-
2302
- const transferrables$1 = [];
2303
- if (typeof MessagePort !== 'undefined') {
2304
- transferrables$1.push(MessagePort);
2305
- }
2306
- if (typeof OffscreenCanvas !== 'undefined') {
2307
- transferrables$1.push(OffscreenCanvas);
2308
- }
2309
-
2310
- const isTransferrable$1 = value => {
2311
- for (const fn of transferrables$1) {
2312
- if (value instanceof fn) {
2313
- return true;
2314
- }
2454
+ messagePort.start();
2455
+ const {
2456
+ event,
2457
+ type
2458
+ } = await eventPromise;
2459
+ if (type !== Message$1) {
2460
+ throw new IpcError$1('Failed to wait for ipc message');
2315
2461
  }
2316
- return false;
2462
+ if (event.data !== readyMessage) {
2463
+ throw new IpcError$1('unexpected first message');
2464
+ }
2465
+ return messagePort;
2317
2466
  };
2318
-
2319
- const walkValue$1 = (value, transferrables) => {
2320
- if (!value) {
2321
- return;
2467
+ const signal$1 = messagePort => {
2468
+ messagePort.start();
2469
+ };
2470
+ let IpcParentWithMessagePort$1 = class IpcParentWithMessagePort extends Ipc {
2471
+ getData = getData$2;
2472
+ send(message) {
2473
+ this._rawIpc.postMessage(message);
2322
2474
  }
2323
- if (isTransferrable$1(value)) {
2324
- transferrables.push(value);
2475
+ sendAndTransfer(message) {
2476
+ const transfer = getTransferrables(message);
2477
+ this._rawIpc.postMessage(message, transfer);
2325
2478
  }
2326
- if (Array.isArray(value)) {
2327
- for (const item of value) {
2328
- walkValue$1(item, transferrables);
2329
- }
2330
- return;
2479
+ dispose() {
2480
+ this._rawIpc.close();
2331
2481
  }
2332
- if (typeof value === 'object') {
2333
- for (const property of Object.values(value)) {
2334
- walkValue$1(property, transferrables);
2335
- }
2482
+ onMessage(callback) {
2483
+ this._rawIpc.addEventListener('message', callback);
2336
2484
  }
2485
+ onClose(callback) {}
2337
2486
  };
2338
-
2339
- const getTransfer = value => {
2340
- const transferrables = [];
2341
- walkValue$1(value, transferrables);
2342
- return transferrables;
2487
+ const wrap$5 = messagePort => {
2488
+ return new IpcParentWithMessagePort$1(messagePort);
2343
2489
  };
2344
-
2345
- let IpcError$1 = class IpcError extends Error {
2346
- constructor(message) {
2347
- super(message);
2348
- this.name = 'IpcError';
2349
- }
2490
+ const IpcParentWithMessagePort$1$1 = {
2491
+ __proto__: null,
2492
+ create: create$5$1,
2493
+ signal: signal$1,
2494
+ wrap: wrap$5
2495
+ };
2496
+ const Message$2 = 'message';
2497
+ const Error$1$1 = 'error';
2498
+ const getFirstWorkerEvent$1 = worker => {
2499
+ return getFirstEvent$1(worker, {
2500
+ error: Error$1$1,
2501
+ message: Message$2
2502
+ });
2350
2503
  };
2351
-
2352
2504
  const isErrorEvent$1 = event => {
2353
2505
  return event instanceof ErrorEvent;
2354
2506
  };
2355
-
2356
- const NewLine$3 = '\n';
2357
-
2358
- const joinLines$2 = lines => {
2359
- return lines.join(NewLine$3);
2507
+ const getWorkerDisplayName$1 = name => {
2508
+ if (!name) {
2509
+ return '<unknown> worker';
2510
+ }
2511
+ if (name.endsWith('Worker') || name.endsWith('worker')) {
2512
+ return name.toLowerCase();
2513
+ }
2514
+ return `${name} Worker`;
2360
2515
  };
2361
-
2362
- const splitLines$2 = lines => {
2363
- string(lines);
2364
- return lines.split(NewLine$3);
2516
+ const tryToGetActualErrorMessage = async ({
2517
+ name
2518
+ }) => {
2519
+ const displayName = getWorkerDisplayName$1(name);
2520
+ return `Failed to start ${displayName}: Worker Launch Error`;
2365
2521
  };
2366
-
2367
2522
  let WorkerError$1 = class WorkerError extends Error {
2368
2523
  constructor(event) {
2369
2524
  super(event.message);
2370
- const stackLines = splitLines$2(this.stack);
2525
+ const stackLines = splitLines$2(this.stack || '');
2371
2526
  const relevantLines = stackLines.slice(1);
2372
2527
  const relevant = joinLines$2(relevantLines);
2373
2528
  this.stack = `${event.message}
@@ -2375,16 +2530,8 @@ let WorkerError$1 = class WorkerError extends Error {
2375
2530
  ${relevant}`;
2376
2531
  }
2377
2532
  };
2378
-
2379
2533
  const Module$1 = 'module';
2380
-
2381
- const getWorkerDisplayName$1 = name => {
2382
- if (name && name.endsWith('Worker')) {
2383
- return name;
2384
- }
2385
- return `${name} worker`;
2386
- };
2387
- const create$I = async ({
2534
+ const create$4$1 = async ({
2388
2535
  name,
2389
2536
  url
2390
2537
  }) => {
@@ -2392,23 +2539,24 @@ const create$I = async ({
2392
2539
  name,
2393
2540
  type: Module$1
2394
2541
  });
2395
- // @ts-expect-error
2396
2542
  const {
2397
2543
  event,
2398
2544
  type
2399
2545
  } = await getFirstWorkerEvent$1(worker);
2400
2546
  switch (type) {
2401
2547
  case Message$2:
2402
- if (event.data !== 'ready') {
2548
+ if (event.data !== readyMessage) {
2403
2549
  throw new IpcError$1('unexpected first message from worker');
2404
2550
  }
2405
2551
  break;
2406
- case Error$3:
2552
+ case Error$1$1:
2407
2553
  if (isErrorEvent$1(event)) {
2408
2554
  throw new WorkerError$1(event);
2409
2555
  }
2410
- const displayName = getWorkerDisplayName$1(name);
2411
- throw new IpcError$1(`Failed to start ${displayName}`);
2556
+ const actualErrorMessage = await tryToGetActualErrorMessage({
2557
+ name
2558
+ });
2559
+ throw new Error(actualErrorMessage);
2412
2560
  }
2413
2561
  return worker;
2414
2562
  };
@@ -2419,1229 +2567,1379 @@ const getData$1 = event => {
2419
2567
  }
2420
2568
  return event;
2421
2569
  };
2422
- const wrap = worker => {
2423
- let handleMessage;
2424
- const wrapped = {
2425
- get onmessage() {
2426
- return handleMessage;
2427
- },
2428
- set onmessage(listener) {
2429
- if (listener) {
2430
- handleMessage = event => {
2431
- const data = getData$1(event);
2432
- listener({
2433
- data,
2434
- target: wrapped
2435
- });
2436
- };
2437
- } else {
2438
- handleMessage = null;
2439
- }
2440
- worker.onmessage = handleMessage;
2441
- },
2442
- send(message) {
2443
- worker.postMessage(message);
2444
- },
2445
- sendAndTransfer(message) {
2446
- const transfer = getTransfer(message);
2447
- worker.postMessage(message, transfer);
2448
- }
2449
- };
2450
- return wrapped;
2451
- };
2452
-
2453
- const IpcParentWithModuleWorker$2 = {
2454
- __proto__: null,
2455
- create: create$I,
2456
- wrap
2457
- };
2458
-
2459
- const isMessagePort$1 = value => {
2460
- return value instanceof MessagePort;
2461
- };
2462
-
2463
- const create$H = async ({
2464
- url
2465
- }) => {
2466
- string(url);
2467
- const portPromise = await new Promise(resolve => {
2468
- Object.defineProperty(globalThis, 'acceptPort', {
2469
- configurable: true,
2470
- value: resolve
2471
- });
2472
- });
2473
- await import(url);
2474
- const port = await portPromise;
2475
- delete globalThis.acceptPort;
2476
- if (!port) {
2477
- throw new IpcError$1('port must be defined');
2570
+ let IpcParentWithModuleWorker$1 = class IpcParentWithModuleWorker extends Ipc {
2571
+ getData(event) {
2572
+ return getData$1(event);
2478
2573
  }
2479
- if (!isMessagePort$1(port)) {
2480
- throw new IpcError$1('port must be of type MessagePort');
2574
+ send(message) {
2575
+ this._rawIpc.postMessage(message);
2576
+ }
2577
+ sendAndTransfer(message) {
2578
+ const transfer = getTransferrables(message);
2579
+ this._rawIpc.postMessage(message, transfer);
2580
+ }
2581
+ dispose() {
2582
+ // ignore
2583
+ }
2584
+ onClose(callback) {
2585
+ // ignore
2586
+ }
2587
+ onMessage(callback) {
2588
+ this._rawIpc.addEventListener('message', callback);
2481
2589
  }
2482
- return port;
2483
- };
2484
-
2485
- const IpcParentWithMessagePort$2 = {
2486
- __proto__: null,
2487
- create: create$H
2488
2590
  };
2489
-
2490
- const create$G = async url => {
2491
- const referencePort = await new Promise(resolve => {
2492
- Object.defineProperty(globalThis, 'acceptReferencePort', {
2493
- configurable: true,
2494
- value: resolve
2495
- });
2496
- import(url);
2497
- });
2498
- delete globalThis.acceptReferencePort;
2499
- return referencePort;
2591
+ const wrap$4 = worker => {
2592
+ return new IpcParentWithModuleWorker$1(worker);
2500
2593
  };
2501
-
2502
- const IpcParentWithReferencePort = {
2594
+ const IpcParentWithModuleWorker$1$1 = {
2503
2595
  __proto__: null,
2504
- create: create$G
2596
+ create: create$4$1,
2597
+ wrap: wrap$4
2505
2598
  };
2506
2599
 
2507
- const normalizeLine = line => {
2508
- if (line.startsWith('Error: ')) {
2509
- return line.slice('Error: '.length);
2510
- }
2511
- if (line.startsWith('VError: ')) {
2512
- return line.slice('VError: '.length);
2600
+ class CommandNotFoundError extends Error {
2601
+ constructor(command) {
2602
+ super(`Command not found ${command}`);
2603
+ this.name = 'CommandNotFoundError';
2513
2604
  }
2514
- return line;
2605
+ }
2606
+ const commands = Object.create(null);
2607
+ const register = commandMap => {
2608
+ Object.assign(commands, commandMap);
2515
2609
  };
2516
- const getCombinedMessage = (error, message) => {
2517
- const stringifiedError = normalizeLine(`${error}`);
2518
- if (message) {
2519
- return `${message}: ${stringifiedError}`;
2610
+ const getCommand = key => {
2611
+ return commands[key];
2612
+ };
2613
+ const execute = (command, ...args) => {
2614
+ const fn = getCommand(command);
2615
+ if (!fn) {
2616
+ throw new CommandNotFoundError(command);
2520
2617
  }
2521
- return stringifiedError;
2618
+ return fn(...args);
2522
2619
  };
2523
- const NewLine$2 = '\n';
2524
- const getNewLineIndex$1 = (string, startIndex = undefined) => {
2525
- return string.indexOf(NewLine$2, startIndex);
2620
+
2621
+ const Two$1 = '2.0';
2622
+ const callbacks = Object.create(null);
2623
+ const get$6 = id => {
2624
+ return callbacks[id];
2526
2625
  };
2527
- const mergeStacks$1 = (parent, child) => {
2528
- if (!child) {
2529
- return parent;
2626
+ const remove$4 = id => {
2627
+ delete callbacks[id];
2628
+ };
2629
+ class JsonRpcError extends Error {
2630
+ constructor(message) {
2631
+ super(message);
2632
+ this.name = 'JsonRpcError';
2530
2633
  }
2531
- const parentNewLineIndex = getNewLineIndex$1(parent);
2532
- const childNewLineIndex = getNewLineIndex$1(child);
2533
- if (childNewLineIndex === -1) {
2534
- return parent;
2634
+ }
2635
+ const NewLine$1 = '\n';
2636
+ const DomException = 'DOMException';
2637
+ const ReferenceError$1 = 'ReferenceError';
2638
+ const SyntaxError$1 = 'SyntaxError';
2639
+ const TypeError$1 = 'TypeError';
2640
+ const getErrorConstructor = (message, type) => {
2641
+ if (type) {
2642
+ switch (type) {
2643
+ case DomException:
2644
+ return DOMException;
2645
+ case ReferenceError$1:
2646
+ return ReferenceError;
2647
+ case SyntaxError$1:
2648
+ return SyntaxError;
2649
+ case TypeError$1:
2650
+ return TypeError;
2651
+ default:
2652
+ return Error;
2653
+ }
2535
2654
  }
2536
- const parentFirstLine = parent.slice(0, parentNewLineIndex);
2537
- const childRest = child.slice(childNewLineIndex);
2538
- const childFirstLine = normalizeLine(child.slice(0, childNewLineIndex));
2539
- if (parentFirstLine.includes(childFirstLine)) {
2540
- return parentFirstLine + childRest;
2655
+ if (message.startsWith('TypeError: ')) {
2656
+ return TypeError;
2541
2657
  }
2542
- return child;
2658
+ if (message.startsWith('SyntaxError: ')) {
2659
+ return SyntaxError;
2660
+ }
2661
+ if (message.startsWith('ReferenceError: ')) {
2662
+ return ReferenceError;
2663
+ }
2664
+ return Error;
2543
2665
  };
2544
- let VError$1 = class VError extends Error {
2545
- constructor(error, message) {
2546
- const combinedMessage = getCombinedMessage(error, message);
2547
- super(combinedMessage);
2548
- this.name = 'VError';
2549
- if (error instanceof Error) {
2550
- this.stack = mergeStacks$1(this.stack, error.stack);
2551
- }
2552
- if (error.codeFrame) {
2553
- // @ts-ignore
2554
- this.codeFrame = error.codeFrame;
2555
- }
2556
- if (error.code) {
2557
- // @ts-ignore
2558
- this.code = error.code;
2666
+ const constructError = (message, type, name) => {
2667
+ const ErrorConstructor = getErrorConstructor(message, type);
2668
+ if (ErrorConstructor === DOMException && name) {
2669
+ return new ErrorConstructor(message, name);
2670
+ }
2671
+ if (ErrorConstructor === Error) {
2672
+ const error = new Error(message);
2673
+ if (name && name !== 'VError') {
2674
+ Object.defineProperty(error, 'name', {
2675
+ configurable: true,
2676
+ value: name
2677
+ });
2559
2678
  }
2679
+ return error;
2560
2680
  }
2681
+ return new ErrorConstructor(message);
2561
2682
  };
2562
-
2563
- const isMessagePort = value => {
2564
- return value && value instanceof MessagePort;
2683
+ const joinLines$1 = lines => {
2684
+ return lines.join(NewLine$1);
2565
2685
  };
2566
- const isMessagePortMain = value => {
2567
- return value && value.constructor && value.constructor.name === 'MessagePortMain';
2686
+ const splitLines$1 = lines => {
2687
+ return lines.split(NewLine$1);
2568
2688
  };
2569
- const isOffscreenCanvas = value => {
2570
- return typeof OffscreenCanvas !== 'undefined' && value instanceof OffscreenCanvas;
2689
+ const getCurrentStack = () => {
2690
+ const stackLinesToSkip = 3;
2691
+ const currentStack = joinLines$1(splitLines$1(new Error().stack || '').slice(stackLinesToSkip));
2692
+ return currentStack;
2571
2693
  };
2572
- const isInstanceOf = (value, constructorName) => {
2573
- return value?.constructor?.name === constructorName;
2694
+ const getNewLineIndex = (string, startIndex) => {
2695
+ {
2696
+ return string.indexOf(NewLine$1);
2697
+ }
2574
2698
  };
2575
- const isSocket = value => {
2576
- return isInstanceOf(value, 'Socket');
2699
+ const getParentStack = error => {
2700
+ let parentStack = error.stack || error.data || error.message || '';
2701
+ if (parentStack.startsWith(' at')) {
2702
+ parentStack = error.message + NewLine$1 + parentStack;
2703
+ }
2704
+ return parentStack;
2577
2705
  };
2578
- const transferrables = [isMessagePort, isMessagePortMain, isOffscreenCanvas, isSocket];
2579
- const isTransferrable = value => {
2580
- for (const fn of transferrables) {
2581
- if (fn(value)) {
2582
- return true;
2706
+ const MethodNotFound = -32601;
2707
+ const Custom = -32001;
2708
+ const setStack = (error, stack) => {
2709
+ const descriptor = Object.getOwnPropertyDescriptor(error, 'stack');
2710
+ if (descriptor) {
2711
+ if (!descriptor.configurable && !descriptor.writable) {
2712
+ return;
2713
+ }
2714
+ if (!descriptor.configurable && descriptor.writable) {
2715
+ error.stack = stack;
2716
+ return;
2583
2717
  }
2584
2718
  }
2585
- return false;
2719
+ Object.defineProperty(error, 'stack', {
2720
+ configurable: true,
2721
+ value: stack,
2722
+ writable: true
2723
+ });
2586
2724
  };
2587
- const walkValue = (value, transferrables, isTransferrable) => {
2588
- if (!value) {
2589
- return;
2590
- }
2591
- if (isTransferrable(value)) {
2592
- transferrables.push(value);
2593
- return;
2725
+ const restoreExistingError = (error, currentStack) => {
2726
+ if (typeof error.stack === 'string') {
2727
+ setStack(error, `${error.stack}${NewLine$1}${currentStack}`);
2594
2728
  }
2595
- if (Array.isArray(value)) {
2596
- for (const item of value) {
2597
- walkValue(item, transferrables, isTransferrable);
2598
- }
2729
+ return error;
2730
+ };
2731
+ const restoreMethodNotFoundError = (error, currentStack) => {
2732
+ const restoredError = new JsonRpcError(error.message);
2733
+ const parentStack = getParentStack(error);
2734
+ setStack(restoredError, `${parentStack}${NewLine$1}${currentStack}`);
2735
+ return restoredError;
2736
+ };
2737
+ const restoreStackFromData = (restoredError, error, currentStack) => {
2738
+ if (error.data.stack && error.data.type && error.message) {
2739
+ setStack(restoredError, `${error.data.type}: ${error.message}${NewLine$1}${error.data.stack}${NewLine$1}${currentStack}`);
2599
2740
  return;
2600
2741
  }
2601
- if (typeof value === 'object') {
2602
- for (const property of Object.values(value)) {
2603
- walkValue(property, transferrables, isTransferrable);
2604
- }
2742
+ if (error.data.stack) {
2743
+ setStack(restoredError, error.data.stack);
2605
2744
  }
2606
2745
  };
2607
- const getTransferrables = value => {
2608
- const transferrables = [];
2609
- walkValue(value, transferrables, isTransferrable);
2610
- return transferrables;
2611
- };
2612
- const removeValues = (value, toRemove) => {
2613
- if (!value) {
2614
- return value;
2746
+ const applyDataProperties = (restoredError, error) => {
2747
+ restoreStackFromData(restoredError, error, getCurrentStack());
2748
+ if (error.data.codeFrame) {
2749
+ // @ts-ignore
2750
+ restoredError.codeFrame = error.data.codeFrame;
2615
2751
  }
2616
- if (Array.isArray(value)) {
2617
- const newItems = [];
2618
- for (const item of value) {
2619
- if (!toRemove.includes(item)) {
2620
- newItems.push(removeValues(item, toRemove));
2621
- }
2622
- }
2623
- return newItems;
2752
+ if (error.data.code) {
2753
+ // @ts-ignore
2754
+ restoredError.code = error.data.code;
2624
2755
  }
2625
- if (typeof value === 'object') {
2626
- const newObject = Object.create(null);
2627
- for (const [key, property] of Object.entries(value)) {
2628
- if (!toRemove.includes(property)) {
2629
- newObject[key] = removeValues(property, toRemove);
2630
- }
2631
- }
2632
- return newObject;
2756
+ if (error.data.type) {
2757
+ // @ts-ignore
2758
+ restoredError.name = error.data.type;
2633
2759
  }
2634
- return value;
2635
- };
2636
-
2637
- // workaround for electron not supporting transferrable objects
2638
- // as parameters. If the transferrable object is a parameter, in electron
2639
- // only an empty objected is received in the main process
2640
- const fixElectronParameters = value => {
2641
- const transfer = getTransferrables(value);
2642
- const newValue = removeValues(value, transfer);
2643
- return {
2644
- newValue,
2645
- transfer
2646
- };
2647
- };
2648
- const attachEvents$8 = that => {
2649
- const handleMessage = (...args) => {
2650
- const data = that.getData(...args);
2651
- that.dispatchEvent(new MessageEvent('message', {
2652
- data
2653
- }));
2654
- };
2655
- that.onMessage(handleMessage);
2656
- const handleClose = event => {
2657
- that.dispatchEvent(new Event('close'));
2658
- };
2659
- that.onClose(handleClose);
2660
2760
  };
2661
- class Ipc extends EventTarget {
2662
- constructor(rawIpc) {
2663
- super();
2664
- this._rawIpc = rawIpc;
2665
- attachEvents$8(this);
2761
+ const applyDirectProperties = (restoredError, error) => {
2762
+ if (error.stack) {
2763
+ const lowerStack = restoredError.stack || '';
2764
+ const indexNewLine = getNewLineIndex(lowerStack);
2765
+ const parentStack = getParentStack(error);
2766
+ // @ts-ignore
2767
+ setStack(restoredError, `${parentStack}${lowerStack.slice(indexNewLine)}`);
2768
+ }
2769
+ if (error.codeFrame) {
2770
+ // @ts-ignore
2771
+ restoredError.codeFrame = error.codeFrame;
2666
2772
  }
2667
- }
2668
- const E_INCOMPATIBLE_NATIVE_MODULE = 'E_INCOMPATIBLE_NATIVE_MODULE';
2669
- const E_MODULES_NOT_SUPPORTED_IN_ELECTRON = 'E_MODULES_NOT_SUPPORTED_IN_ELECTRON';
2670
- const ERR_MODULE_NOT_FOUND = 'ERR_MODULE_NOT_FOUND';
2671
- const NewLine$1 = '\n';
2672
- const joinLines$1 = lines => {
2673
- return lines.join(NewLine$1);
2674
2773
  };
2675
- const RE_AT$1 = /^\s+at/;
2676
- const RE_AT_PROMISE_INDEX$1 = /^\s*at async Promise.all \(index \d+\)$/;
2677
- const isNormalStackLine$1 = line => {
2678
- return RE_AT$1.test(line) && !RE_AT_PROMISE_INDEX$1.test(line);
2774
+ const restoreMessageError = (error, _currentStack) => {
2775
+ const restoredError = constructError(error.message, error.type, error.name);
2776
+ if (error.data) {
2777
+ applyDataProperties(restoredError, error);
2778
+ } else {
2779
+ applyDirectProperties(restoredError, error);
2780
+ }
2781
+ return restoredError;
2679
2782
  };
2680
- const getDetails$1 = lines => {
2681
- const index = lines.findIndex(isNormalStackLine$1);
2682
- if (index === -1) {
2683
- return {
2684
- actualMessage: joinLines$1(lines),
2685
- rest: []
2686
- };
2783
+ const restoreJsonRpcError = error => {
2784
+ const currentStack = getCurrentStack();
2785
+ if (error && error instanceof Error) {
2786
+ return restoreExistingError(error, currentStack);
2687
2787
  }
2688
- let lastIndex = index - 1;
2689
- while (++lastIndex < lines.length) {
2690
- if (!isNormalStackLine$1(lines[lastIndex])) {
2691
- break;
2692
- }
2788
+ if (error && error.code && error.code === MethodNotFound) {
2789
+ return restoreMethodNotFoundError(error, currentStack);
2693
2790
  }
2694
- return {
2695
- actualMessage: lines[index - 1],
2696
- rest: lines.slice(index, lastIndex)
2697
- };
2698
- };
2699
- const splitLines$1 = lines => {
2700
- return lines.split(NewLine$1);
2791
+ if (error && error.message) {
2792
+ return restoreMessageError(error);
2793
+ }
2794
+ if (typeof error === 'string') {
2795
+ return new Error(`JsonRpc Error: ${error}`);
2796
+ }
2797
+ return new Error(`JsonRpc Error: ${error}`);
2701
2798
  };
2702
- const RE_MESSAGE_CODE_BLOCK_START = /^Error: The module '.*'$/;
2703
- const RE_MESSAGE_CODE_BLOCK_END = /^\s* at/;
2704
- const isMessageCodeBlockStartIndex = line => {
2705
- return RE_MESSAGE_CODE_BLOCK_START.test(line);
2799
+ const unwrapJsonRpcResult = responseMessage => {
2800
+ if ('error' in responseMessage) {
2801
+ const restoredError = restoreJsonRpcError(responseMessage.error);
2802
+ throw restoredError;
2803
+ }
2804
+ if ('result' in responseMessage) {
2805
+ return responseMessage.result;
2806
+ }
2807
+ throw new JsonRpcError('unexpected response message');
2706
2808
  };
2707
- const isMessageCodeBlockEndIndex = line => {
2708
- return RE_MESSAGE_CODE_BLOCK_END.test(line);
2809
+ const warn = (...args) => {
2810
+ console.warn(...args);
2709
2811
  };
2710
- const getMessageCodeBlock = stderr => {
2711
- const lines = splitLines$1(stderr);
2712
- const startIndex = lines.findIndex(isMessageCodeBlockStartIndex);
2713
- const endIndex = startIndex + lines.slice(startIndex).findIndex(isMessageCodeBlockEndIndex, startIndex);
2714
- const relevantLines = lines.slice(startIndex, endIndex);
2715
- const relevantMessage = relevantLines.join(' ').slice('Error: '.length);
2716
- return relevantMessage;
2812
+ const resolve = (id, response) => {
2813
+ const fn = get$6(id);
2814
+ if (!fn) {
2815
+ console.log(response);
2816
+ warn(`callback ${id} may already be disposed`);
2817
+ return;
2818
+ }
2819
+ fn(response);
2820
+ remove$4(id);
2717
2821
  };
2718
- const isModuleNotFoundMessage = line => {
2719
- return line.includes('[ERR_MODULE_NOT_FOUND]');
2822
+ const E_COMMAND_NOT_FOUND = 'E_COMMAND_NOT_FOUND';
2823
+ const getErrorType = prettyError => {
2824
+ if (prettyError && prettyError.type) {
2825
+ return prettyError.type;
2826
+ }
2827
+ if (prettyError && prettyError.constructor && prettyError.constructor.name) {
2828
+ return prettyError.constructor.name;
2829
+ }
2830
+ return undefined;
2720
2831
  };
2721
- const getModuleNotFoundError = stderr => {
2722
- const lines = splitLines$1(stderr);
2723
- const messageIndex = lines.findIndex(isModuleNotFoundMessage);
2724
- const message = lines[messageIndex];
2725
- return {
2726
- code: ERR_MODULE_NOT_FOUND,
2727
- message
2728
- };
2832
+ const isAlreadyStack = line => {
2833
+ return line.trim().startsWith('at ');
2729
2834
  };
2730
- const isModuleNotFoundError = stderr => {
2731
- if (!stderr) {
2732
- return false;
2835
+ const getStack = prettyError => {
2836
+ const stackString = prettyError.stack || '';
2837
+ const newLineIndex = stackString.indexOf('\n');
2838
+ if (newLineIndex !== -1 && !isAlreadyStack(stackString.slice(0, newLineIndex))) {
2839
+ return stackString.slice(newLineIndex + 1);
2733
2840
  }
2734
- return stderr.includes('ERR_MODULE_NOT_FOUND');
2841
+ return stackString;
2735
2842
  };
2736
- const isModulesSyntaxError = stderr => {
2737
- if (!stderr) {
2738
- return false;
2843
+ const getErrorProperty = (error, prettyError) => {
2844
+ if (error && error.code === E_COMMAND_NOT_FOUND) {
2845
+ return {
2846
+ code: MethodNotFound,
2847
+ data: error.stack,
2848
+ message: error.message
2849
+ };
2739
2850
  }
2740
- return stderr.includes('SyntaxError: Cannot use import statement outside a module');
2741
- };
2742
- const RE_NATIVE_MODULE_ERROR = /^innerError Error: Cannot find module '.*.node'/;
2743
- const RE_NATIVE_MODULE_ERROR_2 = /was compiled against a different Node.js version/;
2744
- const isUnhelpfulNativeModuleError = stderr => {
2745
- return RE_NATIVE_MODULE_ERROR.test(stderr) && RE_NATIVE_MODULE_ERROR_2.test(stderr);
2746
- };
2747
- const getNativeModuleErrorMessage = stderr => {
2748
- const message = getMessageCodeBlock(stderr);
2749
2851
  return {
2750
- code: E_INCOMPATIBLE_NATIVE_MODULE,
2751
- message: `Incompatible native node module: ${message}`
2852
+ code: Custom,
2853
+ data: {
2854
+ code: prettyError.code,
2855
+ codeFrame: prettyError.codeFrame,
2856
+ name: prettyError.name,
2857
+ stack: getStack(prettyError),
2858
+ type: getErrorType(prettyError)
2859
+ },
2860
+ message: prettyError.message
2752
2861
  };
2753
2862
  };
2754
- const getModuleSyntaxError = () => {
2863
+ const create$1$1 = (id, error) => {
2755
2864
  return {
2756
- code: E_MODULES_NOT_SUPPORTED_IN_ELECTRON,
2757
- message: `ES Modules are not supported in electron`
2865
+ error,
2866
+ id,
2867
+ jsonrpc: Two$1
2758
2868
  };
2759
2869
  };
2760
- const getHelpfulChildProcessError = (stdout, stderr) => {
2761
- if (isUnhelpfulNativeModuleError(stderr)) {
2762
- return getNativeModuleErrorMessage(stderr);
2763
- }
2764
- if (isModulesSyntaxError(stderr)) {
2765
- return getModuleSyntaxError();
2766
- }
2767
- if (isModuleNotFoundError(stderr)) {
2768
- return getModuleNotFoundError(stderr);
2769
- }
2770
- const lines = splitLines$1(stderr);
2771
- const {
2772
- actualMessage,
2773
- rest
2774
- } = getDetails$1(lines);
2870
+ const getErrorResponse = (id, error, preparePrettyError, logError) => {
2871
+ const prettyError = preparePrettyError(error);
2872
+ logError(error, prettyError);
2873
+ const errorProperty = getErrorProperty(error, prettyError);
2874
+ return create$1$1(id, errorProperty);
2875
+ };
2876
+ const create$I = (message, result) => {
2775
2877
  return {
2776
- code: '',
2777
- message: actualMessage,
2778
- stack: rest
2878
+ id: message.id,
2879
+ jsonrpc: Two$1,
2880
+ result: result ?? null
2779
2881
  };
2780
2882
  };
2781
- class IpcError extends VError$1 {
2782
- // @ts-ignore
2783
- constructor(betterMessage, stdout = '', stderr = '') {
2784
- if (stdout || stderr) {
2785
- // @ts-ignore
2786
- const {
2787
- code,
2788
- message,
2789
- stack
2790
- } = getHelpfulChildProcessError(stdout, stderr);
2791
- const cause = new Error(message);
2883
+ const getSuccessResponse = (message, result) => {
2884
+ const resultProperty = result ?? null;
2885
+ return create$I(message, resultProperty);
2886
+ };
2887
+ const getErrorResponseSimple = (id, error) => {
2888
+ return {
2889
+ error: {
2890
+ code: Custom,
2891
+ data: error,
2792
2892
  // @ts-ignore
2793
- cause.code = code;
2794
- if (stack) {
2795
- Object.defineProperty(cause, 'stack', {
2796
- configurable: true,
2797
- enumerable: false,
2798
- value: stack,
2799
- writable: true
2800
- });
2801
- }
2802
- super(cause, betterMessage);
2803
- } else {
2804
- super(betterMessage);
2893
+ message: error.message
2894
+ },
2895
+ id,
2896
+ jsonrpc: Two$1
2897
+ };
2898
+ };
2899
+ const getResponse = async (message, ipc, execute, preparePrettyError, logError, requiresSocket) => {
2900
+ try {
2901
+ const result = requiresSocket(message.method) ? await execute(message.method, ipc, ...message.params) : await execute(message.method, ...message.params);
2902
+ return getSuccessResponse(message, result);
2903
+ } catch (error) {
2904
+ if (ipc.canUseSimpleErrorResponse) {
2905
+ return getErrorResponseSimple(message.id, error);
2805
2906
  }
2806
- // @ts-ignore
2807
- this.name = 'IpcError';
2808
- // @ts-ignore
2809
- this.stdout = stdout;
2810
- // @ts-ignore
2811
- this.stderr = stderr;
2907
+ return getErrorResponse(message.id, error, preparePrettyError, logError);
2812
2908
  }
2813
- }
2814
- const readyMessage = 'ready';
2815
- const getData$2 = event => {
2816
- return event.data;
2817
2909
  };
2818
- const listen$9 = () => {
2819
- return globalThis;
2910
+ const defaultPreparePrettyError = error => {
2911
+ return error;
2820
2912
  };
2821
- const signal$a = global => {
2822
- global.postMessage(readyMessage);
2913
+ const defaultLogError = () => {
2914
+ // ignore
2823
2915
  };
2824
- class IpcChildWithElectronWindow extends Ipc {
2825
- getData(event) {
2826
- return getData$2(event);
2827
- }
2828
- send(message) {
2829
- this._rawIpc.postMessage(message);
2830
- }
2831
- sendAndTransfer(message) {
2832
- const {
2833
- newValue,
2834
- transfer
2835
- } = fixElectronParameters(message);
2836
- this._rawIpc.postMessage(newValue, location.origin, transfer);
2837
- }
2838
- dispose() {
2839
- // ignore
2840
- }
2841
- onClose(callback) {
2842
- // ignore
2843
- }
2844
- onMessage(callback) {
2845
- const wrapped = event => {
2846
- const {
2847
- ports
2848
- } = event;
2849
- if (ports.length > 0) {
2850
- return;
2851
- }
2852
- callback(event);
2853
- this._rawIpc.removeEventListener('message', wrapped);
2916
+ const defaultRequiresSocket = () => {
2917
+ return false;
2918
+ };
2919
+ const defaultResolve = resolve;
2920
+
2921
+ // TODO maybe remove this in v6 or v7, only accept options object to simplify the code
2922
+ const normalizeParams = args => {
2923
+ if (args.length === 1) {
2924
+ const options = args[0];
2925
+ return {
2926
+ execute: options.execute,
2927
+ ipc: options.ipc,
2928
+ logError: options.logError || defaultLogError,
2929
+ message: options.message,
2930
+ preparePrettyError: options.preparePrettyError || defaultPreparePrettyError,
2931
+ requiresSocket: options.requiresSocket || defaultRequiresSocket,
2932
+ resolve: options.resolve || defaultResolve
2854
2933
  };
2855
- this._rawIpc.addEventListener('message', wrapped);
2856
2934
  }
2857
- }
2858
- const wrap$h = window => {
2859
- return new IpcChildWithElectronWindow(window);
2935
+ return {
2936
+ execute: args[2],
2937
+ ipc: args[0],
2938
+ logError: args[5],
2939
+ message: args[1],
2940
+ preparePrettyError: args[4],
2941
+ requiresSocket: args[6],
2942
+ resolve: args[3]
2943
+ };
2860
2944
  };
2861
- const IpcChildWithElectronWindow$1 = {
2862
- __proto__: null,
2863
- listen: listen$9,
2864
- signal: signal$a,
2865
- wrap: wrap$h
2866
- };
2867
- const addListener = (emitter, type, callback) => {
2868
- if ('addEventListener' in emitter) {
2869
- emitter.addEventListener(type, callback);
2870
- } else {
2871
- emitter.on(type, callback);
2945
+ const handleJsonRpcMessage = async (...args) => {
2946
+ const options = normalizeParams(args);
2947
+ const {
2948
+ execute,
2949
+ ipc,
2950
+ logError,
2951
+ message,
2952
+ preparePrettyError,
2953
+ requiresSocket,
2954
+ resolve
2955
+ } = options;
2956
+ if ('id' in message) {
2957
+ if ('method' in message) {
2958
+ const response = await getResponse(message, ipc, execute, preparePrettyError, logError, requiresSocket);
2959
+ try {
2960
+ ipc.send(response);
2961
+ } catch (error) {
2962
+ const errorResponse = getErrorResponse(message.id, error, preparePrettyError, logError);
2963
+ ipc.send(errorResponse);
2964
+ }
2965
+ return;
2966
+ }
2967
+ resolve(message.id, message);
2968
+ return;
2872
2969
  }
2873
- };
2874
- const removeListener = (emitter, type, callback) => {
2875
- if ('removeEventListener' in emitter) {
2876
- emitter.removeEventListener(type, callback);
2877
- } else {
2878
- emitter.off(type, callback);
2970
+ if ('method' in message) {
2971
+ await getResponse(message, ipc, execute, preparePrettyError, logError, requiresSocket);
2972
+ return;
2879
2973
  }
2974
+ throw new JsonRpcError('unexpected message');
2975
+ };
2976
+
2977
+ const Two = '2.0';
2978
+
2979
+ const create$H = (method, params) => {
2980
+ return {
2981
+ jsonrpc: Two,
2982
+ method,
2983
+ params
2984
+ };
2985
+ };
2986
+
2987
+ const create$G = (id, method, params) => {
2988
+ const message = {
2989
+ id,
2990
+ jsonrpc: Two,
2991
+ method,
2992
+ params
2993
+ };
2994
+ return message;
2995
+ };
2996
+
2997
+ let id = 0;
2998
+ const create$F = () => {
2999
+ return ++id;
2880
3000
  };
2881
- const getFirstEvent = (eventEmitter, eventMap) => {
3001
+
3002
+ const registerPromise = map => {
3003
+ const id = create$F();
2882
3004
  const {
2883
3005
  promise,
2884
3006
  resolve
2885
3007
  } = Promise.withResolvers();
2886
- const listenerMap = Object.create(null);
2887
- const cleanup = value => {
2888
- for (const event of Object.keys(eventMap)) {
2889
- removeListener(eventEmitter, event, listenerMap[event]);
2890
- }
2891
- resolve(value);
3008
+ map[id] = resolve;
3009
+ return {
3010
+ id,
3011
+ promise
2892
3012
  };
2893
- for (const [event, type] of Object.entries(eventMap)) {
2894
- const listener = event => {
2895
- cleanup({
2896
- event,
2897
- type
2898
- });
2899
- };
2900
- addListener(eventEmitter, event, listener);
2901
- listenerMap[event] = listener;
2902
- }
2903
- return promise;
2904
3013
  };
2905
- const Message$1 = 3;
2906
- const create$5$1 = async ({
2907
- isMessagePortOpen,
2908
- messagePort
2909
- }) => {
2910
- if (!isMessagePort(messagePort)) {
2911
- throw new IpcError('port must be of type MessagePort');
2912
- }
2913
- if (isMessagePortOpen) {
2914
- return messagePort;
2915
- }
2916
- const eventPromise = getFirstEvent(messagePort, {
2917
- message: Message$1
2918
- });
2919
- messagePort.start();
3014
+
3015
+ const invokeHelper = async (callbacks, ipc, method, params, useSendAndTransfer) => {
2920
3016
  const {
2921
- event,
2922
- type
2923
- } = await eventPromise;
2924
- if (type !== Message$1) {
2925
- throw new IpcError('Failed to wait for ipc message');
2926
- }
2927
- if (event.data !== readyMessage) {
2928
- throw new IpcError('unexpected first message');
3017
+ id,
3018
+ promise
3019
+ } = registerPromise(callbacks);
3020
+ const message = create$G(id, method, params);
3021
+ if (useSendAndTransfer && ipc.sendAndTransfer) {
3022
+ ipc.sendAndTransfer(message);
3023
+ } else {
3024
+ ipc.send(message);
2929
3025
  }
2930
- return messagePort;
3026
+ const responseMessage = await promise;
3027
+ return unwrapJsonRpcResult(responseMessage);
2931
3028
  };
2932
- const signal$1 = messagePort => {
2933
- messagePort.start();
3029
+ const createRpc = ipc => {
3030
+ const callbacks = Object.create(null);
3031
+ ipc._resolve = (id, response) => {
3032
+ const fn = callbacks[id];
3033
+ if (!fn) {
3034
+ console.warn(`callback ${id} may already be disposed`);
3035
+ return;
3036
+ }
3037
+ fn(response);
3038
+ delete callbacks[id];
3039
+ };
3040
+ const rpc = {
3041
+ async dispose() {
3042
+ await ipc?.dispose();
3043
+ },
3044
+ invoke(method, ...params) {
3045
+ return invokeHelper(callbacks, ipc, method, params, false);
3046
+ },
3047
+ invokeAndTransfer(method, ...params) {
3048
+ return invokeHelper(callbacks, ipc, method, params, true);
3049
+ },
3050
+ // @ts-ignore
3051
+ ipc,
3052
+ /**
3053
+ * @deprecated
3054
+ */
3055
+ send(method, ...params) {
3056
+ const message = create$H(method, params);
3057
+ ipc.send(message);
3058
+ }
3059
+ };
3060
+ return rpc;
2934
3061
  };
2935
- class IpcParentWithMessagePort extends Ipc {
2936
- getData = getData$2;
2937
- send(message) {
2938
- this._rawIpc.postMessage(message);
2939
- }
2940
- sendAndTransfer(message) {
2941
- const transfer = getTransferrables(message);
2942
- this._rawIpc.postMessage(message, transfer);
2943
- }
2944
- dispose() {
2945
- this._rawIpc.close();
2946
- }
2947
- onMessage(callback) {
2948
- this._rawIpc.addEventListener('message', callback);
2949
- }
2950
- onClose(callback) {}
2951
- }
2952
- const wrap$5 = messagePort => {
2953
- return new IpcParentWithMessagePort(messagePort);
3062
+
3063
+ const requiresSocket = () => {
3064
+ return false;
2954
3065
  };
2955
- const IpcParentWithMessagePort$1 = {
2956
- __proto__: null,
2957
- create: create$5$1,
2958
- signal: signal$1,
2959
- wrap: wrap$5
3066
+ const preparePrettyError = error => {
3067
+ return error;
2960
3068
  };
2961
- const Message = 'message';
2962
- const Error$1$1 = 'error';
2963
- const getFirstWorkerEvent = worker => {
2964
- return getFirstEvent(worker, {
2965
- error: Error$1$1,
2966
- message: Message
2967
- });
3069
+ const logError$1 = () => {
3070
+ // handled by renderer worker
2968
3071
  };
2969
- const isErrorEvent = event => {
2970
- return event instanceof ErrorEvent;
3072
+ const handleMessage = event => {
3073
+ const actualRequiresSocket = event?.target?.requiresSocket || requiresSocket;
3074
+ const actualExecute = event?.target?.execute || execute;
3075
+ return handleJsonRpcMessage(event.target, event.data, actualExecute, event.target._resolve, preparePrettyError, logError$1, actualRequiresSocket);
2971
3076
  };
2972
- const getWorkerDisplayName = name => {
2973
- if (!name) {
2974
- return '<unknown> worker';
3077
+
3078
+ const handleIpc = ipc => {
3079
+ if ('addEventListener' in ipc) {
3080
+ ipc.addEventListener('message', handleMessage);
3081
+ } else if ('on' in ipc) {
3082
+ // deprecated
3083
+ ipc.on('message', handleMessage);
2975
3084
  }
2976
- if (name.endsWith('Worker') || name.endsWith('worker')) {
2977
- return name.toLowerCase();
3085
+ };
3086
+ const unhandleIpc = ipc => {
3087
+ if ('removeEventListener' in ipc) {
3088
+ ipc.removeEventListener('message', handleMessage);
3089
+ } else {
3090
+ // deprecated
3091
+ ipc.onmessage = null;
2978
3092
  }
2979
- return `${name} Worker`;
2980
3093
  };
2981
- const tryToGetActualErrorMessage = async ({
2982
- name
3094
+
3095
+ const create$E = async ({
3096
+ commandMap,
3097
+ window
2983
3098
  }) => {
2984
- const displayName = getWorkerDisplayName(name);
2985
- return `Failed to start ${displayName}: Worker Launch Error`;
3099
+ // TODO create a commandMap per rpc instance
3100
+ register(commandMap);
3101
+ const ipc = IpcChildWithElectronWindow$1.wrap(window);
3102
+ handleIpc(ipc);
3103
+ const rpc = createRpc(ipc);
3104
+ return rpc;
2986
3105
  };
2987
- class WorkerError extends Error {
2988
- constructor(event) {
2989
- super(event.message);
2990
- const stackLines = splitLines$1(this.stack || '');
2991
- const relevantLines = stackLines.slice(1);
2992
- const relevant = joinLines$1(relevantLines);
2993
- this.stack = `${event.message}
2994
- at Module (${event.filename}:${event.lineno}:${event.colno})
2995
- ${relevant}`;
2996
- }
2997
- }
2998
- const Module = 'module';
2999
- const create$4$1 = async ({
3106
+
3107
+ const create$D = async ({
3108
+ commandMap,
3109
+ isMessagePortOpen = true,
3110
+ messagePort
3111
+ }) => {
3112
+ // TODO create a commandMap per rpc instance
3113
+ register(commandMap);
3114
+ const rawIpc = await IpcParentWithMessagePort$1$1.create({
3115
+ isMessagePortOpen,
3116
+ messagePort
3117
+ });
3118
+ const ipc = IpcParentWithMessagePort$1$1.wrap(rawIpc);
3119
+ handleIpc(ipc);
3120
+ const rpc = createRpc(ipc);
3121
+ messagePort.start();
3122
+ return rpc;
3123
+ };
3124
+
3125
+ const isWorker = value => {
3126
+ return value instanceof Worker;
3127
+ };
3128
+
3129
+ const create$C = async ({
3130
+ commandMap,
3000
3131
  name,
3001
3132
  url
3002
3133
  }) => {
3003
- const worker = new Worker(url, {
3134
+ // TODO create a commandMap per rpc instance
3135
+ register(commandMap);
3136
+ const worker = await IpcParentWithModuleWorker$1$1.create({
3004
3137
  name,
3005
- type: Module
3138
+ url
3006
3139
  });
3007
- const {
3008
- event,
3009
- type
3010
- } = await getFirstWorkerEvent(worker);
3011
- switch (type) {
3012
- case Message:
3013
- if (event.data !== readyMessage) {
3014
- throw new IpcError('unexpected first message from worker');
3015
- }
3016
- break;
3017
- case Error$1$1:
3018
- if (isErrorEvent(event)) {
3019
- throw new WorkerError(event);
3020
- }
3021
- const actualErrorMessage = await tryToGetActualErrorMessage({
3022
- name
3023
- });
3024
- throw new Error(actualErrorMessage);
3140
+ if (!isWorker(worker)) {
3141
+ throw new Error(`worker must be of type Worker`);
3025
3142
  }
3026
- return worker;
3143
+ const ipc = IpcParentWithModuleWorker$1$1.wrap(worker);
3144
+ handleIpc(ipc);
3145
+ const workerRpc = createRpc(ipc);
3146
+ return workerRpc;
3027
3147
  };
3028
- const getData = event => {
3029
- // TODO why are some events not instance of message event?
3030
- if (event instanceof MessageEvent) {
3031
- return event.data;
3148
+
3149
+ const create$B = async ({
3150
+ commandMap,
3151
+ name,
3152
+ port,
3153
+ url
3154
+ }) => {
3155
+ // TODO create a commandMap per rpc instance
3156
+ register(commandMap);
3157
+ const worker = await IpcParentWithModuleWorker$1$1.create({
3158
+ name,
3159
+ url
3160
+ });
3161
+ if (!isWorker(worker)) {
3162
+ throw new Error(`worker must be of type Worker`);
3032
3163
  }
3033
- return event;
3164
+ const ipc = IpcParentWithModuleWorker$1$1.wrap(worker);
3165
+ handleIpc(ipc);
3166
+ const workerRpc = createRpc(ipc);
3167
+ await workerRpc.invokeAndTransfer('initialize', 'message-port', port);
3168
+ unhandleIpc(ipc);
3169
+ return workerRpc;
3034
3170
  };
3035
- class IpcParentWithModuleWorker extends Ipc {
3036
- getData(event) {
3037
- return getData(event);
3171
+
3172
+ const create$A = async ({
3173
+ commandMap,
3174
+ messagePort
3175
+ }) => {
3176
+ return create$D({
3177
+ commandMap,
3178
+ messagePort
3179
+ });
3180
+ };
3181
+
3182
+ const commandMapRef = {};
3183
+
3184
+ const Web = 1;
3185
+ const Electron$1 = 2;
3186
+ const Remote = 3;
3187
+
3188
+ /**
3189
+ * @returns {number}
3190
+ */
3191
+ const getPlatform = () => {
3192
+ // @ts-expect-error
3193
+ if (typeof PLATFORM !== 'undefined') {
3194
+ // @ts-expect-error
3195
+ return PLATFORM;
3038
3196
  }
3039
- send(message) {
3040
- this._rawIpc.postMessage(message);
3197
+ // @ts-ignore
3198
+ if (typeof process !== 'undefined' && process.env.NODE_ENV === 'test') {
3199
+ return Remote;
3041
3200
  }
3042
- sendAndTransfer(message) {
3043
- const transfer = getTransferrables(message);
3044
- this._rawIpc.postMessage(message, transfer);
3201
+ if (globalThis.isElectron) {
3202
+ return Electron$1;
3045
3203
  }
3046
- dispose() {
3047
- // ignore
3204
+ if (typeof location !== 'undefined' && location.search === '?web') {
3205
+ return Web;
3048
3206
  }
3049
- onClose(callback) {
3050
- // ignore
3207
+ return Remote;
3208
+ };
3209
+ const platform = getPlatform();
3210
+
3211
+ const getAssetDir = () => {
3212
+ // @ts-expect-error
3213
+ if (typeof ASSET_DIR !== 'undefined') {
3214
+ // @ts-expect-error
3215
+ return ASSET_DIR;
3051
3216
  }
3052
- onMessage(callback) {
3053
- this._rawIpc.addEventListener('message', callback);
3217
+ if (platform === Electron$1) {
3218
+ return '../../../../..';
3054
3219
  }
3055
- }
3056
- const wrap$4 = worker => {
3057
- return new IpcParentWithModuleWorker(worker);
3058
- };
3059
- const IpcParentWithModuleWorker$1 = {
3060
- __proto__: null,
3061
- create: create$4$1,
3062
- wrap: wrap$4
3220
+ return '';
3063
3221
  };
3222
+ const assetDir = getAssetDir();
3064
3223
 
3065
- class CommandNotFoundError extends Error {
3066
- constructor(command) {
3067
- super(`Command not found ${command}`);
3068
- this.name = 'CommandNotFoundError';
3224
+ const getConfiguredWorkerUrl = key => {
3225
+ if (typeof location === 'undefined' || typeof document === 'undefined') {
3226
+ return '';
3069
3227
  }
3070
- }
3071
- const commands = Object.create(null);
3072
- const register = commandMap => {
3073
- Object.assign(commands, commandMap);
3074
- };
3075
- const getCommand = key => {
3076
- return commands[key];
3077
- };
3078
- const execute = (command, ...args) => {
3079
- const fn = getCommand(command);
3080
- if (!fn) {
3081
- throw new CommandNotFoundError(command);
3228
+ const configElement = document.getElementById('Config');
3229
+ if (!configElement) {
3230
+ return '';
3082
3231
  }
3083
- return fn(...args);
3232
+ const text = configElement.textContent;
3233
+ if (!text) {
3234
+ return '';
3235
+ }
3236
+ const config = JSON.parse(text);
3237
+ return config[key] || '';
3084
3238
  };
3085
3239
 
3086
- const Two$1 = '2.0';
3087
- const callbacks = Object.create(null);
3088
- const get$4 = id => {
3089
- return callbacks[id];
3240
+ const getConfiguredDragAndDropWorkerUrl = () => {
3241
+ const workerUrls = getConfiguredWorkerUrl('workerUrls');
3242
+ return workerUrls?.['develop.dragAndDropWorkerPath'] || '';
3090
3243
  };
3091
- const remove$4 = id => {
3092
- delete callbacks[id];
3244
+
3245
+ const dragAndDropWorkerUrl = getConfiguredDragAndDropWorkerUrl() || `${assetDir}/packages/renderer-worker/node_modules/@lvce-editor/drag-and-drop-worker/dist/dragAndDropWorkerMain.js`;
3246
+
3247
+ const success = value => {
3248
+ return {
3249
+ ok: true,
3250
+ value
3251
+ };
3093
3252
  };
3094
- class JsonRpcError extends Error {
3095
- constructor(message) {
3096
- super(message);
3097
- this.name = 'JsonRpcError';
3253
+ const error = error => {
3254
+ return {
3255
+ error,
3256
+ ok: false
3257
+ };
3258
+ };
3259
+ const isError = result => {
3260
+ return !result.ok;
3261
+ };
3262
+
3263
+ const launchDragAndDropWorker = async () => {
3264
+ try {
3265
+ const {
3266
+ port1,
3267
+ port2
3268
+ } = new MessageChannel();
3269
+ await create$B({
3270
+ commandMap: {},
3271
+ name: 'Drag And Drop Worker',
3272
+ port: port1,
3273
+ url: dragAndDropWorkerUrl
3274
+ });
3275
+ const rpc = await create$D({
3276
+ commandMap: commandMapRef,
3277
+ messagePort: port2
3278
+ });
3279
+ return success(rpc);
3280
+ } catch (error$1) {
3281
+ return error(error$1);
3098
3282
  }
3099
- }
3100
- const NewLine = '\n';
3101
- const DomException = 'DOMException';
3102
- const ReferenceError$1 = 'ReferenceError';
3103
- const SyntaxError$1 = 'SyntaxError';
3104
- const TypeError$1 = 'TypeError';
3105
- const getErrorConstructor = (message, type) => {
3106
- if (type) {
3107
- switch (type) {
3108
- case DomException:
3109
- return DOMException;
3110
- case ReferenceError$1:
3111
- return ReferenceError;
3112
- case SyntaxError$1:
3113
- return SyntaxError;
3114
- case TypeError$1:
3115
- return TypeError;
3116
- default:
3117
- return Error;
3118
- }
3283
+ };
3284
+
3285
+ const state$b = {
3286
+ rpc: undefined
3287
+ };
3288
+ const hydrate$4 = async () => {
3289
+ const result = await launchDragAndDropWorker();
3290
+ if (isError(result)) {
3291
+ state$b.rpc = undefined;
3292
+ return result;
3119
3293
  }
3120
- if (message.startsWith('TypeError: ')) {
3121
- return TypeError;
3294
+ state$b.rpc = result.value;
3295
+ return success(undefined);
3296
+ };
3297
+ const handleMessagePort$1 = async port => {
3298
+ if (!state$b.rpc) {
3299
+ throw new Error('Drag And Drop Worker is not initialized');
3122
3300
  }
3123
- if (message.startsWith('SyntaxError: ')) {
3124
- return SyntaxError;
3301
+ await state$b.rpc.invokeAndTransfer('DragAndDrop.handleMessagePort', port);
3302
+ };
3303
+
3304
+ const downloadFile = (fileName, url) => {
3305
+ const a = document.createElement('a');
3306
+ a.href = url;
3307
+ a.download = fileName;
3308
+ a.click();
3309
+ };
3310
+
3311
+ const isFile = value => {
3312
+ return value instanceof File;
3313
+ };
3314
+
3315
+ const getFilePathElectron = async file => {
3316
+ if (!isFile(file)) {
3317
+ throw new TypeError(`file must be of type File`);
3125
3318
  }
3126
- if (message.startsWith('ReferenceError: ')) {
3127
- return ReferenceError;
3319
+ if (!globalThis.electronGlobals) {
3320
+ throw new Error(`electron globals are not available`);
3128
3321
  }
3129
- return Error;
3322
+ const filePath = globalThis.electronGlobals.getPathForFile(file);
3323
+ return filePath;
3130
3324
  };
3131
- const constructError = (message, type, name) => {
3132
- const ErrorConstructor = getErrorConstructor(message, type);
3133
- if (ErrorConstructor === DOMException && name) {
3134
- return new ErrorConstructor(message, name);
3325
+
3326
+ const validFormats = new Set(['file', 'fileSystemHandle', 'string']);
3327
+ const validateOptions = options => {
3328
+ if (!options || !Array.isArray(options.formats) || typeof options.includeElectronFilePaths !== 'boolean') {
3329
+ throw new TypeError('Invalid drop data options');
3135
3330
  }
3136
- if (ErrorConstructor === Error) {
3137
- const error = new Error(message);
3138
- if (name && name !== 'VError') {
3139
- Object.defineProperty(error, 'name', {
3140
- configurable: true,
3141
- value: name
3142
- });
3331
+ for (const format of options.formats) {
3332
+ if (!validFormats.has(format)) {
3333
+ throw new TypeError(`Invalid drop data format: ${format}`);
3143
3334
  }
3144
- return error;
3145
3335
  }
3146
- return new ErrorConstructor(message);
3147
3336
  };
3148
- const joinLines = lines => {
3149
- return lines.join(NewLine);
3150
- };
3151
- const splitLines = lines => {
3152
- return lines.split(NewLine);
3153
- };
3154
- const getCurrentStack = () => {
3155
- const stackLinesToSkip = 3;
3156
- const currentStack = joinLines(splitLines(new Error().stack || '').slice(stackLinesToSkip));
3157
- return currentStack;
3158
- };
3159
- const getNewLineIndex = (string, startIndex) => {
3160
- {
3161
- return string.indexOf(NewLine);
3162
- }
3337
+ const resolveString = async item => {
3338
+ return {
3339
+ index: item.index,
3340
+ kind: 'string',
3341
+ type: item.type,
3342
+ value: await item.value
3343
+ };
3163
3344
  };
3164
- const getParentStack = error => {
3165
- let parentStack = error.stack || error.data || error.message || '';
3166
- if (parentStack.startsWith(' at')) {
3167
- parentStack = error.message + NewLine + parentStack;
3345
+ const resolveFile = async (item, formats, includeElectronFilePaths) => {
3346
+ const includeFile = formats.has('file');
3347
+ const includeFileSystemHandle = formats.has('fileSystemHandle');
3348
+ const fileSystemHandle = includeFileSystemHandle ? await item.fileSystemHandle : undefined;
3349
+ const electronFilePath = includeElectronFilePaths && globalThis.electronGlobals && item.file ? await getFilePathElectron(item.file) : undefined;
3350
+ if ((!includeFile || !item.file) && !fileSystemHandle && electronFilePath === undefined) {
3351
+ return undefined;
3168
3352
  }
3169
- return parentStack;
3353
+ return {
3354
+ ...(electronFilePath !== undefined && {
3355
+ electronFilePath
3356
+ }),
3357
+ ...(includeFile && item.file && {
3358
+ file: item.file
3359
+ }),
3360
+ ...(fileSystemHandle && {
3361
+ fileSystemHandle
3362
+ }),
3363
+ index: item.index,
3364
+ kind: 'file',
3365
+ name: fileSystemHandle?.name || item.file?.name || '',
3366
+ type: item.type
3367
+ };
3170
3368
  };
3171
- const MethodNotFound = -32601;
3172
- const Custom = -32001;
3173
- const setStack = (error, stack) => {
3174
- const descriptor = Object.getOwnPropertyDescriptor(error, 'stack');
3175
- if (descriptor) {
3176
- if (!descriptor.configurable && !descriptor.writable) {
3177
- return;
3369
+ const get$5 = async (dropId, options) => {
3370
+ validateOptions(options);
3371
+ const retainedItems = acquire$2(dropId);
3372
+ const formats = new Set(options.formats);
3373
+ const items = [];
3374
+ for (const retainedItem of retainedItems) {
3375
+ if (retainedItem.kind === 'string') {
3376
+ if (formats.has('string')) {
3377
+ items.push(await resolveString(retainedItem));
3378
+ }
3379
+ continue;
3178
3380
  }
3179
- if (!descriptor.configurable && descriptor.writable) {
3180
- error.stack = stack;
3181
- return;
3381
+ const item = await resolveFile(retainedItem, formats, options.includeElectronFilePaths);
3382
+ if (item) {
3383
+ items.push(item);
3182
3384
  }
3183
3385
  }
3184
- Object.defineProperty(error, 'stack', {
3185
- configurable: true,
3186
- value: stack,
3187
- writable: true
3188
- });
3189
- };
3190
- const restoreExistingError = (error, currentStack) => {
3191
- if (typeof error.stack === 'string') {
3192
- setStack(error, `${error.stack}${NewLine}${currentStack}`);
3193
- }
3194
- return error;
3195
- };
3196
- const restoreMethodNotFoundError = (error, currentStack) => {
3197
- const restoredError = new JsonRpcError(error.message);
3198
- const parentStack = getParentStack(error);
3199
- setStack(restoredError, `${parentStack}${NewLine}${currentStack}`);
3200
- return restoredError;
3386
+ return items;
3201
3387
  };
3202
- const restoreStackFromData = (restoredError, error, currentStack) => {
3203
- if (error.data.stack && error.data.type && error.message) {
3204
- setStack(restoredError, `${error.data.type}: ${error.message}${NewLine}${error.data.stack}${NewLine}${currentStack}`);
3205
- return;
3206
- }
3207
- if (error.data.stack) {
3208
- setStack(restoredError, error.data.stack);
3388
+
3389
+ const isFileSystemFileHandle = value => {
3390
+ if (!value || typeof value !== 'object') {
3391
+ return false;
3209
3392
  }
3393
+ const candidate = value;
3394
+ return candidate.kind === 'file' && typeof candidate.getFile === 'function';
3210
3395
  };
3211
- const applyDataProperties = (restoredError, error) => {
3212
- restoreStackFromData(restoredError, error, getCurrentStack());
3213
- if (error.data.codeFrame) {
3214
- // @ts-ignore
3215
- restoredError.codeFrame = error.data.codeFrame;
3396
+ const getNativeFile = async item => {
3397
+ if (item.kind === 'file-legacy') {
3398
+ return item.value instanceof File ? item.value : undefined;
3216
3399
  }
3217
- if (error.data.code) {
3218
- // @ts-ignore
3219
- restoredError.code = error.data.code;
3400
+ if (item.file instanceof File) {
3401
+ return item.file;
3220
3402
  }
3221
- if (error.data.type) {
3222
- // @ts-ignore
3223
- restoredError.name = error.data.type;
3403
+ if (isFileSystemFileHandle(item.value)) {
3404
+ return item.value.getFile();
3224
3405
  }
3406
+ return undefined;
3225
3407
  };
3226
- const applyDirectProperties = (restoredError, error) => {
3227
- if (error.stack) {
3228
- const lowerStack = restoredError.stack || '';
3229
- const indexNewLine = getNewLineIndex(lowerStack);
3230
- const parentStack = getParentStack(error);
3231
- // @ts-ignore
3232
- setStack(restoredError, `${parentStack}${lowerStack.slice(indexNewLine)}`);
3408
+ const addElectronPath = async item => {
3409
+ if (!globalThis.electronGlobals) {
3410
+ return item;
3233
3411
  }
3234
- if (error.codeFrame) {
3235
- // @ts-ignore
3236
- restoredError.codeFrame = error.codeFrame;
3412
+ const file = await getNativeFile(item);
3413
+ if (!file) {
3414
+ return item;
3237
3415
  }
3416
+ const path = await getFilePathElectron(file);
3417
+ return {
3418
+ ...item,
3419
+ path
3420
+ };
3238
3421
  };
3239
- const restoreMessageError = (error, _currentStack) => {
3240
- const restoredError = constructError(error.message, error.type, error.name);
3241
- if (error.data) {
3242
- applyDataProperties(restoredError, error);
3243
- } else {
3244
- applyDirectProperties(restoredError, error);
3245
- }
3246
- return restoredError;
3422
+ const get$4 = async ids => {
3423
+ const items = await getFileHandles$1(ids);
3424
+ return Promise.all(items.map(addElectronPath));
3247
3425
  };
3248
- const restoreJsonRpcError = error => {
3249
- const currentStack = getCurrentStack();
3250
- if (error && error instanceof Error) {
3251
- return restoreExistingError(error, currentStack);
3252
- }
3253
- if (error && error.code && error.code === MethodNotFound) {
3254
- return restoreMethodNotFoundError(error, currentStack);
3255
- }
3256
- if (error && error.message) {
3257
- return restoreMessageError(error);
3258
- }
3259
- if (typeof error === 'string') {
3260
- return new Error(`JsonRpc Error: ${error}`);
3261
- }
3262
- return new Error(`JsonRpc Error: ${error}`);
3426
+
3427
+ const showDirectoryPicker = options => {
3428
+ // @ts-expect-error
3429
+ return window.showDirectoryPicker(options);
3263
3430
  };
3264
- const unwrapJsonRpcResult = responseMessage => {
3265
- if ('error' in responseMessage) {
3266
- const restoredError = restoreJsonRpcError(responseMessage.error);
3267
- throw restoredError;
3431
+ const showFilePicker = options => {
3432
+ // @ts-expect-error
3433
+ return window.showOpenFilePicker(options);
3434
+ };
3435
+ const showSaveFilePicker = options => {
3436
+ // @ts-expect-error
3437
+ return window.showSaveFilePicker(options);
3438
+ };
3439
+
3440
+ const launchWorker = async ({
3441
+ name,
3442
+ url
3443
+ }) => {
3444
+ try {
3445
+ const rpc = await create$C({
3446
+ commandMap: commandMapRef,
3447
+ name,
3448
+ url
3449
+ });
3450
+ return success(rpc);
3451
+ } catch (error$1) {
3452
+ return error(error$1);
3268
3453
  }
3269
- if ('result' in responseMessage) {
3270
- return responseMessage.result;
3454
+ };
3455
+
3456
+ const getConfiguredRendererWorkerUrl = () => {
3457
+ return getConfiguredWorkerUrl('rendererWorkerUrl');
3458
+ };
3459
+
3460
+ const rendererWorkerUrl = getConfiguredRendererWorkerUrl() || `${assetDir}/packages/renderer-worker/src/rendererWorkerMain.ts`;
3461
+
3462
+ const getName = platform => {
3463
+ switch (platform) {
3464
+ case Electron$1:
3465
+ return 'Renderer Worker (Electron)';
3466
+ case Web:
3467
+ return 'Renderer Worker (Web)';
3468
+ default:
3469
+ return 'Renderer Worker';
3271
3470
  }
3272
- throw new JsonRpcError('unexpected response message');
3273
3471
  };
3274
- const warn = (...args) => {
3275
- console.warn(...args);
3472
+ const launchRendererWorker = async () => {
3473
+ const name = getName(platform);
3474
+ return launchWorker({
3475
+ name,
3476
+ url: rendererWorkerUrl
3477
+ });
3276
3478
  };
3277
- const resolve = (id, response) => {
3278
- const fn = get$4(id);
3279
- if (!fn) {
3280
- console.log(response);
3281
- warn(`callback ${id} may already be disposed`);
3479
+
3480
+ const selector = 'script.RendererWorkerTrace';
3481
+ const state$a = {
3482
+ enabled: false,
3483
+ entries: []
3484
+ };
3485
+ const serialize = value => {
3486
+ const seen = new WeakSet();
3487
+ const text = JSON.stringify(value, (_key, currentValue) => {
3488
+ if (typeof currentValue === 'bigint') {
3489
+ return `${currentValue}n`;
3490
+ }
3491
+ if (typeof currentValue !== 'object' || currentValue === null) {
3492
+ return currentValue;
3493
+ }
3494
+ if (seen.has(currentValue)) {
3495
+ return '[Circular]';
3496
+ }
3497
+ seen.add(currentValue);
3498
+ if (currentValue instanceof ArrayBuffer) {
3499
+ return {
3500
+ byteLength: currentValue.byteLength,
3501
+ type: 'ArrayBuffer'
3502
+ };
3503
+ }
3504
+ if (ArrayBuffer.isView(currentValue)) {
3505
+ return {
3506
+ byteLength: currentValue.byteLength,
3507
+ type: currentValue.constructor.name
3508
+ };
3509
+ }
3510
+ if (currentValue instanceof Error) {
3511
+ return {
3512
+ message: currentValue.message,
3513
+ name: currentValue.name,
3514
+ stack: currentValue.stack
3515
+ };
3516
+ }
3517
+ if (currentValue.constructor?.name === 'MessagePort') {
3518
+ return {
3519
+ type: 'MessagePort'
3520
+ };
3521
+ }
3522
+ return currentValue;
3523
+ });
3524
+ return JSON.parse(text);
3525
+ };
3526
+ const isCommand = value => {
3527
+ return typeof value === 'object' && value !== null && 'method' in value && typeof value.method === 'string';
3528
+ };
3529
+ const initialize = search => {
3530
+ const searchParams = new URLSearchParams(search);
3531
+ state$a.enabled = searchParams.has('traceRendererWorker');
3532
+ state$a.entries = [];
3533
+ };
3534
+ const record = (direction, method, params) => {
3535
+ if (!state$a.enabled) {
3282
3536
  return;
3283
3537
  }
3284
- fn(response);
3285
- remove$4(id);
3538
+ state$a.entries.push({
3539
+ direction,
3540
+ method,
3541
+ params: serialize(params),
3542
+ timestamp: performance.now()
3543
+ });
3286
3544
  };
3287
- const E_COMMAND_NOT_FOUND = 'E_COMMAND_NOT_FOUND';
3288
- const getErrorType = prettyError => {
3289
- if (prettyError && prettyError.type) {
3290
- return prettyError.type;
3545
+ const listen = rpc => {
3546
+ if (!state$a.enabled) {
3547
+ return;
3291
3548
  }
3292
- if (prettyError && prettyError.constructor && prettyError.constructor.name) {
3293
- return prettyError.constructor.name;
3549
+ const ipc = rpc.ipc;
3550
+ if (!ipc) {
3551
+ return;
3294
3552
  }
3295
- return undefined;
3296
- };
3297
- const isAlreadyStack = line => {
3298
- return line.trim().startsWith('at ');
3553
+ ipc.addEventListener('message', event => {
3554
+ const message = ipc.getData(event);
3555
+ if (isCommand(message)) {
3556
+ record('received', message.method, message.params || []);
3557
+ }
3558
+ });
3299
3559
  };
3300
- const getStack = prettyError => {
3301
- const stackString = prettyError.stack || '';
3302
- const newLineIndex = stackString.indexOf('\n');
3303
- if (newLineIndex !== -1 && !isAlreadyStack(stackString.slice(0, newLineIndex))) {
3304
- return stackString.slice(newLineIndex + 1);
3560
+ const exportToDom = () => {
3561
+ if (!state$a.enabled) {
3562
+ return;
3305
3563
  }
3306
- return stackString;
3307
- };
3308
- const getErrorProperty = (error, prettyError) => {
3309
- if (error && error.code === E_COMMAND_NOT_FOUND) {
3310
- return {
3311
- code: MethodNotFound,
3312
- data: error.stack,
3313
- message: error.message
3314
- };
3564
+ const existing = document.querySelector(selector);
3565
+ const script = existing || document.createElement('script');
3566
+ script.className = 'RendererWorkerTrace';
3567
+ script.type = 'application/json';
3568
+ script.textContent = JSON.stringify({
3569
+ entries: state$a.entries,
3570
+ version: 1
3571
+ });
3572
+ if (!existing) {
3573
+ document.body.append(script);
3315
3574
  }
3316
- return {
3317
- code: Custom,
3318
- data: {
3319
- code: prettyError.code,
3320
- codeFrame: prettyError.codeFrame,
3321
- name: prettyError.name,
3322
- stack: getStack(prettyError),
3323
- type: getErrorType(prettyError)
3324
- },
3325
- message: prettyError.message
3326
- };
3327
3575
  };
3328
- const create$1$1 = (id, error) => {
3329
- return {
3330
- error,
3331
- id,
3332
- jsonrpc: Two$1
3333
- };
3576
+ const scheduleExport = () => {
3577
+ if (!state$a.enabled) {
3578
+ return;
3579
+ }
3580
+ queueMicrotask(exportToDom);
3334
3581
  };
3335
- const getErrorResponse = (id, error, preparePrettyError, logError) => {
3336
- const prettyError = preparePrettyError(error);
3337
- logError(error, prettyError);
3338
- const errorProperty = getErrorProperty(error, prettyError);
3339
- return create$1$1(id, errorProperty);
3582
+
3583
+ const state$9 = {
3584
+ rpc: undefined
3340
3585
  };
3341
- const create$F = (message, result) => {
3342
- return {
3343
- id: message.id,
3344
- jsonrpc: Two$1,
3345
- result: result ?? null
3346
- };
3586
+ const hydrate$3 = async () => {
3587
+ const result = await launchRendererWorker();
3588
+ if (isError(result)) {
3589
+ state$9.rpc = undefined;
3590
+ return result;
3591
+ }
3592
+ state$9.rpc = result.value;
3593
+ listen(result.value);
3594
+ return success(undefined);
3347
3595
  };
3348
- const getSuccessResponse = (message, result) => {
3349
- const resultProperty = result ?? null;
3350
- return create$F(message, resultProperty);
3596
+ const send$1 = (method, ...params) => {
3597
+ record('sent', method, params);
3598
+ // @ts-ignore
3599
+ state$9.rpc.send(method, ...params);
3351
3600
  };
3352
- const getErrorResponseSimple = (id, error) => {
3353
- return {
3354
- error: {
3355
- code: Custom,
3356
- data: error,
3357
- // @ts-ignore
3358
- message: error.message
3359
- },
3360
- id,
3361
- jsonrpc: Two$1
3362
- };
3601
+ const invoke$1 = (method, ...params) => {
3602
+ record('sent', method, params);
3603
+ // @ts-ignore
3604
+ return state$9.rpc.invoke(method, ...params);
3363
3605
  };
3364
- const getResponse = async (message, ipc, execute, preparePrettyError, logError, requiresSocket) => {
3365
- try {
3366
- const result = requiresSocket(message.method) ? await execute(message.method, ipc, ...message.params) : await execute(message.method, ...message.params);
3367
- return getSuccessResponse(message, result);
3368
- } catch (error) {
3369
- if (ipc.canUseSimpleErrorResponse) {
3370
- return getErrorResponseSimple(message.id, error);
3371
- }
3372
- return getErrorResponse(message.id, error, preparePrettyError, logError);
3373
- }
3606
+ const invokeAndTransfer = (method, ...params) => {
3607
+ record('sent', method, params);
3608
+ // @ts-ignore
3609
+ return state$9.rpc.invokeAndTransfer(method, ...params);
3374
3610
  };
3375
- const defaultPreparePrettyError = error => {
3376
- return error;
3611
+
3612
+ const writeFile = (uri, content) => {
3613
+ return invoke$1('FileSystem.writeFile', uri, content);
3377
3614
  };
3378
- const defaultLogError = () => {
3379
- // ignore
3615
+
3616
+ const requestPermission = (handle, options) => {
3617
+ return handle.requestPermission(options);
3380
3618
  };
3381
- const defaultRequiresSocket = () => {
3382
- return false;
3619
+ const getFileHandles = ids => {
3620
+ return getFileHandles$1(ids);
3621
+ };
3622
+ const addFileHandle = fileHandle => {
3623
+ return addFileHandle$1(fileHandle);
3383
3624
  };
3384
- const defaultResolve = resolve;
3385
3625
 
3386
- // TODO maybe remove this in v6 or v7, only accept options object to simplify the code
3387
- const normalizeParams = args => {
3388
- if (args.length === 1) {
3389
- const options = args[0];
3390
- return {
3391
- execute: options.execute,
3392
- ipc: options.ipc,
3393
- logError: options.logError || defaultLogError,
3394
- message: options.message,
3395
- preparePrettyError: options.preparePrettyError || defaultPreparePrettyError,
3396
- requiresSocket: options.requiresSocket || defaultRequiresSocket,
3397
- resolve: options.resolve || defaultResolve
3398
- };
3626
+ const getTitleBarHeight = () => {
3627
+ if (
3628
+ // @ts-expect-error
3629
+ globalThis.navigator.windowControlsOverlay?.getTitlebarAreaRect) {
3630
+ // @ts-expect-error
3631
+ const titleBarRect = globalThis.navigator.windowControlsOverlay.getTitlebarAreaRect();
3632
+ return titleBarRect.height;
3399
3633
  }
3634
+ return 0;
3635
+ };
3636
+ const getBounds = () => {
3400
3637
  return {
3401
- execute: args[2],
3402
- ipc: args[0],
3403
- logError: args[5],
3404
- message: args[1],
3405
- preparePrettyError: args[4],
3406
- requiresSocket: args[6],
3407
- resolve: args[3]
3638
+ titleBarHeight: getTitleBarHeight(),
3639
+ windowHeight: window.innerHeight,
3640
+ windowWidth: window.innerWidth
3408
3641
  };
3409
3642
  };
3410
- const handleJsonRpcMessage = async (...args) => {
3411
- const options = normalizeParams(args);
3412
- const {
3413
- execute,
3414
- ipc,
3415
- logError,
3416
- message,
3417
- preparePrettyError,
3418
- requiresSocket,
3419
- resolve
3420
- } = options;
3421
- if ('id' in message) {
3422
- if ('method' in message) {
3423
- const response = await getResponse(message, ipc, execute, preparePrettyError, logError, requiresSocket);
3424
- try {
3425
- ipc.send(response);
3426
- } catch (error) {
3427
- const errorResponse = getErrorResponse(message.id, error, preparePrettyError, logError);
3428
- ipc.send(errorResponse);
3429
- }
3430
- return;
3431
- }
3432
- resolve(message.id, message);
3433
- return;
3434
- }
3435
- if ('method' in message) {
3436
- await getResponse(message, ipc, execute, preparePrettyError, logError, requiresSocket);
3643
+
3644
+ const getPathName = () => {
3645
+ return location.pathname;
3646
+ };
3647
+ const getHref = () => {
3648
+ return location.href;
3649
+ };
3650
+ const matchesPathName = (currentPathName, pathName) => {
3651
+ const resolvedPathName = new URL(pathName, getHref()).pathname;
3652
+ return currentPathName === resolvedPathName;
3653
+ };
3654
+ const setPathName = pathName => {
3655
+ const currentPathName = getPathName();
3656
+ if (matchesPathName(currentPathName, pathName)) {
3437
3657
  return;
3438
3658
  }
3439
- throw new JsonRpcError('unexpected message');
3659
+ history.pushState(null, '', pathName);
3660
+ };
3661
+ const hydrate$2 = () => {
3662
+ // addEventListener('popstate', handlePopState)
3440
3663
  };
3441
3664
 
3442
- const Two = '2.0';
3665
+ const shouldLaunchMultipleWorkers = true;
3443
3666
 
3444
- const create$E = (method, params) => {
3445
- return {
3446
- jsonrpc: Two,
3447
- method,
3448
- params
3449
- };
3667
+ const getConfig = () => {
3668
+ const configElement = document.getElementById('Config');
3669
+ if (!configElement?.textContent) {
3670
+ return {};
3671
+ }
3672
+ return JSON.parse(configElement.textContent);
3450
3673
  };
3451
-
3452
- const create$D = (id, method, params) => {
3453
- const message = {
3454
- id,
3455
- jsonrpc: Two,
3456
- method,
3457
- params
3674
+ const getInitData = () => {
3675
+ const initData = {
3676
+ Config: {
3677
+ ...getConfig(),
3678
+ shouldLaunchMultipleWorkers: shouldLaunchMultipleWorkers
3679
+ },
3680
+ Layout: {
3681
+ bounds: getBounds()
3682
+ },
3683
+ Location: {
3684
+ href: getHref()
3685
+ }
3458
3686
  };
3459
- return message;
3687
+ return initData;
3460
3688
  };
3461
3689
 
3462
- let id = 0;
3463
- const create$C = () => {
3464
- return ++id;
3465
- };
3690
+ const MessagePort$1 = 1;
3691
+ const ModuleWorker = 2;
3692
+ const ReferencePort = 3;
3693
+ const ModuleWorkerWithMessagePort = 4;
3694
+ const Electron = 5;
3466
3695
 
3467
- const registerPromise = map => {
3468
- const id = create$C();
3469
- const {
3470
- promise,
3471
- resolve
3472
- } = Promise.withResolvers();
3473
- map[id] = resolve;
3474
- return {
3475
- id,
3476
- promise
3477
- };
3696
+ const Message = 'message';
3697
+ const Error$3 = 'error';
3698
+
3699
+ const withResolvers = () => {
3700
+ return Promise.withResolvers();
3478
3701
  };
3479
3702
 
3480
- const invokeHelper = async (callbacks, ipc, method, params, useSendAndTransfer) => {
3703
+ const getFirstEvent = (eventTarget, eventMap) => {
3481
3704
  const {
3482
- id,
3483
- promise
3484
- } = registerPromise(callbacks);
3485
- const message = create$D(id, method, params);
3486
- if (useSendAndTransfer && ipc.sendAndTransfer) {
3487
- ipc.sendAndTransfer(message);
3488
- } else {
3489
- ipc.send(message);
3490
- }
3491
- const responseMessage = await promise;
3492
- return unwrapJsonRpcResult(responseMessage);
3493
- };
3494
- const createRpc = ipc => {
3495
- const callbacks = Object.create(null);
3496
- ipc._resolve = (id, response) => {
3497
- const fn = callbacks[id];
3498
- if (!fn) {
3499
- console.warn(`callback ${id} may already be disposed`);
3500
- return;
3501
- }
3502
- fn(response);
3503
- delete callbacks[id];
3504
- };
3505
- const rpc = {
3506
- async dispose() {
3507
- await ipc?.dispose();
3508
- },
3509
- invoke(method, ...params) {
3510
- return invokeHelper(callbacks, ipc, method, params, false);
3511
- },
3512
- invokeAndTransfer(method, ...params) {
3513
- return invokeHelper(callbacks, ipc, method, params, true);
3514
- },
3515
- // @ts-ignore
3516
- ipc,
3517
- /**
3518
- * @deprecated
3519
- */
3520
- send(method, ...params) {
3521
- const message = create$E(method, params);
3522
- ipc.send(message);
3705
+ promise,
3706
+ resolve
3707
+ } = withResolvers();
3708
+ const listenerMap = Object.create(null);
3709
+ const cleanup = value => {
3710
+ for (const event of Object.keys(eventMap)) {
3711
+ eventTarget.removeEventListener(event, listenerMap[event]);
3523
3712
  }
3713
+ resolve(value);
3524
3714
  };
3525
- return rpc;
3715
+ for (const [event, type] of Object.entries(eventMap)) {
3716
+ const listener = event => {
3717
+ cleanup({
3718
+ event,
3719
+ type
3720
+ });
3721
+ };
3722
+ eventTarget.addEventListener(event, listener);
3723
+ listenerMap[event] = listener;
3724
+ }
3725
+ return promise;
3526
3726
  };
3527
3727
 
3528
- const requiresSocket = () => {
3529
- return false;
3530
- };
3531
- const preparePrettyError = error => {
3532
- return error;
3533
- };
3534
- const logError$1 = () => {
3535
- // handled by renderer worker
3536
- };
3537
- const handleMessage = event => {
3538
- const actualRequiresSocket = event?.target?.requiresSocket || requiresSocket;
3539
- const actualExecute = event?.target?.execute || execute;
3540
- return handleJsonRpcMessage(event.target, event.data, actualExecute, event.target._resolve, preparePrettyError, logError$1, actualRequiresSocket);
3728
+ /**
3729
+ *
3730
+ * @param {Worker} worker
3731
+ * @returns
3732
+ */
3733
+ const getFirstWorkerEvent = worker => {
3734
+ return getFirstEvent(worker, {
3735
+ error: Error$3,
3736
+ message: Message
3737
+ });
3541
3738
  };
3542
3739
 
3543
- const handleIpc = ipc => {
3544
- if ('addEventListener' in ipc) {
3545
- ipc.addEventListener('message', handleMessage);
3546
- } else if ('on' in ipc) {
3547
- // deprecated
3548
- ipc.on('message', handleMessage);
3740
+ const transferrables = [];
3741
+ if (typeof MessagePort !== 'undefined') {
3742
+ transferrables.push(MessagePort);
3743
+ }
3744
+ if (typeof OffscreenCanvas !== 'undefined') {
3745
+ transferrables.push(OffscreenCanvas);
3746
+ }
3747
+
3748
+ const isTransferrable = value => {
3749
+ for (const fn of transferrables) {
3750
+ if (value instanceof fn) {
3751
+ return true;
3752
+ }
3549
3753
  }
3754
+ return false;
3550
3755
  };
3551
- const unhandleIpc = ipc => {
3552
- if ('removeEventListener' in ipc) {
3553
- ipc.removeEventListener('message', handleMessage);
3554
- } else {
3555
- // deprecated
3556
- ipc.onmessage = null;
3756
+
3757
+ const walkValue = (value, transferrables) => {
3758
+ if (!value) {
3759
+ return;
3760
+ }
3761
+ if (isTransferrable(value)) {
3762
+ transferrables.push(value);
3763
+ }
3764
+ if (Array.isArray(value)) {
3765
+ for (const item of value) {
3766
+ walkValue(item, transferrables);
3767
+ }
3768
+ return;
3769
+ }
3770
+ if (typeof value === 'object') {
3771
+ for (const property of Object.values(value)) {
3772
+ walkValue(property, transferrables);
3773
+ }
3557
3774
  }
3558
3775
  };
3559
3776
 
3560
- const create$B = async ({
3561
- commandMap,
3562
- window
3563
- }) => {
3564
- // TODO create a commandMap per rpc instance
3565
- register(commandMap);
3566
- const ipc = IpcChildWithElectronWindow$1.wrap(window);
3567
- handleIpc(ipc);
3568
- const rpc = createRpc(ipc);
3569
- return rpc;
3777
+ const getTransfer = value => {
3778
+ const transferrables = [];
3779
+ walkValue(value, transferrables);
3780
+ return transferrables;
3570
3781
  };
3571
3782
 
3572
- const create$A = async ({
3573
- commandMap,
3574
- isMessagePortOpen = true,
3575
- messagePort
3576
- }) => {
3577
- // TODO create a commandMap per rpc instance
3578
- register(commandMap);
3579
- const rawIpc = await IpcParentWithMessagePort$1.create({
3580
- isMessagePortOpen,
3581
- messagePort
3582
- });
3583
- const ipc = IpcParentWithMessagePort$1.wrap(rawIpc);
3584
- handleIpc(ipc);
3585
- const rpc = createRpc(ipc);
3586
- messagePort.start();
3587
- return rpc;
3783
+ class IpcError extends Error {
3784
+ constructor(message) {
3785
+ super(message);
3786
+ this.name = 'IpcError';
3787
+ }
3788
+ }
3789
+
3790
+ const isErrorEvent = event => {
3791
+ return event instanceof ErrorEvent;
3588
3792
  };
3589
3793
 
3590
- const isWorker = value => {
3591
- return value instanceof Worker;
3794
+ const NewLine = '\n';
3795
+
3796
+ const joinLines = lines => {
3797
+ return lines.join(NewLine);
3798
+ };
3799
+
3800
+ const splitLines = lines => {
3801
+ string(lines);
3802
+ return lines.split(NewLine);
3592
3803
  };
3593
3804
 
3805
+ class WorkerError extends Error {
3806
+ constructor(event) {
3807
+ super(event.message);
3808
+ const stackLines = splitLines(this.stack);
3809
+ const relevantLines = stackLines.slice(1);
3810
+ const relevant = joinLines(relevantLines);
3811
+ this.stack = `${event.message}
3812
+ at Module (${event.filename}:${event.lineno}:${event.colno})
3813
+ ${relevant}`;
3814
+ }
3815
+ }
3816
+
3817
+ const Module = 'module';
3818
+
3819
+ const getWorkerDisplayName = name => {
3820
+ if (name && name.endsWith('Worker')) {
3821
+ return name;
3822
+ }
3823
+ return `${name} worker`;
3824
+ };
3594
3825
  const create$z = async ({
3595
- commandMap,
3596
3826
  name,
3597
3827
  url
3598
3828
  }) => {
3599
- // TODO create a commandMap per rpc instance
3600
- register(commandMap);
3601
- const worker = await IpcParentWithModuleWorker$1.create({
3829
+ const worker = new Worker(url, {
3602
3830
  name,
3603
- url
3831
+ type: Module
3604
3832
  });
3605
- if (!isWorker(worker)) {
3606
- throw new Error(`worker must be of type Worker`);
3833
+ // @ts-expect-error
3834
+ const {
3835
+ event,
3836
+ type
3837
+ } = await getFirstWorkerEvent(worker);
3838
+ switch (type) {
3839
+ case Message:
3840
+ if (event.data !== 'ready') {
3841
+ throw new IpcError('unexpected first message from worker');
3842
+ }
3843
+ break;
3844
+ case Error$3:
3845
+ if (isErrorEvent(event)) {
3846
+ throw new WorkerError(event);
3847
+ }
3848
+ const displayName = getWorkerDisplayName(name);
3849
+ throw new IpcError(`Failed to start ${displayName}`);
3607
3850
  }
3608
- const ipc = IpcParentWithModuleWorker$1.wrap(worker);
3609
- handleIpc(ipc);
3610
- const workerRpc = createRpc(ipc);
3611
- return workerRpc;
3851
+ return worker;
3852
+ };
3853
+ const getData = event => {
3854
+ // TODO why are some events not instance of message event?
3855
+ if (event instanceof MessageEvent) {
3856
+ return event.data;
3857
+ }
3858
+ return event;
3859
+ };
3860
+ const wrap = worker => {
3861
+ let handleMessage;
3862
+ const wrapped = {
3863
+ get onmessage() {
3864
+ return handleMessage;
3865
+ },
3866
+ set onmessage(listener) {
3867
+ if (listener) {
3868
+ handleMessage = event => {
3869
+ const data = getData(event);
3870
+ listener({
3871
+ data,
3872
+ target: wrapped
3873
+ });
3874
+ };
3875
+ } else {
3876
+ handleMessage = null;
3877
+ }
3878
+ worker.onmessage = handleMessage;
3879
+ },
3880
+ send(message) {
3881
+ worker.postMessage(message);
3882
+ },
3883
+ sendAndTransfer(message) {
3884
+ const transfer = getTransfer(message);
3885
+ worker.postMessage(message, transfer);
3886
+ }
3887
+ };
3888
+ return wrapped;
3889
+ };
3890
+
3891
+ const IpcParentWithModuleWorker = {
3892
+ __proto__: null,
3893
+ create: create$z,
3894
+ wrap
3895
+ };
3896
+
3897
+ const isMessagePort = value => {
3898
+ return value instanceof MessagePort;
3612
3899
  };
3613
3900
 
3614
3901
  const create$y = async ({
3615
- commandMap,
3616
- name,
3617
- port,
3618
3902
  url
3619
3903
  }) => {
3620
- // TODO create a commandMap per rpc instance
3621
- register(commandMap);
3622
- const worker = await IpcParentWithModuleWorker$1.create({
3623
- name,
3624
- url
3904
+ string(url);
3905
+ const portPromise = await new Promise(resolve => {
3906
+ Object.defineProperty(globalThis, 'acceptPort', {
3907
+ configurable: true,
3908
+ value: resolve
3909
+ });
3625
3910
  });
3626
- if (!isWorker(worker)) {
3627
- throw new Error(`worker must be of type Worker`);
3911
+ await import(url);
3912
+ const port = await portPromise;
3913
+ delete globalThis.acceptPort;
3914
+ if (!port) {
3915
+ throw new IpcError('port must be defined');
3628
3916
  }
3629
- const ipc = IpcParentWithModuleWorker$1.wrap(worker);
3630
- handleIpc(ipc);
3631
- const workerRpc = createRpc(ipc);
3632
- await workerRpc.invokeAndTransfer('initialize', 'message-port', port);
3633
- unhandleIpc(ipc);
3634
- return workerRpc;
3917
+ if (!isMessagePort(port)) {
3918
+ throw new IpcError('port must be of type MessagePort');
3919
+ }
3920
+ return port;
3635
3921
  };
3636
3922
 
3637
- const create$x = async ({
3638
- commandMap,
3639
- messagePort
3640
- }) => {
3641
- return create$A({
3642
- commandMap,
3643
- messagePort
3923
+ const IpcParentWithMessagePort = {
3924
+ __proto__: null,
3925
+ create: create$y
3926
+ };
3927
+
3928
+ const create$x = async url => {
3929
+ const referencePort = await new Promise(resolve => {
3930
+ Object.defineProperty(globalThis, 'acceptReferencePort', {
3931
+ configurable: true,
3932
+ value: resolve
3933
+ });
3934
+ import(url);
3644
3935
  });
3936
+ delete globalThis.acceptReferencePort;
3937
+ return referencePort;
3938
+ };
3939
+
3940
+ const IpcParentWithReferencePort = {
3941
+ __proto__: null,
3942
+ create: create$x
3645
3943
  };
3646
3944
 
3647
3945
  const workers = Object.create(null);
@@ -3661,7 +3959,7 @@ const create$w = async ({
3661
3959
  raw,
3662
3960
  rpcId,
3663
3961
  url
3664
- }, createTransferredRpc = create$y, createNativeRpc = create$z) => {
3962
+ }, createTransferredRpc = create$B, createNativeRpc = create$C) => {
3665
3963
  const rpc = await (rpcId === undefined ? createTransferredRpc({
3666
3964
  commandMap: {},
3667
3965
  name,
@@ -3688,34 +3986,7 @@ const IpcParentWithModuleWorkerWithMessagePort = {
3688
3986
  create: create$w
3689
3987
  };
3690
3988
 
3691
- const Web = 1;
3692
- const Electron = 2;
3693
- const Remote = 3;
3694
-
3695
- /**
3696
- * @returns {number}
3697
- */
3698
- const getPlatform = () => {
3699
- // @ts-expect-error
3700
- if (typeof PLATFORM !== 'undefined') {
3701
- // @ts-expect-error
3702
- return PLATFORM;
3703
- }
3704
- // @ts-ignore
3705
- if (typeof process !== 'undefined' && process.env.NODE_ENV === 'test') {
3706
- return Remote;
3707
- }
3708
- if (globalThis.isElectron) {
3709
- return Electron;
3710
- }
3711
- if (typeof location !== 'undefined' && location.search === '?web') {
3712
- return Web;
3713
- }
3714
- return Remote;
3715
- };
3716
- const platform = getPlatform();
3717
-
3718
- const isElectron = platform === Electron;
3989
+ const isElectron = platform === Electron$1;
3719
3990
 
3720
3991
  // TODO use handleIncomingIpc function
3721
3992
  const create$v = async ({
@@ -3726,7 +3997,7 @@ const create$v = async ({
3726
3997
  if (!isElectron) {
3727
3998
  throw new Error('Electron api was requested but is not available');
3728
3999
  }
3729
- const rpc = await create$B({
4000
+ const rpc = await create$E({
3730
4001
  commandMap: {},
3731
4002
  window
3732
4003
  });
@@ -3741,12 +4012,12 @@ const IpcParentWithElectron = {
3741
4012
 
3742
4013
  const getModule = method => {
3743
4014
  switch (method) {
3744
- case Electron$1:
4015
+ case Electron:
3745
4016
  return IpcParentWithElectron;
3746
4017
  case MessagePort$1:
3747
- return IpcParentWithMessagePort$2;
4018
+ return IpcParentWithMessagePort;
3748
4019
  case ModuleWorker:
3749
- return IpcParentWithModuleWorker$2;
4020
+ return IpcParentWithModuleWorker;
3750
4021
  case ModuleWorkerWithMessagePort:
3751
4022
  return IpcParentWithModuleWorkerWithMessagePort;
3752
4023
  case ReferencePort:
@@ -3770,225 +4041,6 @@ const has = name => {
3770
4041
  return ipcs[name];
3771
4042
  };
3772
4043
 
3773
- const commandMapRef = {};
3774
-
3775
- const success = value => {
3776
- return {
3777
- ok: true,
3778
- value
3779
- };
3780
- };
3781
- const error = error => {
3782
- return {
3783
- error,
3784
- ok: false
3785
- };
3786
- };
3787
- const isError = result => {
3788
- return !result.ok;
3789
- };
3790
-
3791
- const launchWorker = async ({
3792
- name,
3793
- url
3794
- }) => {
3795
- try {
3796
- const rpc = await create$z({
3797
- commandMap: commandMapRef,
3798
- name,
3799
- url
3800
- });
3801
- return success(rpc);
3802
- } catch (error$1) {
3803
- return error(error$1);
3804
- }
3805
- };
3806
-
3807
- const getAssetDir = () => {
3808
- // @ts-expect-error
3809
- if (typeof ASSET_DIR !== 'undefined') {
3810
- // @ts-expect-error
3811
- return ASSET_DIR;
3812
- }
3813
- if (platform === Electron) {
3814
- return '../../../../..';
3815
- }
3816
- return '';
3817
- };
3818
- const assetDir = getAssetDir();
3819
-
3820
- const getConfiguredWorkerUrl = key => {
3821
- if (typeof location === 'undefined' || typeof document === 'undefined') {
3822
- return '';
3823
- }
3824
- const configElement = document.getElementById('Config');
3825
- if (!configElement) {
3826
- return '';
3827
- }
3828
- const text = configElement.textContent;
3829
- if (!text) {
3830
- return '';
3831
- }
3832
- const config = JSON.parse(text);
3833
- return config[key] || '';
3834
- };
3835
-
3836
- const getConfiguredRendererWorkerUrl = () => {
3837
- return getConfiguredWorkerUrl('rendererWorkerUrl');
3838
- };
3839
-
3840
- const rendererWorkerUrl = getConfiguredRendererWorkerUrl() || `${assetDir}/packages/renderer-worker/src/rendererWorkerMain.ts`;
3841
-
3842
- const getName = platform => {
3843
- switch (platform) {
3844
- case Electron:
3845
- return 'Renderer Worker (Electron)';
3846
- case Web:
3847
- return 'Renderer Worker (Web)';
3848
- default:
3849
- return 'Renderer Worker';
3850
- }
3851
- };
3852
- const launchRendererWorker = async () => {
3853
- const name = getName(platform);
3854
- return launchWorker({
3855
- name,
3856
- url: rendererWorkerUrl
3857
- });
3858
- };
3859
-
3860
- const selector = 'script.RendererWorkerTrace';
3861
- const state$a = {
3862
- enabled: false,
3863
- entries: []
3864
- };
3865
- const serialize = value => {
3866
- const seen = new WeakSet();
3867
- const text = JSON.stringify(value, (_key, currentValue) => {
3868
- if (typeof currentValue === 'bigint') {
3869
- return `${currentValue}n`;
3870
- }
3871
- if (typeof currentValue !== 'object' || currentValue === null) {
3872
- return currentValue;
3873
- }
3874
- if (seen.has(currentValue)) {
3875
- return '[Circular]';
3876
- }
3877
- seen.add(currentValue);
3878
- if (currentValue instanceof ArrayBuffer) {
3879
- return {
3880
- byteLength: currentValue.byteLength,
3881
- type: 'ArrayBuffer'
3882
- };
3883
- }
3884
- if (ArrayBuffer.isView(currentValue)) {
3885
- return {
3886
- byteLength: currentValue.byteLength,
3887
- type: currentValue.constructor.name
3888
- };
3889
- }
3890
- if (currentValue instanceof Error) {
3891
- return {
3892
- message: currentValue.message,
3893
- name: currentValue.name,
3894
- stack: currentValue.stack
3895
- };
3896
- }
3897
- if (currentValue.constructor?.name === 'MessagePort') {
3898
- return {
3899
- type: 'MessagePort'
3900
- };
3901
- }
3902
- return currentValue;
3903
- });
3904
- return JSON.parse(text);
3905
- };
3906
- const isCommand = value => {
3907
- return typeof value === 'object' && value !== null && 'method' in value && typeof value.method === 'string';
3908
- };
3909
- const initialize = search => {
3910
- const searchParams = new URLSearchParams(search);
3911
- state$a.enabled = searchParams.has('traceRendererWorker');
3912
- state$a.entries = [];
3913
- };
3914
- const record = (direction, method, params) => {
3915
- if (!state$a.enabled) {
3916
- return;
3917
- }
3918
- state$a.entries.push({
3919
- direction,
3920
- method,
3921
- params: serialize(params),
3922
- timestamp: performance.now()
3923
- });
3924
- };
3925
- const listen = rpc => {
3926
- if (!state$a.enabled) {
3927
- return;
3928
- }
3929
- const ipc = rpc.ipc;
3930
- if (!ipc) {
3931
- return;
3932
- }
3933
- ipc.addEventListener('message', event => {
3934
- const message = ipc.getData(event);
3935
- if (isCommand(message)) {
3936
- record('received', message.method, message.params || []);
3937
- }
3938
- });
3939
- };
3940
- const exportToDom = () => {
3941
- if (!state$a.enabled) {
3942
- return;
3943
- }
3944
- const existing = document.querySelector(selector);
3945
- const script = existing || document.createElement('script');
3946
- script.className = 'RendererWorkerTrace';
3947
- script.type = 'application/json';
3948
- script.textContent = JSON.stringify({
3949
- entries: state$a.entries,
3950
- version: 1
3951
- });
3952
- if (!existing) {
3953
- document.body.append(script);
3954
- }
3955
- };
3956
- const scheduleExport = () => {
3957
- if (!state$a.enabled) {
3958
- return;
3959
- }
3960
- queueMicrotask(exportToDom);
3961
- };
3962
-
3963
- const state$9 = {
3964
- rpc: undefined
3965
- };
3966
- const hydrate$2 = async () => {
3967
- const result = await launchRendererWorker();
3968
- if (isError(result)) {
3969
- state$9.rpc = undefined;
3970
- return result;
3971
- }
3972
- state$9.rpc = result.value;
3973
- listen(result.value);
3974
- return success(undefined);
3975
- };
3976
- const send$1 = (method, ...params) => {
3977
- record('sent', method, params);
3978
- // @ts-ignore
3979
- state$9.rpc.send(method, ...params);
3980
- };
3981
- const invoke$1 = (method, ...params) => {
3982
- record('sent', method, params);
3983
- // @ts-ignore
3984
- return state$9.rpc.invoke(method, ...params);
3985
- };
3986
- const invokeAndTransfer = (method, ...params) => {
3987
- record('sent', method, params);
3988
- // @ts-ignore
3989
- return state$9.rpc.invokeAndTransfer(method, ...params);
3990
- };
3991
-
3992
4044
  const create$u = async ({
3993
4045
  method,
3994
4046
  ...options
@@ -4684,7 +4736,7 @@ const openUrl = (url, useRedirect = false) => {
4684
4736
  };
4685
4737
 
4686
4738
  const isElectronUserAgentSpecificMemoryError = error => {
4687
- if (platform !== Electron) {
4739
+ if (platform !== Electron$1) {
4688
4740
  return;
4689
4741
  }
4690
4742
  return error.message === `Failed to execute 'measureUserAgentSpecificMemory' on 'Performance': performance.measureUserAgentSpecificMemory is not available.`;
@@ -9873,11 +9925,15 @@ const unmock = () => {
9873
9925
  Element.prototype.releasePointerCapture = originalPointerCapture.releasePointerCapture;
9874
9926
  };
9875
9927
 
9928
+ const addHandle = (uri, handle) => {
9929
+ return invoke$1('PersistentFileHandle.addHandle', uri, handle);
9930
+ };
9931
+
9876
9932
  const forwardRendererWorkerCommand = (method, ...params) => {
9877
9933
  send$1(method, ...params);
9878
9934
  };
9879
9935
  const handleMessagePort = async (port, rpcId) => {
9880
- const rpc = await create$x({
9936
+ const rpc = await create$A({
9881
9937
  commandMap: {
9882
9938
  'Viewlet.forwardRendererWorkerCommand': forwardRendererWorkerCommand,
9883
9939
  'Viewlet.queueCommands': queueCommands
@@ -10157,13 +10213,16 @@ const commandMap = {
10157
10213
  'DirectView.getFocusedUid': getFocusedViewUid,
10158
10214
  'DirectView.getUid': getViewUid,
10159
10215
  'Download.downloadFile': downloadFile,
10160
- 'DropData.get': get$6,
10161
- 'FileHandles.get': get$5,
10216
+ 'DragAndDrop.handleMessagePort': handleMessagePort$1,
10217
+ 'DropData.get': get$5,
10218
+ 'FileHandles.get': get$4,
10162
10219
  'FilePicker.showDirectoryPicker': showDirectoryPicker,
10163
10220
  'FilePicker.showFilePicker': showFilePicker,
10164
10221
  'FilePicker.showSaveFilePicker': showSaveFilePicker,
10222
+ 'FileSystem.writeFile': writeFile,
10165
10223
  'FileSystemHandle.addFileHandle': addFileHandle,
10166
10224
  'FileSystemHandle.getFileHandles': getFileHandles,
10225
+ 'FileSystemHandle.getFilePathElectron': getFilePathElectron,
10167
10226
  'FileSystemHandle.requestPermission': requestPermission,
10168
10227
  'GetFilePathElectron.getFilePathElectron': getFilePathElectron,
10169
10228
  'HandleMessagePort.handleMessagePort': handleMessagePort,
@@ -10174,7 +10233,7 @@ const commandMap = {
10174
10233
  'Layout.getBounds': getBounds,
10175
10234
  'Location.getHref': getHref,
10176
10235
  'Location.getPathName': getPathName,
10177
- 'Location.hydrate': hydrate$3,
10236
+ 'Location.hydrate': hydrate$2,
10178
10237
  'Location.setPathName': setPathName,
10179
10238
  'MeasureTextBlockHeight.measureTextBlockHeight': measureTextBlockHeight,
10180
10239
  'MeasureTextHeight.measureTextHeight': measureTextHeight,
@@ -10193,6 +10252,7 @@ const commandMap = {
10193
10252
  'Open.redirectToUrl': redirectToUrl,
10194
10253
  'Performance.getMemory': getMemory,
10195
10254
  'Performance.measureUserAgentSpecificMemory': measureUserAgentSpecificMemory,
10255
+ 'PersistentFileHandle.addHandle': addHandle,
10196
10256
  'PointerCapture.mock': mock,
10197
10257
  'PointerCapture.unmock': unmock,
10198
10258
  'Prompt.prompt': prompt,
@@ -10330,7 +10390,7 @@ const mergeCustom = (custom, relevantStack) => {
10330
10390
  };
10331
10391
  const cleanStack = stack => {
10332
10392
  string(stack);
10333
- const lines = splitLines$2(stack);
10393
+ const lines = splitLines(stack);
10334
10394
  const {
10335
10395
  actualStack,
10336
10396
  custom
@@ -10380,7 +10440,7 @@ const prepareErrorMessageWithCodeFrame = error => {
10380
10440
  }
10381
10441
  const message = getErrorMessage(error);
10382
10442
  const lines = cleanStack(error.stack);
10383
- const relevantStack = joinLines$2(lines);
10443
+ const relevantStack = joinLines(lines);
10384
10444
  if (error.codeFrame) {
10385
10445
  return {
10386
10446
  _error: error,
@@ -10599,19 +10659,19 @@ const hydrate = async () => {
10599
10659
  return success(undefined);
10600
10660
  };
10601
10661
 
10602
- const workerFns = [hydrate$2, hydrate$1, hydrate];
10662
+ const requiredWorkerFns = [hydrate$3, hydrate$4];
10663
+ const additionalWorkerFns = [hydrate$1, hydrate];
10603
10664
  const call = fn => {
10604
10665
  return fn();
10605
10666
  };
10606
10667
  const launchWorkers = async () => {
10607
- {
10608
- const results = await Promise.all(workerFns.map(call));
10609
- const firstError = results.find(isError);
10610
- if (firstError) {
10611
- return firstError;
10612
- }
10613
- return success(undefined);
10668
+ const workerFns = [...requiredWorkerFns, ...additionalWorkerFns] ;
10669
+ const results = await Promise.all(workerFns.map(call));
10670
+ const firstError = results.find(isError);
10671
+ if (firstError) {
10672
+ return firstError;
10614
10673
  }
10674
+ return success(undefined);
10615
10675
  };
10616
10676
 
10617
10677
  const handleFocusIn = event => {