new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

Deno · Reference · all subjects

api/globals

35 notes, read out of this brain and free to use. Each one was extracted from a source and is re-checked against its exam.

window global replaced with globalThis

The window global has been removed. Use globalThis instead. Change window.crypto.subtle to globalThis.crypto.subtle.

structuredClone and postMessage serializable types

Deno supports structuredClone() and postMessage() for cloning and transferring objects across contexts. Serializable types that can be cloned: primitives (string, number, boolean, null, undefined, bigint), Array, Object, Map, Set (including nested structures and circular references), Date, RegExp, ArrayBuffer, TypedArray, DataView (copied by default), Error types (Error, EvalError, RangeError, ReferenceError, SyntaxError, TypeError, URIError), Blob (requires Deno 2.8+), File (requires Deno 2.8+), DOMException, and CryptoKey.

structuredClone and postMessage transferable types

Deno supports transferring (not copying) objects via the transfer option in structuredClone() or transfer list in postMessage(). Transferable types: ArrayBuffer (moves backing memory to receiver), MessagePort (transfers port to another context), ReadableStream (transfers stream to another context), WritableStream (transfers stream to another context), TransformStream (transfers stream to another context). After transfer, the original object becomes unusable.

CustomEvent and EventTarget spec deviations

Deno's DOM Event API implementation deviates from the WHATWG DOM spec in two ways: (1) Events do not bubble because Deno does not have a DOM hierarchy, so there is no tree for events to bubble or capture through. (2) timeStamp property is always set to 0.

location global and --location flag

Deno supports the location global from the web. To emulate a document location, specify one on the CLI using the --location flag with an http or https URL. Example: deno run --location https://example.com/path main.ts sets location.href to "https://example.com/path". Accessing location without --location throws ReferenceError with message: Access to "location", run again with --location <href>. Setting location or any of its fields throws NotSupportedError because navigation is not applicable in Deno. If --location is specified, relative URLs use the location as the base.

location.href as base for relative URLs in fetch and Worker

When --location is specified, location.href is used as the base for relative URLs. For fetch: deno run --location https://api.github.com/ --allow-net main.ts allows fetch("./orgs/denoland") to fetch "https://api.github.com/orgs/denoland". For Worker modules: deno run --location https://example.com/index.html --allow-net main.ts allows new Worker("./workers/hello.ts", { type: "module" }) to fetch worker module at "https://example.com/workers/hello.ts". For portability, it is preferable to pass full URLs rather than relying on --location. Use the URL constructor and import.meta.url to manually base relative URLs.

Web Storage API with 10MB limit

Deno supports the Web Storage API providing string key-value storage. It has a 10MB storage limit. sessionStorage persists data only for the current execution context. localStorage persists data from execution to execution. Methods: localStorage.setItem(key, value), localStorage.getItem(key), localStorage.removeItem(key), localStorage.clear().

localStorage unique storage location rules

