2024-01-01 14:58:21 -05:00
|
|
|
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
|
2023-02-14 11:38:45 -05:00
|
|
|
// Copyright Joyent and Node contributors. All rights reserved. MIT license.
|
2024-04-03 15:37:10 -04:00
|
|
|
// This code has been inspired by https://github.com/bevry/domain-browser/commit/8bce7f4a093966ca850da75b024239ad5d0b33c6
|
2023-02-14 11:38:45 -05:00
|
|
|
|
2024-04-03 15:37:10 -04:00
|
|
|
import { primordials } from "ext:core/mod.js";
|
|
|
|
const {
|
|
|
|
ArrayPrototypeSlice,
|
|
|
|
FunctionPrototypeBind,
|
|
|
|
FunctionPrototypeCall,
|
|
|
|
FunctionPrototypeApply,
|
|
|
|
} = primordials;
|
|
|
|
import { EventEmitter } from "node:events";
|
|
|
|
|
|
|
|
function emitError(e) {
|
|
|
|
this.emit("error", e);
|
|
|
|
}
|
2023-02-14 11:38:45 -05:00
|
|
|
|
|
|
|
export function create() {
|
2024-04-03 15:37:10 -04:00
|
|
|
return new Domain();
|
2023-02-14 11:38:45 -05:00
|
|
|
}
|
2024-04-03 15:37:10 -04:00
|
|
|
export class Domain extends EventEmitter {
|
|
|
|
#handler;
|
|
|
|
|
2023-02-14 11:38:45 -05:00
|
|
|
constructor() {
|
2024-04-03 15:37:10 -04:00
|
|
|
super();
|
|
|
|
this.#handler = FunctionPrototypeBind(emitError, this);
|
|
|
|
}
|
|
|
|
|
|
|
|
add(emitter) {
|
|
|
|
emitter.on("error", this.#handler);
|
|
|
|
}
|
|
|
|
|
|
|
|
remove(emitter) {
|
|
|
|
emitter.off("error", this.#handler);
|
|
|
|
}
|
|
|
|
|
|
|
|
bind(fn) {
|
|
|
|
// deno-lint-ignore no-this-alias
|
|
|
|
const self = this;
|
|
|
|
return function () {
|
|
|
|
try {
|
|
|
|
FunctionPrototypeApply(fn, null, ArrayPrototypeSlice(arguments));
|
|
|
|
} catch (e) {
|
|
|
|
FunctionPrototypeCall(emitError, self, e);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
intercept(fn) {
|
|
|
|
// deno-lint-ignore no-this-alias
|
|
|
|
const self = this;
|
|
|
|
return function (e) {
|
|
|
|
if (e) {
|
|
|
|
FunctionPrototypeCall(emitError, self, e);
|
|
|
|
} else {
|
|
|
|
try {
|
|
|
|
FunctionPrototypeApply(fn, null, ArrayPrototypeSlice(arguments, 1));
|
|
|
|
} catch (e) {
|
|
|
|
FunctionPrototypeCall(emitError, self, e);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
run(fn) {
|
|
|
|
try {
|
|
|
|
fn();
|
|
|
|
} catch (e) {
|
|
|
|
FunctionPrototypeCall(emitError, this, e);
|
|
|
|
}
|
|
|
|
return this;
|
|
|
|
}
|
|
|
|
|
|
|
|
dispose() {
|
|
|
|
this.removeAllListeners();
|
|
|
|
return this;
|
|
|
|
}
|
|
|
|
|
|
|
|
enter() {
|
|
|
|
return this;
|
|
|
|
}
|
|
|
|
|
|
|
|
exit() {
|
|
|
|
return this;
|
2023-02-14 11:38:45 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
export default {
|
|
|
|
create,
|
|
|
|
Domain,
|
|
|
|
};
|