Bounded XFA FormCalc and JavaScript

Version 2.1206.0 adds native validation-picture matching before scriptTest, with independent policies, inherited messages and rollback on refusal

Version 2.1205.7 skips validate/script execution for empty or explicitly null field and exclusion-group values, including direct HPDFXFAEvaluateFieldScript calls and prepared standalone contexts; skipped results succeed with no executed script

Nonempty values, including a preserved space, retain normal script validation; valueless subform containers are not treated as empty scalar fields, and foreign or detached field/data nodes retain their live-document diagnostic

This empty-value rule does not add full nullTest or calculated-input override handling: ordinary clearing is not an explicit nullTest trigger, and the script API remains distinct from complete form validation

HotPDF evaluates XFA calculate scripts while flattening a form, with an always-available bounded FormCalc path and a broader QuickJS path that remains disabled until the application explicitly enables it

Native flatten lifecycle

Version 2.1191.2 runs nonempty native FormCalc initialize and ready events while flattening, including selected-record output, without enabling a JavaScript provider

Initialization, existing calculations and bounded layout-ready rounds complete before field or page emission; accepted values, including empty values, feed both layout measurement and emitted field values

Ordinary dependent calculations resolve current Form references in their actual SOM scope before the legacy data fallback, so an initialized unbound field is not replaced by similarly named old datasets content

An omitted script contentType defaults to FormCalc, so ordinary native initialization statements and loops follow the same evaluator as explicitly typed FormCalc events

Calculate-only forms retain the existing expression evaluator and its date/function library; native event standard-library breadth and cross-document batch query methods remain separate compatibility work

Existing script operation, reflow and deadline limits apply; a lifecycle failure is reported before output callbacks begin for that document, while external callback side effects from earlier documents cannot be undone

Extended FormCalc

FormCalc expressions support arithmetic, strings, booleans, comparison operators, short-circuit And, Or, and Not, plus the lazy If(condition, whenTrue, whenFalse) branch

Sum, Avg, Min, Max, and Count accept mixed scalar and SOM node-set arguments using rooted, direct, indexed, wildcard, or descendant paths such as $record.rows[*].amount; only the selected branch of If is evaluated, so an unused invalid branch does not reject the calculation

Nested calls can combine numeric, string, and node-set results, with deterministic support for At, Choose, Concat, LTrim, RTrim, Str, Stuff, Null, Sign, Exp, Log, Sin, Cos, Tan, Deg2Rad, Rad2Deg, Within, and Oneof

The expression-only calculate path retains its existing bounded function library; native event scripts additionally support the statement, function and loop profile described below, while broader locale picture clauses and network functions remain separate work

InstanceAdd(name, count) and InstanceRemove(name, index) dispatch through OnXFAInstanceAction only after argument and operation-budget validation

Provider-free FormCalc events

Version 2.1185.0 adds a native evaluator for ordinary runtime events marked application/x-formcalc and computed FormCalc input-reference predicates when EnableJavaScript is False

It supports local variables, if/elseif/else, while and for loops, foreach lists, functions, recursion and early return, with bounded expression depth, operations, values and elapsed time

Event scripts can read and assign field values and presentation properties, query accepted Form, Template and Data contexts, use instance operations and rebuild the Form within the existing transaction rules

For example, var total = Sum(score,5) if (total ge 30) then this.presence = "invisible" endif uses the event owner's scope without enabling JavaScript

Current-input selection and replacement edits, candidate versus listener ownership, nested query continuation and retired explicit references follow the native input-listener profile

Version 2.1186.0 adds native choice item methods and exact selection, plus read-only dataNode references to accepted field values and subform groups

Version 2.1187.0 adds native instance-manager lifetime and actual new-instance returns, including saved and fresh empty-group managers, current occurrence limits and setInstances

Version 2.1188.0 interprets leading SOM class selectors in native resolveNode/resolveNodes as actual class queries, including indexed/wildcard fields, current properties and repeated-row FormCalc predicates; class lookup searches current children before the existing scope fallback and retains root-self results when no child candidate exists

Version 2.1189.0 adds native conditional layout execution, including extended FormCalc page-break conditions, live layout-ready state, mutation restart and shared limits; the broader date/locale library, additional DOM and generated-context combinations remain separate compatibility work

Version 2.1188.2 gives native and JavaScript class queries and classAll/classIndex actual-parent sibling scope across unnamed containers, while ordinary names and explicit descendant queries retain their existing traversal behavior