Deno determines unique storage locations for localStorage based on these rules in order: (1) If --location flag is used, the origin of the location URL is used (e.g., http://example.com/a.ts, http://example.com/b.ts, and http://example.com:80/ all share storage, but https://example.com/ is different). (2) If no --location but --config configuration file is specified, the absolute path to that config file is used (deno run --config deno.jsonc a.ts and deno run --config deno.jsonc b.ts share storage, but different config file results in different storage). (3) If neither --location nor --config is specified, the absolute path to the main module determines shared storage. The Deno REPL generates a synthetic main module based on the current working directory, so multiple REPL invocations from the same path share persisted localStorage data.

Web Worker API only supports module type workers

Deno supports the Web Worker API. Each Worker instance runs on a separate thread dedicated only to that worker. Deno currently supports only module type workers; the type: "module" option is essential when creating a new worker. new Worker(import.meta.resolve("./worker.js"), { type: "module" }) is the correct pattern. Relative module specifiers in the main worker are only supported with --location <href> passed on the CLI, which is not recommended for portability. Use import.meta.resolve() with import.meta.url instead. Dedicated workers have a location and support relative module specifiers by default.

Web Worker top-level await pitfall with message handlers

Worker modules support top-level await, but register the message handler before the first await. Messages can be lost if the handler is not registered before an await, because messages arriving during the await have no handler to receive them. This is not a Deno bug but an unfortunate interaction of features that also happens in all browsers supporting module workers.

Worker communication between main thread and worker

Workers communicate bidirectionally with the main thread. Main thread: worker.postMessage(data) sends data to worker; worker.onmessage receives replies. Worker: self.onmessage receives messages from main thread; self.postMessage(result) sends results back to main thread. Example: main thread sends worker.postMessage(41), worker receives it via self.onmessage, computes evt.data + 1 = 42, and sends back via self.postMessage(42); main thread receives via worker.onmessage.

Worker instantiation permissions

Creating a new Worker instance requires appropriate permission, similar to dynamic import. For workers using local modules: --allow-read permission is required. For workers using remote modules: --allow-net permission is required. Without the required permission, creating a Worker throws PermissionDenied error.

Worker permissions configuration via deno.permissions

This is an unstable Deno feature. Worker permissions can be configured via the deno.permissions option in the Worker constructor. Permissions available in workers are analogous to CLI permission flags. By default, a worker inherits permissions from the thread it was created in. For granular permissions (net, read, write, etc.), pass an array of desired resources. For boolean permissions (env, hrtime, ffi, run), pass true/false. Both deno.permissions and its children support "inherit" to borrow parent permissions. Not specifying deno.permissions or its children causes the worker to inherit by default. Pass "none" to disable all permissions.

Worker permissions example with granular access

const worker = new Worker(import.meta.resolve("./worker.js"), { type: "module", deno: { permissions: { net: ["deno.land"], read: [new URL("./file_1.txt", import.meta.url), new URL("./file_2.txt", import.meta.url)], write: false } } }); Relative routes in granular permissions are resolved relative to the file the worker is instantiated in, not the path the worker file is in.

OffscreenCanvas available since Deno 2.8

Starting in Deno 2.8, the OffscreenCanvas API is available. OffscreenCanvas is a canvas that lives outside any DOM and can be used anywhere, including Web Workers, for off-thread rendering and image generation.

OffscreenCanvas supported rendering contexts

OffscreenCanvas#getContext accepts two rendering context IDs: (1) "bitmaprenderer" returns an ImageBitmapRenderingContext for displaying an ImageBitmap produced via createImageBitmap. (2) "webgpu" returns a GPUCanvasContext for rendering with WebGPU. Calling getContext with "2d", "webgl", or "webgl2" returns null; these contexts are not implemented in Deno.

OffscreenCanvas example encoding image to PNG

const data = await Deno.readFile("./input.jpg"); const bitmap = await createImageBitmap(new Blob([data])); const canvas = new OffscreenCanvas(bitmap.width, bitmap.height); const ctx = canvas.getContext("bitmaprenderer")!; ctx.transferFromImageBitmap(bitmap); const blob = await canvas.convertToBlob({ type: "image/png" }); await Deno.writeFile("./output.png", new Uint8Array(await blob.arrayBuffer()));

Geometry Interfaces available since Deno 2.8

Starting in Deno 2.8, the Geometry Interfaces Module Level 1 types are available as globals: DOMMatrix and DOMMatrixReadOnly (4×4 transform matrices for 2D and 3D operations), DOMPoint and DOMPointReadOnly (points in 2D/3D space), DOMRect and DOMRectReadOnly (axis-aligned rectangles), DOMQuad (quadrilateral defined by four points). These are the same types found in a browser and are useful for graphics work: applying transforms to canvas drawings, computing layout math, or porting browser code that depends on geometry types.

Geometry Interfaces example DOMMatrix and DOMPoint

const m = new DOMMatrix().translateSelf(10, 20).scaleSelf(2); const p = new DOMPoint(1, 1).matrixTransform(m); console.log(p.x, p.y); // 12 22

navigator global properties in Deno

Deno implements a subset of the navigator global with these properties: navigator.userAgent always returns "Deno/<version>". navigator.platform returns the underlying OS platform (e.g., "Linux x86_64", "MacIntel", "Win32"); added in Deno 2.7. navigator.hardwareConcurrency returns the number of logical CPU cores. navigator.userAgentData returns a NavigatorUAData object implementing the User-Agent Client Hints API; brands, mobile, and platform are read synchronously; getHighEntropyValues(hints) resolves with additional details like architecture, model, and platformVersion. navigator.locks returns a LockManager implementing the Web Locks API for coordinating access to named resources with navigator.locks.request() and navigator.locks.query().

Temporal API stabilized in Deno 2.7

The Temporal API, a modern date/time library replacing Date for most use cases, was stabilized in Deno 2.7 and is available as a global without any flags. Prior to Deno 2.7, Temporal required the --unstable-temporal flag.

Temporal API example usage

// Current date/time in local timezone const now = Temporal.Now.plainDateTimeISO(); console.log(now.toString()); // e.g. "2025-03-12T10:30:00" // Parse a date const date = Temporal.PlainDate.from("2025-03-12"); console.log(date.month); // 3 // Timezone-aware const zonedNow = Temporal.Now.zonedDateTimeISO("America/New_York"); console.log(zonedNow.timeZoneId); // "America/New_York"

CompressionStream and DecompressionStream supported formats

Deno supports CompressionStream and DecompressionStream for streaming compression and decompression. Supported formats: gzip ("gzip", RFC 1952), deflate ("deflate", zlib RFC 1950), deflate-raw ("deflate-raw", raw DEFLATE RFC 1951), Brotli ("brotli", added in Deno 2.7).

Cache API implemented methods in Deno

Only the following Cache API methods are implemented: CacheStorage: open(), has(), delete(), keys() (Deno 2.8+). Cache: match(), put(), delete(), keys() (Deno 2.8+). Differences from browsers: (1) Cannot pass relative paths to the APIs; request can be Request instance, URL, or url string. (2) match() and delete() do not support query options yet.

CompressionStream example with Brotli compression

// Compress with Brotli const input = new TextEncoder().encode("Hello, Deno!"); const cs = new CompressionStream("brotli"); const writer = cs.writable.getWriter(); writer.write(input); writer.close(); const compressed = await new Response(cs.readable).arrayBuffer(); // Decompress const ds = new DecompressionStream("brotli"); const writer2 = ds.writable.getWriter(); writer2.write(new Uint8Array(compressed)); writer2.close(); const result = await new Response(ds.readable).text(); console.log(result); // "Hello, Deno!"

SubtleCrypto.supports() feature detection method

SubtleCrypto.supports() is a static method for synchronously checking whether a given algorithm and operation combination is available, without running the operation or catching an error. Added in Deno 2.9. It takes an operation name, an algorithm name, and an optional third argument, and returns a boolean. Operations: "encrypt", "decrypt", "sign", "verify", "digest", "generateKey", "deriveKey", "deriveBits", "importKey", "exportKey", "wrapKey", "unwrapKey", "encapsulateKey", "encapsulateBits", "decapsulateKey", "decapsulateBits", or "getPublicKey". Optional third argument interpretation: length in bits for "deriveBits", or a related algorithm otherwise (derived-key algorithm for "deriveKey", shared-key algorithm for "encapsulateKey" and "decapsulateKey"). Examples: SubtleCrypto.supports("digest", "SHA3-256") returns true; SubtleCrypto.supports("generateKey", "ChaCha20-Poly1305") returns true; SubtleCrypto.supports("sign", "ML-DSA-65") returns true; SubtleCrypto.supports("deriveKey", "HKDF", { name: "AES-GCM", length: 256 }).

SHA-3 hash algorithms in crypto.subtle.digest

Starting with Deno 2.7, the SHA-3 family of hash algorithms is supported by crypto.subtle.digest: SHA3-256, SHA3-384, SHA3-512. An HMAC key can also use a SHA-3 hash by passing the algorithm name as the hash when generating or importing the key.

Extendable-output functions (XOFs) in Deno 2.9

Deno 2.9 adds SHAKE, cSHAKE, TurboSHAKE, and KangarooTwelve extendable-output functions (XOFs). Unlike fixed-size hashes, XOFs can produce any length digest, so crypto.subtle.digest requires an outputLength option in bits (must be positive multiple of 8). Supported names: SHAKE128, SHAKE256, cSHAKE128, cSHAKE256, TurboSHAKE128, TurboSHAKE256, KT128 (also KangarooTwelve), KT256. cSHAKE128/256 accept optional functionName and customization BufferSource parameters. TurboSHAKE128/256 accept optional domainSeparation byte (0x01 to 0x7F). KT128/KT256 accept optional customization BufferSource.

KMAC keyed message authentication codes added in Deno 2.9

KMAC128 and KMAC256 are keyed message authentication codes built on cSHAKE, added in Deno 2.9. Generate a key with length in bits, then sign and verify with outputLength in bits and optional customization BufferSource. KMAC keys can be imported and exported in "raw", "raw-secret", and "jwk" formats.

Argon2 password hashing added in Deno 2.9

Argon2d, Argon2i, and Argon2id are password-hashing key-derivation functions, added in Deno 2.9. Import the password as a key in "raw-secret" format with deriveBits usage, then call deriveBits. Parameters: memory (memory cost in kibibytes), passes (iterations), parallelism (degree of parallelism), nonce BufferSource (salt). Optional secretValue and associatedData BufferSource values.

ChaCha20-Poly1305 authenticated encryption in Deno 2.9

Deno 2.9 supports ChaCha20-Poly1305 authenticated encryption through generateKey, encrypt, and decrypt. Keys are always 256 bits. Each encrypt and decrypt call takes a 12-byte nonce and optional additionalData (authenticated but not encrypted). Use a fresh nonce for every message encrypted under the same key. The returned ciphertext includes the 16-byte Poly1305 authentication tag.

ML-DSA lattice-based digital signatures in Deno 2.9

ML-DSA (FIPS 204) is a lattice-based digital signature scheme. Three parameter sets available: ML-DSA-44, ML-DSA-65, ML-DSA-87 (increasing security levels). Generate a key pair, then sign with private key and verify with public key. sign and verify accept optional context (BufferSource binding signature to application-specific value); same context must be supplied to both calls. ML-DSA keys can be imported/exported in "pkcs8", "spki", "jwk", "raw-public", "raw-private", and "raw-seed" formats.

SLH-DSA stateless hash-based signatures in Deno 2.9

SLH-DSA (FIPS 205) is a stateless hash-based signature scheme. All twelve parameter sets available combining hash family (SHA2 or SHAKE), security level (128, 192, or 256), and tradeoff (s for small signature or f for fast): SLH-DSA-SHA2-128s, SLH-DSA-SHA2-128f, SLH-DSA-SHA2-192s, SLH-DSA-SHA2-192f, SLH-DSA-SHA2-256s, SLH-DSA-SHA2-256f, SLH-DSA-SHAKE-128s, SLH-DSA-SHAKE-128f, SLH-DSA-SHAKE-192s, SLH-DSA-SHAKE-192f, SLH-DSA-SHAKE-256s, SLH-DSA-SHAKE-256f. Uses same generateKey, sign, verify flow as ML-DSA, including optional context. SLH-DSA keys can be imported/exported in "pkcs8", "spki", "jwk", "raw-public", and "raw-private" formats.

ML-KEM key encapsulation mechanism in Deno 2.9

ML-KEM (FIPS 203) is a key-encapsulation mechanism where one party encapsulates a fresh shared secret to a recipient's public key, and recipient decapsulates to recover same secret. Parameter sets: ML-KEM-512, ML-KEM-768, ML-KEM-1024. Recipient generates key pair and publishes public key. Sender calls encapsulateKey, which returns ciphertext to send and sharedKey CryptoKey for specified algorithm. Recipient passes ciphertext to decapsulateKey to derive same key. encapsulateBits and decapsulateBits are lower-level variants returning raw shared secret as ArrayBuffer. A decapsulation (private) key exposes getPublicKey() returning its matching encapsulation (public) key.

createImageBitmap for decoding images

Deno supports createImageBitmap() for decoding images into ImageBitmap objects usable with OffscreenCanvas. Supported formats: PNG, JPEG, BMP, GIF (added in Deno 2.7), WebP (added in Deno 2.7).

Give your agent this brain