premiere distribution de la page web

This commit is contained in:
2026-07-30 23:04:01 +02:00
commit c975fb87ea
1759 changed files with 719978 additions and 0 deletions

11
client/index.html Normal file
View File

@@ -0,0 +1,11 @@
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<title>Ma page</title>
</head>
<body>
<h1>Bonjour !</h1>
<p>Ceci est une page statique servie par Express.</p>
</body>
</html>

1
client/node_modules/.bin/nanoid generated vendored Symbolic link
View File

@@ -0,0 +1 @@
../nanoid/bin/nanoid.cjs

1
client/node_modules/.bin/rolldown generated vendored Symbolic link
View File

@@ -0,0 +1 @@
../rolldown/bin/cli.mjs

1
client/node_modules/.bin/vite generated vendored Symbolic link
View File

@@ -0,0 +1 @@
../vite/bin/vite.js

424
client/node_modules/.package-lock.json generated vendored Normal file
View File

@@ -0,0 +1,424 @@
{
"name": "client",
"lockfileVersion": 3,
"requires": true,
"packages": {
"node_modules/@emnapi/core": {
"version": "2.0.0-alpha.3",
"resolved": "https://registry.npmjs.org/@emnapi/core/-/core-2.0.0-alpha.3.tgz",
"integrity": "sha512-AZypUeJ/yByuxyS7BlSNRDOMLMlROYtjYdIAuBmJssVz1UJDSeYxLrdizhXCFYhedC5bqd/ASy8EuNXbVVXp9g==",
"dev": true,
"license": "MIT",
"optional": true,
"dependencies": {
"@emnapi/wasi-threads": "2.0.1",
"tslib": "^2.4.0"
}
},
"node_modules/@emnapi/runtime": {
"version": "2.0.0-alpha.3",
"resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-2.0.0-alpha.3.tgz",
"integrity": "sha512-hFPAhMUjJD9BSyCANEISPOogeXC9Zo9ZQl7L6vKnaVsMkCtzznaW/naYypeyl0Gv5rYfWYsZbpixTMpjDJzQeA==",
"dev": true,
"license": "MIT",
"optional": true,
"dependencies": {
"tslib": "^2.4.0"
}
},
"node_modules/@emnapi/wasi-threads": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-2.0.1.tgz",
"integrity": "sha512-9DsSk+o5NBX0CCJT8s0EROGSGxjR/tKu6aBTaVyq+SjAEQH4XcdcRxPBRzsBLizTTJ49MJjF+jgu3qnO9GLQcQ==",
"dev": true,
"license": "MIT",
"optional": true,
"dependencies": {
"tslib": "^2.4.0"
}
},
"node_modules/@napi-rs/wasm-runtime": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.2.1.tgz",
"integrity": "sha512-KjZdi8Q1wh89gsVmghvbrMgWl6ZWmRmHV6wjB7/g4Zf0dyO+hH3neZUtuDNPO00qq5YE5RITVWvrIZKRaAmzGQ==",
"dev": true,
"license": "MIT",
"optional": true,
"dependencies": {
"@tybys/wasm-util": "^0.10.3"
},
"engines": {
"node": "^20.19.0 || ^22.13.0 || >=23.5.0"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
},
"peerDependencies": {
"@emnapi/core": "^1.7.1 || ^2.0.0-alpha.3",
"@emnapi/runtime": "^1.7.1 || ^2.0.0-alpha.3"
}
},
"node_modules/@oxc-project/types": {
"version": "0.142.0",
"resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.142.0.tgz",
"integrity": "sha512-7W+2q5AKQVU36fkaryontrHn3YDt1RyUYXatw9i5H8ocYe2sPKSFB6eS8WNPeRKiN1qAWWZUPm7gwFzJGrccqQ==",
"dev": true,
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/Boshen"
}
},
"node_modules/@rolldown/binding-linux-x64-gnu": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.1.tgz",
"integrity": "sha512-/Orga1fZYkLc/56jBICcHrKchl8Z2UKdDSr3LG9ToWO1lQ6a4Livk9Xz+9WN91zsz5QR3XQz2NNoSDEvP6qadw==",
"cpu": [
"x64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": "^20.19.0 || >=22.12.0"
}
},
"node_modules/@rolldown/binding-wasm32-wasi": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/@rolldown/binding-wasm32-wasi/-/binding-wasm32-wasi-1.2.1.tgz",
"integrity": "sha512-/TX0SoRGojHzSAHpfVBbavRVSazg5U3h3Y3VXfcc0cdugq6kxdqw8LPGFiPr+/7gE/60zRcsOY2Vi9b9eT0jww==",
"dev": true,
"license": "MIT",
"optional": true,
"dependencies": {
"@emnapi/core": "2.0.0-alpha.3",
"@emnapi/runtime": "2.0.0-alpha.3",
"@napi-rs/wasm-runtime": "^1.2.0"
},
"engines": {
"node": "^20.19.0 || ^22.13.0 || >=23.5.0"
}
},
"node_modules/@rolldown/pluginutils": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.1.tgz",
"integrity": "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==",
"dev": true,
"license": "MIT"
},
"node_modules/@tybys/wasm-util": {
"version": "0.10.3",
"resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.3.tgz",
"integrity": "sha512-F3fo1MYrRJYL3zER0OUOmkutjr1Vp23m7OsSgp7nq4SP6OqX6C/56XFIPAl5bt3zaBRjmW7SGz3u/6LwFpYcOg==",
"dev": true,
"license": "MIT",
"optional": true,
"dependencies": {
"tslib": "^2.4.0"
}
},
"node_modules/detect-libc": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",
"integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==",
"dev": true,
"license": "Apache-2.0",
"engines": {
"node": ">=8"
}
},
"node_modules/fdir": {
"version": "6.5.0",
"resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
"integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=12.0.0"
},
"peerDependencies": {
"picomatch": "^3 || ^4"
},
"peerDependenciesMeta": {
"picomatch": {
"optional": true
}
}
},
"node_modules/lightningcss": {
"version": "1.33.0",
"resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz",
"integrity": "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==",
"dev": true,
"license": "MPL-2.0",
"dependencies": {
"detect-libc": "^2.0.3"
},
"engines": {
"node": ">= 12.0.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/parcel"
},
"optionalDependencies": {
"lightningcss-android-arm64": "1.33.0",
"lightningcss-darwin-arm64": "1.33.0",
"lightningcss-darwin-x64": "1.33.0",
"lightningcss-freebsd-x64": "1.33.0",
"lightningcss-linux-arm-gnueabihf": "1.33.0",
"lightningcss-linux-arm64-gnu": "1.33.0",
"lightningcss-linux-arm64-musl": "1.33.0",
"lightningcss-linux-x64-gnu": "1.33.0",
"lightningcss-linux-x64-musl": "1.33.0",
"lightningcss-win32-arm64-msvc": "1.33.0",
"lightningcss-win32-x64-msvc": "1.33.0"
}
},
"node_modules/lightningcss-linux-x64-gnu": {
"version": "1.33.0",
"resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.33.0.tgz",
"integrity": "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==",
"cpu": [
"x64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MPL-2.0",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 12.0.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/parcel"
}
},
"node_modules/nanoid": {
"version": "3.3.16",
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.16.tgz",
"integrity": "sha512-bzlKTyNJ7+LdGIIwy8ijFpIqEQIvafahV7eYykJ8Cvh42EdJeODoJ6gUJXpQJvej1BddH8OqTXZNE/KfbWAu8Q==",
"dev": true,
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/ai"
}
],
"license": "MIT",
"bin": {
"nanoid": "bin/nanoid.cjs"
},
"engines": {
"node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
}
},
"node_modules/picocolors": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
"integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",
"dev": true,
"license": "ISC"
},
"node_modules/picomatch": {
"version": "4.0.5",
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.5.tgz",
"integrity": "sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=12"
},
"funding": {
"url": "https://github.com/sponsors/jonschlinkert"
}
},
"node_modules/postcss": {
"version": "8.5.25",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.25.tgz",
"integrity": "sha512-DTPx3RWSSnWyzLxQnlH0rJP+EW5ekl16ZU4/psbIhA0e53kJfdgaN5vKM+xP7yJtXVu+nfdVFmlgFDEKAe4Pyw==",
"dev": true,
"funding": [
{
"type": "opencollective",
"url": "https://opencollective.com/postcss/"
},
{
"type": "tidelift",
"url": "https://tidelift.com/funding/github/npm/postcss"
},
{
"type": "github",
"url": "https://github.com/sponsors/ai"
}
],
"license": "MIT",
"dependencies": {
"nanoid": "^3.3.16",
"picocolors": "^1.1.1",
"source-map-js": "^1.2.1"
},
"engines": {
"node": "^10 || ^12 || >=14"
}
},
"node_modules/rolldown": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.1.tgz",
"integrity": "sha512-4FKJhg8d3OiyQOA6Q1Q0hoFFpW9/OoX+VsHzpECsdsIZoOArrAK90gl59YK/Z+gnDel45bgJZK03ozH/9bCqEw==",
"dev": true,
"license": "MIT",
"dependencies": {
"@oxc-project/types": "=0.142.0",
"@rolldown/pluginutils": "^1.0.0"
},
"bin": {
"rolldown": "bin/cli.mjs"
},
"engines": {
"node": "^20.19.0 || >=22.12.0"
},
"optionalDependencies": {
"@rolldown/binding-android-arm64": "1.2.1",
"@rolldown/binding-darwin-arm64": "1.2.1",
"@rolldown/binding-darwin-x64": "1.2.1",
"@rolldown/binding-freebsd-x64": "1.2.1",
"@rolldown/binding-linux-arm-gnueabihf": "1.2.1",
"@rolldown/binding-linux-arm64-gnu": "1.2.1",
"@rolldown/binding-linux-arm64-musl": "1.2.1",
"@rolldown/binding-linux-ppc64-gnu": "1.2.1",
"@rolldown/binding-linux-s390x-gnu": "1.2.1",
"@rolldown/binding-linux-x64-gnu": "1.2.1",
"@rolldown/binding-linux-x64-musl": "1.2.1",
"@rolldown/binding-openharmony-arm64": "1.2.1",
"@rolldown/binding-wasm32-wasi": "1.2.1",
"@rolldown/binding-win32-arm64-msvc": "1.2.1",
"@rolldown/binding-win32-x64-msvc": "1.2.1"
}
},
"node_modules/source-map-js": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",
"integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==",
"dev": true,
"license": "BSD-3-Clause",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/tinyglobby": {
"version": "0.2.17",
"resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz",
"integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==",
"dev": true,
"license": "MIT",
"dependencies": {
"fdir": "^6.5.0",
"picomatch": "^4.0.4"
},
"engines": {
"node": ">=12.0.0"
},
"funding": {
"url": "https://github.com/sponsors/SuperchupuDev"
}
},
"node_modules/tslib": {
"version": "2.8.1",
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
"dev": true,
"license": "0BSD",
"optional": true
},
"node_modules/vite": {
"version": "8.2.0",
"resolved": "https://registry.npmjs.org/vite/-/vite-8.2.0.tgz",
"integrity": "sha512-pn+CFpM0lwDeKwmOq1ZaBK/9sjorZcgqxki6MbY/jPEVd9vichIlmlD4HmQ5wdP5EgqQCFRaACBxMC7uEGc6lQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"lightningcss": "^1.33.0",
"picomatch": "^4.0.5",
"postcss": "^8.5.23",
"rolldown": "~1.2.0",
"tinyglobby": "^0.2.17"
},
"bin": {
"vite": "bin/vite.js"
},
"engines": {
"node": "^20.19.0 || >=22.12.0"
},
"funding": {
"url": "https://github.com/vitejs/vite?sponsor=1"
},
"optionalDependencies": {
"fsevents": "~2.3.3"
},
"peerDependencies": {
"@types/node": "^20.19.0 || >=22.12.0",
"@vitejs/devtools": "^0.4.0",
"esbuild": "^0.27.0 || ^0.28.0",
"jiti": ">=1.21.0",
"less": "^4.0.0",
"sass": "^1.70.0",
"sass-embedded": "^1.70.0",
"stylus": ">=0.54.8",
"sugarss": "^5.0.0",
"terser": "^5.16.0",
"tsx": "^4.8.1",
"yaml": "^2.4.2"
},
"peerDependenciesMeta": {
"@types/node": {
"optional": true
},
"@vitejs/devtools": {
"optional": true
},
"esbuild": {
"optional": true
},
"jiti": {
"optional": true
},
"less": {
"optional": true
},
"sass": {
"optional": true
},
"sass-embedded": {
"optional": true
},
"stylus": {
"optional": true
},
"sugarss": {
"optional": true
},
"terser": {
"optional": true
},
"tsx": {
"optional": true
},
"yaml": {
"optional": true
}
}
}
}
}

21
client/node_modules/@emnapi/core/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2021-present Toyobayashi
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

1
client/node_modules/@emnapi/core/README.md generated vendored Normal file
View File

@@ -0,0 +1 @@
See [https://github.com/toyobayashi/emnapi](https://github.com/toyobayashi/emnapi)

366
client/node_modules/@emnapi/core/dist/emnapi-core.d.ts generated vendored Normal file
View File

@@ -0,0 +1,366 @@
import type { Context } from '@emnapi/runtime';
import type { ReferenceOwnership } from '@emnapi/runtime';
import type { Worker as Worker_2 } from 'worker_threads';
/** @public */
export declare type BaseCreateOptions = {
filename?: string
nodeBinding?: NodeBinding
reuseWorker?: ThreadManagerOptionsMain['reuseWorker']
asyncWorkPoolSize?: number
waitThreadStart?: MainThreadBaseOptions['waitThreadStart']
onCreateWorker?: (info: CreateWorkerInfo) => any
print?: (str: string) => void
printErr?: (str: string) => void
postMessage?: (msg: any) => any
plugins?: (PluginFactory | EmnapiPlugin)[]
}
export declare interface BaseOptions {
wasi: WASIInstance;
version?: 'preview1';
wasm64?: boolean;
}
export declare interface ChildThreadOptions extends BaseOptions {
childThread: true;
postMessage?: (data: any) => void;
}
export declare interface CleanupThreadPayload {
tid: number;
}
export declare interface CommandInfo<T extends CommandType> {
type: T;
payload: CommandPayloadMap[T];
}
export declare interface CommandPayloadMap {
load: LoadPayload;
loaded: LoadedPayload;
start: StartPayload;
'cleanup-thread': CleanupThreadPayload;
'terminate-all-threads': TerminateAllThreadsPayload;
'spawn-thread': SpawnThreadPayload;
}
export declare type CommandType = keyof CommandPayloadMap;
export declare function createInstanceProxy(instance: WebAssembly.Instance, memory?: WebAssembly.Memory | (() => WebAssembly.Memory)): WebAssembly.Instance;
/** @public */
export declare function createNapiModule (
options: CreateOptions
): NapiModule
/** @public */
export declare type CreateOptions = BaseCreateOptions & ({
context: Context
childThread?: boolean
} | {
context?: Context
childThread: true
})
/** @public */
export declare interface CreateWorkerInfo {
type: 'thread' | 'async-work'
name: string
}
/** @public */
export declare interface EmnapiPlugin {
importObject?: (originalImports: WebAssembly.Imports) => (WebAssembly.Imports | void)
}
/** @public */
export declare interface InitOptions {
instance: WebAssembly.Instance
module: WebAssembly.Module
memory?: WebAssembly.Memory
table?: WebAssembly.Table
}
export declare type InputType = string | URL | Response | BufferSource | WebAssembly.Module;
export declare interface InstantiatedSource extends LoadedSource {
napiModule: NapiModule;
}
export declare function instantiateNapiModule(wasmInput: InputType | Promise<InputType>, options: InstantiateOptions): Promise<InstantiatedSource>;
export declare function instantiateNapiModuleSync(wasmInput: BufferSource | WebAssembly.Module, options: InstantiateOptions): InstantiatedSource;
export declare type InstantiateOptions = CreateOptions & LoadOptions;
export declare function isSharedArrayBuffer(value: any): value is SharedArrayBuffer;
export declare function isTrapError(e: Error): e is WebAssembly.RuntimeError;
export declare interface LoadedPayload {
}
export declare interface LoadedSource extends WebAssembly.WebAssemblyInstantiatedSource {
usedInstance: WebAssembly.Instance;
}
export declare function loadNapiModule(napiModule: NapiModule, wasmInput: InputType | Promise<InputType>, options?: LoadOptions): Promise<LoadedSource>;
export declare function loadNapiModuleSync(napiModule: NapiModule, wasmInput: BufferSource | WebAssembly.Module, options?: LoadOptions): LoadedSource;
export declare interface LoadOptions {
wasi?: WASIInstance;
overwriteImports?: (importObject: WebAssembly.Imports) => WebAssembly.Imports;
beforeInit?: (source: WebAssembly.WebAssemblyInstantiatedSource) => void;
getMemory?: (exports: WebAssembly.Exports) => WebAssembly.Memory;
getTable?: (exports: WebAssembly.Exports) => WebAssembly.Table;
}
export declare interface LoadPayload {
wasmModule: WebAssembly.Module;
wasmMemory: WebAssembly.Memory;
sab?: Int32Array;
}
export declare interface MainThreadBaseOptions extends BaseOptions {
waitThreadStart?: boolean | number;
}
export declare type MainThreadOptions = MainThreadOptionsWithThreadManager | MainThreadOptionsCreateThreadManager;
export declare interface MainThreadOptionsCreateThreadManager extends MainThreadBaseOptions, ThreadManagerOptionsMain {
}
export declare interface MainThreadOptionsWithThreadManager extends MainThreadBaseOptions {
threadManager?: ThreadManager | (() => ThreadManager);
}
export declare interface MessageEventData<T extends CommandType> {
__emnapi__: CommandInfo<T>;
}
export declare class MessageHandler extends ThreadMessageHandler {
napiModule: NapiModule | undefined;
constructor(options: MessageHandlerOptions);
instantiate(data: LoadPayload): InstantiatedSource | PromiseLike<InstantiatedSource>;
handle(e: WorkerMessageEvent): void;
}
export declare interface MessageHandlerOptions extends ThreadMessageHandlerOptions {
onLoad: (data: LoadPayload) => InstantiatedSource | PromiseLike<InstantiatedSource>;
}
/** @public */
export declare interface NapiModule {
imports: {
env: any
napi: any
emnapi: any
}
exports: any
loaded: boolean
filename: string
childThread: boolean
emnapi: {
/**
* Synchronize data between the wasm memory and an ArrayBuffer / view.
*
* Note: when a non-shared wasm memory has grown, a view over the
* detached old buffer is re-created over the current buffer through the
* intrinsic base-class constructor, so for view inputs the returned view
* may be a base-class instance (e.g. `Uint8Array` or `DataView`)
* instead of the subclass that was passed in.
*/
syncMemory<T extends ArrayBuffer | ArrayBufferView> (
js_to_wasm: boolean,
arrayBufferOrView: T,
offset?: number,
len?: number
): T extends ArrayBufferView ? ArrayBufferView : T
getMemoryAddress (arrayBufferOrView: ArrayBuffer | ArrayBufferView): PointerInfo
addSendListener (worker: any): boolean
}
init (options: InitOptions): any
initWorker (arg: number, func: [number, number]): void
postMessage?: (msg: any) => any
waitThreadStart: boolean | number
/* Excluded from this release type: PThread */}
/** @public */
export declare interface NodeBinding {
node: {
emitAsyncInit: Function
emitAsyncDestroy: Function
makeCallback: Function
}
napi: {
asyncInit: Function
asyncDestroy: Function
makeCallback: Function
}
}
/** @public */
export declare type PluginContext = any
/** @public */
export declare type PluginFactory = (ctx: PluginContext) => EmnapiPlugin
/** @public */
export declare interface PointerInfo {
address: number
ownership: ReferenceOwnership
runtimeAllocated: 0 | 1
}
export declare interface ReuseWorkerOptions {
size: number;
strict?: boolean;
}
export declare interface SpawnThreadPayload {
startArg: number;
errorOrTid: number;
}
export declare interface StartPayload {
tid: number;
arg: number;
sab?: Int32Array;
}
export declare interface StartResult {
exitCode: number;
instance: WebAssembly.Instance;
}
export declare interface TerminateAllThreadsPayload {
}
export declare class ThreadManager {
unusedWorkers: WorkerLike[];
pthreads: Record<number, WorkerLike>;
get nextWorkerID(): number;
wasmModule: WebAssembly.Module | null;
wasmMemory: WebAssembly.Memory | null;
private readonly messageEvents;
private readonly _childThread;
private readonly _onCreateWorker;
private readonly _reuseWorker;
private readonly _beforeLoad?;
readonly printErr: (message: string) => void;
threadSpawn?: ((startArg: number, errorOrTid?: number) => number);
constructor(options: ThreadManagerOptions);
init(): void;
initMainThread(): void;
private preparePool;
shouldPreloadWorkers(): boolean;
loadWasmModuleToAllWorkers(): Promise<WorkerLike[]>;
preloadWorkers(): Promise<WorkerLike[]>;
setup(wasmModule: WebAssembly.Module, wasmMemory: WebAssembly.Memory): void;
markId(worker: WorkerLike): number;
returnWorkerToPool(worker: WorkerLike): void;
loadWasmModuleToWorker(worker: WorkerLike, sab?: Int32Array): Promise<WorkerLike>;
allocateUnusedWorker(): WorkerLike;
getNewWorker(sab?: Int32Array): WorkerLike | undefined;
cleanThread(worker: WorkerLike, tid: number, force?: boolean): void;
terminateWorker(worker: WorkerLike): void;
terminateAllThreads(): void;
addMessageEventListener(worker: WorkerLike, onMessage: (e: WorkerMessageEvent) => void): () => void;
fireMessageEvent(worker: WorkerLike, e: WorkerMessageEvent): void;
}
export declare type ThreadManagerOptions = ThreadManagerOptionsMain | ThreadManagerOptionsChild;
export declare interface ThreadManagerOptionsBase {
printErr?: (message: string) => void;
threadSpawn?: (startArg: number, errorOrTid?: number) => number;
}
export declare interface ThreadManagerOptionsChild extends ThreadManagerOptionsBase {
childThread: true;
}
export declare interface ThreadManagerOptionsMain extends ThreadManagerOptionsBase {
beforeLoad?: (worker: WorkerLike) => any;
reuseWorker?: boolean | number | ReuseWorkerOptions;
onCreateWorker: WorkerFactory;
childThread?: false;
}
export declare class ThreadMessageHandler {
protected instance: WebAssembly.Instance | undefined;
private messagesBeforeLoad;
protected postMessage: (message: any) => void;
protected onLoad?: (data: LoadPayload) => WebAssembly.WebAssemblyInstantiatedSource | PromiseLike<WebAssembly.WebAssemblyInstantiatedSource>;
protected onError: (error: Error, type: WorkerMessageType) => void;
constructor(options?: ThreadMessageHandlerOptions);
instantiate(data: LoadPayload): WebAssembly.WebAssemblyInstantiatedSource | PromiseLike<WebAssembly.WebAssemblyInstantiatedSource>;
handle(e: WorkerMessageEvent<MessageEventData<WorkerMessageType>>): void;
private _load;
private _start;
protected _loaded(err: Error | null, source: WebAssembly.WebAssemblyInstantiatedSource | null, payload: LoadPayload): void;
protected handleAfterLoad<E extends WorkerMessageEvent>(e: E, f: (e: E) => void): void;
}
export declare interface ThreadMessageHandlerOptions {
onLoad?: (data: LoadPayload) => WebAssembly.WebAssemblyInstantiatedSource | PromiseLike<WebAssembly.WebAssemblyInstantiatedSource>;
onError?: (error: Error, type: WorkerMessageType) => void;
postMessage?: (message: any) => void;
}
export declare const version: string;
export declare interface WASIInstance {
readonly wasiImport?: Record<string, any>;
initialize(instance: object): void;
start(instance: object): number;
getImportObject?(): any;
}
export declare class WASIThreads {
PThread: ThreadManager | undefined;
private wasmMemory;
private wasmInstance;
private readonly threadSpawn;
readonly childThread: boolean;
private readonly postMessage;
readonly wasi: WASIInstance;
constructor(options: WASIThreadsOptions);
getImportObject(): {
wasi: WASIThreadsImports;
};
setup(wasmInstance: WebAssembly.Instance, wasmModule: WebAssembly.Module, wasmMemory?: WebAssembly.Memory): void;
preloadWorkers(): Promise<WorkerLike[]>;
initialize(instance: WebAssembly.Instance, module: WebAssembly.Module, memory?: WebAssembly.Memory): WebAssembly.Instance;
start(instance: WebAssembly.Instance, module: WebAssembly.Module, memory?: WebAssembly.Memory): StartResult;
terminateAllThreads(): void;
}
export declare interface WASIThreadsImports {
'thread-spawn': (startArg: number, errorOrTid?: number) => number;
}
export declare type WASIThreadsOptions = MainThreadOptions | ChildThreadOptions;
export declare type WorkerFactory = (ctx: {
type: string;
name: string;
}) => WorkerLike;
export declare type WorkerLike = (Worker | Worker_2) & {
whenLoaded?: Promise<WorkerLike>;
loaded?: boolean;
__emnapi_tid?: number;
};
export declare interface WorkerMessageEvent<T = any> {
data: T;
}
export declare type WorkerMessageType = 'load' | 'start';
export { }

View File

@@ -0,0 +1,366 @@
import type { Context } from '@emnapi/runtime';
import type { ReferenceOwnership } from '@emnapi/runtime';
import type { Worker as Worker_2 } from 'worker_threads';
/** @public */
export declare type BaseCreateOptions = {
filename?: string
nodeBinding?: NodeBinding
reuseWorker?: ThreadManagerOptionsMain['reuseWorker']
asyncWorkPoolSize?: number
waitThreadStart?: MainThreadBaseOptions['waitThreadStart']
onCreateWorker?: (info: CreateWorkerInfo) => any
print?: (str: string) => void
printErr?: (str: string) => void
postMessage?: (msg: any) => any
plugins?: (PluginFactory | EmnapiPlugin)[]
}
export declare interface BaseOptions {
wasi: WASIInstance;
version?: 'preview1';
wasm64?: boolean;
}
export declare interface ChildThreadOptions extends BaseOptions {
childThread: true;
postMessage?: (data: any) => void;
}
export declare interface CleanupThreadPayload {
tid: number;
}
export declare interface CommandInfo<T extends CommandType> {
type: T;
payload: CommandPayloadMap[T];
}
export declare interface CommandPayloadMap {
load: LoadPayload;
loaded: LoadedPayload;
start: StartPayload;
'cleanup-thread': CleanupThreadPayload;
'terminate-all-threads': TerminateAllThreadsPayload;
'spawn-thread': SpawnThreadPayload;
}
export declare type CommandType = keyof CommandPayloadMap;
export declare function createInstanceProxy(instance: WebAssembly.Instance, memory?: WebAssembly.Memory | (() => WebAssembly.Memory)): WebAssembly.Instance;
/** @public */
export declare function createNapiModule (
options: CreateOptions
): NapiModule
/** @public */
export declare type CreateOptions = BaseCreateOptions & ({
context: Context
childThread?: boolean
} | {
context?: Context
childThread: true
})
/** @public */
export declare interface CreateWorkerInfo {
type: 'thread' | 'async-work'
name: string
}
/** @public */
export declare interface EmnapiPlugin {
importObject?: (originalImports: WebAssembly.Imports) => (WebAssembly.Imports | void)
}
/** @public */
export declare interface InitOptions {
instance: WebAssembly.Instance
module: WebAssembly.Module
memory?: WebAssembly.Memory
table?: WebAssembly.Table
}
export declare type InputType = string | URL | Response | BufferSource | WebAssembly.Module;
export declare interface InstantiatedSource extends LoadedSource {
napiModule: NapiModule;
}
export declare function instantiateNapiModule(wasmInput: InputType | Promise<InputType>, options: InstantiateOptions): Promise<InstantiatedSource>;
export declare function instantiateNapiModuleSync(wasmInput: BufferSource | WebAssembly.Module, options: InstantiateOptions): InstantiatedSource;
export declare type InstantiateOptions = CreateOptions & LoadOptions;
export declare function isSharedArrayBuffer(value: any): value is SharedArrayBuffer;
export declare function isTrapError(e: Error): e is WebAssembly.RuntimeError;
export declare interface LoadedPayload {
}
export declare interface LoadedSource extends WebAssembly.WebAssemblyInstantiatedSource {
usedInstance: WebAssembly.Instance;
}
export declare function loadNapiModule(napiModule: NapiModule, wasmInput: InputType | Promise<InputType>, options?: LoadOptions): Promise<LoadedSource>;
export declare function loadNapiModuleSync(napiModule: NapiModule, wasmInput: BufferSource | WebAssembly.Module, options?: LoadOptions): LoadedSource;
export declare interface LoadOptions {
wasi?: WASIInstance;
overwriteImports?: (importObject: WebAssembly.Imports) => WebAssembly.Imports;
beforeInit?: (source: WebAssembly.WebAssemblyInstantiatedSource) => void;
getMemory?: (exports: WebAssembly.Exports) => WebAssembly.Memory;
getTable?: (exports: WebAssembly.Exports) => WebAssembly.Table;
}
export declare interface LoadPayload {
wasmModule: WebAssembly.Module;
wasmMemory: WebAssembly.Memory;
sab?: Int32Array;
}
export declare interface MainThreadBaseOptions extends BaseOptions {
waitThreadStart?: boolean | number;
}
export declare type MainThreadOptions = MainThreadOptionsWithThreadManager | MainThreadOptionsCreateThreadManager;
export declare interface MainThreadOptionsCreateThreadManager extends MainThreadBaseOptions, ThreadManagerOptionsMain {
}
export declare interface MainThreadOptionsWithThreadManager extends MainThreadBaseOptions {
threadManager?: ThreadManager | (() => ThreadManager);
}
export declare interface MessageEventData<T extends CommandType> {
__emnapi__: CommandInfo<T>;
}
export declare class MessageHandler extends ThreadMessageHandler {
napiModule: NapiModule | undefined;
constructor(options: MessageHandlerOptions);
instantiate(data: LoadPayload): InstantiatedSource | PromiseLike<InstantiatedSource>;
handle(e: WorkerMessageEvent): void;
}
export declare interface MessageHandlerOptions extends ThreadMessageHandlerOptions {
onLoad: (data: LoadPayload) => InstantiatedSource | PromiseLike<InstantiatedSource>;
}
/** @public */
export declare interface NapiModule {
imports: {
env: any
napi: any
emnapi: any
}
exports: any
loaded: boolean
filename: string
childThread: boolean
emnapi: {
/**
* Synchronize data between the wasm memory and an ArrayBuffer / view.
*
* Note: when a non-shared wasm memory has grown, a view over the
* detached old buffer is re-created over the current buffer through the
* intrinsic base-class constructor, so for view inputs the returned view
* may be a base-class instance (e.g. `Uint8Array` or `DataView`)
* instead of the subclass that was passed in.
*/
syncMemory<T extends ArrayBuffer | ArrayBufferView> (
js_to_wasm: boolean,
arrayBufferOrView: T,
offset?: number,
len?: number
): T extends ArrayBufferView ? ArrayBufferView : T
getMemoryAddress (arrayBufferOrView: ArrayBuffer | ArrayBufferView): PointerInfo
addSendListener (worker: any): boolean
}
init (options: InitOptions): any
initWorker (arg: number, func: [number, number]): void
postMessage?: (msg: any) => any
waitThreadStart: boolean | number
/* Excluded from this release type: PThread */}
/** @public */
export declare interface NodeBinding {
node: {
emitAsyncInit: Function
emitAsyncDestroy: Function
makeCallback: Function
}
napi: {
asyncInit: Function
asyncDestroy: Function
makeCallback: Function
}
}
/** @public */
export declare type PluginContext = any
/** @public */
export declare type PluginFactory = (ctx: PluginContext) => EmnapiPlugin
/** @public */
export declare interface PointerInfo {
address: number
ownership: ReferenceOwnership
runtimeAllocated: 0 | 1
}
export declare interface ReuseWorkerOptions {
size: number;
strict?: boolean;
}
export declare interface SpawnThreadPayload {
startArg: number;
errorOrTid: number;
}
export declare interface StartPayload {
tid: number;
arg: number;
sab?: Int32Array;
}
export declare interface StartResult {
exitCode: number;
instance: WebAssembly.Instance;
}
export declare interface TerminateAllThreadsPayload {
}
export declare class ThreadManager {
unusedWorkers: WorkerLike[];
pthreads: Record<number, WorkerLike>;
get nextWorkerID(): number;
wasmModule: WebAssembly.Module | null;
wasmMemory: WebAssembly.Memory | null;
private readonly messageEvents;
private readonly _childThread;
private readonly _onCreateWorker;
private readonly _reuseWorker;
private readonly _beforeLoad?;
readonly printErr: (message: string) => void;
threadSpawn?: ((startArg: number, errorOrTid?: number) => number);
constructor(options: ThreadManagerOptions);
init(): void;
initMainThread(): void;
private preparePool;
shouldPreloadWorkers(): boolean;
loadWasmModuleToAllWorkers(): Promise<WorkerLike[]>;
preloadWorkers(): Promise<WorkerLike[]>;
setup(wasmModule: WebAssembly.Module, wasmMemory: WebAssembly.Memory): void;
markId(worker: WorkerLike): number;
returnWorkerToPool(worker: WorkerLike): void;
loadWasmModuleToWorker(worker: WorkerLike, sab?: Int32Array): Promise<WorkerLike>;
allocateUnusedWorker(): WorkerLike;
getNewWorker(sab?: Int32Array): WorkerLike | undefined;
cleanThread(worker: WorkerLike, tid: number, force?: boolean): void;
terminateWorker(worker: WorkerLike): void;
terminateAllThreads(): void;
addMessageEventListener(worker: WorkerLike, onMessage: (e: WorkerMessageEvent) => void): () => void;
fireMessageEvent(worker: WorkerLike, e: WorkerMessageEvent): void;
}
export declare type ThreadManagerOptions = ThreadManagerOptionsMain | ThreadManagerOptionsChild;
export declare interface ThreadManagerOptionsBase {
printErr?: (message: string) => void;
threadSpawn?: (startArg: number, errorOrTid?: number) => number;
}
export declare interface ThreadManagerOptionsChild extends ThreadManagerOptionsBase {
childThread: true;
}
export declare interface ThreadManagerOptionsMain extends ThreadManagerOptionsBase {
beforeLoad?: (worker: WorkerLike) => any;
reuseWorker?: boolean | number | ReuseWorkerOptions;
onCreateWorker: WorkerFactory;
childThread?: false;
}
export declare class ThreadMessageHandler {
protected instance: WebAssembly.Instance | undefined;
private messagesBeforeLoad;
protected postMessage: (message: any) => void;
protected onLoad?: (data: LoadPayload) => WebAssembly.WebAssemblyInstantiatedSource | PromiseLike<WebAssembly.WebAssemblyInstantiatedSource>;
protected onError: (error: Error, type: WorkerMessageType) => void;
constructor(options?: ThreadMessageHandlerOptions);
instantiate(data: LoadPayload): WebAssembly.WebAssemblyInstantiatedSource | PromiseLike<WebAssembly.WebAssemblyInstantiatedSource>;
handle(e: WorkerMessageEvent<MessageEventData<WorkerMessageType>>): void;
private _load;
private _start;
protected _loaded(err: Error | null, source: WebAssembly.WebAssemblyInstantiatedSource | null, payload: LoadPayload): void;
protected handleAfterLoad<E extends WorkerMessageEvent>(e: E, f: (e: E) => void): void;
}
export declare interface ThreadMessageHandlerOptions {
onLoad?: (data: LoadPayload) => WebAssembly.WebAssemblyInstantiatedSource | PromiseLike<WebAssembly.WebAssemblyInstantiatedSource>;
onError?: (error: Error, type: WorkerMessageType) => void;
postMessage?: (message: any) => void;
}
export declare const version: string;
export declare interface WASIInstance {
readonly wasiImport?: Record<string, any>;
initialize(instance: object): void;
start(instance: object): number;
getImportObject?(): any;
}
export declare class WASIThreads {
PThread: ThreadManager | undefined;
private wasmMemory;
private wasmInstance;
private readonly threadSpawn;
readonly childThread: boolean;
private readonly postMessage;
readonly wasi: WASIInstance;
constructor(options: WASIThreadsOptions);
getImportObject(): {
wasi: WASIThreadsImports;
};
setup(wasmInstance: WebAssembly.Instance, wasmModule: WebAssembly.Module, wasmMemory?: WebAssembly.Memory): void;
preloadWorkers(): Promise<WorkerLike[]>;
initialize(instance: WebAssembly.Instance, module: WebAssembly.Module, memory?: WebAssembly.Memory): WebAssembly.Instance;
start(instance: WebAssembly.Instance, module: WebAssembly.Module, memory?: WebAssembly.Memory): StartResult;
terminateAllThreads(): void;
}
export declare interface WASIThreadsImports {
'thread-spawn': (startArg: number, errorOrTid?: number) => number;
}
export declare type WASIThreadsOptions = MainThreadOptions | ChildThreadOptions;
export declare type WorkerFactory = (ctx: {
type: string;
name: string;
}) => WorkerLike;
export declare type WorkerLike = (Worker | Worker_2) & {
whenLoaded?: Promise<WorkerLike>;
loaded?: boolean;
__emnapi_tid?: number;
};
export declare interface WorkerMessageEvent<T = any> {
data: T;
}
export declare type WorkerMessageType = 'load' | 'start';
export { }

8142
client/node_modules/@emnapi/core/dist/emnapi-core.full.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

7227
client/node_modules/@emnapi/core/dist/emnapi-core.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,5 @@
import { PluginFactory } from '../emnapi-core'
export { PluginFactory, PluginContext, EmnapiPlugin } from '../emnapi-core'
declare const _default: PluginFactory
export default _default

View File

@@ -0,0 +1,818 @@
//#region src/emnapi/async-work.js
function asyncWork (emnapiPluginCtx) {
const { emnapiCtx, emnapiNodeBinding, emnapiAsyncWorkPoolSize } = emnapiPluginCtx;
var mod = (function (exports, emnapi_shared, emscripten_runtime) {
//#region src/async-work.ts
/**
* @__deps $emnapiCtx
* @__deps $emnapiEnv
* @__deps $emnapiNodeBinding
* @__deps $emnapiAsyncWorkPoolSize
* @__postset
* ```
* emnapiAWST.init();
* ```
*/
var emnapiAWST = {
idGen: {},
values: [undefined],
queued: new Set(),
pending: [],
init: function () {
const idGen = {
nextId: 1,
list: [],
generate: function () {
let id;
if (idGen.list.length) {
id = idGen.list.shift();
}
else {
id = idGen.nextId;
idGen.nextId++;
}
return id;
},
reuse: function (id) {
idGen.list.push(id);
}
};
emnapiAWST.idGen = idGen;
emnapiAWST.values = [undefined];
emnapiAWST.queued = new Set();
emnapiAWST.pending = [];
},
create: function (env, resource, resourceName, execute, complete, data) {
let asyncId = 0;
let triggerAsyncId = 0;
if (emnapiNodeBinding) {
const asyncContext = emnapiNodeBinding.node.emitAsyncInit(resource, resourceName, -1);
asyncId = asyncContext.asyncId;
triggerAsyncId = asyncContext.triggerAsyncId;
}
const id = emnapiAWST.idGen.generate();
emnapiAWST.values[id] = {
env,
id,
resource,
asyncId,
triggerAsyncId,
status: 0,
execute,
complete,
data
};
return id;
},
callComplete: function (work, status) {
const complete = work.complete;
const env = work.env;
const data = work.data;
const callback = () => {
if (!complete)
return;
const envObject = emnapi_shared.emnapiEnv;
const scope = emnapiCtx.openScope(envObject);
try {
envObject.callbackIntoModule(true, () => {
(emnapiPluginCtx.wasmTable.get(complete))(env, status, data);
});
}
finally {
emnapiCtx.closeScope(envObject, scope);
}
};
if (emnapiNodeBinding) {
emnapiNodeBinding.node.makeCallback(work.resource, callback, [], {
asyncId: work.asyncId,
triggerAsyncId: work.triggerAsyncId
});
}
else {
callback();
}
},
queue: function (id) {
const work = emnapiAWST.values[id];
if (!work)
return;
if (work.status === 0) {
work.status = 1;
if (emnapiAWST.queued.size >= (Math.abs(emnapiAsyncWorkPoolSize) || 4)) {
emnapiAWST.pending.push(id);
return;
}
emnapiAWST.queued.add(id);
const env = work.env;
const data = work.data;
const execute = work.execute;
work.status = 2;
emnapiCtx.features.setImmediate(() => {
(emnapiPluginCtx.wasmTable.get(execute))(env, data);
emnapiAWST.queued.delete(id);
work.status = 3;
emnapiCtx.features.setImmediate(() => {
emnapiAWST.callComplete(work, 0 /* napi_status.napi_ok */);
});
if (emnapiAWST.pending.length > 0) {
const nextWorkId = emnapiAWST.pending.shift();
emnapiAWST.values[nextWorkId].status = 0;
emnapiAWST.queue(nextWorkId);
}
});
}
},
cancel: function (id) {
const index = emnapiAWST.pending.indexOf(id);
if (index !== -1) {
const work = emnapiAWST.values[id];
if (work && (work.status === 1)) {
work.status = 4;
emnapiAWST.pending.splice(index, 1);
emnapiCtx.features.setImmediate(() => {
emnapiAWST.callComplete(work, 11 /* napi_status.napi_cancelled */);
});
return 0 /* napi_status.napi_ok */;
}
else {
return 9 /* napi_status.napi_generic_failure */;
}
}
return 9 /* napi_status.napi_generic_failure */;
},
remove: function (id) {
const work = emnapiAWST.values[id];
if (!work)
return;
if (emnapiNodeBinding) {
emnapiNodeBinding.node.emitAsyncDestroy({
asyncId: work.asyncId,
triggerAsyncId: work.triggerAsyncId
});
}
emnapiAWST.values[id] = undefined;
emnapiAWST.idGen.reuse(id);
}
};
//#endregion src/async-work.ts
//#region src/macro.ts
//#endregion src/macro.ts
//#region src/core/async-work.ts
const {
// onCreateWorker, napiModule, singleThreadAsyncWork, _emnapi_async_work_pool_size,
// PThread, ENVIRONMENT_IS_NODE, ENVIRONMENT_IS_PTHREAD, wasmInstance, _free, wasmMemory, _malloc,
_emnapi_node_emit_async_init, _emnapi_node_emit_async_destroy, _emnapi_runtime_keepalive_pop, _emnapi_runtime_keepalive_push } = emnapiPluginCtx;
var emnapiAWMT = {
pool: [],
workerReady: null,
globalAddress: 0,
globalOffset: {
idle_threads: 0,
q: 1 * 4,
next: 1 * 4,
prev: 2 * 4,
mutex: 3 * 4,
cond: 4 * 4,
exit_message: 5 * 4,
end: 7 * 4
},
offset: {
/* napi_ref */ resource: 0,
/* double */ async_id: 8,
/* double */ trigger_async_id: 16,
/* napi_env */ env: 24,
/* int32_t */ status: 1 * 4 + 24, // 0 for pending, 1 for cancelled, 2 for completed
queue: 2 * 4 + 24,
queue_next: 2 * 4 + 24,
queue_prev: 3 * 4 + 24,
/* void* */ data: 4 * 4 + 24,
/* napi_async_execute_callback */ execute: 5 * 4 + 24,
/* napi_async_complete_callback */ complete: 6 * 4 + 24,
end: 7 * 4 + 24
},
/**
* When another thread grows the shared WebAssembly.Memory, this agent's
* cached `wasmMemory.buffer` may still have the old shorter length
* (V8 refreshes it lazily). If a pointer derived from shared memory lies
* beyond the cached length, `wasmMemory.grow(0)` forces the agent to
* observe the current memory size and refreshes the buffer.
*/
ensureBufferFor(end) {
let buffer = emscripten_runtime.wasmMemory.buffer;
if (end > buffer.byteLength) {
emscripten_runtime.wasmMemory.grow(0);
buffer = emscripten_runtime.wasmMemory.buffer;
}
return buffer;
},
init() {
emnapiAWMT.pool = [];
emnapiAWMT.workerReady = null;
if (typeof emscripten_runtime.PThread !== 'undefined') {
emscripten_runtime.PThread.unusedWorkers.forEach(emnapiAWMT.addListener);
Object.values(emscripten_runtime.PThread.pthreads).forEach(emnapiAWMT.addListener);
const __original_getNewWorker = emscripten_runtime.PThread.getNewWorker;
emscripten_runtime.PThread.getNewWorker = function () {
const r = __original_getNewWorker.apply(this, arguments);
emnapiAWMT.addListener(r);
return r;
};
}
},
addListener(worker) {
if (!worker)
return false;
if (worker._emnapiAWMTListener)
return true;
const handler = function (e) {
const data = emscripten_runtime.ENVIRONMENT_IS_NODE ? e : e.data;
const __emnapi__ = data.__emnapi__;
if (__emnapi__) {
const type = __emnapi__.type;
const payload = __emnapi__.payload;
if (type === 'async-work-complete') {
emnapiAWMT.callComplete(payload.work, 0 /* napi_status.napi_ok */);
}
}
};
const dispose = function () {
if (emscripten_runtime.ENVIRONMENT_IS_NODE) {
worker.off('message', handler);
}
else {
worker.removeEventListener('message', handler, false);
}
delete worker._emnapiAWMTListener;
};
worker._emnapiAWMTListener = { handler, dispose };
if (emscripten_runtime.ENVIRONMENT_IS_NODE) {
worker.on('message', handler);
}
else {
worker.addEventListener('message', handler, false);
}
return true;
},
initGlobal() {
if (!emnapiAWMT.globalAddress) {
emnapiAWMT.globalAddress = emscripten_runtime._malloc(emnapiAWMT.globalOffset.end);
emnapiAWMT.globalAddress >>>= 0;
const size = emnapiAWMT.globalOffset.end;
const addr = emnapiAWMT.globalAddress;
new Uint8Array(emnapiAWMT.ensureBufferFor(addr + size), addr, size).fill(0);
emnapiAWMT.queueInit(emnapiAWMT.globalAddress + emnapiAWMT.globalOffset.q);
emnapiAWMT.queueInit(emnapiAWMT.globalAddress + emnapiAWMT.globalOffset.exit_message);
}
},
terminateWorkers() {
emnapiAWMT.pool.forEach(w => {
w._emnapiAWMTListener?.dispose();
w._emnapiTSFNListener?.dispose();
w.terminate();
});
emnapiAWMT.pool.length = 0;
},
initWorkers(n) {
if (emscripten_runtime.ENVIRONMENT_IS_PTHREAD) {
return emnapiAWMT.workerReady || (emnapiAWMT.workerReady = Promise.resolve());
}
if (emnapiAWMT.workerReady)
return emnapiAWMT.workerReady;
if (!('emnapi_async_worker_create' in emscripten_runtime.wasmInstance.exports)) {
throw new TypeError('`emnapi_async_worker_create` is not exported, please try to add `--export=emnapi_async_worker_create` to linker flags');
}
const emnapi_async_worker_create = emscripten_runtime.wasmInstance.exports.emnapi_async_worker_create;
const args = [];
emnapiAWMT.initGlobal();
for (let i = 0; i < n; ++i) {
args.push(emnapi_async_worker_create(1, emnapiAWMT.globalAddress));
}
const promises = args.map(index => {
if (index === 0) {
return Promise.reject(new Error('Failed to create async worker'));
}
let worker;
if (index < 0) {
worker = emnapiAWMT.pool[-index - 1];
if (worker)
return worker.whenLoaded;
}
index >>>= 0;
const tidOffset = 20;
const view = new DataView(emnapiAWMT.ensureBufferFor(index + tidOffset + 4));
const tid = view.getInt32(index + tidOffset, true);
worker = emscripten_runtime.PThread.pthreads[tid];
return worker.whenLoaded;
});
emnapiAWMT.workerReady = Promise.all(promises);
return emnapiAWMT.workerReady;
},
getResource(work) {
emnapiAWMT.ensureBufferFor(work + emnapiAWMT.offset.resource + 4);
var HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer), GET_HEAP_DATA_VIEW = () => HEAP_DATA_VIEW.buffer === emnapiPluginCtx.wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer));
return GET_HEAP_DATA_VIEW().getUint32(work + emnapiAWMT.offset.resource, true);
},
getExecute(work) {
emnapiAWMT.ensureBufferFor(work + emnapiAWMT.offset.execute + 4);
var HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer), GET_HEAP_DATA_VIEW = () => HEAP_DATA_VIEW.buffer === emnapiPluginCtx.wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer));
return GET_HEAP_DATA_VIEW().getUint32(work + emnapiAWMT.offset.execute, true);
},
getComplete(work) {
emnapiAWMT.ensureBufferFor(work + emnapiAWMT.offset.complete + 4);
var HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer), GET_HEAP_DATA_VIEW = () => HEAP_DATA_VIEW.buffer === emnapiPluginCtx.wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer));
return GET_HEAP_DATA_VIEW().getUint32(work + emnapiAWMT.offset.complete, true);
},
getEnv(work) {
emnapiAWMT.ensureBufferFor(work + emnapiAWMT.offset.env + 4);
var HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer), GET_HEAP_DATA_VIEW = () => HEAP_DATA_VIEW.buffer === emnapiPluginCtx.wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer));
return GET_HEAP_DATA_VIEW().getUint32(work + emnapiAWMT.offset.env, true);
},
getData(work) {
emnapiAWMT.ensureBufferFor(work + emnapiAWMT.offset.data + 4);
var HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer), GET_HEAP_DATA_VIEW = () => HEAP_DATA_VIEW.buffer === emnapiPluginCtx.wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer));
return GET_HEAP_DATA_VIEW().getUint32(work + emnapiAWMT.offset.data, true);
},
getMutex() {
const index = emnapiAWMT.globalAddress + emnapiAWMT.globalOffset.mutex;
const mutex = {
lock() {
const isBrowserMain = typeof window !== 'undefined' && typeof document !== 'undefined' && !emscripten_runtime.ENVIRONMENT_IS_NODE;
const i32a = new Int32Array(emnapiAWMT.ensureBufferFor(index + 4), index, 1);
if (isBrowserMain) {
while (true) {
const oldValue = Atomics.compareExchange(i32a, 0, 0, 10);
if (oldValue === 0) {
return;
}
}
}
else {
while (true) {
const oldValue = Atomics.compareExchange(i32a, 0, 0, 10);
if (oldValue === 0) {
return;
}
Atomics.wait(i32a, 0, 10);
}
}
},
unlock() {
const i32a = new Int32Array(emnapiAWMT.ensureBufferFor(index + 4), index, 1);
const oldValue = Atomics.compareExchange(i32a, 0, 10, 0);
if (oldValue !== 10) {
throw new Error('Tried to unlock while not holding the mutex');
}
Atomics.notify(i32a, 0, 1);
},
execute(fn) {
mutex.lock();
try {
return fn();
}
finally {
mutex.unlock();
}
}
};
return mutex;
},
getCond() {
const index = emnapiAWMT.globalAddress + emnapiAWMT.globalOffset.cond;
const mutex = emnapiAWMT.getMutex();
const cond = {
wait() {
const i32a = new Int32Array(emnapiAWMT.ensureBufferFor(index + 4), index, 1);
const value = Atomics.load(i32a, 0);
mutex.unlock();
Atomics.wait(i32a, 0, value);
mutex.lock();
},
signal() {
const i32a = new Int32Array(emnapiAWMT.ensureBufferFor(index + 4), index, 1);
Atomics.add(i32a, 0, 1);
Atomics.notify(i32a, 0, 1);
}
};
return cond;
},
queueInit(q) {
emnapiAWMT.ensureBufferFor(q + 4 + 4);
var HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer), GET_HEAP_DATA_VIEW = () => HEAP_DATA_VIEW.buffer === emnapiPluginCtx.wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer));
GET_HEAP_DATA_VIEW().setUint32(q, q, true);
GET_HEAP_DATA_VIEW().setUint32(q + 4, q, true);
},
queueInsertTail(h, q) {
emnapiAWMT.ensureBufferFor(h + 4 + 4);
emnapiAWMT.ensureBufferFor(q + 4 + 4);
var HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer), GET_HEAP_DATA_VIEW = () => HEAP_DATA_VIEW.buffer === emnapiPluginCtx.wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer));
GET_HEAP_DATA_VIEW().setUint32(q, h, true);
const tempValue = GET_HEAP_DATA_VIEW().getUint32(h + 4, true);
GET_HEAP_DATA_VIEW().setUint32(q + 4, tempValue, true);
const qprev = GET_HEAP_DATA_VIEW().getUint32(q + 4, true);
GET_HEAP_DATA_VIEW().setUint32(qprev, q, true);
GET_HEAP_DATA_VIEW().setUint32(h + 4, q, true);
},
queueRemove(q) {
emnapiAWMT.ensureBufferFor(q + 4 + 4);
var HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer), GET_HEAP_DATA_VIEW = () => HEAP_DATA_VIEW.buffer === emnapiPluginCtx.wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer));
const qprev = GET_HEAP_DATA_VIEW().getUint32(q + 4, true);
const qnext = GET_HEAP_DATA_VIEW().getUint32(q, true);
GET_HEAP_DATA_VIEW().setUint32(qprev, qnext, true);
GET_HEAP_DATA_VIEW().setUint32(qnext + 4, qprev, true);
},
queueEmpty(q) {
emnapiAWMT.ensureBufferFor(q + 4);
var HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer), GET_HEAP_DATA_VIEW = () => HEAP_DATA_VIEW.buffer === emnapiPluginCtx.wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer));
// eslint-disable-next-line eqeqeq
return q == GET_HEAP_DATA_VIEW().getUint32(q, true);
},
scheduleWork: function (work) {
if (!emnapiAWMT.workerReady?.ready) {
emnapiAWMT.initWorkers(emnapi_shared._emnapi_async_work_pool_size()).then(() => {
emnapiAWMT.workerReady.ready = true;
}).catch((err) => {
emnapiAWMT.workerReady = null;
throw err;
});
}
_emnapi_runtime_keepalive_push();
emnapiCtx.increaseWaitingRequestCounter();
const statusBuffer = new Int32Array(emnapiAWMT.ensureBufferFor(work + emnapiAWMT.offset.status + 4), work + emnapiAWMT.offset.status, 1);
Atomics.store(statusBuffer, 0, 0 /* AsyncWorkStatus.Pending */);
const mutex = emnapiAWMT.getMutex();
const cond = emnapiAWMT.getCond();
mutex.lock();
try {
emnapiAWMT.queueInsertTail(emnapiAWMT.globalAddress + emnapiAWMT.globalOffset.q, work + emnapiAWMT.offset.queue);
}
catch (err) {
_emnapi_runtime_keepalive_pop();
emnapiCtx.decreaseWaitingRequestCounter();
mutex.unlock();
throw err;
}
emnapiAWMT.ensureBufferFor(emnapiAWMT.globalAddress + emnapiAWMT.globalOffset.idle_threads + 4);
var HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer), GET_HEAP_DATA_VIEW = () => HEAP_DATA_VIEW.buffer === emnapiPluginCtx.wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer));
if (GET_HEAP_DATA_VIEW().getUint32(emnapiAWMT.globalAddress + emnapiAWMT.globalOffset.idle_threads, true) > 0) {
cond.signal();
}
mutex.unlock();
},
cancelWork(work) {
let cancelled = false;
emnapiAWMT.getMutex().execute(() => {
emnapiAWMT.ensureBufferFor(work + emnapiAWMT.offset.status + 4);
var HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer), GET_HEAP_DATA_VIEW = () => HEAP_DATA_VIEW.buffer === emnapiPluginCtx.wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer));
cancelled = !emnapiAWMT.queueEmpty(work + emnapiAWMT.offset.queue) && GET_HEAP_DATA_VIEW().getInt32(work + emnapiAWMT.offset.status, true) !== 2 /* AsyncWorkStatus.Completed */;
if (cancelled) {
emnapiAWMT.queueRemove(work + emnapiAWMT.offset.queue);
}
});
if (!cancelled) {
return 9 /* napi_status.napi_generic_failure */;
}
if (Atomics.compareExchange(new Int32Array(emnapiAWMT.ensureBufferFor(work + emnapiAWMT.offset.status + 4), work + emnapiAWMT.offset.status, 1), 0, 0 /* AsyncWorkStatus.Pending */, 1 /* AsyncWorkStatus.Cancelled */) !== 0 /* AsyncWorkStatus.Pending */) {
return 9 /* napi_status.napi_generic_failure */;
}
emnapiCtx.features.setImmediate(() => {
emnapiAWMT.callComplete(work, 11 /* napi_status.napi_cancelled */);
});
return 0 /* napi_status.napi_ok */;
},
callComplete: function (work, status) {
_emnapi_runtime_keepalive_pop();
emnapiCtx.decreaseWaitingRequestCounter();
const complete = emnapiAWMT.getComplete(work);
const env = emnapiAWMT.getEnv(work);
const data = emnapiAWMT.getData(work);
const envObject = emnapi_shared.emnapiEnv;
const scope = emnapiCtx.openScope(envObject);
const callback = () => {
if (!complete)
return;
envObject.callbackIntoModule(true, () => {
(emnapiPluginCtx.wasmTable.get(complete))(env, status, data);
});
};
try {
if (emnapiNodeBinding) {
const resource = emnapiAWMT.getResource(work);
const resource_value = emnapiCtx.getRef(resource).get();
const resourceObject = emnapiCtx.jsValueFromNapiValue(resource_value);
const view = new DataView(emnapiAWMT.ensureBufferFor(work + emnapiAWMT.offset.trigger_async_id + 8));
const asyncId = view.getFloat64(work + emnapiAWMT.offset.async_id, true);
const triggerAsyncId = view.getFloat64(work + emnapiAWMT.offset.trigger_async_id, true);
emnapiNodeBinding.node.makeCallback(resourceObject, callback, [], {
asyncId,
triggerAsyncId
});
}
else {
callback();
}
}
finally {
emnapiCtx.closeScope(envObject, scope);
}
}
};
emnapiAWST.init();
emnapiAWMT.init();
/** @__sig ippppppp */
var napi_create_async_work = emnapi_shared.singleThreadAsyncWork
? function (env, resource, resource_name, execute, complete, data, result) {
if (!env)
return 1 /* napi_status.napi_invalid_arg */;
// @ts-expect-error
const envObject = emnapi_shared.emnapiEnv;
envObject.checkGCAccess();
if (!execute)
return envObject.setLastError(1 /* napi_status.napi_invalid_arg */);
if (!result)
return envObject.setLastError(1 /* napi_status.napi_invalid_arg */);
let resourceObject;
if (resource) {
resourceObject = Object(emnapiCtx.jsValueFromNapiValue(resource));
}
else {
resourceObject = {};
}
if (!resource_name)
return envObject.setLastError(1 /* napi_status.napi_invalid_arg */);
const resourceName = String(emnapiCtx.jsValueFromNapiValue(resource_name));
const id = emnapiAWST.create(env, resourceObject, resourceName, execute, complete, data);
result >>>= 0;
var HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer), GET_HEAP_DATA_VIEW = () => HEAP_DATA_VIEW.buffer === emnapiPluginCtx.wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer));
GET_HEAP_DATA_VIEW().setUint32(result, id, true);
return envObject.clearLastError();
}
: function (env, resource, resource_name, execute, complete, data, result) {
if (!env)
return 1 /* napi_status.napi_invalid_arg */;
// @ts-expect-error
const envObject = emnapi_shared.emnapiEnv;
envObject.checkGCAccess();
if (!execute)
return envObject.setLastError(1 /* napi_status.napi_invalid_arg */);
if (!result)
return envObject.setLastError(1 /* napi_status.napi_invalid_arg */);
let resourceObject;
if (resource) {
resourceObject = Object(emnapiCtx.jsValueFromNapiValue(resource));
}
else {
resourceObject = {};
}
if (!resource_name)
return envObject.setLastError(1 /* napi_status.napi_invalid_arg */);
const sizeofAW = emnapiAWMT.offset.end;
let aw = emscripten_runtime._malloc(sizeofAW);
if (!aw)
return envObject.setLastError(9 /* napi_status.napi_generic_failure */);
aw >>>= 0;
new Uint8Array(emnapiAWMT.ensureBufferFor(aw + sizeofAW)).subarray(aw, aw + sizeofAW).fill(0);
const s = emnapiCtx.napiValueFromJsValue(resourceObject);
const resourceRef = emnapiCtx.createReference(envObject, s, 1, 1 /* ReferenceOwnership.kUserland */);
const resource_ = resourceRef.id;
var HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer), GET_HEAP_DATA_VIEW = () => HEAP_DATA_VIEW.buffer === emnapiPluginCtx.wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer));
GET_HEAP_DATA_VIEW().setUint32(aw, resource_, true);
_emnapi_node_emit_async_init(s, resource_name, -1, aw + emnapiAWMT.offset.async_id);
GET_HEAP_DATA_VIEW().setUint32(aw + emnapiAWMT.offset.env, env, true);
GET_HEAP_DATA_VIEW().setUint32(aw + emnapiAWMT.offset.execute, execute, true);
GET_HEAP_DATA_VIEW().setUint32(aw + emnapiAWMT.offset.complete, complete, true);
GET_HEAP_DATA_VIEW().setUint32(aw + emnapiAWMT.offset.data, data, true);
emnapiAWMT.queueInit(aw + emnapiAWMT.offset.queue);
result >>>= 0;
GET_HEAP_DATA_VIEW().setUint32(result, aw, true);
return envObject.clearLastError();
};
/** @__sig ipp */
var napi_delete_async_work = emnapi_shared.singleThreadAsyncWork
? function (env, work) {
if (!env)
return 1 /* napi_status.napi_invalid_arg */;
// @ts-expect-error
const envObject = emnapi_shared.emnapiEnv;
envObject.checkGCAccess();
if (!work)
return envObject.setLastError(1 /* napi_status.napi_invalid_arg */);
work >>>= 0;
emnapiAWST.remove(work);
return envObject.clearLastError();
}
: function (env, work) {
if (!env)
return 1 /* napi_status.napi_invalid_arg */;
// @ts-expect-error
const envObject = emnapi_shared.emnapiEnv;
envObject.checkGCAccess();
if (!work)
return envObject.setLastError(1 /* napi_status.napi_invalid_arg */);
work >>>= 0;
const resource = emnapiAWMT.getResource(work);
emnapiCtx.getRef(resource).dispose();
if (emnapiNodeBinding) {
const view = new DataView(emnapiAWMT.ensureBufferFor(work + emnapiAWMT.offset.trigger_async_id + 8));
const asyncId = view.getFloat64(work + emnapiAWMT.offset.async_id, true);
const triggerAsyncId = view.getFloat64(work + emnapiAWMT.offset.trigger_async_id, true);
_emnapi_node_emit_async_destroy(asyncId, triggerAsyncId);
}
emscripten_runtime._free(work);
return envObject.clearLastError();
};
/** @__sig ipp */
var napi_queue_async_work = emnapi_shared.singleThreadAsyncWork
? function (env, work) {
if (!env)
return 1 /* napi_status.napi_invalid_arg */;
const envObject = emnapi_shared.emnapiEnv;
if (!work)
return envObject.setLastError(1 /* napi_status.napi_invalid_arg */);
work >>>= 0;
emnapiAWST.queue(work);
return envObject.clearLastError();
}
: function (env, work) {
if (!env)
return 1 /* napi_status.napi_invalid_arg */;
const envObject = emnapi_shared.emnapiEnv;
if (!work)
return envObject.setLastError(1 /* napi_status.napi_invalid_arg */);
work >>>= 0;
emnapiAWMT.scheduleWork(work);
return envObject.clearLastError();
};
/** @__sig ipp */
var napi_cancel_async_work = emnapi_shared.singleThreadAsyncWork
? function (env, work) {
if (!env)
return 1 /* napi_status.napi_invalid_arg */;
const envObject = emnapi_shared.emnapiEnv;
if (!work)
return envObject.setLastError(1 /* napi_status.napi_invalid_arg */);
work >>>= 0;
const status = emnapiAWST.cancel(work);
if (status === 0 /* napi_status.napi_ok */)
return envObject.clearLastError();
return envObject.setLastError(status);
}
: function (env, work) {
if (!env)
return 1 /* napi_status.napi_invalid_arg */;
const envObject = emnapi_shared.emnapiEnv;
if (!work)
return envObject.setLastError(1 /* napi_status.napi_invalid_arg */);
work >>>= 0;
const status = emnapiAWMT.cancelWork(work);
if (status === 0 /* napi_status.napi_ok */)
return envObject.clearLastError();
return envObject.setLastError(status);
};
/** @__sig pp */
function _emnapi_async_worker(globalAddress) {
globalAddress >>>= 0;
emnapiAWMT.globalAddress = globalAddress;
const mutex = emnapiAWMT.getMutex();
const cond = emnapiAWMT.getCond();
mutex.lock();
const exitMessageAddr = globalAddress + emnapiAWMT.globalOffset.exit_message;
const idleThreadsAddr = globalAddress + emnapiAWMT.globalOffset.idle_threads;
const workerQueueAddr = globalAddress + emnapiAWMT.globalOffset.q;
var HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer), GET_HEAP_DATA_VIEW = () => HEAP_DATA_VIEW.buffer === emnapiPluginCtx.wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer));
for (;;) {
emnapiAWMT.ensureBufferFor(workerQueueAddr + 4);
while (emnapiAWMT.queueEmpty(workerQueueAddr)) {
Atomics.add(new Int32Array(emnapiAWMT.ensureBufferFor(idleThreadsAddr + 4), idleThreadsAddr, 1), 0, 1);
cond.wait();
Atomics.sub(new Int32Array(emnapiAWMT.ensureBufferFor(idleThreadsAddr + 4), idleThreadsAddr, 1), 0, 1);
}
const q = GET_HEAP_DATA_VIEW().getUint32(workerQueueAddr, true);
if (q === exitMessageAddr) {
cond.signal();
mutex.unlock();
break;
}
const work = q - emnapiAWMT.offset.queue;
emnapiAWMT.queueRemove(q);
emnapiAWMT.queueInit(q);
mutex.unlock();
const statusBuffer = new Int32Array(emnapiAWMT.ensureBufferFor(work + emnapiAWMT.offset.status + 4), work + emnapiAWMT.offset.status, 1);
if (Atomics.load(statusBuffer, 0) === 1 /* AsyncWorkStatus.Cancelled */) {
emscripten_runtime.abort('unreachable');
}
const execute = emnapiAWMT.getExecute(work);
const env = emnapiAWMT.getEnv(work);
const data = emnapiAWMT.getData(work);
(emnapiPluginCtx.wasmTable.get(execute))(env, data);
Atomics.store(statusBuffer, 0, 2 /* AsyncWorkStatus.Completed */);
const postMessage = emnapi_shared.napiModule.postMessage;
postMessage({
__emnapi__: {
type: 'async-work-complete',
payload: { work }
}
});
mutex.lock();
}
return 0;
}
/** @__sig ipp */
function _emnapi_spawn_worker(f, globalAddress) {
if (typeof emnapi_shared.onCreateWorker !== 'function') {
throw new TypeError('`options.onCreateWorker` is not a function');
}
const promises = [];
const args = [];
if (!('emnapi_async_worker_create' in emscripten_runtime.wasmInstance.exports)) {
throw new TypeError('`emnapi_async_worker_create` is not exported, please try to add `--export=emnapi_async_worker_create` to linker flags');
}
args.push(emscripten_runtime.wasmInstance.exports.emnapi_async_worker_create(0, 0));
const handleError = (e) => {
if ('message' in e && (e.message.indexOf('RuntimeError') !== -1 || e.message.indexOf('unreachable') !== -1)) {
emnapiAWMT.terminateWorkers();
}
};
let ret;
try {
const worker = emnapi_shared.onCreateWorker({ type: 'async-work', name: 'emnapi-async-worker' });
const p = emscripten_runtime.PThread.loadWasmModuleToWorker(worker);
if (emscripten_runtime.ENVIRONMENT_IS_NODE) {
worker.on('error', handleError);
}
else {
worker.addEventListener('error', handleError, false);
}
emnapiAWMT.addListener(worker);
if (typeof emnapiPluginCtx.emnapiTSFN !== 'undefined') {
emnapiPluginCtx.emnapiTSFN.addListener(worker);
}
promises.push(p.then(() => {
if (typeof worker.unref === 'function') {
worker.unref();
}
}));
ret = emnapiAWMT.pool.push(worker) - 1;
const arg = args[0];
worker.threadBlockBase = arg;
worker.postMessage({
__emnapi__: {
type: 'async-worker-init',
payload: { arg, func: [f, globalAddress] }
}
});
}
catch (err) {
const arg = args[0];
emscripten_runtime._free(arg);
throw err;
}
return ret;
}
function initWorker(startArg, func) {
if (emnapi_shared.napiModule.childThread) {
if (typeof emscripten_runtime.wasmInstance.exports.emnapi_async_worker_init !== 'function') {
throw new TypeError('`emnapi_async_worker_init` is not exported, please try to add `--export=emnapi_async_worker_init` to linker flags');
}
emscripten_runtime.wasmInstance.exports.emnapi_async_worker_init(startArg);
(emnapiPluginCtx.wasmTable.get(func[0]))(func[1]);
}
else {
throw new Error('startThread is only available in child threads');
}
}
emnapi_shared.napiModule.initWorker = initWorker;
//#endregion src/core/async-work.ts
exports._emnapi_async_worker = _emnapi_async_worker;
exports._emnapi_spawn_worker = _emnapi_spawn_worker;
exports.napi_cancel_async_work = napi_cancel_async_work;
exports.napi_create_async_work = napi_create_async_work;
exports.napi_delete_async_work = napi_delete_async_work;
exports.napi_queue_async_work = napi_queue_async_work;
return exports;
})({}, emnapiPluginCtx, emnapiPluginCtx);
return {
importObject: (original) => {
Object.keys(mod).forEach(key => {
if (key.startsWith('napi_') || key.startsWith('node_api_')) {
original.napi[key] = mod[key];
} else {
original.env[key] = mod[key];
}
});
}
};
}
//#endregion src/emnapi/async-work.js
export { asyncWork as default };

View File

@@ -0,0 +1,4 @@
export { PluginFactory, PluginContext, EmnapiPlugin } from '../emnapi-core'
export { default as v8 } from './v8'
export { default as asyncWork } from './async-work'
export { default as tsfn } from './threadsafe-function'

View File

@@ -0,0 +1,3 @@
export { default as v8 } from './v8.js'
export { default as asyncWork } from './async-work.js'
export { default as tsfn } from './threadsafe-function.js'

View File

@@ -0,0 +1,5 @@
import { PluginFactory } from '../emnapi-core'
export { PluginFactory, PluginContext, EmnapiPlugin } from '../emnapi-core'
declare const _default: PluginFactory
export default _default

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,5 @@
import { PluginFactory } from '../emnapi-core'
export { PluginFactory, PluginContext, EmnapiPlugin } from '../emnapi-core'
declare const _default: PluginFactory
export default _default

1446
client/node_modules/@emnapi/core/dist/plugins/v8.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

39
client/node_modules/@emnapi/core/package.json generated vendored Normal file
View File

@@ -0,0 +1,39 @@
{
"name": "@emnapi/core",
"version": "2.0.0-alpha.3",
"description": "emnapi core",
"type": "module",
"main": "./dist/emnapi-core.js",
"module": "./dist/emnapi-core.js",
"types": "./dist/emnapi-core.d.ts",
"sideEffects": false,
"exports": {
".": "./dist/emnapi-core.js",
"./plugins": "./dist/plugins/index.js",
"./plugins/index": "./dist/plugins/index.js",
"./plugins/v8": "./dist/plugins/v8.js",
"./plugins/async-work": "./dist/plugins/async-work.js",
"./plugins/threadsafe-function": "./dist/plugins/threadsafe-function.js",
"./package.json": "./package.json"
},
"dependencies": {
"@emnapi/wasi-threads": "2.0.1",
"tslib": "^2.4.0"
},
"scripts": {
"build": "node ./script/build.js && rollup -c"
},
"repository": {
"type": "git",
"url": "git+https://github.com/toyobayashi/emnapi.git"
},
"author": "toyobayashi",
"license": "MIT",
"bugs": {
"url": "https://github.com/toyobayashi/emnapi/issues"
},
"homepage": "https://github.com/toyobayashi/emnapi#readme",
"publishConfig": {
"access": "public"
}
}

60
client/node_modules/@emnapi/core/rollup.config.js generated vendored Normal file
View File

@@ -0,0 +1,60 @@
import { defineConfig } from '@emnapi/shared'
import pkg from './package.json' with { type: 'json' }
import { join, dirname } from 'path'
import fs from 'fs'
const plugins = [
['v8', 'v8', 'emnapiCorePluginsV8'],
['asyncWork', 'async-work', 'emnapiCorePluginsAsyncWork'],
['tsfn', 'threadsafe-function', 'emnapiCorePluginsThreadSafeFunction']
]
export default [
...defineConfig({
outputName: 'emnapiCore',
outputFile: 'emnapi-core',
defines: {
__VERSION__: JSON.stringify(pkg.version)
},
external: ['@emnapi/wasi-threads'],
plugins: [
{
name: 'rollup-plugin-create-plugin-entry',
writeBundle (outputOptions) {
const distDir = dirname(outputOptions.file)
fs.mkdirSync(join(distDir, 'plugins'), { recursive: true })
const entryFile = join(distDir, 'plugins', 'index.js')
const dtsEntryFile = join(distDir, 'plugins', 'index.d.ts')
let content = ''
for (const [name, file] of plugins) {
content += `export { default as ${name} } from './${file}.js'\n`
}
let dtsContent = "export { PluginFactory, PluginContext, EmnapiPlugin } from '../emnapi-core'\n"
for (const [name, file] of plugins) {
dtsContent += `export { default as ${name} } from './${file}'\n`
}
fs.writeFileSync(entryFile, content, 'utf8')
fs.writeFileSync(dtsEntryFile, dtsContent, 'utf8')
}
}
]
}),
...defineConfig({
outputFile: 'emnapi-core.full',
defines: {
__VERSION__: JSON.stringify(pkg.version)
},
}),
...plugins.flatMap(([_, name, outputName]) => defineConfig({
outputName,
outputFile: `plugins/${name}`,
dtsEntry: `dist/types/emnapi/${name}.d.ts`,
staticDtsContent: (code) => code.replace(/\.\/index/g, '../emnapi-core'),
input: join(import.meta.dirname, `src/emnapi/${name}.js`),
compilerOptions: {
declaration: false,
declarationMap: false,
declarationDir: undefined
}
}))
]

21
client/node_modules/@emnapi/runtime/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2021-present Toyobayashi
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

1
client/node_modules/@emnapi/runtime/README.md generated vendored Normal file
View File

@@ -0,0 +1 @@
See [https://github.com/toyobayashi/emnapi](https://github.com/toyobayashi/emnapi)

828
client/node_modules/@emnapi/runtime/dist/emnapi.d.ts generated vendored Normal file
View File

@@ -0,0 +1,828 @@
/// <reference lib="esnext.disposable" />
export declare type Ptr = number | bigint
export declare interface IBuffer extends Uint8Array {
toString (encoding?: string, start?: number, end?: number): string
}
export declare interface BufferCtor {
readonly prototype: IBuffer
/** @deprecated */
new (...args: any[]): IBuffer
from: {
(buffer: ArrayBufferLike): IBuffer
(buffer: ArrayBufferLike, byteOffset: number, length: number): IBuffer
}
alloc: (size: number) => IBuffer
isBuffer: (obj: unknown) => obj is IBuffer
}
export declare const enum Constant {
HOLE,
EMPTY,
UNDEFINED,
NULL,
FALSE,
TRUE,
GLOBAL,
EMPTY_STRING,
}
export declare const enum Version {
NODE_API_SUPPORTED_VERSION_MIN = 1,
NODE_API_DEFAULT_MODULE_API_VERSION = 8,
NODE_API_SUPPORTED_VERSION_MAX = 10,
NODE_MODULE_VERSION = 127,
NAPI_VERSION_EXPERIMENTAL = 2147483647 // INT_MAX
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
export declare type Pointer<T> = number | bigint
// eslint-disable-next-line @typescript-eslint/no-unused-vars
export declare type PointerPointer<T> = number
export declare type FunctionPointer<T extends (...args: any[]) => any> = Pointer<T>
export declare type Const<T> = T
export declare type void_p = Pointer<void>
export declare type void_pp = Pointer<void_p>
export declare type bool = number
export declare type char = number
export declare type char_p = Pointer<char>
export declare type unsigned_char = number
export declare type const_char = Const<char>
export declare type const_char_p = Pointer<const_char>
export declare type char16_t = number
export declare type const_char16_t = number
export declare type char16_t_p = Pointer<char16_t>
export declare type const_char16_t_p = Pointer<const_char16_t>
export declare type short = number
export declare type unsigned_short = number
export declare type int = number
export declare type unsigned_int = number
export declare type long = number
export declare type unsigned_long = number
export declare type long_long = bigint
export declare type unsigned_long_long = bigint
export declare type float = number
export declare type double = number
export declare type long_double = number
export declare type size_t = number
export declare type int8_t = number
export declare type uint8_t = number
export declare type int16_t = number
export declare type uint16_t = number
export declare type int32_t = number
export declare type uint32_t = number
export declare type int64_t = bigint
export declare type uint64_t = bigint
export declare type napi_env = Pointer<unknown>
export declare type napi_value = Pointer<unknown>
export declare type napi_ref = Pointer<unknown>
export declare type napi_deferred = Pointer<unknown>
export declare type napi_handle_scope = Pointer<unknown>
export declare type napi_escapable_handle_scope = Pointer<unknown>
export declare type napi_addon_register_func = FunctionPointer<(env: napi_env, exports: napi_value) => napi_value>
export declare type napi_callback_info = Pointer<unknown>
export declare type napi_callback = FunctionPointer<(env: napi_env, info: napi_callback_info) => napi_value>
export declare interface napi_extended_error_info {
error_message: const_char_p
engine_reserved: void_p
engine_error_code: uint32_t
error_code: napi_status
}
export declare interface napi_property_descriptor {
// One of utf8name or name should be NULL.
utf8name: const_char_p
name: napi_value
method: napi_callback
getter: napi_callback
setter: napi_callback
value: napi_value
/* napi_property_attributes */
attributes: number
data: void_p
}
export declare type napi_finalize = FunctionPointer<(
env: napi_env,
finalize_data: void_p,
finalize_hint: void_p
) => void>
export declare interface node_module {
nm_version: int32_t
nm_flags: uint32_t
nm_filename: Pointer<const_char>
nm_register_func: napi_addon_register_func
nm_modname: Pointer<const_char>
nm_priv: Pointer<void>
reserved: PointerPointer<void>
}
export declare interface napi_node_version {
major: uint32_t
minor: uint32_t
patch: uint32_t
release: const_char_p
}
export declare interface emnapi_emscripten_version {
major: uint32_t
minor: uint32_t
patch: uint32_t
}
export declare const enum napi_status {
napi_ok,
napi_invalid_arg,
napi_object_expected,
napi_string_expected,
napi_name_expected,
napi_function_expected,
napi_number_expected,
napi_boolean_expected,
napi_array_expected,
napi_generic_failure,
napi_pending_exception,
napi_cancelled,
napi_escape_called_twice,
napi_handle_scope_mismatch,
napi_callback_scope_mismatch,
napi_queue_full,
napi_closing,
napi_bigint_expected,
napi_date_expected,
napi_arraybuffer_expected,
napi_detachable_arraybuffer_expected,
napi_would_deadlock, // unused
napi_no_external_buffers_allowed,
napi_cannot_run_js
}
export declare const enum napi_property_attributes {
napi_default = 0,
napi_writable = 1 << 0,
napi_enumerable = 1 << 1,
napi_configurable = 1 << 2,
// Used with napi_define_class to distinguish static properties
// from instance properties. Ignored by napi_define_properties.
napi_static = 1 << 10,
/// #ifdef NAPI_EXPERIMENTAL
// Default for class methods.
napi_default_method = napi_writable | napi_configurable,
// Default for object properties, like in JS obj[prop].
napi_default_jsproperty = napi_writable | napi_enumerable | napi_configurable
/// #endif // NAPI_EXPERIMENTAL
}
export declare const enum napi_valuetype {
napi_undefined,
napi_null,
napi_boolean,
napi_number,
napi_string,
napi_symbol,
napi_object,
napi_function,
napi_external,
napi_bigint
}
export declare const enum napi_typedarray_type {
napi_int8_array,
napi_uint8_array,
napi_uint8_clamped_array,
napi_int16_array,
napi_uint16_array,
napi_int32_array,
napi_uint32_array,
napi_float32_array,
napi_float64_array,
napi_bigint64_array,
napi_biguint64_array,
napi_float16_array,
}
export declare const enum napi_key_collection_mode {
napi_key_include_prototypes,
napi_key_own_only
}
export declare const enum napi_key_filter {
napi_key_all_properties = 0,
napi_key_writable = 1,
napi_key_enumerable = 1 << 1,
napi_key_configurable = 1 << 2,
napi_key_skip_strings = 1 << 3,
napi_key_skip_symbols = 1 << 4
}
export declare const enum napi_key_conversion {
napi_key_keep_numbers,
napi_key_numbers_to_strings
}
export declare const enum emnapi_memory_view_type {
emnapi_int8_array,
emnapi_uint8_array,
emnapi_uint8_clamped_array,
emnapi_int16_array,
emnapi_uint16_array,
emnapi_int32_array,
emnapi_uint32_array,
emnapi_float32_array,
emnapi_float64_array,
emnapi_bigint64_array,
emnapi_biguint64_array,
emnapi_float16_array,
emnapi_data_view = -1,
emnapi_buffer = -2
}
export declare const enum napi_threadsafe_function_call_mode {
napi_tsfn_nonblocking,
napi_tsfn_blocking
}
export declare const enum napi_threadsafe_function_release_mode {
napi_tsfn_release,
napi_tsfn_abort
}
export declare class ArrayStore<T extends {
id: number | bigint;
}> extends BaseArrayStore<T> {
protected _allocator: IdAllocator;
constructor(initialCapacity?: number);
insert(value: T): void;
alloc<P extends any[]>(factory: (...args: P) => T, ...args: P): T;
dealloc(id: number | bigint): void;
}
export declare class BaseArrayStore<T> extends Disposable_2 implements ObjectAllocator<T> {
protected _values: [undefined, ...(T | undefined)[]];
constructor(initialCapacity?: number);
assign(id: number | bigint, value: T): T;
deref<R extends T = T>(id: number | bigint): R | undefined;
alloc<P extends any[]>(factory: (...args: P) => T, ...args: P): T;
dealloc(id: number | bigint): void;
dispose(): void;
}
export declare type CleanupHookCallbackFunction = number | ((arg: number) => void);
export declare class Context {
private _isStopping;
private _canCallIntoJs;
private _suppressDestroy;
private envStore;
refStore: Map<number, Reference>;
private readonly refCounter?;
private readonly cleanupQueue;
readonly features: Features;
readonly isolate: Isolate;
constructor(options?: ContextOptions);
getIsolate(): Isolate;
suppressDestroy(): void;
getRuntimeVersions(): {
version: string;
NODE_API_SUPPORTED_VERSION_MAX: Version;
NAPI_VERSION_EXPERIMENTAL: Version;
NODE_API_DEFAULT_MODULE_API_VERSION: Version;
NODE_MODULE_VERSION: Version;
};
createNotSupportWeakRefError(api: string, message: string): NotSupportWeakRefError;
createNotSupportBufferError(api: string, message: string): NotSupportBufferError;
createReference(envObject: Env, handle_id: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership): Reference;
createReferenceWithData(envObject: Env, handle_id: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership, data: void_p): Reference;
createReferenceWithFinalizer(envObject: Env, handle_id: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership, finalize_callback?: napi_finalize, finalize_data?: void_p, finalize_hint?: void_p): Reference;
createResolver<T>(): Resolver<T>;
adjustAmountOfExternalAllocatedMemory(changeInBytes: number | bigint): bigint;
createEnv(filename: string, moduleApiVersion: number, bridge: EnvNativeBridge, nodeBinding?: any): Env;
createFunction(envObject: Env, napiCallback: (env: napi_env, info: napi_callback_info) => void_p, data: number | bigint, name: string, dynamicExecution: boolean): Function;
createTrackedFinalizer(envObject: Env, finalize_callback: napi_finalize, finalize_data: void_p, finalize_hint: void_p): TrackedFinalizer;
getCurrentScope(): HandleScope;
openScope(envObject: Env): HandleScope;
closeScope(envObject: Env, scope?: HandleScope): void;
getEnv(env: napi_env): Env | undefined;
getRef(ref: napi_ref): Reference | undefined;
getHandleScope(scope: napi_handle_scope): HandleScope | undefined;
getCallbackInfo(info: napi_callback_info): ICallbackInfo;
napiValueFromJsValue(value: unknown): number | bigint;
jsValueFromNapiValue<T = any>(napiValue: number | bigint): T | undefined;
createExternal(data: number | bigint): External_2;
getExternalValue(external: External_2): number | bigint;
isExternal(value: unknown): boolean;
addCleanupHook(envObject: Env, fn: CleanupHookCallbackFunction, arg: number): void;
removeCleanupHook(envObject: Env, fn: CleanupHookCallbackFunction, arg: number): void;
runCleanup(): void;
increaseWaitingRequestCounter(): void;
decreaseWaitingRequestCounter(): void;
setCanCallIntoJs(value: boolean): void;
setStopping(value: boolean): void;
canCallIntoJs(): boolean;
getDylinkMetadata(binary: WebAssembly.Module | Uint8Array): DylinkMetadata;
destroy(): void;
}
export declare interface ContextOptions extends IsolateOptions {
}
export declare class CountIdAllocator extends Disposable_2 implements IdAllocator {
next: number;
constructor(initialNext?: number);
aquire(): number;
release(_: number): void;
dispose(): void;
}
export declare class CountIdReuseAllocator extends CountIdAllocator implements IdAllocator {
private _freeList;
aquire(): number;
release(id: number): void;
dispose(): void;
}
export declare function createContext(options?: ContextOptions): Context;
export declare function deletePrivate(obj: any, key: Private): boolean;
declare abstract class Disposable_2 implements globalThis.Disposable {
abstract dispose(): void;
[Symbol.dispose](): void;
}
export { Disposable_2 as Disposable }
export declare interface DylinkMetadata {
neededDynlibs: string[];
tlsExports: Set<string>;
weakImports: Set<string>;
runtimePaths: string[];
memorySize: number;
memoryAlign: number;
tableSize: number;
tableAlign: number;
}
export declare class EmnapiError extends Error {
constructor(message?: string);
}
export declare abstract class Env extends Disposable_2 {
id: number | bigint;
openHandleScopes: number;
instanceData: TrackedFinalizer | null;
lastException: Persistent<any>;
refs: number;
reflist: RefTracker;
finalizing_reflist: RefTracker;
pendingFinalizers: RefTracker[];
moduleApiVersion: number;
filename: string;
nodeBinding?: any;
inGcFinalizer: boolean;
bridge: EnvNativeBridge;
readonly ctx: Context;
private store;
constructor(ctx: Context, store: ArrayStore<Env>, bridge: EnvNativeBridge);
canCallIntoJs(): boolean;
terminatedOrTerminating(): boolean;
ref(): void;
unref(): void;
clearLastError(): napi_status;
setLastError(error_code: napi_status, engine_error_code?: uint32_t, engine_reserved?: number): napi_status;
callIntoModule<T>(fn: (env: Env) => T, handleException?: (envObject: Env, value: any) => void): T;
abstract callFinalizer(cb: napi_finalize, data: void_p, hint: void_p): void;
invokeFinalizerFromGC(finalizer: RefTracker): void;
checkGCAccess(): void;
enqueueFinalizer(finalizer: RefTracker): void;
dequeueFinalizer(finalizer: RefTracker): void;
deleteMe(): void;
dispose(): void;
private readonly _bindingMap;
initObjectBinding<S extends object>(value: S): IReferenceBinding;
getObjectBinding<S extends object>(value: S): IReferenceBinding;
setInstanceData(data: number, finalize_cb: number, finalize_hint: number): void;
getInstanceData(): number | bigint;
}
export declare interface EnvNativeBridge {
address: number;
deleteEnv: (ptr: number) => void;
setLastError: (env: napi_env, error_code: napi_status, engine_error_code: uint32_t, engine_reserved: number) => void;
makeDynCall_vppp: (cb: Ptr) => (a: Ptr, b: Ptr, c: Ptr) => void;
makeDynCall_vp: (cb: Ptr) => (a: Ptr) => void;
abort: (msg?: string) => never;
wasm64?: boolean;
}
declare interface External_2 extends Record<any, any> {
}
declare const External_2: {
new (value: number | bigint): External_2;
prototype: null;
};
export { External_2 as External }
export declare interface Features {
makeDynamicFunction: ((...args: any[]) => Function) | undefined;
getGlobalThis: () => typeof globalThis;
setFunctionName: ((fn: Function, name: string) => void) | undefined;
Reflect: typeof Reflect | undefined;
finalizer: boolean;
weakSymbol: boolean;
BigInt: typeof BigInt | undefined;
MessageChannel: typeof MessageChannel | undefined;
Buffer: BufferCtor | undefined;
setImmediate: (callback: () => void) => any;
withResolvers: <T>(this: PromiseConstructor) => Resolver<T>;
}
export declare class Finalizer {
envObject: Env;
private _finalizeCallback;
private _finalizeData;
private _finalizeHint;
private _makeDynCall_vppp;
constructor(envObject: Env, _finalizeCallback?: napi_finalize, _finalizeData?: void_p, _finalizeHint?: void_p);
copy(): Finalizer;
move(target: Finalizer): void;
callback(): napi_finalize;
data(): void_p;
hint(): void_p;
resetEnv(): void;
resetFinalizer(): void;
callFinalizer(): void;
dispose(): void;
}
export declare class FunctionTemplate extends Template {
callback: (info: napi_callback_info, v8FunctionCallback: Ptr) => Ptr;
v8FunctionCallback: Ptr;
data: any;
className: string | undefined;
signature: Signature | undefined;
private _instanceTemplate;
private _prototypeTemplate;
private _cached;
constructor(ctx: Isolate, callback: (info: napi_callback_info, v8FunctionCallback: Ptr) => Ptr, v8FunctionCallback: Ptr, data: any, signature?: Signature);
setClassName(name: string): void;
instanceTemplate(): ObjectTemplate;
prototypeTemplate(): ObjectTemplate;
getFunction(): (...args: any[]) => any;
}
export declare function getDefaultContext(): Context;
export declare function getDylinkMetadata(binary: WebAssembly.Module | Uint8Array): DylinkMetadata;
export declare function getExternalValue(external: External_2): number | bigint;
export declare function getInternalField(instance: object, index: number): any;
export declare function getPrivate(obj: any, key: Private): any;
export declare class HandleScope extends Disposable_2 {
handleStore: HandleStore;
id: number | bigint;
parent: HandleScope | null;
child: HandleScope | null;
start: number;
end: number;
private _escapeCalled;
callbackInfo: ICallbackInfo;
static create(parentScope: HandleScope | null, handleStore: HandleStore, start?: number, end?: number): HandleScope;
constructor(parentScope: HandleScope | null, handleStore: HandleStore, start?: number, end?: number);
reuse(parentScope: HandleScope): void;
add<V>(value: V): number;
addExternal(data: number | bigint): number;
dispose(): void;
escape(handle: number): number;
escapeCalled(): boolean;
}
export declare class HandleStore extends BaseArrayStore<any> {
static MIN_ID: 8;
private _allocator;
private _features;
readonly refValues: Map<number, PersistentValueType<any>>;
private _erase;
private _deref;
constructor(features: Features);
isOutOfScope(id: number): boolean;
deepDeref<R = any>(id: number | bigint): R | undefined;
push<S>(value: S): number;
erase(start: number, end: number, weak: boolean): void;
swap(a: number, b: number): void;
}
export declare function hasPrivate(obj: any, key: Private): boolean;
export declare interface ICallbackInfo {
thiz: any;
holder: any;
data: void_p;
args: ArrayLike<any>;
fn: Function;
}
export declare interface IdAllocator extends Disposable_2 {
aquire(): number;
release(id: number): void;
}
export declare interface IReferenceBinding {
wrapped: number;
tag: Uint32Array | null;
}
export declare function isExternal(object: unknown): object is External_2;
export declare class Isolate {
private _lastException;
private _globalThis;
private _scopeStore;
private _handleStore;
private _externalMemory;
globalHandleStore: PersistentStore;
readonly features: Features;
constructor(options?: IsolateOptions);
napiValueFromJsValue(value: unknown): number | bigint;
jsValueFromNapiValue<T = any>(napiValue: number | bigint): T | undefined;
deleteRefSlotValue(id: number | bigint): void;
getRefSlotValue(id: number | bigint): PersistentValueType<any>;
setRefSlotValue(id: number | bigint, ref: PersistentValueType<any>): void;
createReference<T>(...args: [T] | []): Persistent<T>;
insertRef<T>(persistent: Persistent<T>): void;
getRef<T = any>(ref: napi_ref): Persistent<T> | undefined;
removeRef(ref: napi_ref, force?: boolean): void;
getTryCatch(address: number | bigint): TryCatch | undefined;
pushTryCatch(address: number | bigint): TryCatch;
popTryCatch(address: number | bigint): void;
setLastException(err: any): void;
throwException(err: any): any;
hasPendingException(): boolean;
getAndClearLastException(): any;
adjustAmountOfExternalAllocatedMemory(changeInBytes: number | bigint): bigint;
createSignature(template: FunctionTemplate): Signature;
createObjectTemplate(constructor: any): ObjectTemplate;
setInternalField(obj: any, index: number, value: any): void;
getInternalField(obj: any, index: number): any;
getInternalFieldCount(obj: any): number;
createFunctionTemplate(callback: (info: napi_callback_info, v8FunctionCallback: Ptr) => Ptr, v8FunctionCallback: Ptr, data: any, signature?: Signature): FunctionTemplate;
isScopeEmpty(): boolean;
getCurrentScope(): HandleScope;
openScope(): HandleScope;
closeScope(_scope?: HandleScope): void;
getHandleScope(scope: napi_handle_scope): HandleScope | undefined;
getCallbackInfo(info: napi_callback_info): ICallbackInfo;
createExternal(data: number | bigint): External_2;
getExternalValue(external: External_2): number | bigint;
isExternal(value: unknown): boolean;
createResolver<T>(): Resolver<T>;
createPrivate(name: string): Private;
getOrCreateGlobalPrivate(name: string): Private;
setPrivate(obj: any, key: Private, value: any): void;
getPrivate(obj: any, key: Private): any;
hasPrivate(obj: any, key: Private): boolean;
deletePrivate(obj: any, key: Private): boolean;
}
export declare interface IsolateOptions {
features?: Partial<Features>;
onExternalMemoryChange?: (current: bigint, old: bigint, delta: bigint) => any;
}
export declare function isReferenceType(v: any): v is object;
export declare const NAPI_VERSION_EXPERIMENTAL = Version.NAPI_VERSION_EXPERIMENTAL;
export declare const NODE_API_DEFAULT_MODULE_API_VERSION = Version.NODE_API_DEFAULT_MODULE_API_VERSION;
export declare const NODE_API_SUPPORTED_VERSION_MAX = Version.NODE_API_SUPPORTED_VERSION_MAX;
export declare const NODE_API_SUPPORTED_VERSION_MIN = Version.NODE_API_SUPPORTED_VERSION_MIN;
export declare class NodeEnv extends Env {
destructing: boolean;
finalizationScheduled: boolean;
constructor(ctx: Context, store: ArrayStore<Env>, bridge: EnvNativeBridge);
deleteMe(): void;
canCallIntoJs(): boolean;
triggerFatalException(err: any): void;
callbackIntoModule<T>(enforceUncaughtExceptionPolicy: boolean, fn: (env: Env) => T): T;
callFinalizer(cb: napi_finalize, data: void_p, hint: void_p): void;
callFinalizerInternal(forceUncaught: int, cb: napi_finalize, data: void_p, hint: void_p): void;
enqueueFinalizer(finalizer: RefTracker): void;
drainFinalizerQueue(): void;
}
export declare class NotSupportBufferError extends EmnapiError {
constructor(api: string, message: string);
}
export declare class NotSupportWeakRefError extends EmnapiError {
constructor(api: string, message: string);
}
export declare interface ObjectAllocator<T> extends Disposable_2 {
deref<R extends T = T>(id: number | bigint): R | undefined;
alloc<P extends any[]>(factory: (...args: P) => T, ...args: P): T;
dealloc(id: number | bigint): void;
}
export declare class ObjectTemplate extends Template {
Ctor: any;
internalFieldCount: number;
private _accessors;
constructor(ctx: Isolate, Ctor?: any);
setAccessor(name: string | symbol, getterWrap: (property: Ptr, info: Ptr, getter: Ptr) => Ptr, setterWrap: (property: Ptr, value: Ptr, info: Ptr, setter: Ptr) => Ptr, getter: Ptr, setter: Ptr, data: any, attribute: number, getterSideEffectType: number, setterSideEffectType: number): void;
setInternalFieldCount(value: number): void;
applyToInstance(instance: any): void;
newInstance(_context: any): any;
}
export declare class Persistent<T> extends Disposable_2 {
private _param;
private _callback;
private _isolate;
id: number;
private static readonly _registry;
constructor(isolate: Isolate, ...args: [T] | []);
dispose(): void;
copy(): Persistent<T>;
move(to: Persistent<T>): void;
slot(): number;
getSlot(): PersistentValueType<T>;
setSlot(ref: PersistentValueType<T>): void;
deleteSlot(): void;
setWeak<P>(param: P, callback: (param: P) => void): void;
clearWeak(): void;
reset(): void;
resetTo(value: T): void;
isEmpty(): boolean;
deref(): T | undefined;
}
export declare class PersistentStore extends ArrayStore<Persistent<any>> {
private _recyleList;
constructor(initialCapacity?: number);
markUnused(id: number | bigint): void;
recycle(): void;
}
export declare type PersistentValueType<T> = StrongRef<T> | WeakRef<T extends object ? T : never> | undefined;
export declare class Private {
private _name;
constructor(name: string);
name(): string;
static forApi(name: string): Private;
}
export declare class Reference extends RefTracker {
private static weakCallback;
id: number;
envObject: Env | undefined;
private ctx;
private canBeWeak;
private _refcount;
private _ownership;
static create(ctx: Context, envObject: Env, handle_id: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership, _unused1?: void_p, _unused2?: void_p, _unused3?: void_p): Reference;
constructor(ctx: Context, envObject: Env, handle_id: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership);
getPersistent(): Persistent<any>;
ref(): number;
unref(): number;
deref(): any;
get(): napi_value;
resetFinalizer(): void;
data(): void_p;
refcount(): number;
ownership(): ReferenceOwnership;
protected callUserFinalizer(): void;
protected invokeFinalizerFromGC(): void;
private _setWeak;
setWeakWithData<T>(data: T, callback: (data: T) => void): void;
clearWeak(): void;
finalize(): void;
dispose(): void;
}
export declare enum ReferenceOwnership {
kRuntime = 0,
kUserland = 1
}
export declare class ReferenceWithData extends Reference {
private _data;
static create(ctx: Context, envObject: Env, value: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership, data: void_p): ReferenceWithData;
constructor(ctx: Context, envObject: Env, value: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership, data: void_p);
data(): void_p;
}
export declare class ReferenceWithFinalizer extends Reference {
private _finalizer;
static create(ctx: Context, envObject: Env, value: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership, finalize_callback: napi_finalize, finalize_data: void_p, finalize_hint: void_p): ReferenceWithFinalizer;
constructor(ctx: Context, envObject: Env, value: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership, finalize_callback: napi_finalize, finalize_data: void_p, finalize_hint: void_p);
resetFinalizer(): void;
data(): void_p;
protected callUserFinalizer(): void;
protected invokeFinalizerFromGC(): void;
dispose(): void;
}
export declare class RefTracker extends Disposable_2 {
dispose(): void;
finalize(): void;
protected _next: RefTracker | null;
protected _prev: RefTracker | null;
link(list: RefTracker): void;
unlink(): void;
static finalizeAll(list: RefTracker): void;
}
export declare interface Resolver<T> {
promise: Promise<T>;
resolve: (value: T | PromiseLike<T>) => void;
reject: (reason?: any) => void;
}
export declare interface ReusableStoreValue extends Disposable_2 {
reuse(...args: any[]): void;
}
export declare class ScopeStore extends BaseArrayStore<HandleScope> {
private readonly _rootScope;
currentScope: HandleScope;
constructor();
openScope(handleStore: HandleStore): HandleScope;
closeScope(): void;
isEmpty(): boolean;
}
export declare function setInternalField(instance: object, index: number, value: any): void;
export declare function setPrivate(obj: any, key: Private, value: any): void;
export declare class Signature {
receiver: FunctionTemplate | undefined;
constructor(receiver: FunctionTemplate | undefined);
}
export declare class StrongRef<T> extends Disposable_2 {
private _value;
constructor(value: T);
deref(): T;
dispose(): void;
}
export declare class Template {
protected ctx: Isolate;
protected _properties: Map<string | symbol, [any, number]>;
constructor(ctx: Isolate);
set(name: string | symbol, value: any, attr: number): void;
protected _addPropertiesToInstance(instance: any): void;
}
export declare class TrackedFinalizer extends RefTracker {
private _finalizer;
static create(envObject: Env, finalize_callback: napi_finalize, finalize_data: void_p, finalize_hint: void_p): TrackedFinalizer;
private constructor();
data(): void_p;
dispose(): void;
finalize(): void;
}
export declare class TryCatch {
static top: TryCatch | null;
private static _map;
id: number | bigint;
private _exception;
private _caught;
private _next;
constructor(id: number | bigint);
static deref(id: number | bigint): TryCatch | undefined;
static pop(): void;
isEmpty(): boolean;
hasCaught(): boolean;
exception(): any;
rethrow(ctx: Isolate): any;
setError(err: any): void;
reset(): void;
extractException(): any;
}
export declare const version: string;
export { }

2225
client/node_modules/@emnapi/runtime/dist/emnapi.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

63
client/node_modules/@emnapi/runtime/index.cjs generated vendored Normal file
View File

@@ -0,0 +1,63 @@
'use strict'
// Mutable CommonJS facade over the ESM build. The v1 package shipped a real
// CJS entry whose exports object was mutable; generated WASI loaders and
// @napi-rs/wasm-runtime's runtime.cjs rely on sharing that one mutable
// exports object (e.g. test harnesses intercept `createContext` around a
// fresh loader require). The v2 package is ESM-only, and `require()` of an
// ES module returns a frozen namespace, so restore the contract here. Each
// export is re-assigned individually (instead of spreading the namespace
// into `module.exports`) so cjs-module-lexer can statically detect the named
// exports -- `import()` of this CJS entry must still expose them as module
// namespace properties. Module-level state (the default-context memoization)
// lives inside the ESM module itself, so both entries observe the same
// runtime state.
const __emnapiRuntime = require('./dist/emnapi.js')
module.exports.ArrayStore = __emnapiRuntime.ArrayStore
module.exports.BaseArrayStore = __emnapiRuntime.BaseArrayStore
module.exports.Context = __emnapiRuntime.Context
module.exports.CountIdAllocator = __emnapiRuntime.CountIdAllocator
module.exports.CountIdReuseAllocator = __emnapiRuntime.CountIdReuseAllocator
module.exports.Disposable = __emnapiRuntime.Disposable
module.exports.EmnapiError = __emnapiRuntime.EmnapiError
module.exports.Env = __emnapiRuntime.Env
module.exports.External = __emnapiRuntime.External
module.exports.Finalizer = __emnapiRuntime.Finalizer
module.exports.FunctionTemplate = __emnapiRuntime.FunctionTemplate
module.exports.HandleScope = __emnapiRuntime.HandleScope
module.exports.HandleStore = __emnapiRuntime.HandleStore
module.exports.Isolate = __emnapiRuntime.Isolate
module.exports.NAPI_VERSION_EXPERIMENTAL = __emnapiRuntime.NAPI_VERSION_EXPERIMENTAL
module.exports.NODE_API_DEFAULT_MODULE_API_VERSION = __emnapiRuntime.NODE_API_DEFAULT_MODULE_API_VERSION
module.exports.NODE_API_SUPPORTED_VERSION_MAX = __emnapiRuntime.NODE_API_SUPPORTED_VERSION_MAX
module.exports.NODE_API_SUPPORTED_VERSION_MIN = __emnapiRuntime.NODE_API_SUPPORTED_VERSION_MIN
module.exports.NodeEnv = __emnapiRuntime.NodeEnv
module.exports.NotSupportBufferError = __emnapiRuntime.NotSupportBufferError
module.exports.NotSupportWeakRefError = __emnapiRuntime.NotSupportWeakRefError
module.exports.ObjectTemplate = __emnapiRuntime.ObjectTemplate
module.exports.Persistent = __emnapiRuntime.Persistent
module.exports.PersistentStore = __emnapiRuntime.PersistentStore
module.exports.Private = __emnapiRuntime.Private
module.exports.RefTracker = __emnapiRuntime.RefTracker
module.exports.Reference = __emnapiRuntime.Reference
module.exports.ReferenceOwnership = __emnapiRuntime.ReferenceOwnership
module.exports.ReferenceWithData = __emnapiRuntime.ReferenceWithData
module.exports.ReferenceWithFinalizer = __emnapiRuntime.ReferenceWithFinalizer
module.exports.ScopeStore = __emnapiRuntime.ScopeStore
module.exports.Signature = __emnapiRuntime.Signature
module.exports.StrongRef = __emnapiRuntime.StrongRef
module.exports.Template = __emnapiRuntime.Template
module.exports.TrackedFinalizer = __emnapiRuntime.TrackedFinalizer
module.exports.TryCatch = __emnapiRuntime.TryCatch
module.exports.createContext = __emnapiRuntime.createContext
module.exports.deletePrivate = __emnapiRuntime.deletePrivate
module.exports.getDefaultContext = __emnapiRuntime.getDefaultContext
module.exports.getDylinkMetadata = __emnapiRuntime.getDylinkMetadata
module.exports.getExternalValue = __emnapiRuntime.getExternalValue
module.exports.getInternalField = __emnapiRuntime.getInternalField
module.exports.getPrivate = __emnapiRuntime.getPrivate
module.exports.hasPrivate = __emnapiRuntime.hasPrivate
module.exports.isExternal = __emnapiRuntime.isExternal
module.exports.isReferenceType = __emnapiRuntime.isReferenceType
module.exports.setInternalField = __emnapiRuntime.setInternalField
module.exports.setPrivate = __emnapiRuntime.setPrivate
module.exports.version = __emnapiRuntime.version

39
client/node_modules/@emnapi/runtime/package.json generated vendored Normal file
View File

@@ -0,0 +1,39 @@
{
"name": "@emnapi/runtime",
"version": "2.0.0-alpha.3",
"description": "emnapi runtime",
"type": "module",
"main": "./dist/emnapi.js",
"module": "./dist/emnapi.js",
"types": "./dist/emnapi.d.ts",
"sideEffects": false,
"exports": {
".": {
"types": "./dist/emnapi.d.ts",
"import": "./dist/emnapi.js",
"require": "./index.cjs",
"default": "./dist/emnapi.js"
},
"./package.json": "./package.json"
},
"dependencies": {
"tslib": "^2.4.0"
},
"scripts": {
"build": "rollup -c",
"test": "node ./test/index.js"
},
"repository": {
"type": "git",
"url": "git+https://github.com/toyobayashi/emnapi.git"
},
"author": "toyobayashi",
"license": "MIT",
"bugs": {
"url": "https://github.com/toyobayashi/emnapi/issues"
},
"homepage": "https://github.com/toyobayashi/emnapi#readme",
"publishConfig": {
"access": "public"
}
}

25
client/node_modules/@emnapi/runtime/rollup.config.js generated vendored Normal file
View File

@@ -0,0 +1,25 @@
import { defineConfig } from '@emnapi/shared'
import fs from 'fs'
import path from 'path'
import { EOL } from 'os'
import pkg from './package.json' with { type: 'json' }
export default defineConfig({
outputName: 'emnapi',
outputFile: 'emnapi',
sourcemap: true,
defines: {
__VERSION__: JSON.stringify(pkg.version)
},
apiExtractorCallback: (result) => {
if (result.succeeded) {
let dts = ''
dts += '/// <reference lib="esnext.disposable" />' + EOL + EOL
dts += fs.readFileSync(path.join(import.meta.dirname, 'src/typings/common.d.ts'), 'utf8').replace(/declare/g, 'export declare')
dts += fs.readFileSync(path.join(import.meta.dirname, 'src/typings/ctype.d.ts'), 'utf8').replace(/declare/g, 'export declare')
dts += fs.readFileSync(path.join(import.meta.dirname, 'src/typings/napi.d.ts'), 'utf8').replace(/declare/g, 'export declare')
dts += fs.readFileSync(result.extractorConfig.publicTrimmedFilePath, 'utf8')
fs.writeFileSync(result.extractorConfig.publicTrimmedFilePath, dts, 'utf8')
}
}
})

21
client/node_modules/@emnapi/wasi-threads/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2021-present Toyobayashi
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

203
client/node_modules/@emnapi/wasi-threads/README.md generated vendored Normal file
View File

@@ -0,0 +1,203 @@
# @emnapi/wasi-threads
This package makes [wasi-threads proposal](https://github.com/WebAssembly/wasi-threads) based WASI modules work in Node.js and browser.
## Quick Start
`index.html`
```html
<script src="./node_modules/@tybys/wasm-util/dist/wasm-util.js"></script>
<script src="./node_modules/@emnapi/wasi-threads/dist/wasi-threads.js"></script>
<script src="./index.js"></script>
```
If your application will block browser main thread (for example `pthread_join`), please run it in worker instead.
```html
<script>
// pthread_join (Atomics.wait) cannot be called in browser main thread
new Worker('./index.js')
</script>
```
`index.js`
```js
const ENVIRONMENT_IS_NODE =
typeof process === 'object' && process !== null &&
typeof process.versions === 'object' && process.versions !== null &&
typeof process.versions.node === 'string';
(function (main) {
if (ENVIRONMENT_IS_NODE) {
main(require)
} else {
if (typeof importScripts === 'function') {
importScripts('./node_modules/@tybys/wasm-util/dist/wasm-util.js')
importScripts('./node_modules/@emnapi/wasi-threads/dist/wasi-threads.js')
}
const nodeWasi = { WASI: globalThis.wasmUtil.WASI }
const nodeWorkerThreads = {
Worker: globalThis.Worker
}
const _require = function (request) {
if (request === 'node:wasi' || request === 'wasi') return nodeWasi
if (request === 'node:worker_threads' || request === 'worker_threads') return nodeWorkerThreads
if (request === '@emnapi/wasi-threads') return globalThis.wasiThreads
throw new Error('Can not find module: ' + request)
}
main(_require)
}
})(async function (require) {
const { WASI } = require('wasi')
const { Worker } = require('worker_threads')
const { WASIThreads } = require('@emnapi/wasi-threads')
const wasi = new WASI({
version: 'preview1'
})
const wasiThreads = new WASIThreads({
wasi,
/**
* avoid Atomics.wait() deadlock during thread creation in browser
* see https://emscripten.org/docs/tools_reference/settings_reference.html#pthread-pool-size
*/
reuseWorker: ENVIRONMENT_IS_NODE
? false
: {
size: 4 /** greater than actual needs (2) */,
strict: true
},
/**
* Synchronous thread creation
* pthread_create will not return until thread worker actually starts
*/
waitThreadStart: typeof window === 'undefined' ? 1000 : false,
onCreateWorker: () => {
return new Worker('./worker.js', {
execArgv: ['--experimental-wasi-unstable-preview1']
})
}
})
const memory = new WebAssembly.Memory({
initial: 16777216 / 65536,
maximum: 2147483648 / 65536,
shared: true
})
let input
const file = 'path/to/your/wasi-module.wasm'
try {
input = require('fs').readFileSync(require('path').join(__dirname, file))
} catch (err) {
const response = await fetch(file)
input = await response.arrayBuffer()
}
let { module, instance } = await WebAssembly.instantiate(input, {
env: { memory },
wasi_snapshot_preview1: wasi.wasiImport,
...wasiThreads.getImportObject()
})
wasiThreads.setup(instance, module, memory)
await wasiThreads.preloadWorkers()
if (typeof instance.exports._start === 'function') {
return wasi.start(instance)
} else {
wasi.initialize(instance)
// instance.exports.exported_wasm_function()
}
})
```
`worker.js`
```js
(function (main) {
const ENVIRONMENT_IS_NODE =
typeof process === 'object' && process !== null &&
typeof process.versions === 'object' && process.versions !== null &&
typeof process.versions.node === 'string'
if (ENVIRONMENT_IS_NODE) {
const _require = function (request) {
return require(request)
}
const _init = function () {
const nodeWorkerThreads = require('worker_threads')
const parentPort = nodeWorkerThreads.parentPort
parentPort.on('message', (data) => {
globalThis.onmessage({ data })
})
Object.assign(globalThis, {
self: globalThis,
require,
Worker: nodeWorkerThreads.Worker,
importScripts: function (f) {
(0, eval)(require('fs').readFileSync(f, 'utf8') + '//# sourceURL=' + f)
},
postMessage: function (msg) {
parentPort.postMessage(msg)
}
})
}
main(_require, _init)
} else {
importScripts('./node_modules/@tybys/wasm-util/dist/wasm-util.js')
importScripts('./node_modules/@emnapi/wasi-threads/dist/wasi-threads.js')
const nodeWasi = { WASI: globalThis.wasmUtil.WASI }
const _require = function (request) {
if (request === '@emnapi/wasi-threads') return globalThis.wasiThreads
if (request === 'node:wasi' || request === 'wasi') return nodeWasi
throw new Error('Can not find module: ' + request)
}
const _init = function () {}
main(_require, _init)
}
})(function main (require, init) {
init()
const { WASI } = require('wasi')
const { ThreadMessageHandler, WASIThreads } = require('@emnapi/wasi-threads')
const handler = new ThreadMessageHandler({
async onLoad ({ wasmModule, wasmMemory }) {
const wasi = new WASI({
version: 'preview1'
})
const wasiThreads = new WASIThreads({
wasi,
childThread: true
})
const originalInstance = await WebAssembly.instantiate(wasmModule, {
env: {
memory: wasmMemory,
},
wasi_snapshot_preview1: wasi.wasiImport,
...wasiThreads.getImportObject()
})
// must call `initialize` instead of `start` in child thread
const instance = wasiThreads.initialize(originalInstance, wasmModule, wasmMemory)
return { module: wasmModule, instance }
}
})
globalThis.onmessage = function (e) {
handler.handle(e)
// handle other messages
}
})
```

View File

@@ -0,0 +1,211 @@
import type { Worker as Worker_2 } from 'worker_threads';
export declare interface BaseOptions {
wasi: WASIInstance;
version?: 'preview1';
wasm64?: boolean;
}
export declare interface ChildThreadOptions extends BaseOptions {
childThread: true;
postMessage?: (data: any) => void;
}
export declare interface CleanupThreadPayload {
tid: number;
}
export declare interface CommandInfo<T extends CommandType> {
type: T;
payload: CommandPayloadMap[T];
}
export declare interface CommandPayloadMap {
load: LoadPayload;
loaded: LoadedPayload;
start: StartPayload;
'cleanup-thread': CleanupThreadPayload;
'terminate-all-threads': TerminateAllThreadsPayload;
'spawn-thread': SpawnThreadPayload;
}
export declare type CommandType = keyof CommandPayloadMap;
export declare function createInstanceProxy(instance: WebAssembly.Instance, memory?: WebAssembly.Memory | (() => WebAssembly.Memory)): WebAssembly.Instance;
export declare function isSharedArrayBuffer(value: any): value is SharedArrayBuffer;
export declare function isTrapError(e: Error): e is WebAssembly.RuntimeError;
export declare interface LoadedPayload {
}
export declare interface LoadPayload {
wasmModule: WebAssembly.Module;
wasmMemory: WebAssembly.Memory;
sab?: Int32Array;
}
export declare interface MainThreadBaseOptions extends BaseOptions {
waitThreadStart?: boolean | number;
}
export declare type MainThreadOptions = MainThreadOptionsWithThreadManager | MainThreadOptionsCreateThreadManager;
export declare interface MainThreadOptionsCreateThreadManager extends MainThreadBaseOptions, ThreadManagerOptionsMain {
}
export declare interface MainThreadOptionsWithThreadManager extends MainThreadBaseOptions {
threadManager?: ThreadManager | (() => ThreadManager);
}
export declare interface MessageEventData<T extends CommandType> {
__emnapi__: CommandInfo<T>;
}
export declare interface ReuseWorkerOptions {
size: number;
strict?: boolean;
}
export declare interface SpawnThreadPayload {
startArg: number;
errorOrTid: number;
}
export declare interface StartPayload {
tid: number;
arg: number;
sab?: Int32Array;
}
export declare interface StartResult {
exitCode: number;
instance: WebAssembly.Instance;
}
export declare interface TerminateAllThreadsPayload {
}
export declare class ThreadManager {
unusedWorkers: WorkerLike[];
pthreads: Record<number, WorkerLike>;
get nextWorkerID(): number;
wasmModule: WebAssembly.Module | null;
wasmMemory: WebAssembly.Memory | null;
private readonly messageEvents;
private readonly _childThread;
private readonly _onCreateWorker;
private readonly _reuseWorker;
private readonly _beforeLoad?;
readonly printErr: (message: string) => void;
threadSpawn?: ((startArg: number, errorOrTid?: number) => number);
constructor(options: ThreadManagerOptions);
init(): void;
initMainThread(): void;
private preparePool;
shouldPreloadWorkers(): boolean;
loadWasmModuleToAllWorkers(): Promise<WorkerLike[]>;
preloadWorkers(): Promise<WorkerLike[]>;
setup(wasmModule: WebAssembly.Module, wasmMemory: WebAssembly.Memory): void;
markId(worker: WorkerLike): number;
returnWorkerToPool(worker: WorkerLike): void;
loadWasmModuleToWorker(worker: WorkerLike, sab?: Int32Array): Promise<WorkerLike>;
allocateUnusedWorker(): WorkerLike;
getNewWorker(sab?: Int32Array): WorkerLike | undefined;
cleanThread(worker: WorkerLike, tid: number, force?: boolean): void;
terminateWorker(worker: WorkerLike): void;
terminateAllThreads(): void;
addMessageEventListener(worker: WorkerLike, onMessage: (e: WorkerMessageEvent) => void): () => void;
fireMessageEvent(worker: WorkerLike, e: WorkerMessageEvent): void;
}
export declare type ThreadManagerOptions = ThreadManagerOptionsMain | ThreadManagerOptionsChild;
export declare interface ThreadManagerOptionsBase {
printErr?: (message: string) => void;
threadSpawn?: (startArg: number, errorOrTid?: number) => number;
}
export declare interface ThreadManagerOptionsChild extends ThreadManagerOptionsBase {
childThread: true;
}
export declare interface ThreadManagerOptionsMain extends ThreadManagerOptionsBase {
beforeLoad?: (worker: WorkerLike) => any;
reuseWorker?: boolean | number | ReuseWorkerOptions;
onCreateWorker: WorkerFactory;
childThread?: false;
}
export declare class ThreadMessageHandler {
protected instance: WebAssembly.Instance | undefined;
private messagesBeforeLoad;
protected postMessage: (message: any) => void;
protected onLoad?: (data: LoadPayload) => WebAssembly.WebAssemblyInstantiatedSource | PromiseLike<WebAssembly.WebAssemblyInstantiatedSource>;
protected onError: (error: Error, type: WorkerMessageType) => void;
constructor(options?: ThreadMessageHandlerOptions);
instantiate(data: LoadPayload): WebAssembly.WebAssemblyInstantiatedSource | PromiseLike<WebAssembly.WebAssemblyInstantiatedSource>;
handle(e: WorkerMessageEvent<MessageEventData<WorkerMessageType>>): void;
private _load;
private _start;
protected _loaded(err: Error | null, source: WebAssembly.WebAssemblyInstantiatedSource | null, payload: LoadPayload): void;
protected handleAfterLoad<E extends WorkerMessageEvent>(e: E, f: (e: E) => void): void;
}
export declare interface ThreadMessageHandlerOptions {
onLoad?: (data: LoadPayload) => WebAssembly.WebAssemblyInstantiatedSource | PromiseLike<WebAssembly.WebAssemblyInstantiatedSource>;
onError?: (error: Error, type: WorkerMessageType) => void;
postMessage?: (message: any) => void;
}
export declare interface WASIInstance {
readonly wasiImport?: Record<string, any>;
initialize(instance: object): void;
start(instance: object): number;
getImportObject?(): any;
}
export declare class WASIThreads {
PThread: ThreadManager | undefined;
private wasmMemory;
private wasmInstance;
private readonly threadSpawn;
readonly childThread: boolean;
private readonly postMessage;
readonly wasi: WASIInstance;
constructor(options: WASIThreadsOptions);
getImportObject(): {
wasi: WASIThreadsImports;
};
setup(wasmInstance: WebAssembly.Instance, wasmModule: WebAssembly.Module, wasmMemory?: WebAssembly.Memory): void;
preloadWorkers(): Promise<WorkerLike[]>;
initialize(instance: WebAssembly.Instance, module: WebAssembly.Module, memory?: WebAssembly.Memory): WebAssembly.Instance;
start(instance: WebAssembly.Instance, module: WebAssembly.Module, memory?: WebAssembly.Memory): StartResult;
terminateAllThreads(): void;
}
export declare interface WASIThreadsImports {
'thread-spawn': (startArg: number, errorOrTid?: number) => number;
}
export declare type WASIThreadsOptions = MainThreadOptions | ChildThreadOptions;
export declare type WorkerFactory = (ctx: {
type: string;
name: string;
}) => WorkerLike;
export declare type WorkerLike = (Worker | Worker_2) & {
whenLoaded?: Promise<WorkerLike>;
loaded?: boolean;
__emnapi_tid?: number;
};
export declare interface WorkerMessageEvent<T = any> {
data: T;
}
export declare type WorkerMessageType = 'load' | 'start';
export { }

View File

@@ -0,0 +1,918 @@
//#region src/util.ts
const _WebAssembly = typeof WebAssembly !== 'undefined'
? WebAssembly
: typeof WXWebAssembly !== 'undefined'
? WXWebAssembly
: undefined;
const ENVIRONMENT_IS_NODE = typeof process === 'object' && process !== null &&
typeof process.versions === 'object' && process.versions !== null &&
typeof process.versions.node === 'string';
function getPostMessage(options) {
return typeof options?.postMessage === 'function'
? options.postMessage
: typeof postMessage === 'function'
? postMessage
: undefined;
}
function serizeErrorToBuffer(sab, code, error) {
const i32array = new Int32Array(sab);
Atomics.store(i32array, 0, code);
if (code > 1 && error) {
const name = error.name;
const message = error.message;
const stack = error.stack;
const nameBuffer = new TextEncoder().encode(name);
const messageBuffer = new TextEncoder().encode(message);
const stackBuffer = new TextEncoder().encode(stack);
Atomics.store(i32array, 1, nameBuffer.length);
Atomics.store(i32array, 2, messageBuffer.length);
Atomics.store(i32array, 3, stackBuffer.length);
const buffer = new Uint8Array(sab);
buffer.set(nameBuffer, 16);
buffer.set(messageBuffer, 16 + nameBuffer.length);
buffer.set(stackBuffer, 16 + nameBuffer.length + messageBuffer.length);
}
}
function deserizeErrorFromBuffer(sab) {
const i32array = new Int32Array(sab);
const status = Atomics.load(i32array, 0);
if (status <= 1) {
return null;
}
const nameLength = Atomics.load(i32array, 1);
const messageLength = Atomics.load(i32array, 2);
const stackLength = Atomics.load(i32array, 3);
const buffer = new Uint8Array(sab);
const nameBuffer = buffer.slice(16, 16 + nameLength);
const messageBuffer = buffer.slice(16 + nameLength, 16 + nameLength + messageLength);
const stackBuffer = buffer.slice(16 + nameLength + messageLength, 16 + nameLength + messageLength + stackLength);
const name = new TextDecoder().decode(nameBuffer);
const message = new TextDecoder().decode(messageBuffer);
const stack = new TextDecoder().decode(stackBuffer);
const ErrorConstructor = globalThis[name] ?? (name === 'RuntimeError' ? (_WebAssembly.RuntimeError ?? Error) : Error);
const error = new ErrorConstructor(message);
Object.defineProperty(error, 'stack', {
value: stack,
writable: true,
enumerable: false,
configurable: true
});
return error;
}
function isSharedArrayBuffer(value) {
return ((typeof SharedArrayBuffer === 'function' && value instanceof SharedArrayBuffer) ||
(Object.prototype.toString.call(value) === '[object SharedArrayBuffer]'));
}
function isTrapError(e) {
try {
return e instanceof _WebAssembly.RuntimeError;
}
catch (_) {
return false;
}
}
//#endregion src/util.ts
//#region src/command.ts
function createMessage(type, payload) {
return {
__emnapi__: {
type,
payload
}
};
}
//#endregion src/command.ts
//#region src/thread-manager.ts
const WASI_THREADS_MAX_TID = 0x1FFFFFFF;
function checkSharedWasmMemory(wasmMemory) {
if (wasmMemory) {
if (!isSharedArrayBuffer(wasmMemory.buffer)) {
throw new Error('Multithread features require shared wasm memory. ' +
'Try to compile with `-matomics -mbulk-memory` and use `--import-memory --shared-memory` during linking, ' +
'then create WebAssembly.Memory with `shared: true` option');
}
}
else {
if (typeof SharedArrayBuffer === 'undefined') {
throw new Error('Current environment does not support SharedArrayBuffer, threads are not available!');
}
}
}
function getReuseWorker(value) {
if (typeof value === 'boolean') {
return value ? { size: 0, strict: false } : false;
}
if (typeof value === 'number') {
if (!(value >= 0)) {
throw new RangeError('reuseWorker: size must be a non-negative integer');
}
return { size: value, strict: false };
}
if (!value) {
return false;
}
const size = Number(value.size) || 0;
const strict = Boolean(value.strict);
if (!(size > 0) && strict) {
throw new RangeError('reuseWorker: size must be set to positive integer if strict is set to true');
}
return { size, strict };
}
let nextWorkerID = 0;
class ThreadManager {
get nextWorkerID() { return nextWorkerID; }
constructor(options) {
this.unusedWorkers = [];
this.pthreads = Object.create(null);
this.wasmModule = null;
this.wasmMemory = null;
this.messageEvents = new WeakMap();
if (!options) {
throw new TypeError('ThreadManager(): options is not provided');
}
if ('childThread' in options) {
this._childThread = Boolean(options.childThread);
}
else {
this._childThread = false;
}
if (this._childThread) {
this._onCreateWorker = undefined;
this._reuseWorker = false;
this._beforeLoad = undefined;
}
else {
this._onCreateWorker = options.onCreateWorker;
this._reuseWorker = getReuseWorker(options.reuseWorker);
this._beforeLoad = options.beforeLoad;
}
this.printErr = options.printErr ?? console.error.bind(console);
this.threadSpawn = options.threadSpawn;
}
init() {
if (!this._childThread) {
this.initMainThread();
}
}
initMainThread() {
this.preparePool();
}
preparePool() {
if (this._reuseWorker) {
if (this._reuseWorker.size) {
let pthreadPoolSize = this._reuseWorker.size;
while (pthreadPoolSize--) {
const worker = this.allocateUnusedWorker();
if (ENVIRONMENT_IS_NODE) {
worker.once('message', () => { });
worker.unref();
}
}
}
}
}
shouldPreloadWorkers() {
return !this._childThread && this._reuseWorker && this._reuseWorker.size > 0;
}
loadWasmModuleToAllWorkers() {
const promises = Array(this.unusedWorkers.length);
for (let i = 0; i < this.unusedWorkers.length; ++i) {
const worker = this.unusedWorkers[i];
if (ENVIRONMENT_IS_NODE)
worker.ref();
promises[i] = this.loadWasmModuleToWorker(worker).then((w) => {
if (ENVIRONMENT_IS_NODE)
worker.unref();
return w;
}, (e) => {
if (ENVIRONMENT_IS_NODE)
worker.unref();
throw e;
});
}
return Promise.all(promises).catch((err) => {
this.terminateAllThreads();
throw err;
});
}
preloadWorkers() {
if (this.shouldPreloadWorkers()) {
return this.loadWasmModuleToAllWorkers();
}
return Promise.resolve([]);
}
setup(wasmModule, wasmMemory) {
this.wasmModule = wasmModule;
this.wasmMemory = wasmMemory;
}
markId(worker) {
if (worker.__emnapi_tid)
return worker.__emnapi_tid;
const tid = nextWorkerID + 43;
nextWorkerID = (nextWorkerID + 1) % (WASI_THREADS_MAX_TID - 42);
this.pthreads[tid] = worker;
worker.__emnapi_tid = tid;
return tid;
}
returnWorkerToPool(worker) {
var tid = worker.__emnapi_tid;
if (tid !== undefined) {
delete this.pthreads[tid];
}
this.unusedWorkers.push(worker);
delete worker.__emnapi_tid;
if (ENVIRONMENT_IS_NODE) {
worker.unref();
}
}
loadWasmModuleToWorker(worker, sab) {
if (worker.whenLoaded)
return worker.whenLoaded;
const err = this.printErr;
const beforeLoad = this._beforeLoad;
const _this = this;
worker.whenLoaded = new Promise((resolve, reject) => {
const handleError = function (e) {
let message = 'worker sent an error!';
if (worker.__emnapi_tid !== undefined) {
message = 'worker (tid = ' + worker.__emnapi_tid + ') sent an error!';
}
if ('message' in e) {
err(message + ' ' + e.message);
if (e.message.indexOf('RuntimeError') !== -1 || e.message.indexOf('unreachable') !== -1) {
try {
_this.terminateAllThreads();
}
catch (_) { }
}
}
else {
err(message);
}
reject(e);
throw e;
};
const handleMessage = (data) => {
if (data.__emnapi__) {
const type = data.__emnapi__.type;
const payload = data.__emnapi__.payload;
if (type === 'loaded') {
worker.loaded = true;
if (ENVIRONMENT_IS_NODE && !worker.__emnapi_tid) {
worker.unref();
}
resolve(worker);
}
else if (type === 'cleanup-thread') {
if (payload.tid in this.pthreads) {
this.cleanThread(worker, payload.tid);
}
}
else if (type === 'spawn-thread') {
this.threadSpawn(payload.startArg, payload.errorOrTid);
}
else if (type === 'terminate-all-threads') {
this.terminateAllThreads();
}
}
};
worker.onmessage = (e) => {
handleMessage(e.data);
this.fireMessageEvent(worker, e);
};
worker.onerror = handleError;
if (ENVIRONMENT_IS_NODE) {
worker.on('message', function (data) {
worker.onmessage?.({
data
});
});
worker.on('error', function (e) {
worker.onerror?.(e);
});
worker.on('detachedExit', function () { });
}
if (typeof beforeLoad === 'function') {
beforeLoad(worker);
}
try {
worker.postMessage(createMessage('load', {
wasmModule: this.wasmModule,
wasmMemory: this.wasmMemory,
sab
}));
}
catch (err) {
checkSharedWasmMemory(this.wasmMemory);
throw err;
}
});
return worker.whenLoaded;
}
allocateUnusedWorker() {
const _onCreateWorker = this._onCreateWorker;
if (typeof _onCreateWorker !== 'function') {
throw new TypeError('`options.onCreateWorker` is not provided');
}
const worker = _onCreateWorker({ type: 'thread', name: 'emnapi-pthread' });
this.unusedWorkers.push(worker);
return worker;
}
getNewWorker(sab) {
if (this._reuseWorker) {
if (this.unusedWorkers.length === 0) {
if (this._reuseWorker.strict) {
if (!ENVIRONMENT_IS_NODE) {
const err = this.printErr;
err('Tried to spawn a new thread, but the thread pool is exhausted.\n' +
'This might result in a deadlock unless some threads eventually exit or the code explicitly breaks out to the event loop.');
return;
}
}
const worker = this.allocateUnusedWorker();
this.loadWasmModuleToWorker(worker, sab);
}
return this.unusedWorkers.pop();
}
const worker = this.allocateUnusedWorker();
this.loadWasmModuleToWorker(worker, sab);
return this.unusedWorkers.pop();
}
cleanThread(worker, tid, force) {
if (!force && this._reuseWorker) {
this.returnWorkerToPool(worker);
}
else {
delete this.pthreads[tid];
this.terminateWorker(worker);
delete worker.__emnapi_tid;
}
}
terminateWorker(worker) {
const tid = worker.__emnapi_tid;
worker.terminate();
this.messageEvents.get(worker)?.clear();
this.messageEvents.delete(worker);
worker.onmessage = (e) => {
if (e.data.__emnapi__) {
const err = this.printErr;
err('received "' + e.data.__emnapi__.type + '" command from terminated worker: ' + tid);
}
};
}
terminateAllThreads() {
const runningWorkers = Object.values(this.pthreads);
for (let i = 0; i < runningWorkers.length; ++i) {
this.terminateWorker(runningWorkers[i]);
}
for (let i = 0; i < this.unusedWorkers.length; ++i) {
this.terminateWorker(this.unusedWorkers[i]);
}
this.unusedWorkers = [];
this.pthreads = Object.create(null);
this.preparePool();
}
addMessageEventListener(worker, onMessage) {
let listeners = this.messageEvents.get(worker);
if (!listeners) {
listeners = new Set();
this.messageEvents.set(worker, listeners);
}
listeners.add(onMessage);
return () => {
listeners?.delete(onMessage);
};
}
fireMessageEvent(worker, e) {
const listeners = this.messageEvents.get(worker);
if (!listeners)
return;
const err = this.printErr;
listeners.forEach((listener) => {
try {
listener(e);
}
catch (e) {
err(e.stack);
}
});
}
}
//#endregion src/thread-manager.ts
//#region src/proxy.ts
const kIsProxy = Symbol('kIsProxy');
function createInstanceProxy(instance, memory) {
if (instance[kIsProxy])
return instance;
const originalExports = instance.exports;
const createHandler = function (target) {
const handlers = [
'apply',
'construct',
'defineProperty',
'deleteProperty',
'get',
'getOwnPropertyDescriptor',
'getPrototypeOf',
'has',
'isExtensible',
'ownKeys',
'preventExtensions',
'set',
'setPrototypeOf'
];
const handler = {};
for (let i = 0; i < handlers.length; i++) {
const name = handlers[i];
handler[name] = function () {
const args = Array.prototype.slice.call(arguments, 1);
args.unshift(target);
return Reflect[name].apply(Reflect, args);
};
}
return handler;
};
const handler = createHandler(originalExports);
const _initialize = () => { };
const _start = () => 0;
handler.get = function (_target, p, receiver) {
if (p === 'memory') {
return (typeof memory === 'function' ? memory() : memory) ?? Reflect.get(originalExports, p, receiver);
}
if (p === '_initialize') {
return p in originalExports ? _initialize : undefined;
}
if (p === '_start') {
return p in originalExports ? _start : undefined;
}
return Reflect.get(originalExports, p, receiver);
};
handler.has = function (_target, p) {
if (p === 'memory')
return true;
return Reflect.has(originalExports, p);
};
const exportsProxy = new Proxy(Object.create(null), handler);
return new Proxy(instance, {
get(target, p, receiver) {
if (p === 'exports') {
return exportsProxy;
}
if (p === kIsProxy) {
return true;
}
return Reflect.get(target, p, receiver);
}
});
}
//#endregion src/proxy.ts
//#region src/wasi-threads.ts
const patchedWasiInstances = new WeakMap();
const THREAD_SPAWN_RESULT_SIZE = Int32Array.BYTES_PER_ELEMENT * 2;
const sharedArrayBufferByteLength = typeof SharedArrayBuffer === 'function'
? Object.getOwnPropertyDescriptor(SharedArrayBuffer.prototype, 'byteLength').get
: undefined;
function isConclusivelySharedArrayBuffer(buffer) {
if (sharedArrayBufferByteLength === undefined)
return false;
try {
sharedArrayBufferByteLength.call(buffer);
return true;
}
catch (_) {
return false;
}
}
function getThreadSpawnResultView(memory, address, wasm64) {
const offset = typeof address === 'bigint' ? Number(address) : address >>> 0;
let buffer = memory.buffer;
if (offset + THREAD_SPAWN_RESULT_SIZE > buffer.byteLength &&
isConclusivelySharedArrayBuffer(buffer)) {
if (wasm64) {
memory.grow(BigInt(0));
}
else {
memory.grow(0);
}
buffer = memory.buffer;
}
return new Int32Array(buffer, offset, 2);
}
class WASIThreads {
constructor(options) {
if (!options) {
throw new TypeError('WASIThreads(): options is not provided');
}
if (!options.wasi) {
throw new TypeError('WASIThreads(): options.wasi is not provided');
}
patchedWasiInstances.set(this, new WeakSet());
const wasi = options.wasi;
patchWasiInstance(this, wasi);
this.wasi = wasi;
if ('childThread' in options) {
this.childThread = Boolean(options.childThread);
}
else {
this.childThread = false;
}
this.PThread = undefined;
if ('threadManager' in options) {
if (typeof options.threadManager === 'function') {
this.PThread = options.threadManager();
}
else {
this.PThread = options.threadManager;
}
}
else {
if (!this.childThread) {
this.PThread = new ThreadManager(options);
this.PThread.init();
}
}
let waitThreadStart = false;
if ('waitThreadStart' in options) {
waitThreadStart = typeof options.waitThreadStart === 'number' ? options.waitThreadStart : Boolean(options.waitThreadStart);
}
const postMessage = getPostMessage(options);
if (this.childThread && typeof postMessage !== 'function') {
throw new TypeError('options.postMessage is not a function');
}
this.postMessage = postMessage;
const wasm64 = Boolean(options.wasm64);
const threadSpawn = (startArg, errorOrTid) => {
const EAGAIN = 6;
const isNewABI = errorOrTid !== undefined;
try {
checkSharedWasmMemory(this.wasmMemory);
}
catch (err) {
this.PThread?.printErr(err.stack);
if (isNewABI) {
const struct = getThreadSpawnResultView(this.wasmMemory, errorOrTid, wasm64);
Atomics.store(struct, 0, 1);
Atomics.store(struct, 1, EAGAIN);
Atomics.notify(struct, 1);
return 1;
}
else {
return -EAGAIN;
}
}
if (!isNewABI) {
const malloc = this.wasmInstance.exports.malloc;
errorOrTid = wasm64 ? Number(malloc(BigInt(8))) : (malloc(8) >>> 0);
if (!errorOrTid) {
return -48;
}
}
const _free = this.wasmInstance.exports.free;
const free = wasm64 ? (ptr) => { _free(BigInt(ptr)); } : _free;
const struct = getThreadSpawnResultView(this.wasmMemory, errorOrTid, wasm64);
Atomics.store(struct, 0, 0);
Atomics.store(struct, 1, 0);
if (this.childThread) {
postMessage(createMessage('spawn-thread', {
startArg,
errorOrTid: errorOrTid
}));
Atomics.wait(struct, 1, 0);
const isError = Atomics.load(struct, 0);
const result = Atomics.load(struct, 1);
if (isNewABI) {
return isError;
}
free(errorOrTid);
return isError ? -result : result;
}
const shouldWait = waitThreadStart || (waitThreadStart === 0);
let sab;
if (shouldWait) {
sab = new Int32Array(new SharedArrayBuffer(16 + 8192));
Atomics.store(sab, 0, 0);
}
let worker;
let tid;
const PThread = this.PThread;
try {
worker = PThread.getNewWorker(sab);
if (!worker) {
throw new Error('failed to get new worker');
}
tid = PThread.markId(worker);
if (ENVIRONMENT_IS_NODE) {
worker.unref();
}
worker.postMessage(createMessage('start', {
tid,
arg: startArg,
sab
}));
if (shouldWait) {
if (typeof waitThreadStart === 'number') {
const waitResult = Atomics.wait(sab, 0, 0, waitThreadStart);
if (waitResult === 'timed-out') {
throw new Error('Spawning thread timed out. Please check if the worker is created successfully and if message is handled properly in the worker.');
}
}
else {
Atomics.wait(sab, 0, 0);
}
const r = Atomics.load(sab, 0);
if (r > 1) {
throw deserizeErrorFromBuffer(sab.buffer);
}
}
}
catch (e) {
if (worker !== undefined && tid !== undefined) {
try {
PThread.cleanThread(worker, tid, true);
}
catch (_) { }
}
Atomics.store(struct, 0, 1);
Atomics.store(struct, 1, EAGAIN);
Atomics.notify(struct, 1);
PThread?.printErr(e.stack);
if (isNewABI) {
return 1;
}
free(errorOrTid);
return -EAGAIN;
}
Atomics.store(struct, 0, 0);
Atomics.store(struct, 1, tid);
Atomics.notify(struct, 1);
if (!shouldWait) {
worker.whenLoaded.catch((err) => {
delete worker.whenLoaded;
PThread.cleanThread(worker, tid, true);
throw err;
});
}
if (isNewABI) {
return 0;
}
free(errorOrTid);
return tid;
};
this.threadSpawn = threadSpawn;
if (this.PThread) {
this.PThread.threadSpawn = threadSpawn;
}
}
getImportObject() {
return {
wasi: {
'thread-spawn': this.threadSpawn
}
};
}
setup(wasmInstance, wasmModule, wasmMemory) {
wasmMemory ??= wasmInstance.exports.memory;
this.wasmInstance = wasmInstance;
this.wasmMemory = wasmMemory;
if (this.PThread) {
this.PThread.setup(wasmModule, wasmMemory);
}
}
preloadWorkers() {
if (this.PThread) {
return this.PThread.preloadWorkers();
}
return Promise.resolve([]);
}
initialize(instance, module, memory) {
const exports = instance.exports;
memory ??= exports.memory;
if (this.childThread) {
instance = createInstanceProxy(instance, memory);
}
this.setup(instance, module, memory);
const wasi = this.wasi;
if (('_start' in exports) && (typeof exports._start === 'function')) {
if (this.childThread) {
wasi.start(instance);
try {
const kStarted = getWasiSymbol(wasi, 'kStarted');
wasi[kStarted] = false;
}
catch (_) { }
}
else {
setupInstance(wasi, instance);
}
}
else {
wasi.initialize(instance);
}
return instance;
}
start(instance, module, memory) {
const exports = instance.exports;
memory ??= exports.memory;
if (this.childThread) {
instance = createInstanceProxy(instance, memory);
}
this.setup(instance, module, memory);
const exitCode = this.wasi.start(instance);
return { exitCode, instance };
}
terminateAllThreads() {
if (!this.childThread) {
this.PThread?.terminateAllThreads();
}
else {
this.postMessage(createMessage('terminate-all-threads', {}));
}
}
}
function patchWasiInstance(wasiThreads, wasi) {
const patched = patchedWasiInstances.get(wasiThreads);
if (patched.has(wasi)) {
return;
}
const _this = wasiThreads;
const wasiImport = wasi.wasiImport;
if (wasiImport) {
const proc_exit = wasiImport.proc_exit;
wasiImport.proc_exit = function (code) {
_this.terminateAllThreads();
return proc_exit.call(this, code);
};
}
if (!_this.childThread) {
const start = wasi.start;
if (typeof start === 'function') {
wasi.start = function (instance) {
try {
return start.call(this, instance);
}
catch (err) {
if (isTrapError(err)) {
_this.terminateAllThreads();
}
throw err;
}
};
}
}
patched.add(wasi);
}
function getWasiSymbol(wasi, description) {
const symbols = Object.getOwnPropertySymbols(wasi);
const selectDescription = (description) => (s) => {
if (s.description) {
return s.description === description;
}
return s.toString() === `Symbol(${description})`;
};
if (Array.isArray(description)) {
return description.map(d => symbols.filter(selectDescription(d))[0]);
}
return symbols.filter(selectDescription(description))[0];
}
function setupInstance(wasi, instance) {
const [kInstance, kSetMemory] = getWasiSymbol(wasi, ['kInstance', 'kSetMemory']);
wasi[kInstance] = instance;
wasi[kSetMemory](instance.exports.memory);
}
//#endregion src/wasi-threads.ts
//#region src/worker.ts
class ThreadMessageHandler {
constructor(options) {
const postMsg = getPostMessage(options);
if (typeof postMsg !== 'function') {
throw new TypeError('options.postMessage is not a function');
}
this.postMessage = postMsg;
this.onLoad = options?.onLoad;
this.onError = typeof options?.onError === 'function' ? options.onError : (_type, err) => { throw err; };
this.instance = undefined;
this.messagesBeforeLoad = [];
}
instantiate(data) {
if (typeof this.onLoad === 'function') {
return this.onLoad(data);
}
throw new Error('ThreadMessageHandler.prototype.instantiate is not implemented');
}
handle(e) {
if (e?.data?.__emnapi__) {
const type = e.data.__emnapi__.type;
const payload = e.data.__emnapi__.payload;
try {
if (type === 'load') {
this._load(payload);
}
else if (type === 'start') {
this.handleAfterLoad(e, () => {
this._start(payload);
});
}
}
catch (err) {
this.onError(err, type);
}
}
}
_load(payload) {
if (this.instance !== undefined)
return;
let source;
try {
source = this.instantiate(payload);
}
catch (err) {
this._loaded(err, null, payload);
return;
}
const then = source && 'then' in source ? source.then : undefined;
if (typeof then === 'function') {
then.call(source, (source) => { this._loaded(null, source, payload); }, (err) => { this._loaded(err, null, payload); });
}
else {
this._loaded(null, source, payload);
}
}
_start(payload) {
const wasi_thread_start = this.instance.exports.wasi_thread_start;
if (typeof wasi_thread_start !== 'function') {
const err = new TypeError('wasi_thread_start is not exported');
notifyPthreadCreateResult(payload.sab, 2, err);
throw err;
}
const postMessage = this.postMessage;
const tid = payload.tid;
const startArg = payload.arg;
notifyPthreadCreateResult(payload.sab, 1);
try {
wasi_thread_start(tid, startArg);
}
catch (err) {
if (err !== 'unwind') {
throw err;
}
else {
return;
}
}
postMessage(createMessage('cleanup-thread', { tid }));
}
_loaded(err, source, payload) {
if (err) {
notifyPthreadCreateResult(payload.sab, 2, err);
throw err;
}
if (source == null) {
const err = new TypeError('onLoad should return an object');
notifyPthreadCreateResult(payload.sab, 2, err);
throw err;
}
const instance = source.instance;
if (!instance) {
const err = new TypeError('onLoad should return an object which includes "instance"');
notifyPthreadCreateResult(payload.sab, 2, err);
throw err;
}
this.instance = instance;
const postMessage = this.postMessage;
postMessage(createMessage('loaded', {}));
const messages = this.messagesBeforeLoad;
this.messagesBeforeLoad = [];
for (let i = 0; i < messages.length; i++) {
const data = messages[i];
this.handle({ data });
}
}
handleAfterLoad(e, f) {
if (this.instance !== undefined) {
f.call(this, e);
}
else {
this.messagesBeforeLoad.push(e.data);
}
}
}
function notifyPthreadCreateResult(sab, result, error) {
if (sab) {
serizeErrorToBuffer(sab.buffer, result, error);
Atomics.notify(sab, 0);
}
}
//#endregion src/worker.ts
export { ThreadManager, ThreadMessageHandler, WASIThreads, createInstanceProxy, isSharedArrayBuffer, isTrapError };

35
client/node_modules/@emnapi/wasi-threads/package.json generated vendored Normal file
View File

@@ -0,0 +1,35 @@
{
"name": "@emnapi/wasi-threads",
"version": "2.0.1",
"description": "WASI threads proposal implementation in JavaScript",
"type": "module",
"main": "./dist/wasi-threads.js",
"module": "./dist/wasi-threads.js",
"types": "./dist/wasi-threads.d.ts",
"sideEffects": false,
"exports": {
".": "./dist/wasi-threads.js",
"./package.json": "./package.json"
},
"dependencies": {
"tslib": "^2.4.0"
},
"scripts": {
"build": "rollup -c",
"build:test": "node ./test/build.js",
"test": "node ./test/index.js"
},
"repository": {
"type": "git",
"url": "git+https://github.com/toyobayashi/emnapi.git"
},
"author": "toyobayashi",
"license": "MIT",
"bugs": {
"url": "https://github.com/toyobayashi/emnapi/issues"
},
"homepage": "https://github.com/toyobayashi/emnapi#readme",
"publishConfig": {
"access": "public"
}
}

View File

@@ -0,0 +1,6 @@
import { defineConfig } from '@emnapi/shared'
export default defineConfig({
outputName: 'wasiThreads',
outputFile: 'wasi-threads'
})

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,321 @@
'use strict';
// @ts-check
/**
* @param {unknown} value
*/
const getType = (value) => {
if (value === undefined) return 0
if (value === null) return 1
if (isBuffer(value)) return 10
const t = typeof value;
if (t === 'boolean') return 2
if (t === 'number') return 3
if (t === 'string') return 4
if (t === 'object') return 6
if (t === 'bigint') return 9
return -1
};
/**
* @param {unknown} value
* @returns {value is Uint8Array}
*/
const isBuffer = (value) => {
const BufferCtor = globalThis.Buffer;
if (typeof BufferCtor?.isBuffer === 'function') {
return BufferCtor.isBuffer(value)
}
return value instanceof Uint8Array && value.constructor?.name === 'Buffer'
};
const RESPONSE_HEADER_SIZE = 16;
const RESPONSE_PAYLOAD_SIZE = 10240;
const RESPONSE_BUFFER_SIZE = RESPONSE_HEADER_SIZE + RESPONSE_PAYLOAD_SIZE;
/**
* @param {Int32Array} sab
* @param {Uint8Array} payload
*/
const writeResponsePayload = (sab, payload) => {
if (payload.length > RESPONSE_PAYLOAD_SIZE) {
throw new RangeError('payload overflow')
}
new Uint8Array(sab.buffer).set(payload, RESPONSE_HEADER_SIZE);
};
/**
* @param {import('memfs').IFs} memfs
* @param {any} value
* @param {ReturnType<typeof getType>} type
* @returns {Uint8Array}
*/
const encodeValue = (memfs, value, type) => {
switch (type) {
case 0:
case 1:
return new Uint8Array(0)
case 2: {
const view = new Int32Array(1);
view[0] = value ? 1 : 0;
return new Uint8Array(view.buffer)
}
case 3: {
const view = new Float64Array(1);
view[0] = value;
return new Uint8Array(view.buffer)
}
case 4: {
const view = new TextEncoder().encode(value);
return view
}
case 10:
return new Uint8Array(value)
case 6: {
function storeConstructor(obj, memfs, processed = new WeakSet()) {
if (!obj || typeof obj !== 'object') {
return
}
if (processed.has(obj)) {
return
}
processed.add(obj);
const [entry] =
Object.entries(memfs).filter(([_, v]) => v === obj.constructor)[0] ??
[];
if (entry) {
Object.defineProperty(obj, '__constructor__', {
configurable: true,
writable: true,
enumerable: true,
value: entry,
});
}
for (const value of Object.values(obj)) {
storeConstructor(value, memfs, processed);
}
}
storeConstructor(value, memfs);
const json = JSON.stringify(value, (_, value) => {
if (typeof value === 'bigint') {
return `BigInt(${String(value)})`
}
if (value instanceof Error) {
return {
...value,
message: value.message,
stack: value.stack,
__error__: value.constructor.name,
}
}
return value
});
const view = new TextEncoder().encode(json);
return view
}
case 9: {
return new TextEncoder().encode(String(value))
}
case -1:
default:
throw new Error('unsupported data')
}
};
/**
* @param {typeof import('memfs')} memfs
* @param {Uint8Array} payload
* @param {number} type
* @returns {any}
*/
const decodeValue = (memfs, payload, type) => {
if (type === 0) return undefined
if (type === 1) return null
if (type === 2)
return Boolean(new Int32Array(payload.buffer, payload.byteOffset, 1)[0])
if (type === 3)
return new Float64Array(payload.buffer, payload.byteOffset, 1)[0]
if (type === 4) return new TextDecoder().decode(payload.slice())
if (type === 10) {
const BufferCtor = globalThis.Buffer;
if (typeof BufferCtor?.from === 'function') {
return BufferCtor.from(payload)
}
return payload.slice()
}
if (type === 6) {
const obj = JSON.parse(
new TextDecoder().decode(payload.slice()),
(_key, value) => {
if (typeof value === 'string') {
const matched = value.match(/^BigInt\((-?\d+)\)$/);
if (matched && matched[1]) {
return BigInt(matched[1])
}
}
return value
},
);
function loadConstructor(obj, memfs, processed = new WeakSet()) {
if (!obj || typeof obj !== 'object') {
return
}
if (processed.has(obj)) {
return
}
processed.add(obj);
if (obj.__constructor__) {
const ctor = obj.__constructor__;
delete obj.__constructor__;
Object.setPrototypeOf(obj, memfs[ctor].prototype);
}
for (const value of Object.values(obj)) {
loadConstructor(value, memfs, processed);
}
}
loadConstructor(obj, memfs);
if (obj.__error__) {
const name = obj.__error__;
const ErrorConstructor = globalThis[name] || Error;
delete obj.__error__;
const err = new ErrorConstructor(obj.message);
Object.defineProperty(err, 'stack', {
configurable: true,
enumerable: false,
writable: true,
value: err.stack,
});
Object.defineProperty(err, Symbol.toStringTag, {
configurable: true,
enumerable: false,
writable: true,
value: name,
});
for (const [k, v] of Object.entries(obj)) {
if (k === 'message' || k === 'stack') continue
err[k] = v;
}
return err
}
return obj
}
if (type === 9) {
return BigInt(new TextDecoder().decode(payload.slice()))
}
throw new Error('unsupported data')
};
/**
* @param {import('memfs').IFs} fs
* @returns {(e: { data: { __fs__: { sab: Int32Array, type: keyof import('memfs').IFs, payload: any[] } } }) => void}
*/
// oxlint-disable-next-line no-unused-vars -- fixed in an upcoming release
const createOnMessage = (fs) =>
function onMessage(e) {
if (e.data.__fs__) {
/**
* 0..4 status(int32_t): 21(waiting) 0(success) 1(error)
* 5..8 type(napi_valuetype): 0(undefined) 1(null) 2(boolean) 3(number) 4(string) 6(jsonstring) 9(bigint) 10(buffer) -1(unsupported)
* 9..16 payload_size(uint32_t) <= 10240
* 16..16 + payload_size payload_content
*/
const { sab, type, payload } = e.data.__fs__;
const fn = fs[type];
try {
const ret = fn.apply(fs, payload);
const t = getType(ret);
Atomics.store(sab, 1, t);
const v = encodeValue(fs, ret, t);
Atomics.store(sab, 2, v.length);
writeResponsePayload(sab, v);
Atomics.store(sab, 0, 0); // success
} catch (/** @type {any} */ err) {
let t = getType(err);
let v;
try {
if (t === -1) {
throw new Error('unsupported data')
}
v = encodeValue(fs, err, t);
} catch {
const fallback = (() => {
try {
return String(err)
} catch {
return 'Unserializable thrown value'
}
})();
t = getType(fallback);
v = encodeValue(fs, fallback, t);
}
if (v.length > RESPONSE_PAYLOAD_SIZE) {
const overflowErr = new RangeError('payload overflow');
t = getType(overflowErr);
v = encodeValue(fs, overflowErr, t);
}
Atomics.store(sab, 1, t);
Atomics.store(sab, 2, v.length);
writeResponsePayload(sab, v);
Atomics.store(sab, 0, 1); // error
} finally {
Atomics.notify(sab, 0);
}
}
};
/**
* @param {typeof import('memfs')} memfs
*/
const createFsProxy = (memfs) =>
new Proxy(
{},
{
get(_target, p, _receiver) {
/**
* @param {any[]} args
*/
return function (...args) {
const sab = new SharedArrayBuffer(RESPONSE_BUFFER_SIZE);
const i32arr = new Int32Array(sab);
Atomics.store(i32arr, 0, 21);
postMessage({
__fs__: {
sab: i32arr,
type: p,
payload: args,
},
});
Atomics.wait(i32arr, 0, 21);
const status = Atomics.load(i32arr, 0);
const type = Atomics.load(i32arr, 1);
const size = Atomics.load(i32arr, 2);
const content = new Uint8Array(sab, RESPONSE_HEADER_SIZE, size);
const value = decodeValue(memfs, content, type);
if (status === 1) {
throw value
}
return value
}
},
},
);
exports.createFsProxy = createFsProxy;
exports.createOnMessage = createOnMessage;

25525
client/node_modules/@napi-rs/wasm-runtime/dist/fs.js generated vendored Normal file

File diff suppressed because one or more lines are too long

316
client/node_modules/@napi-rs/wasm-runtime/fs-proxy.js generated vendored Normal file
View File

@@ -0,0 +1,316 @@
// @ts-check
/**
* @param {unknown} value
*/
const getType = (value) => {
if (value === undefined) return 0
if (value === null) return 1
if (isBuffer(value)) return 10
const t = typeof value
if (t === 'boolean') return 2
if (t === 'number') return 3
if (t === 'string') return 4
if (t === 'object') return 6
if (t === 'bigint') return 9
return -1
}
/**
* @param {unknown} value
* @returns {value is Uint8Array}
*/
const isBuffer = (value) => {
const BufferCtor = globalThis.Buffer
if (typeof BufferCtor?.isBuffer === 'function') {
return BufferCtor.isBuffer(value)
}
return value instanceof Uint8Array && value.constructor?.name === 'Buffer'
}
const RESPONSE_HEADER_SIZE = 16
const RESPONSE_PAYLOAD_SIZE = 10240
const RESPONSE_BUFFER_SIZE = RESPONSE_HEADER_SIZE + RESPONSE_PAYLOAD_SIZE
/**
* @param {Int32Array} sab
* @param {Uint8Array} payload
*/
const writeResponsePayload = (sab, payload) => {
if (payload.length > RESPONSE_PAYLOAD_SIZE) {
throw new RangeError('payload overflow')
}
new Uint8Array(sab.buffer).set(payload, RESPONSE_HEADER_SIZE)
}
/**
* @param {import('memfs').IFs} memfs
* @param {any} value
* @param {ReturnType<typeof getType>} type
* @returns {Uint8Array}
*/
const encodeValue = (memfs, value, type) => {
switch (type) {
case 0:
case 1:
return new Uint8Array(0)
case 2: {
const view = new Int32Array(1)
view[0] = value ? 1 : 0
return new Uint8Array(view.buffer)
}
case 3: {
const view = new Float64Array(1)
view[0] = value
return new Uint8Array(view.buffer)
}
case 4: {
const view = new TextEncoder().encode(value)
return view
}
case 10:
return new Uint8Array(value)
case 6: {
function storeConstructor(obj, memfs, processed = new WeakSet()) {
if (!obj || typeof obj !== 'object') {
return
}
if (processed.has(obj)) {
return
}
processed.add(obj)
const [entry] =
Object.entries(memfs).filter(([_, v]) => v === obj.constructor)[0] ??
[]
if (entry) {
Object.defineProperty(obj, '__constructor__', {
configurable: true,
writable: true,
enumerable: true,
value: entry,
})
}
for (const value of Object.values(obj)) {
storeConstructor(value, memfs, processed)
}
}
storeConstructor(value, memfs)
const json = JSON.stringify(value, (_, value) => {
if (typeof value === 'bigint') {
return `BigInt(${String(value)})`
}
if (value instanceof Error) {
return {
...value,
message: value.message,
stack: value.stack,
__error__: value.constructor.name,
}
}
return value
})
const view = new TextEncoder().encode(json)
return view
}
case 9: {
return new TextEncoder().encode(String(value))
}
case -1:
default:
throw new Error('unsupported data')
}
}
/**
* @param {typeof import('memfs')} memfs
* @param {Uint8Array} payload
* @param {number} type
* @returns {any}
*/
const decodeValue = (memfs, payload, type) => {
if (type === 0) return undefined
if (type === 1) return null
if (type === 2)
return Boolean(new Int32Array(payload.buffer, payload.byteOffset, 1)[0])
if (type === 3)
return new Float64Array(payload.buffer, payload.byteOffset, 1)[0]
if (type === 4) return new TextDecoder().decode(payload.slice())
if (type === 10) {
const BufferCtor = globalThis.Buffer
if (typeof BufferCtor?.from === 'function') {
return BufferCtor.from(payload)
}
return payload.slice()
}
if (type === 6) {
const obj = JSON.parse(
new TextDecoder().decode(payload.slice()),
(_key, value) => {
if (typeof value === 'string') {
const matched = value.match(/^BigInt\((-?\d+)\)$/)
if (matched && matched[1]) {
return BigInt(matched[1])
}
}
return value
},
)
function loadConstructor(obj, memfs, processed = new WeakSet()) {
if (!obj || typeof obj !== 'object') {
return
}
if (processed.has(obj)) {
return
}
processed.add(obj)
if (obj.__constructor__) {
const ctor = obj.__constructor__
delete obj.__constructor__
Object.setPrototypeOf(obj, memfs[ctor].prototype)
}
for (const value of Object.values(obj)) {
loadConstructor(value, memfs, processed)
}
}
loadConstructor(obj, memfs)
if (obj.__error__) {
const name = obj.__error__
const ErrorConstructor = globalThis[name] || Error
delete obj.__error__
const err = new ErrorConstructor(obj.message)
Object.defineProperty(err, 'stack', {
configurable: true,
enumerable: false,
writable: true,
value: err.stack,
})
Object.defineProperty(err, Symbol.toStringTag, {
configurable: true,
enumerable: false,
writable: true,
value: name,
})
for (const [k, v] of Object.entries(obj)) {
if (k === 'message' || k === 'stack') continue
err[k] = v
}
return err
}
return obj
}
if (type === 9) {
return BigInt(new TextDecoder().decode(payload.slice()))
}
throw new Error('unsupported data')
}
/**
* @param {import('memfs').IFs} fs
* @returns {(e: { data: { __fs__: { sab: Int32Array, type: keyof import('memfs').IFs, payload: any[] } } }) => void}
*/
// oxlint-disable-next-line no-unused-vars -- fixed in an upcoming release
export const createOnMessage = (fs) =>
function onMessage(e) {
if (e.data.__fs__) {
/**
* 0..4 status(int32_t): 21(waiting) 0(success) 1(error)
* 5..8 type(napi_valuetype): 0(undefined) 1(null) 2(boolean) 3(number) 4(string) 6(jsonstring) 9(bigint) 10(buffer) -1(unsupported)
* 9..16 payload_size(uint32_t) <= 10240
* 16..16 + payload_size payload_content
*/
const { sab, type, payload } = e.data.__fs__
const fn = fs[type]
try {
const ret = fn.apply(fs, payload)
const t = getType(ret)
Atomics.store(sab, 1, t)
const v = encodeValue(fs, ret, t)
Atomics.store(sab, 2, v.length)
writeResponsePayload(sab, v)
Atomics.store(sab, 0, 0) // success
} catch (/** @type {any} */ err) {
let t = getType(err)
let v
try {
if (t === -1) {
throw new Error('unsupported data')
}
v = encodeValue(fs, err, t)
} catch {
const fallback = (() => {
try {
return String(err)
} catch {
return 'Unserializable thrown value'
}
})()
t = getType(fallback)
v = encodeValue(fs, fallback, t)
}
if (v.length > RESPONSE_PAYLOAD_SIZE) {
const overflowErr = new RangeError('payload overflow')
t = getType(overflowErr)
v = encodeValue(fs, overflowErr, t)
}
Atomics.store(sab, 1, t)
Atomics.store(sab, 2, v.length)
writeResponsePayload(sab, v)
Atomics.store(sab, 0, 1) // error
} finally {
Atomics.notify(sab, 0)
}
}
}
/**
* @param {typeof import('memfs')} memfs
*/
export const createFsProxy = (memfs) =>
new Proxy(
{},
{
get(_target, p, _receiver) {
/**
* @param {any[]} args
*/
return function (...args) {
const sab = new SharedArrayBuffer(RESPONSE_BUFFER_SIZE)
const i32arr = new Int32Array(sab)
Atomics.store(i32arr, 0, 21)
postMessage({
__fs__: {
sab: i32arr,
type: p,
payload: args,
},
})
Atomics.wait(i32arr, 0, 21)
const status = Atomics.load(i32arr, 0)
const type = Atomics.load(i32arr, 1)
const size = Atomics.load(i32arr, 2)
const content = new Uint8Array(sab, RESPONSE_HEADER_SIZE, size)
const value = decodeValue(memfs, content, type)
if (status === 1) {
throw value
}
return value
}
},
},
)

74
client/node_modules/@napi-rs/wasm-runtime/package.json generated vendored Normal file
View File

@@ -0,0 +1,74 @@
{
"name": "@napi-rs/wasm-runtime",
"version": "1.2.1",
"type": "module",
"description": "Runtime and polyfill for wasm targets",
"engines": {
"node": "^20.19.0 || ^22.13.0 || >=23.5.0"
},
"homepage": "https://napi.rs/",
"author": {
"name": "LongYinan",
"url": "https://github.com/Brooooooklyn"
},
"repository": {
"type": "git",
"url": "git+https://github.com/napi-rs/napi-rs.git",
"directory": "wasm-runtime"
},
"license": "MIT",
"publishConfig": {
"registry": "https://registry.npmjs.org/",
"access": "public"
},
"files": [
"runtime.cjs",
"runtime.js",
"fs-proxy.js",
"dist/*.cjs",
"dist/*.js"
],
"devDependencies": {
"@emnapi/core": "2.0.0-alpha.3",
"@rollup/plugin-alias": "^6.0.0",
"@rollup/plugin-commonjs": "^29.0.3",
"@rollup/plugin-inject": "^5.0.5",
"@rollup/plugin-json": "^6.1.0",
"@rollup/plugin-node-resolve": "^16.0.3",
"@rollup/plugin-replace": "^6.0.3",
"buffer": "^6.0.3",
"events": "^3.3.0",
"memfs": "^4.64.0",
"node-inspect-extracted": "^3.3.2",
"path-browserify": "^1.0.1",
"process": "^0.11.10",
"readable-stream": "^4.7.0",
"rollup": "^4.61.1",
"rollup-plugin-polyfill-node": "^0.13.0",
"tslib": "^2.8.1"
},
"dependencies": {
"@tybys/wasm-util": "^0.10.3"
},
"peerDependencies": {
"@emnapi/core": "^1.7.1 || ^2.0.0-alpha.3",
"@emnapi/runtime": "^1.7.1 || ^2.0.0-alpha.3"
},
"scripts": {
"build": "rollup -c rollup.config.js",
"test": "yarn run build && node --test"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
},
"exports": {
".": {
"import": "./runtime.js",
"require": "./runtime.cjs"
},
"./fs": {
"import": "./dist/fs.js"
}
}
}

39
client/node_modules/@napi-rs/wasm-runtime/runtime.cjs generated vendored Normal file
View File

@@ -0,0 +1,39 @@
const {
MessageHandler,
instantiateNapiModuleSync,
instantiateNapiModule,
} = require('@emnapi/core')
// Single-threaded (non-shared-memory) WASI builds link an emnapi archive
// without the C async-work and threadsafe-function implementations (they are
// unconditional `napi_generic_failure` stubs without threads), so the
// generated loaders provide the JavaScript implementations through these
// plugins instead. Raw `instantiateNapiModule(Sync)` callers instantiating a
// single-threaded napi-rs wasm must pass them too:
// `plugins: [emnapiAsyncWorkPlugin, emnapiTSFNPlugin]` — without them
// instantiation fails with a LinkError naming the missing import. Threaded
// (shared-memory) builds link the C implementations and need no plugins;
// this mirrors the upstream @emnapi/core v2 plugin split (v1 bundled these
// implementations in the core runtime). The plugins are bundled into this
// package so loading the runtime with @emnapi/core v1 does not resolve the
// v2-only `@emnapi/core/plugins` package export.
const {
emnapiAsyncWorkPlugin,
emnapiTSFNPlugin,
} = require('./dist/emnapi-plugins.cjs')
const { createContext, getDefaultContext } = require('@emnapi/runtime')
const { WASI } = require('@tybys/wasm-util')
const { createFsProxy, createOnMessage } = require('./dist/fs-proxy.cjs')
module.exports = {
MessageHandler,
createContext,
emnapiAsyncWorkPlugin,
emnapiTSFNPlugin,
instantiateNapiModule,
instantiateNapiModuleSync,
getDefaultContext,
WASI,
createFsProxy,
createOnMessage,
}

36
client/node_modules/@napi-rs/wasm-runtime/runtime.js generated vendored Normal file
View File

@@ -0,0 +1,36 @@
import * as emnapiCore from '@emnapi/core'
import * as emnapiRuntime from '@emnapi/runtime'
import {
emnapiAsyncWorkPlugin,
emnapiTSFNPlugin,
} from './dist/emnapi-plugins.js'
const { instantiateNapiModuleSync, instantiateNapiModule, MessageHandler } =
emnapiCore
const { createContext, getDefaultContext } = emnapiRuntime
// Single-threaded (non-shared-memory) WASI builds link an emnapi archive
// without the C async-work and threadsafe-function implementations (they are
// unconditional `napi_generic_failure` stubs without threads), so the
// generated loaders provide the JavaScript implementations through these
// plugins instead. Raw `instantiateNapiModule(Sync)` callers instantiating a
// single-threaded napi-rs wasm must pass them too:
// `plugins: [emnapiAsyncWorkPlugin, emnapiTSFNPlugin]` — without them
// instantiation fails with a LinkError naming the missing import. Threaded
// (shared-memory) builds link the C implementations and need no plugins;
// this mirrors the upstream @emnapi/core v2 plugin split (v1 bundled these
// implementations in the core runtime). The plugins are bundled into this
// package so loading the runtime with @emnapi/core v1 does not resolve the
// v2-only `@emnapi/core/plugins` package export.
export {
MessageHandler,
createContext,
emnapiAsyncWorkPlugin,
emnapiTSFNPlugin,
getDefaultContext,
instantiateNapiModule,
instantiateNapiModuleSync,
}
export * from '@tybys/wasm-util'
export { createOnMessage, createFsProxy } from './fs-proxy.js'

22
client/node_modules/@oxc-project/types/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,22 @@
MIT License
Copyright (c) 2024-present VoidZero Inc. & Contributors
Copyright (c) 2023 Boshen
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

3
client/node_modules/@oxc-project/types/README.md generated vendored Normal file
View File

@@ -0,0 +1,3 @@
# Oxc Types
Typescript definitions for Oxc AST nodes.

26
client/node_modules/@oxc-project/types/package.json generated vendored Normal file
View File

@@ -0,0 +1,26 @@
{
"name": "@oxc-project/types",
"version": "0.142.0",
"description": "Types for Oxc AST nodes",
"keywords": [
"AST",
"Parser"
],
"homepage": "https://oxc.rs",
"bugs": "https://github.com/oxc-project/oxc/issues",
"license": "MIT",
"author": "Boshen and oxc contributors",
"repository": {
"type": "git",
"url": "git+https://github.com/oxc-project/oxc.git",
"directory": "npm/oxc-types"
},
"funding": {
"url": "https://github.com/sponsors/Boshen"
},
"files": [
"types.d.ts"
],
"type": "module",
"types": "types.d.ts"
}

1912
client/node_modules/@oxc-project/types/types.d.ts generated vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,3 @@
# `@rolldown/binding-linux-x64-gnu`
This is the **x86_64-unknown-linux-gnu** binary for `@rolldown/binding`

View File

@@ -0,0 +1,40 @@
{
"name": "@rolldown/binding-linux-x64-gnu",
"version": "1.2.1",
"cpu": [
"x64"
],
"main": "rolldown-binding.linux-x64-gnu.node",
"files": [
"rolldown-binding.linux-x64-gnu.node"
],
"description": "Fast JavaScript/TypeScript bundler in Rust with Rollup-compatible API.",
"keywords": [
"bundler",
"esbuild",
"parcel",
"rolldown",
"rollup",
"webpack"
],
"homepage": "https://rolldown.rs/",
"license": "MIT",
"engines": {
"node": "^20.19.0 || >=22.12.0"
},
"repository": {
"type": "git",
"url": "git+https://github.com/rolldown/rolldown.git",
"directory": "packages/rolldown"
},
"publishConfig": {
"registry": "https://registry.npmjs.org/",
"access": "public"
},
"os": [
"linux"
],
"libc": [
"glibc"
]
}

View File

@@ -0,0 +1,3 @@
# `@rolldown/binding-wasm32-wasi`
This is the **wasm32-wasip1-threads** binary for `@rolldown/binding`

View File

@@ -0,0 +1,44 @@
{
"name": "@rolldown/binding-wasm32-wasi",
"version": "1.2.1",
"main": "rolldown-binding.wasi.cjs",
"files": [
"rolldown-binding.wasm32-wasi.wasm",
"rolldown-binding.wasi.cjs",
"rolldown-binding.wasi.d.cts",
"rolldown-binding.wasi-browser.js",
"wasi-worker.mjs",
"wasi-worker-browser.mjs"
],
"description": "Fast JavaScript/TypeScript bundler in Rust with Rollup-compatible API.",
"keywords": [
"bundler",
"esbuild",
"parcel",
"rolldown",
"rollup",
"webpack"
],
"homepage": "https://rolldown.rs/",
"license": "MIT",
"engines": {
"node": "^20.19.0 || ^22.13.0 || >=23.5.0"
},
"repository": {
"type": "git",
"url": "git+https://github.com/rolldown/rolldown.git",
"directory": "packages/rolldown"
},
"publishConfig": {
"registry": "https://registry.npmjs.org/",
"access": "public"
},
"types": "rolldown-binding.wasi.d.cts",
"browser": "rolldown-binding.wasi-browser.js",
"type": "module",
"dependencies": {
"@napi-rs/wasm-runtime": "^1.2.0",
"@emnapi/core": "2.0.0-alpha.3",
"@emnapi/runtime": "2.0.0-alpha.3"
}
}

View File

@@ -0,0 +1,431 @@
import {
emnapiAsyncWorkPlugin as __emnapiAsyncWorkPlugin,
emnapiTSFNPlugin as __emnapiTSFNPlugin,
createOnMessage as __wasmCreateOnMessageForFsProxy,
instantiateNapiModule as __emnapiInstantiateNapiModule,
WASI as __WASI,
} from '@napi-rs/wasm-runtime'
import { createContext as __emnapiCreateContext } from '@emnapi/runtime'
import { memfs } from '@napi-rs/wasm-runtime/fs'
export const { fs: __fs, vol: __volume } = memfs()
const __wasi = new __WASI({
version: 'preview1',
fs: __fs,
preopens: {
'/': '/',
},
})
const __wasmUrl = new URL('./rolldown-binding.wasm32-wasi.wasm', import.meta.url).href
const __wasmResponse = await globalThis.fetch(__wasmUrl)
if (!__wasmResponse.ok) {
throw new Error(
'Failed to fetch WASI module ' +
__wasmUrl +
': ' +
__wasmResponse.status +
' ' +
(__wasmResponse.statusText || 'Unknown Status'),
)
}
const __wasmFile = await __wasmResponse.arrayBuffer()
const __sharedMemory = new WebAssembly.Memory({
initial: 16384,
maximum: 65536,
shared: true,
})
let __emnapiContext
const __wasiDisposeSymbol = Symbol.for('napi.rs.wasi.dispose')
const __wasiWorkers = new Set()
let __napiInstance
let __emnapiContextDestroyed = false
let __emnapiContextDestroyPromise
let __emnapiWasmEnvCleanupPrepared = false
let __wasiDisposed = false
let __wasiDisposePromise
let __completeWasiDisposal = function() {}
function __isThenable(value) {
return (
value !== null &&
(typeof value === 'object' || typeof value === 'function') &&
typeof value.then === 'function'
)
}
function __createCleanupError(errors, message) {
if (errors.length === 1) {
return errors[0]
}
const __AggregateError = globalThis.AggregateError
if (typeof __AggregateError === 'function') {
return new __AggregateError(errors, message)
}
const error = new Error(message)
error.errors = errors
return error
}
function __attachCleanupErrors(error, cleanupErrors) {
if (cleanupErrors.length === 0) {
return error
}
const cleanupError = __createCleanupError(
cleanupErrors,
'WASI binding cleanup failed',
)
try {
if (
error &&
(typeof error === 'object' || typeof error === 'function')
) {
if (error.cause === undefined) {
error.cause = cleanupError
if (error.cause === cleanupError) {
return error
}
}
if (Array.isArray(error.cleanupErrors)) {
error.cleanupErrors.push(cleanupError)
return error
} else {
const attachedCleanupErrors = [cleanupError]
error.cleanupErrors = attachedCleanupErrors
if (error.cleanupErrors === attachedCleanupErrors) {
return error
}
}
}
} catch {}
const aggregate = __createCleanupError(
[error, cleanupError],
'WASI binding initialization and cleanup failed',
)
try {
aggregate.cause = error
} catch {}
return aggregate
}
function __prepareWasmEnvCleanup() {
if (__emnapiWasmEnvCleanupPrepared) {
return
}
const prepare = __napiInstance?.exports?.napi_prepare_wasm_env_cleanup
if (typeof prepare === 'function') {
prepare()
}
__emnapiWasmEnvCleanupPrepared = true
}
function __destroyEmnapiContext() {
if (__emnapiContextDestroyed || __emnapiContext === undefined) {
__emnapiContextDestroyed = true
return
}
if (__emnapiContextDestroyPromise) {
return __emnapiContextDestroyPromise
}
__prepareWasmEnvCleanup()
const result = __emnapiContext.destroy()
if (!__isThenable(result)) {
__emnapiContextDestroyed = true
return
}
const destroyPromise = Promise.resolve(result).then(
(value) => {
__emnapiContextDestroyed = true
return value
},
(error) => {
__emnapiContextDestroyPromise = undefined
throw error
},
)
__emnapiContextDestroyPromise = destroyPromise
return destroyPromise
}
function __terminateWasiWorkers() {
const cleanupErrors = []
const pending = []
for (const worker of __wasiWorkers) {
let result
try {
result = worker.terminate()
} catch (error) {
cleanupErrors.push(error)
continue
}
if (__isThenable(result)) {
pending.push(
Promise.resolve(result).then(
() => {
__wasiWorkers.delete(worker)
},
(error) => {
cleanupErrors.push(error)
},
),
)
} else {
__wasiWorkers.delete(worker)
}
}
const finish = () => {
if (cleanupErrors.length > 0) {
throw __createCleanupError(
cleanupErrors,
'Failed to terminate WASI workers',
)
}
}
return pending.length > 0 ? Promise.all(pending).then(finish) : finish()
}
function __finishWasiDisposal() {
const workerResult = __terminateWasiWorkers()
if (__isThenable(workerResult)) {
return Promise.resolve(workerResult).then(__completeWasiDisposal)
}
return __completeWasiDisposal()
}
function __startWasiDisposal() {
const destroyResult = __destroyEmnapiContext()
if (__isThenable(destroyResult)) {
return Promise.resolve(destroyResult).then(__finishWasiDisposal)
}
return __finishWasiDisposal()
}
/**
* Disposes this generated WASI binding.
*
* Access this function with:
* binding[Symbol.for('napi.rs.wasi.dispose')]()
*/
function __disposeWasiBinding() {
if (__wasiDisposePromise) {
return __wasiDisposePromise
}
if (__wasiDisposed) {
return Promise.resolve()
}
let resolveDispose
let rejectDispose
const disposePromise = new Promise((resolve, reject) => {
resolveDispose = resolve
rejectDispose = reject
})
__wasiDisposePromise = disposePromise
let result
try {
result = __startWasiDisposal()
} catch (error) {
__wasiDisposePromise = undefined
rejectDispose(error)
return disposePromise
}
Promise.resolve(result).then(
(value) => {
__wasiDisposed = true
resolveDispose(value)
},
(error) => {
__wasiDisposePromise = undefined
rejectDispose(error)
},
)
return disposePromise
}
function __publishWasiDispose(exports) {
Object.defineProperty(exports, __wasiDisposeSymbol, {
configurable: false,
enumerable: false,
value: __disposeWasiBinding,
writable: false,
})
}
function __finishWasiInitializationRollback(cleanupErrors) {
let workerResult
try {
workerResult = __terminateWasiWorkers()
} catch (cleanupError) {
cleanupErrors.push(cleanupError)
return cleanupErrors
}
if (__isThenable(workerResult)) {
return Promise.resolve(workerResult)
.catch((cleanupError) => {
cleanupErrors.push(cleanupError)
})
.then(() => cleanupErrors)
}
return cleanupErrors
}
function __rollbackWasiInitialization() {
const cleanupErrors = []
let destroyResult
try {
destroyResult = __destroyEmnapiContext()
} catch (cleanupError) {
cleanupErrors.push(cleanupError)
return __finishWasiInitializationRollback(cleanupErrors)
}
if (__isThenable(destroyResult)) {
return Promise.resolve(destroyResult)
.catch((cleanupError) => {
cleanupErrors.push(cleanupError)
})
.then(() => __finishWasiInitializationRollback(cleanupErrors))
}
return __finishWasiInitializationRollback(cleanupErrors)
}
let __wasiModule
let __napiModule
try {
__emnapiContext = __emnapiCreateContext({ autoDestroy: false })
__emnapiContext.suppressDestroy()
;({
instance: __napiInstance,
module: __wasiModule,
napiModule: __napiModule,
} = await __emnapiInstantiateNapiModule(__wasmFile, {
context: __emnapiContext,
asyncWorkPoolSize: 4,
plugins: [__emnapiAsyncWorkPlugin, __emnapiTSFNPlugin],
wasi: __wasi,
onCreateWorker() {
const worker = new Worker(new URL('@rolldown/binding-wasm32-wasi/wasi-worker-browser.mjs', import.meta.url), {
type: 'module',
})
__wasiWorkers.add(worker)
worker.addEventListener('message', __wasmCreateOnMessageForFsProxy(__fs))
worker.addEventListener('message', (event) => {
if (event.data && typeof event.data === 'object' && event.data.type === 'error') {
const __CustomEvent = globalThis.CustomEvent
if (
typeof globalThis.dispatchEvent === 'function' &&
typeof __CustomEvent === 'function'
) {
globalThis.dispatchEvent(
new __CustomEvent('napi-rs-worker-error', { detail: event.data }),
)
}
}
})
return worker
},
overwriteImports(importObject) {
importObject.env = {
...importObject.env,
...importObject.napi,
...importObject.emnapi,
memory: __sharedMemory,
}
return importObject
},
beforeInit({ instance }) {
__napiInstance = instance
for (const name of Object.keys(instance.exports)) {
if (name.startsWith('__napi_register__')) {
instance.exports[name]()
}
}
},
}))
__publishWasiDispose(__napiModule.exports)
} catch (error) {
const cleanupErrors = await __rollbackWasiInitialization()
throw __attachCleanupErrors(error, cleanupErrors)
}
export default __napiModule.exports
export const LegalCommentsMode = __napiModule.exports.LegalCommentsMode
export const minify = __napiModule.exports.minify
export const minifySync = __napiModule.exports.minifySync
export const Severity = __napiModule.exports.Severity
export const ParseResult = __napiModule.exports.ParseResult
export const ExportExportNameKind = __napiModule.exports.ExportExportNameKind
export const ExportImportNameKind = __napiModule.exports.ExportImportNameKind
export const ExportLocalNameKind = __napiModule.exports.ExportLocalNameKind
export const ImportNameKind = __napiModule.exports.ImportNameKind
export const parse = __napiModule.exports.parse
export const parseSync = __napiModule.exports.parseSync
export const rawTransferSupported = __napiModule.exports.rawTransferSupported
export const ResolverFactory = __napiModule.exports.ResolverFactory
export const EnforceExtension = __napiModule.exports.EnforceExtension
export const ModuleType = __napiModule.exports.ModuleType
export const sync = __napiModule.exports.sync
export const HelperMode = __napiModule.exports.HelperMode
export const isolatedDeclaration = __napiModule.exports.isolatedDeclaration
export const isolatedDeclarationSync = __napiModule.exports.isolatedDeclarationSync
export const moduleRunnerTransform = __napiModule.exports.moduleRunnerTransform
export const moduleRunnerTransformSync = __napiModule.exports.moduleRunnerTransformSync
export const transform = __napiModule.exports.transform
export const transformSync = __napiModule.exports.transformSync
export const BindingBundleEndEventData = __napiModule.exports.BindingBundleEndEventData
export const BindingBundleErrorEventData = __napiModule.exports.BindingBundleErrorEventData
export const BindingBundler = __napiModule.exports.BindingBundler
export const BindingCallableBuiltinPlugin = __napiModule.exports.BindingCallableBuiltinPlugin
export const BindingChunkingContext = __napiModule.exports.BindingChunkingContext
export const BindingDecodedMap = __napiModule.exports.BindingDecodedMap
export const BindingDevEngine = __napiModule.exports.BindingDevEngine
export const BindingLoadPluginContext = __napiModule.exports.BindingLoadPluginContext
export const BindingMagicString = __napiModule.exports.BindingMagicString
export const BindingModuleInfo = __napiModule.exports.BindingModuleInfo
export const BindingNormalizedOptions = __napiModule.exports.BindingNormalizedOptions
export const BindingOutputAsset = __napiModule.exports.BindingOutputAsset
export const BindingOutputChunk = __napiModule.exports.BindingOutputChunk
export const BindingPluginContext = __napiModule.exports.BindingPluginContext
export const BindingRenderedChunk = __napiModule.exports.BindingRenderedChunk
export const BindingRenderedChunkMeta = __napiModule.exports.BindingRenderedChunkMeta
export const BindingRenderedModule = __napiModule.exports.BindingRenderedModule
export const BindingSourceMap = __napiModule.exports.BindingSourceMap
export const BindingTransformPluginContext = __napiModule.exports.BindingTransformPluginContext
export const BindingWatcher = __napiModule.exports.BindingWatcher
export const BindingWatcherBundler = __napiModule.exports.BindingWatcherBundler
export const BindingWatcherChangeData = __napiModule.exports.BindingWatcherChangeData
export const BindingWatcherEvent = __napiModule.exports.BindingWatcherEvent
export const ParallelJsPluginRegistry = __napiModule.exports.ParallelJsPluginRegistry
export const TraceSubscriberGuard = __napiModule.exports.TraceSubscriberGuard
export const TsconfigCache = __napiModule.exports.TsconfigCache
export const BindingAttachDebugInfo = __napiModule.exports.BindingAttachDebugInfo
export const BindingBuiltinPluginName = __napiModule.exports.BindingBuiltinPluginName
export const BindingChunkModuleOrderBy = __napiModule.exports.BindingChunkModuleOrderBy
export const BindingErrorStage = __napiModule.exports.BindingErrorStage
export const BindingLogLevel = __napiModule.exports.BindingLogLevel
export const BindingPluginOrder = __napiModule.exports.BindingPluginOrder
export const BindingPropertyReadSideEffects = __napiModule.exports.BindingPropertyReadSideEffects
export const BindingPropertyWriteSideEffects = __napiModule.exports.BindingPropertyWriteSideEffects
export const BindingRebuildStrategy = __napiModule.exports.BindingRebuildStrategy
export const collapseSourcemaps = __napiModule.exports.collapseSourcemaps
export const enhancedTransform = __napiModule.exports.enhancedTransform
export const enhancedTransformSync = __napiModule.exports.enhancedTransformSync
export const FilterTokenKind = __napiModule.exports.FilterTokenKind
export const initTraceSubscriber = __napiModule.exports.initTraceSubscriber
export const registerPlugins = __napiModule.exports.registerPlugins
export const resolveTsconfig = __napiModule.exports.resolveTsconfig
export const shutdownAsyncRuntime = __napiModule.exports.shutdownAsyncRuntime
export const startAsyncRuntime = __napiModule.exports.startAsyncRuntime

View File

@@ -0,0 +1,722 @@
// napi-rs-artifact-metadata:{"version":2,"rootEntry":"binding.cjs","exports":["LegalCommentsMode","minify","minifySync","Severity","ParseResult","ExportExportNameKind","ExportImportNameKind","ExportLocalNameKind","ImportNameKind","parse","parseSync","rawTransferSupported","ResolverFactory","EnforceExtension","ModuleType","sync","HelperMode","isolatedDeclaration","isolatedDeclarationSync","moduleRunnerTransform","moduleRunnerTransformSync","transform","transformSync","BindingBundleEndEventData","BindingBundleErrorEventData","BindingBundler","BindingCallableBuiltinPlugin","BindingChunkingContext","BindingDecodedMap","BindingDevEngine","BindingLoadPluginContext","BindingMagicString","BindingModuleInfo","BindingNormalizedOptions","BindingOutputAsset","BindingOutputChunk","BindingPluginContext","BindingRenderedChunk","BindingRenderedChunkMeta","BindingRenderedModule","BindingSourceMap","BindingTransformPluginContext","BindingWatcher","BindingWatcherBundler","BindingWatcherChangeData","BindingWatcherEvent","ParallelJsPluginRegistry","TraceSubscriberGuard","TsconfigCache","BindingAttachDebugInfo","BindingBuiltinPluginName","BindingChunkModuleOrderBy","BindingErrorStage","BindingLogLevel","BindingPluginOrder","BindingPropertyReadSideEffects","BindingPropertyWriteSideEffects","BindingRebuildStrategy","collapseSourcemaps","enhancedTransform","enhancedTransformSync","FilterTokenKind","initTraceSubscriber","registerPlugins","resolveTsconfig","shutdownAsyncRuntime","startAsyncRuntime"],"managedRootEntries":["browser.js","binding.cjs","rolldown-binding.wasm","rolldown-binding.debug.wasm"]}
/* eslint-disable */
/* prettier-ignore */
/* auto-generated by NAPI-RS */
const __nodeFs = require('node:fs')
const __nodePath = require('node:path')
const { WASI: __nodeWASI } = require('node:wasi')
const { Worker } = require('node:worker_threads')
const {
emnapiAsyncWorkPlugin: __emnapiAsyncWorkPlugin,
emnapiTSFNPlugin: __emnapiTSFNPlugin,
createOnMessage: __wasmCreateOnMessageForFsProxy,
instantiateNapiModuleSync: __emnapiInstantiateNapiModuleSync,
} = require('@napi-rs/wasm-runtime')
const { createContext: __emnapiCreateContext } = require('@emnapi/runtime')
function __getWasiWorkerExecArgv() {
const __workerExecArgv = []
for (let __index = 0; __index < process.execArgv.length; __index += 1) {
const __arg = process.execArgv[__index]
if (
__arg === '--input-type' ||
__arg === '--eval' ||
__arg === '-e' ||
__arg === '--print' ||
__arg === '-p'
) {
__index += 1
continue
}
if (
__arg.startsWith('--input-type=') ||
__arg.startsWith('--eval=') ||
__arg.startsWith('--print=')
) {
continue
}
__workerExecArgv.push(__arg)
}
return __workerExecArgv
}
function __isInvalidWasiWorkerExecArgv(errorMessage, argument) {
const __equalsIndex = argument.indexOf('=')
const __argumentName =
__equalsIndex === -1 ? argument : argument.slice(0, __equalsIndex)
return (
errorMessage.includes(': ' + __argumentName + ',') ||
errorMessage.includes(': ' + __argumentName + '=') ||
errorMessage.endsWith(': ' + __argumentName) ||
errorMessage.includes(', ' + __argumentName + ',') ||
errorMessage.includes(', ' + __argumentName + '=') ||
errorMessage.endsWith(', ' + __argumentName)
)
}
function __removeInvalidWasiWorkerExecArgv(execArgv, error) {
if (typeof error.message !== 'string') {
return
}
const __workerExecArgv = []
let __removed = false
for (let __index = 0; __index < execArgv.length; __index += 1) {
const __arg = execArgv[__index]
if (
__arg.startsWith('-') &&
__isInvalidWasiWorkerExecArgv(error.message, __arg)
) {
__removed = true
if (
!__arg.includes('=') &&
__index + 1 < execArgv.length &&
!execArgv[__index + 1].startsWith('-')
) {
__index += 1
}
continue
}
__workerExecArgv.push(__arg)
}
return __removed ? __workerExecArgv : undefined
}
function __createWasiWorker(filename) {
let __workerExecArgv = __getWasiWorkerExecArgv()
while (true) {
try {
return new Worker(filename, {
env: process.env,
execArgv: __workerExecArgv,
})
} catch (error) {
if (!error || error.code !== 'ERR_WORKER_INVALID_EXEC_ARGV') {
throw error
}
const __nextWorkerExecArgv =
__removeInvalidWasiWorkerExecArgv(__workerExecArgv, error)
if (!__nextWorkerExecArgv) {
throw error
}
__workerExecArgv = __nextWorkerExecArgv
}
}
}
const __rootDir = __nodePath.parse(process.cwd()).root
const __wasi = new __nodeWASI({
version: 'preview1',
env: process.env,
preopens: {
[__rootDir]: __rootDir,
}
})
const __sharedMemory = new WebAssembly.Memory({
initial: 16384,
maximum: 65536,
shared: true,
})
let __wasmFilePath = __nodePath.join(__dirname, 'rolldown-binding.wasm32-wasi.wasm')
const __wasmDebugFilePath = __nodePath.join(__dirname, 'rolldown-binding.wasm32-wasi.debug.wasm')
if (__nodeFs.existsSync(__wasmDebugFilePath)) {
__wasmFilePath = __wasmDebugFilePath
} else if (!__nodeFs.existsSync(__wasmFilePath)) {
const __wasiPackageEntry = require.resolve('@rolldown/binding-wasm32-wasi')
const __packagedWasmFilePath = __nodePath.join(
__nodePath.dirname(__wasiPackageEntry),
'rolldown-binding.wasm32-wasi.wasm',
)
if (!__nodeFs.existsSync(__packagedWasmFilePath)) {
throw new Error(
'@rolldown/binding-wasm32-wasi is installed but is missing rolldown-binding.wasm32-wasi.wasm.',
)
}
__wasmFilePath = __packagedWasmFilePath
}
const __wasmFile = __nodeFs.readFileSync(__wasmFilePath)
let __emnapiContext
const __wasiDisposeSymbol = Symbol.for('napi.rs.wasi.dispose')
const __wasiWorkers = new Set()
let __napiInstance
let __emnapiContextDestroyed = false
let __emnapiContextDestroyPromise
let __emnapiWasmEnvCleanupPrepared = false
let __wasiDisposed = false
let __wasiDisposePromise
let __completeWasiDisposal = function() {}
function __isThenable(value) {
return (
value !== null &&
(typeof value === 'object' || typeof value === 'function') &&
typeof value.then === 'function'
)
}
function __createCleanupError(errors, message) {
if (errors.length === 1) {
return errors[0]
}
const __AggregateError = globalThis.AggregateError
if (typeof __AggregateError === 'function') {
return new __AggregateError(errors, message)
}
const error = new Error(message)
error.errors = errors
return error
}
function __attachCleanupErrors(error, cleanupErrors) {
if (cleanupErrors.length === 0) {
return error
}
const cleanupError = __createCleanupError(
cleanupErrors,
'WASI binding cleanup failed',
)
try {
if (
error &&
(typeof error === 'object' || typeof error === 'function')
) {
if (error.cause === undefined) {
error.cause = cleanupError
if (error.cause === cleanupError) {
return error
}
}
if (Array.isArray(error.cleanupErrors)) {
error.cleanupErrors.push(cleanupError)
return error
} else {
const attachedCleanupErrors = [cleanupError]
error.cleanupErrors = attachedCleanupErrors
if (error.cleanupErrors === attachedCleanupErrors) {
return error
}
}
}
} catch {}
const aggregate = __createCleanupError(
[error, cleanupError],
'WASI binding initialization and cleanup failed',
)
try {
aggregate.cause = error
} catch {}
return aggregate
}
function __prepareWasmEnvCleanup() {
if (__emnapiWasmEnvCleanupPrepared) {
return
}
const prepare = __napiInstance?.exports?.napi_prepare_wasm_env_cleanup
if (typeof prepare === 'function') {
prepare()
}
__emnapiWasmEnvCleanupPrepared = true
}
function __destroyEmnapiContext() {
if (__emnapiContextDestroyed || __emnapiContext === undefined) {
__emnapiContextDestroyed = true
return
}
if (__emnapiContextDestroyPromise) {
return __emnapiContextDestroyPromise
}
__prepareWasmEnvCleanup()
const result = __emnapiContext.destroy()
if (!__isThenable(result)) {
__emnapiContextDestroyed = true
return
}
const destroyPromise = Promise.resolve(result).then(
(value) => {
__emnapiContextDestroyed = true
return value
},
(error) => {
__emnapiContextDestroyPromise = undefined
throw error
},
)
__emnapiContextDestroyPromise = destroyPromise
return destroyPromise
}
function __terminateWasiWorkers() {
const cleanupErrors = []
const pending = []
for (const worker of __wasiWorkers) {
let result
try {
result = worker.terminate()
} catch (error) {
cleanupErrors.push(error)
continue
}
if (__isThenable(result)) {
pending.push(
Promise.resolve(result).then(
() => {
__wasiWorkers.delete(worker)
},
(error) => {
cleanupErrors.push(error)
},
),
)
} else {
__wasiWorkers.delete(worker)
}
}
const finish = () => {
if (cleanupErrors.length > 0) {
throw __createCleanupError(
cleanupErrors,
'Failed to terminate WASI workers',
)
}
}
return pending.length > 0 ? Promise.all(pending).then(finish) : finish()
}
function __finishWasiDisposal() {
const workerResult = __terminateWasiWorkers()
if (__isThenable(workerResult)) {
return Promise.resolve(workerResult).then(__completeWasiDisposal)
}
return __completeWasiDisposal()
}
function __startWasiDisposal() {
const destroyResult = __destroyEmnapiContext()
if (__isThenable(destroyResult)) {
return Promise.resolve(destroyResult).then(__finishWasiDisposal)
}
return __finishWasiDisposal()
}
/**
* Disposes this generated WASI binding.
*
* Access this function with:
* binding[Symbol.for('napi.rs.wasi.dispose')]()
*/
function __disposeWasiBinding() {
if (__wasiDisposePromise) {
return __wasiDisposePromise
}
if (__wasiDisposed) {
return Promise.resolve()
}
let resolveDispose
let rejectDispose
const disposePromise = new Promise((resolve, reject) => {
resolveDispose = resolve
rejectDispose = reject
})
__wasiDisposePromise = disposePromise
let result
try {
result = __startWasiDisposal()
} catch (error) {
__wasiDisposePromise = undefined
rejectDispose(error)
return disposePromise
}
Promise.resolve(result).then(
(value) => {
__wasiDisposed = true
resolveDispose(value)
},
(error) => {
__wasiDisposePromise = undefined
rejectDispose(error)
},
)
return disposePromise
}
function __publishWasiDispose(exports) {
Object.defineProperty(exports, __wasiDisposeSymbol, {
configurable: false,
enumerable: false,
value: __disposeWasiBinding,
writable: false,
})
}
function __finishWasiInitializationRollback(cleanupErrors) {
let workerResult
try {
workerResult = __terminateWasiWorkers()
} catch (cleanupError) {
cleanupErrors.push(cleanupError)
return cleanupErrors
}
if (__isThenable(workerResult)) {
return Promise.resolve(workerResult)
.catch((cleanupError) => {
cleanupErrors.push(cleanupError)
})
.then(() => cleanupErrors)
}
return cleanupErrors
}
function __rollbackWasiInitialization() {
const cleanupErrors = []
let destroyResult
try {
destroyResult = __destroyEmnapiContext()
} catch (cleanupError) {
cleanupErrors.push(cleanupError)
return __finishWasiInitializationRollback(cleanupErrors)
}
if (__isThenable(destroyResult)) {
return Promise.resolve(destroyResult)
.catch((cleanupError) => {
cleanupErrors.push(cleanupError)
})
.then(() => __finishWasiInitializationRollback(cleanupErrors))
}
return __finishWasiInitializationRollback(cleanupErrors)
}
const __wasiRollbackRegistrySymbol = Symbol.for('napi.rs.wasi.rollback.registry.v1')
const __wasiRollbackRegistryKey =
typeof __filename === 'string' ? __filename : __wasmFilePath
function __getWasiRollbackRegistry() {
const existing = process[__wasiRollbackRegistrySymbol]
if (existing !== undefined) {
if (!(existing instanceof Map)) {
throw new TypeError(
'The process-wide NAPI-RS WASI rollback registry is invalid',
)
}
return existing
}
const registry = new Map()
Object.defineProperty(process, __wasiRollbackRegistrySymbol, {
configurable: false,
enumerable: false,
value: registry,
writable: false,
})
return registry
}
const __wasiRollbackRegistry = __getWasiRollbackRegistry()
function __completeWasiInitializationRollback(record, cleanupErrors) {
try {
if (cleanupErrors.length === 0) {
if (
__wasiRollbackRegistry.get(__wasiRollbackRegistryKey) === record
) {
__wasiRollbackRegistry.delete(__wasiRollbackRegistryKey)
}
return
}
record.error = __attachCleanupErrors(record.error, cleanupErrors)
} catch (cleanupError) {
try {
record.error = __createCleanupError(
[record.error, cleanupError],
'WASI binding initialization and cleanup failed',
)
} catch {}
} finally {
record.active = false
record.promise = undefined
}
}
function __runWasiInitializationRollback(record) {
if (record.active) {
return
}
record.active = true
let rollbackResult
try {
rollbackResult = record.rollback()
} catch (cleanupError) {
__completeWasiInitializationRollback(record, [cleanupError])
return
}
if (!__isThenable(rollbackResult)) {
__completeWasiInitializationRollback(record, rollbackResult)
return
}
record.promise = Promise.resolve(rollbackResult).then(
(cleanupErrors) => {
__completeWasiInitializationRollback(record, cleanupErrors)
},
(cleanupError) => {
__completeWasiInitializationRollback(record, [cleanupError])
},
)
}
const __pendingWasiRollback = __wasiRollbackRegistry.get(
__wasiRollbackRegistryKey,
)
if (__pendingWasiRollback !== undefined) {
__runWasiInitializationRollback(__pendingWasiRollback)
throw __pendingWasiRollback.error
}
let __wasiModule
let __napiModule
let __wasiExitListenerRegistered = false
function __removeWasiExitListener() {
if (
__wasiExitListenerRegistered &&
typeof process.removeListener === 'function'
) {
process.removeListener('exit', __disposeWasiBindingAtExit)
}
__wasiExitListenerRegistered = false
}
function __disposeWasiBindingAtExit() {
__wasiExitListenerRegistered = false
try {
const result = __disposeWasiBinding()
if (__isThenable(result)) {
void Promise.resolve(result).catch(() => {})
}
} catch {}
}
function __registerWasiExitListener() {
if (
!__wasiExitListenerRegistered &&
typeof process.once === 'function'
) {
process.once('exit', __disposeWasiBindingAtExit)
__wasiExitListenerRegistered = true
}
}
__completeWasiDisposal = __removeWasiExitListener
function __captureEmnapiAutoDestroyListener() {
if (
typeof process.prependListener !== 'function' ||
typeof process.removeListener !== 'function'
) {
return
}
let __autoDestroyListener
const __captureListener = (__event, __listener) => {
if (__event === 'beforeExit' && __autoDestroyListener === undefined) {
__autoDestroyListener = __listener
}
}
try {
// Run before existing newListener hooks so a hook that registers its own
// beforeExit listener cannot be mistaken for emnapi's registration.
process.prependListener('newListener', __captureListener)
} catch {
return
}
return () => {
try {
process.removeListener('newListener', __captureListener)
} catch {}
if (__autoDestroyListener !== undefined) {
try {
process.removeListener('beforeExit', __autoDestroyListener)
} catch {}
}
}
}
try {
const __finishAutoDestroyCapture = __captureEmnapiAutoDestroyListener()
try {
__emnapiContext = __emnapiCreateContext({ autoDestroy: false })
// emnapi 2.x still registers an unconditional once-listener for
// beforeExit that auto-destroys the context, and suppressDestroy() only
// neutralizes its callback without removing it. This loader owns cleanup
// through its 'exit' listener, so emnapi's listener is captured and
// removed; suppressDestroy() remains the safety net when removal fails.
__emnapiContext.suppressDestroy()
} finally {
// Remove only the exact emnapi callback captured above.
__finishAutoDestroyCapture?.()
}
;({
instance: __napiInstance,
module: __wasiModule,
napiModule: __napiModule,
} = __emnapiInstantiateNapiModuleSync(__wasmFile, {
context: __emnapiContext,
asyncWorkPoolSize: (function() {
const threadsSizeFromEnv = Number(process.env.NAPI_RS_ASYNC_WORK_POOL_SIZE ?? process.env.UV_THREADPOOL_SIZE)
// NaN > 0 is false
if (threadsSizeFromEnv > 0) {
return threadsSizeFromEnv
} else {
return 4
}
})(),
reuseWorker: true,
plugins: [__emnapiAsyncWorkPlugin, __emnapiTSFNPlugin],
wasi: __wasi,
onCreateWorker() {
const worker = __createWasiWorker(__nodePath.join(__dirname, 'wasi-worker.mjs'))
__wasiWorkers.add(worker)
worker.onmessage = ({ data }) => {
__wasmCreateOnMessageForFsProxy(__nodeFs)(data)
}
// The main thread of Node.js waits for all the active handles before exiting.
// But Rust threads are never waited without `thread::join`.
// So here we hack the code of Node.js to prevent the workers from being referenced (active).
// According to https://github.com/nodejs/node/blob/19e0d472728c79d418b74bddff588bea70a403d0/lib/internal/worker.js#L415,
// a worker is consist of two handles: kPublicPort and kHandle.
{
const kPublicPort = Object.getOwnPropertySymbols(worker).find(s =>
s.toString().includes("kPublicPort")
);
if (kPublicPort) {
worker[kPublicPort].ref = () => {};
}
const kHandle = Object.getOwnPropertySymbols(worker).find(s =>
s.toString().includes("kHandle")
);
if (kHandle) {
worker[kHandle].ref = () => {};
}
worker.unref();
}
return worker
},
overwriteImports(importObject) {
importObject.env = {
...importObject.env,
...importObject.napi,
...importObject.emnapi,
memory: __sharedMemory,
}
return importObject
},
beforeInit({ instance }) {
__napiInstance = instance
for (const name of Object.keys(instance.exports)) {
if (name.startsWith('__napi_register__')) {
instance.exports[name]()
}
}
},
}))
__publishWasiDispose(__napiModule.exports)
__registerWasiExitListener()
} catch (error) {
const rollback = {
active: false,
error,
promise: undefined,
rollback: __rollbackWasiInitialization,
}
__wasiRollbackRegistry.set(__wasiRollbackRegistryKey, rollback)
__runWasiInitializationRollback(rollback)
throw rollback.error
}
module.exports = __napiModule.exports
module.exports.LegalCommentsMode = __napiModule.exports.LegalCommentsMode
module.exports.minify = __napiModule.exports.minify
module.exports.minifySync = __napiModule.exports.minifySync
module.exports.Severity = __napiModule.exports.Severity
module.exports.ParseResult = __napiModule.exports.ParseResult
module.exports.ExportExportNameKind = __napiModule.exports.ExportExportNameKind
module.exports.ExportImportNameKind = __napiModule.exports.ExportImportNameKind
module.exports.ExportLocalNameKind = __napiModule.exports.ExportLocalNameKind
module.exports.ImportNameKind = __napiModule.exports.ImportNameKind
module.exports.parse = __napiModule.exports.parse
module.exports.parseSync = __napiModule.exports.parseSync
module.exports.rawTransferSupported = __napiModule.exports.rawTransferSupported
module.exports.ResolverFactory = __napiModule.exports.ResolverFactory
module.exports.EnforceExtension = __napiModule.exports.EnforceExtension
module.exports.ModuleType = __napiModule.exports.ModuleType
module.exports.sync = __napiModule.exports.sync
module.exports.HelperMode = __napiModule.exports.HelperMode
module.exports.isolatedDeclaration = __napiModule.exports.isolatedDeclaration
module.exports.isolatedDeclarationSync = __napiModule.exports.isolatedDeclarationSync
module.exports.moduleRunnerTransform = __napiModule.exports.moduleRunnerTransform
module.exports.moduleRunnerTransformSync = __napiModule.exports.moduleRunnerTransformSync
module.exports.transform = __napiModule.exports.transform
module.exports.transformSync = __napiModule.exports.transformSync
module.exports.BindingBundleEndEventData = __napiModule.exports.BindingBundleEndEventData
module.exports.BindingBundleErrorEventData = __napiModule.exports.BindingBundleErrorEventData
module.exports.BindingBundler = __napiModule.exports.BindingBundler
module.exports.BindingCallableBuiltinPlugin = __napiModule.exports.BindingCallableBuiltinPlugin
module.exports.BindingChunkingContext = __napiModule.exports.BindingChunkingContext
module.exports.BindingDecodedMap = __napiModule.exports.BindingDecodedMap
module.exports.BindingDevEngine = __napiModule.exports.BindingDevEngine
module.exports.BindingLoadPluginContext = __napiModule.exports.BindingLoadPluginContext
module.exports.BindingMagicString = __napiModule.exports.BindingMagicString
module.exports.BindingModuleInfo = __napiModule.exports.BindingModuleInfo
module.exports.BindingNormalizedOptions = __napiModule.exports.BindingNormalizedOptions
module.exports.BindingOutputAsset = __napiModule.exports.BindingOutputAsset
module.exports.BindingOutputChunk = __napiModule.exports.BindingOutputChunk
module.exports.BindingPluginContext = __napiModule.exports.BindingPluginContext
module.exports.BindingRenderedChunk = __napiModule.exports.BindingRenderedChunk
module.exports.BindingRenderedChunkMeta = __napiModule.exports.BindingRenderedChunkMeta
module.exports.BindingRenderedModule = __napiModule.exports.BindingRenderedModule
module.exports.BindingSourceMap = __napiModule.exports.BindingSourceMap
module.exports.BindingTransformPluginContext = __napiModule.exports.BindingTransformPluginContext
module.exports.BindingWatcher = __napiModule.exports.BindingWatcher
module.exports.BindingWatcherBundler = __napiModule.exports.BindingWatcherBundler
module.exports.BindingWatcherChangeData = __napiModule.exports.BindingWatcherChangeData
module.exports.BindingWatcherEvent = __napiModule.exports.BindingWatcherEvent
module.exports.ParallelJsPluginRegistry = __napiModule.exports.ParallelJsPluginRegistry
module.exports.TraceSubscriberGuard = __napiModule.exports.TraceSubscriberGuard
module.exports.TsconfigCache = __napiModule.exports.TsconfigCache
module.exports.BindingAttachDebugInfo = __napiModule.exports.BindingAttachDebugInfo
module.exports.BindingBuiltinPluginName = __napiModule.exports.BindingBuiltinPluginName
module.exports.BindingChunkModuleOrderBy = __napiModule.exports.BindingChunkModuleOrderBy
module.exports.BindingErrorStage = __napiModule.exports.BindingErrorStage
module.exports.BindingLogLevel = __napiModule.exports.BindingLogLevel
module.exports.BindingPluginOrder = __napiModule.exports.BindingPluginOrder
module.exports.BindingPropertyReadSideEffects = __napiModule.exports.BindingPropertyReadSideEffects
module.exports.BindingPropertyWriteSideEffects = __napiModule.exports.BindingPropertyWriteSideEffects
module.exports.BindingRebuildStrategy = __napiModule.exports.BindingRebuildStrategy
module.exports.collapseSourcemaps = __napiModule.exports.collapseSourcemaps
module.exports.enhancedTransform = __napiModule.exports.enhancedTransform
module.exports.enhancedTransformSync = __napiModule.exports.enhancedTransformSync
module.exports.FilterTokenKind = __napiModule.exports.FilterTokenKind
module.exports.initTraceSubscriber = __napiModule.exports.initTraceSubscriber
module.exports.registerPlugins = __napiModule.exports.registerPlugins
module.exports.resolveTsconfig = __napiModule.exports.resolveTsconfig
module.exports.shutdownAsyncRuntime = __napiModule.exports.shutdownAsyncRuntime
module.exports.startAsyncRuntime = __napiModule.exports.startAsyncRuntime

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,59 @@
import {
instantiateNapiModuleSync,
MessageHandler,
WASI,
createFsProxy,
emnapiAsyncWorkPlugin,
emnapiTSFNPlugin,
} from '@napi-rs/wasm-runtime'
import { memfsExported as __memfsExported } from '@napi-rs/wasm-runtime/fs'
const fs = createFsProxy(__memfsExported)
const errorOutputs = []
const handler = new MessageHandler({
onLoad({ wasmModule, wasmMemory }) {
const wasi = new WASI({
fs,
preopens: {
'/': '/',
},
print: function () {
// eslint-disable-next-line no-console
console.log.apply(console, arguments)
},
printErr: function() {
// eslint-disable-next-line no-console
console.error.apply(console, arguments)
errorOutputs.push([...arguments])
},
})
return instantiateNapiModuleSync(wasmModule, {
childThread: true,
wasi,
// The wasm links a "basic" emnapi archive (no C async-work /
// threadsafe-function implementations), so every thread that
// instantiates it must provide the JavaScript implementations
// through the emnapi plugins.
plugins: [emnapiAsyncWorkPlugin, emnapiTSFNPlugin],
overwriteImports(importObject) {
importObject.env = {
...importObject.env,
...importObject.napi,
...importObject.emnapi,
memory: wasmMemory,
}
},
})
},
onError(error) {
postMessage({ type: 'error', error, errorOutputs })
errorOutputs.length = 0
}
})
globalThis.onmessage = function (e) {
handler.handle(e)
}

View File

@@ -0,0 +1,74 @@
import fs from "node:fs";
import { createRequire } from "node:module";
import { parse } from "node:path";
import { WASI } from "node:wasi";
import { parentPort, Worker } from "node:worker_threads";
const require = createRequire(import.meta.url);
const {
instantiateNapiModuleSync,
MessageHandler,
getDefaultContext,
emnapiAsyncWorkPlugin,
emnapiTSFNPlugin,
} = require("@napi-rs/wasm-runtime");
if (parentPort) {
parentPort.on("message", (data) => {
globalThis.onmessage({ data });
});
}
Object.assign(globalThis, {
self: globalThis,
require,
Worker,
importScripts: function (f) {
;(0, eval)(fs.readFileSync(f, "utf8") + "//# sourceURL=" + f);
},
postMessage: function (msg) {
if (parentPort) {
parentPort.postMessage(msg);
}
},
});
const emnapiContext = getDefaultContext();
const __rootDir = parse(process.cwd()).root;
const handler = new MessageHandler({
onLoad({ wasmModule, wasmMemory }) {
const wasi = new WASI({
version: 'preview1',
env: process.env,
preopens: {
[__rootDir]: __rootDir,
},
});
return instantiateNapiModuleSync(wasmModule, {
childThread: true,
wasi,
context: emnapiContext,
// The wasm links a "basic" emnapi archive (no C async-work /
// threadsafe-function implementations), so every thread that
// instantiates it must provide the JavaScript implementations
// through the emnapi plugins.
plugins: [emnapiAsyncWorkPlugin, emnapiTSFNPlugin],
overwriteImports(importObject) {
importObject.env = {
...importObject.env,
...importObject.napi,
...importObject.emnapi,
memory: wasmMemory
};
},
});
},
});
globalThis.onmessage = function (e) {
handler.handle(e);
};

21
client/node_modules/@rolldown/pluginutils/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026-present, rolldown/plugins repository contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

145
client/node_modules/@rolldown/pluginutils/README.md generated vendored Normal file
View File

@@ -0,0 +1,145 @@
# @rolldown/pluginutils [![npm](https://img.shields.io/npm/v/@rolldown/pluginutils.svg)](https://npmx.dev/package/@rolldown/pluginutils)
Plugin utilities for [Rolldown](https://rolldown.rs).
Includes regex helpers for plugin hook filters, composable filter expressions, and a helper for filtering out Vite-serve-only plugins.
## Install
```bash
pnpm add -D @rolldown/pluginutils
```
## Usage
```ts
import { exactRegex, prefixRegex, makeIdFiltersToMatchWithQuery } from '@rolldown/pluginutils'
```
All filter helpers are also exposed via the `/filter` subpath:
```ts
import { and, or, id, include } from '@rolldown/pluginutils/filter'
```
## Regex helpers
### `exactRegex`
- **Type:** `(str: string, flags?: string) => RegExp`
Constructs a `RegExp` that matches the exact string specified. Useful as a plugin hook filter.
```ts
import { exactRegex } from '@rolldown/pluginutils'
const plugin = {
name: 'plugin',
resolveId: {
filter: { id: exactRegex('foo') },
handler(id) {}, // only called for `foo`
},
}
```
### `prefixRegex`
- **Type:** `(str: string, flags?: string) => RegExp`
Constructs a `RegExp` that matches values starting with the specified prefix.
```ts
import { prefixRegex } from '@rolldown/pluginutils'
const plugin = {
name: 'plugin',
resolveId: {
filter: { id: prefixRegex('foo') },
handler(id) {}, // called for IDs starting with `foo`
},
}
```
### `makeIdFiltersToMatchWithQuery`
- **Type:** `(input: string | RegExp | (string | RegExp)[]) => string | RegExp | (string | RegExp)[]`
Converts an id filter so that it also matches ids that include a query string.
```ts
import { makeIdFiltersToMatchWithQuery } from '@rolldown/pluginutils'
const plugin = {
name: 'plugin',
transform: {
filter: { id: makeIdFiltersToMatchWithQuery(['**/*.js', /\.ts$/]) },
// Matches:
// foo.js, foo.js?foo, foo.txt?foo.js,
// foo.ts, foo.ts?foo, foo.txt?foo.ts
handler(code, id) {},
},
}
```
## Composable filters
[Composable filter expressions](https://rolldown.rs/apis/plugin-api/hook-filters#composable-filters) for use cases where a simple `id`/`include`/`exclude` is not enough. For example, when a plugin needs to combine `id`, `moduleType`, `code`, and `query` conditions.
```ts
import { and, code, id, include, interpreter, moduleType, or } from '@rolldown/pluginutils'
const expr = include(and(or(id(/\.tsx?$/), id(/\.jsx?$/)), moduleType('tsx'), code(/import React/)))
interpreter(expr, sourceCode, sourceId, 'tsx') // boolean
```
### Builders
| Builder | Description |
| ------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `and(...exprs)` | All operands must match. |
| `or(...exprs)` | At least one operand must match. |
| `not(expr)` | Negates the operand. |
| `id(pattern, params?)` | Match the module id. `pattern` is `string` or `RegExp`. `params.cleanUrl` strips the query/hash before matching. |
| `importerId(pattern, params?)` | Match the importer's id. Same shape as `id`. |
| `moduleType(type)` | Match Rolldown's module type (`'js'`, `'jsx'`, `'ts'`, `'tsx'`, `'json'`, `'text'`, `'base64'`, `'dataurl'`, `'binary'`, `'empty'`, or a custom string). |
| `code(pattern)` | Match the module source. `string` matches with `includes`; `RegExp` with `test`. |
| `query(key, pattern)` | Match a single query parameter. `pattern` is `boolean` (key presence/truthiness), `string` (exact value), or `RegExp` (value pattern). |
| `queries(obj)` | Shorthand for `and(...)` over multiple `query` entries. |
| `include(expr)` | Top-level wrapper marking `expr` as an inclusion rule. |
| `exclude(expr)` | Top-level wrapper marking `expr` as an exclusion rule. |
### `interpreter`
- **Type:** `(exprs, code?, id?, moduleType?, importerId?) => boolean`
Evaluates one or more top-level expressions against the given inputs. Returns `true` when at least one `include` matches and no `exclude` matches; when no `include` is present, defaults to `true` unless an `exclude` matches.
The argument required by each expression must be provided. For example, evaluating an `id(...)` expression without passing `id` will throw.
## `filterVitePlugins`
- **Type:** `<T>(plugins: T | T[] | null | undefined | false) => T[]`
Removes Vite plugins that target the dev server (`apply: 'serve'`) from a (possibly nested) plugin array. Plugins whose `apply` is a function are invoked with a `command: 'build'` context to decide. Useful when reusing a Vite plugin array inside a Rolldown config.
```ts
import { defineConfig } from 'rolldown'
import { filterVitePlugins } from '@rolldown/pluginutils'
import viteReact from '@vitejs/plugin-react'
export default defineConfig({
plugins: filterVitePlugins([
viteReact(),
{
name: 'dev-only',
apply: 'serve', // filtered out
// ...
},
]),
})
```
## License
MIT

View File

@@ -0,0 +1,323 @@
//#region src/utils.ts
const postfixRE = /[?#].*$/;
function cleanUrl(url) {
return url.replace(postfixRE, "");
}
function extractQueryWithoutFragment(url) {
const questionMarkIndex = url.indexOf("?");
if (questionMarkIndex === -1) return "";
const fragmentIndex = url.indexOf("#", questionMarkIndex);
if (fragmentIndex === -1) return url.substring(questionMarkIndex);
else return url.substring(questionMarkIndex, fragmentIndex);
}
//#endregion
//#region src/filter/composable-filters.ts
var And = class {
kind;
args;
constructor(...args) {
if (args.length === 0) throw new Error("`And` expects at least one operand");
this.args = args;
this.kind = "and";
}
};
var Or = class {
kind;
args;
constructor(...args) {
if (args.length === 0) throw new Error("`Or` expects at least one operand");
this.args = args;
this.kind = "or";
}
};
var Not = class {
kind;
expr;
constructor(expr) {
this.expr = expr;
this.kind = "not";
}
};
var Id = class {
kind;
pattern;
params;
constructor(pattern, params) {
this.pattern = pattern;
this.kind = "id";
this.params = params ?? { cleanUrl: false };
}
};
var ImporterId = class {
kind;
pattern;
params;
constructor(pattern, params) {
this.pattern = pattern;
this.kind = "importerId";
this.params = params ?? { cleanUrl: false };
}
};
var ModuleType = class {
kind;
pattern;
constructor(pattern) {
this.pattern = pattern;
this.kind = "moduleType";
}
};
var Code = class {
kind;
pattern;
constructor(expr) {
this.pattern = expr;
this.kind = "code";
}
};
var Query = class {
kind;
key;
pattern;
constructor(key, pattern) {
this.pattern = pattern;
this.key = key;
this.kind = "query";
}
};
var Include = class {
kind;
expr;
constructor(expr) {
this.expr = expr;
this.kind = "include";
}
};
var Exclude = class {
kind;
expr;
constructor(expr) {
this.expr = expr;
this.kind = "exclude";
}
};
function and(...args) {
return new And(...args);
}
function or(...args) {
return new Or(...args);
}
function not(expr) {
return new Not(expr);
}
function id(pattern, params) {
return new Id(pattern, params);
}
function importerId(pattern, params) {
return new ImporterId(pattern, params);
}
function moduleType(pattern) {
return new ModuleType(pattern);
}
function code(pattern) {
return new Code(pattern);
}
function query(key, pattern) {
return new Query(key, pattern);
}
function include(expr) {
return new Include(expr);
}
function exclude(expr) {
return new Exclude(expr);
}
/**
* convert a queryObject to FilterExpression like
* ```js
* and(query(k1, v1), query(k2, v2))
* ```
* @param queryFilterObject The query filter object needs to be matched.
* @returns a `And` FilterExpression
*/
function queries(queryFilter) {
return and(...Object.entries(queryFilter).map(([key, value]) => {
return new Query(key, value);
}));
}
function interpreter(exprs, code, id, moduleType, importerId) {
let arr = [];
if (Array.isArray(exprs)) arr = exprs;
else arr = [exprs];
return interpreterImpl(arr, code, id, moduleType, importerId);
}
function interpreterImpl(expr, code, id, moduleType, importerId, ctx = {}) {
let hasInclude = false;
for (const e of expr) switch (e.kind) {
case "include":
hasInclude = true;
if (exprInterpreter(e.expr, code, id, moduleType, importerId, ctx)) return true;
break;
case "exclude":
if (exprInterpreter(e.expr, code, id, moduleType, importerId, ctx)) return false;
break;
}
return !hasInclude;
}
function exprInterpreter(expr, code, id, moduleType, importerId, ctx = {}) {
switch (expr.kind) {
case "and": return expr.args.every((e) => exprInterpreter(e, code, id, moduleType, importerId, ctx));
case "or": return expr.args.some((e) => exprInterpreter(e, code, id, moduleType, importerId, ctx));
case "not": return !exprInterpreter(expr.expr, code, id, moduleType, importerId, ctx);
case "id": {
if (id === void 0) throw new Error("`id` is required for `id` expression");
let idToMatch = id;
if (expr.params.cleanUrl) idToMatch = cleanUrl(idToMatch);
return typeof expr.pattern === "string" ? idToMatch === expr.pattern : expr.pattern.test(idToMatch);
}
case "importerId": {
if (importerId === void 0) return false;
let importerIdToMatch = importerId;
if (expr.params.cleanUrl) importerIdToMatch = cleanUrl(importerIdToMatch);
return typeof expr.pattern === "string" ? importerIdToMatch === expr.pattern : expr.pattern.test(importerIdToMatch);
}
case "moduleType":
if (moduleType === void 0) throw new Error("`moduleType` is required for `moduleType` expression");
return moduleType === expr.pattern;
case "code":
if (code === void 0) throw new Error("`code` is required for `code` expression");
return typeof expr.pattern === "string" ? code.includes(expr.pattern) : expr.pattern.test(code);
case "query": {
if (id === void 0) throw new Error("`id` is required for `Query` expression");
if (!ctx.urlSearchParamsCache) {
let queryString = extractQueryWithoutFragment(id);
ctx.urlSearchParamsCache = new URLSearchParams(queryString);
}
let urlParams = ctx.urlSearchParamsCache;
if (typeof expr.pattern === "boolean") if (expr.pattern) return urlParams.has(expr.key);
else return !urlParams.has(expr.key);
else if (typeof expr.pattern === "string") return urlParams.get(expr.key) === expr.pattern;
else return expr.pattern.test(urlParams.get(expr.key) ?? "");
}
default: throw new Error(`Expression ${JSON.stringify(expr)} is not expected.`);
}
}
//#endregion
//#region src/filter/filter-vite-plugins.ts
/**
* Filters out Vite plugins that have `apply: 'serve'` set.
*
* Since Rolldown operates in build mode, plugins marked with `apply: 'serve'`
* are intended only for Vite's dev server and should be excluded from the build process.
*
* @param plugins - Array of plugins (can include nested arrays)
* @returns Filtered array with serve-only plugins removed
*
* @example
* ```ts
* import { defineConfig } from 'rolldown';
* import { filterVitePlugins } from '@rolldown/pluginutils';
* import viteReact from '@vitejs/plugin-react';
*
* export default defineConfig({
* plugins: filterVitePlugins([
* viteReact(),
* {
* name: 'dev-only',
* apply: 'serve', // This will be filtered out
* // ...
* }
* ])
* });
* ```
*/
function filterVitePlugins(plugins) {
if (!plugins) return [];
const pluginArray = Array.isArray(plugins) ? plugins : [plugins];
const result = [];
for (const plugin of pluginArray) {
if (!plugin) continue;
if (Array.isArray(plugin)) {
result.push(...filterVitePlugins(plugin));
continue;
}
const pluginWithApply = plugin;
if ("apply" in pluginWithApply) {
const applyValue = pluginWithApply.apply;
if (typeof applyValue === "function") try {
if (applyValue({}, {
command: "build",
mode: "production"
})) result.push(plugin);
} catch {
result.push(plugin);
}
else if (applyValue === "serve") continue;
else result.push(plugin);
} else result.push(plugin);
}
return result;
}
//#endregion
//#region src/filter/simple-filters.ts
/**
* Constructs a RegExp that matches the exact string specified.
*
* This is useful for plugin hook filters.
*
* @param str the string to match.
* @param flags flags for the RegExp.
*
* @example
* ```ts
* import { exactRegex } from '@rolldown/pluginutils';
* const plugin = {
* name: 'plugin',
* resolveId: {
* filter: { id: exactRegex('foo') },
* handler(id) {} // will only be called for `foo`
* }
* }
* ```
*/
function exactRegex(str, flags) {
return new RegExp(`^${escapeRegex(str)}$`, flags);
}
/**
* Constructs a RegExp that matches a value that has the specified prefix.
*
* This is useful for plugin hook filters.
*
* @param str the string to match.
* @param flags flags for the RegExp.
*
* @example
* ```ts
* import { prefixRegex } from '@rolldown/pluginutils';
* const plugin = {
* name: 'plugin',
* resolveId: {
* filter: { id: prefixRegex('foo') },
* handler(id) {} // will only be called for IDs starting with `foo`
* }
* }
* ```
*/
function prefixRegex(str, flags) {
return new RegExp(`^${escapeRegex(str)}`, flags);
}
const escapeRegexRE = /[-/\\^$*+?.()|[\]{}]/g;
function escapeRegex(str) {
return str.replace(escapeRegexRE, "\\$&");
}
function makeIdFiltersToMatchWithQuery(input) {
if (!Array.isArray(input)) return makeIdFilterToMatchWithQuery(input);
return input.map((i) => makeIdFilterToMatchWithQuery(i));
}
function makeIdFilterToMatchWithQuery(input) {
if (typeof input === "string") return `${input}{?*,}`;
return makeRegexIdFilterToMatchWithQuery(input);
}
function makeRegexIdFilterToMatchWithQuery(input) {
return new RegExp(input.source.replace(/(?<!\\)\$/g, "(?:\\?.*)?$"), input.flags);
}
//#endregion
export { queries as _, and as a, exprInterpreter as c, include as d, interpreter as f, or as g, not as h, filterVitePlugins as i, id as l, moduleType as m, makeIdFiltersToMatchWithQuery as n, code as o, interpreterImpl as p, prefixRegex as r, exclude as s, exactRegex as t, importerId as u, query as v };

View File

@@ -0,0 +1,194 @@
//#region src/filter/composable-filters.d.ts
type StringOrRegExp = string | RegExp;
type PluginModuleType = 'js' | 'jsx' | 'ts' | 'tsx' | 'json' | 'text' | 'base64' | 'dataurl' | 'binary' | 'empty' | (string & {});
type FilterExpressionKind = FilterExpression['kind'];
type FilterExpression = And | Or | Not | Id | ImporterId | ModuleType | Code | Query;
type TopLevelFilterExpression = Include | Exclude;
declare class And {
kind: 'and';
args: FilterExpression[];
constructor(...args: FilterExpression[]);
}
declare class Or {
kind: 'or';
args: FilterExpression[];
constructor(...args: FilterExpression[]);
}
declare class Not {
kind: 'not';
expr: FilterExpression;
constructor(expr: FilterExpression);
}
interface QueryFilterObject {
[key: string]: StringOrRegExp | boolean;
}
interface IdParams {
cleanUrl?: boolean;
}
declare class Id {
kind: 'id';
pattern: StringOrRegExp;
params: IdParams;
constructor(pattern: StringOrRegExp, params?: IdParams);
}
declare class ImporterId {
kind: 'importerId';
pattern: StringOrRegExp;
params: IdParams;
constructor(pattern: StringOrRegExp, params?: IdParams);
}
declare class ModuleType {
kind: 'moduleType';
pattern: PluginModuleType;
constructor(pattern: PluginModuleType);
}
declare class Code {
kind: 'code';
pattern: StringOrRegExp;
constructor(expr: StringOrRegExp);
}
declare class Query {
kind: 'query';
key: string;
pattern: StringOrRegExp | boolean;
constructor(key: string, pattern: StringOrRegExp | boolean);
}
declare class Include {
kind: 'include';
expr: FilterExpression;
constructor(expr: FilterExpression);
}
declare class Exclude {
kind: 'exclude';
expr: FilterExpression;
constructor(expr: FilterExpression);
}
declare function and(...args: FilterExpression[]): And;
declare function or(...args: FilterExpression[]): Or;
declare function not(expr: FilterExpression): Not;
declare function id(pattern: StringOrRegExp, params?: IdParams): Id;
declare function importerId(pattern: StringOrRegExp, params?: IdParams): ImporterId;
declare function moduleType(pattern: PluginModuleType): ModuleType;
declare function code(pattern: StringOrRegExp): Code;
declare function query(key: string, pattern: StringOrRegExp | boolean): Query;
declare function include(expr: FilterExpression): Include;
declare function exclude(expr: FilterExpression): Exclude;
/**
* convert a queryObject to FilterExpression like
* ```js
* and(query(k1, v1), query(k2, v2))
* ```
* @param queryFilterObject The query filter object needs to be matched.
* @returns a `And` FilterExpression
*/
declare function queries(queryFilter: QueryFilterObject): And;
declare function interpreter(exprs: TopLevelFilterExpression | TopLevelFilterExpression[], code?: string, id?: string, moduleType?: PluginModuleType, importerId?: string): boolean;
interface InterpreterCtx {
urlSearchParamsCache?: URLSearchParams;
}
declare function interpreterImpl(expr: TopLevelFilterExpression[], code?: string, id?: string, moduleType?: PluginModuleType, importerId?: string, ctx?: InterpreterCtx): boolean;
declare function exprInterpreter(expr: FilterExpression, code?: string, id?: string, moduleType?: PluginModuleType, importerId?: string, ctx?: InterpreterCtx): boolean;
//#endregion
//#region src/filter/filter-vite-plugins.d.ts
/**
* Filters out Vite plugins that have `apply: 'serve'` set.
*
* Since Rolldown operates in build mode, plugins marked with `apply: 'serve'`
* are intended only for Vite's dev server and should be excluded from the build process.
*
* @param plugins - Array of plugins (can include nested arrays)
* @returns Filtered array with serve-only plugins removed
*
* @example
* ```ts
* import { defineConfig } from 'rolldown';
* import { filterVitePlugins } from '@rolldown/pluginutils';
* import viteReact from '@vitejs/plugin-react';
*
* export default defineConfig({
* plugins: filterVitePlugins([
* viteReact(),
* {
* name: 'dev-only',
* apply: 'serve', // This will be filtered out
* // ...
* }
* ])
* });
* ```
*/
declare function filterVitePlugins<T = any>(plugins: T | T[] | null | undefined | false): T[];
//#endregion
//#region src/filter/simple-filters.d.ts
/**
* Constructs a RegExp that matches the exact string specified.
*
* This is useful for plugin hook filters.
*
* @param str the string to match.
* @param flags flags for the RegExp.
*
* @example
* ```ts
* import { exactRegex } from '@rolldown/pluginutils';
* const plugin = {
* name: 'plugin',
* resolveId: {
* filter: { id: exactRegex('foo') },
* handler(id) {} // will only be called for `foo`
* }
* }
* ```
*/
declare function exactRegex(str: string, flags?: string): RegExp;
/**
* Constructs a RegExp that matches a value that has the specified prefix.
*
* This is useful for plugin hook filters.
*
* @param str the string to match.
* @param flags flags for the RegExp.
*
* @example
* ```ts
* import { prefixRegex } from '@rolldown/pluginutils';
* const plugin = {
* name: 'plugin',
* resolveId: {
* filter: { id: prefixRegex('foo') },
* handler(id) {} // will only be called for IDs starting with `foo`
* }
* }
* ```
*/
declare function prefixRegex(str: string, flags?: string): RegExp;
type WidenString<T> = T extends string ? string : T;
/**
* Converts a id filter to match with an id with a query.
*
* @param input the id filters to convert.
*
* @example
* ```ts
* import { makeIdFiltersToMatchWithQuery } from '@rolldown/pluginutils';
* const plugin = {
* name: 'plugin',
* transform: {
* filter: { id: makeIdFiltersToMatchWithQuery(['**' + '/*.js', /\.ts$/]) },
* // The handler will be called for IDs like:
* // - foo.js
* // - foo.js?foo
* // - foo.txt?foo.js
* // - foo.ts
* // - foo.ts?foo
* // - foo.txt?foo.ts
* handler(code, id) {}
* }
* }
* ```
*/
declare function makeIdFiltersToMatchWithQuery<T extends string | RegExp>(input: T): WidenString<T>;
declare function makeIdFiltersToMatchWithQuery<T extends string | RegExp>(input: readonly T[]): WidenString<T>[];
declare function makeIdFiltersToMatchWithQuery(input: string | RegExp | readonly (string | RegExp)[]): string | RegExp | (string | RegExp)[];
//#endregion
export { FilterExpression, FilterExpressionKind, QueryFilterObject, TopLevelFilterExpression, and, code, exactRegex, exclude, exprInterpreter, filterVitePlugins, id, importerId, include, interpreter, interpreterImpl, makeIdFiltersToMatchWithQuery, moduleType, not, or, prefixRegex, queries, query };

View File

@@ -0,0 +1,2 @@
import { _ as queries, a as and, c as exprInterpreter, d as include, f as interpreter, g as or, h as not, i as filterVitePlugins, l as id, m as moduleType, n as makeIdFiltersToMatchWithQuery, o as code, p as interpreterImpl, r as prefixRegex, s as exclude, t as exactRegex, u as importerId, v as query } from "../filter-B_mD-HGz.mjs";
export { and, code, exactRegex, exclude, exprInterpreter, filterVitePlugins, id, importerId, include, interpreter, interpreterImpl, makeIdFiltersToMatchWithQuery, moduleType, not, or, prefixRegex, queries, query };

View File

@@ -0,0 +1,2 @@
import { FilterExpression, FilterExpressionKind, QueryFilterObject, TopLevelFilterExpression, and, code, exactRegex, exclude, exprInterpreter, filterVitePlugins, id, importerId, include, interpreter, interpreterImpl, makeIdFiltersToMatchWithQuery, moduleType, not, or, prefixRegex, queries, query } from "./filter/index.mjs";
export { FilterExpression, FilterExpressionKind, QueryFilterObject, TopLevelFilterExpression, and, code, exactRegex, exclude, exprInterpreter, filterVitePlugins, id, importerId, include, interpreter, interpreterImpl, makeIdFiltersToMatchWithQuery, moduleType, not, or, prefixRegex, queries, query };

View File

@@ -0,0 +1,2 @@
import { _ as queries, a as and, c as exprInterpreter, d as include, f as interpreter, g as or, h as not, i as filterVitePlugins, l as id, m as moduleType, n as makeIdFiltersToMatchWithQuery, o as code, p as interpreterImpl, r as prefixRegex, s as exclude, t as exactRegex, u as importerId, v as query } from "./filter-B_mD-HGz.mjs";
export { and, code, exactRegex, exclude, exprInterpreter, filterVitePlugins, id, importerId, include, interpreter, interpreterImpl, makeIdFiltersToMatchWithQuery, moduleType, not, or, prefixRegex, queries, query };

40
client/node_modules/@rolldown/pluginutils/package.json generated vendored Normal file
View File

@@ -0,0 +1,40 @@
{
"name": "@rolldown/pluginutils",
"version": "1.0.1",
"description": "Plugin utilities for Rolldown",
"keywords": [
"filter",
"plugin",
"rolldown"
],
"homepage": "https://github.com/rolldown/plugins/tree/main/packages/pluginutils#readme",
"bugs": {
"url": "https://github.com/rolldown/plugins/issues"
},
"license": "MIT",
"repository": {
"type": "git",
"url": "git+https://github.com/rolldown/plugins.git",
"directory": "packages/pluginutils"
},
"files": [
"dist"
],
"type": "module",
"exports": {
".": "./dist/index.mjs",
"./filter": "./dist/filter/index.mjs",
"./package.json": "./package.json"
},
"devDependencies": {
"@types/picomatch": "^4.0.3",
"picomatch": "^4.0.4",
"typescript": "^5.9.3"
},
"scripts": {
"dev": "tsdown --watch",
"build": "tsdown",
"test": "vitest --project pluginutils",
"test:types": "vitest --project pluginutils --typecheck.only"
}
}

193
client/node_modules/@tybys/wasm-util/README.md generated vendored Normal file
View File

@@ -0,0 +1,193 @@
# @tybys/wasm-util
WebAssembly related utils for browser environment
**The output code is ES2019**
## Features
All example code below need to be bundled by ES module bundlers like `webpack` / `rollup`, or specify import map in browser native ES module runtime.
### WASI polyfill for browser
The API is similar to the `require('wasi').WASI` in Node.js.
You can use `memfs-browser` to provide filesystem capability.
- Example: [https://github.com/toyobayashi/wasi-wabt](https://github.com/toyobayashi/wasi-wabt)
- Demo: [https://toyobayashi.github.io/wasi-wabt/](https://toyobayashi.github.io/wasi-wabt/)
```js
import { load, WASI } from '@tybys/wasm-util'
import { Volume, createFsFromVolume } from 'memfs-browser'
const fs = createFsFromVolume(Volume.fromJSON({
'/home/wasi': null
}))
const wasi = new WASI({
args: ['chrome', 'file.wasm'],
env: {
NODE_ENV: 'development',
WASI_SDK_PATH: '/opt/wasi-sdk'
},
preopens: {
'/': '/'
},
fs,
// redirect stdout / stderr
// print (text) { console.log(text) },
// printErr (text) { console.error(text) }
})
const imports = {
wasi_snapshot_preview1: wasi.wasiImport
}
const { module, instance } = await load('/path/to/file.wasm', imports)
wasi.start(instance)
// wasi.initialize(instance)
```
Implemented syscalls: [wasi_snapshot_preview1](#wasi_snapshot_preview1)
### `load` / `loadSync`
`loadSync` has 4KB wasm size limit in browser.
```js
// bundler
import { load, loadSync } from '@tybys/wasm-util'
const imports = { /* ... */ }
// using path
const { module, instance } = await load('/path/to/file.wasm', imports)
const { module, instance } = loadSync('/path/to/file.wasm', imports)
// using URL
const { module, instance } = await load(new URL('./file.wasm', import.meta.url), imports)
const { module, instance } = loadSync(new URL('./file.wasm', import.meta.url), imports)
// using Uint8Array
const buffer = new Uint8Array([
0x00, 0x61, 0x73, 0x6d,
0x01, 0x00, 0x00, 0x00
])
const { module, instance } = await load(buffer, imports)
const { module, instance } = loadSync(buffer, imports)
// auto asyncify
const {
module,
instance: asyncifiedInstance
} = await load(buffer, imports, { /* asyncify options */})
asyncifiedInstance.exports.fn() // => return Promise
```
### Extend Memory instance
```js
import { Memory, extendMemory } from '@tybys/wasm-util'
const memory = new WebAssembly.Memory({ initial: 256 })
// const memory = instance.exports.memory
extendMemory(memory)
console.log(memory instanceof Memory)
console.log(memory instanceof WebAssembly.Memory)
// expose memory view getters like Emscripten
const { HEAPU8, HEAPU32, view } = memory
```
### Asyncify wrap
Build the C code using `clang`, `wasm-ld` and `wasm-opt`
```c
void async_sleep(int ms);
int main() {
async_sleep(200);
return 0;
}
```
```js
import { Asyncify } from '@tybys/wasm-util'
const asyncify = new Asyncify()
const imports = {
env: {
async_sleep: asyncify.wrapImportFunction(function (ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms)
})
})
}
}
// async_sleep(200)
const bytes = await (await fetch('/asyncfied_by_wasm-opt.wasm')).arrayBuffer()
const { instance } = await WebAssembly.instantiate(bytes, imports)
const asyncifiedInstance = asyncify.init(instance.exports.memory, instance, {
wrapExports: ['_start']
})
const p = asyncifedInstance._start()
console.log(typeof p.then === 'function')
const now = Date.now()
await p
console.log(Date.now() - now >= 200)
```
### wasi_snapshot_preview1
- [x] args_get
- [x] args_sizes_get
- [x] environ_get
- [x] environ_sizes_get
- [x] clock_res_get
- [x] clock_time_get
- [ ] ~~fd_advise~~
- [x] fd_allocate
- [x] fd_close
- [x] fd_datasync
- [x] fd_fdstat_get
- [ ] ~~fd_fdstat_set_flags~~
- [x] fd_fdstat_set_rights
- [x] fd_filestat_get
- [x] fd_filestat_set_size
- [x] fd_filestat_set_times
- [x] fd_pread
- [x] fd_prestat_get
- [x] fd_prestat_dir_name
- [x] fd_pwrite
- [x] fd_read
- [x] fd_readdir
- [x] fd_renumber
- [x] fd_seek
- [x] fd_sync
- [x] fd_tell
- [x] fd_write
- [x] path_create_directory
- [x] path_filestat_get
- [x] path_filestat_set_times
- [x] path_link
- [x] path_open
- [x] path_readlink
- [x] path_remove_directory
- [x] path_rename
- [x] path_symlink
- [x] path_unlink_file
- [x] poll_oneoff (timer only)
- [x] proc_exit
- [ ] ~~proc_raise~~
- [x] sched_yield
- [x] random_get
- [ ] ~~sock_recv~~
- [ ] ~~sock_send~~
- [ ] ~~sock_shutdown~~

View File

@@ -0,0 +1,11 @@
// This file is read by tools that parse documentation comments conforming to the TSDoc standard.
// It should be published with your NPM package. It should not be tracked by Git.
{
"tsdocVersion": "0.12",
"toolPackages": [
{
"packageName": "@microsoft/api-extractor",
"packageVersion": "7.34.4"
}
]
}

View File

@@ -0,0 +1,423 @@
/**
* @packageDocumentation
*/
/** @public */
export declare class Asyncify {
private value;
private exports;
private dataPtr;
init<T extends WebAssembly.Exports, U extends Array<Exclude<keyof T, AsyncifyExportName>>>(memory: WebAssembly.Memory, instance: {
readonly exports: T;
}, options: AsyncifyOptions): {
readonly exports: AsyncifyExports<T, U>;
};
private assertState;
wrapImportFunction<T extends Function>(f: T): T;
wrapImports<T extends WebAssembly.Imports>(imports: T): T;
wrapExportFunction<T extends Function>(f: T): AsyncifyExportFunction<T>;
wrapExports<T extends WebAssembly.Exports>(exports: T): AsyncifyExports<T, void>;
wrapExports<T extends WebAssembly.Exports, U extends Array<Exclude<keyof T, AsyncifyExportName>>>(exports: T, needWrap: U): AsyncifyExports<T, U>;
}
/** @public */
export declare type AsyncifyExportFunction<T> = T extends Callable ? (...args: Parameters<T>) => Promise<ReturnType<T>> : T;
/** @public */
export declare type AsyncifyExportName = 'asyncify_get_state' | 'asyncify_start_unwind' | 'asyncify_stop_unwind' | 'asyncify_start_rewind' | 'asyncify_stop_rewind';
/** @public */
export declare type AsyncifyExports<T, U> = T extends Record<string, any> ? {
[P in keyof T]: T[P] extends Callable ? U extends Array<Exclude<keyof T, AsyncifyExportName>> ? P extends U[number] ? AsyncifyExportFunction<T[P]> : T[P] : AsyncifyExportFunction<T[P]> : T[P];
} : T;
/** @public */
export declare function asyncifyLoad(asyncify: AsyncifyOptions, urlOrBuffer: string | URL | BufferSource | WebAssembly.Module, imports?: WebAssembly.Imports): Promise<WebAssembly.WebAssemblyInstantiatedSource>;
/** @public */
export declare function asyncifyLoadSync(asyncify: AsyncifyOptions, buffer: BufferSource | WebAssembly.Module, imports?: WebAssembly.Imports): WebAssembly.WebAssemblyInstantiatedSource;
/** @public */
export declare interface AsyncifyOptions {
wasm64?: boolean;
tryAllocate?: boolean | {
size?: number;
name?: string;
};
wrapExports?: string[];
}
/** @public */
export declare interface AsyncWASIOptions extends WASIOptions {
fs: {
promises: IFsPromises;
};
asyncify?: Asyncify;
}
/** @public */
export declare interface BaseEncodingOptions {
encoding?: BufferEncoding_2;
}
/** @public */
export declare interface BigIntStats extends StatsBase<bigint> {
}
/** @public */
declare type BufferEncoding_2 = 'ascii' | 'utf8' | 'utf-8' | 'utf16le' | 'ucs2' | 'ucs-2' | 'base64' | 'base64url' | 'latin1' | 'binary' | 'hex';
export { BufferEncoding_2 as BufferEncoding }
/** @public */
export declare type BufferEncodingOption = 'buffer' | {
encoding: 'buffer';
};
/** @public */
export declare type Callable = (...args: any[]) => any;
/** @public */
export declare function createAsyncWASI(options?: AsyncWASIOptions): Promise<WASI>;
/** @public */
export declare function extendMemory(memory: WebAssembly.Memory): Memory;
/** @public */
export declare interface FileHandle {
readonly fd: number;
datasync(): Promise<void>;
sync(): Promise<void>;
read<TBuffer extends Uint8Array>(buffer: TBuffer, offset?: number, length?: number, position?: number): Promise<{
bytesRead: number;
buffer: TBuffer;
}>;
stat(opts?: StatOptions & {
bigint?: false;
}): Promise<Stats>;
stat(opts: StatOptions & {
bigint: true;
}): Promise<BigIntStats>;
stat(opts?: StatOptions): Promise<Stats | BigIntStats>;
truncate(len?: number): Promise<void>;
utimes(atime: string | number | Date, mtime: string | number | Date): Promise<void>;
write<TBuffer extends Uint8Array>(buffer: TBuffer, offset?: number, length?: number, position?: number): Promise<{
bytesWritten: number;
buffer: TBuffer;
}>;
write(data: string | Uint8Array, position?: number, encoding?: BufferEncoding_2): Promise<{
bytesWritten: number;
buffer: string;
}>;
close(): Promise<void>;
}
/** @public */
export declare interface FinalizeBindingsOptions {
memory?: WebAssembly.Memory;
}
/** @public */
export declare interface IDirent {
isFile(): boolean;
isDirectory(): boolean;
isBlockDevice(): boolean;
isCharacterDevice(): boolean;
isSymbolicLink(): boolean;
isFIFO(): boolean;
isSocket(): boolean;
name: string;
}
/** @public */
export declare interface IFs {
fstatSync(fd: number, options?: StatOptions & {
bigint?: false;
}): Stats;
fstatSync(fd: number, options: StatOptions & {
bigint: true;
}): BigIntStats;
fstatSync(fd: number, options?: StatOptions): Stats | BigIntStats;
statSync(path: PathLike, options?: StatOptions & {
bigint?: false;
}): Stats;
statSync(path: PathLike, options: StatOptions & {
bigint: true;
}): BigIntStats;
statSync(path: PathLike, options?: StatOptions): Stats | BigIntStats;
lstatSync(path: PathLike, options?: StatOptions & {
bigint?: false;
}): Stats;
lstatSync(path: PathLike, options: StatOptions & {
bigint: true;
}): BigIntStats;
lstatSync(path: PathLike, options?: StatOptions): Stats | BigIntStats;
utimesSync(path: PathLike, atime: string | number | Date, mtime: string | number | Date): void;
openSync(path: PathLike, flags: OpenMode, mode?: Mode): number;
readSync(fd: number, buffer: ArrayBufferView, offset: number, length: number, position: number | null): number;
readSync(fd: number, buffer: ArrayBufferView, opts?: ReadSyncOptions): number;
writeSync(fd: number, buffer: ArrayBufferView, offset?: number, length?: number, position?: number): number;
writeSync(fd: number, string: string, position?: number, encoding?: BufferEncoding_2): number;
closeSync(fd: number): void;
readlinkSync(path: PathLike, options?: BaseEncodingOptions | BufferEncoding_2): string;
readlinkSync(path: PathLike, options: BufferEncodingOption): Uint8Array;
readlinkSync(path: PathLike, options?: BaseEncodingOptions | string): string | Uint8Array;
realpathSync(path: PathLike, options?: BaseEncodingOptions | BufferEncoding_2): string;
realpathSync(path: PathLike, options: BufferEncodingOption): Uint8Array;
realpathSync(path: PathLike, options?: BaseEncodingOptions | string): string | Uint8Array;
truncateSync(path: PathLike, len?: number): void;
ftruncateSync(fd: number, len?: number): void;
fdatasyncSync(fd: number): void;
futimesSync(fd: number, atime: string | number | Date, mtime: string | number | Date): void;
readdirSync(path: PathLike, options?: {
encoding: BufferEncoding_2 | null;
withFileTypes?: false;
} | BufferEncoding_2): string[];
readdirSync(path: PathLike, options: {
encoding: 'buffer';
withFileTypes?: false;
} | 'buffer'): Uint8Array[];
readdirSync(path: PathLike, options?: BaseEncodingOptions & {
withFileTypes?: false;
} | BufferEncoding_2): string[] | Uint8Array[];
readdirSync(path: PathLike, options: BaseEncodingOptions & {
withFileTypes: true;
}): IDirent[];
fsyncSync(fd: number): void;
mkdirSync(path: PathLike, options: MakeDirectoryOptions & {
recursive: true;
}): string | undefined;
mkdirSync(path: PathLike, options?: Mode | (MakeDirectoryOptions & {
recursive?: false;
})): void;
mkdirSync(path: PathLike, options?: Mode | MakeDirectoryOptions): string | undefined;
rmdirSync(path: PathLike, options?: RmDirOptions): void;
linkSync(existingPath: PathLike, newPath: PathLike): void;
unlinkSync(path: PathLike): void;
renameSync(oldPath: PathLike, newPath: PathLike): void;
symlinkSync(target: PathLike, path: PathLike, type?: 'dir' | 'file' | 'junction'): void;
}
/** @public */
export declare interface IFsPromises {
stat(path: PathLike, options?: StatOptions & {
bigint?: false;
}): Promise<Stats>;
stat(path: PathLike, options: StatOptions & {
bigint: true;
}): Promise<BigIntStats>;
stat(path: PathLike, options?: StatOptions): Promise<Stats | BigIntStats>;
lstat(path: PathLike, options?: StatOptions & {
bigint?: false;
}): Promise<Stats>;
lstat(path: PathLike, options: StatOptions & {
bigint: true;
}): Promise<BigIntStats>;
lstat(path: PathLike, options?: StatOptions): Promise<Stats | BigIntStats>;
utimes(path: PathLike, atime: string | number | Date, mtime: string | number | Date): Promise<void>;
open(path: PathLike, flags: OpenMode, mode?: Mode): Promise<FileHandle>;
read<TBuffer extends Uint8Array>(handle: FileHandle, buffer: TBuffer, offset?: number, length?: number, position?: number): Promise<{
bytesRead: number;
buffer: TBuffer;
}>;
write<TBuffer extends Uint8Array>(handle: FileHandle, buffer: TBuffer, offset?: number, length?: number, position?: number): Promise<{
bytesWritten: number;
buffer: TBuffer;
}>;
readlink(path: PathLike, options?: BaseEncodingOptions | BufferEncoding_2): Promise<string>;
readlink(path: PathLike, options: BufferEncodingOption): Promise<Uint8Array>;
readlink(path: PathLike, options?: BaseEncodingOptions | string): Promise<string | Uint8Array>;
realpath(path: PathLike, options?: BaseEncodingOptions | BufferEncoding_2): Promise<string>;
realpath(path: PathLike, options: BufferEncodingOption): Promise<Uint8Array>;
realpath(path: PathLike, options?: BaseEncodingOptions | string): Promise<string | Uint8Array>;
truncate(path: PathLike, len?: number): Promise<void>;
ftruncate(handle: FileHandle, len?: number): Promise<void>;
fdatasync(handle: FileHandle): Promise<void>;
futimes(handle: FileHandle, atime: string | number | Date, mtime: string | number | Date): Promise<void>;
readdir(path: PathLike, options?: {
encoding: BufferEncoding_2 | null;
withFileTypes?: false;
} | BufferEncoding_2): Promise<string[]>;
readdir(path: PathLike, options: {
encoding: 'buffer';
withFileTypes?: false;
} | 'buffer'): Promise<Uint8Array[]>;
readdir(path: PathLike, options?: BaseEncodingOptions & {
withFileTypes?: false;
} | BufferEncoding_2): Promise<string[] | Uint8Array[]>;
readdir(path: PathLike, options: BaseEncodingOptions & {
withFileTypes: true;
}): Promise<IDirent[]>;
fsync(handle: FileHandle): Promise<void>;
mkdir(path: PathLike, options: MakeDirectoryOptions & {
recursive: true;
}): Promise<string | undefined>;
mkdir(path: PathLike, options?: Mode | (MakeDirectoryOptions & {
recursive?: false;
})): Promise<void>;
mkdir(path: PathLike, options?: Mode | MakeDirectoryOptions): Promise<string | undefined>;
rmdir(path: PathLike, options?: RmDirOptions): Promise<void>;
link(existingPath: PathLike, newPath: PathLike): Promise<void>;
unlink(path: PathLike): Promise<void>;
rename(oldPath: PathLike, newPath: PathLike): Promise<void>;
symlink(target: PathLike, path: PathLike, type?: 'dir' | 'file' | 'junction'): Promise<void>;
}
declare const kBindingName: unique symbol;
declare const kExitCode: unique symbol;
declare const kInstance: unique symbol;
declare const kSetMemory: unique symbol;
declare const kStarted: unique symbol;
/** @public */
export declare function load(wasmInput: string | URL | BufferSource | WebAssembly.Module, imports?: WebAssembly.Imports): Promise<WebAssembly.WebAssemblyInstantiatedSource>;
/** @public */
export declare function loadSync(wasmInput: BufferSource | WebAssembly.Module, imports?: WebAssembly.Imports): WebAssembly.WebAssemblyInstantiatedSource;
/** @public */
export declare interface MakeDirectoryOptions {
recursive?: boolean;
mode?: Mode;
}
/** @public */
export declare class Memory extends WebAssemblyMemory {
constructor(descriptor: WebAssembly.MemoryDescriptor);
get HEAP8(): Int8Array;
get HEAPU8(): Uint8Array;
get HEAP16(): Int16Array;
get HEAPU16(): Uint16Array;
get HEAP32(): Int32Array;
get HEAPU32(): Uint32Array;
get HEAP64(): BigInt64Array;
get HEAPU64(): BigUint64Array;
get HEAPF32(): Float32Array;
get HEAPF64(): Float64Array;
get view(): DataView;
}
/** @public */
export declare type Mode = number | string;
/** @public */
export declare type OpenMode = number | string;
/** @public */
export declare type PathLike = string | Uint8Array | URL;
/** @public */
export declare type PromisifyExports<T, U> = T extends Record<string, any> ? {
[P in keyof T]: T[P] extends Callable ? U extends Array<keyof T> ? P extends U[number] ? AsyncifyExportFunction<T[P]> : T[P] : AsyncifyExportFunction<T[P]> : T[P];
} : T;
/** @public */
export declare interface ReadSyncOptions {
offset?: number;
length?: number;
position?: number;
}
/** @public */
export declare interface RmDirOptions {
maxRetries?: number;
recursive?: boolean;
retryDelay?: number;
}
/** @public */
export declare interface StatOptions {
bigint?: boolean;
}
/** @public */
export declare interface Stats extends StatsBase<number> {
}
/** @public */
export declare interface StatsBase<T> {
isFile(): boolean;
isDirectory(): boolean;
isBlockDevice(): boolean;
isCharacterDevice(): boolean;
isSymbolicLink(): boolean;
isFIFO(): boolean;
isSocket(): boolean;
dev: T;
ino: T;
mode: T;
nlink: T;
uid: T;
gid: T;
rdev: T;
size: T;
blksize: T;
blocks: T;
atimeMs: T;
mtimeMs: T;
ctimeMs: T;
birthtimeMs: T;
atime: Date;
mtime: Date;
ctime: Date;
birthtime: Date;
}
/** @public */
export declare interface SyncWASIOptions extends WASIOptions {
fs?: IFs;
}
/** @public */
export declare class WASI {
private [kSetMemory];
private [kStarted];
private [kExitCode];
private [kInstance];
private [kBindingName];
readonly wasiImport: Record<string, any>;
constructor(options?: SyncWASIOptions);
finalizeBindings(instance: WebAssembly.Instance, { memory }?: FinalizeBindingsOptions): void;
start(instance: WebAssembly.Instance): number | undefined | Promise<number> | Promise<undefined>;
initialize(instance: WebAssembly.Instance): void | Promise<void>;
getImportObject(): Record<string, Record<string, any>>;
}
/** @public */
export declare interface WASIOptions {
version?: 'unstable' | 'preview1';
args?: string[] | undefined;
env?: Record<string, string> | undefined;
preopens?: Record<string, string> | undefined;
/**
* @defaultValue `false`
*/
returnOnExit?: boolean | undefined;
print?: (str: string) => void;
printErr?: (str: string) => void;
}
/** @public */
export declare const WebAssemblyMemory: {
new (descriptor: WebAssembly.MemoryDescriptor): WebAssembly.Memory;
prototype: WebAssembly.Memory;
};
/** @public */
export declare function wrapAsyncExport<T extends Function = any>(f: Function): T;
/** @public */
export declare function wrapAsyncImport<T extends (...args: any[]) => any>(f: T, parameterType: WebAssembly.ValueType[], returnType: WebAssembly.ValueType[]): (...args: [object, ...Parameters<T>]) => ReturnType<T>;
/** @public */
export declare function wrapExports<T extends WebAssembly.Exports>(exports: T): PromisifyExports<T, void>;
/** @public */
export declare function wrapExports<T extends WebAssembly.Exports, U extends Array<keyof T>>(exports: T, needWrap: U): PromisifyExports<T, U>;
export { }
export as namespace wasmUtil;

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

2954
client/node_modules/@tybys/wasm-util/dist/wasm-util.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,158 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Asyncify = void 0;
const webassembly_1 = require("./webassembly");
const util_1 = require("./wasi/util");
const ignoreNames = [
'asyncify_get_state',
'asyncify_start_rewind',
'asyncify_start_unwind',
'asyncify_stop_rewind',
'asyncify_stop_unwind'
];
// const wrappedExports = new WeakMap<WebAssembly.Exports, WebAssembly.Exports>()
var AsyncifyState;
(function (AsyncifyState) {
AsyncifyState[AsyncifyState["NONE"] = 0] = "NONE";
AsyncifyState[AsyncifyState["UNWINDING"] = 1] = "UNWINDING";
AsyncifyState[AsyncifyState["REWINDING"] = 2] = "REWINDING";
})(AsyncifyState || (AsyncifyState = {}));
function tryAllocate(instance, wasm64, size, mallocName) {
if (typeof instance.exports[mallocName] !== 'function' || size <= 0) {
return {
wasm64,
dataPtr: 16,
start: wasm64 ? 32 : 24,
end: 1024
};
}
const malloc = instance.exports[mallocName];
const dataPtr = wasm64 ? Number(malloc(BigInt(16) + BigInt(size))) : malloc(8 + size);
if (dataPtr === 0) {
throw new Error('Allocate asyncify data failed');
}
return wasm64
? { wasm64, dataPtr, start: dataPtr + 16, end: dataPtr + 16 + size }
: { wasm64, dataPtr, start: dataPtr + 8, end: dataPtr + 8 + size };
}
/** @public */
class Asyncify {
constructor() {
this.value = undefined;
this.exports = undefined;
this.dataPtr = 0;
}
init(memory, instance, options) {
var _a, _b;
if (this.exports) {
throw new Error('Asyncify has been initialized');
}
if (!(memory instanceof webassembly_1._WebAssembly.Memory)) {
throw new TypeError('Require WebAssembly.Memory object');
}
const exports = instance.exports;
for (let i = 0; i < ignoreNames.length; ++i) {
if (typeof exports[ignoreNames[i]] !== 'function') {
throw new TypeError('Invalid asyncify wasm');
}
}
let address;
const wasm64 = Boolean(options.wasm64);
if (!options.tryAllocate) {
address = {
wasm64,
dataPtr: 16,
start: wasm64 ? 32 : 24,
end: 1024
};
}
else {
if (options.tryAllocate === true) {
address = tryAllocate(instance, wasm64, 4096, 'malloc');
}
else {
address = tryAllocate(instance, wasm64, (_a = options.tryAllocate.size) !== null && _a !== void 0 ? _a : 4096, (_b = options.tryAllocate.name) !== null && _b !== void 0 ? _b : 'malloc');
}
}
this.dataPtr = address.dataPtr;
if (wasm64) {
new BigInt64Array(memory.buffer, this.dataPtr).set([BigInt(address.start), BigInt(address.end)]);
}
else {
new Int32Array(memory.buffer, this.dataPtr).set([address.start, address.end]);
}
this.exports = this.wrapExports(exports, options.wrapExports);
const asyncifiedInstance = Object.create(webassembly_1._WebAssembly.Instance.prototype);
Object.defineProperty(asyncifiedInstance, 'exports', { value: this.exports });
// Object.setPrototypeOf(instance, Instance.prototype)
return asyncifiedInstance;
}
assertState() {
if (this.exports.asyncify_get_state() !== AsyncifyState.NONE) {
throw new Error('Asyncify state error');
}
}
wrapImportFunction(f) {
// eslint-disable-next-line @typescript-eslint/no-this-alias
const _this = this;
return (function () {
// eslint-disable-next-line no-unreachable-loop
while (_this.exports.asyncify_get_state() === AsyncifyState.REWINDING) {
_this.exports.asyncify_stop_rewind();
return _this.value;
}
_this.assertState();
const v = f.apply(this, arguments);
if (!(0, util_1.isPromiseLike)(v))
return v;
_this.exports.asyncify_start_unwind(_this.dataPtr);
_this.value = v;
});
}
wrapImports(imports) {
const importObject = {};
Object.keys(imports).forEach(k => {
const mod = imports[k];
const newModule = {};
Object.keys(mod).forEach(name => {
const importValue = mod[name];
if (typeof importValue === 'function') {
newModule[name] = this.wrapImportFunction(importValue);
}
else {
newModule[name] = importValue;
}
});
importObject[k] = newModule;
});
return importObject;
}
wrapExportFunction(f) {
// eslint-disable-next-line @typescript-eslint/no-this-alias
const _this = this;
return (async function () {
_this.assertState();
let ret = f.apply(this, arguments);
while (_this.exports.asyncify_get_state() === AsyncifyState.UNWINDING) {
_this.exports.asyncify_stop_unwind();
_this.value = await _this.value;
_this.assertState();
_this.exports.asyncify_start_rewind(_this.dataPtr);
ret = f.call(this);
}
_this.assertState();
return ret;
});
}
wrapExports(exports, needWrap) {
return (0, util_1.wrapInstanceExports)(exports, (exportValue, name) => {
let ignore = ignoreNames.indexOf(name) !== -1 || typeof exportValue !== 'function';
if (Array.isArray(needWrap)) {
ignore = ignore || (needWrap.indexOf(name) === -1);
}
return ignore ? exportValue : this.wrapExportFunction(exportValue);
});
}
}
exports.Asyncify = Asyncify;
//# sourceMappingURL=asyncify.js.map

13
client/node_modules/@tybys/wasm-util/lib/cjs/index.js generated vendored Normal file
View File

@@ -0,0 +1,13 @@
"use strict";
/**
* @packageDocumentation
*/
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
tslib_1.__exportStar(require("./asyncify"), exports);
tslib_1.__exportStar(require("./load"), exports);
tslib_1.__exportStar(require("./wasi/index"), exports);
tslib_1.__exportStar(require("./memory"), exports);
tslib_1.__exportStar(require("./jspi"), exports);
tslib_1.__exportStar(require("./wasi/fs"), exports);
//# sourceMappingURL=index.js.map

46
client/node_modules/@tybys/wasm-util/lib/cjs/jspi.js generated vendored Normal file
View File

@@ -0,0 +1,46 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.wrapExports = exports.wrapAsyncExport = exports.wrapAsyncImport = void 0;
const util_1 = require("./wasi/util");
const webassembly_1 = require("./webassembly");
function checkWebAssemblyFunction() {
const WebAssemblyFunction = webassembly_1._WebAssembly.Function;
if (typeof WebAssemblyFunction !== 'function') {
throw new Error('WebAssembly.Function is not supported in this environment.' +
' If you are using V8 based browser like Chrome, try to specify' +
' --js-flags="--wasm-staging --experimental-wasm-stack-switching"');
}
return WebAssemblyFunction;
}
/** @public */
function wrapAsyncImport(f, parameterType, returnType) {
const WebAssemblyFunction = checkWebAssemblyFunction();
if (typeof f !== 'function') {
throw new TypeError('Function required');
}
const parameters = parameterType.slice(0);
parameters.unshift('externref');
return new WebAssemblyFunction({ parameters, results: returnType }, f, { suspending: 'first' });
}
exports.wrapAsyncImport = wrapAsyncImport;
/** @public */
function wrapAsyncExport(f) {
const WebAssemblyFunction = checkWebAssemblyFunction();
if (typeof f !== 'function') {
throw new TypeError('Function required');
}
return new WebAssemblyFunction({ parameters: [...WebAssemblyFunction.type(f).parameters.slice(1)], results: ['externref'] }, f, { promising: 'first' });
}
exports.wrapAsyncExport = wrapAsyncExport;
/** @public */
function wrapExports(exports, needWrap) {
return (0, util_1.wrapInstanceExports)(exports, (exportValue, name) => {
let ignore = typeof exportValue !== 'function';
if (Array.isArray(needWrap)) {
ignore = ignore || (needWrap.indexOf(name) === -1);
}
return ignore ? exportValue : wrapAsyncExport(exportValue);
});
}
exports.wrapExports = wrapExports;
//# sourceMappingURL=jspi.js.map

97
client/node_modules/@tybys/wasm-util/lib/cjs/load.js generated vendored Normal file
View File

@@ -0,0 +1,97 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.asyncifyLoadSync = exports.loadSync = exports.asyncifyLoad = exports.load = void 0;
const webassembly_1 = require("./webassembly");
const asyncify_1 = require("./asyncify");
function validateImports(imports) {
if (imports && typeof imports !== 'object') {
throw new TypeError('imports must be an object or undefined');
}
}
function fetchWasm(urlOrBuffer, imports) {
if (typeof wx !== 'undefined' && typeof __wxConfig !== 'undefined') {
return webassembly_1._WebAssembly.instantiate(urlOrBuffer, imports);
}
return fetch(urlOrBuffer)
.then(response => response.arrayBuffer())
.then(buffer => webassembly_1._WebAssembly.instantiate(buffer, imports));
}
/** @public */
function load(wasmInput, imports) {
validateImports(imports);
imports = imports !== null && imports !== void 0 ? imports : {};
let source;
if (wasmInput instanceof ArrayBuffer || ArrayBuffer.isView(wasmInput)) {
return webassembly_1._WebAssembly.instantiate(wasmInput, imports);
}
if (wasmInput instanceof webassembly_1._WebAssembly.Module) {
return webassembly_1._WebAssembly.instantiate(wasmInput, imports).then((instance) => {
return { instance, module: wasmInput };
});
}
if (typeof wasmInput !== 'string' && !(wasmInput instanceof URL)) {
throw new TypeError('Invalid source');
}
if (typeof webassembly_1._WebAssembly.instantiateStreaming === 'function') {
let responsePromise;
try {
responsePromise = fetch(wasmInput);
source = webassembly_1._WebAssembly.instantiateStreaming(responsePromise, imports).catch(() => {
return fetchWasm(wasmInput, imports);
});
}
catch (_) {
source = fetchWasm(wasmInput, imports);
}
}
else {
source = fetchWasm(wasmInput, imports);
}
return source;
}
exports.load = load;
/** @public */
function asyncifyLoad(asyncify, urlOrBuffer, imports) {
validateImports(imports);
imports = imports !== null && imports !== void 0 ? imports : {};
const asyncifyHelper = new asyncify_1.Asyncify();
imports = asyncifyHelper.wrapImports(imports);
return load(urlOrBuffer, imports).then(source => {
var _a;
const memory = source.instance.exports.memory || ((_a = imports.env) === null || _a === void 0 ? void 0 : _a.memory);
return { module: source.module, instance: asyncifyHelper.init(memory, source.instance, asyncify) };
});
}
exports.asyncifyLoad = asyncifyLoad;
/** @public */
function loadSync(wasmInput, imports) {
validateImports(imports);
imports = imports !== null && imports !== void 0 ? imports : {};
let module;
if ((wasmInput instanceof ArrayBuffer) || ArrayBuffer.isView(wasmInput)) {
module = new webassembly_1._WebAssembly.Module(wasmInput);
}
else if (wasmInput instanceof WebAssembly.Module) {
module = wasmInput;
}
else {
throw new TypeError('Invalid source');
}
const instance = new webassembly_1._WebAssembly.Instance(module, imports);
const source = { instance, module };
return source;
}
exports.loadSync = loadSync;
/** @public */
function asyncifyLoadSync(asyncify, buffer, imports) {
var _a;
validateImports(imports);
imports = imports !== null && imports !== void 0 ? imports : {};
const asyncifyHelper = new asyncify_1.Asyncify();
imports = asyncifyHelper.wrapImports(imports);
const source = loadSync(buffer, imports);
const memory = source.instance.exports.memory || ((_a = imports.env) === null || _a === void 0 ? void 0 : _a.memory);
return { module: source.module, instance: asyncifyHelper.init(memory, source.instance, asyncify) };
}
exports.asyncifyLoadSync = asyncifyLoadSync;
//# sourceMappingURL=load.js.map

35
client/node_modules/@tybys/wasm-util/lib/cjs/memory.js generated vendored Normal file
View File

@@ -0,0 +1,35 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.extendMemory = exports.Memory = exports.WebAssemblyMemory = void 0;
/* eslint-disable spaced-comment */
const webassembly_1 = require("./webassembly");
/** @public */
exports.WebAssemblyMemory = (function () { return webassembly_1._WebAssembly.Memory; })();
/** @public */
class Memory extends exports.WebAssemblyMemory {
// eslint-disable-next-line @typescript-eslint/no-useless-constructor
constructor(descriptor) {
super(descriptor);
}
get HEAP8() { return new Int8Array(super.buffer); }
get HEAPU8() { return new Uint8Array(super.buffer); }
get HEAP16() { return new Int16Array(super.buffer); }
get HEAPU16() { return new Uint16Array(super.buffer); }
get HEAP32() { return new Int32Array(super.buffer); }
get HEAPU32() { return new Uint32Array(super.buffer); }
get HEAP64() { return new BigInt64Array(super.buffer); }
get HEAPU64() { return new BigUint64Array(super.buffer); }
get HEAPF32() { return new Float32Array(super.buffer); }
get HEAPF64() { return new Float64Array(super.buffer); }
get view() { return new DataView(super.buffer); }
}
exports.Memory = Memory;
/** @public */
function extendMemory(memory) {
if (Object.getPrototypeOf(memory) === webassembly_1._WebAssembly.Memory.prototype) {
Object.setPrototypeOf(memory, Memory.prototype);
}
return memory;
}
exports.extendMemory = extendMemory;
//# sourceMappingURL=memory.js.map

View File

@@ -0,0 +1,103 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.WasiError = exports.strerror = void 0;
const types_1 = require("./types");
function strerror(errno) {
switch (errno) {
case types_1.WasiErrno.ESUCCESS: return 'Success';
case types_1.WasiErrno.E2BIG: return 'Argument list too long';
case types_1.WasiErrno.EACCES: return 'Permission denied';
case types_1.WasiErrno.EADDRINUSE: return 'Address in use';
case types_1.WasiErrno.EADDRNOTAVAIL: return 'Address not available';
case types_1.WasiErrno.EAFNOSUPPORT: return 'Address family not supported by protocol';
case types_1.WasiErrno.EAGAIN: return 'Resource temporarily unavailable';
case types_1.WasiErrno.EALREADY: return 'Operation already in progress';
case types_1.WasiErrno.EBADF: return 'Bad file descriptor';
case types_1.WasiErrno.EBADMSG: return 'Bad message';
case types_1.WasiErrno.EBUSY: return 'Resource busy';
case types_1.WasiErrno.ECANCELED: return 'Operation canceled';
case types_1.WasiErrno.ECHILD: return 'No child process';
case types_1.WasiErrno.ECONNABORTED: return 'Connection aborted';
case types_1.WasiErrno.ECONNREFUSED: return 'Connection refused';
case types_1.WasiErrno.ECONNRESET: return 'Connection reset by peer';
case types_1.WasiErrno.EDEADLK: return 'Resource deadlock would occur';
case types_1.WasiErrno.EDESTADDRREQ: return 'Destination address required';
case types_1.WasiErrno.EDOM: return 'Domain error';
case types_1.WasiErrno.EDQUOT: return 'Quota exceeded';
case types_1.WasiErrno.EEXIST: return 'File exists';
case types_1.WasiErrno.EFAULT: return 'Bad address';
case types_1.WasiErrno.EFBIG: return 'File too large';
case types_1.WasiErrno.EHOSTUNREACH: return 'Host is unreachable';
case types_1.WasiErrno.EIDRM: return 'Identifier removed';
case types_1.WasiErrno.EILSEQ: return 'Illegal byte sequence';
case types_1.WasiErrno.EINPROGRESS: return 'Operation in progress';
case types_1.WasiErrno.EINTR: return 'Interrupted system call';
case types_1.WasiErrno.EINVAL: return 'Invalid argument';
case types_1.WasiErrno.EIO: return 'I/O error';
case types_1.WasiErrno.EISCONN: return 'Socket is connected';
case types_1.WasiErrno.EISDIR: return 'Is a directory';
case types_1.WasiErrno.ELOOP: return 'Symbolic link loop';
case types_1.WasiErrno.EMFILE: return 'No file descriptors available';
case types_1.WasiErrno.EMLINK: return 'Too many links';
case types_1.WasiErrno.EMSGSIZE: return 'Message too large';
case types_1.WasiErrno.EMULTIHOP: return 'Multihop attempted';
case types_1.WasiErrno.ENAMETOOLONG: return 'Filename too long';
case types_1.WasiErrno.ENETDOWN: return 'Network is down';
case types_1.WasiErrno.ENETRESET: return 'Connection reset by network';
case types_1.WasiErrno.ENETUNREACH: return 'Network unreachable';
case types_1.WasiErrno.ENFILE: return 'Too many files open in system';
case types_1.WasiErrno.ENOBUFS: return 'No buffer space available';
case types_1.WasiErrno.ENODEV: return 'No such device';
case types_1.WasiErrno.ENOENT: return 'No such file or directory';
case types_1.WasiErrno.ENOEXEC: return 'Exec format error';
case types_1.WasiErrno.ENOLCK: return 'No locks available';
case types_1.WasiErrno.ENOLINK: return 'Link has been severed';
case types_1.WasiErrno.ENOMEM: return 'Out of memory';
case types_1.WasiErrno.ENOMSG: return 'No message of the desired type';
case types_1.WasiErrno.ENOPROTOOPT: return 'Protocol not available';
case types_1.WasiErrno.ENOSPC: return 'No space left on device';
case types_1.WasiErrno.ENOSYS: return 'Function not implemented';
case types_1.WasiErrno.ENOTCONN: return 'Socket not connected';
case types_1.WasiErrno.ENOTDIR: return 'Not a directory';
case types_1.WasiErrno.ENOTEMPTY: return 'Directory not empty';
case types_1.WasiErrno.ENOTRECOVERABLE: return 'State not recoverable';
case types_1.WasiErrno.ENOTSOCK: return 'Not a socket';
case types_1.WasiErrno.ENOTSUP: return 'Not supported';
case types_1.WasiErrno.ENOTTY: return 'Not a tty';
case types_1.WasiErrno.ENXIO: return 'No such device or address';
case types_1.WasiErrno.EOVERFLOW: return 'Value too large for data type';
case types_1.WasiErrno.EOWNERDEAD: return 'Previous owner died';
case types_1.WasiErrno.EPERM: return 'Operation not permitted';
case types_1.WasiErrno.EPIPE: return 'Broken pipe';
case types_1.WasiErrno.EPROTO: return 'Protocol error';
case types_1.WasiErrno.EPROTONOSUPPORT: return 'Protocol not supported';
case types_1.WasiErrno.EPROTOTYPE: return 'Protocol wrong type for socket';
case types_1.WasiErrno.ERANGE: return 'Result not representable';
case types_1.WasiErrno.EROFS: return 'Read-only file system';
case types_1.WasiErrno.ESPIPE: return 'Invalid seek';
case types_1.WasiErrno.ESRCH: return 'No such process';
case types_1.WasiErrno.ESTALE: return 'Stale file handle';
case types_1.WasiErrno.ETIMEDOUT: return 'Operation timed out';
case types_1.WasiErrno.ETXTBSY: return 'Text file busy';
case types_1.WasiErrno.EXDEV: return 'Cross-device link';
case types_1.WasiErrno.ENOTCAPABLE: return 'Capabilities insufficient';
default: return 'Unknown error';
}
}
exports.strerror = strerror;
class WasiError extends Error {
constructor(message, errno) {
super(message);
this.errno = errno;
}
getErrorMessage() {
return strerror(this.errno);
}
}
exports.WasiError = WasiError;
Object.defineProperty(WasiError.prototype, 'name', {
configurable: true,
writable: true,
value: 'WasiError'
});
//# sourceMappingURL=error.js.map

268
client/node_modules/@tybys/wasm-util/lib/cjs/wasi/fd.js generated vendored Normal file
View File

@@ -0,0 +1,268 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AsyncTable = exports.SyncTable = exports.FileDescriptorTable = exports.toFileStat = exports.toFileType = exports.StandardOutput = exports.FileDescriptor = exports.concatBuffer = void 0;
const types_1 = require("./types");
const rights_1 = require("./rights");
const error_1 = require("./error");
function concatBuffer(buffers, size) {
let total = 0;
if (typeof size === 'number' && size >= 0) {
total = size;
}
else {
for (let i = 0; i < buffers.length; i++) {
const buffer = buffers[i];
total += buffer.length;
}
}
let pos = 0;
const ret = new Uint8Array(total);
for (let i = 0; i < buffers.length; i++) {
const buffer = buffers[i];
ret.set(buffer, pos);
pos += buffer.length;
}
return ret;
}
exports.concatBuffer = concatBuffer;
class FileDescriptor {
constructor(id, fd, path, realPath, type, rightsBase, rightsInheriting, preopen) {
this.id = id;
this.fd = fd;
this.path = path;
this.realPath = realPath;
this.type = type;
this.rightsBase = rightsBase;
this.rightsInheriting = rightsInheriting;
this.preopen = preopen;
this.pos = BigInt(0);
this.size = BigInt(0);
}
seek(offset, whence) {
if (whence === types_1.WasiWhence.SET) {
this.pos = BigInt(offset);
}
else if (whence === types_1.WasiWhence.CUR) {
this.pos += BigInt(offset);
}
else if (whence === types_1.WasiWhence.END) {
this.pos = BigInt(this.size) - BigInt(offset);
}
else {
throw new error_1.WasiError('Unknown whence', types_1.WasiErrno.EIO);
}
return this.pos;
}
}
exports.FileDescriptor = FileDescriptor;
class StandardOutput extends FileDescriptor {
constructor(log, id, fd, path, realPath, type, rightsBase, rightsInheriting, preopen) {
super(id, fd, path, realPath, type, rightsBase, rightsInheriting, preopen);
this._log = log;
this._buf = null;
}
write(buffer) {
const originalBuffer = buffer;
if (this._buf) {
buffer = concatBuffer([this._buf, buffer]);
this._buf = null;
}
if (buffer.indexOf(10) === -1) {
this._buf = buffer;
return originalBuffer.byteLength;
}
let written = 0;
let lastBegin = 0;
let index;
while ((index = buffer.indexOf(10, written)) !== -1) {
const str = new TextDecoder().decode(buffer.subarray(lastBegin, index));
this._log(str);
written += index - lastBegin + 1;
lastBegin = index + 1;
}
if (written < buffer.length) {
this._buf = buffer.slice(written);
}
return originalBuffer.byteLength;
}
}
exports.StandardOutput = StandardOutput;
function toFileType(stat) {
if (stat.isBlockDevice())
return types_1.WasiFileType.BLOCK_DEVICE;
if (stat.isCharacterDevice())
return types_1.WasiFileType.CHARACTER_DEVICE;
if (stat.isDirectory())
return types_1.WasiFileType.DIRECTORY;
if (stat.isSocket())
return types_1.WasiFileType.SOCKET_STREAM;
if (stat.isFile())
return types_1.WasiFileType.REGULAR_FILE;
if (stat.isSymbolicLink())
return types_1.WasiFileType.SYMBOLIC_LINK;
return types_1.WasiFileType.UNKNOWN;
}
exports.toFileType = toFileType;
function toFileStat(view, buf, stat) {
view.setBigUint64(buf, stat.dev, true);
view.setBigUint64(buf + 8, stat.ino, true);
view.setBigUint64(buf + 16, BigInt(toFileType(stat)), true);
view.setBigUint64(buf + 24, stat.nlink, true);
view.setBigUint64(buf + 32, stat.size, true);
view.setBigUint64(buf + 40, stat.atimeMs * BigInt(1000000), true);
view.setBigUint64(buf + 48, stat.mtimeMs * BigInt(1000000), true);
view.setBigUint64(buf + 56, stat.ctimeMs * BigInt(1000000), true);
}
exports.toFileStat = toFileStat;
class FileDescriptorTable {
constructor(options) {
this.used = 0;
this.size = options.size;
this.fds = Array(options.size);
this.stdio = [options.in, options.out, options.err];
this.print = options.print;
this.printErr = options.printErr;
this.insertStdio(options.in, 0, '<stdin>');
this.insertStdio(options.out, 1, '<stdout>');
this.insertStdio(options.err, 2, '<stderr>');
}
insertStdio(fd, expected, name) {
const type = types_1.WasiFileType.CHARACTER_DEVICE;
const { base, inheriting } = (0, rights_1.getRights)(this.stdio, fd, types_1.FileControlFlag.O_RDWR, type);
const wrap = this.insert(fd, name, name, type, base, inheriting, 0);
if (wrap.id !== expected) {
throw new error_1.WasiError(`id: ${wrap.id} !== expected: ${expected}`, types_1.WasiErrno.EBADF);
}
return wrap;
}
insert(fd, mappedPath, realPath, type, rightsBase, rightsInheriting, preopen) {
var _a, _b;
let index = -1;
if (this.used >= this.size) {
const newSize = this.size * 2;
this.fds.length = newSize;
index = this.size;
this.size = newSize;
}
else {
for (let i = 0; i < this.size; ++i) {
if (this.fds[i] == null) {
index = i;
break;
}
}
}
let entry;
if (mappedPath === '<stdout>') {
entry = new StandardOutput((_a = this.print) !== null && _a !== void 0 ? _a : console.log, index, fd, mappedPath, realPath, type, rightsBase, rightsInheriting, preopen);
}
else if (mappedPath === '<stderr>') {
entry = new StandardOutput((_b = this.printErr) !== null && _b !== void 0 ? _b : console.error, index, fd, mappedPath, realPath, type, rightsBase, rightsInheriting, preopen);
}
else {
entry = new FileDescriptor(index, fd, mappedPath, realPath, type, rightsBase, rightsInheriting, preopen);
}
this.fds[index] = entry;
this.used++;
return entry;
}
get(id, base, inheriting) {
if (id >= this.size) {
throw new error_1.WasiError('Invalid fd', types_1.WasiErrno.EBADF);
}
const entry = this.fds[id];
if (!entry || entry.id !== id) {
throw new error_1.WasiError('Bad file descriptor', types_1.WasiErrno.EBADF);
}
/* Validate that the fd has the necessary rights. */
if ((~entry.rightsBase & base) !== BigInt(0) || (~entry.rightsInheriting & inheriting) !== BigInt(0)) {
throw new error_1.WasiError('Capabilities insufficient', types_1.WasiErrno.ENOTCAPABLE);
}
return entry;
}
remove(id) {
if (id >= this.size) {
throw new error_1.WasiError('Invalid fd', types_1.WasiErrno.EBADF);
}
const entry = this.fds[id];
if (!entry || entry.id !== id) {
throw new error_1.WasiError('Bad file descriptor', types_1.WasiErrno.EBADF);
}
this.fds[id] = undefined;
this.used--;
}
}
exports.FileDescriptorTable = FileDescriptorTable;
class SyncTable extends FileDescriptorTable {
constructor(options) {
super(options);
this.fs = options.fs;
}
getFileTypeByFd(fd) {
const stats = this.fs.fstatSync(fd, { bigint: true });
return toFileType(stats);
}
insertPreopen(fd, mappedPath, realPath) {
const type = this.getFileTypeByFd(fd);
if (type !== types_1.WasiFileType.DIRECTORY) {
throw new error_1.WasiError(`Preopen not dir: ["${mappedPath}", "${realPath}"]`, types_1.WasiErrno.ENOTDIR);
}
const result = (0, rights_1.getRights)(this.stdio, fd, 0, type);
return this.insert(fd, mappedPath, realPath, type, result.base, result.inheriting, 1);
}
renumber(dst, src) {
if (dst === src)
return;
if (dst >= this.size || src >= this.size) {
throw new error_1.WasiError('Invalid fd', types_1.WasiErrno.EBADF);
}
const dstEntry = this.fds[dst];
const srcEntry = this.fds[src];
if (!dstEntry || !srcEntry || dstEntry.id !== dst || srcEntry.id !== src) {
throw new error_1.WasiError('Invalid fd', types_1.WasiErrno.EBADF);
}
this.fs.closeSync(dstEntry.fd);
this.fds[dst] = this.fds[src];
this.fds[dst].id = dst;
this.fds[src] = undefined;
this.used--;
}
}
exports.SyncTable = SyncTable;
class AsyncTable extends FileDescriptorTable {
// eslint-disable-next-line @typescript-eslint/no-useless-constructor
constructor(options) {
super(options);
}
async getFileTypeByFd(fd) {
const stats = await fd.stat({ bigint: true });
return toFileType(stats);
}
async insertPreopen(fd, mappedPath, realPath) {
const type = await this.getFileTypeByFd(fd);
if (type !== types_1.WasiFileType.DIRECTORY) {
throw new error_1.WasiError(`Preopen not dir: ["${mappedPath}", "${realPath}"]`, types_1.WasiErrno.ENOTDIR);
}
const result = (0, rights_1.getRights)(this.stdio, fd.fd, 0, type);
return this.insert(fd, mappedPath, realPath, type, result.base, result.inheriting, 1);
}
async renumber(dst, src) {
if (dst === src)
return;
if (dst >= this.size || src >= this.size) {
throw new error_1.WasiError('Invalid fd', types_1.WasiErrno.EBADF);
}
const dstEntry = this.fds[dst];
const srcEntry = this.fds[src];
if (!dstEntry || !srcEntry || dstEntry.id !== dst || srcEntry.id !== src) {
throw new error_1.WasiError('Invalid fd', types_1.WasiErrno.EBADF);
}
await dstEntry.fd.close();
this.fds[dst] = this.fds[src];
this.fds[dst].id = dst;
this.fds[src] = undefined;
this.used--;
}
}
exports.AsyncTable = AsyncTable;
//# sourceMappingURL=fd.js.map

View File

@@ -0,0 +1,3 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=fs.js.map

View File

@@ -0,0 +1,192 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createAsyncWASI = exports.WASI = void 0;
const preview1_1 = require("./preview1");
const util_1 = require("./util");
// eslint-disable-next-line spaced-comment
const kEmptyObject = /*#__PURE__*/ Object.freeze(/*#__PURE__*/ Object.create(null));
const kExitCode = Symbol('kExitCode');
const kSetMemory = Symbol('kSetMemory');
const kStarted = Symbol('kStarted');
const kInstance = Symbol('kInstance');
const kBindingName = Symbol('kBindingName');
function validateOptions(options) {
var _a;
(0, util_1.validateObject)(options, 'options');
let _WASI;
if (options.version !== undefined) {
(0, util_1.validateString)(options.version, 'options.version');
switch (options.version) {
case 'unstable':
_WASI = preview1_1.WASI;
this[kBindingName] = 'wasi_unstable';
break;
case 'preview1':
_WASI = preview1_1.WASI;
this[kBindingName] = 'wasi_snapshot_preview1';
break;
default:
throw new TypeError(`unsupported WASI version "${options.version}"`);
}
}
else {
_WASI = preview1_1.WASI;
this[kBindingName] = 'wasi_snapshot_preview1';
}
if (options.args !== undefined) {
(0, util_1.validateArray)(options.args, 'options.args');
}
const args = ((_a = options.args) !== null && _a !== void 0 ? _a : []).map(String);
const env = [];
if (options.env !== undefined) {
(0, util_1.validateObject)(options.env, 'options.env');
Object.entries(options.env).forEach(({ 0: key, 1: value }) => {
if (value !== undefined) {
env.push(`${key}=${value}`);
}
});
}
const preopens = [];
if (options.preopens !== undefined) {
(0, util_1.validateObject)(options.preopens, 'options.preopens');
Object.entries(options.preopens).forEach(({ 0: key, 1: value }) => preopens.push({ mappedPath: String(key), realPath: String(value) }));
}
if (preopens.length > 0) {
if (options.fs === undefined) {
throw new Error('filesystem is disabled, can not preopen directory');
}
try {
(0, util_1.validateObject)(options.fs, 'options.fs');
}
catch (_) {
throw new TypeError('Node.js fs like implementation is not provided');
}
}
// if (options.filesystem !== undefined) {
// validateObject(options.filesystem, 'options.filesystem')
// validateString(options.filesystem.type, 'options.filesystem.type')
// if (options.filesystem.type !== 'memfs' && options.filesystem.type !== 'file-system-access-api') {
// throw new Error(`Filesystem type ${(options.filesystem as any).type as string} is not supported, only "memfs" and "file-system-access-api" is supported currently`)
// }
// try {
// validateObject(options.filesystem.fs, 'options.filesystem.fs')
// } catch (_) {
// throw new Error('Node.js fs like implementation is not provided')
// }
// }
if (options.print !== undefined)
(0, util_1.validateFunction)(options.print, 'options.print');
if (options.printErr !== undefined)
(0, util_1.validateFunction)(options.printErr, 'options.printErr');
if (options.returnOnExit !== undefined) {
(0, util_1.validateBoolean)(options.returnOnExit, 'options.returnOnExit');
}
// const { stdin = 0, stdout = 1, stderr = 2 } = options
// validateInt32(stdin, 'options.stdin', 0)
// validateInt32(stdout, 'options.stdout', 0)
// validateInt32(stderr, 'options.stderr', 0)
// const stdio = [stdin, stdout, stderr] as const
const stdio = [0, 1, 2];
return {
args,
env,
preopens,
stdio,
_WASI
};
}
function initWASI(setMemory, wrap) {
this[kSetMemory] = setMemory;
this.wasiImport = wrap;
this[kStarted] = false;
this[kExitCode] = 0;
this[kInstance] = undefined;
}
/** @public */
class WASI {
constructor(options = kEmptyObject) {
const { args, env, preopens, stdio, _WASI } = validateOptions.call(this, options);
const wrap = _WASI.createSync(args, env, preopens, stdio, options.fs, options.print, options.printErr);
const setMemory = wrap._setMemory;
delete wrap._setMemory;
initWASI.call(this, setMemory, wrap);
if (options.returnOnExit) {
wrap.proc_exit = wasiReturnOnProcExit.bind(this);
}
}
finalizeBindings(instance, _a) {
var _b;
var { memory = (_b = instance === null || instance === void 0 ? void 0 : instance.exports) === null || _b === void 0 ? void 0 : _b.memory } = _a === void 0 ? {} : _a;
if (this[kStarted]) {
throw new Error('WASI instance has already started');
}
(0, util_1.validateObject)(instance, 'instance');
(0, util_1.validateObject)(instance.exports, 'instance.exports');
this[kSetMemory](memory);
this[kInstance] = instance;
this[kStarted] = true;
}
// Must not export _initialize, must export _start
start(instance) {
this.finalizeBindings(instance);
const { _start, _initialize } = this[kInstance].exports;
(0, util_1.validateFunction)(_start, 'instance.exports._start');
(0, util_1.validateUndefined)(_initialize, 'instance.exports._initialize');
let ret;
try {
ret = _start();
}
catch (err) {
if (err !== kExitCode) {
throw err;
}
}
if (ret instanceof Promise) {
return ret.then(() => this[kExitCode], (err) => {
if (err !== kExitCode) {
throw err;
}
return this[kExitCode];
});
}
return this[kExitCode];
}
// Must not export _start, may optionally export _initialize
initialize(instance) {
this.finalizeBindings(instance);
const { _start, _initialize } = this[kInstance].exports;
(0, util_1.validateUndefined)(_start, 'instance.exports._start');
if (_initialize !== undefined) {
(0, util_1.validateFunction)(_initialize, 'instance.exports._initialize');
return _initialize();
}
}
getImportObject() {
return { [this[kBindingName]]: this.wasiImport };
}
}
exports.WASI = WASI;
function wasiReturnOnProcExit(rval) {
this[kExitCode] = rval;
// eslint-disable-next-line @typescript-eslint/no-throw-literal
throw kExitCode;
}
/** @public */
async function createAsyncWASI(options = kEmptyObject) {
const _this = Object.create(WASI.prototype);
const { args, env, preopens, stdio, _WASI } = validateOptions.call(_this, options);
if (options.asyncify !== undefined) {
(0, util_1.validateObject)(options.asyncify, 'options.asyncify');
(0, util_1.validateFunction)(options.asyncify.wrapImportFunction, 'options.asyncify.wrapImportFunction');
}
const wrap = await _WASI.createAsync(args, env, preopens, stdio, options.fs, options.print, options.printErr, options.asyncify);
const setMemory = wrap._setMemory;
delete wrap._setMemory;
initWASI.call(_this, setMemory, wrap);
if (options.returnOnExit) {
wrap.proc_exit = wasiReturnOnProcExit.bind(_this);
}
return _this;
}
exports.createAsyncWASI = createAsyncWASI;
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1,316 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.relative = exports.resolve = void 0;
const util_1 = require("./util");
const CHAR_DOT = 46; /* . */
const CHAR_FORWARD_SLASH = 47; /* / */
const CHAR_BACKWARD_SLASH = 92; /* \ */
const CHAR_COLON = 58; /* : */
const CHAR_UPPERCASE_A = 65; /* A */
const CHAR_UPPERCASE_Z = 90; /* Z */
const CHAR_LOWERCASE_A = 97; /* a */
const CHAR_LOWERCASE_Z = 122; /* z */
function isPathSeparatorWin(code) {
return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
}
function isWindowsDeviceRoot(code) {
return (code >= CHAR_UPPERCASE_A && code <= CHAR_UPPERCASE_Z) ||
(code >= CHAR_LOWERCASE_A && code <= CHAR_LOWERCASE_Z);
}
const _isWin32 = typeof process !== 'undefined' && process.platform === 'win32';
/**
* Windows variant of `resolve()`. Mirrors Node's `path.win32.resolve`
* semantics enough for the WASI shim's needs (drive-letter absolutes
* + UNC paths + per-drive cwd lookups via `process.env`/`process.cwd`).
*
* Why this is needed: on Windows, `FileDescriptor.realPath` is the
* host realpath returned by `fs.realpathSync(realPath, 'utf8')` — the
* backslash form `D:\…`. The POSIX-only `resolveImpl` below only
* treats `/` as a separator, reads `D` as non-`/`, decides realPath
* is "relative", and produces a garbage joined path. Downstream
* `fs.openSync(garbage)` then returns `EINVAL` and the WASI caller
* sees a permanent failure. This function gives us the correct
* Windows-style resolution without taking a Node-only `path` import
* (which would break browser bundles of this package).
*
* Cribbed from Node's `lib/path.js` `win32.resolve()` (MIT-licensed),
* trimmed to what WASI realpath resolution actually exercises.
*/
function resolveWin32(args) {
let resolvedDevice = '';
let resolvedTail = '';
let resolvedAbsolute = false;
for (let i = args.length - 1; i >= -1; i--) {
let path;
if (i >= 0) {
path = args[i];
(0, util_1.validateString)(path, 'path');
if (path.length === 0)
continue;
}
else if (resolvedDevice.length === 0) {
path = (typeof process !== 'undefined' && typeof process.cwd === 'function')
? process.cwd()
: '';
}
else {
// Look up per-drive cwd via the `=X:` env var convention; fall back
// to the global cwd if absent.
const envKey = `=${resolvedDevice}`;
const env = (typeof process !== 'undefined') ? process.env : undefined;
path = (env && typeof env[envKey] === 'string')
? env[envKey]
: (typeof process !== 'undefined' && typeof process.cwd === 'function')
? process.cwd()
: '';
if (path === undefined ||
(path.slice(0, 2).toLowerCase() !== resolvedDevice.toLowerCase() &&
path.charCodeAt(2) === CHAR_BACKWARD_SLASH)) {
path = `${resolvedDevice}\\`;
}
}
const len = path.length;
let rootEnd = 0;
let device = '';
let isAbsolute = false;
const code = path.charCodeAt(0);
if (len === 1) {
if (isPathSeparatorWin(code)) {
rootEnd = 1;
isAbsolute = true;
}
}
else if (isPathSeparatorWin(code)) {
isAbsolute = true;
if (isPathSeparatorWin(path.charCodeAt(1))) {
// UNC path: `\\server\share\…`
let j = 2;
let last = j;
while (j < len && !isPathSeparatorWin(path.charCodeAt(j)))
j++;
if (j < len && j !== last) {
const firstPart = path.slice(last, j);
last = j;
while (j < len && isPathSeparatorWin(path.charCodeAt(j)))
j++;
if (j < len && j !== last) {
last = j;
while (j < len && !isPathSeparatorWin(path.charCodeAt(j)))
j++;
if (j === len || j !== last) {
device = `\\\\${firstPart}\\${path.slice(last, j)}`;
rootEnd = j;
}
}
}
}
else {
rootEnd = 1;
}
}
else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) {
device = path.slice(0, 2);
rootEnd = 2;
if (len > 2 && isPathSeparatorWin(path.charCodeAt(2))) {
isAbsolute = true;
rootEnd = 3;
}
}
if (device.length > 0) {
if (resolvedDevice.length > 0) {
if (device.toLowerCase() !== resolvedDevice.toLowerCase())
continue;
}
else {
resolvedDevice = device;
}
}
if (resolvedAbsolute) {
if (resolvedDevice.length > 0)
break;
}
else {
resolvedTail = `${path.slice(rootEnd)}\\${resolvedTail}`;
resolvedAbsolute = isAbsolute;
if (isAbsolute && resolvedDevice.length > 0)
break;
}
}
resolvedTail = normalizeString(resolvedTail, !resolvedAbsolute, '\\', isPathSeparatorWin);
return resolvedDevice + (resolvedAbsolute ? '\\' : '') + resolvedTail || '.';
}
function isPosixPathSeparator(code) {
return code === CHAR_FORWARD_SLASH;
}
function normalizeString(path, allowAboveRoot, separator, isPathSeparator) {
let res = '';
let lastSegmentLength = 0;
let lastSlash = -1;
let dots = 0;
let code = 0;
for (let i = 0; i <= path.length; ++i) {
if (i < path.length) {
code = path.charCodeAt(i);
}
else if (isPathSeparator(code)) {
break;
}
else {
code = CHAR_FORWARD_SLASH;
}
if (isPathSeparator(code)) {
if (lastSlash === i - 1 || dots === 1) {
// NOOP
}
else if (dots === 2) {
if (res.length < 2 || lastSegmentLength !== 2 ||
res.charCodeAt(res.length - 1) !== CHAR_DOT ||
res.charCodeAt(res.length - 2) !== CHAR_DOT) {
if (res.length > 2) {
const lastSlashIndex = res.indexOf(separator);
if (lastSlashIndex === -1) {
res = '';
lastSegmentLength = 0;
}
else {
res = res.slice(0, lastSlashIndex);
lastSegmentLength =
res.length - 1 - res.indexOf(separator);
}
lastSlash = i;
dots = 0;
continue;
}
else if (res.length !== 0) {
res = '';
lastSegmentLength = 0;
lastSlash = i;
dots = 0;
continue;
}
}
if (allowAboveRoot) {
res += res.length > 0 ? `${separator}..` : '..';
lastSegmentLength = 2;
}
}
else {
if (res.length > 0) {
res += `${separator}${path.slice(lastSlash + 1, i)}`;
}
else {
res = path.slice(lastSlash + 1, i);
}
lastSegmentLength = i - lastSlash - 1;
}
lastSlash = i;
dots = 0;
}
else if (code === CHAR_DOT && dots !== -1) {
++dots;
}
else {
dots = -1;
}
}
return res;
}
function resolve(...args) {
// On Windows, host paths are `D:\…` style. The POSIX-only resolver
// below treats `D` as a non-`/` character and produces garbage; route
// to the Windows-aware variant. POSIX hosts (Linux/macOS/browser)
// run the original code path unchanged — `_isWin32` is constant-folded
// away on those targets.
if (_isWin32)
return resolveWin32(args);
let resolvedPath = '';
let resolvedAbsolute = false;
for (let i = args.length - 1; i >= -1 && !resolvedAbsolute; i--) {
const path = i >= 0 ? args[i] : '/';
(0, util_1.validateString)(path, 'path');
// Skip empty entries
if (path.length === 0) {
continue;
}
resolvedPath = `${path}/${resolvedPath}`;
resolvedAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH;
}
// At this point the path should be resolved to a full absolute path, but
// handle relative paths to be safe (might happen when process.cwd() fails)
// Normalize the path
resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute, '/', isPosixPathSeparator);
if (resolvedAbsolute) {
return `/${resolvedPath}`;
}
return resolvedPath.length > 0 ? resolvedPath : '.';
}
exports.resolve = resolve;
function relative(from, to) {
(0, util_1.validateString)(from, 'from');
(0, util_1.validateString)(to, 'to');
if (from === to)
return '';
// Trim leading forward slashes.
from = resolve(from);
to = resolve(to);
if (from === to)
return '';
const fromStart = 1;
const fromEnd = from.length;
const fromLen = fromEnd - fromStart;
const toStart = 1;
const toLen = to.length - toStart;
// Compare paths to find the longest common path from root
const length = (fromLen < toLen ? fromLen : toLen);
let lastCommonSep = -1;
let i = 0;
for (; i < length; i++) {
const fromCode = from.charCodeAt(fromStart + i);
if (fromCode !== to.charCodeAt(toStart + i)) {
break;
}
else if (fromCode === CHAR_FORWARD_SLASH) {
lastCommonSep = i;
}
}
if (i === length) {
if (toLen > length) {
if (to.charCodeAt(toStart + i) === CHAR_FORWARD_SLASH) {
// We get here if `from` is the exact base path for `to`.
// For example: from='/foo/bar'; to='/foo/bar/baz'
return to.slice(toStart + i + 1);
}
if (i === 0) {
// We get here if `from` is the root
// For example: from='/'; to='/foo'
return to.slice(toStart + i);
}
}
else if (fromLen > length) {
if (from.charCodeAt(fromStart + i) === CHAR_FORWARD_SLASH) {
// We get here if `to` is the exact base path for `from`.
// For example: from='/foo/bar/baz'; to='/foo/bar'
lastCommonSep = i;
}
else if (i === 0) {
// We get here if `to` is the root.
// For example: from='/foo/bar'; to='/'
lastCommonSep = 0;
}
}
}
let out = '';
// Generate the relative path based on the path difference between `to`
// and `from`.
for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {
if (i === fromEnd ||
from.charCodeAt(i) === CHAR_FORWARD_SLASH) {
out += out.length === 0 ? '..' : '/..';
}
}
// Lastly, append the rest of the destination (`to`) path that comes after
// the common path parts.
return `${out}${to.slice(toStart + lastCommonSep)}`;
}
exports.relative = relative;
//# sourceMappingURL=path.js.map

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,141 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getRights = exports.TTY_INHERITING = exports.TTY_BASE = exports.SOCKET_INHERITING = exports.SOCKET_BASE = exports.DIRECTORY_INHERITING = exports.DIRECTORY_BASE = exports.REGULAR_FILE_INHERITING = exports.REGULAR_FILE_BASE = exports.CHARACTER_DEVICE_INHERITING = exports.CHARACTER_DEVICE_BASE = exports.BLOCK_DEVICE_INHERITING = exports.BLOCK_DEVICE_BASE = exports.RIGHTS_ALL = void 0;
/* eslint-disable spaced-comment */
const error_1 = require("./error");
const types_1 = require("./types");
exports.RIGHTS_ALL = types_1.WasiRights.FD_DATASYNC |
types_1.WasiRights.FD_READ |
types_1.WasiRights.FD_SEEK |
types_1.WasiRights.FD_FDSTAT_SET_FLAGS |
types_1.WasiRights.FD_SYNC |
types_1.WasiRights.FD_TELL |
types_1.WasiRights.FD_WRITE |
types_1.WasiRights.FD_ADVISE |
types_1.WasiRights.FD_ALLOCATE |
types_1.WasiRights.PATH_CREATE_DIRECTORY |
types_1.WasiRights.PATH_CREATE_FILE |
types_1.WasiRights.PATH_LINK_SOURCE |
types_1.WasiRights.PATH_LINK_TARGET |
types_1.WasiRights.PATH_OPEN |
types_1.WasiRights.FD_READDIR |
types_1.WasiRights.PATH_READLINK |
types_1.WasiRights.PATH_RENAME_SOURCE |
types_1.WasiRights.PATH_RENAME_TARGET |
types_1.WasiRights.PATH_FILESTAT_GET |
types_1.WasiRights.PATH_FILESTAT_SET_SIZE |
types_1.WasiRights.PATH_FILESTAT_SET_TIMES |
types_1.WasiRights.FD_FILESTAT_GET |
types_1.WasiRights.FD_FILESTAT_SET_TIMES |
types_1.WasiRights.FD_FILESTAT_SET_SIZE |
types_1.WasiRights.PATH_SYMLINK |
types_1.WasiRights.PATH_UNLINK_FILE |
types_1.WasiRights.PATH_REMOVE_DIRECTORY |
types_1.WasiRights.POLL_FD_READWRITE |
types_1.WasiRights.SOCK_SHUTDOWN |
types_1.WasiRights.SOCK_ACCEPT;
exports.BLOCK_DEVICE_BASE = exports.RIGHTS_ALL;
exports.BLOCK_DEVICE_INHERITING = exports.RIGHTS_ALL;
exports.CHARACTER_DEVICE_BASE = exports.RIGHTS_ALL;
exports.CHARACTER_DEVICE_INHERITING = exports.RIGHTS_ALL;
exports.REGULAR_FILE_BASE = types_1.WasiRights.FD_DATASYNC |
types_1.WasiRights.FD_READ |
types_1.WasiRights.FD_SEEK |
types_1.WasiRights.FD_FDSTAT_SET_FLAGS |
types_1.WasiRights.FD_SYNC |
types_1.WasiRights.FD_TELL |
types_1.WasiRights.FD_WRITE |
types_1.WasiRights.FD_ADVISE |
types_1.WasiRights.FD_ALLOCATE |
types_1.WasiRights.FD_FILESTAT_GET |
types_1.WasiRights.FD_FILESTAT_SET_SIZE |
types_1.WasiRights.FD_FILESTAT_SET_TIMES |
types_1.WasiRights.POLL_FD_READWRITE;
exports.REGULAR_FILE_INHERITING = BigInt(0);
exports.DIRECTORY_BASE = types_1.WasiRights.FD_FDSTAT_SET_FLAGS |
types_1.WasiRights.FD_SYNC |
types_1.WasiRights.FD_ADVISE |
types_1.WasiRights.PATH_CREATE_DIRECTORY |
types_1.WasiRights.PATH_CREATE_FILE |
types_1.WasiRights.PATH_LINK_SOURCE |
types_1.WasiRights.PATH_LINK_TARGET |
types_1.WasiRights.PATH_OPEN |
types_1.WasiRights.FD_READDIR |
types_1.WasiRights.PATH_READLINK |
types_1.WasiRights.PATH_RENAME_SOURCE |
types_1.WasiRights.PATH_RENAME_TARGET |
types_1.WasiRights.PATH_FILESTAT_GET |
types_1.WasiRights.PATH_FILESTAT_SET_SIZE |
types_1.WasiRights.PATH_FILESTAT_SET_TIMES |
types_1.WasiRights.FD_FILESTAT_GET |
types_1.WasiRights.FD_FILESTAT_SET_TIMES |
types_1.WasiRights.PATH_SYMLINK |
types_1.WasiRights.PATH_UNLINK_FILE |
types_1.WasiRights.PATH_REMOVE_DIRECTORY |
types_1.WasiRights.POLL_FD_READWRITE;
exports.DIRECTORY_INHERITING = exports.DIRECTORY_BASE | exports.REGULAR_FILE_BASE;
exports.SOCKET_BASE = (types_1.WasiRights.FD_READ |
types_1.WasiRights.FD_FDSTAT_SET_FLAGS |
types_1.WasiRights.FD_WRITE |
types_1.WasiRights.FD_FILESTAT_GET |
types_1.WasiRights.POLL_FD_READWRITE |
types_1.WasiRights.SOCK_SHUTDOWN);
exports.SOCKET_INHERITING = exports.RIGHTS_ALL;
exports.TTY_BASE = types_1.WasiRights.FD_READ |
types_1.WasiRights.FD_FDSTAT_SET_FLAGS |
types_1.WasiRights.FD_WRITE |
types_1.WasiRights.FD_FILESTAT_GET |
types_1.WasiRights.POLL_FD_READWRITE;
exports.TTY_INHERITING = BigInt(0);
function getRights(stdio, fd, flags, type) {
const ret = {
base: BigInt(0),
inheriting: BigInt(0)
};
if (type === types_1.WasiFileType.UNKNOWN) {
throw new error_1.WasiError('Unknown file type', types_1.WasiErrno.EINVAL);
}
switch (type) {
case types_1.WasiFileType.REGULAR_FILE:
ret.base = exports.REGULAR_FILE_BASE;
ret.inheriting = exports.REGULAR_FILE_INHERITING;
break;
case types_1.WasiFileType.DIRECTORY:
ret.base = exports.DIRECTORY_BASE;
ret.inheriting = exports.DIRECTORY_INHERITING;
break;
case types_1.WasiFileType.SOCKET_STREAM:
case types_1.WasiFileType.SOCKET_DGRAM:
ret.base = exports.SOCKET_BASE;
ret.inheriting = exports.SOCKET_INHERITING;
break;
case types_1.WasiFileType.CHARACTER_DEVICE:
if (stdio.indexOf(fd) !== -1) {
ret.base = exports.TTY_BASE;
ret.inheriting = exports.TTY_INHERITING;
}
else {
ret.base = exports.CHARACTER_DEVICE_BASE;
ret.inheriting = exports.CHARACTER_DEVICE_INHERITING;
}
break;
case types_1.WasiFileType.BLOCK_DEVICE:
ret.base = exports.BLOCK_DEVICE_BASE;
ret.inheriting = exports.BLOCK_DEVICE_INHERITING;
break;
default:
ret.base = BigInt(0);
ret.inheriting = BigInt(0);
}
/* Disable read/write bits depending on access mode. */
const read_or_write_only = flags & (0 | 1 | 2);
if (read_or_write_only === 0) {
ret.base &= ~types_1.WasiRights.FD_WRITE;
}
else if (read_or_write_only === 1) {
ret.base &= ~types_1.WasiRights.FD_READ;
}
return ret;
}
exports.getRights = getRights;
//# sourceMappingURL=rights.js.map

View File

@@ -0,0 +1,220 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.WasiSubclockflags = exports.WasiEventType = exports.WasiFstFlag = exports.WasiClockid = exports.WasiFdFlag = exports.WasiFileControlFlag = exports.FileControlFlag = exports.WasiWhence = exports.WasiRights = exports.WasiFileType = exports.WasiErrno = void 0;
/* eslint-disable spaced-comment */
var WasiErrno;
(function (WasiErrno) {
WasiErrno[WasiErrno["ESUCCESS"] = 0] = "ESUCCESS";
WasiErrno[WasiErrno["E2BIG"] = 1] = "E2BIG";
WasiErrno[WasiErrno["EACCES"] = 2] = "EACCES";
WasiErrno[WasiErrno["EADDRINUSE"] = 3] = "EADDRINUSE";
WasiErrno[WasiErrno["EADDRNOTAVAIL"] = 4] = "EADDRNOTAVAIL";
WasiErrno[WasiErrno["EAFNOSUPPORT"] = 5] = "EAFNOSUPPORT";
WasiErrno[WasiErrno["EAGAIN"] = 6] = "EAGAIN";
WasiErrno[WasiErrno["EALREADY"] = 7] = "EALREADY";
WasiErrno[WasiErrno["EBADF"] = 8] = "EBADF";
WasiErrno[WasiErrno["EBADMSG"] = 9] = "EBADMSG";
WasiErrno[WasiErrno["EBUSY"] = 10] = "EBUSY";
WasiErrno[WasiErrno["ECANCELED"] = 11] = "ECANCELED";
WasiErrno[WasiErrno["ECHILD"] = 12] = "ECHILD";
WasiErrno[WasiErrno["ECONNABORTED"] = 13] = "ECONNABORTED";
WasiErrno[WasiErrno["ECONNREFUSED"] = 14] = "ECONNREFUSED";
WasiErrno[WasiErrno["ECONNRESET"] = 15] = "ECONNRESET";
WasiErrno[WasiErrno["EDEADLK"] = 16] = "EDEADLK";
WasiErrno[WasiErrno["EDESTADDRREQ"] = 17] = "EDESTADDRREQ";
WasiErrno[WasiErrno["EDOM"] = 18] = "EDOM";
WasiErrno[WasiErrno["EDQUOT"] = 19] = "EDQUOT";
WasiErrno[WasiErrno["EEXIST"] = 20] = "EEXIST";
WasiErrno[WasiErrno["EFAULT"] = 21] = "EFAULT";
WasiErrno[WasiErrno["EFBIG"] = 22] = "EFBIG";
WasiErrno[WasiErrno["EHOSTUNREACH"] = 23] = "EHOSTUNREACH";
WasiErrno[WasiErrno["EIDRM"] = 24] = "EIDRM";
WasiErrno[WasiErrno["EILSEQ"] = 25] = "EILSEQ";
WasiErrno[WasiErrno["EINPROGRESS"] = 26] = "EINPROGRESS";
WasiErrno[WasiErrno["EINTR"] = 27] = "EINTR";
WasiErrno[WasiErrno["EINVAL"] = 28] = "EINVAL";
WasiErrno[WasiErrno["EIO"] = 29] = "EIO";
WasiErrno[WasiErrno["EISCONN"] = 30] = "EISCONN";
WasiErrno[WasiErrno["EISDIR"] = 31] = "EISDIR";
WasiErrno[WasiErrno["ELOOP"] = 32] = "ELOOP";
WasiErrno[WasiErrno["EMFILE"] = 33] = "EMFILE";
WasiErrno[WasiErrno["EMLINK"] = 34] = "EMLINK";
WasiErrno[WasiErrno["EMSGSIZE"] = 35] = "EMSGSIZE";
WasiErrno[WasiErrno["EMULTIHOP"] = 36] = "EMULTIHOP";
WasiErrno[WasiErrno["ENAMETOOLONG"] = 37] = "ENAMETOOLONG";
WasiErrno[WasiErrno["ENETDOWN"] = 38] = "ENETDOWN";
WasiErrno[WasiErrno["ENETRESET"] = 39] = "ENETRESET";
WasiErrno[WasiErrno["ENETUNREACH"] = 40] = "ENETUNREACH";
WasiErrno[WasiErrno["ENFILE"] = 41] = "ENFILE";
WasiErrno[WasiErrno["ENOBUFS"] = 42] = "ENOBUFS";
WasiErrno[WasiErrno["ENODEV"] = 43] = "ENODEV";
WasiErrno[WasiErrno["ENOENT"] = 44] = "ENOENT";
WasiErrno[WasiErrno["ENOEXEC"] = 45] = "ENOEXEC";
WasiErrno[WasiErrno["ENOLCK"] = 46] = "ENOLCK";
WasiErrno[WasiErrno["ENOLINK"] = 47] = "ENOLINK";
WasiErrno[WasiErrno["ENOMEM"] = 48] = "ENOMEM";
WasiErrno[WasiErrno["ENOMSG"] = 49] = "ENOMSG";
WasiErrno[WasiErrno["ENOPROTOOPT"] = 50] = "ENOPROTOOPT";
WasiErrno[WasiErrno["ENOSPC"] = 51] = "ENOSPC";
WasiErrno[WasiErrno["ENOSYS"] = 52] = "ENOSYS";
WasiErrno[WasiErrno["ENOTCONN"] = 53] = "ENOTCONN";
WasiErrno[WasiErrno["ENOTDIR"] = 54] = "ENOTDIR";
WasiErrno[WasiErrno["ENOTEMPTY"] = 55] = "ENOTEMPTY";
WasiErrno[WasiErrno["ENOTRECOVERABLE"] = 56] = "ENOTRECOVERABLE";
WasiErrno[WasiErrno["ENOTSOCK"] = 57] = "ENOTSOCK";
WasiErrno[WasiErrno["ENOTSUP"] = 58] = "ENOTSUP";
WasiErrno[WasiErrno["ENOTTY"] = 59] = "ENOTTY";
WasiErrno[WasiErrno["ENXIO"] = 60] = "ENXIO";
WasiErrno[WasiErrno["EOVERFLOW"] = 61] = "EOVERFLOW";
WasiErrno[WasiErrno["EOWNERDEAD"] = 62] = "EOWNERDEAD";
WasiErrno[WasiErrno["EPERM"] = 63] = "EPERM";
WasiErrno[WasiErrno["EPIPE"] = 64] = "EPIPE";
WasiErrno[WasiErrno["EPROTO"] = 65] = "EPROTO";
WasiErrno[WasiErrno["EPROTONOSUPPORT"] = 66] = "EPROTONOSUPPORT";
WasiErrno[WasiErrno["EPROTOTYPE"] = 67] = "EPROTOTYPE";
WasiErrno[WasiErrno["ERANGE"] = 68] = "ERANGE";
WasiErrno[WasiErrno["EROFS"] = 69] = "EROFS";
WasiErrno[WasiErrno["ESPIPE"] = 70] = "ESPIPE";
WasiErrno[WasiErrno["ESRCH"] = 71] = "ESRCH";
WasiErrno[WasiErrno["ESTALE"] = 72] = "ESTALE";
WasiErrno[WasiErrno["ETIMEDOUT"] = 73] = "ETIMEDOUT";
WasiErrno[WasiErrno["ETXTBSY"] = 74] = "ETXTBSY";
WasiErrno[WasiErrno["EXDEV"] = 75] = "EXDEV";
WasiErrno[WasiErrno["ENOTCAPABLE"] = 76] = "ENOTCAPABLE";
})(WasiErrno = exports.WasiErrno || (exports.WasiErrno = {}));
var WasiFileType;
(function (WasiFileType) {
WasiFileType[WasiFileType["UNKNOWN"] = 0] = "UNKNOWN";
WasiFileType[WasiFileType["BLOCK_DEVICE"] = 1] = "BLOCK_DEVICE";
WasiFileType[WasiFileType["CHARACTER_DEVICE"] = 2] = "CHARACTER_DEVICE";
WasiFileType[WasiFileType["DIRECTORY"] = 3] = "DIRECTORY";
WasiFileType[WasiFileType["REGULAR_FILE"] = 4] = "REGULAR_FILE";
WasiFileType[WasiFileType["SOCKET_DGRAM"] = 5] = "SOCKET_DGRAM";
WasiFileType[WasiFileType["SOCKET_STREAM"] = 6] = "SOCKET_STREAM";
WasiFileType[WasiFileType["SYMBOLIC_LINK"] = 7] = "SYMBOLIC_LINK";
})(WasiFileType = exports.WasiFileType || (exports.WasiFileType = {}));
const FD_DATASYNC = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(0));
const FD_READ = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(1));
const FD_SEEK = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(2));
const FD_FDSTAT_SET_FLAGS = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(3));
const FD_SYNC = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(4));
const FD_TELL = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(5));
const FD_WRITE = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(6));
const FD_ADVISE = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(7));
const FD_ALLOCATE = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(8));
const PATH_CREATE_DIRECTORY = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(9));
const PATH_CREATE_FILE = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(10));
const PATH_LINK_SOURCE = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(11));
const PATH_LINK_TARGET = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(12));
const PATH_OPEN = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(13));
const FD_READDIR = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(14));
const PATH_READLINK = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(15));
const PATH_RENAME_SOURCE = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(16));
const PATH_RENAME_TARGET = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(17));
const PATH_FILESTAT_GET = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(18));
const PATH_FILESTAT_SET_SIZE = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(19));
const PATH_FILESTAT_SET_TIMES = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(20));
const FD_FILESTAT_GET = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(21));
const FD_FILESTAT_SET_SIZE = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(22));
const FD_FILESTAT_SET_TIMES = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(23));
const PATH_SYMLINK = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(24));
const PATH_REMOVE_DIRECTORY = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(25));
const PATH_UNLINK_FILE = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(26));
const POLL_FD_READWRITE = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(27));
const SOCK_SHUTDOWN = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(28));
const SOCK_ACCEPT = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(29));
exports.WasiRights = {
FD_DATASYNC,
FD_READ,
FD_SEEK,
FD_FDSTAT_SET_FLAGS,
FD_SYNC,
FD_TELL,
FD_WRITE,
FD_ADVISE,
FD_ALLOCATE,
PATH_CREATE_DIRECTORY,
PATH_CREATE_FILE,
PATH_LINK_SOURCE,
PATH_LINK_TARGET,
PATH_OPEN,
FD_READDIR,
PATH_READLINK,
PATH_RENAME_SOURCE,
PATH_RENAME_TARGET,
PATH_FILESTAT_GET,
PATH_FILESTAT_SET_SIZE,
PATH_FILESTAT_SET_TIMES,
FD_FILESTAT_GET,
FD_FILESTAT_SET_SIZE,
FD_FILESTAT_SET_TIMES,
PATH_SYMLINK,
PATH_REMOVE_DIRECTORY,
PATH_UNLINK_FILE,
POLL_FD_READWRITE,
SOCK_SHUTDOWN,
SOCK_ACCEPT
};
var WasiWhence;
(function (WasiWhence) {
WasiWhence[WasiWhence["SET"] = 0] = "SET";
WasiWhence[WasiWhence["CUR"] = 1] = "CUR";
WasiWhence[WasiWhence["END"] = 2] = "END";
})(WasiWhence = exports.WasiWhence || (exports.WasiWhence = {}));
var FileControlFlag;
(function (FileControlFlag) {
FileControlFlag[FileControlFlag["O_RDONLY"] = 0] = "O_RDONLY";
FileControlFlag[FileControlFlag["O_WRONLY"] = 1] = "O_WRONLY";
FileControlFlag[FileControlFlag["O_RDWR"] = 2] = "O_RDWR";
FileControlFlag[FileControlFlag["O_CREAT"] = 64] = "O_CREAT";
FileControlFlag[FileControlFlag["O_EXCL"] = 128] = "O_EXCL";
FileControlFlag[FileControlFlag["O_NOCTTY"] = 256] = "O_NOCTTY";
FileControlFlag[FileControlFlag["O_TRUNC"] = 512] = "O_TRUNC";
FileControlFlag[FileControlFlag["O_APPEND"] = 1024] = "O_APPEND";
FileControlFlag[FileControlFlag["O_DIRECTORY"] = 65536] = "O_DIRECTORY";
FileControlFlag[FileControlFlag["O_NOATIME"] = 262144] = "O_NOATIME";
FileControlFlag[FileControlFlag["O_NOFOLLOW"] = 131072] = "O_NOFOLLOW";
FileControlFlag[FileControlFlag["O_SYNC"] = 1052672] = "O_SYNC";
FileControlFlag[FileControlFlag["O_DIRECT"] = 16384] = "O_DIRECT";
FileControlFlag[FileControlFlag["O_NONBLOCK"] = 2048] = "O_NONBLOCK";
})(FileControlFlag = exports.FileControlFlag || (exports.FileControlFlag = {}));
var WasiFileControlFlag;
(function (WasiFileControlFlag) {
WasiFileControlFlag[WasiFileControlFlag["O_CREAT"] = 1] = "O_CREAT";
WasiFileControlFlag[WasiFileControlFlag["O_DIRECTORY"] = 2] = "O_DIRECTORY";
WasiFileControlFlag[WasiFileControlFlag["O_EXCL"] = 4] = "O_EXCL";
WasiFileControlFlag[WasiFileControlFlag["O_TRUNC"] = 8] = "O_TRUNC";
})(WasiFileControlFlag = exports.WasiFileControlFlag || (exports.WasiFileControlFlag = {}));
var WasiFdFlag;
(function (WasiFdFlag) {
WasiFdFlag[WasiFdFlag["APPEND"] = 1] = "APPEND";
WasiFdFlag[WasiFdFlag["DSYNC"] = 2] = "DSYNC";
WasiFdFlag[WasiFdFlag["NONBLOCK"] = 4] = "NONBLOCK";
WasiFdFlag[WasiFdFlag["RSYNC"] = 8] = "RSYNC";
WasiFdFlag[WasiFdFlag["SYNC"] = 16] = "SYNC";
})(WasiFdFlag = exports.WasiFdFlag || (exports.WasiFdFlag = {}));
var WasiClockid;
(function (WasiClockid) {
WasiClockid[WasiClockid["REALTIME"] = 0] = "REALTIME";
WasiClockid[WasiClockid["MONOTONIC"] = 1] = "MONOTONIC";
WasiClockid[WasiClockid["PROCESS_CPUTIME_ID"] = 2] = "PROCESS_CPUTIME_ID";
WasiClockid[WasiClockid["THREAD_CPUTIME_ID"] = 3] = "THREAD_CPUTIME_ID";
})(WasiClockid = exports.WasiClockid || (exports.WasiClockid = {}));
var WasiFstFlag;
(function (WasiFstFlag) {
WasiFstFlag[WasiFstFlag["SET_ATIM"] = 1] = "SET_ATIM";
WasiFstFlag[WasiFstFlag["SET_ATIM_NOW"] = 2] = "SET_ATIM_NOW";
WasiFstFlag[WasiFstFlag["SET_MTIM"] = 4] = "SET_MTIM";
WasiFstFlag[WasiFstFlag["SET_MTIM_NOW"] = 8] = "SET_MTIM_NOW";
})(WasiFstFlag = exports.WasiFstFlag || (exports.WasiFstFlag = {}));
var WasiEventType;
(function (WasiEventType) {
WasiEventType[WasiEventType["CLOCK"] = 0] = "CLOCK";
WasiEventType[WasiEventType["FD_READ"] = 1] = "FD_READ";
WasiEventType[WasiEventType["FD_WRITE"] = 2] = "FD_WRITE";
})(WasiEventType = exports.WasiEventType || (exports.WasiEventType = {}));
var WasiSubclockflags;
(function (WasiSubclockflags) {
WasiSubclockflags[WasiSubclockflags["ABSTIME"] = 1] = "ABSTIME";
})(WasiSubclockflags = exports.WasiSubclockflags || (exports.WasiSubclockflags = {}));
//# sourceMappingURL=types.js.map

View File

@@ -0,0 +1,128 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.unsharedSlice = exports.sleepBreakIf = exports.postMsg = exports.isMainThread = exports.wrapInstanceExports = exports.isPromiseLike = exports.validateInt32 = exports.validateUndefined = exports.validateFunction = exports.validateString = exports.validateBoolean = exports.validateArray = exports.validateObject = void 0;
/* eslint-disable spaced-comment */
function validateObject(value, name) {
if (value === null || typeof value !== 'object') {
throw new TypeError(`${name} must be an object. Received ${value === null ? 'null' : typeof value}`);
}
}
exports.validateObject = validateObject;
function validateArray(value, name) {
if (!Array.isArray(value)) {
throw new TypeError(`${name} must be an array. Received ${value === null ? 'null' : typeof value}`);
}
}
exports.validateArray = validateArray;
function validateBoolean(value, name) {
if (typeof value !== 'boolean') {
throw new TypeError(`${name} must be a boolean. Received ${value === null ? 'null' : typeof value}`);
}
}
exports.validateBoolean = validateBoolean;
function validateString(value, name) {
if (typeof value !== 'string') {
throw new TypeError(`${name} must be a string. Received ${value === null ? 'null' : typeof value}`);
}
}
exports.validateString = validateString;
function validateFunction(value, name) {
if (typeof value !== 'function') {
throw new TypeError(`${name} must be a function. Received ${value === null ? 'null' : typeof value}`);
}
}
exports.validateFunction = validateFunction;
function validateUndefined(value, name) {
if (value !== undefined) {
throw new TypeError(`${name} must be undefined. Received ${value === null ? 'null' : typeof value}`);
}
}
exports.validateUndefined = validateUndefined;
function validateInt32(value, name, min = -2147483648, max = 2147483647) {
if (typeof value !== 'number') {
throw new TypeError(`${name} must be a number. Received ${value === null ? 'null' : typeof value}`);
}
if (!Number.isInteger(value)) {
throw new RangeError(`${name} must be a integer.`);
}
if (value < min || value > max) {
throw new RangeError(`${name} must be >= ${min} && <= ${max}. Received ${value}`);
}
}
exports.validateInt32 = validateInt32;
function isPromiseLike(obj) {
return !!(obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function');
}
exports.isPromiseLike = isPromiseLike;
function wrapInstanceExports(exports, mapFn) {
const newExports = Object.create(null);
Object.keys(exports).forEach(name => {
const exportValue = exports[name];
Object.defineProperty(newExports, name, {
enumerable: true,
value: mapFn(exportValue, name)
});
});
return newExports;
}
exports.wrapInstanceExports = wrapInstanceExports;
const _require = /*#__PURE__*/ (function () {
let nativeRequire;
if (typeof __webpack_public_path__ !== 'undefined') {
nativeRequire = (function () {
return typeof __non_webpack_require__ !== 'undefined' ? __non_webpack_require__ : undefined;
})();
}
else {
nativeRequire = (function () {
return typeof __webpack_public_path__ !== 'undefined' ? (typeof __non_webpack_require__ !== 'undefined' ? __non_webpack_require__ : undefined) : (typeof require !== 'undefined' ? require : undefined);
})();
}
return nativeRequire;
})();
exports.isMainThread = (function () {
let worker_threads;
try {
worker_threads = _require('worker_threads');
}
catch (_) { }
if (!worker_threads) {
return typeof importScripts === 'undefined';
}
return worker_threads.isMainThread;
})();
exports.postMsg = exports.isMainThread
? () => { }
: /*#__PURE__*/ (function () {
let worker_threads;
try {
worker_threads = _require('worker_threads');
}
catch (_) { }
if (!worker_threads) {
return postMessage;
}
return function postMessage(data) {
worker_threads.parentPort.postMessage({ data });
};
})();
function sleepBreakIf(delay, breakIf) {
const start = Date.now();
const end = start + delay;
let ret = false;
while (Date.now() < end) {
if (breakIf()) {
ret = true;
break;
}
}
return ret;
}
exports.sleepBreakIf = sleepBreakIf;
function unsharedSlice(view, start, end) {
return ((typeof SharedArrayBuffer === 'function' && view.buffer instanceof SharedArrayBuffer) || (Object.prototype.toString.call(view.buffer.constructor) === '[object SharedArrayBuffer]'))
? view.slice(start, end)
: view.subarray(start, end);
}
exports.unsharedSlice = unsharedSlice;
//# sourceMappingURL=util.js.map

View File

@@ -0,0 +1,13 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports._WebAssembly = void 0;
const _WebAssembly = typeof WebAssembly !== 'undefined'
? WebAssembly
: typeof WXWebAssembly !== 'undefined'
? WXWebAssembly
: undefined;
exports._WebAssembly = _WebAssembly;
if (!_WebAssembly) {
throw new Error('WebAssembly is not supported in this environment');
}
//# sourceMappingURL=webassembly.js.map

View File

@@ -0,0 +1,153 @@
import { _WebAssembly } from "./webassembly.mjs";
import { isPromiseLike, wrapInstanceExports } from "./wasi/util.mjs";
const ignoreNames = [
'asyncify_get_state',
'asyncify_start_rewind',
'asyncify_start_unwind',
'asyncify_stop_rewind',
'asyncify_stop_unwind'
];
// const wrappedExports = new WeakMap<WebAssembly.Exports, WebAssembly.Exports>()
var AsyncifyState;
(function (AsyncifyState) {
AsyncifyState[AsyncifyState["NONE"] = 0] = "NONE";
AsyncifyState[AsyncifyState["UNWINDING"] = 1] = "UNWINDING";
AsyncifyState[AsyncifyState["REWINDING"] = 2] = "REWINDING";
})(AsyncifyState || (AsyncifyState = {}));
function tryAllocate(instance, wasm64, size, mallocName) {
if (typeof instance.exports[mallocName] !== 'function' || size <= 0) {
return {
wasm64,
dataPtr: 16,
start: wasm64 ? 32 : 24,
end: 1024
};
}
const malloc = instance.exports[mallocName];
const dataPtr = wasm64 ? Number(malloc(BigInt(16) + BigInt(size))) : malloc(8 + size);
if (dataPtr === 0) {
throw new Error('Allocate asyncify data failed');
}
return wasm64
? { wasm64, dataPtr, start: dataPtr + 16, end: dataPtr + 16 + size }
: { wasm64, dataPtr, start: dataPtr + 8, end: dataPtr + 8 + size };
}
/** @public */
export class Asyncify {
constructor() {
this.value = undefined;
this.exports = undefined;
this.dataPtr = 0;
}
init(memory, instance, options) {
var _a, _b;
if (this.exports) {
throw new Error('Asyncify has been initialized');
}
if (!(memory instanceof _WebAssembly.Memory)) {
throw new TypeError('Require WebAssembly.Memory object');
}
const exports = instance.exports;
for (let i = 0; i < ignoreNames.length; ++i) {
if (typeof exports[ignoreNames[i]] !== 'function') {
throw new TypeError('Invalid asyncify wasm');
}
}
let address;
const wasm64 = Boolean(options.wasm64);
if (!options.tryAllocate) {
address = {
wasm64,
dataPtr: 16,
start: wasm64 ? 32 : 24,
end: 1024
};
}
else {
if (options.tryAllocate === true) {
address = tryAllocate(instance, wasm64, 4096, 'malloc');
}
else {
address = tryAllocate(instance, wasm64, (_a = options.tryAllocate.size) !== null && _a !== void 0 ? _a : 4096, (_b = options.tryAllocate.name) !== null && _b !== void 0 ? _b : 'malloc');
}
}
this.dataPtr = address.dataPtr;
if (wasm64) {
new BigInt64Array(memory.buffer, this.dataPtr).set([BigInt(address.start), BigInt(address.end)]);
}
else {
new Int32Array(memory.buffer, this.dataPtr).set([address.start, address.end]);
}
this.exports = this.wrapExports(exports, options.wrapExports);
const asyncifiedInstance = Object.create(_WebAssembly.Instance.prototype);
Object.defineProperty(asyncifiedInstance, 'exports', { value: this.exports });
// Object.setPrototypeOf(instance, Instance.prototype)
return asyncifiedInstance;
}
assertState() {
if (this.exports.asyncify_get_state() !== AsyncifyState.NONE) {
throw new Error('Asyncify state error');
}
}
wrapImportFunction(f) {
// eslint-disable-next-line @typescript-eslint/no-this-alias
const _this = this;
return (function () {
// eslint-disable-next-line no-unreachable-loop
while (_this.exports.asyncify_get_state() === AsyncifyState.REWINDING) {
_this.exports.asyncify_stop_rewind();
return _this.value;
}
_this.assertState();
const v = f.apply(this, arguments);
if (!isPromiseLike(v))
return v;
_this.exports.asyncify_start_unwind(_this.dataPtr);
_this.value = v;
});
}
wrapImports(imports) {
const importObject = {};
Object.keys(imports).forEach(k => {
const mod = imports[k];
const newModule = {};
Object.keys(mod).forEach(name => {
const importValue = mod[name];
if (typeof importValue === 'function') {
newModule[name] = this.wrapImportFunction(importValue);
}
else {
newModule[name] = importValue;
}
});
importObject[k] = newModule;
});
return importObject;
}
wrapExportFunction(f) {
// eslint-disable-next-line @typescript-eslint/no-this-alias
const _this = this;
return (async function () {
_this.assertState();
let ret = f.apply(this, arguments);
while (_this.exports.asyncify_get_state() === AsyncifyState.UNWINDING) {
_this.exports.asyncify_stop_unwind();
_this.value = await _this.value;
_this.assertState();
_this.exports.asyncify_start_rewind(_this.dataPtr);
ret = f.call(this);
}
_this.assertState();
return ret;
});
}
wrapExports(exports, needWrap) {
return wrapInstanceExports(exports, (exportValue, name) => {
let ignore = ignoreNames.indexOf(name) !== -1 || typeof exportValue !== 'function';
if (Array.isArray(needWrap)) {
ignore = ignore || (needWrap.indexOf(name) === -1);
}
return ignore ? exportValue : this.wrapExportFunction(exportValue);
});
}
}

View File

@@ -0,0 +1,9 @@
/**
* @packageDocumentation
*/
export * from "./asyncify.mjs";
export * from "./load.mjs";
export * from "./wasi/index.mjs";
export * from "./memory.mjs";
export * from "./jspi.mjs";
export * from "./wasi/fs.mjs";

39
client/node_modules/@tybys/wasm-util/lib/mjs/jspi.mjs generated vendored Normal file
View File

@@ -0,0 +1,39 @@
import { wrapInstanceExports } from "./wasi/util.mjs";
import { _WebAssembly } from "./webassembly.mjs";
function checkWebAssemblyFunction() {
const WebAssemblyFunction = _WebAssembly.Function;
if (typeof WebAssemblyFunction !== 'function') {
throw new Error('WebAssembly.Function is not supported in this environment.' +
' If you are using V8 based browser like Chrome, try to specify' +
' --js-flags="--wasm-staging --experimental-wasm-stack-switching"');
}
return WebAssemblyFunction;
}
/** @public */
export function wrapAsyncImport(f, parameterType, returnType) {
const WebAssemblyFunction = checkWebAssemblyFunction();
if (typeof f !== 'function') {
throw new TypeError('Function required');
}
const parameters = parameterType.slice(0);
parameters.unshift('externref');
return new WebAssemblyFunction({ parameters, results: returnType }, f, { suspending: 'first' });
}
/** @public */
export function wrapAsyncExport(f) {
const WebAssemblyFunction = checkWebAssemblyFunction();
if (typeof f !== 'function') {
throw new TypeError('Function required');
}
return new WebAssemblyFunction({ parameters: [...WebAssemblyFunction.type(f).parameters.slice(1)], results: ['externref'] }, f, { promising: 'first' });
}
/** @public */
export function wrapExports(exports, needWrap) {
return wrapInstanceExports(exports, (exportValue, name) => {
let ignore = typeof exportValue !== 'function';
if (Array.isArray(needWrap)) {
ignore = ignore || (needWrap.indexOf(name) === -1);
}
return ignore ? exportValue : wrapAsyncExport(exportValue);
});
}

89
client/node_modules/@tybys/wasm-util/lib/mjs/load.mjs generated vendored Normal file
View File

@@ -0,0 +1,89 @@
import { _WebAssembly } from "./webassembly.mjs";
import { Asyncify } from "./asyncify.mjs";
function validateImports(imports) {
if (imports && typeof imports !== 'object') {
throw new TypeError('imports must be an object or undefined');
}
}
function fetchWasm(urlOrBuffer, imports) {
if (typeof wx !== 'undefined' && typeof __wxConfig !== 'undefined') {
return _WebAssembly.instantiate(urlOrBuffer, imports);
}
return fetch(urlOrBuffer)
.then(response => response.arrayBuffer())
.then(buffer => _WebAssembly.instantiate(buffer, imports));
}
/** @public */
export function load(wasmInput, imports) {
validateImports(imports);
imports = imports !== null && imports !== void 0 ? imports : {};
let source;
if (wasmInput instanceof ArrayBuffer || ArrayBuffer.isView(wasmInput)) {
return _WebAssembly.instantiate(wasmInput, imports);
}
if (wasmInput instanceof _WebAssembly.Module) {
return _WebAssembly.instantiate(wasmInput, imports).then((instance) => {
return { instance, module: wasmInput };
});
}
if (typeof wasmInput !== 'string' && !(wasmInput instanceof URL)) {
throw new TypeError('Invalid source');
}
if (typeof _WebAssembly.instantiateStreaming === 'function') {
let responsePromise;
try {
responsePromise = fetch(wasmInput);
source = _WebAssembly.instantiateStreaming(responsePromise, imports).catch(() => {
return fetchWasm(wasmInput, imports);
});
}
catch (_) {
source = fetchWasm(wasmInput, imports);
}
}
else {
source = fetchWasm(wasmInput, imports);
}
return source;
}
/** @public */
export function asyncifyLoad(asyncify, urlOrBuffer, imports) {
validateImports(imports);
imports = imports !== null && imports !== void 0 ? imports : {};
const asyncifyHelper = new Asyncify();
imports = asyncifyHelper.wrapImports(imports);
return load(urlOrBuffer, imports).then(source => {
var _a;
const memory = source.instance.exports.memory || ((_a = imports.env) === null || _a === void 0 ? void 0 : _a.memory);
return { module: source.module, instance: asyncifyHelper.init(memory, source.instance, asyncify) };
});
}
/** @public */
export function loadSync(wasmInput, imports) {
validateImports(imports);
imports = imports !== null && imports !== void 0 ? imports : {};
let module;
if ((wasmInput instanceof ArrayBuffer) || ArrayBuffer.isView(wasmInput)) {
module = new _WebAssembly.Module(wasmInput);
}
else if (wasmInput instanceof WebAssembly.Module) {
module = wasmInput;
}
else {
throw new TypeError('Invalid source');
}
const instance = new _WebAssembly.Instance(module, imports);
const source = { instance, module };
return source;
}
/** @public */
export function asyncifyLoadSync(asyncify, buffer, imports) {
var _a;
validateImports(imports);
imports = imports !== null && imports !== void 0 ? imports : {};
const asyncifyHelper = new Asyncify();
imports = asyncifyHelper.wrapImports(imports);
const source = loadSync(buffer, imports);
const memory = source.instance.exports.memory || ((_a = imports.env) === null || _a === void 0 ? void 0 : _a.memory);
return { module: source.module, instance: asyncifyHelper.init(memory, source.instance, asyncify) };
}

View File

@@ -0,0 +1,28 @@
import { _WebAssembly } from "./webassembly.mjs";
/** @public */
export const WebAssemblyMemory = /*#__PURE__*/ (function () { return _WebAssembly.Memory; })();
/** @public */
export class Memory extends WebAssemblyMemory {
// eslint-disable-next-line @typescript-eslint/no-useless-constructor
constructor(descriptor) {
super(descriptor);
}
get HEAP8() { return new Int8Array(super.buffer); }
get HEAPU8() { return new Uint8Array(super.buffer); }
get HEAP16() { return new Int16Array(super.buffer); }
get HEAPU16() { return new Uint16Array(super.buffer); }
get HEAP32() { return new Int32Array(super.buffer); }
get HEAPU32() { return new Uint32Array(super.buffer); }
get HEAP64() { return new BigInt64Array(super.buffer); }
get HEAPU64() { return new BigUint64Array(super.buffer); }
get HEAPF32() { return new Float32Array(super.buffer); }
get HEAPF64() { return new Float64Array(super.buffer); }
get view() { return new DataView(super.buffer); }
}
/** @public */
export function extendMemory(memory) {
if (Object.getPrototypeOf(memory) === _WebAssembly.Memory.prototype) {
Object.setPrototypeOf(memory, Memory.prototype);
}
return memory;
}

View File

@@ -0,0 +1,97 @@
import { WasiErrno } from "./types.mjs";
export function strerror(errno) {
switch (errno) {
case WasiErrno.ESUCCESS: return 'Success';
case WasiErrno.E2BIG: return 'Argument list too long';
case WasiErrno.EACCES: return 'Permission denied';
case WasiErrno.EADDRINUSE: return 'Address in use';
case WasiErrno.EADDRNOTAVAIL: return 'Address not available';
case WasiErrno.EAFNOSUPPORT: return 'Address family not supported by protocol';
case WasiErrno.EAGAIN: return 'Resource temporarily unavailable';
case WasiErrno.EALREADY: return 'Operation already in progress';
case WasiErrno.EBADF: return 'Bad file descriptor';
case WasiErrno.EBADMSG: return 'Bad message';
case WasiErrno.EBUSY: return 'Resource busy';
case WasiErrno.ECANCELED: return 'Operation canceled';
case WasiErrno.ECHILD: return 'No child process';
case WasiErrno.ECONNABORTED: return 'Connection aborted';
case WasiErrno.ECONNREFUSED: return 'Connection refused';
case WasiErrno.ECONNRESET: return 'Connection reset by peer';
case WasiErrno.EDEADLK: return 'Resource deadlock would occur';
case WasiErrno.EDESTADDRREQ: return 'Destination address required';
case WasiErrno.EDOM: return 'Domain error';
case WasiErrno.EDQUOT: return 'Quota exceeded';
case WasiErrno.EEXIST: return 'File exists';
case WasiErrno.EFAULT: return 'Bad address';
case WasiErrno.EFBIG: return 'File too large';
case WasiErrno.EHOSTUNREACH: return 'Host is unreachable';
case WasiErrno.EIDRM: return 'Identifier removed';
case WasiErrno.EILSEQ: return 'Illegal byte sequence';
case WasiErrno.EINPROGRESS: return 'Operation in progress';
case WasiErrno.EINTR: return 'Interrupted system call';
case WasiErrno.EINVAL: return 'Invalid argument';
case WasiErrno.EIO: return 'I/O error';
case WasiErrno.EISCONN: return 'Socket is connected';
case WasiErrno.EISDIR: return 'Is a directory';
case WasiErrno.ELOOP: return 'Symbolic link loop';
case WasiErrno.EMFILE: return 'No file descriptors available';
case WasiErrno.EMLINK: return 'Too many links';
case WasiErrno.EMSGSIZE: return 'Message too large';
case WasiErrno.EMULTIHOP: return 'Multihop attempted';
case WasiErrno.ENAMETOOLONG: return 'Filename too long';
case WasiErrno.ENETDOWN: return 'Network is down';
case WasiErrno.ENETRESET: return 'Connection reset by network';
case WasiErrno.ENETUNREACH: return 'Network unreachable';
case WasiErrno.ENFILE: return 'Too many files open in system';
case WasiErrno.ENOBUFS: return 'No buffer space available';
case WasiErrno.ENODEV: return 'No such device';
case WasiErrno.ENOENT: return 'No such file or directory';
case WasiErrno.ENOEXEC: return 'Exec format error';
case WasiErrno.ENOLCK: return 'No locks available';
case WasiErrno.ENOLINK: return 'Link has been severed';
case WasiErrno.ENOMEM: return 'Out of memory';
case WasiErrno.ENOMSG: return 'No message of the desired type';
case WasiErrno.ENOPROTOOPT: return 'Protocol not available';
case WasiErrno.ENOSPC: return 'No space left on device';
case WasiErrno.ENOSYS: return 'Function not implemented';
case WasiErrno.ENOTCONN: return 'Socket not connected';
case WasiErrno.ENOTDIR: return 'Not a directory';
case WasiErrno.ENOTEMPTY: return 'Directory not empty';
case WasiErrno.ENOTRECOVERABLE: return 'State not recoverable';
case WasiErrno.ENOTSOCK: return 'Not a socket';
case WasiErrno.ENOTSUP: return 'Not supported';
case WasiErrno.ENOTTY: return 'Not a tty';
case WasiErrno.ENXIO: return 'No such device or address';
case WasiErrno.EOVERFLOW: return 'Value too large for data type';
case WasiErrno.EOWNERDEAD: return 'Previous owner died';
case WasiErrno.EPERM: return 'Operation not permitted';
case WasiErrno.EPIPE: return 'Broken pipe';
case WasiErrno.EPROTO: return 'Protocol error';
case WasiErrno.EPROTONOSUPPORT: return 'Protocol not supported';
case WasiErrno.EPROTOTYPE: return 'Protocol wrong type for socket';
case WasiErrno.ERANGE: return 'Result not representable';
case WasiErrno.EROFS: return 'Read-only file system';
case WasiErrno.ESPIPE: return 'Invalid seek';
case WasiErrno.ESRCH: return 'No such process';
case WasiErrno.ESTALE: return 'Stale file handle';
case WasiErrno.ETIMEDOUT: return 'Operation timed out';
case WasiErrno.ETXTBSY: return 'Text file busy';
case WasiErrno.EXDEV: return 'Cross-device link';
case WasiErrno.ENOTCAPABLE: return 'Capabilities insufficient';
default: return 'Unknown error';
}
}
export class WasiError extends Error {
constructor(message, errno) {
super(message);
this.errno = errno;
}
getErrorMessage() {
return strerror(this.errno);
}
}
Object.defineProperty(WasiError.prototype, 'name', {
configurable: true,
writable: true,
value: 'WasiError'
});

View File

@@ -0,0 +1,256 @@
import { WasiErrno, FileControlFlag, WasiFileType, WasiWhence } from "./types.mjs";
import { getRights } from "./rights.mjs";
import { WasiError } from "./error.mjs";
export function concatBuffer(buffers, size) {
let total = 0;
if (typeof size === 'number' && size >= 0) {
total = size;
}
else {
for (let i = 0; i < buffers.length; i++) {
const buffer = buffers[i];
total += buffer.length;
}
}
let pos = 0;
const ret = new Uint8Array(total);
for (let i = 0; i < buffers.length; i++) {
const buffer = buffers[i];
ret.set(buffer, pos);
pos += buffer.length;
}
return ret;
}
export class FileDescriptor {
constructor(id, fd, path, realPath, type, rightsBase, rightsInheriting, preopen) {
this.id = id;
this.fd = fd;
this.path = path;
this.realPath = realPath;
this.type = type;
this.rightsBase = rightsBase;
this.rightsInheriting = rightsInheriting;
this.preopen = preopen;
this.pos = BigInt(0);
this.size = BigInt(0);
}
seek(offset, whence) {
if (whence === WasiWhence.SET) {
this.pos = BigInt(offset);
}
else if (whence === WasiWhence.CUR) {
this.pos += BigInt(offset);
}
else if (whence === WasiWhence.END) {
this.pos = BigInt(this.size) - BigInt(offset);
}
else {
throw new WasiError('Unknown whence', WasiErrno.EIO);
}
return this.pos;
}
}
export class StandardOutput extends FileDescriptor {
constructor(log, id, fd, path, realPath, type, rightsBase, rightsInheriting, preopen) {
super(id, fd, path, realPath, type, rightsBase, rightsInheriting, preopen);
this._log = log;
this._buf = null;
}
write(buffer) {
const originalBuffer = buffer;
if (this._buf) {
buffer = concatBuffer([this._buf, buffer]);
this._buf = null;
}
if (buffer.indexOf(10) === -1) {
this._buf = buffer;
return originalBuffer.byteLength;
}
let written = 0;
let lastBegin = 0;
let index;
while ((index = buffer.indexOf(10, written)) !== -1) {
const str = new TextDecoder().decode(buffer.subarray(lastBegin, index));
this._log(str);
written += index - lastBegin + 1;
lastBegin = index + 1;
}
if (written < buffer.length) {
this._buf = buffer.slice(written);
}
return originalBuffer.byteLength;
}
}
export function toFileType(stat) {
if (stat.isBlockDevice())
return WasiFileType.BLOCK_DEVICE;
if (stat.isCharacterDevice())
return WasiFileType.CHARACTER_DEVICE;
if (stat.isDirectory())
return WasiFileType.DIRECTORY;
if (stat.isSocket())
return WasiFileType.SOCKET_STREAM;
if (stat.isFile())
return WasiFileType.REGULAR_FILE;
if (stat.isSymbolicLink())
return WasiFileType.SYMBOLIC_LINK;
return WasiFileType.UNKNOWN;
}
export function toFileStat(view, buf, stat) {
view.setBigUint64(buf, stat.dev, true);
view.setBigUint64(buf + 8, stat.ino, true);
view.setBigUint64(buf + 16, BigInt(toFileType(stat)), true);
view.setBigUint64(buf + 24, stat.nlink, true);
view.setBigUint64(buf + 32, stat.size, true);
view.setBigUint64(buf + 40, stat.atimeMs * BigInt(1000000), true);
view.setBigUint64(buf + 48, stat.mtimeMs * BigInt(1000000), true);
view.setBigUint64(buf + 56, stat.ctimeMs * BigInt(1000000), true);
}
export class FileDescriptorTable {
constructor(options) {
this.used = 0;
this.size = options.size;
this.fds = Array(options.size);
this.stdio = [options.in, options.out, options.err];
this.print = options.print;
this.printErr = options.printErr;
this.insertStdio(options.in, 0, '<stdin>');
this.insertStdio(options.out, 1, '<stdout>');
this.insertStdio(options.err, 2, '<stderr>');
}
insertStdio(fd, expected, name) {
const type = WasiFileType.CHARACTER_DEVICE;
const { base, inheriting } = getRights(this.stdio, fd, FileControlFlag.O_RDWR, type);
const wrap = this.insert(fd, name, name, type, base, inheriting, 0);
if (wrap.id !== expected) {
throw new WasiError(`id: ${wrap.id} !== expected: ${expected}`, WasiErrno.EBADF);
}
return wrap;
}
insert(fd, mappedPath, realPath, type, rightsBase, rightsInheriting, preopen) {
var _a, _b;
let index = -1;
if (this.used >= this.size) {
const newSize = this.size * 2;
this.fds.length = newSize;
index = this.size;
this.size = newSize;
}
else {
for (let i = 0; i < this.size; ++i) {
if (this.fds[i] == null) {
index = i;
break;
}
}
}
let entry;
if (mappedPath === '<stdout>') {
entry = new StandardOutput((_a = this.print) !== null && _a !== void 0 ? _a : console.log, index, fd, mappedPath, realPath, type, rightsBase, rightsInheriting, preopen);
}
else if (mappedPath === '<stderr>') {
entry = new StandardOutput((_b = this.printErr) !== null && _b !== void 0 ? _b : console.error, index, fd, mappedPath, realPath, type, rightsBase, rightsInheriting, preopen);
}
else {
entry = new FileDescriptor(index, fd, mappedPath, realPath, type, rightsBase, rightsInheriting, preopen);
}
this.fds[index] = entry;
this.used++;
return entry;
}
get(id, base, inheriting) {
if (id >= this.size) {
throw new WasiError('Invalid fd', WasiErrno.EBADF);
}
const entry = this.fds[id];
if (!entry || entry.id !== id) {
throw new WasiError('Bad file descriptor', WasiErrno.EBADF);
}
/* Validate that the fd has the necessary rights. */
if ((~entry.rightsBase & base) !== BigInt(0) || (~entry.rightsInheriting & inheriting) !== BigInt(0)) {
throw new WasiError('Capabilities insufficient', WasiErrno.ENOTCAPABLE);
}
return entry;
}
remove(id) {
if (id >= this.size) {
throw new WasiError('Invalid fd', WasiErrno.EBADF);
}
const entry = this.fds[id];
if (!entry || entry.id !== id) {
throw new WasiError('Bad file descriptor', WasiErrno.EBADF);
}
this.fds[id] = undefined;
this.used--;
}
}
export class SyncTable extends FileDescriptorTable {
constructor(options) {
super(options);
this.fs = options.fs;
}
getFileTypeByFd(fd) {
const stats = this.fs.fstatSync(fd, { bigint: true });
return toFileType(stats);
}
insertPreopen(fd, mappedPath, realPath) {
const type = this.getFileTypeByFd(fd);
if (type !== WasiFileType.DIRECTORY) {
throw new WasiError(`Preopen not dir: ["${mappedPath}", "${realPath}"]`, WasiErrno.ENOTDIR);
}
const result = getRights(this.stdio, fd, 0, type);
return this.insert(fd, mappedPath, realPath, type, result.base, result.inheriting, 1);
}
renumber(dst, src) {
if (dst === src)
return;
if (dst >= this.size || src >= this.size) {
throw new WasiError('Invalid fd', WasiErrno.EBADF);
}
const dstEntry = this.fds[dst];
const srcEntry = this.fds[src];
if (!dstEntry || !srcEntry || dstEntry.id !== dst || srcEntry.id !== src) {
throw new WasiError('Invalid fd', WasiErrno.EBADF);
}
this.fs.closeSync(dstEntry.fd);
this.fds[dst] = this.fds[src];
this.fds[dst].id = dst;
this.fds[src] = undefined;
this.used--;
}
}
export class AsyncTable extends FileDescriptorTable {
// eslint-disable-next-line @typescript-eslint/no-useless-constructor
constructor(options) {
super(options);
}
async getFileTypeByFd(fd) {
const stats = await fd.stat({ bigint: true });
return toFileType(stats);
}
async insertPreopen(fd, mappedPath, realPath) {
const type = await this.getFileTypeByFd(fd);
if (type !== WasiFileType.DIRECTORY) {
throw new WasiError(`Preopen not dir: ["${mappedPath}", "${realPath}"]`, WasiErrno.ENOTDIR);
}
const result = getRights(this.stdio, fd.fd, 0, type);
return this.insert(fd, mappedPath, realPath, type, result.base, result.inheriting, 1);
}
async renumber(dst, src) {
if (dst === src)
return;
if (dst >= this.size || src >= this.size) {
throw new WasiError('Invalid fd', WasiErrno.EBADF);
}
const dstEntry = this.fds[dst];
const srcEntry = this.fds[src];
if (!dstEntry || !srcEntry || dstEntry.id !== dst || srcEntry.id !== src) {
throw new WasiError('Invalid fd', WasiErrno.EBADF);
}
await dstEntry.fd.close();
this.fds[dst] = this.fds[src];
this.fds[dst].id = dst;
this.fds[src] = undefined;
this.used--;
}
}

View File

@@ -0,0 +1 @@
export {};

View File

@@ -0,0 +1,186 @@
import { WASI as WASIPreview1 } from "./preview1.mjs";
import { validateObject, validateArray, validateBoolean, validateFunction, validateUndefined, validateString } from "./util.mjs";
// eslint-disable-next-line spaced-comment
const kEmptyObject = /*#__PURE__*/ Object.freeze(/*#__PURE__*/ Object.create(null));
const kExitCode = Symbol('kExitCode');
const kSetMemory = Symbol('kSetMemory');
const kStarted = Symbol('kStarted');
const kInstance = Symbol('kInstance');
const kBindingName = Symbol('kBindingName');
function validateOptions(options) {
var _a;
validateObject(options, 'options');
let _WASI;
if (options.version !== undefined) {
validateString(options.version, 'options.version');
switch (options.version) {
case 'unstable':
_WASI = WASIPreview1;
this[kBindingName] = 'wasi_unstable';
break;
case 'preview1':
_WASI = WASIPreview1;
this[kBindingName] = 'wasi_snapshot_preview1';
break;
default:
throw new TypeError(`unsupported WASI version "${options.version}"`);
}
}
else {
_WASI = WASIPreview1;
this[kBindingName] = 'wasi_snapshot_preview1';
}
if (options.args !== undefined) {
validateArray(options.args, 'options.args');
}
const args = ((_a = options.args) !== null && _a !== void 0 ? _a : []).map(String);
const env = [];
if (options.env !== undefined) {
validateObject(options.env, 'options.env');
Object.entries(options.env).forEach(({ 0: key, 1: value }) => {
if (value !== undefined) {
env.push(`${key}=${value}`);
}
});
}
const preopens = [];
if (options.preopens !== undefined) {
validateObject(options.preopens, 'options.preopens');
Object.entries(options.preopens).forEach(({ 0: key, 1: value }) => preopens.push({ mappedPath: String(key), realPath: String(value) }));
}
if (preopens.length > 0) {
if (options.fs === undefined) {
throw new Error('filesystem is disabled, can not preopen directory');
}
try {
validateObject(options.fs, 'options.fs');
}
catch (_) {
throw new TypeError('Node.js fs like implementation is not provided');
}
}
// if (options.filesystem !== undefined) {
// validateObject(options.filesystem, 'options.filesystem')
// validateString(options.filesystem.type, 'options.filesystem.type')
// if (options.filesystem.type !== 'memfs' && options.filesystem.type !== 'file-system-access-api') {
// throw new Error(`Filesystem type ${(options.filesystem as any).type as string} is not supported, only "memfs" and "file-system-access-api" is supported currently`)
// }
// try {
// validateObject(options.filesystem.fs, 'options.filesystem.fs')
// } catch (_) {
// throw new Error('Node.js fs like implementation is not provided')
// }
// }
if (options.print !== undefined)
validateFunction(options.print, 'options.print');
if (options.printErr !== undefined)
validateFunction(options.printErr, 'options.printErr');
if (options.returnOnExit !== undefined) {
validateBoolean(options.returnOnExit, 'options.returnOnExit');
}
// const { stdin = 0, stdout = 1, stderr = 2 } = options
// validateInt32(stdin, 'options.stdin', 0)
// validateInt32(stdout, 'options.stdout', 0)
// validateInt32(stderr, 'options.stderr', 0)
// const stdio = [stdin, stdout, stderr] as const
const stdio = [0, 1, 2];
return {
args,
env,
preopens,
stdio,
_WASI
};
}
function initWASI(setMemory, wrap) {
this[kSetMemory] = setMemory;
this.wasiImport = wrap;
this[kStarted] = false;
this[kExitCode] = 0;
this[kInstance] = undefined;
}
/** @public */
export class WASI {
constructor(options = kEmptyObject) {
const { args, env, preopens, stdio, _WASI } = validateOptions.call(this, options);
const wrap = _WASI.createSync(args, env, preopens, stdio, options.fs, options.print, options.printErr);
const setMemory = wrap._setMemory;
delete wrap._setMemory;
initWASI.call(this, setMemory, wrap);
if (options.returnOnExit) {
wrap.proc_exit = wasiReturnOnProcExit.bind(this);
}
}
finalizeBindings(instance, _a) {
var _b;
var { memory = (_b = instance === null || instance === void 0 ? void 0 : instance.exports) === null || _b === void 0 ? void 0 : _b.memory } = _a === void 0 ? {} : _a;
if (this[kStarted]) {
throw new Error('WASI instance has already started');
}
validateObject(instance, 'instance');
validateObject(instance.exports, 'instance.exports');
this[kSetMemory](memory);
this[kInstance] = instance;
this[kStarted] = true;
}
// Must not export _initialize, must export _start
start(instance) {
this.finalizeBindings(instance);
const { _start, _initialize } = this[kInstance].exports;
validateFunction(_start, 'instance.exports._start');
validateUndefined(_initialize, 'instance.exports._initialize');
let ret;
try {
ret = _start();
}
catch (err) {
if (err !== kExitCode) {
throw err;
}
}
if (ret instanceof Promise) {
return ret.then(() => this[kExitCode], (err) => {
if (err !== kExitCode) {
throw err;
}
return this[kExitCode];
});
}
return this[kExitCode];
}
// Must not export _start, may optionally export _initialize
initialize(instance) {
this.finalizeBindings(instance);
const { _start, _initialize } = this[kInstance].exports;
validateUndefined(_start, 'instance.exports._start');
if (_initialize !== undefined) {
validateFunction(_initialize, 'instance.exports._initialize');
return _initialize();
}
}
getImportObject() {
return { [this[kBindingName]]: this.wasiImport };
}
}
function wasiReturnOnProcExit(rval) {
this[kExitCode] = rval;
// eslint-disable-next-line @typescript-eslint/no-throw-literal
throw kExitCode;
}
/** @public */
export async function createAsyncWASI(options = kEmptyObject) {
const _this = Object.create(WASI.prototype);
const { args, env, preopens, stdio, _WASI } = validateOptions.call(_this, options);
if (options.asyncify !== undefined) {
validateObject(options.asyncify, 'options.asyncify');
validateFunction(options.asyncify.wrapImportFunction, 'options.asyncify.wrapImportFunction');
}
const wrap = await _WASI.createAsync(args, env, preopens, stdio, options.fs, options.print, options.printErr, options.asyncify);
const setMemory = wrap._setMemory;
delete wrap._setMemory;
initWASI.call(_this, setMemory, wrap);
if (options.returnOnExit) {
wrap.proc_exit = wasiReturnOnProcExit.bind(_this);
}
return _this;
}

View File

@@ -0,0 +1,310 @@
import { validateString } from "./util.mjs";
const CHAR_DOT = 46; /* . */
const CHAR_FORWARD_SLASH = 47; /* / */
const CHAR_BACKWARD_SLASH = 92; /* \ */
const CHAR_COLON = 58; /* : */
const CHAR_UPPERCASE_A = 65; /* A */
const CHAR_UPPERCASE_Z = 90; /* Z */
const CHAR_LOWERCASE_A = 97; /* a */
const CHAR_LOWERCASE_Z = 122; /* z */
function isPathSeparatorWin(code) {
return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
}
function isWindowsDeviceRoot(code) {
return (code >= CHAR_UPPERCASE_A && code <= CHAR_UPPERCASE_Z) ||
(code >= CHAR_LOWERCASE_A && code <= CHAR_LOWERCASE_Z);
}
const _isWin32 = typeof process !== 'undefined' && process.platform === 'win32';
/**
* Windows variant of `resolve()`. Mirrors Node's `path.win32.resolve`
* semantics enough for the WASI shim's needs (drive-letter absolutes
* + UNC paths + per-drive cwd lookups via `process.env`/`process.cwd`).
*
* Why this is needed: on Windows, `FileDescriptor.realPath` is the
* host realpath returned by `fs.realpathSync(realPath, 'utf8')` — the
* backslash form `D:\…`. The POSIX-only `resolveImpl` below only
* treats `/` as a separator, reads `D` as non-`/`, decides realPath
* is "relative", and produces a garbage joined path. Downstream
* `fs.openSync(garbage)` then returns `EINVAL` and the WASI caller
* sees a permanent failure. This function gives us the correct
* Windows-style resolution without taking a Node-only `path` import
* (which would break browser bundles of this package).
*
* Cribbed from Node's `lib/path.js` `win32.resolve()` (MIT-licensed),
* trimmed to what WASI realpath resolution actually exercises.
*/
function resolveWin32(args) {
let resolvedDevice = '';
let resolvedTail = '';
let resolvedAbsolute = false;
for (let i = args.length - 1; i >= -1; i--) {
let path;
if (i >= 0) {
path = args[i];
validateString(path, 'path');
if (path.length === 0)
continue;
}
else if (resolvedDevice.length === 0) {
path = (typeof process !== 'undefined' && typeof process.cwd === 'function')
? process.cwd()
: '';
}
else {
// Look up per-drive cwd via the `=X:` env var convention; fall back
// to the global cwd if absent.
const envKey = `=${resolvedDevice}`;
const env = (typeof process !== 'undefined') ? process.env : undefined;
path = (env && typeof env[envKey] === 'string')
? env[envKey]
: (typeof process !== 'undefined' && typeof process.cwd === 'function')
? process.cwd()
: '';
if (path === undefined ||
(path.slice(0, 2).toLowerCase() !== resolvedDevice.toLowerCase() &&
path.charCodeAt(2) === CHAR_BACKWARD_SLASH)) {
path = `${resolvedDevice}\\`;
}
}
const len = path.length;
let rootEnd = 0;
let device = '';
let isAbsolute = false;
const code = path.charCodeAt(0);
if (len === 1) {
if (isPathSeparatorWin(code)) {
rootEnd = 1;
isAbsolute = true;
}
}
else if (isPathSeparatorWin(code)) {
isAbsolute = true;
if (isPathSeparatorWin(path.charCodeAt(1))) {
// UNC path: `\\server\share\…`
let j = 2;
let last = j;
while (j < len && !isPathSeparatorWin(path.charCodeAt(j)))
j++;
if (j < len && j !== last) {
const firstPart = path.slice(last, j);
last = j;
while (j < len && isPathSeparatorWin(path.charCodeAt(j)))
j++;
if (j < len && j !== last) {
last = j;
while (j < len && !isPathSeparatorWin(path.charCodeAt(j)))
j++;
if (j === len || j !== last) {
device = `\\\\${firstPart}\\${path.slice(last, j)}`;
rootEnd = j;
}
}
}
}
else {
rootEnd = 1;
}
}
else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) {
device = path.slice(0, 2);
rootEnd = 2;
if (len > 2 && isPathSeparatorWin(path.charCodeAt(2))) {
isAbsolute = true;
rootEnd = 3;
}
}
if (device.length > 0) {
if (resolvedDevice.length > 0) {
if (device.toLowerCase() !== resolvedDevice.toLowerCase())
continue;
}
else {
resolvedDevice = device;
}
}
if (resolvedAbsolute) {
if (resolvedDevice.length > 0)
break;
}
else {
resolvedTail = `${path.slice(rootEnd)}\\${resolvedTail}`;
resolvedAbsolute = isAbsolute;
if (isAbsolute && resolvedDevice.length > 0)
break;
}
}
resolvedTail = normalizeString(resolvedTail, !resolvedAbsolute, '\\', isPathSeparatorWin);
return resolvedDevice + (resolvedAbsolute ? '\\' : '') + resolvedTail || '.';
}
function isPosixPathSeparator(code) {
return code === CHAR_FORWARD_SLASH;
}
function normalizeString(path, allowAboveRoot, separator, isPathSeparator) {
let res = '';
let lastSegmentLength = 0;
let lastSlash = -1;
let dots = 0;
let code = 0;
for (let i = 0; i <= path.length; ++i) {
if (i < path.length) {
code = path.charCodeAt(i);
}
else if (isPathSeparator(code)) {
break;
}
else {
code = CHAR_FORWARD_SLASH;
}
if (isPathSeparator(code)) {
if (lastSlash === i - 1 || dots === 1) {
// NOOP
}
else if (dots === 2) {
if (res.length < 2 || lastSegmentLength !== 2 ||
res.charCodeAt(res.length - 1) !== CHAR_DOT ||
res.charCodeAt(res.length - 2) !== CHAR_DOT) {
if (res.length > 2) {
const lastSlashIndex = res.indexOf(separator);
if (lastSlashIndex === -1) {
res = '';
lastSegmentLength = 0;
}
else {
res = res.slice(0, lastSlashIndex);
lastSegmentLength =
res.length - 1 - res.indexOf(separator);
}
lastSlash = i;
dots = 0;
continue;
}
else if (res.length !== 0) {
res = '';
lastSegmentLength = 0;
lastSlash = i;
dots = 0;
continue;
}
}
if (allowAboveRoot) {
res += res.length > 0 ? `${separator}..` : '..';
lastSegmentLength = 2;
}
}
else {
if (res.length > 0) {
res += `${separator}${path.slice(lastSlash + 1, i)}`;
}
else {
res = path.slice(lastSlash + 1, i);
}
lastSegmentLength = i - lastSlash - 1;
}
lastSlash = i;
dots = 0;
}
else if (code === CHAR_DOT && dots !== -1) {
++dots;
}
else {
dots = -1;
}
}
return res;
}
export function resolve(...args) {
// On Windows, host paths are `D:\…` style. The POSIX-only resolver
// below treats `D` as a non-`/` character and produces garbage; route
// to the Windows-aware variant. POSIX hosts (Linux/macOS/browser)
// run the original code path unchanged — `_isWin32` is constant-folded
// away on those targets.
if (_isWin32)
return resolveWin32(args);
let resolvedPath = '';
let resolvedAbsolute = false;
for (let i = args.length - 1; i >= -1 && !resolvedAbsolute; i--) {
const path = i >= 0 ? args[i] : '/';
validateString(path, 'path');
// Skip empty entries
if (path.length === 0) {
continue;
}
resolvedPath = `${path}/${resolvedPath}`;
resolvedAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH;
}
// At this point the path should be resolved to a full absolute path, but
// handle relative paths to be safe (might happen when process.cwd() fails)
// Normalize the path
resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute, '/', isPosixPathSeparator);
if (resolvedAbsolute) {
return `/${resolvedPath}`;
}
return resolvedPath.length > 0 ? resolvedPath : '.';
}
export function relative(from, to) {
validateString(from, 'from');
validateString(to, 'to');
if (from === to)
return '';
// Trim leading forward slashes.
from = resolve(from);
to = resolve(to);
if (from === to)
return '';
const fromStart = 1;
const fromEnd = from.length;
const fromLen = fromEnd - fromStart;
const toStart = 1;
const toLen = to.length - toStart;
// Compare paths to find the longest common path from root
const length = (fromLen < toLen ? fromLen : toLen);
let lastCommonSep = -1;
let i = 0;
for (; i < length; i++) {
const fromCode = from.charCodeAt(fromStart + i);
if (fromCode !== to.charCodeAt(toStart + i)) {
break;
}
else if (fromCode === CHAR_FORWARD_SLASH) {
lastCommonSep = i;
}
}
if (i === length) {
if (toLen > length) {
if (to.charCodeAt(toStart + i) === CHAR_FORWARD_SLASH) {
// We get here if `from` is the exact base path for `to`.
// For example: from='/foo/bar'; to='/foo/bar/baz'
return to.slice(toStart + i + 1);
}
if (i === 0) {
// We get here if `from` is the root
// For example: from='/'; to='/foo'
return to.slice(toStart + i);
}
}
else if (fromLen > length) {
if (from.charCodeAt(fromStart + i) === CHAR_FORWARD_SLASH) {
// We get here if `to` is the exact base path for `from`.
// For example: from='/foo/bar/baz'; to='/foo/bar'
lastCommonSep = i;
}
else if (i === 0) {
// We get here if `to` is the root.
// For example: from='/foo/bar'; to='/'
lastCommonSep = 0;
}
}
}
let out = '';
// Generate the relative path based on the path difference between `to`
// and `from`.
for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {
if (i === fromEnd ||
from.charCodeAt(i) === CHAR_FORWARD_SLASH) {
out += out.length === 0 ? '..' : '/..';
}
}
// Lastly, append the rest of the destination (`to`) path that comes after
// the common path parts.
return `${out}${to.slice(toStart + lastCommonSep)}`;
}

File diff suppressed because it is too large Load Diff

Some files were not shown because too many files have changed in this diff Show More