Version 2.1190.0 adds native accepted-layout queries for pages, spans, parent-relative fragment geometry and actual page-content references, with native foreach collection expansion and exact unbound-event contexts

Version 2.1191.0 adds native relayout and page-area requests, including bounded layout-ready continuation after nested remerge and complete transaction rollback

Version 2.1191.1 adds native sheet queries for physical page surfaces, including unnumbered pages and duplex filler surfaces

Native FormCalc Replace matches Unicode text without a platform code-page conversion. With an empty search string, replacement text is inserted between Unicode characters, keeping supplementary characters such as emoji intact

Native FormCalc Upper and Lower apply the compiler runtime's Unicode case mappings without converting text through the platform code page

Native FormCalc Ltrim, Rtrim, and Trim remove ASCII whitespace and Unicode space separators from the selected ends, while preserving internal whitespace and the rest of the original text

Native FormCalc Stuff accepts three arguments for deletion without insertion. The start is one-based, with out-of-range positions limited to the first or last character of a nonempty string. Insertion and deletion preserve supplementary Unicode characters

Native FormCalc Len, At, Left, Right, and Substr count a supplementary Unicode character as one character. A nonpositive Left count returns an empty string, and Substr limits the start to the first or last character of a nonempty string

FormCalc compiled through QuickJS uses the same character offsets and boundary rules for Len, At, Left, Right, Substr, and Stuff. Empty-search Replace inserts between Unicode characters, and the trim functions recognize ASCII whitespace and Unicode space separators

FormCalc uses numerically stable formulas for very small nonzero rates in Pmt, FV, PV, Rate, CTerm, Term, and NPer. Rate and CTerm retain precision for nearly equal amounts and avoid an intermediate ratio overflow or underflow when the result is representable

Version 2.1192.0 completes the provider-free FormCalc standard library with current and ISO date/time conversion, locale-aware DateFmt, TimeFmt, Date2Num, Num2Date, Time2Num, Num2Time and Num2GMTime

Native Format and Parse support numeric, date, time, datetime, text and compound picture clauses, including document localeSet symbols, named patterns, currency, grouping, signs, quoted literals and input validation

The same evaluator also implements UnitType, UnitValue, Encode, Decode, Uuid, WordNum, Str, Apr, IPmt and PPmt without enabling JavaScript or exposing implicit network I/O

Apr returns zero when the payment equals the principal divided by the number of periods and uses a stable payment calculation when solving for small positive rates

IPmt and PPmt accept nonnegative whole payment indices and counts, with zero as an alias for the first payment. Their payment ranges fit signed 32-bit indices, and amortization stops when the remaining principal reaches zero

NPV discounts signed cash flows without forming an oversized denominator, preserving cash flows whose discounted value still fits in a double

Numeric literals in XFA field calculations can use e or E with an optional exponent sign, as in 2.5e-3

Version 2.1193.0 adds native node.getElement(name, occurrence) on Form and property nodes, returning the occurrence-th existing child by class name and creating schema-legal missing children with their defaults

Occurrences beyond the schema cardinality and property-choice conflicts fail with specific diagnostics, names outside the property schema return null, and returned references stay live across writes while retired references remain rejected after remerge

Optional JavaScript

Version 2.1188.1 corrects JavaScript SOM class queries when the current container and its children share a class: indexed/wildcard subforms and FormCalc or JavaScript predicates select the actual child instances before the existing upward scope fallback

Form and Template root-self queries remain available when no original child candidate exists, while a predicate that rejects existing children stays empty; saved row edits, fresh queries after remerge and transaction rollback retain their existing rules

Version 2.1191.4 expands FormCalc foreach collections on the provider path, matching the provider-free evaluator: each parenthesized argument is visited member by member instead of being bound whole, an empty collection iterates zero times rather than once, argument and document order are preserved across mixed scalar, single-node and collection arguments, and every member is the actual node reference so assignments and Ref comparisons inside the loop reach the field the loop variable names

Each argument is evaluated once before the loop and the member list is frozen, so a body that writes through a member cannot change the set being iterated; break, continue, return and nested loops keep working across expanded members, every item stays charged to the shared operation budget, and argument, array and item ceilings under MaxArrayItems report separately

