Something went wrong. Try again.
[READ-ONLY] Mirror of https://github.com/okikio/bundlejs-api.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881/** * Reactive contexts. * * ## Terminology * * ### Ancestor contexts * Any {@link Context} that is further up in the chain of creation of a given {@link Context}. * A "parent context" refers to the immediate ancestor context. * * ### Descendant contexts * Any new {@link Context} created from a given {@link Context}. * A "child context" refers to the immediate descendant context. * * ### Sibling contexts * Any child context that shares the same parent context. * * ## Concepts * * ### Isolated data * * Refers to properties that are explicitly (re)defined in a child context and do not affect nor inherit from ancestor contexts properties. * Changes made to isolated data in a child context do not propagate back to ancestor and sibling contexts. * Isolated data becomes shared data in all descendant contexts unless isolated again. * * ### Shared Data * Refers to properties that are inherited from ancestor contexts. * These properties can be accessed and modified by descendant contexts. * Changes made to shared data in a descendant context propagate back to ancestor contexts and vice-versa. * * ## Features * * ### Observable properties * {@link Context} implements `EventTarget` interface and accepts event listeners. * Properties in the {@link Context.target} can be tracked and reacted to via events like `get`, `set`, `delete`, and `call`. * A `change` event is also dispatched whenever a property is set, deleted, or called. * * ### Context inheritance * Child contexts inherit properties from their parent contexts, making it easy to share data across multiple related contexts. * Properties set in a child context can override parent context properties, but inherited properties are still accessible unless explicitly overridden. * * ### Handling of specific classes: * Classes listed in {@link Context.unproxyable} are not proxied by default to avoid proxy-related issues and allow reflection. * It includes various built-in such as `Map`, `Set`, `Promise`, etc. and can be modified to fit specific use cases. * * ### Bidirectional data flow * Inherited properties propagate down to descendant contexts, and changes to shared properties reflect back up to ancestor contexts. * Isolated properties remain unique to the child context. * * > [!NOTE] * > * > Properties specified in {@link Context.with} are automatically isolated from the parent and sibling contexts. * * @module */
import type { ESBUILD, ESBUILD_WASM } from "../types.ts";
// Importsimport type { DeepMerge } from "@bundle/utils/deep-object"export type { DeepMerge }
/** Nullable type. */export type Nullable<T> = T | null
/** Callback function. */// deno-lint-ignore ban-typesexport type callback = Function
/** Record. */export type record<T = unknown> = Record<PropertyKey, T>
/** * Reactive context. * * Create an object where every `get`, `set`, `delete`, and `call` operations are observable. * These events can be tracked using the `EventTarget` interface. Observability is applied * recursively to all properties of the object, including functions and collections such as * `Map`, `Set`, and `Array`. * * ## Key Concepts * * ### Isolated Data * - **Isolated data** refers to properties that are explicitly defined in a child context and do not * affect or inherit from the parent context's properties. Changes made to isolated data in a child * context do not propagate back to the parent context or affect sibling contexts. * - **Example**: When creating a child context, you can specify new properties or reassign existing * ones. These properties are isolated to that child context unless explicitly shared back with the * parent. * * ### Shared Data * - **Shared data** refers to properties that are inherited from the parent context. These properties * can be accessed and modified by child contexts. Changes made to shared data in a child context * propagate back to the parent context. * - **Example**: Shared data is inherited from the parent context by default. When a child modifies * shared data, the changes are reflected across all contexts that share the same data. * * ## Key Features * * 1. **Observable Properties**: * - Properties in the context can be tracked and reacted to via events like `get`, `set`, `delete`, * and `call`. * * 2. **Context Inheritance**: * - Child contexts inherit properties from their parent contexts, making it easy to share * data across multiple related contexts. * - Properties set in a child context can override parent context properties, but inherited * properties are still accessible unless explicitly overridden. * * 3. **Handling of Native Classes**: * - Specific native classes such as `Set`, `Map`, `ArrayBuffer`, `WeakMap`, and others are handled * carefully to avoid proxy-related issues. These objects are accessed directly without * unnecessary proxy traps. * * 4. **Bidirectional Data Flow**: * - Inherited properties propagate down to child contexts, and changes to shared properties reflect * back up to parent contexts. Isolated properties remain unique to the child context. * * **Note:** Properties specified in `.with({ ... })` are automatically isolated from the parent * and sibling contexts. This means that properties defined or modified in a child context do not * propagate to parent or sibling contexts unless explicitly shared. * * @example Example: Observing Property Changes in a Context * This example demonstrates the setup of listeners for observing `get`, `set`, `delete`, and `call` operations. * We initialize a context and attach listeners to capture events as we interact with the context's target object. * * ```ts * import { Context } from "./context.ts" * * const context = new Context({ foo: "bar", bar: () => null }); * * // Attach listeners * context.addEventListener("get", ({detail:{property}}: any) => console.log(`get: ${property}`)); * context.addEventListener("set", ({detail:{property, value}}: any) => console.log(`set: ${property}: ${value.old} => ${value.new}`)); * context.addEventListener("delete", ({detail:{property}}: any) => console.log(`delete: ${property}`)); * context.addEventListener("call", ({detail:{property, args}}: any) => console.log(`call: ${property}(${args.join(", ")})`)); * context.addEventListener("change", ({detail:{type}}: any) => console.log(`change: ${type}`)); * * // Operate on the context * context.target.foo = "baz"; // Triggers the "set" and "change" events * context.target.bar(); // Triggers the "call" and "change" events * ``` * * @example Example: Basic Usage with Shared and Isolated Properties * This example illustrates how shared and isolated properties work across contexts. Shared properties are accessible * and modifiable across contexts, whereas isolated properties remain unique to each context. * * ```ts * import { Context } from "./context.ts" * * const parentContext = new Context({ * setOfUrls: new Set<string>(), // Shared across contexts * isolatedSetOfUrls: new Set<string>(), // Isolated to each child context * name: "ParentContext", * }); * * const childContext = parentContext.with({ * name: "ChildContext", // Isolated in child context * }); * * // Modify isolated and shared properties * childContext.target.isolatedSetOfUrls.add("bar"); // Only affects the child context * childContext.target.setOfUrls.add("https://child.com"); // Affects all contexts sharing this property * * console.log(parentContext.target.setOfUrls); // Includes 'https://child.com' * console.log(childContext.target.isolatedSetOfUrls); // Only 'bar' in the child context * ``` * * @example Example: Accessing Properties Across Multiple Levels of Context * This example demonstrates how properties are inherited across multiple context levels and how updates propagate. * * ```ts * import { Context } from "./context.ts" * * const parentContext = new Context({ foo: "parent value" }); * const childContext = parentContext.with({ bar: "child value" }); * const grandchildContext = childContext.with({ baz: "grandchild value" }); * * // Access inherited properties across levels * console.log(grandchildContext.target.foo); // "parent value" (inherited from parentContext) * console.log(grandchildContext.target.bar); // "child value" (inherited from childContext) * console.log(grandchildContext.target.baz); // "grandchild value" (from grandchildContext) * * // Updating a shared property propagates to the parent context * grandchildContext.target.foo = "updated value"; * console.log(parentContext.target.foo); // "updated value" * ``` * * @example Example: Handling Native Classes with Proxies * This example shows how native classes such as `Set` and `Map` are handled within a context, allowing * seamless modification without proxy interference. * * ```ts * import { Context } from "./context.ts" * * const context = new Context({ * mySet: new Set([1, 2, 3]), * myMap: new Map([["key", "value"]]), * }); * * // Add to the set and update the map * context.target.mySet.add(4); * context.target.myMap.set("newKey", "newValue"); * * console.log(context.target.mySet); // Set { 1, 2, 3, 4 } * console.log(context.target.myMap); // Map { "key" => "value", "newKey" => "newValue" } * ``` * * @example Example: Shared and Isolated Data with Buffer and Date * This example highlights how `ArrayBuffer` and `Date` instances can be shared across contexts or isolated to specific contexts. * * ```ts * import { Context } from "./context.ts" * * const context = new Context({ * buffer: new ArrayBuffer(16), // Shared buffer * currentDate: new Date(), // Shared Date * }); * * const childContext = context.with({ * buffer: new ArrayBuffer(32), // Isolated buffer * }); * * const grandchildContext = childContext.with({ * currentDate: new Date("2025-01-01T00:00:00Z"), // Isolated Date * }); * * // Check data in different contexts * console.log(context.target.buffer.byteLength); // 16 bytes (shared) * console.log(childContext.target.buffer.byteLength); // 32 bytes (isolated) * console.log(grandchildContext.target.currentDate); // 2025-01-01T00:00:00.000Z * ``` * * @example Example: Working with WeakMap, WeakSet, and Symbol * This example shows how `WeakMap`, `WeakSet`, and `Symbol` are handled within the context, with support for * isolated symbols across child contexts. * * ```ts * import { Context } from "./context.ts" * * const weakMap = new WeakMap<object, number>(); * const symbolKey = Symbol("uniqueKey"); * const context = new Context({ weakMap, symbolKey }); * * const obj = {}; * context.target.weakMap.set(obj, 123); * * const childContext = context.with({ * symbolKey: Symbol("childSymbol"), // Isolated Symbol * }); * * console.log(context.target.weakMap.get(obj)); // 123 (shared WeakMap) * console.log(childContext.target.symbolKey); // Symbol("childSymbol") (isolated Symbol) * ``` * * @example Example: Streams and Transferables * This example demonstrates how `ReadableStream` and `WritableStream` can be utilized within the context * and connected via the `pipeTo` method. * * ```ts * import { Context } from "./context.ts" * * const readableStream = new ReadableStream({ * start(controller) { * controller.enqueue("data"); * controller.close(); * }, * }); * * const writableStream = new WritableStream({ * write(chunk) { * console.log(chunk); // "data" * }, * }); * * const context = new Context({ readable: readableStream, writable: writableStream }); * * const childContext = context.with({}); * * childContext.target.readable.pipeTo(childContext.target.writable); * ``` * * @author Simon Lecoq (lowlighter) * @license MIT * @module */export class Context<T extends record = record> extends EventTarget { /** Constructor. */ constructor(target = {} as T, { parent = null as Nullable<Context<record>> } = {}) { super() this.#parent = parent this.#target = target this.#isolated = new Set(Object.keys(this.#target)) this.target = this.#proxify(this.#target) }
/** * Parent {@link Context}. * Properties not found in the current context will be searched in the parent context. */ readonly #parent: Nullable<Context<record>>
/** * Children {@link Context | Contexts}. * Any property change in the parent context will be dispatched to the children contexts. */ readonly #children = new Set<Context<record>>()
/** * A set of properties that are considered isolated in the current {@link Context | context}. * * - **Isolated properties** are those that are explicitly defined in a child context. * - These properties do not propagate changes to the parent context or sibling contexts. * - Changes made to isolated properties in the child context are restricted to that context * and do not affect shared data or other contexts. */ readonly #isolated: Set<PropertyKey>
/** * Actual target value. * This value is not proxified. */ readonly #target
/** * Observable target value. * This value is proxified. */ readonly target: T
/** * Proxified cache. * Used to avoid creating multiple proxies for the same object. */ readonly #cache = new WeakMap() /** * Opaque plain objects */ static #opaque = new WeakSet<object>() static opaque<T extends object>(value: T) { if (typeof value === "object") Context.#opaque.add(value) return value }
/** * Keep track of the number of listeners */ #listeners = 0
/** Instantiate a new inherited {@link Context} with superseded value. */ with<U extends record>(target: U): Context<DeepMerge<T, U>> { const context = new Context(target, { parent: this }) this.#children.add(context) return context as Context<DeepMerge<T, U>> }
/** Access target value from a property path. */ #access(path = [] as PropertyKey[]) { return path.reduce((value, property) => (value as target)?.[property], this.#target) }
/** * Proxify an object. * * This method creates a proxy for the target object and attaches traps for `get`, `set`, * `delete`, and other operations. The traps are designed to enforce the observable nature * of the context, while respecting the rules for specific native classes and types. * * Example: * ```ts * import { Context } from "./context.ts" * * const context = new Context({ foo: "bar" }); * const proxied = context.target; // Returns a proxied object * ``` * * @param target - The object to proxify. * @param path - The property path associated with the object (default is an empty array). * @returns A proxied version of the target object. */ #proxify(target: target, { path = [] as PropertyKey[] } = {}) { return new Proxy(target, this.#trap(target, path)) }
/** * Generate trap handlers. * Handlers are different depending on whether the target is a function or an object at root path. */ #trap(target: target, path: PropertyKey[] = []) { if (typeof target === "function") { return { apply: this.#trap_apply.bind(this, path) } } const traps = { get: this.#trap_get.bind(this, path), set: this.#trap_set.bind(this, path), deleteProperty: this.#trap_delete.bind(this, path), } if ((this.#parent) && (!path.length)) { Object.assign(traps, { has: this.#trap_has.bind(this), ownKeys: this.#trap_keys.bind(this), getOwnPropertyDescriptor: this.#trap_descriptors.bind(this), }) } return traps }
/** * Trap function calls. * * This trap has been updated to handle native classes like `Map` and `Set`, * ensuring that these objects are not proxied. Additionally, the trap now correctly * accesses properties across multiple context levels. * * Example: * ```ts * import { Context } from "./context.ts" * * const context = new Context({ setFunc: new Set([1, 2, 3]) }); * context.target.setFunc.add(4); // Works correctly without proxy interference * ``` * * @param path - The path to the function being called. * @param callable - The function to call. * @param that - The `this` context for the function call. * @param args - The arguments to pass to the function. * @returns The result of the function call. */ #trap_apply(path: PropertyKey[], callable: trap<"apply", 0>, that: trap<"apply", 1>, args: trap<"apply", 2>) { try { return Reflect.apply(callable, that, args) } finally { if (this.#listeners > 0) { const target = this.#access(path.slice(0, -1)) const property = path.at(-1)! if (target && Reflect.has(target, property)) { this.#dispatch("call", { path, target, property, args }) } } } }
/** * Trap property access. * * This trap has been updated to correctly access properties across multiple levels * in the context hierarchy, as well as handling specific native classes and types * that should not be proxied. * * Example: * ```ts * import { Context } from "./context.ts" * * const parent = new Context({ foo: "parent" }); * const child = parent.with({ bar: "child" }); * * console.log(child.target.foo); // Accesses "foo" from parent context * ``` * * @param path - The path to the property being accessed. * @param target - The target object. * @param property - The property key. * @returns The value of the property. */ #trap_get(path: PropertyKey[], target: trap<"get", 0>, property: trap<"get", 1>) { if ((this.#parent) && (!path.length)) { if (!this.#isolated.has(property) && !Reflect.has(target, property)) { return Reflect.get(this.#parent.target, property) } }
const value = Reflect.get(target, property) try { if (value) { let proxify = false if (typeof value === "function") { // Skip and constructors if ((property === "constructor") && (value !== Object.prototype.constructor)) { return value } proxify = true } else if (typeof value === "object") { // Skip some built-in objects if (Context.#isNotProxyable(value) || Context.#opaque.has(value)) { return value } proxify = true } if (proxify) { if (!this.#cache.has(value)) { this.#cache.set(value, this.#proxify(value, { path: [...path, property] })) } return this.#cache.get(value) } } return value } finally { if (this.#listeners > 0) { this.#dispatch("get", { path, target, property, value }) } } }
/** Trap property assignment. */ #trap_set(path: PropertyKey[], target: trap<"set", 0>, property: trap<"set", 1>, value: trap<"set", 2>) { if ((this.#parent) && (!path.length) && (!Reflect.has(this.#target, property)) && (Reflect.has(this.#parent.target, property)) && !this.#isolated.has(property)) { return Reflect.set(this.#parent.target, property, value) }
const old = Reflect.get(target, property) try { return Reflect.set(target, property, value) } finally { if (this.#listeners > 0) { this.#dispatch("set", { path, target, property, value: { old, new: value } }) } } }
/** Trap property deletion. */ #trap_delete(path: PropertyKey[], target: trap<"deleteProperty", 0>, property: trap<"deleteProperty", 1>) { if ((this.#parent) && (!path.length) && (!Reflect.has(this.#target, property)) && (Reflect.has(this.#parent.target, property)) && !this.#isolated.has(property)) { return Reflect.deleteProperty(this.#parent.target, property) }
const deleted = Reflect.get(target, property) try { return Reflect.deleteProperty(target, property) } finally { if (this.#listeners > 0) { this.#dispatch("delete", { path, target, property, value: deleted }) } } }
/** Trap property keys. */ #trap_keys(target: trap<"ownKeys", 0>) { const isolatedKeys = this.#isolated // Convert isolated Set to array const parentKeys = Reflect.ownKeys(this.#parent!.target) const targetKeys = Reflect.ownKeys(target)
// Create the filtered result const allKeys = Array.from(new Set(parentKeys.concat(targetKeys))) .filter((key) => { const inIsolated = isolatedKeys.has(key) const inTarget = targetKeys.includes(key)
// Keep the key if: // - It is in both isolatedKeys and targetKeys (keep it) // - It is not in isolatedKeys (keep it) return (inIsolated && inTarget) || !inIsolated })
return allKeys }
/** Trap property descriptors. */ #trap_descriptors(target: trap<"getOwnPropertyDescriptor", 0>, property: trap<"getOwnPropertyDescriptor", 1>) { const descriptor = Reflect.getOwnPropertyDescriptor(target, property) return descriptor ?? (!this.#isolated.has(property) ? Reflect.getOwnPropertyDescriptor(this.#parent!.target, property) : descriptor) }
/** Trap property existence tests. */ #trap_has(target: trap<"has", 0>, property: trap<"has", 1>) { return Reflect.has(target, property) || (!this.#isolated.has(property) && Reflect.has(this.#parent!.target, property)) }
/** Dispatch event. */ #dispatch(type: string, detail: Omit<detail, "type">) { if (this.#listeners <= 0) return;
Object.assign(detail, { type }) this.dispatchEvent(new Context.Event(type, { detail })) if ((type === "set") || (type === "delete") || (type === "call")) { this.dispatchEvent(new Context.Event("change", { detail })) }
this.dispatchEvent(new Context.Event("all", { detail })) for (const child of this.#children) { const property = detail.path[0] ?? detail.property if (!child.#isolated.has(property) && !Reflect.has(child.#target, property)) { child.#dispatch(type, detail) } } }
override addEventListener(...args: Parameters<EventTarget['addEventListener']>): void { super.addEventListener(...args) this.#listeners++; if (this.#parent) this.#parent.#listeners++; }
override removeEventListener(...args: Parameters<EventTarget['removeEventListener']>): void { super.removeEventListener(...args) if (this.#listeners > 0) this.#listeners--; if (this.#parent && this.#parent.#listeners > 0) this.#parent.#listeners--; }
/** * Check if object is a native class or type that should not be proxied. * * The following objects are avoided by default because: * * - **Map, Set, WeakMap, WeakSet**: These collections have internal slots that rely on the object being intact for correct behavior. * - **WeakRef**: Holds a weak reference to an object, preventing interference with garbage collection. * - **Promise**: Proxying promises can interfere with their state management and chaining. * - **Error**: Proxying errors can disrupt stack traces and error handling mechanisms. * - **RegExp**: Regular expressions rely on internal optimizations that can be disrupted by proxying. * - **Date**: Dates have special methods like `getTime()` and `toISOString()` that are tightly coupled with the internal state of the `Date` object. * - **ArrayBuffer, TypedArray**: These represent binary data and are performance-critical. Proxying them could cause significant performance degradation. * - **Function**: Functions have special behavior when called or applied. Proxying can lead to unexpected side effects. * - **Symbol**: Symbols are unique and immutable, making proxying unnecessary and potentially harmful. * - **BigInt**: BigInts are immutable and behave like primitives; proxying them is not meaningful. * - **Intl Objects**: Objects like `Intl.DateTimeFormat`, `Intl.NumberFormat`, and `Intl.Collator` are optimized for locale-aware formatting and should not be altered. * - **MessagePort, MessageChannel, Worker, SharedWorker**: Used for communication between contexts; proxying could disrupt message-passing mechanisms. * - **ImageBitmap**: Represents image data optimized for performance; proxying could slow down rendering operations. * - **OffscreenCanvas**: Enables off-main-thread rendering; proxying could break parallel rendering tasks. * - **ReadableStream, WritableStream, TransformStream**: Streams are designed for efficient data handling. Proxying could introduce latency or disrupt data flow. * - **AudioData, VideoFrame**: Media-related transferables used in real-time processing; proxying could cause performance issues. * * @param obj - The object to check. * @returns `true` if the object is a native class or type that should not be proxied, otherwise `false`. */ static #isNotProxyable(obj: unknown): boolean { return ( ("Map" in globalThis && obj instanceof globalThis.Map) || ("Set" in globalThis && obj instanceof globalThis.Set) || ("WeakMap" in globalThis && obj instanceof globalThis.WeakMap) || ("WeakSet" in globalThis && obj instanceof globalThis.WeakSet) || ("WeakRef" in globalThis && obj instanceof globalThis.WeakRef) || ("Request" in globalThis && obj instanceof globalThis.Request) || ("Response" in globalThis && obj instanceof globalThis.Response) || ("Headers" in globalThis && obj instanceof globalThis.Headers) || ("URL" in globalThis && obj instanceof globalThis.URL) || ("Promise" in globalThis && obj instanceof globalThis.Promise) || ("Error" in globalThis && obj instanceof globalThis.Error) || ("RegExp" in globalThis && obj instanceof globalThis.RegExp) || ("Date" in globalThis && obj instanceof globalThis.Date) || ("ArrayBuffer" in globalThis && obj instanceof globalThis.ArrayBuffer) || ("ArrayBuffer" in globalThis && globalThis.ArrayBuffer.isView(obj)) || // Covers TypedArrays (Uint8Array, Float32Array, etc.) ("Function" in globalThis && obj instanceof globalThis.Function) || ("BigInt" in globalThis && typeof obj === "bigint") || ("Symbol" in globalThis && typeof obj === "symbol") || ("Intl" in globalThis && "DateTimeFormat" in globalThis.Intl && obj instanceof globalThis.Intl.DateTimeFormat) || ("Intl" in globalThis && "NumberFormat" in globalThis.Intl && obj instanceof globalThis.Intl.NumberFormat) || ("Intl" in globalThis && "Collator" in globalThis.Intl && obj instanceof globalThis.Intl.Collator) || ("Worker" in globalThis && obj instanceof globalThis.Worker) || // @ts-ignore Not all environments support SharedWorkers ("SharedWorker" in globalThis && obj instanceof globalThis.SharedWorker) || ("MessageChannel" in globalThis && obj instanceof globalThis.MessageChannel) || ("MessagePort" in globalThis && obj instanceof globalThis.MessagePort) || ("ImageBitmap" in globalThis && obj instanceof globalThis.ImageBitmap) || // @ts-ignore Deno doesn't support `OffscreenCanvas`, but the browsers do ("OffscreenCanvas" in globalThis && obj instanceof globalThis.OffscreenCanvas) || ("ReadableStream" in globalThis && obj instanceof globalThis.ReadableStream) || ("WritableStream" in globalThis && obj instanceof globalThis.WritableStream) || ("TransformStream" in globalThis && obj instanceof globalThis.TransformStream) || // @ts-ignore Deno doesn't support `AudioData`, but the browsers do ("AudioData" in globalThis && obj instanceof globalThis.AudioData) || // @ts-ignore Deno doesn't support `VideoFrame`, but the browsers do ("VideoFrame" in globalThis && obj instanceof globalThis.VideoFrame) ) }
/** Context event. */ static readonly Event = class ContextEvent extends CustomEvent<detail> { } as typeof CustomEvent}
/** Context target. */// deno-lint-ignore no-explicit-anyexport type target = any
/** Context event detail. */type detail = { type: string; path: PropertyKey[]; target: target; property: PropertyKey; value?: unknown; args?: unknown[] }
/** Trap arguments. */// deno-lint-ignore ban-typestype trap<K extends keyof ProxyHandler<object>, I extends number> = K extends "apply" ? Parameters<NonNullable<ProxyHandler<Function>[K]>>[I] : Parameters<NonNullable<ProxyHandler<object>[K]>>[I]
export interface GlobalState extends record { /** * Registers if esbuild has been initialized */ initialized: boolean;
/** * Instance of esbuild being used */ esbuild: typeof ESBUILD | typeof ESBUILD_WASM | null;
/** * In-flight initialization promise. * * Guards against the race where multiple concurrent callers all see * `initialized === false` and each try to call `esbuild.initialize()`, * which only allows a single invocation. The first caller stores its * promise here; all subsequent callers await the same promise. * * Reset to `null` once initialization settles (success or failure) and * when {@link stop} tears everything down. */ initPromise: Promise<typeof ESBUILD | typeof ESBUILD_WASM | null> | null;}
/** * Global reactive context. * * This context is used to store global state that can be observed and reacted to. * It creates an object where every get, set, delete, and call operations are observable. * These events can be reacted to using the `EventTarget` interface. * Observability is applied recursively to all properties of the object. * * The context also tracks function calls, making it possible to track updates to keyed collections such as `Map`, `Set`, and `Array`. * * @example * ```ts * import { Context } from "./context.ts" * * const context = new Context({ foo: "bar", bar: () => null }) * * // Attach listeners * context.addEventListener("get", ({detail:{property}}:any) => console.log(`get: ${property}`)) * context.addEventListener("set", ({detail:{property, value}}:any) => console.log(`set: ${property}: ${value.old} => ${value.new}`)) * context.addEventListener("delete", ({detail:{property}}:any) => console.log(`delete: ${property}`)) * context.addEventListener("call", ({detail:{property, args}}:any) => console.log(`call: ${property}(${args.join(", ")})`)) * context.addEventListener("change", ({detail:{type}}:any) => console.log(`change: ${type}`)) * * // Operate on context * context.target.foo = "baz" * context.target.bar() * ``` * * It is possible to create child contexts from a context. * * Child contexts inherit the parent context properties if they're left undefined. * In this case, changes will be effective bidirectionally (both the parent and child will have the same reference, meaning that * operations performed on parent value are applied on child value and vice-versa). * * If a property is defined in the child context, changes will only be effective in the child context. * * @example * ```ts * import { Context } from "./context.ts" * * const a = new Context({ foo: "bar" }) * const b = a.with({ bar: "baz" }) * * console.assert("foo" in a.target) * console.assert(!("bar" in a.target)) * console.assert("foo" in b.target) * console.assert("bar" in b.target) * ``` * * @see {@link Context} * @see {@link fromContext} * @see {@link toContext} * @see {@link withContext} */export const GlobalContext = new Context<GlobalState>({ initialized: false, esbuild: null, initPromise: null,});
/** * Gets a value from a context. * * This function retrieves a value from the specified context based on the provided key. * If no context is provided, it defaults to the `GlobalContext`. * * @param name The key to get the value from. * @param ctx The context to get the value from. Defaults to `GlobalContext`. * @returns The value that was retrieved, or `null` if the key does not exist in the context. * * @example * ```ts * const value = fromContext("foo"); * console.log(value); // Outputs the value of "foo" from the context * ``` * * @see {@link GlobalContext} * @see {@link toContext} * @see {@link withContext} */export function fromContext<T extends keyof GlobalState>( name: T): GlobalState[T];export function fromContext<State extends record, T extends keyof State>( name: T, ctx: Context<State>,): State[T];export function fromContext<State extends record, T extends keyof State>( name: T, ctx?: Context<State>): State[T] | null { const _ctx = (ctx ?? GlobalContext) return name && name in _ctx.target ? _ctx.target[name] as State[T] : null;}
/** * Sets a value to a context. * * This function sets a value in the specified context based on the provided key. * If no context is provided, it defaults to the `GlobalContext`. * * @param name The key to set the value to. * @param value The value to set. * @param ctx The context to set the value to. Defaults to `GlobalContext`. * @returns The value that was set. * * @example * ```ts * toContext("foo", "bar"); * console.log(toContext("foo")); // Outputs "bar" * ``` * * @see {@link GlobalContext} * @see {@link fromContext} * @see {@link withContext} */export function toContext<T extends keyof GlobalState>( name: T, value: GlobalState[T],): GlobalState[T];export function toContext<State extends record, T extends keyof State>( name: T, value: State[T], ctx: Context<State>,): State[T];export function toContext<State extends record, T extends keyof State>( name: T, value: State[T], ctx?: Context<State>): State[T] { const _ctx = (ctx ?? GlobalContext) _ctx.target[name] = value; return value;}
/** * Creates a new context by merging the provided value with the existing context. * * This function takes a new state object and merges it with the existing context to create a new context. * If no context is provided, it defaults to the `GlobalContext`. * * @template NewState - The type of the new state to be merged. * @template State - The type of the existing state in the context. Defaults to `GlobalState`. * * @param value - The new state object to be merged with the existing context. * @param ctx - The existing context to merge the new state with. Defaults to `GlobalContext`. * * @returns A new context that includes both the existing state and the new state. * * @example * ```ts * import { withContext, GlobalContext } from "./context"; * * const newState = { foo: "bar" }; * const newContext = withContext(newState); * * console.log(newContext.target.foo); // Outputs: "bar" * ``` * * @see {@link Context} * @see {@link GlobalContext} */export function withContext<NewState extends record>( value: NewState,): Context<GlobalState & NewState>;export function withContext<State extends record, NewState extends record>( value: NewState, ctx: Context<State>,): Context<State & NewState>;export function withContext<State extends record, NewState extends record>( value: NewState, ctx?: Context<State>,): Context<State & NewState> { const base = (ctx ?? GlobalContext); return base.with(value) as Context<State & NewState>;}