API overview
For the full symbol inventory, public type contracts, and per-symbol examples, see the complete public API reference.
Model and compilation
import { cashflow, currencies, defineModel, entity, inflow, periods, schedule } from "deccf";
const building = entity.asset();
const rent = cashflow({ owner: building, direction: inflow, schedule: schedule.monthly(), amount: 5_000 });
const model = defineModel({
name: "example",
currency: currencies.SEK,
timeline: periods.monthly({ from: "2026-01", count: 12 }),
entities: { building },
flows: { rent },
});
return model;currency and timeline are required; the other maps are optional. currency is a Currency value. A run may select a different reporting denomination through run(model, { currency }); this does not convert numeric values. Map keys become declaration names in results, and their values are references created by API factories.
Optional inflation is an annual decimal rate (0.02 means 2%), supplied as a finite number greater than -1 or a declared scalar numeric input reference. It defaults to zero. Reuse an input wherever it belongs in the model's groups, tabs or pages. deccf.run(model, {moneyValue: "today"}) converts monetary outputs to purchasing power at the first resolved timeline date; "nominal" is the default. Rates, ages, text and plain numeric outputs retain their values. This output setting leaves financial callbacks and input values nominal; use inflation explicitly in a callback when nominal costs or income should grow. See Show money in today's value for callable examples, timing and validation.
Optional run setting amountStorage is "period" (default), "calendar-year" or "fiscal-year". Annual modes save monetary series and postings by year while retaining the calculation timeline, final metrics and Monte Carlo statistics. Flows sum after valuation; balances use their final observation; monetary metrics use annualAggregation. Fiscal dates follow each owner or an explicit metric fiscal start, with January for ownerless data. Compacted indexes publish exact dates, periodEnds and periodLabels. Authored calculation records and reference accessors retain their calculation detail. Invalid values are rejected. The setting is shared by run(), runMonteCarlo(), runScenarios() and fixed prepare() options. See Store monetary results by year for callable examples and saved result/report details.
Optional model setting monteCarlo: {execution: "indexed", baselineMetrics: [...]} selects strict indexed Monte Carlo for static sampled dependencies and declarative final-period metric({value}) outcomes. baselineMetrics defaults to []; unique declared names select fixed baseline outcomes whose final numeric values are repeated across all trials. Indexed mode summarizes declared numeric metrics and omits automatic sampled total, npv, irr and wal summaries. The complete ordinary baseline retains its reports and built-in metrics. Unsupported sampled dependencies and active approximation above 1,000 trials are rejected. Omission preserves general execution. See Indexed Monte Carlo for validation and Simulate uncertainty for a callable example through deccf.defineModel() and deccf.runMonteCarlo().
Optional monteCarlo: {samplingLayout: "static-first"} reserves declared bind.sample() coordinates before the remaining owner/period coordinates for Sobol. Annual bindings reserve one early sample per represented calendar year, which helps long forecasts with many entities stay within the 21,201 supported coordinates. Omission preserves existing Sobol streams; the opt-in preserves global draws and all pseudorandom streams. See Static-first Sobol layout for the complete contract and a callable example.
compileModel(model)validates the model and returns a plan with dates, references, periods, and dependency order.run(modelOrPlan, options?)evaluates the model. Declarations are compiled automatically.prepare(modelOrPlan, options?)prepares fixed structure for repeated.run({parameters?,seed?,trial?})calls. Optionaloutputsselects final values instead of a full report.- Calculations and cashflows default to static
bindingsand callbacks receiving(values,{time,currency}). Usebind.previous,bind.history,bind.parameterandbind.oncefor historical and execution-scoped reads, or explicitly setdynamic:truefor the broad context. See Static bindings. ModelErrorexposes a stable machine-readablecode, optionalpathandperiod, anddetails.
result.deterministic.account_postings serializes account movements with period, account, type, category, side, amount, and flow metadata. It includes explicit booking rows and moves movements. Account-plan closing rows have flow_role: "period-close", allowing a report to distinguish closing entries using only the run output.
Values and inputs
- Currencies:
currency("SEK")creates a three-letter uppercase code.currenciesincludes USD, SEK, EUR, GBP, NOK, DKK, CHF, CAD, AUD, and JPY. - Money:
money(amount, currency, {date}?),scaleMoney,addMoney,subtractMoney, andconvertMoney(value, target, unitsOfTargetPerSource). An explicit valuation date such as"2027-01-01"takes priority over a money series point or final metric date during today's value conversion. It also dates future Money leaves inside a record produced in an earlier model period. Scaling and currency conversion retain the date; addition and subtraction retain it only when both operand dates match. - Ready input bounds:
deccf.sym.posis[0, 1e8],deccf.sym.max100is[0, 100], anddeccf.sym.max1is[0, 1]. Use them asdomainvalues. Domains expose their ownsymoption libraries: householdbudgetMode, housingkeepSellBuy, loanskeepSettleNewTempandamortMethods, and Swedish family benefitsbenefitKinds. For example,input.enum('keep', {options:modules.housing.sym.keepSellBuy('en')})offers Keep, Sell and Buy. Option functions accept'sv'or'en', default to English and keep the same stored values in both languages. All collections are immutable. - Direction:
inflowandoutflow. Create categories for a model withcategory(path), such ascategory("sales.subscription"). An optional{ label }gives the category a display name indeterministic.categories. The core has no predefined categories; domain packs can provide them. - The accountplan domain pack adds account codes and classifications. The Swedish income-tax pack is separate.
- Inputs:
input.decimal,rate,fraction,integer,boolean(aliasboolen),lockable,hidden,readonly(aliasreadOnly),str,id,enum,date,money,object,objectArray,textfile,tableToSie,sni,curve,normal,logNormal,uniform, andtriangular.derived({ inputs, calculate })declares a value derived from other references before simulation.input.textfile(defaultText?)is a string precondition; a run can replace it with the contents of a text file or any other string throughdeterministic.inputs.input.tableToSie(defaultContent, options?)is also a normal textfile string, displayed as an editable table for SIE periods and balances. It can offer personal or business account choices, separate balance/result tabs, add complete financial years, and import a local SIE file. Both inputs can be sent directly tosieStatement().input.sni(mainGroup?)is a string precondition validated against the SNI 2025 two-digit main-group list. It carries dropdown choices in the model description and result metadata for UIs.
fraction must be between 0 and 1; integer must be a whole number. Numeric values must be finite and can be checked against a domain. A date input accepts an ISO year-month or date. Curves and distributions are covered in Valuation and uncertainty; run-time overrides are described in Run configuration.
input.tableToSie(defaultContent, options?) keeps an SIE document as an ordinary string input and displays its supported account balances in a table. All six options default to false: dynamicAccounts enables adding and removing account rows; businessAccounts and personalAccounts offer those account plans in the account selector; splitResAndUb separates balance accounts (#UB) and result accounts (#RES) into tabs; dynamicPeriods enables adding or removing whole-year periods at either edge; and fileDrop enables choosing or dropping a local SIE file. If a selected account plan is enabled, choosing one of its personal accounts writes a numeric SIE account code and its account name so sieStatement() can map the balance back to that personal account. Existing input.textfile() values remain supported by sieStatement().
The SIE import pack's thisYear(offset = 0) returns the current calendar year and its January 1 to December 31 dates. An integer offset selects an adjacent year, for example thisYear(-1) for the previous year.
input.boolean(true, { ui: "switch" }) displays a switch; { ui: "check" } displays a checkbox. Both store true or false. To give the choice a label, use { ui: { control: "switch", label: "Include extra costs" } }. Without a control choice, the editor displays Yes/No buttons. New collection rows default to false; set newItem: true when needed.
input.lockable(true, input.money(1000, currencies.SEK)) groups a lock and a typed value as { locked: true, value: { amount: 1000, currency: "SEK" } }. Locked means use the model's declared default: the value and all its nested fields are read-only, including array rows, and adding or removing rows is unavailable. The lock toggle remains available so you can unlock and enter a custom value. Turning the lock on discards the custom value, restores the declared default and keeps focus on the toggle. For an object this restores its default fields; for an ordinary array it restores the original rows, order and IDs. Connected arrays continue to follow their source's rows and bound values. Turning the lock off keeps the displayed value and restores editing, while fields declared read-only or bound to another input stay protected. Nested locks keep their own state after unlocking the enclosing lock. The inner input keeps its currency, limits and new-row default; new rows retain the declared initial lock state. You can wrap an ordinary scalar, object or object-array input.
Collection add buttons display a plus by default. Use input.objectArray(rows, { ui: { addLabel: "Add person" } }) for a visible label beside the plus. An omitted or empty addLabel displays only the plus; the button retains an accessible name.
Input display metadata also accepts optional ui.initialValueFrom to retain a saved value when moving an input to another group:
const growth = deccf.input.rate(0, {ui:{initialValueFrom:"domain.legacyGrowth"}});When opening a saved case or scenario draft, a missing target field copies the source value at that absolute object-field path; an explicitly supplied target value, including zero, wins. The path starts with a root input name and follows nested object fields. Omission, missing or malformed paths, accessor or inherited properties and array-row selections fall back to the declared default. The source is read from the saved values before reconciliation, without changing them. This metadata changes draft initialization only; direct calculation inputs still follow their ordinary validation rules. Keep former fields optional when direct saved records must remain valid.
Object input display metadata accepts optional ui.note text after its fields. It appears at the end of the owning object, group, aspect tab, section page or domain. It defaults to absent; blank and non-string values display nothing. Notes display as plain text, add no saved input or calculation value, and do not apply to scalar fields, arrays, compact sum dropdowns or custom widgets. App language resources translate them like other authored labels.
const savings = deccf.input.aspect({
annualSavings: deccf.input.money(25000, deccf.currencies.SEK),
}, {ui:{label:"Savings",note:"Enter the same nominal amount for each year."}});
// Include savings in a section or register it as a model input.input.hidden(value) retains a value without displaying a field. input.readonly(value) displays it without allowing edits; input.readOnly is an alias. Both accept a typed input or a scalar literal and retain the original type. Their declared values remain authoritative when running a saved case. Inside a connected array they also accept projections such as members.item.data.name, which follow the corresponding source row.
input.objectArray(rows, {type:"table"}) displays a Tabulator table with the same typed field controls and keyed values as cards. {dynamic:false} hides collection add/remove actions. To make another list control membership, declare connectedSource: members and bind the target key using input.hidden(members.item.data.id). Connected rows follow source order and cannot be added or removed independently. Editable values stay with their keys, new rows use the item template's initial defaults, and source-bound fields refresh automatically. {connectedWhere:{role:"adult"}} includes only matching source rows. Declare the source in the same model; it can live on another input page. See Connected input pages.
input.object(fields, {type:"sumdropdown", label:"Operating costs & land lease"}) groups values in a compact control: a read-only sum with a dropdown containing the editable fields. input.Object is an alias of input.object. The panel opens downward over following fields. Numeric values and Money amounts contribute to the summary; text and booleans do not, and different currencies retain separate totals. The submitted value remains the original nested object. label sets ui.label while preserving other UI options. See Compact cost groups.
Alternative object inputs
Use deccf.input.Object(variants, {title}) (or lowercase object) to select one object, defaulting to the first variant. Use deccf.input.objectArray(variants, {type, title}) for mixed cards: manyOfAnyChangeable allows repeated types and changing each card's type; manyOfAny chooses a fixed type when adding and allows repeats; anyOf allows each type once, reenabling a removed type. All three arrays start empty. Each variant is an ordinary object reference with a non-empty label and unique non-empty hidden string type.
const isk = deccf.input.Object({
type: deccf.input.hidden("isk"),
amount: deccf.input.money(2500, deccf.currencies.SEK),
annualReturn: deccf.input.rate(0.02),
}, {label: "ISK"});
const vp = deccf.input.Object({
type: deccf.input.hidden("vp"),
amount: deccf.input.money(2500, deccf.currencies.SEK),
annualReturn: deccf.input.rate(0.02),
}, {label: "VP-konto"});
const savings = deccf.input.objectArray([isk, vp], {type: "manyOfAnyChangeable", title: "Sparande"});
const selectedSavings = deccf.input.Object([isk, vp], {title: "Sparande"});Register these references in preconditions. input.rate(0.02) means 2%. New cards use authored defaults and fresh hidden IDs when no explicit key is declared. Switching preserves identity and compatible common values; target-specific fields reset to their declaration defaults and inactive fields are removed. Saved unknown types and invalid catalogues produce explicit errors. Variant declarations do not support connectedSource or connectionBinding; ordinary connected lists remain supported. See Offer alternative object inputs for all four callable modes, saved values, identity, switching and validation. Ordinary object fields, homogeneous row arrays and table views keep their existing contracts.
Input options accept visible:true, visible:false, or visible:{field:"decision",values:["keep","buy"]}. A condition displays the field when its declared sibling decision has one of those values. Conditions use fields in the same object or row. Changing visibility retains the field's value and validation, so switching back restores the entered amount. This also applies to groups, compact objects and arrays. ui.visibleWhen accepts the same condition as a presentation alias; an explicit visible option takes precedence. Visibility controls presentation, while input.hidden declares an authoritative hidden value.
const ownCost = input.lockable(true,
input.money(1000, currencies.SEK, { ui: { label: "Monthly cost" } }));
const enabled = input.boolean(true, { ui: "check" });
// Declare ownCost and enabled among the model inputs.
// ownCost.value uses 1000 while locked, or the entered value while unlocked.
const chosenCost = expr.when(enabled, ownCost.value, money(0, currencies.SEK));Components, collections, and funding
input.object({ field: inputValue })groups typed input fields into one value.input.objectArray(rows, { key: "id", item?, dynamic?, type?, connectedSource?, connectedWhere? })declares keyed rows rendered as cards or tables. Use a stable ID field and an explicit item schema when the initial list is empty. A connected array infers its key from the field bound to the source key; an explicitkeymust name that field.component({ entities, accounts, flows, calculations, components, outputs })composes ordinary declarations and exposes selected outputs.repeat(source, template)creates one component per object-array row. Inside the template,source.item.dataexposes row inputs andsource.item.outputsexposes component outputs..where({ role: "adult" })selects rows;.column("salary")gives a keyed column for allocation.allocation({ amount, method, limits?, redistribute?, signed?, unit?, schedule?, phase? })reports shares fromproportional({ weights, overrides?, zeroBasis? })orpriority({ order, requests? }). Allocation has no cash or account side effects.transfer({ from, to, amount, schedule, posting? })makes a balanced movement. Cross-owner transfers need a posting policy.funding({ from, to, amount, method, posting, schedule, limits?, shortfall? })uses the same allocation methods and records real transfers. Its calculation outputs are not counted again as cashflow.
See the declarative collections and funding guide for complete examples and the Household pack guide for a domain-specific composition.
Time
periods.daily/weekly/monthly/quarterly/annual({ from, count, projection? })phase({ from, to });frequencies.day/week/month/quarter/yearschedule.once(date, options?),.onceAfterNoOfDays(days),.every(frequency, options?),.daily,.weekly,.monthly,.quarterly,.annual,.yearEnd,.phaseStart,.phaseEnter, and.phaseEnd
Schedule options include from, to, interval, placement, except, also, dayOfMonth, and endOfMonth. See Time, phases, and schedules.
Entities and calculations
entity(options?)and the.asset,.party,.bundle, and.referencefactories. Optional properties includeowner,parent,fields,attributes, andlifecycle.ownerlinks an entity to another entity and includes it in owner-scoped grouping;parentdefines the entity tree.attributesholds static facts such as a person's date of birth. The Household pack exportshousehold()for household entities.field({ initial, next? })stores a numeric value per period.next(previous, ctx)can calculate the next value.cashflow({ schedule?, amount?, bindings?, dynamic?, direction?, owner?, agreement?, category?, currency?, active?, dependsOn?, readsInflowsFrom?, readsCashflowsFrom?, readsAccountsFrom?, readsHistoricalAccountsFrom? }). A basic cashflow normally declares a direction. A posting cashflow can omitowner; it inherits the owner if all booked accounts share one.directioncan be omitted when the cash account is selected or inferred, or when postings do not represent cash. A grouped flow can omit settings supplied by its group; compilation reports an error if a required setting is still missing. Flows follow model declaration order;dependsOnadds explicit dependencies.readsCashflowsFromorders a flow after the owner's cashflows, andreadsAccountsFromorders it after flows that post to selected accounts, excluding period-closing flows.readsHistoricalAccountsFromdeclares accounts a flow reads only from earlier periods, without adding same-period ordering edges.flowGroup({ flows, preconditions?, ...defaults })groups flows and nested groups, applies shared settings such asowner,schedule,direction, or dependencies, and can own named run inputs. A nested input likepreconditions: { openingAssets: { remainingLifeYears: input.integer(5) } }is discovered bydefineModel()and receives a stable dotted path based on its flow-group names. Values on an individual flow override the group. Put a group in the model'sflowsmap, or useflows(...items)to flatten groups and flows into an array fordefineModel({ flows }).statement({ name?, owner?, schedule, balances, balancingAccount?, dependsOn? })creates a flow group for importing absolute account values. Each{ account, value }entry targets an account balance. Astdaccountreference is registered automatically; ordinaryaccount()references must still be declared inaccounts. One-time schedules apply values once; recurring schedules spread the remaining adjustment over the remaining occurrences. Income values are positive, expense values are negative, and asset, liability, or equity values use positive normal balances; the engine converts them to signed postings. Untyped and transfer accounts use signed ledger values. SetbalancingAccountwhen the supplied entries do not balance; otherwise the statement requires a balanced set of account adjustments. See Import a historical statement.account({ owner?, side?: "owed" | "due", type?, initial?, category? })creates a balance.typecan beasset,liability,equity,income,expense, ortransfer. Posting rows inheritcategoryfrom their target account. Debits increase the signed balance and credits decrease it. For income and expense categories, reporting signs are reversed so income is positive and expenses negative. Other account categories follow signed movements.sideapplies tomovescashflows.stdaccount({ code, owner, initial? })creates or reuses a plan-backed account. The code is always a string, including numeric business codes such as"1930"and groups such as"19". It selects the account type and category from the Business or Personal account plan; person, household, and company entities can be owners. The compiler automatically registers accounts referenced by flows, statements, and supported domain packs. A matching explicit account keeps its name and opening balance. Declare an account inaccountsto choose its result name, retain an otherwise-unused opening balance, or register a reference used only inside a callback. Creating a parent while a more specific same-owner subaccount already exists is an error.cashflow({ debit, credit, schedule, amount, cashAccount? })is shorthand for two equal posting rows. Usebookings: [{ debit: account, amount }, { credit: account, amount }]for multiple rows. Each row sets exactly one side; amounts must be finite, non-negative, and balanced for each occurrence. If a row omitsamount, it inherits the cashflow's base amount or, for a triggered occurrence, the source amount. Each row inherits the account category; do not setcategoryon a posting cashflow.cashAccountmust be one of the booked accounts and its signed movement determines the flow's net cashflow. If exactly one booked account is an asset, it is inferred. Without a cash account or direction, a posting flow has zero net cashflow.ctx.amountexposes the base amount in booking callbacks.trigger(name?)creates a trigger reference.cashflow({ triggers })emits it for each occurrence. A subscriber usesschedule.onceAfterNoOfDays(days)and may specifytriggeredBy. When only one trigger type is emitted in the model, it can be inferred.ctx.sourcecontains the source flow, model name, optional trigger name, amount, currency, date, and period. Each received trigger creates an occurrence.state(label)andlifecycle({ states, initial, transitions?, onEnter? })define state. Actions includeactions.setState(entity, state),.setField(field, value),.activate(flow), and.deactivate(flow).event({ schedule?, when?, actions? })requires a schedule or condition.agreement({ subject, parties?, from?, to?, terms?, onStart?, onEnd? })attaches to an entity.partiesmaps roles to party entities. UseagreementTerm(value)for terms; declare cashflows separately.option({ subject?, direction?, currency?, schedule?, maxExercises?, when, payoff })creates a separate payoff series. Default direction is inflow and the default limit is one exercise. The condition must become true after being false; further exercises require another false-to-true transition.metric({ calculate, schedule?, label?, unit?, periodLength?, frequency?, annualAggregation?, owner?, fiscalYearStartMonth? })declares a model metric. The optional label and unit are copied to its result series for presentation. The window length and frequency are counts of model periods, both defaulting to 1. An optional calendar schedule, including a declared input or derived date, further selects eligible periods; it intersects the frequency and complete-window conditions. Omission retains every otherwise-eligible period. Skipped dates do not call the metric callback and appear asnullin its series. Trigger-relative schedules are rejected. A metric callback receivesctx.metricPeriodwith the inclusive period indexes and dates; annual results are rolled up withsumorlast. When an owner is set, itsfiscalYearStartMonthentity attribute supplies the default year boundary.
Calculation and cashflow callbacks are synchronous. Static callbacks read their declared binding values and receive {time,currency} as a second argument. With dynamic:true, they receive the broad calculation context, including reference readers, state access and optional draws. ctx.sumAccount(account, from, to, options?) totals the account's debit-minus-credit postings over inclusive dates; set excludePeriodClosing: true to ignore internal account-closing entries. A flow must list current-period dependencies in readsAccountsFrom; historical-only readers can use readsHistoricalAccountsFrom to avoid same-period dependency edges.
Runs and packs
runMonteCarlo(model, { trials, seed, ...runOptions })returns the complete ordinary base calculation together with numeric metric summaries across draws and runtime timings. Base outputs use the same overrides and central distribution values; summaries describe the sampled outcomes.runScenarios(model, scenarios, runOptions?)returns{ name, result }entries, each with its own result timings. The array also exposes atimingsproperty with per-scenario measurements and totals. Each scenario has a name and optionaloverridesmap keyed byInputReference; map values accept scalar inputs and curve series. Put scenario-specific inputs in the maps; shared run options apply across scenarios. Passtrialswithseedin run options to execute Monte Carlo simulations for every scenario.definePack({ name, version, extract })creates a reusable pack;extractPacks(model, packs)adds its declarations to the model.
The Household pack requires the Personal account plan. It exports household() and householdBudget({ household, members, funding? }). Enabling the module makes the declarations available; the model author explicitly creates a budget component for each selected household. Missing budget expense and cash accounts are resolved from the Personal plan during compilation. See the Household pack guide. The SIE import pack exposes sieStatement({ owner, sieContent }) to apply the latest imported account balances at the end of their SIE period. It recognizes the selected Business-plan accounts and Personal-plan accounts from the account numbers and names written by the SIE table input.
Period order and actions
Within a period, the engine opens period state, updates fields, applies lifecycle transitions and agreement boundaries, evaluates events, calculates cashflows in dependency order and posts movements, then evaluates options and period-end calculations. Actions cannot change periods already calculated. ctx.previous(accountRef) reads the account's opening balance. An ordinary calculation reads that opening balance with ctx.get(accountRef); an explicit phase:"periodEnd" calculation reads the settled current-period balance. Both declare accounts in readsAccountsFrom. Closing balances are also available from the result account series.
One current typing mismatch: runtime expects lifecycle onEnter entries as { state, actions }, while TypeScript currently declares Action[]. See Errors and limits.