Bounded QuickJS Runtime

HPDFQuickJS and HPDFQuickJSStatic expose the same application-controlled JavaScript evaluation API on Win32 and Win64

Choose a deployment mode

The DLL binding accepts an explicit path, the HOTPDF_QUICKJS_DLL environment value, or the platform directory found below an executable ancestor

Default builds place the bridge at Lib\thirdparty\QuickJS\bin\Win32\quickjs.dll or Lib\thirdparty\QuickJS\bin\Win64\quickjs.dll

On Linux x86-64, HPDFQuickJS loads the native libhpdfquickjs.so bridge built by tools/Build-HotPDFQuickJSLinux.sh; the explicit path and environment variable follow the same ownership and ABI rules

Linux default discovery checks the executable directory and Lib/thirdparty/QuickJS/bin/Linux64; native static OMF deployment remains specific to Windows

A relative explicit path resolves against the current working directory, including a working directory longer than the platform's usual path buffer

When the bridge cannot be loaded, LoadError reports the platform message for that failure; the resolved path is exposed as the read-only THPDFQuickJS.DllPath property and the reported bridge version as THPDFQuickJS.EngineVersion, and both strings with that message are held under the runtime memory budget and released with the instance

Win64 static allocation

The Win64 static runtime needs low-address allocations for its linked value representation. Version 2.1147.0 reuses aligned small slots within low-address blocks and releases a block after its final slot is freed, avoiding a separate Windows virtual-memory reservation and release for every short-lived object

Large requests retain the direct allocation route, Win32 behavior is unchanged, and the existing C allocation header and usable-size contract keep requested-byte VM charging unchanged. Slab metadata and unused slot space remain separate native overhead; the pool does not enlarge the runtime heap budget or promise a fixed process working set

Evaluate a script

uses
  HPDFQuickJS;

var
  Engine: THPDFQuickJS;
  EvalResult: THPDFQuickJSResult;
begin
  Engine := THPDFQuickJS.Create;
  try
    if not Engine.Available then
      raise Exception.Create(Engine.LoadError);
    EvalResult := Engine.Eval('JSON.stringify([1, 2, 3].map(x => x * 2))');
    if not EvalResult.Success then
      raise Exception.Create(EvalResult.Error);
  finally
    Engine.Free;
  end;
end;

Eval converts the final JavaScript value to UTF-8 text and preserves Unicode when returning a Delphi string

EvalInt and EvalFloat add strict numeric conversion without exposing engine values across the ABI boundary

Execution limits

Limits := THPDFQuickJSLimits.CreateDefault;
Limits.MemoryBytes := 32 * 1024 * 1024;
Limits.StackBytes := 64 * 1024;
Limits.MaxScriptBytes := 256 * 1024;
Limits.TimeoutMs := 250;
Limits.MaxInterruptChecks := 250000;
Engine := THPDFQuickJS.Create(Limits);

The defaults allow 64 MiB of engine memory, a 64 KiB stack, a 1 MiB UTF-8 script, one second of wall time, and one million interrupt checks

The Win32 static runtime caps a zero or larger requested stack budget at 48 KiB to stay inside the compiler-safe recursion boundary; DLL and Win64 modes honor the requested value directly

Memory and stack limits are runtime-wide while script, time, and interrupt limits are applied to each evaluation

Time and interrupt limits remain active through final completion-value conversion, including JavaScript toString methods and their native callbacks. A caught limit exception cannot produce a successful result, and the original deadline and interrupt counter are not restarted for conversion

Status and recovery

A rejected or interrupted evaluation clears its pending exception and buffers, so the same engine instance can execute a later valid script

One engine instance is not reentrant; use one instance per concurrent worker

XFA form scripting

The XFA flattening engine reuses this runtime only when THotPDF.XFAJavaScriptEnabled is explicitly set; it supplies a restricted data facade, native typed arrays, validated instance requests, and no file, process, browser, or network objects

TXFAFormScriptOptions.JavaScriptEvaluator can adapt the static runtime without forcing static QuickJS objects into every HotPDF application

See Bounded XFA FormCalc and JavaScript

Optional compact native alias Map

Version 2.1143.0 adds SupportsAliasMapOptimization and InstallAliasMapOptimization without changing required bridge ABI version 1. A general XFA Session installs the optional feature automatically before its support bootstrap; older providers retain ordinary Map storage

The initial alias object keeps its genuine native Map brand and observable methods, order and live iteration. Consecutive hexadecimal identities sharing string targets use compact runs; general types and histories atomically promote to the ordinary native representation under the same memory and execution budgets. Ordinary application-created Maps remain generic

