/** * The workbook kernel: sheets, reactive atoms, and the mutation/commit/recalc * surface that is *always* present. Opt-in behavior (formats, merges, clipboard, * fill, provenance, names, async) lives in capabilities (`./capabilities/*`) * that assign their methods onto the instance during construction via * {@link WorkbookInternal}. This module deliberately does **not** import * `builtins` (the ~1375-line function catalog): the builtins default lives in * the `createWorkbook`/`Workbook` factory layer (`./workbook`), so a consumer * who constructs through the lean `constructWorkbook` entry and supplies their * own `functions` gets a module graph free of `./functions`. * * Invariants from the design spec: * 1. Mutation and commit are separate — `setInput` returns patches without * applying them; everything funnels through `applyPatches`. * 2. Computed values are never patches — they are re-derived on commit. * 3. `subscribeRegion` is the perf primitive — a grid observes only its * ~2k visible cells. * * `applyPatches` runs the full pipeline: apply inputs -> update the dependency * graph -> gather the transitive dirty set -> topo-sort (detecting cycles) -> * evaluate -> notify affected regions. */ import { createAtom } from '@tanstack/store' import { colOf, makeRect, pack, parseA1, rectContains, rowOf } from './addr' import { DepGraph, decodeNode, nodeId } from './deps' import { err, evaluate } from './eval' import { Scheduler } from './async' import { FunctionRegistry, mathRng, systemClock } from './ports' import { ParseError, parse, refsOf } from './parser' import { Sheet } from './sheet' import { makeCell } from './tx' import { validateCalls } from './validate' import type { ReadonlySheet } from './sheet' import type { Clipboard } from './clipboard' import type { WorkbookCapabilities, WorkbookCapability, WorkbookInternal, } from './capability' import type { AsyncPort, Clock, FunctionCatalogEntry, FunctionDef, FunctionOrigin, FunctionPack, FunctionPorts, Locale, PackManifestEntry, Rng, SheetProvider, VisibilityPort, } from './ports' import type { AsyncCacheSeed, SchedulerStats } from './async' import type { Environment } from './eval' import type { NodeId, Precedents } from './deps' import type { Atom, ReadonlyAtom } from '@tanstack/store' import type { FunctionDiagnostic } from './validate' import type { Cell, CellKey, CellValue, CommitResult, Node, Patch, RangeNode, Rect, Ref, SheetId, SheetInfo, SheetProvenance, } from './types' /** * A workbook-defined name. `scope` undefined means workbook-scoped; otherwise * the name is scoped to that sheet. `definition` is the formula text the name * binds to (a range, a constant, or a formula); `ast` is it parsed once. */ export interface DefinedName { name: string scope?: SheetId definition: string ast: Node } /** A listed defined name (the `ast` is internal and omitted). */ export interface DefinedNameInfo { name: string scope?: SheetId definition: string } /** * Map key for the name table: scope (or `''` for workbook) + upper-cased name. * Exported for the names capability, which keys the same shared `names` map. */ export function nameTableKey( scope: SheetId | undefined, upperName: string, ): string { return (scope ?? '') + '\u0000' + upperName } export interface WorkbookOptions { functions?: FunctionRegistry /** Custom function packs registered into the (possibly fresh) registry. */ packs?: Array /** Host-provided ports surfaced to every function via `FnContext.ports`. */ functionPorts?: FunctionPorts /** Host port that executes async requests (§3). Without it, async cells stay pending. */ asyncPort?: AsyncPort /** Opt-in cap: max async requests dispatched before pausing. Defaults to unlimited. */ asyncBudget?: number /** Seed the async result cache on load (persistence) so cells resolve without refiring. */ asyncCache?: Array /** Cooldown (ms) before a negative (error) async cache entry expires; default 30 000. */ asyncNegativeTtl?: number clock?: Clock rng?: Rng locale?: Locale visibility?: VisibilityPort } /** Result of {@link WorkbookKernelBase.validateFormula}. */ export interface FormulaValidation { ok: boolean diagnostics: Array /** Set when the formula could not be parsed (diagnostics will be empty). */ parseError?: string } interface Region { sheet: SheetId rect: Rect cb: () => void } /** * Options accepted by the kernel constructor. Extends {@link WorkbookOptions} * with the opt-in capability set. When omitted, no capabilities are registered; * the factory layer supplies the default (all) capabilities, and the lean * `constructWorkbook` entry forwards a caller-chosen set so unused capabilities * tree-shake away. */ export interface WorkbookKernelOptions extends WorkbookOptions { /** The capabilities to register (assign their methods onto the instance). */ capabilities?: WorkbookCapabilities } /** * The always-present workbook runtime. `class Workbook` (in `./workbook`) * extends this to add the `builtins()` default; capabilities assign their * opt-in methods onto instances during construction. Kept as a base class so * the lean `constructWorkbook` entry can build an instance without the factory * layer's static `./functions` import. */ export class WorkbookKernelBase { /** * Internal writable atoms. Only the workbook mutates these; the public * {@link atoms} facade below exposes the same instances as {@link ReadonlyAtom} * so consumers can read and subscribe but never `.set()` — matching the * baseAtoms→atoms split in table-core. */ private readonly baseAtoms: { revision: Atom sheets: Atom> } readonly atoms: { revision: ReadonlyAtom sheets: ReadonlyAtom> } readonly functions: FunctionRegistry private readonly clock: Clock private readonly rng: Rng private readonly sheetMap = new Map() /** Read-only external sheets (§6.2). Referenced by formulas, never written. */ private readonly virtualSheets = new Map() /** Re-entrancy depth — a synchronous re-entry is a cross-boundary cycle (§6.2). */ private committing = 0 private readonly regions = new Set() /** * Display number-format codes, kept independent of the cell value lifecycle. * @internal Read/written by the formats capability via {@link WorkbookInternal}. */ readonly formats = new Map>() private readonly deps = new DepGraph() /** Defined names, keyed by {@link nameTableKey}. */ private readonly names = new Map() /** Merge rectangles per sheet — workbook-owned state, read by every view. */ private readonly merges = new Map>() /** Provenance recorded per source sheet (Tier-1 staging), outside the grid. */ private readonly provenance = new Map() /** The last staged extent per source sheet (for tail-blanking on re-stage). */ private readonly stagedExtents = new Map() private volatileNames: Set /** Whether an async execution route (port) is wired — gates async registration. */ private readonly hasAsyncPort: boolean private readonly env: Environment private readonly scheduler: Scheduler constructor(opts: WorkbookKernelOptions = {}) { // The kernel never defaults to `builtins()` — that lives in the factory // layer (`./workbook`). A kernel built without `functions` gets an empty // registry, keeping the lean path's module graph free of `./functions`. this.functions = opts.functions ?? new FunctionRegistry() this.clock = opts.clock ?? systemClock this.rng = opts.rng ?? mathRng this.hasAsyncPort = opts.asyncPort !== undefined for (const p of opts.packs ?? []) { for (const fn of p.functions) this.assertAsyncRoutable(fn) this.functions.registerPack(p) } this.volatileNames = this.functions.volatileNames() this.baseAtoms = { revision: createAtom(0), sheets: createAtom>([]), } // Public facade: same instances, read-only type. Writes go via baseAtoms. this.atoms = this.baseAtoms this.scheduler = new Scheduler({ port: opts.asyncPort, budget: opts.asyncBudget, seed: opts.asyncCache, negativeTtl: opts.asyncNegativeTtl, now: () => this.clock.now(), // `onAsyncResolved` is assigned by the async capability during // construction (below); the scheduler only invokes this after // construction completes, so it is always defined when the async // capability is registered. Optional-call keeps a capability-less // workbook safe if async results ever resolve without it. onResolved: (nodes) => this.onAsyncResolved?.(nodes), }) this.env = { getCellValue: (sheet, row, col) => { const provider = this.virtualSheets.get(sheet) if (provider) return provider.getCell(row, col) return this.sheetMap.get(sheet)?.get(pack(row, col))?.value ?? null }, getSheet: (sheet) => this.sheetMap.get(sheet), functions: this.functions, clock: this.clock, rng: this.rng, visibility: opts.visibility, ports: opts.functionPorts, resolveName: (name, ownerSheet, scope) => this.lookupName(name, ownerSheet, scope)?.ast, sheetOrder: () => this.atoms.sheets.get(), async: { lookup: (key) => this.scheduler.lookup(key), collect: (req, cell) => this.scheduler.record( req, cell ? nodeId(cell.sheet, pack(cell.row, cell.col)) : undefined, ), }, } // Register the opt-in capabilities: each assigns its methods onto this // instance, reading private kernel state through the internal accessor. const internal = this as unknown as WorkbookInternal const capabilities: Array = Object.values( opts.capabilities ?? {}, ) for (const capability of capabilities) { capability?.construct?.(internal) } } /** * The workbook's sheet order. * @internal Internal accessor surface for capabilities ({@link WorkbookInternal}). */ sheetOrder(): ReadonlyArray { return this.atoms.sheets.get() } // ------------------------------------------------------------------------- // Capability methods (declared for typing; assigned at runtime by the // registered capabilities via their `construct` hook). Declaring them on the // base means the default-capability `Workbook` instance type carries every // method, so `new Workbook()` / `createWorkbook()` stay fully typed with no // call-site changes. // ------------------------------------------------------------------------- /** @see Workbook_Formats.setFormat (formatsCapability) */ declare setFormat: (ref: Ref, code: string | undefined) => void /** @see Workbook_Formats.getFormat (formatsCapability) */ declare getFormat: (ref: Ref) => string | undefined /** @see Workbook_Provenance.setSheetProvenance (provenanceCapability) */ declare setSheetProvenance: ( sheet: SheetId, prov: SheetProvenance | undefined, ) => void /** @see Workbook_Provenance.sheetProvenance (provenanceCapability) */ declare sheetProvenance: (sheet: SheetId) => SheetProvenance | undefined /** @see Workbook_Provenance.getStagedExtent (provenanceCapability) */ declare getStagedExtent: (sheet: SheetId) => Rect | undefined /** @see Workbook_Provenance.setStagedExtent (provenanceCapability) */ declare setStagedExtent: (sheet: SheetId, rect: Rect | undefined) => void /** @see Workbook_Merges.mergeCells (mergesCapability) */ declare mergeCells: (sheet: SheetId, rect: Rect) => CommitResult /** @see Workbook_Merges.unmergeCells (mergesCapability) */ declare unmergeCells: (sheet: SheetId, rect: Rect) => CommitResult /** @see Workbook_Merges.getMerges (mergesCapability) */ declare getMerges: (sheet: SheetId) => Array /** @see Workbook_Merges.getMergeAt (mergesCapability) */ declare getMergeAt: ( sheet: SheetId, row: number, col: number, ) => Rect | undefined /** @see Workbook_Clipboard.rangeToTSV (clipboardCapability) */ declare rangeToTSV: (sheet: SheetId, rect: Rect) => string /** @see Workbook_Clipboard.copyRange (clipboardCapability) */ declare copyRange: (sheet: SheetId, rect: Rect) => Clipboard /** @see Workbook_Clipboard.buildPastePatches (clipboardCapability) */ declare buildPastePatches: ( target: Ref, clip: Clipboard | string, into?: Rect, ) => Array /** @see Workbook_Fill.buildFillPatches (fillCapability) */ declare buildFillPatches: ( sheet: SheetId, source: Rect, target: Rect, ) => Array /** @see Workbook_Names.defineName (namesCapability) */ declare defineName: ( name: string, definition: string, opts?: { scope?: SheetId }, ) => void /** @see Workbook_Names.removeName (namesCapability) */ declare removeName: (name: string, opts?: { scope?: SheetId }) => boolean /** @see Workbook_Names.getName (namesCapability) */ declare getName: ( name: string, opts?: { sheet?: SheetId; scope?: SheetId }, ) => DefinedNameInfo | undefined /** @see Workbook_Names.listNames (namesCapability) */ declare listNames: () => Array /** @see Workbook_Async.settle (asyncCapability) */ declare settle: () => Promise /** @see Workbook_Async.asyncStats (asyncCapability) */ declare asyncStats: () => SchedulerStats /** @see Workbook_Async.exportAsyncCache (asyncCapability) */ declare exportAsyncCache: () => Array /** @see Workbook_Async.resumeAsync (asyncCapability) */ declare resumeAsync: (additional?: number) => void /** @see Workbook_Async.refreshAsync (asyncCapability) */ declare refreshAsync: (opts?: { key?: string functionName?: string }) => CommitResult /** * Assigned by the async capability; invoked by the scheduler's `onResolved`. * @see Workbook_Async.onAsyncResolved (asyncCapability) * @internal */ declare onAsyncResolved?: (nodes: Array) => void // ------------------------------------------------------------------------- // Function registry (M8) // ------------------------------------------------------------------------- /** * Register a custom function pack into this workbook's registry. Collisions * with builtins (or already-registered packs) throw a `FunctionCollisionError` * and leave the registry unchanged. Recomputes the volatile set so a volatile * custom function recalculates every commit. */ registerPack(pack: FunctionPack): this { for (const fn of pack.functions) this.assertAsyncRoutable(fn) this.functions.registerPack(pack) this.volatileNames = this.functions.volatileNames() return this } /** * Register or replace a single custom function. This is the **host-trusted** * direct path (origin `host` by default) — it bypasses the Code Mode example * gate, so hosts call it for functions they already trust; the gated path is * `approveAndRegister` in `@tanstack/spreadsheet-codemode`. Code Mode * registration passes `{ origin: 'code-mode', source }` so the function's * source rides on the one registry (and `removeFunction` drops it from the * export). Replacing an existing definition re-evaluates every call site, so a * version bump invalidates correctly; a function with zero live call sites * skips the recalc fan-out. */ upsertFunction( def: FunctionDef, opts: { origin?: FunctionOrigin; source?: unknown } = {}, ): CommitResult { this.assertAsyncRoutable(def) this.functions.register(def, { replace: true, origin: opts.origin ?? 'host', source: opts.source, }) this.volatileNames = this.functions.volatileNames() const sites = this.callSitesOf(def.name) return sites.length ? this.commit(sites, []) : { applied: [], recalculated: [], cycles: [] } } /** Remove a custom function everywhere (registry + export); call sites re-evaluate. */ removeFunction(name: string): CommitResult { const sites = this.callSitesOf(name) this.functions.unregister(name) this.volatileNames = this.functions.volatileNames() return sites.length ? this.commit(sites, []) : { applied: [], recalculated: [], cycles: [] } } /** * Registering an async function with no execution route (the workbook has no * `asyncPort`) throws here, at registration — never a silent degrade to a * never-resolving `pending`. Sync functions always route. */ private assertAsyncRoutable(def: FunctionDef): void { if (def.kind === 'async' && !this.hasAsyncPort) { throw new Error( `async function '${def.name}' has no execution route: construct the ` + `workbook with an asyncPort before registering async functions`, ) } } /** The serializable source records of every function with the given origin. */ functionSources(origin: FunctionOrigin): Array { return this.functions.sources(origin) } /** Nodes of every formula whose AST calls `name` (case-insensitive). */ private callSitesOf(name: string): Array { const target = name.toUpperCase() const out: Array = [] const calls = (node: Node): boolean => { switch (node.type) { case 'call': return node.name.toUpperCase() === target || node.args.some(calls) case 'unary': return calls(node.operand) case 'binary': return calls(node.left) || calls(node.right) default: return false } } for (const [sheetId, sheet] of this.sheetMap) { for (const key of sheet.keys()) { const cell = sheet.get(key) if (cell?.ast && calls(cell.ast)) out.push(nodeId(sheetId, key)) } } return out } /** * The machine-readable function catalog (§2.2) — every registered function * with its origin tag, enriched with the **live call-site count** so unused * functions can be surfaced for cleanup. Counts are computed from the current * cell ASTs on each call. */ functionCatalog(): Array { const counts = this.callSiteCounts() return this.functions.catalog().map((e) => ({ ...e, callSites: counts.get(e.name.toUpperCase()) ?? 0, })) } /** How many formulas reference each function name right now (by upper name). */ private callSiteCounts(): Map { const counts = new Map() const bump = (node: Node): void => { switch (node.type) { case 'call': counts.set( node.name.toUpperCase(), (counts.get(node.name.toUpperCase()) ?? 0) + 1, ) node.args.forEach(bump) break case 'unary': bump(node.operand) break case 'binary': bump(node.left) bump(node.right) break default: break } } for (const sheet of this.sheetMap.values()) { for (const key of sheet.keys()) { const cell = sheet.get(key) if (cell?.ast) bump(cell.ast) } } return counts } /** The portability manifest: every registered pack's `{ name, version }`. */ functionManifest(): Array { return this.functions.manifest() } /** * Function names referenced by a formula somewhere in the workbook that are * **not** registered — e.g. a pack that has not been loaded. Such calls * evaluate to `#NAME?`; this surfaces the degrade in the manifest view rather * than leaving it silent (an XLSX import seeds the last cached value for the * cell where one exists, so the number survives even when the pack is absent). */ missingFunctions(): Array { const missing = new Set() for (const [name, count] of this.callSiteCounts()) { if (count > 0 && !this.functions.has(name)) missing.add(name) } return [...missing] } /** * Validate a formula against the registry without committing it: reports * parse errors, unknown functions, and bad argument counts. Powers formula-bar * linting and agent checks. A leading `=` is optional. */ validateFormula( input: string, opts: { sheet?: SheetId } = {}, ): FormulaValidation { const sheet = opts.sheet ?? this.atoms.sheets.get()[0] let ast: Node try { ast = parse(input, { defaultSheet: sheet }) } catch (e) { if (e instanceof ParseError) { return { ok: false, diagnostics: [], parseError: e.message } } throw e } const diagnostics = validateCalls(ast, this.functions) return { ok: diagnostics.length === 0, diagnostics } } // ------------------------------------------------------------------------- // Defined names (resolution stays in the kernel — dependency analysis // resolves names; the public define/remove/get/list surface is contributed // by namesCapability) // ------------------------------------------------------------------------- /** * Resolve a name to its record. An explicit scope (`Budget!Total`) tries that * sheet then the workbook; otherwise the owning sheet is tried first, then the * workbook. */ private lookupName( name: string, ownerSheet: SheetId | undefined, explicitScope?: SheetId, ): DefinedName | undefined { const upper = name.toUpperCase() if (explicitScope !== undefined) { return ( this.names.get(nameTableKey(explicitScope, upper)) ?? this.names.get(nameTableKey(undefined, upper)) ) } if (ownerSheet !== undefined) { const scoped = this.names.get(nameTableKey(ownerSheet, upper)) if (scoped) return scoped } return this.names.get(nameTableKey(undefined, upper)) } // ------------------------------------------------------------------------- // Sheets // ------------------------------------------------------------------------- addSheet(id: SheetId): Sheet { if (this.sheetMap.has(id) || this.virtualSheets.has(id)) { throw new Error(`sheet already exists: ${id}`) } const sheet = new Sheet(id) this.sheetMap.set(id, sheet) this.baseAtoms.sheets.set((prev) => [...prev, id]) return sheet } removeSheet(id: SheetId): boolean { if (!this.sheetMap.delete(id)) return false this.baseAtoms.sheets.set((prev) => prev.filter((s) => s !== id)) this.merges.delete(id) this.provenance.delete(id) this.stagedExtents.delete(id) return true } getSheet(id: SheetId): ReadonlySheet | undefined { return this.sheetMap.get(id) } /** * Every sheet — real and virtual — in workbook order, flagged by kind. Virtual * sheets list alongside real ones (they are read-only); this is the surface a * UI or agent enumerates. */ listSheets(): Array { return this.atoms.sheets .get() .map((id) => this.virtualSheets.has(id) ? { id, kind: 'virtual', readOnly: true } : { id, kind: 'real', readOnly: false }, ) } private requireSheet(id: SheetId): Sheet { const sheet = this.sheetMap.get(id) if (!sheet) { if (this.virtualSheets.has(id)) { throw new Error( `sheet '${id}' is a read-only virtual sheet and cannot be written`, ) } throw new Error(`unknown sheet: ${id}`) } return sheet } // ------------------------------------------------------------------------- // Reading // ------------------------------------------------------------------------- /** * The cell at `ref`. On a virtual sheet this reads through the provider and * returns a synthesized read-only cell view (the value formulas already see), * so a virtual sheet is a first-class citizen of `getCell`, not evaluator-only. */ getCell(ref: Ref): Cell | undefined { const provider = this.virtualSheets.get(ref.sheet) if (provider) { const value = provider.getCell(ref.row, ref.col) if (value === null) return undefined const view: Cell = { input: '', kind: 'literal', value } return Object.freeze(view) } const cell = this.sheetMap.get(ref.sheet)?.get(pack(ref.row, ref.col)) // Return a frozen shallow copy: recalc mutates the stored cell's `value` // in place, so the live record must never escape — a consumer writing to // it would corrupt the engine. return cell === undefined ? undefined : Object.freeze({ ...cell }) } /** * Evaluate a formula ad-hoc against the workbook's current (settled) values, * without writing a cell or creating any dependency edges. A leading `=` is * optional. Unqualified references resolve against `opts.sheet` (defaulting to * the first sheet); cross-sheet references (`Sheet2!A1`) work regardless. * * This is the entry point for using the workbook as a headless data manager — * server-side reports, validation, agent queries — outside any cell context. * * @example * workbook.runFormula('SUM(E1:E6)') * workbook.runFormula('VLOOKUP("Gadgets", A1:F4, 5, FALSE)', { sheet: 's1' }) */ runFormula(input: string, opts: { sheet?: SheetId } = {}): CellValue { const sheet = opts.sheet ?? this.atoms.sheets.get()[0] if (sheet === undefined) { throw new Error('runFormula: workbook has no sheets') } const ast = parse(input, { defaultSheet: sheet }) // Ad-hoc evaluation has no owning cell, so it must not register async // requests (nothing to invalidate on resolution). Async calls return pending. return evaluate(ast, { ...this.env, async: undefined }) } /** * The evaluator environment (read-only value access, function registry, ports) * for advanced use — e.g. evaluating a pre-parsed AST via `evaluate(ast, env)`. */ get environment(): Environment { return this.env } // ------------------------------------------------------------------------- // Convenience surface (sugar over setInput + applyPatches) // ------------------------------------------------------------------------- /** * Resolve a `Ref | string` to a {@link Ref}. A string is A1 (`'B2'`) with an * optional sheet qualifier (`'Sheet1!B2'`, `"'My Sheet'!B2"`); a bare A1 * resolves against the first sheet. `Ref` objects pass through. A1 strings are * the ergonomic form at this convenience layer; `Ref` stays canonical beneath. */ private toRef(ref: Ref | string): Ref { if (typeof ref !== 'string') return ref let sheet: SheetId | undefined let a1 = ref const bang = ref.lastIndexOf('!') if (bang >= 0) { sheet = ref .slice(0, bang) .replace(/^'(.*)'$/, '$1') .replace(/''/g, "'") a1 = ref.slice(bang + 1) } const parsed = parseA1(a1) if (!parsed) throw new Error(`invalid A1 reference: '${ref}'`) const s = sheet ?? this.atoms.sheets.get()[0] if (s === undefined) { throw new Error(`no sheet to resolve reference '${ref}' against`) } return { sheet: s, row: parsed.row, col: parsed.col } } /** * One-call write: compose `setInput` + `applyPatches` for a single cell. * Accepts an A1 string or a {@link Ref}. Patches remain the power surface for * batching and undo — this is the ergonomic path for a single edit. */ set(ref: Ref | string, input: string): CommitResult { return this.applyPatches(this.setInput(this.toRef(ref), input)) } /** One-call batch write: apply several cell edits in a single commit. */ setMany(edits: Array<{ ref: Ref | string; input: string }>): CommitResult { return this.applyPatches( edits.flatMap((e) => this.setInput(this.toRef(e.ref), e.input)), ) } // ------------------------------------------------------------------------- // Dependency graph queries (public view of the real graph) // ------------------------------------------------------------------------- /** The cells and ranges a formula reads directly (its precedents). */ precedentsOf(ref: Ref): { cells: Array ranges: Array<{ sheet: SheetId; rect: Rect }> } { const node = nodeId(ref.sheet, pack(ref.row, ref.col)) const cells: Array = [] for (const p of this.deps.scalarPrecedentsOf(node)) { cells.push(this.nodeToRef(p)) } const ranges = this.deps .rangesOf(node) .map((d) => ({ sheet: d.sheet, rect: d.rect })) return { cells, ranges } } /** The formulas that read `ref` directly (its dependents), via scalar or range edges. */ dependentsOf(ref: Ref): Array { const node = nodeId(ref.sheet, pack(ref.row, ref.col)) const out = new Set() for (const d of this.deps.dependentsOf(node)) out.add(d) for (const f of this.deps.rangeFormulasCovering( ref.sheet, ref.row, ref.col, )) { out.add(f) } return [...out].map((n) => this.nodeToRef(n)) } private nodeToRef(node: NodeId): Ref { const { sheet, key } = decodeNode(node) return { sheet, row: rowOf(key), col: colOf(key) } } // ------------------------------------------------------------------------- // Mutation (returns patches) and commit // ------------------------------------------------------------------------- setInput(ref: Ref, input: string): Array { const sheet = this.requireSheet(ref.sheet) const key = pack(ref.row, ref.col) const before = sheet.get(key)?.input const after = input === '' ? undefined : input if (before === after) return [] return [{ sheet: ref.sheet, key, before, after }] } applyPatches(patches: Array): CommitResult { const applied: Array = [] const changed: Array = [] // Phase 1: apply inputs and update the dependency graph. for (const patch of patches) { const sheet = this.requireSheet(patch.sheet) const current = sheet.get(patch.key)?.input if (current === patch.after) continue if (patch.after === undefined) { sheet.delete(patch.key) } else { sheet.set(patch.key, makeCell(patch.after)) } const node = nodeId(patch.sheet, patch.key) this.updateDeps(patch.sheet, patch.key) applied.push(patch) changed.push(node) } if (applied.length === 0) { return { applied, recalculated: [], cycles: [] } } return this.commit(changed, applied) } /** * Run recalc for `changed`, notify affected regions, and dispatch any async * requests the pass produced. Shared by `applyPatches` (input edits) and async * resolution (re-invalidated nodes), so both paths notify + flush identically. */ private commit(changed: Array, applied: Array): CommitResult { // A synchronous re-entry means a store-backed virtual sheet update wrote back // into the graph *during* a recalc (§6.2 cross-boundary cycle). Reject it — // an undetected cross-boundary cycle invalidates every §1 guarantee. if (this.committing > 0) { throw new Error( 'cross-boundary cycle detected: a virtual-sheet/store update re-entered recalc', ) } this.committing++ try { return this.commitInner(changed, applied) } finally { this.committing-- } } private commitInner( changed: Array, applied: Array, ): CommitResult { const { evaluated, cycles } = this.recalc(changed) // Every changed key (input edits + recomputed values), grouped by sheet. const changedBySheet = new Map>() const add = (sheet: SheetId, key: CellKey) => { let set = changedBySheet.get(sheet) if (!set) changedBySheet.set(sheet, (set = new Set())) set.add(key) } for (const p of applied) add(p.sheet, p.key) for (const node of evaluated) { const { sheet, key } = decodeNode(node) add(sheet, key) } const recalculated: Array = [] for (const [sheet, keys] of changedBySheet) { for (const key of keys) { recalculated.push({ sheet, row: rowOf(key), col: colOf(key) }) } } this.baseAtoms.revision.set((r) => r + 1) this.notifyRegions(changedBySheet) // Fire async requests collected during this pass (dedupe/batch in the scheduler). this.scheduler.flush() return { applied, recalculated, cycles } } // ------------------------------------------------------------------------- // Virtual sheets (M12, §6.2) // ------------------------------------------------------------------------- /** * Register a read-only external sheet. Formulas reference it by name * (`ExtSheet!A1`); the workbook reads through the provider and treats its cells * as precedents. The provider's backing state (e.g. a Store) signals changes * via {@link recalcVirtual}. The id must not collide with a real sheet. */ addVirtualSheet(id: SheetId, provider: SheetProvider): void { if (this.sheetMap.has(id) || this.virtualSheets.has(id)) { throw new Error(`sheet already exists: ${id}`) } this.virtualSheets.set(id, provider) // List alongside real sheets (flagged virtual via `listSheets`). this.baseAtoms.sheets.set((prev) => [...prev, id]) } removeVirtualSheet(id: SheetId): boolean { if (!this.virtualSheets.delete(id)) return false this.baseAtoms.sheets.set((prev) => prev.filter((s) => s !== id)) return true } hasVirtualSheet(id: SheetId): boolean { return this.virtualSheets.has(id) } /** * Signal that cells in a virtual sheet changed: invalidate their dependents and * recalc (the normal synchronous pass). Pass specific cells, or omit `cells` to * invalidate every formula that reads this virtual sheet. Throws if called * re-entrantly from within a recalc (cross-boundary cycle). */ recalcVirtual( sheet: SheetId, cells?: Array<{ row: number; col: number }>, ): CommitResult { if (!this.virtualSheets.has(sheet)) throw new Error(`unknown virtual sheet: ${sheet}`) const nodes = cells ? cells.map((c) => nodeId(sheet, pack(c.row, c.col))) : this.deps.precedentNodesOnSheet(sheet) if (nodes.length === 0) return { applied: [], recalculated: [], cycles: [] } return this.commit(nodes, []) } // ------------------------------------------------------------------------- // Dependency graph maintenance // ------------------------------------------------------------------------- /** Reparse a changed cell's formula and update its edges (or clear them). */ private updateDeps(sheet: SheetId, key: CellKey): void { const node = nodeId(sheet, key) const cell = this.sheetMap.get(sheet)!.get(key) if (!cell || cell.kind !== 'formula') { this.deps.clearNode(node) return } try { const ast = parse(cell.input, { defaultSheet: sheet }) cell.ast = ast cell.parseError = undefined this.deps.setPrecedents(node, this.analyze(ast, sheet)) } catch (e) { // Unparseable formula: no dependencies; the cell surfaces an `#ERR!` value // carrying the parse message during evaluation. cell.ast = undefined cell.parseError = e instanceof ParseError ? e.message : String(e) this.deps.clearNode(node) } } /** * Derive a formula's precedents (scalar refs, ranges, volatility) from its * AST. References flow through defined names (so a formula recalcs when its * named target changes) and 3D ranges expand to one range precedent per sheet * in the span, in workbook order. */ private analyze(ast: Node, ownerSheet: SheetId): Precedents { const scalar = new Set() const ranges: Array<{ sheet: SheetId; rect: Rect }> = [] this.collectRefs(ast, ownerSheet, scalar, ranges, new Set()) return { scalar, ranges, volatile: this.usesVolatile(ast) } } private collectRefs( ast: Node, ownerSheet: SheetId | undefined, scalar: Set, ranges: Array<{ sheet: SheetId; rect: Rect }>, seenNames: Set, ): void { for (const ref of refsOf(ast)) { if (ref.kind === 'cell') { const s = ref.ref.sheet if (s !== undefined) { scalar.add(nodeId(s, pack(ref.ref.row, ref.ref.col))) } } else if (ref.kind === 'range') { this.addRangePrecedents(ref.range, ranges) } else { // name: resolve and flow precedents through its definition const rec = this.lookupName(ref.name.name, ownerSheet, ref.name.sheet) if (!rec) continue const k = nameTableKey(rec.scope, rec.name.toUpperCase()) if (seenNames.has(k)) continue seenNames.add(k) this.collectRefs( rec.ast, rec.scope ?? ownerSheet, scalar, ranges, seenNames, ) } } } /** Add range precedents for a (possibly 3D) range node. */ private addRangePrecedents( range: RangeNode, out: Array<{ sheet: SheetId; rect: Rect }>, ): void { const s0 = range.start.sheet const s1 = range.end.sheet if (s0 === undefined || s1 === undefined) return const rect = makeRect( range.start.row, range.start.col, range.end.row, range.end.col, ) if (s0 === s1) { out.push({ sheet: s0, rect }) return } const order = this.atoms.sheets.get() const i0 = order.indexOf(s0) const i1 = order.indexOf(s1) if (i0 < 0 || i1 < 0) return for (const sheet of order.slice(Math.min(i0, i1), Math.max(i0, i1) + 1)) { out.push({ sheet, rect }) } } private usesVolatile(node: Node): boolean { switch (node.type) { case 'call': if (this.volatileNames.has(node.name)) return true return node.args.some((a) => this.usesVolatile(a)) case 'name': { const rec = this.lookupName(node.name, undefined, node.sheet) return rec ? this.usesVolatile(rec.ast) : false } case 'unary': return this.usesVolatile(node.operand) case 'binary': return this.usesVolatile(node.left) || this.usesVolatile(node.right) default: return false } } // ------------------------------------------------------------------------- // Recalculation // ------------------------------------------------------------------------- private recalc(changed: Array): { evaluated: Array cycles: Array> } { // --- gather the transitive dirty set (formula nodes needing evaluation) --- const dirty = new Set() const queue: Array = [] const enqueue = (n: NodeId) => { if (!dirty.has(n)) { dirty.add(n) queue.push(n) } } const propagate = (node: NodeId) => { const { sheet, key } = decodeNode(node) const row = rowOf(key) const col = colOf(key) for (const dep of this.deps.dependentsOf(node)) enqueue(dep) for (const f of this.deps.rangeFormulasCovering(sheet, row, col)) enqueue(f) } for (const node of changed) { const { sheet, key } = decodeNode(node) const cell = this.sheetMap.get(sheet)?.get(key) if (cell?.kind === 'formula') enqueue(node) // an edited formula re-evaluates propagate(node) // its dependents recalc regardless } for (const v of this.deps.volatile) enqueue(v) while (queue.length > 0) { propagate(queue.shift()!) } // --- topo-sort the dirty subgraph, detecting cycles in the same pass --- const order: Array = [] const color = new Map() // 1=gray (on stack), 2=black (done) const cyclic = new Set() const cycles: Array> = [] const stack: Array = [] const precedentsInDirty = (node: NodeId): Array => { const out: Array = [] for (const p of this.deps.scalarPrecedentsOf(node)) { if (dirty.has(p)) out.push(p) } const ranges = this.deps.rangesOf(node) if (ranges.length > 0) { for (const d of dirty) { const { sheet, key } = decodeNode(d) const row = rowOf(key) const col = colOf(key) for (const rg of ranges) { if (rg.sheet === sheet && rectContains(rg.rect, row, col)) { out.push(d) break } } } } return out } const visit = (node: NodeId) => { color.set(node, 1) stack.push(node) for (const p of precedentsInDirty(node)) { const c = color.get(p) if (c === 1) { // back edge -> cycle: the stack slice from p to node is circular const idx = stack.indexOf(p) const group = stack.slice(idx) for (const g of group) cyclic.add(g) cycles.push( group.map((g) => { const { sheet, key } = decodeNode(g) return { sheet, row: rowOf(key), col: colOf(key) } }), ) } else if (c === undefined) { visit(p) } } color.set(node, 2) stack.pop() order.push(node) } for (const node of dirty) { if (!color.has(node)) visit(node) } // --- evaluate in dependency order --- const evaluated: Array = [] for (const node of order) { const { sheet, key } = decodeNode(node) const cell = this.sheetMap.get(sheet)?.get(key) if (!cell) continue if (cyclic.has(node)) { cell.value = err('#CIRCULAR') } else if (cell.kind === 'formula') { cell.value = cell.ast ? evaluate(cell.ast, this.env, { sheet, row: rowOf(key), col: colOf(key), }) : err('#ERR!', cell.parseError) } evaluated.push(node) } return { evaluated, cycles } } // ------------------------------------------------------------------------- // Region subscriptions (pull model) // ------------------------------------------------------------------------- subscribeRegion(sheet: SheetId, rect: Rect, cb: () => void): () => void { const region: Region = { sheet, rect, cb } this.regions.add(region) return () => { this.regions.delete(region) } } private notifyRegions(changedBySheet: Map>): void { for (const region of this.regions) { const keys = changedBySheet.get(region.sheet) if (!keys) continue for (const key of keys) { if (rectContains(region.rect, rowOf(key), colOf(key))) { region.cb() break // fire once per region per commit } } } } }