Version 2.1191.5 honors explicit non-self ref declarations on enter and exit events driven by public focus changes: refOnly selects the actual target, refAndDescendents also selects an accepted ancestor, and a declaration no longer runs against its owner merely because that owner receives focus

Explicit focus listeners run after the target's own event and before the next ancestor scope, with exit references preceding parent validation; focus redirection, bound-instance remerge continuation and the existing transaction budgets and rollback are retained

Version 2.1191.6 connects JavaScript xfa.layout.relayout() and relayoutPageArea() to the bounded lifecycle scheduler, so an explicit request triggers a real ready round even when geometry is unchanged and page-area requests can publish additional pages

The optional page argument is checked as a nonnegative safe integer within the accepted layout; request order around remerge, retained layout facade lifetime, coalesced and successive requests, shared reflow budgets and exact transaction rollback follow the provider-free behavior

Set THotPDF.XFAJavaScriptEnabled to True before ApplyXFAAsAcroForm or FlattenLoadedXFA to run scripts whose contentType selects JavaScript

The runtime supports normal JavaScript control flow and native typed arrays such as Float64Array, but receives no file, process, network, browser, or application object; fetch, XMLHttpRequest, WebSocket, require, process, and Deno are unavailable

var
  Budgets: THPDFXFAFormScriptBudgets;
begin
  Budgets := THPDFXFAFormScriptBudgets.Default;
  Budgets.MaxElapsedMilliseconds := 100;
  Budgets.JavaScriptMemoryBytes := 8 * 1024 * 1024;
  PDF.XFAFormScriptBudgets := Budgets;
  PDF.XFAJavaScriptEnabled := True;
  PDF.OnXFAInstanceAction := HandleXFAInstanceAction;
  PDF.ApplyXFAAsAcroForm(XDPBytes, False);
end;

Script context

JavaScript receives a mutable this.rawValue, an event.value, and a frozen xfa facade

Budgets and telemetry

THPDFXFAFormScriptBudgets bounds script bytes, FormCalc operations, elapsed time, expression depth, repeated-array items, value bytes, instance operations, JavaScript memory, JavaScript stack use, and interrupt checks

The stack budget provides the recursion boundary, while the time and interrupt budgets stop non-terminating loops; scripts that cross any boundary fail closed and append a diagnostic to XFAFlattenWarnings

XFAFlattenScriptsEvaluated, XFAFlattenScriptsRejected, and XFAFlattenInstanceOperations report the latest flattening pass

Direct runtime integration

The extended HPDFXFAFlatten overload accepts TXFAFormScriptOptions and TXFAFormInstanceAction directly; assign TXFAFormScriptOptions.JavaScriptEvaluator to adapt the static QuickJS binding or another application-owned evaluator while retaining the same wrapper and budgets

See TXFAFormScriptOptions, TXFAFormScriptLimits, THPDFXFAFormScriptBudgets, and THPDFXFAInstanceAction

Standalone field evaluation

Version 2.1198.1 adds HPDFXFAPrepareStandaloneFieldContext, HPDFXFAEvaluateFieldScriptInContext and HPDFXFAReleaseStandaloneFieldContext, so a single field script can be evaluated without flattening or running the whole form

Preparation builds a real field context over your own document: the actually selected record, widget geometry taken from the document medium and a materialized form model, without replaying the form initialize or ready events

TXFAStandaloneFieldContext carries one shared operation pool and one absolute deadline started from your TXFAFormScriptOptions limits; both persist across evaluations through the same context and are never reset, and releasing a context frees the runtime the factory created while leaving a joined external runtime alone

A field or data node outside the document, an exhausted operation pool and an expired deadline each fail with a specific diagnostic, and a failed standalone evaluation restores the document bytes it touched so the same context can be retried

FormCalc runs through the native interpreter while JavaScript is disabled, and JavaScript through the runtime session while it is enabled without an external evaluator; every other combination, and every call without a prepared context, keeps the existing field script engine unchanged

var
  Context: TXFAStandaloneFieldContext;
  Evaluation: TXFAFieldScriptEvaluation;
begin
  if HPDFXFAPrepareStandaloneFieldContext(Document, Options, 0, 0, Context) then
  try
    Evaluation := HPDFXFAEvaluateFieldScriptInContext(
      Context, FieldNode, DataNode, xfskCalculate, Warnings);
  finally
    HPDFXFAReleaseStandaloneFieldContext(Context);
  end;
end;