Files
arcrun-rag-bundles-staging/arcrun-code/worker.mjs
T
Leo ea9690692a staging 1.4.17:執行紀錄不再吃 KV 額度(Evan 事故止血)
來源 matrix/arcrun main(60688c3 KV 搬離 + 7ba7855 credential 走 API)。
打包後 grep 複驗(不假設):
  ANALYTICS_KV.put 殘留 = 0   ← 舊行為清乾淨
  execution_log       = 2 處   ← 新行為在 bundle 裡

版本處理:staging manifest 原本沒有 release 欄位,每次重打都從 1.4.0 起算
=> 版本會倒退、安裝器判成不用更新。先對齊 prod 的 1.4.16 再重打 => bump 成 1.4.17。
(這是 stage/prod 又一個漂移,已記入 wiki。)

僅 staging,不影響 prod。
2026-08-07 18:46:14 +08:00

4019 lines
151 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
var __defProp = Object.defineProperty;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __esm = (fn, res, err2) => function __init() {
if (err2) throw err2[0];
try {
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
} catch (e) {
throw err2 = [e], e;
}
};
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
// ../../matrix/arcrun/registry/components/code/node_modules/@jitl/quickjs-ffi-types/dist/index.mjs
var EvalFlags, IntrinsicsFlags, JSPromiseStateEnum, GetOwnPropertyNamesFlags, IsEqualOp;
var init_dist = __esm({
"../../matrix/arcrun/registry/components/code/node_modules/@jitl/quickjs-ffi-types/dist/index.mjs"() {
EvalFlags = { JS_EVAL_TYPE_GLOBAL: 0, JS_EVAL_TYPE_MODULE: 1, JS_EVAL_TYPE_DIRECT: 2, JS_EVAL_TYPE_INDIRECT: 3, JS_EVAL_TYPE_MASK: 3, JS_EVAL_FLAG_STRICT: 8, JS_EVAL_FLAG_STRIP: 16, JS_EVAL_FLAG_COMPILE_ONLY: 32, JS_EVAL_FLAG_BACKTRACE_BARRIER: 64 };
IntrinsicsFlags = { BaseObjects: 1, Date: 2, Eval: 4, StringNormalize: 8, RegExp: 16, RegExpCompiler: 32, JSON: 64, Proxy: 128, MapSet: 256, TypedArrays: 512, Promise: 1024, BigInt: 2048, BigFloat: 4096, BigDecimal: 8192, OperatorOverloading: 16384, BignumExt: 32768 };
JSPromiseStateEnum = { Pending: 0, Fulfilled: 1, Rejected: 2 };
GetOwnPropertyNamesFlags = { JS_GPN_STRING_MASK: 1, JS_GPN_SYMBOL_MASK: 2, JS_GPN_PRIVATE_MASK: 4, JS_GPN_ENUM_ONLY: 16, JS_GPN_SET_ENUM: 32, QTS_GPN_NUMBER_MASK: 64, QTS_STANDARD_COMPLIANT_NUMBER: 128 };
IsEqualOp = { IsStrictlyEqual: 0, IsSameValue: 1, IsSameValueZero: 2 };
}
});
// ../../matrix/arcrun/registry/components/code/node_modules/quickjs-emscripten-core/dist/chunk-JTKJZQYV.mjs
function debugLog(...args) {
QTS_DEBUG && console.log("quickjs-emscripten:", ...args);
}
function* awaitYield(value) {
return yield value;
}
function awaitYieldOf(generator) {
return awaitYield(awaitEachYieldedPromise(generator));
}
function maybeAsyncFn(that, fn) {
return (...args) => {
let generator = fn.call(that, AwaitYield, ...args);
return awaitEachYieldedPromise(generator);
};
}
function maybeAsync(that, startGenerator) {
let generator = startGenerator.call(that, AwaitYield);
return awaitEachYieldedPromise(generator);
}
function awaitEachYieldedPromise(gen) {
function handleNextStep(step) {
return step.done ? step.value : step.value instanceof Promise ? step.value.then((value) => handleNextStep(gen.next(value)), (error) => handleNextStep(gen.throw(error))) : handleNextStep(gen.next(step.value));
}
return handleNextStep(gen.next());
}
function scopeFinally(scope, blockError) {
let disposeError;
try {
scope.dispose();
} catch (error) {
disposeError = error;
}
if (blockError && disposeError) throw Object.assign(blockError, { message: `${blockError.message}
Then, failed to dispose scope: ${disposeError.message}`, disposeError }), blockError;
if (blockError || disposeError) throw blockError || disposeError;
}
function createDisposableArray(items) {
let array = items ? Array.from(items) : [];
function disposeAlive() {
return array.forEach((disposable) => disposable.alive ? disposable.dispose() : void 0);
}
function someIsAlive() {
return array.some((disposable) => disposable.alive);
}
return Object.defineProperty(array, SymbolDispose, { configurable: true, enumerable: false, value: disposeAlive }), Object.defineProperty(array, "dispose", { configurable: true, enumerable: false, value: disposeAlive }), Object.defineProperty(array, "alive", { configurable: true, enumerable: false, get: someIsAlive }), array;
}
function isDisposable(value) {
return !!(value && (typeof value == "object" || typeof value == "function") && "alive" in value && typeof value.alive == "boolean" && "dispose" in value && typeof value.dispose == "function");
}
function intrinsicsToFlags(intrinsics) {
if (!intrinsics) return 0;
let result = 0;
for (let [maybeIntrinsicName, enabled] of Object.entries(intrinsics)) {
if (!(maybeIntrinsicName in IntrinsicsFlags)) throw new QuickJSUnknownIntrinsic(maybeIntrinsicName);
enabled && (result |= IntrinsicsFlags[maybeIntrinsicName]);
}
return result;
}
function evalOptionsToFlags(evalOptions) {
if (typeof evalOptions == "number") return evalOptions;
if (evalOptions === void 0) return 0;
let { type, strict, strip, compileOnly, backtraceBarrier } = evalOptions, flags = 0;
return type === "global" && (flags |= EvalFlags.JS_EVAL_TYPE_GLOBAL), type === "module" && (flags |= EvalFlags.JS_EVAL_TYPE_MODULE), strict && (flags |= EvalFlags.JS_EVAL_FLAG_STRICT), strip && (flags |= EvalFlags.JS_EVAL_FLAG_STRIP), compileOnly && (flags |= EvalFlags.JS_EVAL_FLAG_COMPILE_ONLY), backtraceBarrier && (flags |= EvalFlags.JS_EVAL_FLAG_BACKTRACE_BARRIER), flags;
}
function getOwnPropertyNamesOptionsToFlags(options) {
if (typeof options == "number") return options;
if (options === void 0) return 0;
let { strings: includeStrings, symbols: includeSymbols, quickjsPrivate: includePrivate, onlyEnumerable, numbers: includeNumbers, numbersAsStrings } = options, flags = 0;
return includeStrings && (flags |= GetOwnPropertyNamesFlags.JS_GPN_STRING_MASK), includeSymbols && (flags |= GetOwnPropertyNamesFlags.JS_GPN_SYMBOL_MASK), includePrivate && (flags |= GetOwnPropertyNamesFlags.JS_GPN_PRIVATE_MASK), onlyEnumerable && (flags |= GetOwnPropertyNamesFlags.JS_GPN_ENUM_ONLY), includeNumbers && (flags |= GetOwnPropertyNamesFlags.QTS_GPN_NUMBER_MASK), numbersAsStrings && (flags |= GetOwnPropertyNamesFlags.QTS_STANDARD_COMPLIANT_NUMBER), flags;
}
function concat(...values) {
let result = [];
for (let value of values) value !== void 0 && (result = result.concat(value));
return result;
}
function applyBaseRuntimeOptions(runtime, options) {
options.interruptHandler && runtime.setInterruptHandler(options.interruptHandler), options.maxStackSizeBytes !== void 0 && runtime.setMaxStackSize(options.maxStackSizeBytes), options.memoryLimitBytes !== void 0 && runtime.setMemoryLimit(options.memoryLimitBytes);
}
function applyModuleEvalRuntimeOptions(runtime, options) {
options.moduleLoader && runtime.setModuleLoader(options.moduleLoader), options.shouldInterrupt && runtime.setInterruptHandler(options.shouldInterrupt), options.memoryLimitBytes !== void 0 && runtime.setMemoryLimit(options.memoryLimitBytes), options.maxStackSizeBytes !== void 0 && runtime.setMaxStackSize(options.maxStackSizeBytes);
}
var __defProp2, __export2, QTS_DEBUG, errors_exports, QuickJSUnwrapError, QuickJSWrongOwner, QuickJSUseAfterFree, QuickJSNotImplemented, QuickJSAsyncifyError, QuickJSAsyncifySuspended, QuickJSMemoryLeakDetected, QuickJSEmscriptenModuleError, QuickJSUnknownIntrinsic, QuickJSPromisePending, QuickJSEmptyGetOwnPropertyNames, AwaitYield, UsingDisposable, SymbolDispose, prototypeAsAny, Lifetime, StaticLifetime, WeakLifetime, Scope, AbstractDisposableResult, DisposableSuccess, DisposableFail, DisposableResult, QuickJSDeferredPromise, ModuleMemory, DefaultIntrinsics, QuickJSIterator, ContextMemory, QuickJSContext, QuickJSRuntime, QuickJSEmscriptenModuleCallbacks, QuickJSModuleCallbacks, QuickJSWASMModule;
var init_chunk_JTKJZQYV = __esm({
"../../matrix/arcrun/registry/components/code/node_modules/quickjs-emscripten-core/dist/chunk-JTKJZQYV.mjs"() {
init_dist();
init_dist();
__defProp2 = Object.defineProperty;
__export2 = (target, all) => {
for (var name in all) __defProp2(target, name, { get: all[name], enumerable: true });
};
QTS_DEBUG = false;
errors_exports = {};
__export2(errors_exports, { QuickJSAsyncifyError: () => QuickJSAsyncifyError, QuickJSAsyncifySuspended: () => QuickJSAsyncifySuspended, QuickJSEmptyGetOwnPropertyNames: () => QuickJSEmptyGetOwnPropertyNames, QuickJSEmscriptenModuleError: () => QuickJSEmscriptenModuleError, QuickJSMemoryLeakDetected: () => QuickJSMemoryLeakDetected, QuickJSNotImplemented: () => QuickJSNotImplemented, QuickJSPromisePending: () => QuickJSPromisePending, QuickJSUnknownIntrinsic: () => QuickJSUnknownIntrinsic, QuickJSUnwrapError: () => QuickJSUnwrapError, QuickJSUseAfterFree: () => QuickJSUseAfterFree, QuickJSWrongOwner: () => QuickJSWrongOwner });
QuickJSUnwrapError = class extends Error {
constructor(cause, context) {
let message = typeof cause == "object" && cause && "message" in cause ? String(cause.message) : String(cause);
super(message);
this.cause = cause;
this.context = context;
this.name = "QuickJSUnwrapError";
}
};
QuickJSWrongOwner = class extends Error {
constructor() {
super(...arguments);
this.name = "QuickJSWrongOwner";
}
};
QuickJSUseAfterFree = class extends Error {
constructor() {
super(...arguments);
this.name = "QuickJSUseAfterFree";
}
};
QuickJSNotImplemented = class extends Error {
constructor() {
super(...arguments);
this.name = "QuickJSNotImplemented";
}
};
QuickJSAsyncifyError = class extends Error {
constructor() {
super(...arguments);
this.name = "QuickJSAsyncifyError";
}
};
QuickJSAsyncifySuspended = class extends Error {
constructor() {
super(...arguments);
this.name = "QuickJSAsyncifySuspended";
}
};
QuickJSMemoryLeakDetected = class extends Error {
constructor() {
super(...arguments);
this.name = "QuickJSMemoryLeakDetected";
}
};
QuickJSEmscriptenModuleError = class extends Error {
constructor() {
super(...arguments);
this.name = "QuickJSEmscriptenModuleError";
}
};
QuickJSUnknownIntrinsic = class extends TypeError {
constructor() {
super(...arguments);
this.name = "QuickJSUnknownIntrinsic";
}
};
QuickJSPromisePending = class extends Error {
constructor() {
super(...arguments);
this.name = "QuickJSPromisePending";
}
};
QuickJSEmptyGetOwnPropertyNames = class extends Error {
constructor() {
super(...arguments);
this.name = "QuickJSEmptyGetOwnPropertyNames";
}
};
AwaitYield = awaitYield;
AwaitYield.of = awaitYieldOf;
UsingDisposable = class {
[Symbol.dispose]() {
return this.dispose();
}
};
SymbolDispose = Symbol.dispose ?? /* @__PURE__ */ Symbol.for("Symbol.dispose");
prototypeAsAny = UsingDisposable.prototype;
prototypeAsAny[SymbolDispose] || (prototypeAsAny[SymbolDispose] = function() {
return this.dispose();
});
Lifetime = class _Lifetime extends UsingDisposable {
constructor(_value, copier, disposer, _owner) {
super();
this._value = _value;
this.copier = copier;
this.disposer = disposer;
this._owner = _owner;
this._alive = true;
this._constructorStack = QTS_DEBUG ? new Error("Lifetime constructed").stack : void 0;
}
get alive() {
return this._alive;
}
get value() {
return this.assertAlive(), this._value;
}
get owner() {
return this._owner;
}
get dupable() {
return !!this.copier;
}
dup() {
if (this.assertAlive(), !this.copier) throw new Error("Non-dupable lifetime");
return new _Lifetime(this.copier(this._value), this.copier, this.disposer, this._owner);
}
consume(map) {
this.assertAlive();
let result = map(this);
return this.dispose(), result;
}
map(map) {
return this.assertAlive(), map(this);
}
tap(fn) {
return fn(this), this;
}
dispose() {
this.assertAlive(), this.disposer && this.disposer(this._value), this._alive = false;
}
assertAlive() {
if (!this.alive) throw this._constructorStack ? new QuickJSUseAfterFree(`Lifetime not alive
${this._constructorStack}
Lifetime used`) : new QuickJSUseAfterFree("Lifetime not alive");
}
};
StaticLifetime = class extends Lifetime {
constructor(value, owner) {
super(value, void 0, void 0, owner);
}
get dupable() {
return true;
}
dup() {
return this;
}
dispose() {
}
};
WeakLifetime = class extends Lifetime {
constructor(value, copier, disposer, owner) {
super(value, copier, disposer, owner);
}
dispose() {
this._alive = false;
}
};
Scope = class _Scope extends UsingDisposable {
constructor() {
super(...arguments);
this._disposables = new Lifetime(/* @__PURE__ */ new Set());
this.manage = (lifetime) => (this._disposables.value.add(lifetime), lifetime);
}
static withScope(block) {
let scope = new _Scope(), blockError;
try {
return block(scope);
} catch (error) {
throw blockError = error, error;
} finally {
scopeFinally(scope, blockError);
}
}
static withScopeMaybeAsync(_this, block) {
return maybeAsync(void 0, function* (awaited) {
let scope = new _Scope(), blockError;
try {
return yield* awaited.of(block.call(_this, awaited, scope));
} catch (error) {
throw blockError = error, error;
} finally {
scopeFinally(scope, blockError);
}
});
}
static async withScopeAsync(block) {
let scope = new _Scope(), blockError;
try {
return await block(scope);
} catch (error) {
throw blockError = error, error;
} finally {
scopeFinally(scope, blockError);
}
}
get alive() {
return this._disposables.alive;
}
dispose() {
let lifetimes = Array.from(this._disposables.value.values()).reverse();
for (let lifetime of lifetimes) lifetime.alive && lifetime.dispose();
this._disposables.dispose();
}
};
AbstractDisposableResult = class _AbstractDisposableResult extends UsingDisposable {
static success(value) {
return new DisposableSuccess(value);
}
static fail(error, onUnwrap) {
return new DisposableFail(error, onUnwrap);
}
static is(result) {
return result instanceof _AbstractDisposableResult;
}
};
DisposableSuccess = class extends AbstractDisposableResult {
constructor(value) {
super();
this.value = value;
}
get alive() {
return isDisposable(this.value) ? this.value.alive : true;
}
dispose() {
isDisposable(this.value) && this.value.dispose();
}
unwrap() {
return this.value;
}
unwrapOr(_fallback) {
return this.value;
}
};
DisposableFail = class extends AbstractDisposableResult {
constructor(error, onUnwrap) {
super();
this.error = error;
this.onUnwrap = onUnwrap;
}
get alive() {
return isDisposable(this.error) ? this.error.alive : true;
}
dispose() {
isDisposable(this.error) && this.error.dispose();
}
unwrap() {
throw this.onUnwrap(this), this.error;
}
unwrapOr(fallback) {
return fallback;
}
};
DisposableResult = AbstractDisposableResult;
QuickJSDeferredPromise = class extends UsingDisposable {
constructor(args) {
super();
this.resolve = (value) => {
this.resolveHandle.alive && (this.context.unwrapResult(this.context.callFunction(this.resolveHandle, this.context.undefined, value || this.context.undefined)).dispose(), this.disposeResolvers(), this.onSettled());
};
this.reject = (value) => {
this.rejectHandle.alive && (this.context.unwrapResult(this.context.callFunction(this.rejectHandle, this.context.undefined, value || this.context.undefined)).dispose(), this.disposeResolvers(), this.onSettled());
};
this.dispose = () => {
this.handle.alive && this.handle.dispose(), this.disposeResolvers();
};
this.context = args.context, this.owner = args.context.runtime, this.handle = args.promiseHandle, this.settled = new Promise((resolve) => {
this.onSettled = resolve;
}), this.resolveHandle = args.resolveHandle, this.rejectHandle = args.rejectHandle;
}
get alive() {
return this.handle.alive || this.resolveHandle.alive || this.rejectHandle.alive;
}
disposeResolvers() {
this.resolveHandle.alive && this.resolveHandle.dispose(), this.rejectHandle.alive && this.rejectHandle.dispose();
}
};
ModuleMemory = class {
constructor(module) {
this.module = module;
}
toPointerArray(handleArray) {
let typedArray = new Int32Array(handleArray.map((handle) => handle.value)), numBytes = typedArray.length * typedArray.BYTES_PER_ELEMENT, ptr = this.module._malloc(numBytes);
return new Uint8Array(this.module.HEAPU8.buffer, ptr, numBytes).set(new Uint8Array(typedArray.buffer)), new Lifetime(ptr, void 0, (ptr2) => this.module._free(ptr2));
}
newTypedArray(kind, length) {
let zeros = new kind(new Array(length).fill(0)), numBytes = zeros.length * zeros.BYTES_PER_ELEMENT, ptr = this.module._malloc(numBytes), typedArray = new kind(this.module.HEAPU8.buffer, ptr, length);
return typedArray.set(zeros), new Lifetime({ typedArray, ptr }, void 0, (value) => this.module._free(value.ptr));
}
newMutablePointerArray(length) {
return this.newTypedArray(Int32Array, length);
}
newHeapCharPointer(string) {
let strlen = this.module.lengthBytesUTF8(string), dataBytes = strlen + 1, ptr = this.module._malloc(dataBytes);
return this.module.stringToUTF8(string, ptr, dataBytes), new Lifetime({ ptr, strlen }, void 0, (value) => this.module._free(value.ptr));
}
newHeapBufferPointer(buffer) {
let numBytes = buffer.byteLength, ptr = this.module._malloc(numBytes);
return this.module.HEAPU8.set(buffer, ptr), new Lifetime({ pointer: ptr, numBytes }, void 0, (value) => this.module._free(value.pointer));
}
consumeHeapCharPointer(ptr) {
let str = this.module.UTF8ToString(ptr);
return this.module._free(ptr), str;
}
};
DefaultIntrinsics = Object.freeze({ BaseObjects: true, Date: true, Eval: true, StringNormalize: true, RegExp: true, JSON: true, Proxy: true, MapSet: true, TypedArrays: true, Promise: true });
QuickJSIterator = class extends UsingDisposable {
constructor(handle, context) {
super();
this.handle = handle;
this.context = context;
this._isDone = false;
this.owner = context.runtime;
}
[Symbol.iterator]() {
return this;
}
next(value) {
if (!this.alive || this._isDone) return { done: true, value: void 0 };
let nextMethod = this._next ?? (this._next = this.context.getProp(this.handle, "next"));
return this.callIteratorMethod(nextMethod, value);
}
return(value) {
if (!this.alive) return { done: true, value: void 0 };
let returnMethod = this.context.getProp(this.handle, "return");
if (returnMethod === this.context.undefined && value === void 0) return this.dispose(), { done: true, value: void 0 };
let result = this.callIteratorMethod(returnMethod, value);
return returnMethod.dispose(), this.dispose(), result;
}
throw(e) {
if (!this.alive) return { done: true, value: void 0 };
let errorHandle = e instanceof Lifetime ? e : this.context.newError(e), throwMethod = this.context.getProp(this.handle, "throw"), result = this.callIteratorMethod(throwMethod, e);
return errorHandle.alive && errorHandle.dispose(), throwMethod.dispose(), this.dispose(), result;
}
get alive() {
return this.handle.alive;
}
dispose() {
this._isDone = true, this.handle.dispose(), this._next?.dispose();
}
callIteratorMethod(method, input) {
let callResult = input ? this.context.callFunction(method, this.handle, input) : this.context.callFunction(method, this.handle);
if (callResult.error) return this.dispose(), { value: callResult };
let done = this.context.getProp(callResult.value, "done").consume((v) => this.context.dump(v));
if (done) return callResult.value.dispose(), this.dispose(), { done, value: void 0 };
let value = this.context.getProp(callResult.value, "value");
return callResult.value.dispose(), { value: DisposableResult.success(value), done };
}
};
ContextMemory = class extends ModuleMemory {
constructor(args) {
super(args.module);
this.scope = new Scope();
this.copyJSValue = (ptr) => this.ffi.QTS_DupValuePointer(this.ctx.value, ptr);
this.freeJSValue = (ptr) => {
this.ffi.QTS_FreeValuePointer(this.ctx.value, ptr);
};
args.ownedLifetimes?.forEach((lifetime) => this.scope.manage(lifetime)), this.owner = args.owner, this.module = args.module, this.ffi = args.ffi, this.rt = args.rt, this.ctx = this.scope.manage(args.ctx);
}
get alive() {
return this.scope.alive;
}
dispose() {
return this.scope.dispose();
}
[Symbol.dispose]() {
return this.dispose();
}
manage(lifetime) {
return this.scope.manage(lifetime);
}
consumeJSCharPointer(ptr) {
let str = this.module.UTF8ToString(ptr);
return this.ffi.QTS_FreeCString(this.ctx.value, ptr), str;
}
heapValueHandle(ptr) {
return new Lifetime(ptr, this.copyJSValue, this.freeJSValue, this.owner);
}
staticHeapValueHandle(ptr) {
return this.manage(this.heapValueHandle(ptr)), new StaticLifetime(ptr, this.owner);
}
};
QuickJSContext = class extends UsingDisposable {
constructor(args) {
super();
this._undefined = void 0;
this._null = void 0;
this._false = void 0;
this._true = void 0;
this._global = void 0;
this._BigInt = void 0;
this._Symbol = void 0;
this._SymbolIterator = void 0;
this._SymbolAsyncIterator = void 0;
this.fnNextId = -32768;
this.fnMaps = /* @__PURE__ */ new Map();
this.cToHostCallbacks = { callFunction: (ctx, this_ptr, argc, argv, fn_id) => {
if (ctx !== this.ctx.value) throw new Error("QuickJSContext instance received C -> JS call with mismatched ctx");
let fn = this.getFunction(fn_id);
if (!fn) throw new Error(`QuickJSContext had no callback with id ${fn_id}`);
return Scope.withScopeMaybeAsync(this, function* (awaited, scope) {
let thisHandle = scope.manage(new WeakLifetime(this_ptr, this.memory.copyJSValue, this.memory.freeJSValue, this.runtime)), argHandles = new Array(argc);
for (let i = 0; i < argc; i++) {
let ptr = this.ffi.QTS_ArgvGetJSValueConstPointer(argv, i);
argHandles[i] = scope.manage(new WeakLifetime(ptr, this.memory.copyJSValue, this.memory.freeJSValue, this.runtime));
}
try {
let result = yield* awaited(fn.apply(thisHandle, argHandles));
if (result) {
if ("error" in result && result.error) throw this.runtime.debugLog("throw error", result.error), result.error;
let handle = scope.manage(result instanceof Lifetime ? result : result.value);
return this.ffi.QTS_DupValuePointer(this.ctx.value, handle.value);
}
return 0;
} catch (error) {
return this.errorToHandle(error).consume((errorHandle) => this.ffi.QTS_Throw(this.ctx.value, errorHandle.value));
}
});
} };
this.runtime = args.runtime, this.module = args.module, this.ffi = args.ffi, this.rt = args.rt, this.ctx = args.ctx, this.memory = new ContextMemory({ ...args, owner: this.runtime }), args.callbacks.setContextCallbacks(this.ctx.value, this.cToHostCallbacks), this.dump = this.dump.bind(this), this.getString = this.getString.bind(this), this.getNumber = this.getNumber.bind(this), this.resolvePromise = this.resolvePromise.bind(this), this.uint32Out = this.memory.manage(this.memory.newTypedArray(Uint32Array, 1));
}
get alive() {
return this.memory.alive;
}
dispose() {
this.memory.dispose();
}
get undefined() {
if (this._undefined) return this._undefined;
let ptr = this.ffi.QTS_GetUndefined();
return this._undefined = new StaticLifetime(ptr);
}
get null() {
if (this._null) return this._null;
let ptr = this.ffi.QTS_GetNull();
return this._null = new StaticLifetime(ptr);
}
get true() {
if (this._true) return this._true;
let ptr = this.ffi.QTS_GetTrue();
return this._true = new StaticLifetime(ptr);
}
get false() {
if (this._false) return this._false;
let ptr = this.ffi.QTS_GetFalse();
return this._false = new StaticLifetime(ptr);
}
get global() {
if (this._global) return this._global;
let ptr = this.ffi.QTS_GetGlobalObject(this.ctx.value);
return this._global = this.memory.staticHeapValueHandle(ptr), this._global;
}
newNumber(num) {
return this.memory.heapValueHandle(this.ffi.QTS_NewFloat64(this.ctx.value, num));
}
newString(str) {
let ptr = this.memory.newHeapCharPointer(str).consume((charHandle) => this.ffi.QTS_NewString(this.ctx.value, charHandle.value.ptr));
return this.memory.heapValueHandle(ptr);
}
newUniqueSymbol(description) {
let key = (typeof description == "symbol" ? description.description : description) ?? "", ptr = this.memory.newHeapCharPointer(key).consume((charHandle) => this.ffi.QTS_NewSymbol(this.ctx.value, charHandle.value.ptr, 0));
return this.memory.heapValueHandle(ptr);
}
newSymbolFor(key) {
let description = (typeof key == "symbol" ? key.description : key) ?? "", ptr = this.memory.newHeapCharPointer(description).consume((charHandle) => this.ffi.QTS_NewSymbol(this.ctx.value, charHandle.value.ptr, 1));
return this.memory.heapValueHandle(ptr);
}
getWellKnownSymbol(name) {
return this._Symbol ?? (this._Symbol = this.memory.manage(this.getProp(this.global, "Symbol"))), this.getProp(this._Symbol, name);
}
newBigInt(num) {
if (!this._BigInt) {
let bigIntHandle2 = this.getProp(this.global, "BigInt");
this.memory.manage(bigIntHandle2), this._BigInt = new StaticLifetime(bigIntHandle2.value, this.runtime);
}
let bigIntHandle = this._BigInt, asString = String(num);
return this.newString(asString).consume((handle) => this.unwrapResult(this.callFunction(bigIntHandle, this.undefined, handle)));
}
newObject(prototype) {
prototype && this.runtime.assertOwned(prototype);
let ptr = prototype ? this.ffi.QTS_NewObjectProto(this.ctx.value, prototype.value) : this.ffi.QTS_NewObject(this.ctx.value);
return this.memory.heapValueHandle(ptr);
}
newArray() {
let ptr = this.ffi.QTS_NewArray(this.ctx.value);
return this.memory.heapValueHandle(ptr);
}
newArrayBuffer(buffer) {
let array = new Uint8Array(buffer), handle = this.memory.newHeapBufferPointer(array), ptr = this.ffi.QTS_NewArrayBuffer(this.ctx.value, handle.value.pointer, array.length);
return this.memory.heapValueHandle(ptr);
}
newPromise(value) {
let deferredPromise = Scope.withScope((scope) => {
let mutablePointerArray = scope.manage(this.memory.newMutablePointerArray(2)), promisePtr = this.ffi.QTS_NewPromiseCapability(this.ctx.value, mutablePointerArray.value.ptr), promiseHandle = this.memory.heapValueHandle(promisePtr), [resolveHandle, rejectHandle] = Array.from(mutablePointerArray.value.typedArray).map((jsvaluePtr) => this.memory.heapValueHandle(jsvaluePtr));
return new QuickJSDeferredPromise({ context: this, promiseHandle, resolveHandle, rejectHandle });
});
return value && typeof value == "function" && (value = new Promise(value)), value && Promise.resolve(value).then(deferredPromise.resolve, (error) => error instanceof Lifetime ? deferredPromise.reject(error) : this.newError(error).consume(deferredPromise.reject)), deferredPromise;
}
newFunction(name, fn) {
let fnId = ++this.fnNextId;
return this.setFunction(fnId, fn), this.memory.heapValueHandle(this.ffi.QTS_NewFunction(this.ctx.value, fnId, name));
}
newError(error) {
let errorHandle = this.memory.heapValueHandle(this.ffi.QTS_NewError(this.ctx.value));
return error && typeof error == "object" ? (error.name !== void 0 && this.newString(error.name).consume((handle) => this.setProp(errorHandle, "name", handle)), error.message !== void 0 && this.newString(error.message).consume((handle) => this.setProp(errorHandle, "message", handle))) : typeof error == "string" ? this.newString(error).consume((handle) => this.setProp(errorHandle, "message", handle)) : error !== void 0 && this.newString(String(error)).consume((handle) => this.setProp(errorHandle, "message", handle)), errorHandle;
}
typeof(handle) {
return this.runtime.assertOwned(handle), this.memory.consumeHeapCharPointer(this.ffi.QTS_Typeof(this.ctx.value, handle.value));
}
getNumber(handle) {
return this.runtime.assertOwned(handle), this.ffi.QTS_GetFloat64(this.ctx.value, handle.value);
}
getString(handle) {
return this.runtime.assertOwned(handle), this.memory.consumeJSCharPointer(this.ffi.QTS_GetString(this.ctx.value, handle.value));
}
getSymbol(handle) {
this.runtime.assertOwned(handle);
let key = this.memory.consumeJSCharPointer(this.ffi.QTS_GetSymbolDescriptionOrKey(this.ctx.value, handle.value));
return this.ffi.QTS_IsGlobalSymbol(this.ctx.value, handle.value) ? Symbol.for(key) : Symbol(key);
}
getBigInt(handle) {
this.runtime.assertOwned(handle);
let asString = this.getString(handle);
return BigInt(asString);
}
getArrayBuffer(handle) {
this.runtime.assertOwned(handle);
let len = this.ffi.QTS_GetArrayBufferLength(this.ctx.value, handle.value), ptr = this.ffi.QTS_GetArrayBuffer(this.ctx.value, handle.value);
if (!ptr) throw new Error("Couldn't allocate memory to get ArrayBuffer");
return new Lifetime(this.module.HEAPU8.subarray(ptr, ptr + len), void 0, () => this.module._free(ptr));
}
getPromiseState(handle) {
this.runtime.assertOwned(handle);
let state = this.ffi.QTS_PromiseState(this.ctx.value, handle.value);
if (state < 0) return { type: "fulfilled", value: handle, notAPromise: true };
if (state === JSPromiseStateEnum.Pending) return { type: "pending", get error() {
return new QuickJSPromisePending("Cannot unwrap a pending promise");
} };
let ptr = this.ffi.QTS_PromiseResult(this.ctx.value, handle.value), result = this.memory.heapValueHandle(ptr);
if (state === JSPromiseStateEnum.Fulfilled) return { type: "fulfilled", value: result };
if (state === JSPromiseStateEnum.Rejected) return { type: "rejected", error: result };
throw result.dispose(), new Error(`Unknown JSPromiseStateEnum: ${state}`);
}
resolvePromise(promiseLikeHandle) {
this.runtime.assertOwned(promiseLikeHandle);
let vmResolveResult = Scope.withScope((scope) => {
let vmPromise = scope.manage(this.getProp(this.global, "Promise")), vmPromiseResolve = scope.manage(this.getProp(vmPromise, "resolve"));
return this.callFunction(vmPromiseResolve, vmPromise, promiseLikeHandle);
});
return vmResolveResult.error ? Promise.resolve(vmResolveResult) : new Promise((resolve) => {
Scope.withScope((scope) => {
let resolveHandle = scope.manage(this.newFunction("resolve", (value) => {
resolve(this.success(value && value.dup()));
})), rejectHandle = scope.manage(this.newFunction("reject", (error) => {
resolve(this.fail(error && error.dup()));
})), promiseHandle = scope.manage(vmResolveResult.value), promiseThenHandle = scope.manage(this.getProp(promiseHandle, "then"));
this.callFunction(promiseThenHandle, promiseHandle, resolveHandle, rejectHandle).unwrap().dispose();
});
});
}
isEqual(a, b, equalityType = IsEqualOp.IsStrictlyEqual) {
if (a === b) return true;
this.runtime.assertOwned(a), this.runtime.assertOwned(b);
let result = this.ffi.QTS_IsEqual(this.ctx.value, a.value, b.value, equalityType);
if (result === -1) throw new QuickJSNotImplemented("WASM variant does not expose equality");
return !!result;
}
eq(handle, other) {
return this.isEqual(handle, other, IsEqualOp.IsStrictlyEqual);
}
sameValue(handle, other) {
return this.isEqual(handle, other, IsEqualOp.IsSameValue);
}
sameValueZero(handle, other) {
return this.isEqual(handle, other, IsEqualOp.IsSameValueZero);
}
getProp(handle, key) {
this.runtime.assertOwned(handle);
let ptr;
return typeof key == "number" && key >= 0 ? ptr = this.ffi.QTS_GetPropNumber(this.ctx.value, handle.value, key) : ptr = this.borrowPropertyKey(key).consume((quickJSKey) => this.ffi.QTS_GetProp(this.ctx.value, handle.value, quickJSKey.value)), this.memory.heapValueHandle(ptr);
}
getLength(handle) {
if (this.runtime.assertOwned(handle), !(this.ffi.QTS_GetLength(this.ctx.value, this.uint32Out.value.ptr, handle.value) < 0)) return this.uint32Out.value.typedArray[0];
}
getOwnPropertyNames(handle, options = { strings: true, numbersAsStrings: true }) {
this.runtime.assertOwned(handle), handle.value;
let flags = getOwnPropertyNamesOptionsToFlags(options);
if (flags === 0) throw new QuickJSEmptyGetOwnPropertyNames("No options set, will return an empty array");
return Scope.withScope((scope) => {
let outPtr = scope.manage(this.memory.newMutablePointerArray(1)), errorPtr = this.ffi.QTS_GetOwnPropertyNames(this.ctx.value, outPtr.value.ptr, this.uint32Out.value.ptr, handle.value, flags);
if (errorPtr) return this.fail(this.memory.heapValueHandle(errorPtr));
let len = this.uint32Out.value.typedArray[0], ptr = outPtr.value.typedArray[0], pointerArray = new Uint32Array(this.module.HEAP8.buffer, ptr, len), handles = Array.from(pointerArray).map((ptr2) => this.memory.heapValueHandle(ptr2));
return this.ffi.QTS_FreeVoidPointer(this.ctx.value, ptr), this.success(createDisposableArray(handles));
});
}
getIterator(iterableHandle) {
let SymbolIterator = this._SymbolIterator ?? (this._SymbolIterator = this.memory.manage(this.getWellKnownSymbol("iterator")));
return Scope.withScope((scope) => {
let methodHandle = scope.manage(this.getProp(iterableHandle, SymbolIterator)), iteratorCallResult = this.callFunction(methodHandle, iterableHandle);
return iteratorCallResult.error ? iteratorCallResult : this.success(new QuickJSIterator(iteratorCallResult.value, this));
});
}
setProp(handle, key, value) {
this.runtime.assertOwned(handle), this.borrowPropertyKey(key).consume((quickJSKey) => this.ffi.QTS_SetProp(this.ctx.value, handle.value, quickJSKey.value, value.value));
}
defineProp(handle, key, descriptor) {
this.runtime.assertOwned(handle), Scope.withScope((scope) => {
let quickJSKey = scope.manage(this.borrowPropertyKey(key)), value = descriptor.value || this.undefined, configurable = !!descriptor.configurable, enumerable = !!descriptor.enumerable, hasValue = !!descriptor.value, get = descriptor.get ? scope.manage(this.newFunction(descriptor.get.name, descriptor.get)) : this.undefined, set = descriptor.set ? scope.manage(this.newFunction(descriptor.set.name, descriptor.set)) : this.undefined;
this.ffi.QTS_DefineProp(this.ctx.value, handle.value, quickJSKey.value, value.value, get.value, set.value, configurable, enumerable, hasValue);
});
}
callFunction(func, thisVal, ...restArgs) {
this.runtime.assertOwned(func);
let args, firstArg = restArgs[0];
firstArg === void 0 || Array.isArray(firstArg) ? args = firstArg ?? [] : args = restArgs;
let resultPtr = this.memory.toPointerArray(args).consume((argsArrayPtr) => this.ffi.QTS_Call(this.ctx.value, func.value, thisVal.value, args.length, argsArrayPtr.value)), errorPtr = this.ffi.QTS_ResolveException(this.ctx.value, resultPtr);
return errorPtr ? (this.ffi.QTS_FreeValuePointer(this.ctx.value, resultPtr), this.fail(this.memory.heapValueHandle(errorPtr))) : this.success(this.memory.heapValueHandle(resultPtr));
}
callMethod(thisHandle, key, args = []) {
return this.getProp(thisHandle, key).consume((func) => this.callFunction(func, thisHandle, args));
}
evalCode(code, filename = "eval.js", options) {
let detectModule = options === void 0 ? 1 : 0, flags = evalOptionsToFlags(options), resultPtr = this.memory.newHeapCharPointer(code).consume((charHandle) => this.ffi.QTS_Eval(this.ctx.value, charHandle.value.ptr, charHandle.value.strlen, filename, detectModule, flags)), errorPtr = this.ffi.QTS_ResolveException(this.ctx.value, resultPtr);
return errorPtr ? (this.ffi.QTS_FreeValuePointer(this.ctx.value, resultPtr), this.fail(this.memory.heapValueHandle(errorPtr))) : this.success(this.memory.heapValueHandle(resultPtr));
}
throw(error) {
return this.errorToHandle(error).consume((handle) => this.ffi.QTS_Throw(this.ctx.value, handle.value));
}
borrowPropertyKey(key) {
return typeof key == "number" ? this.newNumber(key) : typeof key == "string" ? this.newString(key) : new StaticLifetime(key.value, this.runtime);
}
getMemory(rt) {
if (rt === this.rt.value) return this.memory;
throw new Error("Private API. Cannot get memory from a different runtime");
}
dump(handle) {
this.runtime.assertOwned(handle);
let type = this.typeof(handle);
if (type === "string") return this.getString(handle);
if (type === "number") return this.getNumber(handle);
if (type === "bigint") return this.getBigInt(handle);
if (type === "undefined") return;
if (type === "symbol") return this.getSymbol(handle);
let asPromiseState = this.getPromiseState(handle);
if (asPromiseState.type === "fulfilled" && !asPromiseState.notAPromise) return handle.dispose(), { type: asPromiseState.type, value: asPromiseState.value.consume(this.dump) };
if (asPromiseState.type === "pending") return handle.dispose(), { type: asPromiseState.type };
if (asPromiseState.type === "rejected") return handle.dispose(), { type: asPromiseState.type, error: asPromiseState.error.consume(this.dump) };
let str = this.memory.consumeJSCharPointer(this.ffi.QTS_Dump(this.ctx.value, handle.value));
try {
return JSON.parse(str);
} catch {
return str;
}
}
unwrapResult(result) {
if (result.error) {
let context = "context" in result.error ? result.error.context : this, cause = result.error.consume((error) => this.dump(error));
if (cause && typeof cause == "object" && typeof cause.message == "string") {
let { message, name, stack, ...rest } = cause, exception = new QuickJSUnwrapError(cause, context);
typeof name == "string" && (exception.name = cause.name), exception.message = message;
let hostStack = exception.stack;
throw typeof stack == "string" && (exception.stack = `${name}: ${message}
${cause.stack}Host: ${hostStack}`), Object.assign(exception, rest), exception;
}
throw new QuickJSUnwrapError(cause);
}
return result.value;
}
[/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
return this.alive ? `${this.constructor.name} { ctx: ${this.ctx.value} rt: ${this.rt.value} }` : `${this.constructor.name} { disposed }`;
}
getFunction(fn_id) {
let map_id = fn_id >> 8, fnMap = this.fnMaps.get(map_id);
if (fnMap) return fnMap.get(fn_id);
}
setFunction(fn_id, handle) {
let map_id = fn_id >> 8, fnMap = this.fnMaps.get(map_id);
return fnMap || (fnMap = /* @__PURE__ */ new Map(), this.fnMaps.set(map_id, fnMap)), fnMap.set(fn_id, handle);
}
errorToHandle(error) {
return error instanceof Lifetime ? error : this.newError(error);
}
encodeBinaryJSON(handle) {
let ptr = this.ffi.QTS_bjson_encode(this.ctx.value, handle.value);
return this.memory.heapValueHandle(ptr);
}
decodeBinaryJSON(handle) {
let ptr = this.ffi.QTS_bjson_decode(this.ctx.value, handle.value);
return this.memory.heapValueHandle(ptr);
}
success(value) {
return DisposableResult.success(value);
}
fail(error) {
return DisposableResult.fail(error, (error2) => this.unwrapResult(error2));
}
};
QuickJSRuntime = class extends UsingDisposable {
constructor(args) {
super();
this.scope = new Scope();
this.contextMap = /* @__PURE__ */ new Map();
this._debugMode = false;
this.cToHostCallbacks = { shouldInterrupt: (rt) => {
if (rt !== this.rt.value) throw new Error("QuickJSContext instance received C -> JS interrupt with mismatched rt");
let fn = this.interruptHandler;
if (!fn) throw new Error("QuickJSContext had no interrupt handler");
return fn(this) ? 1 : 0;
}, loadModuleSource: maybeAsyncFn(this, function* (awaited, rt, ctx, moduleName) {
let moduleLoader = this.moduleLoader;
if (!moduleLoader) throw new Error("Runtime has no module loader");
if (rt !== this.rt.value) throw new Error("Runtime pointer mismatch");
let context = this.contextMap.get(ctx) ?? this.newContext({ contextPointer: ctx });
try {
let result = yield* awaited(moduleLoader(moduleName, context));
if (typeof result == "object" && "error" in result && result.error) throw this.debugLog("cToHostLoadModule: loader returned error", result.error), result.error;
let moduleSource = typeof result == "string" ? result : "value" in result ? result.value : result;
return this.memory.newHeapCharPointer(moduleSource).value.ptr;
} catch (error) {
return this.debugLog("cToHostLoadModule: caught error", error), context.throw(error), 0;
}
}), normalizeModule: maybeAsyncFn(this, function* (awaited, rt, ctx, baseModuleName, moduleNameRequest) {
let moduleNormalizer = this.moduleNormalizer;
if (!moduleNormalizer) throw new Error("Runtime has no module normalizer");
if (rt !== this.rt.value) throw new Error("Runtime pointer mismatch");
let context = this.contextMap.get(ctx) ?? this.newContext({ contextPointer: ctx });
try {
let result = yield* awaited(moduleNormalizer(baseModuleName, moduleNameRequest, context));
if (typeof result == "object" && "error" in result && result.error) throw this.debugLog("cToHostNormalizeModule: normalizer returned error", result.error), result.error;
let name = typeof result == "string" ? result : result.value;
return context.getMemory(this.rt.value).newHeapCharPointer(name).value.ptr;
} catch (error) {
return this.debugLog("normalizeModule: caught error", error), context.throw(error), 0;
}
}) };
args.ownedLifetimes?.forEach((lifetime) => this.scope.manage(lifetime)), this.module = args.module, this.memory = new ModuleMemory(this.module), this.ffi = args.ffi, this.rt = args.rt, this.callbacks = args.callbacks, this.scope.manage(this.rt), this.callbacks.setRuntimeCallbacks(this.rt.value, this.cToHostCallbacks), this.executePendingJobs = this.executePendingJobs.bind(this), QTS_DEBUG && this.setDebugMode(true);
}
get alive() {
return this.scope.alive;
}
dispose() {
return this.scope.dispose();
}
newContext(options = {}) {
let intrinsics = intrinsicsToFlags(options.intrinsics), ctx = new Lifetime(options.contextPointer || this.ffi.QTS_NewContext(this.rt.value, intrinsics), void 0, (ctx_ptr) => {
this.contextMap.delete(ctx_ptr), this.callbacks.deleteContext(ctx_ptr), this.ffi.QTS_FreeContext(ctx_ptr);
}), context = new QuickJSContext({ module: this.module, ctx, ffi: this.ffi, rt: this.rt, ownedLifetimes: options.ownedLifetimes, runtime: this, callbacks: this.callbacks });
return this.contextMap.set(ctx.value, context), context;
}
setModuleLoader(moduleLoader, moduleNormalizer) {
this.moduleLoader = moduleLoader, this.moduleNormalizer = moduleNormalizer, this.ffi.QTS_RuntimeEnableModuleLoader(this.rt.value, this.moduleNormalizer ? 1 : 0);
}
removeModuleLoader() {
this.moduleLoader = void 0, this.ffi.QTS_RuntimeDisableModuleLoader(this.rt.value);
}
hasPendingJob() {
return !!this.ffi.QTS_IsJobPending(this.rt.value);
}
setInterruptHandler(cb) {
let prevInterruptHandler = this.interruptHandler;
this.interruptHandler = cb, prevInterruptHandler || this.ffi.QTS_RuntimeEnableInterruptHandler(this.rt.value);
}
removeInterruptHandler() {
this.interruptHandler && (this.ffi.QTS_RuntimeDisableInterruptHandler(this.rt.value), this.interruptHandler = void 0);
}
executePendingJobs(maxJobsToExecute = -1) {
let ctxPtrOut = this.memory.newMutablePointerArray(1), valuePtr = this.ffi.QTS_ExecutePendingJob(this.rt.value, maxJobsToExecute ?? -1, ctxPtrOut.value.ptr), ctxPtr = ctxPtrOut.value.typedArray[0];
if (ctxPtrOut.dispose(), ctxPtr === 0) return this.ffi.QTS_FreeValuePointerRuntime(this.rt.value, valuePtr), DisposableResult.success(0);
let context = this.contextMap.get(ctxPtr) ?? this.newContext({ contextPointer: ctxPtr }), resultValue = context.getMemory(this.rt.value).heapValueHandle(valuePtr);
if (context.typeof(resultValue) === "number") {
let executedJobs = context.getNumber(resultValue);
return resultValue.dispose(), DisposableResult.success(executedJobs);
} else {
let error = Object.assign(resultValue, { context });
return DisposableResult.fail(error, (error2) => context.unwrapResult(error2));
}
}
setMemoryLimit(limitBytes) {
if (limitBytes < 0 && limitBytes !== -1) throw new Error("Cannot set memory limit to negative number. To unset, pass -1");
this.ffi.QTS_RuntimeSetMemoryLimit(this.rt.value, limitBytes);
}
computeMemoryUsage() {
let serviceContextMemory = this.getSystemContext().getMemory(this.rt.value);
return serviceContextMemory.heapValueHandle(this.ffi.QTS_RuntimeComputeMemoryUsage(this.rt.value, serviceContextMemory.ctx.value));
}
dumpMemoryUsage() {
return this.memory.consumeHeapCharPointer(this.ffi.QTS_RuntimeDumpMemoryUsage(this.rt.value));
}
setMaxStackSize(stackSize) {
if (stackSize < 0) throw new Error("Cannot set memory limit to negative number. To unset, pass 0.");
this.ffi.QTS_RuntimeSetMaxStackSize(this.rt.value, stackSize);
}
assertOwned(handle) {
if (handle.owner && handle.owner.rt !== this.rt) throw new QuickJSWrongOwner(`Handle is not owned by this runtime: ${handle.owner.rt.value} != ${this.rt.value}`);
}
setDebugMode(enabled) {
this._debugMode = enabled, this.ffi.DEBUG && this.rt.alive && this.ffi.QTS_SetDebugLogEnabled(this.rt.value, enabled ? 1 : 0);
}
isDebugMode() {
return this._debugMode;
}
debugLog(...msg) {
this._debugMode && console.log("quickjs-emscripten:", ...msg);
}
[/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
return this.alive ? `${this.constructor.name} { rt: ${this.rt.value} }` : `${this.constructor.name} { disposed }`;
}
getSystemContext() {
return this.context || (this.context = this.scope.manage(this.newContext())), this.context;
}
};
QuickJSEmscriptenModuleCallbacks = class {
constructor(args) {
this.callFunction = args.callFunction, this.shouldInterrupt = args.shouldInterrupt, this.loadModuleSource = args.loadModuleSource, this.normalizeModule = args.normalizeModule;
}
};
QuickJSModuleCallbacks = class {
constructor(module) {
this.contextCallbacks = /* @__PURE__ */ new Map();
this.runtimeCallbacks = /* @__PURE__ */ new Map();
this.suspendedCount = 0;
this.cToHostCallbacks = new QuickJSEmscriptenModuleCallbacks({ callFunction: (asyncify, ctx, this_ptr, argc, argv, fn_id) => this.handleAsyncify(asyncify, () => {
try {
let vm = this.contextCallbacks.get(ctx);
if (!vm) throw new Error(`QuickJSContext(ctx = ${ctx}) not found for C function call "${fn_id}"`);
return vm.callFunction(ctx, this_ptr, argc, argv, fn_id);
} catch (error) {
return console.error("[C to host error: returning null]", error), 0;
}
}), shouldInterrupt: (asyncify, rt) => this.handleAsyncify(asyncify, () => {
try {
let vm = this.runtimeCallbacks.get(rt);
if (!vm) throw new Error(`QuickJSRuntime(rt = ${rt}) not found for C interrupt`);
return vm.shouldInterrupt(rt);
} catch (error) {
return console.error("[C to host interrupt: returning error]", error), 1;
}
}), loadModuleSource: (asyncify, rt, ctx, moduleName) => this.handleAsyncify(asyncify, () => {
try {
let runtimeCallbacks = this.runtimeCallbacks.get(rt);
if (!runtimeCallbacks) throw new Error(`QuickJSRuntime(rt = ${rt}) not found for C module loader`);
let loadModule = runtimeCallbacks.loadModuleSource;
if (!loadModule) throw new Error(`QuickJSRuntime(rt = ${rt}) does not support module loading`);
return loadModule(rt, ctx, moduleName);
} catch (error) {
return console.error("[C to host module loader error: returning null]", error), 0;
}
}), normalizeModule: (asyncify, rt, ctx, moduleBaseName, moduleName) => this.handleAsyncify(asyncify, () => {
try {
let runtimeCallbacks = this.runtimeCallbacks.get(rt);
if (!runtimeCallbacks) throw new Error(`QuickJSRuntime(rt = ${rt}) not found for C module loader`);
let normalizeModule = runtimeCallbacks.normalizeModule;
if (!normalizeModule) throw new Error(`QuickJSRuntime(rt = ${rt}) does not support module loading`);
return normalizeModule(rt, ctx, moduleBaseName, moduleName);
} catch (error) {
return console.error("[C to host module loader error: returning null]", error), 0;
}
}) });
this.module = module, this.module.callbacks = this.cToHostCallbacks;
}
setRuntimeCallbacks(rt, callbacks) {
this.runtimeCallbacks.set(rt, callbacks);
}
deleteRuntime(rt) {
this.runtimeCallbacks.delete(rt);
}
setContextCallbacks(ctx, callbacks) {
this.contextCallbacks.set(ctx, callbacks);
}
deleteContext(ctx) {
this.contextCallbacks.delete(ctx);
}
handleAsyncify(asyncify, fn) {
if (asyncify) return asyncify.handleSleep((done) => {
try {
let result = fn();
if (!(result instanceof Promise)) {
debugLog("asyncify.handleSleep: not suspending:", result), done(result);
return;
}
if (this.suspended) throw new QuickJSAsyncifyError(`Already suspended at: ${this.suspended.stack}
Attempted to suspend at:`);
this.suspended = new QuickJSAsyncifySuspended(`(${this.suspendedCount++})`), debugLog("asyncify.handleSleep: suspending:", this.suspended), result.then((resolvedResult) => {
this.suspended = void 0, debugLog("asyncify.handleSleep: resolved:", resolvedResult), done(resolvedResult);
}, (error) => {
debugLog("asyncify.handleSleep: rejected:", error), console.error("QuickJS: cannot handle error in suspended function", error), this.suspended = void 0;
});
} catch (error) {
throw debugLog("asyncify.handleSleep: error:", error), this.suspended = void 0, error;
}
});
let value = fn();
if (value instanceof Promise) throw new Error("Promise return value not supported in non-asyncify context.");
return value;
}
};
QuickJSWASMModule = class {
constructor(module, ffi) {
this.module = module, this.ffi = ffi, this.callbacks = new QuickJSModuleCallbacks(module);
}
newRuntime(options = {}) {
let rt = new Lifetime(this.ffi.QTS_NewRuntime(), void 0, (rt_ptr) => {
this.callbacks.deleteRuntime(rt_ptr), this.ffi.QTS_FreeRuntime(rt_ptr);
}), runtime = new QuickJSRuntime({ module: this.module, callbacks: this.callbacks, ffi: this.ffi, rt });
return applyBaseRuntimeOptions(runtime, options), options.moduleLoader && runtime.setModuleLoader(options.moduleLoader), runtime;
}
newContext(options = {}) {
let runtime = this.newRuntime(), context = runtime.newContext({ ...options, ownedLifetimes: concat(runtime, options.ownedLifetimes) });
return runtime.context = context, context;
}
evalCode(code, options = {}) {
return Scope.withScope((scope) => {
let vm = scope.manage(this.newContext());
applyModuleEvalRuntimeOptions(vm.runtime, options);
let result = vm.evalCode(code, "eval.js");
if (options.memoryLimitBytes !== void 0 && vm.runtime.setMemoryLimit(-1), result.error) throw vm.dump(scope.manage(result.error));
return vm.dump(scope.manage(result.value));
});
}
getWasmMemory() {
let memory = this.module.quickjsEmscriptenInit?.(() => {
})?.getWasmMemory?.();
if (!memory) throw new Error("Variant does not support getting WebAssembly.Memory");
return memory;
}
getFFI() {
return this.ffi;
}
};
}
});
// ../../matrix/arcrun/registry/components/code/node_modules/quickjs-emscripten-core/dist/module-6F3E5H7Y.mjs
var module_6F3E5H7Y_exports = {};
__export(module_6F3E5H7Y_exports, {
QuickJSModuleCallbacks: () => QuickJSModuleCallbacks,
QuickJSWASMModule: () => QuickJSWASMModule,
applyBaseRuntimeOptions: () => applyBaseRuntimeOptions,
applyModuleEvalRuntimeOptions: () => applyModuleEvalRuntimeOptions
});
var init_module_6F3E5H7Y = __esm({
"../../matrix/arcrun/registry/components/code/node_modules/quickjs-emscripten-core/dist/module-6F3E5H7Y.mjs"() {
init_chunk_JTKJZQYV();
}
});
// ../../matrix/arcrun/registry/components/code/node_modules/@jitl/quickjs-wasmfile-release-sync/dist/ffi.mjs
var ffi_exports = {};
__export(ffi_exports, {
QuickJSFFI: () => QuickJSFFI
});
var QuickJSFFI;
var init_ffi = __esm({
"../../matrix/arcrun/registry/components/code/node_modules/@jitl/quickjs-wasmfile-release-sync/dist/ffi.mjs"() {
QuickJSFFI = class {
constructor(module) {
this.module = module;
this.DEBUG = false;
this.QTS_Throw = this.module.cwrap("QTS_Throw", "number", ["number", "number"]);
this.QTS_NewError = this.module.cwrap("QTS_NewError", "number", ["number"]);
this.QTS_RuntimeSetMemoryLimit = this.module.cwrap("QTS_RuntimeSetMemoryLimit", null, ["number", "number"]);
this.QTS_RuntimeComputeMemoryUsage = this.module.cwrap("QTS_RuntimeComputeMemoryUsage", "number", ["number", "number"]);
this.QTS_RuntimeDumpMemoryUsage = this.module.cwrap("QTS_RuntimeDumpMemoryUsage", "number", ["number"]);
this.QTS_RecoverableLeakCheck = this.module.cwrap("QTS_RecoverableLeakCheck", "number", []);
this.QTS_BuildIsSanitizeLeak = this.module.cwrap("QTS_BuildIsSanitizeLeak", "number", []);
this.QTS_RuntimeSetMaxStackSize = this.module.cwrap("QTS_RuntimeSetMaxStackSize", null, ["number", "number"]);
this.QTS_GetUndefined = this.module.cwrap("QTS_GetUndefined", "number", []);
this.QTS_GetNull = this.module.cwrap("QTS_GetNull", "number", []);
this.QTS_GetFalse = this.module.cwrap("QTS_GetFalse", "number", []);
this.QTS_GetTrue = this.module.cwrap("QTS_GetTrue", "number", []);
this.QTS_NewHostRef = this.module.cwrap("QTS_NewHostRef", "number", ["number", "number"]);
this.QTS_GetHostRefId = this.module.cwrap("QTS_GetHostRefId", "number", ["number"]);
this.QTS_NewRuntime = this.module.cwrap("QTS_NewRuntime", "number", []);
this.QTS_FreeRuntime = this.module.cwrap("QTS_FreeRuntime", null, ["number"]);
this.QTS_NewContext = this.module.cwrap("QTS_NewContext", "number", ["number", "number"]);
this.QTS_FreeContext = this.module.cwrap("QTS_FreeContext", null, ["number"]);
this.QTS_FreeValuePointer = this.module.cwrap("QTS_FreeValuePointer", null, ["number", "number"]);
this.QTS_FreeValuePointerRuntime = this.module.cwrap("QTS_FreeValuePointerRuntime", null, ["number", "number"]);
this.QTS_FreeVoidPointer = this.module.cwrap("QTS_FreeVoidPointer", null, ["number", "number"]);
this.QTS_FreeCString = this.module.cwrap("QTS_FreeCString", null, ["number", "number"]);
this.QTS_DupValuePointer = this.module.cwrap("QTS_DupValuePointer", "number", ["number", "number"]);
this.QTS_NewObject = this.module.cwrap("QTS_NewObject", "number", ["number"]);
this.QTS_NewObjectProto = this.module.cwrap("QTS_NewObjectProto", "number", ["number", "number"]);
this.QTS_NewArray = this.module.cwrap("QTS_NewArray", "number", ["number"]);
this.QTS_NewArrayBuffer = this.module.cwrap("QTS_NewArrayBuffer", "number", ["number", "number", "number"]);
this.QTS_NewFloat64 = this.module.cwrap("QTS_NewFloat64", "number", ["number", "number"]);
this.QTS_GetFloat64 = this.module.cwrap("QTS_GetFloat64", "number", ["number", "number"]);
this.QTS_NewString = this.module.cwrap("QTS_NewString", "number", ["number", "number"]);
this.QTS_GetString = this.module.cwrap("QTS_GetString", "number", ["number", "number"]);
this.QTS_GetArrayBuffer = this.module.cwrap("QTS_GetArrayBuffer", "number", ["number", "number"]);
this.QTS_GetArrayBufferLength = this.module.cwrap("QTS_GetArrayBufferLength", "number", ["number", "number"]);
this.QTS_NewSymbol = this.module.cwrap("QTS_NewSymbol", "number", ["number", "number", "number"]);
this.QTS_GetSymbolDescriptionOrKey = this.module.cwrap("QTS_GetSymbolDescriptionOrKey", "number", ["number", "number"]);
this.QTS_IsGlobalSymbol = this.module.cwrap("QTS_IsGlobalSymbol", "number", ["number", "number"]);
this.QTS_IsJobPending = this.module.cwrap("QTS_IsJobPending", "number", ["number"]);
this.QTS_ExecutePendingJob = this.module.cwrap("QTS_ExecutePendingJob", "number", ["number", "number", "number"]);
this.QTS_GetProp = this.module.cwrap("QTS_GetProp", "number", ["number", "number", "number"]);
this.QTS_GetPropNumber = this.module.cwrap("QTS_GetPropNumber", "number", ["number", "number", "number"]);
this.QTS_SetProp = this.module.cwrap("QTS_SetProp", null, ["number", "number", "number", "number"]);
this.QTS_DefineProp = this.module.cwrap("QTS_DefineProp", null, ["number", "number", "number", "number", "number", "number", "boolean", "boolean", "boolean"]);
this.QTS_GetOwnPropertyNames = this.module.cwrap("QTS_GetOwnPropertyNames", "number", ["number", "number", "number", "number", "number"]);
this.QTS_Call = this.module.cwrap("QTS_Call", "number", ["number", "number", "number", "number", "number"]);
this.QTS_ResolveException = this.module.cwrap("QTS_ResolveException", "number", ["number", "number"]);
this.QTS_Dump = this.module.cwrap("QTS_Dump", "number", ["number", "number"]);
this.QTS_Eval = this.module.cwrap("QTS_Eval", "number", ["number", "number", "number", "string", "number", "number"]);
this.QTS_GetModuleNamespace = this.module.cwrap("QTS_GetModuleNamespace", "number", ["number", "number"]);
this.QTS_Typeof = this.module.cwrap("QTS_Typeof", "number", ["number", "number"]);
this.QTS_GetLength = this.module.cwrap("QTS_GetLength", "number", ["number", "number", "number"]);
this.QTS_IsEqual = this.module.cwrap("QTS_IsEqual", "number", ["number", "number", "number", "number"]);
this.QTS_GetGlobalObject = this.module.cwrap("QTS_GetGlobalObject", "number", ["number"]);
this.QTS_NewPromiseCapability = this.module.cwrap("QTS_NewPromiseCapability", "number", ["number", "number"]);
this.QTS_PromiseState = this.module.cwrap("QTS_PromiseState", "number", ["number", "number"]);
this.QTS_PromiseResult = this.module.cwrap("QTS_PromiseResult", "number", ["number", "number"]);
this.QTS_TestStringArg = this.module.cwrap("QTS_TestStringArg", null, ["string"]);
this.QTS_GetDebugLogEnabled = this.module.cwrap("QTS_GetDebugLogEnabled", "number", ["number"]);
this.QTS_SetDebugLogEnabled = this.module.cwrap("QTS_SetDebugLogEnabled", null, ["number", "number"]);
this.QTS_BuildIsDebug = this.module.cwrap("QTS_BuildIsDebug", "number", []);
this.QTS_BuildIsAsyncify = this.module.cwrap("QTS_BuildIsAsyncify", "number", []);
this.QTS_NewFunction = this.module.cwrap("QTS_NewFunction", "number", ["number", "string", "number", "boolean", "number"]);
this.QTS_ArgvGetJSValueConstPointer = this.module.cwrap("QTS_ArgvGetJSValueConstPointer", "number", ["number", "number"]);
this.QTS_RuntimeEnableInterruptHandler = this.module.cwrap("QTS_RuntimeEnableInterruptHandler", null, ["number"]);
this.QTS_RuntimeDisableInterruptHandler = this.module.cwrap("QTS_RuntimeDisableInterruptHandler", null, ["number"]);
this.QTS_RuntimeEnableModuleLoader = this.module.cwrap("QTS_RuntimeEnableModuleLoader", null, ["number", "number"]);
this.QTS_RuntimeDisableModuleLoader = this.module.cwrap("QTS_RuntimeDisableModuleLoader", null, ["number"]);
this.QTS_bjson_encode = this.module.cwrap("QTS_bjson_encode", "number", ["number", "number"]);
this.QTS_bjson_decode = this.module.cwrap("QTS_bjson_decode", "number", ["number", "number"]);
}
};
}
});
// ../../matrix/arcrun/registry/components/code/node_modules/@jitl/quickjs-wasmfile-release-sync/dist/emscripten-module.browser.mjs
var emscripten_module_browser_exports = {};
__export(emscripten_module_browser_exports, {
default: () => emscripten_module_browser_default
});
async function QuickJSRaw(moduleArg = {}) {
var moduleRtn;
var c = moduleArg, aa = !!globalThis.window, n = !!globalThis.WorkerGlobalScope;
function q(a) {
a = { log: a || function() {
} };
for (const d of q.Pa) d(a);
return c.quickJSEmscriptenExtensions = a;
}
q.Pa = [];
c.quickjsEmscriptenInit = q;
q.Pa.push((a) => {
a.getWasmMemory = function() {
return r;
};
});
var t = "./this.program", ba = import.meta.url, u = "", v, w;
if (aa || n) {
try {
u = new URL(".", ba).href;
} catch {
}
n && (w = (a) => {
var d = new XMLHttpRequest();
d.open("GET", a, false);
d.responseType = "arraybuffer";
d.send(null);
return new Uint8Array(d.response);
});
v = async (a) => {
a = await fetch(a, { credentials: "same-origin" });
if (a.ok) return a.arrayBuffer();
throw Error(a.status + " : " + a.url);
};
}
var y = console.log.bind(console), z = console.error.bind(console), A, B = false, C, D, E, F, G, H, I, J = false;
function K() {
var a = r.buffer;
c.HEAP8 = F = new Int8Array(a);
new Int16Array(a);
c.HEAPU8 = G = new Uint8Array(a);
new Uint16Array(a);
H = new Int32Array(a);
I = new Uint32Array(a);
new Float32Array(a);
new Float64Array(a);
new BigInt64Array(a);
new BigUint64Array(a);
}
function L(a) {
c.onAbort?.(a);
a = "Aborted(" + a + ")";
z(a);
B = true;
a = new WebAssembly.RuntimeError(a + ". Build with -sASSERTIONS for more info.");
E?.(a);
throw a;
}
var M;
async function ca(a) {
if (!A) try {
var d = await v(a);
return new Uint8Array(d);
} catch {
}
if (a == M && A) a = new Uint8Array(A);
else if (w) a = w(a);
else throw "both async and sync fetching of the wasm failed";
return a;
}
async function da(a, d) {
try {
var b = await ca(a);
return await WebAssembly.instantiate(b, d);
} catch (e) {
z(`failed to asynchronously prepare wasm: ${e}`), L(e);
}
}
async function ea(a) {
var d = M;
if (!A) try {
var b = fetch(d, { credentials: "same-origin" });
return await WebAssembly.instantiateStreaming(b, a);
} catch (e) {
z(`wasm streaming compile failed: ${e}`), z("falling back to ArrayBuffer instantiation");
}
return da(d, a);
}
class N {
name = "ExitStatus";
constructor(a) {
this.message = `Program terminated with exit(${a})`;
this.status = a;
}
}
var O = (a) => {
for (; 0 < a.length; ) a.shift()(c);
}, P = [], fa = [], ha = () => {
var a = c.preRun.shift();
fa.push(a);
}, Q = true, r, ia = new TextDecoder(), ja = (a, d, b, e) => {
b = d + b;
if (e) return b;
for (; a[d] && !(d >= b); ) ++d;
return d;
}, R = (a, d, b) => a ? ia.decode(G.subarray(a, ja(G, a, d, b))) : "", S = 0, ka = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335], la = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334], T = {}, ma = (a) => {
if (!(a instanceof N || "unwind" == a)) throw a;
}, na = (a) => {
C = a;
Q || 0 < S || (c.onExit?.(a), B = true);
throw new N(a);
}, oa = (a) => {
if (!B) try {
a();
} catch (d) {
ma(d);
} finally {
if (!(Q || 0 < S)) try {
C = a = C, na(a);
} catch (d) {
ma(d);
}
}
}, U = (a, d, b) => {
var e = G;
if (!(0 < b)) return 0;
var f = d;
b = d + b - 1;
for (var g = 0; g < a.length; ++g) {
var h = a.codePointAt(g);
if (127 >= h) {
if (d >= b) break;
e[d++] = h;
} else if (2047 >= h) {
if (d + 1 >= b) break;
e[d++] = 192 | h >> 6;
e[d++] = 128 | h & 63;
} else if (65535 >= h) {
if (d + 2 >= b) break;
e[d++] = 224 | h >> 12;
e[d++] = 128 | h >> 6 & 63;
e[d++] = 128 | h & 63;
} else {
if (d + 3 >= b) break;
e[d++] = 240 | h >> 18;
e[d++] = 128 | h >> 12 & 63;
e[d++] = 128 | h >> 6 & 63;
e[d++] = 128 | h & 63;
g++;
}
}
e[d] = 0;
return d - f;
}, V = {}, pa = () => {
if (!W) {
var a = {
USER: "web_user",
LOGNAME: "web_user",
PATH: "/",
PWD: "/",
HOME: "/home/web_user",
LANG: (globalThis.navigator?.language ?? "C").replace("-", "_") + ".UTF-8",
_: t || "./this.program"
}, d;
for (d in V) void 0 === V[d] ? delete a[d] : a[d] = V[d];
var b = [];
for (d in a) b.push(`${d}=${a[d]}`);
W = b;
}
return W;
}, W, X = (a) => {
for (var d = 0, b = 0; b < a.length; ++b) {
var e = a.charCodeAt(b);
127 >= e ? d++ : 2047 >= e ? d += 2 : 55296 <= e && 57343 >= e ? (d += 4, ++b) : d += 3;
}
return d;
}, qa = [null, [], []], ta = (a, d, b, e) => {
var f = { string: (k) => {
var l = 0;
if (null !== k && void 0 !== k && 0 !== k) {
l = X(k) + 1;
var p = Y(l);
U(k, p, l);
l = p;
}
return l;
}, array: (k) => {
var l = Y(k.length);
F.set(k, l);
return l;
} };
a = c["_" + a];
var g = [], h = 0;
if (e) for (var m = 0; m < e.length; m++) {
var x = f[b[m]];
x ? (0 === h && (h = ra()), g[m] = x(e[m])) : g[m] = e[m];
}
b = a(...g);
return b = (function(k) {
0 !== h && sa(h);
return "string" === d ? R(k) : "boolean" === d ? !!k : k;
})(b);
};
c.wasmMemory ? r = c.wasmMemory : r = new WebAssembly.Memory({ initial: (c.INITIAL_MEMORY || 16777216) / 65536, maximum: 32768 });
K();
c.noExitRuntime && (Q = c.noExitRuntime);
c.print && (y = c.print);
c.printErr && (z = c.printErr);
c.wasmBinary && (A = c.wasmBinary);
c.thisProgram && (t = c.thisProgram);
if (c.preInit) for ("function" == typeof c.preInit && (c.preInit = [c.preInit]); 0 < c.preInit.length; ) c.preInit.shift()();
c.cwrap = (a, d, b, e) => {
var f = !b || b.every((g) => "number" === g || "boolean" === g);
return "string" !== d && f && !e ? c["_" + a] : (...g) => ta(a, d, b, g);
};
c.UTF8ToString = R;
c.stringToUTF8 = (a, d, b) => U(a, d, b);
c.lengthBytesUTF8 = X;
var ua, sa, Y, ra, va = { b: (a, d, b, e) => L(`Assertion failed: ${R(a)}, at: ` + [d ? R(d) : "unknown filename", b, e ? R(e) : "unknown function"]), q: () => L(""), l: () => {
Q = false;
S = 0;
}, m: function(a, d) {
a = -9007199254740992 > a || 9007199254740992 < a ? NaN : Number(a);
a = new Date(1e3 * a);
H[d >> 2] = a.getSeconds();
H[d + 4 >> 2] = a.getMinutes();
H[d + 8 >> 2] = a.getHours();
H[d + 12 >> 2] = a.getDate();
H[d + 16 >> 2] = a.getMonth();
H[d + 20 >> 2] = a.getFullYear() - 1900;
H[d + 24 >> 2] = a.getDay();
var b = a.getFullYear();
H[d + 28 >> 2] = (0 !== b % 4 || 0 === b % 100 && 0 !== b % 400 ? la : ka)[a.getMonth()] + a.getDate() - 1 | 0;
H[d + 36 >> 2] = -(60 * a.getTimezoneOffset());
b = new Date(a.getFullYear(), 6, 1).getTimezoneOffset();
var e = new Date(a.getFullYear(), 0, 1).getTimezoneOffset();
H[d + 32 >> 2] = (b != e && a.getTimezoneOffset() == Math.min(e, b)) | 0;
}, j: (a, d) => {
T[a] && (clearTimeout(T[a].id), delete T[a]);
if (!d) return 0;
var b = setTimeout(() => {
delete T[a];
oa(() => ua(a, performance.now()));
}, d);
T[a] = { id: b, Qa: d };
return 0;
}, n: (a, d, b, e) => {
var f = (/* @__PURE__ */ new Date()).getFullYear(), g = new Date(f, 0, 1).getTimezoneOffset();
f = new Date(f, 6, 1).getTimezoneOffset();
I[a >> 2] = 60 * Math.max(g, f);
H[d >> 2] = Number(g != f);
d = (h) => {
var m = Math.abs(h);
return `UTC${0 <= h ? "-" : "+"}${String(Math.floor(m / 60)).padStart(2, "0")}${String(m % 60).padStart(2, "0")}`;
};
a = d(g);
d = d(f);
f < g ? (U(a, b, 17), U(d, e, 17)) : (U(a, e, 17), U(d, b, 17));
}, p: () => Date.now(), k: (a) => {
var d = G.length;
a >>>= 0;
if (2147483648 < a) return false;
for (var b = 1; 4 >= b; b *= 2) {
var e = d * (1 + 0.2 / b);
e = Math.min(e, a + 100663296);
a: {
e = (Math.min(2147483648, 65536 * Math.ceil(Math.max(a, e) / 65536)) - r.buffer.byteLength + 65535) / 65536 | 0;
try {
r.grow(e);
K();
var f = 1;
break a;
} catch (g) {
}
f = void 0;
}
if (f) return true;
}
return false;
}, e: (a, d) => {
var b = 0, e = 0, f;
for (f of pa()) {
var g = d + b;
I[a + e >> 2] = g;
b += U(f, g, Infinity) + 1;
e += 4;
}
return 0;
}, f: (a, d) => {
var b = pa();
I[a >> 2] = b.length;
a = 0;
for (var e of b) a += X(e) + 1;
I[d >> 2] = a;
return 0;
}, d: () => 52, o: function() {
return 70;
}, c: (a, d, b, e) => {
for (var f = 0, g = 0; g < b; g++) {
var h = I[d >> 2], m = I[d + 4 >> 2];
d += 8;
for (var x = 0; x < m; x++) {
var k = a, l = G[h + x], p = qa[k];
0 === l || 10 === l ? (k = 1 === k ? y : z, l = ja(p, 0), l = ia.decode(p.buffer ? p.subarray(0, l) : new Uint8Array(p.slice(0, l))), k(l), p.length = 0) : p.push(l);
}
f += m;
}
I[e >> 2] = f;
return 0;
}, a: r, r: na, s: function(a, d, b, e, f) {
return c.callbacks.callFunction(void 0, a, d, b, e, f);
}, i: function(a) {
return c.callbacks.shouldInterrupt(void 0, a);
}, h: function(a, d, b) {
b = R(b);
return c.callbacks.loadModuleSource(void 0, a, d, b);
}, g: function(a, d, b, e) {
b = R(b);
e = R(e);
return c.callbacks.normalizeModule(void 0, a, d, b, e);
}, t: function(a, d) {
c.callbacks.freeHostRef(void 0, a, d);
} }, Z;
Z = await (async function() {
function a(b) {
b = Z = b.exports;
c._malloc = b.v;
c._QTS_Throw = b.w;
c._QTS_NewError = b.x;
c._QTS_RuntimeSetMemoryLimit = b.y;
c._QTS_RuntimeComputeMemoryUsage = b.z;
c._QTS_RuntimeDumpMemoryUsage = b.A;
c._QTS_RecoverableLeakCheck = b.B;
c._QTS_BuildIsSanitizeLeak = b.C;
c._QTS_RuntimeSetMaxStackSize = b.D;
c._QTS_GetUndefined = b.E;
c._QTS_GetNull = b.F;
c._QTS_GetFalse = b.G;
c._QTS_GetTrue = b.H;
c._QTS_NewHostRef = b.I;
c._QTS_GetHostRefId = b.J;
c._QTS_NewRuntime = b.K;
c._QTS_FreeRuntime = b.L;
c._free = b.M;
c._QTS_NewContext = b.N;
c._QTS_FreeContext = b.O;
c._QTS_FreeValuePointer = b.P;
c._QTS_FreeValuePointerRuntime = b.Q;
c._QTS_FreeVoidPointer = b.R;
c._QTS_FreeCString = b.S;
c._QTS_DupValuePointer = b.T;
c._QTS_NewObject = b.U;
c._QTS_NewObjectProto = b.V;
c._QTS_NewArray = b.W;
c._QTS_NewArrayBuffer = b.X;
c._QTS_NewFloat64 = b.Y;
c._QTS_GetFloat64 = b.Z;
c._QTS_NewString = b._;
c._QTS_GetString = b.$;
c._QTS_GetArrayBuffer = b.aa;
c._QTS_GetArrayBufferLength = b.ba;
c._QTS_NewSymbol = b.ca;
c._QTS_GetSymbolDescriptionOrKey = b.da;
c._QTS_IsGlobalSymbol = b.ea;
c._QTS_IsJobPending = b.fa;
c._QTS_ExecutePendingJob = b.ga;
c._QTS_GetProp = b.ha;
c._QTS_GetPropNumber = b.ia;
c._QTS_SetProp = b.ja;
c._QTS_DefineProp = b.ka;
c._QTS_GetOwnPropertyNames = b.la;
c._QTS_Call = b.ma;
c._QTS_ResolveException = b.na;
c._QTS_Dump = b.oa;
c._QTS_Eval = b.pa;
c._QTS_GetModuleNamespace = b.qa;
c._QTS_Typeof = b.ra;
c._QTS_GetLength = b.sa;
c._QTS_IsEqual = b.ta;
c._QTS_GetGlobalObject = b.ua;
c._QTS_NewPromiseCapability = b.va;
c._QTS_PromiseState = b.wa;
c._QTS_PromiseResult = b.xa;
c._QTS_TestStringArg = b.ya;
c._QTS_GetDebugLogEnabled = b.za;
c._QTS_SetDebugLogEnabled = b.Aa;
c._QTS_BuildIsDebug = b.Ba;
c._QTS_BuildIsAsyncify = b.Ca;
c._QTS_NewFunction = b.Da;
c._QTS_ArgvGetJSValueConstPointer = b.Ea;
c._QTS_RuntimeEnableInterruptHandler = b.Fa;
c._QTS_RuntimeDisableInterruptHandler = b.Ga;
c._QTS_RuntimeEnableModuleLoader = b.Ha;
c._QTS_RuntimeDisableModuleLoader = b.Ia;
c._QTS_bjson_encode = b.Ja;
c._QTS_bjson_decode = b.Ka;
ua = b.La;
sa = b.Ma;
Y = b.Na;
ra = b.Oa;
return Z;
}
var d = { a: va };
if (c.instantiateWasm) return new Promise((b) => {
c.instantiateWasm(d, (e, f) => {
b(a(e, f));
});
});
M ??= c.locateFile ? c.locateFile ? c.locateFile("emscripten-module.wasm", u) : u + "emscripten-module.wasm" : new URL("emscripten-module.wasm", import.meta.url).href;
return a((await ea(d)).instance);
})();
(function() {
function a() {
c.calledRun = true;
if (!B) {
J = true;
Z.u();
D?.(c);
c.onRuntimeInitialized?.();
if (c.postRun) for ("function" == typeof c.postRun && (c.postRun = [c.postRun]); c.postRun.length; ) {
var d = c.postRun.shift();
P.push(d);
}
O(P);
}
}
if (c.preRun) for ("function" == typeof c.preRun && (c.preRun = [c.preRun]); c.preRun.length; ) ha();
O(fa);
c.setStatus ? (c.setStatus("Running..."), setTimeout(() => {
setTimeout(() => c.setStatus(""), 1);
a();
}, 1)) : a();
})();
J ? moduleRtn = c : moduleRtn = new Promise((a, d) => {
D = a;
E = d;
});
;
return moduleRtn;
}
var emscripten_module_browser_default;
var init_emscripten_module_browser = __esm({
"../../matrix/arcrun/registry/components/code/node_modules/@jitl/quickjs-wasmfile-release-sync/dist/emscripten-module.browser.mjs"() {
emscripten_module_browser_default = QuickJSRaw;
}
});
// ../../matrix/arcrun/registry/components/code/node_modules/hono/dist/compose.js
var compose = (middleware, onError, onNotFound) => {
return (context, next) => {
let index = -1;
return dispatch(0);
async function dispatch(i) {
if (i <= index) {
throw new Error("next() called multiple times");
}
index = i;
let res;
let isError = false;
let handler;
if (middleware[i]) {
handler = middleware[i][0][0];
context.req.routeIndex = i;
} else {
handler = i === middleware.length && next || void 0;
}
if (handler) {
try {
res = await handler(context, () => dispatch(i + 1));
} catch (err2) {
if (err2 instanceof Error && onError) {
context.error = err2;
res = await onError(err2, context);
isError = true;
} else {
throw err2;
}
}
} else {
if (context.finalized === false && onNotFound) {
res = await onNotFound(context);
}
}
if (res && (context.finalized === false || isError)) {
context.res = res;
}
return context;
}
};
};
// ../../matrix/arcrun/registry/components/code/node_modules/hono/dist/request/constants.js
var GET_MATCH_RESULT = /* @__PURE__ */ Symbol();
// ../../matrix/arcrun/registry/components/code/node_modules/hono/dist/utils/body.js
var parseBody = async (request, options = /* @__PURE__ */ Object.create(null)) => {
const { all = false, dot = false } = options;
const headers = request instanceof HonoRequest ? request.raw.headers : request.headers;
const contentType = headers.get("Content-Type");
if (contentType?.startsWith("multipart/form-data") || contentType?.startsWith("application/x-www-form-urlencoded")) {
return parseFormData(request, { all, dot });
}
return {};
};
async function parseFormData(request, options) {
const formData = await request.formData();
if (formData) {
return convertFormDataToBodyData(formData, options);
}
return {};
}
function convertFormDataToBodyData(formData, options) {
const form = /* @__PURE__ */ Object.create(null);
formData.forEach((value, key) => {
const shouldParseAllValues = options.all || key.endsWith("[]");
if (!shouldParseAllValues) {
form[key] = value;
} else {
handleParsingAllValues(form, key, value);
}
});
if (options.dot) {
Object.entries(form).forEach(([key, value]) => {
const shouldParseDotValues = key.includes(".");
if (shouldParseDotValues) {
handleParsingNestedValues(form, key, value);
delete form[key];
}
});
}
return form;
}
var handleParsingAllValues = (form, key, value) => {
if (form[key] !== void 0) {
if (Array.isArray(form[key])) {
;
form[key].push(value);
} else {
form[key] = [form[key], value];
}
} else {
if (!key.endsWith("[]")) {
form[key] = value;
} else {
form[key] = [value];
}
}
};
var handleParsingNestedValues = (form, key, value) => {
if (/(?:^|\.)__proto__\./.test(key)) {
return;
}
let nestedForm = form;
const keys = key.split(".");
keys.forEach((key2, index) => {
if (index === keys.length - 1) {
nestedForm[key2] = value;
} else {
if (!nestedForm[key2] || typeof nestedForm[key2] !== "object" || Array.isArray(nestedForm[key2]) || nestedForm[key2] instanceof File) {
nestedForm[key2] = /* @__PURE__ */ Object.create(null);
}
nestedForm = nestedForm[key2];
}
});
};
// ../../matrix/arcrun/registry/components/code/node_modules/hono/dist/utils/url.js
var splitPath = (path) => {
const paths = path.split("/");
if (paths[0] === "") {
paths.shift();
}
return paths;
};
var splitRoutingPath = (routePath) => {
const { groups, path } = extractGroupsFromPath(routePath);
const paths = splitPath(path);
return replaceGroupMarks(paths, groups);
};
var extractGroupsFromPath = (path) => {
const groups = [];
path = path.replace(/\{[^}]+\}/g, (match2, index) => {
const mark = `@${index}`;
groups.push([mark, match2]);
return mark;
});
return { groups, path };
};
var replaceGroupMarks = (paths, groups) => {
for (let i = groups.length - 1; i >= 0; i--) {
const [mark] = groups[i];
for (let j = paths.length - 1; j >= 0; j--) {
if (paths[j].includes(mark)) {
paths[j] = paths[j].replace(mark, groups[i][1]);
break;
}
}
}
return paths;
};
var patternCache = {};
var getPattern = (label, next) => {
if (label === "*") {
return "*";
}
const match2 = label.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
if (match2) {
const cacheKey = `${label}#${next}`;
if (!patternCache[cacheKey]) {
if (match2[2]) {
patternCache[cacheKey] = next && next[0] !== ":" && next[0] !== "*" ? [cacheKey, match2[1], new RegExp(`^${match2[2]}(?=/${next})`)] : [label, match2[1], new RegExp(`^${match2[2]}$`)];
} else {
patternCache[cacheKey] = [label, match2[1], true];
}
}
return patternCache[cacheKey];
}
return null;
};
var tryDecode = (str, decoder) => {
try {
return decoder(str);
} catch {
return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match2) => {
try {
return decoder(match2);
} catch {
return match2;
}
});
}
};
var tryDecodeURI = (str) => tryDecode(str, decodeURI);
var getPath = (request) => {
const url = request.url;
const start = url.indexOf("/", url.indexOf(":") + 4);
let i = start;
for (; i < url.length; i++) {
const charCode = url.charCodeAt(i);
if (charCode === 37) {
const queryIndex = url.indexOf("?", i);
const hashIndex = url.indexOf("#", i);
const end = queryIndex === -1 ? hashIndex === -1 ? void 0 : hashIndex : hashIndex === -1 ? queryIndex : Math.min(queryIndex, hashIndex);
const path = url.slice(start, end);
return tryDecodeURI(path.includes("%25") ? path.replace(/%25/g, "%2525") : path);
} else if (charCode === 63 || charCode === 35) {
break;
}
}
return url.slice(start, i);
};
var getPathNoStrict = (request) => {
const result = getPath(request);
return result.length > 1 && result.at(-1) === "/" ? result.slice(0, -1) : result;
};
var mergePath = (base, sub, ...rest) => {
if (rest.length) {
sub = mergePath(sub, ...rest);
}
return `${base?.[0] === "/" ? "" : "/"}${base}${sub === "/" ? "" : `${base?.at(-1) === "/" ? "" : "/"}${sub?.[0] === "/" ? sub.slice(1) : sub}`}`;
};
var checkOptionalParameter = (path) => {
if (path.charCodeAt(path.length - 1) !== 63 || !path.includes(":")) {
return null;
}
const segments = path.split("/");
const results = [];
let basePath = "";
segments.forEach((segment) => {
if (segment !== "" && !/\:/.test(segment)) {
basePath += "/" + segment;
} else if (/\:/.test(segment)) {
if (/\?/.test(segment)) {
if (results.length === 0 && basePath === "") {
results.push("/");
} else {
results.push(basePath);
}
const optionalSegment = segment.replace("?", "");
basePath += "/" + optionalSegment;
results.push(basePath);
} else {
basePath += "/" + segment;
}
}
});
return results.filter((v, i, a) => a.indexOf(v) === i);
};
var _decodeURI = (value) => {
if (!/[%+]/.test(value)) {
return value;
}
if (value.indexOf("+") !== -1) {
value = value.replace(/\+/g, " ");
}
return value.indexOf("%") !== -1 ? tryDecode(value, decodeURIComponent_) : value;
};
var _getQueryParam = (url, key, multiple) => {
let encoded;
if (!multiple && key && !/[%+]/.test(key)) {
let keyIndex2 = url.indexOf("?", 8);
if (keyIndex2 === -1) {
return void 0;
}
if (!url.startsWith(key, keyIndex2 + 1)) {
keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
}
while (keyIndex2 !== -1) {
const trailingKeyCode = url.charCodeAt(keyIndex2 + key.length + 1);
if (trailingKeyCode === 61) {
const valueIndex = keyIndex2 + key.length + 2;
const endIndex = url.indexOf("&", valueIndex);
return _decodeURI(url.slice(valueIndex, endIndex === -1 ? void 0 : endIndex));
} else if (trailingKeyCode == 38 || isNaN(trailingKeyCode)) {
return "";
}
keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
}
encoded = /[%+]/.test(url);
if (!encoded) {
return void 0;
}
}
const results = {};
encoded ??= /[%+]/.test(url);
let keyIndex = url.indexOf("?", 8);
while (keyIndex !== -1) {
const nextKeyIndex = url.indexOf("&", keyIndex + 1);
let valueIndex = url.indexOf("=", keyIndex);
if (valueIndex > nextKeyIndex && nextKeyIndex !== -1) {
valueIndex = -1;
}
let name = url.slice(
keyIndex + 1,
valueIndex === -1 ? nextKeyIndex === -1 ? void 0 : nextKeyIndex : valueIndex
);
if (encoded) {
name = _decodeURI(name);
}
keyIndex = nextKeyIndex;
if (name === "") {
continue;
}
let value;
if (valueIndex === -1) {
value = "";
} else {
value = url.slice(valueIndex + 1, nextKeyIndex === -1 ? void 0 : nextKeyIndex);
if (encoded) {
value = _decodeURI(value);
}
}
if (multiple) {
if (!(results[name] && Array.isArray(results[name]))) {
results[name] = [];
}
;
results[name].push(value);
} else {
results[name] ??= value;
}
}
return key ? results[key] : results;
};
var getQueryParam = _getQueryParam;
var getQueryParams = (url, key) => {
return _getQueryParam(url, key, true);
};
var decodeURIComponent_ = decodeURIComponent;
// ../../matrix/arcrun/registry/components/code/node_modules/hono/dist/request.js
var tryDecodeURIComponent = (str) => tryDecode(str, decodeURIComponent_);
var HonoRequest = class {
/**
* `.raw` can get the raw Request object.
*
* @see {@link https://hono.dev/docs/api/request#raw}
*
* @example
* ```ts
* // For Cloudflare Workers
* app.post('/', async (c) => {
* const metadata = c.req.raw.cf?.hostMetadata?
* ...
* })
* ```
*/
raw;
#validatedData;
// Short name of validatedData
#matchResult;
routeIndex = 0;
/**
* `.path` can get the pathname of the request.
*
* @see {@link https://hono.dev/docs/api/request#path}
*
* @example
* ```ts
* app.get('/about/me', (c) => {
* const pathname = c.req.path // `/about/me`
* })
* ```
*/
path;
bodyCache = {};
constructor(request, path = "/", matchResult = [[]]) {
this.raw = request;
this.path = path;
this.#matchResult = matchResult;
this.#validatedData = {};
}
param(key) {
return key ? this.#getDecodedParam(key) : this.#getAllDecodedParams();
}
#getDecodedParam(key) {
const paramKey = this.#matchResult[0][this.routeIndex][1][key];
const param = this.#getParamValue(paramKey);
return param && /\%/.test(param) ? tryDecodeURIComponent(param) : param;
}
#getAllDecodedParams() {
const decoded = {};
const keys = Object.keys(this.#matchResult[0][this.routeIndex][1]);
for (const key of keys) {
const value = this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key]);
if (value !== void 0) {
decoded[key] = /\%/.test(value) ? tryDecodeURIComponent(value) : value;
}
}
return decoded;
}
#getParamValue(paramKey) {
return this.#matchResult[1] ? this.#matchResult[1][paramKey] : paramKey;
}
query(key) {
return getQueryParam(this.url, key);
}
queries(key) {
return getQueryParams(this.url, key);
}
header(name) {
if (name) {
return this.raw.headers.get(name) ?? void 0;
}
const headerData = {};
this.raw.headers.forEach((value, key) => {
headerData[key] = value;
});
return headerData;
}
async parseBody(options) {
return parseBody(this, options);
}
#cachedBody = (key) => {
const { bodyCache, raw: raw2 } = this;
const cachedBody = bodyCache[key];
if (cachedBody) {
return cachedBody;
}
const anyCachedKey = Object.keys(bodyCache)[0];
if (anyCachedKey) {
return bodyCache[anyCachedKey].then((body) => {
if (anyCachedKey === "json") {
body = JSON.stringify(body);
}
return new Response(body)[key]();
});
}
return bodyCache[key] = raw2[key]();
};
/**
* `.json()` can parse Request body of type `application/json`
*
* @see {@link https://hono.dev/docs/api/request#json}
*
* @example
* ```ts
* app.post('/entry', async (c) => {
* const body = await c.req.json()
* })
* ```
*/
json() {
return this.#cachedBody("text").then((text) => JSON.parse(text));
}
/**
* `.text()` can parse Request body of type `text/plain`
*
* @see {@link https://hono.dev/docs/api/request#text}
*
* @example
* ```ts
* app.post('/entry', async (c) => {
* const body = await c.req.text()
* })
* ```
*/
text() {
return this.#cachedBody("text");
}
/**
* `.arrayBuffer()` parse Request body as an `ArrayBuffer`
*
* @see {@link https://hono.dev/docs/api/request#arraybuffer}
*
* @example
* ```ts
* app.post('/entry', async (c) => {
* const body = await c.req.arrayBuffer()
* })
* ```
*/
arrayBuffer() {
return this.#cachedBody("arrayBuffer");
}
/**
* `.bytes()` parses the request body as a `Uint8Array`.
*
* @see {@link https://hono.dev/docs/api/request#bytes}
*
* @example
* ```ts
* app.post('/entry', async (c) => {
* const body = await c.req.bytes()
* })
* ```
*/
bytes() {
return this.#cachedBody("arrayBuffer").then((buffer) => new Uint8Array(buffer));
}
/**
* Parses the request body as a `Blob`.
* @example
* ```ts
* app.post('/entry', async (c) => {
* const body = await c.req.blob();
* });
* ```
* @see https://hono.dev/docs/api/request#blob
*/
blob() {
return this.#cachedBody("blob");
}
/**
* Parses the request body as `FormData`.
* @example
* ```ts
* app.post('/entry', async (c) => {
* const body = await c.req.formData();
* });
* ```
* @see https://hono.dev/docs/api/request#formdata
*/
formData() {
return this.#cachedBody("formData");
}
/**
* Adds validated data to the request.
*
* @param target - The target of the validation.
* @param data - The validated data to add.
*/
addValidatedData(target, data) {
this.#validatedData[target] = data;
}
valid(target) {
return this.#validatedData[target];
}
/**
* `.url()` can get the request url strings.
*
* @see {@link https://hono.dev/docs/api/request#url}
*
* @example
* ```ts
* app.get('/about/me', (c) => {
* const url = c.req.url // `http://localhost:8787/about/me`
* ...
* })
* ```
*/
get url() {
return this.raw.url;
}
/**
* `.method()` can get the method name of the request.
*
* @see {@link https://hono.dev/docs/api/request#method}
*
* @example
* ```ts
* app.get('/about/me', (c) => {
* const method = c.req.method // `GET`
* })
* ```
*/
get method() {
return this.raw.method;
}
get [GET_MATCH_RESULT]() {
return this.#matchResult;
}
/**
* `.matchedRoutes()` can return a matched route in the handler
*
* @deprecated
*
* Use matchedRoutes helper defined in "hono/route" instead.
*
* @see {@link https://hono.dev/docs/api/request#matchedroutes}
*
* @example
* ```ts
* app.use('*', async function logger(c, next) {
* await next()
* c.req.matchedRoutes.forEach(({ handler, method, path }, i) => {
* const name = handler.name || (handler.length < 2 ? '[handler]' : '[middleware]')
* console.log(
* method,
* ' ',
* path,
* ' '.repeat(Math.max(10 - path.length, 0)),
* name,
* i === c.req.routeIndex ? '<- respond from here' : ''
* )
* })
* })
* ```
*/
get matchedRoutes() {
return this.#matchResult[0].map(([[, route]]) => route);
}
/**
* `routePath()` can retrieve the path registered within the handler
*
* @deprecated
*
* Use routePath helper defined in "hono/route" instead.
*
* @see {@link https://hono.dev/docs/api/request#routepath}
*
* @example
* ```ts
* app.get('/posts/:id', (c) => {
* return c.json({ path: c.req.routePath })
* })
* ```
*/
get routePath() {
return this.#matchResult[0].map(([[, route]]) => route)[this.routeIndex].path;
}
};
// ../../matrix/arcrun/registry/components/code/node_modules/hono/dist/utils/html.js
var HtmlEscapedCallbackPhase = {
Stringify: 1,
BeforeStream: 2,
Stream: 3
};
var raw = (value, callbacks) => {
const escapedString = new String(value);
escapedString.isEscaped = true;
escapedString.callbacks = callbacks;
return escapedString;
};
var resolveCallback = async (str, phase, preserveCallbacks, context, buffer) => {
if (typeof str === "object" && !(str instanceof String)) {
if (!(str instanceof Promise)) {
str = str.toString();
}
if (str instanceof Promise) {
str = await str;
}
}
const callbacks = str.callbacks;
if (!callbacks?.length) {
return Promise.resolve(str);
}
if (buffer) {
buffer[0] += str;
} else {
buffer = [str];
}
const resStr = Promise.all(callbacks.map((c) => c({ phase, buffer, context }))).then(
(res) => Promise.all(
res.filter(Boolean).map((str2) => resolveCallback(str2, phase, false, context, buffer))
).then(() => buffer[0])
);
if (preserveCallbacks) {
return raw(await resStr, callbacks);
} else {
return resStr;
}
};
// ../../matrix/arcrun/registry/components/code/node_modules/hono/dist/context.js
var TEXT_PLAIN = "text/plain; charset=UTF-8";
var setDefaultContentType = (contentType, headers) => {
return {
"Content-Type": contentType,
...headers
};
};
var createResponseInstance = (body, init) => new Response(body, init);
var Context = class {
#rawRequest;
#req;
/**
* `.env` can get bindings (environment variables, secrets, KV namespaces, D1 database, R2 bucket etc.) in Cloudflare Workers.
*
* @see {@link https://hono.dev/docs/api/context#env}
*
* @example
* ```ts
* // Environment object for Cloudflare Workers
* app.get('*', async c => {
* const counter = c.env.COUNTER
* })
* ```
*/
env = {};
#var;
finalized = false;
/**
* `.error` can get the error object from the middleware if the Handler throws an error.
*
* @see {@link https://hono.dev/docs/api/context#error}
*
* @example
* ```ts
* app.use('*', async (c, next) => {
* await next()
* if (c.error) {
* // do something...
* }
* })
* ```
*/
error;
#status;
#executionCtx;
#res;
#layout;
#renderer;
#notFoundHandler;
#preparedHeaders;
#matchResult;
#path;
/**
* Creates an instance of the Context class.
*
* @param req - The Request object.
* @param options - Optional configuration options for the context.
*/
constructor(req, options) {
this.#rawRequest = req;
if (options) {
this.#executionCtx = options.executionCtx;
this.env = options.env;
this.#notFoundHandler = options.notFoundHandler;
this.#path = options.path;
this.#matchResult = options.matchResult;
}
}
/**
* `.req` is the instance of {@link HonoRequest}.
*/
get req() {
this.#req ??= new HonoRequest(this.#rawRequest, this.#path, this.#matchResult);
return this.#req;
}
/**
* @see {@link https://hono.dev/docs/api/context#event}
* The FetchEvent associated with the current request.
*
* @throws Will throw an error if the context does not have a FetchEvent.
*/
get event() {
if (this.#executionCtx && "respondWith" in this.#executionCtx) {
return this.#executionCtx;
} else {
throw Error("This context has no FetchEvent");
}
}
/**
* @see {@link https://hono.dev/docs/api/context#executionctx}
* The ExecutionContext associated with the current request.
*
* @throws Will throw an error if the context does not have an ExecutionContext.
*/
get executionCtx() {
if (this.#executionCtx) {
return this.#executionCtx;
} else {
throw Error("This context has no ExecutionContext");
}
}
/**
* @see {@link https://hono.dev/docs/api/context#res}
* The Response object for the current request.
*/
get res() {
return this.#res ||= createResponseInstance(null, {
headers: this.#preparedHeaders ??= new Headers()
});
}
/**
* Sets the Response object for the current request.
*
* @param _res - The Response object to set.
*/
set res(_res) {
if (this.#res && _res) {
_res = createResponseInstance(_res.body, _res);
for (const [k, v] of this.#res.headers.entries()) {
if (k === "content-type") {
continue;
}
if (k === "set-cookie") {
const cookies = this.#res.headers.getSetCookie();
_res.headers.delete("set-cookie");
for (const cookie of cookies) {
_res.headers.append("set-cookie", cookie);
}
} else {
_res.headers.set(k, v);
}
}
}
this.#res = _res;
this.finalized = true;
}
/**
* `.render()` can create a response within a layout.
*
* @see {@link https://hono.dev/docs/api/context#render-setrenderer}
*
* @example
* ```ts
* app.get('/', (c) => {
* return c.render('Hello!')
* })
* ```
*/
render = (...args) => {
this.#renderer ??= (content) => this.html(content);
return this.#renderer(...args);
};
/**
* Sets the layout for the response.
*
* @param layout - The layout to set.
* @returns The layout function.
*/
setLayout = (layout) => this.#layout = layout;
/**
* Gets the current layout for the response.
*
* @returns The current layout function.
*/
getLayout = () => this.#layout;
/**
* `.setRenderer()` can set the layout in the custom middleware.
*
* @see {@link https://hono.dev/docs/api/context#render-setrenderer}
*
* @example
* ```tsx
* app.use('*', async (c, next) => {
* c.setRenderer((content) => {
* return c.html(
* <html>
* <body>
* <p>{content}</p>
* </body>
* </html>
* )
* })
* await next()
* })
* ```
*/
setRenderer = (renderer) => {
this.#renderer = renderer;
};
/**
* `.header()` can set headers.
*
* @see {@link https://hono.dev/docs/api/context#header}
*
* @example
* ```ts
* app.get('/welcome', (c) => {
* // Set headers
* c.header('X-Message', 'Hello!')
* c.header('Content-Type', 'text/plain')
*
* return c.body('Thank you for coming')
* })
* ```
*/
header = (name, value, options) => {
if (this.finalized) {
this.#res = createResponseInstance(this.#res.body, this.#res);
}
const headers = this.#res ? this.#res.headers : this.#preparedHeaders ??= new Headers();
if (value === void 0) {
headers.delete(name);
} else if (options?.append) {
headers.append(name, value);
} else {
headers.set(name, value);
}
};
status = (status) => {
this.#status = status;
};
/**
* `.set()` can set the value specified by the key.
*
* @see {@link https://hono.dev/docs/api/context#set-get}
*
* @example
* ```ts
* app.use('*', async (c, next) => {
* c.set('message', 'Hono is hot!!')
* await next()
* })
* ```
*/
set = (key, value) => {
this.#var ??= /* @__PURE__ */ new Map();
this.#var.set(key, value);
};
/**
* `.get()` can use the value specified by the key.
*
* @see {@link https://hono.dev/docs/api/context#set-get}
*
* @example
* ```ts
* app.get('/', (c) => {
* const message = c.get('message')
* return c.text(`The message is "${message}"`)
* })
* ```
*/
get = (key) => {
return this.#var ? this.#var.get(key) : void 0;
};
/**
* `.var` can access the value of a variable.
*
* @see {@link https://hono.dev/docs/api/context#var}
*
* @example
* ```ts
* const result = c.var.client.oneMethod()
* ```
*/
// c.var.propName is a read-only
get var() {
if (!this.#var) {
return {};
}
return Object.fromEntries(this.#var);
}
#newResponse(data, arg, headers) {
const responseHeaders = this.#res ? new Headers(this.#res.headers) : this.#preparedHeaders ?? new Headers();
if (typeof arg === "object" && "headers" in arg) {
const argHeaders = arg.headers instanceof Headers ? arg.headers : new Headers(arg.headers);
for (const [key, value] of argHeaders) {
if (key.toLowerCase() === "set-cookie") {
responseHeaders.append(key, value);
} else {
responseHeaders.set(key, value);
}
}
}
if (headers) {
for (const [k, v] of Object.entries(headers)) {
if (typeof v === "string") {
responseHeaders.set(k, v);
} else {
responseHeaders.delete(k);
for (const v2 of v) {
responseHeaders.append(k, v2);
}
}
}
}
const status = typeof arg === "number" ? arg : arg?.status ?? this.#status;
return createResponseInstance(data, { status, headers: responseHeaders });
}
newResponse = (...args) => this.#newResponse(...args);
/**
* `.body()` can return the HTTP response.
* You can set headers with `.header()` and set HTTP status code with `.status`.
* This can also be set in `.text()`, `.json()` and so on.
*
* @see {@link https://hono.dev/docs/api/context#body}
*
* @example
* ```ts
* app.get('/welcome', (c) => {
* // Set headers
* c.header('X-Message', 'Hello!')
* c.header('Content-Type', 'text/plain')
* // Set HTTP status code
* c.status(201)
*
* // Return the response body
* return c.body('Thank you for coming')
* })
* ```
*/
body = (data, arg, headers) => this.#newResponse(data, arg, headers);
/**
* `.text()` can render text as `Content-Type:text/plain`.
*
* @see {@link https://hono.dev/docs/api/context#text}
*
* @example
* ```ts
* app.get('/say', (c) => {
* return c.text('Hello!')
* })
* ```
*/
text = (text, arg, headers) => {
return !this.#preparedHeaders && !this.#status && !arg && !headers && !this.finalized ? new Response(text) : this.#newResponse(
text,
arg,
setDefaultContentType(TEXT_PLAIN, headers)
);
};
/**
* `.json()` can render JSON as `Content-Type:application/json`.
*
* @see {@link https://hono.dev/docs/api/context#json}
*
* @example
* ```ts
* app.get('/api', (c) => {
* return c.json({ message: 'Hello!' })
* })
* ```
*/
json = (object, arg, headers) => {
return this.#newResponse(
JSON.stringify(object),
arg,
setDefaultContentType("application/json", headers)
);
};
html = (html, arg, headers) => {
const res = (html2) => this.#newResponse(html2, arg, setDefaultContentType("text/html; charset=UTF-8", headers));
return typeof html === "object" ? resolveCallback(html, HtmlEscapedCallbackPhase.Stringify, false, {}).then(res) : res(html);
};
/**
* `.redirect()` can Redirect, default status code is 302.
*
* @see {@link https://hono.dev/docs/api/context#redirect}
*
* @example
* ```ts
* app.get('/redirect', (c) => {
* return c.redirect('/')
* })
* app.get('/redirect-permanently', (c) => {
* return c.redirect('/', 301)
* })
* ```
*/
redirect = (location, status) => {
const locationString = String(location);
this.header(
"Location",
// Multibyes should be encoded
// eslint-disable-next-line no-control-regex
!/[^\x00-\xFF]/.test(locationString) ? locationString : encodeURI(locationString)
);
return this.newResponse(null, status ?? 302);
};
/**
* `.notFound()` can return the Not Found Response.
*
* @see {@link https://hono.dev/docs/api/context#notfound}
*
* @example
* ```ts
* app.get('/notfound', (c) => {
* return c.notFound()
* })
* ```
*/
notFound = () => {
this.#notFoundHandler ??= () => createResponseInstance();
return this.#notFoundHandler(this);
};
};
// ../../matrix/arcrun/registry/components/code/node_modules/hono/dist/router.js
var METHOD_NAME_ALL = "ALL";
var METHOD_NAME_ALL_LOWERCASE = "all";
var METHODS = ["get", "post", "put", "delete", "options", "patch"];
var MESSAGE_MATCHER_IS_ALREADY_BUILT = "Can not add a route since the matcher is already built.";
var UnsupportedPathError = class extends Error {
};
// ../../matrix/arcrun/registry/components/code/node_modules/hono/dist/utils/constants.js
var COMPOSED_HANDLER = "__COMPOSED_HANDLER";
// ../../matrix/arcrun/registry/components/code/node_modules/hono/dist/hono-base.js
var notFoundHandler = (c) => {
return c.text("404 Not Found", 404);
};
var errorHandler = (err2, c) => {
if ("getResponse" in err2) {
const res = err2.getResponse();
return c.newResponse(res.body, res);
}
console.error(err2);
return c.text("Internal Server Error", 500);
};
var Hono = class _Hono {
get;
post;
put;
delete;
options;
patch;
all;
on;
use;
/*
This class is like an abstract class and does not have a router.
To use it, inherit the class and implement router in the constructor.
*/
router;
getPath;
// Cannot use `#` because it requires visibility at JavaScript runtime.
_basePath = "/";
#path = "/";
routes = [];
constructor(options = {}) {
const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE];
allMethods.forEach((method) => {
this[method] = (args1, ...args) => {
if (typeof args1 === "string") {
this.#path = args1;
} else {
this.#addRoute(method, this.#path, args1);
}
args.forEach((handler) => {
this.#addRoute(method, this.#path, handler);
});
return this;
};
});
this.on = (method, path, ...handlers) => {
for (const p of [path].flat()) {
this.#path = p;
for (const m of [method].flat()) {
handlers.map((handler) => {
this.#addRoute(m.toUpperCase(), this.#path, handler);
});
}
}
return this;
};
this.use = (arg1, ...handlers) => {
if (typeof arg1 === "string") {
this.#path = arg1;
} else {
this.#path = "*";
handlers.unshift(arg1);
}
handlers.forEach((handler) => {
this.#addRoute(METHOD_NAME_ALL, this.#path, handler);
});
return this;
};
const { strict, ...optionsWithoutStrict } = options;
Object.assign(this, optionsWithoutStrict);
this.getPath = strict ?? true ? options.getPath ?? getPath : getPathNoStrict;
}
#clone() {
const clone = new _Hono({
router: this.router,
getPath: this.getPath
});
clone.errorHandler = this.errorHandler;
clone.#notFoundHandler = this.#notFoundHandler;
clone.routes = this.routes;
return clone;
}
#notFoundHandler = notFoundHandler;
// Cannot use `#` because it requires visibility at JavaScript runtime.
errorHandler = errorHandler;
/**
* `.route()` allows grouping other Hono instance in routes.
*
* @see {@link https://hono.dev/docs/api/routing#grouping}
*
* @param {string} path - base Path
* @param {Hono} app - other Hono instance
* @returns {Hono} routed Hono instance
*
* @example
* ```ts
* const app = new Hono()
* const app2 = new Hono()
*
* app2.get("/user", (c) => c.text("user"))
* app.route("/api", app2) // GET /api/user
* ```
*/
route(path, app2) {
const subApp = this.basePath(path);
app2.routes.map((r) => {
let handler;
if (app2.errorHandler === errorHandler) {
handler = r.handler;
} else {
handler = async (c, next) => (await compose([], app2.errorHandler)(c, () => r.handler(c, next))).res;
handler[COMPOSED_HANDLER] = r.handler;
}
subApp.#addRoute(r.method, r.path, handler, r.basePath);
});
return this;
}
/**
* `.basePath()` allows base paths to be specified.
*
* @see {@link https://hono.dev/docs/api/routing#base-path}
*
* @param {string} path - base Path
* @returns {Hono} changed Hono instance
*
* @example
* ```ts
* const api = new Hono().basePath('/api')
* ```
*/
basePath(path) {
const subApp = this.#clone();
subApp._basePath = mergePath(this._basePath, path);
return subApp;
}
/**
* `.onError()` handles an error and returns a customized Response.
*
* @see {@link https://hono.dev/docs/api/hono#error-handling}
*
* @param {ErrorHandler} handler - request Handler for error
* @returns {Hono} changed Hono instance
*
* @example
* ```ts
* app.onError((err, c) => {
* console.error(`${err}`)
* return c.text('Custom Error Message', 500)
* })
* ```
*/
onError = (handler) => {
this.errorHandler = handler;
return this;
};
/**
* `.notFound()` allows you to customize a Not Found Response.
*
* @see {@link https://hono.dev/docs/api/hono#not-found}
*
* @param {NotFoundHandler} handler - request handler for not-found
* @returns {Hono} changed Hono instance
*
* @example
* ```ts
* app.notFound((c) => {
* return c.text('Custom 404 Message', 404)
* })
* ```
*/
notFound = (handler) => {
this.#notFoundHandler = handler;
return this;
};
/**
* `.mount()` allows you to mount applications built with other frameworks into your Hono application.
*
* @see {@link https://hono.dev/docs/api/hono#mount}
*
* @param {string} path - base Path
* @param {Function} applicationHandler - other Request Handler
* @param {MountOptions} [options] - options of `.mount()`
* @returns {Hono} mounted Hono instance
*
* @example
* ```ts
* import { Router as IttyRouter } from 'itty-router'
* import { Hono } from 'hono'
* // Create itty-router application
* const ittyRouter = IttyRouter()
* // GET /itty-router/hello
* ittyRouter.get('/hello', () => new Response('Hello from itty-router'))
*
* const app = new Hono()
* app.mount('/itty-router', ittyRouter.handle)
* ```
*
* @example
* ```ts
* const app = new Hono()
* // Send the request to another application without modification.
* app.mount('/app', anotherApp, {
* replaceRequest: (req) => req,
* })
* ```
*/
mount(path, applicationHandler, options) {
let replaceRequest;
let optionHandler;
if (options) {
if (typeof options === "function") {
optionHandler = options;
} else {
optionHandler = options.optionHandler;
if (options.replaceRequest === false) {
replaceRequest = (request) => request;
} else {
replaceRequest = options.replaceRequest;
}
}
}
const getOptions = optionHandler ? (c) => {
const options2 = optionHandler(c);
return Array.isArray(options2) ? options2 : [options2];
} : (c) => {
let executionContext = void 0;
try {
executionContext = c.executionCtx;
} catch {
}
return [c.env, executionContext];
};
replaceRequest ||= (() => {
const mergedPath = mergePath(this._basePath, path);
const pathPrefixLength = mergedPath === "/" ? 0 : mergedPath.length;
return (request) => {
const url = new URL(request.url);
url.pathname = this.getPath(request).slice(pathPrefixLength) || "/";
return new Request(url, request);
};
})();
const handler = async (c, next) => {
const res = await applicationHandler(replaceRequest(c.req.raw), ...getOptions(c));
if (res) {
return res;
}
await next();
};
this.#addRoute(METHOD_NAME_ALL, mergePath(path, "*"), handler);
return this;
}
#addRoute(method, path, handler, baseRoutePath) {
method = method.toUpperCase();
path = mergePath(this._basePath, path);
const r = {
basePath: baseRoutePath !== void 0 ? mergePath(this._basePath, baseRoutePath) : this._basePath,
path,
method,
handler
};
this.router.add(method, path, [handler, r]);
this.routes.push(r);
}
#handleError(err2, c) {
if (err2 instanceof Error) {
return this.errorHandler(err2, c);
}
throw err2;
}
#dispatch(request, executionCtx, env, method) {
if (method === "HEAD") {
return (async () => new Response(null, await this.#dispatch(request, executionCtx, env, "GET")))();
}
const path = this.getPath(request, { env });
const matchResult = this.router.match(method, path);
const c = new Context(request, {
path,
matchResult,
env,
executionCtx,
notFoundHandler: this.#notFoundHandler
});
if (matchResult[0].length === 1) {
let res;
try {
res = matchResult[0][0][0][0](c, async () => {
c.res = await this.#notFoundHandler(c);
});
} catch (err2) {
return this.#handleError(err2, c);
}
return res instanceof Promise ? res.then(
(resolved) => resolved || (c.finalized ? c.res : this.#notFoundHandler(c))
).catch((err2) => this.#handleError(err2, c)) : res ?? this.#notFoundHandler(c);
}
const composed = compose(matchResult[0], this.errorHandler, this.#notFoundHandler);
return (async () => {
try {
const context = await composed(c);
if (!context.finalized) {
throw new Error(
"Context is not finalized. Did you forget to return a Response object or `await next()`?"
);
}
return context.res;
} catch (err2) {
return this.#handleError(err2, c);
}
})();
}
/**
* `.fetch()` will be entry point of your app.
*
* @see {@link https://hono.dev/docs/api/hono#fetch}
*
* @param {Request} request - request Object of request
* @param {Env} Env - env Object
* @param {ExecutionContext} - context of execution
* @returns {Response | Promise<Response>} response of request
*
*/
fetch = (request, ...rest) => {
return this.#dispatch(request, rest[1], rest[0], request.method);
};
/**
* `.request()` is a useful method for testing.
* You can pass a URL or pathname to send a GET request.
* app will return a Response object.
* ```ts
* test('GET /hello is ok', async () => {
* const res = await app.request('/hello')
* expect(res.status).toBe(200)
* })
* ```
* @see https://hono.dev/docs/api/hono#request
*/
request = (input, requestInit, Env, executionCtx) => {
if (input instanceof Request) {
return this.fetch(requestInit ? new Request(input, requestInit) : input, Env, executionCtx);
}
input = input.toString();
return this.fetch(
new Request(
/^https?:\/\//.test(input) ? input : `http://localhost${mergePath("/", input)}`,
requestInit
),
Env,
executionCtx
);
};
/**
* `.fire()` automatically adds a global fetch event listener.
* This can be useful for environments that adhere to the Service Worker API, such as non-ES module Cloudflare Workers.
* @deprecated
* Use `fire` from `hono/service-worker` instead.
* ```ts
* import { Hono } from 'hono'
* import { fire } from 'hono/service-worker'
*
* const app = new Hono()
* // ...
* fire(app)
* ```
* @see https://hono.dev/docs/api/hono#fire
* @see https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API
* @see https://developers.cloudflare.com/workers/reference/migrate-to-module-workers/
*/
fire = () => {
addEventListener("fetch", (event) => {
event.respondWith(this.#dispatch(event.request, event, void 0, event.request.method));
});
};
};
// ../../matrix/arcrun/registry/components/code/node_modules/hono/dist/router/reg-exp-router/matcher.js
var emptyParam = [];
function match(method, path) {
const matchers = this.buildAllMatchers();
const match2 = ((method2, path2) => {
const matcher = matchers[method2] || matchers[METHOD_NAME_ALL];
const staticMatch = matcher[2][path2];
if (staticMatch) {
return staticMatch;
}
const match3 = path2.match(matcher[0]);
if (!match3) {
return [[], emptyParam];
}
const index = match3.indexOf("", 1);
return [matcher[1][index], match3];
});
this.match = match2;
return match2(method, path);
}
// ../../matrix/arcrun/registry/components/code/node_modules/hono/dist/router/reg-exp-router/node.js
var LABEL_REG_EXP_STR = "[^/]+";
var ONLY_WILDCARD_REG_EXP_STR = ".*";
var TAIL_WILDCARD_REG_EXP_STR = "(?:|/.*)";
var PATH_ERROR = /* @__PURE__ */ Symbol();
var regExpMetaChars = new Set(".\\+*[^]$()");
function compareKey(a, b) {
if (a.length === 1) {
return b.length === 1 ? a < b ? -1 : 1 : -1;
}
if (b.length === 1) {
return 1;
}
if (a === ONLY_WILDCARD_REG_EXP_STR || a === TAIL_WILDCARD_REG_EXP_STR) {
return 1;
} else if (b === ONLY_WILDCARD_REG_EXP_STR || b === TAIL_WILDCARD_REG_EXP_STR) {
return -1;
}
if (a === LABEL_REG_EXP_STR) {
return 1;
} else if (b === LABEL_REG_EXP_STR) {
return -1;
}
return a.length === b.length ? a < b ? -1 : 1 : b.length - a.length;
}
var Node = class _Node {
#index;
#varIndex;
#children = /* @__PURE__ */ Object.create(null);
insert(tokens, index, paramMap, context, pathErrorCheckOnly) {
if (tokens.length === 0) {
if (this.#index !== void 0) {
throw PATH_ERROR;
}
if (pathErrorCheckOnly) {
return;
}
this.#index = index;
return;
}
const [token, ...restTokens] = tokens;
const pattern = token === "*" ? restTokens.length === 0 ? ["", "", ONLY_WILDCARD_REG_EXP_STR] : ["", "", LABEL_REG_EXP_STR] : token === "/*" ? ["", "", TAIL_WILDCARD_REG_EXP_STR] : token.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
let node;
if (pattern) {
const name = pattern[1];
let regexpStr = pattern[2] || LABEL_REG_EXP_STR;
if (name && pattern[2]) {
if (regexpStr === ".*") {
throw PATH_ERROR;
}
regexpStr = regexpStr.replace(/^\((?!\?:)(?=[^)]+\)$)/, "(?:");
if (/\((?!\?:)/.test(regexpStr)) {
throw PATH_ERROR;
}
}
node = this.#children[regexpStr];
if (!node) {
if (Object.keys(this.#children).some(
(k) => k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR
)) {
throw PATH_ERROR;
}
if (pathErrorCheckOnly) {
return;
}
node = this.#children[regexpStr] = new _Node();
if (name !== "") {
node.#varIndex = context.varIndex++;
}
}
if (!pathErrorCheckOnly && name !== "") {
paramMap.push([name, node.#varIndex]);
}
} else {
node = this.#children[token];
if (!node) {
if (Object.keys(this.#children).some(
(k) => k.length > 1 && k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR
)) {
throw PATH_ERROR;
}
if (pathErrorCheckOnly) {
return;
}
node = this.#children[token] = new _Node();
}
}
node.insert(restTokens, index, paramMap, context, pathErrorCheckOnly);
}
buildRegExpStr() {
const childKeys = Object.keys(this.#children).sort(compareKey);
const strList = childKeys.map((k) => {
const c = this.#children[k];
return (typeof c.#varIndex === "number" ? `(${k})@${c.#varIndex}` : regExpMetaChars.has(k) ? `\\${k}` : k) + c.buildRegExpStr();
});
if (typeof this.#index === "number") {
strList.unshift(`#${this.#index}`);
}
if (strList.length === 0) {
return "";
}
if (strList.length === 1) {
return strList[0];
}
return "(?:" + strList.join("|") + ")";
}
};
// ../../matrix/arcrun/registry/components/code/node_modules/hono/dist/router/reg-exp-router/trie.js
var Trie = class {
#context = { varIndex: 0 };
#root = new Node();
insert(path, index, pathErrorCheckOnly) {
const paramAssoc = [];
const groups = [];
for (let i = 0; ; ) {
let replaced = false;
path = path.replace(/\{[^}]+\}/g, (m) => {
const mark = `@\\${i}`;
groups[i] = [mark, m];
i++;
replaced = true;
return mark;
});
if (!replaced) {
break;
}
}
const tokens = path.match(/(?::[^\/]+)|(?:\/\*$)|./g) || [];
for (let i = groups.length - 1; i >= 0; i--) {
const [mark] = groups[i];
for (let j = tokens.length - 1; j >= 0; j--) {
if (tokens[j].indexOf(mark) !== -1) {
tokens[j] = tokens[j].replace(mark, groups[i][1]);
break;
}
}
}
this.#root.insert(tokens, index, paramAssoc, this.#context, pathErrorCheckOnly);
return paramAssoc;
}
buildRegExp() {
let regexp = this.#root.buildRegExpStr();
if (regexp === "") {
return [/^$/, [], []];
}
let captureIndex = 0;
const indexReplacementMap = [];
const paramReplacementMap = [];
regexp = regexp.replace(/#(\d+)|@(\d+)|\.\*\$/g, (_, handlerIndex, paramIndex) => {
if (handlerIndex !== void 0) {
indexReplacementMap[++captureIndex] = Number(handlerIndex);
return "$()";
}
if (paramIndex !== void 0) {
paramReplacementMap[Number(paramIndex)] = ++captureIndex;
return "";
}
return "";
});
return [new RegExp(`^${regexp}`), indexReplacementMap, paramReplacementMap];
}
};
// ../../matrix/arcrun/registry/components/code/node_modules/hono/dist/router/reg-exp-router/router.js
var nullMatcher = [/^$/, [], /* @__PURE__ */ Object.create(null)];
var wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
function buildWildcardRegExp(path) {
return wildcardRegExpCache[path] ??= new RegExp(
path === "*" ? "" : `^${path.replace(
/\/\*$|([.\\+*[^\]$()])/g,
(_, metaChar) => metaChar ? `\\${metaChar}` : "(?:|/.*)"
)}$`
);
}
function clearWildcardRegExpCache() {
wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
}
function buildMatcherFromPreprocessedRoutes(routes) {
const trie = new Trie();
const handlerData = [];
if (routes.length === 0) {
return nullMatcher;
}
const routesWithStaticPathFlag = routes.map(
(route) => [!/\*|\/:/.test(route[0]), ...route]
).sort(
([isStaticA, pathA], [isStaticB, pathB]) => isStaticA ? 1 : isStaticB ? -1 : pathA.length - pathB.length
);
const staticMap = /* @__PURE__ */ Object.create(null);
for (let i = 0, j = -1, len = routesWithStaticPathFlag.length; i < len; i++) {
const [pathErrorCheckOnly, path, handlers] = routesWithStaticPathFlag[i];
if (pathErrorCheckOnly) {
staticMap[path] = [handlers.map(([h]) => [h, /* @__PURE__ */ Object.create(null)]), emptyParam];
} else {
j++;
}
let paramAssoc;
try {
paramAssoc = trie.insert(path, j, pathErrorCheckOnly);
} catch (e) {
throw e === PATH_ERROR ? new UnsupportedPathError(path) : e;
}
if (pathErrorCheckOnly) {
continue;
}
handlerData[j] = handlers.map(([h, paramCount]) => {
const paramIndexMap = /* @__PURE__ */ Object.create(null);
paramCount -= 1;
for (; paramCount >= 0; paramCount--) {
const [key, value] = paramAssoc[paramCount];
paramIndexMap[key] = value;
}
return [h, paramIndexMap];
});
}
const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp();
for (let i = 0, len = handlerData.length; i < len; i++) {
for (let j = 0, len2 = handlerData[i].length; j < len2; j++) {
const map = handlerData[i][j]?.[1];
if (!map) {
continue;
}
const keys = Object.keys(map);
for (let k = 0, len3 = keys.length; k < len3; k++) {
map[keys[k]] = paramReplacementMap[map[keys[k]]];
}
}
}
const handlerMap = [];
for (const i in indexReplacementMap) {
handlerMap[i] = handlerData[indexReplacementMap[i]];
}
return [regexp, handlerMap, staticMap];
}
function findMiddleware(middleware, path) {
if (!middleware) {
return void 0;
}
for (const k of Object.keys(middleware).sort((a, b) => b.length - a.length)) {
if (buildWildcardRegExp(k).test(path)) {
return [...middleware[k]];
}
}
return void 0;
}
var RegExpRouter = class {
name = "RegExpRouter";
#middleware;
#routes;
constructor() {
this.#middleware = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
this.#routes = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
}
add(method, path, handler) {
const middleware = this.#middleware;
const routes = this.#routes;
if (!middleware || !routes) {
throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
}
if (!middleware[method]) {
;
[middleware, routes].forEach((handlerMap) => {
handlerMap[method] = /* @__PURE__ */ Object.create(null);
Object.keys(handlerMap[METHOD_NAME_ALL]).forEach((p) => {
handlerMap[method][p] = [...handlerMap[METHOD_NAME_ALL][p]];
});
});
}
if (path === "/*") {
path = "*";
}
const paramCount = (path.match(/\/:/g) || []).length;
if (/\*$/.test(path)) {
const re = buildWildcardRegExp(path);
if (method === METHOD_NAME_ALL) {
Object.keys(middleware).forEach((m) => {
middleware[m][path] ||= findMiddleware(middleware[m], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];
});
} else {
middleware[method][path] ||= findMiddleware(middleware[method], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];
}
Object.keys(middleware).forEach((m) => {
if (method === METHOD_NAME_ALL || method === m) {
Object.keys(middleware[m]).forEach((p) => {
re.test(p) && middleware[m][p].push([handler, paramCount]);
});
}
});
Object.keys(routes).forEach((m) => {
if (method === METHOD_NAME_ALL || method === m) {
Object.keys(routes[m]).forEach(
(p) => re.test(p) && routes[m][p].push([handler, paramCount])
);
}
});
return;
}
const paths = checkOptionalParameter(path) || [path];
for (let i = 0, len = paths.length; i < len; i++) {
const path2 = paths[i];
Object.keys(routes).forEach((m) => {
if (method === METHOD_NAME_ALL || method === m) {
routes[m][path2] ||= [
...findMiddleware(middleware[m], path2) || findMiddleware(middleware[METHOD_NAME_ALL], path2) || []
];
routes[m][path2].push([handler, paramCount - len + i + 1]);
}
});
}
}
match = match;
buildAllMatchers() {
const matchers = /* @__PURE__ */ Object.create(null);
Object.keys(this.#routes).concat(Object.keys(this.#middleware)).forEach((method) => {
matchers[method] ||= this.#buildMatcher(method);
});
this.#middleware = this.#routes = void 0;
clearWildcardRegExpCache();
return matchers;
}
#buildMatcher(method) {
const routes = [];
let hasOwnRoute = method === METHOD_NAME_ALL;
[this.#middleware, this.#routes].forEach((r) => {
const ownRoute = r[method] ? Object.keys(r[method]).map((path) => [path, r[method][path]]) : [];
if (ownRoute.length !== 0) {
hasOwnRoute ||= true;
routes.push(...ownRoute);
} else if (method !== METHOD_NAME_ALL) {
routes.push(
...Object.keys(r[METHOD_NAME_ALL]).map((path) => [path, r[METHOD_NAME_ALL][path]])
);
}
});
if (!hasOwnRoute) {
return null;
} else {
return buildMatcherFromPreprocessedRoutes(routes);
}
}
};
// ../../matrix/arcrun/registry/components/code/node_modules/hono/dist/router/smart-router/router.js
var SmartRouter = class {
name = "SmartRouter";
#routers = [];
#routes = [];
constructor(init) {
this.#routers = init.routers;
}
add(method, path, handler) {
if (!this.#routes) {
throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
}
this.#routes.push([method, path, handler]);
}
match(method, path) {
if (!this.#routes) {
throw new Error("Fatal error");
}
const routers = this.#routers;
const routes = this.#routes;
const len = routers.length;
let i = 0;
let res;
for (; i < len; i++) {
const router = routers[i];
try {
for (let i2 = 0, len2 = routes.length; i2 < len2; i2++) {
router.add(...routes[i2]);
}
res = router.match(method, path);
} catch (e) {
if (e instanceof UnsupportedPathError) {
continue;
}
throw e;
}
this.match = router.match.bind(router);
this.#routers = [router];
this.#routes = void 0;
break;
}
if (i === len) {
throw new Error("Fatal error");
}
this.name = `SmartRouter + ${this.activeRouter.name}`;
return res;
}
get activeRouter() {
if (this.#routes || this.#routers.length !== 1) {
throw new Error("No active router has been determined yet.");
}
return this.#routers[0];
}
};
// ../../matrix/arcrun/registry/components/code/node_modules/hono/dist/router/trie-router/node.js
var emptyParams = /* @__PURE__ */ Object.create(null);
var hasChildren = (children) => {
for (const _ in children) {
return true;
}
return false;
};
var Node2 = class _Node2 {
#methods;
#children;
#patterns;
#order = 0;
#params = emptyParams;
constructor(method, handler, children) {
this.#children = children || /* @__PURE__ */ Object.create(null);
this.#methods = [];
if (method && handler) {
const m = /* @__PURE__ */ Object.create(null);
m[method] = { handler, possibleKeys: [], score: 0 };
this.#methods = [m];
}
this.#patterns = [];
}
insert(method, path, handler) {
this.#order = ++this.#order;
let curNode = this;
const parts = splitRoutingPath(path);
const possibleKeys = [];
for (let i = 0, len = parts.length; i < len; i++) {
const p = parts[i];
const nextP = parts[i + 1];
const pattern = getPattern(p, nextP);
const key = Array.isArray(pattern) ? pattern[0] : p;
if (key in curNode.#children) {
curNode = curNode.#children[key];
if (pattern) {
possibleKeys.push(pattern[1]);
}
continue;
}
curNode.#children[key] = new _Node2();
if (pattern) {
curNode.#patterns.push(pattern);
possibleKeys.push(pattern[1]);
}
curNode = curNode.#children[key];
}
curNode.#methods.push({
[method]: {
handler,
possibleKeys: possibleKeys.filter((v, i, a) => a.indexOf(v) === i),
score: this.#order
}
});
return curNode;
}
#pushHandlerSets(handlerSets, node, method, nodeParams, params) {
for (let i = 0, len = node.#methods.length; i < len; i++) {
const m = node.#methods[i];
const handlerSet = m[method] || m[METHOD_NAME_ALL];
const processedSet = {};
if (handlerSet !== void 0) {
handlerSet.params = /* @__PURE__ */ Object.create(null);
handlerSets.push(handlerSet);
if (nodeParams !== emptyParams || params && params !== emptyParams) {
for (let i2 = 0, len2 = handlerSet.possibleKeys.length; i2 < len2; i2++) {
const key = handlerSet.possibleKeys[i2];
const processed = processedSet[handlerSet.score];
handlerSet.params[key] = params?.[key] && !processed ? params[key] : nodeParams[key] ?? params?.[key];
processedSet[handlerSet.score] = true;
}
}
}
}
}
search(method, path) {
const handlerSets = [];
this.#params = emptyParams;
const curNode = this;
let curNodes = [curNode];
const parts = splitPath(path);
const curNodesQueue = [];
const len = parts.length;
let partOffsets = null;
for (let i = 0; i < len; i++) {
const part = parts[i];
const isLast = i === len - 1;
const tempNodes = [];
for (let j = 0, len2 = curNodes.length; j < len2; j++) {
const node = curNodes[j];
const nextNode = node.#children[part];
if (nextNode) {
nextNode.#params = node.#params;
if (isLast) {
if (nextNode.#children["*"]) {
this.#pushHandlerSets(handlerSets, nextNode.#children["*"], method, node.#params);
}
this.#pushHandlerSets(handlerSets, nextNode, method, node.#params);
} else {
tempNodes.push(nextNode);
}
}
for (let k = 0, len3 = node.#patterns.length; k < len3; k++) {
const pattern = node.#patterns[k];
const params = node.#params === emptyParams ? {} : { ...node.#params };
if (pattern === "*") {
const astNode = node.#children["*"];
if (astNode) {
this.#pushHandlerSets(handlerSets, astNode, method, node.#params);
astNode.#params = params;
tempNodes.push(astNode);
}
continue;
}
const [key, name, matcher] = pattern;
if (!part && !(matcher instanceof RegExp)) {
continue;
}
const child = node.#children[key];
if (matcher instanceof RegExp) {
if (partOffsets === null) {
partOffsets = new Array(len);
let offset = path[0] === "/" ? 1 : 0;
for (let p = 0; p < len; p++) {
partOffsets[p] = offset;
offset += parts[p].length + 1;
}
}
const restPathString = path.substring(partOffsets[i]);
const m = matcher.exec(restPathString);
if (m) {
params[name] = m[0];
this.#pushHandlerSets(handlerSets, child, method, node.#params, params);
if (hasChildren(child.#children)) {
child.#params = params;
const componentCount = m[0].match(/\//)?.length ?? 0;
const targetCurNodes = curNodesQueue[componentCount] ||= [];
targetCurNodes.push(child);
}
continue;
}
}
if (matcher === true || matcher.test(part)) {
params[name] = part;
if (isLast) {
this.#pushHandlerSets(handlerSets, child, method, params, node.#params);
if (child.#children["*"]) {
this.#pushHandlerSets(
handlerSets,
child.#children["*"],
method,
params,
node.#params
);
}
} else {
child.#params = params;
tempNodes.push(child);
}
}
}
}
const shifted = curNodesQueue.shift();
curNodes = shifted ? tempNodes.concat(shifted) : tempNodes;
}
if (handlerSets.length > 1) {
handlerSets.sort((a, b) => {
return a.score - b.score;
});
}
return [handlerSets.map(({ handler, params }) => [handler, params])];
}
};
// ../../matrix/arcrun/registry/components/code/node_modules/hono/dist/router/trie-router/router.js
var TrieRouter = class {
name = "TrieRouter";
#node;
constructor() {
this.#node = new Node2();
}
add(method, path, handler) {
const results = checkOptionalParameter(path);
if (results) {
for (let i = 0, len = results.length; i < len; i++) {
this.#node.insert(method, results[i], handler);
}
return;
}
this.#node.insert(method, path, handler);
}
match(method, path) {
return this.#node.search(method, path);
}
};
// ../../matrix/arcrun/registry/components/code/node_modules/hono/dist/hono.js
var Hono2 = class extends Hono {
/**
* Creates an instance of the Hono class.
*
* @param options - Optional configuration options for the Hono instance.
*/
constructor(options = {}) {
super(options);
this.router = options.router ?? new SmartRouter({
routers: [new RegExpRouter(), new TrieRouter()]
});
}
};
// ../../matrix/arcrun/registry/components/code/node_modules/hono/dist/middleware/cors/index.js
var cors = (options) => {
const opts = {
origin: "*",
allowMethods: ["GET", "HEAD", "PUT", "POST", "DELETE", "PATCH"],
allowHeaders: [],
exposeHeaders: [],
...options
};
const findAllowOrigin = ((optsOrigin) => {
if (typeof optsOrigin === "string") {
if (optsOrigin === "*") {
return () => optsOrigin;
} else {
return (origin) => optsOrigin === origin ? origin : null;
}
} else if (typeof optsOrigin === "function") {
return optsOrigin;
} else {
return (origin) => optsOrigin.includes(origin) ? origin : null;
}
})(opts.origin);
const findAllowMethods = ((optsAllowMethods) => {
if (typeof optsAllowMethods === "function") {
return optsAllowMethods;
} else if (Array.isArray(optsAllowMethods)) {
return () => optsAllowMethods;
} else {
return () => [];
}
})(opts.allowMethods);
return async function cors2(c, next) {
function set(key, value) {
c.res.headers.set(key, value);
}
const allowOrigin = await findAllowOrigin(c.req.header("origin") || "", c);
if (allowOrigin) {
set("Access-Control-Allow-Origin", allowOrigin);
}
if (opts.credentials) {
set("Access-Control-Allow-Credentials", "true");
}
if (opts.exposeHeaders?.length) {
set("Access-Control-Expose-Headers", opts.exposeHeaders.join(","));
}
if (c.req.method === "OPTIONS") {
if (opts.origin !== "*") {
set("Vary", "Origin");
}
if (opts.maxAge != null) {
set("Access-Control-Max-Age", opts.maxAge.toString());
}
const allowMethods = await findAllowMethods(c.req.header("origin") || "", c);
if (allowMethods.length) {
set("Access-Control-Allow-Methods", allowMethods.join(","));
}
let headers = opts.allowHeaders;
if (!headers?.length) {
const requestHeaders = c.req.header("Access-Control-Request-Headers");
if (requestHeaders) {
headers = requestHeaders.split(/\s*,\s*/);
}
}
if (headers?.length) {
set("Access-Control-Allow-Headers", headers.join(","));
c.res.headers.append("Vary", "Access-Control-Request-Headers");
}
c.res.headers.delete("Content-Length");
c.res.headers.delete("Content-Type");
return new Response(null, {
headers: c.res.headers,
status: 204,
statusText: "No Content"
});
}
await next();
if (opts.origin !== "*") {
c.header("Vary", "Origin", { append: true });
}
};
};
// ../../matrix/arcrun/registry/components/code/node_modules/quickjs-emscripten-core/dist/index.mjs
init_chunk_JTKJZQYV();
init_dist();
async function newQuickJSWASMModuleFromVariant(variantOrPromise) {
let variant2 = smartUnwrap(await variantOrPromise), [wasmModuleLoader, QuickJSFFI2, { QuickJSWASMModule: QuickJSWASMModule2 }] = await Promise.all([variant2.importModuleLoader().then(smartUnwrap), variant2.importFFI(), Promise.resolve().then(() => (init_module_6F3E5H7Y(), module_6F3E5H7Y_exports)).then(smartUnwrap)]), wasmModule2 = await wasmModuleLoader();
wasmModule2.type = "sync";
let ffi = new QuickJSFFI2(wasmModule2);
return new QuickJSWASMModule2(wasmModule2, ffi);
}
function smartUnwrap(val) {
return val && "default" in val && val.default ? val.default && "default" in val.default && val.default.default ? val.default.default : val.default : val;
}
function newVariant(baseVariant, options) {
return { ...baseVariant, async importModuleLoader() {
let moduleLoader = smartUnwrap(await baseVariant.importModuleLoader());
return async function() {
let moduleLoaderArg = options.emscriptenModule ? { ...options.emscriptenModule } : {}, log = options.log ?? ((...args) => debugLog("newVariant moduleLoader:", ...args)), tapValue = (message, val) => (log(...message, val), val), force = (val) => typeof val == "function" ? val() : val;
(options.wasmLocation || options.wasmSourceMapLocation || options.locateFile) && (moduleLoaderArg.locateFile = (fileName, relativeTo) => {
let args = { fileName, relativeTo };
if (fileName.endsWith(".wasm") && options.wasmLocation !== void 0) return tapValue(["locateFile .wasm: provide wasmLocation", args], options.wasmLocation);
if (fileName.endsWith(".map")) {
if (options.wasmSourceMapLocation !== void 0) return tapValue(["locateFile .map: provide wasmSourceMapLocation", args], options.wasmSourceMapLocation);
if (options.wasmLocation && !options.locateFile) return tapValue(["locateFile .map: infer from wasmLocation", args], options.wasmLocation + ".map");
}
return options.locateFile ? tapValue(["locateFile: use provided fn", args], options.locateFile(fileName, relativeTo)) : tapValue(["locateFile: unhandled, passthrough", args], fileName);
}), options.wasmBinary && (moduleLoaderArg.wasmBinary = await force(options.wasmBinary)), options.wasmMemory && (moduleLoaderArg.wasmMemory = await force(options.wasmMemory));
let optionsWasmModule = options.wasmModule, modulePromise;
optionsWasmModule && (moduleLoaderArg.instantiateWasm = async (imports, onSuccess) => {
modulePromise ?? (modulePromise = Promise.resolve(force(optionsWasmModule)));
let wasmModule2 = await modulePromise;
if (!wasmModule2) throw new QuickJSEmscriptenModuleError(`options.wasmModule returned ${String(wasmModule2)}`);
let instance = await WebAssembly.instantiate(wasmModule2, imports);
return onSuccess(instance), instance.exports;
}), moduleLoaderArg.monitorRunDependencies = (left) => {
log("monitorRunDependencies:", left);
}, moduleLoaderArg.quickjsEmscriptenInit = () => newMockExtensions(log);
let resultPromise = moduleLoader(moduleLoaderArg), extensions = moduleLoaderArg.quickjsEmscriptenInit?.(log);
if (optionsWasmModule && extensions?.receiveWasmOffsetConverter && !extensions.existingWasmOffsetConverter) {
let wasmBinary = await force(options.wasmBinary) ?? new ArrayBuffer(0);
modulePromise ?? (modulePromise = Promise.resolve(force(optionsWasmModule)));
let wasmModule2 = await modulePromise;
if (!wasmModule2) throw new QuickJSEmscriptenModuleError(`options.wasmModule returned ${String(wasmModule2)}`);
extensions.receiveWasmOffsetConverter(wasmBinary, wasmModule2);
}
if (extensions?.receiveSourceMapJSON) {
let loadedSourceMapData = await force(options.wasmSourceMapData);
typeof loadedSourceMapData == "string" ? extensions.receiveSourceMapJSON(JSON.parse(loadedSourceMapData)) : loadedSourceMapData ? extensions.receiveSourceMapJSON(loadedSourceMapData) : extensions.receiveSourceMapJSON({ version: 3, names: [], sources: [], mappings: "" });
}
return resultPromise;
};
} };
}
function newMockExtensions(log) {
let mockMessage = "mock called, emscripten module may not be initialized yet";
return { mock: true, removeRunDependency(name) {
log(`${mockMessage}: removeRunDependency called:`, name);
}, receiveSourceMapJSON(data) {
log(`${mockMessage}: receiveSourceMapJSON called:`, data);
}, WasmOffsetConverter: void 0, receiveWasmOffsetConverter(bytes, mod) {
log(`${mockMessage}: receiveWasmOffsetConverter called:`, bytes, mod);
} };
}
// ../../matrix/arcrun/registry/components/code/node_modules/@jitl/quickjs-wasmfile-release-sync/dist/index.mjs
var variant = { type: "sync", importFFI: () => Promise.resolve().then(() => (init_ffi(), ffi_exports)).then((mod) => mod.QuickJSFFI), importModuleLoader: () => Promise.resolve().then(() => (init_emscripten_module_browser(), emscripten_module_browser_exports)).then((mod) => mod.default) };
var src_default = variant;
// ../../matrix/arcrun/registry/components/code/index.ts
import wasmModule from "./quickjs.wasm";
// ../../matrix/arcrun/registry/components/code/sandbox.mjs
var _variant = null;
function setVariant(v) {
_variant = v;
_modulePromise = null;
}
var DEFAULT_LIMITS = {
timeout_ms: 1e3,
// 牆鐘上限(Node/本機保護;CF 同步執行會凍結 Date.now,故非主保護)
max_ticks: 500,
// ★ 指令計數上限(CF 主保護):interrupt 回呼被叫超過此數即中止。
// CF Workers 凍結同步 Date.now → 純同步無窮迴圈只能靠此計數中止。
// 校準(leo21c 實測):interrupt cadence ≈ 5000 指令/tick
// 真實 card 解析 ≈ 4 ticksCF CPU 1102 門檻 ≈ 1000+ ticks。
// 500 ticks(≈ 2.5M 指令)= card 的 125× 餘裕、且穩在 CF 門檻下。
// 需更多算力的 user code 可提高 limits.max_ticks(但別逼近 ~1000)。
memory_bytes: 16 * 1024 * 1024,
// QuickJS runtime 記憶體硬上限
max_stack_bytes: 512 * 1024,
// 遞迴/深堆疊上限
max_output_bytes: 1024 * 1024,
// stdout JSON 大小上限(防跑飛)
max_code_bytes: 256 * 1024
// user code 本身大小上限
};
var SHA256_PRELUDE = `
function sha256(ascii) {
function rr(n, x) { return (x >>> n) | (x << (32 - n)); }
var mathPow = Math.pow, maxWord = mathPow(2, 32), result = '';
var words = [], asciiBitLength;
var utf8 = [];
for (var ci = 0; ci < ascii.length; ci++) {
var code = ascii.charCodeAt(ci);
if (code < 0x80) utf8.push(code);
else if (code < 0x800) { utf8.push(0xc0 | (code >> 6), 0x80 | (code & 0x3f)); }
else if (code < 0xd800 || code >= 0xe000) { utf8.push(0xe0 | (code >> 12), 0x80 | ((code >> 6) & 0x3f), 0x80 | (code & 0x3f)); }
else {
ci++;
code = 0x10000 + (((code & 0x3ff) << 10) | (ascii.charCodeAt(ci) & 0x3ff));
utf8.push(0xf0 | (code >> 18), 0x80 | ((code >> 12) & 0x3f), 0x80 | ((code >> 6) & 0x3f), 0x80 | (code & 0x3f));
}
}
asciiBitLength = utf8.length * 8;
var hash = sha256.h = sha256.h || [];
var k = sha256.k = sha256.k || [];
var primeCounter = k.length;
var isComposite = {};
for (var candidate = 2; primeCounter < 64; candidate++) {
if (!isComposite[candidate]) {
for (var i2 = 0; i2 < 313; i2 += candidate) isComposite[i2] = candidate;
hash[primeCounter] = (mathPow(candidate, 0.5) * maxWord) | 0;
k[primeCounter++] = (mathPow(candidate, 1 / 3) * maxWord) | 0;
}
}
hash = hash.slice(0, 8);
var bytes = utf8.slice();
bytes.push(0x80);
while (bytes.length % 64 - 56) bytes.push(0x00);
for (var b = 0; b < bytes.length; b++) {
words[b >> 2] |= bytes[b] << ((3 - b) % 4) * 8;
}
words[words.length] = (asciiBitLength / maxWord) | 0;
words[words.length] = asciiBitLength;
for (var j = 0; j < words.length;) {
var w = words.slice(j, j += 16);
var oldHash = hash;
hash = hash.slice(0, 8);
for (var i = 0; i < 64; i++) {
var w15 = w[i - 15], w2 = w[i - 2];
var a = hash[0], e = hash[4];
var temp1 = hash[7]
+ (rr(6, e) ^ rr(11, e) ^ rr(25, e))
+ ((e & hash[5]) ^ ((~e) & hash[6]))
+ k[i]
+ (w[i] = (i < 16) ? w[i] : (
w[i - 16]
+ (rr(7, w15) ^ rr(18, w15) ^ (w15 >>> 3))
+ w[i - 7]
+ (rr(17, w2) ^ rr(19, w2) ^ (w2 >>> 10))
) | 0);
var temp2 = (rr(2, a) ^ rr(13, a) ^ rr(22, a))
+ ((a & hash[1]) ^ (a & hash[2]) ^ (hash[1] & hash[2]));
hash = [(temp1 + temp2) | 0].concat(hash);
hash[4] = (hash[4] + temp1) | 0;
}
for (var i = 0; i < 8; i++) hash[i] = (hash[i] + oldHash[i]) | 0;
}
for (var i = 0; i < 8; i++) {
for (var j = 3; j + 1; j--) {
var b2 = (hash[i] >> (j * 8)) & 255;
result += ((b2 < 16) ? 0 : '') + b2.toString(16);
}
}
return result;
}
`;
var _modulePromise = null;
function getModule() {
if (!_variant) throw new Error("sandbox variant not set \u2014 \u547C\u53EB setVariant() \u6CE8\u5165\u9810\u7DE8 WebAssembly.Module");
if (!_modulePromise) _modulePromise = newQuickJSWASMModuleFromVariant(_variant);
return _modulePromise;
}
async function runCode(code, input, opts = {}) {
const limits = { ...DEFAULT_LIMITS, ...opts.limits || {} };
if (typeof code !== "string") return err("code must be a string", "ContractError");
if (byteLen(code) > limits.max_code_bytes) {
return err(`code exceeds max_code_bytes (${limits.max_code_bytes})`, "ResourceError");
}
const QuickJS = await getModule();
const runtime = QuickJS.newRuntime();
runtime.setMemoryLimit(limits.memory_bytes);
runtime.setMaxStackSize(limits.max_stack_bytes);
const deadline = Date.now() + limits.timeout_ms;
let interrupted = false;
let ticks = 0;
runtime.setInterruptHandler(() => {
if (++ticks > limits.max_ticks) {
interrupted = true;
return true;
}
if (Date.now() > deadline) {
interrupted = true;
return true;
}
return false;
});
const ctx = runtime.newContext();
try {
const inputJson = JSON.stringify(input === void 0 ? null : input);
const wrapped = `(() => {
"use strict";
${SHA256_PRELUDE}
const input = JSON.parse(${JSON.stringify(inputJson)});
const __run = (input) => { ${code}
};
const __out = __run(input);
return JSON.stringify(__out === undefined ? null : __out);
})()`;
const evalResult = ctx.evalCode(wrapped, "user-code.js");
if (evalResult.error) {
const detail = ctx.dump(evalResult.error);
evalResult.error.dispose();
if (interrupted) return err(`execution aborted: exceeded time (${limits.timeout_ms}ms) or instruction budget (${limits.max_ticks} ticks)`, "TimeoutError");
const msg = typeof detail === "object" && detail ? `${detail.name || "Error"}: ${detail.message || ""}`.trim() : String(detail);
return err(msg, "UserCodeError");
}
const outJson = ctx.getString(evalResult.value);
evalResult.value.dispose();
if (byteLen(outJson) > limits.max_output_bytes) {
return err(`output exceeds max_output_bytes (${limits.max_output_bytes})`, "ResourceError");
}
return { success: true, data: JSON.parse(outJson) };
} catch (e) {
if (interrupted) return err(`execution aborted: exceeded time (${limits.timeout_ms}ms) or instruction budget (${limits.max_ticks} ticks)`, "TimeoutError");
const m = e instanceof Error ? e.message : String(e);
if (/out of memory|memory/i.test(m)) return err("out of memory", "ResourceError");
return err(m, "SandboxError");
} finally {
ctx.dispose();
runtime.dispose();
}
}
function byteLen(s) {
if (typeof Buffer !== "undefined") return Buffer.byteLength(s, "utf8");
return new TextEncoder().encode(s).length;
}
function err(message, error_type) {
return { success: false, error: message, error_type };
}
// ../../matrix/arcrun/registry/components/code/index.ts
setVariant(newVariant(src_default, { wasmModule }));
var app = new Hono2();
app.use("*", cors());
app.get("/", (c) => c.json({ ok: true, component: "code" }));
app.post("/", async (c) => {
let body;
try {
body = await c.req.json();
} catch {
return c.json({ success: false, error: "request body must be JSON", error_type: "ContractError" }, 400);
}
if (typeof body.code !== "string") {
return c.json({ success: false, error: "code (string) is required", error_type: "ContractError" }, 400);
}
try {
const result = await runCode(body.code, body.input, { limits: body.limits });
return c.json(result);
} catch (e) {
return c.json(
{ success: false, error: e instanceof Error ? e.message : String(e), error_type: "SandboxError" },
500
);
}
});
var index_default = app;
export {
index_default as default
};