Windows DLL and static build paths and the Linux bridge build apply the same pinned core hooks through tools/prepare_quickjs_alias_core.py. The tool verifies the vendor core, header and project helper hashes, applies unique exact edit spans into a new private directory and records a source manifest. It does not edit vendor sources or reuse an existing output directory; existing platform-specific transforms follow preparation

Rebuilding the bridge is required to obtain the optional export. Deploy the matching architecture's rebuilt provider with the updated Pascal unit and generated XFA support source; merely updating documentation or a capability declaration does not update an older binary. See Session storage and limits

Reproducible runtime build

powershell -ExecutionPolicy Bypass -File Lib\thirdparty\build-quickjs-runtime.ps1

The build script produces both static object sets and both bridge DLLs from the bundled source and requires Python 3 for pinned core preparation. Set HPDFQJS_PYTHON to select a Windows Python executable or PYTHON for the Linux build. Generated source directories and their manifests remain in temporary storage for inspection

Guarded alias predecessor scans

Version 2.1147.0 adds an optional read-only query to the existing native alias installer. For an enabled compact Map with an admitted hexadecimal identity, it can prove that no current value refers to the newly bound alias and avoid enumerating every alias pair

The query also verifies the ordinary same-realm iterator path without invoking getters, Proxies or lazy property initialization. It checks Map and Array iterator functions and the return lookup observed by pair destructuring. Any uncertainty, matching predecessor or customized path retains the original loop

The original tick executes before the query, and the fallback uses the same iterable value obtained for that loop. Borrowed native set, delete and clear operations remain visible through the current native backing; no separate mutable reverse index or duplicate value roots are introduced

Version 2.1147.1 extends this proof to the same enabled Map after promotion to general storage. A fixed 512-bit summary records primitive values of sixteen UTF-16 code units through successful native writes. An absent query bit proves absence; a collision or a saturated summary retains the original loop. Deletion and replacement keep stale bits conservatively, while clear resets the summary after removing the live entries

The summary is independent of compact backing and contains no JavaScript roots. Each enabled Map allocates 64 bytes through the existing runtime allocator, and each native Map-state structure gains one pointer, including ordinary Map, Set and weak variants. Allocator rounding and the existing memory budget still apply; no process-memory reduction is promised

The retained sparse-key and object-key-promoted 4000-binding families now complete under the original budgets in native Session controls, including public replay after rollback. Focused Win32 DLL, Linux native-provider and Win64 static controls also pass. Custom iteration, genuine predecessors, collisions and saturation can still require full scans, so arbitrary binding histories do not gain a constant-time guarantee

See promoted alias acceptance (Tests/XFA/IdentityStorage/PromotedAliasScans/Readme.en-us.md) for frozen sources, original failures and focused execution evidence

The first ordinary loop can materialize lazy iterator methods before a later query admits. Older compatible bridges without the optional query retain their existing behavior. Rebuild and deploy the matching native provider and generated support source to obtain the optimization

The event and self-contained external-evaluator bootstraps initialize Handles before Retention so the query is captured before the original temporary installer global is removed. Delphi Sessions reuse the immutable prelude's UTF-8 byte charge between assignments instead of converting the whole factory during every retired-membership callback; all original journal checks remain, and FPC retains its original codepage conversion path

The retained 4000-binding family completes in native Session and real event paths under the original memory, stack, operation, time and interrupt limits. This is a focused profile, not a claim that every alias representation, custom iterator or complete dynamic XFA application has constant cost

See guard, trace, actual event and deployment acceptance (Tests/XFA/IdentityStorage/GuardedAliasScans/Readme.en-us.md) for exact producers and the preserved failed integration attempts

Optional native retired identity registry

Version 2.1135.0 adds the optional HPDFQJS_InstallRetiredRegistry bridge export for session-owned exact identity membership. Rebuild the bridge with the existing runtime scripts to enable disk-backed retirement storage

The original required ABI remains compatible. A bridge without this export continues to use the original JavaScript membership representation; THPDFQuickJS.SupportsRetiredRegistry reports whether the loaded bridge carries the V1 export, and support discovery does not claim that older binaries have the new storage behavior

Optional native retired value registry

Version 2.1140.0 adds InstallRetiredValueRegistry and SupportsRetiredValueRegistry for exact primitive scalar membership, including Number SameValueZero and type-separated BigInt, string, boolean, null and undefined keys

Rebuild the native bridge with the existing Windows or Linux build script to obtain HPDFQJS_InstallRetiredValueRegistry. Older bridges remain compatible through optional capability discovery. The original V1 string callback is unchanged

