@rstest/core 0.7.0 → 0.7.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE.md +1 -1
- package/dist/0~122.js +53 -23
- package/dist/0~151.js +303 -264
- package/dist/0~173.js +7 -2
- package/dist/0~346.js +46 -0
- package/dist/0~583.js +1 -1
- package/dist/0~588.js +1 -1
- package/dist/0~62.js +1 -1
- package/dist/0~634.js +3 -3
- package/dist/0~809.js +1 -1
- package/dist/0~835.js +143 -0
- package/dist/0~919.js +65 -33
- package/dist/0~923.js +149 -0
- package/dist/{155.js → 131.js} +14 -12
- package/dist/404.js +210 -0
- package/dist/{362.js → 554.js} +85 -233
- package/dist/734.js +1 -1
- package/dist/946.js +40 -30
- package/dist/index.d.ts +52 -18
- package/dist/index.js +1 -1
- package/dist/worker.d.ts +56 -24
- package/dist/worker.js +1 -1
- package/package.json +7 -6
- package/dist/770.js +0 -167
- /package/dist/{0~454.js → 0~907.js} +0 -0
- /package/dist/{362.js.LICENSE.txt → 554.js.LICENSE.txt} +0 -0
package/dist/0~923.js
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
import 'module';
|
|
2
|
+
/*#__PURE__*/ import.meta.url;
|
|
3
|
+
import { __webpack_require__ } from "./rslib-runtime.js";
|
|
4
|
+
import { posix, src_logger } from "./946.js";
|
|
5
|
+
import { pathToFileURL } from "./404.js";
|
|
6
|
+
import { node_vm, interopModule, shouldInterop } from "./0~346.js";
|
|
7
|
+
const external_node_path_ = __webpack_require__("node:path");
|
|
8
|
+
var loadEsModule_EsmMode = /*#__PURE__*/ function(EsmMode) {
|
|
9
|
+
EsmMode[EsmMode["Unknown"] = 0] = "Unknown";
|
|
10
|
+
EsmMode[EsmMode["Evaluated"] = 1] = "Evaluated";
|
|
11
|
+
EsmMode[EsmMode["Unlinked"] = 2] = "Unlinked";
|
|
12
|
+
return EsmMode;
|
|
13
|
+
}({});
|
|
14
|
+
const isRelativePath = (p)=>/^\.\.?\//.test(p);
|
|
15
|
+
const defineRstestDynamicImport = ({ distPath, testPath, assetFiles, interopDefault, returnModule, esmMode })=>async (specifier, importAttributes)=>{
|
|
16
|
+
const currentDirectory = posix.dirname(distPath);
|
|
17
|
+
const joinedPath = isRelativePath(specifier) ? posix.join(currentDirectory, specifier) : specifier;
|
|
18
|
+
const content = assetFiles[joinedPath];
|
|
19
|
+
if (content) try {
|
|
20
|
+
return await loadModule({
|
|
21
|
+
codeContent: content,
|
|
22
|
+
testPath,
|
|
23
|
+
distPath: joinedPath,
|
|
24
|
+
rstestContext: {},
|
|
25
|
+
assetFiles,
|
|
26
|
+
interopDefault,
|
|
27
|
+
esmMode
|
|
28
|
+
});
|
|
29
|
+
} catch (err) {
|
|
30
|
+
src_logger.error(`load file ${joinedPath} failed:\n`, err instanceof Error ? err.message : err);
|
|
31
|
+
}
|
|
32
|
+
const resolvedPath = (0, external_node_path_.isAbsolute)(specifier) ? pathToFileURL(specifier) : import.meta.resolve(specifier, pathToFileURL(testPath));
|
|
33
|
+
const modulePath = 'string' == typeof resolvedPath ? resolvedPath : resolvedPath.pathname;
|
|
34
|
+
if (importAttributes?.with?.rstest) delete importAttributes.with.rstest;
|
|
35
|
+
if (modulePath.endsWith('.json')) {
|
|
36
|
+
const importedModule = await import(modulePath, {
|
|
37
|
+
with: {
|
|
38
|
+
type: 'json'
|
|
39
|
+
}
|
|
40
|
+
});
|
|
41
|
+
return returnModule ? asModule(importedModule.default) : {
|
|
42
|
+
...importedModule.default,
|
|
43
|
+
default: importedModule.default
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
const importedModule = await import(modulePath, importAttributes);
|
|
47
|
+
if (shouldInterop({
|
|
48
|
+
interopDefault,
|
|
49
|
+
modulePath,
|
|
50
|
+
mod: importedModule
|
|
51
|
+
}) && !modulePath.startsWith('node:')) {
|
|
52
|
+
const { mod, defaultExport } = interopModule(importedModule);
|
|
53
|
+
if (returnModule) return asModule(mod);
|
|
54
|
+
return new Proxy(mod, {
|
|
55
|
+
get (mod, prop) {
|
|
56
|
+
if ('default' === prop) return defaultExport;
|
|
57
|
+
return mod[prop] ?? defaultExport?.[prop];
|
|
58
|
+
},
|
|
59
|
+
has (mod, prop) {
|
|
60
|
+
if ('default' === prop) return void 0 !== defaultExport;
|
|
61
|
+
return prop in mod || defaultExport && prop in defaultExport;
|
|
62
|
+
},
|
|
63
|
+
getOwnPropertyDescriptor (mod, prop) {
|
|
64
|
+
const descriptor = Reflect.getOwnPropertyDescriptor(mod, prop);
|
|
65
|
+
if (descriptor) return descriptor;
|
|
66
|
+
if ('default' === prop && void 0 !== defaultExport) return {
|
|
67
|
+
value: defaultExport,
|
|
68
|
+
enumerable: true,
|
|
69
|
+
configurable: true
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
return importedModule;
|
|
75
|
+
};
|
|
76
|
+
const asModule = async (something, context, unlinked)=>{
|
|
77
|
+
const { Module, SyntheticModule } = await import("node:vm");
|
|
78
|
+
if (something instanceof Module) return something;
|
|
79
|
+
const exports = [
|
|
80
|
+
...new Set([
|
|
81
|
+
'default',
|
|
82
|
+
...Object.keys(something)
|
|
83
|
+
])
|
|
84
|
+
];
|
|
85
|
+
const syntheticModule = new SyntheticModule(exports, ()=>{
|
|
86
|
+
for (const name of exports)syntheticModule.setExport(name, 'default' === name ? something[name] ?? something : something[name]);
|
|
87
|
+
}, {
|
|
88
|
+
context
|
|
89
|
+
});
|
|
90
|
+
if (unlinked) return syntheticModule;
|
|
91
|
+
await syntheticModule.link(()=>{});
|
|
92
|
+
await syntheticModule.evaluate();
|
|
93
|
+
return syntheticModule;
|
|
94
|
+
};
|
|
95
|
+
const esmCache = new Map();
|
|
96
|
+
const loadModule = async ({ codeContent, distPath, testPath, assetFiles, interopDefault, esmMode = 0 })=>{
|
|
97
|
+
const code = codeContent;
|
|
98
|
+
let esm = esmCache.get(distPath);
|
|
99
|
+
if (!esm) {
|
|
100
|
+
esm = new node_vm.SourceTextModule(code, {
|
|
101
|
+
identifier: distPath,
|
|
102
|
+
lineOffset: 0,
|
|
103
|
+
columnOffset: 0,
|
|
104
|
+
initializeImportMeta: (meta)=>{
|
|
105
|
+
meta.url = pathToFileURL(distPath.endsWith('rstest-runtime.mjs') ? distPath : testPath).toString();
|
|
106
|
+
meta.__rstest_dynamic_import__ = defineRstestDynamicImport({
|
|
107
|
+
assetFiles,
|
|
108
|
+
testPath,
|
|
109
|
+
distPath: distPath || testPath,
|
|
110
|
+
interopDefault,
|
|
111
|
+
returnModule: false,
|
|
112
|
+
esmMode: 0
|
|
113
|
+
});
|
|
114
|
+
meta.readWasmFile = (wasmPath, callback)=>{
|
|
115
|
+
const joinedPath = isRelativePath(wasmPath.pathname) ? posix.join(posix.dirname(distPath), wasmPath.pathname) : wasmPath.pathname;
|
|
116
|
+
const content = assetFiles[posix.normalize(joinedPath)];
|
|
117
|
+
if (content) callback(null, Buffer.from(content, 'base64'));
|
|
118
|
+
else callback(new Error(`WASM file ${joinedPath} not found in asset files.`));
|
|
119
|
+
};
|
|
120
|
+
},
|
|
121
|
+
importModuleDynamically: (specifier, _referencer, importAttributes)=>defineRstestDynamicImport({
|
|
122
|
+
assetFiles,
|
|
123
|
+
testPath,
|
|
124
|
+
distPath: distPath || testPath,
|
|
125
|
+
interopDefault,
|
|
126
|
+
returnModule: true,
|
|
127
|
+
esmMode: 2
|
|
128
|
+
})(specifier, importAttributes)
|
|
129
|
+
});
|
|
130
|
+
distPath && esmCache.set(distPath, esm);
|
|
131
|
+
}
|
|
132
|
+
if (2 === esmMode) return esm;
|
|
133
|
+
if ('unlinked' === esm.status) await esm.link(async (specifier, referencingModule)=>{
|
|
134
|
+
const result = await defineRstestDynamicImport({
|
|
135
|
+
assetFiles,
|
|
136
|
+
testPath,
|
|
137
|
+
distPath: distPath || testPath,
|
|
138
|
+
interopDefault,
|
|
139
|
+
returnModule: true,
|
|
140
|
+
esmMode: 2
|
|
141
|
+
})(specifier, referencingModule);
|
|
142
|
+
const linkedModule = await asModule(result, referencingModule.context, true);
|
|
143
|
+
return linkedModule;
|
|
144
|
+
});
|
|
145
|
+
'evaluated' !== esm.status && 'evaluating' !== esm.status && await esm.evaluate();
|
|
146
|
+
const ns = esm.namespace;
|
|
147
|
+
return ns.default && ns.default instanceof Promise ? ns.default : ns;
|
|
148
|
+
};
|
|
149
|
+
export { asModule, loadEsModule_EsmMode, loadModule };
|
package/dist/{155.js → 131.js}
RENAMED
|
@@ -2,8 +2,8 @@ import 'module';
|
|
|
2
2
|
/*#__PURE__*/ import.meta.url;
|
|
3
3
|
import { __webpack_require__ } from "./rslib-runtime.js";
|
|
4
4
|
import { EventEmitter } from "events";
|
|
5
|
-
import { createRsbuild, loadConfig, logger, mergeRsbuildConfig } from "@rsbuild/core";
|
|
6
|
-
import {
|
|
5
|
+
import { createRsbuild, loadConfig, logger as core_logger, mergeRsbuildConfig } from "@rsbuild/core";
|
|
6
|
+
import { DEFAULT_CONFIG_NAME, posix, globalApis, resolve as pathe_M_eThtNZ_resolve, pathe_M_eThtNZ_relative, filterProjects, join, glob, prettyTestPath, prettyTime, isAbsolute, TEMP_RSTEST_OUTPUT_DIR_GLOB, formatTestPath, TS_CONFIG_FILE, basename, isTTY, dirname, getAbsolutePath, bgColor, formatRootStr, isDynamicPattern, writeFile, castArray, src_logger, isDebug, getTaskNameWithPrefix, DEFAULT_CONFIG_EXTENSIONS, formatError, normalize } from "./946.js";
|
|
7
7
|
import { decode } from "./397.js";
|
|
8
8
|
function toArr(any) {
|
|
9
9
|
return null == any ? [] : Array.isArray(any) ? any : [
|
|
@@ -500,7 +500,7 @@ function prepareCli() {
|
|
|
500
500
|
if (!npm_execpath || npm_execpath.includes('npx-cli.js') || npm_execpath.includes('.bun')) console.log();
|
|
501
501
|
}
|
|
502
502
|
function showRstest() {
|
|
503
|
-
src_logger.greet(" Rstest v0.7.
|
|
503
|
+
src_logger.greet(" Rstest v0.7.2");
|
|
504
504
|
src_logger.log('');
|
|
505
505
|
}
|
|
506
506
|
const applyCommonOptions = (cli)=>{
|
|
@@ -544,7 +544,7 @@ const runRest = async ({ options, filters, command })=>{
|
|
|
544
544
|
function setupCommands() {
|
|
545
545
|
const cli = dist('rstest');
|
|
546
546
|
cli.help();
|
|
547
|
-
cli.version("0.7.
|
|
547
|
+
cli.version("0.7.2");
|
|
548
548
|
applyCommonOptions(cli);
|
|
549
549
|
cli.command('[...filters]', 'run tests').option('-w, --watch', 'Run tests in watch mode').action(async (filters, options)=>{
|
|
550
550
|
showRstest();
|
|
@@ -1443,7 +1443,7 @@ const printSummaryErrorLogs = async ({ testResults, results, rootPath, getSource
|
|
|
1443
1443
|
for (const test of failedTests){
|
|
1444
1444
|
const relativePath = posix.relative(rootPath, test.testPath);
|
|
1445
1445
|
const nameStr = getTaskNameWithPrefix(test);
|
|
1446
|
-
src_logger.log(`${
|
|
1446
|
+
src_logger.log(`${bgColor('bgRed', ' FAIL ')} ${prettyTestPath(relativePath)} ${nameStr.length ? `${picocolors_default().dim(">")} ${nameStr}` : ''}`);
|
|
1447
1447
|
if (test.errors) {
|
|
1448
1448
|
const { printError } = await Promise.resolve().then(()=>({
|
|
1449
1449
|
printError: error_printError
|
|
@@ -1575,11 +1575,11 @@ class StatusRenderer {
|
|
|
1575
1575
|
renderer;
|
|
1576
1576
|
startTime = void 0;
|
|
1577
1577
|
testState;
|
|
1578
|
-
constructor(rootPath, state){
|
|
1578
|
+
constructor(rootPath, state, logger){
|
|
1579
1579
|
this.rootPath = rootPath;
|
|
1580
1580
|
this.renderer = new WindowRenderer({
|
|
1581
1581
|
getWindow: ()=>this.getContent(),
|
|
1582
|
-
logger: {
|
|
1582
|
+
logger: logger ?? {
|
|
1583
1583
|
outputStream: process.stdout,
|
|
1584
1584
|
errorStream: process.stderr,
|
|
1585
1585
|
getColumns: ()=>'columns' in process.stdout ? process.stdout.columns : 80
|
|
@@ -1596,7 +1596,7 @@ class StatusRenderer {
|
|
|
1596
1596
|
const shouldDisplayRunningTests = (runningTests)=>runningTests[0]?.startTime && now - runningTests[0].startTime > 2000;
|
|
1597
1597
|
for (const [module, { runningTests }] of runningModules.entries()){
|
|
1598
1598
|
const relativePath = pathe_M_eThtNZ_relative(this.rootPath, module);
|
|
1599
|
-
summary.push(`${
|
|
1599
|
+
summary.push(`${bgColor('bgYellow', ' RUNS ')} ${prettyTestPath(relativePath)}`);
|
|
1600
1600
|
if (runningTests.length && shouldDisplayRunningTests(runningTests)) {
|
|
1601
1601
|
let caseLog = ` ${picocolors_default().gray("➜")} ${getTaskNameWithPrefix(runningTests[0])} ${picocolors_default().magenta(prettyTime(now - runningTests[0].startTime))}`;
|
|
1602
1602
|
if (runningTests.length > 1) caseLog += picocolors_default().gray(` and ${runningTests.length - 1} more cases`);
|
|
@@ -1667,7 +1667,7 @@ class DefaultReporter {
|
|
|
1667
1667
|
this.rootPath = rootPath;
|
|
1668
1668
|
this.config = config;
|
|
1669
1669
|
this.options = options;
|
|
1670
|
-
if (isTTY()) this.statusRenderer = new StatusRenderer(rootPath, testState);
|
|
1670
|
+
if (isTTY() || options.logger) this.statusRenderer = new StatusRenderer(rootPath, testState, options.logger);
|
|
1671
1671
|
}
|
|
1672
1672
|
onTestFileStart() {
|
|
1673
1673
|
this.statusRenderer?.onTestFileStart();
|
|
@@ -2175,7 +2175,7 @@ const stackIgnores = [
|
|
|
2175
2175
|
];
|
|
2176
2176
|
async function error_parseErrorStacktrace({ stack, getSourcemap, fullStack = isDebug() }) {
|
|
2177
2177
|
const stackFrames = await Promise.all(stack_trace_parser_esm_parse(stack).filter((frame)=>fullStack ? true : frame.file && !stackIgnores.some((entry)=>frame.file?.match(entry))).map(async (frame)=>{
|
|
2178
|
-
const sourcemap = await getSourcemap(frame.file);
|
|
2178
|
+
const sourcemap = await getSourcemap?.(frame.file);
|
|
2179
2179
|
if (sourcemap) {
|
|
2180
2180
|
const traceMap = new TraceMap(sourcemap);
|
|
2181
2181
|
const { line, column, source, name } = originalPositionFor(traceMap, {
|
|
@@ -2428,7 +2428,7 @@ class Rstest {
|
|
|
2428
2428
|
});
|
|
2429
2429
|
this.reporters = reporters;
|
|
2430
2430
|
this.snapshotManager = snapshotManager;
|
|
2431
|
-
this.version = "0.7.
|
|
2431
|
+
this.version = "0.7.2";
|
|
2432
2432
|
this.rootPath = rootPath;
|
|
2433
2433
|
this.originalConfig = userConfig;
|
|
2434
2434
|
this.normalizedConfig = rstestConfig;
|
|
@@ -2448,6 +2448,7 @@ class Rstest {
|
|
|
2448
2448
|
configFilePath: project.configFilePath,
|
|
2449
2449
|
rootPath: config.root,
|
|
2450
2450
|
name: config.name,
|
|
2451
|
+
outputModule: config.output?.module ?? 'true' === process.env.RSTEST_OUTPUT_MODULE,
|
|
2451
2452
|
environmentName: formatEnvironmentName(config.name),
|
|
2452
2453
|
normalizedConfig: config
|
|
2453
2454
|
};
|
|
@@ -2456,6 +2457,7 @@ class Rstest {
|
|
|
2456
2457
|
configFilePath,
|
|
2457
2458
|
rootPath,
|
|
2458
2459
|
name: rstestConfig.name,
|
|
2460
|
+
outputModule: rstestConfig.output?.module ?? 'true' === process.env.RSTEST_OUTPUT_MODULE,
|
|
2459
2461
|
environmentName: formatEnvironmentName(rstestConfig.name),
|
|
2460
2462
|
normalizedConfig: rstestConfig
|
|
2461
2463
|
}
|
|
@@ -2569,4 +2571,4 @@ function defineConfig(config) {
|
|
|
2569
2571
|
function defineProject(config) {
|
|
2570
2572
|
return config;
|
|
2571
2573
|
}
|
|
2572
|
-
export { EventEmitter, afterAll, afterEach, assert, beforeAll, beforeEach, config_loadConfig as loadConfig, core_createRstest as createRstest, createRsbuild, defineConfig, defineProject, describe, error_printError, expect, init_initCli as initCli, it,
|
|
2574
|
+
export { EventEmitter, afterAll, afterEach, assert, beforeAll, beforeEach, config_loadConfig as loadConfig, core_createRstest as createRstest, core_logger, createRsbuild, defineConfig, defineProject, describe, error_printError, expect, init_initCli as initCli, it, mergeRstestConfig, onTestFailed, onTestFinished, public_rstest as rstest, public_test as test, rs, runCLI, runRest };
|
package/dist/404.js
ADDED
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
import 'module';
|
|
2
|
+
/*#__PURE__*/ import.meta.url;
|
|
3
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
4
|
+
import node_v8 from "node:v8";
|
|
5
|
+
const TYPE_REQUEST = "q";
|
|
6
|
+
const TYPE_RESPONSE = "s";
|
|
7
|
+
const DEFAULT_TIMEOUT = 6e4;
|
|
8
|
+
function defaultSerialize(i) {
|
|
9
|
+
return i;
|
|
10
|
+
}
|
|
11
|
+
const defaultDeserialize = defaultSerialize;
|
|
12
|
+
const { clearTimeout: dist_clearTimeout, setTimeout: dist_setTimeout } = globalThis;
|
|
13
|
+
const random = Math.random.bind(Math);
|
|
14
|
+
function createBirpc($functions, options) {
|
|
15
|
+
const { post, on, off = ()=>{}, eventNames = [], serialize = defaultSerialize, deserialize = defaultDeserialize, resolver, bind = "rpc", timeout = DEFAULT_TIMEOUT } = options;
|
|
16
|
+
let $closed = false;
|
|
17
|
+
const _rpcPromiseMap = /* @__PURE__ */ new Map();
|
|
18
|
+
let _promiseInit;
|
|
19
|
+
let rpc;
|
|
20
|
+
async function _call(method, args, event, optional) {
|
|
21
|
+
if ($closed) throw new Error(`[birpc] rpc is closed, cannot call "${method}"`);
|
|
22
|
+
const req = {
|
|
23
|
+
m: method,
|
|
24
|
+
a: args,
|
|
25
|
+
t: TYPE_REQUEST
|
|
26
|
+
};
|
|
27
|
+
if (optional) req.o = true;
|
|
28
|
+
const send = async (_req)=>post(serialize(_req));
|
|
29
|
+
if (event) return void await send(req);
|
|
30
|
+
if (_promiseInit) try {
|
|
31
|
+
await _promiseInit;
|
|
32
|
+
} finally{
|
|
33
|
+
_promiseInit = void 0;
|
|
34
|
+
}
|
|
35
|
+
let { promise, resolve, reject } = createPromiseWithResolvers();
|
|
36
|
+
const id = nanoid();
|
|
37
|
+
req.i = id;
|
|
38
|
+
let timeoutId;
|
|
39
|
+
async function handler(newReq = req) {
|
|
40
|
+
if (timeout >= 0) {
|
|
41
|
+
timeoutId = dist_setTimeout(()=>{
|
|
42
|
+
try {
|
|
43
|
+
const handleResult = options.onTimeoutError?.call(rpc, method, args);
|
|
44
|
+
if (true !== handleResult) throw new Error(`[birpc] timeout on calling "${method}"`);
|
|
45
|
+
} catch (e) {
|
|
46
|
+
reject(e);
|
|
47
|
+
}
|
|
48
|
+
_rpcPromiseMap.delete(id);
|
|
49
|
+
}, timeout);
|
|
50
|
+
if ("object" == typeof timeoutId) timeoutId = timeoutId.unref?.();
|
|
51
|
+
}
|
|
52
|
+
_rpcPromiseMap.set(id, {
|
|
53
|
+
resolve,
|
|
54
|
+
reject,
|
|
55
|
+
timeoutId,
|
|
56
|
+
method
|
|
57
|
+
});
|
|
58
|
+
await send(newReq);
|
|
59
|
+
return promise;
|
|
60
|
+
}
|
|
61
|
+
try {
|
|
62
|
+
if (options.onRequest) await options.onRequest.call(rpc, req, handler, resolve);
|
|
63
|
+
else await handler();
|
|
64
|
+
} catch (e) {
|
|
65
|
+
if (options.onGeneralError?.call(rpc, e) !== true) throw e;
|
|
66
|
+
return;
|
|
67
|
+
} finally{
|
|
68
|
+
dist_clearTimeout(timeoutId);
|
|
69
|
+
_rpcPromiseMap.delete(id);
|
|
70
|
+
}
|
|
71
|
+
return promise;
|
|
72
|
+
}
|
|
73
|
+
const $call = (method, ...args)=>_call(method, args, false);
|
|
74
|
+
const $callOptional = (method, ...args)=>_call(method, args, false, true);
|
|
75
|
+
const $callEvent = (method, ...args)=>_call(method, args, true);
|
|
76
|
+
const $callRaw = (options2)=>_call(options2.method, options2.args, options2.event, options2.optional);
|
|
77
|
+
const builtinMethods = {
|
|
78
|
+
$call,
|
|
79
|
+
$callOptional,
|
|
80
|
+
$callEvent,
|
|
81
|
+
$callRaw,
|
|
82
|
+
$rejectPendingCalls,
|
|
83
|
+
get $closed () {
|
|
84
|
+
return $closed;
|
|
85
|
+
},
|
|
86
|
+
get $meta () {
|
|
87
|
+
return options.meta;
|
|
88
|
+
},
|
|
89
|
+
$close,
|
|
90
|
+
$functions
|
|
91
|
+
};
|
|
92
|
+
rpc = new Proxy({}, {
|
|
93
|
+
get (_, method) {
|
|
94
|
+
if (Object.prototype.hasOwnProperty.call(builtinMethods, method)) return builtinMethods[method];
|
|
95
|
+
if ("then" === method && !eventNames.includes("then") && !("then" in $functions)) return;
|
|
96
|
+
const sendEvent = (...args)=>_call(method, args, true);
|
|
97
|
+
if (eventNames.includes(method)) {
|
|
98
|
+
sendEvent.asEvent = sendEvent;
|
|
99
|
+
return sendEvent;
|
|
100
|
+
}
|
|
101
|
+
const sendCall = (...args)=>_call(method, args, false);
|
|
102
|
+
sendCall.asEvent = sendEvent;
|
|
103
|
+
return sendCall;
|
|
104
|
+
}
|
|
105
|
+
});
|
|
106
|
+
function $close(customError) {
|
|
107
|
+
$closed = true;
|
|
108
|
+
_rpcPromiseMap.forEach(({ reject, method })=>{
|
|
109
|
+
const error = new Error(`[birpc] rpc is closed, cannot call "${method}"`);
|
|
110
|
+
if (customError) {
|
|
111
|
+
customError.cause ??= error;
|
|
112
|
+
return reject(customError);
|
|
113
|
+
}
|
|
114
|
+
reject(error);
|
|
115
|
+
});
|
|
116
|
+
_rpcPromiseMap.clear();
|
|
117
|
+
off(onMessage);
|
|
118
|
+
}
|
|
119
|
+
function $rejectPendingCalls(handler) {
|
|
120
|
+
const entries = Array.from(_rpcPromiseMap.values());
|
|
121
|
+
const handlerResults = entries.map(({ method, reject })=>{
|
|
122
|
+
if (!handler) return reject(new Error(`[birpc]: rejected pending call "${method}".`));
|
|
123
|
+
return handler({
|
|
124
|
+
method,
|
|
125
|
+
reject
|
|
126
|
+
});
|
|
127
|
+
});
|
|
128
|
+
_rpcPromiseMap.clear();
|
|
129
|
+
return handlerResults;
|
|
130
|
+
}
|
|
131
|
+
async function onMessage(data, ...extra) {
|
|
132
|
+
let msg;
|
|
133
|
+
try {
|
|
134
|
+
msg = deserialize(data);
|
|
135
|
+
} catch (e) {
|
|
136
|
+
if (options.onGeneralError?.call(rpc, e) !== true) throw e;
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
139
|
+
if (msg.t === TYPE_REQUEST) {
|
|
140
|
+
const { m: method, a: args, o: optional } = msg;
|
|
141
|
+
let result, error;
|
|
142
|
+
let fn = await (resolver ? resolver.call(rpc, method, $functions[method]) : $functions[method]);
|
|
143
|
+
if (optional) fn ||= ()=>void 0;
|
|
144
|
+
if (fn) try {
|
|
145
|
+
result = await fn.apply("rpc" === bind ? rpc : $functions, args);
|
|
146
|
+
} catch (e) {
|
|
147
|
+
error = e;
|
|
148
|
+
}
|
|
149
|
+
else error = new Error(`[birpc] function "${method}" not found`);
|
|
150
|
+
if (msg.i) {
|
|
151
|
+
if (error && options.onError) options.onError.call(rpc, error, method, args);
|
|
152
|
+
if (error && options.onFunctionError) {
|
|
153
|
+
if (true === options.onFunctionError.call(rpc, error, method, args)) return;
|
|
154
|
+
}
|
|
155
|
+
if (!error) try {
|
|
156
|
+
await post(serialize({
|
|
157
|
+
t: TYPE_RESPONSE,
|
|
158
|
+
i: msg.i,
|
|
159
|
+
r: result
|
|
160
|
+
}), ...extra);
|
|
161
|
+
return;
|
|
162
|
+
} catch (e) {
|
|
163
|
+
error = e;
|
|
164
|
+
if (options.onGeneralError?.call(rpc, e, method, args) !== true) throw e;
|
|
165
|
+
}
|
|
166
|
+
try {
|
|
167
|
+
await post(serialize({
|
|
168
|
+
t: TYPE_RESPONSE,
|
|
169
|
+
i: msg.i,
|
|
170
|
+
e: error
|
|
171
|
+
}), ...extra);
|
|
172
|
+
} catch (e) {
|
|
173
|
+
if (options.onGeneralError?.call(rpc, e, method, args) !== true) throw e;
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
} else {
|
|
177
|
+
const { i: ack, r: result, e: error } = msg;
|
|
178
|
+
const promise = _rpcPromiseMap.get(ack);
|
|
179
|
+
if (promise) {
|
|
180
|
+
dist_clearTimeout(promise.timeoutId);
|
|
181
|
+
if (error) promise.reject(error);
|
|
182
|
+
else promise.resolve(result);
|
|
183
|
+
}
|
|
184
|
+
_rpcPromiseMap.delete(ack);
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
_promiseInit = on(onMessage);
|
|
188
|
+
return rpc;
|
|
189
|
+
}
|
|
190
|
+
function createPromiseWithResolvers() {
|
|
191
|
+
let resolve;
|
|
192
|
+
let reject;
|
|
193
|
+
const promise = new Promise((res, rej)=>{
|
|
194
|
+
resolve = res;
|
|
195
|
+
reject = rej;
|
|
196
|
+
});
|
|
197
|
+
return {
|
|
198
|
+
promise,
|
|
199
|
+
resolve,
|
|
200
|
+
reject
|
|
201
|
+
};
|
|
202
|
+
}
|
|
203
|
+
const urlAlphabet = "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";
|
|
204
|
+
function nanoid(size = 21) {
|
|
205
|
+
let id = "";
|
|
206
|
+
let i = size;
|
|
207
|
+
while(i--)id += urlAlphabet[64 * random() | 0];
|
|
208
|
+
return id;
|
|
209
|
+
}
|
|
210
|
+
export { createBirpc, fileURLToPath, node_v8, pathToFileURL };
|