The Session prefers the typed callback when present. Version 2.1141.0 adds exact object, function and Symbol membership when the installed native function exposes its own strongValues=true data capability; inherited properties and accessors do not enable that route. Earlier scalar-only V2 bridges and V1 bridges retain references in the existing strong JavaScript Set

Reference keys use 00 4F for objects and functions or 00 59 for Symbols, followed by big-endian engine and JSValue identity pointers: 18 bytes on 64-bit targets or 10 bytes on 32-bit targets. They do not coerce values or trigger Proxy traps. Existing scalar wire formats and V1 callback fields remain unchanged

A strong callback provider must be fresh, engine-private and append-only, with coherent membership and insertion results. Reinstallation must preserve the same namespace, and a namespace must never be reused after engine destruction or rebuilding. The Session recreates its index with the engine

For a missing reference, the bridge reserves root-vector capacity under the engine budget before host insertion and retains one JSValue only when insertion reports a new member. Teardown releases those roots without reading the provider. The vector and object payload still consume linear heap; transient key conversion and the existing engine and journal limits apply without raised hard caps

Hosts implementing callbacks must consume explicit-length opaque bytes synchronously and keep V1 raw and V2 typed backing-store namespaces separate

Indexed compiled-script cache

Version 2.1144.2 indexes the optional process-wide compiled-script cache by source hash, then verifies the complete source length and bytes before accepting a hit; distinct scripts and embedded NUL bytes retain exact source identity

Retained-history rebuilds search the matching bucket instead of walking the entire cache for each script. Removal updates both cache indexes directly, and stored-entry statistics use a maintained counter

Hashing still reads the source bytes, collisions still require exact comparison, and the original oldest-use eviction search remains linear in entry count. Bytecode restoration, script execution, result conversion and execution limits retain their existing behavior

The existing 256 MiB cap and stored-byte statistic charge source and serialized bytecode only. The fixed index adds 512 KiB on 64-bit hosts or 256 KiB on 32-bit hosts; entry records also grow from 48 to 80 bytes or from 32 to 48 bytes respectively, outside that payload statistic

The 2.1144.2 index changes lookup cost only. With the optional owner support added in 2.1146.0, Session-only entries are reclaimed on Session destruction; unscoped entries and older providers retain their original residency. Recorded epoch and random-seed prefixes can make repeated business scripts distinct cache keys

See the focused source-index acceptance (Tests/XFA/ReplayCompilationCache/IndexedSource/Readme.en-us.md) for native execution, collision and recovery controls and the separate cache-lifetime measurement

Session-owned compiled-cache lifetime

Version 2.1146.0 adds optional compiled-cache owner registrations without changing required bridge ABI version 1 or the EvalCached signature. Exact source bytes still identify one shared source/bytecode entry across owners

SupportsEvalCacheOwners requires a live engine, EvalCached and all three owner exports; THPDFQuickJS.SupportsEvalCached and THPDFQuickJS.SupportsEvalUncached report the two evaluation-phase exports separately. Use TryCreateEvalCacheOwner, TrySetEvalCacheOwner and TryReleaseEvalCacheOwner for explicit lifetimes

THPDFQuickJS.EvalUncached runs the cached-compatible budget phases without cache lookup or storage, and THPDFQuickJS.TryGetEvalCacheStats returns the shared cache counters — hits, misses, stored entries, stored bytes and the byte cap — for telemetry

An XFA Session automatically keeps one owner across dirty engine rebuilds. Destroying the Session first frees its engine, then releases its owner through the still-pinned module, reclaiming entries used only by that owner. Other owners, their shared entries, public replay strings and JavaScript roots retain their existing lifetimes

Owner zero selects the original unscoped mode. Unscoped cache entries stay eligible for reuse while the module remains loaded and are never charged to the owner budget. A successful unscoped use of an owned entry promotes it to that legacy lifetime

New owner records, membership links, owned-entry state and their fixed directories have a separate 16 MiB native bookkeeping cap. The directories occupy 608 KiB on 64-bit hosts or 304 KiB on 32-bit hosts; each engine adds one pointer, 8 or 4 bytes respectively. These are separate from VM memory, the existing source index, allocator overhead and the unchanged 256 MiB source/bytecode statistic

Explicit owner creation reports resource failure when it cannot register an owner. Optional cache-membership allocation failure uses the existing compile-miss execution path instead of failing an otherwise valid script; compile/execution deadlines and conversion guards remain unchanged

Normal Windows DLL unloading destroys the private heap used for persistent cache allocations; normal Linux shared-library unloading releases completed cache/owner storage. All engines and API calls must have finished before unload. Windows process-termination detach skips cleanup; Linux cleanup skips a busy cache or live engines rather than waiting. Static hosts have no module-unload hook

Older compatible bridges remain loadable and keep their original cache residency. Deploy rebuilt matching native artifacts to obtain owner reclamation and unload cleanup. See focused owner-lifetime acceptance (Tests/XFA/ReplayCompilationCache/SessionOwners/Readme.en-us.md) for tested artifacts and limitations

Direct event compilation cache

Version 2.1148.0 reuses compiled direct-eval source at the shipped XFA event wrapper's fixed call site. The core recognizes the exact wrapper source, static argument and local layout, permissions, mode and same-realm execution; the key includes the complete serialized static caller signature, call-site flags, filename and exact event-source bytes

A hit restores a fresh bytecode graph and creates fresh closures using the current invocation's frame and variable references. Current event bindings, lexical captures, intrinsic-versus-replaced eval dispatch and the original execution limits remain effective; a saved executed closure or earlier event result is never reused

Tagged templates, larger sources and other unadmitted constant graphs use the original compilation path without rejecting valid JavaScript. Optimization admission is limited to 64 KiB of input, 256 KiB of combined key and bytecode and a 512-atom writer bound. Native serialization workspace has a 1 MiB logical allocation budget, with allocator overhead additional; these are cache-admission limits rather than increases to the engine's accepted-input or execution budgets

Direct entries share the existing 256 MiB native payload cap and 16 MiB owner-bookkeeping cap, charging the complete key and bytecode bytes. Their masked namespace remains separate from the original global source keys, while cache statistics report global and direct entries together. Existing owner sharing, eviction, Session release and normal module-unload rules apply

Each context adds two native pointers, 16 bytes on 64-bit targets or 8 bytes on 32-bit targets. Persistent cache entries retain native key and bytecode bytes without retaining an additional VM bytecode graph, JS root, caller frame or executed closure. Cache misses and recoverable admission failures use original compilation; interrupted or uncatchable faults preserve their failure state. A contended cache lock is tried once rather than waited on

This feature is supplied by matching rebuilt native artifacts and adds no JS global or public Pascal or C ABI. The shipped JS and Pascal modules and the existing global EvalCached serializer and admission behavior are unchanged

Focused public-event acceptance passes 105 checks on each Windows architecture, 14 Linux checks, five static-runtime checks and four continuous cold/hit limit checks, with the existing 11-check public alias control retained. In the finite 32-event profile with changing current bindings and two alternating sources, combined statistics change from zero hits and 33 misses with the older provider to 30 hits and 35 misses with the new provider, which also counts the new direct namespace; owner release restores the original entry and byte baseline

See Session event compilation and the focused direct-event acceptance (Tests/XFA/ReplayCompilationCache/DirectEvents/Readme.en-us.md) for exact artifacts, retained controls and scope

Optional native replay field provider

Version 2.1142.0 adds InstallReplayProvider and SupportsReplayProvider for synchronous exact script/result field reads from an immutable host replay journal

Rebuild the matching native bridge to expose HPDFQJS_InstallReplayProvider. Required ABI loading and both retired-registry modes remain unchanged; older compatible bridges keep the eager JS replay pool

The provider uses an exact-length two-pass UTF-8 query/copy protocol. A zero-length field is a valid empty string. The bridge owns temporary allocations, and host callbacks must not reenter or destroy the engine

The constructor's actual script-byte limit applies to the fetched recorded script, not just the short outer Eval call. New fetch infrastructure errors and the original fetch deadline remain effective through completion conversion, so a JS catch or toString cannot turn those failures into success; ordinary unavailable IDs remain nonfatal

Native-mode Sessions synchronize logical-ID metadata before user execution and fetch only fields actually used by generated replay fragments. The bootstrap captures the provider and removes the Session's temporary raw global; direct advanced engine installation intentionally leaves its raw native function exposed

In the finite Win64 profile of 32 published 32 KiB inert payloads with an otherwise matching control, pool and control engine malloc both report 90275 bytes, compared with 1150437 pool bytes in the original eager implementation. This removes that measured unused-payload residency class, not required state reconstruction or all process storage

Published payload bytes remain on disk until their permitted lifetime ends, and explicit legacy entry access still retains a stable frozen pair. Normal strong roots, object payloads, live history hydration and existing VM, journal and cache limits remain in force

See Session replay field residency and the targeted native-provider acceptance (Tests/XFA/ReplayReferences/NativeProvider/README.en-us.md) for the tested scope